diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..868a782 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +_test_*.* +__pycache__ +.venv +.idea +*.pth +*.ini diff --git a/README.md b/README.md index 97db0b0..116a443 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,1073 @@ -# ComfyUI_LayerStyle_Advance +# ComfyUI Layer Style Advance + +[中文说明点这里](./README_CN.MD) + + The nodes detached from [ComfyUI Layer Style](https://github.com/chflame163/ComfyUI_LayerStyle) are mainly those with complex requirements for dependency packages. + + + +## Example workflow + +Some JSON workflow files in the ```workflow``` directory, That's examples of how these nodes can be used in ComfyUI. + +## How to install + +(Taking ComfyUI official portable package and Aki ComfyUI package as examples, please modify the dependency environment directory for other ComfyUI environments) + +### Install plugin + +* Recommended use ComfyUI Manager for installation. + +* Or open the cmd window in the plugin directory of ComfyUI, like ```ComfyUI\custom_nodes```,type + + ``` + git clone https://github.com/chflame163/ComfyUI_LayerStyle.git + ``` + +* Or download the zip file and extracted, copy the resulting folder to ```ComfyUI\custom_ Nodes``` + +### Install dependency packages + +* for ComfyUI official portable package, double-click the ```install_requirements.bat``` in the plugin directory, for Aki ComfyUI package double-click on the ```install_requirements_aki.bat``` in the plugin directory, and wait for the installation to complete. + +* Or install dependency packages, open the cmd window in the ComfyUI_LayerStyle plugin directory like + ```ComfyUI\custom_ Nodes\ComfyUI_LayerStyle``` and enter the following command, + +  for ComfyUI official portable package, type: + +``` +..\..\..\python_embeded\python.exe -s -m pip install .\whl\docopt-0.6.2-py2.py3-none-any.whl +..\..\..\python_embeded\python.exe -s -m pip install .\whl\hydra_core-1.3.2-py3-none-any.whl +..\..\..\python_embeded\python.exe -s -m pip install -r requirements.txt +.\repair_dependency.bat +``` + +  for Aki ComfyUI package, type: + +``` +..\..\python\python.exe -s -m pip install .\whl\docopt-0.6.2-py2.py3-none-any.whl +..\..\python\python.exe -s -m pip install .\whl\hydra_core-1.3.2-py3-none-any.whl +..\..\python\python.exe -s -m pip install -r requirements.txt +.\repair_dependency.bat +``` + +* Restart ComfyUI. + +### Download Model Files + +Chinese domestic users from [BaiduNetdisk](https://pan.baidu.com/s/1T_uXMX3OKIWOJLPuLijrgA?pwd=1yye) and other users from [huggingface.co/chflame163/ComfyUI_LayerStyle](https://huggingface.co/chflame163/ComfyUI_LayerStyle/tree/main) +download all files and copy them to ```ComfyUI\models``` folder. This link provides all the model files required for this plugin. +Or download the model file according to the instructions of each node. + +## Common Issues + +If the node cannot load properly or there are errors during use, please check the error message in the ComfyUI terminal window. The following are common errors and their solutions. + +### Warning: xxxx.ini not found, use default xxxx.. + +This warning message indicates that the ini file cannot be found and does not affect usage. If you do not want to see these warnings, please modify all ```*.ini.example``` files in the plugin directory to ```*.ini```. + +### ModuleNotFoundError: No module named 'psd_tools' + +This error is that the ```psd_tools``` were not installed correctly. + +Solution: + +* Close ComfyUI and open the terminal window in the plugin directory and execute the following command: + ```../../../python_embeded/python.exe -s -m pip install psd_tools``` + If error occurs during the installation of psd_tool, such as ```ModuleNotFoundError: No module named 'docopt'``` , please download [docopt's whl](https://www.piwheels.org/project/docopt/) and manual install it. + execute the following command in terminal window: + ```../../../python_embeded/python.exe -s -m pip install path/docopt-0.6.2-py2.py3-none-any.whl``` the ```path``` is path name of whl file. + +### Cannot import name 'guidedFilter' from 'cv2.ximgproc' + +This error is caused by incorrect version of the ```opencv-contrib-python``` package,or this package is overwriteen by other opencv packages. + +### NameError: name 'guidedFilter' is not defined + +The reason for the problem is the same as above. + +### Cannot import name 'VitMatteImageProcessor' from 'transformers' + +This error is caused by the low version of ```transformers``` package. + +### insightface Loading very slow + +This error is caused by the low version of ```protobuf``` package. + +#### For the issues with the above three dependency packages, please double click ```repair_dependency.bat``` (for Official ComfyUI Protable) or ```repair_dependency_aki.bat``` (for ComfyUI-aki-v1.x) in the plugin folder to automatically fix them. + +### onnxruntime::python::CreateExecutionProviderInstance CUDA_PATH is set but CUDA wasn't able to be loaded. Please install the correct version of CUDA and cuDNN as mentioned in the GPU requirements page + +Solution: +Reinstall the ```onnxruntime``` dependency package. + +### Error loading model xxx: We couldn't connect to huggingface.co ... + +Check the network environment. If you cannot access huggingface.co normally in China, try modifying the huggingface_hub package to force the use hf_mirror. + +* Find ```constants.py``` in the directory of ```huggingface_hub``` package (usually ```Lib/site packages/huggingface_hub``` in the virtual environment path), + Add a line after ```import os``` + + ``` + os.environ['HF_ENDPOINT'] = 'https://hf-mirror.com' + ``` + +### ValueError: Trimap did not contain foreground values (xxxx...) + +This error is caused by the mask area being too large or too small when using the ```PyMatting``` method to handle the mask edges. + +Solution: + +* Please adjust the parameters to change the effective area of the mask. Or use other methods to handle the edges. + +### Requests.exceptions.ProxyError: HTTPSConnectionPool(xxxx...) + +When this error has occurred, please check the network environment. + +### UnboundLocalError: local variable 'clip_processor' referenced before assignment +### UnboundLocalError: local variable 'text_model' referenced before assignment +If this error occurs when executing ```JoyCaption2``` node and it has been confirmed that the model file has been placed in the correct directory, +please check the ```transformers``` dependency package version is at least 4.43.2 or higher. +If ```transformers``` version is higher than or equal to 4.45.0, and also have error message: +``` +Error loading models: De️️scriptors cannot be created directly. +If this call came from a _pb2.py file, your generated code is out of date and must be regenerated with protoc >= 3.19.0. +...... +``` +Please try downgrading the ```protobuf``` dependency package to 3.20.3, or set environment variables: ```PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=python```. + + + +## Update + +**If the dependency package error after updating, please double clicking ```repair_dependency.bat``` (for Official ComfyUI Protable) or ```repair_dependency_aki.bat``` (for ComfyUI-aki-v1.x) in the plugin folder to reinstall the dependency packages. + +* Discard the dependencies required for the [ObjectDetector YOLOWorld](#ObjectDetectorYOLOWorld) node from the requirements. txt file. To use this node, please manually install the dependency package. +* Strip some nodes from [ComfyUI Layer Style](https://github.com/chflame163/ComfyUI_LayerStyle) to this repository. + + + +## Description + +### QWenImage2Prompt + +Inference the prompts based on the image. this node is repackage of the [ComfyUI_VLM_nodes](https://github.com/gokayfem/ComfyUI_VLM_nodes)'s ```UForm-Gen2 Qwen Node```, thanks to the original author. +Download model files from [huggingface](https://huggingface.co/unum-cloud/uform-gen2-qwen-500m) or [Baidu Netdisk](https://pan.baidu.com/s/1oRkUoOKWaxGod_XTJ8NiTA?pwd=d5d2) to ```ComfyUI/models/LLavacheckpoints/files_for_uform_gen2_qwen``` folder. + +![image](image/qwen_image2prompt_example.jpg) + +Node Options: + +* question: Prompt of UForm-Gen-QWen model. + + +### LlamaVision +Use the Llama 3.2 vision model for local inference. Can be used to generate prompt words. part of the code for this node comes from [ComfyUI-PixtralLlamaMolmoVision](https://github.com/SeanScripts/ComfyUI-PixtralLlamaMolmoVision), thank you to the original author. +To use this node, the ```transformers``` need upgraded to 4.45.0 or higher. +Download models from [BaiduNetdisk](https://pan.baidu.com/s/18oHnTrkNMiwKLMcUVrfFjA?pwd=4g81) or [huggingface/SeanScripts](https://huggingface.co/SeanScripts/Llama-3.2-11B-Vision-Instruct-nf4/tree/main) , and copy to ```ComfyUI/models/LLM```. +![image](image/llama_vision_example.jpg) + +Node Options: +![image](image/llama_vision_node.jpg) + +* image: Image input. +* model: Currently, only the "Llama-3.2-11B-Vision-Instruct-nf4" is available. +* system_prompt: System prompt words for LLM model. +* user_prompt: User prompt words for LLM model. +* max_new_tokens: max_new_tokens for LLM model. +* do_sample: do_sample for LLM model. +* top-p: top_p for LLM model. +* top_k: top_k for LLM model. +* stop_strings: The stop strings. +* seed: The seed of random number. +* control_after_generate: Seed change options. If this option is fixed, the generated random number will always be the same. +* include_prompt_in_output: Does the output contain prompt words. +* cache_model: Whether to cache the model. + +### JoyCaption2 +Use the JoyCaption-alpha-two model for local inference. Can be used to generate prompt words. this node is https://huggingface.co/John6666/joy-caption-alpha-two-cli-mod Implementation in ComfyUI, thank you to the original author. +Download models form [BaiduNetdisk](https://pan.baidu.com/s/1dOjbUEacUOhzFitAQ3uIeQ?pwd=4ypv) and [BaiduNetdisk](https://pan.baidu.com/s/1mH1SuW45Dy6Wga7aws5siQ?pwd=w6h5) , +or [huggingface/Orenguteng](https://huggingface.co/Orenguteng/Llama-3.1-8B-Lexi-Uncensored-V2/tree/main) and [huggingface/unsloth](https://huggingface.co/unsloth/Meta-Llama-3.1-8B-Instruct/tree/main) , then copy to ```ComfyUI/models/LLM```, +Download models from [BaiduNetdisk](https://pan.baidu.com/s/1pkVymOsDcXqL7IdQJ6lMVw?pwd=v8wp) or [huggingface/google](https://huggingface.co/google/siglip-so400m-patch14-384/tree/main) , and copy to ```ComfyUI/models/clip```, +Donwload the ```cgrkzexw-599808``` folder from [BaiduNetdisk](https://pan.baidu.com/s/12TDwZAeI68hWT6MgRrrK7Q?pwd=d7dh) or [huggingface/John6666](https://huggingface.co/John6666/joy-caption-alpha-two-cli-mod/tree/main) , and copy to ```ComfyUI/models/Joy_caption```。 +![image](image/joycaption2_example.jpg) + +Node Options: +![image](image/joycaption2_node.jpg) + +* image: Image input. +* extra_options: Input the extra_options. +* llm_model: There are two LLM models to choose, Orenguteng/Llama-3.1-8B-Lexi-Uncensored-V2 and unsloth/Meta-Llama-3.1-8B-Instruct. +* device: Model loading device. Currently, only CUDA is supported. +* dtype: Model precision, nf4 and bf16. +* vlm_lora: Whether to load text_madel. +* caption_type: Caption type options, including: "Descriptive", "Descriptive (Informal)", "Training Prompt", "MidJourney", "Booru tag list", "Booru-like tag list", "Art Critic", "Product Listing", "Social Media Post". +* caption_length: The length of caption. +* user_prompt: User prompt words for LLM model. If there is content here, it will overwrite all the settings for caption_type and extra_options. +* max_new_tokens: The max_new_token parameter of LLM. +* do_sample: The do_sample parameter of LLM. +* top-p: The top_p parameter of LLM. +* temperature: The temperature parameter of LLM. +* cache_model: Whether to cache the model. + +### JoyCaption2Split +The node of JoyCaption2 separate model loading and inference, and when multiple JoyCaption2 nodes are used, the model can be shared to improve efficiency. + +Node Options: +![image](image/joycaption2_split_node.jpg) + +* image: Image input.。 +* joy2_model: The JoyCaption model input. +* extra_options: Input the extra_options. +* caption_type: Caption type options, including: "Descriptive", "Descriptive (Informal)", "Training Prompt", "MidJourney", "Booru tag list", "Booru-like tag list", "Art Critic", "Product Listing", "Social Media Post". +* caption_length: The length of caption. +* user_prompt: User prompt words for LLM model. If there is content here, it will overwrite all the settings for caption_type and extra_options. +* max_new_tokens: The max_new_token parameter of LLM. +* do_sample: The do_sample parameter of LLM. +* top-p: The top_p parameter of LLM. +* temperature: The temperature parameter of LLM. + +### LoadJoyCaption2Model +JoyCaption2's model loading node, used in conjunction with JoyCaption2Split. + +Node Options: +![image](image/load_joycaption2_model_node.jpg) + +* llm_model: There are two LLM models to choose, Orenguteng/Llama-3.1-8B-Lexi-Uncensored-V2 and unsloth/Meta-Llama-3.1-8B-Instruct. +* device: Model loading device. Currently, only CUDA is supported. +* dtype: Model precision, nf4 and bf16. +* vlm_lora: Whether to load text_madel. + +### JoyCaption2ExtraOptions +The extra_options parameter node of JoyCaption2. + +Node Options: +![image](image/joycaption2_extra_options_node.jpg) + +* refer_character_name: If there is a person/character in the image you must refer to them as {name}. +* exclude_people_info: Do NOT include information about people/characters that cannot be changed (like ethnicity, gender, etc), but do still include changeable attributes (like hair style). +* include_lighting: Include information about lighting. +* include_camera_angle: Include information about camera angle. +* include_watermark: Include information about whether there is a watermark or not. +* include_JPEG_artifacts: Include information about whether there are JPEG artifacts or not. +* include_exif: If it is a photo you MUST include information about what camera was likely used and details such as aperture, shutter speed, ISO, etc. +* exclude_sexual: Do NOT include anything sexual; keep it PG. +* exclude_image_resolution: Do NOT mention the image's resolution. +* include_aesthetic_quality: You MUST include information about the subjective aesthetic quality of the image from low to very high. +* include_composition_style: Include information on the image's composition style, such as leading lines, rule of thirds, or symmetry. +* exclude_text: Do NOT mention any text that is in the image. +* specify_depth_field: Specify the depth of field and whether the background is in focus or blurred. +* specify_lighting_sources: If applicable, mention the likely use of artificial or natural lighting sources. +* do_not_use_ambiguous_language: Do NOT use any ambiguous language. +* include_nsfw: Include whether the image is sfw, suggestive, or nsfw. +* only_describe_most_important_elements: ONLY describe the most important elements of the image. +* character_name: Person/Character Name, if choice ```refer_character_name```. + +### PhiPrompt + +Use Microsoft Phi 3.5 text and visual models for local inference. Can be used to generate prompt words, process prompt words, or infer prompt words from images. Running this model requires at least 16GB of video memory. +Download model files from [BaiduNetdisk](https://pan.baidu.com/s/1BdTLdaeGC3trh1U3V-6XTA?pwd=29dh) or [huggingface.co/microsoft/Phi-3.5-vision-instruct](https://huggingface.co/microsoft/Phi-3.5-vision-instruct/tree/main) and [huggingface.co/microsoft/Phi-3.5-mini-instruct](https://huggingface.co/microsoft/Phi-3.5-mini-instruct/tree/main) and copy to ```ComfyUI\models\LLM``` folder. +![image](image/phi_prompt_example.jpg) + +Node Options: +![image](image/phi_prompt_node.jpg) + +* image: Optional input. The input image will serve as the input for Phi-3.5-vision-instruct. +* model: Selectable to load Phi-3.5-vision-instruct or Phi-3.5-mini-instruct model. The default value of auto will automatically load the corresponding model based on whether there is image input. +* device: Model loading device. Supports CPU and CUDA. +* dtype: The model loading accuracy has three options: fp16, bf16, and fp32. +* cache_model: Whether to cache the model. +* system_prompt: The system prompt of Phi-3.5-mini-instruct. +* user_prompt: User prompt words for LLM model. +* do_sample: The do_Sample parameter of LLM defaults to True. +* temperature: The temperature parameter of LLM defaults to 0.5. +* max_new_tokens: The max_new_token parameter of LLM defaults to 512. + +### UserPromptGeneratorTxtImg + +UserPrompt preset for generating SD text to image prompt words. + +Node options: +![image](image/userprompt_generator_txt2img_node.jpg) + +* template: Prompt word template. Currently, only the 'SD txt2img prompt' is available. +* describe: Prompt word description. Enter a simple description here. +* limit_word: Maximum length limit for output prompt words. For example, 200 means that the output text will be limited to 200 words. + +### UserPromptGeneratorTxtImgWithReference + +UserCompt preset for generating SD text to image prompt words based on input content. + +Node options: +![image](image/userprompt_generator_txt2img_with_reference_node.jpg) + +* reference_text: Reference text input. Usually it is a style description of the image. +* template: Prompt word template. Currently, only the 'SD txt2img prompt' is available. +* describe: Prompt word description. Enter a simple description here. +* limit_word: Maximum length limit for output prompt words. For example, 200 means that the output text will be limited to 200 words. + +### UserPromptGeneratorReplaceWord + +UserPrompt preset used to replace a keyword in text with different content. This is not only a simple replacement, but also a logical sorting of the text based on the context of the prompt words to achieve the rationality of the output content. + +Node options: +![image](image/userprompt_generator_replace_word_node.jpg) + +* orig_prompt: Original prompt word input. +* template: Prompt word template. Currently, only 'prompt replace word' is available. +* exclude_word: Keywords that need to be excluded. +* replace_with_word: That word will replace the exclude_word. + +### PromptTagger + +Inference the prompts based on the image. it can replace key word for the prompt. This node currently uses Google Gemini API as the backend service. Please ensure that the network environment can use Gemini normally. +Please apply for your API key on [Google AI Studio](https://makersuite.google.com/app/apikey), And fill it in ```api_key.ini```, this file is located in the root directory of the plug-in, and the default name is ```api_key.ini.example```. to use this file for the first time, you need to change the file suffix to ```.ini```. Open it using text editing software, fill in your API key after ```google_api_key=``` and save it. +![image](image/prompt_tagger_example.jpg) + +Node options: +![image](image/prompt_tagger_node.jpg) + +* api: The Api used. At present, there are two options "gemini-1. 5-flash" and "google-gemini". +* token_limit: The maximum token limit for generating prompt words. +* exclude_word: Keywords that need to be excluded. +* replace_with_word: That word will replace the exclude_word. + +### PromptEmbellish + +Enter simple prompt words, output polished prompt words, and support inputting images as references, and support Chinese input. This node currently uses Google Gemini API as the backend service. Please ensure that the network environment can use Gemini normally. +Please apply for your API key on [Google AI Studio](https://makersuite.google.com/app/apikey), And fill it in ```api_key.ini```, this file is located in the root directory of the plug-in, and the default name is ```api_key.ini.example```. to use this file for the first time, you need to change the file suffix to ```.ini```. Open it using text editing software, fill in your API key after ```google_api_key=``` and save it. +![image](image/prompt_embellish_example.jpg) + +Node options: +![image](image/prompt_embellish_node.jpg) + +* image: Optional, input image as a reference for prompt words. +* api: The Api used. At present, there are two options "gemini-1. 5-flash" and "google-gemini". +* token_limit: The maximum token limit for generating prompt words. +* discribe: Enter a simple description here. supports Chinese text input. + +### Florence2Image2Prompt + +Use the Florence 2 model to infer prompt words. The code for this node section is from[yiwangsimple/florence_dw](https://github.com/yiwangsimple/florence_dw), thanks to the original author. +*When using it for the first time, the model will be automatically downloaded. You can also download the model file from [BaiduNetdisk](https://pan.baidu.com/s/1hzw9-QiU1vB8pMbBgofZIA?pwd=mfl3) to ```ComfyUI/models/florence2``` folder. +![image](image/florence2_image2prompt_example.jpg) + +Node Options: +![image](image/florence2_image2prompt_node.jpg) + +* florence2_model: Florence2 model input. +* image: Image input. +* task: Select the task for florence2. +* text_input: Text input for florence2. +* max_new_tokens: The maximum number of tokens for generating text. +* num_beams: The number of beam searches that generate text. +* do_sample: Whether to use text generated sampling. +* fill_mask: Whether to use text marker mask filling. + + + +### GetColorTone + +Obtain the main color or average color from the image and output RGB values. +![image](image/get_color_tone_example.jpg) + +Node options: +![image](image/get_color_tone_node.jpg) + +* mode: There are two modes to choose from, with the main color and average color. + +Output type: + +* RGB color in HEX: The RGB color described by hexadecimal RGB format, like '#FA3D86'. +* HSV color in list: The HSV color described by python's list data format. + +### GetColorToneV2 + +V2 upgrade of GetColorTone. You can specify the dominant or average color to get the body or background. +![image](image/get_color_tone_v2_example.jpg) + +The following changes have been made on the basis of GetColorTong: +![image](image/get_color_tone_v2_node.jpg) + +* color_of: Provides 4 options, mask, entire, background, and subject, to select the color of the mask area, entire picture, background, or subject, respectively. +* remove_background_method: There are two methods of background recognition: BiRefNet and RMBG V1.4. +* invert_mask: Whether to reverse the mask. +* mask_grow: Mask expansion. For subject, a larger value brings the obtained color closer to the color at the center of the body. + +Output: + +* image: Solid color picture output, the size is the same as the input picture. +* mask: Mask output. + + +### ImageRewardFilter + +![image](image/image_reward_filter_example.jpg) +Rating bulk pictures and outputting top-ranked pictures. it used [ImageReward] (https://github.com/THUDM/ImageReward) for image scoring, thanks to the original authors. + +![image](image/image_reward_filter_node.jpg) +Node options: + +* prompt: Optional input. Entering prompt here will be used as a basis to determine how well it matches the picture. +* output_nun: Number of pictures outputted. This value should be less than the picture batch. + +Outputs: + +* images: Bulk pictures output from high to low in order of rating. +* obsolete_images: Knockout pictures. Also output in order of rating from high to low. + + +### LaMa + +![image](image/lama_example.jpg) +Erase objects from the image based on the mask. this node is repackage of [IOPaint](https://www.iopaint.com), powered by state-of-the-art AI models, thanks to the original author. +It is have [LaMa](https://github.com/advimman/lama), [LDM](https://github.com/CompVis/latent-diffusion), [ZITS](https://github.com/DQiaole/ZITS_inpainting),[MAT](https://github.com/fenglinglwb/MAT), [FcF](https://github.com/SHI-Labs/FcF-Inpainting), [Manga](https://github.com/msxie92/MangaInpainting) models and the SPREAD method to erase. Please refer to the original link for the introduction of each model. +Please download the model files from [lama models(BaiduNetdisk)](https://pan.baidu.com/s/1m7La2ELsSKaIFhQ57qg1XQ?pwd=jn10) or [lama models(Google Drive)](https://drive.google.com/drive/folders/1Aq0a4sybb3SRxi7j1e1_ZbBRjaWDdP9e?usp=sharing) to ```ComfyUI/models/lama``` folder. + +Node optons: +![image](image/lama_node.jpg) + +* lama_model: Choose a model or method. +* device: After correctly installing Torch and Nvidia CUDA drivers, using cuda will significantly improve running speed. +* invert_mask: Whether to reverse the mask. +* grow: Positive values expand outward, while negative values contract inward. +* blur: Blur the edge. + + + +### ImageAutoCrop + +![image](image/image_auto_crop_example.jpg) +Automatically cutout and crop the image according to the mask. it can specify the background color, aspect ratio, and size for output image. this node is designed to generate the image materials for training models. +*Please refer to the model installation methods for [SegmentAnythingUltra](#SegmentAnythingUltra) and [RemBgUltra](#RemBgUltra). + +Node options: +![image](image/image_auto_crop_node.jpg) + +* background_color4: The background color. +* aspect_ratio: Here are several common frame ratios provided. alternatively, you can choose "original" to keep original ratio or customize the ratio using "custom". +* proportional_width: Proportional width. if the aspect ratio option is not "custom", this setting will be ignored. +* proportional_height: Proportional height. if the aspect ratio option is not "custom", this setting will be ignored. +* scale_by_longest_side: Allow scaling by long edge size. +* longest_side: When the scale_by_longest_side is set to True, this will be used this value to the long edge of the image. when the original_size have input, this setting will be ignored. +* detect: Detection method, min_bounding_rect is the minimum bounding rectangle, max_inscribed_rect is the maximum inscribed rectangle. +* border_reserve: Keep the border. expand the cutting range beyond the detected mask body area. +* ultra_detail_range: Mask edge ultra fine processing range, 0 is not processed, which can save generation time. +* matting_method: The method of generate masks. There are two methods available: Segment Anything and RMBG 1.4. RMBG 1.4 runs faster. +* sam_model: Select the SAM model used by Segment Anything here. +* grounding_dino_model: Select the Grounding_Dino model used by Segment Anything here. +* sam_threshold: The threshold for Segment Anything. +* sam_prompt: The prompt for Segment Anything. + +Output: +cropped_image: Crop and replace the background image. +box_preview: Crop position preview. +cropped_mask: Cropped mask. + +### ImageAutoCropV2 + +The V2 upgrad version of ```ImageAutoCrop```, it has made the following changes based on the previous version: +![image](image/image_auto_crop_v2_node.jpg) + +* Add optional input for mask. when there is a mask input, use that input directly to skip the built-in mask generation. +* Add ```fill_background```. When set to False, the background will not be processed and any parts beyond the frame will not be included in the output range. +* ```aspect_ratio``` adds the ```original``` option. +* scale_by: Allow scaling by specified dimensions for longest, shortest, width, or height. +* scale_by_length: The value here is used as ```scale_by``` to specify the length of the edge. + +### ImageAutoCropV3 + +Automatically crop the image to the specified size. You can input a mask to preserve the specified area of the mask. This node is designed to generate image materials for training the model. + +Node Options: +![image](image/image_auto_crop_v3_node.jpg) + +* image: The input image. +* mask: Optional input mask. The masking part will be preserved within the range of the cutting aspect ratio. +* aspect_ratio: The aspect ratio of the output. Here are common frame ratios provided, with "custom" being the custom ratio and "original" being the original frame ratio. +* proportional_width: Proportionally wide. If the aspect_ratio option is not 'custom', this setting will be ignored. +* proportional_height: High proportion. If the aspect_ratio option is not 'custom', this setting will be ignored. +* method: Scaling sampling methods include Lanczos, Bicubic, Hamming, Bilinear, Box, and Nearest. +* scale_to_side: Allow scaling to be specified by long side, short side, width, height, or total pixels. +* scale_to_length: The value here is used as the scale_to-side to specify the length of the edge or the total number of pixels (kilo pixels). +* round_to_multiple: Multiply to the nearest whole. For example, if set to 8, the width and height will be forcibly set to multiples of 8. + +Outputs: +cropped_image: The cropped image. +box_preview: Preview of cutting position. + + + +### SaveImagePlus + +![image](image/saveimage_plus_example.jpg) +Enhanced save image node. You can customize the directory where the picture is saved, add a timestamp to the file name, select the save format, set the image compression rate, set whether to save the workflow, and optionally add invisible watermarks to the picture. (Add information in a way that is invisible to the naked eye, and use the ```ShowBlindWaterMark``` node to decode the watermark). Optionally output the json file of the workflow. + +Node Options: +![image](image/saveimage_plus_node.jpg) + +* iamge: The input image. +* custom_path*: User-defined directory, enter the directory name in the correct format. If empty, it is saved in the default output directory of ComfyUI. +* filename_prefix*: The prefix of file name. +* timestamp: Timestamp the file name, opting for date, time to seconds, and time to milliseconds. +* format: The format of image save. Currently available in ```png``` and ```jpg```. Note that only png format is supported for RGBA mode pictures. +* quality: Image quality, the value range 10-100, the higher the value, the better the picture quality, the volume of the file also correspondingly increases. +* meta_data: Whether to save metadata to png file, that is workflow information. Set this to false if you do not want the workflow to be leaked. +* blind_watermark: The text entered here (does not support multilingualism) will be converted into a QR code and saved as an invisible watermark. Use ```ShowBlindWaterMark``` node can decode watermarks. Note that pictures with watermarks are recommended to be saved in png format, and lower-quality jpg format will cause watermark information to be lost. +* save_workflow_as_json: Whether the output workflow is a json file at the same time (the output json is in the same directory as the picture). +* preview: Preview switch. + +* Enter```%date``` for the current date (YY-mm-dd) and ```%time``` for the current time (HH-MM-SS). You can enter ```/``` for subdirectories. For example, ```%date/name_%tiem``` will output the image to the ```YY-mm-dd``` folder, with ```name_HH-MM-SS``` as the file name prefix. + + + +### AddBlindWaterMark + +![image](image/watermark_example.jpg) +Add an invisible watermark to a picture. Add the watermark image in a way that is invisible to the naked eye, and use the ```ShowBlindWaterMark``` node to decode the watermark. + +Node Options: +![image](image/add_blind_watermark_node.jpg) + +* iamge: The input image. +* watermark_image: Watermark image. The image entered here will automatically be converted to a square black and white image as a watermark. It is recommended to use a QR code as a watermark. + +### ShowBlindWaterMark + +Decoding the invisible watermark added to the ```AddBlindWaterMark``` and ```SaveImagePlus``` nodes. +![image](image/show_blind_watermark_node.jpg) + +### CreateQRCode + +Generate a square QR code picture. + +Node Options: +![image](image/create_qrcode_node.jpg) + +* size: The side length of image. +* border: The size of the border around the QR code, the larger the value, the wider the border. +* text: Enter the text content of the QR code here, and multi-language is not supported. + +### DecodeQRCode + +Decoding the QR code. + +Node Options: +![image](image/decode_qrcode_node.jpg) + +* image: The input QR code image. +* pre_blur: Pre-blurring, you can try to adjust this value for QR codes that are difficult to identify. + +### LoadPSD + +![image](image/load_image_example_psd_file.jpg) +![image](image/load_image_example.jpg) +Load the PSD format file and export the layers. +Note that this node requires the installation of the ```psd_tools``` dependency package, If error occurs during the installation of psd_tool, such as ```ModuleNotFoundError: No module named 'docopt'``` , please download [docopt's whl](https://www.piwheels.org/project/docopt/) and manual install it. + +Node Options: +![image](image/load_image_node.jpg) + +* image: Here is a list of *.psd files under ```ComfyUI/input```, where previously loaded psd images can be selected. +* file_path: The complete path and file name of the psd file. +* include_hidden_layer: whether include hidden layers. +* find_layer_by: The method for finding layers can be selected by layer key number or layer name. Layer groups are treated as one layer. +* layer_index: The layer key number, where 0 is the bottom layer, is incremented sequentially. If include_hiddenlayer is set to false, hidden layers are not counted. Set to -1 to output the top layer. +* layer_name: Layer name. Note that capitalization and punctuation must match exactly. + +Outputs: +flat_image: PSD preview image. +layer_iamge: Find the layer output. +all_layers: Batch images containing all layers. + +### SD3NegativeConditioning + +![image](image/sd3_negative_conditioning_node_note.jpg) +Encapsulate the four nodes of Negative Condition in SD3 into a separate node. + +Node Options: +![image](image/sd3_negative_conditioning_node.jpg) + +* zero_out_start: Set the ConditioningSetTimestepRange start value for Negative ConditioningZeroOut, which is the same as the ConditioningSetTimestepRange end value for Negative. + + + +### SegmentAnythingUltra + +Improvements to [ComfyUI Segment Anything](https://github.com/storyicon/comfyui_segment_anything), thanks to the original author. + +*Please refer to the installation of ComfyUI Segment Anything to install the model. If ComfyUI Segment Anything has been correctly installed, you can skip this step. + +* From [here](https://huggingface.co/bert-base-uncased/tree/main) download the config.json,model.safetensors,tokenizer_config.json,tokenizer.json and vocab.txt 5 files to ```ComfyUI/models/bert-base-uncased``` folder. +* Download [GroundingDINO_SwinT_OGC config file](https://huggingface.co/ShilongLiu/GroundingDINO/resolve/main/GroundingDINO_SwinT_OGC.cfg.py), [GroundingDINO_SwinT_OGC model](https://huggingface.co/ShilongLiu/GroundingDINO/resolve/main/groundingdino_swint_ogc.pth), + [GroundingDINO_SwinB config file](https://huggingface.co/ShilongLiu/GroundingDINO/resolve/main/GroundingDINO_SwinB.cfg.py), [GroundingDINO_SwinB model](https://huggingface.co/ShilongLiu/GroundingDINO/resolve/main/groundingdino_swinb_cogcoor.pth) to ```ComfyUI/models/grounding-dino``` folder. +* Download [sam_vit_h](https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth),[sam_vit_l](https://dl.fbaipublicfiles.com/segment_anything/sam_vit_l_0b3195.pth), + [sam_vit_b](https://dl.fbaipublicfiles.com/segment_anything/sam_vit_b_01ec64.pth), [sam_hq_vit_h](https://huggingface.co/lkeab/hq-sam/resolve/main/sam_hq_vit_h.pth), + [sam_hq_vit_l](https://huggingface.co/lkeab/hq-sam/resolve/main/sam_hq_vit_l.pth), [sam_hq_vit_b](https://huggingface.co/lkeab/hq-sam/resolve/main/sam_hq_vit_b.pth), + [mobile_sam](https://github.com/ChaoningZhang/MobileSAM/blob/master/weights/mobile_sam.pt) to ```ComfyUI/models/sams``` folder. + *Or download them from [GroundingDino models on BaiduNetdisk](https://pan.baidu.com/s/1P7WQDuaqSYazlSQX8SJjxw?pwd=24ki) and [SAM models on BaiduNetdisk](https://pan.baidu.com/s/1n7JrHb2vzV2K2z3ktqpNxg?pwd=yoqh) . + ![image](image/segment_anything_ultra_compare.jpg) + ![image](image/segment_anything_ultra_example.jpg) + +Node options: +![image](image/segment_anything_ultra_node.jpg) + +* sam_model: Select the SAM model. +* ground_dino_model: Select the Grounding DINO model. +* threshold: The threshold of SAM. +* detail_range: Edge detail range. +* black_point: Edge black sampling threshold. +* white_point: Edge white sampling threshold. +* process_detail: Set to false here will skip edge processing to save runtime. +* prompt: Input for SAM's prompt. +* cache_model: Set whether to cache the model. + +### SegmentAnythingUltraV2 + +The V2 upgraded version of SegmentAnythingUltra has added the VITMatte edge processing method.(Note: Images larger than 2K in size using this method will consume huge memory) +![image](image/ultra_v2_nodes_example.jpg) + +On the basis of SegmentAnythingUltra, the following changes have been made: +![image](image/segment_anything_ultra_v2_node.jpg) + +* detail_method: Edge processing methods. provides VITMatte, VITMatte(local), PyMatting, GuidedFilter. If the model has been downloaded after the first use of VITMatte, you can use VITMatte (local) afterwards. +* detail_erode: Mask the erosion range inward from the edge. the larger the value, the larger the range of inward repair. +* detail_dilate: The edge of the mask expands outward. the larger the value, the wider the range of outward repair. +* device: Set whether the VitMatte to use cuda. +* max_megapixels: Set the maximum size for VitMate operations. + +### SAM2Ultra + +This node is modified from [kijai/ComfyUI-segment-anything-2](https://github.com/kijai/ComfyUI-segment-anything-2). Thank to [kijai](https://github.com/kijai) for making significant contributions to the Comfyui community. +SAM2 Ultra node only support single image. If you need to process multiple images, please first convert the image batch to image list. +*Download models from [BaiduNetdisk](https://pan.baidu.com/s/1xaQYBA6ktxvAxm310HXweQ?pwd=auki) or [huggingface.co/Kijai/sam2-safetensors](https://huggingface.co/Kijai/sam2-safetensors/tree/main) and copy to ```ComfyUI/models/sam2``` folder. + +![image](image/sam2_example.jpg) + +Node Options: +![image](image/sam2_ultra_node.jpg) + +* image: The image to segment. +* bboxes: Input recognition box data. +* sam2_model: Select the SAM2 model. +* presicion: Model's persicion. can be selected from fp16, bf16, and fp32. +* bbox_select: Select the input box data. There are three options: "all" to select all, "first" to select the box with the highest confidence, and "by_index" to specify the index of the box. +* select_index: This option is valid when bbox_delect is 'by_index'. 0 is the first one. Multiple values can be entered, separated by any non numeric character, including but not limited to commas, periods, semicolons, spaces or letters, and even Chinese. +* cache_model: Whether to cache the model. After caching the model, it will save time for model loading. +* detail_method: Edge processing methods. provides VITMatte, VITMatte(local), PyMatting, GuidedFilter. If the model has been downloaded after the first use of VITMatte, you can use VITMatte (local) afterwards. +* detail_erode: Mask the erosion range inward from the edge. the larger the value, the larger the range of inward repair. +* detail_dilate: The edge of the mask expands outward. the larger the value, the wider the range of outward repair. +* black_point: Edge black sampling threshold. +* white_point: Edge white sampling threshold. +* process_detail: Set to false here will skip edge processing to save runtime. +* device: Set whether the VitMatte to use cuda. +* max_megapixels: Set the maximum size for VitMate operations. + +### SAM2VideoUltra + +SAM2 Video Ultra node support processing multiple frames of images or video sequences. Please define the recognition box data in the first frame of the sequence to ensure correct recognition. + +https://github.com/user-attachments/assets/4726b8bf-9b98-4630-8f54-cb7ed7a3d2c5 + +https://github.com/user-attachments/assets/b2a45c96-4be1-4470-8ceb-addaf301b0cb + +Node Options: +![image](image/sam2_video_ultra_node.jpg) + +* image: The image to segment. +* bboxes: Optional input of recognition bbox data. ```bboxes``` and ```first_frame_mask``` must have least one input. If first_frame_mask inputed, bbboxes will be ignored. +* first_frame_mask: Optional input of the first frame mask. The mask will be used as the first frame recognition object. ```bboxes``` and ```first_frame_mask``` must have least one input. If first_frame_mask inputed, bbboxes will be ignored. +* pre_mask: Optional input mask, which will serve as a propagation focus range limitation and help improve recognition accuracy. +* sam2_model: Select the SAM2 model. +* presicion: Model's persicion. can be selected from fp16 and bf16. +* cache_model: Whether to cache the model. After caching the model, it will save time for model loading. +* individual_object: When set to True, it will focus on identifying a single object. When set to False, attempts will be made to generate recognition boxes for multiple objects. +* mask_preview_color: Display the color of non masked areas in the preview output. +* detail_method: Edge processing methods. Only VITMatte method can be used. +* detail_erode: Mask the erosion range inward from the edge. the larger the value, the larger the range of inward repair. +* detail_dilate: The edge of the mask expands outward. the larger the value, the wider the range of outward repair. +* black_point: Edge black sampling threshold. +* white_point: Edge white sampling threshold. +* process_detail: Set to false here will skip edge processing to save runtime. +* device: Only cuda can be used. +* max_megapixels: Set the maximum size for VitMate operations.A larger size will result in finer mask edges, but it will lead to a significant decrease in computation speed. + +### ObjectDetectorFL2 + +Use the Florence2 model to identify objects in images and output recognition box data. +*Download models from [BaiduNetdisk](https://pan.baidu.com/s/1hzw9-QiU1vB8pMbBgofZIA?pwd=mfl3) and copy to ```ComfyUI/models/florence2``` folder. + +Node Options: +![image](image/object_detector_fl2_node.jpg) + +* image: The image to segment. +* florence2_model: Florence2 model, it from [LoadFlorence2Model](#LoadFlorence2Model) node. +* prompt: Describe the object that needs to be identified. +* sort_method: The selection box sorting method has 4 options: "left_to_right", "top_to_bottom", "big_to_small" and "confidence". +* bbox_select: Select the input box data. There are three options: "all" to select all, "first" to select the box with the highest confidence, and "by_index" to specify the index of the box. +* select_index: This option is valid when bbox_delect is 'by_index'. 0 is the first one. Multiple values can be entered, separated by any non numeric character, including but not limited to commas, periods, semicolons, spaces or letters, and even Chinese. + +### ObjectDetectorYOLOWorld(Obsoleted. If you want to continue using it, you need to manually install the dependency package) +Due to potential installation issues with dependency packages, this node has been obsoleted. To use, please manually install the following dependency packages: +``` +pip install inference-cli>=0.13.0 +pip install inference-gpu[yolo-world]>=0.13.0 +``` + +Use the YOLO-World model to identify objects in images and output recognition box data. +*Download models from [BaiduNetdisk](https://pan.baidu.com/s/1QpjajeTA37vEAU2OQnbDcQ?pwd=nqsk) or [GoogleDrive](https://drive.google.com/drive/folders/1nrsfq4S-yk9ewJgwrhXAoNVqIFLZ1at7?usp=sharing) and copy to ```ComfyUI/models/yolo-world``` folder. + +Node Options: +![image](image/object_detector_yolo_world_node.jpg) + +* image: The image to segment. +* confidence_threshold: The threshold of confidence. +* nms_iou_threshold: The threshold of Non-Maximum Suppression. +* prompt: Describe the object that needs to be identified. +* sort_method: The selection box sorting method has 4 options: "left_to_right", "top_to_bottom", "big_to_small" and "confidence". +* bbox_select: Select the input box data. There are three options: "all" to select all, "first" to select the box with the highest confidence, and "by_index" to specify the index of the box. +* select_index: This option is valid when bbox_delect is 'by_index'. 0 is the first one. Multiple values can be entered, separated by any non numeric character, including but not limited to commas, periods, semicolons, spaces or letters, and even Chinese. + +### ObjectDetectorYOLO8 + +Use the YOLO-8 model to identify objects in images and output recognition box data. +*Download models from [GoogleDrive](https://drive.google.com/drive/folders/1I5TISO2G1ArSkKJu1O9b4Uvj3DVgn5d2) or [BaiduNetdisk](https://pan.baidu.com/s/1pEY6sjABQaPs6QtpK0q6XA?pwd=grqe) and copy to ```ComfyUI/models/yolo``` folder. + +Node Options: +![image](image/object_detector_yolo8_node.jpg) + +* image: The image to segment. +* yolo_model: Choose the yolo model. +* sort_method: The selection box sorting method has 4 options: "left_to_right", "top_to_bottom", "big_to_small" and "confidence". +* bbox_select: Select the input box data. There are three options: "all" to select all, "first" to select the box with the highest confidence, and "by_index" to specify the index of the box. +* select_index: This option is valid when bbox_delect is 'by_index'. 0 is the first one. Multiple values can be entered, separated by any non numeric character, including but not limited to commas, periods, semicolons, spaces or letters, and even Chinese. + +### ObjectDetectorMask + +Use mask as recognition box data. All areas surrounded by white areas on the mask will be recognized as an object. Multiple enclosed areas will be identified separately. + +Node Options: +![image](image/object_detector_mask_node.jpg) + +* object_mask: The mask input. +* sort_method: The selection box sorting method has 4 options: "left_to_right", "top_to_bottom", "big_to_small" and "confidence". +* bbox_select: Select the input box data. There are three options: "all" to select all, "first" to select the box with the highest confidence, and "by_index" to specify the index of the box. +* select_index: This option is valid when bbox_delect is 'by_index'. 0 is the first one. Multiple values can be entered, separated by any non numeric character, including but not limited to commas, periods, semicolons, spaces or letters, and even Chinese. + +### BBoxJoin + +Merge recognition box data. + +Node Options: +![image](image/bbox_join_node.jpg) + +* bboxes_1: Required input. The first set of identification boxes. +* bboxes_2: Optional input. The second set of identification boxes. +* bboxes_3: Optional input. The third set of identification boxes. +* bboxes_4: Optional input. The fourth set of identification boxes. + +### DrawBBoxMask + +Draw the recognition BBoxes data output by the Object Detector node as a mask. +![image](image/draw_bbox_mask_example.jpg) + +Node Options: +![image](image/draw_bbox_mask_node.jpg) + +* image: Image input. It must be consistent with the image recognized by the Object Detector node. +* bboxes: Input recognition BBoxes data. +* grow_top: Each BBox expands upwards as a percentage of its height, positive values indicate upward expansion and negative values indicate downward expansion. +* grow_bottom: Each BBox expands downwards as a percentage of its height, positive values indicating downward expansion and negative values indicating upward expansion. +* grow_left: Each BBox expands to the left as a percentage of its width, positive values expand to the left and negative values expand to the right. +* grow_right: Each BBox expands to the right as a percentage of its width, positive values indicate expansion to the right and negative values indicate expansion to the left. + +### EVF-SAMUltra + +This node is implementation of [EVF-SAM](https://github.com/hustvl/EVF-SAM) in ComfyUI. +*Please download model files from [BaiduNetdisk](https://pan.baidu.com/s/1EvaxgKcCxUpMbYKzLnEx9w?pwd=69bn) or [huggingface/EVF-SAM2](https://huggingface.co/YxZhang/evf-sam2/tree/main), [huggingface/EVF-SAM](https://huggingface.co/YxZhang/evf-sam/tree/main) to ```ComfyUI/models/EVF-SAM``` folder(save the models in their respective subdirectories). +![image](image/evf_sam_ultra_example.jpg) + +Node Options: +![image](image/evf_sam_ultra_node.jpg) + +* image: The input image. +* model: Select the model. Currently, there are options for evf-sam2 and evf sam. +* presicion: Model accuracy can be selected from fp16, bf16, and fp32. +* load_in_bit: Load the model with positional accuracy. You can choose from full, 8, and 4. +* pormpt: Prompt words used for segmentation. +* detail_method: Edge processing methods. provides VITMatte, VITMatte(local), PyMatting, GuidedFilter. If the model has been downloaded after the first use of VITMatte, you can use VITMatte (local) afterwards. +* detail_erode: Mask the erosion range inward from the edge. the larger the value, the larger the range of inward repair. +* detail_dilate: The edge of the mask expands outward. the larger the value, the wider the range of outward repair. +* black_point: Edge black sampling threshold. +* white_point: Edge white sampling threshold. +* process_detail: Set to false here will skip edge processing to save runtime. +* device: Set whether the VitMatte to use cuda. +* max_megapixels: Set the maximum size for VitMate operations. + +### Florence2Ultra + +Using the segmentation function of the Florence2 model, while also having ultra-high edge details. +The code for this node section is from [spacepxl/ComfyUI-Florence-2](https://github.com/spacepxl/ComfyUI-Florence-2), thanks to the original author. +*Download the model files from [BaiduNetdisk](https://pan.baidu.com/s/1hzw9-QiU1vB8pMbBgofZIA?pwd=mfl3) to ```ComfyUI/models/florence2``` folder. + +![image](image/florence2_ultra_example.jpg) + +Node Options: +![image](image/florence2_ultra_node.jpg) + +* florence2_model: Florence2 model input. +* image: Image input. +* task: Select the task for florence2. +* text_input: Text input for florence2. +* detail_method: Edge processing methods. provides VITMatte, VITMatte(local), PyMatting, GuidedFilter. If the model has been downloaded after the first use of VITMatte, you can use VITMatte (local) afterwards. +* detail_erode: Mask the erosion range inward from the edge. the larger the value, the larger the range of inward repair. +* detail_dilate: The edge of the mask expands outward. the larger the value, the wider the range of outward repair. +* black_point: Edge black sampling threshold. +* white_point: Edge white sampling threshold. +* process_detail: Set to false here will skip edge processing to save runtime. +* device: Set whether the VitMatte to use cuda. +* max_megapixels: Set the maximum size for VitMate operations. + +### LoadFlorence2Model + +Florence2 model loader. +*When using it for the first time, the model will be automatically downloaded. + +![image](image/load_florence2_model_node.jpg) +At present, there are base, base-ft, large, large-ft, DocVQA, SD3-Captioner and base-PromptGen models to choose from. + + + +### BiRefNetUltra + +Using the BiRefNet model to remove background has better recognition ability and ultra-high edge details. +The code for the model part of this node comes from Viper's [ComfyUI-BiRefNet](https://github.com/viperyl/ComfyUI-BiRefNet),thanks to the original author. + +*From [https://huggingface.co/ViperYX/BiRefNet](https://huggingface.co/ViperYX/BiRefNet/tree/main) or [BaiduNetdisk](https://pan.baidu.com/s/1GxtuNDTIHkuu4FR4uGAT-g?pwd=t2cf) download the ```BiRefNet-ep480.pth```,```pvt_v2_b2.pth```,```pvt_v2_b5.pth```,```swin_base_patch4_window12_384_22kto1k.pth```, ```swin_large_patch4_window12_384_22kto1k.pth``` 5 files to ```ComfyUI/models/BiRefNet``` folder. + +![image](image/birefnet_ultra_example.jpg) + +Node options: +![image](image/birefnet_ultra_node.jpg) + +* detail_method: Edge processing methods. provides VITMatte, VITMatte(local), PyMatting, GuidedFilter. If the model has been downloaded after the first use of VITMatte, you can use VITMatte (local) afterwards. +* detail_erode: Mask the erosion range inward from the edge. the larger the value, the larger the range of inward repair. +* detail_dilate: The edge of the mask expands outward. the larger the value, the wider the range of outward repair. +* black_point: Edge black sampling threshold. +* white_point: Edge white sampling threshold. +* process_detail: Set to false here will skip edge processing to save runtime. +* device: Set whether the VitMatte to use cuda. +* max_megapixels: Set the maximum size for VitMate operations. + +### BiRefNetUltraV2 + +This node supports the use of the latest BiRefNet model. +*Download model file from [BaiduNetdisk](https://pan.baidu.com/s/12z3qUuqag3nqpN2NJ5pSzg?pwd=ek65) or [GoogleDrive](https://drive.google.com/drive/folders/1s2Xe0cjq-2ctnJBR24563yMSCOu4CcxM) named ```BiRefNet-general-epoch_244.pth``` to ```ComfyUI/Models/BiRefNet/pth``` folder. You can also download more BiRefNet models and put them here. + +![image](image/birefnet_ultra_v2_example.jpg) + +Node Options: +![image](image/birefnet_ultra_v2_node.jpg) + +* image: The input image. +* birefnet_model: The BiRefNet model is input and it is output from the LoadBiRefNetModel node. +* detail_method: Edge processing methods. provides VITMatte, VITMatte(local), PyMatting, GuidedFilter. If the model has been downloaded after the first use of VITMatte, you can use VITMatte (local) afterwards. +* detail_erode: Mask the erosion range inward from the edge. the larger the value, the larger the range of inward repair. +* detail_dilate: The edge of the mask expands outward. the larger the value, the wider the range of outward repair. +* black_point: Edge black sampling threshold. +* white_point: Edge white sampling threshold. +* process_detail: Due to the excellent edge processing of BiRefNet, it is set to False by default here. +* device: Set whether the VitMatte to use cuda. +* max_megapixels: Set the maximum size for VitMate operations. + +### LoadBiRefNetModel + +Load the BiRefNet model. + +Node Options: +![image](image/load_birefnet_model_node.jpg) + +* model: Select the model. List the files in the ```CoomfyUI/models/BiRefNet/pth``` folder for selection. + + +### LoadBiRefNetModelV2 +This node is a PR submitted by [jimlee2048](https://github.com/jimlee2048) and supports loading RMBG-2.0 models. + +Download model files from [huggingface](https://huggingface.co/briaai/RMBG-2.0/tree/main) or [百度网盘](https://pan.baidu.com/s/1viIXlZnpTYTKkm2F-QMj_w?pwd=axr9) and copy to ```ComfyUI/models/BiRefNet/RMBG-2.0``` folder. + +Node Options: +![image](image/load_birefnet_model_v2_node.jpg) + +* model: Select the model. There are two options, ```BiRefNet-General``` and ```RMBG-2.0```. + + +### TransparentBackgroundUltra + +Using the transparent-background model to remove background has better recognition ability and speed, while also having ultra-high edge details. + +*From [googledrive](https://drive.google.com/drive/folders/10KBDY19egb8qEQBv34cqIVSwd38bUAa9?usp=sharing) or [BaiduNetdisk](https://pan.baidu.com/s/10JO0uKzTxJaIkhN_J7RSyw?pwd=v0b0) download all files to ```ComfyUI/models/transparent-background``` folder. + +![image](image/transparent_background_ultra_example.jpg) + +Node Options: +![image](image/transparent_background_ultra_node.jpg) + +* model: Select the model. +* detail_method: Edge processing methods. provides VITMatte, VITMatte(local), PyMatting, GuidedFilter. If the model has been downloaded after the first use of VITMatte, you can use VITMatte (local) afterwards. +* detail_erode: Mask the erosion range inward from the edge. the larger the value, the larger the range of inward repair. +* detail_dilate: The edge of the mask expands outward. the larger the value, the wider the range of outward repair. +* black_point: Edge black sampling threshold. +* white_point: Edge white sampling threshold. +* process_detail: Set to false here will skip edge processing to save runtime. +* device: Set whether the VitMatte to use cuda. +* max_megapixels: Set the maximum size for VitMate operations. + +### PersonMaskUltra + +Generate masks for portrait's face, hair, body skin, clothing, or accessories. Compared to the previous A Person Mask Generator node, this node has ultra-high edge details. +The model code for this node comes from [a-person-mask-generator](https://github.com/djbielejeski/a-person-mask-generator), edge processing code from [ComfyUI-Image-Filters](https://github.com/spacepxl/ComfyUI-Image-Filters),thanks to the original author. +*Download model files from [BaiduNetdisk](https://pan.baidu.com/s/13zqZtBt89ueCyFufzUlcDg?pwd=jh5g) to ```ComfyUI/models/mediapipe``` folder. + +![image](image/person_mask_ultra_example.jpg) + +Node options: +![image](image/person_mask_ultra_node.jpg) + +* face: Face recognition. +* hair: Hair recognition. +* body: Body skin recognition. +* clothes: Clothing recognition. +* accessories: Identification of accessories (such as backpacks). +* background: Background recognition. +* confidence: Recognition threshold, lower values will output more mask ranges. +* detail_range: Edge detail range. +* black_point: Edge black sampling threshold. +* white_point: Edge white sampling threshold. +* process_detail: Set to false here will skip edge processing to save runtime. + +### PersonMaskUltraV2 + +The V2 upgraded version of PersonMaskUltra has added the VITMatte edge processing method.(Note: Images larger than 2K in size using this method will consume huge memory) + +On the basis of PersonMaskUltra, the following changes have been made: +![image](image/person_mask_ultra_v2_node.jpg) + +* detail_method: Edge processing methods. provides VITMatte, VITMatte(local), PyMatting, GuidedFilter. If the model has been downloaded after the first use of VITMatte, you can use VITMatte (local) afterwards. +* detail_erode: Mask the erosion range inward from the edge. the larger the value, the larger the range of inward repair. +* detail_dilate: The edge of the mask expands outward. the larger the value, the wider the range of outward repair. +* device: Set whether the VitMatte to use cuda. +* max_megapixels: Set the maximum size for VitMate operations. + + +### HumanPartsUltra + +Used for generate human body parts masks, it is based on the warrper of [metal3d/ComfyUI_Human_Parts](https://github.com/metal3d/ComfyUI_Human_Parts), thank the original author. +This node has added ultra-fine edge processing based on the original work. Download model file from [BaiduNetdisk](https://pan.baidu.com/s/1-6uwH6RB0FhIVfa3qO7hhQ?pwd=d862) or [huggingface](https://huggingface.co/Metal3d/deeplabv3p-resnet50-human/tree/main) and copy to ```ComfyUI\models\onnx\human-parts``` folder. +![image](image/human_parts_ultra_example.jpg) + +Node Options: +![image](image/human_parts_node.jpg) + +* image: The input image. +* face: Recognize face switch. +* hair: Recognize hair switch. +* galsses: Recognize glasses switch. +* top_clothes: Recognize top clothes switch. +* bottom_clothes: Recognize bottom clothes switch. +* torso_skin: Recognize torso skin switch. +* left_arm: Recognize left arm switch. +* right_arm: Recognize right arm switch. +* left_leg: Recognize left leg switch. +* right_leg: Recognize right leg switch. +* left_foot: Recognize left foot switch. +* right_foot: Recognize right foot switch. +* detail_method: Edge processing methods. provides VITMatte, VITMatte(local), PyMatting, GuidedFilter. If the model has been downloaded after the first use of VITMatte, you can use VITMatte (local) afterwards. +* detail_erode: Mask the erosion range inward from the edge. the larger the value, the larger the range of inward repair. +* detail_dilate: The edge of the mask expands outward. the larger the value, the wider the range of outward repair. +* black_point: Edge black sampling threshold. +* white_point: Edge white sampling threshold. +* process_detail: Set to false here will skip edge processing to save runtime. +* device: Set whether the VitMatte to use cuda. +* max_megapixels: Set the maximum size for VitMate operations. + + + +### YoloV8Detect + +Use the YoloV8 model to detect faces, hand box areas, or character segmentation. Supports the output of the selected number of channels. +Download the model files from [GoogleDrive](https://drive.google.com/drive/folders/1I5TISO2G1ArSkKJu1O9b4Uvj3DVgn5d2) or [BaiduNetdisk](https://pan.baidu.com/s/1pEY6sjABQaPs6QtpK0q6XA?pwd=grqe) to ```ComfyUI/models/yolo``` folder. + +![image](image/yolov8_detect_example.jpg) + +Node Options: +![image](image/yolov8_detect_node.jpg) + +* yolo_model: Yolo model selection. the model with ```seg``` name can output segmented masks, otherwise they can only output box masks. +* mask_merge: Select the merged mask. ```all``` is to merge all mask outputs. The selected number is how many masks to output, sorted by recognition confidence to merge the output. + +Outputs: + +* mask: The output mask. +* yolo_plot_image: Preview of yolo recognition results. +* yolo_masks: For all masks identified by yolo, each individual mask is output as a mask. + +### MediapipeFacialSegment + +Use the Mediapipe model to detect facial features, segment left and right eyebrows, eyes, lips, and tooth. +*Download the model files from [BaiduNetdisk](https://pan.baidu.com/s/13zqZtBt89ueCyFufzUlcDg?pwd=jh5g) to ```ComfyUI/models/mediapipe``` folder. + +![image](image/mediapipe_facial_segment_example.jpg) + +Node Options: +![image](image/mediapipe_facial_segment_node.jpg) + +* left_eye: Recognition switch of left eye. +* left_eyebrow: Recognition switch of left eyebrow. +* right_eye: Recognition switch of right eye. +* right_eyebrow: Recognition switch of right eyebrow. +* lips: Recognition switch of lips. +* tooth: Recognition switch of tooth. + + +### MaskByDifferent + +Calculate the differences between two images and output them as mask. +![image](image/mask_by_different_example.jpg) + +Node options: +![image](image/mask_by_different_node.jpg) + +* gain: The gain of difference calculate. higher value will result in a more significant slight difference. +* fix_gap: Fix the internal gaps of the mask. higher value will repair larger gaps. +* fix_threshold: The threshold for fix_gap. +* main_subject_detect: Setting this to True will enable subject detection, ignoring differences outside of the subject. + + +## Annotation for notes + +1 The layer_image, layer_mask and the background_image(if have input), These three items must be of the same size. + +2 The mask not a mandatory input item. the alpha channel of the image is used by default. If the image input does not include an alpha channel, the entire image's alpha channel will be automatically created. if have masks input simultaneously, the alpha channel will be overwrite by the mask. + +3 The Blend Mode include **normal, multply, screen, add, subtract, difference, darker, color_burn, color_dodge, linear_burn, linear_dodge, overlay, soft_light, hard_light, vivid_light, pin_light, linear_light, and hard_mix.** all of 19 blend modes in total. +![image](image/blend_mode_result.jpg) +*Preview of the blend mode
+ +3 The BlendModeV2 include **normal, dissolve, darken, multiply, color burn, linear burn, darker color, lighten, screen, color dodge, linear dodge(add), lighter color, dodge, overlay, soft light, hard light, vivid light, linear light, pin light, hard mix, difference, exclusion, subtract, divide, hue, saturation, color, luminosity, grain extract, grain merge** all of 30 blend modes in total. +Part of the code for BlendMode V2 is from [Virtuoso Nodes for ComfyUI](https://github.com/chrisfreilich/virtuoso-nodes). Thanks to the original authors. +![image](image/blend_mode_v2_example.jpg) +*Preview of the Blend Mode V2
+ +4 The RGB color described by hexadecimal RGB format, like '#FA3D86'. + +5 The layer_image and layer_mask must be of the same size. + +## Stars + +[![Star History Chart](https://api.star-history.com/svg?repos=chflame163/ComfyUI_LayerStyle_Advance&type=Date)](https://star-history.com/#chflame163/ComfyUI_LayerStyle_Advance&Date) + +# statement + +LayerStyle Advance nodes follows the MIT license, Some of its functional code comes from other open-source projects. Thanks to the original author. If used for commercial purposes, please refer to the original project license to authorization agreement. diff --git a/README_CN.MD b/README_CN.MD new file mode 100644 index 0000000..a2004b4 --- /dev/null +++ b/README_CN.MD @@ -0,0 +1,980 @@ +# ComfyUI Layer Style Advance + +从ComfyUI Layer Style 剥离出来的节点,主要是一些对依赖包要求较为复杂的节点。 + + +## 工作流用示例 +在workflow目录下有json格式的工作流示例文件,示范了如何在ComfyUI中使用这些节点。 + + +## 安装方法 +(以ComfyUI官方便携包和秋叶整合包为例,其他ComfyUI环境请修改依赖环境目录) + +### 安装插件 +* 推荐使用 ComfyUI Manager 安装。 +* 或者在CompyUI插件目录(例如“CompyUI\custom_nodes\”)中打开cmd窗口,键入 +``` +git clone https://github.com/chflame163/ComfyUI_LayerStyle_Advance.git +``` + +* 或者下载解压zip文件,将得到的文件夹复制到 ```ComfyUI\custom_nodes\```。 + +### 安装依赖包 + +* 官方便携包请双击运行插件目录下的```install_requirements.bat```,秋叶整合包请双击运行插件目录下的```install_requirements_aki.bat```,然后等待安装完成。 + +* 或者在资源管理器```ComfyUI\custom_nodes\ComfyUI_LayerStyle_Advance``` 插件目录位置打开cmd窗口, + +  官方便携包输入以下命令: + +``` +..\..\..\python_embeded\python.exe -s -m pip install .\whl\docopt-0.6.2-py2.py3-none-any.whl +..\..\..\python_embeded\python.exe -s -m pip install .\whl\hydra_core-1.3.2-py3-none-any.whl +..\..\..\python_embeded\python.exe -s -m pip install -r requirements.txt +.\repair_dependency.bat +``` +  秋叶整合包输入以下命令: + +``` +..\..\python\python.exe -s -m pip install .\whl\docopt-0.6.2-py2.py3-none-any.whl +..\..\python\python.exe -s -m pip install .\whl\hydra_core-1.3.2-py3-none-any.whl +..\..\python\python.exe -s -m pip install -r requirements.txt +.\repair_dependency.bat +``` +* 重新打开ComfyUI。 + +### 下载模型 +国内用户请从[百度网盘](https://pan.baidu.com/s/1T_uXMX3OKIWOJLPuLijrgA?pwd=1yye), 海外用户请从[huggingface](https://huggingface.co/chflame163/ComfyUI_LayerStyle/tree/main), +下载全部模型文件并复制到```ComfyUI\models```文件夹。这个链接提供了本插件需要的所有的模型文件。 +或者按各个节点的说明下载模型文件。 + +## 常见问题 +如果节点不能正常加载,或者使用中出现错误,请在ComfyUI终端窗口查看报错信息。以下是常见的错误及解决方法。 + +### Warning: xxxx.ini not found, use default xxxx.. +这个警告信息是找不到ini文件的提示,不影响使用。如果不想看到这些警告,请修改插件目录下所有的 ```*.ini.example``` 文件名为```*.ini```。 + +### ModuleNotFoundError: No module named 'psd_tools' +这个错误是```psd_tools```没有正确安装。 + +解决方法: +* 关闭ComfyUI,在插件目录下打开终端窗口,执行以下命令: +```../../../python_embeded/python.exe -s -m pip install psd_tools``` +如果安装psd_tool中出现```ModuleNotFoundError: No module named 'docopt'```错误,请下载[docopt的whl](https://www.piwheels.org/project/docopt/)手动安装。在终端执行以下命令: +```../../../python_embeded/python.exe -s -m pip install path/docopt-0.6.2-py2.py3-none-any.whl``` path为whl文件的路径名。 + +### Cannot import name 'guidedFilter' from 'cv2.ximgproc' +这个错误是```opencv-contrib-python```没有正确安装,或者安装后又安装了其他opencv包导致。 + +### NameError: name 'guidedFilter' is not defined +问题原因同上。 + +### Cannot import name 'VitMatteImageProcessor' from 'transformers' +这个错误是由于```transformers``` 版本过低造成的 + +### insightface 加载缓慢 +这是由于```protobuf``` 版本过低造成的。 + +#### 以上3个依赖包的问题,请双击运行插件目录下的```repair_dependency.bat```(官方便携包)或者```repair_dependency_aki.bat```(秋叶整合包)自动修复。 + +### onnxruntime::python::CreateExecutionProviderInstance CUDA_PATH is set but CUDA wasn't able to be loaded. Please install the correct version of CUDA and cuDNN as mentioned in the GPU requirements page +解决方法: +请重新安装```onnxruntime```依赖包 + +### Error loading model xxx: We couldn't connect to huggingface.co ... +请检查网络环境。如果在中国不能正常访问huggingface.co,请尝试修改huggingface_hub包强制使用hf_mirror镜像。 +* 在```huggingface_hub```包的目录(通常在虚拟环境内的```Lib/site-packages/huggingface_hub```)中找到```constants.py```, +在```import os```之后增加一行 +``` +os.environ['HF_ENDPOINT'] = 'https://hf-mirror.com' +``` + +### ValueError: Trimap did not contain foreground values (xxxx...) +这个错误是由于使用PyMatting方法处理遮罩边缘时,遮罩面积过大或者过小引起的。 + +解决方法: +* 请调整参数,改变遮罩有效面积。或者换用其他的方法处理边缘。 + +### Requests.exceptions.ProxyError: HTTPSConnectionPool(xxxx...) +出现这个错误,请检查网络环境。 + +### UnboundLocalError: local variable 'clip_processor' referenced before assignment +### UnboundLocalError: local variable 'text_model' referenced before assignment +如果执行JoyCaption2节点时出现这个报错,同时已确定模型文件已放在正确的目录,请检查```transformers```依赖包版本至少在4.43.2以上。 +如果```transformers```依赖包版本大于等于4.45.0, 并同时有报错信息: +``` +Error loading models: De️️scriptors cannot be created directly. +If this call came from a _pb2.py file, your generated code is out of date and must be regenerated with protoc >= 3.19.0. +...... +``` +请尝试降级```protobuf```依赖包到3.20.3, 或者设置环境变量:```PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=python```。 + +## 如何找到本节点组 +* 在ComfyUI画布点击右键 - Add Node, 找到 "😺dzNodes"。 +![image](image/node-menu.jpg) + +* 或者在ComfyUI画布双击, 在搜索框输入"layer"。 +![image](image/node-search.jpg) + + +## 更新说明 +**如果本插件更新后出现依赖包错误,请双击运行插件目录下的```install_requirements.bat```(官方便携包),或 ```install_requirements_aki.bat```(秋叶整合包) 重新安装依赖包。 + +* 从requirements.txt 中废弃 [ObjectDetector YOLOWorld](#ObjectDetectorYOLOWorld) 节点所需的依赖。如需使用此节点,请手动安装依赖包。 +* 从ComfyUI Layer Style 剥离部分节点至本仓库。 + + +## 节点说明 + +### QWenImage2Prompt +根据图片反推提示词。这个节点是[ComfyUI_VLM_nodes](https://github.com/gokayfem/ComfyUI_VLM_nodes)中的```UForm-Gen2 Qwen Node```节点的重新封装,感谢原作者。 +请从[huggingface](https://huggingface.co/unum-cloud/uform-gen2-qwen-500m)或者[百度网盘](https://pan.baidu.com/s/1oRkUoOKWaxGod_XTJ8NiTA?pwd=d5d2)下载模型到```ComfyUI/models/LLavacheckpoints/files_for_uform_gen2_qwen```文件夹。 + +![image](image/qwen_image2prompt_example.jpg) + +节点选项说明: +* question: 对UForm-Gen-QWen模型的提示词。 + +### LlamaVision +使用Llama 3.2 vision 模型进行本地推理。可以用于生成提示词。本节点部分代码来自[ComfyUI-PixtralLlamaMolmoVision](https://github.com/SeanScripts/ComfyUI-PixtralLlamaMolmoVision),感谢原作者。 +运行这个节点需要transformers升级到4.45.0以上。 +请从 [百度网盘](https://pan.baidu.com/s/18oHnTrkNMiwKLMcUVrfFjA?pwd=4g81) 或 [huggingface/SeanScripts](https://huggingface.co/SeanScripts/Llama-3.2-11B-Vision-Instruct-nf4/tree/main)下载整个文件夹,并复制到ComfyUI/models/LLM。 + +![image](image/llama_vision_example.jpg) + +节点选项说明: +![image](image/llama_vision_node.jpg) + +* image: 图片输入。 +* model: 目前仅有"Llama-3.2-11B-Vision-Instruct-nf4"这一个模型可用。 +* system_prompt: LLM模型的系统提示词。 +* user_prompt: LLM模型的用户提示词。 +* max_new_tokens: LLM的max_new_tokens参数。 +* do_sample: LLM的do_sample参数。 +* top-p: LLM的top_p参数。 +* top_k: LLM的top_k参数。 +* stop_strings: 截止字符串。 +* seed: 随机种子。 +* control_after_generate: 种子变化选项。 +* include_prompt_in_output: 输出是否包含提示词。 +* cache_model: 是否缓存模型。 + +### JoyCaption2 +使用JoyCaption-alpha-two模型生成提示词。本节点是 https://huggingface.co/John6666/joy-caption-alpha-two-cli-mod 在ComfyUI中的实现,感谢原作者。 +请从 [百度网盘](https://pan.baidu.com/s/1dOjbUEacUOhzFitAQ3uIeQ?pwd=4ypv) 以及 [百度网盘](https://pan.baidu.com/s/1mH1SuW45Dy6Wga7aws5siQ?pwd=w6h5) , +或者 [huggingface/Orenguteng](https://huggingface.co/Orenguteng/Llama-3.1-8B-Lexi-Uncensored-V2/tree/main) 以及 [huggingface/unsloth](https://huggingface.co/unsloth/Meta-Llama-3.1-8B-Instruct/tree/main) 下载整个文件夹,并复制到ComfyUI/models/LLM, +从 [百度网盘](https://pan.baidu.com/s/1pkVymOsDcXqL7IdQJ6lMVw?pwd=v8wp) 或者 [huggingface/google](https://huggingface.co/google/siglip-so400m-patch14-384/tree/main) 下载整个文件夹,并复制到ComfyUI/models/clip, +从 [百度网盘](https://pan.baidu.com/s/12TDwZAeI68hWT6MgRrrK7Q?pwd=d7dh) 或者 [huggingface/John6666](https://huggingface.co/John6666/joy-caption-alpha-two-cli-mod/tree/main)下载 ```cgrkzexw-599808``` 文件夹,并复制到ComfyUI/models/Joy_caption。 +![image](image/joycaption2_example.jpg) + +节点选项说明: +![image](image/joycaption2_node.jpg) + +* image: 图片输入。 +* extra_options: extra_options参数输入。 +* llm_model: 目前有 Orenguteng/Llama-3.1-8B-Lexi-Uncensored-V2 和 unsloth/Meta-Llama-3.1-8B-Instruct 两种LLM模型可选择。 +* device: 模型加载设备。目前仅支持cuda。 +* dtype: 模型加载精度,有nf4 和 bf16 两个选项。 +* vlm_lora: 是否加载text_model。 +* caption_type: caption类型选项, 包括"Descriptive"(正式语气描述), "Descriptive (Informal)"(非正式语气描述), "Training Prompt"(SD训练描述), "MidJourney"(MJ风格描述), "Booru tag list"(标签列表), "Booru-like tag list"(类标签列表), "Art Critic"(艺术评论), "Product Listing"(产品列表), "Social Media Post"(社交媒体风格)。 +* caption_length: 描述长度。 +* user_prompt: LLM模型的用户提示词。如果这里有内容将覆盖caption_type和extra_options的所有设置。 +* max_new_tokens: LLM的max_new_tokens参数。 +* do_sample: LLM的do_sample参数。 +* top-p: LLM的top_p参数。 +* temperature: LLM的temperature参数。 +* cache_model: 是否缓存模型。 + +### JoyCaption2Split +JoyCaption2 的分离式节点,将模型加载与推理分离,使用多个JoyCaption2节点时可共用模型提高效率。 + +节点选项说明: +![image](image/joycaption2_split_node.jpg) + +* image: 图片输入。 +* joy2_model: JoyCaption模型输入。 +* extra_options: extra_options参数输入。 +* caption_type: caption类型选项, 包括"Descriptive"(正式语气描述), "Descriptive (Informal)"(非正式语气描述), "Training Prompt"(SD训练描述), "MidJourney"(MJ风格描述), "Booru tag list"(标签列表), "Booru-like tag list"(类标签列表), "Art Critic"(艺术评论), "Product Listing"(产品列表), "Social Media Post"(社交媒体风格)。 +* caption_length: 描述长度。 +* user_prompt: LLM模型的用户提示词。如果这里有内容将覆盖caption_type和extra_options的所有设置。 +* max_new_tokens: LLM的max_new_tokens参数。 +* do_sample: LLM的do_sample参数。 +* top-p: LLM的top_p参数。 +* temperature: LLM的temperature参数。 + +### LoadJoyCaption2Model +JoyCaption2 的模型加载节点,与JoyCaption2Split配合使用。 + +节点选项说明: +![image](image/load_joycaption2_model_node.jpg) + +* llm_model: 目前有 Orenguteng/Llama-3.1-8B-Lexi-Uncensored-V2 和 unsloth/Meta-Llama-3.1-8B-Instruct 两种LLM模型可选择。 +* device: 模型加载设备。目前仅支持cuda。 +* dtype: 模型加载精度,有nf4 和 bf16 两个选项。 +* vlm_lora: 是否加载text_model。 + + +### JoyCaption2ExtraOptions +JoyCaption2的extra_options参数节点。 + +节点选项说明: +![image](image/joycaption2_extra_options_node.jpg) + +* refer_character_name: 如果图像中有人物/角色,必须将其称为{name} +* exclude_people_info: 不要包含有关无法更改的人物/角色的信息(例如种族、性别等),但仍包含可更改的属性(例如发型)。 +* include_lighting: 包括照明信息。 +* include_camera_angle: 包括摄影机角度信息。 +* include_watermark: 包括是否有水印信息。 +* include_JPEG_artifacts: 包括是否存在 JPEG 伪影信息。 +* include_exif: 如果是照片,包含相机的信息以及光圈、快门速度、ISO等信息。 +* exclude_sexual: 不要包含任何与性有关的内容,保持PG。 +* exclude_image_resolution: 不要包含图像分辨率信息。 +* include_aesthetic_quality: 包含图像美学(从低到非常高)信息。 +* include_composition_style: 包括有关图像构图风格的信息,例如引导线、三分法或对称性。 +* exclude_text: 不要包含任何文字信息。 +* specify_depth_field: 包含景深以及背景模糊信息。 +* specify_lighting_sources: 如果可以判别人造或自然光源,则包含在内。 +* do_not_use_ambiguous_language: 不要使用任何含糊不清的言辞。 +* include_nsfw: 包含NSFW或性暗示信息。 +* only_describe_most_important_elements: 只描述最重要的元素。 +* character_name: 如果选择了```refer_character_name```,则使用此处的名字。 + +### PhiPrompt +使用Micrisoft Phi 3.5文字及视觉模型进行本地推理。可以用于生成提示词,加工提示词或者反推图片的提示词。运行这个模型需要至少16GB的显存。 +请从[百度网盘](https://pan.baidu.com/s/1BdTLdaeGC3trh1U3V-6XTA?pwd=29dh) 或者 [huggingface.co/microsoft/Phi-3.5-vision-instruct](https://huggingface.co/microsoft/Phi-3.5-vision-instruct/tree/main) 和 [huggingface.co/microsoft/Phi-3.5-mini-instruct](https://huggingface.co/microsoft/Phi-3.5-mini-instruct/tree/main) 下载全部模型文件并放到 ```ComfyUI\models\LLM``` 文件夹。 +![image](image/phi_prompt_example.jpg) + +节点选项说明: +![image](image/phi_prompt_node.jpg) + +* image: 可选输入。输入的图片将作为Phi-3.5-vision-instruct的输入。 +* model: 可选择加载的Phi-3.5-vision-instruct模型,或者Phi-3.5-mini-instruct模型。默认值auto将根据是否有图片输入自动加载对应模型。 +* device: 模型加载设备。支持cpu和cuda。 +* dtype: 模型加载精度,有fp16、bf16和fp32三个选项。 +* cache_model: 是否缓存模型。 +* system_prompt: Phi-3.5-mini-instruct的系统提示词。 +* user_prompt: LLM模型的用户提示词。 +* do_sample: LLM的do_sample参数,默认为True。 +* temperature: LLM的temperature参数,默认为0.5。 +* max_new_tokens: LLM的max_new_tokens参数,默认为512。 + + +### UserPromptGeneratorTxtImg +用于生成SD文本到图片提示词的UserPrompt预设。 + +节点选项说明: +![image](image/userprompt_generator_txt2img_node.jpg) + +* template: 提示词模板。目前仅有“SD txt2img prompt”可用。 +* describe: 提示词描述。在这里输入简单的描述。 +* limit_word: 输出的提示词最大长度限制。例如200即表示输出文本将被限制在200个词以内。 + +### UserPromptGeneratorTxtImgWithReference +用于参考输入的内容生成SD文本到图片提示词的UserPrompt预设。 + +节点选项说明: +![image](image/userprompt_generator_txt2img_with_reference_node.jpg) + +* reference_text: 参考文本输入。通常是图片的风格描述。 +* template: 提示词模板。目前仅有“SD txt2img prompt”可用。 +* describe: 提示词描述。在这里输入简单的描述。 +* limit_word: 输出的提示词最大长度限制。例如200即表示输出文本将被限制在200个词以内。 + + +### UserPromptGeneratorReplaceWord +用于将文本中的某个关键词替换为不同内容的UserPrompt预设。这不仅是简单的替换,还可以根据提示词上下文进行文字逻辑梳理以达到输出内容的合理性。 + +节点选项说明: +![image](image/userprompt_generator_replace_word_node.jpg) + +* orig_prompt: 原始提示词输入。 +* template: 提示词模板。目前仅有“prompt replace word”可用。 +* exclude_word: 需要排除的关键词。 +* replace_with_word: 替换exclude_word的关键词。 + +### PromptTagger +根据图片反推提示词,可以设置替换词。这个节点目前使用Google Gemini API作为后端服务,请确保网络环境可以正常使用Gemini。 +请在[Google AI Studio](https://makersuite.google.com/app/apikey)申请你的API key, 并将其填到```api_key.ini```, 这个文件位于插件根目录下, 默认名字是```api_key.ini.example```, 初次使用这个文件需将文件后缀改为.ini。用文本编辑软件打开,在```google_api_key=```后面填入你的API key并保存。 +![image](image/prompt_tagger_example.jpg) + +节点选项说明: +![image](image/prompt_tagger_node.jpg) + +* api: 使用的Api。有"gemini-1.5-flash"和"google-gemini"两个选项。 +* token_limit: 生成提示词的最大token限制。 +* exclude_word: 需要排除的关键词。 +* replace_with_word: 替换exclude_word的关键词。 + +### PromptEmbellish +输入简单的提示词,输出经过润色的提示词,支持输入图片作为参考,支持中文输入。这个节点目前使用Google Gemini API作为后端服务,请确保网络环境可以正常使用Gemini。 +请在[Google AI Studio](https://makersuite.google.com/app/apikey)申请你的API key, 并将其填到```api_key.ini```, 这个文件位于插件根目录下, 默认名字是```api_key.ini.example```, 初次使用这个文件需将文件后缀改为.ini。用文本编辑软件打开,在```google_api_key=```后面填入你的API key并保存。 +![image](image/prompt_embellish_example.jpg) + +节点选项说明: +![image](image/prompt_embellish_node.jpg) + +* image: 可选项,输入图像作为提示词参考。 +* api: 使用的Api。有"gemini-1.5-flash"和"google-gemini"两个选项。 +* token_limit: 生成提示词的最大token限制。 +* discribe: 在这里输入简单的描述。支持中文。 + +### Florence2Image2Prompt +使用florence2模型反推提示词。本节点部分的代码来自[yiwangsimple/florence_dw](https://github.com/yiwangsimple/florence_dw),感谢原作者。 +*首次使用时将自动下载模型,请在可以访问huggingface.co的网络环境下使用。您也可以从[百度网盘](https://pan.baidu.com/s/1hzw9-QiU1vB8pMbBgofZIA?pwd=mfl3)下载模型文件并复制到```ComfyUI/models/florence2```文件夹。 + +![image](image/florence2_image2prompt_example.jpg) + +节点选项说明: +![image](image/florence2_image2prompt_node.jpg) +* florence2_model: Florence2模型输入。 +* image: 图片输入。 +* task: 选择florence2任务。 +* text_input: florence2任务文本输入。 +* max_new_tokens: 生成文本的最大token数量。 +* num_beams: 生成文本的beam search数量。 +* do_sample: 是否使用文本生成采样。 +* fill_mask: 是否使用文本标记掩码填充。 + +### GetColorTone +从图片中获取主颜色或平均色。 +![image](image/get_color_tone_example.jpg) + +节点选项说明: +![image](image/get_color_tone_node.jpg) +* mode: 模式,有两种可选择,主颜色main_color和平均色average。 + +输出: +* RGB color in HEX: 使用16进制RGB字符串格式描述,例如 '#FA3D86'。 +* HSV color in list: HSV颜色值,使用list格式描述。 + +### GetColorToneV2 +GetColorTone的V2升级版。可以指定获取主体或背景的主色或平均色。 +![image](image/get_color_tone_v2_example.jpg) +![image](image/get_color_tone_v2_example2.jpg) + +在GetColorTong基础上做了如下改变: +![image](image/get_color_tone_v2_node.jpg) +* color_of: 提供4个选项,mask, entire, background和subject, 分别表示选择遮罩区域,整个图片,背景,或主体的颜色。 +* remove_background_method: 背景识别的方法, 有BiRefNet和RMBG V1.4两种可以选择。 +* invert_mask: 是否反转遮罩。 +* mask_grow: 遮罩扩张。对于subject, 更大的值使获得的颜色更接近主体中心的颜色。 + +输出: +* image: 纯色图片输出, 尺寸与输入的图片相同。 +* mask: 遮罩输出。 + + +### ImageRewardFilter +![image](image/image_reward_filter_example.jpg) +对批量图片评分并输出排名靠前的图片。这个节点使用了[ImageReward](https://github.com/THUDM/ImageReward)作为图片评分,感谢原作者。 + +![image](image/image_reward_filter_node.jpg) +节点选项说明: +* prompt: 可选输入。将prompt在此输入将作为依据判定其与图片的符合程度。 +* output_nun: 输出的图片数量。此数值应小于图片批量。 + +输出: +* images: 按评分顺序从高到低输出的批量图片。 +* obsolete_images: 淘汰的图片。同样按评分顺序从高到低输出。 + + +### LaMa +![image](image/lama_example.jpg) +根据图像遮罩擦除物体。本节点是对[IOPaint](https://www.iopaint.com)的封装,由 SOTA AI 模型提供支持, 感谢原作者。 +提供[LaMa](https://github.com/advimman/lama), [LDM](https://github.com/CompVis/latent-diffusion), [ZITS](https://github.com/DQiaole/ZITS_inpainting),[MAT](https://github.com/fenglinglwb/MAT), [FcF](https://github.com/SHI-Labs/FcF-Inpainting), [Manga](https://github.com/msxie92/MangaInpainting) 模型以及 SPREAD 擦除方法。请查看链接了解各个模型的介绍。 +请下载模型文件 [lama models(百度网盘)](https://pan.baidu.com/s/1m7La2ELsSKaIFhQ57qg1XQ?pwd=jn10) 或者 [lama models(Google Drive)](https://drive.google.com/drive/folders/1Aq0a4sybb3SRxi7j1e1_ZbBRjaWDdP9e?usp=sharing), 将文件放到```ComfyUI/models/lama``` + +节点选项说明: +![image](image/lama_node.jpg) +* lama_model: 选择模型或方法。 +* device: 在正确安装torch和Nvidia CUDA驱动程序后,使用cuda将明显提高运行速度。 +* invert_mask: 是否反转遮罩。 +* grow: 遮罩扩张幅度。正值是向外扩张,负值是向内收缩。 +* blur: 遮罩模糊幅度。 + + +### ImageAutoCrop +![image](image/image_auto_crop_example.jpg) +自动抠图并按照遮罩裁切图片。可指定生成图片的背景颜色、长宽比和大小。这个节点是为生成训练模型的图片素材而设计的。 +*请参照 [SegmentAnythingUltra](#SegmentAnythingUltra) 和 [RemBgUltra](#RemBgUltra) 节点的模型安装方法安装模型。 + + +节点选项说明: +![image](image/image_auto_crop_node.jpg) +* background_color4: 背景颜色。 +* aspect_ratio: 输出的宽高比。这里提供了常见的画幅比例, "custom"为自定义比例。 +* proportional_width: 比例宽。如果aspect_ratio选项不是"custom",此处设置将被忽略。 +* proportional_height: 比例高。如果aspect_ratio选项不是"custom",此处设置将被忽略。 +* scale_by_longest_side: 允许按长边尺寸缩放。 +* longest_side: scale_by_longest_side被设置为True时,此项将作为是图像长边的长度。 +* detect: 探测方法,min_bounding_rect是最小外接矩形, max_inscribed_rect是最大内接矩形。 +* border_reserve: 保留边框。在探测到的遮罩主体区域之外扩展裁切范围。 +* ultra_detail_range: 遮罩边缘超精细处理范围,0为不处理,可以节省生成时间。 +* matting_method: 生成遮罩的方法。有Segment Anything和 RMBG 1.4两种方法。RMBG 1.4运行速度更快。 +* sam_model: 此处选择Segment Anything所使用的sam模型。 +* grounding_dino_model: 此处选择Segment Anything所使用的grounding_dino模型。 +* sam_threshold: Segment Anything的阈值。 +* sam_prompt: Segment Anything的提示词。 + +输出: +cropped_image: 裁切并更换背景后的图像。 +box_preview: 裁切位置预览。 +cropped_mask: 裁切后的遮罩。 + +### ImageAutoCropV2 + +```ImageAutoCrop```的V2升级版,在之前基础上做了如下改变: +![image](image/image_auto_crop_v2_node.jpg) + +* 增加```mask```可选输入。当有mask输入时,直接使用该输入跳过内置遮罩生成。 +* 增加```fill_background```, 当此项设置为False时将不处理背景,并且超出画幅的部分不纳入输出范围。 +* ```aspect_ratio```增加```original```(原始画面宽高比)选项。 +* scale_by: 允许按长边、短边、宽度或高度指定尺寸缩放。 +* scale_by_length: 这里的数值作为scale_by指定边的长度。 + +### ImageAutoCropV3 +自动裁切图片到指定的尺寸。可输入mask以保留遮罩指定的区域。这个节点是为生成训练模型的图片素材而设计的。 + + +节点选项说明: +![image](image/image_auto_crop_v3_node.jpg) +* image: 输入的图像。 +* mask: 可选输入遮罩。遮罩部分将在裁切长宽比例范围内得到保留。 +* aspect_ratio: 输出的宽高比。这里提供了常见的画幅比例, "custom"为自定义比例, "original"为原始画面比例。 +* proportional_width: 比例宽。如果aspect_ratio选项不是"custom",此处设置将被忽略。 +* proportional_height: 比例高。如果aspect_ratio选项不是"custom",此处设置将被忽略。 +* method: 缩放的采样方法,包括lanczos、bicubic、hamming、bilinear、box和nearest。 +* scale_to_side: 允许按长边、短边、宽度、高度或总像素指定尺寸缩放。 +* scale_to_length: 这里的数值作为scale_to_side指定边的长度, 或者总像素数量(kilo pixels)。 +* round_to_multiple: 倍数取整。例如设置为8,宽和高将强制设置为8的倍数。 + +输出: +cropped_image: 裁切后的图像。 +box_preview: 裁切位置预览。 + + +### SaveImagePlus +![image](image/saveimage_plus_example.jpg) +增强版的保存图片节点。可自定义保存图片的目录,文件名增加时间戳,选择保存格式,设置图片压缩率,设置是否保存工作流,以及可选给图片添加隐形水印(以肉眼无法觉察的方式添加信息,使用配套的```ShowBlindWaterMark```节点可以解码水印)。可选择是否同时输出工作流的json文件。 + +节点选项说明: +![image](image/saveimage_plus_node.jpg) +* iamge: 输入的图片。 +* custom_path*: 用户自定义目录,请按正确的格式输入目录名。如果为空则保存在ComfyUI默认的output目录。 +* filename_prefix*:文件名前缀。。 +* timestamp: 为文件名加上时间戳,可选择日期、时间到秒和时间到毫秒。 +* format:图片保存格式。目前提供png和jpg两种。注意RGBA模式的图片仅支持png格式。 +* quality:图片质量,数值范围10-100,数值越高,图片质量越好,文件的体积也对应增大。 +* meta_data:是否保存元数据即工作流信息到png文件。如果不希望泄露工作流,请把这里设置为false。 +* blind_watermark:这里输入的文字(不支持多语言)将被转换为二维码作为隐形水印保存,使用```ShowBlindWaterMark```节点可以解码水印。注意有水印的图片建议保存为png格式,质量较低的jpg格式将导致水印信息丢失。 +* save_workflow_as_json: 是否同时输出工作流为json文件(输出的json与图片在同一目录)。 +* preview: 预览开关。 + +*输入```%date```表示当前日期(YY-mm-dd),```%time```表示当前时间(HH-MM-SS)。可以输入```/```表示子目录。例如```%date/name_%time``` 将输出图片到```YY-mm-dd```文件夹下,以```name_HH-MM-SS```为文件名前缀。 + + +### AddBlindWaterMark +![image](image/watermark_example.jpg) +给图片添加隐形水印。以肉眼无法觉察的方式添加水印图片,使用```ShowBlindWaterMark```节点可以解码水印。 + +节点选项说明: +![image](image/add_blind_watermark_node.jpg) +* iamge: 输入的图片。 +* watermark_image: 水印图片。这里输入的图片将自动转为正方形的黑白图片作为水印。建议使用二维码作为水印。 + + +### ShowBlindWaterMark +对```AddBlindWaterMark``` 和 ```SaveImagePlus``` 节点添加的隐形水印解码。 +![image](image/show_blind_watermark_node.jpg) + + +### CreateQRCode +生成一个正方形的二维码图片。 + +节点选项说明: +![image](image/create_qrcode_node.jpg) +* size: 生成图片的边长。 +* border: 二维码四周边框的大小,数值越大,边框越宽。 +* text: 这里输入二维码文字内容,不支持多语言。 + +### DecodeQRCode +解码二维码。 + +节点选项说明: +![image](image/decode_qrcode_node.jpg) +* image: 输入二维码图片。 +* pre_blur: 预模糊,对难以识别的二维码可以尝试调整此数值。 + +### LoadPSD +![image](image/load_image_example_psd_file.jpg) +![image](image/load_image_example.jpg) +加载PSD格式文件,并导出图层。 +注意这个节点需要安装psd_tools依赖包,如果安装psd_tool中出现```ModuleNotFoundError: No module named 'docopt'```错误,请下载[docopt的whl](https://www.piwheels.org/project/docopt/)手动安装。 + +节点选项说明: +![image](image/load_image_node.jpg) +* image: 这里列出了```ComfyUI/input```下的*.psd文件,之前加载过的psd图片可以从这里选择。 +* file_path: psd文件的完整路径以及文件名。 +* include_hidden_layer: 是否包括隐藏图层。 +* find_layer_by: 查找图层的方法,可选择按图层索引编号或者图层名称查找。图层组被作为一个图层对待。 +* layer_index: 图层索引编号,0是最下面的图层,依次递增。如果include_hidden_layer设置为false,隐藏的图层不计入。设为-1则输出最上层的图层。 +* layer_name: 图层名称。注意大小写和标点符号必须完全匹配。 + +输出: +flat_image: psd预览图。 +layer_iamge: 查找的图层输出。 +all_layers: 包含全部图层的批量图片。 + +### SD3NegativeConditioning +![image](image/sd3_negative_conditioning_node_note.jpg) +把SD3的Negative Conditioning 的4个节点封装为一个单独节点。 + +节点选项说明: +![image](image/sd3_negative_conditioning_node.jpg) +* zero_out_start: 设置Negative ConditioningZeroOut的ConditioningSetTimestepRange start值, 此数值与Negative的ConditioningSetTimestepRange end值相同。 + + + +### SegmentAnythingUltra +对[ComfyUI Segment Anything](https://github.com/storyicon/comfyui_segment_anything)的改进,使遮罩有更具细节的边缘,感谢原作者。 +*请参照ComfyUI Segment Anything的安装方法安装模型。如果已经正确安装了ComfyUI Segment Anything,可跳过此步骤。 +* 从 [这里](https://huggingface.co/bert-base-uncased/tree/main) 下载 config.json,model.safetensors,tokenizer_config.json,tokenizer.json 和 vocab.txt 5个文件到 ```ComfyUI/models/bert-base-uncased```文件夹。 +* 下载 [GroundingDINO_SwinT_OGC config file](https://huggingface.co/ShilongLiu/GroundingDINO/resolve/main/GroundingDINO_SwinT_OGC.cfg.py), [GroundingDINO_SwinT_OGC model](https://huggingface.co/ShilongLiu/GroundingDINO/resolve/main/groundingdino_swint_ogc.pth), +[GroundingDINO_SwinB config file](https://huggingface.co/ShilongLiu/GroundingDINO/resolve/main/GroundingDINO_SwinB.cfg.py), [GroundingDINO_SwinB model](https://huggingface.co/ShilongLiu/GroundingDINO/resolve/main/groundingdino_swinb_cogcoor.pth) 到 ```ComfyUI/models/grounding-dino```文件夹。 +* 下载 [sam_vit_h](https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth),[sam_vit_l](https://dl.fbaipublicfiles.com/segment_anything/sam_vit_l_0b3195.pth), +[sam_vit_b](https://dl.fbaipublicfiles.com/segment_anything/sam_vit_b_01ec64.pth), [sam_hq_vit_h](https://huggingface.co/lkeab/hq-sam/resolve/main/sam_hq_vit_h.pth), +[sam_hq_vit_l](https://huggingface.co/lkeab/hq-sam/resolve/main/sam_hq_vit_l.pth), [sam_hq_vit_b](https://huggingface.co/lkeab/hq-sam/resolve/main/sam_hq_vit_b.pth), +[mobile_sam](https://github.com/ChaoningZhang/MobileSAM/blob/master/weights/mobile_sam.pt) 这几个文件到```ComfyUI/models/sams```文件夹。 +*或者从[GroundingDino模型百度网盘](https://pan.baidu.com/s/1P7WQDuaqSYazlSQX8SJjxw?pwd=24ki) 和 [SAM模型百度网盘](https://pan.baidu.com/s/1n7JrHb2vzV2K2z3ktqpNxg?pwd=yoqh) 下载它们。 + +![image](image/segment_anything_ultra_compare.jpg) +![image](image/segment_anything_ultra_example.jpg) + +节点选项说明: +![image](image/segment_anything_ultra_node.jpg) +* sam_model: 选择SAM模型。 +* ground_dino_model: 选择Grounding DINO模型。 +* threshold: SAM阈值。 +* detail_range: 边缘细节范围。 +* black_point: 边缘黑色采样阈值。 +* white_point: 边缘白色采样阈值。 +* process_detail: 此处设为False将跳过边缘处理以节省运行时间。 +* prompt: SAM的prompt输入。 +* cache_model: 是否缓存模型。 + +### SegmentAnythingUltraV2 +SegmentAnythingUltra的V2升级版,增加了VITMatte边缘处理方法。 +![image](image/ultra_v2_nodes_example.jpg) + +在SegmentAnythingUltra的基础上做了如下改变: +![image](image/segment_anything_ultra_v2_node.jpg) +* detail_method: 边缘处理方法。提供了VITMatte, VITMatte(local), PyMatting, GuidedFilter。 +* detail_erode: 遮罩边缘向内侵蚀范围。数值越大,向内修复的范围越大。 +* detail_dilate: 遮罩边缘向外扩张范围。数值越大,向外修复的范围越大。 +* device: 设置是否使用cuda。 +* max_megapixels: 设置vitmatte运算的最大尺寸。 + +### SAM2Ultra +本节点是[kijai/ComfyUI-segment-anything-2](https://github.com/kijai/ComfyUI-segment-anything-2)的改造版本。感谢[kijai](https://github.com/kijai)为ComfyUI社区做出的巨大贡献。 +SAM2 Ultra 节点仅支持单张图片,如果需要处理多张图片,请先将image batch 转换为 image list。 +*请从[百度网盘](https://pan.baidu.com/s/1xaQYBA6ktxvAxm310HXweQ?pwd=auki) 或者 [huggingface.co/Kijai/sam2-safetensors](https://huggingface.co/Kijai/sam2-safetensors/tree/main)下载全部模型文件并复制到```ComfyUI/models/sam2```文件夹。 + +![image](image/sam2_example.jpg) + +节点选项说明: +![image](image/sam2_ultra_node.jpg) + +* image: 图片输入。 +* bboxes: 识别框数据输入。 +* sam2_model: 选择SAM2模型。 +* presicion: 模型精度,可选择fp16, bf16 和 fp32。 +* bbox_select: 选择输入的框数据。有3个选项:"all"为全部选择,"first"为选择置信度最高的框,"by_index"可以指定框的索引。 +* select_index: 当bbox_select为"by_index"时,此选项有效。0为第一张。可以输入多个值,中间用任意非数字字符分隔,包括不仅限于逗号,句号,分号,空格或者字母,甚至中文。 +* cache_model: 是否缓存模型。缓存模型后将节省模型加载的时间。 +* detail_method: 边缘处理方法。提供了VITMatte, VITMatte(local), PyMatting, GuidedFilter。如果首次使用VITMatte后模型已经下载,之后可以使用VITMatte(local)。 +* detail_erode: 遮罩边缘向内侵蚀范围。数值越大,向内修复的范围越大。 +* detail_dilate: 遮罩边缘向外扩张范围。数值越大,向外修复的范围越大。 +* black_point: 边缘黑色采样阈值。 +* white_point: 边缘白色采样阈值。 +* process_detail: 此处设为False将跳过边缘处理以节省运行时间。 +* device: 设置是否使用cuda。 +* max_megapixels: 设置vitmatte运算的最大尺寸。 + +### SAM2VideoUltra +SAM2 Video Ultra 节点支持处理多张图片或视频序列帧。请在序列的第一帧定义识别框数据以保证正确识别。 + +https://github.com/user-attachments/assets/4726b8bf-9b98-4630-8f54-cb7ed7a3d2c5 + +https://github.com/user-attachments/assets/b2a45c96-4be1-4470-8ceb-addaf301b0cb + +节点选项说明: +![image](image/sam2_video_ultra_node.jpg) + +* image: 图片输入。 +* bboxes: 可选输入,识别框数据输入。bboxes 和 first_frame_mask 二者必须输入其中之一。如果有first_frame_mask输入,bboxes将被忽略。 +* first_frame_mask: 可选输入遮罩,这里的遮罩将作为首帧识别对象。bboxes 和 first_frame_mask 二者必须输入其中之一。如果有first_frame_mask输入,bboxes将被忽略。 +* pre_mask: 可选输入遮罩,这里的遮罩将作为传播关注范围限制,有助于提高识别准确度。 +* sam2_model: 选择SAM2模型。 +* presicion: 模型精度,可选择fp16, bf16。 +* cache_model: 是否缓存模型。缓存模型后将节省模型加载的时间。 +* individual_object: 当设置为 True时,将专注于识别单一对象。设置为False时,将尝试为多个对象生成识别框。 +* mask_preview_color: 在预览输出中显示非遮罩区域的颜色。 +* detail_method: 边缘处理方法。仅VITMatte可用。 +* detail_erode: 遮罩边缘向内侵蚀范围。数值越大,向内修复的范围越大。 +* detail_dilate: 遮罩边缘向外扩张范围。数值越大,向外修复的范围越大。 +* black_point: 边缘黑色采样阈值。 +* white_point: 边缘白色采样阈值。 +* process_detail: 此处设为False将跳过边缘处理以节省运行时间。 +* device: 本节点限制仅使用cuda。 +* max_megapixels: 设置vitmatte运算的最大尺寸。更大的尺寸将获得更精细的遮罩边缘,但会导致运算速度明显下降。 + +### ObjectDetectorFL2 +使用Florence2模型识别图片中的对象,并输出识别框数据。 +*请从 [百度网盘](https://pan.baidu.com/s/1hzw9-QiU1vB8pMbBgofZIA?pwd=mfl3)下载模型文件并复制到```ComfyUI/models/florence2```文件夹。 + +节点选项说明: +![image](image/object_detector_fl2_node.jpg) + +* image: 图片输入。 +* florence2_model: Florence2模型。从[Florence2模型加载器](#LoadFlorence2Model)输入。 +* prompt: 描述需要识别的对象。 +* sort_method: 选择框排序方法, 有4个选项:"left_to_right"为从左到右排序,"top_to_bottom"为从上到下排序,"big_to_small"为从大到小排序,"confidence"为按置信度排序。 +* bbox_select: 选择输入的框数据。有3个选项:"all"为全部选择,"first"为选择置信度最高的框,"by_index"可以指定框的索引。 +* select_index: 当bbox_select为"by_index"时,此选项有效。0为第一张。可以输入多个值,中间用任意非数字字符分隔,包括不仅限于逗号,句号,分号,空格或者字母,甚至中文。 + +### ObjectDetectorYOLOWorld (已废弃,如继续使用需要手动安装依赖包) + +由于依赖包安装易出问题,已废弃此节点。如需使用,请手动安装下列依赖包: +``` +pip install inference-cli>=0.13.0 +pip install inference-gpu[yolo-world]>=0.13.0 +``` + +使用YOLO World模型识别图片中的对象,并输出识别框数据。 +*请从 [百度网盘](https://pan.baidu.com/s/1QpjajeTA37vEAU2OQnbDcQ?pwd=nqsk) 或[GoogleDrive](https://drive.google.com/drive/folders/1nrsfq4S-yk9ewJgwrhXAoNVqIFLZ1at7?usp=sharing)下载模型文件并复制到```ComfyUI/models/yolo-world```文件夹。 + + +节点选项说明: +![image](image/object_detector_yolo_world_node.jpg) + +* image: 图片输入。 +* confidence_threshold: 置信度阈值。 +* nms_iou_threshold: 非极大值抑制阈值。 +* prompt: 描述需要识别的对象。 +* sort_method: 选择框排序方法, 有4个选项:"left_to_right"为从左到右排序,"top_to_bottom"为从上到下排序,"big_to_small"为从大到小排序,"confidence"为按置信度排序。 +* bbox_select: 选择输入的框数据。有3个选项:"all"为全部选择,"first"为选择置信度最高的框,"by_index"可以指定框的索引。 +* select_index: 当bbox_select为"by_index"时,此选项有效。0为第一张。可以输入多个值,中间用任意非数字字符分隔,包括不仅限于逗号,句号,分号,空格或者字母,甚至中文。 + +### ObjectDetectorYOLO8 +使用YOLO 8模型识别图片中的对象,并输出识别框数据。 +*请在 [GoogleDrive](https://drive.google.com/drive/folders/1I5TISO2G1ArSkKJu1O9b4Uvj3DVgn5d2) 或者 [百度网盘](https://pan.baidu.com/s/1pEY6sjABQaPs6QtpK0q6XA?pwd=grqe) 下载模型文件并放到 ```ComfyUI/models/yolo``` 文件夹。 + +节点选项说明: +![image](image/object_detector_yolo8_node.jpg) +* image: 图片输入。 +* yolo_model: 选择yolo模型。 +* sort_method: 选择框排序方法, 有4个选项:"left_to_right"为从左到右排序,"top_to_bottom"为从上到下排序,"big_to_small"为从大到小排序,"confidence"为按置信度排序。 +* bbox_select: 选择输入的框数据。有3个选项:"all"为全部选择,"first"为选择置信度最高的框,"by_index"可以指定框的索引。 +* select_index: 当bbox_select为"by_index"时,此选项有效。0为第一张。可以输入多个值,中间用任意非数字字符分隔,包括不仅限于逗号,句号,分号,空格或者字母,甚至中文。 + +### ObjectDetectorMask +使用遮罩作为识别框数据。遮罩上所有被白色区域包围的区域,将被识别为一个对象。多个封闭区域将各自识别。 + +节点选项说明: +![image](image/object_detector_mask_node.jpg) +* object_mask: 遮罩输入。 +* sort_method: 选择框排序方法, 有4个选项:"left_to_right"为从左到右排序,"top_to_bottom"为从上到下排序,"big_to_small"为从大到小排序,"confidence"为默认排序。 +* bbox_select: 选择输入的框数据。有3个选项:"all"为全部选择,"first"为选择置信度最高的框,"by_index"可以指定框的索引。 +* select_index: 当bbox_select为"by_index"时,此选项有效。0为第一张。可以输入多个值,中间用任意非数字字符分隔,包括不仅限于逗号,句号,分号,空格或者字母,甚至中文。 + +### BBoxJoin +合并识别框数据。 + +节点选项说明: +![image](image/bbox_join_node.jpg) +* bboxes_1: 必选输入。第一组识别框。 +* bboxes_2: 可选输入。第二组识别框。 +* bboxes_3: 可选输入。第三组识别框。 +* bboxes_4: 可选输入。第四组识别框。 + +### DrawBBoxMask +将ObjectDetector节点输出的识别框数据绘制为遮罩。 +![image](image/draw_bbox_mask_example.jpg) + +节点选项说明: +![image](image/draw_bbox_mask_node.jpg) +* image: 图片输入。必须与ObjectDetector节点识别的图片一致。 +* bboxes: 识别框数据输入。 +* grow_top: 每个识别框向上扩展范围,为识别框高度的百分比。正值为向上扩展,负值为向下扩展。 +* grow_bottom: 每个识别框向下扩展范围,为识别框高度的百分比,正值为向下扩展,负值为向上扩展。 +* grow_left: 每个识别框向左扩展范围,为识别框宽度的百分比。正值为向左扩展,负值为向右扩展。 +* grow_right: 每个识别框向右扩展范围,为识别框宽度的百分比。正值为向右扩展,负值为向左扩展。 + + +### EVF-SAMUltra +本节点是[EVF-SAM](https://github.com/hustvl/EVF-SAM)在ComfyUI中的实现。 +*请从[百度网盘](https://pan.baidu.com/s/1EvaxgKcCxUpMbYKzLnEx9w?pwd=69bn) 或者 [huggingface/EVF-SAM2](https://huggingface.co/YxZhang/evf-sam2/tree/main), [huggingface/EVF-SAM](https://huggingface.co/YxZhang/evf-sam/tree/main) 下载全部模型文件并复制到```ComfyUI/models/EVF-SAM```文件夹(请将模型保存在各自子目录中)。 + +![image](image/evf_sam_ultra_example.jpg) + +节点选项说明: +![image](image/evf_sam_ultra_node.jpg) + +* image: 图片输入。 +* model: 选择模型。目前有 evf-sam2 和 evf-sam 可选。 +* presicion: 模型精度,可选择fp16, bf16 和 fp32。 +* load_in_bit: 按位精度加载模型。可选择full, 8 和 4。 +* pormpt: 用于分割的提示词。 +* detail_method: 边缘处理方法。提供了VITMatte, VITMatte(local), PyMatting, GuidedFilter。如果首次使用VITMatte后模型已经下载,之后可以使用VITMatte(local)。 +* detail_erode: 遮罩边缘向内侵蚀范围。数值越大,向内修复的范围越大。 +* detail_dilate: 遮罩边缘向外扩张范围。数值越大,向外修复的范围越大。 +* black_point: 边缘黑色采样阈值。 +* white_point: 边缘白色采样阈值。 +* process_detail: 此处设为False将跳过边缘处理以节省运行时间。 +* device: 设置是否使用cuda。 +* max_megapixels: 设置vitmatte运算的最大尺寸。 + + +### Florence2Ultra +使用 Florence2 模型的分割功能,同时具有超高的边缘细节。 +本节点部分的代码来自[spacepxl/ComfyUI-Florence-2](https://github.com/spacepxl/ComfyUI-Florence-2),感谢原作者。 +*请从 [百度网盘](https://pan.baidu.com/s/1hzw9-QiU1vB8pMbBgofZIA?pwd=mfl3)下载模型文件并复制到```ComfyUI/models/florence2```文件夹。 + +![image](image/florence2_ultra_example.jpg) + +节点选项说明: +![image](image/florence2_ultra_node.jpg) +* florence2_model: Florence2模型输入。 +* image: 图片输入。 +* task: 选择florence2任务。 +* text_input: florence2任务文本输入。 +* detail_method: 边缘处理方法。提供了VITMatte, VITMatte(local), PyMatting, GuidedFilter。如果首次使用VITMatte后模型已经下载,之后可以使用VITMatte(local)。 +* detail_erode: 遮罩边缘向内侵蚀范围。数值越大,向内修复的范围越大。 +* detail_dilate: 遮罩边缘向外扩张范围。数值越大,向外修复的范围越大。 +* black_point: 边缘黑色采样阈值。 +* white_point: 边缘白色采样阈值。 +* process_detail: 此处设为False将跳过边缘处理以节省运行时间。 +* device: 设置是否使用cuda。 +* max_megapixels: 设置vitmatte运算的最大尺寸。 + +### LoadFlorence2Model +Florence2 模型加载器。 +![image](image/load_florence2_model_node.jpg) +目前有 base, base-ft, large, large-ft, DocVQA, SD3-Captioner 和 base-PromptGen模型可以选择。 + + +### BiRefNetUltra +使用BiRefNet模型去除背景,有更好的识别能力,同时具有超高的边缘细节。 +本节点模型部分的代码来自vipery的[ComfyUI-BiRefNet](https://github.com/viperyl/ComfyUI-BiRefNet),感谢原作者。 + +*从[https://huggingface.co/ViperYX/BiRefNet](https://huggingface.co/ViperYX/BiRefNet/tree/main) 或者 [百度网盘](https://pan.baidu.com/s/1GxtuNDTIHkuu4FR4uGAT-g?pwd=t2cf) 下载```BiRefNet-ep480.pth```,```pvt_v2_b2.pth```,```pvt_v2_b5.pth```,```swin_base_patch4_window12_384_22kto1k.pth```, ```swin_large_patch4_window12_384_22kto1k.pth```5个文件至```ComfyUI/models/BiRefNet```文件夹。 + +![image](image/birefnet_ultra_example.jpg) + +节点选项说明: +![image](image/birefnet_ultra_node.jpg) +* detail_method: 边缘处理方法。提供了VITMatte, VITMatte(local), PyMatting, GuidedFilter。如果首次使用VITMatte后模型已经下载,之后可以使用VITMatte(local)。 +* detail_erode: 遮罩边缘向内侵蚀范围。数值越大,向内修复的范围越大。 +* detail_dilate: 遮罩边缘向外扩张范围。数值越大,向外修复的范围越大。 +* black_point: 边缘黑色采样阈值。 +* white_point: 边缘白色采样阈值。 +* process_detail: 此处设为False将跳过边缘处理以节省运行时间。 +* device: 设置是否使用cuda。 +* max_megapixels: 设置vitmatte运算的最大尺寸。 + + +### BiRefNetUltraV2 +本节点支持使用最新的BiRefNet模型。 +*从[百度网盘](https://pan.baidu.com/s/12z3qUuqag3nqpN2NJ5pSzg?pwd=ek65) 或 [GoogleDrive](https://drive.google.com/drive/folders/1s2Xe0cjq-2ctnJBR24563yMSCOu4CcxM) 下载 ```BiRefNet-general-epoch_244.pth``` 到 ```ComfyUI/Models/BiRefNet/pth``` 文件夹。也可以下载更多的BiRefNet模型放到这里。 + +![image](image/birefnet_ultra_v2_example.jpg) + +节点选项说明: +![image](image/birefnet_ultra_v2_node.jpg) + +* image: 图片输入。 +* birefnet_model: BiRefNet模型输入,模型从LoadBiRefNetModel节点输出。 +* detail_method: 边缘处理方法。提供了VITMatte, VITMatte(local), PyMatting, GuidedFilter。如果首次使用VITMatte后模型已经下载,之后可以使用VITMatte(local)。 +* detail_erode: 遮罩边缘向内侵蚀范围。数值越大,向内修复的范围越大。 +* detail_dilate: 遮罩边缘向外扩张范围。数值越大,向外修复的范围越大。 +* black_point: 边缘黑色采样阈值。 +* white_point: 边缘白色采样阈值。 +* process_detail: 由于BiRefNet的边缘处理已经非常不错,此处默认设为False。 +* device: 设置是否使用cuda。 +* max_megapixels: 设置vitmatte运算的最大尺寸。 + + +### LoadBiRefNetModel +加载BiRefNet模型。 + + +节点选项说明: +![image](image/load_birefnet_model_node.jpg) + +* model: 选择模型。列出 ```CoomfyUI/models/BiRefNet/pth``` 文件夹下的文件供选择。 + +### LoadBiRefNetModelV2 +本节点是[jimlee2048](https://github.com/jimlee2048)提交的PR,支持加载RMBG-2.0模型。 +从 [huggingface](https://huggingface.co/briaai/RMBG-2.0/tree/main) 或 [百度网盘](https://pan.baidu.com/s/1viIXlZnpTYTKkm2F-QMj_w?pwd=axr9) 下载全部文件并复制到```ComfyUI/models/BiRefNet/RMBG-2.0```文件夹。 + +节点选项说明: +![image](image/load_birefnet_model_v2_node.jpg) + +* model: 选择模型。有两个选项: ```BiRefNet-General``` 和 ```RMBG-2.0```。 + + + +### TransparentBackgroundUltra +使用transparent-background模型去除背景,有更好的识别能力和识别速度,同时具有超高的边缘细节。 + +*从 [googledrive](https://drive.google.com/drive/folders/10KBDY19egb8qEQBv34cqIVSwd38bUAa9?usp=sharing) 或 [百度网盘](https://pan.baidu.com/s/10JO0uKzTxJaIkhN_J7RSyw?pwd=v0b0) 下载全部文件至```ComfyUI/models/transparent-background```文件夹。 + +![image](image/transparent_background_ultra_example.jpg) + +节点选项说明: +![image](image/transparent_background_ultra_node.jpg) +* model: 选择模型。 +* detail_method: 边缘处理方法。提供了VITMatte, VITMatte(local), PyMatting, GuidedFilter。如果首次使用VITMatte后模型已经下载,之后可以使用VITMatte(local)。 +* detail_erode: 遮罩边缘向内侵蚀范围。数值越大,向内修复的范围越大。 +* detail_dilate: 遮罩边缘向外扩张范围。数值越大,向外修复的范围越大。 +* black_point: 边缘黑色采样阈值。 +* white_point: 边缘白色采样阈值。 +* process_detail: 此处设为False将跳过边缘处理以节省运行时间。 +* device: 设置是否使用cuda。 +* max_megapixels: 设置vitmatte运算的最大尺寸。 + +### PersonMaskUltra +为人物生成脸、头发、身体皮肤、衣服或配饰的遮罩。与之前的A Person Mask Generator节点相比,这个节点具有超高的边缘细节。 +本节点的模型代码来自[a-person-mask-generator](https://github.com/djbielejeski/a-person-mask-generator),边缘处理代码来自spacepxl的[ComfyUI-Image-Filters](https://github.com/spacepxl/ComfyUI-Image-Filters),感谢原作者。 +*从[百度网盘](https://pan.baidu.com/s/13zqZtBt89ueCyFufzUlcDg?pwd=jh5g) 下载模型文件并放到```ComfyUI/models/mediapipe```文件夹。 + +![image](image/person_mask_ultra_example.jpg) + +节点选项说明: +![image](image/person_mask_ultra_node.jpg) +* face: 脸部识别。 +* hair: 头发识别。 +* body: 身体皮肤识别。 +* clothes: 衣服识别。 +* accessories: 配饰(例如背包)识别。 +* background: 背景识别。 +* confidence: 识别阈值,更低的值将输出更多的遮罩范围。 +* detail_range: 边缘细节范围。 +* black_point: 边缘黑色采样阈值。 +* white_point: 边缘白色采样阈值。 +* process_detail: 此处设为False将跳过边缘处理以节省运行时间。 + +### PersonMaskUltraV2 +PersonMaskUltra的V2升级版,增加了VITMatte边缘处理方法。 + +在PersonMaskUltra的基础上做了如下改变: +![image](image/person_mask_ultra_v2_node.jpg) +* detail_method: 边缘处理方法。提供了VITMatte, VITMatte(local), PyMatting, GuidedFilter。如果首次使用VITMatte后模型已经下载,之后可以使用VITMatte(local)。 +* detail_erode: 遮罩边缘向内侵蚀范围。数值越大,向内修复的范围越大。 +* detail_dilate: 遮罩边缘向外扩张范围。数值越大,向外修复的范围越大。 +* device: 设置是否使用cuda。 +* max_megapixels: 设置vitmatte运算的最大尺寸。 + + +### HumanPartsUltra +用于分割人体肢体,是基于[metal3d/ComfyUI_Human_Parts](https://github.com/metal3d/ComfyUI_Human_Parts) 的重新封装,感谢原作者。 +本节点在原作基础上增加了超精细边缘处理。请从[百度网盘](https://pan.baidu.com/s/1-6uwH6RB0FhIVfa3qO7hhQ?pwd=d862) 或 [huggingface](https://huggingface.co/Metal3d/deeplabv3p-resnet50-human/tree/main) 下载模型文件并复制到 ```ComfyUI\models\onnx\human-parts``` 文件夹。 +![image](image/human_parts_ultra_example.jpg) + +节点选项说明: +![image](image/human_parts_node.jpg) + +* image: 图片输入。 +* face: 是否识别人脸。 +* hair: 是否识别头发。 +* galsses: 是否识别眼镜。 +* top_clothes: 是否识别上装。 +* bottom_clothes: 是否识别下装。 +* torso_skin: 是否识别躯干皮肤。 +* left_arm: 是否识别左手臂。 +* right_arm: 是否识别右手臂。 +* left_leg: 是否识别左腿。 +* right_leg: 是否识别右腿。 +* left_foot: 是否识别左脚。 +* right_foot: 是否识别右脚。 +* detail_method: 边缘处理方法。提供了VITMatte, VITMatte(local), PyMatting, GuidedFilter。如果首次使用VITMatte后模型已经下载,之后可以使用VITMatte(local)。 +* detail_erode: 遮罩边缘向内侵蚀范围。数值越大,向内修复的范围越大。 +* detail_dilate: 遮罩边缘向外扩张范围。数值越大,向外修复的范围越大。 +* black_point: 边缘黑色采样阈值。 +* white_point: 边缘白色采样阈值。 +* process_detail: 此处设为False将跳过边缘处理以节省运行时间。 +* device: 设置是否使用cuda。 +* max_megapixels: 设置vitmatte运算的最大尺寸。 + + +### YoloV8Detect +使用YoloV8模型检测人脸、手部box区域,或者人物分割。支持输出所选择数量的通道。 +请在 [GoogleDrive](https://drive.google.com/drive/folders/1I5TISO2G1ArSkKJu1O9b4Uvj3DVgn5d2) 或者 [百度网盘](https://pan.baidu.com/s/1pEY6sjABQaPs6QtpK0q6XA?pwd=grqe) 下载模型文件并放到 ```ComfyUI/models/yolo``` 文件夹。 + +![image](image/yolov8_detect_example.jpg) + +节点选项说明: +![image](image/yolov8_detect_node.jpg) +* yolo_model: yolo模型选择。带有```seg```名字的模型可以输出分割的mask, 否则只能输出box区域的遮罩。 +* mask_merge: 选择合并的遮罩。```all```是合并全部遮罩输出。选数值是输出多少个遮罩,按识别置信度排序合并输出。 + +输出: +* mask: 输出的遮罩。 +* yolo_plot_image: yolo识别结果预览图。 +* yolo_masks: yolo识别出来的所有遮罩,每个单独的遮罩输出为一个mask。 + + +### MediapipeFacialSegment +使用Mediapipe模型检测人脸五官,分割左右眉、眼睛、嘴唇和牙齿。 +*从[百度网盘](https://pan.baidu.com/s/13zqZtBt89ueCyFufzUlcDg?pwd=jh5g) 下载模型文件并放到```ComfyUI/models/mediapipe```文件夹。 + +![image](image/mediapipe_facial_segment_example.jpg) + +节点选项说明: +![image](image/mediapipe_facial_segment_node.jpg) +* left_eye: 左眼识别开关。 +* left_eyebrow: 左眉识别开关。 +* right_eye: 右眼识别开关。 +* right_eyebrow: 右眉识别开关。 +* lips: 嘴唇识别开关。 +* tooth: 牙齿识别开关。 + + +### MaskByDifferent +计算两张图像不同之处,并输出为遮罩。 +![image](image/mask_by_different_example.jpg) + +节点选项说明: +![image](image/mask_by_different_node.jpg) +* gain: 计算增益。调高此值,微弱的差异将更显著的呈现。 +* fix_gap: 修补遮罩内部缝隙。更高的值将修补更大的缝隙。 +* fix_threshold: 修补阈值。 +* main_subject_detect: 此项设为True将开启主体侦测,忽略主体之外的差异。 + + + +## 节点注解 +1 image、mask和background_image(如果有输入)这三项必须是相同的尺寸。 + +2 mask不是必须的输入项,默认使用image的alpha通道,如果image输入不包含alpha通道将自动创建整个图像的alpha通道。如果输入mask,原本的alpha通道将被mask覆盖。 + +3 混合模式 包括normal、multply、screen、add、subtract、difference、darker、lighter、color_burn、color_dodge、linear_burn、linear_dodge、overlay、soft_light、hard_light、vivid_light、pin_light、linear_light、hard_mix, 共19种混合模式。 +![image](image/blend_mode_result.jpg) +*混合模式预览
+ + +3 混合模式V2 包括nomal, dissolve, darken, multiply, color burn, linear burn, darker color, lighten, screen, color dodge, linear dodge(add), lighter color, dodge, overlay, soft light, hard light, vivid light, linear light, pin light, hard mix, difference, exclusion, subtract, divide, hue, saturation, color, luminosity, grain extract, grain merge共30种模式。 +混合模式V2的部分代码来自[Virtuoso Nodes for ComfyUI](https://github.com/chrisfreilich/virtuoso-nodes)的```Blend Modes```节点。感谢原作者。 +![image](image/blend_mode_v2_example.jpg) +*混合模式V2版预览
+ +4 颜色使用16进制RGB字符串格式描述,例如 '#FA3D86'。 + +5 image和mask这两项必须是相同的尺寸。 + +## Star 记录 + +[![Star History Chart](https://api.star-history.com/svg?repos=chflame163/ComfyUI_LayerStyle_Advance&type=Date)](https://star-history.com/#chflame163/ComfyUI_LayerStyle_Advance&Date) + +## 声明 +LayerStyle Advance节点遵照MIT开源协议,有部分功能代码和模型来自其他开源项目,感谢原作者。如果作为商业用途,请查阅原项目授权协议使用。 diff --git a/__init__.py b/__init__.py new file mode 100644 index 0000000..cec1e3d --- /dev/null +++ b/__init__.py @@ -0,0 +1,53 @@ +import importlib.util +import os +import sys +import json + +NODE_CLASS_MAPPINGS = {} +NODE_DISPLAY_NAME_MAPPINGS = {} + +python = sys.executable + +def get_ext_dir(subpath=None, mkdir=False): + dir = os.path.dirname(__file__) + if subpath is not None: + dir = os.path.join(dir, subpath) + + dir = os.path.abspath(dir) + + if mkdir and not os.path.exists(dir): + os.makedirs(dir) + return dir + +def serialize(obj): + if isinstance(obj, (str, int, float, bool, list, dict, type(None))): + return obj + return str(obj) # 转为字符串 + + +py = get_ext_dir("py") +files = os.listdir(py) +all_nodes = {} +for file in files: + if not file.endswith(".py"): + continue + name = os.path.splitext(file)[0] + imported_module = importlib.import_module(".py.{}".format(name), __name__) + try: + NODE_CLASS_MAPPINGS = {**NODE_CLASS_MAPPINGS, **imported_module.NODE_CLASS_MAPPINGS} + NODE_DISPLAY_NAME_MAPPINGS = {**NODE_DISPLAY_NAME_MAPPINGS, **imported_module.NODE_DISPLAY_NAME_MAPPINGS} + serialized_CLASS_MAPPINGS = {k: serialize(v) for k, v in imported_module.NODE_CLASS_MAPPINGS.items()} + serialized_DISPLAY_NAME_MAPPINGS = {k: serialize(v) for k, v in imported_module.NODE_DISPLAY_NAME_MAPPINGS.items()} + all_nodes[file]={"NODE_CLASS_MAPPINGS": serialized_CLASS_MAPPINGS, "NODE_DISPLAY_NAME_MAPPINGS": serialized_DISPLAY_NAME_MAPPINGS} + except: + pass + + +# 保存为文件 +with open("all_nodes.json", "w", encoding="utf-8") as f: + json.dump(all_nodes, f, ensure_ascii=False, indent=4) + + +WEB_DIRECTORY = "./js" + +__all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS", "WEB_DIRECTORY"] diff --git a/api_key.ini.example b/api_key.ini.example new file mode 100644 index 0000000..3ed1f43 --- /dev/null +++ b/api_key.ini.example @@ -0,0 +1,2 @@ +# LayerStyle api_key +google_api_key= \ No newline at end of file diff --git a/custom_size.ini.example b/custom_size.ini.example new file mode 100644 index 0000000..fc8de0c --- /dev/null +++ b/custom_size.ini.example @@ -0,0 +1,10 @@ +# LayerStyle Custom_size +1024 x 1024 +768 x 512 +512 x 768 +1280 x 720 +720 x 1280 +1344 x 768 +768 x 1344 +1536 x 640 +640 x 1536 diff --git a/font/Alibaba-PuHuiTi-Heavy.ttf b/font/Alibaba-PuHuiTi-Heavy.ttf new file mode 100644 index 0000000..7eb047f Binary files /dev/null and b/font/Alibaba-PuHuiTi-Heavy.ttf differ diff --git a/image/add_blind_watermark_node.jpg b/image/add_blind_watermark_node.jpg new file mode 100644 index 0000000..f2c95fb Binary files /dev/null and b/image/add_blind_watermark_node.jpg differ diff --git a/image/bbox_join_node.jpg b/image/bbox_join_node.jpg new file mode 100644 index 0000000..c80cbb1 Binary files /dev/null and b/image/bbox_join_node.jpg differ diff --git a/image/birefnet_ultra_example.jpg b/image/birefnet_ultra_example.jpg new file mode 100644 index 0000000..7ec3f83 Binary files /dev/null and b/image/birefnet_ultra_example.jpg differ diff --git a/image/birefnet_ultra_node.jpg b/image/birefnet_ultra_node.jpg new file mode 100644 index 0000000..b5f69f9 Binary files /dev/null and b/image/birefnet_ultra_node.jpg differ diff --git a/image/birefnet_ultra_v2_example.jpg b/image/birefnet_ultra_v2_example.jpg new file mode 100644 index 0000000..c424fe7 Binary files /dev/null and b/image/birefnet_ultra_v2_example.jpg differ diff --git a/image/birefnet_ultra_v2_node.jpg b/image/birefnet_ultra_v2_node.jpg new file mode 100644 index 0000000..4c95748 Binary files /dev/null and b/image/birefnet_ultra_v2_node.jpg differ diff --git a/image/blend_mode_result.jpg b/image/blend_mode_result.jpg new file mode 100644 index 0000000..732d7b8 Binary files /dev/null and b/image/blend_mode_result.jpg differ diff --git a/image/blend_mode_v2_example.jpg b/image/blend_mode_v2_example.jpg new file mode 100644 index 0000000..b2fbaad Binary files /dev/null and b/image/blend_mode_v2_example.jpg differ diff --git a/image/create_qrcode_node.jpg b/image/create_qrcode_node.jpg new file mode 100644 index 0000000..87d1a17 Binary files /dev/null and b/image/create_qrcode_node.jpg differ diff --git a/image/data_nodes_example.jpg b/image/data_nodes_example.jpg new file mode 100644 index 0000000..6995c09 Binary files /dev/null and b/image/data_nodes_example.jpg differ diff --git a/image/decode_qrcode_node.jpg b/image/decode_qrcode_node.jpg new file mode 100644 index 0000000..569814d Binary files /dev/null and b/image/decode_qrcode_node.jpg differ diff --git a/image/draw_bbox_mask_example.jpg b/image/draw_bbox_mask_example.jpg new file mode 100644 index 0000000..a478112 Binary files /dev/null and b/image/draw_bbox_mask_example.jpg differ diff --git a/image/draw_bbox_mask_node.jpg b/image/draw_bbox_mask_node.jpg new file mode 100644 index 0000000..cf008a3 Binary files /dev/null and b/image/draw_bbox_mask_node.jpg differ diff --git a/image/evf_sam_ultra_example.jpg b/image/evf_sam_ultra_example.jpg new file mode 100644 index 0000000..ed747af Binary files /dev/null and b/image/evf_sam_ultra_example.jpg differ diff --git a/image/evf_sam_ultra_node.jpg b/image/evf_sam_ultra_node.jpg new file mode 100644 index 0000000..e45626d Binary files /dev/null and b/image/evf_sam_ultra_node.jpg differ diff --git a/image/florence2_image2prompt_example.jpg b/image/florence2_image2prompt_example.jpg new file mode 100644 index 0000000..eedca22 Binary files /dev/null and b/image/florence2_image2prompt_example.jpg differ diff --git a/image/florence2_image2prompt_node.jpg b/image/florence2_image2prompt_node.jpg new file mode 100644 index 0000000..99b5b50 Binary files /dev/null and b/image/florence2_image2prompt_node.jpg differ diff --git a/image/florence2_ultra_example.jpg b/image/florence2_ultra_example.jpg new file mode 100644 index 0000000..737c9cf Binary files /dev/null and b/image/florence2_ultra_example.jpg differ diff --git a/image/florence2_ultra_node.jpg b/image/florence2_ultra_node.jpg new file mode 100644 index 0000000..06e9e3d Binary files /dev/null and b/image/florence2_ultra_node.jpg differ diff --git a/image/get_color_tone_example.jpg b/image/get_color_tone_example.jpg new file mode 100644 index 0000000..a3dbaad Binary files /dev/null and b/image/get_color_tone_example.jpg differ diff --git a/image/get_color_tone_node.jpg b/image/get_color_tone_node.jpg new file mode 100644 index 0000000..197dc95 Binary files /dev/null and b/image/get_color_tone_node.jpg differ diff --git a/image/get_color_tone_v2_example.jpg b/image/get_color_tone_v2_example.jpg new file mode 100644 index 0000000..15ffef1 Binary files /dev/null and b/image/get_color_tone_v2_example.jpg differ diff --git a/image/get_color_tone_v2_example2.jpg b/image/get_color_tone_v2_example2.jpg new file mode 100644 index 0000000..606ebc9 Binary files /dev/null and b/image/get_color_tone_v2_example2.jpg differ diff --git a/image/get_color_tone_v2_node.jpg b/image/get_color_tone_v2_node.jpg new file mode 100644 index 0000000..5f656a9 Binary files /dev/null and b/image/get_color_tone_v2_node.jpg differ diff --git a/image/human_parts_node.jpg b/image/human_parts_node.jpg new file mode 100644 index 0000000..efcc868 Binary files /dev/null and b/image/human_parts_node.jpg differ diff --git a/image/human_parts_ultra_example.jpg b/image/human_parts_ultra_example.jpg new file mode 100644 index 0000000..578122f Binary files /dev/null and b/image/human_parts_ultra_example.jpg differ diff --git a/image/image_auto_crop_example.jpg b/image/image_auto_crop_example.jpg new file mode 100644 index 0000000..59377b9 Binary files /dev/null and b/image/image_auto_crop_example.jpg differ diff --git a/image/image_auto_crop_node.jpg b/image/image_auto_crop_node.jpg new file mode 100644 index 0000000..d3d2f83 Binary files /dev/null and b/image/image_auto_crop_node.jpg differ diff --git a/image/image_auto_crop_v2_node.jpg b/image/image_auto_crop_v2_node.jpg new file mode 100644 index 0000000..8420c78 Binary files /dev/null and b/image/image_auto_crop_v2_node.jpg differ diff --git a/image/image_auto_crop_v3_node.jpg b/image/image_auto_crop_v3_node.jpg new file mode 100644 index 0000000..4bd1683 Binary files /dev/null and b/image/image_auto_crop_v3_node.jpg differ diff --git a/image/image_reward_filter_example.jpg b/image/image_reward_filter_example.jpg new file mode 100644 index 0000000..1024b3e Binary files /dev/null and b/image/image_reward_filter_example.jpg differ diff --git a/image/image_reward_filter_node.jpg b/image/image_reward_filter_node.jpg new file mode 100644 index 0000000..8de28f8 Binary files /dev/null and b/image/image_reward_filter_node.jpg differ diff --git a/image/joycaption2_example.jpg b/image/joycaption2_example.jpg new file mode 100644 index 0000000..433c5fb Binary files /dev/null and b/image/joycaption2_example.jpg differ diff --git a/image/joycaption2_extra_options_node.jpg b/image/joycaption2_extra_options_node.jpg new file mode 100644 index 0000000..879cfe5 Binary files /dev/null and b/image/joycaption2_extra_options_node.jpg differ diff --git a/image/joycaption2_node.jpg b/image/joycaption2_node.jpg new file mode 100644 index 0000000..fc817b3 Binary files /dev/null and b/image/joycaption2_node.jpg differ diff --git a/image/joycaption2_split_node.jpg b/image/joycaption2_split_node.jpg new file mode 100644 index 0000000..4eccf6f Binary files /dev/null and b/image/joycaption2_split_node.jpg differ diff --git a/image/lama_example.jpg b/image/lama_example.jpg new file mode 100644 index 0000000..68f9e5e Binary files /dev/null and b/image/lama_example.jpg differ diff --git a/image/lama_node.jpg b/image/lama_node.jpg new file mode 100644 index 0000000..a870081 Binary files /dev/null and b/image/lama_node.jpg differ diff --git a/image/light_leak_example.jpg b/image/light_leak_example.jpg new file mode 100644 index 0000000..bff5535 Binary files /dev/null and b/image/light_leak_example.jpg differ diff --git a/image/light_leak_node.jpg b/image/light_leak_node.jpg new file mode 100644 index 0000000..597e1dd Binary files /dev/null and b/image/light_leak_node.jpg differ diff --git a/image/llama_vision_example.jpg b/image/llama_vision_example.jpg new file mode 100644 index 0000000..141f563 Binary files /dev/null and b/image/llama_vision_example.jpg differ diff --git a/image/llama_vision_node.jpg b/image/llama_vision_node.jpg new file mode 100644 index 0000000..bb78416 Binary files /dev/null and b/image/llama_vision_node.jpg differ diff --git a/image/load_ben_model_node.jpg b/image/load_ben_model_node.jpg new file mode 100644 index 0000000..95d0dc7 Binary files /dev/null and b/image/load_ben_model_node.jpg differ diff --git a/image/load_birefnet_model_node.jpg b/image/load_birefnet_model_node.jpg new file mode 100644 index 0000000..d9500f2 Binary files /dev/null and b/image/load_birefnet_model_node.jpg differ diff --git a/image/load_birefnet_model_v2_node.jpg b/image/load_birefnet_model_v2_node.jpg new file mode 100644 index 0000000..1b63f0f Binary files /dev/null and b/image/load_birefnet_model_v2_node.jpg differ diff --git a/image/load_florence2_model_node.jpg b/image/load_florence2_model_node.jpg new file mode 100644 index 0000000..a6b6ffb Binary files /dev/null and b/image/load_florence2_model_node.jpg differ diff --git a/image/load_image_example.jpg b/image/load_image_example.jpg new file mode 100644 index 0000000..c132eb1 Binary files /dev/null and b/image/load_image_example.jpg differ diff --git a/image/load_image_example_psd_file.jpg b/image/load_image_example_psd_file.jpg new file mode 100644 index 0000000..3bf4464 Binary files /dev/null and b/image/load_image_example_psd_file.jpg differ diff --git a/image/load_image_node.jpg b/image/load_image_node.jpg new file mode 100644 index 0000000..b12cc2b Binary files /dev/null and b/image/load_image_node.jpg differ diff --git a/image/load_joycaption2_model_node.jpg b/image/load_joycaption2_model_node.jpg new file mode 100644 index 0000000..7b6ae05 Binary files /dev/null and b/image/load_joycaption2_model_node.jpg differ diff --git a/image/mask_by_different_example.jpg b/image/mask_by_different_example.jpg new file mode 100644 index 0000000..f114ce4 Binary files /dev/null and b/image/mask_by_different_example.jpg differ diff --git a/image/mask_by_different_node.jpg b/image/mask_by_different_node.jpg new file mode 100644 index 0000000..489db5d Binary files /dev/null and b/image/mask_by_different_node.jpg differ diff --git a/image/mediapipe_facial_segment_example.jpg b/image/mediapipe_facial_segment_example.jpg new file mode 100644 index 0000000..46561cb Binary files /dev/null and b/image/mediapipe_facial_segment_example.jpg differ diff --git a/image/mediapipe_facial_segment_node.jpg b/image/mediapipe_facial_segment_node.jpg new file mode 100644 index 0000000..8f5b2d6 Binary files /dev/null and b/image/mediapipe_facial_segment_node.jpg differ diff --git a/image/node-menu.jpg b/image/node-menu.jpg new file mode 100644 index 0000000..8edcf7f Binary files /dev/null and b/image/node-menu.jpg differ diff --git a/image/node-search.jpg b/image/node-search.jpg new file mode 100644 index 0000000..47ac217 Binary files /dev/null and b/image/node-search.jpg differ diff --git a/image/object_detector_fl2_node.jpg b/image/object_detector_fl2_node.jpg new file mode 100644 index 0000000..b8e28fe Binary files /dev/null and b/image/object_detector_fl2_node.jpg differ diff --git a/image/object_detector_mask_node.jpg b/image/object_detector_mask_node.jpg new file mode 100644 index 0000000..bb03ce5 Binary files /dev/null and b/image/object_detector_mask_node.jpg differ diff --git a/image/object_detector_yolo8_node.jpg b/image/object_detector_yolo8_node.jpg new file mode 100644 index 0000000..5a9ce4f Binary files /dev/null and b/image/object_detector_yolo8_node.jpg differ diff --git a/image/object_detector_yolo_world_node.jpg b/image/object_detector_yolo_world_node.jpg new file mode 100644 index 0000000..a2ef02a Binary files /dev/null and b/image/object_detector_yolo_world_node.jpg differ diff --git a/image/outer_glow_example.jpg b/image/outer_glow_example.jpg new file mode 100644 index 0000000..2955587 Binary files /dev/null and b/image/outer_glow_example.jpg differ diff --git a/image/person_mask_ultra_example.jpg b/image/person_mask_ultra_example.jpg new file mode 100644 index 0000000..a5f7645 Binary files /dev/null and b/image/person_mask_ultra_example.jpg differ diff --git a/image/person_mask_ultra_node.jpg b/image/person_mask_ultra_node.jpg new file mode 100644 index 0000000..4f4773e Binary files /dev/null and b/image/person_mask_ultra_node.jpg differ diff --git a/image/person_mask_ultra_v2_node.jpg b/image/person_mask_ultra_v2_node.jpg new file mode 100644 index 0000000..ec2ce54 Binary files /dev/null and b/image/person_mask_ultra_v2_node.jpg differ diff --git a/image/phi_prompt_example.jpg b/image/phi_prompt_example.jpg new file mode 100644 index 0000000..5d420ed Binary files /dev/null and b/image/phi_prompt_example.jpg differ diff --git a/image/phi_prompt_node.jpg b/image/phi_prompt_node.jpg new file mode 100644 index 0000000..5325b9e Binary files /dev/null and b/image/phi_prompt_node.jpg differ diff --git a/image/prompt_embellish_example.jpg b/image/prompt_embellish_example.jpg new file mode 100644 index 0000000..e65d18f Binary files /dev/null and b/image/prompt_embellish_example.jpg differ diff --git a/image/prompt_embellish_node.jpg b/image/prompt_embellish_node.jpg new file mode 100644 index 0000000..b8ca5dc Binary files /dev/null and b/image/prompt_embellish_node.jpg differ diff --git a/image/prompt_tagger_example.jpg b/image/prompt_tagger_example.jpg new file mode 100644 index 0000000..1dd9727 Binary files /dev/null and b/image/prompt_tagger_example.jpg differ diff --git a/image/prompt_tagger_example1.jpg b/image/prompt_tagger_example1.jpg new file mode 100644 index 0000000..07d1d9f Binary files /dev/null and b/image/prompt_tagger_example1.jpg differ diff --git a/image/prompt_tagger_node.jpg b/image/prompt_tagger_node.jpg new file mode 100644 index 0000000..dde7564 Binary files /dev/null and b/image/prompt_tagger_node.jpg differ diff --git a/image/qwen_image2prompt_example.jpg b/image/qwen_image2prompt_example.jpg new file mode 100644 index 0000000..99f84bb Binary files /dev/null and b/image/qwen_image2prompt_example.jpg differ diff --git a/image/sam2_example.jpg b/image/sam2_example.jpg new file mode 100644 index 0000000..9d47627 Binary files /dev/null and b/image/sam2_example.jpg differ diff --git a/image/sam2_ultra_node.jpg b/image/sam2_ultra_node.jpg new file mode 100644 index 0000000..0dfbaf8 Binary files /dev/null and b/image/sam2_ultra_node.jpg differ diff --git a/image/sam2_video_ultra_node.jpg b/image/sam2_video_ultra_node.jpg new file mode 100644 index 0000000..a6aaf5f Binary files /dev/null and b/image/sam2_video_ultra_node.jpg differ diff --git a/image/saveimage_plus_example.jpg b/image/saveimage_plus_example.jpg new file mode 100644 index 0000000..2427d57 Binary files /dev/null and b/image/saveimage_plus_example.jpg differ diff --git a/image/saveimage_plus_node.jpg b/image/saveimage_plus_node.jpg new file mode 100644 index 0000000..2ae6d18 Binary files /dev/null and b/image/saveimage_plus_node.jpg differ diff --git a/image/sd3_negative_conditioning_example.jpg b/image/sd3_negative_conditioning_example.jpg new file mode 100644 index 0000000..299718b Binary files /dev/null and b/image/sd3_negative_conditioning_example.jpg differ diff --git a/image/sd3_negative_conditioning_node.jpg b/image/sd3_negative_conditioning_node.jpg new file mode 100644 index 0000000..e19548e Binary files /dev/null and b/image/sd3_negative_conditioning_node.jpg differ diff --git a/image/sd3_negative_conditioning_node_note.jpg b/image/sd3_negative_conditioning_node_note.jpg new file mode 100644 index 0000000..913d07a Binary files /dev/null and b/image/sd3_negative_conditioning_node_note.jpg differ diff --git a/image/segment_anything_ultra_compare.jpg b/image/segment_anything_ultra_compare.jpg new file mode 100644 index 0000000..550df2c Binary files /dev/null and b/image/segment_anything_ultra_compare.jpg differ diff --git a/image/segment_anything_ultra_example.jpg b/image/segment_anything_ultra_example.jpg new file mode 100644 index 0000000..e816dc2 Binary files /dev/null and b/image/segment_anything_ultra_example.jpg differ diff --git a/image/segment_anything_ultra_node.jpg b/image/segment_anything_ultra_node.jpg new file mode 100644 index 0000000..9a9e7fc Binary files /dev/null and b/image/segment_anything_ultra_node.jpg differ diff --git a/image/segment_anything_ultra_v2_node.jpg b/image/segment_anything_ultra_v2_node.jpg new file mode 100644 index 0000000..ea31e86 Binary files /dev/null and b/image/segment_anything_ultra_v2_node.jpg differ diff --git a/image/show_blind_watermark_node.jpg b/image/show_blind_watermark_node.jpg new file mode 100644 index 0000000..166ffa5 Binary files /dev/null and b/image/show_blind_watermark_node.jpg differ diff --git a/image/transparent_background_ultra_example.jpg b/image/transparent_background_ultra_example.jpg new file mode 100644 index 0000000..b906e5a Binary files /dev/null and b/image/transparent_background_ultra_example.jpg differ diff --git a/image/transparent_background_ultra_node.jpg b/image/transparent_background_ultra_node.jpg new file mode 100644 index 0000000..c979480 Binary files /dev/null and b/image/transparent_background_ultra_node.jpg differ diff --git a/image/ultra_v2_nodes_example.jpg b/image/ultra_v2_nodes_example.jpg new file mode 100644 index 0000000..d9b06c4 Binary files /dev/null and b/image/ultra_v2_nodes_example.jpg differ diff --git a/image/userprompt_generator_replace_word_node.jpg b/image/userprompt_generator_replace_word_node.jpg new file mode 100644 index 0000000..a592e23 Binary files /dev/null and b/image/userprompt_generator_replace_word_node.jpg differ diff --git a/image/userprompt_generator_txt2img_node.jpg b/image/userprompt_generator_txt2img_node.jpg new file mode 100644 index 0000000..6463c77 Binary files /dev/null and b/image/userprompt_generator_txt2img_node.jpg differ diff --git a/image/userprompt_generator_txt2img_with_reference_node.jpg b/image/userprompt_generator_txt2img_with_reference_node.jpg new file mode 100644 index 0000000..88c10c9 Binary files /dev/null and b/image/userprompt_generator_txt2img_with_reference_node.jpg differ diff --git a/image/water_color_example.jpg b/image/water_color_example.jpg new file mode 100644 index 0000000..3642972 Binary files /dev/null and b/image/water_color_example.jpg differ diff --git a/image/water_color_node.jpg b/image/water_color_node.jpg new file mode 100644 index 0000000..8a66baa Binary files /dev/null and b/image/water_color_node.jpg differ diff --git a/image/watermark_example.jpg b/image/watermark_example.jpg new file mode 100644 index 0000000..e3b4c09 Binary files /dev/null and b/image/watermark_example.jpg differ diff --git a/image/yolov8_detect_example.jpg b/image/yolov8_detect_example.jpg new file mode 100644 index 0000000..1dccdec Binary files /dev/null and b/image/yolov8_detect_example.jpg differ diff --git a/image/yolov8_detect_node.jpg b/image/yolov8_detect_node.jpg new file mode 100644 index 0000000..ea1a6b3 Binary files /dev/null and b/image/yolov8_detect_node.jpg differ diff --git a/install_requirements.bat b/install_requirements.bat new file mode 100644 index 0000000..d86aa03 --- /dev/null +++ b/install_requirements.bat @@ -0,0 +1,31 @@ +@echo off + +set "python_exec=..\..\..\python_embeded\python.exe" +set "repair_dependency_txt=%~dp0\repair_dependency_list.txt" +set "requirements_txt=%~dp0\requirements.txt" + +echo Installing with ComfyUI Portable +echo . +echo Install whl... +%python_exec% -s -m pip install ./whl/docopt-0.6.2-py2.py3-none-any.whl +%python_exec% -s -m pip install ./whl/hydra_core-1.3.2-py3-none-any.whl + +echo . +echo Install requirement.txt... + +for /f "delims=" %%i in (%requirements_txt%) do ( + %python_exec% -s -m pip install "%%i" + ) + +echo . +echo Fixing Dependency Package... +%python_exec% -s -m pip uninstall -y onnxruntime +%python_exec% -s -m pip uninstall -y opencv-python opencv-contrib-python opencv-python-headless opencv-contrib-python-headless +for /f "delims=" %%i in (%repair_dependency_txt%) do ( + %python_exec% -s -m pip install "%%i" + ) + +echo . +echo Install Finish! +pause + diff --git a/install_requirements_aki.bat b/install_requirements_aki.bat new file mode 100644 index 0000000..f7b9e33 --- /dev/null +++ b/install_requirements_aki.bat @@ -0,0 +1,30 @@ +@echo off + +set "python_exec=..\..\python\python.exe" +set "repair_dependency_txt=%~dp0\repair_dependency_list.txt" +set "requirements_txt=%~dp0\requirements.txt" + +echo Installing with ComfyUI Portable +echo . +echo Install whl... +%python_exec% -s -m pip install ./whl/docopt-0.6.2-py2.py3-none-any.whl +%python_exec% -s -m pip install ./whl/hydra_core-1.3.2-py3-none-any.whl + +echo . +echo Install requirement.txt... +for /f "delims=" %%i in (%requirements_txt%) do ( + %python_exec% -s -m pip install "%%i" + ) + +echo . +echo Fixing Dependency Package... +%python_exec% -s -m pip uninstall -y onnxruntime +%python_exec% -s -m pip uninstall -y opencv-python opencv-contrib-python opencv-python-headless opencv-contrib-python-headless +for /f "delims=" %%i in (%repair_dependency_txt%) do ( + %python_exec% -s -m pip install "%%i" + ) + +echo . +echo Install Finish! +pause + diff --git a/js/dz_node_palette.js b/js/dz_node_palette.js new file mode 100644 index 0000000..6356500 --- /dev/null +++ b/js/dz_node_palette.js @@ -0,0 +1,42 @@ +import { app } from "../../scripts/app.js"; + + +app.registerExtension({ + name: "ColorOverlay", + async nodeCreated(node) { + // 判断是否为layer节点 + if(!node.comfyClass.startsWith("Layer")) { + return; + } + + if(node.comfyClass.startsWith("LayerStyle:")) { + node.color = "rgba(20, 95, 121, 0.7)"; +// node.bgcolor = "rgba(50, 241, 255, 0.15)"; + } + + if(node.comfyClass.startsWith("LayerColor:")) { + node.color = "rgba(27, 89, 123, 0.7)"; +// node.bgcolor = "rgba(43, 209, 255, 0.15)"; + } + + if(node.comfyClass.startsWith("LayerMask:")) { + node.color = "rgba(27, 80, 119, 0.7)"; +// node.bgcolor = "rgba(4, 174, 255, 0.15)"; + } + + if(node.comfyClass.startsWith("LayerUtility:")) { + node.color = "rgba(38, 73, 116, 0.7)"; +// node.bgcolor = "rgba(23, 113, 255, 0.15)"; + } + + if(node.comfyClass.startsWith("LayerFilter:")) { + node.color = "rgba(34, 67, 111, 0.7)"; +// node.bgcolor = "rgba(19, 85, 255, 0.15)"; + } + + +// if(node.comfyClass === "LayerStyle: ColorOverlay"){ +// node.setSize([600, 120]); +// } + } +}); \ No newline at end of file diff --git a/py/BiRefNet_legacy/__init__.py b/py/BiRefNet_legacy/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/py/BiRefNet_legacy/backbones/__init__.py b/py/BiRefNet_legacy/backbones/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/py/BiRefNet_legacy/backbones/build_backbone.py b/py/BiRefNet_legacy/backbones/build_backbone.py new file mode 100644 index 0000000..e637c5e --- /dev/null +++ b/py/BiRefNet_legacy/backbones/build_backbone.py @@ -0,0 +1,45 @@ +import torch +import torch.nn as nn +from collections import OrderedDict +from torchvision.models import vgg16, vgg16_bn, VGG16_Weights, VGG16_BN_Weights, resnet50, ResNet50_Weights +from BiRefNet_legacy.backbones.pvt_v2 import pvt_v2_b2, pvt_v2_b5 +from BiRefNet_legacy.backbones.swin_v1 import swin_v1_t, swin_v1_s, swin_v1_b, swin_v1_l +from ..config import Config + + +config = Config() + +def build_backbone(bb_name, pretrained=True, params_settings=''): + if bb_name == 'vgg16': + bb_net = list(vgg16(pretrained=VGG16_Weights.DEFAULT if pretrained else None).children())[0] + bb = nn.Sequential(OrderedDict({'conv1': bb_net[:4], 'conv2': bb_net[4:9], 'conv3': bb_net[9:16], 'conv4': bb_net[16:23]})) + elif bb_name == 'vgg16bn': + bb_net = list(vgg16_bn(pretrained=VGG16_BN_Weights.DEFAULT if pretrained else None).children())[0] + bb = nn.Sequential(OrderedDict({'conv1': bb_net[:6], 'conv2': bb_net[6:13], 'conv3': bb_net[13:23], 'conv4': bb_net[23:33]})) + elif bb_name == 'resnet50': + bb_net = list(resnet50(pretrained=ResNet50_Weights.DEFAULT if pretrained else None).children()) + bb = nn.Sequential(OrderedDict({'conv1': nn.Sequential(*bb_net[0:3]), 'conv2': bb_net[4], 'conv3': bb_net[5], 'conv4': bb_net[6]})) + else: + bb = eval('{}({})'.format(bb_name, params_settings)) + if pretrained: + bb = load_weights(bb, bb_name) + return bb + +def load_weights(model, model_name): + # save_model = torch.load(config.weights[model_name]) + save_model = torch.load(config.weights[model_name], map_location=torch.device('cpu')) + model_dict = model.state_dict() + state_dict = {k: v if v.size() == model_dict[k].size() else model_dict[k] for k, v in save_model.items() if k in model_dict.keys()} + # to ignore the weights with mismatched size when I modify the backbone itself. + if not state_dict: + save_model_keys = list(save_model.keys()) + sub_item = save_model_keys[0] if len(save_model_keys) == 1 else None + state_dict = {k: v if v.size() == model_dict[k].size() else model_dict[k] for k, v in save_model[sub_item].items() if k in model_dict.keys()} + if not state_dict or not sub_item: + print('Weights are not successully loaded. Check the state dict of weights file.') + return None + else: + print('Found correct weights in the "{}" item of loaded state_dict.'.format(sub_item)) + model_dict.update(state_dict) + model.load_state_dict(model_dict) + return model diff --git a/py/BiRefNet_legacy/backbones/pvt_v2.py b/py/BiRefNet_legacy/backbones/pvt_v2.py new file mode 100644 index 0000000..7164f85 --- /dev/null +++ b/py/BiRefNet_legacy/backbones/pvt_v2.py @@ -0,0 +1,434 @@ +import torch +import torch.nn as nn +from functools import partial + +from timm.models.layers import DropPath, to_2tuple, trunc_normal_ +from timm.models import register_model + +import math + +from ..config import Config +config = Config() + +class Mlp(nn.Module): + def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.): + super().__init__() + out_features = out_features or in_features + hidden_features = hidden_features or in_features + self.fc1 = nn.Linear(in_features, hidden_features) + self.dwconv = DWConv(hidden_features) + self.act = act_layer() + self.fc2 = nn.Linear(hidden_features, out_features) + self.drop = nn.Dropout(drop) + + self.apply(self._init_weights) + + def _init_weights(self, m): + if isinstance(m, nn.Linear): + trunc_normal_(m.weight, std=.02) + if isinstance(m, nn.Linear) and m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.LayerNorm): + nn.init.constant_(m.bias, 0) + nn.init.constant_(m.weight, 1.0) + elif isinstance(m, nn.Conv2d): + fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels + fan_out //= m.groups + m.weight.data.normal_(0, math.sqrt(2.0 / fan_out)) + if m.bias is not None: + m.bias.data.zero_() + + def forward(self, x, H, W): + x = self.fc1(x) + x = self.dwconv(x, H, W) + x = self.act(x) + x = self.drop(x) + x = self.fc2(x) + x = self.drop(x) + return x + + +class Attention(nn.Module): + def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0., sr_ratio=1): + super().__init__() + assert dim % num_heads == 0, f"dim {dim} should be divided by num_heads {num_heads}." + + self.dim = dim + self.num_heads = num_heads + head_dim = dim // num_heads + self.scale = qk_scale or head_dim ** -0.5 + + self.q = nn.Linear(dim, dim, bias=qkv_bias) + self.kv = nn.Linear(dim, dim * 2, bias=qkv_bias) + self.attn_drop_prob = attn_drop + self.attn_drop = nn.Dropout(attn_drop) + self.proj = nn.Linear(dim, dim) + self.proj_drop = nn.Dropout(proj_drop) + + self.sr_ratio = sr_ratio + if sr_ratio > 1: + self.sr = nn.Conv2d(dim, dim, kernel_size=sr_ratio, stride=sr_ratio) + self.norm = nn.LayerNorm(dim) + + self.apply(self._init_weights) + + def _init_weights(self, m): + if isinstance(m, nn.Linear): + trunc_normal_(m.weight, std=.02) + if isinstance(m, nn.Linear) and m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.LayerNorm): + nn.init.constant_(m.bias, 0) + nn.init.constant_(m.weight, 1.0) + elif isinstance(m, nn.Conv2d): + fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels + fan_out //= m.groups + m.weight.data.normal_(0, math.sqrt(2.0 / fan_out)) + if m.bias is not None: + m.bias.data.zero_() + + def forward(self, x, H, W): + B, N, C = x.shape + q = self.q(x).reshape(B, N, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3) + + if self.sr_ratio > 1: + x_ = x.permute(0, 2, 1).reshape(B, C, H, W) + x_ = self.sr(x_).reshape(B, C, -1).permute(0, 2, 1) + x_ = self.norm(x_) + kv = self.kv(x_).reshape(B, -1, 2, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) + else: + kv = self.kv(x).reshape(B, -1, 2, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) + k, v = kv[0], kv[1] + + if config.SDPA_enabled: + x = torch.nn.functional.scaled_dot_product_attention( + q, k, v, + attn_mask=None, dropout_p=self.attn_drop_prob, is_causal=False + ).transpose(1, 2).reshape(B, N, C) + else: + attn = (q @ k.transpose(-2, -1)) * self.scale + attn = attn.softmax(dim=-1) + attn = self.attn_drop(attn) + + x = (attn @ v).transpose(1, 2).reshape(B, N, C) + x = self.proj(x) + x = self.proj_drop(x) + + return x + + +class Block(nn.Module): + + def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0., + drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, sr_ratio=1): + super().__init__() + self.norm1 = norm_layer(dim) + self.attn = Attention( + dim, + num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, + attn_drop=attn_drop, proj_drop=drop, sr_ratio=sr_ratio) + # NOTE: drop path for stochastic depth, we shall see if this is better than dropout here + self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity() + self.norm2 = norm_layer(dim) + mlp_hidden_dim = int(dim * mlp_ratio) + self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop) + + self.apply(self._init_weights) + + def _init_weights(self, m): + if isinstance(m, nn.Linear): + trunc_normal_(m.weight, std=.02) + if isinstance(m, nn.Linear) and m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.LayerNorm): + nn.init.constant_(m.bias, 0) + nn.init.constant_(m.weight, 1.0) + elif isinstance(m, nn.Conv2d): + fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels + fan_out //= m.groups + m.weight.data.normal_(0, math.sqrt(2.0 / fan_out)) + if m.bias is not None: + m.bias.data.zero_() + + def forward(self, x, H, W): + x = x + self.drop_path(self.attn(self.norm1(x), H, W)) + x = x + self.drop_path(self.mlp(self.norm2(x), H, W)) + + return x + + +class OverlapPatchEmbed(nn.Module): + """ Image to Patch Embedding + """ + + def __init__(self, img_size=224, patch_size=7, stride=4, in_channels=3, embed_dim=768): + super().__init__() + img_size = to_2tuple(img_size) + patch_size = to_2tuple(patch_size) + + self.img_size = img_size + self.patch_size = patch_size + self.H, self.W = img_size[0] // patch_size[0], img_size[1] // patch_size[1] + self.num_patches = self.H * self.W + self.proj = nn.Conv2d(in_channels, embed_dim, kernel_size=patch_size, stride=stride, + padding=(patch_size[0] // 2, patch_size[1] // 2)) + self.norm = nn.LayerNorm(embed_dim) + + self.apply(self._init_weights) + + def _init_weights(self, m): + if isinstance(m, nn.Linear): + trunc_normal_(m.weight, std=.02) + if isinstance(m, nn.Linear) and m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.LayerNorm): + nn.init.constant_(m.bias, 0) + nn.init.constant_(m.weight, 1.0) + elif isinstance(m, nn.Conv2d): + fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels + fan_out //= m.groups + m.weight.data.normal_(0, math.sqrt(2.0 / fan_out)) + if m.bias is not None: + m.bias.data.zero_() + + def forward(self, x): + x = self.proj(x) + _, _, H, W = x.shape + x = x.flatten(2).transpose(1, 2) + x = self.norm(x) + + return x, H, W + + +class PyramidVisionTransformerImpr(nn.Module): + def __init__(self, img_size=224, patch_size=16, in_channels=3, num_classes=1000, embed_dims=[64, 128, 256, 512], + num_heads=[1, 2, 4, 8], mlp_ratios=[4, 4, 4, 4], qkv_bias=False, qk_scale=None, drop_rate=0., + attn_drop_rate=0., drop_path_rate=0., norm_layer=nn.LayerNorm, + depths=[3, 4, 6, 3], sr_ratios=[8, 4, 2, 1]): + super().__init__() + self.num_classes = num_classes + self.depths = depths + + # patch_embed + self.patch_embed1 = OverlapPatchEmbed(img_size=img_size, patch_size=7, stride=4, in_channels=in_channels, + embed_dim=embed_dims[0]) + self.patch_embed2 = OverlapPatchEmbed(img_size=img_size // 4, patch_size=3, stride=2, in_channels=embed_dims[0], + embed_dim=embed_dims[1]) + self.patch_embed3 = OverlapPatchEmbed(img_size=img_size // 8, patch_size=3, stride=2, in_channels=embed_dims[1], + embed_dim=embed_dims[2]) + self.patch_embed4 = OverlapPatchEmbed(img_size=img_size // 16, patch_size=3, stride=2, in_channels=embed_dims[2], + embed_dim=embed_dims[3]) + + # transformer encoder + dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] # stochastic depth decay rule + cur = 0 + self.block1 = nn.ModuleList([Block( + dim=embed_dims[0], num_heads=num_heads[0], mlp_ratio=mlp_ratios[0], qkv_bias=qkv_bias, qk_scale=qk_scale, + drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer, + sr_ratio=sr_ratios[0]) + for i in range(depths[0])]) + self.norm1 = norm_layer(embed_dims[0]) + + cur += depths[0] + self.block2 = nn.ModuleList([Block( + dim=embed_dims[1], num_heads=num_heads[1], mlp_ratio=mlp_ratios[1], qkv_bias=qkv_bias, qk_scale=qk_scale, + drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer, + sr_ratio=sr_ratios[1]) + for i in range(depths[1])]) + self.norm2 = norm_layer(embed_dims[1]) + + cur += depths[1] + self.block3 = nn.ModuleList([Block( + dim=embed_dims[2], num_heads=num_heads[2], mlp_ratio=mlp_ratios[2], qkv_bias=qkv_bias, qk_scale=qk_scale, + drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer, + sr_ratio=sr_ratios[2]) + for i in range(depths[2])]) + self.norm3 = norm_layer(embed_dims[2]) + + cur += depths[2] + self.block4 = nn.ModuleList([Block( + dim=embed_dims[3], num_heads=num_heads[3], mlp_ratio=mlp_ratios[3], qkv_bias=qkv_bias, qk_scale=qk_scale, + drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer, + sr_ratio=sr_ratios[3]) + for i in range(depths[3])]) + self.norm4 = norm_layer(embed_dims[3]) + + # classification head + # self.head = nn.Linear(embed_dims[3], num_classes) if num_classes > 0 else nn.Identity() + + self.apply(self._init_weights) + + def _init_weights(self, m): + if isinstance(m, nn.Linear): + trunc_normal_(m.weight, std=.02) + if isinstance(m, nn.Linear) and m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.LayerNorm): + nn.init.constant_(m.bias, 0) + nn.init.constant_(m.weight, 1.0) + elif isinstance(m, nn.Conv2d): + fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels + fan_out //= m.groups + m.weight.data.normal_(0, math.sqrt(2.0 / fan_out)) + if m.bias is not None: + m.bias.data.zero_() + + def init_weights(self, pretrained=None): + if isinstance(pretrained, str): + logger = 1 + #load_checkpoint(self, pretrained, map_location='cpu', strict=False, logger=logger) + + def reset_drop_path(self, drop_path_rate): + dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(self.depths))] + cur = 0 + for i in range(self.depths[0]): + self.block1[i].drop_path.drop_prob = dpr[cur + i] + + cur += self.depths[0] + for i in range(self.depths[1]): + self.block2[i].drop_path.drop_prob = dpr[cur + i] + + cur += self.depths[1] + for i in range(self.depths[2]): + self.block3[i].drop_path.drop_prob = dpr[cur + i] + + cur += self.depths[2] + for i in range(self.depths[3]): + self.block4[i].drop_path.drop_prob = dpr[cur + i] + + def freeze_patch_emb(self): + self.patch_embed1.requires_grad = False + + @torch.jit.ignore + def no_weight_decay(self): + return {'pos_embed1', 'pos_embed2', 'pos_embed3', 'pos_embed4', 'cls_token'} # has pos_embed may be better + + def get_classifier(self): + return self.head + + def reset_classifier(self, num_classes, global_pool=''): + self.num_classes = num_classes + self.head = nn.Linear(self.embed_dim, num_classes) if num_classes > 0 else nn.Identity() + + def forward_features(self, x): + B = x.shape[0] + outs = [] + + # stage 1 + x, H, W = self.patch_embed1(x) + for i, blk in enumerate(self.block1): + x = blk(x, H, W) + x = self.norm1(x) + x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous() + outs.append(x) + + # stage 2 + x, H, W = self.patch_embed2(x) + for i, blk in enumerate(self.block2): + x = blk(x, H, W) + x = self.norm2(x) + x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous() + outs.append(x) + + # stage 3 + x, H, W = self.patch_embed3(x) + for i, blk in enumerate(self.block3): + x = blk(x, H, W) + x = self.norm3(x) + x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous() + outs.append(x) + + # stage 4 + x, H, W = self.patch_embed4(x) + for i, blk in enumerate(self.block4): + x = blk(x, H, W) + x = self.norm4(x) + x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous() + outs.append(x) + + return outs + + # return x.mean(dim=1) + + def forward(self, x): + x = self.forward_features(x) + # x = self.head(x) + + return x + + +class DWConv(nn.Module): + def __init__(self, dim=768): + super(DWConv, self).__init__() + self.dwconv = nn.Conv2d(dim, dim, 3, 1, 1, bias=True, groups=dim) + + def forward(self, x, H, W): + B, N, C = x.shape + x = x.transpose(1, 2).view(B, C, H, W).contiguous() + x = self.dwconv(x) + x = x.flatten(2).transpose(1, 2) + + return x + + +def _conv_filter(state_dict, patch_size=16): + """ convert patch embedding weight from manual patchify + linear proj to conv""" + out_dict = {} + for k, v in state_dict.items(): + if 'patch_embed.proj.weight' in k: + v = v.reshape((v.shape[0], 3, patch_size, patch_size)) + out_dict[k] = v + + return out_dict + + +## @register_model +class pvt_v2_b0(PyramidVisionTransformerImpr): + def __init__(self, **kwargs): + super(pvt_v2_b0, self).__init__( + patch_size=4, embed_dims=[32, 64, 160, 256], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4], + qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[2, 2, 2, 2], sr_ratios=[8, 4, 2, 1], + drop_rate=0.0, drop_path_rate=0.1) + + + +## @register_model +class pvt_v2_b1(PyramidVisionTransformerImpr): + def __init__(self, **kwargs): + super(pvt_v2_b1, self).__init__( + patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4], + qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[2, 2, 2, 2], sr_ratios=[8, 4, 2, 1], + drop_rate=0.0, drop_path_rate=0.1) + +## @register_model +class pvt_v2_b2(PyramidVisionTransformerImpr): + def __init__(self, in_channels=3, **kwargs): + super(pvt_v2_b2, self).__init__( + patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4], + qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 4, 6, 3], sr_ratios=[8, 4, 2, 1], + drop_rate=0.0, drop_path_rate=0.1, in_channels=in_channels) + +## @register_model +class pvt_v2_b3(PyramidVisionTransformerImpr): + def __init__(self, **kwargs): + super(pvt_v2_b3, self).__init__( + patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4], + qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 4, 18, 3], sr_ratios=[8, 4, 2, 1], + drop_rate=0.0, drop_path_rate=0.1) + +## @register_model +class pvt_v2_b4(PyramidVisionTransformerImpr): + def __init__(self, **kwargs): + super(pvt_v2_b4, self).__init__( + patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4], + qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 8, 27, 3], sr_ratios=[8, 4, 2, 1], + drop_rate=0.0, drop_path_rate=0.1) + + +## @register_model +class pvt_v2_b5(PyramidVisionTransformerImpr): + def __init__(self, **kwargs): + super(pvt_v2_b5, self).__init__( + patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[4, 4, 4, 4], + qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 6, 40, 3], sr_ratios=[8, 4, 2, 1], + drop_rate=0.0, drop_path_rate=0.1) diff --git a/py/BiRefNet_legacy/backbones/swin_v1.py b/py/BiRefNet_legacy/backbones/swin_v1.py new file mode 100644 index 0000000..57501dc --- /dev/null +++ b/py/BiRefNet_legacy/backbones/swin_v1.py @@ -0,0 +1,652 @@ +# -------------------------------------------------------- +# Swin Transformer +# Copyright (c) 2021 Microsoft +# Licensed under The MIT License [see LICENSE for details] +# Written by Ze Liu, Yutong Lin, Yixuan Wei +# -------------------------------------------------------- + +import torch +import torch.nn as nn +import torch.nn.functional as F +import torch.utils.checkpoint as checkpoint +import numpy as np +from timm.models.layers import DropPath, to_2tuple, trunc_normal_ + +from ..config import Config + + +config = Config() + +class Mlp(nn.Module): + """ Multilayer perceptron.""" + + def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.): + super().__init__() + out_features = out_features or in_features + hidden_features = hidden_features or in_features + self.fc1 = nn.Linear(in_features, hidden_features) + self.act = act_layer() + self.fc2 = nn.Linear(hidden_features, out_features) + self.drop = nn.Dropout(drop) + + def forward(self, x): + x = self.fc1(x) + x = self.act(x) + x = self.drop(x) + x = self.fc2(x) + x = self.drop(x) + return x + + +def window_partition(x, window_size): + """ + Args: + x: (B, H, W, C) + window_size (int): window size + + Returns: + windows: (num_windows*B, window_size, window_size, C) + """ + B, H, W, C = x.shape + x = x.view(B, H // window_size, window_size, W // window_size, window_size, C) + windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C) + return windows + + +def window_reverse(windows, window_size, H, W): + """ + Args: + windows: (num_windows*B, window_size, window_size, C) + window_size (int): Window size + H (int): Height of image + W (int): Width of image + + Returns: + x: (B, H, W, C) + """ + B = int(windows.shape[0] / (H * W / window_size / window_size)) + x = windows.view(B, H // window_size, W // window_size, window_size, window_size, -1) + x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1) + return x + + +class WindowAttention(nn.Module): + """ Window based multi-head self attention (W-MSA) module with relative position bias. + It supports both of shifted and non-shifted window. + + Args: + dim (int): Number of input channels. + window_size (tuple[int]): The height and width of the window. + num_heads (int): Number of attention heads. + qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True + qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set + attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0 + proj_drop (float, optional): Dropout ratio of output. Default: 0.0 + """ + + def __init__(self, dim, window_size, num_heads, qkv_bias=True, qk_scale=None, attn_drop=0., proj_drop=0.): + + super().__init__() + self.dim = dim + self.window_size = window_size # Wh, Ww + self.num_heads = num_heads + head_dim = dim // num_heads + self.scale = qk_scale or head_dim ** -0.5 + + # define a parameter table of relative position bias + self.relative_position_bias_table = nn.Parameter( + torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1), num_heads)) # 2*Wh-1 * 2*Ww-1, nH + + # get pair-wise relative position index for each token inside the window + coords_h = torch.arange(self.window_size[0]) + coords_w = torch.arange(self.window_size[1]) + coords = torch.stack(torch.meshgrid([coords_h, coords_w], indexing='ij')) # 2, Wh, Ww + coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww + relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww + relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2 + relative_coords[:, :, 0] += self.window_size[0] - 1 # shift to start from 0 + relative_coords[:, :, 1] += self.window_size[1] - 1 + relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1 + relative_position_index = relative_coords.sum(-1) # Wh*Ww, Wh*Ww + self.register_buffer("relative_position_index", relative_position_index) + + self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) + self.attn_drop_prob = attn_drop + self.attn_drop = nn.Dropout(attn_drop) + self.proj = nn.Linear(dim, dim) + self.proj_drop = nn.Dropout(proj_drop) + + trunc_normal_(self.relative_position_bias_table, std=.02) + self.softmax = nn.Softmax(dim=-1) + + def forward(self, x, mask=None): + """ Forward function. + + Args: + x: input features with shape of (num_windows*B, N, C) + mask: (0/-inf) mask with shape of (num_windows, Wh*Ww, Wh*Ww) or None + """ + B_, N, C = x.shape + qkv = self.qkv(x).reshape(B_, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) + q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple) + + q = q * self.scale + + if config.SDPA_enabled: + x = torch.nn.functional.scaled_dot_product_attention( + q, k, v, + attn_mask=None, dropout_p=self.attn_drop_prob, is_causal=False + ).transpose(1, 2).reshape(B_, N, C) + else: + attn = (q @ k.transpose(-2, -1)) + + relative_position_bias = self.relative_position_bias_table[self.relative_position_index.view(-1)].view( + self.window_size[0] * self.window_size[1], self.window_size[0] * self.window_size[1], -1) # Wh*Ww,Wh*Ww,nH + relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww + attn = attn + relative_position_bias.unsqueeze(0) + + if mask is not None: + nW = mask.shape[0] + attn = attn.view(B_ // nW, nW, self.num_heads, N, N) + mask.unsqueeze(1).unsqueeze(0) + attn = attn.view(-1, self.num_heads, N, N) + attn = self.softmax(attn) + else: + attn = self.softmax(attn) + + attn = self.attn_drop(attn) + + x = (attn @ v).transpose(1, 2).reshape(B_, N, C) + x = self.proj(x) + x = self.proj_drop(x) + return x + + +class SwinTransformerBlock(nn.Module): + """ Swin Transformer Block. + + Args: + dim (int): Number of input channels. + num_heads (int): Number of attention heads. + window_size (int): Window size. + shift_size (int): Shift size for SW-MSA. + mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. + qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True + qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set. + drop (float, optional): Dropout rate. Default: 0.0 + attn_drop (float, optional): Attention dropout rate. Default: 0.0 + drop_path (float, optional): Stochastic depth rate. Default: 0.0 + act_layer (nn.Module, optional): Activation layer. Default: nn.GELU + norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm + """ + + def __init__(self, dim, num_heads, window_size=7, shift_size=0, + mlp_ratio=4., qkv_bias=True, qk_scale=None, drop=0., attn_drop=0., drop_path=0., + act_layer=nn.GELU, norm_layer=nn.LayerNorm): + super().__init__() + self.dim = dim + self.num_heads = num_heads + self.window_size = window_size + self.shift_size = shift_size + self.mlp_ratio = mlp_ratio + assert 0 <= self.shift_size < self.window_size, "shift_size must in 0-window_size" + + self.norm1 = norm_layer(dim) + self.attn = WindowAttention( + dim, window_size=to_2tuple(self.window_size), num_heads=num_heads, + qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop) + + self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity() + self.norm2 = norm_layer(dim) + mlp_hidden_dim = int(dim * mlp_ratio) + self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop) + + self.H = None + self.W = None + + def forward(self, x, mask_matrix): + """ Forward function. + + Args: + x: Input feature, tensor size (B, H*W, C). + H, W: Spatial resolution of the input feature. + mask_matrix: Attention mask for cyclic shift. + """ + B, L, C = x.shape + H, W = self.H, self.W + assert L == H * W, "input feature has wrong size" + + shortcut = x + x = self.norm1(x) + x = x.view(B, H, W, C) + + # pad feature maps to multiples of window size + pad_l = pad_t = 0 + pad_r = (self.window_size - W % self.window_size) % self.window_size + pad_b = (self.window_size - H % self.window_size) % self.window_size + x = F.pad(x, (0, 0, pad_l, pad_r, pad_t, pad_b)) + _, Hp, Wp, _ = x.shape + + # cyclic shift + if self.shift_size > 0: + shifted_x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2)) + attn_mask = mask_matrix + else: + shifted_x = x + attn_mask = None + + # partition windows + x_windows = window_partition(shifted_x, self.window_size) # nW*B, window_size, window_size, C + x_windows = x_windows.view(-1, self.window_size * self.window_size, C) # nW*B, window_size*window_size, C + + # W-MSA/SW-MSA + attn_windows = self.attn(x_windows, mask=attn_mask) # nW*B, window_size*window_size, C + + # merge windows + attn_windows = attn_windows.view(-1, self.window_size, self.window_size, C) + shifted_x = window_reverse(attn_windows, self.window_size, Hp, Wp) # B H' W' C + + # reverse cyclic shift + if self.shift_size > 0: + x = torch.roll(shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2)) + else: + x = shifted_x + + if pad_r > 0 or pad_b > 0: + x = x[:, :H, :W, :].contiguous() + + x = x.view(B, H * W, C) + + # FFN + x = shortcut + self.drop_path(x) + x = x + self.drop_path(self.mlp(self.norm2(x))) + + return x + + +class PatchMerging(nn.Module): + """ Patch Merging Layer + + Args: + dim (int): Number of input channels. + norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm + """ + def __init__(self, dim, norm_layer=nn.LayerNorm): + super().__init__() + self.dim = dim + self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False) + self.norm = norm_layer(4 * dim) + + def forward(self, x, H, W): + """ Forward function. + + Args: + x: Input feature, tensor size (B, H*W, C). + H, W: Spatial resolution of the input feature. + """ + B, L, C = x.shape + assert L == H * W, "input feature has wrong size" + + x = x.view(B, H, W, C) + + # padding + pad_input = (H % 2 == 1) or (W % 2 == 1) + if pad_input: + x = F.pad(x, (0, 0, 0, W % 2, 0, H % 2)) + + x0 = x[:, 0::2, 0::2, :] # B H/2 W/2 C + x1 = x[:, 1::2, 0::2, :] # B H/2 W/2 C + x2 = x[:, 0::2, 1::2, :] # B H/2 W/2 C + x3 = x[:, 1::2, 1::2, :] # B H/2 W/2 C + x = torch.cat([x0, x1, x2, x3], -1) # B H/2 W/2 4*C + x = x.view(B, -1, 4 * C) # B H/2*W/2 4*C + + x = self.norm(x) + x = self.reduction(x) + + return x + + +class BasicLayer(nn.Module): + """ A basic Swin Transformer layer for one stage. + + Args: + dim (int): Number of feature channels + depth (int): Depths of this stage. + num_heads (int): Number of attention head. + window_size (int): Local window size. Default: 7. + mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4. + qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True + qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set. + drop (float, optional): Dropout rate. Default: 0.0 + attn_drop (float, optional): Attention dropout rate. Default: 0.0 + drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0 + norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm + downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None + use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False. + """ + + def __init__(self, + dim, + depth, + num_heads, + window_size=7, + mlp_ratio=4., + qkv_bias=True, + qk_scale=None, + drop=0., + attn_drop=0., + drop_path=0., + norm_layer=nn.LayerNorm, + downsample=None, + use_checkpoint=False): + super().__init__() + self.window_size = window_size + self.shift_size = window_size // 2 + self.depth = depth + self.use_checkpoint = use_checkpoint + + # build blocks + self.blocks = nn.ModuleList([ + SwinTransformerBlock( + dim=dim, + num_heads=num_heads, + window_size=window_size, + shift_size=0 if (i % 2 == 0) else window_size // 2, + mlp_ratio=mlp_ratio, + qkv_bias=qkv_bias, + qk_scale=qk_scale, + drop=drop, + attn_drop=attn_drop, + drop_path=drop_path[i] if isinstance(drop_path, list) else drop_path, + norm_layer=norm_layer) + for i in range(depth)]) + + # patch merging layer + if downsample is not None: + self.downsample = downsample(dim=dim, norm_layer=norm_layer) + else: + self.downsample = None + + def forward(self, x, H, W): + """ Forward function. + + Args: + x: Input feature, tensor size (B, H*W, C). + H, W: Spatial resolution of the input feature. + """ + + # calculate attention mask for SW-MSA + Hp = int(np.ceil(H / self.window_size)) * self.window_size + Wp = int(np.ceil(W / self.window_size)) * self.window_size + img_mask = torch.zeros((1, Hp, Wp, 1), device=x.device) # 1 Hp Wp 1 + h_slices = (slice(0, -self.window_size), + slice(-self.window_size, -self.shift_size), + slice(-self.shift_size, None)) + w_slices = (slice(0, -self.window_size), + slice(-self.window_size, -self.shift_size), + slice(-self.shift_size, None)) + cnt = 0 + for h in h_slices: + for w in w_slices: + img_mask[:, h, w, :] = cnt + cnt += 1 + + mask_windows = window_partition(img_mask, self.window_size) # nW, window_size, window_size, 1 + mask_windows = mask_windows.view(-1, self.window_size * self.window_size) + attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2) + attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(attn_mask == 0, float(0.0)) + + for blk in self.blocks: + blk.H, blk.W = H, W + if self.use_checkpoint: + x = checkpoint.checkpoint(blk, x, attn_mask) + else: + x = blk(x, attn_mask) + if self.downsample is not None: + x_down = self.downsample(x, H, W) + Wh, Ww = (H + 1) // 2, (W + 1) // 2 + return x, H, W, x_down, Wh, Ww + else: + return x, H, W, x, H, W + + +class PatchEmbed(nn.Module): + """ Image to Patch Embedding + + Args: + patch_size (int): Patch token size. Default: 4. + in_channels (int): Number of input image channels. Default: 3. + embed_dim (int): Number of linear projection output channels. Default: 96. + norm_layer (nn.Module, optional): Normalization layer. Default: None + """ + + def __init__(self, patch_size=4, in_channels=3, embed_dim=96, norm_layer=None): + super().__init__() + patch_size = to_2tuple(patch_size) + self.patch_size = patch_size + + self.in_channels = in_channels + self.embed_dim = embed_dim + + self.proj = nn.Conv2d(in_channels, embed_dim, kernel_size=patch_size, stride=patch_size) + if norm_layer is not None: + self.norm = norm_layer(embed_dim) + else: + self.norm = None + + def forward(self, x): + """Forward function.""" + # padding + _, _, H, W = x.size() + if W % self.patch_size[1] != 0: + x = F.pad(x, (0, self.patch_size[1] - W % self.patch_size[1])) + if H % self.patch_size[0] != 0: + x = F.pad(x, (0, 0, 0, self.patch_size[0] - H % self.patch_size[0])) + + x = self.proj(x) # B C Wh Ww + if self.norm is not None: + Wh, Ww = x.size(2), x.size(3) + x = x.flatten(2).transpose(1, 2) + x = self.norm(x) + x = x.transpose(1, 2).view(-1, self.embed_dim, Wh, Ww) + + return x + + +class SwinTransformer(nn.Module): + """ Swin Transformer backbone. + A PyTorch impl of : `Swin Transformer: Hierarchical Vision Transformer using Shifted Windows` - + https://arxiv.org/pdf/2103.14030 + + Args: + pretrain_img_size (int): Input image size for training the pretrained model, + used in absolute postion embedding. Default 224. + patch_size (int | tuple(int)): Patch size. Default: 4. + in_channels (int): Number of input image channels. Default: 3. + embed_dim (int): Number of linear projection output channels. Default: 96. + depths (tuple[int]): Depths of each Swin Transformer stage. + num_heads (tuple[int]): Number of attention head of each stage. + window_size (int): Window size. Default: 7. + mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4. + qkv_bias (bool): If True, add a learnable bias to query, key, value. Default: True + qk_scale (float): Override default qk scale of head_dim ** -0.5 if set. + drop_rate (float): Dropout rate. + attn_drop_rate (float): Attention dropout rate. Default: 0. + drop_path_rate (float): Stochastic depth rate. Default: 0.2. + norm_layer (nn.Module): Normalization layer. Default: nn.LayerNorm. + ape (bool): If True, add absolute position embedding to the patch embedding. Default: False. + patch_norm (bool): If True, add normalization after patch embedding. Default: True. + out_indices (Sequence[int]): Output from which stages. + frozen_stages (int): Stages to be frozen (stop grad and set eval mode). + -1 means not freezing any parameters. + use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False. + """ + + def __init__(self, + pretrain_img_size=224, + patch_size=4, + in_channels=3, + embed_dim=96, + depths=[2, 2, 6, 2], + num_heads=[3, 6, 12, 24], + window_size=7, + mlp_ratio=4., + qkv_bias=True, + qk_scale=None, + drop_rate=0., + attn_drop_rate=0., + drop_path_rate=0.2, + norm_layer=nn.LayerNorm, + ape=False, + patch_norm=True, + out_indices=(0, 1, 2, 3), + frozen_stages=-1, + use_checkpoint=False): + super().__init__() + + self.pretrain_img_size = pretrain_img_size + self.num_layers = len(depths) + self.embed_dim = embed_dim + self.ape = ape + self.patch_norm = patch_norm + self.out_indices = out_indices + self.frozen_stages = frozen_stages + + # split image into non-overlapping patches + self.patch_embed = PatchEmbed( + patch_size=patch_size, in_channels=in_channels, embed_dim=embed_dim, + norm_layer=norm_layer if self.patch_norm else None) + + # absolute position embedding + if self.ape: + pretrain_img_size = to_2tuple(pretrain_img_size) + patch_size = to_2tuple(patch_size) + patches_resolution = [pretrain_img_size[0] // patch_size[0], pretrain_img_size[1] // patch_size[1]] + + self.absolute_pos_embed = nn.Parameter(torch.zeros(1, embed_dim, patches_resolution[0], patches_resolution[1])) + trunc_normal_(self.absolute_pos_embed, std=.02) + + self.pos_drop = nn.Dropout(p=drop_rate) + + # stochastic depth + dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] # stochastic depth decay rule + + # build layers + self.layers = nn.ModuleList() + for i_layer in range(self.num_layers): + layer = BasicLayer( + dim=int(embed_dim * 2 ** i_layer), + depth=depths[i_layer], + num_heads=num_heads[i_layer], + window_size=window_size, + mlp_ratio=mlp_ratio, + qkv_bias=qkv_bias, + qk_scale=qk_scale, + drop=drop_rate, + attn_drop=attn_drop_rate, + drop_path=dpr[sum(depths[:i_layer]):sum(depths[:i_layer + 1])], + norm_layer=norm_layer, + downsample=PatchMerging if (i_layer < self.num_layers - 1) else None, + use_checkpoint=use_checkpoint) + self.layers.append(layer) + + num_features = [int(embed_dim * 2 ** i) for i in range(self.num_layers)] + self.num_features = num_features + + # add a norm layer for each output + for i_layer in out_indices: + layer = norm_layer(num_features[i_layer]) + layer_name = f'norm{i_layer}' + self.add_module(layer_name, layer) + + self._freeze_stages() + + def _freeze_stages(self): + if self.frozen_stages >= 0: + self.patch_embed.eval() + for param in self.patch_embed.parameters(): + param.requires_grad = False + + if self.frozen_stages >= 1 and self.ape: + self.absolute_pos_embed.requires_grad = False + + if self.frozen_stages >= 2: + self.pos_drop.eval() + for i in range(0, self.frozen_stages - 1): + m = self.layers[i] + m.eval() + for param in m.parameters(): + param.requires_grad = False + + def init_weights(self, pretrained=None): + """Initialize the weights in backbone. + + Args: + pretrained (str, optional): Path to pre-trained weights. + Defaults to None. + """ + + def _init_weights(m): + if isinstance(m, nn.Linear): + trunc_normal_(m.weight, std=.02) + if isinstance(m, nn.Linear) and m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.LayerNorm): + nn.init.constant_(m.bias, 0) + nn.init.constant_(m.weight, 1.0) + + if isinstance(pretrained, str): + self.apply(_init_weights) + logger = get_root_logger() + load_checkpoint(self, pretrained, strict=False, logger=logger) + elif pretrained is None: + self.apply(_init_weights) + else: + raise TypeError('pretrained must be a str or None') + + def forward(self, x): + """Forward function.""" + x = self.patch_embed(x) + + Wh, Ww = x.size(2), x.size(3) + if self.ape: + # interpolate the position embedding to the corresponding size + absolute_pos_embed = F.interpolate(self.absolute_pos_embed, size=(Wh, Ww), mode='bicubic') + x = (x + absolute_pos_embed) # B Wh*Ww C + + outs = []#x.contiguous()] + x = x.flatten(2).transpose(1, 2) + x = self.pos_drop(x) + for i in range(self.num_layers): + layer = self.layers[i] + x_out, H, W, x, Wh, Ww = layer(x, Wh, Ww) + + if i in self.out_indices: + norm_layer = getattr(self, f'norm{i}') + x_out = norm_layer(x_out) + + out = x_out.view(-1, H, W, self.num_features[i]).permute(0, 3, 1, 2).contiguous() + outs.append(out) + + return tuple(outs) + + def train(self, mode=True): + """Convert the model into training mode while keep layers freezed.""" + super(SwinTransformer, self).train(mode) + self._freeze_stages() + +def swin_v1_t(): + model = SwinTransformer(embed_dim=96, depths=[2, 2, 6, 2], num_heads=[3, 6, 12, 24], window_size=7) + return model + +def swin_v1_s(): + model = SwinTransformer(embed_dim=96, depths=[2, 2, 18, 2], num_heads=[3, 6, 12, 24], window_size=7) + return model + +def swin_v1_b(): + model = SwinTransformer(embed_dim=128, depths=[2, 2, 18, 2], num_heads=[4, 8, 16, 32], window_size=12) + return model + +def swin_v1_l(): + model = SwinTransformer(embed_dim=192, depths=[2, 2, 18, 2], num_heads=[6, 12, 24, 48], window_size=12) + return model diff --git a/py/BiRefNet_legacy/baseline.py b/py/BiRefNet_legacy/baseline.py new file mode 100644 index 0000000..e2bb6a9 --- /dev/null +++ b/py/BiRefNet_legacy/baseline.py @@ -0,0 +1,292 @@ +import torch +import torch.nn as nn +from collections import OrderedDict +import torch +import torch.nn as nn +import torch.nn.functional as F +from torchvision.models import vgg16, vgg16_bn +from torchvision.models import resnet50 +from kornia.filters import laplacian + +from BiRefNet_legacy.backbones.build_backbone import build_backbone +from BiRefNet_legacy.modules.decoder_blocks import BasicDecBlk, ResBlk, HierarAttDecBlk +from BiRefNet_legacy.modules.lateral_blocks import BasicLatBlk +from BiRefNet_legacy.modules.aspp import ASPP, ASPPDeformable +from BiRefNet_legacy.modules.ing import * +from BiRefNet_legacy.refinement.refiner import Refiner, RefinerPVTInChannels4, RefUNet +from BiRefNet_legacy.refinement.stem_layer import StemLayer + +from .config import Config +from .dataset import class_labels_TR_sorted + + +class BiRefNet(nn.Module): + def __init__(self): + super(BiRefNet, self).__init__() + self.config = Config() + self.epoch = 1 + self.bb = build_backbone(self.config.bb, pretrained=True) + + channels = self.config.lateral_channels_in_collection + + if self.config.auxiliary_classification: + self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) + self.cls_head = nn.Sequential( + nn.Linear(channels[0], len(class_labels_TR_sorted)) + ) + + if self.config.squeeze_block: + self.squeeze_module = nn.Sequential(*[ + eval(self.config.squeeze_block.split('_x')[0])(channels[0]+sum(self.config.cxt), channels[0]) + for _ in range(eval(self.config.squeeze_block.split('_x')[1])) + ]) + + self.decoder = Decoder(channels) + + if self.config.locate_head: + self.locate_header = nn.ModuleList([ + BasicDecBlk(channels[0], channels[-1]), + nn.Sequential( + nn.Conv2d(channels[-1], 1, 1, 1, 0), + ) + ]) + + if self.config.ender: + self.dec_end = nn.Sequential( + nn.Conv2d(1, 16, 3, 1, 1), + nn.Conv2d(16, 1, 3, 1, 1), + nn.ReLU(inplace=True), + ) + + # refine patch-level segmentation + if self.config.refine: + if self.config.refine == 'itself': + self.stem_layer = StemLayer(in_channels=3+1, inter_channels=48, out_channels=3) + else: + self.refiner = eval('{}({})'.format(self.config.refine, 'in_channels=3+1')) + + if self.config.freeze_bb: + # Freeze the backbone... + print(self.named_parameters()) + for key, value in self.named_parameters(): + if 'bb.' in key and 'refiner.' not in key: + value.requires_grad = False + + def forward_enc(self, x): + if self.config.bb in ['vgg16', 'vgg16bn', 'resnet50']: + x1 = self.bb.conv1(x); x2 = self.bb.conv2(x1); x3 = self.bb.conv3(x2); x4 = self.bb.conv4(x3) + else: + x1, x2, x3, x4 = self.bb(x) + if self.config.mul_scl_ipt == 'cat': + B, C, H, W = x.shape + x1_, x2_, x3_, x4_ = self.bb(F.interpolate(x, size=(H//2, W//2), mode='bilinear', align_corners=True)) + x1 = torch.cat([x1, F.interpolate(x1_, size=x1.shape[2:], mode='bilinear', align_corners=True)], dim=1) + x2 = torch.cat([x2, F.interpolate(x2_, size=x2.shape[2:], mode='bilinear', align_corners=True)], dim=1) + x3 = torch.cat([x3, F.interpolate(x3_, size=x3.shape[2:], mode='bilinear', align_corners=True)], dim=1) + x4 = torch.cat([x4, F.interpolate(x4_, size=x4.shape[2:], mode='bilinear', align_corners=True)], dim=1) + elif self.config.mul_scl_ipt == 'add': + B, C, H, W = x.shape + x1_, x2_, x3_, x4_ = self.bb(F.interpolate(x, size=(H//2, W//2), mode='bilinear', align_corners=True)) + x1 = x1 + F.interpolate(x1_, size=x1.shape[2:], mode='bilinear', align_corners=True) + x2 = x2 + F.interpolate(x2_, size=x2.shape[2:], mode='bilinear', align_corners=True) + x3 = x3 + F.interpolate(x3_, size=x3.shape[2:], mode='bilinear', align_corners=True) + x4 = x4 + F.interpolate(x4_, size=x4.shape[2:], mode='bilinear', align_corners=True) + class_preds = self.cls_head(self.avgpool(x4).view(x4.shape[0], -1)) if self.training and self.config.auxiliary_classification else None + if self.config.cxt: + x4 = torch.cat( + ( + *[ + F.interpolate(x1, size=x4.shape[2:], mode='bilinear', align_corners=True), + F.interpolate(x2, size=x4.shape[2:], mode='bilinear', align_corners=True), + F.interpolate(x3, size=x4.shape[2:], mode='bilinear', align_corners=True), + ][-len(self.config.cxt):], + x4 + ), + dim=1 + ) + return (x1, x2, x3, x4), class_preds + + def forward_ori(self, x): + ########## Encoder ########## + (x1, x2, x3, x4), class_preds = self.forward_enc(x) + if self.config.squeeze_block: + x4 = self.squeeze_module(x4) + ########## Decoder ########## + features = [x, x1, x2, x3, x4] + if self.config.out_ref: + features.append(laplacian(torch.mean(x, dim=1).unsqueeze(1), kernel_size=5)) + scaled_preds = self.decoder(features) + return scaled_preds, class_preds + + def forward_ref(self, x, pred): + # refine patch-level segmentation + if pred.shape[2:] != x.shape[2:]: + pred = F.interpolate(pred, size=x.shape[2:], mode='bilinear', align_corners=True) + # pred = pred.sigmoid() + if self.config.refine == 'itself': + x = self.stem_layer(torch.cat([x, pred], dim=1)) + scaled_preds, class_preds = self.forward_ori(x) + else: + scaled_preds = self.refiner([x, pred]) + class_preds = None + return scaled_preds, class_preds + + def forward_ref_end(self, x): + # remove the grids of concatenated preds + return self.dec_end(x) if self.config.ender else x + + + def forward(self, x): + scaled_preds, class_preds = self.forward_ori(x) + class_preds_lst = [class_preds] + return [scaled_preds, class_preds_lst] if self.training else scaled_preds + + +class Decoder(nn.Module): + def __init__(self, channels): + super(Decoder, self).__init__() + self.config = Config() + DecoderBlock = eval(self.config.dec_blk) + LateralBlock = eval(self.config.lat_blk) + + if self.config.dec_ipt: + self.split = self.config.dec_ipt_split + N_dec_ipt = 64 + DBlock = SimpleConvs + ic = 64 + ipt_cha_opt = 1 + self.ipt_blk4 = DBlock(2**8*3 if self.split else 3, [N_dec_ipt, channels[0]//8][ipt_cha_opt], inter_channels=ic) + self.ipt_blk3 = DBlock(2**6*3 if self.split else 3, [N_dec_ipt, channels[1]//8][ipt_cha_opt], inter_channels=ic) + self.ipt_blk2 = DBlock(2**4*3 if self.split else 3, [N_dec_ipt, channels[2]//8][ipt_cha_opt], inter_channels=ic) + self.ipt_blk1 = DBlock(2**0*3 if self.split else 3, [N_dec_ipt, channels[3]//8][ipt_cha_opt], inter_channels=ic) + else: + self.split = None + + self.decoder_block4 = DecoderBlock(channels[0], channels[1]) + self.decoder_block3 = DecoderBlock(channels[1]+([N_dec_ipt, channels[0]//8][ipt_cha_opt] if self.config.dec_ipt else 0), channels[2]) + self.decoder_block2 = DecoderBlock(channels[2]+([N_dec_ipt, channels[1]//8][ipt_cha_opt] if self.config.dec_ipt else 0), channels[3]) + self.decoder_block1 = DecoderBlock(channels[3]+([N_dec_ipt, channels[2]//8][ipt_cha_opt] if self.config.dec_ipt else 0), channels[3]//2) + self.conv_out1 = nn.Sequential(nn.Conv2d(channels[3]//2+([N_dec_ipt, channels[3]//8][ipt_cha_opt] if self.config.dec_ipt else 0), 1, 1, 1, 0)) + + self.lateral_block4 = LateralBlock(channels[1], channels[1]) + self.lateral_block3 = LateralBlock(channels[2], channels[2]) + self.lateral_block2 = LateralBlock(channels[3], channels[3]) + + if self.config.ms_supervision: + self.conv_ms_spvn_4 = nn.Conv2d(channels[1], 1, 1, 1, 0) + self.conv_ms_spvn_3 = nn.Conv2d(channels[2], 1, 1, 1, 0) + self.conv_ms_spvn_2 = nn.Conv2d(channels[3], 1, 1, 1, 0) + + if self.config.out_ref: + _N = 16 + # self.gdt_convs_4 = nn.Sequential(nn.Conv2d(channels[1], _N, 3, 1, 1), nn.BatchNorm2d(_N), nn.ReLU(inplace=True)) + self.gdt_convs_3 = nn.Sequential(nn.Conv2d(channels[2], _N, 3, 1, 1), nn.BatchNorm2d(_N), nn.ReLU(inplace=True)) + self.gdt_convs_2 = nn.Sequential(nn.Conv2d(channels[3], _N, 3, 1, 1), nn.BatchNorm2d(_N), nn.ReLU(inplace=True)) + + # self.gdt_convs_pred_4 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0)) + self.gdt_convs_pred_3 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0)) + self.gdt_convs_pred_2 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0)) + + # self.gdt_convs_attn_4 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0)) + self.gdt_convs_attn_3 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0)) + self.gdt_convs_attn_2 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0)) + + + def get_patches_batch(self, x, p): + _size_h, _size_w = p.shape[2:] + patches_batch = [] + for idx in range(x.shape[0]): + columns_x = torch.split(x[idx], split_size_or_sections=_size_w, dim=-1) + patches_x = [] + for column_x in columns_x: + patches_x += [p.unsqueeze(0) for p in torch.split(column_x, split_size_or_sections=_size_h, dim=-2)] + patch_sample = torch.cat(patches_x, dim=1) + patches_batch.append(patch_sample) + return torch.cat(patches_batch, dim=0) + + def forward(self, features): + if self.config.out_ref: + outs_gdt_pred = [] + outs_gdt_label = [] + x, x1, x2, x3, x4, gdt_gt = features + else: + x, x1, x2, x3, x4 = features + outs = [] + p4 = self.decoder_block4(x4) + m4 = self.conv_ms_spvn_4(p4) if self.config.ms_supervision else None + _p4 = F.interpolate(p4, size=x3.shape[2:], mode='bilinear', align_corners=True) + _p3 = _p4 + self.lateral_block4(x3) + if self.config.dec_ipt: + patches_batch = self.get_patches_batch(x, _p3) if self.split else x + _p3 = torch.cat((_p3, self.ipt_blk4(F.interpolate(patches_batch, size=x3.shape[2:], mode='bilinear', align_corners=True))), 1) + + p3 = self.decoder_block3(_p3) + m3 = self.conv_ms_spvn_3(p3) if self.config.ms_supervision else None + if self.config.out_ref: + # >> GT: + # m3 --dilation--> m3_dia + # G_3^gt * m3_dia --> G_3^m, which is the label of gradient + m3_dia = m3 + gdt_label_main_3 = gdt_gt * F.interpolate(m3_dia, size=gdt_gt.shape[2:], mode='bilinear', align_corners=True) + outs_gdt_label.append(gdt_label_main_3) + # >> Pred: + # p3 --conv--BN--> F_3^G, where F_3^G predicts the \hat{G_3} with xx + # F_3^G --sigmoid--> A_3^G + p3_gdt = self.gdt_convs_3(p3) + gdt_pred_3 = self.gdt_convs_pred_3(p3_gdt) + outs_gdt_pred.append(gdt_pred_3) + gdt_attn_3 = self.gdt_convs_attn_3(p3_gdt).sigmoid() + # >> Finally: + # p3 = p3 * A_3^G + p3 = p3 * gdt_attn_3 + _p3 = F.interpolate(p3, size=x2.shape[2:], mode='bilinear', align_corners=True) + _p2 = _p3 + self.lateral_block3(x2) + if self.config.dec_ipt: + patches_batch = self.get_patches_batch(x, _p2) if self.split else x + _p2 = torch.cat((_p2, self.ipt_blk3(F.interpolate(patches_batch, size=x2.shape[2:], mode='bilinear', align_corners=True))), 1) + + p2 = self.decoder_block2(_p2) + m2 = self.conv_ms_spvn_2(p2) if self.config.ms_supervision else None + if self.config.out_ref: + # >> GT: + m2_dia = m2 + gdt_label_main_2 = gdt_gt * F.interpolate(m2_dia, size=gdt_gt.shape[2:], mode='bilinear', align_corners=True) + outs_gdt_label.append(gdt_label_main_2) + # >> Pred: + p2_gdt = self.gdt_convs_2(p2) + gdt_pred_2 = self.gdt_convs_pred_2(p2_gdt) + outs_gdt_pred.append(gdt_pred_2) + gdt_attn_2 = self.gdt_convs_attn_2(p2_gdt).sigmoid() + # >> Finally: + p2 = p2 * gdt_attn_2 + _p2 = F.interpolate(p2, size=x1.shape[2:], mode='bilinear', align_corners=True) + _p1 = _p2 + self.lateral_block2(x1) + if self.config.dec_ipt: + patches_batch = self.get_patches_batch(x, _p1) if self.split else x + _p1 = torch.cat((_p1, self.ipt_blk2(F.interpolate(patches_batch, size=x1.shape[2:], mode='bilinear', align_corners=True))), 1) + + _p1 = self.decoder_block1(_p1) + _p1 = F.interpolate(_p1, size=x.shape[2:], mode='bilinear', align_corners=True) + if self.config.dec_ipt: + patches_batch = self.get_patches_batch(x, _p1) if self.split else x + _p1 = torch.cat((_p1, self.ipt_blk1(F.interpolate(patches_batch, size=x.shape[2:], mode='bilinear', align_corners=True))), 1) + p1_out = self.conv_out1(_p1) + + if self.config.ms_supervision: + outs.append(m4) + outs.append(m3) + outs.append(m2) + outs.append(p1_out) + return outs if not (self.config.out_ref and self.training) else ([outs_gdt_pred, outs_gdt_label], outs) + + +class SimpleConvs(nn.Module): + def __init__( + self, in_channels: int, out_channels: int, inter_channels=64 + ) -> None: + super().__init__() + self.conv1 = nn.Conv2d(in_channels, inter_channels, 3, 1, 1) + self.conv_out = nn.Conv2d(inter_channels, out_channels, 3, 1, 1) + + def forward(self, x): + return self.conv_out(self.conv1(x)) diff --git a/py/BiRefNet_legacy/config.py b/py/BiRefNet_legacy/config.py new file mode 100644 index 0000000..e7ee155 --- /dev/null +++ b/py/BiRefNet_legacy/config.py @@ -0,0 +1,104 @@ +import os +import math +from folder_paths import models_dir + + +class Config(): + def __init__(self) -> None: + self.ms_supervision = True + self.out_ref = self.ms_supervision and True + self.dec_ipt = True + self.dec_ipt_split = True + self.locate_head = False + self.cxt_num = [0, 3][1] # multi-scale skip connections from encoder + self.mul_scl_ipt = ['', 'add', 'cat'][2] + self.refine = ['', 'itself', 'RefUNet', 'Refiner', 'RefinerPVTInChannels4'][0] + self.progressive_ref = self.refine and True + self.ender = self.progressive_ref and False + self.scale = self.progressive_ref and 2 + self.dec_att = ['', 'ASPP', 'ASPPDeformable'][2] + self.squeeze_block = ['', 'BasicDecBlk_x1', 'ResBlk_x4', 'ASPP_x3', 'ASPPDeformable_x3'][1] + self.dec_blk = ['BasicDecBlk', 'ResBlk', 'HierarAttDecBlk'][0] + self.auxiliary_classification = False + self.refine_iteration = 1 + self.freeze_bb = False + self.precisionHigh = True + self.compile = True + self.load_all = True + self.verbose_eval = True + + self.size = 1024 + self.batch_size = 2 + self.IoU_finetune_last_epochs = [0, -40][1] # choose 0 to skip + if self.dec_blk == 'HierarAttDecBlk': + self.batch_size = 2 ** [0, 1, 2, 3, 4][2] + self.model = [ + 'BiRefNet', + ][0] + + # Components + self.lat_blk = ['BasicLatBlk'][0] + self.dec_channels_inter = ['fixed', 'adap'][0] + + # Backbone + self.bb = [ + 'vgg16', 'vgg16bn', 'resnet50', # 0, 1, 2 + 'pvt_v2_b2', 'pvt_v2_b5', # 3-bs10, 4-bs5 + 'swin_v1_b', 'swin_v1_l' # 5-bs9, 6-bs6 + ][6] + self.lateral_channels_in_collection = { + 'vgg16': [512, 256, 128, 64], 'vgg16bn': [512, 256, 128, 64], 'resnet50': [1024, 512, 256, 64], + 'pvt_v2_b2': [512, 320, 128, 64], 'pvt_v2_b5': [512, 320, 128, 64], + 'swin_v1_b': [1024, 512, 256, 128], 'swin_v1_l': [1536, 768, 384, 192], + }[self.bb] + if self.mul_scl_ipt == 'cat': + self.lateral_channels_in_collection = [channel * 2 for channel in self.lateral_channels_in_collection] + self.cxt = self.lateral_channels_in_collection[1:][::-1][-self.cxt_num:] if self.cxt_num else [] + self.sys_home_dir = models_dir + self.weights_root_dir = os.path.join(self.sys_home_dir, "BiRefNet") + self.weights = { + 'pvt_v2_b2': os.path.join(self.weights_root_dir, 'pvt_v2_b2.pth'), + 'pvt_v2_b5': os.path.join(self.weights_root_dir, ['pvt_v2_b5.pth', 'pvt_v2_b5_22k.pth'][0]), + 'swin_v1_b': os.path.join(self.weights_root_dir, ['swin_base_patch4_window12_384_22kto1k.pth', 'swin_base_patch4_window12_384_22k.pth'][0]), + 'swin_v1_l': os.path.join(self.weights_root_dir, ['swin_large_patch4_window12_384_22kto1k.pth', 'swin_large_patch4_window12_384_22k.pth'][0]), + } + + # Training + self.num_workers = 5 # will be decrease to min(it, batch_size) at the initialization of the data_loader + self.optimizer = ['Adam', 'AdamW'][0] + self.lr = 1e-5 * math.sqrt(self.batch_size / 5) # adapt the lr linearly + self.lr_decay_epochs = [1e4] # Set to negative N to decay the lr in the last N-th epoch. + self.lr_decay_rate = 0.5 + self.only_S_MAE = False + self.SDPA_enabled = False # Bug. Slower and errors occur in multi-GPUs + + # Data + self.data_root_dir = os.path.join(self.sys_home_dir, 'datasets/dis') + self.dataset = ['DIS5K', 'COD', 'SOD'][0] + self.preproc_methods = ['flip', 'enhance', 'rotate', 'pepper', 'crop'][:4] + + # Loss + self.lambdas_pix_last = { + # not 0 means opening this loss + # original rate -- 1 : 30 : 1.5 : 0.2, bce x 30 + 'bce': 30 * 1, # high performance + 'iou': 0.5 * 1, # 0 / 255 + 'iou_patch': 0.5 * 0, # 0 / 255, win_size = (64, 64) + 'mse': 150 * 0, # can smooth the saliency map + 'triplet': 3 * 0, + 'reg': 100 * 0, + 'ssim': 10 * 1, # help contours, + 'cnt': 5 * 0, # help contours + } + self.lambdas_cls = { + 'ce': 5.0 + } + # Adv + self.lambda_adv_g = 10. * 0 # turn to 0 to avoid adv training + self.lambda_adv_d = 3. * (self.lambda_adv_g > 0) + + # others + self.device = [0, 'cpu'][0] # .to(0) = .to('cuda:0') + + self.batch_size_valid = 1 + self.rand_seed = 7 diff --git a/py/BiRefNet_legacy/dataset.py b/py/BiRefNet_legacy/dataset.py new file mode 100644 index 0000000..cd4280c --- /dev/null +++ b/py/BiRefNet_legacy/dataset.py @@ -0,0 +1,140 @@ +import os +import cv2 +from tqdm import tqdm +from PIL import Image +from torch.utils import data +from torchvision import transforms + +from .preproc import preproc +from .config import Config +from glob import glob + + +Image.MAX_IMAGE_PIXELS = None # remove DecompressionBombWarning +config = Config() +_class_labels_TR_sorted = 'Airplane, Ant, Antenna, Archery, Axe, BabyCarriage, Bag, BalanceBeam, Balcony, Balloon, Basket, BasketballHoop, Beatle, Bed, Bee, Bench, Bicycle, BicycleFrame, BicycleStand, Boat, Bonsai, BoomLift, Bridge, BunkBed, Butterfly, Button, Cable, CableLift, Cage, Camcorder, Cannon, Canoe, Car, CarParkDropArm, Carriage, Cart, Caterpillar, CeilingLamp, Centipede, Chair, Clip, Clock, Clothes, CoatHanger, Comb, ConcretePumpTruck, Crack, Crane, Cup, DentalChair, Desk, DeskChair, Diagram, DishRack, DoorHandle, Dragonfish, Dragonfly, Drum, Earphone, Easel, ElectricIron, Excavator, Eyeglasses, Fan, Fence, Fencing, FerrisWheel, FireExtinguisher, Fishing, Flag, FloorLamp, Forklift, GasStation, Gate, Gear, Goal, Golf, GymEquipment, Hammock, Handcart, Handcraft, Handrail, HangGlider, Harp, Harvester, Headset, Helicopter, Helmet, Hook, HorizontalBar, Hydrovalve, IroningTable, Jewelry, Key, KidsPlayground, Kitchenware, Kite, Knife, Ladder, LaundryRack, Lightning, Lobster, Locust, Machine, MachineGun, MagazineRack, Mantis, Medal, MemorialArchway, Microphone, Missile, MobileHolder, Monitor, Mosquito, Motorcycle, MovingTrolley, Mower, MusicPlayer, MusicStand, ObservationTower, Octopus, OilWell, OlympicLogo, OperatingTable, OutdoorFitnessEquipment, Parachute, Pavilion, Piano, Pipe, PlowHarrow, PoleVault, Punchbag, Rack, Racket, Rifle, Ring, Robot, RockClimbing, Rope, Sailboat, Satellite, Scaffold, Scale, Scissor, Scooter, Sculpture, Seadragon, Seahorse, Seal, SewingMachine, Ship, Shoe, ShoppingCart, ShoppingTrolley, Shower, Shrimp, Signboard, Skateboarding, Skeleton, Skiing, Spade, SpeedBoat, Spider, Spoon, Stair, Stand, Stationary, SteeringWheel, Stethoscope, Stool, Stove, StreetLamp, SweetStand, Swing, Sword, TV, Table, TableChair, TableLamp, TableTennis, Tank, Tapeline, Teapot, Telescope, Tent, TobaccoPipe, Toy, Tractor, TrafficLight, TrafficSign, Trampoline, TransmissionTower, Tree, Tricycle, TrimmerCover, Tripod, Trombone, Truck, Trumpet, Tuba, UAV, Umbrella, UnevenBars, UtilityPole, VacuumCleaner, Violin, Wakesurfing, Watch, WaterTower, WateringPot, Well, WellLid, Wheel, Wheelchair, WindTurbine, Windmill, WineGlass, WireWhisk, Yacht' +class_labels_TR_sorted = _class_labels_TR_sorted.split(', ') + + +class MyData(data.Dataset): + def __init__(self, data_root, image_size, is_train=True): + self.size_train = image_size + self.size_test = image_size + self.keep_size = not config.size + self.data_size = (config.size, config.size) + self.is_train = is_train + self.load_all = config.load_all + self.device = config.device + self.dataset = data_root.replace('\\', '/').split('/')[-1] + if self.is_train and config.auxiliary_classification: + self.cls_name2id = {_name: _id for _id, _name in enumerate(class_labels_TR_sorted)} + self.transform_image = transforms.Compose([ + transforms.Resize(self.data_size), + transforms.ToTensor(), + transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]), + ][self.load_all or self.keep_size:]) + self.transform_label = transforms.Compose([ + transforms.Resize(self.data_size), + transforms.ToTensor(), + ][self.load_all or self.keep_size:]) + ## 'im' and 'gt' need modifying + image_root = os.path.join(data_root, 'im') + self.image_paths = [os.path.join(image_root, p) for p in os.listdir(image_root)] + self.label_paths = [p.replace('/im/', '/gt/').replace('.jpg', '.png') for p in self.image_paths] + if self.load_all: + self.images_loaded, self.labels_loaded = [], [] + self.class_labels_loaded = [] + # for image_path, label_path in zip(self.image_paths, self.label_paths): + for image_path, label_path in tqdm(zip(self.image_paths, self.label_paths), total=len(self.image_paths)): + _image = cv2.imread(image_path) + _label = cv2.imread(label_path, cv2.IMREAD_GRAYSCALE) + if not self.keep_size: + _image_rs = cv2.resize(_image, (config.size, config.size), interpolation=cv2.INTER_LINEAR) + _label_rs = cv2.resize(_label, (config.size, config.size), interpolation=cv2.INTER_LINEAR) + self.images_loaded.append( + Image.fromarray(cv2.cvtColor(_image_rs, cv2.COLOR_BGR2RGB)).convert('RGB') + ) + self.labels_loaded.append( + Image.fromarray(_label_rs).convert('L') + ) + self.class_labels_loaded.append( + self.cls_name2id[label_path.split('/')[-1].split('#')[3]] if self.is_train and config.auxiliary_classification else -1 + ) + + + def __getitem__(self, index): + + if self.load_all: + image = self.images_loaded[index] + class_label = self.class_labels_loaded[index] if self.is_train and config.auxiliary_classification else -1 + else: + image = Image.open(self.image_paths[index]).convert('RGB') + + # loading image and label + if self.is_train: + image, label = preproc(image, image, preproc_methods=config.preproc_methods) + # else: + # if _label.shape[0] > 2048 or _label.shape[1] > 2048: + # _image = cv2.resize(_image, (2048, 2048), interpolation=cv2.INTER_LINEAR) + # _label = cv2.resize(_label, (2048, 2048), interpolation=cv2.INTER_LINEAR) + + image, label = self.transform_image(image), self.transform_label(label) + + if self.is_train: + return image, label, class_label + else: + return image, label, self.label_paths[index] + + def __len__(self): + return len(self.image_paths) + + +class YouData(data.Dataset): + def __init__(self, data_root, image_size, is_train=True): + self.size_train = image_size + self.size_test = image_size + self.keep_size = not config.size + self.data_size = (config.size, config.size) + self.is_train = is_train + self.load_all = config.load_all + self.device = config.device + self.dataset = data_root.replace('\\', '/').split('/')[-1] + if self.is_train and config.auxiliary_classification: + self.cls_name2id = {_name: _id for _id, _name in enumerate(class_labels_TR_sorted)} + self.transform_image = transforms.Compose([ + transforms.Resize(self.data_size), + transforms.ToTensor(), + transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]), + ][self.load_all or self.keep_size:]) + ## 'im' and 'gt' need modifying + self.image_paths = glob(data_root + "/*") + self.img_sizes = [] + if self.load_all: + self.images_loaded, self.labels_loaded = [], [] + for image_path in tqdm(self.image_paths, total=len(self.image_paths)): + _image = cv2.imread(image_path) + if not self.keep_size: + _image_rs = cv2.resize(_image, (config.size, config.size), interpolation=cv2.INTER_LINEAR) + self.images_loaded.append( + Image.fromarray(cv2.cvtColor(_image_rs, cv2.COLOR_BGR2RGB)).convert('RGB') + ) + self.img_sizes.append(_image.shape[:2]) + + + def __getitem__(self, index): + + if self.load_all: + image = self.images_loaded[index] + else: + image = Image.open(self.image_paths[index]).convert('RGB') + + # loading image and label + if self.is_train: + image, _ = preproc(image, image, preproc_methods=config.preproc_methods) + + image = self.transform_image(image) + size = self.img_sizes[index] + return image, size + + def __len__(self): + return len(self.image_paths) diff --git a/py/BiRefNet_legacy/modules/__init__.py b/py/BiRefNet_legacy/modules/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/py/BiRefNet_legacy/modules/aspp.py b/py/BiRefNet_legacy/modules/aspp.py new file mode 100644 index 0000000..a34d69a --- /dev/null +++ b/py/BiRefNet_legacy/modules/aspp.py @@ -0,0 +1,162 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F +from BiRefNet_legacy.modules.deform_conv import DeformableConv2d +from ..config import Config + + +config = Config() + + +class ASPPComplex(nn.Module): + def __init__(self, in_channels=64, out_channels=None, output_stride=16): + super(ASPPComplex, self).__init__() + self.down_scale = 1 + if out_channels is None: + out_channels = in_channels + self.in_channelster = 256 // self.down_scale + if output_stride == 16: + dilations = [1, 6, 12, 18] + elif output_stride == 8: + dilations = [1, 12, 24, 36] + else: + raise NotImplementedError + + self.aspp1 = _ASPPModule(in_channels, self.in_channelster, 1, padding=0, dilation=dilations[0]) + self.aspp2 = _ASPPModule(in_channels, self.in_channelster, 3, padding=dilations[1], dilation=dilations[1]) + self.aspp3 = _ASPPModule(in_channels, self.in_channelster, 3, padding=dilations[2], dilation=dilations[2]) + self.aspp4 = _ASPPModule(in_channels, self.in_channelster, 3, padding=dilations[3], dilation=dilations[3]) + + self.global_avg_pool = nn.Sequential(nn.AdaptiveAvgPool2d((1, 1)), + nn.Conv2d(in_channels, self.in_channelster, 1, stride=1, bias=False), + nn.BatchNorm2d(self.in_channelster) if config.batch_size > 1 else nn.Identity(), + nn.ReLU(inplace=True)) + self.conv1 = nn.Conv2d(self.in_channelster * 5, out_channels, 1, bias=False) + self.bn1 = nn.BatchNorm2d(out_channels) + self.relu = nn.ReLU(inplace=True) + self.dropout = nn.Dropout(0.5) + + def forward(self, x): + x1 = self.aspp1(x) + x2 = self.aspp2(x) + x3 = self.aspp3(x) + x4 = self.aspp4(x) + x5 = self.global_avg_pool(x) + x5 = F.interpolate(x5, size=x1.size()[2:], mode='bilinear', align_corners=True) + x = torch.cat((x1, x2, x3, x4, x5), dim=1) + + x = self.conv1(x) + x = self.bn1(x) + x = self.relu(x) + + return self.dropout(x) + + +class _ASPPModule(nn.Module): + def __init__(self, in_channels, planes, kernel_size, padding, dilation): + super(_ASPPModule, self).__init__() + self.atrous_conv = nn.Conv2d(in_channels, planes, kernel_size=kernel_size, + stride=1, padding=padding, dilation=dilation, bias=False) + self.bn = nn.BatchNorm2d(planes) + self.relu = nn.ReLU(inplace=True) + + def forward(self, x): + x = self.atrous_conv(x) + x = self.bn(x) + + return self.relu(x) + +class ASPP(nn.Module): + def __init__(self, in_channels=64, out_channels=None, output_stride=16): + super(ASPP, self).__init__() + self.down_scale = 1 + if out_channels is None: + out_channels = in_channels + self.in_channelster = 256 // self.down_scale + if output_stride == 16: + dilations = [1, 6, 12, 18] + elif output_stride == 8: + dilations = [1, 12, 24, 36] + else: + raise NotImplementedError + + self.aspp1 = _ASPPModule(in_channels, self.in_channelster, 1, padding=0, dilation=dilations[0]) + self.aspp2 = _ASPPModule(in_channels, self.in_channelster, 3, padding=dilations[1], dilation=dilations[1]) + self.aspp3 = _ASPPModule(in_channels, self.in_channelster, 3, padding=dilations[2], dilation=dilations[2]) + self.aspp4 = _ASPPModule(in_channels, self.in_channelster, 3, padding=dilations[3], dilation=dilations[3]) + + self.global_avg_pool = nn.Sequential(nn.AdaptiveAvgPool2d((1, 1)), + nn.Conv2d(in_channels, self.in_channelster, 1, stride=1, bias=False), + nn.BatchNorm2d(self.in_channelster) if config.batch_size > 1 else nn.Identity(), + nn.ReLU(inplace=True)) + self.conv1 = nn.Conv2d(self.in_channelster * 5, out_channels, 1, bias=False) + self.bn1 = nn.BatchNorm2d(out_channels) + self.relu = nn.ReLU(inplace=True) + self.dropout = nn.Dropout(0.5) + + def forward(self, x): + x1 = self.aspp1(x) + x2 = self.aspp2(x) + x3 = self.aspp3(x) + x4 = self.aspp4(x) + x5 = self.global_avg_pool(x) + x5 = F.interpolate(x5, size=x1.size()[2:], mode='bilinear', align_corners=True) + x = torch.cat((x1, x2, x3, x4, x5), dim=1) + + x = self.conv1(x) + x = self.bn1(x) + x = self.relu(x) + + return self.dropout(x) + + +##################### Deformable +class _ASPPModuleDeformable(nn.Module): + def __init__(self, in_channels, planes, kernel_size, padding): + super(_ASPPModuleDeformable, self).__init__() + self.atrous_conv = DeformableConv2d(in_channels, planes, kernel_size=kernel_size, + stride=1, padding=padding, bias=False) + self.bn = nn.BatchNorm2d(planes) + self.relu = nn.ReLU(inplace=True) + + def forward(self, x): + x = self.atrous_conv(x) + x = self.bn(x) + + return self.relu(x) + + +class ASPPDeformable(nn.Module): + def __init__(self, in_channels, out_channels=None, num_parallel_block=1): + super(ASPPDeformable, self).__init__() + self.down_scale = 1 + if out_channels is None: + out_channels = in_channels + self.in_channelster = 256 // self.down_scale + + self.aspp1 = _ASPPModuleDeformable(in_channels, self.in_channelster, 1, padding=0) + self.aspp_deforms = nn.ModuleList([ + _ASPPModuleDeformable(in_channels, self.in_channelster, 3, padding=1) for _ in range(num_parallel_block) + ]) + + self.global_avg_pool = nn.Sequential(nn.AdaptiveAvgPool2d((1, 1)), + nn.Conv2d(in_channels, self.in_channelster, 1, stride=1, bias=False), + nn.BatchNorm2d(self.in_channelster) if config.batch_size > 1 else nn.Identity(), + nn.ReLU(inplace=True)) + self.conv1 = nn.Conv2d(self.in_channelster * (2 + len(self.aspp_deforms)), out_channels, 1, bias=False) + self.bn1 = nn.BatchNorm2d(out_channels) + self.relu = nn.ReLU(inplace=True) + self.dropout = nn.Dropout(0.5) + + def forward(self, x): + x1 = self.aspp1(x) + x_aspp_deforms = [aspp_deform(x) for aspp_deform in self.aspp_deforms] + x5 = self.global_avg_pool(x) + x5 = F.interpolate(x5, size=x1.size()[2:], mode='bilinear', align_corners=True) + x = torch.cat((x1, *x_aspp_deforms, x5), dim=1) + + x = self.conv1(x) + x = self.bn1(x) + x = self.relu(x) + + return self.dropout(x) diff --git a/py/BiRefNet_legacy/modules/attentions.py b/py/BiRefNet_legacy/modules/attentions.py new file mode 100644 index 0000000..e1032af --- /dev/null +++ b/py/BiRefNet_legacy/modules/attentions.py @@ -0,0 +1,93 @@ +import numpy as np +import torch +from torch import nn +from torch.nn import init + + +class SEWeightModule(nn.Module): + def __init__(self, channels, reduction=16): + super(SEWeightModule, self).__init__() + self.avg_pool = nn.AdaptiveAvgPool2d(1) + self.fc1 = nn.Conv2d(channels, channels//reduction, kernel_size=1, padding=0) + self.relu = nn.ReLU(inplace=True) + self.fc2 = nn.Conv2d(channels//reduction, channels, kernel_size=1, padding=0) + self.sigmoid = nn.Sigmoid() + + def forward(self, x): + out = self.avg_pool(x) + out = self.fc1(out) + out = self.relu(out) + out = self.fc2(out) + weight = self.sigmoid(out) + return weight + + +class PSA(nn.Module): + + def __init__(self, in_channels, S=4, reduction=4): + super().__init__() + self.S = S + + _convs = [] + for i in range(S): + _convs.append(nn.Conv2d(in_channels//S, in_channels//S, kernel_size=2*(i+1)+1, padding=i+1)) + self.convs = nn.ModuleList(_convs) + + self.se_block = SEWeightModule(in_channels//S, reduction=S*reduction) + + self.softmax = nn.Softmax(dim=1) + + def forward(self, x): + b, c, h, w = x.size() + + # Step1: SPC module + SPC_out = x.view(b, self.S, c//self.S, h, w) #bs,s,ci,h,w + for idx, conv in enumerate(self.convs): + SPC_out[:,idx,:,:,:] = conv(SPC_out[:,idx,:,:,:].clone()) + + # Step2: SE weight + se_out=[] + for idx in range(self.S): + se_out.append(self.se_block(SPC_out[:, idx, :, :, :])) + SE_out = torch.stack(se_out, dim=1) + SE_out = SE_out.expand_as(SPC_out) + + # Step3: Softmax + softmax_out = self.softmax(SE_out) + + # Step4: SPA + PSA_out = SPC_out * softmax_out + PSA_out = PSA_out.view(b, -1, h, w) + + return PSA_out + + +class SGE(nn.Module): + + def __init__(self, groups): + super().__init__() + self.groups=groups + self.avg_pool = nn.AdaptiveAvgPool2d(1) + self.weight=nn.Parameter(torch.zeros(1,groups,1,1)) + self.bias=nn.Parameter(torch.zeros(1,groups,1,1)) + self.sig=nn.Sigmoid() + + def forward(self, x): + b, c, h,w=x.shape + x=x.view(b*self.groups,-1,h,w) #bs*g,dim//g,h,w + xn=x*self.avg_pool(x) #bs*g,dim//g,h,w + xn=xn.sum(dim=1,keepdim=True) #bs*g,1,h,w + t=xn.view(b*self.groups,-1) #bs*g,h*w + + t=t-t.mean(dim=1,keepdim=True) #bs*g,h*w + std=t.std(dim=1,keepdim=True)+1e-5 + t=t/std #bs*g,h*w + t=t.view(b,self.groups,h,w) #bs,g,h*w + + t=t*self.weight+self.bias #bs,g,h*w + t=t.view(b*self.groups,1,h,w) #bs*g,1,h*w + x=x*self.sig(t) + x=x.view(b,c,h,w) + + return x + diff --git a/py/BiRefNet_legacy/modules/decoder_blocks.py b/py/BiRefNet_legacy/modules/decoder_blocks.py new file mode 100644 index 0000000..84c9592 --- /dev/null +++ b/py/BiRefNet_legacy/modules/decoder_blocks.py @@ -0,0 +1,101 @@ +import torch +import torch.nn as nn +from BiRefNet_legacy.modules.aspp import ASPP, ASPPDeformable +from BiRefNet_legacy.modules.attentions import PSA, SGE +from ..config import Config + + +config = Config() + + +class BasicDecBlk(nn.Module): + def __init__(self, in_channels=64, out_channels=64, inter_channels=64): + super(BasicDecBlk, self).__init__() + inter_channels = in_channels // 4 if config.dec_channels_inter == 'adap' else 64 + self.conv_in = nn.Conv2d(in_channels, inter_channels, 3, 1, padding=1) + self.relu_in = nn.ReLU(inplace=True) + if config.dec_att == 'ASPP': + self.dec_att = ASPP(in_channels=inter_channels) + elif config.dec_att == 'ASPPDeformable': + self.dec_att = ASPPDeformable(in_channels=inter_channels) + self.conv_out = nn.Conv2d(inter_channels, out_channels, 3, 1, padding=1) + self.bn_in = nn.BatchNorm2d(inter_channels) + self.bn_out = nn.BatchNorm2d(out_channels) + + def forward(self, x): + x = self.conv_in(x) + x = self.bn_in(x) + x = self.relu_in(x) + if hasattr(self, 'dec_att'): + x = self.dec_att(x) + x = self.conv_out(x) + x = self.bn_out(x) + return x + + +class ResBlk(nn.Module): + def __init__(self, in_channels=64, out_channels=None, inter_channels=64): + super(ResBlk, self).__init__() + if out_channels is None: + out_channels = in_channels + inter_channels = in_channels // 4 if config.dec_channels_inter == 'adap' else 64 + + self.conv_in = nn.Conv2d(in_channels, inter_channels, 3, 1, padding=1) + self.bn_in = nn.BatchNorm2d(inter_channels) + self.relu_in = nn.ReLU(inplace=True) + + if config.dec_att == 'ASPP': + self.dec_att = ASPP(in_channels=inter_channels) + elif config.dec_att == 'ASPPDeformable': + self.dec_att = ASPPDeformable(in_channels=inter_channels) + + self.conv_out = nn.Conv2d(inter_channels, out_channels, 3, 1, padding=1) + self.bn_out = nn.BatchNorm2d(out_channels) + + self.conv_resi = nn.Conv2d(in_channels, out_channels, 1, 1, 0) + + def forward(self, x): + _x = self.conv_resi(x) + x = self.conv_in(x) + x = self.bn_in(x) + x = self.relu_in(x) + if hasattr(self, 'dec_att'): + x = self.dec_att(x) + x = self.conv_out(x) + x = self.bn_out(x) + return x + _x + + +class HierarAttDecBlk(nn.Module): + def __init__(self, in_channels=64, out_channels=None, inter_channels=64): + super(HierarAttDecBlk, self).__init__() + if out_channels is None: + out_channels = in_channels + inter_channels = in_channels // 4 if config.dec_channels_inter == 'adap' else 64 + self.split_y = 8 # must be divided by channels of all intermediate features + self.split_x = 8 + + self.conv_in = nn.Conv2d(in_channels, inter_channels, 3, 1, 1) + + self.psa = PSA(inter_channels*self.split_y*self.split_x, S=config.batch_size) + self.sge = SGE(groups=config.batch_size) + + if config.dec_att == 'ASPP': + self.dec_att = ASPP(in_channels=inter_channels) + elif config.dec_att == 'ASPPDeformable': + self.dec_att = ASPPDeformable(in_channels=inter_channels) + self.conv_out = nn.Conv2d(inter_channels, out_channels, 3, 1, 1) + + def forward(self, x): + x = self.conv_in(x) + N, C, H, W = x.shape + x_patchs = x.reshape(N, -1, H//self.split_y, W//self.split_x) + + # Hierarchical attention: group attention X patch spatial attention + x_patchs = self.psa(x_patchs) # Group Channel Attention -- each group is a single image + x_patchs = self.sge(x_patchs) # Patch Spatial Attention + x = x.reshape(N, C, H, W) + if hasattr(self, 'dec_att'): + x = self.dec_att(x) + x = self.conv_out(x) + return x diff --git a/py/BiRefNet_legacy/modules/deform_conv.py b/py/BiRefNet_legacy/modules/deform_conv.py new file mode 100644 index 0000000..43f5e57 --- /dev/null +++ b/py/BiRefNet_legacy/modules/deform_conv.py @@ -0,0 +1,66 @@ +import torch +import torch.nn as nn +from torchvision.ops import deform_conv2d + + +class DeformableConv2d(nn.Module): + def __init__(self, + in_channels, + out_channels, + kernel_size=3, + stride=1, + padding=1, + bias=False): + + super(DeformableConv2d, self).__init__() + + assert type(kernel_size) == tuple or type(kernel_size) == int + + kernel_size = kernel_size if type(kernel_size) == tuple else (kernel_size, kernel_size) + self.stride = stride if type(stride) == tuple else (stride, stride) + self.padding = padding + + self.offset_conv = nn.Conv2d(in_channels, + 2 * kernel_size[0] * kernel_size[1], + kernel_size=kernel_size, + stride=stride, + padding=self.padding, + bias=True) + + nn.init.constant_(self.offset_conv.weight, 0.) + nn.init.constant_(self.offset_conv.bias, 0.) + + self.modulator_conv = nn.Conv2d(in_channels, + 1 * kernel_size[0] * kernel_size[1], + kernel_size=kernel_size, + stride=stride, + padding=self.padding, + bias=True) + + nn.init.constant_(self.modulator_conv.weight, 0.) + nn.init.constant_(self.modulator_conv.bias, 0.) + + self.regular_conv = nn.Conv2d(in_channels, + out_channels=out_channels, + kernel_size=kernel_size, + stride=stride, + padding=self.padding, + bias=bias) + + def forward(self, x): + #h, w = x.shape[2:] + #max_offset = max(h, w)/4. + + offset = self.offset_conv(x)#.clamp(-max_offset, max_offset) + modulator = 2. * torch.sigmoid(self.modulator_conv(x)) + + x = deform_conv2d( + input=x, + offset=offset, + weight=self.regular_conv.weight, + bias=self.regular_conv.bias, + padding=self.padding, + mask=modulator, + stride=self.stride, + ) + return x diff --git a/py/BiRefNet_legacy/modules/ing.py b/py/BiRefNet_legacy/modules/ing.py new file mode 100644 index 0000000..3032075 --- /dev/null +++ b/py/BiRefNet_legacy/modules/ing.py @@ -0,0 +1,29 @@ +import torch.nn as nn +from BiRefNet_legacy.modules.mlp import MLPLayer + + +class BlockA(nn.Module): + def __init__(self, in_channels=64, out_channels=64, inter_channels=64, mlp_ratio=4.): + super(BlockA, self).__init__() + inter_channels = in_channels + self.conv = nn.Conv2d(in_channels, inter_channels, 3, 1, 1) + self.norm1 = nn.LayerNorm(inter_channels) + self.ffn = MLPLayer(in_features=inter_channels, + hidden_features=int(inter_channels * mlp_ratio), + act_layer=nn.GELU, + drop=0.) + self.norm2 = nn.LayerNorm(inter_channels) + + def forward(self, x): + B, C, H, W = x.shape + _x = self.conv(x) + _x = _x.flatten(2).transpose(1, 2) + _x = self.norm1(_x) + x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous() + + x = x + _x + _x1 = self.ffn(x) + _x1 = self.norm2(_x1) + _x1 = _x1.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous() + x = x + _x1 + return x \ No newline at end of file diff --git a/py/BiRefNet_legacy/modules/lateral_blocks.py b/py/BiRefNet_legacy/modules/lateral_blocks.py new file mode 100644 index 0000000..a3022e6 --- /dev/null +++ b/py/BiRefNet_legacy/modules/lateral_blocks.py @@ -0,0 +1,21 @@ +import numpy as np +import torch +import torch.nn as nn +import torch.nn.functional as F +from functools import partial + +from ..config import Config + + +config = Config() + + +class BasicLatBlk(nn.Module): + def __init__(self, in_channels=64, out_channels=64, inter_channels=64): + super(BasicLatBlk, self).__init__() + inter_channels = in_channels // 4 if config.dec_channels_inter == 'adap' else 64 + self.conv = nn.Conv2d(in_channels, out_channels, 1, 1, 0) + + def forward(self, x): + x = self.conv(x) + return x diff --git a/py/BiRefNet_legacy/modules/mlp.py b/py/BiRefNet_legacy/modules/mlp.py new file mode 100644 index 0000000..a383459 --- /dev/null +++ b/py/BiRefNet_legacy/modules/mlp.py @@ -0,0 +1,118 @@ +import torch +import torch.nn as nn +from functools import partial + +from timm.models.layers import DropPath, to_2tuple, trunc_normal_ +from timm.models import register_model + +import math + + +class MLPLayer(nn.Module): + def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.): + super().__init__() + out_features = out_features or in_features + hidden_features = hidden_features or in_features + self.fc1 = nn.Linear(in_features, hidden_features) + self.act = act_layer() + self.fc2 = nn.Linear(hidden_features, out_features) + self.drop = nn.Dropout(drop) + + def forward(self, x): + x = self.fc1(x) + x = self.act(x) + x = self.drop(x) + x = self.fc2(x) + x = self.drop(x) + return x + + +class Attention(nn.Module): + def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0., sr_ratio=1): + super().__init__() + assert dim % num_heads == 0, f"dim {dim} should be divided by num_heads {num_heads}." + + self.dim = dim + self.num_heads = num_heads + head_dim = dim // num_heads + self.scale = qk_scale or head_dim ** -0.5 + + self.q = nn.Linear(dim, dim, bias=qkv_bias) + self.kv = nn.Linear(dim, dim * 2, bias=qkv_bias) + self.attn_drop = nn.Dropout(attn_drop) + self.proj = nn.Linear(dim, dim) + self.proj_drop = nn.Dropout(proj_drop) + + self.sr_ratio = sr_ratio + if sr_ratio > 1: + self.sr = nn.Conv2d(dim, dim, kernel_size=sr_ratio, stride=sr_ratio) + self.norm = nn.LayerNorm(dim) + + def forward(self, x, H, W): + B, N, C = x.shape + q = self.q(x).reshape(B, N, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3) + + if self.sr_ratio > 1: + x_ = x.permute(0, 2, 1).reshape(B, C, H, W) + x_ = self.sr(x_).reshape(B, C, -1).permute(0, 2, 1) + x_ = self.norm(x_) + kv = self.kv(x_).reshape(B, -1, 2, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) + else: + kv = self.kv(x).reshape(B, -1, 2, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) + k, v = kv[0], kv[1] + + attn = (q @ k.transpose(-2, -1)) * self.scale + attn = attn.softmax(dim=-1) + attn = self.attn_drop(attn) + + x = (attn @ v).transpose(1, 2).reshape(B, N, C) + x = self.proj(x) + x = self.proj_drop(x) + return x + + +class Block(nn.Module): + def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0., + drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, sr_ratio=1): + super().__init__() + self.norm1 = norm_layer(dim) + self.attn = Attention( + dim, + num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, + attn_drop=attn_drop, proj_drop=drop, sr_ratio=sr_ratio) + # NOTE: drop path for stochastic depth, we shall see if this is better than dropout here + self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity() + self.norm2 = norm_layer(dim) + mlp_hidden_dim = int(dim * mlp_ratio) + self.mlp = MLPLayer(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop) + + def forward(self, x, H, W): + x = x + self.drop_path(self.attn(self.norm1(x), H, W)) + x = x + self.drop_path(self.mlp(self.norm2(x), H, W)) + return x + + +class OverlapPatchEmbed(nn.Module): + """ Image to Patch Embedding + """ + + def __init__(self, img_size=224, patch_size=7, stride=4, in_channels=3, embed_dim=768): + super().__init__() + img_size = to_2tuple(img_size) + patch_size = to_2tuple(patch_size) + + self.img_size = img_size + self.patch_size = patch_size + self.H, self.W = img_size[0] // patch_size[0], img_size[1] // patch_size[1] + self.num_patches = self.H * self.W + self.proj = nn.Conv2d(in_channels, embed_dim, kernel_size=patch_size, stride=stride, + padding=(patch_size[0] // 2, patch_size[1] // 2)) + self.norm = nn.LayerNorm(embed_dim) + + def forward(self, x): + x = self.proj(x) + _, _, H, W = x.shape + x = x.flatten(2).transpose(1, 2) + x = self.norm(x) + return x, H, W + diff --git a/py/BiRefNet_legacy/modules/utils.py b/py/BiRefNet_legacy/modules/utils.py new file mode 100644 index 0000000..59bd912 --- /dev/null +++ b/py/BiRefNet_legacy/modules/utils.py @@ -0,0 +1,54 @@ +import torch.nn as nn + + +def build_act_layer(act_layer): + if act_layer == 'ReLU': + return nn.ReLU(inplace=True) + elif act_layer == 'SiLU': + return nn.SiLU(inplace=True) + elif act_layer == 'GELU': + return nn.GELU() + + raise NotImplementedError(f'build_act_layer does not support {act_layer}') + + +def build_norm_layer(dim, + norm_layer, + in_format='channels_last', + out_format='channels_last', + eps=1e-6): + layers = [] + if norm_layer == 'BN': + if in_format == 'channels_last': + layers.append(to_channels_first()) + layers.append(nn.BatchNorm2d(dim)) + if out_format == 'channels_last': + layers.append(to_channels_last()) + elif norm_layer == 'LN': + if in_format == 'channels_first': + layers.append(to_channels_last()) + layers.append(nn.LayerNorm(dim, eps=eps)) + if out_format == 'channels_first': + layers.append(to_channels_first()) + else: + raise NotImplementedError( + f'build_norm_layer does not support {norm_layer}') + return nn.Sequential(*layers) + + +class to_channels_first(nn.Module): + + def __init__(self): + super().__init__() + + def forward(self, x): + return x.permute(0, 3, 1, 2) + + +class to_channels_last(nn.Module): + + def __init__(self): + super().__init__() + + def forward(self, x): + return x.permute(0, 2, 3, 1) diff --git a/py/BiRefNet_legacy/preproc.py b/py/BiRefNet_legacy/preproc.py new file mode 100644 index 0000000..a059c5d --- /dev/null +++ b/py/BiRefNet_legacy/preproc.py @@ -0,0 +1,85 @@ +from PIL import Image, ImageEnhance +import random +import numpy as np +import random + + +def preproc(image, label, preproc_methods=['flip']): + if 'flip' in preproc_methods: + image, label = cv_random_flip(image, label) + if 'crop' in preproc_methods: + image, label = random_crop(image, label) + if 'rotate' in preproc_methods: + image, label = random_rotate(image, label) + if 'enhance' in preproc_methods: + image = color_enhance(image) + if 'pepper' in preproc_methods: + label = random_pepper(label) + return image, label + + +def cv_random_flip(img, label): + if random.random() > 0.5: + img = img.transpose(Image.FLIP_LEFT_RIGHT) + label = label.transpose(Image.FLIP_LEFT_RIGHT) + return img, label + + +def random_crop(image, label): + border = 30 + image_width = image.size[0] + image_height = image.size[1] + border = int(min(image_width, image_height) * 0.1) + crop_win_width = np.random.randint(image_width - border, image_width) + crop_win_height = np.random.randint(image_height - border, image_height) + random_region = ( + (image_width - crop_win_width) >> 1, (image_height - crop_win_height) >> 1, (image_width + crop_win_width) >> 1, + (image_height + crop_win_height) >> 1) + return image.crop(random_region), label.crop(random_region) + + +def random_rotate(image, label, angle=15): + mode = Image.BICUBIC + if random.random() > 0.8: + random_angle = np.random.randint(-angle, angle) + image = image.rotate(random_angle, mode) + label = label.rotate(random_angle, mode) + return image, label + + +def color_enhance(image): + bright_intensity = random.randint(5, 15) / 10.0 + image = ImageEnhance.Brightness(image).enhance(bright_intensity) + contrast_intensity = random.randint(5, 15) / 10.0 + image = ImageEnhance.Contrast(image).enhance(contrast_intensity) + color_intensity = random.randint(0, 20) / 10.0 + image = ImageEnhance.Color(image).enhance(color_intensity) + sharp_intensity = random.randint(0, 30) / 10.0 + image = ImageEnhance.Sharpness(image).enhance(sharp_intensity) + return image + + +def random_gaussian(image, mean=0.1, sigma=0.35): + def gaussianNoisy(im, mean=mean, sigma=sigma): + for _i in range(len(im)): + im[_i] += random.gauss(mean, sigma) + return im + + img = np.asarray(image) + width, height = img.shape + img = gaussianNoisy(img[:].flatten(), mean, sigma) + img = img.reshape([width, height]) + return Image.fromarray(np.uint8(img)) + + +def random_pepper(img, N=0.0015): + img = np.array(img) + noiseNum = int(N * img.shape[0] * img.shape[1]) + for i in range(noiseNum): + randX = random.randint(0, img.shape[0] - 1) + randY = random.randint(0, img.shape[1] - 1) + if random.randint(0, 1) == 0: + img[randX, randY] = 0 + else: + img[randX, randY] = 255 + return Image.fromarray(img) diff --git a/py/BiRefNet_legacy/refinement/__init__.py b/py/BiRefNet_legacy/refinement/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/py/BiRefNet_legacy/refinement/refiner.py b/py/BiRefNet_legacy/refinement/refiner.py new file mode 100644 index 0000000..71567a6 --- /dev/null +++ b/py/BiRefNet_legacy/refinement/refiner.py @@ -0,0 +1,253 @@ +import torch +import torch.nn as nn +from collections import OrderedDict +import torch +import torch.nn as nn +import torch.nn.functional as F +from torchvision.models import vgg16, vgg16_bn +from torchvision.models import resnet50 + +from ..config import Config +from ..dataset import class_labels_TR_sorted +from BiRefNet_legacy.backbones.build_backbone import build_backbone +from BiRefNet_legacy.modules.decoder_blocks import BasicDecBlk +from BiRefNet_legacy.modules.lateral_blocks import BasicLatBlk +from BiRefNet_legacy.modules.ing import * +from BiRefNet_legacy.refinement.stem_layer import StemLayer + + +class RefinerPVTInChannels4(nn.Module): + def __init__(self, in_channels=3+1): + super(RefinerPVTInChannels4, self).__init__() + self.config = Config() + self.epoch = 1 + self.bb = build_backbone(self.config.bb, params_settings='in_channels=4') + + lateral_channels_in_collection = { + 'vgg16': [512, 256, 128, 64], 'vgg16bn': [512, 256, 128, 64], 'resnet50': [1024, 512, 256, 64], + 'pvt_v2_b2': [512, 320, 128, 64], 'pvt_v2_b5': [512, 320, 128, 64], + 'swin_v1_b': [1024, 512, 256, 128], 'swin_v1_l': [1536, 768, 384, 192], + } + channels = lateral_channels_in_collection[self.config.bb] + self.squeeze_module = BasicDecBlk(channels[0], channels[0]) + + self.decoder = Decoder(channels) + + if 0: + for key, value in self.named_parameters(): + if 'bb.' in key: + value.requires_grad = False + + def forward(self, x): + if isinstance(x, list): + x = torch.cat(x, dim=1) + ########## Encoder ########## + if self.config.bb in ['vgg16', 'vgg16bn', 'resnet50']: + x1 = self.bb.conv1(x) + x2 = self.bb.conv2(x1) + x3 = self.bb.conv3(x2) + x4 = self.bb.conv4(x3) + else: + x1, x2, x3, x4 = self.bb(x) + + x4 = self.squeeze_module(x4) + + ########## Decoder ########## + + features = [x, x1, x2, x3, x4] + scaled_preds = self.decoder(features) + + return scaled_preds + + +class Refiner(nn.Module): + def __init__(self, in_channels=3+1): + super(Refiner, self).__init__() + self.config = Config() + self.epoch = 1 + self.stem_layer = StemLayer(in_channels=in_channels, inter_channels=48, out_channels=3) + self.bb = build_backbone(self.config.bb) + + lateral_channels_in_collection = { + 'vgg16': [512, 256, 128, 64], 'vgg16bn': [512, 256, 128, 64], 'resnet50': [1024, 512, 256, 64], + 'pvt_v2_b2': [512, 320, 128, 64], 'pvt_v2_b5': [512, 320, 128, 64], + 'swin_v1_b': [1024, 512, 256, 128], 'swin_v1_l': [1536, 768, 384, 192], + } + channels = lateral_channels_in_collection[self.config.bb] + self.squeeze_module = BasicDecBlk(channels[0], channels[0]) + + self.decoder = Decoder(channels) + + if 0: + for key, value in self.named_parameters(): + if 'bb.' in key: + value.requires_grad = False + + def forward(self, x): + if isinstance(x, list): + x = torch.cat(x, dim=1) + x = self.stem_layer(x) + ########## Encoder ########## + if self.config.bb in ['vgg16', 'vgg16bn', 'resnet50']: + x1 = self.bb.conv1(x) + x2 = self.bb.conv2(x1) + x3 = self.bb.conv3(x2) + x4 = self.bb.conv4(x3) + else: + x1, x2, x3, x4 = self.bb(x) + + x4 = self.squeeze_module(x4) + + ########## Decoder ########## + + features = [x, x1, x2, x3, x4] + scaled_preds = self.decoder(features) + + return scaled_preds + + +class Decoder(nn.Module): + def __init__(self, channels): + super(Decoder, self).__init__() + self.config = Config() + DecoderBlock = eval('BasicDecBlk') + LateralBlock = eval('BasicLatBlk') + + self.decoder_block4 = DecoderBlock(channels[0], channels[1]) + self.decoder_block3 = DecoderBlock(channels[1], channels[2]) + self.decoder_block2 = DecoderBlock(channels[2], channels[3]) + self.decoder_block1 = DecoderBlock(channels[3], channels[3]//2) + + self.lateral_block4 = LateralBlock(channels[1], channels[1]) + self.lateral_block3 = LateralBlock(channels[2], channels[2]) + self.lateral_block2 = LateralBlock(channels[3], channels[3]) + + if self.config.ms_supervision: + self.conv_ms_spvn_4 = nn.Conv2d(channels[1], 1, 1, 1, 0) + self.conv_ms_spvn_3 = nn.Conv2d(channels[2], 1, 1, 1, 0) + self.conv_ms_spvn_2 = nn.Conv2d(channels[3], 1, 1, 1, 0) + self.conv_out1 = nn.Sequential(nn.Conv2d(channels[3]//2, 1, 1, 1, 0)) + + def forward(self, features): + x, x1, x2, x3, x4 = features + outs = [] + p4 = self.decoder_block4(x4) + _p4 = F.interpolate(p4, size=x3.shape[2:], mode='bilinear', align_corners=True) + _p3 = _p4 + self.lateral_block4(x3) + + p3 = self.decoder_block3(_p3) + _p3 = F.interpolate(p3, size=x2.shape[2:], mode='bilinear', align_corners=True) + _p2 = _p3 + self.lateral_block3(x2) + + p2 = self.decoder_block2(_p2) + _p2 = F.interpolate(p2, size=x1.shape[2:], mode='bilinear', align_corners=True) + _p1 = _p2 + self.lateral_block2(x1) + + _p1 = self.decoder_block1(_p1) + _p1 = F.interpolate(_p1, size=x.shape[2:], mode='bilinear', align_corners=True) + p1_out = self.conv_out1(_p1) + + if self.config.ms_supervision: + outs.append(self.conv_ms_spvn_4(p4)) + outs.append(self.conv_ms_spvn_3(p3)) + outs.append(self.conv_ms_spvn_2(p2)) + outs.append(p1_out) + return outs + + +class RefUNet(nn.Module): + # Refinement + def __init__(self, in_channels=3+1): + super(RefUNet, self).__init__() + self.encoder_1 = nn.Sequential( + nn.Conv2d(in_channels, 64, 3, 1, 1), + nn.Conv2d(64, 64, 3, 1, 1), + nn.BatchNorm2d(64), + nn.ReLU(inplace=True) + ) + + self.encoder_2 = nn.Sequential( + nn.MaxPool2d(2, 2, ceil_mode=True), + nn.Conv2d(64, 64, 3, 1, 1), + nn.BatchNorm2d(64), + nn.ReLU(inplace=True) + ) + + self.encoder_3 = nn.Sequential( + nn.MaxPool2d(2, 2, ceil_mode=True), + nn.Conv2d(64, 64, 3, 1, 1), + nn.BatchNorm2d(64), + nn.ReLU(inplace=True) + ) + + self.encoder_4 = nn.Sequential( + nn.MaxPool2d(2, 2, ceil_mode=True), + nn.Conv2d(64, 64, 3, 1, 1), + nn.BatchNorm2d(64), + nn.ReLU(inplace=True) + ) + + self.pool4 = nn.MaxPool2d(2, 2, ceil_mode=True) + ##### + self.decoder_5 = nn.Sequential( + nn.Conv2d(64, 64, 3, 1, 1), + nn.BatchNorm2d(64), + nn.ReLU(inplace=True) + ) + ##### + self.decoder_4 = nn.Sequential( + nn.Conv2d(128, 64, 3, 1, 1), + nn.BatchNorm2d(64), + nn.ReLU(inplace=True) + ) + + self.decoder_3 = nn.Sequential( + nn.Conv2d(128, 64, 3, 1, 1), + nn.BatchNorm2d(64), + nn.ReLU(inplace=True) + ) + + self.decoder_2 = nn.Sequential( + nn.Conv2d(128, 64, 3, 1, 1), + nn.BatchNorm2d(64), + nn.ReLU(inplace=True) + ) + + self.decoder_1 = nn.Sequential( + nn.Conv2d(128, 64, 3, 1, 1), + nn.BatchNorm2d(64), + nn.ReLU(inplace=True) + ) + + self.conv_d0 = nn.Conv2d(64, 1, 3, 1, 1) + + self.upscore2 = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True) + + def forward(self, x): + outs = [] + if isinstance(x, list): + x = torch.cat(x, dim=1) + hx = x + + hx1 = self.encoder_1(hx) + hx2 = self.encoder_2(hx1) + hx3 = self.encoder_3(hx2) + hx4 = self.encoder_4(hx3) + + hx = self.decoder_5(self.pool4(hx4)) + hx = torch.cat((self.upscore2(hx), hx4), 1) + + d4 = self.decoder_4(hx) + hx = torch.cat((self.upscore2(d4), hx3), 1) + + d3 = self.decoder_3(hx) + hx = torch.cat((self.upscore2(d3), hx2), 1) + + d2 = self.decoder_2(hx) + hx = torch.cat((self.upscore2(d2), hx1), 1) + + d1 = self.decoder_1(hx) + + x = self.conv_d0(d1) + outs.append(x) + return outs diff --git a/py/BiRefNet_legacy/refinement/stem_layer.py b/py/BiRefNet_legacy/refinement/stem_layer.py new file mode 100644 index 0000000..116d546 --- /dev/null +++ b/py/BiRefNet_legacy/refinement/stem_layer.py @@ -0,0 +1,45 @@ +import torch.nn as nn +from BiRefNet_legacy.modules.utils import build_act_layer, build_norm_layer + + +class StemLayer(nn.Module): + r""" Stem layer of InternImage + Args: + in_channels (int): number of input channels + out_channels (int): number of output channels + act_layer (str): activation layer + norm_layer (str): normalization layer + """ + + def __init__(self, + in_channels=3+1, + inter_channels=48, + out_channels=96, + act_layer='GELU', + norm_layer='BN'): + super().__init__() + self.conv1 = nn.Conv2d(in_channels, + inter_channels, + kernel_size=3, + stride=1, + padding=1) + self.norm1 = build_norm_layer( + inter_channels, norm_layer, 'channels_first', 'channels_first' + ) + self.act = build_act_layer(act_layer) + self.conv2 = nn.Conv2d(inter_channels, + out_channels, + kernel_size=3, + stride=1, + padding=1) + self.norm2 = build_norm_layer( + out_channels, norm_layer, 'channels_first', 'channels_first' + ) + + def forward(self, x): + x = self.conv1(x) + x = self.norm1(x) + x = self.act(x) + x = self.conv2(x) + x = self.norm2(x) + return x diff --git a/py/BiRefNet_v2/LICENSE b/py/BiRefNet_v2/LICENSE new file mode 100644 index 0000000..485921e --- /dev/null +++ b/py/BiRefNet_v2/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 ZhengPeng + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/py/BiRefNet_v2/README.md b/py/BiRefNet_v2/README.md new file mode 100644 index 0000000..39f71d7 --- /dev/null +++ b/py/BiRefNet_v2/README.md @@ -0,0 +1,316 @@ +

Bilateral Reference for High-Resolution Dichotomous Image Segmentation

+ +
+ Peng Zheng 1,4,5,6,  + Dehong Gao 2,  + Deng-Ping Fan 1*,  + Li Liu 3,  + Jorma Laaksonen 4,  + Wanli Ouyang 5,  + Nicu Sebe 6 +
+ +
+ 1 Nankai University  2 Northwestern Polytechnical University  3 National University of Defense Technology  +
+ 4 Aalto University  5 Shanghai AI Laboratory  6 University of Trento  +
+ +
+   +   +   +   +   +   +   +   +
+ +
+   +   +   +
+ + +| *DIS-Sample_1* | *DIS-Sample_2* | +| :------------------------------: | :-------------------------------: | +| | | + +This repo is the official implementation of "[**Bilateral Reference for High-Resolution Dichotomous Image Segmentation**](https://arxiv.org/pdf/2401.03407)" (___CAAI AIR 2024___). + +> [!note] +> **We need more GPU resources** to push forward the performance of BiRefNet, especially on *matting* tasks, higher-resolution inference (*2K*), and more *efficient* model design. If you are happy to cooperate, please contact me at zhengpeng0108@gmail.com. + +## News :newspaper: +* **`Aug 30, 2024`:** We uploaded notebooks in `tutorials` to run the inference and ONNX conversion locally. +* **`Aug 23, 2024`:** Our BiRefNet is now officially released [online](https://www.sciopen.com/article/10.26599/AIR.2024.9150038) on CAAI AIR journal. And thanks to the [press release](https://www.eurekalert.org/news-releases/1055380). +* **`Aug 19, 2024`:** We uploaded the ONNX model files of all weights in the [GitHub release](https://github.com/ZhengPeng7/BiRefNet/releases/tag/v1) and [GDrive folder](https://drive.google.com/drive/u/0/folders/1kZM55bwsRdS__bdnsXpkmH6QPyza-9-N). Check out the **ONNX conversion** part in [model zoo](https://github.com/ZhengPeng7/BiRefNet?tab=readme-ov-file#model-zoo) for more details. +* **`Jul 30, 2024`:** Thanks to @not-lain for his kind efforts in adding BiRefNet to the official huggingface.js [repo](https://github.com/huggingface/huggingface.js/blob/3a8651fbc6508920475564a692bf0e5b601d9343/packages/tasks/src/model-libraries-snippets.ts#L763). +* **`Jul 28, 2024`:** We released the [Colab demo for box-guided segmentation](https://colab.research.google.com/drive/1B6aKZ3ekcvKMkSBn0N5mCASLUYMp0whK). +* **`Jul 15, 2024`:** We deployed our BiRefNet on [Hugging Face Models](https://huggingface.co/ZhengPeng7/BiRefNet) for users to easily load it in one line code. +* **`Jun 21, 2024`:** We released and uploaded the Chinese version of our original paper to my [GDrive](https://drive.google.com/file/d/1aBnJ_R9lbnC2dm8dqD0-pzP2Cu-U1Xpt/view). +* **`May 28, 2024`:** We hold a [model zoo](https://github.com/ZhengPeng7/BiRefNet?tab=readme-ov-file#model-zoo) with well-trained weights of our BiRefNet in different sizes and for different tasks, including general use, matting segmentation, DIS, HRSOD, COD, etc. +* **`May 7, 2024`:** We also released the [Colab demo for multiple images inference](https://colab.research.google.com/drive/14Dqg7oeBkFEtchaHLNpig2BcdkZEogba). Many thanks to @rishabh063 for his support on it. +* **`Apr 9, 2024`:** Thanks to [Features and Labels Inc.](https://fal.ai/) for deploying a cool online BiRefNet [inference API](https://fal.ai/models/fal-ai/birefnet/playground) and providing me with strong GPU resources for 4 months on more extensive experiments! +* **`Mar 7, 2024`:** We released BiRefNet codes, the well-trained weights for all tasks in the original papers, and all related stuff in my [GDrive folder](https://drive.google.com/drive/folders/1s2Xe0cjq-2ctnJBR24563yMSCOu4CcxM). Meanwhile, we also deployed our BiRefNet on [Hugging Face Spaces](https://huggingface.co/spaces/ZhengPeng7/BiRefNet_demo) for easier online use and released the [Colab demo for inference and evaluation](https://colab.research.google.com/drive/1MaEiBfJ4xIaZZn0DqKrhydHB8X97hNXl). +* **`Jan 7, 2024`:** We released our paper on [arXiv](https://arxiv.org/pdf/2401.03407). + + +## :rocket: Load BiRefNet in _ONE LINE_ by HuggingFace, check more: [![BiRefNet](https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Models-blue)](https://huggingface.co/ZhengPeng7/birefnet) +```python +from transformers import AutoModelForImageSegmentation +birefnet = AutoModelForImageSegmentation.from_pretrained('zhengpeng7/BiRefNet', trust_remote_code=True) +``` +## :flight_arrival: Inference Partner: +We are really happy to collaborate with [FAL](https://fal.ai) to deploy the **inference API** of BiRefNet. You can access this service via the link below: ++ https://fal.ai/models/fal-ai/birefnet + +Our BiRefNet has achieved SOTA on many similar HR tasks: + +**DIS**: [![PWC](https://img.shields.io/endpoint.svg?url=https://paperswithcode.com/badge/bilateral-reference-for-high-resolution/dichotomous-image-segmentation-on-dis-te1)](https://paperswithcode.com/sota/dichotomous-image-segmentation-on-dis-te1?p=bilateral-reference-for-high-resolution) [![PWC](https://img.shields.io/endpoint.svg?url=https://paperswithcode.com/badge/bilateral-reference-for-high-resolution/dichotomous-image-segmentation-on-dis-te2)](https://paperswithcode.com/sota/dichotomous-image-segmentation-on-dis-te2?p=bilateral-reference-for-high-resolution) [![PWC](https://img.shields.io/endpoint.svg?url=https://paperswithcode.com/badge/bilateral-reference-for-high-resolution/dichotomous-image-segmentation-on-dis-te3)](https://paperswithcode.com/sota/dichotomous-image-segmentation-on-dis-te3?p=bilateral-reference-for-high-resolution) [![PWC](https://img.shields.io/endpoint.svg?url=https://paperswithcode.com/badge/bilateral-reference-for-high-resolution/dichotomous-image-segmentation-on-dis-te4)](https://paperswithcode.com/sota/dichotomous-image-segmentation-on-dis-te4?p=bilateral-reference-for-high-resolution) [![PWC](https://img.shields.io/endpoint.svg?url=https://paperswithcode.com/badge/bilateral-reference-for-high-resolution/dichotomous-image-segmentation-on-dis-vd)](https://paperswithcode.com/sota/dichotomous-image-segmentation-on-dis-vd?p=bilateral-reference-for-high-resolution) + +
Figure of Comparison on DIS Papers with Codes (by the time of this work): + + + + + +
+
+ +**COD**:[![PWC](https://img.shields.io/endpoint.svg?url=https://paperswithcode.com/badge/bilateral-reference-for-high-resolution/camouflaged-object-segmentation-on-cod)](https://paperswithcode.com/sota/camouflaged-object-segmentation-on-cod?p=bilateral-reference-for-high-resolution) [![PWC](https://img.shields.io/endpoint.svg?url=https://paperswithcode.com/badge/bilateral-reference-for-high-resolution/camouflaged-object-segmentation-on-nc4k)](https://paperswithcode.com/sota/camouflaged-object-segmentation-on-nc4k?p=bilateral-reference-for-high-resolution) [![PWC](https://img.shields.io/endpoint.svg?url=https://paperswithcode.com/badge/bilateral-reference-for-high-resolution/camouflaged-object-segmentation-on-camo)](https://paperswithcode.com/sota/camouflaged-object-segmentation-on-camo?p=bilateral-reference-for-high-resolution) [![PWC](https://img.shields.io/endpoint.svg?url=https://paperswithcode.com/badge/bilateral-reference-for-high-resolution/camouflaged-object-segmentation-on-chameleon)](https://paperswithcode.com/sota/camouflaged-object-segmentation-on-chameleon?p=bilateral-reference-for-high-resolution) + +
Figure of Comparison on COD Papers with Codes (by the time of this work): + + + +
+
+ +**HRSOD**: [![PWC](https://img.shields.io/endpoint.svg?url=https://paperswithcode.com/badge/bilateral-reference-for-high-resolution/rgb-salient-object-detection-on-davis-s)](https://paperswithcode.com/sota/rgb-salient-object-detection-on-davis-s?p=bilateral-reference-for-high-resolution) [![PWC](https://img.shields.io/endpoint.svg?url=https://paperswithcode.com/badge/bilateral-reference-for-high-resolution/rgb-salient-object-detection-on-hrsod)](https://paperswithcode.com/sota/rgb-salient-object-detection-on-hrsod?p=bilateral-reference-for-high-resolution) [![PWC](https://img.shields.io/endpoint.svg?url=https://paperswithcode.com/badge/bilateral-reference-for-high-resolution/rgb-salient-object-detection-on-uhrsd)](https://paperswithcode.com/sota/rgb-salient-object-detection-on-uhrsd?p=bilateral-reference-for-high-resolution) [![PWC](https://img.shields.io/endpoint.svg?url=https://paperswithcode.com/badge/bilateral-reference-for-high-resolution/salient-object-detection-on-duts-te)](https://paperswithcode.com/sota/salient-object-detection-on-duts-te?p=bilateral-reference-for-high-resolution) [![PWC](https://img.shields.io/endpoint.svg?url=https://paperswithcode.com/badge/bilateral-reference-for-high-resolution/salient-object-detection-on-dut-omron)](https://paperswithcode.com/sota/salient-object-detection-on-dut-omron?p=bilateral-reference-for-high-resolution) + +
Figure of Comparison on HRSOD Papers with Codes (by the time of this work): + + + + + +
+
+ +#### Try our online demos for inference: + ++ **Inference and evaluation** of your given weights: [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1MaEiBfJ4xIaZZn0DqKrhydHB8X97hNXl) ++ **Online Inference with GUI** with adjustable resolutions: [![Hugging Face Spaces](https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Spaces-blue)](https://huggingface.co/spaces/ZhengPeng7/BiRefNet_demo) ++ Online **Multiple Images Inference** on Colab: [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/14Dqg7oeBkFEtchaHLNpig2BcdkZEogba) + + + + + +## Model Zoo + +> For more general use of our BiRefNet, I extended the original academic one to more general ones for better real-life application. +> +> Datasets and datasets are suggested to be downloaded from official pages. But you can also download the packaged ones: [DIS](https://drive.google.com/drive/folders/1hZW6tAGPJwo9mPS7qGGGdpxuvuXiyoMJ), [HRSOD](https://drive.google.com/drive/folders/18_hAE3QM4cwAzEAKXuSNtKjmgFXTQXZN), [COD](https://drive.google.com/drive/folders/1EyHmKWsXfaCR9O0BiZEc3roZbRcs4ECO), [Backbones](https://drive.google.com/drive/folders/1cmce_emsS8A5ha5XT2c_CZiJzlLM81ms). +> +> Find performances (almost all metrics) of all models in the `exp-TASK_SETTINGS` folders in [[**stuff**](https://drive.google.com/drive/folders/1s2Xe0cjq-2ctnJBR24563yMSCOu4CcxM)]. + + + +
Models in the original paper, for comparison on benchmarks: + +| Task | Training Sets | Backbone | Download | +| :---: | :-------------------------: | :-----------: | :----------------------------------------------------------: | +| DIS | DIS5K-TR | swin_v1_large | [google-drive](https://drive.google.com/file/d/1J90LucvDQaS3R_-9E7QUh1mgJ8eQvccb/view) | +| COD | COD10K-TR, CAMO-TR | swin_v1_large | [google-drive](https://drive.google.com/file/d/1tM5M72k7a8aKF-dYy-QXaqvfEhbFaWkC/view) | +| HRSOD | DUTS-TR | swin_v1_large | [google-drive](https://drive.google.com/file/d/1f7L0Pb1Y3RkOMbqLCW_zO31dik9AiUFa/view) | +| HRSOD | HRSOD-TR | swin_v1_large | google-drive | +| HRSOD | UHRSD-TR | swin_v1_large | google-drive | +| HRSOD | DUTS-TR, HRSOD-TR | swin_v1_large | [google-drive](https://drive.google.com/file/d/1WJooyTkhoDLllaqwbpur_9Hle0XTHEs_/view) | +| HRSOD | DUTS-TR, UHRSD-TR | swin_v1_large | [google-drive](https://drive.google.com/file/d/1Pu1mv3ORobJatIuUoEuZaWDl2ylP3Gw7/view) | +| HRSOD | HRSOD-TR, UHRSD-TR | swin_v1_large | [google-drive](https://drive.google.com/file/d/1xEh7fsgWGaS5c3IffMswasv0_u-aVM9E/view) | +| HRSOD | DUTS-TR, HRSOD-TR, UHRSD-TR | swin_v1_large | [google-drive](https://drive.google.com/file/d/13FaxyyOwyCddfZn2vZo1xG1KNZ3cZ-6B/view) | + +
+ + + +
Models trained with customed data (general, matting), for general use in practical application: + +| Task | Training Sets | Backbone | Test Set | Metric (S, wF[, HCE]) | Download | +| :-----------------------: | :----------------------------------------------------------: | :-----------: | :-------: | :-------------------: | :----------------------------------------------------------: | +| **general use** | DIS5K-TR,DIS-TEs, DUTS-TR_TE,HRSOD-TR_TE,UHRSD-TR_TE, HRS10K-TR_TE, TR-P3M-10k, TE-P3M-500-NP, TE-P3M-500-P, TR-humans | swin_v1_large | DIS-VD | 0.911, 0.875, 1069 | [google-drive](https://drive.google.com/file/d/1_IfUnu8Fpfn-nerB89FzdNXQ7zk6FKxc/view) | +| **general use** | DIS5K-TR,DIS-TEs, DUTS-TR_TE,HRSOD-TR_TE,UHRSD-TR_TE, HRS10K-TR_TE, TR-P3M-10k, TE-P3M-500-NP, TE-P3M-500-P, TR-humans | swin_v1_tiny | DIS-VD | 0.882, 0.830, 1175 | [google-drive](https://drive.google.com/file/d/1fzInDWiE2n65tmjaHDSZpqhL0VME6-Yl/view) | +| **general use** | DIS5K-TR, DIS-TEs | swin_v1_large | DIS-VD | 0.907, 0.865, 1059 | [google-drive](https://drive.google.com/file/d/1P6NJzG3Jf1sl7js2q1CPC3yqvBn_O8UJ/view) | +| **matting segmentation** | [P3M-10k](https://github.com/JizhiziLi/P3M), [humans](https://huggingface.co/datasets/schirrmacher/humans) | swin_v1_large | P3M-500-P | 0.983, 0.989 | [google-drive](https://drive.google.com/file/d/1uUeXjEUoD2XF_6YjD_fsct-TJp7TFiqh) | + +
+ + + +
Segmentation with box guidance: + ++ Given box guidance: [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1B6aKZ3ekcvKMkSBn0N5mCASLUYMp0whK) + +
+ + + +
Model efficiency: + +> Screenshot from the original paper. All tests are conducted on a single A100 GPU. + + + +
+ + + +
ONNX conversion: + +> We converted from `.pth` weights files to `.onnx` files. +> We referred a lot to the [Kazuhito00/BiRefNet-ONNX-Sample](https://github.com/Kazuhito00/BiRefNet-ONNX-Sample), many thanks to @Kazuhito00. + ++ Check our [Colab demo for ONNX conversion](https://colab.research.google.com/drive/1z6OruR52LOvDDpnp516F-N4EyPGrp5om) or the [notebook file for local running](https://drive.google.com/file/d/1cgL2qyvOO5q3ySfhytypX46swdQwZLrJ), where you can do the conversion/inference by yourself and find all relevant info. ++ As tested, BiRefNets with SwinL (default backbone) cost `~90%` more time (the inference costs `~165ms` on an A100 GPU) using ONNX files. Meanwhile, BiRefNets with SwinT (lightweight) cost `~75%` more time (the inference costs `~93.8ms` on an A100 GPU) using ONNX files. Input resolution is `1024x1024` as default. ++ The results of the original pth files and the converted onnx files are slightly different, which is acceptable. ++ Pay attention to the compatibility among `onnxruntime-gpu, CUDA, and CUDNN` (we use `torch==2.0.1, cuda=11.8` here). + + +
+ +## Third-Party Creations + +> Concerning edge devices with less computing power, we provide a lightweight version with `swin_v1_tiny` as the backbone, which is x4+ faster and x5+ smaller. The details can be found in [this issue](https://github.com/ZhengPeng7/BiRefNet/issues/11#issuecomment-2041033576) and links there. + +We found there've been some 3rd party applications based on our BiRefNet. Many thanks for their contribution to the community! +Choose the one you like to try with clicks instead of codes: +1. **Applications**: + + Thanks [**lbq779660843/BiRefNet-Tensorrt**](https://github.com/lbq779660843/BiRefNet-Tensorrt) and [**yuanyang1991/birefnet_tensorrt**](https://github.com/yuanyang1991/birefnet_tensorrt): they both provided the project to convert BiRefNet to **TensorRT**, which is faster and better for deployment. Their repos offer solid local establishment (Win and Linux) and [colab demo](https://colab.research.google.com/drive/1r8GkFPyMMO0OkMX6ih5FjZnUCQrl2SHV?usp=sharing), respectively. And @yuanyang1991 kindly offered the comparison among the inference efficiency of naive PyTorch, ONNX, and TensorRT on an RTX 4080S: + +| Methods | [Pytorch](https://drive.google.com/file/d/1_IfUnu8Fpfn-nerB89FzdNXQ7zk6FKxc/view) | [ONNX](https://drive.google.com/drive/u/0/folders/1kZM55bwsRdS__bdnsXpkmH6QPyza-9-N) | TensorRT | +|:------------------------------------------------------------------------------------:|:--------------:|:--------------:|:--------------:| +|        First Inference Time       | 0.71s | 5.32s | **0.17s** | + +| Methods | [Pytorch](https://drive.google.com/file/d/1_IfUnu8Fpfn-nerB89FzdNXQ7zk6FKxc/view) | [ONNX](https://drive.google.com/drive/u/0/folders/1kZM55bwsRdS__bdnsXpkmH6QPyza-9-N) | TensorRT | +|:------------------------------------------------------------------------------------:|:--------------:|:--------------:|:--------------:| +| Avg Inf Time (excluding 1st) | 0.15s | 4.43s | **0.11s** | + + + Thanks [**dimitribarbot/sd-webui-birefnet**](https://github.com/dimitribarbot/sd-webui-birefnet): this project allows to add a BiRefNet section to the original **Stable Diffusion WebUI**'s Extras tab. +

+ + + Thanks [**fal.ai/birefnet**](https://fal.ai/models/birefnet): this project on `fal.ai` encapsulates BiRefNet **online** with more useful options in **UI** and **API** to call the model. +

+ + + Thanks [**ZHO-ZHO-ZHO/ComfyUI-BiRefNet-ZHO**](https://github.com/ZHO-ZHO-ZHO/ComfyUI-BiRefNet-ZHO): this project further improves the **UI** for BiRefNet in ComfyUI, especially for **video data**. +

+ + + + + Thanks [**viperyl/ComfyUI-BiRefNet**](https://github.com/viperyl/ComfyUI-BiRefNet): this project packs BiRefNet as **ComfyUI nodes**, and makes this SOTA model easier use for everyone. +

+ + + Thanks [**Rishabh**](https://github.com/rishabh063) for offering a demo for the [easier multiple images inference on colab](https://colab.research.google.com/drive/14Dqg7oeBkFEtchaHLNpig2BcdkZEogba). + +2. **More Visual Comparisons** + + Thanks [**twitter.com/ZHOZHO672070**](https://twitter.com/ZHOZHO672070) for the comparison with more background-removal methods in images: + + + + + Thanks [**twitter.com/toyxyz3**](https://twitter.com/toyxyz3) for the comparison with more background-removal methods in videos: + + + + + + +## Usage + +#### Environment Setup + +```shell +# PyTorch==2.0.1 is used for faster training with compilation. +conda create -n birefnet python=3.9 -y && conda activate birefnet +pip install -r requirements.txt +``` + +#### Dataset Preparation + +Download combined training / test sets I have organized well from: [DIS](https://drive.google.com/drive/folders/1hZW6tAGPJwo9mPS7qGGGdpxuvuXiyoMJ)--[COD](https://drive.google.com/drive/folders/1EyHmKWsXfaCR9O0BiZEc3roZbRcs4ECO)--[HRSOD](https://drive.google.com/drive/folders/18_hAE3QM4cwAzEAKXuSNtKjmgFXTQXZN) or the single official ones in the `single_ones` folder, or their official pages. You can also find the same ones on my **BaiduDisk**: [DIS](https://pan.baidu.com/s/1O_pQIGAE4DKqL93xOxHpxw?pwd=PSWD)--[COD](https://pan.baidu.com/s/1RnxAzaHSTGBC1N6r_RfeqQ?pwd=PSWD)--[HRSOD](https://pan.baidu.com/s/1_Del53_0lBuG0DKJJAk4UA?pwd=PSWD). + +#### Weights Preparation + +Download backbone weights from [my google-drive folder](https://drive.google.com/drive/folders/1s2Xe0cjq-2ctnJBR24563yMSCOu4CcxM) or their official pages. + +## Run + +```shell +# Train & Test & Evaluation +./train_test.sh RUN_NAME GPU_NUMBERS_FOR_TRAINING GPU_NUMBERS_FOR_TEST +# Example: ./train_test.sh tmp-proj 0,1,2,3,4,5,6,7 0 + +# See train.sh / test.sh for only training / test-evaluation. +# After the evaluation, run `gen_best_ep.py` to select the best ckpt from a specific metric (you choose it from Sm, wFm, HCE (DIS only)). +``` + +#### Well-trained weights: + +Download the `BiRefNet-{TASK}-{EPOCH}.pth` from [[**stuff**](https://drive.google.com/drive/folders/1s2Xe0cjq-2ctnJBR24563yMSCOu4CcxM)]. Info of the corresponding (predicted\_maps/performance/training\_log) weights can be also found in folders like `exp-BiRefNet-{TASK_SETTINGS}` in the same directory. + +You can also download the weights from the release of this repo. + +The results might be a bit different from those in the original paper, you can see them in the `eval_results-BiRefNet-{TASK_SETTINGS}` folder in each `exp-xx`, we will update them in the following days. Due to the very high cost I used (A100-80G x 8) which many people cannot afford to (including myself....), I re-trained BiRefNet on a single A100-40G only and achieve the performance on the same level (even better). It means you can directly train the model on a single GPU with 36.5G+ memory. BTW, 5.5G GPU memory is needed for inference in 1024x1024. (I personally paid a lot for renting an A100-40G to re-train BiRefNet on the three tasks... T_T. Hope it can help you.) + +But if you have more and more powerful GPUs, you can set GPU IDs and increase the batch size in `config.py` to accelerate the training. We have made all this kind of things adaptive in scripts to seamlessly switch between single-card training and multi-card training. Enjoy it :) + +#### Some of my messages: + +This project was originally built for DIS only. But after the updates one by one, I made it larger and larger with many functions embedded together. Finally, you can **use it for any binary image segmentation tasks**, such as DIS/COD/SOD, medical image segmentation, anomaly segmentation, etc. You can eaily open/close below things (usually in `config.py`): ++ Multi-GPU training: open/close with one variable. ++ Backbone choices: Swin_v1, PVT_v2, ConvNets, ... ++ Weighted losses: BCE, IoU, SSIM, MAE, Reg, ... ++ Adversarial loss for binary segmentation (proposed in my previous work [MCCL](https://arxiv.org/pdf/2302.14485)). ++ Training tricks: multi-scale supervision, freezing backbone, multi-scale input... ++ Data collator: loading all in memory, smooth combination of different datasets for combined training and test. ++ ... +I really hope you enjoy this project and use it in more works to achieve new SOTAs. + + +### Quantitative Results + +

+ +

+ + + +### Qualitative Results + +

+ +

+ + + +### Citation + +``` +@article{zheng2024birefnet, + title={Bilateral Reference for High-Resolution Dichotomous Image Segmentation}, + author={Zheng, Peng and Gao, Dehong and Fan, Deng-Ping and Liu, Li and Laaksonen, Jorma and Ouyang, Wanli and Sebe, Nicu}, + journal={CAAI Artificial Intelligence Research}, + volume = {3}, + pages = {9150038}, + year={2024} +} +``` + + + +## Contact + +Any questions, discussions, or even complaints, feel free to leave issues here or send me e-mails (zhengpeng0108@gmail.com). You can also join the Discord Group (https://discord.gg/d9NN5sgFrq) or QQ Group (https://qm.qq.com/q/y6WPy7WOIK) if you want to talk a lot publicly. + diff --git a/py/BiRefNet_v2/__init__.py b/py/BiRefNet_v2/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/py/BiRefNet_v2/config.py b/py/BiRefNet_v2/config.py new file mode 100644 index 0000000..c333160 --- /dev/null +++ b/py/BiRefNet_v2/config.py @@ -0,0 +1,174 @@ +import os +import math + + +class Config(): + def __init__(self) -> None: + # PATH settings + # Make up your file system as: SYS_HOME_DIR/codes/dis/BiRefNet, SYS_HOME_DIR/datasets/dis/xx, SYS_HOME_DIR/weights/xx + if os.name == 'nt': + self.sys_home_dir = os.environ['USERPROFILE'] # For windows system + else: + self.sys_home_dir = os.environ['HOME'] # For Linux system + + # TASK settings + self.task = ['DIS5K', 'COD', 'HRSOD', 'General', 'Matting'][0] + self.training_set = { + 'DIS5K': ['DIS-TR', 'DIS-TR+DIS-TE1+DIS-TE2+DIS-TE3+DIS-TE4'][0], + 'COD': 'TR-COD10K+TR-CAMO', + 'HRSOD': ['TR-DUTS', 'TR-HRSOD', 'TR-UHRSD', 'TR-DUTS+TR-HRSOD', 'TR-DUTS+TR-UHRSD', 'TR-HRSOD+TR-UHRSD', 'TR-DUTS+TR-HRSOD+TR-UHRSD'][5], + 'General': 'DIS-TE1+DIS-TE2+DIS-TE3+DIS-TE4+DIS-TR+TR-HRSOD+TE-HRSOD+TR-HRS10K+TE-HRS10K+TR-UHRSD+TE-UHRSD+TR-P3M-10k+TE-P3M-500-NP+TE-P3M-500-P+TR-humans', # leave DIS-VD for evaluation. + 'Matting': 'TR-P3M-10k+TE-P3M-500-NP+TR-humans+TR-Distrinctions-646', + }[self.task] + self.prompt4loc = ['dense', 'sparse'][0] + + # Faster-Training settings + self.load_all = False # Turn it on/off by your case. It may consume a lot of CPU memory. And for multi-GPU (N), it would cost N times the CPU memory to load the data. + self.use_fp16 = False # It may cause nan in training. + self.compile = True and (not self.use_fp16) # 1. Trigger CPU memory leak in some extend, which is an inherent problem of PyTorch. + # Machines with > 70GB CPU memory can run the whole training on DIS5K with default setting. + # 2. Higher PyTorch version may fix it: https://github.com/pytorch/pytorch/issues/119607. + # 3. But compile in Pytorch > 2.0.1 seems to bring no acceleration for training. + self.precisionHigh = True + + # MODEL settings + self.ms_supervision = True + self.out_ref = self.ms_supervision and True + self.dec_ipt = True + self.dec_ipt_split = True + self.cxt_num = [0, 3][1] # multi-scale skip connections from encoder + self.mul_scl_ipt = ['', 'add', 'cat'][2] + self.dec_att = ['', 'ASPP', 'ASPPDeformable'][2] + self.squeeze_block = ['', 'BasicDecBlk_x1', 'ResBlk_x4', 'ASPP_x3', 'ASPPDeformable_x3'][1] + self.dec_blk = ['BasicDecBlk', 'ResBlk'][0] + + # TRAINING settings + self.batch_size = 4 + self.finetune_last_epochs = [ + ('IoU', 0), + { + 'DIS5K': ('IoU', -30), + 'COD': ('IoU', -20), + 'HRSOD': ('IoU', -20), + 'General': ('MAE', -10), + 'Matting': ('MAE', -10), + }[self.task] + ][1] # choose 0 to skip + self.lr = (1e-4 if 'DIS5K' in self.task else 1e-5) * math.sqrt(self.batch_size / 4) # DIS needs high lr to converge faster. Adapt the lr linearly + self.size = 1024 + self.num_workers = max(4, self.batch_size) # will be decrease to min(it, batch_size) at the initialization of the data_loader + + # Backbone settings + self.bb = [ + 'vgg16', 'vgg16bn', 'resnet50', # 0, 1, 2 + 'swin_v1_t', 'swin_v1_s', # 3, 4 + 'swin_v1_b', 'swin_v1_l', # 5-bs9, 6-bs4 + 'pvt_v2_b0', 'pvt_v2_b1', # 7, 8 + 'pvt_v2_b2', 'pvt_v2_b5', # 9-bs10, 10-bs5 + ][6] + self.lateral_channels_in_collection = { + 'vgg16': [512, 256, 128, 64], 'vgg16bn': [512, 256, 128, 64], 'resnet50': [1024, 512, 256, 64], + 'pvt_v2_b2': [512, 320, 128, 64], 'pvt_v2_b5': [512, 320, 128, 64], + 'swin_v1_b': [1024, 512, 256, 128], 'swin_v1_l': [1536, 768, 384, 192], + 'swin_v1_t': [768, 384, 192, 96], 'swin_v1_s': [768, 384, 192, 96], + 'pvt_v2_b0': [256, 160, 64, 32], 'pvt_v2_b1': [512, 320, 128, 64], + }[self.bb] + if self.mul_scl_ipt == 'cat': + self.lateral_channels_in_collection = [channel * 2 for channel in self.lateral_channels_in_collection] + self.cxt = self.lateral_channels_in_collection[1:][::-1][-self.cxt_num:] if self.cxt_num else [] + + # MODEL settings - inactive + self.lat_blk = ['BasicLatBlk'][0] + self.dec_channels_inter = ['fixed', 'adap'][0] + self.refine = ['', 'itself', 'RefUNet', 'Refiner', 'RefinerPVTInChannels4'][0] + self.progressive_ref = self.refine and True + self.ender = self.progressive_ref and False + self.scale = self.progressive_ref and 2 + self.auxiliary_classification = False # Only for DIS5K, where class labels are saved in `dataset.py`. + self.refine_iteration = 1 + self.freeze_bb = False + self.model = [ + 'BiRefNet', + ][0] + + # TRAINING settings - inactive + self.preproc_methods = ['flip', 'enhance', 'rotate', 'pepper', 'crop'][:4] + self.optimizer = ['Adam', 'AdamW'][1] + self.lr_decay_epochs = [1e5] # Set to negative N to decay the lr in the last N-th epoch. + self.lr_decay_rate = 0.5 + # Loss + if self.task not in ['Matting']: + self.lambdas_pix_last = { + # not 0 means opening this loss + # original rate -- 1 : 30 : 1.5 : 0.2, bce x 30 + 'bce': 30 * 1, # high performance + 'iou': 0.5 * 1, # 0 / 255 + 'iou_patch': 0.5 * 0, # 0 / 255, win_size = (64, 64) + 'mae': 30 * 0, + 'mse': 30 * 0, # can smooth the saliency map + 'triplet': 3 * 0, + 'reg': 100 * 0, + 'ssim': 10 * 1, # help contours, + 'cnt': 5 * 0, # help contours + 'structure': 5 * 0, # structure loss from codes of MVANet. A little improvement on DIS-TE[1,2,3], a bit more decrease on DIS-TE4. + } + else: + self.lambdas_pix_last = { + # not 0 means opening this loss + # original rate -- 1 : 30 : 1.5 : 0.2, bce x 30 + 'bce': 30 * 0, # high performance + 'iou': 0.5 * 0, # 0 / 255 + 'iou_patch': 0.5 * 0, # 0 / 255, win_size = (64, 64) + 'mae': 100 * 1, + 'mse': 30 * 0, # can smooth the saliency map + 'triplet': 3 * 0, + 'reg': 100 * 0, + 'ssim': 10 * 1, # help contours, + 'cnt': 5 * 0, # help contours + 'structure': 5 * 0, # structure loss from codes of MVANet. A little improvement on DIS-TE[1,2,3], a bit more decrease on DIS-TE4. + } + self.lambdas_cls = { + 'ce': 5.0 + } + # Adv + self.lambda_adv_g = 10. * 0 # turn to 0 to avoid adv training + self.lambda_adv_d = 3. * (self.lambda_adv_g > 0) + + # PATH settings - inactive + self.data_root_dir = os.path.join(self.sys_home_dir, 'datasets/dis') + self.weights_root_dir = os.path.join(self.sys_home_dir, 'weights') + self.weights = { + 'pvt_v2_b2': os.path.join(self.weights_root_dir, 'pvt_v2_b2.pth'), + 'pvt_v2_b5': os.path.join(self.weights_root_dir, ['pvt_v2_b5.pth', 'pvt_v2_b5_22k.pth'][0]), + 'swin_v1_b': os.path.join(self.weights_root_dir, ['swin_base_patch4_window12_384_22kto1k.pth', 'swin_base_patch4_window12_384_22k.pth'][0]), + 'swin_v1_l': os.path.join(self.weights_root_dir, ['swin_large_patch4_window12_384_22kto1k.pth', 'swin_large_patch4_window12_384_22k.pth'][0]), + 'swin_v1_t': os.path.join(self.weights_root_dir, ['swin_tiny_patch4_window7_224_22kto1k_finetune.pth'][0]), + 'swin_v1_s': os.path.join(self.weights_root_dir, ['swin_small_patch4_window7_224_22kto1k_finetune.pth'][0]), + 'pvt_v2_b0': os.path.join(self.weights_root_dir, ['pvt_v2_b0.pth'][0]), + 'pvt_v2_b1': os.path.join(self.weights_root_dir, ['pvt_v2_b1.pth'][0]), + } + + # Callbacks - inactive + self.verbose_eval = True + self.only_S_MAE = False + self.SDPA_enabled = False # Bugs. Slower and errors occur in multi-GPUs + + # others + self.device = [0, 'cpu'][0] # .to(0) == .to('cuda:0') + + self.batch_size_valid = 1 + self.rand_seed = 7 + run_sh_file = [f for f in os.listdir('.') if 'train.sh' == f] + [os.path.join('..', f) for f in os.listdir('..') if 'train.sh' == f] + if run_sh_file: + with open(run_sh_file[0], 'r') as f: + lines = f.readlines() + self.save_last = int([l.strip() for l in lines if '"{}")'.format(self.task) in l and 'val_last=' in l][0].split('val_last=')[-1].split()[0]) + + def print_task(self) -> None: + # Return task for choosing settings in shell scripts. + print(self.task) + +if __name__ == '__main__': + config = Config() + config.print_task() + diff --git a/py/BiRefNet_v2/dataset.py b/py/BiRefNet_v2/dataset.py new file mode 100644 index 0000000..a7d9e13 --- /dev/null +++ b/py/BiRefNet_v2/dataset.py @@ -0,0 +1,118 @@ +import os +import cv2 +from tqdm import tqdm +from PIL import Image +from torch.utils import data +from torchvision import transforms + +from .image_proc import preproc +from .config import Config +from .utils import path_to_image + + +Image.MAX_IMAGE_PIXELS = None # remove DecompressionBombWarning +config = Config() +_class_labels_TR_sorted = ( + 'Airplane, Ant, Antenna, Archery, Axe, BabyCarriage, Bag, BalanceBeam, Balcony, Balloon, Basket, BasketballHoop, Beatle, Bed, Bee, Bench, Bicycle, ' + 'BicycleFrame, BicycleStand, Boat, Bonsai, BoomLift, Bridge, BunkBed, Butterfly, Button, Cable, CableLift, Cage, Camcorder, Cannon, Canoe, Car, ' + 'CarParkDropArm, Carriage, Cart, Caterpillar, CeilingLamp, Centipede, Chair, Clip, Clock, Clothes, CoatHanger, Comb, ConcretePumpTruck, Crack, Crane, ' + 'Cup, DentalChair, Desk, DeskChair, Diagram, DishRack, DoorHandle, Dragonfish, Dragonfly, Drum, Earphone, Easel, ElectricIron, Excavator, Eyeglasses, ' + 'Fan, Fence, Fencing, FerrisWheel, FireExtinguisher, Fishing, Flag, FloorLamp, Forklift, GasStation, Gate, Gear, Goal, Golf, GymEquipment, Hammock, ' + 'Handcart, Handcraft, Handrail, HangGlider, Harp, Harvester, Headset, Helicopter, Helmet, Hook, HorizontalBar, Hydrovalve, IroningTable, Jewelry, Key, ' + 'KidsPlayground, Kitchenware, Kite, Knife, Ladder, LaundryRack, Lightning, Lobster, Locust, Machine, MachineGun, MagazineRack, Mantis, Medal, MemorialArchway, ' + 'Microphone, Missile, MobileHolder, Monitor, Mosquito, Motorcycle, MovingTrolley, Mower, MusicPlayer, MusicStand, ObservationTower, Octopus, OilWell, ' + 'OlympicLogo, OperatingTable, OutdoorFitnessEquipment, Parachute, Pavilion, Piano, Pipe, PlowHarrow, PoleVault, Punchbag, Rack, Racket, Rifle, Ring, Robot, ' + 'RockClimbing, Rope, Sailboat, Satellite, Scaffold, Scale, Scissor, Scooter, Sculpture, Seadragon, Seahorse, Seal, SewingMachine, Ship, Shoe, ShoppingCart, ' + 'ShoppingTrolley, Shower, Shrimp, Signboard, Skateboarding, Skeleton, Skiing, Spade, SpeedBoat, Spider, Spoon, Stair, Stand, Stationary, SteeringWheel, ' + 'Stethoscope, Stool, Stove, StreetLamp, SweetStand, Swing, Sword, TV, Table, TableChair, TableLamp, TableTennis, Tank, Tapeline, Teapot, Telescope, Tent, ' + 'TobaccoPipe, Toy, Tractor, TrafficLight, TrafficSign, Trampoline, TransmissionTower, Tree, Tricycle, TrimmerCover, Tripod, Trombone, Truck, Trumpet, Tuba, ' + 'UAV, Umbrella, UnevenBars, UtilityPole, VacuumCleaner, Violin, Wakesurfing, Watch, WaterTower, WateringPot, Well, WellLid, Wheel, Wheelchair, WindTurbine, Windmill, WineGlass, WireWhisk, Yacht' +) +class_labels_TR_sorted = _class_labels_TR_sorted.split(', ') + + +class MyData(data.Dataset): + def __init__(self, datasets, image_size, is_train=True): + self.size_train = image_size + self.size_test = image_size + self.keep_size = not config.size + self.data_size = (config.size, config.size) + self.is_train = is_train + self.load_all = config.load_all + self.device = config.device + valid_extensions = ['.png', '.jpg', '.PNG', '.JPG', '.JPEG'] + + if self.is_train and config.auxiliary_classification: + self.cls_name2id = {_name: _id for _id, _name in enumerate(class_labels_TR_sorted)} + self.transform_image = transforms.Compose([ + transforms.Resize(self.data_size), + transforms.ToTensor(), + transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]), + ][self.load_all or self.keep_size:]) + self.transform_label = transforms.Compose([ + transforms.Resize(self.data_size), + transforms.ToTensor(), + ][self.load_all or self.keep_size:]) + dataset_root = os.path.join(config.data_root_dir, config.task) + # datasets can be a list of different datasets for training on combined sets. + self.image_paths = [] + for dataset in datasets.split('+'): + image_root = os.path.join(dataset_root, dataset, 'im') + self.image_paths += [os.path.join(image_root, p) for p in os.listdir(image_root) if any(p.endswith(ext) for ext in valid_extensions)] + self.label_paths = [] + for p in self.image_paths: + for ext in valid_extensions: + ## 'im' and 'gt' may need modifying + p_gt = p.replace('/im/', '/gt/')[:-(len(p.split('.')[-1])+1)] + ext + file_exists = False + if os.path.exists(p_gt): + self.label_paths.append(p_gt) + file_exists = True + break + if not file_exists: + print('Not exists:', p_gt) + + if len(self.label_paths) != len(self.image_paths): + raise ValueError(f"There are different numbers of images ({len(self.label_paths)}) and labels ({len(self.image_paths)})") + + if self.load_all: + self.images_loaded, self.labels_loaded = [], [] + self.class_labels_loaded = [] + # for image_path, label_path in zip(self.image_paths, self.label_paths): + for image_path, label_path in tqdm(zip(self.image_paths, self.label_paths), total=len(self.image_paths)): + _image = path_to_image(image_path, size=(config.size, config.size), color_type='rgb') + _label = path_to_image(label_path, size=(config.size, config.size), color_type='gray') + self.images_loaded.append(_image) + self.labels_loaded.append(_label) + self.class_labels_loaded.append( + self.cls_name2id[label_path.split('/')[-1].split('#')[3]] if self.is_train and config.auxiliary_classification else -1 + ) + + def __getitem__(self, index): + + if self.load_all: + image = self.images_loaded[index] + label = self.labels_loaded[index] + class_label = self.class_labels_loaded[index] if self.is_train and config.auxiliary_classification else -1 + else: + image = path_to_image(self.image_paths[index], size=(config.size, config.size), color_type='rgb') + label = path_to_image(self.label_paths[index], size=(config.size, config.size), color_type='gray') + class_label = self.cls_name2id[self.label_paths[index].split('/')[-1].split('#')[3]] if self.is_train and config.auxiliary_classification else -1 + + # loading image and label + if self.is_train: + image, label = preproc(image, label, preproc_methods=config.preproc_methods) + # else: + # if _label.shape[0] > 2048 or _label.shape[1] > 2048: + # _image = cv2.resize(_image, (2048, 2048), interpolation=cv2.INTER_LINEAR) + # _label = cv2.resize(_label, (2048, 2048), interpolation=cv2.INTER_LINEAR) + + image, label = self.transform_image(image), self.transform_label(label) + + if self.is_train: + return image, label, class_label + else: + return image, label, self.label_paths[index] + + def __len__(self): + return len(self.image_paths) diff --git a/py/BiRefNet_v2/eval_existingOnes.py b/py/BiRefNet_v2/eval_existingOnes.py new file mode 100644 index 0000000..9a66c93 --- /dev/null +++ b/py/BiRefNet_v2/eval_existingOnes.py @@ -0,0 +1,146 @@ +import os +import argparse +from glob import glob +import prettytable as pt + +from .evaluation.evaluate import evaluator +from .config import Config + + +config = Config() + + +def do_eval(args): + # evaluation for whole dataset + # dataset first in evaluation + for _data_name in args.data_lst.split('+'): + pred_data_dir = sorted(glob(os.path.join(args.pred_root, args.model_lst[0], _data_name))) + if not pred_data_dir: + print('Skip dataset {}.'.format(_data_name)) + continue + gt_src = os.path.join(args.gt_root, _data_name) + gt_paths = sorted(glob(os.path.join(gt_src, 'gt', '*'))) + print('#' * 20, _data_name, '#' * 20) + filename = os.path.join(args.save_dir, '{}_eval.txt'.format(_data_name)) + tb = pt.PrettyTable() + tb.vertical_char = '&' + if config.task == 'DIS5K': + tb.field_names = ["Dataset", "Method", "maxFm", "wFmeasure", 'MAE', "Smeasure", "meanEm", "HCE", "maxEm", "meanFm", "adpEm", "adpFm", 'mBA', 'maxBIoU', 'meanBIoU'] + elif config.task == 'COD': + tb.field_names = ["Dataset", "Method", "Smeasure", "wFmeasure", "meanFm", "meanEm", "maxEm", 'MAE', "maxFm", "adpEm", "adpFm", "HCE", 'mBA', 'maxBIoU', 'meanBIoU'] + elif config.task == 'HRSOD': + tb.field_names = ["Dataset", "Method", "Smeasure", "maxFm", "meanEm", 'MAE', "maxEm", "meanFm", "wFmeasure", "adpEm", "adpFm", "HCE", 'mBA', 'maxBIoU', 'meanBIoU'] + elif config.task == 'General': + tb.field_names = ["Dataset", "Method", "maxFm", "wFmeasure", 'MAE', "Smeasure", "meanEm", "HCE", "maxEm", "meanFm", "adpEm", "adpFm", 'mBA', 'maxBIoU', 'meanBIoU'] + elif config.task == 'Matting': + tb.field_names = ["Dataset", "Method", "Smeasure", "maxFm", "meanEm", 'MSE', "maxEm", "meanFm", "wFmeasure", "adpEm", "adpFm", "HCE", 'mBA', 'maxBIoU', 'meanBIoU'] + else: + tb.field_names = ["Dataset", "Method", "Smeasure", 'MAE', "maxEm", "meanEm", "maxFm", "meanFm", "wFmeasure", "adpEm", "adpFm", "HCE", 'mBA', 'maxBIoU', 'meanBIoU'] + for _model_name in args.model_lst[:]: + print('\t', 'Evaluating model: {}...'.format(_model_name)) + pred_paths = [p.replace(args.gt_root, os.path.join(args.pred_root, _model_name)).replace('/gt/', '/') for p in gt_paths] + # print(pred_paths[:1], gt_paths[:1]) + em, sm, fm, mae, wfm, hce, mba, biou = evaluator( + gt_paths=gt_paths, + pred_paths=pred_paths, + metrics=args.metrics.split('+'), + verbose=config.verbose_eval + ) + if config.task == 'DIS5K': + scores = [ + fm['curve'].max().round(3), wfm.round(3), mae.round(3), sm.round(3), em['curve'].mean().round(3), int(hce.round()), + em['curve'].max().round(3), fm['curve'].mean().round(3), em['adp'].round(3), fm['adp'].round(3), + mba.round(3), biou['curve'].max().round(3), biou['curve'].mean().round(3), + ] + elif config.task == 'COD': + scores = [ + sm.round(3), wfm.round(3), fm['curve'].mean().round(3), em['curve'].mean().round(3), em['curve'].max().round(3), mae.round(3), + fm['curve'].max().round(3), em['adp'].round(3), fm['adp'].round(3), int(hce.round()), + mba.round(3), biou['curve'].max().round(3), biou['curve'].mean().round(3), + ] + elif config.task == 'HRSOD': + scores = [ + sm.round(3), fm['curve'].max().round(3), em['curve'].mean().round(3), mae.round(3), + em['curve'].max().round(3), fm['curve'].mean().round(3), wfm.round(3), em['adp'].round(3), fm['adp'].round(3), int(hce.round()), + mba.round(3), biou['curve'].max().round(3), biou['curve'].mean().round(3), + ] + elif config.task == 'General': + scores = [ + fm['curve'].max().round(3), wfm.round(3), mae.round(3), sm.round(3), em['curve'].mean().round(3), int(hce.round()), + em['curve'].max().round(3), fm['curve'].mean().round(3), em['adp'].round(3), fm['adp'].round(3), + mba.round(3), biou['curve'].max().round(3), biou['curve'].mean().round(3), + ] + elif config.task == 'Matting': + scores = [ + sm.round(3), fm['curve'].max().round(3), em['curve'].mean().round(3), mse.round(3), + em['curve'].max().round(3), fm['curve'].mean().round(3), wfm.round(3), em['adp'].round(3), fm['adp'].round(3), int(hce.round()), + mba.round(3), biou['curve'].max().round(3), biou['curve'].mean().round(3), + ] + else: + scores = [ + sm.round(3), mae.round(3), em['curve'].max().round(3), em['curve'].mean().round(3), + fm['curve'].max().round(3), fm['curve'].mean().round(3), wfm.round(3), + em['adp'].round(3), fm['adp'].round(3), int(hce.round()), + mba.round(3), biou['curve'].max().round(3), biou['curve'].mean().round(3), + ] + + for idx_score, score in enumerate(scores): + scores[idx_score] = '.' + format(score, '.3f').split('.')[-1] if score <= 1 else format(score, '<4') + records = [_data_name, _model_name] + scores + tb.add_row(records) + # Write results after every check. + with open(filename, 'w+') as file_to_write: + file_to_write.write(str(tb)+'\n') + print(tb) + + +if __name__ == '__main__': + # set parameters + parser = argparse.ArgumentParser() + parser.add_argument( + '--gt_root', type=str, help='ground-truth root', + default=os.path.join(config.data_root_dir, config.task)) + parser.add_argument( + '--pred_root', type=str, help='prediction root', + default='./e_preds') + parser.add_argument( + '--data_lst', type=str, help='test dataset', + default={ + 'DIS5K': '+'.join(['DIS-VD', 'DIS-TE1', 'DIS-TE2', 'DIS-TE3', 'DIS-TE4'][:]), + 'COD': '+'.join(['TE-COD10K', 'NC4K', 'TE-CAMO', 'CHAMELEON'][:]), + 'HRSOD': '+'.join(['DAVIS-S', 'TE-HRSOD', 'TE-UHRSD', 'TE-DUTS', 'DUT-OMRON'][:]), + 'General': '+'.join(['DIS-VD'][:]), + 'Matting': '+'.join(['TE-P3M-500-P'][:]), + }[config.task]) + parser.add_argument( + '--save_dir', type=str, help='candidate competitors', + default='e_results') + parser.add_argument( + '--check_integrity', type=bool, help='whether to check the file integrity', + default=False) + parser.add_argument( + '--metrics', type=str, help='candidate competitors', + default='+'.join(['S', 'MAE', 'E', 'F', 'WF', 'MBA', 'BIoU', 'HCE'][:100 if 'DIS5K' in config.task else -1])) + args = parser.parse_args() + args.metrics = '+'.join(['S', 'MAE', 'E', 'F', 'WF', 'MBA', 'BIoU', 'HCE'][:100 if sum(['DIS-' in _data for _data in args.data_lst.split('+')]) else -1]) + + os.makedirs(args.save_dir, exist_ok=True) + try: + args.model_lst = [m for m in sorted(os.listdir(args.pred_root), key=lambda x: int(x.split('epoch_')[-1]), reverse=True) if int(m.split('epoch_')[-1]) % 1 == 0] + except: + args.model_lst = [m for m in sorted(os.listdir(args.pred_root))] + + # check the integrity of each candidates + if args.check_integrity: + for _data_name in args.data_lst.split('+'): + for _model_name in args.model_lst: + gt_pth = os.path.join(args.gt_root, _data_name) + pred_pth = os.path.join(args.pred_root, _model_name, _data_name) + if not sorted(os.listdir(gt_pth)) == sorted(os.listdir(pred_pth)): + print(len(sorted(os.listdir(gt_pth))), len(sorted(os.listdir(pred_pth)))) + print('The {} Dataset of {} Model is not matching to the ground-truth'.format(_data_name, _model_name)) + else: + print('>>> skip check the integrity of each candidates') + + # start engine + do_eval(args) diff --git a/py/BiRefNet_v2/evaluation/metrics.py b/py/BiRefNet_v2/evaluation/metrics.py new file mode 100644 index 0000000..76ebc45 --- /dev/null +++ b/py/BiRefNet_v2/evaluation/metrics.py @@ -0,0 +1,763 @@ +import os +from tqdm import tqdm +import cv2 +import numpy as np +from scipy.ndimage import convolve, distance_transform_edt as bwdist +from skimage.morphology import skeletonize +from skimage.morphology import disk +from skimage.measure import label + + +_EPS = np.spacing(1) +_TYPE = np.float64 + + +def evaluator(gt_paths, pred_paths, metrics=['S', 'MAE', 'E', 'F', 'WF', 'MBA', 'BIoU', 'HCE'], verbose=False): + # define measures + if 'E' in metrics: + EM = EMeasure() + if 'S' in metrics: + SM = SMeasure() + if 'F' in metrics: + FM = FMeasure() + if 'MAE' in metrics: + MAE = MAEMeasure() + if 'WF' in metrics: + WFM = WeightedFMeasure() + if 'HCE' in metrics: + HCE = HCEMeasure() + if 'MBA' in metrics: + MBA = MBAMeasure() + if 'BIoU' in metrics: + BIoU = BIoUMeasure() + + if isinstance(gt_paths, list) and isinstance(pred_paths, list): + # print(len(gt_paths), len(pred_paths)) + assert len(gt_paths) == len(pred_paths) + + for idx_sample in tqdm(range(len(gt_paths)), total=len(gt_paths)) if verbose else range(len(gt_paths)): + gt = gt_paths[idx_sample] + pred = pred_paths[idx_sample] + + pred = pred[:-4] + '.png' + valid_extensions = ['.png', '.jpg', '.PNG', '.JPG', '.JPEG'] + file_exists = False + for ext in valid_extensions: + if os.path.exists(pred[:-4] + ext): + pred = pred[:-4] + ext + file_exists = True + break + if file_exists: + pred_ary = cv2.imread(pred, cv2.IMREAD_GRAYSCALE) + else: + print('Not exists:', pred) + + gt_ary = cv2.imread(gt, cv2.IMREAD_GRAYSCALE) + pred_ary = cv2.resize(pred_ary, (gt_ary.shape[1], gt_ary.shape[0])) + + if 'E' in metrics: + EM.step(pred=pred_ary, gt=gt_ary) + if 'S' in metrics: + SM.step(pred=pred_ary, gt=gt_ary) + if 'F' in metrics: + FM.step(pred=pred_ary, gt=gt_ary) + if 'MAE' in metrics: + MAE.step(pred=pred_ary, gt=gt_ary) + if 'WF' in metrics: + WFM.step(pred=pred_ary, gt=gt_ary) + if 'HCE' in metrics: + ske_path = gt.replace('/gt/', '/ske/') + if os.path.exists(ske_path): + ske_ary = cv2.imread(ske_path, cv2.IMREAD_GRAYSCALE) + ske_ary = ske_ary > 128 + else: + ske_ary = skeletonize(gt_ary > 128) + ske_save_dir = os.path.join(*ske_path.split(os.sep)[:-1]) + if ske_path[0] == os.sep: + ske_save_dir = os.sep + ske_save_dir + os.makedirs(ske_save_dir, exist_ok=True) + cv2.imwrite(ske_path, ske_ary.astype(np.uint8) * 255) + HCE.step(pred=pred_ary, gt=gt_ary, gt_ske=ske_ary) + if 'MBA' in metrics: + MBA.step(pred=pred_ary, gt=gt_ary) + if 'BIoU' in metrics: + BIoU.step(pred=pred_ary, gt=gt_ary) + + if 'E' in metrics: + em = EM.get_results()['em'] + else: + em = {'curve': np.array([np.float64(-1)]), 'adp': np.float64(-1)} + if 'S' in metrics: + sm = SM.get_results()['sm'] + else: + sm = np.float64(-1) + if 'F' in metrics: + fm = FM.get_results()['fm'] + else: + fm = {'curve': np.array([np.float64(-1)]), 'adp': np.float64(-1)} + if 'MAE' in metrics: + mae = MAE.get_results()['mae'] + else: + mae = np.float64(-1) + if 'WF' in metrics: + wfm = WFM.get_results()['wfm'] + else: + wfm = np.float64(-1) + if 'HCE' in metrics: + hce = HCE.get_results()['hce'] + else: + hce = np.float64(-1) + if 'MBA' in metrics: + mba = MBA.get_results()['mba'] + else: + mba = np.float64(-1) + if 'BIoU' in metrics: + biou = BIoU.get_results()['biou'] + else: + biou = {'curve': np.array([np.float64(-1)])} + + return em, sm, fm, mae, wfm, hce, mba, biou + + +def _prepare_data(pred: np.ndarray, gt: np.ndarray) -> tuple: + gt = gt > 128 + pred = pred / 255 + if pred.max() != pred.min(): + pred = (pred - pred.min()) / (pred.max() - pred.min()) + return pred, gt + + +def _get_adaptive_threshold(matrix: np.ndarray, max_value: float = 1) -> float: + return min(2 * matrix.mean(), max_value) + + +class FMeasure(object): + def __init__(self, beta: float = 0.3): + self.beta = beta + self.precisions = [] + self.recalls = [] + self.adaptive_fms = [] + self.changeable_fms = [] + + def step(self, pred: np.ndarray, gt: np.ndarray): + pred, gt = _prepare_data(pred, gt) + + adaptive_fm = self.cal_adaptive_fm(pred=pred, gt=gt) + self.adaptive_fms.append(adaptive_fm) + + precisions, recalls, changeable_fms = self.cal_pr(pred=pred, gt=gt) + self.precisions.append(precisions) + self.recalls.append(recalls) + self.changeable_fms.append(changeable_fms) + + def cal_adaptive_fm(self, pred: np.ndarray, gt: np.ndarray) -> float: + adaptive_threshold = _get_adaptive_threshold(pred, max_value=1) + binary_predcition = pred >= adaptive_threshold + area_intersection = binary_predcition[gt].sum() + if area_intersection == 0: + adaptive_fm = 0 + else: + pre = area_intersection / np.count_nonzero(binary_predcition) + rec = area_intersection / np.count_nonzero(gt) + adaptive_fm = (1 + self.beta) * pre * rec / (self.beta * pre + rec) + return adaptive_fm + + def cal_pr(self, pred: np.ndarray, gt: np.ndarray) -> tuple: + pred = (pred * 255).astype(np.uint8) + bins = np.linspace(0, 256, 257) + fg_hist, _ = np.histogram(pred[gt], bins=bins) + bg_hist, _ = np.histogram(pred[~gt], bins=bins) + fg_w_thrs = np.cumsum(np.flip(fg_hist), axis=0) + bg_w_thrs = np.cumsum(np.flip(bg_hist), axis=0) + TPs = fg_w_thrs + Ps = fg_w_thrs + bg_w_thrs + Ps[Ps == 0] = 1 + T = max(np.count_nonzero(gt), 1) + precisions = TPs / Ps + recalls = TPs / T + numerator = (1 + self.beta) * precisions * recalls + denominator = np.where(numerator == 0, 1, self.beta * precisions + recalls) + changeable_fms = numerator / denominator + return precisions, recalls, changeable_fms + + def get_results(self) -> dict: + adaptive_fm = np.mean(np.array(self.adaptive_fms, _TYPE)) + changeable_fm = np.mean(np.array(self.changeable_fms, dtype=_TYPE), axis=0) + precision = np.mean(np.array(self.precisions, dtype=_TYPE), axis=0) # N, 256 + recall = np.mean(np.array(self.recalls, dtype=_TYPE), axis=0) # N, 256 + return dict(fm=dict(adp=adaptive_fm, curve=changeable_fm), + pr=dict(p=precision, r=recall)) + + +class MAEMeasure(object): + def __init__(self): + self.maes = [] + + def step(self, pred: np.ndarray, gt: np.ndarray): + pred, gt = _prepare_data(pred, gt) + + mae = self.cal_mae(pred, gt) + self.maes.append(mae) + + def cal_mae(self, pred: np.ndarray, gt: np.ndarray) -> float: + mae = np.mean(np.abs(pred - gt)) + return mae + + def get_results(self) -> dict: + mae = np.mean(np.array(self.maes, _TYPE)) + return dict(mae=mae) + + +class SMeasure(object): + def __init__(self, alpha: float = 0.5): + self.sms = [] + self.alpha = alpha + + def step(self, pred: np.ndarray, gt: np.ndarray): + pred, gt = _prepare_data(pred=pred, gt=gt) + + sm = self.cal_sm(pred, gt) + self.sms.append(sm) + + def cal_sm(self, pred: np.ndarray, gt: np.ndarray) -> float: + y = np.mean(gt) + if y == 0: + sm = 1 - np.mean(pred) + elif y == 1: + sm = np.mean(pred) + else: + sm = self.alpha * self.object(pred, gt) + (1 - self.alpha) * self.region(pred, gt) + sm = max(0, sm) + return sm + + def object(self, pred: np.ndarray, gt: np.ndarray) -> float: + fg = pred * gt + bg = (1 - pred) * (1 - gt) + u = np.mean(gt) + object_score = u * self.s_object(fg, gt) + (1 - u) * self.s_object(bg, 1 - gt) + return object_score + + def s_object(self, pred: np.ndarray, gt: np.ndarray) -> float: + x = np.mean(pred[gt == 1]) + sigma_x = np.std(pred[gt == 1], ddof=1) + score = 2 * x / (np.power(x, 2) + 1 + sigma_x + _EPS) + return score + + def region(self, pred: np.ndarray, gt: np.ndarray) -> float: + x, y = self.centroid(gt) + part_info = self.divide_with_xy(pred, gt, x, y) + w1, w2, w3, w4 = part_info['weight'] + pred1, pred2, pred3, pred4 = part_info['pred'] + gt1, gt2, gt3, gt4 = part_info['gt'] + score1 = self.ssim(pred1, gt1) + score2 = self.ssim(pred2, gt2) + score3 = self.ssim(pred3, gt3) + score4 = self.ssim(pred4, gt4) + + return w1 * score1 + w2 * score2 + w3 * score3 + w4 * score4 + + def centroid(self, matrix: np.ndarray) -> tuple: + h, w = matrix.shape + area_object = np.count_nonzero(matrix) + if area_object == 0: + x = np.round(w / 2) + y = np.round(h / 2) + else: + # More details can be found at: https://www.yuque.com/lart/blog/gpbigm + y, x = np.argwhere(matrix).mean(axis=0).round() + return int(x) + 1, int(y) + 1 + + def divide_with_xy(self, pred: np.ndarray, gt: np.ndarray, x, y) -> dict: + h, w = gt.shape + area = h * w + + gt_LT = gt[0:y, 0:x] + gt_RT = gt[0:y, x:w] + gt_LB = gt[y:h, 0:x] + gt_RB = gt[y:h, x:w] + + pred_LT = pred[0:y, 0:x] + pred_RT = pred[0:y, x:w] + pred_LB = pred[y:h, 0:x] + pred_RB = pred[y:h, x:w] + + w1 = x * y / area + w2 = y * (w - x) / area + w3 = (h - y) * x / area + w4 = 1 - w1 - w2 - w3 + + return dict(gt=(gt_LT, gt_RT, gt_LB, gt_RB), + pred=(pred_LT, pred_RT, pred_LB, pred_RB), + weight=(w1, w2, w3, w4)) + + def ssim(self, pred: np.ndarray, gt: np.ndarray) -> float: + h, w = pred.shape + N = h * w + + x = np.mean(pred) + y = np.mean(gt) + + sigma_x = np.sum((pred - x) ** 2) / (N - 1) + sigma_y = np.sum((gt - y) ** 2) / (N - 1) + sigma_xy = np.sum((pred - x) * (gt - y)) / (N - 1) + + alpha = 4 * x * y * sigma_xy + beta = (x ** 2 + y ** 2) * (sigma_x + sigma_y) + + if alpha != 0: + score = alpha / (beta + _EPS) + elif alpha == 0 and beta == 0: + score = 1 + else: + score = 0 + return score + + def get_results(self) -> dict: + sm = np.mean(np.array(self.sms, dtype=_TYPE)) + return dict(sm=sm) + + +class EMeasure(object): + def __init__(self): + self.adaptive_ems = [] + self.changeable_ems = [] + + def step(self, pred: np.ndarray, gt: np.ndarray): + pred, gt = _prepare_data(pred=pred, gt=gt) + self.gt_fg_numel = np.count_nonzero(gt) + self.gt_size = gt.shape[0] * gt.shape[1] + + changeable_ems = self.cal_changeable_em(pred, gt) + self.changeable_ems.append(changeable_ems) + adaptive_em = self.cal_adaptive_em(pred, gt) + self.adaptive_ems.append(adaptive_em) + + def cal_adaptive_em(self, pred: np.ndarray, gt: np.ndarray) -> float: + adaptive_threshold = _get_adaptive_threshold(pred, max_value=1) + adaptive_em = self.cal_em_with_threshold(pred, gt, threshold=adaptive_threshold) + return adaptive_em + + def cal_changeable_em(self, pred: np.ndarray, gt: np.ndarray) -> np.ndarray: + changeable_ems = self.cal_em_with_cumsumhistogram(pred, gt) + return changeable_ems + + def cal_em_with_threshold(self, pred: np.ndarray, gt: np.ndarray, threshold: float) -> float: + binarized_pred = pred >= threshold + fg_fg_numel = np.count_nonzero(binarized_pred & gt) + fg_bg_numel = np.count_nonzero(binarized_pred & ~gt) + + fg___numel = fg_fg_numel + fg_bg_numel + bg___numel = self.gt_size - fg___numel + + if self.gt_fg_numel == 0: + enhanced_matrix_sum = bg___numel + elif self.gt_fg_numel == self.gt_size: + enhanced_matrix_sum = fg___numel + else: + parts_numel, combinations = self.generate_parts_numel_combinations( + fg_fg_numel=fg_fg_numel, fg_bg_numel=fg_bg_numel, + pred_fg_numel=fg___numel, pred_bg_numel=bg___numel, + ) + + results_parts = [] + for i, (part_numel, combination) in enumerate(zip(parts_numel, combinations)): + align_matrix_value = 2 * (combination[0] * combination[1]) / \ + (combination[0] ** 2 + combination[1] ** 2 + _EPS) + enhanced_matrix_value = (align_matrix_value + 1) ** 2 / 4 + results_parts.append(enhanced_matrix_value * part_numel) + enhanced_matrix_sum = sum(results_parts) + + em = enhanced_matrix_sum / (self.gt_size - 1 + _EPS) + return em + + def cal_em_with_cumsumhistogram(self, pred: np.ndarray, gt: np.ndarray) -> np.ndarray: + pred = (pred * 255).astype(np.uint8) + bins = np.linspace(0, 256, 257) + fg_fg_hist, _ = np.histogram(pred[gt], bins=bins) + fg_bg_hist, _ = np.histogram(pred[~gt], bins=bins) + fg_fg_numel_w_thrs = np.cumsum(np.flip(fg_fg_hist), axis=0) + fg_bg_numel_w_thrs = np.cumsum(np.flip(fg_bg_hist), axis=0) + + fg___numel_w_thrs = fg_fg_numel_w_thrs + fg_bg_numel_w_thrs + bg___numel_w_thrs = self.gt_size - fg___numel_w_thrs + + if self.gt_fg_numel == 0: + enhanced_matrix_sum = bg___numel_w_thrs + elif self.gt_fg_numel == self.gt_size: + enhanced_matrix_sum = fg___numel_w_thrs + else: + parts_numel_w_thrs, combinations = self.generate_parts_numel_combinations( + fg_fg_numel=fg_fg_numel_w_thrs, fg_bg_numel=fg_bg_numel_w_thrs, + pred_fg_numel=fg___numel_w_thrs, pred_bg_numel=bg___numel_w_thrs, + ) + + results_parts = np.empty(shape=(4, 256), dtype=np.float64) + for i, (part_numel, combination) in enumerate(zip(parts_numel_w_thrs, combinations)): + align_matrix_value = 2 * (combination[0] * combination[1]) / \ + (combination[0] ** 2 + combination[1] ** 2 + _EPS) + enhanced_matrix_value = (align_matrix_value + 1) ** 2 / 4 + results_parts[i] = enhanced_matrix_value * part_numel + enhanced_matrix_sum = results_parts.sum(axis=0) + + em = enhanced_matrix_sum / (self.gt_size - 1 + _EPS) + return em + + def generate_parts_numel_combinations(self, fg_fg_numel, fg_bg_numel, pred_fg_numel, pred_bg_numel): + bg_fg_numel = self.gt_fg_numel - fg_fg_numel + bg_bg_numel = pred_bg_numel - bg_fg_numel + + parts_numel = [fg_fg_numel, fg_bg_numel, bg_fg_numel, bg_bg_numel] + + mean_pred_value = pred_fg_numel / self.gt_size + mean_gt_value = self.gt_fg_numel / self.gt_size + + demeaned_pred_fg_value = 1 - mean_pred_value + demeaned_pred_bg_value = 0 - mean_pred_value + demeaned_gt_fg_value = 1 - mean_gt_value + demeaned_gt_bg_value = 0 - mean_gt_value + + combinations = [ + (demeaned_pred_fg_value, demeaned_gt_fg_value), + (demeaned_pred_fg_value, demeaned_gt_bg_value), + (demeaned_pred_bg_value, demeaned_gt_fg_value), + (demeaned_pred_bg_value, demeaned_gt_bg_value) + ] + return parts_numel, combinations + + def get_results(self) -> dict: + adaptive_em = np.mean(np.array(self.adaptive_ems, dtype=_TYPE)) + changeable_em = np.mean(np.array(self.changeable_ems, dtype=_TYPE), axis=0) + return dict(em=dict(adp=adaptive_em, curve=changeable_em)) + + +class WeightedFMeasure(object): + def __init__(self, beta: float = 1): + self.beta = beta + self.weighted_fms = [] + + def step(self, pred: np.ndarray, gt: np.ndarray): + pred, gt = _prepare_data(pred=pred, gt=gt) + + if np.all(~gt): + wfm = 0 + else: + wfm = self.cal_wfm(pred, gt) + self.weighted_fms.append(wfm) + + def cal_wfm(self, pred: np.ndarray, gt: np.ndarray) -> float: + # [Dst,IDXT] = bwdist(dGT); + Dst, Idxt = bwdist(gt == 0, return_indices=True) + + # %Pixel dependency + # E = abs(FG-dGT); + E = np.abs(pred - gt) + Et = np.copy(E) + Et[gt == 0] = Et[Idxt[0][gt == 0], Idxt[1][gt == 0]] + + # K = fspecial('gaussian',7,5); + # EA = imfilter(Et,K); + K = self.matlab_style_gauss2D((7, 7), sigma=5) + EA = convolve(Et, weights=K, mode="constant", cval=0) + # MIN_E_EA = E; + # MIN_E_EA(GT & EA np.ndarray: + """ + 2D gaussian mask - should give the same result as MATLAB's + fspecial('gaussian',[shape],[sigma]) + """ + m, n = [(ss - 1) / 2 for ss in shape] + y, x = np.ogrid[-m: m + 1, -n: n + 1] + h = np.exp(-(x * x + y * y) / (2 * sigma * sigma)) + h[h < np.finfo(h.dtype).eps * h.max()] = 0 + sumh = h.sum() + if sumh != 0: + h /= sumh + return h + + def get_results(self) -> dict: + weighted_fm = np.mean(np.array(self.weighted_fms, dtype=_TYPE)) + return dict(wfm=weighted_fm) + + +class HCEMeasure(object): + def __init__(self): + self.hces = [] + + def step(self, pred: np.ndarray, gt: np.ndarray, gt_ske): + # pred, gt = _prepare_data(pred, gt) + + hce = self.cal_hce(pred, gt, gt_ske) + self.hces.append(hce) + + def get_results(self) -> dict: + hce = np.mean(np.array(self.hces, _TYPE)) + return dict(hce=hce) + + + def cal_hce(self, pred: np.ndarray, gt: np.ndarray, gt_ske: np.ndarray, relax=5, epsilon=2.0) -> float: + # Binarize gt + if(len(gt.shape)>2): + gt = gt[:, :, 0] + + epsilon_gt = 128#(np.amin(gt)+np.amax(gt))/2.0 + gt = (gt>epsilon_gt).astype(np.uint8) + + # Binarize pred + if(len(pred.shape)>2): + pred = pred[:, :, 0] + epsilon_pred = 128#(np.amin(pred)+np.amax(pred))/2.0 + pred = (pred>epsilon_pred).astype(np.uint8) + + Union = np.logical_or(gt, pred) + TP = np.logical_and(gt, pred) + FP = pred - TP + FN = gt - TP + + # relax the Union of gt and pred + Union_erode = Union.copy() + Union_erode = cv2.erode(Union_erode.astype(np.uint8), disk(1), iterations=relax) + + # --- get the relaxed False Positive regions for computing the human efforts in correcting them --- + FP_ = np.logical_and(FP, Union_erode) # get the relaxed FP + for i in range(0, relax): + FP_ = cv2.dilate(FP_.astype(np.uint8), disk(1)) + FP_ = np.logical_and(FP_, 1-np.logical_or(TP, FN)) + FP_ = np.logical_and(FP, FP_) + + # --- get the relaxed False Negative regions for computing the human efforts in correcting them --- + FN_ = np.logical_and(FN, Union_erode) # preserve the structural components of FN + ## recover the FN, where pixels are not close to the TP borders + for i in range(0, relax): + FN_ = cv2.dilate(FN_.astype(np.uint8), disk(1)) + FN_ = np.logical_and(FN_, 1-np.logical_or(TP, FP)) + FN_ = np.logical_and(FN, FN_) + FN_ = np.logical_or(FN_, np.logical_xor(gt_ske, np.logical_and(TP, gt_ske))) # preserve the structural components of FN + + ## 2. =============Find exact polygon control points and independent regions============== + ## find contours from FP_ + ctrs_FP, hier_FP = cv2.findContours(FP_.astype(np.uint8), cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE) + ## find control points and independent regions for human correction + bdies_FP, indep_cnt_FP = self.filter_bdy_cond(ctrs_FP, FP_, np.logical_or(TP,FN_)) + ## find contours from FN_ + ctrs_FN, hier_FN = cv2.findContours(FN_.astype(np.uint8), cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE) + ## find control points and independent regions for human correction + bdies_FN, indep_cnt_FN = self.filter_bdy_cond(ctrs_FN, FN_, 1-np.logical_or(np.logical_or(TP, FP_), FN_)) + + poly_FP, poly_FP_len, poly_FP_point_cnt = self.approximate_RDP(bdies_FP, epsilon=epsilon) + poly_FN, poly_FN_len, poly_FN_point_cnt = self.approximate_RDP(bdies_FN, epsilon=epsilon) + + # FP_points+FP_indep+FN_points+FN_indep + return poly_FP_point_cnt+indep_cnt_FP+poly_FN_point_cnt+indep_cnt_FN + + def filter_bdy_cond(self, bdy_, mask, cond): + + cond = cv2.dilate(cond.astype(np.uint8), disk(1)) + labels = label(mask) # find the connected regions + lbls = np.unique(labels) # the indices of the connected regions + indep = np.ones(lbls.shape[0]) # the label of each connected regions + indep[0] = 0 # 0 indicate the background region + + boundaries = [] + h,w = cond.shape[0:2] + ind_map = np.zeros((h, w)) + indep_cnt = 0 + + for i in range(0, len(bdy_)): + tmp_bdies = [] + tmp_bdy = [] + for j in range(0, bdy_[i].shape[0]): + r, c = bdy_[i][j,0,1],bdy_[i][j,0,0] + + if(np.sum(cond[r, c])==0 or ind_map[r, c]!=0): + if(len(tmp_bdy)>0): + tmp_bdies.append(tmp_bdy) + tmp_bdy = [] + continue + tmp_bdy.append([c, r]) + ind_map[r, c] = ind_map[r, c] + 1 + indep[labels[r, c]] = 0 # indicates part of the boundary of this region needs human correction + if(len(tmp_bdy)>0): + tmp_bdies.append(tmp_bdy) + + # check if the first and the last boundaries are connected + # if yes, invert the first boundary and attach it after the last boundary + if(len(tmp_bdies)>1): + first_x, first_y = tmp_bdies[0][0] + last_x, last_y = tmp_bdies[-1][-1] + if((abs(first_x-last_x)==1 and first_y==last_y) or + (first_x==last_x and abs(first_y-last_y)==1) or + (abs(first_x-last_x)==1 and abs(first_y-last_y)==1) + ): + tmp_bdies[-1].extend(tmp_bdies[0][::-1]) + del tmp_bdies[0] + + for k in range(0, len(tmp_bdies)): + tmp_bdies[k] = np.array(tmp_bdies[k])[:, np.newaxis, :] + if(len(tmp_bdies)>0): + boundaries.extend(tmp_bdies) + + return boundaries, np.sum(indep) + + # this function approximate each boundary by DP algorithm + # https://en.wikipedia.org/wiki/Ramer%E2%80%93Douglas%E2%80%93Peucker_algorithm + def approximate_RDP(self, boundaries, epsilon=1.0): + + boundaries_ = [] + boundaries_len_ = [] + pixel_cnt_ = 0 + + # polygon approximate of each boundary + for i in range(0, len(boundaries)): + boundaries_.append(cv2.approxPolyDP(boundaries[i], epsilon, False)) + + # count the control points number of each boundary and the total control points number of all the boundaries + for i in range(0, len(boundaries_)): + boundaries_len_.append(len(boundaries_[i])) + pixel_cnt_ = pixel_cnt_ + len(boundaries_[i]) + + return boundaries_, boundaries_len_, pixel_cnt_ + + +class MBAMeasure(object): + def __init__(self): + self.bas = [] + self.all_h = 0 + self.all_w = 0 + self.all_max = 0 + + def step(self, pred: np.ndarray, gt: np.ndarray): + # pred, gt = _prepare_data(pred, gt) + + refined = gt.copy() + + rmin = cmin = 0 + rmax, cmax = gt.shape + + self.all_h += rmax + self.all_w += cmax + self.all_max += max(rmax, cmax) + + refined_h, refined_w = refined.shape + if refined_h != cmax: + refined = np.array(Image.fromarray(pred).resize((cmax, rmax), Image.BILINEAR)) + + if not(gt.sum() < 32*32): + if not((cmax==cmin) or (rmax==rmin)): + class_refined_prob = np.array(Image.fromarray(pred).resize((cmax-cmin, rmax-rmin), Image.BILINEAR)) + refined[rmin:rmax, cmin:cmax] = class_refined_prob + + pred = pred > 128 + gt = gt > 128 + + ba = self.cal_ba(pred, gt) + self.bas.append(ba) + + def get_disk_kernel(self, radius): + return cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (radius*2+1, radius*2+1)) + + def cal_ba(self, pred: np.ndarray, gt: np.ndarray) -> np.ndarray: + """ + Calculate the mean absolute error. + + :return: ba + """ + + gt = gt.astype(np.uint8) + pred = pred.astype(np.uint8) + + h, w = gt.shape + + min_radius = 1 + max_radius = (w+h)/300 + num_steps = 5 + + pred_acc = [None] * num_steps + + for i in range(num_steps): + curr_radius = min_radius + int((max_radius-min_radius)/num_steps*i) + + kernel = self.get_disk_kernel(curr_radius) + boundary_region = cv2.morphologyEx(gt, cv2.MORPH_GRADIENT, kernel) > 0 + + gt_in_bound = gt[boundary_region] + pred_in_bound = pred[boundary_region] + + num_edge_pixels = (boundary_region).sum() + num_pred_gd_pix = ((gt_in_bound) * (pred_in_bound) + (1-gt_in_bound) * (1-pred_in_bound)).sum() + + pred_acc[i] = num_pred_gd_pix / num_edge_pixels + + ba = sum(pred_acc)/num_steps + return ba + + def get_results(self) -> dict: + mba = np.mean(np.array(self.bas, _TYPE)) + return dict(mba=mba) + + +class BIoUMeasure(object): + def __init__(self, dilation_ratio=0.02): + self.bious = [] + self.dilation_ratio = dilation_ratio + + def mask_to_boundary(self, mask): + h, w = mask.shape + img_diag = np.sqrt(h ** 2 + w ** 2) + dilation = int(round(self.dilation_ratio * img_diag)) + if dilation < 1: + dilation = 1 + # Pad image so mask truncated by the image border is also considered as boundary. + new_mask = cv2.copyMakeBorder(mask, 1, 1, 1, 1, cv2.BORDER_CONSTANT, value=0) + kernel = np.ones((3, 3), dtype=np.uint8) + new_mask_erode = cv2.erode(new_mask, kernel, iterations=dilation) + mask_erode = new_mask_erode[1 : h + 1, 1 : w + 1] + # G_d intersects G in the paper. + return mask - mask_erode + + def step(self, pred: np.ndarray, gt: np.ndarray): + pred, gt = _prepare_data(pred, gt) + + bious = self.cal_biou(pred=pred, gt=gt) + self.bious.append(bious) + + def cal_biou(self, pred, gt): + pred = (pred * 255).astype(np.uint8) + pred = self.mask_to_boundary(pred) + gt = (gt * 255).astype(np.uint8) + gt = self.mask_to_boundary(gt) + gt = gt > 128 + + bins = np.linspace(0, 256, 257) + fg_hist, _ = np.histogram(pred[gt], bins=bins) # ture positive + bg_hist, _ = np.histogram(pred[~gt], bins=bins) # false positive + fg_w_thrs = np.cumsum(np.flip(fg_hist), axis=0) + bg_w_thrs = np.cumsum(np.flip(bg_hist), axis=0) + TPs = fg_w_thrs + Ps = fg_w_thrs + bg_w_thrs # positives + Ps[Ps == 0] = 1 + T = max(np.count_nonzero(gt), 1) + + ious = TPs / (T + bg_w_thrs) + return ious + + def get_results(self) -> dict: + biou = np.mean(np.array(self.bious, dtype=_TYPE), axis=0) + return dict(biou=dict(curve=biou)) diff --git a/py/BiRefNet_v2/gen_best_ep.py b/py/BiRefNet_v2/gen_best_ep.py new file mode 100644 index 0000000..8e59868 --- /dev/null +++ b/py/BiRefNet_v2/gen_best_ep.py @@ -0,0 +1,86 @@ +import os +from glob import glob +import numpy as np + +from .config import Config + + +config = Config() + +eval_txts = sorted(glob('e_results/*_eval.txt')) +print('eval_txts:', [_.split(os.sep)[-1] for _ in eval_txts]) +score_panel = {} +sep = '&' +metrics = ['sm', 'wfm', 'hce'] # we used HCE for DIS and wFm for others. +if 'DIS5K' not in config.task: + metrics.remove('hce') + +for metric in metrics: + print('Metric:', metric) + current_line_nums = [] + for idx_et, eval_txt in enumerate(eval_txts): + with open(eval_txt, 'r') as f: + lines = [l for l in f.readlines()[3:] if '.' in l] + current_line_nums.append(len(lines)) + for idx_et, eval_txt in enumerate(eval_txts): + with open(eval_txt, 'r') as f: + lines = [l for l in f.readlines()[3:] if '.' in l] + for idx_line, line in enumerate(lines[:min(current_line_nums)]): # Consist line numbers by the minimal result file. + properties = line.strip().strip(sep).split(sep) + dataset = properties[0].strip() + ckpt = properties[1].strip() + if int(ckpt.split('--epoch_')[-1].strip()) < 0: + continue + targe_idx = { + 'sm': [5, 2, 2, 5, 2], + 'wfm': [3, 3, 8, 3, 8], + 'hce': [7, -1, -1, 7, -1] + }[metric][['DIS5K', 'COD', 'HRSOD', 'General', 'Matting'].index(config.task)] + if metric != 'hce': + score_sm = float(properties[targe_idx].strip()) + else: + score_sm = int(properties[targe_idx].strip().strip('.')) + if idx_et == 0: + score_panel[ckpt] = [] + score_panel[ckpt].append(score_sm) + + metrics_min = ['hce', 'mae'] + max_or_min = min if metric in metrics_min else max + score_max = max_or_min(score_panel.values(), key=lambda x: np.sum(x)) + + good_models = [] + for k, v in score_panel.items(): + if (np.sum(v) <= np.sum(score_max)) if metric in metrics_min else (np.sum(v) >= np.sum(score_max)): + print(k, v) + good_models.append(k) + + # Write + with open(eval_txt, 'r') as f: + lines = f.readlines() + info4good_models = lines[:3] + metric_names = [m.strip() for m in lines[1].strip().strip('&').split('&')[2:]] + testset_mean_values = {metric_name: [] for metric_name in metric_names} + for good_model in good_models: + for idx_et, eval_txt in enumerate(eval_txts): + with open(eval_txt, 'r') as f: + lines = f.readlines() + for line in lines: + if set([good_model]) & set([_.strip() for _ in line.split(sep)]): + info4good_models.append(line) + metric_scores = [float(m.strip()) for m in line.strip().strip('&').split('&')[2:]] + for idx_score, metric_score in enumerate(metric_scores): + testset_mean_values[metric_names[idx_score]].append(metric_score) + + if 'DIS5K' in config.task: + testset_mean_values_lst = ['{:<4}'.format(int(np.mean(v_lst[:-1]).round())) if name == 'HCE' else '{:.3f}'.format(np.mean(v_lst[:-1])).lstrip('0') for name, v_lst in testset_mean_values.items()] # [:-1] to remove DIS-VD + sample_line_for_placing_mean_values = info4good_models[-2] + numbers_placed_well = sample_line_for_placing_mean_values.replace(sample_line_for_placing_mean_values.split('&')[1].strip(), 'DIS-TEs').strip().split('&')[3:] + for idx_number, (number_placed_well, testset_mean_value) in enumerate(zip(numbers_placed_well, testset_mean_values_lst)): + numbers_placed_well[idx_number] = number_placed_well.replace(number_placed_well.strip(), testset_mean_value) + testset_mean_line = '&'.join(sample_line_for_placing_mean_values.replace(sample_line_for_placing_mean_values.split('&')[1].strip(), 'DIS-TEs').split('&')[:3] + numbers_placed_well) + '\n' + info4good_models.append(testset_mean_line) + info4good_models.append(lines[-1]) + info = ''.join(info4good_models) + print(info) + with open(os.path.join('e_results', 'eval-{}_best_on_{}.txt'.format(config.task, metric)), 'w') as f: + f.write(info + '\n') diff --git a/py/BiRefNet_v2/image_proc.py b/py/BiRefNet_v2/image_proc.py new file mode 100644 index 0000000..2ebfbfa --- /dev/null +++ b/py/BiRefNet_v2/image_proc.py @@ -0,0 +1,119 @@ +import random +from PIL import Image, ImageEnhance +import numpy as np +import cv2 + + +def refine_foreground(image, mask, r=90): + if mask.size != image.size: + mask = mask.resize(image.size) + image = np.array(image) / 255.0 + mask = np.array(mask) / 255.0 + estimated_foreground = FB_blur_fusion_foreground_estimator_2(image, mask, r=r) + image_masked = Image.fromarray((estimated_foreground * 255.0).astype(np.uint8)) + return image_masked + + +def FB_blur_fusion_foreground_estimator_2(image, alpha, r=90): + # Thanks to the source: https://github.com/Photoroom/fast-foreground-estimation + alpha = alpha[:, :, None] + F, blur_B = FB_blur_fusion_foreground_estimator( + image, image, image, alpha, r) + return FB_blur_fusion_foreground_estimator(image, F, blur_B, alpha, r=6)[0] + + +def FB_blur_fusion_foreground_estimator(image, F, B, alpha, r=90): + if isinstance(image, Image.Image): + image = np.array(image) / 255.0 + blurred_alpha = cv2.blur(alpha, (r, r))[:, :, None] + + blurred_FA = cv2.blur(F * alpha, (r, r)) + blurred_F = blurred_FA / (blurred_alpha + 1e-5) + + blurred_B1A = cv2.blur(B * (1 - alpha), (r, r)) + blurred_B = blurred_B1A / ((1 - blurred_alpha) + 1e-5) + F = blurred_F + alpha * \ + (image - alpha * blurred_F - (1 - alpha) * blurred_B) + F = np.clip(F, 0, 1) + return F, blurred_B + + +def preproc(image, label, preproc_methods=['flip']): + if 'flip' in preproc_methods: + image, label = cv_random_flip(image, label) + if 'crop' in preproc_methods: + image, label = random_crop(image, label) + if 'rotate' in preproc_methods: + image, label = random_rotate(image, label) + if 'enhance' in preproc_methods: + image = color_enhance(image) + if 'pepper' in preproc_methods: + label = random_pepper(label) + return image, label + + +def cv_random_flip(img, label): + if random.random() > 0.5: + img = img.transpose(Image.FLIP_LEFT_RIGHT) + label = label.transpose(Image.FLIP_LEFT_RIGHT) + return img, label + + +def random_crop(image, label): + border = 30 + image_width = image.size[0] + image_height = image.size[1] + border = int(min(image_width, image_height) * 0.1) + crop_win_width = np.random.randint(image_width - border, image_width) + crop_win_height = np.random.randint(image_height - border, image_height) + random_region = ( + (image_width - crop_win_width) >> 1, (image_height - crop_win_height) >> 1, (image_width + crop_win_width) >> 1, + (image_height + crop_win_height) >> 1) + return image.crop(random_region), label.crop(random_region) + + +def random_rotate(image, label, angle=15): + mode = Image.BICUBIC + if random.random() > 0.8: + random_angle = np.random.randint(-angle, angle) + image = image.rotate(random_angle, mode) + label = label.rotate(random_angle, mode) + return image, label + + +def color_enhance(image): + bright_intensity = random.randint(5, 15) / 10.0 + image = ImageEnhance.Brightness(image).enhance(bright_intensity) + contrast_intensity = random.randint(5, 15) / 10.0 + image = ImageEnhance.Contrast(image).enhance(contrast_intensity) + color_intensity = random.randint(0, 20) / 10.0 + image = ImageEnhance.Color(image).enhance(color_intensity) + sharp_intensity = random.randint(0, 30) / 10.0 + image = ImageEnhance.Sharpness(image).enhance(sharp_intensity) + return image + + +def random_gaussian(image, mean=0.1, sigma=0.35): + def gaussianNoisy(im, mean=mean, sigma=sigma): + for _i in range(len(im)): + im[_i] += random.gauss(mean, sigma) + return im + + img = np.asarray(image) + width, height = img.shape + img = gaussianNoisy(img[:].flatten(), mean, sigma) + img = img.reshape([width, height]) + return Image.fromarray(np.uint8(img)) + + +def random_pepper(img, N=0.0015): + img = np.array(img) + noiseNum = int(N * img.shape[0] * img.shape[1]) + for i in range(noiseNum): + randX = random.randint(0, img.shape[0] - 1) + randY = random.randint(0, img.shape[1] - 1) + if random.randint(0, 1) == 0: + img[randX, randY] = 0 + else: + img[randX, randY] = 255 + return Image.fromarray(img) diff --git a/py/BiRefNet_v2/inference.py b/py/BiRefNet_v2/inference.py new file mode 100644 index 0000000..21ed88f --- /dev/null +++ b/py/BiRefNet_v2/inference.py @@ -0,0 +1,105 @@ +import os +import argparse +from glob import glob +from tqdm import tqdm +import cv2 +import torch + +from .dataset import MyData +from .models.birefnet import BiRefNet +from .utils import save_tensor_img, check_state_dict +from .config import Config + + +config = Config() + + +def inference(model, data_loader_test, pred_root, method, testset, device=0): + model_training = model.training + if model_training: + model.eval() + for batch in tqdm(data_loader_test, total=len(data_loader_test)) if 1 or config.verbose_eval else data_loader_test: + inputs = batch[0].to(device) + # gts = batch[1].to(device) + label_paths = batch[-1] + with torch.no_grad(): + scaled_preds = model(inputs)[-1].sigmoid() + + os.makedirs(os.path.join(pred_root, method, testset), exist_ok=True) + + for idx_sample in range(scaled_preds.shape[0]): + res = torch.nn.functional.interpolate( + scaled_preds[idx_sample].unsqueeze(0), + size=cv2.imread(label_paths[idx_sample], cv2.IMREAD_GRAYSCALE).shape[:2], + mode='bilinear', + align_corners=True + ) + save_tensor_img(res, os.path.join(os.path.join(pred_root, method, testset), label_paths[idx_sample].replace('\\', '/').split('/')[-1])) # test set dir + file name + if model_training: + model.train() + return None + + +def main(args): + # Init model + + device = config.device + if args.ckpt_folder: + print('Testing with models in {}'.format(args.ckpt_folder)) + else: + print('Testing with model {}'.format(args.ckpt)) + + if config.model == 'BiRefNet': + model = BiRefNet(bb_pretrained=False) + weights_lst = sorted( + glob(os.path.join(args.ckpt_folder, '*.pth')) if args.ckpt_folder else [args.ckpt], + key=lambda x: int(x.split('epoch_')[-1].split('.pth')[0]), + reverse=True + ) + for testset in args.testsets.split('+'): + print('>>>> Testset: {}...'.format(testset)) + data_loader_test = torch.utils.data.DataLoader( + dataset=MyData(testset, image_size=config.size, is_train=False), + batch_size=config.batch_size_valid, shuffle=False, num_workers=config.num_workers, pin_memory=True + ) + for weights in weights_lst: + if int(weights.strip('.pth').split('epoch_')[-1]) % 1 != 0: + continue + print('\tInferencing {}...'.format(weights)) + # model.load_state_dict(torch.load(weights, map_location='cpu')) + state_dict = torch.load(weights, map_location='cpu') + state_dict = check_state_dict(state_dict) + model.load_state_dict(state_dict) + model = model.to(device) + inference( + model, data_loader_test=data_loader_test, pred_root=args.pred_root, + method='--'.join([w.rstrip('.pth') for w in weights.split(os.sep)[-2:]]), + testset=testset, device=config.device + ) + + +if __name__ == '__main__': + # Parameter from command line + parser = argparse.ArgumentParser(description='') + parser.add_argument('--ckpt', type=str, help='model folder') + parser.add_argument('--ckpt_folder', default=sorted(glob(os.path.join('ckpt', '*')))[-1], type=str, help='model folder') + parser.add_argument('--pred_root', default='e_preds', type=str, help='Output folder') + parser.add_argument('--testsets', + default={ + 'DIS5K': 'DIS-VD+DIS-TE1+DIS-TE2+DIS-TE3+DIS-TE4', + 'COD': 'TE-COD10K+NC4K+TE-CAMO+CHAMELEON', + 'HRSOD': 'DAVIS-S+TE-HRSOD+TE-UHRSD+TE-DUTS+DUT-OMRON', + 'General': 'DIS-VD', + 'Matting': 'TE-P3M-500-P', + 'DIS5K-': 'DIS-VD', + 'COD-': 'TE-COD10K', + 'SOD-': 'DAVIS-S+TE-HRSOD+TE-UHRSD', + }[config.task + ''], + type=str, + help="Test all sets: , 'DIS-VD+DIS-TE1+DIS-TE2+DIS-TE3+DIS-TE4'") + + args = parser.parse_args() + + if config.precisionHigh: + torch.set_float32_matmul_precision('high') + main(args) diff --git a/py/BiRefNet_v2/loss.py b/py/BiRefNet_v2/loss.py new file mode 100644 index 0000000..ee0c5a2 --- /dev/null +++ b/py/BiRefNet_v2/loss.py @@ -0,0 +1,277 @@ +import torch +from torch import nn +import torch.nn.functional as F +from torch.autograd import Variable +from math import exp + +from .config import Config + + +class Discriminator(nn.Module): + def __init__(self, channels=1, img_size=256): + super(Discriminator, self).__init__() + + def discriminator_block(in_filters, out_filters, bn=Config().batch_size > 1): + block = [nn.Conv2d(in_filters, out_filters, 3, 2, 1), nn.LeakyReLU(0.2, inplace=True), nn.Dropout2d(0.25)] + if bn: + block.append(nn.BatchNorm2d(out_filters, 0.8)) + return block + + self.model = nn.Sequential( + *discriminator_block(channels, 16, bn=False), + *discriminator_block(16, 32), + *discriminator_block(32, 64), + *discriminator_block(64, 128), + ) + + # The height and width of downsampled image + ds_size = img_size // 2 ** 4 + self.adv_layer = nn.Sequential(nn.Linear(128 * ds_size ** 2, 1), nn.Sigmoid()) + + def forward(self, img): + out = self.model(img) + out = out.view(out.shape[0], -1) + validity = self.adv_layer(out) + + return validity + + +class ContourLoss(torch.nn.Module): + def __init__(self): + super(ContourLoss, self).__init__() + + def forward(self, pred, target, weight=10): + ''' + target, pred: tensor of shape (B, C, H, W), where target[:,:,region_in_contour] == 1, + target[:,:,region_out_contour] == 0. + weight: scalar, length term weight. + ''' + # length term + delta_r = pred[:,:,1:,:] - pred[:,:,:-1,:] # horizontal gradient (B, C, H-1, W) + delta_c = pred[:,:,:,1:] - pred[:,:,:,:-1] # vertical gradient (B, C, H, W-1) + + delta_r = delta_r[:,:,1:,:-2]**2 # (B, C, H-2, W-2) + delta_c = delta_c[:,:,:-2,1:]**2 # (B, C, H-2, W-2) + delta_pred = torch.abs(delta_r + delta_c) + + epsilon = 1e-8 # where is a parameter to avoid square root is zero in practice. + length = torch.mean(torch.sqrt(delta_pred + epsilon)) # eq.(11) in the paper, mean is used instead of sum. + + c_in = torch.ones_like(pred) + c_out = torch.zeros_like(pred) + + region_in = torch.mean( pred * (target - c_in )**2 ) # equ.(12) in the paper, mean is used instead of sum. + region_out = torch.mean( (1-pred) * (target - c_out)**2 ) + region = region_in + region_out + + loss = weight * length + region + + return loss + + +class IoULoss(torch.nn.Module): + def __init__(self): + super(IoULoss, self).__init__() + + def forward(self, pred, target): + b = pred.shape[0] + IoU = 0.0 + for i in range(0, b): + # compute the IoU of the foreground + Iand1 = torch.sum(target[i, :, :, :] * pred[i, :, :, :]) + Ior1 = torch.sum(target[i, :, :, :]) + torch.sum(pred[i, :, :, :]) - Iand1 + IoU1 = Iand1 / Ior1 + # IoU loss is (1-IoU1) + IoU = IoU + (1-IoU1) + # return IoU/b + return IoU + + +class StructureLoss(torch.nn.Module): + def __init__(self): + super(StructureLoss, self).__init__() + + def forward(self, pred, target): + weit = 1+5*torch.abs(F.avg_pool2d(target, kernel_size=31, stride=1, padding=15)-target) + wbce = F.binary_cross_entropy_with_logits(pred, target, reduction='none') + wbce = (weit*wbce).sum(dim=(2,3))/weit.sum(dim=(2,3)) + + pred = torch.sigmoid(pred) + inter = ((pred * target) * weit).sum(dim=(2, 3)) + union = ((pred + target) * weit).sum(dim=(2, 3)) + wiou = 1-(inter+1)/(union-inter+1) + + return (wbce+wiou).mean() + + +class PatchIoULoss(torch.nn.Module): + def __init__(self): + super(PatchIoULoss, self).__init__() + self.iou_loss = IoULoss() + + def forward(self, pred, target): + win_y, win_x = 64, 64 + iou_loss = 0. + for anchor_y in range(0, target.shape[0], win_y): + for anchor_x in range(0, target.shape[1], win_y): + patch_pred = pred[:, :, anchor_y:anchor_y+win_y, anchor_x:anchor_x+win_x] + patch_target = target[:, :, anchor_y:anchor_y+win_y, anchor_x:anchor_x+win_x] + patch_iou_loss = self.iou_loss(patch_pred, patch_target) + iou_loss += patch_iou_loss + return iou_loss + + +class ThrReg_loss(torch.nn.Module): + def __init__(self): + super(ThrReg_loss, self).__init__() + + def forward(self, pred, gt=None): + return torch.mean(1 - ((pred - 0) ** 2 + (pred - 1) ** 2)) + + +class ClsLoss(nn.Module): + """ + Auxiliary classification loss for each refined class output. + """ + def __init__(self): + super(ClsLoss, self).__init__() + self.config = Config() + self.lambdas_cls = self.config.lambdas_cls + + self.criterions_last = { + 'ce': nn.CrossEntropyLoss() + } + + def forward(self, preds, gt): + loss = 0. + for _, pred_lvl in enumerate(preds): + if pred_lvl is None: + continue + for criterion_name, criterion in self.criterions_last.items(): + loss += criterion(pred_lvl, gt) * self.lambdas_cls[criterion_name] + return loss + + +class PixLoss(nn.Module): + """ + Pixel loss for each refined map output. + """ + def __init__(self): + super(PixLoss, self).__init__() + self.config = Config() + self.lambdas_pix_last = self.config.lambdas_pix_last + + self.criterions_last = {} + if 'bce' in self.lambdas_pix_last and self.lambdas_pix_last['bce']: + self.criterions_last['bce'] = nn.BCELoss() if not self.config.use_fp16 else nn.BCEWithLogitsLoss() + if 'iou' in self.lambdas_pix_last and self.lambdas_pix_last['iou']: + self.criterions_last['iou'] = IoULoss() + if 'iou_patch' in self.lambdas_pix_last and self.lambdas_pix_last['iou_patch']: + self.criterions_last['iou_patch'] = PatchIoULoss() + if 'ssim' in self.lambdas_pix_last and self.lambdas_pix_last['ssim']: + self.criterions_last['ssim'] = SSIMLoss() + if 'mae' in self.lambdas_pix_last and self.lambdas_pix_last['mae']: + self.criterions_last['mae'] = nn.L1Loss() + if 'mse' in self.lambdas_pix_last and self.lambdas_pix_last['mse']: + self.criterions_last['mse'] = nn.MSELoss() + if 'reg' in self.lambdas_pix_last and self.lambdas_pix_last['reg']: + self.criterions_last['reg'] = ThrReg_loss() + if 'cnt' in self.lambdas_pix_last and self.lambdas_pix_last['cnt']: + self.criterions_last['cnt'] = ContourLoss() + if 'structure' in self.lambdas_pix_last and self.lambdas_pix_last['structure']: + self.criterions_last['structure'] = StructureLoss() + + def forward(self, scaled_preds, gt): + loss = 0. + criterions_embedded_with_sigmoid = ['structure', ] + ['bce'] if self.config.use_fp16 else [] + for _, pred_lvl in enumerate(scaled_preds): + if pred_lvl.shape != gt.shape: + pred_lvl = nn.functional.interpolate(pred_lvl, size=gt.shape[2:], mode='bilinear', align_corners=True) + for criterion_name, criterion in self.criterions_last.items(): + _loss = criterion(pred_lvl.sigmoid() if criterion_name not in criterions_embedded_with_sigmoid else pred_lvl, gt) * self.lambdas_pix_last[criterion_name] + loss += _loss + # print(criterion_name, _loss.item()) + return loss + + +class SSIMLoss(torch.nn.Module): + def __init__(self, window_size=11, size_average=True): + super(SSIMLoss, self).__init__() + self.window_size = window_size + self.size_average = size_average + self.channel = 1 + self.window = create_window(window_size, self.channel) + + def forward(self, img1, img2): + (_, channel, _, _) = img1.size() + if channel == self.channel and self.window.data.type() == img1.data.type(): + window = self.window + else: + window = create_window(self.window_size, channel) + if img1.is_cuda: + window = window.cuda(img1.get_device()) + window = window.type_as(img1) + self.window = window + self.channel = channel + return 1 - _ssim(img1, img2, window, self.window_size, channel, self.size_average) + + +def gaussian(window_size, sigma): + gauss = torch.Tensor([exp(-(x - window_size//2)**2/float(2*sigma**2)) for x in range(window_size)]) + return gauss/gauss.sum() + + +def create_window(window_size, channel): + _1D_window = gaussian(window_size, 1.5).unsqueeze(1) + _2D_window = _1D_window.mm(_1D_window.t()).float().unsqueeze(0).unsqueeze(0) + window = Variable(_2D_window.expand(channel, 1, window_size, window_size).contiguous()) + return window + + +def _ssim(img1, img2, window, window_size, channel, size_average=True): + mu1 = F.conv2d(img1, window, padding = window_size//2, groups=channel) + mu2 = F.conv2d(img2, window, padding = window_size//2, groups=channel) + + mu1_sq = mu1.pow(2) + mu2_sq = mu2.pow(2) + mu1_mu2 = mu1*mu2 + + sigma1_sq = F.conv2d(img1*img1, window, padding=window_size//2, groups=channel) - mu1_sq + sigma2_sq = F.conv2d(img2*img2, window, padding=window_size//2, groups=channel) - mu2_sq + sigma12 = F.conv2d(img1*img2, window, padding=window_size//2, groups=channel) - mu1_mu2 + + C1 = 0.01**2 + C2 = 0.03**2 + + ssim_map = ((2*mu1_mu2 + C1)*(2*sigma12 + C2))/((mu1_sq + mu2_sq + C1)*(sigma1_sq + sigma2_sq + C2)) + + if size_average: + return ssim_map.mean() + else: + return ssim_map.mean(1).mean(1).mean(1) + + +def SSIM(x, y): + C1 = 0.01 ** 2 + C2 = 0.03 ** 2 + + mu_x = nn.AvgPool2d(3, 1, 1)(x) + mu_y = nn.AvgPool2d(3, 1, 1)(y) + mu_x_mu_y = mu_x * mu_y + mu_x_sq = mu_x.pow(2) + mu_y_sq = mu_y.pow(2) + + sigma_x = nn.AvgPool2d(3, 1, 1)(x * x) - mu_x_sq + sigma_y = nn.AvgPool2d(3, 1, 1)(y * y) - mu_y_sq + sigma_xy = nn.AvgPool2d(3, 1, 1)(x * y) - mu_x_mu_y + + SSIM_n = (2 * mu_x_mu_y + C1) * (2 * sigma_xy + C2) + SSIM_d = (mu_x_sq + mu_y_sq + C1) * (sigma_x + sigma_y + C2) + SSIM = SSIM_n / SSIM_d + + return torch.clamp((1 - SSIM) / 2, 0, 1) + + +def saliency_structure_consistency(x, y): + ssim = torch.mean(SSIM(x,y)) + return ssim diff --git a/py/BiRefNet_v2/make_a_copy.sh b/py/BiRefNet_v2/make_a_copy.sh new file mode 100644 index 0000000..97a35fb --- /dev/null +++ b/py/BiRefNet_v2/make_a_copy.sh @@ -0,0 +1,18 @@ +#!/bin/bash +# Set dst repo here. +repo=$1 +mkdir ../${repo} +mkdir ../${repo}/evaluation +mkdir ../${repo}/models +mkdir ../${repo}/models/backbones +mkdir ../${repo}/models/modules +mkdir ../${repo}/models/refinement + +cp ./*.sh ../${repo} +cp ./*.py ../${repo} +cp ./evaluation/*.py ../${repo}/evaluation +cp ./models/*.py ../${repo}/models +cp ./models/backbones/*.py ../${repo}/models/backbones +cp ./models/modules/*.py ../${repo}/models/modules +cp ./models/refinement/*.py ../${repo}/models/refinement +cp -r ./.git* ../${repo} diff --git a/py/BiRefNet_v2/models/backbones/build_backbone.py b/py/BiRefNet_v2/models/backbones/build_backbone.py new file mode 100644 index 0000000..65761a1 --- /dev/null +++ b/py/BiRefNet_v2/models/backbones/build_backbone.py @@ -0,0 +1,44 @@ +import torch +import torch.nn as nn +from collections import OrderedDict +from torchvision.models import vgg16, vgg16_bn, VGG16_Weights, VGG16_BN_Weights, resnet50, ResNet50_Weights +from ...models.backbones.pvt_v2 import pvt_v2_b0, pvt_v2_b1, pvt_v2_b2, pvt_v2_b5 +from ...models.backbones.swin_v1 import swin_v1_t, swin_v1_s, swin_v1_b, swin_v1_l +from ...config import Config + + +config = Config() + +def build_backbone(bb_name, pretrained=True, params_settings=''): + if bb_name == 'vgg16': + bb_net = list(vgg16(pretrained=VGG16_Weights.DEFAULT if pretrained else None).children())[0] + bb = nn.Sequential(OrderedDict({'conv1': bb_net[:4], 'conv2': bb_net[4:9], 'conv3': bb_net[9:16], 'conv4': bb_net[16:23]})) + elif bb_name == 'vgg16bn': + bb_net = list(vgg16_bn(pretrained=VGG16_BN_Weights.DEFAULT if pretrained else None).children())[0] + bb = nn.Sequential(OrderedDict({'conv1': bb_net[:6], 'conv2': bb_net[6:13], 'conv3': bb_net[13:23], 'conv4': bb_net[23:33]})) + elif bb_name == 'resnet50': + bb_net = list(resnet50(pretrained=ResNet50_Weights.DEFAULT if pretrained else None).children()) + bb = nn.Sequential(OrderedDict({'conv1': nn.Sequential(*bb_net[0:3]), 'conv2': bb_net[4], 'conv3': bb_net[5], 'conv4': bb_net[6]})) + else: + bb = eval('{}({})'.format(bb_name, params_settings)) + if pretrained: + bb = load_weights(bb, bb_name) + return bb + +def load_weights(model, model_name): + save_model = torch.load(config.weights[model_name], map_location='cpu') + model_dict = model.state_dict() + state_dict = {k: v if v.size() == model_dict[k].size() else model_dict[k] for k, v in save_model.items() if k in model_dict.keys()} + # to ignore the weights with mismatched size when I modify the backbone itself. + if not state_dict: + save_model_keys = list(save_model.keys()) + sub_item = save_model_keys[0] if len(save_model_keys) == 1 else None + state_dict = {k: v if v.size() == model_dict[k].size() else model_dict[k] for k, v in save_model[sub_item].items() if k in model_dict.keys()} + if not state_dict or not sub_item: + print('Weights are not successully loaded. Check the state dict of weights file.') + return None + else: + print('Found correct weights in the "{}" item of loaded state_dict.'.format(sub_item)) + model_dict.update(state_dict) + model.load_state_dict(model_dict) + return model diff --git a/py/BiRefNet_v2/models/backbones/pvt_v2.py b/py/BiRefNet_v2/models/backbones/pvt_v2.py new file mode 100644 index 0000000..4b902dd --- /dev/null +++ b/py/BiRefNet_v2/models/backbones/pvt_v2.py @@ -0,0 +1,435 @@ +import torch +import torch.nn as nn +from functools import partial + +from timm.models.layers import DropPath, to_2tuple, trunc_normal_ +from timm.models import register_model + +import math + +from ...config import Config + +config = Config() + +class Mlp(nn.Module): + def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.): + super().__init__() + out_features = out_features or in_features + hidden_features = hidden_features or in_features + self.fc1 = nn.Linear(in_features, hidden_features) + self.dwconv = DWConv(hidden_features) + self.act = act_layer() + self.fc2 = nn.Linear(hidden_features, out_features) + self.drop = nn.Dropout(drop) + + self.apply(self._init_weights) + + def _init_weights(self, m): + if isinstance(m, nn.Linear): + trunc_normal_(m.weight, std=.02) + if isinstance(m, nn.Linear) and m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.LayerNorm): + nn.init.constant_(m.bias, 0) + nn.init.constant_(m.weight, 1.0) + elif isinstance(m, nn.Conv2d): + fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels + fan_out //= m.groups + m.weight.data.normal_(0, math.sqrt(2.0 / fan_out)) + if m.bias is not None: + m.bias.data.zero_() + + def forward(self, x, H, W): + x = self.fc1(x) + x = self.dwconv(x, H, W) + x = self.act(x) + x = self.drop(x) + x = self.fc2(x) + x = self.drop(x) + return x + + +class Attention(nn.Module): + def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0., sr_ratio=1): + super().__init__() + assert dim % num_heads == 0, f"dim {dim} should be divided by num_heads {num_heads}." + + self.dim = dim + self.num_heads = num_heads + head_dim = dim // num_heads + self.scale = qk_scale or head_dim ** -0.5 + + self.q = nn.Linear(dim, dim, bias=qkv_bias) + self.kv = nn.Linear(dim, dim * 2, bias=qkv_bias) + self.attn_drop_prob = attn_drop + self.attn_drop = nn.Dropout(attn_drop) + self.proj = nn.Linear(dim, dim) + self.proj_drop = nn.Dropout(proj_drop) + + self.sr_ratio = sr_ratio + if sr_ratio > 1: + self.sr = nn.Conv2d(dim, dim, kernel_size=sr_ratio, stride=sr_ratio) + self.norm = nn.LayerNorm(dim) + + self.apply(self._init_weights) + + def _init_weights(self, m): + if isinstance(m, nn.Linear): + trunc_normal_(m.weight, std=.02) + if isinstance(m, nn.Linear) and m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.LayerNorm): + nn.init.constant_(m.bias, 0) + nn.init.constant_(m.weight, 1.0) + elif isinstance(m, nn.Conv2d): + fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels + fan_out //= m.groups + m.weight.data.normal_(0, math.sqrt(2.0 / fan_out)) + if m.bias is not None: + m.bias.data.zero_() + + def forward(self, x, H, W): + B, N, C = x.shape + q = self.q(x).reshape(B, N, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3) + + if self.sr_ratio > 1: + x_ = x.permute(0, 2, 1).reshape(B, C, H, W) + x_ = self.sr(x_).reshape(B, C, -1).permute(0, 2, 1) + x_ = self.norm(x_) + kv = self.kv(x_).reshape(B, -1, 2, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) + else: + kv = self.kv(x).reshape(B, -1, 2, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) + k, v = kv[0], kv[1] + + if config.SDPA_enabled: + x = torch.nn.functional.scaled_dot_product_attention( + q, k, v, + attn_mask=None, dropout_p=self.attn_drop_prob, is_causal=False + ).transpose(1, 2).reshape(B, N, C) + else: + attn = (q @ k.transpose(-2, -1)) * self.scale + attn = attn.softmax(dim=-1) + attn = self.attn_drop(attn) + + x = (attn @ v).transpose(1, 2).reshape(B, N, C) + x = self.proj(x) + x = self.proj_drop(x) + + return x + + +class Block(nn.Module): + + def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0., + drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, sr_ratio=1): + super().__init__() + self.norm1 = norm_layer(dim) + self.attn = Attention( + dim, + num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, + attn_drop=attn_drop, proj_drop=drop, sr_ratio=sr_ratio) + # NOTE: drop path for stochastic depth, we shall see if this is better than dropout here + self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity() + self.norm2 = norm_layer(dim) + mlp_hidden_dim = int(dim * mlp_ratio) + self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop) + + self.apply(self._init_weights) + + def _init_weights(self, m): + if isinstance(m, nn.Linear): + trunc_normal_(m.weight, std=.02) + if isinstance(m, nn.Linear) and m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.LayerNorm): + nn.init.constant_(m.bias, 0) + nn.init.constant_(m.weight, 1.0) + elif isinstance(m, nn.Conv2d): + fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels + fan_out //= m.groups + m.weight.data.normal_(0, math.sqrt(2.0 / fan_out)) + if m.bias is not None: + m.bias.data.zero_() + + def forward(self, x, H, W): + x = x + self.drop_path(self.attn(self.norm1(x), H, W)) + x = x + self.drop_path(self.mlp(self.norm2(x), H, W)) + + return x + + +class OverlapPatchEmbed(nn.Module): + """ Image to Patch Embedding + """ + + def __init__(self, img_size=224, patch_size=7, stride=4, in_channels=3, embed_dim=768): + super().__init__() + img_size = to_2tuple(img_size) + patch_size = to_2tuple(patch_size) + + self.img_size = img_size + self.patch_size = patch_size + self.H, self.W = img_size[0] // patch_size[0], img_size[1] // patch_size[1] + self.num_patches = self.H * self.W + self.proj = nn.Conv2d(in_channels, embed_dim, kernel_size=patch_size, stride=stride, + padding=(patch_size[0] // 2, patch_size[1] // 2)) + self.norm = nn.LayerNorm(embed_dim) + + self.apply(self._init_weights) + + def _init_weights(self, m): + if isinstance(m, nn.Linear): + trunc_normal_(m.weight, std=.02) + if isinstance(m, nn.Linear) and m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.LayerNorm): + nn.init.constant_(m.bias, 0) + nn.init.constant_(m.weight, 1.0) + elif isinstance(m, nn.Conv2d): + fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels + fan_out //= m.groups + m.weight.data.normal_(0, math.sqrt(2.0 / fan_out)) + if m.bias is not None: + m.bias.data.zero_() + + def forward(self, x): + x = self.proj(x) + _, _, H, W = x.shape + x = x.flatten(2).transpose(1, 2) + x = self.norm(x) + + return x, H, W + + +class PyramidVisionTransformerImpr(nn.Module): + def __init__(self, img_size=224, patch_size=16, in_channels=3, num_classes=1000, embed_dims=[64, 128, 256, 512], + num_heads=[1, 2, 4, 8], mlp_ratios=[4, 4, 4, 4], qkv_bias=False, qk_scale=None, drop_rate=0., + attn_drop_rate=0., drop_path_rate=0., norm_layer=nn.LayerNorm, + depths=[3, 4, 6, 3], sr_ratios=[8, 4, 2, 1]): + super().__init__() + self.num_classes = num_classes + self.depths = depths + + # patch_embed + self.patch_embed1 = OverlapPatchEmbed(img_size=img_size, patch_size=7, stride=4, in_channels=in_channels, + embed_dim=embed_dims[0]) + self.patch_embed2 = OverlapPatchEmbed(img_size=img_size // 4, patch_size=3, stride=2, in_channels=embed_dims[0], + embed_dim=embed_dims[1]) + self.patch_embed3 = OverlapPatchEmbed(img_size=img_size // 8, patch_size=3, stride=2, in_channels=embed_dims[1], + embed_dim=embed_dims[2]) + self.patch_embed4 = OverlapPatchEmbed(img_size=img_size // 16, patch_size=3, stride=2, in_channels=embed_dims[2], + embed_dim=embed_dims[3]) + + # transformer encoder + dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] # stochastic depth decay rule + cur = 0 + self.block1 = nn.ModuleList([Block( + dim=embed_dims[0], num_heads=num_heads[0], mlp_ratio=mlp_ratios[0], qkv_bias=qkv_bias, qk_scale=qk_scale, + drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer, + sr_ratio=sr_ratios[0]) + for i in range(depths[0])]) + self.norm1 = norm_layer(embed_dims[0]) + + cur += depths[0] + self.block2 = nn.ModuleList([Block( + dim=embed_dims[1], num_heads=num_heads[1], mlp_ratio=mlp_ratios[1], qkv_bias=qkv_bias, qk_scale=qk_scale, + drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer, + sr_ratio=sr_ratios[1]) + for i in range(depths[1])]) + self.norm2 = norm_layer(embed_dims[1]) + + cur += depths[1] + self.block3 = nn.ModuleList([Block( + dim=embed_dims[2], num_heads=num_heads[2], mlp_ratio=mlp_ratios[2], qkv_bias=qkv_bias, qk_scale=qk_scale, + drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer, + sr_ratio=sr_ratios[2]) + for i in range(depths[2])]) + self.norm3 = norm_layer(embed_dims[2]) + + cur += depths[2] + self.block4 = nn.ModuleList([Block( + dim=embed_dims[3], num_heads=num_heads[3], mlp_ratio=mlp_ratios[3], qkv_bias=qkv_bias, qk_scale=qk_scale, + drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer, + sr_ratio=sr_ratios[3]) + for i in range(depths[3])]) + self.norm4 = norm_layer(embed_dims[3]) + + # classification head + # self.head = nn.Linear(embed_dims[3], num_classes) if num_classes > 0 else nn.Identity() + + self.apply(self._init_weights) + + def _init_weights(self, m): + if isinstance(m, nn.Linear): + trunc_normal_(m.weight, std=.02) + if isinstance(m, nn.Linear) and m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.LayerNorm): + nn.init.constant_(m.bias, 0) + nn.init.constant_(m.weight, 1.0) + elif isinstance(m, nn.Conv2d): + fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels + fan_out //= m.groups + m.weight.data.normal_(0, math.sqrt(2.0 / fan_out)) + if m.bias is not None: + m.bias.data.zero_() + + def init_weights(self, pretrained=None): + if isinstance(pretrained, str): + logger = 1 + #load_checkpoint(self, pretrained, map_location='cpu', strict=False, logger=logger) + + def reset_drop_path(self, drop_path_rate): + dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(self.depths))] + cur = 0 + for i in range(self.depths[0]): + self.block1[i].drop_path.drop_prob = dpr[cur + i] + + cur += self.depths[0] + for i in range(self.depths[1]): + self.block2[i].drop_path.drop_prob = dpr[cur + i] + + cur += self.depths[1] + for i in range(self.depths[2]): + self.block3[i].drop_path.drop_prob = dpr[cur + i] + + cur += self.depths[2] + for i in range(self.depths[3]): + self.block4[i].drop_path.drop_prob = dpr[cur + i] + + def freeze_patch_emb(self): + self.patch_embed1.requires_grad = False + + @torch.jit.ignore + def no_weight_decay(self): + return {'pos_embed1', 'pos_embed2', 'pos_embed3', 'pos_embed4', 'cls_token'} # has pos_embed may be better + + def get_classifier(self): + return self.head + + def reset_classifier(self, num_classes, global_pool=''): + self.num_classes = num_classes + self.head = nn.Linear(self.embed_dim, num_classes) if num_classes > 0 else nn.Identity() + + def forward_features(self, x): + B = x.shape[0] + outs = [] + + # stage 1 + x, H, W = self.patch_embed1(x) + for i, blk in enumerate(self.block1): + x = blk(x, H, W) + x = self.norm1(x) + x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous() + outs.append(x) + + # stage 2 + x, H, W = self.patch_embed2(x) + for i, blk in enumerate(self.block2): + x = blk(x, H, W) + x = self.norm2(x) + x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous() + outs.append(x) + + # stage 3 + x, H, W = self.patch_embed3(x) + for i, blk in enumerate(self.block3): + x = blk(x, H, W) + x = self.norm3(x) + x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous() + outs.append(x) + + # stage 4 + x, H, W = self.patch_embed4(x) + for i, blk in enumerate(self.block4): + x = blk(x, H, W) + x = self.norm4(x) + x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous() + outs.append(x) + + return outs + + # return x.mean(dim=1) + + def forward(self, x): + x = self.forward_features(x) + # x = self.head(x) + + return x + + +class DWConv(nn.Module): + def __init__(self, dim=768): + super(DWConv, self).__init__() + self.dwconv = nn.Conv2d(dim, dim, 3, 1, 1, bias=True, groups=dim) + + def forward(self, x, H, W): + B, N, C = x.shape + x = x.transpose(1, 2).view(B, C, H, W).contiguous() + x = self.dwconv(x) + x = x.flatten(2).transpose(1, 2) + + return x + + +def _conv_filter(state_dict, patch_size=16): + """ convert patch embedding weight from manual patchify + linear proj to conv""" + out_dict = {} + for k, v in state_dict.items(): + if 'patch_embed.proj.weight' in k: + v = v.reshape((v.shape[0], 3, patch_size, patch_size)) + out_dict[k] = v + + return out_dict + + +## @register_model +class pvt_v2_b0(PyramidVisionTransformerImpr): + def __init__(self, **kwargs): + super(pvt_v2_b0, self).__init__( + patch_size=4, embed_dims=[32, 64, 160, 256], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4], + qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[2, 2, 2, 2], sr_ratios=[8, 4, 2, 1], + drop_rate=0.0, drop_path_rate=0.1) + + + +## @register_model +class pvt_v2_b1(PyramidVisionTransformerImpr): + def __init__(self, **kwargs): + super(pvt_v2_b1, self).__init__( + patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4], + qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[2, 2, 2, 2], sr_ratios=[8, 4, 2, 1], + drop_rate=0.0, drop_path_rate=0.1) + +## @register_model +class pvt_v2_b2(PyramidVisionTransformerImpr): + def __init__(self, in_channels=3, **kwargs): + super(pvt_v2_b2, self).__init__( + patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4], + qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 4, 6, 3], sr_ratios=[8, 4, 2, 1], + drop_rate=0.0, drop_path_rate=0.1, in_channels=in_channels) + +## @register_model +class pvt_v2_b3(PyramidVisionTransformerImpr): + def __init__(self, **kwargs): + super(pvt_v2_b3, self).__init__( + patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4], + qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 4, 18, 3], sr_ratios=[8, 4, 2, 1], + drop_rate=0.0, drop_path_rate=0.1) + +## @register_model +class pvt_v2_b4(PyramidVisionTransformerImpr): + def __init__(self, **kwargs): + super(pvt_v2_b4, self).__init__( + patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4], + qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 8, 27, 3], sr_ratios=[8, 4, 2, 1], + drop_rate=0.0, drop_path_rate=0.1) + + +## @register_model +class pvt_v2_b5(PyramidVisionTransformerImpr): + def __init__(self, **kwargs): + super(pvt_v2_b5, self).__init__( + patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[4, 4, 4, 4], + qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 6, 40, 3], sr_ratios=[8, 4, 2, 1], + drop_rate=0.0, drop_path_rate=0.1) diff --git a/py/BiRefNet_v2/models/backbones/swin_v1.py b/py/BiRefNet_v2/models/backbones/swin_v1.py new file mode 100644 index 0000000..7739622 --- /dev/null +++ b/py/BiRefNet_v2/models/backbones/swin_v1.py @@ -0,0 +1,627 @@ +# -------------------------------------------------------- +# Swin Transformer +# Copyright (c) 2021 Microsoft +# Licensed under The MIT License [see LICENSE for details] +# Written by Ze Liu, Yutong Lin, Yixuan Wei +# -------------------------------------------------------- + +import torch +import torch.nn as nn +import torch.nn.functional as F +import torch.utils.checkpoint as checkpoint +import numpy as np +from timm.models.layers import DropPath, to_2tuple, trunc_normal_ + +from ...config import Config + + +config = Config() + +class Mlp(nn.Module): + """ Multilayer perceptron.""" + + def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.): + super().__init__() + out_features = out_features or in_features + hidden_features = hidden_features or in_features + self.fc1 = nn.Linear(in_features, hidden_features) + self.act = act_layer() + self.fc2 = nn.Linear(hidden_features, out_features) + self.drop = nn.Dropout(drop) + + def forward(self, x): + x = self.fc1(x) + x = self.act(x) + x = self.drop(x) + x = self.fc2(x) + x = self.drop(x) + return x + + +def window_partition(x, window_size): + """ + Args: + x: (B, H, W, C) + window_size (int): window size + + Returns: + windows: (num_windows*B, window_size, window_size, C) + """ + B, H, W, C = x.shape + x = x.view(B, H // window_size, window_size, W // window_size, window_size, C) + windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C) + return windows + + +def window_reverse(windows, window_size, H, W): + """ + Args: + windows: (num_windows*B, window_size, window_size, C) + window_size (int): Window size + H (int): Height of image + W (int): Width of image + + Returns: + x: (B, H, W, C) + """ + B = int(windows.shape[0] / (H * W / window_size / window_size)) + x = windows.view(B, H // window_size, W // window_size, window_size, window_size, -1) + x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1) + return x + + +class WindowAttention(nn.Module): + """ Window based multi-head self attention (W-MSA) module with relative position bias. + It supports both of shifted and non-shifted window. + + Args: + dim (int): Number of input channels. + window_size (tuple[int]): The height and width of the window. + num_heads (int): Number of attention heads. + qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True + qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set + attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0 + proj_drop (float, optional): Dropout ratio of output. Default: 0.0 + """ + + def __init__(self, dim, window_size, num_heads, qkv_bias=True, qk_scale=None, attn_drop=0., proj_drop=0.): + + super().__init__() + self.dim = dim + self.window_size = window_size # Wh, Ww + self.num_heads = num_heads + head_dim = dim // num_heads + self.scale = qk_scale or head_dim ** -0.5 + + # define a parameter table of relative position bias + self.relative_position_bias_table = nn.Parameter( + torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1), num_heads)) # 2*Wh-1 * 2*Ww-1, nH + + # get pair-wise relative position index for each token inside the window + coords_h = torch.arange(self.window_size[0]) + coords_w = torch.arange(self.window_size[1]) + coords = torch.stack(torch.meshgrid([coords_h, coords_w], indexing='ij')) # 2, Wh, Ww + coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww + relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww + relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2 + relative_coords[:, :, 0] += self.window_size[0] - 1 # shift to start from 0 + relative_coords[:, :, 1] += self.window_size[1] - 1 + relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1 + relative_position_index = relative_coords.sum(-1) # Wh*Ww, Wh*Ww + self.register_buffer("relative_position_index", relative_position_index) + + self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) + self.attn_drop_prob = attn_drop + self.attn_drop = nn.Dropout(attn_drop) + self.proj = nn.Linear(dim, dim) + self.proj_drop = nn.Dropout(proj_drop) + + trunc_normal_(self.relative_position_bias_table, std=.02) + self.softmax = nn.Softmax(dim=-1) + + def forward(self, x, mask=None): + """ Forward function. + + Args: + x: input features with shape of (num_windows*B, N, C) + mask: (0/-inf) mask with shape of (num_windows, Wh*Ww, Wh*Ww) or None + """ + B_, N, C = x.shape + qkv = self.qkv(x).reshape(B_, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) + q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple) + + q = q * self.scale + + if config.SDPA_enabled: + x = torch.nn.functional.scaled_dot_product_attention( + q, k, v, + attn_mask=None, dropout_p=self.attn_drop_prob, is_causal=False + ).transpose(1, 2).reshape(B_, N, C) + else: + attn = (q @ k.transpose(-2, -1)) + + relative_position_bias = self.relative_position_bias_table[self.relative_position_index.view(-1)].view( + self.window_size[0] * self.window_size[1], self.window_size[0] * self.window_size[1], -1) # Wh*Ww,Wh*Ww,nH + relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww + attn = attn + relative_position_bias.unsqueeze(0) + + if mask is not None: + nW = mask.shape[0] + attn = attn.view(B_ // nW, nW, self.num_heads, N, N) + mask.unsqueeze(1).unsqueeze(0) + attn = attn.view(-1, self.num_heads, N, N) + attn = self.softmax(attn) + else: + attn = self.softmax(attn) + + attn = self.attn_drop(attn) + + x = (attn @ v).transpose(1, 2).reshape(B_, N, C) + x = self.proj(x) + x = self.proj_drop(x) + return x + + +class SwinTransformerBlock(nn.Module): + """ Swin Transformer Block. + + Args: + dim (int): Number of input channels. + num_heads (int): Number of attention heads. + window_size (int): Window size. + shift_size (int): Shift size for SW-MSA. + mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. + qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True + qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set. + drop (float, optional): Dropout rate. Default: 0.0 + attn_drop (float, optional): Attention dropout rate. Default: 0.0 + drop_path (float, optional): Stochastic depth rate. Default: 0.0 + act_layer (nn.Module, optional): Activation layer. Default: nn.GELU + norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm + """ + + def __init__(self, dim, num_heads, window_size=7, shift_size=0, + mlp_ratio=4., qkv_bias=True, qk_scale=None, drop=0., attn_drop=0., drop_path=0., + act_layer=nn.GELU, norm_layer=nn.LayerNorm): + super().__init__() + self.dim = dim + self.num_heads = num_heads + self.window_size = window_size + self.shift_size = shift_size + self.mlp_ratio = mlp_ratio + assert 0 <= self.shift_size < self.window_size, "shift_size must in 0-window_size" + + self.norm1 = norm_layer(dim) + self.attn = WindowAttention( + dim, window_size=to_2tuple(self.window_size), num_heads=num_heads, + qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop) + + self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity() + self.norm2 = norm_layer(dim) + mlp_hidden_dim = int(dim * mlp_ratio) + self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop) + + self.H = None + self.W = None + + def forward(self, x, mask_matrix): + """ Forward function. + + Args: + x: Input feature, tensor size (B, H*W, C). + H, W: Spatial resolution of the input feature. + mask_matrix: Attention mask for cyclic shift. + """ + B, L, C = x.shape + H, W = self.H, self.W + assert L == H * W, "input feature has wrong size" + + shortcut = x + x = self.norm1(x) + x = x.view(B, H, W, C) + + # pad feature maps to multiples of window size + pad_l = pad_t = 0 + pad_r = (self.window_size - W % self.window_size) % self.window_size + pad_b = (self.window_size - H % self.window_size) % self.window_size + x = F.pad(x, (0, 0, pad_l, pad_r, pad_t, pad_b)) + _, Hp, Wp, _ = x.shape + + # cyclic shift + if self.shift_size > 0: + shifted_x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2)) + attn_mask = mask_matrix + else: + shifted_x = x + attn_mask = None + + # partition windows + x_windows = window_partition(shifted_x, self.window_size) # nW*B, window_size, window_size, C + x_windows = x_windows.view(-1, self.window_size * self.window_size, C) # nW*B, window_size*window_size, C + + # W-MSA/SW-MSA + attn_windows = self.attn(x_windows, mask=attn_mask) # nW*B, window_size*window_size, C + + # merge windows + attn_windows = attn_windows.view(-1, self.window_size, self.window_size, C) + shifted_x = window_reverse(attn_windows, self.window_size, Hp, Wp) # B H' W' C + + # reverse cyclic shift + if self.shift_size > 0: + x = torch.roll(shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2)) + else: + x = shifted_x + + if pad_r > 0 or pad_b > 0: + x = x[:, :H, :W, :].contiguous() + + x = x.view(B, H * W, C) + + # FFN + x = shortcut + self.drop_path(x) + x = x + self.drop_path(self.mlp(self.norm2(x))) + + return x + + +class PatchMerging(nn.Module): + """ Patch Merging Layer + + Args: + dim (int): Number of input channels. + norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm + """ + def __init__(self, dim, norm_layer=nn.LayerNorm): + super().__init__() + self.dim = dim + self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False) + self.norm = norm_layer(4 * dim) + + def forward(self, x, H, W): + """ Forward function. + + Args: + x: Input feature, tensor size (B, H*W, C). + H, W: Spatial resolution of the input feature. + """ + B, L, C = x.shape + assert L == H * W, "input feature has wrong size" + + x = x.view(B, H, W, C) + + # padding + pad_input = (H % 2 == 1) or (W % 2 == 1) + if pad_input: + x = F.pad(x, (0, 0, 0, W % 2, 0, H % 2)) + + x0 = x[:, 0::2, 0::2, :] # B H/2 W/2 C + x1 = x[:, 1::2, 0::2, :] # B H/2 W/2 C + x2 = x[:, 0::2, 1::2, :] # B H/2 W/2 C + x3 = x[:, 1::2, 1::2, :] # B H/2 W/2 C + x = torch.cat([x0, x1, x2, x3], -1) # B H/2 W/2 4*C + x = x.view(B, -1, 4 * C) # B H/2*W/2 4*C + + x = self.norm(x) + x = self.reduction(x) + + return x + + +class BasicLayer(nn.Module): + """ A basic Swin Transformer layer for one stage. + + Args: + dim (int): Number of feature channels + depth (int): Depths of this stage. + num_heads (int): Number of attention head. + window_size (int): Local window size. Default: 7. + mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4. + qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True + qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set. + drop (float, optional): Dropout rate. Default: 0.0 + attn_drop (float, optional): Attention dropout rate. Default: 0.0 + drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0 + norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm + downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None + use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False. + """ + + def __init__(self, + dim, + depth, + num_heads, + window_size=7, + mlp_ratio=4., + qkv_bias=True, + qk_scale=None, + drop=0., + attn_drop=0., + drop_path=0., + norm_layer=nn.LayerNorm, + downsample=None, + use_checkpoint=False): + super().__init__() + self.window_size = window_size + self.shift_size = window_size // 2 + self.depth = depth + self.use_checkpoint = use_checkpoint + + # build blocks + self.blocks = nn.ModuleList([ + SwinTransformerBlock( + dim=dim, + num_heads=num_heads, + window_size=window_size, + shift_size=0 if (i % 2 == 0) else window_size // 2, + mlp_ratio=mlp_ratio, + qkv_bias=qkv_bias, + qk_scale=qk_scale, + drop=drop, + attn_drop=attn_drop, + drop_path=drop_path[i] if isinstance(drop_path, list) else drop_path, + norm_layer=norm_layer) + for i in range(depth)]) + + # patch merging layer + if downsample is not None: + self.downsample = downsample(dim=dim, norm_layer=norm_layer) + else: + self.downsample = None + + def forward(self, x, H, W): + """ Forward function. + + Args: + x: Input feature, tensor size (B, H*W, C). + H, W: Spatial resolution of the input feature. + """ + + # calculate attention mask for SW-MSA + Hp = int(np.ceil(H / self.window_size)) * self.window_size + Wp = int(np.ceil(W / self.window_size)) * self.window_size + img_mask = torch.zeros((1, Hp, Wp, 1), device=x.device) # 1 Hp Wp 1 + h_slices = (slice(0, -self.window_size), + slice(-self.window_size, -self.shift_size), + slice(-self.shift_size, None)) + w_slices = (slice(0, -self.window_size), + slice(-self.window_size, -self.shift_size), + slice(-self.shift_size, None)) + cnt = 0 + for h in h_slices: + for w in w_slices: + img_mask[:, h, w, :] = cnt + cnt += 1 + + mask_windows = window_partition(img_mask, self.window_size) # nW, window_size, window_size, 1 + mask_windows = mask_windows.view(-1, self.window_size * self.window_size) + attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2) + attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(attn_mask == 0, float(0.0)) + + for blk in self.blocks: + blk.H, blk.W = H, W + if self.use_checkpoint: + x = checkpoint.checkpoint(blk, x, attn_mask) + else: + x = blk(x, attn_mask) + if self.downsample is not None: + x_down = self.downsample(x, H, W) + Wh, Ww = (H + 1) // 2, (W + 1) // 2 + return x, H, W, x_down, Wh, Ww + else: + return x, H, W, x, H, W + + +class PatchEmbed(nn.Module): + """ Image to Patch Embedding + + Args: + patch_size (int): Patch token size. Default: 4. + in_channels (int): Number of input image channels. Default: 3. + embed_dim (int): Number of linear projection output channels. Default: 96. + norm_layer (nn.Module, optional): Normalization layer. Default: None + """ + + def __init__(self, patch_size=4, in_channels=3, embed_dim=96, norm_layer=None): + super().__init__() + patch_size = to_2tuple(patch_size) + self.patch_size = patch_size + + self.in_channels = in_channels + self.embed_dim = embed_dim + + self.proj = nn.Conv2d(in_channels, embed_dim, kernel_size=patch_size, stride=patch_size) + if norm_layer is not None: + self.norm = norm_layer(embed_dim) + else: + self.norm = None + + def forward(self, x): + """Forward function.""" + # padding + _, _, H, W = x.size() + if W % self.patch_size[1] != 0: + x = F.pad(x, (0, self.patch_size[1] - W % self.patch_size[1])) + if H % self.patch_size[0] != 0: + x = F.pad(x, (0, 0, 0, self.patch_size[0] - H % self.patch_size[0])) + + x = self.proj(x) # B C Wh Ww + if self.norm is not None: + Wh, Ww = x.size(2), x.size(3) + x = x.flatten(2).transpose(1, 2) + x = self.norm(x) + x = x.transpose(1, 2).view(-1, self.embed_dim, Wh, Ww) + + return x + + +class SwinTransformer(nn.Module): + """ Swin Transformer backbone. + A PyTorch impl of : `Swin Transformer: Hierarchical Vision Transformer using Shifted Windows` - + https://arxiv.org/pdf/2103.14030 + + Args: + pretrain_img_size (int): Input image size for training the pretrained model, + used in absolute postion embedding. Default 224. + patch_size (int | tuple(int)): Patch size. Default: 4. + in_channels (int): Number of input image channels. Default: 3. + embed_dim (int): Number of linear projection output channels. Default: 96. + depths (tuple[int]): Depths of each Swin Transformer stage. + num_heads (tuple[int]): Number of attention head of each stage. + window_size (int): Window size. Default: 7. + mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4. + qkv_bias (bool): If True, add a learnable bias to query, key, value. Default: True + qk_scale (float): Override default qk scale of head_dim ** -0.5 if set. + drop_rate (float): Dropout rate. + attn_drop_rate (float): Attention dropout rate. Default: 0. + drop_path_rate (float): Stochastic depth rate. Default: 0.2. + norm_layer (nn.Module): Normalization layer. Default: nn.LayerNorm. + ape (bool): If True, add absolute position embedding to the patch embedding. Default: False. + patch_norm (bool): If True, add normalization after patch embedding. Default: True. + out_indices (Sequence[int]): Output from which stages. + frozen_stages (int): Stages to be frozen (stop grad and set eval mode). + -1 means not freezing any parameters. + use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False. + """ + + def __init__(self, + pretrain_img_size=224, + patch_size=4, + in_channels=3, + embed_dim=96, + depths=[2, 2, 6, 2], + num_heads=[3, 6, 12, 24], + window_size=7, + mlp_ratio=4., + qkv_bias=True, + qk_scale=None, + drop_rate=0., + attn_drop_rate=0., + drop_path_rate=0.2, + norm_layer=nn.LayerNorm, + ape=False, + patch_norm=True, + out_indices=(0, 1, 2, 3), + frozen_stages=-1, + use_checkpoint=False): + super().__init__() + + self.pretrain_img_size = pretrain_img_size + self.num_layers = len(depths) + self.embed_dim = embed_dim + self.ape = ape + self.patch_norm = patch_norm + self.out_indices = out_indices + self.frozen_stages = frozen_stages + + # split image into non-overlapping patches + self.patch_embed = PatchEmbed( + patch_size=patch_size, in_channels=in_channels, embed_dim=embed_dim, + norm_layer=norm_layer if self.patch_norm else None) + + # absolute position embedding + if self.ape: + pretrain_img_size = to_2tuple(pretrain_img_size) + patch_size = to_2tuple(patch_size) + patches_resolution = [pretrain_img_size[0] // patch_size[0], pretrain_img_size[1] // patch_size[1]] + + self.absolute_pos_embed = nn.Parameter(torch.zeros(1, embed_dim, patches_resolution[0], patches_resolution[1])) + trunc_normal_(self.absolute_pos_embed, std=.02) + + self.pos_drop = nn.Dropout(p=drop_rate) + + # stochastic depth + dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] # stochastic depth decay rule + + # build layers + self.layers = nn.ModuleList() + for i_layer in range(self.num_layers): + layer = BasicLayer( + dim=int(embed_dim * 2 ** i_layer), + depth=depths[i_layer], + num_heads=num_heads[i_layer], + window_size=window_size, + mlp_ratio=mlp_ratio, + qkv_bias=qkv_bias, + qk_scale=qk_scale, + drop=drop_rate, + attn_drop=attn_drop_rate, + drop_path=dpr[sum(depths[:i_layer]):sum(depths[:i_layer + 1])], + norm_layer=norm_layer, + downsample=PatchMerging if (i_layer < self.num_layers - 1) else None, + use_checkpoint=use_checkpoint) + self.layers.append(layer) + + num_features = [int(embed_dim * 2 ** i) for i in range(self.num_layers)] + self.num_features = num_features + + # add a norm layer for each output + for i_layer in out_indices: + layer = norm_layer(num_features[i_layer]) + layer_name = f'norm{i_layer}' + self.add_module(layer_name, layer) + + self._freeze_stages() + + def _freeze_stages(self): + if self.frozen_stages >= 0: + self.patch_embed.eval() + for param in self.patch_embed.parameters(): + param.requires_grad = False + + if self.frozen_stages >= 1 and self.ape: + self.absolute_pos_embed.requires_grad = False + + if self.frozen_stages >= 2: + self.pos_drop.eval() + for i in range(0, self.frozen_stages - 1): + m = self.layers[i] + m.eval() + for param in m.parameters(): + param.requires_grad = False + + + def forward(self, x): + """Forward function.""" + x = self.patch_embed(x) + + Wh, Ww = x.size(2), x.size(3) + if self.ape: + # interpolate the position embedding to the corresponding size + absolute_pos_embed = F.interpolate(self.absolute_pos_embed, size=(Wh, Ww), mode='bicubic') + x = (x + absolute_pos_embed) # B Wh*Ww C + + outs = []#x.contiguous()] + x = x.flatten(2).transpose(1, 2) + x = self.pos_drop(x) + for i in range(self.num_layers): + layer = self.layers[i] + x_out, H, W, x, Wh, Ww = layer(x, Wh, Ww) + + if i in self.out_indices: + norm_layer = getattr(self, f'norm{i}') + x_out = norm_layer(x_out) + + out = x_out.view(-1, H, W, self.num_features[i]).permute(0, 3, 1, 2).contiguous() + outs.append(out) + + return tuple(outs) + + def train(self, mode=True): + """Convert the model into training mode while keep layers freezed.""" + super(SwinTransformer, self).train(mode) + self._freeze_stages() + +def swin_v1_t(): + model = SwinTransformer(embed_dim=96, depths=[2, 2, 6, 2], num_heads=[3, 6, 12, 24], window_size=7) + return model + +def swin_v1_s(): + model = SwinTransformer(embed_dim=96, depths=[2, 2, 18, 2], num_heads=[3, 6, 12, 24], window_size=7) + return model + +def swin_v1_b(): + model = SwinTransformer(embed_dim=128, depths=[2, 2, 18, 2], num_heads=[4, 8, 16, 32], window_size=12) + return model + +def swin_v1_l(): + model = SwinTransformer(embed_dim=192, depths=[2, 2, 18, 2], num_heads=[6, 12, 24, 48], window_size=12) + return model diff --git a/py/BiRefNet_v2/models/birefnet.py b/py/BiRefNet_v2/models/birefnet.py new file mode 100644 index 0000000..e3fe196 --- /dev/null +++ b/py/BiRefNet_v2/models/birefnet.py @@ -0,0 +1,286 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F +from kornia.filters import laplacian +from huggingface_hub import PyTorchModelHubMixin + +from ..config import Config +from ..dataset import class_labels_TR_sorted +from ..models.backbones.build_backbone import build_backbone +from ..models.modules.decoder_blocks import BasicDecBlk, ResBlk +from ..models.modules.lateral_blocks import BasicLatBlk +from ..models.modules.aspp import ASPP, ASPPDeformable +from ..models.refinement.refiner import Refiner, RefinerPVTInChannels4, RefUNet +from ..models.refinement.stem_layer import StemLayer + + +class BiRefNet( + nn.Module, + PyTorchModelHubMixin, + library_name="birefnet", + repo_url="https://github.com/ZhengPeng7/BiRefNet", + tags=['Image Segmentation', 'Background Removal', 'Mask Generation', 'Dichotomous Image Segmentation', 'Camouflaged Object Detection', 'Salient Object Detection'] +): + def __init__(self, bb_pretrained=True): + super(BiRefNet, self).__init__() + self.config = Config() + self.epoch = 1 + self.bb = build_backbone(self.config.bb, pretrained=bb_pretrained) + + channels = self.config.lateral_channels_in_collection + + if self.config.auxiliary_classification: + self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) + self.cls_head = nn.Sequential( + nn.Linear(channels[0], len(class_labels_TR_sorted)) + ) + + if self.config.squeeze_block: + self.squeeze_module = nn.Sequential(*[ + eval(self.config.squeeze_block.split('_x')[0])(channels[0]+sum(self.config.cxt), channels[0]) + for _ in range(eval(self.config.squeeze_block.split('_x')[1])) + ]) + + self.decoder = Decoder(channels) + + if self.config.ender: + self.dec_end = nn.Sequential( + nn.Conv2d(1, 16, 3, 1, 1), + nn.Conv2d(16, 1, 3, 1, 1), + nn.ReLU(inplace=True), + ) + + # refine patch-level segmentation + if self.config.refine: + if self.config.refine == 'itself': + self.stem_layer = StemLayer(in_channels=3+1, inter_channels=48, out_channels=3, norm_layer='BN' if self.config.batch_size > 1 else 'LN') + else: + self.refiner = eval('{}({})'.format(self.config.refine, 'in_channels=3+1')) + + if self.config.freeze_bb: + # Freeze the backbone... + print(self.named_parameters()) + for key, value in self.named_parameters(): + if 'bb.' in key and 'refiner.' not in key: + value.requires_grad = False + + def forward_enc(self, x): + if self.config.bb in ['vgg16', 'vgg16bn', 'resnet50']: + x1 = self.bb.conv1(x); x2 = self.bb.conv2(x1); x3 = self.bb.conv3(x2); x4 = self.bb.conv4(x3) + else: + x1, x2, x3, x4 = self.bb(x) + if self.config.mul_scl_ipt == 'cat': + B, C, H, W = x.shape + x1_, x2_, x3_, x4_ = self.bb(F.interpolate(x, size=(H//2, W//2), mode='bilinear', align_corners=True)) + x1 = torch.cat([x1, F.interpolate(x1_, size=x1.shape[2:], mode='bilinear', align_corners=True)], dim=1) + x2 = torch.cat([x2, F.interpolate(x2_, size=x2.shape[2:], mode='bilinear', align_corners=True)], dim=1) + x3 = torch.cat([x3, F.interpolate(x3_, size=x3.shape[2:], mode='bilinear', align_corners=True)], dim=1) + x4 = torch.cat([x4, F.interpolate(x4_, size=x4.shape[2:], mode='bilinear', align_corners=True)], dim=1) + elif self.config.mul_scl_ipt == 'add': + B, C, H, W = x.shape + x1_, x2_, x3_, x4_ = self.bb(F.interpolate(x, size=(H//2, W//2), mode='bilinear', align_corners=True)) + x1 = x1 + F.interpolate(x1_, size=x1.shape[2:], mode='bilinear', align_corners=True) + x2 = x2 + F.interpolate(x2_, size=x2.shape[2:], mode='bilinear', align_corners=True) + x3 = x3 + F.interpolate(x3_, size=x3.shape[2:], mode='bilinear', align_corners=True) + x4 = x4 + F.interpolate(x4_, size=x4.shape[2:], mode='bilinear', align_corners=True) + class_preds = self.cls_head(self.avgpool(x4).view(x4.shape[0], -1)) if self.training and self.config.auxiliary_classification else None + if self.config.cxt: + x4 = torch.cat( + ( + *[ + F.interpolate(x1, size=x4.shape[2:], mode='bilinear', align_corners=True), + F.interpolate(x2, size=x4.shape[2:], mode='bilinear', align_corners=True), + F.interpolate(x3, size=x4.shape[2:], mode='bilinear', align_corners=True), + ][-len(self.config.cxt):], + x4 + ), + dim=1 + ) + return (x1, x2, x3, x4), class_preds + + def forward_ori(self, x): + ########## Encoder ########## + (x1, x2, x3, x4), class_preds = self.forward_enc(x) + if self.config.squeeze_block: + x4 = self.squeeze_module(x4) + ########## Decoder ########## + features = [x, x1, x2, x3, x4] + if self.training and self.config.out_ref: + features.append(laplacian(torch.mean(x, dim=1).unsqueeze(1), kernel_size=5)) + scaled_preds = self.decoder(features) + return scaled_preds, class_preds + + def forward(self, x): + scaled_preds, class_preds = self.forward_ori(x) + class_preds_lst = [class_preds] + return [scaled_preds, class_preds_lst] if self.training else scaled_preds + + +class Decoder(nn.Module): + def __init__(self, channels): + super(Decoder, self).__init__() + self.config = Config() + DecoderBlock = eval(self.config.dec_blk) + LateralBlock = eval(self.config.lat_blk) + + if self.config.dec_ipt: + self.split = self.config.dec_ipt_split + N_dec_ipt = 64 + DBlock = SimpleConvs + ic = 64 + ipt_cha_opt = 1 + self.ipt_blk5 = DBlock(2**10*3 if self.split else 3, [N_dec_ipt, channels[0]//8][ipt_cha_opt], inter_channels=ic) + self.ipt_blk4 = DBlock(2**8*3 if self.split else 3, [N_dec_ipt, channels[0]//8][ipt_cha_opt], inter_channels=ic) + self.ipt_blk3 = DBlock(2**6*3 if self.split else 3, [N_dec_ipt, channels[1]//8][ipt_cha_opt], inter_channels=ic) + self.ipt_blk2 = DBlock(2**4*3 if self.split else 3, [N_dec_ipt, channels[2]//8][ipt_cha_opt], inter_channels=ic) + self.ipt_blk1 = DBlock(2**0*3 if self.split else 3, [N_dec_ipt, channels[3]//8][ipt_cha_opt], inter_channels=ic) + else: + self.split = None + + self.decoder_block4 = DecoderBlock(channels[0]+([N_dec_ipt, channels[0]//8][ipt_cha_opt] if self.config.dec_ipt else 0), channels[1]) + self.decoder_block3 = DecoderBlock(channels[1]+([N_dec_ipt, channels[0]//8][ipt_cha_opt] if self.config.dec_ipt else 0), channels[2]) + self.decoder_block2 = DecoderBlock(channels[2]+([N_dec_ipt, channels[1]//8][ipt_cha_opt] if self.config.dec_ipt else 0), channels[3]) + self.decoder_block1 = DecoderBlock(channels[3]+([N_dec_ipt, channels[2]//8][ipt_cha_opt] if self.config.dec_ipt else 0), channels[3]//2) + self.conv_out1 = nn.Sequential(nn.Conv2d(channels[3]//2+([N_dec_ipt, channels[3]//8][ipt_cha_opt] if self.config.dec_ipt else 0), 1, 1, 1, 0)) + + self.lateral_block4 = LateralBlock(channels[1], channels[1]) + self.lateral_block3 = LateralBlock(channels[2], channels[2]) + self.lateral_block2 = LateralBlock(channels[3], channels[3]) + + if self.config.ms_supervision: + self.conv_ms_spvn_4 = nn.Conv2d(channels[1], 1, 1, 1, 0) + self.conv_ms_spvn_3 = nn.Conv2d(channels[2], 1, 1, 1, 0) + self.conv_ms_spvn_2 = nn.Conv2d(channels[3], 1, 1, 1, 0) + + if self.config.out_ref: + _N = 16 + self.gdt_convs_4 = nn.Sequential(nn.Conv2d(channels[1], _N, 3, 1, 1), nn.BatchNorm2d(_N) if self.config.batch_size > 1 else nn.Identity(), nn.ReLU(inplace=True)) + self.gdt_convs_3 = nn.Sequential(nn.Conv2d(channels[2], _N, 3, 1, 1), nn.BatchNorm2d(_N) if self.config.batch_size > 1 else nn.Identity(), nn.ReLU(inplace=True)) + self.gdt_convs_2 = nn.Sequential(nn.Conv2d(channels[3], _N, 3, 1, 1), nn.BatchNorm2d(_N) if self.config.batch_size > 1 else nn.Identity(), nn.ReLU(inplace=True)) + + self.gdt_convs_pred_4 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0)) + self.gdt_convs_pred_3 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0)) + self.gdt_convs_pred_2 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0)) + + self.gdt_convs_attn_4 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0)) + self.gdt_convs_attn_3 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0)) + self.gdt_convs_attn_2 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0)) + + def get_patches_batch(self, x, p): + _size_h, _size_w = p.shape[2:] + patches_batch = [] + for idx in range(x.shape[0]): + columns_x = torch.split(x[idx], split_size_or_sections=_size_w, dim=-1) + patches_x = [] + for column_x in columns_x: + patches_x += [p.unsqueeze(0) for p in torch.split(column_x, split_size_or_sections=_size_h, dim=-2)] + patch_sample = torch.cat(patches_x, dim=1) + patches_batch.append(patch_sample) + return torch.cat(patches_batch, dim=0) + + def forward(self, features): + if self.training and self.config.out_ref: + outs_gdt_pred = [] + outs_gdt_label = [] + x, x1, x2, x3, x4, gdt_gt = features + else: + x, x1, x2, x3, x4 = features + outs = [] + + if self.config.dec_ipt: + patches_batch = self.get_patches_batch(x, x4) if self.split else x + x4 = torch.cat((x4, self.ipt_blk5(F.interpolate(patches_batch, size=x4.shape[2:], mode='bilinear', align_corners=True))), 1) + p4 = self.decoder_block4(x4) + m4 = self.conv_ms_spvn_4(p4) if self.config.ms_supervision and self.training else None + if self.config.out_ref: + p4_gdt = self.gdt_convs_4(p4) + if self.training: + # >> GT: + m4_dia = m4 + gdt_label_main_4 = gdt_gt * F.interpolate(m4_dia, size=gdt_gt.shape[2:], mode='bilinear', align_corners=True) + outs_gdt_label.append(gdt_label_main_4) + # >> Pred: + gdt_pred_4 = self.gdt_convs_pred_4(p4_gdt) + outs_gdt_pred.append(gdt_pred_4) + gdt_attn_4 = self.gdt_convs_attn_4(p4_gdt).sigmoid() + # >> Finally: + p4 = p4 * gdt_attn_4 + _p4 = F.interpolate(p4, size=x3.shape[2:], mode='bilinear', align_corners=True) + _p3 = _p4 + self.lateral_block4(x3) + + if self.config.dec_ipt: + patches_batch = self.get_patches_batch(x, _p3) if self.split else x + _p3 = torch.cat((_p3, self.ipt_blk4(F.interpolate(patches_batch, size=x3.shape[2:], mode='bilinear', align_corners=True))), 1) + p3 = self.decoder_block3(_p3) + m3 = self.conv_ms_spvn_3(p3) if self.config.ms_supervision and self.training else None + if self.config.out_ref: + p3_gdt = self.gdt_convs_3(p3) + if self.training: + # >> GT: + # m3 --dilation--> m3_dia + # G_3^gt * m3_dia --> G_3^m, which is the label of gradient + m3_dia = m3 + gdt_label_main_3 = gdt_gt * F.interpolate(m3_dia, size=gdt_gt.shape[2:], mode='bilinear', align_corners=True) + outs_gdt_label.append(gdt_label_main_3) + # >> Pred: + # p3 --conv--BN--> F_3^G, where F_3^G predicts the \hat{G_3} with xx + # F_3^G --sigmoid--> A_3^G + gdt_pred_3 = self.gdt_convs_pred_3(p3_gdt) + outs_gdt_pred.append(gdt_pred_3) + gdt_attn_3 = self.gdt_convs_attn_3(p3_gdt).sigmoid() + # >> Finally: + # p3 = p3 * A_3^G + p3 = p3 * gdt_attn_3 + _p3 = F.interpolate(p3, size=x2.shape[2:], mode='bilinear', align_corners=True) + _p2 = _p3 + self.lateral_block3(x2) + + if self.config.dec_ipt: + patches_batch = self.get_patches_batch(x, _p2) if self.split else x + _p2 = torch.cat((_p2, self.ipt_blk3(F.interpolate(patches_batch, size=x2.shape[2:], mode='bilinear', align_corners=True))), 1) + p2 = self.decoder_block2(_p2) + m2 = self.conv_ms_spvn_2(p2) if self.config.ms_supervision and self.training else None + if self.config.out_ref: + p2_gdt = self.gdt_convs_2(p2) + if self.training: + # >> GT: + m2_dia = m2 + gdt_label_main_2 = gdt_gt * F.interpolate(m2_dia, size=gdt_gt.shape[2:], mode='bilinear', align_corners=True) + outs_gdt_label.append(gdt_label_main_2) + # >> Pred: + gdt_pred_2 = self.gdt_convs_pred_2(p2_gdt) + outs_gdt_pred.append(gdt_pred_2) + gdt_attn_2 = self.gdt_convs_attn_2(p2_gdt).sigmoid() + # >> Finally: + p2 = p2 * gdt_attn_2 + _p2 = F.interpolate(p2, size=x1.shape[2:], mode='bilinear', align_corners=True) + _p1 = _p2 + self.lateral_block2(x1) + + if self.config.dec_ipt: + patches_batch = self.get_patches_batch(x, _p1) if self.split else x + _p1 = torch.cat((_p1, self.ipt_blk2(F.interpolate(patches_batch, size=x1.shape[2:], mode='bilinear', align_corners=True))), 1) + _p1 = self.decoder_block1(_p1) + _p1 = F.interpolate(_p1, size=x.shape[2:], mode='bilinear', align_corners=True) + + if self.config.dec_ipt: + patches_batch = self.get_patches_batch(x, _p1) if self.split else x + _p1 = torch.cat((_p1, self.ipt_blk1(F.interpolate(patches_batch, size=x.shape[2:], mode='bilinear', align_corners=True))), 1) + p1_out = self.conv_out1(_p1) + + if self.config.ms_supervision and self.training: + outs.append(m4) + outs.append(m3) + outs.append(m2) + outs.append(p1_out) + return outs if not (self.config.out_ref and self.training) else ([outs_gdt_pred, outs_gdt_label], outs) + + +class SimpleConvs(nn.Module): + def __init__( + self, in_channels: int, out_channels: int, inter_channels=64 + ) -> None: + super().__init__() + self.conv1 = nn.Conv2d(in_channels, inter_channels, 3, 1, 1) + self.conv_out = nn.Conv2d(inter_channels, out_channels, 3, 1, 1) + + def forward(self, x): + return self.conv_out(self.conv1(x)) diff --git a/py/BiRefNet_v2/models/modules/aspp.py b/py/BiRefNet_v2/models/modules/aspp.py new file mode 100644 index 0000000..3c4f87e --- /dev/null +++ b/py/BiRefNet_v2/models/modules/aspp.py @@ -0,0 +1,120 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F + +from ...models.modules.deform_conv import DeformableConv2d +from ...config import Config + + +config = Config() + + +class _ASPPModule(nn.Module): + def __init__(self, in_channels, planes, kernel_size, padding, dilation): + super(_ASPPModule, self).__init__() + self.atrous_conv = nn.Conv2d(in_channels, planes, kernel_size=kernel_size, + stride=1, padding=padding, dilation=dilation, bias=False) + self.bn = nn.BatchNorm2d(planes) if config.batch_size > 1 else nn.Identity() + self.relu = nn.ReLU(inplace=True) + + def forward(self, x): + x = self.atrous_conv(x) + x = self.bn(x) + + return self.relu(x) + + +class ASPP(nn.Module): + def __init__(self, in_channels=64, out_channels=None, output_stride=16): + super(ASPP, self).__init__() + self.down_scale = 1 + if out_channels is None: + out_channels = in_channels + self.in_channelster = 256 // self.down_scale + if output_stride == 16: + dilations = [1, 6, 12, 18] + elif output_stride == 8: + dilations = [1, 12, 24, 36] + else: + raise NotImplementedError + + self.aspp1 = _ASPPModule(in_channels, self.in_channelster, 1, padding=0, dilation=dilations[0]) + self.aspp2 = _ASPPModule(in_channels, self.in_channelster, 3, padding=dilations[1], dilation=dilations[1]) + self.aspp3 = _ASPPModule(in_channels, self.in_channelster, 3, padding=dilations[2], dilation=dilations[2]) + self.aspp4 = _ASPPModule(in_channels, self.in_channelster, 3, padding=dilations[3], dilation=dilations[3]) + + self.global_avg_pool = nn.Sequential(nn.AdaptiveAvgPool2d((1, 1)), + nn.Conv2d(in_channels, self.in_channelster, 1, stride=1, bias=False), + nn.BatchNorm2d(self.in_channelster) if config.batch_size > 1 else nn.Identity(), + nn.ReLU(inplace=True)) + self.conv1 = nn.Conv2d(self.in_channelster * 5, out_channels, 1, bias=False) + self.bn1 = nn.BatchNorm2d(out_channels) if config.batch_size > 1 else nn.Identity() + self.relu = nn.ReLU(inplace=True) + self.dropout = nn.Dropout(0.5) + + def forward(self, x): + x1 = self.aspp1(x) + x2 = self.aspp2(x) + x3 = self.aspp3(x) + x4 = self.aspp4(x) + x5 = self.global_avg_pool(x) + x5 = F.interpolate(x5, size=x1.size()[2:], mode='bilinear', align_corners=True) + x = torch.cat((x1, x2, x3, x4, x5), dim=1) + + x = self.conv1(x) + x = self.bn1(x) + x = self.relu(x) + + return self.dropout(x) + + +##################### Deformable +class _ASPPModuleDeformable(nn.Module): + def __init__(self, in_channels, planes, kernel_size, padding): + super(_ASPPModuleDeformable, self).__init__() + self.atrous_conv = DeformableConv2d(in_channels, planes, kernel_size=kernel_size, + stride=1, padding=padding, bias=False) + self.bn = nn.BatchNorm2d(planes) if config.batch_size > 1 else nn.Identity() + self.relu = nn.ReLU(inplace=True) + + def forward(self, x): + x = self.atrous_conv(x) + x = self.bn(x) + + return self.relu(x) + + +class ASPPDeformable(nn.Module): + def __init__(self, in_channels, out_channels=None, parallel_block_sizes=[1, 3, 7]): + super(ASPPDeformable, self).__init__() + self.down_scale = 1 + if out_channels is None: + out_channels = in_channels + self.in_channelster = 256 // self.down_scale + + self.aspp1 = _ASPPModuleDeformable(in_channels, self.in_channelster, 1, padding=0) + self.aspp_deforms = nn.ModuleList([ + _ASPPModuleDeformable(in_channels, self.in_channelster, conv_size, padding=int(conv_size//2)) for conv_size in parallel_block_sizes + ]) + + self.global_avg_pool = nn.Sequential(nn.AdaptiveAvgPool2d((1, 1)), + nn.Conv2d(in_channels, self.in_channelster, 1, stride=1, bias=False), + nn.BatchNorm2d(self.in_channelster) if config.batch_size > 1 else nn.Identity(), + nn.ReLU(inplace=True)) + self.conv1 = nn.Conv2d(self.in_channelster * (2 + len(self.aspp_deforms)), out_channels, 1, bias=False) + self.bn1 = nn.BatchNorm2d(out_channels) if config.batch_size > 1 else nn.Identity() + self.relu = nn.ReLU(inplace=True) + self.dropout = nn.Dropout(0.5) + + def forward(self, x): + x1 = self.aspp1(x) + x_aspp_deforms = [aspp_deform(x) for aspp_deform in self.aspp_deforms] + x5 = self.global_avg_pool(x) + x5 = F.interpolate(x5, size=x1.size()[2:], mode='bilinear', align_corners=True) + x = torch.cat((x1, *x_aspp_deforms, x5), dim=1) + + x = self.conv1(x) + x = self.bn1(x) + x = self.relu(x) + + return self.dropout(x) diff --git a/py/BiRefNet_v2/models/modules/decoder_blocks.py b/py/BiRefNet_v2/models/modules/decoder_blocks.py new file mode 100644 index 0000000..32a0b6a --- /dev/null +++ b/py/BiRefNet_v2/models/modules/decoder_blocks.py @@ -0,0 +1,66 @@ +import torch +import torch.nn as nn + +from ...models.modules.aspp import ASPP, ASPPDeformable +from ...config import Config + + +config = Config() + + +class BasicDecBlk(nn.Module): + def __init__(self, in_channels=64, out_channels=64, inter_channels=64): + super(BasicDecBlk, self).__init__() + inter_channels = in_channels // 4 if config.dec_channels_inter == 'adap' else 64 + self.conv_in = nn.Conv2d(in_channels, inter_channels, 3, 1, padding=1) + self.relu_in = nn.ReLU(inplace=True) + if config.dec_att == 'ASPP': + self.dec_att = ASPP(in_channels=inter_channels) + elif config.dec_att == 'ASPPDeformable': + self.dec_att = ASPPDeformable(in_channels=inter_channels) + self.conv_out = nn.Conv2d(inter_channels, out_channels, 3, 1, padding=1) + self.bn_in = nn.BatchNorm2d(inter_channels) if config.batch_size > 1 else nn.Identity() + self.bn_out = nn.BatchNorm2d(out_channels) if config.batch_size > 1 else nn.Identity() + + def forward(self, x): + x = self.conv_in(x) + x = self.bn_in(x) + x = self.relu_in(x) + if hasattr(self, 'dec_att'): + x = self.dec_att(x) + x = self.conv_out(x) + x = self.bn_out(x) + return x + + +class ResBlk(nn.Module): + def __init__(self, in_channels=64, out_channels=None, inter_channels=64): + super(ResBlk, self).__init__() + if out_channels is None: + out_channels = in_channels + inter_channels = in_channels // 4 if config.dec_channels_inter == 'adap' else 64 + + self.conv_in = nn.Conv2d(in_channels, inter_channels, 3, 1, padding=1) + self.bn_in = nn.BatchNorm2d(inter_channels) if config.batch_size > 1 else nn.Identity() + self.relu_in = nn.ReLU(inplace=True) + + if config.dec_att == 'ASPP': + self.dec_att = ASPP(in_channels=inter_channels) + elif config.dec_att == 'ASPPDeformable': + self.dec_att = ASPPDeformable(in_channels=inter_channels) + + self.conv_out = nn.Conv2d(inter_channels, out_channels, 3, 1, padding=1) + self.bn_out = nn.BatchNorm2d(out_channels) if config.batch_size > 1 else nn.Identity() + + self.conv_resi = nn.Conv2d(in_channels, out_channels, 1, 1, 0) + + def forward(self, x): + _x = self.conv_resi(x) + x = self.conv_in(x) + x = self.bn_in(x) + x = self.relu_in(x) + if hasattr(self, 'dec_att'): + x = self.dec_att(x) + x = self.conv_out(x) + x = self.bn_out(x) + return x + _x diff --git a/py/BiRefNet_v2/models/modules/deform_conv.py b/py/BiRefNet_v2/models/modules/deform_conv.py new file mode 100644 index 0000000..43f5e57 --- /dev/null +++ b/py/BiRefNet_v2/models/modules/deform_conv.py @@ -0,0 +1,66 @@ +import torch +import torch.nn as nn +from torchvision.ops import deform_conv2d + + +class DeformableConv2d(nn.Module): + def __init__(self, + in_channels, + out_channels, + kernel_size=3, + stride=1, + padding=1, + bias=False): + + super(DeformableConv2d, self).__init__() + + assert type(kernel_size) == tuple or type(kernel_size) == int + + kernel_size = kernel_size if type(kernel_size) == tuple else (kernel_size, kernel_size) + self.stride = stride if type(stride) == tuple else (stride, stride) + self.padding = padding + + self.offset_conv = nn.Conv2d(in_channels, + 2 * kernel_size[0] * kernel_size[1], + kernel_size=kernel_size, + stride=stride, + padding=self.padding, + bias=True) + + nn.init.constant_(self.offset_conv.weight, 0.) + nn.init.constant_(self.offset_conv.bias, 0.) + + self.modulator_conv = nn.Conv2d(in_channels, + 1 * kernel_size[0] * kernel_size[1], + kernel_size=kernel_size, + stride=stride, + padding=self.padding, + bias=True) + + nn.init.constant_(self.modulator_conv.weight, 0.) + nn.init.constant_(self.modulator_conv.bias, 0.) + + self.regular_conv = nn.Conv2d(in_channels, + out_channels=out_channels, + kernel_size=kernel_size, + stride=stride, + padding=self.padding, + bias=bias) + + def forward(self, x): + #h, w = x.shape[2:] + #max_offset = max(h, w)/4. + + offset = self.offset_conv(x)#.clamp(-max_offset, max_offset) + modulator = 2. * torch.sigmoid(self.modulator_conv(x)) + + x = deform_conv2d( + input=x, + offset=offset, + weight=self.regular_conv.weight, + bias=self.regular_conv.bias, + padding=self.padding, + mask=modulator, + stride=self.stride, + ) + return x diff --git a/py/BiRefNet_v2/models/modules/lateral_blocks.py b/py/BiRefNet_v2/models/modules/lateral_blocks.py new file mode 100644 index 0000000..de907ac --- /dev/null +++ b/py/BiRefNet_v2/models/modules/lateral_blocks.py @@ -0,0 +1,21 @@ +import numpy as np +import torch +import torch.nn as nn +import torch.nn.functional as F +from functools import partial + +from ...config import Config + + +config = Config() + + +class BasicLatBlk(nn.Module): + def __init__(self, in_channels=64, out_channels=64, inter_channels=64): + super(BasicLatBlk, self).__init__() + inter_channels = in_channels // 4 if config.dec_channels_inter == 'adap' else 64 + self.conv = nn.Conv2d(in_channels, out_channels, 1, 1, 0) + + def forward(self, x): + x = self.conv(x) + return x diff --git a/py/BiRefNet_v2/models/modules/mlp.py b/py/BiRefNet_v2/models/modules/mlp.py new file mode 100644 index 0000000..a383459 --- /dev/null +++ b/py/BiRefNet_v2/models/modules/mlp.py @@ -0,0 +1,118 @@ +import torch +import torch.nn as nn +from functools import partial + +from timm.models.layers import DropPath, to_2tuple, trunc_normal_ +from timm.models import register_model + +import math + + +class MLPLayer(nn.Module): + def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.): + super().__init__() + out_features = out_features or in_features + hidden_features = hidden_features or in_features + self.fc1 = nn.Linear(in_features, hidden_features) + self.act = act_layer() + self.fc2 = nn.Linear(hidden_features, out_features) + self.drop = nn.Dropout(drop) + + def forward(self, x): + x = self.fc1(x) + x = self.act(x) + x = self.drop(x) + x = self.fc2(x) + x = self.drop(x) + return x + + +class Attention(nn.Module): + def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0., sr_ratio=1): + super().__init__() + assert dim % num_heads == 0, f"dim {dim} should be divided by num_heads {num_heads}." + + self.dim = dim + self.num_heads = num_heads + head_dim = dim // num_heads + self.scale = qk_scale or head_dim ** -0.5 + + self.q = nn.Linear(dim, dim, bias=qkv_bias) + self.kv = nn.Linear(dim, dim * 2, bias=qkv_bias) + self.attn_drop = nn.Dropout(attn_drop) + self.proj = nn.Linear(dim, dim) + self.proj_drop = nn.Dropout(proj_drop) + + self.sr_ratio = sr_ratio + if sr_ratio > 1: + self.sr = nn.Conv2d(dim, dim, kernel_size=sr_ratio, stride=sr_ratio) + self.norm = nn.LayerNorm(dim) + + def forward(self, x, H, W): + B, N, C = x.shape + q = self.q(x).reshape(B, N, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3) + + if self.sr_ratio > 1: + x_ = x.permute(0, 2, 1).reshape(B, C, H, W) + x_ = self.sr(x_).reshape(B, C, -1).permute(0, 2, 1) + x_ = self.norm(x_) + kv = self.kv(x_).reshape(B, -1, 2, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) + else: + kv = self.kv(x).reshape(B, -1, 2, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) + k, v = kv[0], kv[1] + + attn = (q @ k.transpose(-2, -1)) * self.scale + attn = attn.softmax(dim=-1) + attn = self.attn_drop(attn) + + x = (attn @ v).transpose(1, 2).reshape(B, N, C) + x = self.proj(x) + x = self.proj_drop(x) + return x + + +class Block(nn.Module): + def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0., + drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, sr_ratio=1): + super().__init__() + self.norm1 = norm_layer(dim) + self.attn = Attention( + dim, + num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, + attn_drop=attn_drop, proj_drop=drop, sr_ratio=sr_ratio) + # NOTE: drop path for stochastic depth, we shall see if this is better than dropout here + self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity() + self.norm2 = norm_layer(dim) + mlp_hidden_dim = int(dim * mlp_ratio) + self.mlp = MLPLayer(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop) + + def forward(self, x, H, W): + x = x + self.drop_path(self.attn(self.norm1(x), H, W)) + x = x + self.drop_path(self.mlp(self.norm2(x), H, W)) + return x + + +class OverlapPatchEmbed(nn.Module): + """ Image to Patch Embedding + """ + + def __init__(self, img_size=224, patch_size=7, stride=4, in_channels=3, embed_dim=768): + super().__init__() + img_size = to_2tuple(img_size) + patch_size = to_2tuple(patch_size) + + self.img_size = img_size + self.patch_size = patch_size + self.H, self.W = img_size[0] // patch_size[0], img_size[1] // patch_size[1] + self.num_patches = self.H * self.W + self.proj = nn.Conv2d(in_channels, embed_dim, kernel_size=patch_size, stride=stride, + padding=(patch_size[0] // 2, patch_size[1] // 2)) + self.norm = nn.LayerNorm(embed_dim) + + def forward(self, x): + x = self.proj(x) + _, _, H, W = x.shape + x = x.flatten(2).transpose(1, 2) + x = self.norm(x) + return x, H, W + diff --git a/py/BiRefNet_v2/models/modules/prompt_encoder.py b/py/BiRefNet_v2/models/modules/prompt_encoder.py new file mode 100644 index 0000000..23ce18c --- /dev/null +++ b/py/BiRefNet_v2/models/modules/prompt_encoder.py @@ -0,0 +1,222 @@ +import numpy as np +import torch +import torch.nn as nn +from typing import Any, Optional, Tuple, Type + + +class PromptEncoder(nn.Module): + def __init__( + self, + embed_dim=256, + image_embedding_size=1024, + input_image_size=(1024, 1024), + mask_in_chans=16, + activation=nn.GELU + ) -> None: + super().__init__() + """ + Codes are partially from SAM: https://github.com/facebookresearch/segment-anything/blob/6fdee8f2727f4506cfbbe553e23b895e27956588/segment_anything/modeling/prompt_encoder.py. + + Arguments: + embed_dim (int): The prompts' embedding dimension + image_embedding_size (tuple(int, int)): The spatial size of the + image embedding, as (H, W). + input_image_size (int): The padded size of the image as input + to the image encoder, as (H, W). + mask_in_chans (int): The number of hidden channels used for + encoding input masks. + activation (nn.Module): The activation to use when encoding + input masks. + """ + super().__init__() + self.embed_dim = embed_dim + self.input_image_size = input_image_size + self.image_embedding_size = image_embedding_size + self.pe_layer = PositionEmbeddingRandom(embed_dim // 2) + + self.num_point_embeddings: int = 4 # pos/neg point + 2 box corners + point_embeddings = [nn.Embedding(1, embed_dim) for i in range(self.num_point_embeddings)] + self.point_embeddings = nn.ModuleList(point_embeddings) + self.not_a_point_embed = nn.Embedding(1, embed_dim) + + self.mask_input_size = (4 * image_embedding_size[0], 4 * image_embedding_size[1]) + self.mask_downscaling = nn.Sequential( + nn.Conv2d(1, mask_in_chans // 4, kernel_size=2, stride=2), + LayerNorm2d(mask_in_chans // 4), + activation(), + nn.Conv2d(mask_in_chans // 4, mask_in_chans, kernel_size=2, stride=2), + LayerNorm2d(mask_in_chans), + activation(), + nn.Conv2d(mask_in_chans, embed_dim, kernel_size=1), + ) + self.no_mask_embed = nn.Embedding(1, embed_dim) + + def get_dense_pe(self) -> torch.Tensor: + """ + Returns the positional encoding used to encode point prompts, + applied to a dense set of points the shape of the image encoding. + + Returns: + torch.Tensor: Positional encoding with shape + 1x(embed_dim)x(embedding_h)x(embedding_w) + """ + return self.pe_layer(self.image_embedding_size).unsqueeze(0) + + def _embed_points( + self, + points: torch.Tensor, + labels: torch.Tensor, + pad: bool, + ) -> torch.Tensor: + """Embeds point prompts.""" + points = points + 0.5 # Shift to center of pixel + if pad: + padding_point = torch.zeros((points.shape[0], 1, 2), device=points.device) + padding_label = -torch.ones((labels.shape[0], 1), device=labels.device) + points = torch.cat([points, padding_point], dim=1) + labels = torch.cat([labels, padding_label], dim=1) + point_embedding = self.pe_layer.forward_with_coords(points, self.input_image_size) + point_embedding[labels == -1] = 0.0 + point_embedding[labels == -1] += self.not_a_point_embed.weight + point_embedding[labels == 0] += self.point_embeddings[0].weight + point_embedding[labels == 1] += self.point_embeddings[1].weight + return point_embedding + + def _embed_boxes(self, boxes: torch.Tensor) -> torch.Tensor: + """Embeds box prompts.""" + boxes = boxes + 0.5 # Shift to center of pixel + coords = boxes.reshape(-1, 2, 2) + corner_embedding = self.pe_layer.forward_with_coords(coords, self.input_image_size) + corner_embedding[:, 0, :] += self.point_embeddings[2].weight + corner_embedding[:, 1, :] += self.point_embeddings[3].weight + return corner_embedding + + def _embed_masks(self, masks: torch.Tensor) -> torch.Tensor: + """Embeds mask inputs.""" + mask_embedding = self.mask_downscaling(masks) + return mask_embedding + + def _get_batch_size( + self, + points: Optional[Tuple[torch.Tensor, torch.Tensor]], + boxes: Optional[torch.Tensor], + masks: Optional[torch.Tensor], + ) -> int: + """ + Gets the batch size of the output given the batch size of the input prompts. + """ + if points is not None: + return points[0].shape[0] + elif boxes is not None: + return boxes.shape[0] + elif masks is not None: + return masks.shape[0] + else: + return 1 + + def _get_device(self) -> torch.device: + return self.point_embeddings[0].weight.device + + def forward( + self, + points: Optional[Tuple[torch.Tensor, torch.Tensor]], + boxes: Optional[torch.Tensor], + masks: Optional[torch.Tensor], + ) -> Tuple[torch.Tensor, torch.Tensor]: + """ + Embeds different types of prompts, returning both sparse and dense + embeddings. + + Arguments: + points (tuple(torch.Tensor, torch.Tensor) or none): point coordinates + and labels to embed. + boxes (torch.Tensor or none): boxes to embed + masks (torch.Tensor or none): masks to embed + + Returns: + torch.Tensor: sparse embeddings for the points and boxes, with shape + BxNx(embed_dim), where N is determined by the number of input points + and boxes. + torch.Tensor: dense embeddings for the masks, in the shape + Bx(embed_dim)x(embed_H)x(embed_W) + """ + bs = self._get_batch_size(points, boxes, masks) + sparse_embeddings = torch.empty((bs, 0, self.embed_dim), device=self._get_device()) + if points is not None: + coords, labels = points + point_embeddings = self._embed_points(coords, labels, pad=(boxes is None)) + sparse_embeddings = torch.cat([sparse_embeddings, point_embeddings], dim=1) + if boxes is not None: + box_embeddings = self._embed_boxes(boxes) + sparse_embeddings = torch.cat([sparse_embeddings, box_embeddings], dim=1) + + if masks is not None: + dense_embeddings = self._embed_masks(masks) + else: + dense_embeddings = self.no_mask_embed.weight.reshape(1, -1, 1, 1).expand( + bs, -1, self.image_embedding_size[0], self.image_embedding_size[1] + ) + + return sparse_embeddings, dense_embeddings + + +class PositionEmbeddingRandom(nn.Module): + """ + Positional encoding using random spatial frequencies. + """ + + def __init__(self, num_pos_feats: int = 64, scale: Optional[float] = None) -> None: + super().__init__() + if scale is None or scale <= 0.0: + scale = 1.0 + self.register_buffer( + "positional_encoding_gaussian_matrix", + scale * torch.randn((2, num_pos_feats)), + ) + + def _pe_encoding(self, coords: torch.Tensor) -> torch.Tensor: + """Positionally encode points that are normalized to [0,1].""" + # assuming coords are in [0, 1]^2 square and have d_1 x ... x d_n x 2 shape + coords = 2 * coords - 1 + coords = coords @ self.positional_encoding_gaussian_matrix + coords = 2 * np.pi * coords + # outputs d_1 x ... x d_n x C shape + return torch.cat([torch.sin(coords), torch.cos(coords)], dim=-1) + + def forward(self, size: Tuple[int, int]) -> torch.Tensor: + """Generate positional encoding for a grid of the specified size.""" + h, w = size + device: Any = self.positional_encoding_gaussian_matrix.device + grid = torch.ones((h, w), device=device, dtype=torch.float32) + y_embed = grid.cumsum(dim=0) - 0.5 + x_embed = grid.cumsum(dim=1) - 0.5 + y_embed = y_embed / h + x_embed = x_embed / w + + pe = self._pe_encoding(torch.stack([x_embed, y_embed], dim=-1)) + return pe.permute(2, 0, 1) # C x H x W + + def forward_with_coords( + self, coords_input: torch.Tensor, image_size: Tuple[int, int] + ) -> torch.Tensor: + """Positionally encode points that are not normalized to [0,1].""" + coords = coords_input.clone() + coords[:, :, 0] = coords[:, :, 0] / image_size[1] + coords[:, :, 1] = coords[:, :, 1] / image_size[0] + return self._pe_encoding(coords.to(torch.float)) # B x N x C + + +class LayerNorm2d(nn.Module): + def __init__(self, num_channels: int, eps: float = 1e-6) -> None: + super().__init__() + self.weight = nn.Parameter(torch.ones(num_channels)) + self.bias = nn.Parameter(torch.zeros(num_channels)) + self.eps = eps + + def forward(self, x: torch.Tensor) -> torch.Tensor: + u = x.mean(1, keepdim=True) + s = (x - u).pow(2).mean(1, keepdim=True) + x = (x - u) / torch.sqrt(s + self.eps) + x = self.weight[:, None, None] * x + self.bias[:, None, None] + return x + diff --git a/py/BiRefNet_v2/models/modules/utils.py b/py/BiRefNet_v2/models/modules/utils.py new file mode 100644 index 0000000..59bd912 --- /dev/null +++ b/py/BiRefNet_v2/models/modules/utils.py @@ -0,0 +1,54 @@ +import torch.nn as nn + + +def build_act_layer(act_layer): + if act_layer == 'ReLU': + return nn.ReLU(inplace=True) + elif act_layer == 'SiLU': + return nn.SiLU(inplace=True) + elif act_layer == 'GELU': + return nn.GELU() + + raise NotImplementedError(f'build_act_layer does not support {act_layer}') + + +def build_norm_layer(dim, + norm_layer, + in_format='channels_last', + out_format='channels_last', + eps=1e-6): + layers = [] + if norm_layer == 'BN': + if in_format == 'channels_last': + layers.append(to_channels_first()) + layers.append(nn.BatchNorm2d(dim)) + if out_format == 'channels_last': + layers.append(to_channels_last()) + elif norm_layer == 'LN': + if in_format == 'channels_first': + layers.append(to_channels_last()) + layers.append(nn.LayerNorm(dim, eps=eps)) + if out_format == 'channels_first': + layers.append(to_channels_first()) + else: + raise NotImplementedError( + f'build_norm_layer does not support {norm_layer}') + return nn.Sequential(*layers) + + +class to_channels_first(nn.Module): + + def __init__(self): + super().__init__() + + def forward(self, x): + return x.permute(0, 3, 1, 2) + + +class to_channels_last(nn.Module): + + def __init__(self): + super().__init__() + + def forward(self, x): + return x.permute(0, 2, 3, 1) diff --git a/py/BiRefNet_v2/models/refinement/refiner.py b/py/BiRefNet_v2/models/refinement/refiner.py new file mode 100644 index 0000000..f63ad28 --- /dev/null +++ b/py/BiRefNet_v2/models/refinement/refiner.py @@ -0,0 +1,252 @@ +import torch +import torch.nn as nn +from collections import OrderedDict +import torch +import torch.nn as nn +import torch.nn.functional as F +from torchvision.models import vgg16, vgg16_bn +from torchvision.models import resnet50 + +from ...config import Config +from ...dataset import class_labels_TR_sorted +from ...models.backbones.build_backbone import build_backbone +from ...models.modules.decoder_blocks import BasicDecBlk +from ...models.modules.lateral_blocks import BasicLatBlk +from ...models.refinement.stem_layer import StemLayer + + +class RefinerPVTInChannels4(nn.Module): + def __init__(self, in_channels=3+1): + super(RefinerPVTInChannels4, self).__init__() + self.config = Config() + self.epoch = 1 + self.bb = build_backbone(self.config.bb, params_settings='in_channels=4') + + lateral_channels_in_collection = { + 'vgg16': [512, 256, 128, 64], 'vgg16bn': [512, 256, 128, 64], 'resnet50': [1024, 512, 256, 64], + 'pvt_v2_b2': [512, 320, 128, 64], 'pvt_v2_b5': [512, 320, 128, 64], + 'swin_v1_b': [1024, 512, 256, 128], 'swin_v1_l': [1536, 768, 384, 192], + } + channels = lateral_channels_in_collection[self.config.bb] + self.squeeze_module = BasicDecBlk(channels[0], channels[0]) + + self.decoder = Decoder(channels) + + if 0: + for key, value in self.named_parameters(): + if 'bb.' in key: + value.requires_grad = False + + def forward(self, x): + if isinstance(x, list): + x = torch.cat(x, dim=1) + ########## Encoder ########## + if self.config.bb in ['vgg16', 'vgg16bn', 'resnet50']: + x1 = self.bb.conv1(x) + x2 = self.bb.conv2(x1) + x3 = self.bb.conv3(x2) + x4 = self.bb.conv4(x3) + else: + x1, x2, x3, x4 = self.bb(x) + + x4 = self.squeeze_module(x4) + + ########## Decoder ########## + + features = [x, x1, x2, x3, x4] + scaled_preds = self.decoder(features) + + return scaled_preds + + +class Refiner(nn.Module): + def __init__(self, in_channels=3+1): + super(Refiner, self).__init__() + self.config = Config() + self.epoch = 1 + self.stem_layer = StemLayer(in_channels=in_channels, inter_channels=48, out_channels=3, norm_layer='BN' if self.config.batch_size > 1 else 'LN') + self.bb = build_backbone(self.config.bb) + + lateral_channels_in_collection = { + 'vgg16': [512, 256, 128, 64], 'vgg16bn': [512, 256, 128, 64], 'resnet50': [1024, 512, 256, 64], + 'pvt_v2_b2': [512, 320, 128, 64], 'pvt_v2_b5': [512, 320, 128, 64], + 'swin_v1_b': [1024, 512, 256, 128], 'swin_v1_l': [1536, 768, 384, 192], + } + channels = lateral_channels_in_collection[self.config.bb] + self.squeeze_module = BasicDecBlk(channels[0], channels[0]) + + self.decoder = Decoder(channels) + + if 0: + for key, value in self.named_parameters(): + if 'bb.' in key: + value.requires_grad = False + + def forward(self, x): + if isinstance(x, list): + x = torch.cat(x, dim=1) + x = self.stem_layer(x) + ########## Encoder ########## + if self.config.bb in ['vgg16', 'vgg16bn', 'resnet50']: + x1 = self.bb.conv1(x) + x2 = self.bb.conv2(x1) + x3 = self.bb.conv3(x2) + x4 = self.bb.conv4(x3) + else: + x1, x2, x3, x4 = self.bb(x) + + x4 = self.squeeze_module(x4) + + ########## Decoder ########## + + features = [x, x1, x2, x3, x4] + scaled_preds = self.decoder(features) + + return scaled_preds + + +class Decoder(nn.Module): + def __init__(self, channels): + super(Decoder, self).__init__() + self.config = Config() + DecoderBlock = eval('BasicDecBlk') + LateralBlock = eval('BasicLatBlk') + + self.decoder_block4 = DecoderBlock(channels[0], channels[1]) + self.decoder_block3 = DecoderBlock(channels[1], channels[2]) + self.decoder_block2 = DecoderBlock(channels[2], channels[3]) + self.decoder_block1 = DecoderBlock(channels[3], channels[3]//2) + + self.lateral_block4 = LateralBlock(channels[1], channels[1]) + self.lateral_block3 = LateralBlock(channels[2], channels[2]) + self.lateral_block2 = LateralBlock(channels[3], channels[3]) + + if self.config.ms_supervision: + self.conv_ms_spvn_4 = nn.Conv2d(channels[1], 1, 1, 1, 0) + self.conv_ms_spvn_3 = nn.Conv2d(channels[2], 1, 1, 1, 0) + self.conv_ms_spvn_2 = nn.Conv2d(channels[3], 1, 1, 1, 0) + self.conv_out1 = nn.Sequential(nn.Conv2d(channels[3]//2, 1, 1, 1, 0)) + + def forward(self, features): + x, x1, x2, x3, x4 = features + outs = [] + p4 = self.decoder_block4(x4) + _p4 = F.interpolate(p4, size=x3.shape[2:], mode='bilinear', align_corners=True) + _p3 = _p4 + self.lateral_block4(x3) + + p3 = self.decoder_block3(_p3) + _p3 = F.interpolate(p3, size=x2.shape[2:], mode='bilinear', align_corners=True) + _p2 = _p3 + self.lateral_block3(x2) + + p2 = self.decoder_block2(_p2) + _p2 = F.interpolate(p2, size=x1.shape[2:], mode='bilinear', align_corners=True) + _p1 = _p2 + self.lateral_block2(x1) + + _p1 = self.decoder_block1(_p1) + _p1 = F.interpolate(_p1, size=x.shape[2:], mode='bilinear', align_corners=True) + p1_out = self.conv_out1(_p1) + + if self.config.ms_supervision: + outs.append(self.conv_ms_spvn_4(p4)) + outs.append(self.conv_ms_spvn_3(p3)) + outs.append(self.conv_ms_spvn_2(p2)) + outs.append(p1_out) + return outs + + +class RefUNet(nn.Module): + # Refinement + def __init__(self, in_channels=3+1): + super(RefUNet, self).__init__() + self.encoder_1 = nn.Sequential( + nn.Conv2d(in_channels, 64, 3, 1, 1), + nn.Conv2d(64, 64, 3, 1, 1), + nn.BatchNorm2d(64), + nn.ReLU(inplace=True) + ) + + self.encoder_2 = nn.Sequential( + nn.MaxPool2d(2, 2, ceil_mode=True), + nn.Conv2d(64, 64, 3, 1, 1), + nn.BatchNorm2d(64), + nn.ReLU(inplace=True) + ) + + self.encoder_3 = nn.Sequential( + nn.MaxPool2d(2, 2, ceil_mode=True), + nn.Conv2d(64, 64, 3, 1, 1), + nn.BatchNorm2d(64), + nn.ReLU(inplace=True) + ) + + self.encoder_4 = nn.Sequential( + nn.MaxPool2d(2, 2, ceil_mode=True), + nn.Conv2d(64, 64, 3, 1, 1), + nn.BatchNorm2d(64), + nn.ReLU(inplace=True) + ) + + self.pool4 = nn.MaxPool2d(2, 2, ceil_mode=True) + ##### + self.decoder_5 = nn.Sequential( + nn.Conv2d(64, 64, 3, 1, 1), + nn.BatchNorm2d(64), + nn.ReLU(inplace=True) + ) + ##### + self.decoder_4 = nn.Sequential( + nn.Conv2d(128, 64, 3, 1, 1), + nn.BatchNorm2d(64), + nn.ReLU(inplace=True) + ) + + self.decoder_3 = nn.Sequential( + nn.Conv2d(128, 64, 3, 1, 1), + nn.BatchNorm2d(64), + nn.ReLU(inplace=True) + ) + + self.decoder_2 = nn.Sequential( + nn.Conv2d(128, 64, 3, 1, 1), + nn.BatchNorm2d(64), + nn.ReLU(inplace=True) + ) + + self.decoder_1 = nn.Sequential( + nn.Conv2d(128, 64, 3, 1, 1), + nn.BatchNorm2d(64), + nn.ReLU(inplace=True) + ) + + self.conv_d0 = nn.Conv2d(64, 1, 3, 1, 1) + + self.upscore2 = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True) + + def forward(self, x): + outs = [] + if isinstance(x, list): + x = torch.cat(x, dim=1) + hx = x + + hx1 = self.encoder_1(hx) + hx2 = self.encoder_2(hx1) + hx3 = self.encoder_3(hx2) + hx4 = self.encoder_4(hx3) + + hx = self.decoder_5(self.pool4(hx4)) + hx = torch.cat((self.upscore2(hx), hx4), 1) + + d4 = self.decoder_4(hx) + hx = torch.cat((self.upscore2(d4), hx3), 1) + + d3 = self.decoder_3(hx) + hx = torch.cat((self.upscore2(d3), hx2), 1) + + d2 = self.decoder_2(hx) + hx = torch.cat((self.upscore2(d2), hx1), 1) + + d1 = self.decoder_1(hx) + + x = self.conv_d0(d1) + outs.append(x) + return outs diff --git a/py/BiRefNet_v2/models/refinement/stem_layer.py b/py/BiRefNet_v2/models/refinement/stem_layer.py new file mode 100644 index 0000000..8dd0a0d --- /dev/null +++ b/py/BiRefNet_v2/models/refinement/stem_layer.py @@ -0,0 +1,45 @@ +import torch.nn as nn +from ...models.modules.utils import build_act_layer, build_norm_layer + + +class StemLayer(nn.Module): + r""" Stem layer of InternImage + Args: + in_channels (int): number of input channels + out_channels (int): number of output channels + act_layer (str): activation layer + norm_layer (str): normalization layer + """ + + def __init__(self, + in_channels=3+1, + inter_channels=48, + out_channels=96, + act_layer='GELU', + norm_layer='BN'): + super().__init__() + self.conv1 = nn.Conv2d(in_channels, + inter_channels, + kernel_size=3, + stride=1, + padding=1) + self.norm1 = build_norm_layer( + inter_channels, norm_layer, 'channels_first', 'channels_first' + ) + self.act = build_act_layer(act_layer) + self.conv2 = nn.Conv2d(inter_channels, + out_channels, + kernel_size=3, + stride=1, + padding=1) + self.norm2 = build_norm_layer( + out_channels, norm_layer, 'channels_first', 'channels_first' + ) + + def forward(self, x): + x = self.conv1(x) + x = self.norm1(x) + x = self.act(x) + x = self.conv2(x) + x = self.norm2(x) + return x diff --git a/py/BiRefNet_v2/requirements.txt b/py/BiRefNet_v2/requirements.txt new file mode 100644 index 0000000..546ffa3 --- /dev/null +++ b/py/BiRefNet_v2/requirements.txt @@ -0,0 +1,15 @@ +--extra-index-url https://download.pytorch.org/whl/cu118 +torch==2.0.1 +--extra-index-url https://download.pytorch.org/whl/cu118 +torchvision==0.15.2 +numpy<2 +opencv-python +timm +scipy +scikit-image +kornia + +tqdm +prettytable + +huggingface_hub diff --git a/py/BiRefNet_v2/rm_cache.sh b/py/BiRefNet_v2/rm_cache.sh new file mode 100644 index 0000000..5e75b92 --- /dev/null +++ b/py/BiRefNet_v2/rm_cache.sh @@ -0,0 +1,20 @@ +#!/bin/bash +rm -rf __pycache__ */__pycache__ + +# Val +rm -r tmp* + +# Train +rm slurm* +rm -r ckpt +rm nohup.out* + +# Eval +rm -r evaluation/eval-* +rm -r tmp* +rm -r e_logs/ + +# System +rm core-*-python-* + +clear diff --git a/py/BiRefNet_v2/sub.sh b/py/BiRefNet_v2/sub.sh new file mode 100644 index 0000000..9e216b9 --- /dev/null +++ b/py/BiRefNet_v2/sub.sh @@ -0,0 +1,17 @@ +#!/bin/sh +# Example: ./sub.sh tmp_proj 0,1,2,3 3 --> Use 0,1,2,3 for training, release GPUs, use GPU:3 for inference. + +# module load gcc/11.2.0 cuda/11.8 cudnn/8.6.0_cu11x && cpu_core_num=6 +module load compilers/cuda/11.8 compilers/gcc/12.2.0 cudnn/8.4.0.27_cuda11.x && cpu_core_num=32 + +export PYTHONUNBUFFERED=1 + +method=${1:-"BSL"} +devices=${2:-0} +gpu_num=$(($(echo ${devices%%,} | grep -o "," | wc -l)+1)) + +sbatch --nodes=1 -p vip_gpu_ailab -A ai4bio \ + --gres=gpu:${gpu_num} --ntasks-per-node=1 --cpus-per-task=$((gpu_num*cpu_core_num)) \ + ./train_test.sh ${method} ${devices} + +hostname diff --git a/py/BiRefNet_v2/test.sh b/py/BiRefNet_v2/test.sh new file mode 100644 index 0000000..66a6149 --- /dev/null +++ b/py/BiRefNet_v2/test.sh @@ -0,0 +1,29 @@ +devices=${1:-0} +pred_root=${2:-e_preds} + +# Inference + +CUDA_VISIBLE_DEVICES=${devices} python inference.py --pred_root ${pred_root} + +echo Inference finished at $(date) + +# Evaluation +log_dir=e_logs && mkdir ${log_dir} + +task=$(python3 config.py) +case "${task}" in + "DIS5K") testsets='DIS-VD,DIS-TE1,DIS-TE2,DIS-TE3,DIS-TE4' ;; + "COD") testsets='CHAMELEON,NC4K,TE-CAMO,TE-COD10K' ;; + "HRSOD") testsets='DAVIS-S,TE-HRSOD,TE-UHRSD,DUT-OMRON,TE-DUTS' ;; + "General") testsets='DIS-VD' ;; + "Matting") testsets='TE-P3M-500-P' ;; +esac +testsets=(`echo ${testsets} | tr ',' ' '`) && testsets=${testsets[@]} + +for testset in ${testsets}; do + python eval_existingOnes.py --pred_root ${pred_root} --data_lst ${testset} > ${log_dir}/eval_${testset}.out + # nohup python eval_existingOnes.py --pred_root ${pred_root} --data_lst ${testset} > ${log_dir}/eval_${testset}.out 2>&1 & +done + + +echo Evaluation started at $(date) diff --git a/py/BiRefNet_v2/train.py b/py/BiRefNet_v2/train.py new file mode 100644 index 0000000..8b47b54 --- /dev/null +++ b/py/BiRefNet_v2/train.py @@ -0,0 +1,333 @@ +import os +import datetime +import argparse +import torch +import torch.nn as nn +import torch.optim as optim +from torch.autograd import Variable + +from .config import Config +from .loss import PixLoss, ClsLoss +from .dataset import MyData +from .models.birefnet import BiRefNet +from .utils import Logger, AverageMeter, set_seed, check_state_dict + +from torch.utils.data.distributed import DistributedSampler +from torch.nn.parallel import DistributedDataParallel as DDP +from torch.distributed import init_process_group, destroy_process_group, get_rank +from torch.cuda import amp + + +parser = argparse.ArgumentParser(description='') +parser.add_argument('--resume', default=None, type=str, help='path to latest checkpoint') +parser.add_argument('--epochs', default=120, type=int) +parser.add_argument('--trainset', default='DIS5K', type=str, help="Options: 'DIS5K'") +parser.add_argument('--ckpt_dir', default=None, help='Temporary folder') +parser.add_argument('--testsets', default='DIS-VD+DIS-TE1+DIS-TE2+DIS-TE3+DIS-TE4', type=str) +parser.add_argument('--dist', default=False, type=lambda x: x == 'True') +args = parser.parse_args() + + +config = Config() +if config.rand_seed: + set_seed(config.rand_seed) + +if config.use_fp16: + # Half Precision + scaler = amp.GradScaler(enabled=config.use_fp16) + +# DDP +to_be_distributed = args.dist +if to_be_distributed: + init_process_group(backend="nccl", timeout=datetime.timedelta(seconds=3600*10)) + device = int(os.environ["LOCAL_RANK"]) +else: + device = config.device + +epoch_st = 1 +# make dir for ckpt +os.makedirs(args.ckpt_dir, exist_ok=True) + +# Init log file +logger = Logger(os.path.join(args.ckpt_dir, "log.txt")) +logger_loss_idx = 1 + +# log model and optimizer params +# logger.info("Model details:"); logger.info(model) +logger.info("datasets: load_all={}, compile={}.".format(config.load_all, config.compile)) +logger.info("Other hyperparameters:"); logger.info(args) +print('batch size:', config.batch_size) + + +if os.path.exists(os.path.join(config.data_root_dir, config.task, args.testsets.strip('+').split('+')[0])): + args.testsets = args.testsets.strip('+').split('+') +else: + args.testsets = [] + +# Init model +def prepare_dataloader(dataset: torch.utils.data.Dataset, batch_size: int, to_be_distributed=False, is_train=True): + if to_be_distributed: + return torch.utils.data.DataLoader( + dataset=dataset, batch_size=batch_size, num_workers=min(config.num_workers, batch_size), pin_memory=True, + shuffle=False, sampler=DistributedSampler(dataset), drop_last=True + ) + else: + return torch.utils.data.DataLoader( + dataset=dataset, batch_size=batch_size, num_workers=min(config.num_workers, batch_size, 0), pin_memory=True, + shuffle=is_train, drop_last=True + ) + + +def init_data_loaders(to_be_distributed): + # Prepare dataset + train_loader = prepare_dataloader( + MyData(datasets=config.training_set, image_size=config.size, is_train=True), + config.batch_size, to_be_distributed=to_be_distributed, is_train=True + ) + print(len(train_loader), "batches of train dataloader {} have been created.".format(config.training_set)) + test_loaders = {} + for testset in args.testsets: + _data_loader_test = prepare_dataloader( + MyData(datasets=testset, image_size=config.size, is_train=False), + config.batch_size_valid, is_train=False + ) + print(len(_data_loader_test), "batches of valid dataloader {} have been created.".format(testset)) + test_loaders[testset] = _data_loader_test + return train_loader, test_loaders + + +def init_models_optimizers(epochs, to_be_distributed): + model = BiRefNet(bb_pretrained=True) + if args.resume: + if os.path.isfile(args.resume): + logger.info("=> loading checkpoint '{}'".format(args.resume)) + state_dict = torch.load(args.resume, map_location='cpu') + state_dict = check_state_dict(state_dict) + model.load_state_dict(state_dict) + global epoch_st + epoch_st = int(args.resume.rstrip('.pth').split('epoch_')[-1]) + 1 + else: + logger.info("=> no checkpoint found at '{}'".format(args.resume)) + if to_be_distributed: + model = model.to(device) + model = DDP(model, device_ids=[device]) + else: + model = model.to(device) + if config.compile: + model = torch.compile(model, mode=['default', 'reduce-overhead', 'max-autotune'][0]) + if config.precisionHigh: + torch.set_float32_matmul_precision('high') + + + # Setting optimizer + if config.optimizer == 'AdamW': + optimizer = optim.AdamW(params=model.parameters(), lr=config.lr, weight_decay=1e-2) + elif config.optimizer == 'Adam': + optimizer = optim.Adam(params=model.parameters(), lr=config.lr, weight_decay=0) + lr_scheduler = torch.optim.lr_scheduler.MultiStepLR( + optimizer, + milestones=[lde if lde > 0 else epochs + lde + 1 for lde in config.lr_decay_epochs], + gamma=config.lr_decay_rate + ) + logger.info("Optimizer details:"); logger.info(optimizer) + logger.info("Scheduler details:"); logger.info(lr_scheduler) + + return model, optimizer, lr_scheduler + + +class Trainer: + def __init__( + self, data_loaders, model_opt_lrsch, + ): + self.model, self.optimizer, self.lr_scheduler = model_opt_lrsch + self.train_loader, self.test_loaders = data_loaders + if config.out_ref: + self.criterion_gdt = nn.BCELoss() if not config.use_fp16 else nn.BCEWithLogitsLoss() + + # Setting Losses + self.pix_loss = PixLoss() + self.cls_loss = ClsLoss() + + # Others + self.loss_log = AverageMeter() + if config.lambda_adv_g: + self.optimizer_d, self.lr_scheduler_d, self.disc, self.adv_criterion = self._load_adv_components() + self.disc_update_for_odd = 0 + + def _load_adv_components(self): + # AIL + from loss import Discriminator + disc = Discriminator(channels=3, img_size=config.size) + if to_be_distributed: + disc = disc.to(device) + disc = DDP(disc, device_ids=[device], broadcast_buffers=False) + else: + disc = disc.to(device) + if config.compile: + disc = torch.compile(disc, mode=['default', 'reduce-overhead', 'max-autotune'][0]) + adv_criterion = nn.BCELoss() if not config.use_fp16 else nn.BCEWithLogitsLoss() + if config.optimizer == 'AdamW': + optimizer_d = optim.AdamW(params=disc.parameters(), lr=config.lr, weight_decay=1e-2) + elif config.optimizer == 'Adam': + optimizer_d = optim.Adam(params=disc.parameters(), lr=config.lr, weight_decay=0) + lr_scheduler_d = torch.optim.lr_scheduler.MultiStepLR( + optimizer_d, + milestones=[lde if lde > 0 else args.epochs + lde + 1 for lde in config.lr_decay_epochs], + gamma=config.lr_decay_rate + ) + return optimizer_d, lr_scheduler_d, disc, adv_criterion + + def _train_batch(self, batch): + inputs = batch[0].to(device) + gts = batch[1].to(device) + class_labels = batch[2].to(device) + if config.use_fp16: + with amp.autocast(enabled=config.use_fp16): + scaled_preds, class_preds_lst = self.model(inputs) + if config.out_ref: + (outs_gdt_pred, outs_gdt_label), scaled_preds = scaled_preds + for _idx, (_gdt_pred, _gdt_label) in enumerate(zip(outs_gdt_pred, outs_gdt_label)): + _gdt_pred = nn.functional.interpolate(_gdt_pred, size=_gdt_label.shape[2:], mode='bilinear', align_corners=True)#.sigmoid() + # _gdt_label = _gdt_label.sigmoid() + loss_gdt = self.criterion_gdt(_gdt_pred, _gdt_label) if _idx == 0 else self.criterion_gdt(_gdt_pred, _gdt_label) + loss_gdt + # self.loss_dict['loss_gdt'] = loss_gdt.item() + if None in class_preds_lst: + loss_cls = 0. + else: + loss_cls = self.cls_loss(class_preds_lst, class_labels) * 1.0 + self.loss_dict['loss_cls'] = loss_cls.item() + + # Loss + loss_pix = self.pix_loss(scaled_preds, torch.clamp(gts, 0, 1)) * 1.0 + self.loss_dict['loss_pix'] = loss_pix.item() + # since there may be several losses for sal, the lambdas for them (lambdas_pix) are inside the loss.py + loss = loss_pix + loss_cls + if config.out_ref: + loss = loss + loss_gdt * 1.0 + + if config.lambda_adv_g: + # gen + valid = Variable(torch.cuda.FloatTensor(scaled_preds[-1].shape[0], 1).fill_(1.0), requires_grad=False).to(device) + adv_loss_g = self.adv_criterion(self.disc(scaled_preds[-1] * inputs), valid) * config.lambda_adv_g + loss += adv_loss_g + self.loss_dict['loss_adv'] = adv_loss_g.item() + self.disc_update_for_odd += 1 + # self.loss_log.update(loss.item(), inputs.size(0)) + # self.optimizer.zero_grad() + # loss.backward() + # self.optimizer.step() + self.optimizer.zero_grad() + scaler.scale(loss).backward() + scaler.step(self.optimizer) + scaler.update() + + if config.lambda_adv_g and self.disc_update_for_odd % 2 == 0: + # disc + fake = Variable(torch.cuda.FloatTensor(scaled_preds[-1].shape[0], 1).fill_(0.0), requires_grad=False).to(device) + adv_loss_real = self.adv_criterion(self.disc(gts * inputs), valid) + adv_loss_fake = self.adv_criterion(self.disc(scaled_preds[-1].detach() * inputs.detach()), fake) + adv_loss_d = (adv_loss_real + adv_loss_fake) / 2 * config.lambda_adv_d + self.loss_dict['loss_adv_d'] = adv_loss_d.item() + # self.optimizer_d.zero_grad() + # adv_loss_d.backward() + # self.optimizer_d.step() + self.optimizer_d.zero_grad() + scaler.scale(adv_loss_d).backward() + scaler.step(self.optimizer_d) + scaler.update() + else: + scaled_preds, class_preds_lst = self.model(inputs) + if config.out_ref: + (outs_gdt_pred, outs_gdt_label), scaled_preds = scaled_preds + for _idx, (_gdt_pred, _gdt_label) in enumerate(zip(outs_gdt_pred, outs_gdt_label)): + _gdt_pred = nn.functional.interpolate(_gdt_pred, size=_gdt_label.shape[2:], mode='bilinear', align_corners=True).sigmoid() + _gdt_label = _gdt_label.sigmoid() + loss_gdt = self.criterion_gdt(_gdt_pred, _gdt_label) if _idx == 0 else self.criterion_gdt(_gdt_pred, _gdt_label) + loss_gdt + # self.loss_dict['loss_gdt'] = loss_gdt.item() + if None in class_preds_lst: + loss_cls = 0. + else: + loss_cls = self.cls_loss(class_preds_lst, class_labels) * 1.0 + self.loss_dict['loss_cls'] = loss_cls.item() + + # Loss + loss_pix = self.pix_loss(scaled_preds, torch.clamp(gts, 0, 1)) * 1.0 + self.loss_dict['loss_pix'] = loss_pix.item() + # since there may be several losses for sal, the lambdas for them (lambdas_pix) are inside the loss.py + loss = loss_pix + loss_cls + if config.out_ref: + loss = loss + loss_gdt * 1.0 + + if config.lambda_adv_g: + # gen + valid = Variable(torch.cuda.FloatTensor(scaled_preds[-1].shape[0], 1).fill_(1.0), requires_grad=False).to(device) + adv_loss_g = self.adv_criterion(self.disc(scaled_preds[-1] * inputs), valid) * config.lambda_adv_g + loss += adv_loss_g + self.loss_dict['loss_adv'] = adv_loss_g.item() + self.disc_update_for_odd += 1 + self.loss_log.update(loss.item(), inputs.size(0)) + self.optimizer.zero_grad() + loss.backward() + self.optimizer.step() + + if config.lambda_adv_g and self.disc_update_for_odd % 2 == 0: + # disc + fake = Variable(torch.cuda.FloatTensor(scaled_preds[-1].shape[0], 1).fill_(0.0), requires_grad=False).to(device) + adv_loss_real = self.adv_criterion(self.disc(gts * inputs), valid) + adv_loss_fake = self.adv_criterion(self.disc(scaled_preds[-1].detach() * inputs.detach()), fake) + adv_loss_d = (adv_loss_real + adv_loss_fake) / 2 * config.lambda_adv_d + self.loss_dict['loss_adv_d'] = adv_loss_d.item() + self.optimizer_d.zero_grad() + adv_loss_d.backward() + self.optimizer_d.step() + + def train_epoch(self, epoch): + global logger_loss_idx + self.model.train() + self.loss_dict = {} + if epoch > args.epochs + config.finetune_last_epochs[1]: + for k in self.pix_loss.lambdas_pix_last.keys(): + if k.lower() == config.finetune_last_epochs[0].lower(): + self.pix_loss.lambdas_pix_last[k] = config.lambdas_pix_last[k] * 0.5 + else: + self.pix_loss.lambdas_pix_last[k] = 0 + + for batch_idx, batch in enumerate(self.train_loader): + self._train_batch(batch) + # Logger + if batch_idx % 20 == 0: + info_progress = 'Epoch[{0}/{1}] Iter[{2}/{3}].'.format(epoch, args.epochs, batch_idx, len(self.train_loader)) + info_loss = 'Training Losses' + for loss_name, loss_value in self.loss_dict.items(): + info_loss += ', {}: {:.3f}'.format(loss_name, loss_value) + logger.info(' '.join((info_progress, info_loss))) + info_loss = '@==Final== Epoch[{0}/{1}] Training Loss: {loss.avg:.3f} '.format(epoch, args.epochs, loss=self.loss_log) + logger.info(info_loss) + + self.lr_scheduler.step() + if config.lambda_adv_g: + self.lr_scheduler_d.step() + return self.loss_log.avg + + +def main(): + + trainer = Trainer( + data_loaders=init_data_loaders(to_be_distributed), + model_opt_lrsch=init_models_optimizers(args.epochs, to_be_distributed) + ) + + for epoch in range(epoch_st, args.epochs+1): + train_loss = trainer.train_epoch(epoch) + # Save checkpoint + # DDP + if epoch >= args.epochs - config.save_last and epoch % config.save_step == 0: + torch.save( + trainer.model.module.state_dict() if to_be_distributed else trainer.model.state_dict(), + os.path.join(args.ckpt_dir, 'epoch_{}.pth'.format(epoch)) + ) + if to_be_distributed: + destroy_process_group() + +if __name__ == '__main__': + main() diff --git a/py/BiRefNet_v2/train.sh b/py/BiRefNet_v2/train.sh new file mode 100644 index 0000000..78421d8 --- /dev/null +++ b/py/BiRefNet_v2/train.sh @@ -0,0 +1,42 @@ +#!/bin/bash +# Run script +# Settings of training & test for different tasks. +method="$1" +task=$(python3 config.py) +case "${task}" in + "DIS5K") epochs=600 && val_last=50 && step=5 ;; + "COD") epochs=150 && val_last=50 && step=5 ;; + "HRSOD") epochs=150 && val_last=50 && step=5 ;; + "General") epochs=250 && val_last=20 && step=2 ;; + "Matting") epochs=100 && val_last=20 && step=2 ;; +esac +testsets=NO # Non-existing folder to skip. +# testsets=TE-COD10K # for COD + +# Train +devices=$2 +nproc_per_node=$(echo ${devices%%,} | grep -o "," | wc -l) + +to_be_distributed=`echo ${nproc_per_node} | awk '{if($e > 0) print "True"; else print "False";}'` + +echo Training started at $(date) +if [ ${to_be_distributed} == "True" ] +then + # Adapt the nproc_per_node by the number of GPUs. Give 8989 as the default value of master_port. + echo "Multi-GPU mode received..." + CUDA_VISIBLE_DEVICES=${devices} \ + torchrun --nproc_per_node $((nproc_per_node+1)) --master_port=${3:-8999} \ + train.py --ckpt_dir ckpt/${method} --epochs ${epochs} \ + --testsets ${testsets} \ + --dist ${to_be_distributed} \ + --resume xx/xx-epoch_244.pth +else + echo "Single-GPU mode received..." + CUDA_VISIBLE_DEVICES=${devices} \ + python train.py --ckpt_dir ckpt/${method} --epochs ${epochs} \ + --testsets ${testsets} \ + --dist ${to_be_distributed} \ + --resume xx/xx-epoch_244.pth +fi + +echo Training finished at $(date) diff --git a/py/BiRefNet_v2/train_test.sh b/py/BiRefNet_v2/train_test.sh new file mode 100644 index 0000000..e9d3a26 --- /dev/null +++ b/py/BiRefNet_v2/train_test.sh @@ -0,0 +1,11 @@ +#!/bin/sh + +method=${1:-"BSL"} +devices=${2:-"0,1,2,3,4,5,6,7"} + +bash train.sh ${method} ${devices} + +devices_test=${3:-0} +bash test.sh ${devices_test} + +hostname diff --git a/py/BiRefNet_v2/tutorials/BiRefNet_inference.ipynb b/py/BiRefNet_v2/tutorials/BiRefNet_inference.ipynb new file mode 100644 index 0000000..4173711 --- /dev/null +++ b/py/BiRefNet_v2/tutorials/BiRefNet_inference.ipynb @@ -0,0 +1,1575 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Online Colab Demo: https://colab.research.google.com/drive/14Dqg7oeBkFEtchaHLNpig2BcdkZEogba\n", + "### Hugging Face Spaces Demo: https://huggingface.co/spaces/ZhengPeng7/BiRefNet_demo" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 391, + "referenced_widgets": [ + "7d19deaab4c845eea4705567bdc65d60", + "a8941bdff0984189be91fab5bfe1c52c", + "b6be81c6cc1e4608a88c785c448bfaa4", + "3b0ddb32ffa442aab3b02a22432bb233", + "688a14cd34704e4ea2e261f6619449ee", + "8a54f72e65a24d7a93852aca8ecae0a2", + "7745af46aa694f5b8ff0ec8fbd72025f", + "4e5fe4296291455f88ae0e5f257c398e", + "60d3c15d4b944546992d3517bb73912a", + "a124da94c5b143a29d9420eba3954859", + "96485cf384484a709e4c32b74e0223af", + "7bef3ce58df040c986a74eb5334f42c9", + "1848689bf6a14235b508647d1bdb7f69", + "055ec5d0d4da4d1b8df33ddb22d6b55b", + "3c9b1a3ed2f64ed58a29083280098292", + "b2b95dd8b75d4625ad1bd02a461f304d", + "044920317fb64cd088d49f334930b886", + "a8416e76428b46c092c7afbf7129b5f9", + "ebf0b02bc7734ebea9a846233a1a6ec4", + "fb3e80729a214bc5993b62ee04d7c58d", + "cf459ec049624ba29f54cceeb1469785", + "db64a13268ab452db1241d06f16d3d6a", + "80a53775d54e47b2922031cc4cd00548", + "e13013a9d20843bca6da8fe9f0fdb644", + "6f45e75849f749a1b5fad6e8f7879c8f", + "0ef4b41f8d0141859b7767d112596198", + "fecc8e75d8d643759123eaf2ff30fa2a", + "56eb4e5291404f3289196d526fef524f", + "7fb491d5b8f34a2e842518c1e4ea4906", + "e02fc794fb3645bda6b802277a3e5c1a", + "f9a719112f53400782f97d0683862a5f", + "4480d4d37c2648e7bb5635109b5d4715", + "67ce0f56b38941749bdb580a830598c2", + "6667788f1fa44603a4a04ba8aa5e1cc9", + "4d162f2efc364cf793709f0b9c9dc888", + "e078f8d23e8449e7a9b5771e342febeb", + "a330873af8cf45eca95780c50260dbb9", + "61746c0aaf96444391d1a86ea7223cb0", + "2ad78a6887eb4a369bac75e2436758b9", + "78d3ab060eb64941bcba51fa3b32f493", + "1f1a0c0dc2b74d56b68a779ef944416d", + "1546b1d7383c4a25b2ab3782ff204cad", + "6588cde28032444980c4e314d6b9a648", + "3e8d434d8e524c8c9f3fe3359df4b327" + ] + }, + "id": "7lFgKfPS8Icy", + "outputId": "2f00b063-86bf-4ba8-fa5e-38d2f5a66462" + }, + "outputs": [], + "source": [ + "# Imports\n", + "from PIL import Image\n", + "import torch\n", + "from torchvision import transforms\n", + "from IPython.display import display\n", + "\n", + "import sys\n", + "sys.path.insert(0, \"../\")\n", + "from models.birefnet import BiRefNet\n", + "\n", + "\n", + "# Load Model\n", + "# Option 2 and Option 3 is better for local running -- we can modify codes locally.\n", + "\n", + "# # # Option 1: loading BiRefNet with weights:\n", + "# from transformers import AutoModelForImageSegmentation\n", + "# birefnet = AutoModelForImageSegmentation.from_pretrained('zhengpeng7/BiRefNet', trust_remote_code=True)\n", + "\n", + "# Option-2: loading weights with BiReNet codes:\n", + "birefnet = BiRefNet.from_pretrained(\n", + " [\n", + " 'zhengpeng7/BiRefNet',\n", + " 'zhengpeng7/BiRefNet-portrait',\n", + " 'zhengpeng7/BiRefNet-legacy', 'zhengpeng7/BiRefNet-DIS5K-TR_TEs', 'zhengpeng7/BiRefNet-DIS5K', 'zhengpeng7/BiRefNet-HRSOD', 'zhengpeng7/BiRefNet-COD',\n", + " 'zhengpeng7/BiRefNet_lite', # Modify the `bb` in `config.py` to `swin_v1_tiny`.\n", + " ][0]\n", + ")\n", + "\n", + "# # Option-3: Loading model and weights from local disk:\n", + "# from utils import check_state_dict\n", + "\n", + "# birefnet = BiRefNet(bb_pretrained=False)\n", + "# state_dict = torch.load('../BiRefNet-general-epoch_244.pth', map_location='cpu')\n", + "# state_dict = check_state_dict(state_dict)\n", + "# birefnet.load_state_dict(state_dict)\n", + "\n", + "device = 'cuda' if torch.cuda.is_available() else 'cpu'\n", + "\n", + "torch.set_float32_matmul_precision(['high', 'highest'][0])\n", + "\n", + "birefnet.to(device)\n", + "birefnet.eval()\n", + "print('BiRefNet is ready to use.')\n", + "\n", + "# Input Data\n", + "transform_image = transforms.Compose([\n", + " transforms.Resize((1024, 1024)),\n", + " transforms.ToTensor(),\n", + " transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n", + "])" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 1000 + }, + "id": "PECYekO53hrR", + "outputId": "73f47406-9d92-48b1-fe74-abbb5b83c7a8" + }, + "outputs": [], + "source": [ + "import os\n", + "from glob import glob\n", + "from image_proc import refine_foreground\n", + "\n", + "src_dir = '../images_todo'\n", + "image_paths = glob(os.path.join(src_dir, '*'))\n", + "dst_dir = '../predictions'\n", + "os.makedirs(dst_dir, exist_ok=True)\n", + "for image_path in image_paths:\n", + " print('Processing {} ...'.format(image_path))\n", + " image = Image.open(image_path)\n", + " input_images = transform_image(image).unsqueeze(0).to(device)\n", + "\n", + " # Prediction\n", + " with torch.no_grad():\n", + " preds = birefnet(input_images)[-1].sigmoid().cpu()\n", + " pred = preds[0].squeeze()\n", + "\n", + " # Show Results\n", + " pred_pil = transforms.ToPILImage()(pred)\n", + " pred_pil.resize(image.size).save(image_path.replace(src_dir, dst_dir))\n", + "\n", + " # Visualize the last sample:\n", + " # Scale proportionally with max length to 1024 for faster showing\n", + " scale_ratio = 1024 / max(image.size)\n", + " scaled_size = (int(image.size[0] * scale_ratio), int(image.size[1] * scale_ratio))\n", + "\n", + " image_masked = refine_foreground(image, pred_pil)\n", + " image_masked.putalpha(pred_pil.resize(image.size))\n", + "\n", + "display(image.resize(scaled_size))\n", + "display(pred_pil.resize(scaled_size))\n", + "display(image_masked.resize(scaled_size))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "accelerator": "GPU", + "colab": { + "gpuType": "T4", + "provenance": [] + }, + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.19" + }, + "widgets": { + "application/vnd.jupyter.widget-state+json": { + "044920317fb64cd088d49f334930b886": { + "model_module": "@jupyter-widgets/base", + "model_module_version": "1.2.0", + "model_name": "LayoutModel", + "state": { + "_model_module": "@jupyter-widgets/base", + "_model_module_version": "1.2.0", + "_model_name": "LayoutModel", + "_view_count": null, + "_view_module": "@jupyter-widgets/base", + "_view_module_version": "1.2.0", + "_view_name": "LayoutView", + "align_content": null, + "align_items": null, + "align_self": null, + "border": null, + "bottom": null, + "display": null, + "flex": null, + "flex_flow": null, + "grid_area": null, + "grid_auto_columns": null, + "grid_auto_flow": null, + "grid_auto_rows": null, + "grid_column": null, + "grid_gap": null, + "grid_row": null, + "grid_template_areas": null, + "grid_template_columns": null, + "grid_template_rows": null, + "height": null, + "justify_content": null, + "justify_items": null, + "left": null, + "margin": null, + "max_height": null, + "max_width": null, + "min_height": null, + "min_width": null, + "object_fit": null, + "object_position": null, + "order": null, + "overflow": null, + "overflow_x": null, + "overflow_y": null, + "padding": null, + "right": null, + "top": null, + "visibility": null, + "width": null + } + }, + "055ec5d0d4da4d1b8df33ddb22d6b55b": { + "model_module": "@jupyter-widgets/controls", + "model_module_version": "1.5.0", + "model_name": "FloatProgressModel", + "state": { + "_dom_classes": [], + "_model_module": "@jupyter-widgets/controls", + "_model_module_version": "1.5.0", + "_model_name": "FloatProgressModel", + "_view_count": null, + "_view_module": "@jupyter-widgets/controls", + "_view_module_version": "1.5.0", + "_view_name": "ProgressView", + "bar_style": "success", + "description": "", + "description_tooltip": null, + "layout": "IPY_MODEL_ebf0b02bc7734ebea9a846233a1a6ec4", + "max": 298, + "min": 0, + "orientation": "horizontal", + "style": "IPY_MODEL_fb3e80729a214bc5993b62ee04d7c58d", + "value": 298 + } + }, + "0ef4b41f8d0141859b7767d112596198": { + "model_module": "@jupyter-widgets/controls", + "model_module_version": "1.5.0", + "model_name": "HTMLModel", + "state": { + "_dom_classes": [], + "_model_module": "@jupyter-widgets/controls", + "_model_module_version": "1.5.0", + "_model_name": "HTMLModel", + "_view_count": null, + "_view_module": "@jupyter-widgets/controls", + "_view_module_version": "1.5.0", + "_view_name": "HTMLView", + "description": "", + "description_tooltip": null, + "layout": "IPY_MODEL_4480d4d37c2648e7bb5635109b5d4715", + "placeholder": "​", + "style": "IPY_MODEL_67ce0f56b38941749bdb580a830598c2", + "value": " 91.3k/91.3k [00:00<00:00, 1.97MB/s]" + } + }, + "1546b1d7383c4a25b2ab3782ff204cad": { + "model_module": "@jupyter-widgets/controls", + "model_module_version": "1.5.0", + "model_name": "ProgressStyleModel", + "state": { + "_model_module": "@jupyter-widgets/controls", + "_model_module_version": "1.5.0", + "_model_name": "ProgressStyleModel", + "_view_count": null, + "_view_module": "@jupyter-widgets/base", + "_view_module_version": "1.2.0", + "_view_name": "StyleView", + "bar_color": null, + "description_width": "" + } + }, + "1848689bf6a14235b508647d1bdb7f69": { + "model_module": "@jupyter-widgets/controls", + "model_module_version": "1.5.0", + "model_name": "HTMLModel", + "state": { + "_dom_classes": [], + "_model_module": "@jupyter-widgets/controls", + "_model_module_version": "1.5.0", + "_model_name": "HTMLModel", + "_view_count": null, + "_view_module": "@jupyter-widgets/controls", + "_view_module_version": "1.5.0", + "_view_name": "HTMLView", + "description": "", + "description_tooltip": null, + "layout": "IPY_MODEL_044920317fb64cd088d49f334930b886", + "placeholder": "​", + "style": "IPY_MODEL_a8416e76428b46c092c7afbf7129b5f9", + "value": "BiRefNet_config.py: 100%" + } + }, + "1f1a0c0dc2b74d56b68a779ef944416d": { + "model_module": "@jupyter-widgets/base", + "model_module_version": "1.2.0", + "model_name": "LayoutModel", + "state": { + "_model_module": "@jupyter-widgets/base", + "_model_module_version": "1.2.0", + "_model_name": "LayoutModel", + "_view_count": null, + "_view_module": "@jupyter-widgets/base", + "_view_module_version": "1.2.0", + "_view_name": "LayoutView", + "align_content": null, + "align_items": null, + "align_self": null, + "border": null, + "bottom": null, + "display": null, + "flex": null, + "flex_flow": null, + "grid_area": null, + "grid_auto_columns": null, + "grid_auto_flow": null, + "grid_auto_rows": null, + "grid_column": null, + "grid_gap": null, + "grid_row": null, + "grid_template_areas": null, + "grid_template_columns": null, + "grid_template_rows": null, + "height": null, + "justify_content": null, + "justify_items": null, + "left": null, + "margin": null, + "max_height": null, + "max_width": null, + "min_height": null, + "min_width": null, + "object_fit": null, + "object_position": null, + "order": null, + "overflow": null, + "overflow_x": null, + "overflow_y": null, + "padding": null, + "right": null, + "top": null, + "visibility": null, + "width": null + } + }, + "2ad78a6887eb4a369bac75e2436758b9": { + "model_module": "@jupyter-widgets/base", + "model_module_version": "1.2.0", + "model_name": "LayoutModel", + "state": { + "_model_module": "@jupyter-widgets/base", + "_model_module_version": "1.2.0", + "_model_name": "LayoutModel", + "_view_count": null, + "_view_module": "@jupyter-widgets/base", + "_view_module_version": "1.2.0", + "_view_name": "LayoutView", + "align_content": null, + "align_items": null, + "align_self": null, + "border": null, + "bottom": null, + "display": null, + "flex": null, + "flex_flow": null, + "grid_area": null, + "grid_auto_columns": null, + "grid_auto_flow": null, + "grid_auto_rows": null, + "grid_column": null, + "grid_gap": null, + "grid_row": null, + "grid_template_areas": null, + "grid_template_columns": null, + "grid_template_rows": null, + "height": null, + "justify_content": null, + "justify_items": null, + "left": null, + "margin": null, + "max_height": null, + "max_width": null, + "min_height": null, + "min_width": null, + "object_fit": null, + "object_position": null, + "order": null, + "overflow": null, + "overflow_x": null, + "overflow_y": null, + "padding": null, + "right": null, + "top": null, + "visibility": null, + "width": null + } + }, + "3b0ddb32ffa442aab3b02a22432bb233": { + "model_module": "@jupyter-widgets/controls", + "model_module_version": "1.5.0", + "model_name": "HTMLModel", + "state": { + "_dom_classes": [], + "_model_module": "@jupyter-widgets/controls", + "_model_module_version": "1.5.0", + "_model_name": "HTMLModel", + "_view_count": null, + "_view_module": "@jupyter-widgets/controls", + "_view_module_version": "1.5.0", + "_view_name": "HTMLView", + "description": "", + "description_tooltip": null, + "layout": "IPY_MODEL_a124da94c5b143a29d9420eba3954859", + "placeholder": "​", + "style": "IPY_MODEL_96485cf384484a709e4c32b74e0223af", + "value": " 413/413 [00:00<00:00, 5.97kB/s]" + } + }, + "3c9b1a3ed2f64ed58a29083280098292": { + "model_module": "@jupyter-widgets/controls", + "model_module_version": "1.5.0", + "model_name": "HTMLModel", + "state": { + "_dom_classes": [], + "_model_module": "@jupyter-widgets/controls", + "_model_module_version": "1.5.0", + "_model_name": "HTMLModel", + "_view_count": null, + "_view_module": "@jupyter-widgets/controls", + "_view_module_version": "1.5.0", + "_view_name": "HTMLView", + "description": "", + "description_tooltip": null, + "layout": "IPY_MODEL_cf459ec049624ba29f54cceeb1469785", + "placeholder": "​", + "style": "IPY_MODEL_db64a13268ab452db1241d06f16d3d6a", + "value": " 298/298 [00:00<00:00, 9.24kB/s]" + } + }, + "3e8d434d8e524c8c9f3fe3359df4b327": { + "model_module": "@jupyter-widgets/controls", + "model_module_version": "1.5.0", + "model_name": "DescriptionStyleModel", + "state": { + "_model_module": "@jupyter-widgets/controls", + "_model_module_version": "1.5.0", + "_model_name": "DescriptionStyleModel", + "_view_count": null, + "_view_module": "@jupyter-widgets/base", + "_view_module_version": "1.2.0", + "_view_name": "StyleView", + "description_width": "" + } + }, + "4480d4d37c2648e7bb5635109b5d4715": { + "model_module": "@jupyter-widgets/base", + "model_module_version": "1.2.0", + "model_name": "LayoutModel", + "state": { + "_model_module": "@jupyter-widgets/base", + "_model_module_version": "1.2.0", + "_model_name": "LayoutModel", + "_view_count": null, + "_view_module": "@jupyter-widgets/base", + "_view_module_version": "1.2.0", + "_view_name": "LayoutView", + "align_content": null, + "align_items": null, + "align_self": null, + "border": null, + "bottom": null, + "display": null, + "flex": null, + "flex_flow": null, + "grid_area": null, + "grid_auto_columns": null, + "grid_auto_flow": null, + "grid_auto_rows": null, + "grid_column": null, + "grid_gap": null, + "grid_row": null, + "grid_template_areas": null, + "grid_template_columns": null, + "grid_template_rows": null, + "height": null, + "justify_content": null, + "justify_items": null, + "left": null, + "margin": null, + "max_height": null, + "max_width": null, + "min_height": null, + "min_width": null, + "object_fit": null, + "object_position": null, + "order": null, + "overflow": null, + "overflow_x": null, + "overflow_y": null, + "padding": null, + "right": null, + "top": null, + "visibility": null, + "width": null + } + }, + "4d162f2efc364cf793709f0b9c9dc888": { + "model_module": "@jupyter-widgets/controls", + "model_module_version": "1.5.0", + "model_name": "HTMLModel", + "state": { + "_dom_classes": [], + "_model_module": "@jupyter-widgets/controls", + "_model_module_version": "1.5.0", + "_model_name": "HTMLModel", + "_view_count": null, + "_view_module": "@jupyter-widgets/controls", + "_view_module_version": "1.5.0", + "_view_name": "HTMLView", + "description": "", + "description_tooltip": null, + "layout": "IPY_MODEL_2ad78a6887eb4a369bac75e2436758b9", + "placeholder": "​", + "style": "IPY_MODEL_78d3ab060eb64941bcba51fa3b32f493", + "value": "model.safetensors: 100%" + } + }, + "4e5fe4296291455f88ae0e5f257c398e": { + "model_module": "@jupyter-widgets/base", + "model_module_version": "1.2.0", + "model_name": "LayoutModel", + "state": { + "_model_module": "@jupyter-widgets/base", + "_model_module_version": "1.2.0", + "_model_name": "LayoutModel", + "_view_count": null, + "_view_module": "@jupyter-widgets/base", + "_view_module_version": "1.2.0", + "_view_name": "LayoutView", + "align_content": null, + "align_items": null, + "align_self": null, + "border": null, + "bottom": null, + "display": null, + "flex": null, + "flex_flow": null, + "grid_area": null, + "grid_auto_columns": null, + "grid_auto_flow": null, + "grid_auto_rows": null, + "grid_column": null, + "grid_gap": null, + "grid_row": null, + "grid_template_areas": null, + "grid_template_columns": null, + "grid_template_rows": null, + "height": null, + "justify_content": null, + "justify_items": null, + "left": null, + "margin": null, + "max_height": null, + "max_width": null, + "min_height": null, + "min_width": null, + "object_fit": null, + "object_position": null, + "order": null, + "overflow": null, + "overflow_x": null, + "overflow_y": null, + "padding": null, + "right": null, + "top": null, + "visibility": null, + "width": null + } + }, + "56eb4e5291404f3289196d526fef524f": { + "model_module": "@jupyter-widgets/base", + "model_module_version": "1.2.0", + "model_name": "LayoutModel", + "state": { + "_model_module": "@jupyter-widgets/base", + "_model_module_version": "1.2.0", + "_model_name": "LayoutModel", + "_view_count": null, + "_view_module": "@jupyter-widgets/base", + "_view_module_version": "1.2.0", + "_view_name": "LayoutView", + "align_content": null, + "align_items": null, + "align_self": null, + "border": null, + "bottom": null, + "display": null, + "flex": null, + "flex_flow": null, + "grid_area": null, + "grid_auto_columns": null, + "grid_auto_flow": null, + "grid_auto_rows": null, + "grid_column": null, + "grid_gap": null, + "grid_row": null, + "grid_template_areas": null, + "grid_template_columns": null, + "grid_template_rows": null, + "height": null, + "justify_content": null, + "justify_items": null, + "left": null, + "margin": null, + "max_height": null, + "max_width": null, + "min_height": null, + "min_width": null, + "object_fit": null, + "object_position": null, + "order": null, + "overflow": null, + "overflow_x": null, + "overflow_y": null, + "padding": null, + "right": null, + "top": null, + "visibility": null, + "width": null + } + }, + "60d3c15d4b944546992d3517bb73912a": { + "model_module": "@jupyter-widgets/controls", + "model_module_version": "1.5.0", + "model_name": "ProgressStyleModel", + "state": { + "_model_module": "@jupyter-widgets/controls", + "_model_module_version": "1.5.0", + "_model_name": "ProgressStyleModel", + "_view_count": null, + "_view_module": "@jupyter-widgets/base", + "_view_module_version": "1.2.0", + "_view_name": "StyleView", + "bar_color": null, + "description_width": "" + } + }, + "61746c0aaf96444391d1a86ea7223cb0": { + "model_module": "@jupyter-widgets/base", + "model_module_version": "1.2.0", + "model_name": "LayoutModel", + "state": { + "_model_module": "@jupyter-widgets/base", + "_model_module_version": "1.2.0", + "_model_name": "LayoutModel", + "_view_count": null, + "_view_module": "@jupyter-widgets/base", + "_view_module_version": "1.2.0", + "_view_name": "LayoutView", + "align_content": null, + "align_items": null, + "align_self": null, + "border": null, + "bottom": null, + "display": null, + "flex": null, + "flex_flow": null, + "grid_area": null, + "grid_auto_columns": null, + "grid_auto_flow": null, + "grid_auto_rows": null, + "grid_column": null, + "grid_gap": null, + "grid_row": null, + "grid_template_areas": null, + "grid_template_columns": null, + "grid_template_rows": null, + "height": null, + "justify_content": null, + "justify_items": null, + "left": null, + "margin": null, + "max_height": null, + "max_width": null, + "min_height": null, + "min_width": null, + "object_fit": null, + "object_position": null, + "order": null, + "overflow": null, + "overflow_x": null, + "overflow_y": null, + "padding": null, + "right": null, + "top": null, + "visibility": null, + "width": null + } + }, + "6588cde28032444980c4e314d6b9a648": { + "model_module": "@jupyter-widgets/base", + "model_module_version": "1.2.0", + "model_name": "LayoutModel", + "state": { + "_model_module": "@jupyter-widgets/base", + "_model_module_version": "1.2.0", + "_model_name": "LayoutModel", + "_view_count": null, + "_view_module": "@jupyter-widgets/base", + "_view_module_version": "1.2.0", + "_view_name": "LayoutView", + "align_content": null, + "align_items": null, + "align_self": null, + "border": null, + "bottom": null, + "display": null, + "flex": null, + "flex_flow": null, + "grid_area": null, + "grid_auto_columns": null, + "grid_auto_flow": null, + "grid_auto_rows": null, + "grid_column": null, + "grid_gap": null, + "grid_row": null, + "grid_template_areas": null, + "grid_template_columns": null, + "grid_template_rows": null, + "height": null, + "justify_content": null, + "justify_items": null, + "left": null, + "margin": null, + "max_height": null, + "max_width": null, + "min_height": null, + "min_width": null, + "object_fit": null, + "object_position": null, + "order": null, + "overflow": null, + "overflow_x": null, + "overflow_y": null, + "padding": null, + "right": null, + "top": null, + "visibility": null, + "width": null + } + }, + "6667788f1fa44603a4a04ba8aa5e1cc9": { + "model_module": "@jupyter-widgets/controls", + "model_module_version": "1.5.0", + "model_name": "HBoxModel", + "state": { + "_dom_classes": [], + "_model_module": "@jupyter-widgets/controls", + "_model_module_version": "1.5.0", + "_model_name": "HBoxModel", + "_view_count": null, + "_view_module": "@jupyter-widgets/controls", + "_view_module_version": "1.5.0", + "_view_name": "HBoxView", + "box_style": "", + "children": [ + "IPY_MODEL_4d162f2efc364cf793709f0b9c9dc888", + "IPY_MODEL_e078f8d23e8449e7a9b5771e342febeb", + "IPY_MODEL_a330873af8cf45eca95780c50260dbb9" + ], + "layout": "IPY_MODEL_61746c0aaf96444391d1a86ea7223cb0" + } + }, + "67ce0f56b38941749bdb580a830598c2": { + "model_module": "@jupyter-widgets/controls", + "model_module_version": "1.5.0", + "model_name": "DescriptionStyleModel", + "state": { + "_model_module": "@jupyter-widgets/controls", + "_model_module_version": "1.5.0", + "_model_name": "DescriptionStyleModel", + "_view_count": null, + "_view_module": "@jupyter-widgets/base", + "_view_module_version": "1.2.0", + "_view_name": "StyleView", + "description_width": "" + } + }, + "688a14cd34704e4ea2e261f6619449ee": { + "model_module": "@jupyter-widgets/base", + "model_module_version": "1.2.0", + "model_name": "LayoutModel", + "state": { + "_model_module": "@jupyter-widgets/base", + "_model_module_version": "1.2.0", + "_model_name": "LayoutModel", + "_view_count": null, + "_view_module": "@jupyter-widgets/base", + "_view_module_version": "1.2.0", + "_view_name": "LayoutView", + "align_content": null, + "align_items": null, + "align_self": null, + "border": null, + "bottom": null, + "display": null, + "flex": null, + "flex_flow": null, + "grid_area": null, + "grid_auto_columns": null, + "grid_auto_flow": null, + "grid_auto_rows": null, + "grid_column": null, + "grid_gap": null, + "grid_row": null, + "grid_template_areas": null, + "grid_template_columns": null, + "grid_template_rows": null, + "height": null, + "justify_content": null, + "justify_items": null, + "left": null, + "margin": null, + "max_height": null, + "max_width": null, + "min_height": null, + "min_width": null, + "object_fit": null, + "object_position": null, + "order": null, + "overflow": null, + "overflow_x": null, + "overflow_y": null, + "padding": null, + "right": null, + "top": null, + "visibility": null, + "width": null + } + }, + "6f45e75849f749a1b5fad6e8f7879c8f": { + "model_module": "@jupyter-widgets/controls", + "model_module_version": "1.5.0", + "model_name": "FloatProgressModel", + "state": { + "_dom_classes": [], + "_model_module": "@jupyter-widgets/controls", + "_model_module_version": "1.5.0", + "_model_name": "FloatProgressModel", + "_view_count": null, + "_view_module": "@jupyter-widgets/controls", + "_view_module_version": "1.5.0", + "_view_name": "ProgressView", + "bar_style": "success", + "description": "", + "description_tooltip": null, + "layout": "IPY_MODEL_e02fc794fb3645bda6b802277a3e5c1a", + "max": 91316, + "min": 0, + "orientation": "horizontal", + "style": "IPY_MODEL_f9a719112f53400782f97d0683862a5f", + "value": 91316 + } + }, + "7745af46aa694f5b8ff0ec8fbd72025f": { + "model_module": "@jupyter-widgets/controls", + "model_module_version": "1.5.0", + "model_name": "DescriptionStyleModel", + "state": { + "_model_module": "@jupyter-widgets/controls", + "_model_module_version": "1.5.0", + "_model_name": "DescriptionStyleModel", + "_view_count": null, + "_view_module": "@jupyter-widgets/base", + "_view_module_version": "1.2.0", + "_view_name": "StyleView", + "description_width": "" + } + }, + "78d3ab060eb64941bcba51fa3b32f493": { + "model_module": "@jupyter-widgets/controls", + "model_module_version": "1.5.0", + "model_name": "DescriptionStyleModel", + "state": { + "_model_module": "@jupyter-widgets/controls", + "_model_module_version": "1.5.0", + "_model_name": "DescriptionStyleModel", + "_view_count": null, + "_view_module": "@jupyter-widgets/base", + "_view_module_version": "1.2.0", + "_view_name": "StyleView", + "description_width": "" + } + }, + "7bef3ce58df040c986a74eb5334f42c9": { + "model_module": "@jupyter-widgets/controls", + "model_module_version": "1.5.0", + "model_name": "HBoxModel", + "state": { + "_dom_classes": [], + "_model_module": "@jupyter-widgets/controls", + "_model_module_version": "1.5.0", + "_model_name": "HBoxModel", + "_view_count": null, + "_view_module": "@jupyter-widgets/controls", + "_view_module_version": "1.5.0", + "_view_name": "HBoxView", + "box_style": "", + "children": [ + "IPY_MODEL_1848689bf6a14235b508647d1bdb7f69", + "IPY_MODEL_055ec5d0d4da4d1b8df33ddb22d6b55b", + "IPY_MODEL_3c9b1a3ed2f64ed58a29083280098292" + ], + "layout": "IPY_MODEL_b2b95dd8b75d4625ad1bd02a461f304d" + } + }, + "7d19deaab4c845eea4705567bdc65d60": { + "model_module": "@jupyter-widgets/controls", + "model_module_version": "1.5.0", + "model_name": "HBoxModel", + "state": { + "_dom_classes": [], + "_model_module": "@jupyter-widgets/controls", + "_model_module_version": "1.5.0", + "_model_name": "HBoxModel", + "_view_count": null, + "_view_module": "@jupyter-widgets/controls", + "_view_module_version": "1.5.0", + "_view_name": "HBoxView", + "box_style": "", + "children": [ + "IPY_MODEL_a8941bdff0984189be91fab5bfe1c52c", + "IPY_MODEL_b6be81c6cc1e4608a88c785c448bfaa4", + "IPY_MODEL_3b0ddb32ffa442aab3b02a22432bb233" + ], + "layout": "IPY_MODEL_688a14cd34704e4ea2e261f6619449ee" + } + }, + "7fb491d5b8f34a2e842518c1e4ea4906": { + "model_module": "@jupyter-widgets/controls", + "model_module_version": "1.5.0", + "model_name": "DescriptionStyleModel", + "state": { + "_model_module": "@jupyter-widgets/controls", + "_model_module_version": "1.5.0", + "_model_name": "DescriptionStyleModel", + "_view_count": null, + "_view_module": "@jupyter-widgets/base", + "_view_module_version": "1.2.0", + "_view_name": "StyleView", + "description_width": "" + } + }, + "80a53775d54e47b2922031cc4cd00548": { + "model_module": "@jupyter-widgets/controls", + "model_module_version": "1.5.0", + "model_name": "HBoxModel", + "state": { + "_dom_classes": [], + "_model_module": "@jupyter-widgets/controls", + "_model_module_version": "1.5.0", + "_model_name": "HBoxModel", + "_view_count": null, + "_view_module": "@jupyter-widgets/controls", + "_view_module_version": "1.5.0", + "_view_name": "HBoxView", + "box_style": "", + "children": [ + "IPY_MODEL_e13013a9d20843bca6da8fe9f0fdb644", + "IPY_MODEL_6f45e75849f749a1b5fad6e8f7879c8f", + "IPY_MODEL_0ef4b41f8d0141859b7767d112596198" + ], + "layout": "IPY_MODEL_fecc8e75d8d643759123eaf2ff30fa2a" + } + }, + "8a54f72e65a24d7a93852aca8ecae0a2": { + "model_module": "@jupyter-widgets/base", + "model_module_version": "1.2.0", + "model_name": "LayoutModel", + "state": { + "_model_module": "@jupyter-widgets/base", + "_model_module_version": "1.2.0", + "_model_name": "LayoutModel", + "_view_count": null, + "_view_module": "@jupyter-widgets/base", + "_view_module_version": "1.2.0", + "_view_name": "LayoutView", + "align_content": null, + "align_items": null, + "align_self": null, + "border": null, + "bottom": null, + "display": null, + "flex": null, + "flex_flow": null, + "grid_area": null, + "grid_auto_columns": null, + "grid_auto_flow": null, + "grid_auto_rows": null, + "grid_column": null, + "grid_gap": null, + "grid_row": null, + "grid_template_areas": null, + "grid_template_columns": null, + "grid_template_rows": null, + "height": null, + "justify_content": null, + "justify_items": null, + "left": null, + "margin": null, + "max_height": null, + "max_width": null, + "min_height": null, + "min_width": null, + "object_fit": null, + "object_position": null, + "order": null, + "overflow": null, + "overflow_x": null, + "overflow_y": null, + "padding": null, + "right": null, + "top": null, + "visibility": null, + "width": null + } + }, + "96485cf384484a709e4c32b74e0223af": { + "model_module": "@jupyter-widgets/controls", + "model_module_version": "1.5.0", + "model_name": "DescriptionStyleModel", + "state": { + "_model_module": "@jupyter-widgets/controls", + "_model_module_version": "1.5.0", + "_model_name": "DescriptionStyleModel", + "_view_count": null, + "_view_module": "@jupyter-widgets/base", + "_view_module_version": "1.2.0", + "_view_name": "StyleView", + "description_width": "" + } + }, + "a124da94c5b143a29d9420eba3954859": { + "model_module": "@jupyter-widgets/base", + "model_module_version": "1.2.0", + "model_name": "LayoutModel", + "state": { + "_model_module": "@jupyter-widgets/base", + "_model_module_version": "1.2.0", + "_model_name": "LayoutModel", + "_view_count": null, + "_view_module": "@jupyter-widgets/base", + "_view_module_version": "1.2.0", + "_view_name": "LayoutView", + "align_content": null, + "align_items": null, + "align_self": null, + "border": null, + "bottom": null, + "display": null, + "flex": null, + "flex_flow": null, + "grid_area": null, + "grid_auto_columns": null, + "grid_auto_flow": null, + "grid_auto_rows": null, + "grid_column": null, + "grid_gap": null, + "grid_row": null, + "grid_template_areas": null, + "grid_template_columns": null, + "grid_template_rows": null, + "height": null, + "justify_content": null, + "justify_items": null, + "left": null, + "margin": null, + "max_height": null, + "max_width": null, + "min_height": null, + "min_width": null, + "object_fit": null, + "object_position": null, + "order": null, + "overflow": null, + "overflow_x": null, + "overflow_y": null, + "padding": null, + "right": null, + "top": null, + "visibility": null, + "width": null + } + }, + "a330873af8cf45eca95780c50260dbb9": { + "model_module": "@jupyter-widgets/controls", + "model_module_version": "1.5.0", + "model_name": "HTMLModel", + "state": { + "_dom_classes": [], + "_model_module": "@jupyter-widgets/controls", + "_model_module_version": "1.5.0", + "_model_name": "HTMLModel", + "_view_count": null, + "_view_module": "@jupyter-widgets/controls", + "_view_module_version": "1.5.0", + "_view_name": "HTMLView", + "description": "", + "description_tooltip": null, + "layout": "IPY_MODEL_6588cde28032444980c4e314d6b9a648", + "placeholder": "​", + "style": "IPY_MODEL_3e8d434d8e524c8c9f3fe3359df4b327", + "value": " 885M/885M [00:05<00:00, 192MB/s]" + } + }, + "a8416e76428b46c092c7afbf7129b5f9": { + "model_module": "@jupyter-widgets/controls", + "model_module_version": "1.5.0", + "model_name": "DescriptionStyleModel", + "state": { + "_model_module": "@jupyter-widgets/controls", + "_model_module_version": "1.5.0", + "_model_name": "DescriptionStyleModel", + "_view_count": null, + "_view_module": "@jupyter-widgets/base", + "_view_module_version": "1.2.0", + "_view_name": "StyleView", + "description_width": "" + } + }, + "a8941bdff0984189be91fab5bfe1c52c": { + "model_module": "@jupyter-widgets/controls", + "model_module_version": "1.5.0", + "model_name": "HTMLModel", + "state": { + "_dom_classes": [], + "_model_module": "@jupyter-widgets/controls", + "_model_module_version": "1.5.0", + "_model_name": "HTMLModel", + "_view_count": null, + "_view_module": "@jupyter-widgets/controls", + "_view_module_version": "1.5.0", + "_view_name": "HTMLView", + "description": "", + "description_tooltip": null, + "layout": "IPY_MODEL_8a54f72e65a24d7a93852aca8ecae0a2", + "placeholder": "​", + "style": "IPY_MODEL_7745af46aa694f5b8ff0ec8fbd72025f", + "value": "config.json: 100%" + } + }, + "b2b95dd8b75d4625ad1bd02a461f304d": { + "model_module": "@jupyter-widgets/base", + "model_module_version": "1.2.0", + "model_name": "LayoutModel", + "state": { + "_model_module": "@jupyter-widgets/base", + "_model_module_version": "1.2.0", + "_model_name": "LayoutModel", + "_view_count": null, + "_view_module": "@jupyter-widgets/base", + "_view_module_version": "1.2.0", + "_view_name": "LayoutView", + "align_content": null, + "align_items": null, + "align_self": null, + "border": null, + "bottom": null, + "display": null, + "flex": null, + "flex_flow": null, + "grid_area": null, + "grid_auto_columns": null, + "grid_auto_flow": null, + "grid_auto_rows": null, + "grid_column": null, + "grid_gap": null, + "grid_row": null, + "grid_template_areas": null, + "grid_template_columns": null, + "grid_template_rows": null, + "height": null, + "justify_content": null, + "justify_items": null, + "left": null, + "margin": null, + "max_height": null, + "max_width": null, + "min_height": null, + "min_width": null, + "object_fit": null, + "object_position": null, + "order": null, + "overflow": null, + "overflow_x": null, + "overflow_y": null, + "padding": null, + "right": null, + "top": null, + "visibility": null, + "width": null + } + }, + "b6be81c6cc1e4608a88c785c448bfaa4": { + "model_module": "@jupyter-widgets/controls", + "model_module_version": "1.5.0", + "model_name": "FloatProgressModel", + "state": { + "_dom_classes": [], + "_model_module": "@jupyter-widgets/controls", + "_model_module_version": "1.5.0", + "_model_name": "FloatProgressModel", + "_view_count": null, + "_view_module": "@jupyter-widgets/controls", + "_view_module_version": "1.5.0", + "_view_name": "ProgressView", + "bar_style": "success", + "description": "", + "description_tooltip": null, + "layout": "IPY_MODEL_4e5fe4296291455f88ae0e5f257c398e", + "max": 413, + "min": 0, + "orientation": "horizontal", + "style": "IPY_MODEL_60d3c15d4b944546992d3517bb73912a", + "value": 413 + } + }, + "cf459ec049624ba29f54cceeb1469785": { + "model_module": "@jupyter-widgets/base", + "model_module_version": "1.2.0", + "model_name": "LayoutModel", + "state": { + "_model_module": "@jupyter-widgets/base", + "_model_module_version": "1.2.0", + "_model_name": "LayoutModel", + "_view_count": null, + "_view_module": "@jupyter-widgets/base", + "_view_module_version": "1.2.0", + "_view_name": "LayoutView", + "align_content": null, + "align_items": null, + "align_self": null, + "border": null, + "bottom": null, + "display": null, + "flex": null, + "flex_flow": null, + "grid_area": null, + "grid_auto_columns": null, + "grid_auto_flow": null, + "grid_auto_rows": null, + "grid_column": null, + "grid_gap": null, + "grid_row": null, + "grid_template_areas": null, + "grid_template_columns": null, + "grid_template_rows": null, + "height": null, + "justify_content": null, + "justify_items": null, + "left": null, + "margin": null, + "max_height": null, + "max_width": null, + "min_height": null, + "min_width": null, + "object_fit": null, + "object_position": null, + "order": null, + "overflow": null, + "overflow_x": null, + "overflow_y": null, + "padding": null, + "right": null, + "top": null, + "visibility": null, + "width": null + } + }, + "db64a13268ab452db1241d06f16d3d6a": { + "model_module": "@jupyter-widgets/controls", + "model_module_version": "1.5.0", + "model_name": "DescriptionStyleModel", + "state": { + "_model_module": "@jupyter-widgets/controls", + "_model_module_version": "1.5.0", + "_model_name": "DescriptionStyleModel", + "_view_count": null, + "_view_module": "@jupyter-widgets/base", + "_view_module_version": "1.2.0", + "_view_name": "StyleView", + "description_width": "" + } + }, + "e02fc794fb3645bda6b802277a3e5c1a": { + "model_module": "@jupyter-widgets/base", + "model_module_version": "1.2.0", + "model_name": "LayoutModel", + "state": { + "_model_module": "@jupyter-widgets/base", + "_model_module_version": "1.2.0", + "_model_name": "LayoutModel", + "_view_count": null, + "_view_module": "@jupyter-widgets/base", + "_view_module_version": "1.2.0", + "_view_name": "LayoutView", + "align_content": null, + "align_items": null, + "align_self": null, + "border": null, + "bottom": null, + "display": null, + "flex": null, + "flex_flow": null, + "grid_area": null, + "grid_auto_columns": null, + "grid_auto_flow": null, + "grid_auto_rows": null, + "grid_column": null, + "grid_gap": null, + "grid_row": null, + "grid_template_areas": null, + "grid_template_columns": null, + "grid_template_rows": null, + "height": null, + "justify_content": null, + "justify_items": null, + "left": null, + "margin": null, + "max_height": null, + "max_width": null, + "min_height": null, + "min_width": null, + "object_fit": null, + "object_position": null, + "order": null, + "overflow": null, + "overflow_x": null, + "overflow_y": null, + "padding": null, + "right": null, + "top": null, + "visibility": null, + "width": null + } + }, + "e078f8d23e8449e7a9b5771e342febeb": { + "model_module": "@jupyter-widgets/controls", + "model_module_version": "1.5.0", + "model_name": "FloatProgressModel", + "state": { + "_dom_classes": [], + "_model_module": "@jupyter-widgets/controls", + "_model_module_version": "1.5.0", + "_model_name": "FloatProgressModel", + "_view_count": null, + "_view_module": "@jupyter-widgets/controls", + "_view_module_version": "1.5.0", + "_view_name": "ProgressView", + "bar_style": "success", + "description": "", + "description_tooltip": null, + "layout": "IPY_MODEL_1f1a0c0dc2b74d56b68a779ef944416d", + "max": 884878856, + "min": 0, + "orientation": "horizontal", + "style": "IPY_MODEL_1546b1d7383c4a25b2ab3782ff204cad", + "value": 884878856 + } + }, + "e13013a9d20843bca6da8fe9f0fdb644": { + "model_module": "@jupyter-widgets/controls", + "model_module_version": "1.5.0", + "model_name": "HTMLModel", + "state": { + "_dom_classes": [], + "_model_module": "@jupyter-widgets/controls", + "_model_module_version": "1.5.0", + "_model_name": "HTMLModel", + "_view_count": null, + "_view_module": "@jupyter-widgets/controls", + "_view_module_version": "1.5.0", + "_view_name": "HTMLView", + "description": "", + "description_tooltip": null, + "layout": "IPY_MODEL_56eb4e5291404f3289196d526fef524f", + "placeholder": "​", + "style": "IPY_MODEL_7fb491d5b8f34a2e842518c1e4ea4906", + "value": "birefnet.py: 100%" + } + }, + "ebf0b02bc7734ebea9a846233a1a6ec4": { + "model_module": "@jupyter-widgets/base", + "model_module_version": "1.2.0", + "model_name": "LayoutModel", + "state": { + "_model_module": "@jupyter-widgets/base", + "_model_module_version": "1.2.0", + "_model_name": "LayoutModel", + "_view_count": null, + "_view_module": "@jupyter-widgets/base", + "_view_module_version": "1.2.0", + "_view_name": "LayoutView", + "align_content": null, + "align_items": null, + "align_self": null, + "border": null, + "bottom": null, + "display": null, + "flex": null, + "flex_flow": null, + "grid_area": null, + "grid_auto_columns": null, + "grid_auto_flow": null, + "grid_auto_rows": null, + "grid_column": null, + "grid_gap": null, + "grid_row": null, + "grid_template_areas": null, + "grid_template_columns": null, + "grid_template_rows": null, + "height": null, + "justify_content": null, + "justify_items": null, + "left": null, + "margin": null, + "max_height": null, + "max_width": null, + "min_height": null, + "min_width": null, + "object_fit": null, + "object_position": null, + "order": null, + "overflow": null, + "overflow_x": null, + "overflow_y": null, + "padding": null, + "right": null, + "top": null, + "visibility": null, + "width": null + } + }, + "f9a719112f53400782f97d0683862a5f": { + "model_module": "@jupyter-widgets/controls", + "model_module_version": "1.5.0", + "model_name": "ProgressStyleModel", + "state": { + "_model_module": "@jupyter-widgets/controls", + "_model_module_version": "1.5.0", + "_model_name": "ProgressStyleModel", + "_view_count": null, + "_view_module": "@jupyter-widgets/base", + "_view_module_version": "1.2.0", + "_view_name": "StyleView", + "bar_color": null, + "description_width": "" + } + }, + "fb3e80729a214bc5993b62ee04d7c58d": { + "model_module": "@jupyter-widgets/controls", + "model_module_version": "1.5.0", + "model_name": "ProgressStyleModel", + "state": { + "_model_module": "@jupyter-widgets/controls", + "_model_module_version": "1.5.0", + "_model_name": "ProgressStyleModel", + "_view_count": null, + "_view_module": "@jupyter-widgets/base", + "_view_module_version": "1.2.0", + "_view_name": "StyleView", + "bar_color": null, + "description_width": "" + } + }, + "fecc8e75d8d643759123eaf2ff30fa2a": { + "model_module": "@jupyter-widgets/base", + "model_module_version": "1.2.0", + "model_name": "LayoutModel", + "state": { + "_model_module": "@jupyter-widgets/base", + "_model_module_version": "1.2.0", + "_model_name": "LayoutModel", + "_view_count": null, + "_view_module": "@jupyter-widgets/base", + "_view_module_version": "1.2.0", + "_view_name": "LayoutView", + "align_content": null, + "align_items": null, + "align_self": null, + "border": null, + "bottom": null, + "display": null, + "flex": null, + "flex_flow": null, + "grid_area": null, + "grid_auto_columns": null, + "grid_auto_flow": null, + "grid_auto_rows": null, + "grid_column": null, + "grid_gap": null, + "grid_row": null, + "grid_template_areas": null, + "grid_template_columns": null, + "grid_template_rows": null, + "height": null, + "justify_content": null, + "justify_items": null, + "left": null, + "margin": null, + "max_height": null, + "max_width": null, + "min_height": null, + "min_width": null, + "object_fit": null, + "object_position": null, + "order": null, + "overflow": null, + "overflow_x": null, + "overflow_y": null, + "padding": null, + "right": null, + "top": null, + "visibility": null, + "width": null + } + } + } + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} diff --git a/py/BiRefNet_v2/tutorials/BiRefNet_pth2onnx.ipynb b/py/BiRefNet_v2/tutorials/BiRefNet_pth2onnx.ipynb new file mode 100644 index 0000000..c087b08 --- /dev/null +++ b/py/BiRefNet_v2/tutorials/BiRefNet_pth2onnx.ipynb @@ -0,0 +1,312 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "id": "LTj2A0RUQFNo" + }, + "source": [ + "# Convert our BiRefNet weights to onnx format.\n", + "\n", + "> This colab file is modified from [Kazuhito00](https://github.com/Kazuhito00)'s nice work.\n", + "\n", + "> Repo: https://github.com/Kazuhito00/BiRefNet-ONNX-Sample \n", + "> Original Colab: https://colab.research.google.com/github/Kazuhito00/BiRefNet-ONNX-Sample/blob/main/Convert2ONNX.ipynb\n", + "\n", + "+ Currently, Colab with 12.7GB RAM / 15GB GPU Mem cannot hold the transformation of BiRefNet in default setting. So, I take BiRefNet with swin_v1_tiny backbone as an example." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Online Colab version: https://colab.research.google.com/drive/1z6OruR52LOvDDpnp516F-N4EyPGrp5om" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "781JHjLJmveh" + }, + "outputs": [], + "source": [ + "import torch\n", + "\n", + "\n", + "weights_file = 'BiRefNet-general-bb_swin_v1_tiny-epoch_232.pth' # https://github.com/ZhengPeng7/BiRefNet/releases/download/v1/BiRefNet-general-bb_swin_v1_tiny-epoch_232.pth\n", + "device = 'cuda' if torch.cuda.is_available() else 'cpu'" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "with open('config.py') as fp:\n", + " file_lines = fp.read()\n", + "if 'swin_v1_tiny' in weights_file:\n", + " print('Set `swin_v1_tiny` as the backbone.')\n", + " file_lines = file_lines.replace(\n", + " '''\n", + " 'pvt_v2_b2', 'pvt_v2_b5', # 9-bs10, 10-bs5\n", + " ][6]\n", + " ''',\n", + " '''\n", + " 'pvt_v2_b2', 'pvt_v2_b5', # 9-bs10, 10-bs5\n", + " ][3]\n", + " ''',\n", + " )\n", + " with open('config.py', mode=\"w\") as fp:\n", + " fp.write(file_lines)\n", + "else:\n", + " file_lines = file_lines.replace(\n", + " '''\n", + " 'pvt_v2_b2', 'pvt_v2_b5', # 9-bs10, 10-bs5\n", + " ][3]\n", + " ''',\n", + " '''\n", + " 'pvt_v2_b2', 'pvt_v2_b5', # 9-bs10, 10-bs5\n", + " ][6]\n", + " ''',\n", + " )\n", + " with open('config.py', mode=\"w\") as fp:\n", + " fp.write(file_lines)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "7lFgKfPS8Icy" + }, + "outputs": [], + "source": [ + "from utils import check_state_dict\n", + "from models.birefnet import BiRefNet\n", + "\n", + "\n", + "birefnet = BiRefNet(bb_pretrained=False)\n", + "state_dict = torch.load('./{}'.format(weights_file), map_location=device)\n", + "state_dict = check_state_dict(state_dict)\n", + "birefnet.load_state_dict(state_dict)\n", + "\n", + "torch.set_float32_matmul_precision(['high', 'highest'][0])\n", + "\n", + "birefnet.to(device)\n", + "_ = birefnet.eval()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "JVgJAdgxQVJW" + }, + "source": [ + "# Process deform_conv2d in the conversion to ONNX" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "vJiZv0L75kTe" + }, + "outputs": [], + "source": [ + "from torchvision.ops.deform_conv import DeformConv2d\n", + "import deform_conv2d_onnx_exporter\n", + "\n", + "# register deform_conv2d operator\n", + "deform_conv2d_onnx_exporter.register_deform_conv2d_onnx_op()\n", + "\n", + "def convert_to_onnx(net, file_name='output.onnx', input_shape=(1024, 1024), device=device):\n", + " input = torch.randn(1, 3, input_shape[0], input_shape[1]).to(device)\n", + "\n", + " input_layer_names = ['input_image']\n", + " output_layer_names = ['output_image']\n", + "\n", + " torch.onnx.export(\n", + " net,\n", + " input,\n", + " file_name,\n", + " verbose=False,\n", + " opset_version=17,\n", + " input_names=input_layer_names,\n", + " output_names=output_layer_names,\n", + " )\n", + "convert_to_onnx(birefnet, weights_file.replace('.pth', '.onnx'), input_shape=(1024, 1024), device=device)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "-eU-g40P1zS-" + }, + "source": [ + "# Load ONNX weights and do the inference." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "LZ4HVqcoDvto" + }, + "outputs": [], + "source": [ + "from PIL import Image\n", + "from torchvision import transforms\n", + "\n", + "\n", + "transform_image = transforms.Compose([\n", + " transforms.Resize((1024, 1024)),\n", + " transforms.ToTensor(),\n", + " transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n", + "])\n", + "\n", + "imagepath = './Helicopter-HR.jpg'\n", + "image = Image.open(imagepath)\n", + "input_images = transform_image(image).unsqueeze(0).to(device)\n", + "input_images_numpy = input_images.cpu().numpy()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "rwzdKX1EfYkd" + }, + "outputs": [], + "source": [ + "import onnxruntime\n", + "import matplotlib.pyplot as plt\n", + "\n", + "\n", + "providers = ['CPUExecutionProvider'] if device == 'cpu' else ['CUDAExecutionProvider']\n", + "onnx_session = onnxruntime.InferenceSession(\n", + " weights_file.replace('.pth', '.onnx'),\n", + " providers=providers\n", + ")\n", + "input_name = onnx_session.get_inputs()[0].name\n", + "print(onnxruntime.get_device(), onnx_session.get_providers())" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "DJVtxZUZum4-" + }, + "outputs": [], + "source": [ + "from time import time\n", + "import matplotlib.pyplot as plt\n", + "\n", + "time_st = time()\n", + "pred_onnx = torch.tensor(\n", + " onnx_session.run(None, {input_name: input_images_numpy if device == 'cpu' else input_images_numpy})[-1]\n", + ").squeeze(0).sigmoid().cpu()\n", + "print(time() - time_st)\n", + "\n", + "plt.imshow(pred_onnx.squeeze(), cmap='gray'); plt.show()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "with torch.no_grad():\n", + " preds = birefnet(input_images)[-1].sigmoid().cpu()\n", + "plt.imshow(preds.squeeze(), cmap='gray'); plt.show()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "diff = abs(preds - pred_onnx)\n", + "print('sum(diff):', diff.sum())\n", + "plt.imshow((diff).squeeze(), cmap='gray'); plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "qzYHflt92Bjd" + }, + "source": [ + "# Efficiency Comparison between .pth and .onnx" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "A5IYfT-uzphA", + "outputId": "2999e345-950e-41b3-ddd3-9f58a71a3f21" + }, + "outputs": [], + "source": [ + "%%timeit\n", + "with torch.no_grad():\n", + " preds = birefnet(input_images)[-1].sigmoid().cpu()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "G0Ul4rfNg1za" + }, + "outputs": [], + "source": [ + "%%timeit\n", + "pred_onnx = torch.tensor(\n", + " onnx_session.run(None, {input_name: input_images_numpy})[-1]\n", + ").squeeze(0).sigmoid().cpu()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "accelerator": "GPU", + "colab": { + "gpuType": "T4", + "provenance": [] + }, + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.14" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/py/BiRefNet_v2/utils.py b/py/BiRefNet_v2/utils.py new file mode 100644 index 0000000..1b43754 --- /dev/null +++ b/py/BiRefNet_v2/utils.py @@ -0,0 +1,97 @@ +import logging +import os +import torch +from torchvision import transforms +import numpy as np +import random +import cv2 +from PIL import Image + + +def path_to_image(path, size=(1024, 1024), color_type=['rgb', 'gray'][0]): + if color_type.lower() == 'rgb': + image = cv2.imread(path) + elif color_type.lower() == 'gray': + image = cv2.imread(path, cv2.IMREAD_GRAYSCALE) + else: + print('Select the color_type to return, either to RGB or gray image.') + return + if size: + image = cv2.resize(image, size, interpolation=cv2.INTER_LINEAR) + if color_type.lower() == 'rgb': + image = Image.fromarray(cv2.cvtColor(image, cv2.COLOR_BGR2RGB)).convert('RGB') + else: + image = Image.fromarray(image).convert('L') + return image + + + +def check_state_dict(state_dict, unwanted_prefix='_orig_mod.'): + for k, v in list(state_dict.items()): + if k.startswith(unwanted_prefix): + state_dict[k[len(unwanted_prefix):]] = state_dict.pop(k) + return state_dict + + +def generate_smoothed_gt(gts): + epsilon = 0.001 + new_gts = (1-epsilon)*gts+epsilon/2 + return new_gts + + +class Logger(): + def __init__(self, path="log.txt"): + self.logger = logging.getLogger('BiRefNet') + self.file_handler = logging.FileHandler(path, "w") + self.stdout_handler = logging.StreamHandler() + self.stdout_handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(message)s')) + self.file_handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(message)s')) + self.logger.addHandler(self.file_handler) + self.logger.addHandler(self.stdout_handler) + self.logger.setLevel(logging.INFO) + self.logger.propagate = False + + def info(self, txt): + self.logger.info(txt) + + def close(self): + self.file_handler.close() + self.stdout_handler.close() + + +class AverageMeter(object): + """Computes and stores the average and current value""" + def __init__(self): + self.reset() + + def reset(self): + self.val = 0.0 + self.avg = 0.0 + self.sum = 0.0 + self.count = 0.0 + + def update(self, val, n=1): + self.val = val + self.sum += val * n + self.count += n + self.avg = self.sum / self.count + + +def save_checkpoint(state, path, filename="latest.pth"): + torch.save(state, os.path.join(path, filename)) + + +def save_tensor_img(tenor_im, path): + im = tenor_im.cpu().clone() + im = im.squeeze(0) + tensor2pil = transforms.ToPILImage() + im = tensor2pil(im) + im.save(path) + + +def set_seed(seed): + torch.manual_seed(seed) + torch.cuda.manual_seed_all(seed) + np.random.seed(seed) + random.seed(seed) + torch.backends.cudnn.deterministic = True diff --git a/py/Qwen_image2prompt.py b/py/Qwen_image2prompt.py new file mode 100644 index 0000000..533e7fb --- /dev/null +++ b/py/Qwen_image2prompt.py @@ -0,0 +1,60 @@ +# layerstyle advance + +import os.path +from pathlib import Path +import torch +from PIL import Image +import math +from torchvision.transforms import ToPILImage +import folder_paths +from .imagefunc import files_for_uform_gen2_qwen, StopOnTokens, UformGen2QwenChat, clear_memory, log + +NODE_NAME = "QWenImage2Prompt" +# Example of integrating UformGen2QwenChat into a node-like structure +class QWenImage2Prompt: + + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "image": ("IMAGE",), + "question": ("STRING", {"multiline": False, "default": "describe this image",},), + }, + } + + RETURN_TYPES = ("STRING",) + RETURN_NAMES = ("text",) + FUNCTION = "uform_gen2_qwen_chat" + CATEGORY = '😺dzNodes/LayerUtility/Prompt' + + def uform_gen2_qwen_chat(self, image, question): + chat_model = UformGen2QwenChat() + history = [] # Example empty history + pil_image = ToPILImage()(image[0].permute(2, 0, 1)) + width, height = pil_image.size + ratio = width / height + if width * height > 1024 * 1024: + target_width = math.sqrt(ratio * 1024 * 1024) + target_height = target_width / ratio + target_width = int(target_width) + target_height = int(target_height) + pil_image = pil_image.resize((target_width, target_height), Image.LANCZOS) + temp_path = files_for_uform_gen2_qwen / "temp.png" + pil_image.save(temp_path) + question = f"{question} but output no more then 80 words." + response = chat_model.chat_response(question, history, temp_path) + + # Cleanup + del chat_model + clear_memory() + ret_text = response.split("assistant\n", 1)[1] + log(f"{NODE_NAME} Processed, Question: {question}, Response: {ret_text} ", message_type='finish') + return (ret_text, ) + +NODE_CLASS_MAPPINGS = { + "LayerUtility: QWenImage2Prompt": QWenImage2Prompt +} + +NODE_DISPLAY_NAME_MAPPINGS = { + "LayerUtility: QWenImage2Prompt": "LayerUtility: QWenImage2Prompt(Advance)" +} \ No newline at end of file diff --git a/py/birefnet_legacy.py b/py/birefnet_legacy.py new file mode 100644 index 0000000..02943c5 --- /dev/null +++ b/py/birefnet_legacy.py @@ -0,0 +1,83 @@ +# layerstyle advance + +from .imagefunc import * + +import torch.nn as nn +from torchvision import transforms +from .BiRefNet_legacy.baseline import BiRefNet +from .BiRefNet_legacy.config import Config + +class BiRefNet_img_processor: + def __init__(self, config): + self.config = config + self.data_size = (config.size, config.size) + self.transform_image = transforms.Compose([ + transforms.Resize(self.data_size), + transforms.ToTensor(), + transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]), + ]) + + def __call__(self, _image: np.array): + _image_rs = cv2.resize(_image, (self.config.size, self.config.size), interpolation=cv2.INTER_LINEAR) + _image_rs = Image.fromarray(np.uint8(_image_rs*255)).convert('RGB') + image = self.transform_image(_image_rs) + return image + +class BiRefNetRemoveBackground: + def __init__(self): + self.ready = False + + def load(self, weight_path, device): + # load model + self.model = BiRefNet() + state_dict = torch.load(weight_path, map_location='cpu') + unwanted_prefix = '_orig_mod.' + for k, v in list(state_dict.items()): + if k.startswith(unwanted_prefix): + state_dict[k[len(unwanted_prefix):]] = state_dict.pop(k) + self.model.load_state_dict(state_dict) + self.model = self.model.to(device) + self.model.eval() + # load processor + self.processor = BiRefNet_img_processor(Config()) + self.ready = True + + + def generate_mask(self, image:Image) -> Image: + + if torch.backends.mps.is_available(): + device = "mps" + elif torch.cuda.is_available(): + device = "cuda" + else: + device = "cpu" + + if not self.ready: + model_folder_name = 'BiRefNet' + model_name = 'BiRefNet-ep480.pth' + model_file_path = "" + try: + model_file_path = os.path.join( + os.path.normpath(folder_paths.folder_names_and_paths[model_folder_name][0][0]), model_name) + except: + pass + if not os.path.exists(model_file_path): + model_file_path = os.path.join(folder_paths.models_dir, model_folder_name, model_name) + self.load(model_file_path, device=device) + + i = pil2tensor(image) + orig_image = image.convert('RGB') + np_image = i.squeeze().numpy() + img = self.processor(np_image) + inputs = img[None, ...].to(device) + with torch.no_grad(): + scaled_preds = self.model(inputs)[-1].sigmoid() + _mask = nn.functional.interpolate(scaled_preds[0].unsqueeze(0), + size=np_image.shape[:2], + mode='bilinear', + align_corners=True + )[0] + + brightness_image = ImageEnhance.Brightness(tensor2pil(_mask)) + + return brightness_image.enhance(factor=1.01) diff --git a/py/birefnet_ultra.py b/py/birefnet_ultra.py new file mode 100644 index 0000000..8fbcfc3 --- /dev/null +++ b/py/birefnet_ultra.py @@ -0,0 +1,83 @@ +# layerstyle advance + +from .imagefunc import * + +NODE_NAME = 'BiRefNetUltra' + +class BiRefNetUltra: + + @classmethod + def INPUT_TYPES(cls): + + method_list = ['VITMatte', 'VITMatte(local)', 'PyMatting', 'GuidedFilter', ] + device_list = ['cuda','cpu'] + return { + "required": { + "image": ("IMAGE",), + "detail_method": (method_list,), + "detail_erode": ("INT", {"default": 6, "min": 1, "max": 255, "step": 1}), + "detail_dilate": ("INT", {"default": 6, "min": 1, "max": 255, "step": 1}), + "black_point": ("FLOAT", {"default": 0.01, "min": 0.01, "max": 0.98, "step": 0.01, "display": "slider"}), + "white_point": ("FLOAT", {"default": 0.99, "min": 0.02, "max": 0.99, "step": 0.01, "display": "slider"}), + "process_detail": ("BOOLEAN", {"default": True}), + "device": (device_list,), + "max_megapixels": ("FLOAT", {"default": 2.0, "min": 1, "max": 999, "step": 0.1}), + }, + "optional": { + } + } + + RETURN_TYPES = ("IMAGE", "MASK", ) + RETURN_NAMES = ("image", "mask", ) + FUNCTION = "birefnet_ultra" + CATEGORY = '😺dzNodes/LayerMask' + + def birefnet_ultra(self, image, detail_method, detail_erode, detail_dilate, + black_point, white_point, process_detail, device, max_megapixels): + ret_images = [] + ret_masks = [] + + if detail_method == 'VITMatte(local)': + local_files_only = True + else: + local_files_only = False + + from .birefnet_legacy import BiRefNetRemoveBackground + birefnetrmbg = BiRefNetRemoveBackground() + + for i in image: + i = torch.unsqueeze(i, 0) + orig_image = tensor2pil(i).convert('RGB') + + _mask = birefnetrmbg.generate_mask(orig_image) + _mask = image2mask(_mask) + + detail_range = detail_erode + detail_dilate + + if process_detail: + if detail_method == 'GuidedFilter': + _mask = guided_filter_alpha(i, _mask, detail_range // 6 + 1) + _mask = tensor2pil(histogram_remap(_mask, black_point, white_point)) + elif detail_method == 'PyMatting': + _mask = tensor2pil(mask_edge_detail(i, _mask, detail_range // 8 + 1, black_point, white_point)) + else: + _trimap = generate_VITMatte_trimap(_mask, detail_erode, detail_dilate) + _mask = generate_VITMatte(orig_image, _trimap, local_files_only=local_files_only, device=device, max_megapixels=max_megapixels) + _mask = tensor2pil(histogram_remap(pil2tensor(_mask), black_point, white_point)) + else: + _mask = tensor2pil(_mask) + + ret_image = RGB2RGBA(orig_image, _mask.convert('L')) + ret_images.append(pil2tensor(ret_image)) + ret_masks.append(image2mask(_mask)) + + log(f"{NODE_NAME} Processed {len(ret_masks)} image(s).", message_type='finish') + return (torch.cat(ret_images, dim=0), torch.cat(ret_masks, dim=0),) + +NODE_CLASS_MAPPINGS = { + "LayerMask: BiRefNetUltra": BiRefNetUltra, +} + +NODE_DISPLAY_NAME_MAPPINGS = { + "LayerMask: BiRefNetUltra": "LayerMask: BiRefNetUltra(Advance)", +} diff --git a/py/birefnet_ultra_v2.py b/py/birefnet_ultra_v2.py new file mode 100644 index 0000000..596ebc4 --- /dev/null +++ b/py/birefnet_ultra_v2.py @@ -0,0 +1,215 @@ +# layerstyle advance + +import os +import sys +import torch +from torchvision import transforms +from transformers import AutoModelForImageSegmentation +import tqdm +from .imagefunc import * +from comfy.utils import ProgressBar +sys.path.append(os.path.join(os.path.dirname(__file__), 'BiRefNet_v2')) + + +def get_models(): + model_path = os.path.join(folder_paths.models_dir, 'BiRefNet', 'pth') + model_ext = [".pth"] + model_dict = get_files(model_path, model_ext) + return model_dict + +class LS_LoadBiRefNetModel: + + def __init__(self): + self.birefnet = None + self.state_dict = None + + + @classmethod + def INPUT_TYPES(s): + tmp_list = list(get_models().keys()) + model_list = [] + if 'BiRefNet-general-epoch_244.pth' in tmp_list: + model_list.append('BiRefNet-general-epoch_244.pth') + tmp_list.remove('BiRefNet-general-epoch_244.pth') + model_list.extend(tmp_list) + + return { + "required": { + "model": (model_list,), + }, + } + + RETURN_TYPES = ("BIREFNET_MODEL",) + RETURN_NAMES = ("birefnet_model",) + FUNCTION = "load_birefnet_model" + CATEGORY = '😺dzNodes/LayerMask' + + def load_birefnet_model(self, model): + from .BiRefNet_v2.models.birefnet import BiRefNet + from .BiRefNet_v2.utils import check_state_dict + model_dict = get_models() + self.birefnet = BiRefNet(bb_pretrained=False) + self.state_dict = torch.load(model_dict[model], map_location='cpu', weights_only=True) + self.state_dict = check_state_dict(self.state_dict) + self.birefnet.load_state_dict(self.state_dict) + return (self.birefnet,) + +class LS_LoadBiRefNetModelV2: + def __init__(self): + self.model = None + + @classmethod + def INPUT_TYPES(s): + model_list = list(s.birefnet_model_repos.keys()) + return { + "required": { + "version": (model_list,{"default": model_list[0]}), + }, + } + + RETURN_TYPES = ("BIREFNET_MODEL",) + RETURN_NAMES = ("birefnet_model",) + FUNCTION = "load_birefnet_model" + CATEGORY = '😺dzNodes/LayerMask' + + birefnet_model_repos = { + "BiRefNet-General": "ZhengPeng7/BiRefNet", + "RMBG-2.0": "briaai/RMBG-2.0" + } + + def load_birefnet_model(self, version): + birefnet_path = os.path.join(folder_paths.models_dir, 'BiRefNet') + os.makedirs(birefnet_path, exist_ok=True) + + model_path = os.path.join(birefnet_path, version) + + if version == "BiRefNet-General": + old_birefnet_path = os.path.join(birefnet_path, 'pth') + old_model = "BiRefNet-general-epoch_244.pth" + old_model_path = os.path.join(old_birefnet_path, old_model) + if os.path.exists(old_model_path): + from .BiRefNet_v2.models.birefnet import BiRefNet + from .BiRefNet_v2.utils import check_state_dict + self.birefnet = BiRefNet(bb_pretrained=False) + self.state_dict = torch.load(old_model_path, map_location='cpu', weights_only=True) + self.state_dict = check_state_dict(self.state_dict) + self.birefnet.load_state_dict(self.state_dict) + return (self.birefnet,) + elif not os.path.exists(model_path): + log(f"Downloading {version} model...") + repo_id = self.birefnet_model_repos[version] + from huggingface_hub import snapshot_download + snapshot_download(repo_id=repo_id, local_dir=model_path, ignore_patterns=["*.md", "*.txt"]) + + self.model = AutoModelForImageSegmentation.from_pretrained(model_path, trust_remote_code=True) + return (self.model,) + +class LS_BiRefNetUltraV2: + + def __init__(self): + self.NODE_NAME = 'BiRefNetUltraV2' + + @classmethod + def INPUT_TYPES(cls): + + method_list = ['VITMatte', 'VITMatte(local)', 'PyMatting', 'GuidedFilter', ] + device_list = ['cuda', 'cpu'] + return { + "required": { + "image": ("IMAGE",), + "birefnet_model": ("BIREFNET_MODEL",), + "detail_method": (method_list,), + "detail_erode": ("INT", {"default": 4, "min": 1, "max": 255, "step": 1}), + "detail_dilate": ("INT", {"default": 2, "min": 1, "max": 255, "step": 1}), + "black_point": ("FLOAT", {"default": 0.01, "min": 0.01, "max": 0.98, "step": 0.01, "display": "slider"}), + "white_point": ("FLOAT", {"default": 0.99, "min": 0.02, "max": 0.99, "step": 0.01, "display": "slider"}), + "process_detail": ("BOOLEAN", {"default": False}), + "device": (device_list,), + "max_megapixels": ("FLOAT", {"default": 2.0, "min": 1, "max": 999, "step": 0.1}), + }, + "optional": { + } + } + + RETURN_TYPES = ("IMAGE", "MASK", ) + RETURN_NAMES = ("image", "mask", ) + FUNCTION = "birefnet_ultra_v2" + CATEGORY = '😺dzNodes/LayerMask' + + def birefnet_ultra_v2(self, image, birefnet_model, detail_method, detail_erode, detail_dilate, + black_point, white_point, process_detail, device, max_megapixels): + ret_images = [] + ret_masks = [] + inference_image_size = (1024, 1024) + if detail_method == 'VITMatte(local)': + local_files_only = True + else: + local_files_only = False + + torch.set_float32_matmul_precision(['high', 'highest'][0]) + birefnet_model.to(device) + birefnet_model.eval() + + comfy_pbar = ProgressBar(len(image)) + tqdm_pbar = tqdm(total=len(image), desc="Processing BiRefNet") + for i in image: + i = torch.unsqueeze(i, 0) + orig_image = tensor2pil(i).convert('RGB') + + transform_image = transforms.Compose([ + transforms.Resize(inference_image_size), + transforms.ToTensor(), + transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) + ]) + + inference_image = transform_image(orig_image).unsqueeze(0).to(device) + + # Prediction + with torch.no_grad(): + preds = birefnet_model(inference_image)[-1].sigmoid().cpu() + pred = preds[0].squeeze() + pred_pil = transforms.ToPILImage()(pred) + _mask = pred_pil.resize(inference_image_size) + + resize_sampler = Image.BILINEAR + _mask = _mask.resize(orig_image.size, resize_sampler) + brightness_image = ImageEnhance.Brightness(_mask) + _mask = brightness_image.enhance(factor=1.08) + _mask = image2mask(_mask) + + detail_range = detail_erode + detail_dilate + + if process_detail: + if detail_method == 'GuidedFilter': + _mask = guided_filter_alpha(i, _mask, detail_range // 6 + 1) + _mask = tensor2pil(histogram_remap(_mask, black_point, white_point)) + elif detail_method == 'PyMatting': + _mask = tensor2pil(mask_edge_detail(i, _mask, detail_range // 8 + 1, black_point, white_point)) + else: + _trimap = generate_VITMatte_trimap(_mask, detail_erode, detail_dilate) + _mask = generate_VITMatte(orig_image, _trimap, local_files_only=local_files_only, device=device, max_megapixels=max_megapixels) + _mask = tensor2pil(histogram_remap(pil2tensor(_mask), black_point, white_point)) + else: + _mask = tensor2pil(_mask) + + ret_image = RGB2RGBA(orig_image, _mask.convert('L')) + ret_images.append(pil2tensor(ret_image)) + ret_masks.append(image2mask(_mask)) + + comfy_pbar.update(1) + tqdm_pbar.update(1) + + log(f"{self.NODE_NAME} Processed {len(ret_masks)} image(s).", message_type='finish') + return (torch.cat(ret_images, dim=0), torch.cat(ret_masks, dim=0),) + +NODE_CLASS_MAPPINGS = { + "LayerMask: BiRefNetUltraV2": LS_BiRefNetUltraV2, + "LayerMask: LoadBiRefNetModel": LS_LoadBiRefNetModel, + "LayerMask: LoadBiRefNetModelV2": LS_LoadBiRefNetModelV2 +} + +NODE_DISPLAY_NAME_MAPPINGS = { + "LayerMask: BiRefNetUltraV2": "LayerMask: BiRefNet Ultra V2(Advance)", + "LayerMask: LoadBiRefNetModel": "LayerMask: Load BiRefNet Model(Advance)", + "LayerMask: LoadBiRefNetModelV2": "LayerMask: Load BiRefNet Model V2(Advance)" +} diff --git a/py/blendmodes.py b/py/blendmodes.py new file mode 100644 index 0000000..fac31af --- /dev/null +++ b/py/blendmodes.py @@ -0,0 +1,324 @@ +""" +author: Chris Freilich +description: This extension provides a blend modes node with 30 blend modes. +""" +from PIL import Image +import numpy as np +import torch +import torch.nn.functional as F +from colorsys import rgb_to_hsv +from blend_modes import difference, normal, screen, soft_light, lighten_only, dodge, \ + addition, darken_only, multiply, hard_light, \ + grain_extract, grain_merge, divide, overlay + +def dissolve(backdrop, source, opacity): + # Normalize the RGB and alpha values to 0-1 + backdrop_norm = backdrop[:, :, :3] / 255 + source_norm = source[:, :, :3] / 255 + source_alpha_norm = source[:, :, 3] / 255 + + # Calculate the transparency of each pixel in the source image + transparency = opacity * source_alpha_norm + + # Generate a random matrix with the same shape as the source image + random_matrix = np.random.random(source.shape[:2]) + + # Create a mask where the random values are less than the transparency + mask = random_matrix < transparency + + # Use the mask to select pixels from the source or backdrop + blend = np.where(mask[..., None], source_norm, backdrop_norm) + + # Apply the alpha channel of the source image to the blended image + new_rgb = (1 - source_alpha_norm[..., None]) * backdrop_norm + source_alpha_norm[..., None] * blend + + # Ensure the RGB values are within the valid range + new_rgb = np.clip(new_rgb, 0, 1) + + # Convert the RGB values back to 0-255 + new_rgb = new_rgb * 255 + + # Calculate the new alpha value by taking the maximum of the backdrop and source alpha channels + new_alpha = np.maximum(backdrop[:, :, 3], source[:, :, 3]) + + # Create a new RGBA image with the calculated RGB and alpha values + result = np.dstack((new_rgb, new_alpha)) + + return result + +def rgb_to_hsv_via_torch(rgb_numpy: np.ndarray, device=None) -> torch.Tensor: + """ + Convert an RGB image to HSV. + + :param rgb: A tensor of shape (3, H, W) where the three channels correspond to R, G, B. + The values should be in the range [0, 1]. + :return: A tensor of shape (3, H, W) where the three channels correspond to H, S, V. + The hue (H) will be in the range [0, 1], while S and V will be in the range [0, 1]. + """ + if device is None: + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + + rgb = torch.from_numpy(rgb_numpy).float().permute(2, 0, 1).to(device) + r, g, b = rgb[0], rgb[1], rgb[2] + + max_val, _ = torch.max(rgb, dim=0) + min_val, _ = torch.min(rgb, dim=0) + delta = max_val - min_val + + h = torch.zeros_like(max_val) + s = torch.zeros_like(max_val) + v = max_val + + # calc hue... avoid div by zero (by masking the delta) + mask = delta != 0 + r_eq_max = (r == max_val) & mask + g_eq_max = (g == max_val) & mask + b_eq_max = (b == max_val) & mask + + h[r_eq_max] = (g[r_eq_max] - b[r_eq_max]) / delta[r_eq_max] % 6 + h[g_eq_max] = (b[g_eq_max] - r[g_eq_max]) / delta[g_eq_max] + 2.0 + h[b_eq_max] = (r[b_eq_max] - g[b_eq_max]) / delta[b_eq_max] + 4.0 + + h = (h / 6.0) % 1.0 + + # calc saturation + s[max_val != 0] = delta[max_val != 0] / max_val[max_val != 0] + + hsv = torch.stack([h, s, v], dim=0) + + hsv_numpy = hsv.permute(1, 2, 0).cpu().numpy() + return hsv_numpy + +def hsv_to_rgb_via_torch(hsv_numpy: np.ndarray, device=None) -> torch.Tensor: + """ + Convert an HSV image to RGB. + + :param hsv: A tensor of shape (3, H, W) where the three channels correspond to H, S, V. + The H channel values should be in the range [0, 1], while S and V will be in the range [0, 1]. + :return: A tensor of shape (3, H, W) where the three channels correspond to R, G, B. + The RGB values will be in the range [0, 1]. + """ + if device is None: + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + + hsv = torch.from_numpy(hsv_numpy).float().permute(2, 0, 1).to(device) + h, s, v = hsv[0], hsv[1], hsv[2] + + c = v * s # chroma + x = c * (1 - torch.abs((h * 6) % 2 - 1)) + m = v - c # match value + + z = torch.zeros_like(h) + rgb = torch.zeros_like(hsv) + + # define conditions for different hue ranges + h_cond = [ + (h < 1/6, torch.stack([c, x, z], dim=0)), + ((1/6 <= h) & (h < 2/6), torch.stack([x, c, z], dim=0)), + ((2/6 <= h) & (h < 3/6), torch.stack([z, c, x], dim=0)), + ((3/6 <= h) & (h < 4/6), torch.stack([z, x, c], dim=0)), + ((4/6 <= h) & (h < 5/6), torch.stack([x, z, c], dim=0)), + (h >= 5/6, torch.stack([c, z, x], dim=0)), + ] + + # conditionally set RGB values based on the hue range + for cond, result in h_cond: + rgb[:, cond] = result[:, cond] + + # add match value to convert to final RGB values + rgb = rgb + m + + rgb_numpy = rgb.permute(1, 2, 0).cpu().numpy() + return rgb_numpy + +def hsv(backdrop, source, opacity, channel): + + # Convert RGBA to RGB, normalized + backdrop_rgb = backdrop[:, :, :3] / 255.0 + source_rgb = source[:, :, :3] / 255.0 + source_alpha = source[:, :, 3] / 255.0 + + # Convert RGB to HSV + backdrop_hsv = rgb_to_hsv_via_torch(backdrop_rgb) + source_hsv = rgb_to_hsv_via_torch(source_rgb) + + # Combine HSV values + new_hsv = backdrop_hsv.copy() + + # Determine which channel to operate on + if channel == "saturation": + new_hsv[:, :, 1] = (1 - opacity * source_alpha) * backdrop_hsv[:, :, 1] + opacity * source_alpha * source_hsv[:, :, 1] + elif channel == "luminance": + new_hsv[:, :, 2] = (1 - opacity * source_alpha) * backdrop_hsv[:, :, 2] + opacity * source_alpha * source_hsv[:, :, 2] + elif channel == "hue": + new_hsv[:, :, 0] = (1 - opacity * source_alpha) * backdrop_hsv[:, :, 0] + opacity * source_alpha * source_hsv[:, :, 0] + elif channel == "color": + new_hsv[:, :, :2] = (1 - opacity * source_alpha[..., None]) * backdrop_hsv[:, :, :2] + opacity * source_alpha[..., None] * source_hsv[:, :, :2] + + # Convert HSV back to RGB + new_rgb = hsv_to_rgb_via_torch(new_hsv) + + # Apply the alpha channel of the source image to the new RGB image + new_rgb = (1 - source_alpha[..., None]) * backdrop_rgb + source_alpha[..., None] * new_rgb + + # Ensure the RGB values are within the valid range + new_rgb = np.clip(new_rgb, 0, 1) + + # Convert RGB back to RGBA and scale to 0-255 range + new_rgba = np.dstack((new_rgb * 255, backdrop[:, :, 3])) + + return new_rgba.astype(np.uint8) + +def saturation(backdrop, source, opacity): + return hsv(backdrop, source, opacity, "saturation") + +def luminance(backdrop, source, opacity): + return hsv(backdrop, source, opacity, "luminance") + +def hue(backdrop, source, opacity): + return hsv(backdrop, source, opacity, "hue") + +def color(backdrop, source, opacity): + return hsv(backdrop, source, opacity, "color") + +def darker_lighter_color(backdrop, source, opacity, type): + + # Normalize the RGB and alpha values to 0-1 + backdrop_norm = backdrop[:, :, :3] / 255 + source_norm = source[:, :, :3] / 255 + source_alpha_norm = source[:, :, 3] / 255 + + # Convert RGB to HSV + backdrop_hsv = np.array([rgb_to_hsv(*rgb) for row in backdrop_norm for rgb in row]).reshape(backdrop.shape[:2] + (3,)) + source_hsv = np.array([rgb_to_hsv(*rgb) for row in source_norm for rgb in row]).reshape(source.shape[:2] + (3,)) + + # Create a mask where the value (brightness) of the source image is less than the value of the backdrop image + if type == "dark": + mask = source_hsv[:, :, 2] < backdrop_hsv[:, :, 2] + else: + mask = source_hsv[:, :, 2] > backdrop_hsv[:, :, 2] + + # Use the mask to select pixels from the source or backdrop + blend = np.where(mask[..., None], source_norm, backdrop_norm) + + # Apply the alpha channel of the source image to the blended image + new_rgb = (1 - source_alpha_norm[..., None] * opacity) * backdrop_norm + source_alpha_norm[..., None] * opacity * blend + + # Ensure the RGB values are within the valid range + new_rgb = np.clip(new_rgb, 0, 1) + + # Convert the RGB values back to 0-255 + new_rgb = new_rgb * 255 + + # Calculate the new alpha value by taking the maximum of the backdrop and source alpha channels + new_alpha = np.maximum(backdrop[:, :, 3], source[:, :, 3]) + + # Create a new RGBA image with the calculated RGB and alpha values + result = np.dstack((new_rgb, new_alpha)) + + return result + +def darker_color(backdrop, source, opacity): + return darker_lighter_color(backdrop, source, opacity, "dark") + +def lighter_color(backdrop, source, opacity): + return darker_lighter_color(backdrop, source, opacity, "light") + +def simple_mode(backdrop, source, opacity, mode): + # Normalize the RGB and alpha values to 0-1 + backdrop_norm = backdrop[:, :, :3] / 255 + source_norm = source[:, :, :3] / 255 + source_alpha_norm = source[:, :, 3:4] / 255 + + # Calculate the blend without any transparency considerations + if mode == "linear_burn": + blend = backdrop_norm + source_norm - 1 + elif mode == "linear_light": + blend = backdrop_norm + (2 * source_norm) - 1 + elif mode == "color_dodge": + blend = backdrop_norm / (1 - source_norm) + blend = np.clip(blend, 0, 1) + elif mode == "color_burn": + blend = 1 - ((1 - backdrop_norm) / source_norm) + blend = np.clip(blend, 0, 1) + elif mode == "exclusion": + blend = backdrop_norm + source_norm - (2 * backdrop_norm * source_norm) + elif mode == "subtract": + blend = backdrop_norm - source_norm + elif mode == "vivid_light": + blend = np.where(source_norm <= 0.5, backdrop_norm / (1 - 2 * source_norm), 1 - (1 -backdrop_norm) / (2 * source_norm - 0.5) ) + blend = np.clip(blend, 0, 1) + elif mode == "pin_light": + blend = np.where(source_norm <= 0.5, np.minimum(backdrop_norm, 2 * source_norm), np.maximum(backdrop_norm, 2 * (source_norm - 0.5))) + elif mode == "hard_mix": + blend = simple_mode(backdrop, source, opacity, "linear_light") + blend = np.round(blend[:, :, :3] / 255) + + # Apply the blended layer back onto the backdrop layer while utilizing the alpha channel and opacity information + new_rgb = (1 - source_alpha_norm * opacity) * backdrop_norm + source_alpha_norm * opacity * blend + + # Ensure the RGB values are within the valid range + new_rgb = np.clip(new_rgb, 0, 1) + + # Convert the RGB values back to 0-255 + new_rgb = new_rgb * 255 + + # Calculate the new alpha value by taking the maximum of the backdrop and source alpha channels + new_alpha = np.maximum(backdrop[:, :, 3], source[:, :, 3]) + + # Create a new RGBA image with the calculated RGB and alpha values + result = np.dstack((new_rgb, new_alpha)) + + return result + +def linear_light(backdrop, source, opacity): + return simple_mode(backdrop, source, opacity, "linear_light") +def vivid_light(backdrop, source, opacity): + return simple_mode(backdrop, source, opacity, "vivid_light") +def pin_light(backdrop, source, opacity): + return simple_mode(backdrop, source, opacity, "pin_light") +def hard_mix(backdrop, source, opacity): + return simple_mode(backdrop, source, opacity, "hard_mix") +def linear_burn(backdrop, source, opacity): + return simple_mode(backdrop, source, opacity, "linear_burn") +def color_dodge(backdrop, source, opacity): + return simple_mode(backdrop, source, opacity, "color_dodge") +def color_burn(backdrop, source, opacity): + return simple_mode(backdrop, source, opacity, "color_burn") +def exclusion(backdrop, source, opacity): + return simple_mode(backdrop, source, opacity, "exclusion") +def subtract(backdrop, source, opacity): + return simple_mode(backdrop, source, opacity, "subtract") + +BLEND_MODES = { + "normal": normal, + "dissolve": dissolve, + "darken": darken_only, + "multiply": multiply, + "color burn": color_burn, + "linear burn": linear_burn, + "darker color": darker_color, + "lighten": lighten_only, + "screen": screen, + "color dodge": color_dodge, + "linear dodge(add)": addition, + "lighter color": lighter_color, + "dodge": dodge, + "overlay": overlay, + "soft light": soft_light, + "hard light": hard_light, + "vivid light": vivid_light, + "linear light": linear_light, + "pin light": pin_light, + "hard mix": hard_mix, + "difference": difference, + "exclusion": exclusion, + "subtract": subtract, + "divide": divide, + "hue": hue, + "saturation": saturation, + "color": color, + "luminosity": luminance, + "grain extract": grain_extract, + "grain merge": grain_merge +} diff --git a/py/briarmbg.py b/py/briarmbg.py new file mode 100644 index 0000000..647bdc0 --- /dev/null +++ b/py/briarmbg.py @@ -0,0 +1,455 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F + +class REBNCONV(nn.Module): + def __init__(self,in_ch=3,out_ch=3,dirate=1,stride=1): + super(REBNCONV,self).__init__() + + self.conv_s1 = nn.Conv2d(in_ch,out_ch,3,padding=1*dirate,dilation=1*dirate,stride=stride) + self.bn_s1 = nn.BatchNorm2d(out_ch) + self.relu_s1 = nn.ReLU(inplace=True) + + def forward(self,x): + + hx = x + xout = self.relu_s1(self.bn_s1(self.conv_s1(hx))) + + return xout + +## upsample tensor 'src' to have the same spatial size with tensor 'tar' +def _upsample_like(src,tar): + + src = F.interpolate(src,size=tar.shape[2:],mode='bilinear') + + return src + + +### RSU-7 ### +class RSU7(nn.Module): + + def __init__(self, in_ch=3, mid_ch=12, out_ch=3, img_size=512): + super(RSU7,self).__init__() + + self.in_ch = in_ch + self.mid_ch = mid_ch + self.out_ch = out_ch + + self.rebnconvin = REBNCONV(in_ch,out_ch,dirate=1) ## 1 -> 1/2 + + self.rebnconv1 = REBNCONV(out_ch,mid_ch,dirate=1) + self.pool1 = nn.MaxPool2d(2,stride=2,ceil_mode=True) + + self.rebnconv2 = REBNCONV(mid_ch,mid_ch,dirate=1) + self.pool2 = nn.MaxPool2d(2,stride=2,ceil_mode=True) + + self.rebnconv3 = REBNCONV(mid_ch,mid_ch,dirate=1) + self.pool3 = nn.MaxPool2d(2,stride=2,ceil_mode=True) + + self.rebnconv4 = REBNCONV(mid_ch,mid_ch,dirate=1) + self.pool4 = nn.MaxPool2d(2,stride=2,ceil_mode=True) + + self.rebnconv5 = REBNCONV(mid_ch,mid_ch,dirate=1) + self.pool5 = nn.MaxPool2d(2,stride=2,ceil_mode=True) + + self.rebnconv6 = REBNCONV(mid_ch,mid_ch,dirate=1) + + self.rebnconv7 = REBNCONV(mid_ch,mid_ch,dirate=2) + + self.rebnconv6d = REBNCONV(mid_ch*2,mid_ch,dirate=1) + self.rebnconv5d = REBNCONV(mid_ch*2,mid_ch,dirate=1) + self.rebnconv4d = REBNCONV(mid_ch*2,mid_ch,dirate=1) + self.rebnconv3d = REBNCONV(mid_ch*2,mid_ch,dirate=1) + self.rebnconv2d = REBNCONV(mid_ch*2,mid_ch,dirate=1) + self.rebnconv1d = REBNCONV(mid_ch*2,out_ch,dirate=1) + + def forward(self,x): + b, c, h, w = x.shape + + hx = x + hxin = self.rebnconvin(hx) + + hx1 = self.rebnconv1(hxin) + hx = self.pool1(hx1) + + hx2 = self.rebnconv2(hx) + hx = self.pool2(hx2) + + hx3 = self.rebnconv3(hx) + hx = self.pool3(hx3) + + hx4 = self.rebnconv4(hx) + hx = self.pool4(hx4) + + hx5 = self.rebnconv5(hx) + hx = self.pool5(hx5) + + hx6 = self.rebnconv6(hx) + + hx7 = self.rebnconv7(hx6) + + hx6d = self.rebnconv6d(torch.cat((hx7,hx6),1)) + hx6dup = _upsample_like(hx6d,hx5) + + hx5d = self.rebnconv5d(torch.cat((hx6dup,hx5),1)) + hx5dup = _upsample_like(hx5d,hx4) + + hx4d = self.rebnconv4d(torch.cat((hx5dup,hx4),1)) + hx4dup = _upsample_like(hx4d,hx3) + + hx3d = self.rebnconv3d(torch.cat((hx4dup,hx3),1)) + hx3dup = _upsample_like(hx3d,hx2) + + hx2d = self.rebnconv2d(torch.cat((hx3dup,hx2),1)) + hx2dup = _upsample_like(hx2d,hx1) + + hx1d = self.rebnconv1d(torch.cat((hx2dup,hx1),1)) + + return hx1d + hxin + + +### RSU-6 ### +class RSU6(nn.Module): + + def __init__(self, in_ch=3, mid_ch=12, out_ch=3): + super(RSU6,self).__init__() + + self.rebnconvin = REBNCONV(in_ch,out_ch,dirate=1) + + self.rebnconv1 = REBNCONV(out_ch,mid_ch,dirate=1) + self.pool1 = nn.MaxPool2d(2,stride=2,ceil_mode=True) + + self.rebnconv2 = REBNCONV(mid_ch,mid_ch,dirate=1) + self.pool2 = nn.MaxPool2d(2,stride=2,ceil_mode=True) + + self.rebnconv3 = REBNCONV(mid_ch,mid_ch,dirate=1) + self.pool3 = nn.MaxPool2d(2,stride=2,ceil_mode=True) + + self.rebnconv4 = REBNCONV(mid_ch,mid_ch,dirate=1) + self.pool4 = nn.MaxPool2d(2,stride=2,ceil_mode=True) + + self.rebnconv5 = REBNCONV(mid_ch,mid_ch,dirate=1) + + self.rebnconv6 = REBNCONV(mid_ch,mid_ch,dirate=2) + + self.rebnconv5d = REBNCONV(mid_ch*2,mid_ch,dirate=1) + self.rebnconv4d = REBNCONV(mid_ch*2,mid_ch,dirate=1) + self.rebnconv3d = REBNCONV(mid_ch*2,mid_ch,dirate=1) + self.rebnconv2d = REBNCONV(mid_ch*2,mid_ch,dirate=1) + self.rebnconv1d = REBNCONV(mid_ch*2,out_ch,dirate=1) + + def forward(self,x): + + hx = x + + hxin = self.rebnconvin(hx) + + hx1 = self.rebnconv1(hxin) + hx = self.pool1(hx1) + + hx2 = self.rebnconv2(hx) + hx = self.pool2(hx2) + + hx3 = self.rebnconv3(hx) + hx = self.pool3(hx3) + + hx4 = self.rebnconv4(hx) + hx = self.pool4(hx4) + + hx5 = self.rebnconv5(hx) + + hx6 = self.rebnconv6(hx5) + + + hx5d = self.rebnconv5d(torch.cat((hx6,hx5),1)) + hx5dup = _upsample_like(hx5d,hx4) + + hx4d = self.rebnconv4d(torch.cat((hx5dup,hx4),1)) + hx4dup = _upsample_like(hx4d,hx3) + + hx3d = self.rebnconv3d(torch.cat((hx4dup,hx3),1)) + hx3dup = _upsample_like(hx3d,hx2) + + hx2d = self.rebnconv2d(torch.cat((hx3dup,hx2),1)) + hx2dup = _upsample_like(hx2d,hx1) + + hx1d = self.rebnconv1d(torch.cat((hx2dup,hx1),1)) + + return hx1d + hxin + +### RSU-5 ### +class RSU5(nn.Module): + + def __init__(self, in_ch=3, mid_ch=12, out_ch=3): + super(RSU5,self).__init__() + + self.rebnconvin = REBNCONV(in_ch,out_ch,dirate=1) + + self.rebnconv1 = REBNCONV(out_ch,mid_ch,dirate=1) + self.pool1 = nn.MaxPool2d(2,stride=2,ceil_mode=True) + + self.rebnconv2 = REBNCONV(mid_ch,mid_ch,dirate=1) + self.pool2 = nn.MaxPool2d(2,stride=2,ceil_mode=True) + + self.rebnconv3 = REBNCONV(mid_ch,mid_ch,dirate=1) + self.pool3 = nn.MaxPool2d(2,stride=2,ceil_mode=True) + + self.rebnconv4 = REBNCONV(mid_ch,mid_ch,dirate=1) + + self.rebnconv5 = REBNCONV(mid_ch,mid_ch,dirate=2) + + self.rebnconv4d = REBNCONV(mid_ch*2,mid_ch,dirate=1) + self.rebnconv3d = REBNCONV(mid_ch*2,mid_ch,dirate=1) + self.rebnconv2d = REBNCONV(mid_ch*2,mid_ch,dirate=1) + self.rebnconv1d = REBNCONV(mid_ch*2,out_ch,dirate=1) + + def forward(self,x): + + hx = x + + hxin = self.rebnconvin(hx) + + hx1 = self.rebnconv1(hxin) + hx = self.pool1(hx1) + + hx2 = self.rebnconv2(hx) + hx = self.pool2(hx2) + + hx3 = self.rebnconv3(hx) + hx = self.pool3(hx3) + + hx4 = self.rebnconv4(hx) + + hx5 = self.rebnconv5(hx4) + + hx4d = self.rebnconv4d(torch.cat((hx5,hx4),1)) + hx4dup = _upsample_like(hx4d,hx3) + + hx3d = self.rebnconv3d(torch.cat((hx4dup,hx3),1)) + hx3dup = _upsample_like(hx3d,hx2) + + hx2d = self.rebnconv2d(torch.cat((hx3dup,hx2),1)) + hx2dup = _upsample_like(hx2d,hx1) + + hx1d = self.rebnconv1d(torch.cat((hx2dup,hx1),1)) + + return hx1d + hxin + +### RSU-4 ### +class RSU4(nn.Module): + + def __init__(self, in_ch=3, mid_ch=12, out_ch=3): + super(RSU4,self).__init__() + + self.rebnconvin = REBNCONV(in_ch,out_ch,dirate=1) + + self.rebnconv1 = REBNCONV(out_ch,mid_ch,dirate=1) + self.pool1 = nn.MaxPool2d(2,stride=2,ceil_mode=True) + + self.rebnconv2 = REBNCONV(mid_ch,mid_ch,dirate=1) + self.pool2 = nn.MaxPool2d(2,stride=2,ceil_mode=True) + + self.rebnconv3 = REBNCONV(mid_ch,mid_ch,dirate=1) + + self.rebnconv4 = REBNCONV(mid_ch,mid_ch,dirate=2) + + self.rebnconv3d = REBNCONV(mid_ch*2,mid_ch,dirate=1) + self.rebnconv2d = REBNCONV(mid_ch*2,mid_ch,dirate=1) + self.rebnconv1d = REBNCONV(mid_ch*2,out_ch,dirate=1) + + def forward(self,x): + + hx = x + + hxin = self.rebnconvin(hx) + + hx1 = self.rebnconv1(hxin) + hx = self.pool1(hx1) + + hx2 = self.rebnconv2(hx) + hx = self.pool2(hx2) + + hx3 = self.rebnconv3(hx) + + hx4 = self.rebnconv4(hx3) + + hx3d = self.rebnconv3d(torch.cat((hx4,hx3),1)) + hx3dup = _upsample_like(hx3d,hx2) + + hx2d = self.rebnconv2d(torch.cat((hx3dup,hx2),1)) + hx2dup = _upsample_like(hx2d,hx1) + + hx1d = self.rebnconv1d(torch.cat((hx2dup,hx1),1)) + + return hx1d + hxin + +### RSU-4F ### +class RSU4F(nn.Module): + + def __init__(self, in_ch=3, mid_ch=12, out_ch=3): + super(RSU4F,self).__init__() + + self.rebnconvin = REBNCONV(in_ch,out_ch,dirate=1) + + self.rebnconv1 = REBNCONV(out_ch,mid_ch,dirate=1) + self.rebnconv2 = REBNCONV(mid_ch,mid_ch,dirate=2) + self.rebnconv3 = REBNCONV(mid_ch,mid_ch,dirate=4) + + self.rebnconv4 = REBNCONV(mid_ch,mid_ch,dirate=8) + + self.rebnconv3d = REBNCONV(mid_ch*2,mid_ch,dirate=4) + self.rebnconv2d = REBNCONV(mid_ch*2,mid_ch,dirate=2) + self.rebnconv1d = REBNCONV(mid_ch*2,out_ch,dirate=1) + + def forward(self,x): + + hx = x + + hxin = self.rebnconvin(hx) + + hx1 = self.rebnconv1(hxin) + hx2 = self.rebnconv2(hx1) + hx3 = self.rebnconv3(hx2) + + hx4 = self.rebnconv4(hx3) + + hx3d = self.rebnconv3d(torch.cat((hx4,hx3),1)) + hx2d = self.rebnconv2d(torch.cat((hx3d,hx2),1)) + hx1d = self.rebnconv1d(torch.cat((hx2d,hx1),1)) + + return hx1d + hxin + + +class myrebnconv(nn.Module): + def __init__(self, in_ch=3, + out_ch=1, + kernel_size=3, + stride=1, + padding=1, + dilation=1, + groups=1): + super(myrebnconv,self).__init__() + + self.conv = nn.Conv2d(in_ch, + out_ch, + kernel_size=kernel_size, + stride=stride, + padding=padding, + dilation=dilation, + groups=groups) + self.bn = nn.BatchNorm2d(out_ch) + self.rl = nn.ReLU(inplace=True) + + def forward(self,x): + return self.rl(self.bn(self.conv(x))) + + +class BriaRMBG(nn.Module): + + def __init__(self,in_ch=3,out_ch=1): + super(BriaRMBG,self).__init__() + + self.conv_in = nn.Conv2d(in_ch,64,3,stride=2,padding=1) + self.pool_in = nn.MaxPool2d(2,stride=2,ceil_mode=True) + + self.stage1 = RSU7(64,32,64) + self.pool12 = nn.MaxPool2d(2,stride=2,ceil_mode=True) + + self.stage2 = RSU6(64,32,128) + self.pool23 = nn.MaxPool2d(2,stride=2,ceil_mode=True) + + self.stage3 = RSU5(128,64,256) + self.pool34 = nn.MaxPool2d(2,stride=2,ceil_mode=True) + + self.stage4 = RSU4(256,128,512) + self.pool45 = nn.MaxPool2d(2,stride=2,ceil_mode=True) + + self.stage5 = RSU4F(512,256,512) + self.pool56 = nn.MaxPool2d(2,stride=2,ceil_mode=True) + + self.stage6 = RSU4F(512,256,512) + + # decoder + self.stage5d = RSU4F(1024,256,512) + self.stage4d = RSU4(1024,128,256) + self.stage3d = RSU5(512,64,128) + self.stage2d = RSU6(256,32,64) + self.stage1d = RSU7(128,16,64) + + self.side1 = nn.Conv2d(64,out_ch,3,padding=1) + self.side2 = nn.Conv2d(64,out_ch,3,padding=1) + self.side3 = nn.Conv2d(128,out_ch,3,padding=1) + self.side4 = nn.Conv2d(256,out_ch,3,padding=1) + self.side5 = nn.Conv2d(512,out_ch,3,padding=1) + self.side6 = nn.Conv2d(512,out_ch,3,padding=1) + + # self.outconv = nn.Conv2d(6*out_ch,out_ch,1) + + def forward(self,x): + + hx = x + + hxin = self.conv_in(hx) + #hx = self.pool_in(hxin) + + #stage 1 + hx1 = self.stage1(hxin) + hx = self.pool12(hx1) + + #stage 2 + hx2 = self.stage2(hx) + hx = self.pool23(hx2) + + #stage 3 + hx3 = self.stage3(hx) + hx = self.pool34(hx3) + + #stage 4 + hx4 = self.stage4(hx) + hx = self.pool45(hx4) + + #stage 5 + hx5 = self.stage5(hx) + hx = self.pool56(hx5) + + #stage 6 + hx6 = self.stage6(hx) + hx6up = _upsample_like(hx6,hx5) + + #-------------------- decoder -------------------- + hx5d = self.stage5d(torch.cat((hx6up,hx5),1)) + hx5dup = _upsample_like(hx5d,hx4) + + hx4d = self.stage4d(torch.cat((hx5dup,hx4),1)) + hx4dup = _upsample_like(hx4d,hx3) + + hx3d = self.stage3d(torch.cat((hx4dup,hx3),1)) + hx3dup = _upsample_like(hx3d,hx2) + + hx2d = self.stage2d(torch.cat((hx3dup,hx2),1)) + hx2dup = _upsample_like(hx2d,hx1) + + hx1d = self.stage1d(torch.cat((hx2dup,hx1),1)) + + + #side output + d1 = self.side1(hx1d) + d1 = _upsample_like(d1,x) + + d2 = self.side2(hx2d) + d2 = _upsample_like(d2,x) + + d3 = self.side3(hx3d) + d3 = _upsample_like(d3,x) + + d4 = self.side4(hx4d) + d4 = _upsample_like(d4,x) + + d5 = self.side5(hx5d) + d5 = _upsample_like(d5,x) + + d6 = self.side6(hx6) + d6 = _upsample_like(d6,x) + + return [F.sigmoid(d1), F.sigmoid(d2), F.sigmoid(d3), F.sigmoid(d4), F.sigmoid(d5), F.sigmoid(d6)],[hx1d,hx2d,hx3d,hx4d,hx5d,hx6] + diff --git a/py/evf_sam/__init__.py b/py/evf_sam/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/py/evf_sam/evf_sam_inference.py b/py/evf_sam/evf_sam_inference.py new file mode 100644 index 0000000..9571fa4 --- /dev/null +++ b/py/evf_sam/evf_sam_inference.py @@ -0,0 +1,146 @@ +import os +import sys +from PIL import Image +import cv2 +import numpy as np +import torch +import torch.nn.functional as F +from torchvision import transforms +from torchvision.transforms.functional import InterpolationMode +from transformers import AutoTokenizer, BitsAndBytesConfig +sys.path.insert(0, os.path.abspath(os.path.dirname(__file__))) +from .model.segment_anything.utils.transforms import ResizeLongestSide + +def sam_preprocess( + x: np.ndarray, + pixel_mean=torch.Tensor([123.675, 116.28, 103.53]).view(-1, 1, 1), + pixel_std=torch.Tensor([58.395, 57.12, 57.375]).view(-1, 1, 1), + img_size=1024, + model_type="ori") -> torch.Tensor: + ''' + preprocess of Segment Anything Model, including scaling, normalization and padding. + preprocess differs between SAM and Effi-SAM, where Effi-SAM use no padding. + input: ndarray + output: torch.Tensor + ''' + assert img_size==1024, \ + "both SAM and Effi-SAM receive images of size 1024^2, don't change this setting unless you're sure that your employed model works well with another size." + x = ResizeLongestSide(img_size).apply_image(x) + resize_shape = x.shape[:2] + x = torch.from_numpy(x).permute(2,0,1).contiguous() + + # Normalize colors + x = (x - pixel_mean) / pixel_std + if model_type=="effi" or model_type=="sam2": + x = F.interpolate(x.unsqueeze(0), (img_size, img_size), mode="bilinear").squeeze(0) + else: + # Pad + h, w = x.shape[-2:] + padh = img_size - h + padw = img_size - w + x = F.pad(x, (0, padw, 0, padh)) + return x, resize_shape + +def beit3_preprocess(x: np.ndarray, img_size=224) -> torch.Tensor: + ''' + preprocess for BEIT-3 model. + input: ndarray + output: torch.Tensor + ''' + beit_preprocess = transforms.Compose([ + transforms.ToTensor(), + transforms.Resize((img_size, img_size), interpolation=InterpolationMode.BICUBIC), + transforms.Normalize(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5)) + ]) + return beit_preprocess(x) + +def init_models(model_path:str, model_type:str, precision:str, load_in_bit:int=16): + tokenizer = AutoTokenizer.from_pretrained( + model_path, + padding_side="right", + use_fast=False, + ) + + torch_dtype = torch.float32 + if precision == "bf16": + torch_dtype = torch.bfloat16 + elif precision == "fp16": + torch_dtype = torch.half + + kwargs = {"torch_dtype": torch_dtype} + + if load_in_bit==4: + kwargs.update( + { + "torch_dtype": torch.half, + "quantization_config": BitsAndBytesConfig( + llm_int8_skip_modules=["visual_model"], + load_in_4bit=True, + bnb_4bit_compute_dtype=torch.float16, + bnb_4bit_use_double_quant=True, + bnb_4bit_quant_type="nf4", + ), + } + ) + elif load_in_bit==8: + kwargs.update( + { + "torch_dtype": torch.half, + "quantization_config": BitsAndBytesConfig( + llm_int8_skip_modules=["visual_model"], + load_in_8bit=True, + ), + } + ) + + if model_type=="ori": + from model.evf_sam import EvfSamModel + model = EvfSamModel.from_pretrained( + model_path, low_cpu_mem_usage=True, **kwargs + ) + elif model_type=="effi": + from model.evf_effisam import EvfEffiSamModel + model = EvfEffiSamModel.from_pretrained( + model_path, low_cpu_mem_usage=True, **kwargs + ) + elif model_type=="sam2": + from model.evf_sam2 import EvfSam2Model + model = EvfSam2Model.from_pretrained( + model_path, low_cpu_mem_usage=True, **kwargs + ) + + if load_in_bit > 8 and torch.cuda.is_available(): + model = model.cuda() + model.eval() + + return tokenizer, model + +def evf_sam_main(model_path:str, model_type:str, precision:str, load_in_bit:int, image:Image, prompt:str, ): + + image_size = 224 + # initialize model and tokenizer + tokenizer, model = init_models(model_path, model_type, precision, load_in_bit) + + # preprocess + image_np = np.asarray(image) + image_np = cv2.cvtColor(image_np, cv2.COLOR_BGR2RGB) + original_size_list = [image_np.shape[:2]] + image_beit = beit3_preprocess(image_np, image_size).to(dtype=model.dtype, device=model.device) + image_sam, resize_shape = sam_preprocess(image_np, model_type=model_type) + image_sam = image_sam.to(dtype=model.dtype, device=model.device) + input_ids = tokenizer(prompt, return_tensors="pt")["input_ids"].to(device=model.device) + + # infer + pred_mask = model.inference( + image_sam.unsqueeze(0), + image_beit.unsqueeze(0), + input_ids, + resize_list=[resize_shape], + original_size_list=original_size_list, + ) + + pred_mask = pred_mask.detach().cpu().numpy()[0] + pred_mask = (pred_mask > 0).astype(np.uint8) * 255 + out_put_image = Image.fromarray(pred_mask.squeeze(), mode="L") + + return out_put_image \ No newline at end of file diff --git a/py/evf_sam/model/EfficientSAM/efficient_sam/__init__.py b/py/evf_sam/model/EfficientSAM/efficient_sam/__init__.py new file mode 100644 index 0000000..22a2d29 --- /dev/null +++ b/py/evf_sam/model/EfficientSAM/efficient_sam/__init__.py @@ -0,0 +1,7 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +from .build_efficient_sam import ( + build_efficient_sam_vitt, + build_efficient_sam_vits, +) diff --git a/py/evf_sam/model/EfficientSAM/efficient_sam/build_efficient_sam.py b/py/evf_sam/model/EfficientSAM/efficient_sam/build_efficient_sam.py new file mode 100644 index 0000000..b5a030d --- /dev/null +++ b/py/evf_sam/model/EfficientSAM/efficient_sam/build_efficient_sam.py @@ -0,0 +1,22 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +from .efficient_sam import build_efficient_sam + +def build_efficient_sam_vitt(checkpoint=None): + return build_efficient_sam( + encoder_patch_embed_dim=192, + encoder_num_heads=3, + checkpoint=checkpoint, + ).eval() + + +def build_efficient_sam_vits(checkpoint=None): + return build_efficient_sam( + encoder_patch_embed_dim=384, + encoder_num_heads=6, + checkpoint=checkpoint, + ).eval() diff --git a/py/evf_sam/model/EfficientSAM/efficient_sam/efficient_sam.py b/py/evf_sam/model/EfficientSAM/efficient_sam/efficient_sam.py new file mode 100644 index 0000000..a4ad17d --- /dev/null +++ b/py/evf_sam/model/EfficientSAM/efficient_sam/efficient_sam.py @@ -0,0 +1,306 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import math +from typing import Any, List, Tuple, Type + +import torch +import torch.nn.functional as F + +from torch import nn, Tensor + +from .efficient_sam_decoder import MaskDecoder, PromptEncoder +from .efficient_sam_encoder import ImageEncoderViT +from .two_way_transformer import TwoWayAttentionBlock, TwoWayTransformer + +class EfficientSam(nn.Module): + mask_threshold: float = 0.0 + image_format: str = "RGB" + + def __init__( + self, + image_encoder: ImageEncoderViT, + prompt_encoder: PromptEncoder, + decoder_max_num_input_points: int, + mask_decoder: MaskDecoder, + pixel_mean: List[float] = [0.485, 0.456, 0.406], + pixel_std: List[float] = [0.229, 0.224, 0.225], + ) -> None: + """ + SAM predicts object masks from an image and input prompts. + + Arguments: + image_encoder (ImageEncoderViT): The backbone used to encode the + image into image embeddings that allow for efficient mask prediction. + prompt_encoder (PromptEncoder): Encodes various types of input prompts. + mask_decoder (MaskDecoder): Predicts masks from the image embeddings + and encoded prompts. + pixel_mean (list(float)): Mean values for normalizing pixels in the input image. + pixel_std (list(float)): Std values for normalizing pixels in the input image. + """ + super().__init__() + self.image_encoder = image_encoder + self.prompt_encoder = prompt_encoder + self.decoder_max_num_input_points = decoder_max_num_input_points + self.mask_decoder = mask_decoder + self.register_buffer( + "pixel_mean", torch.Tensor(pixel_mean).view(1, 3, 1, 1), False + ) + self.register_buffer( + "pixel_std", torch.Tensor(pixel_std).view(1, 3, 1, 1), False + ) + + @torch.jit.export + def predict_masks( + self, + image_embeddings: torch.Tensor, + batched_points: torch.Tensor, + batched_point_labels: torch.Tensor, + multimask_output: bool, + input_h: int, + input_w: int, + output_h: int = -1, + output_w: int = -1, + ) -> Tuple[torch.Tensor, torch.Tensor]: + """ + Predicts masks given image embeddings and prompts. This only runs the decoder. + + Arguments: + image_embeddings: A tensor of shape [B, C, H, W] or [B*max_num_queries, C, H, W] + batched_points: A tensor of shape [B, max_num_queries, num_pts, 2] + batched_point_labels: A tensor of shape [B, max_num_queries, num_pts] + Returns: + A tuple of two tensors: + low_res_mask: A tensor of shape [B, max_num_queries, 256, 256] of predicted masks + iou_predictions: A tensor of shape [B, max_num_queries] of estimated IOU scores + """ + + batch_size, max_num_queries, num_pts, _ = batched_points.shape + num_pts = batched_points.shape[2] + rescaled_batched_points = self.get_rescaled_pts(batched_points, input_h, input_w) + + if num_pts > self.decoder_max_num_input_points: + rescaled_batched_points = rescaled_batched_points[ + :, :, : self.decoder_max_num_input_points, : + ] + batched_point_labels = batched_point_labels[ + :, :, : self.decoder_max_num_input_points + ] + elif num_pts < self.decoder_max_num_input_points: + rescaled_batched_points = F.pad( + rescaled_batched_points, + (0, 0, 0, self.decoder_max_num_input_points - num_pts), + value=-1.0, + ) + batched_point_labels = F.pad( + batched_point_labels, + (0, self.decoder_max_num_input_points - num_pts), + value=-1.0, + ) + + sparse_embeddings = self.prompt_encoder( + rescaled_batched_points.reshape( + batch_size * max_num_queries, self.decoder_max_num_input_points, 2 + ), + batched_point_labels.reshape( + batch_size * max_num_queries, self.decoder_max_num_input_points + ), + ) + + sparse_embeddings = sparse_embeddings.view( + batch_size, + max_num_queries, + sparse_embeddings.shape[1], + sparse_embeddings.shape[2], + ) + low_res_masks, iou_predictions = self.mask_decoder( + image_embeddings, + self.prompt_encoder.get_dense_pe(), + sparse_prompt_embeddings=sparse_embeddings, + multimask_output=multimask_output, + ) + _, num_predictions, low_res_size, _ = low_res_masks.shape + + if output_w > 0 and output_h > 0: + output_masks = F.interpolate( + low_res_masks, (output_h, output_w), mode="bicubic" + ) + output_masks = torch.reshape( + output_masks, + (batch_size, max_num_queries, num_predictions, output_h, output_w), + ) + else: + output_masks = torch.reshape( + low_res_masks, + ( + batch_size, + max_num_queries, + num_predictions, + low_res_size, + low_res_size, + ), + ) + iou_predictions = torch.reshape( + iou_predictions, (batch_size, max_num_queries, num_predictions) + ) + return output_masks, iou_predictions + + def get_rescaled_pts(self, batched_points: torch.Tensor, input_h: int, input_w: int): + return torch.stack( + [ + torch.where( + batched_points[..., 0] >= 0, + batched_points[..., 0] * self.image_encoder.img_size / input_w, + -1.0, + ), + torch.where( + batched_points[..., 1] >= 0, + batched_points[..., 1] * self.image_encoder.img_size / input_h, + -1.0, + ), + ], + dim=-1, + ) + + @torch.jit.export + def get_image_embeddings(self, batched_images) -> torch.Tensor: + """ + Predicts masks end-to-end from provided images and prompts. + If prompts are not known in advance, using SamPredictor is + recommended over calling the model directly. + + Arguments: + batched_images: A tensor of shape [B, 3, H, W] + Returns: + List of image embeddings each of of shape [B, C(i), H(i), W(i)]. + The last embedding corresponds to the final layer. + """ + batched_images = self.preprocess(batched_images) + return self.image_encoder(batched_images) + + def forward( + self, + batched_images: torch.Tensor, + batched_points: torch.Tensor, + batched_point_labels: torch.Tensor, + scale_to_original_image_size: bool = True, + ) -> Tuple[torch.Tensor, torch.Tensor]: + """ + Predicts masks end-to-end from provided images and prompts. + If prompts are not known in advance, using SamPredictor is + recommended over calling the model directly. + + Arguments: + batched_images: A tensor of shape [B, 3, H, W] + batched_points: A tensor of shape [B, num_queries, max_num_pts, 2] + batched_point_labels: A tensor of shape [B, num_queries, max_num_pts] + + Returns: + A list tuples of two tensors where the ith element is by considering the first i+1 points. + low_res_mask: A tensor of shape [B, 256, 256] of predicted masks + iou_predictions: A tensor of shape [B, max_num_queries] of estimated IOU scores + """ + batch_size, _, input_h, input_w = batched_images.shape + image_embeddings = self.get_image_embeddings(batched_images) + return self.predict_masks( + image_embeddings, + batched_points, + batched_point_labels, + multimask_output=True, + input_h=input_h, + input_w=input_w, + output_h=input_h if scale_to_original_image_size else -1, + output_w=input_w if scale_to_original_image_size else -1, + ) + + def preprocess(self, x: torch.Tensor) -> torch.Tensor: + """Normalize pixel values and pad to a square input.""" + if ( + x.shape[2] != self.image_encoder.img_size + or x.shape[3] != self.image_encoder.img_size + ): + x = F.interpolate( + x, + (self.image_encoder.img_size, self.image_encoder.img_size), + mode="bilinear", + ) + return (x - self.pixel_mean) / self.pixel_std + + +def build_efficient_sam(encoder_patch_embed_dim, encoder_num_heads, checkpoint=None): + img_size = 1024 + encoder_patch_size = 16 + encoder_depth = 12 + encoder_mlp_ratio = 4.0 + encoder_neck_dims = [256, 256] + decoder_max_num_input_points = 6 + decoder_transformer_depth = 2 + decoder_transformer_mlp_dim = 2048 + decoder_num_heads = 8 + decoder_upscaling_layer_dims = [64, 32] + num_multimask_outputs = 3 + iou_head_depth = 3 + iou_head_hidden_dim = 256 + activation = "gelu" + normalization_type = "layer_norm" + normalize_before_activation = False + + assert activation == "relu" or activation == "gelu" + if activation == "relu": + activation_fn = nn.ReLU + else: + activation_fn = nn.GELU + + image_encoder = ImageEncoderViT( + img_size=img_size, + patch_size=encoder_patch_size, + in_chans=3, + patch_embed_dim=encoder_patch_embed_dim, + normalization_type=normalization_type, + depth=encoder_depth, + num_heads=encoder_num_heads, + mlp_ratio=encoder_mlp_ratio, + neck_dims=encoder_neck_dims, + act_layer=activation_fn, + ) + + image_embedding_size = image_encoder.image_embedding_size + encoder_transformer_output_dim = image_encoder.transformer_output_dim + + sam = EfficientSam( + image_encoder=image_encoder, + prompt_encoder=PromptEncoder( + embed_dim=encoder_transformer_output_dim, + image_embedding_size=(image_embedding_size, image_embedding_size), + input_image_size=(img_size, img_size), + ), + decoder_max_num_input_points=decoder_max_num_input_points, + mask_decoder=MaskDecoder( + transformer_dim=encoder_transformer_output_dim, + transformer=TwoWayTransformer( + depth=decoder_transformer_depth, + embedding_dim=encoder_transformer_output_dim, + num_heads=decoder_num_heads, + mlp_dim=decoder_transformer_mlp_dim, + activation=activation_fn, + normalize_before_activation=normalize_before_activation, + ), + num_multimask_outputs=num_multimask_outputs, + activation=activation_fn, + normalization_type=normalization_type, + normalize_before_activation=normalize_before_activation, + iou_head_depth=iou_head_depth - 1, + iou_head_hidden_dim=iou_head_hidden_dim, + upscaling_layer_dims=decoder_upscaling_layer_dims, + ), + pixel_mean=[0.485, 0.456, 0.406], + pixel_std=[0.229, 0.224, 0.225], + ) + if checkpoint is not None: + with open(checkpoint, "rb") as f: + state_dict = torch.load(f, map_location="cpu") + sam.load_state_dict(state_dict["model"]) + return sam diff --git a/py/evf_sam/model/EfficientSAM/efficient_sam/efficient_sam_decoder.py b/py/evf_sam/model/EfficientSAM/efficient_sam/efficient_sam_decoder.py new file mode 100644 index 0000000..909605d --- /dev/null +++ b/py/evf_sam/model/EfficientSAM/efficient_sam/efficient_sam_decoder.py @@ -0,0 +1,318 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +from typing import List, Tuple, Type + +import numpy as np +import torch +import torch.nn as nn +import torch.nn.functional as F + +from .mlp import MLPBlock + + +class PromptEncoder(nn.Module): + def __init__( + self, + embed_dim: int, + image_embedding_size: Tuple[int, int], + input_image_size: Tuple[int, int], + ) -> None: + """ + Encodes prompts for input to SAM's mask decoder. + + Arguments: + embed_dim (int): The prompts' embedding dimension + image_embedding_size (tuple(int, int)): The spatial size of the + image embedding, as (H, W). + input_image_size (int): The padded size of the image as input + to the image encoder, as (H, W). + """ + super().__init__() + self.embed_dim = embed_dim + self.input_image_size = input_image_size + self.image_embedding_size = image_embedding_size + self.pe_layer = PositionEmbeddingRandom(embed_dim // 2) + self.invalid_points = nn.Embedding(1, embed_dim) + self.point_embeddings = nn.Embedding(1, embed_dim) + self.bbox_top_left_embeddings = nn.Embedding(1, embed_dim) + self.bbox_bottom_right_embeddings = nn.Embedding(1, embed_dim) + + def get_dense_pe(self) -> torch.Tensor: + """ + Returns the positional encoding used to encode point prompts, + applied to a dense set of points the shape of the image encoding. + + Returns: + torch.Tensor: Positional encoding with shape + 1x(embed_dim)x(embedding_h)x(embedding_w) + """ + return self.pe_layer(self.image_embedding_size).unsqueeze(0) + + def _embed_points( + self, + points: torch.Tensor, + labels: torch.Tensor, + ) -> torch.Tensor: + """Embeds point prompts.""" + + points = points + 0.5 # Shift to center of pixel + point_embedding = self.pe_layer.forward_with_coords( + points, self.input_image_size + ) + invalid_label_ids = torch.eq(labels, -1)[:,:,None] + point_label_ids = torch.eq(labels, 1)[:,:,None] + topleft_label_ids = torch.eq(labels, 2)[:,:,None] + bottomright_label_ids = torch.eq(labels, 3)[:,:,None] + point_embedding = point_embedding + self.invalid_points.weight[:,None,:] * invalid_label_ids + point_embedding = point_embedding + self.point_embeddings.weight[:,None,:] * point_label_ids + point_embedding = point_embedding + self.bbox_top_left_embeddings.weight[:,None,:] * topleft_label_ids + point_embedding = point_embedding + self.bbox_bottom_right_embeddings.weight[:,None,:] * bottomright_label_ids + return point_embedding + + def forward( + self, + coords, + labels, + ) -> torch.Tensor: + """ + Embeds different types of prompts, returning both sparse and dense + embeddings. + + Arguments: + points: A tensor of shape [B, 2] + labels: An integer tensor of shape [B] where each element is 1,2 or 3. + + Returns: + torch.Tensor: sparse embeddings for the points and boxes, with shape + BxNx(embed_dim), where N is determined by the number of input points + and boxes. + """ + return self._embed_points(coords, labels) + + +class PositionEmbeddingRandom(nn.Module): + """ + Positional encoding using random spatial frequencies. + """ + + def __init__(self, num_pos_feats: int) -> None: + super().__init__() + self.register_buffer( + "positional_encoding_gaussian_matrix", torch.randn((2, num_pos_feats)) + ) + + def _pe_encoding(self, coords: torch.Tensor) -> torch.Tensor: + """Positionally encode points that are normalized to [0,1].""" + # assuming coords are in [0, 1]^2 square and have d_1 x ... x d_n x 2 shape + coords = 2 * coords - 1 + coords = coords @ self.positional_encoding_gaussian_matrix + coords = 2 * np.pi * coords + # outputs d_1 x ... x d_n x C shape + return torch.cat([torch.sin(coords), torch.cos(coords)], dim=-1) + + def forward(self, size: Tuple[int, int]) -> torch.Tensor: + """Generate positional encoding for a grid of the specified size.""" + h, w = size + device = self.positional_encoding_gaussian_matrix.device + grid = torch.ones([h, w], device=device, dtype=self.positional_encoding_gaussian_matrix.dtype) + y_embed = grid.cumsum(dim=0) - 0.5 + x_embed = grid.cumsum(dim=1) - 0.5 + y_embed = y_embed / h + x_embed = x_embed / w + + pe = self._pe_encoding(torch.stack([x_embed, y_embed], dim=-1)) + return pe.permute(2, 0, 1) # C x H x W + + def forward_with_coords( + self, coords_input: torch.Tensor, image_size: Tuple[int, int] + ) -> torch.Tensor: + """Positionally encode points that are not normalized to [0,1].""" + coords = coords_input.clone() + coords[:, :, 0] = coords[:, :, 0] / image_size[1] + coords[:, :, 1] = coords[:, :, 1] / image_size[0] + # remove to(float) here, don't know why original implementation add this + return self._pe_encoding(coords) # B x N x C + + +class MaskDecoder(nn.Module): + def __init__( + self, + *, + transformer_dim: int, + transformer: nn.Module, + num_multimask_outputs: int, + activation: Type[nn.Module], + normalization_type: str, + normalize_before_activation: bool, + iou_head_depth: int, + iou_head_hidden_dim: int, + upscaling_layer_dims: List[int], + ) -> None: + """ + Predicts masks given an image and prompt embeddings, using a + transformer architecture. + + Arguments: + transformer_dim (int): the channel dimension of the transformer + transformer (nn.Module): the transformer used to predict masks + num_multimask_outputs (int): the number of masks to predict + when disambiguating masks + activation (nn.Module): the type of activation to use when + upscaling masks + iou_head_depth (int): the depth of the MLP used to predict + mask quality + iou_head_hidden_dim (int): the hidden dimension of the MLP + used to predict mask quality + """ + super().__init__() + self.transformer_dim = transformer_dim + self.transformer = transformer + + self.num_multimask_outputs = num_multimask_outputs + + self.iou_token = nn.Embedding(1, transformer_dim) + if num_multimask_outputs > 1: + self.num_mask_tokens = num_multimask_outputs + 1 + else: + self.num_mask_tokens = 1 + self.mask_tokens = nn.Embedding(self.num_mask_tokens, transformer_dim) + output_dim_after_upscaling = transformer_dim + + self.final_output_upscaling_layers = nn.ModuleList([]) + for idx, layer_dims in enumerate(upscaling_layer_dims): + self.final_output_upscaling_layers.append( + nn.Sequential( + nn.ConvTranspose2d( + output_dim_after_upscaling, + layer_dims, + kernel_size=2, + stride=2, + ), + nn.GroupNorm(1, layer_dims) + if idx < len(upscaling_layer_dims) - 1 + else nn.Identity(), + activation(), + ) + ) + output_dim_after_upscaling = layer_dims + + self.output_hypernetworks_mlps = nn.ModuleList( + [ + MLPBlock( + input_dim=transformer_dim, + hidden_dim=transformer_dim, + output_dim=output_dim_after_upscaling, + num_layers=2, + act=activation, + ) + for i in range(self.num_mask_tokens) + ] + ) + + self.iou_prediction_head = MLPBlock( + input_dim=transformer_dim, + hidden_dim=iou_head_hidden_dim, + output_dim=self.num_mask_tokens, + num_layers=iou_head_depth, + act=activation, + ) + + def forward( + self, + image_embeddings: torch.Tensor, + image_pe: torch.Tensor, + sparse_prompt_embeddings: torch.Tensor, + multimask_output: bool, + ) -> Tuple[torch.Tensor, torch.Tensor]: + """ + Predict masks given image and prompt embeddings. + + Arguments: + image_embeddings: A tensor of shape [B, C, H, W] or [B*max_num_queries, C, H, W] + image_pe (torch.Tensor): positional encoding with the shape of image_embeddings (the batch dimension is broadcastable). + sparse_prompt_embeddings (torch.Tensor): the embeddings of the points and boxes + multimask_output (bool): Whether to return multiple masks or a single + mask. + + Returns: + torch.Tensor: batched predicted masks + torch.Tensor: batched predictions of mask quality + """ + + ( + batch_size, + max_num_queries, + sparse_embed_dim_1, + sparse_embed_dim_2, + ) = sparse_prompt_embeddings.shape + + ( + _, + image_embed_dim_c, + image_embed_dim_h, + image_embed_dim_w, + ) = image_embeddings.shape + + # Tile the image embedding for all queries. + image_embeddings_tiled = torch.tile( + image_embeddings[:, None, :, :, :], [1, max_num_queries, 1, 1, 1] + ).view( + batch_size * max_num_queries, + image_embed_dim_c, + image_embed_dim_h, + image_embed_dim_w, + ) + sparse_prompt_embeddings = sparse_prompt_embeddings.reshape( + batch_size * max_num_queries, sparse_embed_dim_1, sparse_embed_dim_2 + ) + masks, iou_pred = self.predict_masks( + image_embeddings=image_embeddings_tiled, + image_pe=image_pe, + sparse_prompt_embeddings=sparse_prompt_embeddings, + ) + + if multimask_output and self.num_multimask_outputs > 1: + return masks[:, 1:, :], iou_pred[:, 1:] + else: + return masks[:, :1, :], iou_pred[:, :1] + + def predict_masks( + self, + image_embeddings: torch.Tensor, + image_pe: torch.Tensor, + sparse_prompt_embeddings: torch.Tensor, + ) -> Tuple[torch.Tensor, torch.Tensor]: + """Predicts masks. See 'forward' for more details.""" + # Concatenate output tokens + output_tokens = torch.cat( + [self.iou_token.weight, self.mask_tokens.weight], dim=0 + ) + output_tokens = output_tokens.unsqueeze(0).expand( + sparse_prompt_embeddings.size(0), -1, -1 + ) + tokens = torch.cat((output_tokens, sparse_prompt_embeddings), dim=1) + # Expand per-image data in batch direction to be per-mask + pos_src = torch.repeat_interleave(image_pe, tokens.shape[0], dim=0) + b, c, h, w = image_embeddings.shape + hs, src = self.transformer(image_embeddings, pos_src, tokens) + iou_token_out = hs[:, 0, :] + mask_tokens_out = hs[:, 1 : (1 + self.num_mask_tokens), :] + + # Upscale mask embeddings and predict masks using the mask tokens + upscaled_embedding = src.transpose(1, 2).view(b, c, h, w) + + for upscaling_layer in self.final_output_upscaling_layers: + upscaled_embedding = upscaling_layer(upscaled_embedding) + hyper_in_list: List[torch.Tensor] = [] + for i, output_hypernetworks_mlp in enumerate(self.output_hypernetworks_mlps): + hyper_in_list.append(output_hypernetworks_mlp(mask_tokens_out[:, i, :])) + hyper_in = torch.stack(hyper_in_list, dim=1) + b, c, h, w = upscaled_embedding.shape + masks = (hyper_in @ upscaled_embedding.view(b, c, h * w)).view(b, -1, h, w) + # Generate mask quality predictions + iou_pred = self.iou_prediction_head(iou_token_out) + return masks, iou_pred diff --git a/py/evf_sam/model/EfficientSAM/efficient_sam/efficient_sam_encoder.py b/py/evf_sam/model/EfficientSAM/efficient_sam/efficient_sam_encoder.py new file mode 100644 index 0000000..73fd7ac --- /dev/null +++ b/py/evf_sam/model/EfficientSAM/efficient_sam/efficient_sam_encoder.py @@ -0,0 +1,257 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import math +from typing import List, Optional, Tuple, Type + +import torch +import torch.nn as nn +import torch.nn.functional as F + + +class LayerNorm2d(nn.Module): + def __init__(self, num_channels: int, eps: float = 1e-6) -> None: + super().__init__() + self.weight = nn.Parameter(torch.ones(num_channels)) + self.bias = nn.Parameter(torch.zeros(num_channels)) + self.eps = eps + + def forward(self, x: torch.Tensor) -> torch.Tensor: + u = x.mean(1, keepdim=True) + s = (x - u).pow(2).mean(1, keepdim=True) + x = (x - u) / torch.sqrt(s + self.eps) + x = self.weight[:, None, None] * x + self.bias[:, None, None] + return x + + +class PatchEmbed(nn.Module): + """2D Image to Patch Embedding""" + + def __init__( + self, + img_size, + patch_size, + in_chans, + embed_dim, + ): + super().__init__() + self.proj = nn.Conv2d( + in_chans, + embed_dim, + kernel_size=(patch_size, patch_size), + stride=(patch_size, patch_size), + bias=True, + ) + + def forward(self, x): + B, C, H, W = x.shape + x = self.proj(x) + return x + + +class Attention(nn.Module): + def __init__( + self, + dim, + num_heads, + qkv_bias, + qk_scale=None, + ): + super().__init__() + self.num_heads = num_heads + head_dim = dim // num_heads + self.scale = qk_scale or head_dim**-0.5 + self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) + self.proj = nn.Linear(dim, dim) + + def forward(self, x): + B, N, C = x.shape + qkv = ( + self.qkv(x) + .reshape(B, N, 3, self.num_heads, C // self.num_heads) + .permute(2, 0, 3, 1, 4) + ) + q, k, v = ( + qkv[0], + qkv[1], + qkv[2], + ) + attn = (q @ k.transpose(-2, -1)) * self.scale + attn = attn.softmax(dim=-1) + x = (attn @ v).transpose(1, 2).reshape(B, N, C) + x = self.proj(x) + return x + + +class Mlp(nn.Module): + def __init__( + self, + in_features, + hidden_features=None, + out_features=None, + act_layer=nn.GELU, + ): + super().__init__() + out_features = out_features or in_features + hidden_features = hidden_features or in_features + self.fc1 = nn.Linear(in_features, hidden_features) + self.act = act_layer() + self.fc2 = nn.Linear(hidden_features, out_features) + + def forward(self, x): + x = self.fc1(x) + x = self.act(x) + x = self.fc2(x) + return x + + +class Block(nn.Module): + def __init__( + self, + dim, + num_heads, + mlp_ratio=4.0, + qkv_bias=False, + qk_scale=None, + act_layer=nn.GELU, + ): + super().__init__() + self.norm1 = nn.LayerNorm(dim, eps=1e-6) + self.attn = Attention( + dim, + num_heads=num_heads, + qkv_bias=qkv_bias, + qk_scale=qk_scale, + ) + self.norm2 = nn.LayerNorm(dim, eps=1e-6) + mlp_hidden_dim = int(dim * mlp_ratio) + self.mlp = Mlp( + in_features=dim, + hidden_features=mlp_hidden_dim, + act_layer=act_layer, + ) + + def forward(self, x): + x = x + self.attn(self.norm1(x)) + x = x + self.mlp(self.norm2(x)) + return x + + +@torch.jit.export +def get_abs_pos( + abs_pos: torch.Tensor, has_cls_token: bool, hw: List[int] +) -> torch.Tensor: + """ + Calculate absolute positional embeddings. If needed, resize embeddings and remove cls_token + dimension for the original embeddings. + Args: + abs_pos (Tensor): absolute positional embeddings with (1, num_position, C). + has_cls_token (bool): If true, has 1 embedding in abs_pos for cls token. + hw (Tuple): size of input image tokens. + + Returns: + Absolute positional embeddings after processing with shape (1, H, W, C) + """ + h = hw[0] + w = hw[1] + if has_cls_token: + abs_pos = abs_pos[:, 1:] + xy_num = abs_pos.shape[1] + size = int(math.sqrt(xy_num)) + assert size * size == xy_num + + if size != h or size != w: + new_abs_pos = F.interpolate( + abs_pos.reshape(1, size, size, -1).permute(0, 3, 1, 2), + size=(h, w), + mode="bicubic", + align_corners=False, + ) + return new_abs_pos.permute(0, 2, 3, 1) + else: + return abs_pos.reshape(1, h, w, -1) + + +# Image encoder for efficient SAM. +class ImageEncoderViT(nn.Module): + def __init__( + self, + img_size: int, + patch_size: int, + in_chans: int, + patch_embed_dim: int, + normalization_type: str, + depth: int, + num_heads: int, + mlp_ratio: float, + neck_dims: List[int], + act_layer: Type[nn.Module], + ) -> None: + """ + Args: + img_size (int): Input image size. + patch_size (int): Patch size. + in_chans (int): Number of input image channels. + patch_embed_dim (int): Patch embedding dimension. + depth (int): Depth of ViT. + num_heads (int): Number of attention heads in each ViT block. + mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. + act_layer (nn.Module): Activation layer. + """ + super().__init__() + + self.img_size = img_size + self.image_embedding_size = img_size // ((patch_size if patch_size > 0 else 1)) + self.transformer_output_dim = ([patch_embed_dim] + neck_dims)[-1] + self.pretrain_use_cls_token = True + pretrain_img_size = 224 + self.patch_embed = PatchEmbed(img_size, patch_size, in_chans, patch_embed_dim) + # Initialize absolute positional embedding with pretrain image size. + num_patches = (pretrain_img_size // patch_size) * ( + pretrain_img_size // patch_size + ) + num_positions = num_patches + 1 + self.pos_embed = nn.Parameter(torch.zeros(1, num_positions, patch_embed_dim)) + self.blocks = nn.ModuleList() + for i in range(depth): + vit_block = Block(patch_embed_dim, num_heads, mlp_ratio, True) + self.blocks.append(vit_block) + self.neck = nn.Sequential( + nn.Conv2d( + patch_embed_dim, + neck_dims[0], + kernel_size=1, + bias=False, + ), + LayerNorm2d(neck_dims[0]), + nn.Conv2d( + neck_dims[0], + neck_dims[0], + kernel_size=3, + padding=1, + bias=False, + ), + LayerNorm2d(neck_dims[0]), + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + assert ( + x.shape[2] == self.img_size and x.shape[3] == self.img_size + ), "input image size must match self.img_size" + x = self.patch_embed(x) + # B C H W -> B H W C + x = x.permute(0, 2, 3, 1) + x = x + get_abs_pos( + self.pos_embed, self.pretrain_use_cls_token, [x.shape[1], x.shape[2]] + ) + num_patches = x.shape[1] + assert x.shape[2] == num_patches + x = x.reshape(x.shape[0], num_patches * num_patches, x.shape[3]) + for blk in self.blocks: + x = blk(x) + x = x.reshape(x.shape[0], num_patches, num_patches, x.shape[2]) + x = self.neck(x.permute(0, 3, 1, 2)) + return x diff --git a/py/evf_sam/model/EfficientSAM/efficient_sam/mlp.py b/py/evf_sam/model/EfficientSAM/efficient_sam/mlp.py new file mode 100644 index 0000000..b3be8db --- /dev/null +++ b/py/evf_sam/model/EfficientSAM/efficient_sam/mlp.py @@ -0,0 +1,29 @@ +from typing import Type + +from torch import nn + + +# Lightly adapted from +# https://github.com/facebookresearch/MaskFormer/blob/main/mask_former/modeling/transformer/transformer_predictor.py # noqa +class MLPBlock(nn.Module): + def __init__( + self, + input_dim: int, + hidden_dim: int, + output_dim: int, + num_layers: int, + act: Type[nn.Module], + ) -> None: + super().__init__() + self.num_layers = num_layers + h = [hidden_dim] * (num_layers - 1) + self.layers = nn.ModuleList( + nn.Sequential(nn.Linear(n, k), act()) + for n, k in zip([input_dim] + h, [hidden_dim] * num_layers) + ) + self.fc = nn.Linear(hidden_dim, output_dim) + + def forward(self, x): + for layer in self.layers: + x = layer(x) + return self.fc(x) diff --git a/py/evf_sam/model/EfficientSAM/efficient_sam/two_way_transformer.py b/py/evf_sam/model/EfficientSAM/efficient_sam/two_way_transformer.py new file mode 100644 index 0000000..b06e528 --- /dev/null +++ b/py/evf_sam/model/EfficientSAM/efficient_sam/two_way_transformer.py @@ -0,0 +1,266 @@ +import math +from typing import Tuple, Type +import torch +from torch import nn, Tensor +from .mlp import MLPBlock + + + + +class TwoWayTransformer(nn.Module): + def __init__( + self, + depth: int, + embedding_dim: int, + num_heads: int, + mlp_dim: int, + activation: Type[nn.Module], + normalize_before_activation: bool, + attention_downsample_rate: int = 2, + ) -> None: + """ + A transformer decoder that attends to an input image using + queries whose positional embedding is supplied. + + Args: + depth (int): number of layers in the transformer + embedding_dim (int): the channel dimension for the input embeddings + num_heads (int): the number of heads for multihead attention. Must + divide embedding_dim + mlp_dim (int): the channel dimension internal to the MLP block + activation (nn.Module): the activation to use in the MLP block + """ + super().__init__() + self.depth = depth + self.embedding_dim = embedding_dim + self.num_heads = num_heads + self.mlp_dim = mlp_dim + self.layers = nn.ModuleList() + + for i in range(depth): + curr_layer = TwoWayAttentionBlock( + embedding_dim=embedding_dim, + num_heads=num_heads, + mlp_dim=mlp_dim, + activation=activation, + normalize_before_activation=normalize_before_activation, + attention_downsample_rate=attention_downsample_rate, + skip_first_layer_pe=(i == 0), + ) + self.layers.append(curr_layer) + + self.final_attn_token_to_image = AttentionForTwoWayAttentionBlock( + embedding_dim, + num_heads, + downsample_rate=attention_downsample_rate, + ) + self.norm_final_attn = nn.LayerNorm(embedding_dim) + + def forward( + self, + image_embedding: Tensor, + image_pe: Tensor, + point_embedding: Tensor, + ) -> Tuple[Tensor, Tensor]: + """ + Args: + image_embedding (torch.Tensor): image to attend to. Should be shape + B x embedding_dim x h x w for any h and w. + image_pe (torch.Tensor): the positional encoding to add to the image. Must + have the same shape as image_embedding. + point_embedding (torch.Tensor): the embedding to add to the query points. + Must have shape B x N_points x embedding_dim for any N_points. + + Returns: + torch.Tensor: the processed point_embedding + torch.Tensor: the processed image_embedding + """ + + # BxCxHxW -> BxHWxC == B x N_image_tokens x C + bs, c, h, w = image_embedding.shape + image_embedding = image_embedding.flatten(2).permute(0, 2, 1) + image_pe = image_pe.flatten(2).permute(0, 2, 1) + + # Prepare queries + queries = point_embedding + keys = image_embedding + + # Apply transformer blocks and final layernorm + for idx, layer in enumerate(self.layers): + queries, keys = layer( + queries=queries, + keys=keys, + query_pe=point_embedding, + key_pe=image_pe, + ) + + # Apply the final attention layer from the points to the image + q = queries + point_embedding + k = keys + image_pe + attn_out = self.final_attn_token_to_image(q=q, k=k, v=keys) + queries = queries + attn_out + queries = self.norm_final_attn(queries) + return queries, keys + + +class TwoWayAttentionBlock(nn.Module): + def __init__( + self, + embedding_dim: int, + num_heads: int, + mlp_dim: int, + activation: Type[nn.Module], + normalize_before_activation: bool, + attention_downsample_rate: int = 2, + skip_first_layer_pe: bool = False, + ) -> None: + """ + A transformer block with four layers: (1) self-attention of sparse + inputs, (2) cross attention of sparse inputs to dense inputs, (3) mlp + block on sparse inputs, and (4) cross attention of dense inputs to sparse + inputs. + + Arguments: + embedding_dim (int): the channel dimension of the embeddings + num_heads (int): the number of heads in the attention layers + mlp_dim (int): the hidden dimension of the mlp block + activation (nn.Module): the activation of the mlp block + skip_first_layer_pe (bool): skip the PE on the first layer + """ + super().__init__() + self.self_attn = AttentionForTwoWayAttentionBlock(embedding_dim, num_heads) + self.norm1 = nn.LayerNorm(embedding_dim) + + self.cross_attn_token_to_image = AttentionForTwoWayAttentionBlock( + embedding_dim, + num_heads, + downsample_rate=attention_downsample_rate, + ) + self.norm2 = nn.LayerNorm(embedding_dim) + + self.mlp = MLPBlock( + embedding_dim, + mlp_dim, + embedding_dim, + 1, + activation, + ) + + self.norm3 = nn.LayerNorm(embedding_dim) + + self.norm4 = nn.LayerNorm(embedding_dim) + self.cross_attn_image_to_token = AttentionForTwoWayAttentionBlock( + embedding_dim, + num_heads, + downsample_rate=attention_downsample_rate, + ) + + self.skip_first_layer_pe = skip_first_layer_pe + + def forward( + self, queries: Tensor, keys: Tensor, query_pe: Tensor, key_pe: Tensor + ) -> Tuple[Tensor, Tensor]: + # Self attention block + if not self.skip_first_layer_pe: + queries = queries + query_pe + attn_out = self.self_attn(q=queries, k=queries, v=queries) + queries = queries + attn_out + queries = self.norm1(queries) + + # Cross attention block, tokens attending to image embedding + q = queries + query_pe + k = keys + key_pe + attn_out = self.cross_attn_token_to_image(q=q, k=k, v=keys) + queries = queries + attn_out + queries = self.norm2(queries) + + # MLP block + mlp_out = self.mlp(queries) + queries = queries + mlp_out + queries = self.norm3(queries) + + # Cross attention block, image embedding attending to tokens + q = queries + query_pe + k = keys + key_pe + attn_out = self.cross_attn_image_to_token(q=k, k=q, v=queries) + keys = keys + attn_out + keys = self.norm4(keys) + + return queries, keys + + +class AttentionForTwoWayAttentionBlock(nn.Module): + """ + An attention layer that allows for downscaling the size of the embedding + after projection to queries, keys, and values. + """ + + def __init__( + self, + embedding_dim: int, + num_heads: int, + downsample_rate: int = 1, + ) -> None: + super().__init__() + self.embedding_dim = embedding_dim + self.internal_dim = embedding_dim // downsample_rate + self.num_heads = num_heads + assert ( + self.internal_dim % num_heads == 0 + ), "num_heads must divide embedding_dim." + self.c_per_head = self.internal_dim / num_heads + self.inv_sqrt_c_per_head = 1.0 / math.sqrt(self.c_per_head) + + self.q_proj = nn.Linear(embedding_dim, self.internal_dim) + self.k_proj = nn.Linear(embedding_dim, self.internal_dim) + self.v_proj = nn.Linear(embedding_dim, self.internal_dim) + self.out_proj = nn.Linear(self.internal_dim, embedding_dim) + self._reset_parameters() + + def _reset_parameters(self) -> None: + # The fan_out is incorrect, but matches pytorch's initialization + # for which qkv is a single 3*embedding_dim x embedding_dim matrix + fan_in = self.embedding_dim + fan_out = 3 * self.internal_dim + # Xavier uniform with our custom fan_out + bnd = math.sqrt(6 / (fan_in + fan_out)) + nn.init.uniform_(self.q_proj.weight, -bnd, bnd) + nn.init.uniform_(self.k_proj.weight, -bnd, bnd) + nn.init.uniform_(self.v_proj.weight, -bnd, bnd) + # out_proj.weight is left with default initialization, like pytorch attention + nn.init.zeros_(self.q_proj.bias) + nn.init.zeros_(self.k_proj.bias) + nn.init.zeros_(self.v_proj.bias) + nn.init.zeros_(self.out_proj.bias) + + def _separate_heads(self, x: Tensor, num_heads: int) -> Tensor: + b, n, c = x.shape + x = x.reshape(b, n, num_heads, c // num_heads) + return x.transpose(1, 2) # B x N_heads x N_tokens x C_per_head + + def _recombine_heads(self, x: Tensor) -> Tensor: + b, n_heads, n_tokens, c_per_head = x.shape + x = x.transpose(1, 2) + return x.reshape(b, n_tokens, n_heads * c_per_head) # B x N_tokens x C + + def forward(self, q: Tensor, k: Tensor, v: Tensor) -> Tensor: + # Input projections + q = self.q_proj(q) + k = self.k_proj(k) + v = self.v_proj(v) + + # Separate into heads + q = self._separate_heads(q, self.num_heads) + k = self._separate_heads(k, self.num_heads) + v = self._separate_heads(v, self.num_heads) + + # Attention + _, _, _, c_per_head = q.shape + attn = q @ k.permute(0, 1, 3, 2) # B x N_heads x N_tokens x N_tokens + attn = attn * self.inv_sqrt_c_per_head + attn = torch.softmax(attn, dim=-1) + # Get output + out = attn @ v + out = self._recombine_heads(out) + out = self.out_proj(out) + return out diff --git a/py/evf_sam/model/__init__.py b/py/evf_sam/model/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/py/evf_sam/model/configuration_evf.py b/py/evf_sam/model/configuration_evf.py new file mode 100644 index 0000000..fc1383f --- /dev/null +++ b/py/evf_sam/model/configuration_evf.py @@ -0,0 +1,113 @@ +# coding=utf-8 +# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved. +# +# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX +# and OPT implementations in this library. It has been modified from its +# original forms to accommodate minor architectural differences compared +# to GPT-NeoX and OPT used by the Meta AI team that trained the model. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" Evf model configuration""" + +from transformers.configuration_utils import PretrainedConfig +from transformers.utils import logging + +logger = logging.get_logger(__name__) + +EVF_PRETRAINED_CONFIG_ARCHIVE_MAP = {} + + +class EvfConfig(PretrainedConfig): + r""" + This is the configuration class to store the configuration of a [`EvfSam`]. + + Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the + documentation from [`PretrainedConfig`] for more information. + + Args: + hidden_size (`int`, *optional*, defaults to 4096): + Dimension of the hidden representations. + pretraining_tp (`int`, *optional*, defaults to `1`): + Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this + document](https://huggingface.co/docs/transformers/parallelism) to understand more about it. This value is + necessary to ensure exact reproducibility of the pretraining results. Please refer to [this + issue](https://github.com/pytorch/pytorch/issues/76232). + rope_scaling (`Dict`, *optional*): + Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports three scaling + strategies: linear and dynamic. Their scaling factor must be an float greater than 1. The expected format + is `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update + `max_position_embeddings` to the expected new maximum. See the following thread for more information on how + these scaling strategies behave: + https://www.reddit.com/r/LocalLLaMA/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This is an + experimental feature, subject to breaking API changes in future versions. + + Example: + + ```python + + >>> configuration = EvfConfig() + >>> model = EvfSam(configuration) + + >>> # Accessing the model configuration + >>> configuration = model.config + ```""" + model_type = "evf" + keys_to_ignore_at_inference = ["past_key_values"] + + def __init__( + self, + hidden_size=768, + pad_token_id=1, + bos_token_id=0, + eos_token_id=2, + pretraining_tp=1, + tie_word_embeddings=False, + rope_scaling=None, + out_dim=256, + **kwargs, + ): + self.hidden_size = hidden_size + self.out_dim = out_dim + + # self.pretraining_tp = pretraining_tp + # self.rope_scaling = rope_scaling + # self._rope_scaling_validation() + + super().__init__( + pad_token_id=pad_token_id, + bos_token_id=bos_token_id, + eos_token_id=eos_token_id, + tie_word_embeddings=tie_word_embeddings, + **kwargs, + ) + + def _rope_scaling_validation(self): + """ + Validate the `rope_scaling` configuration. + """ + if self.rope_scaling is None: + return + + if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2: + raise ValueError( + "`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, " + f"got {self.rope_scaling}" + ) + rope_scaling_type = self.rope_scaling.get("type", None) + rope_scaling_factor = self.rope_scaling.get("factor", None) + if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]: + raise ValueError( + f"`rope_scaling`'s name field must be one of ['linear', 'dynamic'], got {rope_scaling_type}" + ) + if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0: + raise ValueError(f"`rope_scaling`'s factor field must be an float > 1, got {rope_scaling_factor}") diff --git a/py/evf_sam/model/evf_effisam.py b/py/evf_sam/model/evf_effisam.py new file mode 100644 index 0000000..9820624 --- /dev/null +++ b/py/evf_sam/model/evf_effisam.py @@ -0,0 +1,313 @@ +from typing import List, Tuple + +import torch +import torch.nn as nn +import torch.nn.functional as F +from transformers import PreTrainedModel, AutoConfig, AutoModelForCausalLM +from .EfficientSAM.efficient_sam.build_efficient_sam import build_efficient_sam_vits, build_efficient_sam_vitt +from .unilm.beit3.modeling_utils import BEiT3Wrapper, _get_base_config, _get_large_config +from .configuration_evf import EvfConfig + + +def dice_loss( + inputs: torch.Tensor, + targets: torch.Tensor, + num_masks: float, + scale=1000, # 100000.0, + eps=1e-6, +): + """ + Compute the DICE loss, similar to generalized IOU for masks + Args: + inputs: A float tensor of arbitrary shape. + The predictions for each example. + targets: A float tensor with the same shape as inputs. Stores the binary + classification label for each element in inputs + (0 for the negative class and 1 for the positive class). + """ + inputs = inputs.sigmoid() + inputs = inputs.flatten(1, 2) + targets = targets.flatten(1, 2) + numerator = 2 * (inputs / scale * targets).sum(-1) + denominator = (inputs / scale).sum(-1) + (targets / scale).sum(-1) + loss = 1 - (numerator + eps) / (denominator + eps) + loss = loss.sum() / (num_masks + 1e-8) + return loss + + +def sigmoid_ce_loss( + inputs: torch.Tensor, + targets: torch.Tensor, + num_masks: float, +): + """ + Args: + inputs: A float tensor of arbitrary shape. + The predictions for each example. + targets: A float tensor with the same shape as inputs. Stores the binary + classification label for each element in inputs + (0 for the negative class and 1 for the positive class). + Returns: + Loss tensor + """ + loss = F.binary_cross_entropy_with_logits(inputs, targets, reduction="none") + loss = loss.flatten(1, 2).mean(1).sum() / (num_masks + 1e-8) + return loss + + + +class EvfEffiSamModel(PreTrainedModel): + config_class = EvfConfig + def __init__( + self, + config, + **kwargs + ): + super(EvfEffiSamModel, self).__init__(config) + + self.config = config + self.vision_pretrained = kwargs.get("vision_pretrained", None) + self.encoder_pretrained = kwargs.get("encoder_pretrained", None) + self.dice_loss_weight = kwargs.get("dice_loss_weight", None) + self.bce_loss_weight = kwargs.get("bce_loss_weight", None) + self.train_mask_decoder = kwargs.get("train_mask_decoder", False) + self.initialize_evf_modules(config) + + + def initialize_evf_modules(self, config): + # EffiSAM + if config.sam_scale=="tiny": + self.visual_model = build_efficient_sam_vitt(self.vision_pretrained) + elif config.sam_scale=="small": + # vits scale, or without pretrained weight (self.vision_pretrained=None) + self.visual_model = build_efficient_sam_vits(self.vision_pretrained) + else: + raise NotImplementedError + + for param in self.visual_model.parameters(): + param.requires_grad = False + if self.train_mask_decoder: + self.visual_model.mask_decoder.train() + for param in self.visual_model.mask_decoder.parameters(): + param.requires_grad = True + + # beit-3 + if self.config.mm_extractor_scale == "base": + beit_config = _get_base_config() + elif self.config.mm_extractor_scale == "large": + beit_config = _get_large_config() + else: + raise AttributeError(f"model config should contain key 'mm_extractor_scale', with value 'base' or 'large'.") + + self.mm_extractor = BEiT3Wrapper(beit_config) + if self.encoder_pretrained is not None: + beit_state_dict = torch.load(self.encoder_pretrained)["model"] + self.mm_extractor.load_state_dict( + beit_state_dict, + strict=False + ) + + for param in self.mm_extractor.parameters(): + param.requires_grad = True + + # Projection layer + in_dim = config.hidden_size + assert in_dim==beit_config.encoder_embed_dim, \ + f"projection layer dim {in_dim} mismatch with mm_extractor dim {beit_config.encoder_embed_dim}" + out_dim = config.out_dim + text_fc = [ + nn.Linear(in_dim, in_dim), + nn.ReLU(), + nn.Linear(in_dim, out_dim) + ] + self.text_hidden_fcs = nn.ModuleList([nn.Sequential(*text_fc)]) + self.text_hidden_fcs.train() + for param in self.text_hidden_fcs.parameters(): + param.requires_grad = True + + def get_visual_embs(self, pixel_values: torch.Tensor): + with torch.no_grad(): + image_embeddings_list = [] + for i in range(pixel_values.shape[0]): + torch.cuda.empty_cache() + image_embeddings = self.visual_model.image_encoder( + pixel_values[i].unsqueeze(0) + ) + image_embeddings_list.append(image_embeddings) + torch.cuda.empty_cache() + image_embeddings = torch.cat(image_embeddings_list, 0) + return image_embeddings + + def forward( + self, + images: torch.Tensor, + images_evf: torch.Tensor, + input_ids: torch.Tensor, + attention_masks: torch.Tensor, + offset: torch.Tensor, + masks_list: List[torch.Tensor], + label_list: List[torch.Tensor], + resize_list: List[tuple], + inference: bool = False, + **kwargs, + ): + image_embeddings = self.get_visual_embs(images) + batch_size = image_embeddings.shape[0] + assert batch_size == len(offset) - 1 + + images_evf_list = [] + for i in range(len(offset) - 1): + start_i, end_i = offset[i], offset[i + 1] + images_evf_i = ( + images_evf[i] + .unsqueeze(0) + .expand(end_i - start_i, -1, -1, -1) + .contiguous() + ) + images_evf_list.append(images_evf_i) + images_evf = torch.cat(images_evf_list, dim=0) + + multimask_output = False + output = self.mm_extractor.beit3( + visual_tokens=images_evf, + textual_tokens=input_ids, + text_padding_position=~attention_masks + ) + + feat = output["encoder_out"][:, :1, ...] + + feat = self.text_hidden_fcs[0](feat) + feat = torch.split(feat, [offset[i+1] - offset[i] for i in range(len(offset)-1)]) + + pred_masks = [] + for i in range(len(feat)): + sparse_embeddings = feat[i].unsqueeze(0) + sparse_embeddings = sparse_embeddings.to(feat[i].dtype) + low_res_masks, iou_predictions = self.visual_model.mask_decoder( + image_embeddings=image_embeddings[i].unsqueeze(0), + image_pe=self.visual_model.prompt_encoder.get_dense_pe(), + sparse_prompt_embeddings=sparse_embeddings, + multimask_output=multimask_output, + ) + + if multimask_output: + sorted_ids = torch.argsort(iou_predictions, dim=-1, descending=True) + low_res_masks = torch.take_along_dim(low_res_masks, sorted_ids[..., None, None], dim=1) + + pred_mask = self.postprocess_masks( + low_res_masks[:, :1], + input_size=resize_list[i], + original_size=label_list[i].shape, + ) + pred_masks.append(pred_mask[:, 0]) + + gt_masks = masks_list + + if inference: + return { + "pred_masks": pred_masks, + "gt_masks": gt_masks, + } + + mask_bce_loss = 0 + mask_dice_loss = 0 + num_masks = 0 + for batch_idx in range(len(pred_masks)): + gt_mask = gt_masks[batch_idx] + pred_mask = pred_masks[batch_idx] + + assert ( + gt_mask.shape[0] == pred_mask.shape[0] + ), "gt_mask.shape: {}, pred_mask.shape: {}".format( + gt_mask.shape, pred_mask.shape + ) + mask_bce_loss += ( + sigmoid_ce_loss(pred_mask, gt_mask, num_masks=gt_mask.shape[0]) + * gt_mask.shape[0] + ) + mask_dice_loss += ( + dice_loss(pred_mask, gt_mask, num_masks=gt_mask.shape[0]) + * gt_mask.shape[0] + ) + num_masks += gt_mask.shape[0] + + mask_bce_loss = self.bce_loss_weight * mask_bce_loss / (num_masks + 1e-8) + mask_dice_loss = self.dice_loss_weight * mask_dice_loss / (num_masks + 1e-8) + mask_loss = mask_bce_loss + mask_dice_loss + + loss = mask_loss + + return { + "loss": loss, + "mask_bce_loss": mask_bce_loss, + "mask_dice_loss": mask_dice_loss, + "mask_loss": mask_loss, + } + + def postprocess_masks( + self, + masks: torch.Tensor, + input_size: Tuple[int, ...], + original_size: Tuple[int, ...], + ) -> torch.Tensor: + """ + pre-process of Effi-SAM is different from SAM, where there is no padding, + so cropping is not needed in post-process. + """ + + dtype = masks.dtype + + # masks = F.interpolate( + # masks.float(), + # (1024, 1024), + # mode="bilinear", + # align_corners=False, + # ) + # masks = masks.to(dtype) + # masks = masks[..., : input_size[0], : input_size[1]] + + masks = F.interpolate( + masks, original_size, mode="bilinear", align_corners=False + ) + masks = masks.to(dtype) + return masks + + def inference( + self, + images, + images_evf, + input_ids, + resize_list, + original_size_list, + multimask_output=False, + ): + with torch.no_grad(): + image_embeddings = self.visual_model.image_encoder(images) + + output = self.mm_extractor.beit3(visual_tokens=images_evf, textual_tokens=input_ids, text_padding_position=torch.zeros_like(input_ids)) + + feat = output["encoder_out"][:, :1, ...] + feat = self.text_hidden_fcs[0](feat) + sparse_embeddings = feat.unsqueeze(0) + sparse_embeddings = sparse_embeddings.to(feat.dtype) + low_res_masks, iou_predictions = self.visual_model.mask_decoder( + image_embeddings=image_embeddings, + image_pe=self.visual_model.prompt_encoder.get_dense_pe(), + sparse_prompt_embeddings=sparse_embeddings, + multimask_output=multimask_output, + ) + if multimask_output: + sorted_ids = torch.argsort(iou_predictions, dim=-1, descending=True) + low_res_masks = torch.take_along_dim(low_res_masks, sorted_ids[..., None, None], dim=1) + + pred_mask = self.postprocess_masks( + low_res_masks[:, :1], + input_size=resize_list[0], + original_size=original_size_list[0], + ) + + return pred_mask[:, 0] + + +AutoConfig.register("evf", EvfConfig) +AutoModelForCausalLM.register(EvfConfig, EvfEffiSamModel) diff --git a/py/evf_sam/model/evf_sam.py b/py/evf_sam/model/evf_sam.py new file mode 100644 index 0000000..a0ec88e --- /dev/null +++ b/py/evf_sam/model/evf_sam.py @@ -0,0 +1,303 @@ +from typing import List + +import torch +import torch.nn as nn +import torch.nn.functional as F +from transformers import PreTrainedModel, AutoConfig, AutoModelForCausalLM +from .segment_anything import build_sam_vit_h +from .unilm.beit3.modeling_utils import BEiT3Wrapper, _get_base_config, _get_large_config +from .configuration_evf import EvfConfig + +def dice_loss( + inputs: torch.Tensor, + targets: torch.Tensor, + num_masks: float, + scale=1000, # 100000.0, + eps=1e-6, +): + """ + Compute the DICE loss, similar to generalized IOU for masks + Args: + inputs: A float tensor of arbitrary shape. + The predictions for each example. + targets: A float tensor with the same shape as inputs. Stores the binary + classification label for each element in inputs + (0 for the negative class and 1 for the positive class). + """ + inputs = inputs.sigmoid() + inputs = inputs.flatten(1, 2) + targets = targets.flatten(1, 2) + numerator = 2 * (inputs / scale * targets).sum(-1) + denominator = (inputs / scale).sum(-1) + (targets / scale).sum(-1) + loss = 1 - (numerator + eps) / (denominator + eps) + loss = loss.sum() / (num_masks + 1e-8) + return loss + + +def sigmoid_ce_loss( + inputs: torch.Tensor, + targets: torch.Tensor, + num_masks: float, +): + """ + Args: + inputs: A float tensor of arbitrary shape. + The predictions for each example. + targets: A float tensor with the same shape as inputs. Stores the binary + classification label for each element in inputs + (0 for the negative class and 1 for the positive class). + Returns: + Loss tensor + """ + loss = F.binary_cross_entropy_with_logits(inputs, targets, reduction="none") + loss = loss.flatten(1, 2).mean(1).sum() / (num_masks + 1e-8) + return loss + + + +class EvfSamModel(PreTrainedModel): + config_class = EvfConfig + def __init__( + self, + config, + **kwargs + ): + super(EvfSamModel, self).__init__(config) + + self.config = config + self.vision_pretrained = kwargs.get("vision_pretrained", None) + self.encoder_pretrained = kwargs.get("encoder_pretrained", None) + self.dice_loss_weight = kwargs.get("dice_loss_weight", None) + self.bce_loss_weight = kwargs.get("bce_loss_weight", None) + self.train_mask_decoder = kwargs.get("train_mask_decoder", False) + self.train_prompt_encoder = kwargs.get("train_prompt_encoder", False) + self.initialize_evf_modules(config) + + + def initialize_evf_modules(self, config): + # SAM + if config.sam_scale=="huge": + self.visual_model = build_sam_vit_h(self.vision_pretrained) + else: + raise NotImplementedError + + for param in self.visual_model.parameters(): + param.requires_grad = False + if self.train_mask_decoder: + self.visual_model.mask_decoder.train() + for param in self.visual_model.mask_decoder.parameters(): + param.requires_grad = True + if self.train_prompt_encoder: + self.visual_model.prompt_encoder.no_mask_embed.requires_grad_(True) + + # beit-3 + if self.config.mm_extractor_scale == "base": + beit_config = _get_base_config() + elif self.config.mm_extractor_scale == "large": + beit_config = _get_large_config() + else: + raise AttributeError(f"model config should contain key 'mm_extractor_scale', with value 'base' or 'large'.") + + self.mm_extractor = BEiT3Wrapper(beit_config) + if self.encoder_pretrained is not None: + beit_state_dict = torch.load(self.encoder_pretrained)["model"] + self.mm_extractor.load_state_dict( + beit_state_dict, + strict=False + ) + + for param in self.mm_extractor.parameters(): + param.requires_grad = True + + # Projection layer + in_dim = config.hidden_size + assert in_dim==beit_config.encoder_embed_dim, \ + f"projection layer dim {in_dim} mismatch with mm_extractor dim {beit_config.encoder_embed_dim}" + out_dim = config.out_dim + text_fc = [ + nn.Linear(in_dim, in_dim), + nn.ReLU(), + nn.Linear(in_dim, out_dim) + ] + self.text_hidden_fcs = nn.ModuleList([nn.Sequential(*text_fc)]) + self.text_hidden_fcs.train() + for param in self.text_hidden_fcs.parameters(): + param.requires_grad = True + + def get_visual_embs(self, pixel_values: torch.FloatTensor): + with torch.no_grad(): + image_embeddings_list = [] + for i in range(pixel_values.shape[0]): + torch.cuda.empty_cache() + image_embeddings = self.visual_model.image_encoder( + pixel_values[i].unsqueeze(0) + ) + image_embeddings_list.append(image_embeddings) + torch.cuda.empty_cache() + image_embeddings = torch.cat(image_embeddings_list, 0) + return image_embeddings + + def forward( + self, + images: torch.FloatTensor, + images_evf: torch.FloatTensor, + input_ids: torch.LongTensor, + attention_masks: torch.LongTensor, + offset: torch.LongTensor, + masks_list: List[torch.FloatTensor], + label_list: List[torch.Tensor], + resize_list: List[tuple], + inference: bool = False, + **kwargs, + ): + image_embeddings = self.get_visual_embs(images) + batch_size = image_embeddings.shape[0] + assert batch_size == len(offset) - 1 + + images_evf_list = [] + for i in range(len(offset) - 1): + start_i, end_i = offset[i], offset[i + 1] + images_evf_i = ( + images_evf[i] + .unsqueeze(0) + .expand(end_i - start_i, -1, -1, -1) + .contiguous() + ) + images_evf_list.append(images_evf_i) + images_evf = torch.cat(images_evf_list, dim=0) + + multimask_output = False + output = self.mm_extractor.beit3( + visual_tokens=images_evf, + textual_tokens=input_ids, + text_padding_position=~attention_masks + ) + + feat = output["encoder_out"][:, :1, ...] + + feat = self.text_hidden_fcs[0](feat) + feat = torch.split(feat, [offset[i+1] - offset[i] for i in range(len(offset)-1)]) + + pred_masks = [] + for i in range(len(feat)): + ( + sparse_embeddings, + dense_embeddings, + ) = self.visual_model.prompt_encoder( + points=None, + boxes=None, + masks=None, + text_embeds=feat[i], + ) + sparse_embeddings = sparse_embeddings.to(feat[i].dtype) + low_res_masks, iou_predictions = self.visual_model.mask_decoder( + image_embeddings=image_embeddings[i].unsqueeze(0), + image_pe=self.visual_model.prompt_encoder.get_dense_pe(), + sparse_prompt_embeddings=sparse_embeddings, + dense_prompt_embeddings=dense_embeddings, + multimask_output=multimask_output, + ) + + if multimask_output: + sorted_ids = torch.argsort(iou_predictions, dim=-1, descending=True) + low_res_masks = torch.take_along_dim(low_res_masks, sorted_ids[..., None, None], dim=1)[:, :1] + + pred_mask = self.visual_model.postprocess_masks( + low_res_masks, + input_size=resize_list[i], + original_size=label_list[i].shape, + ) + pred_masks.append(pred_mask[:, 0]) + + gt_masks = masks_list + + if inference: + return { + "pred_masks": pred_masks, + "gt_masks": gt_masks, + } + + mask_bce_loss = 0 + mask_dice_loss = 0 + num_masks = 0 + for batch_idx in range(len(pred_masks)): + gt_mask = gt_masks[batch_idx] + pred_mask = pred_masks[batch_idx] + + assert ( + gt_mask.shape[0] == pred_mask.shape[0] + ), "gt_mask.shape: {}, pred_mask.shape: {}".format( + gt_mask.shape, pred_mask.shape + ) + mask_bce_loss += ( + sigmoid_ce_loss(pred_mask, gt_mask, num_masks=gt_mask.shape[0]) + * gt_mask.shape[0] + ) + mask_dice_loss += ( + dice_loss(pred_mask, gt_mask, num_masks=gt_mask.shape[0]) + * gt_mask.shape[0] + ) + num_masks += gt_mask.shape[0] + + mask_bce_loss = self.bce_loss_weight * mask_bce_loss / (num_masks + 1e-8) + mask_dice_loss = self.dice_loss_weight * mask_dice_loss / (num_masks + 1e-8) + mask_loss = mask_bce_loss + mask_dice_loss + + loss = mask_loss + + return { + "loss": loss, + "mask_bce_loss": mask_bce_loss, + "mask_dice_loss": mask_dice_loss, + "mask_loss": mask_loss, + } + + def inference( + self, + images, + images_evf, + input_ids, + resize_list, + original_size_list, + multimask_output=False, + ): + with torch.no_grad(): + image_embeddings = self.visual_model.image_encoder(images) + multimask_output = multimask_output + + output = self.mm_extractor.beit3(visual_tokens=images_evf, textual_tokens=input_ids, text_padding_position=torch.zeros_like(input_ids)) + + feat = output["encoder_out"][:, :1, ...] + feat = self.text_hidden_fcs[0](feat) + ( + sparse_embeddings, + dense_embeddings, + ) = self.visual_model.prompt_encoder( + points=None, + boxes=None, + masks=None, + text_embeds=feat, + ) + sparse_embeddings = sparse_embeddings.to(feat.dtype) + low_res_masks, iou_predictions = self.visual_model.mask_decoder( + image_embeddings=image_embeddings, + image_pe=self.visual_model.prompt_encoder.get_dense_pe(), + sparse_prompt_embeddings=sparse_embeddings, + dense_prompt_embeddings=dense_embeddings, + multimask_output=multimask_output, + ) + if multimask_output: + sorted_ids = torch.argsort(iou_predictions, dim=-1, descending=True) + low_res_masks = torch.take_along_dim(low_res_masks, sorted_ids[..., None, None], dim=1)[:, :1] + + pred_mask = self.visual_model.postprocess_masks( + low_res_masks, + input_size=resize_list[0], + original_size=original_size_list[0], + ) + + return pred_mask[:, 0] + + +AutoConfig.register("evf", EvfConfig) +AutoModelForCausalLM.register(EvfConfig, EvfSamModel) \ No newline at end of file diff --git a/py/evf_sam/model/evf_sam2.py b/py/evf_sam/model/evf_sam2.py new file mode 100644 index 0000000..93aa295 --- /dev/null +++ b/py/evf_sam/model/evf_sam2.py @@ -0,0 +1,341 @@ +from typing import List +import os +import torch +import torch.nn as nn +import torch.nn.functional as F +from transformers import PreTrainedModel, AutoConfig, AutoModelForCausalLM +from .segment_anything_2.sam2.build_sam import build_sam2 +from .unilm.beit3.modeling_utils import BEiT3Wrapper, _get_base_config, _get_large_config +from .configuration_evf import EvfConfig +from .segment_anything_2.sam2.utils.misc import load_video_frames +from collections import OrderedDict + + +def dice_loss( + inputs: torch.Tensor, + targets: torch.Tensor, + num_masks: float, + scale=1000, # 100000.0, + eps=1e-6, +): + """ + Compute the DICE loss, similar to generalized IOU for masks + Args: + inputs: A float tensor of arbitrary shape. + The predictions for each example. + targets: A float tensor with the same shape as inputs. Stores the binary + classification label for each element in inputs + (0 for the negative class and 1 for the positive class). + """ + inputs = inputs.sigmoid() + inputs = inputs.flatten(1, 2) + targets = targets.flatten(1, 2) + numerator = 2 * (inputs / scale * targets).sum(-1) + denominator = (inputs / scale).sum(-1) + (targets / scale).sum(-1) + loss = 1 - (numerator + eps) / (denominator + eps) + loss = loss.sum() / (num_masks + 1e-8) + return loss + + +def sigmoid_ce_loss( + inputs: torch.Tensor, + targets: torch.Tensor, + num_masks: float, +): + """ + Args: + inputs: A float tensor of arbitrary shape. + The predictions for each example. + targets: A float tensor with the same shape as inputs. Stores the binary + classification label for each element in inputs + (0 for the negative class and 1 for the positive class). + Returns: + Loss tensor + """ + loss = F.binary_cross_entropy_with_logits(inputs, targets, reduction="none") + loss = loss.flatten(1, 2).mean(1).sum() / (num_masks + 1e-8) + return loss + +class EvfSam2Model(PreTrainedModel): + config_class = EvfConfig + def __init__( + self, + config, + **kwargs + ): + super(EvfSam2Model, self).__init__(config) + + self.config = config + self.vision_pretrained = kwargs.get("vision_pretrained", None) + self.encoder_pretrained = kwargs.get("encoder_pretrained", None) + self.dice_loss_weight = kwargs.get("dice_loss_weight", None) + self.bce_loss_weight = kwargs.get("bce_loss_weight", None) + self.train_mask_decoder = kwargs.get("train_mask_decoder", False) + self.train_prompt_encoder = kwargs.get("train_prompt_encoder", False) + self.initialize_evf_modules(config) + self._bb_feat_sizes = [ + (256, 256), + (128, 128), + (64, 64), + ] + + def initialize_evf_modules(self, config): + # SAM + if config.sam_scale=="large": + self.visual_model = build_sam2("sam2_hiera_l.yaml", self.vision_pretrained, device=None) + elif config.sam_scale=="tiny": + self.visual_model = build_sam2("sam2_hiera_t.yaml", self.vision_pretrained, device=None) + else: + raise NotImplementedError + + for param in self.visual_model.parameters(): + param.requires_grad = False + if self.train_mask_decoder: + self.visual_model.sam_mask_decoder.train() + for param in self.visual_model.sam_mask_decoder.parameters(): + param.requires_grad = True + if self.train_prompt_encoder: + self.visual_model.sam_prompt_encoder.no_mask_embed.requires_grad_(True) + + # beit-3 + if self.config.mm_extractor_scale == "base": + beit_config = _get_base_config() + elif self.config.mm_extractor_scale == "large": + beit_config = _get_large_config() + else: + raise AttributeError(f"model config should contain key 'mm_extractor_scale', with value 'base' or 'large'.") + + self.mm_extractor = BEiT3Wrapper(beit_config) + if self.encoder_pretrained is not None: + beit_state_dict = torch.load(self.encoder_pretrained)["model"] + self.mm_extractor.load_state_dict( + beit_state_dict, + strict=False + ) + + for param in self.mm_extractor.parameters(): + param.requires_grad = True + + # Projection layer + in_dim = config.hidden_size + assert in_dim==beit_config.encoder_embed_dim, \ + f"projection layer dim {in_dim} mismatch with mm_extractor dim {beit_config.encoder_embed_dim}" + out_dim = config.out_dim + text_fc = [ + nn.Linear(in_dim, in_dim), + nn.ReLU(), + nn.Linear(in_dim, out_dim) + ] + self.text_hidden_fcs = nn.ModuleList([nn.Sequential(*text_fc)]) + self.text_hidden_fcs.train() + for param in self.text_hidden_fcs.parameters(): + param.requires_grad = True + + def postprocess_masks(self, masks: torch.Tensor, orig_hw) -> torch.Tensor: + """ + Perform PostProcessing on output masks. + """ + masks = masks.float() + masks = F.interpolate(masks, orig_hw, mode="bilinear", align_corners=False) + return masks + + def forward( + self, + images: torch.FloatTensor, + images_evf: torch.FloatTensor, + input_ids: torch.LongTensor, + attention_masks: torch.LongTensor, + offset: torch.LongTensor, + masks_list: List[torch.FloatTensor], + label_list: List[torch.Tensor], + resize_list: List[tuple], + inference: bool = False, + **kwargs, + ): + # image_embeddings = self.get_visual_embs(images) + backbone_out = self.visual_model.forward_image(images) + # dict_keys(['vision_features', 'vision_pos_enc', 'backbone_fpn']) + _, image_embeddings, _, _ = self.visual_model._prepare_backbone_features(backbone_out) + image_embeddings = [_.to(images.dtype) for _ in image_embeddings] + batch_size = images.shape[0] + if self.visual_model.directly_add_no_mem_embed: + image_embeddings[-1] = image_embeddings[-1] + self.visual_model.no_mem_embed + + feats = [ + feat.permute(1, 2, 0).view(batch_size, -1, *feat_size) + for feat, feat_size in zip(image_embeddings[::-1], self._bb_feat_sizes[::-1]) + ][::-1] + _features = {"image_embed": feats[-1], "high_res_feats": feats[:-1]} + + + assert batch_size == len(offset) - 1 + + images_evf_list = [] + for i in range(len(offset) - 1): + start_i, end_i = offset[i], offset[i + 1] + images_evf_i = ( + images_evf[i] + .unsqueeze(0) + .expand(end_i - start_i, -1, -1, -1) + .contiguous() + ) + images_evf_list.append(images_evf_i) + images_evf = torch.cat(images_evf_list, dim=0) + + multimask_output = False + output = self.mm_extractor.beit3( + visual_tokens=images_evf, + textual_tokens=input_ids, + text_padding_position=~attention_masks + ) + + feat = output["encoder_out"][:, :1, ...] + + feat = self.text_hidden_fcs[0](feat) + feat = torch.split(feat, [offset[i+1] - offset[i] for i in range(len(offset)-1)]) + + pred_masks = [] + + for i in range(len(feat)): + ( + sparse_embeddings, + dense_embeddings, + ) = self.visual_model.sam_prompt_encoder( + points=None, + boxes=None, + masks=None, + text_embeds=feat[i], + ) + sparse_embeddings = sparse_embeddings.to(feat[i].dtype) + high_res_features = [ + feat_level[i].unsqueeze(0) + for feat_level in _features["high_res_feats"] + ] + low_res_masks, iou_predictions, _, _ = self.visual_model.sam_mask_decoder( + image_embeddings=_features["image_embed"][i].unsqueeze(0), + image_pe=self.visual_model.sam_prompt_encoder.get_dense_pe(), + sparse_prompt_embeddings=sparse_embeddings, + dense_prompt_embeddings=dense_embeddings, + multimask_output=multimask_output, + repeat_image = True, + high_res_features=high_res_features, + ) + + if multimask_output: + sorted_ids = torch.argsort(iou_predictions, dim=-1, descending=True) + low_res_masks = torch.take_along_dim(low_res_masks, sorted_ids[..., None, None], dim=1)[:, :1] + + pred_mask = self.postprocess_masks( + low_res_masks, + orig_hw=label_list[i].shape, + ) + pred_masks.append(pred_mask[:, 0]) + + gt_masks = masks_list + + if inference: + return { + "pred_masks": pred_masks, + "gt_masks": gt_masks, + } + + mask_bce_loss = 0 + mask_dice_loss = 0 + num_masks = 0 + for batch_idx in range(len(pred_masks)): + gt_mask = gt_masks[batch_idx] + pred_mask = pred_masks[batch_idx] + + assert ( + gt_mask.shape[0] == pred_mask.shape[0] + ), "gt_mask.shape: {}, pred_mask.shape: {}".format( + gt_mask.shape, pred_mask.shape + ) + mask_bce_loss += ( + sigmoid_ce_loss(pred_mask, gt_mask, num_masks=gt_mask.shape[0]) + * gt_mask.shape[0] + ) + mask_dice_loss += ( + dice_loss(pred_mask, gt_mask, num_masks=gt_mask.shape[0]) + * gt_mask.shape[0] + ) + num_masks += gt_mask.shape[0] + + mask_bce_loss = self.bce_loss_weight * mask_bce_loss / (num_masks + 1e-8) + mask_dice_loss = self.dice_loss_weight * mask_dice_loss / (num_masks + 1e-8) + mask_loss = mask_bce_loss + mask_dice_loss + + loss = mask_loss + + return { + "loss": loss, + "mask_bce_loss": mask_bce_loss, + "mask_dice_loss": mask_dice_loss, + "mask_loss": mask_loss, + } + + def inference( + self, + images, + images_evf, + input_ids, + resize_list, + original_size_list, + multimask_output=False, + ): + with torch.no_grad(): + backbone_out = self.visual_model.forward_image(images) + # dict_keys(['vision_features', 'vision_pos_enc', 'backbone_fpn']) + _, image_embeddings, _, _ = self.visual_model._prepare_backbone_features(backbone_out) + image_embeddings = [_.to(images.dtype) for _ in image_embeddings] + batch_size = images.shape[0] + if self.visual_model.directly_add_no_mem_embed: + image_embeddings[-1] = image_embeddings[-1] + self.visual_model.no_mem_embed + + feats = [ + feat.permute(1, 2, 0).view(batch_size, -1, *feat_size) + for feat, feat_size in zip(image_embeddings[::-1], self._bb_feat_sizes[::-1]) + ][::-1] + _features = {"image_embed": feats[-1], "high_res_feats": feats[:-1]} + + + multimask_output = multimask_output + + output = self.mm_extractor.beit3(visual_tokens=images_evf, textual_tokens=input_ids, text_padding_position=torch.zeros_like(input_ids)) + + feat = output["encoder_out"][:, :1, ...] + feat = self.text_hidden_fcs[0](feat) + ( + sparse_embeddings, + dense_embeddings, + ) = self.visual_model.sam_prompt_encoder( + points=None, + boxes=None, + masks=None, + text_embeds=feat, + ) + high_res_features = _features["high_res_feats"] + sparse_embeddings = sparse_embeddings.to(feat.dtype) + low_res_masks, iou_predictions, _, _ = self.visual_model.sam_mask_decoder( + image_embeddings=_features["image_embed"], + image_pe=self.visual_model.sam_prompt_encoder.get_dense_pe(), + sparse_prompt_embeddings=sparse_embeddings, + dense_prompt_embeddings=dense_embeddings, + multimask_output=multimask_output, + repeat_image = True, + high_res_features=high_res_features, + ) + if multimask_output: + sorted_ids = torch.argsort(iou_predictions, dim=-1, descending=True) + low_res_masks = torch.take_along_dim(low_res_masks, sorted_ids[..., None, None], dim=1)[:, :1] + + pred_mask = self.postprocess_masks( + low_res_masks, + orig_hw=original_size_list[0], + ) + + return pred_mask[:, 0] + + +AutoConfig.register("evf", EvfConfig) +AutoModelForCausalLM.register(EvfConfig, EvfSam2Model) \ No newline at end of file diff --git a/py/evf_sam/model/evf_sam2_video.py b/py/evf_sam/model/evf_sam2_video.py new file mode 100644 index 0000000..ef2499a --- /dev/null +++ b/py/evf_sam/model/evf_sam2_video.py @@ -0,0 +1,321 @@ +from typing import List +import os +import torch +import torch.nn as nn +import torch.nn.functional as F +from transformers import PreTrainedModel, AutoConfig, AutoModelForCausalLM +from .segment_anything_2.sam2.build_sam import build_sam2, build_sam2_video_predictor +from .unilm.beit3.modeling_utils import BEiT3Wrapper, _get_base_config, _get_large_config +from .configuration_evf import EvfConfig +from .segment_anything_2.sam2.utils.misc import load_video_frames +from collections import OrderedDict + + + +def dice_loss( + inputs: torch.Tensor, + targets: torch.Tensor, + num_masks: float, + scale=1000, # 100000.0, + eps=1e-6, +): + """ + Compute the DICE loss, similar to generalized IOU for masks + Args: + inputs: A float tensor of arbitrary shape. + The predictions for each example. + targets: A float tensor with the same shape as inputs. Stores the binary + classification label for each element in inputs + (0 for the negative class and 1 for the positive class). + """ + inputs = inputs.sigmoid() + inputs = inputs.flatten(1, 2) + targets = targets.flatten(1, 2) + numerator = 2 * (inputs / scale * targets).sum(-1) + denominator = (inputs / scale).sum(-1) + (targets / scale).sum(-1) + loss = 1 - (numerator + eps) / (denominator + eps) + loss = loss.sum() / (num_masks + 1e-8) + return loss + + +def sigmoid_ce_loss( + inputs: torch.Tensor, + targets: torch.Tensor, + num_masks: float, +): + """ + Args: + inputs: A float tensor of arbitrary shape. + The predictions for each example. + targets: A float tensor with the same shape as inputs. Stores the binary + classification label for each element in inputs + (0 for the negative class and 1 for the positive class). + Returns: + Loss tensor + """ + loss = F.binary_cross_entropy_with_logits(inputs, targets, reduction="none") + loss = loss.flatten(1, 2).mean(1).sum() / (num_masks + 1e-8) + return loss + +class EvfSam2Model(PreTrainedModel): + config_class = EvfConfig + def __init__( + self, + config, + **kwargs + ): + super(EvfSam2Model, self).__init__(config) + + self.config = config + self.vision_pretrained = kwargs.get("vision_pretrained", None) + self.encoder_pretrained = kwargs.get("encoder_pretrained", None) + self.dice_loss_weight = kwargs.get("dice_loss_weight", None) + self.bce_loss_weight = kwargs.get("bce_loss_weight", None) + self.train_mask_decoder = kwargs.get("train_mask_decoder", False) + self.train_prompt_encoder = kwargs.get("train_prompt_encoder", False) + self.initialize_evf_modules(config) + self._bb_feat_sizes = [ + (256, 256), + (128, 128), + (64, 64), + ] + + def initialize_evf_modules(self, config): + # SAM + if config.sam_scale=="large": + self.visual_model = build_sam2_video_predictor("sam2_hiera_l.yaml", self.vision_pretrained, device=None) + elif config.sam_scale=="tiny": + self.visual_model = build_sam2_video_predictor("sam2_hiera_t.yaml", self.vision_pretrained, device=None) + else: + raise NotImplementedError + + for param in self.visual_model.parameters(): + param.requires_grad = False + if self.train_mask_decoder: + self.visual_model.sam_mask_decoder.train() + for param in self.visual_model.sam_mask_decoder.parameters(): + param.requires_grad = True + if self.train_prompt_encoder: + self.visual_model.sam_prompt_encoder.no_mask_embed.requires_grad_(True) + + # beit-3 + if self.config.mm_extractor_scale == "base": + beit_config = _get_base_config() + elif self.config.mm_extractor_scale == "large": + beit_config = _get_large_config() + else: + raise AttributeError(f"model config should contain key 'mm_extractor_scale', with value 'base' or 'large'.") + + self.mm_extractor = BEiT3Wrapper(beit_config) + if self.encoder_pretrained is not None: + beit_state_dict = torch.load(self.encoder_pretrained)["model"] + self.mm_extractor.load_state_dict( + beit_state_dict, + strict=False + ) + + for param in self.mm_extractor.parameters(): + param.requires_grad = True + + # Projection layer + in_dim = config.hidden_size + assert in_dim==beit_config.encoder_embed_dim, \ + f"projection layer dim {in_dim} mismatch with mm_extractor dim {beit_config.encoder_embed_dim}" + out_dim = config.out_dim + text_fc = [ + nn.Linear(in_dim, in_dim), + nn.ReLU(), + nn.Linear(in_dim, out_dim) + ] + self.text_hidden_fcs = nn.ModuleList([nn.Sequential(*text_fc)]) + self.text_hidden_fcs.train() + for param in self.text_hidden_fcs.parameters(): + param.requires_grad = True + + + def postprocess_masks(self, masks: torch.Tensor, orig_hw) -> torch.Tensor: + """ + Perform PostProcessing on output masks. + """ + masks = masks.float() + masks = F.interpolate(masks, orig_hw, mode="bilinear", align_corners=False) + return masks + + # def forward( + # self, + # images: torch.FloatTensor, + # images_evf: torch.FloatTensor, + # input_ids: torch.LongTensor, + # attention_masks: torch.LongTensor, + # offset: torch.LongTensor, + # masks_list: List[torch.FloatTensor], + # label_list: List[torch.Tensor], + # resize_list: List[tuple], + # inference: bool = False, + # **kwargs, + # ): + # # image_embeddings = self.get_visual_embs(images) + # backbone_out = self.visual_model.forward_image(images) + # # dict_keys(['vision_features', 'vision_pos_enc', 'backbone_fpn']) + # _, image_embeddings, _, _ = self.visual_model._prepare_backbone_features(backbone_out) + # image_embeddings = [_.to(images.dtype) for _ in image_embeddings] + # batch_size = images.shape[0] + # if self.visual_model.directly_add_no_mem_embed: + # image_embeddings[-1] = image_embeddings[-1] + self.visual_model.no_mem_embed + + # feats = [ + # feat.permute(1, 2, 0).view(batch_size, -1, *feat_size) + # for feat, feat_size in zip(image_embeddings[::-1], self._bb_feat_sizes[::-1]) + # ][::-1] + # _features = {"image_embed": feats[-1], "high_res_feats": feats[:-1]} + + + # assert batch_size == len(offset) - 1 + + # images_evf_list = [] + # for i in range(len(offset) - 1): + # start_i, end_i = offset[i], offset[i + 1] + # images_evf_i = ( + # images_evf[i] + # .unsqueeze(0) + # .expand(end_i - start_i, -1, -1, -1) + # .contiguous() + # ) + # images_evf_list.append(images_evf_i) + # images_evf = torch.cat(images_evf_list, dim=0) + + # multimask_output = False + # output = self.mm_extractor.beit3( + # visual_tokens=images_evf, + # textual_tokens=input_ids, + # text_padding_position=~attention_masks + # ) + + # feat = output["encoder_out"][:, :1, ...] + + # feat = self.text_hidden_fcs[0](feat) + # feat = torch.split(feat, [offset[i+1] - offset[i] for i in range(len(offset)-1)]) + + # pred_masks = [] + + # for i in range(len(feat)): + # ( + # sparse_embeddings, + # dense_embeddings, + # ) = self.visual_model.sam_prompt_encoder( + # points=None, + # boxes=None, + # masks=None, + # text_embeds=feat[i], + # ) + # sparse_embeddings = sparse_embeddings.to(feat[i].dtype) + # high_res_features = [ + # feat_level[i].unsqueeze(0) + # for feat_level in _features["high_res_feats"] + # ] + # low_res_masks, iou_predictions, _, _ = self.visual_model.sam_mask_decoder( + # image_embeddings=_features["image_embed"][i].unsqueeze(0), + # image_pe=self.visual_model.sam_prompt_encoder.get_dense_pe(), + # sparse_prompt_embeddings=sparse_embeddings, + # dense_prompt_embeddings=dense_embeddings, + # multimask_output=multimask_output, + # repeat_image = True, + # high_res_features=high_res_features, + # ) + + # if multimask_output: + # sorted_ids = torch.argsort(iou_predictions, dim=-1, descending=True) + # low_res_masks = torch.take_along_dim(low_res_masks, sorted_ids[..., None, None], dim=1)[:, :1] + + # pred_mask = self.postprocess_masks( + # low_res_masks, + # orig_hw=label_list[i].shape, + # ) + # pred_masks.append(pred_mask[:, 0]) + + # gt_masks = masks_list + + # if inference: + # return { + # "pred_masks": pred_masks, + # "gt_masks": gt_masks, + # } + + # mask_bce_loss = 0 + # mask_dice_loss = 0 + # num_masks = 0 + # for batch_idx in range(len(pred_masks)): + # gt_mask = gt_masks[batch_idx] + # pred_mask = pred_masks[batch_idx] + + # assert ( + # gt_mask.shape[0] == pred_mask.shape[0] + # ), "gt_mask.shape: {}, pred_mask.shape: {}".format( + # gt_mask.shape, pred_mask.shape + # ) + # mask_bce_loss += ( + # sigmoid_ce_loss(pred_mask, gt_mask, num_masks=gt_mask.shape[0]) + # * gt_mask.shape[0] + # ) + # mask_dice_loss += ( + # dice_loss(pred_mask, gt_mask, num_masks=gt_mask.shape[0]) + # * gt_mask.shape[0] + # ) + # num_masks += gt_mask.shape[0] + + # mask_bce_loss = self.bce_loss_weight * mask_bce_loss / (num_masks + 1e-8) + # mask_dice_loss = self.dice_loss_weight * mask_dice_loss / (num_masks + 1e-8) + # mask_loss = mask_bce_loss + mask_dice_loss + + # loss = mask_loss + + # return { + # "loss": loss, + # "mask_bce_loss": mask_bce_loss, + # "mask_dice_loss": mask_dice_loss, + # "mask_loss": mask_loss, + # } + + def inference( + self, + video_path, + images_evf, + input_ids, + # original_size_list, + multimask_output=False, + ): + predictor = self.visual_model + inference_state = predictor.init_state(video_path=video_path) + predictor.reset_state(inference_state) + + + multimask_output = multimask_output + + output = self.mm_extractor.beit3(visual_tokens=images_evf, textual_tokens=input_ids, text_padding_position=torch.zeros_like(input_ids)) + + feat = output["encoder_out"][:, :1, ...] + feat = self.text_hidden_fcs[0](feat) + + ann_frame_idx = 0 # the frame index we interact with + ann_obj_id = 1 # give a unique id to each object we interact with (it can be any integers) + + _, out_obj_ids, out_mask_logits = predictor.add_new_text( + inference_state=inference_state, + frame_idx=ann_frame_idx, + obj_id=ann_obj_id, + text=feat + ) + + # run propagation throughout the video and collect the results in a dict + video_segments = {} # video_segments contains the per-frame segmentation results + for out_frame_idx, out_obj_ids, out_mask_logits in predictor.propagate_in_video(inference_state): + video_segments[out_frame_idx] = { + out_obj_id: (out_mask_logits[i] > 0.0).cpu().numpy() + for i, out_obj_id in enumerate(out_obj_ids) + } + + return video_segments + + +AutoConfig.register("evf", EvfConfig) +AutoModelForCausalLM.register(EvfConfig, EvfSam2Model) \ No newline at end of file diff --git a/py/evf_sam/model/segment_anything/__init__.py b/py/evf_sam/model/segment_anything/__init__.py new file mode 100644 index 0000000..e66218b --- /dev/null +++ b/py/evf_sam/model/segment_anything/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +from .automatic_mask_generator import SamAutomaticMaskGenerator +from .build_sam import (build_sam, build_sam_vit_b, build_sam_vit_h, + build_sam_vit_l, sam_model_registry) +from .predictor import SamPredictor diff --git a/py/evf_sam/model/segment_anything/automatic_mask_generator.py b/py/evf_sam/model/segment_anything/automatic_mask_generator.py new file mode 100644 index 0000000..aa4bc4f --- /dev/null +++ b/py/evf_sam/model/segment_anything/automatic_mask_generator.py @@ -0,0 +1,372 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +from typing import Any, Dict, List, Optional, Tuple + +import numpy as np +import torch +from torchvision.ops.boxes import batched_nms, box_area # type: ignore + +from .modeling import Sam +from .predictor import SamPredictor +from .utils.amg import (MaskData, area_from_rle, batch_iterator, + batched_mask_to_box, box_xyxy_to_xywh, + build_all_layer_point_grids, calculate_stability_score, + coco_encode_rle, generate_crop_boxes, + is_box_near_crop_edge, mask_to_rle_pytorch, + remove_small_regions, rle_to_mask, uncrop_boxes_xyxy, + uncrop_masks, uncrop_points) + + +class SamAutomaticMaskGenerator: + def __init__( + self, + model: Sam, + points_per_side: Optional[int] = 32, + points_per_batch: int = 64, + pred_iou_thresh: float = 0.88, + stability_score_thresh: float = 0.95, + stability_score_offset: float = 1.0, + box_nms_thresh: float = 0.7, + crop_n_layers: int = 0, + crop_nms_thresh: float = 0.7, + crop_overlap_ratio: float = 512 / 1500, + crop_n_points_downscale_factor: int = 1, + point_grids: Optional[List[np.ndarray]] = None, + min_mask_region_area: int = 0, + output_mode: str = "binary_mask", + ) -> None: + """ + Using a SAM model, generates masks for the entire image. + Generates a grid of point prompts over the image, then filters + low quality and duplicate masks. The default settings are chosen + for SAM with a ViT-H backbone. + + Arguments: + model (Sam): The SAM model to use for mask prediction. + points_per_side (int or None): The number of points to be sampled + along one side of the image. The total number of points is + points_per_side**2. If None, 'point_grids' must provide explicit + point sampling. + points_per_batch (int): Sets the number of points run simultaneously + by the model. Higher numbers may be faster but use more GPU memory. + pred_iou_thresh (float): A filtering threshold in [0,1], using the + model's predicted mask quality. + stability_score_thresh (float): A filtering threshold in [0,1], using + the stability of the mask under changes to the cutoff used to binarize + the model's mask predictions. + stability_score_offset (float): The amount to shift the cutoff when + calculated the stability score. + box_nms_thresh (float): The box IoU cutoff used by non-maximal + suppression to filter duplicate masks. + crop_n_layers (int): If >0, mask prediction will be run again on + crops of the image. Sets the number of layers to run, where each + layer has 2**i_layer number of image crops. + crop_nms_thresh (float): The box IoU cutoff used by non-maximal + suppression to filter duplicate masks between different crops. + crop_overlap_ratio (float): Sets the degree to which crops overlap. + In the first crop layer, crops will overlap by this fraction of + the image length. Later layers with more crops scale down this overlap. + crop_n_points_downscale_factor (int): The number of points-per-side + sampled in layer n is scaled down by crop_n_points_downscale_factor**n. + point_grids (list(np.ndarray) or None): A list over explicit grids + of points used for sampling, normalized to [0,1]. The nth grid in the + list is used in the nth crop layer. Exclusive with points_per_side. + min_mask_region_area (int): If >0, postprocessing will be applied + to remove disconnected regions and holes in masks with area smaller + than min_mask_region_area. Requires opencv. + output_mode (str): The form masks are returned in. Can be 'binary_mask', + 'uncompressed_rle', or 'coco_rle'. 'coco_rle' requires pycocotools. + For large resolutions, 'binary_mask' may consume large amounts of + memory. + """ + + assert (points_per_side is None) != ( + point_grids is None + ), "Exactly one of points_per_side or point_grid must be provided." + if points_per_side is not None: + self.point_grids = build_all_layer_point_grids( + points_per_side, + crop_n_layers, + crop_n_points_downscale_factor, + ) + elif point_grids is not None: + self.point_grids = point_grids + else: + raise ValueError("Can't have both points_per_side and point_grid be None.") + + assert output_mode in [ + "binary_mask", + "uncompressed_rle", + "coco_rle", + ], f"Unknown output_mode {output_mode}." + if output_mode == "coco_rle": + from pycocotools import \ + mask as mask_utils # type: ignore # noqa: F401 + + if min_mask_region_area > 0: + import cv2 # type: ignore # noqa: F401 + + self.predictor = SamPredictor(model) + self.points_per_batch = points_per_batch + self.pred_iou_thresh = pred_iou_thresh + self.stability_score_thresh = stability_score_thresh + self.stability_score_offset = stability_score_offset + self.box_nms_thresh = box_nms_thresh + self.crop_n_layers = crop_n_layers + self.crop_nms_thresh = crop_nms_thresh + self.crop_overlap_ratio = crop_overlap_ratio + self.crop_n_points_downscale_factor = crop_n_points_downscale_factor + self.min_mask_region_area = min_mask_region_area + self.output_mode = output_mode + + @torch.no_grad() + def generate(self, image: np.ndarray) -> List[Dict[str, Any]]: + """ + Generates masks for the given image. + + Arguments: + image (np.ndarray): The image to generate masks for, in HWC uint8 format. + + Returns: + list(dict(str, any)): A list over records for masks. Each record is + a dict containing the following keys: + segmentation (dict(str, any) or np.ndarray): The mask. If + output_mode='binary_mask', is an array of shape HW. Otherwise, + is a dictionary containing the RLE. + bbox (list(float)): The box around the mask, in XYWH format. + area (int): The area in pixels of the mask. + predicted_iou (float): The model's own prediction of the mask's + quality. This is filtered by the pred_iou_thresh parameter. + point_coords (list(list(float))): The point coordinates input + to the model to generate this mask. + stability_score (float): A measure of the mask's quality. This + is filtered on using the stability_score_thresh parameter. + crop_box (list(float)): The crop of the image used to generate + the mask, given in XYWH format. + """ + + # Generate masks + mask_data = self._generate_masks(image) + + # Filter small disconnected regions and holes in masks + if self.min_mask_region_area > 0: + mask_data = self.postprocess_small_regions( + mask_data, + self.min_mask_region_area, + max(self.box_nms_thresh, self.crop_nms_thresh), + ) + + # Encode masks + if self.output_mode == "coco_rle": + mask_data["segmentations"] = [ + coco_encode_rle(rle) for rle in mask_data["rles"] + ] + elif self.output_mode == "binary_mask": + mask_data["segmentations"] = [rle_to_mask(rle) for rle in mask_data["rles"]] + else: + mask_data["segmentations"] = mask_data["rles"] + + # Write mask records + curr_anns = [] + for idx in range(len(mask_data["segmentations"])): + ann = { + "segmentation": mask_data["segmentations"][idx], + "area": area_from_rle(mask_data["rles"][idx]), + "bbox": box_xyxy_to_xywh(mask_data["boxes"][idx]).tolist(), + "predicted_iou": mask_data["iou_preds"][idx].item(), + "point_coords": [mask_data["points"][idx].tolist()], + "stability_score": mask_data["stability_score"][idx].item(), + "crop_box": box_xyxy_to_xywh(mask_data["crop_boxes"][idx]).tolist(), + } + curr_anns.append(ann) + + return curr_anns + + def _generate_masks(self, image: np.ndarray) -> MaskData: + orig_size = image.shape[:2] + crop_boxes, layer_idxs = generate_crop_boxes( + orig_size, self.crop_n_layers, self.crop_overlap_ratio + ) + + # Iterate over image crops + data = MaskData() + for crop_box, layer_idx in zip(crop_boxes, layer_idxs): + crop_data = self._process_crop(image, crop_box, layer_idx, orig_size) + data.cat(crop_data) + + # Remove duplicate masks between crops + if len(crop_boxes) > 1: + # Prefer masks from smaller crops + scores = 1 / box_area(data["crop_boxes"]) + scores = scores.to(data["boxes"].device) + keep_by_nms = batched_nms( + data["boxes"].float(), + scores, + torch.zeros_like(data["boxes"][:, 0]), # categories + iou_threshold=self.crop_nms_thresh, + ) + data.filter(keep_by_nms) + + data.to_numpy() + return data + + def _process_crop( + self, + image: np.ndarray, + crop_box: List[int], + crop_layer_idx: int, + orig_size: Tuple[int, ...], + ) -> MaskData: + # Crop the image and calculate embeddings + x0, y0, x1, y1 = crop_box + cropped_im = image[y0:y1, x0:x1, :] + cropped_im_size = cropped_im.shape[:2] + self.predictor.set_image(cropped_im) + + # Get points for this crop + points_scale = np.array(cropped_im_size)[None, ::-1] + points_for_image = self.point_grids[crop_layer_idx] * points_scale + + # Generate masks for this crop in batches + data = MaskData() + for (points,) in batch_iterator(self.points_per_batch, points_for_image): + batch_data = self._process_batch( + points, cropped_im_size, crop_box, orig_size + ) + data.cat(batch_data) + del batch_data + self.predictor.reset_image() + + # Remove duplicates within this crop. + keep_by_nms = batched_nms( + data["boxes"].float(), + data["iou_preds"], + torch.zeros_like(data["boxes"][:, 0]), # categories + iou_threshold=self.box_nms_thresh, + ) + data.filter(keep_by_nms) + + # Return to the original image frame + data["boxes"] = uncrop_boxes_xyxy(data["boxes"], crop_box) + data["points"] = uncrop_points(data["points"], crop_box) + data["crop_boxes"] = torch.tensor([crop_box for _ in range(len(data["rles"]))]) + + return data + + def _process_batch( + self, + points: np.ndarray, + im_size: Tuple[int, ...], + crop_box: List[int], + orig_size: Tuple[int, ...], + ) -> MaskData: + orig_h, orig_w = orig_size + + # Run model on this batch + transformed_points = self.predictor.transform.apply_coords(points, im_size) + in_points = torch.as_tensor(transformed_points, device=self.predictor.device) + in_labels = torch.ones( + in_points.shape[0], dtype=torch.int, device=in_points.device + ) + masks, iou_preds, _ = self.predictor.predict_torch( + in_points[:, None, :], + in_labels[:, None], + multimask_output=True, + return_logits=True, + ) + + # Serialize predictions and store in MaskData + data = MaskData( + masks=masks.flatten(0, 1), + iou_preds=iou_preds.flatten(0, 1), + points=torch.as_tensor(points.repeat(masks.shape[1], axis=0)), + ) + del masks + + # Filter by predicted IoU + if self.pred_iou_thresh > 0.0: + keep_mask = data["iou_preds"] > self.pred_iou_thresh + data.filter(keep_mask) + + # Calculate stability score + data["stability_score"] = calculate_stability_score( + data["masks"], + self.predictor.model.mask_threshold, + self.stability_score_offset, + ) + if self.stability_score_thresh > 0.0: + keep_mask = data["stability_score"] >= self.stability_score_thresh + data.filter(keep_mask) + + # Threshold masks and calculate boxes + data["masks"] = data["masks"] > self.predictor.model.mask_threshold + data["boxes"] = batched_mask_to_box(data["masks"]) + + # Filter boxes that touch crop boundaries + keep_mask = ~is_box_near_crop_edge( + data["boxes"], crop_box, [0, 0, orig_w, orig_h] + ) + if not torch.all(keep_mask): + data.filter(keep_mask) + + # Compress to RLE + data["masks"] = uncrop_masks(data["masks"], crop_box, orig_h, orig_w) + data["rles"] = mask_to_rle_pytorch(data["masks"]) + del data["masks"] + + return data + + @staticmethod + def postprocess_small_regions( + mask_data: MaskData, min_area: int, nms_thresh: float + ) -> MaskData: + """ + Removes small disconnected regions and holes in masks, then reruns + box NMS to remove any new duplicates. + + Edits mask_data in place. + + Requires open-cv as a dependency. + """ + if len(mask_data["rles"]) == 0: + return mask_data + + # Filter small disconnected regions and holes + new_masks = [] + scores = [] + for rle in mask_data["rles"]: + mask = rle_to_mask(rle) + + mask, changed = remove_small_regions(mask, min_area, mode="holes") + unchanged = not changed + mask, changed = remove_small_regions(mask, min_area, mode="islands") + unchanged = unchanged and not changed + + new_masks.append(torch.as_tensor(mask).unsqueeze(0)) + # Give score=0 to changed masks and score=1 to unchanged masks + # so NMS will prefer ones that didn't need postprocessing + scores.append(float(unchanged)) + + # Recalculate boxes and remove any new duplicates + masks = torch.cat(new_masks, dim=0) + boxes = batched_mask_to_box(masks) + keep_by_nms = batched_nms( + boxes.float(), + torch.as_tensor(scores), + torch.zeros_like(boxes[:, 0]), # categories + iou_threshold=nms_thresh, + ) + + # Only recalculate RLEs for masks that have changed + for i_mask in keep_by_nms: + if scores[i_mask] == 0.0: + mask_torch = masks[i_mask].unsqueeze(0) + mask_data["rles"][i_mask] = mask_to_rle_pytorch(mask_torch)[0] + mask_data["boxes"][i_mask] = boxes[i_mask] # update res directly + mask_data.filter(keep_by_nms) + + return mask_data diff --git a/py/evf_sam/model/segment_anything/build_sam.py b/py/evf_sam/model/segment_anything/build_sam.py new file mode 100644 index 0000000..788d25a --- /dev/null +++ b/py/evf_sam/model/segment_anything/build_sam.py @@ -0,0 +1,108 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +from functools import partial + +import torch + +from .modeling import (ImageEncoderViT, MaskDecoder, PromptEncoder, Sam, + TwoWayTransformer) + + +def build_sam_vit_h(checkpoint=None): + return _build_sam( + encoder_embed_dim=1280, + encoder_depth=32, + encoder_num_heads=16, + encoder_global_attn_indexes=[7, 15, 23, 31], + checkpoint=checkpoint, + ) + + +build_sam = build_sam_vit_h + + +def build_sam_vit_l(checkpoint=None): + return _build_sam( + encoder_embed_dim=1024, + encoder_depth=24, + encoder_num_heads=16, + encoder_global_attn_indexes=[5, 11, 17, 23], + checkpoint=checkpoint, + ) + + +def build_sam_vit_b(checkpoint=None): + return _build_sam( + encoder_embed_dim=768, + encoder_depth=12, + encoder_num_heads=12, + encoder_global_attn_indexes=[2, 5, 8, 11], + checkpoint=checkpoint, + ) + + +sam_model_registry = { + "default": build_sam_vit_h, + "vit_h": build_sam_vit_h, + "vit_l": build_sam_vit_l, + "vit_b": build_sam_vit_b, +} + + +def _build_sam( + encoder_embed_dim, + encoder_depth, + encoder_num_heads, + encoder_global_attn_indexes, + checkpoint=None, +): + prompt_embed_dim = 256 + image_size = 1024 + vit_patch_size = 16 + image_embedding_size = image_size // vit_patch_size + sam = Sam( + image_encoder=ImageEncoderViT( + depth=encoder_depth, + embed_dim=encoder_embed_dim, + img_size=image_size, + mlp_ratio=4, + norm_layer=partial(torch.nn.LayerNorm, eps=1e-6), + num_heads=encoder_num_heads, + patch_size=vit_patch_size, + qkv_bias=True, + use_rel_pos=True, + global_attn_indexes=encoder_global_attn_indexes, + window_size=14, + out_chans=prompt_embed_dim, + ), + prompt_encoder=PromptEncoder( + embed_dim=prompt_embed_dim, + image_embedding_size=(image_embedding_size, image_embedding_size), + input_image_size=(image_size, image_size), + mask_in_chans=16, + ), + mask_decoder=MaskDecoder( + num_multimask_outputs=3, + transformer=TwoWayTransformer( + depth=2, + embedding_dim=prompt_embed_dim, + mlp_dim=2048, + num_heads=8, + ), + transformer_dim=prompt_embed_dim, + iou_head_depth=3, + iou_head_hidden_dim=256, + ), + pixel_mean=[123.675, 116.28, 103.53], + pixel_std=[58.395, 57.12, 57.375], + ) + sam.eval() + if checkpoint is not None: + with open(checkpoint, "rb") as f: + state_dict = torch.load(f) + sam.load_state_dict(state_dict, strict=False) + return sam diff --git a/py/evf_sam/model/segment_anything/modeling/__init__.py b/py/evf_sam/model/segment_anything/modeling/__init__.py new file mode 100644 index 0000000..088af38 --- /dev/null +++ b/py/evf_sam/model/segment_anything/modeling/__init__.py @@ -0,0 +1,11 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +from .image_encoder import ImageEncoderViT +from .mask_decoder import MaskDecoder +from .prompt_encoder import PromptEncoder +from .sam import Sam +from .transformer import TwoWayTransformer diff --git a/py/evf_sam/model/segment_anything/modeling/common.py b/py/evf_sam/model/segment_anything/modeling/common.py new file mode 100644 index 0000000..e872781 --- /dev/null +++ b/py/evf_sam/model/segment_anything/modeling/common.py @@ -0,0 +1,43 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +from typing import Type + +import torch +import torch.nn as nn + + +class MLPBlock(nn.Module): + def __init__( + self, + embedding_dim: int, + mlp_dim: int, + act: Type[nn.Module] = nn.GELU, + ) -> None: + super().__init__() + self.lin1 = nn.Linear(embedding_dim, mlp_dim) + self.lin2 = nn.Linear(mlp_dim, embedding_dim) + self.act = act() + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return self.lin2(self.act(self.lin1(x))) + + +# From https://github.com/facebookresearch/detectron2/blob/main/detectron2/layers/batch_norm.py # noqa +# Itself from https://github.com/facebookresearch/ConvNeXt/blob/d1fa8f6fef0a165b27399986cc2bdacc92777e40/models/convnext.py#L119 # noqa +class LayerNorm2d(nn.Module): + def __init__(self, num_channels: int, eps: float = 1e-6) -> None: + super().__init__() + self.weight = nn.Parameter(torch.ones(num_channels)) + self.bias = nn.Parameter(torch.zeros(num_channels)) + self.eps = eps + + def forward(self, x: torch.Tensor) -> torch.Tensor: + u = x.mean(1, keepdim=True) + s = (x - u).pow(2).mean(1, keepdim=True) + x = (x - u) / torch.sqrt(s + self.eps) + x = self.weight[:, None, None] * x + self.bias[:, None, None] + return x diff --git a/py/evf_sam/model/segment_anything/modeling/image_encoder.py b/py/evf_sam/model/segment_anything/modeling/image_encoder.py new file mode 100644 index 0000000..b472a3d --- /dev/null +++ b/py/evf_sam/model/segment_anything/modeling/image_encoder.py @@ -0,0 +1,426 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +from typing import Optional, Tuple, Type + +import torch +import torch.nn as nn +import torch.nn.functional as F + +from .common import LayerNorm2d, MLPBlock + + +# This class and its supporting functions below lightly adapted from the ViTDet backbone available at: https://github.com/facebookresearch/detectron2/blob/main/detectron2/modeling/backbone/vit.py # noqa +class ImageEncoderViT(nn.Module): + def __init__( + self, + img_size: int = 1024, + patch_size: int = 16, + in_chans: int = 3, + embed_dim: int = 768, + depth: int = 12, + num_heads: int = 12, + mlp_ratio: float = 4.0, + out_chans: int = 256, + qkv_bias: bool = True, + norm_layer: Type[nn.Module] = nn.LayerNorm, + act_layer: Type[nn.Module] = nn.GELU, + use_abs_pos: bool = True, + use_rel_pos: bool = False, + rel_pos_zero_init: bool = True, + window_size: int = 0, + global_attn_indexes: Tuple[int, ...] = (), + ) -> None: + """ + Args: + img_size (int): Input image size. + patch_size (int): Patch size. + in_chans (int): Number of input image channels. + embed_dim (int): Patch embedding dimension. + depth (int): Depth of ViT. + num_heads (int): Number of attention heads in each ViT block. + mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. + qkv_bias (bool): If True, add a learnable bias to query, key, value. + norm_layer (nn.Module): Normalization layer. + act_layer (nn.Module): Activation layer. + use_abs_pos (bool): If True, use absolute positional embeddings. + use_rel_pos (bool): If True, add relative positional embeddings to the attention map. + rel_pos_zero_init (bool): If True, zero initialize relative positional parameters. + window_size (int): Window size for window attention blocks. + global_attn_indexes (list): Indexes for blocks using global attention. + """ + super().__init__() + self.img_size = img_size + self.embed_dim = embed_dim + self.out_chans = out_chans + + self.patch_embed = PatchEmbed( + kernel_size=(patch_size, patch_size), + stride=(patch_size, patch_size), + in_chans=in_chans, + embed_dim=embed_dim, + ) + + self.pos_embed: Optional[nn.Parameter] = None + if use_abs_pos: + # Initialize absolute positional embedding with pretrain image size. + self.pos_embed = nn.Parameter( + torch.zeros( + 1, img_size // patch_size, img_size // patch_size, embed_dim + ) + ) + + self.blocks = nn.ModuleList() + for i in range(depth): + block = Block( + dim=embed_dim, + num_heads=num_heads, + mlp_ratio=mlp_ratio, + qkv_bias=qkv_bias, + norm_layer=norm_layer, + act_layer=act_layer, + use_rel_pos=use_rel_pos, + rel_pos_zero_init=rel_pos_zero_init, + window_size=window_size if i not in global_attn_indexes else 0, + input_size=(img_size // patch_size, img_size // patch_size), + ) + self.blocks.append(block) + + self.neck = nn.Sequential( + nn.Conv2d( + embed_dim, + out_chans, + kernel_size=1, + bias=False, + ), + LayerNorm2d(out_chans), + nn.Conv2d( + out_chans, + out_chans, + kernel_size=3, + padding=1, + bias=False, + ), + LayerNorm2d(out_chans), + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x = self.patch_embed(x) + if self.pos_embed is not None: + x = x + self.pos_embed + + for blk in self.blocks: + x = blk(x) + + dtype = x.dtype + if dtype == torch.float16: # prevent overflow + with torch.autocast(device_type="cuda", dtype=torch.float32): + x = self.neck(x.permute(0, 3, 1, 2)) + x = x.to(dtype) + else: + x = self.neck(x.permute(0, 3, 1, 2)) + return x + + +class Block(nn.Module): + """Transformer blocks with support of window attention and residual propagation blocks""" + + def __init__( + self, + dim: int, + num_heads: int, + mlp_ratio: float = 4.0, + qkv_bias: bool = True, + norm_layer: Type[nn.Module] = nn.LayerNorm, + act_layer: Type[nn.Module] = nn.GELU, + use_rel_pos: bool = False, + rel_pos_zero_init: bool = True, + window_size: int = 0, + input_size: Optional[Tuple[int, int]] = None, + ) -> None: + """ + Args: + dim (int): Number of input channels. + num_heads (int): Number of attention heads in each ViT block. + mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. + qkv_bias (bool): If True, add a learnable bias to query, key, value. + norm_layer (nn.Module): Normalization layer. + act_layer (nn.Module): Activation layer. + use_rel_pos (bool): If True, add relative positional embeddings to the attention map. + rel_pos_zero_init (bool): If True, zero initialize relative positional parameters. + window_size (int): Window size for window attention blocks. If it equals 0, then + use global attention. + input_size (tuple(int, int) or None): Input resolution for calculating the relative + positional parameter size. + """ + super().__init__() + self.norm1 = norm_layer(dim) + self.attn = Attention( + dim, + num_heads=num_heads, + qkv_bias=qkv_bias, + use_rel_pos=use_rel_pos, + rel_pos_zero_init=rel_pos_zero_init, + input_size=input_size if window_size == 0 else (window_size, window_size), + ) + + self.norm2 = norm_layer(dim) + self.mlp = MLPBlock( + embedding_dim=dim, mlp_dim=int(dim * mlp_ratio), act=act_layer + ) + + self.window_size = window_size + + def forward(self, x: torch.Tensor) -> torch.Tensor: + shortcut = x + x = self.norm1(x) + # Window partition + if self.window_size > 0: + H, W = x.shape[1], x.shape[2] + x, pad_hw = window_partition(x, self.window_size) + + x = self.attn(x) + # Reverse window partition + if self.window_size > 0: + x = window_unpartition(x, self.window_size, pad_hw, (H, W)) + + x = shortcut + x + x = x + self.mlp(self.norm2(x)) + + return x + + +class Attention(nn.Module): + """Multi-head Attention block with relative position embeddings.""" + + def __init__( + self, + dim: int, + num_heads: int = 8, + qkv_bias: bool = True, + use_rel_pos: bool = False, + rel_pos_zero_init: bool = True, + input_size: Optional[Tuple[int, int]] = None, + ) -> None: + """ + Args: + dim (int): Number of input channels. + num_heads (int): Number of attention heads. + qkv_bias (bool): If True, add a learnable bias to query, key, value. + rel_pos (bool): If True, add relative positional embeddings to the attention map. + rel_pos_zero_init (bool): If True, zero initialize relative positional parameters. + input_size (tuple(int, int) or None): Input resolution for calculating the relative + positional parameter size. + """ + super().__init__() + self.num_heads = num_heads + head_dim = dim // num_heads + self.scale = head_dim**-0.5 + + self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) + self.proj = nn.Linear(dim, dim) + + self.use_rel_pos = use_rel_pos + if self.use_rel_pos: + assert ( + input_size is not None + ), "Input size must be provided if using relative positional encoding." + # initialize relative positional embeddings + self.rel_pos_h = nn.Parameter(torch.zeros(2 * input_size[0] - 1, head_dim)) + self.rel_pos_w = nn.Parameter(torch.zeros(2 * input_size[1] - 1, head_dim)) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + B, H, W, _ = x.shape + # qkv with shape (3, B, nHead, H * W, C) + qkv = ( + self.qkv(x).reshape(B, H * W, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4) + ) + # q, k, v with shape (B * nHead, H * W, C) + q, k, v = qkv.reshape(3, B * self.num_heads, H * W, -1).unbind(0) + + attn = (q * self.scale) @ k.transpose(-2, -1) + + if self.use_rel_pos: + attn = add_decomposed_rel_pos( + attn, q, self.rel_pos_h, self.rel_pos_w, (H, W), (H, W) + ) + + attn = attn.softmax(dim=-1) + x = ( + (attn @ v) + .view(B, self.num_heads, H, W, -1) + .permute(0, 2, 3, 1, 4) + .reshape(B, H, W, -1) + ) + x = self.proj(x) + + return x + + +def window_partition( + x: torch.Tensor, window_size: int +) -> Tuple[torch.Tensor, Tuple[int, int]]: + """ + Partition into non-overlapping windows with padding if needed. + Args: + x (tensor): input tokens with [B, H, W, C]. + window_size (int): window size. + + Returns: + windows: windows after partition with [B * num_windows, window_size, window_size, C]. + (Hp, Wp): padded height and width before partition + """ + B, H, W, C = x.shape + + pad_h = (window_size - H % window_size) % window_size + pad_w = (window_size - W % window_size) % window_size + if pad_h > 0 or pad_w > 0: + x = F.pad(x, (0, 0, 0, pad_w, 0, pad_h)) + Hp, Wp = H + pad_h, W + pad_w + + x = x.view(B, Hp // window_size, window_size, Wp // window_size, window_size, C) + windows = ( + x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C) + ) + return windows, (Hp, Wp) + + +def window_unpartition( + windows: torch.Tensor, + window_size: int, + pad_hw: Tuple[int, int], + hw: Tuple[int, int], +) -> torch.Tensor: + """ + Window unpartition into original sequences and removing padding. + Args: + windows (tensor): input tokens with [B * num_windows, window_size, window_size, C]. + window_size (int): window size. + pad_hw (Tuple): padded height and width (Hp, Wp). + hw (Tuple): original height and width (H, W) before padding. + + Returns: + x: unpartitioned sequences with [B, H, W, C]. + """ + Hp, Wp = pad_hw + H, W = hw + B = windows.shape[0] // (Hp * Wp // window_size // window_size) + x = windows.view( + B, Hp // window_size, Wp // window_size, window_size, window_size, -1 + ) + x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, Hp, Wp, -1) + + if Hp > H or Wp > W: + x = x[:, :H, :W, :].contiguous() + return x + + +def get_rel_pos(q_size: int, k_size: int, rel_pos: torch.Tensor) -> torch.Tensor: + """ + Get relative positional embeddings according to the relative positions of + query and key sizes. + Args: + q_size (int): size of query q. + k_size (int): size of key k. + rel_pos (Tensor): relative position embeddings (L, C). + + Returns: + Extracted positional embeddings according to relative positions. + """ + max_rel_dist = int(2 * max(q_size, k_size) - 1) + # Interpolate rel pos if needed. + if rel_pos.shape[0] != max_rel_dist: + # Interpolate rel pos. + rel_pos_resized = F.interpolate( + rel_pos.reshape(1, rel_pos.shape[0], -1).permute(0, 2, 1), + size=max_rel_dist, + mode="linear", + ) + rel_pos_resized = rel_pos_resized.reshape(-1, max_rel_dist).permute(1, 0) + else: + rel_pos_resized = rel_pos + + # Scale the coords with short length if shapes for q and k are different. + q_coords = torch.arange(q_size)[:, None] * max(k_size / q_size, 1.0) + k_coords = torch.arange(k_size)[None, :] * max(q_size / k_size, 1.0) + relative_coords = (q_coords - k_coords) + (k_size - 1) * max(q_size / k_size, 1.0) + + return rel_pos_resized[relative_coords.long()] + + +def add_decomposed_rel_pos( + attn: torch.Tensor, + q: torch.Tensor, + rel_pos_h: torch.Tensor, + rel_pos_w: torch.Tensor, + q_size: Tuple[int, int], + k_size: Tuple[int, int], +) -> torch.Tensor: + """ + Calculate decomposed Relative Positional Embeddings from :paper:`mvitv2`. + https://github.com/facebookresearch/mvit/blob/19786631e330df9f3622e5402b4a419a263a2c80/mvit/models/attention.py # noqa B950 + Args: + attn (Tensor): attention map. + q (Tensor): query q in the attention layer with shape (B, q_h * q_w, C). + rel_pos_h (Tensor): relative position embeddings (Lh, C) for height axis. + rel_pos_w (Tensor): relative position embeddings (Lw, C) for width axis. + q_size (Tuple): spatial sequence size of query q with (q_h, q_w). + k_size (Tuple): spatial sequence size of key k with (k_h, k_w). + + Returns: + attn (Tensor): attention map with added relative positional embeddings. + """ + q_h, q_w = q_size + k_h, k_w = k_size + Rh = get_rel_pos(q_h, k_h, rel_pos_h) + Rw = get_rel_pos(q_w, k_w, rel_pos_w) + + B, _, dim = q.shape + r_q = q.reshape(B, q_h, q_w, dim) + rel_h = torch.einsum("bhwc,hkc->bhwk", r_q, Rh) + rel_w = torch.einsum("bhwc,wkc->bhwk", r_q, Rw) + + attn = ( + attn.view(B, q_h, q_w, k_h, k_w) + + rel_h[:, :, :, :, None] + + rel_w[:, :, :, None, :] + ).view(B, q_h * q_w, k_h * k_w) + + return attn + + +class PatchEmbed(nn.Module): + """ + Image to Patch Embedding. + """ + + def __init__( + self, + kernel_size: Tuple[int, int] = (16, 16), + stride: Tuple[int, int] = (16, 16), + padding: Tuple[int, int] = (0, 0), + in_chans: int = 3, + embed_dim: int = 768, + ) -> None: + """ + Args: + kernel_size (Tuple): kernel size of the projection layer. + stride (Tuple): stride of the projection layer. + padding (Tuple): padding size of the projection layer. + in_chans (int): Number of input image channels. + embed_dim (int): Patch embedding dimension. + """ + super().__init__() + + self.proj = nn.Conv2d( + in_chans, embed_dim, kernel_size=kernel_size, stride=stride, padding=padding + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x = self.proj(x) + # B C H W -> B H W C + x = x.permute(0, 2, 3, 1) + return x diff --git a/py/evf_sam/model/segment_anything/modeling/mask_decoder.py b/py/evf_sam/model/segment_anything/modeling/mask_decoder.py new file mode 100644 index 0000000..fb104ea --- /dev/null +++ b/py/evf_sam/model/segment_anything/modeling/mask_decoder.py @@ -0,0 +1,191 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +from typing import List, Tuple, Type + +import torch +from torch import nn +from torch.nn import functional as F + +from .common import LayerNorm2d + + +class MaskDecoder(nn.Module): + def __init__( + self, + *, + transformer_dim: int, + transformer: nn.Module, + num_multimask_outputs: int = 3, + activation: Type[nn.Module] = nn.GELU, + iou_head_depth: int = 3, + iou_head_hidden_dim: int = 256, + ) -> None: + """ + Predicts masks given an image and prompt embeddings, using a + transformer architecture. + + Arguments: + transformer_dim (int): the channel dimension of the transformer + transformer (nn.Module): the transformer used to predict masks + num_multimask_outputs (int): the number of masks to predict + when disambiguating masks + activation (nn.Module): the type of activation to use when + upscaling masks + iou_head_depth (int): the depth of the MLP used to predict + mask quality + iou_head_hidden_dim (int): the hidden dimension of the MLP + used to predict mask quality + """ + super().__init__() + self.transformer_dim = transformer_dim + self.transformer = transformer + + self.num_multimask_outputs = num_multimask_outputs + + self.iou_token = nn.Embedding(1, transformer_dim) + self.num_mask_tokens = num_multimask_outputs + 1 + self.mask_tokens = nn.Embedding(self.num_mask_tokens, transformer_dim) + + self.output_upscaling = nn.Sequential( + nn.ConvTranspose2d( + transformer_dim, transformer_dim // 4, kernel_size=2, stride=2 + ), + LayerNorm2d(transformer_dim // 4), + activation(), + nn.ConvTranspose2d( + transformer_dim // 4, transformer_dim // 8, kernel_size=2, stride=2 + ), + activation(), + ) + self.output_hypernetworks_mlps = nn.ModuleList( + [ + MLP(transformer_dim, transformer_dim, transformer_dim // 8, 3) + for i in range(self.num_mask_tokens) + ] + ) + + self.iou_prediction_head = MLP( + transformer_dim, iou_head_hidden_dim, self.num_mask_tokens, iou_head_depth + ) + + def forward( + self, + image_embeddings: torch.Tensor, + image_pe: torch.Tensor, + sparse_prompt_embeddings: torch.Tensor, + dense_prompt_embeddings: torch.Tensor, + multimask_output: bool, + ) -> Tuple[torch.Tensor, torch.Tensor]: + """ + Predict masks given image and prompt embeddings. + + Arguments: + image_embeddings (torch.Tensor): the embeddings from the image encoder + image_pe (torch.Tensor): positional encoding with the shape of image_embeddings + sparse_prompt_embeddings (torch.Tensor): the embeddings of the points and boxes + dense_prompt_embeddings (torch.Tensor): the embeddings of the mask inputs + multimask_output (bool): Whether to return multiple masks or a single + mask. + + Returns: + torch.Tensor: batched predicted masks + torch.Tensor: batched predictions of mask quality + """ + masks, iou_pred = self.predict_masks( + image_embeddings=image_embeddings, + image_pe=image_pe, + sparse_prompt_embeddings=sparse_prompt_embeddings, + dense_prompt_embeddings=dense_prompt_embeddings, + ) + + # Select the correct mask or masks for output + if multimask_output: + mask_slice = slice(1, None) + else: + mask_slice = slice(0, 1) + masks = masks[:, mask_slice, :, :] + iou_pred = iou_pred[:, mask_slice] + + # Prepare output + return masks, iou_pred + + def predict_masks( + self, + image_embeddings: torch.Tensor, + image_pe: torch.Tensor, + sparse_prompt_embeddings: torch.Tensor, + dense_prompt_embeddings: torch.Tensor, + ) -> Tuple[torch.Tensor, torch.Tensor]: + """Predicts masks. See 'forward' for more details.""" + # Concatenate output tokens + output_tokens = torch.cat( + [self.iou_token.weight, self.mask_tokens.weight], dim=0 + ) + output_tokens = output_tokens.unsqueeze(0).expand( + sparse_prompt_embeddings.size(0), -1, -1 + ) + + tokens = torch.cat((output_tokens, sparse_prompt_embeddings), dim=1) + + # image_embeddings: [1, C, H, W], tokens: [B, N, C] + # dense_prompt_embeddings: [B, C, H, W] + # Expand per-image data in batch direction to be per-mask + src = torch.repeat_interleave(image_embeddings, tokens.shape[0], dim=0) + src = src + dense_prompt_embeddings + pos_src = torch.repeat_interleave(image_pe, tokens.shape[0], dim=0) + b, c, h, w = src.shape + + # Run the transformer + hs, src = self.transformer(src, pos_src, tokens) + iou_token_out = hs[:, 0, :] + mask_tokens_out = hs[:, 1 : (1 + self.num_mask_tokens), :] + + # Upscale mask embeddings and predict masks using the mask tokens + src = src.transpose(1, 2).view(b, c, h, w) + upscaled_embedding = self.output_upscaling(src) + hyper_in_list: List[torch.Tensor] = [] + for i in range(self.num_mask_tokens): + hyper_in_list.append( + self.output_hypernetworks_mlps[i](mask_tokens_out[:, i, :]) + ) + hyper_in = torch.stack(hyper_in_list, dim=1) + b, c, h, w = upscaled_embedding.shape + masks = (hyper_in @ upscaled_embedding.view(b, c, h * w)).view( + b, self.num_mask_tokens, h, w + ) + + # Generate mask quality predictions + iou_pred = self.iou_prediction_head(iou_token_out) + + return masks, iou_pred + + +# Lightly adapted from +# https://github.com/facebookresearch/MaskFormer/blob/main/mask_former/modeling/transformer/transformer_predictor.py # noqa +class MLP(nn.Module): + def __init__( + self, + input_dim: int, + hidden_dim: int, + output_dim: int, + num_layers: int, + sigmoid_output: bool = False, + ) -> None: + super().__init__() + self.num_layers = num_layers + h = [hidden_dim] * (num_layers - 1) + self.layers = nn.ModuleList( + nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim]) + ) + self.sigmoid_output = sigmoid_output + + def forward(self, x): + for i, layer in enumerate(self.layers): + x = F.relu(layer(x)) if i < self.num_layers - 1 else layer(x) + if self.sigmoid_output: + x = F.sigmoid(x) + return x diff --git a/py/evf_sam/model/segment_anything/modeling/prompt_encoder.py b/py/evf_sam/model/segment_anything/modeling/prompt_encoder.py new file mode 100644 index 0000000..16bc3a4 --- /dev/null +++ b/py/evf_sam/model/segment_anything/modeling/prompt_encoder.py @@ -0,0 +1,238 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +from typing import Any, Optional, Tuple, Type + +import numpy as np +import torch +from torch import nn + +from .common import LayerNorm2d + + +class PromptEncoder(nn.Module): + def __init__( + self, + embed_dim: int, + image_embedding_size: Tuple[int, int], + input_image_size: Tuple[int, int], + mask_in_chans: int, + activation: Type[nn.Module] = nn.GELU, + ) -> None: + """ + Encodes prompts for input to SAM's mask decoder. + + Arguments: + embed_dim (int): The prompts' embedding dimension + image_embedding_size (tuple(int, int)): The spatial size of the + image embedding, as (H, W). + input_image_size (int): The padded size of the image as input + to the image encoder, as (H, W). + mask_in_chans (int): The number of hidden channels used for + encoding input masks. + activation (nn.Module): The activation to use when encoding + input masks. + """ + super().__init__() + self.embed_dim = embed_dim + self.input_image_size = input_image_size + self.image_embedding_size = image_embedding_size + self.pe_layer = PositionEmbeddingRandom(embed_dim // 2) + + self.num_point_embeddings: int = 4 # pos/neg point + 2 box corners + point_embeddings = [ + nn.Embedding(1, embed_dim) for i in range(self.num_point_embeddings) + ] + self.point_embeddings = nn.ModuleList(point_embeddings) + self.not_a_point_embed = nn.Embedding(1, embed_dim) + + self.mask_input_size = ( + 4 * image_embedding_size[0], + 4 * image_embedding_size[1], + ) + self.mask_downscaling = nn.Sequential( + nn.Conv2d(1, mask_in_chans // 4, kernel_size=2, stride=2), + LayerNorm2d(mask_in_chans // 4), + activation(), + nn.Conv2d(mask_in_chans // 4, mask_in_chans, kernel_size=2, stride=2), + LayerNorm2d(mask_in_chans), + activation(), + nn.Conv2d(mask_in_chans, embed_dim, kernel_size=1), + ) + self.no_mask_embed = nn.Embedding(1, embed_dim) + + def get_dense_pe(self) -> torch.Tensor: + """ + Returns the positional encoding used to encode point prompts, + applied to a dense set of points the shape of the image encoding. + + Returns: + torch.Tensor: Positional encoding with shape + 1x(embed_dim)x(embedding_h)x(embedding_w) + """ + return self.pe_layer(self.image_embedding_size).unsqueeze(0) + + def _embed_points( + self, + points: torch.Tensor, + labels: torch.Tensor, + pad: bool, + ) -> torch.Tensor: + """Embeds point prompts.""" + points = points + 0.5 # Shift to center of pixel + if pad: + padding_point = torch.zeros((points.shape[0], 1, 2), device=points.device) + padding_label = -torch.ones((labels.shape[0], 1), device=labels.device) + points = torch.cat([points, padding_point], dim=1) + labels = torch.cat([labels, padding_label], dim=1) + point_embedding = self.pe_layer.forward_with_coords( + points, self.input_image_size + ) + point_embedding[labels == -1] = 0.0 + point_embedding[labels == -1] += self.not_a_point_embed.weight + point_embedding[labels == 0] += self.point_embeddings[0].weight + point_embedding[labels == 1] += self.point_embeddings[1].weight + return point_embedding + + def _embed_boxes(self, boxes: torch.Tensor) -> torch.Tensor: + """Embeds box prompts.""" + boxes = boxes + 0.5 # Shift to center of pixel + coords = boxes.reshape(-1, 2, 2) + corner_embedding = self.pe_layer.forward_with_coords( + coords, self.input_image_size + ) + corner_embedding[:, 0, :] += self.point_embeddings[2].weight + corner_embedding[:, 1, :] += self.point_embeddings[3].weight + return corner_embedding + + def _embed_masks(self, masks: torch.Tensor) -> torch.Tensor: + """Embeds mask inputs.""" + mask_embedding = self.mask_downscaling(masks) + return mask_embedding + + def _get_batch_size( + self, + points: Optional[Tuple[torch.Tensor, torch.Tensor]], + boxes: Optional[torch.Tensor], + masks: Optional[torch.Tensor], + text_embeds: Optional[torch.Tensor], + ) -> int: + """ + Gets the batch size of the output given the batch size of the input prompts. + """ + if points is not None: + return points[0].shape[0] + elif boxes is not None: + return boxes.shape[0] + elif masks is not None: + return masks.shape[0] + elif text_embeds is not None: + return text_embeds.shape[0] + else: + return 1 + + def _get_device(self) -> torch.device: + return self.point_embeddings[0].weight.device + + def forward( + self, + points: Optional[Tuple[torch.Tensor, torch.Tensor]], + boxes: Optional[torch.Tensor], + masks: Optional[torch.Tensor], + text_embeds: Optional[torch.Tensor], + ) -> Tuple[torch.Tensor, torch.Tensor]: + """ + Embeds different types of prompts, returning both sparse and dense + embeddings. + + Arguments: + points (tuple(torch.Tensor, torch.Tensor) or none): point coordinates + and labels to embed. + boxes (torch.Tensor or none): boxes to embed + masks (torch.Tensor or none): masks to embed + + Returns: + torch.Tensor: sparse embeddings for the points and boxes, with shape + BxNx(embed_dim), where N is determined by the number of input points + and boxes. + torch.Tensor: dense embeddings for the masks, in the shape + Bx(embed_dim)x(embed_H)x(embed_W) + """ + bs = self._get_batch_size(points, boxes, masks, text_embeds) + sparse_embeddings = torch.empty( + (bs, 0, self.embed_dim), device=self._get_device() + ) + if points is not None: + coords, labels = points + point_embeddings = self._embed_points(coords, labels, pad=(boxes is None)) + sparse_embeddings = torch.cat([sparse_embeddings, point_embeddings], dim=1) + if boxes is not None: + box_embeddings = self._embed_boxes(boxes) + sparse_embeddings = torch.cat([sparse_embeddings, box_embeddings], dim=1) + + if text_embeds is not None: + sparse_embeddings = torch.cat([sparse_embeddings, text_embeds], dim=1) + + if masks is not None: + dense_embeddings = self._embed_masks(masks) + else: + dense_embeddings = self.no_mask_embed.weight.reshape(1, -1, 1, 1).expand( + bs, -1, self.image_embedding_size[0], self.image_embedding_size[1] + ) + + return sparse_embeddings, dense_embeddings + + +class PositionEmbeddingRandom(nn.Module): + """ + Positional encoding using random spatial frequencies. + """ + + def __init__(self, num_pos_feats: int = 64, scale: Optional[float] = None) -> None: + super().__init__() + if scale is None or scale <= 0.0: + scale = 1.0 + self.register_buffer( + "positional_encoding_gaussian_matrix", + scale * torch.randn((2, num_pos_feats)), + ) + + def _pe_encoding(self, coords: torch.Tensor) -> torch.Tensor: + """Positionally encode points that are normalized to [0,1].""" + # assuming coords are in [0, 1]^2 square and have d_1 x ... x d_n x 2 shape + coords = 2 * coords - 1 + + if coords.dtype != self.positional_encoding_gaussian_matrix.dtype: + coords = coords.to(self.positional_encoding_gaussian_matrix.dtype) + + coords = coords @ self.positional_encoding_gaussian_matrix + coords = 2 * np.pi * coords + # outputs d_1 x ... x d_n x C shape + return torch.cat([torch.sin(coords), torch.cos(coords)], dim=-1) + + def forward(self, size: Tuple[int, int]) -> torch.Tensor: + """Generate positional encoding for a grid of the specified size.""" + h, w = size + device: Any = self.positional_encoding_gaussian_matrix.device + grid = torch.ones( + (h, w), device=device, dtype=self.positional_encoding_gaussian_matrix.dtype + ) + y_embed = grid.cumsum(dim=0) - 0.5 + x_embed = grid.cumsum(dim=1) - 0.5 + y_embed = y_embed / h + x_embed = x_embed / w + + pe = self._pe_encoding(torch.stack([x_embed, y_embed], dim=-1)) + return pe.permute(2, 0, 1) # C x H x W + + def forward_with_coords( + self, coords_input: torch.Tensor, image_size: Tuple[int, int] + ) -> torch.Tensor: + """Positionally encode points that are not normalized to [0,1].""" + coords = coords_input.clone() + coords[:, :, 0] = coords[:, :, 0] / image_size[1] + coords[:, :, 1] = coords[:, :, 1] / image_size[0] + return self._pe_encoding(coords.to(torch.float)) # B x N x C diff --git a/py/evf_sam/model/segment_anything/modeling/sam.py b/py/evf_sam/model/segment_anything/modeling/sam.py new file mode 100644 index 0000000..f1d82ca --- /dev/null +++ b/py/evf_sam/model/segment_anything/modeling/sam.py @@ -0,0 +1,184 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +from typing import Any, Dict, List, Tuple + +import torch +from torch import nn +from torch.nn import functional as F + +from .image_encoder import ImageEncoderViT +from .mask_decoder import MaskDecoder +from .prompt_encoder import PromptEncoder + + +class Sam(nn.Module): + mask_threshold: float = 0.0 + image_format: str = "RGB" + + def __init__( + self, + image_encoder: ImageEncoderViT, + prompt_encoder: PromptEncoder, + mask_decoder: MaskDecoder, + pixel_mean: List[float] = [123.675, 116.28, 103.53], + pixel_std: List[float] = [58.395, 57.12, 57.375], + ) -> None: + """ + SAM predicts object masks from an image and input prompts. + + Arguments: + image_encoder (ImageEncoderViT): The backbone used to encode the + image into image embeddings that allow for efficient mask prediction. + prompt_encoder (PromptEncoder): Encodes various types of input prompts. + mask_decoder (MaskDecoder): Predicts masks from the image embeddings + and encoded prompts. + pixel_mean (list(float)): Mean values for normalizing pixels in the input image. + pixel_std (list(float)): Std values for normalizing pixels in the input image. + """ + super().__init__() + self.image_encoder = image_encoder + self.prompt_encoder = prompt_encoder + self.mask_decoder = mask_decoder + self.register_buffer( + "pixel_mean", torch.Tensor(pixel_mean).view(-1, 1, 1), False + ) + self.register_buffer("pixel_std", torch.Tensor(pixel_std).view(-1, 1, 1), False) + + @property + def device(self) -> Any: + return self.pixel_mean.device + + @torch.no_grad() + def forward( + self, + batched_input: List[Dict[str, Any]], + multimask_output: bool, + ) -> List[Dict[str, torch.Tensor]]: + """ + Predicts masks end-to-end from provided images and prompts. + If prompts are not known in advance, using SamPredictor is + recommended over calling the model directly. + + Arguments: + batched_input (list(dict)): A list over input images, each a + dictionary with the following keys. A prompt key can be + excluded if it is not present. + 'image': The image as a torch tensor in 3xHxW format, + already transformed for input to the model. + 'original_size': (tuple(int, int)) The original size of + the image before transformation, as (H, W). + 'point_coords': (torch.Tensor) Batched point prompts for + this image, with shape BxNx2. Already transformed to the + input frame of the model. + 'point_labels': (torch.Tensor) Batched labels for point prompts, + with shape BxN. + 'boxes': (torch.Tensor) Batched box inputs, with shape Bx4. + Already transformed to the input frame of the model. + 'mask_inputs': (torch.Tensor) Batched mask inputs to the model, + in the form Bx1xHxW. + multimask_output (bool): Whether the model should predict multiple + disambiguating masks, or return a single mask. + + Returns: + (list(dict)): A list over input images, where each element is + as dictionary with the following keys. + 'masks': (torch.Tensor) Batched binary mask predictions, + with shape BxCxHxW, where B is the number of input prompts, + C is determined by multimask_output, and (H, W) is the + original size of the image. + 'iou_predictions': (torch.Tensor) The model's predictions + of mask quality, in shape BxC. + 'low_res_logits': (torch.Tensor) Low resolution logits with + shape BxCxHxW, where H=W=256. Can be passed as mask input + to subsequent iterations of prediction. + """ + input_images = torch.stack( + [self.preprocess(x["image"]) for x in batched_input], dim=0 + ) + image_embeddings = self.image_encoder(input_images) + + outputs = [] + for image_record, curr_embedding in zip(batched_input, image_embeddings): + if "point_coords" in image_record: + points = (image_record["point_coords"], image_record["point_labels"]) + else: + points = None + sparse_embeddings, dense_embeddings = self.prompt_encoder( + points=points, + boxes=image_record.get("boxes", None), + masks=image_record.get("mask_inputs", None), + ) + low_res_masks, iou_predictions = self.mask_decoder( + image_embeddings=curr_embedding.unsqueeze(0), + image_pe=self.prompt_encoder.get_dense_pe(), + sparse_prompt_embeddings=sparse_embeddings, + dense_prompt_embeddings=dense_embeddings, + multimask_output=multimask_output, + ) + masks = self.postprocess_masks( + low_res_masks, + input_size=image_record["image"].shape[-2:], + original_size=image_record["original_size"], + ) + masks = masks > self.mask_threshold + outputs.append( + { + "masks": masks, + "iou_predictions": iou_predictions, + "low_res_logits": low_res_masks, + } + ) + return outputs + + def postprocess_masks( + self, + masks: torch.Tensor, + input_size: Tuple[int, ...], + original_size: Tuple[int, ...], + ) -> torch.Tensor: + """ + Remove padding and upscale masks to the original image size. + + Arguments: + masks (torch.Tensor): Batched masks from the mask_decoder, + in BxCxHxW format. + input_size (tuple(int, int)): The size of the image input to the + model, in (H, W) format. Used to remove padding. + original_size (tuple(int, int)): The original size of the image + before resizing for input to the model, in (H, W) format. + + Returns: + (torch.Tensor): Batched masks in BxCxHxW format, where (H, W) + is given by original_size. + """ + + dtype = masks.dtype + + masks = F.interpolate( + masks.float(), + (self.image_encoder.img_size, self.image_encoder.img_size), + mode="bilinear", + align_corners=False, + ) + # masks = masks.to(dtype) + masks = masks[..., : input_size[0], : input_size[1]] + masks = F.interpolate( + masks, original_size, mode="bilinear", align_corners=False + ) + return masks + + def preprocess(self, x: torch.Tensor) -> torch.Tensor: + """Normalize pixel values and pad to a square input.""" + # Normalize colors + x = (x - self.pixel_mean) / self.pixel_std + + # Pad + h, w = x.shape[-2:] + padh = self.image_encoder.img_size - h + padw = self.image_encoder.img_size - w + x = F.pad(x, (0, padw, 0, padh)) + return x diff --git a/py/evf_sam/model/segment_anything/modeling/transformer.py b/py/evf_sam/model/segment_anything/modeling/transformer.py new file mode 100644 index 0000000..8c511e4 --- /dev/null +++ b/py/evf_sam/model/segment_anything/modeling/transformer.py @@ -0,0 +1,242 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import math +from typing import Tuple, Type + +import torch +from torch import Tensor, nn + +from .common import MLPBlock + + +class TwoWayTransformer(nn.Module): + def __init__( + self, + depth: int, + embedding_dim: int, + num_heads: int, + mlp_dim: int, + activation: Type[nn.Module] = nn.ReLU, + attention_downsample_rate: int = 2, + ) -> None: + """ + A transformer decoder that attends to an input image using + queries whose positional embedding is supplied. + + Args: + depth (int): number of layers in the transformer + embedding_dim (int): the channel dimension for the input embeddings + num_heads (int): the number of heads for multihead attention. Must + divide embedding_dim + mlp_dim (int): the channel dimension internal to the MLP block + activation (nn.Module): the activation to use in the MLP block + """ + super().__init__() + self.depth = depth + self.embedding_dim = embedding_dim + self.num_heads = num_heads + self.mlp_dim = mlp_dim + self.layers = nn.ModuleList() + + for i in range(depth): + self.layers.append( + TwoWayAttentionBlock( + embedding_dim=embedding_dim, + num_heads=num_heads, + mlp_dim=mlp_dim, + activation=activation, + attention_downsample_rate=attention_downsample_rate, + skip_first_layer_pe=(i == 0), + ) + ) + + self.final_attn_token_to_image = Attention( + embedding_dim, num_heads, downsample_rate=attention_downsample_rate + ) + self.norm_final_attn = nn.LayerNorm(embedding_dim) + + def forward( + self, + image_embedding: Tensor, + image_pe: Tensor, + point_embedding: Tensor, + ) -> Tuple[Tensor, Tensor]: + """ + Args: + image_embedding (torch.Tensor): image to attend to. Should be shape + B x embedding_dim x h x w for any h and w. + image_pe (torch.Tensor): the positional encoding to add to the image. Must + have the same shape as image_embedding. + point_embedding (torch.Tensor): the embedding to add to the query points. + Must have shape B x N_points x embedding_dim for any N_points. + + Returns: + torch.Tensor: the processed point_embedding + torch.Tensor: the processed image_embedding + """ + # BxCxHxW -> BxHWxC == B x N_image_tokens x C + bs, c, h, w = image_embedding.shape + image_embedding = image_embedding.flatten(2).permute(0, 2, 1) + image_pe = image_pe.flatten(2).permute(0, 2, 1) + + # Prepare queries + queries = point_embedding + keys = image_embedding + + # Apply transformer blocks and final layernorm + for layer in self.layers: + queries, keys = layer( + queries=queries, + keys=keys, + query_pe=point_embedding, + key_pe=image_pe, + ) + + # Apply the final attention layer from the points to the image + q = queries + point_embedding + k = keys + image_pe + attn_out = self.final_attn_token_to_image(q=q, k=k, v=keys) + queries = queries + attn_out + queries = self.norm_final_attn(queries) + + return queries, keys + + +class TwoWayAttentionBlock(nn.Module): + def __init__( + self, + embedding_dim: int, + num_heads: int, + mlp_dim: int = 2048, + activation: Type[nn.Module] = nn.ReLU, + attention_downsample_rate: int = 2, + skip_first_layer_pe: bool = False, + ) -> None: + """ + A transformer block with four layers: (1) self-attention of sparse + inputs, (2) cross attention of sparse inputs to dense inputs, (3) mlp + block on sparse inputs, and (4) cross attention of dense inputs to sparse + inputs. + + Arguments: + embedding_dim (int): the channel dimension of the embeddings + num_heads (int): the number of heads in the attention layers + mlp_dim (int): the hidden dimension of the mlp block + activation (nn.Module): the activation of the mlp block + skip_first_layer_pe (bool): skip the PE on the first layer + """ + super().__init__() + self.self_attn = Attention(embedding_dim, num_heads) + self.norm1 = nn.LayerNorm(embedding_dim) + + self.cross_attn_token_to_image = Attention( + embedding_dim, num_heads, downsample_rate=attention_downsample_rate + ) + self.norm2 = nn.LayerNorm(embedding_dim) + + self.mlp = MLPBlock(embedding_dim, mlp_dim, activation) + self.norm3 = nn.LayerNorm(embedding_dim) + + self.norm4 = nn.LayerNorm(embedding_dim) + self.cross_attn_image_to_token = Attention( + embedding_dim, num_heads, downsample_rate=attention_downsample_rate + ) + + self.skip_first_layer_pe = skip_first_layer_pe + + def forward( + self, queries: Tensor, keys: Tensor, query_pe: Tensor, key_pe: Tensor + ) -> Tuple[Tensor, Tensor]: + # Self attention block + if self.skip_first_layer_pe: + queries = self.self_attn(q=queries, k=queries, v=queries) + else: + q = queries + query_pe + attn_out = self.self_attn(q=q, k=q, v=queries) + queries = queries + attn_out + queries = self.norm1(queries) + + # Cross attention block, tokens attending to image embedding + q = queries + query_pe + k = keys + key_pe + attn_out = self.cross_attn_token_to_image(q=q, k=k, v=keys) + queries = queries + attn_out + queries = self.norm2(queries) + + # MLP block + mlp_out = self.mlp(queries) + queries = queries + mlp_out + queries = self.norm3(queries) + + # Cross attention block, image embedding attending to tokens + q = queries + query_pe + k = keys + key_pe + attn_out = self.cross_attn_image_to_token(q=k, k=q, v=queries) + keys = keys + attn_out + keys = self.norm4(keys) + + return queries, keys + + +class Attention(nn.Module): + """ + An attention layer that allows for downscaling the size of the embedding + after projection to queries, keys, and values. + """ + + def __init__( + self, + embedding_dim: int, + num_heads: int, + downsample_rate: int = 1, + ) -> None: + super().__init__() + self.embedding_dim = embedding_dim + self.internal_dim = embedding_dim // downsample_rate + self.num_heads = num_heads + assert ( + self.internal_dim % num_heads == 0 + ), "num_heads must divide embedding_dim." + + self.q_proj = nn.Linear(embedding_dim, self.internal_dim) + self.k_proj = nn.Linear(embedding_dim, self.internal_dim) + self.v_proj = nn.Linear(embedding_dim, self.internal_dim) + self.out_proj = nn.Linear(self.internal_dim, embedding_dim) + + def _separate_heads(self, x: Tensor, num_heads: int) -> Tensor: + b, n, c = x.shape + x = x.reshape(b, n, num_heads, c // num_heads) + return x.transpose(1, 2) # B x N_heads x N_tokens x C_per_head + + def _recombine_heads(self, x: Tensor) -> Tensor: + b, n_heads, n_tokens, c_per_head = x.shape + x = x.transpose(1, 2) + return x.reshape(b, n_tokens, n_heads * c_per_head) # B x N_tokens x C + + def forward(self, q: Tensor, k: Tensor, v: Tensor) -> Tensor: + # Input projections + q = self.q_proj(q) + k = self.k_proj(k) + v = self.v_proj(v) + + # Separate into heads + q = self._separate_heads(q, self.num_heads) + k = self._separate_heads(k, self.num_heads) + v = self._separate_heads(v, self.num_heads) + + # Attention + _, _, _, c_per_head = q.shape + attn = q @ k.permute(0, 1, 3, 2) # B x N_heads x N_tokens x N_tokens + attn = attn / math.sqrt(c_per_head) + attn = torch.softmax(attn, dim=-1) + + # Get output + out = attn @ v + out = self._recombine_heads(out) + out = self.out_proj(out) + + return out diff --git a/py/evf_sam/model/segment_anything/predictor.py b/py/evf_sam/model/segment_anything/predictor.py new file mode 100644 index 0000000..bf52d81 --- /dev/null +++ b/py/evf_sam/model/segment_anything/predictor.py @@ -0,0 +1,284 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +from typing import Optional, Tuple + +import numpy as np +import torch + +from .modeling import Sam +from .utils.transforms import ResizeLongestSide + + +class SamPredictor: + def __init__( + self, + sam_model: Sam, + ) -> None: + """ + Uses SAM to calculate the image embedding for an image, and then + allow repeated, efficient mask prediction given prompts. + + Arguments: + sam_model (Sam): The model to use for mask prediction. + """ + super().__init__() + self.model = sam_model + self.transform = ResizeLongestSide(sam_model.image_encoder.img_size) + self.reset_image() + + def set_image( + self, + image: np.ndarray, + image_format: str = "RGB", + ) -> None: + """ + Calculates the image embeddings for the provided image, allowing + masks to be predicted with the 'predict' method. + + Arguments: + image (np.ndarray): The image for calculating masks. Expects an + image in HWC uint8 format, with pixel values in [0, 255]. + image_format (str): The color format of the image, in ['RGB', 'BGR']. + """ + assert image_format in [ + "RGB", + "BGR", + ], f"image_format must be in ['RGB', 'BGR'], is {image_format}." + if image_format != self.model.image_format: + image = image[..., ::-1] + + # Transform the image to the form expected by the model + input_image = self.transform.apply_image(image) + input_image_torch = torch.as_tensor(input_image, device=self.device) + input_image_torch = input_image_torch.permute(2, 0, 1).contiguous()[ + None, :, :, : + ] + + self.set_torch_image(input_image_torch, image.shape[:2]) + + @torch.no_grad() + def set_torch_image( + self, + transformed_image: torch.Tensor, + original_image_size: Tuple[int, ...], + ) -> None: + """ + Calculates the image embeddings for the provided image, allowing + masks to be predicted with the 'predict' method. Expects the input + image to be already transformed to the format expected by the model. + + Arguments: + transformed_image (torch.Tensor): The input image, with shape + 1x3xHxW, which has been transformed with ResizeLongestSide. + original_image_size (tuple(int, int)): The size of the image + before transformation, in (H, W) format. + """ + assert ( + len(transformed_image.shape) == 4 + and transformed_image.shape[1] == 3 + and max(*transformed_image.shape[2:]) == self.model.image_encoder.img_size + ), f"set_torch_image input must be BCHW with long side {self.model.image_encoder.img_size}." + self.reset_image() + + self.original_size = original_image_size + self.input_size = tuple(transformed_image.shape[-2:]) + input_image = self.model.preprocess(transformed_image) + self.features = self.model.image_encoder(input_image) + self.is_image_set = True + + def predict( + self, + point_coords: Optional[np.ndarray] = None, + point_labels: Optional[np.ndarray] = None, + box: Optional[np.ndarray] = None, + mask_input: Optional[np.ndarray] = None, + multimask_output: bool = True, + return_logits: bool = False, + ) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: + """ + Predict masks for the given input prompts, using the currently set image. + + Arguments: + point_coords (np.ndarray or None): A Nx2 array of point prompts to the + model. Each point is in (X,Y) in pixels. + point_labels (np.ndarray or None): A length N array of labels for the + point prompts. 1 indicates a foreground point and 0 indicates a + background point. + box (np.ndarray or None): A length 4 array given a box prompt to the + model, in XYXY format. + mask_input (np.ndarray): A low resolution mask input to the model, typically + coming from a previous prediction iteration. Has form 1xHxW, where + for SAM, H=W=256. + multimask_output (bool): If true, the model will return three masks. + For ambiguous input prompts (such as a single click), this will often + produce better masks than a single prediction. If only a single + mask is needed, the model's predicted quality score can be used + to select the best mask. For non-ambiguous prompts, such as multiple + input prompts, multimask_output=False can give better results. + return_logits (bool): If true, returns un-thresholded masks logits + instead of a binary mask. + + Returns: + (np.ndarray): The output masks in CxHxW format, where C is the + number of masks, and (H, W) is the original image size. + (np.ndarray): An array of length C containing the model's + predictions for the quality of each mask. + (np.ndarray): An array of shape CxHxW, where C is the number + of masks and H=W=256. These low resolution logits can be passed to + a subsequent iteration as mask input. + """ + if not self.is_image_set: + raise RuntimeError( + "An image must be set with .set_image(...) before mask prediction." + ) + + # Transform input prompts + coords_torch, labels_torch, box_torch, mask_input_torch = None, None, None, None + if point_coords is not None: + assert ( + point_labels is not None + ), "point_labels must be supplied if point_coords is supplied." + point_coords = self.transform.apply_coords(point_coords, self.original_size) + coords_torch = torch.as_tensor( + point_coords, dtype=torch.float, device=self.device + ) + labels_torch = torch.as_tensor( + point_labels, dtype=torch.int, device=self.device + ) + coords_torch, labels_torch = coords_torch[None, :, :], labels_torch[None, :] + if box is not None: + box = self.transform.apply_boxes(box, self.original_size) + box_torch = torch.as_tensor(box, dtype=torch.float, device=self.device) + box_torch = box_torch[None, :] + if mask_input is not None: + mask_input_torch = torch.as_tensor( + mask_input, dtype=torch.float, device=self.device + ) + mask_input_torch = mask_input_torch[None, :, :, :] + + masks, iou_predictions, low_res_masks = self.predict_torch( + coords_torch, + labels_torch, + box_torch, + mask_input_torch, + multimask_output, + return_logits=return_logits, + ) + + masks_np = masks[0].detach().cpu().numpy() + iou_predictions_np = iou_predictions[0].detach().cpu().numpy() + low_res_masks_np = low_res_masks[0].detach().cpu().numpy() + return masks_np, iou_predictions_np, low_res_masks_np + + @torch.no_grad() + def predict_torch( + self, + point_coords: Optional[torch.Tensor], + point_labels: Optional[torch.Tensor], + boxes: Optional[torch.Tensor] = None, + mask_input: Optional[torch.Tensor] = None, + multimask_output: bool = True, + return_logits: bool = False, + ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """ + Predict masks for the given input prompts, using the currently set image. + Input prompts are batched torch tensors and are expected to already be + transformed to the input frame using ResizeLongestSide. + + Arguments: + point_coords (torch.Tensor or None): A BxNx2 array of point prompts to the + model. Each point is in (X,Y) in pixels. + point_labels (torch.Tensor or None): A BxN array of labels for the + point prompts. 1 indicates a foreground point and 0 indicates a + background point. + boxes (np.ndarray or None): A Bx4 array given a box prompt to the + model, in XYXY format. + mask_input (np.ndarray): A low resolution mask input to the model, typically + coming from a previous prediction iteration. Has form Bx1xHxW, where + for SAM, H=W=256. Masks returned by a previous iteration of the + predict method do not need further transformation. + multimask_output (bool): If true, the model will return three masks. + For ambiguous input prompts (such as a single click), this will often + produce better masks than a single prediction. If only a single + mask is needed, the model's predicted quality score can be used + to select the best mask. For non-ambiguous prompts, such as multiple + input prompts, multimask_output=False can give better results. + return_logits (bool): If true, returns un-thresholded masks logits + instead of a binary mask. + + Returns: + (torch.Tensor): The output masks in BxCxHxW format, where C is the + number of masks, and (H, W) is the original image size. + (torch.Tensor): An array of shape BxC containing the model's + predictions for the quality of each mask. + (torch.Tensor): An array of shape BxCxHxW, where C is the number + of masks and H=W=256. These low res logits can be passed to + a subsequent iteration as mask input. + """ + if not self.is_image_set: + raise RuntimeError( + "An image must be set with .set_image(...) before mask prediction." + ) + + if point_coords is not None: + points = (point_coords, point_labels) + else: + points = None + + # Embed prompts + sparse_embeddings, dense_embeddings = self.model.prompt_encoder( + points=points, + boxes=boxes, + masks=mask_input, + ) + + # Predict masks + low_res_masks, iou_predictions = self.model.mask_decoder( + image_embeddings=self.features, + image_pe=self.model.prompt_encoder.get_dense_pe(), + sparse_prompt_embeddings=sparse_embeddings, + dense_prompt_embeddings=dense_embeddings, + multimask_output=multimask_output, + ) + + # Upscale the masks to the original image resolution + masks = self.model.postprocess_masks( + low_res_masks, self.input_size, self.original_size + ) + + if not return_logits: + masks = masks > self.model.mask_threshold + + return masks, iou_predictions, low_res_masks + + def get_image_embedding(self) -> torch.Tensor: + """ + Returns the image embeddings for the currently set image, with + shape 1xCxHxW, where C is the embedding dimension and (H,W) are + the embedding spatial dimension of SAM (typically C=256, H=W=64). + """ + if not self.is_image_set: + raise RuntimeError( + "An image must be set with .set_image(...) to generate an embedding." + ) + assert ( + self.features is not None + ), "Features must exist if an image has been set." + return self.features + + @property + def device(self) -> torch.device: + return self.model.device + + def reset_image(self) -> None: + """Resets the currently set image.""" + self.is_image_set = False + self.features = None + self.orig_h = None + self.orig_w = None + self.input_h = None + self.input_w = None diff --git a/py/evf_sam/model/segment_anything/utils/__init__.py b/py/evf_sam/model/segment_anything/utils/__init__.py new file mode 100644 index 0000000..5277f46 --- /dev/null +++ b/py/evf_sam/model/segment_anything/utils/__init__.py @@ -0,0 +1,5 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. diff --git a/py/evf_sam/model/segment_anything/utils/amg.py b/py/evf_sam/model/segment_anything/utils/amg.py new file mode 100644 index 0000000..5c3bc5d --- /dev/null +++ b/py/evf_sam/model/segment_anything/utils/amg.py @@ -0,0 +1,346 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import math +from copy import deepcopy +from itertools import product +from typing import Any, Dict, Generator, ItemsView, List, Tuple + +import numpy as np +import torch + + +class MaskData: + """ + A structure for storing masks and their related data in batched format. + Implements basic filtering and concatenation. + """ + + def __init__(self, **kwargs) -> None: + for v in kwargs.values(): + assert isinstance( + v, (list, np.ndarray, torch.Tensor) + ), "MaskData only supports list, numpy arrays, and torch tensors." + self._stats = dict(**kwargs) + + def __setitem__(self, key: str, item: Any) -> None: + assert isinstance( + item, (list, np.ndarray, torch.Tensor) + ), "MaskData only supports list, numpy arrays, and torch tensors." + self._stats[key] = item + + def __delitem__(self, key: str) -> None: + del self._stats[key] + + def __getitem__(self, key: str) -> Any: + return self._stats[key] + + def items(self) -> ItemsView[str, Any]: + return self._stats.items() + + def filter(self, keep: torch.Tensor) -> None: + for k, v in self._stats.items(): + if v is None: + self._stats[k] = None + elif isinstance(v, torch.Tensor): + self._stats[k] = v[torch.as_tensor(keep, device=v.device)] + elif isinstance(v, np.ndarray): + self._stats[k] = v[keep.detach().cpu().numpy()] + elif isinstance(v, list) and keep.dtype == torch.bool: + self._stats[k] = [a for i, a in enumerate(v) if keep[i]] + elif isinstance(v, list): + self._stats[k] = [v[i] for i in keep] + else: + raise TypeError(f"MaskData key {k} has an unsupported type {type(v)}.") + + def cat(self, new_stats: "MaskData") -> None: + for k, v in new_stats.items(): + if k not in self._stats or self._stats[k] is None: + self._stats[k] = deepcopy(v) + elif isinstance(v, torch.Tensor): + self._stats[k] = torch.cat([self._stats[k], v], dim=0) + elif isinstance(v, np.ndarray): + self._stats[k] = np.concatenate([self._stats[k], v], axis=0) + elif isinstance(v, list): + self._stats[k] = self._stats[k] + deepcopy(v) + else: + raise TypeError(f"MaskData key {k} has an unsupported type {type(v)}.") + + def to_numpy(self) -> None: + for k, v in self._stats.items(): + if isinstance(v, torch.Tensor): + self._stats[k] = v.detach().cpu().numpy() + + +def is_box_near_crop_edge( + boxes: torch.Tensor, crop_box: List[int], orig_box: List[int], atol: float = 20.0 +) -> torch.Tensor: + """Filter masks at the edge of a crop, but not at the edge of the original image.""" + crop_box_torch = torch.as_tensor(crop_box, dtype=torch.float, device=boxes.device) + orig_box_torch = torch.as_tensor(orig_box, dtype=torch.float, device=boxes.device) + boxes = uncrop_boxes_xyxy(boxes, crop_box).float() + near_crop_edge = torch.isclose(boxes, crop_box_torch[None, :], atol=atol, rtol=0) + near_image_edge = torch.isclose(boxes, orig_box_torch[None, :], atol=atol, rtol=0) + near_crop_edge = torch.logical_and(near_crop_edge, ~near_image_edge) + return torch.any(near_crop_edge, dim=1) + + +def box_xyxy_to_xywh(box_xyxy: torch.Tensor) -> torch.Tensor: + box_xywh = deepcopy(box_xyxy) + box_xywh[2] = box_xywh[2] - box_xywh[0] + box_xywh[3] = box_xywh[3] - box_xywh[1] + return box_xywh + + +def batch_iterator(batch_size: int, *args) -> Generator[List[Any], None, None]: + assert len(args) > 0 and all( + len(a) == len(args[0]) for a in args + ), "Batched iteration must have inputs of all the same size." + n_batches = len(args[0]) // batch_size + int(len(args[0]) % batch_size != 0) + for b in range(n_batches): + yield [arg[b * batch_size : (b + 1) * batch_size] for arg in args] + + +def mask_to_rle_pytorch(tensor: torch.Tensor) -> List[Dict[str, Any]]: + """ + Encodes masks to an uncompressed RLE, in the format expected by + pycoco tools. + """ + # Put in fortran order and flatten h,w + b, h, w = tensor.shape + tensor = tensor.permute(0, 2, 1).flatten(1) + + # Compute change indices + diff = tensor[:, 1:] ^ tensor[:, :-1] + change_indices = diff.nonzero() + + # Encode run length + out = [] + for i in range(b): + cur_idxs = change_indices[change_indices[:, 0] == i, 1] + cur_idxs = torch.cat( + [ + torch.tensor([0], dtype=cur_idxs.dtype, device=cur_idxs.device), + cur_idxs + 1, + torch.tensor([h * w], dtype=cur_idxs.dtype, device=cur_idxs.device), + ] + ) + btw_idxs = cur_idxs[1:] - cur_idxs[:-1] + counts = [] if tensor[i, 0] == 0 else [0] + counts.extend(btw_idxs.detach().cpu().tolist()) + out.append({"size": [h, w], "counts": counts}) + return out + + +def rle_to_mask(rle: Dict[str, Any]) -> np.ndarray: + """Compute a binary mask from an uncompressed RLE.""" + h, w = rle["size"] + mask = np.empty(h * w, dtype=bool) + idx = 0 + parity = False + for count in rle["counts"]: + mask[idx : idx + count] = parity + idx += count + parity ^= True + mask = mask.reshape(w, h) + return mask.transpose() # Put in C order + + +def area_from_rle(rle: Dict[str, Any]) -> int: + return sum(rle["counts"][1::2]) + + +def calculate_stability_score( + masks: torch.Tensor, mask_threshold: float, threshold_offset: float +) -> torch.Tensor: + """ + Computes the stability score for a batch of masks. The stability + score is the IoU between the binary masks obtained by thresholding + the predicted mask logits at high and low values. + """ + # One mask is always contained inside the other. + # Save memory by preventing unnecessary cast to torch.int64 + intersections = ( + (masks > (mask_threshold + threshold_offset)) + .sum(-1, dtype=torch.int16) + .sum(-1, dtype=torch.int32) + ) + unions = ( + (masks > (mask_threshold - threshold_offset)) + .sum(-1, dtype=torch.int16) + .sum(-1, dtype=torch.int32) + ) + return intersections / unions + + +def build_point_grid(n_per_side: int) -> np.ndarray: + """Generates a 2D grid of points evenly spaced in [0,1]x[0,1].""" + offset = 1 / (2 * n_per_side) + points_one_side = np.linspace(offset, 1 - offset, n_per_side) + points_x = np.tile(points_one_side[None, :], (n_per_side, 1)) + points_y = np.tile(points_one_side[:, None], (1, n_per_side)) + points = np.stack([points_x, points_y], axis=-1).reshape(-1, 2) + return points + + +def build_all_layer_point_grids( + n_per_side: int, n_layers: int, scale_per_layer: int +) -> List[np.ndarray]: + """Generates point grids for all crop layers.""" + points_by_layer = [] + for i in range(n_layers + 1): + n_points = int(n_per_side / (scale_per_layer**i)) + points_by_layer.append(build_point_grid(n_points)) + return points_by_layer + + +def generate_crop_boxes( + im_size: Tuple[int, ...], n_layers: int, overlap_ratio: float +) -> Tuple[List[List[int]], List[int]]: + """ + Generates a list of crop boxes of different sizes. Each layer + has (2**i)**2 boxes for the ith layer. + """ + crop_boxes, layer_idxs = [], [] + im_h, im_w = im_size + short_side = min(im_h, im_w) + + # Original image + crop_boxes.append([0, 0, im_w, im_h]) + layer_idxs.append(0) + + def crop_len(orig_len, n_crops, overlap): + return int(math.ceil((overlap * (n_crops - 1) + orig_len) / n_crops)) + + for i_layer in range(n_layers): + n_crops_per_side = 2 ** (i_layer + 1) + overlap = int(overlap_ratio * short_side * (2 / n_crops_per_side)) + + crop_w = crop_len(im_w, n_crops_per_side, overlap) + crop_h = crop_len(im_h, n_crops_per_side, overlap) + + crop_box_x0 = [int((crop_w - overlap) * i) for i in range(n_crops_per_side)] + crop_box_y0 = [int((crop_h - overlap) * i) for i in range(n_crops_per_side)] + + # Crops in XYWH format + for x0, y0 in product(crop_box_x0, crop_box_y0): + box = [x0, y0, min(x0 + crop_w, im_w), min(y0 + crop_h, im_h)] + crop_boxes.append(box) + layer_idxs.append(i_layer + 1) + + return crop_boxes, layer_idxs + + +def uncrop_boxes_xyxy(boxes: torch.Tensor, crop_box: List[int]) -> torch.Tensor: + x0, y0, _, _ = crop_box + offset = torch.tensor([[x0, y0, x0, y0]], device=boxes.device) + # Check if boxes has a channel dimension + if len(boxes.shape) == 3: + offset = offset.unsqueeze(1) + return boxes + offset + + +def uncrop_points(points: torch.Tensor, crop_box: List[int]) -> torch.Tensor: + x0, y0, _, _ = crop_box + offset = torch.tensor([[x0, y0]], device=points.device) + # Check if points has a channel dimension + if len(points.shape) == 3: + offset = offset.unsqueeze(1) + return points + offset + + +def uncrop_masks( + masks: torch.Tensor, crop_box: List[int], orig_h: int, orig_w: int +) -> torch.Tensor: + x0, y0, x1, y1 = crop_box + if x0 == 0 and y0 == 0 and x1 == orig_w and y1 == orig_h: + return masks + # Coordinate transform masks + pad_x, pad_y = orig_w - (x1 - x0), orig_h - (y1 - y0) + pad = (x0, pad_x - x0, y0, pad_y - y0) + return torch.nn.functional.pad(masks, pad, value=0) + + +def remove_small_regions( + mask: np.ndarray, area_thresh: float, mode: str +) -> Tuple[np.ndarray, bool]: + """ + Removes small disconnected regions and holes in a mask. Returns the + mask and an indicator of if the mask has been modified. + """ + import cv2 # type: ignore + + assert mode in ["holes", "islands"] + correct_holes = mode == "holes" + working_mask = (correct_holes ^ mask).astype(np.uint8) + n_labels, regions, stats, _ = cv2.connectedComponentsWithStats(working_mask, 8) + sizes = stats[:, -1][1:] # Row 0 is background label + small_regions = [i + 1 for i, s in enumerate(sizes) if s < area_thresh] + if len(small_regions) == 0: + return mask, False + fill_labels = [0] + small_regions + if not correct_holes: + fill_labels = [i for i in range(n_labels) if i not in fill_labels] + # If every region is below threshold, keep largest + if len(fill_labels) == 0: + fill_labels = [int(np.argmax(sizes)) + 1] + mask = np.isin(regions, fill_labels) + return mask, True + + +def coco_encode_rle(uncompressed_rle: Dict[str, Any]) -> Dict[str, Any]: + from pycocotools import mask as mask_utils # type: ignore + + h, w = uncompressed_rle["size"] + rle = mask_utils.frPyObjects(uncompressed_rle, h, w) + rle["counts"] = rle["counts"].decode("utf-8") # Necessary to serialize with json + return rle + + +def batched_mask_to_box(masks: torch.Tensor) -> torch.Tensor: + """ + Calculates boxes in XYXY format around masks. Return [0,0,0,0] for + an empty mask. For input shape C1xC2x...xHxW, the output shape is C1xC2x...x4. + """ + # torch.max below raises an error on empty inputs, just skip in this case + if torch.numel(masks) == 0: + return torch.zeros(*masks.shape[:-2], 4, device=masks.device) + + # Normalize shape to CxHxW + shape = masks.shape + h, w = shape[-2:] + if len(shape) > 2: + masks = masks.flatten(0, -3) + else: + masks = masks.unsqueeze(0) + + # Get top and bottom edges + in_height, _ = torch.max(masks, dim=-1) + in_height_coords = in_height * torch.arange(h, device=in_height.device)[None, :] + bottom_edges, _ = torch.max(in_height_coords, dim=-1) + in_height_coords = in_height_coords + h * (~in_height) + top_edges, _ = torch.min(in_height_coords, dim=-1) + + # Get left and right edges + in_width, _ = torch.max(masks, dim=-2) + in_width_coords = in_width * torch.arange(w, device=in_width.device)[None, :] + right_edges, _ = torch.max(in_width_coords, dim=-1) + in_width_coords = in_width_coords + w * (~in_width) + left_edges, _ = torch.min(in_width_coords, dim=-1) + + # If the mask is empty the right edge will be to the left of the left edge. + # Replace these boxes with [0, 0, 0, 0] + empty_filter = (right_edges < left_edges) | (bottom_edges < top_edges) + out = torch.stack([left_edges, top_edges, right_edges, bottom_edges], dim=-1) + out = out * (~empty_filter).unsqueeze(-1) + + # Return to original shape + if len(shape) > 2: + out = out.reshape(*shape[:-2], 4) + else: + out = out[0] + + return out diff --git a/py/evf_sam/model/segment_anything/utils/onnx.py b/py/evf_sam/model/segment_anything/utils/onnx.py new file mode 100644 index 0000000..3521208 --- /dev/null +++ b/py/evf_sam/model/segment_anything/utils/onnx.py @@ -0,0 +1,157 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +from typing import Tuple + +import torch +import torch.nn as nn +from torch.nn import functional as F + +from ..modeling import Sam +from .amg import calculate_stability_score + + +class SamOnnxModel(nn.Module): + """ + This model should not be called directly, but is used in ONNX export. + It combines the prompt encoder, mask decoder, and mask postprocessing of Sam, + with some functions modified to enable model tracing. Also supports extra + options controlling what information. See the ONNX export script for details. + """ + + def __init__( + self, + model: Sam, + return_single_mask: bool, + use_stability_score: bool = False, + return_extra_metrics: bool = False, + ) -> None: + super().__init__() + self.mask_decoder = model.mask_decoder + self.model = model + self.img_size = model.image_encoder.img_size + self.return_single_mask = return_single_mask + self.use_stability_score = use_stability_score + self.stability_score_offset = 1.0 + self.return_extra_metrics = return_extra_metrics + + @staticmethod + def resize_longest_image_size( + input_image_size: torch.Tensor, longest_side: int + ) -> torch.Tensor: + input_image_size = input_image_size.to(torch.float32) + scale = longest_side / torch.max(input_image_size) + transformed_size = scale * input_image_size + transformed_size = torch.floor(transformed_size + 0.5).to(torch.int64) + return transformed_size + + def _embed_points( + self, point_coords: torch.Tensor, point_labels: torch.Tensor + ) -> torch.Tensor: + point_coords = point_coords + 0.5 + point_coords = point_coords / self.img_size + point_embedding = self.model.prompt_encoder.pe_layer._pe_encoding(point_coords) + point_labels = point_labels.unsqueeze(-1).expand_as(point_embedding) + + point_embedding = point_embedding * (point_labels != -1) + point_embedding = ( + point_embedding + + self.model.prompt_encoder.not_a_point_embed.weight * (point_labels == -1) + ) + + for i in range(self.model.prompt_encoder.num_point_embeddings): + point_embedding = ( + point_embedding + + self.model.prompt_encoder.point_embeddings[i].weight + * (point_labels == i) + ) + + return point_embedding + + def _embed_masks( + self, input_mask: torch.Tensor, has_mask_input: torch.Tensor + ) -> torch.Tensor: + mask_embedding = has_mask_input * self.model.prompt_encoder.mask_downscaling( + input_mask + ) + mask_embedding = mask_embedding + ( + 1 - has_mask_input + ) * self.model.prompt_encoder.no_mask_embed.weight.reshape(1, -1, 1, 1) + return mask_embedding + + def mask_postprocessing( + self, masks: torch.Tensor, orig_im_size: torch.Tensor + ) -> torch.Tensor: + masks = F.interpolate( + masks, + size=(self.img_size, self.img_size), + mode="bilinear", + align_corners=False, + ) + + prepadded_size = self.resize_longest_image_size(orig_im_size, self.img_size).to( + torch.int64 + ) + masks = masks[..., : prepadded_size[0], : prepadded_size[1]] # type: ignore + + orig_im_size = orig_im_size.to(torch.int64) + h, w = orig_im_size[0], orig_im_size[1] + masks = F.interpolate(masks, size=(h, w), mode="bilinear", align_corners=False) + return masks + + def select_masks( + self, masks: torch.Tensor, iou_preds: torch.Tensor, num_points: int + ) -> Tuple[torch.Tensor, torch.Tensor]: + # Determine if we should return the multiclick mask or not from the number of points. + # The reweighting is used to avoid control flow. + score_reweight = torch.tensor( + [[1000] + [0] * (self.model.mask_decoder.num_mask_tokens - 1)] + ).to(iou_preds.device) + score = iou_preds + (num_points - 2.5) * score_reweight + best_idx = torch.argmax(score, dim=1) + masks = masks[torch.arange(masks.shape[0]), best_idx, :, :].unsqueeze(1) + iou_preds = iou_preds[torch.arange(masks.shape[0]), best_idx].unsqueeze(1) + + return masks, iou_preds + + @torch.no_grad() + def forward( + self, + image_embeddings: torch.Tensor, + point_coords: torch.Tensor, + point_labels: torch.Tensor, + mask_input: torch.Tensor, + has_mask_input: torch.Tensor, + orig_im_size: torch.Tensor, + ): + sparse_embedding = self._embed_points(point_coords, point_labels) + dense_embedding = self._embed_masks(mask_input, has_mask_input) + + masks, scores = self.model.mask_decoder.predict_masks( + image_embeddings=image_embeddings, + image_pe=self.model.prompt_encoder.get_dense_pe(), + sparse_prompt_embeddings=sparse_embedding, + dense_prompt_embeddings=dense_embedding, + ) + + if self.use_stability_score: + scores = calculate_stability_score( + masks, self.model.mask_threshold, self.stability_score_offset + ) + + if self.return_single_mask: + masks, scores = self.select_masks(masks, scores, point_coords.shape[1]) + + upscaled_masks = self.mask_postprocessing(masks, orig_im_size) + + if self.return_extra_metrics: + stability_scores = calculate_stability_score( + upscaled_masks, self.model.mask_threshold, self.stability_score_offset + ) + areas = (upscaled_masks > self.model.mask_threshold).sum(-1).sum(-1) + return upscaled_masks, scores, stability_scores, areas, masks + + return upscaled_masks, scores, masks diff --git a/py/evf_sam/model/segment_anything/utils/transforms.py b/py/evf_sam/model/segment_anything/utils/transforms.py new file mode 100644 index 0000000..4232d84 --- /dev/null +++ b/py/evf_sam/model/segment_anything/utils/transforms.py @@ -0,0 +1,113 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +from copy import deepcopy +from typing import Tuple + +import numpy as np +import torch +from torch.nn import functional as F +from torchvision.transforms.functional import resize # type: ignore +from torchvision.transforms.functional import to_pil_image + + +class ResizeLongestSide: + """ + Resizes images to the longest side 'target_length', as well as provides + methods for resizing coordinates and boxes. Provides methods for + transforming both numpy array and batched torch tensors. + """ + + def __init__(self, target_length: int) -> None: + self.target_length = target_length + + def apply_image(self, image: np.ndarray) -> np.ndarray: + """ + Expects a numpy array with shape HxWxC in uint8 format. + """ + target_size = self.get_preprocess_shape( + image.shape[0], image.shape[1], self.target_length + ) + return np.array(resize(to_pil_image(image), target_size)) + + def apply_coords( + self, coords: np.ndarray, original_size: Tuple[int, ...] + ) -> np.ndarray: + """ + Expects a numpy array of length 2 in the final dimension. Requires the + original image size in (H, W) format. + """ + old_h, old_w = original_size + new_h, new_w = self.get_preprocess_shape( + original_size[0], original_size[1], self.target_length + ) + coords = deepcopy(coords).astype(float) + coords[..., 0] = coords[..., 0] * (new_w / old_w) + coords[..., 1] = coords[..., 1] * (new_h / old_h) + return coords + + def apply_boxes( + self, boxes: np.ndarray, original_size: Tuple[int, ...] + ) -> np.ndarray: + """ + Expects a numpy array shape Bx4. Requires the original image size + in (H, W) format. + """ + boxes = self.apply_coords(boxes.reshape(-1, 2, 2), original_size) + return boxes.reshape(-1, 4) + + def apply_image_torch(self, image: torch.Tensor) -> torch.Tensor: + """ + Expects batched images with shape BxCxHxW and float format. This + transformation may not exactly match apply_image. apply_image is + the transformation expected by the model. + """ + # Expects an image in BCHW format. May not exactly match apply_image. + target_size = self.get_preprocess_shape( + image.shape[0], image.shape[1], self.target_length + ) + return F.interpolate( + image, target_size, mode="bilinear", align_corners=False, antialias=True + ) + + def apply_coords_torch( + self, coords: torch.Tensor, original_size: Tuple[int, ...] + ) -> torch.Tensor: + """ + Expects a torch tensor with length 2 in the last dimension. Requires the + original image size in (H, W) format. + """ + old_h, old_w = original_size + new_h, new_w = self.get_preprocess_shape( + original_size[0], original_size[1], self.target_length + ) + coords = deepcopy(coords).to(torch.float) + coords[..., 0] = coords[..., 0] * (new_w / old_w) + coords[..., 1] = coords[..., 1] * (new_h / old_h) + return coords + + def apply_boxes_torch( + self, boxes: torch.Tensor, original_size: Tuple[int, ...] + ) -> torch.Tensor: + """ + Expects a torch tensor with shape Bx4. Requires the original image + size in (H, W) format. + """ + boxes = self.apply_coords_torch(boxes.reshape(-1, 2, 2), original_size) + return boxes.reshape(-1, 4) + + @staticmethod + def get_preprocess_shape( + oldh: int, oldw: int, long_side_length: int + ) -> Tuple[int, int]: + """ + Compute the output size given input size and target long side length. + """ + scale = long_side_length * 1.0 / max(oldh, oldw) + newh, neww = oldh * scale, oldw * scale + neww = int(neww + 0.5) + newh = int(newh + 0.5) + return (newh, neww) diff --git a/py/evf_sam/model/segment_anything_2/sam2/__init__.py b/py/evf_sam/model/segment_anything_2/sam2/__init__.py new file mode 100644 index 0000000..ad3406c --- /dev/null +++ b/py/evf_sam/model/segment_anything_2/sam2/__init__.py @@ -0,0 +1,11 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + + +from hydra import initialize_config_module + +# initialize_config_module("model/segment_anything_2/sam2_configs", version_base="1.2") +initialize_config_module("model/segment_anything_2/sam2_configs") diff --git a/py/evf_sam/model/segment_anything_2/sam2/automatic_mask_generator.py b/py/evf_sam/model/segment_anything_2/sam2/automatic_mask_generator.py new file mode 100644 index 0000000..91b76f1 --- /dev/null +++ b/py/evf_sam/model/segment_anything_2/sam2/automatic_mask_generator.py @@ -0,0 +1,434 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +# Adapted from https://github.com/facebookresearch/segment-anything/blob/main/segment_anything/automatic_mask_generator.py +from typing import Any, Dict, List, Optional, Tuple + +import numpy as np +import torch +from torchvision.ops.boxes import batched_nms, box_area # type: ignore + +from model.segment_anything_2.sam2.modeling.sam2_base import SAM2Base +from model.segment_anything_2.sam2.sam2_image_predictor import SAM2ImagePredictor +from model.segment_anything_2.sam2.utils.amg import ( + area_from_rle, + batch_iterator, + batched_mask_to_box, + box_xyxy_to_xywh, + build_all_layer_point_grids, + calculate_stability_score, + coco_encode_rle, + generate_crop_boxes, + is_box_near_crop_edge, + mask_to_rle_pytorch, + MaskData, + remove_small_regions, + rle_to_mask, + uncrop_boxes_xyxy, + uncrop_masks, + uncrop_points, +) + + +class SAM2AutomaticMaskGenerator: + def __init__( + self, + model: SAM2Base, + points_per_side: Optional[int] = 32, + points_per_batch: int = 64, + pred_iou_thresh: float = 0.8, + stability_score_thresh: float = 0.95, + stability_score_offset: float = 1.0, + mask_threshold: float = 0.0, + box_nms_thresh: float = 0.7, + crop_n_layers: int = 0, + crop_nms_thresh: float = 0.7, + crop_overlap_ratio: float = 512 / 1500, + crop_n_points_downscale_factor: int = 1, + point_grids: Optional[List[np.ndarray]] = None, + min_mask_region_area: int = 0, + output_mode: str = "binary_mask", + use_m2m: bool = False, + multimask_output: bool = True, + ) -> None: + """ + Using a SAM 2 model, generates masks for the entire image. + Generates a grid of point prompts over the image, then filters + low quality and duplicate masks. The default settings are chosen + for SAM 2 with a HieraL backbone. + + Arguments: + model (Sam): The SAM 2 model to use for mask prediction. + points_per_side (int or None): The number of points to be sampled + along one side of the image. The total number of points is + points_per_side**2. If None, 'point_grids' must provide explicit + point sampling. + points_per_batch (int): Sets the number of points run simultaneously + by the model. Higher numbers may be faster but use more GPU memory. + pred_iou_thresh (float): A filtering threshold in [0,1], using the + model's predicted mask quality. + stability_score_thresh (float): A filtering threshold in [0,1], using + the stability of the mask under changes to the cutoff used to binarize + the model's mask predictions. + stability_score_offset (float): The amount to shift the cutoff when + calculated the stability score. + mask_threshold (float): Threshold for binarizing the mask logits + box_nms_thresh (float): The box IoU cutoff used by non-maximal + suppression to filter duplicate masks. + crop_n_layers (int): If >0, mask prediction will be run again on + crops of the image. Sets the number of layers to run, where each + layer has 2**i_layer number of image crops. + crop_nms_thresh (float): The box IoU cutoff used by non-maximal + suppression to filter duplicate masks between different crops. + crop_overlap_ratio (float): Sets the degree to which crops overlap. + In the first crop layer, crops will overlap by this fraction of + the image length. Later layers with more crops scale down this overlap. + crop_n_points_downscale_factor (int): The number of points-per-side + sampled in layer n is scaled down by crop_n_points_downscale_factor**n. + point_grids (list(np.ndarray) or None): A list over explicit grids + of points used for sampling, normalized to [0,1]. The nth grid in the + list is used in the nth crop layer. Exclusive with points_per_side. + min_mask_region_area (int): If >0, postprocessing will be applied + to remove disconnected regions and holes in masks with area smaller + than min_mask_region_area. Requires opencv. + output_mode (str): The form masks are returned in. Can be 'binary_mask', + 'uncompressed_rle', or 'coco_rle'. 'coco_rle' requires pycocotools. + For large resolutions, 'binary_mask' may consume large amounts of + memory. + use_m2m (bool): Whether to add a one step refinement using previous mask predictions. + multimask_output (bool): Whether to output multimask at each point of the grid. + """ + + assert (points_per_side is None) != ( + point_grids is None + ), "Exactly one of points_per_side or point_grid must be provided." + if points_per_side is not None: + self.point_grids = build_all_layer_point_grids( + points_per_side, + crop_n_layers, + crop_n_points_downscale_factor, + ) + elif point_grids is not None: + self.point_grids = point_grids + else: + raise ValueError("Can't have both points_per_side and point_grid be None.") + + assert output_mode in [ + "binary_mask", + "uncompressed_rle", + "coco_rle", + ], f"Unknown output_mode {output_mode}." + if output_mode == "coco_rle": + try: + from pycocotools import mask as mask_utils # type: ignore # noqa: F401 + except ImportError as e: + print("Please install pycocotools") + raise e + + self.predictor = SAM2ImagePredictor( + model, + max_hole_area=min_mask_region_area, + max_sprinkle_area=min_mask_region_area, + ) + self.points_per_batch = points_per_batch + self.pred_iou_thresh = pred_iou_thresh + self.stability_score_thresh = stability_score_thresh + self.stability_score_offset = stability_score_offset + self.mask_threshold = mask_threshold + self.box_nms_thresh = box_nms_thresh + self.crop_n_layers = crop_n_layers + self.crop_nms_thresh = crop_nms_thresh + self.crop_overlap_ratio = crop_overlap_ratio + self.crop_n_points_downscale_factor = crop_n_points_downscale_factor + self.min_mask_region_area = min_mask_region_area + self.output_mode = output_mode + self.use_m2m = use_m2m + self.multimask_output = multimask_output + + @torch.no_grad() + def generate(self, image: np.ndarray) -> List[Dict[str, Any]]: + """ + Generates masks for the given image. + + Arguments: + image (np.ndarray): The image to generate masks for, in HWC uint8 format. + + Returns: + list(dict(str, any)): A list over records for masks. Each record is + a dict containing the following keys: + segmentation (dict(str, any) or np.ndarray): The mask. If + output_mode='binary_mask', is an array of shape HW. Otherwise, + is a dictionary containing the RLE. + bbox (list(float)): The box around the mask, in XYWH format. + area (int): The area in pixels of the mask. + predicted_iou (float): The model's own prediction of the mask's + quality. This is filtered by the pred_iou_thresh parameter. + point_coords (list(list(float))): The point coordinates input + to the model to generate this mask. + stability_score (float): A measure of the mask's quality. This + is filtered on using the stability_score_thresh parameter. + crop_box (list(float)): The crop of the image used to generate + the mask, given in XYWH format. + """ + + # Generate masks + mask_data = self._generate_masks(image) + + # Encode masks + if self.output_mode == "coco_rle": + mask_data["segmentations"] = [ + coco_encode_rle(rle) for rle in mask_data["rles"] + ] + elif self.output_mode == "binary_mask": + mask_data["segmentations"] = [rle_to_mask(rle) for rle in mask_data["rles"]] + else: + mask_data["segmentations"] = mask_data["rles"] + + # Write mask records + curr_anns = [] + for idx in range(len(mask_data["segmentations"])): + ann = { + "segmentation": mask_data["segmentations"][idx], + "area": area_from_rle(mask_data["rles"][idx]), + "bbox": box_xyxy_to_xywh(mask_data["boxes"][idx]).tolist(), + "predicted_iou": mask_data["iou_preds"][idx].item(), + "point_coords": [mask_data["points"][idx].tolist()], + "stability_score": mask_data["stability_score"][idx].item(), + "crop_box": box_xyxy_to_xywh(mask_data["crop_boxes"][idx]).tolist(), + } + curr_anns.append(ann) + + return curr_anns + + def _generate_masks(self, image: np.ndarray) -> MaskData: + orig_size = image.shape[:2] + crop_boxes, layer_idxs = generate_crop_boxes( + orig_size, self.crop_n_layers, self.crop_overlap_ratio + ) + + # Iterate over image crops + data = MaskData() + for crop_box, layer_idx in zip(crop_boxes, layer_idxs): + crop_data = self._process_crop(image, crop_box, layer_idx, orig_size) + data.cat(crop_data) + + # Remove duplicate masks between crops + if len(crop_boxes) > 1: + # Prefer masks from smaller crops + scores = 1 / box_area(data["crop_boxes"]) + scores = scores.to(data["boxes"].device) + keep_by_nms = batched_nms( + data["boxes"].float(), + scores, + torch.zeros_like(data["boxes"][:, 0]), # categories + iou_threshold=self.crop_nms_thresh, + ) + data.filter(keep_by_nms) + data.to_numpy() + return data + + def _process_crop( + self, + image: np.ndarray, + crop_box: List[int], + crop_layer_idx: int, + orig_size: Tuple[int, ...], + ) -> MaskData: + # Crop the image and calculate embeddings + x0, y0, x1, y1 = crop_box + cropped_im = image[y0:y1, x0:x1, :] + cropped_im_size = cropped_im.shape[:2] + self.predictor.set_image(cropped_im) + + # Get points for this crop + points_scale = np.array(cropped_im_size)[None, ::-1] + points_for_image = self.point_grids[crop_layer_idx] * points_scale + + # Generate masks for this crop in batches + data = MaskData() + for (points,) in batch_iterator(self.points_per_batch, points_for_image): + batch_data = self._process_batch( + points, cropped_im_size, crop_box, orig_size, normalize=True + ) + data.cat(batch_data) + del batch_data + self.predictor.reset_predictor() + + # Remove duplicates within this crop. + keep_by_nms = batched_nms( + data["boxes"].float(), + data["iou_preds"], + torch.zeros_like(data["boxes"][:, 0]), # categories + iou_threshold=self.box_nms_thresh, + ) + data.filter(keep_by_nms) + + # Return to the original image frame + data["boxes"] = uncrop_boxes_xyxy(data["boxes"], crop_box) + data["points"] = uncrop_points(data["points"], crop_box) + data["crop_boxes"] = torch.tensor([crop_box for _ in range(len(data["rles"]))]) + + return data + + def _process_batch( + self, + points: np.ndarray, + im_size: Tuple[int, ...], + crop_box: List[int], + orig_size: Tuple[int, ...], + normalize=False, + ) -> MaskData: + orig_h, orig_w = orig_size + + # Run model on this batch + points = torch.as_tensor(points, device=self.predictor.device) + in_points = self.predictor._transforms.transform_coords( + points, normalize=normalize, orig_hw=im_size + ) + in_labels = torch.ones( + in_points.shape[0], dtype=torch.int, device=in_points.device + ) + masks, iou_preds, low_res_masks = self.predictor._predict( + in_points[:, None, :], + in_labels[:, None], + multimask_output=self.multimask_output, + return_logits=True, + ) + + # Serialize predictions and store in MaskData + data = MaskData( + masks=masks.flatten(0, 1), + iou_preds=iou_preds.flatten(0, 1), + points=points.repeat_interleave(masks.shape[1], dim=0), + low_res_masks=low_res_masks.flatten(0, 1), + ) + del masks + + if not self.use_m2m: + # Filter by predicted IoU + if self.pred_iou_thresh > 0.0: + keep_mask = data["iou_preds"] > self.pred_iou_thresh + data.filter(keep_mask) + + # Calculate and filter by stability score + data["stability_score"] = calculate_stability_score( + data["masks"], self.mask_threshold, self.stability_score_offset + ) + if self.stability_score_thresh > 0.0: + keep_mask = data["stability_score"] >= self.stability_score_thresh + data.filter(keep_mask) + else: + # One step refinement using previous mask predictions + in_points = self.predictor._transforms.transform_coords( + data["points"], normalize=normalize, orig_hw=im_size + ) + labels = torch.ones( + in_points.shape[0], dtype=torch.int, device=in_points.device + ) + masks, ious = self.refine_with_m2m( + in_points, labels, data["low_res_masks"], self.points_per_batch + ) + data["masks"] = masks.squeeze(1) + data["iou_preds"] = ious.squeeze(1) + + if self.pred_iou_thresh > 0.0: + keep_mask = data["iou_preds"] > self.pred_iou_thresh + data.filter(keep_mask) + + data["stability_score"] = calculate_stability_score( + data["masks"], self.mask_threshold, self.stability_score_offset + ) + if self.stability_score_thresh > 0.0: + keep_mask = data["stability_score"] >= self.stability_score_thresh + data.filter(keep_mask) + + # Threshold masks and calculate boxes + data["masks"] = data["masks"] > self.mask_threshold + data["boxes"] = batched_mask_to_box(data["masks"]) + + # Filter boxes that touch crop boundaries + keep_mask = ~is_box_near_crop_edge( + data["boxes"], crop_box, [0, 0, orig_w, orig_h] + ) + if not torch.all(keep_mask): + data.filter(keep_mask) + + # Compress to RLE + data["masks"] = uncrop_masks(data["masks"], crop_box, orig_h, orig_w) + data["rles"] = mask_to_rle_pytorch(data["masks"]) + del data["masks"] + + return data + + @staticmethod + def postprocess_small_regions( + mask_data: MaskData, min_area: int, nms_thresh: float + ) -> MaskData: + """ + Removes small disconnected regions and holes in masks, then reruns + box NMS to remove any new duplicates. + + Edits mask_data in place. + + Requires open-cv as a dependency. + """ + if len(mask_data["rles"]) == 0: + return mask_data + + # Filter small disconnected regions and holes + new_masks = [] + scores = [] + for rle in mask_data["rles"]: + mask = rle_to_mask(rle) + + mask, changed = remove_small_regions(mask, min_area, mode="holes") + unchanged = not changed + mask, changed = remove_small_regions(mask, min_area, mode="islands") + unchanged = unchanged and not changed + + new_masks.append(torch.as_tensor(mask).unsqueeze(0)) + # Give score=0 to changed masks and score=1 to unchanged masks + # so NMS will prefer ones that didn't need postprocessing + scores.append(float(unchanged)) + + # Recalculate boxes and remove any new duplicates + masks = torch.cat(new_masks, dim=0) + boxes = batched_mask_to_box(masks) + keep_by_nms = batched_nms( + boxes.float(), + torch.as_tensor(scores), + torch.zeros_like(boxes[:, 0]), # categories + iou_threshold=nms_thresh, + ) + + # Only recalculate RLEs for masks that have changed + for i_mask in keep_by_nms: + if scores[i_mask] == 0.0: + mask_torch = masks[i_mask].unsqueeze(0) + mask_data["rles"][i_mask] = mask_to_rle_pytorch(mask_torch)[0] + mask_data["boxes"][i_mask] = boxes[i_mask] # update res directly + mask_data.filter(keep_by_nms) + + return mask_data + + def refine_with_m2m(self, points, point_labels, low_res_masks, points_per_batch): + new_masks = [] + new_iou_preds = [] + + for cur_points, cur_point_labels, low_res_mask in batch_iterator( + points_per_batch, points, point_labels, low_res_masks + ): + best_masks, best_iou_preds, _ = self.predictor._predict( + cur_points[:, None, :], + cur_point_labels[:, None], + mask_input=low_res_mask[:, None, :], + multimask_output=False, + return_logits=True, + ) + new_masks.append(best_masks) + new_iou_preds.append(best_iou_preds) + masks = torch.cat(new_masks, dim=0) + return masks, torch.cat(new_iou_preds, dim=0) diff --git a/py/evf_sam/model/segment_anything_2/sam2/build_sam.py b/py/evf_sam/model/segment_anything_2/sam2/build_sam.py new file mode 100644 index 0000000..c0cfe12 --- /dev/null +++ b/py/evf_sam/model/segment_anything_2/sam2/build_sam.py @@ -0,0 +1,90 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import logging + +import torch +from hydra import compose +from hydra.utils import instantiate +from omegaconf import OmegaConf + +def build_sam2( + config_file, + ckpt_path=None, + device="cuda", + mode="eval", + hydra_overrides_extra=[], + apply_postprocessing=True, +): + + if apply_postprocessing: + hydra_overrides_extra = hydra_overrides_extra.copy() + hydra_overrides_extra += [ + # dynamically fall back to multi-mask if the single mask is not stable + "++model.sam_mask_decoder_extra_args.dynamic_multimask_via_stability=true", + "++model.sam_mask_decoder_extra_args.dynamic_multimask_stability_delta=0.05", + "++model.sam_mask_decoder_extra_args.dynamic_multimask_stability_thresh=0.98", + ] + # Read config and init model + cfg = compose(config_name=config_file, overrides=hydra_overrides_extra) + OmegaConf.resolve(cfg) + model = instantiate(cfg.model, _recursive_=True) + _load_checkpoint(model, ckpt_path) + if device: + model = model.to(device) + if mode == "eval": + model.eval() + return model + + +def build_sam2_video_predictor( + config_file, + ckpt_path=None, + device="cuda", + mode="eval", + hydra_overrides_extra=[], + apply_postprocessing=True, +): + hydra_overrides = [ + "++model._target_=model.segment_anything_2.sam2.sam2_video_predictor.SAM2VideoPredictor", + ] + if apply_postprocessing: + hydra_overrides_extra = hydra_overrides_extra.copy() + hydra_overrides_extra += [ + # dynamically fall back to multi-mask if the single mask is not stable + "++model.sam_mask_decoder_extra_args.dynamic_multimask_via_stability=true", + "++model.sam_mask_decoder_extra_args.dynamic_multimask_stability_delta=0.05", + "++model.sam_mask_decoder_extra_args.dynamic_multimask_stability_thresh=0.98", + # the sigmoid mask logits on interacted frames with clicks in the memory encoder so that the encoded masks are exactly as what users see from clicking + "++model.binarize_mask_from_pts_for_mem_enc=true", + # fill small holes in the low-res masks up to `fill_hole_area` (before resizing them to the original video resolution) + "++model.fill_hole_area=8", + ] + hydra_overrides.extend(hydra_overrides_extra) + + # Read config and init model + cfg = compose(config_name=config_file, overrides=hydra_overrides) + OmegaConf.resolve(cfg) + model = instantiate(cfg.model, _recursive_=True) + _load_checkpoint(model, ckpt_path) + if device: + model = model.to(device) + if mode == "eval": + model.eval() + return model + + +def _load_checkpoint(model, ckpt_path): + if ckpt_path is not None: + sd = torch.load(ckpt_path, map_location="cpu")["model"] + missing_keys, unexpected_keys = model.load_state_dict(sd) + if missing_keys: + logging.error(missing_keys) + raise RuntimeError() + if unexpected_keys: + logging.error(unexpected_keys) + raise RuntimeError() + logging.info("Loaded checkpoint sucessfully") diff --git a/py/evf_sam/model/segment_anything_2/sam2/csrc/connected_components.cu b/py/evf_sam/model/segment_anything_2/sam2/csrc/connected_components.cu new file mode 100644 index 0000000..eb83231 --- /dev/null +++ b/py/evf_sam/model/segment_anything_2/sam2/csrc/connected_components.cu @@ -0,0 +1,289 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. +// All rights reserved. + +// This source code is licensed under the license found in the +// LICENSE file in the root directory of this source tree. + +// adapted from https://github.com/zsef123/Connected_components_PyTorch +// with license found in the LICENSE_cctorch file in the root directory. +#include +#include +#include +#include +#include +#include + +// 2d +#define BLOCK_ROWS 16 +#define BLOCK_COLS 16 + +namespace cc2d { + +template +__device__ __forceinline__ unsigned char hasBit(T bitmap, unsigned char pos) { + return (bitmap >> pos) & 1; +} + +__device__ int32_t find(const int32_t* s_buf, int32_t n) { + while (s_buf[n] != n) + n = s_buf[n]; + return n; +} + +__device__ int32_t find_n_compress(int32_t* s_buf, int32_t n) { + const int32_t id = n; + while (s_buf[n] != n) { + n = s_buf[n]; + s_buf[id] = n; + } + return n; +} + +__device__ void union_(int32_t* s_buf, int32_t a, int32_t b) { + bool done; + do { + a = find(s_buf, a); + b = find(s_buf, b); + + if (a < b) { + int32_t old = atomicMin(s_buf + b, a); + done = (old == b); + b = old; + } else if (b < a) { + int32_t old = atomicMin(s_buf + a, b); + done = (old == a); + a = old; + } else + done = true; + + } while (!done); +} + +__global__ void +init_labeling(int32_t* label, const uint32_t W, const uint32_t H) { + const uint32_t row = (blockIdx.y * blockDim.y + threadIdx.y) * 2; + const uint32_t col = (blockIdx.x * blockDim.x + threadIdx.x) * 2; + const uint32_t idx = row * W + col; + + if (row < H && col < W) + label[idx] = idx; +} + +__global__ void +merge(uint8_t* img, int32_t* label, const uint32_t W, const uint32_t H) { + const uint32_t row = (blockIdx.y * blockDim.y + threadIdx.y) * 2; + const uint32_t col = (blockIdx.x * blockDim.x + threadIdx.x) * 2; + const uint32_t idx = row * W + col; + + if (row >= H || col >= W) + return; + + uint32_t P = 0; + + if (img[idx]) + P |= 0x777; + if (row + 1 < H && img[idx + W]) + P |= 0x777 << 4; + if (col + 1 < W && img[idx + 1]) + P |= 0x777 << 1; + + if (col == 0) + P &= 0xEEEE; + if (col + 1 >= W) + P &= 0x3333; + else if (col + 2 >= W) + P &= 0x7777; + + if (row == 0) + P &= 0xFFF0; + if (row + 1 >= H) + P &= 0xFF; + + if (P > 0) { + // If need check about top-left pixel(if flag the first bit) and hit the + // top-left pixel + if (hasBit(P, 0) && img[idx - W - 1]) { + union_(label, idx, idx - 2 * W - 2); // top left block + } + + if ((hasBit(P, 1) && img[idx - W]) || (hasBit(P, 2) && img[idx - W + 1])) + union_(label, idx, idx - 2 * W); // top bottom block + + if (hasBit(P, 3) && img[idx + 2 - W]) + union_(label, idx, idx - 2 * W + 2); // top right block + + if ((hasBit(P, 4) && img[idx - 1]) || (hasBit(P, 8) && img[idx + W - 1])) + union_(label, idx, idx - 2); // just left block + } +} + +__global__ void compression(int32_t* label, const int32_t W, const int32_t H) { + const uint32_t row = (blockIdx.y * blockDim.y + threadIdx.y) * 2; + const uint32_t col = (blockIdx.x * blockDim.x + threadIdx.x) * 2; + const uint32_t idx = row * W + col; + + if (row < H && col < W) + find_n_compress(label, idx); +} + +__global__ void final_labeling( + const uint8_t* img, + int32_t* label, + const int32_t W, + const int32_t H) { + const uint32_t row = (blockIdx.y * blockDim.y + threadIdx.y) * 2; + const uint32_t col = (blockIdx.x * blockDim.x + threadIdx.x) * 2; + const uint32_t idx = row * W + col; + + if (row >= H || col >= W) + return; + + int32_t y = label[idx] + 1; + + if (img[idx]) + label[idx] = y; + else + label[idx] = 0; + + if (col + 1 < W) { + if (img[idx + 1]) + label[idx + 1] = y; + else + label[idx + 1] = 0; + + if (row + 1 < H) { + if (img[idx + W + 1]) + label[idx + W + 1] = y; + else + label[idx + W + 1] = 0; + } + } + + if (row + 1 < H) { + if (img[idx + W]) + label[idx + W] = y; + else + label[idx + W] = 0; + } +} + +__global__ void init_counting( + const int32_t* label, + int32_t* count_init, + const int32_t W, + const int32_t H) { + const uint32_t row = (blockIdx.y * blockDim.y + threadIdx.y); + const uint32_t col = (blockIdx.x * blockDim.x + threadIdx.x); + const uint32_t idx = row * W + col; + + if (row >= H || col >= W) + return; + + int32_t y = label[idx]; + if (y > 0) { + int32_t count_idx = y - 1; + atomicAdd(count_init + count_idx, 1); + } +} + +__global__ void final_counting( + const int32_t* label, + const int32_t* count_init, + int32_t* count_final, + const int32_t W, + const int32_t H) { + const uint32_t row = (blockIdx.y * blockDim.y + threadIdx.y); + const uint32_t col = (blockIdx.x * blockDim.x + threadIdx.x); + const uint32_t idx = row * W + col; + + if (row >= H || col >= W) + return; + + int32_t y = label[idx]; + if (y > 0) { + int32_t count_idx = y - 1; + count_final[idx] = count_init[count_idx]; + } else { + count_final[idx] = 0; + } +} + +} // namespace cc2d + +std::vector get_connected_componnets( + const torch::Tensor& inputs) { + AT_ASSERTM(inputs.is_cuda(), "inputs must be a CUDA tensor"); + AT_ASSERTM(inputs.ndimension() == 4, "inputs must be [N, 1, H, W] shape"); + AT_ASSERTM( + inputs.scalar_type() == torch::kUInt8, "inputs must be a uint8 type"); + + const uint32_t N = inputs.size(0); + const uint32_t C = inputs.size(1); + const uint32_t H = inputs.size(2); + const uint32_t W = inputs.size(3); + + AT_ASSERTM(C == 1, "inputs must be [N, 1, H, W] shape"); + AT_ASSERTM((H % 2) == 0, "height must be a even number"); + AT_ASSERTM((W % 2) == 0, "width must be a even number"); + + // label must be uint32_t + auto label_options = + torch::TensorOptions().dtype(torch::kInt32).device(inputs.device()); + torch::Tensor labels = torch::zeros({N, C, H, W}, label_options); + torch::Tensor counts_init = torch::zeros({N, C, H, W}, label_options); + torch::Tensor counts_final = torch::zeros({N, C, H, W}, label_options); + + dim3 grid = dim3( + ((W + 1) / 2 + BLOCK_COLS - 1) / BLOCK_COLS, + ((H + 1) / 2 + BLOCK_ROWS - 1) / BLOCK_ROWS); + dim3 block = dim3(BLOCK_COLS, BLOCK_ROWS); + dim3 grid_count = + dim3((W + BLOCK_COLS) / BLOCK_COLS, (H + BLOCK_ROWS) / BLOCK_ROWS); + dim3 block_count = dim3(BLOCK_COLS, BLOCK_ROWS); + cudaStream_t stream = at::cuda::getCurrentCUDAStream(); + + for (int n = 0; n < N; n++) { + uint32_t offset = n * H * W; + + cc2d::init_labeling<<>>( + labels.data_ptr() + offset, W, H); + cc2d::merge<<>>( + inputs.data_ptr() + offset, + labels.data_ptr() + offset, + W, + H); + cc2d::compression<<>>( + labels.data_ptr() + offset, W, H); + cc2d::final_labeling<<>>( + inputs.data_ptr() + offset, + labels.data_ptr() + offset, + W, + H); + + // get the counting of each pixel + cc2d::init_counting<<>>( + labels.data_ptr() + offset, + counts_init.data_ptr() + offset, + W, + H); + cc2d::final_counting<<>>( + labels.data_ptr() + offset, + counts_init.data_ptr() + offset, + counts_final.data_ptr() + offset, + W, + H); + } + + // returned values are [labels, counts] + std::vector outputs; + outputs.push_back(labels); + outputs.push_back(counts_final); + return outputs; +} + +PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { + m.def( + "get_connected_componnets", + &get_connected_componnets, + "get_connected_componnets"); +} diff --git a/py/evf_sam/model/segment_anything_2/sam2/modeling/__init__.py b/py/evf_sam/model/segment_anything_2/sam2/modeling/__init__.py new file mode 100644 index 0000000..5277f46 --- /dev/null +++ b/py/evf_sam/model/segment_anything_2/sam2/modeling/__init__.py @@ -0,0 +1,5 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. diff --git a/py/evf_sam/model/segment_anything_2/sam2/modeling/backbones/__init__.py b/py/evf_sam/model/segment_anything_2/sam2/modeling/backbones/__init__.py new file mode 100644 index 0000000..5277f46 --- /dev/null +++ b/py/evf_sam/model/segment_anything_2/sam2/modeling/backbones/__init__.py @@ -0,0 +1,5 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. diff --git a/py/evf_sam/model/segment_anything_2/sam2/modeling/backbones/hieradet.py b/py/evf_sam/model/segment_anything_2/sam2/modeling/backbones/hieradet.py new file mode 100644 index 0000000..407598e --- /dev/null +++ b/py/evf_sam/model/segment_anything_2/sam2/modeling/backbones/hieradet.py @@ -0,0 +1,295 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +from functools import partial +from typing import List, Tuple, Union + +import torch +import torch.nn as nn +import torch.nn.functional as F + +from model.segment_anything_2.sam2.modeling.backbones.utils import ( + PatchEmbed, + window_partition, + window_unpartition, +) + +from model.segment_anything_2.sam2.modeling.sam2_utils import DropPath, MLP + + +def do_pool(x: torch.Tensor, pool: nn.Module, norm: nn.Module = None) -> torch.Tensor: + if pool is None: + return x + # (B, H, W, C) -> (B, C, H, W) + x = x.permute(0, 3, 1, 2) + x = pool(x) + # (B, C, H', W') -> (B, H', W', C) + x = x.permute(0, 2, 3, 1) + if norm: + x = norm(x) + + return x + + +class MultiScaleAttention(nn.Module): + def __init__( + self, + dim: int, + dim_out: int, + num_heads: int, + q_pool: nn.Module = None, + ): + super().__init__() + + self.dim = dim + self.dim_out = dim_out + + self.num_heads = num_heads + head_dim = dim_out // num_heads + self.scale = head_dim**-0.5 + + self.q_pool = q_pool + self.qkv = nn.Linear(dim, dim_out * 3) + self.proj = nn.Linear(dim_out, dim_out) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + B, H, W, _ = x.shape + # qkv with shape (B, H * W, 3, nHead, C) + qkv = self.qkv(x).reshape(B, H * W, 3, self.num_heads, -1) + # q, k, v with shape (B, H * W, nheads, C) + q, k, v = torch.unbind(qkv, 2) + + # Q pooling (for downsample at stage changes) + if self.q_pool: + q = do_pool(q.reshape(B, H, W, -1), self.q_pool) + H, W = q.shape[1:3] # downsampled shape + q = q.reshape(B, H * W, self.num_heads, -1) + + # Torch's SDPA expects [B, nheads, H*W, C] so we transpose + x = F.scaled_dot_product_attention( + q.transpose(1, 2), + k.transpose(1, 2), + v.transpose(1, 2), + ) + # Transpose back + x = x.transpose(1, 2) + x = x.reshape(B, H, W, -1) + + x = self.proj(x) + + return x + + +class MultiScaleBlock(nn.Module): + def __init__( + self, + dim: int, + dim_out: int, + num_heads: int, + mlp_ratio: float = 4.0, + drop_path: float = 0.0, + norm_layer: Union[nn.Module, str] = "LayerNorm", + q_stride: Tuple[int, int] = None, + act_layer: nn.Module = nn.GELU, + window_size: int = 0, + ): + super().__init__() + + if isinstance(norm_layer, str): + norm_layer = partial(getattr(nn, norm_layer), eps=1e-6) + + self.dim = dim + self.dim_out = dim_out + self.norm1 = norm_layer(dim) + + self.window_size = window_size + + self.pool, self.q_stride = None, q_stride + if self.q_stride: + self.pool = nn.MaxPool2d( + kernel_size=q_stride, stride=q_stride, ceil_mode=False + ) + + self.attn = MultiScaleAttention( + dim, + dim_out, + num_heads=num_heads, + q_pool=self.pool, + ) + self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity() + + self.norm2 = norm_layer(dim_out) + self.mlp = MLP( + dim_out, + int(dim_out * mlp_ratio), + dim_out, + num_layers=2, + activation=act_layer, + ) + + if dim != dim_out: + self.proj = nn.Linear(dim, dim_out) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + shortcut = x # B, H, W, C + x = self.norm1(x) + + # Skip connection + if self.dim != self.dim_out: + shortcut = do_pool(self.proj(x), self.pool) + + # Window partition + window_size = self.window_size + if window_size > 0: + H, W = x.shape[1], x.shape[2] + x, pad_hw = window_partition(x, window_size) + + # Window Attention + Q Pooling (if stage change) + x = self.attn(x) + if self.q_stride: + # Shapes have changed due to Q pooling + window_size = self.window_size // self.q_stride[0] + H, W = shortcut.shape[1:3] + + pad_h = (window_size - H % window_size) % window_size + pad_w = (window_size - W % window_size) % window_size + pad_hw = (H + pad_h, W + pad_w) + + # Reverse window partition + if self.window_size > 0: + x = window_unpartition(x, window_size, pad_hw, (H, W)) + + x = shortcut + self.drop_path(x) + # MLP + x = x + self.drop_path(self.mlp(self.norm2(x))) + return x + + +class Hiera(nn.Module): + """ + Reference: https://arxiv.org/abs/2306.00989 + """ + + def __init__( + self, + embed_dim: int = 96, # initial embed dim + num_heads: int = 1, # initial number of heads + drop_path_rate: float = 0.0, # stochastic depth + q_pool: int = 3, # number of q_pool stages + q_stride: Tuple[int, int] = (2, 2), # downsample stride bet. stages + stages: Tuple[int, ...] = (2, 3, 16, 3), # blocks per stage + dim_mul: float = 2.0, # dim_mul factor at stage shift + head_mul: float = 2.0, # head_mul factor at stage shift + window_pos_embed_bkg_spatial_size: Tuple[int, int] = (14, 14), + # window size per stage, when not using global att. + window_spec: Tuple[int, ...] = ( + 8, + 4, + 14, + 7, + ), + # global attn in these blocks + global_att_blocks: Tuple[int, ...] = ( + 12, + 16, + 20, + ), + return_interm_layers=True, # return feats from every stage + ): + super().__init__() + + assert len(stages) == len(window_spec) + self.window_spec = window_spec + + depth = sum(stages) + self.q_stride = q_stride + self.stage_ends = [sum(stages[:i]) - 1 for i in range(1, len(stages) + 1)] + assert 0 <= q_pool <= len(self.stage_ends[:-1]) + self.q_pool_blocks = [x + 1 for x in self.stage_ends[:-1]][:q_pool] + self.return_interm_layers = return_interm_layers + + self.patch_embed = PatchEmbed( + embed_dim=embed_dim, + ) + # Which blocks have global att? + self.global_att_blocks = global_att_blocks + + # Windowed positional embedding (https://arxiv.org/abs/2311.05613) + self.window_pos_embed_bkg_spatial_size = window_pos_embed_bkg_spatial_size + self.pos_embed = nn.Parameter( + torch.zeros(1, embed_dim, *self.window_pos_embed_bkg_spatial_size) + ) + self.pos_embed_window = nn.Parameter( + torch.zeros(1, embed_dim, self.window_spec[0], self.window_spec[0]) + ) + + dpr = [ + x.item() for x in torch.linspace(0, drop_path_rate, depth) + ] # stochastic depth decay rule + + cur_stage = 1 + self.blocks = nn.ModuleList() + + for i in range(depth): + dim_out = embed_dim + # lags by a block, so first block of + # next stage uses an initial window size + # of previous stage and final window size of current stage + window_size = self.window_spec[cur_stage - 1] + + if self.global_att_blocks is not None: + window_size = 0 if i in self.global_att_blocks else window_size + + if i - 1 in self.stage_ends: + dim_out = int(embed_dim * dim_mul) + num_heads = int(num_heads * head_mul) + cur_stage += 1 + + block = MultiScaleBlock( + dim=embed_dim, + dim_out=dim_out, + num_heads=num_heads, + drop_path=dpr[i], + q_stride=self.q_stride if i in self.q_pool_blocks else None, + window_size=window_size, + ) + + embed_dim = dim_out + self.blocks.append(block) + + self.channel_list = ( + [self.blocks[i].dim_out for i in self.stage_ends[::-1]] + if return_interm_layers + else [self.blocks[-1].dim_out] + ) + + def _get_pos_embed(self, hw: Tuple[int, int]) -> torch.Tensor: + h, w = hw + window_embed = self.pos_embed_window + pos_embed = F.interpolate(self.pos_embed, size=(h, w), mode="bicubic") + pos_embed = pos_embed + window_embed.tile( + [x // y for x, y in zip(pos_embed.shape, window_embed.shape)] + ) + pos_embed = pos_embed.permute(0, 2, 3, 1) + return pos_embed + + def forward(self, x: torch.Tensor) -> List[torch.Tensor]: + x = self.patch_embed(x) + # x: (B, H, W, C) + + # Add pos embed + x = x + self._get_pos_embed(x.shape[1:3]) + + outputs = [] + for i, blk in enumerate(self.blocks): + x = blk(x) + if (i == self.stage_ends[-1]) or ( + i in self.stage_ends and self.return_interm_layers + ): + feats = x.permute(0, 3, 1, 2) + outputs.append(feats) + + return outputs diff --git a/py/evf_sam/model/segment_anything_2/sam2/modeling/backbones/image_encoder.py b/py/evf_sam/model/segment_anything_2/sam2/modeling/backbones/image_encoder.py new file mode 100644 index 0000000..5f92baf --- /dev/null +++ b/py/evf_sam/model/segment_anything_2/sam2/modeling/backbones/image_encoder.py @@ -0,0 +1,133 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +from typing import List, Optional + +import torch +import torch.nn as nn +import torch.nn.functional as F + + +class ImageEncoder(nn.Module): + def __init__( + self, + trunk: nn.Module, + neck: nn.Module, + scalp: int = 0, + ): + super().__init__() + self.trunk = trunk + self.neck = neck + self.scalp = scalp + assert ( + self.trunk.channel_list == self.neck.backbone_channel_list + ), f"Channel dims of trunk and neck do not match. Trunk: {self.trunk.channel_list}, neck: {self.neck.backbone_channel_list}" + + def forward(self, sample: torch.Tensor): + # Forward through backbone + features, pos = self.neck(self.trunk(sample)) + if self.scalp > 0: + # Discard the lowest resolution features + features, pos = features[: -self.scalp], pos[: -self.scalp] + + src = features[-1] + output = { + "vision_features": src, + "vision_pos_enc": pos, + "backbone_fpn": features, + } + return output + + +class FpnNeck(nn.Module): + """ + A modified variant of Feature Pyramid Network (FPN) neck + (we remove output conv and also do bicubic interpolation similar to ViT + pos embed interpolation) + """ + + def __init__( + self, + position_encoding: nn.Module, + d_model: int, + backbone_channel_list: List[int], + kernel_size: int = 1, + stride: int = 1, + padding: int = 0, + fpn_interp_model: str = "bilinear", + fuse_type: str = "sum", + fpn_top_down_levels: Optional[List[int]] = None, + ): + """Initialize the neck + :param trunk: the backbone + :param position_encoding: the positional encoding to use + :param d_model: the dimension of the model + :param neck_norm: the normalization to use + """ + super().__init__() + self.position_encoding = position_encoding + self.convs = nn.ModuleList() + self.backbone_channel_list = backbone_channel_list + for dim in backbone_channel_list: + current = nn.Sequential() + current.add_module( + "conv", + nn.Conv2d( + in_channels=dim, + out_channels=d_model, + kernel_size=kernel_size, + stride=stride, + padding=padding, + ), + ) + + self.convs.append(current) + self.fpn_interp_model = fpn_interp_model + assert fuse_type in ["sum", "avg"] + self.fuse_type = fuse_type + + # levels to have top-down features in its outputs + # e.g. if fpn_top_down_levels is [2, 3], then only outputs of level 2 and 3 + # have top-down propagation, while outputs of level 0 and level 1 have only + # lateral features from the same backbone level. + if fpn_top_down_levels is None: + # default is to have top-down features on all levels + fpn_top_down_levels = range(len(self.convs)) + self.fpn_top_down_levels = list(fpn_top_down_levels) + + def forward(self, xs: List[torch.Tensor]): + + out = [None] * len(self.convs) + pos = [None] * len(self.convs) + assert len(xs) == len(self.convs) + # fpn forward pass + # see https://github.com/facebookresearch/detectron2/blob/main/detectron2/modeling/backbone/fpn.py + prev_features = None + # forward in top-down order (from low to high resolution) + n = len(self.convs) - 1 + for i in range(n, -1, -1): + x = xs[i] + lateral_features = self.convs[n - i](x) + if i in self.fpn_top_down_levels and prev_features is not None: + top_down_features = F.interpolate( + prev_features.to(dtype=torch.float32), + scale_factor=2.0, + mode=self.fpn_interp_model, + align_corners=( + None if self.fpn_interp_model == "nearest" else False + ), + antialias=False, + ) + prev_features = lateral_features + top_down_features + if self.fuse_type == "avg": + prev_features /= 2 + else: + prev_features = lateral_features + x_out = prev_features + out[i] = x_out + pos[i] = self.position_encoding(x_out).to(x_out.dtype) + + return out, pos diff --git a/py/evf_sam/model/segment_anything_2/sam2/modeling/backbones/utils.py b/py/evf_sam/model/segment_anything_2/sam2/modeling/backbones/utils.py new file mode 100644 index 0000000..32d55c7 --- /dev/null +++ b/py/evf_sam/model/segment_anything_2/sam2/modeling/backbones/utils.py @@ -0,0 +1,95 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +"""Some utilities for backbones, in particular for windowing""" + +from typing import Tuple + +import torch +import torch.nn as nn +import torch.nn.functional as F + + +def window_partition(x, window_size): + """ + Partition into non-overlapping windows with padding if needed. + Args: + x (tensor): input tokens with [B, H, W, C]. + window_size (int): window size. + Returns: + windows: windows after partition with [B * num_windows, window_size, window_size, C]. + (Hp, Wp): padded height and width before partition + """ + B, H, W, C = x.shape + + pad_h = (window_size - H % window_size) % window_size + pad_w = (window_size - W % window_size) % window_size + if pad_h > 0 or pad_w > 0: + x = F.pad(x, (0, 0, 0, pad_w, 0, pad_h)) + Hp, Wp = H + pad_h, W + pad_w + + x = x.view(B, Hp // window_size, window_size, Wp // window_size, window_size, C) + windows = ( + x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C) + ) + return windows, (Hp, Wp) + + +def window_unpartition(windows, window_size, pad_hw, hw): + """ + Window unpartition into original sequences and removing padding. + Args: + x (tensor): input tokens with [B * num_windows, window_size, window_size, C]. + window_size (int): window size. + pad_hw (Tuple): padded height and width (Hp, Wp). + hw (Tuple): original height and width (H, W) before padding. + Returns: + x: unpartitioned sequences with [B, H, W, C]. + """ + Hp, Wp = pad_hw + H, W = hw + B = windows.shape[0] // (Hp * Wp // window_size // window_size) + x = windows.view( + B, Hp // window_size, Wp // window_size, window_size, window_size, -1 + ) + x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, Hp, Wp, -1) + + if Hp > H or Wp > W: + x = x[:, :H, :W, :].contiguous() + return x + + +class PatchEmbed(nn.Module): + """ + Image to Patch Embedding. + """ + + def __init__( + self, + kernel_size: Tuple[int, ...] = (7, 7), + stride: Tuple[int, ...] = (4, 4), + padding: Tuple[int, ...] = (3, 3), + in_chans: int = 3, + embed_dim: int = 768, + ): + """ + Args: + kernel_size (Tuple): kernel size of the projection layer. + stride (Tuple): stride of the projection layer. + padding (Tuple): padding size of the projection layer. + in_chans (int): Number of input image channels. + embed_dim (int): embed_dim (int): Patch embedding dimension. + """ + super().__init__() + self.proj = nn.Conv2d( + in_chans, embed_dim, kernel_size=kernel_size, stride=stride, padding=padding + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x = self.proj(x) + # B C H W -> B H W C + x = x.permute(0, 2, 3, 1) + return x diff --git a/py/evf_sam/model/segment_anything_2/sam2/modeling/memory_attention.py b/py/evf_sam/model/segment_anything_2/sam2/modeling/memory_attention.py new file mode 100644 index 0000000..42f56ef --- /dev/null +++ b/py/evf_sam/model/segment_anything_2/sam2/modeling/memory_attention.py @@ -0,0 +1,169 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +from typing import Optional + +import torch +from torch import nn, Tensor + +from model.segment_anything_2.sam2.modeling.sam.transformer import RoPEAttention + +from model.segment_anything_2.sam2.modeling.sam2_utils import get_activation_fn, get_clones + + +class MemoryAttentionLayer(nn.Module): + + def __init__( + self, + activation: str, + cross_attention: nn.Module, + d_model: int, + dim_feedforward: int, + dropout: float, + pos_enc_at_attn: bool, + pos_enc_at_cross_attn_keys: bool, + pos_enc_at_cross_attn_queries: bool, + self_attention: nn.Module, + ): + super().__init__() + self.d_model = d_model + self.dim_feedforward = dim_feedforward + self.dropout_value = dropout + self.self_attn = self_attention + self.cross_attn_image = cross_attention + + # Implementation of Feedforward model + self.linear1 = nn.Linear(d_model, dim_feedforward) + self.dropout = nn.Dropout(dropout) + self.linear2 = nn.Linear(dim_feedforward, d_model) + + self.norm1 = nn.LayerNorm(d_model) + self.norm2 = nn.LayerNorm(d_model) + self.norm3 = nn.LayerNorm(d_model) + self.dropout1 = nn.Dropout(dropout) + self.dropout2 = nn.Dropout(dropout) + self.dropout3 = nn.Dropout(dropout) + + self.activation_str = activation + self.activation = get_activation_fn(activation) + + # Where to add pos enc + self.pos_enc_at_attn = pos_enc_at_attn + self.pos_enc_at_cross_attn_queries = pos_enc_at_cross_attn_queries + self.pos_enc_at_cross_attn_keys = pos_enc_at_cross_attn_keys + + def _forward_sa(self, tgt, query_pos): + # Self-Attention + tgt2 = self.norm1(tgt) + q = k = tgt2 + query_pos if self.pos_enc_at_attn else tgt2 + tgt2 = self.self_attn(q, k, v=tgt2) + tgt = tgt + self.dropout1(tgt2) + return tgt + + def _forward_ca(self, tgt, memory, query_pos, pos, num_k_exclude_rope=0): + kwds = {} + if num_k_exclude_rope > 0: + assert isinstance(self.cross_attn_image, RoPEAttention) + kwds = {"num_k_exclude_rope": num_k_exclude_rope} + + # Cross-Attention + tgt2 = self.norm2(tgt) + tgt2 = self.cross_attn_image( + q=tgt2 + query_pos if self.pos_enc_at_cross_attn_queries else tgt2, + k=memory + pos if self.pos_enc_at_cross_attn_keys else memory, + v=memory, + **kwds, + ) + tgt = tgt + self.dropout2(tgt2) + return tgt + + def forward( + self, + tgt, + memory, + pos: Optional[Tensor] = None, + query_pos: Optional[Tensor] = None, + num_k_exclude_rope: int = 0, + ) -> torch.Tensor: + + # Self-Attn, Cross-Attn + tgt = self._forward_sa(tgt, query_pos) + tgt = self._forward_ca(tgt, memory, query_pos, pos, num_k_exclude_rope) + # MLP + tgt2 = self.norm3(tgt) + tgt2 = self.linear2(self.dropout(self.activation(self.linear1(tgt2)))) + tgt = tgt + self.dropout3(tgt2) + return tgt + + +class MemoryAttention(nn.Module): + def __init__( + self, + d_model: int, + pos_enc_at_input: bool, + layer: nn.Module, + num_layers: int, + batch_first: bool = True, # Do layers expect batch first input? + ): + super().__init__() + self.d_model = d_model + self.layers = get_clones(layer, num_layers) + self.num_layers = num_layers + self.norm = nn.LayerNorm(d_model) + self.pos_enc_at_input = pos_enc_at_input + self.batch_first = batch_first + + def forward( + self, + curr: torch.Tensor, # self-attention inputs + memory: torch.Tensor, # cross-attention inputs + curr_pos: Optional[Tensor] = None, # pos_enc for self-attention inputs + memory_pos: Optional[Tensor] = None, # pos_enc for cross-attention inputs + num_obj_ptr_tokens: int = 0, # number of object pointer *tokens* + ): + if isinstance(curr, list): + assert isinstance(curr_pos, list) + assert len(curr) == len(curr_pos) == 1 + curr, curr_pos = ( + curr[0], + curr_pos[0], + ) + + assert ( + curr.shape[1] == memory.shape[1] + ), "Batch size must be the same for curr and memory" + + output = curr + if self.pos_enc_at_input and curr_pos is not None: + output = output + 0.1 * curr_pos + + if self.batch_first: + # Convert to batch first + output = output.transpose(0, 1) + curr_pos = curr_pos.transpose(0, 1) + memory = memory.transpose(0, 1) + memory_pos = memory_pos.transpose(0, 1) + + for layer in self.layers: + kwds = {} + if isinstance(layer.cross_attn_image, RoPEAttention): + kwds = {"num_k_exclude_rope": num_obj_ptr_tokens} + + output = layer( + tgt=output, + memory=memory, + pos=memory_pos, + query_pos=curr_pos, + **kwds, + ) + normed_output = self.norm(output) + + if self.batch_first: + # Convert back to seq first + normed_output = normed_output.transpose(0, 1) + curr_pos = curr_pos.transpose(0, 1) + + return normed_output diff --git a/py/evf_sam/model/segment_anything_2/sam2/modeling/memory_encoder.py b/py/evf_sam/model/segment_anything_2/sam2/modeling/memory_encoder.py new file mode 100644 index 0000000..fb11cbf --- /dev/null +++ b/py/evf_sam/model/segment_anything_2/sam2/modeling/memory_encoder.py @@ -0,0 +1,182 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import math +from typing import Tuple + +import torch +import torch.nn as nn +import torch.nn.functional as F + +from model.segment_anything_2.sam2.modeling.sam2_utils import DropPath, get_clones, LayerNorm2d + + +class MaskDownSampler(nn.Module): + """ + Progressively downsample a mask by total_stride, each time by stride. + Note that LayerNorm is applied per *token*, like in ViT. + + With each downsample (by a factor stride**2), channel capacity increases by the same factor. + In the end, we linearly project to embed_dim channels. + """ + + def __init__( + self, + embed_dim=256, + kernel_size=4, + stride=4, + padding=0, + total_stride=16, + activation=nn.GELU, + ): + super().__init__() + num_layers = int(math.log2(total_stride) // math.log2(stride)) + assert stride**num_layers == total_stride + self.encoder = nn.Sequential() + mask_in_chans, mask_out_chans = 1, 1 + for _ in range(num_layers): + mask_out_chans = mask_in_chans * (stride**2) + self.encoder.append( + nn.Conv2d( + mask_in_chans, + mask_out_chans, + kernel_size=kernel_size, + stride=stride, + padding=padding, + ) + ) + self.encoder.append(LayerNorm2d(mask_out_chans)) + self.encoder.append(activation()) + mask_in_chans = mask_out_chans + + self.encoder.append(nn.Conv2d(mask_out_chans, embed_dim, kernel_size=1)) + + def forward(self, x): + return self.encoder(x) + + +# Lightly adapted from ConvNext (https://github.com/facebookresearch/ConvNeXt) +class CXBlock(nn.Module): + r"""ConvNeXt Block. There are two equivalent implementations: + (1) DwConv -> LayerNorm (channels_first) -> 1x1 Conv -> GELU -> 1x1 Conv; all in (N, C, H, W) + (2) DwConv -> Permute to (N, H, W, C); LayerNorm (channels_last) -> Linear -> GELU -> Linear; Permute back + We use (2) as we find it slightly faster in PyTorch + + Args: + dim (int): Number of input channels. + drop_path (float): Stochastic depth rate. Default: 0.0 + layer_scale_init_value (float): Init value for Layer Scale. Default: 1e-6. + """ + + def __init__( + self, + dim, + kernel_size=7, + padding=3, + drop_path=0.0, + layer_scale_init_value=1e-6, + use_dwconv=True, + ): + super().__init__() + self.dwconv = nn.Conv2d( + dim, + dim, + kernel_size=kernel_size, + padding=padding, + groups=dim if use_dwconv else 1, + ) # depthwise conv + self.norm = LayerNorm2d(dim, eps=1e-6) + self.pwconv1 = nn.Linear( + dim, 4 * dim + ) # pointwise/1x1 convs, implemented with linear layers + self.act = nn.GELU() + self.pwconv2 = nn.Linear(4 * dim, dim) + # modified by ZhangYx from self.gamma to self.weight. Due to (https://github.com/facebookresearch/segment-anything-2/issues/85) + self.weight = ( + nn.Parameter(layer_scale_init_value * torch.ones((dim)), requires_grad=True) + if layer_scale_init_value > 0 + else None + ) + self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity() + + def forward(self, x): + input = x + x = self.dwconv(x) + x = self.norm(x) + x = x.permute(0, 2, 3, 1) # (N, C, H, W) -> (N, H, W, C) + x = self.pwconv1(x) + x = self.act(x) + x = self.pwconv2(x) + if self.weight is not None: + x = self.weight * x + x = x.permute(0, 3, 1, 2) # (N, H, W, C) -> (N, C, H, W) + + x = input + self.drop_path(x) + return x + + +class Fuser(nn.Module): + def __init__(self, layer, num_layers, dim=None, input_projection=False): + super().__init__() + self.proj = nn.Identity() + self.layers = get_clones(layer, num_layers) + + if input_projection: + assert dim is not None + self.proj = nn.Conv2d(dim, dim, kernel_size=1) + + def forward(self, x): + # normally x: (N, C, H, W) + x = self.proj(x) + for layer in self.layers: + x = layer(x) + return x + + +class MemoryEncoder(nn.Module): + def __init__( + self, + out_dim, + mask_downsampler, + fuser, + position_encoding, + in_dim=256, # in_dim of pix_feats + ): + super().__init__() + + self.mask_downsampler = mask_downsampler + + self.pix_feat_proj = nn.Conv2d(in_dim, in_dim, kernel_size=1) + self.fuser = fuser + self.position_encoding = position_encoding + self.out_proj = nn.Identity() + if out_dim != in_dim: + self.out_proj = nn.Conv2d(in_dim, out_dim, kernel_size=1) + + def forward( + self, + pix_feat: torch.Tensor, + masks: torch.Tensor, + skip_mask_sigmoid: bool = False, + ) -> Tuple[torch.Tensor, torch.Tensor]: + ## Process masks + # sigmoid, so that less domain shift from gt masks which are bool + if not skip_mask_sigmoid: + masks = F.sigmoid(masks) + masks = self.mask_downsampler(masks) + + ## Fuse pix_feats and downsampled masks + # in case the visual features are on CPU, cast them to CUDA + pix_feat = pix_feat.to(masks.device) + + x = self.pix_feat_proj(pix_feat) + x = x + masks + x = self.fuser(x) + x = self.out_proj(x) + + pos = self.position_encoding(x).to(x.dtype) + + return {"vision_features": x, "vision_pos_enc": [pos]} diff --git a/py/evf_sam/model/segment_anything_2/sam2/modeling/position_encoding.py b/py/evf_sam/model/segment_anything_2/sam2/modeling/position_encoding.py new file mode 100644 index 0000000..f4b57ae --- /dev/null +++ b/py/evf_sam/model/segment_anything_2/sam2/modeling/position_encoding.py @@ -0,0 +1,216 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import math +from typing import Any, Optional, Tuple + +import numpy as np + +import torch +from torch import nn + + +class PositionEmbeddingSine(nn.Module): + """ + This is a more standard version of the position embedding, very similar to the one + used by the Attention is all you need paper, generalized to work on images. + """ + + def __init__( + self, + num_pos_feats, + temperature: int = 10000, + normalize: bool = True, + scale: Optional[float] = None, + ): + super().__init__() + assert num_pos_feats % 2 == 0, "Expecting even model width" + self.num_pos_feats = num_pos_feats // 2 + self.temperature = temperature + self.normalize = normalize + if scale is not None and normalize is False: + raise ValueError("normalize should be True if scale is passed") + if scale is None: + scale = 2 * math.pi + self.scale = scale + + self.cache = {} + + def _encode_xy(self, x, y): + # The positions are expected to be normalized + assert len(x) == len(y) and x.ndim == y.ndim == 1 + x_embed = x * self.scale + y_embed = y * self.scale + + dim_t = torch.arange(self.num_pos_feats, dtype=torch.float32, device=x.device) + dim_t = self.temperature ** (2 * (dim_t // 2) / self.num_pos_feats) + + pos_x = x_embed[:, None] / dim_t + pos_y = y_embed[:, None] / dim_t + pos_x = torch.stack( + (pos_x[:, 0::2].sin(), pos_x[:, 1::2].cos()), dim=2 + ).flatten(1) + pos_y = torch.stack( + (pos_y[:, 0::2].sin(), pos_y[:, 1::2].cos()), dim=2 + ).flatten(1) + return pos_x, pos_y + + @torch.no_grad() + def encode_boxes(self, x, y, w, h): + pos_x, pos_y = self._encode_xy(x, y) + pos = torch.cat((pos_y, pos_x, h[:, None], w[:, None]), dim=1) + return pos + + encode = encode_boxes # Backwards compatibility + + @torch.no_grad() + def encode_points(self, x, y, labels): + (bx, nx), (by, ny), (bl, nl) = x.shape, y.shape, labels.shape + assert bx == by and nx == ny and bx == bl and nx == nl + pos_x, pos_y = self._encode_xy(x.flatten(), y.flatten()) + pos_x, pos_y = pos_x.reshape(bx, nx, -1), pos_y.reshape(by, ny, -1) + pos = torch.cat((pos_y, pos_x, labels[:, :, None]), dim=2) + return pos + + @torch.no_grad() + def forward(self, x: torch.Tensor): + cache_key = (x.shape[-2], x.shape[-1]) + if cache_key in self.cache: + return self.cache[cache_key][None].repeat(x.shape[0], 1, 1, 1) + y_embed = ( + torch.arange(1, x.shape[-2] + 1, dtype=torch.float32, device=x.device) + .view(1, -1, 1) + .repeat(x.shape[0], 1, x.shape[-1]) + ) + x_embed = ( + torch.arange(1, x.shape[-1] + 1, dtype=torch.float32, device=x.device) + .view(1, 1, -1) + .repeat(x.shape[0], x.shape[-2], 1) + ) + + if self.normalize: + eps = 1e-6 + y_embed = y_embed / (y_embed[:, -1:, :] + eps) * self.scale + x_embed = x_embed / (x_embed[:, :, -1:] + eps) * self.scale + + dim_t = torch.arange(self.num_pos_feats, dtype=torch.float32, device=x.device) + dim_t = self.temperature ** (2 * (dim_t // 2) / self.num_pos_feats) + + pos_x = x_embed[:, :, :, None] / dim_t + pos_y = y_embed[:, :, :, None] / dim_t + pos_x = torch.stack( + (pos_x[:, :, :, 0::2].sin(), pos_x[:, :, :, 1::2].cos()), dim=4 + ).flatten(3) + pos_y = torch.stack( + (pos_y[:, :, :, 0::2].sin(), pos_y[:, :, :, 1::2].cos()), dim=4 + ).flatten(3) + pos = torch.cat((pos_y, pos_x), dim=3).permute(0, 3, 1, 2) + self.cache[cache_key] = pos[0] + return pos + + +class PositionEmbeddingRandom(nn.Module): + """ + Positional encoding using random spatial frequencies. + """ + + def __init__(self, num_pos_feats: int = 64, scale: Optional[float] = None) -> None: + super().__init__() + if scale is None or scale <= 0.0: + scale = 1.0 + self.register_buffer( + "positional_encoding_gaussian_matrix", + scale * torch.randn((2, num_pos_feats)), + ) + + def _pe_encoding(self, coords: torch.Tensor) -> torch.Tensor: + """Positionally encode points that are normalized to [0,1].""" + # assuming coords are in [0, 1]^2 square and have d_1 x ... x d_n x 2 shape + coords = 2 * coords - 1 + coords = coords @ self.positional_encoding_gaussian_matrix + coords = 2 * np.pi * coords + # outputs d_1 x ... x d_n x C shape + return torch.cat([torch.sin(coords), torch.cos(coords)], dim=-1) + + def forward(self, size: Tuple[int, int]) -> torch.Tensor: + """Generate positional encoding for a grid of the specified size.""" + h, w = size + device: Any = self.positional_encoding_gaussian_matrix.device + grid = torch.ones((h, w), device=device, dtype=torch.float32) + y_embed = grid.cumsum(dim=0) - 0.5 + x_embed = grid.cumsum(dim=1) - 0.5 + y_embed = y_embed / h + x_embed = x_embed / w + + pe = self._pe_encoding(torch.stack([x_embed, y_embed], dim=-1)) + return pe.permute(2, 0, 1) # C x H x W + + def forward_with_coords( + self, coords_input: torch.Tensor, image_size: Tuple[int, int] + ) -> torch.Tensor: + """Positionally encode points that are not normalized to [0,1].""" + coords = coords_input.clone() + coords[:, :, 0] = coords[:, :, 0] / image_size[1] + coords[:, :, 1] = coords[:, :, 1] / image_size[0] + return self._pe_encoding(coords.to(torch.float)) # B x N x C + + +# Rotary Positional Encoding, adapted from: +# 1. https://github.com/meta-llama/codellama/blob/main/llama/model.py +# 2. https://github.com/naver-ai/rope-vit +# 3. https://github.com/lucidrains/rotary-embedding-torch + + +def init_t_xy(end_x: int, end_y: int): + t = torch.arange(end_x * end_y, dtype=torch.float32) + t_x = (t % end_x).float() + t_y = torch.div(t, end_x, rounding_mode="floor").float() + return t_x, t_y + + +def compute_axial_cis(dim: int, end_x: int, end_y: int, theta: float = 10000.0): + freqs_x = 1.0 / (theta ** (torch.arange(0, dim, 4)[: (dim // 4)].float() / dim)) + freqs_y = 1.0 / (theta ** (torch.arange(0, dim, 4)[: (dim // 4)].float() / dim)) + + t_x, t_y = init_t_xy(end_x, end_y) + freqs_x = torch.outer(t_x, freqs_x) + freqs_y = torch.outer(t_y, freqs_y) + freqs_cis_x = torch.polar(torch.ones_like(freqs_x), freqs_x) + freqs_cis_y = torch.polar(torch.ones_like(freqs_y), freqs_y) + return torch.cat([freqs_cis_x, freqs_cis_y], dim=-1) + + +def reshape_for_broadcast(freqs_cis: torch.Tensor, x: torch.Tensor): + ndim = x.ndim + assert 0 <= 1 < ndim + assert freqs_cis.shape == (x.shape[-2], x.shape[-1]) + shape = [d if i >= ndim - 2 else 1 for i, d in enumerate(x.shape)] + return freqs_cis.view(*shape) + + +def apply_rotary_enc( + xq: torch.Tensor, + xk: torch.Tensor, + freqs_cis: torch.Tensor, + repeat_freqs_k: bool = False, +): + xq_ = torch.view_as_complex(xq.float().reshape(*xq.shape[:-1], -1, 2)) + xk_ = ( + torch.view_as_complex(xk.float().reshape(*xk.shape[:-1], -1, 2)) + if xk.shape[-2] != 0 + else None + ) + freqs_cis = reshape_for_broadcast(freqs_cis, xq_) + xq_out = torch.view_as_real(xq_ * freqs_cis).flatten(3) + if xk_ is None: + # no keys to rotate, due to dropout + return xq_out.type_as(xq).to(xq.device), xk + # repeat freqs along seq_len dim to match k seq_len + if repeat_freqs_k: + r = xk_.shape[-2] // xq_.shape[-2] + freqs_cis = freqs_cis.repeat(*([1] * (freqs_cis.ndim - 2)), r, 1) + xk_out = torch.view_as_real(xk_ * freqs_cis).flatten(3) + return xq_out.type_as(xq).to(xq.device), xk_out.type_as(xk).to(xk.device) diff --git a/py/evf_sam/model/segment_anything_2/sam2/modeling/sam/__init__.py b/py/evf_sam/model/segment_anything_2/sam2/modeling/sam/__init__.py new file mode 100644 index 0000000..5277f46 --- /dev/null +++ b/py/evf_sam/model/segment_anything_2/sam2/modeling/sam/__init__.py @@ -0,0 +1,5 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. diff --git a/py/evf_sam/model/segment_anything_2/sam2/modeling/sam/mask_decoder.py b/py/evf_sam/model/segment_anything_2/sam2/modeling/sam/mask_decoder.py new file mode 100644 index 0000000..1992910 --- /dev/null +++ b/py/evf_sam/model/segment_anything_2/sam2/modeling/sam/mask_decoder.py @@ -0,0 +1,295 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +from typing import List, Optional, Tuple, Type + +import torch +from torch import nn + +from model.segment_anything_2.sam2.modeling.sam2_utils import LayerNorm2d, MLP + + +class MaskDecoder(nn.Module): + def __init__( + self, + *, + transformer_dim: int, + transformer: nn.Module, + num_multimask_outputs: int = 3, + activation: Type[nn.Module] = nn.GELU, + iou_head_depth: int = 3, + iou_head_hidden_dim: int = 256, + use_high_res_features: bool = False, + iou_prediction_use_sigmoid=False, + dynamic_multimask_via_stability=False, + dynamic_multimask_stability_delta=0.05, + dynamic_multimask_stability_thresh=0.98, + pred_obj_scores: bool = False, + pred_obj_scores_mlp: bool = False, + use_multimask_token_for_obj_ptr: bool = False, + ) -> None: + """ + Predicts masks given an image and prompt embeddings, using a + transformer architecture. + + Arguments: + transformer_dim (int): the channel dimension of the transformer + transformer (nn.Module): the transformer used to predict masks + num_multimask_outputs (int): the number of masks to predict + when disambiguating masks + activation (nn.Module): the type of activation to use when + upscaling masks + iou_head_depth (int): the depth of the MLP used to predict + mask quality + iou_head_hidden_dim (int): the hidden dimension of the MLP + used to predict mask quality + """ + super().__init__() + self.transformer_dim = transformer_dim + self.transformer = transformer + + self.num_multimask_outputs = num_multimask_outputs + + self.iou_token = nn.Embedding(1, transformer_dim) + self.num_mask_tokens = num_multimask_outputs + 1 + self.mask_tokens = nn.Embedding(self.num_mask_tokens, transformer_dim) + + self.pred_obj_scores = pred_obj_scores + if self.pred_obj_scores: + self.obj_score_token = nn.Embedding(1, transformer_dim) + self.use_multimask_token_for_obj_ptr = use_multimask_token_for_obj_ptr + + self.output_upscaling = nn.Sequential( + nn.ConvTranspose2d( + transformer_dim, transformer_dim // 4, kernel_size=2, stride=2 + ), + LayerNorm2d(transformer_dim // 4), + activation(), + nn.ConvTranspose2d( + transformer_dim // 4, transformer_dim // 8, kernel_size=2, stride=2 + ), + activation(), + ) + self.use_high_res_features = use_high_res_features + if use_high_res_features: + self.conv_s0 = nn.Conv2d( + transformer_dim, transformer_dim // 8, kernel_size=1, stride=1 + ) + self.conv_s1 = nn.Conv2d( + transformer_dim, transformer_dim // 4, kernel_size=1, stride=1 + ) + + self.output_hypernetworks_mlps = nn.ModuleList( + [ + MLP(transformer_dim, transformer_dim, transformer_dim // 8, 3) + for i in range(self.num_mask_tokens) + ] + ) + + self.iou_prediction_head = MLP( + transformer_dim, + iou_head_hidden_dim, + self.num_mask_tokens, + iou_head_depth, + sigmoid_output=iou_prediction_use_sigmoid, + ) + if self.pred_obj_scores: + self.pred_obj_score_head = nn.Linear(transformer_dim, 1) + if pred_obj_scores_mlp: + self.pred_obj_score_head = MLP(transformer_dim, transformer_dim, 1, 3) + + # When outputting a single mask, optionally we can dynamically fall back to the best + # multimask output token if the single mask output token gives low stability scores. + self.dynamic_multimask_via_stability = dynamic_multimask_via_stability + self.dynamic_multimask_stability_delta = dynamic_multimask_stability_delta + self.dynamic_multimask_stability_thresh = dynamic_multimask_stability_thresh + + def forward( + self, + image_embeddings: torch.Tensor, + image_pe: torch.Tensor, + sparse_prompt_embeddings: torch.Tensor, + dense_prompt_embeddings: torch.Tensor, + multimask_output: bool, + repeat_image: bool, + high_res_features: Optional[List[torch.Tensor]] = None, + ) -> Tuple[torch.Tensor, torch.Tensor]: + """ + Predict masks given image and prompt embeddings. + + Arguments: + image_embeddings (torch.Tensor): the embeddings from the image encoder + image_pe (torch.Tensor): positional encoding with the shape of image_embeddings + sparse_prompt_embeddings (torch.Tensor): the embeddings of the points and boxes + dense_prompt_embeddings (torch.Tensor): the embeddings of the mask inputs + multimask_output (bool): Whether to return multiple masks or a single + mask. + + Returns: + torch.Tensor: batched predicted masks + torch.Tensor: batched predictions of mask quality + torch.Tensor: batched SAM token for mask output + """ + masks, iou_pred, mask_tokens_out, object_score_logits = self.predict_masks( + image_embeddings=image_embeddings, + image_pe=image_pe, + sparse_prompt_embeddings=sparse_prompt_embeddings, + dense_prompt_embeddings=dense_prompt_embeddings, + repeat_image=repeat_image, + high_res_features=high_res_features, + ) + + # Select the correct mask or masks for output + if multimask_output: + masks = masks[:, 1:, :, :] + iou_pred = iou_pred[:, 1:] + elif self.dynamic_multimask_via_stability and not self.training: + masks, iou_pred = self._dynamic_multimask_via_stability(masks, iou_pred) + else: + masks = masks[:, 0:1, :, :] + iou_pred = iou_pred[:, 0:1] + + if multimask_output and self.use_multimask_token_for_obj_ptr: + sam_tokens_out = mask_tokens_out[:, 1:] # [b, 3, c] shape + else: + # Take the mask output token. Here we *always* use the token for single mask output. + # At test time, even if we track after 1-click (and using multimask_output=True), + # we still take the single mask token here. The rationale is that we always track + # after multiple clicks during training, so the past tokens seen during training + # are always the single mask token (and we'll let it be the object-memory token). + sam_tokens_out = mask_tokens_out[:, 0:1] # [b, 1, c] shape + + # Prepare output + return masks, iou_pred, sam_tokens_out, object_score_logits + + def predict_masks( + self, + image_embeddings: torch.Tensor, + image_pe: torch.Tensor, + sparse_prompt_embeddings: torch.Tensor, + dense_prompt_embeddings: torch.Tensor, + repeat_image: bool, + high_res_features: Optional[List[torch.Tensor]] = None, + ) -> Tuple[torch.Tensor, torch.Tensor]: + """Predicts masks. See 'forward' for more details.""" + # Concatenate output tokens + s = 0 + if self.pred_obj_scores: + output_tokens = torch.cat( + [ + self.obj_score_token.weight, + self.iou_token.weight, + self.mask_tokens.weight, + ], + dim=0, + ) + s = 1 + else: + output_tokens = torch.cat( + [self.iou_token.weight, self.mask_tokens.weight], dim=0 + ) + output_tokens = output_tokens.unsqueeze(0).expand( + sparse_prompt_embeddings.size(0), -1, -1 + ) + tokens = torch.cat((output_tokens, sparse_prompt_embeddings), dim=1) + + # Expand per-image data in batch direction to be per-mask + if repeat_image: + src = torch.repeat_interleave(image_embeddings, tokens.shape[0], dim=0) + else: + assert image_embeddings.shape[0] == tokens.shape[0] + src = image_embeddings + src = src + dense_prompt_embeddings + assert ( + image_pe.size(0) == 1 + ), "image_pe should have size 1 in batch dim (from `get_dense_pe()`)" + pos_src = torch.repeat_interleave(image_pe, tokens.shape[0], dim=0) + b, c, h, w = src.shape + + # Run the transformer + hs, src = self.transformer(src, pos_src, tokens) + iou_token_out = hs[:, s, :] + mask_tokens_out = hs[:, s + 1 : (s + 1 + self.num_mask_tokens), :] + + # Upscale mask embeddings and predict masks using the mask tokens + src = src.transpose(1, 2).view(b, c, h, w) + if not self.use_high_res_features: + upscaled_embedding = self.output_upscaling(src) + else: + dc1, ln1, act1, dc2, act2 = self.output_upscaling + feat_s0, feat_s1 = high_res_features + upscaled_embedding = act1(ln1(dc1(src) + feat_s1)) + upscaled_embedding = act2(dc2(upscaled_embedding) + feat_s0) + + hyper_in_list: List[torch.Tensor] = [] + for i in range(self.num_mask_tokens): + hyper_in_list.append( + self.output_hypernetworks_mlps[i](mask_tokens_out[:, i, :]) + ) + hyper_in = torch.stack(hyper_in_list, dim=1) + b, c, h, w = upscaled_embedding.shape + masks = (hyper_in @ upscaled_embedding.view(b, c, h * w)).view(b, -1, h, w) + + # Generate mask quality predictions + iou_pred = self.iou_prediction_head(iou_token_out) + if self.pred_obj_scores: + assert s == 1 + object_score_logits = self.pred_obj_score_head(hs[:, 0, :]) + else: + # Obj scores logits - default to 10.0, i.e. assuming the object is present, sigmoid(10)=1 + object_score_logits = 10.0 * iou_pred.new_ones(iou_pred.shape[0], 1) + + return masks, iou_pred, mask_tokens_out, object_score_logits + + def _get_stability_scores(self, mask_logits): + """ + Compute stability scores of the mask logits based on the IoU between upper and + lower thresholds, similar to https://github.com/fairinternal/onevision/pull/568. + """ + mask_logits = mask_logits.flatten(-2) + stability_delta = self.dynamic_multimask_stability_delta + area_i = torch.sum(mask_logits > stability_delta, dim=-1).float() + area_u = torch.sum(mask_logits > -stability_delta, dim=-1).float() + stability_scores = torch.where(area_u > 0, area_i / area_u, 1.0) + return stability_scores + + def _dynamic_multimask_via_stability(self, all_mask_logits, all_iou_scores): + """ + When outputting a single mask, if the stability score from the current single-mask + output (based on output token 0) falls below a threshold, we instead select from + multi-mask outputs (based on output token 1~3) the mask with the highest predicted + IoU score. This is intended to ensure a valid mask for both clicking and tracking. + """ + # The best mask from multimask output tokens (1~3) + multimask_logits = all_mask_logits[:, 1:, :, :] + multimask_iou_scores = all_iou_scores[:, 1:] + best_scores_inds = torch.argmax(multimask_iou_scores, dim=-1) + batch_inds = torch.arange( + multimask_iou_scores.size(0), device=all_iou_scores.device + ) + best_multimask_logits = multimask_logits[batch_inds, best_scores_inds] + best_multimask_logits = best_multimask_logits.unsqueeze(1) + best_multimask_iou_scores = multimask_iou_scores[batch_inds, best_scores_inds] + best_multimask_iou_scores = best_multimask_iou_scores.unsqueeze(1) + + # The mask from singlemask output token 0 and its stability score + singlemask_logits = all_mask_logits[:, 0:1, :, :] + singlemask_iou_scores = all_iou_scores[:, 0:1] + stability_scores = self._get_stability_scores(singlemask_logits) + is_stable = stability_scores >= self.dynamic_multimask_stability_thresh + + # Dynamically fall back to best multimask output upon low stability scores. + mask_logits_out = torch.where( + is_stable[..., None, None].expand_as(singlemask_logits), + singlemask_logits, + best_multimask_logits, + ) + iou_scores_out = torch.where( + is_stable.expand_as(singlemask_iou_scores), + singlemask_iou_scores, + best_multimask_iou_scores, + ) + return mask_logits_out, iou_scores_out diff --git a/py/evf_sam/model/segment_anything_2/sam2/modeling/sam/prompt_encoder.py b/py/evf_sam/model/segment_anything_2/sam2/modeling/sam/prompt_encoder.py new file mode 100644 index 0000000..44fb6c5 --- /dev/null +++ b/py/evf_sam/model/segment_anything_2/sam2/modeling/sam/prompt_encoder.py @@ -0,0 +1,241 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +from typing import Any, Optional, Tuple, Type + +import numpy as np +import torch +from torch import nn +# from model.segment_anything_2.sam2.modeling.position_encoding import PositionEmbeddingRandom + +from model.segment_anything_2.sam2.modeling.sam2_utils import LayerNorm2d + + +class PromptEncoder(nn.Module): + def __init__( + self, + embed_dim: int, + image_embedding_size: Tuple[int, int], + input_image_size: Tuple[int, int], + mask_in_chans: int, + activation: Type[nn.Module] = nn.GELU, + ) -> None: + """ + Encodes prompts for input to SAM's mask decoder. + + Arguments: + embed_dim (int): The prompts' embedding dimension + image_embedding_size (tuple(int, int)): The spatial size of the + image embedding, as (H, W). + input_image_size (int): The padded size of the image as input + to the image encoder, as (H, W). + mask_in_chans (int): The number of hidden channels used for + encoding input masks. + activation (nn.Module): The activation to use when encoding + input masks. + """ + super().__init__() + self.embed_dim = embed_dim + self.input_image_size = input_image_size + self.image_embedding_size = image_embedding_size + self.pe_layer = PositionEmbeddingRandom(embed_dim // 2) + + self.num_point_embeddings: int = 4 # pos/neg point + 2 box corners + point_embeddings = [ + nn.Embedding(1, embed_dim) for i in range(self.num_point_embeddings) + ] + self.point_embeddings = nn.ModuleList(point_embeddings) + self.not_a_point_embed = nn.Embedding(1, embed_dim) + + self.mask_input_size = ( + 4 * image_embedding_size[0], + 4 * image_embedding_size[1], + ) + self.mask_downscaling = nn.Sequential( + nn.Conv2d(1, mask_in_chans // 4, kernel_size=2, stride=2), + LayerNorm2d(mask_in_chans // 4), + activation(), + nn.Conv2d(mask_in_chans // 4, mask_in_chans, kernel_size=2, stride=2), + LayerNorm2d(mask_in_chans), + activation(), + nn.Conv2d(mask_in_chans, embed_dim, kernel_size=1), + ) + self.no_mask_embed = nn.Embedding(1, embed_dim) + + def get_dense_pe(self) -> torch.Tensor: + """ + Returns the positional encoding used to encode point prompts, + applied to a dense set of points the shape of the image encoding. + + Returns: + torch.Tensor: Positional encoding with shape + 1x(embed_dim)x(embedding_h)x(embedding_w) + """ + return self.pe_layer(self.image_embedding_size).unsqueeze(0) + + def _embed_points( + self, + points: torch.Tensor, + labels: torch.Tensor, + pad: bool, + ) -> torch.Tensor: + """Embeds point prompts.""" + points = points + 0.5 # Shift to center of pixel + if pad: + padding_point = torch.zeros((points.shape[0], 1, 2), device=points.device) + padding_label = -torch.ones((labels.shape[0], 1), device=labels.device) + points = torch.cat([points, padding_point], dim=1) + labels = torch.cat([labels, padding_label], dim=1) + point_embedding = self.pe_layer.forward_with_coords( + points, self.input_image_size + ) + point_embedding[labels == -1] = 0.0 + point_embedding[labels == -1] += self.not_a_point_embed.weight + point_embedding[labels == 0] += self.point_embeddings[0].weight + point_embedding[labels == 1] += self.point_embeddings[1].weight + point_embedding[labels == 2] += self.point_embeddings[2].weight + point_embedding[labels == 3] += self.point_embeddings[3].weight + return point_embedding + + def _embed_boxes(self, boxes: torch.Tensor) -> torch.Tensor: + """Embeds box prompts.""" + boxes = boxes + 0.5 # Shift to center of pixel + coords = boxes.reshape(-1, 2, 2) + corner_embedding = self.pe_layer.forward_with_coords( + coords, self.input_image_size + ) + corner_embedding[:, 0, :] += self.point_embeddings[2].weight + corner_embedding[:, 1, :] += self.point_embeddings[3].weight + return corner_embedding + + def _embed_masks(self, masks: torch.Tensor) -> torch.Tensor: + """Embeds mask inputs.""" + mask_embedding = self.mask_downscaling(masks) + return mask_embedding + + def _get_batch_size( + self, + points: Optional[Tuple[torch.Tensor, torch.Tensor]], + boxes: Optional[torch.Tensor], + masks: Optional[torch.Tensor], + text_embeds: Optional[torch.Tensor], + ) -> int: + """ + Gets the batch size of the output given the batch size of the input prompts. + """ + if points is not None: + return points[0].shape[0] + elif boxes is not None: + return boxes.shape[0] + elif masks is not None: + return masks.shape[0] + elif text_embeds is not None: + return text_embeds.shape[0] + else: + return 1 + + def _get_device(self) -> torch.device: + return self.point_embeddings[0].weight.device + + def forward( + self, + points: Optional[Tuple[torch.Tensor, torch.Tensor]], + boxes: Optional[torch.Tensor], + masks: Optional[torch.Tensor], + text_embeds: Optional[torch.Tensor], + ) -> Tuple[torch.Tensor, torch.Tensor]: + """ + Embeds different types of prompts, returning both sparse and dense + embeddings. + + Arguments: + points (tuple(torch.Tensor, torch.Tensor) or none): point coordinates + and labels to embed. + boxes (torch.Tensor or none): boxes to embed + masks (torch.Tensor or none): masks to embed + + Returns: + torch.Tensor: sparse embeddings for the points and boxes, with shape + BxNx(embed_dim), where N is determined by the number of input points + and boxes. + torch.Tensor: dense embeddings for the masks, in the shape + Bx(embed_dim)x(embed_H)x(embed_W) + """ + bs = self._get_batch_size(points, boxes, masks, text_embeds) + sparse_embeddings = torch.empty( + (bs, 0, self.embed_dim), device=self._get_device() + ) + if points is not None: + coords, labels = points + point_embeddings = self._embed_points(coords, labels, pad=(boxes is None)) + sparse_embeddings = torch.cat([sparse_embeddings, point_embeddings], dim=1) + if boxes is not None: + box_embeddings = self._embed_boxes(boxes) + sparse_embeddings = torch.cat([sparse_embeddings, box_embeddings], dim=1) + + if text_embeds is not None: + sparse_embeddings = torch.cat([sparse_embeddings, text_embeds], dim=1) + + if masks is not None: + dense_embeddings = self._embed_masks(masks) + else: + dense_embeddings = self.no_mask_embed.weight.reshape(1, -1, 1, 1).expand( + bs, -1, self.image_embedding_size[0], self.image_embedding_size[1] + ) + + return sparse_embeddings, dense_embeddings + + +class PositionEmbeddingRandom(nn.Module): + """ + Positional encoding using random spatial frequencies. + """ + + def __init__(self, num_pos_feats: int = 64, scale: Optional[float] = None) -> None: + super().__init__() + if scale is None or scale <= 0.0: + scale = 1.0 + self.register_buffer( + "positional_encoding_gaussian_matrix", + scale * torch.randn((2, num_pos_feats)), + ) + + def _pe_encoding(self, coords: torch.Tensor) -> torch.Tensor: + """Positionally encode points that are normalized to [0,1].""" + # assuming coords are in [0, 1]^2 square and have d_1 x ... x d_n x 2 shape + coords = 2 * coords - 1 + + if coords.dtype != self.positional_encoding_gaussian_matrix.dtype: + coords = coords.to(self.positional_encoding_gaussian_matrix.dtype) + + coords = coords @ self.positional_encoding_gaussian_matrix + coords = 2 * np.pi * coords + # outputs d_1 x ... x d_n x C shape + return torch.cat([torch.sin(coords), torch.cos(coords)], dim=-1) + + def forward(self, size: Tuple[int, int]) -> torch.Tensor: + """Generate positional encoding for a grid of the specified size.""" + h, w = size + device: Any = self.positional_encoding_gaussian_matrix.device + grid = torch.ones( + (h, w), device=device, dtype=self.positional_encoding_gaussian_matrix.dtype + ) + y_embed = grid.cumsum(dim=0) - 0.5 + x_embed = grid.cumsum(dim=1) - 0.5 + y_embed = y_embed / h + x_embed = x_embed / w + + pe = self._pe_encoding(torch.stack([x_embed, y_embed], dim=-1)) + return pe.permute(2, 0, 1) # C x H x W + + def forward_with_coords( + self, coords_input: torch.Tensor, image_size: Tuple[int, int] + ) -> torch.Tensor: + """Positionally encode points that are not normalized to [0,1].""" + coords = coords_input.clone() + coords[:, :, 0] = coords[:, :, 0] / image_size[1] + coords[:, :, 1] = coords[:, :, 1] / image_size[0] + return self._pe_encoding(coords.to(torch.float)) # B x N x C diff --git a/py/evf_sam/model/segment_anything_2/sam2/modeling/sam/transformer.py b/py/evf_sam/model/segment_anything_2/sam2/modeling/sam/transformer.py new file mode 100644 index 0000000..dae74f5 --- /dev/null +++ b/py/evf_sam/model/segment_anything_2/sam2/modeling/sam/transformer.py @@ -0,0 +1,330 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import math +import warnings +from functools import partial +from typing import Tuple, Type + +import torch +import torch.nn.functional as F +from torch import nn, Tensor + +from model.segment_anything_2.sam2.modeling.position_encoding import apply_rotary_enc, compute_axial_cis + +from model.segment_anything_2.sam2.modeling.sam2_utils import MLP +from model.segment_anything_2.sam2.utils.misc import get_sdpa_settings + +warnings.simplefilter(action="ignore", category=FutureWarning) +# OLD_GPU, USE_FLASH_ATTN, MATH_KERNEL_ON = get_sdpa_settings() +USE_FLASH_ATTN = False +MATH_KERNEL_ON = True +OLD_GPU = True + + +class TwoWayTransformer(nn.Module): + def __init__( + self, + depth: int, + embedding_dim: int, + num_heads: int, + mlp_dim: int, + activation: Type[nn.Module] = nn.ReLU, + attention_downsample_rate: int = 2, + ) -> None: + """ + A transformer decoder that attends to an input image using + queries whose positional embedding is supplied. + + Args: + depth (int): number of layers in the transformer + embedding_dim (int): the channel dimension for the input embeddings + num_heads (int): the number of heads for multihead attention. Must + divide embedding_dim + mlp_dim (int): the channel dimension internal to the MLP block + activation (nn.Module): the activation to use in the MLP block + """ + super().__init__() + self.depth = depth + self.embedding_dim = embedding_dim + self.num_heads = num_heads + self.mlp_dim = mlp_dim + self.layers = nn.ModuleList() + + for i in range(depth): + self.layers.append( + TwoWayAttentionBlock( + embedding_dim=embedding_dim, + num_heads=num_heads, + mlp_dim=mlp_dim, + activation=activation, + attention_downsample_rate=attention_downsample_rate, + skip_first_layer_pe=(i == 0), + ) + ) + + self.final_attn_token_to_image = Attention( + embedding_dim, num_heads, downsample_rate=attention_downsample_rate + ) + self.norm_final_attn = nn.LayerNorm(embedding_dim) + + def forward( + self, + image_embedding: Tensor, + image_pe: Tensor, + point_embedding: Tensor, + ) -> Tuple[Tensor, Tensor]: + """ + Args: + image_embedding (torch.Tensor): image to attend to. Should be shape + B x embedding_dim x h x w for any h and w. + image_pe (torch.Tensor): the positional encoding to add to the image. Must + have the same shape as image_embedding. + point_embedding (torch.Tensor): the embedding to add to the query points. + Must have shape B x N_points x embedding_dim for any N_points. + + Returns: + torch.Tensor: the processed point_embedding + torch.Tensor: the processed image_embedding + """ + # BxCxHxW -> BxHWxC == B x N_image_tokens x C + bs, c, h, w = image_embedding.shape + image_embedding = image_embedding.flatten(2).permute(0, 2, 1) + image_pe = image_pe.flatten(2).permute(0, 2, 1) + + # Prepare queries + queries = point_embedding + keys = image_embedding + + # Apply transformer blocks and final layernorm + for layer in self.layers: + queries, keys = layer( + queries=queries, + keys=keys, + query_pe=point_embedding, + key_pe=image_pe, + ) + + # Apply the final attention layer from the points to the image + q = queries + point_embedding + k = keys + image_pe + attn_out = self.final_attn_token_to_image(q=q, k=k, v=keys) + queries = queries + attn_out + queries = self.norm_final_attn(queries) + + return queries, keys + + +class TwoWayAttentionBlock(nn.Module): + def __init__( + self, + embedding_dim: int, + num_heads: int, + mlp_dim: int = 2048, + activation: Type[nn.Module] = nn.ReLU, + attention_downsample_rate: int = 2, + skip_first_layer_pe: bool = False, + ) -> None: + """ + A transformer block with four layers: (1) self-attention of sparse + inputs, (2) cross attention of sparse inputs to dense inputs, (3) mlp + block on sparse inputs, and (4) cross attention of dense inputs to sparse + inputs. + + Arguments: + embedding_dim (int): the channel dimension of the embeddings + num_heads (int): the number of heads in the attention layers + mlp_dim (int): the hidden dimension of the mlp block + activation (nn.Module): the activation of the mlp block + skip_first_layer_pe (bool): skip the PE on the first layer + """ + super().__init__() + self.self_attn = Attention(embedding_dim, num_heads) + self.norm1 = nn.LayerNorm(embedding_dim) + + self.cross_attn_token_to_image = Attention( + embedding_dim, num_heads, downsample_rate=attention_downsample_rate + ) + self.norm2 = nn.LayerNorm(embedding_dim) + + self.mlp = MLP( + embedding_dim, mlp_dim, embedding_dim, num_layers=2, activation=activation + ) + self.norm3 = nn.LayerNorm(embedding_dim) + + self.norm4 = nn.LayerNorm(embedding_dim) + self.cross_attn_image_to_token = Attention( + embedding_dim, num_heads, downsample_rate=attention_downsample_rate + ) + + self.skip_first_layer_pe = skip_first_layer_pe + + def forward( + self, queries: Tensor, keys: Tensor, query_pe: Tensor, key_pe: Tensor + ) -> Tuple[Tensor, Tensor]: + # Self attention block + if self.skip_first_layer_pe: + queries = self.self_attn(q=queries, k=queries, v=queries) + else: + q = queries + query_pe + attn_out = self.self_attn(q=q, k=q, v=queries) + queries = queries + attn_out + queries = self.norm1(queries) + + # Cross attention block, tokens attending to image embedding + q = queries + query_pe + k = keys + key_pe + attn_out = self.cross_attn_token_to_image(q=q, k=k, v=keys) + queries = queries + attn_out + queries = self.norm2(queries) + + # MLP block + mlp_out = self.mlp(queries) + queries = queries + mlp_out + queries = self.norm3(queries) + + # Cross attention block, image embedding attending to tokens + q = queries + query_pe + k = keys + key_pe + attn_out = self.cross_attn_image_to_token(q=k, k=q, v=queries) + keys = keys + attn_out + keys = self.norm4(keys) + + return queries, keys + + +class Attention(nn.Module): + """ + An attention layer that allows for downscaling the size of the embedding + after projection to queries, keys, and values. + """ + + def __init__( + self, + embedding_dim: int, + num_heads: int, + downsample_rate: int = 1, + dropout: float = 0.0, + kv_in_dim: int = None, + ) -> None: + super().__init__() + self.embedding_dim = embedding_dim + self.kv_in_dim = kv_in_dim if kv_in_dim is not None else embedding_dim + self.internal_dim = embedding_dim // downsample_rate + self.num_heads = num_heads + assert ( + self.internal_dim % num_heads == 0 + ), "num_heads must divide embedding_dim." + + self.q_proj = nn.Linear(embedding_dim, self.internal_dim) + self.k_proj = nn.Linear(self.kv_in_dim, self.internal_dim) + self.v_proj = nn.Linear(self.kv_in_dim, self.internal_dim) + self.out_proj = nn.Linear(self.internal_dim, embedding_dim) + + self.dropout_p = dropout + + def _separate_heads(self, x: Tensor, num_heads: int) -> Tensor: + b, n, c = x.shape + x = x.reshape(b, n, num_heads, c // num_heads) + return x.transpose(1, 2) # B x N_heads x N_tokens x C_per_head + + def _recombine_heads(self, x: Tensor) -> Tensor: + b, n_heads, n_tokens, c_per_head = x.shape + x = x.transpose(1, 2) + return x.reshape(b, n_tokens, n_heads * c_per_head) # B x N_tokens x C + + def forward(self, q: Tensor, k: Tensor, v: Tensor) -> Tensor: + # Input projections + q = self.q_proj(q) + k = self.k_proj(k) + v = self.v_proj(v) + + # Separate into heads + q = self._separate_heads(q, self.num_heads) + k = self._separate_heads(k, self.num_heads) + v = self._separate_heads(v, self.num_heads) + + dropout_p = self.dropout_p if self.training else 0.0 + # Attention + with torch.backends.cuda.sdp_kernel( + enable_flash=USE_FLASH_ATTN, + # if Flash attention kernel is off, then math kernel needs to be enabled + enable_math=(OLD_GPU and dropout_p > 0.0) or MATH_KERNEL_ON, + enable_mem_efficient=OLD_GPU, + ): + out = F.scaled_dot_product_attention(q, k, v, dropout_p=dropout_p) + + out = self._recombine_heads(out) + out = self.out_proj(out) + + return out + + +class RoPEAttention(Attention): + """Attention with rotary position encoding.""" + + def __init__( + self, + *args, + rope_theta=10000.0, + # whether to repeat q rope to match k length + # this is needed for cross-attention to memories + rope_k_repeat=False, + feat_sizes=(32, 32), # [w, h] for stride 16 feats at 512 resolution + **kwargs, + ): + super().__init__(*args, **kwargs) + + self.compute_cis = partial( + compute_axial_cis, dim=self.internal_dim // self.num_heads, theta=rope_theta + ) + freqs_cis = self.compute_cis(end_x=feat_sizes[0], end_y=feat_sizes[1]) + self.freqs_cis = freqs_cis + self.rope_k_repeat = rope_k_repeat + + def forward( + self, q: Tensor, k: Tensor, v: Tensor, num_k_exclude_rope: int = 0 + ) -> Tensor: + # Input projections + q = self.q_proj(q) + k = self.k_proj(k) + v = self.v_proj(v) + + # Separate into heads + q = self._separate_heads(q, self.num_heads) + k = self._separate_heads(k, self.num_heads) + v = self._separate_heads(v, self.num_heads) + + # Apply rotary position encoding + w = h = math.sqrt(q.shape[-2]) + self.freqs_cis = self.freqs_cis.to(q.device) + if self.freqs_cis.shape[0] != q.shape[-2]: + self.freqs_cis = self.compute_cis(end_x=w, end_y=h).to(q.device) + if q.shape[-2] != k.shape[-2]: + assert self.rope_k_repeat + + num_k_rope = k.size(-2) - num_k_exclude_rope + q, k[:, :, :num_k_rope] = apply_rotary_enc( + q, + k[:, :, :num_k_rope], + freqs_cis=self.freqs_cis, + repeat_freqs_k=self.rope_k_repeat, + ) + + dropout_p = self.dropout_p if self.training else 0.0 + # Attention + with torch.backends.cuda.sdp_kernel( + enable_flash=USE_FLASH_ATTN, + # if Flash attention kernel is off, then math kernel needs to be enabled + enable_math=(OLD_GPU and dropout_p > 0.0) or MATH_KERNEL_ON, + enable_mem_efficient=OLD_GPU, + ): + out = F.scaled_dot_product_attention(q, k, v, dropout_p=dropout_p) + + out = self._recombine_heads(out) + out = self.out_proj(out) + + return out diff --git a/py/evf_sam/model/segment_anything_2/sam2/modeling/sam2_base.py b/py/evf_sam/model/segment_anything_2/sam2/modeling/sam2_base.py new file mode 100644 index 0000000..746f2ed --- /dev/null +++ b/py/evf_sam/model/segment_anything_2/sam2/modeling/sam2_base.py @@ -0,0 +1,833 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import torch +import torch.distributed +import torch.nn.functional as F + +from torch.nn.init import trunc_normal_ + +from model.segment_anything_2.sam2.modeling.sam.mask_decoder import MaskDecoder +from model.segment_anything_2.sam2.modeling.sam.prompt_encoder import PromptEncoder +from model.segment_anything_2.sam2.modeling.sam.transformer import TwoWayTransformer +from model.segment_anything_2.sam2.modeling.sam2_utils import get_1d_sine_pe, MLP, select_closest_cond_frames + +# a large negative value as a placeholder score for missing objects +NO_OBJ_SCORE = -1024.0 + + +class SAM2Base(torch.nn.Module): + def __init__( + self, + image_encoder, + memory_attention, + memory_encoder, + num_maskmem=7, # default 1 input frame + 6 previous frames + image_size=512, + backbone_stride=16, # stride of the image backbone output + sigmoid_scale_for_mem_enc=1.0, # scale factor for mask sigmoid prob + sigmoid_bias_for_mem_enc=0.0, # bias factor for mask sigmoid prob + # During evaluation, whether to binarize the sigmoid mask logits on interacted frames with clicks + binarize_mask_from_pts_for_mem_enc=False, + use_mask_input_as_output_without_sam=False, # on frames with mask input, whether to directly output the input mask without using a SAM prompt encoder + mask decoder + # The maximum number of conditioning frames to participate in the memory attention (-1 means no limit; if there are more conditioning frames than this limit, + # we only cross-attend to the temporally closest `max_cond_frames_in_attn` conditioning frames in the encoder when tracking each frame). This gives the model + # a temporal locality when handling a large number of annotated frames (since closer frames should be more important) and also avoids GPU OOM. + max_cond_frames_in_attn=-1, + # on the first frame, whether to directly add the no-memory embedding to the image feature + # (instead of using the transformer encoder) + directly_add_no_mem_embed=False, + # whether to use high-resolution feature maps in the SAM mask decoder + use_high_res_features_in_sam=False, + # whether to output multiple (3) masks for the first click on initial conditioning frames + multimask_output_in_sam=False, + # the minimum and maximum number of clicks to use multimask_output_in_sam (only relevant when `multimask_output_in_sam=True`; + # default is 1 for both, meaning that only the first click gives multimask output; also note that a box counts as two points) + multimask_min_pt_num=1, + multimask_max_pt_num=1, + # whether to also use multimask output for tracking (not just for the first click on initial conditioning frames; only relevant when `multimask_output_in_sam=True`) + multimask_output_for_tracking=False, + # Whether to use multimask tokens for obj ptr; Only relevant when both + # use_obj_ptrs_in_encoder=True and multimask_output_for_tracking=True + use_multimask_token_for_obj_ptr: bool = False, + # whether to use sigmoid to restrict ious prediction to [0-1] + iou_prediction_use_sigmoid=False, + # The memory bank's temporal stride during evaluation (i.e. the `r` parameter in XMem and Cutie; XMem and Cutie use r=5). + # For r>1, the (self.num_maskmem - 1) non-conditioning memory frames consist of + # (self.num_maskmem - 2) nearest frames from every r-th frames, plus the last frame. + memory_temporal_stride_for_eval=1, + # if `add_all_frames_to_correct_as_cond` is True, we also append to the conditioning frame list any frame that receives a later correction click + # if `add_all_frames_to_correct_as_cond` is False, we conditioning frame list to only use those initial conditioning frames + add_all_frames_to_correct_as_cond=False, + # whether to apply non-overlapping constraints on the object masks in the memory encoder during evaluation (to avoid/alleviate superposing masks) + non_overlap_masks_for_mem_enc=False, + # whether to cross-attend to object pointers from other frames (based on SAM output tokens) in the encoder + use_obj_ptrs_in_encoder=False, + # the maximum number of object pointers from other frames in encoder cross attention (only relevant when `use_obj_ptrs_in_encoder=True`) + max_obj_ptrs_in_encoder=16, + # whether to add temporal positional encoding to the object pointers in the encoder (only relevant when `use_obj_ptrs_in_encoder=True`) + add_tpos_enc_to_obj_ptrs=True, + # whether to add an extra linear projection layer for the temporal positional encoding in the object pointers to avoid potential interference + # with spatial positional encoding (only relevant when both `use_obj_ptrs_in_encoder=True` and `add_tpos_enc_to_obj_ptrs=True`) + proj_tpos_enc_in_obj_ptrs=False, + # whether to only attend to object pointers in the past (before the current frame) in the encoder during evaluation + # (only relevant when `use_obj_ptrs_in_encoder=True`; this might avoid pointer information too far in the future to distract the initial tracking) + only_obj_ptrs_in_the_past_for_eval=False, + # Whether to predict if there is an object in the frame + pred_obj_scores: bool = False, + # Whether to use an MLP to predict object scores + pred_obj_scores_mlp: bool = False, + # Only relevant if pred_obj_scores=True and use_obj_ptrs_in_encoder=True; + # Whether to have a fixed no obj pointer when there is no object present + # or to use it as an additive embedding with obj_ptr produced by decoder + fixed_no_obj_ptr: bool = False, + # Soft no object, i.e. mix in no_obj_ptr softly, + # hope to make recovery easier if there is a mistake and mitigate accumulation of errors + soft_no_obj_ptr: bool = False, + use_mlp_for_obj_ptr_proj: bool = False, + # extra arguments used to construct the SAM mask decoder; if not None, it should be a dict of kwargs to be passed into `MaskDecoder` class. + sam_mask_decoder_extra_args=None, + compile_image_encoder: bool = False, + ): + super().__init__() + + # Part 1: the image backbone + self.image_encoder = image_encoder + # Use level 0, 1, 2 for high-res setting, or just level 2 for the default setting + self.use_high_res_features_in_sam = use_high_res_features_in_sam + self.num_feature_levels = 3 if use_high_res_features_in_sam else 1 + self.use_obj_ptrs_in_encoder = use_obj_ptrs_in_encoder + self.max_obj_ptrs_in_encoder = max_obj_ptrs_in_encoder + if use_obj_ptrs_in_encoder: + # A conv layer to downsample the mask prompt to stride 4 (the same stride as + # low-res SAM mask logits) and to change its scales from 0~1 to SAM logit scale, + # so that it can be fed into the SAM mask decoder to generate a pointer. + self.mask_downsample = torch.nn.Conv2d(1, 1, kernel_size=4, stride=4) + self.add_tpos_enc_to_obj_ptrs = add_tpos_enc_to_obj_ptrs + if proj_tpos_enc_in_obj_ptrs: + assert add_tpos_enc_to_obj_ptrs # these options need to be used together + self.proj_tpos_enc_in_obj_ptrs = proj_tpos_enc_in_obj_ptrs + self.only_obj_ptrs_in_the_past_for_eval = only_obj_ptrs_in_the_past_for_eval + + # Part 2: memory attention to condition current frame's visual features + # with memories (and obj ptrs) from past frames + self.memory_attention = memory_attention + self.hidden_dim = memory_attention.d_model + + # Part 3: memory encoder for the previous frame's outputs + self.memory_encoder = memory_encoder + self.mem_dim = self.hidden_dim + if hasattr(self.memory_encoder, "out_proj") and hasattr( + self.memory_encoder.out_proj, "weight" + ): + # if there is compression of memories along channel dim + self.mem_dim = self.memory_encoder.out_proj.weight.shape[0] + self.num_maskmem = num_maskmem # Number of memories accessible + # Temporal encoding of the memories + self.maskmem_tpos_enc = torch.nn.Parameter( + torch.zeros(num_maskmem, 1, 1, self.mem_dim) + ) + trunc_normal_(self.maskmem_tpos_enc, std=0.02) + # a single token to indicate no memory embedding from previous frames + self.no_mem_embed = torch.nn.Parameter(torch.zeros(1, 1, self.hidden_dim)) + self.no_mem_pos_enc = torch.nn.Parameter(torch.zeros(1, 1, self.hidden_dim)) + trunc_normal_(self.no_mem_embed, std=0.02) + trunc_normal_(self.no_mem_pos_enc, std=0.02) + self.directly_add_no_mem_embed = directly_add_no_mem_embed + # Apply sigmoid to the output raw mask logits (to turn them from + # range (-inf, +inf) to range (0, 1)) before feeding them into the memory encoder + self.sigmoid_scale_for_mem_enc = sigmoid_scale_for_mem_enc + self.sigmoid_bias_for_mem_enc = sigmoid_bias_for_mem_enc + self.binarize_mask_from_pts_for_mem_enc = binarize_mask_from_pts_for_mem_enc + self.non_overlap_masks_for_mem_enc = non_overlap_masks_for_mem_enc + self.memory_temporal_stride_for_eval = memory_temporal_stride_for_eval + # On frames with mask input, whether to directly output the input mask without + # using a SAM prompt encoder + mask decoder + self.use_mask_input_as_output_without_sam = use_mask_input_as_output_without_sam + self.multimask_output_in_sam = multimask_output_in_sam + self.multimask_min_pt_num = multimask_min_pt_num + self.multimask_max_pt_num = multimask_max_pt_num + self.multimask_output_for_tracking = multimask_output_for_tracking + self.use_multimask_token_for_obj_ptr = use_multimask_token_for_obj_ptr + self.iou_prediction_use_sigmoid = iou_prediction_use_sigmoid + + # Part 4: SAM-style prompt encoder (for both mask and point inputs) + # and SAM-style mask decoder for the final mask output + self.image_size = image_size + self.backbone_stride = backbone_stride + self.sam_mask_decoder_extra_args = sam_mask_decoder_extra_args + self.pred_obj_scores = pred_obj_scores + self.pred_obj_scores_mlp = pred_obj_scores_mlp + self.fixed_no_obj_ptr = fixed_no_obj_ptr + self.soft_no_obj_ptr = soft_no_obj_ptr + if self.fixed_no_obj_ptr: + assert self.pred_obj_scores + assert self.use_obj_ptrs_in_encoder + if self.pred_obj_scores and self.use_obj_ptrs_in_encoder: + self.no_obj_ptr = torch.nn.Parameter(torch.zeros(1, self.hidden_dim)) + trunc_normal_(self.no_obj_ptr, std=0.02) + self.use_mlp_for_obj_ptr_proj = use_mlp_for_obj_ptr_proj + + self._build_sam_heads() + self.add_all_frames_to_correct_as_cond = add_all_frames_to_correct_as_cond + self.max_cond_frames_in_attn = max_cond_frames_in_attn + + # Model compilation + if compile_image_encoder: + # Compile the forward function (not the full module) to allow loading checkpoints. + print( + "Image encoder compilation is enabled. First forward pass will be slow." + ) + self.image_encoder.forward = torch.compile( + self.image_encoder.forward, + mode="max-autotune", + fullgraph=True, + dynamic=False, + ) + + @property + def device(self): + return next(self.parameters()).device + + def forward(self, *args, **kwargs): + raise NotImplementedError( + "Please use the corresponding methods in SAM2VideoPredictor for inference." + "See notebooks/video_predictor_example.ipynb for an example." + ) + + def _build_sam_heads(self): + """Build SAM-style prompt encoder and mask decoder.""" + self.sam_prompt_embed_dim = self.hidden_dim + self.sam_image_embedding_size = self.image_size // self.backbone_stride + + # build PromptEncoder and MaskDecoder from SAM + # (their hyperparameters like `mask_in_chans=16` are from SAM code) + self.sam_prompt_encoder = PromptEncoder( + embed_dim=self.sam_prompt_embed_dim, + image_embedding_size=( + self.sam_image_embedding_size, + self.sam_image_embedding_size, + ), + input_image_size=(self.image_size, self.image_size), + mask_in_chans=16, + ) + self.sam_mask_decoder = MaskDecoder( + num_multimask_outputs=3, + transformer=TwoWayTransformer( + depth=2, + embedding_dim=self.sam_prompt_embed_dim, + mlp_dim=2048, + num_heads=8, + ), + transformer_dim=self.sam_prompt_embed_dim, + iou_head_depth=3, + iou_head_hidden_dim=256, + use_high_res_features=self.use_high_res_features_in_sam, + iou_prediction_use_sigmoid=self.iou_prediction_use_sigmoid, + pred_obj_scores=self.pred_obj_scores, + pred_obj_scores_mlp=self.pred_obj_scores_mlp, + use_multimask_token_for_obj_ptr=self.use_multimask_token_for_obj_ptr, + **(self.sam_mask_decoder_extra_args or {}), + ) + if self.use_obj_ptrs_in_encoder: + # a linear projection on SAM output tokens to turn them into object pointers + self.obj_ptr_proj = torch.nn.Linear(self.hidden_dim, self.hidden_dim) + if self.use_mlp_for_obj_ptr_proj: + self.obj_ptr_proj = MLP( + self.hidden_dim, self.hidden_dim, self.hidden_dim, 3 + ) + else: + self.obj_ptr_proj = torch.nn.Identity() + if self.proj_tpos_enc_in_obj_ptrs: + # a linear projection on temporal positional encoding in object pointers to + # avoid potential interference with spatial positional encoding + self.obj_ptr_tpos_proj = torch.nn.Linear(self.hidden_dim, self.mem_dim) + else: + self.obj_ptr_tpos_proj = torch.nn.Identity() + + def _forward_sam_heads( + self, + backbone_features, + point_inputs=None, + mask_inputs=None, + text_inputs=None, + high_res_features=None, + multimask_output=False, + ): + """ + Forward SAM prompt encoders and mask heads. + + Inputs: + - backbone_features: image features of [B, C, H, W] shape + - point_inputs: a dictionary with "point_coords" and "point_labels", where + 1) "point_coords" has [B, P, 2] shape and float32 dtype and contains the + absolute pixel-unit coordinate in (x, y) format of the P input points + 2) "point_labels" has shape [B, P] and int32 dtype, where 1 means + positive clicks, 0 means negative clicks, and -1 means padding + - mask_inputs: a mask of [B, 1, H*16, W*16] shape, float or bool, with the + same spatial size as the image. + - high_res_features: either 1) None or 2) or a list of length 2 containing + two feature maps of [B, C, 4*H, 4*W] and [B, C, 2*H, 2*W] shapes respectively, + which will be used as high-resolution feature maps for SAM decoder. + - multimask_output: if it's True, we output 3 candidate masks and their 3 + corresponding IoU estimates, and if it's False, we output only 1 mask and + its corresponding IoU estimate. + + Outputs: + - low_res_multimasks: [B, M, H*4, W*4] shape (where M = 3 if + `multimask_output=True` and M = 1 if `multimask_output=False`), the SAM + output mask logits (before sigmoid) for the low-resolution masks, with 4x + the resolution (1/4 stride) of the input backbone_features. + - high_res_multimasks: [B, M, H*16, W*16] shape (where M = 3 + if `multimask_output=True` and M = 1 if `multimask_output=False`), + upsampled from the low-resolution masks, with shape size as the image + (stride is 1 pixel). + - ious, [B, M] shape, where (where M = 3 if `multimask_output=True` and M = 1 + if `multimask_output=False`), the estimated IoU of each output mask. + - low_res_masks: [B, 1, H*4, W*4] shape, the best mask in `low_res_multimasks`. + If `multimask_output=True`, it's the mask with the highest IoU estimate. + If `multimask_output=False`, it's the same as `low_res_multimasks`. + - high_res_masks: [B, 1, H*16, W*16] shape, the best mask in `high_res_multimasks`. + If `multimask_output=True`, it's the mask with the highest IoU estimate. + If `multimask_output=False`, it's the same as `high_res_multimasks`. + - obj_ptr: [B, C] shape, the object pointer vector for the output mask, extracted + based on the output token from the SAM mask decoder. + """ + B = backbone_features.size(0) + device = backbone_features.device + assert backbone_features.size(1) == self.sam_prompt_embed_dim + assert backbone_features.size(2) == self.sam_image_embedding_size + assert backbone_features.size(3) == self.sam_image_embedding_size + + # a) Handle point prompts + if point_inputs is not None: + sam_point_coords = point_inputs["point_coords"] + sam_point_labels = point_inputs["point_labels"] + assert sam_point_coords.size(0) == B and sam_point_labels.size(0) == B + else: + # If no points are provide, pad with an empty point (with label -1) + sam_point_coords = torch.zeros(B, 1, 2, device=device) + sam_point_labels = -torch.ones(B, 1, dtype=torch.int32, device=device) + + # b) Handle mask prompts + if mask_inputs is not None: + # If mask_inputs is provided, downsize it into low-res mask input if needed + # and feed it as a dense mask prompt into the SAM mask encoder + assert len(mask_inputs.shape) == 4 and mask_inputs.shape[:2] == (B, 1) + if mask_inputs.shape[-2:] != self.sam_prompt_encoder.mask_input_size: + sam_mask_prompt = F.interpolate( + mask_inputs.float(), + size=self.sam_prompt_encoder.mask_input_size, + align_corners=False, + mode="bilinear", + antialias=True, # use antialias for downsampling + ) + else: + sam_mask_prompt = mask_inputs + else: + # Otherwise, simply feed None (and SAM's prompt encoder will add + # a learned `no_mask_embed` to indicate no mask input in this case). + sam_mask_prompt = None + + sparse_embeddings, dense_embeddings = self.sam_prompt_encoder( + points=(sam_point_coords, sam_point_labels), + boxes=None, + masks=sam_mask_prompt, + text_embeds=text_inputs + ) + ( + low_res_multimasks, + ious, + sam_output_tokens, + object_score_logits, + ) = self.sam_mask_decoder( + image_embeddings=backbone_features, + image_pe=self.sam_prompt_encoder.get_dense_pe(), + sparse_prompt_embeddings=sparse_embeddings, + dense_prompt_embeddings=dense_embeddings, + multimask_output=multimask_output, + repeat_image=False, # the image is already batched + high_res_features=high_res_features, + ) + if self.pred_obj_scores: + is_obj_appearing = object_score_logits > 0 + + # Mask used for spatial memories is always a *hard* choice between obj and no obj, + # consistent with the actual mask prediction + low_res_multimasks = torch.where( + is_obj_appearing[:, None, None], + low_res_multimasks, + NO_OBJ_SCORE, + ) + + # convert masks from possibly bfloat16 (or float16) to float32 + # (older PyTorch versions before 2.1 don't support `interpolate` on bf16) + low_res_multimasks = low_res_multimasks.float() + high_res_multimasks = F.interpolate( + low_res_multimasks, + size=(self.image_size, self.image_size), + mode="bilinear", + align_corners=False, + ) + + sam_output_token = sam_output_tokens[:, 0] + if multimask_output: + # take the best mask prediction (with the highest IoU estimation) + best_iou_inds = torch.argmax(ious, dim=-1) + batch_inds = torch.arange(B, device=device) + low_res_masks = low_res_multimasks[batch_inds, best_iou_inds].unsqueeze(1) + high_res_masks = high_res_multimasks[batch_inds, best_iou_inds].unsqueeze(1) + if sam_output_tokens.size(1) > 1: + sam_output_token = sam_output_tokens[batch_inds, best_iou_inds] + else: + low_res_masks, high_res_masks = low_res_multimasks, high_res_multimasks + + # Extract object pointer from the SAM output token (with occlusion handling) + obj_ptr = self.obj_ptr_proj(sam_output_token) + if self.pred_obj_scores: + # Allow *soft* no obj ptr, unlike for masks + if self.soft_no_obj_ptr: + # Only hard possible with gt + assert not self.teacher_force_obj_scores_for_mem + lambda_is_obj_appearing = object_score_logits.sigmoid() + else: + lambda_is_obj_appearing = is_obj_appearing.float() + + if self.fixed_no_obj_ptr: + obj_ptr = lambda_is_obj_appearing * obj_ptr + obj_ptr = obj_ptr + (1 - lambda_is_obj_appearing) * self.no_obj_ptr + + return ( + low_res_multimasks, + high_res_multimasks, + ious, + low_res_masks, + high_res_masks, + obj_ptr, + object_score_logits, + ) + + def _use_mask_as_output(self, backbone_features, high_res_features, mask_inputs): + """ + Directly turn binary `mask_inputs` into a output mask logits without using SAM. + (same input and output shapes as in _forward_sam_heads above). + """ + # Use -10/+10 as logits for neg/pos pixels (very close to 0/1 in prob after sigmoid). + out_scale, out_bias = 20.0, -10.0 # sigmoid(-10.0)=4.5398e-05 + mask_inputs_float = mask_inputs.float() + high_res_masks = mask_inputs_float * out_scale + out_bias + low_res_masks = F.interpolate( + high_res_masks, + size=(high_res_masks.size(-2) // 4, high_res_masks.size(-1) // 4), + align_corners=False, + mode="bilinear", + antialias=True, # use antialias for downsampling + ) + # a dummy IoU prediction of all 1's under mask input + ious = mask_inputs.new_ones(mask_inputs.size(0), 1).float() + if not self.use_obj_ptrs_in_encoder: + # all zeros as a dummy object pointer (of shape [B, C]) + obj_ptr = torch.zeros( + mask_inputs.size(0), self.hidden_dim, device=mask_inputs.device + ) + else: + # produce an object pointer using the SAM decoder from the mask input + _, _, _, _, _, obj_ptr, _ = self._forward_sam_heads( + backbone_features=backbone_features, + mask_inputs=self.mask_downsample(mask_inputs_float), + high_res_features=high_res_features, + ) + # In this method, we are treating mask_input as output, e.g. using it directly to create spatial mem; + # Below, we follow the same design axiom to use mask_input to decide if obj appears or not instead of relying + # on the object_scores from the SAM decoder. + is_obj_appearing = torch.any(mask_inputs.flatten(1).float() > 0.0, dim=1) + is_obj_appearing = is_obj_appearing[..., None] + lambda_is_obj_appearing = is_obj_appearing.float() + object_score_logits = out_scale * lambda_is_obj_appearing + out_bias + if self.pred_obj_scores: + if self.fixed_no_obj_ptr: + obj_ptr = lambda_is_obj_appearing * obj_ptr + obj_ptr = obj_ptr + (1 - lambda_is_obj_appearing) * self.no_obj_ptr + + return ( + low_res_masks, + high_res_masks, + ious, + low_res_masks, + high_res_masks, + obj_ptr, + object_score_logits, + ) + + def forward_image(self, img_batch: torch.Tensor): + """Get the image feature on the input batch.""" + backbone_out = self.image_encoder(img_batch) + if self.use_high_res_features_in_sam: + # precompute projected level 0 and level 1 features in SAM decoder + # to avoid running it again on every SAM click + backbone_out["backbone_fpn"][0] = self.sam_mask_decoder.conv_s0( + backbone_out["backbone_fpn"][0] + ) + backbone_out["backbone_fpn"][1] = self.sam_mask_decoder.conv_s1( + backbone_out["backbone_fpn"][1] + ) + return backbone_out + + def _prepare_backbone_features(self, backbone_out): + """Prepare and flatten visual features.""" + backbone_out = backbone_out.copy() + assert len(backbone_out["backbone_fpn"]) == len(backbone_out["vision_pos_enc"]) + assert len(backbone_out["backbone_fpn"]) >= self.num_feature_levels + + feature_maps = backbone_out["backbone_fpn"][-self.num_feature_levels :] + vision_pos_embeds = backbone_out["vision_pos_enc"][-self.num_feature_levels :] + + feat_sizes = [(x.shape[-2], x.shape[-1]) for x in vision_pos_embeds] + # flatten NxCxHxW to HWxNxC + vision_feats = [x.flatten(2).permute(2, 0, 1) for x in feature_maps] + vision_pos_embeds = [x.flatten(2).permute(2, 0, 1) for x in vision_pos_embeds] + + return backbone_out, vision_feats, vision_pos_embeds, feat_sizes + + def _prepare_memory_conditioned_features( + self, + frame_idx, + is_init_cond_frame, + current_vision_feats, + current_vision_pos_embeds, + feat_sizes, + output_dict, + num_frames, + track_in_reverse=False, # tracking in reverse time order (for demo usage) + ): + """Fuse the current frame's visual feature map with previous memory.""" + B = current_vision_feats[-1].size(1) # batch size on this frame + C = self.hidden_dim + H, W = feat_sizes[-1] # top-level (lowest-resolution) feature size + device = current_vision_feats[-1].device + # The case of `self.num_maskmem == 0` below is primarily used for reproducing SAM on images. + # In this case, we skip the fusion with any memory. + if self.num_maskmem == 0: # Disable memory and skip fusion + pix_feat = current_vision_feats[-1].permute(1, 2, 0).view(B, C, H, W) + return pix_feat + + num_obj_ptr_tokens = 0 + # Step 1: condition the visual features of the current frame on previous memories + if not is_init_cond_frame: + # Retrieve the memories encoded with the maskmem backbone + to_cat_memory, to_cat_memory_pos_embed = [], [] + # Add conditioning frames's output first (all cond frames have t_pos=0 for + # when getting temporal positional embedding below) + assert len(output_dict["cond_frame_outputs"]) > 0 + # Select a maximum number of temporally closest cond frames for cross attention + cond_outputs = output_dict["cond_frame_outputs"] + selected_cond_outputs, unselected_cond_outputs = select_closest_cond_frames( + frame_idx, cond_outputs, self.max_cond_frames_in_attn + ) + t_pos_and_prevs = [(0, out) for out in selected_cond_outputs.values()] + # Add last (self.num_maskmem - 1) frames before current frame for non-conditioning memory + # the earliest one has t_pos=1 and the latest one has t_pos=self.num_maskmem-1 + # We also allow taking the memory frame non-consecutively (with r>1), in which case + # we take (self.num_maskmem - 2) frames among every r-th frames plus the last frame. + r = self.memory_temporal_stride_for_eval + for t_pos in range(1, self.num_maskmem): + t_rel = self.num_maskmem - t_pos # how many frames before current frame + if t_rel == 1: + # for t_rel == 1, we take the last frame (regardless of r) + if not track_in_reverse: + # the frame immediately before this frame (i.e. frame_idx - 1) + prev_frame_idx = frame_idx - t_rel + else: + # the frame immediately after this frame (i.e. frame_idx + 1) + prev_frame_idx = frame_idx + t_rel + else: + # for t_rel >= 2, we take the memory frame from every r-th frames + if not track_in_reverse: + # first find the nearest frame among every r-th frames before this frame + # for r=1, this would be (frame_idx - 2) + prev_frame_idx = ((frame_idx - 2) // r) * r + # then seek further among every r-th frames + prev_frame_idx = prev_frame_idx - (t_rel - 2) * r + else: + # first find the nearest frame among every r-th frames after this frame + # for r=1, this would be (frame_idx + 2) + prev_frame_idx = -(-(frame_idx + 2) // r) * r + # then seek further among every r-th frames + prev_frame_idx = prev_frame_idx + (t_rel - 2) * r + out = output_dict["non_cond_frame_outputs"].get(prev_frame_idx, None) + if out is None: + # If an unselected conditioning frame is among the last (self.num_maskmem - 1) + # frames, we still attend to it as if it's a non-conditioning frame. + out = unselected_cond_outputs.get(prev_frame_idx, None) + t_pos_and_prevs.append((t_pos, out)) + + for t_pos, prev in t_pos_and_prevs: + if prev is None: + continue # skip padding frames + # "maskmem_features" might have been offloaded to CPU in demo use cases, + # so we load it back to GPU (it's a no-op if it's already on GPU). + feats = prev["maskmem_features"].cuda(non_blocking=True) + to_cat_memory.append(feats.flatten(2).permute(2, 0, 1)) + # Spatial positional encoding (it might have been offloaded to CPU in eval) + maskmem_enc = prev["maskmem_pos_enc"][-1].cuda() + maskmem_enc = maskmem_enc.flatten(2).permute(2, 0, 1) + # Temporal positional encoding + maskmem_enc = ( + maskmem_enc + self.maskmem_tpos_enc[self.num_maskmem - t_pos - 1] + ) + to_cat_memory_pos_embed.append(maskmem_enc) + + # Construct the list of past object pointers + if self.use_obj_ptrs_in_encoder: + max_obj_ptrs_in_encoder = min(num_frames, self.max_obj_ptrs_in_encoder) + # First add those object pointers from selected conditioning frames + # (optionally, only include object pointers in the past during evaluation) + if not self.training and self.only_obj_ptrs_in_the_past_for_eval: + ptr_cond_outputs = { + t: out + for t, out in selected_cond_outputs.items() + if (t >= frame_idx if track_in_reverse else t <= frame_idx) + } + else: + ptr_cond_outputs = selected_cond_outputs + pos_and_ptrs = [ + # Temporal pos encoding contains how far away each pointer is from current frame + (abs(frame_idx - t), out["obj_ptr"]) + for t, out in ptr_cond_outputs.items() + ] + # Add up to (max_obj_ptrs_in_encoder - 1) non-conditioning frames before current frame + for t_diff in range(1, max_obj_ptrs_in_encoder): + t = frame_idx + t_diff if track_in_reverse else frame_idx - t_diff + if t < 0 or (num_frames is not None and t >= num_frames): + break + out = output_dict["non_cond_frame_outputs"].get( + t, unselected_cond_outputs.get(t, None) + ) + if out is not None: + pos_and_ptrs.append((t_diff, out["obj_ptr"])) + # If we have at least one object pointer, add them to the across attention + if len(pos_and_ptrs) > 0: + pos_list, ptrs_list = zip(*pos_and_ptrs) + # stack object pointers along dim=0 into [ptr_seq_len, B, C] shape + obj_ptrs = torch.stack(ptrs_list, dim=0) + # a temporal positional embedding based on how far each object pointer is from + # the current frame (sine embedding normalized by the max pointer num). + if self.add_tpos_enc_to_obj_ptrs: + t_diff_max = max_obj_ptrs_in_encoder - 1 + tpos_dim = C if self.proj_tpos_enc_in_obj_ptrs else self.mem_dim + obj_pos = torch.tensor(pos_list, device=device) + obj_pos = get_1d_sine_pe(obj_pos / t_diff_max, dim=tpos_dim) + obj_pos = self.obj_ptr_tpos_proj(obj_pos) + obj_pos = obj_pos.unsqueeze(1).expand(-1, B, self.mem_dim) + else: + obj_pos = obj_ptrs.new_zeros(len(pos_list), B, self.mem_dim) + if self.mem_dim < C: + # split a pointer into (C // self.mem_dim) tokens for self.mem_dim < C + obj_ptrs = obj_ptrs.reshape( + -1, B, C // self.mem_dim, self.mem_dim + ) + obj_ptrs = obj_ptrs.permute(0, 2, 1, 3).flatten(0, 1) + obj_pos = obj_pos.repeat_interleave(C // self.mem_dim, dim=0) + to_cat_memory.append(obj_ptrs) + to_cat_memory_pos_embed.append(obj_pos) + num_obj_ptr_tokens = obj_ptrs.shape[0] + else: + num_obj_ptr_tokens = 0 + else: + # for initial conditioning frames, encode them without using any previous memory + if self.directly_add_no_mem_embed: + # directly add no-mem embedding (instead of using the transformer encoder) + pix_feat_with_mem = current_vision_feats[-1] + self.no_mem_embed + pix_feat_with_mem = pix_feat_with_mem.permute(1, 2, 0).view(B, C, H, W) + return pix_feat_with_mem + + # Use a dummy token on the first frame (to avoid emtpy memory input to tranformer encoder) + to_cat_memory = [self.no_mem_embed.expand(1, B, self.mem_dim)] + to_cat_memory_pos_embed = [self.no_mem_pos_enc.expand(1, B, self.mem_dim)] + + # Step 2: Concatenate the memories and forward through the transformer encoder + memory = torch.cat(to_cat_memory, dim=0) + memory_pos_embed = torch.cat(to_cat_memory_pos_embed, dim=0) + + pix_feat_with_mem = self.memory_attention( + curr=current_vision_feats, + curr_pos=current_vision_pos_embeds, + memory=memory, + memory_pos=memory_pos_embed, + num_obj_ptr_tokens=num_obj_ptr_tokens, + ) + # reshape the output (HW)BC => BCHW + pix_feat_with_mem = pix_feat_with_mem.permute(1, 2, 0).view(B, C, H, W) + return pix_feat_with_mem + + def _encode_new_memory( + self, + current_vision_feats, + feat_sizes, + pred_masks_high_res, + is_mask_from_pts, + ): + """Encode the current image and its prediction into a memory feature.""" + B = current_vision_feats[-1].size(1) # batch size on this frame + C = self.hidden_dim + H, W = feat_sizes[-1] # top-level (lowest-resolution) feature size + # top-level feature, (HW)BC => BCHW + pix_feat = current_vision_feats[-1].permute(1, 2, 0).view(B, C, H, W) + if self.non_overlap_masks_for_mem_enc and not self.training: + # optionally, apply non-overlapping constraints to the masks (it's applied + # in the batch dimension and should only be used during eval, where all + # the objects come from the same video under batch size 1). + pred_masks_high_res = self._apply_non_overlapping_constraints( + pred_masks_high_res + ) + # scale the raw mask logits with a temperature before applying sigmoid + binarize = self.binarize_mask_from_pts_for_mem_enc and is_mask_from_pts + if binarize and not self.training: + mask_for_mem = (pred_masks_high_res > 0).float() + else: + # apply sigmoid on the raw mask logits to turn them into range (0, 1) + mask_for_mem = torch.sigmoid(pred_masks_high_res) + # apply scale and bias terms to the sigmoid probabilities + if self.sigmoid_scale_for_mem_enc != 1.0: + mask_for_mem = mask_for_mem * self.sigmoid_scale_for_mem_enc + if self.sigmoid_bias_for_mem_enc != 0.0: + mask_for_mem = mask_for_mem + self.sigmoid_bias_for_mem_enc + maskmem_out = self.memory_encoder( + pix_feat, mask_for_mem, skip_mask_sigmoid=True # sigmoid already applied + ) + maskmem_features = maskmem_out["vision_features"] + maskmem_pos_enc = maskmem_out["vision_pos_enc"] + + return maskmem_features, maskmem_pos_enc + + def track_step( + self, + frame_idx, + is_init_cond_frame, + current_vision_feats, + current_vision_pos_embeds, + feat_sizes, + point_inputs, + mask_inputs, + output_dict, + num_frames, + track_in_reverse=False, # tracking in reverse time order (for demo usage) + # Whether to run the memory encoder on the predicted masks. Sometimes we might want + # to skip the memory encoder with `run_mem_encoder=False`. For example, + # in demo we might call `track_step` multiple times for each user click, + # and only encode the memory when the user finalizes their clicks. And in ablation + # settings like SAM training on static images, we don't need the memory encoder. + run_mem_encoder=True, + # The previously predicted SAM mask logits (which can be fed together with new clicks in demo). + prev_sam_mask_logits=None, + text_inputs=None, + ): + current_out = {"point_inputs": point_inputs, "mask_inputs": mask_inputs} + # High-resolution feature maps for the SAM head, reshape (HW)BC => BCHW + if len(current_vision_feats) > 1: + high_res_features = [ + x.permute(1, 2, 0).view(x.size(1), x.size(2), *s) + for x, s in zip(current_vision_feats[:-1], feat_sizes[:-1]) + ] + else: + high_res_features = None + if mask_inputs is not None and self.use_mask_input_as_output_without_sam: + # When use_mask_input_as_output_without_sam=True, we directly output the mask input + # (see it as a GT mask) without using a SAM prompt encoder + mask decoder. + pix_feat = current_vision_feats[-1].permute(1, 2, 0) + pix_feat = pix_feat.view(-1, self.hidden_dim, *feat_sizes[-1]) + sam_outputs = self._use_mask_as_output( + pix_feat, high_res_features, mask_inputs + ) + else: + # fused the visual feature with previous memory features in the memory bank + pix_feat_with_mem = self._prepare_memory_conditioned_features( + frame_idx=frame_idx, + is_init_cond_frame=is_init_cond_frame, + current_vision_feats=current_vision_feats[-1:], + current_vision_pos_embeds=current_vision_pos_embeds[-1:], + feat_sizes=feat_sizes[-1:], + output_dict=output_dict, + num_frames=num_frames, + track_in_reverse=track_in_reverse, + ) + # apply SAM-style segmentation head + # here we might feed previously predicted low-res SAM mask logits into the SAM mask decoder, + # e.g. in demo where such logits come from earlier interaction instead of correction sampling + # (in this case, any `mask_inputs` shouldn't reach here as they are sent to _use_mask_as_output instead) + if prev_sam_mask_logits is not None: + assert point_inputs is not None and mask_inputs is None + mask_inputs = prev_sam_mask_logits + multimask_output = self._use_multimask(is_init_cond_frame, point_inputs) + sam_outputs = self._forward_sam_heads( + backbone_features=pix_feat_with_mem, + point_inputs=point_inputs, + mask_inputs=mask_inputs, + high_res_features=high_res_features, + multimask_output=multimask_output, + text_inputs=text_inputs + ) + ( + _, + _, + _, + low_res_masks, + high_res_masks, + obj_ptr, + _, + ) = sam_outputs + + current_out["pred_masks"] = low_res_masks + current_out["pred_masks_high_res"] = high_res_masks + current_out["obj_ptr"] = obj_ptr + + # Finally run the memory encoder on the predicted mask to encode + # it into a new memory feature (that can be used in future frames) + if run_mem_encoder and self.num_maskmem > 0: + high_res_masks_for_mem_enc = high_res_masks + maskmem_features, maskmem_pos_enc = self._encode_new_memory( + current_vision_feats=current_vision_feats, + feat_sizes=feat_sizes, + pred_masks_high_res=high_res_masks_for_mem_enc, + is_mask_from_pts=(point_inputs is not None), + ) + current_out["maskmem_features"] = maskmem_features + current_out["maskmem_pos_enc"] = maskmem_pos_enc + else: + current_out["maskmem_features"] = None + current_out["maskmem_pos_enc"] = None + + return current_out + + def _use_multimask(self, is_init_cond_frame, point_inputs): + """Whether to use multimask output in the SAM head.""" + num_pts = 0 if point_inputs is None else point_inputs["point_labels"].size(1) + multimask_output = ( + self.multimask_output_in_sam + and (is_init_cond_frame or self.multimask_output_for_tracking) + and (self.multimask_min_pt_num <= num_pts <= self.multimask_max_pt_num) + ) + return multimask_output + + def _apply_non_overlapping_constraints(self, pred_masks): + """ + Apply non-overlapping constraints to the object scores in pred_masks. Here we + keep only the highest scoring object at each spatial location in pred_masks. + """ + batch_size = pred_masks.size(0) + if batch_size == 1: + return pred_masks + + device = pred_masks.device + # "max_obj_inds": object index of the object with the highest score at each location + max_obj_inds = torch.argmax(pred_masks, dim=0, keepdim=True) + # "batch_obj_inds": object index of each object slice (along dim 0) in `pred_masks` + batch_obj_inds = torch.arange(batch_size, device=device)[:, None, None, None] + keep = max_obj_inds == batch_obj_inds + # suppress overlapping regions' scores below -10.0 so that the foreground regions + # don't overlap (here sigmoid(-10.0)=4.5398e-05) + pred_masks = torch.where(keep, pred_masks, torch.clamp(pred_masks, max=-10.0)) + return pred_masks diff --git a/py/evf_sam/model/segment_anything_2/sam2/modeling/sam2_utils.py b/py/evf_sam/model/segment_anything_2/sam2/modeling/sam2_utils.py new file mode 100644 index 0000000..6d97059 --- /dev/null +++ b/py/evf_sam/model/segment_anything_2/sam2/modeling/sam2_utils.py @@ -0,0 +1,149 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + + +import copy + +import torch +import torch.nn as nn +import torch.nn.functional as F + + +def select_closest_cond_frames(frame_idx, cond_frame_outputs, max_cond_frame_num): + """ + Select up to `max_cond_frame_num` conditioning frames from `cond_frame_outputs` + that are temporally closest to the current frame at `frame_idx`. Here, we take + - a) the closest conditioning frame before `frame_idx` (if any); + - b) the closest conditioning frame after `frame_idx` (if any); + - c) any other temporally closest conditioning frames until reaching a total + of `max_cond_frame_num` conditioning frames. + + Outputs: + - selected_outputs: selected items (keys & values) from `cond_frame_outputs`. + - unselected_outputs: items (keys & values) not selected in `cond_frame_outputs`. + """ + if max_cond_frame_num == -1 or len(cond_frame_outputs) <= max_cond_frame_num: + selected_outputs = cond_frame_outputs + unselected_outputs = {} + else: + assert max_cond_frame_num >= 2, "we should allow using 2+ conditioning frames" + selected_outputs = {} + + # the closest conditioning frame before `frame_idx` (if any) + idx_before = max((t for t in cond_frame_outputs if t < frame_idx), default=None) + if idx_before is not None: + selected_outputs[idx_before] = cond_frame_outputs[idx_before] + + # the closest conditioning frame after `frame_idx` (if any) + idx_after = min((t for t in cond_frame_outputs if t >= frame_idx), default=None) + if idx_after is not None: + selected_outputs[idx_after] = cond_frame_outputs[idx_after] + + # add other temporally closest conditioning frames until reaching a total + # of `max_cond_frame_num` conditioning frames. + num_remain = max_cond_frame_num - len(selected_outputs) + inds_remain = sorted( + (t for t in cond_frame_outputs if t not in selected_outputs), + key=lambda x: abs(x - frame_idx), + )[:num_remain] + selected_outputs.update((t, cond_frame_outputs[t]) for t in inds_remain) + unselected_outputs = { + t: v for t, v in cond_frame_outputs.items() if t not in selected_outputs + } + + return selected_outputs, unselected_outputs + + +def get_1d_sine_pe(pos_inds, dim, temperature=10000): + """ + Get 1D sine positional embedding as in the original Transformer paper. + """ + pe_dim = dim // 2 + dim_t = torch.arange(pe_dim, dtype=torch.float32, device=pos_inds.device) + dim_t = temperature ** (2 * (dim_t // 2) / pe_dim) + + pos_embed = pos_inds.unsqueeze(-1) / dim_t + pos_embed = torch.cat([pos_embed.sin(), pos_embed.cos()], dim=-1) + return pos_embed + + +def get_activation_fn(activation): + """Return an activation function given a string""" + if activation == "relu": + return F.relu + if activation == "gelu": + return F.gelu + if activation == "glu": + return F.glu + raise RuntimeError(f"activation should be relu/gelu, not {activation}.") + + +def get_clones(module, N): + return nn.ModuleList([copy.deepcopy(module) for i in range(N)]) + + +class DropPath(nn.Module): + # adapted from https://github.com/huggingface/pytorch-image-models/blob/main/timm/layers/drop.py + def __init__(self, drop_prob=0.0, scale_by_keep=True): + super(DropPath, self).__init__() + self.drop_prob = drop_prob + self.scale_by_keep = scale_by_keep + + def forward(self, x): + if self.drop_prob == 0.0 or not self.training: + return x + keep_prob = 1 - self.drop_prob + shape = (x.shape[0],) + (1,) * (x.ndim - 1) + random_tensor = x.new_empty(shape).bernoulli_(keep_prob) + if keep_prob > 0.0 and self.scale_by_keep: + random_tensor.div_(keep_prob) + return x * random_tensor + + +# Lightly adapted from +# https://github.com/facebookresearch/MaskFormer/blob/main/mask_former/modeling/transformer/transformer_predictor.py # noqa +class MLP(nn.Module): + def __init__( + self, + input_dim: int, + hidden_dim: int, + output_dim: int, + num_layers: int, + activation: nn.Module = nn.ReLU, + sigmoid_output: bool = False, + ) -> None: + super().__init__() + self.num_layers = num_layers + h = [hidden_dim] * (num_layers - 1) + self.layers = nn.ModuleList( + nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim]) + ) + self.sigmoid_output = sigmoid_output + self.act = activation() + + def forward(self, x): + for i, layer in enumerate(self.layers): + x = self.act(layer(x)) if i < self.num_layers - 1 else layer(x) + if self.sigmoid_output: + x = F.sigmoid(x) + return x + + +# From https://github.com/facebookresearch/detectron2/blob/main/detectron2/layers/batch_norm.py # noqa +# Itself from https://github.com/facebookresearch/ConvNeXt/blob/d1fa8f6fef0a165b27399986cc2bdacc92777e40/models/convnext.py#L119 # noqa +class LayerNorm2d(nn.Module): + def __init__(self, num_channels: int, eps: float = 1e-6) -> None: + super().__init__() + self.weight = nn.Parameter(torch.ones(num_channels)) + self.bias = nn.Parameter(torch.zeros(num_channels)) + self.eps = eps + + def forward(self, x: torch.Tensor) -> torch.Tensor: + u = x.mean(1, keepdim=True) + s = (x - u).pow(2).mean(1, keepdim=True) + x = (x - u) / torch.sqrt(s + self.eps) + x = self.weight[:, None, None] * x + self.bias[:, None, None] + return x diff --git a/py/evf_sam/model/segment_anything_2/sam2/sam2_image_predictor.py b/py/evf_sam/model/segment_anything_2/sam2/sam2_image_predictor.py new file mode 100644 index 0000000..5b7d762 --- /dev/null +++ b/py/evf_sam/model/segment_anything_2/sam2/sam2_image_predictor.py @@ -0,0 +1,446 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import logging + +from typing import List, Optional, Tuple, Union + +import numpy as np +import torch +from PIL.Image import Image + +from model.segment_anything_2.sam2.modeling.sam2_base import SAM2Base + +from model.segment_anything_2.sam2.utils.transforms import SAM2Transforms + + +class SAM2ImagePredictor: + def __init__( + self, + sam_model: SAM2Base, + mask_threshold=0.0, + max_hole_area=0.0, + max_sprinkle_area=0.0, + ) -> None: + """ + Uses SAM-2 to calculate the image embedding for an image, and then + allow repeated, efficient mask prediction given prompts. + + Arguments: + sam_model (Sam-2): The model to use for mask prediction. + mask_threshold (float): The threshold to use when converting mask logits + to binary masks. Masks are thresholded at 0 by default. + fill_hole_area (int): If fill_hole_area > 0, we fill small holes in up to + the maximum area of fill_hole_area in low_res_masks. + """ + super().__init__() + self.model = sam_model + self._transforms = SAM2Transforms( + resolution=self.model.image_size, + mask_threshold=mask_threshold, + max_hole_area=max_hole_area, + max_sprinkle_area=max_sprinkle_area, + ) + + # Predictor state + self._is_image_set = False + self._features = None + self._orig_hw = None + # Whether the predictor is set for single image or a batch of images + self._is_batch = False + + # Predictor config + self.mask_threshold = mask_threshold + + # Spatial dim for backbone feature maps + self._bb_feat_sizes = [ + (256, 256), + (128, 128), + (64, 64), + ] + + @torch.no_grad() + def set_image( + self, + image: Union[np.ndarray, Image], + ) -> None: + """ + Calculates the image embeddings for the provided image, allowing + masks to be predicted with the 'predict' method. + + Arguments: + image (np.ndarray or PIL Image): The input image to embed in RGB format. The image should be in HWC format if np.ndarray, or WHC format if PIL Image + with pixel values in [0, 255]. + image_format (str): The color format of the image, in ['RGB', 'BGR']. + """ + self.reset_predictor() + # Transform the image to the form expected by the model + if isinstance(image, np.ndarray): + logging.info("For numpy array image, we assume (HxWxC) format") + self._orig_hw = [image.shape[:2]] + elif isinstance(image, Image): + w, h = image.size + self._orig_hw = [(h, w)] + else: + raise NotImplementedError("Image format not supported") + + input_image = self._transforms(image) + input_image = input_image[None, ...].to(self.device) + + assert ( + len(input_image.shape) == 4 and input_image.shape[1] == 3 + ), f"input_image must be of size 1x3xHxW, got {input_image.shape}" + logging.info("Computing image embeddings for the provided image...") + backbone_out = self.model.forward_image(input_image) + _, vision_feats, _, _ = self.model._prepare_backbone_features(backbone_out) + # Add no_mem_embed, which is added to the lowest rest feat. map during training on videos + if self.model.directly_add_no_mem_embed: + vision_feats[-1] = vision_feats[-1] + self.model.no_mem_embed + + feats = [ + feat.permute(1, 2, 0).view(1, -1, *feat_size) + for feat, feat_size in zip(vision_feats[::-1], self._bb_feat_sizes[::-1]) + ][::-1] + self._features = {"image_embed": feats[-1], "high_res_feats": feats[:-1]} + self._is_image_set = True + logging.info("Image embeddings computed.") + + @torch.no_grad() + def set_image_batch( + self, + image_list: List[Union[np.ndarray]], + ) -> None: + """ + Calculates the image embeddings for the provided image batch, allowing + masks to be predicted with the 'predict_batch' method. + + Arguments: + image_list (List[np.ndarray]): The input images to embed in RGB format. The image should be in HWC format if np.ndarray + with pixel values in [0, 255]. + """ + self.reset_predictor() + assert isinstance(image_list, list) + self._orig_hw = [] + for image in image_list: + assert isinstance( + image, np.ndarray + ), "Images are expected to be an np.ndarray in RGB format, and of shape HWC" + self._orig_hw.append(image.shape[:2]) + # Transform the image to the form expected by the model + img_batch = self._transforms.forward_batch(image_list) + img_batch = img_batch.to(self.device) + batch_size = img_batch.shape[0] + assert ( + len(img_batch.shape) == 4 and img_batch.shape[1] == 3 + ), f"img_batch must be of size Bx3xHxW, got {img_batch.shape}" + logging.info("Computing image embeddings for the provided images...") + backbone_out = self.model.forward_image(img_batch) + _, vision_feats, _, _ = self.model._prepare_backbone_features(backbone_out) + # Add no_mem_embed, which is added to the lowest rest feat. map during training on videos + if self.model.directly_add_no_mem_embed: + vision_feats[-1] = vision_feats[-1] + self.model.no_mem_embed + + feats = [ + feat.permute(1, 2, 0).view(batch_size, -1, *feat_size) + for feat, feat_size in zip(vision_feats[::-1], self._bb_feat_sizes[::-1]) + ][::-1] + self._features = {"image_embed": feats[-1], "high_res_feats": feats[:-1]} + self._is_image_set = True + self._is_batch = True + logging.info("Image embeddings computed.") + + def predict_batch( + self, + point_coords_batch: List[np.ndarray] = None, + point_labels_batch: List[np.ndarray] = None, + box_batch: List[np.ndarray] = None, + mask_input_batch: List[np.ndarray] = None, + multimask_output: bool = True, + return_logits: bool = False, + normalize_coords=True, + ) -> Tuple[List[np.ndarray], List[np.ndarray], List[np.ndarray]]: + """This function is very similar to predict(...), however it is used for batched mode, when the model is expected to generate predictions on multiple images. + It returns a tupele of lists of masks, ious, and low_res_masks_logits. + """ + assert self._is_batch, "This function should only be used when in batched mode" + if not self._is_image_set: + raise RuntimeError( + "An image must be set with .set_image_batch(...) before mask prediction." + ) + num_images = len(self._features["image_embed"]) + all_masks = [] + all_ious = [] + all_low_res_masks = [] + for img_idx in range(num_images): + # Transform input prompts + point_coords = ( + point_coords_batch[img_idx] if point_coords_batch is not None else None + ) + point_labels = ( + point_labels_batch[img_idx] if point_labels_batch is not None else None + ) + box = box_batch[img_idx] if box_batch is not None else None + mask_input = ( + mask_input_batch[img_idx] if mask_input_batch is not None else None + ) + mask_input, unnorm_coords, labels, unnorm_box = self._prep_prompts( + point_coords, + point_labels, + box, + mask_input, + normalize_coords, + img_idx=img_idx, + ) + masks, iou_predictions, low_res_masks = self._predict( + unnorm_coords, + labels, + unnorm_box, + mask_input, + multimask_output, + return_logits=return_logits, + img_idx=img_idx, + ) + masks_np = masks.squeeze(0).float().detach().cpu().numpy() + iou_predictions_np = ( + iou_predictions.squeeze(0).float().detach().cpu().numpy() + ) + low_res_masks_np = low_res_masks.squeeze(0).float().detach().cpu().numpy() + all_masks.append(masks_np) + all_ious.append(iou_predictions_np) + all_low_res_masks.append(low_res_masks_np) + + return all_masks, all_ious, all_low_res_masks + + def predict( + self, + point_coords: Optional[np.ndarray] = None, + point_labels: Optional[np.ndarray] = None, + box: Optional[np.ndarray] = None, + mask_input: Optional[np.ndarray] = None, + multimask_output: bool = True, + return_logits: bool = False, + normalize_coords=True, + ) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: + """ + Predict masks for the given input prompts, using the currently set image. + + Arguments: + point_coords (np.ndarray or None): A Nx2 array of point prompts to the + model. Each point is in (X,Y) in pixels. + point_labels (np.ndarray or None): A length N array of labels for the + point prompts. 1 indicates a foreground point and 0 indicates a + background point. + box (np.ndarray or None): A length 4 array given a box prompt to the + model, in XYXY format. + mask_input (np.ndarray): A low resolution mask input to the model, typically + coming from a previous prediction iteration. Has form 1xHxW, where + for SAM, H=W=256. + multimask_output (bool): If true, the model will return three masks. + For ambiguous input prompts (such as a single click), this will often + produce better masks than a single prediction. If only a single + mask is needed, the model's predicted quality score can be used + to select the best mask. For non-ambiguous prompts, such as multiple + input prompts, multimask_output=False can give better results. + return_logits (bool): If true, returns un-thresholded masks logits + instead of a binary mask. + normalize_coords (bool): If true, the point coordinates will be normalized to the range [0,1] and point_coords is expected to be wrt. image dimensions. + + Returns: + (np.ndarray): The output masks in CxHxW format, where C is the + number of masks, and (H, W) is the original image size. + (np.ndarray): An array of length C containing the model's + predictions for the quality of each mask. + (np.ndarray): An array of shape CxHxW, where C is the number + of masks and H=W=256. These low resolution logits can be passed to + a subsequent iteration as mask input. + """ + if not self._is_image_set: + raise RuntimeError( + "An image must be set with .set_image(...) before mask prediction." + ) + + # Transform input prompts + + mask_input, unnorm_coords, labels, unnorm_box = self._prep_prompts( + point_coords, point_labels, box, mask_input, normalize_coords + ) + + masks, iou_predictions, low_res_masks = self._predict( + unnorm_coords, + labels, + unnorm_box, + mask_input, + multimask_output, + return_logits=return_logits, + ) + + masks_np = masks.squeeze(0).float().detach().cpu().numpy() + iou_predictions_np = iou_predictions.squeeze(0).float().detach().cpu().numpy() + low_res_masks_np = low_res_masks.squeeze(0).float().detach().cpu().numpy() + return masks_np, iou_predictions_np, low_res_masks_np + + def _prep_prompts( + self, point_coords, point_labels, box, mask_logits, normalize_coords, img_idx=-1 + ): + + unnorm_coords, labels, unnorm_box, mask_input = None, None, None, None + if point_coords is not None: + assert ( + point_labels is not None + ), "point_labels must be supplied if point_coords is supplied." + point_coords = torch.as_tensor( + point_coords, dtype=torch.float, device=self.device + ) + unnorm_coords = self._transforms.transform_coords( + point_coords, normalize=normalize_coords, orig_hw=self._orig_hw[img_idx] + ) + labels = torch.as_tensor(point_labels, dtype=torch.int, device=self.device) + if len(unnorm_coords.shape) == 2: + unnorm_coords, labels = unnorm_coords[None, ...], labels[None, ...] + if box is not None: + box = torch.as_tensor(box, dtype=torch.float, device=self.device) + unnorm_box = self._transforms.transform_boxes( + box, normalize=normalize_coords, orig_hw=self._orig_hw[img_idx] + ) # Bx2x2 + if mask_logits is not None: + mask_input = torch.as_tensor( + mask_logits, dtype=torch.float, device=self.device + ) + if len(mask_input.shape) == 3: + mask_input = mask_input[None, :, :, :] + return mask_input, unnorm_coords, labels, unnorm_box + + @torch.no_grad() + def _predict( + self, + point_coords: Optional[torch.Tensor], + point_labels: Optional[torch.Tensor], + boxes: Optional[torch.Tensor] = None, + mask_input: Optional[torch.Tensor] = None, + multimask_output: bool = True, + return_logits: bool = False, + img_idx: int = -1, + ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """ + Predict masks for the given input prompts, using the currently set image. + Input prompts are batched torch tensors and are expected to already be + transformed to the input frame using SAM2Transforms. + + Arguments: + point_coords (torch.Tensor or None): A BxNx2 array of point prompts to the + model. Each point is in (X,Y) in pixels. + point_labels (torch.Tensor or None): A BxN array of labels for the + point prompts. 1 indicates a foreground point and 0 indicates a + background point. + boxes (np.ndarray or None): A Bx4 array given a box prompt to the + model, in XYXY format. + mask_input (np.ndarray): A low resolution mask input to the model, typically + coming from a previous prediction iteration. Has form Bx1xHxW, where + for SAM, H=W=256. Masks returned by a previous iteration of the + predict method do not need further transformation. + multimask_output (bool): If true, the model will return three masks. + For ambiguous input prompts (such as a single click), this will often + produce better masks than a single prediction. If only a single + mask is needed, the model's predicted quality score can be used + to select the best mask. For non-ambiguous prompts, such as multiple + input prompts, multimask_output=False can give better results. + return_logits (bool): If true, returns un-thresholded masks logits + instead of a binary mask. + + Returns: + (torch.Tensor): The output masks in BxCxHxW format, where C is the + number of masks, and (H, W) is the original image size. + (torch.Tensor): An array of shape BxC containing the model's + predictions for the quality of each mask. + (torch.Tensor): An array of shape BxCxHxW, where C is the number + of masks and H=W=256. These low res logits can be passed to + a subsequent iteration as mask input. + """ + if not self._is_image_set: + raise RuntimeError( + "An image must be set with .set_image(...) before mask prediction." + ) + + if point_coords is not None: + concat_points = (point_coords, point_labels) + else: + concat_points = None + + # Embed prompts + if boxes is not None: + box_coords = boxes.reshape(-1, 2, 2) + box_labels = torch.tensor([[2, 3]], dtype=torch.int, device=boxes.device) + box_labels = box_labels.repeat(boxes.size(0), 1) + # we merge "boxes" and "points" into a single "concat_points" input (where + # boxes are added at the beginning) to sam_prompt_encoder + if concat_points is not None: + concat_coords = torch.cat([box_coords, concat_points[0]], dim=1) + concat_labels = torch.cat([box_labels, concat_points[1]], dim=1) + concat_points = (concat_coords, concat_labels) + else: + concat_points = (box_coords, box_labels) + + sparse_embeddings, dense_embeddings = self.model.sam_prompt_encoder( + points=concat_points, + boxes=None, + masks=mask_input, + ) + + # Predict masks + batched_mode = ( + concat_points is not None and concat_points[0].shape[0] > 1 + ) # multi object prediction + high_res_features = [ + feat_level[img_idx].unsqueeze(0) + for feat_level in self._features["high_res_feats"] + ] + low_res_masks, iou_predictions, _, _ = self.model.sam_mask_decoder( + image_embeddings=self._features["image_embed"][img_idx].unsqueeze(0), + image_pe=self.model.sam_prompt_encoder.get_dense_pe(), + sparse_prompt_embeddings=sparse_embeddings, + dense_prompt_embeddings=dense_embeddings, + multimask_output=multimask_output, + repeat_image=batched_mode, + high_res_features=high_res_features, + ) + + # Upscale the masks to the original image resolution + masks = self._transforms.postprocess_masks( + low_res_masks, self._orig_hw[img_idx] + ) + low_res_masks = torch.clamp(low_res_masks, -32.0, 32.0) + if not return_logits: + masks = masks > self.mask_threshold + + return masks, iou_predictions, low_res_masks + + def get_image_embedding(self) -> torch.Tensor: + """ + Returns the image embeddings for the currently set image, with + shape 1xCxHxW, where C is the embedding dimension and (H,W) are + the embedding spatial dimension of SAM (typically C=256, H=W=64). + """ + if not self._is_image_set: + raise RuntimeError( + "An image must be set with .set_image(...) to generate an embedding." + ) + assert ( + self._features is not None + ), "Features must exist if an image has been set." + return self._features["image_embed"] + + @property + def device(self) -> torch.device: + return self.model.device + + def reset_predictor(self) -> None: + """ + Resets the image embeddings and other state variables. + """ + self._is_image_set = False + self._features = None + self._orig_hw = None + self._is_batch = False diff --git a/py/evf_sam/model/segment_anything_2/sam2/sam2_video_predictor.py b/py/evf_sam/model/segment_anything_2/sam2/sam2_video_predictor.py new file mode 100644 index 0000000..be925cb --- /dev/null +++ b/py/evf_sam/model/segment_anything_2/sam2/sam2_video_predictor.py @@ -0,0 +1,984 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +from collections import OrderedDict + +import torch + +from tqdm import tqdm + +from model.segment_anything_2.sam2.modeling.sam2_base import NO_OBJ_SCORE, SAM2Base +from model.segment_anything_2.sam2.utils.misc import concat_points, fill_holes_in_mask_scores, load_video_frames + + +class SAM2VideoPredictor(SAM2Base): + """The predictor class to handle user interactions and manage inference states.""" + + def __init__( + self, + fill_hole_area=0, + # whether to apply non-overlapping constraints on the output object masks + non_overlap_masks=False, + # whether to clear non-conditioning memory of the surrounding frames (which may contain outdated information) after adding correction clicks; + # note that this would only apply to *single-object tracking* unless `clear_non_cond_mem_for_multi_obj` is also set to True) + clear_non_cond_mem_around_input=False, + # whether to also clear non-conditioning memory of the surrounding frames (only effective when `clear_non_cond_mem_around_input` is True). + clear_non_cond_mem_for_multi_obj=False, + **kwargs, + ): + super().__init__(**kwargs) + self.fill_hole_area = fill_hole_area + self.non_overlap_masks = non_overlap_masks + self.clear_non_cond_mem_around_input = clear_non_cond_mem_around_input + self.clear_non_cond_mem_for_multi_obj = clear_non_cond_mem_for_multi_obj + + @torch.inference_mode() + def init_state( + self, + video_path, + offload_video_to_cpu=False, + offload_state_to_cpu=False, + async_loading_frames=False, + ): + """Initialize a inference state.""" + images, video_height, video_width = load_video_frames( + video_path=video_path, + image_size=self.image_size, + offload_video_to_cpu=offload_video_to_cpu, + async_loading_frames=async_loading_frames, + ) + inference_state = {} + inference_state["images"] = images + inference_state["num_frames"] = len(images) + # whether to offload the video frames to CPU memory + # turning on this option saves the GPU memory with only a very small overhead + inference_state["offload_video_to_cpu"] = offload_video_to_cpu + # whether to offload the inference state to CPU memory + # turning on this option saves the GPU memory at the cost of a lower tracking fps + # (e.g. in a test case of 768x768 model, fps dropped from 27 to 24 when tracking one object + # and from 24 to 21 when tracking two objects) + inference_state["offload_state_to_cpu"] = offload_state_to_cpu + # the original video height and width, used for resizing final output scores + inference_state["video_height"] = video_height + inference_state["video_width"] = video_width + inference_state["device"] = torch.device("cuda") + if offload_state_to_cpu: + inference_state["storage_device"] = torch.device("cpu") + else: + inference_state["storage_device"] = torch.device("cuda") + # inputs on each frame + inference_state["point_inputs_per_obj"] = {} + inference_state["mask_inputs_per_obj"] = {} + # visual features on a small number of recently visited frames for quick interactions + inference_state["cached_features"] = {} + # values that don't change across frames (so we only need to hold one copy of them) + inference_state["constants"] = {} + # mapping between client-side object id and model-side object index + inference_state["obj_id_to_idx"] = OrderedDict() + inference_state["obj_idx_to_id"] = OrderedDict() + inference_state["obj_ids"] = [] + # A storage to hold the model's tracking results and states on each frame + inference_state["output_dict"] = { + "cond_frame_outputs": {}, # dict containing {frame_idx: } + "non_cond_frame_outputs": {}, # dict containing {frame_idx: } + } + # Slice (view) of each object tracking results, sharing the same memory with "output_dict" + inference_state["output_dict_per_obj"] = {} + # A temporary storage to hold new outputs when user interact with a frame + # to add clicks or mask (it's merged into "output_dict" before propagation starts) + inference_state["temp_output_dict_per_obj"] = {} + # Frames that already holds consolidated outputs from click or mask inputs + # (we directly use their consolidated outputs during tracking) + inference_state["consolidated_frame_inds"] = { + "cond_frame_outputs": set(), # set containing frame indices + "non_cond_frame_outputs": set(), # set containing frame indices + } + # metadata for each tracking frame (e.g. which direction it's tracked) + inference_state["tracking_has_started"] = False + inference_state["frames_already_tracked"] = {} + # Warm up the visual backbone and cache the image feature on frame 0 + self._get_image_feature(inference_state, frame_idx=0, batch_size=1) + return inference_state + + def _obj_id_to_idx(self, inference_state, obj_id): + """Map client-side object id to model-side object index.""" + obj_idx = inference_state["obj_id_to_idx"].get(obj_id, None) + if obj_idx is not None: + return obj_idx + + # This is a new object id not sent to the server before. We only allow adding + # new objects *before* the tracking starts. + allow_new_object = not inference_state["tracking_has_started"] + if allow_new_object: + # get the next object slot + obj_idx = len(inference_state["obj_id_to_idx"]) + inference_state["obj_id_to_idx"][obj_id] = obj_idx + inference_state["obj_idx_to_id"][obj_idx] = obj_id + inference_state["obj_ids"] = list(inference_state["obj_id_to_idx"]) + # set up input and output structures for this object + inference_state["point_inputs_per_obj"][obj_idx] = {} + inference_state["mask_inputs_per_obj"][obj_idx] = {} + inference_state["output_dict_per_obj"][obj_idx] = { + "cond_frame_outputs": {}, # dict containing {frame_idx: } + "non_cond_frame_outputs": {}, # dict containing {frame_idx: } + } + inference_state["temp_output_dict_per_obj"][obj_idx] = { + "cond_frame_outputs": {}, # dict containing {frame_idx: } + "non_cond_frame_outputs": {}, # dict containing {frame_idx: } + } + return obj_idx + else: + raise RuntimeError( + f"Cannot add new object id {obj_id} after tracking starts. " + f"All existing object ids: {inference_state['obj_ids']}. " + f"Please call 'reset_state' to restart from scratch." + ) + + def _obj_idx_to_id(self, inference_state, obj_idx): + """Map model-side object index to client-side object id.""" + return inference_state["obj_idx_to_id"][obj_idx] + + def _get_obj_num(self, inference_state): + """Get the total number of unique object ids received so far in this session.""" + return len(inference_state["obj_idx_to_id"]) + + @torch.inference_mode() + def add_new_points( + self, + inference_state, + frame_idx, + obj_id, + points, + labels, + clear_old_points=True, + normalize_coords=True, + ): + """Add new points to a frame.""" + obj_idx = self._obj_id_to_idx(inference_state, obj_id) + point_inputs_per_frame = inference_state["point_inputs_per_obj"][obj_idx] + mask_inputs_per_frame = inference_state["mask_inputs_per_obj"][obj_idx] + + if not isinstance(points, torch.Tensor): + points = torch.tensor(points, dtype=torch.float32) + if not isinstance(labels, torch.Tensor): + labels = torch.tensor(labels, dtype=torch.int32) + if points.dim() == 2: + points = points.unsqueeze(0) # add batch dimension + if labels.dim() == 1: + labels = labels.unsqueeze(0) # add batch dimension + if normalize_coords: + video_H = inference_state["video_height"] + video_W = inference_state["video_width"] + points = points / torch.tensor([video_W, video_H]).to(points.device) + # scale the (normalized) coordinates by the model's internal image size + points = points * self.image_size + points = points.to(inference_state["device"]) + labels = labels.to(inference_state["device"]) + + if not clear_old_points: + point_inputs = point_inputs_per_frame.get(frame_idx, None) + else: + point_inputs = None + point_inputs = concat_points(point_inputs, points, labels) + + point_inputs_per_frame[frame_idx] = point_inputs + mask_inputs_per_frame.pop(frame_idx, None) + # If this frame hasn't been tracked before, we treat it as an initial conditioning + # frame, meaning that the inputs points are to generate segments on this frame without + # using any memory from other frames, like in SAM. Otherwise (if it has been tracked), + # the input points will be used to correct the already tracked masks. + is_init_cond_frame = frame_idx not in inference_state["frames_already_tracked"] + # whether to track in reverse time order + if is_init_cond_frame: + reverse = False + else: + reverse = inference_state["frames_already_tracked"][frame_idx]["reverse"] + obj_output_dict = inference_state["output_dict_per_obj"][obj_idx] + obj_temp_output_dict = inference_state["temp_output_dict_per_obj"][obj_idx] + # Add a frame to conditioning output if it's an initial conditioning frame or + # if the model sees all frames receiving clicks/mask as conditioning frames. + is_cond = is_init_cond_frame or self.add_all_frames_to_correct_as_cond + storage_key = "cond_frame_outputs" if is_cond else "non_cond_frame_outputs" + + # Get any previously predicted mask logits on this object and feed it along with + # the new clicks into the SAM mask decoder. + prev_sam_mask_logits = None + # lookup temporary output dict first, which contains the most recent output + # (if not found, then lookup conditioning and non-conditioning frame output) + prev_out = obj_temp_output_dict[storage_key].get(frame_idx) + if prev_out is None: + prev_out = obj_output_dict["cond_frame_outputs"].get(frame_idx) + if prev_out is None: + prev_out = obj_output_dict["non_cond_frame_outputs"].get(frame_idx) + + if prev_out is not None and prev_out["pred_masks"] is not None: + prev_sam_mask_logits = prev_out["pred_masks"].cuda(non_blocking=True) + # Clamp the scale of prev_sam_mask_logits to avoid rare numerical issues. + prev_sam_mask_logits = torch.clamp(prev_sam_mask_logits, -32.0, 32.0) + current_out, _ = self._run_single_frame_inference( + inference_state=inference_state, + output_dict=obj_output_dict, # run on the slice of a single object + frame_idx=frame_idx, + batch_size=1, # run on the slice of a single object + is_init_cond_frame=is_init_cond_frame, + point_inputs=point_inputs, + mask_inputs=None, + reverse=reverse, + # Skip the memory encoder when adding clicks or mask. We execute the memory encoder + # at the beginning of `propagate_in_video` (after user finalize their clicks). This + # allows us to enforce non-overlapping constraints on all objects before encoding + # them into memory. + run_mem_encoder=False, + prev_sam_mask_logits=prev_sam_mask_logits, + ) + # Add the output to the output dict (to be used as future memory) + obj_temp_output_dict[storage_key][frame_idx] = current_out + + # Resize the output mask to the original video resolution + obj_ids = inference_state["obj_ids"] + consolidated_out = self._consolidate_temp_output_across_obj( + inference_state, + frame_idx, + is_cond=is_cond, + run_mem_encoder=False, + consolidate_at_video_res=True, + ) + _, video_res_masks = self._get_orig_video_res_output( + inference_state, consolidated_out["pred_masks_video_res"] + ) + return frame_idx, obj_ids, video_res_masks + + @torch.inference_mode() + def add_new_mask( + self, + inference_state, + frame_idx, + obj_id, + mask, + ): + """Add new mask to a frame.""" + obj_idx = self._obj_id_to_idx(inference_state, obj_id) + point_inputs_per_frame = inference_state["point_inputs_per_obj"][obj_idx] + mask_inputs_per_frame = inference_state["mask_inputs_per_obj"][obj_idx] + + if not isinstance(mask, torch.Tensor): + mask = torch.tensor(mask, dtype=torch.bool) + assert mask.dim() == 2 + mask_H, mask_W = mask.shape + mask_inputs_orig = mask[None, None] # add batch and channel dimension + mask_inputs_orig = mask_inputs_orig.float().to(inference_state["device"]) + + # resize the mask if it doesn't match the model's image size + if mask_H != self.image_size or mask_W != self.image_size: + mask_inputs = torch.nn.functional.interpolate( + mask_inputs_orig, + size=(self.image_size, self.image_size), + align_corners=False, + mode="bilinear", + antialias=True, # use antialias for downsampling + ) + mask_inputs = (mask_inputs >= 0.5).float() + else: + mask_inputs = mask_inputs_orig + + mask_inputs_per_frame[frame_idx] = mask_inputs + point_inputs_per_frame.pop(frame_idx, None) + # If this frame hasn't been tracked before, we treat it as an initial conditioning + # frame, meaning that the inputs points are to generate segments on this frame without + # using any memory from other frames, like in SAM. Otherwise (if it has been tracked), + # the input points will be used to correct the already tracked masks. + is_init_cond_frame = frame_idx not in inference_state["frames_already_tracked"] + # whether to track in reverse time order + if is_init_cond_frame: + reverse = False + else: + reverse = inference_state["frames_already_tracked"][frame_idx]["reverse"] + obj_output_dict = inference_state["output_dict_per_obj"][obj_idx] + obj_temp_output_dict = inference_state["temp_output_dict_per_obj"][obj_idx] + # Add a frame to conditioning output if it's an initial conditioning frame or + # if the model sees all frames receiving clicks/mask as conditioning frames. + is_cond = is_init_cond_frame or self.add_all_frames_to_correct_as_cond + storage_key = "cond_frame_outputs" if is_cond else "non_cond_frame_outputs" + + current_out, _ = self._run_single_frame_inference( + inference_state=inference_state, + output_dict=obj_output_dict, # run on the slice of a single object + frame_idx=frame_idx, + batch_size=1, # run on the slice of a single object + is_init_cond_frame=is_init_cond_frame, + point_inputs=None, + mask_inputs=mask_inputs, + reverse=reverse, + # Skip the memory encoder when adding clicks or mask. We execute the memory encoder + # at the beginning of `propagate_in_video` (after user finalize their clicks). This + # allows us to enforce non-overlapping constraints on all objects before encoding + # them into memory. + run_mem_encoder=False, + ) + # Add the output to the output dict (to be used as future memory) + obj_temp_output_dict[storage_key][frame_idx] = current_out + + # Resize the output mask to the original video resolution + obj_ids = inference_state["obj_ids"] + consolidated_out = self._consolidate_temp_output_across_obj( + inference_state, + frame_idx, + is_cond=is_cond, + run_mem_encoder=False, + consolidate_at_video_res=True, + ) + _, video_res_masks = self._get_orig_video_res_output( + inference_state, consolidated_out["pred_masks_video_res"] + ) + return frame_idx, obj_ids, video_res_masks + + + @torch.inference_mode() + def add_new_text( + self, + inference_state, + frame_idx, + obj_id, + text, + clear_old_points=True, + normalize_coords=True, + ): + """Add new text to a frame.""" + obj_idx = self._obj_id_to_idx(inference_state, obj_id) + point_inputs_per_frame = inference_state["point_inputs_per_obj"][obj_idx] + mask_inputs_per_frame = inference_state["mask_inputs_per_obj"][obj_idx] + + mask_inputs_per_frame.pop(frame_idx, None) + # If this frame hasn't been tracked before, we treat it as an initial conditioning + # frame, meaning that the inputs points are to generate segments on this frame without + # using any memory from other frames, like in SAM. Otherwise (if it has been tracked), + # the input points will be used to correct the already tracked masks. + is_init_cond_frame = frame_idx not in inference_state["frames_already_tracked"] + # whether to track in reverse time order + if is_init_cond_frame: + reverse = False + else: + reverse = inference_state["frames_already_tracked"][frame_idx]["reverse"] + obj_output_dict = inference_state["output_dict_per_obj"][obj_idx] + obj_temp_output_dict = inference_state["temp_output_dict_per_obj"][obj_idx] + # Add a frame to conditioning output if it's an initial conditioning frame or + # if the model sees all frames receiving clicks/mask as conditioning frames. + is_cond = is_init_cond_frame or self.add_all_frames_to_correct_as_cond + storage_key = "cond_frame_outputs" if is_cond else "non_cond_frame_outputs" + + # Get any previously predicted mask logits on this object and feed it along with + # the new clicks into the SAM mask decoder. + prev_sam_mask_logits = None + # lookup temporary output dict first, which contains the most recent output + # (if not found, then lookup conditioning and non-conditioning frame output) + prev_out = obj_temp_output_dict[storage_key].get(frame_idx) + if prev_out is None: + prev_out = obj_output_dict["cond_frame_outputs"].get(frame_idx) + if prev_out is None: + prev_out = obj_output_dict["non_cond_frame_outputs"].get(frame_idx) + + if prev_out is not None and prev_out["pred_masks"] is not None: + prev_sam_mask_logits = prev_out["pred_masks"].cuda(non_blocking=True) + # Clamp the scale of prev_sam_mask_logits to avoid rare numerical issues. + prev_sam_mask_logits = torch.clamp(prev_sam_mask_logits, -32.0, 32.0) + current_out, _ = self._run_single_frame_inference( + inference_state=inference_state, + output_dict=obj_output_dict, # run on the slice of a single object + frame_idx=frame_idx, + batch_size=1, # run on the slice of a single object + is_init_cond_frame=is_init_cond_frame, + point_inputs=None, + mask_inputs=None, + reverse=reverse, + # Skip the memory encoder when adding clicks or mask. We execute the memory encoder + # at the beginning of `propagate_in_video` (after user finalize their clicks). This + # allows us to enforce non-overlapping constraints on all objects before encoding + # them into memory. + run_mem_encoder=False, + prev_sam_mask_logits=prev_sam_mask_logits, + text_inputs=text + ) + # Add the output to the output dict (to be used as future memory) + obj_temp_output_dict[storage_key][frame_idx] = current_out + + # Resize the output mask to the original video resolution + obj_ids = inference_state["obj_ids"] + consolidated_out = self._consolidate_temp_output_across_obj( + inference_state, + frame_idx, + is_cond=is_cond, + run_mem_encoder=False, + consolidate_at_video_res=True, + ) + _, video_res_masks = self._get_orig_video_res_output( + inference_state, consolidated_out["pred_masks_video_res"] + ) + return frame_idx, obj_ids, video_res_masks + + + def _get_orig_video_res_output(self, inference_state, any_res_masks): + """ + Resize the object scores to the original video resolution (video_res_masks) + and apply non-overlapping constraints for final output. + """ + device = inference_state["device"] + video_H = inference_state["video_height"] + video_W = inference_state["video_width"] + any_res_masks = any_res_masks.to(device, non_blocking=True) + if any_res_masks.shape[-2:] == (video_H, video_W): + video_res_masks = any_res_masks + else: + video_res_masks = torch.nn.functional.interpolate( + any_res_masks, + size=(video_H, video_W), + mode="bilinear", + align_corners=False, + ) + if self.non_overlap_masks: + video_res_masks = self._apply_non_overlapping_constraints(video_res_masks) + return any_res_masks, video_res_masks + + def _consolidate_temp_output_across_obj( + self, + inference_state, + frame_idx, + is_cond, + run_mem_encoder, + consolidate_at_video_res=False, + ): + """ + Consolidate the per-object temporary outputs in `temp_output_dict_per_obj` on + a frame into a single output for all objects, including + 1) fill any missing objects either from `output_dict_per_obj` (if they exist in + `output_dict_per_obj` for this frame) or leave them as placeholder values + (if they don't exist in `output_dict_per_obj` for this frame); + 2) if specified, rerun memory encoder after apply non-overlapping constraints + on the object scores. + """ + batch_size = self._get_obj_num(inference_state) + storage_key = "cond_frame_outputs" if is_cond else "non_cond_frame_outputs" + # Optionally, we allow consolidating the temporary outputs at the original + # video resolution (to provide a better editing experience for mask prompts). + if consolidate_at_video_res: + assert not run_mem_encoder, "memory encoder cannot run at video resolution" + consolidated_H = inference_state["video_height"] + consolidated_W = inference_state["video_width"] + consolidated_mask_key = "pred_masks_video_res" + else: + consolidated_H = consolidated_W = self.image_size // 4 + consolidated_mask_key = "pred_masks" + + # Initialize `consolidated_out`. Its "maskmem_features" and "maskmem_pos_enc" + # will be added when rerunning the memory encoder after applying non-overlapping + # constraints to object scores. Its "pred_masks" are prefilled with a large + # negative value (NO_OBJ_SCORE) to represent missing objects. + consolidated_out = { + "maskmem_features": None, + "maskmem_pos_enc": None, + consolidated_mask_key: torch.full( + size=(batch_size, 1, consolidated_H, consolidated_W), + fill_value=NO_OBJ_SCORE, + dtype=torch.float32, + device=inference_state["storage_device"], + ), + "obj_ptr": torch.full( + size=(batch_size, self.hidden_dim), + fill_value=NO_OBJ_SCORE, + dtype=torch.float32, + device=inference_state["device"], + ), + } + empty_mask_ptr = None + for obj_idx in range(batch_size): + obj_temp_output_dict = inference_state["temp_output_dict_per_obj"][obj_idx] + obj_output_dict = inference_state["output_dict_per_obj"][obj_idx] + out = obj_temp_output_dict[storage_key].get(frame_idx, None) + # If the object doesn't appear in "temp_output_dict_per_obj" on this frame, + # we fall back and look up its previous output in "output_dict_per_obj". + # We look up both "cond_frame_outputs" and "non_cond_frame_outputs" in + # "output_dict_per_obj" to find a previous output for this object. + if out is None: + out = obj_output_dict["cond_frame_outputs"].get(frame_idx, None) + if out is None: + out = obj_output_dict["non_cond_frame_outputs"].get(frame_idx, None) + # If the object doesn't appear in "output_dict_per_obj" either, we skip it + # and leave its mask scores to the default scores (i.e. the NO_OBJ_SCORE + # placeholder above) and set its object pointer to be a dummy pointer. + if out is None: + # Fill in dummy object pointers for those objects without any inputs or + # tracking outcomes on this frame (only do it under `run_mem_encoder=True`, + # i.e. when we need to build the memory for tracking). + if run_mem_encoder: + if empty_mask_ptr is None: + empty_mask_ptr = self._get_empty_mask_ptr( + inference_state, frame_idx + ) + # fill object pointer with a dummy pointer (based on an empty mask) + consolidated_out["obj_ptr"][obj_idx : obj_idx + 1] = empty_mask_ptr + continue + # Add the temporary object output mask to consolidated output mask + obj_mask = out["pred_masks"] + consolidated_pred_masks = consolidated_out[consolidated_mask_key] + if obj_mask.shape[-2:] == consolidated_pred_masks.shape[-2:]: + consolidated_pred_masks[obj_idx : obj_idx + 1] = obj_mask + else: + # Resize first if temporary object mask has a different resolution + resized_obj_mask = torch.nn.functional.interpolate( + obj_mask, + size=consolidated_pred_masks.shape[-2:], + mode="bilinear", + align_corners=False, + ) + consolidated_pred_masks[obj_idx : obj_idx + 1] = resized_obj_mask + consolidated_out["obj_ptr"][obj_idx : obj_idx + 1] = out["obj_ptr"] + + # Optionally, apply non-overlapping constraints on the consolidated scores + # and rerun the memory encoder + if run_mem_encoder: + device = inference_state["device"] + high_res_masks = torch.nn.functional.interpolate( + consolidated_out["pred_masks"].to(device, non_blocking=True), + size=(self.image_size, self.image_size), + mode="bilinear", + align_corners=False, + ) + if self.non_overlap_masks_for_mem_enc: + high_res_masks = self._apply_non_overlapping_constraints(high_res_masks) + maskmem_features, maskmem_pos_enc = self._run_memory_encoder( + inference_state=inference_state, + frame_idx=frame_idx, + batch_size=batch_size, + high_res_masks=high_res_masks, + is_mask_from_pts=True, # these frames are what the user interacted with + ) + consolidated_out["maskmem_features"] = maskmem_features + consolidated_out["maskmem_pos_enc"] = maskmem_pos_enc + + return consolidated_out + + def _get_empty_mask_ptr(self, inference_state, frame_idx): + """Get a dummy object pointer based on an empty mask on the current frame.""" + # A dummy (empty) mask with a single object + batch_size = 1 + mask_inputs = torch.zeros( + (batch_size, 1, self.image_size, self.image_size), + dtype=torch.float32, + device=inference_state["device"], + ) + + # Retrieve correct image features + ( + _, + _, + current_vision_feats, + current_vision_pos_embeds, + feat_sizes, + ) = self._get_image_feature(inference_state, frame_idx, batch_size) + + # Feed the empty mask and image feature above to get a dummy object pointer + current_out = self.track_step( + frame_idx=frame_idx, + is_init_cond_frame=True, + current_vision_feats=current_vision_feats, + current_vision_pos_embeds=current_vision_pos_embeds, + feat_sizes=feat_sizes, + point_inputs=None, + mask_inputs=mask_inputs, + output_dict={}, + num_frames=inference_state["num_frames"], + track_in_reverse=False, + run_mem_encoder=False, + prev_sam_mask_logits=None, + ) + return current_out["obj_ptr"] + + @torch.inference_mode() + def propagate_in_video_preflight(self, inference_state): + """Prepare inference_state and consolidate temporary outputs before tracking.""" + # Tracking has started and we don't allow adding new objects until session is reset. + inference_state["tracking_has_started"] = True + batch_size = self._get_obj_num(inference_state) + + # Consolidate per-object temporary outputs in "temp_output_dict_per_obj" and + # add them into "output_dict". + temp_output_dict_per_obj = inference_state["temp_output_dict_per_obj"] + output_dict = inference_state["output_dict"] + # "consolidated_frame_inds" contains indices of those frames where consolidated + # temporary outputs have been added (either in this call or any previous calls + # to `propagate_in_video_preflight`). + consolidated_frame_inds = inference_state["consolidated_frame_inds"] + for is_cond in [False, True]: + # Separately consolidate conditioning and non-conditioning temp outptus + storage_key = "cond_frame_outputs" if is_cond else "non_cond_frame_outputs" + # Find all the frames that contain temporary outputs for any objects + # (these should be the frames that have just received clicks for mask inputs + # via `add_new_points` or `add_new_mask`) + temp_frame_inds = set() + for obj_temp_output_dict in temp_output_dict_per_obj.values(): + temp_frame_inds.update(obj_temp_output_dict[storage_key].keys()) + consolidated_frame_inds[storage_key].update(temp_frame_inds) + # consolidate the temprary output across all objects on this frame + for frame_idx in temp_frame_inds: + consolidated_out = self._consolidate_temp_output_across_obj( + inference_state, frame_idx, is_cond=is_cond, run_mem_encoder=True + ) + # merge them into "output_dict" and also create per-object slices + output_dict[storage_key][frame_idx] = consolidated_out + self._add_output_per_object( + inference_state, frame_idx, consolidated_out, storage_key + ) + clear_non_cond_mem = self.clear_non_cond_mem_around_input and ( + self.clear_non_cond_mem_for_multi_obj or batch_size <= 1 + ) + if clear_non_cond_mem: + # clear non-conditioning memory of the surrounding frames + self._clear_non_cond_mem_around_input(inference_state, frame_idx) + + # clear temporary outputs in `temp_output_dict_per_obj` + for obj_temp_output_dict in temp_output_dict_per_obj.values(): + obj_temp_output_dict[storage_key].clear() + + # edge case: if an output is added to "cond_frame_outputs", we remove any prior + # output on the same frame in "non_cond_frame_outputs" + for frame_idx in output_dict["cond_frame_outputs"]: + output_dict["non_cond_frame_outputs"].pop(frame_idx, None) + for obj_output_dict in inference_state["output_dict_per_obj"].values(): + for frame_idx in obj_output_dict["cond_frame_outputs"]: + obj_output_dict["non_cond_frame_outputs"].pop(frame_idx, None) + for frame_idx in consolidated_frame_inds["cond_frame_outputs"]: + assert frame_idx in output_dict["cond_frame_outputs"] + consolidated_frame_inds["non_cond_frame_outputs"].discard(frame_idx) + + # Make sure that the frame indices in "consolidated_frame_inds" are exactly those frames + # with either points or mask inputs (which should be true under a correct workflow). + # all_consolidated_frame_inds = ( + # consolidated_frame_inds["cond_frame_outputs"] + # | consolidated_frame_inds["non_cond_frame_outputs"] + # ) + # input_frames_inds = set() + # for point_inputs_per_frame in inference_state["point_inputs_per_obj"].values(): + # input_frames_inds.update(point_inputs_per_frame.keys()) + # for mask_inputs_per_frame in inference_state["mask_inputs_per_obj"].values(): + # input_frames_inds.update(mask_inputs_per_frame.keys()) + # assert all_consolidated_frame_inds == input_frames_inds + + @torch.inference_mode() + def propagate_in_video( + self, + inference_state, + start_frame_idx=None, + max_frame_num_to_track=None, + reverse=False, + ): + """Propagate the input points across frames to track in the entire video.""" + self.propagate_in_video_preflight(inference_state) + + output_dict = inference_state["output_dict"] + consolidated_frame_inds = inference_state["consolidated_frame_inds"] + obj_ids = inference_state["obj_ids"] + num_frames = inference_state["num_frames"] + batch_size = self._get_obj_num(inference_state) + if len(output_dict["cond_frame_outputs"]) == 0: + raise RuntimeError("No points are provided; please add points first") + clear_non_cond_mem = self.clear_non_cond_mem_around_input and ( + self.clear_non_cond_mem_for_multi_obj or batch_size <= 1 + ) + + # set start index, end index, and processing order + if start_frame_idx is None: + # default: start from the earliest frame with input points + start_frame_idx = min(output_dict["cond_frame_outputs"]) + if max_frame_num_to_track is None: + # default: track all the frames in the video + max_frame_num_to_track = num_frames + if reverse: + end_frame_idx = max(start_frame_idx - max_frame_num_to_track, 0) + if start_frame_idx > 0: + processing_order = range(start_frame_idx, end_frame_idx - 1, -1) + else: + processing_order = [] # skip reverse tracking if starting from frame 0 + else: + end_frame_idx = min( + start_frame_idx + max_frame_num_to_track, num_frames - 1 + ) + processing_order = range(start_frame_idx, end_frame_idx + 1) + + for frame_idx in tqdm(processing_order, desc="propagate in video"): + # We skip those frames already in consolidated outputs (these are frames + # that received input clicks or mask). Note that we cannot directly run + # batched forward on them via `_run_single_frame_inference` because the + # number of clicks on each object might be different. + if frame_idx in consolidated_frame_inds["cond_frame_outputs"]: + storage_key = "cond_frame_outputs" + current_out = output_dict[storage_key][frame_idx] + pred_masks = current_out["pred_masks"] + if clear_non_cond_mem: + # clear non-conditioning memory of the surrounding frames + self._clear_non_cond_mem_around_input(inference_state, frame_idx) + elif frame_idx in consolidated_frame_inds["non_cond_frame_outputs"]: + storage_key = "non_cond_frame_outputs" + current_out = output_dict[storage_key][frame_idx] + pred_masks = current_out["pred_masks"] + else: + storage_key = "non_cond_frame_outputs" + current_out, pred_masks = self._run_single_frame_inference( + inference_state=inference_state, + output_dict=output_dict, + frame_idx=frame_idx, + batch_size=batch_size, + is_init_cond_frame=False, + point_inputs=None, + mask_inputs=None, + reverse=reverse, + run_mem_encoder=True, + ) + output_dict[storage_key][frame_idx] = current_out + # Create slices of per-object outputs for subsequent interaction with each + # individual object after tracking. + self._add_output_per_object( + inference_state, frame_idx, current_out, storage_key + ) + inference_state["frames_already_tracked"][frame_idx] = {"reverse": reverse} + + # Resize the output mask to the original video resolution (we directly use + # the mask scores on GPU for output to avoid any CPU conversion in between) + _, video_res_masks = self._get_orig_video_res_output( + inference_state, pred_masks + ) + yield frame_idx, obj_ids, video_res_masks + + def _add_output_per_object( + self, inference_state, frame_idx, current_out, storage_key + ): + """ + Split a multi-object output into per-object output slices and add them into + `output_dict_per_obj`. The resulting slices share the same tensor storage. + """ + maskmem_features = current_out["maskmem_features"] + assert maskmem_features is None or isinstance(maskmem_features, torch.Tensor) + + maskmem_pos_enc = current_out["maskmem_pos_enc"] + assert maskmem_pos_enc is None or isinstance(maskmem_pos_enc, list) + + output_dict_per_obj = inference_state["output_dict_per_obj"] + for obj_idx, obj_output_dict in output_dict_per_obj.items(): + obj_slice = slice(obj_idx, obj_idx + 1) + obj_out = { + "maskmem_features": None, + "maskmem_pos_enc": None, + "pred_masks": current_out["pred_masks"][obj_slice], + "obj_ptr": current_out["obj_ptr"][obj_slice], + } + if maskmem_features is not None: + obj_out["maskmem_features"] = maskmem_features[obj_slice] + if maskmem_pos_enc is not None: + obj_out["maskmem_pos_enc"] = [x[obj_slice] for x in maskmem_pos_enc] + obj_output_dict[storage_key][frame_idx] = obj_out + + @torch.inference_mode() + def reset_state(self, inference_state): + """Remove all input points or mask in all frames throughout the video.""" + self._reset_tracking_results(inference_state) + # Remove all object ids + inference_state["obj_id_to_idx"].clear() + inference_state["obj_idx_to_id"].clear() + inference_state["obj_ids"].clear() + inference_state["point_inputs_per_obj"].clear() + inference_state["mask_inputs_per_obj"].clear() + inference_state["output_dict_per_obj"].clear() + inference_state["temp_output_dict_per_obj"].clear() + + def _reset_tracking_results(self, inference_state): + """Reset all tracking inputs and results across the videos.""" + for v in inference_state["point_inputs_per_obj"].values(): + v.clear() + for v in inference_state["mask_inputs_per_obj"].values(): + v.clear() + for v in inference_state["output_dict_per_obj"].values(): + v["cond_frame_outputs"].clear() + v["non_cond_frame_outputs"].clear() + for v in inference_state["temp_output_dict_per_obj"].values(): + v["cond_frame_outputs"].clear() + v["non_cond_frame_outputs"].clear() + inference_state["output_dict"]["cond_frame_outputs"].clear() + inference_state["output_dict"]["non_cond_frame_outputs"].clear() + inference_state["consolidated_frame_inds"]["cond_frame_outputs"].clear() + inference_state["consolidated_frame_inds"]["non_cond_frame_outputs"].clear() + inference_state["tracking_has_started"] = False + inference_state["frames_already_tracked"].clear() + + def _get_image_feature(self, inference_state, frame_idx, batch_size): + """Compute the image features on a given frame.""" + # Look up in the cache first + image, backbone_out = inference_state["cached_features"].get( + frame_idx, (None, None) + ) + if backbone_out is None: + # Cache miss -- we will run inference on a single image + image = inference_state["images"][frame_idx].cuda().float().unsqueeze(0) + backbone_out = self.forward_image(image) + # Cache the most recent frame's feature (for repeated interactions with + # a frame; we can use an LRU cache for more frames in the future). + inference_state["cached_features"] = {frame_idx: (image, backbone_out)} + + # expand the features to have the same dimension as the number of objects + expanded_image = image.expand(batch_size, -1, -1, -1) + expanded_backbone_out = { + "backbone_fpn": backbone_out["backbone_fpn"].copy(), + "vision_pos_enc": backbone_out["vision_pos_enc"].copy(), + } + for i, feat in enumerate(expanded_backbone_out["backbone_fpn"]): + expanded_backbone_out["backbone_fpn"][i] = feat.expand( + batch_size, -1, -1, -1 + ) + for i, pos in enumerate(expanded_backbone_out["vision_pos_enc"]): + pos = pos.expand(batch_size, -1, -1, -1) + expanded_backbone_out["vision_pos_enc"][i] = pos + + features = self._prepare_backbone_features(expanded_backbone_out) + features = (expanded_image,) + features + return features + + def _run_single_frame_inference( + self, + inference_state, + output_dict, + frame_idx, + batch_size, + is_init_cond_frame, + point_inputs, + mask_inputs, + reverse, + run_mem_encoder, + prev_sam_mask_logits=None, + text_inputs=None + ): + """Run tracking on a single frame based on current inputs and previous memory.""" + # Retrieve correct image features + ( + _, + _, + current_vision_feats, + current_vision_pos_embeds, + feat_sizes, + ) = self._get_image_feature(inference_state, frame_idx, batch_size) + + # point and mask should not appear as input simultaneously on the same frame + assert point_inputs is None or mask_inputs is None + current_out = self.track_step( + frame_idx=frame_idx, + is_init_cond_frame=is_init_cond_frame, + current_vision_feats=current_vision_feats, + current_vision_pos_embeds=current_vision_pos_embeds, + feat_sizes=feat_sizes, + point_inputs=point_inputs, + mask_inputs=mask_inputs, + output_dict=output_dict, + num_frames=inference_state["num_frames"], + track_in_reverse=reverse, + run_mem_encoder=run_mem_encoder, + prev_sam_mask_logits=prev_sam_mask_logits, + text_inputs=text_inputs + ) + + # optionally offload the output to CPU memory to save GPU space + storage_device = inference_state["storage_device"] + maskmem_features = current_out["maskmem_features"] + if maskmem_features is not None: + maskmem_features = maskmem_features.to(torch.bfloat16) + maskmem_features = maskmem_features.to(storage_device, non_blocking=True) + pred_masks_gpu = current_out["pred_masks"] + # potentially fill holes in the predicted masks + if self.fill_hole_area > 0: + pred_masks_gpu = fill_holes_in_mask_scores( + pred_masks_gpu, self.fill_hole_area + ) + pred_masks = pred_masks_gpu.to(storage_device, non_blocking=True) + # "maskmem_pos_enc" is the same across frames, so we only need to store one copy of it + maskmem_pos_enc = self._get_maskmem_pos_enc(inference_state, current_out) + # object pointer is a small tensor, so we always keep it on GPU memory for fast access + obj_ptr = current_out["obj_ptr"] + # make a compact version of this frame's output to reduce the state size + compact_current_out = { + "maskmem_features": maskmem_features, + "maskmem_pos_enc": maskmem_pos_enc, + "pred_masks": pred_masks, + "obj_ptr": obj_ptr, + } + return compact_current_out, pred_masks_gpu + + def _run_memory_encoder( + self, inference_state, frame_idx, batch_size, high_res_masks, is_mask_from_pts + ): + """ + Run the memory encoder on `high_res_masks`. This is usually after applying + non-overlapping constraints to object scores. Since their scores changed, their + memory also need to be computed again with the memory encoder. + """ + # Retrieve correct image features + _, _, current_vision_feats, _, feat_sizes = self._get_image_feature( + inference_state, frame_idx, batch_size + ) + maskmem_features, maskmem_pos_enc = self._encode_new_memory( + current_vision_feats=current_vision_feats, + feat_sizes=feat_sizes, + pred_masks_high_res=high_res_masks, + is_mask_from_pts=is_mask_from_pts, + ) + + # optionally offload the output to CPU memory to save GPU space + storage_device = inference_state["storage_device"] + maskmem_features = maskmem_features.to(torch.bfloat16) + maskmem_features = maskmem_features.to(storage_device, non_blocking=True) + # "maskmem_pos_enc" is the same across frames, so we only need to store one copy of it + maskmem_pos_enc = self._get_maskmem_pos_enc( + inference_state, {"maskmem_pos_enc": maskmem_pos_enc} + ) + return maskmem_features, maskmem_pos_enc + + def _get_maskmem_pos_enc(self, inference_state, current_out): + """ + `maskmem_pos_enc` is the same across frames and objects, so we cache it as + a constant in the inference session to reduce session storage size. + """ + model_constants = inference_state["constants"] + # "out_maskmem_pos_enc" should be either a list of tensors or None + out_maskmem_pos_enc = current_out["maskmem_pos_enc"] + if out_maskmem_pos_enc is not None: + if "maskmem_pos_enc" not in model_constants: + assert isinstance(out_maskmem_pos_enc, list) + # only take the slice for one object, since it's same across objects + maskmem_pos_enc = [x[0:1].clone() for x in out_maskmem_pos_enc] + model_constants["maskmem_pos_enc"] = maskmem_pos_enc + else: + maskmem_pos_enc = model_constants["maskmem_pos_enc"] + # expand the cached maskmem_pos_enc to the actual batch size + batch_size = out_maskmem_pos_enc[0].size(0) + expanded_maskmem_pos_enc = [ + x.expand(batch_size, -1, -1, -1) for x in maskmem_pos_enc + ] + else: + expanded_maskmem_pos_enc = None + return expanded_maskmem_pos_enc + + def _clear_non_cond_mem_around_input(self, inference_state, frame_idx): + """ + Remove the non-conditioning memory around the input frame. When users provide + correction clicks, the surrounding frames' non-conditioning memories can still + contain outdated object appearance information and could confuse the model. + + This method clears those non-conditioning memories surrounding the interacted + frame to avoid giving the model both old and new information about the object. + """ + r = self.memory_temporal_stride_for_eval + frame_idx_begin = frame_idx - r * self.num_maskmem + frame_idx_end = frame_idx + r * self.num_maskmem + output_dict = inference_state["output_dict"] + non_cond_frame_outputs = output_dict["non_cond_frame_outputs"] + for t in range(frame_idx_begin, frame_idx_end + 1): + non_cond_frame_outputs.pop(t, None) + for obj_output_dict in inference_state["output_dict_per_obj"].values(): + obj_output_dict["non_cond_frame_outputs"].pop(t, None) diff --git a/py/evf_sam/model/segment_anything_2/sam2/utils/__init__.py b/py/evf_sam/model/segment_anything_2/sam2/utils/__init__.py new file mode 100644 index 0000000..5277f46 --- /dev/null +++ b/py/evf_sam/model/segment_anything_2/sam2/utils/__init__.py @@ -0,0 +1,5 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. diff --git a/py/evf_sam/model/segment_anything_2/sam2/utils/amg.py b/py/evf_sam/model/segment_anything_2/sam2/utils/amg.py new file mode 100644 index 0000000..9868429 --- /dev/null +++ b/py/evf_sam/model/segment_anything_2/sam2/utils/amg.py @@ -0,0 +1,348 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import math +from copy import deepcopy +from itertools import product +from typing import Any, Dict, Generator, ItemsView, List, Tuple + +import numpy as np +import torch + +# Very lightly adapted from https://github.com/facebookresearch/segment-anything/blob/main/segment_anything/utils/amg.py + + +class MaskData: + """ + A structure for storing masks and their related data in batched format. + Implements basic filtering and concatenation. + """ + + def __init__(self, **kwargs) -> None: + for v in kwargs.values(): + assert isinstance( + v, (list, np.ndarray, torch.Tensor) + ), "MaskData only supports list, numpy arrays, and torch tensors." + self._stats = dict(**kwargs) + + def __setitem__(self, key: str, item: Any) -> None: + assert isinstance( + item, (list, np.ndarray, torch.Tensor) + ), "MaskData only supports list, numpy arrays, and torch tensors." + self._stats[key] = item + + def __delitem__(self, key: str) -> None: + del self._stats[key] + + def __getitem__(self, key: str) -> Any: + return self._stats[key] + + def items(self) -> ItemsView[str, Any]: + return self._stats.items() + + def filter(self, keep: torch.Tensor) -> None: + for k, v in self._stats.items(): + if v is None: + self._stats[k] = None + elif isinstance(v, torch.Tensor): + self._stats[k] = v[torch.as_tensor(keep, device=v.device)] + elif isinstance(v, np.ndarray): + self._stats[k] = v[keep.detach().cpu().numpy()] + elif isinstance(v, list) and keep.dtype == torch.bool: + self._stats[k] = [a for i, a in enumerate(v) if keep[i]] + elif isinstance(v, list): + self._stats[k] = [v[i] for i in keep] + else: + raise TypeError(f"MaskData key {k} has an unsupported type {type(v)}.") + + def cat(self, new_stats: "MaskData") -> None: + for k, v in new_stats.items(): + if k not in self._stats or self._stats[k] is None: + self._stats[k] = deepcopy(v) + elif isinstance(v, torch.Tensor): + self._stats[k] = torch.cat([self._stats[k], v], dim=0) + elif isinstance(v, np.ndarray): + self._stats[k] = np.concatenate([self._stats[k], v], axis=0) + elif isinstance(v, list): + self._stats[k] = self._stats[k] + deepcopy(v) + else: + raise TypeError(f"MaskData key {k} has an unsupported type {type(v)}.") + + def to_numpy(self) -> None: + for k, v in self._stats.items(): + if isinstance(v, torch.Tensor): + self._stats[k] = v.float().detach().cpu().numpy() + + +def is_box_near_crop_edge( + boxes: torch.Tensor, crop_box: List[int], orig_box: List[int], atol: float = 20.0 +) -> torch.Tensor: + """Filter masks at the edge of a crop, but not at the edge of the original image.""" + crop_box_torch = torch.as_tensor(crop_box, dtype=torch.float, device=boxes.device) + orig_box_torch = torch.as_tensor(orig_box, dtype=torch.float, device=boxes.device) + boxes = uncrop_boxes_xyxy(boxes, crop_box).float() + near_crop_edge = torch.isclose(boxes, crop_box_torch[None, :], atol=atol, rtol=0) + near_image_edge = torch.isclose(boxes, orig_box_torch[None, :], atol=atol, rtol=0) + near_crop_edge = torch.logical_and(near_crop_edge, ~near_image_edge) + return torch.any(near_crop_edge, dim=1) + + +def box_xyxy_to_xywh(box_xyxy: torch.Tensor) -> torch.Tensor: + box_xywh = deepcopy(box_xyxy) + box_xywh[2] = box_xywh[2] - box_xywh[0] + box_xywh[3] = box_xywh[3] - box_xywh[1] + return box_xywh + + +def batch_iterator(batch_size: int, *args) -> Generator[List[Any], None, None]: + assert len(args) > 0 and all( + len(a) == len(args[0]) for a in args + ), "Batched iteration must have inputs of all the same size." + n_batches = len(args[0]) // batch_size + int(len(args[0]) % batch_size != 0) + for b in range(n_batches): + yield [arg[b * batch_size : (b + 1) * batch_size] for arg in args] + + +def mask_to_rle_pytorch(tensor: torch.Tensor) -> List[Dict[str, Any]]: + """ + Encodes masks to an uncompressed RLE, in the format expected by + pycoco tools. + """ + # Put in fortran order and flatten h,w + b, h, w = tensor.shape + tensor = tensor.permute(0, 2, 1).flatten(1) + + # Compute change indices + diff = tensor[:, 1:] ^ tensor[:, :-1] + change_indices = diff.nonzero() + + # Encode run length + out = [] + for i in range(b): + cur_idxs = change_indices[change_indices[:, 0] == i, 1] + cur_idxs = torch.cat( + [ + torch.tensor([0], dtype=cur_idxs.dtype, device=cur_idxs.device), + cur_idxs + 1, + torch.tensor([h * w], dtype=cur_idxs.dtype, device=cur_idxs.device), + ] + ) + btw_idxs = cur_idxs[1:] - cur_idxs[:-1] + counts = [] if tensor[i, 0] == 0 else [0] + counts.extend(btw_idxs.detach().cpu().tolist()) + out.append({"size": [h, w], "counts": counts}) + return out + + +def rle_to_mask(rle: Dict[str, Any]) -> np.ndarray: + """Compute a binary mask from an uncompressed RLE.""" + h, w = rle["size"] + mask = np.empty(h * w, dtype=bool) + idx = 0 + parity = False + for count in rle["counts"]: + mask[idx : idx + count] = parity + idx += count + parity ^= True + mask = mask.reshape(w, h) + return mask.transpose() # Put in C order + + +def area_from_rle(rle: Dict[str, Any]) -> int: + return sum(rle["counts"][1::2]) + + +def calculate_stability_score( + masks: torch.Tensor, mask_threshold: float, threshold_offset: float +) -> torch.Tensor: + """ + Computes the stability score for a batch of masks. The stability + score is the IoU between the binary masks obtained by thresholding + the predicted mask logits at high and low values. + """ + # One mask is always contained inside the other. + # Save memory by preventing unnecessary cast to torch.int64 + intersections = ( + (masks > (mask_threshold + threshold_offset)) + .sum(-1, dtype=torch.int16) + .sum(-1, dtype=torch.int32) + ) + unions = ( + (masks > (mask_threshold - threshold_offset)) + .sum(-1, dtype=torch.int16) + .sum(-1, dtype=torch.int32) + ) + return intersections / unions + + +def build_point_grid(n_per_side: int) -> np.ndarray: + """Generates a 2D grid of points evenly spaced in [0,1]x[0,1].""" + offset = 1 / (2 * n_per_side) + points_one_side = np.linspace(offset, 1 - offset, n_per_side) + points_x = np.tile(points_one_side[None, :], (n_per_side, 1)) + points_y = np.tile(points_one_side[:, None], (1, n_per_side)) + points = np.stack([points_x, points_y], axis=-1).reshape(-1, 2) + return points + + +def build_all_layer_point_grids( + n_per_side: int, n_layers: int, scale_per_layer: int +) -> List[np.ndarray]: + """Generates point grids for all crop layers.""" + points_by_layer = [] + for i in range(n_layers + 1): + n_points = int(n_per_side / (scale_per_layer**i)) + points_by_layer.append(build_point_grid(n_points)) + return points_by_layer + + +def generate_crop_boxes( + im_size: Tuple[int, ...], n_layers: int, overlap_ratio: float +) -> Tuple[List[List[int]], List[int]]: + """ + Generates a list of crop boxes of different sizes. Each layer + has (2**i)**2 boxes for the ith layer. + """ + crop_boxes, layer_idxs = [], [] + im_h, im_w = im_size + short_side = min(im_h, im_w) + + # Original image + crop_boxes.append([0, 0, im_w, im_h]) + layer_idxs.append(0) + + def crop_len(orig_len, n_crops, overlap): + return int(math.ceil((overlap * (n_crops - 1) + orig_len) / n_crops)) + + for i_layer in range(n_layers): + n_crops_per_side = 2 ** (i_layer + 1) + overlap = int(overlap_ratio * short_side * (2 / n_crops_per_side)) + + crop_w = crop_len(im_w, n_crops_per_side, overlap) + crop_h = crop_len(im_h, n_crops_per_side, overlap) + + crop_box_x0 = [int((crop_w - overlap) * i) for i in range(n_crops_per_side)] + crop_box_y0 = [int((crop_h - overlap) * i) for i in range(n_crops_per_side)] + + # Crops in XYWH format + for x0, y0 in product(crop_box_x0, crop_box_y0): + box = [x0, y0, min(x0 + crop_w, im_w), min(y0 + crop_h, im_h)] + crop_boxes.append(box) + layer_idxs.append(i_layer + 1) + + return crop_boxes, layer_idxs + + +def uncrop_boxes_xyxy(boxes: torch.Tensor, crop_box: List[int]) -> torch.Tensor: + x0, y0, _, _ = crop_box + offset = torch.tensor([[x0, y0, x0, y0]], device=boxes.device) + # Check if boxes has a channel dimension + if len(boxes.shape) == 3: + offset = offset.unsqueeze(1) + return boxes + offset + + +def uncrop_points(points: torch.Tensor, crop_box: List[int]) -> torch.Tensor: + x0, y0, _, _ = crop_box + offset = torch.tensor([[x0, y0]], device=points.device) + # Check if points has a channel dimension + if len(points.shape) == 3: + offset = offset.unsqueeze(1) + return points + offset + + +def uncrop_masks( + masks: torch.Tensor, crop_box: List[int], orig_h: int, orig_w: int +) -> torch.Tensor: + x0, y0, x1, y1 = crop_box + if x0 == 0 and y0 == 0 and x1 == orig_w and y1 == orig_h: + return masks + # Coordinate transform masks + pad_x, pad_y = orig_w - (x1 - x0), orig_h - (y1 - y0) + pad = (x0, pad_x - x0, y0, pad_y - y0) + return torch.nn.functional.pad(masks, pad, value=0) + + +def remove_small_regions( + mask: np.ndarray, area_thresh: float, mode: str +) -> Tuple[np.ndarray, bool]: + """ + Removes small disconnected regions and holes in a mask. Returns the + mask and an indicator of if the mask has been modified. + """ + import cv2 # type: ignore + + assert mode in ["holes", "islands"] + correct_holes = mode == "holes" + working_mask = (correct_holes ^ mask).astype(np.uint8) + n_labels, regions, stats, _ = cv2.connectedComponentsWithStats(working_mask, 8) + sizes = stats[:, -1][1:] # Row 0 is background label + small_regions = [i + 1 for i, s in enumerate(sizes) if s < area_thresh] + if len(small_regions) == 0: + return mask, False + fill_labels = [0] + small_regions + if not correct_holes: + fill_labels = [i for i in range(n_labels) if i not in fill_labels] + # If every region is below threshold, keep largest + if len(fill_labels) == 0: + fill_labels = [int(np.argmax(sizes)) + 1] + mask = np.isin(regions, fill_labels) + return mask, True + + +def coco_encode_rle(uncompressed_rle: Dict[str, Any]) -> Dict[str, Any]: + from pycocotools import mask as mask_utils # type: ignore + + h, w = uncompressed_rle["size"] + rle = mask_utils.frPyObjects(uncompressed_rle, h, w) + rle["counts"] = rle["counts"].decode("utf-8") # Necessary to serialize with json + return rle + + +def batched_mask_to_box(masks: torch.Tensor) -> torch.Tensor: + """ + Calculates boxes in XYXY format around masks. Return [0,0,0,0] for + an empty mask. For input shape C1xC2x...xHxW, the output shape is C1xC2x...x4. + """ + # torch.max below raises an error on empty inputs, just skip in this case + if torch.numel(masks) == 0: + return torch.zeros(*masks.shape[:-2], 4, device=masks.device) + + # Normalize shape to CxHxW + shape = masks.shape + h, w = shape[-2:] + if len(shape) > 2: + masks = masks.flatten(0, -3) + else: + masks = masks.unsqueeze(0) + + # Get top and bottom edges + in_height, _ = torch.max(masks, dim=-1) + in_height_coords = in_height * torch.arange(h, device=in_height.device)[None, :] + bottom_edges, _ = torch.max(in_height_coords, dim=-1) + in_height_coords = in_height_coords + h * (~in_height) + top_edges, _ = torch.min(in_height_coords, dim=-1) + + # Get left and right edges + in_width, _ = torch.max(masks, dim=-2) + in_width_coords = in_width * torch.arange(w, device=in_width.device)[None, :] + right_edges, _ = torch.max(in_width_coords, dim=-1) + in_width_coords = in_width_coords + w * (~in_width) + left_edges, _ = torch.min(in_width_coords, dim=-1) + + # If the mask is empty the right edge will be to the left of the left edge. + # Replace these boxes with [0, 0, 0, 0] + empty_filter = (right_edges < left_edges) | (bottom_edges < top_edges) + out = torch.stack([left_edges, top_edges, right_edges, bottom_edges], dim=-1) + out = out * (~empty_filter).unsqueeze(-1) + + # Return to original shape + if len(shape) > 2: + out = out.reshape(*shape[:-2], 4) + else: + out = out[0] + + return out diff --git a/py/evf_sam/model/segment_anything_2/sam2/utils/misc.py b/py/evf_sam/model/segment_anything_2/sam2/utils/misc.py new file mode 100644 index 0000000..9adf6e4 --- /dev/null +++ b/py/evf_sam/model/segment_anything_2/sam2/utils/misc.py @@ -0,0 +1,238 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import os +import warnings +from threading import Thread + +import numpy as np +import torch +from PIL import Image +from tqdm import tqdm + + +def get_sdpa_settings(): + if torch.cuda.is_available(): + old_gpu = torch.cuda.get_device_properties(0).major < 7 + # only use Flash Attention on Ampere (8.0) or newer GPUs + use_flash_attn = torch.cuda.get_device_properties(0).major >= 8 + if not use_flash_attn: + warnings.warn( + "Flash Attention is disabled as it requires a GPU with Ampere (8.0) CUDA capability.", + category=UserWarning, + stacklevel=2, + ) + # keep math kernel for PyTorch versions before 2.2 (Flash Attention v2 is only + # available on PyTorch 2.2+, while Flash Attention v1 cannot handle all cases) + pytorch_version = tuple(int(v) for v in torch.__version__.split(".")[:2]) + if pytorch_version < (2, 2): + warnings.warn( + f"You are using PyTorch {torch.__version__} without Flash Attention v2 support. " + "Consider upgrading to PyTorch 2.2+ for Flash Attention v2 (which could be faster).", + category=UserWarning, + stacklevel=2, + ) + math_kernel_on = pytorch_version < (2, 2) or not use_flash_attn + else: + old_gpu = True + use_flash_attn = False + math_kernel_on = True + + return old_gpu, use_flash_attn, math_kernel_on + + +def get_connected_components(mask): + """ + Get the connected components (8-connectivity) of binary masks of shape (N, 1, H, W). + + Inputs: + - mask: A binary mask tensor of shape (N, 1, H, W), where 1 is foreground and 0 is + background. + + Outputs: + - labels: A tensor of shape (N, 1, H, W) containing the connected component labels + for foreground pixels and 0 for background pixels. + - counts: A tensor of shape (N, 1, H, W) containing the area of the connected + components for foreground pixels and 0 for background pixels. + """ + from model.segment_anything_2.sam2 import _C + + return _C.get_connected_componnets(mask.to(torch.uint8).contiguous()) + + +def mask_to_box(masks: torch.Tensor): + """ + compute bounding box given an input mask + + Inputs: + - masks: [B, 1, H, W] boxes, dtype=torch.Tensor + + Returns: + - box_coords: [B, 1, 4], contains (x, y) coordinates of top left and bottom right box corners, dtype=torch.Tensor + """ + B, _, h, w = masks.shape + device = masks.device + xs = torch.arange(w, device=device, dtype=torch.int32) + ys = torch.arange(h, device=device, dtype=torch.int32) + grid_xs, grid_ys = torch.meshgrid(xs, ys, indexing="xy") + grid_xs = grid_xs[None, None, ...].expand(B, 1, h, w) + grid_ys = grid_ys[None, None, ...].expand(B, 1, h, w) + min_xs, _ = torch.min(torch.where(masks, grid_xs, w).flatten(-2), dim=-1) + max_xs, _ = torch.max(torch.where(masks, grid_xs, -1).flatten(-2), dim=-1) + min_ys, _ = torch.min(torch.where(masks, grid_ys, h).flatten(-2), dim=-1) + max_ys, _ = torch.max(torch.where(masks, grid_ys, -1).flatten(-2), dim=-1) + bbox_coords = torch.stack((min_xs, min_ys, max_xs, max_ys), dim=-1) + + return bbox_coords + + +def _load_img_as_tensor(img_path, image_size): + img_pil = Image.open(img_path) + img_np = np.array(img_pil.convert("RGB").resize((image_size, image_size))) + if img_np.dtype == np.uint8: # np.uint8 is expected for JPEG images + img_np = img_np / 255.0 + else: + raise RuntimeError(f"Unknown image dtype: {img_np.dtype} on {img_path}") + img = torch.from_numpy(img_np).permute(2, 0, 1) + video_width, video_height = img_pil.size # the original video size + return img, video_height, video_width + + +class AsyncVideoFrameLoader: + """ + A list of video frames to be load asynchronously without blocking session start. + """ + + def __init__(self, img_paths, image_size, offload_video_to_cpu, img_mean, img_std): + self.img_paths = img_paths + self.image_size = image_size + self.offload_video_to_cpu = offload_video_to_cpu + self.img_mean = img_mean + self.img_std = img_std + # items in `self._images` will be loaded asynchronously + self.images = [None] * len(img_paths) + # catch and raise any exceptions in the async loading thread + self.exception = None + # video_height and video_width be filled when loading the first image + self.video_height = None + self.video_width = None + + # load the first frame to fill video_height and video_width and also + # to cache it (since it's most likely where the user will click) + self.__getitem__(0) + + # load the rest of frames asynchronously without blocking the session start + def _load_frames(): + try: + for n in tqdm(range(len(self.images)), desc="frame loading (JPEG)"): + self.__getitem__(n) + except Exception as e: + self.exception = e + + self.thread = Thread(target=_load_frames, daemon=True) + self.thread.start() + + def __getitem__(self, index): + if self.exception is not None: + raise RuntimeError("Failure in frame loading thread") from self.exception + + img = self.images[index] + if img is not None: + return img + + img, video_height, video_width = _load_img_as_tensor( + self.img_paths[index], self.image_size + ) + self.video_height = video_height + self.video_width = video_width + # normalize by mean and std + img -= self.img_mean + img /= self.img_std + if not self.offload_video_to_cpu: + img = img.cuda(non_blocking=True) + self.images[index] = img + return img + + def __len__(self): + return len(self.images) + + +def load_video_frames( + video_path, + image_size, + offload_video_to_cpu, + img_mean=(0.485, 0.456, 0.406), + img_std=(0.229, 0.224, 0.225), + async_loading_frames=False, +): + """ + Load the video frames from a directory of JPEG files (".jpg" format). + + The frames are resized to image_size x image_size and are loaded to GPU if + `offload_video_to_cpu` is `False` and to CPU if `offload_video_to_cpu` is `True`. + + You can load a frame asynchronously by setting `async_loading_frames` to `True`. + """ + if isinstance(video_path, str) and os.path.isdir(video_path): + jpg_folder = video_path + else: + raise NotImplementedError("Only JPEG frames are supported at this moment") + + frame_names = [ + p + for p in os.listdir(jpg_folder) + if os.path.splitext(p)[-1] in [".jpg", ".jpeg", ".JPG", ".JPEG"] + ] + frame_names.sort(key=lambda p: int(os.path.splitext(p)[0])) + num_frames = len(frame_names) + if num_frames == 0: + raise RuntimeError(f"no images found in {jpg_folder}") + img_paths = [os.path.join(jpg_folder, frame_name) for frame_name in frame_names] + img_mean = torch.tensor(img_mean, dtype=torch.float32)[:, None, None] + img_std = torch.tensor(img_std, dtype=torch.float32)[:, None, None] + + if async_loading_frames: + lazy_images = AsyncVideoFrameLoader( + img_paths, image_size, offload_video_to_cpu, img_mean, img_std + ) + return lazy_images, lazy_images.video_height, lazy_images.video_width + + images = torch.zeros(num_frames, 3, image_size, image_size, dtype=torch.float32) + for n, img_path in enumerate(tqdm(img_paths, desc="frame loading (JPEG)")): + images[n], video_height, video_width = _load_img_as_tensor(img_path, image_size) + if not offload_video_to_cpu: + images = images.cuda() + img_mean = img_mean.cuda() + img_std = img_std.cuda() + # normalize by mean and std + images -= img_mean + images /= img_std + return images, video_height, video_width + + +def fill_holes_in_mask_scores(mask, max_area): + """ + A post processor to fill small holes in mask scores with area under `max_area`. + """ + # Holes are those connected components in background with area <= self.max_area + # (background regions are those with mask scores <= 0) + assert max_area > 0, "max_area must be positive" + labels, areas = get_connected_components(mask <= 0) + is_hole = (labels > 0) & (areas <= max_area) + # We fill holes with a small positive mask score (0.1) to change them to foreground. + mask = torch.where(is_hole, 0.1, mask) + return mask + + +def concat_points(old_point_inputs, new_points, new_labels): + """Add new points and labels to previous point inputs (add at the end).""" + if old_point_inputs is None: + points, labels = new_points, new_labels + else: + points = torch.cat([old_point_inputs["point_coords"], new_points], dim=1) + labels = torch.cat([old_point_inputs["point_labels"], new_labels], dim=1) + + return {"point_coords": points, "point_labels": labels} diff --git a/py/evf_sam/model/segment_anything_2/sam2/utils/transforms.py b/py/evf_sam/model/segment_anything_2/sam2/utils/transforms.py new file mode 100644 index 0000000..082a351 --- /dev/null +++ b/py/evf_sam/model/segment_anything_2/sam2/utils/transforms.py @@ -0,0 +1,99 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import torch +import torch.nn as nn +import torch.nn.functional as F +from torchvision.transforms import Normalize, Resize, ToTensor + + +class SAM2Transforms(nn.Module): + def __init__( + self, resolution, mask_threshold, max_hole_area=0.0, max_sprinkle_area=0.0 + ): + """ + Transforms for SAM2. + """ + super().__init__() + self.resolution = resolution + self.mask_threshold = mask_threshold + self.max_hole_area = max_hole_area + self.max_sprinkle_area = max_sprinkle_area + self.mean = [0.485, 0.456, 0.406] + self.std = [0.229, 0.224, 0.225] + self.to_tensor = ToTensor() + self.transforms = torch.jit.script( + nn.Sequential( + Resize((self.resolution, self.resolution)), + Normalize(self.mean, self.std), + ) + ) + + def __call__(self, x): + x = self.to_tensor(x) + return self.transforms(x) + + def forward_batch(self, img_list): + img_batch = [self.transforms(self.to_tensor(img)) for img in img_list] + img_batch = torch.stack(img_batch, dim=0) + return img_batch + + def transform_coords( + self, coords: torch.Tensor, normalize=False, orig_hw=None + ) -> torch.Tensor: + """ + Expects a torch tensor with length 2 in the last dimension. The coordinates can be in absolute image or normalized coordinates, + If the coords are in absolute image coordinates, normalize should be set to True and original image size is required. + + Returns + Un-normalized coordinates in the range of [0, 1] which is expected by the SAM2 model. + """ + if normalize: + assert orig_hw is not None + h, w = orig_hw + coords = coords.clone() + coords[..., 0] = coords[..., 0] / w + coords[..., 1] = coords[..., 1] / h + + coords = coords * self.resolution # unnormalize coords + return coords + + def transform_boxes( + self, boxes: torch.Tensor, normalize=False, orig_hw=None + ) -> torch.Tensor: + """ + Expects a tensor of shape Bx4. The coordinates can be in absolute image or normalized coordinates, + if the coords are in absolute image coordinates, normalize should be set to True and original image size is required. + """ + boxes = self.transform_coords(boxes.reshape(-1, 2, 2), normalize, orig_hw) + return boxes + + def postprocess_masks(self, masks: torch.Tensor, orig_hw) -> torch.Tensor: + """ + Perform PostProcessing on output masks. + """ + from model.segment_anything_2.sam2.utils.misc import get_connected_components + + masks = masks.float() + if self.max_hole_area > 0: + # Holes are those connected components in background with area <= self.fill_hole_area + # (background regions are those with mask scores <= self.mask_threshold) + mask_flat = masks.flatten(0, 1).unsqueeze(1) # flatten as 1-channel image + labels, areas = get_connected_components(mask_flat <= self.mask_threshold) + is_hole = (labels > 0) & (areas <= self.max_hole_area) + is_hole = is_hole.reshape_as(masks) + # We fill holes with a small positive mask score (10.0) to change them to foreground. + masks = torch.where(is_hole, self.mask_threshold + 10.0, masks) + + if self.max_sprinkle_area > 0: + labels, areas = get_connected_components(mask_flat > self.mask_threshold) + is_hole = (labels > 0) & (areas <= self.max_sprinkle_area) + is_hole = is_hole.reshape_as(masks) + # We fill holes with negative mask score (-10.0) to change them to background. + masks = torch.where(is_hole, self.mask_threshold - 10.0, masks) + + masks = F.interpolate(masks, orig_hw, mode="bilinear", align_corners=False) + return masks diff --git a/py/evf_sam/model/segment_anything_2/sam2_configs/__init__.py b/py/evf_sam/model/segment_anything_2/sam2_configs/__init__.py new file mode 100644 index 0000000..5277f46 --- /dev/null +++ b/py/evf_sam/model/segment_anything_2/sam2_configs/__init__.py @@ -0,0 +1,5 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. diff --git a/py/evf_sam/model/segment_anything_2/sam2_configs/sam2_hiera_b+.yaml b/py/evf_sam/model/segment_anything_2/sam2_configs/sam2_hiera_b+.yaml new file mode 100644 index 0000000..5ca7bfc --- /dev/null +++ b/py/evf_sam/model/segment_anything_2/sam2_configs/sam2_hiera_b+.yaml @@ -0,0 +1,113 @@ +# @package _global_ + +# Model +model: + _target_: model.segment_anything_2.sam2.modeling.sam2_base.SAM2Base + image_encoder: + _target_: model.segment_anything_2.sam2.modeling.backbones.image_encoder.ImageEncoder + scalp: 1 + trunk: + _target_: model.segment_anything_2.sam2.modeling.backbones.hieradet.Hiera + embed_dim: 112 + num_heads: 2 + neck: + _target_: model.segment_anything_2.sam2.modeling.backbones.image_encoder.FpnNeck + position_encoding: + _target_: model.segment_anything_2.sam2.modeling.position_encoding.PositionEmbeddingSine + num_pos_feats: 256 + normalize: true + scale: null + temperature: 10000 + d_model: 256 + backbone_channel_list: [896, 448, 224, 112] + fpn_top_down_levels: [2, 3] # output level 0 and 1 directly use the backbone features + fpn_interp_model: nearest + + memory_attention: + _target_: model.segment_anything_2.sam2.modeling.memory_attention.MemoryAttention + d_model: 256 + pos_enc_at_input: true + layer: + _target_: model.segment_anything_2.sam2.modeling.memory_attention.MemoryAttentionLayer + activation: relu + dim_feedforward: 2048 + dropout: 0.1 + pos_enc_at_attn: false + self_attention: + _target_: model.segment_anything_2.sam2.modeling.sam.transformer.RoPEAttention + rope_theta: 10000.0 + feat_sizes: [32, 32] + embedding_dim: 256 + num_heads: 1 + downsample_rate: 1 + dropout: 0.1 + d_model: 256 + pos_enc_at_cross_attn_keys: true + pos_enc_at_cross_attn_queries: false + cross_attention: + _target_: model.segment_anything_2.sam2.modeling.sam.transformer.RoPEAttention + rope_theta: 10000.0 + feat_sizes: [32, 32] + rope_k_repeat: True + embedding_dim: 256 + num_heads: 1 + downsample_rate: 1 + dropout: 0.1 + kv_in_dim: 64 + num_layers: 4 + + memory_encoder: + _target_: model.segment_anything_2.sam2.modeling.memory_encoder.MemoryEncoder + out_dim: 64 + position_encoding: + _target_: model.segment_anything_2.sam2.modeling.position_encoding.PositionEmbeddingSine + num_pos_feats: 64 + normalize: true + scale: null + temperature: 10000 + mask_downsampler: + _target_: model.segment_anything_2.sam2.modeling.memory_encoder.MaskDownSampler + kernel_size: 3 + stride: 2 + padding: 1 + fuser: + _target_: model.segment_anything_2.sam2.modeling.memory_encoder.Fuser + layer: + _target_: model.segment_anything_2.sam2.modeling.memory_encoder.CXBlock + dim: 256 + kernel_size: 7 + padding: 3 + layer_scale_init_value: 1e-6 + use_dwconv: True # depth-wise convs + num_layers: 2 + + num_maskmem: 7 + image_size: 1024 + # apply scaled sigmoid on mask logits for memory encoder, and directly feed input mask as output mask + sigmoid_scale_for_mem_enc: 20.0 + sigmoid_bias_for_mem_enc: -10.0 + use_mask_input_as_output_without_sam: true + # Memory + directly_add_no_mem_embed: true + # use high-resolution feature map in the SAM mask decoder + use_high_res_features_in_sam: true + # output 3 masks on the first click on initial conditioning frames + multimask_output_in_sam: true + # SAM heads + iou_prediction_use_sigmoid: True + # cross-attend to object pointers from other frames (based on SAM output tokens) in the encoder + use_obj_ptrs_in_encoder: true + add_tpos_enc_to_obj_ptrs: false + only_obj_ptrs_in_the_past_for_eval: true + # object occlusion prediction + pred_obj_scores: true + pred_obj_scores_mlp: true + fixed_no_obj_ptr: true + # multimask tracking settings + multimask_output_for_tracking: true + use_multimask_token_for_obj_ptr: true + multimask_min_pt_num: 0 + multimask_max_pt_num: 1 + use_mlp_for_obj_ptr_proj: true + # Compilation flag + compile_image_encoder: False diff --git a/py/evf_sam/model/segment_anything_2/sam2_configs/sam2_hiera_l.yaml b/py/evf_sam/model/segment_anything_2/sam2_configs/sam2_hiera_l.yaml new file mode 100644 index 0000000..293d038 --- /dev/null +++ b/py/evf_sam/model/segment_anything_2/sam2_configs/sam2_hiera_l.yaml @@ -0,0 +1,117 @@ +# @package _global_ + +# Model +model: + _target_: model.segment_anything_2.sam2.modeling.sam2_base.SAM2Base + image_encoder: + _target_: model.segment_anything_2.sam2.modeling.backbones.image_encoder.ImageEncoder + scalp: 1 + trunk: + _target_: model.segment_anything_2.sam2.modeling.backbones.hieradet.Hiera + embed_dim: 144 + num_heads: 2 + stages: [2, 6, 36, 4] + global_att_blocks: [23, 33, 43] + window_pos_embed_bkg_spatial_size: [7, 7] + window_spec: [8, 4, 16, 8] + neck: + _target_: model.segment_anything_2.sam2.modeling.backbones.image_encoder.FpnNeck + position_encoding: + _target_: model.segment_anything_2.sam2.modeling.position_encoding.PositionEmbeddingSine + num_pos_feats: 256 + normalize: true + scale: null + temperature: 10000 + d_model: 256 + backbone_channel_list: [1152, 576, 288, 144] + fpn_top_down_levels: [2, 3] # output level 0 and 1 directly use the backbone features + fpn_interp_model: nearest + + memory_attention: + _target_: model.segment_anything_2.sam2.modeling.memory_attention.MemoryAttention + d_model: 256 + pos_enc_at_input: true + layer: + _target_: model.segment_anything_2.sam2.modeling.memory_attention.MemoryAttentionLayer + activation: relu + dim_feedforward: 2048 + dropout: 0.1 + pos_enc_at_attn: false + self_attention: + _target_: model.segment_anything_2.sam2.modeling.sam.transformer.RoPEAttention + rope_theta: 10000.0 + feat_sizes: [32, 32] + embedding_dim: 256 + num_heads: 1 + downsample_rate: 1 + dropout: 0.1 + d_model: 256 + pos_enc_at_cross_attn_keys: true + pos_enc_at_cross_attn_queries: false + cross_attention: + _target_: model.segment_anything_2.sam2.modeling.sam.transformer.RoPEAttention + rope_theta: 10000.0 + feat_sizes: [32, 32] + rope_k_repeat: True + embedding_dim: 256 + num_heads: 1 + downsample_rate: 1 + dropout: 0.1 + kv_in_dim: 64 + num_layers: 4 + + memory_encoder: + _target_: model.segment_anything_2.sam2.modeling.memory_encoder.MemoryEncoder + out_dim: 64 + position_encoding: + _target_: model.segment_anything_2.sam2.modeling.position_encoding.PositionEmbeddingSine + num_pos_feats: 64 + normalize: true + scale: null + temperature: 10000 + mask_downsampler: + _target_: model.segment_anything_2.sam2.modeling.memory_encoder.MaskDownSampler + kernel_size: 3 + stride: 2 + padding: 1 + fuser: + _target_: model.segment_anything_2.sam2.modeling.memory_encoder.Fuser + layer: + _target_: model.segment_anything_2.sam2.modeling.memory_encoder.CXBlock + dim: 256 + kernel_size: 7 + padding: 3 + layer_scale_init_value: 1e-6 + use_dwconv: True # depth-wise convs + num_layers: 2 + + num_maskmem: 7 + image_size: 1024 + # apply scaled sigmoid on mask logits for memory encoder, and directly feed input mask as output mask + sigmoid_scale_for_mem_enc: 20.0 + sigmoid_bias_for_mem_enc: -10.0 + use_mask_input_as_output_without_sam: true + # Memory + directly_add_no_mem_embed: true + # use high-resolution feature map in the SAM mask decoder + use_high_res_features_in_sam: true + # output 3 masks on the first click on initial conditioning frames + multimask_output_in_sam: true + # SAM heads + iou_prediction_use_sigmoid: True + # cross-attend to object pointers from other frames (based on SAM output tokens) in the encoder + use_obj_ptrs_in_encoder: true + add_tpos_enc_to_obj_ptrs: false + only_obj_ptrs_in_the_past_for_eval: true + # object occlusion prediction + pred_obj_scores: true + pred_obj_scores_mlp: true + fixed_no_obj_ptr: true + # multimask tracking settings + multimask_output_for_tracking: true + use_multimask_token_for_obj_ptr: true + multimask_min_pt_num: 0 + multimask_max_pt_num: 1 + use_mlp_for_obj_ptr_proj: true + # Compilation flag + compile_image_encoder: False diff --git a/py/evf_sam/model/segment_anything_2/sam2_configs/sam2_hiera_s.yaml b/py/evf_sam/model/segment_anything_2/sam2_configs/sam2_hiera_s.yaml new file mode 100644 index 0000000..8d4627b --- /dev/null +++ b/py/evf_sam/model/segment_anything_2/sam2_configs/sam2_hiera_s.yaml @@ -0,0 +1,116 @@ +# @package _global_ + +# Model +model: + _target_: model.segment_anything_2.sam2.modeling.sam2_base.SAM2Base + image_encoder: + _target_: model.segment_anything_2.sam2.modeling.backbones.image_encoder.ImageEncoder + scalp: 1 + trunk: + _target_: model.segment_anything_2.sam2.modeling.backbones.hieradet.Hiera + embed_dim: 96 + num_heads: 1 + stages: [1, 2, 11, 2] + global_att_blocks: [7, 10, 13] + window_pos_embed_bkg_spatial_size: [7, 7] + neck: + _target_: model.segment_anything_2.sam2.modeling.backbones.image_encoder.FpnNeck + position_encoding: + _target_: model.segment_anything_2.sam2.modeling.position_encoding.PositionEmbeddingSine + num_pos_feats: 256 + normalize: true + scale: null + temperature: 10000 + d_model: 256 + backbone_channel_list: [768, 384, 192, 96] + fpn_top_down_levels: [2, 3] # output level 0 and 1 directly use the backbone features + fpn_interp_model: nearest + + memory_attention: + _target_: model.segment_anything_2.sam2.modeling.memory_attention.MemoryAttention + d_model: 256 + pos_enc_at_input: true + layer: + _target_: model.segment_anything_2.sam2.modeling.memory_attention.MemoryAttentionLayer + activation: relu + dim_feedforward: 2048 + dropout: 0.1 + pos_enc_at_attn: false + self_attention: + _target_: model.segment_anything_2.sam2.modeling.sam.transformer.RoPEAttention + rope_theta: 10000.0 + feat_sizes: [32, 32] + embedding_dim: 256 + num_heads: 1 + downsample_rate: 1 + dropout: 0.1 + d_model: 256 + pos_enc_at_cross_attn_keys: true + pos_enc_at_cross_attn_queries: false + cross_attention: + _target_: model.segment_anything_2.sam2.modeling.sam.transformer.RoPEAttention + rope_theta: 10000.0 + feat_sizes: [32, 32] + rope_k_repeat: True + embedding_dim: 256 + num_heads: 1 + downsample_rate: 1 + dropout: 0.1 + kv_in_dim: 64 + num_layers: 4 + + memory_encoder: + _target_: model.segment_anything_2.sam2.modeling.memory_encoder.MemoryEncoder + out_dim: 64 + position_encoding: + _target_: model.segment_anything_2.sam2.modeling.position_encoding.PositionEmbeddingSine + num_pos_feats: 64 + normalize: true + scale: null + temperature: 10000 + mask_downsampler: + _target_: model.segment_anything_2.sam2.modeling.memory_encoder.MaskDownSampler + kernel_size: 3 + stride: 2 + padding: 1 + fuser: + _target_: model.segment_anything_2.sam2.modeling.memory_encoder.Fuser + layer: + _target_: model.segment_anything_2.sam2.modeling.memory_encoder.CXBlock + dim: 256 + kernel_size: 7 + padding: 3 + layer_scale_init_value: 1e-6 + use_dwconv: True # depth-wise convs + num_layers: 2 + + num_maskmem: 7 + image_size: 1024 + # apply scaled sigmoid on mask logits for memory encoder, and directly feed input mask as output mask + sigmoid_scale_for_mem_enc: 20.0 + sigmoid_bias_for_mem_enc: -10.0 + use_mask_input_as_output_without_sam: true + # Memory + directly_add_no_mem_embed: true + # use high-resolution feature map in the SAM mask decoder + use_high_res_features_in_sam: true + # output 3 masks on the first click on initial conditioning frames + multimask_output_in_sam: true + # SAM heads + iou_prediction_use_sigmoid: True + # cross-attend to object pointers from other frames (based on SAM output tokens) in the encoder + use_obj_ptrs_in_encoder: true + add_tpos_enc_to_obj_ptrs: false + only_obj_ptrs_in_the_past_for_eval: true + # object occlusion prediction + pred_obj_scores: true + pred_obj_scores_mlp: true + fixed_no_obj_ptr: true + # multimask tracking settings + multimask_output_for_tracking: true + use_multimask_token_for_obj_ptr: true + multimask_min_pt_num: 0 + multimask_max_pt_num: 1 + use_mlp_for_obj_ptr_proj: true + # Compilation flag + compile_image_encoder: False diff --git a/py/evf_sam/model/segment_anything_2/sam2_configs/sam2_hiera_t.yaml b/py/evf_sam/model/segment_anything_2/sam2_configs/sam2_hiera_t.yaml new file mode 100644 index 0000000..2664b7c --- /dev/null +++ b/py/evf_sam/model/segment_anything_2/sam2_configs/sam2_hiera_t.yaml @@ -0,0 +1,118 @@ +# @package _global_ + +# Model +model: + _target_: model.segment_anything_2.sam2.modeling.sam2_base.SAM2Base + image_encoder: + _target_: model.segment_anything_2.sam2.modeling.backbones.image_encoder.ImageEncoder + scalp: 1 + trunk: + _target_: model.segment_anything_2.sam2.modeling.backbones.hieradet.Hiera + embed_dim: 96 + num_heads: 1 + stages: [1, 2, 7, 2] + global_att_blocks: [5, 7, 9] + window_pos_embed_bkg_spatial_size: [7, 7] + neck: + _target_: model.segment_anything_2.sam2.modeling.backbones.image_encoder.FpnNeck + position_encoding: + _target_: model.segment_anything_2.sam2.modeling.position_encoding.PositionEmbeddingSine + num_pos_feats: 256 + normalize: true + scale: null + temperature: 10000 + d_model: 256 + backbone_channel_list: [768, 384, 192, 96] + fpn_top_down_levels: [2, 3] # output level 0 and 1 directly use the backbone features + fpn_interp_model: nearest + + memory_attention: + _target_: model.segment_anything_2.sam2.modeling.memory_attention.MemoryAttention + d_model: 256 + pos_enc_at_input: true + layer: + _target_: model.segment_anything_2.sam2.modeling.memory_attention.MemoryAttentionLayer + activation: relu + dim_feedforward: 2048 + dropout: 0.1 + pos_enc_at_attn: false + self_attention: + _target_: model.segment_anything_2.sam2.modeling.sam.transformer.RoPEAttention + rope_theta: 10000.0 + feat_sizes: [32, 32] + embedding_dim: 256 + num_heads: 1 + downsample_rate: 1 + dropout: 0.1 + d_model: 256 + pos_enc_at_cross_attn_keys: true + pos_enc_at_cross_attn_queries: false + cross_attention: + _target_: model.segment_anything_2.sam2.modeling.sam.transformer.RoPEAttention + rope_theta: 10000.0 + feat_sizes: [32, 32] + rope_k_repeat: True + embedding_dim: 256 + num_heads: 1 + downsample_rate: 1 + dropout: 0.1 + kv_in_dim: 64 + num_layers: 4 + + memory_encoder: + _target_: model.segment_anything_2.sam2.modeling.memory_encoder.MemoryEncoder + out_dim: 64 + position_encoding: + _target_: model.segment_anything_2.sam2.modeling.position_encoding.PositionEmbeddingSine + num_pos_feats: 64 + normalize: true + scale: null + temperature: 10000 + mask_downsampler: + _target_: model.segment_anything_2.sam2.modeling.memory_encoder.MaskDownSampler + kernel_size: 3 + stride: 2 + padding: 1 + fuser: + _target_: model.segment_anything_2.sam2.modeling.memory_encoder.Fuser + layer: + _target_: model.segment_anything_2.sam2.modeling.memory_encoder.CXBlock + dim: 256 + kernel_size: 7 + padding: 3 + layer_scale_init_value: 1e-6 + use_dwconv: True # depth-wise convs + num_layers: 2 + + num_maskmem: 7 + image_size: 1024 + # apply scaled sigmoid on mask logits for memory encoder, and directly feed input mask as output mask + # SAM decoder + sigmoid_scale_for_mem_enc: 20.0 + sigmoid_bias_for_mem_enc: -10.0 + use_mask_input_as_output_without_sam: true + # Memory + directly_add_no_mem_embed: true + # use high-resolution feature map in the SAM mask decoder + use_high_res_features_in_sam: true + # output 3 masks on the first click on initial conditioning frames + multimask_output_in_sam: true + # SAM heads + iou_prediction_use_sigmoid: True + # cross-attend to object pointers from other frames (based on SAM output tokens) in the encoder + use_obj_ptrs_in_encoder: true + add_tpos_enc_to_obj_ptrs: false + only_obj_ptrs_in_the_past_for_eval: true + # object occlusion prediction + pred_obj_scores: true + pred_obj_scores_mlp: true + fixed_no_obj_ptr: true + # multimask tracking settings + multimask_output_for_tracking: true + use_multimask_token_for_obj_ptr: true + multimask_min_pt_num: 0 + multimask_max_pt_num: 1 + use_mlp_for_obj_ptr_proj: true + # Compilation flag + # HieraT does not currently support compilation, should always be set to False + compile_image_encoder: False diff --git a/py/evf_sam/model/segment_anything_2/setup.py b/py/evf_sam/model/segment_anything_2/setup.py new file mode 100644 index 0000000..a228990 --- /dev/null +++ b/py/evf_sam/model/segment_anything_2/setup.py @@ -0,0 +1,29 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +from setuptools import find_packages, setup +from torch.utils.cpp_extension import BuildExtension, CUDAExtension + +def get_extensions(): + srcs = ["sam2/csrc/connected_components.cu"] + compile_args = { + "cxx": [], + "nvcc": [ + "-DCUDA_HAS_FP16=1", + "-D__CUDA_NO_HALF_OPERATORS__", + "-D__CUDA_NO_HALF_CONVERSIONS__", + "-D__CUDA_NO_HALF2_OPERATORS__", + ], + } + ext_modules = [CUDAExtension("sam2._C", srcs, extra_compile_args=compile_args)] + return ext_modules + + +# Setup configuration +setup( + ext_modules=get_extensions(), + cmdclass={"build_ext": BuildExtension.with_options(no_python_abi_suffix=True)}, +) diff --git a/py/evf_sam/model/unilm/beit3/README.md b/py/evf_sam/model/unilm/beit3/README.md new file mode 100644 index 0000000..39c5b2e --- /dev/null +++ b/py/evf_sam/model/unilm/beit3/README.md @@ -0,0 +1,191 @@ +# [(BEiT-3) Image as a Foreign Language: BEiT Pretraining for Vision and Vision-Language Tasks](https://arxiv.org/abs/2208.10442) + +Official PyTorch implementation and pretrained models of BEiT-3. + +The code and pretrained models of **BEiT** can be found at [here](https://github.com/microsoft/unilm/tree/master/beit). + +The code and pretrained models of **BEiT v2** can be found at [here](https://github.com/microsoft/unilm/tree/master/beit2). + +- March, 2023: release [the code and pretrained models of **BEiT-3**](https://github.com/microsoft/unilm/tree/master/beit3) +- March, 2023: [**BEiT-3**](https://arxiv.org/abs/2208.10442) was accepted by **CVPR 2023**. +- Sept 2022: release [the code and pretrained models of **BEiT v2**](https://github.com/microsoft/unilm/tree/master/beit2) +- Aug 2022: release preprint [Image as a Foreign Language: BEiT Pretraining for All Vision and Vision-Language Tasks](https://arxiv.org/abs/2208.10442) +- Aug 2022: release preprint [BEiT v2: Masked Image Modeling with Vector-Quantized Visual Tokenizers](https://arxiv.org/abs/2208.06366) +- June 2022: release preprint [VL-BEiT: Generative Vision-Language Pretraining](https://arxiv.org/abs/2206.01127) +- March, 2022: add [linear probe examples](https://github.com/microsoft/unilm/blob/master/beit/get_started_for_image_classification.md#example-linear-probe-on-imagenet) +- January, 2022: [**BEiT**](https://openreview.net/forum?id=p-BhZSz59o4) was accepted by **ICLR 2022 as Oral presentation** (54 out of 3391). +- August 2021: [**BEiT**](https://huggingface.co/transformers/master/model_doc/beit.html) is on [HuggingFace](https://github.com/huggingface/transformers) +- July 2021: BEiT-large achieves **[state-of-the-art results on ADE20K](https://paperswithcode.com/sota/semantic-segmentation-on-ade20k) (a big jump to 57.0 mIoU) for semantic segmentation**. +- July 2021: BEiT-large achieves **state-of-the-art ImageNet top-1 accuracy (88.6%) under the setting without extra data other than ImageNet-22k**. +- July 2021: release [the code and pretrained models of **BEiT**](https://github.com/microsoft/unilm/tree/master/beit) +- June 2021: release preprint [BEiT: BERT Pre-Training of Image Transformers](https://arxiv.org/abs/2106.08254) + +## Pretrained models + +We provide BEiT-3 weights pretrained on monomodal and multimodal data. Our large-size model outperforms previous large-size models across various vision-language and vision downstream tasks. The models were pretrained with 224x224 resolution. + +### Tips +- For vision-language tasks that require deep fusion, we recommend using `BEiT3-base` and `BEiT3-large`. +- For image-text retrieval or vision tasks, using `BEiT3-base-itc` and `BEiT3-large-itc` usually achieve better performance. + +### Download Checkpoints + +1. Models pretrained on ImageNet-21k images, 160 GB text documents, and web-scale image-text pairs (collected from [LAION-400M](https://laion.ai/blog/laion-400-open-dataset/), [English LAION-2B](https://laion.ai/blog/laion-5b/), [COYO-700M](https://github.com/kakaobrain/coyo-dataset), and CC15M). + - [`BEiT3-base`](https://github.com/addf400/files/releases/download/beit3/beit3_base_patch16_224.pth): #layer=12; hidden=768; FFN factor=4x; #head=12; patch=16x16; #parameters: 276M + - [`BEiT3-large`](https://github.com/addf400/files/releases/download/beit3/beit3_large_patch16_224.pth): #layer=24; hidden=1024; FFN factor=4x; #head=16; patch=16x16; #parameters: 746M + +2. Perform image-text contrastive intermediate tuning on `BEiT3-base` and `BEiT3-large`. + - [`BEiT3-base-itc`](https://github.com/addf400/files/releases/download/beit3/beit3_base_itc_patch16_224.pth): #layer=12; hidden=768; FFN factor=4x; #head=12; patch=16x16; #parameters: 222M + - [`BEiT3-large-itc`](https://github.com/addf400/files/releases/download/beit3/beit3_large_itc_patch16_224.pth): #layer=24; hidden=1024; FFN factor=4x; #head=16; patch=16x16; #parameters: 674M + +3. Add indomain image-text pairs (COCO and VG) to continue training `BEiT3-base` and `BEiT3-large` using masked data modeling. The indomain models achieve better performance on VQAv2 and NLVR2 tasks. + - [`BEiT3-base-indomain`](https://github.com/addf400/files/releases/download/beit3/beit3_base_indomain_patch16_224.pth): #layer=12; hidden=768; FFN factor=4x; #head=12; patch=16x16; #parameters: 276M + - [`BEiT3-large-indomain`](https://github.com/addf400/files/releases/download/beit3/beit3_large_indomain_patch16_224.pth): #layer=24; hidden=1024; FFN factor=4x; #head=16; patch=16x16; #parameters: 746M + +### Text Tokenizer + +[beit3.spm](https://github.com/addf400/files/releases/download/beit3/beit3.spm) is the sentencepiece model used for tokenizing texts. +``` +from transformers import XLMRobertaTokenizer +tokenizer = XLMRobertaTokenizer("/your_beit3_model_path/beit3.spm") +``` + +### Architecture + +We use [Magneto](https://arxiv.org/abs/2210.06423) with decoupled Multiway Transformer as the backbone architecture. Magneto can have better training stability and obtain better performance across modalities (such as vision, and language). The implementation is based on the [torchscale](https://github.com/microsoft/torchscale/blob/main/torchscale/model/BEiT3.py) package. + + +## Setup + +``` +alias=`whoami | cut -d'.' -f2`; docker run -it --rm --runtime=nvidia --ipc=host --privileged -v /home/${alias}:/home/${alias} pytorch/pytorch:1.8.1-cuda11.1-cudnn8-devel bash +``` + +Clone the repo and install required packages: +``` +git clone https://github.com/microsoft/unilm.git +cd unilm/beit3 +pip install -r requirements.txt +``` + + +## Fine-tuning on ImageNet-1k (Image Classification) + +The detailed instructions can be found at [`get_started_for_image_classification.md`](get_started/get_started_for_image_classification.md). We only use vision-related parameters for image classification fine-tuning. + +| initialized checkpoint | resolution | acc@1 | acc@5 | #params | weight | +|:----------------------------------------|:----------:|:-----:|:-----:|:-------:|-------------------| +| [beit3_base_patch16_224](https://github.com/addf400/files/releases/download/beit3/beit3_base_patch16_224.pth) | 224x224 | 85.4 | 97.6 | 87M | [link](https://github.com/addf400/files/releases/download/beit3/beit3_base_patch16_224_in1k.pth) | +| [beit3_base_indomain_patch16_224](https://github.com/addf400/files/releases/download/beit3/beit3_base_indomain_patch16_224.pth) | 224x224 | 85.4 | 97.6 | 87M | [link](https://github.com/addf400/files/releases/download/beit3/beit3_base_indomain_patch16_224_in1k.pth) | +| [beit3_large_patch16_224](https://github.com/addf400/files/releases/download/beit3/beit3_large_patch16_224.pth) | 224x224 | 87.6 | 98.3 | 305M | [link](https://github.com/addf400/files/releases/download/beit3/beit3_large_patch16_224_in1k.pth) | +| [beit3_large_indomain_patch16_224](https://github.com/addf400/files/releases/download/beit3/beit3_large_indomain_patch16_224.pth) | 224x224 | 87.5 | 98.3 | 305M | [link](https://github.com/addf400/files/releases/download/beit3/beit3_large_indomain_patch16_224_in1k.pth) | + + +## Fine-tuning on VQAv2 (Visual Question Answering) + +The detailed instructions can be found at [`get_started_for_vqav2.md`](get_started/get_started_for_vqav2.md). + +| initialized checkpoint | resolution | augmented data | test-dev | test-std | #params | weight | +|:----------------------------------------|:----------:|:-----:|:-----:|:-----:|:-------:|-------------------| +| [beit3_base_patch16_224](https://github.com/addf400/files/releases/download/beit3/beit3_base_patch16_224.pth) | 480x480 | - | 77.65 | - | 228M | [link](https://github.com/addf400/files/releases/download/beit3/beit3_base_patch16_480_vqa.pth) | +| [beit3_base_indomain_patch16_224](https://github.com/addf400/files/releases/download/beit3/beit3_base_indomain_patch16_224.pth) | 480x480 | - | 78.46 | - | 228M | [link](https://github.com/addf400/files/releases/download/beit3/beit3_base_indomain_patch16_480_vqa.pth) | +| [beit3_large_patch16_224](https://github.com/addf400/files/releases/download/beit3/beit3_large_patch16_224.pth) | 480x480 | - | 81.85 | - | 683M | [link](https://github.com/addf400/files/releases/download/beit3/beit3_large_patch16_480_vqa.pth) | +| [beit3_large_indomain_patch16_224](https://github.com/addf400/files/releases/download/beit3/beit3_large_indomain_patch16_224.pth) | 480x480 | - | 82.53 | - | 683M | [link](https://github.com/addf400/files/releases/download/beit3/beit3_large_indomain_patch16_480_vqa.pth) | +| [beit3_large_indomain_patch16_224](https://github.com/addf400/files/releases/download/beit3/beit3_large_indomain_patch16_224.pth) | 768x768 | VGQA | 82.97 | 83.03 | 684M | [link](https://github.com/addf400/files/releases/download/beit3/beit3_large_indomain_patch16_768_vgqaaug_vqa.pth) | + + +## Fine-tuning on NLVR2 (Visual Reasoning) + +The detailed instructions can be found at [`get_started_for_nlvr2.md`](get_started/get_started_for_nlvr2.md). + +| initialized checkpoint | resolution | dev | test-P | #params | weight | +|:----------------------------------------|:----------:|:-----:|:-----:|:-------:|-------------------| +| [beit3_base_patch16_224](https://github.com/addf400/files/releases/download/beit3/beit3_base_patch16_224.pth) | 224x224 | 83.6 | 84.4 | 226M | [link](https://github.com/addf400/files/releases/download/beit3/beit3_base_patch16_224_nlvr2.pth) | +| [beit3_base_indomain_patch16_224](https://github.com/addf400/files/releases/download/beit3/beit3_base_indomain_patch16_224.pth) | 224x224 | 84.6 | 85.3 | 226M | [link](https://github.com/addf400/files/releases/download/beit3/beit3_base_indomain_patch16_224_nlvr2.pth) | +| [beit3_large_patch16_224](https://github.com/addf400/files/releases/download/beit3/beit3_large_patch16_224.pth) | 224x224 | 88.5 | 89.4 | 681M | [link](https://github.com/addf400/files/releases/download/beit3/beit3_large_patch16_224_nlvr2.pth) | +| [beit3_large_indomain_patch16_224](https://github.com/addf400/files/releases/download/beit3/beit3_large_indomain_patch16_224.pth) | 224x224 | 89.2 | 90.0 | 681M | [link](https://github.com/addf400/files/releases/download/beit3/beit3_large_indomain_patch16_224_nlvr2.pth) | + + +## Fine-tuning on COCO Captioning and NoCaps (Image Captioning) + +The detailed instructions can be found at [`get_started_for_image_captioning.md`](get_started/get_started_for_captioning.md). + +### COCO Captioning + +| initialized checkpoint | resolution | test CIDEr | #params | weight | +|:----------------------------------------|:----------:|:-----:|:-------:|-------------------| +| [beit3_base_patch16_224](https://github.com/addf400/files/releases/download/beit3/beit3_base_patch16_224.pth) | 480x480 | 133.6 | 271M | [link](https://github.com/addf400/files/releases/download/beit3/beit3_base_patch16_480_coco_captioning.pth) | +| [beit3_base_indomain_patch16_224](https://github.com/addf400/files/releases/download/beit3/beit3_base_indomain_patch16_224.pth) | 480x480 | 135.0 | 271M | [link](https://github.com/addf400/files/releases/download/beit3/beit3_base_indomain_patch16_480_coco_captioning.pth) | +| [beit3_large_patch16_224](https://github.com/addf400/files/releases/download/beit3/beit3_large_patch16_224.pth) | 480x480 | 143.2 | 739M | [link](https://github.com/addf400/files/releases/download/beit3/beit3_large_patch16_480_coco_captioning.pth) | + +### NoCaps + +| initialized checkpoint | resolution | val CIDEr | #params | weight | +|:----------------------------------------|:----------:|:-----:|:-------:|-------------------| +| [beit3_base_patch16_224](https://github.com/addf400/files/releases/download/beit3/beit3_base_patch16_224.pth) | 480x480 | 104.4 | 271M | [link](https://github.com/addf400/files/releases/download/beit3/beit3_base_patch16_480_nocaps.pth) | +| [beit3_base_indomain_patch16_224](https://github.com/addf400/files/releases/download/beit3/beit3_base_indomain_patch16_224.pth) | 480x480 | 105.6 | 271M | [link](https://github.com/addf400/files/releases/download/beit3/beit3_base_indomain_patch16_480_nocaps.pth) | +| [beit3_large_patch16_224](https://github.com/addf400/files/releases/download/beit3/beit3_large_patch16_224.pth) | 480x480 | 120.2 | 739M | [link](https://github.com/addf400/files/releases/download/beit3/beit3_large_patch16_480_nocaps.pth) | + + +## Fine-tuning on COCO and Flickr30k Retrieval (Image-Text Retrieval) + +The detailed instructions can be found at [`get_started_for_retrieval.md`](get_started/get_started_for_retrieval.md). + +### COCO Retrieval + +| initialized checkpoint | resolution | IR@1 | TR@1 | #params | weight | +|:----------------------------------------|:----------:|:-----:|:-----:|:-------:|-------------------| +| [beit3_base_itc_patch16_224](https://github.com/addf400/files/releases/download/beit3/beit3_base_itc_patch16_224.pth) | 384x384 | 61.4 | 79.1 | 222M | [link](https://github.com/addf400/files/releases/download/beit3/beit3_base_patch16_384_coco_retrieval.pth) | +| [beit3_large_itc_patch16_224](https://github.com/addf400/files/releases/download/beit3/beit3_large_itc_patch16_224.pth) | 384x384 | 63.4 | 82.1 | 675M | [link](https://github.com/addf400/files/releases/download/beit3/beit3_large_patch16_384_coco_retrieval.pth) | + +### Flickr30k Retrieval + +| initialized checkpoint | resolution | IR@1 | TR@1 | #params | weight | +|:----------------------------------------|:----------:|:-----:|:-----:|:-------:|-------------------| +| [beit3_base_itc_patch16_224](https://github.com/addf400/files/releases/download/beit3/beit3_base_itc_patch16_224.pth) | 384x384 | 86.2 | 96.3 | 222M | [link](https://github.com/addf400/files/releases/download/beit3/beit3_base_patch16_384_f30k_retrieval.pth) | +| [beit3_large_itc_patch16_224](https://github.com/addf400/files/releases/download/beit3/beit3_large_itc_patch16_224.pth) | 384x384 | 88.1 | 97.2 | 675M | [link](https://github.com/addf400/files/releases/download/beit3/beit3_large_patch16_384_f30k_retrieval.pth) | + + +## Citation + +If you find this repository useful, please consider citing our work: +``` +@inproceedings{beit3, +title={Image as a foreign language: {BEiT} pretraining for vision and vision-language tasks}, +author={Wenhui Wang and Hangbo Bao and Li Dong and Johan Bjorck and Zhiliang Peng and Qiang Liu and Kriti Aggarwal and Owais Khan Mohammed and Saksham Singhal and Subhojit Som and Furu Wei}, +booktitle={Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition}, +year={2023} +} + +@article{beitv2, +title={{BEiT v2}: Masked Image Modeling with Vector-Quantized Visual Tokenizers}, +author={Zhiliang Peng and Li Dong and Hangbo Bao and Qixiang Ye and Furu Wei}, +year={2022}, +eprint={2208.06366}, +archivePrefix={arXiv}, +primaryClass={cs.CV} +} + +@inproceedings{beit, +title={{BEiT}: {BERT} Pre-Training of Image Transformers}, +author={Hangbo Bao and Li Dong and Songhao Piao and Furu Wei}, +booktitle={International Conference on Learning Representations}, +year={2022}, +url={https://openreview.net/forum?id=p-BhZSz59o4} +} +``` + + +## Acknowledgement + +This repository is built using the [BEiT](https://github.com/microsoft/unilm/tree/master/beit), the [BEiTv2](https://github.com/microsoft/unilm/tree/master/beit2), the [CLIP](https://github.com/openai/CLIP), the [open_clip](https://github.com/mlfoundations/open_clip), the [Oscar](https://github.com/microsoft/Oscar), the [DeiT](https://github.com/facebookresearch/deit), the [Dino](https://github.com/facebookresearch/dino) repository and the [timm](https://github.com/rwightman/pytorch-image-models) library. + + +## License +This project is licensed under the license found in the LICENSE file in the root directory of this source tree. + +[Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct) + +### Contact Information + +For help or issues using BEiT-3 models, please submit a GitHub issue. diff --git a/py/evf_sam/model/unilm/beit3/datasets.py b/py/evf_sam/model/unilm/beit3/datasets.py new file mode 100644 index 0000000..9f6dab8 --- /dev/null +++ b/py/evf_sam/model/unilm/beit3/datasets.py @@ -0,0 +1,847 @@ +# -------------------------------------------------------- +# Image as a Foreign Language: BEiT Pretraining for Vision and Vision-Language Tasks (https://arxiv.org/abs/2208.10442) +# Github source: https://github.com/microsoft/unilm/tree/master/beit3 +# Copyright (c) 2023 Microsoft +# Licensed under The MIT License [see LICENSE for details] +# --------------------------------------------------------' + +import os +import json +import random +import torch +import glob +from collections import defaultdict, Counter +from torchvision import transforms +from torchvision.datasets.folder import default_loader +from timm.data.constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, IMAGENET_INCEPTION_MEAN, IMAGENET_INCEPTION_STD +from timm.data.transforms import RandomResizedCropAndInterpolation +from timm.data import create_transform + +import utils +from glossary import normalize_word +from randaug import RandomAugment + + +class BaseDataset(torch.utils.data.Dataset): + def __init__( + self, data_path, split, transform, + tokenizer, num_max_bpe_tokens, task=None, + ): + index_files = self.get_index_files(split, task=task) + self.tokenizer = tokenizer + self.num_max_bpe_tokens = num_max_bpe_tokens + self.data_path = data_path + items = [] + self.index_files = index_files + + offset = 0 + for _index_file in index_files: + index_file = os.path.join(data_path, _index_file) + with open(index_file, mode="r", encoding="utf-8") as reader: + for line in reader: + data = json.loads(line) + items.append(data) + print("Load %d image-text pairs from %s. " % (len(items) - offset, index_file)) + offset = len(items) + self.items = items + self.bos_token_id = tokenizer.bos_token_id + self.eos_token_id = tokenizer.eos_token_id + self.pad_token_id = tokenizer.pad_token_id + self.loader = default_loader + self.transform = transform + self.split = split + + @staticmethod + def get_index_files(split): + raise NotImplementedError() + + def _get_image(self, image_path: str): + image_path = os.path.join(self.data_path, image_path) + image = self.loader(image_path) + return self.transform(image) + + def _get_text_segment(self, text_segment, max_len=None): + if isinstance(text_segment, str): + tokens = self.tokenizer.tokenize(text_segment) + else: + tokens = text_segment[:] + if len(tokens) == 0: + raise RuntimeError("The text segment should contains at least one tokens!") + if max_len is None: + max_len = self.num_max_bpe_tokens + + if len(tokens) > max_len - 2: + tokens = tokens[:max_len - 2] + + tokens = [self.bos_token_id] + tokens[:] + [self.eos_token_id] + num_tokens = len(tokens) + padding_mask = [0] * num_tokens + [1] * (max_len - num_tokens) + return tokens + [self.pad_token_id] * (max_len - num_tokens), padding_mask, num_tokens + + def _get_image_text_example(self, index: int, data: dict): + item = self.items[index] + img_path = item["image_path"] + img = self._get_image(img_path) + data["image"] = img + + text_segment = item["text_segment"] + language_tokens, padding_mask, _ = self._get_text_segment(text_segment) + data["language_tokens"] = language_tokens + data["padding_mask"] = padding_mask + + def __getitem__(self, index: int): + data = dict() + self._get_image_text_example(index, data) + return data + + def __len__(self) -> int: + return len(self.items) + + def __repr__(self) -> str: + head = "Dataset " + self.__class__.__name__ + body = '{' + "\n Number of items: %s," % self.__len__() + body += "\n data root = %s," % self.data_path + body += "\n split = %s," % self.split + body += "\n dataset index files = %s" % str(self.index_files) + body += "\n num max bpe tokens = %s" % self.num_max_bpe_tokens + body += "\n transforms = [" + for t in self.transform.transforms: + body += "\n %s" % str(t) + body += "\n ]" + body += "\n}" + + return head + body + + +def _write_data_into_jsonl(items, jsonl_file): + with open(jsonl_file, mode="w", encoding="utf-8") as writer: + for data in items: + writer.write(json.dumps(data, indent=None)) + writer.write('\n') + print("Write %s with %d items !" % (jsonl_file, len(items))) + + +def _make_retrieval_coco_karpathy_dataset_index( + data_path, + tokenizer, + split=("train", "restval"), + split_name="train", +): + coco_karpathy_split_json_file = os.path.join(data_path, "dataset_coco.json") + items = [] + image_counter = set() + print("read %s" % coco_karpathy_split_json_file) + with open(coco_karpathy_split_json_file, mode="r", encoding="utf-8") as reader: + data = json.loads(reader.read()) + for item in data["images"]: + if item["split"] in split: + image_path = os.path.join(item["filepath"], item["filename"]) + for sent in item["sentences"]: + tokens = tokenizer.tokenize(sent["raw"]) + token_ids = tokenizer.convert_tokens_to_ids(tokens) + items.append({ + "image_path": image_path, + "text_segment": token_ids, + "image_id": len(image_counter), + }) + if image_path not in image_counter: + image_counter.add(image_path) + print("Find %d images and %d image-text pairs for karpathy dataset %s split !" % \ + (len(image_counter), len(items), split_name)) + index_file = os.path.join(data_path, "coco_retrieval.%s.jsonl" % split_name) + _write_data_into_jsonl(items, index_file) + pass + + +def _make_captioning_coco_karpathy_dataset_index( + data_path, + tokenizer, + split=("train", "restval"), + split_name="train", +): + coco_karpathy_split_json_file = os.path.join(data_path, "dataset_coco.json") + items = [] + image_counter = set() + print("read %s" % coco_karpathy_split_json_file) + with open(coco_karpathy_split_json_file, mode="r", encoding="utf-8") as reader: + data = json.loads(reader.read()) + for item in data["images"]: + if item["split"] in split: + image_path = os.path.join(item["filepath"], item["filename"]) + if item["split"] in ["train", "restval"]: + for sent in item["sentences"]: + tokens = tokenizer.tokenize(sent["raw"]) + token_ids = tokenizer.convert_tokens_to_ids(tokens) + items.append({ + "image_path": image_path, + "text_segment": token_ids, + "image_id": item["cocoid"], + }) + else: + items.append({ + "image_path": image_path, + "text_segment": None, + "image_id": item["cocoid"], + }) + if image_path not in image_counter: + image_counter.add(image_path) + print("Find %d images and %d image-text pairs for karpathy dataset %s split !" % \ + (len(image_counter), len(items), split_name)) + index_file = os.path.join(data_path, "coco_captioning.%s.jsonl" % split_name) + _write_data_into_jsonl(items, index_file) + pass + + +def _make_nocaps_dataset_index( + data_path, + split="val", +): + if split == "val": + json_file = "nocaps_val_4500_captions.json" + elif split == "test": + json_file = "nocaps_test_image_info.json" + nocaps_split_json_file = os.path.join(data_path, json_file) + items = [] + image_counter = set() + print("read %s" % nocaps_split_json_file) + with open(nocaps_split_json_file, mode="r", encoding="utf-8") as reader: + data = json.loads(reader.read()) + for item in data["images"]: + image_path = os.path.join(split, item["file_name"]) + items.append({ + "image_path": image_path, + "text_segment": None, + "image_id": item["id"], + }) + + if image_path not in image_counter: + image_counter.add(image_path) + + print("Find %d images and %d image-text pairs for nocaps dataset %s split !" % \ + (len(image_counter), len(items), split)) + index_file = os.path.join(data_path, "nocaps.%s.jsonl" % split) + _write_data_into_jsonl(items, index_file) + + +class NLVR2Dataset(BaseDataset): + @staticmethod + def get_index_files(split, task=None): + if split == "train": + return ("nlvr2.train.index.jsonl", ) + elif split == "val": + return ("nlvr2.dev.index.jsonl", ) + elif split == "test": + return ("nlvr2.test-P.index.jsonl", ) + else: + raise RuntimeError("split %s is not found!" % split) + + def __getitem__(self, index: int): + data = super().__getitem__(index) + item = self.items[index] + img_path = item["image2_path"] + img = self._get_image(img_path) + data["image2"] = img + data["label"] = self.items[index]["label"] + return data + + @staticmethod + def __preprocess_json(preifx, json_file, tokenizer, index_file): + items = [] + with open(json_file, mode="r", encoding="utf-8") as reader: + for line in reader: + data = json.loads(line) + path = os.path.join(preifx, str(data["directory"])) if "directory" in data else preifx + path = os.path.join(path, "-".join(data["identifier"].split("-")[:-1])) + tokens = tokenizer.tokenize(data["sentence"]) + token_ids = tokenizer.convert_tokens_to_ids(tokens) + items.append({ + "image_path": path + "-img0.png", + "image2_path": path + "-img1.png", + "text_segment": token_ids, + "label": 1 if data["label"] == "True" else 0, + "identifier": data["identifier"], + }) + _write_data_into_jsonl(items, index_file) + + @classmethod + def make_dataset_index(cls, data_path, tokenizer, nlvr_repo_path): + cls.__preprocess_json( + preifx="images/train", json_file=os.path.join(nlvr_repo_path, "nlvr2/data/train.json"), + tokenizer=tokenizer, index_file=os.path.join(data_path, cls.get_index_files("train")[0]), + ) + cls.__preprocess_json( + preifx="dev", json_file=os.path.join(nlvr_repo_path, "nlvr2/data/dev.json"), + tokenizer=tokenizer, index_file=os.path.join(data_path, cls.get_index_files("val")[0]), + ) + cls.__preprocess_json( + preifx="test1", json_file=os.path.join(nlvr_repo_path, "nlvr2/data/test1.json"), + tokenizer=tokenizer, index_file=os.path.join(data_path, cls.get_index_files("test")[0]), + ) + + +class ImageNetDataset(BaseDataset): + @staticmethod + def get_index_files(split, task=None): + if split == "train": + return ("imagenet.train.index.jsonl", ) + elif split == "val": + return ("imagenet.val.index.jsonl", ) + elif split == "test": + return ("imagenet.val.index.jsonl", ) + else: + raise RuntimeError("split %s is not found!" % split) + + def __getitem__(self, index: int): + data = dict() + item = self.items[index] + img_path = item["image_path"] + img = self._get_image(img_path) + data["image"] = img + data["label"] = item["label"] + return data + + @staticmethod + def _find_classes(dir): + """ + Finds the class folders in a dataset. + Args: + dir (string): Root directory path. + Returns: + tuple: (classes, class_to_idx) where classes are relative to (dir), and class_to_idx is a dictionary. + Ensures: + No class is a subdirectory of another. + """ + classes = [d.name for d in os.scandir(dir) if d.is_dir()] + classes.sort() + class_to_idx = {cls_name: i for i, cls_name in enumerate(classes)} + return classes, class_to_idx + + @staticmethod + def _make_imagenet_index(data_path, index_path, data_path_prefix, class_to_idx, split): + items = [] + index_file = os.path.join(index_path, f"imagenet.{split}.index.jsonl") + for target_class in sorted(class_to_idx.keys()): + class_index = class_to_idx[target_class] + target_dir = os.path.join(data_path, target_class) + if not os.path.isdir(target_dir): + continue + for root, _, fnames in sorted(os.walk(target_dir, followlinks=True)): + for fname in sorted(fnames): + path = os.path.join(root, fname) + path = path.replace(data_path_prefix, "") + items.append({ + "image_path": path, + "label": class_index, + }) + + _write_data_into_jsonl(items, index_file) + + @classmethod + def make_dataset_index(cls, train_data_path, val_data_path, index_path): + data_path_prefix = train_data_path[:[x[0]==x[1] for x in zip(train_data_path, val_data_path)].index(0)] + classes, class_to_idx = cls._find_classes(train_data_path) + cls._make_imagenet_index( + data_path=train_data_path, index_path=index_path, data_path_prefix=data_path_prefix, + class_to_idx=class_to_idx, split="train", + ) + cls._make_imagenet_index( + data_path=val_data_path, index_path=index_path, data_path_prefix=data_path_prefix, + class_to_idx=class_to_idx, split="val", + ) + + +class VQAv2Dataset(BaseDataset): + def __init__(self, data_path, **kwargs): + super().__init__(data_path=data_path, **kwargs) + ans2label_file = os.path.join(data_path, "answer2label.txt") + ans2label = {} + label2ans = [] + with open(ans2label_file, mode="r", encoding="utf-8") as reader: + for i, line in enumerate(reader): + data = json.loads(line) + ans = data["answer"] + label = data["label"] + label = int(label) + assert label == i + ans2label[ans] = i + label2ans.append(ans) + + self.ans2label = ans2label + self.label2ans = label2ans + + @staticmethod + def get_index_files(split, task=None): + if split == "train": + return ("vqa.train.jsonl", "vqa.trainable_val.jsonl") + elif split == "val": + return ("vqa.rest_val.jsonl", ) + elif split == "test": + return ("vqa.test.jsonl", ) + elif split == "test-dev": + return ("vqa.test-dev.jsonl", ) + else: + raise RuntimeError("split %s is not found!" % split) + + def __getitem__(self, index: int): + data = super().__getitem__(index) + if "labels" in self.items[index] and len(self.items[index]["labels"]) > 0: + labels = [0.] * len(self.label2ans) + for l, s in zip(self.items[index]["labels"], self.items[index]["scores"]): + labels[l] = s + data["labels"] = torch.FloatTensor(labels) + else: + data["qid"] = self.items[index]["qid"] + return data + + @staticmethod + def get_score(occurences): + if occurences == 0: + return 0.0 + elif occurences == 1: + return 0.3 + elif occurences == 2: + return 0.6 + elif occurences == 3: + return 0.9 + else: + return 1.0 + + @classmethod + def make_dataset_index(cls, data_path, tokenizer, annotation_data_path): + with open(os.path.join(annotation_data_path, "v2_OpenEnded_mscoco_train2014_questions.json"), "r") as fp: + questions_train2014 = json.load(fp)["questions"] + with open(os.path.join(annotation_data_path, "v2_OpenEnded_mscoco_val2014_questions.json"), "r") as fp: + questions_val2014 = json.load(fp)["questions"] + with open(os.path.join(annotation_data_path, "v2_OpenEnded_mscoco_test2015_questions.json"), "r") as fp: + questions_test2015 = json.load(fp)["questions"] + with open(os.path.join(annotation_data_path, "v2_OpenEnded_mscoco_test-dev2015_questions.json"), "r") as fp: + questions_test_dev2015 = json.load(fp)["questions"] + + with open(os.path.join(annotation_data_path, "v2_mscoco_train2014_annotations.json"), "r") as fp: + annotations_train2014 = json.load(fp)["annotations"] + with open(os.path.join(annotation_data_path, "v2_mscoco_val2014_annotations.json"), "r") as fp: + annotations_val2014 = json.load(fp)["annotations"] + + annotations = dict() + + for split, questions in zip( + ["train", "val", "test", "test-dev"], + [questions_train2014, questions_val2014, questions_test2015, questions_test_dev2015], + ): + _annot = defaultdict(dict) + for q in questions: + question_text = q["question"] + tokens = tokenizer.tokenize(question_text) + token_ids = tokenizer.convert_tokens_to_ids(tokens) + + assert q["question_id"] not in _annot[q["image_id"]] + _annot[q["image_id"]][q["question_id"]] = { + "question": question_text, + "token_ids": token_ids, + } + + annotations[split] = _annot + + all_major_answers = list() + + for split, annots in zip( + ["train", "val"], [annotations_train2014, annotations_val2014], + ): + # _annot = annotations[split] + for q in annots: + all_major_answers.append(q["multiple_choice_answer"]) + + all_major_answers = [normalize_word(word) for word in all_major_answers] + counter = {k: v for k, v in Counter(all_major_answers).items() if v >= 9} + ans2label = {k: i for i, k in enumerate(counter.keys())} + label2ans = list(counter.keys()) + + for split, annots in zip( + ["train", "val"], [annotations_train2014, annotations_val2014], + ): + _annot = annotations[split] + for q in annots: + answers = q["answers"] + answer_count = {} + for answer in answers: + answer_ = answer["answer"] + answer_count[answer_] = answer_count.get(answer_, 0) + 1 + + labels = [] + scores = [] + for answer in answer_count: + if answer not in ans2label: + continue + labels.append(ans2label[answer]) + score = cls.get_score(answer_count[answer]) + scores.append(score) + + assert "labels" not in _annot[q["image_id"]][q["question_id"]] + assert "question" in _annot[q["image_id"]][q["question_id"]] + _annot[q["image_id"]][q["question_id"]]["labels"] = labels + _annot[q["image_id"]][q["question_id"]]["scores"] = scores + + for split in ["train", "val"]: + filtered_annot = dict() + for ik, iv in annotations[split].items(): + new_q = dict() + for qk, qv in iv.items(): + if len(qv["labels"]) != 0: + new_q[qk] = qv + if len(new_q) != 0: + filtered_annot[ik] = new_q + annotations[split] = filtered_annot + + split2items = {} + for split in ["train", "val", "test", "test-dev"]: + annot = annotations[split] + split_name = { + "train": "train2014", + "val": "val2014", + "test": "test2015", + "test-dev": "test2015", + }[split] + paths = list(glob.glob(f"{data_path}/{split_name}/*.jpg")) + random.shuffle(paths) + annot_paths = [path for path in paths \ + if int(path.split("/")[-1].split("_")[-1][:-4]) in annot] + + if len(paths) == len(annot_paths): + print("all images have caption annotations") + else: + print("not all images have caption annotations") + print(len(paths), len(annot_paths), len(annot)) + + items = [] + for path in annot_paths: + iid = int(path.split("/")[-1].split("_")[-1][:-4]) + _annot = annotations[split][iid] + for qid in _annot: + q = _annot[qid] + if split in ["train", "val"]: + labels = q["labels"] + scores = q["scores"] + else: + labels, scores = [], [] + + items.append({ + "image_path": os.path.join(split_name, path.split('/')[-1]), + "text_segment": q["token_ids"], + "labels": labels, + "scores": scores, + "qid": qid, + }) + split2items[split] = items + + _write_data_into_jsonl(items=items, jsonl_file=os.path.join(data_path, "vqa.%s.jsonl" % split)) + + # Following ViLT, we use 1000 images of the original val set as the final val set + val_image2items = defaultdict(list) + for item in split2items["val"]: + val_image2items[item["image_path"]].append(item) + + print("Contains %d image and %d pairs for val set!" % (len(val_image2items), len(split2items["val"]))) + + val_images = list(val_image2items.keys()) + random.shuffle(val_images) + trainable_val = [] + rest_val = [] + for i, image_id in enumerate(val_images): + if i < 1000: + rest_val += val_image2items[image_id] + else: + trainable_val += val_image2items[image_id] + + _write_data_into_jsonl(items=trainable_val, jsonl_file=os.path.join(data_path, "vqa.trainable_val.jsonl")) + _write_data_into_jsonl(items=rest_val, jsonl_file=os.path.join(data_path, "vqa.rest_val.jsonl")) + + with open(os.path.join(data_path, "answer2label.txt"), mode="w", encoding="utf-8") as writer: + for ans in ans2label: + to_json = { + "answer": ans, + "label": ans2label[ans] + } + writer.write("%s\n" % json.dumps(to_json)) + + +class RetrievalDataset(BaseDataset): + @staticmethod + def get_index_files(split, task=None): + if split == "train": + return (f"{task}.train.jsonl", ) + elif split == "val": + return (f"{task}.val.jsonl", ) + elif split == "test": + return (f"{task}.test.jsonl", ) + else: + raise RuntimeError("split %s is not found!" % split) + + def __getitem__(self, index: int): + data = super().__getitem__(index) + data["image_id"] = self.items[index]["image_id"] + return data + + @staticmethod + def make_flickr30k_dataset_index(data_path, tokenizer, karpathy_path): + + with open(os.path.join(karpathy_path, "dataset_flickr30k.json"), "r") as reader: + captions = json.loads(reader.read()) + + captions = captions["images"] + split2items = defaultdict(list) + split2images = defaultdict(set) + + for each_item in captions: + image_path = os.path.join("flickr30k-images", each_item["filename"]) + split = each_item["split"] + + for text_segment in each_item["sentences"]: + tokens = tokenizer.tokenize(text_segment["raw"]) + token_ids = tokenizer.convert_tokens_to_ids(tokens) + + split2items[split].append({ + "image_path": image_path, + "text_segment": token_ids, + "image_id": len(split2images[split]), + }) + + assert each_item["filename"] not in split2images[split] + split2images[split].add(each_item["filename"]) + + for split in split2items: + print("%d images and %d image-text pairs!" % (len(split2images[split]), len(split2items[split]))) + _write_data_into_jsonl(split2items[split], os.path.join(data_path, "flickr30k.%s.jsonl" % split)) + + @staticmethod + def make_coco_dataset_index(data_path, tokenizer): + _make_retrieval_coco_karpathy_dataset_index(data_path, tokenizer, split=("train", "restval"), split_name="train") + _make_retrieval_coco_karpathy_dataset_index(data_path, tokenizer, split=("val", ), split_name="val") + _make_retrieval_coco_karpathy_dataset_index(data_path, tokenizer, split=("test", ), split_name="test") + + +class CaptioningDataset(BaseDataset): + + def __init__(self, data_path, split, transform, + tokenizer, num_max_bpe_tokens, task, mask_prob): + super().__init__( + data_path=data_path, split=split, + transform=transform, tokenizer=tokenizer, + num_max_bpe_tokens=num_max_bpe_tokens, task=task, + ) + self.mask_token_id = tokenizer.mask_token_id + self.language_vocab_size = tokenizer.vocab_size + self.mask_prob = mask_prob + + @staticmethod + def get_index_files(split, task=None): + if split == "train": + return ("coco_captioning.train.jsonl", ) + elif split == "val": + return (f"{task}.val.jsonl", ) + elif split == "test": + return (f"{task}.test.jsonl", ) + else: + raise RuntimeError("split %s is not found!" % split) + + def _get_mask_token(self, token): + p = random.random() + if p < 0.8: + return self.mask_token_id + elif p < 0.9: + return token + else: + return random.randint(3, self.language_vocab_size - 1) + + def _masking_on_text_tokens(self, tokens, num_tokens, mask_prob): + bool_masked_pos = [0] * len(tokens) + to_mask = min(int(num_tokens * mask_prob + 0.5), num_tokens - 1) + to_mask = max(to_mask, 1) + num_masked_tokens = 0 + while num_masked_tokens < to_mask: + i = random.randint(1, num_tokens - 1) + if bool_masked_pos[i] == 0: + bool_masked_pos[i] = 1 + tokens[i] = self._get_mask_token(tokens[i]) + num_masked_tokens += 1 + + return tokens, bool_masked_pos + + def __getitem__(self, index: int): + data = dict() + item = self.items[index] + img_path = item["image_path"] + img = self._get_image(img_path) + data["image"] = img + data["image_id"] = item["image_id"] + + text_segment = item["text_segment"] + if text_segment is not None: + language_tokens, padding_mask, num_tokens = self._get_text_segment(text_segment) + masked_tokens = language_tokens[:] + masked_tokens, language_masked_pos = \ + self._masking_on_text_tokens(masked_tokens, num_tokens, self.mask_prob) + data["language_tokens"] = language_tokens + data["masked_tokens"] = masked_tokens + data["language_masked_pos"] = language_masked_pos + data["padding_mask"] = padding_mask + return data + + @staticmethod + def make_coco_captioning_dataset_index(data_path, tokenizer): + _make_captioning_coco_karpathy_dataset_index(data_path, tokenizer, split=("train", "restval"), split_name="train") + _make_captioning_coco_karpathy_dataset_index(data_path, tokenizer, split=("val", ), split_name="val") + _make_captioning_coco_karpathy_dataset_index(data_path, tokenizer, split=("test", ), split_name="test") + + @staticmethod + def make_nocaps_captioning_dataset_index(data_path): + _make_nocaps_dataset_index(data_path, split="val") + _make_nocaps_dataset_index(data_path, split="test") + + +task2dataset = { + "nlvr2": NLVR2Dataset, + "vqav2": VQAv2Dataset, + "flickr30k": RetrievalDataset, + "coco_retrieval": RetrievalDataset, + "coco_captioning": CaptioningDataset, + "nocaps": CaptioningDataset, + "imagenet": ImageNetDataset, +} + + +def create_dataloader(dataset, is_train, batch_size, num_workers, pin_mem, dist_eval=False): + if is_train or dist_eval: + num_tasks = utils.get_world_size() + global_rank = utils.get_rank() + + if not is_train and dist_eval and len(dataset) % num_tasks != 0: + print('Warning: Enabling distributed evaluation with an eval dataset not divisible by process number. ' + 'This will slightly alter validation results as extra duplicate entries are added to achieve ' + 'equal num of samples per-process.') + + sampler = torch.utils.data.DistributedSampler( + dataset, num_replicas=num_tasks, rank=global_rank, shuffle=is_train + ) + else: + sampler = torch.utils.data.SequentialSampler(dataset) + + return torch.utils.data.DataLoader( + dataset, sampler=sampler, + batch_size=batch_size, + num_workers=num_workers, + pin_memory=pin_mem, + drop_last=is_train, + collate_fn=utils.merge_batch_tensors_by_dict_key, + ) + + +def build_transform(is_train, args): + if args.task in ["imagenet"]: + return build_imagenet_transform(is_train, args) + + if is_train: + t = [ + RandomResizedCropAndInterpolation(args.input_size, scale=(0.5, 1.0), interpolation=args.train_interpolation), + transforms.RandomHorizontalFlip(), + ] + if args.randaug: + t.append( + RandomAugment( + 2, 7, isPIL=True, + augs=[ + 'Identity','AutoContrast','Equalize','Brightness','Sharpness', + 'ShearX', 'ShearY', 'TranslateX', 'TranslateY', 'Rotate', + ])) + t += [ + transforms.ToTensor(), + transforms.Normalize(mean=IMAGENET_INCEPTION_MEAN, std=IMAGENET_INCEPTION_STD), + ] + t = transforms.Compose(t) + else: + t = transforms.Compose([ + transforms.Resize((args.input_size, args.input_size), interpolation=3), + transforms.ToTensor(), + transforms.Normalize(mean=IMAGENET_INCEPTION_MEAN, std=IMAGENET_INCEPTION_STD) + ]) + + return t + + +def build_imagenet_transform(is_train, args): + resize_im = args.input_size > 32 + if is_train: + # this should always dispatch to transforms_imagenet_train + transform = create_transform( + input_size=args.input_size, + is_training=True, + color_jitter=args.color_jitter, + auto_augment=args.aa, + interpolation=args.train_interpolation, + re_prob=args.reprob, + re_mode=args.remode, + re_count=args.recount, + mean=IMAGENET_DEFAULT_MEAN, + std=IMAGENET_DEFAULT_STD, + ) + if not resize_im: + # replace RandomResizedCropAndInterpolation with + # RandomCrop + transform.transforms[0] = transforms.RandomCrop( + args.input_size, padding=4) + return transform + + t = [] + if resize_im: + if args.crop_pct is None: + args.crop_pct = 1.0 + size = int(args.input_size / args.crop_pct) + t.append( + transforms.Resize(size, interpolation=3), # to maintain same ratio w.r.t. 224 images + ) + t.append(transforms.CenterCrop(args.input_size)) + + t.append(transforms.ToTensor()) + t.append(transforms.Normalize(mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD)) + return transforms.Compose(t) + + +def get_sentencepiece_model_for_beit3(args): + from transformers import XLMRobertaTokenizer + return XLMRobertaTokenizer(args.sentencepiece_model) + + +def create_dataset_by_split(args, split, is_train=True): + transform = build_transform(is_train=is_train, args=args) + dataset_class = task2dataset[args.task] + tokenizer = get_sentencepiece_model_for_beit3(args) + + opt_kwargs = {} + if args.task in ["coco_captioning", "nocaps"]: + opt_kwargs["mask_prob"] = args.captioning_mask_prob + + dataset = dataset_class( + data_path=args.data_path, split=split, + transform=transform, tokenizer=tokenizer, + num_max_bpe_tokens=args.num_max_bpe_tokens, + task=args.task, **opt_kwargs, + ) + if is_train: + batch_size = args.batch_size + elif hasattr(args, "eval_batch_size") and args.eval_batch_size is not None: + batch_size = args.eval_batch_size + else: + batch_size = int(args.batch_size * 1.5) + + return create_dataloader( + dataset, is_train=is_train, batch_size=batch_size, + num_workers=args.num_workers, pin_mem=args.pin_mem, dist_eval=args.dist_eval, + ) + + +def create_downstream_dataset(args, is_eval=False): + if is_eval: + return create_dataset_by_split(args, split="test", is_train=False) + else: + return \ + create_dataset_by_split(args, split="train", is_train=True), \ + create_dataset_by_split(args, split="val", is_train=True) diff --git a/py/evf_sam/model/unilm/beit3/engine_for_finetuning.py b/py/evf_sam/model/unilm/beit3/engine_for_finetuning.py new file mode 100644 index 0000000..9be308c --- /dev/null +++ b/py/evf_sam/model/unilm/beit3/engine_for_finetuning.py @@ -0,0 +1,598 @@ +# -------------------------------------------------------- +# Image as a Foreign Language: BEiT Pretraining for Vision and Vision-Language Tasks (https://arxiv.org/abs/2208.10442) +# Github source: https://github.com/microsoft/unilm/tree/master/beit3 +# Copyright (c) 2023 Microsoft +# Licensed under The MIT License [see LICENSE for details] +# --------------------------------------------------------' + +import math +import sys +import json +from typing import Iterable, Optional + +import torch +import torch.nn as nn +import torch.nn.functional as F + +from timm.utils import ModelEma +from timm.utils import accuracy, ModelEma +from timm.loss import LabelSmoothingCrossEntropy, SoftTargetCrossEntropy +from datasets import get_sentencepiece_model_for_beit3 + +import utils + + +class TaskHandler(object): + def __init__(self) -> None: + self.metric_logger = None + self.split = None + + def train_batch(self, model, **kwargs): + raise NotImplementedError() + + def eval_batch(self, model, **kwargs): + raise NotImplementedError() + + def before_eval(self, metric_logger, data_loader, **kwargs): + self.metric_logger = metric_logger + self.split = data_loader.dataset.split + + def after_eval(self, **kwargs): + raise NotImplementedError() + + +class NLVR2Handler(TaskHandler): + def __init__(self) -> None: + super().__init__() + self.criterion = torch.nn.CrossEntropyLoss() + + def train_batch(self, model, image, image2, language_tokens, padding_mask, label): + logits = model( + image_a=image, image_b=image2, + text_description=language_tokens, + padding_mask=padding_mask) + acc = (logits.max(-1)[-1] == label).float().mean() + return { + "loss": self.criterion(input=logits, target=label), + "acc": acc, + } + + def eval_batch(self, model, image, image2, language_tokens, padding_mask, label): + logits = model( + image_a=image, image_b=image2, + text_description=language_tokens, + padding_mask=padding_mask) + batch_size = language_tokens.shape[0] + acc = (logits.max(-1)[-1] == label).float().sum(0) * 100.0 / batch_size + self.metric_logger.meters['acc'].update(acc.item(), n=batch_size) + + def after_eval(self, **kwargs): + print('* Acc {acc.global_avg:.3f}'.format(acc=self.metric_logger.acc)) + return {k: meter.global_avg for k, meter in self.metric_logger.meters.items()}, "acc" + + +class ImageNetHandler(TaskHandler): + def __init__(self, args) -> None: + super().__init__() + mixup_active = args.mixup > 0 or args.cutmix > 0. or args.cutmix_minmax is not None + if mixup_active: + # smoothing is handled with mixup label transform + self.criterion = SoftTargetCrossEntropy() + elif args.label_smoothing > 0.: + self.criterion = LabelSmoothingCrossEntropy(smoothing=args.label_smoothing) + else: + self.criterion = torch.nn.CrossEntropyLoss() + + def train_batch(self, model, image, label): + logits = model(image=image) + return { + "loss": self.criterion(logits, label), + } + + def eval_batch(self, model, image, label): + logits = model(image=image) + batch_size = image.shape[0] + acc1, acc5 = accuracy(logits, label, topk=(1, 5)) + self.metric_logger.meters['acc1'].update(acc1.item(), n=batch_size) + self.metric_logger.meters['acc5'].update(acc5.item(), n=batch_size) + + def after_eval(self, **kwargs): + print('* Acc@1 {top1.global_avg:.3f} Acc@5 {top5.global_avg:.3f}' + .format(top1=self.metric_logger.acc1, top5=self.metric_logger.acc5)) + return {k: meter.global_avg for k, meter in self.metric_logger.meters.items()}, "acc1" + + +class RetrievalHandler(TaskHandler): + def __init__(self) -> None: + super().__init__() + self.image_feats = [] + self.text_feats = [] + self.image_ids = [] + self.metric_logger = None + + def train_batch(self, model, image, language_tokens, padding_mask, image_id): + loss, vision_cls, language_cls = model( + image=image, text_description=language_tokens, padding_mask=padding_mask) + return { + "loss": loss, + } + + def before_eval(self, metric_logger, **kwargs): + self.image_feats.clear() + self.text_feats.clear() + self.image_ids.clear() + self.metric_logger = metric_logger + + def eval_batch(self, model, image, language_tokens, padding_mask, image_id): + vision_cls, _ = model(image=image, only_infer=True) + _, language_cls = model( + text_description=language_tokens, padding_mask=padding_mask, only_infer=True) + + self.image_feats.append(vision_cls.clone()) + self.text_feats.append(language_cls.clone()) + self.image_ids.append(image_id.clone()) + + def after_eval(self, **kwargs): + image_feats = {} + for feats, ids in zip(self.image_feats, self.image_ids): + for i, _idx in enumerate(ids): + idx = _idx.item() + if idx not in image_feats: + image_feats[idx] = feats[i] + + tiids = torch.cat(self.image_ids, dim=0) + iids = [] + sorted_tensors = [] + for key in sorted(image_feats.keys()): + sorted_tensors.append(image_feats[key].view(1, -1)) + iids.append(key) + + image_cls_feats = torch.cat(sorted_tensors, dim=0) + text_cls_feats = torch.cat(self.text_feats, dim=0) + + scores = image_cls_feats @ text_cls_feats.t() + iids = torch.LongTensor(iids).to(scores.device) + + print("scores: {}".format(scores.size())) + print("iids: {}".format(iids.size())) + print("tiids: {}".format(tiids.size())) + + topk10 = scores.topk(10, dim=1) + topk5 = scores.topk(5, dim=1) + topk1 = scores.topk(1, dim=1) + + topk10_iids = tiids[topk10.indices] + topk5_iids = tiids[topk5.indices] + topk1_iids = tiids[topk1.indices] + + tr_r10 = (iids.unsqueeze(1) == topk10_iids).float().max(dim=1)[0].mean() + tr_r5 = (iids.unsqueeze(1) == topk5_iids).float().max(dim=1)[0].mean() + tr_r1 = (iids.unsqueeze(1) == topk1_iids).float().max(dim=1)[0].mean() + + topk10 = scores.topk(10, dim=0) + topk5 = scores.topk(5, dim=0) + topk1 = scores.topk(1, dim=0) + topk10_iids = iids[topk10.indices] + topk5_iids = iids[topk5.indices] + topk1_iids = iids[topk1.indices] + + ir_r10 = (tiids.unsqueeze(0) == topk10_iids).float().max(dim=0)[0].mean() + ir_r5 = (tiids.unsqueeze(0) == topk5_iids).float().max(dim=0)[0].mean() + ir_r1 = (tiids.unsqueeze(0) == topk1_iids).float().max(dim=0)[0].mean() + + eval_result = { + "tr_r10": tr_r10.item() * 100.0, + "tr_r5": tr_r5.item() * 100.0, + "tr_r1": tr_r1.item() * 100.0, + "ir_r10": ir_r10.item() * 100.0, + "ir_r5": ir_r5.item() * 100.0, + "ir_r1": ir_r1.item() * 100.0, + "average_score": 100.0 * (tr_r1 + tr_r5 + tr_r10 + ir_r1 + ir_r5 + ir_r10).item() / 6.0, + } + + print('* Eval result = %s' % json.dumps(eval_result)) + return eval_result, "average_score" + + +class VQAHandler(TaskHandler): + def __init__(self) -> None: + super().__init__() + self.predictions = [] + self.criterion = nn.BCEWithLogitsLoss(reduction='mean') + self.label2ans = None + + def train_batch(self, model, image, language_tokens, padding_mask, labels): + logits = model( + image=image, question=language_tokens, + padding_mask=padding_mask) + return { + "loss": self.criterion(input=logits.float(), target=labels.float()) * labels.shape[1], + } + + def before_eval(self, metric_logger, data_loader, **kwargs): + self.predictions.clear() + self.metric_logger = metric_logger + self.label2ans = data_loader.dataset.label2ans + + def eval_batch(self, model, image, language_tokens, padding_mask, labels=None, qid=None): + logits = model( + image=image, question=language_tokens, + padding_mask=padding_mask) + batch_size = language_tokens.shape[0] + if labels is not None: + scores = utils.VQAScore()(logits, labels) * 100.0 + self.metric_logger.meters['score'].update(scores.item(), n=batch_size) + else: + _, preds = logits.max(-1) + for image_id, pred in zip(qid, preds): + self.predictions.append({ + "question_id": image_id.item(), + "answer": self.label2ans[pred.item()], + }) + + def after_eval(self, **kwargs): + if len(self.predictions) == 0: + print('* Score {score.global_avg:.3f}'.format(score=self.metric_logger.score)) + return {k: meter.global_avg for k, meter in self.metric_logger.meters.items()}, "score" + else: + return self.predictions, "prediction" + + +class CaptioningHandler(TaskHandler): + def __init__(self, args) -> None: + super().__init__() + self.predictions = [] + self.criterion = utils.BertCaptioningLoss(args.label_smoothing, args.drop_worst_ratio, args.drop_worst_after) + self.tokenizer = get_sentencepiece_model_for_beit3(args) + self.num_beams = args.num_beams + self.max_len = args.num_max_bpe_tokens + self.length_penalty = args.length_penalty + self.vocab_size = args.vocab_size + + def train_batch(self, model, image, language_tokens, masked_tokens, language_masked_pos, padding_mask, image_id, global_step): + logits, _ = model( + image=image, text_ids=masked_tokens, padding_mask=padding_mask, language_masked_pos=language_masked_pos, image_id=image_id) + masked_labels = language_tokens[language_masked_pos.bool()] + score = torch.max(logits, -1)[1].data == masked_labels + acc = torch.sum(score.float()) / torch.sum(language_masked_pos) + return { + "loss": self.criterion(logits, masked_labels, global_step), + "acc": acc + } + + def before_eval(self, metric_logger, data_loader, **kwargs): + self.predictions.clear() + self.metric_logger = metric_logger + + def eval_batch(self, model, image, image_id=None): + cur_len = 2 + num_keep_best = 1 + TOPN_PER_BEAM = 3 + + batch_size = image.size(0) + mask_id = self.tokenizer.mask_token_id + cls_id = self.tokenizer.cls_token_id + pad_id = self.tokenizer.pad_token_id + sep_id = self.tokenizer.sep_token_id + eos_token_ids = [sep_id] + + cls_ids = torch.full( + (batch_size, 1), cls_id, dtype=torch.long, device=image.device + ) + mask_ids = torch.full( + (batch_size, 1), mask_id, dtype=torch.long, device=image.device + ) + cur_input_ids = torch.cat([cls_ids, mask_ids], dim=1) + tmp_ids = torch.full( + (batch_size, self.max_len-1), mask_id, dtype=torch.long, device=image.device + ) + decoding_results = torch.cat([cls_ids, tmp_ids], dim=1) + + # Expand input to num beams + cur_input_ids = cur_input_ids.unsqueeze(1).expand(batch_size, self.num_beams, cur_len) + cur_input_ids = cur_input_ids.contiguous().view(batch_size * self.num_beams, cur_len) # (batch_size * num_beams, cur_len) + decoding_results = decoding_results.unsqueeze(1).expand(batch_size, self.num_beams, self.max_len) + decoding_results = decoding_results.contiguous().view(batch_size * self.num_beams, self.max_len) # (batch_size * num_beams, cur_len) + image = image.unsqueeze(1).expand(batch_size, self.num_beams, image.size(-3), image.size(-2), image.size(-1)) + image = image.contiguous().view(batch_size * self.num_beams, image.size(-3), image.size(-2), image.size(-1)) + + generated_hyps = [ + utils.BeamHypotheses( + num_keep_best, self.max_len, length_penalty=self.length_penalty, early_stopping=False + ) for _ in range(batch_size) + ] + # scores for each sentence in the beam + beam_scores = torch.zeros((batch_size, self.num_beams), dtype=torch.float, device=cur_input_ids.device) + beam_scores[:, 1:] = -1e9 + beam_scores = beam_scores.view(-1) # shape (batch_size * num_beams,) + + # done sentences + done = [False for _ in range(batch_size)] + incremental_state = {} + + while cur_len <= self.max_len: + next_token_idx = 1 + padding_masks = torch.full( + cur_input_ids.shape, 0, dtype=torch.long, device=image.device + ) + input_image = image + if cur_len != 2: + input_image = None + + outputs, incremental_state_next = model( + image=input_image, text_ids=cur_input_ids, language_masked_pos=None, + padding_mask=padding_masks, text_len=cur_len, incremental_state=incremental_state) + incremental_state = incremental_state_next + + # assert outputs.shape[1] == token_len + scores = outputs[:, next_token_idx, :] # (batch_size * num_beams, vocab_size) + scores = F.log_softmax(scores, dim=-1) # (batch_size * num_beams, vocab_size) + assert scores.size() == (batch_size * self.num_beams, self.vocab_size) + # Add the log prob of the new beams to the log prob of the beginning of the sequence (sum of logs == log of the product) + _scores = scores + beam_scores[:, None].expand_as(scores) # (batch_size * num_beams, vocab_size) + # re-organize to group the beam together (we are keeping top hypothesis accross beams) + _scores = _scores.view(batch_size, self.num_beams * self.vocab_size) # (batch_size, num_beams * vocab_size) + next_scores, next_words = torch.topk(_scores, TOPN_PER_BEAM * self.num_beams, dim=1, largest=True, sorted=True) + assert next_scores.size() == next_words.size() == (batch_size, TOPN_PER_BEAM * self.num_beams) + + # next batch beam content + # list of (batch_size * num_beams) tuple(next hypothesis score, next word, current position in the batch) + next_batch_beam = [] + # for each sentence + for batch_ex in range(batch_size): + # if we are done with this sentence + done[batch_ex] = done[batch_ex] or generated_hyps[batch_ex].is_done(next_scores[batch_ex].max().item()) + if done[batch_ex]: + next_batch_beam.extend([(0, pad_id, 0)] * self.num_beams) # pad the batch + continue + + # next sentence beam content + next_sent_beam = [] + for idx, score in zip(next_words[batch_ex], next_scores[batch_ex]): + # get beam and word IDs + beam_id = idx // self.vocab_size + word_id = idx % self.vocab_size + # end of sentence, or next word + # if word_id.item() in eos_token_ids or cur_len + 1 == max_len: + if (word_id.item() in eos_token_ids and cur_len + 1 <= self.max_len) or (cur_len + 1 == self.max_len): + generated_hyps[batch_ex].add( + decoding_results[batch_ex * self.num_beams + beam_id, :cur_len].clone(), score.item() + ) + else: + next_sent_beam.append((score, word_id, batch_ex * self.num_beams + beam_id)) + # the beam for next step is full + if len(next_sent_beam) == self.num_beams: + break + + # update next beam content + if cur_len + 1 == self.max_len: + assert len(next_sent_beam) == 0 + else: + assert len(next_sent_beam) == self.num_beams + + if len(next_sent_beam) == 0: + next_sent_beam = [(0, pad_id, 0)] * self.num_beams # pad the batch + next_batch_beam.extend(next_sent_beam) + assert len(next_batch_beam) == self.num_beams * (batch_ex + 1) + + # sanity check / prepare next batch + assert len(next_batch_beam) == batch_size * self.num_beams + beam_scores = beam_scores.new([x[0] for x in next_batch_beam]) + beam_words = cur_input_ids.new([x[1] for x in next_batch_beam]) + beam_idx = cur_input_ids.new([x[2] for x in next_batch_beam]) + + # re-order batch + cur_input_ids = cur_input_ids[beam_idx, :] + decoding_results = decoding_results[beam_idx, :] + for module in incremental_state: + for key in incremental_state[module]: + result = incremental_state[module][key].index_select(0, beam_idx) + incremental_state[module][key] = result[:,:,:-1,:] + + next_ids = torch.full( + (batch_size * self.num_beams, 1), mask_id, dtype=torch.long, device=image.device + ) + cur_input_ids = torch.cat([beam_words.unsqueeze(1), next_ids], dim=1) + decoding_results[:, cur_len-1] = beam_words + # update current length + cur_len = cur_len + 1 + # stop when we are done with each sentence + if all(done): + break + + # select the best hypotheses + tgt_len = torch.ones(batch_size, num_keep_best, dtype=torch.long) + logprobs = torch.zeros(batch_size, num_keep_best, + dtype=torch.float).fill_(-1e5).to(cur_input_ids.device) + all_best = [] + + for i, hypotheses in enumerate(generated_hyps): + best = [] + hyp_scores = torch.tensor([x[0] for x in hypotheses.hyp]) + _, best_indices = torch.topk(hyp_scores, + min(num_keep_best, len(hyp_scores)), largest=True) + for best_idx, hyp_idx in enumerate(best_indices): + conf, best_hyp = hypotheses.hyp[hyp_idx] + best.append(best_hyp) + logprobs[i, best_idx] = conf + tgt_len[i, best_idx] = len(best_hyp) + 1 # +1 for the symbol + all_best.append(best) + + # generate target batch, pad to the same length + decoded = cur_input_ids.new(batch_size, num_keep_best, self.max_len).fill_(pad_id) + for batch_idx, best in enumerate(all_best): + for best_idx, hypo in enumerate(best): + decoded[batch_idx, best_idx, : tgt_len[batch_idx, best_idx] - 1] = hypo + decoded[batch_idx, best_idx, tgt_len[batch_idx, best_idx] - 1] = eos_token_ids[0] + + captions = self.tokenizer.batch_decode(decoded.squeeze(1), skip_special_tokens=True) + for qid, pred in zip(image_id, captions): + self.predictions.append({ + "image_id": qid.item(), + "caption": pred, + }) + + def after_eval(self, **kwargs): + return self.predictions, "prediction" + + +def get_handler(args): + if args.task == "nlvr2": + return NLVR2Handler() + elif args.task == "vqav2": + return VQAHandler() + elif args.task in ("flickr30k", "coco_retrieval"): + return RetrievalHandler() + elif args.task in ("coco_captioning", "nocaps"): + return CaptioningHandler(args) + elif args.task in ("imagenet"): + return ImageNetHandler(args) + else: + raise NotImplementedError("Sorry, %s is not support." % args.task) + + +def train_one_epoch( + model: torch.nn.Module, data_loader: Iterable, + optimizer: torch.optim.Optimizer, device: torch.device, + handler: TaskHandler, epoch: int, start_steps: int, + lr_schedule_values: list, loss_scaler, max_norm: float = 0, + update_freq: int = 1, model_ema: Optional[ModelEma] = None, + log_writer: Optional[utils.TensorboardLogger] = None, + task = None, mixup_fn=None, +): + model.train(True) + metric_logger = utils.MetricLogger(delimiter=" ") + metric_logger.add_meter('lr', utils.SmoothedValue(window_size=1, fmt='{value:.6f}')) + metric_logger.add_meter('min_lr', utils.SmoothedValue(window_size=1, fmt='{value:.6f}')) + header = 'Epoch: [{}]'.format(epoch) + print_freq = 10 + + if loss_scaler is None: + model.zero_grad() + model.micro_steps = 0 + else: + optimizer.zero_grad() + + for data_iter_step, data in enumerate(metric_logger.log_every(data_loader, print_freq, header)): + step = data_iter_step // update_freq + global_step = start_steps + step # global training iteration + # Update LR & WD for the first acc + if lr_schedule_values is not None and data_iter_step % update_freq == 0: + for i, param_group in enumerate(optimizer.param_groups): + if lr_schedule_values is not None: + param_group["lr"] = lr_schedule_values[global_step] * param_group["lr_scale"] + # put input data into cuda + for tensor_key in data.keys(): + data[tensor_key] = data[tensor_key].to(device, non_blocking=True) + # print("input %s = %s" % (tensor_key, data[tensor_key])) + if loss_scaler is None and tensor_key.startswith("image"): + data[tensor_key] = data[tensor_key].half() + + # mixup for imagenet finetuning + if mixup_fn is not None: + data["image"], data["label"] = mixup_fn(data["image"], data["label"]) + + if task in ["coco_captioning", "nocaps"]: + data["global_step"] = global_step + + if loss_scaler is None: + results = handler.train_batch(model, **data) + else: + with torch.cuda.amp.autocast(): + results = handler.train_batch(model, **data) + + loss = results.pop("loss") + loss_value = loss.item() + + if not math.isfinite(loss_value): + print("Loss is {}, stopping training".format(loss_value)) + sys.exit(1) + + if loss_scaler is None: + loss /= update_freq + model.backward(loss) + model.step() + + if (data_iter_step + 1) % update_freq == 0: + # model.zero_grad() + # Deepspeed will call step() & model.zero_grad() automatic + if model_ema is not None: + model_ema.update(model) + grad_norm = None + loss_scale_value = utils.get_loss_scale_for_deepspeed(model) + else: + # this attribute is added by timm on one optimizer (adahessian) + is_second_order = hasattr(optimizer, 'is_second_order') and optimizer.is_second_order + loss /= update_freq + grad_norm = loss_scaler(loss, optimizer, clip_grad=max_norm, + parameters=model.parameters(), create_graph=is_second_order, + update_grad=(data_iter_step + 1) % update_freq == 0) + if (data_iter_step + 1) % update_freq == 0: + optimizer.zero_grad() + if model_ema is not None: + model_ema.update(model) + loss_scale_value = loss_scaler.state_dict()["scale"] + + torch.cuda.synchronize() + + metric_logger.update(loss=loss_value) + metric_logger.update(loss_scale=loss_scale_value) + min_lr = 10. + max_lr = 0. + for group in optimizer.param_groups: + min_lr = min(min_lr, group["lr"]) + max_lr = max(max_lr, group["lr"]) + + metric_logger.update(lr=max_lr) + metric_logger.update(min_lr=min_lr) + weight_decay_value = None + for group in optimizer.param_groups: + if group["weight_decay"] > 0: + weight_decay_value = group["weight_decay"] + metric_logger.update(weight_decay=weight_decay_value) + metric_logger.update(grad_norm=grad_norm) + + if log_writer is not None: + kwargs = { + "loss": loss_value, + } + for key in results: + kwargs[key] = results[key] + log_writer.update(head="train", **kwargs) + + kwargs = { + "loss_scale": loss_scale_value, + "lr": max_lr, + "min_lr": min_lr, + "weight_decay": weight_decay_value, + "grad_norm": grad_norm, + } + log_writer.update(head="opt", **kwargs) + log_writer.set_step() + + # gather the stats from all processes + metric_logger.synchronize_between_processes() + print("Averaged stats:", metric_logger) + return {k: meter.global_avg for k, meter in metric_logger.meters.items()} + + +@torch.no_grad() +def evaluate(data_loader, model, device, handler): + metric_logger = utils.MetricLogger(delimiter=" ") + header = 'Test:' + + # switch to evaluation mode + model.eval() + handler.before_eval(metric_logger=metric_logger, data_loader=data_loader) + + for data in metric_logger.log_every(data_loader, 10, header): + for tensor_key in data.keys(): + data[tensor_key] = data[tensor_key].to(device, non_blocking=True) + + with torch.cuda.amp.autocast(): + handler.eval_batch(model=model, **data) + + # gather the stats from all processes + metric_logger.synchronize_between_processes() + + return handler.after_eval() diff --git a/py/evf_sam/model/unilm/beit3/get_started/get_started_for_captioning.md b/py/evf_sam/model/unilm/beit3/get_started/get_started_for_captioning.md new file mode 100644 index 0000000..3b0f6bd --- /dev/null +++ b/py/evf_sam/model/unilm/beit3/get_started/get_started_for_captioning.md @@ -0,0 +1,176 @@ +# Fine-tuning BEiT-3 on Image Captioning + +## COCO Captioning Setup + +1. [Setup environment](../README.md#setup). +2. Download [2014 train images](http://images.cocodataset.org/zips/train2014.zip), [2014 val images](http://images.cocodataset.org/zips/val2014.zip) and [karpathy split](https://cs.stanford.edu/people/karpathy/deepimagesent/caption_datasets.zip), then organize the dataset as following structure: + +``` +/path/to/your_data/ + train2014/ + COCO_train2014_000000000009.jpg + ... + val2014/ + COCO_val2014_000000000042.jpg + ... + dataset_coco.json +``` + +We then generate the index json files using the following command. [beit3.spm](https://github.com/addf400/files/releases/download/beit3/beit3.spm) is the sentencepiece model used for tokenizing texts. +``` +from datasets import CaptioningDataset +from transformers import XLMRobertaTokenizer + +tokenizer = XLMRobertaTokenizer("/your_beit3_model_path/beit3.spm") + +CaptioningDataset.make_coco_captioning_dataset_index( + data_path="/path/to/your_data", + tokenizer=tokenizer, +) +``` + + +## NoCaps Setup + +1. [Setup environment](README.md#setup). +2. Download [NoCaps val set](https://nocaps.s3.amazonaws.com/nocaps_val_4500_captions.json), [NoCaps test set](https://s3.amazonaws.com/nocaps/nocaps_test_image_info.json) and download imags using the urls in val and test json files, then organize the dataset as following structure: + +``` +/path/to/your_data/ + val/ + 09c863d76bcf6b00.jpg + ... + test/ + 19dc6913830a0a21.jpg + ... + nocaps_val_4500_captions.json + nocaps_test_image_info.json +``` + +We then generate the index json files using the following command. [beit3.spm](https://github.com/addf400/files/releases/download/beit3/beit3.spm) is the sentencepiece model used for tokenizing texts. +``` +from datasets import CaptioningDataset +from transformers import XLMRobertaTokenizer + +tokenizer = XLMRobertaTokenizer("/your_beit3_model_path/beit3.spm") + +CaptioningDataset.make_nocaps_captioning_dataset_index( + data_path="/path/to/your_data", +) +``` +We use COCO captioning training set as the training data of NoCaps. + + +## Example: Fine-tuning BEiT-3 on Captioning + +The BEiT-3 **base** model can be fine-tuned on captioning tasks using 8 V100-32GB: + +```bash +python -m torch.distributed.launch --nproc_per_node=8 run_beit3_finetuning.py \ + --model beit3_base_patch16_480 \ + --input_size 480 \ + --task coco_captioning \ + --batch_size 32 \ + --layer_decay 1.0 \ + --lr 4e-5 \ + --randaug \ + --epochs 10 \ + --warmup_epochs 1 \ + --drop_path 0.1 \ + --sentencepiece_model /your_beit3_model_path/beit3.spm \ + --finetune /your_beit3_model_path/beit3_base_patch16_224.pth \ + --data_path /path/to/your_data \ + --output_dir /path/to/save/your_model \ + --log_dir /path/to/save/your_model/log \ + --weight_decay 0.05 \ + --seed 42 \ + --save_ckpt_freq 5 \ + --num_max_bpe_tokens 32 \ + --captioning_mask_prob 0.7 \ + --drop_worst_after 12000 \ + --dist_eval \ + --checkpoint_activations \ + --enable_deepspeed +``` +- `--batch_size`: batch size per GPU. Effective batch size = `number of GPUs` * `--batch_size` * `--update_freq`. So in the above example, the effective batch size is `8*32 = 256`. +- `--finetune`: weight path of your pretrained models; please download the pretrained model weights in [README.md](../README.md#pretrained-models). +- `--task`: **coco_captioning** for COCO captioning and **nocaps** for NoCaps dataset. +- `lr`: 4e-5 for COCO captioning and 1e-5 for NoCaps. +- `--enable_deepspeed`: optional. If you use apex, please enable deepspeed. +- `--checkpoint_activations`: using gradient checkpointing for saving GPU memory. + + +The BEiT-3 **large** model can be fine-tuned on captioning tasks using 8 V100-32GB: + +```bash +python -m torch.distributed.launch --nproc_per_node=8 run_beit3_finetuning.py \ + --model beit3_large_patch16_480 \ + --input_size 480 \ + --task coco_captioning \ + --batch_size 32 \ + --layer_decay 1.0 \ + --lr 8e-6 \ + --randaug \ + --epochs 10 \ + --warmup_epochs 1 \ + --drop_path 0.1 \ + --sentencepiece_model /your_beit3_model_path/beit3.spm \ + --finetune /your_beit3_model_path/beit3_large_patch16_224.pth \ + --data_path /path/to/your_data \ + --output_dir /path/to/save/your_model \ + --log_dir /path/to/save/your_model/log \ + --weight_decay 0.05 \ + --seed 42 \ + --save_ckpt_freq 5 \ + --num_max_bpe_tokens 32 \ + --captioning_mask_prob 0.7 \ + --drop_worst_after 12000 \ + --dist_eval \ + --checkpoint_activations \ + --enable_deepspeed +``` +- `--batch_size`: batch size per GPU. Effective batch size = `number of GPUs` * `--batch_size` * `--update_freq`. So in the above example, the effective batch size is `8*32 = 256`. +- `--finetune`: weight path of your pretrained models; please download the pretrained model weights in [README.md](../README.md#pretrained-models). +- `--task`: **coco_captioning** for COCO captioning and **nocaps** for NoCaps dataset. +- `lr`: 8e-6 for COCO captioning and NoCaps. +- `--enable_deepspeed`: optional. If you use apex, please enable deepspeed. +- `--checkpoint_activations`: using gradient checkpointing for saving GPU memory. + + +## Example: Evaluate BEiT-3 Fine-tuned model on Captioning + +- Get the prediction file of the fine-tuned BEiT3-base model on captioning with 8 V100-32GB: +```bash +python -m torch.distributed.launch --nproc_per_node=8 run_beit3_finetuning.py \ + --model beit3_base_patch16_480 \ + --input_size 480 \ + --task coco_captioning \ + --batch_size 16 \ + --sentencepiece_model /your_beit3_model_path/beit3.spm \ + --finetune /your_beit3_model_path/beit3_base_patch16_480_coco_captioning.pth \ + --data_path /path/to/your_data \ + --output_dir /path/to/save/your_prediction \ + --eval \ + --dist_eval +``` +- `--task`: **coco_captioning** for COCO captioning and **nocaps** for NoCaps dataset. +- `--finetune`: **beit3_base_patch16_480_coco_captioning.pth** for COCO captioning and **beit3_base_patch16_480_nocaps.pth** for NoCaps dataset. + +- Get the prediction file of the fine-tuned BEiT3-large model on captioning with 8 V100-32GB: +```bash +python -m torch.distributed.launch --nproc_per_node=8 run_beit3_finetuning.py \ + --model beit3_large_patch16_480 \ + --input_size 480 \ + --task coco_captioning \ + --batch_size 16 \ + --sentencepiece_model /your_beit3_model_path/beit3.spm \ + --finetune /your_beit3_model_path/beit3_large_patch16_480_coco_captioning.pth \ + --data_path /path/to/your_data \ + --output_dir /path/to/save/your_prediction \ + --eval \ + --dist_eval +``` +- `--task`: **coco_captioning** for COCO captioning and **nocaps** for NoCaps dataset. +- `--finetune`: **beit3_large_patch16_480_coco_captioning.pth** for COCO captioning and **beit3_large_patch16_480_nocaps.pth** for NoCaps dataset. + +Please then submit the prediction file in the `output_dir` to the [evaluation server](https://eval.ai/web/challenges/challenge-page/355/overview) to obtain the NoCaps val and test results. diff --git a/py/evf_sam/model/unilm/beit3/get_started/get_started_for_image_classification.md b/py/evf_sam/model/unilm/beit3/get_started/get_started_for_image_classification.md new file mode 100644 index 0000000..18b0231 --- /dev/null +++ b/py/evf_sam/model/unilm/beit3/get_started/get_started_for_image_classification.md @@ -0,0 +1,138 @@ +# Fine-tuning BEiT-3 on ImageNet-1k (Image Classification) + + +## Setup + +1. [Setup environment](../README.md#setup). +2. Download and extract ImageNet-1k from http://image-net.org/. + +The directory structure is the standard layout of torchvision's [`datasets.ImageFolder`](https://pytorch.org/docs/stable/torchvision/datasets.html#imagefolder). The training and validation data are expected to be in the `train/` folder and `val/` folder, respectively: + +``` +/path/to/imagenet/ + train/ + class1/ + img1.jpeg + class2/ + img2.jpeg + val/ + class1/ + img3.jpeg + class/2 + img4.jpeg +``` + +We then generate the index json files using the following command. [beit3.spm](https://github.com/addf400/files/releases/download/beit3/beit3.spm) is the sentencepiece model used for tokenizing texts. +``` +from datasets import ImageNetDataset + +ImageNetDataset.make_dataset_index( + train_data_path = "/path/to/your_data/train", + val_data_path = "/path/to/your_data/val", + index_path = "/path/to/your_data" +) +``` + + +## Example: Fine-tuning BEiT-3 on ImageNet-1k (Image Classification) + +The BEiT-3 **base** model can be finetuned on ImageNet-1k using 8 V100-32GB: + +```bash +python -m torch.distributed.launch --nproc_per_node=8 run_beit3_finetuning.py \ + --model beit3_base_patch16_224 \ + --task imagenet \ + --batch_size 128 \ + --layer_decay 0.65 \ + --lr 7e-4 \ + --update_freq 1 \ + --epochs 50 \ + --warmup_epochs 5 \ + --drop_path 0.15 \ + --sentencepiece_model /your_beit3_model_path/beit3.spm \ + --finetune /your_beit3_model_path/beit3_base_patch16_224.pth \ + --data_path /path/to/your_data \ + --output_dir /path/to/save/your_model \ + --log_dir /path/to/save/your_model/log \ + --weight_decay 0.05 \ + --seed 42 \ + --save_ckpt_freq 5 \ + --dist_eval \ + --mixup 0.8 \ + --cutmix 1.0 \ + --enable_deepspeed +``` +- `--batch_size`: batch size per GPU. Effective batch size = `number of GPUs` * `--batch_size` * `--update_freq`. So in the above example, the effective batch size is `8*128*1 = 1024`. +- `--finetune`: weight path of your pretrained models; please download the pretrained model weights in [README.md](../README.md#pretrained-models) +- `--enable_deepspeed`: optional. If you use apex, please enable deepspeed. + + +The BEiT-3 **large** model can be finetuned on ImageNet-1k using a DGX box (8 V100-32GB): + +```bash +python -m torch.distributed.launch --nproc_per_node=8 run_beit3_finetuning.py \ + --model beit3_large_patch16_224 \ + --task imagenet \ + --batch_size 128 \ + --layer_decay 0.8 \ + --lr 2e-4 \ + --update_freq 1 \ + --epochs 50 \ + --warmup_epochs 5 \ + --drop_path 0.25 \ + --sentencepiece_model /your_beit3_model_path/beit3.spm \ + --finetune /your_beit3_model_path/beit3_large_patch16_224.pth \ + --data_path /path/to/your_data \ + --output_dir /path/to/save/your_model \ + --log_dir /path/to/save/your_model/log \ + --weight_decay 0.05 \ + --seed 42 \ + --save_ckpt_freq 5 \ + --dist_eval \ + --mixup 0.8 \ + --cutmix 1.0 \ + --enable_deepspeed \ + --checkpoint_activations +``` +- `--batch_size`: batch size per GPU. Effective batch size = `number of GPUs` * `--batch_size` * `--update_freq`. So in the above example, the effective batch size is `8*128 = 1024`. +- `--finetune`: weight path of your pretrained models; please download the pretrained model weights in [README.md](../README.md#pretrained-models) +- `--enable_deepspeed`: optional. If you use apex, please enable deepspeed. +- `--checkpoint_activations`: using gradient checkpointing for saving GPU memory + +## Example: Evaluate BEiT-3 Finetuned model on ImageNet-1k (Image Classification) + +- Evaluate our fine-tuned BEiT3-base model on ImageNet val with a single GPU: +```bash +python -m torch.distributed.launch --nproc_per_node=1 run_beit3_finetuning.py \ + --model beit3_base_patch16_224 \ + --task imagenet \ + --batch_size 128 \ + --sentencepiece_model /your_beit3_model_path/beit3.spm \ + --finetune /your_beit3_model_path/beit3_base_patch16_224_in1k.pth \ + --data_path /path/to/your_data \ + --eval \ + --dist_eval +``` + +Expected results: +``` +* Acc@1 85.400 Acc@5 97.630 +``` + +- Evaluate our fine-tuned BEiT3-large model on ImageNet val with a single GPU: +```bash +python -m torch.distributed.launch --nproc_per_node=1 run_beit3_finetuning.py \ + --model beit3_large_patch16_224 \ + --task imagenet \ + --batch_size 128 \ + --sentencepiece_model /your_beit3_model_path/beit3.spm \ + --finetune /your_beit3_model_path/beit3_large_patch16_224_in1k.pth \ + --data_path /path/to/your_data \ + --eval \ + --dist_eval +``` + +Expected results: +``` +* Acc@1 87.580 Acc@5 98.326 +``` diff --git a/py/evf_sam/model/unilm/beit3/get_started/get_started_for_nlvr2.md b/py/evf_sam/model/unilm/beit3/get_started/get_started_for_nlvr2.md new file mode 100644 index 0000000..68e482e --- /dev/null +++ b/py/evf_sam/model/unilm/beit3/get_started/get_started_for_nlvr2.md @@ -0,0 +1,136 @@ +# Fine-tuning BEiT-3 on NLVR2 (Visual Reasoning) + + +## Setup + +1. [Setup environment](../README.md#setup). +2. Clone the [repository](https://github.com/lil-lab/nlvr) and sign the [request form](https://goo.gl/forms/yS29stWnFWzrDBFH3) to download the images, then organize the dataset as following structure: + +``` +/path/to/your_data/ + images/train/ + 0/train-11670-0-img0.png + ... + dev/ + dev-269-0-img0.png + ... + test1/ + test1-261-0-img0.png + ... + nlvr/ (nlvr repo) + nlvr/ + nlvr2/ +``` + +We then generate the index json files using the following command. [beit3.spm](https://github.com/addf400/files/releases/download/beit3/beit3.spm) is the sentencepiece model used for tokenizing texts. +``` +from datasets import NLVR2Dataset +from transformers import XLMRobertaTokenizer + +tokenizer = XLMRobertaTokenizer("/your_beit3_model_path/beit3.spm") + +NLVR2Dataset.make_dataset_index( + data_path="/path/to/your_data", + tokenizer=tokenizer, + nlvr_repo_path="/path/to/your_data/nlvr" +) +``` + + +## Example: Fine-tuning BEiT-3 on NLVR2 (Visual Reasoning) + +The BEiT-3 **base** model can be finetuned on NLVR2 using 8 V100-32GB: + +```bash +python -m torch.distributed.launch --nproc_per_node=8 run_beit3_finetuning.py \ + --model beit3_base_patch16_224 \ + --task nlvr2 \ + --batch_size 32 \ + --layer_decay 0.65 \ + --lr 7e-4 \ + --epochs 20 \ + --warmup_epochs 5 \ + --drop_path 0.2 \ + --sentencepiece_model /your_beit3_model_path/beit3.spm \ + --finetune /your_beit3_model_path/beit3_base_patch16_224.pth \ + --data_path /path/to/your_data \ + --output_dir /path/to/save/your_model \ + --log_dir /path/to/save/your_model/log \ + --weight_decay 0.2 \ + --seed 42 \ + --save_ckpt_freq 5 \ + --enable_deepspeed +``` +- `--batch_size`: batch size per GPU. Effective batch size = `number of GPUs` * `--batch_size` * `--update_freq`. So in the above example, the effective batch size is `8*32 = 256`. +- `--finetune`: weight path of your pretrained models; please download the pretrained model weights in [README.md](../README.md#pretrained-models). +- `--enable_deepspeed`: optional. If you use apex, please enable deepspeed. +- `--lr`: 7e-4 for `BEiT3-base`, 5e-4 for `BEiT3-base-indomain`. + + +The BEiT-3 **large** model can be finetuned on NLVR2 using 8 V100-32GB: + +```bash +python -m torch.distributed.launch --nproc_per_node=8 run_beit3_finetuning.py \ + --model beit3_large_patch16_224 \ + --task nlvr2 \ + --batch_size 32 \ + --layer_decay 0.85 \ + --lr 3e-4 \ + --epochs 20 \ + --warmup_epochs 5 \ + --drop_path 0.2 \ + --sentencepiece_model /your_beit3_model_path/beit3.spm \ + --finetune /your_beit3_model_path/beit3_large_patch16_224.pth \ + --data_path /path/to/your_data \ + --output_dir /path/to/save/your_model \ + --log_dir /path/to/save/your_model/log \ + --weight_decay 0.2 \ + --seed 42 \ + --save_ckpt_freq 5 \ + --enable_deepspeed \ + --checkpoint_activations +``` +- `--batch_size`: batch size per GPU. Effective batch size = `number of GPUs` * `--batch_size` * `--update_freq`. So in the above example, the effective batch size is `8*32 = 256`. +- `--finetune`: weight path of your pretrained models; please download the pretrained model weights in [README.md](../README.md#pretrained-models). +- `--enable_deepspeed`: optional. If you use apex, please enable deepspeed. +- `--lr`: 3e-4 for `BEiT3-large`, 1e-4 for `BEiT3-large-indomain`. +- `--checkpoint_activations`: using gradient checkpointing for saving GPU memory. + + +## Example: Evaluate BEiT-3 Finetuned model on NLVR2 (Visual Reasoning) + +- Get the result of our fine-tuned BEiT3-base model on NLVR2 test with 8 V100-32GB: +```bash +python -m torch.distributed.launch --nproc_per_node=8 run_beit3_finetuning.py \ + --model beit3_base_patch16_224 \ + --task nlvr2 \ + --batch_size 32 \ + --sentencepiece_model /your_beit3_model_path/beit3.spm \ + --finetune /your_beit3_model_path/beit3_base_patch16_224_nlvr2.pth \ + --data_path /path/to/your_data \ + --eval \ + --dist_eval +``` + +Expected results: +``` +* Acc 84.386 +``` + +- Get the result of our fine-tuned BEiT3-large model on NLVR2 test with 8 V100-32GB: +```bash +python -m torch.distributed.launch --nproc_per_node=8 run_beit3_finetuning.py \ + --model beit3_large_patch16_224 \ + --task nlvr2 \ + --batch_size 32 \ + --sentencepiece_model /your_beit3_model_path/beit3.spm \ + --finetune /your_beit3_model_path/beit3_large_patch16_224_nlvr2.pth \ + --data_path /path/to/your_data \ + --eval \ + --dist_eval +``` + +Expected results: +``` +* Acc 89.437 +``` diff --git a/py/evf_sam/model/unilm/beit3/get_started/get_started_for_retrieval.md b/py/evf_sam/model/unilm/beit3/get_started/get_started_for_retrieval.md new file mode 100644 index 0000000..a2ef2c1 --- /dev/null +++ b/py/evf_sam/model/unilm/beit3/get_started/get_started_for_retrieval.md @@ -0,0 +1,161 @@ +# Fine-tuning BEiT-3 on Image-text Retrieval + +## COCO Retrieval Setup + +1. [Setup environment](../README.md#setup). +2. Download [2014 train images](http://images.cocodataset.org/zips/train2014.zip), [2014 val images](http://images.cocodataset.org/zips/val2014.zip) and [karpathy split](https://cs.stanford.edu/people/karpathy/deepimagesent/caption_datasets.zip), then organize the dataset as following structure: + +``` +/path/to/your_data/ + train2014/ + COCO_train2014_000000000009.jpg + ... + val2014/ + COCO_val2014_000000000042.jpg + ... + dataset_coco.json +``` + +We then generate the index json files using the following command. [beit3.spm](https://github.com/addf400/files/releases/download/beit3/beit3.spm) is the sentencepiece model used for tokenizing texts. +``` +from datasets import RetrievalDataset +from transformers import XLMRobertaTokenizer + +tokenizer = XLMRobertaTokenizer("/your_beit3_model_path/beit3.spm") + +RetrievalDataset.make_coco_dataset_index( + data_path="/path/to/your_data", + tokenizer=tokenizer, +) +``` + + +## Flickr30k Retrieval Setup + +1. [Setup environment](README.md#setup). +2. Sign [flickr images request form](https://forms.illinois.edu/sec/229675) and download [karpathy split](https://cs.stanford.edu/people/karpathy/deepimagesent/caption_datasets.zip), then organize the dataset as following structure: + +``` +/path/to/your_data/ + flickr30k-images/ + 2923475135.jpg + ... + dataset_flickr30k.json +``` + +We then generate the index json files using the following command. [beit3.spm](https://github.com/addf400/files/releases/download/beit3/beit3.spm) is the sentencepiece model used for tokenizing texts. +``` +from datasets import RetrievalDataset +from transformers import XLMRobertaTokenizer + +tokenizer = XLMRobertaTokenizer("/your_beit3_model_path/beit3.spm") + +RetrievalDataset.make_flickr30k_dataset_index( + data_path="/path/to/your_data", + tokenizer=tokenizer, + karpathy_path="/path/to/your_data", +) +``` + + +## Example: Fine-tuning BEiT-3 on Retrieval + +The BEiT-3 **base** model can be finetuned on retrieval tasks using 16 V100-32GB: + +```bash +python -m torch.distributed.launch --nproc_per_node=16 run_beit3_finetuning.py \ + --model beit3_base_patch16_384 \ + --input_size 384 \ + --task coco_retrieval \ + --batch_size 192 \ + --layer_decay 0.65 \ + --lr 2e-4 \ + --epochs 15 \ + --warmup_epochs 3 \ + --drop_path 0.2 \ + --sentencepiece_model /your_beit3_model_path/beit3.spm \ + --finetune /your_beit3_model_path/beit3_base_itc_patch16_224.pth \ + --data_path /path/to/your_data \ + --output_dir /path/to/save/your_model \ + --log_dir /path/to/save/your_model/log \ + --weight_decay 0.05 \ + --seed 42 \ + --save_ckpt_freq 5 \ + --enable_deepspeed \ + --checkpoint_activations +``` +- `--batch_size`: batch size per GPU. Effective batch size = `number of GPUs` * `--batch_size` * `--update_freq`. So in the above example, the effective batch size is `192*16 = 3072`. +- `--finetune`: weight path of your pretrained models; please download the pretrained model weights in [README.md](../README.md#pretrained-models) +- `--task`: **coco_retrieval** for COCO retrieval, **flickr30k** for Flickr30k retrieval +- `--lr`: 2e-4 for COCO retrieval, 1e-4 for Flickr30k retrieval +- `--epochs`: 15 for COCO retrieval, 20 for Flickr30k retrieval +- `--warmup_epochs`: 3 for COCO retrieval, 5 for Flickr30k retrieval +- `--checkpoint_activations`: using gradient checkpointing for saving GPU memory + + +The BEiT-3 **large** model can be finetuned on retrieval tasks using 2x16 V100-32GB: + +```bash +python -m torch.distributed.launch --nproc_per_node=16 --nnodes=2 --node_rank=$NODE_RANK \ + --master_addr=$MASTER_ADDR --master_port=$MASTER_PORT run_beit3_finetuning.py \ + --model beit3_large_patch16_384 \ + --input_size 384 \ + --task coco_retrieval \ + --batch_size 96 \ + --layer_decay 0.85 \ + --lr 5e-5 \ + --epochs 15 \ + --warmup_epochs 3 \ + --drop_path 0.2 \ + --sentencepiece_model /your_beit3_model_path/beit3.spm \ + --finetune /your_beit3_model_path/beit3_large_itc_patch16_224.pth \ + --data_path /path/to/your_data \ + --output_dir /path/to/save/your_model \ + --log_dir /path/to/save/your_model/log \ + --weight_decay 0.05 \ + --seed 42 \ + --save_ckpt_freq 5 \ + --enable_deepspeed \ + --checkpoint_activations +``` +- `--batch_size`: batch size per GPU. Effective batch size = `number of GPUs` * `--batch_size` * `--update_freq`. So in the above example, the effective batch size is `96*32 = 3072`. +- `--finetune`: weight path of your pretrained models; please download the pretrained model weights in [README.md](../README.md#pretrained-models) +- `--task`: **coco_retrieval** for COCO retrieval, **flickr30k** for Flickr30k retrieval +- `--epochs`: 15 for COCO retrieval, 20 for Flickr30k retrieval +- `--warmup_epochs`: 3 for COCO retrieval, 5 for Flickr30k retrieval +- `--checkpoint_activations`: using gradient checkpointing for saving GPU memory + + +## Example: Evaluate BEiT-3 Fine-tuned model on COCO Retrieval and Flickr30k Retrieval + +- Get the results of our fine-tuned BEiT3-base model on retrieval tasks using a single GPU: +```bash +python -m torch.distributed.launch --nproc_per_node=1 run_beit3_finetuning.py \ + --model beit3_base_patch16_384 \ + --input_size 384 \ + --task coco_retrieval \ + --batch_size 16 \ + --sentencepiece_model /your_beit3_model_path/beit3.spm \ + --finetune /your_beit3_model_path/beit3_base_patch16_384_coco_retrieval.pth \ + --data_path /path/to/your_data \ + --eval \ + --dist_eval +``` +- `--task`: **coco_retrieval** for COCO retrieval, **flickr30k** for Flickr30k retrieval +- `--finetune`: **beit3_base_patch16_384_coco_retrieval.pth** for COCO retrieval, **beit3_base_patch16_384_f30k_retrieval.pth** for Flickr30k retrieval + +- Get the results of our fine-tuned BEiT3-large model on retrieval tasks using a single GPU: +```bash +python -m torch.distributed.launch --nproc_per_node=1 run_beit3_finetuning.py \ + --model beit3_large_patch16_384 \ + --input_size 384 \ + --task coco_retrieval \ + --batch_size 16 \ + --sentencepiece_model /your_beit3_model_path/beit3.spm \ + --finetune /your_beit3_model_path/beit3_large_patch16_384_coco_retrieval.pth \ + --data_path /path/to/your_data \ + --eval \ + --dist_eval +``` +- `--task`: **coco_retrieval** for COCO retrieval, **flickr30k** for Flickr30k retrieval +- `--finetune`: **beit3_large_patch16_384_coco_retrieval.pth** for COCO retrieval, **beit3_large_patch16_384_f30k_retrieval.pth** for Flickr30k retrieval diff --git a/py/evf_sam/model/unilm/beit3/get_started/get_started_for_vqav2.md b/py/evf_sam/model/unilm/beit3/get_started/get_started_for_vqav2.md new file mode 100644 index 0000000..b834b07 --- /dev/null +++ b/py/evf_sam/model/unilm/beit3/get_started/get_started_for_vqav2.md @@ -0,0 +1,144 @@ +# Fine-tuning BEiT-3 on VQAv2 (Visual Question Answering) + + +## Setup + +1. [Setup environment](../README.md#setup). +2. Download COCO [2014 train images](http://images.cocodataset.org/zips/train2014.zip), [2014 val images](http://images.cocodataset.org/zips/val2014.zip), [2015 test images](http://images.cocodataset.org/zips/test2015.zip), annotations ([train](https://s3.amazonaws.com/cvmlp/vqa/mscoco/vqa/v2_Annotations_Train_mscoco.zip), [val](https://s3.amazonaws.com/cvmlp/vqa/mscoco/vqa/v2_Annotations_Val_mscoco.zip)), and questions ([train](https://s3.amazonaws.com/cvmlp/vqa/mscoco/vqa/v2_Questions_Train_mscoco.zip), [val](https://s3.amazonaws.com/cvmlp/vqa/mscoco/vqa/v2_Questions_Val_mscoco.zip), [test](https://s3.amazonaws.com/cvmlp/vqa/mscoco/vqa/v2_Questions_Test_mscoco.zip)), then organize the dataset as following structure: + +``` +/path/to/your_data/ + train2014/ + COCO_train2014_000000000009.jpg + ... + val2014/ + COCO_val2014_000000000042.jpg + ... + test2015/ + COCO_test2015_000000000001.jpg + ... + vqa/ + v2_OpenEnded_mscoco_train2014_questions.json + v2_OpenEnded_mscoco_val2014_questions.json + v2_OpenEnded_mscoco_test2015_questions.json + v2_OpenEnded_mscoco_test-dev2015_questions.json + v2_mscoco_train2014_annotations.json + v2_mscoco_val2014_annotations.json +``` + +We then generate the index json files using the following command. [beit3.spm](https://github.com/addf400/files/releases/download/beit3/beit3.spm) is the sentencepiece model used for tokenizing texts. +``` +from datasets import VQAv2Dataset +from transformers import XLMRobertaTokenizer + +tokenizer = XLMRobertaTokenizer("/your_beit3_model_path/beit3.spm") + +VQAv2Dataset.make_dataset_index( + data_path="/path/to/your_data", + tokenizer=tokenizer, + annotation_data_path="/path/to/your_data/vqa", +) +``` + + +## Example: Fine-tuning BEiT-3 on VQAv2 (Visual Question Answering) + +The BEiT-3 **base** model can be finetuned on VQAv2 using 8 V100-32GB: + +```bash +python -m torch.distributed.launch --nproc_per_node=8 run_beit3_finetuning.py \ + --model beit3_base_patch16_480 \ + --input_size 480 \ + --task vqav2 \ + --batch_size 16 \ + --layer_decay 1.0 \ + --lr 3e-5 \ + --update_freq 1 \ + --randaug \ + --epochs 10 \ + --warmup_epochs 1 \ + --drop_path 0.1 \ + --sentencepiece_model /your_beit3_model_path/beit3.spm \ + --finetune /your_beit3_model_path/beit3_base_patch16_224.pth \ + --data_path /path/to/your_data \ + --output_dir /path/to/save/your_model \ + --log_dir /path/to/save/your_model/log \ + --weight_decay 0.01 \ + --seed 42 \ + --save_ckpt_freq 5 \ + --task_head_lr_weight 20 \ + --opt_betas 0.9 0.98 \ + --enable_deepspeed +``` +- `--batch_size`: batch size per GPU. Effective batch size = `number of GPUs` * `--batch_size` * `--update_freq`. So in the above example, the effective batch size is `8*16 = 128`. +- `--finetune`: weight path of your pretrained models; please download the pretrained model weights in [README.md](../README.md#pretrained-models) +- `--enable_deepspeed`: optional. If you use apex, please enable deepspeed. + + +The BEiT-3 **large** model can be finetuned on VQAv2 using 8 V100-32GB: + +```bash +python -m torch.distributed.launch --nproc_per_node=8 run_beit3_finetuning.py \ + --model beit3_large_patch16_480 \ + --input_size 480 \ + --task vqav2 \ + --batch_size 16 \ + --layer_decay 1.0 \ + --lr 2e-5 \ + --update_freq 1 \ + --randaug \ + --epochs 10 \ + --warmup_epochs 1 \ + --drop_path 0.15 \ + --sentencepiece_model /your_beit3_model_path/beit3.spm \ + --finetune /your_beit3_model_path/beit3_large_patch16_224.pth \ + --data_path /path/to/your_data \ + --output_dir /path/to/save/your_model \ + --log_dir /path/to/save/your_model/log \ + --weight_decay 0.01 \ + --seed 42 \ + --save_ckpt_freq 5 \ + --task_head_lr_weight 20 \ + --opt_betas 0.9 0.98 \ + --enable_deepspeed \ + --checkpoint_activations +``` +- `--batch_size`: batch size per GPU. Effective batch size = `number of GPUs` * `--batch_size` * `--update_freq`. So in the above example, the effective batch size is `8*16 = 128`. +- `--finetune`: weight path of your pretrained models; please download the pretrained model weights in [README.md](../README.md#pretrained-models) +- `--enable_deepspeed`: optional. If you use apex, please enable deepspeed. +- `--checkpoint_activations`: using gradient checkpointing for saving GPU memory + + +## Example: Evaluate BEiT-3 Finetuned model on VQAv2 (Visual Question Answering) + +- Get the prediction file of the fine-tuned BEiT3-base model on VQAv2 test with 8 V100-32GB: +```bash +python -m torch.distributed.launch --nproc_per_node=8 run_beit3_finetuning.py \ + --model beit3_base_patch16_480 \ + --input_size 480 \ + --task vqav2 \ + --batch_size 16 \ + --sentencepiece_model /your_beit3_model_path/beit3.spm \ + --finetune /your_beit3_model_path/beit3_base_patch16_480_vqa.pth \ + --data_path /path/to/your_data \ + --output_dir /path/to/save/your_prediction \ + --eval \ + --dist_eval +``` + +- Get the prediction file of the fine-tuned BEiT3-large model on VQAv2 test with 8 V100-32GB: +```bash +python -m torch.distributed.launch --nproc_per_node=8 run_beit3_finetuning.py \ + --model beit3_large_patch16_480 \ + --input_size 480 \ + --task vqav2 \ + --batch_size 16 \ + --sentencepiece_model /your_beit3_model_path/beit3.spm \ + --finetune /your_beit3_model_path/beit3_large_patch16_480_vqa.pth \ + --data_path /path/to/your_data \ + --output_dir /path/to/save/your_prediction \ + --eval \ + --dist_eval +``` + +Please then submit the prediction file in the `output_dir` to the [evaluation server](https://eval.ai/web/challenges/challenge-page/830/overview) to obtain the VQAv2 test-dev and test-std results. diff --git a/py/evf_sam/model/unilm/beit3/glossary.py b/py/evf_sam/model/unilm/beit3/glossary.py new file mode 100644 index 0000000..81fddf3 --- /dev/null +++ b/py/evf_sam/model/unilm/beit3/glossary.py @@ -0,0 +1,190 @@ +import re + +contractions = { + "aint": "ain't", + "arent": "aren't", + "cant": "can't", + "couldve": "could've", + "couldnt": "couldn't", + "couldn'tve": "couldn't've", + "couldnt've": "couldn't've", + "didnt": "didn't", + "doesnt": "doesn't", + "dont": "don't", + "hadnt": "hadn't", + "hadnt've": "hadn't've", + "hadn'tve": "hadn't've", + "hasnt": "hasn't", + "havent": "haven't", + "hed": "he'd", + "hed've": "he'd've", + "he'dve": "he'd've", + "hes": "he's", + "howd": "how'd", + "howll": "how'll", + "hows": "how's", + "Id've": "I'd've", + "I'dve": "I'd've", + "Im": "I'm", + "Ive": "I've", + "isnt": "isn't", + "itd": "it'd", + "itd've": "it'd've", + "it'dve": "it'd've", + "itll": "it'll", + "let's": "let's", + "maam": "ma'am", + "mightnt": "mightn't", + "mightnt've": "mightn't've", + "mightn'tve": "mightn't've", + "mightve": "might've", + "mustnt": "mustn't", + "mustve": "must've", + "neednt": "needn't", + "notve": "not've", + "oclock": "o'clock", + "oughtnt": "oughtn't", + "ow's'at": "'ow's'at", + "'ows'at": "'ow's'at", + "'ow'sat": "'ow's'at", + "shant": "shan't", + "shed've": "she'd've", + "she'dve": "she'd've", + "she's": "she's", + "shouldve": "should've", + "shouldnt": "shouldn't", + "shouldnt've": "shouldn't've", + "shouldn'tve": "shouldn't've", + "somebody'd": "somebodyd", + "somebodyd've": "somebody'd've", + "somebody'dve": "somebody'd've", + "somebodyll": "somebody'll", + "somebodys": "somebody's", + "someoned": "someone'd", + "someoned've": "someone'd've", + "someone'dve": "someone'd've", + "someonell": "someone'll", + "someones": "someone's", + "somethingd": "something'd", + "somethingd've": "something'd've", + "something'dve": "something'd've", + "somethingll": "something'll", + "thats": "that's", + "thered": "there'd", + "thered've": "there'd've", + "there'dve": "there'd've", + "therere": "there're", + "theres": "there's", + "theyd": "they'd", + "theyd've": "they'd've", + "they'dve": "they'd've", + "theyll": "they'll", + "theyre": "they're", + "theyve": "they've", + "twas": "'twas", + "wasnt": "wasn't", + "wed've": "we'd've", + "we'dve": "we'd've", + "weve": "we've", + "werent": "weren't", + "whatll": "what'll", + "whatre": "what're", + "whats": "what's", + "whatve": "what've", + "whens": "when's", + "whered": "where'd", + "wheres": "where's", + "whereve": "where've", + "whod": "who'd", + "whod've": "who'd've", + "who'dve": "who'd've", + "wholl": "who'll", + "whos": "who's", + "whove": "who've", + "whyll": "why'll", + "whyre": "why're", + "whys": "why's", + "wont": "won't", + "wouldve": "would've", + "wouldnt": "wouldn't", + "wouldnt've": "wouldn't've", + "wouldn'tve": "wouldn't've", + "yall": "y'all", + "yall'll": "y'all'll", + "y'allll": "y'all'll", + "yall'd've": "y'all'd've", + "y'alld've": "y'all'd've", + "y'all'dve": "y'all'd've", + "youd": "you'd", + "youd've": "you'd've", + "you'dve": "you'd've", + "youll": "you'll", + "youre": "you're", + "youve": "you've", +} + +manual_map = { + "none": "0", + "zero": "0", + "one": "1", + "two": "2", + "three": "3", + "four": "4", + "five": "5", + "six": "6", + "seven": "7", + "eight": "8", + "nine": "9", + "ten": "10", +} +articles = ["a", "an", "the"] +period_strip = re.compile("(?!<=\d)(\.)(?!\d)") +comma_strip = re.compile("(\d)(\,)(\d)") +punct = [ + ";", + r"/", + "[", + "]", + '"', + "{", + "}", + "(", + ")", + "=", + "+", + "\\", + "_", + "-", + ">", + "<", + "@", + "`", + ",", + "?", + "!", +] + + +def normalize_word(token): + _token = token + for p in punct: + if (p + " " in token or " " + p in token) or ( + re.search(comma_strip, token) != None + ): + _token = _token.replace(p, "") + else: + _token = _token.replace(p, " ") + token = period_strip.sub("", _token, re.UNICODE) + + _token = [] + temp = token.lower().split() + for word in temp: + word = manual_map.setdefault(word, word) + if word not in articles: + _token.append(word) + for i, word in enumerate(_token): + if word in contractions: + _token[i] = contractions[word] + token = " ".join(_token) + token = token.replace(",", "") + return token diff --git a/py/evf_sam/model/unilm/beit3/modeling_finetune.py b/py/evf_sam/model/unilm/beit3/modeling_finetune.py new file mode 100644 index 0000000..dc5ea0a --- /dev/null +++ b/py/evf_sam/model/unilm/beit3/modeling_finetune.py @@ -0,0 +1,386 @@ +# -------------------------------------------------------- +# Image as a Foreign Language: BEiT Pretraining for Vision and Vision-Language Tasks (https://arxiv.org/abs/2208.10442) +# Github source: https://github.com/microsoft/unilm/tree/master/beit3 +# Copyright (c) 2023 Microsoft +# Licensed under The MIT License [see LICENSE for details] +# --------------------------------------------------------' + +import torch +import torch.nn as nn +import torch.nn.functional as F +from timm.models import register_model +import numpy as np + +import utils +from modeling_utils import BEiT3Wrapper, _get_base_config, _get_large_config + + +class TwoLayerMLP(nn.Module): + def __init__( + self, + in_features, + hidden_features, + out_features, + norm_layer, + norm_input=True, + ): + super().__init__() + self.norm1 = norm_layer(in_features) if norm_input else nn.Identity() + self.dense1 = nn.Linear(in_features, hidden_features) + self.norm2 = norm_layer(hidden_features) + self.act = nn.GELU() + self.dense2 = nn.Linear(hidden_features, out_features) + + def forward(self, x): + x = self.norm1(x) + x = self.dense1(x) + x = self.norm2(x) + x = self.act(x) + return self.dense2(x) + + +class Pooler(nn.Module): + def __init__(self, input_features, output_features, norm_layer): + super().__init__() + self.norm = norm_layer(input_features) + self.dense = nn.Linear(input_features, output_features) + self.activation = nn.Tanh() + + def forward(self, x): + cls_rep = x[:, 0, :] + cls_rep = self.norm(cls_rep) + pooled_output = self.dense(cls_rep) + pooled_output = self.activation(pooled_output) + return pooled_output + + +class BEiT3ForVisualReasoning(BEiT3Wrapper): + def __init__( + self, + args, + num_classes, + norm_layer=nn.LayerNorm, + **kwargs + ): + super(BEiT3ForVisualReasoning, self).__init__(args=args) + embed_dim = args.encoder_embed_dim + self.head = TwoLayerMLP( + in_features=embed_dim * 4, + hidden_features=embed_dim * 2, + out_features=num_classes, + norm_layer=norm_layer, + ) + init_scale = 0.001 + self.head.apply(self._init_weights) + if isinstance(self.head.dense1, nn.Linear): + self.head.dense1.weight.data.mul_(init_scale) + self.head.dense1.bias.data.mul_(init_scale) + + if isinstance(self.head.dense2, nn.Linear): + self.head.dense2.weight.data.mul_(init_scale) + self.head.dense2.bias.data.mul_(init_scale) + + def forward(self, image_a, image_b, text_description, padding_mask, **kwargs): + bsz, _ = text_description.size() + + vision_input = torch.cat((image_a, image_b), dim=0) + language_input = torch.cat((text_description, text_description), dim=0) + padding_mask = torch.cat((padding_mask, padding_mask), dim=0) + + outputs = self.beit3( + textual_tokens=language_input, + visual_tokens=vision_input, + text_padding_position=padding_mask, + ) + x = outputs["encoder_out"] + multiway_split_position = outputs["multiway_split_position"] + + vision_cls = x[:, 0, :] + language_cls = x[:, multiway_split_position, :] + cls_rep = torch.cat((vision_cls, language_cls), dim=-1) + a, b = torch.split(cls_rep, split_size_or_sections=[bsz, bsz], dim=0) + cls_rep = torch.cat((a, b), dim=-1) + return self.head(cls_rep) + + +class BEiT3ForImageClassification(BEiT3Wrapper): + def __init__( + self, + args, + num_classes, + norm_layer=nn.LayerNorm, + **kwargs + ): + super(BEiT3ForImageClassification, self).__init__(args=args) + embed_dim = args.encoder_embed_dim + self.fc_norm = norm_layer(embed_dim) + self.head = nn.Linear(embed_dim, num_classes) if num_classes > 0 else nn.Identity() + + self.fc_norm.apply(self._init_weights) + self.head.apply(self._init_weights) + init_scale = 0.001 + if isinstance(self.head, nn.Linear): + self.head.weight.data.mul_(init_scale) + self.head.bias.data.mul_(init_scale) + + def forward(self, image, **kwargs): + x = self.beit3(textual_tokens=None, visual_tokens=image)["encoder_out"] + t = x[:, 1:, :] + cls_x = self.fc_norm(t.mean(1)) + return self.head(cls_x) + + +class BEiT3ForCaptioning(BEiT3Wrapper): + def __init__( + self, + args, + **kwargs + ): + super(BEiT3ForCaptioning, self).__init__(args=args) + embed_dim = args.encoder_embed_dim + self.mlm_head = nn.Linear(embed_dim, args.vocab_size) + self.mlm_head.apply(self._init_weights) + + def forward(self, image, text_ids, padding_mask, language_masked_pos, text_len=None, incremental_state=None, **kwargs): + text_len = text_len if text_len is not None else text_ids.size(1) + image_len = self.beit3.vision_embed.num_position_embeddings() + max_len = text_len + image_len + uni_mask = torch.zeros((max_len, max_len), dtype=torch.long, device=text_ids.device) + i_start, i_end = 0, image_len + t_start, t_end = image_len, max_len + # triangle mask for caption to caption + uni_mask[t_start:t_end, t_start:t_end] = torch.tril(torch.ones(text_len, text_len, dtype=torch.long, device=text_ids.device)) + # full attention for caption to image + uni_mask[t_start:t_end, i_start:i_end] = 1 + # full attention for image to image + uni_mask[i_start:i_end, i_start:i_end] = 1 + uni_mask = 1-uni_mask + + if incremental_state is not None: + for idx in range(self.get_num_layers()): + if idx not in incremental_state: + incremental_state[idx] = {} + + # for incremental decoding + positions = None + if image is None: + uni_mask = uni_mask[-2:] + padding_mask = None + # start position (2 (fairseq starts at 2) + cur_position) is equal to text_len + positions = torch.arange(text_len, text_ids.size(1) + text_len, device=text_ids.device).long().unsqueeze(0) + + outputs = self.beit3( + textual_tokens=text_ids, + visual_tokens=image, + text_padding_position=padding_mask, + attn_mask=uni_mask, + incremental_state=incremental_state, + positions=positions, + ) + if image is not None: + text_feats = outputs["encoder_out"][:, image_len:] + else: + text_feats = outputs["encoder_out"] + + if language_masked_pos is not None: + text_feats = text_feats[language_masked_pos.bool()] + + return self.mlm_head(text_feats), incremental_state + + +class BEiT3ForVisualQuestionAnswering(BEiT3Wrapper): + def __init__( + self, + args, + num_classes, + norm_layer=nn.LayerNorm, + **kwargs + ): + super(BEiT3ForVisualQuestionAnswering, self).__init__(args=args) + embed_dim = args.encoder_embed_dim + self.pooler = Pooler( + input_features=embed_dim, + output_features=embed_dim, + norm_layer=norm_layer, + ) + self.pooler.apply(self._init_weights) + self.head = nn.Sequential( + nn.Linear(embed_dim, embed_dim * 2), + norm_layer(embed_dim * 2), + nn.GELU(), + nn.Linear(embed_dim * 2, num_classes), + ) + self.head.apply(self._init_weights) + + def forward(self, image, question, padding_mask, **kwargs): + outputs = self.beit3( + textual_tokens=question, + visual_tokens=image, + text_padding_position=padding_mask, + ) + x = outputs["encoder_out"] + cls_rep = self.pooler(x) + return self.head(cls_rep) + + +class BEiT3ForRetrieval(BEiT3Wrapper): + def __init__( + self, + args, + **kwargs + ): + super(BEiT3ForRetrieval, self).__init__(args=args) + embed_dim = args.encoder_embed_dim + self.language_head = nn.Linear(embed_dim, embed_dim, bias=False) + self.vision_head = nn.Linear(embed_dim, embed_dim, bias=False) + self.language_head.apply(self._init_weights) + self.vision_head.apply(self._init_weights) + self.criterion = utils.ClipLoss( + rank=utils.get_rank(), + world_size=utils.get_world_size(), + ) + self.logit_scale = nn.Parameter(torch.ones([]) * np.log(1 / 0.07)) + + def forward(self, image=None, text_description=None, padding_mask=None, only_infer=False, **kwargs): + if image is not None: + outputs = self.beit3( + textual_tokens=None, + visual_tokens=image, + text_padding_position=None, + ) + x = outputs["encoder_out"] + vision_cls = self.vision_head(x[:, 0, :]) + vision_cls = F.normalize(vision_cls, dim=-1) + else: + vision_cls = None + + if text_description is not None: + outputs = self.beit3( + textual_tokens=text_description, + visual_tokens=None, + text_padding_position=padding_mask, + ) + x = outputs["encoder_out"] + language_cls = self.language_head(x[:, 0, :]) + language_cls = F.normalize(language_cls, dim=-1) + else: + language_cls = None + + if only_infer: + return vision_cls, language_cls + else: + loss, logits_per_image, logits_per_text = self.criterion( + vision_cls, language_cls, self.logit_scale.exp()) + return loss, vision_cls, language_cls + + +@register_model +def beit3_base_patch16_224_imageclassification(pretrained=False, **kwargs): + args = _get_base_config(**kwargs) + args.normalize_output = False + model = BEiT3ForImageClassification(args, num_classes=1000, **kwargs) + return model + + +@register_model +def beit3_large_patch16_224_imageclassification(pretrained=False, **kwargs): + args = _get_large_config(**kwargs) + args.normalize_output = False + model = BEiT3ForImageClassification(args, num_classes=1000, **kwargs) + return model + + +@register_model +def beit3_base_patch16_224_nlvr2(pretrained=False, **kwargs): + args = _get_base_config(**kwargs) + model = BEiT3ForVisualReasoning(args, num_classes=2, **kwargs) + return model + + +@register_model +def beit3_large_patch16_224_nlvr2(pretrained=False, **kwargs): + args = _get_large_config(**kwargs) + model = BEiT3ForVisualReasoning(args, num_classes=2, **kwargs) + return model + + +@register_model +def beit3_base_patch16_384_vqav2(pretrained=False, **kwargs): + args = _get_base_config(img_size=384, **kwargs) + args.normalize_output = False + model = BEiT3ForVisualQuestionAnswering(args, num_classes=3129, **kwargs) + return model + + +@register_model +def beit3_base_patch16_480_vqav2(pretrained=False, **kwargs): + args = _get_base_config(img_size=480, **kwargs) + args.normalize_output = False + model = BEiT3ForVisualQuestionAnswering(args, num_classes=3129, **kwargs) + return model + + +@register_model +def beit3_large_patch16_384_vqav2(pretrained=False, **kwargs): + args = _get_large_config(img_size=384, **kwargs) + args.normalize_output = False + model = BEiT3ForVisualQuestionAnswering(args, num_classes=3129, **kwargs) + return model + + +@register_model +def beit3_large_patch16_480_vqav2(pretrained=False, **kwargs): + args = _get_large_config(img_size=480, **kwargs) + args.normalize_output = False + model = BEiT3ForVisualQuestionAnswering(args, num_classes=3129, **kwargs) + return model + + +@register_model +def beit3_large_patch16_768_vqav2(pretrained=False, **kwargs): + args = _get_large_config(img_size=768, **kwargs) + args.normalize_output = False + model = BEiT3ForVisualQuestionAnswering(args, num_classes=3129, **kwargs) + return model + + +@register_model +def beit3_base_patch16_224_captioning(pretrained=False, **kwargs): + args = _get_base_config(**kwargs) + model = BEiT3ForCaptioning(args, **kwargs) + return model + + +@register_model +def beit3_base_patch16_480_captioning(pretrained=False, **kwargs): + args = _get_base_config(img_size=480, **kwargs) + model = BEiT3ForCaptioning(args, **kwargs) + return model + + +@register_model +def beit3_large_patch16_480_captioning(pretrained=False, **kwargs): + args = _get_large_config(img_size=480, **kwargs) + model = BEiT3ForCaptioning(args, **kwargs) + return model + + +@register_model +def beit3_base_patch16_224_retrieval(pretrained=False, **kwargs): + args = _get_base_config(**kwargs) + model = BEiT3ForRetrieval(args, **kwargs) + return model + + +@register_model +def beit3_base_patch16_384_retrieval(pretrained=False, **kwargs): + args = _get_base_config(img_size=384, **kwargs) + model = BEiT3ForRetrieval(args, **kwargs) + return model + + +@register_model +def beit3_large_patch16_384_retrieval(pretrained=False, **kwargs): + args = _get_large_config(img_size=384, **kwargs) + model = BEiT3ForRetrieval(args, **kwargs) + return model diff --git a/py/evf_sam/model/unilm/beit3/modeling_utils.py b/py/evf_sam/model/unilm/beit3/modeling_utils.py new file mode 100644 index 0000000..6581159 --- /dev/null +++ b/py/evf_sam/model/unilm/beit3/modeling_utils.py @@ -0,0 +1,76 @@ +# -------------------------------------------------------- +# Image as a Foreign Language: BEiT Pretraining for Vision and Vision-Language Tasks (https://arxiv.org/abs/2208.10442) +# Github source: https://github.com/microsoft/unilm/tree/master/beit3 +# Copyright (c) 2023 Microsoft +# Licensed under The MIT License [see LICENSE for details] +# --------------------------------------------------------' + +import math +import torch +import torch.nn as nn +from timm.models.layers import trunc_normal_ as __call_trunc_normal_ + +from torchscale.model.BEiT3 import BEiT3 +from torchscale.architecture.config import EncoderConfig + + +def trunc_normal_(tensor, mean=0., std=1.): + __call_trunc_normal_(tensor, mean=mean, std=std, a=-std, b=std) + + +def _get_base_config( + img_size=224, patch_size=16, drop_path_rate=0, + checkpoint_activations=None, mlp_ratio=4, vocab_size=64010, **kwargs +): + return EncoderConfig( + img_size=img_size, patch_size=patch_size, vocab_size=vocab_size, multiway=True, + layernorm_embedding=False, normalize_output=True, no_output_layer=True, + drop_path_rate=drop_path_rate, encoder_embed_dim=768, encoder_attention_heads=12, + encoder_ffn_embed_dim=int(768 * mlp_ratio), encoder_layers=12, + checkpoint_activations=checkpoint_activations, + ) + + +def _get_large_config( + img_size=224, patch_size=16, drop_path_rate=0, + checkpoint_activations=None, mlp_ratio=4, vocab_size=64010, **kwargs +): + return EncoderConfig( + img_size=img_size, patch_size=patch_size, vocab_size=vocab_size, multiway=True, + layernorm_embedding=False, normalize_output=True, no_output_layer=True, + drop_path_rate=drop_path_rate, encoder_embed_dim=1024, encoder_attention_heads=16, + encoder_ffn_embed_dim=int(1024 * mlp_ratio), encoder_layers=24, + checkpoint_activations=checkpoint_activations, + ) + + +class BEiT3Wrapper(nn.Module): + def __init__(self, args, **kwargs): + super().__init__() + self.args = args + self.beit3 = BEiT3(args) + self.apply(self._init_weights) + + def fix_init_weight(self): + def rescale(param, layer_id): + param.div_(math.sqrt(2.0 * layer_id)) + + for layer_id, layer in enumerate(self.blocks): + rescale(layer.attn.proj.weight.data, layer_id + 1) + rescale(layer.mlp.fc2.weight.data, layer_id + 1) + + def get_num_layers(self): + return self.beit3.encoder.num_layers + + @torch.jit.ignore + def no_weight_decay(self): + return {'pos_embed', 'cls_token', 'beit3.encoder.embed_positions.A.weight', 'beit3.vision_embed.cls_token', 'logit_scale'} + + def _init_weights(self, m): + if isinstance(m, nn.Linear): + trunc_normal_(m.weight, std=.02) + if isinstance(m, nn.Linear) and m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.LayerNorm): + nn.init.constant_(m.bias, 0) + nn.init.constant_(m.weight, 1.0) diff --git a/py/evf_sam/model/unilm/beit3/optim_factory.py b/py/evf_sam/model/unilm/beit3/optim_factory.py new file mode 100644 index 0000000..a3d32bb --- /dev/null +++ b/py/evf_sam/model/unilm/beit3/optim_factory.py @@ -0,0 +1,128 @@ +# -------------------------------------------------------- +# Image as a Foreign Language: BEiT Pretraining for Vision and Vision-Language Tasks (https://arxiv.org/abs/2208.10442) +# Github source: https://github.com/microsoft/unilm/tree/master/beit3 +# Copyright (c) 2023 Microsoft +# Licensed under The MIT License [see LICENSE for details] +# --------------------------------------------------------' + +from torch import optim as optim +from timm.optim.lookahead import Lookahead + +import json + + +def get_num_layer_for_vit(var_name, num_max_layer): + if "embed" in var_name: + return 0 + elif var_name in ( + "cls_token", "mask_token", "pos_embed", "language_pos_embed", + "word_embeddings.weight", "vision_cls_token", "vision_pos_embed" + ): + return 0 + elif var_name.startswith("patch_embed"): + return 0 + elif var_name.startswith("rel_pos_bias"): + return num_max_layer - 1 + elif "layers." in var_name: + layer_id = int(var_name.split('layers.')[1].split('.')[0]) + return layer_id + 1 + else: + return num_max_layer - 1 + + +def get_is_head_flag_for_vit(var_name, num_max_layer): + if var_name.startswith("head"): + return 1 + # elif var_name.startswith("pooler"): + # return 1 + else: + return 0 + + +class LayerDecayValueAssigner(object): + def __init__(self, values, scale_handler=None): + self.scale_handler = scale_handler or get_num_layer_for_vit + self.values = values + + def get_scale(self, layer_id): + return self.values[layer_id] + + def get_layer_id(self, var_name): + return self.scale_handler(var_name, len(self.values)) + + +# The implementation code is modified from Timm (https://github.com/huggingface/pytorch-image-models/tree/main/timm +def get_parameter_groups(model, weight_decay=1e-5, skip_list=(), get_num_layer=None, get_layer_scale=None): + parameter_group_names = {} + parameter_group_vars = {} + + for name, param in model.named_parameters(): + if not param.requires_grad: + continue # frozen weights + if len(param.shape) == 1 or name.endswith(".bias") or name in skip_list: + group_name = "no_decay" + this_weight_decay = 0. + else: + group_name = "decay" + this_weight_decay = weight_decay + if get_num_layer is not None: + layer_id = get_num_layer(name) + group_name = "layer_%d_%s" % (layer_id, group_name) + else: + layer_id = None + + if group_name not in parameter_group_names: + if get_layer_scale is not None: + scale = get_layer_scale(layer_id) + else: + scale = 1. + + parameter_group_names[group_name] = { + "weight_decay": this_weight_decay, + "params": [], + "lr_scale": scale + } + parameter_group_vars[group_name] = { + "weight_decay": this_weight_decay, + "params": [], + "lr_scale": scale + } + + parameter_group_vars[group_name]["params"].append(param) + parameter_group_names[group_name]["params"].append(name) + print("Param groups = %s" % json.dumps(parameter_group_names, indent=2)) + return list(parameter_group_vars.values()) + + +def create_optimizer(args, model, get_num_layer=None, get_layer_scale=None, filter_bias_and_bn=True, skip_list=None): + opt_lower = args.opt.lower() + weight_decay = args.weight_decay + if weight_decay and filter_bias_and_bn: + skip = {} + if skip_list is not None: + skip = skip_list + elif hasattr(model, 'no_weight_decay'): + skip = model.no_weight_decay() + parameters = get_parameter_groups(model, weight_decay, skip, get_num_layer, get_layer_scale) + weight_decay = 0. + else: + parameters = model.parameters() + + opt_args = dict(lr=args.lr, weight_decay=weight_decay) + if hasattr(args, 'opt_eps') and args.opt_eps is not None: + opt_args['eps'] = args.opt_eps + if hasattr(args, 'opt_betas') and args.opt_betas is not None: + opt_args['betas'] = args.opt_betas + + opt_split = opt_lower.split('_') + opt_lower = opt_split[-1] + if opt_lower == 'adamw': + optimizer = optim.AdamW(parameters, **opt_args) + else: + raise ValueError("Invalid optimizer") + + if len(opt_split) > 1: + if opt_split[0] == 'lookahead': + optimizer = Lookahead(optimizer) + + return optimizer diff --git a/py/evf_sam/model/unilm/beit3/randaug.py b/py/evf_sam/model/unilm/beit3/randaug.py new file mode 100644 index 0000000..359e97d --- /dev/null +++ b/py/evf_sam/model/unilm/beit3/randaug.py @@ -0,0 +1,340 @@ +import cv2 +import numpy as np + + +## aug functions +def identity_func(img): + return img + + +def autocontrast_func(img, cutoff=0): + ''' + same output as PIL.ImageOps.autocontrast + ''' + n_bins = 256 + + def tune_channel(ch): + n = ch.size + cut = cutoff * n // 100 + if cut == 0: + high, low = ch.max(), ch.min() + else: + hist = cv2.calcHist([ch], [0], None, [n_bins], [0, n_bins]) + low = np.argwhere(np.cumsum(hist) > cut) + low = 0 if low.shape[0] == 0 else low[0] + high = np.argwhere(np.cumsum(hist[::-1]) > cut) + high = n_bins - 1 if high.shape[0] == 0 else n_bins - 1 - high[0] + if high <= low: + table = np.arange(n_bins) + else: + scale = (n_bins - 1) / (high - low) + offset = -low * scale + table = np.arange(n_bins) * scale + offset + table[table < 0] = 0 + table[table > n_bins - 1] = n_bins - 1 + table = table.clip(0, 255).astype(np.uint8) + return table[ch] + + channels = [tune_channel(ch) for ch in cv2.split(img)] + out = cv2.merge(channels) + return out + + +def equalize_func(img): + ''' + same output as PIL.ImageOps.equalize + PIL's implementation is different from cv2.equalize + ''' + n_bins = 256 + + def tune_channel(ch): + hist = cv2.calcHist([ch], [0], None, [n_bins], [0, n_bins]) + non_zero_hist = hist[hist != 0].reshape(-1) + step = np.sum(non_zero_hist[:-1]) // (n_bins - 1) + if step == 0: return ch + n = np.empty_like(hist) + n[0] = step // 2 + n[1:] = hist[:-1] + table = (np.cumsum(n) // step).clip(0, 255).astype(np.uint8) + return table[ch] + + channels = [tune_channel(ch) for ch in cv2.split(img)] + out = cv2.merge(channels) + return out + + +def rotate_func(img, degree, fill=(0, 0, 0)): + ''' + like PIL, rotate by degree, not radians + ''' + H, W = img.shape[0], img.shape[1] + center = W / 2, H / 2 + M = cv2.getRotationMatrix2D(center, degree, 1) + out = cv2.warpAffine(img, M, (W, H), borderValue=fill) + return out + + +def solarize_func(img, thresh=128): + ''' + same output as PIL.ImageOps.posterize + ''' + table = np.array([el if el < thresh else 255 - el for el in range(256)]) + table = table.clip(0, 255).astype(np.uint8) + out = table[img] + return out + + +def color_func(img, factor): + ''' + same output as PIL.ImageEnhance.Color + ''' + ## implementation according to PIL definition, quite slow + # degenerate = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)[:, :, np.newaxis] + # out = blend(degenerate, img, factor) + # M = ( + # np.eye(3) * factor + # + np.float32([0.114, 0.587, 0.299]).reshape(3, 1) * (1. - factor) + # )[np.newaxis, np.newaxis, :] + M = ( + np.float32([ + [0.886, -0.114, -0.114], + [-0.587, 0.413, -0.587], + [-0.299, -0.299, 0.701]]) * factor + + np.float32([[0.114], [0.587], [0.299]]) + ) + out = np.matmul(img, M).clip(0, 255).astype(np.uint8) + return out + + +def contrast_func(img, factor): + """ + same output as PIL.ImageEnhance.Contrast + """ + mean = np.sum(np.mean(img, axis=(0, 1)) * np.array([0.114, 0.587, 0.299])) + table = np.array([( + el - mean) * factor + mean + for el in range(256) + ]).clip(0, 255).astype(np.uint8) + out = table[img] + return out + + +def brightness_func(img, factor): + ''' + same output as PIL.ImageEnhance.Contrast + ''' + table = (np.arange(256, dtype=np.float32) * factor).clip(0, 255).astype(np.uint8) + out = table[img] + return out + + +def sharpness_func(img, factor): + ''' + The differences the this result and PIL are all on the 4 boundaries, the center + areas are same + ''' + kernel = np.ones((3, 3), dtype=np.float32) + kernel[1][1] = 5 + kernel /= 13 + degenerate = cv2.filter2D(img, -1, kernel) + if factor == 0.0: + out = degenerate + elif factor == 1.0: + out = img + else: + out = img.astype(np.float32) + degenerate = degenerate.astype(np.float32)[1:-1, 1:-1, :] + out[1:-1, 1:-1, :] = degenerate + factor * (out[1:-1, 1:-1, :] - degenerate) + out = out.astype(np.uint8) + return out + + +def shear_x_func(img, factor, fill=(0, 0, 0)): + H, W = img.shape[0], img.shape[1] + M = np.float32([[1, factor, 0], [0, 1, 0]]) + out = cv2.warpAffine(img, M, (W, H), borderValue=fill, flags=cv2.INTER_LINEAR).astype(np.uint8) + return out + + +def translate_x_func(img, offset, fill=(0, 0, 0)): + ''' + same output as PIL.Image.transform + ''' + H, W = img.shape[0], img.shape[1] + M = np.float32([[1, 0, -offset], [0, 1, 0]]) + out = cv2.warpAffine(img, M, (W, H), borderValue=fill, flags=cv2.INTER_LINEAR).astype(np.uint8) + return out + + +def translate_y_func(img, offset, fill=(0, 0, 0)): + ''' + same output as PIL.Image.transform + ''' + H, W = img.shape[0], img.shape[1] + M = np.float32([[1, 0, 0], [0, 1, -offset]]) + out = cv2.warpAffine(img, M, (W, H), borderValue=fill, flags=cv2.INTER_LINEAR).astype(np.uint8) + return out + + +def posterize_func(img, bits): + ''' + same output as PIL.ImageOps.posterize + ''' + out = np.bitwise_and(img, np.uint8(255 << (8 - bits))) + return out + + +def shear_y_func(img, factor, fill=(0, 0, 0)): + H, W = img.shape[0], img.shape[1] + M = np.float32([[1, 0, 0], [factor, 1, 0]]) + out = cv2.warpAffine(img, M, (W, H), borderValue=fill, flags=cv2.INTER_LINEAR).astype(np.uint8) + return out + + +def cutout_func(img, pad_size, replace=(0, 0, 0)): + replace = np.array(replace, dtype=np.uint8) + H, W = img.shape[0], img.shape[1] + rh, rw = np.random.random(2) + pad_size = pad_size // 2 + ch, cw = int(rh * H), int(rw * W) + x1, x2 = max(ch - pad_size, 0), min(ch + pad_size, H) + y1, y2 = max(cw - pad_size, 0), min(cw + pad_size, W) + out = img.copy() + out[x1:x2, y1:y2, :] = replace + return out + + +### level to args +def enhance_level_to_args(MAX_LEVEL): + def level_to_args(level): + return ((level / MAX_LEVEL) * 1.8 + 0.1,) + return level_to_args + + +def shear_level_to_args(MAX_LEVEL, replace_value): + def level_to_args(level): + level = (level / MAX_LEVEL) * 0.3 + if np.random.random() > 0.5: level = -level + return (level, replace_value) + + return level_to_args + + +def translate_level_to_args(translate_const, MAX_LEVEL, replace_value): + def level_to_args(level): + level = (level / MAX_LEVEL) * float(translate_const) + if np.random.random() > 0.5: level = -level + return (level, replace_value) + + return level_to_args + + +def cutout_level_to_args(cutout_const, MAX_LEVEL, replace_value): + def level_to_args(level): + level = int((level / MAX_LEVEL) * cutout_const) + return (level, replace_value) + + return level_to_args + + +def solarize_level_to_args(MAX_LEVEL): + def level_to_args(level): + level = int((level / MAX_LEVEL) * 256) + return (level, ) + return level_to_args + + +def none_level_to_args(level): + return () + + +def posterize_level_to_args(MAX_LEVEL): + def level_to_args(level): + level = int((level / MAX_LEVEL) * 4) + return (level, ) + return level_to_args + + +def rotate_level_to_args(MAX_LEVEL, replace_value): + def level_to_args(level): + level = (level / MAX_LEVEL) * 30 + if np.random.random() < 0.5: + level = -level + return (level, replace_value) + + return level_to_args + + +func_dict = { + 'Identity': identity_func, + 'AutoContrast': autocontrast_func, + 'Equalize': equalize_func, + 'Rotate': rotate_func, + 'Solarize': solarize_func, + 'Color': color_func, + 'Contrast': contrast_func, + 'Brightness': brightness_func, + 'Sharpness': sharpness_func, + 'ShearX': shear_x_func, + 'TranslateX': translate_x_func, + 'TranslateY': translate_y_func, + 'Posterize': posterize_func, + 'ShearY': shear_y_func, +} + +translate_const = 10 +MAX_LEVEL = 10 +replace_value = (128, 128, 128) +arg_dict = { + 'Identity': none_level_to_args, + 'AutoContrast': none_level_to_args, + 'Equalize': none_level_to_args, + 'Rotate': rotate_level_to_args(MAX_LEVEL, replace_value), + 'Solarize': solarize_level_to_args(MAX_LEVEL), + 'Color': enhance_level_to_args(MAX_LEVEL), + 'Contrast': enhance_level_to_args(MAX_LEVEL), + 'Brightness': enhance_level_to_args(MAX_LEVEL), + 'Sharpness': enhance_level_to_args(MAX_LEVEL), + 'ShearX': shear_level_to_args(MAX_LEVEL, replace_value), + 'TranslateX': translate_level_to_args( + translate_const, MAX_LEVEL, replace_value + ), + 'TranslateY': translate_level_to_args( + translate_const, MAX_LEVEL, replace_value + ), + 'Posterize': posterize_level_to_args(MAX_LEVEL), + 'ShearY': shear_level_to_args(MAX_LEVEL, replace_value), +} + + +class RandomAugment(object): + + def __init__(self, N=2, M=10, isPIL=False, augs=[]): + self.N = N + self.M = M + self.isPIL = isPIL + if augs: + self.augs = augs + else: + self.augs = list(arg_dict.keys()) + + def get_random_ops(self): + sampled_ops = np.random.choice(self.augs, self.N) + return [(op, 0.5, self.M) for op in sampled_ops] + + def __call__(self, img): + if self.isPIL: + img = np.array(img) + ops = self.get_random_ops() + for name, prob, level in ops: + if np.random.random() > prob: + continue + args = arg_dict[name](level) + img = func_dict[name](img, *args) + return img + + +if __name__ == '__main__': + a = RandomAugment() + img = np.random.randn(32, 32, 3) + a(img) diff --git a/py/evf_sam/model/unilm/beit3/requirements.txt b/py/evf_sam/model/unilm/beit3/requirements.txt new file mode 100644 index 0000000..4d8ffa5 --- /dev/null +++ b/py/evf_sam/model/unilm/beit3/requirements.txt @@ -0,0 +1,22 @@ +torch +torchvision +timm==0.4.12 +Pillow +blobfile +mypy +numpy +pytest +requests +einops +tensorboardX +scipy +ftfy +opencv-python +sentencepiece +pyarrow +torchmetrics==0.7.3 +transformers +deepspeed==0.4.0 +pycocotools +pycocoevalcap +torchscale==0.2.0 diff --git a/py/evf_sam/model/unilm/beit3/run_beit3_finetuning.py b/py/evf_sam/model/unilm/beit3/run_beit3_finetuning.py new file mode 100644 index 0000000..758cd69 --- /dev/null +++ b/py/evf_sam/model/unilm/beit3/run_beit3_finetuning.py @@ -0,0 +1,448 @@ +# -------------------------------------------------------- +# Image as a Foreign Language: BEiT Pretraining for Vision and Vision-Language Tasks (https://arxiv.org/abs/2208.10442) +# Github source: https://github.com/microsoft/unilm/tree/master/beit3 +# Copyright (c) 2023 Microsoft +# Licensed under The MIT License [see LICENSE for details] +# --------------------------------------------------------' + +import argparse +import datetime +import numpy as np +import time +import torch +import torch.backends.cudnn as cudnn +import json +import os + +from pathlib import Path + +from timm.data.mixup import Mixup +from timm.models import create_model +from timm.utils import ModelEma +from optim_factory import create_optimizer, get_parameter_groups, \ + LayerDecayValueAssigner, get_is_head_flag_for_vit + +from engine_for_finetuning import train_one_epoch, get_handler, evaluate +from datasets import create_downstream_dataset +from utils import NativeScalerWithGradNormCount as NativeScaler +import utils +import modeling_finetune + + +def get_args(): + parser = argparse.ArgumentParser('BEiT fine-tuning and evaluation script for image classification', add_help=False) + + # Model parameters + parser.add_argument('--model', default='beit_base_patch16_224', type=str, metavar='MODEL', + help='Name of model to train') + parser.add_argument('--task', type=str, required=True, + choices=['nlvr2', 'vqav2', 'flickr30k', 'coco_retrieval', 'coco_captioning', 'nocaps', 'imagenet'], + help='Name of task to fine-tuning') + + parser.add_argument('--input_size', default=224, type=int, + help='images input size') + parser.add_argument('--drop_path', type=float, default=0.1, metavar='PCT', + help='Drop path rate (default: 0.1)') + + parser.add_argument('--checkpoint_activations', action='store_true', default=None, + help='Enable checkpointing to save your memory.') + parser.add_argument('--sentencepiece_model', type=str, required=True, + help='Sentencepiece model path for the pretrained model.') + parser.add_argument('--vocab_size', type=int, default=64010) + parser.add_argument('--num_max_bpe_tokens', type=int, default=64) + + parser.add_argument('--model_ema', action='store_true', default=False) + parser.add_argument('--model_ema_decay', type=float, default=0.9999, help='') + parser.add_argument('--model_ema_force_cpu', action='store_true', default=False, help='') + + # Optimizer parameters + parser.add_argument('--opt', default='adamw', type=str, metavar='OPTIMIZER', + help='Optimizer (default: "adamw"') + parser.add_argument('--opt_eps', default=1e-8, type=float, metavar='EPSILON', + help='Optimizer Epsilon (default: 1e-8)') + parser.add_argument('--opt_betas', default=[0.9, 0.999], type=float, nargs='+', metavar='BETA', + help='Optimizer Betas (default: 0.9, 0.999, use opt default)') + parser.add_argument('--clip_grad', type=float, default=None, metavar='NORM', + help='Clip gradient norm (default: None, no clipping)') + parser.add_argument('--momentum', type=float, default=0.9, metavar='M', + help='SGD momentum (default: 0.9)') + parser.add_argument('--weight_decay', type=float, default=0.05, + help='weight decay (default: 0.05)') + + parser.add_argument('--lr', type=float, default=5e-4, metavar='LR', + help='learning rate (default: 5e-4)') + parser.add_argument('--layer_decay', type=float, default=0.9) + parser.add_argument('--task_head_lr_weight', type=float, default=0) + + parser.add_argument('--warmup_lr', type=float, default=1e-6, metavar='LR', + help='warmup learning rate (default: 1e-6)') + parser.add_argument('--min_lr', type=float, default=1e-6, metavar='LR', + help='lower lr bound for cyclic schedulers that hit 0 (1e-6)') + parser.add_argument('--warmup_epochs', type=int, default=5, metavar='N', + help='epochs to warmup LR, if scheduler supports') + parser.add_argument('--warmup_steps', type=int, default=-1, metavar='N', + help='num of steps to warmup LR, will overload warmup_epochs if set > 0') + + parser.add_argument('--batch_size', default=64, type=int) + parser.add_argument('--eval_batch_size', default=None, type=int) + parser.add_argument('--epochs', default=20, type=int) + parser.add_argument('--update_freq', default=1, type=int) + parser.add_argument('--save_ckpt_freq', default=5, type=int) + + # Augmentation parameters + parser.add_argument('--randaug', action='store_true', default=False) + parser.add_argument('--train_interpolation', type=str, default='bicubic', + help='Training interpolation (random, bilinear, bicubic default: "bicubic")') + + # Finetuning params + parser.add_argument('--finetune', default='', + help='finetune from checkpoint') + parser.add_argument('--model_key', default='model|module', type=str) + parser.add_argument('--model_prefix', default='', type=str) + + # Dataset parameters + parser.add_argument('--data_path', default='/datasets01/imagenet_full_size/061417/', type=str, + help='dataset path') + + parser.add_argument('--output_dir', default='', + help='path where to save, empty for no saving') + parser.add_argument('--log_dir', default=None, + help='path where to tensorboard log') + parser.add_argument('--device', default='cuda', + help='device to use for training / testing') + parser.add_argument('--seed', default=0, type=int) + parser.add_argument('--resume', default='', + help='resume from checkpoint') + parser.add_argument('--auto_resume', action='store_true') + parser.add_argument('--no_auto_resume', action='store_false', dest='auto_resume') + parser.set_defaults(auto_resume=True) + + parser.add_argument('--save_ckpt', action='store_true') + parser.add_argument('--no_save_ckpt', action='store_false', dest='save_ckpt') + parser.set_defaults(save_ckpt=True) + + parser.add_argument('--start_epoch', default=0, type=int, metavar='N', + help='start epoch') + parser.add_argument('--eval', action='store_true', + help='Perform evaluation only') + parser.add_argument('--dist_eval', action='store_true', default=False, + help='Enabling distributed evaluation') + parser.add_argument('--num_workers', default=10, type=int) + parser.add_argument('--pin_mem', action='store_true', + help='Pin CPU memory in DataLoader for more efficient (sometimes) transfer to GPU.') + parser.add_argument('--no_pin_mem', action='store_false', dest='pin_mem') + parser.set_defaults(pin_mem=True) + + # distributed training parameters + parser.add_argument('--world_size', default=1, type=int, + help='number of distributed processes') + parser.add_argument('--local_rank', default=-1, type=int) + parser.add_argument('--dist_on_itp', action='store_true') + parser.add_argument('--dist_url', default='env://', + help='url used to set up distributed training') + + # parameter for dump predictions (VQA, COCO captioning, NoCaps) + parser.add_argument('--task_cache_path', default=None, type=str) + + # parameter for imagenet finetuning + parser.add_argument('--nb_classes', default=1000, type=int, + help='number of the classification types') + parser.add_argument('--mixup', type=float, default=0, + help='mixup alpha, mixup enabled if > 0.') + parser.add_argument('--cutmix', type=float, default=0, + help='cutmix alpha, cutmix enabled if > 0.') + parser.add_argument('--cutmix_minmax', type=float, nargs='+', default=None, + help='cutmix min/max ratio, overrides alpha and enables cutmix if set (default: None)') + parser.add_argument('--mixup_prob', type=float, default=1.0, + help='Probability of performing mixup or cutmix when either/both is enabled') + parser.add_argument('--mixup_switch_prob', type=float, default=0.5, + help='Probability of switching to cutmix when both mixup and cutmix enabled') + parser.add_argument('--mixup_mode', type=str, default='batch', + help='How to apply mixup/cutmix params. Per "batch", "pair", or "elem"') + + # augmentation parameters for imagenet finetuning + parser.add_argument('--color_jitter', type=float, default=0.4, metavar='PCT', + help='Color jitter factor (default: 0.4)') + parser.add_argument('--aa', type=str, default='rand-m9-mstd0.5-inc1', metavar='NAME', + help='Use AutoAugment policy. "v0" or "original". " + "(default: rand-m9-mstd0.5-inc1)') + parser.add_argument('--smoothing', type=float, default=0.1, + help='Label smoothing (default: 0.1)') + + # evaluation parameters for imagenet + parser.add_argument('--crop_pct', type=float, default=None) + + # random Erase params for imagenet finetuning + parser.add_argument('--reprob', type=float, default=0.25, metavar='PCT', + help='Random erase prob (default: 0.25)') + parser.add_argument('--remode', type=str, default='pixel', + help='Random erase mode (default: "pixel")') + parser.add_argument('--recount', type=int, default=1, + help='Random erase count (default: 1)') + parser.add_argument('--resplit', action='store_true', default=False, + help='Do not random erase first (clean) augmentation split') + + # parameter for captioning finetuning + parser.add_argument('--captioning_mask_prob', type=float, default=0.6) + parser.add_argument('--drop_worst_ratio', type=float, default=0.2) + parser.add_argument('--drop_worst_after', type=int, default=12000) + parser.add_argument('--num_beams', type=int, default=3) + parser.add_argument('--length_penalty', type=float, default=0.6) + + # label smoothing for imagenet and captioning + parser.add_argument('--label_smoothing', type=float, default=0.1) + + # deepspeed parameters + parser.add_argument('--enable_deepspeed', action='store_true', default=False) + parser.add_argument('--initial_scale_power', type=int, default=16) + parser.add_argument('--zero_stage', default=0, type=int, + help='ZeRO optimizer stage (default: 0)') + + known_args, _ = parser.parse_known_args() + + if known_args.enable_deepspeed: + try: + import deepspeed + from deepspeed import DeepSpeedConfig + parser = deepspeed.add_config_arguments(parser) + ds_init = deepspeed.initialize + except: + print("Please 'pip install deepspeed==0.4.0'") + exit(0) + else: + ds_init = None + + return parser.parse_args(), ds_init + + +def main(args, ds_init): + utils.init_distributed_mode(args) + + if ds_init is not None: + utils.create_ds_config(args) + + if args.task_cache_path is None: + args.task_cache_path = args.output_dir + + print(args) + + device = torch.device(args.device) + + # fix the seed for reproducibility + seed = args.seed + utils.get_rank() + torch.manual_seed(seed) + np.random.seed(seed) + # random.seed(seed) + + cudnn.benchmark = True + + if utils.get_rank() == 0 and args.log_dir is not None: + os.makedirs(args.log_dir, exist_ok=True) + log_writer = utils.TensorboardLogger(log_dir=args.log_dir) + else: + log_writer = None + + data_loader_train, data_loader_val = create_downstream_dataset(args) + + if not args.model.endswith(args.task): + if args.task in ("flickr30k", "coco_retrieval"): + model_config = "%s_retrieval" % args.model + elif args.task in ("coco_captioning", "nocaps"): + model_config = "%s_captioning" % args.model + elif args.task in ("imagenet"): + model_config = "%s_imageclassification" % args.model + else: + model_config = "%s_%s" % (args.model, args.task) + else: + model_config = args.model + print("model_config = %s" % model_config) + model = create_model( + model_config, + pretrained=False, + drop_path_rate=args.drop_path, + vocab_size=args.vocab_size, + checkpoint_activations=args.checkpoint_activations, + ) + + if args.finetune: + utils.load_model_and_may_interpolate(args.finetune, model, args.model_key, args.model_prefix) + + model.to(device) + + model_ema = None + if args.model_ema: + # Important to create EMA model after cuda(), DP wrapper, and AMP but before SyncBN and DDP wrapper + model_ema = ModelEma( + model, + decay=args.model_ema_decay, + device='cpu' if args.model_ema_force_cpu else '', + resume='') + print("Using EMA with decay = %.8f" % args.model_ema_decay) + + model_without_ddp = model + n_parameters = sum(p.numel() for p in model.parameters() if p.requires_grad) + + print("Model = %s" % str(model_without_ddp)) + print('number of params:', n_parameters) + + total_batch_size = args.batch_size * args.update_freq * utils.get_world_size() + num_training_steps_per_epoch = len(data_loader_train.dataset) // total_batch_size + print("LR = %.8f" % args.lr) + print("Batch size = %d" % total_batch_size) + print("Update frequent = %d" % args.update_freq) + print("Number of training examples = %d" % len(data_loader_train.dataset)) + print("Number of training training per epoch = %d" % num_training_steps_per_epoch) + + num_layers = model_without_ddp.get_num_layers() + if args.layer_decay < 1.0: + lrs = list(args.layer_decay ** (num_layers + 1 - i) for i in range(num_layers + 2)) + assigner = LayerDecayValueAssigner(lrs) + elif args.task_head_lr_weight > 1: + assigner = LayerDecayValueAssigner([1.0, args.task_head_lr_weight], scale_handler=get_is_head_flag_for_vit) + else: + assigner = None + + if assigner is not None: + print("Assigned values = %s" % str(assigner.values)) + + skip_weight_decay_list = model.no_weight_decay() + + if args.distributed: + torch.distributed.barrier() + if args.enable_deepspeed: + loss_scaler = None + optimizer_params = get_parameter_groups( + model, args.weight_decay, skip_weight_decay_list, + assigner.get_layer_id if assigner is not None else None, + assigner.get_scale if assigner is not None else None) + model, optimizer, _, _ = ds_init( + args=args, model=model, model_parameters=optimizer_params, + dist_init_required=not args.distributed, + ) + + print("model.gradient_accumulation_steps() = %d" % model.gradient_accumulation_steps()) + assert model.gradient_accumulation_steps() == args.update_freq + else: + if args.distributed: + model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.gpu], find_unused_parameters=True) + model_without_ddp = model.module + + optimizer = create_optimizer( + args, model_without_ddp, skip_list=skip_weight_decay_list, + get_num_layer=assigner.get_layer_id if assigner is not None else None, + get_layer_scale=assigner.get_scale if assigner is not None else None) + loss_scaler = NativeScaler() + + lr_schedule_values = utils.cosine_scheduler( + args.lr, args.min_lr, args.epochs, num_training_steps_per_epoch, + warmup_epochs=args.warmup_epochs, warmup_steps=args.warmup_steps, + ) + + utils.auto_load_model( + args=args, model=model, model_without_ddp=model_without_ddp, + optimizer=optimizer, loss_scaler=loss_scaler, model_ema=model_ema) + + task_handler = get_handler(args) + + # mixup for imagenet + mixup_fn = None + if args.task in ["imagenet", "in1k"]: + mixup_active = args.mixup > 0 or args.cutmix > 0. or args.cutmix_minmax is not None + if mixup_active: + print("Mixup is activated!") + mixup_fn = Mixup( + mixup_alpha=args.mixup, cutmix_alpha=args.cutmix, cutmix_minmax=args.cutmix_minmax, + prob=args.mixup_prob, switch_prob=args.mixup_switch_prob, mode=args.mixup_mode, + label_smoothing=args.label_smoothing, num_classes=args.nb_classes) + + if args.eval: + data_loader_test = create_downstream_dataset(args, is_eval=True) + if args.task in ["nlvr2", "flickr30k", "coco_retrieval", "imagenet"]: + ext_test_stats, task_key = evaluate(data_loader_test, model, device, task_handler) + print(f"Accuracy of the network on the {len(data_loader_test.dataset)} test images: {ext_test_stats[task_key]:.3f}%") + exit(0) + elif args.task == "vqav2": + result, _ = evaluate(data_loader_test, model, device, task_handler) + utils.dump_predictions(args, result, "vqav2_test") + exit(0) + elif args.task in ["coco_captioning", "nocaps"]: + predictions, _ = evaluate(data_loader_test, model, device, task_handler) + prediction_file = utils.dump_predictions(args, predictions, "{}_test".format(args.task)) + if utils.is_main_process() and args.task == "coco_captioning": + captioning_result = utils.coco_caption_eval(args.output_dir, prediction_file, "{}_test".format(args.task)) + result_file = os.path.join(args.output_dir, f"{args.task}_result.json") + print(json.dumps(captioning_result)) + utils.write_result_to_jsonl(captioning_result, result_file) + exit(0) + + print(f"Start training for {args.epochs} epochs") + start_time = time.time() + + max_accuracy = 0.0 + for epoch in range(args.start_epoch, args.epochs): + if args.distributed: + data_loader_train.sampler.set_epoch(epoch) + if log_writer is not None: + log_writer.set_step(epoch * num_training_steps_per_epoch * args.update_freq) + train_stats = train_one_epoch( + model, data_loader_train, optimizer, device, task_handler, epoch, + epoch * num_training_steps_per_epoch, lr_schedule_values, loss_scaler, + args.clip_grad, args.update_freq, model_ema, log_writer, args.task, mixup_fn, + ) + if args.output_dir and args.save_ckpt: + if (epoch + 1) % args.save_ckpt_freq == 0 or epoch + 1 == args.epochs: + utils.save_model( + args=args, model=model, model_without_ddp=model_without_ddp, optimizer=optimizer, + loss_scaler=loss_scaler, epoch=epoch, model_ema=model_ema) + if data_loader_val is not None: + if args.task not in ["coco_captioning", "nocaps"]: + test_stats, task_key = evaluate(data_loader_val, model, device, task_handler) + else: + predictions, _ = evaluate(data_loader_val, model, device, task_handler) + prediction_file = utils.dump_predictions(args, predictions, f"{args.task}_val_e{epoch}") + result_file = os.path.join(args.output_dir, f"{args.task}_result_val_e{epoch}.json") + task_key = "CIDEr" + if utils.is_main_process(): + test_stats = utils.coco_caption_eval(args.output_dir, prediction_file, "{}_val".format(args.task)) + utils.write_result_to_jsonl(test_stats, result_file) + torch.distributed.barrier() + if not utils.is_main_process(): + test_stats = utils.read_result_from_jsonl(result_file) + + print(f"Performance of the network on the {len(data_loader_val.dataset)} val images: {test_stats[task_key]:.1f}%") + if max_accuracy < test_stats[task_key]: + max_accuracy = test_stats[task_key] + if args.output_dir and args.save_ckpt: + utils.save_model( + args=args, model=model, model_without_ddp=model_without_ddp, optimizer=optimizer, + loss_scaler=loss_scaler, epoch="best", model_ema=model_ema) + + print(f'Max performance: {max_accuracy:.2f}%') + if log_writer is not None: + log_writer.update(acc=test_stats[task_key], head="perf", step=epoch) + + log_stats = {**{f'train_{k}': v for k, v in train_stats.items()}, + **{f'val_{k}': v for k, v in test_stats.items()}, + 'epoch': epoch, + 'n_parameters': n_parameters} + else: + log_stats = {**{f'train_{k}': v for k, v in train_stats.items()}, + # **{f'test_{k}': v for k, v in test_stats.items()}, + 'epoch': epoch, + 'n_parameters': n_parameters} + + if args.output_dir and utils.is_main_process(): + if log_writer is not None: + log_writer.flush() + with open(os.path.join(args.output_dir, "log.txt"), mode="a", encoding="utf-8") as f: + f.write(json.dumps(log_stats) + "\n") + + total_time = time.time() - start_time + total_time_str = str(datetime.timedelta(seconds=int(total_time))) + print('Training time {}'.format(total_time_str)) + + +if __name__ == '__main__': + opts, ds_init = get_args() + if opts.output_dir: + Path(opts.output_dir).mkdir(parents=True, exist_ok=True) + main(opts, ds_init) diff --git a/py/evf_sam/model/unilm/beit3/utils.py b/py/evf_sam/model/unilm/beit3/utils.py new file mode 100644 index 0000000..ca052f0 --- /dev/null +++ b/py/evf_sam/model/unilm/beit3/utils.py @@ -0,0 +1,913 @@ +# -------------------------------------------------------- +# Image as a Foreign Language: BEiT Pretraining for Vision and Vision-Language Tasks (https://arxiv.org/abs/2208.10442) +# Github source: https://github.com/microsoft/unilm/tree/master/beit3 +# Copyright (c) 2023 Microsoft +# Licensed under The MIT License [see LICENSE for details] +# --------------------------------------------------------' + +import datetime +import io +import os +import math +import time +import json +import argparse +import numpy as np +from pathlib import Path +from collections import defaultdict, deque +from timm.utils import get_state_dict + +import torch +import torch.distributed as dist +import torch.nn as nn +import torch.nn.functional as F +from torch._six import inf +from torchmetrics import Metric +from tensorboardX import SummaryWriter + + +def bool_flag(s): + """ + Parse boolean arguments from the command line. + """ + FALSY_STRINGS = {"off", "false", "0"} + TRUTHY_STRINGS = {"on", "true", "1"} + if s.lower() in FALSY_STRINGS: + return False + elif s.lower() in TRUTHY_STRINGS: + return True + else: + raise argparse.ArgumentTypeError("invalid value for a boolean flag") + + +class SmoothedValue(object): + """Track a series of values and provide access to smoothed values over a + window or the global series average. + """ + + def __init__(self, window_size=20, fmt=None): + if fmt is None: + fmt = "{median:.4f} ({global_avg:.4f})" + self.deque = deque(maxlen=window_size) + self.total = 0.0 + self.count = 0 + self.fmt = fmt + + def update(self, value, n=1): + self.deque.append(value) + self.count += n + self.total += value * n + + def synchronize_between_processes(self): + """ + Warning: does not synchronize the deque! + """ + if not is_dist_avail_and_initialized(): + return + t = torch.tensor([self.count, self.total], dtype=torch.float64, device='cuda') + dist.barrier() + dist.all_reduce(t) + t = t.tolist() + self.count = int(t[0]) + self.total = t[1] + + @property + def median(self): + d = torch.tensor(list(self.deque)) + return d.median().item() + + @property + def avg(self): + d = torch.tensor(list(self.deque), dtype=torch.float32) + return d.mean().item() + + @property + def global_avg(self): + return self.total / self.count + + @property + def max(self): + return max(self.deque) + + @property + def value(self): + return self.deque[-1] + + def __str__(self): + return self.fmt.format( + median=self.median, + avg=self.avg, + global_avg=self.global_avg, + max=self.max, + value=self.value) + + +class MetricLogger(object): + def __init__(self, delimiter="\t"): + self.meters = defaultdict(SmoothedValue) + self.delimiter = delimiter + + def update(self, **kwargs): + for k, v in kwargs.items(): + if v is None: + continue + if isinstance(v, torch.Tensor): + v = v.item() + assert isinstance(v, (float, int)) + self.meters[k].update(v) + + def __getattr__(self, attr): + if attr in self.meters: + return self.meters[attr] + if attr in self.__dict__: + return self.__dict__[attr] + raise AttributeError("'{}' object has no attribute '{}'".format( + type(self).__name__, attr)) + + def __str__(self): + loss_str = [] + for name, meter in self.meters.items(): + loss_str.append( + "{}: {}".format(name, str(meter)) + ) + return self.delimiter.join(loss_str) + + def synchronize_between_processes(self): + for meter in self.meters.values(): + meter.synchronize_between_processes() + + def add_meter(self, name, meter): + self.meters[name] = meter + + def log_every(self, iterable, print_freq, header=None): + i = 0 + if not header: + header = '' + start_time = time.time() + end = time.time() + iter_time = SmoothedValue(fmt='{avg:.4f}') + data_time = SmoothedValue(fmt='{avg:.4f}') + space_fmt = ':' + str(len(str(len(iterable)))) + 'd' + log_msg = [ + header, + '[{0' + space_fmt + '}/{1}]', + 'eta: {eta}', + '{meters}', + 'time: {time}', + 'data: {data}' + ] + if torch.cuda.is_available(): + log_msg.append('max mem: {memory:.0f}') + log_msg = self.delimiter.join(log_msg) + MB = 1024.0 * 1024.0 + for obj in iterable: + data_time.update(time.time() - end) + yield obj + iter_time.update(time.time() - end) + if i % print_freq == 0 or i == len(iterable) - 1: + eta_seconds = iter_time.global_avg * (len(iterable) - i) + eta_string = str(datetime.timedelta(seconds=int(eta_seconds))) + if torch.cuda.is_available(): + print(log_msg.format( + i, len(iterable), eta=eta_string, + meters=str(self), + time=str(iter_time), data=str(data_time), + memory=torch.cuda.max_memory_allocated() / MB)) + else: + print(log_msg.format( + i, len(iterable), eta=eta_string, + meters=str(self), + time=str(iter_time), data=str(data_time))) + i += 1 + end = time.time() + total_time = time.time() - start_time + total_time_str = str(datetime.timedelta(seconds=int(total_time))) + print('{} Total time: {} ({:.4f} s / it)'.format( + header, total_time_str, total_time / len(iterable))) + + +class TensorboardLogger(object): + def __init__(self, log_dir): + self.writer = SummaryWriter(logdir=log_dir) + self.step = 0 + + def set_step(self, step=None): + if step is not None: + self.step = step + else: + self.step += 1 + + def update(self, head='scalar', step=None, **kwargs): + for k, v in kwargs.items(): + if v is None: + continue + if isinstance(v, torch.Tensor): + v = v.item() + assert isinstance(v, (float, int)) + self.writer.add_scalar(head + "/" + k, v, self.step if step is None else step) + + def flush(self): + self.writer.flush() + + +def _load_checkpoint_for_ema(model_ema, checkpoint): + """ + Workaround for ModelEma._load_checkpoint to accept an already-loaded object + """ + mem_file = io.BytesIO() + torch.save(checkpoint, mem_file) + mem_file.seek(0) + model_ema._load_checkpoint(mem_file) + + +def setup_for_distributed(is_master): + """ + This function disables printing when not in master process + """ + import builtins as __builtin__ + builtin_print = __builtin__.print + + def print(*args, **kwargs): + force = kwargs.pop('force', False) + if is_master or force: + builtin_print(*args, **kwargs) + + __builtin__.print = print + + +def is_dist_avail_and_initialized(): + if not dist.is_available(): + return False + if not dist.is_initialized(): + return False + return True + + +def get_world_size(): + if not is_dist_avail_and_initialized(): + return 1 + return dist.get_world_size() + + +def get_rank(): + if not is_dist_avail_and_initialized(): + return 0 + return dist.get_rank() + + +def is_main_process(): + return get_rank() == 0 + + +def save_on_master(*args, **kwargs): + if is_main_process(): + torch.save(*args, **kwargs) + + +def _get_rank_env(): + if "RANK" in os.environ: + return int(os.environ["RANK"]) + else: + return int(os.environ['OMPI_COMM_WORLD_RANK']) + + +def _get_local_rank_env(): + if "LOCAL_RANK" in os.environ: + return int(os.environ["LOCAL_RANK"]) + else: + return int(os.environ['OMPI_COMM_WORLD_LOCAL_RANK']) + + +def _get_world_size_env(): + if "WORLD_SIZE" in os.environ: + return int(os.environ["WORLD_SIZE"]) + else: + return int(os.environ['OMPI_COMM_WORLD_SIZE']) + + +# The implementation code is modified from DeiT (https://github.com/facebookresearch/deit.git) +def init_distributed_mode(args): + if args.dist_on_itp: + args.rank = _get_rank_env() + args.world_size = _get_world_size_env() # int(os.environ['OMPI_COMM_WORLD_SIZE']) + args.gpu = _get_local_rank_env() + args.dist_url = "tcp://%s:%s" % (os.environ['MASTER_ADDR'], os.environ['MASTER_PORT']) + os.environ['LOCAL_RANK'] = str(args.gpu) + os.environ['RANK'] = str(args.rank) + os.environ['WORLD_SIZE'] = str(args.world_size) + # ["RANK", "WORLD_SIZE", "MASTER_ADDR", "MASTER_PORT", "LOCAL_RANK"] + elif 'RANK' in os.environ and 'WORLD_SIZE' in os.environ: + args.rank = int(os.environ["RANK"]) + args.world_size = int(os.environ['WORLD_SIZE']) + args.gpu = int(os.environ['LOCAL_RANK']) + elif 'SLURM_PROCID' in os.environ: + args.rank = int(os.environ['SLURM_PROCID']) + args.gpu = args.rank % torch.cuda.device_count() + else: + print('Not using distributed mode') + args.distributed = False + return + + args.distributed = True + + torch.cuda.set_device(args.gpu) + args.dist_backend = 'nccl' + print('| distributed init (rank {}): {}, gpu {}'.format( + args.rank, args.dist_url, args.gpu), flush=True) + torch.distributed.init_process_group( + backend=args.dist_backend, init_method=args.dist_url, + world_size=args.world_size, rank=args.rank, + timeout=datetime.timedelta(0, 7200) + ) + torch.distributed.barrier() + setup_for_distributed(args.rank == 0) + + +def load_state_dict(model, state_dict, prefix='', ignore_missing="relative_position_index"): + missing_keys = [] + unexpected_keys = [] + error_msgs = [] + # copy state_dict so _load_from_state_dict can modify it + metadata = getattr(state_dict, '_metadata', None) + state_dict = state_dict.copy() + if metadata is not None: + state_dict._metadata = metadata + + def load(module, prefix=''): + local_metadata = {} if metadata is None else metadata.get( + prefix[:-1], {}) + module._load_from_state_dict( + state_dict, prefix, local_metadata, True, missing_keys, unexpected_keys, error_msgs) + for name, child in module._modules.items(): + if child is not None: + load(child, prefix + name + '.') + + load(model, prefix=prefix) + + warn_missing_keys = [] + ignore_missing_keys = [] + for key in missing_keys: + keep_flag = True + for ignore_key in ignore_missing.split('|'): + if ignore_key in key: + keep_flag = False + break + if keep_flag: + warn_missing_keys.append(key) + else: + ignore_missing_keys.append(key) + + missing_keys = warn_missing_keys + + if len(missing_keys) > 0: + print("Weights of {} not initialized from pretrained model: {}".format( + model.__class__.__name__, missing_keys)) + if len(unexpected_keys) > 0: + print("Weights from pretrained model not used in {}: {}".format( + model.__class__.__name__, unexpected_keys)) + if len(ignore_missing_keys) > 0: + print("Ignored weights of {} not initialized from pretrained model: {}".format( + model.__class__.__name__, ignore_missing_keys)) + if len(error_msgs) > 0: + print('\n'.join(error_msgs)) + + +class NativeScalerWithGradNormCount: + state_dict_key = "amp_scaler" + + def __init__(self): + self._scaler = torch.cuda.amp.GradScaler() + + def __call__(self, loss, optimizer, clip_grad=None, parameters=None, create_graph=False, update_grad=True): + self._scaler.scale(loss).backward(create_graph=create_graph) + if update_grad: + if clip_grad is not None: + assert parameters is not None + self._scaler.unscale_(optimizer) # unscale the gradients of optimizer's assigned params in-place + norm = torch.nn.utils.clip_grad_norm_(parameters, clip_grad) + else: + self._scaler.unscale_(optimizer) + norm = get_grad_norm_(parameters) + self._scaler.step(optimizer) + self._scaler.update() + else: + norm = None + return norm + + def state_dict(self): + return self._scaler.state_dict() + + def load_state_dict(self, state_dict): + self._scaler.load_state_dict(state_dict) + + +def get_grad_norm_(parameters, norm_type: float = 2.0) -> torch.Tensor: + if isinstance(parameters, torch.Tensor): + parameters = [parameters] + parameters = [p for p in parameters if p.grad is not None] + norm_type = float(norm_type) + if len(parameters) == 0: + return torch.tensor(0.) + device = parameters[0].grad.device + if norm_type == inf: + total_norm = max(p.grad.detach().abs().max().to(device) for p in parameters) + else: + total_norm = torch.norm(torch.stack([torch.norm(p.grad.detach(), norm_type).to(device) for p in parameters]), norm_type) + return total_norm + + +def cosine_scheduler(base_value, final_value, epochs, niter_per_ep, warmup_epochs=0, + start_warmup_value=0, warmup_steps=-1, sched_type="cos"): + warmup_schedule = np.array([]) + warmup_iters = warmup_epochs * niter_per_ep + if warmup_steps > 0: + warmup_iters = warmup_steps + print("Set warmup steps = %d" % warmup_iters) + if warmup_epochs > 0: + warmup_schedule = np.linspace(start_warmup_value, base_value, warmup_iters) + + if sched_type == "cos": + iters = np.arange(epochs * niter_per_ep - warmup_iters) + schedule = np.array([ + final_value + 0.5 * (base_value - final_value) * (1 + math.cos(math.pi * i / (len(iters)))) for i in iters]) + elif sched_type == "linear": + schedule = np.linspace(base_value, final_value, epochs * niter_per_ep - warmup_iters) + else: + raise NotImplementedError() + + schedule = np.concatenate((warmup_schedule, schedule)) + + assert len(schedule) == epochs * niter_per_ep + return schedule + + +def save_model(args, epoch, model, model_without_ddp, optimizer, loss_scaler, model_ema=None): + output_dir = Path(args.output_dir) + if loss_scaler is not None: + checkpoint_paths = [output_dir / ('checkpoint-%s.pth' % epoch)] + for checkpoint_path in checkpoint_paths: + to_save = { + 'model': model_without_ddp.state_dict(), + 'optimizer': optimizer.state_dict(), + 'epoch': epoch, + 'scaler': loss_scaler.state_dict(), + 'args': args, + } + + if model_ema is not None: + to_save['model_ema'] = get_state_dict(model_ema) + + save_on_master(to_save, checkpoint_path) + else: + client_state = {'epoch': epoch, "args": args} + if model_ema is not None: + client_state['model_ema'] = get_state_dict(model_ema) + model.save_checkpoint(save_dir=args.output_dir, tag="checkpoint-%s" % epoch, client_state=client_state) + + +def auto_load_model(args, model, model_without_ddp, optimizer, loss_scaler, model_ema=None): + output_dir = Path(args.output_dir) + if loss_scaler is not None: + # torch.amp + if args.auto_resume and len(args.resume) == 0: + import glob + all_checkpoints = glob.glob(os.path.join(output_dir, 'checkpoint-*.pth')) + latest_ckpt = -1 + for ckpt in all_checkpoints: + t = ckpt.split('-')[-1].split('.')[0] + if t.isdigit(): + latest_ckpt = max(int(t), latest_ckpt) + if latest_ckpt >= 0: + args.resume = os.path.join(output_dir, 'checkpoint-%d.pth' % latest_ckpt) + print("Auto resume checkpoint: %s" % args.resume) + + if args.resume: + if args.resume.startswith('https'): + checkpoint = torch.hub.load_state_dict_from_url( + args.resume, map_location='cpu', check_hash=True) + else: + checkpoint = torch.load(args.resume, map_location='cpu') + model_without_ddp.load_state_dict(checkpoint['model']) + print("Resume checkpoint %s" % args.resume) + if 'optimizer' in checkpoint and 'epoch' in checkpoint: + optimizer.load_state_dict(checkpoint['optimizer']) + args.start_epoch = checkpoint['epoch'] + 1 + if hasattr(args, 'model_ema') and args.model_ema: + _load_checkpoint_for_ema(model_ema, checkpoint['model_ema']) + if 'scaler' in checkpoint: + loss_scaler.load_state_dict(checkpoint['scaler']) + print("With optim & sched!") + else: + # deepspeed, only support '--auto_resume'. + if args.auto_resume: + import glob + all_checkpoints = glob.glob(os.path.join(output_dir, 'checkpoint-*')) + latest_ckpt = -1 + for ckpt in all_checkpoints: + t = ckpt.split('-')[-1].split('.')[0] + if t.isdigit(): + latest_ckpt = max(int(t), latest_ckpt) + if latest_ckpt >= 0: + args.resume = os.path.join(output_dir, 'checkpoint-%d' % latest_ckpt) + print("Auto resume checkpoint: %d" % latest_ckpt) + _, client_states = model.load_checkpoint(args.output_dir, tag='checkpoint-%d' % latest_ckpt) + args.start_epoch = client_states['epoch'] + 1 + if model_ema is not None: + if args.model_ema: + _load_checkpoint_for_ema(model_ema, client_states['model_ema']) + + +# The implementation code is modified from DeiT (https://github.com/facebookresearch/deit.git) +def load_model_and_may_interpolate(ckpt_path, model, model_key, model_prefix): + if ckpt_path.startswith('https'): + checkpoint = torch.hub.load_state_dict_from_url( + ckpt_path, map_location='cpu', check_hash=True) + else: + checkpoint = torch.load(ckpt_path, map_location='cpu') + + print("Load ckpt from %s" % ckpt_path) + checkpoint_model = None + for model_key in model_key.split('|'): + if model_key in checkpoint: + checkpoint_model = checkpoint[model_key] + print("Load state_dict by model_key = %s" % model_key) + break + + if checkpoint_model is None: + checkpoint_model = checkpoint + + state_dict = model.state_dict() + for k in ['head.weight', 'head.bias']: + if k in checkpoint_model and checkpoint_model[k].shape != state_dict[k].shape: + print(f"Removing key {k} from pretrained checkpoint") + del checkpoint_model[k] + + # interpolate position embedding + for pos_embed_key in ("vision_pos_embed", "pos_embed", "beit3.encoder.embed_positions.A.weight"): + if pos_embed_key in checkpoint_model: + pos_embed_checkpoint = checkpoint_model[pos_embed_key] + embedding_size = pos_embed_checkpoint.shape[-1] + if pos_embed_key == "beit3.encoder.embed_positions.A.weight": + # being consistent with Fairseq, which starts from 2 for position embedding + torchscale_model = True + num_patches = model.beit3.vision_embed.num_patches + num_extra_tokens = model.beit3.vision_embed.num_position_embeddings() + 2 - num_patches + else: + torchscale_model = False + num_patches = model.patch_embed.num_patches + num_extra_tokens = getattr(model, pos_embed_key).shape[-2] - num_patches + # height (== width) for the checkpoint position embedding + orig_size = int((pos_embed_checkpoint.shape[-2] - num_extra_tokens) ** 0.5) + # height (== width) for the new position embedding + new_size = int(num_patches ** 0.5) + # class_token and dist_token are kept unchanged + if orig_size != new_size: + print("Position interpolate from %dx%d to %dx%d" % (orig_size, orig_size, new_size, new_size)) + if torchscale_model: + extra_tokens = pos_embed_checkpoint[:num_extra_tokens].unsqueeze(0) + # only the position tokens are interpolated + pos_tokens = pos_embed_checkpoint[num_extra_tokens:] + else: + extra_tokens = pos_embed_checkpoint[:, :num_extra_tokens] + # only the position tokens are interpolated + pos_tokens = pos_embed_checkpoint[:, num_extra_tokens:] + pos_tokens = pos_tokens.reshape(-1, orig_size, orig_size, embedding_size).permute(0, 3, 1, 2) + pos_tokens = torch.nn.functional.interpolate( + pos_tokens, size=(new_size, new_size), mode='bicubic', align_corners=False) + pos_tokens = pos_tokens.permute(0, 2, 3, 1).flatten(1, 2) + new_pos_embed = torch.cat((extra_tokens, pos_tokens), dim=1) + if torchscale_model: + new_pos_embed = new_pos_embed.squeeze(0) + checkpoint_model[pos_embed_key] = new_pos_embed + + load_state_dict(model, checkpoint_model, prefix=model_prefix) + + +def create_ds_config(args): + args.deepspeed_config = os.path.join(args.output_dir, "deepspeed_config.json") + with open(args.deepspeed_config, mode="w") as writer: + ds_config = { + "train_batch_size": args.batch_size * args.update_freq * get_world_size(), + "train_micro_batch_size_per_gpu": args.batch_size, + "steps_per_print": 1000, + "optimizer": { + "type": "Adam", + "adam_w_mode": True, + "params": { + "lr": args.lr, + "weight_decay": args.weight_decay, + "bias_correction": True, + "betas": [ + args.opt_betas[0], + args.opt_betas[1] + ], + "eps": args.opt_eps + } + }, + "fp16": { + "enabled": True, + "loss_scale": 0, + "initial_scale_power": getattr(args, "initial_scale_power", 12), + "loss_scale_window": 1000, + "hysteresis": 2, + "min_loss_scale": 1 + }, + "amp": { + "enabled": False, + "opt_level": "O2" + } + } + + if args.clip_grad is not None: + ds_config.update({'gradient_clipping': args.clip_grad}) + + if args.zero_stage == 1: + ds_config.update({"zero_optimization": {"stage": args.zero_stage, "reduce_bucket_size": 5e8}}) + elif args.zero_stage > 1: + raise NotImplementedError() + + writer.write(json.dumps(ds_config, indent=2)) + + +def merge_batch_tensors_by_dict_key(batch): + batch_tensors = {} + for tensor_key in batch[0]: + if isinstance(batch[0][tensor_key], torch.Tensor): + batch_tensors[tensor_key] = torch.stack([d[tensor_key] for d in batch]) + else: + batch_tensors[tensor_key] = torch.tensor([d[tensor_key] for d in batch], dtype=torch.long) + return batch_tensors + + +def get_loss_scale_for_deepspeed(model): + optimizer = model.optimizer + loss_scale = None + if hasattr(optimizer, 'loss_scale'): + loss_scale = optimizer.loss_scale + elif hasattr(optimizer, 'cur_scale'): + loss_scale = optimizer.cur_scale + return loss_scale + + +class GatherLayer(torch.autograd.Function): + """ + Gather tensors from all workers with support for backward propagation: + This implementation does not cut the gradients as torch.distributed.all_gather does. + """ + @staticmethod + def forward(ctx, x): + output = [torch.zeros_like(x) for _ in range(dist.get_world_size())] + dist.all_gather(output, x) + return tuple(output) + @staticmethod + def backward(ctx, *grads): + all_gradients = torch.stack(grads) + dist.all_reduce(all_gradients) + return all_gradients[dist.get_rank()] + + +def gather_features( + image_features, + text_features, +): + gathered_image_features = GatherLayer.apply(image_features) + gathered_text_features = GatherLayer.apply(text_features) + all_image_features = torch.cat(gathered_image_features) + all_text_features = torch.cat(gathered_text_features) + + return all_image_features, all_text_features + + +# The implementation code is modified from open_clip (https://github.com/mlfoundations/open_clip.git) +class ClipLoss(nn.Module): + + def __init__( + self, + cache_labels=False, + rank=0, + world_size=1, + ): + super().__init__() + self.cache_labels = cache_labels + self.rank = rank + self.world_size = world_size + + # cache state + self.prev_num_logits = 0 + self.labels = {} + + def forward(self, image_features, text_features, logit_scale): + device = image_features.device + if self.world_size > 1: + all_image_features, all_text_features = gather_features( + image_features, text_features + ) + + logits_per_image = logit_scale * image_features @ all_text_features.T + logits_per_text = logit_scale * text_features @ all_image_features.T + else: + logits_per_image = logit_scale * image_features @ text_features.T + logits_per_text = logit_scale * text_features @ image_features.T + + # calculated ground-truth and cache if enabled + num_logits = logits_per_image.shape[0] + if self.prev_num_logits != num_logits or device not in self.labels: + labels = torch.arange(num_logits, device=device, dtype=torch.long) + if self.world_size > 1: + labels = labels + num_logits * self.rank + if self.cache_labels: + self.labels[device] = labels + self.prev_num_logits = num_logits + else: + labels = self.labels[device] + + total_loss = ( + F.cross_entropy(logits_per_image, labels) + + F.cross_entropy(logits_per_text, labels) + ) / 2 + return total_loss, logits_per_image, logits_per_text + + +def write_result_to_jsonl(test_stats, result_file): + with open(result_file, mode="w", encoding="utf-8") as writer: + writer.write(json.dumps(test_stats, indent=None)) + + +def read_result_from_jsonl(result_file): + with open(result_file, mode="r", encoding="utf-8") as reader: + return json.load(reader) + + +# The implementation code is from ViLT (https://github.com/dandelin/ViLT.git) +class VQAScore(Metric): + def __init__(self, dist_sync_on_step=False): + super().__init__(dist_sync_on_step=dist_sync_on_step) + self.add_state("score", default=torch.tensor(0.0), dist_reduce_fx="sum") + self.add_state("total", default=torch.tensor(0.0), dist_reduce_fx="sum") + + def update(self, logits, target): + logits, target = ( + logits.detach().float().to(self.score.device), + target.detach().float().to(self.score.device), + ) + logits = torch.max(logits, 1)[1] + one_hots = torch.zeros(*target.size()).to(target) + one_hots.scatter_(1, logits.view(-1, 1), 1) + scores = one_hots * target + + self.score += scores.sum() + self.total += len(logits) + + def compute(self): + return self.score / self.total + + +class BertCaptioningLoss(nn.Module): + def __init__(self, label_smoothing, drop_worst_ratio, drop_worst_after): + super().__init__() + self.label_smoothing = label_smoothing + self.drop_worst_ratio = drop_worst_ratio + self.drop_worst_after = drop_worst_after + self.log_soft = nn.LogSoftmax(dim=1) + self.kl = nn.KLDivLoss(reduction='none') + self.iter = 0 + + def forward(self, logits, target, iter): + eps = self.label_smoothing + n_class = logits.size(1) + one_hot = torch.zeros_like(logits).scatter(1, target.view(-1, 1), 1) + one_hot = one_hot * (1 - eps) + (1 - one_hot) * eps / (n_class - 1) + log_prb = self.log_soft(logits) + loss = self.kl(log_prb, one_hot).sum(1) + + if self.drop_worst_ratio > 0 and iter > self.drop_worst_after: + loss, _ = torch.topk(loss, + k=int(loss.shape[0] * (1-self.drop_worst_ratio)), + largest=False) + loss = loss.mean() + + return loss + + +class BeamHypotheses(object): + def __init__(self, n_hyp, max_length, length_penalty, early_stopping): + """ + Initialize n-best list of hypotheses. + """ + self.max_length = max_length - 1 # ignoring bos_token + self.length_penalty = length_penalty + self.early_stopping = early_stopping + self.n_hyp = n_hyp + self.hyp = [] + self.worst_score = 1e9 + + def __len__(self): + """ + Number of hypotheses in the list. + """ + return len(self.hyp) + + def add(self, hyp, sum_logprobs): + """ + Add a new hypothesis to the list. + """ + score = sum_logprobs / len(hyp) ** self.length_penalty + if len(self) < self.n_hyp or score > self.worst_score: + self.hyp.append((score, hyp)) + if len(self) > self.n_hyp: + sorted_scores = sorted([(s, idx) for idx, (s, _) in enumerate(self.hyp)]) + del self.hyp[sorted_scores[0][1]] + self.worst_score = sorted_scores[1][0] + else: + self.worst_score = min(score, self.worst_score) + + def is_done(self, best_sum_logprobs): + """ + If there are enough hypotheses and that none of the hypotheses being generated + can become better than the worst one in the heap, then we are done with this sentence. + """ + if len(self) < self.n_hyp: + return False + elif self.early_stopping: + return True + else: + return self.worst_score >= best_sum_logprobs / self.max_length ** self.length_penalty + + +def dump_predictions(args, result, file_suffix): + global_rank = get_rank() + jsons = None + if global_rank >= 0: + output_file = os.path.join(args.task_cache_path, f"submit_{global_rank}_{file_suffix}.json") + with open(output_file, "w") as fp: + json.dump(result, fp, indent=2) + torch.distributed.barrier() + + if global_rank == 0: + world_size = get_world_size() + jsons = [] + for i in range(world_size): + each_file = os.path.join(args.task_cache_path, f"submit_{i}_{file_suffix}.json") + with open(each_file, "r") as fp: + jsons += json.load(fp) + + new_jsons = [] + res_dict = dict() + if args.task in ["coco_captioning", "nocaps"]: + qid_key = "image_id" + else: + # for VQAv2 + qid_key = "question_id" + for item in jsons: + if item[qid_key] in res_dict: + continue + new_jsons.append(item) + res_dict[item[qid_key]] = item + jsons = new_jsons + + torch.distributed.barrier() + os.remove(output_file) + else: + jsons = result + + result_file = os.path.join(args.output_dir, f"submit_{file_suffix}.json") + if jsons is not None: + with open(result_file, "w") as fp: + json.dump(jsons, fp, indent=2) + print("Infer %d examples into %s" % (len(jsons), result_file)) + return result_file + + +# The evaluation code is from BLIP (https://github.com/salesforce/BLIP) +# For nocaps, please submit the prediction file to the evaluate server (https://eval.ai/web/challenges/challenge-page/355/overview) to obtain the final results +def coco_caption_eval(gt_dir, results_file, split): + from pycocotools.coco import COCO + from pycocoevalcap.eval import COCOEvalCap + from torchvision.datasets.utils import download_url + + urls = {'coco_captioning_val': 'https://storage.googleapis.com/sfr-vision-language-research/datasets/coco_karpathy_val_gt.json', + 'coco_captioning_test': 'https://storage.googleapis.com/sfr-vision-language-research/datasets/coco_karpathy_test_gt.json', + 'nocaps_val': 'https://github.com/addf400/files/releases/download/beit3/nocaps_val_gt.json'} + filenames = {'coco_captioning_val':'coco_karpathy_val_gt.json', + 'coco_captioning_test':'coco_karpathy_test_gt.json', + 'nocaps_val':'nocaps_val_gt.json'} + + download_url(urls[split], gt_dir) + annotation_file = os.path.join(gt_dir, filenames[split]) + + # create coco object and coco_result object + coco = COCO(annotation_file) + coco_result = coco.loadRes(results_file) + + # create coco_eval object by taking coco and coco_result + coco_eval = COCOEvalCap(coco, coco_result) + + # evaluate results + # SPICE will take a few minutes the first time, but speeds up due to caching + coco_eval.evaluate() + + res_dict = dict() + for metric, score in coco_eval.eval.items(): + res_dict[metric] = score + + return res_dict diff --git a/py/evf_sam/utils/ade20k_classes.json b/py/evf_sam/utils/ade20k_classes.json new file mode 100644 index 0000000..1f96e61 --- /dev/null +++ b/py/evf_sam/utils/ade20k_classes.json @@ -0,0 +1,30 @@ +[ + "wall", "building", "sky", "floor", "tree", "ceiling", "road", + "bed", "windowpane", "grass", "cabinet", "sidewalk", + "person", "earth", "door", "table", "mountain", "plant", + "curtain", "chair", "car", "water", "painting", "sofa", + "shelf", "house", "sea", "mirror", "rug", "field", "armchair", + "seat", "fence", "desk", "rock", "wardrobe", "lamp", + "bathtub", "railing", "cushion", "base", "box", "column", + "signboard", "chest of drawers", "counter", "sand", "sink", + "skyscraper", "fireplace", "refrigerator", "grandstand", + "path", "stairs", "runway", "case", "pool table", "pillow", + "screen door", "stairway", "river", "bridge", "bookcase", + "blind", "coffee table", "toilet", "flower", "book", "hill", + "bench", "countertop", "stove", "palm", "kitchen island", + "computer", "swivel chair", "boat", "bar", "arcade machine", + "hovel", "bus", "towel", "light", "truck", "tower", + "chandelier", "awning", "streetlight", "booth", + "television receiver", "airplane", "dirt track", "apparel", + "pole", "land", "bannister", "escalator", "ottoman", "bottle", + "buffet", "poster", "stage", "van", "ship", "fountain", + "conveyer belt", "canopy", "washer", "plaything", + "swimming pool", "stool", "barrel", "basket", "waterfall", + "tent", "bag", "minibike", "cradle", "oven", "ball", "food", + "step", "tank", "trade name", "microwave", "pot", "animal", + "bicycle", "lake", "dishwasher", "screen", "blanket", + "sculpture", "hood", "sconce", "vase", "traffic light", + "tray", "ashcan", "fan", "pier", "crt screen", "plate", + "monitor", "bulletin board", "shower", "radiator", "glass", + "clock", "flag" +] \ No newline at end of file diff --git a/py/evf_sam/utils/aug.py b/py/evf_sam/utils/aug.py new file mode 100644 index 0000000..a01a5eb --- /dev/null +++ b/py/evf_sam/utils/aug.py @@ -0,0 +1,117 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +from copy import deepcopy +from typing import Tuple + +import numpy as np +import torch +from torch.nn import functional as F +from torchvision.transforms.functional import resize # type: ignore +from torchvision.transforms.functional import to_pil_image +import random + + +class RandomScale: + """ + Resizes images to the longest side 'target_length', as well as provides + methods for resizing coordinates and boxes. Provides methods for + transforming both numpy array and batched torch tensors. + """ + + def __init__(self, max_length: int, min_length: int) -> None: + self.max_length = max_length + self.min_length = min_length + + def apply_image(self, image: np.ndarray) -> np.ndarray: + """ + Expects a numpy array with shape HxWxC in uint8 format. + """ + target_size = self.get_preprocess_shape( + image.shape[0], image.shape[1], self.max_length, self.min_length + ) + return np.array(resize(to_pil_image(image), target_size)) + + def apply_coords( + self, coords: np.ndarray, original_size: Tuple[int, ...] + ) -> np.ndarray: + """ + Expects a numpy array of length 2 in the final dimension. Requires the + original image size in (H, W) format. + """ + old_h, old_w = original_size + new_h, new_w = self.get_preprocess_shape( + original_size[0], original_size[1], self.max_length, self.min_length + ) + coords = deepcopy(coords).astype(float) + coords[..., 0] = coords[..., 0] * (new_w / old_w) + coords[..., 1] = coords[..., 1] * (new_h / old_h) + return coords + + def apply_boxes( + self, boxes: np.ndarray, original_size: Tuple[int, ...] + ) -> np.ndarray: + """ + Expects a numpy array shape Bx4. Requires the original image size + in (H, W) format. + """ + boxes = self.apply_coords(boxes.reshape(-1, 2, 2), original_size) + return boxes.reshape(-1, 4) + + def apply_image_torch(self, image: torch.Tensor) -> torch.Tensor: + """ + Expects batched images with shape BxCxHxW and float format. This + transformation may not exactly match apply_image. apply_image is + the transformation expected by the model. + """ + # Expects an image in BCHW format. May not exactly match apply_image. + target_size = self.get_preprocess_shape( + image.shape[0], image.shape[1], self.max_length, self.min_length + ) + return F.interpolate( + image, target_size, mode="bilinear", align_corners=False, antialias=True + ) + + def apply_coords_torch( + self, coords: torch.Tensor, original_size: Tuple[int, ...] + ) -> torch.Tensor: + """ + Expects a torch tensor with length 2 in the last dimension. Requires the + original image size in (H, W) format. + """ + old_h, old_w = original_size + new_h, new_w = self.get_preprocess_shape( + original_size[0], original_size[1], self.max_length, self.min_length + ) + coords = deepcopy(coords).to(torch.float) + coords[..., 0] = coords[..., 0] * (new_w / old_w) + coords[..., 1] = coords[..., 1] * (new_h / old_h) + return coords + + def apply_boxes_torch( + self, boxes: torch.Tensor, original_size: Tuple[int, ...] + ) -> torch.Tensor: + """ + Expects a torch tensor with shape Bx4. Requires the original image + size in (H, W) format. + """ + boxes = self.apply_coords_torch(boxes.reshape(-1, 2, 2), original_size) + return boxes.reshape(-1, 4) + + @staticmethod + def get_preprocess_shape( + oldh: int, oldw: int, max_length: int, min_length: int + ) -> Tuple[int, int]: + """ + Compute the output size given input size and target long side length. + """ + max_scale = max_length * 1.0 / max(oldh, oldw) + min_scale = min_length * 1.0 / max(oldh, oldw) + scale = min_scale + random.random() * (max_scale-min_scale) + newh, neww = oldh * scale, oldw * scale + neww = int(neww + 0.5) + newh = int(newh + 0.5) + return (newh, neww) diff --git a/py/evf_sam/utils/data_processing.py b/py/evf_sam/utils/data_processing.py new file mode 100644 index 0000000..d47a80f --- /dev/null +++ b/py/evf_sam/utils/data_processing.py @@ -0,0 +1,90 @@ +import glob +import json +import os + +import cv2 +import numpy as np + + +def get_mask_from_json(json_path, img): + try: + with open(json_path, "r") as r: + anno = json.loads(r.read()) + except: + with open(json_path, "r", encoding="cp1252") as r: + anno = json.loads(r.read()) + + inform = anno["shapes"] + comments = anno["text"] + is_sentence = anno["is_sentence"] + + height, width = img.shape[:2] + + ### sort polies by area + area_list = [] + valid_poly_list = [] + for i in inform: + label_id = i["label"] + points = i["points"] + if "flag" == label_id.lower(): ## meaningless deprecated annotations + continue + + tmp_mask = np.zeros((height, width), dtype=np.uint8) + cv2.polylines(tmp_mask, np.array([points], dtype=np.int32), True, 1, 1) + cv2.fillPoly(tmp_mask, np.array([points], dtype=np.int32), 1) + tmp_area = tmp_mask.sum() + + area_list.append(tmp_area) + valid_poly_list.append(i) + + ### ground-truth mask + sort_index = np.argsort(area_list)[::-1].astype(np.int32) + sort_index = list(sort_index) + sort_inform = [] + for s_idx in sort_index: + sort_inform.append(valid_poly_list[s_idx]) + + mask = np.zeros((height, width), dtype=np.uint8) + for i in sort_inform: + label_id = i["label"] + points = i["points"] + + if "ignore" in label_id.lower(): + label_value = 255 # ignored during evaluation + else: + label_value = 1 # target + + cv2.polylines(mask, np.array([points], dtype=np.int32), True, label_value, 1) + cv2.fillPoly(mask, np.array([points], dtype=np.int32), label_value) + + return mask, comments, is_sentence + + +if __name__ == "__main__": + data_dir = "./train" + vis_dir = "./vis" + + if not os.path.exists(vis_dir): + os.makedirs(vis_dir) + + json_path_list = sorted(glob.glob(data_dir + "/*.json")) + for json_path in json_path_list: + img_path = json_path.replace(".json", ".jpg") + img = cv2.imread(img_path)[:, :, ::-1] + + # In generated mask, value 1 denotes valid target region, and value 255 stands for region ignored during evaluaiton. + mask, comments, is_sentence = get_mask_from_json(json_path, img) + + ## visualization. Green for target, and red for ignore. + valid_mask = (mask == 1).astype(np.float32)[:, :, None] + ignore_mask = (mask == 255).astype(np.float32)[:, :, None] + vis_img = img * (1 - valid_mask) * (1 - ignore_mask) + ( + (np.array([0, 255, 0]) * 0.6 + img * 0.4) * valid_mask + + (np.array([255, 0, 0]) * 0.6 + img * 0.4) * ignore_mask + ) + vis_img = np.concatenate([img, vis_img], 1) + vis_path = os.path.join( + vis_dir, json_path.split("/")[-1].replace(".json", ".jpg") + ) + cv2.imwrite(vis_path, vis_img[:, :, ::-1]) + print("Visualization has been saved to: ", vis_path) diff --git a/py/evf_sam/utils/dataset.py b/py/evf_sam/utils/dataset.py new file mode 100644 index 0000000..9969078 --- /dev/null +++ b/py/evf_sam/utils/dataset.py @@ -0,0 +1,386 @@ +import glob +import os +import random + +import cv2 +import numpy as np +import torch +import torch.nn.functional as F +from pycocotools import mask + +from model.segment_anything.utils.transforms import ResizeLongestSide + +from .data_processing import get_mask_from_json +from .refer import REFER +from .refer_seg_dataset import ReferSegDataset +from .sem_seg_dataset import SemSegDataset +from torchvision import transforms +import json +from PIL import Image + +def collate_fn( + batch, tokenizer=None, local_rank=-1 +): + image_path_list = [] + images_list = [] + images_evf_list = [] + masks_list = [] + label_list = [] + resize_list = [] + sampled_classes_list = [] + offset_list = [0] + cnt = 0 + inferences = [] + for ( + image_path, + images, + images_evf, + masks, + label, + resize, + sampled_classes, + inference, + ) in batch: + image_path_list.append(image_path) + images_list.append(images) + images_evf_list.append(images_evf) + label_list.append(label) + masks_list.append(masks.float()) + resize_list.append(resize) + sampled_classes_list.extend(sampled_classes) + cnt += len(sampled_classes) + offset_list.append(cnt) + inferences.append(inference) + + input_ids = [ + tokenizer(prompt, return_tensors="pt").input_ids[0] + for prompt in sampled_classes_list + ] + + input_ids = torch.nn.utils.rnn.pad_sequence( + input_ids, batch_first=True, padding_value=tokenizer.pad_token_id + ) + attention_masks = input_ids.ne(tokenizer.pad_token_id) + + if inferences[0] == False: + truncate_len = tokenizer.model_max_length + + if input_ids.shape[1] > truncate_len: + input_ids = input_ids[:, :truncate_len] + targets = targets[:, :truncate_len] + attention_masks = attention_masks[:, :truncate_len] + + return { + "image_paths": image_path_list, + "images": torch.stack(images_list, dim=0), + "images_evf": torch.stack(images_evf_list, dim=0), + "input_ids": input_ids, + "attention_masks": attention_masks, + "masks_list": masks_list, + "label_list": label_list, + "resize_list": resize_list, + "offset": torch.LongTensor(offset_list), + "sampled_classes_list": sampled_classes_list, + "inference": inferences[0], + } + + +class HybridDataset(torch.utils.data.Dataset): + pixel_mean = torch.Tensor([123.675, 116.28, 103.53]).view(-1, 1, 1) + pixel_std = torch.Tensor([58.395, 57.12, 57.375]).view(-1, 1, 1) + img_size = 1024 + ignore_label = 255 + + def __init__( + self, + base_image_dir, + tokenizer, + samples_per_epoch=500 * 8 * 2 * 10, + precision: str = "fp32", + image_size: int = 224, + num_classes_per_sample: int = 3, + exclude_val=False, + dataset="sem_seg||refer_seg", + sample_rate=[9, 3, 3, 1], + sem_seg_data="ade20k||cocostuff||pascal_part||mapillary", + refer_seg_data="refclef||refcoco||refcoco+||refcocog", + explanatory=-1, + model_type="ori", + transform=ResizeLongestSide(1024), + ): + self.transform=transform + self.model_type = model_type + self.exclude_val = exclude_val + self.dataset = dataset + self.samples_per_epoch = samples_per_epoch + self.explanatory = explanatory + self.num_classes_per_sample = num_classes_per_sample + sample_rate = np.array(sample_rate) + self.sample_rate = sample_rate / sample_rate.sum() + + self.base_image_dir = base_image_dir + self.image_size = image_size + self.tokenizer = tokenizer + self.precision = precision + + self.datasets = dataset.split("||") + + self.all_datasets = [] + for dataset in self.datasets: + if dataset == "sem_seg": + self.all_datasets.append( + SemSegDataset( + base_image_dir, + tokenizer, + samples_per_epoch, + precision, + image_size, + num_classes_per_sample, + exclude_val, + sem_seg_data, + self.model_type, + self.transform + ) + ) + elif dataset == "refer_seg": + self.all_datasets.append( + ReferSegDataset( + base_image_dir, + tokenizer, + samples_per_epoch, + precision, + image_size, + num_classes_per_sample, + exclude_val, + refer_seg_data, + self.model_type, + self.transform + ) + ) + + def __len__(self): + return self.samples_per_epoch + + def __getitem__(self, idx): + ind = np.random.choice(list(range(len(self.datasets))), p=self.sample_rate) + data = self.all_datasets[ind] + inference = False + return *data[0], inference + + +def init_ade20k(base_image_dir): + with open("utils/ade20k_classes.json", "r") as f: + ade20k_classes = json.load(f) + ade20k_classes = np.array(ade20k_classes) + image_ids = sorted( + os.listdir(os.path.join(base_image_dir, "ade20k/images", "validation")) + ) + ade20k_image_ids = [] + for x in image_ids: + if x.endswith(".jpg"): + ade20k_image_ids.append(x[:-4]) + ade20k_images = [] + for image_id in ade20k_image_ids: # self.descriptions: + ade20k_images.append( + os.path.join( + base_image_dir, + "ade20k", + "images", + "validation", + "{}.jpg".format(image_id), + ) + ) + ade20k_labels = [ + x.replace(".jpg", ".png").replace("images", "annotations") + for x in ade20k_images + ] + print("ade20k: ", len(ade20k_images)) + return ade20k_classes, ade20k_images, ade20k_labels + + +class ValDataset(torch.utils.data.Dataset): + pixel_mean = torch.Tensor([123.675, 116.28, 103.53]).view(-1, 1, 1) + pixel_std = torch.Tensor([58.395, 57.12, 57.375]).view(-1, 1, 1) + img_size = 1024 + ignore_label = 255 + + def __init__( + self, + base_image_dir, + tokenizer, + val_dataset, + image_size=224, + model_type="ori" + ): + self.model_type = model_type + self.base_image_dir = base_image_dir + splits = val_dataset.split("|") + if len(splits) == 3: + ds, splitBy, split = splits + base_image_dir = os.path.join(base_image_dir, "refer_seg") + refer_api = REFER(base_image_dir, ds, splitBy) + ref_ids_val = refer_api.getRefIds(split=split) + images_ids_val = refer_api.getImgIds(ref_ids=ref_ids_val) + refs_val = refer_api.loadRefs(ref_ids=ref_ids_val) + refer_seg_ds = {} + refer_seg_ds["images"] = [] + loaded_images = refer_api.loadImgs(image_ids=images_ids_val) + for item in loaded_images: + item = item.copy() + if ds == "refclef": + item["file_name"] = os.path.join( + base_image_dir, "images/saiapr_tc-12", item["file_name"] + ) + elif ds in ["refcoco", "refcoco+", "refcocog", "grefcoco"]: + item["file_name"] = os.path.join( + base_image_dir, + "images/mscoco/images/train2014", + item["file_name"], + ) + refer_seg_ds["images"].append(item) + refer_seg_ds["annotations"] = refer_api.Anns # anns_val + + img2refs = {} + for ref in refs_val: + image_id = ref["image_id"] + img2refs[image_id] = img2refs.get(image_id, []) + [ + ref, + ] + refer_seg_ds["img2refs"] = img2refs + self.refer_seg_ds = refer_seg_ds + self.data_type = "refer_seg" + elif val_dataset=="ade": + ds = "ade" + self.classes, self.images, self.labels = init_ade20k(base_image_dir) + self.data_type = "sem_seg" + + + self.ds = ds + self.tokenizer = tokenizer + self.transform = ResizeLongestSide(1024) + self.image_preprocessor = transforms.Compose([ + transforms.ToTensor(), + transforms.Resize((image_size, image_size), interpolation=3), + transforms.Normalize(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5)) + ]) + def __len__(self): + if self.data_type == "refer_seg": + return len(self.refer_seg_ds["images"]) + else: + return len(self.images) + + def preprocess(self, x: torch.Tensor) -> torch.Tensor: + """Normalize pixel values and pad to a square input.""" + # Normalize colors + x = (x - self.pixel_mean) / self.pixel_std + + if self.model_type=="effi" or self.model_type=="sam2": + x = F.interpolate(x.unsqueeze(0), (self.img_size, self.img_size), mode="bilinear").squeeze(0) + else: + # Pad + h, w = x.shape[-2:] + padh = self.img_size - h + padw = self.img_size - w + x = F.pad(x, (0, padw, 0, padh)) + return x + + def __getitem__(self, idx): + if self.data_type == "refer_seg": + refer_seg_ds = self.refer_seg_ds + images = refer_seg_ds["images"] + annotations = refer_seg_ds["annotations"] + img2refs = refer_seg_ds["img2refs"] + + image_info = images[idx] + image_path = image_info["file_name"] + image_id = image_info["id"] + + refs = img2refs[image_id] + if len(refs) == 0: + raise ValueError("image {} has no refs".format(image_id)) + + sents = [] + ann_ids = [] + for ref in refs: + for sent in ref["sentences"]: + sents.append(sent["sent"].strip().lower()) + ann_ids.append(ref["ann_id"]) + + sampled_sents = sents + sampled_ann_ids = ann_ids + image = cv2.imread(image_path) + image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) + is_sentence = False + + elif self.data_type == "sem_seg": + image_path = self.images[idx] + label_path = self.labels[idx] + label = Image.open(label_path) + label = np.array(label) + label[label == 0] = 255 + label -= 1 + label[label == 254] = 255 + unique_label = np.unique(label).tolist() + if 255 in unique_label: + unique_label.remove(255) + + sampled_sents = [self.classes[class_id] for class_id in unique_label] + + img = cv2.imread(image_path) + image = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) + class_ids = unique_label + label = torch.from_numpy(label).long() + masks = [] + for class_id in class_ids: + masks.append(label == class_id) + masks = torch.stack(masks, dim=0) + + # preprocess image for evf + image_evf = self.image_preprocessor(image) + + # preprocess image for sam + image = self.transform.apply_image(image) + resize = image.shape[:2] + image = self.preprocess(torch.from_numpy(image).permute(2, 0, 1).contiguous()) + + if self.data_type == "refer_seg": + masks = [] + for i, ann_id in enumerate(sampled_ann_ids): + ann = annotations[ann_id] + if len(ann["segmentation"]) == 0 and sampled_sents[i] != "": + m = np.zeros((image_info["height"], image_info["width"], 1)) + else: + if type(ann["segmentation"][0]) == list: # polygon + rle = mask.frPyObjects( + ann["segmentation"], + image_info["height"], + image_info["width"], + ) + else: + rle = ann["segmentation"] + for i in range(len(rle)): + if not isinstance(rle[i]["counts"], bytes): + rle[i]["counts"] = rle[i]["counts"].encode() + m = mask.decode(rle) + m = np.sum( + m, axis=2 + ) # sometimes there are multiple binary map (corresponding to multiple segs) + m = m.astype(np.uint8) # convert to np.uint8 + masks.append(m) + + if not isinstance(masks, torch.Tensor): + masks = np.stack(masks, axis=0) + masks = torch.from_numpy(masks) + labels = torch.ones(masks.shape[1], masks.shape[2]) * self.ignore_label + inference = True + + return ( + image_path, + image, + image_evf, + masks, + labels, + resize, + sampled_sents, + inference, + ) diff --git a/py/evf_sam/utils/grefcoco.py b/py/evf_sam/utils/grefcoco.py new file mode 100644 index 0000000..7e1a49f --- /dev/null +++ b/py/evf_sam/utils/grefcoco.py @@ -0,0 +1,193 @@ +import contextlib +import copy +import io +import logging +import os +import random + +import numpy as np +import pycocotools.mask as mask_util +from detectron2.structures import Boxes, BoxMode, PolygonMasks, RotatedBoxes +from detectron2.utils.file_io import PathManager +from fvcore.common.timer import Timer +from PIL import Image + +""" +This file contains functions to parse RefCOCO-format annotations into dicts in "Detectron2 format". +""" + + +logger = logging.getLogger(__name__) + +__all__ = ["load_refcoco_json"] + + +def load_grefcoco_json( + refer_root, + dataset_name, + splitby, + split, + image_root, + extra_annotation_keys=None, + extra_refer_keys=None, +): + if dataset_name == "refcocop": + dataset_name = "refcoco+" + if dataset_name == "refcoco" or dataset_name == "refcoco+": + splitby == "unc" + if dataset_name == "refcocog": + assert splitby == "umd" or splitby == "google" + + dataset_id = "_".join([dataset_name, splitby, split]) + + from .grefer import G_REFER + + logger.info("Loading dataset {} ({}-{}) ...".format(dataset_name, splitby, split)) + logger.info("Refcoco root: {}".format(refer_root)) + timer = Timer() + refer_root = PathManager.get_local_path(refer_root) + with contextlib.redirect_stdout(io.StringIO()): + refer_api = G_REFER(data_root=refer_root, dataset=dataset_name, splitBy=splitby) + if timer.seconds() > 1: + logger.info( + "Loading {} takes {:.2f} seconds.".format(dataset_id, timer.seconds()) + ) + + ref_ids = refer_api.getRefIds(split=split) + img_ids = refer_api.getImgIds(ref_ids) + refs = refer_api.loadRefs(ref_ids) + imgs = [refer_api.loadImgs(ref["image_id"])[0] for ref in refs] + anns = [refer_api.loadAnns(ref["ann_id"]) for ref in refs] + imgs_refs_anns = list(zip(imgs, refs, anns)) + + logger.info( + "Loaded {} images, {} referring object sets in G_RefCOCO format from {}".format( + len(img_ids), len(ref_ids), dataset_id + ) + ) + + dataset_dicts = [] + + ann_keys = ["iscrowd", "bbox", "category_id"] + (extra_annotation_keys or []) + ref_keys = ["raw", "sent_id"] + (extra_refer_keys or []) + + ann_lib = {} + + NT_count = 0 + MT_count = 0 + + for img_dict, ref_dict, anno_dicts in imgs_refs_anns: + record = {} + record["source"] = "grefcoco" + record["file_name"] = os.path.join(image_root, img_dict["file_name"]) + record["height"] = img_dict["height"] + record["width"] = img_dict["width"] + image_id = record["image_id"] = img_dict["id"] + + # Check that information of image, ann and ref match each other + # This fails only when the data parsing logic or the annotation file is buggy. + assert ref_dict["image_id"] == image_id + assert ref_dict["split"] == split + if not isinstance(ref_dict["ann_id"], list): + ref_dict["ann_id"] = [ref_dict["ann_id"]] + + # No target samples + if None in anno_dicts: + assert anno_dicts == [None] + assert ref_dict["ann_id"] == [-1] + record["empty"] = True + obj = {key: None for key in ann_keys if key in ann_keys} + obj["bbox_mode"] = BoxMode.XYWH_ABS + obj["empty"] = True + obj = [obj] + + # Multi target samples + else: + record["empty"] = False + obj = [] + for anno_dict in anno_dicts: + ann_id = anno_dict["id"] + if anno_dict["iscrowd"]: + continue + assert anno_dict["image_id"] == image_id + assert ann_id in ref_dict["ann_id"] + + if ann_id in ann_lib: + ann = ann_lib[ann_id] + else: + ann = {key: anno_dict[key] for key in ann_keys if key in anno_dict} + ann["bbox_mode"] = BoxMode.XYWH_ABS + ann["empty"] = False + + segm = anno_dict.get("segmentation", None) + assert segm # either list[list[float]] or dict(RLE) + if isinstance(segm, dict): + if isinstance(segm["counts"], list): + # convert to compressed RLE + segm = mask_util.frPyObjects(segm, *segm["size"]) + else: + # filter out invalid polygons (< 3 points) + segm = [ + poly + for poly in segm + if len(poly) % 2 == 0 and len(poly) >= 6 + ] + if len(segm) == 0: + num_instances_without_valid_segmentation += 1 + continue # ignore this instance + ann["segmentation"] = segm + ann_lib[ann_id] = ann + + obj.append(ann) + + record["annotations"] = obj + + # Process referring expressions + sents = ref_dict["sentences"] + for sent in sents: + ref_record = record.copy() + ref = {key: sent[key] for key in ref_keys if key in sent} + ref["ref_id"] = ref_dict["ref_id"] + ref_record["sentence"] = ref + dataset_dicts.append(ref_record) + # if ref_record['empty']: + # NT_count += 1 + # else: + # MT_count += 1 + + # logger.info("NT samples: %d, MT samples: %d", NT_count, MT_count) + + # Debug mode + # return dataset_dicts[:100] + + return dataset_dicts + + +if __name__ == "__main__": + """ + Test the COCO json dataset loader. + + Usage: + python -m detectron2.data.datasets.coco \ + path/to/json path/to/image_root dataset_name + + "dataset_name" can be "coco_2014_minival_100", or other + pre-registered ones + """ + import sys + + REFCOCO_PATH = "/mnt/lustre/hhding/code/ReLA/datasets" + COCO_TRAIN_2014_IMAGE_ROOT = "/mnt/lustre/hhding/code/ReLA/datasets/images" + REFCOCO_DATASET = "grefcoco" + REFCOCO_SPLITBY = "unc" + REFCOCO_SPLIT = "train" + + + dicts = load_grefcoco_json( + REFCOCO_PATH, + REFCOCO_DATASET, + REFCOCO_SPLITBY, + REFCOCO_SPLIT, + COCO_TRAIN_2014_IMAGE_ROOT, + ) + print(1) diff --git a/py/evf_sam/utils/grefer.py b/py/evf_sam/utils/grefer.py new file mode 100644 index 0000000..3c881c5 --- /dev/null +++ b/py/evf_sam/utils/grefer.py @@ -0,0 +1,352 @@ +""" +grefer v0.1 +This interface provides access to gRefCOCO. + +The following API functions are defined: +G_REFER - REFER api class +getRefIds - get ref ids that satisfy given filter conditions. +getAnnIds - get ann ids that satisfy given filter conditions. +getImgIds - get image ids that satisfy given filter conditions. +getCatIds - get category ids that satisfy given filter conditions. +loadRefs - load refs with the specified ref ids. +loadAnns - load anns with the specified ann ids. +loadImgs - load images with the specified image ids. +loadCats - load category names with the specified category ids. +getRefBox - get ref's bounding box [x, y, w, h] given the ref_id +showRef - show image, segmentation or box of the referred object with the ref +getMaskByRef - get mask and area of the referred object given ref or ref ids +getMask - get mask and area of the referred object given ref +showMask - show mask of the referred object given ref +""" + +import itertools +import json +import os.path as osp +import pickle +import time + +import matplotlib.pyplot as plt +import numpy as np +import skimage.io as io +from matplotlib.collections import PatchCollection +from matplotlib.patches import Polygon, Rectangle +from pycocotools import mask + + +class G_REFER: + def __init__(self, data_root, dataset="grefcoco", splitBy="unc"): + # provide data_root folder which contains grefcoco + print("loading dataset %s into memory..." % dataset) + self.ROOT_DIR = osp.abspath(osp.dirname(__file__)) + self.DATA_DIR = osp.join(data_root, dataset) + if dataset in ["grefcoco"]: + self.IMAGE_DIR = osp.join(data_root, "images/train2014") + else: + raise KeyError("No refer dataset is called [%s]" % dataset) + + tic = time.time() + + # load refs from data/dataset/refs(dataset).json + self.data = {} + self.data["dataset"] = dataset + + ref_file = osp.join(self.DATA_DIR, f"grefs({splitBy}).p") + if osp.exists(ref_file): + self.data["refs"] = pickle.load(open(ref_file, "rb"), fix_imports=True) + else: + ref_file = osp.join(self.DATA_DIR, f"grefs({splitBy}).json") + if osp.exists(ref_file): + self.data["refs"] = json.load(open(ref_file, "rb")) + else: + raise FileNotFoundError("JSON file not found") + + # load annotations from data/dataset/instances.json + instances_file = osp.join(self.DATA_DIR, "instances.json") + instances = json.load(open(instances_file, "r")) + self.data["images"] = instances["images"] + self.data["annotations"] = instances["annotations"] + self.data["categories"] = instances["categories"] + + # create index + self.createIndex() + print("DONE (t=%.2fs)" % (time.time() - tic)) + + @staticmethod + def _toList(x): + return x if isinstance(x, list) else [x] + + @staticmethod + def match_any(a, b): + a = a if isinstance(a, list) else [a] + b = b if isinstance(b, list) else [b] + return set(a) & set(b) + + def createIndex(self): + # create sets of mapping + # 1) Refs: {ref_id: ref} + # 2) Anns: {ann_id: ann} + # 3) Imgs: {image_id: image} + # 4) Cats: {category_id: category_name} + # 5) Sents: {sent_id: sent} + # 6) imgToRefs: {image_id: refs} + # 7) imgToAnns: {image_id: anns} + # 8) refToAnn: {ref_id: ann} + # 9) annToRef: {ann_id: ref} + # 10) catToRefs: {category_id: refs} + # 11) sentToRef: {sent_id: ref} + # 12) sentToTokens: {sent_id: tokens} + print("creating index...") + # fetch info from instances + Anns, Imgs, Cats, imgToAnns = {}, {}, {}, {} + Anns[-1] = None + for ann in self.data["annotations"]: + Anns[ann["id"]] = ann + imgToAnns[ann["image_id"]] = imgToAnns.get(ann["image_id"], []) + [ann] + for img in self.data["images"]: + Imgs[img["id"]] = img + for cat in self.data["categories"]: + Cats[cat["id"]] = cat["name"] + + # fetch info from refs + Refs, imgToRefs, refToAnn, annToRef, catToRefs = {}, {}, {}, {}, {} + Sents, sentToRef, sentToTokens = {}, {}, {} + availableSplits = [] + for ref in self.data["refs"]: + # ids + ref_id = ref["ref_id"] + ann_id = ref["ann_id"] + category_id = ref["category_id"] + image_id = ref["image_id"] + + if ref["split"] not in availableSplits: + availableSplits.append(ref["split"]) + + # add mapping related to ref + if ref_id in Refs: + print("Duplicate ref id") + Refs[ref_id] = ref + imgToRefs[image_id] = imgToRefs.get(image_id, []) + [ref] + + category_id = self._toList(category_id) + added_cats = [] + for cat in category_id: + if cat not in added_cats: + added_cats.append(cat) + catToRefs[cat] = catToRefs.get(cat, []) + [ref] + + ann_id = self._toList(ann_id) + refToAnn[ref_id] = [Anns[ann] for ann in ann_id] + for ann_id_n in ann_id: + annToRef[ann_id_n] = annToRef.get(ann_id_n, []) + [ref] + + # add mapping of sent + for sent in ref["sentences"]: + Sents[sent["sent_id"]] = sent + sentToRef[sent["sent_id"]] = ref + sentToTokens[sent["sent_id"]] = sent["tokens"] + + # create class members + self.Refs = Refs + self.Anns = Anns + self.Imgs = Imgs + self.Cats = Cats + self.Sents = Sents + self.imgToRefs = imgToRefs + self.imgToAnns = imgToAnns + self.refToAnn = refToAnn + self.annToRef = annToRef + self.catToRefs = catToRefs + self.sentToRef = sentToRef + self.sentToTokens = sentToTokens + self.availableSplits = availableSplits + print("index created.") + + def getRefIds(self, image_ids=[], cat_ids=[], split=[]): + image_ids = self._toList(image_ids) + cat_ids = self._toList(cat_ids) + split = self._toList(split) + + for s in split: + if s not in self.availableSplits: + raise ValueError(f"Invalid split name: {s}") + + refs = self.data["refs"] + + if len(image_ids) > 0: + lists = [self.imgToRefs[image_id] for image_id in image_ids] + refs = list(itertools.chain.from_iterable(lists)) + if len(cat_ids) > 0: + refs = [ref for ref in refs if self.match_any(ref["category_id"], cat_ids)] + if len(split) > 0: + refs = [ref for ref in refs if ref["split"] in split] + + ref_ids = [ref["ref_id"] for ref in refs] + return ref_ids + + def getAnnIds(self, image_ids=[], ref_ids=[]): + image_ids = self._toList(image_ids) + ref_ids = self._toList(ref_ids) + + if any([len(image_ids), len(ref_ids)]): + if len(image_ids) > 0: + lists = [ + self.imgToAnns[image_id] + for image_id in image_ids + if image_id in self.imgToAnns + ] + anns = list(itertools.chain.from_iterable(lists)) + else: + anns = self.data["annotations"] + ann_ids = [ann["id"] for ann in anns] + if len(ref_ids) > 0: + lists = [self.Refs[ref_id]["ann_id"] for ref_id in ref_ids] + anns_by_ref_id = list(itertools.chain.from_iterable(lists)) + ann_ids = list(set(ann_ids).intersection(set(anns_by_ref_id))) + else: + ann_ids = [ann["id"] for ann in self.data["annotations"]] + + return ann_ids + + def getImgIds(self, ref_ids=[]): + ref_ids = self._toList(ref_ids) + + if len(ref_ids) > 0: + image_ids = list(set([self.Refs[ref_id]["image_id"] for ref_id in ref_ids])) + else: + image_ids = self.Imgs.keys() + return image_ids + + def getCatIds(self): + return self.Cats.keys() + + def loadRefs(self, ref_ids=[]): + return [self.Refs[ref_id] for ref_id in self._toList(ref_ids)] + + def loadAnns(self, ann_ids=[]): + if isinstance(ann_ids, str): + ann_ids = int(ann_ids) + return [self.Anns[ann_id] for ann_id in self._toList(ann_ids)] + + def loadImgs(self, image_ids=[]): + return [self.Imgs[image_id] for image_id in self._toList(image_ids)] + + def loadCats(self, cat_ids=[]): + return [self.Cats[cat_id] for cat_id in self._toList(cat_ids)] + + def getRefBox(self, ref_id): + anns = self.refToAnn[ref_id] + return [ann["bbox"] for ann in anns] # [x, y, w, h] + + def showRef(self, ref, seg_box="seg"): + ax = plt.gca() + # show image + image = self.Imgs[ref["image_id"]] + I = io.imread(osp.join(self.IMAGE_DIR, image["file_name"])) + ax.imshow(I) + # show refer expression + for sid, sent in enumerate(ref["sentences"]): + print("%s. %s" % (sid + 1, sent["sent"])) + # show segmentations + if seg_box == "seg": + ann_id = ref["ann_id"] + ann = self.Anns[ann_id] + polygons = [] + color = [] + c = "none" + if type(ann["segmentation"][0]) == list: + # polygon used for refcoco* + for seg in ann["segmentation"]: + poly = np.array(seg).reshape((len(seg) / 2, 2)) + polygons.append(Polygon(poly, True, alpha=0.4)) + color.append(c) + p = PatchCollection( + polygons, + facecolors=color, + edgecolors=(1, 1, 0, 0), + linewidths=3, + alpha=1, + ) + ax.add_collection(p) # thick yellow polygon + p = PatchCollection( + polygons, + facecolors=color, + edgecolors=(1, 0, 0, 0), + linewidths=1, + alpha=1, + ) + ax.add_collection(p) # thin red polygon + else: + # mask used for refclef + rle = ann["segmentation"] + m = mask.decode(rle) + img = np.ones((m.shape[0], m.shape[1], 3)) + color_mask = np.array([2.0, 166.0, 101.0]) / 255 + for i in range(3): + img[:, :, i] = color_mask[i] + ax.imshow(np.dstack((img, m * 0.5))) + # show bounding-box + elif seg_box == "box": + ann_id = ref["ann_id"] + ann = self.Anns[ann_id] + bbox = self.getRefBox(ref["ref_id"]) + box_plot = Rectangle( + (bbox[0], bbox[1]), + bbox[2], + bbox[3], + fill=False, + edgecolor="green", + linewidth=3, + ) + ax.add_patch(box_plot) + + def getMask(self, ann): + if not ann: + return None + if ann["iscrowd"]: + raise ValueError("Crowd object") + image = self.Imgs[ann["image_id"]] + if type(ann["segmentation"][0]) == list: # polygon + rle = mask.frPyObjects(ann["segmentation"], image["height"], image["width"]) + else: + rle = ann["segmentation"] + + m = mask.decode(rle) + m = np.sum( + m, axis=2 + ) # sometimes there are multiple binary map (corresponding to multiple segs) + m = m.astype(np.uint8) # convert to np.uint8 + # compute area + area = sum(mask.area(rle)) # should be close to ann['area'] + return {"mask": m, "area": area} + + def getMaskByRef(self, ref=None, ref_id=None, merge=False): + if not ref and not ref_id: + raise ValueError + if ref: + ann_ids = ref["ann_id"] + ref_id = ref["ref_id"] + else: + ann_ids = self.getAnnIds(ref_ids=ref_id) + + if ann_ids == [-1]: + img = self.Imgs[self.Refs[ref_id]["image_id"]] + return { + "mask": np.zeros([img["height"], img["width"]], dtype=np.uint8), + "empty": True, + } + + anns = self.loadAnns(ann_ids) + mask_list = [self.getMask(ann) for ann in anns if not ann["iscrowd"]] + + if merge: + merged_masks = sum([mask["mask"] for mask in mask_list]) + merged_masks[np.where(merged_masks > 1)] = 1 + return {"mask": merged_masks, "empty": False} + else: + return mask_list + + def showMask(self, ref): + M = self.getMask(ref) + msk = M["mask"] + ax = plt.gca() + ax.imshow(msk) diff --git a/py/evf_sam/utils/refer.py b/py/evf_sam/utils/refer.py new file mode 100644 index 0000000..3b4cea7 --- /dev/null +++ b/py/evf_sam/utils/refer.py @@ -0,0 +1,391 @@ +__author__ = "licheng" + +""" +This interface provides access to four datasets: +1) refclef +2) refcoco +3) refcoco+ +4) refcocog +split by unc and google + +The following API functions are defined: +REFER - REFER api class +getRefIds - get ref ids that satisfy given filter conditions. +getAnnIds - get ann ids that satisfy given filter conditions. +getImgIds - get image ids that satisfy given filter conditions. +getCatIds - get category ids that satisfy given filter conditions. +loadRefs - load refs with the specified ref ids. +loadAnns - load anns with the specified ann ids. +loadImgs - load images with the specified image ids. +loadCats - load category names with the specified category ids. +getRefBox - get ref's bounding box [x, y, w, h] given the ref_id +showRef - show image, segmentation or box of the referred object with the ref +getMask - get mask and area of the referred object given ref +showMask - show mask of the referred object given ref +""" + +import itertools +import json +import os.path as osp +import pickle +import sys +import time +from pprint import pprint + +import matplotlib.pyplot as plt +import numpy as np +import skimage.io as io +from matplotlib.collections import PatchCollection +from matplotlib.patches import Polygon, Rectangle +from pycocotools import mask + + +class REFER: + def __init__(self, data_root, dataset="refcoco", splitBy="unc"): + # provide data_root folder which contains refclef, refcoco, refcoco+ and refcocog + # also provide dataset name and splitBy information + # e.g., dataset = 'refcoco', splitBy = 'unc' + print("loading dataset %s into memory..." % dataset) + self.ROOT_DIR = osp.abspath(osp.dirname(__file__)) + self.DATA_DIR = osp.join(data_root, dataset) + if dataset in ["refcoco", "refcoco+", "refcocog"]: + self.IMAGE_DIR = osp.join(data_root, "images/mscoco/images/train2014") + elif dataset == "refclef": + self.IMAGE_DIR = osp.join(data_root, "images/saiapr_tc-12") + else: + print("No refer dataset is called [%s]" % dataset) + sys.exit() + + self.dataset = dataset + + # load refs from data/dataset/refs(dataset).json + tic = time.time() + + ref_file = osp.join(self.DATA_DIR, "refs(" + splitBy + ").p") + print("ref_file: ", ref_file) + self.data = {} + self.data["dataset"] = dataset + self.data["refs"] = pickle.load(open(ref_file, "rb")) + + # load annotations from data/dataset/instances.json + instances_file = osp.join(self.DATA_DIR, "instances.json") + instances = json.load(open(instances_file, "rb")) + self.data["images"] = instances["images"] + self.data["annotations"] = instances["annotations"] + self.data["categories"] = instances["categories"] + + # create index + self.createIndex() + print("DONE (t=%.2fs)" % (time.time() - tic)) + + def createIndex(self): + # create sets of mapping + # 1) Refs: {ref_id: ref} + # 2) Anns: {ann_id: ann} + # 3) Imgs: {image_id: image} + # 4) Cats: {category_id: category_name} + # 5) Sents: {sent_id: sent} + # 6) imgToRefs: {image_id: refs} + # 7) imgToAnns: {image_id: anns} + # 8) refToAnn: {ref_id: ann} + # 9) annToRef: {ann_id: ref} + # 10) catToRefs: {category_id: refs} + # 11) sentToRef: {sent_id: ref} + # 12) sentToTokens: {sent_id: tokens} + print("creating index...") + # fetch info from instances + Anns, Imgs, Cats, imgToAnns = {}, {}, {}, {} + for ann in self.data["annotations"]: + Anns[ann["id"]] = ann + imgToAnns[ann["image_id"]] = imgToAnns.get(ann["image_id"], []) + [ann] + for img in self.data["images"]: + Imgs[img["id"]] = img + for cat in self.data["categories"]: + Cats[cat["id"]] = cat["name"] + + # fetch info from refs + Refs, imgToRefs, refToAnn, annToRef, catToRefs = {}, {}, {}, {}, {} + Sents, sentToRef, sentToTokens = {}, {}, {} + for ref in self.data["refs"]: + # ids + ref_id = ref["ref_id"] + ann_id = ref["ann_id"] + category_id = ref["category_id"] + image_id = ref["image_id"] + + # add mapping related to ref + Refs[ref_id] = ref + imgToRefs[image_id] = imgToRefs.get(image_id, []) + [ref] + catToRefs[category_id] = catToRefs.get(category_id, []) + [ref] + refToAnn[ref_id] = Anns[ann_id] + annToRef[ann_id] = ref + + # add mapping of sent + for sent in ref["sentences"]: + Sents[sent["sent_id"]] = sent + sentToRef[sent["sent_id"]] = ref + sentToTokens[sent["sent_id"]] = sent["tokens"] + + # create class members + self.Refs = Refs + self.Anns = Anns + self.Imgs = Imgs + self.Cats = Cats + self.Sents = Sents + self.imgToRefs = imgToRefs + self.imgToAnns = imgToAnns + self.refToAnn = refToAnn + self.annToRef = annToRef + self.catToRefs = catToRefs + self.sentToRef = sentToRef + self.sentToTokens = sentToTokens + print("index created.") + + def getRefIds(self, image_ids=[], cat_ids=[], ref_ids=[], split=""): + image_ids = image_ids if type(image_ids) == list else [image_ids] + cat_ids = cat_ids if type(cat_ids) == list else [cat_ids] + ref_ids = ref_ids if type(ref_ids) == list else [ref_ids] + + if len(image_ids) == len(cat_ids) == len(ref_ids) == len(split) == 0: + refs = self.data["refs"] + else: + if not len(image_ids) == 0: + refs = [self.imgToRefs[image_id] for image_id in image_ids] + else: + refs = self.data["refs"] + if not len(cat_ids) == 0: + refs = [ref for ref in refs if ref["category_id"] in cat_ids] + if not len(ref_ids) == 0: + refs = [ref for ref in refs if ref["ref_id"] in ref_ids] + if not len(split) == 0: + if split in ["testA", "testB", "testC"]: + refs = [ + ref for ref in refs if split[-1] in ref["split"] + ] # we also consider testAB, testBC, ... + elif split in ["testAB", "testBC", "testAC"]: + refs = [ + ref for ref in refs if ref["split"] == split + ] # rarely used I guess... + elif split == "test": + refs = [ref for ref in refs if "test" in ref["split"]] + elif split == "train" or split == "val": + refs = [ref for ref in refs if ref["split"] == split] + else: + print("No such split [%s]" % split) + sys.exit() + ref_ids = [ref["ref_id"] for ref in refs] + return ref_ids + + def getAnnIds(self, image_ids=[], cat_ids=[], ref_ids=[]): + image_ids = image_ids if type(image_ids) == list else [image_ids] + cat_ids = cat_ids if type(cat_ids) == list else [cat_ids] + ref_ids = ref_ids if type(ref_ids) == list else [ref_ids] + + if len(image_ids) == len(cat_ids) == len(ref_ids) == 0: + ann_ids = [ann["id"] for ann in self.data["annotations"]] + else: + if not len(image_ids) == 0: + lists = [ + self.imgToAnns[image_id] + for image_id in image_ids + if image_id in self.imgToAnns + ] # list of [anns] + anns = list(itertools.chain.from_iterable(lists)) + else: + anns = self.data["annotations"] + if not len(cat_ids) == 0: + anns = [ann for ann in anns if ann["category_id"] in cat_ids] + ann_ids = [ann["id"] for ann in anns] + if not len(ref_ids) == 0: + ids = set(ann_ids).intersection( + set([self.Refs[ref_id]["ann_id"] for ref_id in ref_ids]) + ) + return ann_ids + + def getImgIds(self, ref_ids=[]): + ref_ids = ref_ids if type(ref_ids) == list else [ref_ids] + + if not len(ref_ids) == 0: + image_ids = list(set([self.Refs[ref_id]["image_id"] for ref_id in ref_ids])) + else: + image_ids = self.Imgs.keys() + return image_ids + + def getCatIds(self): + return self.Cats.keys() + + def loadRefs(self, ref_ids=[]): + if type(ref_ids) == list: + return [self.Refs[ref_id] for ref_id in ref_ids] + elif type(ref_ids) == int: + return [self.Refs[ref_ids]] + + def loadAnns(self, ann_ids=[]): + if type(ann_ids) == list: + return [self.Anns[ann_id] for ann_id in ann_ids] + elif type(ann_ids) == int or type(ann_ids) == unicode: + return [self.Anns[ann_ids]] + + def loadImgs(self, image_ids=[]): + if type(image_ids) == list: + return [self.Imgs[image_id] for image_id in image_ids] + elif type(image_ids) == int: + return [self.Imgs[image_ids]] + + def loadCats(self, cat_ids=[]): + if type(cat_ids) == list: + return [self.Cats[cat_id] for cat_id in cat_ids] + elif type(cat_ids) == int: + return [self.Cats[cat_ids]] + + def getRefBox(self, ref_id): + ref = self.Refs[ref_id] + ann = self.refToAnn[ref_id] + return ann["bbox"] # [x, y, w, h] + + def showRef(self, ref, seg_box="seg"): + ax = plt.gca() + # show image + image = self.Imgs[ref["image_id"]] + I = io.imread(osp.join(self.IMAGE_DIR, image["file_name"])) + ax.imshow(I) + # show refer expression + for sid, sent in enumerate(ref["sentences"]): + print("%s. %s" % (sid + 1, sent["sent"])) + # show segmentations + if seg_box == "seg": + ann_id = ref["ann_id"] + ann = self.Anns[ann_id] + polygons = [] + color = [] + c = "none" + if type(ann["segmentation"][0]) == list: + # polygon used for refcoco* + for seg in ann["segmentation"]: + poly = np.array(seg).reshape((len(seg) / 2, 2)) + polygons.append(Polygon(poly, True, alpha=0.4)) + color.append(c) + p = PatchCollection( + polygons, + facecolors=color, + edgecolors=(1, 1, 0, 0), + linewidths=3, + alpha=1, + ) + ax.add_collection(p) # thick yellow polygon + p = PatchCollection( + polygons, + facecolors=color, + edgecolors=(1, 0, 0, 0), + linewidths=1, + alpha=1, + ) + ax.add_collection(p) # thin red polygon + else: + # mask used for refclef + rle = ann["segmentation"] + m = mask.decode(rle) + img = np.ones((m.shape[0], m.shape[1], 3)) + color_mask = np.array([2.0, 166.0, 101.0]) / 255 + for i in range(3): + img[:, :, i] = color_mask[i] + ax.imshow(np.dstack((img, m * 0.5))) + # show bounding-box + elif seg_box == "box": + ann_id = ref["ann_id"] + ann = self.Anns[ann_id] + bbox = self.getRefBox(ref["ref_id"]) + box_plot = Rectangle( + (bbox[0], bbox[1]), + bbox[2], + bbox[3], + fill=False, + edgecolor="green", + linewidth=3, + ) + ax.add_patch(box_plot) + + def getMask(self, ref): + # return mask, area and mask-center + ann = self.refToAnn[ref["ref_id"]] + image = self.Imgs[ref["image_id"]] + if type(ann["segmentation"][0]) == list: # polygon + rle = mask.frPyObjects(ann["segmentation"], image["height"], image["width"]) + else: + rle = ann["segmentation"] + m = mask.decode(rle) + m = np.sum( + m, axis=2 + ) # sometimes there are multiple binary map (corresponding to multiple segs) + m = m.astype(np.uint8) # convert to np.uint8 + # compute area + area = sum(mask.area(rle)) # should be close to ann['area'] + return {"mask": m, "area": area} + # # position + # position_x = np.mean(np.where(m==1)[1]) # [1] means columns (matlab style) -> x (c style) + # position_y = np.mean(np.where(m==1)[0]) # [0] means rows (matlab style) -> y (c style) + # # mass position (if there were multiple regions, we use the largest one.) + # label_m = label(m, connectivity=m.ndim) + # regions = regionprops(label_m) + # if len(regions) > 0: + # largest_id = np.argmax(np.array([props.filled_area for props in regions])) + # largest_props = regions[largest_id] + # mass_y, mass_x = largest_props.centroid + # else: + # mass_x, mass_y = position_x, position_y + # # if centroid is not in mask, we find the closest point to it from mask + # if m[mass_y, mass_x] != 1: + # print('Finding closes mask point ...') + # kernel = np.ones((10, 10),np.uint8) + # me = cv2.erode(m, kernel, iterations = 1) + # points = zip(np.where(me == 1)[0].tolist(), np.where(me == 1)[1].tolist()) # row, col style + # points = np.array(points) + # dist = np.sum((points - (mass_y, mass_x))**2, axis=1) + # id = np.argsort(dist)[0] + # mass_y, mass_x = points[id] + # # return + # return {'mask': m, 'area': area, 'position_x': position_x, 'position_y': position_y, 'mass_x': mass_x, 'mass_y': mass_y} + # # show image and mask + # I = io.imread(osp.join(self.IMAGE_DIR, image['file_name'])) + # plt.figure() + # plt.imshow(I) + # ax = plt.gca() + # img = np.ones( (m.shape[0], m.shape[1], 3) ) + # color_mask = np.array([2.0,166.0,101.0])/255 + # for i in range(3): + # img[:,:,i] = color_mask[i] + # ax.imshow(np.dstack( (img, m*0.5) )) + # plt.show() + + def showMask(self, ref): + M = self.getMask(ref) + msk = M["mask"] + ax = plt.gca() + ax.imshow(msk) + + +if __name__ == "__main__": + refer = REFER(dataset="refcocog", splitBy="google") + ref_ids = refer.getRefIds() + print(len(ref_ids)) + + print(len(refer.Imgs)) + print(len(refer.imgToRefs)) + + ref_ids = refer.getRefIds(split="train") + print("There are %s training referred objects." % len(ref_ids)) + + for ref_id in ref_ids: + ref = refer.loadRefs(ref_id)[0] + if len(ref["sentences"]) < 2: + continue + + pprint(ref) + print("The label is %s." % refer.Cats[ref["category_id"]]) + plt.figure() + refer.showRef(ref, seg_box="box") + plt.show() + + # plt.figure() + # refer.showMask(ref) + # plt.show() diff --git a/py/evf_sam/utils/refer_seg_dataset.py b/py/evf_sam/utils/refer_seg_dataset.py new file mode 100644 index 0000000..fc8bdcb --- /dev/null +++ b/py/evf_sam/utils/refer_seg_dataset.py @@ -0,0 +1,254 @@ +import os +import random + +import cv2 +import numpy as np +import torch +import torch.nn.functional as F +from pycocotools import mask + +from model.segment_anything.utils.transforms import ResizeLongestSide + +from .grefer import G_REFER +from .refer import REFER +from torchvision import transforms + + +class ReferSegDataset(torch.utils.data.Dataset): + pixel_mean = torch.Tensor([123.675, 116.28, 103.53]).view(-1, 1, 1) + pixel_std = torch.Tensor([58.395, 57.12, 57.375]).view(-1, 1, 1) + img_size = 1024 + ignore_label = 255 + + def __init__( + self, + base_image_dir, + tokenizer, + samples_per_epoch=500 * 8 * 2 * 10, + precision: str = "fp32", + image_size: int = 224, + num_classes_per_sample: int = 3, + exclude_val=False, + refer_seg_data="refclef||refcoco||refcoco+||refcocog", + model_type="ori", + transform=ResizeLongestSide(1024), + ): + self.model_type = model_type + self.exclude_val = exclude_val + self.samples_per_epoch = samples_per_epoch + self.num_classes_per_sample = num_classes_per_sample + + self.base_image_dir = base_image_dir + self.tokenizer = tokenizer + self.precision = precision + self.transform = transform + self.image_preprocessor = transforms.Compose([ + transforms.ToTensor(), + transforms.Resize((image_size, image_size), interpolation=3), + transforms.Normalize(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5)) + ]) + + DATA_DIR = os.path.join(base_image_dir, "refer_seg") + self.refer_seg_ds_list = refer_seg_data.split( + "||" + ) # ['refclef', 'refcoco', 'refcoco+', 'refcocog'] + self.refer_seg_data = {} + for ds in self.refer_seg_ds_list: + if ds == "refcocog": + splitBy = "umd" + else: + splitBy = "unc" + + if ds == "grefcoco": + refer_api = G_REFER(DATA_DIR, ds, splitBy) + else: + refer_api = REFER(DATA_DIR, ds, splitBy) + + ref_ids_train = refer_api.getRefIds(split="train") + images_ids_train = refer_api.getImgIds(ref_ids=ref_ids_train) + refs_train = refer_api.loadRefs(ref_ids=ref_ids_train) + + refer_seg_ds = {} + refer_seg_ds["images"] = [] + loaded_images = refer_api.loadImgs(image_ids=images_ids_train) + + for item in loaded_images: + item = item.copy() + if ds == "refclef": + item["file_name"] = os.path.join( + DATA_DIR, "images/saiapr_tc-12", item["file_name"] + ) + else: + item["file_name"] = os.path.join( + DATA_DIR, "images/mscoco/images/train2014", item["file_name"] + ) + refer_seg_ds["images"].append(item) + refer_seg_ds["annotations"] = refer_api.Anns # anns_train + + print( + "dataset {} (refs {}) (train split) has {} images and {} annotations.".format( + ds, + splitBy, + len(refer_seg_ds["images"]), + len(refer_seg_ds["annotations"]), + ) + ) + + img2refs = {} + for ref in refs_train: + image_id = ref["image_id"] + img2refs[image_id] = img2refs.get(image_id, []) + [ + ref, + ] + refer_seg_ds["img2refs"] = img2refs + self.refer_seg_data[ds] = refer_seg_ds + + def __len__(self): + return self.samples_per_epoch + + def preprocess(self, x: torch.Tensor) -> torch.Tensor: + """Normalize pixel values and pad to a square input.""" + if self.model_type=="hq": + h, w = x.shape[-2:] + padh = self.img_size - h + padw = self.img_size - w + x = F.pad(x, (0, padw, 0, padh), value=128) + + # Normalize colors + x = (x - self.pixel_mean) / self.pixel_std + + if self.model_type=="effi" or self.model_type=="sam2": + x = F.interpolate(x.unsqueeze(0), (self.img_size, self.img_size), mode="bilinear").squeeze(0) + else: + # Pad + h, w = x.shape[-2:] + padh = self.img_size - h + padw = self.img_size - w + x = F.pad(x, (0, padw, 0, padh)) + return x + + def __getitem__(self, idx): + ds = random.randint(0, len(self.refer_seg_ds_list) - 1) + ds = self.refer_seg_ds_list[ds] + refer_seg_ds = self.refer_seg_data[ds] + images = refer_seg_ds["images"] + annotations = refer_seg_ds["annotations"] + img2refs = refer_seg_ds["img2refs"] + idx = random.randint(0, len(images) - 1) + image_info = images[idx] + image_path = image_info["file_name"] + image_id = image_info["id"] + refs = img2refs[image_id] + if len(refs) == 0: + return self.__getitem__(0) + + sents = [] + ann_ids = [] + for ref in refs: + for sent in ref["sentences"]: + text = sent["sent"] + sents.append(text) + ann_ids.append(ref["ann_id"]) + if len(sents) >= self.num_classes_per_sample: + sampled_inds = np.random.choice( + list(range(len(sents))), size=self.num_classes_per_sample, replace=False + ) + else: + sampled_inds = list(range(len(sents))) + sampled_sents = np.vectorize(sents.__getitem__)(sampled_inds).tolist() + # sampled_ann_ids = np.vectorize(ann_ids.__getitem__)(sampled_inds).tolist() + sampled_ann_ids = [ann_ids[ind] for ind in sampled_inds] + sampled_classes = sampled_sents + image = cv2.imread(image_path) + image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) + + # preprocess image for evf + image_evf = self.image_preprocessor(image) + + image = self.transform.apply_image(image) # preprocess image for sam + resize = image.shape[:2] + + image = self.preprocess(torch.from_numpy(image).permute(2, 0, 1).contiguous()) + + flag = False + masks = [] + for ann_id in sampled_ann_ids: + if isinstance(ann_id, list): + flag = True + if -1 in ann_id: + assert len(ann_id) == 1 + m = np.zeros((image_info["height"], image_info["width"])).astype( + np.uint8 + ) + else: + m_final = np.zeros( + (image_info["height"], image_info["width"]) + ).astype(np.uint8) + for ann_id_i in ann_id: + ann = annotations[ann_id_i] + + if len(ann["segmentation"]) == 0: + m = np.zeros( + (image_info["height"], image_info["width"]) + ).astype(np.uint8) + else: + if type(ann["segmentation"][0]) == list: # polygon + rle = mask.frPyObjects( + ann["segmentation"], + image_info["height"], + image_info["width"], + ) + else: + rle = ann["segmentation"] + for i in range(len(rle)): + if not isinstance(rle[i]["counts"], bytes): + rle[i]["counts"] = rle[i]["counts"].encode() + m = mask.decode(rle) + m = np.sum( + m, axis=2 + ) # sometimes there are multiple binary map (corresponding to multiple segs) + m = m.astype(np.uint8) # convert to np.uint8 + m_final = m_final | m + m = m_final + masks.append(m) + continue + + ann = annotations[ann_id] + + if len(ann["segmentation"]) == 0: + m = np.zeros((image_info["height"], image_info["width"])).astype( + np.uint8 + ) + masks.append(m) + continue + + if type(ann["segmentation"][0]) == list: # polygon + rle = mask.frPyObjects( + ann["segmentation"], image_info["height"], image_info["width"] + ) + else: + rle = ann["segmentation"] + for i in range(len(rle)): + if not isinstance(rle[i]["counts"], bytes): + rle[i]["counts"] = rle[i]["counts"].encode() + m = mask.decode(rle) + m = np.sum( + m, axis=2 + ) # sometimes there are multiple binary map (corresponding to multiple segs) + m = m.astype(np.uint8) # convert to np.uint8 + masks.append(m) + + masks = np.stack(masks, axis=0) + + masks = torch.from_numpy(masks) + label = torch.ones(masks.shape[1], masks.shape[2]) * self.ignore_label + + return ( + image_path, + image, + image_evf, + masks, + label, + resize, + sampled_classes, + ) diff --git a/py/evf_sam/utils/sem_seg_dataset.py b/py/evf_sam/utils/sem_seg_dataset.py new file mode 100644 index 0000000..b19fd1a --- /dev/null +++ b/py/evf_sam/utils/sem_seg_dataset.py @@ -0,0 +1,290 @@ +import glob +import json +import os +import random + +import cv2 +import numpy as np +import torch +import torch.nn.functional as F +from PIL import Image +from pycocotools.coco import COCO + +from model.segment_anything.utils.transforms import ResizeLongestSide +from torchvision import transforms + +def init_mapillary(base_image_dir): + mapillary_data_root = os.path.join(base_image_dir, "mapillary") + with open(os.path.join(mapillary_data_root, "config_v2.0.json")) as f: + mapillary_classes = json.load(f)["labels"] + mapillary_classes = [x["readable"].lower() for x in mapillary_classes] + mapillary_classes = np.array(mapillary_classes) + mapillary_labels = sorted( + glob.glob( + os.path.join(mapillary_data_root, "training", "v2.0", "labels", "*.png") + ) + ) + mapillary_images = [ + x.replace(".png", ".jpg").replace("v2.0/labels", "images") + for x in mapillary_labels + ] + print("mapillary: ", len(mapillary_images)) + return mapillary_classes, mapillary_images, mapillary_labels + + +def init_ade20k(base_image_dir): + with open("utils/ade20k_classes.json", "r") as f: + ade20k_classes = json.load(f) + ade20k_classes = np.array(ade20k_classes) + image_ids = sorted( + os.listdir(os.path.join(base_image_dir, "ade20k/images", "training")) + ) + ade20k_image_ids = [] + for x in image_ids: + if x.endswith(".jpg"): + ade20k_image_ids.append(x[:-4]) + ade20k_images = [] + for image_id in ade20k_image_ids: # self.descriptions: + ade20k_images.append( + os.path.join( + base_image_dir, + "ade20k", + "images", + "training", + "{}.jpg".format(image_id), + ) + ) + ade20k_labels = [ + x.replace(".jpg", ".png").replace("images", "annotations") + for x in ade20k_images + ] + print("ade20k: ", len(ade20k_images)) + return ade20k_classes, ade20k_images, ade20k_labels + +def init_paco_lvis(base_image_dir): + coco_api_paco_lvis = COCO( + os.path.join( + base_image_dir, "vlpart", "paco", "annotations", "paco_lvis_v1_train.json" + ) + ) + all_classes = coco_api_paco_lvis.loadCats(coco_api_paco_lvis.getCatIds()) + class_map_paco_lvis = {} + for cat in all_classes: + cat_split = cat["name"].strip().split(":") + if len(cat_split) == 1: + name = cat_split[0].split("_(")[0] + else: + assert len(cat_split) == 2 + obj, part = cat_split + obj = obj.split("_(")[0] + part = part.split("_(")[0] + name = (obj, part) + class_map_paco_lvis[cat["id"]] = name + img_ids = coco_api_paco_lvis.getImgIds() + print("paco_lvis: ", len(img_ids)) + return class_map_paco_lvis, img_ids, coco_api_paco_lvis + + +def init_pascal_part(base_image_dir): + coco_api_pascal_part = COCO( + os.path.join(base_image_dir, "vlpart", "pascal_part", "train.json") + ) + all_classes = coco_api_pascal_part.loadCats(coco_api_pascal_part.getCatIds()) + class_map_pascal_part = {} + for cat in all_classes: + cat_main, cat_part = cat["name"].strip().split(":") + name = (cat_main, cat_part) + class_map_pascal_part[cat["id"]] = name + img_ids = coco_api_pascal_part.getImgIds() + print("pascal_part: ", len(img_ids)) + return class_map_pascal_part, img_ids, coco_api_pascal_part + + +class SemSegDataset(torch.utils.data.Dataset): + pixel_mean = torch.Tensor([123.675, 116.28, 103.53]).view(-1, 1, 1) + pixel_std = torch.Tensor([58.395, 57.12, 57.375]).view(-1, 1, 1) + img_size = 1024 + ignore_label = 255 + + def __init__( + self, + base_image_dir, + tokenizer, + samples_per_epoch=500 * 8 * 2 * 10, + precision: str = "fp32", + image_size: int = 224, + num_classes_per_sample: int = 3, + exclude_val=False, + sem_seg_data="ade20k||pascal_part||mapillary", + model_type="ori", + transform=ResizeLongestSide(1024), + ): + self.model_type = model_type + self.exclude_val = exclude_val + self.samples_per_epoch = samples_per_epoch + self.num_classes_per_sample = num_classes_per_sample + + self.base_image_dir = base_image_dir + self.tokenizer = tokenizer + self.precision = precision + self.transform = transform + self.image_preprocessor = transforms.Compose([ + transforms.ToTensor(), + transforms.Resize((image_size, image_size), interpolation=3), + transforms.Normalize(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5)) + ]) + + self.data2list = {} + self.data2classes = {} + + self.sem_seg_datas = sem_seg_data.split("||") + for ds in self.sem_seg_datas: + classes, images, labels = eval("init_{}".format(ds))(base_image_dir) + self.data2list[ds] = (images, labels) + self.data2classes[ds] = classes + + + def __len__(self): + return self.samples_per_epoch + + def preprocess(self, x: torch.Tensor) -> torch.Tensor: + """Normalize pixel values and pad to a square input.""" + if self.model_type=="hq": + h, w = x.shape[-2:] + padh = self.img_size - h + padw = self.img_size - w + x = F.pad(x, (0, padw, 0, padh), value=128) + + # Normalize colors + x = (x - self.pixel_mean) / self.pixel_std + + if self.model_type=="effi" or self.model_type=="sam2": + x = F.interpolate(x.unsqueeze(0), (self.img_size, self.img_size), mode="bilinear").squeeze(0) + else: + # Pad + h, w = x.shape[-2:] + padh = self.img_size - h + padw = self.img_size - w + x = F.pad(x, (0, padw, 0, padh)) + return x + + def __getitem__(self, idx): + ds = random.randint(0, len(self.sem_seg_datas) - 1) + ds = self.sem_seg_datas[ds] + + if ds in ["pascal_part"]: + class_map = self.data2classes[ds] + img_ids, coco_api = self.data2list[ds] + idx = random.randint(0, len(img_ids) - 1) + img_id = img_ids[idx] + image_info = coco_api.loadImgs([img_id])[0] + file_name = image_info["file_name"] + file_name = os.path.join( + "VOCdevkit", "VOC2010", "JPEGImages", file_name + ) + image_path = os.path.join(self.base_image_dir, "vlpart", ds, file_name) + + image = cv2.imread(image_path) + image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) + + # preprocess image for evf + image_evf = self.image_preprocessor(image) + + image = self.transform.apply_image(image) # preprocess image for sam + resize = image.shape[:2] + annIds = coco_api.getAnnIds(imgIds=image_info["id"]) + anns = coco_api.loadAnns(annIds) + if len(anns) == 0: + return self.__getitem__(0) + if len(anns) >= self.num_classes_per_sample: + sampled_anns = np.random.choice( + anns, size=self.num_classes_per_sample, replace=False + ).tolist() + else: + sampled_anns = anns + sampled_classes = [] + for ann in sampled_anns: + sampled_cls = class_map[ann["category_id"]] + if isinstance(sampled_cls, tuple): + obj, part = sampled_cls + if random.random() < 0.5: + name = obj + " " + part + else: + name = "the {} of the {}".format(part, obj) + else: + name = sampled_cls + sampled_classes.append(name) + + elif ds in ["ade20k", "mapillary"]: + image, labels = self.data2list[ds] + idx = random.randint(0, len(image) - 1) + image_path = image[idx] + label_path = labels[idx] + label = Image.open(label_path) + label = np.array(label) + if ds == "ade20k": + label[label == 0] = 255 + label -= 1 + label[label == 254] = 255 + + img = cv2.imread(image_path) + image = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) + # preprocess image for evf + image_evf = self.image_preprocessor(image) + image = self.transform.apply_image(image) # preprocess image for sam + resize = image.shape[:2] + unique_label = np.unique(label).tolist() + if 255 in unique_label: + unique_label.remove(255) + if len(unique_label) == 0: + return self.__getitem__(0) + + classes = [self.data2classes[ds][class_id] for class_id in unique_label] + if len(classes) >= self.num_classes_per_sample: + sampled_classes = np.random.choice( + classes, size=self.num_classes_per_sample, replace=False + ).tolist() + else: + sampled_classes = classes + + class_ids = [] + for sampled_cls in sampled_classes: + assert len(sampled_cls.split("||")) == 1 + + if ds in ["paco_lvis", "pascal_part"]: + continue + + class_id = self.data2classes[ds].tolist().index(sampled_cls) + class_ids.append(class_id) + + image = self.preprocess(torch.from_numpy(image).permute(2, 0, 1).contiguous()) + + if ds in ["pascal_part"]: + masks = [] + for ann in sampled_anns: + try: + masks.append(coco_api.annToMask(ann)) + except Exception as e: + print(e) + return self.__getitem__(0) + + masks = np.stack(masks, axis=0) + masks = torch.from_numpy(masks) + label = torch.ones(masks.shape[1], masks.shape[2]) * self.ignore_label + + else: + label = torch.from_numpy(label).long() + masks = [] + for class_id in class_ids: + masks.append(label == class_id) + masks = torch.stack(masks, dim=0) + # sampled_classes = ["all "+_ for _ in sampled_classes] + return ( + image_path, + image, + image_evf, + masks, + label, + resize, + sampled_classes, + ) diff --git a/py/evf_sam/utils/utils.py b/py/evf_sam/utils/utils.py new file mode 100644 index 0000000..4900182 --- /dev/null +++ b/py/evf_sam/utils/utils.py @@ -0,0 +1,127 @@ +from enum import Enum + +import numpy as np +import torch +import torch.distributed as dist + +IGNORE_INDEX = -100 + +class Summary(Enum): + NONE = 0 + AVERAGE = 1 + SUM = 2 + COUNT = 3 + + +class AverageMeter(object): + """Computes and stores the average and current value""" + + def __init__(self, name, fmt=":f", summary_type=Summary.AVERAGE): + self.name = name + self.fmt = fmt + self.summary_type = summary_type + self.reset() + + def reset(self): + self.val = 0 + self.avg = 0 + self.sum = 0 + self.count = 0 + + def update(self, val, n=1): + self.val = val + self.sum += val * n + self.count += n + self.avg = self.sum / self.count + + def all_reduce(self): + device = "cuda" if torch.cuda.is_available() else "cpu" + if isinstance(self.sum, np.ndarray): + total = torch.tensor( + self.sum.tolist() + + [ + self.count, + ], + dtype=torch.float32, + device=device, + ) + else: + total = torch.tensor( + [self.sum, self.count], dtype=torch.float32, device=device + ) + + dist.all_reduce(total, dist.ReduceOp.SUM, async_op=False) + if total.shape[0] > 2: + self.sum, self.count = total[:-1].cpu().numpy(), total[-1].cpu().item() + else: + self.sum, self.count = total.tolist() + self.avg = self.sum / (self.count + 1e-5) + + def __str__(self): + fmtstr = "{name} {val" + self.fmt + "} ({avg" + self.fmt + "})" + return fmtstr.format(**self.__dict__) + + def summary(self): + fmtstr = "" + if self.summary_type is Summary.NONE: + fmtstr = "" + elif self.summary_type is Summary.AVERAGE: + fmtstr = "{name} {avg:.3f}" + elif self.summary_type is Summary.SUM: + fmtstr = "{name} {sum:.3f}" + elif self.summary_type is Summary.COUNT: + fmtstr = "{name} {count:.3f}" + else: + raise ValueError("invalid summary type %r" % self.summary_type) + + return fmtstr.format(**self.__dict__) + + +def intersectionAndUnionGPU(output, target, K, ignore_index=255): + # 'K' classes, output and target sizes are N or N * L or N * H * W, each value in range 0 to K - 1. + assert output.dim() in [1, 2, 3] + assert output.shape == target.shape + output = output.view(-1) + target = target.view(-1) + output[target == ignore_index] = ignore_index + intersection = output[output == target] + area_intersection = torch.histc(intersection, bins=K, min=0, max=K - 1) + area_output = torch.histc(output, bins=K, min=0, max=K - 1) + area_target = torch.histc(target, bins=K, min=0, max=K - 1) + area_union = area_output + area_target - area_intersection + return area_intersection, area_union, area_target + + +class ProgressMeter(object): + def __init__(self, num_batches, meters, prefix=""): + self.batch_fmtstr = self._get_batch_fmtstr(num_batches) + self.meters = meters + self.prefix = prefix + + def display(self, batch): + entries = [self.prefix + self.batch_fmtstr.format(batch)] + entries += [str(meter) for meter in self.meters] + print("\t".join(entries)) + + def display_summary(self): + entries = [" *"] + entries += [meter.summary() for meter in self.meters] + print(" ".join(entries)) + + def _get_batch_fmtstr(self, num_batches): + num_digits = len(str(num_batches // 1)) + fmt = "{:" + str(num_digits) + "d}" + return "[" + fmt + "/" + fmt.format(num_batches) + "]" + + +def dict_to_cuda(input_dict): + for k, v in input_dict.items(): + if isinstance(input_dict[k], torch.Tensor): + input_dict[k] = v.cuda(non_blocking=True) + elif ( + isinstance(input_dict[k], list) + and len(input_dict[k]) > 0 + and isinstance(input_dict[k][0], torch.Tensor) + ): + input_dict[k] = [ele.cuda(non_blocking=True) for ele in v] + return input_dict diff --git a/py/evf_sam_ultra.py b/py/evf_sam_ultra.py new file mode 100644 index 0000000..72e1da6 --- /dev/null +++ b/py/evf_sam_ultra.py @@ -0,0 +1,120 @@ +# layerstyle advance + +''' +推理部分代码来自https://github.com/hustvl/EVF-SAM +''' +import sys + +from .imagefunc import * +sys.path.append(os.path.join(os.path.dirname(__file__), 'evf_sam')) +from evf_sam.evf_sam_inference import evf_sam_main +class EVF_SAM_Ultra: + + def __init__(self): + self.NODE_NAME = 'EVF_SAM Ultra' + pass + + @classmethod + def INPUT_TYPES(cls): + # model_list = ["evf-sam2","evf-sam", "evf-sam2-multitask", "evf-sam-multitask"] + model_list = ["evf-sam2", "evf-sam"] + precision_list = ["fp16", "bf16", "fp32"] + load_in_bit_list = ["full", "8", "4"] + method_list = ['VITMatte', 'VITMatte(local)', 'PyMatting', 'GuidedFilter', ] + device_list = ['cuda', 'cpu'] + return {"required": + { + "image": ("IMAGE",), + "model": (model_list,), + "precision": (precision_list,), + "load_in_bit": (load_in_bit_list,), + "prompt": ("STRING", {"default": "subject"}), + "detail_method": (method_list,), + "detail_erode": ("INT", {"default": 6, "min": 1, "max": 255, "step": 1}), + "detail_dilate": ("INT", {"default": 4, "min": 1, "max": 255, "step": 1}), + "black_point": ("FLOAT", {"default": 0.01, "min": 0.01, "max": 0.98, "step": 0.01, "display": "slider"}), + "white_point": ("FLOAT", {"default": 0.99, "min": 0.02, "max": 0.99, "step": 0.01, "display": "slider"}), + "process_detail": ("BOOLEAN", {"default": True}), + "device": (device_list,), + "max_megapixels": ("FLOAT", {"default": 2.0, "min": 1, "max": 999, "step": 0.1}), + } + } + + RETURN_TYPES = ("IMAGE", "MASK",) + RETURN_NAMES = ("image", "mask",) + FUNCTION = "evf_sam_ultra" + CATEGORY = '😺dzNodes/LayerMask' + + def evf_sam_ultra(self, image, model, precision, load_in_bit, prompt, + detail_method, detail_erode, detail_dilate, black_point, white_point, + process_detail, device, max_megapixels, + ): + + ret_images = [] + ret_masks = [] + + if detail_method == 'VITMatte(local)': + local_files_only = True + else: + local_files_only = False + + if model == 'evf-sam2' or model == 'evf-sam2-multitask': + model_type = 'sam2' + elif model == 'evf-sam' or model == 'evf-sam-multitask': + model_type = 'ori' + else: + model_type = 'effi' + + if load_in_bit == 'full': + load_in_bit = 16 + else: + load_in_bit = int(load_in_bit) + + model_path = "" + model_folder_name = 'EVF-SAM' + try: + model_path = os.path.join( + os.path.normpath(folder_paths.folder_names_and_paths[model_folder_name][0][0]), model) + except: + pass + if not os.path.exists(model_path): + model_path = os.path.join(folder_paths.models_dir, model_folder_name, model) + + for i in image: + i = torch.unsqueeze(i, 0) + orig_image = tensor2pil(i).convert('RGB') + sys.path.append(os.path.dirname(os.path.abspath(__file__))) + + mask_image = evf_sam_main(model_path, model_type, precision, load_in_bit, orig_image, prompt) + _mask = pil2tensor(mask_image) + + detail_range = detail_erode + detail_dilate + if process_detail: + if detail_method == 'GuidedFilter': + _mask = guided_filter_alpha(i, _mask, detail_range // 6 + 1) + _mask = tensor2pil(histogram_remap(_mask, black_point, white_point)) + elif detail_method == 'PyMatting': + _mask = tensor2pil(mask_edge_detail(i, _mask, detail_range // 8 + 1, black_point, white_point)) + else: + _trimap = generate_VITMatte_trimap(_mask, detail_erode, detail_dilate) + _mask = generate_VITMatte(orig_image, _trimap, local_files_only=local_files_only, device=device, + max_megapixels=max_megapixels) + _mask = tensor2pil(histogram_remap(pil2tensor(_mask), black_point, white_point)) + else: + _mask = mask2image(_mask) + + ret_image = RGB2RGBA(orig_image, _mask.convert('L')) + ret_images.append(pil2tensor(ret_image)) + ret_masks.append(image2mask(_mask)) + + log(f"{self.NODE_NAME} Processed {len(ret_images)} image(s).", message_type='finish') + return (torch.cat(ret_images, dim=0), torch.cat(ret_masks, dim=0),) + +NODE_CLASS_MAPPINGS = { + "LayerMask: EVFSAMUltra": EVF_SAM_Ultra +} + +NODE_DISPLAY_NAME_MAPPINGS = { + "LayerMask: EVFSAMUltra": "LayerMask: EVF-SAM Ultra(Advance)" +} + diff --git a/py/florence2_ultra.py b/py/florence2_ultra.py new file mode 100644 index 0000000..4749f99 --- /dev/null +++ b/py/florence2_ultra.py @@ -0,0 +1,615 @@ +# layerstyle advance + +import io +from unittest.mock import patch +import matplotlib.pyplot as plt +import matplotlib.patches as patches +import colorsys +from transformers.dynamic_module_utils import get_imports +import comfy.model_management +from .imagefunc import * + +colormap = ['blue', 'orange', 'green', 'purple', 'brown', 'pink', 'gray', 'olive', 'cyan', 'red', + 'lime', 'indigo', 'violet', 'aqua', 'magenta', 'coral', 'gold', 'tan', 'skyblue'] + +device = comfy.model_management.get_torch_device() + +fl2_model_repos = { + "base": "microsoft/Florence-2-base", + "base-ft": "microsoft/Florence-2-base-ft", + "large": "microsoft/Florence-2-large", + "large-ft": "microsoft/Florence-2-large-ft", + "DocVQA": "HuggingFaceM4/Florence-2-DocVQA", + "SD3-Captioner": "gokaygokay/Florence-2-SD3-Captioner", + "base-PromptGen": "MiaoshouAI/Florence-2-base-PromptGen", + "CogFlorence-2-Large-Freeze": "thwri/CogFlorence-2-Large-Freeze", + "CogFlorence-2.1-Large": "thwri/CogFlorence-2.1-Large", + "base-PromptGen-v1.5":"MiaoshouAI/Florence-2-base-PromptGen-v1.5", + "large-PromptGen-v1.5":"MiaoshouAI/Florence-2-large-PromptGen-v1.5", + "base-PromptGen-v2.0":"MiaoshouAI/Florence-2-base-PromptGen-v2.0", + "large-PromptGen-v2.0":"MiaoshouAI/Florence-2-large-PromptGen-v2.0" +} + +def fixed_get_imports(filename) -> list[str]: + """Workaround for FlashAttention""" + if os.path.basename(filename) != "modeling_florence2.py": + return get_imports(filename) + imports = get_imports(filename) + try: + imports.remove("flash_attn") + except: + pass + return imports + +def load_model(version): + florence_path = os.path.join(folder_paths.models_dir, "florence2") + os.makedirs(florence_path, exist_ok=True) + + model_path = os.path.join(florence_path, version) + attention = 'sdpa' + + if not os.path.exists(model_path): + log(f"Downloading Florence2 {version} model...") + repo_id = fl2_model_repos[version] + from huggingface_hub import snapshot_download + snapshot_download(repo_id=repo_id, local_dir=model_path, ignore_patterns=["*.md", "*.txt"]) + + try: + with patch("transformers.dynamic_module_utils.get_imports", fixed_get_imports): + # model = AutoModelForCausalLM.from_pretrained(model_path, trust_remote_code=True) + model = AutoModelForCausalLM.from_pretrained(model_path, attn_implementation=attention, device_map=device, + torch_dtype=torch.float32, trust_remote_code=True) + processor = AutoProcessor.from_pretrained(model_path, trust_remote_code=True) + except Exception as e: + try: + model = AutoModelForCausalLM.from_pretrained(model_path, attn_implementation=attention, device_map=device, + torch_dtype=torch.float32, trust_remote_code=True) + processor = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True) + except Exception as e: + sys.path.append(model_path) + # Import the Florence modules + if version == 'large-PromptGen-v1.5': + from florence2_large.modeling_florence2 import Florence2ForConditionalGeneration + from florence2_large.configuration_florence2 import Florence2Config + elif version == 'base-PromptGen-v1.5': + from florence2_base_ft.modeling_florence2 import Florence2ForConditionalGeneration + from florence2_base_ft.configuration_florence2 import Florence2Config + else: + log(f"Error loading model or tokenizer: {str(e)}", message_type='error') + return (None, None) + + # Load the model configuration + model_config = Florence2Config.from_pretrained(model_path) + # Load the model + with patch("transformers.dynamic_module_utils.get_imports", fixed_get_imports): + model = Florence2ForConditionalGeneration.from_pretrained( + model_path, + config=model_config, + attn_implementation=attention, + device_map=device + ).to(device) + + processor = AutoProcessor.from_pretrained(model_path, trust_remote_code=True) + + return (model.to(device), processor) + +def fig_to_pil(fig): + buf = io.BytesIO() + fig.savefig(buf, format='png', dpi=100, bbox_inches='tight', pad_inches=0) + buf.seek(0) + pil = Image.open(buf) + plt.close() + return pil + +def plot_bbox(image, data): + fig, ax = plt.subplots() + fig.set_size_inches(image.width / 100, image.height / 100) + ax.imshow(image) + for i, (bbox, label) in enumerate(zip(data['bboxes'], data['labels'])): + x1, y1, x2, y2 = bbox + rect = patches.Rectangle((x1, y1), x2 - x1, y2 - y1, linewidth=1, edgecolor='r', facecolor='none') + ax.add_patch(rect) + enum_label = f"{i}: {label}" + plt.text(x1 + 7, y1 + 17, enum_label, color='white', fontsize=8, bbox=dict(facecolor='red', alpha=0.5)) + ax.axis('off') + return fig + +def generate_color(index, total_colors=25): + # Generate color by varying the hue to maximize difference between colors + hue = (index / total_colors) % 1.0 # Normalize hue to be between 0 and 1 + saturation = 0.65 # Keep saturation constant + lightness = 0.5 # Keep lightness constant + + # Convert HSL to RGB, then to hexadecimal + r, g, b = colorsys.hls_to_rgb(hue, lightness, saturation) + return f'#{int(r * 255):02X}{int(g * 255):02X}{int(b * 255):02X}' + +def plot_mask_bbox(image, data): + fig, ax = plt.subplots() + fig.set_size_inches(image.width / 100, image.height / 100) + ax.imshow(image) + num_bboxes = len(data['bboxes']) + for i, (bbox, label) in enumerate(list(zip(data['bboxes'], data['labels']))[1:], start=1): + x1, y1, x2, y2 = bbox + if x2 < x1: + x1, y1, x2, y2 = x2, y2, x1, y1 + color = generate_color(i, total_colors=num_bboxes) + rect = patches.Rectangle((x1, y1), x2 - x1, y2 - y1, linewidth=1, edgecolor=color, facecolor='none') + ax.add_patch(rect) + enum_label = f"{i}: {label}" + plt.text(x1 + 7, y1 + 17, enum_label, color='white', fontsize=8, bbox=dict(facecolor=color, alpha=0.5)) + ax.axis('off') + return fig + +def plot_mask(image, data, indexes): + # Create a black background image (mode "1" for binary, "L" for grayscale) + mask = Image.new("L", (image.width, image.height), 0) # Black background + fig, ax = plt.subplots() + fig.set_size_inches(mask.width / 100, mask.height / 100) + ax.imshow(mask, cmap='gray') # Display the mask in grayscale + ax.set_facecolor('black') # Set the axes background to black + fig.patch.set_facecolor('black') # Set the figure background to black + for i, (bbox, label) in enumerate(list(zip(data['bboxes'], data['labels']))[1:], start=1): + x1, y1, x2, y2 = bbox + if x2 < x1: + x1, y1, x2, y2 = x2, y2, x1, y1 + rect = patches.Rectangle((x1, y1), x2 - x1, y2 - y1, linewidth=1, edgecolor='w', facecolor='w') + if i in indexes: + ax.add_patch(rect) + ax.axis('off') + return fig + +def draw_polygons(image, prediction, fill_mask=False): + output_image = copy.deepcopy(image) + draw = ImageDraw.Draw(output_image) + scale = 1 + for polygons, label in zip(prediction['polygons'], prediction['labels']): + color = random.choice(colormap) + fill_color = color if fill_mask else None + for _polygon in polygons: + _polygon = np.array(_polygon).reshape(-1, 2) + if len(_polygon) < 3: + print('Invalid polygon:', _polygon) + continue + _polygon = (_polygon * scale).reshape(-1).tolist() + if fill_mask: + draw.polygon(_polygon, outline=color, fill=fill_color) + else: + draw.polygon(_polygon, outline=color) + draw.text((_polygon[0] + 8, _polygon[1] + 2), label, fill=color) + return output_image + + +def convert_to_od_format(data): + od_results = { + 'bboxes': data.get('bboxes', []), + 'labels': data.get('bboxes_labels', []) + } + return od_results + + +def draw_ocr_bboxes(image, prediction): + scale = 1 + output_image = copy.deepcopy(image) + draw = ImageDraw.Draw(output_image) + bboxes, labels = prediction['quad_boxes'], prediction['labels'] + for box, label in zip(bboxes, labels): + color = random.choice(colormap) + new_box = (np.array(box) * scale).tolist() + draw.polygon(new_box, width=3, outline=color) + draw.text((new_box[0] + 8, new_box[1] + 2), + "{}".format(label), + align="right", + fill=color) + return output_image + + +def run_example(model, processor, task_prompt, image, max_new_tokens, num_beams, do_sample, text_input=None): + if text_input is None: + prompt = task_prompt + else: + prompt = task_prompt + text_input + inputs = processor(text=prompt, images=image, return_tensors="pt").to(device) + generated_ids = model.generate( + input_ids=inputs["input_ids"], + pixel_values=inputs["pixel_values"], + max_new_tokens=max_new_tokens, + early_stopping=False, + do_sample=do_sample, + num_beams=num_beams, + ) + generated_text = processor.batch_decode(generated_ids, skip_special_tokens=False)[0] + parsed_answer = processor.post_process_generation( + generated_text, + task=task_prompt, + image_size=(image.width, image.height) + ) + return parsed_answer + + +def process_image(model, processor, image, task_prompt, max_new_tokens, num_beams, do_sample, fill_mask, text_input=None): + if task_prompt == 'caption': + task_prompt = '' + result = run_example(model, processor, task_prompt, image, max_new_tokens, num_beams, do_sample) + return result[task_prompt], None + elif task_prompt == 'detailed caption': + task_prompt = '' + result = run_example(model, processor, task_prompt, image, max_new_tokens, num_beams, do_sample) + return result[task_prompt], None + elif task_prompt == 'more detailed caption': + task_prompt = '' + result = run_example(model, processor, task_prompt, image, max_new_tokens, num_beams, do_sample) + return result[task_prompt], None + elif task_prompt == 'object detection': + task_prompt = '' + results = run_example(model, processor, task_prompt, image, max_new_tokens, num_beams, do_sample) + fig = plot_bbox(image, results['']) + return results[task_prompt], fig_to_pil(fig) + elif task_prompt == 'dense region caption': + task_prompt = '' + results = run_example(model, processor, task_prompt, image, max_new_tokens, num_beams, do_sample) + fig = plot_bbox(image, results['']) + return results[task_prompt], fig_to_pil(fig) + elif task_prompt == 'region proposal': + task_prompt = '' + results = run_example(model, processor, task_prompt, image, max_new_tokens, num_beams, do_sample) + fig = plot_bbox(image, results['']) + return results[task_prompt], fig_to_pil(fig) + elif task_prompt == 'region proposal (mask)': + task_prompt = '' + results = run_example(model, processor, task_prompt, image, max_new_tokens, num_beams, do_sample) + indexes = [] + if isinstance(text_input, str): + for i in text_input.split(','): + try: + indexes.append(int(i)) + except ValueError: + print(f"{i} is nit an instance of int") + if len(indexes) > 0: + fig = plot_mask(image, results[''], indexes) + pil = fig_to_pil(fig).resize((image.width, image.height), Image.Resampling.LANCZOS) + else: + fig = plot_mask_bbox(image, results['']) + pil = fig_to_pil(fig) + return results[task_prompt], pil + elif task_prompt == 'caption to phrase grounding': + task_prompt = '' + results = run_example(model, processor, task_prompt, image, max_new_tokens, num_beams, do_sample, text_input) + fig = plot_bbox(image, results['']) + return results[task_prompt], fig_to_pil(fig) + elif task_prompt == 'referring expression segmentation': + task_prompt = '' + results = run_example(model, processor, task_prompt, image, max_new_tokens, num_beams, do_sample, text_input) + output_image = draw_polygons(image, results[''], fill_mask) + return results[task_prompt], output_image + elif task_prompt == 'region to segmentation': + task_prompt = '' + results = run_example(model, processor, task_prompt, image, max_new_tokens, num_beams, do_sample, text_input) + output_image = draw_polygons(image, results[''], fill_mask) + return results[task_prompt], output_image + elif task_prompt == 'open vocabulary detection': + task_prompt = '' + results = run_example(model, processor, task_prompt, image, max_new_tokens, num_beams, do_sample, text_input) + bbox_results = convert_to_od_format(results['']) + fig = plot_bbox(image, bbox_results) + return bbox_results, fig_to_pil(fig) + elif task_prompt == 'region to category': + task_prompt = '' + results = run_example(model, processor, task_prompt, image, max_new_tokens, num_beams, do_sample, text_input) + return results[task_prompt], None + elif task_prompt == 'region to description': + task_prompt = '' + results = run_example(model, processor, task_prompt, image, max_new_tokens, num_beams, do_sample, text_input) + return results[task_prompt], None + elif task_prompt == 'OCR': + task_prompt = '' + result = run_example(model, processor, task_prompt, image, max_new_tokens, num_beams, do_sample) + return result[task_prompt], None + elif task_prompt == 'OCR with region': + task_prompt = '' + results = run_example(model, processor, task_prompt, image, max_new_tokens, num_beams, do_sample) + output_image = draw_ocr_bboxes(image, results['']) + output_results = {'bboxes': results[task_prompt].get('quad_boxes', []), + 'labels': results[task_prompt].get('labels', [])} + return output_results, output_image + # gokaygokay/Florence-2-SD3-Captioner task + elif task_prompt == 'description': + task_prompt = '' + result = run_example(model, processor, task_prompt, image, max_new_tokens, num_beams, do_sample) + return result[task_prompt], None + # MiaoshouAI/Florence-2-large-PromptGen-v1.5 task + elif task_prompt == 'generate tags(PromptGen 1.5)': + task_prompt = '' + result = run_example(model, processor, task_prompt, image, max_new_tokens, num_beams, do_sample) + return result[task_prompt], None + elif task_prompt == 'mixed caption(PromptGen 1.5)': + task_prompt = '' + result = run_example(model, processor, task_prompt, image, max_new_tokens, num_beams, do_sample) + return result[task_prompt], None + elif task_prompt == 'mixed caption plus(PromptGen 2.0)': + task_prompt = '' + result = run_example(model, processor, task_prompt, image, max_new_tokens, num_beams, do_sample) + return result[task_prompt], None + elif task_prompt == 'analyze(PromptGen 2.0)': + task_prompt = '<>' + result = run_example(model, processor, task_prompt, image, max_new_tokens, num_beams, do_sample) + return result[task_prompt], None + + else: + return "", None # Return empty string and None for unknown task prompts + + +def remove_angle_bracket_content(text): + import re + # 正则表达式匹配 "<>" 包围的内容,包括尖括号本身 + pattern = r'<[^>]*>' + # 使用 re.sub 替换匹配的内容为空字符串 + cleaned_text = re.sub(pattern, '', text) + return cleaned_text + + +def decode_f_bboxes(F_BBOXES): + if isinstance(F_BBOXES, str): + return (torch.zeros(1, 512, 512, dtype=torch.float32), F_BBOXES) + + width = F_BBOXES["width"] + height = F_BBOXES["height"] + mask = np.zeros((height, width), dtype=np.uint8) + + x1_c = width + y1_c = height + x2_c = y2_c = 0 + label = "" + if "bboxes" in F_BBOXES: + for idx in range(len(F_BBOXES["bboxes"])): + bbox = F_BBOXES["bboxes"][idx] + + new_label = F_BBOXES["labels"][idx].removeprefix("") + if new_label not in label: + if idx > 0: + label = label + ", " + label = label + new_label + + if len(bbox) == 4: + x1, y1, x2, y2 = int(bbox[0]), int(bbox[1]), int(bbox[2]), int(bbox[3]) + elif len(bbox) == 8: + x1 = int(min(bbox[0::2])) + x2 = int(max(bbox[0::2])) + y1 = int(min(bbox[1::2])) + y2 = int(max(bbox[1::2])) + else: + continue + + x1_c = min(x1_c, x1) + y1_c = min(y1_c, y1) + x2_c = max(x2_c, x2) + y2_c = max(y2_c, y2) + + mask[y1:y2, x1:x2] = 1 + + else: + image = Image.new('RGB', (width, height), color='black') + draw = ImageDraw.Draw(image) + + x1_c = width + y1_c = height + x2_c = y2_c = 0 + + for polygon in F_BBOXES["polygons"][0]: + _polygon = np.array(polygon).reshape(-1, 2) + if len(_polygon) < 3: + print('Invalid polygon:', _polygon) + continue + + draw.polygon(_polygon.flatten().tolist(), outline='white', fill='white') + + x1_c = min(x1_c, int(min(polygon[0::2]))) + x2_c = max(x2_c, int(max(polygon[0::2]))) + y1_c = min(y1_c, int(min(polygon[1::2]))) + y2_c = max(y2_c, int(max(polygon[1::2]))) + + mask = np.asarray(image)[..., 0].astype(np.float32) / 255 + + mask = torch.from_numpy(mask.astype(np.float32)).unsqueeze(0) + # label = remove_angle_bracket_content(label) + return (mask, label) + + +class LS_LoadFlorence2Model: + def __init__(self): + self.model = None + self.processor = None + self.version = None + + @classmethod + def INPUT_TYPES(s): + model_list = list(fl2_model_repos.keys()) + return { + "required": { + "version": (model_list,{"default": model_list[0]}), + }, + } + + RETURN_TYPES = ("FLORENCE2",) + RETURN_NAMES = ("florence2_model",) + FUNCTION = "load" + CATEGORY = '😺dzNodes/LayerMask' + + def load(self, version): + if self.version != version: + self.model, self.processor = load_model(version) + self.version = version + + return ({'model': self.model, 'processor': self.processor, 'version': self.version, 'device': device},) + + +class Florence2Ultra: + def __init__(self): + self.NODE_NAME = 'Florence2Ultra' + + @classmethod + def INPUT_TYPES(s): + segment_task_list = [ + "region to segmentation", + "referring expression segmentation", + "open vocabulary detection", + ] + method_list = ['VITMatte', 'VITMatte(local)', 'PyMatting', 'GuidedFilter', ] + device_list = ['cuda','cpu'] + return { + "required": { + "florence2_model": ("FLORENCE2",), + "image": ("IMAGE",), + "task": (segment_task_list,{"default": segment_task_list[0]}), + "text_input": ("STRING", {"default": "subject"}), + "detail_method": (method_list,), + "detail_erode": ("INT", {"default": 6, "min": 1, "max": 255, "step": 1}), + "detail_dilate": ("INT", {"default": 6, "min": 1, "max": 255, "step": 1}), + "black_point": ("FLOAT", {"default": 0.01, "min": 0.01, "max": 0.98, "step": 0.01, "display": "slider"}), + "white_point": ("FLOAT", {"default": 0.99, "min": 0.02, "max": 0.99, "step": 0.01, "display": "slider"}), + "process_detail": ("BOOLEAN", {"default": True}), + "device": (device_list,), + "max_megapixels": ("FLOAT", {"default": 2.0, "min": 1, "max": 999, "step": 0.1}), + }, + } + + RETURN_TYPES = ("IMAGE", "MASK",) + RETURN_NAMES = ("image", "mask",) + FUNCTION = "florence2_ultra" + CATEGORY = '😺dzNodes/LayerMask' + + def florence2_ultra(self, florence2_model, image, task, text_input, + detail_method, detail_erode, detail_dilate, + black_point, white_point, process_detail, device, max_megapixels): + max_new_tokens = 512 + num_beams = 3 + do_sample = False + fill_mask = False + + ret_images = [] + ret_masks = [] + + if detail_method == 'VITMatte(local)': + local_files_only = True + else: + local_files_only = False + + model = florence2_model['model'] + processor = florence2_model['processor'] + + for i in image: + img = tensor2pil(i).convert("RGB") + + results, _ = process_image(model, processor, img, task, + max_new_tokens, num_beams, do_sample, + fill_mask, text_input) + + if isinstance(results, dict): + results["width"] = img.width + results["height"] = img.height + + _mask, _ = decode_f_bboxes(results) + + if process_detail: + detail_range = detail_erode + detail_dilate + if detail_method == 'GuidedFilter': + _mask = guided_filter_alpha(i, _mask, detail_range // 6 + 1) + _mask = tensor2pil(histogram_remap(_mask, black_point, white_point)) + elif detail_method == 'PyMatting': + _mask = tensor2pil(mask_edge_detail(i, _mask, detail_range // 8 + 1, black_point, white_point)) + else: + _trimap = generate_VITMatte_trimap(_mask, detail_erode, detail_dilate) + _mask = generate_VITMatte(img, _trimap, local_files_only=local_files_only, device=device, max_megapixels=max_megapixels) + _mask = tensor2pil(histogram_remap(pil2tensor(_mask), black_point, white_point)) + else: + _mask = tensor2pil(_mask) + + ret_image = RGB2RGBA(img, _mask.convert('L')) + ret_images.append(pil2tensor(ret_image)) + ret_masks.append(image2mask(_mask)) + + return (torch.cat(ret_images, dim=0), torch.cat(ret_masks, dim=0),) + + +class Florence2Image2Prompt: + + def __init__(self): + self.NODE_NAME = 'Florence2Image2Prompt' + + @classmethod + def INPUT_TYPES(s): + caption_task_list = [ + "caption", + "detailed caption", + "more detailed caption", + 'description', + 'generate tags(PromptGen 1.5)', + 'mixed caption(PromptGen 1.5)', + 'mixed caption plus(PromptGen 2.0)', + 'analyze(PromptGen 2.0)', + "object detection", + "dense region caption", + "region proposal", + "region proposal (mask)", + "caption to phrase grounding", + "open vocabulary detection", + "region to category", + "region to description", + "OCR", + "OCR with region", + ] + return { + "required": { + "florence2_model": ("FLORENCE2",), + "image": ("IMAGE",), + "task": (caption_task_list,{"default": caption_task_list[2]}), + "text_input": ("STRING", {"default": ""}), + "max_new_tokens": ("INT", {"default": 1024, "step": 1}), + "num_beams": ("INT", {"default": 3, "min": 1, "step": 1}), + "do_sample": ('BOOLEAN', {"default": False}), + "fill_mask": ('BOOLEAN', {"default": False}), + }, + } + + RETURN_TYPES = ("STRING", "IMAGE",) + RETURN_NAMES = ("text", "preview_image",) + FUNCTION = "florence2_image2prompt" + CATEGORY = '😺dzNodes/LayerUtility/Prompt' + + def florence2_image2prompt(self, florence2_model, image, task, text_input, + max_new_tokens, num_beams, do_sample, fill_mask): + + model = florence2_model['model'] + processor = florence2_model['processor'] + + img = tensor2pil(image[0]) + caption = "" + results, output_image = process_image(model, processor, img, task, max_new_tokens, num_beams, + do_sample, fill_mask, + text_input) + + if isinstance(results, dict): + results["width"] = img.width + results["height"] = img.height + + if output_image == None: + output_image = image[0].detach().clone().unsqueeze(0) + else: + output_image = np.asarray(output_image).astype(np.float32) / 255 + output_image = torch.from_numpy(output_image).unsqueeze(0) + + _, caption = decode_f_bboxes(results) + + return (remove_angle_bracket_content(caption), output_image,) + +NODE_CLASS_MAPPINGS = { + "LayerMask: Florence2Ultra": Florence2Ultra, + "LayerMask: LoadFlorence2Model": LS_LoadFlorence2Model, + "LayerUtility: Florence2Image2Prompt": Florence2Image2Prompt +} + +NODE_DISPLAY_NAME_MAPPINGS = { + "LayerMask: Florence2Ultra": "LayerMask: Florence2 Ultra(Advance)", + "LayerMask: LoadFlorence2Model": "LayerMask: Load Florence2 Model(Advance)", + "LayerUtility: Florence2Image2Prompt": "LayerUtility: Florence2 Image2Prompt(Advance)" +} diff --git a/py/get_color_tone.py b/py/get_color_tone.py new file mode 100644 index 0000000..52404d5 --- /dev/null +++ b/py/get_color_tone.py @@ -0,0 +1,46 @@ +# layer style advance +import torch +from .imagefunc import log, tensor2pil, gaussian_blur, get_image_color_tone, get_image_color_average, RGB_to_HSV, Hex_to_RGB + +class GetColorTone: + + def __init__(self): + self.NODE_NAME = 'GetColorTone' + + @classmethod + def INPUT_TYPES(self): + mode_list = ['main_color', 'average'] + return { + "required": { + "image": ("IMAGE", ), # + "mode": (mode_list,), # 主色/平均色 + }, + "optional": { + } + } + + RETURN_TYPES = ("STRING", "LIST") + RETURN_NAMES = ("RGB color in HEX", "HSV color in list") + FUNCTION = 'get_color_tone' + CATEGORY = '😺dzNodes/LayerUtility' + + def get_color_tone(self, image, mode,): + if image.shape[0] > 0: + image = torch.unsqueeze(image[0], 0) + _canvas = tensor2pil(image).convert('RGB') + _canvas = gaussian_blur(_canvas, int((_canvas.width + _canvas.height) / 200)) + if mode == 'main_color': + ret_color = get_image_color_tone(_canvas) + else: + ret_color = get_image_color_average(_canvas) + hsv_color = RGB_to_HSV(Hex_to_RGB(ret_color)) + log(f"{self.NODE_NAME}: color is {ret_color}/{hsv_color}", message_type='finish') + return (ret_color, hsv_color) + +NODE_CLASS_MAPPINGS = { + "LayerUtility: GetColorTone": GetColorTone +} + +NODE_DISPLAY_NAME_MAPPINGS = { + "LayerUtility: GetColorTone": "LayerUtility: GetColorTone(Advance)" +} \ No newline at end of file diff --git a/py/get_color_tone_v2.py b/py/get_color_tone_v2.py new file mode 100644 index 0000000..9587687 --- /dev/null +++ b/py/get_color_tone_v2.py @@ -0,0 +1,123 @@ +# layerstyle advance + +import torch +from PIL import Image +from .imagefunc import log, tensor2pil, pil2tensor, image2mask, gaussian_blur, get_image_color_tone, get_image_color_average +from .imagefunc import RGB_to_HSV, Hex_to_RGB, pixel_spread, RMBG, expand_mask + + + +class GetColorToneV2: + + def __init__(self): + self.NODE_NAME = 'GetColorToneV2' + + @classmethod + def INPUT_TYPES(self): + remove_background_list = ['none','BiRefNet', 'RMBG 1.4',] + subject_list = ['mask','entire', 'background', 'subject'] + mode_list = ['main_color', 'average'] + return { + "required": { + "image": ("IMAGE", ), # + "mode": (mode_list,), # 主色/平均色 + "color_of": (subject_list,), + "remove_bkgd_method": (remove_background_list,), + "invert_mask": ("BOOLEAN", {"default": False}), # 反转mask# + "mask_grow": ("INT", {"default": 0, "min": -999, "max": 999, "step": 1}), + }, + "optional": { + "mask": ("MASK",), # + } + } + + RETURN_TYPES = ("IMAGE", "STRING", "LIST", "MASK") + RETURN_NAMES = ("image", "color_in_hex", "HSV color in list", "mask",) + FUNCTION = 'get_color_tone_v2' + CATEGORY = '😺dzNodes/LayerUtility' + + def get_color_tone_v2(self, image, mode, remove_bkgd_method, color_of, invert_mask, mask_grow, + mask=None + ): + + _images = [] + _masks = [] + ret_images = [] + ret_masks = [] + need_rmbg = False + for i in image: + _images.append(torch.unsqueeze(i, 0)) + m = tensor2pil(i) + if m.mode == 'RGBA': + _masks.append(1 - image2mask(m.split()[-1])) + else: + _masks.append(pil2tensor(Image.new("L", (m.width, m.height), color="white"))) + if remove_bkgd_method != 'none': + need_rmbg = True + + if mask is not None: + if mask.dim() == 2: + mask = torch.unsqueeze(mask, 0) + _masks = [] + for m in mask: + _masks.append(torch.unsqueeze(m, 0)) + need_rmbg = False + + max_batch = max(len(_images), len(_masks)) + + if remove_bkgd_method == 'BiRefNet': + from .birefnet_legacy import BiRefNetRemoveBackground + birefnetrmbg = BiRefNetRemoveBackground() + + for i in range(max_batch): + _image = _images[i] if i < len(_images) else _images[-1] + _image = tensor2pil(_image).convert("RGB") + if need_rmbg: + if remove_bkgd_method == 'BiRefNet': + _mask = birefnetrmbg.generate_mask(_image) + else: + _mask = RMBG(_image) + _mask = image2mask(_mask) + else: + _mask = _masks[i] if i < len(_masks) else _masks[-1] + + if invert_mask: + _mask = 1 - _mask + + if mask_grow != 0: + _mask = expand_mask(_mask, mask_grow, 0) # 扩张,模糊 + + if color_of == 'entire': + blured_image = gaussian_blur(_image, int((_image.width + _image.height) / 400)) + else: + if color_of == 'background': + _mask = 1 - _mask + _mask = tensor2pil(_mask) + pixel_spread_image = pixel_spread(_image, _mask.convert('RGB')) + blured_image = gaussian_blur(pixel_spread_image, int((_image.width + _image.height) / 400)) + + ret_color = '#000000' + if mode == 'main_color' and color_of != 'mask': + ret_color = get_image_color_tone(blured_image) + elif mode == 'average' and color_of != 'mask': + ret_color = get_image_color_average(blured_image) + elif mode == 'main_color' and color_of == 'mask': + ret_color = get_image_color_tone(blured_image, mask=_mask) + elif mode == 'average' and color_of == 'mask': + ret_color = get_image_color_average(blured_image, mask=_mask) + + ret_image = Image.new('RGB', size=_image.size, color=ret_color) + ret_images.append(pil2tensor(ret_image)) + ret_masks.append(pil2tensor(_mask)) + hsv_color = RGB_to_HSV(Hex_to_RGB(ret_color)) + log(f"{self.NODE_NAME} Processed {len(ret_images)} image(s). Color is {ret_color}/{hsv_color}", message_type='finish') + + return (torch.cat(ret_images, dim=0), ret_color, hsv_color, torch.cat(ret_masks, dim=0),) + +NODE_CLASS_MAPPINGS = { + "LayerUtility: GetColorToneV2": GetColorToneV2 +} + +NODE_DISPLAY_NAME_MAPPINGS = { + "LayerUtility: GetColorToneV2": "LayerUtility: GetColorTone V2(Advance)" +} \ No newline at end of file diff --git a/py/human_parts_ultra.py b/py/human_parts_ultra.py new file mode 100644 index 0000000..6bc7f0f --- /dev/null +++ b/py/human_parts_ultra.py @@ -0,0 +1,199 @@ +# layerstyle advance + +import os +from typing import Tuple +import torch +import numpy as np +from PIL import Image, ImageEnhance +import folder_paths +from .imagefunc import pil2tensor, tensor2pil, image2mask, mask2image, log, RGB2RGBA, histogram_remap +from .imagefunc import generate_VITMatte_trimap, generate_VITMatte, mask_edge_detail, guided_filter_alpha + +models_dir_path = os.path.join(folder_paths.models_dir, "onnx", "human-parts") +model_url = "https://huggingface.co/Metal3d/deeplabv3p-resnet50-human/resolve/main/deeplabv3p-resnet50-human.onnx" +model_name = os.path.basename(model_url) +model_path = os.path.join(models_dir_path, "deeplabv3p-resnet50-human.onnx") + + +class LS_HumanPartsUltra: + """ + This node is used to get a mask of the human parts in the image. + + The model used is DeepLabV3+ with a ResNet50 backbone trained + by Keras-io, converted to ONNX format. + + """ + + def __init__(self): + self.NODE_NAME = 'HumanPartsUltra' + + RETURN_TYPES = ("IMAGE", "MASK",) + RETURN_NAMES = ("image", "mask",) + FUNCTION = "human_parts_ultra" + CATEGORY = '😺dzNodes/LayerMask' + + @classmethod + def INPUT_TYPES(cls): + method_list = ['VITMatte', 'VITMatte(local)', 'PyMatting', 'GuidedFilter', ] + device_list = ['cuda', 'cpu'] + return { + "required": { + "image": ("IMAGE",), + "face": ("BOOLEAN", {"default": False, "label_on": "enabled(脸)", "label_off": "disabled(脸)"}), + "hair": ("BOOLEAN", {"default": False, "label_on": "enabled(头发)", "label_off": "disabled(头发)"}), + "glasses": ("BOOLEAN", {"default": False, "label_on": "enabled(眼镜)", "label_off": "disabled(眼镜)"}), + "top_clothes": ("BOOLEAN", {"default": False, "label_on": "enabled(上装)", "label_off": "disabled(上装)"}), + "bottom_clothes": ("BOOLEAN", {"default": False, "label_on": "enabled(下装)", "label_off": "disabled(下装)"}), + "torso_skin": ("BOOLEAN", {"default": False, "label_on": "enabled(躯干)", "label_off": "disabled(躯干)"}), + "left_arm": ("BOOLEAN", {"default": False, "label_on": "enabled(左臂)", "label_off": "disabled(左臂)"}), + "right_arm": ("BOOLEAN", {"default": False, "label_on": "enabled(右臂)", "label_off": "disabled(右臂)"}), + "left_leg": ("BOOLEAN", {"default": False, "label_on": "enabled(左腿)", "label_off": "disabled(左腿)"}), + "right_leg": ("BOOLEAN", {"default": False, "label_on": "enabled(右腿)", "label_off": "disabled(右腿)"}), + "left_foot": ("BOOLEAN", {"default": False, "label_on": "enabled(左脚)", "label_off": "disabled(左脚)"}), + "right_foot": ("BOOLEAN", {"default": False, "label_on": "enabled(右脚)", "label_off": "disabled(右脚)"}), + "detail_method": (method_list,), + "detail_erode": ("INT", {"default": 8, "min": 1, "max": 255, "step": 1}), + "detail_dilate": ("INT", {"default": 6, "min": 1, "max": 255, "step": 1}), + "black_point": ( + "FLOAT", {"default": 0.01, "min": 0.01, "max": 0.98, "step": 0.01, "display": "slider"}), + "white_point": ( + "FLOAT", {"default": 0.99, "min": 0.02, "max": 0.99, "step": 0.01, "display": "slider"}), + "process_detail": ("BOOLEAN", {"default": True}), + "device": (device_list,), + "max_megapixels": ("FLOAT", {"default": 2.0, "min": 1, "max": 999, "step": 0.1}), + } + } + + def human_parts_ultra(self, image, face, hair, glasses, top_clothes, bottom_clothes, + torso_skin, left_arm, right_arm, left_leg, right_leg, left_foot, right_foot, + detail_method, detail_erode, detail_dilate, black_point, white_point, + process_detail, device, max_megapixels): + """ + Return a Tensor with the mask of the human parts in the image. + """ + import onnxruntime as ort + + model = ort.InferenceSession(model_path, providers=['TensorrtExecutionProvider', 'CUDAExecutionProvider', 'CPUExecutionProvider']) + ret_images = [] + ret_masks = [] + for img in image: + orig_image = tensor2pil(img).convert('RGB') + + human_parts_mask, _ = self.get_mask(orig_image, model=model, rotation=0, background=False, + face=face, hair=hair, glasses=glasses, + top_clothes=top_clothes, bottom_clothes=bottom_clothes, + torso_skin=torso_skin, left_arm=left_arm, right_arm=right_arm, + left_leg=left_leg, right_leg=right_leg, + left_foot=right_foot, right_foot=right_foot) + _mask = tensor2pil(human_parts_mask).convert('L') + brightness_image = ImageEnhance.Brightness(_mask) + _mask = brightness_image.enhance(factor=1.08) + _mask = image2mask(_mask) + + if detail_method == 'VITMatte(local)': + local_files_only = True + else: + local_files_only = False + detail_range = detail_erode + detail_dilate + if process_detail: + if detail_method == 'GuidedFilter': + _mask = guided_filter_alpha(img.unsqueeze(0), _mask, detail_range // 6 + 1) + _mask = tensor2pil(histogram_remap(_mask, black_point, white_point)) + elif detail_method == 'PyMatting': + _mask = tensor2pil(mask_edge_detail(img.unsqueeze(0), _mask, detail_range // 8 + 1, black_point, white_point)) + else: + _trimap = generate_VITMatte_trimap(_mask, detail_erode, detail_dilate) + _mask = generate_VITMatte(orig_image, _trimap, local_files_only=local_files_only, device=device, + max_megapixels=max_megapixels) + _mask = tensor2pil(histogram_remap(pil2tensor(_mask), black_point, white_point)) + else: + _mask = mask2image(_mask) + + ret_image = RGB2RGBA(orig_image, _mask.convert('L')) + ret_images.append(pil2tensor(ret_image)) + ret_masks.append(image2mask(_mask)) + + log(f"{self.NODE_NAME} Processed {len(ret_images)} image(s).", message_type='finish') + return (torch.cat(ret_images, dim=0), torch.cat(ret_masks, dim=0),) + + def get_mask(self, pil_image:Image, model, rotation:float, **kwargs) -> tuple: + """ + Return a Tensor with the mask of the human parts in the image. + + The rotation parameter is not used for now. The idea is to propose rotation to help + the model to detect the human parts in the image if the character is not in a casual position. + Several tests have been done, but the model seems to fail to detect the human parts in these cases, + and the rotation does not help. + """ + + # classes used in the model + classes = { + "background": 0, + "hair": 2, + "glasses": 4, + "top_clothes": 5, + "bottom_clothes": 9, + "torso_skin": 10, + "face": 13, + "left_arm": 14, + "right_arm": 15, + "left_leg": 16, + "right_leg": 17, + "left_foot": 18, + "right_foot": 19, + } + + original_size = pil_image.size # to resize the mask later + # resize to 512x512 as the model expects + pil_image = pil_image.resize((512, 512)) + center = (256, 256) + + if rotation != 0: + pil_image = pil_image.rotate(rotation, center=center) + + # normalize the image + image_np = np.array(pil_image).astype(np.float32) / 127.5 - 1 + image_np = np.expand_dims(image_np, axis=0) + + # use the onnx model to get the mask + input_name = model.get_inputs()[0].name + output_name = model.get_outputs()[0].name + result = model.run([output_name], {input_name: image_np}) + result = np.array(result[0]).argmax(axis=3).squeeze(0) + + score: int = 0 + + mask = np.zeros_like(result) + for class_name, enabled in kwargs.items(): + if enabled and class_name in classes: + class_index = classes[class_name] + detected = result == class_index + mask[detected] = 255 + score += mask.sum() + + # back to the original size + mask_image = Image.fromarray(mask.astype(np.uint8), mode="L") + if rotation != 0: + mask_image = mask_image.rotate(-rotation, center=center) + + mask_image = mask_image.resize(original_size) + + # and back to numpy... + mask = np.array(mask_image).astype(np.float32) / 255 + + # add 2 dimensions to match the expected output + mask = np.expand_dims(mask, axis=0) + mask = np.expand_dims(mask, axis=0) + # ensure to return a "binary mask_image" + + del image_np, result # free up memory, maybe not necessary + return (torch.from_numpy(mask.astype(np.uint8)), score) + + +NODE_CLASS_MAPPINGS = { + "LayerMask: HumanPartsUltra": LS_HumanPartsUltra +} + +NODE_DISPLAY_NAME_MAPPINGS = { + "LayerMask: HumanPartsUltra": "LayerMask: Human Parts Ultra(Advance)" +} diff --git a/py/image_auto_crop.py b/py/image_auto_crop.py new file mode 100644 index 0000000..8095319 --- /dev/null +++ b/py/image_auto_crop.py @@ -0,0 +1,165 @@ +# layerstyle advance + +from .imagefunc import * +from .segment_anything_func import * + + + +class ImageAutoCrop: + + def __init__(self): + self.NODE_NAME = 'ImageAutoCrop' + + @classmethod + def INPUT_TYPES(self): + matting_method_list = ['RMBG 1.4', 'SegmentAnything'] + detect_mode = ['min_bounding_rect', 'max_inscribed_rect', 'mask_area'] + ratio_list = ['1:1', '3:2', '4:3', '16:9', '2:3', '3:4', '9:16', 'custom', 'detect_mask'] + return { + "required": { + "image": ("IMAGE", ), # + "background_color": ("STRING", {"default": "#FFFFFF"}), # 背景颜色 + "aspect_ratio": (ratio_list,), + "proportional_width": ("INT", {"default": 2, "min": 1, "max": 999, "step": 1}), + "proportional_height": ("INT", {"default": 1, "min": 1, "max": 999, "step": 1}), + "scale_to_longest_side": ("BOOLEAN", {"default": True}), # 是否按长边缩放 + "longest_side": ("INT", {"default": 1024, "min": 4, "max": 999999, "step": 1}), + "detect": (detect_mode,), + "border_reserve": ("INT", {"default": 100, "min": -9999, "max": 9999, "step": 1}), + "ultra_detail_range": ("INT", {"default": 0, "min": 0, "max": 256, "step": 1}), + "matting_method": (matting_method_list,), + "sam_model": (list_sam_model(),), + "grounding_dino_model": (list_groundingdino_model(),), + "sam_threshold": ("FLOAT", {"default": 0.3, "min": 0, "max": 1.0, "step": 0.01}), + "sam_prompt": ("STRING", {"default": "subject"}), + }, + "optional": { + } + } + + RETURN_TYPES = ("IMAGE", "IMAGE", "MASK",) + RETURN_NAMES = ("cropped_image", "box_preview", "cropped_mask",) + FUNCTION = 'image_auto_crop' + CATEGORY = '😺dzNodes/LayerUtility' + + def image_auto_crop(self, image, detect, border_reserve, aspect_ratio, proportional_width, proportional_height, + background_color, ultra_detail_range, scale_to_longest_side, longest_side, + matting_method, sam_model, grounding_dino_model, sam_threshold, sam_prompt + ): + + ret_images = [] + ret_box_previews = [] + ret_masks = [] + input_images = [] + input_masks = [] + crop_boxs = [] + + for l in image: + input_images.append(torch.unsqueeze(l, 0)) + m = tensor2pil(l) + if m.mode == 'RGBA': + input_masks.append(m.split()[-1]) + + if len(input_masks) > 0 and len(input_masks) != len(input_images): + input_masks = [] + log(f"Warning, {self.NODE_NAME} unable align alpha to image, drop it.", message_type='warning') + + if aspect_ratio == 'custom': + ratio = proportional_width / proportional_height + elif aspect_ratio == 'detect_mask': + ratio = 0 + else: + s = aspect_ratio.split(":") + ratio = int(s[0]) / int(s[1]) + side_limit = longest_side if scale_to_longest_side else 0 + + for i in range(len(input_images)): + _image = tensor2pil(input_images[i]).convert('RGB') + if len(input_masks) > 0: + _mask = input_masks[i] + else: + if matting_method == 'SegmentAnything': + sam_model = load_sam_model(sam_model) + dino_model = load_groundingdino_model(grounding_dino_model) + item = _image.convert('RGBA') + boxes = groundingdino_predict(dino_model, item, sam_prompt, sam_threshold) + (_, _mask) = sam_segment(sam_model, item, boxes) + _mask = mask2image(_mask[0]) + else: + _mask = RMBG(_image) + if ultra_detail_range: + _mask = tensor2pil(mask_edge_detail(input_images[i], pil2tensor(_mask), ultra_detail_range, 0.01, 0.99)) + bluredmask = gaussian_blur(_mask, 20).convert('L') + x = 0 + y = 0 + width = 0 + height = 0 + x_offset = 0 + y_offset = 0 + if detect == "min_bounding_rect": + (x, y, width, height) = min_bounding_rect(bluredmask) + elif detect == "max_inscribed_rect": + (x, y, width, height) = max_inscribed_rect(bluredmask) + else: + (x, y, width, height) = mask_area(bluredmask) + canvas_width, canvas_height = _image.size + x1 = x - border_reserve + y1 = y - border_reserve + x2 = x + width + border_reserve + y2 = y + height + border_reserve + if x1 < 0: + canvas_width -= x1 + x_offset = -x1 + if y1 < 0: + canvas_height -= y1 + y_offset = -y1 + if x2 > _image.width: + canvas_width += x2 - _image.width + if y2 > _image.height: + canvas_height += y2 - _image.height + crop_box = (x1 + x_offset, y1 + y_offset, width + border_reserve*2, height + border_reserve*2) + crop_boxs.append(crop_box) + if len(crop_boxs) > 0: # 批量图强制使用同一尺寸 + crop_box = crop_boxs[0] + if aspect_ratio == 'detect_mask': + ratio = crop_box[2] / crop_box[3] + target_width, target_height = calculate_side_by_ratio(crop_box[2], crop_box[3], ratio, + longest_side=side_limit) + _canvas = Image.new('RGB', size=(canvas_width, canvas_height), color=background_color) + _mask_canvas = Image.new('L', size=(canvas_width, canvas_height), color='black') + if ultra_detail_range: + _image = pixel_spread(_image, _mask) + _canvas.paste(_image, box=(x_offset, y_offset), mask=_mask.convert('L')) + _mask_canvas.paste(_mask, box=(x_offset, y_offset)) + preview_image = Image.new('RGB', size=(canvas_width, canvas_height), color='gray') + preview_image.paste(_mask, box=(x_offset, y_offset)) + preview_image = draw_rect(preview_image, + crop_box[0], crop_box[1], crop_box[2], crop_box[3], + line_color="#F00000", line_width=(canvas_width + canvas_height)//200) + + ret_image = _canvas.crop((crop_box[0], crop_box[1], crop_box[0]+crop_box[2], crop_box[1]+crop_box[3])) + ret_image = fit_resize_image(ret_image, target_width, target_height, + fit='letterbox', resize_sampler=Image.LANCZOS, + background_color=background_color) + ret_mask = _mask_canvas.crop((crop_box[0], crop_box[1], crop_box[0]+crop_box[2], crop_box[1]+crop_box[3])) + ret_mask = fit_resize_image(ret_mask, target_width, target_height, + fit='letterbox', resize_sampler=Image.LANCZOS, + background_color="#000000") + ret_images.append(pil2tensor(ret_image)) + ret_box_previews.append(pil2tensor(preview_image)) + ret_masks.append(image2mask(ret_mask)) + + log(f"{self.NODE_NAME} Processed {len(ret_images)} image(s).", message_type='finish') + return (torch.cat(ret_images, dim=0), + torch.cat(ret_box_previews, dim=0), + torch.cat(ret_masks, dim=0), + ) + + +NODE_CLASS_MAPPINGS = { + "LayerUtility: ImageAutoCrop": ImageAutoCrop +} + +NODE_DISPLAY_NAME_MAPPINGS = { + "LayerUtility: ImageAutoCrop": "LayerUtility: ImageAutoCrop(Advance)" +} \ No newline at end of file diff --git a/py/image_auto_crop_v2.py b/py/image_auto_crop_v2.py new file mode 100644 index 0000000..c0605a6 --- /dev/null +++ b/py/image_auto_crop_v2.py @@ -0,0 +1,253 @@ +# layerstyle advance + +from .imagefunc import * +from .segment_anything_func import * + + +SAM_MODEL = None +DINO_MODEL = None +previous_sam_model = "" +previous_dino_model = "" + +class ImageAutoCropV2: + + def __init__(self): + self.NODE_NAME = 'ImageAutoCropV2' + + @classmethod + def INPUT_TYPES(self): + matting_method_list = ['RMBG 1.4', 'SegmentAnything'] + detect_mode = ['min_bounding_rect', 'max_inscribed_rect', 'mask_area'] + ratio_list = ['1:1', '3:2', '4:3', '16:9', '2:3', '3:4', '9:16', 'custom', 'detect_mask', 'original'] + scale_to_side_list = ['None', 'longest', 'shortest', 'width', 'height'] + return { + "required": { + "image": ("IMAGE", ), # + "fill_background": ("BOOLEAN", {"default": True}), # 是否填充背景 + "background_color": ("STRING", {"default": "#FFFFFF"}), # 背景颜色 + "aspect_ratio": (ratio_list,), + "proportional_width": ("INT", {"default": 1, "min": 1, "max": 999, "step": 1}), + "proportional_height": ("INT", {"default": 1, "min": 1, "max": 999, "step": 1}), + "scale_to_side": (scale_to_side_list,), # 是否按长边缩放 + "scale_to_length": ("INT", {"default": 1024, "min": 4, "max": 999999, "step": 1}), + "detect": (detect_mode,), + "border_reserve": ("INT", {"default": 100, "min": -9999, "max": 9999, "step": 1}), + "ultra_detail_range": ("INT", {"default": 0, "min": 0, "max": 256, "step": 1}), + "matting_method": (matting_method_list,), + "sam_model": (list_sam_model(),), + "grounding_dino_model": (list_groundingdino_model(),), + "sam_threshold": ("FLOAT", {"default": 0.3, "min": 0, "max": 1.0, "step": 0.01}), + "sam_prompt": ("STRING", {"default": "subject"}), + }, + "optional": { + "mask": ("MASK",), # + } + } + + RETURN_TYPES = ("IMAGE", "IMAGE", "MASK",) + RETURN_NAMES = ("cropped_image", "box_preview", "cropped_mask",) + FUNCTION = 'image_auto_crop_v2' + CATEGORY = '😺dzNodes/LayerUtility' + + def image_auto_crop_v2(self, image, fill_background, background_color, aspect_ratio, + proportional_width, proportional_height, + scale_to_side, scale_to_length, detect, border_reserve, + ultra_detail_range, matting_method, + sam_model, grounding_dino_model, sam_threshold, sam_prompt, + mask=None, + ): + + ret_images = [] + ret_box_previews = [] + ret_masks = [] + input_images = [] + input_masks = [] + crop_boxs = [] + + global SAM_MODEL + global DINO_MODEL + global previous_sam_model + global previous_dino_model + + for l in image: + input_images.append(torch.unsqueeze(l, 0)) + m = tensor2pil(l) + if m.mode == 'RGBA': + input_masks.append(m.split()[-1]) + if mask is not None: + if mask.dim() == 2: + mask = torch.unsqueeze(mask, 0) + input_masks = [] + for m in mask: + input_masks.append(tensor2pil(torch.unsqueeze(m, 0)).convert('L')) + + if len(input_masks) > 0 and len(input_masks) != len(input_images): + input_masks = [] + log(f"Warning, {self.NODE_NAME} unable align alpha to image, drop it.", message_type='warning') + + fit = 'letterbox' + if aspect_ratio == 'custom': + ratio = proportional_width / proportional_height + elif aspect_ratio == 'original': + _image = tensor2pil(input_images[0]) + ratio = _image.width / _image.height + elif aspect_ratio == 'detect_mask': + ratio = 0 + fit = 'fill' + else: + s = aspect_ratio.split(":") + ratio = int(s[0]) / int(s[1]) + + for i in range(len(input_images)): + _image = tensor2pil(input_images[i]).convert('RGB') + + if len(input_masks) > 0: + _mask = input_masks[i] + else: + if matting_method == 'SegmentAnything': + if previous_sam_model != sam_model: + SAM_MODEL = load_sam_model(sam_model) + previous_sam_model = sam_model + if previous_dino_model != grounding_dino_model: + DINO_MODEL = load_groundingdino_model(grounding_dino_model) + previous_dino_model = grounding_dino_model + item = _image.convert('RGBA') + boxes = groundingdino_predict(DINO_MODEL, item, sam_prompt, sam_threshold) + (_, _mask) = sam_segment(SAM_MODEL, item, boxes) + _mask = mask2image(_mask[0]) + else: + _mask = RMBG(_image) + if ultra_detail_range: + _mask = tensor2pil(mask_edge_detail(input_images[i], pil2tensor(_mask), ultra_detail_range, 0.01, 0.99)) + bluredmask = gaussian_blur(_mask, 20).convert('L') + x = 0 + y = 0 + width = 0 + height = 0 + x_offset = 0 + y_offset = 0 + if detect == "min_bounding_rect": + (x, y, width, height) = min_bounding_rect(bluredmask) + elif detect == "max_inscribed_rect": + (x, y, width, height) = max_inscribed_rect(bluredmask) + else: + (x, y, width, height) = mask_area(bluredmask) + + canvas_width, canvas_height = _image.size + + x1 = x - border_reserve + y1 = y - border_reserve + x2 = x + width + border_reserve + y2 = y + height + border_reserve + + if x1 < 0: + if fill_background: + canvas_width -= x1 + x_offset = -x1 + else: + x1 = 0 + if y1 < 0: + if fill_background: + canvas_height -= y1 + y_offset = -y1 + else: + y1 = 0 + if x2 > _image.width: + if fill_background: + canvas_width += x2 - _image.width + else: + x2 = _image.width + if y2 > _image.height: + if fill_background: + canvas_height += y2 - _image.height + else: + y2 = _image.height + + if fill_background: + crop_box = (x1 + x_offset, y1 + y_offset, width + border_reserve*2, height + border_reserve*2) + else: + crop_box = (x1, y1, x2 - x1, y2 - y1) + crop_boxs.append(crop_box) + if len(crop_boxs) > 0: # 批量图强制使用同一尺寸 + crop_box = crop_boxs[0] + + orig_width = crop_box[2] + orig_height = crop_box[3] + if aspect_ratio == 'detect_mask': + ratio = orig_width / orig_height + + # calculate target width and height + if orig_width > orig_height: + if scale_to_side == 'longest': + target_width = scale_to_length + target_height = int(target_width / ratio) + elif scale_to_side == 'shortest': + target_height = scale_to_length + target_width = int(target_height * ratio) + elif scale_to_side == 'width': + target_width = scale_to_length + target_height = int(target_width / ratio) + elif scale_to_side == 'height': + target_height = scale_to_length + target_width = int(target_height * ratio) + else: + target_width = orig_width + target_height = int(target_width / ratio) + else: + if scale_to_side == 'longest': + target_height = scale_to_length + target_width = int(target_height * ratio) + elif scale_to_side == 'shortest': + target_width = scale_to_length + target_height = int(target_width / ratio) + elif scale_to_side == 'width': + target_width = scale_to_length + target_height = int(target_width / ratio) + elif scale_to_side == 'height': + target_height = scale_to_length + target_width = int(target_height * ratio) + else: + target_height = orig_height + target_width = int(target_height * ratio) + + _canvas = Image.new('RGB', size=(canvas_width, canvas_height), color=background_color) + _mask_canvas = Image.new('L', size=(canvas_width, canvas_height), color='black') + if ultra_detail_range: + _image = pixel_spread(_image, _mask) + if fill_background: + _canvas.paste(_image, box=(x_offset, y_offset), mask=_mask.convert('L')) + else: + _canvas.paste(_image, box=(x_offset, y_offset)) + _mask_canvas.paste(_mask, box=(x_offset, y_offset)) + preview_image = Image.new('RGB', size=(canvas_width, canvas_height), color='gray') + preview_image.paste(_mask, box=(x_offset, y_offset)) + preview_image = draw_rect(preview_image, + crop_box[0], crop_box[1], crop_box[2], crop_box[3], + line_color="#F00000", line_width=(canvas_width + canvas_height)//200) + + ret_image = _canvas.crop((crop_box[0], crop_box[1], crop_box[0]+crop_box[2], crop_box[1]+crop_box[3])) + ret_image = fit_resize_image(ret_image, target_width, target_height, + fit=fit, resize_sampler=Image.LANCZOS, + background_color=background_color) + ret_mask = _mask_canvas.crop((crop_box[0], crop_box[1], crop_box[0]+crop_box[2], crop_box[1]+crop_box[3])) + ret_mask = fit_resize_image(ret_mask, target_width, target_height, + fit=fit, resize_sampler=Image.LANCZOS, + background_color="#000000") + ret_images.append(pil2tensor(ret_image)) + ret_box_previews.append(pil2tensor(preview_image)) + ret_masks.append(image2mask(ret_mask)) + + log(f"{self.NODE_NAME} Processed {len(ret_images)} image(s).", message_type='finish') + return (torch.cat(ret_images, dim=0), + torch.cat(ret_box_previews, dim=0), + torch.cat(ret_masks, dim=0), + ) + + +NODE_CLASS_MAPPINGS = { + "LayerUtility: ImageAutoCrop V2": ImageAutoCropV2 +} + +NODE_DISPLAY_NAME_MAPPINGS = { + "LayerUtility: ImageAutoCrop V2": "LayerUtility: ImageAutoCrop V2(Advance)" +} \ No newline at end of file diff --git a/py/image_auto_crop_v3.py b/py/image_auto_crop_v3.py new file mode 100644 index 0000000..511737b --- /dev/null +++ b/py/image_auto_crop_v3.py @@ -0,0 +1,193 @@ +# layerstyle advance + +import torch +import numpy as np +import math +from PIL import Image +from .imagefunc import log, tensor2pil, pil2tensor, num_round_up_to_multiple, draw_rect, gaussian_blur, mask_area + + + +class ImageAutoCropV3: + + def __init__(self): + self.NODE_NAME = 'ImageAutoCropV3' + + @classmethod + def INPUT_TYPES(self): + ratio_list = ['1:1', '3:2', '4:3', '16:9', '2:3', '3:4', '9:16', 'custom', 'original'] + scale_to_side_list = ['None', 'longest', 'shortest', 'width', 'height', 'total_pixel(kilo pixel)'] + multiple_list = ['8', '16', '32', '64', '128', '256', '512', 'None'] + method_mode = ['lanczos', 'bicubic', 'hamming', 'bilinear', 'box', 'nearest'] + return { + "required": { + "image": ("IMAGE", ), + "aspect_ratio": (ratio_list,), + "proportional_width": ("INT", {"default": 1, "min": 1, "max": 99999999, "step": 1}), + "proportional_height": ("INT", {"default": 1, "min": 1, "max": 99999999, "step": 1}), + "method": (method_mode,), + "scale_to_side": (scale_to_side_list,), + "scale_to_length": ("INT", {"default": 1024, "min": 4, "max": 999999, "step": 1}), + "round_to_multiple": (multiple_list,), + }, + "optional": { + "mask": ("MASK",), + } + } + + RETURN_TYPES = ("IMAGE", "IMAGE",) + RETURN_NAMES = ("cropped_image", "box_preview",) + FUNCTION = 'image_auto_crop_v3' + CATEGORY = '😺dzNodes/LayerUtility' + + def image_auto_crop_v3(self, image, aspect_ratio, + proportional_width, proportional_height, method, + scale_to_side, scale_to_length, round_to_multiple, + mask=None, + ): + + ret_images = [] + ret_box_previews = [] + ret_masks = [] + input_images = [] + input_masks = [] + crop_boxs = [] + + for l in image: + input_images.append(torch.unsqueeze(l, 0)) + m = tensor2pil(l) + if m.mode == 'RGBA': + input_masks.append(m.split()[-1]) + if mask is not None: + if mask.dim() == 2: + mask = torch.unsqueeze(mask, 0) + input_masks = [] + for m in mask: + input_masks.append(tensor2pil(torch.unsqueeze(m, 0)).convert('L')) + + if len(input_masks) > 0 and len(input_masks) != len(input_images): + input_masks = [] + log(f"Warning, {self.NODE_NAME} unable align alpha to image, drop it.", message_type='warning') + + fit = 'crop' + _image = tensor2pil(input_images[0]) + (orig_width, orig_height) = _image.size + if aspect_ratio == 'custom': + ratio = proportional_width / proportional_height + elif aspect_ratio == 'original': + ratio = orig_width / orig_height + else: + s = aspect_ratio.split(":") + ratio = int(s[0]) / int(s[1]) + + resize_sampler = Image.LANCZOS + if method == "bicubic": + resize_sampler = Image.BICUBIC + elif method == "hamming": + resize_sampler = Image.HAMMING + elif method == "bilinear": + resize_sampler = Image.BILINEAR + elif method == "box": + resize_sampler = Image.BOX + elif method == "nearest": + resize_sampler = Image.NEAREST + + # calculate target width and height + if ratio > 1: + if scale_to_side == 'longest': + target_width = scale_to_length + target_height = int(target_width / ratio) + elif scale_to_side == 'shortest': + target_height = scale_to_length + target_width = int(target_height * ratio) + elif scale_to_side == 'width': + target_width = scale_to_length + target_height = int(target_width / ratio) + elif scale_to_side == 'height': + target_height = scale_to_length + target_width = int(target_height * ratio) + elif scale_to_side == 'total_pixel(kilo pixel)': + target_width = math.sqrt(ratio * scale_to_length * 1000) + target_height = target_width / ratio + target_width = int(target_width) + target_height = int(target_height) + else: + target_width = orig_width + target_height = int(target_width / ratio) + else: + if scale_to_side == 'longest': + target_height = scale_to_length + target_width = int(target_height * ratio) + elif scale_to_side == 'shortest': + target_width = scale_to_length + target_height = int(target_width / ratio) + elif scale_to_side == 'width': + target_width = scale_to_length + target_height = int(target_width / ratio) + elif scale_to_side == 'height': + target_height = scale_to_length + target_width = int(target_height * ratio) + elif scale_to_side == 'total_pixel(kilo pixel)': + target_width = math.sqrt(ratio * scale_to_length * 1000) + target_height = target_width / ratio + target_width = int(target_width) + target_height = int(target_height) + else: + target_height = orig_height + target_width = int(target_height * ratio) + + if round_to_multiple != 'None': + multiple = int(round_to_multiple) + target_width = num_round_up_to_multiple(target_width, multiple) + target_height = num_round_up_to_multiple(target_height, multiple) + + for i in range(len(input_images)): + _image = tensor2pil(input_images[i]).convert('RGB') + + if len(input_masks) > 0: + _mask = input_masks[i] + else: + _mask = Image.new('L', _image.size, color='black') + + bluredmask = gaussian_blur(_mask, 20).convert('L') + (mask_x, mask_y, mask_w, mask_h) = mask_area(bluredmask) + orig_ratio = _image.width / _image.height + target_ratio = target_width / target_height + # crop image to target ratio + if orig_ratio > target_ratio: # crop LiftRight side + crop_w = int(_image.height * target_ratio) + crop_h = _image.height + else: # crop TopBottom side + crop_w = _image.width + crop_h = int(_image.width / target_ratio) + crop_x = mask_w // 2 + mask_x - crop_w // 2 + if crop_x < 0: + crop_x = 0 + if crop_x + crop_w > _image.width: + crop_x = _image.width - crop_w + crop_y = mask_h // 2 + mask_y - crop_h // 2 + if crop_y < 0: + crop_y = 0 + if crop_y + crop_h > _image.height: + crop_y = _image.height - crop_h + crop_image = _image.crop((crop_x, crop_y, crop_x + crop_w, crop_y + crop_h)) + line_width = (_image.width + _image.height) // 200 + preview_image = draw_rect(_image, crop_x, crop_y, + crop_w, crop_h, + line_color="#F00000", line_width=line_width) + ret_image = crop_image.resize((target_width, target_height), resize_sampler) + ret_images.append(pil2tensor(ret_image)) + ret_box_previews.append(pil2tensor(preview_image)) + + log(f"{self.NODE_NAME} Processed {len(ret_images)} image(s).", message_type='finish') + return (torch.cat(ret_images, dim=0), + torch.cat(ret_box_previews, dim=0), + ) + +NODE_CLASS_MAPPINGS = { + "LayerUtility: ImageAutoCrop V3": ImageAutoCropV3 +} + +NODE_DISPLAY_NAME_MAPPINGS = { + "LayerUtility: ImageAutoCrop V3": "LayerUtility: ImageAutoCrop V3(Advance)" +} \ No newline at end of file diff --git a/py/image_reward_filter.py b/py/image_reward_filter.py new file mode 100644 index 0000000..dbf1daa --- /dev/null +++ b/py/image_reward_filter.py @@ -0,0 +1,77 @@ +# layerstyle advance + +from .imagefunc import * + + +class ImageRewardFilter: + + def __init__(self): + self.NODE_NAME = 'ImageRewardFilter' + + @classmethod + def INPUT_TYPES(self): + return { + "required": { + "images": ("IMAGE", ), + "prompt": ("STRING", {"multiline": False}), + "output_num": ("INT", {"default": 3, "min": 1, "max": 999999, "step": 1}), + }, + "optional": { + } + } + + RETURN_TYPES = ("IMAGE", "IMAGE",) + RETURN_NAMES = ("images", 'obsolete_images',) + FUNCTION = 'image_reward_filter' + CATEGORY = '😺dzNodes/LayerUtility' + + def image_reward_filter(self, images, prompt, output_num,): + log(f"len(images)= {len(images)}, output_num={output_num}") + if output_num > len(images): + log(f"Error: {self.NODE_NAME} skipped, because 'output_num' is greater then input images.", message_type='error') + return (images,) + + scores = [] + ret_images = [] + obsolete_images = [] + + if not torch.cuda.is_available() : + device = "cpu" + else: + device = "cuda" + + import ImageReward as RM + reward_model = RM.load("ImageReward-v1.0") + reward_model = reward_model.to(device=device) + + with torch.no_grad(): + for i in range(len(images)): + score = reward_model.score(prompt, tensor2pil(images[i])) + scores.append( + { + "score":score, + "image_index":i + } + ) + scores = sorted(scores, key=lambda s: s['score'], reverse=True) + + for i in range(len(images)): + if i < output_num: + log(f"{self.NODE_NAME} append image #{i}: {scores[i]['image_index']}, score = {scores[i]['score']}.") + ret_images.append(images[scores[i]['image_index']]) + else: + log(f"{self.NODE_NAME} obsolete image #{i}: {scores[i]['image_index']}, score = {scores[i]['score']}.") + obsolete_images.append(images[scores[i]['image_index']]) + + log(f"{self.NODE_NAME} Processed {len(ret_images)} image(s).", message_type='finish') + + return (ret_images, obsolete_images,) + + +NODE_CLASS_MAPPINGS = { + "LayerUtility: ImageRewardFilter": ImageRewardFilter +} + +NODE_DISPLAY_NAME_MAPPINGS = { + "LayerUtility: ImageRewardFilter": "LayerUtility: ImageRewardFilter(Obsolete)" +} \ No newline at end of file diff --git a/py/imagefunc.py b/py/imagefunc.py new file mode 100644 index 0000000..a20748f --- /dev/null +++ b/py/imagefunc.py @@ -0,0 +1,2485 @@ +"""Image process functions for ComfyUI nodes +by chflame https://github.com/chflame163 + +@author: chflame +@title: LayerStyle +@nickname: LayerStyle +@description: A set of nodes for ComfyUI that can composite layer and mask to achieve Photoshop like functionality. +""" + +import os +import sys +sys.path.append(os.path.dirname(os.path.abspath(__file__))) +import pickle +import copy +import re +import json +import math +import glob +import numpy as np +import torch +import scipy.ndimage +import cv2 +import random +import time +from pathlib import Path +from tqdm import tqdm +from functools import lru_cache +from typing import Union, List +from PIL import Image, ImageFilter, ImageChops, ImageDraw, ImageOps, ImageEnhance, ImageFont +from skimage import img_as_float, img_as_ubyte +import torchvision.transforms.functional as TF +import torch.nn.functional as F +from transformers import AutoModel, AutoProcessor, StoppingCriteria, StoppingCriteriaList, AutoModelForCausalLM, AutoTokenizer +from colorsys import rgb_to_hsv +import folder_paths +import comfy.model_management +from .blendmodes import * + +def log(message:str, message_type:str='info'): + name = 'LayerStyle' + + if message_type == 'error': + message = '\033[1;41m' + message + '\033[m' + elif message_type == 'warning': + message = '\033[1;31m' + message + '\033[m' + elif message_type == 'finish': + message = '\033[1;32m' + message + '\033[m' + else: + message = '\033[1;33m' + message + '\033[m' + print(f"# 😺dzNodes: {name} -> {message}") + +try: + from cv2.ximgproc import guidedFilter +except ImportError as e: + # print(e) + log(f"Cannot import name 'guidedFilter' from 'cv2.ximgproc'" + f"\nA few nodes cannot works properly, while most nodes are not affected. Please REINSTALL package 'opencv-contrib-python'." + f"\nFor detail refer to \033[4mhttps://github.com/chflame163/ComfyUI_LayerStyle/issues/5\033[0m") + + + +'''warpper''' + +# create a wrapper function that can apply a function to multiple images in a batch while passing all other arguments to the function +def apply_to_batch(func): + def wrapper(self, image, *args, **kwargs): + images = [] + for img in image: + images.append(func(self, img, *args, **kwargs)) + batch_tensor = torch.cat(images, dim=0) + return (batch_tensor,) + return wrapper + + +'''pickle''' + + +def read_image(filename:str) -> Image: + return Image.open(filename) + +def pickle_to_file(obj:object, file_path:str): + with open(file_path, 'wb') as f: + pickle.dump(obj, f) + +def load_pickle(file_name:str) -> object: + with open(file_name, 'rb') as f: + obj = pickle.load(f) + return obj + +def load_light_leak_images() -> list: + file = os.path.join(folder_paths.models_dir, "layerstyle", "light_leak.pkl") + return load_pickle(file) + +'''Converter''' + +def cv22ski(cv2_image:np.ndarray) -> np.array: + return img_as_float(cv2_image) + +def ski2cv2(ski:np.array) -> np.ndarray: + return img_as_ubyte(ski) + +def cv22pil(cv2_img:np.ndarray) -> Image: + cv2_img = cv2.cvtColor(cv2_img, cv2.COLOR_BGR2RGB) + return Image.fromarray(cv2_img) + +def pil2cv2(pil_img:Image) -> np.array: + np_img_array = np.asarray(pil_img) + return cv2.cvtColor(np_img_array, cv2.COLOR_RGB2BGR) + +def pil2tensor(image:Image) -> torch.Tensor: + return torch.from_numpy(np.array(image).astype(np.float32) / 255.0).unsqueeze(0) + +def np2pil(np_image:np.ndarray) -> Image: + return Image.fromarray(np_image) + +def pil2np(pil_image:Image) -> np.array: + return np.ndarray(pil_image) + +def np2tensor(img_np: Union[np.ndarray, List[np.ndarray]]) -> torch.Tensor: + if isinstance(img_np, list): + return torch.cat([np2tensor(img) for img in img_np], dim=0) + return torch.from_numpy(img_np.astype(np.float32) / 255.0).unsqueeze(0) + +def tensor2np(tensor: torch.Tensor) -> List[np.ndarray]: + if len(tensor.shape) == 3: # Single image + return np.clip(255.0 * tensor.cpu().numpy(), 0, 255).astype(np.uint8) + else: # Batch of images + return [np.clip(255.0 * t.cpu().numpy(), 0, 255).astype(np.uint8) for t in tensor] + +def tensor2pil(t_image: torch.Tensor) -> Image: + return Image.fromarray(np.clip(255.0 * t_image.cpu().numpy().squeeze(), 0, 255).astype(np.uint8)) + +def tensor2cv2(image:torch.Tensor) -> np.array: + if image.dim() == 4: + image = image.squeeze() + npimage = image.numpy() + cv2image = np.uint8(npimage * 255 / npimage.max()) + return cv2.cvtColor(cv2image, cv2.COLOR_RGB2BGR) + +def image2mask(image:Image) -> torch.Tensor: + if image.mode == 'L': + return torch.tensor([pil2tensor(image)[0, :, :].tolist()]) + else: + image = image.convert('RGB').split()[0] + return torch.tensor([pil2tensor(image)[0, :, :].tolist()]) + +def mask2image(mask:torch.Tensor) -> Image: + masks = tensor2np(mask) + for m in masks: + _mask = Image.fromarray(m).convert("L") + _image = Image.new("RGBA", _mask.size, color='white') + _image = Image.composite( + _image, Image.new("RGBA", _mask.size, color='black'), _mask) + return _image + +'''Image Functions''' + +# 颜色加深 +def blend_color_burn(background_image:Image, layer_image:Image) -> Image: + img_1 = cv22ski(pil2cv2(background_image)) + img_2 = cv22ski(pil2cv2(layer_image)) + img = 1 - (1 - img_2) / (img_1 + 0.001) + mask_1 = img < 0 + mask_2 = img > 1 + img = img * (1 - mask_1) + img = img * (1 - mask_2) + mask_2 + return cv22pil(ski2cv2(img)) + +# 颜色减淡 +def blend_color_dodge(background_image:Image, layer_image:Image) -> Image: + img_1 = cv22ski(pil2cv2(background_image)) + img_2 = cv22ski(pil2cv2(layer_image)) + img = img_2 / (1.0 - img_1 + 0.001) + mask_2 = img > 1 + img = img * (1 - mask_2) + mask_2 + return cv22pil(ski2cv2(img)) + +# 线性加深 +def blend_linear_burn(background_image:Image, layer_image:Image) -> Image: + img_1 = cv22ski(pil2cv2(background_image)) + img_2 = cv22ski(pil2cv2(layer_image)) + img = img_1 + img_2 - 1 + mask_1 = img < 0 + img = img * (1 - mask_1) + return cv22pil(ski2cv2(img)) + +# 线性减淡 +def blend_linear_dodge(background_image:Image, layer_image:Image) -> Image: + img_1 = cv22ski(pil2cv2(background_image)) + img_2 = cv22ski(pil2cv2(layer_image)) + img = img_1 + img_2 + mask_2 = img > 1 + img = img * (1 - mask_2) + mask_2 + return cv22pil(ski2cv2(img)) + +# 变亮 +def blend_lighten(background_image:Image, layer_image:Image) -> Image: + img_1 = cv22ski(pil2cv2(background_image)) + img_2 = cv22ski(pil2cv2(layer_image)) + img = img_1 - img_2 + mask = img > 0 + img = img_1 * mask + img_2 * (1 - mask) + return cv22pil(ski2cv2(img)) + +# 变暗 +def blend_dark(background_image:Image, layer_image:Image) -> Image: + img_1 = cv22ski(pil2cv2(background_image)) + img_2 = cv22ski(pil2cv2(layer_image)) + img = img_1 - img_2 + mask = img < 0 + img = img_1 * mask + img_2 * (1 - mask) + return cv22pil(ski2cv2(img)) + +# 滤色 +def blend_screen(background_image:Image, layer_image:Image) -> Image: + img_1 = cv22ski(pil2cv2(background_image)) + img_2 = cv22ski(pil2cv2(layer_image)) + img = 1 - (1 - img_1) * (1 - img_2) + return cv22pil(ski2cv2(img)) + +# 叠加 +def blend_overlay(background_image:Image, layer_image:Image) -> Image: + img_1 = cv22ski(pil2cv2(background_image)) + img_2 = cv22ski(pil2cv2(layer_image)) + mask = img_2 < 0.5 + img = 2 * img_1 * img_2 * mask + (1 - mask) * (1 - 2 * (1 - img_1) * (1 - img_2)) + return cv22pil(ski2cv2(img)) + +# 柔光 +def blend_soft_light(background_image:Image, layer_image:Image) -> Image: + img_1 = cv22ski(pil2cv2(background_image)) + img_2 = cv22ski(pil2cv2(layer_image)) + mask = img_1 < 0.5 + T1 = (2 * img_1 - 1) * (img_2 - img_2 * img_2) + img_2 + T2 = (2 * img_1 - 1) * (np.sqrt(img_2) - img_2) + img_2 + img = T1 * mask + T2 * (1 - mask) + return cv22pil(ski2cv2(img)) + +# 强光 +def blend_hard_light(background_image:Image, layer_image:Image) -> Image: + img_1 = cv22ski(pil2cv2(background_image)) + img_2 = cv22ski(pil2cv2(layer_image)) + mask = img_1 < 0.5 + T1 = 2 * img_1 * img_2 + T2 = 1 - 2 * (1 - img_1) * (1 - img_2) + img = T1 * mask + T2 * (1 - mask) + return cv22pil(ski2cv2(img)) + +# 亮光 +def blend_vivid_light(background_image:Image, layer_image:Image) -> Image: + img_1 = cv22ski(pil2cv2(background_image)) + img_2 = cv22ski(pil2cv2(layer_image)) + mask = img_1 < 0.5 + T1 = 1 - (1 - img_2) / (2 * img_1 + 0.001) + T2 = img_2 / (2 * (1 - img_1) + 0.001) + mask_1 = T1 < 0 + mask_2 = T2 > 1 + T1 = T1 * (1 - mask_1) + T2 = T2 * (1 - mask_2) + mask_2 + img = T1 * mask + T2 * (1 - mask) + return cv22pil(ski2cv2(img)) + +# 点光 +def blend_pin_light(background_image:Image, layer_image:Image) -> Image: + img_1 = cv22ski(pil2cv2(background_image)) + img_2 = cv22ski(pil2cv2(layer_image)) + mask_1 = img_2 < (img_1 * 2 - 1) + mask_2 = img_2 > 2 * img_1 + T1 = 2 * img_1 - 1 + T2 = img_2 + T3 = 2 * img_1 + img = T1 * mask_1 + T2 * (1 - mask_1) * (1 - mask_2) + T3 * mask_2 + return cv22pil(ski2cv2(img)) + +# 线性光 +def blend_linear_light(background_image:Image, layer_image:Image) -> Image: + img_1 = cv22ski(pil2cv2(background_image)) + img_2 = cv22ski(pil2cv2(layer_image)) + img = img_2 + img_1 * 2 - 1 + mask_1 = img < 0 + mask_2 = img > 1 + img = img * (1 - mask_1) + img = img * (1 - mask_2) + mask_2 + return cv22pil(ski2cv2(img)) + +def blend_hard_mix(background_image:Image, layer_image:Image) -> Image: + img_1 = cv22ski(pil2cv2(background_image)) + img_2 = cv22ski(pil2cv2(layer_image)) + img = img_1 + img_2 + mask = img_1 + img_2 > 1 + img = img * (1 - mask) + mask + img = img * mask + return cv22pil(ski2cv2(img)) + +def shift_image(image:Image, distance_x:int, distance_y:int, background_color:str='#000000', cyclic:bool=False) -> Image: + width = image.width + height = image.height + ret_image = Image.new('RGB', size=(width, height), color=background_color) + for x in range(width): + for y in range(height): + if cyclic: + orig_x = x + distance_x + if orig_x > width-1 or orig_x < 0: + orig_x = abs(orig_x % width) + orig_y = y + distance_y + if orig_y > height-1 or orig_y < 0: + orig_y = abs(orig_y % height) + + pixel = image.getpixel((orig_x, orig_y)) + ret_image.putpixel((x, y), pixel) + else: + if x > -distance_x and y > -distance_y: # 防止回转 + if x + distance_x < width and y + distance_y < height: # 防止越界 + pixel = image.getpixel((x + distance_x, y + distance_y)) + ret_image.putpixel((x, y), pixel) + return ret_image + +def chop_image(background_image:Image, layer_image:Image, blend_mode:str, opacity:int) -> Image: + ret_image = background_image + if blend_mode == 'normal': + ret_image = copy.deepcopy(layer_image) + if blend_mode == 'multply': + ret_image = ImageChops.multiply(background_image,layer_image) + if blend_mode == 'screen': + ret_image = ImageChops.screen(background_image, layer_image) + if blend_mode == 'add': + ret_image = ImageChops.add(background_image, layer_image, 1, 0) + if blend_mode == 'subtract': + ret_image = ImageChops.subtract(background_image, layer_image, 1, 0) + if blend_mode == 'difference': + ret_image = ImageChops.difference(background_image, layer_image) + if blend_mode == 'darker': + ret_image = ImageChops.darker(background_image, layer_image) + if blend_mode == 'lighter': + ret_image = ImageChops.lighter(background_image, layer_image) + if blend_mode == 'color_burn': + ret_image = blend_color_burn(background_image, layer_image) + if blend_mode == 'color_dodge': + ret_image = blend_color_dodge(background_image, layer_image) + if blend_mode == 'linear_burn': + ret_image = blend_linear_burn(background_image, layer_image) + if blend_mode == 'linear_dodge': + ret_image = blend_linear_dodge(background_image, layer_image) + if blend_mode == 'overlay': + ret_image = blend_overlay(background_image, layer_image) + if blend_mode == 'soft_light': + ret_image = blend_soft_light(background_image, layer_image) + if blend_mode == 'hard_light': + ret_image = blend_hard_light(background_image, layer_image) + if blend_mode == 'vivid_light': + ret_image = blend_vivid_light(background_image, layer_image) + if blend_mode == 'pin_light': + ret_image = blend_pin_light(background_image, layer_image) + if blend_mode == 'linear_light': + ret_image = blend_linear_light(background_image, layer_image) + if blend_mode == 'hard_mix': + ret_image = blend_hard_mix(background_image, layer_image) + # opacity + if opacity == 0: + ret_image = background_image + elif opacity < 100: + alpha = 1.0 - float(opacity) / 100 + ret_image = Image.blend(ret_image, background_image, alpha) + return ret_image + +def chop_image_v2(background_image:Image, layer_image:Image, blend_mode:str, opacity:int) -> Image: + + backdrop_prepped = np.asfarray(background_image.convert('RGBA')) + source_prepped = np.asfarray(layer_image.convert('RGBA')) + blended_np = BLEND_MODES[blend_mode](backdrop_prepped, source_prepped, opacity / 100) + + # final_tensor = (torch.from_numpy(blended_np / 255)).unsqueeze(0) + # return tensor2pil(_tensor) + + return Image.fromarray(np.uint8(blended_np)).convert('RGB') + +def remove_background(image:Image, mask:Image, color:str) -> Image: + width = image.width + height = image.height + ret_image = Image.new('RGB', size=(width, height), color=color) + ret_image.paste(image, mask=mask) + return ret_image + +def sharpen(image:Image) -> Image: + img = pil2cv2(image) + Laplace_kernel = np.array([[-1, -1, -1], + [-1, 9, -1], + [-1, -1, -1]], dtype=np.float32) + ret_image = cv2.filter2D(img, -1, Laplace_kernel) + return cv22pil(ret_image) + +def gaussian_blur(image:Image, radius:int) -> Image: + # image = image.convert("RGBA") + ret_image = image.filter(ImageFilter.GaussianBlur(radius=radius)) + return ret_image + +def motion_blur(image:Image, angle:int, blur:int) -> Image: + angle += 45 + blur *= 5 + image = np.array(pil2cv2(image)) + M = cv2.getRotationMatrix2D((blur / 2, blur / 2), angle, 1) + motion_blur_kernel = np.diag(np.ones(blur)) + motion_blur_kernel = cv2.warpAffine(motion_blur_kernel, M, (blur, blur)) + motion_blur_kernel = motion_blur_kernel / blur + blurred = cv2.filter2D(image, -1, motion_blur_kernel) + # convert to uint8 + cv2.normalize(blurred, blurred, 0, 255, cv2.NORM_MINMAX) + blurred = np.array(blurred, dtype=np.uint8) + ret_image = cv22pil(blurred) + return ret_image + +def __apply_vignette(image, vignette): + # If image needs to be normalized (0-1 range) + needs_normalization = image.max() > 1 + if needs_normalization: + image = image.astype(np.float32) / 255 + final_image = np.clip(image * vignette[..., np.newaxis], 0, 1) + if needs_normalization: + final_image = (final_image * 255).astype(np.uint8) + return final_image +def vignette_image(image:Image, intensity: float, center_x: float, center_y: float) -> Image: + image = pil2tensor(image) + _, height, width, _ = image.shape + # Generate the vignette for each image in the batch + # Create linear space but centered around the provided center point ratios + x = np.linspace(-1, 1, width) + y = np.linspace(-1, 1, height) + X, Y = np.meshgrid(x - (2 * center_x - 1), y - (2 * center_y - 1)) + # Calculate distances to the furthest corner + distances_to_corners = [ + np.sqrt((0 - center_x) ** 2 + (0 - center_y) ** 2), + np.sqrt((1 - center_x) ** 2 + (0 - center_y) ** 2), + np.sqrt((0 - center_x) ** 2 + (1 - center_y) ** 2), + np.sqrt((1 - center_x) ** 2 + (1 - center_y) ** 2) + ] + max_distance_to_corner = np.max(distances_to_corners) + radius = np.sqrt(X ** 2 + Y ** 2) + radius = radius / (max_distance_to_corner * np.sqrt(2)) # Normalize radius + opacity = np.clip(intensity, 0, 1) + vignette = 1 - radius * opacity + tensor_image = image.numpy() + # Apply vignette + vignette_image = __apply_vignette(tensor_image, vignette) + return tensor2pil(torch.from_numpy(vignette_image).unsqueeze(0)) + +def RGB2YCbCr(t): + YCbCr = t.detach().clone() + YCbCr[:,:,:,0] = 0.2123 * t[:,:,:,0] + 0.7152 * t[:,:,:,1] + 0.0722 * t[:,:,:,2] + YCbCr[:,:,:,1] = 0 - 0.1146 * t[:,:,:,0] - 0.3854 * t[:,:,:,1] + 0.5 * t[:,:,:,2] + YCbCr[:,:,:,2] = 0.5 * t[:,:,:,0] - 0.4542 * t[:,:,:,1] - 0.0458 * t[:,:,:,2] + return YCbCr + +def YCbCr2RGB(t): + RGB = t.detach().clone() + RGB[:,:,:,0] = t[:,:,:,0] + 1.5748 * t[:,:,:,2] + RGB[:,:,:,1] = t[:,:,:,0] - 0.1873 * t[:,:,:,1] - 0.4681 * t[:,:,:,2] + RGB[:,:,:,2] = t[:,:,:,0] + 1.8556 * t[:,:,:,1] + return RGB + +# gaussian blur a tensor image batch in format [B x H x W x C] on H/W (spatial, per-image, per-channel) +def cv_blur_tensor(images, dx, dy): + if min(dx, dy) > 100: + np_img = torch.nn.functional.interpolate(images.detach().clone().movedim(-1,1), scale_factor=0.1, mode='bilinear').movedim(1,-1).cpu().numpy() + for index, image in enumerate(np_img): + np_img[index] = cv2.GaussianBlur(image, (dx // 20 * 2 + 1, dy // 20 * 2 + 1), 0) + return torch.nn.functional.interpolate(torch.from_numpy(np_img).movedim(-1,1), size=(images.shape[1], images.shape[2]), mode='bilinear').movedim(1,-1) + else: + np_img = images.detach().clone().cpu().numpy() + for index, image in enumerate(np_img): + np_img[index] = cv2.GaussianBlur(image, (dx, dy), 0) + return torch.from_numpy(np_img) + +def image_add_grain(image:Image, scale:float=0.5, strength:float=0.5, saturation:float=0.7, toe:float=0.0, seed:int=0) -> Image: + + image = pil2tensor(image.convert("RGB")) + t = image.detach().clone() + torch.manual_seed(seed) + grain = torch.rand(t.shape[0], int(t.shape[1] // scale), int(t.shape[2] // scale), 3) + + YCbCr = RGB2YCbCr(grain) + YCbCr[:, :, :, 0] = cv_blur_tensor(YCbCr[:, :, :, 0], 3, 3) + YCbCr[:, :, :, 1] = cv_blur_tensor(YCbCr[:, :, :, 1], 15, 15) + YCbCr[:, :, :, 2] = cv_blur_tensor(YCbCr[:, :, :, 2], 11, 11) + + grain = (YCbCr2RGB(YCbCr) - 0.5) * strength + grain[:, :, :, 0] *= 2 + grain[:, :, :, 2] *= 3 + grain += 1 + grain = grain * saturation + grain[:, :, :, 1].unsqueeze(3).repeat(1, 1, 1, 3) * (1 - saturation) + + grain = torch.nn.functional.interpolate(grain.movedim(-1, 1), size=(t.shape[1], t.shape[2]), + mode='bilinear').movedim(1, -1) + t[:, :, :, :3] = torch.clip((1 - (1 - t[:, :, :, :3]) * grain) * (1 - toe) + toe, 0, 1) + return tensor2pil(t) + +def filmgrain_image(image:Image, scale:float, grain_power:float, + shadows:float, highs:float, grain_sat:float, + sharpen:int=1, grain_type:int=4, src_gamma:float=1.0, + gray_scale:bool=False, seed:int=0) -> Image: + # image = pil2tensor(image) + # grain_type, 1=fine, 2=fine simple, 3=coarse, 4=coarser + grain_type_index = 3 + + # Apply grain + from .filmgrainer import filmgrainer as fg + grain_image = fg.process(image, scale=scale, src_gamma=src_gamma, grain_power=grain_power, + shadows=shadows, highs=highs, grain_type=grain_type_index, + grain_sat=grain_sat, gray_scale=gray_scale, sharpen=sharpen, seed=seed) + return tensor2pil(torch.from_numpy(grain_image).unsqueeze(0)) + +def __apply_radialblur(image, blur_strength, radial_mask, focus_spread, steps): + from .filmgrainer import processing as processing_utils + needs_normalization = image.max() > 1 + if needs_normalization: + image = image.astype(np.float32) / 255 + blurred_images = processing_utils.generate_blurred_images(image, blur_strength, steps, focus_spread) + final_image = processing_utils.apply_blurred_images(image, blurred_images, radial_mask) + if needs_normalization: + final_image = np.clip(final_image * 255, 0, 255).astype(np.uint8) + return final_image + +def radialblur_image(image:Image, blur_strength:float, center_x:float, center_y:float, focus_spread:float, steps:int=5) -> Image: + width, height = image.size + image = pil2tensor(image) + if image.dim() == 4: + image = image[0] + + # _, height, width, = image.shape + # Generate the vignette for each image in the batch + c_x, c_y = int(width * center_x), int(height * center_y) + # Calculate distances to all corners from the center + distances_to_corners = [ + np.sqrt((c_x - 0)**2 + (c_y - 0)**2), + np.sqrt((c_x - width)**2 + (c_y - 0)**2), + np.sqrt((c_x - 0)**2 + (c_y - height)**2), + np.sqrt((c_x - width)**2 + (c_y - height)**2) + ] + max_distance_to_corner = max(distances_to_corners) + # Create and adjust radial mask + X, Y = np.meshgrid(np.arange(width) - c_x, np.arange(height) - c_y) + radial_mask = np.sqrt(X**2 + Y**2) / max_distance_to_corner + tensor_image = image.numpy() + # Apply blur + blur_image = __apply_radialblur(tensor_image, blur_strength, radial_mask, focus_spread, steps) + return tensor2pil(torch.from_numpy(blur_image).unsqueeze(0)) + +def __apply_depthblur(image, depth_map, blur_strength, focal_depth, focus_spread, steps): + from .filmgrainer import processing as processing_utils + # Normalize the input image if needed + needs_normalization = image.max() > 1 + if needs_normalization: + image = image.astype(np.float32) / 255 + # Normalize the depth map if needed + depth_map = depth_map.astype(np.float32) / 255 if depth_map.max() > 1 else depth_map + # Resize depth map to match the image dimensions + depth_map_resized = cv2.resize(depth_map, (image.shape[1], image.shape[0]), interpolation=cv2.INTER_LINEAR) + if len(depth_map_resized.shape) > 2: + depth_map_resized = cv2.cvtColor(depth_map_resized, cv2.COLOR_BGR2GRAY) + # Adjust the depth map based on the focal plane + depth_mask = np.abs(depth_map_resized - focal_depth) + depth_mask = np.clip(depth_mask / np.max(depth_mask), 0, 1) + # Generate blurred versions of the image + blurred_images = processing_utils.generate_blurred_images(image, blur_strength, steps, focus_spread) + # Use the adjusted depth map as a mask for applying blurred images + final_image = processing_utils.apply_blurred_images(image, blurred_images, depth_mask) + # Convert back to original range if the image was normalized + if needs_normalization: + final_image = np.clip(final_image * 255, 0, 255).astype(np.uint8) + return final_image + +def depthblur_image(image:Image, depth_map:Image, blur_strength:float, focal_depth:float, focus_spread:float, steps:int=5) -> Image: + width, height = image.size + image = pil2tensor(image) + depth_map = pil2tensor(depth_map) + if image.dim() == 4: + image = image[0] + if depth_map.dim() == 4: + depth_map = depth_map[0] + tensor_image = image.numpy() + tensor_image_depth = depth_map.numpy() + # Apply blur + blur_image = __apply_depthblur(tensor_image, tensor_image_depth, blur_strength, focal_depth, focus_spread, steps) + return tensor2pil(torch.from_numpy(blur_image).unsqueeze(0)) + +def fit_resize_image(image:Image, target_width:int, target_height:int, fit:str, resize_sampler:str, background_color:str = '#000000') -> Image: + image = image.convert('RGB') + orig_width, orig_height = image.size + if image is not None: + if fit == 'letterbox': + if orig_width / orig_height > target_width / target_height: # 更宽,上下留黑 + fit_width = target_width + fit_height = int(target_width / orig_width * orig_height) + else: # 更瘦,左右留黑 + fit_height = target_height + fit_width = int(target_height / orig_height * orig_width) + fit_image = image.resize((fit_width, fit_height), resize_sampler) + ret_image = Image.new('RGB', size=(target_width, target_height), color=background_color) + ret_image.paste(fit_image, box=((target_width - fit_width)//2, (target_height - fit_height)//2)) + elif fit == 'crop': + if orig_width / orig_height > target_width / target_height: # 更宽,裁左右 + fit_width = int(orig_height * target_width / target_height) + fit_image = image.crop( + ((orig_width - fit_width)//2, 0, (orig_width - fit_width)//2 + fit_width, orig_height)) + else: # 更瘦,裁上下 + fit_height = int(orig_width * target_height / target_width) + fit_image = image.crop( + (0, (orig_height-fit_height)//2, orig_width, (orig_height-fit_height)//2 + fit_height)) + ret_image = fit_image.resize((target_width, target_height), resize_sampler) + else: + ret_image = image.resize((target_width, target_height), resize_sampler) + return ret_image + +def __rotate_expand(image:Image, angle:float, SSAA:int=0, method:str="lanczos") -> Image: + images = pil2tensor(image) + expand = "true" + height, width = images[0, :, :, 0].shape + + def rotate_tensor(tensor): + resize_sampler = Image.LANCZOS + rotate_sampler = Image.BICUBIC + if method == "bicubic": + resize_sampler = Image.BICUBIC + rotate_sampler = Image.BICUBIC + elif method == "hamming": + resize_sampler = Image.HAMMING + rotate_sampler = Image.BILINEAR + elif method == "bilinear": + resize_sampler = Image.BILINEAR + rotate_sampler = Image.BILINEAR + elif method == "box": + resize_sampler = Image.BOX + rotate_sampler = Image.NEAREST + elif method == "nearest": + resize_sampler = Image.NEAREST + rotate_sampler = Image.NEAREST + img = tensor2pil(tensor) + if SSAA > 1: + img_us_scaled = img.resize((width * SSAA, height * SSAA), resize_sampler) + img_rotated = img_us_scaled.rotate(angle, rotate_sampler, expand == "true", fillcolor=(0, 0, 0, 0)) + img_down_scaled = img_rotated.resize((img_rotated.width // SSAA, img_rotated.height // SSAA), resize_sampler) + result = pil2tensor(img_down_scaled) + else: + img_rotated = img.rotate(angle, rotate_sampler, expand == "true", fillcolor=(0, 0, 0, 0)) + result = pil2tensor(img_rotated) + return result + + if angle == 0.0 or angle == 360.0: + return tensor2pil(images) + else: + rotated_tensor = torch.stack([rotate_tensor(images[i]) for i in range(len(images))]) + return tensor2pil(rotated_tensor).convert('RGB') + +def image_rotate_extend_with_alpha(image:Image, angle:float, alpha:Image=None, method:str="lanczos", SSAA:int=0) -> tuple: + _image = __rotate_expand(image.convert('RGB'), angle, SSAA, method) + if angle is not None: + _alpha = __rotate_expand(alpha.convert('RGB'), angle, SSAA, method) + ret_image = RGB2RGBA(_image, _alpha) + else: + ret_image = _image + return (_image, _alpha.convert('L'), ret_image) + +def create_box_gradient(start_color_inhex:str, end_color_inhex:str, width:int, height:int, scale:int=50) -> Image: + # scale is percent of border to center for the rectangle + if scale > 100: + scale = 100 + elif scale < 1: + scale = 1 + start_color = Hex_to_RGB(start_color_inhex) + end_color = Hex_to_RGB(end_color_inhex) + ret_image = Image.new("RGB", (width, height), start_color) + draw = ImageDraw.Draw(ret_image) + step = int(min(width, height) * scale / 100 / 2) + if step > 0: + for i in range(step): + R = int(start_color[0] * (step - i) / step + end_color[0] * i / step) + G = int(start_color[1] * (step - i) / step + end_color[1] * i / step) + B = int(start_color[2] * (step - i) / step + end_color[2] * i / step) + color = (R, G, B) + draw.rectangle((i, i, width - i, height - i), fill=color) + draw.rectangle((step, step, width - step, height - step), fill=end_color) + return ret_image + +def create_gradient(start_color_inhex:str, end_color_inhex:str, width:int, height:int, direction:str='bottom') -> Image: + # direction = one of top, bottom, left, right + start_color = Hex_to_RGB(start_color_inhex) + end_color = Hex_to_RGB(end_color_inhex) + ret_image = Image.new("RGB", (width, height), start_color) + draw = ImageDraw.Draw(ret_image) + if direction == 'bottom': + for i in range(height): + R = int(start_color[0] * (height - i) / height + end_color[0] * i / height) + G = int(start_color[1] * (height - i) / height + end_color[1] * i / height) + B = int(start_color[2] * (height - i) / height + end_color[2] * i / height) + color = (R, G, B) + draw.line((0, i, width, i), fill=color) + elif direction == 'top': + for i in range(height): + R = int(end_color[0] * (height - i) / height + start_color[0] * i / height) + G = int(end_color[1] * (height - i) / height + start_color[1] * i / height) + B = int(end_color[2] * (height - i) / height + start_color[2] * i / height) + color = (R, G, B) + draw.line((0, i, width, i), fill=color) + elif direction == 'right': + for i in range(width): + R = int(start_color[0] * (width - i) / width + end_color[0] * i / width) + G = int(start_color[1] * (width - i) / width + end_color[1] * i / width) + B = int(start_color[2] * (width - i) / width + end_color[2] * i / width) + color = (R, G, B) + draw.line((i, 0, i, height), fill=color) + elif direction == 'left': + for i in range(width): + R = int(end_color[0] * (width - i) / width + start_color[0] * i / width) + G = int(end_color[1] * (width - i) / width + start_color[1] * i / width) + B = int(end_color[2] * (width - i) / width + start_color[2] * i / width) + color = (R, G, B) + draw.line((i, 0, i, height), fill=color) + else: + log(f'A argument error of imagefunc.create_gradient(), ' + f'"direction=" must one of "top, bottom, left, right".', + message_type='error') + + return ret_image + +def gradient(start_color_inhex:str, end_color_inhex:str, width:int, height:int, angle:float, ) -> Image: + radius = int((width + height) / 4) + g = create_gradient(start_color_inhex, end_color_inhex, radius, radius) + _canvas = Image.new('RGB', size=(radius, radius*3), color=start_color_inhex) + top = Image.new('RGB', size=(radius, radius), color=start_color_inhex) + bottom = Image.new('RGB', size=(radius, radius),color=end_color_inhex) + _canvas.paste(top, box=(0, 0, radius, radius)) + _canvas.paste(g, box=(0, radius, radius, radius * 2)) + _canvas.paste(bottom,box=(0, radius * 2, radius, radius * 3)) + _canvas = _canvas.resize((radius * 3, radius * 3)) + _canvas = __rotate_expand(_canvas,angle) + center = int(_canvas.width / 2) + _x = int(width / 3) + _y = int(height / 3) + ret_image = _canvas.crop((center - _x, center - _y, center + _x, center + _y)) + ret_image = ret_image.resize((width, height)) + return ret_image + +def draw_rect(image:Image, x:int, y:int, width:int, height:int, line_color:str, line_width:int, + box_color:str=None) -> Image: + draw = ImageDraw.Draw(image) + draw.rectangle((x, y, x + width, y + height), fill=box_color, outline=line_color, width=line_width, ) + return image + +def draw_border(image:Image, border_width:int, color:str='#FFFFFF') -> Image: + return ImageOps.expand(image, border=border_width, fill=color) + +# 对灰度图像进行直方图均衡化 +def normalize_gray(image:Image) -> Image: + if image.mode != 'L': + image = image.convert('L') + img = np.asarray(image) + balanced_img = img.copy() + hist, bins = np.histogram(img.reshape(-1), 256, (0, 256)) + bmin = np.min(np.where(hist > (hist.sum() * 0.0005))) + bmax = np.max(np.where(hist > (hist.sum() * 0.0005))) + balanced_img = np.clip(img, bmin, bmax) + balanced_img = ((balanced_img - bmin) / (bmax - bmin) * 255) + return Image.fromarray(balanced_img).convert('L') + +def remap_pixel(pixel:int, min_brightness:int, max_brightness:int) -> int: + return int((pixel - min_brightness) / (max_brightness - min_brightness) * 255) +def histogram_range(image:Image, black_point:int, black_range:int, white_point:int, white_range:int) -> Image: + + if image.mode != 'L': + image = image.convert('L') + + if black_point == 255: + black_point = 254 + if white_point == 0: + white_point = 1 + if black_point + black_range > 255: + black_range = 255 - black_point + if white_range > white_point: + white_range = white_point + + white_image = Image.new("L", size=image.size, color="white") + black_image = Image.new("L", size=image.size, color="black") + + if black_point == white_point: + return white_image + + + # draw white part + white_part = black_image + if white_point < 255 or white_range > 0: + for y in (range(image.height)): + for x in range(image.width): + pixel = image.getpixel((x, y)) + if pixel > white_point: # put white + white_part.putpixel((x, y), 255) + elif pixel > white_point - white_range: + pixel = remap_pixel(pixel, white_point - white_range, white_point) + white_part.putpixel((x, y), pixel) + white_part = ImageChops.invert(white_part) + + + # draw black part + black_part = black_image + if black_point > 0 or black_range > 0: + for y in (range(image.height)): + for x in range(image.width): + pixel = image.getpixel((x, y)) + if pixel < black_point: # put black + black_part.putpixel((x, y), 255) + elif pixel < black_point + black_range: + pixel = remap_pixel(pixel, black_point, black_point + black_range) + black_part.putpixel((x, y), 255 - pixel) + black_part = ImageChops.invert(black_part) + + ret_image = chop_image_v2(white_part, black_part, blend_mode='darken', opacity=100) + + return ret_image + +def histogram_equalization(image:Image, mask:Image=None, gamma_strength=0.5) -> Image: + + if image.mode != 'L': + image = image.convert('L') + + if mask is not None: + if mask.mode != 'L': + mask = mask.convert('L') + else: + mask = Image.new('L', size=image.size, color = 'white') + + # calculate Min/Max brightness pixel + min_brightness = 255 + max_brightness = 0 + average_brightness = 0 + total_pixel = 0 + for y in range(image.height): + for x in range(image.width): + if mask.getpixel((x, y)) == 0: + continue + else: + pixel = image.getpixel((x, y)) + if pixel < min_brightness: + min_brightness = pixel + if pixel > max_brightness: + max_brightness = pixel + average_brightness += pixel + total_pixel += 1 + if total_pixel == 0: + log(f"histogram_equalization: mask is not available, return orinianl image.") + return image + average_brightness = int(average_brightness / total_pixel) + + for y in range(image.height): + for x in range(image.width): + pixel = image.getpixel((x, y)) + image.putpixel((x, y), remap_pixel(pixel, min_brightness, max_brightness)) + + image = gamma_trans(image, (average_brightness - 127) / 127 * gamma_strength * 0.66 + 1) + + return image.convert('L') + +def adjust_levels(image:Image, input_black:int=0, input_white:int=255, midtones:float=1.0, + output_black:int=0, output_white:int=255) -> Image: + + if input_black == input_white or output_black == output_white: + return Image.new('RGB', size=image.size, color='gray') + + img = pil2cv2(image).astype(np.float64) + + if input_black > input_white: + input_black, input_white = input_white, input_black + if output_black > output_white: + output_black, output_white = output_white, output_black + + + # input_levels remap + if input_black > 0 or input_white < 255: + img = 255 * ((img - input_black) / (input_white - input_black)) + img[img < 0] = 0 + img[img > 255] = 255 + + # # mid_tone + if midtones != 1.0: + img = 255 * np.power(img / 255, 1.0 / midtones) + + img[img < 0] = 0 + img[img > 255] = 255 + + # output_levels remap + if output_black > 0 or output_white < 255: + img = (img / 255) * (output_white - output_black) + output_black + img[img < 0] = 0 + img[img > 255] = 255 + + img = img.astype(np.uint8) + return cv22pil(img) + +def get_image_color_tone(image:Image, mask:Image=None) -> str: + image = image.convert('RGB') + max_score = 0.0001 + dominant_color = (255, 255, 255) + if mask is not None: + if mask.mode != 'L': + mask = mask.convert('L') + canvas = Image.new('RGB', size=image.size, color='black') + canvas.paste(image, mask=mask) + image = canvas + + all_colors = image.getcolors(image.width * image.height) + for count, (r, g, b) in all_colors: + if mask is not None: + if r + g + b < 2: # 忽略黑色 + continue + saturation = rgb_to_hsv(r / 255.0, g / 255.0, b / 255.0)[1] + y = min(abs(r * 2104 + g * 4130 + b * 802 + 4096 + 131072) >> 13,235) + y = (y - 16.0) / (235 - 16) + score = (saturation+0.1)*count + if score > max_score: + max_score = score + dominant_color = (r, g, b) + ret_color = RGB_to_Hex(dominant_color) + return ret_color + +def get_image_color_average(image:Image, mask:Image=None) -> str: + image = image.convert('RGB') + width, height = image.size + total_red = 0 + total_green = 0 + total_blue = 0 + total_pixel =0 + for y in range(height): + for x in range(width): + if mask is not None: + if mask.mode != 'L': + mask = mask.convert('L') + if mask.getpixel((x, y)) <= 127: + continue + rgb = image.getpixel((x, y)) + total_red += rgb[0] + total_green += rgb[1] + total_blue += rgb[2] + total_pixel += 1 + + average_red = total_red // total_pixel + average_green = total_green // total_pixel + average_blue = total_blue // total_pixel + color = (average_red, average_green, average_blue) + ret_color = RGB_to_Hex(color) + return ret_color + +def get_gray_average(image:Image, mask:Image=None) -> int: + # image.mode = 'HSV', mask.mode = 'L' + image = image.convert('HSV') + + if mask is not None: + if mask.mode != 'L': + mask = mask.convert('L') + else: + mask = Image.new('L', size=image.size, color='white') + _, _, _v = image.convert('HSV').split() + _v = np.array(_v) + average_gray = _v[np.array(mask) > 16].mean() + # width, height = image.size + # total_gray = 0 + # valid_pixels = 0 + # for y in range(height): + # for x in range(width): + # if mask is not None: + # if mask.getpixel((x, y)) > 16: #mask亮度低于16的忽略不计 + # gray = _v.getpixel((x, y)) + # total_gray += gray + # valid_pixels += 1 + # else: + # gray = _v.getpixel((x, y)) + # total_gray += gray + # valid_pixels += 1 + # average_gray = total_gray // valid_pixels + return average_gray + +def calculate_shadow_highlight_level(gray:int) -> float: + range = 255 + shadow_exponent = 3 + highlight_exponent = 2 + shadow_ratio = gray ** shadow_exponent / range ** shadow_exponent + highlight_ratio = gray ** highlight_exponent / range ** highlight_exponent + shadow_level = shadow_ratio * 100 + (1 - shadow_ratio) * 32 + highlight_level = highlight_ratio * 100 + (1 - highlight_ratio) * 32 + return shadow_level, highlight_level + +def luminance_keyer(image:Image, low:float=0, high:float=1, gamma:float=1) -> Image: + image = pil2tensor(image) + t = image[:, :, :, :3].detach().clone() + alpha = 0.2126 * t[:, :, :, 0] + 0.7152 * t[:, :, :, 1] + 0.0722 * t[:, :, :, 2] + if low == high: + alpha = (alpha > high).to(t.dtype) + else: + alpha = (alpha - low) / (high - low) + if gamma != 1.0: + alpha = torch.pow(alpha, 1 / gamma) + alpha = torch.clamp(alpha, min=0, max=1).unsqueeze(3).repeat(1, 1, 1, 3) + return tensor2pil(alpha).convert('L') + +def get_image_bright_average(image:Image) -> int: + image = image.convert('L') + width, height = image.size + total_bright = 0 + pixels = 0 + for y in range(height): + for x in range(width): + b = image.getpixel((x, y)) + if b > 1: # 排除死黑 + pixels += 1 + total_bright += b + return int(total_bright / pixels) + +def image_channel_split(image:Image, mode = 'RGBA') -> tuple: + _image = image.convert('RGBA') + channel1 = Image.new('L', size=_image.size, color='black') + channel2 = Image.new('L', size=_image.size, color='black') + channel3 = Image.new('L', size=_image.size, color='black') + channel4 = Image.new('L', size=_image.size, color='black') + if mode == 'RGBA': + channel1, channel2, channel3, channel4 = _image.split() + if mode == 'RGB': + channel1, channel2, channel3 = _image.convert('RGB').split() + if mode == 'YCbCr': + channel1, channel2, channel3 = _image.convert('YCbCr').split() + if mode == 'LAB': + channel1, channel2, channel3 = _image.convert('LAB').split() + if mode == 'HSV': + channel1, channel2, channel3 = _image.convert('HSV').split() + return channel1, channel2, channel3, channel4 + +def image_channel_merge(channels:tuple, mode = 'RGB' ) -> Image: + channel1 = channels[0].convert('L') + channel2 = channels[1].convert('L') + channel3 = channels[2].convert('L') + channel4 = Image.new('L', size=channel1.size, color='white') + if mode == 'RGBA': + if len(channels) > 3: + channel4 = channels[3].convert('L') + ret_image = Image.merge('RGBA',[channel1, channel2, channel3, channel4]) + elif mode == 'RGB': + ret_image = Image.merge('RGB', [channel1, channel2, channel3]) + elif mode == 'YCbCr': + ret_image = Image.merge('YCbCr', [channel1, channel2, channel3]).convert('RGB') + elif mode == 'LAB': + ret_image = Image.merge('LAB', [channel1, channel2, channel3]).convert('RGB') + elif mode == 'HSV': + ret_image = Image.merge('HSV', [channel1, channel2, channel3]).convert('RGB') + return ret_image + +def image_gray_offset(image:Image, offset:int) -> Image: + image = image.convert('L') + image_array = np.array(image, dtype=np.int16) + image_array = np.clip(image_array + offset, 0, 255).astype(np.uint8) + ret_image = Image.fromarray(image_array, mode='L') + return ret_image + +def image_gray_ratio(image:Image, ratio:float) -> Image: + image = image.convert('L') + image_array = np.array(image, dtype=np.float32) + image_array = np.clip(image_array * ratio, 0, 255).astype(np.uint8) + ret_image = Image.fromarray(image_array, mode='L') + return ret_image + +def image_hue_offset(image:Image, offset:int) -> Image: + image = image.convert('L') + image_array = np.array(image, dtype=np.int16) + image_array = (image_array + offset) % 256 + image_array = image_array.astype(np.uint8) + ret_image = Image.fromarray(image_array, mode='L') + + return ret_image + +def gamma_trans(image:Image, gamma:float) -> Image: + cv2_image = pil2cv2(image) + gamma_table = [np.power(x/255.0,gamma)*255.0 for x in range(256)] + gamma_table = np.round(np.array(gamma_table)).astype(np.uint8) + _corrected = cv2.LUT(cv2_image,gamma_table) + return cv22pil(_corrected) + + +def read_LUT_IridasCube_encode_utf8(path: str): + from colour.utilities import as_float_array, as_int_scalar + from colour.io.luts.lut import LUT3x1D, LUT3D + title = re.sub("_|-|\\.", " ", os.path.splitext(os.path.basename(path))[0]) + domain_min, domain_max = np.array([0, 0, 0]), np.array([1, 1, 1]) + dimensions: int = 3 + size: int = 2 + data = [] + comments = [] + + with open(path, encoding='utf-8') as cube_file: + lines = cube_file.readlines() + for line in lines: + + line = line.strip() # noqa: PLW2901 + + if len(line) == 0: + continue + + if line.startswith("#"): + comments.append(line[1:].strip()) + continue + + tokens = line.split() + if tokens[0] == "TITLE": + title = " ".join(tokens[1:])[1:-1] + elif tokens[0] == "DOMAIN_MIN": + domain_min = as_float_array(tokens[1:]) + elif tokens[0] == "DOMAIN_MAX": + domain_max = as_float_array(tokens[1:]) + elif tokens[0] == "LUT_1D_SIZE": + dimensions = 2 + size = as_int_scalar(tokens[1]) + elif tokens[0] == "LUT_3D_SIZE": + dimensions = 3 + size = as_int_scalar(tokens[1]) + else: + data.append(tokens) + + table = as_float_array(data) + + LUT: LUT3x1D | LUT3D + if dimensions == 2: + LUT = LUT3x1D( + table, + title, + np.vstack([domain_min, domain_max]), + comments=comments, + ) + elif dimensions == 3: + # The lines of table data shall be in ascending index order, + # with the first component index (Red) changing most rapidly, + # and the last component index (Blue) changing least rapidly. + table = table.reshape([size, size, size, 3], order="F") + + LUT = LUT3D( + table, + title, + np.vstack([domain_min, domain_max]), + comments=comments, + ) + + return LUT + + +def apply_lut(image:Image, lut_file:str, colorspace:str, strength:int, clip_values:bool=True) -> Image: + """ + Apply a LUT to an image. + :param image: Image to apply the LUT to. + :param lut_file: LUT file to apply. + :param colorspace: Colorspace to convert the image to before applying the LUT. + :param clip_values: Clip the values of the LUT to the domain of the LUT. + :param strength: Strength of the LUT. + :return: Image with the LUT applied. + """ + log_colorspace = False + if colorspace == "log": + log_colorspace = True + + # from colour.io.luts.iridas_cube import read_LUT_IridasCube + + lut = read_LUT_IridasCube_encode_utf8(lut_file) + lut.name = lut_file + + if clip_values: + if lut.domain[0].max() == lut.domain[0].min() and lut.domain[1].max() == lut.domain[1].min(): + lut.table = np.clip(lut.table, lut.domain[0, 0], lut.domain[1, 0]) + else: + if len(lut.table.shape) == 2: # 3x1D + for dim in range(3): + lut.table[:, dim] = np.clip(lut.table[:, dim], lut.domain[0, dim], lut.domain[1, dim]) + else: # 3D + for dim in range(3): + lut.table[:, :, :, dim] = np.clip(lut.table[:, :, :, dim], lut.domain[0, dim], lut.domain[1, dim]) + + img = pil2tensor(image) + lut_img = img.numpy().copy() + is_non_default_domain = not np.array_equal(lut.domain, np.array([[0., 0., 0.], [1., 1., 1.]])) + dom_scale = None + if is_non_default_domain: + dom_scale = lut.domain[1] - lut.domain[0] + lut_img = lut_img * dom_scale + lut.domain[0] + if log_colorspace: + lut_img = lut_img ** (1/2.2) + lut_img = lut.apply(lut_img) + if log_colorspace: + lut_img = lut_img ** (2.2) + if is_non_default_domain: + lut_img = (lut_img - lut.domain[0]) / dom_scale + lut_img = torch.from_numpy(lut_img) + if strength < 100: + strength /= 100 + lut_img = strength * lut_img + (1 - strength) * img + + return tensor2pil(lut_img) + +def color_adapter(image:Image, ref_image:Image) -> Image: + image = pil2cv2(image) + ref_image = pil2cv2(ref_image) + image = cv2.cvtColor(image, cv2.COLOR_BGR2LAB) + image_mean, image_std = calculate_mean_std(image) + ref_image = cv2.cvtColor(ref_image, cv2.COLOR_BGR2LAB) + ref_image_mean, ref_image_std = calculate_mean_std(ref_image) + _image = ((image - image_mean) * (ref_image_std / image_std)) + ref_image_mean + np.putmask(_image, _image > 255, values=255) + np.putmask(_image, _image < 0, values=0) + ret_image = cv2.cvtColor(cv2.convertScaleAbs(_image), cv2.COLOR_LAB2BGR) + return cv22pil(ret_image) + +def calculate_mean_std(image:Image): + mean, std = cv2.meanStdDev(image) + mean = np.hstack(np.around(mean, decimals=2)) + std = np.hstack(np.around(std, decimals=2)) + return mean, std + +def image_watercolor(image:Image, level:int=50) -> Image: + img = pil2cv2(image) + img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) + factor = (level / 128.0) ** 2 + sigmaS= int((image.width + image.height) / 5.0 * factor) + 1 + sigmaR = sigmaS / 32.0 * factor + 0.002 + img_color = cv2.stylization(img, sigma_s=sigmaS, sigma_r=sigmaR) + ret_image = cv2.cvtColor(img_color, cv2.COLOR_BGR2RGB) + return cv22pil(ret_image) + + +def image_beauty(image:Image, level:int=50) -> Image: + img = pil2cv2(image) + img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) + factor = (level / 50.0)**2 + d = int((image.width + image.height) / 256 * factor) + sigmaColor = int((image.width + image.height) / 256 * factor) + sigmaSpace = int((image.width + image.height) / 160 * factor) + img_bit = cv2.bilateralFilter(src=img, d=d, sigmaColor=sigmaColor, sigmaSpace=sigmaSpace) + ret_image = cv2.cvtColor(img_bit, cv2.COLOR_BGR2RGB) + return cv22pil(ret_image) + + +def pixel_spread(image:Image, mask:Image) -> Image: + from pymatting import estimate_foreground_ml + i1 = pil2tensor(image) + if mask.mode != 'RGB': + mask = mask.convert('RGB') + i_dup = copy.deepcopy(i1.cpu().numpy().astype(np.float64)) + a_dup = copy.deepcopy(pil2tensor(mask).cpu().numpy().astype(np.float64)) + fg = copy.deepcopy(i1.cpu().numpy().astype(np.float64)) + + for index, img in enumerate(i_dup): + alpha = a_dup[index][:, :, 0] + fg[index], _ = estimate_foreground_ml(img, np.array(alpha), return_background=True) + + return tensor2pil(torch.from_numpy(fg.astype(np.float32))) + + +def generate_text_image(text:str, font_path:str, font_size:int, text_color:str="#FFFFFF", + vertical:bool=True, stroke_width:int=1, stroke_color:str="#000000", + spacing:int=0, leading:int=0) -> tuple: + + lines = text.split("\n") + if vertical: + layout = "vertical" + else: + layout = "horizontal" + char_coordinates = [] + if layout == "vertical": + x = 0 + y = 0 + for i in range(len(lines)): + line = lines[i] + for char in line: + char_coordinates.append((x, y)) + y += font_size + spacing + x += font_size + leading + y = 0 + else: + x = 0 + y = 0 + for line in lines: + for char in line: + char_coordinates.append((x, y)) + x += font_size + spacing + y += font_size + leading + x = 0 + if layout == "vertical": + width = (len(lines) * (font_size + spacing)) - spacing + height = ((len(max(lines, key=len)) + 1) * (font_size + spacing)) + spacing + else: + width = (len(max(lines, key=len)) * (font_size + spacing)) - spacing + height = ((len(lines) - 1) * (font_size + spacing)) + font_size + + image = Image.new('RGBA', size=(width, height), color=stroke_color) + draw = ImageDraw.Draw(image) + font = ImageFont.truetype(font_path, font_size) + index = 0 + for i, line in enumerate(lines): + for j, char in enumerate(line): + x, y = char_coordinates[index] + if stroke_width > 0: + draw.text((x - stroke_width, y), char, font=font, fill=stroke_color) + draw.text((x + stroke_width, y), char, font=font, fill=stroke_color) + draw.text((x, y - stroke_width), char, font=font, fill=stroke_color) + draw.text((x, y + stroke_width), char, font=font, fill=stroke_color) + draw.text((x, y), char, font=font, fill=text_color) + index += 1 + return (image.convert('RGB'), image.split()[3]) + +def watermark_image_size(image:Image) -> int: + size = int(math.sqrt(image.width * image.height * 0.015625) * 0.9) + return size + +def add_invisibal_watermark(image:Image, watermark_image:Image) -> Image: + """ + Adds an invisible watermark to an image. + """ + orig_image_mode = image.mode + temp_dir = os.path.join(folder_paths.get_temp_directory(), generate_random_name('_watermark_', '_temp', 16)) + if os.path.isdir(temp_dir): + shutil.rmtree(temp_dir) + image_dir = os.path.join(temp_dir, 'image') + wm_dir = os.path.join(temp_dir, 'wm') + result_dir = os.path.join(temp_dir, 'result') + + try: + os.makedirs(image_dir) + os.makedirs(wm_dir) + os.makedirs(result_dir) + except Exception as e: + # print(e) + log(f"Error: {NODE_NAME} skipped, because unable to create temporary folder.", message_type='error') + return (image,) + + image_file_name = os.path.join(generate_random_name('watermark_orig_', '_temp', 16) + '.png') + wm_file_name = os.path.join(generate_random_name('watermark_image_', '_temp', 16) + '.png') + output_file_name = os.path.join(generate_random_name('watermark_output_', '_temp', 16) + '.png') + + try: + if image.mode != "RGB": + image = image.convert("RGB") + image.save(os.path.join(image_dir, image_file_name)) + watermark_image.save(os.path.join(wm_dir, wm_file_name)) + except IOError as e: + # print(e) + log(f"Error: {NODE_NAME} skipped, because unable to create temporary file.", message_type='error') + return (image,) + + from blind_watermark import WaterMark + bwm1 = WaterMark(password_img=1, password_wm=1) + bwm1.read_img(os.path.join(image_dir, image_file_name)) + bwm1.read_wm(os.path.join(wm_dir, wm_file_name)) + output_image = os.path.join(result_dir, output_file_name) + bwm1.embed(output_image, compression_ratio=100) + + return Image.open(output_image).convert(orig_image_mode) + +def decode_watermark(image:Image, watermark_image_size:int=94) -> Image: + temp_dir = os.path.join(folder_paths.get_temp_directory(), generate_random_name('_watermark_', '_temp', 16)) + if os.path.isdir(temp_dir): + shutil.rmtree(temp_dir) + image_dir = os.path.join(temp_dir, 'decode_image') + result_dir = os.path.join(temp_dir, 'decode_result') + + try: + os.makedirs(image_dir) + os.makedirs(result_dir) + except Exception as e: + # print(e) + log(f"Error: {NODE_NAME} skipped, because unable to create temporary folder.", message_type='error') + return (image,) + + image_file_name = os.path.join(generate_random_name('watermark_decode_', '_temp', 16) + '.png') + output_file_name = os.path.join(generate_random_name('watermark_decode_output_', '_temp', 16) + '.png') + + try: + image.save(os.path.join(image_dir, image_file_name)) + except IOError as e: + # print(e) + log(f"Error: {NODE_NAME} skipped, because unable to create temporary file.", message_type='error') + return (image,) + + from blind_watermark import WaterMark + bwm1 = WaterMark(password_img=1, password_wm=1) + decode_image = os.path.join(image_dir, image_file_name) + output_image = os.path.join(result_dir, output_file_name) + + try: + bwm1.extract(filename=decode_image, wm_shape=(watermark_image_size, watermark_image_size), + out_wm_name=os.path.join(output_image),) + ret_image = Image.open(output_image) + except Exception as e: + log(f"blind watermark extract fail, {e}") + ret_image = Image.new("RGB", (64, 64), color="black") + ret_image = normalize_gray(ret_image) + return ret_image + +def generate_text_image(width:int, height:int, text:str, font_file:str, text_scale:float=1, font_color:str="#FFFFFF",) -> Image: + image = Image.new("RGBA", (width, height), (0, 0, 0, 0)) + draw = ImageDraw.Draw(image) + font_size = int(width / len(text) * text_scale) + font = ImageFont.truetype(font_file, font_size) + bbox = draw.textbbox((0, 0), text, font=font) + text_width, text_height = bbox[2] - bbox[0], bbox[3] - bbox[1] + x = int((width - text_width) / 2) + y = int((height - text_height) / 2) - int(font_size / 2) + draw.text((x, y), text, font=font, fill=font_color) + return image + +'''Mask Functions''' + +def create_mask_from_color_cv2(image:Image, color:str, tolerance:int=0) -> Image: + (r, g, b) = Hex_to_RGB(color) + target_color = (b, g, r) + tolerance = 127 + int(tolerance * 1.28) + # tolerance = 255 - tolerance + # 将RGB颜色转换为HSV颜色空间 + image = pil2cv2(image) + hsv_image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) + + # 定义目标颜色的HSV范围 + lower_color = np.array([max(target_color[0] - tolerance, 0), max(target_color[1] - tolerance, 0), max(target_color[2] - tolerance, 0)]) + upper_color = np.array([min(target_color[0] + tolerance, 255), min(target_color[1] + tolerance, 255), min(target_color[2] + tolerance, 255)]) + + # 创建掩码 + mask = cv2.inRange(hsv_image, lower_color, upper_color) + + return cv22pil(mask).convert("L") + +def create_mask_from_color_tensor(image:Image, color:str, tolerance:int=0) -> Image: + threshold = int(tolerance * 1.28) + (red, green, blue) = Hex_to_RGB(color) + image = pil2tensor(image).squeeze() + temp = (torch.clamp(image, 0, 1.0) * 255.0).round().to(torch.int) + color_value = torch.tensor([red, green, blue]) + lower_bound = (color_value - threshold).clamp(min=0) + upper_bound = (color_value + threshold).clamp(max=255) + lower_bound = lower_bound.view(1, 1, 1, 3) + upper_bound = upper_bound.view(1, 1, 1, 3) + mask = (temp >= lower_bound) & (temp <= upper_bound) + mask = mask.all(dim=-1) + mask = mask.float() + return tensor2pil(mask).convert("L") + +@lru_cache(maxsize=1, typed=False) +def load_RMBG_model(): + from .briarmbg import BriaRMBG + current_directory = os.path.dirname(os.path.abspath(__file__)) + device = "cuda" if torch.cuda.is_available() else "cpu" + net = BriaRMBG() + model_path = "" + try: + model_path = os.path.join(os.path.normpath(folder_paths.folder_names_and_paths['rmbg'][0][0]), "model.pth") + except: + pass + if not os.path.exists(model_path): + model_path = os.path.join(folder_paths.models_dir, "rmbg", "RMBG-1.4", "model.pth") + if not os.path.exists(model_path): + model_path = os.path.join(os.path.dirname(current_directory), "RMBG-1.4", "model.pth") + net.load_state_dict(torch.load(model_path, map_location=device, weights_only=True)) + net.to(device) + net.eval() + return net + + +def RMBG(image:Image) -> Image: + rmbgmodel = load_RMBG_model() + w, h = image.size + im_np = np.array(image.resize((1024, 1024), Image.BILINEAR)) + im_tensor = torch.tensor(im_np, dtype=torch.float32).permute(2, 0, 1) + im_tensor = torch.divide(torch.unsqueeze(im_tensor, 0), 255.0) + im_tensor = TF.normalize(im_tensor, [0.5, 0.5, 0.5], [1.0, 1.0, 1.0]) + if torch.cuda.is_available(): + im_tensor = im_tensor.cuda() + result = rmbgmodel(im_tensor) + result = torch.squeeze(F.interpolate(result[0][0], size=(h, w), mode='bilinear'), 0) + ma = torch.max(result) + mi = torch.min(result) + result = (result - mi) / (ma - mi) + im_array = (result * 255).cpu().data.numpy().astype(np.uint8) + _mask = torch.from_numpy(np.squeeze(im_array).astype(np.float32)) + return tensor2pil(_mask) + +def guided_filter_alpha(image:torch.Tensor, mask:torch.Tensor, filter_radius:int) -> torch.Tensor: + sigma = 0.15 + d = filter_radius + 1 + mask = pil2tensor(tensor2pil(mask).convert('RGB')) + if not bool(d % 2): + d += 1 + s = sigma / 10 + i_dup = copy.deepcopy(image.cpu().numpy()) + a_dup = copy.deepcopy(mask.cpu().numpy()) + for index, image in enumerate(i_dup): + alpha_work = a_dup[index] + i_dup[index] = guidedFilter(image, alpha_work, d, s) + return torch.from_numpy(i_dup) + +#pymatting edge detail +def mask_edge_detail(image:torch.Tensor, mask:torch.Tensor, detail_range:int=8, black_point:float=0.01, white_point:float=0.99) -> torch.Tensor: + from pymatting import fix_trimap, estimate_alpha_cf + d = detail_range * 5 + 1 + mask = pil2tensor(tensor2pil(mask).convert('RGB')) + if not bool(d % 2): + d += 1 + i_dup = copy.deepcopy(image.cpu().numpy().astype(np.float64)) + a_dup = copy.deepcopy(mask.cpu().numpy().astype(np.float64)) + for index, img in enumerate(i_dup): + trimap = a_dup[index][:, :, 0] # convert to single channel + if detail_range > 0: + trimap = cv2.GaussianBlur(trimap, (d, d), 0) + trimap = fix_trimap(trimap, black_point, white_point) + alpha = estimate_alpha_cf(img, trimap, laplacian_kwargs={"epsilon": 1e-6}, + cg_kwargs={"maxiter": 500}) + a_dup[index] = np.stack([alpha, alpha, alpha], axis=-1) # convert back to rgb + return torch.from_numpy(a_dup.astype(np.float32)) + +class VITMatteModel: + def __init__(self,model,processor): + self.model = model + self.processor = processor + +def load_VITMatte_model(model_name:str, local_files_only:bool=False) -> object: + if local_files_only: + model_name = Path(os.path.join(folder_paths.models_dir, "vitmatte")) + # model_name = Path(os.path.join(folder_paths.models_dir, "vitmatte")) + from transformers import VitMatteImageProcessor, VitMatteForImageMatting + model = VitMatteForImageMatting.from_pretrained(model_name, local_files_only=local_files_only) + processor = VitMatteImageProcessor.from_pretrained(model_name, local_files_only=local_files_only) + vitmatte = VITMatteModel(model, processor) + return vitmatte + +def generate_VITMatte(image:Image, trimap:Image, local_files_only:bool=False, device:str="cpu", max_megapixels:float=2.0) -> Image: + if image.mode != 'RGB': + image = image.convert('RGB') + if trimap.mode != 'L': + trimap = trimap.convert('L') + max_megapixels *= 1048576 + width, height = image.size + ratio = width / height + target_width = math.sqrt(ratio * max_megapixels) + target_height = target_width / ratio + target_width = int(target_width) + target_height = int(target_height) + if width * height > max_megapixels: + image = image.resize((target_width, target_height), Image.BILINEAR) + trimap = trimap.resize((target_width, target_height), Image.BILINEAR) + # log(f"vitmatte image size {width}x{height} too large, resize to {target_width}x{target_height} for processing.") + model_name = "hustvl/vitmatte-small-composition-1k" + if device=="cpu": + device = torch.device('cpu') + else: + if torch.cuda.is_available(): + device = torch.device('cuda') + else: + log("vitmatte device is set to cuda, but not available, using cpu instead.") + device = torch.device('cpu') + vit_matte_model = load_VITMatte_model(model_name=model_name, local_files_only=local_files_only) + vit_matte_model.model.to(device) + # log(f"vitmatte processing, image size = {image.width}x{image.height}, device = {device}.") + inputs = vit_matte_model.processor(images=image, trimaps=trimap, return_tensors="pt") + with torch.no_grad(): + inputs = {k: v.to(device) for k, v in inputs.items()} + predictions = vit_matte_model.model(**inputs).alphas + if torch.cuda.is_available(): + torch.cuda.empty_cache() + torch.cuda.ipc_collect() + mask = tensor2pil(predictions).convert('L') + mask = mask.crop( + (0, 0, image.width, image.height)) # remove padding that the prediction appends (works in 32px tiles) + if width * height > max_megapixels: + mask = mask.resize((width, height), Image.BILINEAR) + return mask + +def generate_VITMatte_trimap(mask:torch.Tensor, erode_kernel_size:int, dilate_kernel_size:int) -> Image: + def g_trimap(mask, erode_kernel_size=10, dilate_kernel_size=10): + erode_kernel = np.ones((erode_kernel_size, erode_kernel_size), np.uint8) + dilate_kernel = np.ones((dilate_kernel_size, dilate_kernel_size), np.uint8) + eroded = cv2.erode(mask, erode_kernel, iterations=5) + dilated = cv2.dilate(mask, dilate_kernel, iterations=5) + trimap = np.zeros_like(mask) + trimap[dilated == 255] = 128 + trimap[eroded == 255] = 255 + return trimap + + mask = mask.squeeze(0).cpu().detach().numpy().astype(np.uint8) * 255 + trimap = g_trimap(mask, erode_kernel_size, dilate_kernel_size).astype(np.float32) + trimap[trimap == 128] = 0.5 + trimap[trimap == 255] = 1 + trimap = torch.from_numpy(trimap).unsqueeze(0) + + return tensor2pil(trimap).convert('L') + + +def get_a_person_mask_generator_model_path() -> str: + model_folder_name = 'mediapipe' + model_name = 'selfie_multiclass_256x256.tflite' + + model_file_path = "" + try: + model_file_path = os.path.join(os.path.normpath(folder_paths.folder_names_and_paths[model_folder_name][0][0]), model_name) + except: + pass + if not os.path.exists(model_file_path): + model_file_path = os.path.join(folder_paths.models_dir, model_folder_name, model_name) + + if not os.path.exists(model_file_path): + import wget + model_url = f'https://storage.googleapis.com/mediapipe-models/image_segmenter/selfie_multiclass_256x256/float32/latest/{model_name}' + log(f"Downloading '{model_name}' model") + os.makedirs(os.path.dirname(model_file_path), exist_ok=True) + wget.download(model_url, model_file_path) + return model_file_path + +def mask_fix(images:torch.Tensor, radius:int, fill_holes:int, white_threshold:float, extra_clip:float) -> torch.Tensor: + d = radius * 2 + 1 + i_dup = copy.deepcopy(images.cpu().numpy()) + for index, image in enumerate(i_dup): + cleaned = cv2.bilateralFilter(image, 9, 0.05, 8) + alpha = np.clip((image - white_threshold) / (1 - white_threshold), 0, 1) + rgb = image * alpha + alpha = cv2.GaussianBlur(alpha, (d, d), 0) * 0.99 + np.average(alpha) * 0.01 + rgb = cv2.GaussianBlur(rgb, (d, d), 0) * 0.99 + np.average(rgb) * 0.01 + rgb = rgb / np.clip(alpha, 0.00001, 1) + rgb = rgb * extra_clip + cleaned = np.clip(cleaned / rgb, 0, 1) + if fill_holes > 0: + fD = fill_holes * 2 + 1 + gamma = cleaned * cleaned + kD = np.ones((fD, fD), np.uint8) + kE = np.ones((fD + 2, fD + 2), np.uint8) + gamma = cv2.dilate(gamma, kD, iterations=1) + gamma = cv2.erode(gamma, kE, iterations=1) + gamma = cv2.GaussianBlur(gamma, (fD, fD), 0) + cleaned = np.maximum(cleaned, gamma) + i_dup[index] = cleaned + return torch.from_numpy(i_dup) + +def histogram_remap(image:torch.Tensor, blackpoint:float, whitepoint:float) -> torch.Tensor: + bp = min(blackpoint, whitepoint - 0.001) + scale = 1 / (whitepoint - bp) + i_dup = copy.deepcopy(image.cpu().numpy()) + i_dup = np.clip((i_dup - bp) * scale, 0.0, 1.0) + return torch.from_numpy(i_dup) + +def expand_mask(mask:torch.Tensor, grow:int, blur:int) -> torch.Tensor: + # grow + c = 0 + kernel = np.array([[c, 1, c], + [1, 1, 1], + [c, 1, c]]) + growmask = mask.reshape((-1, mask.shape[-2], mask.shape[-1])) + out = [] + for m in growmask: + output = m.numpy() + for _ in range(abs(grow)): + if grow < 0: + output = scipy.ndimage.grey_erosion(output, footprint=kernel) + else: + output = scipy.ndimage.grey_dilation(output, footprint=kernel) + output = torch.from_numpy(output) + out.append(output) + # blur + for idx, tensor in enumerate(out): + pil_image = tensor2pil(tensor.cpu().detach()) + pil_image = pil_image.filter(ImageFilter.GaussianBlur(blur)) + out[idx] = pil2tensor(pil_image) + ret_mask = torch.cat(out, dim=0) + return ret_mask + +def mask_invert(mask:torch.Tensor) -> torch.Tensor: + return 1 - mask + +def subtract_mask(masks_a:torch.Tensor, masks_b:torch.Tensor) -> torch.Tensor: + return torch.clamp(masks_a - masks_b, 0, 255) + +def add_mask(masks_a:torch.Tensor, masks_b:torch.Tensor) -> torch.Tensor: + mask = chop_image(tensor2pil(masks_a), tensor2pil(masks_b), blend_mode='add', opacity=100) + return image2mask(mask) + +def RGB2RGBA(image:Image, mask:Image) -> Image: + (R, G, B) = image.convert('RGB').split() + return Image.merge('RGBA', (R, G, B, mask.convert('L'))) + +def mask_area(image:Image) -> tuple: + cv2_image = pil2cv2(image.convert('RGBA')) + gray = cv2.cvtColor(cv2_image, cv2.COLOR_BGR2GRAY) + _, thresh = cv2.threshold(gray, 127, 255, 0) + locs = np.where(thresh == 255) + x1 = np.min(locs[1]) if len(locs[1]) > 0 else 0 + x2 = np.max(locs[1]) if len(locs[1]) > 0 else image.width + y1 = np.min(locs[0]) if len(locs[0]) > 0 else 0 + y2 = np.max(locs[0]) if len(locs[0]) > 0 else image.height + x1, y1, x2, y2 = min(x1, x2), min(y1, y2), max(x1, x2), max(y1, y2) + return (x1, y1, x2 - x1, y2 - y1) + +def min_bounding_rect(image:Image) -> tuple: + cv2_image = pil2cv2(image) + gray = cv2.cvtColor(cv2_image, cv2.COLOR_BGR2GRAY) + ret, thresh = cv2.threshold(gray, 127, 255, 0) + contours, _ = cv2.findContours(thresh, 1, 2) + x, y, width, height = 0, 0, 0, 0 + area = 0 + for contour in contours: + _x, _y, _w, _h = cv2.boundingRect(contour) + _area = _w * _h + if _area > area: + area = _area + x, y, width, height = _x, _y, _w, _h + return (x, y, width, height) + +def max_inscribed_rect(image:Image) -> tuple: + img = pil2cv2(image) + img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) + ret, img_bin = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY) + contours, _ = cv2.findContours(img_bin, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE) + contour = contours[0].reshape(len(contours[0]), 2) + rect = [] + for i in range(len(contour)): + x1, y1 = contour[i] + for j in range(len(contour)): + x2, y2 = contour[j] + area = abs(y2 - y1) * abs(x2 - x1) + rect.append(((x1, y1), (x2, y2), area)) + all_rect = sorted(rect, key=lambda x: x[2], reverse=True) + if all_rect: + best_rect_found = False + index_rect = 0 + nb_rect = len(all_rect) + while not best_rect_found and index_rect < nb_rect: + rect = all_rect[index_rect] + (x1, y1) = rect[0] + (x2, y2) = rect[1] + valid_rect = True + x = min(x1, x2) + while x < max(x1, x2) + 1 and valid_rect: + if any(img[y1, x]) == 0 or any(img[y2, x]) == 0: + valid_rect = False + x += 1 + y = min(y1, y2) + while y < max(y1, y2) + 1 and valid_rect: + if any(img[y, x1]) == 0 or any(img[y, x2]) == 0: + valid_rect = False + y += 1 + if valid_rect: + best_rect_found = True + index_rect += 1 + #较小的数值排前面 + x1, y1, x2, y2 = min(x1, x2), min(y1, y2), max(x1, x2), max(y1, y2) + return (x1, y1, x2 - x1, y2 - y1) + +def gray_threshold(image:Image, thresh:int=127, otsu:bool=False) -> Image: + cv2_image = pil2cv2(image) + gray = cv2.cvtColor(cv2_image, cv2.COLOR_BGR2GRAY) + if otsu: + _, thresh = cv2.threshold(gray,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU) + else: + _, thresh = cv2.threshold(gray, thresh, 255, cv2.THRESH_TOZERO) + return cv22pil(thresh).convert('L') + +def image_to_colormap(image:Image, index:int) -> Image: + return cv22pil(cv2.applyColorMap(pil2cv2(image), index)) + +# 检查mask有效区域面积比例 +def mask_white_area(mask:Image, white_point:int) -> float: + if mask.mode != 'L': + mask.convert('L') + white_pixels = 0 + for y in range(mask.height): + for x in range(mask.width): + mask.getpixel((x, y)) > 16 + if mask.getpixel((x, y)) > white_point: + white_pixels += 1 + return white_pixels / (mask.width * mask.height) + +'''Color Functions''' + +def color_balance(image:Image, shadows:list, midtones:list, highlights:list, + shadow_center:float=0.15, midtone_center:float=0.5, highlight_center:float=0.8, + shadow_max:float=0.1, midtone_max:float=0.3, highlight_max:float=0.2, + preserve_luminosity:bool=False) -> Image: + + img = pil2tensor(image) + # Create a copy of the img tensor + img_copy = img.clone() + + # Calculate the original luminance if preserve_luminosity is True + if preserve_luminosity: + original_luminance = 0.2126 * img_copy[..., 0] + 0.7152 * img_copy[..., 1] + 0.0722 * img_copy[..., 2] + + # Define the adjustment curves + def adjust(x, center, value, max_adjustment): + # Scale the adjustment value + value = value * max_adjustment + + # Define control points + points = torch.tensor([[0, 0], [center, center + value], [1, 1]]) + + # Create cubic spline + from scipy.interpolate import CubicSpline + cs = CubicSpline(points[:, 0], points[:, 1]) + + # Apply the cubic spline to the color channel + return torch.clamp(torch.from_numpy(cs(x)), 0, 1) + + # Apply the adjustments to each color channel + # shadows, midtones, highlights are lists of length 3 (for R, G, B channels) with values between -1 and 1 + for i, (s, m, h) in enumerate(zip(shadows, midtones, highlights)): + img_copy[..., i] = adjust(img_copy[..., i], shadow_center, s, shadow_max) + img_copy[..., i] = adjust(img_copy[..., i], midtone_center, m, midtone_max) + img_copy[..., i] = adjust(img_copy[..., i], highlight_center, h, highlight_max) + + # If preserve_luminosity is True, adjust the RGB values to match the original luminance + if preserve_luminosity: + current_luminance = 0.2126 * img_copy[..., 0] + 0.7152 * img_copy[..., 1] + 0.0722 * img_copy[..., 2] + img_copy *= (original_luminance / current_luminance).unsqueeze(-1) + + return tensor2pil(img_copy) + +def RGB_to_Hex(RGB:tuple) -> str: + color = '#' + for i in RGB: + num = int(i) + color += str(hex(num))[-2:].replace('x', '0').upper() + return color + +def Hex_to_RGB(inhex:str) -> tuple: + if not inhex.startswith('#'): + raise ValueError(f'Invalid Hex Code in {inhex}') + else: + rval = inhex[1:3] + gval = inhex[3:5] + bval = inhex[5:] + rgb = (int(rval, 16), int(gval, 16), int(bval, 16)) + return tuple(rgb) + +def RGB_to_HSV(RGB:tuple) -> list: + HSV = rgb_to_hsv(RGB[0] / 255.0, RGB[1] / 255.0, RGB[2] / 255.0) + return [int(x * 360) for x in HSV] + +def Hex_to_HSV_255level(inhex:str) -> list: + if not inhex.startswith('#'): + raise ValueError(f'Invalid Hex Code in {inhex}') + else: + rval = inhex[1:3] + gval = inhex[3:5] + bval = inhex[5:] + RGB = (int(rval, 16), int(gval, 16), int(bval, 16)) + HSV = rgb_to_hsv(RGB[0] / 255.0, RGB[1] / 255.0, RGB[2] / 255.0) + return [int(x * 255) for x in HSV] + +def HSV_255level_to_Hex(HSV: list) -> str: + if len(HSV) != 3 or any((not isinstance(v, int) or v < 0 or v > 255) for v in HSV): + raise ValueError('Invalid HSV values, each value should be an integer between 0 and 255') + + H, S, V = HSV + RGB = tuple(int(x * 255) for x in hsv_to_rgb(H / 255.0, S / 255.0, V / 255.0)) + + # Convert RGB values to hexadecimal format + hex_r = format(RGB[0], '02x') + hex_g = format(RGB[1], '02x') + hex_b = format(RGB[2], '02x') + + return '#' + hex_r + hex_g + hex_b + +# 返回补色色值 +def complementary_color(color: str) -> str: + color = Hex_to_RGB(color) + return RGB_to_Hex((255 - color[0], 255 - color[1], 255 - color[2])) + +# 返回颜色对应灰度值 +def rgb2gray(color:str)->int: + (r, g, b) = Hex_to_RGB(color) + return int((r * 299 + g * 587 + b * 114) / 1000) + +'''Value Functions''' +def is_valid_mask(tensor:torch.Tensor) -> bool: + return not bool(torch.all(tensor == 0).item()) + +def step_value(start_value, end_value, total_step, step) -> float: # 按当前步数在总步数中的位置返回比例值 + factor = step / total_step + return (end_value - start_value) * factor + start_value + +def step_color(start_color_inhex:str, end_color_inhex:str, total_step:int, step:int) -> str: # 按当前步数在总步数中的位置返回比例颜色 + start_color = tuple(Hex_to_RGB(start_color_inhex)) + end_color = tuple(Hex_to_RGB(end_color_inhex)) + start_R, start_G, start_B = start_color[0], start_color[1], start_color[2] + end_R, end_G, end_B = end_color[0], end_color[1], end_color[2] + ret_color = (int(step_value(start_R, end_R, total_step, step)), + int(step_value(start_G, end_G, total_step, step)), + int(step_value(start_B, end_B, total_step, step)), + ) + return RGB_to_Hex(ret_color) + +def has_letters(string:str) -> bool: + pattern = r'[a-zA-Z]' + match = re.search(pattern, string) + if match: + return True + else: + return False + + +def replace_case(old:str, new:str, text:str) -> str: + index = text.lower().find(old.lower()) + if index == -1: + return text + return replace_case(old, new, text[:index] + new + text[index + len(old):]) + +def random_numbers(total:int, random_range:int, seed:int=0, sum_of_numbers:int=0) -> list: + random.seed(seed) + numbers = [random.randint(-random_range//2, random_range//2) for _ in range(total - 1)] + avg = sum(numbers) // total + ret_list = [] + for i in numbers: + ret_list.append(i - avg) + ret_list.append((sum_of_numbers - sum(ret_list)) // 2) + return ret_list + +# 四舍五入取整数倍 +def num_round_to_multiple(number:int, multiple:int) -> int: + remainder = number % multiple + if remainder == 0 : + return number + else: + factor = int(number / multiple) + if number - factor * multiple > multiple / 2: + factor += 1 + return factor * multiple + +# 向上取整数倍 +def num_round_up_to_multiple(number: int, multiple: int) -> int: + remainder = number % multiple + if remainder == 0: + return number + else: + factor = (number + multiple - 1) // multiple # 向上取整的计算方式 + return factor * multiple + +def calculate_side_by_ratio(orig_width:int, orig_height:int, ratio:float, longest_side:int=0) -> int: + + if orig_width > orig_height: + if longest_side: + target_width = longest_side + else: + target_width = orig_width + target_height = int(target_width / ratio) + else: + if longest_side: + target_height = longest_side + else: + target_height = orig_height + target_width = int(target_height * ratio) + + if ratio < 1: + if longest_side: + _r = longest_side / target_height + target_height = longest_side + else: + _r = orig_height / target_height + target_height = orig_height + target_width = int(target_width * _r) + + return target_width, target_height + +def generate_random_name(prefix:str, suffix:str, length:int) -> str: + name = ''.join(random.choice("abcdefghijklmnopqrstupvxyz1234567890") for x in range(length)) + return prefix + name + suffix + +def check_image_file(file_name:str, interval:int) -> object: + while True: + if os.path.isfile(file_name): + try: + image = Image.open(file_name) + ret_image = copy.deepcopy(image) + image.close() + return ret_image + except Exception as e: + log(e) + return None + break + time.sleep(interval / 1000) + +# 判断字符串是否包含中文 +def is_contain_chinese(check_str:str) -> bool: + for ch in check_str: + if u'\u4e00' <= ch <= u'\u9fff': + return True + return False + +# 生成随机颜色 +def generate_random_color(): + """ + Generate a random color in hexadecimal format. + """ + # random.seed(int(time.time())) + return "#{:06x}".format(random.randint(0x101010, 0xFFFFFF)) + +# 提取字符串中的int数为列表 +def extract_numbers(string): + return [int(s) for s in re.findall(r'\d+', string)] + +# 提取字符串中的数值, 返回为列表 +def extract_all_numbers_from_str(string, checkint:bool=False): + # 定义浮点数的正则表达式模式 + number_pattern = r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?' + # 使用re.findall找到所有匹配的字符串 + matches = re.findall(number_pattern, string) + # 转换为浮点数 + numbers = [float(match) for match in matches] + number_list = [] + # 如果需要检查是否为整数,则将浮点数转换为整数 + if checkint: + for num in numbers: + int_num = int(num) + if math.isclose(num, int_num, rel_tol=1e-19): + number_list.append(int_num) + else: + number_list.append(num) + else: + number_list = numbers + + return number_list + + + +# 提取字符串中用"," ";" " "分开的字符串, 返回为列表 +def extract_substr_from_str(string) -> list: + return re.split(r'[,\s;,;]+', string) + +def clear_memory(): + import gc + # Cleanup + gc.collect() + if torch.cuda.is_available(): + torch.cuda.empty_cache() + torch.cuda.ipc_collect() + +def tensor_info(tensor:object) -> str: + value = '' + if isinstance(tensor, torch.Tensor): + value += f"\n Input dim = {tensor.dim()}, shape[0] = {tensor.shape[0]} \n" + for i in range(tensor.shape[0]): + t = tensor[i] + image = tensor2pil(t) + value += f'\n index {i}: Image.size = {image.size}, Image.mode = {image.mode}, dim = {t.dim()}, ' + for j in range(t.dim()): + value += f'shape[{j}] = {t.shape[j]}, ' + else: + value = f"tensor_info: Not tensor, type is {type(tensor)}" + return value + +# 去除空行 +def remove_empty_lines(text): + lines = text.split('\n') + non_empty_lines = [line for line in lines if line.strip() != ''] + return '\n'.join(non_empty_lines) + +# 去除重复的句子 +def remove_duplicate_string(text:str) -> str: + sentences = re.split(r'(?<=[:;,.!?])\s+', text) + unique_sentences = [] + seen = set() + for sentence in sentences: + if sentence not in seen: + seen.add(sentence) + unique_sentences.append(sentence) + return ' '.join(unique_sentences) + +files_for_uform_gen2_qwen = Path(os.path.join(folder_paths.models_dir, "LLavacheckpoints", "files_for_uform_gen2_qwen")) +class StopOnTokens(StoppingCriteria): + def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool: + stop_ids = [151645] # Define stop tokens as per your model's specifics + for stop_id in stop_ids: + if input_ids[0][-1] == stop_id: + return True + return False + +class UformGen2QwenChat: + + def __init__(self): + from huggingface_hub import snapshot_download + # self.model_path = snapshot_download("unum-cloud/uform-gen2-qwen-500m", + # local_dir=files_for_uform_gen2_qwen, + # force_download=False, # Set to True if you always want to download, regardless of local copy + # local_files_only=False, # Set to False to allow downloading if not available locally + # local_dir_use_symlinks="auto") # or set to True/False based on your symlink preference + self.model_path = files_for_uform_gen2_qwen + self.device = "cuda" if torch.cuda.is_available() else "cpu" + self.model = AutoModel.from_pretrained(self.model_path, trust_remote_code=True).to(self.device) + self.processor = AutoProcessor.from_pretrained(self.model_path, trust_remote_code=True) + + def chat_response(self, message, history, image_path): + stop = StopOnTokens() + messages = [{"role": "system", "content": "You are a helpful Assistant."}] + + for user_msg, assistant_msg in history: + messages.append({"role": "user", "content": user_msg}) + messages.append({"role": "assistant", "content": assistant_msg}) + + if len(messages) == 1: + message = f" {message}" + + messages.append({"role": "user", "content": message}) + + model_inputs = self.processor.tokenizer.apply_chat_template( + messages, + add_generation_prompt=True, + return_tensors="pt" + ) + + image = Image.open(image_path) # Load image using PIL + image_tensor = ( + self.processor.feature_extractor(image) + .unsqueeze(0) + ) + + attention_mask = torch.ones( + 1, model_inputs.shape[1] + self.processor.num_image_latents - 1 + ) + + model_inputs = { + "input_ids": model_inputs, + "images": image_tensor, + "attention_mask": attention_mask + } + + model_inputs = {k: v.to(self.device) for k, v in model_inputs.items()} + + with torch.inference_mode(): + output = self.model.generate( + **model_inputs, + max_new_tokens=512, + do_sample=True, + temperature=0.3, + repetition_penalty=1.2, + stopping_criteria=StoppingCriteriaList([stop]) + ) + + response_text = self.processor.tokenizer.decode(output[0], skip_special_tokens=True) + response_text = remove_duplicate_string(response_text) + return response_text + +'''CLASS''' + +class AnyType(str): + """A special class that is always equal in not equal comparisons. Credit to pythongosssss""" + def __eq__(self, __value: object) -> bool: + return True + def __ne__(self, __value: object) -> bool: + return False + + + +'''Load File''' + +def download_hg_model(model_id:str,exDir:str='') -> str: + # 下载本地 + model_checkpoint = os.path.join(folder_paths.models_dir, exDir, os.path.basename(model_id)) + if not os.path.exists(model_checkpoint): + from huggingface_hub import snapshot_download + snapshot_download(repo_id=model_id, local_dir=model_checkpoint, local_dir_use_symlinks=False) + return model_checkpoint + + +def get_files(model_path: str, file_ext_list:list) -> dict: + file_list = [] + for ext in file_ext_list: + file_list.extend(glob.glob(os.path.join(model_path, '*' + ext))) + files_dict = {} + for i in range(len(file_list)): + _, filename = os.path.split(file_list[i]) + files_dict[filename] = file_list[i] + return files_dict + +# def load_inference_prompt() -> str: +# inference_prompt_file = os.path.join(os.path.dirname(os.path.dirname(os.path.normpath(__file__))), "resource", +# "inference.prompt") +# ret_value = '' +# try: +# with open(inference_prompt_file, 'r') as f: +# ret_value = f.readlines() +# except Exception as e: +# log(f'Warning: {inference_prompt_file} ' + repr(e) + f", check it to be correct. ", message_type='warning') +# return ''.join(ret_value) + +def load_custom_size() -> list: + custom_size_file = os.path.join(os.path.dirname(os.path.dirname(os.path.normpath(__file__))), "custom_size.ini") + ret_value = ['1024 x 1024', + '768 x 512', + '512 x 768', + '1280 x 720', + '720 x 1280', + '1344 x 768', + '768 x 1344', + '1536 x 640', + '640 x 1536' + ] + try: + with open(custom_size_file, 'r') as f: + ini = f.readlines() + for line in ini: + if not line.startswith(f'#'): + ret_value.append(line.strip()) + except Exception as e: + pass + # log(f'Warning: {custom_size_file} not found' + f", use default size. ") + return ret_value + +def get_api_key(api_name:str) -> str: + api_key_ini_file = os.path.join(os.path.dirname(os.path.dirname(os.path.normpath(__file__))), "api_key.ini") + ret_value = '' + try: + with open(api_key_ini_file, 'r') as f: + ini = f.readlines() + for line in ini: + if line.startswith(f'{api_name}='): + ret_value = line[line.find('=') + 1:].rstrip().lstrip() + break + except Exception as e: + log(f'Warning: {api_key_ini_file} ' + repr(e) + f", check it to be correct. ", message_type='warning') + remove_char = ['"', "'", '“', '”', '‘', '’'] + for i in remove_char: + if i in ret_value: + ret_value = ret_value.replace(i, '') + if len(ret_value) < 4: + log(f'Warning: Invalid API-key, Check the key in {api_key_ini_file}.', message_type='warning') + return ret_value + +# 判断文件名后缀是否包括在列表中(忽略大小写) +def file_is_extension(filename:str, ext_list:tuple) -> bool: + # 获取文件的真实后缀(包括点) + true_ext = os.path.splitext(filename)[1] + if true_ext.lower() in ext_list: + return True + return False + +# 遍历目录下包括子目录指定后缀文件,返回字典 +def collect_files(root_dir:str, suffixes:tuple, default_dir:str=""): + result = {} + for dirpath, _, filenames in os.walk(root_dir): + for file in filenames: + if file_is_extension(file, suffixes): + # 获取文件的完整路径作为 value + full_path = os.path.join(dirpath, file) + # 如果是default_dir 则去掉路径,使用文件名作为 key + if dirpath == default_dir: + relative_path = os.path.relpath(full_path, root_dir) + result.update({relative_path: full_path}) + else: + result.update({full_path: full_path}) + return result + + +def get_resource_dir() -> list: + default_lut_dir = [] + default_lut_dir.append(os.path.join(os.path.dirname(os.path.dirname(os.path.normpath(__file__))), 'lut')) + default_font_dir = [] + default_font_dir.append(os.path.join(os.path.dirname(os.path.dirname(os.path.normpath(__file__))), 'font')) + resource_dir_ini_file = os.path.join(os.path.dirname(os.path.dirname(os.path.normpath(__file__))), + "resource_dir.ini") + try: + with open(resource_dir_ini_file, 'r') as f: + ini = f.readlines() + for line in ini: + if line.startswith('LUT_dir='): + _ldir = line[line.find('=') + 1:].rstrip().lstrip() + for dir in extract_substr_from_str(_ldir) : + if os.path.exists(dir): + default_lut_dir.append(dir) + elif line.startswith('FONT_dir='): + _fdir = line[line.find('=') + 1:].rstrip().lstrip() + for dir in extract_substr_from_str(_fdir): + if os.path.exists(dir): + default_font_dir.append(dir) + except Exception as e: + pass + # log(f'Warning: {resource_dir_ini_file} not found' + f", default directory to be used. ") + + + LUT_DICT = {} + for dir in default_lut_dir: + LUT_DICT.update(collect_files(root_dir=dir, suffixes= ('.cube'), default_dir=default_lut_dir[0] )) # 后缀要小写 + LUT_LIST = list(LUT_DICT.keys()) + + FONT_DICT = {} + for dir in default_font_dir: + FONT_DICT.update(collect_files(root_dir=dir, suffixes=('.ttf', '.otf'), default_dir=default_font_dir[0])) # 后缀要小写 + FONT_LIST = list(FONT_DICT.keys()) + + return (LUT_DICT, FONT_DICT) + +# (LUT_DICT, FONT_DICT) = get_resource_dir() +# FONT_LIST = list(FONT_DICT.keys()) +# LUT_LIST = list(LUT_DICT.keys()) + +# def get_models_dir() -> dict: +# models_dir_ini_file = os.path.join(os.path.dirname(os.path.dirname(os.path.normpath(__file__))), "models_dir.ini") +# MODELS_DIR = {} +# model_dir_list = [ +# "birefnet_dir", +# "evf-sam_dir", +# "florence2_dir", +# "lama_dir", +# "rmbg_dir", +# "segformerB2_dir", +# "segformerB3_clothes_dir", +# "segformerB3_fashion_dir", +# "sam2_dir", +# "transparent-background_dir", +# "yolo8_dir", +# "yolo_world_dir" +# ] +# try: +# with open(models_dir_ini_file, 'r') as f: +# ini = f.readlines() +# for line in ini: +# for model_dir in model_dir_list: +# if line.startswith(model_dir): +# path = line[line.find('=') + 1:].rstrip().lstrip() +# if os.path.exists(path): +# MODELS_DIR[model_dir] = path +# log(f'Find {len(MODELS_DIR)} path(s) in {models_dir_ini_file}.') +# except Exception as e: +# log(f'Warning: {models_dir_ini_file} not found' + f', default directory to be used.') +# +# return MODELS_DIR +# +# MODELS_DIR = get_models_dir() + +def draw_bounding_boxes(image: Image, bboxes: list, color: str = "#FF0000", line_width: int = 5) -> Image: + """ + Draw bounding boxes on the image using the coordinates provided in the bboxes dictionary. + """ + + (_, FONT_DICT) = get_resource_dir() + + font_size = 25 + font = ImageFont.truetype(list(FONT_DICT.items())[0][1], font_size) + + if len(bboxes) > 0: + draw = ImageDraw.Draw(image) + width, height = image.size + if line_width < 0: # auto line width + line_width = (image.width + image.height) // 1000 + + for index, box in enumerate(bboxes): + random_color = generate_random_color() + if color != "random": + random_color = color + xmin = min(box[0], box[2]) + xmax = max(box[0], box[2]) + ymin = min(box[1], box[3]) + ymax = max(box[1], box[3]) + draw.rectangle([xmin, ymin, xmax, ymax], outline=random_color, width=line_width) + draw.text((xmin, ymin - font_size*1.2), str(index), font=font, fill=random_color) + + return image + +def draw_bbox(image: Image, bbox: tuple, color: str = "#FF0000", line_width: int = 5, title: str = "", font_size: int = 10) -> Image: + """ + Draw bounding boxes on the image using the coordinates provided in the bboxes dictionary. + """ + + (_, FONT_DICT) = get_resource_dir() + + font = ImageFont.truetype(list(FONT_DICT.items())[0][1], font_size) + + draw = ImageDraw.Draw(image) + width, height = image.size + if line_width < 0: # auto line width + line_width = (image.width + image.height) // 1000 + + random_color = generate_random_color() + if color != "random": + random_color = color + xmin = min(bbox[0], bbox[2]) + xmax = max(bbox[0], bbox[2]) + ymin = min(bbox[1], bbox[3]) + ymax = max(bbox[1], bbox[3]) + draw.rectangle([xmin, ymin, xmax, ymax], outline=random_color, width=line_width) + if title != "": + draw.text((xmin, ymin - font_size*1.2), title, font=font, fill=random_color) + + return image + + + +'''Constant''' + +chop_mode = [ + 'normal', + 'multply', + 'screen', + 'add', + 'subtract', + 'difference', + 'darker', + 'lighter', + 'color_burn', + 'color_dodge', + 'linear_burn', + 'linear_dodge', + 'overlay', + 'soft_light', + 'hard_light', + 'vivid_light', + 'pin_light', + 'linear_light', + 'hard_mix' + ] + +# Blend Mode from Virtuoso Pack https://github.com/chrisfreilich/virtuoso-nodes +chop_mode_v2 = list(BLEND_MODES.keys()) + +gemini_generate_config = { + "temperature": 0, + "top_p": 1, + "top_k": 1, + "max_output_tokens": 400 +} + +gemini_safety_settings = [ + { + "category": "HARM_CATEGORY_HARASSMENT", + "threshold": "BLOCK_NONE" + }, + { + "category": "HARM_CATEGORY_HATE_SPEECH", + "threshold": "BLOCK_NONE" + }, + { + "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT", + "threshold": "BLOCK_NONE" + }, + { + "category": "HARM_CATEGORY_DANGEROUS_CONTENT", + "threshold": "BLOCK_NONE" + } +] + +minicpm_llama3_v25_prompts = """ + # MISSION + You are an imagine generator for a slide deck tool. You will be given the text or description of a slide and you'll generate a few image descriptions that will be fed to an AI image generator. It will need to have a particular format (seen below). You will also be given some examples below. Think metaphorically and symbolically. + + # FORMAT + The format should follow this general pattern: + +
, , , , , + + It's not strictly required, as you'll see below, you can pick and choose various aspects, but this is the general order of operations + + # EXAMPLES + + a Shakespeare stage play, yellow mist, atmospheric, set design by Michel Crête, Aerial acrobatics design by André Simard, hyperrealistic, 4K, Octane render, unreal engine + + The Moon Knight dissolving into swirling sand, volumetric dust, cinematic lighting, close up portrait + + ethereal Bohemian Waxwing bird, Bombycilla garrulus :: intricate details, ornate, detailed illustration, octane render :: Johanna Rupprecht style, William Morris style :: trending on artstation + + steampunk cat, octane render, hyper realistic + + Hyper detailed movie still that fuses the iconic tea party scene from Alice in Wonderland showing the hatter and an adult alice. a wooden table is filled with teacups and cannabis plants. The scene is surrounded by flying weed. Some playcards flying around in the air. Captured with a Hasselblad medium format camera + + venice in a carnival picture 3, in the style of fantastical compositions, colorful, eye-catching compositions, symmetrical arrangements, navy and aquamarine, distinctive noses, gothic references, spiral group –style expressive + + Beautiful and terrifying Egyptian mummy, flirting and vamping with the viewer, rotting and decaying climbing out of a sarcophagus lunging at the viewer, symmetrical full body Portrait photo, elegant, highly detailed, soft ambient lighting, rule of thirds, professional photo HD Photography, film, sony, portray, kodak Polaroid 3200dpi scan medium format film Portra 800, vibrantly colored portrait photo by Joel – Peter Witkin + Diane Arbus + Rhiannon + Mike Tang, fashion shoot + + A grandmotherly Fate sits on a cozy cosmic throne knitting with mirrored threads of time, the solar system spins like clockwork behind her as she knits the futures of people together like an endless collage of destiny, maximilism, cinematic quality, sharp – focus, intricate details + + A cloud with several airplanes flying around on top, in the style of detailed fantasy art, nightcore, quiet moments captured in paint, radiant clusters, i cant believe how beautiful this is, detailed character design, dark cyan and light crimson + + An incredibly detailed close up macro beauty photo of an Asian model, hands holding a bouquet of pink roses, surrounded by scary crows from hell. Shot on a Hasselblad medium format camera with a 100mm lens. Unmistakable to a photograph. Cinematic lighting. Photographed by Tim Walker, trending on 500px + + Game-Art | An island with different geographical properties and multiple small cities floating in space ::10 Island | Floating island in space – waterfalls over the edge of the island falling into space – island fragments floating around the edge of the island, Mountain Ranges – Deserts – Snowy Landscapes – Small Villages – one larger city ::8 Environment | Galaxy – in deep space – other universes can be seen in the distance ::2 Style | Unreal Engine 5 – 8K UHD – Highly Detailed – Game-Art + + a warrior sitting on a giant creature and riding it in the water, with wings spread wide in the water, camera positioned just above the water to capture this beautiful scene, surface showing intricate details of the creature’s scales, fins, and wings, majesty, Hero rides on the creature in the water, digitally enhanced, enhanced graphics, straight, sharp focus, bright lighting, closeup, cinematic, Bronze, Azure, blue, ultra highly detailed, 18k, sharp focus, bright photo with rich colors, full coverage of a scene, straight view shot + + A real photographic landscape painting with incomparable reality,Super wide,Ominous sky,Sailing boat,Wooden boat,Lotus,Huge waves,Starry night,Harry potter,Volumetric lighting,Clearing,Realistic,James gurney,artstation + + Tiger monster with monstera plant over him, back alley in Bangkok, art by Otomo Katsuhiro crossover Yayoi Kusama and Hayao Miyazaki + + An elderly Italian woman with wrinkles, sitting in a local cafe filled with plants and wood decorations, looking out the window, wearing a white top with light purple linen blazer, natural afternoon light shining through the window + + # OUTPUT + Your output should just be an plain list of descriptions. No numbers, no extraneous labels, no hyphens. + Create only one prompt. + """ diff --git a/py/iopaint/__init__.py b/py/iopaint/__init__.py new file mode 100644 index 0000000..852736e --- /dev/null +++ b/py/iopaint/__init__.py @@ -0,0 +1,23 @@ +import os + +os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1" +# https://github.com/pytorch/pytorch/issues/27971#issuecomment-1768868068 +os.environ["ONEDNN_PRIMITIVE_CACHE_CAPACITY"] = "1" +os.environ["LRU_CACHE_CAPACITY"] = "1" +# prevent CPU memory leak when run model on GPU +# https://github.com/pytorch/pytorch/issues/98688#issuecomment-1869288431 +# https://github.com/pytorch/pytorch/issues/108334#issuecomment-1752763633 +os.environ["TORCH_CUDNN_V8_API_LRU_CACHE_LIMIT"] = "1" + + +import warnings + +warnings.simplefilter("ignore", UserWarning) + + +def entry_point(): + # To make os.environ["XDG_CACHE_HOME"] = args.model_cache_dir works for diffusers + # https://github.com/huggingface/diffusers/blob/be99201a567c1ccd841dc16fb24e88f7f239c187/src/diffusers/utils/constants.py#L18 + from .cli import typer_app + + typer_app() diff --git a/py/iopaint/__main__.py b/py/iopaint/__main__.py new file mode 100644 index 0000000..73b4ed7 --- /dev/null +++ b/py/iopaint/__main__.py @@ -0,0 +1,4 @@ +from . import entry_point + +if __name__ == "__main__": + entry_point() diff --git a/py/iopaint/api.py b/py/iopaint/api.py new file mode 100644 index 0000000..d98574f --- /dev/null +++ b/py/iopaint/api.py @@ -0,0 +1,397 @@ +import asyncio +import os +import threading +import time +import traceback +from pathlib import Path +from typing import Optional, Dict, List + +import cv2 +import numpy as np +import socketio +import torch + +try: + torch._C._jit_override_can_fuse_on_cpu(False) + torch._C._jit_override_can_fuse_on_gpu(False) + torch._C._jit_set_texpr_fuser_enabled(False) + torch._C._jit_set_nvfuser_enabled(False) +except: + pass + + +import uvicorn +from PIL import Image +from fastapi import APIRouter, FastAPI, Request, UploadFile +from fastapi.encoders import jsonable_encoder +from fastapi.exceptions import HTTPException +from fastapi.middleware.cors import CORSMiddleware +from fastapi.responses import JSONResponse, FileResponse, Response +from fastapi.staticfiles import StaticFiles +from loguru import logger +from socketio import AsyncServer + +from .file_manager import FileManager +from .helper import ( + load_img, + decode_base64_to_image, + pil_to_bytes, + numpy_to_bytes, + concat_alpha_channel, + gen_frontend_mask, + adjust_mask, +) +from .model.utils import torch_gc +from .model_manager import ModelManager +from .plugins import build_plugins, RealESRGANUpscaler, InteractiveSeg +from .plugins.base_plugin import BasePlugin +from .plugins.remove_bg import RemoveBG +from .schema import ( + GenInfoResponse, + ApiConfig, + ServerConfigResponse, + SwitchModelRequest, + InpaintRequest, + RunPluginRequest, + SDSampler, + PluginInfo, + AdjustMaskRequest, + RemoveBGModel, + SwitchPluginModelRequest, + ModelInfo, + InteractiveSegModel, + RealESRGANModel, +) + +CURRENT_DIR = Path(__file__).parent.absolute().resolve() +WEB_APP_DIR = CURRENT_DIR / "web_app" + + +def api_middleware(app: FastAPI): + rich_available = False + try: + if os.environ.get("WEBUI_RICH_EXCEPTIONS", None) is not None: + import anyio # importing just so it can be placed on silent list + import starlette # importing just so it can be placed on silent list + from rich.console import Console + + console = Console() + rich_available = True + except Exception: + pass + + def handle_exception(request: Request, e: Exception): + err = { + "error": type(e).__name__, + "detail": vars(e).get("detail", ""), + "body": vars(e).get("body", ""), + "errors": str(e), + } + if not isinstance( + e, HTTPException + ): # do not print backtrace on known httpexceptions + message = f"API error: {request.method}: {request.url} {err}" + if rich_available: + print(message) + console.print_exception( + show_locals=True, + max_frames=2, + extra_lines=1, + suppress=[anyio, starlette], + word_wrap=False, + width=min([console.width, 200]), + ) + else: + traceback.print_exc() + return JSONResponse( + status_code=vars(e).get("status_code", 500), content=jsonable_encoder(err) + ) + + @app.middleware("http") + async def exception_handling(request: Request, call_next): + try: + return await call_next(request) + except Exception as e: + return handle_exception(request, e) + + @app.exception_handler(Exception) + async def fastapi_exception_handler(request: Request, e: Exception): + return handle_exception(request, e) + + @app.exception_handler(HTTPException) + async def http_exception_handler(request: Request, e: HTTPException): + return handle_exception(request, e) + + cors_options = { + "allow_methods": ["*"], + "allow_headers": ["*"], + "allow_origins": ["*"], + "allow_credentials": True, + "expose_headers": ["X-Seed"] + } + app.add_middleware(CORSMiddleware, **cors_options) + + +global_sio: AsyncServer = None + + +def diffuser_callback(pipe, step: int, timestep: int, callback_kwargs: Dict = {}): + # self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict + # logger.info(f"diffusion callback: step={step}, timestep={timestep}") + + # We use asyncio loos for task processing. Perhaps in the future, we can add a processing queue similar to InvokeAI, + # but for now let's just start a separate event loop. It shouldn't make a difference for single person use + asyncio.run(global_sio.emit("diffusion_progress", {"step": step})) + return {} + + +class Api: + def __init__(self, app: FastAPI, config: ApiConfig): + self.app = app + self.config = config + self.router = APIRouter() + self.queue_lock = threading.Lock() + api_middleware(self.app) + + self.file_manager = self._build_file_manager() + self.plugins = self._build_plugins() + self.model_manager = self._build_model_manager() + + # fmt: off + self.add_api_route("/api/v1/gen-info", self.api_geninfo, methods=["POST"], response_model=GenInfoResponse) + self.add_api_route("/api/v1/server-config", self.api_server_config, methods=["GET"], response_model=ServerConfigResponse) + self.add_api_route("/api/v1/model", self.api_current_model, methods=["GET"], response_model=ModelInfo) + self.add_api_route("/api/v1/model", self.api_switch_model, methods=["POST"], response_model=ModelInfo) + self.add_api_route("/api/v1/inputimage", self.api_input_image, methods=["GET"]) + self.add_api_route("/api/v1/inpaint", self.api_inpaint, methods=["POST"]) + self.add_api_route("/api/v1/switch_plugin_model", self.api_switch_plugin_model, methods=["POST"]) + self.add_api_route("/api/v1/run_plugin_gen_mask", self.api_run_plugin_gen_mask, methods=["POST"]) + self.add_api_route("/api/v1/run_plugin_gen_image", self.api_run_plugin_gen_image, methods=["POST"]) + self.add_api_route("/api/v1/samplers", self.api_samplers, methods=["GET"]) + self.add_api_route("/api/v1/adjust_mask", self.api_adjust_mask, methods=["POST"]) + self.add_api_route("/api/v1/save_image", self.api_save_image, methods=["POST"]) + self.app.mount("/", StaticFiles(directory=WEB_APP_DIR, html=True), name="assets") + # fmt: on + + global global_sio + self.sio = socketio.AsyncServer(async_mode="asgi", cors_allowed_origins="*") + self.combined_asgi_app = socketio.ASGIApp(self.sio, self.app) + self.app.mount("/ws", self.combined_asgi_app) + global_sio = self.sio + + def add_api_route(self, path: str, endpoint, **kwargs): + return self.app.add_api_route(path, endpoint, **kwargs) + + def api_save_image(self, file: UploadFile): + filename = file.filename + origin_image_bytes = file.file.read() + with open(self.config.output_dir / filename, "wb") as fw: + fw.write(origin_image_bytes) + + def api_current_model(self) -> ModelInfo: + return self.model_manager.current_model + + def api_switch_model(self, req: SwitchModelRequest) -> ModelInfo: + if req.name == self.model_manager.name: + return self.model_manager.current_model + self.model_manager.switch(req.name) + return self.model_manager.current_model + + def api_switch_plugin_model(self, req: SwitchPluginModelRequest): + if req.plugin_name in self.plugins: + self.plugins[req.plugin_name].switch_model(req.model_name) + if req.plugin_name == RemoveBG.name: + self.config.remove_bg_model = req.model_name + if req.plugin_name == RealESRGANUpscaler.name: + self.config.realesrgan_model = req.model_name + if req.plugin_name == InteractiveSeg.name: + self.config.interactive_seg_model = req.model_name + torch_gc() + + def api_server_config(self) -> ServerConfigResponse: + plugins = [] + for it in self.plugins.values(): + plugins.append( + PluginInfo( + name=it.name, + support_gen_image=it.support_gen_image, + support_gen_mask=it.support_gen_mask, + ) + ) + + return ServerConfigResponse( + plugins=plugins, + modelInfos=self.model_manager.scan_models(), + removeBGModel=self.config.remove_bg_model, + removeBGModels=RemoveBGModel.values(), + realesrganModel=self.config.realesrgan_model, + realesrganModels=RealESRGANModel.values(), + interactiveSegModel=self.config.interactive_seg_model, + interactiveSegModels=InteractiveSegModel.values(), + enableFileManager=self.file_manager is not None, + enableAutoSaving=self.config.output_dir is not None, + enableControlnet=self.model_manager.enable_controlnet, + controlnetMethod=self.model_manager.controlnet_method, + disableModelSwitch=False, + isDesktop=False, + samplers=self.api_samplers(), + ) + + def api_input_image(self) -> FileResponse: + if self.config.input and self.config.input.is_file(): + return FileResponse(self.config.input) + raise HTTPException(status_code=404, detail="Input image not found") + + def api_geninfo(self, file: UploadFile) -> GenInfoResponse: + _, _, info = load_img(file.file.read(), return_info=True) + parts = info.get("parameters", "").split("Negative prompt: ") + prompt = parts[0].strip() + negative_prompt = "" + if len(parts) > 1: + negative_prompt = parts[1].split("\n")[0].strip() + return GenInfoResponse(prompt=prompt, negative_prompt=negative_prompt) + + def api_inpaint(self, req: InpaintRequest): + image, alpha_channel, infos = decode_base64_to_image(req.image) + mask, _, _ = decode_base64_to_image(req.mask, gray=True) + + mask = cv2.threshold(mask, 127, 255, cv2.THRESH_BINARY)[1] + if image.shape[:2] != mask.shape[:2]: + raise HTTPException( + 400, + detail=f"Image size({image.shape[:2]}) and mask size({mask.shape[:2]}) not match.", + ) + + if req.paint_by_example_example_image: + paint_by_example_image, _, _ = decode_base64_to_image( + req.paint_by_example_example_image + ) + + start = time.time() + rgb_np_img = self.model_manager(image, mask, req) + logger.info(f"process time: {(time.time() - start) * 1000:.2f}ms") + torch_gc() + + rgb_np_img = cv2.cvtColor(rgb_np_img.astype(np.uint8), cv2.COLOR_BGR2RGB) + rgb_res = concat_alpha_channel(rgb_np_img, alpha_channel) + + ext = "png" + res_img_bytes = pil_to_bytes( + Image.fromarray(rgb_res), + ext=ext, + quality=self.config.quality, + infos=infos, + ) + + asyncio.run(self.sio.emit("diffusion_finish")) + + return Response( + content=res_img_bytes, + media_type=f"image/{ext}", + headers={"X-Seed": str(req.sd_seed)}, + ) + + def api_run_plugin_gen_image(self, req: RunPluginRequest): + ext = "png" + if req.name not in self.plugins: + raise HTTPException(status_code=422, detail="Plugin not found") + if not self.plugins[req.name].support_gen_image: + raise HTTPException( + status_code=422, detail="Plugin does not support output image" + ) + rgb_np_img, alpha_channel, infos = decode_base64_to_image(req.image) + bgr_or_rgba_np_img = self.plugins[req.name].gen_image(rgb_np_img, req) + torch_gc() + + if bgr_or_rgba_np_img.shape[2] == 4: + rgba_np_img = bgr_or_rgba_np_img + else: + rgba_np_img = cv2.cvtColor(bgr_or_rgba_np_img, cv2.COLOR_BGR2RGB) + rgba_np_img = concat_alpha_channel(rgba_np_img, alpha_channel) + + return Response( + content=pil_to_bytes( + Image.fromarray(rgba_np_img), + ext=ext, + quality=self.config.quality, + infos=infos, + ), + media_type=f"image/{ext}", + ) + + def api_run_plugin_gen_mask(self, req: RunPluginRequest): + if req.name not in self.plugins: + raise HTTPException(status_code=422, detail="Plugin not found") + if not self.plugins[req.name].support_gen_mask: + raise HTTPException( + status_code=422, detail="Plugin does not support output image" + ) + rgb_np_img, alpha_channel, infos = decode_base64_to_image(req.image) + bgr_or_gray_mask = self.plugins[req.name].gen_mask(rgb_np_img, req) + torch_gc() + res_mask = gen_frontend_mask(bgr_or_gray_mask) + return Response( + content=numpy_to_bytes(res_mask, "png"), + media_type="image/png", + ) + + def api_samplers(self) -> List[str]: + return [member.value for member in SDSampler.__members__.values()] + + def api_adjust_mask(self, req: AdjustMaskRequest): + mask, _, _ = decode_base64_to_image(req.mask, gray=True) + mask = adjust_mask(mask, req.kernel_size, req.operate) + return Response(content=numpy_to_bytes(mask, "png"), media_type="image/png") + + def launch(self): + self.app.include_router(self.router) + uvicorn.run( + self.combined_asgi_app, + host=self.config.host, + port=self.config.port, + timeout_keep_alive=999999999, + ) + + def _build_file_manager(self) -> Optional[FileManager]: + if self.config.input and self.config.input.is_dir(): + logger.info( + f"Input is directory, initialize file manager {self.config.input}" + ) + + return FileManager( + app=self.app, + input_dir=self.config.input, + output_dir=self.config.output_dir, + ) + return None + + def _build_plugins(self) -> Dict[str, BasePlugin]: + return build_plugins( + self.config.enable_interactive_seg, + self.config.interactive_seg_model, + self.config.interactive_seg_device, + self.config.enable_remove_bg, + self.config.remove_bg_model, + self.config.enable_anime_seg, + self.config.enable_realesrgan, + self.config.realesrgan_device, + self.config.realesrgan_model, + self.config.enable_gfpgan, + self.config.gfpgan_device, + self.config.enable_restoreformer, + self.config.restoreformer_device, + self.config.no_half, + ) + + def _build_model_manager(self): + return ModelManager( + name=self.config.model, + device=torch.device(self.config.device), + no_half=self.config.no_half, + low_mem=self.config.low_mem, + disable_nsfw=self.config.disable_nsfw_checker, + sd_cpu_textencoder=self.config.cpu_textencoder, + local_files_only=self.config.local_files_only, + cpu_offload=self.config.cpu_offload, + callback=diffuser_callback, + ) diff --git a/py/iopaint/batch_processing.py b/py/iopaint/batch_processing.py new file mode 100644 index 0000000..607e5a4 --- /dev/null +++ b/py/iopaint/batch_processing.py @@ -0,0 +1,127 @@ +import json +from pathlib import Path +from typing import Dict, Optional + +import cv2 +import psutil +from PIL import Image +from loguru import logger +from rich.console import Console +from rich.progress import ( + Progress, + SpinnerColumn, + TimeElapsedColumn, + MofNCompleteColumn, + TextColumn, + BarColumn, + TaskProgressColumn, +) + +from .helper import pil_to_bytes +from .model.utils import torch_gc +from .model_manager import ModelManager +from .schema import InpaintRequest + + +def glob_images(path: Path) -> Dict[str, Path]: + # png/jpg/jpeg + if path.is_file(): + return {path.stem: path} + elif path.is_dir(): + res = {} + for it in path.glob("*.*"): + if it.suffix.lower() in [".png", ".jpg", ".jpeg"]: + res[it.stem] = it + return res + + +def batch_inpaint( + model: str, + device, + image: Path, + mask: Path, + output: Path, + config: Optional[Path] = None, + concat: bool = False, +): + if image.is_dir() and output.is_file(): + logger.error( + f"invalid --output: when image is a directory, output should be a directory" + ) + exit(-1) + output.mkdir(parents=True, exist_ok=True) + + image_paths = glob_images(image) + mask_paths = glob_images(mask) + if len(image_paths) == 0: + logger.error(f"invalid --image: empty image folder") + exit(-1) + if len(mask_paths) == 0: + logger.error(f"invalid --mask: empty mask folder") + exit(-1) + + if config is None: + inpaint_request = InpaintRequest() + # logger.info(f"Using default config: {inpaint_request}") + else: + with open(config, "r", encoding="utf-8") as f: + inpaint_request = InpaintRequest(**json.load(f)) + + model_manager = ModelManager(name=model, device=device) + first_mask = list(mask_paths.values())[0] + + console = Console() + + with Progress( + SpinnerColumn(), + TextColumn("[progress.description]{task.description}"), + BarColumn(), + TaskProgressColumn(), + MofNCompleteColumn(), + TimeElapsedColumn(), + console=console, + transient=False, + ) as progress: + task = progress.add_task("Batch processing...", total=len(image_paths)) + for stem, image_p in image_paths.items(): + if stem not in mask_paths and mask.is_dir(): + progress.log(f"mask for {image_p} not found") + progress.update(task, advance=1) + continue + mask_p = mask_paths.get(stem, first_mask) + + infos = Image.open(image_p).info + + img = cv2.imread(str(image_p)) + img = cv2.cvtColor(img, cv2.COLOR_BGRA2RGB) + mask_img = cv2.imread(str(mask_p), cv2.IMREAD_GRAYSCALE) + if mask_img.shape[:2] != img.shape[:2]: + progress.log( + f"resize mask {mask_p.name} to image {image_p.name} size: {img.shape[:2]}" + ) + mask_img = cv2.resize( + mask_img, + (img.shape[1], img.shape[0]), + interpolation=cv2.INTER_NEAREST, + ) + mask_img[mask_img >= 127] = 255 + mask_img[mask_img < 127] = 0 + + # bgr + inpaint_result = model_manager(img, mask_img, inpaint_request) + inpaint_result = cv2.cvtColor(inpaint_result, cv2.COLOR_BGR2RGB) + if concat: + mask_img = cv2.cvtColor(mask_img, cv2.COLOR_GRAY2RGB) + inpaint_result = cv2.hconcat([img, mask_img, inpaint_result]) + + img_bytes = pil_to_bytes(Image.fromarray(inpaint_result), "png", 100, infos) + save_p = output / f"{stem}.png" + with open(save_p, "wb") as fw: + fw.write(img_bytes) + + progress.update(task, advance=1) + torch_gc() + # pid = psutil.Process().pid + # memory_info = psutil.Process(pid).memory_info() + # memory_in_mb = memory_info.rss / (1024 * 1024) + # print(f"原图大小:{img.shape},当前进程的内存占用:{memory_in_mb}MB") diff --git a/py/iopaint/benchmark.py b/py/iopaint/benchmark.py new file mode 100644 index 0000000..f0b7cb9 --- /dev/null +++ b/py/iopaint/benchmark.py @@ -0,0 +1,109 @@ +#!/usr/bin/env python3 + +import argparse +import os +import time + +import numpy as np +import nvidia_smi +import psutil +import torch + +from .model_manager import ModelManager +from .schema import InpaintRequest, HDStrategy, SDSampler + +try: + torch._C._jit_override_can_fuse_on_cpu(False) + torch._C._jit_override_can_fuse_on_gpu(False) + torch._C._jit_set_texpr_fuser_enabled(False) + torch._C._jit_set_nvfuser_enabled(False) +except: + pass + +NUM_THREADS = str(4) + +os.environ["OMP_NUM_THREADS"] = NUM_THREADS +os.environ["OPENBLAS_NUM_THREADS"] = NUM_THREADS +os.environ["MKL_NUM_THREADS"] = NUM_THREADS +os.environ["VECLIB_MAXIMUM_THREADS"] = NUM_THREADS +os.environ["NUMEXPR_NUM_THREADS"] = NUM_THREADS +if os.environ.get("CACHE_DIR"): + os.environ["TORCH_HOME"] = os.environ["CACHE_DIR"] + + +def run_model(model, size): + # RGB + image = np.random.randint(0, 256, (size[0], size[1], 3)).astype(np.uint8) + mask = np.random.randint(0, 255, size).astype(np.uint8) + + config = InpaintRequest( + ldm_steps=2, + hd_strategy=HDStrategy.ORIGINAL, + hd_strategy_crop_margin=128, + hd_strategy_crop_trigger_size=128, + hd_strategy_resize_limit=128, + prompt="a fox is sitting on a bench", + sd_steps=5, + sd_sampler=SDSampler.ddim, + ) + model(image, mask, config) + + +def benchmark(model, times: int, empty_cache: bool): + sizes = [(512, 512)] + + nvidia_smi.nvmlInit() + device_id = 0 + handle = nvidia_smi.nvmlDeviceGetHandleByIndex(device_id) + + def format(metrics): + return f"{np.mean(metrics):.2f} ± {np.std(metrics):.2f}" + + process = psutil.Process(os.getpid()) + # 每个 size 给出显存和内存占用的指标 + for size in sizes: + torch.cuda.empty_cache() + time_metrics = [] + cpu_metrics = [] + memory_metrics = [] + gpu_memory_metrics = [] + for _ in range(times): + start = time.time() + run_model(model, size) + torch.cuda.synchronize() + + # cpu_metrics.append(process.cpu_percent()) + time_metrics.append((time.time() - start) * 1000) + memory_metrics.append(process.memory_info().rss / 1024 / 1024) + gpu_memory_metrics.append( + nvidia_smi.nvmlDeviceGetMemoryInfo(handle).used / 1024 / 1024 + ) + + print(f"size: {size}".center(80, "-")) + # print(f"cpu: {format(cpu_metrics)}") + print(f"latency: {format(time_metrics)}ms") + print(f"memory: {format(memory_metrics)} MB") + print(f"gpu memory: {format(gpu_memory_metrics)} MB") + + nvidia_smi.nvmlShutdown() + + +def get_args_parser(): + parser = argparse.ArgumentParser() + parser.add_argument("--name") + parser.add_argument("--device", default="cuda", type=str) + parser.add_argument("--times", default=10, type=int) + parser.add_argument("--empty-cache", action="store_true") + return parser.parse_args() + + +if __name__ == "__main__": + args = get_args_parser() + device = torch.device(args.device) + model = ModelManager( + name=args.name, + device=device, + disable_nsfw=True, + sd_cpu_textencoder=True, + ) + benchmark(model, args.times, args.empty_cache) diff --git a/py/iopaint/cli.py b/py/iopaint/cli.py new file mode 100644 index 0000000..5fdc975 --- /dev/null +++ b/py/iopaint/cli.py @@ -0,0 +1,220 @@ +import webbrowser +from contextlib import asynccontextmanager +from pathlib import Path +from typing import Dict, Optional + +import typer +from fastapi import FastAPI +from loguru import logger +from typer import Option +from typer_config import use_json_config + +from .const import * +from .runtime import setup_model_dir, dump_environment_info, check_device +from .schema import InteractiveSegModel, Device, RealESRGANModel, RemoveBGModel + +typer_app = typer.Typer(pretty_exceptions_show_locals=False, add_completion=False) + + +@typer_app.command(help="Install all plugins dependencies") +def install_plugins_packages(): + from .installer import install_plugins_package + + install_plugins_package() + + +@typer_app.command(help="Download SD/SDXL normal/inpainting model from HuggingFace") +def download( + model: str = Option( + ..., help="Model id on HuggingFace e.g: runwayml/stable-diffusion-inpainting" + ), + model_dir: Path = Option( + DEFAULT_MODEL_DIR, + help=MODEL_DIR_HELP, + file_okay=False, + callback=setup_model_dir, + ), +): + from .download import cli_download_model + + cli_download_model(model) + + +@typer_app.command(name="list", help="List downloaded models") +def list_model( + model_dir: Path = Option( + DEFAULT_MODEL_DIR, + help=MODEL_DIR_HELP, + file_okay=False, + callback=setup_model_dir, + ), +): + from .download import scan_models + + scanned_models = scan_models() + for it in scanned_models: + print(it.name) + + +@typer_app.command(help="Batch processing images") +def run( + model: str = Option("lama"), + device: Device = Option(Device.cpu), + image: Path = Option(..., help="Image folders or file path"), + mask: Path = Option( + ..., + help="Mask folders or file path. " + "If it is a directory, the mask images in the directory should have the same name as the original image." + "If it is a file, all images will use this mask." + "Mask will automatically resize to the same size as the original image.", + ), + output: Path = Option(..., help="Output directory or file path"), + config: Path = None, + concat: bool = False, + model_dir: Path = Option( + DEFAULT_MODEL_DIR, + help=MODEL_DIR_HELP, + file_okay=False, + callback=setup_model_dir, + ), +): + from .download import cli_download_model, scan_models + + scanned_models = scan_models() + if model not in [it.name for it in scanned_models]: + logger.info(f"{model} not found in {model_dir}, try to downloading") + cli_download_model(model) + + from .batch_processing import batch_inpaint + + + batch_inpaint(model, device, image, mask, output, config, concat) + + +@typer_app.command(help="Start IOPaint server") +@use_json_config() +def start( + host: str = Option("127.0.0.1"), + port: int = Option(8080), + inbrowser: bool = Option(False, help=INBROWSER_HELP), + model: str = Option( + DEFAULT_MODEL, + help=f"Erase models: [{', '.join(AVAILABLE_MODELS)}].\n" + f"Diffusion models: [{', '.join(DIFFUSION_MODELS)}] or any SD/SDXL normal/inpainting models on HuggingFace.", + ), + model_dir: Path = Option( + DEFAULT_MODEL_DIR, + help=MODEL_DIR_HELP, + dir_okay=True, + file_okay=False, + callback=setup_model_dir, + ), + low_mem: bool = Option(False, help=LOW_MEM_HELP), + no_half: bool = Option(False, help=NO_HALF_HELP), + cpu_offload: bool = Option(False, help=CPU_OFFLOAD_HELP), + disable_nsfw_checker: bool = Option(False, help=DISABLE_NSFW_HELP), + cpu_textencoder: bool = Option(False, help=CPU_TEXTENCODER_HELP), + local_files_only: bool = Option(False, help=LOCAL_FILES_ONLY_HELP), + device: Device = Option(Device.cpu), + input: Optional[Path] = Option(None, help=INPUT_HELP), + output_dir: Optional[Path] = Option( + None, help=OUTPUT_DIR_HELP, dir_okay=True, file_okay=False + ), + quality: int = Option(95, help=QUALITY_HELP), + enable_interactive_seg: bool = Option(False, help=INTERACTIVE_SEG_HELP), + interactive_seg_model: InteractiveSegModel = Option( + InteractiveSegModel.vit_b, help=INTERACTIVE_SEG_MODEL_HELP + ), + interactive_seg_device: Device = Option(Device.cpu), + enable_remove_bg: bool = Option(False, help=REMOVE_BG_HELP), + remove_bg_model: RemoveBGModel = Option(RemoveBGModel.briaai_rmbg_1_4), + enable_anime_seg: bool = Option(False, help=ANIMESEG_HELP), + enable_realesrgan: bool = Option(False), + realesrgan_device: Device = Option(Device.cpu), + realesrgan_model: RealESRGANModel = Option(RealESRGANModel.realesr_general_x4v3), + enable_gfpgan: bool = Option(False), + gfpgan_device: Device = Option(Device.cpu), + enable_restoreformer: bool = Option(False), + restoreformer_device: Device = Option(Device.cpu), +): + dump_environment_info() + device = check_device(device) + if input and not input.exists(): + logger.error(f"invalid --input: {input} not exists") + exit(-1) + if input and input.is_dir() and not output_dir: + logger.error(f"invalid --output-dir: must be set when --input is a directory") + exit(-1) + if output_dir: + output_dir = output_dir.expanduser().absolute() + logger.info(f"Image will be saved to {output_dir}") + if not output_dir.exists(): + logger.info(f"Create output directory {output_dir}") + output_dir.mkdir(parents=True) + + model_dir = model_dir.expanduser().absolute() + + if local_files_only: + os.environ["TRANSFORMERS_OFFLINE"] = "1" + os.environ["HF_HUB_OFFLINE"] = "1" + + from .download import cli_download_model, scan_models + + scanned_models = scan_models() + if model not in [it.name for it in scanned_models]: + logger.info(f"{model} not found in {model_dir}, try to downloading") + cli_download_model(model) + + from .api import Api + from .schema import ApiConfig + + @asynccontextmanager + async def lifespan(app: FastAPI): + if inbrowser: + webbrowser.open(f"http://localhost:{port}", new=0, autoraise=True) + yield + + app = FastAPI(lifespan=lifespan) + + api_config = ApiConfig( + host=host, + port=port, + inbrowser=inbrowser, + model=model, + no_half=no_half, + low_mem=low_mem, + cpu_offload=cpu_offload, + disable_nsfw_checker=disable_nsfw_checker, + local_files_only=local_files_only, + cpu_textencoder=cpu_textencoder if device == Device.cuda else False, + device=device, + input=input, + output_dir=output_dir, + quality=quality, + enable_interactive_seg=enable_interactive_seg, + interactive_seg_model=interactive_seg_model, + interactive_seg_device=interactive_seg_device, + enable_remove_bg=enable_remove_bg, + remove_bg_model=remove_bg_model, + enable_anime_seg=enable_anime_seg, + enable_realesrgan=enable_realesrgan, + realesrgan_device=realesrgan_device, + realesrgan_model=realesrgan_model, + enable_gfpgan=enable_gfpgan, + gfpgan_device=gfpgan_device, + enable_restoreformer=enable_restoreformer, + restoreformer_device=restoreformer_device, + ) + # print(api_config.model_dump_json(indent=4)) + api = Api(app, api_config) + api.launch() + + +@typer_app.command(help="Start IOPaint web config page") +def start_web_config( + config_file: Path = Option("config.json"), +): + dump_environment_info() + from .web_config import main + + main(config_file) diff --git a/py/iopaint/const.py b/py/iopaint/const.py new file mode 100644 index 0000000..4d64d1e --- /dev/null +++ b/py/iopaint/const.py @@ -0,0 +1,125 @@ +import os +from typing import List +import folder_paths + +INSTRUCT_PIX2PIX_NAME = "timbrooks/instruct-pix2pix" +KANDINSKY22_NAME = "kandinsky-community/kandinsky-2-2-decoder-inpaint" +POWERPAINT_NAME = "Sanster/PowerPaint-V1-stable-diffusion-inpainting" +ANYTEXT_NAME = "Sanster/AnyText" + + +DIFFUSERS_SD_CLASS_NAME = "StableDiffusionPipeline" +DIFFUSERS_SD_INPAINT_CLASS_NAME = "StableDiffusionInpaintPipeline" +DIFFUSERS_SDXL_CLASS_NAME = "StableDiffusionXLPipeline" +DIFFUSERS_SDXL_INPAINT_CLASS_NAME = "StableDiffusionXLInpaintPipeline" + +MPS_UNSUPPORT_MODELS = [ + "lama", + "ldm", + "zits", + "mat", + "fcf", + "cv2", + "manga", +] + +DEFAULT_MODEL = "lama" +AVAILABLE_MODELS = ["lama", "ldm", "zits", "mat", "fcf", "manga", "cv2", "migan"] +DIFFUSION_MODELS = [ + "runwayml/stable-diffusion-inpainting", + "Uminosachi/realisticVisionV51_v51VAE-inpainting", + "redstonehero/dreamshaper-inpainting", + "Sanster/anything-4.0-inpainting", + "diffusers/stable-diffusion-xl-1.0-inpainting-0.1", + "Fantasy-Studio/Paint-by-Example", + POWERPAINT_NAME, + ANYTEXT_NAME, +] + +NO_HALF_HELP = """ +Using full precision(fp32) model. +If your diffusion model generate result is always black or green, use this argument. +""" + +CPU_OFFLOAD_HELP = """ +Offloads diffusion model's weight to CPU RAM, significantly reducing vRAM usage. +""" + +LOW_MEM_HELP = "Enable attention slicing and vae tiling to save memory." + +DISABLE_NSFW_HELP = """ +Disable NSFW checker for diffusion model. +""" + +CPU_TEXTENCODER_HELP = """ +Run diffusion models text encoder on CPU to reduce vRAM usage. +""" + +SD_CONTROLNET_CHOICES: List[str] = [ + "lllyasviel/control_v11p_sd15_canny", + # "lllyasviel/control_v11p_sd15_seg", + "lllyasviel/control_v11p_sd15_openpose", + "lllyasviel/control_v11p_sd15_inpaint", + "lllyasviel/control_v11f1p_sd15_depth", +] + +SD2_CONTROLNET_CHOICES = [ + "thibaud/controlnet-sd21-canny-diffusers", + "thibaud/controlnet-sd21-depth-diffusers", + "thibaud/controlnet-sd21-openpose-diffusers", +] + +SDXL_CONTROLNET_CHOICES = [ + "thibaud/controlnet-openpose-sdxl-1.0", + "destitech/controlnet-inpaint-dreamer-sdxl", + "diffusers/controlnet-canny-sdxl-1.0", + "diffusers/controlnet-canny-sdxl-1.0-mid", + "diffusers/controlnet-canny-sdxl-1.0-small", + "diffusers/controlnet-depth-sdxl-1.0", + "diffusers/controlnet-depth-sdxl-1.0-mid", + "diffusers/controlnet-depth-sdxl-1.0-small", +] + +LOCAL_FILES_ONLY_HELP = """ +When loading diffusion models, using local files only, not connect to HuggingFace server. +""" + +# DEFAULT_MODEL_DIR = os.path.abspath( +# os.getenv("XDG_CACHE_HOME", os.path.join(os.path.expanduser("~"), ".cache")) +# ) + + +DEFAULT_MODEL_DIR = os.path.abspath(os.path.join(folder_paths.models_dir, 'lama')) +# print(f"DEFAULT_MODEL_DIR={DEFAULT_MODEL_DIR}") + +MODEL_DIR_HELP = f""" +Model download directory (by setting XDG_CACHE_HOME environment variable), by default model download to {DEFAULT_MODEL_DIR} +""" + +OUTPUT_DIR_HELP = """ +Result images will be saved to output directory automatically. +""" + +INPUT_HELP = """ +If input is image, it will be loaded by default. +If input is directory, you can browse and select image in file manager. +""" + +GUI_HELP = """ +Launch Lama Cleaner as desktop app +""" + +QUALITY_HELP = """ +Quality of image encoding, 0-100. Default is 95, higher quality will generate larger file size. +""" + +INTERACTIVE_SEG_HELP = "Enable interactive segmentation using Segment Anything." +INTERACTIVE_SEG_MODEL_HELP = "Model size: mobile_sam < vit_b < vit_l < vit_h. Bigger model size means better segmentation but slower speed." +REMOVE_BG_HELP = "Enable remove background plugin. Always run on CPU" +ANIMESEG_HELP = "Enable anime segmentation plugin. Always run on CPU" +REALESRGAN_HELP = "Enable realesrgan super resolution" +GFPGAN_HELP = "Enable GFPGAN face restore. To also enhance background, use with --enable-realesrgan" +RESTOREFORMER_HELP = "Enable RestoreFormer face restore. To also enhance background, use with --enable-realesrgan" +GIF_HELP = "Enable GIF plugin. Make GIF to compare original and cleaned image" + +INBROWSER_HELP = "Automatically launch IOPaint in a new tab on the default browser" diff --git a/py/iopaint/download.py b/py/iopaint/download.py new file mode 100644 index 0000000..53c441f --- /dev/null +++ b/py/iopaint/download.py @@ -0,0 +1,294 @@ +import json +import os +from functools import lru_cache +from typing import List + +from .schema import ModelType, ModelInfo +from loguru import logger +from pathlib import Path + +from .const import ( + DEFAULT_MODEL_DIR, + DIFFUSERS_SD_CLASS_NAME, + DIFFUSERS_SD_INPAINT_CLASS_NAME, + DIFFUSERS_SDXL_CLASS_NAME, + DIFFUSERS_SDXL_INPAINT_CLASS_NAME, + ANYTEXT_NAME, +) +from .model.original_sd_configs import get_config_files + + +def cli_download_model(model: str): + from .model import models + from .model.utils import handle_from_pretrained_exceptions + + if model in models and models[model].is_erase_model: + logger.info(f"Downloading {model}...") + models[model].download() + logger.info(f"Done.") + elif model == ANYTEXT_NAME: + logger.info(f"Downloading {model}...") + models[model].download() + logger.info(f"Done.") + else: + logger.info(f"Downloading model from Huggingface: {model}") + from diffusers import DiffusionPipeline + + downloaded_path = handle_from_pretrained_exceptions( + DiffusionPipeline.download, + pretrained_model_name=model, + variant="fp16", + resume_download=True, + ) + logger.info(f"Done. Downloaded to {downloaded_path}") + + +def folder_name_to_show_name(name: str) -> str: + return name.replace("models--", "").replace("--", "/") + + +@lru_cache(maxsize=512) +def get_sd_model_type(model_abs_path: str) -> ModelType: + if "inpaint" in Path(model_abs_path).name.lower(): + model_type = ModelType.DIFFUSERS_SD_INPAINT + else: + # load once to check num_in_channels + from diffusers import StableDiffusionInpaintPipeline + + try: + StableDiffusionInpaintPipeline.from_single_file( + model_abs_path, + load_safety_checker=False, + num_in_channels=9, + config_files=get_config_files(), + ) + model_type = ModelType.DIFFUSERS_SD_INPAINT + except ValueError as e: + if "Trying to set a tensor of shape torch.Size([320, 4, 3, 3])" in str(e): + model_type = ModelType.DIFFUSERS_SD + else: + raise e + return model_type + + +@lru_cache() +def get_sdxl_model_type(model_abs_path: str) -> ModelType: + if "inpaint" in model_abs_path: + model_type = ModelType.DIFFUSERS_SDXL_INPAINT + else: + # load once to check num_in_channels + from diffusers import StableDiffusionXLInpaintPipeline + + try: + model = StableDiffusionXLInpaintPipeline.from_single_file( + model_abs_path, + load_safety_checker=False, + num_in_channels=9, + config_files=get_config_files(), + ) + if model.unet.config.in_channels == 9: + # https://github.com/huggingface/diffusers/issues/6610 + model_type = ModelType.DIFFUSERS_SDXL_INPAINT + else: + model_type = ModelType.DIFFUSERS_SDXL + except ValueError as e: + if "Trying to set a tensor of shape torch.Size([320, 4, 3, 3])" in str(e): + model_type = ModelType.DIFFUSERS_SDXL + else: + raise e + return model_type + + +def scan_single_file_diffusion_models(cache_dir) -> List[ModelInfo]: + cache_dir = Path(cache_dir) + stable_diffusion_dir = cache_dir / "stable_diffusion" + cache_file = stable_diffusion_dir / "iopaint_cache.json" + model_type_cache = {} + if cache_file.exists(): + try: + with open(cache_file, "r", encoding="utf-8") as f: + model_type_cache = json.load(f) + assert isinstance(model_type_cache, dict) + except: + pass + + res = [] + for it in stable_diffusion_dir.glob(f"*.*"): + if it.suffix not in [".safetensors", ".ckpt"]: + continue + model_abs_path = str(it.absolute()) + model_type = model_type_cache.get(it.name) + if model_type is None: + model_type = get_sd_model_type(model_abs_path) + model_type_cache[it.name] = model_type + res.append( + ModelInfo( + name=it.name, + path=model_abs_path, + model_type=model_type, + is_single_file_diffusers=True, + ) + ) + if stable_diffusion_dir.exists(): + with open(cache_file, "w", encoding="utf-8") as fw: + json.dump(model_type_cache, fw, indent=2, ensure_ascii=False) + + stable_diffusion_xl_dir = cache_dir / "stable_diffusion_xl" + sdxl_cache_file = stable_diffusion_xl_dir / "iopaint_cache.json" + sdxl_model_type_cache = {} + if sdxl_cache_file.exists(): + try: + with open(sdxl_cache_file, "r", encoding="utf-8") as f: + sdxl_model_type_cache = json.load(f) + assert isinstance(sdxl_model_type_cache, dict) + except: + pass + + for it in stable_diffusion_xl_dir.glob(f"*.*"): + if it.suffix not in [".safetensors", ".ckpt"]: + continue + model_abs_path = str(it.absolute()) + model_type = sdxl_model_type_cache.get(it.name) + if model_type is None: + model_type = get_sdxl_model_type(model_abs_path) + sdxl_model_type_cache[it.name] = model_type + if stable_diffusion_xl_dir.exists(): + with open(sdxl_cache_file, "w", encoding="utf-8") as fw: + json.dump(sdxl_model_type_cache, fw, indent=2, ensure_ascii=False) + + res.append( + ModelInfo( + name=it.name, + path=model_abs_path, + model_type=model_type, + is_single_file_diffusers=True, + ) + ) + return res + + +def scan_inpaint_models(model_dir: Path) -> List[ModelInfo]: + res = [] + from .model import models + + # logger.info(f"Scanning inpaint models in {model_dir}") + + for name, m in models.items(): + if m.is_erase_model and m.is_downloaded(): + res.append( + ModelInfo( + name=name, + path=name, + model_type=ModelType.INPAINT, + ) + ) + return res + + +def scan_diffusers_models() -> List[ModelInfo]: + from huggingface_hub.constants import HF_HUB_CACHE + + available_models = [] + cache_dir = Path(HF_HUB_CACHE) + # logger.info(f"Scanning diffusers models in {cache_dir}") + diffusers_model_names = [] + for it in cache_dir.glob("**/*/model_index.json"): + with open(it, "r", encoding="utf-8") as f: + try: + data = json.load(f) + except: + continue + + _class_name = data["_class_name"] + name = folder_name_to_show_name(it.parent.parent.parent.name) + if name in diffusers_model_names: + continue + if "PowerPaint" in name: + model_type = ModelType.DIFFUSERS_OTHER + elif _class_name == DIFFUSERS_SD_CLASS_NAME: + model_type = ModelType.DIFFUSERS_SD + elif _class_name == DIFFUSERS_SD_INPAINT_CLASS_NAME: + model_type = ModelType.DIFFUSERS_SD_INPAINT + elif _class_name == DIFFUSERS_SDXL_CLASS_NAME: + model_type = ModelType.DIFFUSERS_SDXL + elif _class_name == DIFFUSERS_SDXL_INPAINT_CLASS_NAME: + model_type = ModelType.DIFFUSERS_SDXL_INPAINT + elif _class_name in [ + "StableDiffusionInstructPix2PixPipeline", + "PaintByExamplePipeline", + "KandinskyV22InpaintPipeline", + "AnyText", + ]: + model_type = ModelType.DIFFUSERS_OTHER + else: + continue + + diffusers_model_names.append(name) + available_models.append( + ModelInfo( + name=name, + path=name, + model_type=model_type, + ) + ) + return available_models + + +def _scan_converted_diffusers_models(cache_dir) -> List[ModelInfo]: + cache_dir = Path(cache_dir) + available_models = [] + diffusers_model_names = [] + for it in cache_dir.glob("**/*/model_index.json"): + with open(it, "r", encoding="utf-8") as f: + try: + data = json.load(f) + except: + logger.error( + f"Failed to load {it}, please try revert from original model or fix model_index.json by hand." + ) + continue + + _class_name = data["_class_name"] + name = folder_name_to_show_name(it.parent.name) + if name in diffusers_model_names: + continue + elif _class_name == DIFFUSERS_SD_CLASS_NAME: + model_type = ModelType.DIFFUSERS_SD + elif _class_name == DIFFUSERS_SD_INPAINT_CLASS_NAME: + model_type = ModelType.DIFFUSERS_SD_INPAINT + elif _class_name == DIFFUSERS_SDXL_CLASS_NAME: + model_type = ModelType.DIFFUSERS_SDXL + elif _class_name == DIFFUSERS_SDXL_INPAINT_CLASS_NAME: + model_type = ModelType.DIFFUSERS_SDXL_INPAINT + else: + continue + + diffusers_model_names.append(name) + available_models.append( + ModelInfo( + name=name, + path=str(it.parent.absolute()), + model_type=model_type, + ) + ) + return available_models + + +def scan_converted_diffusers_models(cache_dir) -> List[ModelInfo]: + cache_dir = Path(cache_dir) + available_models = [] + stable_diffusion_dir = cache_dir / "stable_diffusion" + stable_diffusion_xl_dir = cache_dir / "stable_diffusion_xl" + available_models.extend(_scan_converted_diffusers_models(stable_diffusion_dir)) + available_models.extend(_scan_converted_diffusers_models(stable_diffusion_xl_dir)) + return available_models + + +def scan_models() -> List[ModelInfo]: + model_dir = os.getenv("XDG_CACHE_HOME", DEFAULT_MODEL_DIR) + available_models = [] + available_models.extend(scan_inpaint_models(model_dir)) + available_models.extend(scan_single_file_diffusion_models(model_dir)) + available_models.extend(scan_diffusers_models()) + available_models.extend(scan_converted_diffusers_models(model_dir)) + return available_models diff --git a/py/iopaint/file_manager/__init__.py b/py/iopaint/file_manager/__init__.py new file mode 100644 index 0000000..1a24998 --- /dev/null +++ b/py/iopaint/file_manager/__init__.py @@ -0,0 +1 @@ +from .file_manager import FileManager diff --git a/py/iopaint/file_manager/file_manager.py b/py/iopaint/file_manager/file_manager.py new file mode 100644 index 0000000..413162c --- /dev/null +++ b/py/iopaint/file_manager/file_manager.py @@ -0,0 +1,215 @@ +import os +from io import BytesIO +from pathlib import Path +from typing import List + +from PIL import Image, ImageOps, PngImagePlugin +from fastapi import FastAPI, UploadFile, HTTPException +from starlette.responses import FileResponse + +from ..schema import MediasResponse, MediaTab + +LARGE_ENOUGH_NUMBER = 100 +PngImagePlugin.MAX_TEXT_CHUNK = LARGE_ENOUGH_NUMBER * (1024**2) +from .storage_backends import FilesystemStorageBackend +from .utils import aspect_to_string, generate_filename, glob_img + + +class FileManager: + def __init__(self, app: FastAPI, input_dir: Path, output_dir: Path): + self.app = app + self.input_dir: Path = input_dir + self.output_dir: Path = output_dir + + self.image_dir_filenames = [] + self.output_dir_filenames = [] + if not self.thumbnail_directory.exists(): + self.thumbnail_directory.mkdir(parents=True) + + # fmt: off + self.app.add_api_route("/api/v1/medias", self.api_medias, methods=["GET"], response_model=List[MediasResponse]) + self.app.add_api_route("/api/v1/media_file", self.api_media_file, methods=["GET"]) + self.app.add_api_route("/api/v1/media_thumbnail_file", self.api_media_thumbnail_file, methods=["GET"]) + # fmt: on + + def api_medias(self, tab: MediaTab) -> List[MediasResponse]: + img_dir = self._get_dir(tab) + return self._media_names(img_dir) + + def api_media_file(self, tab: MediaTab, filename: str) -> FileResponse: + file_path = self._get_file(tab, filename) + return FileResponse(file_path, media_type="image/png") + + # tab=${tab}?filename=${filename.name}?width=${width}&height=${height} + def api_media_thumbnail_file( + self, tab: MediaTab, filename: str, width: int, height: int + ) -> FileResponse: + img_dir = self._get_dir(tab) + thumb_filename, (width, height) = self.get_thumbnail( + img_dir, filename, width=width, height=height + ) + thumbnail_filepath = self.thumbnail_directory / thumb_filename + return FileResponse( + thumbnail_filepath, + headers={ + "X-Width": str(width), + "X-Height": str(height), + }, + media_type="image/jpeg", + ) + + def _get_dir(self, tab: MediaTab) -> Path: + if tab == "input": + return self.input_dir + elif tab == "output": + return self.output_dir + else: + raise HTTPException(status_code=422, detail=f"tab not found: {tab}") + + def _get_file(self, tab: MediaTab, filename: str) -> Path: + file_path = self._get_dir(tab) / filename + if not file_path.exists(): + raise HTTPException(status_code=422, detail=f"file not found: {file_path}") + return file_path + + @property + def thumbnail_directory(self) -> Path: + return self.output_dir / "thumbnails" + + @staticmethod + def _media_names(directory: Path) -> List[MediasResponse]: + names = sorted([it.name for it in glob_img(directory)]) + res = [] + for name in names: + path = os.path.join(directory, name) + img = Image.open(path) + res.append( + MediasResponse( + name=name, + height=img.height, + width=img.width, + ctime=os.path.getctime(path), + mtime=os.path.getmtime(path), + ) + ) + return res + + def get_thumbnail( + self, directory: Path, original_filename: str, width, height, **options + ): + directory = Path(directory) + storage = FilesystemStorageBackend(self.app) + crop = options.get("crop", "fit") + background = options.get("background") + quality = options.get("quality", 90) + + original_path, original_filename = os.path.split(original_filename) + original_filepath = os.path.join(directory, original_path, original_filename) + image = Image.open(BytesIO(storage.read(original_filepath))) + + # keep ratio resize + if not width and not height: + width = 256 + + if width != 0: + height = int(image.height * width / image.width) + else: + width = int(image.width * height / image.height) + + thumbnail_size = (width, height) + + thumbnail_filename = generate_filename( + directory, + original_filename, + aspect_to_string(thumbnail_size), + crop, + background, + quality, + ) + + thumbnail_filepath = os.path.join( + self.thumbnail_directory, original_path, thumbnail_filename + ) + + if storage.exists(thumbnail_filepath): + return thumbnail_filepath, (width, height) + + try: + image.load() + except (IOError, OSError): + self.app.logger.warning("Thumbnail not load image: %s", original_filepath) + return thumbnail_filepath, (width, height) + + # get original image format + options["format"] = options.get("format", image.format) + + image = self._create_thumbnail( + image, thumbnail_size, crop, background=background + ) + + raw_data = self.get_raw_data(image, **options) + storage.save(thumbnail_filepath, raw_data) + + return thumbnail_filepath, (width, height) + + def get_raw_data(self, image, **options): + data = { + "format": self._get_format(image, **options), + "quality": options.get("quality", 90), + } + + _file = BytesIO() + image.save(_file, **data) + return _file.getvalue() + + @staticmethod + def colormode(image, colormode="RGB"): + if colormode == "RGB" or colormode == "RGBA": + if image.mode == "RGBA": + return image + if image.mode == "LA": + return image.convert("RGBA") + return image.convert(colormode) + + if colormode == "GRAY": + return image.convert("L") + + return image.convert(colormode) + + @staticmethod + def background(original_image, color=0xFF): + size = (max(original_image.size),) * 2 + image = Image.new("L", size, color) + image.paste( + original_image, + tuple(map(lambda x: (x[0] - x[1]) / 2, zip(size, original_image.size))), + ) + + return image + + def _get_format(self, image, **options): + if options.get("format"): + return options.get("format") + if image.format: + return image.format + + return "JPEG" + + def _create_thumbnail(self, image, size, crop="fit", background=None): + try: + resample = Image.Resampling.LANCZOS + except AttributeError: # pylint: disable=raise-missing-from + resample = Image.ANTIALIAS + + if crop == "fit": + image = ImageOps.fit(image, size, resample) + else: + image = image.copy() + image.thumbnail(size, resample=resample) + + if background is not None: + image = self.background(image) + + image = self.colormode(image) + + return image diff --git a/py/iopaint/file_manager/storage_backends.py b/py/iopaint/file_manager/storage_backends.py new file mode 100644 index 0000000..3f453ad --- /dev/null +++ b/py/iopaint/file_manager/storage_backends.py @@ -0,0 +1,46 @@ +# Copy from https://github.com/silentsokolov/flask-thumbnails/blob/master/flask_thumbnails/storage_backends.py +import errno +import os +from abc import ABC, abstractmethod + + +class BaseStorageBackend(ABC): + def __init__(self, app=None): + self.app = app + + @abstractmethod + def read(self, filepath, mode="rb", **kwargs): + raise NotImplementedError + + @abstractmethod + def exists(self, filepath): + raise NotImplementedError + + @abstractmethod + def save(self, filepath, data): + raise NotImplementedError + + +class FilesystemStorageBackend(BaseStorageBackend): + def read(self, filepath, mode="rb", **kwargs): + with open(filepath, mode) as f: # pylint: disable=unspecified-encoding + return f.read() + + def exists(self, filepath): + return os.path.exists(filepath) + + def save(self, filepath, data): + directory = os.path.dirname(filepath) + + if not os.path.exists(directory): + try: + os.makedirs(directory) + except OSError as e: + if e.errno != errno.EEXIST: + raise + + if not os.path.isdir(directory): + raise IOError("{} is not a directory".format(directory)) + + with open(filepath, "wb") as f: + f.write(data) diff --git a/py/iopaint/file_manager/utils.py b/py/iopaint/file_manager/utils.py new file mode 100644 index 0000000..f6890af --- /dev/null +++ b/py/iopaint/file_manager/utils.py @@ -0,0 +1,65 @@ +# Copy from: https://github.com/silentsokolov/flask-thumbnails/blob/master/flask_thumbnails/utils.py +import hashlib +from pathlib import Path + +from typing import Union + + +def generate_filename(directory: Path, original_filename, *options) -> str: + text = str(directory.absolute()) + original_filename + for v in options: + text += "%s" % v + md5_hash = hashlib.md5() + md5_hash.update(text.encode("utf-8")) + return md5_hash.hexdigest() + ".jpg" + + +def parse_size(size): + if isinstance(size, int): + # If the size parameter is a single number, assume square aspect. + return [size, size] + + if isinstance(size, (tuple, list)): + if len(size) == 1: + # If single value tuple/list is provided, exand it to two elements + return size + type(size)(size) + return size + + try: + thumbnail_size = [int(x) for x in size.lower().split("x", 1)] + except ValueError: + raise ValueError( # pylint: disable=raise-missing-from + "Bad thumbnail size format. Valid format is INTxINT." + ) + + if len(thumbnail_size) == 1: + # If the size parameter only contains a single integer, assume square aspect. + thumbnail_size.append(thumbnail_size[0]) + + return thumbnail_size + + +def aspect_to_string(size): + if isinstance(size, str): + return size + + return "x".join(map(str, size)) + + +IMG_SUFFIX = {".jpg", ".jpeg", ".png", ".JPG", ".JPEG", ".PNG"} + + +def glob_img(p: Union[Path, str], recursive: bool = False): + p = Path(p) + if p.is_file() and p.suffix in IMG_SUFFIX: + yield p + else: + if recursive: + files = Path(p).glob("**/*.*") + else: + files = Path(p).glob("*.*") + + for it in files: + if it.suffix not in IMG_SUFFIX: + continue + yield it diff --git a/py/iopaint/helper.py b/py/iopaint/helper.py new file mode 100644 index 0000000..35d348e --- /dev/null +++ b/py/iopaint/helper.py @@ -0,0 +1,411 @@ +import base64 +import imghdr +import io +import os +import sys +from typing import List, Optional, Dict, Tuple + +from urllib.parse import urlparse +import cv2 +from PIL import Image, ImageOps, PngImagePlugin +import numpy as np +import torch +from .const import MPS_UNSUPPORT_MODELS +from loguru import logger +from torch.hub import download_url_to_file, get_dir +import hashlib +from .const import DEFAULT_MODEL_DIR + + +def md5sum(filename): + md5 = hashlib.md5() + with open(filename, "rb") as f: + for chunk in iter(lambda: f.read(128 * md5.block_size), b""): + md5.update(chunk) + return md5.hexdigest() + + +def switch_mps_device(model_name, device): + if model_name in MPS_UNSUPPORT_MODELS and str(device) == "mps": + logger.info(f"{model_name} not support mps, switch to cpu") + return torch.device("cpu") + return device + + +def get_cache_path_by_url(url): + parts = urlparse(url) + # hub_dir = get_dir() + # model_dir = os.path.join(hub_dir, "checkpoints") + model_dir = DEFAULT_MODEL_DIR + if not os.path.isdir(model_dir): + os.makedirs(model_dir) + filename = os.path.basename(parts.path) + cached_file = os.path.join(model_dir, filename) + return cached_file + + +def download_model(url, model_md5: str = None): + if os.path.exists(url): + cached_file = url + else: + cached_file = get_cache_path_by_url(url) + if not os.path.exists(cached_file): + sys.stderr.write('Downloading: "{}" to {}\n'.format(url, cached_file)) + hash_prefix = None + download_url_to_file(url, cached_file, hash_prefix, progress=True) + if model_md5: + _md5 = md5sum(cached_file) + if model_md5 == _md5: + logger.info(f"Download model success, md5: {_md5}") + else: + try: + os.remove(cached_file) + logger.error( + f"Model md5: {_md5}, expected md5: {model_md5}, wrong model deleted. Please restart iopaint." + f"If you still have errors, please try download model manually first https://lama-cleaner-docs.vercel.app/install/download_model_manually.\n" + ) + except: + logger.error( + f"Model md5: {_md5}, expected md5: {model_md5}, please delete {cached_file} and restart iopaint." + ) + exit(-1) + + return cached_file + + +def ceil_modulo(x, mod): + if x % mod == 0: + return x + return (x // mod + 1) * mod + + +def handle_error(model_path, model_md5, e): + _md5 = md5sum(model_path) + if _md5 != model_md5: + try: + os.remove(model_path) + logger.error( + f"Model md5: {_md5}, expected md5: {model_md5}, wrong model deleted. Please restart iopaint." + f"If you still have errors, please try download model manually first https://lama-cleaner-docs.vercel.app/install/download_model_manually.\n" + ) + except: + logger.error( + f"Model md5: {_md5}, expected md5: {model_md5}, please delete {model_path} and restart iopaint." + ) + else: + logger.error( + f"Failed to load model {model_path}," + f"please submit an issue at https://github.com/Sanster/lama-cleaner/issues and include a screenshot of the error:\n{e}" + ) + exit(-1) + + +def load_jit_model(url_or_path, device, model_md5: str): + if os.path.exists(url_or_path): + model_path = url_or_path + else: + model_path = download_model(url_or_path, model_md5) + model_path = os.path.normpath(model_path) + logger.info(f"Loading model from: {model_path}") + + try: + model = torch.jit.load(model_path, map_location="cpu").to(device) + except Exception as e: + handle_error(model_path, model_md5, e) + model.eval() + return model + + +def load_model(model: torch.nn.Module, url_or_path, device, model_md5): + if os.path.exists(url_or_path): + model_path = url_or_path + else: + model_path = download_model(url_or_path, model_md5) + + try: + logger.info(f"Loading model from: {model_path}") + state_dict = torch.load(model_path, map_location="cpu") + model.load_state_dict(state_dict, strict=True) + model.to(device) + except Exception as e: + handle_error(model_path, model_md5, e) + model.eval() + return model + + +def numpy_to_bytes(image_numpy: np.ndarray, ext: str) -> bytes: + data = cv2.imencode( + f".{ext}", + image_numpy, + [int(cv2.IMWRITE_JPEG_QUALITY), 100, int(cv2.IMWRITE_PNG_COMPRESSION), 0], + )[1] + image_bytes = data.tobytes() + return image_bytes + + +def pil_to_bytes(pil_img, ext: str, quality: int = 95, infos={}) -> bytes: + with io.BytesIO() as output: + kwargs = {k: v for k, v in infos.items() if v is not None} + if ext == "jpg": + ext = "jpeg" + if "png" == ext.lower() and "parameters" in kwargs: + pnginfo_data = PngImagePlugin.PngInfo() + pnginfo_data.add_text("parameters", kwargs["parameters"]) + kwargs["pnginfo"] = pnginfo_data + + pil_img.save(output, format=ext, quality=quality, **kwargs) + image_bytes = output.getvalue() + return image_bytes + + +def load_img(img_bytes, gray: bool = False, return_info: bool = False): + alpha_channel = None + image = Image.open(io.BytesIO(img_bytes)) + + if return_info: + infos = image.info + + try: + image = ImageOps.exif_transpose(image) + except: + pass + + if gray: + image = image.convert("L") + np_img = np.array(image) + else: + if image.mode == "RGBA": + np_img = np.array(image) + alpha_channel = np_img[:, :, -1] + np_img = cv2.cvtColor(np_img, cv2.COLOR_RGBA2RGB) + else: + image = image.convert("RGB") + np_img = np.array(image) + + if return_info: + return np_img, alpha_channel, infos + return np_img, alpha_channel + + +def norm_img(np_img): + if len(np_img.shape) == 2: + np_img = np_img[:, :, np.newaxis] + np_img = np.transpose(np_img, (2, 0, 1)) + np_img = np_img.astype("float32") / 255 + return np_img + + +def resize_max_size( + np_img, size_limit: int, interpolation=cv2.INTER_CUBIC +) -> np.ndarray: + # Resize image's longer size to size_limit if longer size larger than size_limit + h, w = np_img.shape[:2] + if max(h, w) > size_limit: + ratio = size_limit / max(h, w) + new_w = int(w * ratio + 0.5) + new_h = int(h * ratio + 0.5) + return cv2.resize(np_img, dsize=(new_w, new_h), interpolation=interpolation) + else: + return np_img + + +def pad_img_to_modulo( + img: np.ndarray, mod: int, square: bool = False, min_size: Optional[int] = None +): + """ + + Args: + img: [H, W, C] + mod: + square: 是否为正方形 + min_size: + + Returns: + + """ + if len(img.shape) == 2: + img = img[:, :, np.newaxis] + height, width = img.shape[:2] + out_height = ceil_modulo(height, mod) + out_width = ceil_modulo(width, mod) + + if min_size is not None: + assert min_size % mod == 0 + out_width = max(min_size, out_width) + out_height = max(min_size, out_height) + + if square: + max_size = max(out_height, out_width) + out_height = max_size + out_width = max_size + + return np.pad( + img, + ((0, out_height - height), (0, out_width - width), (0, 0)), + mode="symmetric", + ) + + +def boxes_from_mask(mask: np.ndarray) -> List[np.ndarray]: + """ + Args: + mask: (h, w, 1) 0~255 + + Returns: + + """ + height, width = mask.shape[:2] + _, thresh = cv2.threshold(mask, 127, 255, 0) + contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) + + boxes = [] + for cnt in contours: + x, y, w, h = cv2.boundingRect(cnt) + box = np.array([x, y, x + w, y + h]).astype(int) + + box[::2] = np.clip(box[::2], 0, width) + box[1::2] = np.clip(box[1::2], 0, height) + boxes.append(box) + + return boxes + + +def only_keep_largest_contour(mask: np.ndarray) -> List[np.ndarray]: + """ + Args: + mask: (h, w) 0~255 + + Returns: + + """ + _, thresh = cv2.threshold(mask, 127, 255, 0) + contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) + + max_area = 0 + max_index = -1 + for i, cnt in enumerate(contours): + area = cv2.contourArea(cnt) + if area > max_area: + max_area = area + max_index = i + + if max_index != -1: + new_mask = np.zeros_like(mask) + return cv2.drawContours(new_mask, contours, max_index, 255, -1) + else: + return mask + + +def is_mac(): + return sys.platform == "darwin" + + +def get_image_ext(img_bytes): + w = imghdr.what("", img_bytes) + if w is None: + w = "jpeg" + return w + + +def decode_base64_to_image( + encoding: str, gray=False +) -> Tuple[np.array, Optional[np.array], Dict]: + if encoding.startswith("data:image/") or encoding.startswith( + "data:application/octet-stream;base64," + ): + encoding = encoding.split(";")[1].split(",")[1] + image = Image.open(io.BytesIO(base64.b64decode(encoding))) + + alpha_channel = None + try: + image = ImageOps.exif_transpose(image) + except: + pass + # exif_transpose will remove exif rotate info,we must call image.info after exif_transpose + infos = image.info + + if gray: + image = image.convert("L") + np_img = np.array(image) + else: + if image.mode == "RGBA": + np_img = np.array(image) + alpha_channel = np_img[:, :, -1] + np_img = cv2.cvtColor(np_img, cv2.COLOR_RGBA2RGB) + else: + image = image.convert("RGB") + np_img = np.array(image) + + return np_img, alpha_channel, infos + + +def encode_pil_to_base64(image: Image, quality: int, infos: Dict) -> bytes: + img_bytes = pil_to_bytes( + image, + "png", + quality=quality, + infos=infos, + ) + return base64.b64encode(img_bytes) + + +def concat_alpha_channel(rgb_np_img, alpha_channel) -> np.ndarray: + if alpha_channel is not None: + if alpha_channel.shape[:2] != rgb_np_img.shape[:2]: + alpha_channel = cv2.resize( + alpha_channel, dsize=(rgb_np_img.shape[1], rgb_np_img.shape[0]) + ) + rgb_np_img = np.concatenate( + (rgb_np_img, alpha_channel[:, :, np.newaxis]), axis=-1 + ) + return rgb_np_img + + +def adjust_mask(mask: np.ndarray, kernel_size: int, operate): + # fronted brush color "ffcc00bb" + # kernel_size = kernel_size*2+1 + mask[mask >= 127] = 255 + mask[mask < 127] = 0 + + if operate == "reverse": + mask = 255 - mask + else: + kernel = cv2.getStructuringElement( + cv2.MORPH_ELLIPSE, (2 * kernel_size + 1, 2 * kernel_size + 1) + ) + if operate == "expand": + mask = cv2.dilate( + mask, + kernel, + iterations=1, + ) + else: + mask = cv2.erode( + mask, + kernel, + iterations=1, + ) + res_mask = np.zeros((mask.shape[0], mask.shape[1], 4), dtype=np.uint8) + res_mask[mask > 128] = [255, 203, 0, int(255 * 0.73)] + res_mask = cv2.cvtColor(res_mask, cv2.COLOR_BGRA2RGBA) + return res_mask + + +def gen_frontend_mask(bgr_or_gray_mask): + if len(bgr_or_gray_mask.shape) == 3 and bgr_or_gray_mask.shape[2] != 1: + bgr_or_gray_mask = cv2.cvtColor(bgr_or_gray_mask, cv2.COLOR_BGR2GRAY) + + # fronted brush color "ffcc00bb" + # TODO: how to set kernel size? + kernel_size = 9 + bgr_or_gray_mask = cv2.dilate( + bgr_or_gray_mask, + np.ones((kernel_size, kernel_size), np.uint8), + iterations=1, + ) + res_mask = np.zeros( + (bgr_or_gray_mask.shape[0], bgr_or_gray_mask.shape[1], 4), dtype=np.uint8 + ) + res_mask[bgr_or_gray_mask > 128] = [255, 203, 0, int(255 * 0.73)] + res_mask = cv2.cvtColor(res_mask, cv2.COLOR_BGRA2RGBA) + return res_mask diff --git a/py/iopaint/installer.py b/py/iopaint/installer.py new file mode 100644 index 0000000..f255e33 --- /dev/null +++ b/py/iopaint/installer.py @@ -0,0 +1,12 @@ +import subprocess +import sys + + +def install(package): + subprocess.check_call([sys.executable, "-m", "pip", "install", package]) + + +def install_plugins_package(): + install("rembg") + install("realesrgan") + install("gfpgan") diff --git a/py/iopaint/model/__init__.py b/py/iopaint/model/__init__.py new file mode 100644 index 0000000..799e2ec --- /dev/null +++ b/py/iopaint/model/__init__.py @@ -0,0 +1,37 @@ +from .anytext.anytext_model import AnyText +from .controlnet import ControlNet +from .fcf import FcF +from .instruct_pix2pix import InstructPix2Pix +from .kandinsky import Kandinsky22 +from .lama import LaMa +from .ldm import LDM +from .manga import Manga +from .mat import MAT +from .mi_gan import MIGAN +from .opencv2 import OpenCV2 +from .paint_by_example import PaintByExample +from .power_paint.power_paint import PowerPaint +from .sd import SD15, SD2, Anything4, RealisticVision14, SD +from .sdxl import SDXL +from .zits import ZITS + +models = { + LaMa.name: LaMa, + LDM.name: LDM, + ZITS.name: ZITS, + MAT.name: MAT, + FcF.name: FcF, + OpenCV2.name: OpenCV2, + Manga.name: Manga, + MIGAN.name: MIGAN, + SD15.name: SD15, + Anything4.name: Anything4, + RealisticVision14.name: RealisticVision14, + SD2.name: SD2, + PaintByExample.name: PaintByExample, + InstructPix2Pix.name: InstructPix2Pix, + Kandinsky22.name: Kandinsky22, + SDXL.name: SDXL, + PowerPaint.name: PowerPaint, + AnyText.name: AnyText, +} diff --git a/py/iopaint/model/anytext/__init__.py b/py/iopaint/model/anytext/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/py/iopaint/model/anytext/anytext_model.py b/py/iopaint/model/anytext/anytext_model.py new file mode 100644 index 0000000..097ce5c --- /dev/null +++ b/py/iopaint/model/anytext/anytext_model.py @@ -0,0 +1,73 @@ +import torch +from huggingface_hub import hf_hub_download + +from ...const import ANYTEXT_NAME +from ...model.anytext.anytext_pipeline import AnyTextPipeline +from ...model.base import DiffusionInpaintModel +from ...model.utils import get_torch_dtype, is_local_files_only +from ...schema import InpaintRequest + + +class AnyText(DiffusionInpaintModel): + name = ANYTEXT_NAME + pad_mod = 64 + is_erase_model = False + + @staticmethod + def download(local_files_only=False): + hf_hub_download( + repo_id=ANYTEXT_NAME, + filename="model_index.json", + local_files_only=local_files_only, + ) + ckpt_path = hf_hub_download( + repo_id=ANYTEXT_NAME, + filename="pytorch_model.fp16.safetensors", + local_files_only=local_files_only, + ) + font_path = hf_hub_download( + repo_id=ANYTEXT_NAME, + filename="SourceHanSansSC-Medium.otf", + local_files_only=local_files_only, + ) + return ckpt_path, font_path + + def init_model(self, device, **kwargs): + local_files_only = is_local_files_only(**kwargs) + ckpt_path, font_path = self.download(local_files_only) + use_gpu, torch_dtype = get_torch_dtype(device, kwargs.get("no_half", False)) + self.model = AnyTextPipeline( + ckpt_path=ckpt_path, + font_path=font_path, + device=device, + use_fp16=torch_dtype == torch.float16, + ) + self.callback = kwargs.pop("callback", None) + + def forward(self, image, mask, config: InpaintRequest): + """Input image and output image have same size + image: [H, W, C] RGB + mask: [H, W, 1] 255 means area to inpainting + return: BGR IMAGE + """ + height, width = image.shape[:2] + mask = mask.astype("float32") / 255.0 + masked_image = image * (1 - mask) + + # list of rgb ndarray + results, rtn_code, rtn_warning = self.model( + image=image, + masked_image=masked_image, + prompt=config.prompt, + negative_prompt=config.negative_prompt, + num_inference_steps=config.sd_steps, + strength=config.sd_strength, + guidance_scale=config.sd_guidance_scale, + height=height, + width=width, + seed=config.sd_seed, + sort_priority="y", + callback=self.callback + ) + inpainted_rgb_image = results[0][..., ::-1] + return inpainted_rgb_image diff --git a/py/iopaint/model/anytext/anytext_pipeline.py b/py/iopaint/model/anytext/anytext_pipeline.py new file mode 100644 index 0000000..445f943 --- /dev/null +++ b/py/iopaint/model/anytext/anytext_pipeline.py @@ -0,0 +1,403 @@ +""" +AnyText: Multilingual Visual Text Generation And Editing +Paper: https://arxiv.org/abs/2311.03054 +Code: https://github.com/tyxsspa/AnyText +Copyright (c) Alibaba, Inc. and its affiliates. +""" +import os +from pathlib import Path + +from ...model.utils import set_seed +from safetensors.torch import load_file + +os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3" +import torch +import re +import numpy as np +import cv2 +import einops +from PIL import ImageFont +from ...model.anytext.cldm.model import create_model, load_state_dict +from ...model.anytext.cldm.ddim_hacked import DDIMSampler +from ...model.anytext.utils import ( + check_channels, + draw_glyph, + draw_glyph2, +) + + +BBOX_MAX_NUM = 8 +PLACE_HOLDER = "*" +max_chars = 20 + +ANYTEXT_CFG = os.path.join( + os.path.dirname(os.path.abspath(__file__)), "anytext_sd15.yaml" +) + + +def check_limits(tensor): + float16_min = torch.finfo(torch.float16).min + float16_max = torch.finfo(torch.float16).max + + # 检查张量中是否有值小于float16的最小值或大于float16的最大值 + is_below_min = (tensor < float16_min).any() + is_above_max = (tensor > float16_max).any() + + return is_below_min or is_above_max + + +class AnyTextPipeline: + def __init__(self, ckpt_path, font_path, device, use_fp16=True): + self.cfg_path = ANYTEXT_CFG + self.font_path = font_path + self.use_fp16 = use_fp16 + self.device = device + + self.font = ImageFont.truetype(font_path, size=60) + self.model = create_model( + self.cfg_path, + device=self.device, + use_fp16=self.use_fp16, + ) + if self.use_fp16: + self.model = self.model.half() + if Path(ckpt_path).suffix == ".safetensors": + state_dict = load_file(ckpt_path, device="cpu") + else: + state_dict = load_state_dict(ckpt_path, location="cpu") + self.model.load_state_dict(state_dict, strict=False) + self.model = self.model.eval().to(self.device) + self.ddim_sampler = DDIMSampler(self.model, device=self.device) + + def __call__( + self, + prompt: str, + negative_prompt: str, + image: np.ndarray, + masked_image: np.ndarray, + num_inference_steps: int, + strength: float, + guidance_scale: float, + height: int, + width: int, + seed: int, + sort_priority: str = "y", + callback=None, + ): + """ + + Args: + prompt: + negative_prompt: + image: + masked_image: + num_inference_steps: + strength: + guidance_scale: + height: + width: + seed: + sort_priority: x: left-right, y: top-down + + Returns: + result: list of images in numpy.ndarray format + rst_code: 0: normal -1: error 1:warning + rst_info: string of error or warning + + """ + set_seed(seed) + str_warning = "" + + mode = "text-editing" + revise_pos = False + img_count = 1 + ddim_steps = num_inference_steps + w = width + h = height + strength = strength + cfg_scale = guidance_scale + eta = 0.0 + + prompt, texts = self.modify_prompt(prompt) + if prompt is None and texts is None: + return ( + None, + -1, + "You have input Chinese prompt but the translator is not loaded!", + "", + ) + n_lines = len(texts) + if mode in ["text-generation", "gen"]: + edit_image = np.ones((h, w, 3)) * 127.5 # empty mask image + elif mode in ["text-editing", "edit"]: + if masked_image is None or image is None: + return ( + None, + -1, + "Reference image and position image are needed for text editing!", + "", + ) + if isinstance(image, str): + image = cv2.imread(image)[..., ::-1] + assert image is not None, f"Can't read ori_image image from{image}!" + elif isinstance(image, torch.Tensor): + image = image.cpu().numpy() + else: + assert isinstance( + image, np.ndarray + ), f"Unknown format of ori_image: {type(image)}" + edit_image = image.clip(1, 255) # for mask reason + edit_image = check_channels(edit_image) + # edit_image = resize_image( + # edit_image, max_length=768 + # ) # make w h multiple of 64, resize if w or h > max_length + h, w = edit_image.shape[:2] # change h, w by input ref_img + # preprocess pos_imgs(if numpy, make sure it's white pos in black bg) + if masked_image is None: + pos_imgs = np.zeros((w, h, 1)) + if isinstance(masked_image, str): + masked_image = cv2.imread(masked_image)[..., ::-1] + assert ( + masked_image is not None + ), f"Can't read draw_pos image from{masked_image}!" + pos_imgs = 255 - masked_image + elif isinstance(masked_image, torch.Tensor): + pos_imgs = masked_image.cpu().numpy() + else: + assert isinstance( + masked_image, np.ndarray + ), f"Unknown format of draw_pos: {type(masked_image)}" + pos_imgs = 255 - masked_image + pos_imgs = pos_imgs[..., 0:1] + pos_imgs = cv2.convertScaleAbs(pos_imgs) + _, pos_imgs = cv2.threshold(pos_imgs, 254, 255, cv2.THRESH_BINARY) + # seprate pos_imgs + pos_imgs = self.separate_pos_imgs(pos_imgs, sort_priority) + if len(pos_imgs) == 0: + pos_imgs = [np.zeros((h, w, 1))] + if len(pos_imgs) < n_lines: + if n_lines == 1 and texts[0] == " ": + pass # text-to-image without text + else: + raise RuntimeError( + f"{n_lines} text line to draw from prompt, not enough mask area({len(pos_imgs)}) on images" + ) + elif len(pos_imgs) > n_lines: + str_warning = f"Warning: found {len(pos_imgs)} positions that > needed {n_lines} from prompt." + # get pre_pos, poly_list, hint that needed for anytext + pre_pos = [] + poly_list = [] + for input_pos in pos_imgs: + if input_pos.mean() != 0: + input_pos = ( + input_pos[..., np.newaxis] + if len(input_pos.shape) == 2 + else input_pos + ) + poly, pos_img = self.find_polygon(input_pos) + pre_pos += [pos_img / 255.0] + poly_list += [poly] + else: + pre_pos += [np.zeros((h, w, 1))] + poly_list += [None] + np_hint = np.sum(pre_pos, axis=0).clip(0, 1) + # prepare info dict + info = {} + info["glyphs"] = [] + info["gly_line"] = [] + info["positions"] = [] + info["n_lines"] = [len(texts)] * img_count + gly_pos_imgs = [] + for i in range(len(texts)): + text = texts[i] + if len(text) > max_chars: + str_warning = ( + f'"{text}" length > max_chars: {max_chars}, will be cut off...' + ) + text = text[:max_chars] + gly_scale = 2 + if pre_pos[i].mean() != 0: + gly_line = draw_glyph(self.font, text) + glyphs = draw_glyph2( + self.font, + text, + poly_list[i], + scale=gly_scale, + width=w, + height=h, + add_space=False, + ) + gly_pos_img = cv2.drawContours( + glyphs * 255, [poly_list[i] * gly_scale], 0, (255, 255, 255), 1 + ) + if revise_pos: + resize_gly = cv2.resize( + glyphs, (pre_pos[i].shape[1], pre_pos[i].shape[0]) + ) + new_pos = cv2.morphologyEx( + (resize_gly * 255).astype(np.uint8), + cv2.MORPH_CLOSE, + kernel=np.ones( + (resize_gly.shape[0] // 10, resize_gly.shape[1] // 10), + dtype=np.uint8, + ), + iterations=1, + ) + new_pos = ( + new_pos[..., np.newaxis] if len(new_pos.shape) == 2 else new_pos + ) + contours, _ = cv2.findContours( + new_pos, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE + ) + if len(contours) != 1: + str_warning = f"Fail to revise position {i} to bounding rect, remain position unchanged..." + else: + rect = cv2.minAreaRect(contours[0]) + poly = np.int0(cv2.boxPoints(rect)) + pre_pos[i] = ( + cv2.drawContours(new_pos, [poly], -1, 255, -1) / 255.0 + ) + gly_pos_img = cv2.drawContours( + glyphs * 255, [poly * gly_scale], 0, (255, 255, 255), 1 + ) + gly_pos_imgs += [gly_pos_img] # for show + else: + glyphs = np.zeros((h * gly_scale, w * gly_scale, 1)) + gly_line = np.zeros((80, 512, 1)) + gly_pos_imgs += [ + np.zeros((h * gly_scale, w * gly_scale, 1)) + ] # for show + pos = pre_pos[i] + info["glyphs"] += [self.arr2tensor(glyphs, img_count)] + info["gly_line"] += [self.arr2tensor(gly_line, img_count)] + info["positions"] += [self.arr2tensor(pos, img_count)] + # get masked_x + masked_img = ((edit_image.astype(np.float32) / 127.5) - 1.0) * (1 - np_hint) + masked_img = np.transpose(masked_img, (2, 0, 1)) + masked_img = torch.from_numpy(masked_img.copy()).float().to(self.device) + if self.use_fp16: + masked_img = masked_img.half() + encoder_posterior = self.model.encode_first_stage(masked_img[None, ...]) + masked_x = self.model.get_first_stage_encoding(encoder_posterior).detach() + if self.use_fp16: + masked_x = masked_x.half() + info["masked_x"] = torch.cat([masked_x for _ in range(img_count)], dim=0) + + hint = self.arr2tensor(np_hint, img_count) + cond = self.model.get_learned_conditioning( + dict( + c_concat=[hint], + c_crossattn=[[prompt] * img_count], + text_info=info, + ) + ) + un_cond = self.model.get_learned_conditioning( + dict( + c_concat=[hint], + c_crossattn=[[negative_prompt] * img_count], + text_info=info, + ) + ) + shape = (4, h // 8, w // 8) + self.model.control_scales = [strength] * 13 + samples, intermediates = self.ddim_sampler.sample( + ddim_steps, + img_count, + shape, + cond, + verbose=False, + eta=eta, + unconditional_guidance_scale=cfg_scale, + unconditional_conditioning=un_cond, + callback=callback + ) + if self.use_fp16: + samples = samples.half() + x_samples = self.model.decode_first_stage(samples) + x_samples = ( + (einops.rearrange(x_samples, "b c h w -> b h w c") * 127.5 + 127.5) + .cpu() + .numpy() + .clip(0, 255) + .astype(np.uint8) + ) + results = [x_samples[i] for i in range(img_count)] + # if ( + # mode == "edit" and False + # ): # replace backgound in text editing but not ideal yet + # results = [r * np_hint + edit_image * (1 - np_hint) for r in results] + # results = [r.clip(0, 255).astype(np.uint8) for r in results] + # if len(gly_pos_imgs) > 0 and show_debug: + # glyph_bs = np.stack(gly_pos_imgs, axis=2) + # glyph_img = np.sum(glyph_bs, axis=2) * 255 + # glyph_img = glyph_img.clip(0, 255).astype(np.uint8) + # results += [np.repeat(glyph_img, 3, axis=2)] + rst_code = 1 if str_warning else 0 + return results, rst_code, str_warning + + def modify_prompt(self, prompt): + prompt = prompt.replace("“", '"') + prompt = prompt.replace("”", '"') + p = '"(.*?)"' + strs = re.findall(p, prompt) + if len(strs) == 0: + strs = [" "] + else: + for s in strs: + prompt = prompt.replace(f'"{s}"', f" {PLACE_HOLDER} ", 1) + # if self.is_chinese(prompt): + # if self.trans_pipe is None: + # return None, None + # old_prompt = prompt + # prompt = self.trans_pipe(input=prompt + " .")["translation"][:-1] + # print(f"Translate: {old_prompt} --> {prompt}") + return prompt, strs + + # def is_chinese(self, text): + # text = checker._clean_text(text) + # for char in text: + # cp = ord(char) + # if checker._is_chinese_char(cp): + # return True + # return False + + def separate_pos_imgs(self, img, sort_priority, gap=102): + num_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(img) + components = [] + for label in range(1, num_labels): + component = np.zeros_like(img) + component[labels == label] = 255 + components.append((component, centroids[label])) + if sort_priority == "y": + fir, sec = 1, 0 # top-down first + elif sort_priority == "x": + fir, sec = 0, 1 # left-right first + components.sort(key=lambda c: (c[1][fir] // gap, c[1][sec] // gap)) + sorted_components = [c[0] for c in components] + return sorted_components + + def find_polygon(self, image, min_rect=False): + contours, hierarchy = cv2.findContours( + image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE + ) + max_contour = max(contours, key=cv2.contourArea) # get contour with max area + if min_rect: + # get minimum enclosing rectangle + rect = cv2.minAreaRect(max_contour) + poly = np.int0(cv2.boxPoints(rect)) + else: + # get approximate polygon + epsilon = 0.01 * cv2.arcLength(max_contour, True) + poly = cv2.approxPolyDP(max_contour, epsilon, True) + n, _, xy = poly.shape + poly = poly.reshape(n, xy) + cv2.drawContours(image, [poly], -1, 255, -1) + return poly, image + + def arr2tensor(self, arr, bs): + arr = np.transpose(arr, (2, 0, 1)) + _arr = torch.from_numpy(arr.copy()).float().to(self.device) + if self.use_fp16: + _arr = _arr.half() + _arr = torch.stack([_arr for _ in range(bs)], dim=0) + return _arr diff --git a/py/iopaint/model/anytext/anytext_sd15.yaml b/py/iopaint/model/anytext/anytext_sd15.yaml new file mode 100644 index 0000000..d727594 --- /dev/null +++ b/py/iopaint/model/anytext/anytext_sd15.yaml @@ -0,0 +1,99 @@ +model: + target: iopaint.model.anytext.cldm.cldm.ControlLDM + params: + linear_start: 0.00085 + linear_end: 0.0120 + num_timesteps_cond: 1 + log_every_t: 200 + timesteps: 1000 + first_stage_key: "img" + cond_stage_key: "caption" + control_key: "hint" + glyph_key: "glyphs" + position_key: "positions" + image_size: 64 + channels: 4 + cond_stage_trainable: true # need be true when embedding_manager is valid + conditioning_key: crossattn + monitor: val/loss_simple_ema + scale_factor: 0.18215 + use_ema: False + only_mid_control: False + loss_alpha: 0 # perceptual loss, 0.003 + loss_beta: 0 # ctc loss + latin_weight: 1.0 # latin text line may need smaller weigth + with_step_weight: true + use_vae_upsample: true + embedding_manager_config: + target: iopaint.model.anytext.cldm.embedding_manager.EmbeddingManager + params: + valid: true # v6 + emb_type: ocr # ocr, vit, conv + glyph_channels: 1 + position_channels: 1 + add_pos: false + placeholder_string: '*' + + control_stage_config: + target: iopaint.model.anytext.cldm.cldm.ControlNet + params: + image_size: 32 # unused + in_channels: 4 + model_channels: 320 + glyph_channels: 1 + position_channels: 1 + attention_resolutions: [ 4, 2, 1 ] + num_res_blocks: 2 + channel_mult: [ 1, 2, 4, 4 ] + num_heads: 8 + use_spatial_transformer: True + transformer_depth: 1 + context_dim: 768 + use_checkpoint: True + legacy: False + + unet_config: + target: iopaint.model.anytext.cldm.cldm.ControlledUnetModel + params: + image_size: 32 # unused + in_channels: 4 + out_channels: 4 + model_channels: 320 + attention_resolutions: [ 4, 2, 1 ] + num_res_blocks: 2 + channel_mult: [ 1, 2, 4, 4 ] + num_heads: 8 + use_spatial_transformer: True + transformer_depth: 1 + context_dim: 768 + use_checkpoint: True + legacy: False + + first_stage_config: + target: iopaint.model.anytext.ldm.models.autoencoder.AutoencoderKL + params: + embed_dim: 4 + monitor: val/rec_loss + ddconfig: + double_z: true + z_channels: 4 + resolution: 256 + in_channels: 3 + out_ch: 3 + ch: 128 + ch_mult: + - 1 + - 2 + - 4 + - 4 + num_res_blocks: 2 + attn_resolutions: [] + dropout: 0.0 + lossconfig: + target: torch.nn.Identity + + cond_stage_config: + target: iopaint.model.anytext.ldm.modules.encoders.modules.FrozenCLIPEmbedderT3 + params: + version: openai/clip-vit-large-patch14 + use_vision: false # v6 diff --git a/py/iopaint/model/anytext/cldm/__init__.py b/py/iopaint/model/anytext/cldm/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/py/iopaint/model/anytext/cldm/cldm.py b/py/iopaint/model/anytext/cldm/cldm.py new file mode 100644 index 0000000..ad9692a --- /dev/null +++ b/py/iopaint/model/anytext/cldm/cldm.py @@ -0,0 +1,630 @@ +import os +from pathlib import Path + +import einops +import torch +import torch as th +import torch.nn as nn +import copy +from easydict import EasyDict as edict + +from iopaint.model.anytext.ldm.modules.diffusionmodules.util import ( + conv_nd, + linear, + zero_module, + timestep_embedding, +) + +from einops import rearrange, repeat +from iopaint.model.anytext.ldm.modules.attention import SpatialTransformer +from iopaint.model.anytext.ldm.modules.diffusionmodules.openaimodel import UNetModel, TimestepEmbedSequential, ResBlock, Downsample, AttentionBlock +from iopaint.model.anytext.ldm.models.diffusion.ddpm import LatentDiffusion +from iopaint.model.anytext.ldm.util import log_txt_as_img, exists, instantiate_from_config +from iopaint.model.anytext.ldm.models.diffusion.ddim import DDIMSampler +from iopaint.model.anytext.ldm.modules.distributions.distributions import DiagonalGaussianDistribution +from .recognizer import TextRecognizer, create_predictor + +CURRENT_DIR = Path(os.path.dirname(os.path.abspath(__file__))) + + +def count_parameters(model): + return sum(p.numel() for p in model.parameters() if p.requires_grad) + + +class ControlledUnetModel(UNetModel): + def forward(self, x, timesteps=None, context=None, control=None, only_mid_control=False, **kwargs): + hs = [] + with torch.no_grad(): + t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False) + if self.use_fp16: + t_emb = t_emb.half() + emb = self.time_embed(t_emb) + h = x.type(self.dtype) + for module in self.input_blocks: + h = module(h, emb, context) + hs.append(h) + h = self.middle_block(h, emb, context) + + if control is not None: + h += control.pop() + + for i, module in enumerate(self.output_blocks): + if only_mid_control or control is None: + h = torch.cat([h, hs.pop()], dim=1) + else: + h = torch.cat([h, hs.pop() + control.pop()], dim=1) + h = module(h, emb, context) + + h = h.type(x.dtype) + return self.out(h) + + +class ControlNet(nn.Module): + def __init__( + self, + image_size, + in_channels, + model_channels, + glyph_channels, + position_channels, + num_res_blocks, + attention_resolutions, + dropout=0, + channel_mult=(1, 2, 4, 8), + conv_resample=True, + dims=2, + use_checkpoint=False, + use_fp16=False, + num_heads=-1, + num_head_channels=-1, + num_heads_upsample=-1, + use_scale_shift_norm=False, + resblock_updown=False, + use_new_attention_order=False, + use_spatial_transformer=False, # custom transformer support + transformer_depth=1, # custom transformer support + context_dim=None, # custom transformer support + n_embed=None, # custom support for prediction of discrete ids into codebook of first stage vq model + legacy=True, + disable_self_attentions=None, + num_attention_blocks=None, + disable_middle_self_attn=False, + use_linear_in_transformer=False, + ): + super().__init__() + if use_spatial_transformer: + assert context_dim is not None, 'Fool!! You forgot to include the dimension of your cross-attention conditioning...' + + if context_dim is not None: + assert use_spatial_transformer, 'Fool!! You forgot to use the spatial transformer for your cross-attention conditioning...' + from omegaconf.listconfig import ListConfig + if type(context_dim) == ListConfig: + context_dim = list(context_dim) + + if num_heads_upsample == -1: + num_heads_upsample = num_heads + + if num_heads == -1: + assert num_head_channels != -1, 'Either num_heads or num_head_channels has to be set' + + if num_head_channels == -1: + assert num_heads != -1, 'Either num_heads or num_head_channels has to be set' + self.dims = dims + self.image_size = image_size + self.in_channels = in_channels + self.model_channels = model_channels + if isinstance(num_res_blocks, int): + self.num_res_blocks = len(channel_mult) * [num_res_blocks] + else: + if len(num_res_blocks) != len(channel_mult): + raise ValueError("provide num_res_blocks either as an int (globally constant) or " + "as a list/tuple (per-level) with the same length as channel_mult") + self.num_res_blocks = num_res_blocks + if disable_self_attentions is not None: + # should be a list of booleans, indicating whether to disable self-attention in TransformerBlocks or not + assert len(disable_self_attentions) == len(channel_mult) + if num_attention_blocks is not None: + assert len(num_attention_blocks) == len(self.num_res_blocks) + assert all(map(lambda i: self.num_res_blocks[i] >= num_attention_blocks[i], range(len(num_attention_blocks)))) + print(f"Constructor of UNetModel received num_attention_blocks={num_attention_blocks}. " + f"This option has LESS priority than attention_resolutions {attention_resolutions}, " + f"i.e., in cases where num_attention_blocks[i] > 0 but 2**i not in attention_resolutions, " + f"attention will still not be set.") + self.attention_resolutions = attention_resolutions + self.dropout = dropout + self.channel_mult = channel_mult + self.conv_resample = conv_resample + self.use_checkpoint = use_checkpoint + self.use_fp16 = use_fp16 + self.dtype = th.float16 if use_fp16 else th.float32 + self.num_heads = num_heads + self.num_head_channels = num_head_channels + self.num_heads_upsample = num_heads_upsample + self.predict_codebook_ids = n_embed is not None + + time_embed_dim = model_channels * 4 + self.time_embed = nn.Sequential( + linear(model_channels, time_embed_dim), + nn.SiLU(), + linear(time_embed_dim, time_embed_dim), + ) + + self.input_blocks = nn.ModuleList( + [ + TimestepEmbedSequential( + conv_nd(dims, in_channels, model_channels, 3, padding=1) + ) + ] + ) + self.zero_convs = nn.ModuleList([self.make_zero_conv(model_channels)]) + + self.glyph_block = TimestepEmbedSequential( + conv_nd(dims, glyph_channels, 8, 3, padding=1), + nn.SiLU(), + conv_nd(dims, 8, 8, 3, padding=1), + nn.SiLU(), + conv_nd(dims, 8, 16, 3, padding=1, stride=2), + nn.SiLU(), + conv_nd(dims, 16, 16, 3, padding=1), + nn.SiLU(), + conv_nd(dims, 16, 32, 3, padding=1, stride=2), + nn.SiLU(), + conv_nd(dims, 32, 32, 3, padding=1), + nn.SiLU(), + conv_nd(dims, 32, 96, 3, padding=1, stride=2), + nn.SiLU(), + conv_nd(dims, 96, 96, 3, padding=1), + nn.SiLU(), + conv_nd(dims, 96, 256, 3, padding=1, stride=2), + nn.SiLU(), + ) + + self.position_block = TimestepEmbedSequential( + conv_nd(dims, position_channels, 8, 3, padding=1), + nn.SiLU(), + conv_nd(dims, 8, 8, 3, padding=1), + nn.SiLU(), + conv_nd(dims, 8, 16, 3, padding=1, stride=2), + nn.SiLU(), + conv_nd(dims, 16, 16, 3, padding=1), + nn.SiLU(), + conv_nd(dims, 16, 32, 3, padding=1, stride=2), + nn.SiLU(), + conv_nd(dims, 32, 32, 3, padding=1), + nn.SiLU(), + conv_nd(dims, 32, 64, 3, padding=1, stride=2), + nn.SiLU(), + ) + + self.fuse_block = zero_module(conv_nd(dims, 256+64+4, model_channels, 3, padding=1)) + + self._feature_size = model_channels + input_block_chans = [model_channels] + ch = model_channels + ds = 1 + for level, mult in enumerate(channel_mult): + for nr in range(self.num_res_blocks[level]): + layers = [ + ResBlock( + ch, + time_embed_dim, + dropout, + out_channels=mult * model_channels, + dims=dims, + use_checkpoint=use_checkpoint, + use_scale_shift_norm=use_scale_shift_norm, + ) + ] + ch = mult * model_channels + if ds in attention_resolutions: + if num_head_channels == -1: + dim_head = ch // num_heads + else: + num_heads = ch // num_head_channels + dim_head = num_head_channels + if legacy: + # num_heads = 1 + dim_head = ch // num_heads if use_spatial_transformer else num_head_channels + if exists(disable_self_attentions): + disabled_sa = disable_self_attentions[level] + else: + disabled_sa = False + + if not exists(num_attention_blocks) or nr < num_attention_blocks[level]: + layers.append( + AttentionBlock( + ch, + use_checkpoint=use_checkpoint, + num_heads=num_heads, + num_head_channels=dim_head, + use_new_attention_order=use_new_attention_order, + ) if not use_spatial_transformer else SpatialTransformer( + ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim, + disable_self_attn=disabled_sa, use_linear=use_linear_in_transformer, + use_checkpoint=use_checkpoint + ) + ) + self.input_blocks.append(TimestepEmbedSequential(*layers)) + self.zero_convs.append(self.make_zero_conv(ch)) + self._feature_size += ch + input_block_chans.append(ch) + if level != len(channel_mult) - 1: + out_ch = ch + self.input_blocks.append( + TimestepEmbedSequential( + ResBlock( + ch, + time_embed_dim, + dropout, + out_channels=out_ch, + dims=dims, + use_checkpoint=use_checkpoint, + use_scale_shift_norm=use_scale_shift_norm, + down=True, + ) + if resblock_updown + else Downsample( + ch, conv_resample, dims=dims, out_channels=out_ch + ) + ) + ) + ch = out_ch + input_block_chans.append(ch) + self.zero_convs.append(self.make_zero_conv(ch)) + ds *= 2 + self._feature_size += ch + + if num_head_channels == -1: + dim_head = ch // num_heads + else: + num_heads = ch // num_head_channels + dim_head = num_head_channels + if legacy: + # num_heads = 1 + dim_head = ch // num_heads if use_spatial_transformer else num_head_channels + self.middle_block = TimestepEmbedSequential( + ResBlock( + ch, + time_embed_dim, + dropout, + dims=dims, + use_checkpoint=use_checkpoint, + use_scale_shift_norm=use_scale_shift_norm, + ), + AttentionBlock( + ch, + use_checkpoint=use_checkpoint, + num_heads=num_heads, + num_head_channels=dim_head, + use_new_attention_order=use_new_attention_order, + ) if not use_spatial_transformer else SpatialTransformer( # always uses a self-attn + ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim, + disable_self_attn=disable_middle_self_attn, use_linear=use_linear_in_transformer, + use_checkpoint=use_checkpoint + ), + ResBlock( + ch, + time_embed_dim, + dropout, + dims=dims, + use_checkpoint=use_checkpoint, + use_scale_shift_norm=use_scale_shift_norm, + ), + ) + self.middle_block_out = self.make_zero_conv(ch) + self._feature_size += ch + + def make_zero_conv(self, channels): + return TimestepEmbedSequential(zero_module(conv_nd(self.dims, channels, channels, 1, padding=0))) + + def forward(self, x, hint, text_info, timesteps, context, **kwargs): + t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False) + if self.use_fp16: + t_emb = t_emb.half() + emb = self.time_embed(t_emb) + + # guided_hint from text_info + B, C, H, W = x.shape + glyphs = torch.cat(text_info['glyphs'], dim=1).sum(dim=1, keepdim=True) + positions = torch.cat(text_info['positions'], dim=1).sum(dim=1, keepdim=True) + enc_glyph = self.glyph_block(glyphs, emb, context) + enc_pos = self.position_block(positions, emb, context) + guided_hint = self.fuse_block(torch.cat([enc_glyph, enc_pos, text_info['masked_x']], dim=1)) + + outs = [] + + h = x.type(self.dtype) + for module, zero_conv in zip(self.input_blocks, self.zero_convs): + if guided_hint is not None: + h = module(h, emb, context) + h += guided_hint + guided_hint = None + else: + h = module(h, emb, context) + outs.append(zero_conv(h, emb, context)) + + h = self.middle_block(h, emb, context) + outs.append(self.middle_block_out(h, emb, context)) + + return outs + + +class ControlLDM(LatentDiffusion): + + def __init__(self, control_stage_config, control_key, glyph_key, position_key, only_mid_control, loss_alpha=0, loss_beta=0, with_step_weight=False, use_vae_upsample=False, latin_weight=1.0, embedding_manager_config=None, *args, **kwargs): + self.use_fp16 = kwargs.pop('use_fp16', False) + super().__init__(*args, **kwargs) + self.control_model = instantiate_from_config(control_stage_config) + self.control_key = control_key + self.glyph_key = glyph_key + self.position_key = position_key + self.only_mid_control = only_mid_control + self.control_scales = [1.0] * 13 + self.loss_alpha = loss_alpha + self.loss_beta = loss_beta + self.with_step_weight = with_step_weight + self.use_vae_upsample = use_vae_upsample + self.latin_weight = latin_weight + + if embedding_manager_config is not None and embedding_manager_config.params.valid: + self.embedding_manager = self.instantiate_embedding_manager(embedding_manager_config, self.cond_stage_model) + for param in self.embedding_manager.embedding_parameters(): + param.requires_grad = True + else: + self.embedding_manager = None + if self.loss_alpha > 0 or self.loss_beta > 0 or self.embedding_manager: + if embedding_manager_config.params.emb_type == 'ocr': + self.text_predictor = create_predictor().eval() + args = edict() + args.rec_image_shape = "3, 48, 320" + args.rec_batch_num = 6 + args.rec_char_dict_path = str(CURRENT_DIR.parent / "ocr_recog" / "ppocr_keys_v1.txt") + args.use_fp16 = self.use_fp16 + self.cn_recognizer = TextRecognizer(args, self.text_predictor) + for param in self.text_predictor.parameters(): + param.requires_grad = False + if self.embedding_manager: + self.embedding_manager.recog = self.cn_recognizer + + @torch.no_grad() + def get_input(self, batch, k, bs=None, *args, **kwargs): + if self.embedding_manager is None: # fill in full caption + self.fill_caption(batch) + x, c, mx = super().get_input(batch, self.first_stage_key, mask_k='masked_img', *args, **kwargs) + control = batch[self.control_key] # for log_images and loss_alpha, not real control + if bs is not None: + control = control[:bs] + control = control.to(self.device) + control = einops.rearrange(control, 'b h w c -> b c h w') + control = control.to(memory_format=torch.contiguous_format).float() + + inv_mask = batch['inv_mask'] + if bs is not None: + inv_mask = inv_mask[:bs] + inv_mask = inv_mask.to(self.device) + inv_mask = einops.rearrange(inv_mask, 'b h w c -> b c h w') + inv_mask = inv_mask.to(memory_format=torch.contiguous_format).float() + + glyphs = batch[self.glyph_key] + gly_line = batch['gly_line'] + positions = batch[self.position_key] + n_lines = batch['n_lines'] + language = batch['language'] + texts = batch['texts'] + assert len(glyphs) == len(positions) + for i in range(len(glyphs)): + if bs is not None: + glyphs[i] = glyphs[i][:bs] + gly_line[i] = gly_line[i][:bs] + positions[i] = positions[i][:bs] + n_lines = n_lines[:bs] + glyphs[i] = glyphs[i].to(self.device) + gly_line[i] = gly_line[i].to(self.device) + positions[i] = positions[i].to(self.device) + glyphs[i] = einops.rearrange(glyphs[i], 'b h w c -> b c h w') + gly_line[i] = einops.rearrange(gly_line[i], 'b h w c -> b c h w') + positions[i] = einops.rearrange(positions[i], 'b h w c -> b c h w') + glyphs[i] = glyphs[i].to(memory_format=torch.contiguous_format).float() + gly_line[i] = gly_line[i].to(memory_format=torch.contiguous_format).float() + positions[i] = positions[i].to(memory_format=torch.contiguous_format).float() + info = {} + info['glyphs'] = glyphs + info['positions'] = positions + info['n_lines'] = n_lines + info['language'] = language + info['texts'] = texts + info['img'] = batch['img'] # nhwc, (-1,1) + info['masked_x'] = mx + info['gly_line'] = gly_line + info['inv_mask'] = inv_mask + return x, dict(c_crossattn=[c], c_concat=[control], text_info=info) + + def apply_model(self, x_noisy, t, cond, *args, **kwargs): + assert isinstance(cond, dict) + diffusion_model = self.model.diffusion_model + _cond = torch.cat(cond['c_crossattn'], 1) + _hint = torch.cat(cond['c_concat'], 1) + if self.use_fp16: + x_noisy = x_noisy.half() + control = self.control_model(x=x_noisy, timesteps=t, context=_cond, hint=_hint, text_info=cond['text_info']) + control = [c * scale for c, scale in zip(control, self.control_scales)] + eps = diffusion_model(x=x_noisy, timesteps=t, context=_cond, control=control, only_mid_control=self.only_mid_control) + + return eps + + def instantiate_embedding_manager(self, config, embedder): + model = instantiate_from_config(config, embedder=embedder) + return model + + @torch.no_grad() + def get_unconditional_conditioning(self, N): + return self.get_learned_conditioning(dict(c_crossattn=[[""] * N], text_info=None)) + + def get_learned_conditioning(self, c): + if self.cond_stage_forward is None: + if hasattr(self.cond_stage_model, 'encode') and callable(self.cond_stage_model.encode): + if self.embedding_manager is not None and c['text_info'] is not None: + self.embedding_manager.encode_text(c['text_info']) + if isinstance(c, dict): + cond_txt = c['c_crossattn'][0] + else: + cond_txt = c + if self.embedding_manager is not None: + cond_txt = self.cond_stage_model.encode(cond_txt, embedding_manager=self.embedding_manager) + else: + cond_txt = self.cond_stage_model.encode(cond_txt) + if isinstance(c, dict): + c['c_crossattn'][0] = cond_txt + else: + c = cond_txt + if isinstance(c, DiagonalGaussianDistribution): + c = c.mode() + else: + c = self.cond_stage_model(c) + else: + assert hasattr(self.cond_stage_model, self.cond_stage_forward) + c = getattr(self.cond_stage_model, self.cond_stage_forward)(c) + return c + + def fill_caption(self, batch, place_holder='*'): + bs = len(batch['n_lines']) + cond_list = copy.deepcopy(batch[self.cond_stage_key]) + for i in range(bs): + n_lines = batch['n_lines'][i] + if n_lines == 0: + continue + cur_cap = cond_list[i] + for j in range(n_lines): + r_txt = batch['texts'][j][i] + cur_cap = cur_cap.replace(place_holder, f'"{r_txt}"', 1) + cond_list[i] = cur_cap + batch[self.cond_stage_key] = cond_list + + @torch.no_grad() + def log_images(self, batch, N=4, n_row=2, sample=False, ddim_steps=50, ddim_eta=0.0, return_keys=None, + quantize_denoised=True, inpaint=True, plot_denoise_rows=False, plot_progressive_rows=True, + plot_diffusion_rows=False, unconditional_guidance_scale=9.0, unconditional_guidance_label=None, + use_ema_scope=True, + **kwargs): + use_ddim = ddim_steps is not None + + log = dict() + z, c = self.get_input(batch, self.first_stage_key, bs=N) + if self.cond_stage_trainable: + with torch.no_grad(): + c = self.get_learned_conditioning(c) + c_crossattn = c["c_crossattn"][0][:N] + c_cat = c["c_concat"][0][:N] + text_info = c["text_info"] + text_info['glyphs'] = [i[:N] for i in text_info['glyphs']] + text_info['gly_line'] = [i[:N] for i in text_info['gly_line']] + text_info['positions'] = [i[:N] for i in text_info['positions']] + text_info['n_lines'] = text_info['n_lines'][:N] + text_info['masked_x'] = text_info['masked_x'][:N] + text_info['img'] = text_info['img'][:N] + + N = min(z.shape[0], N) + n_row = min(z.shape[0], n_row) + log["reconstruction"] = self.decode_first_stage(z) + log["masked_image"] = self.decode_first_stage(text_info['masked_x']) + log["control"] = c_cat * 2.0 - 1.0 + log["img"] = text_info['img'].permute(0, 3, 1, 2) # log source image if needed + # get glyph + glyph_bs = torch.stack(text_info['glyphs']) + glyph_bs = torch.sum(glyph_bs, dim=0) * 2.0 - 1.0 + log["glyph"] = torch.nn.functional.interpolate(glyph_bs, size=(512, 512), mode='bilinear', align_corners=True,) + # fill caption + if not self.embedding_manager: + self.fill_caption(batch) + captions = batch[self.cond_stage_key] + log["conditioning"] = log_txt_as_img((512, 512), captions, size=16) + + if plot_diffusion_rows: + # get diffusion row + diffusion_row = list() + z_start = z[:n_row] + for t in range(self.num_timesteps): + if t % self.log_every_t == 0 or t == self.num_timesteps - 1: + t = repeat(torch.tensor([t]), '1 -> b', b=n_row) + t = t.to(self.device).long() + noise = torch.randn_like(z_start) + z_noisy = self.q_sample(x_start=z_start, t=t, noise=noise) + diffusion_row.append(self.decode_first_stage(z_noisy)) + + diffusion_row = torch.stack(diffusion_row) # n_log_step, n_row, C, H, W + diffusion_grid = rearrange(diffusion_row, 'n b c h w -> b n c h w') + diffusion_grid = rearrange(diffusion_grid, 'b n c h w -> (b n) c h w') + diffusion_grid = make_grid(diffusion_grid, nrow=diffusion_row.shape[0]) + log["diffusion_row"] = diffusion_grid + + if sample: + # get denoise row + samples, z_denoise_row = self.sample_log(cond={"c_concat": [c_cat], "c_crossattn": [c], "text_info": text_info}, + batch_size=N, ddim=use_ddim, + ddim_steps=ddim_steps, eta=ddim_eta) + x_samples = self.decode_first_stage(samples) + log["samples"] = x_samples + if plot_denoise_rows: + denoise_grid = self._get_denoise_row_from_list(z_denoise_row) + log["denoise_row"] = denoise_grid + + if unconditional_guidance_scale > 1.0: + uc_cross = self.get_unconditional_conditioning(N) + uc_cat = c_cat # torch.zeros_like(c_cat) + uc_full = {"c_concat": [uc_cat], "c_crossattn": [uc_cross['c_crossattn'][0]], "text_info": text_info} + samples_cfg, tmps = self.sample_log(cond={"c_concat": [c_cat], "c_crossattn": [c_crossattn], "text_info": text_info}, + batch_size=N, ddim=use_ddim, + ddim_steps=ddim_steps, eta=ddim_eta, + unconditional_guidance_scale=unconditional_guidance_scale, + unconditional_conditioning=uc_full, + ) + x_samples_cfg = self.decode_first_stage(samples_cfg) + log[f"samples_cfg_scale_{unconditional_guidance_scale:.2f}"] = x_samples_cfg + pred_x0 = False # wether log pred_x0 + if pred_x0: + for idx in range(len(tmps['pred_x0'])): + pred_x0 = self.decode_first_stage(tmps['pred_x0'][idx]) + log[f"pred_x0_{tmps['index'][idx]}"] = pred_x0 + + return log + + @torch.no_grad() + def sample_log(self, cond, batch_size, ddim, ddim_steps, **kwargs): + ddim_sampler = DDIMSampler(self) + b, c, h, w = cond["c_concat"][0].shape + shape = (self.channels, h // 8, w // 8) + samples, intermediates = ddim_sampler.sample(ddim_steps, batch_size, shape, cond, verbose=False, log_every_t=5, **kwargs) + return samples, intermediates + + def configure_optimizers(self): + lr = self.learning_rate + params = list(self.control_model.parameters()) + if self.embedding_manager: + params += list(self.embedding_manager.embedding_parameters()) + if not self.sd_locked: + # params += list(self.model.diffusion_model.input_blocks.parameters()) + # params += list(self.model.diffusion_model.middle_block.parameters()) + params += list(self.model.diffusion_model.output_blocks.parameters()) + params += list(self.model.diffusion_model.out.parameters()) + if self.unlockKV: + nCount = 0 + for name, param in self.model.diffusion_model.named_parameters(): + if 'attn2.to_k' in name or 'attn2.to_v' in name: + params += [param] + nCount += 1 + print(f'Cross attention is unlocked, and {nCount} Wk or Wv are added to potimizers!!!') + + opt = torch.optim.AdamW(params, lr=lr) + return opt + + def low_vram_shift(self, is_diffusing): + if is_diffusing: + self.model = self.model.cuda() + self.control_model = self.control_model.cuda() + self.first_stage_model = self.first_stage_model.cpu() + self.cond_stage_model = self.cond_stage_model.cpu() + else: + self.model = self.model.cpu() + self.control_model = self.control_model.cpu() + self.first_stage_model = self.first_stage_model.cuda() + self.cond_stage_model = self.cond_stage_model.cuda() diff --git a/py/iopaint/model/anytext/cldm/ddim_hacked.py b/py/iopaint/model/anytext/cldm/ddim_hacked.py new file mode 100644 index 0000000..b23a883 --- /dev/null +++ b/py/iopaint/model/anytext/cldm/ddim_hacked.py @@ -0,0 +1,486 @@ +"""SAMPLING ONLY.""" + +import torch +import numpy as np +from tqdm import tqdm + +from iopaint.model.anytext.ldm.modules.diffusionmodules.util import ( + make_ddim_sampling_parameters, + make_ddim_timesteps, + noise_like, + extract_into_tensor, +) + + +class DDIMSampler(object): + def __init__(self, model, device, schedule="linear", **kwargs): + super().__init__() + self.device = device + self.model = model + self.ddpm_num_timesteps = model.num_timesteps + self.schedule = schedule + + def register_buffer(self, name, attr): + if type(attr) == torch.Tensor: + if attr.device != torch.device(self.device): + attr = attr.to(torch.device(self.device)) + setattr(self, name, attr) + + def make_schedule( + self, ddim_num_steps, ddim_discretize="uniform", ddim_eta=0.0, verbose=True + ): + self.ddim_timesteps = make_ddim_timesteps( + ddim_discr_method=ddim_discretize, + num_ddim_timesteps=ddim_num_steps, + num_ddpm_timesteps=self.ddpm_num_timesteps, + verbose=verbose, + ) + alphas_cumprod = self.model.alphas_cumprod + assert ( + alphas_cumprod.shape[0] == self.ddpm_num_timesteps + ), "alphas have to be defined for each timestep" + to_torch = lambda x: x.clone().detach().to(torch.float32).to(self.device) + + self.register_buffer("betas", to_torch(self.model.betas)) + self.register_buffer("alphas_cumprod", to_torch(alphas_cumprod)) + self.register_buffer( + "alphas_cumprod_prev", to_torch(self.model.alphas_cumprod_prev) + ) + + # calculations for diffusion q(x_t | x_{t-1}) and others + self.register_buffer( + "sqrt_alphas_cumprod", to_torch(np.sqrt(alphas_cumprod.cpu())) + ) + self.register_buffer( + "sqrt_one_minus_alphas_cumprod", + to_torch(np.sqrt(1.0 - alphas_cumprod.cpu())), + ) + self.register_buffer( + "log_one_minus_alphas_cumprod", to_torch(np.log(1.0 - alphas_cumprod.cpu())) + ) + self.register_buffer( + "sqrt_recip_alphas_cumprod", to_torch(np.sqrt(1.0 / alphas_cumprod.cpu())) + ) + self.register_buffer( + "sqrt_recipm1_alphas_cumprod", + to_torch(np.sqrt(1.0 / alphas_cumprod.cpu() - 1)), + ) + + # ddim sampling parameters + ddim_sigmas, ddim_alphas, ddim_alphas_prev = make_ddim_sampling_parameters( + alphacums=alphas_cumprod.cpu(), + ddim_timesteps=self.ddim_timesteps, + eta=ddim_eta, + verbose=verbose, + ) + self.register_buffer("ddim_sigmas", ddim_sigmas) + self.register_buffer("ddim_alphas", ddim_alphas) + self.register_buffer("ddim_alphas_prev", ddim_alphas_prev) + self.register_buffer("ddim_sqrt_one_minus_alphas", np.sqrt(1.0 - ddim_alphas)) + sigmas_for_original_sampling_steps = ddim_eta * torch.sqrt( + (1 - self.alphas_cumprod_prev) + / (1 - self.alphas_cumprod) + * (1 - self.alphas_cumprod / self.alphas_cumprod_prev) + ) + self.register_buffer( + "ddim_sigmas_for_original_num_steps", sigmas_for_original_sampling_steps + ) + + @torch.no_grad() + def sample( + self, + S, + batch_size, + shape, + conditioning=None, + callback=None, + normals_sequence=None, + img_callback=None, + quantize_x0=False, + eta=0.0, + mask=None, + x0=None, + temperature=1.0, + noise_dropout=0.0, + score_corrector=None, + corrector_kwargs=None, + verbose=True, + x_T=None, + log_every_t=100, + unconditional_guidance_scale=1.0, + unconditional_conditioning=None, # this has to come in the same format as the conditioning, # e.g. as encoded tokens, ... + dynamic_threshold=None, + ucg_schedule=None, + **kwargs, + ): + if conditioning is not None: + if isinstance(conditioning, dict): + ctmp = conditioning[list(conditioning.keys())[0]] + while isinstance(ctmp, list): + ctmp = ctmp[0] + cbs = ctmp.shape[0] + if cbs != batch_size: + print( + f"Warning: Got {cbs} conditionings but batch-size is {batch_size}" + ) + + elif isinstance(conditioning, list): + for ctmp in conditioning: + if ctmp.shape[0] != batch_size: + print( + f"Warning: Got {cbs} conditionings but batch-size is {batch_size}" + ) + + else: + if conditioning.shape[0] != batch_size: + print( + f"Warning: Got {conditioning.shape[0]} conditionings but batch-size is {batch_size}" + ) + + self.make_schedule(ddim_num_steps=S, ddim_eta=eta, verbose=verbose) + # sampling + C, H, W = shape + size = (batch_size, C, H, W) + print(f"Data shape for DDIM sampling is {size}, eta {eta}") + + samples, intermediates = self.ddim_sampling( + conditioning, + size, + callback=callback, + img_callback=img_callback, + quantize_denoised=quantize_x0, + mask=mask, + x0=x0, + ddim_use_original_steps=False, + noise_dropout=noise_dropout, + temperature=temperature, + score_corrector=score_corrector, + corrector_kwargs=corrector_kwargs, + x_T=x_T, + log_every_t=log_every_t, + unconditional_guidance_scale=unconditional_guidance_scale, + unconditional_conditioning=unconditional_conditioning, + dynamic_threshold=dynamic_threshold, + ucg_schedule=ucg_schedule, + ) + return samples, intermediates + + @torch.no_grad() + def ddim_sampling( + self, + cond, + shape, + x_T=None, + ddim_use_original_steps=False, + callback=None, + timesteps=None, + quantize_denoised=False, + mask=None, + x0=None, + img_callback=None, + log_every_t=100, + temperature=1.0, + noise_dropout=0.0, + score_corrector=None, + corrector_kwargs=None, + unconditional_guidance_scale=1.0, + unconditional_conditioning=None, + dynamic_threshold=None, + ucg_schedule=None, + ): + device = self.model.betas.device + b = shape[0] + if x_T is None: + img = torch.randn(shape, device=device) + else: + img = x_T + + if timesteps is None: + timesteps = ( + self.ddpm_num_timesteps + if ddim_use_original_steps + else self.ddim_timesteps + ) + elif timesteps is not None and not ddim_use_original_steps: + subset_end = ( + int( + min(timesteps / self.ddim_timesteps.shape[0], 1) + * self.ddim_timesteps.shape[0] + ) + - 1 + ) + timesteps = self.ddim_timesteps[:subset_end] + + intermediates = {"x_inter": [img], "pred_x0": [img]} + time_range = ( + reversed(range(0, timesteps)) + if ddim_use_original_steps + else np.flip(timesteps) + ) + total_steps = timesteps if ddim_use_original_steps else timesteps.shape[0] + print(f"Running DDIM Sampling with {total_steps} timesteps") + + iterator = tqdm(time_range, desc="DDIM Sampler", total=total_steps) + + for i, step in enumerate(iterator): + index = total_steps - i - 1 + ts = torch.full((b,), step, device=device, dtype=torch.long) + + if mask is not None: + assert x0 is not None + img_orig = self.model.q_sample( + x0, ts + ) # TODO: deterministic forward pass? + img = img_orig * mask + (1.0 - mask) * img + + if ucg_schedule is not None: + assert len(ucg_schedule) == len(time_range) + unconditional_guidance_scale = ucg_schedule[i] + + outs = self.p_sample_ddim( + img, + cond, + ts, + index=index, + use_original_steps=ddim_use_original_steps, + quantize_denoised=quantize_denoised, + temperature=temperature, + noise_dropout=noise_dropout, + score_corrector=score_corrector, + corrector_kwargs=corrector_kwargs, + unconditional_guidance_scale=unconditional_guidance_scale, + unconditional_conditioning=unconditional_conditioning, + dynamic_threshold=dynamic_threshold, + ) + img, pred_x0 = outs + if callback: + callback(None, i, None, None) + if img_callback: + img_callback(pred_x0, i) + + if index % log_every_t == 0 or index == total_steps - 1: + intermediates["x_inter"].append(img) + intermediates["pred_x0"].append(pred_x0) + + return img, intermediates + + @torch.no_grad() + def p_sample_ddim( + self, + x, + c, + t, + index, + repeat_noise=False, + use_original_steps=False, + quantize_denoised=False, + temperature=1.0, + noise_dropout=0.0, + score_corrector=None, + corrector_kwargs=None, + unconditional_guidance_scale=1.0, + unconditional_conditioning=None, + dynamic_threshold=None, + ): + b, *_, device = *x.shape, x.device + + if unconditional_conditioning is None or unconditional_guidance_scale == 1.0: + model_output = self.model.apply_model(x, t, c) + else: + model_t = self.model.apply_model(x, t, c) + model_uncond = self.model.apply_model(x, t, unconditional_conditioning) + model_output = model_uncond + unconditional_guidance_scale * ( + model_t - model_uncond + ) + + if self.model.parameterization == "v": + e_t = self.model.predict_eps_from_z_and_v(x, t, model_output) + else: + e_t = model_output + + if score_corrector is not None: + assert self.model.parameterization == "eps", "not implemented" + e_t = score_corrector.modify_score( + self.model, e_t, x, t, c, **corrector_kwargs + ) + + alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas + alphas_prev = ( + self.model.alphas_cumprod_prev + if use_original_steps + else self.ddim_alphas_prev + ) + sqrt_one_minus_alphas = ( + self.model.sqrt_one_minus_alphas_cumprod + if use_original_steps + else self.ddim_sqrt_one_minus_alphas + ) + sigmas = ( + self.model.ddim_sigmas_for_original_num_steps + if use_original_steps + else self.ddim_sigmas + ) + # select parameters corresponding to the currently considered timestep + a_t = torch.full((b, 1, 1, 1), alphas[index], device=device) + a_prev = torch.full((b, 1, 1, 1), alphas_prev[index], device=device) + sigma_t = torch.full((b, 1, 1, 1), sigmas[index], device=device) + sqrt_one_minus_at = torch.full( + (b, 1, 1, 1), sqrt_one_minus_alphas[index], device=device + ) + + # current prediction for x_0 + if self.model.parameterization != "v": + pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt() + else: + pred_x0 = self.model.predict_start_from_z_and_v(x, t, model_output) + + if quantize_denoised: + pred_x0, _, *_ = self.model.first_stage_model.quantize(pred_x0) + + if dynamic_threshold is not None: + raise NotImplementedError() + + # direction pointing to x_t + dir_xt = (1.0 - a_prev - sigma_t**2).sqrt() * e_t + noise = sigma_t * noise_like(x.shape, device, repeat_noise) * temperature + if noise_dropout > 0.0: + noise = torch.nn.functional.dropout(noise, p=noise_dropout) + x_prev = a_prev.sqrt() * pred_x0 + dir_xt + noise + return x_prev, pred_x0 + + @torch.no_grad() + def encode( + self, + x0, + c, + t_enc, + use_original_steps=False, + return_intermediates=None, + unconditional_guidance_scale=1.0, + unconditional_conditioning=None, + callback=None, + ): + timesteps = ( + np.arange(self.ddpm_num_timesteps) + if use_original_steps + else self.ddim_timesteps + ) + num_reference_steps = timesteps.shape[0] + + assert t_enc <= num_reference_steps + num_steps = t_enc + + if use_original_steps: + alphas_next = self.alphas_cumprod[:num_steps] + alphas = self.alphas_cumprod_prev[:num_steps] + else: + alphas_next = self.ddim_alphas[:num_steps] + alphas = torch.tensor(self.ddim_alphas_prev[:num_steps]) + + x_next = x0 + intermediates = [] + inter_steps = [] + for i in tqdm(range(num_steps), desc="Encoding Image"): + t = torch.full( + (x0.shape[0],), timesteps[i], device=self.model.device, dtype=torch.long + ) + if unconditional_guidance_scale == 1.0: + noise_pred = self.model.apply_model(x_next, t, c) + else: + assert unconditional_conditioning is not None + e_t_uncond, noise_pred = torch.chunk( + self.model.apply_model( + torch.cat((x_next, x_next)), + torch.cat((t, t)), + torch.cat((unconditional_conditioning, c)), + ), + 2, + ) + noise_pred = e_t_uncond + unconditional_guidance_scale * ( + noise_pred - e_t_uncond + ) + + xt_weighted = (alphas_next[i] / alphas[i]).sqrt() * x_next + weighted_noise_pred = ( + alphas_next[i].sqrt() + * ((1 / alphas_next[i] - 1).sqrt() - (1 / alphas[i] - 1).sqrt()) + * noise_pred + ) + x_next = xt_weighted + weighted_noise_pred + if ( + return_intermediates + and i % (num_steps // return_intermediates) == 0 + and i < num_steps - 1 + ): + intermediates.append(x_next) + inter_steps.append(i) + elif return_intermediates and i >= num_steps - 2: + intermediates.append(x_next) + inter_steps.append(i) + if callback: + callback(i) + + out = {"x_encoded": x_next, "intermediate_steps": inter_steps} + if return_intermediates: + out.update({"intermediates": intermediates}) + return x_next, out + + @torch.no_grad() + def stochastic_encode(self, x0, t, use_original_steps=False, noise=None): + # fast, but does not allow for exact reconstruction + # t serves as an index to gather the correct alphas + if use_original_steps: + sqrt_alphas_cumprod = self.sqrt_alphas_cumprod + sqrt_one_minus_alphas_cumprod = self.sqrt_one_minus_alphas_cumprod + else: + sqrt_alphas_cumprod = torch.sqrt(self.ddim_alphas) + sqrt_one_minus_alphas_cumprod = self.ddim_sqrt_one_minus_alphas + + if noise is None: + noise = torch.randn_like(x0) + return ( + extract_into_tensor(sqrt_alphas_cumprod, t, x0.shape) * x0 + + extract_into_tensor(sqrt_one_minus_alphas_cumprod, t, x0.shape) * noise + ) + + @torch.no_grad() + def decode( + self, + x_latent, + cond, + t_start, + unconditional_guidance_scale=1.0, + unconditional_conditioning=None, + use_original_steps=False, + callback=None, + ): + timesteps = ( + np.arange(self.ddpm_num_timesteps) + if use_original_steps + else self.ddim_timesteps + ) + timesteps = timesteps[:t_start] + + time_range = np.flip(timesteps) + total_steps = timesteps.shape[0] + print(f"Running DDIM Sampling with {total_steps} timesteps") + + iterator = tqdm(time_range, desc="Decoding image", total=total_steps) + x_dec = x_latent + for i, step in enumerate(iterator): + index = total_steps - i - 1 + ts = torch.full( + (x_latent.shape[0],), step, device=x_latent.device, dtype=torch.long + ) + x_dec, _ = self.p_sample_ddim( + x_dec, + cond, + ts, + index=index, + use_original_steps=use_original_steps, + unconditional_guidance_scale=unconditional_guidance_scale, + unconditional_conditioning=unconditional_conditioning, + ) + if callback: + callback(i) + return x_dec diff --git a/py/iopaint/model/anytext/cldm/embedding_manager.py b/py/iopaint/model/anytext/cldm/embedding_manager.py new file mode 100644 index 0000000..6ccf8a9 --- /dev/null +++ b/py/iopaint/model/anytext/cldm/embedding_manager.py @@ -0,0 +1,165 @@ +''' +Copyright (c) Alibaba, Inc. and its affiliates. +''' +import torch +import torch.nn as nn +import torch.nn.functional as F +from functools import partial +from iopaint.model.anytext.ldm.modules.diffusionmodules.util import conv_nd, linear + + +def get_clip_token_for_string(tokenizer, string): + batch_encoding = tokenizer(string, truncation=True, max_length=77, return_length=True, + return_overflowing_tokens=False, padding="max_length", return_tensors="pt") + tokens = batch_encoding["input_ids"] + assert torch.count_nonzero(tokens - 49407) == 2, f"String '{string}' maps to more than a single token. Please use another string" + return tokens[0, 1] + + +def get_bert_token_for_string(tokenizer, string): + token = tokenizer(string) + assert torch.count_nonzero(token) == 3, f"String '{string}' maps to more than a single token. Please use another string" + token = token[0, 1] + return token + + +def get_clip_vision_emb(encoder, processor, img): + _img = img.repeat(1, 3, 1, 1)*255 + inputs = processor(images=_img, return_tensors="pt") + inputs['pixel_values'] = inputs['pixel_values'].to(img.device) + outputs = encoder(**inputs) + emb = outputs.image_embeds + return emb + + +def get_recog_emb(encoder, img_list): + _img_list = [(img.repeat(1, 3, 1, 1)*255)[0] for img in img_list] + encoder.predictor.eval() + _, preds_neck = encoder.pred_imglist(_img_list, show_debug=False) + return preds_neck + + +def pad_H(x): + _, _, H, W = x.shape + p_top = (W - H) // 2 + p_bot = W - H - p_top + return F.pad(x, (0, 0, p_top, p_bot)) + + +class EncodeNet(nn.Module): + def __init__(self, in_channels, out_channels): + super(EncodeNet, self).__init__() + chan = 16 + n_layer = 4 # downsample + + self.conv1 = conv_nd(2, in_channels, chan, 3, padding=1) + self.conv_list = nn.ModuleList([]) + _c = chan + for i in range(n_layer): + self.conv_list.append(conv_nd(2, _c, _c*2, 3, padding=1, stride=2)) + _c *= 2 + self.conv2 = conv_nd(2, _c, out_channels, 3, padding=1) + self.avgpool = nn.AdaptiveAvgPool2d(1) + self.act = nn.SiLU() + + def forward(self, x): + x = self.act(self.conv1(x)) + for layer in self.conv_list: + x = self.act(layer(x)) + x = self.act(self.conv2(x)) + x = self.avgpool(x) + x = x.view(x.size(0), -1) + return x + + +class EmbeddingManager(nn.Module): + def __init__( + self, + embedder, + valid=True, + glyph_channels=20, + position_channels=1, + placeholder_string='*', + add_pos=False, + emb_type='ocr', + **kwargs + ): + super().__init__() + if hasattr(embedder, 'tokenizer'): # using Stable Diffusion's CLIP encoder + get_token_for_string = partial(get_clip_token_for_string, embedder.tokenizer) + token_dim = 768 + if hasattr(embedder, 'vit'): + assert emb_type == 'vit' + self.get_vision_emb = partial(get_clip_vision_emb, embedder.vit, embedder.processor) + self.get_recog_emb = None + else: # using LDM's BERT encoder + get_token_for_string = partial(get_bert_token_for_string, embedder.tknz_fn) + token_dim = 1280 + self.token_dim = token_dim + self.emb_type = emb_type + + self.add_pos = add_pos + if add_pos: + self.position_encoder = EncodeNet(position_channels, token_dim) + if emb_type == 'ocr': + self.proj = linear(40*64, token_dim) + if emb_type == 'conv': + self.glyph_encoder = EncodeNet(glyph_channels, token_dim) + + self.placeholder_token = get_token_for_string(placeholder_string) + + def encode_text(self, text_info): + if self.get_recog_emb is None and self.emb_type == 'ocr': + self.get_recog_emb = partial(get_recog_emb, self.recog) + + gline_list = [] + pos_list = [] + for i in range(len(text_info['n_lines'])): # sample index in a batch + n_lines = text_info['n_lines'][i] + for j in range(n_lines): # line + gline_list += [text_info['gly_line'][j][i:i+1]] + if self.add_pos: + pos_list += [text_info['positions'][j][i:i+1]] + + if len(gline_list) > 0: + if self.emb_type == 'ocr': + recog_emb = self.get_recog_emb(gline_list) + enc_glyph = self.proj(recog_emb.reshape(recog_emb.shape[0], -1)) + elif self.emb_type == 'vit': + enc_glyph = self.get_vision_emb(pad_H(torch.cat(gline_list, dim=0))) + elif self.emb_type == 'conv': + enc_glyph = self.glyph_encoder(pad_H(torch.cat(gline_list, dim=0))) + if self.add_pos: + enc_pos = self.position_encoder(torch.cat(gline_list, dim=0)) + enc_glyph = enc_glyph+enc_pos + + self.text_embs_all = [] + n_idx = 0 + for i in range(len(text_info['n_lines'])): # sample index in a batch + n_lines = text_info['n_lines'][i] + text_embs = [] + for j in range(n_lines): # line + text_embs += [enc_glyph[n_idx:n_idx+1]] + n_idx += 1 + self.text_embs_all += [text_embs] + + def forward( + self, + tokenized_text, + embedded_text, + ): + b, device = tokenized_text.shape[0], tokenized_text.device + for i in range(b): + idx = tokenized_text[i] == self.placeholder_token.to(device) + if sum(idx) > 0: + if i >= len(self.text_embs_all): + print('truncation for log images...') + break + text_emb = torch.cat(self.text_embs_all[i], dim=0) + if sum(idx) != len(text_emb): + print('truncation for long caption...') + embedded_text[i][idx] = text_emb[:sum(idx)] + return embedded_text + + def embedding_parameters(self): + return self.parameters() diff --git a/py/iopaint/model/anytext/cldm/hack.py b/py/iopaint/model/anytext/cldm/hack.py new file mode 100644 index 0000000..05afe5f --- /dev/null +++ b/py/iopaint/model/anytext/cldm/hack.py @@ -0,0 +1,111 @@ +import torch +import einops + +import iopaint.model.anytext.ldm.modules.encoders.modules +import iopaint.model.anytext.ldm.modules.attention + +from transformers import logging +from iopaint.model.anytext.ldm.modules.attention import default + + +def disable_verbosity(): + logging.set_verbosity_error() + print('logging improved.') + return + + +def enable_sliced_attention(): + iopaint.model.anytext.ldm.modules.attention.CrossAttention.forward = _hacked_sliced_attentin_forward + print('Enabled sliced_attention.') + return + + +def hack_everything(clip_skip=0): + disable_verbosity() + iopaint.model.anytext.ldm.modules.encoders.modules.FrozenCLIPEmbedder.forward = _hacked_clip_forward + iopaint.model.anytext.ldm.modules.encoders.modules.FrozenCLIPEmbedder.clip_skip = clip_skip + print('Enabled clip hacks.') + return + + +# Written by Lvmin +def _hacked_clip_forward(self, text): + PAD = self.tokenizer.pad_token_id + EOS = self.tokenizer.eos_token_id + BOS = self.tokenizer.bos_token_id + + def tokenize(t): + return self.tokenizer(t, truncation=False, add_special_tokens=False)["input_ids"] + + def transformer_encode(t): + if self.clip_skip > 1: + rt = self.transformer(input_ids=t, output_hidden_states=True) + return self.transformer.text_model.final_layer_norm(rt.hidden_states[-self.clip_skip]) + else: + return self.transformer(input_ids=t, output_hidden_states=False).last_hidden_state + + def split(x): + return x[75 * 0: 75 * 1], x[75 * 1: 75 * 2], x[75 * 2: 75 * 3] + + def pad(x, p, i): + return x[:i] if len(x) >= i else x + [p] * (i - len(x)) + + raw_tokens_list = tokenize(text) + tokens_list = [] + + for raw_tokens in raw_tokens_list: + raw_tokens_123 = split(raw_tokens) + raw_tokens_123 = [[BOS] + raw_tokens_i + [EOS] for raw_tokens_i in raw_tokens_123] + raw_tokens_123 = [pad(raw_tokens_i, PAD, 77) for raw_tokens_i in raw_tokens_123] + tokens_list.append(raw_tokens_123) + + tokens_list = torch.IntTensor(tokens_list).to(self.device) + + feed = einops.rearrange(tokens_list, 'b f i -> (b f) i') + y = transformer_encode(feed) + z = einops.rearrange(y, '(b f) i c -> b (f i) c', f=3) + + return z + + +# Stolen from https://github.com/basujindal/stable-diffusion/blob/main/optimizedSD/splitAttention.py +def _hacked_sliced_attentin_forward(self, x, context=None, mask=None): + h = self.heads + + q = self.to_q(x) + context = default(context, x) + k = self.to_k(context) + v = self.to_v(context) + del context, x + + q, k, v = map(lambda t: einops.rearrange(t, 'b n (h d) -> (b h) n d', h=h), (q, k, v)) + + limit = k.shape[0] + att_step = 1 + q_chunks = list(torch.tensor_split(q, limit // att_step, dim=0)) + k_chunks = list(torch.tensor_split(k, limit // att_step, dim=0)) + v_chunks = list(torch.tensor_split(v, limit // att_step, dim=0)) + + q_chunks.reverse() + k_chunks.reverse() + v_chunks.reverse() + sim = torch.zeros(q.shape[0], q.shape[1], v.shape[2], device=q.device) + del k, q, v + for i in range(0, limit, att_step): + q_buffer = q_chunks.pop() + k_buffer = k_chunks.pop() + v_buffer = v_chunks.pop() + sim_buffer = torch.einsum('b i d, b j d -> b i j', q_buffer, k_buffer) * self.scale + + del k_buffer, q_buffer + # attention, what we cannot get enough of, by chunks + + sim_buffer = sim_buffer.softmax(dim=-1) + + sim_buffer = torch.einsum('b i j, b j d -> b i d', sim_buffer, v_buffer) + del v_buffer + sim[i:i + att_step, :, :] = sim_buffer + + del sim_buffer + sim = einops.rearrange(sim, '(b h) n d -> b n (h d)', h=h) + return self.to_out(sim) diff --git a/py/iopaint/model/anytext/cldm/model.py b/py/iopaint/model/anytext/cldm/model.py new file mode 100644 index 0000000..688f2ed --- /dev/null +++ b/py/iopaint/model/anytext/cldm/model.py @@ -0,0 +1,40 @@ +import os +import torch + +from omegaconf import OmegaConf +from iopaint.model.anytext.ldm.util import instantiate_from_config + + +def get_state_dict(d): + return d.get("state_dict", d) + + +def load_state_dict(ckpt_path, location="cpu"): + _, extension = os.path.splitext(ckpt_path) + if extension.lower() == ".safetensors": + import safetensors.torch + + state_dict = safetensors.torch.load_file(ckpt_path, device=location) + else: + state_dict = get_state_dict( + torch.load(ckpt_path, map_location=torch.device(location)) + ) + state_dict = get_state_dict(state_dict) + print(f"Loaded state_dict from [{ckpt_path}]") + return state_dict + + +def create_model(config_path, device, cond_stage_path=None, use_fp16=False): + config = OmegaConf.load(config_path) + # if cond_stage_path: + # config.model.params.cond_stage_config.params.version = ( + # cond_stage_path # use pre-downloaded ckpts, in case blocked + # ) + config.model.params.cond_stage_config.params.device = str(device) + if use_fp16: + config.model.params.use_fp16 = True + config.model.params.control_stage_config.params.use_fp16 = True + config.model.params.unet_config.params.use_fp16 = True + model = instantiate_from_config(config.model).cpu() + print(f"Loaded model config from [{config_path}]") + return model diff --git a/py/iopaint/model/anytext/cldm/recognizer.py b/py/iopaint/model/anytext/cldm/recognizer.py new file mode 100644 index 0000000..0621512 --- /dev/null +++ b/py/iopaint/model/anytext/cldm/recognizer.py @@ -0,0 +1,300 @@ +""" +Copyright (c) Alibaba, Inc. and its affiliates. +""" +import os +import cv2 +import numpy as np +import math +import traceback +from easydict import EasyDict as edict +import time +from iopaint.model.anytext.ocr_recog.RecModel import RecModel +import torch +import torch.nn.functional as F + + +def min_bounding_rect(img): + ret, thresh = cv2.threshold(img, 127, 255, 0) + contours, hierarchy = cv2.findContours( + thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE + ) + if len(contours) == 0: + print("Bad contours, using fake bbox...") + return np.array([[0, 0], [100, 0], [100, 100], [0, 100]]) + max_contour = max(contours, key=cv2.contourArea) + rect = cv2.minAreaRect(max_contour) + box = cv2.boxPoints(rect) + box = np.int0(box) + # sort + x_sorted = sorted(box, key=lambda x: x[0]) + left = x_sorted[:2] + right = x_sorted[2:] + left = sorted(left, key=lambda x: x[1]) + (tl, bl) = left + right = sorted(right, key=lambda x: x[1]) + (tr, br) = right + if tl[1] > bl[1]: + (tl, bl) = (bl, tl) + if tr[1] > br[1]: + (tr, br) = (br, tr) + return np.array([tl, tr, br, bl]) + + +def create_predictor(model_dir=None, model_lang="ch", is_onnx=False): + model_file_path = model_dir + if model_file_path is not None and not os.path.exists(model_file_path): + raise ValueError("not find model file path {}".format(model_file_path)) + + if is_onnx: + import onnxruntime as ort + + sess = ort.InferenceSession( + model_file_path, providers=["CPUExecutionProvider"] + ) # 'TensorrtExecutionProvider', 'CUDAExecutionProvider', 'CPUExecutionProvider' + return sess + else: + if model_lang == "ch": + n_class = 6625 + elif model_lang == "en": + n_class = 97 + else: + raise ValueError(f"Unsupported OCR recog model_lang: {model_lang}") + rec_config = edict( + in_channels=3, + backbone=edict( + type="MobileNetV1Enhance", + scale=0.5, + last_conv_stride=[1, 2], + last_pool_type="avg", + ), + neck=edict( + type="SequenceEncoder", + encoder_type="svtr", + dims=64, + depth=2, + hidden_dims=120, + use_guide=True, + ), + head=edict( + type="CTCHead", + fc_decay=0.00001, + out_channels=n_class, + return_feats=True, + ), + ) + + rec_model = RecModel(rec_config) + if model_file_path is not None: + rec_model.load_state_dict(torch.load(model_file_path, map_location="cpu")) + rec_model.eval() + return rec_model.eval() + + +def _check_image_file(path): + img_end = {"jpg", "bmp", "png", "jpeg", "rgb", "tif", "tiff"} + return any([path.lower().endswith(e) for e in img_end]) + + +def get_image_file_list(img_file): + imgs_lists = [] + if img_file is None or not os.path.exists(img_file): + raise Exception("not found any img file in {}".format(img_file)) + if os.path.isfile(img_file) and _check_image_file(img_file): + imgs_lists.append(img_file) + elif os.path.isdir(img_file): + for single_file in os.listdir(img_file): + file_path = os.path.join(img_file, single_file) + if os.path.isfile(file_path) and _check_image_file(file_path): + imgs_lists.append(file_path) + if len(imgs_lists) == 0: + raise Exception("not found any img file in {}".format(img_file)) + imgs_lists = sorted(imgs_lists) + return imgs_lists + + +class TextRecognizer(object): + def __init__(self, args, predictor): + self.rec_image_shape = [int(v) for v in args.rec_image_shape.split(",")] + self.rec_batch_num = args.rec_batch_num + self.predictor = predictor + self.chars = self.get_char_dict(args.rec_char_dict_path) + self.char2id = {x: i for i, x in enumerate(self.chars)} + self.is_onnx = not isinstance(self.predictor, torch.nn.Module) + self.use_fp16 = args.use_fp16 + + # img: CHW + def resize_norm_img(self, img, max_wh_ratio): + imgC, imgH, imgW = self.rec_image_shape + assert imgC == img.shape[0] + imgW = int((imgH * max_wh_ratio)) + + h, w = img.shape[1:] + ratio = w / float(h) + if math.ceil(imgH * ratio) > imgW: + resized_w = imgW + else: + resized_w = int(math.ceil(imgH * ratio)) + resized_image = torch.nn.functional.interpolate( + img.unsqueeze(0), + size=(imgH, resized_w), + mode="bilinear", + align_corners=True, + ) + resized_image /= 255.0 + resized_image -= 0.5 + resized_image /= 0.5 + padding_im = torch.zeros((imgC, imgH, imgW), dtype=torch.float32).to(img.device) + padding_im[:, :, 0:resized_w] = resized_image[0] + return padding_im + + # img_list: list of tensors with shape chw 0-255 + def pred_imglist(self, img_list, show_debug=False, is_ori=False): + img_num = len(img_list) + assert img_num > 0 + # Calculate the aspect ratio of all text bars + width_list = [] + for img in img_list: + width_list.append(img.shape[2] / float(img.shape[1])) + # Sorting can speed up the recognition process + indices = torch.from_numpy(np.argsort(np.array(width_list))) + batch_num = self.rec_batch_num + preds_all = [None] * img_num + preds_neck_all = [None] * img_num + for beg_img_no in range(0, img_num, batch_num): + end_img_no = min(img_num, beg_img_no + batch_num) + norm_img_batch = [] + + imgC, imgH, imgW = self.rec_image_shape[:3] + max_wh_ratio = imgW / imgH + for ino in range(beg_img_no, end_img_no): + h, w = img_list[indices[ino]].shape[1:] + if h > w * 1.2: + img = img_list[indices[ino]] + img = torch.transpose(img, 1, 2).flip(dims=[1]) + img_list[indices[ino]] = img + h, w = img.shape[1:] + # wh_ratio = w * 1.0 / h + # max_wh_ratio = max(max_wh_ratio, wh_ratio) # comment to not use different ratio + for ino in range(beg_img_no, end_img_no): + norm_img = self.resize_norm_img(img_list[indices[ino]], max_wh_ratio) + if self.use_fp16: + norm_img = norm_img.half() + norm_img = norm_img.unsqueeze(0) + norm_img_batch.append(norm_img) + norm_img_batch = torch.cat(norm_img_batch, dim=0) + if show_debug: + for i in range(len(norm_img_batch)): + _img = norm_img_batch[i].permute(1, 2, 0).detach().cpu().numpy() + _img = (_img + 0.5) * 255 + _img = _img[:, :, ::-1] + file_name = f"{indices[beg_img_no + i]}" + file_name = file_name + "_ori" if is_ori else file_name + cv2.imwrite(file_name + ".jpg", _img) + if self.is_onnx: + input_dict = {} + input_dict[self.predictor.get_inputs()[0].name] = ( + norm_img_batch.detach().cpu().numpy() + ) + outputs = self.predictor.run(None, input_dict) + preds = {} + preds["ctc"] = torch.from_numpy(outputs[0]) + preds["ctc_neck"] = [torch.zeros(1)] * img_num + else: + preds = self.predictor(norm_img_batch) + for rno in range(preds["ctc"].shape[0]): + preds_all[indices[beg_img_no + rno]] = preds["ctc"][rno] + preds_neck_all[indices[beg_img_no + rno]] = preds["ctc_neck"][rno] + + return torch.stack(preds_all, dim=0), torch.stack(preds_neck_all, dim=0) + + def get_char_dict(self, character_dict_path): + character_str = [] + with open(character_dict_path, "rb") as fin: + lines = fin.readlines() + for line in lines: + line = line.decode("utf-8").strip("\n").strip("\r\n") + character_str.append(line) + dict_character = list(character_str) + dict_character = ["sos"] + dict_character + [" "] # eos is space + return dict_character + + def get_text(self, order): + char_list = [self.chars[text_id] for text_id in order] + return "".join(char_list) + + def decode(self, mat): + text_index = mat.detach().cpu().numpy().argmax(axis=1) + ignored_tokens = [0] + selection = np.ones(len(text_index), dtype=bool) + selection[1:] = text_index[1:] != text_index[:-1] + for ignored_token in ignored_tokens: + selection &= text_index != ignored_token + return text_index[selection], np.where(selection)[0] + + def get_ctcloss(self, preds, gt_text, weight): + if not isinstance(weight, torch.Tensor): + weight = torch.tensor(weight).to(preds.device) + ctc_loss = torch.nn.CTCLoss(reduction="none") + log_probs = preds.log_softmax(dim=2).permute(1, 0, 2) # NTC-->TNC + targets = [] + target_lengths = [] + for t in gt_text: + targets += [self.char2id.get(i, len(self.chars) - 1) for i in t] + target_lengths += [len(t)] + targets = torch.tensor(targets).to(preds.device) + target_lengths = torch.tensor(target_lengths).to(preds.device) + input_lengths = torch.tensor([log_probs.shape[0]] * (log_probs.shape[1])).to( + preds.device + ) + loss = ctc_loss(log_probs, targets, input_lengths, target_lengths) + loss = loss / input_lengths * weight + return loss + + +def main(): + rec_model_dir = "./ocr_weights/ppv3_rec.pth" + predictor = create_predictor(rec_model_dir) + args = edict() + args.rec_image_shape = "3, 48, 320" + args.rec_char_dict_path = "./ocr_weights/ppocr_keys_v1.txt" + args.rec_batch_num = 6 + text_recognizer = TextRecognizer(args, predictor) + image_dir = "./test_imgs_cn" + gt_text = ["韩国小馆"] * 14 + + image_file_list = get_image_file_list(image_dir) + valid_image_file_list = [] + img_list = [] + + for image_file in image_file_list: + img = cv2.imread(image_file) + if img is None: + print("error in loading image:{}".format(image_file)) + continue + valid_image_file_list.append(image_file) + img_list.append(torch.from_numpy(img).permute(2, 0, 1).float()) + try: + tic = time.time() + times = [] + for i in range(10): + preds, _ = text_recognizer.pred_imglist(img_list) # get text + preds_all = preds.softmax(dim=2) + times += [(time.time() - tic) * 1000.0] + tic = time.time() + print(times) + print(np.mean(times[1:]) / len(preds_all)) + weight = np.ones(len(gt_text)) + loss = text_recognizer.get_ctcloss(preds, gt_text, weight) + for i in range(len(valid_image_file_list)): + pred = preds_all[i] + order, idx = text_recognizer.decode(pred) + text = text_recognizer.get_text(order) + print( + f'{valid_image_file_list[i]}: pred/gt="{text}"/"{gt_text[i]}", loss={loss[i]:.2f}' + ) + except Exception as E: + print(traceback.format_exc(), E) + + +if __name__ == "__main__": + main() diff --git a/py/iopaint/model/anytext/ldm/__init__.py b/py/iopaint/model/anytext/ldm/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/py/iopaint/model/anytext/ldm/models/__init__.py b/py/iopaint/model/anytext/ldm/models/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/py/iopaint/model/anytext/ldm/models/autoencoder.py b/py/iopaint/model/anytext/ldm/models/autoencoder.py new file mode 100644 index 0000000..20d52e9 --- /dev/null +++ b/py/iopaint/model/anytext/ldm/models/autoencoder.py @@ -0,0 +1,218 @@ +import torch +import torch.nn.functional as F +from contextlib import contextmanager + +from iopaint.model.anytext.ldm.modules.diffusionmodules.model import Encoder, Decoder +from iopaint.model.anytext.ldm.modules.distributions.distributions import DiagonalGaussianDistribution + +from iopaint.model.anytext.ldm.util import instantiate_from_config +from iopaint.model.anytext.ldm.modules.ema import LitEma + + +class AutoencoderKL(torch.nn.Module): + def __init__(self, + ddconfig, + lossconfig, + embed_dim, + ckpt_path=None, + ignore_keys=[], + image_key="image", + colorize_nlabels=None, + monitor=None, + ema_decay=None, + learn_logvar=False + ): + super().__init__() + self.learn_logvar = learn_logvar + self.image_key = image_key + self.encoder = Encoder(**ddconfig) + self.decoder = Decoder(**ddconfig) + self.loss = instantiate_from_config(lossconfig) + assert ddconfig["double_z"] + self.quant_conv = torch.nn.Conv2d(2*ddconfig["z_channels"], 2*embed_dim, 1) + self.post_quant_conv = torch.nn.Conv2d(embed_dim, ddconfig["z_channels"], 1) + self.embed_dim = embed_dim + if colorize_nlabels is not None: + assert type(colorize_nlabels)==int + self.register_buffer("colorize", torch.randn(3, colorize_nlabels, 1, 1)) + if monitor is not None: + self.monitor = monitor + + self.use_ema = ema_decay is not None + if self.use_ema: + self.ema_decay = ema_decay + assert 0. < ema_decay < 1. + self.model_ema = LitEma(self, decay=ema_decay) + print(f"Keeping EMAs of {len(list(self.model_ema.buffers()))}.") + + if ckpt_path is not None: + self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys) + + def init_from_ckpt(self, path, ignore_keys=list()): + sd = torch.load(path, map_location="cpu")["state_dict"] + keys = list(sd.keys()) + for k in keys: + for ik in ignore_keys: + if k.startswith(ik): + print("Deleting key {} from state_dict.".format(k)) + del sd[k] + self.load_state_dict(sd, strict=False) + print(f"Restored from {path}") + + @contextmanager + def ema_scope(self, context=None): + if self.use_ema: + self.model_ema.store(self.parameters()) + self.model_ema.copy_to(self) + if context is not None: + print(f"{context}: Switched to EMA weights") + try: + yield None + finally: + if self.use_ema: + self.model_ema.restore(self.parameters()) + if context is not None: + print(f"{context}: Restored training weights") + + def on_train_batch_end(self, *args, **kwargs): + if self.use_ema: + self.model_ema(self) + + def encode(self, x): + h = self.encoder(x) + moments = self.quant_conv(h) + posterior = DiagonalGaussianDistribution(moments) + return posterior + + def decode(self, z): + z = self.post_quant_conv(z) + dec = self.decoder(z) + return dec + + def forward(self, input, sample_posterior=True): + posterior = self.encode(input) + if sample_posterior: + z = posterior.sample() + else: + z = posterior.mode() + dec = self.decode(z) + return dec, posterior + + def get_input(self, batch, k): + x = batch[k] + if len(x.shape) == 3: + x = x[..., None] + x = x.permute(0, 3, 1, 2).to(memory_format=torch.contiguous_format).float() + return x + + def training_step(self, batch, batch_idx, optimizer_idx): + inputs = self.get_input(batch, self.image_key) + reconstructions, posterior = self(inputs) + + if optimizer_idx == 0: + # train encoder+decoder+logvar + aeloss, log_dict_ae = self.loss(inputs, reconstructions, posterior, optimizer_idx, self.global_step, + last_layer=self.get_last_layer(), split="train") + self.log("aeloss", aeloss, prog_bar=True, logger=True, on_step=True, on_epoch=True) + self.log_dict(log_dict_ae, prog_bar=False, logger=True, on_step=True, on_epoch=False) + return aeloss + + if optimizer_idx == 1: + # train the discriminator + discloss, log_dict_disc = self.loss(inputs, reconstructions, posterior, optimizer_idx, self.global_step, + last_layer=self.get_last_layer(), split="train") + + self.log("discloss", discloss, prog_bar=True, logger=True, on_step=True, on_epoch=True) + self.log_dict(log_dict_disc, prog_bar=False, logger=True, on_step=True, on_epoch=False) + return discloss + + def validation_step(self, batch, batch_idx): + log_dict = self._validation_step(batch, batch_idx) + with self.ema_scope(): + log_dict_ema = self._validation_step(batch, batch_idx, postfix="_ema") + return log_dict + + def _validation_step(self, batch, batch_idx, postfix=""): + inputs = self.get_input(batch, self.image_key) + reconstructions, posterior = self(inputs) + aeloss, log_dict_ae = self.loss(inputs, reconstructions, posterior, 0, self.global_step, + last_layer=self.get_last_layer(), split="val"+postfix) + + discloss, log_dict_disc = self.loss(inputs, reconstructions, posterior, 1, self.global_step, + last_layer=self.get_last_layer(), split="val"+postfix) + + self.log(f"val{postfix}/rec_loss", log_dict_ae[f"val{postfix}/rec_loss"]) + self.log_dict(log_dict_ae) + self.log_dict(log_dict_disc) + return self.log_dict + + def configure_optimizers(self): + lr = self.learning_rate + ae_params_list = list(self.encoder.parameters()) + list(self.decoder.parameters()) + list( + self.quant_conv.parameters()) + list(self.post_quant_conv.parameters()) + if self.learn_logvar: + print(f"{self.__class__.__name__}: Learning logvar") + ae_params_list.append(self.loss.logvar) + opt_ae = torch.optim.Adam(ae_params_list, + lr=lr, betas=(0.5, 0.9)) + opt_disc = torch.optim.Adam(self.loss.discriminator.parameters(), + lr=lr, betas=(0.5, 0.9)) + return [opt_ae, opt_disc], [] + + def get_last_layer(self): + return self.decoder.conv_out.weight + + @torch.no_grad() + def log_images(self, batch, only_inputs=False, log_ema=False, **kwargs): + log = dict() + x = self.get_input(batch, self.image_key) + x = x.to(self.device) + if not only_inputs: + xrec, posterior = self(x) + if x.shape[1] > 3: + # colorize with random projection + assert xrec.shape[1] > 3 + x = self.to_rgb(x) + xrec = self.to_rgb(xrec) + log["samples"] = self.decode(torch.randn_like(posterior.sample())) + log["reconstructions"] = xrec + if log_ema or self.use_ema: + with self.ema_scope(): + xrec_ema, posterior_ema = self(x) + if x.shape[1] > 3: + # colorize with random projection + assert xrec_ema.shape[1] > 3 + xrec_ema = self.to_rgb(xrec_ema) + log["samples_ema"] = self.decode(torch.randn_like(posterior_ema.sample())) + log["reconstructions_ema"] = xrec_ema + log["inputs"] = x + return log + + def to_rgb(self, x): + assert self.image_key == "segmentation" + if not hasattr(self, "colorize"): + self.register_buffer("colorize", torch.randn(3, x.shape[1], 1, 1).to(x)) + x = F.conv2d(x, weight=self.colorize) + x = 2.*(x-x.min())/(x.max()-x.min()) - 1. + return x + + +class IdentityFirstStage(torch.nn.Module): + def __init__(self, *args, vq_interface=False, **kwargs): + self.vq_interface = vq_interface + super().__init__() + + def encode(self, x, *args, **kwargs): + return x + + def decode(self, x, *args, **kwargs): + return x + + def quantize(self, x, *args, **kwargs): + if self.vq_interface: + return x, None, [None, None, None] + return x + + def forward(self, x, *args, **kwargs): + return x + diff --git a/py/iopaint/model/anytext/ldm/models/diffusion/__init__.py b/py/iopaint/model/anytext/ldm/models/diffusion/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/py/iopaint/model/anytext/ldm/models/diffusion/ddim.py b/py/iopaint/model/anytext/ldm/models/diffusion/ddim.py new file mode 100644 index 0000000..f8bbaff --- /dev/null +++ b/py/iopaint/model/anytext/ldm/models/diffusion/ddim.py @@ -0,0 +1,354 @@ +"""SAMPLING ONLY.""" + +import torch +import numpy as np +from tqdm import tqdm + +from iopaint.model.anytext.ldm.modules.diffusionmodules.util import make_ddim_sampling_parameters, make_ddim_timesteps, noise_like, extract_into_tensor + + +class DDIMSampler(object): + def __init__(self, model, schedule="linear", **kwargs): + super().__init__() + self.model = model + self.ddpm_num_timesteps = model.num_timesteps + self.schedule = schedule + + def register_buffer(self, name, attr): + if type(attr) == torch.Tensor: + if attr.device != torch.device("cuda"): + attr = attr.to(torch.device("cuda")) + setattr(self, name, attr) + + def make_schedule(self, ddim_num_steps, ddim_discretize="uniform", ddim_eta=0., verbose=True): + self.ddim_timesteps = make_ddim_timesteps(ddim_discr_method=ddim_discretize, num_ddim_timesteps=ddim_num_steps, + num_ddpm_timesteps=self.ddpm_num_timesteps,verbose=verbose) + alphas_cumprod = self.model.alphas_cumprod + assert alphas_cumprod.shape[0] == self.ddpm_num_timesteps, 'alphas have to be defined for each timestep' + to_torch = lambda x: x.clone().detach().to(torch.float32).to(self.model.device) + + self.register_buffer('betas', to_torch(self.model.betas)) + self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod)) + self.register_buffer('alphas_cumprod_prev', to_torch(self.model.alphas_cumprod_prev)) + + # calculations for diffusion q(x_t | x_{t-1}) and others + self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod.cpu()))) + self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod.cpu()))) + self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod.cpu()))) + self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu()))) + self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu() - 1))) + + # ddim sampling parameters + ddim_sigmas, ddim_alphas, ddim_alphas_prev = make_ddim_sampling_parameters(alphacums=alphas_cumprod.cpu(), + ddim_timesteps=self.ddim_timesteps, + eta=ddim_eta,verbose=verbose) + self.register_buffer('ddim_sigmas', ddim_sigmas) + self.register_buffer('ddim_alphas', ddim_alphas) + self.register_buffer('ddim_alphas_prev', ddim_alphas_prev) + self.register_buffer('ddim_sqrt_one_minus_alphas', np.sqrt(1. - ddim_alphas)) + sigmas_for_original_sampling_steps = ddim_eta * torch.sqrt( + (1 - self.alphas_cumprod_prev) / (1 - self.alphas_cumprod) * ( + 1 - self.alphas_cumprod / self.alphas_cumprod_prev)) + self.register_buffer('ddim_sigmas_for_original_num_steps', sigmas_for_original_sampling_steps) + + @torch.no_grad() + def sample(self, + S, + batch_size, + shape, + conditioning=None, + callback=None, + normals_sequence=None, + img_callback=None, + quantize_x0=False, + eta=0., + mask=None, + x0=None, + temperature=1., + noise_dropout=0., + score_corrector=None, + corrector_kwargs=None, + verbose=True, + x_T=None, + log_every_t=100, + unconditional_guidance_scale=1., + unconditional_conditioning=None, # this has to come in the same format as the conditioning, # e.g. as encoded tokens, ... + dynamic_threshold=None, + ucg_schedule=None, + **kwargs + ): + if conditioning is not None: + if isinstance(conditioning, dict): + ctmp = conditioning[list(conditioning.keys())[0]] + while isinstance(ctmp, list): ctmp = ctmp[0] + cbs = ctmp.shape[0] + # cbs = len(ctmp[0]) + if cbs != batch_size: + print(f"Warning: Got {cbs} conditionings but batch-size is {batch_size}") + + elif isinstance(conditioning, list): + for ctmp in conditioning: + if ctmp.shape[0] != batch_size: + print(f"Warning: Got {cbs} conditionings but batch-size is {batch_size}") + + else: + if conditioning.shape[0] != batch_size: + print(f"Warning: Got {conditioning.shape[0]} conditionings but batch-size is {batch_size}") + + self.make_schedule(ddim_num_steps=S, ddim_eta=eta, verbose=verbose) + # sampling + C, H, W = shape + size = (batch_size, C, H, W) + print(f'Data shape for DDIM sampling is {size}, eta {eta}') + + samples, intermediates = self.ddim_sampling(conditioning, size, + callback=callback, + img_callback=img_callback, + quantize_denoised=quantize_x0, + mask=mask, x0=x0, + ddim_use_original_steps=False, + noise_dropout=noise_dropout, + temperature=temperature, + score_corrector=score_corrector, + corrector_kwargs=corrector_kwargs, + x_T=x_T, + log_every_t=log_every_t, + unconditional_guidance_scale=unconditional_guidance_scale, + unconditional_conditioning=unconditional_conditioning, + dynamic_threshold=dynamic_threshold, + ucg_schedule=ucg_schedule + ) + return samples, intermediates + + @torch.no_grad() + def ddim_sampling(self, cond, shape, + x_T=None, ddim_use_original_steps=False, + callback=None, timesteps=None, quantize_denoised=False, + mask=None, x0=None, img_callback=None, log_every_t=100, + temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None, + unconditional_guidance_scale=1., unconditional_conditioning=None, dynamic_threshold=None, + ucg_schedule=None): + device = self.model.betas.device + b = shape[0] + if x_T is None: + img = torch.randn(shape, device=device) + else: + img = x_T + + if timesteps is None: + timesteps = self.ddpm_num_timesteps if ddim_use_original_steps else self.ddim_timesteps + elif timesteps is not None and not ddim_use_original_steps: + subset_end = int(min(timesteps / self.ddim_timesteps.shape[0], 1) * self.ddim_timesteps.shape[0]) - 1 + timesteps = self.ddim_timesteps[:subset_end] + + intermediates = {'x_inter': [img], 'pred_x0': [img], "index": [10000]} + time_range = reversed(range(0, timesteps)) if ddim_use_original_steps else np.flip(timesteps) + total_steps = timesteps if ddim_use_original_steps else timesteps.shape[0] + print(f"Running DDIM Sampling with {total_steps} timesteps") + + iterator = tqdm(time_range, desc='DDIM Sampler', total=total_steps) + + for i, step in enumerate(iterator): + index = total_steps - i - 1 + ts = torch.full((b,), step, device=device, dtype=torch.long) + + if mask is not None: + assert x0 is not None + img_orig = self.model.q_sample(x0, ts) # TODO: deterministic forward pass? + img = img_orig * mask + (1. - mask) * img + + if ucg_schedule is not None: + assert len(ucg_schedule) == len(time_range) + unconditional_guidance_scale = ucg_schedule[i] + + outs = self.p_sample_ddim(img, cond, ts, index=index, use_original_steps=ddim_use_original_steps, + quantize_denoised=quantize_denoised, temperature=temperature, + noise_dropout=noise_dropout, score_corrector=score_corrector, + corrector_kwargs=corrector_kwargs, + unconditional_guidance_scale=unconditional_guidance_scale, + unconditional_conditioning=unconditional_conditioning, + dynamic_threshold=dynamic_threshold) + img, pred_x0 = outs + if callback: + callback(i) + if img_callback: + img_callback(pred_x0, i) + + if index % log_every_t == 0 or index == total_steps - 1: + intermediates['x_inter'].append(img) + intermediates['pred_x0'].append(pred_x0) + intermediates['index'].append(index) + + return img, intermediates + + @torch.no_grad() + def p_sample_ddim(self, x, c, t, index, repeat_noise=False, use_original_steps=False, quantize_denoised=False, + temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None, + unconditional_guidance_scale=1., unconditional_conditioning=None, + dynamic_threshold=None): + b, *_, device = *x.shape, x.device + + if unconditional_conditioning is None or unconditional_guidance_scale == 1.: + model_output = self.model.apply_model(x, t, c) + else: + x_in = torch.cat([x] * 2) + t_in = torch.cat([t] * 2) + if isinstance(c, dict): + assert isinstance(unconditional_conditioning, dict) + c_in = dict() + for k in c: + if isinstance(c[k], list): + c_in[k] = [torch.cat([ + unconditional_conditioning[k][i], + c[k][i]]) for i in range(len(c[k]))] + elif isinstance(c[k], dict): + c_in[k] = dict() + for key in c[k]: + if isinstance(c[k][key], list): + if not isinstance(c[k][key][0], torch.Tensor): + continue + c_in[k][key] = [torch.cat([ + unconditional_conditioning[k][key][i], + c[k][key][i]]) for i in range(len(c[k][key]))] + else: + c_in[k][key] = torch.cat([ + unconditional_conditioning[k][key], + c[k][key]]) + + else: + c_in[k] = torch.cat([ + unconditional_conditioning[k], + c[k]]) + elif isinstance(c, list): + c_in = list() + assert isinstance(unconditional_conditioning, list) + for i in range(len(c)): + c_in.append(torch.cat([unconditional_conditioning[i], c[i]])) + else: + c_in = torch.cat([unconditional_conditioning, c]) + model_uncond, model_t = self.model.apply_model(x_in, t_in, c_in).chunk(2) + model_output = model_uncond + unconditional_guidance_scale * (model_t - model_uncond) + + if self.model.parameterization == "v": + e_t = self.model.predict_eps_from_z_and_v(x, t, model_output) + else: + e_t = model_output + + if score_corrector is not None: + assert self.model.parameterization == "eps", 'not implemented' + e_t = score_corrector.modify_score(self.model, e_t, x, t, c, **corrector_kwargs) + + alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas + alphas_prev = self.model.alphas_cumprod_prev if use_original_steps else self.ddim_alphas_prev + sqrt_one_minus_alphas = self.model.sqrt_one_minus_alphas_cumprod if use_original_steps else self.ddim_sqrt_one_minus_alphas + sigmas = self.model.ddim_sigmas_for_original_num_steps if use_original_steps else self.ddim_sigmas + # select parameters corresponding to the currently considered timestep + a_t = torch.full((b, 1, 1, 1), alphas[index], device=device) + a_prev = torch.full((b, 1, 1, 1), alphas_prev[index], device=device) + sigma_t = torch.full((b, 1, 1, 1), sigmas[index], device=device) + sqrt_one_minus_at = torch.full((b, 1, 1, 1), sqrt_one_minus_alphas[index],device=device) + + # current prediction for x_0 + if self.model.parameterization != "v": + pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt() + else: + pred_x0 = self.model.predict_start_from_z_and_v(x, t, model_output) + + if quantize_denoised: + pred_x0, _, *_ = self.model.first_stage_model.quantize(pred_x0) + + if dynamic_threshold is not None: + raise NotImplementedError() + + # direction pointing to x_t + dir_xt = (1. - a_prev - sigma_t**2).sqrt() * e_t + noise = sigma_t * noise_like(x.shape, device, repeat_noise) * temperature + if noise_dropout > 0.: + noise = torch.nn.functional.dropout(noise, p=noise_dropout) + x_prev = a_prev.sqrt() * pred_x0 + dir_xt + noise + return x_prev, pred_x0 + + @torch.no_grad() + def encode(self, x0, c, t_enc, use_original_steps=False, return_intermediates=None, + unconditional_guidance_scale=1.0, unconditional_conditioning=None, callback=None): + num_reference_steps = self.ddpm_num_timesteps if use_original_steps else self.ddim_timesteps.shape[0] + + assert t_enc <= num_reference_steps + num_steps = t_enc + + if use_original_steps: + alphas_next = self.alphas_cumprod[:num_steps] + alphas = self.alphas_cumprod_prev[:num_steps] + else: + alphas_next = self.ddim_alphas[:num_steps] + alphas = torch.tensor(self.ddim_alphas_prev[:num_steps]) + + x_next = x0 + intermediates = [] + inter_steps = [] + for i in tqdm(range(num_steps), desc='Encoding Image'): + t = torch.full((x0.shape[0],), i, device=self.model.device, dtype=torch.long) + if unconditional_guidance_scale == 1.: + noise_pred = self.model.apply_model(x_next, t, c) + else: + assert unconditional_conditioning is not None + e_t_uncond, noise_pred = torch.chunk( + self.model.apply_model(torch.cat((x_next, x_next)), torch.cat((t, t)), + torch.cat((unconditional_conditioning, c))), 2) + noise_pred = e_t_uncond + unconditional_guidance_scale * (noise_pred - e_t_uncond) + + xt_weighted = (alphas_next[i] / alphas[i]).sqrt() * x_next + weighted_noise_pred = alphas_next[i].sqrt() * ( + (1 / alphas_next[i] - 1).sqrt() - (1 / alphas[i] - 1).sqrt()) * noise_pred + x_next = xt_weighted + weighted_noise_pred + if return_intermediates and i % ( + num_steps // return_intermediates) == 0 and i < num_steps - 1: + intermediates.append(x_next) + inter_steps.append(i) + elif return_intermediates and i >= num_steps - 2: + intermediates.append(x_next) + inter_steps.append(i) + if callback: callback(i) + + out = {'x_encoded': x_next, 'intermediate_steps': inter_steps} + if return_intermediates: + out.update({'intermediates': intermediates}) + return x_next, out + + @torch.no_grad() + def stochastic_encode(self, x0, t, use_original_steps=False, noise=None): + # fast, but does not allow for exact reconstruction + # t serves as an index to gather the correct alphas + if use_original_steps: + sqrt_alphas_cumprod = self.sqrt_alphas_cumprod + sqrt_one_minus_alphas_cumprod = self.sqrt_one_minus_alphas_cumprod + else: + sqrt_alphas_cumprod = torch.sqrt(self.ddim_alphas) + sqrt_one_minus_alphas_cumprod = self.ddim_sqrt_one_minus_alphas + + if noise is None: + noise = torch.randn_like(x0) + return (extract_into_tensor(sqrt_alphas_cumprod, t, x0.shape) * x0 + + extract_into_tensor(sqrt_one_minus_alphas_cumprod, t, x0.shape) * noise) + + @torch.no_grad() + def decode(self, x_latent, cond, t_start, unconditional_guidance_scale=1.0, unconditional_conditioning=None, + use_original_steps=False, callback=None): + + timesteps = np.arange(self.ddpm_num_timesteps) if use_original_steps else self.ddim_timesteps + timesteps = timesteps[:t_start] + + time_range = np.flip(timesteps) + total_steps = timesteps.shape[0] + print(f"Running DDIM Sampling with {total_steps} timesteps") + + iterator = tqdm(time_range, desc='Decoding image', total=total_steps) + x_dec = x_latent + for i, step in enumerate(iterator): + index = total_steps - i - 1 + ts = torch.full((x_latent.shape[0],), step, device=x_latent.device, dtype=torch.long) + x_dec, _ = self.p_sample_ddim(x_dec, cond, ts, index=index, use_original_steps=use_original_steps, + unconditional_guidance_scale=unconditional_guidance_scale, + unconditional_conditioning=unconditional_conditioning) + if callback: callback(i) + return x_dec \ No newline at end of file diff --git a/py/iopaint/model/anytext/ldm/models/diffusion/ddpm.py b/py/iopaint/model/anytext/ldm/models/diffusion/ddpm.py new file mode 100644 index 0000000..9f48918 --- /dev/null +++ b/py/iopaint/model/anytext/ldm/models/diffusion/ddpm.py @@ -0,0 +1,2380 @@ +""" +Part of the implementation is borrowed and modified from ControlNet, publicly available at https://github.com/lllyasviel/ControlNet/blob/main/ldm/models/diffusion/ddpm.py +""" + +import torch +import torch.nn as nn +import numpy as np +from torch.optim.lr_scheduler import LambdaLR +from einops import rearrange, repeat +from contextlib import contextmanager, nullcontext +from functools import partial +import itertools +from tqdm import tqdm +from torchvision.utils import make_grid +from omegaconf import ListConfig + +from iopaint.model.anytext.ldm.util import ( + log_txt_as_img, + exists, + default, + ismap, + isimage, + mean_flat, + count_params, + instantiate_from_config, +) +from iopaint.model.anytext.ldm.modules.ema import LitEma +from iopaint.model.anytext.ldm.modules.distributions.distributions import ( + normal_kl, + DiagonalGaussianDistribution, +) +from iopaint.model.anytext.ldm.models.autoencoder import IdentityFirstStage, AutoencoderKL +from iopaint.model.anytext.ldm.modules.diffusionmodules.util import ( + make_beta_schedule, + extract_into_tensor, + noise_like, +) +from iopaint.model.anytext.ldm.models.diffusion.ddim import DDIMSampler +import cv2 + + +__conditioning_keys__ = {"concat": "c_concat", "crossattn": "c_crossattn", "adm": "y"} + +PRINT_DEBUG = False + + +def print_grad(grad): + # print('Gradient:', grad) + # print(grad.shape) + a = grad.max() + b = grad.min() + # print(f'mean={grad.mean():.4f}, max={a:.4f}, min={b:.4f}') + s = 255.0 / (a - b) + c = 255 * (-b / (a - b)) + grad = grad * s + c + # print(f'mean={grad.mean():.4f}, max={grad.max():.4f}, min={grad.min():.4f}') + img = grad[0].permute(1, 2, 0).detach().cpu().numpy() + if img.shape[0] == 512: + cv2.imwrite("grad-img.jpg", img) + elif img.shape[0] == 64: + cv2.imwrite("grad-latent.jpg", img) + + +def disabled_train(self, mode=True): + """Overwrite model.train with this function to make sure train/eval mode + does not change anymore.""" + return self + + +def uniform_on_device(r1, r2, shape, device): + return (r1 - r2) * torch.rand(*shape, device=device) + r2 + + +class DDPM(torch.nn.Module): + # classic DDPM with Gaussian diffusion, in image space + def __init__( + self, + unet_config, + timesteps=1000, + beta_schedule="linear", + loss_type="l2", + ckpt_path=None, + ignore_keys=[], + load_only_unet=False, + monitor="val/loss", + use_ema=True, + first_stage_key="image", + image_size=256, + channels=3, + log_every_t=100, + clip_denoised=True, + linear_start=1e-4, + linear_end=2e-2, + cosine_s=8e-3, + given_betas=None, + original_elbo_weight=0.0, + v_posterior=0.0, # weight for choosing posterior variance as sigma = (1-v) * beta_tilde + v * beta + l_simple_weight=1.0, + conditioning_key=None, + parameterization="eps", # all assuming fixed variance schedules + scheduler_config=None, + use_positional_encodings=False, + learn_logvar=False, + logvar_init=0.0, + make_it_fit=False, + ucg_training=None, + reset_ema=False, + reset_num_ema_updates=False, + ): + super().__init__() + assert parameterization in [ + "eps", + "x0", + "v", + ], 'currently only supporting "eps" and "x0" and "v"' + self.parameterization = parameterization + print( + f"{self.__class__.__name__}: Running in {self.parameterization}-prediction mode" + ) + self.cond_stage_model = None + self.clip_denoised = clip_denoised + self.log_every_t = log_every_t + self.first_stage_key = first_stage_key + self.image_size = image_size # try conv? + self.channels = channels + self.use_positional_encodings = use_positional_encodings + self.model = DiffusionWrapper(unet_config, conditioning_key) + count_params(self.model, verbose=True) + self.use_ema = use_ema + if self.use_ema: + self.model_ema = LitEma(self.model) + print(f"Keeping EMAs of {len(list(self.model_ema.buffers()))}.") + + self.use_scheduler = scheduler_config is not None + if self.use_scheduler: + self.scheduler_config = scheduler_config + + self.v_posterior = v_posterior + self.original_elbo_weight = original_elbo_weight + self.l_simple_weight = l_simple_weight + + if monitor is not None: + self.monitor = monitor + self.make_it_fit = make_it_fit + if reset_ema: + assert exists(ckpt_path) + if ckpt_path is not None: + self.init_from_ckpt( + ckpt_path, ignore_keys=ignore_keys, only_model=load_only_unet + ) + if reset_ema: + assert self.use_ema + print( + f"Resetting ema to pure model weights. This is useful when restoring from an ema-only checkpoint." + ) + self.model_ema = LitEma(self.model) + if reset_num_ema_updates: + print( + " +++++++++++ WARNING: RESETTING NUM_EMA UPDATES TO ZERO +++++++++++ " + ) + assert self.use_ema + self.model_ema.reset_num_updates() + + self.register_schedule( + given_betas=given_betas, + beta_schedule=beta_schedule, + timesteps=timesteps, + linear_start=linear_start, + linear_end=linear_end, + cosine_s=cosine_s, + ) + + self.loss_type = loss_type + + self.learn_logvar = learn_logvar + logvar = torch.full(fill_value=logvar_init, size=(self.num_timesteps,)) + if self.learn_logvar: + self.logvar = nn.Parameter(self.logvar, requires_grad=True) + else: + self.register_buffer("logvar", logvar) + + self.ucg_training = ucg_training or dict() + if self.ucg_training: + self.ucg_prng = np.random.RandomState() + + def register_schedule( + self, + given_betas=None, + beta_schedule="linear", + timesteps=1000, + linear_start=1e-4, + linear_end=2e-2, + cosine_s=8e-3, + ): + if exists(given_betas): + betas = given_betas + else: + betas = make_beta_schedule( + beta_schedule, + timesteps, + linear_start=linear_start, + linear_end=linear_end, + cosine_s=cosine_s, + ) + alphas = 1.0 - betas + alphas_cumprod = np.cumprod(alphas, axis=0) + # np.save('1.npy', alphas_cumprod) + alphas_cumprod_prev = np.append(1.0, alphas_cumprod[:-1]) + + (timesteps,) = betas.shape + self.num_timesteps = int(timesteps) + self.linear_start = linear_start + self.linear_end = linear_end + assert ( + alphas_cumprod.shape[0] == self.num_timesteps + ), "alphas have to be defined for each timestep" + + to_torch = partial(torch.tensor, dtype=torch.float32) + + self.register_buffer("betas", to_torch(betas)) + self.register_buffer("alphas_cumprod", to_torch(alphas_cumprod)) + self.register_buffer("alphas_cumprod_prev", to_torch(alphas_cumprod_prev)) + + # calculations for diffusion q(x_t | x_{t-1}) and others + self.register_buffer("sqrt_alphas_cumprod", to_torch(np.sqrt(alphas_cumprod))) + self.register_buffer( + "sqrt_one_minus_alphas_cumprod", to_torch(np.sqrt(1.0 - alphas_cumprod)) + ) + self.register_buffer( + "log_one_minus_alphas_cumprod", to_torch(np.log(1.0 - alphas_cumprod)) + ) + self.register_buffer( + "sqrt_recip_alphas_cumprod", to_torch(np.sqrt(1.0 / alphas_cumprod)) + ) + self.register_buffer( + "sqrt_recipm1_alphas_cumprod", to_torch(np.sqrt(1.0 / alphas_cumprod - 1)) + ) + + # calculations for posterior q(x_{t-1} | x_t, x_0) + posterior_variance = (1 - self.v_posterior) * betas * ( + 1.0 - alphas_cumprod_prev + ) / (1.0 - alphas_cumprod) + self.v_posterior * betas + # above: equal to 1. / (1. / (1. - alpha_cumprod_tm1) + alpha_t / beta_t) + self.register_buffer("posterior_variance", to_torch(posterior_variance)) + # below: log calculation clipped because the posterior variance is 0 at the beginning of the diffusion chain + self.register_buffer( + "posterior_log_variance_clipped", + to_torch(np.log(np.maximum(posterior_variance, 1e-20))), + ) + self.register_buffer( + "posterior_mean_coef1", + to_torch(betas * np.sqrt(alphas_cumprod_prev) / (1.0 - alphas_cumprod)), + ) + self.register_buffer( + "posterior_mean_coef2", + to_torch( + (1.0 - alphas_cumprod_prev) * np.sqrt(alphas) / (1.0 - alphas_cumprod) + ), + ) + + if self.parameterization == "eps": + lvlb_weights = self.betas**2 / ( + 2 + * self.posterior_variance + * to_torch(alphas) + * (1 - self.alphas_cumprod) + ) + elif self.parameterization == "x0": + lvlb_weights = ( + 0.5 + * np.sqrt(torch.Tensor(alphas_cumprod)) + / (2.0 * 1 - torch.Tensor(alphas_cumprod)) + ) + elif self.parameterization == "v": + lvlb_weights = torch.ones_like( + self.betas**2 + / ( + 2 + * self.posterior_variance + * to_torch(alphas) + * (1 - self.alphas_cumprod) + ) + ) + else: + raise NotImplementedError("mu not supported") + lvlb_weights[0] = lvlb_weights[1] + self.register_buffer("lvlb_weights", lvlb_weights, persistent=False) + assert not torch.isnan(self.lvlb_weights).all() + + @contextmanager + def ema_scope(self, context=None): + if self.use_ema: + self.model_ema.store(self.model.parameters()) + self.model_ema.copy_to(self.model) + if context is not None: + print(f"{context}: Switched to EMA weights") + try: + yield None + finally: + if self.use_ema: + self.model_ema.restore(self.model.parameters()) + if context is not None: + print(f"{context}: Restored training weights") + + @torch.no_grad() + def init_from_ckpt(self, path, ignore_keys=list(), only_model=False): + sd = torch.load(path, map_location="cpu") + if "state_dict" in list(sd.keys()): + sd = sd["state_dict"] + keys = list(sd.keys()) + for k in keys: + for ik in ignore_keys: + if k.startswith(ik): + print("Deleting key {} from state_dict.".format(k)) + del sd[k] + if self.make_it_fit: + n_params = len( + [ + name + for name, _ in itertools.chain( + self.named_parameters(), self.named_buffers() + ) + ] + ) + for name, param in tqdm( + itertools.chain(self.named_parameters(), self.named_buffers()), + desc="Fitting old weights to new weights", + total=n_params, + ): + if not name in sd: + continue + old_shape = sd[name].shape + new_shape = param.shape + assert len(old_shape) == len(new_shape) + if len(new_shape) > 2: + # we only modify first two axes + assert new_shape[2:] == old_shape[2:] + # assumes first axis corresponds to output dim + if not new_shape == old_shape: + new_param = param.clone() + old_param = sd[name] + if len(new_shape) == 1: + for i in range(new_param.shape[0]): + new_param[i] = old_param[i % old_shape[0]] + elif len(new_shape) >= 2: + for i in range(new_param.shape[0]): + for j in range(new_param.shape[1]): + new_param[i, j] = old_param[ + i % old_shape[0], j % old_shape[1] + ] + + n_used_old = torch.ones(old_shape[1]) + for j in range(new_param.shape[1]): + n_used_old[j % old_shape[1]] += 1 + n_used_new = torch.zeros(new_shape[1]) + for j in range(new_param.shape[1]): + n_used_new[j] = n_used_old[j % old_shape[1]] + + n_used_new = n_used_new[None, :] + while len(n_used_new.shape) < len(new_shape): + n_used_new = n_used_new.unsqueeze(-1) + new_param /= n_used_new + + sd[name] = new_param + + missing, unexpected = ( + self.load_state_dict(sd, strict=False) + if not only_model + else self.model.load_state_dict(sd, strict=False) + ) + print( + f"Restored from {path} with {len(missing)} missing and {len(unexpected)} unexpected keys" + ) + if len(missing) > 0: + print(f"Missing Keys:\n {missing}") + if len(unexpected) > 0: + print(f"\nUnexpected Keys:\n {unexpected}") + + def q_mean_variance(self, x_start, t): + """ + Get the distribution q(x_t | x_0). + :param x_start: the [N x C x ...] tensor of noiseless inputs. + :param t: the number of diffusion steps (minus 1). Here, 0 means one step. + :return: A tuple (mean, variance, log_variance), all of x_start's shape. + """ + mean = extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start + variance = extract_into_tensor(1.0 - self.alphas_cumprod, t, x_start.shape) + log_variance = extract_into_tensor( + self.log_one_minus_alphas_cumprod, t, x_start.shape + ) + return mean, variance, log_variance + + def predict_start_from_noise(self, x_t, t, noise): + return ( + extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t + - extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) + * noise + ) + + def predict_start_from_z_and_v(self, x_t, t, v): + # self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod))) + # self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod))) + return ( + extract_into_tensor(self.sqrt_alphas_cumprod, t, x_t.shape) * x_t + - extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_t.shape) * v + ) + + def predict_eps_from_z_and_v(self, x_t, t, v): + return ( + extract_into_tensor(self.sqrt_alphas_cumprod, t, x_t.shape) * v + + extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_t.shape) + * x_t + ) + + def q_posterior(self, x_start, x_t, t): + posterior_mean = ( + extract_into_tensor(self.posterior_mean_coef1, t, x_t.shape) * x_start + + extract_into_tensor(self.posterior_mean_coef2, t, x_t.shape) * x_t + ) + posterior_variance = extract_into_tensor(self.posterior_variance, t, x_t.shape) + posterior_log_variance_clipped = extract_into_tensor( + self.posterior_log_variance_clipped, t, x_t.shape + ) + return posterior_mean, posterior_variance, posterior_log_variance_clipped + + def p_mean_variance(self, x, t, clip_denoised: bool): + model_out = self.model(x, t) + if self.parameterization == "eps": + x_recon = self.predict_start_from_noise(x, t=t, noise=model_out) + elif self.parameterization == "x0": + x_recon = model_out + if clip_denoised: + x_recon.clamp_(-1.0, 1.0) + + model_mean, posterior_variance, posterior_log_variance = self.q_posterior( + x_start=x_recon, x_t=x, t=t + ) + return model_mean, posterior_variance, posterior_log_variance + + @torch.no_grad() + def p_sample(self, x, t, clip_denoised=True, repeat_noise=False): + b, *_, device = *x.shape, x.device + model_mean, _, model_log_variance = self.p_mean_variance( + x=x, t=t, clip_denoised=clip_denoised + ) + noise = noise_like(x.shape, device, repeat_noise) + # no noise when t == 0 + nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1))) + return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise + + @torch.no_grad() + def p_sample_loop(self, shape, return_intermediates=False): + device = self.betas.device + b = shape[0] + img = torch.randn(shape, device=device) + intermediates = [img] + for i in tqdm( + reversed(range(0, self.num_timesteps)), + desc="Sampling t", + total=self.num_timesteps, + ): + img = self.p_sample( + img, + torch.full((b,), i, device=device, dtype=torch.long), + clip_denoised=self.clip_denoised, + ) + if i % self.log_every_t == 0 or i == self.num_timesteps - 1: + intermediates.append(img) + if return_intermediates: + return img, intermediates + return img + + @torch.no_grad() + def sample(self, batch_size=16, return_intermediates=False): + image_size = self.image_size + channels = self.channels + return self.p_sample_loop( + (batch_size, channels, image_size, image_size), + return_intermediates=return_intermediates, + ) + + def q_sample(self, x_start, t, noise=None): + noise = default(noise, lambda: torch.randn_like(x_start)) + return ( + extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start + + extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape) + * noise + ) + + def get_v(self, x, noise, t): + return ( + extract_into_tensor(self.sqrt_alphas_cumprod, t, x.shape) * noise + - extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x.shape) * x + ) + + def get_loss(self, pred, target, mean=True): + if self.loss_type == "l1": + loss = (target - pred).abs() + if mean: + loss = loss.mean() + elif self.loss_type == "l2": + if mean: + loss = torch.nn.functional.mse_loss(target, pred) + else: + loss = torch.nn.functional.mse_loss(target, pred, reduction="none") + else: + raise NotImplementedError("unknown loss type '{loss_type}'") + + return loss + + def p_losses(self, x_start, t, noise=None): + noise = default(noise, lambda: torch.randn_like(x_start)) + x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise) + model_out = self.model(x_noisy, t) + + loss_dict = {} + if self.parameterization == "eps": + target = noise + elif self.parameterization == "x0": + target = x_start + elif self.parameterization == "v": + target = self.get_v(x_start, noise, t) + else: + raise NotImplementedError( + f"Parameterization {self.parameterization} not yet supported" + ) + + loss = self.get_loss(model_out, target, mean=False).mean(dim=[1, 2, 3]) + + log_prefix = "train" if self.training else "val" + + loss_dict.update({f"{log_prefix}/loss_simple": loss.mean()}) + loss_simple = loss.mean() * self.l_simple_weight + + loss_vlb = (self.lvlb_weights[t] * loss).mean() + loss_dict.update({f"{log_prefix}/loss_vlb": loss_vlb}) + + loss = loss_simple + self.original_elbo_weight * loss_vlb + + loss_dict.update({f"{log_prefix}/loss": loss}) + + return loss, loss_dict + + def forward(self, x, *args, **kwargs): + # b, c, h, w, device, img_size, = *x.shape, x.device, self.image_size + # assert h == img_size and w == img_size, f'height and width of image must be {img_size}' + t = torch.randint( + 0, self.num_timesteps, (x.shape[0],), device=self.device + ).long() + return self.p_losses(x, t, *args, **kwargs) + + def get_input(self, batch, k): + x = batch[k] + if len(x.shape) == 3: + x = x[..., None] + x = rearrange(x, "b h w c -> b c h w") + x = x.to(memory_format=torch.contiguous_format).float() + return x + + def shared_step(self, batch): + x = self.get_input(batch, self.first_stage_key) + loss, loss_dict = self(x) + return loss, loss_dict + + def training_step(self, batch, batch_idx): + for k in self.ucg_training: + p = self.ucg_training[k]["p"] + val = self.ucg_training[k]["val"] + if val is None: + val = "" + for i in range(len(batch[k])): + if self.ucg_prng.choice(2, p=[1 - p, p]): + batch[k][i] = val + + loss, loss_dict = self.shared_step(batch) + + self.log_dict( + loss_dict, prog_bar=True, logger=True, on_step=True, on_epoch=True + ) + + self.log( + "global_step", + self.global_step, + prog_bar=True, + logger=True, + on_step=True, + on_epoch=False, + ) + + if self.use_scheduler: + lr = self.optimizers().param_groups[0]["lr"] + self.log( + "lr_abs", lr, prog_bar=True, logger=True, on_step=True, on_epoch=False + ) + + return loss + + @torch.no_grad() + def validation_step(self, batch, batch_idx): + _, loss_dict_no_ema = self.shared_step(batch) + with self.ema_scope(): + _, loss_dict_ema = self.shared_step(batch) + loss_dict_ema = {key + "_ema": loss_dict_ema[key] for key in loss_dict_ema} + self.log_dict( + loss_dict_no_ema, prog_bar=False, logger=True, on_step=False, on_epoch=True + ) + self.log_dict( + loss_dict_ema, prog_bar=False, logger=True, on_step=False, on_epoch=True + ) + + def on_train_batch_end(self, *args, **kwargs): + if self.use_ema: + self.model_ema(self.model) + + def _get_rows_from_list(self, samples): + n_imgs_per_row = len(samples) + denoise_grid = rearrange(samples, "n b c h w -> b n c h w") + denoise_grid = rearrange(denoise_grid, "b n c h w -> (b n) c h w") + denoise_grid = make_grid(denoise_grid, nrow=n_imgs_per_row) + return denoise_grid + + @torch.no_grad() + def log_images(self, batch, N=8, n_row=2, sample=True, return_keys=None, **kwargs): + log = dict() + x = self.get_input(batch, self.first_stage_key) + N = min(x.shape[0], N) + n_row = min(x.shape[0], n_row) + x = x.to(self.device)[:N] + log["inputs"] = x + + # get diffusion row + diffusion_row = list() + x_start = x[:n_row] + + for t in range(self.num_timesteps): + if t % self.log_every_t == 0 or t == self.num_timesteps - 1: + t = repeat(torch.tensor([t]), "1 -> b", b=n_row) + t = t.to(self.device).long() + noise = torch.randn_like(x_start) + x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise) + diffusion_row.append(x_noisy) + + log["diffusion_row"] = self._get_rows_from_list(diffusion_row) + + if sample: + # get denoise row + with self.ema_scope("Plotting"): + samples, denoise_row = self.sample( + batch_size=N, return_intermediates=True + ) + + log["samples"] = samples + log["denoise_row"] = self._get_rows_from_list(denoise_row) + + if return_keys: + if np.intersect1d(list(log.keys()), return_keys).shape[0] == 0: + return log + else: + return {key: log[key] for key in return_keys} + return log + + def configure_optimizers(self): + lr = self.learning_rate + params = list(self.model.parameters()) + if self.learn_logvar: + params = params + [self.logvar] + opt = torch.optim.AdamW(params, lr=lr) + return opt + + +class LatentDiffusion(DDPM): + """main class""" + + def __init__( + self, + first_stage_config, + cond_stage_config, + num_timesteps_cond=None, + cond_stage_key="image", + cond_stage_trainable=False, + concat_mode=True, + cond_stage_forward=None, + conditioning_key=None, + scale_factor=1.0, + scale_by_std=False, + force_null_conditioning=False, + *args, + **kwargs, + ): + self.force_null_conditioning = force_null_conditioning + self.num_timesteps_cond = default(num_timesteps_cond, 1) + self.scale_by_std = scale_by_std + assert self.num_timesteps_cond <= kwargs["timesteps"] + # for backwards compatibility after implementation of DiffusionWrapper + if conditioning_key is None: + conditioning_key = "concat" if concat_mode else "crossattn" + if ( + cond_stage_config == "__is_unconditional__" + and not self.force_null_conditioning + ): + conditioning_key = None + ckpt_path = kwargs.pop("ckpt_path", None) + reset_ema = kwargs.pop("reset_ema", False) + reset_num_ema_updates = kwargs.pop("reset_num_ema_updates", False) + ignore_keys = kwargs.pop("ignore_keys", []) + super().__init__(conditioning_key=conditioning_key, *args, **kwargs) + self.concat_mode = concat_mode + self.cond_stage_trainable = cond_stage_trainable + self.cond_stage_key = cond_stage_key + try: + self.num_downs = len(first_stage_config.params.ddconfig.ch_mult) - 1 + except: + self.num_downs = 0 + if not scale_by_std: + self.scale_factor = scale_factor + else: + self.register_buffer("scale_factor", torch.tensor(scale_factor)) + self.instantiate_first_stage(first_stage_config) + self.instantiate_cond_stage(cond_stage_config) + self.cond_stage_forward = cond_stage_forward + self.clip_denoised = False + self.bbox_tokenizer = None + + self.restarted_from_ckpt = False + if ckpt_path is not None: + self.init_from_ckpt(ckpt_path, ignore_keys) + self.restarted_from_ckpt = True + if reset_ema: + assert self.use_ema + print( + f"Resetting ema to pure model weights. This is useful when restoring from an ema-only checkpoint." + ) + self.model_ema = LitEma(self.model) + if reset_num_ema_updates: + print( + " +++++++++++ WARNING: RESETTING NUM_EMA UPDATES TO ZERO +++++++++++ " + ) + assert self.use_ema + self.model_ema.reset_num_updates() + + def make_cond_schedule( + self, + ): + self.cond_ids = torch.full( + size=(self.num_timesteps,), + fill_value=self.num_timesteps - 1, + dtype=torch.long, + ) + ids = torch.round( + torch.linspace(0, self.num_timesteps - 1, self.num_timesteps_cond) + ).long() + self.cond_ids[: self.num_timesteps_cond] = ids + + @torch.no_grad() + def on_train_batch_start(self, batch, batch_idx, dataloader_idx): + # only for very first batch + if ( + self.scale_by_std + and self.current_epoch == 0 + and self.global_step == 0 + and batch_idx == 0 + and not self.restarted_from_ckpt + ): + assert ( + self.scale_factor == 1.0 + ), "rather not use custom rescaling and std-rescaling simultaneously" + # set rescale weight to 1./std of encodings + print("### USING STD-RESCALING ###") + x = super().get_input(batch, self.first_stage_key) + x = x.to(self.device) + encoder_posterior = self.encode_first_stage(x) + z = self.get_first_stage_encoding(encoder_posterior).detach() + del self.scale_factor + self.register_buffer("scale_factor", 1.0 / z.flatten().std()) + print(f"setting self.scale_factor to {self.scale_factor}") + print("### USING STD-RESCALING ###") + + def register_schedule( + self, + given_betas=None, + beta_schedule="linear", + timesteps=1000, + linear_start=1e-4, + linear_end=2e-2, + cosine_s=8e-3, + ): + super().register_schedule( + given_betas, beta_schedule, timesteps, linear_start, linear_end, cosine_s + ) + + self.shorten_cond_schedule = self.num_timesteps_cond > 1 + if self.shorten_cond_schedule: + self.make_cond_schedule() + + def instantiate_first_stage(self, config): + model = instantiate_from_config(config) + self.first_stage_model = model.eval() + self.first_stage_model.train = disabled_train + for param in self.first_stage_model.parameters(): + param.requires_grad = False + + def instantiate_cond_stage(self, config): + if not self.cond_stage_trainable: + if config == "__is_first_stage__": + print("Using first stage also as cond stage.") + self.cond_stage_model = self.first_stage_model + elif config == "__is_unconditional__": + print(f"Training {self.__class__.__name__} as an unconditional model.") + self.cond_stage_model = None + # self.be_unconditional = True + else: + model = instantiate_from_config(config) + self.cond_stage_model = model.eval() + self.cond_stage_model.train = disabled_train + for param in self.cond_stage_model.parameters(): + param.requires_grad = False + else: + assert config != "__is_first_stage__" + assert config != "__is_unconditional__" + model = instantiate_from_config(config) + self.cond_stage_model = model + + def _get_denoise_row_from_list( + self, samples, desc="", force_no_decoder_quantization=False + ): + denoise_row = [] + for zd in tqdm(samples, desc=desc): + denoise_row.append( + self.decode_first_stage( + zd.to(self.device), force_not_quantize=force_no_decoder_quantization + ) + ) + n_imgs_per_row = len(denoise_row) + denoise_row = torch.stack(denoise_row) # n_log_step, n_row, C, H, W + denoise_grid = rearrange(denoise_row, "n b c h w -> b n c h w") + denoise_grid = rearrange(denoise_grid, "b n c h w -> (b n) c h w") + denoise_grid = make_grid(denoise_grid, nrow=n_imgs_per_row) + return denoise_grid + + def get_first_stage_encoding(self, encoder_posterior): + if isinstance(encoder_posterior, DiagonalGaussianDistribution): + z = encoder_posterior.sample() + elif isinstance(encoder_posterior, torch.Tensor): + z = encoder_posterior + else: + raise NotImplementedError( + f"encoder_posterior of type '{type(encoder_posterior)}' not yet implemented" + ) + return self.scale_factor * z + + def get_learned_conditioning(self, c): + if self.cond_stage_forward is None: + if hasattr(self.cond_stage_model, "encode") and callable( + self.cond_stage_model.encode + ): + c = self.cond_stage_model.encode(c) + if isinstance(c, DiagonalGaussianDistribution): + c = c.mode() + else: + c = self.cond_stage_model(c) + else: + assert hasattr(self.cond_stage_model, self.cond_stage_forward) + c = getattr(self.cond_stage_model, self.cond_stage_forward)(c) + return c + + def meshgrid(self, h, w): + y = torch.arange(0, h).view(h, 1, 1).repeat(1, w, 1) + x = torch.arange(0, w).view(1, w, 1).repeat(h, 1, 1) + + arr = torch.cat([y, x], dim=-1) + return arr + + def delta_border(self, h, w): + """ + :param h: height + :param w: width + :return: normalized distance to image border, + wtith min distance = 0 at border and max dist = 0.5 at image center + """ + lower_right_corner = torch.tensor([h - 1, w - 1]).view(1, 1, 2) + arr = self.meshgrid(h, w) / lower_right_corner + dist_left_up = torch.min(arr, dim=-1, keepdims=True)[0] + dist_right_down = torch.min(1 - arr, dim=-1, keepdims=True)[0] + edge_dist = torch.min( + torch.cat([dist_left_up, dist_right_down], dim=-1), dim=-1 + )[0] + return edge_dist + + def get_weighting(self, h, w, Ly, Lx, device): + weighting = self.delta_border(h, w) + weighting = torch.clip( + weighting, + self.split_input_params["clip_min_weight"], + self.split_input_params["clip_max_weight"], + ) + weighting = weighting.view(1, h * w, 1).repeat(1, 1, Ly * Lx).to(device) + + if self.split_input_params["tie_braker"]: + L_weighting = self.delta_border(Ly, Lx) + L_weighting = torch.clip( + L_weighting, + self.split_input_params["clip_min_tie_weight"], + self.split_input_params["clip_max_tie_weight"], + ) + + L_weighting = L_weighting.view(1, 1, Ly * Lx).to(device) + weighting = weighting * L_weighting + return weighting + + def get_fold_unfold( + self, x, kernel_size, stride, uf=1, df=1 + ): # todo load once not every time, shorten code + """ + :param x: img of size (bs, c, h, w) + :return: n img crops of size (n, bs, c, kernel_size[0], kernel_size[1]) + """ + bs, nc, h, w = x.shape + + # number of crops in image + Ly = (h - kernel_size[0]) // stride[0] + 1 + Lx = (w - kernel_size[1]) // stride[1] + 1 + + if uf == 1 and df == 1: + fold_params = dict( + kernel_size=kernel_size, dilation=1, padding=0, stride=stride + ) + unfold = torch.nn.Unfold(**fold_params) + + fold = torch.nn.Fold(output_size=x.shape[2:], **fold_params) + + weighting = self.get_weighting( + kernel_size[0], kernel_size[1], Ly, Lx, x.device + ).to(x.dtype) + normalization = fold(weighting).view(1, 1, h, w) # normalizes the overlap + weighting = weighting.view((1, 1, kernel_size[0], kernel_size[1], Ly * Lx)) + + elif uf > 1 and df == 1: + fold_params = dict( + kernel_size=kernel_size, dilation=1, padding=0, stride=stride + ) + unfold = torch.nn.Unfold(**fold_params) + + fold_params2 = dict( + kernel_size=(kernel_size[0] * uf, kernel_size[0] * uf), + dilation=1, + padding=0, + stride=(stride[0] * uf, stride[1] * uf), + ) + fold = torch.nn.Fold( + output_size=(x.shape[2] * uf, x.shape[3] * uf), **fold_params2 + ) + + weighting = self.get_weighting( + kernel_size[0] * uf, kernel_size[1] * uf, Ly, Lx, x.device + ).to(x.dtype) + normalization = fold(weighting).view( + 1, 1, h * uf, w * uf + ) # normalizes the overlap + weighting = weighting.view( + (1, 1, kernel_size[0] * uf, kernel_size[1] * uf, Ly * Lx) + ) + + elif df > 1 and uf == 1: + fold_params = dict( + kernel_size=kernel_size, dilation=1, padding=0, stride=stride + ) + unfold = torch.nn.Unfold(**fold_params) + + fold_params2 = dict( + kernel_size=(kernel_size[0] // df, kernel_size[0] // df), + dilation=1, + padding=0, + stride=(stride[0] // df, stride[1] // df), + ) + fold = torch.nn.Fold( + output_size=(x.shape[2] // df, x.shape[3] // df), **fold_params2 + ) + + weighting = self.get_weighting( + kernel_size[0] // df, kernel_size[1] // df, Ly, Lx, x.device + ).to(x.dtype) + normalization = fold(weighting).view( + 1, 1, h // df, w // df + ) # normalizes the overlap + weighting = weighting.view( + (1, 1, kernel_size[0] // df, kernel_size[1] // df, Ly * Lx) + ) + + else: + raise NotImplementedError + + return fold, unfold, normalization, weighting + + @torch.no_grad() + def get_input( + self, + batch, + k, + return_first_stage_outputs=False, + force_c_encode=False, + cond_key=None, + return_original_cond=False, + bs=None, + return_x=False, + mask_k=None, + ): + x = super().get_input(batch, k) + if bs is not None: + x = x[:bs] + x = x.to(self.device) + encoder_posterior = self.encode_first_stage(x) + z = self.get_first_stage_encoding(encoder_posterior).detach() + + if mask_k is not None: + mx = super().get_input(batch, mask_k) + if bs is not None: + mx = mx[:bs] + mx = mx.to(self.device) + encoder_posterior = self.encode_first_stage(mx) + mx = self.get_first_stage_encoding(encoder_posterior).detach() + + if self.model.conditioning_key is not None and not self.force_null_conditioning: + if cond_key is None: + cond_key = self.cond_stage_key + if cond_key != self.first_stage_key: + if cond_key in ["caption", "coordinates_bbox", "txt"]: + xc = batch[cond_key] + elif cond_key in ["class_label", "cls"]: + xc = batch + else: + xc = super().get_input(batch, cond_key).to(self.device) + else: + xc = x + if not self.cond_stage_trainable or force_c_encode: + if isinstance(xc, dict) or isinstance(xc, list): + c = self.get_learned_conditioning(xc) + else: + c = self.get_learned_conditioning(xc.to(self.device)) + else: + c = xc + if bs is not None: + c = c[:bs] + + if self.use_positional_encodings: + pos_x, pos_y = self.compute_latent_shifts(batch) + ckey = __conditioning_keys__[self.model.conditioning_key] + c = {ckey: c, "pos_x": pos_x, "pos_y": pos_y} + + else: + c = None + xc = None + if self.use_positional_encodings: + pos_x, pos_y = self.compute_latent_shifts(batch) + c = {"pos_x": pos_x, "pos_y": pos_y} + out = [z, c] + if return_first_stage_outputs: + xrec = self.decode_first_stage(z) + out.extend([x, xrec]) + if return_x: + out.extend([x]) + if return_original_cond: + out.append(xc) + if mask_k: + out.append(mx) + return out + + @torch.no_grad() + def decode_first_stage(self, z, predict_cids=False, force_not_quantize=False): + if predict_cids: + if z.dim() == 4: + z = torch.argmax(z.exp(), dim=1).long() + z = self.first_stage_model.quantize.get_codebook_entry(z, shape=None) + z = rearrange(z, "b h w c -> b c h w").contiguous() + + z = 1.0 / self.scale_factor * z + return self.first_stage_model.decode(z) + + def decode_first_stage_grad(self, z, predict_cids=False, force_not_quantize=False): + if predict_cids: + if z.dim() == 4: + z = torch.argmax(z.exp(), dim=1).long() + z = self.first_stage_model.quantize.get_codebook_entry(z, shape=None) + z = rearrange(z, "b h w c -> b c h w").contiguous() + + z = 1.0 / self.scale_factor * z + return self.first_stage_model.decode(z) + + @torch.no_grad() + def encode_first_stage(self, x): + return self.first_stage_model.encode(x) + + def shared_step(self, batch, **kwargs): + x, c = self.get_input(batch, self.first_stage_key) + loss = self(x, c) + return loss + + def forward(self, x, c, *args, **kwargs): + t = torch.randint( + 0, self.num_timesteps, (x.shape[0],), device=self.device + ).long() + # t = torch.randint(500, 501, (x.shape[0],), device=self.device).long() + if self.model.conditioning_key is not None: + assert c is not None + if self.cond_stage_trainable: + c = self.get_learned_conditioning(c) + if self.shorten_cond_schedule: # TODO: drop this option + tc = self.cond_ids[t].to(self.device) + c = self.q_sample(x_start=c, t=tc, noise=torch.randn_like(c.float())) + return self.p_losses(x, c, t, *args, **kwargs) + + def apply_model(self, x_noisy, t, cond, return_ids=False): + if isinstance(cond, dict): + # hybrid case, cond is expected to be a dict + pass + else: + if not isinstance(cond, list): + cond = [cond] + key = ( + "c_concat" if self.model.conditioning_key == "concat" else "c_crossattn" + ) + cond = {key: cond} + + x_recon = self.model(x_noisy, t, **cond) + + if isinstance(x_recon, tuple) and not return_ids: + return x_recon[0] + else: + return x_recon + + def _predict_eps_from_xstart(self, x_t, t, pred_xstart): + return ( + extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t + - pred_xstart + ) / extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) + + def _prior_bpd(self, x_start): + """ + Get the prior KL term for the variational lower-bound, measured in + bits-per-dim. + This term can't be optimized, as it only depends on the encoder. + :param x_start: the [N x C x ...] tensor of inputs. + :return: a batch of [N] KL values (in bits), one per batch element. + """ + batch_size = x_start.shape[0] + t = torch.tensor([self.num_timesteps - 1] * batch_size, device=x_start.device) + qt_mean, _, qt_log_variance = self.q_mean_variance(x_start, t) + kl_prior = normal_kl( + mean1=qt_mean, logvar1=qt_log_variance, mean2=0.0, logvar2=0.0 + ) + return mean_flat(kl_prior) / np.log(2.0) + + def p_mean_variance( + self, + x, + c, + t, + clip_denoised: bool, + return_codebook_ids=False, + quantize_denoised=False, + return_x0=False, + score_corrector=None, + corrector_kwargs=None, + ): + t_in = t + model_out = self.apply_model(x, t_in, c, return_ids=return_codebook_ids) + + if score_corrector is not None: + assert self.parameterization == "eps" + model_out = score_corrector.modify_score( + self, model_out, x, t, c, **corrector_kwargs + ) + + if return_codebook_ids: + model_out, logits = model_out + + if self.parameterization == "eps": + x_recon = self.predict_start_from_noise(x, t=t, noise=model_out) + elif self.parameterization == "x0": + x_recon = model_out + else: + raise NotImplementedError() + + if clip_denoised: + x_recon.clamp_(-1.0, 1.0) + if quantize_denoised: + x_recon, _, [_, _, indices] = self.first_stage_model.quantize(x_recon) + model_mean, posterior_variance, posterior_log_variance = self.q_posterior( + x_start=x_recon, x_t=x, t=t + ) + if return_codebook_ids: + return model_mean, posterior_variance, posterior_log_variance, logits + elif return_x0: + return model_mean, posterior_variance, posterior_log_variance, x_recon + else: + return model_mean, posterior_variance, posterior_log_variance + + @torch.no_grad() + def p_sample( + self, + x, + c, + t, + clip_denoised=False, + repeat_noise=False, + return_codebook_ids=False, + quantize_denoised=False, + return_x0=False, + temperature=1.0, + noise_dropout=0.0, + score_corrector=None, + corrector_kwargs=None, + ): + b, *_, device = *x.shape, x.device + outputs = self.p_mean_variance( + x=x, + c=c, + t=t, + clip_denoised=clip_denoised, + return_codebook_ids=return_codebook_ids, + quantize_denoised=quantize_denoised, + return_x0=return_x0, + score_corrector=score_corrector, + corrector_kwargs=corrector_kwargs, + ) + if return_codebook_ids: + raise DeprecationWarning("Support dropped.") + model_mean, _, model_log_variance, logits = outputs + elif return_x0: + model_mean, _, model_log_variance, x0 = outputs + else: + model_mean, _, model_log_variance = outputs + + noise = noise_like(x.shape, device, repeat_noise) * temperature + if noise_dropout > 0.0: + noise = torch.nn.functional.dropout(noise, p=noise_dropout) + # no noise when t == 0 + nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1))) + + if return_codebook_ids: + return model_mean + nonzero_mask * ( + 0.5 * model_log_variance + ).exp() * noise, logits.argmax(dim=1) + if return_x0: + return ( + model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise, + x0, + ) + else: + return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise + + @torch.no_grad() + def progressive_denoising( + self, + cond, + shape, + verbose=True, + callback=None, + quantize_denoised=False, + img_callback=None, + mask=None, + x0=None, + temperature=1.0, + noise_dropout=0.0, + score_corrector=None, + corrector_kwargs=None, + batch_size=None, + x_T=None, + start_T=None, + log_every_t=None, + ): + if not log_every_t: + log_every_t = self.log_every_t + timesteps = self.num_timesteps + if batch_size is not None: + b = batch_size if batch_size is not None else shape[0] + shape = [batch_size] + list(shape) + else: + b = batch_size = shape[0] + if x_T is None: + img = torch.randn(shape, device=self.device) + else: + img = x_T + intermediates = [] + if cond is not None: + if isinstance(cond, dict): + cond = { + key: cond[key][:batch_size] + if not isinstance(cond[key], list) + else list(map(lambda x: x[:batch_size], cond[key])) + for key in cond + } + else: + cond = ( + [c[:batch_size] for c in cond] + if isinstance(cond, list) + else cond[:batch_size] + ) + + if start_T is not None: + timesteps = min(timesteps, start_T) + iterator = ( + tqdm( + reversed(range(0, timesteps)), + desc="Progressive Generation", + total=timesteps, + ) + if verbose + else reversed(range(0, timesteps)) + ) + if type(temperature) == float: + temperature = [temperature] * timesteps + + for i in iterator: + ts = torch.full((b,), i, device=self.device, dtype=torch.long) + if self.shorten_cond_schedule: + assert self.model.conditioning_key != "hybrid" + tc = self.cond_ids[ts].to(cond.device) + cond = self.q_sample(x_start=cond, t=tc, noise=torch.randn_like(cond)) + + img, x0_partial = self.p_sample( + img, + cond, + ts, + clip_denoised=self.clip_denoised, + quantize_denoised=quantize_denoised, + return_x0=True, + temperature=temperature[i], + noise_dropout=noise_dropout, + score_corrector=score_corrector, + corrector_kwargs=corrector_kwargs, + ) + if mask is not None: + assert x0 is not None + img_orig = self.q_sample(x0, ts) + img = img_orig * mask + (1.0 - mask) * img + + if i % log_every_t == 0 or i == timesteps - 1: + intermediates.append(x0_partial) + if callback: + callback(i) + if img_callback: + img_callback(img, i) + return img, intermediates + + @torch.no_grad() + def p_sample_loop( + self, + cond, + shape, + return_intermediates=False, + x_T=None, + verbose=True, + callback=None, + timesteps=None, + quantize_denoised=False, + mask=None, + x0=None, + img_callback=None, + start_T=None, + log_every_t=None, + ): + if not log_every_t: + log_every_t = self.log_every_t + device = self.betas.device + b = shape[0] + if x_T is None: + img = torch.randn(shape, device=device) + else: + img = x_T + + intermediates = [img] + if timesteps is None: + timesteps = self.num_timesteps + + if start_T is not None: + timesteps = min(timesteps, start_T) + iterator = ( + tqdm(reversed(range(0, timesteps)), desc="Sampling t", total=timesteps) + if verbose + else reversed(range(0, timesteps)) + ) + + if mask is not None: + assert x0 is not None + assert x0.shape[2:3] == mask.shape[2:3] # spatial size has to match + + for i in iterator: + ts = torch.full((b,), i, device=device, dtype=torch.long) + if self.shorten_cond_schedule: + assert self.model.conditioning_key != "hybrid" + tc = self.cond_ids[ts].to(cond.device) + cond = self.q_sample(x_start=cond, t=tc, noise=torch.randn_like(cond)) + + img = self.p_sample( + img, + cond, + ts, + clip_denoised=self.clip_denoised, + quantize_denoised=quantize_denoised, + ) + if mask is not None: + img_orig = self.q_sample(x0, ts) + img = img_orig * mask + (1.0 - mask) * img + + if i % log_every_t == 0 or i == timesteps - 1: + intermediates.append(img) + if callback: + callback(i) + if img_callback: + img_callback(img, i) + + if return_intermediates: + return img, intermediates + return img + + @torch.no_grad() + def sample( + self, + cond, + batch_size=16, + return_intermediates=False, + x_T=None, + verbose=True, + timesteps=None, + quantize_denoised=False, + mask=None, + x0=None, + shape=None, + **kwargs, + ): + if shape is None: + shape = (batch_size, self.channels, self.image_size, self.image_size) + if cond is not None: + if isinstance(cond, dict): + cond = { + key: cond[key][:batch_size] + if not isinstance(cond[key], list) + else list(map(lambda x: x[:batch_size], cond[key])) + for key in cond + } + else: + cond = ( + [c[:batch_size] for c in cond] + if isinstance(cond, list) + else cond[:batch_size] + ) + return self.p_sample_loop( + cond, + shape, + return_intermediates=return_intermediates, + x_T=x_T, + verbose=verbose, + timesteps=timesteps, + quantize_denoised=quantize_denoised, + mask=mask, + x0=x0, + ) + + @torch.no_grad() + def sample_log(self, cond, batch_size, ddim, ddim_steps, **kwargs): + if ddim: + ddim_sampler = DDIMSampler(self) + shape = (self.channels, self.image_size, self.image_size) + samples, intermediates = ddim_sampler.sample( + ddim_steps, batch_size, shape, cond, verbose=False, **kwargs + ) + + else: + samples, intermediates = self.sample( + cond=cond, batch_size=batch_size, return_intermediates=True, **kwargs + ) + + return samples, intermediates + + @torch.no_grad() + def get_unconditional_conditioning(self, batch_size, null_label=None): + if null_label is not None: + xc = null_label + if isinstance(xc, ListConfig): + xc = list(xc) + if isinstance(xc, dict) or isinstance(xc, list): + c = self.get_learned_conditioning(xc) + else: + if hasattr(xc, "to"): + xc = xc.to(self.device) + c = self.get_learned_conditioning(xc) + else: + if self.cond_stage_key in ["class_label", "cls"]: + xc = self.cond_stage_model.get_unconditional_conditioning( + batch_size, device=self.device + ) + return self.get_learned_conditioning(xc) + else: + raise NotImplementedError("todo") + if isinstance(c, list): # in case the encoder gives us a list + for i in range(len(c)): + c[i] = repeat(c[i], "1 ... -> b ...", b=batch_size).to(self.device) + else: + c = repeat(c, "1 ... -> b ...", b=batch_size).to(self.device) + return c + + @torch.no_grad() + def log_images( + self, + batch, + N=8, + n_row=4, + sample=True, + ddim_steps=50, + ddim_eta=0.0, + return_keys=None, + quantize_denoised=True, + inpaint=True, + plot_denoise_rows=False, + plot_progressive_rows=True, + plot_diffusion_rows=True, + unconditional_guidance_scale=1.0, + unconditional_guidance_label=None, + use_ema_scope=True, + **kwargs, + ): + ema_scope = self.ema_scope if use_ema_scope else nullcontext + use_ddim = ddim_steps is not None + + log = dict() + z, c, x, xrec, xc = self.get_input( + batch, + self.first_stage_key, + return_first_stage_outputs=True, + force_c_encode=True, + return_original_cond=True, + bs=N, + ) + N = min(x.shape[0], N) + n_row = min(x.shape[0], n_row) + log["inputs"] = x + log["reconstruction"] = xrec + if self.model.conditioning_key is not None: + if hasattr(self.cond_stage_model, "decode"): + xc = self.cond_stage_model.decode(c) + log["conditioning"] = xc + elif self.cond_stage_key in ["caption", "txt"]: + xc = log_txt_as_img( + (x.shape[2], x.shape[3]), + batch[self.cond_stage_key], + size=x.shape[2] // 25, + ) + log["conditioning"] = xc + elif self.cond_stage_key in ["class_label", "cls"]: + try: + xc = log_txt_as_img( + (x.shape[2], x.shape[3]), + batch["human_label"], + size=x.shape[2] // 25, + ) + log["conditioning"] = xc + except KeyError: + # probably no "human_label" in batch + pass + elif isimage(xc): + log["conditioning"] = xc + if ismap(xc): + log["original_conditioning"] = self.to_rgb(xc) + + if plot_diffusion_rows: + # get diffusion row + diffusion_row = list() + z_start = z[:n_row] + for t in range(self.num_timesteps): + if t % self.log_every_t == 0 or t == self.num_timesteps - 1: + t = repeat(torch.tensor([t]), "1 -> b", b=n_row) + t = t.to(self.device).long() + noise = torch.randn_like(z_start) + z_noisy = self.q_sample(x_start=z_start, t=t, noise=noise) + diffusion_row.append(self.decode_first_stage(z_noisy)) + + diffusion_row = torch.stack(diffusion_row) # n_log_step, n_row, C, H, W + diffusion_grid = rearrange(diffusion_row, "n b c h w -> b n c h w") + diffusion_grid = rearrange(diffusion_grid, "b n c h w -> (b n) c h w") + diffusion_grid = make_grid(diffusion_grid, nrow=diffusion_row.shape[0]) + log["diffusion_row"] = diffusion_grid + + if sample: + # get denoise row + with ema_scope("Sampling"): + samples, z_denoise_row = self.sample_log( + cond=c, + batch_size=N, + ddim=use_ddim, + ddim_steps=ddim_steps, + eta=ddim_eta, + ) + # samples, z_denoise_row = self.sample(cond=c, batch_size=N, return_intermediates=True) + x_samples = self.decode_first_stage(samples) + log["samples"] = x_samples + if plot_denoise_rows: + denoise_grid = self._get_denoise_row_from_list(z_denoise_row) + log["denoise_row"] = denoise_grid + + if ( + quantize_denoised + and not isinstance(self.first_stage_model, AutoencoderKL) + and not isinstance(self.first_stage_model, IdentityFirstStage) + ): + # also display when quantizing x0 while sampling + with ema_scope("Plotting Quantized Denoised"): + samples, z_denoise_row = self.sample_log( + cond=c, + batch_size=N, + ddim=use_ddim, + ddim_steps=ddim_steps, + eta=ddim_eta, + quantize_denoised=True, + ) + # samples, z_denoise_row = self.sample(cond=c, batch_size=N, return_intermediates=True, + # quantize_denoised=True) + x_samples = self.decode_first_stage(samples.to(self.device)) + log["samples_x0_quantized"] = x_samples + + if unconditional_guidance_scale > 1.0: + uc = self.get_unconditional_conditioning(N, unconditional_guidance_label) + if self.model.conditioning_key == "crossattn-adm": + uc = {"c_crossattn": [uc], "c_adm": c["c_adm"]} + with ema_scope("Sampling with classifier-free guidance"): + samples_cfg, _ = self.sample_log( + cond=c, + batch_size=N, + ddim=use_ddim, + ddim_steps=ddim_steps, + eta=ddim_eta, + unconditional_guidance_scale=unconditional_guidance_scale, + unconditional_conditioning=uc, + ) + x_samples_cfg = self.decode_first_stage(samples_cfg) + log[ + f"samples_cfg_scale_{unconditional_guidance_scale:.2f}" + ] = x_samples_cfg + + if inpaint: + # make a simple center square + b, h, w = z.shape[0], z.shape[2], z.shape[3] + mask = torch.ones(N, h, w).to(self.device) + # zeros will be filled in + mask[:, h // 4 : 3 * h // 4, w // 4 : 3 * w // 4] = 0.0 + mask = mask[:, None, ...] + with ema_scope("Plotting Inpaint"): + samples, _ = self.sample_log( + cond=c, + batch_size=N, + ddim=use_ddim, + eta=ddim_eta, + ddim_steps=ddim_steps, + x0=z[:N], + mask=mask, + ) + x_samples = self.decode_first_stage(samples.to(self.device)) + log["samples_inpainting"] = x_samples + log["mask"] = mask + + # outpaint + mask = 1.0 - mask + with ema_scope("Plotting Outpaint"): + samples, _ = self.sample_log( + cond=c, + batch_size=N, + ddim=use_ddim, + eta=ddim_eta, + ddim_steps=ddim_steps, + x0=z[:N], + mask=mask, + ) + x_samples = self.decode_first_stage(samples.to(self.device)) + log["samples_outpainting"] = x_samples + + if plot_progressive_rows: + with ema_scope("Plotting Progressives"): + img, progressives = self.progressive_denoising( + c, + shape=(self.channels, self.image_size, self.image_size), + batch_size=N, + ) + prog_row = self._get_denoise_row_from_list( + progressives, desc="Progressive Generation" + ) + log["progressive_row"] = prog_row + + if return_keys: + if np.intersect1d(list(log.keys()), return_keys).shape[0] == 0: + return log + else: + return {key: log[key] for key in return_keys} + return log + + def configure_optimizers(self): + lr = self.learning_rate + params = list(self.model.parameters()) + if self.cond_stage_trainable: + print(f"{self.__class__.__name__}: Also optimizing conditioner params!") + params = params + list(self.cond_stage_model.parameters()) + if self.learn_logvar: + print("Diffusion model optimizing logvar") + params.append(self.logvar) + opt = torch.optim.AdamW(params, lr=lr) + if self.use_scheduler: + assert "target" in self.scheduler_config + scheduler = instantiate_from_config(self.scheduler_config) + + print("Setting up LambdaLR scheduler...") + scheduler = [ + { + "scheduler": LambdaLR(opt, lr_lambda=scheduler.schedule), + "interval": "step", + "frequency": 1, + } + ] + return [opt], scheduler + return opt + + @torch.no_grad() + def to_rgb(self, x): + x = x.float() + if not hasattr(self, "colorize"): + self.colorize = torch.randn(3, x.shape[1], 1, 1).to(x) + x = nn.functional.conv2d(x, weight=self.colorize) + x = 2.0 * (x - x.min()) / (x.max() - x.min()) - 1.0 + return x + + +class DiffusionWrapper(torch.nn.Module): + def __init__(self, diff_model_config, conditioning_key): + super().__init__() + self.sequential_cross_attn = diff_model_config.pop( + "sequential_crossattn", False + ) + self.diffusion_model = instantiate_from_config(diff_model_config) + self.conditioning_key = conditioning_key + assert self.conditioning_key in [ + None, + "concat", + "crossattn", + "hybrid", + "adm", + "hybrid-adm", + "crossattn-adm", + ] + + def forward( + self, x, t, c_concat: list = None, c_crossattn: list = None, c_adm=None + ): + if self.conditioning_key is None: + out = self.diffusion_model(x, t) + elif self.conditioning_key == "concat": + xc = torch.cat([x] + c_concat, dim=1) + out = self.diffusion_model(xc, t) + elif self.conditioning_key == "crossattn": + if not self.sequential_cross_attn: + cc = torch.cat(c_crossattn, 1) + else: + cc = c_crossattn + out = self.diffusion_model(x, t, context=cc) + elif self.conditioning_key == "hybrid": + xc = torch.cat([x] + c_concat, dim=1) + cc = torch.cat(c_crossattn, 1) + out = self.diffusion_model(xc, t, context=cc) + elif self.conditioning_key == "hybrid-adm": + assert c_adm is not None + xc = torch.cat([x] + c_concat, dim=1) + cc = torch.cat(c_crossattn, 1) + out = self.diffusion_model(xc, t, context=cc, y=c_adm) + elif self.conditioning_key == "crossattn-adm": + assert c_adm is not None + cc = torch.cat(c_crossattn, 1) + out = self.diffusion_model(x, t, context=cc, y=c_adm) + elif self.conditioning_key == "adm": + cc = c_crossattn[0] + out = self.diffusion_model(x, t, y=cc) + else: + raise NotImplementedError() + + return out + + +class LatentUpscaleDiffusion(LatentDiffusion): + def __init__( + self, + *args, + low_scale_config, + low_scale_key="LR", + noise_level_key=None, + **kwargs, + ): + super().__init__(*args, **kwargs) + # assumes that neither the cond_stage nor the low_scale_model contain trainable params + assert not self.cond_stage_trainable + self.instantiate_low_stage(low_scale_config) + self.low_scale_key = low_scale_key + self.noise_level_key = noise_level_key + + def instantiate_low_stage(self, config): + model = instantiate_from_config(config) + self.low_scale_model = model.eval() + self.low_scale_model.train = disabled_train + for param in self.low_scale_model.parameters(): + param.requires_grad = False + + @torch.no_grad() + def get_input(self, batch, k, cond_key=None, bs=None, log_mode=False): + if not log_mode: + z, c = super().get_input(batch, k, force_c_encode=True, bs=bs) + else: + z, c, x, xrec, xc = super().get_input( + batch, + self.first_stage_key, + return_first_stage_outputs=True, + force_c_encode=True, + return_original_cond=True, + bs=bs, + ) + x_low = batch[self.low_scale_key][:bs] + x_low = rearrange(x_low, "b h w c -> b c h w") + x_low = x_low.to(memory_format=torch.contiguous_format).float() + zx, noise_level = self.low_scale_model(x_low) + if self.noise_level_key is not None: + # get noise level from batch instead, e.g. when extracting a custom noise level for bsr + raise NotImplementedError("TODO") + + all_conds = {"c_concat": [zx], "c_crossattn": [c], "c_adm": noise_level} + if log_mode: + # TODO: maybe disable if too expensive + x_low_rec = self.low_scale_model.decode(zx) + return z, all_conds, x, xrec, xc, x_low, x_low_rec, noise_level + return z, all_conds + + @torch.no_grad() + def log_images( + self, + batch, + N=8, + n_row=4, + sample=True, + ddim_steps=200, + ddim_eta=1.0, + return_keys=None, + plot_denoise_rows=False, + plot_progressive_rows=True, + plot_diffusion_rows=True, + unconditional_guidance_scale=1.0, + unconditional_guidance_label=None, + use_ema_scope=True, + **kwargs, + ): + ema_scope = self.ema_scope if use_ema_scope else nullcontext + use_ddim = ddim_steps is not None + + log = dict() + z, c, x, xrec, xc, x_low, x_low_rec, noise_level = self.get_input( + batch, self.first_stage_key, bs=N, log_mode=True + ) + N = min(x.shape[0], N) + n_row = min(x.shape[0], n_row) + log["inputs"] = x + log["reconstruction"] = xrec + log["x_lr"] = x_low + log[ + f"x_lr_rec_@noise_levels{'-'.join(map(lambda x: str(x), list(noise_level.cpu().numpy())))}" + ] = x_low_rec + if self.model.conditioning_key is not None: + if hasattr(self.cond_stage_model, "decode"): + xc = self.cond_stage_model.decode(c) + log["conditioning"] = xc + elif self.cond_stage_key in ["caption", "txt"]: + xc = log_txt_as_img( + (x.shape[2], x.shape[3]), + batch[self.cond_stage_key], + size=x.shape[2] // 25, + ) + log["conditioning"] = xc + elif self.cond_stage_key in ["class_label", "cls"]: + xc = log_txt_as_img( + (x.shape[2], x.shape[3]), + batch["human_label"], + size=x.shape[2] // 25, + ) + log["conditioning"] = xc + elif isimage(xc): + log["conditioning"] = xc + if ismap(xc): + log["original_conditioning"] = self.to_rgb(xc) + + if plot_diffusion_rows: + # get diffusion row + diffusion_row = list() + z_start = z[:n_row] + for t in range(self.num_timesteps): + if t % self.log_every_t == 0 or t == self.num_timesteps - 1: + t = repeat(torch.tensor([t]), "1 -> b", b=n_row) + t = t.to(self.device).long() + noise = torch.randn_like(z_start) + z_noisy = self.q_sample(x_start=z_start, t=t, noise=noise) + diffusion_row.append(self.decode_first_stage(z_noisy)) + + diffusion_row = torch.stack(diffusion_row) # n_log_step, n_row, C, H, W + diffusion_grid = rearrange(diffusion_row, "n b c h w -> b n c h w") + diffusion_grid = rearrange(diffusion_grid, "b n c h w -> (b n) c h w") + diffusion_grid = make_grid(diffusion_grid, nrow=diffusion_row.shape[0]) + log["diffusion_row"] = diffusion_grid + + if sample: + # get denoise row + with ema_scope("Sampling"): + samples, z_denoise_row = self.sample_log( + cond=c, + batch_size=N, + ddim=use_ddim, + ddim_steps=ddim_steps, + eta=ddim_eta, + ) + # samples, z_denoise_row = self.sample(cond=c, batch_size=N, return_intermediates=True) + x_samples = self.decode_first_stage(samples) + log["samples"] = x_samples + if plot_denoise_rows: + denoise_grid = self._get_denoise_row_from_list(z_denoise_row) + log["denoise_row"] = denoise_grid + + if unconditional_guidance_scale > 1.0: + uc_tmp = self.get_unconditional_conditioning( + N, unconditional_guidance_label + ) + # TODO explore better "unconditional" choices for the other keys + # maybe guide away from empty text label and highest noise level and maximally degraded zx? + uc = dict() + for k in c: + if k == "c_crossattn": + assert isinstance(c[k], list) and len(c[k]) == 1 + uc[k] = [uc_tmp] + elif k == "c_adm": # todo: only run with text-based guidance? + assert isinstance(c[k], torch.Tensor) + # uc[k] = torch.ones_like(c[k]) * self.low_scale_model.max_noise_level + uc[k] = c[k] + elif isinstance(c[k], list): + uc[k] = [c[k][i] for i in range(len(c[k]))] + else: + uc[k] = c[k] + + with ema_scope("Sampling with classifier-free guidance"): + samples_cfg, _ = self.sample_log( + cond=c, + batch_size=N, + ddim=use_ddim, + ddim_steps=ddim_steps, + eta=ddim_eta, + unconditional_guidance_scale=unconditional_guidance_scale, + unconditional_conditioning=uc, + ) + x_samples_cfg = self.decode_first_stage(samples_cfg) + log[ + f"samples_cfg_scale_{unconditional_guidance_scale:.2f}" + ] = x_samples_cfg + + if plot_progressive_rows: + with ema_scope("Plotting Progressives"): + img, progressives = self.progressive_denoising( + c, + shape=(self.channels, self.image_size, self.image_size), + batch_size=N, + ) + prog_row = self._get_denoise_row_from_list( + progressives, desc="Progressive Generation" + ) + log["progressive_row"] = prog_row + + return log + + +class LatentFinetuneDiffusion(LatentDiffusion): + """ + Basis for different finetunas, such as inpainting or depth2image + To disable finetuning mode, set finetune_keys to None + """ + + def __init__( + self, + concat_keys: tuple, + finetune_keys=( + "model.diffusion_model.input_blocks.0.0.weight", + "model_ema.diffusion_modelinput_blocks00weight", + ), + keep_finetune_dims=4, + # if model was trained without concat mode before and we would like to keep these channels + c_concat_log_start=None, # to log reconstruction of c_concat codes + c_concat_log_end=None, + *args, + **kwargs, + ): + ckpt_path = kwargs.pop("ckpt_path", None) + ignore_keys = kwargs.pop("ignore_keys", list()) + super().__init__(*args, **kwargs) + self.finetune_keys = finetune_keys + self.concat_keys = concat_keys + self.keep_dims = keep_finetune_dims + self.c_concat_log_start = c_concat_log_start + self.c_concat_log_end = c_concat_log_end + if exists(self.finetune_keys): + assert exists(ckpt_path), "can only finetune from a given checkpoint" + if exists(ckpt_path): + self.init_from_ckpt(ckpt_path, ignore_keys) + + def init_from_ckpt(self, path, ignore_keys=list(), only_model=False): + sd = torch.load(path, map_location="cpu") + if "state_dict" in list(sd.keys()): + sd = sd["state_dict"] + keys = list(sd.keys()) + for k in keys: + for ik in ignore_keys: + if k.startswith(ik): + print("Deleting key {} from state_dict.".format(k)) + del sd[k] + + # make it explicit, finetune by including extra input channels + if exists(self.finetune_keys) and k in self.finetune_keys: + new_entry = None + for name, param in self.named_parameters(): + if name in self.finetune_keys: + print( + f"modifying key '{name}' and keeping its original {self.keep_dims} (channels) dimensions only" + ) + new_entry = torch.zeros_like(param) # zero init + assert exists(new_entry), "did not find matching parameter to modify" + new_entry[:, : self.keep_dims, ...] = sd[k] + sd[k] = new_entry + + missing, unexpected = ( + self.load_state_dict(sd, strict=False) + if not only_model + else self.model.load_state_dict(sd, strict=False) + ) + print( + f"Restored from {path} with {len(missing)} missing and {len(unexpected)} unexpected keys" + ) + if len(missing) > 0: + print(f"Missing Keys: {missing}") + if len(unexpected) > 0: + print(f"Unexpected Keys: {unexpected}") + + @torch.no_grad() + def log_images( + self, + batch, + N=8, + n_row=4, + sample=True, + ddim_steps=200, + ddim_eta=1.0, + return_keys=None, + quantize_denoised=True, + inpaint=True, + plot_denoise_rows=False, + plot_progressive_rows=True, + plot_diffusion_rows=True, + unconditional_guidance_scale=1.0, + unconditional_guidance_label=None, + use_ema_scope=True, + **kwargs, + ): + ema_scope = self.ema_scope if use_ema_scope else nullcontext + use_ddim = ddim_steps is not None + + log = dict() + z, c, x, xrec, xc = self.get_input( + batch, self.first_stage_key, bs=N, return_first_stage_outputs=True + ) + c_cat, c = c["c_concat"][0], c["c_crossattn"][0] + N = min(x.shape[0], N) + n_row = min(x.shape[0], n_row) + log["inputs"] = x + log["reconstruction"] = xrec + if self.model.conditioning_key is not None: + if hasattr(self.cond_stage_model, "decode"): + xc = self.cond_stage_model.decode(c) + log["conditioning"] = xc + elif self.cond_stage_key in ["caption", "txt"]: + xc = log_txt_as_img( + (x.shape[2], x.shape[3]), + batch[self.cond_stage_key], + size=x.shape[2] // 25, + ) + log["conditioning"] = xc + elif self.cond_stage_key in ["class_label", "cls"]: + xc = log_txt_as_img( + (x.shape[2], x.shape[3]), + batch["human_label"], + size=x.shape[2] // 25, + ) + log["conditioning"] = xc + elif isimage(xc): + log["conditioning"] = xc + if ismap(xc): + log["original_conditioning"] = self.to_rgb(xc) + + if not (self.c_concat_log_start is None and self.c_concat_log_end is None): + log["c_concat_decoded"] = self.decode_first_stage( + c_cat[:, self.c_concat_log_start : self.c_concat_log_end] + ) + + if plot_diffusion_rows: + # get diffusion row + diffusion_row = list() + z_start = z[:n_row] + for t in range(self.num_timesteps): + if t % self.log_every_t == 0 or t == self.num_timesteps - 1: + t = repeat(torch.tensor([t]), "1 -> b", b=n_row) + t = t.to(self.device).long() + noise = torch.randn_like(z_start) + z_noisy = self.q_sample(x_start=z_start, t=t, noise=noise) + diffusion_row.append(self.decode_first_stage(z_noisy)) + + diffusion_row = torch.stack(diffusion_row) # n_log_step, n_row, C, H, W + diffusion_grid = rearrange(diffusion_row, "n b c h w -> b n c h w") + diffusion_grid = rearrange(diffusion_grid, "b n c h w -> (b n) c h w") + diffusion_grid = make_grid(diffusion_grid, nrow=diffusion_row.shape[0]) + log["diffusion_row"] = diffusion_grid + + if sample: + # get denoise row + with ema_scope("Sampling"): + samples, z_denoise_row = self.sample_log( + cond={"c_concat": [c_cat], "c_crossattn": [c]}, + batch_size=N, + ddim=use_ddim, + ddim_steps=ddim_steps, + eta=ddim_eta, + ) + # samples, z_denoise_row = self.sample(cond=c, batch_size=N, return_intermediates=True) + x_samples = self.decode_first_stage(samples) + log["samples"] = x_samples + if plot_denoise_rows: + denoise_grid = self._get_denoise_row_from_list(z_denoise_row) + log["denoise_row"] = denoise_grid + + if unconditional_guidance_scale > 1.0: + uc_cross = self.get_unconditional_conditioning( + N, unconditional_guidance_label + ) + uc_cat = c_cat + uc_full = {"c_concat": [uc_cat], "c_crossattn": [uc_cross]} + with ema_scope("Sampling with classifier-free guidance"): + samples_cfg, _ = self.sample_log( + cond={"c_concat": [c_cat], "c_crossattn": [c]}, + batch_size=N, + ddim=use_ddim, + ddim_steps=ddim_steps, + eta=ddim_eta, + unconditional_guidance_scale=unconditional_guidance_scale, + unconditional_conditioning=uc_full, + ) + x_samples_cfg = self.decode_first_stage(samples_cfg) + log[ + f"samples_cfg_scale_{unconditional_guidance_scale:.2f}" + ] = x_samples_cfg + + return log + + +class LatentInpaintDiffusion(LatentFinetuneDiffusion): + """ + can either run as pure inpainting model (only concat mode) or with mixed conditionings, + e.g. mask as concat and text via cross-attn. + To disable finetuning mode, set finetune_keys to None + """ + + def __init__( + self, + concat_keys=("mask", "masked_image"), + masked_image_key="masked_image", + *args, + **kwargs, + ): + super().__init__(concat_keys, *args, **kwargs) + self.masked_image_key = masked_image_key + assert self.masked_image_key in concat_keys + + @torch.no_grad() + def get_input( + self, batch, k, cond_key=None, bs=None, return_first_stage_outputs=False + ): + # note: restricted to non-trainable encoders currently + assert ( + not self.cond_stage_trainable + ), "trainable cond stages not yet supported for inpainting" + z, c, x, xrec, xc = super().get_input( + batch, + self.first_stage_key, + return_first_stage_outputs=True, + force_c_encode=True, + return_original_cond=True, + bs=bs, + ) + + assert exists(self.concat_keys) + c_cat = list() + for ck in self.concat_keys: + cc = ( + rearrange(batch[ck], "b h w c -> b c h w") + .to(memory_format=torch.contiguous_format) + .float() + ) + if bs is not None: + cc = cc[:bs] + cc = cc.to(self.device) + bchw = z.shape + if ck != self.masked_image_key: + cc = torch.nn.functional.interpolate(cc, size=bchw[-2:]) + else: + cc = self.get_first_stage_encoding(self.encode_first_stage(cc)) + c_cat.append(cc) + c_cat = torch.cat(c_cat, dim=1) + all_conds = {"c_concat": [c_cat], "c_crossattn": [c]} + if return_first_stage_outputs: + return z, all_conds, x, xrec, xc + return z, all_conds + + @torch.no_grad() + def log_images(self, *args, **kwargs): + log = super(LatentInpaintDiffusion, self).log_images(*args, **kwargs) + log["masked_image"] = ( + rearrange(args[0]["masked_image"], "b h w c -> b c h w") + .to(memory_format=torch.contiguous_format) + .float() + ) + return log + + +class LatentDepth2ImageDiffusion(LatentFinetuneDiffusion): + """ + condition on monocular depth estimation + """ + + def __init__(self, depth_stage_config, concat_keys=("midas_in",), *args, **kwargs): + super().__init__(concat_keys=concat_keys, *args, **kwargs) + self.depth_model = instantiate_from_config(depth_stage_config) + self.depth_stage_key = concat_keys[0] + + @torch.no_grad() + def get_input( + self, batch, k, cond_key=None, bs=None, return_first_stage_outputs=False + ): + # note: restricted to non-trainable encoders currently + assert ( + not self.cond_stage_trainable + ), "trainable cond stages not yet supported for depth2img" + z, c, x, xrec, xc = super().get_input( + batch, + self.first_stage_key, + return_first_stage_outputs=True, + force_c_encode=True, + return_original_cond=True, + bs=bs, + ) + + assert exists(self.concat_keys) + assert len(self.concat_keys) == 1 + c_cat = list() + for ck in self.concat_keys: + cc = batch[ck] + if bs is not None: + cc = cc[:bs] + cc = cc.to(self.device) + cc = self.depth_model(cc) + cc = torch.nn.functional.interpolate( + cc, + size=z.shape[2:], + mode="bicubic", + align_corners=False, + ) + + depth_min, depth_max = torch.amin( + cc, dim=[1, 2, 3], keepdim=True + ), torch.amax(cc, dim=[1, 2, 3], keepdim=True) + cc = 2.0 * (cc - depth_min) / (depth_max - depth_min + 0.001) - 1.0 + c_cat.append(cc) + c_cat = torch.cat(c_cat, dim=1) + all_conds = {"c_concat": [c_cat], "c_crossattn": [c]} + if return_first_stage_outputs: + return z, all_conds, x, xrec, xc + return z, all_conds + + @torch.no_grad() + def log_images(self, *args, **kwargs): + log = super().log_images(*args, **kwargs) + depth = self.depth_model(args[0][self.depth_stage_key]) + depth_min, depth_max = torch.amin( + depth, dim=[1, 2, 3], keepdim=True + ), torch.amax(depth, dim=[1, 2, 3], keepdim=True) + log["depth"] = 2.0 * (depth - depth_min) / (depth_max - depth_min) - 1.0 + return log + + +class LatentUpscaleFinetuneDiffusion(LatentFinetuneDiffusion): + """ + condition on low-res image (and optionally on some spatial noise augmentation) + """ + + def __init__( + self, + concat_keys=("lr",), + reshuffle_patch_size=None, + low_scale_config=None, + low_scale_key=None, + *args, + **kwargs, + ): + super().__init__(concat_keys=concat_keys, *args, **kwargs) + self.reshuffle_patch_size = reshuffle_patch_size + self.low_scale_model = None + if low_scale_config is not None: + print("Initializing a low-scale model") + assert exists(low_scale_key) + self.instantiate_low_stage(low_scale_config) + self.low_scale_key = low_scale_key + + def instantiate_low_stage(self, config): + model = instantiate_from_config(config) + self.low_scale_model = model.eval() + self.low_scale_model.train = disabled_train + for param in self.low_scale_model.parameters(): + param.requires_grad = False + + @torch.no_grad() + def get_input( + self, batch, k, cond_key=None, bs=None, return_first_stage_outputs=False + ): + # note: restricted to non-trainable encoders currently + assert ( + not self.cond_stage_trainable + ), "trainable cond stages not yet supported for upscaling-ft" + z, c, x, xrec, xc = super().get_input( + batch, + self.first_stage_key, + return_first_stage_outputs=True, + force_c_encode=True, + return_original_cond=True, + bs=bs, + ) + + assert exists(self.concat_keys) + assert len(self.concat_keys) == 1 + # optionally make spatial noise_level here + c_cat = list() + noise_level = None + for ck in self.concat_keys: + cc = batch[ck] + cc = rearrange(cc, "b h w c -> b c h w") + if exists(self.reshuffle_patch_size): + assert isinstance(self.reshuffle_patch_size, int) + cc = rearrange( + cc, + "b c (p1 h) (p2 w) -> b (p1 p2 c) h w", + p1=self.reshuffle_patch_size, + p2=self.reshuffle_patch_size, + ) + if bs is not None: + cc = cc[:bs] + cc = cc.to(self.device) + if exists(self.low_scale_model) and ck == self.low_scale_key: + cc, noise_level = self.low_scale_model(cc) + c_cat.append(cc) + c_cat = torch.cat(c_cat, dim=1) + if exists(noise_level): + all_conds = {"c_concat": [c_cat], "c_crossattn": [c], "c_adm": noise_level} + else: + all_conds = {"c_concat": [c_cat], "c_crossattn": [c]} + if return_first_stage_outputs: + return z, all_conds, x, xrec, xc + return z, all_conds + + @torch.no_grad() + def log_images(self, *args, **kwargs): + log = super().log_images(*args, **kwargs) + log["lr"] = rearrange(args[0]["lr"], "b h w c -> b c h w") + return log diff --git a/py/iopaint/model/anytext/ldm/models/diffusion/dpm_solver/__init__.py b/py/iopaint/model/anytext/ldm/models/diffusion/dpm_solver/__init__.py new file mode 100644 index 0000000..7427f38 --- /dev/null +++ b/py/iopaint/model/anytext/ldm/models/diffusion/dpm_solver/__init__.py @@ -0,0 +1 @@ +from .sampler import DPMSolverSampler \ No newline at end of file diff --git a/py/iopaint/model/anytext/ldm/models/diffusion/dpm_solver/dpm_solver.py b/py/iopaint/model/anytext/ldm/models/diffusion/dpm_solver/dpm_solver.py new file mode 100644 index 0000000..095e5ba --- /dev/null +++ b/py/iopaint/model/anytext/ldm/models/diffusion/dpm_solver/dpm_solver.py @@ -0,0 +1,1154 @@ +import torch +import torch.nn.functional as F +import math +from tqdm import tqdm + + +class NoiseScheduleVP: + def __init__( + self, + schedule='discrete', + betas=None, + alphas_cumprod=None, + continuous_beta_0=0.1, + continuous_beta_1=20., + ): + """Create a wrapper class for the forward SDE (VP type). + *** + Update: We support discrete-time diffusion models by implementing a picewise linear interpolation for log_alpha_t. + We recommend to use schedule='discrete' for the discrete-time diffusion models, especially for high-resolution images. + *** + The forward SDE ensures that the condition distribution q_{t|0}(x_t | x_0) = N ( alpha_t * x_0, sigma_t^2 * I ). + We further define lambda_t = log(alpha_t) - log(sigma_t), which is the half-logSNR (described in the DPM-Solver paper). + Therefore, we implement the functions for computing alpha_t, sigma_t and lambda_t. For t in [0, T], we have: + log_alpha_t = self.marginal_log_mean_coeff(t) + sigma_t = self.marginal_std(t) + lambda_t = self.marginal_lambda(t) + Moreover, as lambda(t) is an invertible function, we also support its inverse function: + t = self.inverse_lambda(lambda_t) + =============================================================== + We support both discrete-time DPMs (trained on n = 0, 1, ..., N-1) and continuous-time DPMs (trained on t in [t_0, T]). + 1. For discrete-time DPMs: + For discrete-time DPMs trained on n = 0, 1, ..., N-1, we convert the discrete steps to continuous time steps by: + t_i = (i + 1) / N + e.g. for N = 1000, we have t_0 = 1e-3 and T = t_{N-1} = 1. + We solve the corresponding diffusion ODE from time T = 1 to time t_0 = 1e-3. + Args: + betas: A `torch.Tensor`. The beta array for the discrete-time DPM. (See the original DDPM paper for details) + alphas_cumprod: A `torch.Tensor`. The cumprod alphas for the discrete-time DPM. (See the original DDPM paper for details) + Note that we always have alphas_cumprod = cumprod(betas). Therefore, we only need to set one of `betas` and `alphas_cumprod`. + **Important**: Please pay special attention for the args for `alphas_cumprod`: + The `alphas_cumprod` is the \hat{alpha_n} arrays in the notations of DDPM. Specifically, DDPMs assume that + q_{t_n | 0}(x_{t_n} | x_0) = N ( \sqrt{\hat{alpha_n}} * x_0, (1 - \hat{alpha_n}) * I ). + Therefore, the notation \hat{alpha_n} is different from the notation alpha_t in DPM-Solver. In fact, we have + alpha_{t_n} = \sqrt{\hat{alpha_n}}, + and + log(alpha_{t_n}) = 0.5 * log(\hat{alpha_n}). + 2. For continuous-time DPMs: + We support two types of VPSDEs: linear (DDPM) and cosine (improved-DDPM). The hyperparameters for the noise + schedule are the default settings in DDPM and improved-DDPM: + Args: + beta_min: A `float` number. The smallest beta for the linear schedule. + beta_max: A `float` number. The largest beta for the linear schedule. + cosine_s: A `float` number. The hyperparameter in the cosine schedule. + cosine_beta_max: A `float` number. The hyperparameter in the cosine schedule. + T: A `float` number. The ending time of the forward process. + =============================================================== + Args: + schedule: A `str`. The noise schedule of the forward SDE. 'discrete' for discrete-time DPMs, + 'linear' or 'cosine' for continuous-time DPMs. + Returns: + A wrapper object of the forward SDE (VP type). + + =============================================================== + Example: + # For discrete-time DPMs, given betas (the beta array for n = 0, 1, ..., N - 1): + >>> ns = NoiseScheduleVP('discrete', betas=betas) + # For discrete-time DPMs, given alphas_cumprod (the \hat{alpha_n} array for n = 0, 1, ..., N - 1): + >>> ns = NoiseScheduleVP('discrete', alphas_cumprod=alphas_cumprod) + # For continuous-time DPMs (VPSDE), linear schedule: + >>> ns = NoiseScheduleVP('linear', continuous_beta_0=0.1, continuous_beta_1=20.) + """ + + if schedule not in ['discrete', 'linear', 'cosine']: + raise ValueError( + "Unsupported noise schedule {}. The schedule needs to be 'discrete' or 'linear' or 'cosine'".format( + schedule)) + + self.schedule = schedule + if schedule == 'discrete': + if betas is not None: + log_alphas = 0.5 * torch.log(1 - betas).cumsum(dim=0) + else: + assert alphas_cumprod is not None + log_alphas = 0.5 * torch.log(alphas_cumprod) + self.total_N = len(log_alphas) + self.T = 1. + self.t_array = torch.linspace(0., 1., self.total_N + 1)[1:].reshape((1, -1)) + self.log_alpha_array = log_alphas.reshape((1, -1,)) + else: + self.total_N = 1000 + self.beta_0 = continuous_beta_0 + self.beta_1 = continuous_beta_1 + self.cosine_s = 0.008 + self.cosine_beta_max = 999. + self.cosine_t_max = math.atan(self.cosine_beta_max * (1. + self.cosine_s) / math.pi) * 2. * ( + 1. + self.cosine_s) / math.pi - self.cosine_s + self.cosine_log_alpha_0 = math.log(math.cos(self.cosine_s / (1. + self.cosine_s) * math.pi / 2.)) + self.schedule = schedule + if schedule == 'cosine': + # For the cosine schedule, T = 1 will have numerical issues. So we manually set the ending time T. + # Note that T = 0.9946 may be not the optimal setting. However, we find it works well. + self.T = 0.9946 + else: + self.T = 1. + + def marginal_log_mean_coeff(self, t): + """ + Compute log(alpha_t) of a given continuous-time label t in [0, T]. + """ + if self.schedule == 'discrete': + return interpolate_fn(t.reshape((-1, 1)), self.t_array.to(t.device), + self.log_alpha_array.to(t.device)).reshape((-1)) + elif self.schedule == 'linear': + return -0.25 * t ** 2 * (self.beta_1 - self.beta_0) - 0.5 * t * self.beta_0 + elif self.schedule == 'cosine': + log_alpha_fn = lambda s: torch.log(torch.cos((s + self.cosine_s) / (1. + self.cosine_s) * math.pi / 2.)) + log_alpha_t = log_alpha_fn(t) - self.cosine_log_alpha_0 + return log_alpha_t + + def marginal_alpha(self, t): + """ + Compute alpha_t of a given continuous-time label t in [0, T]. + """ + return torch.exp(self.marginal_log_mean_coeff(t)) + + def marginal_std(self, t): + """ + Compute sigma_t of a given continuous-time label t in [0, T]. + """ + return torch.sqrt(1. - torch.exp(2. * self.marginal_log_mean_coeff(t))) + + def marginal_lambda(self, t): + """ + Compute lambda_t = log(alpha_t) - log(sigma_t) of a given continuous-time label t in [0, T]. + """ + log_mean_coeff = self.marginal_log_mean_coeff(t) + log_std = 0.5 * torch.log(1. - torch.exp(2. * log_mean_coeff)) + return log_mean_coeff - log_std + + def inverse_lambda(self, lamb): + """ + Compute the continuous-time label t in [0, T] of a given half-logSNR lambda_t. + """ + if self.schedule == 'linear': + tmp = 2. * (self.beta_1 - self.beta_0) * torch.logaddexp(-2. * lamb, torch.zeros((1,)).to(lamb)) + Delta = self.beta_0 ** 2 + tmp + return tmp / (torch.sqrt(Delta) + self.beta_0) / (self.beta_1 - self.beta_0) + elif self.schedule == 'discrete': + log_alpha = -0.5 * torch.logaddexp(torch.zeros((1,)).to(lamb.device), -2. * lamb) + t = interpolate_fn(log_alpha.reshape((-1, 1)), torch.flip(self.log_alpha_array.to(lamb.device), [1]), + torch.flip(self.t_array.to(lamb.device), [1])) + return t.reshape((-1,)) + else: + log_alpha = -0.5 * torch.logaddexp(-2. * lamb, torch.zeros((1,)).to(lamb)) + t_fn = lambda log_alpha_t: torch.arccos(torch.exp(log_alpha_t + self.cosine_log_alpha_0)) * 2. * ( + 1. + self.cosine_s) / math.pi - self.cosine_s + t = t_fn(log_alpha) + return t + + +def model_wrapper( + model, + noise_schedule, + model_type="noise", + model_kwargs={}, + guidance_type="uncond", + condition=None, + unconditional_condition=None, + guidance_scale=1., + classifier_fn=None, + classifier_kwargs={}, +): + """Create a wrapper function for the noise prediction model. + DPM-Solver needs to solve the continuous-time diffusion ODEs. For DPMs trained on discrete-time labels, we need to + firstly wrap the model function to a noise prediction model that accepts the continuous time as the input. + We support four types of the diffusion model by setting `model_type`: + 1. "noise": noise prediction model. (Trained by predicting noise). + 2. "x_start": data prediction model. (Trained by predicting the data x_0 at time 0). + 3. "v": velocity prediction model. (Trained by predicting the velocity). + The "v" prediction is derivation detailed in Appendix D of [1], and is used in Imagen-Video [2]. + [1] Salimans, Tim, and Jonathan Ho. "Progressive distillation for fast sampling of diffusion models." + arXiv preprint arXiv:2202.00512 (2022). + [2] Ho, Jonathan, et al. "Imagen Video: High Definition Video Generation with Diffusion Models." + arXiv preprint arXiv:2210.02303 (2022). + + 4. "score": marginal score function. (Trained by denoising score matching). + Note that the score function and the noise prediction model follows a simple relationship: + ``` + noise(x_t, t) = -sigma_t * score(x_t, t) + ``` + We support three types of guided sampling by DPMs by setting `guidance_type`: + 1. "uncond": unconditional sampling by DPMs. + The input `model` has the following format: + `` + model(x, t_input, **model_kwargs) -> noise | x_start | v | score + `` + 2. "classifier": classifier guidance sampling [3] by DPMs and another classifier. + The input `model` has the following format: + `` + model(x, t_input, **model_kwargs) -> noise | x_start | v | score + `` + The input `classifier_fn` has the following format: + `` + classifier_fn(x, t_input, cond, **classifier_kwargs) -> logits(x, t_input, cond) + `` + [3] P. Dhariwal and A. Q. Nichol, "Diffusion models beat GANs on image synthesis," + in Advances in Neural Information Processing Systems, vol. 34, 2021, pp. 8780-8794. + 3. "classifier-free": classifier-free guidance sampling by conditional DPMs. + The input `model` has the following format: + `` + model(x, t_input, cond, **model_kwargs) -> noise | x_start | v | score + `` + And if cond == `unconditional_condition`, the model output is the unconditional DPM output. + [4] Ho, Jonathan, and Tim Salimans. "Classifier-free diffusion guidance." + arXiv preprint arXiv:2207.12598 (2022). + + The `t_input` is the time label of the model, which may be discrete-time labels (i.e. 0 to 999) + or continuous-time labels (i.e. epsilon to T). + We wrap the model function to accept only `x` and `t_continuous` as inputs, and outputs the predicted noise: + `` + def model_fn(x, t_continuous) -> noise: + t_input = get_model_input_time(t_continuous) + return noise_pred(model, x, t_input, **model_kwargs) + `` + where `t_continuous` is the continuous time labels (i.e. epsilon to T). And we use `model_fn` for DPM-Solver. + =============================================================== + Args: + model: A diffusion model with the corresponding format described above. + noise_schedule: A noise schedule object, such as NoiseScheduleVP. + model_type: A `str`. The parameterization type of the diffusion model. + "noise" or "x_start" or "v" or "score". + model_kwargs: A `dict`. A dict for the other inputs of the model function. + guidance_type: A `str`. The type of the guidance for sampling. + "uncond" or "classifier" or "classifier-free". + condition: A pytorch tensor. The condition for the guided sampling. + Only used for "classifier" or "classifier-free" guidance type. + unconditional_condition: A pytorch tensor. The condition for the unconditional sampling. + Only used for "classifier-free" guidance type. + guidance_scale: A `float`. The scale for the guided sampling. + classifier_fn: A classifier function. Only used for the classifier guidance. + classifier_kwargs: A `dict`. A dict for the other inputs of the classifier function. + Returns: + A noise prediction model that accepts the noised data and the continuous time as the inputs. + """ + + def get_model_input_time(t_continuous): + """ + Convert the continuous-time `t_continuous` (in [epsilon, T]) to the model input time. + For discrete-time DPMs, we convert `t_continuous` in [1 / N, 1] to `t_input` in [0, 1000 * (N - 1) / N]. + For continuous-time DPMs, we just use `t_continuous`. + """ + if noise_schedule.schedule == 'discrete': + return (t_continuous - 1. / noise_schedule.total_N) * 1000. + else: + return t_continuous + + def noise_pred_fn(x, t_continuous, cond=None): + if t_continuous.reshape((-1,)).shape[0] == 1: + t_continuous = t_continuous.expand((x.shape[0])) + t_input = get_model_input_time(t_continuous) + if cond is None: + output = model(x, t_input, **model_kwargs) + else: + output = model(x, t_input, cond, **model_kwargs) + if model_type == "noise": + return output + elif model_type == "x_start": + alpha_t, sigma_t = noise_schedule.marginal_alpha(t_continuous), noise_schedule.marginal_std(t_continuous) + dims = x.dim() + return (x - expand_dims(alpha_t, dims) * output) / expand_dims(sigma_t, dims) + elif model_type == "v": + alpha_t, sigma_t = noise_schedule.marginal_alpha(t_continuous), noise_schedule.marginal_std(t_continuous) + dims = x.dim() + return expand_dims(alpha_t, dims) * output + expand_dims(sigma_t, dims) * x + elif model_type == "score": + sigma_t = noise_schedule.marginal_std(t_continuous) + dims = x.dim() + return -expand_dims(sigma_t, dims) * output + + def cond_grad_fn(x, t_input): + """ + Compute the gradient of the classifier, i.e. nabla_{x} log p_t(cond | x_t). + """ + with torch.enable_grad(): + x_in = x.detach().requires_grad_(True) + log_prob = classifier_fn(x_in, t_input, condition, **classifier_kwargs) + return torch.autograd.grad(log_prob.sum(), x_in)[0] + + def model_fn(x, t_continuous): + """ + The noise predicition model function that is used for DPM-Solver. + """ + if t_continuous.reshape((-1,)).shape[0] == 1: + t_continuous = t_continuous.expand((x.shape[0])) + if guidance_type == "uncond": + return noise_pred_fn(x, t_continuous) + elif guidance_type == "classifier": + assert classifier_fn is not None + t_input = get_model_input_time(t_continuous) + cond_grad = cond_grad_fn(x, t_input) + sigma_t = noise_schedule.marginal_std(t_continuous) + noise = noise_pred_fn(x, t_continuous) + return noise - guidance_scale * expand_dims(sigma_t, dims=cond_grad.dim()) * cond_grad + elif guidance_type == "classifier-free": + if guidance_scale == 1. or unconditional_condition is None: + return noise_pred_fn(x, t_continuous, cond=condition) + else: + x_in = torch.cat([x] * 2) + t_in = torch.cat([t_continuous] * 2) + c_in = torch.cat([unconditional_condition, condition]) + noise_uncond, noise = noise_pred_fn(x_in, t_in, cond=c_in).chunk(2) + return noise_uncond + guidance_scale * (noise - noise_uncond) + + assert model_type in ["noise", "x_start", "v"] + assert guidance_type in ["uncond", "classifier", "classifier-free"] + return model_fn + + +class DPM_Solver: + def __init__(self, model_fn, noise_schedule, predict_x0=False, thresholding=False, max_val=1.): + """Construct a DPM-Solver. + We support both the noise prediction model ("predicting epsilon") and the data prediction model ("predicting x0"). + If `predict_x0` is False, we use the solver for the noise prediction model (DPM-Solver). + If `predict_x0` is True, we use the solver for the data prediction model (DPM-Solver++). + In such case, we further support the "dynamic thresholding" in [1] when `thresholding` is True. + The "dynamic thresholding" can greatly improve the sample quality for pixel-space DPMs with large guidance scales. + Args: + model_fn: A noise prediction model function which accepts the continuous-time input (t in [epsilon, T]): + `` + def model_fn(x, t_continuous): + return noise + `` + noise_schedule: A noise schedule object, such as NoiseScheduleVP. + predict_x0: A `bool`. If true, use the data prediction model; else, use the noise prediction model. + thresholding: A `bool`. Valid when `predict_x0` is True. Whether to use the "dynamic thresholding" in [1]. + max_val: A `float`. Valid when both `predict_x0` and `thresholding` are True. The max value for thresholding. + + [1] Chitwan Saharia, William Chan, Saurabh Saxena, Lala Li, Jay Whang, Emily Denton, Seyed Kamyar Seyed Ghasemipour, Burcu Karagol Ayan, S Sara Mahdavi, Rapha Gontijo Lopes, et al. Photorealistic text-to-image diffusion models with deep language understanding. arXiv preprint arXiv:2205.11487, 2022b. + """ + self.model = model_fn + self.noise_schedule = noise_schedule + self.predict_x0 = predict_x0 + self.thresholding = thresholding + self.max_val = max_val + + def noise_prediction_fn(self, x, t): + """ + Return the noise prediction model. + """ + return self.model(x, t) + + def data_prediction_fn(self, x, t): + """ + Return the data prediction model (with thresholding). + """ + noise = self.noise_prediction_fn(x, t) + dims = x.dim() + alpha_t, sigma_t = self.noise_schedule.marginal_alpha(t), self.noise_schedule.marginal_std(t) + x0 = (x - expand_dims(sigma_t, dims) * noise) / expand_dims(alpha_t, dims) + if self.thresholding: + p = 0.995 # A hyperparameter in the paper of "Imagen" [1]. + s = torch.quantile(torch.abs(x0).reshape((x0.shape[0], -1)), p, dim=1) + s = expand_dims(torch.maximum(s, self.max_val * torch.ones_like(s).to(s.device)), dims) + x0 = torch.clamp(x0, -s, s) / s + return x0 + + def model_fn(self, x, t): + """ + Convert the model to the noise prediction model or the data prediction model. + """ + if self.predict_x0: + return self.data_prediction_fn(x, t) + else: + return self.noise_prediction_fn(x, t) + + def get_time_steps(self, skip_type, t_T, t_0, N, device): + """Compute the intermediate time steps for sampling. + Args: + skip_type: A `str`. The type for the spacing of the time steps. We support three types: + - 'logSNR': uniform logSNR for the time steps. + - 'time_uniform': uniform time for the time steps. (**Recommended for high-resolutional data**.) + - 'time_quadratic': quadratic time for the time steps. (Used in DDIM for low-resolutional data.) + t_T: A `float`. The starting time of the sampling (default is T). + t_0: A `float`. The ending time of the sampling (default is epsilon). + N: A `int`. The total number of the spacing of the time steps. + device: A torch device. + Returns: + A pytorch tensor of the time steps, with the shape (N + 1,). + """ + if skip_type == 'logSNR': + lambda_T = self.noise_schedule.marginal_lambda(torch.tensor(t_T).to(device)) + lambda_0 = self.noise_schedule.marginal_lambda(torch.tensor(t_0).to(device)) + logSNR_steps = torch.linspace(lambda_T.cpu().item(), lambda_0.cpu().item(), N + 1).to(device) + return self.noise_schedule.inverse_lambda(logSNR_steps) + elif skip_type == 'time_uniform': + return torch.linspace(t_T, t_0, N + 1).to(device) + elif skip_type == 'time_quadratic': + t_order = 2 + t = torch.linspace(t_T ** (1. / t_order), t_0 ** (1. / t_order), N + 1).pow(t_order).to(device) + return t + else: + raise ValueError( + "Unsupported skip_type {}, need to be 'logSNR' or 'time_uniform' or 'time_quadratic'".format(skip_type)) + + def get_orders_and_timesteps_for_singlestep_solver(self, steps, order, skip_type, t_T, t_0, device): + """ + Get the order of each step for sampling by the singlestep DPM-Solver. + We combine both DPM-Solver-1,2,3 to use all the function evaluations, which is named as "DPM-Solver-fast". + Given a fixed number of function evaluations by `steps`, the sampling procedure by DPM-Solver-fast is: + - If order == 1: + We take `steps` of DPM-Solver-1 (i.e. DDIM). + - If order == 2: + - Denote K = (steps // 2). We take K or (K + 1) intermediate time steps for sampling. + - If steps % 2 == 0, we use K steps of DPM-Solver-2. + - If steps % 2 == 1, we use K steps of DPM-Solver-2 and 1 step of DPM-Solver-1. + - If order == 3: + - Denote K = (steps // 3 + 1). We take K intermediate time steps for sampling. + - If steps % 3 == 0, we use (K - 2) steps of DPM-Solver-3, and 1 step of DPM-Solver-2 and 1 step of DPM-Solver-1. + - If steps % 3 == 1, we use (K - 1) steps of DPM-Solver-3 and 1 step of DPM-Solver-1. + - If steps % 3 == 2, we use (K - 1) steps of DPM-Solver-3 and 1 step of DPM-Solver-2. + ============================================ + Args: + order: A `int`. The max order for the solver (2 or 3). + steps: A `int`. The total number of function evaluations (NFE). + skip_type: A `str`. The type for the spacing of the time steps. We support three types: + - 'logSNR': uniform logSNR for the time steps. + - 'time_uniform': uniform time for the time steps. (**Recommended for high-resolutional data**.) + - 'time_quadratic': quadratic time for the time steps. (Used in DDIM for low-resolutional data.) + t_T: A `float`. The starting time of the sampling (default is T). + t_0: A `float`. The ending time of the sampling (default is epsilon). + device: A torch device. + Returns: + orders: A list of the solver order of each step. + """ + if order == 3: + K = steps // 3 + 1 + if steps % 3 == 0: + orders = [3, ] * (K - 2) + [2, 1] + elif steps % 3 == 1: + orders = [3, ] * (K - 1) + [1] + else: + orders = [3, ] * (K - 1) + [2] + elif order == 2: + if steps % 2 == 0: + K = steps // 2 + orders = [2, ] * K + else: + K = steps // 2 + 1 + orders = [2, ] * (K - 1) + [1] + elif order == 1: + K = 1 + orders = [1, ] * steps + else: + raise ValueError("'order' must be '1' or '2' or '3'.") + if skip_type == 'logSNR': + # To reproduce the results in DPM-Solver paper + timesteps_outer = self.get_time_steps(skip_type, t_T, t_0, K, device) + else: + timesteps_outer = self.get_time_steps(skip_type, t_T, t_0, steps, device)[ + torch.cumsum(torch.tensor([0, ] + orders)).to(device)] + return timesteps_outer, orders + + def denoise_to_zero_fn(self, x, s): + """ + Denoise at the final step, which is equivalent to solve the ODE from lambda_s to infty by first-order discretization. + """ + return self.data_prediction_fn(x, s) + + def dpm_solver_first_update(self, x, s, t, model_s=None, return_intermediate=False): + """ + DPM-Solver-1 (equivalent to DDIM) from time `s` to time `t`. + Args: + x: A pytorch tensor. The initial value at time `s`. + s: A pytorch tensor. The starting time, with the shape (x.shape[0],). + t: A pytorch tensor. The ending time, with the shape (x.shape[0],). + model_s: A pytorch tensor. The model function evaluated at time `s`. + If `model_s` is None, we evaluate the model by `x` and `s`; otherwise we directly use it. + return_intermediate: A `bool`. If true, also return the model value at time `s`. + Returns: + x_t: A pytorch tensor. The approximated solution at time `t`. + """ + ns = self.noise_schedule + dims = x.dim() + lambda_s, lambda_t = ns.marginal_lambda(s), ns.marginal_lambda(t) + h = lambda_t - lambda_s + log_alpha_s, log_alpha_t = ns.marginal_log_mean_coeff(s), ns.marginal_log_mean_coeff(t) + sigma_s, sigma_t = ns.marginal_std(s), ns.marginal_std(t) + alpha_t = torch.exp(log_alpha_t) + + if self.predict_x0: + phi_1 = torch.expm1(-h) + if model_s is None: + model_s = self.model_fn(x, s) + x_t = ( + expand_dims(sigma_t / sigma_s, dims) * x + - expand_dims(alpha_t * phi_1, dims) * model_s + ) + if return_intermediate: + return x_t, {'model_s': model_s} + else: + return x_t + else: + phi_1 = torch.expm1(h) + if model_s is None: + model_s = self.model_fn(x, s) + x_t = ( + expand_dims(torch.exp(log_alpha_t - log_alpha_s), dims) * x + - expand_dims(sigma_t * phi_1, dims) * model_s + ) + if return_intermediate: + return x_t, {'model_s': model_s} + else: + return x_t + + def singlestep_dpm_solver_second_update(self, x, s, t, r1=0.5, model_s=None, return_intermediate=False, + solver_type='dpm_solver'): + """ + Singlestep solver DPM-Solver-2 from time `s` to time `t`. + Args: + x: A pytorch tensor. The initial value at time `s`. + s: A pytorch tensor. The starting time, with the shape (x.shape[0],). + t: A pytorch tensor. The ending time, with the shape (x.shape[0],). + r1: A `float`. The hyperparameter of the second-order solver. + model_s: A pytorch tensor. The model function evaluated at time `s`. + If `model_s` is None, we evaluate the model by `x` and `s`; otherwise we directly use it. + return_intermediate: A `bool`. If true, also return the model value at time `s` and `s1` (the intermediate time). + solver_type: either 'dpm_solver' or 'taylor'. The type for the high-order solvers. + The type slightly impacts the performance. We recommend to use 'dpm_solver' type. + Returns: + x_t: A pytorch tensor. The approximated solution at time `t`. + """ + if solver_type not in ['dpm_solver', 'taylor']: + raise ValueError("'solver_type' must be either 'dpm_solver' or 'taylor', got {}".format(solver_type)) + if r1 is None: + r1 = 0.5 + ns = self.noise_schedule + dims = x.dim() + lambda_s, lambda_t = ns.marginal_lambda(s), ns.marginal_lambda(t) + h = lambda_t - lambda_s + lambda_s1 = lambda_s + r1 * h + s1 = ns.inverse_lambda(lambda_s1) + log_alpha_s, log_alpha_s1, log_alpha_t = ns.marginal_log_mean_coeff(s), ns.marginal_log_mean_coeff( + s1), ns.marginal_log_mean_coeff(t) + sigma_s, sigma_s1, sigma_t = ns.marginal_std(s), ns.marginal_std(s1), ns.marginal_std(t) + alpha_s1, alpha_t = torch.exp(log_alpha_s1), torch.exp(log_alpha_t) + + if self.predict_x0: + phi_11 = torch.expm1(-r1 * h) + phi_1 = torch.expm1(-h) + + if model_s is None: + model_s = self.model_fn(x, s) + x_s1 = ( + expand_dims(sigma_s1 / sigma_s, dims) * x + - expand_dims(alpha_s1 * phi_11, dims) * model_s + ) + model_s1 = self.model_fn(x_s1, s1) + if solver_type == 'dpm_solver': + x_t = ( + expand_dims(sigma_t / sigma_s, dims) * x + - expand_dims(alpha_t * phi_1, dims) * model_s + - (0.5 / r1) * expand_dims(alpha_t * phi_1, dims) * (model_s1 - model_s) + ) + elif solver_type == 'taylor': + x_t = ( + expand_dims(sigma_t / sigma_s, dims) * x + - expand_dims(alpha_t * phi_1, dims) * model_s + + (1. / r1) * expand_dims(alpha_t * ((torch.exp(-h) - 1.) / h + 1.), dims) * ( + model_s1 - model_s) + ) + else: + phi_11 = torch.expm1(r1 * h) + phi_1 = torch.expm1(h) + + if model_s is None: + model_s = self.model_fn(x, s) + x_s1 = ( + expand_dims(torch.exp(log_alpha_s1 - log_alpha_s), dims) * x + - expand_dims(sigma_s1 * phi_11, dims) * model_s + ) + model_s1 = self.model_fn(x_s1, s1) + if solver_type == 'dpm_solver': + x_t = ( + expand_dims(torch.exp(log_alpha_t - log_alpha_s), dims) * x + - expand_dims(sigma_t * phi_1, dims) * model_s + - (0.5 / r1) * expand_dims(sigma_t * phi_1, dims) * (model_s1 - model_s) + ) + elif solver_type == 'taylor': + x_t = ( + expand_dims(torch.exp(log_alpha_t - log_alpha_s), dims) * x + - expand_dims(sigma_t * phi_1, dims) * model_s + - (1. / r1) * expand_dims(sigma_t * ((torch.exp(h) - 1.) / h - 1.), dims) * (model_s1 - model_s) + ) + if return_intermediate: + return x_t, {'model_s': model_s, 'model_s1': model_s1} + else: + return x_t + + def singlestep_dpm_solver_third_update(self, x, s, t, r1=1. / 3., r2=2. / 3., model_s=None, model_s1=None, + return_intermediate=False, solver_type='dpm_solver'): + """ + Singlestep solver DPM-Solver-3 from time `s` to time `t`. + Args: + x: A pytorch tensor. The initial value at time `s`. + s: A pytorch tensor. The starting time, with the shape (x.shape[0],). + t: A pytorch tensor. The ending time, with the shape (x.shape[0],). + r1: A `float`. The hyperparameter of the third-order solver. + r2: A `float`. The hyperparameter of the third-order solver. + model_s: A pytorch tensor. The model function evaluated at time `s`. + If `model_s` is None, we evaluate the model by `x` and `s`; otherwise we directly use it. + model_s1: A pytorch tensor. The model function evaluated at time `s1` (the intermediate time given by `r1`). + If `model_s1` is None, we evaluate the model at `s1`; otherwise we directly use it. + return_intermediate: A `bool`. If true, also return the model value at time `s`, `s1` and `s2` (the intermediate times). + solver_type: either 'dpm_solver' or 'taylor'. The type for the high-order solvers. + The type slightly impacts the performance. We recommend to use 'dpm_solver' type. + Returns: + x_t: A pytorch tensor. The approximated solution at time `t`. + """ + if solver_type not in ['dpm_solver', 'taylor']: + raise ValueError("'solver_type' must be either 'dpm_solver' or 'taylor', got {}".format(solver_type)) + if r1 is None: + r1 = 1. / 3. + if r2 is None: + r2 = 2. / 3. + ns = self.noise_schedule + dims = x.dim() + lambda_s, lambda_t = ns.marginal_lambda(s), ns.marginal_lambda(t) + h = lambda_t - lambda_s + lambda_s1 = lambda_s + r1 * h + lambda_s2 = lambda_s + r2 * h + s1 = ns.inverse_lambda(lambda_s1) + s2 = ns.inverse_lambda(lambda_s2) + log_alpha_s, log_alpha_s1, log_alpha_s2, log_alpha_t = ns.marginal_log_mean_coeff( + s), ns.marginal_log_mean_coeff(s1), ns.marginal_log_mean_coeff(s2), ns.marginal_log_mean_coeff(t) + sigma_s, sigma_s1, sigma_s2, sigma_t = ns.marginal_std(s), ns.marginal_std(s1), ns.marginal_std( + s2), ns.marginal_std(t) + alpha_s1, alpha_s2, alpha_t = torch.exp(log_alpha_s1), torch.exp(log_alpha_s2), torch.exp(log_alpha_t) + + if self.predict_x0: + phi_11 = torch.expm1(-r1 * h) + phi_12 = torch.expm1(-r2 * h) + phi_1 = torch.expm1(-h) + phi_22 = torch.expm1(-r2 * h) / (r2 * h) + 1. + phi_2 = phi_1 / h + 1. + phi_3 = phi_2 / h - 0.5 + + if model_s is None: + model_s = self.model_fn(x, s) + if model_s1 is None: + x_s1 = ( + expand_dims(sigma_s1 / sigma_s, dims) * x + - expand_dims(alpha_s1 * phi_11, dims) * model_s + ) + model_s1 = self.model_fn(x_s1, s1) + x_s2 = ( + expand_dims(sigma_s2 / sigma_s, dims) * x + - expand_dims(alpha_s2 * phi_12, dims) * model_s + + r2 / r1 * expand_dims(alpha_s2 * phi_22, dims) * (model_s1 - model_s) + ) + model_s2 = self.model_fn(x_s2, s2) + if solver_type == 'dpm_solver': + x_t = ( + expand_dims(sigma_t / sigma_s, dims) * x + - expand_dims(alpha_t * phi_1, dims) * model_s + + (1. / r2) * expand_dims(alpha_t * phi_2, dims) * (model_s2 - model_s) + ) + elif solver_type == 'taylor': + D1_0 = (1. / r1) * (model_s1 - model_s) + D1_1 = (1. / r2) * (model_s2 - model_s) + D1 = (r2 * D1_0 - r1 * D1_1) / (r2 - r1) + D2 = 2. * (D1_1 - D1_0) / (r2 - r1) + x_t = ( + expand_dims(sigma_t / sigma_s, dims) * x + - expand_dims(alpha_t * phi_1, dims) * model_s + + expand_dims(alpha_t * phi_2, dims) * D1 + - expand_dims(alpha_t * phi_3, dims) * D2 + ) + else: + phi_11 = torch.expm1(r1 * h) + phi_12 = torch.expm1(r2 * h) + phi_1 = torch.expm1(h) + phi_22 = torch.expm1(r2 * h) / (r2 * h) - 1. + phi_2 = phi_1 / h - 1. + phi_3 = phi_2 / h - 0.5 + + if model_s is None: + model_s = self.model_fn(x, s) + if model_s1 is None: + x_s1 = ( + expand_dims(torch.exp(log_alpha_s1 - log_alpha_s), dims) * x + - expand_dims(sigma_s1 * phi_11, dims) * model_s + ) + model_s1 = self.model_fn(x_s1, s1) + x_s2 = ( + expand_dims(torch.exp(log_alpha_s2 - log_alpha_s), dims) * x + - expand_dims(sigma_s2 * phi_12, dims) * model_s + - r2 / r1 * expand_dims(sigma_s2 * phi_22, dims) * (model_s1 - model_s) + ) + model_s2 = self.model_fn(x_s2, s2) + if solver_type == 'dpm_solver': + x_t = ( + expand_dims(torch.exp(log_alpha_t - log_alpha_s), dims) * x + - expand_dims(sigma_t * phi_1, dims) * model_s + - (1. / r2) * expand_dims(sigma_t * phi_2, dims) * (model_s2 - model_s) + ) + elif solver_type == 'taylor': + D1_0 = (1. / r1) * (model_s1 - model_s) + D1_1 = (1. / r2) * (model_s2 - model_s) + D1 = (r2 * D1_0 - r1 * D1_1) / (r2 - r1) + D2 = 2. * (D1_1 - D1_0) / (r2 - r1) + x_t = ( + expand_dims(torch.exp(log_alpha_t - log_alpha_s), dims) * x + - expand_dims(sigma_t * phi_1, dims) * model_s + - expand_dims(sigma_t * phi_2, dims) * D1 + - expand_dims(sigma_t * phi_3, dims) * D2 + ) + + if return_intermediate: + return x_t, {'model_s': model_s, 'model_s1': model_s1, 'model_s2': model_s2} + else: + return x_t + + def multistep_dpm_solver_second_update(self, x, model_prev_list, t_prev_list, t, solver_type="dpm_solver"): + """ + Multistep solver DPM-Solver-2 from time `t_prev_list[-1]` to time `t`. + Args: + x: A pytorch tensor. The initial value at time `s`. + model_prev_list: A list of pytorch tensor. The previous computed model values. + t_prev_list: A list of pytorch tensor. The previous times, each time has the shape (x.shape[0],) + t: A pytorch tensor. The ending time, with the shape (x.shape[0],). + solver_type: either 'dpm_solver' or 'taylor'. The type for the high-order solvers. + The type slightly impacts the performance. We recommend to use 'dpm_solver' type. + Returns: + x_t: A pytorch tensor. The approximated solution at time `t`. + """ + if solver_type not in ['dpm_solver', 'taylor']: + raise ValueError("'solver_type' must be either 'dpm_solver' or 'taylor', got {}".format(solver_type)) + ns = self.noise_schedule + dims = x.dim() + model_prev_1, model_prev_0 = model_prev_list + t_prev_1, t_prev_0 = t_prev_list + lambda_prev_1, lambda_prev_0, lambda_t = ns.marginal_lambda(t_prev_1), ns.marginal_lambda( + t_prev_0), ns.marginal_lambda(t) + log_alpha_prev_0, log_alpha_t = ns.marginal_log_mean_coeff(t_prev_0), ns.marginal_log_mean_coeff(t) + sigma_prev_0, sigma_t = ns.marginal_std(t_prev_0), ns.marginal_std(t) + alpha_t = torch.exp(log_alpha_t) + + h_0 = lambda_prev_0 - lambda_prev_1 + h = lambda_t - lambda_prev_0 + r0 = h_0 / h + D1_0 = expand_dims(1. / r0, dims) * (model_prev_0 - model_prev_1) + if self.predict_x0: + if solver_type == 'dpm_solver': + x_t = ( + expand_dims(sigma_t / sigma_prev_0, dims) * x + - expand_dims(alpha_t * (torch.exp(-h) - 1.), dims) * model_prev_0 + - 0.5 * expand_dims(alpha_t * (torch.exp(-h) - 1.), dims) * D1_0 + ) + elif solver_type == 'taylor': + x_t = ( + expand_dims(sigma_t / sigma_prev_0, dims) * x + - expand_dims(alpha_t * (torch.exp(-h) - 1.), dims) * model_prev_0 + + expand_dims(alpha_t * ((torch.exp(-h) - 1.) / h + 1.), dims) * D1_0 + ) + else: + if solver_type == 'dpm_solver': + x_t = ( + expand_dims(torch.exp(log_alpha_t - log_alpha_prev_0), dims) * x + - expand_dims(sigma_t * (torch.exp(h) - 1.), dims) * model_prev_0 + - 0.5 * expand_dims(sigma_t * (torch.exp(h) - 1.), dims) * D1_0 + ) + elif solver_type == 'taylor': + x_t = ( + expand_dims(torch.exp(log_alpha_t - log_alpha_prev_0), dims) * x + - expand_dims(sigma_t * (torch.exp(h) - 1.), dims) * model_prev_0 + - expand_dims(sigma_t * ((torch.exp(h) - 1.) / h - 1.), dims) * D1_0 + ) + return x_t + + def multistep_dpm_solver_third_update(self, x, model_prev_list, t_prev_list, t, solver_type='dpm_solver'): + """ + Multistep solver DPM-Solver-3 from time `t_prev_list[-1]` to time `t`. + Args: + x: A pytorch tensor. The initial value at time `s`. + model_prev_list: A list of pytorch tensor. The previous computed model values. + t_prev_list: A list of pytorch tensor. The previous times, each time has the shape (x.shape[0],) + t: A pytorch tensor. The ending time, with the shape (x.shape[0],). + solver_type: either 'dpm_solver' or 'taylor'. The type for the high-order solvers. + The type slightly impacts the performance. We recommend to use 'dpm_solver' type. + Returns: + x_t: A pytorch tensor. The approximated solution at time `t`. + """ + ns = self.noise_schedule + dims = x.dim() + model_prev_2, model_prev_1, model_prev_0 = model_prev_list + t_prev_2, t_prev_1, t_prev_0 = t_prev_list + lambda_prev_2, lambda_prev_1, lambda_prev_0, lambda_t = ns.marginal_lambda(t_prev_2), ns.marginal_lambda( + t_prev_1), ns.marginal_lambda(t_prev_0), ns.marginal_lambda(t) + log_alpha_prev_0, log_alpha_t = ns.marginal_log_mean_coeff(t_prev_0), ns.marginal_log_mean_coeff(t) + sigma_prev_0, sigma_t = ns.marginal_std(t_prev_0), ns.marginal_std(t) + alpha_t = torch.exp(log_alpha_t) + + h_1 = lambda_prev_1 - lambda_prev_2 + h_0 = lambda_prev_0 - lambda_prev_1 + h = lambda_t - lambda_prev_0 + r0, r1 = h_0 / h, h_1 / h + D1_0 = expand_dims(1. / r0, dims) * (model_prev_0 - model_prev_1) + D1_1 = expand_dims(1. / r1, dims) * (model_prev_1 - model_prev_2) + D1 = D1_0 + expand_dims(r0 / (r0 + r1), dims) * (D1_0 - D1_1) + D2 = expand_dims(1. / (r0 + r1), dims) * (D1_0 - D1_1) + if self.predict_x0: + x_t = ( + expand_dims(sigma_t / sigma_prev_0, dims) * x + - expand_dims(alpha_t * (torch.exp(-h) - 1.), dims) * model_prev_0 + + expand_dims(alpha_t * ((torch.exp(-h) - 1.) / h + 1.), dims) * D1 + - expand_dims(alpha_t * ((torch.exp(-h) - 1. + h) / h ** 2 - 0.5), dims) * D2 + ) + else: + x_t = ( + expand_dims(torch.exp(log_alpha_t - log_alpha_prev_0), dims) * x + - expand_dims(sigma_t * (torch.exp(h) - 1.), dims) * model_prev_0 + - expand_dims(sigma_t * ((torch.exp(h) - 1.) / h - 1.), dims) * D1 + - expand_dims(sigma_t * ((torch.exp(h) - 1. - h) / h ** 2 - 0.5), dims) * D2 + ) + return x_t + + def singlestep_dpm_solver_update(self, x, s, t, order, return_intermediate=False, solver_type='dpm_solver', r1=None, + r2=None): + """ + Singlestep DPM-Solver with the order `order` from time `s` to time `t`. + Args: + x: A pytorch tensor. The initial value at time `s`. + s: A pytorch tensor. The starting time, with the shape (x.shape[0],). + t: A pytorch tensor. The ending time, with the shape (x.shape[0],). + order: A `int`. The order of DPM-Solver. We only support order == 1 or 2 or 3. + return_intermediate: A `bool`. If true, also return the model value at time `s`, `s1` and `s2` (the intermediate times). + solver_type: either 'dpm_solver' or 'taylor'. The type for the high-order solvers. + The type slightly impacts the performance. We recommend to use 'dpm_solver' type. + r1: A `float`. The hyperparameter of the second-order or third-order solver. + r2: A `float`. The hyperparameter of the third-order solver. + Returns: + x_t: A pytorch tensor. The approximated solution at time `t`. + """ + if order == 1: + return self.dpm_solver_first_update(x, s, t, return_intermediate=return_intermediate) + elif order == 2: + return self.singlestep_dpm_solver_second_update(x, s, t, return_intermediate=return_intermediate, + solver_type=solver_type, r1=r1) + elif order == 3: + return self.singlestep_dpm_solver_third_update(x, s, t, return_intermediate=return_intermediate, + solver_type=solver_type, r1=r1, r2=r2) + else: + raise ValueError("Solver order must be 1 or 2 or 3, got {}".format(order)) + + def multistep_dpm_solver_update(self, x, model_prev_list, t_prev_list, t, order, solver_type='dpm_solver'): + """ + Multistep DPM-Solver with the order `order` from time `t_prev_list[-1]` to time `t`. + Args: + x: A pytorch tensor. The initial value at time `s`. + model_prev_list: A list of pytorch tensor. The previous computed model values. + t_prev_list: A list of pytorch tensor. The previous times, each time has the shape (x.shape[0],) + t: A pytorch tensor. The ending time, with the shape (x.shape[0],). + order: A `int`. The order of DPM-Solver. We only support order == 1 or 2 or 3. + solver_type: either 'dpm_solver' or 'taylor'. The type for the high-order solvers. + The type slightly impacts the performance. We recommend to use 'dpm_solver' type. + Returns: + x_t: A pytorch tensor. The approximated solution at time `t`. + """ + if order == 1: + return self.dpm_solver_first_update(x, t_prev_list[-1], t, model_s=model_prev_list[-1]) + elif order == 2: + return self.multistep_dpm_solver_second_update(x, model_prev_list, t_prev_list, t, solver_type=solver_type) + elif order == 3: + return self.multistep_dpm_solver_third_update(x, model_prev_list, t_prev_list, t, solver_type=solver_type) + else: + raise ValueError("Solver order must be 1 or 2 or 3, got {}".format(order)) + + def dpm_solver_adaptive(self, x, order, t_T, t_0, h_init=0.05, atol=0.0078, rtol=0.05, theta=0.9, t_err=1e-5, + solver_type='dpm_solver'): + """ + The adaptive step size solver based on singlestep DPM-Solver. + Args: + x: A pytorch tensor. The initial value at time `t_T`. + order: A `int`. The (higher) order of the solver. We only support order == 2 or 3. + t_T: A `float`. The starting time of the sampling (default is T). + t_0: A `float`. The ending time of the sampling (default is epsilon). + h_init: A `float`. The initial step size (for logSNR). + atol: A `float`. The absolute tolerance of the solver. For image data, the default setting is 0.0078, followed [1]. + rtol: A `float`. The relative tolerance of the solver. The default setting is 0.05. + theta: A `float`. The safety hyperparameter for adapting the step size. The default setting is 0.9, followed [1]. + t_err: A `float`. The tolerance for the time. We solve the diffusion ODE until the absolute error between the + current time and `t_0` is less than `t_err`. The default setting is 1e-5. + solver_type: either 'dpm_solver' or 'taylor'. The type for the high-order solvers. + The type slightly impacts the performance. We recommend to use 'dpm_solver' type. + Returns: + x_0: A pytorch tensor. The approximated solution at time `t_0`. + [1] A. Jolicoeur-Martineau, K. Li, R. Piché-Taillefer, T. Kachman, and I. Mitliagkas, "Gotta go fast when generating data with score-based models," arXiv preprint arXiv:2105.14080, 2021. + """ + ns = self.noise_schedule + s = t_T * torch.ones((x.shape[0],)).to(x) + lambda_s = ns.marginal_lambda(s) + lambda_0 = ns.marginal_lambda(t_0 * torch.ones_like(s).to(x)) + h = h_init * torch.ones_like(s).to(x) + x_prev = x + nfe = 0 + if order == 2: + r1 = 0.5 + lower_update = lambda x, s, t: self.dpm_solver_first_update(x, s, t, return_intermediate=True) + higher_update = lambda x, s, t, **kwargs: self.singlestep_dpm_solver_second_update(x, s, t, r1=r1, + solver_type=solver_type, + **kwargs) + elif order == 3: + r1, r2 = 1. / 3., 2. / 3. + lower_update = lambda x, s, t: self.singlestep_dpm_solver_second_update(x, s, t, r1=r1, + return_intermediate=True, + solver_type=solver_type) + higher_update = lambda x, s, t, **kwargs: self.singlestep_dpm_solver_third_update(x, s, t, r1=r1, r2=r2, + solver_type=solver_type, + **kwargs) + else: + raise ValueError("For adaptive step size solver, order must be 2 or 3, got {}".format(order)) + while torch.abs((s - t_0)).mean() > t_err: + t = ns.inverse_lambda(lambda_s + h) + x_lower, lower_noise_kwargs = lower_update(x, s, t) + x_higher = higher_update(x, s, t, **lower_noise_kwargs) + delta = torch.max(torch.ones_like(x).to(x) * atol, rtol * torch.max(torch.abs(x_lower), torch.abs(x_prev))) + norm_fn = lambda v: torch.sqrt(torch.square(v.reshape((v.shape[0], -1))).mean(dim=-1, keepdim=True)) + E = norm_fn((x_higher - x_lower) / delta).max() + if torch.all(E <= 1.): + x = x_higher + s = t + x_prev = x_lower + lambda_s = ns.marginal_lambda(s) + h = torch.min(theta * h * torch.float_power(E, -1. / order).float(), lambda_0 - lambda_s) + nfe += order + print('adaptive solver nfe', nfe) + return x + + def sample(self, x, steps=20, t_start=None, t_end=None, order=3, skip_type='time_uniform', + method='singlestep', lower_order_final=True, denoise_to_zero=False, solver_type='dpm_solver', + atol=0.0078, rtol=0.05, + ): + """ + Compute the sample at time `t_end` by DPM-Solver, given the initial `x` at time `t_start`. + ===================================================== + We support the following algorithms for both noise prediction model and data prediction model: + - 'singlestep': + Singlestep DPM-Solver (i.e. "DPM-Solver-fast" in the paper), which combines different orders of singlestep DPM-Solver. + We combine all the singlestep solvers with order <= `order` to use up all the function evaluations (steps). + The total number of function evaluations (NFE) == `steps`. + Given a fixed NFE == `steps`, the sampling procedure is: + - If `order` == 1: + - Denote K = steps. We use K steps of DPM-Solver-1 (i.e. DDIM). + - If `order` == 2: + - Denote K = (steps // 2) + (steps % 2). We take K intermediate time steps for sampling. + - If steps % 2 == 0, we use K steps of singlestep DPM-Solver-2. + - If steps % 2 == 1, we use (K - 1) steps of singlestep DPM-Solver-2 and 1 step of DPM-Solver-1. + - If `order` == 3: + - Denote K = (steps // 3 + 1). We take K intermediate time steps for sampling. + - If steps % 3 == 0, we use (K - 2) steps of singlestep DPM-Solver-3, and 1 step of singlestep DPM-Solver-2 and 1 step of DPM-Solver-1. + - If steps % 3 == 1, we use (K - 1) steps of singlestep DPM-Solver-3 and 1 step of DPM-Solver-1. + - If steps % 3 == 2, we use (K - 1) steps of singlestep DPM-Solver-3 and 1 step of singlestep DPM-Solver-2. + - 'multistep': + Multistep DPM-Solver with the order of `order`. The total number of function evaluations (NFE) == `steps`. + We initialize the first `order` values by lower order multistep solvers. + Given a fixed NFE == `steps`, the sampling procedure is: + Denote K = steps. + - If `order` == 1: + - We use K steps of DPM-Solver-1 (i.e. DDIM). + - If `order` == 2: + - We firstly use 1 step of DPM-Solver-1, then use (K - 1) step of multistep DPM-Solver-2. + - If `order` == 3: + - We firstly use 1 step of DPM-Solver-1, then 1 step of multistep DPM-Solver-2, then (K - 2) step of multistep DPM-Solver-3. + - 'singlestep_fixed': + Fixed order singlestep DPM-Solver (i.e. DPM-Solver-1 or singlestep DPM-Solver-2 or singlestep DPM-Solver-3). + We use singlestep DPM-Solver-`order` for `order`=1 or 2 or 3, with total [`steps` // `order`] * `order` NFE. + - 'adaptive': + Adaptive step size DPM-Solver (i.e. "DPM-Solver-12" and "DPM-Solver-23" in the paper). + We ignore `steps` and use adaptive step size DPM-Solver with a higher order of `order`. + You can adjust the absolute tolerance `atol` and the relative tolerance `rtol` to balance the computatation costs + (NFE) and the sample quality. + - If `order` == 2, we use DPM-Solver-12 which combines DPM-Solver-1 and singlestep DPM-Solver-2. + - If `order` == 3, we use DPM-Solver-23 which combines singlestep DPM-Solver-2 and singlestep DPM-Solver-3. + ===================================================== + Some advices for choosing the algorithm: + - For **unconditional sampling** or **guided sampling with small guidance scale** by DPMs: + Use singlestep DPM-Solver ("DPM-Solver-fast" in the paper) with `order = 3`. + e.g. + >>> dpm_solver = DPM_Solver(model_fn, noise_schedule, predict_x0=False) + >>> x_sample = dpm_solver.sample(x, steps=steps, t_start=t_start, t_end=t_end, order=3, + skip_type='time_uniform', method='singlestep') + - For **guided sampling with large guidance scale** by DPMs: + Use multistep DPM-Solver with `predict_x0 = True` and `order = 2`. + e.g. + >>> dpm_solver = DPM_Solver(model_fn, noise_schedule, predict_x0=True) + >>> x_sample = dpm_solver.sample(x, steps=steps, t_start=t_start, t_end=t_end, order=2, + skip_type='time_uniform', method='multistep') + We support three types of `skip_type`: + - 'logSNR': uniform logSNR for the time steps. **Recommended for low-resolutional images** + - 'time_uniform': uniform time for the time steps. **Recommended for high-resolutional images**. + - 'time_quadratic': quadratic time for the time steps. + ===================================================== + Args: + x: A pytorch tensor. The initial value at time `t_start` + e.g. if `t_start` == T, then `x` is a sample from the standard normal distribution. + steps: A `int`. The total number of function evaluations (NFE). + t_start: A `float`. The starting time of the sampling. + If `T` is None, we use self.noise_schedule.T (default is 1.0). + t_end: A `float`. The ending time of the sampling. + If `t_end` is None, we use 1. / self.noise_schedule.total_N. + e.g. if total_N == 1000, we have `t_end` == 1e-3. + For discrete-time DPMs: + - We recommend `t_end` == 1. / self.noise_schedule.total_N. + For continuous-time DPMs: + - We recommend `t_end` == 1e-3 when `steps` <= 15; and `t_end` == 1e-4 when `steps` > 15. + order: A `int`. The order of DPM-Solver. + skip_type: A `str`. The type for the spacing of the time steps. 'time_uniform' or 'logSNR' or 'time_quadratic'. + method: A `str`. The method for sampling. 'singlestep' or 'multistep' or 'singlestep_fixed' or 'adaptive'. + denoise_to_zero: A `bool`. Whether to denoise to time 0 at the final step. + Default is `False`. If `denoise_to_zero` is `True`, the total NFE is (`steps` + 1). + This trick is firstly proposed by DDPM (https://arxiv.org/abs/2006.11239) and + score_sde (https://arxiv.org/abs/2011.13456). Such trick can improve the FID + for diffusion models sampling by diffusion SDEs for low-resolutional images + (such as CIFAR-10). However, we observed that such trick does not matter for + high-resolutional images. As it needs an additional NFE, we do not recommend + it for high-resolutional images. + lower_order_final: A `bool`. Whether to use lower order solvers at the final steps. + Only valid for `method=multistep` and `steps < 15`. We empirically find that + this trick is a key to stabilizing the sampling by DPM-Solver with very few steps + (especially for steps <= 10). So we recommend to set it to be `True`. + solver_type: A `str`. The taylor expansion type for the solver. `dpm_solver` or `taylor`. We recommend `dpm_solver`. + atol: A `float`. The absolute tolerance of the adaptive step size solver. Valid when `method` == 'adaptive'. + rtol: A `float`. The relative tolerance of the adaptive step size solver. Valid when `method` == 'adaptive'. + Returns: + x_end: A pytorch tensor. The approximated solution at time `t_end`. + """ + t_0 = 1. / self.noise_schedule.total_N if t_end is None else t_end + t_T = self.noise_schedule.T if t_start is None else t_start + device = x.device + if method == 'adaptive': + with torch.no_grad(): + x = self.dpm_solver_adaptive(x, order=order, t_T=t_T, t_0=t_0, atol=atol, rtol=rtol, + solver_type=solver_type) + elif method == 'multistep': + assert steps >= order + timesteps = self.get_time_steps(skip_type=skip_type, t_T=t_T, t_0=t_0, N=steps, device=device) + assert timesteps.shape[0] - 1 == steps + with torch.no_grad(): + vec_t = timesteps[0].expand((x.shape[0])) + model_prev_list = [self.model_fn(x, vec_t)] + t_prev_list = [vec_t] + # Init the first `order` values by lower order multistep DPM-Solver. + for init_order in tqdm(range(1, order), desc="DPM init order"): + vec_t = timesteps[init_order].expand(x.shape[0]) + x = self.multistep_dpm_solver_update(x, model_prev_list, t_prev_list, vec_t, init_order, + solver_type=solver_type) + model_prev_list.append(self.model_fn(x, vec_t)) + t_prev_list.append(vec_t) + # Compute the remaining values by `order`-th order multistep DPM-Solver. + for step in tqdm(range(order, steps + 1), desc="DPM multistep"): + vec_t = timesteps[step].expand(x.shape[0]) + if lower_order_final and steps < 15: + step_order = min(order, steps + 1 - step) + else: + step_order = order + x = self.multistep_dpm_solver_update(x, model_prev_list, t_prev_list, vec_t, step_order, + solver_type=solver_type) + for i in range(order - 1): + t_prev_list[i] = t_prev_list[i + 1] + model_prev_list[i] = model_prev_list[i + 1] + t_prev_list[-1] = vec_t + # We do not need to evaluate the final model value. + if step < steps: + model_prev_list[-1] = self.model_fn(x, vec_t) + elif method in ['singlestep', 'singlestep_fixed']: + if method == 'singlestep': + timesteps_outer, orders = self.get_orders_and_timesteps_for_singlestep_solver(steps=steps, order=order, + skip_type=skip_type, + t_T=t_T, t_0=t_0, + device=device) + elif method == 'singlestep_fixed': + K = steps // order + orders = [order, ] * K + timesteps_outer = self.get_time_steps(skip_type=skip_type, t_T=t_T, t_0=t_0, N=K, device=device) + for i, order in enumerate(orders): + t_T_inner, t_0_inner = timesteps_outer[i], timesteps_outer[i + 1] + timesteps_inner = self.get_time_steps(skip_type=skip_type, t_T=t_T_inner.item(), t_0=t_0_inner.item(), + N=order, device=device) + lambda_inner = self.noise_schedule.marginal_lambda(timesteps_inner) + vec_s, vec_t = t_T_inner.tile(x.shape[0]), t_0_inner.tile(x.shape[0]) + h = lambda_inner[-1] - lambda_inner[0] + r1 = None if order <= 1 else (lambda_inner[1] - lambda_inner[0]) / h + r2 = None if order <= 2 else (lambda_inner[2] - lambda_inner[0]) / h + x = self.singlestep_dpm_solver_update(x, vec_s, vec_t, order, solver_type=solver_type, r1=r1, r2=r2) + if denoise_to_zero: + x = self.denoise_to_zero_fn(x, torch.ones((x.shape[0],)).to(device) * t_0) + return x + + +############################################################# +# other utility functions +############################################################# + +def interpolate_fn(x, xp, yp): + """ + A piecewise linear function y = f(x), using xp and yp as keypoints. + We implement f(x) in a differentiable way (i.e. applicable for autograd). + The function f(x) is well-defined for all x-axis. (For x beyond the bounds of xp, we use the outmost points of xp to define the linear function.) + Args: + x: PyTorch tensor with shape [N, C], where N is the batch size, C is the number of channels (we use C = 1 for DPM-Solver). + xp: PyTorch tensor with shape [C, K], where K is the number of keypoints. + yp: PyTorch tensor with shape [C, K]. + Returns: + The function values f(x), with shape [N, C]. + """ + N, K = x.shape[0], xp.shape[1] + all_x = torch.cat([x.unsqueeze(2), xp.unsqueeze(0).repeat((N, 1, 1))], dim=2) + sorted_all_x, x_indices = torch.sort(all_x, dim=2) + x_idx = torch.argmin(x_indices, dim=2) + cand_start_idx = x_idx - 1 + start_idx = torch.where( + torch.eq(x_idx, 0), + torch.tensor(1, device=x.device), + torch.where( + torch.eq(x_idx, K), torch.tensor(K - 2, device=x.device), cand_start_idx, + ), + ) + end_idx = torch.where(torch.eq(start_idx, cand_start_idx), start_idx + 2, start_idx + 1) + start_x = torch.gather(sorted_all_x, dim=2, index=start_idx.unsqueeze(2)).squeeze(2) + end_x = torch.gather(sorted_all_x, dim=2, index=end_idx.unsqueeze(2)).squeeze(2) + start_idx2 = torch.where( + torch.eq(x_idx, 0), + torch.tensor(0, device=x.device), + torch.where( + torch.eq(x_idx, K), torch.tensor(K - 2, device=x.device), cand_start_idx, + ), + ) + y_positions_expanded = yp.unsqueeze(0).expand(N, -1, -1) + start_y = torch.gather(y_positions_expanded, dim=2, index=start_idx2.unsqueeze(2)).squeeze(2) + end_y = torch.gather(y_positions_expanded, dim=2, index=(start_idx2 + 1).unsqueeze(2)).squeeze(2) + cand = start_y + (x - start_x) * (end_y - start_y) / (end_x - start_x) + return cand + + +def expand_dims(v, dims): + """ + Expand the tensor `v` to the dim `dims`. + Args: + `v`: a PyTorch tensor with shape [N]. + `dim`: a `int`. + Returns: + a PyTorch tensor with shape [N, 1, 1, ..., 1] and the total dimension is `dims`. + """ + return v[(...,) + (None,) * (dims - 1)] \ No newline at end of file diff --git a/py/iopaint/model/anytext/ldm/models/diffusion/dpm_solver/sampler.py b/py/iopaint/model/anytext/ldm/models/diffusion/dpm_solver/sampler.py new file mode 100644 index 0000000..7d137b8 --- /dev/null +++ b/py/iopaint/model/anytext/ldm/models/diffusion/dpm_solver/sampler.py @@ -0,0 +1,87 @@ +"""SAMPLING ONLY.""" +import torch + +from .dpm_solver import NoiseScheduleVP, model_wrapper, DPM_Solver + + +MODEL_TYPES = { + "eps": "noise", + "v": "v" +} + + +class DPMSolverSampler(object): + def __init__(self, model, **kwargs): + super().__init__() + self.model = model + to_torch = lambda x: x.clone().detach().to(torch.float32).to(model.device) + self.register_buffer('alphas_cumprod', to_torch(model.alphas_cumprod)) + + def register_buffer(self, name, attr): + if type(attr) == torch.Tensor: + if attr.device != torch.device("cuda"): + attr = attr.to(torch.device("cuda")) + setattr(self, name, attr) + + @torch.no_grad() + def sample(self, + S, + batch_size, + shape, + conditioning=None, + callback=None, + normals_sequence=None, + img_callback=None, + quantize_x0=False, + eta=0., + mask=None, + x0=None, + temperature=1., + noise_dropout=0., + score_corrector=None, + corrector_kwargs=None, + verbose=True, + x_T=None, + log_every_t=100, + unconditional_guidance_scale=1., + unconditional_conditioning=None, + # this has to come in the same format as the conditioning, # e.g. as encoded tokens, ... + **kwargs + ): + if conditioning is not None: + if isinstance(conditioning, dict): + cbs = conditioning[list(conditioning.keys())[0]].shape[0] + if cbs != batch_size: + print(f"Warning: Got {cbs} conditionings but batch-size is {batch_size}") + else: + if conditioning.shape[0] != batch_size: + print(f"Warning: Got {conditioning.shape[0]} conditionings but batch-size is {batch_size}") + + # sampling + C, H, W = shape + size = (batch_size, C, H, W) + + print(f'Data shape for DPM-Solver sampling is {size}, sampling steps {S}') + + device = self.model.betas.device + if x_T is None: + img = torch.randn(size, device=device) + else: + img = x_T + + ns = NoiseScheduleVP('discrete', alphas_cumprod=self.alphas_cumprod) + + model_fn = model_wrapper( + lambda x, t, c: self.model.apply_model(x, t, c), + ns, + model_type=MODEL_TYPES[self.model.parameterization], + guidance_type="classifier-free", + condition=conditioning, + unconditional_condition=unconditional_conditioning, + guidance_scale=unconditional_guidance_scale, + ) + + dpm_solver = DPM_Solver(model_fn, ns, predict_x0=True, thresholding=False) + x = dpm_solver.sample(img, steps=S, skip_type="time_uniform", method="multistep", order=2, lower_order_final=True) + + return x.to(device), None \ No newline at end of file diff --git a/py/iopaint/model/anytext/ldm/models/diffusion/plms.py b/py/iopaint/model/anytext/ldm/models/diffusion/plms.py new file mode 100644 index 0000000..5f35d55 --- /dev/null +++ b/py/iopaint/model/anytext/ldm/models/diffusion/plms.py @@ -0,0 +1,244 @@ +"""SAMPLING ONLY.""" + +import torch +import numpy as np +from tqdm import tqdm +from functools import partial + +from iopaint.model.anytext.ldm.modules.diffusionmodules.util import make_ddim_sampling_parameters, make_ddim_timesteps, noise_like +from iopaint.model.anytext.ldm.models.diffusion.sampling_util import norm_thresholding + + +class PLMSSampler(object): + def __init__(self, model, schedule="linear", **kwargs): + super().__init__() + self.model = model + self.ddpm_num_timesteps = model.num_timesteps + self.schedule = schedule + + def register_buffer(self, name, attr): + if type(attr) == torch.Tensor: + if attr.device != torch.device("cuda"): + attr = attr.to(torch.device("cuda")) + setattr(self, name, attr) + + def make_schedule(self, ddim_num_steps, ddim_discretize="uniform", ddim_eta=0., verbose=True): + if ddim_eta != 0: + raise ValueError('ddim_eta must be 0 for PLMS') + self.ddim_timesteps = make_ddim_timesteps(ddim_discr_method=ddim_discretize, num_ddim_timesteps=ddim_num_steps, + num_ddpm_timesteps=self.ddpm_num_timesteps,verbose=verbose) + alphas_cumprod = self.model.alphas_cumprod + assert alphas_cumprod.shape[0] == self.ddpm_num_timesteps, 'alphas have to be defined for each timestep' + to_torch = lambda x: x.clone().detach().to(torch.float32).to(self.model.device) + + self.register_buffer('betas', to_torch(self.model.betas)) + self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod)) + self.register_buffer('alphas_cumprod_prev', to_torch(self.model.alphas_cumprod_prev)) + + # calculations for diffusion q(x_t | x_{t-1}) and others + self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod.cpu()))) + self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod.cpu()))) + self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod.cpu()))) + self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu()))) + self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu() - 1))) + + # ddim sampling parameters + ddim_sigmas, ddim_alphas, ddim_alphas_prev = make_ddim_sampling_parameters(alphacums=alphas_cumprod.cpu(), + ddim_timesteps=self.ddim_timesteps, + eta=ddim_eta,verbose=verbose) + self.register_buffer('ddim_sigmas', ddim_sigmas) + self.register_buffer('ddim_alphas', ddim_alphas) + self.register_buffer('ddim_alphas_prev', ddim_alphas_prev) + self.register_buffer('ddim_sqrt_one_minus_alphas', np.sqrt(1. - ddim_alphas)) + sigmas_for_original_sampling_steps = ddim_eta * torch.sqrt( + (1 - self.alphas_cumprod_prev) / (1 - self.alphas_cumprod) * ( + 1 - self.alphas_cumprod / self.alphas_cumprod_prev)) + self.register_buffer('ddim_sigmas_for_original_num_steps', sigmas_for_original_sampling_steps) + + @torch.no_grad() + def sample(self, + S, + batch_size, + shape, + conditioning=None, + callback=None, + normals_sequence=None, + img_callback=None, + quantize_x0=False, + eta=0., + mask=None, + x0=None, + temperature=1., + noise_dropout=0., + score_corrector=None, + corrector_kwargs=None, + verbose=True, + x_T=None, + log_every_t=100, + unconditional_guidance_scale=1., + unconditional_conditioning=None, + # this has to come in the same format as the conditioning, # e.g. as encoded tokens, ... + dynamic_threshold=None, + **kwargs + ): + if conditioning is not None: + if isinstance(conditioning, dict): + cbs = conditioning[list(conditioning.keys())[0]].shape[0] + if cbs != batch_size: + print(f"Warning: Got {cbs} conditionings but batch-size is {batch_size}") + else: + if conditioning.shape[0] != batch_size: + print(f"Warning: Got {conditioning.shape[0]} conditionings but batch-size is {batch_size}") + + self.make_schedule(ddim_num_steps=S, ddim_eta=eta, verbose=verbose) + # sampling + C, H, W = shape + size = (batch_size, C, H, W) + print(f'Data shape for PLMS sampling is {size}') + + samples, intermediates = self.plms_sampling(conditioning, size, + callback=callback, + img_callback=img_callback, + quantize_denoised=quantize_x0, + mask=mask, x0=x0, + ddim_use_original_steps=False, + noise_dropout=noise_dropout, + temperature=temperature, + score_corrector=score_corrector, + corrector_kwargs=corrector_kwargs, + x_T=x_T, + log_every_t=log_every_t, + unconditional_guidance_scale=unconditional_guidance_scale, + unconditional_conditioning=unconditional_conditioning, + dynamic_threshold=dynamic_threshold, + ) + return samples, intermediates + + @torch.no_grad() + def plms_sampling(self, cond, shape, + x_T=None, ddim_use_original_steps=False, + callback=None, timesteps=None, quantize_denoised=False, + mask=None, x0=None, img_callback=None, log_every_t=100, + temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None, + unconditional_guidance_scale=1., unconditional_conditioning=None, + dynamic_threshold=None): + device = self.model.betas.device + b = shape[0] + if x_T is None: + img = torch.randn(shape, device=device) + else: + img = x_T + + if timesteps is None: + timesteps = self.ddpm_num_timesteps if ddim_use_original_steps else self.ddim_timesteps + elif timesteps is not None and not ddim_use_original_steps: + subset_end = int(min(timesteps / self.ddim_timesteps.shape[0], 1) * self.ddim_timesteps.shape[0]) - 1 + timesteps = self.ddim_timesteps[:subset_end] + + intermediates = {'x_inter': [img], 'pred_x0': [img]} + time_range = list(reversed(range(0,timesteps))) if ddim_use_original_steps else np.flip(timesteps) + total_steps = timesteps if ddim_use_original_steps else timesteps.shape[0] + print(f"Running PLMS Sampling with {total_steps} timesteps") + + iterator = tqdm(time_range, desc='PLMS Sampler', total=total_steps) + old_eps = [] + + for i, step in enumerate(iterator): + index = total_steps - i - 1 + ts = torch.full((b,), step, device=device, dtype=torch.long) + ts_next = torch.full((b,), time_range[min(i + 1, len(time_range) - 1)], device=device, dtype=torch.long) + + if mask is not None: + assert x0 is not None + img_orig = self.model.q_sample(x0, ts) # TODO: deterministic forward pass? + img = img_orig * mask + (1. - mask) * img + + outs = self.p_sample_plms(img, cond, ts, index=index, use_original_steps=ddim_use_original_steps, + quantize_denoised=quantize_denoised, temperature=temperature, + noise_dropout=noise_dropout, score_corrector=score_corrector, + corrector_kwargs=corrector_kwargs, + unconditional_guidance_scale=unconditional_guidance_scale, + unconditional_conditioning=unconditional_conditioning, + old_eps=old_eps, t_next=ts_next, + dynamic_threshold=dynamic_threshold) + img, pred_x0, e_t = outs + old_eps.append(e_t) + if len(old_eps) >= 4: + old_eps.pop(0) + if callback: callback(i) + if img_callback: img_callback(pred_x0, i) + + if index % log_every_t == 0 or index == total_steps - 1: + intermediates['x_inter'].append(img) + intermediates['pred_x0'].append(pred_x0) + + return img, intermediates + + @torch.no_grad() + def p_sample_plms(self, x, c, t, index, repeat_noise=False, use_original_steps=False, quantize_denoised=False, + temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None, + unconditional_guidance_scale=1., unconditional_conditioning=None, old_eps=None, t_next=None, + dynamic_threshold=None): + b, *_, device = *x.shape, x.device + + def get_model_output(x, t): + if unconditional_conditioning is None or unconditional_guidance_scale == 1.: + e_t = self.model.apply_model(x, t, c) + else: + x_in = torch.cat([x] * 2) + t_in = torch.cat([t] * 2) + c_in = torch.cat([unconditional_conditioning, c]) + e_t_uncond, e_t = self.model.apply_model(x_in, t_in, c_in).chunk(2) + e_t = e_t_uncond + unconditional_guidance_scale * (e_t - e_t_uncond) + + if score_corrector is not None: + assert self.model.parameterization == "eps" + e_t = score_corrector.modify_score(self.model, e_t, x, t, c, **corrector_kwargs) + + return e_t + + alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas + alphas_prev = self.model.alphas_cumprod_prev if use_original_steps else self.ddim_alphas_prev + sqrt_one_minus_alphas = self.model.sqrt_one_minus_alphas_cumprod if use_original_steps else self.ddim_sqrt_one_minus_alphas + sigmas = self.model.ddim_sigmas_for_original_num_steps if use_original_steps else self.ddim_sigmas + + def get_x_prev_and_pred_x0(e_t, index): + # select parameters corresponding to the currently considered timestep + a_t = torch.full((b, 1, 1, 1), alphas[index], device=device) + a_prev = torch.full((b, 1, 1, 1), alphas_prev[index], device=device) + sigma_t = torch.full((b, 1, 1, 1), sigmas[index], device=device) + sqrt_one_minus_at = torch.full((b, 1, 1, 1), sqrt_one_minus_alphas[index],device=device) + + # current prediction for x_0 + pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt() + if quantize_denoised: + pred_x0, _, *_ = self.model.first_stage_model.quantize(pred_x0) + if dynamic_threshold is not None: + pred_x0 = norm_thresholding(pred_x0, dynamic_threshold) + # direction pointing to x_t + dir_xt = (1. - a_prev - sigma_t**2).sqrt() * e_t + noise = sigma_t * noise_like(x.shape, device, repeat_noise) * temperature + if noise_dropout > 0.: + noise = torch.nn.functional.dropout(noise, p=noise_dropout) + x_prev = a_prev.sqrt() * pred_x0 + dir_xt + noise + return x_prev, pred_x0 + + e_t = get_model_output(x, t) + if len(old_eps) == 0: + # Pseudo Improved Euler (2nd order) + x_prev, pred_x0 = get_x_prev_and_pred_x0(e_t, index) + e_t_next = get_model_output(x_prev, t_next) + e_t_prime = (e_t + e_t_next) / 2 + elif len(old_eps) == 1: + # 2nd order Pseudo Linear Multistep (Adams-Bashforth) + e_t_prime = (3 * e_t - old_eps[-1]) / 2 + elif len(old_eps) == 2: + # 3nd order Pseudo Linear Multistep (Adams-Bashforth) + e_t_prime = (23 * e_t - 16 * old_eps[-1] + 5 * old_eps[-2]) / 12 + elif len(old_eps) >= 3: + # 4nd order Pseudo Linear Multistep (Adams-Bashforth) + e_t_prime = (55 * e_t - 59 * old_eps[-1] + 37 * old_eps[-2] - 9 * old_eps[-3]) / 24 + + x_prev, pred_x0 = get_x_prev_and_pred_x0(e_t_prime, index) + + return x_prev, pred_x0, e_t diff --git a/py/iopaint/model/anytext/ldm/models/diffusion/sampling_util.py b/py/iopaint/model/anytext/ldm/models/diffusion/sampling_util.py new file mode 100644 index 0000000..7eff02b --- /dev/null +++ b/py/iopaint/model/anytext/ldm/models/diffusion/sampling_util.py @@ -0,0 +1,22 @@ +import torch +import numpy as np + + +def append_dims(x, target_dims): + """Appends dimensions to the end of a tensor until it has target_dims dimensions. + From https://github.com/crowsonkb/k-diffusion/blob/master/k_diffusion/utils.py""" + dims_to_append = target_dims - x.ndim + if dims_to_append < 0: + raise ValueError(f'input has {x.ndim} dims but target_dims is {target_dims}, which is less') + return x[(...,) + (None,) * dims_to_append] + + +def norm_thresholding(x0, value): + s = append_dims(x0.pow(2).flatten(1).mean(1).sqrt().clamp(min=value), x0.ndim) + return x0 * (value / s) + + +def spatial_norm_thresholding(x0, value): + # b c h w + s = x0.pow(2).mean(1, keepdim=True).sqrt().clamp(min=value) + return x0 * (value / s) \ No newline at end of file diff --git a/py/iopaint/model/anytext/ldm/modules/__init__.py b/py/iopaint/model/anytext/ldm/modules/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/py/iopaint/model/anytext/ldm/modules/attention.py b/py/iopaint/model/anytext/ldm/modules/attention.py new file mode 100644 index 0000000..df92aa7 --- /dev/null +++ b/py/iopaint/model/anytext/ldm/modules/attention.py @@ -0,0 +1,360 @@ +from inspect import isfunction +import math +import torch +import torch.nn.functional as F +from torch import nn, einsum +from einops import rearrange, repeat +from typing import Optional, Any + +from iopaint.model.anytext.ldm.modules.diffusionmodules.util import checkpoint + + +# CrossAttn precision handling +import os + +_ATTN_PRECISION = os.environ.get("ATTN_PRECISION", "fp32") + + +def exists(val): + return val is not None + + +def uniq(arr): + return {el: True for el in arr}.keys() + + +def default(val, d): + if exists(val): + return val + return d() if isfunction(d) else d + + +def max_neg_value(t): + return -torch.finfo(t.dtype).max + + +def init_(tensor): + dim = tensor.shape[-1] + std = 1 / math.sqrt(dim) + tensor.uniform_(-std, std) + return tensor + + +# feedforward +class GEGLU(nn.Module): + def __init__(self, dim_in, dim_out): + super().__init__() + self.proj = nn.Linear(dim_in, dim_out * 2) + + def forward(self, x): + x, gate = self.proj(x).chunk(2, dim=-1) + return x * F.gelu(gate) + + +class FeedForward(nn.Module): + def __init__(self, dim, dim_out=None, mult=4, glu=False, dropout=0.0): + super().__init__() + inner_dim = int(dim * mult) + dim_out = default(dim_out, dim) + project_in = ( + nn.Sequential(nn.Linear(dim, inner_dim), nn.GELU()) + if not glu + else GEGLU(dim, inner_dim) + ) + + self.net = nn.Sequential( + project_in, nn.Dropout(dropout), nn.Linear(inner_dim, dim_out) + ) + + def forward(self, x): + return self.net(x) + + +def zero_module(module): + """ + Zero out the parameters of a module and return it. + """ + for p in module.parameters(): + p.detach().zero_() + return module + + +def Normalize(in_channels): + return torch.nn.GroupNorm( + num_groups=32, num_channels=in_channels, eps=1e-6, affine=True + ) + + +class SpatialSelfAttention(nn.Module): + def __init__(self, in_channels): + super().__init__() + self.in_channels = in_channels + + self.norm = Normalize(in_channels) + self.q = torch.nn.Conv2d( + in_channels, in_channels, kernel_size=1, stride=1, padding=0 + ) + self.k = torch.nn.Conv2d( + in_channels, in_channels, kernel_size=1, stride=1, padding=0 + ) + self.v = torch.nn.Conv2d( + in_channels, in_channels, kernel_size=1, stride=1, padding=0 + ) + self.proj_out = torch.nn.Conv2d( + in_channels, in_channels, kernel_size=1, stride=1, padding=0 + ) + + def forward(self, x): + h_ = x + h_ = self.norm(h_) + q = self.q(h_) + k = self.k(h_) + v = self.v(h_) + + # compute attention + b, c, h, w = q.shape + q = rearrange(q, "b c h w -> b (h w) c") + k = rearrange(k, "b c h w -> b c (h w)") + w_ = torch.einsum("bij,bjk->bik", q, k) + + w_ = w_ * (int(c) ** (-0.5)) + w_ = torch.nn.functional.softmax(w_, dim=2) + + # attend to values + v = rearrange(v, "b c h w -> b c (h w)") + w_ = rearrange(w_, "b i j -> b j i") + h_ = torch.einsum("bij,bjk->bik", v, w_) + h_ = rearrange(h_, "b c (h w) -> b c h w", h=h) + h_ = self.proj_out(h_) + + return x + h_ + + +class CrossAttention(nn.Module): + def __init__(self, query_dim, context_dim=None, heads=8, dim_head=64, dropout=0.0): + super().__init__() + inner_dim = dim_head * heads + context_dim = default(context_dim, query_dim) + + self.scale = dim_head**-0.5 + self.heads = heads + + self.to_q = nn.Linear(query_dim, inner_dim, bias=False) + self.to_k = nn.Linear(context_dim, inner_dim, bias=False) + self.to_v = nn.Linear(context_dim, inner_dim, bias=False) + + self.to_out = nn.Sequential( + nn.Linear(inner_dim, query_dim), nn.Dropout(dropout) + ) + + def forward(self, x, context=None, mask=None): + h = self.heads + + q = self.to_q(x) + context = default(context, x) + k = self.to_k(context) + v = self.to_v(context) + + q, k, v = map(lambda t: rearrange(t, "b n (h d) -> (b h) n d", h=h), (q, k, v)) + + # force cast to fp32 to avoid overflowing + if _ATTN_PRECISION == "fp32": + with torch.autocast(enabled=False, device_type="cuda"): + q, k = q.float(), k.float() + sim = einsum("b i d, b j d -> b i j", q, k) * self.scale + else: + sim = einsum("b i d, b j d -> b i j", q, k) * self.scale + + del q, k + + if exists(mask): + mask = rearrange(mask, "b ... -> b (...)") + max_neg_value = -torch.finfo(sim.dtype).max + mask = repeat(mask, "b j -> (b h) () j", h=h) + sim.masked_fill_(~mask, max_neg_value) + + # attention, what we cannot get enough of + sim = sim.softmax(dim=-1) + + out = einsum("b i j, b j d -> b i d", sim, v) + out = rearrange(out, "(b h) n d -> b n (h d)", h=h) + return self.to_out(out) + + +class SDPACrossAttention(CrossAttention): + def forward(self, x, context=None, mask=None): + batch_size, sequence_length, inner_dim = x.shape + + if mask is not None: + mask = self.prepare_attention_mask(mask, sequence_length, batch_size) + mask = mask.view(batch_size, self.heads, -1, mask.shape[-1]) + + h = self.heads + q_in = self.to_q(x) + context = default(context, x) + + k_in = self.to_k(context) + v_in = self.to_v(context) + + head_dim = inner_dim // h + q = q_in.view(batch_size, -1, h, head_dim).transpose(1, 2) + k = k_in.view(batch_size, -1, h, head_dim).transpose(1, 2) + v = v_in.view(batch_size, -1, h, head_dim).transpose(1, 2) + + del q_in, k_in, v_in + + dtype = q.dtype + if _ATTN_PRECISION == "fp32": + q, k, v = q.float(), k.float(), v.float() + + # the output of sdp = (batch, num_heads, seq_len, head_dim) + hidden_states = torch.nn.functional.scaled_dot_product_attention( + q, k, v, attn_mask=mask, dropout_p=0.0, is_causal=False + ) + + hidden_states = hidden_states.transpose(1, 2).reshape( + batch_size, -1, h * head_dim + ) + hidden_states = hidden_states.to(dtype) + + # linear proj + hidden_states = self.to_out[0](hidden_states) + # dropout + hidden_states = self.to_out[1](hidden_states) + return hidden_states + + +class BasicTransformerBlock(nn.Module): + def __init__( + self, + dim, + n_heads, + d_head, + dropout=0.0, + context_dim=None, + gated_ff=True, + checkpoint=True, + disable_self_attn=False, + ): + super().__init__() + + if hasattr(torch.nn.functional, "scaled_dot_product_attention"): + attn_cls = SDPACrossAttention + else: + attn_cls = CrossAttention + + self.disable_self_attn = disable_self_attn + self.attn1 = attn_cls( + query_dim=dim, + heads=n_heads, + dim_head=d_head, + dropout=dropout, + context_dim=context_dim if self.disable_self_attn else None, + ) # is a self-attention if not self.disable_self_attn + self.ff = FeedForward(dim, dropout=dropout, glu=gated_ff) + self.attn2 = attn_cls( + query_dim=dim, + context_dim=context_dim, + heads=n_heads, + dim_head=d_head, + dropout=dropout, + ) # is self-attn if context is none + self.norm1 = nn.LayerNorm(dim) + self.norm2 = nn.LayerNorm(dim) + self.norm3 = nn.LayerNorm(dim) + self.checkpoint = checkpoint + + def forward(self, x, context=None): + return checkpoint( + self._forward, (x, context), self.parameters(), self.checkpoint + ) + + def _forward(self, x, context=None): + x = ( + self.attn1( + self.norm1(x), context=context if self.disable_self_attn else None + ) + + x + ) + x = self.attn2(self.norm2(x), context=context) + x + x = self.ff(self.norm3(x)) + x + return x + + +class SpatialTransformer(nn.Module): + """ + Transformer block for image-like data. + First, project the input (aka embedding) + and reshape to b, t, d. + Then apply standard transformer action. + Finally, reshape to image + NEW: use_linear for more efficiency instead of the 1x1 convs + """ + + def __init__( + self, + in_channels, + n_heads, + d_head, + depth=1, + dropout=0.0, + context_dim=None, + disable_self_attn=False, + use_linear=False, + use_checkpoint=True, + ): + super().__init__() + if exists(context_dim) and not isinstance(context_dim, list): + context_dim = [context_dim] + self.in_channels = in_channels + inner_dim = n_heads * d_head + self.norm = Normalize(in_channels) + if not use_linear: + self.proj_in = nn.Conv2d( + in_channels, inner_dim, kernel_size=1, stride=1, padding=0 + ) + else: + self.proj_in = nn.Linear(in_channels, inner_dim) + + self.transformer_blocks = nn.ModuleList( + [ + BasicTransformerBlock( + inner_dim, + n_heads, + d_head, + dropout=dropout, + context_dim=context_dim[d], + disable_self_attn=disable_self_attn, + checkpoint=use_checkpoint, + ) + for d in range(depth) + ] + ) + if not use_linear: + self.proj_out = zero_module( + nn.Conv2d(inner_dim, in_channels, kernel_size=1, stride=1, padding=0) + ) + else: + self.proj_out = zero_module(nn.Linear(in_channels, inner_dim)) + self.use_linear = use_linear + + def forward(self, x, context=None): + # note: if no context is given, cross-attention defaults to self-attention + if not isinstance(context, list): + context = [context] + b, c, h, w = x.shape + x_in = x + x = self.norm(x) + if not self.use_linear: + x = self.proj_in(x) + x = rearrange(x, "b c h w -> b (h w) c").contiguous() + if self.use_linear: + x = self.proj_in(x) + for i, block in enumerate(self.transformer_blocks): + x = block(x, context=context[i]) + if self.use_linear: + x = self.proj_out(x) + x = rearrange(x, "b (h w) c -> b c h w", h=h, w=w).contiguous() + if not self.use_linear: + x = self.proj_out(x) + return x + x_in diff --git a/py/iopaint/model/anytext/ldm/modules/diffusionmodules/__init__.py b/py/iopaint/model/anytext/ldm/modules/diffusionmodules/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/py/iopaint/model/anytext/ldm/modules/diffusionmodules/model.py b/py/iopaint/model/anytext/ldm/modules/diffusionmodules/model.py new file mode 100644 index 0000000..3472824 --- /dev/null +++ b/py/iopaint/model/anytext/ldm/modules/diffusionmodules/model.py @@ -0,0 +1,973 @@ +# pytorch_diffusion + derived encoder decoder +import math + +import numpy as np +import torch +import torch.nn as nn + + +def get_timestep_embedding(timesteps, embedding_dim): + """ + This matches the implementation in Denoising Diffusion Probabilistic Models: + From Fairseq. + Build sinusoidal embeddings. + This matches the implementation in tensor2tensor, but differs slightly + from the description in Section 3.5 of "Attention Is All You Need". + """ + assert len(timesteps.shape) == 1 + + half_dim = embedding_dim // 2 + emb = math.log(10000) / (half_dim - 1) + emb = torch.exp(torch.arange(half_dim, dtype=torch.float32) * -emb) + emb = emb.to(device=timesteps.device) + emb = timesteps.float()[:, None] * emb[None, :] + emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1) + if embedding_dim % 2 == 1: # zero pad + emb = torch.nn.functional.pad(emb, (0, 1, 0, 0)) + return emb + + +def nonlinearity(x): + # swish + return x * torch.sigmoid(x) + + +def Normalize(in_channels, num_groups=32): + return torch.nn.GroupNorm( + num_groups=num_groups, num_channels=in_channels, eps=1e-6, affine=True + ) + + +class Upsample(nn.Module): + def __init__(self, in_channels, with_conv): + super().__init__() + self.with_conv = with_conv + if self.with_conv: + self.conv = torch.nn.Conv2d( + in_channels, in_channels, kernel_size=3, stride=1, padding=1 + ) + + def forward(self, x): + x = torch.nn.functional.interpolate(x, scale_factor=2.0, mode="nearest") + if self.with_conv: + x = self.conv(x) + return x + + +class Downsample(nn.Module): + def __init__(self, in_channels, with_conv): + super().__init__() + self.with_conv = with_conv + if self.with_conv: + # no asymmetric padding in torch conv, must do it ourselves + self.conv = torch.nn.Conv2d( + in_channels, in_channels, kernel_size=3, stride=2, padding=0 + ) + + def forward(self, x): + if self.with_conv: + pad = (0, 1, 0, 1) + x = torch.nn.functional.pad(x, pad, mode="constant", value=0) + x = self.conv(x) + else: + x = torch.nn.functional.avg_pool2d(x, kernel_size=2, stride=2) + return x + + +class ResnetBlock(nn.Module): + def __init__( + self, + *, + in_channels, + out_channels=None, + conv_shortcut=False, + dropout, + temb_channels=512, + ): + super().__init__() + self.in_channels = in_channels + out_channels = in_channels if out_channels is None else out_channels + self.out_channels = out_channels + self.use_conv_shortcut = conv_shortcut + + self.norm1 = Normalize(in_channels) + self.conv1 = torch.nn.Conv2d( + in_channels, out_channels, kernel_size=3, stride=1, padding=1 + ) + if temb_channels > 0: + self.temb_proj = torch.nn.Linear(temb_channels, out_channels) + self.norm2 = Normalize(out_channels) + self.dropout = torch.nn.Dropout(dropout) + self.conv2 = torch.nn.Conv2d( + out_channels, out_channels, kernel_size=3, stride=1, padding=1 + ) + if self.in_channels != self.out_channels: + if self.use_conv_shortcut: + self.conv_shortcut = torch.nn.Conv2d( + in_channels, out_channels, kernel_size=3, stride=1, padding=1 + ) + else: + self.nin_shortcut = torch.nn.Conv2d( + in_channels, out_channels, kernel_size=1, stride=1, padding=0 + ) + + def forward(self, x, temb): + h = x + h = self.norm1(h) + h = nonlinearity(h) + h = self.conv1(h) + + if temb is not None: + h = h + self.temb_proj(nonlinearity(temb))[:, :, None, None] + + h = self.norm2(h) + h = nonlinearity(h) + h = self.dropout(h) + h = self.conv2(h) + + if self.in_channels != self.out_channels: + if self.use_conv_shortcut: + x = self.conv_shortcut(x) + else: + x = self.nin_shortcut(x) + + return x + h + + +class AttnBlock(nn.Module): + def __init__(self, in_channels): + super().__init__() + self.in_channels = in_channels + + self.norm = Normalize(in_channels) + self.q = torch.nn.Conv2d( + in_channels, in_channels, kernel_size=1, stride=1, padding=0 + ) + self.k = torch.nn.Conv2d( + in_channels, in_channels, kernel_size=1, stride=1, padding=0 + ) + self.v = torch.nn.Conv2d( + in_channels, in_channels, kernel_size=1, stride=1, padding=0 + ) + self.proj_out = torch.nn.Conv2d( + in_channels, in_channels, kernel_size=1, stride=1, padding=0 + ) + + def forward(self, x): + h_ = x + h_ = self.norm(h_) + q = self.q(h_) + k = self.k(h_) + v = self.v(h_) + + # compute attention + b, c, h, w = q.shape + q = q.reshape(b, c, h * w) + q = q.permute(0, 2, 1) # b,hw,c + k = k.reshape(b, c, h * w) # b,c,hw + w_ = torch.bmm(q, k) # b,hw,hw w[b,i,j]=sum_c q[b,i,c]k[b,c,j] + w_ = w_ * (int(c) ** (-0.5)) + w_ = torch.nn.functional.softmax(w_, dim=2) + + # attend to values + v = v.reshape(b, c, h * w) + w_ = w_.permute(0, 2, 1) # b,hw,hw (first hw of k, second of q) + h_ = torch.bmm(v, w_) # b, c,hw (hw of q) h_[b,c,j] = sum_i v[b,c,i] w_[b,i,j] + h_ = h_.reshape(b, c, h, w) + + h_ = self.proj_out(h_) + + return x + h_ + + +class AttnBlock2_0(nn.Module): + def __init__(self, in_channels): + super().__init__() + self.in_channels = in_channels + + self.norm = Normalize(in_channels) + self.q = torch.nn.Conv2d( + in_channels, in_channels, kernel_size=1, stride=1, padding=0 + ) + self.k = torch.nn.Conv2d( + in_channels, in_channels, kernel_size=1, stride=1, padding=0 + ) + self.v = torch.nn.Conv2d( + in_channels, in_channels, kernel_size=1, stride=1, padding=0 + ) + self.proj_out = torch.nn.Conv2d( + in_channels, in_channels, kernel_size=1, stride=1, padding=0 + ) + + def forward(self, x): + h_ = x + h_ = self.norm(h_) + # output: [1, 512, 64, 64] + q = self.q(h_) + k = self.k(h_) + v = self.v(h_) + + # compute attention + b, c, h, w = q.shape + + # q = q.reshape(b, c, h * w).transpose() + # q = q.permute(0, 2, 1) # b,hw,c + # k = k.reshape(b, c, h * w) # b,c,hw + q = q.transpose(1, 2) + k = k.transpose(1, 2) + v = v.transpose(1, 2) + # (batch, num_heads, seq_len, head_dim) + hidden_states = torch.nn.functional.scaled_dot_product_attention( + q, k, v, attn_mask=None, dropout_p=0.0, is_causal=False + ) + hidden_states = hidden_states.transpose(1, 2) + hidden_states = hidden_states.to(q.dtype) + + h_ = self.proj_out(hidden_states) + + return x + h_ + + +def make_attn(in_channels, attn_type="vanilla", attn_kwargs=None): + assert attn_type in [ + "vanilla", + "vanilla-xformers", + "memory-efficient-cross-attn", + "linear", + "none", + ], f"attn_type {attn_type} unknown" + assert attn_kwargs is None + if hasattr(torch.nn.functional, "scaled_dot_product_attention"): + # print(f"Using torch.nn.functional.scaled_dot_product_attention") + return AttnBlock2_0(in_channels) + return AttnBlock(in_channels) + + +class Model(nn.Module): + def __init__( + self, + *, + ch, + out_ch, + ch_mult=(1, 2, 4, 8), + num_res_blocks, + attn_resolutions, + dropout=0.0, + resamp_with_conv=True, + in_channels, + resolution, + use_timestep=True, + use_linear_attn=False, + attn_type="vanilla", + ): + super().__init__() + if use_linear_attn: + attn_type = "linear" + self.ch = ch + self.temb_ch = self.ch * 4 + self.num_resolutions = len(ch_mult) + self.num_res_blocks = num_res_blocks + self.resolution = resolution + self.in_channels = in_channels + + self.use_timestep = use_timestep + if self.use_timestep: + # timestep embedding + self.temb = nn.Module() + self.temb.dense = nn.ModuleList( + [ + torch.nn.Linear(self.ch, self.temb_ch), + torch.nn.Linear(self.temb_ch, self.temb_ch), + ] + ) + + # downsampling + self.conv_in = torch.nn.Conv2d( + in_channels, self.ch, kernel_size=3, stride=1, padding=1 + ) + + curr_res = resolution + in_ch_mult = (1,) + tuple(ch_mult) + self.down = nn.ModuleList() + for i_level in range(self.num_resolutions): + block = nn.ModuleList() + attn = nn.ModuleList() + block_in = ch * in_ch_mult[i_level] + block_out = ch * ch_mult[i_level] + for i_block in range(self.num_res_blocks): + block.append( + ResnetBlock( + in_channels=block_in, + out_channels=block_out, + temb_channels=self.temb_ch, + dropout=dropout, + ) + ) + block_in = block_out + if curr_res in attn_resolutions: + attn.append(make_attn(block_in, attn_type=attn_type)) + down = nn.Module() + down.block = block + down.attn = attn + if i_level != self.num_resolutions - 1: + down.downsample = Downsample(block_in, resamp_with_conv) + curr_res = curr_res // 2 + self.down.append(down) + + # middle + self.mid = nn.Module() + self.mid.block_1 = ResnetBlock( + in_channels=block_in, + out_channels=block_in, + temb_channels=self.temb_ch, + dropout=dropout, + ) + self.mid.attn_1 = make_attn(block_in, attn_type=attn_type) + self.mid.block_2 = ResnetBlock( + in_channels=block_in, + out_channels=block_in, + temb_channels=self.temb_ch, + dropout=dropout, + ) + + # upsampling + self.up = nn.ModuleList() + for i_level in reversed(range(self.num_resolutions)): + block = nn.ModuleList() + attn = nn.ModuleList() + block_out = ch * ch_mult[i_level] + skip_in = ch * ch_mult[i_level] + for i_block in range(self.num_res_blocks + 1): + if i_block == self.num_res_blocks: + skip_in = ch * in_ch_mult[i_level] + block.append( + ResnetBlock( + in_channels=block_in + skip_in, + out_channels=block_out, + temb_channels=self.temb_ch, + dropout=dropout, + ) + ) + block_in = block_out + if curr_res in attn_resolutions: + attn.append(make_attn(block_in, attn_type=attn_type)) + up = nn.Module() + up.block = block + up.attn = attn + if i_level != 0: + up.upsample = Upsample(block_in, resamp_with_conv) + curr_res = curr_res * 2 + self.up.insert(0, up) # prepend to get consistent order + + # end + self.norm_out = Normalize(block_in) + self.conv_out = torch.nn.Conv2d( + block_in, out_ch, kernel_size=3, stride=1, padding=1 + ) + + def forward(self, x, t=None, context=None): + # assert x.shape[2] == x.shape[3] == self.resolution + if context is not None: + # assume aligned context, cat along channel axis + x = torch.cat((x, context), dim=1) + if self.use_timestep: + # timestep embedding + assert t is not None + temb = get_timestep_embedding(t, self.ch) + temb = self.temb.dense[0](temb) + temb = nonlinearity(temb) + temb = self.temb.dense[1](temb) + else: + temb = None + + # downsampling + hs = [self.conv_in(x)] + for i_level in range(self.num_resolutions): + for i_block in range(self.num_res_blocks): + h = self.down[i_level].block[i_block](hs[-1], temb) + if len(self.down[i_level].attn) > 0: + h = self.down[i_level].attn[i_block](h) + hs.append(h) + if i_level != self.num_resolutions - 1: + hs.append(self.down[i_level].downsample(hs[-1])) + + # middle + h = hs[-1] + h = self.mid.block_1(h, temb) + h = self.mid.attn_1(h) + h = self.mid.block_2(h, temb) + + # upsampling + for i_level in reversed(range(self.num_resolutions)): + for i_block in range(self.num_res_blocks + 1): + h = self.up[i_level].block[i_block]( + torch.cat([h, hs.pop()], dim=1), temb + ) + if len(self.up[i_level].attn) > 0: + h = self.up[i_level].attn[i_block](h) + if i_level != 0: + h = self.up[i_level].upsample(h) + + # end + h = self.norm_out(h) + h = nonlinearity(h) + h = self.conv_out(h) + return h + + def get_last_layer(self): + return self.conv_out.weight + + +class Encoder(nn.Module): + def __init__( + self, + *, + ch, + out_ch, + ch_mult=(1, 2, 4, 8), + num_res_blocks, + attn_resolutions, + dropout=0.0, + resamp_with_conv=True, + in_channels, + resolution, + z_channels, + double_z=True, + use_linear_attn=False, + attn_type="vanilla", + **ignore_kwargs, + ): + super().__init__() + if use_linear_attn: + attn_type = "linear" + self.ch = ch + self.temb_ch = 0 + self.num_resolutions = len(ch_mult) + self.num_res_blocks = num_res_blocks + self.resolution = resolution + self.in_channels = in_channels + + # downsampling + self.conv_in = torch.nn.Conv2d( + in_channels, self.ch, kernel_size=3, stride=1, padding=1 + ) + + curr_res = resolution + in_ch_mult = (1,) + tuple(ch_mult) + self.in_ch_mult = in_ch_mult + self.down = nn.ModuleList() + for i_level in range(self.num_resolutions): + block = nn.ModuleList() + attn = nn.ModuleList() + block_in = ch * in_ch_mult[i_level] + block_out = ch * ch_mult[i_level] + for i_block in range(self.num_res_blocks): + block.append( + ResnetBlock( + in_channels=block_in, + out_channels=block_out, + temb_channels=self.temb_ch, + dropout=dropout, + ) + ) + block_in = block_out + if curr_res in attn_resolutions: + attn.append(make_attn(block_in, attn_type=attn_type)) + down = nn.Module() + down.block = block + down.attn = attn + if i_level != self.num_resolutions - 1: + down.downsample = Downsample(block_in, resamp_with_conv) + curr_res = curr_res // 2 + self.down.append(down) + + # middle + self.mid = nn.Module() + self.mid.block_1 = ResnetBlock( + in_channels=block_in, + out_channels=block_in, + temb_channels=self.temb_ch, + dropout=dropout, + ) + self.mid.attn_1 = make_attn(block_in, attn_type=attn_type) + self.mid.block_2 = ResnetBlock( + in_channels=block_in, + out_channels=block_in, + temb_channels=self.temb_ch, + dropout=dropout, + ) + + # end + self.norm_out = Normalize(block_in) + self.conv_out = torch.nn.Conv2d( + block_in, + 2 * z_channels if double_z else z_channels, + kernel_size=3, + stride=1, + padding=1, + ) + + def forward(self, x): + # timestep embedding + temb = None + + # downsampling + hs = [self.conv_in(x)] + for i_level in range(self.num_resolutions): + for i_block in range(self.num_res_blocks): + h = self.down[i_level].block[i_block](hs[-1], temb) + if len(self.down[i_level].attn) > 0: + h = self.down[i_level].attn[i_block](h) + hs.append(h) + if i_level != self.num_resolutions - 1: + hs.append(self.down[i_level].downsample(hs[-1])) + + # middle + h = hs[-1] + h = self.mid.block_1(h, temb) + h = self.mid.attn_1(h) + h = self.mid.block_2(h, temb) + + # end + h = self.norm_out(h) + h = nonlinearity(h) + h = self.conv_out(h) + return h + + +class Decoder(nn.Module): + def __init__( + self, + *, + ch, + out_ch, + ch_mult=(1, 2, 4, 8), + num_res_blocks, + attn_resolutions, + dropout=0.0, + resamp_with_conv=True, + in_channels, + resolution, + z_channels, + give_pre_end=False, + tanh_out=False, + use_linear_attn=False, + attn_type="vanilla", + **ignorekwargs, + ): + super().__init__() + if use_linear_attn: + attn_type = "linear" + self.ch = ch + self.temb_ch = 0 + self.num_resolutions = len(ch_mult) + self.num_res_blocks = num_res_blocks + self.resolution = resolution + self.in_channels = in_channels + self.give_pre_end = give_pre_end + self.tanh_out = tanh_out + + # compute in_ch_mult, block_in and curr_res at lowest res + in_ch_mult = (1,) + tuple(ch_mult) + block_in = ch * ch_mult[self.num_resolutions - 1] + curr_res = resolution // 2 ** (self.num_resolutions - 1) + self.z_shape = (1, z_channels, curr_res, curr_res) + print( + "Working with z of shape {} = {} dimensions.".format( + self.z_shape, np.prod(self.z_shape) + ) + ) + + # z to block_in + self.conv_in = torch.nn.Conv2d( + z_channels, block_in, kernel_size=3, stride=1, padding=1 + ) + + # middle + self.mid = nn.Module() + self.mid.block_1 = ResnetBlock( + in_channels=block_in, + out_channels=block_in, + temb_channels=self.temb_ch, + dropout=dropout, + ) + self.mid.attn_1 = make_attn(block_in, attn_type=attn_type) + self.mid.block_2 = ResnetBlock( + in_channels=block_in, + out_channels=block_in, + temb_channels=self.temb_ch, + dropout=dropout, + ) + + # upsampling + self.up = nn.ModuleList() + for i_level in reversed(range(self.num_resolutions)): + block = nn.ModuleList() + attn = nn.ModuleList() + block_out = ch * ch_mult[i_level] + for i_block in range(self.num_res_blocks + 1): + block.append( + ResnetBlock( + in_channels=block_in, + out_channels=block_out, + temb_channels=self.temb_ch, + dropout=dropout, + ) + ) + block_in = block_out + if curr_res in attn_resolutions: + attn.append(make_attn(block_in, attn_type=attn_type)) + up = nn.Module() + up.block = block + up.attn = attn + if i_level != 0: + up.upsample = Upsample(block_in, resamp_with_conv) + curr_res = curr_res * 2 + self.up.insert(0, up) # prepend to get consistent order + + # end + self.norm_out = Normalize(block_in) + self.conv_out = torch.nn.Conv2d( + block_in, out_ch, kernel_size=3, stride=1, padding=1 + ) + + def forward(self, z): + # assert z.shape[1:] == self.z_shape[1:] + self.last_z_shape = z.shape + + # timestep embedding + temb = None + + # z to block_in + h = self.conv_in(z) + + # middle + h = self.mid.block_1(h, temb) + h = self.mid.attn_1(h) + h = self.mid.block_2(h, temb) + + # upsampling + for i_level in reversed(range(self.num_resolutions)): + for i_block in range(self.num_res_blocks + 1): + h = self.up[i_level].block[i_block](h, temb) + if len(self.up[i_level].attn) > 0: + h = self.up[i_level].attn[i_block](h) + if i_level != 0: + h = self.up[i_level].upsample(h) + + # end + if self.give_pre_end: + return h + + h = self.norm_out(h) + h = nonlinearity(h) + h = self.conv_out(h) + if self.tanh_out: + h = torch.tanh(h) + return h + + +class SimpleDecoder(nn.Module): + def __init__(self, in_channels, out_channels, *args, **kwargs): + super().__init__() + self.model = nn.ModuleList( + [ + nn.Conv2d(in_channels, in_channels, 1), + ResnetBlock( + in_channels=in_channels, + out_channels=2 * in_channels, + temb_channels=0, + dropout=0.0, + ), + ResnetBlock( + in_channels=2 * in_channels, + out_channels=4 * in_channels, + temb_channels=0, + dropout=0.0, + ), + ResnetBlock( + in_channels=4 * in_channels, + out_channels=2 * in_channels, + temb_channels=0, + dropout=0.0, + ), + nn.Conv2d(2 * in_channels, in_channels, 1), + Upsample(in_channels, with_conv=True), + ] + ) + # end + self.norm_out = Normalize(in_channels) + self.conv_out = torch.nn.Conv2d( + in_channels, out_channels, kernel_size=3, stride=1, padding=1 + ) + + def forward(self, x): + for i, layer in enumerate(self.model): + if i in [1, 2, 3]: + x = layer(x, None) + else: + x = layer(x) + + h = self.norm_out(x) + h = nonlinearity(h) + x = self.conv_out(h) + return x + + +class UpsampleDecoder(nn.Module): + def __init__( + self, + in_channels, + out_channels, + ch, + num_res_blocks, + resolution, + ch_mult=(2, 2), + dropout=0.0, + ): + super().__init__() + # upsampling + self.temb_ch = 0 + self.num_resolutions = len(ch_mult) + self.num_res_blocks = num_res_blocks + block_in = in_channels + curr_res = resolution // 2 ** (self.num_resolutions - 1) + self.res_blocks = nn.ModuleList() + self.upsample_blocks = nn.ModuleList() + for i_level in range(self.num_resolutions): + res_block = [] + block_out = ch * ch_mult[i_level] + for i_block in range(self.num_res_blocks + 1): + res_block.append( + ResnetBlock( + in_channels=block_in, + out_channels=block_out, + temb_channels=self.temb_ch, + dropout=dropout, + ) + ) + block_in = block_out + self.res_blocks.append(nn.ModuleList(res_block)) + if i_level != self.num_resolutions - 1: + self.upsample_blocks.append(Upsample(block_in, True)) + curr_res = curr_res * 2 + + # end + self.norm_out = Normalize(block_in) + self.conv_out = torch.nn.Conv2d( + block_in, out_channels, kernel_size=3, stride=1, padding=1 + ) + + def forward(self, x): + # upsampling + h = x + for k, i_level in enumerate(range(self.num_resolutions)): + for i_block in range(self.num_res_blocks + 1): + h = self.res_blocks[i_level][i_block](h, None) + if i_level != self.num_resolutions - 1: + h = self.upsample_blocks[k](h) + h = self.norm_out(h) + h = nonlinearity(h) + h = self.conv_out(h) + return h + + +class LatentRescaler(nn.Module): + def __init__(self, factor, in_channels, mid_channels, out_channels, depth=2): + super().__init__() + # residual block, interpolate, residual block + self.factor = factor + self.conv_in = nn.Conv2d( + in_channels, mid_channels, kernel_size=3, stride=1, padding=1 + ) + self.res_block1 = nn.ModuleList( + [ + ResnetBlock( + in_channels=mid_channels, + out_channels=mid_channels, + temb_channels=0, + dropout=0.0, + ) + for _ in range(depth) + ] + ) + self.attn = AttnBlock(mid_channels) + self.res_block2 = nn.ModuleList( + [ + ResnetBlock( + in_channels=mid_channels, + out_channels=mid_channels, + temb_channels=0, + dropout=0.0, + ) + for _ in range(depth) + ] + ) + + self.conv_out = nn.Conv2d( + mid_channels, + out_channels, + kernel_size=1, + ) + + def forward(self, x): + x = self.conv_in(x) + for block in self.res_block1: + x = block(x, None) + x = torch.nn.functional.interpolate( + x, + size=( + int(round(x.shape[2] * self.factor)), + int(round(x.shape[3] * self.factor)), + ), + ) + x = self.attn(x) + for block in self.res_block2: + x = block(x, None) + x = self.conv_out(x) + return x + + +class MergedRescaleEncoder(nn.Module): + def __init__( + self, + in_channels, + ch, + resolution, + out_ch, + num_res_blocks, + attn_resolutions, + dropout=0.0, + resamp_with_conv=True, + ch_mult=(1, 2, 4, 8), + rescale_factor=1.0, + rescale_module_depth=1, + ): + super().__init__() + intermediate_chn = ch * ch_mult[-1] + self.encoder = Encoder( + in_channels=in_channels, + num_res_blocks=num_res_blocks, + ch=ch, + ch_mult=ch_mult, + z_channels=intermediate_chn, + double_z=False, + resolution=resolution, + attn_resolutions=attn_resolutions, + dropout=dropout, + resamp_with_conv=resamp_with_conv, + out_ch=None, + ) + self.rescaler = LatentRescaler( + factor=rescale_factor, + in_channels=intermediate_chn, + mid_channels=intermediate_chn, + out_channels=out_ch, + depth=rescale_module_depth, + ) + + def forward(self, x): + x = self.encoder(x) + x = self.rescaler(x) + return x + + +class MergedRescaleDecoder(nn.Module): + def __init__( + self, + z_channels, + out_ch, + resolution, + num_res_blocks, + attn_resolutions, + ch, + ch_mult=(1, 2, 4, 8), + dropout=0.0, + resamp_with_conv=True, + rescale_factor=1.0, + rescale_module_depth=1, + ): + super().__init__() + tmp_chn = z_channels * ch_mult[-1] + self.decoder = Decoder( + out_ch=out_ch, + z_channels=tmp_chn, + attn_resolutions=attn_resolutions, + dropout=dropout, + resamp_with_conv=resamp_with_conv, + in_channels=None, + num_res_blocks=num_res_blocks, + ch_mult=ch_mult, + resolution=resolution, + ch=ch, + ) + self.rescaler = LatentRescaler( + factor=rescale_factor, + in_channels=z_channels, + mid_channels=tmp_chn, + out_channels=tmp_chn, + depth=rescale_module_depth, + ) + + def forward(self, x): + x = self.rescaler(x) + x = self.decoder(x) + return x + + +class Upsampler(nn.Module): + def __init__(self, in_size, out_size, in_channels, out_channels, ch_mult=2): + super().__init__() + assert out_size >= in_size + num_blocks = int(np.log2(out_size // in_size)) + 1 + factor_up = 1.0 + (out_size % in_size) + print( + f"Building {self.__class__.__name__} with in_size: {in_size} --> out_size {out_size} and factor {factor_up}" + ) + self.rescaler = LatentRescaler( + factor=factor_up, + in_channels=in_channels, + mid_channels=2 * in_channels, + out_channels=in_channels, + ) + self.decoder = Decoder( + out_ch=out_channels, + resolution=out_size, + z_channels=in_channels, + num_res_blocks=2, + attn_resolutions=[], + in_channels=None, + ch=in_channels, + ch_mult=[ch_mult for _ in range(num_blocks)], + ) + + def forward(self, x): + x = self.rescaler(x) + x = self.decoder(x) + return x + + +class Resize(nn.Module): + def __init__(self, in_channels=None, learned=False, mode="bilinear"): + super().__init__() + self.with_conv = learned + self.mode = mode + if self.with_conv: + print( + f"Note: {self.__class__.__name} uses learned downsampling and will ignore the fixed {mode} mode" + ) + raise NotImplementedError() + assert in_channels is not None + # no asymmetric padding in torch conv, must do it ourselves + self.conv = torch.nn.Conv2d( + in_channels, in_channels, kernel_size=4, stride=2, padding=1 + ) + + def forward(self, x, scale_factor=1.0): + if scale_factor == 1.0: + return x + else: + x = torch.nn.functional.interpolate( + x, mode=self.mode, align_corners=False, scale_factor=scale_factor + ) + return x diff --git a/py/iopaint/model/anytext/ldm/modules/diffusionmodules/openaimodel.py b/py/iopaint/model/anytext/ldm/modules/diffusionmodules/openaimodel.py new file mode 100644 index 0000000..fd3d6be --- /dev/null +++ b/py/iopaint/model/anytext/ldm/modules/diffusionmodules/openaimodel.py @@ -0,0 +1,786 @@ +from abc import abstractmethod +import math + +import numpy as np +import torch as th +import torch.nn as nn +import torch.nn.functional as F + +from iopaint.model.anytext.ldm.modules.diffusionmodules.util import ( + checkpoint, + conv_nd, + linear, + avg_pool_nd, + zero_module, + normalization, + timestep_embedding, +) +from iopaint.model.anytext.ldm.modules.attention import SpatialTransformer +from iopaint.model.anytext.ldm.util import exists + + +# dummy replace +def convert_module_to_f16(x): + pass + +def convert_module_to_f32(x): + pass + + +## go +class AttentionPool2d(nn.Module): + """ + Adapted from CLIP: https://github.com/openai/CLIP/blob/main/clip/model.py + """ + + def __init__( + self, + spacial_dim: int, + embed_dim: int, + num_heads_channels: int, + output_dim: int = None, + ): + super().__init__() + self.positional_embedding = nn.Parameter(th.randn(embed_dim, spacial_dim ** 2 + 1) / embed_dim ** 0.5) + self.qkv_proj = conv_nd(1, embed_dim, 3 * embed_dim, 1) + self.c_proj = conv_nd(1, embed_dim, output_dim or embed_dim, 1) + self.num_heads = embed_dim // num_heads_channels + self.attention = QKVAttention(self.num_heads) + + def forward(self, x): + b, c, *_spatial = x.shape + x = x.reshape(b, c, -1) # NC(HW) + x = th.cat([x.mean(dim=-1, keepdim=True), x], dim=-1) # NC(HW+1) + x = x + self.positional_embedding[None, :, :].to(x.dtype) # NC(HW+1) + x = self.qkv_proj(x) + x = self.attention(x) + x = self.c_proj(x) + return x[:, :, 0] + + +class TimestepBlock(nn.Module): + """ + Any module where forward() takes timestep embeddings as a second argument. + """ + + @abstractmethod + def forward(self, x, emb): + """ + Apply the module to `x` given `emb` timestep embeddings. + """ + + +class TimestepEmbedSequential(nn.Sequential, TimestepBlock): + """ + A sequential module that passes timestep embeddings to the children that + support it as an extra input. + """ + + def forward(self, x, emb, context=None): + for layer in self: + if isinstance(layer, TimestepBlock): + x = layer(x, emb) + elif isinstance(layer, SpatialTransformer): + x = layer(x, context) + else: + x = layer(x) + return x + + +class Upsample(nn.Module): + """ + An upsampling layer with an optional convolution. + :param channels: channels in the inputs and outputs. + :param use_conv: a bool determining if a convolution is applied. + :param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then + upsampling occurs in the inner-two dimensions. + """ + + def __init__(self, channels, use_conv, dims=2, out_channels=None, padding=1): + super().__init__() + self.channels = channels + self.out_channels = out_channels or channels + self.use_conv = use_conv + self.dims = dims + if use_conv: + self.conv = conv_nd(dims, self.channels, self.out_channels, 3, padding=padding) + + def forward(self, x): + assert x.shape[1] == self.channels + if self.dims == 3: + x = F.interpolate( + x, (x.shape[2], x.shape[3] * 2, x.shape[4] * 2), mode="nearest" + ) + else: + x = F.interpolate(x, scale_factor=2, mode="nearest") + if self.use_conv: + x = self.conv(x) + return x + +class TransposedUpsample(nn.Module): + 'Learned 2x upsampling without padding' + def __init__(self, channels, out_channels=None, ks=5): + super().__init__() + self.channels = channels + self.out_channels = out_channels or channels + + self.up = nn.ConvTranspose2d(self.channels,self.out_channels,kernel_size=ks,stride=2) + + def forward(self,x): + return self.up(x) + + +class Downsample(nn.Module): + """ + A downsampling layer with an optional convolution. + :param channels: channels in the inputs and outputs. + :param use_conv: a bool determining if a convolution is applied. + :param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then + downsampling occurs in the inner-two dimensions. + """ + + def __init__(self, channels, use_conv, dims=2, out_channels=None,padding=1): + super().__init__() + self.channels = channels + self.out_channels = out_channels or channels + self.use_conv = use_conv + self.dims = dims + stride = 2 if dims != 3 else (1, 2, 2) + if use_conv: + self.op = conv_nd( + dims, self.channels, self.out_channels, 3, stride=stride, padding=padding + ) + else: + assert self.channels == self.out_channels + self.op = avg_pool_nd(dims, kernel_size=stride, stride=stride) + + def forward(self, x): + assert x.shape[1] == self.channels + return self.op(x) + + +class ResBlock(TimestepBlock): + """ + A residual block that can optionally change the number of channels. + :param channels: the number of input channels. + :param emb_channels: the number of timestep embedding channels. + :param dropout: the rate of dropout. + :param out_channels: if specified, the number of out channels. + :param use_conv: if True and out_channels is specified, use a spatial + convolution instead of a smaller 1x1 convolution to change the + channels in the skip connection. + :param dims: determines if the signal is 1D, 2D, or 3D. + :param use_checkpoint: if True, use gradient checkpointing on this module. + :param up: if True, use this block for upsampling. + :param down: if True, use this block for downsampling. + """ + + def __init__( + self, + channels, + emb_channels, + dropout, + out_channels=None, + use_conv=False, + use_scale_shift_norm=False, + dims=2, + use_checkpoint=False, + up=False, + down=False, + ): + super().__init__() + self.channels = channels + self.emb_channels = emb_channels + self.dropout = dropout + self.out_channels = out_channels or channels + self.use_conv = use_conv + self.use_checkpoint = use_checkpoint + self.use_scale_shift_norm = use_scale_shift_norm + + self.in_layers = nn.Sequential( + normalization(channels), + nn.SiLU(), + conv_nd(dims, channels, self.out_channels, 3, padding=1), + ) + + self.updown = up or down + + if up: + self.h_upd = Upsample(channels, False, dims) + self.x_upd = Upsample(channels, False, dims) + elif down: + self.h_upd = Downsample(channels, False, dims) + self.x_upd = Downsample(channels, False, dims) + else: + self.h_upd = self.x_upd = nn.Identity() + + self.emb_layers = nn.Sequential( + nn.SiLU(), + linear( + emb_channels, + 2 * self.out_channels if use_scale_shift_norm else self.out_channels, + ), + ) + self.out_layers = nn.Sequential( + normalization(self.out_channels), + nn.SiLU(), + nn.Dropout(p=dropout), + zero_module( + conv_nd(dims, self.out_channels, self.out_channels, 3, padding=1) + ), + ) + + if self.out_channels == channels: + self.skip_connection = nn.Identity() + elif use_conv: + self.skip_connection = conv_nd( + dims, channels, self.out_channels, 3, padding=1 + ) + else: + self.skip_connection = conv_nd(dims, channels, self.out_channels, 1) + + def forward(self, x, emb): + """ + Apply the block to a Tensor, conditioned on a timestep embedding. + :param x: an [N x C x ...] Tensor of features. + :param emb: an [N x emb_channels] Tensor of timestep embeddings. + :return: an [N x C x ...] Tensor of outputs. + """ + return checkpoint( + self._forward, (x, emb), self.parameters(), self.use_checkpoint + ) + + + def _forward(self, x, emb): + if self.updown: + in_rest, in_conv = self.in_layers[:-1], self.in_layers[-1] + h = in_rest(x) + h = self.h_upd(h) + x = self.x_upd(x) + h = in_conv(h) + else: + h = self.in_layers(x) + emb_out = self.emb_layers(emb).type(h.dtype) + while len(emb_out.shape) < len(h.shape): + emb_out = emb_out[..., None] + if self.use_scale_shift_norm: + out_norm, out_rest = self.out_layers[0], self.out_layers[1:] + scale, shift = th.chunk(emb_out, 2, dim=1) + h = out_norm(h) * (1 + scale) + shift + h = out_rest(h) + else: + h = h + emb_out + h = self.out_layers(h) + return self.skip_connection(x) + h + + +class AttentionBlock(nn.Module): + """ + An attention block that allows spatial positions to attend to each other. + Originally ported from here, but adapted to the N-d case. + https://github.com/hojonathanho/diffusion/blob/1e0dceb3b3495bbe19116a5e1b3596cd0706c543/diffusion_tf/models/unet.py#L66. + """ + + def __init__( + self, + channels, + num_heads=1, + num_head_channels=-1, + use_checkpoint=False, + use_new_attention_order=False, + ): + super().__init__() + self.channels = channels + if num_head_channels == -1: + self.num_heads = num_heads + else: + assert ( + channels % num_head_channels == 0 + ), f"q,k,v channels {channels} is not divisible by num_head_channels {num_head_channels}" + self.num_heads = channels // num_head_channels + self.use_checkpoint = use_checkpoint + self.norm = normalization(channels) + self.qkv = conv_nd(1, channels, channels * 3, 1) + if use_new_attention_order: + # split qkv before split heads + self.attention = QKVAttention(self.num_heads) + else: + # split heads before split qkv + self.attention = QKVAttentionLegacy(self.num_heads) + + self.proj_out = zero_module(conv_nd(1, channels, channels, 1)) + + def forward(self, x): + return checkpoint(self._forward, (x,), self.parameters(), True) # TODO: check checkpoint usage, is True # TODO: fix the .half call!!! + #return pt_checkpoint(self._forward, x) # pytorch + + def _forward(self, x): + b, c, *spatial = x.shape + x = x.reshape(b, c, -1) + qkv = self.qkv(self.norm(x)) + h = self.attention(qkv) + h = self.proj_out(h) + return (x + h).reshape(b, c, *spatial) + + +def count_flops_attn(model, _x, y): + """ + A counter for the `thop` package to count the operations in an + attention operation. + Meant to be used like: + macs, params = thop.profile( + model, + inputs=(inputs, timestamps), + custom_ops={QKVAttention: QKVAttention.count_flops}, + ) + """ + b, c, *spatial = y[0].shape + num_spatial = int(np.prod(spatial)) + # We perform two matmuls with the same number of ops. + # The first computes the weight matrix, the second computes + # the combination of the value vectors. + matmul_ops = 2 * b * (num_spatial ** 2) * c + model.total_ops += th.DoubleTensor([matmul_ops]) + + +class QKVAttentionLegacy(nn.Module): + """ + A module which performs QKV attention. Matches legacy QKVAttention + input/ouput heads shaping + """ + + def __init__(self, n_heads): + super().__init__() + self.n_heads = n_heads + + def forward(self, qkv): + """ + Apply QKV attention. + :param qkv: an [N x (H * 3 * C) x T] tensor of Qs, Ks, and Vs. + :return: an [N x (H * C) x T] tensor after attention. + """ + bs, width, length = qkv.shape + assert width % (3 * self.n_heads) == 0 + ch = width // (3 * self.n_heads) + q, k, v = qkv.reshape(bs * self.n_heads, ch * 3, length).split(ch, dim=1) + scale = 1 / math.sqrt(math.sqrt(ch)) + weight = th.einsum( + "bct,bcs->bts", q * scale, k * scale + ) # More stable with f16 than dividing afterwards + weight = th.softmax(weight.float(), dim=-1).type(weight.dtype) + a = th.einsum("bts,bcs->bct", weight, v) + return a.reshape(bs, -1, length) + + @staticmethod + def count_flops(model, _x, y): + return count_flops_attn(model, _x, y) + + +class QKVAttention(nn.Module): + """ + A module which performs QKV attention and splits in a different order. + """ + + def __init__(self, n_heads): + super().__init__() + self.n_heads = n_heads + + def forward(self, qkv): + """ + Apply QKV attention. + :param qkv: an [N x (3 * H * C) x T] tensor of Qs, Ks, and Vs. + :return: an [N x (H * C) x T] tensor after attention. + """ + bs, width, length = qkv.shape + assert width % (3 * self.n_heads) == 0 + ch = width // (3 * self.n_heads) + q, k, v = qkv.chunk(3, dim=1) + scale = 1 / math.sqrt(math.sqrt(ch)) + weight = th.einsum( + "bct,bcs->bts", + (q * scale).view(bs * self.n_heads, ch, length), + (k * scale).view(bs * self.n_heads, ch, length), + ) # More stable with f16 than dividing afterwards + weight = th.softmax(weight.float(), dim=-1).type(weight.dtype) + a = th.einsum("bts,bcs->bct", weight, v.reshape(bs * self.n_heads, ch, length)) + return a.reshape(bs, -1, length) + + @staticmethod + def count_flops(model, _x, y): + return count_flops_attn(model, _x, y) + + +class UNetModel(nn.Module): + """ + The full UNet model with attention and timestep embedding. + :param in_channels: channels in the input Tensor. + :param model_channels: base channel count for the model. + :param out_channels: channels in the output Tensor. + :param num_res_blocks: number of residual blocks per downsample. + :param attention_resolutions: a collection of downsample rates at which + attention will take place. May be a set, list, or tuple. + For example, if this contains 4, then at 4x downsampling, attention + will be used. + :param dropout: the dropout probability. + :param channel_mult: channel multiplier for each level of the UNet. + :param conv_resample: if True, use learned convolutions for upsampling and + downsampling. + :param dims: determines if the signal is 1D, 2D, or 3D. + :param num_classes: if specified (as an int), then this model will be + class-conditional with `num_classes` classes. + :param use_checkpoint: use gradient checkpointing to reduce memory usage. + :param num_heads: the number of attention heads in each attention layer. + :param num_heads_channels: if specified, ignore num_heads and instead use + a fixed channel width per attention head. + :param num_heads_upsample: works with num_heads to set a different number + of heads for upsampling. Deprecated. + :param use_scale_shift_norm: use a FiLM-like conditioning mechanism. + :param resblock_updown: use residual blocks for up/downsampling. + :param use_new_attention_order: use a different attention pattern for potentially + increased efficiency. + """ + + def __init__( + self, + image_size, + in_channels, + model_channels, + out_channels, + num_res_blocks, + attention_resolutions, + dropout=0, + channel_mult=(1, 2, 4, 8), + conv_resample=True, + dims=2, + num_classes=None, + use_checkpoint=False, + use_fp16=False, + num_heads=-1, + num_head_channels=-1, + num_heads_upsample=-1, + use_scale_shift_norm=False, + resblock_updown=False, + use_new_attention_order=False, + use_spatial_transformer=False, # custom transformer support + transformer_depth=1, # custom transformer support + context_dim=None, # custom transformer support + n_embed=None, # custom support for prediction of discrete ids into codebook of first stage vq model + legacy=True, + disable_self_attentions=None, + num_attention_blocks=None, + disable_middle_self_attn=False, + use_linear_in_transformer=False, + ): + super().__init__() + if use_spatial_transformer: + assert context_dim is not None, 'Fool!! You forgot to include the dimension of your cross-attention conditioning...' + + if context_dim is not None: + assert use_spatial_transformer, 'Fool!! You forgot to use the spatial transformer for your cross-attention conditioning...' + from omegaconf.listconfig import ListConfig + if type(context_dim) == ListConfig: + context_dim = list(context_dim) + + if num_heads_upsample == -1: + num_heads_upsample = num_heads + + if num_heads == -1: + assert num_head_channels != -1, 'Either num_heads or num_head_channels has to be set' + + if num_head_channels == -1: + assert num_heads != -1, 'Either num_heads or num_head_channels has to be set' + + self.image_size = image_size + self.in_channels = in_channels + self.model_channels = model_channels + self.out_channels = out_channels + if isinstance(num_res_blocks, int): + self.num_res_blocks = len(channel_mult) * [num_res_blocks] + else: + if len(num_res_blocks) != len(channel_mult): + raise ValueError("provide num_res_blocks either as an int (globally constant) or " + "as a list/tuple (per-level) with the same length as channel_mult") + self.num_res_blocks = num_res_blocks + if disable_self_attentions is not None: + # should be a list of booleans, indicating whether to disable self-attention in TransformerBlocks or not + assert len(disable_self_attentions) == len(channel_mult) + if num_attention_blocks is not None: + assert len(num_attention_blocks) == len(self.num_res_blocks) + assert all(map(lambda i: self.num_res_blocks[i] >= num_attention_blocks[i], range(len(num_attention_blocks)))) + print(f"Constructor of UNetModel received num_attention_blocks={num_attention_blocks}. " + f"This option has LESS priority than attention_resolutions {attention_resolutions}, " + f"i.e., in cases where num_attention_blocks[i] > 0 but 2**i not in attention_resolutions, " + f"attention will still not be set.") + self.use_fp16 = use_fp16 + self.attention_resolutions = attention_resolutions + self.dropout = dropout + self.channel_mult = channel_mult + self.conv_resample = conv_resample + self.num_classes = num_classes + self.use_checkpoint = use_checkpoint + self.dtype = th.float16 if use_fp16 else th.float32 + self.num_heads = num_heads + self.num_head_channels = num_head_channels + self.num_heads_upsample = num_heads_upsample + self.predict_codebook_ids = n_embed is not None + + time_embed_dim = model_channels * 4 + self.time_embed = nn.Sequential( + linear(model_channels, time_embed_dim), + nn.SiLU(), + linear(time_embed_dim, time_embed_dim), + ) + + if self.num_classes is not None: + if isinstance(self.num_classes, int): + self.label_emb = nn.Embedding(num_classes, time_embed_dim) + elif self.num_classes == "continuous": + print("setting up linear c_adm embedding layer") + self.label_emb = nn.Linear(1, time_embed_dim) + else: + raise ValueError() + + self.input_blocks = nn.ModuleList( + [ + TimestepEmbedSequential( + conv_nd(dims, in_channels, model_channels, 3, padding=1) + ) + ] + ) + self._feature_size = model_channels + input_block_chans = [model_channels] + ch = model_channels + ds = 1 + for level, mult in enumerate(channel_mult): + for nr in range(self.num_res_blocks[level]): + layers = [ + ResBlock( + ch, + time_embed_dim, + dropout, + out_channels=mult * model_channels, + dims=dims, + use_checkpoint=use_checkpoint, + use_scale_shift_norm=use_scale_shift_norm, + ) + ] + ch = mult * model_channels + if ds in attention_resolutions: + if num_head_channels == -1: + dim_head = ch // num_heads + else: + num_heads = ch // num_head_channels + dim_head = num_head_channels + if legacy: + #num_heads = 1 + dim_head = ch // num_heads if use_spatial_transformer else num_head_channels + if exists(disable_self_attentions): + disabled_sa = disable_self_attentions[level] + else: + disabled_sa = False + + if not exists(num_attention_blocks) or nr < num_attention_blocks[level]: + layers.append( + AttentionBlock( + ch, + use_checkpoint=use_checkpoint, + num_heads=num_heads, + num_head_channels=dim_head, + use_new_attention_order=use_new_attention_order, + ) if not use_spatial_transformer else SpatialTransformer( + ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim, + disable_self_attn=disabled_sa, use_linear=use_linear_in_transformer, + use_checkpoint=use_checkpoint + ) + ) + self.input_blocks.append(TimestepEmbedSequential(*layers)) + self._feature_size += ch + input_block_chans.append(ch) + if level != len(channel_mult) - 1: + out_ch = ch + self.input_blocks.append( + TimestepEmbedSequential( + ResBlock( + ch, + time_embed_dim, + dropout, + out_channels=out_ch, + dims=dims, + use_checkpoint=use_checkpoint, + use_scale_shift_norm=use_scale_shift_norm, + down=True, + ) + if resblock_updown + else Downsample( + ch, conv_resample, dims=dims, out_channels=out_ch + ) + ) + ) + ch = out_ch + input_block_chans.append(ch) + ds *= 2 + self._feature_size += ch + + if num_head_channels == -1: + dim_head = ch // num_heads + else: + num_heads = ch // num_head_channels + dim_head = num_head_channels + if legacy: + #num_heads = 1 + dim_head = ch // num_heads if use_spatial_transformer else num_head_channels + self.middle_block = TimestepEmbedSequential( + ResBlock( + ch, + time_embed_dim, + dropout, + dims=dims, + use_checkpoint=use_checkpoint, + use_scale_shift_norm=use_scale_shift_norm, + ), + AttentionBlock( + ch, + use_checkpoint=use_checkpoint, + num_heads=num_heads, + num_head_channels=dim_head, + use_new_attention_order=use_new_attention_order, + ) if not use_spatial_transformer else SpatialTransformer( # always uses a self-attn + ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim, + disable_self_attn=disable_middle_self_attn, use_linear=use_linear_in_transformer, + use_checkpoint=use_checkpoint + ), + ResBlock( + ch, + time_embed_dim, + dropout, + dims=dims, + use_checkpoint=use_checkpoint, + use_scale_shift_norm=use_scale_shift_norm, + ), + ) + self._feature_size += ch + + self.output_blocks = nn.ModuleList([]) + for level, mult in list(enumerate(channel_mult))[::-1]: + for i in range(self.num_res_blocks[level] + 1): + ich = input_block_chans.pop() + layers = [ + ResBlock( + ch + ich, + time_embed_dim, + dropout, + out_channels=model_channels * mult, + dims=dims, + use_checkpoint=use_checkpoint, + use_scale_shift_norm=use_scale_shift_norm, + ) + ] + ch = model_channels * mult + if ds in attention_resolutions: + if num_head_channels == -1: + dim_head = ch // num_heads + else: + num_heads = ch // num_head_channels + dim_head = num_head_channels + if legacy: + #num_heads = 1 + dim_head = ch // num_heads if use_spatial_transformer else num_head_channels + if exists(disable_self_attentions): + disabled_sa = disable_self_attentions[level] + else: + disabled_sa = False + + if not exists(num_attention_blocks) or i < num_attention_blocks[level]: + layers.append( + AttentionBlock( + ch, + use_checkpoint=use_checkpoint, + num_heads=num_heads_upsample, + num_head_channels=dim_head, + use_new_attention_order=use_new_attention_order, + ) if not use_spatial_transformer else SpatialTransformer( + ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim, + disable_self_attn=disabled_sa, use_linear=use_linear_in_transformer, + use_checkpoint=use_checkpoint + ) + ) + if level and i == self.num_res_blocks[level]: + out_ch = ch + layers.append( + ResBlock( + ch, + time_embed_dim, + dropout, + out_channels=out_ch, + dims=dims, + use_checkpoint=use_checkpoint, + use_scale_shift_norm=use_scale_shift_norm, + up=True, + ) + if resblock_updown + else Upsample(ch, conv_resample, dims=dims, out_channels=out_ch) + ) + ds //= 2 + self.output_blocks.append(TimestepEmbedSequential(*layers)) + self._feature_size += ch + + self.out = nn.Sequential( + normalization(ch), + nn.SiLU(), + zero_module(conv_nd(dims, model_channels, out_channels, 3, padding=1)), + ) + if self.predict_codebook_ids: + self.id_predictor = nn.Sequential( + normalization(ch), + conv_nd(dims, model_channels, n_embed, 1), + #nn.LogSoftmax(dim=1) # change to cross_entropy and produce non-normalized logits + ) + + def convert_to_fp16(self): + """ + Convert the torso of the model to float16. + """ + self.input_blocks.apply(convert_module_to_f16) + self.middle_block.apply(convert_module_to_f16) + self.output_blocks.apply(convert_module_to_f16) + + def convert_to_fp32(self): + """ + Convert the torso of the model to float32. + """ + self.input_blocks.apply(convert_module_to_f32) + self.middle_block.apply(convert_module_to_f32) + self.output_blocks.apply(convert_module_to_f32) + + def forward(self, x, timesteps=None, context=None, y=None,**kwargs): + """ + Apply the model to an input batch. + :param x: an [N x C x ...] Tensor of inputs. + :param timesteps: a 1-D batch of timesteps. + :param context: conditioning plugged in via crossattn + :param y: an [N] Tensor of labels, if class-conditional. + :return: an [N x C x ...] Tensor of outputs. + """ + assert (y is not None) == ( + self.num_classes is not None + ), "must specify y if and only if the model is class-conditional" + hs = [] + t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False) + emb = self.time_embed(t_emb) + + if self.num_classes is not None: + assert y.shape[0] == x.shape[0] + emb = emb + self.label_emb(y) + + h = x.type(self.dtype) + for module in self.input_blocks: + h = module(h, emb, context) + hs.append(h) + h = self.middle_block(h, emb, context) + for module in self.output_blocks: + h = th.cat([h, hs.pop()], dim=1) + h = module(h, emb, context) + h = h.type(x.dtype) + if self.predict_codebook_ids: + return self.id_predictor(h) + else: + return self.out(h) diff --git a/py/iopaint/model/anytext/ldm/modules/diffusionmodules/upscaling.py b/py/iopaint/model/anytext/ldm/modules/diffusionmodules/upscaling.py new file mode 100644 index 0000000..5f92630 --- /dev/null +++ b/py/iopaint/model/anytext/ldm/modules/diffusionmodules/upscaling.py @@ -0,0 +1,81 @@ +import torch +import torch.nn as nn +import numpy as np +from functools import partial + +from iopaint.model.anytext.ldm.modules.diffusionmodules.util import extract_into_tensor, make_beta_schedule +from iopaint.model.anytext.ldm.util import default + + +class AbstractLowScaleModel(nn.Module): + # for concatenating a downsampled image to the latent representation + def __init__(self, noise_schedule_config=None): + super(AbstractLowScaleModel, self).__init__() + if noise_schedule_config is not None: + self.register_schedule(**noise_schedule_config) + + def register_schedule(self, beta_schedule="linear", timesteps=1000, + linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3): + betas = make_beta_schedule(beta_schedule, timesteps, linear_start=linear_start, linear_end=linear_end, + cosine_s=cosine_s) + alphas = 1. - betas + alphas_cumprod = np.cumprod(alphas, axis=0) + alphas_cumprod_prev = np.append(1., alphas_cumprod[:-1]) + + timesteps, = betas.shape + self.num_timesteps = int(timesteps) + self.linear_start = linear_start + self.linear_end = linear_end + assert alphas_cumprod.shape[0] == self.num_timesteps, 'alphas have to be defined for each timestep' + + to_torch = partial(torch.tensor, dtype=torch.float32) + + self.register_buffer('betas', to_torch(betas)) + self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod)) + self.register_buffer('alphas_cumprod_prev', to_torch(alphas_cumprod_prev)) + + # calculations for diffusion q(x_t | x_{t-1}) and others + self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod))) + self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod))) + self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod))) + self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod))) + self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod - 1))) + + def q_sample(self, x_start, t, noise=None): + noise = default(noise, lambda: torch.randn_like(x_start)) + return (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start + + extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape) * noise) + + def forward(self, x): + return x, None + + def decode(self, x): + return x + + +class SimpleImageConcat(AbstractLowScaleModel): + # no noise level conditioning + def __init__(self): + super(SimpleImageConcat, self).__init__(noise_schedule_config=None) + self.max_noise_level = 0 + + def forward(self, x): + # fix to constant noise level + return x, torch.zeros(x.shape[0], device=x.device).long() + + +class ImageConcatWithNoiseAugmentation(AbstractLowScaleModel): + def __init__(self, noise_schedule_config, max_noise_level=1000, to_cuda=False): + super().__init__(noise_schedule_config=noise_schedule_config) + self.max_noise_level = max_noise_level + + def forward(self, x, noise_level=None): + if noise_level is None: + noise_level = torch.randint(0, self.max_noise_level, (x.shape[0],), device=x.device).long() + else: + assert isinstance(noise_level, torch.Tensor) + z = self.q_sample(x, noise_level) + return z, noise_level + + + diff --git a/py/iopaint/model/anytext/ldm/modules/diffusionmodules/util.py b/py/iopaint/model/anytext/ldm/modules/diffusionmodules/util.py new file mode 100644 index 0000000..da29c72 --- /dev/null +++ b/py/iopaint/model/anytext/ldm/modules/diffusionmodules/util.py @@ -0,0 +1,271 @@ +# adopted from +# https://github.com/openai/improved-diffusion/blob/main/improved_diffusion/gaussian_diffusion.py +# and +# https://github.com/lucidrains/denoising-diffusion-pytorch/blob/7706bdfc6f527f58d33f84b7b522e61e6e3164b3/denoising_diffusion_pytorch/denoising_diffusion_pytorch.py +# and +# https://github.com/openai/guided-diffusion/blob/0ba878e517b276c45d1195eb29f6f5f72659a05b/guided_diffusion/nn.py +# +# thanks! + + +import os +import math +import torch +import torch.nn as nn +import numpy as np +from einops import repeat + +from iopaint.model.anytext.ldm.util import instantiate_from_config + + +def make_beta_schedule(schedule, n_timestep, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3): + if schedule == "linear": + betas = ( + torch.linspace(linear_start ** 0.5, linear_end ** 0.5, n_timestep, dtype=torch.float64) ** 2 + ) + + elif schedule == "cosine": + timesteps = ( + torch.arange(n_timestep + 1, dtype=torch.float64) / n_timestep + cosine_s + ) + alphas = timesteps / (1 + cosine_s) * np.pi / 2 + alphas = torch.cos(alphas).pow(2) + alphas = alphas / alphas[0] + betas = 1 - alphas[1:] / alphas[:-1] + betas = np.clip(betas, a_min=0, a_max=0.999) + + elif schedule == "sqrt_linear": + betas = torch.linspace(linear_start, linear_end, n_timestep, dtype=torch.float64) + elif schedule == "sqrt": + betas = torch.linspace(linear_start, linear_end, n_timestep, dtype=torch.float64) ** 0.5 + else: + raise ValueError(f"schedule '{schedule}' unknown.") + return betas.numpy() + + +def make_ddim_timesteps(ddim_discr_method, num_ddim_timesteps, num_ddpm_timesteps, verbose=True): + if ddim_discr_method == 'uniform': + c = num_ddpm_timesteps // num_ddim_timesteps + ddim_timesteps = np.asarray(list(range(0, num_ddpm_timesteps, c))) + elif ddim_discr_method == 'quad': + ddim_timesteps = ((np.linspace(0, np.sqrt(num_ddpm_timesteps * .8), num_ddim_timesteps)) ** 2).astype(int) + else: + raise NotImplementedError(f'There is no ddim discretization method called "{ddim_discr_method}"') + + # assert ddim_timesteps.shape[0] == num_ddim_timesteps + # add one to get the final alpha values right (the ones from first scale to data during sampling) + steps_out = ddim_timesteps + 1 + if verbose: + print(f'Selected timesteps for ddim sampler: {steps_out}') + return steps_out + + +def make_ddim_sampling_parameters(alphacums, ddim_timesteps, eta, verbose=True): + # select alphas for computing the variance schedule + alphas = alphacums[ddim_timesteps] + alphas_prev = np.asarray([alphacums[0]] + alphacums[ddim_timesteps[:-1]].tolist()) + + # according the the formula provided in https://arxiv.org/abs/2010.02502 + sigmas = eta * np.sqrt((1 - alphas_prev) / (1 - alphas) * (1 - alphas / alphas_prev)) + if verbose: + print(f'Selected alphas for ddim sampler: a_t: {alphas}; a_(t-1): {alphas_prev}') + print(f'For the chosen value of eta, which is {eta}, ' + f'this results in the following sigma_t schedule for ddim sampler {sigmas}') + return sigmas.to(torch.float32), alphas.to(torch.float32), alphas_prev.astype(np.float32) + + +def betas_for_alpha_bar(num_diffusion_timesteps, alpha_bar, max_beta=0.999): + """ + Create a beta schedule that discretizes the given alpha_t_bar function, + which defines the cumulative product of (1-beta) over time from t = [0,1]. + :param num_diffusion_timesteps: the number of betas to produce. + :param alpha_bar: a lambda that takes an argument t from 0 to 1 and + produces the cumulative product of (1-beta) up to that + part of the diffusion process. + :param max_beta: the maximum beta to use; use values lower than 1 to + prevent singularities. + """ + betas = [] + for i in range(num_diffusion_timesteps): + t1 = i / num_diffusion_timesteps + t2 = (i + 1) / num_diffusion_timesteps + betas.append(min(1 - alpha_bar(t2) / alpha_bar(t1), max_beta)) + return np.array(betas) + + +def extract_into_tensor(a, t, x_shape): + b, *_ = t.shape + out = a.gather(-1, t) + return out.reshape(b, *((1,) * (len(x_shape) - 1))) + + +def checkpoint(func, inputs, params, flag): + """ + Evaluate a function without caching intermediate activations, allowing for + reduced memory at the expense of extra compute in the backward pass. + :param func: the function to evaluate. + :param inputs: the argument sequence to pass to `func`. + :param params: a sequence of parameters `func` depends on but does not + explicitly take as arguments. + :param flag: if False, disable gradient checkpointing. + """ + if flag: + args = tuple(inputs) + tuple(params) + return CheckpointFunction.apply(func, len(inputs), *args) + else: + return func(*inputs) + + +class CheckpointFunction(torch.autograd.Function): + @staticmethod + def forward(ctx, run_function, length, *args): + ctx.run_function = run_function + ctx.input_tensors = list(args[:length]) + ctx.input_params = list(args[length:]) + ctx.gpu_autocast_kwargs = {"enabled": torch.is_autocast_enabled(), + "dtype": torch.get_autocast_gpu_dtype(), + "cache_enabled": torch.is_autocast_cache_enabled()} + with torch.no_grad(): + output_tensors = ctx.run_function(*ctx.input_tensors) + return output_tensors + + @staticmethod + def backward(ctx, *output_grads): + ctx.input_tensors = [x.detach().requires_grad_(True) for x in ctx.input_tensors] + with torch.enable_grad(), \ + torch.cuda.amp.autocast(**ctx.gpu_autocast_kwargs): + # Fixes a bug where the first op in run_function modifies the + # Tensor storage in place, which is not allowed for detach()'d + # Tensors. + shallow_copies = [x.view_as(x) for x in ctx.input_tensors] + output_tensors = ctx.run_function(*shallow_copies) + input_grads = torch.autograd.grad( + output_tensors, + ctx.input_tensors + ctx.input_params, + output_grads, + allow_unused=True, + ) + del ctx.input_tensors + del ctx.input_params + del output_tensors + return (None, None) + input_grads + + +def timestep_embedding(timesteps, dim, max_period=10000, repeat_only=False): + """ + Create sinusoidal timestep embeddings. + :param timesteps: a 1-D Tensor of N indices, one per batch element. + These may be fractional. + :param dim: the dimension of the output. + :param max_period: controls the minimum frequency of the embeddings. + :return: an [N x dim] Tensor of positional embeddings. + """ + if not repeat_only: + half = dim // 2 + freqs = torch.exp( + -math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half + ).to(device=timesteps.device) + args = timesteps[:, None].float() * freqs[None] + embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1) + if dim % 2: + embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1) + else: + embedding = repeat(timesteps, 'b -> b d', d=dim) + return embedding + + +def zero_module(module): + """ + Zero out the parameters of a module and return it. + """ + for p in module.parameters(): + p.detach().zero_() + return module + + +def scale_module(module, scale): + """ + Scale the parameters of a module and return it. + """ + for p in module.parameters(): + p.detach().mul_(scale) + return module + + +def mean_flat(tensor): + """ + Take the mean over all non-batch dimensions. + """ + return tensor.mean(dim=list(range(1, len(tensor.shape)))) + + +def normalization(channels): + """ + Make a standard normalization layer. + :param channels: number of input channels. + :return: an nn.Module for normalization. + """ + return GroupNorm32(32, channels) + + +# PyTorch 1.7 has SiLU, but we support PyTorch 1.5. +class SiLU(nn.Module): + def forward(self, x): + return x * torch.sigmoid(x) + + +class GroupNorm32(nn.GroupNorm): + def forward(self, x): + # return super().forward(x.float()).type(x.dtype) + return super().forward(x).type(x.dtype) + +def conv_nd(dims, *args, **kwargs): + """ + Create a 1D, 2D, or 3D convolution module. + """ + if dims == 1: + return nn.Conv1d(*args, **kwargs) + elif dims == 2: + return nn.Conv2d(*args, **kwargs) + elif dims == 3: + return nn.Conv3d(*args, **kwargs) + raise ValueError(f"unsupported dimensions: {dims}") + + +def linear(*args, **kwargs): + """ + Create a linear module. + """ + return nn.Linear(*args, **kwargs) + + +def avg_pool_nd(dims, *args, **kwargs): + """ + Create a 1D, 2D, or 3D average pooling module. + """ + if dims == 1: + return nn.AvgPool1d(*args, **kwargs) + elif dims == 2: + return nn.AvgPool2d(*args, **kwargs) + elif dims == 3: + return nn.AvgPool3d(*args, **kwargs) + raise ValueError(f"unsupported dimensions: {dims}") + + +class HybridConditioner(nn.Module): + + def __init__(self, c_concat_config, c_crossattn_config): + super().__init__() + self.concat_conditioner = instantiate_from_config(c_concat_config) + self.crossattn_conditioner = instantiate_from_config(c_crossattn_config) + + def forward(self, c_concat, c_crossattn): + c_concat = self.concat_conditioner(c_concat) + c_crossattn = self.crossattn_conditioner(c_crossattn) + return {'c_concat': [c_concat], 'c_crossattn': [c_crossattn]} + + +def noise_like(shape, device, repeat=False): + repeat_noise = lambda: torch.randn((1, *shape[1:]), device=device).repeat(shape[0], *((1,) * (len(shape) - 1))) + noise = lambda: torch.randn(shape, device=device) + return repeat_noise() if repeat else noise() \ No newline at end of file diff --git a/py/iopaint/model/anytext/ldm/modules/distributions/__init__.py b/py/iopaint/model/anytext/ldm/modules/distributions/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/py/iopaint/model/anytext/ldm/modules/distributions/distributions.py b/py/iopaint/model/anytext/ldm/modules/distributions/distributions.py new file mode 100644 index 0000000..f2b8ef9 --- /dev/null +++ b/py/iopaint/model/anytext/ldm/modules/distributions/distributions.py @@ -0,0 +1,92 @@ +import torch +import numpy as np + + +class AbstractDistribution: + def sample(self): + raise NotImplementedError() + + def mode(self): + raise NotImplementedError() + + +class DiracDistribution(AbstractDistribution): + def __init__(self, value): + self.value = value + + def sample(self): + return self.value + + def mode(self): + return self.value + + +class DiagonalGaussianDistribution(object): + def __init__(self, parameters, deterministic=False): + self.parameters = parameters + self.mean, self.logvar = torch.chunk(parameters, 2, dim=1) + self.logvar = torch.clamp(self.logvar, -30.0, 20.0) + self.deterministic = deterministic + self.std = torch.exp(0.5 * self.logvar) + self.var = torch.exp(self.logvar) + if self.deterministic: + self.var = self.std = torch.zeros_like(self.mean).to(device=self.parameters.device) + + def sample(self): + x = self.mean + self.std * torch.randn(self.mean.shape).to(device=self.parameters.device) + return x + + def kl(self, other=None): + if self.deterministic: + return torch.Tensor([0.]) + else: + if other is None: + return 0.5 * torch.sum(torch.pow(self.mean, 2) + + self.var - 1.0 - self.logvar, + dim=[1, 2, 3]) + else: + return 0.5 * torch.sum( + torch.pow(self.mean - other.mean, 2) / other.var + + self.var / other.var - 1.0 - self.logvar + other.logvar, + dim=[1, 2, 3]) + + def nll(self, sample, dims=[1,2,3]): + if self.deterministic: + return torch.Tensor([0.]) + logtwopi = np.log(2.0 * np.pi) + return 0.5 * torch.sum( + logtwopi + self.logvar + torch.pow(sample - self.mean, 2) / self.var, + dim=dims) + + def mode(self): + return self.mean + + +def normal_kl(mean1, logvar1, mean2, logvar2): + """ + source: https://github.com/openai/guided-diffusion/blob/27c20a8fab9cb472df5d6bdd6c8d11c8f430b924/guided_diffusion/losses.py#L12 + Compute the KL divergence between two gaussians. + Shapes are automatically broadcasted, so batches can be compared to + scalars, among other use cases. + """ + tensor = None + for obj in (mean1, logvar1, mean2, logvar2): + if isinstance(obj, torch.Tensor): + tensor = obj + break + assert tensor is not None, "at least one argument must be a Tensor" + + # Force variances to be Tensors. Broadcasting helps convert scalars to + # Tensors, but it does not work for torch.exp(). + logvar1, logvar2 = [ + x if isinstance(x, torch.Tensor) else torch.tensor(x).to(tensor) + for x in (logvar1, logvar2) + ] + + return 0.5 * ( + -1.0 + + logvar2 + - logvar1 + + torch.exp(logvar1 - logvar2) + + ((mean1 - mean2) ** 2) * torch.exp(-logvar2) + ) diff --git a/py/iopaint/model/anytext/ldm/modules/ema.py b/py/iopaint/model/anytext/ldm/modules/ema.py new file mode 100644 index 0000000..bded250 --- /dev/null +++ b/py/iopaint/model/anytext/ldm/modules/ema.py @@ -0,0 +1,80 @@ +import torch +from torch import nn + + +class LitEma(nn.Module): + def __init__(self, model, decay=0.9999, use_num_upates=True): + super().__init__() + if decay < 0.0 or decay > 1.0: + raise ValueError('Decay must be between 0 and 1') + + self.m_name2s_name = {} + self.register_buffer('decay', torch.tensor(decay, dtype=torch.float32)) + self.register_buffer('num_updates', torch.tensor(0, dtype=torch.int) if use_num_upates + else torch.tensor(-1, dtype=torch.int)) + + for name, p in model.named_parameters(): + if p.requires_grad: + # remove as '.'-character is not allowed in buffers + s_name = name.replace('.', '') + self.m_name2s_name.update({name: s_name}) + self.register_buffer(s_name, p.clone().detach().data) + + self.collected_params = [] + + def reset_num_updates(self): + del self.num_updates + self.register_buffer('num_updates', torch.tensor(0, dtype=torch.int)) + + def forward(self, model): + decay = self.decay + + if self.num_updates >= 0: + self.num_updates += 1 + decay = min(self.decay, (1 + self.num_updates) / (10 + self.num_updates)) + + one_minus_decay = 1.0 - decay + + with torch.no_grad(): + m_param = dict(model.named_parameters()) + shadow_params = dict(self.named_buffers()) + + for key in m_param: + if m_param[key].requires_grad: + sname = self.m_name2s_name[key] + shadow_params[sname] = shadow_params[sname].type_as(m_param[key]) + shadow_params[sname].sub_(one_minus_decay * (shadow_params[sname] - m_param[key])) + else: + assert not key in self.m_name2s_name + + def copy_to(self, model): + m_param = dict(model.named_parameters()) + shadow_params = dict(self.named_buffers()) + for key in m_param: + if m_param[key].requires_grad: + m_param[key].data.copy_(shadow_params[self.m_name2s_name[key]].data) + else: + assert not key in self.m_name2s_name + + def store(self, parameters): + """ + Save the current parameters for restoring later. + Args: + parameters: Iterable of `torch.nn.Parameter`; the parameters to be + temporarily stored. + """ + self.collected_params = [param.clone() for param in parameters] + + def restore(self, parameters): + """ + Restore the parameters stored with the `store` method. + Useful to validate the model with EMA parameters without affecting the + original optimization process. Store the parameters before the + `copy_to` method. After validation (or model saving), use this to + restore the former parameters. + Args: + parameters: Iterable of `torch.nn.Parameter`; the parameters to be + updated with the stored parameters. + """ + for c_param, param in zip(self.collected_params, parameters): + param.data.copy_(c_param.data) diff --git a/py/iopaint/model/anytext/ldm/modules/encoders/__init__.py b/py/iopaint/model/anytext/ldm/modules/encoders/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/py/iopaint/model/anytext/ldm/modules/encoders/modules.py b/py/iopaint/model/anytext/ldm/modules/encoders/modules.py new file mode 100644 index 0000000..ceac395 --- /dev/null +++ b/py/iopaint/model/anytext/ldm/modules/encoders/modules.py @@ -0,0 +1,411 @@ +import torch +import torch.nn as nn +from torch.utils.checkpoint import checkpoint + +from transformers import ( + T5Tokenizer, + T5EncoderModel, + CLIPTokenizer, + CLIPTextModel, + AutoProcessor, + CLIPVisionModelWithProjection, +) + +from iopaint.model.anytext.ldm.util import count_params + + +def _expand_mask(mask, dtype, tgt_len=None): + """ + Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`. + """ + bsz, src_len = mask.size() + tgt_len = tgt_len if tgt_len is not None else src_len + + expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype) + + inverted_mask = 1.0 - expanded_mask + + return inverted_mask.masked_fill( + inverted_mask.to(torch.bool), torch.finfo(dtype).min + ) + + +def _build_causal_attention_mask(bsz, seq_len, dtype): + # lazily create causal attention mask, with full attention between the vision tokens + # pytorch uses additive attention mask; fill with -inf + mask = torch.empty(bsz, seq_len, seq_len, dtype=dtype) + mask.fill_(torch.tensor(torch.finfo(dtype).min)) + mask.triu_(1) # zero out the lower diagonal + mask = mask.unsqueeze(1) # expand mask + return mask + + +class AbstractEncoder(nn.Module): + def __init__(self): + super().__init__() + + def encode(self, *args, **kwargs): + raise NotImplementedError + + +class IdentityEncoder(AbstractEncoder): + def encode(self, x): + return x + + +class ClassEmbedder(nn.Module): + def __init__(self, embed_dim, n_classes=1000, key="class", ucg_rate=0.1): + super().__init__() + self.key = key + self.embedding = nn.Embedding(n_classes, embed_dim) + self.n_classes = n_classes + self.ucg_rate = ucg_rate + + def forward(self, batch, key=None, disable_dropout=False): + if key is None: + key = self.key + # this is for use in crossattn + c = batch[key][:, None] + if self.ucg_rate > 0.0 and not disable_dropout: + mask = 1.0 - torch.bernoulli(torch.ones_like(c) * self.ucg_rate) + c = mask * c + (1 - mask) * torch.ones_like(c) * (self.n_classes - 1) + c = c.long() + c = self.embedding(c) + return c + + def get_unconditional_conditioning(self, bs, device="cuda"): + uc_class = ( + self.n_classes - 1 + ) # 1000 classes --> 0 ... 999, one extra class for ucg (class 1000) + uc = torch.ones((bs,), device=device) * uc_class + uc = {self.key: uc} + return uc + + +def disabled_train(self, mode=True): + """Overwrite model.train with this function to make sure train/eval mode + does not change anymore.""" + return self + + +class FrozenT5Embedder(AbstractEncoder): + """Uses the T5 transformer encoder for text""" + + def __init__( + self, version="google/t5-v1_1-large", device="cuda", max_length=77, freeze=True + ): # others are google/t5-v1_1-xl and google/t5-v1_1-xxl + super().__init__() + self.tokenizer = T5Tokenizer.from_pretrained(version) + self.transformer = T5EncoderModel.from_pretrained(version) + self.device = device + self.max_length = max_length # TODO: typical value? + if freeze: + self.freeze() + + def freeze(self): + self.transformer = self.transformer.eval() + # self.train = disabled_train + for param in self.parameters(): + param.requires_grad = False + + def forward(self, text): + batch_encoding = self.tokenizer( + text, + truncation=True, + max_length=self.max_length, + return_length=True, + return_overflowing_tokens=False, + padding="max_length", + return_tensors="pt", + ) + tokens = batch_encoding["input_ids"].to(self.device) + outputs = self.transformer(input_ids=tokens) + + z = outputs.last_hidden_state + return z + + def encode(self, text): + return self(text) + + +class FrozenCLIPEmbedder(AbstractEncoder): + """Uses the CLIP transformer encoder for text (from huggingface)""" + + LAYERS = ["last", "pooled", "hidden"] + + def __init__( + self, + version="openai/clip-vit-large-patch14", + device="cuda", + max_length=77, + freeze=True, + layer="last", + layer_idx=None, + ): # clip-vit-base-patch32 + super().__init__() + assert layer in self.LAYERS + self.tokenizer = CLIPTokenizer.from_pretrained(version) + self.transformer = CLIPTextModel.from_pretrained(version) + self.device = device + self.max_length = max_length + if freeze: + self.freeze() + self.layer = layer + self.layer_idx = layer_idx + if layer == "hidden": + assert layer_idx is not None + assert 0 <= abs(layer_idx) <= 12 + + def freeze(self): + self.transformer = self.transformer.eval() + # self.train = disabled_train + for param in self.parameters(): + param.requires_grad = False + + def forward(self, text): + batch_encoding = self.tokenizer( + text, + truncation=True, + max_length=self.max_length, + return_length=True, + return_overflowing_tokens=False, + padding="max_length", + return_tensors="pt", + ) + tokens = batch_encoding["input_ids"].to(self.device) + outputs = self.transformer( + input_ids=tokens, output_hidden_states=self.layer == "hidden" + ) + if self.layer == "last": + z = outputs.last_hidden_state + elif self.layer == "pooled": + z = outputs.pooler_output[:, None, :] + else: + z = outputs.hidden_states[self.layer_idx] + return z + + def encode(self, text): + return self(text) + + +class FrozenCLIPT5Encoder(AbstractEncoder): + def __init__( + self, + clip_version="openai/clip-vit-large-patch14", + t5_version="google/t5-v1_1-xl", + device="cuda", + clip_max_length=77, + t5_max_length=77, + ): + super().__init__() + self.clip_encoder = FrozenCLIPEmbedder( + clip_version, device, max_length=clip_max_length + ) + self.t5_encoder = FrozenT5Embedder(t5_version, device, max_length=t5_max_length) + print( + f"{self.clip_encoder.__class__.__name__} has {count_params(self.clip_encoder)*1.e-6:.2f} M parameters, " + f"{self.t5_encoder.__class__.__name__} comes with {count_params(self.t5_encoder)*1.e-6:.2f} M params." + ) + + def encode(self, text): + return self(text) + + def forward(self, text): + clip_z = self.clip_encoder.encode(text) + t5_z = self.t5_encoder.encode(text) + return [clip_z, t5_z] + + +class FrozenCLIPEmbedderT3(AbstractEncoder): + """Uses the CLIP transformer encoder for text (from Hugging Face)""" + + def __init__( + self, + version="openai/clip-vit-large-patch14", + device="cuda", + max_length=77, + freeze=True, + use_vision=False, + ): + super().__init__() + self.tokenizer = CLIPTokenizer.from_pretrained(version) + self.transformer = CLIPTextModel.from_pretrained(version) + if use_vision: + self.vit = CLIPVisionModelWithProjection.from_pretrained(version) + self.processor = AutoProcessor.from_pretrained(version) + self.device = device + self.max_length = max_length + if freeze: + self.freeze() + + def embedding_forward( + self, + input_ids=None, + position_ids=None, + inputs_embeds=None, + embedding_manager=None, + ): + seq_length = ( + input_ids.shape[-1] + if input_ids is not None + else inputs_embeds.shape[-2] + ) + if position_ids is None: + position_ids = self.position_ids[:, :seq_length] + if inputs_embeds is None: + inputs_embeds = self.token_embedding(input_ids) + if embedding_manager is not None: + inputs_embeds = embedding_manager(input_ids, inputs_embeds) + position_embeddings = self.position_embedding(position_ids) + embeddings = inputs_embeds + position_embeddings + return embeddings + + self.transformer.text_model.embeddings.forward = embedding_forward.__get__( + self.transformer.text_model.embeddings + ) + + def encoder_forward( + self, + inputs_embeds, + attention_mask=None, + causal_attention_mask=None, + output_attentions=None, + output_hidden_states=None, + return_dict=None, + ): + output_attentions = ( + output_attentions + if output_attentions is not None + else self.config.output_attentions + ) + output_hidden_states = ( + output_hidden_states + if output_hidden_states is not None + else self.config.output_hidden_states + ) + return_dict = ( + return_dict if return_dict is not None else self.config.use_return_dict + ) + encoder_states = () if output_hidden_states else None + all_attentions = () if output_attentions else None + hidden_states = inputs_embeds + for idx, encoder_layer in enumerate(self.layers): + if output_hidden_states: + encoder_states = encoder_states + (hidden_states,) + layer_outputs = encoder_layer( + hidden_states, + attention_mask, + causal_attention_mask, + output_attentions=output_attentions, + ) + hidden_states = layer_outputs[0] + if output_attentions: + all_attentions = all_attentions + (layer_outputs[1],) + if output_hidden_states: + encoder_states = encoder_states + (hidden_states,) + return hidden_states + + self.transformer.text_model.encoder.forward = encoder_forward.__get__( + self.transformer.text_model.encoder + ) + + def text_encoder_forward( + self, + input_ids=None, + attention_mask=None, + position_ids=None, + output_attentions=None, + output_hidden_states=None, + return_dict=None, + embedding_manager=None, + ): + output_attentions = ( + output_attentions + if output_attentions is not None + else self.config.output_attentions + ) + output_hidden_states = ( + output_hidden_states + if output_hidden_states is not None + else self.config.output_hidden_states + ) + return_dict = ( + return_dict if return_dict is not None else self.config.use_return_dict + ) + if input_ids is None: + raise ValueError("You have to specify either input_ids") + input_shape = input_ids.size() + input_ids = input_ids.view(-1, input_shape[-1]) + hidden_states = self.embeddings( + input_ids=input_ids, + position_ids=position_ids, + embedding_manager=embedding_manager, + ) + bsz, seq_len = input_shape + # CLIP's text model uses causal mask, prepare it here. + # https://github.com/openai/CLIP/blob/cfcffb90e69f37bf2ff1e988237a0fbe41f33c04/clip/model.py#L324 + causal_attention_mask = _build_causal_attention_mask( + bsz, seq_len, hidden_states.dtype + ).to(hidden_states.device) + # expand attention_mask + if attention_mask is not None: + # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len] + attention_mask = _expand_mask(attention_mask, hidden_states.dtype) + last_hidden_state = self.encoder( + inputs_embeds=hidden_states, + attention_mask=attention_mask, + causal_attention_mask=causal_attention_mask, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + last_hidden_state = self.final_layer_norm(last_hidden_state) + return last_hidden_state + + self.transformer.text_model.forward = text_encoder_forward.__get__( + self.transformer.text_model + ) + + def transformer_forward( + self, + input_ids=None, + attention_mask=None, + position_ids=None, + output_attentions=None, + output_hidden_states=None, + return_dict=None, + embedding_manager=None, + ): + return self.text_model( + input_ids=input_ids, + attention_mask=attention_mask, + position_ids=position_ids, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + embedding_manager=embedding_manager, + ) + + self.transformer.forward = transformer_forward.__get__(self.transformer) + + def freeze(self): + self.transformer = self.transformer.eval() + for param in self.parameters(): + param.requires_grad = False + + def forward(self, text, **kwargs): + batch_encoding = self.tokenizer( + text, + truncation=True, + max_length=self.max_length, + return_length=True, + return_overflowing_tokens=False, + padding="max_length", + return_tensors="pt", + ) + tokens = batch_encoding["input_ids"].to(self.device) + z = self.transformer(input_ids=tokens, **kwargs) + return z + + def encode(self, text, **kwargs): + return self(text, **kwargs) diff --git a/py/iopaint/model/anytext/ldm/util.py b/py/iopaint/model/anytext/ldm/util.py new file mode 100644 index 0000000..d456a86 --- /dev/null +++ b/py/iopaint/model/anytext/ldm/util.py @@ -0,0 +1,197 @@ +import importlib + +import torch +from torch import optim +import numpy as np + +from inspect import isfunction +from PIL import Image, ImageDraw, ImageFont + + +def log_txt_as_img(wh, xc, size=10): + # wh a tuple of (width, height) + # xc a list of captions to plot + b = len(xc) + txts = list() + for bi in range(b): + txt = Image.new("RGB", wh, color="white") + draw = ImageDraw.Draw(txt) + font = ImageFont.truetype('font/Arial_Unicode.ttf', size=size) + nc = int(32 * (wh[0] / 256)) + 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) + except UnicodeEncodeError: + print("Cant encode string for logging. Skipping.") + + txt = np.array(txt).transpose(2, 0, 1) / 127.5 - 1.0 + txts.append(txt) + txts = np.stack(txts) + txts = torch.tensor(txts) + return txts + + +def ismap(x): + if not isinstance(x, torch.Tensor): + return False + return (len(x.shape) == 4) and (x.shape[1] > 3) + + +def isimage(x): + if not isinstance(x,torch.Tensor): + return False + return (len(x.shape) == 4) and (x.shape[1] == 3 or x.shape[1] == 1) + + +def exists(x): + return x is not None + + +def default(val, d): + if exists(val): + return val + return d() if isfunction(d) else d + + +def mean_flat(tensor): + """ + https://github.com/openai/guided-diffusion/blob/27c20a8fab9cb472df5d6bdd6c8d11c8f430b924/guided_diffusion/nn.py#L86 + Take the mean over all non-batch dimensions. + """ + return tensor.mean(dim=list(range(1, len(tensor.shape)))) + + +def count_params(model, verbose=False): + total_params = sum(p.numel() for p in model.parameters()) + if verbose: + print(f"{model.__class__.__name__} has {total_params*1.e-6:.2f} M params.") + return total_params + + +def instantiate_from_config(config, **kwargs): + if "target" not in config: + if config == '__is_first_stage__': + return None + elif config == "__is_unconditional__": + return None + raise KeyError("Expected key `target` to instantiate.") + return get_obj_from_str(config["target"])(**config.get("params", dict()), **kwargs) + + +def get_obj_from_str(string, reload=False): + module, cls = string.rsplit(".", 1) + if reload: + module_imp = importlib.import_module(module) + importlib.reload(module_imp) + return getattr(importlib.import_module(module, package=None), cls) + + +class AdamWwithEMAandWings(optim.Optimizer): + # credit to https://gist.github.com/crowsonkb/65f7265353f403714fce3b2595e0b298 + def __init__(self, params, lr=1.e-3, betas=(0.9, 0.999), eps=1.e-8, # TODO: check hyperparameters before using + weight_decay=1.e-2, amsgrad=False, ema_decay=0.9999, # ema decay to match previous code + ema_power=1., param_names=()): + """AdamW that saves EMA versions of the parameters.""" + if not 0.0 <= lr: + raise ValueError("Invalid learning rate: {}".format(lr)) + if not 0.0 <= eps: + raise ValueError("Invalid epsilon value: {}".format(eps)) + if not 0.0 <= betas[0] < 1.0: + raise ValueError("Invalid beta parameter at index 0: {}".format(betas[0])) + if not 0.0 <= betas[1] < 1.0: + raise ValueError("Invalid beta parameter at index 1: {}".format(betas[1])) + if not 0.0 <= weight_decay: + raise ValueError("Invalid weight_decay value: {}".format(weight_decay)) + if not 0.0 <= ema_decay <= 1.0: + raise ValueError("Invalid ema_decay value: {}".format(ema_decay)) + defaults = dict(lr=lr, betas=betas, eps=eps, + weight_decay=weight_decay, amsgrad=amsgrad, ema_decay=ema_decay, + ema_power=ema_power, param_names=param_names) + super().__init__(params, defaults) + + def __setstate__(self, state): + super().__setstate__(state) + for group in self.param_groups: + group.setdefault('amsgrad', False) + + @torch.no_grad() + def step(self, closure=None): + """Performs a single optimization step. + Args: + closure (callable, optional): A closure that reevaluates the model + and returns the loss. + """ + loss = None + if closure is not None: + with torch.enable_grad(): + loss = closure() + + for group in self.param_groups: + params_with_grad = [] + grads = [] + exp_avgs = [] + exp_avg_sqs = [] + ema_params_with_grad = [] + state_sums = [] + max_exp_avg_sqs = [] + state_steps = [] + amsgrad = group['amsgrad'] + beta1, beta2 = group['betas'] + ema_decay = group['ema_decay'] + ema_power = group['ema_power'] + + for p in group['params']: + if p.grad is None: + continue + params_with_grad.append(p) + if p.grad.is_sparse: + raise RuntimeError('AdamW does not support sparse gradients') + grads.append(p.grad) + + state = self.state[p] + + # State initialization + if len(state) == 0: + state['step'] = 0 + # Exponential moving average of gradient values + state['exp_avg'] = torch.zeros_like(p, memory_format=torch.preserve_format) + # Exponential moving average of squared gradient values + state['exp_avg_sq'] = torch.zeros_like(p, memory_format=torch.preserve_format) + if amsgrad: + # Maintains max of all exp. moving avg. of sq. grad. values + state['max_exp_avg_sq'] = torch.zeros_like(p, memory_format=torch.preserve_format) + # Exponential moving average of parameter values + state['param_exp_avg'] = p.detach().float().clone() + + exp_avgs.append(state['exp_avg']) + exp_avg_sqs.append(state['exp_avg_sq']) + ema_params_with_grad.append(state['param_exp_avg']) + + if amsgrad: + max_exp_avg_sqs.append(state['max_exp_avg_sq']) + + # update the steps for each param group update + state['step'] += 1 + # record the step after step update + state_steps.append(state['step']) + + optim._functional.adamw(params_with_grad, + grads, + exp_avgs, + exp_avg_sqs, + max_exp_avg_sqs, + state_steps, + amsgrad=amsgrad, + beta1=beta1, + beta2=beta2, + lr=group['lr'], + weight_decay=group['weight_decay'], + eps=group['eps'], + maximize=False) + + cur_ema_decay = min(ema_decay, 1 - state['step'] ** -ema_power) + for param, ema_param in zip(params_with_grad, ema_params_with_grad): + ema_param.mul_(cur_ema_decay).add_(param.float(), alpha=1 - cur_ema_decay) + + return loss \ No newline at end of file diff --git a/py/iopaint/model/anytext/main.py b/py/iopaint/model/anytext/main.py new file mode 100644 index 0000000..f7b2d2e --- /dev/null +++ b/py/iopaint/model/anytext/main.py @@ -0,0 +1,45 @@ +import cv2 +import os + +from anytext_pipeline import AnyTextPipeline +from utils import save_images + +seed = 66273235 +# seed_everything(seed) + +pipe = AnyTextPipeline( + ckpt_path="/Users/cwq/code/github/IOPaint/iopaint/model/anytext/anytext_v1.1_fp16.ckpt", + font_path="/Users/cwq/code/github/AnyText/anytext/font/SourceHanSansSC-Medium.otf", + use_fp16=False, + device="mps", +) + +img_save_folder = "SaveImages" +rgb_image = cv2.imread( + "/Users/cwq/code/github/AnyText/anytext/example_images/ref7.jpg" +)[..., ::-1] + +masked_image = cv2.imread( + "/Users/cwq/code/github/AnyText/anytext/example_images/edit7.png" +)[..., ::-1] + +rgb_image = cv2.resize(rgb_image, (512, 512)) +masked_image = cv2.resize(masked_image, (512, 512)) + +# results: list of rgb ndarray +results, rtn_code, rtn_warning = pipe( + prompt='A cake with colorful characters that reads "EVERYDAY", best quality, extremely detailed,4k, HD, supper legible text, clear text edges, clear strokes, neat writing, no watermarks', + negative_prompt="low-res, bad anatomy, extra digit, fewer digits, cropped, worst quality, low quality, watermark, unreadable text, messy words, distorted text, disorganized writing, advertising picture", + image=rgb_image, + masked_image=masked_image, + num_inference_steps=20, + strength=1.0, + guidance_scale=9.0, + height=rgb_image.shape[0], + width=rgb_image.shape[1], + seed=seed, + sort_priority="y", +) +if rtn_code >= 0: + save_images(results, img_save_folder) + print(f"Done, result images are saved in: {img_save_folder}") diff --git a/py/iopaint/model/anytext/ocr_recog/RNN.py b/py/iopaint/model/anytext/ocr_recog/RNN.py new file mode 100644 index 0000000..cf16855 --- /dev/null +++ b/py/iopaint/model/anytext/ocr_recog/RNN.py @@ -0,0 +1,210 @@ +from torch import nn +import torch +from .RecSVTR import Block + +class Swish(nn.Module): + def __int__(self): + super(Swish, self).__int__() + + def forward(self,x): + return x*torch.sigmoid(x) + +class Im2Im(nn.Module): + def __init__(self, in_channels, **kwargs): + super().__init__() + self.out_channels = in_channels + + def forward(self, x): + return x + +class Im2Seq(nn.Module): + def __init__(self, in_channels, **kwargs): + super().__init__() + self.out_channels = in_channels + + def forward(self, x): + B, C, H, W = x.shape + # assert H == 1 + x = x.reshape(B, C, H * W) + x = x.permute((0, 2, 1)) + return x + +class EncoderWithRNN(nn.Module): + def __init__(self, in_channels,**kwargs): + super(EncoderWithRNN, self).__init__() + hidden_size = kwargs.get('hidden_size', 256) + self.out_channels = hidden_size * 2 + self.lstm = nn.LSTM(in_channels, hidden_size, bidirectional=True, num_layers=2,batch_first=True) + + def forward(self, x): + self.lstm.flatten_parameters() + x, _ = self.lstm(x) + return x + +class SequenceEncoder(nn.Module): + def __init__(self, in_channels, encoder_type='rnn', **kwargs): + super(SequenceEncoder, self).__init__() + self.encoder_reshape = Im2Seq(in_channels) + self.out_channels = self.encoder_reshape.out_channels + self.encoder_type = encoder_type + if encoder_type == 'reshape': + self.only_reshape = True + else: + support_encoder_dict = { + 'reshape': Im2Seq, + 'rnn': EncoderWithRNN, + 'svtr': EncoderWithSVTR + } + assert encoder_type in support_encoder_dict, '{} must in {}'.format( + encoder_type, support_encoder_dict.keys()) + + self.encoder = support_encoder_dict[encoder_type]( + self.encoder_reshape.out_channels,**kwargs) + self.out_channels = self.encoder.out_channels + self.only_reshape = False + + def forward(self, x): + if self.encoder_type != 'svtr': + x = self.encoder_reshape(x) + if not self.only_reshape: + x = self.encoder(x) + return x + else: + x = self.encoder(x) + x = self.encoder_reshape(x) + return x + +class ConvBNLayer(nn.Module): + def __init__(self, + in_channels, + out_channels, + kernel_size=3, + stride=1, + padding=0, + bias_attr=False, + groups=1, + act=nn.GELU): + super().__init__() + self.conv = nn.Conv2d( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=kernel_size, + stride=stride, + padding=padding, + groups=groups, + # weight_attr=paddle.ParamAttr(initializer=nn.initializer.KaimingUniform()), + bias=bias_attr) + self.norm = nn.BatchNorm2d(out_channels) + self.act = Swish() + + def forward(self, inputs): + out = self.conv(inputs) + out = self.norm(out) + out = self.act(out) + return out + + +class EncoderWithSVTR(nn.Module): + def __init__( + self, + in_channels, + dims=64, # XS + depth=2, + hidden_dims=120, + use_guide=False, + num_heads=8, + qkv_bias=True, + mlp_ratio=2.0, + drop_rate=0.1, + attn_drop_rate=0.1, + drop_path=0., + qk_scale=None): + super(EncoderWithSVTR, self).__init__() + self.depth = depth + self.use_guide = use_guide + self.conv1 = ConvBNLayer( + in_channels, in_channels // 8, padding=1, act='swish') + self.conv2 = ConvBNLayer( + in_channels // 8, hidden_dims, kernel_size=1, act='swish') + + self.svtr_block = nn.ModuleList([ + Block( + dim=hidden_dims, + num_heads=num_heads, + mixer='Global', + HW=None, + mlp_ratio=mlp_ratio, + qkv_bias=qkv_bias, + qk_scale=qk_scale, + drop=drop_rate, + act_layer='swish', + attn_drop=attn_drop_rate, + drop_path=drop_path, + norm_layer='nn.LayerNorm', + epsilon=1e-05, + prenorm=False) for i in range(depth) + ]) + self.norm = nn.LayerNorm(hidden_dims, eps=1e-6) + self.conv3 = ConvBNLayer( + hidden_dims, in_channels, kernel_size=1, act='swish') + # last conv-nxn, the input is concat of input tensor and conv3 output tensor + self.conv4 = ConvBNLayer( + 2 * in_channels, in_channels // 8, padding=1, act='swish') + + self.conv1x1 = ConvBNLayer( + in_channels // 8, dims, kernel_size=1, act='swish') + self.out_channels = dims + self.apply(self._init_weights) + + def _init_weights(self, m): + # weight initialization + if isinstance(m, nn.Conv2d): + nn.init.kaiming_normal_(m.weight, mode='fan_out') + if m.bias is not None: + nn.init.zeros_(m.bias) + elif isinstance(m, nn.BatchNorm2d): + nn.init.ones_(m.weight) + nn.init.zeros_(m.bias) + elif isinstance(m, nn.Linear): + nn.init.normal_(m.weight, 0, 0.01) + if m.bias is not None: + nn.init.zeros_(m.bias) + elif isinstance(m, nn.ConvTranspose2d): + nn.init.kaiming_normal_(m.weight, mode='fan_out') + if m.bias is not None: + nn.init.zeros_(m.bias) + elif isinstance(m, nn.LayerNorm): + nn.init.ones_(m.weight) + nn.init.zeros_(m.bias) + + def forward(self, x): + # for use guide + if self.use_guide: + z = x.clone() + z.stop_gradient = True + else: + z = x + # for short cut + h = z + # reduce dim + z = self.conv1(z) + z = self.conv2(z) + # SVTR global block + B, C, H, W = z.shape + z = z.flatten(2).permute(0, 2, 1) + + for blk in self.svtr_block: + z = blk(z) + + z = self.norm(z) + # last stage + z = z.reshape([-1, H, W, C]).permute(0, 3, 1, 2) + z = self.conv3(z) + z = torch.cat((h, z), dim=1) + z = self.conv1x1(self.conv4(z)) + + return z + +if __name__=="__main__": + svtrRNN = EncoderWithSVTR(56) + print(svtrRNN) \ No newline at end of file diff --git a/py/iopaint/model/anytext/ocr_recog/RecCTCHead.py b/py/iopaint/model/anytext/ocr_recog/RecCTCHead.py new file mode 100644 index 0000000..867ede9 --- /dev/null +++ b/py/iopaint/model/anytext/ocr_recog/RecCTCHead.py @@ -0,0 +1,48 @@ +from torch import nn + + +class CTCHead(nn.Module): + def __init__(self, + in_channels, + out_channels=6625, + fc_decay=0.0004, + mid_channels=None, + return_feats=False, + **kwargs): + super(CTCHead, self).__init__() + if mid_channels is None: + self.fc = nn.Linear( + in_channels, + out_channels, + bias=True,) + else: + self.fc1 = nn.Linear( + in_channels, + mid_channels, + bias=True, + ) + self.fc2 = nn.Linear( + mid_channels, + out_channels, + bias=True, + ) + + self.out_channels = out_channels + self.mid_channels = mid_channels + self.return_feats = return_feats + + def forward(self, x, labels=None): + if self.mid_channels is None: + predicts = self.fc(x) + else: + x = self.fc1(x) + predicts = self.fc2(x) + + if self.return_feats: + result = dict() + result['ctc'] = predicts + result['ctc_neck'] = x + else: + result = predicts + + return result diff --git a/py/iopaint/model/anytext/ocr_recog/RecModel.py b/py/iopaint/model/anytext/ocr_recog/RecModel.py new file mode 100644 index 0000000..c2313bf --- /dev/null +++ b/py/iopaint/model/anytext/ocr_recog/RecModel.py @@ -0,0 +1,45 @@ +from torch import nn +from .RNN import SequenceEncoder, Im2Seq, Im2Im +from .RecMv1_enhance import MobileNetV1Enhance + +from .RecCTCHead import CTCHead + +backbone_dict = {"MobileNetV1Enhance":MobileNetV1Enhance} +neck_dict = {'SequenceEncoder': SequenceEncoder, 'Im2Seq': Im2Seq,'None':Im2Im} +head_dict = {'CTCHead':CTCHead} + + +class RecModel(nn.Module): + def __init__(self, config): + super().__init__() + assert 'in_channels' in config, 'in_channels must in model config' + backbone_type = config.backbone.pop('type') + assert backbone_type in backbone_dict, f'backbone.type must in {backbone_dict}' + self.backbone = backbone_dict[backbone_type](config.in_channels, **config.backbone) + + neck_type = config.neck.pop('type') + assert neck_type in neck_dict, f'neck.type must in {neck_dict}' + self.neck = neck_dict[neck_type](self.backbone.out_channels, **config.neck) + + head_type = config.head.pop('type') + assert head_type in head_dict, f'head.type must in {head_dict}' + self.head = head_dict[head_type](self.neck.out_channels, **config.head) + + self.name = f'RecModel_{backbone_type}_{neck_type}_{head_type}' + + def load_3rd_state_dict(self, _3rd_name, _state): + self.backbone.load_3rd_state_dict(_3rd_name, _state) + self.neck.load_3rd_state_dict(_3rd_name, _state) + self.head.load_3rd_state_dict(_3rd_name, _state) + + def forward(self, x): + x = self.backbone(x) + x = self.neck(x) + x = self.head(x) + return x + + def encode(self, x): + x = self.backbone(x) + x = self.neck(x) + x = self.head.ctc_encoder(x) + return x diff --git a/py/iopaint/model/anytext/ocr_recog/RecMv1_enhance.py b/py/iopaint/model/anytext/ocr_recog/RecMv1_enhance.py new file mode 100644 index 0000000..7529b4a --- /dev/null +++ b/py/iopaint/model/anytext/ocr_recog/RecMv1_enhance.py @@ -0,0 +1,232 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F +from .common import Activation + + +class ConvBNLayer(nn.Module): + def __init__(self, + num_channels, + filter_size, + num_filters, + stride, + padding, + channels=None, + num_groups=1, + act='hard_swish'): + super(ConvBNLayer, self).__init__() + self.act = act + self._conv = nn.Conv2d( + in_channels=num_channels, + out_channels=num_filters, + kernel_size=filter_size, + stride=stride, + padding=padding, + groups=num_groups, + bias=False) + + self._batch_norm = nn.BatchNorm2d( + num_filters, + ) + if self.act is not None: + self._act = Activation(act_type=act, inplace=True) + + def forward(self, inputs): + y = self._conv(inputs) + y = self._batch_norm(y) + if self.act is not None: + y = self._act(y) + return y + + +class DepthwiseSeparable(nn.Module): + def __init__(self, + num_channels, + num_filters1, + num_filters2, + num_groups, + stride, + scale, + dw_size=3, + padding=1, + use_se=False): + super(DepthwiseSeparable, self).__init__() + self.use_se = use_se + self._depthwise_conv = ConvBNLayer( + num_channels=num_channels, + num_filters=int(num_filters1 * scale), + filter_size=dw_size, + stride=stride, + padding=padding, + num_groups=int(num_groups * scale)) + if use_se: + self._se = SEModule(int(num_filters1 * scale)) + self._pointwise_conv = ConvBNLayer( + num_channels=int(num_filters1 * scale), + filter_size=1, + num_filters=int(num_filters2 * scale), + stride=1, + padding=0) + + def forward(self, inputs): + y = self._depthwise_conv(inputs) + if self.use_se: + y = self._se(y) + y = self._pointwise_conv(y) + return y + + +class MobileNetV1Enhance(nn.Module): + def __init__(self, + in_channels=3, + scale=0.5, + last_conv_stride=1, + last_pool_type='max', + **kwargs): + super().__init__() + self.scale = scale + self.block_list = [] + + self.conv1 = ConvBNLayer( + num_channels=in_channels, + filter_size=3, + channels=3, + num_filters=int(32 * scale), + stride=2, + padding=1) + + conv2_1 = DepthwiseSeparable( + num_channels=int(32 * scale), + num_filters1=32, + num_filters2=64, + num_groups=32, + stride=1, + scale=scale) + self.block_list.append(conv2_1) + + conv2_2 = DepthwiseSeparable( + num_channels=int(64 * scale), + num_filters1=64, + num_filters2=128, + num_groups=64, + stride=1, + scale=scale) + self.block_list.append(conv2_2) + + conv3_1 = DepthwiseSeparable( + num_channels=int(128 * scale), + num_filters1=128, + num_filters2=128, + num_groups=128, + stride=1, + scale=scale) + self.block_list.append(conv3_1) + + conv3_2 = DepthwiseSeparable( + num_channels=int(128 * scale), + num_filters1=128, + num_filters2=256, + num_groups=128, + stride=(2, 1), + scale=scale) + self.block_list.append(conv3_2) + + conv4_1 = DepthwiseSeparable( + num_channels=int(256 * scale), + num_filters1=256, + num_filters2=256, + num_groups=256, + stride=1, + scale=scale) + self.block_list.append(conv4_1) + + conv4_2 = DepthwiseSeparable( + num_channels=int(256 * scale), + num_filters1=256, + num_filters2=512, + num_groups=256, + stride=(2, 1), + scale=scale) + self.block_list.append(conv4_2) + + for _ in range(5): + conv5 = DepthwiseSeparable( + num_channels=int(512 * scale), + num_filters1=512, + num_filters2=512, + num_groups=512, + stride=1, + dw_size=5, + padding=2, + scale=scale, + use_se=False) + self.block_list.append(conv5) + + conv5_6 = DepthwiseSeparable( + num_channels=int(512 * scale), + num_filters1=512, + num_filters2=1024, + num_groups=512, + stride=(2, 1), + dw_size=5, + padding=2, + scale=scale, + use_se=True) + self.block_list.append(conv5_6) + + conv6 = DepthwiseSeparable( + num_channels=int(1024 * scale), + num_filters1=1024, + num_filters2=1024, + num_groups=1024, + stride=last_conv_stride, + dw_size=5, + padding=2, + use_se=True, + scale=scale) + self.block_list.append(conv6) + + self.block_list = nn.Sequential(*self.block_list) + if last_pool_type == 'avg': + self.pool = nn.AvgPool2d(kernel_size=2, stride=2, padding=0) + else: + self.pool = nn.MaxPool2d(kernel_size=2, stride=2, padding=0) + self.out_channels = int(1024 * scale) + + def forward(self, inputs): + y = self.conv1(inputs) + y = self.block_list(y) + y = self.pool(y) + return y + +def hardsigmoid(x): + return F.relu6(x + 3., inplace=True) / 6. + +class SEModule(nn.Module): + def __init__(self, channel, reduction=4): + super(SEModule, self).__init__() + self.avg_pool = nn.AdaptiveAvgPool2d(1) + self.conv1 = nn.Conv2d( + in_channels=channel, + out_channels=channel // reduction, + kernel_size=1, + stride=1, + padding=0, + bias=True) + self.conv2 = nn.Conv2d( + in_channels=channel // reduction, + out_channels=channel, + kernel_size=1, + stride=1, + padding=0, + bias=True) + + def forward(self, inputs): + outputs = self.avg_pool(inputs) + outputs = self.conv1(outputs) + outputs = F.relu(outputs) + outputs = self.conv2(outputs) + outputs = hardsigmoid(outputs) + x = torch.mul(inputs, outputs) + + return x diff --git a/py/iopaint/model/anytext/ocr_recog/RecSVTR.py b/py/iopaint/model/anytext/ocr_recog/RecSVTR.py new file mode 100644 index 0000000..484b3df --- /dev/null +++ b/py/iopaint/model/anytext/ocr_recog/RecSVTR.py @@ -0,0 +1,591 @@ +import torch +import torch.nn as nn +import numpy as np +from torch.nn.init import trunc_normal_, zeros_, ones_ +from torch.nn import functional + + +def drop_path(x, drop_prob=0., training=False): + """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). + the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper... + See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... + """ + if drop_prob == 0. or not training: + return x + keep_prob = torch.tensor(1 - drop_prob) + shape = (x.size()[0], ) + (1, ) * (x.ndim - 1) + random_tensor = keep_prob + torch.rand(shape, dtype=x.dtype) + random_tensor = torch.floor(random_tensor) # binarize + output = x.divide(keep_prob) * random_tensor + return output + + +class Swish(nn.Module): + def __int__(self): + super(Swish, self).__int__() + + def forward(self,x): + return x*torch.sigmoid(x) + + +class ConvBNLayer(nn.Module): + def __init__(self, + in_channels, + out_channels, + kernel_size=3, + stride=1, + padding=0, + bias_attr=False, + groups=1, + act=nn.GELU): + super().__init__() + self.conv = nn.Conv2d( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=kernel_size, + stride=stride, + padding=padding, + groups=groups, + # weight_attr=paddle.ParamAttr(initializer=nn.initializer.KaimingUniform()), + bias=bias_attr) + self.norm = nn.BatchNorm2d(out_channels) + self.act = act() + + def forward(self, inputs): + out = self.conv(inputs) + out = self.norm(out) + out = self.act(out) + return out + + +class DropPath(nn.Module): + """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). + """ + + def __init__(self, drop_prob=None): + super(DropPath, self).__init__() + self.drop_prob = drop_prob + + def forward(self, x): + return drop_path(x, self.drop_prob, self.training) + + +class Identity(nn.Module): + def __init__(self): + super(Identity, self).__init__() + + def forward(self, input): + return input + + +class Mlp(nn.Module): + def __init__(self, + in_features, + hidden_features=None, + out_features=None, + act_layer=nn.GELU, + drop=0.): + super().__init__() + out_features = out_features or in_features + hidden_features = hidden_features or in_features + self.fc1 = nn.Linear(in_features, hidden_features) + if isinstance(act_layer, str): + self.act = Swish() + else: + self.act = act_layer() + self.fc2 = nn.Linear(hidden_features, out_features) + self.drop = nn.Dropout(drop) + + def forward(self, x): + x = self.fc1(x) + x = self.act(x) + x = self.drop(x) + x = self.fc2(x) + x = self.drop(x) + return x + + +class ConvMixer(nn.Module): + def __init__( + self, + dim, + num_heads=8, + HW=(8, 25), + local_k=(3, 3), ): + super().__init__() + self.HW = HW + self.dim = dim + self.local_mixer = nn.Conv2d( + dim, + dim, + local_k, + 1, (local_k[0] // 2, local_k[1] // 2), + groups=num_heads, + # weight_attr=ParamAttr(initializer=KaimingNormal()) + ) + + def forward(self, x): + h = self.HW[0] + w = self.HW[1] + x = x.transpose([0, 2, 1]).reshape([0, self.dim, h, w]) + x = self.local_mixer(x) + x = x.flatten(2).transpose([0, 2, 1]) + return x + + +class Attention(nn.Module): + def __init__(self, + dim, + num_heads=8, + mixer='Global', + HW=(8, 25), + local_k=(7, 11), + qkv_bias=False, + qk_scale=None, + attn_drop=0., + proj_drop=0.): + super().__init__() + self.num_heads = num_heads + head_dim = dim // num_heads + self.scale = qk_scale or head_dim**-0.5 + + self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) + self.attn_drop = nn.Dropout(attn_drop) + self.proj = nn.Linear(dim, dim) + self.proj_drop = nn.Dropout(proj_drop) + self.HW = HW + if HW is not None: + H = HW[0] + W = HW[1] + self.N = H * W + self.C = dim + if mixer == 'Local' and HW is not None: + hk = local_k[0] + wk = local_k[1] + mask = torch.ones([H * W, H + hk - 1, W + wk - 1]) + for h in range(0, H): + for w in range(0, W): + mask[h * W + w, h:h + hk, w:w + wk] = 0. + mask_paddle = mask[:, hk // 2:H + hk // 2, wk // 2:W + wk // + 2].flatten(1) + mask_inf = torch.full([H * W, H * W],fill_value=float('-inf')) + mask = torch.where(mask_paddle < 1, mask_paddle, mask_inf) + self.mask = mask[None,None,:] + # self.mask = mask.unsqueeze([0, 1]) + self.mixer = mixer + + def forward(self, x): + if self.HW is not None: + N = self.N + C = self.C + else: + _, N, C = x.shape + qkv = self.qkv(x).reshape((-1, N, 3, self.num_heads, C //self.num_heads)).permute((2, 0, 3, 1, 4)) + q, k, v = qkv[0] * self.scale, qkv[1], qkv[2] + + attn = (q.matmul(k.permute((0, 1, 3, 2)))) + if self.mixer == 'Local': + attn += self.mask + attn = functional.softmax(attn, dim=-1) + attn = self.attn_drop(attn) + + x = (attn.matmul(v)).permute((0, 2, 1, 3)).reshape((-1, N, C)) + x = self.proj(x) + x = self.proj_drop(x) + return x + + +class Block(nn.Module): + def __init__(self, + dim, + num_heads, + mixer='Global', + local_mixer=(7, 11), + HW=(8, 25), + mlp_ratio=4., + qkv_bias=False, + qk_scale=None, + drop=0., + attn_drop=0., + drop_path=0., + act_layer=nn.GELU, + norm_layer='nn.LayerNorm', + epsilon=1e-6, + prenorm=True): + super().__init__() + if isinstance(norm_layer, str): + self.norm1 = eval(norm_layer)(dim, eps=epsilon) + else: + self.norm1 = norm_layer(dim) + if mixer == 'Global' or mixer == 'Local': + + self.mixer = Attention( + dim, + num_heads=num_heads, + mixer=mixer, + HW=HW, + local_k=local_mixer, + qkv_bias=qkv_bias, + qk_scale=qk_scale, + attn_drop=attn_drop, + proj_drop=drop) + elif mixer == 'Conv': + self.mixer = ConvMixer( + dim, num_heads=num_heads, HW=HW, local_k=local_mixer) + else: + raise TypeError("The mixer must be one of [Global, Local, Conv]") + + self.drop_path = DropPath(drop_path) if drop_path > 0. else Identity() + if isinstance(norm_layer, str): + self.norm2 = eval(norm_layer)(dim, eps=epsilon) + else: + self.norm2 = norm_layer(dim) + mlp_hidden_dim = int(dim * mlp_ratio) + self.mlp_ratio = mlp_ratio + self.mlp = Mlp(in_features=dim, + hidden_features=mlp_hidden_dim, + act_layer=act_layer, + drop=drop) + self.prenorm = prenorm + + def forward(self, x): + if self.prenorm: + x = self.norm1(x + self.drop_path(self.mixer(x))) + x = self.norm2(x + self.drop_path(self.mlp(x))) + else: + x = x + self.drop_path(self.mixer(self.norm1(x))) + x = x + self.drop_path(self.mlp(self.norm2(x))) + return x + + +class PatchEmbed(nn.Module): + """ Image to Patch Embedding + """ + + def __init__(self, + img_size=(32, 100), + in_channels=3, + embed_dim=768, + sub_num=2): + super().__init__() + num_patches = (img_size[1] // (2 ** sub_num)) * \ + (img_size[0] // (2 ** sub_num)) + self.img_size = img_size + self.num_patches = num_patches + self.embed_dim = embed_dim + self.norm = None + if sub_num == 2: + self.proj = nn.Sequential( + ConvBNLayer( + in_channels=in_channels, + out_channels=embed_dim // 2, + kernel_size=3, + stride=2, + padding=1, + act=nn.GELU, + bias_attr=False), + ConvBNLayer( + in_channels=embed_dim // 2, + out_channels=embed_dim, + kernel_size=3, + stride=2, + padding=1, + act=nn.GELU, + bias_attr=False)) + if sub_num == 3: + self.proj = nn.Sequential( + ConvBNLayer( + in_channels=in_channels, + out_channels=embed_dim // 4, + kernel_size=3, + stride=2, + padding=1, + act=nn.GELU, + bias_attr=False), + ConvBNLayer( + in_channels=embed_dim // 4, + out_channels=embed_dim // 2, + kernel_size=3, + stride=2, + padding=1, + act=nn.GELU, + bias_attr=False), + ConvBNLayer( + in_channels=embed_dim // 2, + out_channels=embed_dim, + kernel_size=3, + stride=2, + padding=1, + act=nn.GELU, + bias_attr=False)) + + def forward(self, x): + B, C, H, W = x.shape + assert H == self.img_size[0] and W == self.img_size[1], \ + f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})." + x = self.proj(x).flatten(2).permute(0, 2, 1) + return x + + +class SubSample(nn.Module): + def __init__(self, + in_channels, + out_channels, + types='Pool', + stride=(2, 1), + sub_norm='nn.LayerNorm', + act=None): + super().__init__() + self.types = types + if types == 'Pool': + self.avgpool = nn.AvgPool2d( + kernel_size=(3, 5), stride=stride, padding=(1, 2)) + self.maxpool = nn.MaxPool2d( + kernel_size=(3, 5), stride=stride, padding=(1, 2)) + self.proj = nn.Linear(in_channels, out_channels) + else: + self.conv = nn.Conv2d( + in_channels, + out_channels, + kernel_size=3, + stride=stride, + padding=1, + # weight_attr=ParamAttr(initializer=KaimingNormal()) + ) + self.norm = eval(sub_norm)(out_channels) + if act is not None: + self.act = act() + else: + self.act = None + + def forward(self, x): + + if self.types == 'Pool': + x1 = self.avgpool(x) + x2 = self.maxpool(x) + x = (x1 + x2) * 0.5 + out = self.proj(x.flatten(2).permute((0, 2, 1))) + else: + x = self.conv(x) + out = x.flatten(2).permute((0, 2, 1)) + out = self.norm(out) + if self.act is not None: + out = self.act(out) + + return out + + +class SVTRNet(nn.Module): + def __init__( + self, + img_size=[48, 100], + in_channels=3, + embed_dim=[64, 128, 256], + depth=[3, 6, 3], + num_heads=[2, 4, 8], + mixer=['Local'] * 6 + ['Global'] * + 6, # Local atten, Global atten, Conv + local_mixer=[[7, 11], [7, 11], [7, 11]], + patch_merging='Conv', # Conv, Pool, None + mlp_ratio=4, + qkv_bias=True, + qk_scale=None, + drop_rate=0., + last_drop=0.1, + attn_drop_rate=0., + drop_path_rate=0.1, + norm_layer='nn.LayerNorm', + sub_norm='nn.LayerNorm', + epsilon=1e-6, + out_channels=192, + out_char_num=25, + block_unit='Block', + act='nn.GELU', + last_stage=True, + sub_num=2, + prenorm=True, + use_lenhead=False, + **kwargs): + super().__init__() + self.img_size = img_size + self.embed_dim = embed_dim + self.out_channels = out_channels + self.prenorm = prenorm + patch_merging = None if patch_merging != 'Conv' and patch_merging != 'Pool' else patch_merging + self.patch_embed = PatchEmbed( + img_size=img_size, + in_channels=in_channels, + embed_dim=embed_dim[0], + sub_num=sub_num) + num_patches = self.patch_embed.num_patches + self.HW = [img_size[0] // (2**sub_num), img_size[1] // (2**sub_num)] + self.pos_embed = nn.Parameter(torch.zeros(1, num_patches, embed_dim[0])) + # self.pos_embed = self.create_parameter( + # shape=[1, num_patches, embed_dim[0]], default_initializer=zeros_) + + # self.add_parameter("pos_embed", self.pos_embed) + + self.pos_drop = nn.Dropout(p=drop_rate) + Block_unit = eval(block_unit) + + dpr = np.linspace(0, drop_path_rate, sum(depth)) + self.blocks1 = nn.ModuleList( + [ + Block_unit( + dim=embed_dim[0], + num_heads=num_heads[0], + mixer=mixer[0:depth[0]][i], + HW=self.HW, + local_mixer=local_mixer[0], + mlp_ratio=mlp_ratio, + qkv_bias=qkv_bias, + qk_scale=qk_scale, + drop=drop_rate, + act_layer=eval(act), + attn_drop=attn_drop_rate, + drop_path=dpr[0:depth[0]][i], + norm_layer=norm_layer, + epsilon=epsilon, + prenorm=prenorm) for i in range(depth[0]) + ] + ) + if patch_merging is not None: + self.sub_sample1 = SubSample( + embed_dim[0], + embed_dim[1], + sub_norm=sub_norm, + stride=[2, 1], + types=patch_merging) + HW = [self.HW[0] // 2, self.HW[1]] + else: + HW = self.HW + self.patch_merging = patch_merging + self.blocks2 = nn.ModuleList([ + Block_unit( + dim=embed_dim[1], + num_heads=num_heads[1], + mixer=mixer[depth[0]:depth[0] + depth[1]][i], + HW=HW, + local_mixer=local_mixer[1], + mlp_ratio=mlp_ratio, + qkv_bias=qkv_bias, + qk_scale=qk_scale, + drop=drop_rate, + act_layer=eval(act), + attn_drop=attn_drop_rate, + drop_path=dpr[depth[0]:depth[0] + depth[1]][i], + norm_layer=norm_layer, + epsilon=epsilon, + prenorm=prenorm) for i in range(depth[1]) + ]) + if patch_merging is not None: + self.sub_sample2 = SubSample( + embed_dim[1], + embed_dim[2], + sub_norm=sub_norm, + stride=[2, 1], + types=patch_merging) + HW = [self.HW[0] // 4, self.HW[1]] + else: + HW = self.HW + self.blocks3 = nn.ModuleList([ + Block_unit( + dim=embed_dim[2], + num_heads=num_heads[2], + mixer=mixer[depth[0] + depth[1]:][i], + HW=HW, + local_mixer=local_mixer[2], + mlp_ratio=mlp_ratio, + qkv_bias=qkv_bias, + qk_scale=qk_scale, + drop=drop_rate, + act_layer=eval(act), + attn_drop=attn_drop_rate, + drop_path=dpr[depth[0] + depth[1]:][i], + norm_layer=norm_layer, + epsilon=epsilon, + prenorm=prenorm) for i in range(depth[2]) + ]) + self.last_stage = last_stage + if last_stage: + self.avg_pool = nn.AdaptiveAvgPool2d((1, out_char_num)) + self.last_conv = nn.Conv2d( + in_channels=embed_dim[2], + out_channels=self.out_channels, + kernel_size=1, + stride=1, + padding=0, + bias=False) + self.hardswish = nn.Hardswish() + self.dropout = nn.Dropout(p=last_drop) + if not prenorm: + self.norm = eval(norm_layer)(embed_dim[-1], epsilon=epsilon) + self.use_lenhead = use_lenhead + if use_lenhead: + self.len_conv = nn.Linear(embed_dim[2], self.out_channels) + self.hardswish_len = nn.Hardswish() + self.dropout_len = nn.Dropout( + p=last_drop) + + trunc_normal_(self.pos_embed,std=.02) + self.apply(self._init_weights) + + def _init_weights(self, m): + if isinstance(m, nn.Linear): + trunc_normal_(m.weight,std=.02) + if isinstance(m, nn.Linear) and m.bias is not None: + zeros_(m.bias) + elif isinstance(m, nn.LayerNorm): + zeros_(m.bias) + ones_(m.weight) + + def forward_features(self, x): + x = self.patch_embed(x) + x = x + self.pos_embed + x = self.pos_drop(x) + for blk in self.blocks1: + x = blk(x) + if self.patch_merging is not None: + x = self.sub_sample1( + x.permute([0, 2, 1]).reshape( + [-1, self.embed_dim[0], self.HW[0], self.HW[1]])) + for blk in self.blocks2: + x = blk(x) + if self.patch_merging is not None: + x = self.sub_sample2( + x.permute([0, 2, 1]).reshape( + [-1, self.embed_dim[1], self.HW[0] // 2, self.HW[1]])) + for blk in self.blocks3: + x = blk(x) + if not self.prenorm: + x = self.norm(x) + return x + + def forward(self, x): + x = self.forward_features(x) + if self.use_lenhead: + len_x = self.len_conv(x.mean(1)) + len_x = self.dropout_len(self.hardswish_len(len_x)) + if self.last_stage: + if self.patch_merging is not None: + h = self.HW[0] // 4 + else: + h = self.HW[0] + x = self.avg_pool( + x.permute([0, 2, 1]).reshape( + [-1, self.embed_dim[2], h, self.HW[1]])) + x = self.last_conv(x) + x = self.hardswish(x) + x = self.dropout(x) + if self.use_lenhead: + return x, len_x + return x + + +if __name__=="__main__": + a = torch.rand(1,3,48,100) + svtr = SVTRNet() + + out = svtr(a) + print(svtr) + print(out.size()) \ No newline at end of file diff --git a/py/iopaint/model/anytext/ocr_recog/__init__.py b/py/iopaint/model/anytext/ocr_recog/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/py/iopaint/model/anytext/ocr_recog/common.py b/py/iopaint/model/anytext/ocr_recog/common.py new file mode 100644 index 0000000..a328bb0 --- /dev/null +++ b/py/iopaint/model/anytext/ocr_recog/common.py @@ -0,0 +1,74 @@ + + +import torch +import torch.nn as nn +import torch.nn.functional as F + + +class Hswish(nn.Module): + def __init__(self, inplace=True): + super(Hswish, self).__init__() + self.inplace = inplace + + def forward(self, x): + return x * F.relu6(x + 3., inplace=self.inplace) / 6. + +# out = max(0, min(1, slop*x+offset)) +# paddle.fluid.layers.hard_sigmoid(x, slope=0.2, offset=0.5, name=None) +class Hsigmoid(nn.Module): + def __init__(self, inplace=True): + super(Hsigmoid, self).__init__() + self.inplace = inplace + + def forward(self, x): + # torch: F.relu6(x + 3., inplace=self.inplace) / 6. + # paddle: F.relu6(1.2 * x + 3., inplace=self.inplace) / 6. + return F.relu6(1.2 * x + 3., inplace=self.inplace) / 6. + +class GELU(nn.Module): + def __init__(self, inplace=True): + super(GELU, self).__init__() + self.inplace = inplace + + def forward(self, x): + return torch.nn.functional.gelu(x) + + +class Swish(nn.Module): + def __init__(self, inplace=True): + super(Swish, self).__init__() + self.inplace = inplace + + def forward(self, x): + if self.inplace: + x.mul_(torch.sigmoid(x)) + return x + else: + return x*torch.sigmoid(x) + + +class Activation(nn.Module): + def __init__(self, act_type, inplace=True): + super(Activation, self).__init__() + act_type = act_type.lower() + if act_type == 'relu': + self.act = nn.ReLU(inplace=inplace) + elif act_type == 'relu6': + self.act = nn.ReLU6(inplace=inplace) + elif act_type == 'sigmoid': + raise NotImplementedError + elif act_type == 'hard_sigmoid': + self.act = Hsigmoid(inplace) + elif act_type == 'hard_swish': + self.act = Hswish(inplace=inplace) + elif act_type == 'leakyrelu': + self.act = nn.LeakyReLU(inplace=inplace) + elif act_type == 'gelu': + self.act = GELU(inplace=inplace) + elif act_type == 'swish': + self.act = Swish(inplace=inplace) + else: + raise NotImplementedError + + def forward(self, inputs): + return self.act(inputs) \ No newline at end of file diff --git a/py/iopaint/model/anytext/ocr_recog/ppocr_keys_v1.txt b/py/iopaint/model/anytext/ocr_recog/ppocr_keys_v1.txt new file mode 100644 index 0000000..84b885d --- /dev/null +++ b/py/iopaint/model/anytext/ocr_recog/ppocr_keys_v1.txt @@ -0,0 +1,6623 @@ +' +疗 +绚 +诚 +娇 +溜 +题 +贿 +者 +廖 +更 +纳 +加 +奉 +公 +一 +就 +汴 +计 +与 +路 +房 +原 +妇 +2 +0 +8 +- +7 +其 +> +: +] +, +, +骑 +刈 +全 +消 +昏 +傈 +安 +久 +钟 +嗅 +不 +影 +处 +驽 +蜿 +资 +关 +椤 +地 +瘸 +专 +问 +忖 +票 +嫉 +炎 +韵 +要 +月 +田 +节 +陂 +鄙 +捌 +备 +拳 +伺 +眼 +网 +盎 +大 +傍 +心 +东 +愉 +汇 +蹿 +科 +每 +业 +里 +航 +晏 +字 +平 +录 +先 +1 +3 +彤 +鲶 +产 +稍 +督 +腴 +有 +象 +岳 +注 +绍 +在 +泺 +文 +定 +核 +名 +水 +过 +理 +让 +偷 +率 +等 +这 +发 +” +为 +含 +肥 +酉 +相 +鄱 +七 +编 +猥 +锛 +日 +镀 +蒂 +掰 +倒 +辆 +栾 +栗 +综 +涩 +州 +雌 +滑 +馀 +了 +机 +块 +司 +宰 +甙 +兴 +矽 +抚 +保 +用 +沧 +秩 +如 +收 +息 +滥 +页 +疑 +埠 +! +! +姥 +异 +橹 +钇 +向 +下 +跄 +的 +椴 +沫 +国 +绥 +獠 +报 +开 +民 +蜇 +何 +分 +凇 +长 +讥 +藏 +掏 +施 +羽 +中 +讲 +派 +嘟 +人 +提 +浼 +间 +世 +而 +古 +多 +倪 +唇 +饯 +控 +庚 +首 +赛 +蜓 +味 +断 +制 +觉 +技 +替 +艰 +溢 +潮 +夕 +钺 +外 +摘 +枋 +动 +双 +单 +啮 +户 +枇 +确 +锦 +曜 +杜 +或 +能 +效 +霜 +盒 +然 +侗 +电 +晁 +放 +步 +鹃 +新 +杖 +蜂 +吒 +濂 +瞬 +评 +总 +隍 +对 +独 +合 +也 +是 +府 +青 +天 +诲 +墙 +组 +滴 +级 +邀 +帘 +示 +已 +时 +骸 +仄 +泅 +和 +遨 +店 +雇 +疫 +持 +巍 +踮 +境 +只 +亨 +目 +鉴 +崤 +闲 +体 +泄 +杂 +作 +般 +轰 +化 +解 +迂 +诿 +蛭 +璀 +腾 +告 +版 +服 +省 +师 +小 +规 +程 +线 +海 +办 +引 +二 +桧 +牌 +砺 +洄 +裴 +修 +图 +痫 +胡 +许 +犊 +事 +郛 +基 +柴 +呼 +食 +研 +奶 +律 +蛋 +因 +葆 +察 +戏 +褒 +戒 +再 +李 +骁 +工 +貂 +油 +鹅 +章 +啄 +休 +场 +给 +睡 +纷 +豆 +器 +捎 +说 +敏 +学 +会 +浒 +设 +诊 +格 +廓 +查 +来 +霓 +室 +溆 +¢ +诡 +寥 +焕 +舜 +柒 +狐 +回 +戟 +砾 +厄 +实 +翩 +尿 +五 +入 +径 +惭 +喹 +股 +宇 +篝 +| +; +美 +期 +云 +九 +祺 +扮 +靠 +锝 +槌 +系 +企 +酰 +阊 +暂 +蚕 +忻 +豁 +本 +羹 +执 +条 +钦 +H +獒 +限 +进 +季 +楦 +于 +芘 +玖 +铋 +茯 +未 +答 +粘 +括 +样 +精 +欠 +矢 +甥 +帷 +嵩 +扣 +令 +仔 +风 +皈 +行 +支 +部 +蓉 +刮 +站 +蜡 +救 +钊 +汗 +松 +嫌 +成 +可 +. +鹤 +院 +从 +交 +政 +怕 +活 +调 +球 +局 +验 +髌 +第 +韫 +谗 +串 +到 +圆 +年 +米 +/ +* +友 +忿 +检 +区 +看 +自 +敢 +刃 +个 +兹 +弄 +流 +留 +同 +没 +齿 +星 +聆 +轼 +湖 +什 +三 +建 +蛔 +儿 +椋 +汕 +震 +颧 +鲤 +跟 +力 +情 +璺 +铨 +陪 +务 +指 +族 +训 +滦 +鄣 +濮 +扒 +商 +箱 +十 +召 +慷 +辗 +所 +莞 +管 +护 +臭 +横 +硒 +嗓 +接 +侦 +六 +露 +党 +馋 +驾 +剖 +高 +侬 +妪 +幂 +猗 +绺 +骐 +央 +酐 +孝 +筝 +课 +徇 +缰 +门 +男 +西 +项 +句 +谙 +瞒 +秃 +篇 +教 +碲 +罚 +声 +呐 +景 +前 +富 +嘴 +鳌 +稀 +免 +朋 +啬 +睐 +去 +赈 +鱼 +住 +肩 +愕 +速 +旁 +波 +厅 +健 +茼 +厥 +鲟 +谅 +投 +攸 +炔 +数 +方 +击 +呋 +谈 +绩 +别 +愫 +僚 +躬 +鹧 +胪 +炳 +招 +喇 +膨 +泵 +蹦 +毛 +结 +5 +4 +谱 +识 +陕 +粽 +婚 +拟 +构 +且 +搜 +任 +潘 +比 +郢 +妨 +醪 +陀 +桔 +碘 +扎 +选 +哈 +骷 +楷 +亿 +明 +缆 +脯 +监 +睫 +逻 +婵 +共 +赴 +淝 +凡 +惦 +及 +达 +揖 +谩 +澹 +减 +焰 +蛹 +番 +祁 +柏 +员 +禄 +怡 +峤 +龙 +白 +叽 +生 +闯 +起 +细 +装 +谕 +竟 +聚 +钙 +上 +导 +渊 +按 +艾 +辘 +挡 +耒 +盹 +饪 +臀 +记 +邮 +蕙 +受 +各 +医 +搂 +普 +滇 +朗 +茸 +带 +翻 +酚 +( +光 +堤 +墟 +蔷 +万 +幻 +〓 +瑙 +辈 +昧 +盏 +亘 +蛀 +吉 +铰 +请 +子 +假 +闻 +税 +井 +诩 +哨 +嫂 +好 +面 +琐 +校 +馊 +鬣 +缂 +营 +访 +炖 +占 +农 +缀 +否 +经 +钚 +棵 +趟 +张 +亟 +吏 +茶 +谨 +捻 +论 +迸 +堂 +玉 +信 +吧 +瞠 +乡 +姬 +寺 +咬 +溏 +苄 +皿 +意 +赉 +宝 +尔 +钰 +艺 +特 +唳 +踉 +都 +荣 +倚 +登 +荐 +丧 +奇 +涵 +批 +炭 +近 +符 +傩 +感 +道 +着 +菊 +虹 +仲 +众 +懈 +濯 +颞 +眺 +南 +释 +北 +缝 +标 +既 +茗 +整 +撼 +迤 +贲 +挎 +耱 +拒 +某 +妍 +卫 +哇 +英 +矶 +藩 +治 +他 +元 +领 +膜 +遮 +穗 +蛾 +飞 +荒 +棺 +劫 +么 +市 +火 +温 +拈 +棚 +洼 +转 +果 +奕 +卸 +迪 +伸 +泳 +斗 +邡 +侄 +涨 +屯 +萋 +胭 +氡 +崮 +枞 +惧 +冒 +彩 +斜 +手 +豚 +随 +旭 +淑 +妞 +形 +菌 +吲 +沱 +争 +驯 +歹 +挟 +兆 +柱 +传 +至 +包 +内 +响 +临 +红 +功 +弩 +衡 +寂 +禁 +老 +棍 +耆 +渍 +织 +害 +氵 +渑 +布 +载 +靥 +嗬 +虽 +苹 +咨 +娄 +库 +雉 +榜 +帜 +嘲 +套 +瑚 +亲 +簸 +欧 +边 +6 +腿 +旮 +抛 +吹 +瞳 +得 +镓 +梗 +厨 +继 +漾 +愣 +憨 +士 +策 +窑 +抑 +躯 +襟 +脏 +参 +贸 +言 +干 +绸 +鳄 +穷 +藜 +音 +折 +详 +) +举 +悍 +甸 +癌 +黎 +谴 +死 +罩 +迁 +寒 +驷 +袖 +媒 +蒋 +掘 +模 +纠 +恣 +观 +祖 +蛆 +碍 +位 +稿 +主 +澧 +跌 +筏 +京 +锏 +帝 +贴 +证 +糠 +才 +黄 +鲸 +略 +炯 +饱 +四 +出 +园 +犀 +牧 +容 +汉 +杆 +浈 +汰 +瑷 +造 +虫 +瘩 +怪 +驴 +济 +应 +花 +沣 +谔 +夙 +旅 +价 +矿 +以 +考 +s +u +呦 +晒 +巡 +茅 +准 +肟 +瓴 +詹 +仟 +褂 +译 +桌 +混 +宁 +怦 +郑 +抿 +些 +余 +鄂 +饴 +攒 +珑 +群 +阖 +岔 +琨 +藓 +预 +环 +洮 +岌 +宀 +杲 +瀵 +最 +常 +囡 +周 +踊 +女 +鼓 +袭 +喉 +简 +范 +薯 +遐 +疏 +粱 +黜 +禧 +法 +箔 +斤 +遥 +汝 +奥 +直 +贞 +撑 +置 +绱 +集 +她 +馅 +逗 +钧 +橱 +魉 +[ +恙 +躁 +唤 +9 +旺 +膘 +待 +脾 +惫 +购 +吗 +依 +盲 +度 +瘿 +蠖 +俾 +之 +镗 +拇 +鲵 +厝 +簧 +续 +款 +展 +啃 +表 +剔 +品 +钻 +腭 +损 +清 +锶 +统 +涌 +寸 +滨 +贪 +链 +吠 +冈 +伎 +迥 +咏 +吁 +览 +防 +迅 +失 +汾 +阔 +逵 +绀 +蔑 +列 +川 +凭 +努 +熨 +揪 +利 +俱 +绉 +抢 +鸨 +我 +即 +责 +膦 +易 +毓 +鹊 +刹 +玷 +岿 +空 +嘞 +绊 +排 +术 +估 +锷 +违 +们 +苟 +铜 +播 +肘 +件 +烫 +审 +鲂 +广 +像 +铌 +惰 +铟 +巳 +胍 +鲍 +康 +憧 +色 +恢 +想 +拷 +尤 +疳 +知 +S +Y +F +D +A +峄 +裕 +帮 +握 +搔 +氐 +氘 +难 +墒 +沮 +雨 +叁 +缥 +悴 +藐 +湫 +娟 +苑 +稠 +颛 +簇 +后 +阕 +闭 +蕤 +缚 +怎 +佞 +码 +嘤 +蔡 +痊 +舱 +螯 +帕 +赫 +昵 +升 +烬 +岫 +、 +疵 +蜻 +髁 +蕨 +隶 +烛 +械 +丑 +盂 +梁 +强 +鲛 +由 +拘 +揉 +劭 +龟 +撤 +钩 +呕 +孛 +费 +妻 +漂 +求 +阑 +崖 +秤 +甘 +通 +深 +补 +赃 +坎 +床 +啪 +承 +吼 +量 +暇 +钼 +烨 +阂 +擎 +脱 +逮 +称 +P +神 +属 +矗 +华 +届 +狍 +葑 +汹 +育 +患 +窒 +蛰 +佼 +静 +槎 +运 +鳗 +庆 +逝 +曼 +疱 +克 +代 +官 +此 +麸 +耧 +蚌 +晟 +例 +础 +榛 +副 +测 +唰 +缢 +迹 +灬 +霁 +身 +岁 +赭 +扛 +又 +菡 +乜 +雾 +板 +读 +陷 +徉 +贯 +郁 +虑 +变 +钓 +菜 +圾 +现 +琢 +式 +乐 +维 +渔 +浜 +左 +吾 +脑 +钡 +警 +T +啵 +拴 +偌 +漱 +湿 +硕 +止 +骼 +魄 +积 +燥 +联 +踢 +玛 +则 +窿 +见 +振 +畿 +送 +班 +钽 +您 +赵 +刨 +印 +讨 +踝 +籍 +谡 +舌 +崧 +汽 +蔽 +沪 +酥 +绒 +怖 +财 +帖 +肱 +私 +莎 +勋 +羔 +霸 +励 +哼 +帐 +将 +帅 +渠 +纪 +婴 +娩 +岭 +厘 +滕 +吻 +伤 +坝 +冠 +戊 +隆 +瘁 +介 +涧 +物 +黍 +并 +姗 +奢 +蹑 +掣 +垸 +锴 +命 +箍 +捉 +病 +辖 +琰 +眭 +迩 +艘 +绌 +繁 +寅 +若 +毋 +思 +诉 +类 +诈 +燮 +轲 +酮 +狂 +重 +反 +职 +筱 +县 +委 +磕 +绣 +奖 +晋 +濉 +志 +徽 +肠 +呈 +獐 +坻 +口 +片 +碰 +几 +村 +柿 +劳 +料 +获 +亩 +惕 +晕 +厌 +号 +罢 +池 +正 +鏖 +煨 +家 +棕 +复 +尝 +懋 +蜥 +锅 +岛 +扰 +队 +坠 +瘾 +钬 +@ +卧 +疣 +镇 +譬 +冰 +彷 +频 +黯 +据 +垄 +采 +八 +缪 +瘫 +型 +熹 +砰 +楠 +襁 +箐 +但 +嘶 +绳 +啤 +拍 +盥 +穆 +傲 +洗 +盯 +塘 +怔 +筛 +丿 +台 +恒 +喂 +葛 +永 +¥ +烟 +酒 +桦 +书 +砂 +蚝 +缉 +态 +瀚 +袄 +圳 +轻 +蛛 +超 +榧 +遛 +姒 +奘 +铮 +右 +荽 +望 +偻 +卡 +丶 +氰 +附 +做 +革 +索 +戚 +坨 +桷 +唁 +垅 +榻 +岐 +偎 +坛 +莨 +山 +殊 +微 +骇 +陈 +爨 +推 +嗝 +驹 +澡 +藁 +呤 +卤 +嘻 +糅 +逛 +侵 +郓 +酌 +德 +摇 +※ +鬃 +被 +慨 +殡 +羸 +昌 +泡 +戛 +鞋 +河 +宪 +沿 +玲 +鲨 +翅 +哽 +源 +铅 +语 +照 +邯 +址 +荃 +佬 +顺 +鸳 +町 +霭 +睾 +瓢 +夸 +椁 +晓 +酿 +痈 +咔 +侏 +券 +噎 +湍 +签 +嚷 +离 +午 +尚 +社 +锤 +背 +孟 +使 +浪 +缦 +潍 +鞅 +军 +姹 +驶 +笑 +鳟 +鲁 +》 +孽 +钜 +绿 +洱 +礴 +焯 +椰 +颖 +囔 +乌 +孔 +巴 +互 +性 +椽 +哞 +聘 +昨 +早 +暮 +胶 +炀 +隧 +低 +彗 +昝 +铁 +呓 +氽 +藉 +喔 +癖 +瑗 +姨 +权 +胱 +韦 +堑 +蜜 +酋 +楝 +砝 +毁 +靓 +歙 +锲 +究 +屋 +喳 +骨 +辨 +碑 +武 +鸠 +宫 +辜 +烊 +适 +坡 +殃 +培 +佩 +供 +走 +蜈 +迟 +翼 +况 +姣 +凛 +浔 +吃 +飘 +债 +犟 +金 +促 +苛 +崇 +坂 +莳 +畔 +绂 +兵 +蠕 +斋 +根 +砍 +亢 +欢 +恬 +崔 +剁 +餐 +榫 +快 +扶 +‖ +濒 +缠 +鳜 +当 +彭 +驭 +浦 +篮 +昀 +锆 +秸 +钳 +弋 +娣 +瞑 +夷 +龛 +苫 +拱 +致 +% +嵊 +障 +隐 +弑 +初 +娓 +抉 +汩 +累 +蓖 +" +唬 +助 +苓 +昙 +押 +毙 +破 +城 +郧 +逢 +嚏 +獭 +瞻 +溱 +婿 +赊 +跨 +恼 +璧 +萃 +姻 +貉 +灵 +炉 +密 +氛 +陶 +砸 +谬 +衔 +点 +琛 +沛 +枳 +层 +岱 +诺 +脍 +榈 +埂 +征 +冷 +裁 +打 +蹴 +素 +瘘 +逞 +蛐 +聊 +激 +腱 +萘 +踵 +飒 +蓟 +吆 +取 +咙 +簋 +涓 +矩 +曝 +挺 +揣 +座 +你 +史 +舵 +焱 +尘 +苏 +笈 +脚 +溉 +榨 +诵 +樊 +邓 +焊 +义 +庶 +儋 +蟋 +蒲 +赦 +呷 +杞 +诠 +豪 +还 +试 +颓 +茉 +太 +除 +紫 +逃 +痴 +草 +充 +鳕 +珉 +祗 +墨 +渭 +烩 +蘸 +慕 +璇 +镶 +穴 +嵘 +恶 +骂 +险 +绋 +幕 +碉 +肺 +戳 +刘 +潞 +秣 +纾 +潜 +銮 +洛 +须 +罘 +销 +瘪 +汞 +兮 +屉 +r +林 +厕 +质 +探 +划 +狸 +殚 +善 +煊 +烹 +〒 +锈 +逯 +宸 +辍 +泱 +柚 +袍 +远 +蹋 +嶙 +绝 +峥 +娥 +缍 +雀 +徵 +认 +镱 +谷 += +贩 +勉 +撩 +鄯 +斐 +洋 +非 +祚 +泾 +诒 +饿 +撬 +威 +晷 +搭 +芍 +锥 +笺 +蓦 +候 +琊 +档 +礁 +沼 +卵 +荠 +忑 +朝 +凹 +瑞 +头 +仪 +弧 +孵 +畏 +铆 +突 +衲 +车 +浩 +气 +茂 +悖 +厢 +枕 +酝 +戴 +湾 +邹 +飚 +攘 +锂 +写 +宵 +翁 +岷 +无 +喜 +丈 +挑 +嗟 +绛 +殉 +议 +槽 +具 +醇 +淞 +笃 +郴 +阅 +饼 +底 +壕 +砚 +弈 +询 +缕 +庹 +翟 +零 +筷 +暨 +舟 +闺 +甯 +撞 +麂 +茌 +蔼 +很 +珲 +捕 +棠 +角 +阉 +媛 +娲 +诽 +剿 +尉 +爵 +睬 +韩 +诰 +匣 +危 +糍 +镯 +立 +浏 +阳 +少 +盆 +舔 +擘 +匪 +申 +尬 +铣 +旯 +抖 +赘 +瓯 +居 +ˇ +哮 +游 +锭 +茏 +歌 +坏 +甚 +秒 +舞 +沙 +仗 +劲 +潺 +阿 +燧 +郭 +嗖 +霏 +忠 +材 +奂 +耐 +跺 +砀 +输 +岖 +媳 +氟 +极 +摆 +灿 +今 +扔 +腻 +枝 +奎 +药 +熄 +吨 +话 +q +额 +慑 +嘌 +协 +喀 +壳 +埭 +视 +著 +於 +愧 +陲 +翌 +峁 +颅 +佛 +腹 +聋 +侯 +咎 +叟 +秀 +颇 +存 +较 +罪 +哄 +岗 +扫 +栏 +钾 +羌 +己 +璨 +枭 +霉 +煌 +涸 +衿 +键 +镝 +益 +岢 +奏 +连 +夯 +睿 +冥 +均 +糖 +狞 +蹊 +稻 +爸 +刿 +胥 +煜 +丽 +肿 +璃 +掸 +跚 +灾 +垂 +樾 +濑 +乎 +莲 +窄 +犹 +撮 +战 +馄 +软 +络 +显 +鸢 +胸 +宾 +妲 +恕 +埔 +蝌 +份 +遇 +巧 +瞟 +粒 +恰 +剥 +桡 +博 +讯 +凯 +堇 +阶 +滤 +卖 +斌 +骚 +彬 +兑 +磺 +樱 +舷 +两 +娱 +福 +仃 +差 +找 +桁 +÷ +净 +把 +阴 +污 +戬 +雷 +碓 +蕲 +楚 +罡 +焖 +抽 +妫 +咒 +仑 +闱 +尽 +邑 +菁 +爱 +贷 +沥 +鞑 +牡 +嗉 +崴 +骤 +塌 +嗦 +订 +拮 +滓 +捡 +锻 +次 +坪 +杩 +臃 +箬 +融 +珂 +鹗 +宗 +枚 +降 +鸬 +妯 +阄 +堰 +盐 +毅 +必 +杨 +崃 +俺 +甬 +状 +莘 +货 +耸 +菱 +腼 +铸 +唏 +痤 +孚 +澳 +懒 +溅 +翘 +疙 +杷 +淼 +缙 +骰 +喊 +悉 +砻 +坷 +艇 +赁 +界 +谤 +纣 +宴 +晃 +茹 +归 +饭 +梢 +铡 +街 +抄 +肼 +鬟 +苯 +颂 +撷 +戈 +炒 +咆 +茭 +瘙 +负 +仰 +客 +琉 +铢 +封 +卑 +珥 +椿 +镧 +窨 +鬲 +寿 +御 +袤 +铃 +萎 +砖 +餮 +脒 +裳 +肪 +孕 +嫣 +馗 +嵇 +恳 +氯 +江 +石 +褶 +冢 +祸 +阻 +狈 +羞 +银 +靳 +透 +咳 +叼 +敷 +芷 +啥 +它 +瓤 +兰 +痘 +懊 +逑 +肌 +往 +捺 +坊 +甩 +呻 +〃 +沦 +忘 +膻 +祟 +菅 +剧 +崆 +智 +坯 +臧 +霍 +墅 +攻 +眯 +倘 +拢 +骠 +铐 +庭 +岙 +瓠 +′ +缺 +泥 +迢 +捶 +? +? +郏 +喙 +掷 +沌 +纯 +秘 +种 +听 +绘 +固 +螨 +团 +香 +盗 +妒 +埚 +蓝 +拖 +旱 +荞 +铀 +血 +遏 +汲 +辰 +叩 +拽 +幅 +硬 +惶 +桀 +漠 +措 +泼 +唑 +齐 +肾 +念 +酱 +虚 +屁 +耶 +旗 +砦 +闵 +婉 +馆 +拭 +绅 +韧 +忏 +窝 +醋 +葺 +顾 +辞 +倜 +堆 +辋 +逆 +玟 +贱 +疾 +董 +惘 +倌 +锕 +淘 +嘀 +莽 +俭 +笏 +绑 +鲷 +杈 +择 +蟀 +粥 +嗯 +驰 +逾 +案 +谪 +褓 +胫 +哩 +昕 +颚 +鲢 +绠 +躺 +鹄 +崂 +儒 +俨 +丝 +尕 +泌 +啊 +萸 +彰 +幺 +吟 +骄 +苣 +弦 +脊 +瑰 +〈 +诛 +镁 +析 +闪 +剪 +侧 +哟 +框 +螃 +守 +嬗 +燕 +狭 +铈 +缮 +概 +迳 +痧 +鲲 +俯 +售 +笼 +痣 +扉 +挖 +满 +咋 +援 +邱 +扇 +歪 +便 +玑 +绦 +峡 +蛇 +叨 +〖 +泽 +胃 +斓 +喋 +怂 +坟 +猪 +该 +蚬 +炕 +弥 +赞 +棣 +晔 +娠 +挲 +狡 +创 +疖 +铕 +镭 +稷 +挫 +弭 +啾 +翔 +粉 +履 +苘 +哦 +楼 +秕 +铂 +土 +锣 +瘟 +挣 +栉 +习 +享 +桢 +袅 +磨 +桂 +谦 +延 +坚 +蔚 +噗 +署 +谟 +猬 +钎 +恐 +嬉 +雒 +倦 +衅 +亏 +璩 +睹 +刻 +殿 +王 +算 +雕 +麻 +丘 +柯 +骆 +丸 +塍 +谚 +添 +鲈 +垓 +桎 +蚯 +芥 +予 +飕 +镦 +谌 +窗 +醚 +菀 +亮 +搪 +莺 +蒿 +羁 +足 +J +真 +轶 +悬 +衷 +靛 +翊 +掩 +哒 +炅 +掐 +冼 +妮 +l +谐 +稚 +荆 +擒 +犯 +陵 +虏 +浓 +崽 +刍 +陌 +傻 +孜 +千 +靖 +演 +矜 +钕 +煽 +杰 +酗 +渗 +伞 +栋 +俗 +泫 +戍 +罕 +沾 +疽 +灏 +煦 +芬 +磴 +叱 +阱 +榉 +湃 +蜀 +叉 +醒 +彪 +租 +郡 +篷 +屎 +良 +垢 +隗 +弱 +陨 +峪 +砷 +掴 +颁 +胎 +雯 +绵 +贬 +沐 +撵 +隘 +篙 +暖 +曹 +陡 +栓 +填 +臼 +彦 +瓶 +琪 +潼 +哪 +鸡 +摩 +啦 +俟 +锋 +域 +耻 +蔫 +疯 +纹 +撇 +毒 +绶 +痛 +酯 +忍 +爪 +赳 +歆 +嘹 +辕 +烈 +册 +朴 +钱 +吮 +毯 +癜 +娃 +谀 +邵 +厮 +炽 +璞 +邃 +丐 +追 +词 +瓒 +忆 +轧 +芫 +谯 +喷 +弟 +半 +冕 +裙 +掖 +墉 +绮 +寝 +苔 +势 +顷 +褥 +切 +衮 +君 +佳 +嫒 +蚩 +霞 +佚 +洙 +逊 +镖 +暹 +唛 +& +殒 +顶 +碗 +獗 +轭 +铺 +蛊 +废 +恹 +汨 +崩 +珍 +那 +杵 +曲 +纺 +夏 +薰 +傀 +闳 +淬 +姘 +舀 +拧 +卷 +楂 +恍 +讪 +厩 +寮 +篪 +赓 +乘 +灭 +盅 +鞣 +沟 +慎 +挂 +饺 +鼾 +杳 +树 +缨 +丛 +絮 +娌 +臻 +嗳 +篡 +侩 +述 +衰 +矛 +圈 +蚜 +匕 +筹 +匿 +濞 +晨 +叶 +骋 +郝 +挚 +蚴 +滞 +增 +侍 +描 +瓣 +吖 +嫦 +蟒 +匾 +圣 +赌 +毡 +癞 +恺 +百 +曳 +需 +篓 +肮 +庖 +帏 +卿 +驿 +遗 +蹬 +鬓 +骡 +歉 +芎 +胳 +屐 +禽 +烦 +晌 +寄 +媾 +狄 +翡 +苒 +船 +廉 +终 +痞 +殇 +々 +畦 +饶 +改 +拆 +悻 +萄 +£ +瓿 +乃 +訾 +桅 +匮 +溧 +拥 +纱 +铍 +骗 +蕃 +龋 +缬 +父 +佐 +疚 +栎 +醍 +掳 +蓄 +x +惆 +颜 +鲆 +榆 +〔 +猎 +敌 +暴 +谥 +鲫 +贾 +罗 +玻 +缄 +扦 +芪 +癣 +落 +徒 +臾 +恿 +猩 +托 +邴 +肄 +牵 +春 +陛 +耀 +刊 +拓 +蓓 +邳 +堕 +寇 +枉 +淌 +啡 +湄 +兽 +酷 +萼 +碚 +濠 +萤 +夹 +旬 +戮 +梭 +琥 +椭 +昔 +勺 +蜊 +绐 +晚 +孺 +僵 +宣 +摄 +冽 +旨 +萌 +忙 +蚤 +眉 +噼 +蟑 +付 +契 +瓜 +悼 +颡 +壁 +曾 +窕 +颢 +澎 +仿 +俑 +浑 +嵌 +浣 +乍 +碌 +褪 +乱 +蔟 +隙 +玩 +剐 +葫 +箫 +纲 +围 +伐 +决 +伙 +漩 +瑟 +刑 +肓 +镳 +缓 +蹭 +氨 +皓 +典 +畲 +坍 +铑 +檐 +塑 +洞 +倬 +储 +胴 +淳 +戾 +吐 +灼 +惺 +妙 +毕 +珐 +缈 +虱 +盖 +羰 +鸿 +磅 +谓 +髅 +娴 +苴 +唷 +蚣 +霹 +抨 +贤 +唠 +犬 +誓 +逍 +庠 +逼 +麓 +籼 +釉 +呜 +碧 +秧 +氩 +摔 +霄 +穸 +纨 +辟 +妈 +映 +完 +牛 +缴 +嗷 +炊 +恩 +荔 +茆 +掉 +紊 +慌 +莓 +羟 +阙 +萁 +磐 +另 +蕹 +辱 +鳐 +湮 +吡 +吩 +唐 +睦 +垠 +舒 +圜 +冗 +瞿 +溺 +芾 +囱 +匠 +僳 +汐 +菩 +饬 +漓 +黑 +霰 +浸 +濡 +窥 +毂 +蒡 +兢 +驻 +鹉 +芮 +诙 +迫 +雳 +厂 +忐 +臆 +猴 +鸣 +蚪 +栈 +箕 +羡 +渐 +莆 +捍 +眈 +哓 +趴 +蹼 +埕 +嚣 +骛 +宏 +淄 +斑 +噜 +严 +瑛 +垃 +椎 +诱 +压 +庾 +绞 +焘 +廿 +抡 +迄 +棘 +夫 +纬 +锹 +眨 +瞌 +侠 +脐 +竞 +瀑 +孳 +骧 +遁 +姜 +颦 +荪 +滚 +萦 +伪 +逸 +粳 +爬 +锁 +矣 +役 +趣 +洒 +颔 +诏 +逐 +奸 +甭 +惠 +攀 +蹄 +泛 +尼 +拼 +阮 +鹰 +亚 +颈 +惑 +勒 +〉 +际 +肛 +爷 +刚 +钨 +丰 +养 +冶 +鲽 +辉 +蔻 +画 +覆 +皴 +妊 +麦 +返 +醉 +皂 +擀 +〗 +酶 +凑 +粹 +悟 +诀 +硖 +港 +卜 +z +杀 +涕 +± +舍 +铠 +抵 +弛 +段 +敝 +镐 +奠 +拂 +轴 +跛 +袱 +e +t +沉 +菇 +俎 +薪 +峦 +秭 +蟹 +历 +盟 +菠 +寡 +液 +肢 +喻 +染 +裱 +悱 +抱 +氙 +赤 +捅 +猛 +跑 +氮 +谣 +仁 +尺 +辊 +窍 +烙 +衍 +架 +擦 +倏 +璐 +瑁 +币 +楞 +胖 +夔 +趸 +邛 +惴 +饕 +虔 +蝎 +§ +哉 +贝 +宽 +辫 +炮 +扩 +饲 +籽 +魏 +菟 +锰 +伍 +猝 +末 +琳 +哚 +蛎 +邂 +呀 +姿 +鄞 +却 +歧 +仙 +恸 +椐 +森 +牒 +寤 +袒 +婆 +虢 +雅 +钉 +朵 +贼 +欲 +苞 +寰 +故 +龚 +坭 +嘘 +咫 +礼 +硷 +兀 +睢 +汶 +’ +铲 +烧 +绕 +诃 +浃 +钿 +哺 +柜 +讼 +颊 +璁 +腔 +洽 +咐 +脲 +簌 +筠 +镣 +玮 +鞠 +谁 +兼 +姆 +挥 +梯 +蝴 +谘 +漕 +刷 +躏 +宦 +弼 +b +垌 +劈 +麟 +莉 +揭 +笙 +渎 +仕 +嗤 +仓 +配 +怏 +抬 +错 +泯 +镊 +孰 +猿 +邪 +仍 +秋 +鼬 +壹 +歇 +吵 +炼 +< +尧 +射 +柬 +廷 +胧 +霾 +凳 +隋 +肚 +浮 +梦 +祥 +株 +堵 +退 +L +鹫 +跎 +凶 +毽 +荟 +炫 +栩 +玳 +甜 +沂 +鹿 +顽 +伯 +爹 +赔 +蛴 +徐 +匡 +欣 +狰 +缸 +雹 +蟆 +疤 +默 +沤 +啜 +痂 +衣 +禅 +w +i +h +辽 +葳 +黝 +钗 +停 +沽 +棒 +馨 +颌 +肉 +吴 +硫 +悯 +劾 +娈 +马 +啧 +吊 +悌 +镑 +峭 +帆 +瀣 +涉 +咸 +疸 +滋 +泣 +翦 +拙 +癸 +钥 +蜒 ++ +尾 +庄 +凝 +泉 +婢 +渴 +谊 +乞 +陆 +锉 +糊 +鸦 +淮 +I +B +N +晦 +弗 +乔 +庥 +葡 +尻 +席 +橡 +傣 +渣 +拿 +惩 +麋 +斛 +缃 +矮 +蛏 +岘 +鸽 +姐 +膏 +催 +奔 +镒 +喱 +蠡 +摧 +钯 +胤 +柠 +拐 +璋 +鸥 +卢 +荡 +倾 +^ +_ +珀 +逄 +萧 +塾 +掇 +贮 +笆 +聂 +圃 +冲 +嵬 +M +滔 +笕 +值 +炙 +偶 +蜱 +搐 +梆 +汪 +蔬 +腑 +鸯 +蹇 +敞 +绯 +仨 +祯 +谆 +梧 +糗 +鑫 +啸 +豺 +囹 +猾 +巢 +柄 +瀛 +筑 +踌 +沭 +暗 +苁 +鱿 +蹉 +脂 +蘖 +牢 +热 +木 +吸 +溃 +宠 +序 +泞 +偿 +拜 +檩 +厚 +朐 +毗 +螳 +吞 +媚 +朽 +担 +蝗 +橘 +畴 +祈 +糟 +盱 +隼 +郜 +惜 +珠 +裨 +铵 +焙 +琚 +唯 +咚 +噪 +骊 +丫 +滢 +勤 +棉 +呸 +咣 +淀 +隔 +蕾 +窈 +饨 +挨 +煅 +短 +匙 +粕 +镜 +赣 +撕 +墩 +酬 +馁 +豌 +颐 +抗 +酣 +氓 +佑 +搁 +哭 +递 +耷 +涡 +桃 +贻 +碣 +截 +瘦 +昭 +镌 +蔓 +氚 +甲 +猕 +蕴 +蓬 +散 +拾 +纛 +狼 +猷 +铎 +埋 +旖 +矾 +讳 +囊 +糜 +迈 +粟 +蚂 +紧 +鲳 +瘢 +栽 +稼 +羊 +锄 +斟 +睁 +桥 +瓮 +蹙 +祉 +醺 +鼻 +昱 +剃 +跳 +篱 +跷 +蒜 +翎 +宅 +晖 +嗑 +壑 +峻 +癫 +屏 +狠 +陋 +袜 +途 +憎 +祀 +莹 +滟 +佶 +溥 +臣 +约 +盛 +峰 +磁 +慵 +婪 +拦 +莅 +朕 +鹦 +粲 +裤 +哎 +疡 +嫖 +琵 +窟 +堪 +谛 +嘉 +儡 +鳝 +斩 +郾 +驸 +酊 +妄 +胜 +贺 +徙 +傅 +噌 +钢 +栅 +庇 +恋 +匝 +巯 +邈 +尸 +锚 +粗 +佟 +蛟 +薹 +纵 +蚊 +郅 +绢 +锐 +苗 +俞 +篆 +淆 +膀 +鲜 +煎 +诶 +秽 +寻 +涮 +刺 +怀 +噶 +巨 +褰 +魅 +灶 +灌 +桉 +藕 +谜 +舸 +薄 +搀 +恽 +借 +牯 +痉 +渥 +愿 +亓 +耘 +杠 +柩 +锔 +蚶 +钣 +珈 +喘 +蹒 +幽 +赐 +稗 +晤 +莱 +泔 +扯 +肯 +菪 +裆 +腩 +豉 +疆 +骜 +腐 +倭 +珏 +唔 +粮 +亡 +润 +慰 +伽 +橄 +玄 +誉 +醐 +胆 +龊 +粼 +塬 +陇 +彼 +削 +嗣 +绾 +芽 +妗 +垭 +瘴 +爽 +薏 +寨 +龈 +泠 +弹 +赢 +漪 +猫 +嘧 +涂 +恤 +圭 +茧 +烽 +屑 +痕 +巾 +赖 +荸 +凰 +腮 +畈 +亵 +蹲 +偃 +苇 +澜 +艮 +换 +骺 +烘 +苕 +梓 +颉 +肇 +哗 +悄 +氤 +涠 +葬 +屠 +鹭 +植 +竺 +佯 +诣 +鲇 +瘀 +鲅 +邦 +移 +滁 +冯 +耕 +癔 +戌 +茬 +沁 +巩 +悠 +湘 +洪 +痹 +锟 +循 +谋 +腕 +鳃 +钠 +捞 +焉 +迎 +碱 +伫 +急 +榷 +奈 +邝 +卯 +辄 +皲 +卟 +醛 +畹 +忧 +稳 +雄 +昼 +缩 +阈 +睑 +扌 +耗 +曦 +涅 +捏 +瞧 +邕 +淖 +漉 +铝 +耦 +禹 +湛 +喽 +莼 +琅 +诸 +苎 +纂 +硅 +始 +嗨 +傥 +燃 +臂 +赅 +嘈 +呆 +贵 +屹 +壮 +肋 +亍 +蚀 +卅 +豹 +腆 +邬 +迭 +浊 +} +童 +螂 +捐 +圩 +勐 +触 +寞 +汊 +壤 +荫 +膺 +渌 +芳 +懿 +遴 +螈 +泰 +蓼 +蛤 +茜 +舅 +枫 +朔 +膝 +眙 +避 +梅 +判 +鹜 +璜 +牍 +缅 +垫 +藻 +黔 +侥 +惚 +懂 +踩 +腰 +腈 +札 +丞 +唾 +慈 +顿 +摹 +荻 +琬 +~ +斧 +沈 +滂 +胁 +胀 +幄 +莜 +Z +匀 +鄄 +掌 +绰 +茎 +焚 +赋 +萱 +谑 +汁 +铒 +瞎 +夺 +蜗 +野 +娆 +冀 +弯 +篁 +懵 +灞 +隽 +芡 +脘 +俐 +辩 +芯 +掺 +喏 +膈 +蝈 +觐 +悚 +踹 +蔗 +熠 +鼠 +呵 +抓 +橼 +峨 +畜 +缔 +禾 +崭 +弃 +熊 +摒 +凸 +拗 +穹 +蒙 +抒 +祛 +劝 +闫 +扳 +阵 +醌 +踪 +喵 +侣 +搬 +仅 +荧 +赎 +蝾 +琦 +买 +婧 +瞄 +寓 +皎 +冻 +赝 +箩 +莫 +瞰 +郊 +笫 +姝 +筒 +枪 +遣 +煸 +袋 +舆 +痱 +涛 +母 +〇 +启 +践 +耙 +绲 +盘 +遂 +昊 +搞 +槿 +诬 +纰 +泓 +惨 +檬 +亻 +越 +C +o +憩 +熵 +祷 +钒 +暧 +塔 +阗 +胰 +咄 +娶 +魔 +琶 +钞 +邻 +扬 +杉 +殴 +咽 +弓 +〆 +髻 +】 +吭 +揽 +霆 +拄 +殖 +脆 +彻 +岩 +芝 +勃 +辣 +剌 +钝 +嘎 +甄 +佘 +皖 +伦 +授 +徕 +憔 +挪 +皇 +庞 +稔 +芜 +踏 +溴 +兖 +卒 +擢 +饥 +鳞 +煲 +‰ +账 +颗 +叻 +斯 +捧 +鳍 +琮 +讹 +蛙 +纽 +谭 +酸 +兔 +莒 +睇 +伟 +觑 +羲 +嗜 +宜 +褐 +旎 +辛 +卦 +诘 +筋 +鎏 +溪 +挛 +熔 +阜 +晰 +鳅 +丢 +奚 +灸 +呱 +献 +陉 +黛 +鸪 +甾 +萨 +疮 +拯 +洲 +疹 +辑 +叙 +恻 +谒 +允 +柔 +烂 +氏 +逅 +漆 +拎 +惋 +扈 +湟 +纭 +啕 +掬 +擞 +哥 +忽 +涤 +鸵 +靡 +郗 +瓷 +扁 +廊 +怨 +雏 +钮 +敦 +E +懦 +憋 +汀 +拚 +啉 +腌 +岸 +f +痼 +瞅 +尊 +咀 +眩 +飙 +忌 +仝 +迦 +熬 +毫 +胯 +篑 +茄 +腺 +凄 +舛 +碴 +锵 +诧 +羯 +後 +漏 +汤 +宓 +仞 +蚁 +壶 +谰 +皑 +铄 +棰 +罔 +辅 +晶 +苦 +牟 +闽 +\ +烃 +饮 +聿 +丙 +蛳 +朱 +煤 +涔 +鳖 +犁 +罐 +荼 +砒 +淦 +妤 +黏 +戎 +孑 +婕 +瑾 +戢 +钵 +枣 +捋 +砥 +衩 +狙 +桠 +稣 +阎 +肃 +梏 +诫 +孪 +昶 +婊 +衫 +嗔 +侃 +塞 +蜃 +樵 +峒 +貌 +屿 +欺 +缫 +阐 +栖 +诟 +珞 +荭 +吝 +萍 +嗽 +恂 +啻 +蜴 +磬 +峋 +俸 +豫 +谎 +徊 +镍 +韬 +魇 +晴 +U +囟 +猜 +蛮 +坐 +囿 +伴 +亭 +肝 +佗 +蝠 +妃 +胞 +滩 +榴 +氖 +垩 +苋 +砣 +扪 +馏 +姓 +轩 +厉 +夥 +侈 +禀 +垒 +岑 +赏 +钛 +辐 +痔 +披 +纸 +碳 +“ +坞 +蠓 +挤 +荥 +沅 +悔 +铧 +帼 +蒌 +蝇 +a +p +y +n +g +哀 +浆 +瑶 +凿 +桶 +馈 +皮 +奴 +苜 +佤 +伶 +晗 +铱 +炬 +优 +弊 +氢 +恃 +甫 +攥 +端 +锌 +灰 +稹 +炝 +曙 +邋 +亥 +眶 +碾 +拉 +萝 +绔 +捷 +浍 +腋 +姑 +菖 +凌 +涞 +麽 +锢 +桨 +潢 +绎 +镰 +殆 +锑 +渝 +铬 +困 +绽 +觎 +匈 +糙 +暑 +裹 +鸟 +盔 +肽 +迷 +綦 +『 +亳 +佝 +俘 +钴 +觇 +骥 +仆 +疝 +跪 +婶 +郯 +瀹 +唉 +脖 +踞 +针 +晾 +忒 +扼 +瞩 +叛 +椒 +疟 +嗡 +邗 +肆 +跆 +玫 +忡 +捣 +咧 +唆 +艄 +蘑 +潦 +笛 +阚 +沸 +泻 +掊 +菽 +贫 +斥 +髂 +孢 +镂 +赂 +麝 +鸾 +屡 +衬 +苷 +恪 +叠 +希 +粤 +爻 +喝 +茫 +惬 +郸 +绻 +庸 +撅 +碟 +宄 +妹 +膛 +叮 +饵 +崛 +嗲 +椅 +冤 +搅 +咕 +敛 +尹 +垦 +闷 +蝉 +霎 +勰 +败 +蓑 +泸 +肤 +鹌 +幌 +焦 +浠 +鞍 +刁 +舰 +乙 +竿 +裔 +。 +茵 +函 +伊 +兄 +丨 +娜 +匍 +謇 +莪 +宥 +似 +蝽 +翳 +酪 +翠 +粑 +薇 +祢 +骏 +赠 +叫 +Q +噤 +噻 +竖 +芗 +莠 +潭 +俊 +羿 +耜 +O +郫 +趁 +嗪 +囚 +蹶 +芒 +洁 +笋 +鹑 +敲 +硝 +啶 +堡 +渲 +揩 +』 +携 +宿 +遒 +颍 +扭 +棱 +割 +萜 +蔸 +葵 +琴 +捂 +饰 +衙 +耿 +掠 +募 +岂 +窖 +涟 +蔺 +瘤 +柞 +瞪 +怜 +匹 +距 +楔 +炜 +哆 +秦 +缎 +幼 +茁 +绪 +痨 +恨 +楸 +娅 +瓦 +桩 +雪 +嬴 +伏 +榔 +妥 +铿 +拌 +眠 +雍 +缇 +‘ +卓 +搓 +哌 +觞 +噩 +屈 +哧 +髓 +咦 +巅 +娑 +侑 +淫 +膳 +祝 +勾 +姊 +莴 +胄 +疃 +薛 +蜷 +胛 +巷 +芙 +芋 +熙 +闰 +勿 +窃 +狱 +剩 +钏 +幢 +陟 +铛 +慧 +靴 +耍 +k +浙 +浇 +飨 +惟 +绗 +祜 +澈 +啼 +咪 +磷 +摞 +诅 +郦 +抹 +跃 +壬 +吕 +肖 +琏 +颤 +尴 +剡 +抠 +凋 +赚 +泊 +津 +宕 +殷 +倔 +氲 +漫 +邺 +涎 +怠 +$ +垮 +荬 +遵 +俏 +叹 +噢 +饽 +蜘 +孙 +筵 +疼 +鞭 +羧 +牦 +箭 +潴 +c +眸 +祭 +髯 +啖 +坳 +愁 +芩 +驮 +倡 +巽 +穰 +沃 +胚 +怒 +凤 +槛 +剂 +趵 +嫁 +v +邢 +灯 +鄢 +桐 +睽 +檗 +锯 +槟 +婷 +嵋 +圻 +诗 +蕈 +颠 +遭 +痢 +芸 +怯 +馥 +竭 +锗 +徜 +恭 +遍 +籁 +剑 +嘱 +苡 +龄 +僧 +桑 +潸 +弘 +澶 +楹 +悲 +讫 +愤 +腥 +悸 +谍 +椹 +呢 +桓 +葭 +攫 +阀 +翰 +躲 +敖 +柑 +郎 +笨 +橇 +呃 +魁 +燎 +脓 +葩 +磋 +垛 +玺 +狮 +沓 +砜 +蕊 +锺 +罹 +蕉 +翱 +虐 +闾 +巫 +旦 +茱 +嬷 +枯 +鹏 +贡 +芹 +汛 +矫 +绁 +拣 +禺 +佃 +讣 +舫 +惯 +乳 +趋 +疲 +挽 +岚 +虾 +衾 +蠹 +蹂 +飓 +氦 +铖 +孩 +稞 +瑜 +壅 +掀 +勘 +妓 +畅 +髋 +W +庐 +牲 +蓿 +榕 +练 +垣 +唱 +邸 +菲 +昆 +婺 +穿 +绡 +麒 +蚱 +掂 +愚 +泷 +涪 +漳 +妩 +娉 +榄 +讷 +觅 +旧 +藤 +煮 +呛 +柳 +腓 +叭 +庵 +烷 +阡 +罂 +蜕 +擂 +猖 +咿 +媲 +脉 +【 +沏 +貅 +黠 +熏 +哲 +烁 +坦 +酵 +兜 +× +潇 +撒 +剽 +珩 +圹 +乾 +摸 +樟 +帽 +嗒 +襄 +魂 +轿 +憬 +锡 +〕 +喃 +皆 +咖 +隅 +脸 +残 +泮 +袂 +鹂 +珊 +囤 +捆 +咤 +误 +徨 +闹 +淙 +芊 +淋 +怆 +囗 +拨 +梳 +渤 +R +G +绨 +蚓 +婀 +幡 +狩 +麾 +谢 +唢 +裸 +旌 +伉 +纶 +裂 +驳 +砼 +咛 +澄 +樨 +蹈 +宙 +澍 +倍 +貔 +操 +勇 +蟠 +摈 +砧 +虬 +够 +缁 +悦 +藿 +撸 +艹 +摁 +淹 +豇 +虎 +榭 +ˉ +吱 +d +° +喧 +荀 +踱 +侮 +奋 +偕 +饷 +犍 +惮 +坑 +璎 +徘 +宛 +妆 +袈 +倩 +窦 +昂 +荏 +乖 +K +怅 +撰 +鳙 +牙 +袁 +酞 +X +痿 +琼 +闸 +雁 +趾 +荚 +虻 +涝 +《 +杏 +韭 +偈 +烤 +绫 +鞘 +卉 +症 +遢 +蓥 +诋 +杭 +荨 +匆 +竣 +簪 +辙 +敕 +虞 +丹 +缭 +咩 +黟 +m +淤 +瑕 +咂 +铉 +硼 +茨 +嶂 +痒 +畸 +敬 +涿 +粪 +窘 +熟 +叔 +嫔 +盾 +忱 +裘 +憾 +梵 +赡 +珙 +咯 +娘 +庙 +溯 +胺 +葱 +痪 +摊 +荷 +卞 +乒 +髦 +寐 +铭 +坩 +胗 +枷 +爆 +溟 +嚼 +羚 +砬 +轨 +惊 +挠 +罄 +竽 +菏 +氧 +浅 +楣 +盼 +枢 +炸 +阆 +杯 +谏 +噬 +淇 +渺 +俪 +秆 +墓 +泪 +跻 +砌 +痰 +垡 +渡 +耽 +釜 +讶 +鳎 +煞 +呗 +韶 +舶 +绷 +鹳 +缜 +旷 +铊 +皱 +龌 +檀 +霖 +奄 +槐 +艳 +蝶 +旋 +哝 +赶 +骞 +蚧 +腊 +盈 +丁 +` +蜚 +矸 +蝙 +睨 +嚓 +僻 +鬼 +醴 +夜 +彝 +磊 +笔 +拔 +栀 +糕 +厦 +邰 +纫 +逭 +纤 +眦 +膊 +馍 +躇 +烯 +蘼 +冬 +诤 +暄 +骶 +哑 +瘠 +」 +臊 +丕 +愈 +咱 +螺 +擅 +跋 +搏 +硪 +谄 +笠 +淡 +嘿 +骅 +谧 +鼎 +皋 +姚 +歼 +蠢 +驼 +耳 +胬 +挝 +涯 +狗 +蒽 +孓 +犷 +凉 +芦 +箴 +铤 +孤 +嘛 +坤 +V +茴 +朦 +挞 +尖 +橙 +诞 +搴 +碇 +洵 +浚 +帚 +蜍 +漯 +柘 +嚎 +讽 +芭 +荤 +咻 +祠 +秉 +跖 +埃 +吓 +糯 +眷 +馒 +惹 +娼 +鲑 +嫩 +讴 +轮 +瞥 +靶 +褚 +乏 +缤 +宋 +帧 +删 +驱 +碎 +扑 +俩 +俄 +偏 +涣 +竹 +噱 +皙 +佰 +渚 +唧 +斡 +# +镉 +刀 +崎 +筐 +佣 +夭 +贰 +肴 +峙 +哔 +艿 +匐 +牺 +镛 +缘 +仡 +嫡 +劣 +枸 +堀 +梨 +簿 +鸭 +蒸 +亦 +稽 +浴 +{ +衢 +束 +槲 +j +阁 +揍 +疥 +棋 +潋 +聪 +窜 +乓 +睛 +插 +冉 +阪 +苍 +搽 +「 +蟾 +螟 +幸 +仇 +樽 +撂 +慢 +跤 +幔 +俚 +淅 +覃 +觊 +溶 +妖 +帛 +侨 +曰 +妾 +泗 +· +: +瀘 +風 +Ë +( +) +∶ +紅 +紗 +瑭 +雲 +頭 +鶏 +財 +許 +• +¥ +樂 +焗 +麗 +— +; +滙 +東 +榮 +繪 +興 +… +門 +業 +π +楊 +國 +顧 +é +盤 +寳 +Λ +龍 +鳳 +島 +誌 +緣 +結 +銭 +萬 +勝 +祎 +璟 +優 +歡 +臨 +時 +購 += +★ +藍 +昇 +鐵 +觀 +勅 +農 +聲 +畫 +兿 +術 +發 +劉 +記 +專 +耑 +園 +書 +壴 +種 +Ο +● +褀 +號 +銀 +匯 +敟 +锘 +葉 +橪 +廣 +進 +蒄 +鑽 +阝 +祙 +貢 +鍋 +豊 +夬 +喆 +團 +閣 +開 +燁 +賓 +館 +酡 +沔 +順 ++ +硚 +劵 +饸 +陽 +車 +湓 +復 +萊 +氣 +軒 +華 +堃 +迮 +纟 +戶 +馬 +學 +裡 +電 +嶽 +獨 +マ +シ +サ +ジ +燘 +袪 +環 +❤ +臺 +灣 +専 +賣 +孖 +聖 +攝 +線 +▪ +α +傢 +俬 +夢 +達 +莊 +喬 +貝 +薩 +劍 +羅 +壓 +棛 +饦 +尃 +璈 +囍 +醫 +G +I +A +# +N +鷄 +髙 +嬰 +啓 +約 +隹 +潔 +賴 +藝 +~ +寶 +籣 +麺 +  +嶺 +√ +義 +網 +峩 +長 +∧ +魚 +機 +構 +② +鳯 +偉 +L +B +㙟 +畵 +鴿 +' +詩 +溝 +嚞 +屌 +藔 +佧 +玥 +蘭 +織 +1 +3 +9 +0 +7 +點 +砭 +鴨 +鋪 +銘 +廳 +弍 +‧ +創 +湯 +坶 +℃ +卩 +骝 +& +烜 +荘 +當 +潤 +扞 +係 +懷 +碶 +钅 +蚨 +讠 +☆ +叢 +爲 +埗 +涫 +塗 +→ +楽 +現 +鯨 +愛 +瑪 +鈺 +忄 +悶 +藥 +飾 +樓 +視 +孬 +ㆍ +燚 +苪 +師 +① +丼 +锽 +│ +韓 +標 +è +兒 +閏 +匋 +張 +漢 +Ü +髪 +會 +閑 +檔 +習 +裝 +の +峯 +菘 +輝 +И +雞 +釣 +億 +浐 +K +O +R +8 +H +E +P +T +W +D +S +C +M +F +姌 +饹 +» +晞 +廰 +ä +嵯 +鷹 +負 +飲 +絲 +冚 +楗 +澤 +綫 +區 +❋ +← +質 +靑 +揚 +③ +滬 +統 +産 +協 +﹑ +乸 +畐 +經 +運 +際 +洺 +岽 +為 +粵 +諾 +崋 +豐 +碁 +ɔ +V +2 +6 +齋 +誠 +訂 +´ +勑 +雙 +陳 +無 +í +泩 +媄 +夌 +刂 +i +c +t +o +r +a +嘢 +耄 +燴 +暃 +壽 +媽 +靈 +抻 +體 +唻 +É +冮 +甹 +鎮 +錦 +ʌ +蜛 +蠄 +尓 +駕 +戀 +飬 +逹 +倫 +貴 +極 +Я +Й +寬 +磚 +嶪 +郎 +職 +| +間 +n +d +剎 +伈 +課 +飛 +橋 +瘊 +№ +譜 +骓 +圗 +滘 +縣 +粿 +咅 +養 +濤 +彳 +® +% +Ⅱ +啰 +㴪 +見 +矞 +薬 +糁 +邨 +鲮 +顔 +罱 +З +選 +話 +贏 +氪 +俵 +競 +瑩 +繡 +枱 +β +綉 +á +獅 +爾 +™ +麵 +戋 +淩 +徳 +個 +劇 +場 +務 +簡 +寵 +h +實 +膠 +轱 +圖 +築 +嘣 +樹 +㸃 +營 +耵 +孫 +饃 +鄺 +飯 +麯 +遠 +輸 +坫 +孃 +乚 +閃 +鏢 +㎡ +題 +廠 +關 +↑ +爺 +將 +軍 +連 +篦 +覌 +參 +箸 +- +窠 +棽 +寕 +夀 +爰 +歐 +呙 +閥 +頡 +熱 +雎 +垟 +裟 +凬 +勁 +帑 +馕 +夆 +疌 +枼 +馮 +貨 +蒤 +樸 +彧 +旸 +靜 +龢 +暢 +㐱 +鳥 +珺 +鏡 +灡 +爭 +堷 +廚 +Ó +騰 +診 +┅ +蘇 +褔 +凱 +頂 +豕 +亞 +帥 +嘬 +⊥ +仺 +桖 +複 +饣 +絡 +穂 +顏 +棟 +納 +▏ +濟 +親 +設 +計 +攵 +埌 +烺 +ò +頤 +燦 +蓮 +撻 +節 +講 +濱 +濃 +娽 +洳 +朿 +燈 +鈴 +護 +膚 +铔 +過 +補 +Z +U +5 +4 +坋 +闿 +䖝 +餘 +缐 +铞 +貿 +铪 +桼 +趙 +鍊 +[ +㐂 +垚 +菓 +揸 +捲 +鐘 +滏 +𣇉 +爍 +輪 +燜 +鴻 +鮮 +動 +鹞 +鷗 +丄 +慶 +鉌 +翥 +飮 +腸 +⇋ +漁 +覺 +來 +熘 +昴 +翏 +鲱 +圧 +鄉 +萭 +頔 +爐 +嫚 +г +貭 +類 +聯 +幛 +輕 +訓 +鑒 +夋 +锨 +芃 +珣 +䝉 +扙 +嵐 +銷 +處 +ㄱ +語 +誘 +苝 +歸 +儀 +燒 +楿 +內 +粢 +葒 +奧 +麥 +礻 +滿 +蠔 +穵 +瞭 +態 +鱬 +榞 +硂 +鄭 +黃 +煙 +祐 +奓 +逺 +* +瑄 +獲 +聞 +薦 +讀 +這 +樣 +決 +問 +啟 +們 +執 +説 +轉 +單 +隨 +唘 +帶 +倉 +庫 +還 +贈 +尙 +皺 +■ +餅 +產 +○ +∈ +報 +狀 +楓 +賠 +琯 +嗮 +禮 +` +傳 +> +≤ +嗞 +Φ +≥ +換 +咭 +∣ +↓ +曬 +ε +応 +寫 +″ +終 +様 +純 +費 +療 +聨 +凍 +壐 +郵 +ü +黒 +∫ +製 +塊 +調 +軽 +確 +撃 +級 +馴 +Ⅲ +涇 +繹 +數 +碼 +證 +狒 +処 +劑 +< +晧 +賀 +衆 +] +櫥 +兩 +陰 +絶 +對 +鯉 +憶 +◎ +p +e +Y +蕒 +煖 +頓 +測 +試 +鼽 +僑 +碩 +妝 +帯 +≈ +鐡 +舖 +權 +喫 +倆 +ˋ +該 +悅 +ā +俫 +. +f +s +b +m +k +g +u +j +貼 +淨 +濕 +針 +適 +備 +l +/ +給 +謢 +強 +觸 +衛 +與 +⊙ +$ +緯 +變 +⑴ +⑵ +⑶ +㎏ +殺 +∩ +幚 +─ +價 +▲ +離 +ú +ó +飄 +烏 +関 +閟 +﹝ +﹞ +邏 +輯 +鍵 +驗 +訣 +導 +歷 +屆 +層 +▼ +儱 +錄 +熳 +ē +艦 +吋 +錶 +辧 +飼 +顯 +④ +禦 +販 +気 +対 +枰 +閩 +紀 +幹 +瞓 +貊 +淚 +△ +眞 +墊 +Ω +獻 +褲 +縫 +緑 +亜 +鉅 +餠 +{ +} +◆ +蘆 +薈 +█ +◇ +溫 +彈 +晳 +粧 +犸 +穩 +訊 +崬 +凖 +熥 +П +舊 +條 +紋 +圍 +Ⅳ +筆 +尷 +難 +雜 +錯 +綁 +識 +頰 +鎖 +艶 +□ +殁 +殼 +⑧ +├ +▕ +鵬 +ǐ +ō +ǒ +糝 +綱 +▎ +μ +盜 +饅 +醬 +籤 +蓋 +釀 +鹽 +據 +à +ɡ +辦 +◥ +彐 +┌ +婦 +獸 +鲩 +伱 +ī +蒟 +蒻 +齊 +袆 +腦 +寧 +凈 +妳 +煥 +詢 +偽 +謹 +啫 +鯽 +騷 +鱸 +損 +傷 +鎻 +髮 +買 +冏 +儥 +両 +﹢ +∞ +載 +喰 +z +羙 +悵 +燙 +曉 +員 +組 +徹 +艷 +痠 +鋼 +鼙 +縮 +細 +嚒 +爯 +≠ +維 +" +鱻 +壇 +厍 +帰 +浥 +犇 +薡 +軎 +² +應 +醜 +刪 +緻 +鶴 +賜 +噁 +軌 +尨 +镔 +鷺 +槗 +彌 +葚 +濛 +請 +溇 +緹 +賢 +訪 +獴 +瑅 +資 +縤 +陣 +蕟 +栢 +韻 +祼 +恁 +伢 +謝 +劃 +涑 +總 +衖 +踺 +砋 +凉 +籃 +駿 +苼 +瘋 +昽 +紡 +驊 +腎 +﹗ +響 +杋 +剛 +嚴 +禪 +歓 +槍 +傘 +檸 +檫 +炣 +勢 +鏜 +鎢 +銑 +尐 +減 +奪 +惡 +θ +僮 +婭 +臘 +ū +ì +殻 +鉄 +∑ +蛲 +焼 +緖 +續 +紹 +懮 \ No newline at end of file diff --git a/py/iopaint/model/anytext/utils.py b/py/iopaint/model/anytext/utils.py new file mode 100644 index 0000000..c9f55b8 --- /dev/null +++ b/py/iopaint/model/anytext/utils.py @@ -0,0 +1,151 @@ +import os +import datetime +import cv2 +import numpy as np +from PIL import Image, ImageDraw + + +def save_images(img_list, folder): + if not os.path.exists(folder): + os.makedirs(folder) + now = datetime.datetime.now() + date_str = now.strftime("%Y-%m-%d") + folder_path = os.path.join(folder, date_str) + if not os.path.exists(folder_path): + os.makedirs(folder_path) + time_str = now.strftime("%H_%M_%S") + for idx, img in enumerate(img_list): + image_number = idx + 1 + filename = f"{time_str}_{image_number}.jpg" + save_path = os.path.join(folder_path, filename) + cv2.imwrite(save_path, img[..., ::-1]) + + +def check_channels(image): + channels = image.shape[2] if len(image.shape) == 3 else 1 + if channels == 1: + image = cv2.cvtColor(image, cv2.COLOR_GRAY2BGR) + elif channels > 3: + image = image[:, :, :3] + return image + + +def resize_image(img, max_length=768): + height, width = img.shape[:2] + max_dimension = max(height, width) + + if max_dimension > max_length: + scale_factor = max_length / max_dimension + new_width = int(round(width * scale_factor)) + new_height = int(round(height * scale_factor)) + new_size = (new_width, new_height) + img = cv2.resize(img, new_size) + height, width = img.shape[:2] + img = cv2.resize(img, (width - (width % 64), height - (height % 64))) + return img + + +def insert_spaces(string, nSpace): + if nSpace == 0: + return string + new_string = "" + for char in string: + new_string += char + " " * nSpace + return new_string[:-nSpace] + + +def draw_glyph(font, text): + g_size = 50 + W, H = (512, 80) + new_font = font.font_variant(size=g_size) + img = Image.new(mode="1", size=(W, H), color=0) + draw = ImageDraw.Draw(img) + left, top, right, bottom = new_font.getbbox(text) + text_width = max(right - left, 5) + text_height = max(bottom - top, 5) + ratio = min(W * 0.9 / text_width, H * 0.9 / text_height) + new_font = font.font_variant(size=int(g_size * ratio)) + + text_width, text_height = new_font.getsize(text) + offset_x, offset_y = new_font.getoffset(text) + x = (img.width - text_width) // 2 + y = (img.height - text_height) // 2 - offset_y // 2 + draw.text((x, y), text, font=new_font, fill="white") + img = np.expand_dims(np.array(img), axis=2).astype(np.float64) + return img + + +def draw_glyph2( + font, text, polygon, vertAng=10, scale=1, width=512, height=512, add_space=True +): + enlarge_polygon = polygon * scale + rect = cv2.minAreaRect(enlarge_polygon) + box = cv2.boxPoints(rect) + box = np.int0(box) + w, h = rect[1] + angle = rect[2] + if angle < -45: + angle += 90 + angle = -angle + if w < h: + angle += 90 + + vert = False + if abs(angle) % 90 < vertAng or abs(90 - abs(angle) % 90) % 90 < vertAng: + _w = max(box[:, 0]) - min(box[:, 0]) + _h = max(box[:, 1]) - min(box[:, 1]) + if _h >= _w: + vert = True + angle = 0 + + img = np.zeros((height * scale, width * scale, 3), np.uint8) + img = Image.fromarray(img) + + # infer font size + image4ratio = Image.new("RGB", img.size, "white") + draw = ImageDraw.Draw(image4ratio) + _, _, _tw, _th = draw.textbbox(xy=(0, 0), text=text, font=font) + text_w = min(w, h) * (_tw / _th) + if text_w <= max(w, h): + # add space + if len(text) > 1 and not vert and add_space: + for i in range(1, 100): + text_space = insert_spaces(text, i) + _, _, _tw2, _th2 = draw.textbbox(xy=(0, 0), text=text_space, font=font) + if min(w, h) * (_tw2 / _th2) > max(w, h): + break + text = insert_spaces(text, i - 1) + font_size = min(w, h) * 0.80 + else: + shrink = 0.75 if vert else 0.85 + font_size = min(w, h) / (text_w / max(w, h)) * shrink + new_font = font.font_variant(size=int(font_size)) + + left, top, right, bottom = new_font.getbbox(text) + text_width = right - left + text_height = bottom - top + + layer = Image.new("RGBA", img.size, (0, 0, 0, 0)) + draw = ImageDraw.Draw(layer) + if not vert: + draw.text( + (rect[0][0] - text_width // 2, rect[0][1] - text_height // 2 - top), + text, + font=new_font, + fill=(255, 255, 255, 255), + ) + else: + x_s = min(box[:, 0]) + _w // 2 - text_height // 2 + y_s = min(box[:, 1]) + for c in text: + draw.text((x_s, y_s), c, font=new_font, fill=(255, 255, 255, 255)) + _, _t, _, _b = new_font.getbbox(c) + y_s += _b + + rotated_layer = layer.rotate(angle, expand=1, center=(rect[0][0], rect[0][1])) + + x_offset = int((img.width - rotated_layer.width) / 2) + y_offset = int((img.height - rotated_layer.height) / 2) + img.paste(rotated_layer, (x_offset, y_offset), rotated_layer) + img = np.expand_dims(np.array(img.convert("1")), axis=2).astype(np.float64) + return img diff --git a/py/iopaint/model/base.py b/py/iopaint/model/base.py new file mode 100644 index 0000000..e992e00 --- /dev/null +++ b/py/iopaint/model/base.py @@ -0,0 +1,418 @@ +import abc +from typing import Optional + +import cv2 +import torch +import numpy as np +from loguru import logger + +from ..helper import ( + boxes_from_mask, + resize_max_size, + pad_img_to_modulo, + switch_mps_device, +) +from ..schema import InpaintRequest, HDStrategy, SDSampler +from .helper.g_diffuser_bot import expand_image +from .utils import get_scheduler + + +class InpaintModel: + name = "base" + min_size: Optional[int] = None + pad_mod = 8 + pad_to_square = False + is_erase_model = False + + def __init__(self, device, **kwargs): + """ + + Args: + device: + """ + device = switch_mps_device(self.name, device) + self.device = device + self.init_model(device, **kwargs) + + @abc.abstractmethod + def init_model(self, device, **kwargs): + ... + + @staticmethod + @abc.abstractmethod + def is_downloaded() -> bool: + return False + + @abc.abstractmethod + def forward(self, image, mask, config: InpaintRequest): + """Input images and output images have same size + images: [H, W, C] RGB + masks: [H, W, 1] 255 为 masks 区域 + return: BGR IMAGE + """ + ... + + @staticmethod + def download(): + ... + + def _pad_forward(self, image, mask, config: InpaintRequest): + origin_height, origin_width = image.shape[:2] + pad_image = pad_img_to_modulo( + image, mod=self.pad_mod, square=self.pad_to_square, min_size=self.min_size + ) + pad_mask = pad_img_to_modulo( + mask, mod=self.pad_mod, square=self.pad_to_square, min_size=self.min_size + ) + + # logger.info(f"final forward pad size: {pad_image.shape}") + + image, mask = self.forward_pre_process(image, mask, config) + + result = self.forward(pad_image, pad_mask, config) + result = result[0:origin_height, 0:origin_width, :] + + result, image, mask = self.forward_post_process(result, image, mask, config) + + if config.sd_keep_unmasked_area: + mask = mask[:, :, np.newaxis] + result = result * (mask / 255) + image[:, :, ::-1] * (1 - (mask / 255)) + return result + + def forward_pre_process(self, image, mask, config): + return image, mask + + def forward_post_process(self, result, image, mask, config): + return result, image, mask + + @torch.no_grad() + def __call__(self, image, mask, config: InpaintRequest): + """ + images: [H, W, C] RGB, not normalized + masks: [H, W] + return: BGR IMAGE + """ + inpaint_result = None + # logger.info(f"hd_strategy: {config.hd_strategy}") + if config.hd_strategy == HDStrategy.CROP: + if max(image.shape) > config.hd_strategy_crop_trigger_size: + logger.info(f"Run crop strategy") + boxes = boxes_from_mask(mask) + crop_result = [] + for box in boxes: + crop_image, crop_box = self._run_box(image, mask, box, config) + crop_result.append((crop_image, crop_box)) + + inpaint_result = image[:, :, ::-1] + for crop_image, crop_box in crop_result: + x1, y1, x2, y2 = crop_box + inpaint_result[y1:y2, x1:x2, :] = crop_image + + elif config.hd_strategy == HDStrategy.RESIZE: + if max(image.shape) > config.hd_strategy_resize_limit: + origin_size = image.shape[:2] + downsize_image = resize_max_size( + image, size_limit=config.hd_strategy_resize_limit + ) + downsize_mask = resize_max_size( + mask, size_limit=config.hd_strategy_resize_limit + ) + + logger.info( + f"Run resize strategy, origin size: {image.shape} forward size: {downsize_image.shape}" + ) + inpaint_result = self._pad_forward( + downsize_image, downsize_mask, config + ) + + # only paste masked area result + inpaint_result = cv2.resize( + inpaint_result, + (origin_size[1], origin_size[0]), + interpolation=cv2.INTER_CUBIC, + ) + original_pixel_indices = mask < 127 + inpaint_result[original_pixel_indices] = image[:, :, ::-1][ + original_pixel_indices + ] + + if inpaint_result is None: + inpaint_result = self._pad_forward(image, mask, config) + + return inpaint_result + + def _crop_box(self, image, mask, box, config: InpaintRequest): + """ + + Args: + image: [H, W, C] RGB + mask: [H, W, 1] + box: [left,top,right,bottom] + + Returns: + BGR IMAGE, (l, r, r, b) + """ + box_h = box[3] - box[1] + box_w = box[2] - box[0] + cx = (box[0] + box[2]) // 2 + cy = (box[1] + box[3]) // 2 + img_h, img_w = image.shape[:2] + + w = box_w + config.hd_strategy_crop_margin * 2 + h = box_h + config.hd_strategy_crop_margin * 2 + + _l = cx - w // 2 + _r = cx + w // 2 + _t = cy - h // 2 + _b = cy + h // 2 + + l = max(_l, 0) + r = min(_r, img_w) + t = max(_t, 0) + b = min(_b, img_h) + + # try to get more context when crop around image edge + if _l < 0: + r += abs(_l) + if _r > img_w: + l -= _r - img_w + if _t < 0: + b += abs(_t) + if _b > img_h: + t -= _b - img_h + + l = max(l, 0) + r = min(r, img_w) + t = max(t, 0) + b = min(b, img_h) + + crop_img = image[t:b, l:r, :] + crop_mask = mask[t:b, l:r] + + # logger.info(f"box size: ({box_h},{box_w}) crop size: {crop_img.shape}") + + return crop_img, crop_mask, [l, t, r, b] + + def _calculate_cdf(self, histogram): + cdf = histogram.cumsum() + normalized_cdf = cdf / float(cdf.max()) + return normalized_cdf + + def _calculate_lookup(self, source_cdf, reference_cdf): + lookup_table = np.zeros(256) + lookup_val = 0 + for source_index, source_val in enumerate(source_cdf): + for reference_index, reference_val in enumerate(reference_cdf): + if reference_val >= source_val: + lookup_val = reference_index + break + lookup_table[source_index] = lookup_val + return lookup_table + + def _match_histograms(self, source, reference, mask): + transformed_channels = [] + if len(mask.shape) == 3: + mask = mask[:, :, -1] + + for channel in range(source.shape[-1]): + source_channel = source[:, :, channel] + reference_channel = reference[:, :, channel] + + # only calculate histograms for non-masked parts + source_histogram, _ = np.histogram(source_channel[mask == 0], 256, [0, 256]) + reference_histogram, _ = np.histogram( + reference_channel[mask == 0], 256, [0, 256] + ) + + source_cdf = self._calculate_cdf(source_histogram) + reference_cdf = self._calculate_cdf(reference_histogram) + + lookup = self._calculate_lookup(source_cdf, reference_cdf) + + transformed_channels.append(cv2.LUT(source_channel, lookup)) + + result = cv2.merge(transformed_channels) + result = cv2.convertScaleAbs(result) + + return result + + def _apply_cropper(self, image, mask, config: InpaintRequest): + img_h, img_w = image.shape[:2] + l, t, w, h = ( + config.croper_x, + config.croper_y, + config.croper_width, + config.croper_height, + ) + r = l + w + b = t + h + + l = max(l, 0) + r = min(r, img_w) + t = max(t, 0) + b = min(b, img_h) + + crop_img = image[t:b, l:r, :] + crop_mask = mask[t:b, l:r] + return crop_img, crop_mask, (l, t, r, b) + + def _run_box(self, image, mask, box, config: InpaintRequest): + """ + + Args: + image: [H, W, C] RGB + mask: [H, W, 1] + box: [left,top,right,bottom] + + Returns: + BGR IMAGE + """ + crop_img, crop_mask, [l, t, r, b] = self._crop_box(image, mask, box, config) + + return self._pad_forward(crop_img, crop_mask, config), [l, t, r, b] + + +class DiffusionInpaintModel(InpaintModel): + def __init__(self, device, **kwargs): + self.model_info = kwargs["model_info"] + self.model_id_or_path = self.model_info.path + super().__init__(device, **kwargs) + + @torch.no_grad() + def __call__(self, image, mask, config: InpaintRequest): + """ + images: [H, W, C] RGB, not normalized + masks: [H, W] + return: BGR IMAGE + """ + # boxes = boxes_from_mask(mask) + if config.use_croper: + crop_img, crop_mask, (l, t, r, b) = self._apply_cropper(image, mask, config) + crop_image = self._scaled_pad_forward(crop_img, crop_mask, config) + inpaint_result = image[:, :, ::-1] + inpaint_result[t:b, l:r, :] = crop_image + elif config.use_extender: + inpaint_result = self._do_outpainting(image, config) + else: + inpaint_result = self._scaled_pad_forward(image, mask, config) + + return inpaint_result + + def _do_outpainting(self, image, config: InpaintRequest): + # cropper 和 image 在同一个坐标系下,croper_x/y 可能为负数 + # 从 image 中 crop 出 outpainting 区域 + image_h, image_w = image.shape[:2] + cropper_l = config.extender_x + cropper_t = config.extender_y + cropper_r = config.extender_x + config.extender_width + cropper_b = config.extender_y + config.extender_height + image_l = 0 + image_t = 0 + image_r = image_w + image_b = image_h + + # 类似求 IOU + l = max(cropper_l, image_l) + t = max(cropper_t, image_t) + r = min(cropper_r, image_r) + b = min(cropper_b, image_b) + + assert ( + 0 <= l < r and 0 <= t < b + ), f"cropper and image not overlap, {l},{t},{r},{b}" + + cropped_image = image[t:b, l:r, :] + padding_l = max(0, image_l - cropper_l) + padding_t = max(0, image_t - cropper_t) + padding_r = max(0, cropper_r - image_r) + padding_b = max(0, cropper_b - image_b) + + expanded_image, mask_image = expand_image( + cropped_image, + left=padding_l, + top=padding_t, + right=padding_r, + bottom=padding_b, + softness=config.sd_outpainting_softness, + space=config.sd_outpainting_space, + ) + + # 最终扩大了的 image, BGR + expanded_cropped_result_image = self._scaled_pad_forward( + expanded_image, mask_image, config + ) + + # RGB -> BGR + outpainting_image = cv2.copyMakeBorder( + image, + left=padding_l, + top=padding_t, + right=padding_r, + bottom=padding_b, + borderType=cv2.BORDER_CONSTANT, + value=0, + )[:, :, ::-1] + + # 把 cropped_result_image 贴到 outpainting_image 上,这一步不需要 blend + paste_t = 0 if config.extender_y < 0 else config.extender_y + paste_l = 0 if config.extender_x < 0 else config.extender_x + + outpainting_image[ + paste_t : paste_t + expanded_cropped_result_image.shape[0], + paste_l : paste_l + expanded_cropped_result_image.shape[1], + :, + ] = expanded_cropped_result_image + return outpainting_image + + def _scaled_pad_forward(self, image, mask, config: InpaintRequest): + longer_side_length = int(config.sd_scale * max(image.shape[:2])) + origin_size = image.shape[:2] + downsize_image = resize_max_size(image, size_limit=longer_side_length) + downsize_mask = resize_max_size(mask, size_limit=longer_side_length) + if config.sd_scale != 1: + logger.info( + f"Resize image to do sd inpainting: {image.shape} -> {downsize_image.shape}" + ) + inpaint_result = self._pad_forward(downsize_image, downsize_mask, config) + # only paste masked area result + inpaint_result = cv2.resize( + inpaint_result, + (origin_size[1], origin_size[0]), + interpolation=cv2.INTER_CUBIC, + ) + + # blend result, copy from g_diffuser_bot + # mask_rgb = 1.0 - np_img_grey_to_rgb(mask / 255.0) + # inpaint_result = np.clip( + # inpaint_result * (1.0 - mask_rgb) + image * mask_rgb, 0.0, 255.0 + # ) + # original_pixel_indices = mask < 127 + # inpaint_result[original_pixel_indices] = image[:, :, ::-1][ + # original_pixel_indices + # ] + return inpaint_result + + def set_scheduler(self, config: InpaintRequest): + scheduler_config = self.model.scheduler.config + sd_sampler = config.sd_sampler + if config.sd_lcm_lora and self.model_info.support_lcm_lora: + sd_sampler = SDSampler.lcm + logger.info(f"LCM Lora enabled, use {sd_sampler} sampler") + scheduler = get_scheduler(sd_sampler, scheduler_config) + self.model.scheduler = scheduler + + def forward_pre_process(self, image, mask, config): + if config.sd_mask_blur != 0: + k = 2 * config.sd_mask_blur + 1 + mask = cv2.GaussianBlur(mask, (k, k), 0) + + return image, mask + + def forward_post_process(self, result, image, mask, config): + if config.sd_match_histograms: + result = self._match_histograms(result, image[:, :, ::-1], mask) + + # if config.sd_mask_blur != 0: + # k = 2 * config.sd_mask_blur + 1 + # mask = cv2.GaussianBlur(mask, (k, k), 0) + return result, image, mask diff --git a/py/iopaint/model/controlnet.py b/py/iopaint/model/controlnet.py new file mode 100644 index 0000000..74453ad --- /dev/null +++ b/py/iopaint/model/controlnet.py @@ -0,0 +1,190 @@ +import PIL.Image +import cv2 +import torch +from diffusers import ControlNetModel +from loguru import logger +from ..schema import InpaintRequest, ModelType + +from .base import DiffusionInpaintModel +from .helper.controlnet_preprocess import ( + make_canny_control_image, + make_openpose_control_image, + make_depth_control_image, + make_inpaint_control_image, +) +from .helper.cpu_text_encoder import CPUTextEncoderWrapper +from .original_sd_configs import get_config_files +from .utils import ( + get_scheduler, + handle_from_pretrained_exceptions, + get_torch_dtype, + enable_low_mem, + is_local_files_only, +) + + +class ControlNet(DiffusionInpaintModel): + name = "controlnet" + pad_mod = 8 + min_size = 512 + + @property + def lcm_lora_id(self): + if self.model_info.model_type in [ + ModelType.DIFFUSERS_SD, + ModelType.DIFFUSERS_SD_INPAINT, + ]: + return "latent-consistency/lcm-lora-sdv1-5" + if self.model_info.model_type in [ + ModelType.DIFFUSERS_SDXL, + ModelType.DIFFUSERS_SDXL_INPAINT, + ]: + return "latent-consistency/lcm-lora-sdxl" + raise NotImplementedError(f"Unsupported controlnet lcm model {self.model_info}") + + def init_model(self, device: torch.device, **kwargs): + model_info = kwargs["model_info"] + controlnet_method = kwargs["controlnet_method"] + + self.model_info = model_info + self.controlnet_method = controlnet_method + + model_kwargs = { + **kwargs.get("pipe_components", {}), + "local_files_only": is_local_files_only(**kwargs), + } + self.local_files_only = model_kwargs["local_files_only"] + + disable_nsfw_checker = kwargs["disable_nsfw"] or kwargs.get( + "cpu_offload", False + ) + if disable_nsfw_checker: + logger.info("Disable Stable Diffusion Model NSFW checker") + model_kwargs.update( + dict( + safety_checker=None, + feature_extractor=None, + requires_safety_checker=False, + ) + ) + + use_gpu, torch_dtype = get_torch_dtype(device, kwargs.get("no_half", False)) + self.torch_dtype = torch_dtype + + if model_info.model_type in [ + ModelType.DIFFUSERS_SD, + ModelType.DIFFUSERS_SD_INPAINT, + ]: + from diffusers import ( + StableDiffusionControlNetInpaintPipeline as PipeClass, + ) + elif model_info.model_type in [ + ModelType.DIFFUSERS_SDXL, + ModelType.DIFFUSERS_SDXL_INPAINT, + ]: + from diffusers import ( + StableDiffusionXLControlNetInpaintPipeline as PipeClass, + ) + + controlnet = ControlNetModel.from_pretrained( + pretrained_model_name_or_path=controlnet_method, + resume_download=True, + local_files_only=model_kwargs["local_files_only"], + torch_dtype=self.torch_dtype, + ) + if model_info.is_single_file_diffusers: + if self.model_info.model_type == ModelType.DIFFUSERS_SD: + model_kwargs["num_in_channels"] = 4 + else: + model_kwargs["num_in_channels"] = 9 + + self.model = PipeClass.from_single_file( + model_info.path, + controlnet=controlnet, + load_safety_checker=not disable_nsfw_checker, + torch_dtype=torch_dtype, + config_files=get_config_files(), + **model_kwargs, + ) + else: + self.model = handle_from_pretrained_exceptions( + PipeClass.from_pretrained, + pretrained_model_name_or_path=model_info.path, + controlnet=controlnet, + variant="fp16", + torch_dtype=torch_dtype, + **model_kwargs, + ) + + enable_low_mem(self.model, kwargs.get("low_mem", False)) + + if kwargs.get("cpu_offload", False) and use_gpu: + logger.info("Enable sequential cpu offload") + self.model.enable_sequential_cpu_offload(gpu_id=0) + else: + self.model = self.model.to(device) + if kwargs["sd_cpu_textencoder"]: + logger.info("Run Stable Diffusion TextEncoder on CPU") + self.model.text_encoder = CPUTextEncoderWrapper( + self.model.text_encoder, torch_dtype + ) + + self.callback = kwargs.pop("callback", None) + + def switch_controlnet_method(self, new_method: str): + self.controlnet_method = new_method + controlnet = ControlNetModel.from_pretrained( + new_method, + resume_download=True, + local_files_only=self.local_files_only, + torch_dtype=self.torch_dtype, + ).to(self.model.device) + self.model.controlnet = controlnet + + def _get_control_image(self, image, mask): + if "canny" in self.controlnet_method: + control_image = make_canny_control_image(image) + elif "openpose" in self.controlnet_method: + control_image = make_openpose_control_image(image) + elif "depth" in self.controlnet_method: + control_image = make_depth_control_image(image) + elif "inpaint" in self.controlnet_method: + control_image = make_inpaint_control_image(image, mask) + else: + raise NotImplementedError(f"{self.controlnet_method} not implemented") + return control_image + + def forward(self, image, mask, config: InpaintRequest): + """Input image and output image have same size + image: [H, W, C] RGB + mask: [H, W, 1] 255 means area to repaint + return: BGR IMAGE + """ + scheduler_config = self.model.scheduler.config + scheduler = get_scheduler(config.sd_sampler, scheduler_config) + self.model.scheduler = scheduler + + img_h, img_w = image.shape[:2] + control_image = self._get_control_image(image, mask) + mask_image = PIL.Image.fromarray(mask[:, :, -1], mode="L") + image = PIL.Image.fromarray(image) + + output = self.model( + image=image, + mask_image=mask_image, + control_image=control_image, + prompt=config.prompt, + negative_prompt=config.negative_prompt, + num_inference_steps=config.sd_steps, + guidance_scale=config.sd_guidance_scale, + output_type="np", + callback_on_step_end=self.callback, + height=img_h, + width=img_w, + generator=torch.manual_seed(config.sd_seed), + controlnet_conditioning_scale=config.controlnet_conditioning_scale, + ).images[0] + + output = (output * 255).round().astype("uint8") + output = cv2.cvtColor(output, cv2.COLOR_RGB2BGR) + return output diff --git a/py/iopaint/model/ddim_sampler.py b/py/iopaint/model/ddim_sampler.py new file mode 100644 index 0000000..a3f44fd --- /dev/null +++ b/py/iopaint/model/ddim_sampler.py @@ -0,0 +1,193 @@ +import torch +import numpy as np +from tqdm import tqdm + +from .utils import make_ddim_timesteps, make_ddim_sampling_parameters, noise_like + +from loguru import logger + + +class DDIMSampler(object): + def __init__(self, model, schedule="linear"): + super().__init__() + self.model = model + self.ddpm_num_timesteps = model.num_timesteps + self.schedule = schedule + + def register_buffer(self, name, attr): + setattr(self, name, attr) + + def make_schedule( + self, ddim_num_steps, ddim_discretize="uniform", ddim_eta=0.0, verbose=True + ): + self.ddim_timesteps = make_ddim_timesteps( + ddim_discr_method=ddim_discretize, + num_ddim_timesteps=ddim_num_steps, + # array([1]) + num_ddpm_timesteps=self.ddpm_num_timesteps, + verbose=verbose, + ) + alphas_cumprod = self.model.alphas_cumprod # torch.Size([1000]) + assert ( + alphas_cumprod.shape[0] == self.ddpm_num_timesteps + ), "alphas have to be defined for each timestep" + to_torch = lambda x: x.clone().detach().to(torch.float32).to(self.model.device) + + self.register_buffer("betas", to_torch(self.model.betas)) + self.register_buffer("alphas_cumprod", to_torch(alphas_cumprod)) + self.register_buffer( + "alphas_cumprod_prev", to_torch(self.model.alphas_cumprod_prev) + ) + + # calculations for diffusion q(x_t | x_{t-1}) and others + self.register_buffer( + "sqrt_alphas_cumprod", to_torch(np.sqrt(alphas_cumprod.cpu())) + ) + self.register_buffer( + "sqrt_one_minus_alphas_cumprod", + to_torch(np.sqrt(1.0 - alphas_cumprod.cpu())), + ) + self.register_buffer( + "log_one_minus_alphas_cumprod", to_torch(np.log(1.0 - alphas_cumprod.cpu())) + ) + self.register_buffer( + "sqrt_recip_alphas_cumprod", to_torch(np.sqrt(1.0 / alphas_cumprod.cpu())) + ) + self.register_buffer( + "sqrt_recipm1_alphas_cumprod", + to_torch(np.sqrt(1.0 / alphas_cumprod.cpu() - 1)), + ) + + # ddim sampling parameters + ddim_sigmas, ddim_alphas, ddim_alphas_prev = make_ddim_sampling_parameters( + alphacums=alphas_cumprod.cpu(), + ddim_timesteps=self.ddim_timesteps, + eta=ddim_eta, + verbose=verbose, + ) + self.register_buffer("ddim_sigmas", ddim_sigmas) + self.register_buffer("ddim_alphas", ddim_alphas) + self.register_buffer("ddim_alphas_prev", ddim_alphas_prev) + self.register_buffer("ddim_sqrt_one_minus_alphas", np.sqrt(1.0 - ddim_alphas)) + sigmas_for_original_sampling_steps = ddim_eta * torch.sqrt( + (1 - self.alphas_cumprod_prev) + / (1 - self.alphas_cumprod) + * (1 - self.alphas_cumprod / self.alphas_cumprod_prev) + ) + self.register_buffer( + "ddim_sigmas_for_original_num_steps", sigmas_for_original_sampling_steps + ) + + @torch.no_grad() + def sample(self, steps, conditioning, batch_size, shape): + self.make_schedule(ddim_num_steps=steps, ddim_eta=0, verbose=False) + # sampling + C, H, W = shape + size = (batch_size, C, H, W) + + # samples: 1,3,128,128 + return self.ddim_sampling( + conditioning, + size, + quantize_denoised=False, + ddim_use_original_steps=False, + noise_dropout=0, + temperature=1.0, + ) + + @torch.no_grad() + def ddim_sampling( + self, + cond, + shape, + ddim_use_original_steps=False, + quantize_denoised=False, + temperature=1.0, + noise_dropout=0.0, + ): + device = self.model.betas.device + b = shape[0] + img = torch.randn(shape, device=device, dtype=cond.dtype) + timesteps = ( + self.ddpm_num_timesteps if ddim_use_original_steps else self.ddim_timesteps + ) + + time_range = ( + reversed(range(0, timesteps)) + if ddim_use_original_steps + else np.flip(timesteps) + ) + total_steps = timesteps if ddim_use_original_steps else timesteps.shape[0] + logger.info(f"Running DDIM Sampling with {total_steps} timesteps") + + iterator = tqdm(time_range, desc="DDIM Sampler", total=total_steps) + + for i, step in enumerate(iterator): + index = total_steps - i - 1 + ts = torch.full((b,), step, device=device, dtype=torch.long) + + outs = self.p_sample_ddim( + img, + cond, + ts, + index=index, + use_original_steps=ddim_use_original_steps, + quantize_denoised=quantize_denoised, + temperature=temperature, + noise_dropout=noise_dropout, + ) + img, _ = outs + + return img + + @torch.no_grad() + def p_sample_ddim( + self, + x, + c, + t, + index, + repeat_noise=False, + use_original_steps=False, + quantize_denoised=False, + temperature=1.0, + noise_dropout=0.0, + ): + b, *_, device = *x.shape, x.device + e_t = self.model.apply_model(x, t, c) + + alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas + alphas_prev = ( + self.model.alphas_cumprod_prev + if use_original_steps + else self.ddim_alphas_prev + ) + sqrt_one_minus_alphas = ( + self.model.sqrt_one_minus_alphas_cumprod + if use_original_steps + else self.ddim_sqrt_one_minus_alphas + ) + sigmas = ( + self.model.ddim_sigmas_for_original_num_steps + if use_original_steps + else self.ddim_sigmas + ) + # select parameters corresponding to the currently considered timestep + a_t = torch.full((b, 1, 1, 1), alphas[index], device=device) + a_prev = torch.full((b, 1, 1, 1), alphas_prev[index], device=device) + sigma_t = torch.full((b, 1, 1, 1), sigmas[index], device=device) + sqrt_one_minus_at = torch.full( + (b, 1, 1, 1), sqrt_one_minus_alphas[index], device=device + ) + + # current prediction for x_0 + pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt() + if quantize_denoised: # 没用 + pred_x0, _, *_ = self.model.first_stage_model.quantize(pred_x0) + # direction pointing to x_t + dir_xt = (1.0 - a_prev - sigma_t ** 2).sqrt() * e_t + noise = sigma_t * noise_like(x.shape, device, repeat_noise) * temperature + if noise_dropout > 0.0: # 没用 + noise = torch.nn.functional.dropout(noise, p=noise_dropout) + x_prev = a_prev.sqrt() * pred_x0 + dir_xt + noise + return x_prev, pred_x0 diff --git a/py/iopaint/model/fcf.py b/py/iopaint/model/fcf.py new file mode 100644 index 0000000..0eb2c1f --- /dev/null +++ b/py/iopaint/model/fcf.py @@ -0,0 +1,1737 @@ +import os +import random + +import cv2 +import torch +import numpy as np +import torch.fft as fft + +from ..schema import InpaintRequest + +from ..helper import ( + load_model, + get_cache_path_by_url, + norm_img, + boxes_from_mask, + resize_max_size, + download_model, +) +from .base import InpaintModel +from torch import conv2d, nn +import torch.nn.functional as F + +from .utils import ( + setup_filter, + _parse_scaling, + _parse_padding, + Conv2dLayer, + FullyConnectedLayer, + MinibatchStdLayer, + activation_funcs, + conv2d_resample, + bias_act, + upsample2d, + normalize_2nd_moment, + downsample2d, +) + + +def upfirdn2d(x, f, up=1, down=1, padding=0, flip_filter=False, gain=1, impl="cuda"): + assert isinstance(x, torch.Tensor) + return _upfirdn2d_ref( + x, f, up=up, down=down, padding=padding, flip_filter=flip_filter, gain=gain + ) + + +def _upfirdn2d_ref(x, f, up=1, down=1, padding=0, flip_filter=False, gain=1): + """Slow reference implementation of `upfirdn2d()` using standard PyTorch ops.""" + # Validate arguments. + assert isinstance(x, torch.Tensor) and x.ndim == 4 + if f is None: + f = torch.ones([1, 1], dtype=torch.float32, device=x.device) + assert isinstance(f, torch.Tensor) and f.ndim in [1, 2] + assert f.dtype == torch.float32 and not f.requires_grad + batch_size, num_channels, in_height, in_width = x.shape + upx, upy = _parse_scaling(up) + downx, downy = _parse_scaling(down) + padx0, padx1, pady0, pady1 = _parse_padding(padding) + + # Upsample by inserting zeros. + x = x.reshape([batch_size, num_channels, in_height, 1, in_width, 1]) + x = torch.nn.functional.pad(x, [0, upx - 1, 0, 0, 0, upy - 1]) + x = x.reshape([batch_size, num_channels, in_height * upy, in_width * upx]) + + # Pad or crop. + x = torch.nn.functional.pad( + x, [max(padx0, 0), max(padx1, 0), max(pady0, 0), max(pady1, 0)] + ) + x = x[ + :, + :, + max(-pady0, 0) : x.shape[2] - max(-pady1, 0), + max(-padx0, 0) : x.shape[3] - max(-padx1, 0), + ] + + # Setup filter. + f = f * (gain ** (f.ndim / 2)) + f = f.to(x.dtype) + if not flip_filter: + f = f.flip(list(range(f.ndim))) + + # Convolve with the filter. + f = f[np.newaxis, np.newaxis].repeat([num_channels, 1] + [1] * f.ndim) + if f.ndim == 4: + x = conv2d(input=x, weight=f, groups=num_channels) + else: + x = conv2d(input=x, weight=f.unsqueeze(2), groups=num_channels) + x = conv2d(input=x, weight=f.unsqueeze(3), groups=num_channels) + + # Downsample by throwing away pixels. + x = x[:, :, ::downy, ::downx] + return x + + +class EncoderEpilogue(torch.nn.Module): + def __init__( + self, + in_channels, # Number of input channels. + cmap_dim, # Dimensionality of mapped conditioning label, 0 = no label. + z_dim, # Output Latent (Z) dimensionality. + resolution, # Resolution of this block. + img_channels, # Number of input color channels. + architecture="resnet", # Architecture: 'orig', 'skip', 'resnet'. + mbstd_group_size=4, # Group size for the minibatch standard deviation layer, None = entire minibatch. + mbstd_num_channels=1, # Number of features for the minibatch standard deviation layer, 0 = disable. + activation="lrelu", # Activation function: 'relu', 'lrelu', etc. + conv_clamp=None, # Clamp the output of convolution layers to +-X, None = disable clamping. + ): + assert architecture in ["orig", "skip", "resnet"] + super().__init__() + self.in_channels = in_channels + self.cmap_dim = cmap_dim + self.resolution = resolution + self.img_channels = img_channels + self.architecture = architecture + + if architecture == "skip": + self.fromrgb = Conv2dLayer( + self.img_channels, in_channels, kernel_size=1, activation=activation + ) + self.mbstd = ( + MinibatchStdLayer( + group_size=mbstd_group_size, num_channels=mbstd_num_channels + ) + if mbstd_num_channels > 0 + else None + ) + self.conv = Conv2dLayer( + in_channels + mbstd_num_channels, + in_channels, + kernel_size=3, + activation=activation, + conv_clamp=conv_clamp, + ) + self.fc = FullyConnectedLayer( + in_channels * (resolution**2), z_dim, activation=activation + ) + self.dropout = torch.nn.Dropout(p=0.5) + + def forward(self, x, cmap, force_fp32=False): + _ = force_fp32 # unused + dtype = torch.float32 + memory_format = torch.contiguous_format + + # FromRGB. + x = x.to(dtype=dtype, memory_format=memory_format) + + # Main layers. + if self.mbstd is not None: + x = self.mbstd(x) + const_e = self.conv(x) + x = self.fc(const_e.flatten(1)) + x = self.dropout(x) + + # Conditioning. + if self.cmap_dim > 0: + x = (x * cmap).sum(dim=1, keepdim=True) * (1 / np.sqrt(self.cmap_dim)) + + assert x.dtype == dtype + return x, const_e + + +class EncoderBlock(torch.nn.Module): + def __init__( + self, + in_channels, # Number of input channels, 0 = first block. + tmp_channels, # Number of intermediate channels. + out_channels, # Number of output channels. + resolution, # Resolution of this block. + img_channels, # Number of input color channels. + first_layer_idx, # Index of the first layer. + architecture="skip", # Architecture: 'orig', 'skip', 'resnet'. + activation="lrelu", # Activation function: 'relu', 'lrelu', etc. + resample_filter=[ + 1, + 3, + 3, + 1, + ], # Low-pass filter to apply when resampling activations. + conv_clamp=None, # Clamp the output of convolution layers to +-X, None = disable clamping. + use_fp16=False, # Use FP16 for this block? + fp16_channels_last=False, # Use channels-last memory format with FP16? + freeze_layers=0, # Freeze-D: Number of layers to freeze. + ): + assert in_channels in [0, tmp_channels] + assert architecture in ["orig", "skip", "resnet"] + super().__init__() + self.in_channels = in_channels + self.resolution = resolution + self.img_channels = img_channels + 1 + self.first_layer_idx = first_layer_idx + self.architecture = architecture + self.use_fp16 = use_fp16 + self.channels_last = use_fp16 and fp16_channels_last + self.register_buffer("resample_filter", setup_filter(resample_filter)) + + self.num_layers = 0 + + def trainable_gen(): + while True: + layer_idx = self.first_layer_idx + self.num_layers + trainable = layer_idx >= freeze_layers + self.num_layers += 1 + yield trainable + + trainable_iter = trainable_gen() + + if in_channels == 0: + self.fromrgb = Conv2dLayer( + self.img_channels, + tmp_channels, + kernel_size=1, + activation=activation, + trainable=next(trainable_iter), + conv_clamp=conv_clamp, + channels_last=self.channels_last, + ) + + self.conv0 = Conv2dLayer( + tmp_channels, + tmp_channels, + kernel_size=3, + activation=activation, + trainable=next(trainable_iter), + conv_clamp=conv_clamp, + channels_last=self.channels_last, + ) + + self.conv1 = Conv2dLayer( + tmp_channels, + out_channels, + kernel_size=3, + activation=activation, + down=2, + trainable=next(trainable_iter), + resample_filter=resample_filter, + conv_clamp=conv_clamp, + channels_last=self.channels_last, + ) + + if architecture == "resnet": + self.skip = Conv2dLayer( + tmp_channels, + out_channels, + kernel_size=1, + bias=False, + down=2, + trainable=next(trainable_iter), + resample_filter=resample_filter, + channels_last=self.channels_last, + ) + + def forward(self, x, img, force_fp32=False): + # dtype = torch.float16 if self.use_fp16 and not force_fp32 else torch.float32 + dtype = torch.float32 + memory_format = ( + torch.channels_last + if self.channels_last and not force_fp32 + else torch.contiguous_format + ) + + # Input. + if x is not None: + x = x.to(dtype=dtype, memory_format=memory_format) + + # FromRGB. + if self.in_channels == 0: + img = img.to(dtype=dtype, memory_format=memory_format) + y = self.fromrgb(img) + x = x + y if x is not None else y + img = ( + downsample2d(img, self.resample_filter) + if self.architecture == "skip" + else None + ) + + # Main layers. + if self.architecture == "resnet": + y = self.skip(x, gain=np.sqrt(0.5)) + x = self.conv0(x) + feat = x.clone() + x = self.conv1(x, gain=np.sqrt(0.5)) + x = y.add_(x) + else: + x = self.conv0(x) + feat = x.clone() + x = self.conv1(x) + + assert x.dtype == dtype + return x, img, feat + + +class EncoderNetwork(torch.nn.Module): + def __init__( + self, + c_dim, # Conditioning label (C) dimensionality. + z_dim, # Input latent (Z) dimensionality. + img_resolution, # Input resolution. + img_channels, # Number of input color channels. + architecture="orig", # Architecture: 'orig', 'skip', 'resnet'. + channel_base=16384, # Overall multiplier for the number of channels. + channel_max=512, # Maximum number of channels in any layer. + num_fp16_res=0, # Use FP16 for the N highest resolutions. + conv_clamp=None, # Clamp the output of convolution layers to +-X, None = disable clamping. + cmap_dim=None, # Dimensionality of mapped conditioning label, None = default. + block_kwargs={}, # Arguments for DiscriminatorBlock. + mapping_kwargs={}, # Arguments for MappingNetwork. + epilogue_kwargs={}, # Arguments for EncoderEpilogue. + ): + super().__init__() + self.c_dim = c_dim + self.z_dim = z_dim + self.img_resolution = img_resolution + self.img_resolution_log2 = int(np.log2(img_resolution)) + self.img_channels = img_channels + self.block_resolutions = [ + 2**i for i in range(self.img_resolution_log2, 2, -1) + ] + channels_dict = { + res: min(channel_base // res, channel_max) + for res in self.block_resolutions + [4] + } + fp16_resolution = max(2 ** (self.img_resolution_log2 + 1 - num_fp16_res), 8) + + if cmap_dim is None: + cmap_dim = channels_dict[4] + if c_dim == 0: + cmap_dim = 0 + + common_kwargs = dict( + img_channels=img_channels, architecture=architecture, conv_clamp=conv_clamp + ) + cur_layer_idx = 0 + for res in self.block_resolutions: + in_channels = channels_dict[res] if res < img_resolution else 0 + tmp_channels = channels_dict[res] + out_channels = channels_dict[res // 2] + use_fp16 = res >= fp16_resolution + use_fp16 = False + block = EncoderBlock( + in_channels, + tmp_channels, + out_channels, + resolution=res, + first_layer_idx=cur_layer_idx, + use_fp16=use_fp16, + **block_kwargs, + **common_kwargs, + ) + setattr(self, f"b{res}", block) + cur_layer_idx += block.num_layers + if c_dim > 0: + self.mapping = MappingNetwork( + z_dim=0, + c_dim=c_dim, + w_dim=cmap_dim, + num_ws=None, + w_avg_beta=None, + **mapping_kwargs, + ) + self.b4 = EncoderEpilogue( + channels_dict[4], + cmap_dim=cmap_dim, + z_dim=z_dim * 2, + resolution=4, + **epilogue_kwargs, + **common_kwargs, + ) + + def forward(self, img, c, **block_kwargs): + x = None + feats = {} + for res in self.block_resolutions: + block = getattr(self, f"b{res}") + x, img, feat = block(x, img, **block_kwargs) + feats[res] = feat + + cmap = None + if self.c_dim > 0: + cmap = self.mapping(None, c) + x, const_e = self.b4(x, cmap) + feats[4] = const_e + + B, _ = x.shape + z = torch.zeros( + (B, self.z_dim), requires_grad=False, dtype=x.dtype, device=x.device + ) ## Noise for Co-Modulation + return x, z, feats + + +def fma(a, b, c): # => a * b + c + return _FusedMultiplyAdd.apply(a, b, c) + + +class _FusedMultiplyAdd(torch.autograd.Function): # a * b + c + @staticmethod + def forward(ctx, a, b, c): # pylint: disable=arguments-differ + out = torch.addcmul(c, a, b) + ctx.save_for_backward(a, b) + ctx.c_shape = c.shape + return out + + @staticmethod + def backward(ctx, dout): # pylint: disable=arguments-differ + a, b = ctx.saved_tensors + c_shape = ctx.c_shape + da = None + db = None + dc = None + + if ctx.needs_input_grad[0]: + da = _unbroadcast(dout * b, a.shape) + + if ctx.needs_input_grad[1]: + db = _unbroadcast(dout * a, b.shape) + + if ctx.needs_input_grad[2]: + dc = _unbroadcast(dout, c_shape) + + return da, db, dc + + +def _unbroadcast(x, shape): + extra_dims = x.ndim - len(shape) + assert extra_dims >= 0 + dim = [ + i + for i in range(x.ndim) + if x.shape[i] > 1 and (i < extra_dims or shape[i - extra_dims] == 1) + ] + if len(dim): + x = x.sum(dim=dim, keepdim=True) + if extra_dims: + x = x.reshape(-1, *x.shape[extra_dims + 1 :]) + assert x.shape == shape + return x + + +def modulated_conv2d( + x, # Input tensor of shape [batch_size, in_channels, in_height, in_width]. + weight, # Weight tensor of shape [out_channels, in_channels, kernel_height, kernel_width]. + styles, # Modulation coefficients of shape [batch_size, in_channels]. + noise=None, # Optional noise tensor to add to the output activations. + up=1, # Integer upsampling factor. + down=1, # Integer downsampling factor. + padding=0, # Padding with respect to the upsampled image. + resample_filter=None, + # Low-pass filter to apply when resampling activations. Must be prepared beforehand by calling upfirdn2d.setup_filter(). + demodulate=True, # Apply weight demodulation? + flip_weight=True, # False = convolution, True = correlation (matches torch.nn.functional.conv2d). + fused_modconv=True, # Perform modulation, convolution, and demodulation as a single fused operation? +): + batch_size = x.shape[0] + out_channels, in_channels, kh, kw = weight.shape + + # Pre-normalize inputs to avoid FP16 overflow. + if x.dtype == torch.float16 and demodulate: + weight = weight * ( + 1 + / np.sqrt(in_channels * kh * kw) + / weight.norm(float("inf"), dim=[1, 2, 3], keepdim=True) + ) # max_Ikk + styles = styles / styles.norm(float("inf"), dim=1, keepdim=True) # max_I + + # Calculate per-sample weights and demodulation coefficients. + w = None + dcoefs = None + if demodulate or fused_modconv: + w = weight.unsqueeze(0) # [NOIkk] + w = w * styles.reshape(batch_size, 1, -1, 1, 1) # [NOIkk] + if demodulate: + dcoefs = (w.square().sum(dim=[2, 3, 4]) + 1e-8).rsqrt() # [NO] + if demodulate and fused_modconv: + w = w * dcoefs.reshape(batch_size, -1, 1, 1, 1) # [NOIkk] + # Execute by scaling the activations before and after the convolution. + if not fused_modconv: + x = x * styles.to(x.dtype).reshape(batch_size, -1, 1, 1) + x = conv2d_resample.conv2d_resample( + x=x, + w=weight.to(x.dtype), + f=resample_filter, + up=up, + down=down, + padding=padding, + flip_weight=flip_weight, + ) + if demodulate and noise is not None: + x = fma( + x, dcoefs.to(x.dtype).reshape(batch_size, -1, 1, 1), noise.to(x.dtype) + ) + elif demodulate: + x = x * dcoefs.to(x.dtype).reshape(batch_size, -1, 1, 1) + elif noise is not None: + x = x.add_(noise.to(x.dtype)) + return x + + # Execute as one fused op using grouped convolution. + batch_size = int(batch_size) + x = x.reshape(1, -1, *x.shape[2:]) + w = w.reshape(-1, in_channels, kh, kw) + x = conv2d_resample( + x=x, + w=w.to(x.dtype), + f=resample_filter, + up=up, + down=down, + padding=padding, + groups=batch_size, + flip_weight=flip_weight, + ) + x = x.reshape(batch_size, -1, *x.shape[2:]) + if noise is not None: + x = x.add_(noise) + return x + + +class SynthesisLayer(torch.nn.Module): + def __init__( + self, + in_channels, # Number of input channels. + out_channels, # Number of output channels. + w_dim, # Intermediate latent (W) dimensionality. + resolution, # Resolution of this layer. + kernel_size=3, # Convolution kernel size. + up=1, # Integer upsampling factor. + use_noise=True, # Enable noise input? + activation="lrelu", # Activation function: 'relu', 'lrelu', etc. + resample_filter=[ + 1, + 3, + 3, + 1, + ], # Low-pass filter to apply when resampling activations. + conv_clamp=None, # Clamp the output of convolution layers to +-X, None = disable clamping. + channels_last=False, # Use channels_last format for the weights? + ): + super().__init__() + self.resolution = resolution + self.up = up + self.use_noise = use_noise + self.activation = activation + self.conv_clamp = conv_clamp + self.register_buffer("resample_filter", setup_filter(resample_filter)) + self.padding = kernel_size // 2 + self.act_gain = activation_funcs[activation].def_gain + + self.affine = FullyConnectedLayer(w_dim, in_channels, bias_init=1) + memory_format = ( + torch.channels_last if channels_last else torch.contiguous_format + ) + self.weight = torch.nn.Parameter( + torch.randn([out_channels, in_channels, kernel_size, kernel_size]).to( + memory_format=memory_format + ) + ) + if use_noise: + self.register_buffer("noise_const", torch.randn([resolution, resolution])) + self.noise_strength = torch.nn.Parameter(torch.zeros([])) + self.bias = torch.nn.Parameter(torch.zeros([out_channels])) + + def forward(self, x, w, noise_mode="none", fused_modconv=True, gain=1): + assert noise_mode in ["random", "const", "none"] + in_resolution = self.resolution // self.up + styles = self.affine(w) + + noise = None + if self.use_noise and noise_mode == "random": + noise = ( + torch.randn( + [x.shape[0], 1, self.resolution, self.resolution], device=x.device + ) + * self.noise_strength + ) + if self.use_noise and noise_mode == "const": + noise = self.noise_const * self.noise_strength + + flip_weight = self.up == 1 # slightly faster + x = modulated_conv2d( + x=x, + weight=self.weight, + styles=styles, + noise=noise, + up=self.up, + padding=self.padding, + resample_filter=self.resample_filter, + flip_weight=flip_weight, + fused_modconv=fused_modconv, + ) + + act_gain = self.act_gain * gain + act_clamp = self.conv_clamp * gain if self.conv_clamp is not None else None + x = F.leaky_relu(x, negative_slope=0.2, inplace=False) + if act_gain != 1: + x = x * act_gain + if act_clamp is not None: + x = x.clamp(-act_clamp, act_clamp) + return x + + +class ToRGBLayer(torch.nn.Module): + def __init__( + self, + in_channels, + out_channels, + w_dim, + kernel_size=1, + conv_clamp=None, + channels_last=False, + ): + super().__init__() + self.conv_clamp = conv_clamp + self.affine = FullyConnectedLayer(w_dim, in_channels, bias_init=1) + memory_format = ( + torch.channels_last if channels_last else torch.contiguous_format + ) + self.weight = torch.nn.Parameter( + torch.randn([out_channels, in_channels, kernel_size, kernel_size]).to( + memory_format=memory_format + ) + ) + self.bias = torch.nn.Parameter(torch.zeros([out_channels])) + self.weight_gain = 1 / np.sqrt(in_channels * (kernel_size**2)) + + def forward(self, x, w, fused_modconv=True): + styles = self.affine(w) * self.weight_gain + x = modulated_conv2d( + x=x, + weight=self.weight, + styles=styles, + demodulate=False, + fused_modconv=fused_modconv, + ) + x = bias_act(x, self.bias.to(x.dtype), clamp=self.conv_clamp) + return x + + +class SynthesisForeword(torch.nn.Module): + def __init__( + self, + z_dim, # Output Latent (Z) dimensionality. + resolution, # Resolution of this block. + in_channels, + img_channels, # Number of input color channels. + architecture="skip", # Architecture: 'orig', 'skip', 'resnet'. + activation="lrelu", # Activation function: 'relu', 'lrelu', etc. + ): + super().__init__() + self.in_channels = in_channels + self.z_dim = z_dim + self.resolution = resolution + self.img_channels = img_channels + self.architecture = architecture + + self.fc = FullyConnectedLayer( + self.z_dim, (self.z_dim // 2) * 4 * 4, activation=activation + ) + self.conv = SynthesisLayer( + self.in_channels, self.in_channels, w_dim=(z_dim // 2) * 3, resolution=4 + ) + + if architecture == "skip": + self.torgb = ToRGBLayer( + self.in_channels, + self.img_channels, + kernel_size=1, + w_dim=(z_dim // 2) * 3, + ) + + def forward(self, x, ws, feats, img, force_fp32=False): + _ = force_fp32 # unused + dtype = torch.float32 + memory_format = torch.contiguous_format + + x_global = x.clone() + # ToRGB. + x = self.fc(x) + x = x.view(-1, self.z_dim // 2, 4, 4) + x = x.to(dtype=dtype, memory_format=memory_format) + + # Main layers. + x_skip = feats[4].clone() + x = x + x_skip + + mod_vector = [] + mod_vector.append(ws[:, 0]) + mod_vector.append(x_global.clone()) + mod_vector = torch.cat(mod_vector, dim=1) + + x = self.conv(x, mod_vector) + + mod_vector = [] + mod_vector.append(ws[:, 2 * 2 - 3]) + mod_vector.append(x_global.clone()) + mod_vector = torch.cat(mod_vector, dim=1) + + if self.architecture == "skip": + img = self.torgb(x, mod_vector) + img = img.to(dtype=torch.float32, memory_format=torch.contiguous_format) + + assert x.dtype == dtype + return x, img + + +class SELayer(nn.Module): + def __init__(self, channel, reduction=16): + super(SELayer, self).__init__() + self.avg_pool = nn.AdaptiveAvgPool2d(1) + self.fc = nn.Sequential( + nn.Linear(channel, channel // reduction, bias=False), + nn.ReLU(inplace=False), + nn.Linear(channel // reduction, channel, bias=False), + nn.Sigmoid(), + ) + + def forward(self, x): + b, c, _, _ = x.size() + y = self.avg_pool(x).view(b, c) + y = self.fc(y).view(b, c, 1, 1) + res = x * y.expand_as(x) + return res + + +class FourierUnit(nn.Module): + def __init__( + self, + in_channels, + out_channels, + groups=1, + spatial_scale_factor=None, + spatial_scale_mode="bilinear", + spectral_pos_encoding=False, + use_se=False, + se_kwargs=None, + ffc3d=False, + fft_norm="ortho", + ): + # bn_layer not used + super(FourierUnit, self).__init__() + self.groups = groups + + self.conv_layer = torch.nn.Conv2d( + in_channels=in_channels * 2 + (2 if spectral_pos_encoding else 0), + out_channels=out_channels * 2, + kernel_size=1, + stride=1, + padding=0, + groups=self.groups, + bias=False, + ) + self.relu = torch.nn.ReLU(inplace=False) + + # squeeze and excitation block + self.use_se = use_se + if use_se: + if se_kwargs is None: + se_kwargs = {} + self.se = SELayer(self.conv_layer.in_channels, **se_kwargs) + + self.spatial_scale_factor = spatial_scale_factor + self.spatial_scale_mode = spatial_scale_mode + self.spectral_pos_encoding = spectral_pos_encoding + self.ffc3d = ffc3d + self.fft_norm = fft_norm + + def forward(self, x): + batch = x.shape[0] + + if self.spatial_scale_factor is not None: + orig_size = x.shape[-2:] + x = F.interpolate( + x, + scale_factor=self.spatial_scale_factor, + mode=self.spatial_scale_mode, + align_corners=False, + ) + + r_size = x.size() + # (batch, c, h, w/2+1, 2) + fft_dim = (-3, -2, -1) if self.ffc3d else (-2, -1) + ffted = fft.rfftn(x, dim=fft_dim, norm=self.fft_norm) + ffted = torch.stack((ffted.real, ffted.imag), dim=-1) + ffted = ffted.permute(0, 1, 4, 2, 3).contiguous() # (batch, c, 2, h, w/2+1) + ffted = ffted.view( + ( + batch, + -1, + ) + + ffted.size()[3:] + ) + + if self.spectral_pos_encoding: + height, width = ffted.shape[-2:] + coords_vert = ( + torch.linspace(0, 1, height)[None, None, :, None] + .expand(batch, 1, height, width) + .to(ffted) + ) + coords_hor = ( + torch.linspace(0, 1, width)[None, None, None, :] + .expand(batch, 1, height, width) + .to(ffted) + ) + ffted = torch.cat((coords_vert, coords_hor, ffted), dim=1) + + if self.use_se: + ffted = self.se(ffted) + + ffted = self.conv_layer(ffted) # (batch, c*2, h, w/2+1) + ffted = self.relu(ffted) + + ffted = ( + ffted.view( + ( + batch, + -1, + 2, + ) + + ffted.size()[2:] + ) + .permute(0, 1, 3, 4, 2) + .contiguous() + ) # (batch,c, t, h, w/2+1, 2) + ffted = torch.complex(ffted[..., 0], ffted[..., 1]) + + ifft_shape_slice = x.shape[-3:] if self.ffc3d else x.shape[-2:] + output = torch.fft.irfftn( + ffted, s=ifft_shape_slice, dim=fft_dim, norm=self.fft_norm + ) + + if self.spatial_scale_factor is not None: + output = F.interpolate( + output, + size=orig_size, + mode=self.spatial_scale_mode, + align_corners=False, + ) + + return output + + +class SpectralTransform(nn.Module): + def __init__( + self, + in_channels, + out_channels, + stride=1, + groups=1, + enable_lfu=True, + **fu_kwargs, + ): + # bn_layer not used + super(SpectralTransform, self).__init__() + self.enable_lfu = enable_lfu + if stride == 2: + self.downsample = nn.AvgPool2d(kernel_size=(2, 2), stride=2) + else: + self.downsample = nn.Identity() + + self.stride = stride + self.conv1 = nn.Sequential( + nn.Conv2d( + in_channels, out_channels // 2, kernel_size=1, groups=groups, bias=False + ), + # nn.BatchNorm2d(out_channels // 2), + nn.ReLU(inplace=True), + ) + self.fu = FourierUnit(out_channels // 2, out_channels // 2, groups, **fu_kwargs) + if self.enable_lfu: + self.lfu = FourierUnit(out_channels // 2, out_channels // 2, groups) + self.conv2 = torch.nn.Conv2d( + out_channels // 2, out_channels, kernel_size=1, groups=groups, bias=False + ) + + def forward(self, x): + x = self.downsample(x) + x = self.conv1(x) + output = self.fu(x) + + if self.enable_lfu: + n, c, h, w = x.shape + split_no = 2 + split_s = h // split_no + xs = torch.cat( + torch.split(x[:, : c // 4], split_s, dim=-2), dim=1 + ).contiguous() + xs = torch.cat(torch.split(xs, split_s, dim=-1), dim=1).contiguous() + xs = self.lfu(xs) + xs = xs.repeat(1, 1, split_no, split_no).contiguous() + else: + xs = 0 + + output = self.conv2(x + output + xs) + + return output + + +class FFC(nn.Module): + def __init__( + self, + in_channels, + out_channels, + kernel_size, + ratio_gin, + ratio_gout, + stride=1, + padding=0, + dilation=1, + groups=1, + bias=False, + enable_lfu=True, + padding_type="reflect", + gated=False, + **spectral_kwargs, + ): + super(FFC, self).__init__() + + assert stride == 1 or stride == 2, "Stride should be 1 or 2." + self.stride = stride + + in_cg = int(in_channels * ratio_gin) + in_cl = in_channels - in_cg + out_cg = int(out_channels * ratio_gout) + out_cl = out_channels - out_cg + # groups_g = 1 if groups == 1 else int(groups * ratio_gout) + # groups_l = 1 if groups == 1 else groups - groups_g + + self.ratio_gin = ratio_gin + self.ratio_gout = ratio_gout + self.global_in_num = in_cg + + module = nn.Identity if in_cl == 0 or out_cl == 0 else nn.Conv2d + self.convl2l = module( + in_cl, + out_cl, + kernel_size, + stride, + padding, + dilation, + groups, + bias, + padding_mode=padding_type, + ) + module = nn.Identity if in_cl == 0 or out_cg == 0 else nn.Conv2d + self.convl2g = module( + in_cl, + out_cg, + kernel_size, + stride, + padding, + dilation, + groups, + bias, + padding_mode=padding_type, + ) + module = nn.Identity if in_cg == 0 or out_cl == 0 else nn.Conv2d + self.convg2l = module( + in_cg, + out_cl, + kernel_size, + stride, + padding, + dilation, + groups, + bias, + padding_mode=padding_type, + ) + module = nn.Identity if in_cg == 0 or out_cg == 0 else SpectralTransform + self.convg2g = module( + in_cg, + out_cg, + stride, + 1 if groups == 1 else groups // 2, + enable_lfu, + **spectral_kwargs, + ) + + self.gated = gated + module = ( + nn.Identity if in_cg == 0 or out_cl == 0 or not self.gated else nn.Conv2d + ) + self.gate = module(in_channels, 2, 1) + + def forward(self, x, fname=None): + x_l, x_g = x if type(x) is tuple else (x, 0) + out_xl, out_xg = 0, 0 + + if self.gated: + total_input_parts = [x_l] + if torch.is_tensor(x_g): + total_input_parts.append(x_g) + total_input = torch.cat(total_input_parts, dim=1) + + gates = torch.sigmoid(self.gate(total_input)) + g2l_gate, l2g_gate = gates.chunk(2, dim=1) + else: + g2l_gate, l2g_gate = 1, 1 + + spec_x = self.convg2g(x_g) + + if self.ratio_gout != 1: + out_xl = self.convl2l(x_l) + self.convg2l(x_g) * g2l_gate + if self.ratio_gout != 0: + out_xg = self.convl2g(x_l) * l2g_gate + spec_x + + return out_xl, out_xg + + +class FFC_BN_ACT(nn.Module): + def __init__( + self, + in_channels, + out_channels, + kernel_size, + ratio_gin, + ratio_gout, + stride=1, + padding=0, + dilation=1, + groups=1, + bias=False, + norm_layer=nn.SyncBatchNorm, + activation_layer=nn.Identity, + padding_type="reflect", + enable_lfu=True, + **kwargs, + ): + super(FFC_BN_ACT, self).__init__() + self.ffc = FFC( + in_channels, + out_channels, + kernel_size, + ratio_gin, + ratio_gout, + stride, + padding, + dilation, + groups, + bias, + enable_lfu, + padding_type=padding_type, + **kwargs, + ) + lnorm = nn.Identity if ratio_gout == 1 else norm_layer + gnorm = nn.Identity if ratio_gout == 0 else norm_layer + global_channels = int(out_channels * ratio_gout) + # self.bn_l = lnorm(out_channels - global_channels) + # self.bn_g = gnorm(global_channels) + + lact = nn.Identity if ratio_gout == 1 else activation_layer + gact = nn.Identity if ratio_gout == 0 else activation_layer + self.act_l = lact(inplace=True) + self.act_g = gact(inplace=True) + + def forward(self, x, fname=None): + x_l, x_g = self.ffc( + x, + fname=fname, + ) + x_l = self.act_l(x_l) + x_g = self.act_g(x_g) + return x_l, x_g + + +class FFCResnetBlock(nn.Module): + def __init__( + self, + dim, + padding_type, + norm_layer, + activation_layer=nn.ReLU, + dilation=1, + spatial_transform_kwargs=None, + inline=False, + ratio_gin=0.75, + ratio_gout=0.75, + ): + super().__init__() + self.conv1 = FFC_BN_ACT( + dim, + dim, + kernel_size=3, + padding=dilation, + dilation=dilation, + norm_layer=norm_layer, + activation_layer=activation_layer, + padding_type=padding_type, + ratio_gin=ratio_gin, + ratio_gout=ratio_gout, + ) + self.conv2 = FFC_BN_ACT( + dim, + dim, + kernel_size=3, + padding=dilation, + dilation=dilation, + norm_layer=norm_layer, + activation_layer=activation_layer, + padding_type=padding_type, + ratio_gin=ratio_gin, + ratio_gout=ratio_gout, + ) + self.inline = inline + + def forward(self, x, fname=None): + if self.inline: + x_l, x_g = ( + x[:, : -self.conv1.ffc.global_in_num], + x[:, -self.conv1.ffc.global_in_num :], + ) + else: + x_l, x_g = x if type(x) is tuple else (x, 0) + + id_l, id_g = x_l, x_g + + x_l, x_g = self.conv1((x_l, x_g), fname=fname) + x_l, x_g = self.conv2((x_l, x_g), fname=fname) + + x_l, x_g = id_l + x_l, id_g + x_g + out = x_l, x_g + if self.inline: + out = torch.cat(out, dim=1) + return out + + +class ConcatTupleLayer(nn.Module): + def forward(self, x): + assert isinstance(x, tuple) + x_l, x_g = x + assert torch.is_tensor(x_l) or torch.is_tensor(x_g) + if not torch.is_tensor(x_g): + return x_l + return torch.cat(x, dim=1) + + +class FFCBlock(torch.nn.Module): + def __init__( + self, + dim, # Number of output/input channels. + kernel_size, # Width and height of the convolution kernel. + padding, + ratio_gin=0.75, + ratio_gout=0.75, + activation="linear", # Activation function: 'relu', 'lrelu', etc. + ): + super().__init__() + if activation == "linear": + self.activation = nn.Identity + else: + self.activation = nn.ReLU + self.padding = padding + self.kernel_size = kernel_size + self.ffc_block = FFCResnetBlock( + dim=dim, + padding_type="reflect", + norm_layer=nn.SyncBatchNorm, + activation_layer=self.activation, + dilation=1, + ratio_gin=ratio_gin, + ratio_gout=ratio_gout, + ) + + self.concat_layer = ConcatTupleLayer() + + def forward(self, gen_ft, mask, fname=None): + x = gen_ft.float() + + x_l, x_g = ( + x[:, : -self.ffc_block.conv1.ffc.global_in_num], + x[:, -self.ffc_block.conv1.ffc.global_in_num :], + ) + id_l, id_g = x_l, x_g + + x_l, x_g = self.ffc_block((x_l, x_g), fname=fname) + x_l, x_g = id_l + x_l, id_g + x_g + x = self.concat_layer((x_l, x_g)) + + return x + gen_ft.float() + + +class FFCSkipLayer(torch.nn.Module): + def __init__( + self, + dim, # Number of input/output channels. + kernel_size=3, # Convolution kernel size. + ratio_gin=0.75, + ratio_gout=0.75, + ): + super().__init__() + self.padding = kernel_size // 2 + + self.ffc_act = FFCBlock( + dim=dim, + kernel_size=kernel_size, + activation=nn.ReLU, + padding=self.padding, + ratio_gin=ratio_gin, + ratio_gout=ratio_gout, + ) + + def forward(self, gen_ft, mask, fname=None): + x = self.ffc_act(gen_ft, mask, fname=fname) + return x + + +class SynthesisBlock(torch.nn.Module): + def __init__( + self, + in_channels, # Number of input channels, 0 = first block. + out_channels, # Number of output channels. + w_dim, # Intermediate latent (W) dimensionality. + resolution, # Resolution of this block. + img_channels, # Number of output color channels. + is_last, # Is this the last block? + architecture="skip", # Architecture: 'orig', 'skip', 'resnet'. + resample_filter=[ + 1, + 3, + 3, + 1, + ], # Low-pass filter to apply when resampling activations. + conv_clamp=None, # Clamp the output of convolution layers to +-X, None = disable clamping. + use_fp16=False, # Use FP16 for this block? + fp16_channels_last=False, # Use channels-last memory format with FP16? + **layer_kwargs, # Arguments for SynthesisLayer. + ): + assert architecture in ["orig", "skip", "resnet"] + super().__init__() + self.in_channels = in_channels + self.w_dim = w_dim + self.resolution = resolution + self.img_channels = img_channels + self.is_last = is_last + self.architecture = architecture + self.use_fp16 = use_fp16 + self.channels_last = use_fp16 and fp16_channels_last + self.register_buffer("resample_filter", setup_filter(resample_filter)) + self.num_conv = 0 + self.num_torgb = 0 + self.res_ffc = {4: 0, 8: 0, 16: 0, 32: 1, 64: 1, 128: 1, 256: 1, 512: 1} + + if in_channels != 0 and resolution >= 8: + self.ffc_skip = nn.ModuleList() + for _ in range(self.res_ffc[resolution]): + self.ffc_skip.append(FFCSkipLayer(dim=out_channels)) + + if in_channels == 0: + self.const = torch.nn.Parameter( + torch.randn([out_channels, resolution, resolution]) + ) + + if in_channels != 0: + self.conv0 = SynthesisLayer( + in_channels, + out_channels, + w_dim=w_dim * 3, + resolution=resolution, + up=2, + resample_filter=resample_filter, + conv_clamp=conv_clamp, + channels_last=self.channels_last, + **layer_kwargs, + ) + self.num_conv += 1 + + self.conv1 = SynthesisLayer( + out_channels, + out_channels, + w_dim=w_dim * 3, + resolution=resolution, + conv_clamp=conv_clamp, + channels_last=self.channels_last, + **layer_kwargs, + ) + self.num_conv += 1 + + if is_last or architecture == "skip": + self.torgb = ToRGBLayer( + out_channels, + img_channels, + w_dim=w_dim * 3, + conv_clamp=conv_clamp, + channels_last=self.channels_last, + ) + self.num_torgb += 1 + + if in_channels != 0 and architecture == "resnet": + self.skip = Conv2dLayer( + in_channels, + out_channels, + kernel_size=1, + bias=False, + up=2, + resample_filter=resample_filter, + channels_last=self.channels_last, + ) + + def forward( + self, + x, + mask, + feats, + img, + ws, + fname=None, + force_fp32=False, + fused_modconv=None, + **layer_kwargs, + ): + dtype = torch.float16 if self.use_fp16 and not force_fp32 else torch.float32 + dtype = torch.float32 + memory_format = ( + torch.channels_last + if self.channels_last and not force_fp32 + else torch.contiguous_format + ) + if fused_modconv is None: + fused_modconv = (not self.training) and ( + dtype == torch.float32 or int(x.shape[0]) == 1 + ) + + x = x.to(dtype=dtype, memory_format=memory_format) + x_skip = ( + feats[self.resolution].clone().to(dtype=dtype, memory_format=memory_format) + ) + + # Main layers. + if self.in_channels == 0: + x = self.conv1(x, ws[1], fused_modconv=fused_modconv, **layer_kwargs) + elif self.architecture == "resnet": + y = self.skip(x, gain=np.sqrt(0.5)) + x = self.conv0( + x, ws[0].clone(), fused_modconv=fused_modconv, **layer_kwargs + ) + if len(self.ffc_skip) > 0: + mask = F.interpolate( + mask, + size=x_skip.shape[2:], + ) + z = x + x_skip + for fres in self.ffc_skip: + z = fres(z, mask) + x = x + z + else: + x = x + x_skip + x = self.conv1( + x, + ws[1].clone(), + fused_modconv=fused_modconv, + gain=np.sqrt(0.5), + **layer_kwargs, + ) + x = y.add_(x) + else: + x = self.conv0( + x, ws[0].clone(), fused_modconv=fused_modconv, **layer_kwargs + ) + if len(self.ffc_skip) > 0: + mask = F.interpolate( + mask, + size=x_skip.shape[2:], + ) + z = x + x_skip + for fres in self.ffc_skip: + z = fres(z, mask) + x = x + z + else: + x = x + x_skip + x = self.conv1( + x, ws[1].clone(), fused_modconv=fused_modconv, **layer_kwargs + ) + # ToRGB. + if img is not None: + img = upsample2d(img, self.resample_filter) + if self.is_last or self.architecture == "skip": + y = self.torgb(x, ws[2].clone(), fused_modconv=fused_modconv) + y = y.to(dtype=torch.float32, memory_format=torch.contiguous_format) + img = img.add_(y) if img is not None else y + + x = x.to(dtype=dtype) + assert x.dtype == dtype + assert img is None or img.dtype == torch.float32 + return x, img + + +class SynthesisNetwork(torch.nn.Module): + def __init__( + self, + w_dim, # Intermediate latent (W) dimensionality. + z_dim, # Output Latent (Z) dimensionality. + img_resolution, # Output image resolution. + img_channels, # Number of color channels. + channel_base=16384, # Overall multiplier for the number of channels. + channel_max=512, # Maximum number of channels in any layer. + num_fp16_res=0, # Use FP16 for the N highest resolutions. + **block_kwargs, # Arguments for SynthesisBlock. + ): + assert img_resolution >= 4 and img_resolution & (img_resolution - 1) == 0 + super().__init__() + self.w_dim = w_dim + self.img_resolution = img_resolution + self.img_resolution_log2 = int(np.log2(img_resolution)) + self.img_channels = img_channels + self.block_resolutions = [ + 2**i for i in range(3, self.img_resolution_log2 + 1) + ] + channels_dict = { + res: min(channel_base // res, channel_max) for res in self.block_resolutions + } + fp16_resolution = max(2 ** (self.img_resolution_log2 + 1 - num_fp16_res), 8) + + self.foreword = SynthesisForeword( + img_channels=img_channels, + in_channels=min(channel_base // 4, channel_max), + z_dim=z_dim * 2, + resolution=4, + ) + + self.num_ws = self.img_resolution_log2 * 2 - 2 + for res in self.block_resolutions: + if res // 2 in channels_dict.keys(): + in_channels = channels_dict[res // 2] if res > 4 else 0 + else: + in_channels = min(channel_base // (res // 2), channel_max) + out_channels = channels_dict[res] + use_fp16 = res >= fp16_resolution + use_fp16 = False + is_last = res == self.img_resolution + block = SynthesisBlock( + in_channels, + out_channels, + w_dim=w_dim, + resolution=res, + img_channels=img_channels, + is_last=is_last, + use_fp16=use_fp16, + **block_kwargs, + ) + setattr(self, f"b{res}", block) + + def forward(self, x_global, mask, feats, ws, fname=None, **block_kwargs): + img = None + + x, img = self.foreword(x_global, ws, feats, img) + + for res in self.block_resolutions: + block = getattr(self, f"b{res}") + mod_vector0 = [] + mod_vector0.append(ws[:, int(np.log2(res)) * 2 - 5]) + mod_vector0.append(x_global.clone()) + mod_vector0 = torch.cat(mod_vector0, dim=1) + + mod_vector1 = [] + mod_vector1.append(ws[:, int(np.log2(res)) * 2 - 4]) + mod_vector1.append(x_global.clone()) + mod_vector1 = torch.cat(mod_vector1, dim=1) + + mod_vector_rgb = [] + mod_vector_rgb.append(ws[:, int(np.log2(res)) * 2 - 3]) + mod_vector_rgb.append(x_global.clone()) + mod_vector_rgb = torch.cat(mod_vector_rgb, dim=1) + x, img = block( + x, + mask, + feats, + img, + (mod_vector0, mod_vector1, mod_vector_rgb), + fname=fname, + **block_kwargs, + ) + return img + + +class MappingNetwork(torch.nn.Module): + def __init__( + self, + z_dim, # Input latent (Z) dimensionality, 0 = no latent. + c_dim, # Conditioning label (C) dimensionality, 0 = no label. + w_dim, # Intermediate latent (W) dimensionality. + num_ws, # Number of intermediate latents to output, None = do not broadcast. + num_layers=8, # Number of mapping layers. + embed_features=None, # Label embedding dimensionality, None = same as w_dim. + layer_features=None, # Number of intermediate features in the mapping layers, None = same as w_dim. + activation="lrelu", # Activation function: 'relu', 'lrelu', etc. + lr_multiplier=0.01, # Learning rate multiplier for the mapping layers. + w_avg_beta=0.995, # Decay for tracking the moving average of W during training, None = do not track. + ): + super().__init__() + self.z_dim = z_dim + self.c_dim = c_dim + self.w_dim = w_dim + self.num_ws = num_ws + self.num_layers = num_layers + self.w_avg_beta = w_avg_beta + + if embed_features is None: + embed_features = w_dim + if c_dim == 0: + embed_features = 0 + if layer_features is None: + layer_features = w_dim + features_list = ( + [z_dim + embed_features] + [layer_features] * (num_layers - 1) + [w_dim] + ) + + if c_dim > 0: + self.embed = FullyConnectedLayer(c_dim, embed_features) + for idx in range(num_layers): + in_features = features_list[idx] + out_features = features_list[idx + 1] + layer = FullyConnectedLayer( + in_features, + out_features, + activation=activation, + lr_multiplier=lr_multiplier, + ) + setattr(self, f"fc{idx}", layer) + + if num_ws is not None and w_avg_beta is not None: + self.register_buffer("w_avg", torch.zeros([w_dim])) + + def forward( + self, z, c, truncation_psi=1, truncation_cutoff=None, skip_w_avg_update=False + ): + # Embed, normalize, and concat inputs. + x = None + with torch.autograd.profiler.record_function("input"): + if self.z_dim > 0: + x = normalize_2nd_moment(z.to(torch.float32)) + if self.c_dim > 0: + y = normalize_2nd_moment(self.embed(c.to(torch.float32))) + x = torch.cat([x, y], dim=1) if x is not None else y + + # Main layers. + for idx in range(self.num_layers): + layer = getattr(self, f"fc{idx}") + x = layer(x) + + # Update moving average of W. + if self.w_avg_beta is not None and self.training and not skip_w_avg_update: + with torch.autograd.profiler.record_function("update_w_avg"): + self.w_avg.copy_( + x.detach().mean(dim=0).lerp(self.w_avg, self.w_avg_beta) + ) + + # Broadcast. + if self.num_ws is not None: + with torch.autograd.profiler.record_function("broadcast"): + x = x.unsqueeze(1).repeat([1, self.num_ws, 1]) + + # Apply truncation. + if truncation_psi != 1: + with torch.autograd.profiler.record_function("truncate"): + assert self.w_avg_beta is not None + if self.num_ws is None or truncation_cutoff is None: + x = self.w_avg.lerp(x, truncation_psi) + else: + x[:, :truncation_cutoff] = self.w_avg.lerp( + x[:, :truncation_cutoff], truncation_psi + ) + return x + + +class Generator(torch.nn.Module): + def __init__( + self, + z_dim, # Input latent (Z) dimensionality. + c_dim, # Conditioning label (C) dimensionality. + w_dim, # Intermediate latent (W) dimensionality. + img_resolution, # Output resolution. + img_channels, # Number of output color channels. + encoder_kwargs={}, # Arguments for EncoderNetwork. + mapping_kwargs={}, # Arguments for MappingNetwork. + synthesis_kwargs={}, # Arguments for SynthesisNetwork. + ): + super().__init__() + self.z_dim = z_dim + self.c_dim = c_dim + self.w_dim = w_dim + self.img_resolution = img_resolution + self.img_channels = img_channels + self.encoder = EncoderNetwork( + c_dim=c_dim, + z_dim=z_dim, + img_resolution=img_resolution, + img_channels=img_channels, + **encoder_kwargs, + ) + self.synthesis = SynthesisNetwork( + z_dim=z_dim, + w_dim=w_dim, + img_resolution=img_resolution, + img_channels=img_channels, + **synthesis_kwargs, + ) + self.num_ws = self.synthesis.num_ws + self.mapping = MappingNetwork( + z_dim=z_dim, c_dim=c_dim, w_dim=w_dim, num_ws=self.num_ws, **mapping_kwargs + ) + + def forward( + self, + img, + c, + fname=None, + truncation_psi=1, + truncation_cutoff=None, + **synthesis_kwargs, + ): + mask = img[:, -1].unsqueeze(1) + x_global, z, feats = self.encoder(img, c) + ws = self.mapping( + z, c, truncation_psi=truncation_psi, truncation_cutoff=truncation_cutoff + ) + img = self.synthesis(x_global, mask, feats, ws, fname=fname, **synthesis_kwargs) + return img + + +FCF_MODEL_URL = os.environ.get( + "FCF_MODEL_URL", + "https://github.com/Sanster/models/releases/download/add_fcf/places_512_G.pth", +) +FCF_MODEL_MD5 = os.environ.get("FCF_MODEL_MD5", "3323152bc01bf1c56fd8aba74435a211") + + +class FcF(InpaintModel): + name = "fcf" + min_size = 512 + pad_mod = 512 + pad_to_square = True + is_erase_model = True + + def init_model(self, device, **kwargs): + seed = 0 + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + torch.cuda.manual_seed_all(seed) + torch.backends.cudnn.deterministic = True + torch.backends.cudnn.benchmark = False + + kwargs = { + "channel_base": 1 * 32768, + "channel_max": 512, + "num_fp16_res": 4, + "conv_clamp": 256, + } + G = Generator( + z_dim=512, + c_dim=0, + w_dim=512, + img_resolution=512, + img_channels=3, + synthesis_kwargs=kwargs, + encoder_kwargs=kwargs, + mapping_kwargs={"num_layers": 2}, + ) + self.model = load_model(G, FCF_MODEL_URL, device, FCF_MODEL_MD5) + self.label = torch.zeros([1, self.model.c_dim], device=device) + + @staticmethod + def download(): + download_model(FCF_MODEL_URL, FCF_MODEL_MD5) + + @staticmethod + def is_downloaded() -> bool: + return os.path.exists(get_cache_path_by_url(FCF_MODEL_URL)) + + @torch.no_grad() + def __call__(self, image, mask, config: InpaintRequest): + """ + images: [H, W, C] RGB, not normalized + masks: [H, W] + return: BGR IMAGE + """ + if image.shape[0] == 512 and image.shape[1] == 512: + return self._pad_forward(image, mask, config) + + boxes = boxes_from_mask(mask) + crop_result = [] + config.hd_strategy_crop_margin = 128 + for box in boxes: + crop_image, crop_mask, crop_box = self._crop_box(image, mask, box, config) + origin_size = crop_image.shape[:2] + resize_image = resize_max_size(crop_image, size_limit=512) + resize_mask = resize_max_size(crop_mask, size_limit=512) + inpaint_result = self._pad_forward(resize_image, resize_mask, config) + + # only paste masked area result + inpaint_result = cv2.resize( + inpaint_result, + (origin_size[1], origin_size[0]), + interpolation=cv2.INTER_CUBIC, + ) + + original_pixel_indices = crop_mask < 127 + inpaint_result[original_pixel_indices] = crop_image[:, :, ::-1][ + original_pixel_indices + ] + + crop_result.append((inpaint_result, crop_box)) + + inpaint_result = image[:, :, ::-1].copy() + for crop_image, crop_box in crop_result: + x1, y1, x2, y2 = crop_box + inpaint_result[y1:y2, x1:x2, :] = crop_image + + return inpaint_result + + def forward(self, image, mask, config: InpaintRequest): + """Input images and output images have same size + images: [H, W, C] RGB + masks: [H, W] mask area == 255 + return: BGR IMAGE + """ + + image = norm_img(image) # [0, 1] + image = image * 2 - 1 # [0, 1] -> [-1, 1] + mask = (mask > 120) * 255 + mask = norm_img(mask) + + image = torch.from_numpy(image).unsqueeze(0).to(self.device) + mask = torch.from_numpy(mask).unsqueeze(0).to(self.device) + + erased_img = image * (1 - mask) + input_image = torch.cat([0.5 - mask, erased_img], dim=1) + + output = self.model( + input_image, self.label, truncation_psi=0.1, noise_mode="none" + ) + output = ( + (output.permute(0, 2, 3, 1) * 127.5 + 127.5) + .round() + .clamp(0, 255) + .to(torch.uint8) + ) + output = output[0].cpu().numpy() + cur_res = cv2.cvtColor(output, cv2.COLOR_RGB2BGR) + return cur_res diff --git a/py/iopaint/model/helper/__init__.py b/py/iopaint/model/helper/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/py/iopaint/model/helper/controlnet_preprocess.py b/py/iopaint/model/helper/controlnet_preprocess.py new file mode 100644 index 0000000..1d2e542 --- /dev/null +++ b/py/iopaint/model/helper/controlnet_preprocess.py @@ -0,0 +1,68 @@ +import torch +import PIL +import cv2 +from PIL import Image +import numpy as np + +from ...helper import pad_img_to_modulo + + +def make_canny_control_image(image: np.ndarray) -> Image: + canny_image = cv2.Canny(image, 100, 200) + canny_image = canny_image[:, :, None] + canny_image = np.concatenate([canny_image, canny_image, canny_image], axis=2) + canny_image = PIL.Image.fromarray(canny_image) + control_image = canny_image + return control_image + + +def make_openpose_control_image(image: np.ndarray) -> Image: + from controlnet_aux import OpenposeDetector + + processor = OpenposeDetector.from_pretrained("lllyasviel/ControlNet") + control_image = processor(image, hand_and_face=True) + return control_image + + +def resize_image(input_image, resolution): + H, W, C = input_image.shape + H = float(H) + W = float(W) + k = float(resolution) / min(H, W) + H *= k + W *= k + H = int(np.round(H / 64.0)) * 64 + W = int(np.round(W / 64.0)) * 64 + img = cv2.resize( + input_image, + (W, H), + interpolation=cv2.INTER_LANCZOS4 if k > 1 else cv2.INTER_AREA, + ) + return img + + +def make_depth_control_image(image: np.ndarray) -> Image: + from controlnet_aux import MidasDetector + + midas = MidasDetector.from_pretrained("lllyasviel/Annotators") + + origin_height, origin_width = image.shape[:2] + pad_image = pad_img_to_modulo(image, mod=64, square=False, min_size=512) + depth_image = midas(pad_image) + depth_image = depth_image[0:origin_height, 0:origin_width] + depth_image = depth_image[:, :, None] + depth_image = np.concatenate([depth_image, depth_image, depth_image], axis=2) + control_image = PIL.Image.fromarray(depth_image) + return control_image + + +def make_inpaint_control_image(image: np.ndarray, mask: np.ndarray) -> torch.Tensor: + """ + image: [H, W, C] RGB + mask: [H, W, 1] 255 means area to repaint + """ + image = image.astype(np.float32) / 255.0 + image[mask[:, :, -1] > 128] = -1.0 # set as masked pixel + image = np.expand_dims(image, 0).transpose(0, 3, 1, 2) + image = torch.from_numpy(image) + return image diff --git a/py/iopaint/model/helper/cpu_text_encoder.py b/py/iopaint/model/helper/cpu_text_encoder.py new file mode 100644 index 0000000..116eb48 --- /dev/null +++ b/py/iopaint/model/helper/cpu_text_encoder.py @@ -0,0 +1,41 @@ +import torch +from transformers import PreTrainedModel + +from ..utils import torch_gc + + +class CPUTextEncoderWrapper(PreTrainedModel): + def __init__(self, text_encoder, torch_dtype): + super().__init__(text_encoder.config) + self.config = text_encoder.config + self._device = text_encoder.device + # cpu not support float16 + self.text_encoder = text_encoder.to(torch.device("cpu"), non_blocking=True) + self.text_encoder = self.text_encoder.to(torch.float32, non_blocking=True) + self.torch_dtype = torch_dtype + del text_encoder + torch_gc() + + def __call__(self, x, **kwargs): + input_device = x.device + original_output = self.text_encoder(x.to(self.text_encoder.device), **kwargs) + for k, v in original_output.items(): + if isinstance(v, tuple): + original_output[k] = [ + v[i].to(input_device).to(self.torch_dtype) for i in range(len(v)) + ] + else: + original_output[k] = v.to(input_device).to(self.torch_dtype) + return original_output + + @property + def dtype(self): + return self.torch_dtype + + @property + def device(self) -> torch.device: + """ + `torch.device`: The device on which the module is (assuming that all the module parameters are on the same + device). + """ + return self._device \ No newline at end of file diff --git a/py/iopaint/model/helper/g_diffuser_bot.py b/py/iopaint/model/helper/g_diffuser_bot.py new file mode 100644 index 0000000..a4147af --- /dev/null +++ b/py/iopaint/model/helper/g_diffuser_bot.py @@ -0,0 +1,167 @@ +# code copy from: https://github.com/parlance-zz/g-diffuser-bot +import cv2 +import numpy as np + + +def np_img_grey_to_rgb(data): + if data.ndim == 3: + return data + return np.expand_dims(data, 2) * np.ones((1, 1, 3)) + + +def convolve(data1, data2): # fast convolution with fft + if data1.ndim != data2.ndim: # promote to rgb if mismatch + if data1.ndim < 3: + data1 = np_img_grey_to_rgb(data1) + if data2.ndim < 3: + data2 = np_img_grey_to_rgb(data2) + return ifft2(fft2(data1) * fft2(data2)) + + +def fft2(data): + if data.ndim > 2: # multiple channels + out_fft = np.zeros( + (data.shape[0], data.shape[1], data.shape[2]), dtype=np.complex128 + ) + for c in range(data.shape[2]): + c_data = data[:, :, c] + out_fft[:, :, c] = np.fft.fft2(np.fft.fftshift(c_data), norm="ortho") + out_fft[:, :, c] = np.fft.ifftshift(out_fft[:, :, c]) + else: # single channel + out_fft = np.zeros((data.shape[0], data.shape[1]), dtype=np.complex128) + out_fft[:, :] = np.fft.fft2(np.fft.fftshift(data), norm="ortho") + out_fft[:, :] = np.fft.ifftshift(out_fft[:, :]) + + return out_fft + + +def ifft2(data): + if data.ndim > 2: # multiple channels + out_ifft = np.zeros( + (data.shape[0], data.shape[1], data.shape[2]), dtype=np.complex128 + ) + for c in range(data.shape[2]): + c_data = data[:, :, c] + out_ifft[:, :, c] = np.fft.ifft2(np.fft.fftshift(c_data), norm="ortho") + out_ifft[:, :, c] = np.fft.ifftshift(out_ifft[:, :, c]) + else: # single channel + out_ifft = np.zeros((data.shape[0], data.shape[1]), dtype=np.complex128) + out_ifft[:, :] = np.fft.ifft2(np.fft.fftshift(data), norm="ortho") + out_ifft[:, :] = np.fft.ifftshift(out_ifft[:, :]) + + return out_ifft + + +def get_gradient_kernel(width, height, std=3.14, mode="linear"): + window_scale_x = float( + width / min(width, height) + ) # for non-square aspect ratios we still want a circular kernel + window_scale_y = float(height / min(width, height)) + if mode == "gaussian": + x = (np.arange(width) / width * 2.0 - 1.0) * window_scale_x + kx = np.exp(-x * x * std) + if window_scale_x != window_scale_y: + y = (np.arange(height) / height * 2.0 - 1.0) * window_scale_y + ky = np.exp(-y * y * std) + else: + y = x + ky = kx + return np.outer(kx, ky) + elif mode == "linear": + x = (np.arange(width) / width * 2.0 - 1.0) * window_scale_x + if window_scale_x != window_scale_y: + y = (np.arange(height) / height * 2.0 - 1.0) * window_scale_y + else: + y = x + return np.clip(1.0 - np.sqrt(np.add.outer(x * x, y * y)) * std / 3.14, 0.0, 1.0) + else: + raise Exception("Error: Unknown mode in get_gradient_kernel: {0}".format(mode)) + + +def image_blur(data, std=3.14, mode="linear"): + width = data.shape[0] + height = data.shape[1] + kernel = get_gradient_kernel(width, height, std, mode=mode) + return np.real(convolve(data, kernel / np.sqrt(np.sum(kernel * kernel)))) + + +def soften_mask(mask_img, softness, space): + if softness == 0: + return mask_img + softness = min(softness, 1.0) + space = np.clip(space, 0.0, 1.0) + original_max_opacity = np.max(mask_img) + out_mask = mask_img <= 0.0 + blurred_mask = image_blur(mask_img, 3.5 / softness, mode="linear") + blurred_mask = np.maximum(blurred_mask - np.max(blurred_mask[out_mask]), 0.0) + mask_img *= blurred_mask # preserve partial opacity in original input mask + mask_img /= np.max(mask_img) # renormalize + mask_img = np.clip(mask_img - space, 0.0, 1.0) # make space + mask_img /= np.max(mask_img) # and renormalize again + mask_img *= original_max_opacity # restore original max opacity + return mask_img + + +def expand_image( + cv2_img, top: int, right: int, bottom: int, left: int, softness: float, space: float +): + assert cv2_img.shape[2] == 3 + origin_h, origin_w = cv2_img.shape[:2] + new_width = cv2_img.shape[1] + left + right + new_height = cv2_img.shape[0] + top + bottom + + # TODO: which is better? + # new_img = np.random.randint(0, 255, (new_height, new_width, 3), np.uint8) + new_img = cv2.copyMakeBorder( + cv2_img, top, bottom, left, right, cv2.BORDER_REPLICATE + ) + mask_img = np.zeros((new_height, new_width), np.uint8) + mask_img[top : top + cv2_img.shape[0], left : left + cv2_img.shape[1]] = 255 + + if softness > 0.0: + mask_img = soften_mask(mask_img / 255.0, softness / 100.0, space / 100.0) + mask_img = (np.clip(mask_img, 0.0, 1.0) * 255.0).astype(np.uint8) + + mask_image = 255.0 - mask_img # extract mask from alpha channel and invert + rgb_init_image = ( + 0.0 + new_img[:, :, 0:3] + ) # strip mask from init_img leaving only rgb channels + + hard_mask = np.zeros_like(cv2_img[:, :, 0]) + if top != 0: + hard_mask[0 : origin_h // 2, :] = 255 + if bottom != 0: + hard_mask[origin_h // 2 :, :] = 255 + if left != 0: + hard_mask[:, 0 : origin_w // 2] = 255 + if right != 0: + hard_mask[:, origin_w // 2 :] = 255 + + hard_mask = cv2.copyMakeBorder( + hard_mask, top, bottom, left, right, cv2.BORDER_DEFAULT, value=255 + ) + mask_image = np.where(hard_mask > 0, mask_image, 0) + return rgb_init_image.astype(np.uint8), mask_image.astype(np.uint8) + + +if __name__ == "__main__": + from pathlib import Path + + current_dir = Path(__file__).parent.absolute().resolve() + image_path = current_dir.parent / "tests" / "bunny.jpeg" + init_image = cv2.imread(str(image_path)) + init_image, mask_image = expand_image( + init_image, + top=100, + right=100, + bottom=100, + left=100, + softness=20, + space=20, + ) + print(mask_image.dtype, mask_image.min(), mask_image.max()) + print(init_image.dtype, init_image.min(), init_image.max()) + mask_image = mask_image.astype(np.uint8) + init_image = init_image.astype(np.uint8) + cv2.imwrite("expanded_image.png", init_image) + cv2.imwrite("expanded_mask.png", mask_image) diff --git a/py/iopaint/model/instruct_pix2pix.py b/py/iopaint/model/instruct_pix2pix.py new file mode 100644 index 0000000..d4d11bb --- /dev/null +++ b/py/iopaint/model/instruct_pix2pix.py @@ -0,0 +1,64 @@ +import PIL.Image +import cv2 +import torch +from loguru import logger + +from ..const import INSTRUCT_PIX2PIX_NAME +from .base import DiffusionInpaintModel +from ..schema import InpaintRequest +from .utils import get_torch_dtype, enable_low_mem, is_local_files_only + + +class InstructPix2Pix(DiffusionInpaintModel): + name = INSTRUCT_PIX2PIX_NAME + pad_mod = 8 + min_size = 512 + + def init_model(self, device: torch.device, **kwargs): + from diffusers import StableDiffusionInstructPix2PixPipeline + + use_gpu, torch_dtype = get_torch_dtype(device, kwargs.get("no_half", False)) + + model_kwargs = {"local_files_only": is_local_files_only(**kwargs)} + if kwargs["disable_nsfw"] or kwargs.get("cpu_offload", False): + logger.info("Disable Stable Diffusion Model NSFW checker") + model_kwargs.update( + dict( + safety_checker=None, + feature_extractor=None, + requires_safety_checker=False, + ) + ) + + self.model = StableDiffusionInstructPix2PixPipeline.from_pretrained( + self.name, variant="fp16", torch_dtype=torch_dtype, **model_kwargs + ) + enable_low_mem(self.model, kwargs.get("low_mem", False)) + + if kwargs.get("cpu_offload", False) and use_gpu: + logger.info("Enable sequential cpu offload") + self.model.enable_sequential_cpu_offload(gpu_id=0) + else: + self.model = self.model.to(device) + + def forward(self, image, mask, config: InpaintRequest): + """Input image and output image have same size + image: [H, W, C] RGB + mask: [H, W, 1] 255 means area to repaint + return: BGR IMAGE + edit = pipe(prompt, image=image, num_inference_steps=20, image_guidance_scale=1.5, guidance_scale=7).images[0] + """ + output = self.model( + image=PIL.Image.fromarray(image), + prompt=config.prompt, + negative_prompt=config.negative_prompt, + num_inference_steps=config.sd_steps, + image_guidance_scale=config.p2p_image_guidance_scale, + guidance_scale=config.sd_guidance_scale, + output_type="np", + generator=torch.manual_seed(config.sd_seed), + ).images[0] + + output = (output * 255).round().astype("uint8") + output = cv2.cvtColor(output, cv2.COLOR_RGB2BGR) + return output diff --git a/py/iopaint/model/kandinsky.py b/py/iopaint/model/kandinsky.py new file mode 100644 index 0000000..c16bd93 --- /dev/null +++ b/py/iopaint/model/kandinsky.py @@ -0,0 +1,65 @@ +import PIL.Image +import cv2 +import numpy as np +import torch + +from ..const import KANDINSKY22_NAME +from .base import DiffusionInpaintModel +from ..schema import InpaintRequest +from .utils import get_torch_dtype, enable_low_mem, is_local_files_only + + +class Kandinsky(DiffusionInpaintModel): + pad_mod = 64 + min_size = 512 + + def init_model(self, device: torch.device, **kwargs): + from diffusers import AutoPipelineForInpainting + + use_gpu, torch_dtype = get_torch_dtype(device, kwargs.get("no_half", False)) + + model_kwargs = { + "torch_dtype": torch_dtype, + "local_files_only": is_local_files_only(**kwargs), + } + self.model = AutoPipelineForInpainting.from_pretrained( + self.name, **model_kwargs + ).to(device) + enable_low_mem(self.model, kwargs.get("low_mem", False)) + + self.callback = kwargs.pop("callback", None) + + def forward(self, image, mask, config: InpaintRequest): + """Input image and output image have same size + image: [H, W, C] RGB + mask: [H, W, 1] 255 means area to repaint + return: BGR IMAGE + """ + self.set_scheduler(config) + + generator = torch.manual_seed(config.sd_seed) + mask = mask.astype(np.float32) / 255 + img_h, img_w = image.shape[:2] + + # kandinsky 没有 strength + output = self.model( + prompt=config.prompt, + negative_prompt=config.negative_prompt, + image=PIL.Image.fromarray(image), + mask_image=mask[:, :, 0], + height=img_h, + width=img_w, + num_inference_steps=config.sd_steps, + guidance_scale=config.sd_guidance_scale, + output_type="np", + callback_on_step_end=self.callback, + generator=generator, + ).images[0] + + output = (output * 255).round().astype("uint8") + output = cv2.cvtColor(output, cv2.COLOR_RGB2BGR) + return output + + +class Kandinsky22(Kandinsky): + name = KANDINSKY22_NAME diff --git a/py/iopaint/model/lama.py b/py/iopaint/model/lama.py new file mode 100644 index 0000000..e2cfd01 --- /dev/null +++ b/py/iopaint/model/lama.py @@ -0,0 +1,57 @@ +import os + +import cv2 +import numpy as np +import torch + +from ..helper import ( + norm_img, + get_cache_path_by_url, + load_jit_model, + download_model, +) +from ..schema import InpaintRequest +from .base import InpaintModel + +LAMA_MODEL_URL = os.environ.get( + "LAMA_MODEL_URL", + "https://github.com/Sanster/models/releases/download/add_big_lama/big-lama.pt", +) +LAMA_MODEL_MD5 = os.environ.get("LAMA_MODEL_MD5", "e3aa4aaa15225a33ec84f9f4bc47e500") + + +class LaMa(InpaintModel): + name = "lama" + pad_mod = 8 + is_erase_model = True + + @staticmethod + def download(): + download_model(LAMA_MODEL_URL, LAMA_MODEL_MD5) + + def init_model(self, device, **kwargs): + self.model = load_jit_model(LAMA_MODEL_URL, device, LAMA_MODEL_MD5).eval() + + @staticmethod + def is_downloaded() -> bool: + return os.path.exists(get_cache_path_by_url(LAMA_MODEL_URL)) + + def forward(self, image, mask, config: InpaintRequest): + """Input image and output image have same size + image: [H, W, C] RGB + mask: [H, W] + return: BGR IMAGE + """ + image = norm_img(image) + mask = norm_img(mask) + + mask = (mask > 0) * 1 + image = torch.from_numpy(image).unsqueeze(0).to(self.device) + mask = torch.from_numpy(mask).unsqueeze(0).to(self.device) + + inpainted_image = self.model(image, mask) + + cur_res = inpainted_image[0].permute(1, 2, 0).detach().cpu().numpy() + cur_res = np.clip(cur_res * 255, 0, 255).astype("uint8") + cur_res = cv2.cvtColor(cur_res, cv2.COLOR_RGB2BGR) + return cur_res diff --git a/py/iopaint/model/ldm.py b/py/iopaint/model/ldm.py new file mode 100644 index 0000000..f0d08c4 --- /dev/null +++ b/py/iopaint/model/ldm.py @@ -0,0 +1,336 @@ +import os + +import numpy as np +import torch +from loguru import logger + +from .base import InpaintModel +from .ddim_sampler import DDIMSampler +from .plms_sampler import PLMSSampler +from ..schema import InpaintRequest, LDMSampler + +torch.manual_seed(42) +import torch.nn as nn +from ..helper import ( + download_model, + norm_img, + get_cache_path_by_url, + load_jit_model, +) +from .utils import ( + make_beta_schedule, + timestep_embedding, +) + +LDM_ENCODE_MODEL_URL = os.environ.get( + "LDM_ENCODE_MODEL_URL", + "https://github.com/Sanster/models/releases/download/add_ldm/cond_stage_model_encode.pt", +) +LDM_ENCODE_MODEL_MD5 = os.environ.get( + "LDM_ENCODE_MODEL_MD5", "23239fc9081956a3e70de56472b3f296" +) + +LDM_DECODE_MODEL_URL = os.environ.get( + "LDM_DECODE_MODEL_URL", + "https://github.com/Sanster/models/releases/download/add_ldm/cond_stage_model_decode.pt", +) +LDM_DECODE_MODEL_MD5 = os.environ.get( + "LDM_DECODE_MODEL_MD5", "fe419cd15a750d37a4733589d0d3585c" +) + +LDM_DIFFUSION_MODEL_URL = os.environ.get( + "LDM_DIFFUSION_MODEL_URL", + "https://github.com/Sanster/models/releases/download/add_ldm/diffusion.pt", +) + +LDM_DIFFUSION_MODEL_MD5 = os.environ.get( + "LDM_DIFFUSION_MODEL_MD5", "b0afda12bf790c03aba2a7431f11d22d" +) + + +class DDPM(nn.Module): + # classic DDPM with Gaussian diffusion, in image space + def __init__( + self, + device, + timesteps=1000, + beta_schedule="linear", + linear_start=0.0015, + linear_end=0.0205, + cosine_s=0.008, + original_elbo_weight=0.0, + v_posterior=0.0, # weight for choosing posterior variance as sigma = (1-v) * beta_tilde + v * beta + l_simple_weight=1.0, + parameterization="eps", # all assuming fixed variance schedules + use_positional_encodings=False, + ): + super().__init__() + self.device = device + self.parameterization = parameterization + self.use_positional_encodings = use_positional_encodings + + self.v_posterior = v_posterior + self.original_elbo_weight = original_elbo_weight + self.l_simple_weight = l_simple_weight + + self.register_schedule( + beta_schedule=beta_schedule, + timesteps=timesteps, + linear_start=linear_start, + linear_end=linear_end, + cosine_s=cosine_s, + ) + + def register_schedule( + self, + given_betas=None, + beta_schedule="linear", + timesteps=1000, + linear_start=1e-4, + linear_end=2e-2, + cosine_s=8e-3, + ): + betas = make_beta_schedule( + self.device, + beta_schedule, + timesteps, + linear_start=linear_start, + linear_end=linear_end, + cosine_s=cosine_s, + ) + alphas = 1.0 - betas + alphas_cumprod = np.cumprod(alphas, axis=0) + alphas_cumprod_prev = np.append(1.0, alphas_cumprod[:-1]) + + (timesteps,) = betas.shape + self.num_timesteps = int(timesteps) + self.linear_start = linear_start + self.linear_end = linear_end + assert ( + alphas_cumprod.shape[0] == self.num_timesteps + ), "alphas have to be defined for each timestep" + + to_torch = lambda x: torch.tensor(x, dtype=torch.float32).to(self.device) + + self.register_buffer("betas", to_torch(betas)) + self.register_buffer("alphas_cumprod", to_torch(alphas_cumprod)) + self.register_buffer("alphas_cumprod_prev", to_torch(alphas_cumprod_prev)) + + # calculations for diffusion q(x_t | x_{t-1}) and others + self.register_buffer("sqrt_alphas_cumprod", to_torch(np.sqrt(alphas_cumprod))) + self.register_buffer( + "sqrt_one_minus_alphas_cumprod", to_torch(np.sqrt(1.0 - alphas_cumprod)) + ) + self.register_buffer( + "log_one_minus_alphas_cumprod", to_torch(np.log(1.0 - alphas_cumprod)) + ) + self.register_buffer( + "sqrt_recip_alphas_cumprod", to_torch(np.sqrt(1.0 / alphas_cumprod)) + ) + self.register_buffer( + "sqrt_recipm1_alphas_cumprod", to_torch(np.sqrt(1.0 / alphas_cumprod - 1)) + ) + + # calculations for posterior q(x_{t-1} | x_t, x_0) + posterior_variance = (1 - self.v_posterior) * betas * ( + 1.0 - alphas_cumprod_prev + ) / (1.0 - alphas_cumprod) + self.v_posterior * betas + # above: equal to 1. / (1. / (1. - alpha_cumprod_tm1) + alpha_t / beta_t) + self.register_buffer("posterior_variance", to_torch(posterior_variance)) + # below: log calculation clipped because the posterior variance is 0 at the beginning of the diffusion chain + self.register_buffer( + "posterior_log_variance_clipped", + to_torch(np.log(np.maximum(posterior_variance, 1e-20))), + ) + self.register_buffer( + "posterior_mean_coef1", + to_torch(betas * np.sqrt(alphas_cumprod_prev) / (1.0 - alphas_cumprod)), + ) + self.register_buffer( + "posterior_mean_coef2", + to_torch( + (1.0 - alphas_cumprod_prev) * np.sqrt(alphas) / (1.0 - alphas_cumprod) + ), + ) + + if self.parameterization == "eps": + lvlb_weights = self.betas**2 / ( + 2 + * self.posterior_variance + * to_torch(alphas) + * (1 - self.alphas_cumprod) + ) + elif self.parameterization == "x0": + lvlb_weights = ( + 0.5 + * np.sqrt(torch.Tensor(alphas_cumprod)) + / (2.0 * 1 - torch.Tensor(alphas_cumprod)) + ) + else: + raise NotImplementedError("mu not supported") + # TODO how to choose this term + lvlb_weights[0] = lvlb_weights[1] + self.register_buffer("lvlb_weights", lvlb_weights, persistent=False) + assert not torch.isnan(self.lvlb_weights).all() + + +class LatentDiffusion(DDPM): + def __init__( + self, + diffusion_model, + device, + cond_stage_key="image", + cond_stage_trainable=False, + concat_mode=True, + scale_factor=1.0, + scale_by_std=False, + *args, + **kwargs, + ): + self.num_timesteps_cond = 1 + self.scale_by_std = scale_by_std + super().__init__(device, *args, **kwargs) + self.diffusion_model = diffusion_model + self.concat_mode = concat_mode + self.cond_stage_trainable = cond_stage_trainable + self.cond_stage_key = cond_stage_key + self.num_downs = 2 + self.scale_factor = scale_factor + + def make_cond_schedule( + self, + ): + self.cond_ids = torch.full( + size=(self.num_timesteps,), + fill_value=self.num_timesteps - 1, + dtype=torch.long, + ) + ids = torch.round( + torch.linspace(0, self.num_timesteps - 1, self.num_timesteps_cond) + ).long() + self.cond_ids[: self.num_timesteps_cond] = ids + + def register_schedule( + self, + given_betas=None, + beta_schedule="linear", + timesteps=1000, + linear_start=1e-4, + linear_end=2e-2, + cosine_s=8e-3, + ): + super().register_schedule( + given_betas, beta_schedule, timesteps, linear_start, linear_end, cosine_s + ) + + self.shorten_cond_schedule = self.num_timesteps_cond > 1 + if self.shorten_cond_schedule: + self.make_cond_schedule() + + def apply_model(self, x_noisy, t, cond): + # x_recon = self.model(x_noisy, t, cond['c_concat'][0]) # cond['c_concat'][0].shape 1,4,128,128 + t_emb = timestep_embedding(x_noisy.device, t, 256, repeat_only=False) + x_recon = self.diffusion_model(x_noisy, t_emb, cond) + return x_recon + + +class LDM(InpaintModel): + name = "ldm" + pad_mod = 32 + is_erase_model = True + + def __init__(self, device, fp16: bool = True, **kwargs): + self.fp16 = fp16 + super().__init__(device) + self.device = device + + def init_model(self, device, **kwargs): + self.diffusion_model = load_jit_model( + LDM_DIFFUSION_MODEL_URL, device, LDM_DIFFUSION_MODEL_MD5 + ) + self.cond_stage_model_decode = load_jit_model( + LDM_DECODE_MODEL_URL, device, LDM_DECODE_MODEL_MD5 + ) + self.cond_stage_model_encode = load_jit_model( + LDM_ENCODE_MODEL_URL, device, LDM_ENCODE_MODEL_MD5 + ) + if self.fp16 and "cuda" in str(device): + self.diffusion_model = self.diffusion_model.half() + self.cond_stage_model_decode = self.cond_stage_model_decode.half() + self.cond_stage_model_encode = self.cond_stage_model_encode.half() + + self.model = LatentDiffusion(self.diffusion_model, device) + + @staticmethod + def download(): + download_model(LDM_DIFFUSION_MODEL_URL, LDM_DIFFUSION_MODEL_MD5) + download_model(LDM_DECODE_MODEL_URL, LDM_DECODE_MODEL_MD5) + download_model(LDM_ENCODE_MODEL_URL, LDM_ENCODE_MODEL_MD5) + + @staticmethod + def is_downloaded() -> bool: + model_paths = [ + get_cache_path_by_url(LDM_DIFFUSION_MODEL_URL), + get_cache_path_by_url(LDM_DECODE_MODEL_URL), + get_cache_path_by_url(LDM_ENCODE_MODEL_URL), + ] + return all([os.path.exists(it) for it in model_paths]) + + @torch.cuda.amp.autocast() + def forward(self, image, mask, config: InpaintRequest): + """ + image: [H, W, C] RGB + mask: [H, W, 1] + return: BGR IMAGE + """ + # image [1,3,512,512] float32 + # mask: [1,1,512,512] float32 + # masked_image: [1,3,512,512] float32 + if config.ldm_sampler == LDMSampler.ddim: + sampler = DDIMSampler(self.model) + elif config.ldm_sampler == LDMSampler.plms: + sampler = PLMSSampler(self.model) + else: + raise ValueError() + + steps = config.ldm_steps + image = norm_img(image) + mask = norm_img(mask) + + mask[mask < 0.5] = 0 + mask[mask >= 0.5] = 1 + + image = torch.from_numpy(image).unsqueeze(0).to(self.device) + mask = torch.from_numpy(mask).unsqueeze(0).to(self.device) + masked_image = (1 - mask) * image + + mask = self._norm(mask) + masked_image = self._norm(masked_image) + + c = self.cond_stage_model_encode(masked_image) + torch.cuda.empty_cache() + + cc = torch.nn.functional.interpolate(mask, size=c.shape[-2:]) # 1,1,128,128 + c = torch.cat((c, cc), dim=1) # 1,4,128,128 + + shape = (c.shape[1] - 1,) + c.shape[2:] + samples_ddim = sampler.sample( + steps=steps, conditioning=c, batch_size=c.shape[0], shape=shape + ) + torch.cuda.empty_cache() + x_samples_ddim = self.cond_stage_model_decode( + samples_ddim + ) # samples_ddim: 1, 3, 128, 128 float32 + torch.cuda.empty_cache() + + # image = torch.clamp((image + 1.0) / 2.0, min=0.0, max=1.0) + # mask = torch.clamp((mask + 1.0) / 2.0, min=0.0, max=1.0) + inpainted_image = torch.clamp((x_samples_ddim + 1.0) / 2.0, min=0.0, max=1.0) + + # inpainted = (1 - mask) * image + mask * predicted_image + inpainted_image = inpainted_image.cpu().numpy().transpose(0, 2, 3, 1)[0] * 255 + inpainted_image = inpainted_image.astype(np.uint8)[:, :, ::-1] + return inpainted_image + + def _norm(self, tensor): + return tensor * 2.0 - 1.0 diff --git a/py/iopaint/model/manga.py b/py/iopaint/model/manga.py new file mode 100644 index 0000000..60d75bc --- /dev/null +++ b/py/iopaint/model/manga.py @@ -0,0 +1,97 @@ +import os +import random + +import cv2 +import numpy as np +import torch +import time +from loguru import logger + +from ..helper import get_cache_path_by_url, load_jit_model, download_model +from .base import InpaintModel +from ..schema import InpaintRequest + + +MANGA_INPAINTOR_MODEL_URL = os.environ.get( + "MANGA_INPAINTOR_MODEL_URL", + "https://github.com/Sanster/models/releases/download/manga/manga_inpaintor.jit", +) +MANGA_INPAINTOR_MODEL_MD5 = os.environ.get( + "MANGA_INPAINTOR_MODEL_MD5", "7d8b269c4613b6b3768af714610da86c" +) + +MANGA_LINE_MODEL_URL = os.environ.get( + "MANGA_LINE_MODEL_URL", + "https://github.com/Sanster/models/releases/download/manga/erika.jit", +) +MANGA_LINE_MODEL_MD5 = os.environ.get( + "MANGA_LINE_MODEL_MD5", "0c926d5a4af8450b0d00bc5b9a095644" +) + + +class Manga(InpaintModel): + name = "manga" + pad_mod = 16 + is_erase_model = True + + def init_model(self, device, **kwargs): + self.inpaintor_model = load_jit_model( + MANGA_INPAINTOR_MODEL_URL, device, MANGA_INPAINTOR_MODEL_MD5 + ) + self.line_model = load_jit_model( + MANGA_LINE_MODEL_URL, device, MANGA_LINE_MODEL_MD5 + ) + self.seed = 42 + + @staticmethod + def download(): + download_model(MANGA_INPAINTOR_MODEL_URL, MANGA_INPAINTOR_MODEL_MD5) + download_model(MANGA_LINE_MODEL_URL, MANGA_LINE_MODEL_MD5) + + @staticmethod + def is_downloaded() -> bool: + model_paths = [ + get_cache_path_by_url(MANGA_INPAINTOR_MODEL_URL), + get_cache_path_by_url(MANGA_LINE_MODEL_URL), + ] + return all([os.path.exists(it) for it in model_paths]) + + def forward(self, image, mask, config: InpaintRequest): + """ + image: [H, W, C] RGB + mask: [H, W, 1] + return: BGR IMAGE + """ + seed = self.seed + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + torch.cuda.manual_seed_all(seed) + + gray_img = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) + gray_img = torch.from_numpy( + gray_img[np.newaxis, np.newaxis, :, :].astype(np.float32) + ).to(self.device) + start = time.time() + lines = self.line_model(gray_img) + torch.cuda.empty_cache() + lines = torch.clamp(lines, 0, 255) + logger.info(f"erika_model time: {time.time() - start}") + + mask = torch.from_numpy(mask[np.newaxis, :, :, :]).to(self.device) + mask = mask.permute(0, 3, 1, 2) + mask = torch.where(mask > 0.5, 1.0, 0.0) + noise = torch.randn_like(mask) + ones = torch.ones_like(mask) + + gray_img = gray_img / 255 * 2 - 1.0 + lines = lines / 255 * 2 - 1.0 + + start = time.time() + inpainted_image = self.inpaintor_model(gray_img, lines, mask, noise, ones) + logger.info(f"image_inpaintor_model time: {time.time() - start}") + + cur_res = inpainted_image[0].permute(1, 2, 0).detach().cpu().numpy() + cur_res = (cur_res * 127.5 + 127.5).astype(np.uint8) + cur_res = cv2.cvtColor(cur_res, cv2.COLOR_GRAY2BGR) + return cur_res diff --git a/py/iopaint/model/mat.py b/py/iopaint/model/mat.py new file mode 100644 index 0000000..f8ea45b --- /dev/null +++ b/py/iopaint/model/mat.py @@ -0,0 +1,1945 @@ +import os +import random + +import cv2 +import numpy as np +import torch +import torch.nn as nn +import torch.nn.functional as F +import torch.utils.checkpoint as checkpoint + +from ..helper import ( + load_model, + get_cache_path_by_url, + norm_img, + download_model, +) +from ..schema import InpaintRequest +from .base import InpaintModel +from .utils import ( + setup_filter, + Conv2dLayer, + FullyConnectedLayer, + conv2d_resample, + bias_act, + upsample2d, + activation_funcs, + MinibatchStdLayer, + to_2tuple, + normalize_2nd_moment, + set_seed, +) + + +class ModulatedConv2d(nn.Module): + def __init__( + self, + in_channels, # Number of input channels. + out_channels, # Number of output channels. + kernel_size, # Width and height of the convolution kernel. + style_dim, # dimension of the style code + demodulate=True, # perfrom demodulation + up=1, # Integer upsampling factor. + down=1, # Integer downsampling factor. + resample_filter=[ + 1, + 3, + 3, + 1, + ], # Low-pass filter to apply when resampling activations. + conv_clamp=None, # Clamp the output to +-X, None = disable clamping. + ): + super().__init__() + self.demodulate = demodulate + + self.weight = torch.nn.Parameter( + torch.randn([1, out_channels, in_channels, kernel_size, kernel_size]) + ) + self.out_channels = out_channels + self.kernel_size = kernel_size + self.weight_gain = 1 / np.sqrt(in_channels * (kernel_size**2)) + self.padding = self.kernel_size // 2 + self.up = up + self.down = down + self.register_buffer("resample_filter", setup_filter(resample_filter)) + self.conv_clamp = conv_clamp + + self.affine = FullyConnectedLayer(style_dim, in_channels, bias_init=1) + + def forward(self, x, style): + batch, in_channels, height, width = x.shape + style = self.affine(style).view(batch, 1, in_channels, 1, 1) + weight = self.weight * self.weight_gain * style + + if self.demodulate: + decoefs = (weight.pow(2).sum(dim=[2, 3, 4]) + 1e-8).rsqrt() + weight = weight * decoefs.view(batch, self.out_channels, 1, 1, 1) + + weight = weight.view( + batch * self.out_channels, in_channels, self.kernel_size, self.kernel_size + ) + x = x.view(1, batch * in_channels, height, width) + x = conv2d_resample( + x=x, + w=weight, + f=self.resample_filter, + up=self.up, + down=self.down, + padding=self.padding, + groups=batch, + ) + out = x.view(batch, self.out_channels, *x.shape[2:]) + + return out + + +class StyleConv(torch.nn.Module): + def __init__( + self, + in_channels, # Number of input channels. + out_channels, # Number of output channels. + style_dim, # Intermediate latent (W) dimensionality. + resolution, # Resolution of this layer. + kernel_size=3, # Convolution kernel size. + up=1, # Integer upsampling factor. + use_noise=False, # Enable noise input? + activation="lrelu", # Activation function: 'relu', 'lrelu', etc. + resample_filter=[ + 1, + 3, + 3, + 1, + ], # Low-pass filter to apply when resampling activations. + conv_clamp=None, # Clamp the output of convolution layers to +-X, None = disable clamping. + demodulate=True, # perform demodulation + ): + super().__init__() + + self.conv = ModulatedConv2d( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=kernel_size, + style_dim=style_dim, + demodulate=demodulate, + up=up, + resample_filter=resample_filter, + conv_clamp=conv_clamp, + ) + + self.use_noise = use_noise + self.resolution = resolution + if use_noise: + self.register_buffer("noise_const", torch.randn([resolution, resolution])) + self.noise_strength = torch.nn.Parameter(torch.zeros([])) + + self.bias = torch.nn.Parameter(torch.zeros([out_channels])) + self.activation = activation + self.act_gain = activation_funcs[activation].def_gain + self.conv_clamp = conv_clamp + + def forward(self, x, style, noise_mode="random", gain=1): + x = self.conv(x, style) + + assert noise_mode in ["random", "const", "none"] + + if self.use_noise: + if noise_mode == "random": + xh, xw = x.size()[-2:] + noise = ( + torch.randn([x.shape[0], 1, xh, xw], device=x.device) + * self.noise_strength + ) + if noise_mode == "const": + noise = self.noise_const * self.noise_strength + x = x + noise + + act_gain = self.act_gain * gain + act_clamp = self.conv_clamp * gain if self.conv_clamp is not None else None + out = bias_act( + x, self.bias, act=self.activation, gain=act_gain, clamp=act_clamp + ) + + return out + + +class ToRGB(torch.nn.Module): + def __init__( + self, + in_channels, + out_channels, + style_dim, + kernel_size=1, + resample_filter=[1, 3, 3, 1], + conv_clamp=None, + demodulate=False, + ): + super().__init__() + + self.conv = ModulatedConv2d( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=kernel_size, + style_dim=style_dim, + demodulate=demodulate, + resample_filter=resample_filter, + conv_clamp=conv_clamp, + ) + self.bias = torch.nn.Parameter(torch.zeros([out_channels])) + self.register_buffer("resample_filter", setup_filter(resample_filter)) + self.conv_clamp = conv_clamp + + def forward(self, x, style, skip=None): + x = self.conv(x, style) + out = bias_act(x, self.bias, clamp=self.conv_clamp) + + if skip is not None: + if skip.shape != out.shape: + skip = upsample2d(skip, self.resample_filter) + out = out + skip + + return out + + +def get_style_code(a, b): + return torch.cat([a, b], dim=1) + + +class DecBlockFirst(nn.Module): + def __init__( + self, + in_channels, + out_channels, + activation, + style_dim, + use_noise, + demodulate, + img_channels, + ): + super().__init__() + self.fc = FullyConnectedLayer( + in_features=in_channels * 2, + out_features=in_channels * 4**2, + activation=activation, + ) + self.conv = StyleConv( + in_channels=in_channels, + out_channels=out_channels, + style_dim=style_dim, + resolution=4, + kernel_size=3, + use_noise=use_noise, + activation=activation, + demodulate=demodulate, + ) + self.toRGB = ToRGB( + in_channels=out_channels, + out_channels=img_channels, + style_dim=style_dim, + kernel_size=1, + demodulate=False, + ) + + def forward(self, x, ws, gs, E_features, noise_mode="random"): + x = self.fc(x).view(x.shape[0], -1, 4, 4) + x = x + E_features[2] + style = get_style_code(ws[:, 0], gs) + x = self.conv(x, style, noise_mode=noise_mode) + style = get_style_code(ws[:, 1], gs) + img = self.toRGB(x, style, skip=None) + + return x, img + + +class DecBlockFirstV2(nn.Module): + def __init__( + self, + in_channels, + out_channels, + activation, + style_dim, + use_noise, + demodulate, + img_channels, + ): + super().__init__() + self.conv0 = Conv2dLayer( + in_channels=in_channels, + out_channels=in_channels, + kernel_size=3, + activation=activation, + ) + self.conv1 = StyleConv( + in_channels=in_channels, + out_channels=out_channels, + style_dim=style_dim, + resolution=4, + kernel_size=3, + use_noise=use_noise, + activation=activation, + demodulate=demodulate, + ) + self.toRGB = ToRGB( + in_channels=out_channels, + out_channels=img_channels, + style_dim=style_dim, + kernel_size=1, + demodulate=False, + ) + + def forward(self, x, ws, gs, E_features, noise_mode="random"): + # x = self.fc(x).view(x.shape[0], -1, 4, 4) + x = self.conv0(x) + x = x + E_features[2] + style = get_style_code(ws[:, 0], gs) + x = self.conv1(x, style, noise_mode=noise_mode) + style = get_style_code(ws[:, 1], gs) + img = self.toRGB(x, style, skip=None) + + return x, img + + +class DecBlock(nn.Module): + def __init__( + self, + res, + in_channels, + out_channels, + activation, + style_dim, + use_noise, + demodulate, + img_channels, + ): # res = 2, ..., resolution_log2 + super().__init__() + self.res = res + + self.conv0 = StyleConv( + in_channels=in_channels, + out_channels=out_channels, + style_dim=style_dim, + resolution=2**res, + kernel_size=3, + up=2, + use_noise=use_noise, + activation=activation, + demodulate=demodulate, + ) + self.conv1 = StyleConv( + in_channels=out_channels, + out_channels=out_channels, + style_dim=style_dim, + resolution=2**res, + kernel_size=3, + use_noise=use_noise, + activation=activation, + demodulate=demodulate, + ) + self.toRGB = ToRGB( + in_channels=out_channels, + out_channels=img_channels, + style_dim=style_dim, + kernel_size=1, + demodulate=False, + ) + + def forward(self, x, img, ws, gs, E_features, noise_mode="random"): + style = get_style_code(ws[:, self.res * 2 - 5], gs) + x = self.conv0(x, style, noise_mode=noise_mode) + x = x + E_features[self.res] + style = get_style_code(ws[:, self.res * 2 - 4], gs) + x = self.conv1(x, style, noise_mode=noise_mode) + style = get_style_code(ws[:, self.res * 2 - 3], gs) + img = self.toRGB(x, style, skip=img) + + return x, img + + +class MappingNet(torch.nn.Module): + def __init__( + self, + z_dim, # Input latent (Z) dimensionality, 0 = no latent. + c_dim, # Conditioning label (C) dimensionality, 0 = no label. + w_dim, # Intermediate latent (W) dimensionality. + num_ws, # Number of intermediate latents to output, None = do not broadcast. + num_layers=8, # Number of mapping layers. + embed_features=None, # Label embedding dimensionality, None = same as w_dim. + layer_features=None, # Number of intermediate features in the mapping layers, None = same as w_dim. + activation="lrelu", # Activation function: 'relu', 'lrelu', etc. + lr_multiplier=0.01, # Learning rate multiplier for the mapping layers. + w_avg_beta=0.995, # Decay for tracking the moving average of W during training, None = do not track. + torch_dtype=torch.float32, + ): + super().__init__() + self.z_dim = z_dim + self.c_dim = c_dim + self.w_dim = w_dim + self.num_ws = num_ws + self.num_layers = num_layers + self.w_avg_beta = w_avg_beta + self.torch_dtype = torch_dtype + + if embed_features is None: + embed_features = w_dim + if c_dim == 0: + embed_features = 0 + if layer_features is None: + layer_features = w_dim + features_list = ( + [z_dim + embed_features] + [layer_features] * (num_layers - 1) + [w_dim] + ) + + if c_dim > 0: + self.embed = FullyConnectedLayer(c_dim, embed_features) + for idx in range(num_layers): + in_features = features_list[idx] + out_features = features_list[idx + 1] + layer = FullyConnectedLayer( + in_features, + out_features, + activation=activation, + lr_multiplier=lr_multiplier, + ) + setattr(self, f"fc{idx}", layer) + + if num_ws is not None and w_avg_beta is not None: + self.register_buffer("w_avg", torch.zeros([w_dim])) + + def forward( + self, z, c, truncation_psi=1, truncation_cutoff=None, skip_w_avg_update=False + ): + # Embed, normalize, and concat inputs. + x = None + if self.z_dim > 0: + x = normalize_2nd_moment(z) + if self.c_dim > 0: + y = normalize_2nd_moment(self.embed(c)) + x = torch.cat([x, y], dim=1) if x is not None else y + + # Main layers. + for idx in range(self.num_layers): + layer = getattr(self, f"fc{idx}") + x = layer(x) + + # Update moving average of W. + if self.w_avg_beta is not None and self.training and not skip_w_avg_update: + self.w_avg.copy_(x.detach().mean(dim=0).lerp(self.w_avg, self.w_avg_beta)) + + # Broadcast. + if self.num_ws is not None: + x = x.unsqueeze(1).repeat([1, self.num_ws, 1]) + + # Apply truncation. + if truncation_psi != 1: + assert self.w_avg_beta is not None + if self.num_ws is None or truncation_cutoff is None: + x = self.w_avg.lerp(x, truncation_psi) + else: + x[:, :truncation_cutoff] = self.w_avg.lerp( + x[:, :truncation_cutoff], truncation_psi + ) + + return x + + +class DisFromRGB(nn.Module): + def __init__( + self, in_channels, out_channels, activation + ): # res = 2, ..., resolution_log2 + super().__init__() + self.conv = Conv2dLayer( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=1, + activation=activation, + ) + + def forward(self, x): + return self.conv(x) + + +class DisBlock(nn.Module): + def __init__( + self, in_channels, out_channels, activation + ): # res = 2, ..., resolution_log2 + super().__init__() + self.conv0 = Conv2dLayer( + in_channels=in_channels, + out_channels=in_channels, + kernel_size=3, + activation=activation, + ) + self.conv1 = Conv2dLayer( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=3, + down=2, + activation=activation, + ) + self.skip = Conv2dLayer( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=1, + down=2, + bias=False, + ) + + def forward(self, x): + skip = self.skip(x, gain=np.sqrt(0.5)) + x = self.conv0(x) + x = self.conv1(x, gain=np.sqrt(0.5)) + out = skip + x + + return out + + +class Discriminator(torch.nn.Module): + def __init__( + self, + c_dim, # Conditioning label (C) dimensionality. + img_resolution, # Input resolution. + img_channels, # Number of input color channels. + channel_base=32768, # Overall multiplier for the number of channels. + channel_max=512, # Maximum number of channels in any layer. + channel_decay=1, + cmap_dim=None, # Dimensionality of mapped conditioning label, None = default. + activation="lrelu", + mbstd_group_size=4, # Group size for the minibatch standard deviation layer, None = entire minibatch. + mbstd_num_channels=1, # Number of features for the minibatch standard deviation layer, 0 = disable. + ): + super().__init__() + self.c_dim = c_dim + self.img_resolution = img_resolution + self.img_channels = img_channels + + resolution_log2 = int(np.log2(img_resolution)) + assert img_resolution == 2**resolution_log2 and img_resolution >= 4 + self.resolution_log2 = resolution_log2 + + def nf(stage): + return np.clip( + int(channel_base / 2 ** (stage * channel_decay)), 1, channel_max + ) + + if cmap_dim == None: + cmap_dim = nf(2) + if c_dim == 0: + cmap_dim = 0 + self.cmap_dim = cmap_dim + + if c_dim > 0: + self.mapping = MappingNet( + z_dim=0, c_dim=c_dim, w_dim=cmap_dim, num_ws=None, w_avg_beta=None + ) + + Dis = [DisFromRGB(img_channels + 1, nf(resolution_log2), activation)] + for res in range(resolution_log2, 2, -1): + Dis.append(DisBlock(nf(res), nf(res - 1), activation)) + + if mbstd_num_channels > 0: + Dis.append( + MinibatchStdLayer( + group_size=mbstd_group_size, num_channels=mbstd_num_channels + ) + ) + Dis.append( + Conv2dLayer( + nf(2) + mbstd_num_channels, nf(2), kernel_size=3, activation=activation + ) + ) + self.Dis = nn.Sequential(*Dis) + + self.fc0 = FullyConnectedLayer(nf(2) * 4**2, nf(2), activation=activation) + self.fc1 = FullyConnectedLayer(nf(2), 1 if cmap_dim == 0 else cmap_dim) + + def forward(self, images_in, masks_in, c): + x = torch.cat([masks_in - 0.5, images_in], dim=1) + x = self.Dis(x) + x = self.fc1(self.fc0(x.flatten(start_dim=1))) + + if self.c_dim > 0: + cmap = self.mapping(None, c) + + if self.cmap_dim > 0: + x = (x * cmap).sum(dim=1, keepdim=True) * (1 / np.sqrt(self.cmap_dim)) + + return x + + +def nf(stage, channel_base=32768, channel_decay=1.0, channel_max=512): + NF = {512: 64, 256: 128, 128: 256, 64: 512, 32: 512, 16: 512, 8: 512, 4: 512} + return NF[2**stage] + + +class Mlp(nn.Module): + def __init__( + self, + in_features, + hidden_features=None, + out_features=None, + act_layer=nn.GELU, + drop=0.0, + ): + super().__init__() + out_features = out_features or in_features + hidden_features = hidden_features or in_features + self.fc1 = FullyConnectedLayer( + in_features=in_features, out_features=hidden_features, activation="lrelu" + ) + self.fc2 = FullyConnectedLayer( + in_features=hidden_features, out_features=out_features + ) + + def forward(self, x): + x = self.fc1(x) + x = self.fc2(x) + return x + + +def window_partition(x, window_size): + """ + Args: + x: (B, H, W, C) + window_size (int): window size + Returns: + windows: (num_windows*B, window_size, window_size, C) + """ + B, H, W, C = x.shape + x = x.view(B, H // window_size, window_size, W // window_size, window_size, C) + windows = ( + x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C) + ) + return windows + + +def window_reverse(windows, window_size: int, H: int, W: int): + """ + Args: + windows: (num_windows*B, window_size, window_size, C) + window_size (int): Window size + H (int): Height of image + W (int): Width of image + Returns: + x: (B, H, W, C) + """ + B = int(windows.shape[0] / (H * W / window_size / window_size)) + # B = windows.shape[0] / (H * W / window_size / window_size) + x = windows.view( + B, H // window_size, W // window_size, window_size, window_size, -1 + ) + x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1) + return x + + +class Conv2dLayerPartial(nn.Module): + def __init__( + self, + in_channels, # Number of input channels. + out_channels, # Number of output channels. + kernel_size, # Width and height of the convolution kernel. + bias=True, # Apply additive bias before the activation function? + activation="linear", # Activation function: 'relu', 'lrelu', etc. + up=1, # Integer upsampling factor. + down=1, # Integer downsampling factor. + resample_filter=[ + 1, + 3, + 3, + 1, + ], # Low-pass filter to apply when resampling activations. + conv_clamp=None, # Clamp the output to +-X, None = disable clamping. + trainable=True, # Update the weights of this layer during training? + ): + super().__init__() + self.conv = Conv2dLayer( + in_channels, + out_channels, + kernel_size, + bias, + activation, + up, + down, + resample_filter, + conv_clamp, + trainable, + ) + + self.weight_maskUpdater = torch.ones(1, 1, kernel_size, kernel_size) + self.slide_winsize = kernel_size**2 + self.stride = down + self.padding = kernel_size // 2 if kernel_size % 2 == 1 else 0 + + def forward(self, x, mask=None): + if mask is not None: + with torch.no_grad(): + if self.weight_maskUpdater.type() != x.type(): + self.weight_maskUpdater = self.weight_maskUpdater.to(x) + update_mask = F.conv2d( + mask, + self.weight_maskUpdater, + bias=None, + stride=self.stride, + padding=self.padding, + ) + mask_ratio = self.slide_winsize / (update_mask.to(torch.float32) + 1e-8) + update_mask = torch.clamp(update_mask, 0, 1) # 0 or 1 + mask_ratio = torch.mul(mask_ratio, update_mask).to(x.dtype) + x = self.conv(x) + x = torch.mul(x, mask_ratio) + return x, update_mask + else: + x = self.conv(x) + return x, None + + +class WindowAttention(nn.Module): + r"""Window based multi-head self attention (W-MSA) module with relative position bias. + It supports both of shifted and non-shifted window. + Args: + dim (int): Number of input channels. + window_size (tuple[int]): The height and width of the window. + num_heads (int): Number of attention heads. + qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True + qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set + attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0 + proj_drop (float, optional): Dropout ratio of output. Default: 0.0 + """ + + def __init__( + self, + dim, + window_size, + num_heads, + down_ratio=1, + qkv_bias=True, + qk_scale=None, + attn_drop=0.0, + proj_drop=0.0, + ): + super().__init__() + self.dim = dim + self.window_size = window_size # Wh, Ww + self.num_heads = num_heads + head_dim = dim // num_heads + self.scale = qk_scale or head_dim**-0.5 + + self.q = FullyConnectedLayer(in_features=dim, out_features=dim) + self.k = FullyConnectedLayer(in_features=dim, out_features=dim) + self.v = FullyConnectedLayer(in_features=dim, out_features=dim) + self.proj = FullyConnectedLayer(in_features=dim, out_features=dim) + + self.softmax = nn.Softmax(dim=-1) + + def forward(self, x, mask_windows=None, mask=None): + """ + Args: + x: input features with shape of (num_windows*B, N, C) + mask: (0/-inf) mask with shape of (num_windows, Wh*Ww, Wh*Ww) or None + """ + B_, N, C = x.shape + norm_x = F.normalize(x, p=2.0, dim=-1, eps=torch.finfo(x.dtype).eps) + q = ( + self.q(norm_x) + .reshape(B_, N, self.num_heads, C // self.num_heads) + .permute(0, 2, 1, 3) + ) + k = ( + self.k(norm_x) + .view(B_, -1, self.num_heads, C // self.num_heads) + .permute(0, 2, 3, 1) + ) + v = ( + self.v(x) + .view(B_, -1, self.num_heads, C // self.num_heads) + .permute(0, 2, 1, 3) + ) + + attn = (q @ k) * self.scale + + if mask is not None: + nW = mask.shape[0] + attn = attn.view(B_ // nW, nW, self.num_heads, N, N) + mask.unsqueeze( + 1 + ).unsqueeze(0) + attn = attn.view(-1, self.num_heads, N, N) + + if mask_windows is not None: + attn_mask_windows = mask_windows.squeeze(-1).unsqueeze(1).unsqueeze(1) + attn = attn + attn_mask_windows.masked_fill( + attn_mask_windows == 0, float(-100.0) + ).masked_fill(attn_mask_windows == 1, float(0.0)) + with torch.no_grad(): + mask_windows = torch.clamp( + torch.sum(mask_windows, dim=1, keepdim=True), 0, 1 + ).repeat(1, N, 1) + + attn = self.softmax(attn) + x = (attn @ v).transpose(1, 2).reshape(B_, N, C) + x = self.proj(x) + return x, mask_windows + + +class SwinTransformerBlock(nn.Module): + r"""Swin Transformer Block. + Args: + dim (int): Number of input channels. + input_resolution (tuple[int]): Input resulotion. + num_heads (int): Number of attention heads. + window_size (int): Window size. + shift_size (int): Shift size for SW-MSA. + mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. + qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True + qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set. + drop (float, optional): Dropout rate. Default: 0.0 + attn_drop (float, optional): Attention dropout rate. Default: 0.0 + drop_path (float, optional): Stochastic depth rate. Default: 0.0 + act_layer (nn.Module, optional): Activation layer. Default: nn.GELU + norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm + """ + + def __init__( + self, + dim, + input_resolution, + num_heads, + down_ratio=1, + window_size=7, + shift_size=0, + mlp_ratio=4.0, + qkv_bias=True, + qk_scale=None, + drop=0.0, + attn_drop=0.0, + drop_path=0.0, + act_layer=nn.GELU, + norm_layer=nn.LayerNorm, + ): + super().__init__() + self.dim = dim + self.input_resolution = input_resolution + self.num_heads = num_heads + self.window_size = window_size + self.shift_size = shift_size + self.mlp_ratio = mlp_ratio + if min(self.input_resolution) <= self.window_size: + # if window size is larger than input resolution, we don't partition windows + self.shift_size = 0 + self.window_size = min(self.input_resolution) + assert ( + 0 <= self.shift_size < self.window_size + ), "shift_size must in 0-window_size" + + if self.shift_size > 0: + down_ratio = 1 + self.attn = WindowAttention( + dim, + window_size=to_2tuple(self.window_size), + num_heads=num_heads, + down_ratio=down_ratio, + qkv_bias=qkv_bias, + qk_scale=qk_scale, + attn_drop=attn_drop, + proj_drop=drop, + ) + + self.fuse = FullyConnectedLayer( + in_features=dim * 2, out_features=dim, activation="lrelu" + ) + + mlp_hidden_dim = int(dim * mlp_ratio) + self.mlp = Mlp( + in_features=dim, + hidden_features=mlp_hidden_dim, + act_layer=act_layer, + drop=drop, + ) + + if self.shift_size > 0: + attn_mask = self.calculate_mask(self.input_resolution) + else: + attn_mask = None + + self.register_buffer("attn_mask", attn_mask) + + def calculate_mask(self, x_size): + # calculate attention mask for SW-MSA + H, W = x_size + img_mask = torch.zeros((1, H, W, 1)) # 1 H W 1 + h_slices = ( + slice(0, -self.window_size), + slice(-self.window_size, -self.shift_size), + slice(-self.shift_size, None), + ) + w_slices = ( + slice(0, -self.window_size), + slice(-self.window_size, -self.shift_size), + slice(-self.shift_size, None), + ) + cnt = 0 + for h in h_slices: + for w in w_slices: + img_mask[:, h, w, :] = cnt + cnt += 1 + + mask_windows = window_partition( + img_mask, self.window_size + ) # nW, window_size, window_size, 1 + mask_windows = mask_windows.view(-1, self.window_size * self.window_size) + attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2) + attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill( + attn_mask == 0, float(0.0) + ) + + return attn_mask + + def forward(self, x, x_size, mask=None): + # H, W = self.input_resolution + H, W = x_size + B, L, C = x.shape + # assert L == H * W, "input feature has wrong size" + + shortcut = x + x = x.view(B, H, W, C) + if mask is not None: + mask = mask.view(B, H, W, 1) + + # cyclic shift + if self.shift_size > 0: + shifted_x = torch.roll( + x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2) + ) + if mask is not None: + shifted_mask = torch.roll( + mask, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2) + ) + else: + shifted_x = x + if mask is not None: + shifted_mask = mask + + # partition windows + x_windows = window_partition( + shifted_x, self.window_size + ) # nW*B, window_size, window_size, C + x_windows = x_windows.view( + -1, self.window_size * self.window_size, C + ) # nW*B, window_size*window_size, C + if mask is not None: + mask_windows = window_partition(shifted_mask, self.window_size) + mask_windows = mask_windows.view(-1, self.window_size * self.window_size, 1) + else: + mask_windows = None + + # W-MSA/SW-MSA (to be compatible for testing on images whose shapes are the multiple of window size + if self.input_resolution == x_size: + attn_windows, mask_windows = self.attn( + x_windows, mask_windows, mask=self.attn_mask + ) # nW*B, window_size*window_size, C + else: + attn_windows, mask_windows = self.attn( + x_windows, + mask_windows, + mask=self.calculate_mask(x_size).to(x.dtype).to(x.device), + ) # nW*B, window_size*window_size, C + + # merge windows + attn_windows = attn_windows.view(-1, self.window_size, self.window_size, C) + shifted_x = window_reverse(attn_windows, self.window_size, H, W) # B H' W' C + if mask is not None: + mask_windows = mask_windows.view(-1, self.window_size, self.window_size, 1) + shifted_mask = window_reverse(mask_windows, self.window_size, H, W) + + # reverse cyclic shift + if self.shift_size > 0: + x = torch.roll( + shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2) + ) + if mask is not None: + mask = torch.roll( + shifted_mask, shifts=(self.shift_size, self.shift_size), dims=(1, 2) + ) + else: + x = shifted_x + if mask is not None: + mask = shifted_mask + x = x.view(B, H * W, C) + if mask is not None: + mask = mask.view(B, H * W, 1) + + # FFN + x = self.fuse(torch.cat([shortcut, x], dim=-1)) + x = self.mlp(x) + + return x, mask + + +class PatchMerging(nn.Module): + def __init__(self, in_channels, out_channels, down=2): + super().__init__() + self.conv = Conv2dLayerPartial( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=3, + activation="lrelu", + down=down, + ) + self.down = down + + def forward(self, x, x_size, mask=None): + x = token2feature(x, x_size) + if mask is not None: + mask = token2feature(mask, x_size) + x, mask = self.conv(x, mask) + if self.down != 1: + ratio = 1 / self.down + x_size = (int(x_size[0] * ratio), int(x_size[1] * ratio)) + x = feature2token(x) + if mask is not None: + mask = feature2token(mask) + return x, x_size, mask + + +class PatchUpsampling(nn.Module): + def __init__(self, in_channels, out_channels, up=2): + super().__init__() + self.conv = Conv2dLayerPartial( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=3, + activation="lrelu", + up=up, + ) + self.up = up + + def forward(self, x, x_size, mask=None): + x = token2feature(x, x_size) + if mask is not None: + mask = token2feature(mask, x_size) + x, mask = self.conv(x, mask) + if self.up != 1: + x_size = (int(x_size[0] * self.up), int(x_size[1] * self.up)) + x = feature2token(x) + if mask is not None: + mask = feature2token(mask) + return x, x_size, mask + + +class BasicLayer(nn.Module): + """A basic Swin Transformer layer for one stage. + Args: + dim (int): Number of input channels. + input_resolution (tuple[int]): Input resolution. + depth (int): Number of blocks. + num_heads (int): Number of attention heads. + window_size (int): Local window size. + mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. + qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True + qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set. + drop (float, optional): Dropout rate. Default: 0.0 + attn_drop (float, optional): Attention dropout rate. Default: 0.0 + drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0 + norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm + downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None + use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False. + """ + + def __init__( + self, + dim, + input_resolution, + depth, + num_heads, + window_size, + down_ratio=1, + mlp_ratio=2.0, + qkv_bias=True, + qk_scale=None, + drop=0.0, + attn_drop=0.0, + drop_path=0.0, + norm_layer=nn.LayerNorm, + downsample=None, + use_checkpoint=False, + ): + super().__init__() + self.dim = dim + self.input_resolution = input_resolution + self.depth = depth + self.use_checkpoint = use_checkpoint + + # patch merging layer + if downsample is not None: + # self.downsample = downsample(input_resolution, dim=dim, norm_layer=norm_layer) + self.downsample = downsample + else: + self.downsample = None + + # build blocks + self.blocks = nn.ModuleList( + [ + SwinTransformerBlock( + dim=dim, + input_resolution=input_resolution, + num_heads=num_heads, + down_ratio=down_ratio, + window_size=window_size, + shift_size=0 if (i % 2 == 0) else window_size // 2, + mlp_ratio=mlp_ratio, + qkv_bias=qkv_bias, + qk_scale=qk_scale, + drop=drop, + attn_drop=attn_drop, + drop_path=drop_path[i] + if isinstance(drop_path, list) + else drop_path, + norm_layer=norm_layer, + ) + for i in range(depth) + ] + ) + + self.conv = Conv2dLayerPartial( + in_channels=dim, out_channels=dim, kernel_size=3, activation="lrelu" + ) + + def forward(self, x, x_size, mask=None): + if self.downsample is not None: + x, x_size, mask = self.downsample(x, x_size, mask) + identity = x + for blk in self.blocks: + if self.use_checkpoint: + x, mask = checkpoint.checkpoint(blk, x, x_size, mask) + else: + x, mask = blk(x, x_size, mask) + if mask is not None: + mask = token2feature(mask, x_size) + x, mask = self.conv(token2feature(x, x_size), mask) + x = feature2token(x) + identity + if mask is not None: + mask = feature2token(mask) + return x, x_size, mask + + +class ToToken(nn.Module): + def __init__(self, in_channels=3, dim=128, kernel_size=5, stride=1): + super().__init__() + + self.proj = Conv2dLayerPartial( + in_channels=in_channels, + out_channels=dim, + kernel_size=kernel_size, + activation="lrelu", + ) + + def forward(self, x, mask): + x, mask = self.proj(x, mask) + + return x, mask + + +class EncFromRGB(nn.Module): + def __init__( + self, in_channels, out_channels, activation + ): # res = 2, ..., resolution_log2 + super().__init__() + self.conv0 = Conv2dLayer( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=1, + activation=activation, + ) + self.conv1 = Conv2dLayer( + in_channels=out_channels, + out_channels=out_channels, + kernel_size=3, + activation=activation, + ) + + def forward(self, x): + x = self.conv0(x) + x = self.conv1(x) + + return x + + +class ConvBlockDown(nn.Module): + def __init__( + self, in_channels, out_channels, activation + ): # res = 2, ..., resolution_log + super().__init__() + + self.conv0 = Conv2dLayer( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=3, + activation=activation, + down=2, + ) + self.conv1 = Conv2dLayer( + in_channels=out_channels, + out_channels=out_channels, + kernel_size=3, + activation=activation, + ) + + def forward(self, x): + x = self.conv0(x) + x = self.conv1(x) + + return x + + +def token2feature(x, x_size): + B, N, C = x.shape + h, w = x_size + x = x.permute(0, 2, 1).reshape(B, C, h, w) + return x + + +def feature2token(x): + B, C, H, W = x.shape + x = x.view(B, C, -1).transpose(1, 2) + return x + + +class Encoder(nn.Module): + def __init__( + self, + res_log2, + img_channels, + activation, + patch_size=5, + channels=16, + drop_path_rate=0.1, + ): + super().__init__() + + self.resolution = [] + + for idx, i in enumerate(range(res_log2, 3, -1)): # from input size to 16x16 + res = 2**i + self.resolution.append(res) + if i == res_log2: + block = EncFromRGB(img_channels * 2 + 1, nf(i), activation) + else: + block = ConvBlockDown(nf(i + 1), nf(i), activation) + setattr(self, "EncConv_Block_%dx%d" % (res, res), block) + + def forward(self, x): + out = {} + for res in self.resolution: + res_log2 = int(np.log2(res)) + x = getattr(self, "EncConv_Block_%dx%d" % (res, res))(x) + out[res_log2] = x + + return out + + +class ToStyle(nn.Module): + def __init__(self, in_channels, out_channels, activation, drop_rate): + super().__init__() + self.conv = nn.Sequential( + Conv2dLayer( + in_channels=in_channels, + out_channels=in_channels, + kernel_size=3, + activation=activation, + down=2, + ), + Conv2dLayer( + in_channels=in_channels, + out_channels=in_channels, + kernel_size=3, + activation=activation, + down=2, + ), + Conv2dLayer( + in_channels=in_channels, + out_channels=in_channels, + kernel_size=3, + activation=activation, + down=2, + ), + ) + + self.pool = nn.AdaptiveAvgPool2d(1) + self.fc = FullyConnectedLayer( + in_features=in_channels, out_features=out_channels, activation=activation + ) + # self.dropout = nn.Dropout(drop_rate) + + def forward(self, x): + x = self.conv(x) + x = self.pool(x) + x = self.fc(x.flatten(start_dim=1)) + # x = self.dropout(x) + + return x + + +class DecBlockFirstV2(nn.Module): + def __init__( + self, + res, + in_channels, + out_channels, + activation, + style_dim, + use_noise, + demodulate, + img_channels, + ): + super().__init__() + self.res = res + + self.conv0 = Conv2dLayer( + in_channels=in_channels, + out_channels=in_channels, + kernel_size=3, + activation=activation, + ) + self.conv1 = StyleConv( + in_channels=in_channels, + out_channels=out_channels, + style_dim=style_dim, + resolution=2**res, + kernel_size=3, + use_noise=use_noise, + activation=activation, + demodulate=demodulate, + ) + self.toRGB = ToRGB( + in_channels=out_channels, + out_channels=img_channels, + style_dim=style_dim, + kernel_size=1, + demodulate=False, + ) + + def forward(self, x, ws, gs, E_features, noise_mode="random"): + # x = self.fc(x).view(x.shape[0], -1, 4, 4) + x = self.conv0(x) + x = x + E_features[self.res] + style = get_style_code(ws[:, 0], gs) + x = self.conv1(x, style, noise_mode=noise_mode) + style = get_style_code(ws[:, 1], gs) + img = self.toRGB(x, style, skip=None) + + return x, img + + +class DecBlock(nn.Module): + def __init__( + self, + res, + in_channels, + out_channels, + activation, + style_dim, + use_noise, + demodulate, + img_channels, + ): # res = 4, ..., resolution_log2 + super().__init__() + self.res = res + + self.conv0 = StyleConv( + in_channels=in_channels, + out_channels=out_channels, + style_dim=style_dim, + resolution=2**res, + kernel_size=3, + up=2, + use_noise=use_noise, + activation=activation, + demodulate=demodulate, + ) + self.conv1 = StyleConv( + in_channels=out_channels, + out_channels=out_channels, + style_dim=style_dim, + resolution=2**res, + kernel_size=3, + use_noise=use_noise, + activation=activation, + demodulate=demodulate, + ) + self.toRGB = ToRGB( + in_channels=out_channels, + out_channels=img_channels, + style_dim=style_dim, + kernel_size=1, + demodulate=False, + ) + + def forward(self, x, img, ws, gs, E_features, noise_mode="random"): + style = get_style_code(ws[:, self.res * 2 - 9], gs) + x = self.conv0(x, style, noise_mode=noise_mode) + x = x + E_features[self.res] + style = get_style_code(ws[:, self.res * 2 - 8], gs) + x = self.conv1(x, style, noise_mode=noise_mode) + style = get_style_code(ws[:, self.res * 2 - 7], gs) + img = self.toRGB(x, style, skip=img) + + return x, img + + +class Decoder(nn.Module): + def __init__( + self, res_log2, activation, style_dim, use_noise, demodulate, img_channels + ): + super().__init__() + self.Dec_16x16 = DecBlockFirstV2( + 4, nf(4), nf(4), activation, style_dim, use_noise, demodulate, img_channels + ) + for res in range(5, res_log2 + 1): + setattr( + self, + "Dec_%dx%d" % (2**res, 2**res), + DecBlock( + res, + nf(res - 1), + nf(res), + activation, + style_dim, + use_noise, + demodulate, + img_channels, + ), + ) + self.res_log2 = res_log2 + + def forward(self, x, ws, gs, E_features, noise_mode="random"): + x, img = self.Dec_16x16(x, ws, gs, E_features, noise_mode=noise_mode) + for res in range(5, self.res_log2 + 1): + block = getattr(self, "Dec_%dx%d" % (2**res, 2**res)) + x, img = block(x, img, ws, gs, E_features, noise_mode=noise_mode) + + return img + + +class DecStyleBlock(nn.Module): + def __init__( + self, + res, + in_channels, + out_channels, + activation, + style_dim, + use_noise, + demodulate, + img_channels, + ): + super().__init__() + self.res = res + + self.conv0 = StyleConv( + in_channels=in_channels, + out_channels=out_channels, + style_dim=style_dim, + resolution=2**res, + kernel_size=3, + up=2, + use_noise=use_noise, + activation=activation, + demodulate=demodulate, + ) + self.conv1 = StyleConv( + in_channels=out_channels, + out_channels=out_channels, + style_dim=style_dim, + resolution=2**res, + kernel_size=3, + use_noise=use_noise, + activation=activation, + demodulate=demodulate, + ) + self.toRGB = ToRGB( + in_channels=out_channels, + out_channels=img_channels, + style_dim=style_dim, + kernel_size=1, + demodulate=False, + ) + + def forward(self, x, img, style, skip, noise_mode="random"): + x = self.conv0(x, style, noise_mode=noise_mode) + x = x + skip + x = self.conv1(x, style, noise_mode=noise_mode) + img = self.toRGB(x, style, skip=img) + + return x, img + + +class FirstStage(nn.Module): + def __init__( + self, + img_channels, + img_resolution=256, + dim=180, + w_dim=512, + use_noise=False, + demodulate=True, + activation="lrelu", + ): + super().__init__() + res = 64 + + self.conv_first = Conv2dLayerPartial( + in_channels=img_channels + 1, + out_channels=dim, + kernel_size=3, + activation=activation, + ) + self.enc_conv = nn.ModuleList() + down_time = int(np.log2(img_resolution // res)) + # 根据图片尺寸构建 swim transformer 的层数 + for i in range(down_time): # from input size to 64 + self.enc_conv.append( + Conv2dLayerPartial( + in_channels=dim, + out_channels=dim, + kernel_size=3, + down=2, + activation=activation, + ) + ) + + # from 64 -> 16 -> 64 + depths = [2, 3, 4, 3, 2] + ratios = [1, 1 / 2, 1 / 2, 2, 2] + num_heads = 6 + window_sizes = [8, 16, 16, 16, 8] + drop_path_rate = 0.1 + dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] + + self.tran = nn.ModuleList() + for i, depth in enumerate(depths): + res = int(res * ratios[i]) + if ratios[i] < 1: + merge = PatchMerging(dim, dim, down=int(1 / ratios[i])) + elif ratios[i] > 1: + merge = PatchUpsampling(dim, dim, up=ratios[i]) + else: + merge = None + self.tran.append( + BasicLayer( + dim=dim, + input_resolution=[res, res], + depth=depth, + num_heads=num_heads, + window_size=window_sizes[i], + drop_path=dpr[sum(depths[:i]) : sum(depths[: i + 1])], + downsample=merge, + ) + ) + + # global style + down_conv = [] + for i in range(int(np.log2(16))): + down_conv.append( + Conv2dLayer( + in_channels=dim, + out_channels=dim, + kernel_size=3, + down=2, + activation=activation, + ) + ) + down_conv.append(nn.AdaptiveAvgPool2d((1, 1))) + self.down_conv = nn.Sequential(*down_conv) + self.to_style = FullyConnectedLayer( + in_features=dim, out_features=dim * 2, activation=activation + ) + self.ws_style = FullyConnectedLayer( + in_features=w_dim, out_features=dim, activation=activation + ) + self.to_square = FullyConnectedLayer( + in_features=dim, out_features=16 * 16, activation=activation + ) + + style_dim = dim * 3 + self.dec_conv = nn.ModuleList() + for i in range(down_time): # from 64 to input size + res = res * 2 + self.dec_conv.append( + DecStyleBlock( + res, + dim, + dim, + activation, + style_dim, + use_noise, + demodulate, + img_channels, + ) + ) + + def forward(self, images_in, masks_in, ws, noise_mode="random"): + x = torch.cat([masks_in - 0.5, images_in * masks_in], dim=1) + + skips = [] + x, mask = self.conv_first(x, masks_in) # input size + skips.append(x) + for i, block in enumerate(self.enc_conv): # input size to 64 + x, mask = block(x, mask) + if i != len(self.enc_conv) - 1: + skips.append(x) + + x_size = x.size()[-2:] + x = feature2token(x) + mask = feature2token(mask) + mid = len(self.tran) // 2 + for i, block in enumerate(self.tran): # 64 to 16 + if i < mid: + x, x_size, mask = block(x, x_size, mask) + skips.append(x) + elif i > mid: + x, x_size, mask = block(x, x_size, None) + x = x + skips[mid - i] + else: + x, x_size, mask = block(x, x_size, None) + + mul_map = torch.ones_like(x) * 0.5 + mul_map = F.dropout(mul_map, training=True) + ws = self.ws_style(ws[:, -1]) + add_n = self.to_square(ws).unsqueeze(1) + add_n = ( + F.interpolate( + add_n, size=x.size(1), mode="linear", align_corners=False + ) + .squeeze(1) + .unsqueeze(-1) + ) + x = x * mul_map + add_n * (1 - mul_map) + gs = self.to_style( + self.down_conv(token2feature(x, x_size)).flatten(start_dim=1) + ) + style = torch.cat([gs, ws], dim=1) + + x = token2feature(x, x_size).contiguous() + img = None + for i, block in enumerate(self.dec_conv): + x, img = block( + x, img, style, skips[len(self.dec_conv) - i - 1], noise_mode=noise_mode + ) + + # ensemble + img = img * (1 - masks_in) + images_in * masks_in + + return img + + +class SynthesisNet(nn.Module): + def __init__( + self, + w_dim, # Intermediate latent (W) dimensionality. + img_resolution, # Output image resolution. + img_channels=3, # Number of color channels. + channel_base=32768, # Overall multiplier for the number of channels. + channel_decay=1.0, + channel_max=512, # Maximum number of channels in any layer. + activation="lrelu", # Activation function: 'relu', 'lrelu', etc. + drop_rate=0.5, + use_noise=False, + demodulate=True, + ): + super().__init__() + resolution_log2 = int(np.log2(img_resolution)) + assert img_resolution == 2**resolution_log2 and img_resolution >= 4 + + self.num_layers = resolution_log2 * 2 - 3 * 2 + self.img_resolution = img_resolution + self.resolution_log2 = resolution_log2 + + # first stage + self.first_stage = FirstStage( + img_channels, + img_resolution=img_resolution, + w_dim=w_dim, + use_noise=False, + demodulate=demodulate, + ) + + # second stage + self.enc = Encoder( + resolution_log2, img_channels, activation, patch_size=5, channels=16 + ) + self.to_square = FullyConnectedLayer( + in_features=w_dim, out_features=16 * 16, activation=activation + ) + self.to_style = ToStyle( + in_channels=nf(4), + out_channels=nf(2) * 2, + activation=activation, + drop_rate=drop_rate, + ) + style_dim = w_dim + nf(2) * 2 + self.dec = Decoder( + resolution_log2, activation, style_dim, use_noise, demodulate, img_channels + ) + + def forward(self, images_in, masks_in, ws, noise_mode="random", return_stg1=False): + out_stg1 = self.first_stage(images_in, masks_in, ws, noise_mode=noise_mode) + + # encoder + x = images_in * masks_in + out_stg1 * (1 - masks_in) + x = torch.cat([masks_in - 0.5, x, images_in * masks_in], dim=1) + E_features = self.enc(x) + + fea_16 = E_features[4] + mul_map = torch.ones_like(fea_16) * 0.5 + mul_map = F.dropout(mul_map, training=True) + add_n = self.to_square(ws[:, 0]).view(-1, 16, 16).unsqueeze(1) + add_n = F.interpolate( + add_n, size=fea_16.size()[-2:], mode="bilinear", align_corners=False + ) + fea_16 = fea_16 * mul_map + add_n * (1 - mul_map) + E_features[4] = fea_16 + + # style + gs = self.to_style(fea_16) + + # decoder + img = self.dec(fea_16, ws, gs, E_features, noise_mode=noise_mode) + + # ensemble + img = img * (1 - masks_in) + images_in * masks_in + + if not return_stg1: + return img + else: + return img, out_stg1 + + +class Generator(nn.Module): + def __init__( + self, + z_dim, # Input latent (Z) dimensionality, 0 = no latent. + c_dim, # Conditioning label (C) dimensionality, 0 = no label. + w_dim, # Intermediate latent (W) dimensionality. + img_resolution, # resolution of generated image + img_channels, # Number of input color channels. + synthesis_kwargs={}, # Arguments for SynthesisNetwork. + mapping_kwargs={}, # Arguments for MappingNetwork. + ): + super().__init__() + self.z_dim = z_dim + self.c_dim = c_dim + self.w_dim = w_dim + self.img_resolution = img_resolution + self.img_channels = img_channels + + self.synthesis = SynthesisNet( + w_dim=w_dim, + img_resolution=img_resolution, + img_channels=img_channels, + **synthesis_kwargs, + ) + self.mapping = MappingNet( + z_dim=z_dim, + c_dim=c_dim, + w_dim=w_dim, + num_ws=self.synthesis.num_layers, + **mapping_kwargs, + ) + + def forward( + self, + images_in, + masks_in, + z, + c, + truncation_psi=1, + truncation_cutoff=None, + skip_w_avg_update=False, + noise_mode="none", + return_stg1=False, + ): + ws = self.mapping( + z, + c, + truncation_psi=truncation_psi, + truncation_cutoff=truncation_cutoff, + skip_w_avg_update=skip_w_avg_update, + ) + img = self.synthesis(images_in, masks_in, ws, noise_mode=noise_mode) + return img + + +class Discriminator(torch.nn.Module): + def __init__( + self, + c_dim, # Conditioning label (C) dimensionality. + img_resolution, # Input resolution. + img_channels, # Number of input color channels. + channel_base=32768, # Overall multiplier for the number of channels. + channel_max=512, # Maximum number of channels in any layer. + channel_decay=1, + cmap_dim=None, # Dimensionality of mapped conditioning label, None = default. + activation="lrelu", + mbstd_group_size=4, # Group size for the minibatch standard deviation layer, None = entire minibatch. + mbstd_num_channels=1, # Number of features for the minibatch standard deviation layer, 0 = disable. + ): + super().__init__() + self.c_dim = c_dim + self.img_resolution = img_resolution + self.img_channels = img_channels + + resolution_log2 = int(np.log2(img_resolution)) + assert img_resolution == 2**resolution_log2 and img_resolution >= 4 + self.resolution_log2 = resolution_log2 + + if cmap_dim == None: + cmap_dim = nf(2) + if c_dim == 0: + cmap_dim = 0 + self.cmap_dim = cmap_dim + + if c_dim > 0: + self.mapping = MappingNet( + z_dim=0, c_dim=c_dim, w_dim=cmap_dim, num_ws=None, w_avg_beta=None + ) + + Dis = [DisFromRGB(img_channels + 1, nf(resolution_log2), activation)] + for res in range(resolution_log2, 2, -1): + Dis.append(DisBlock(nf(res), nf(res - 1), activation)) + + if mbstd_num_channels > 0: + Dis.append( + MinibatchStdLayer( + group_size=mbstd_group_size, num_channels=mbstd_num_channels + ) + ) + Dis.append( + Conv2dLayer( + nf(2) + mbstd_num_channels, nf(2), kernel_size=3, activation=activation + ) + ) + self.Dis = nn.Sequential(*Dis) + + self.fc0 = FullyConnectedLayer(nf(2) * 4**2, nf(2), activation=activation) + self.fc1 = FullyConnectedLayer(nf(2), 1 if cmap_dim == 0 else cmap_dim) + + # for 64x64 + Dis_stg1 = [DisFromRGB(img_channels + 1, nf(resolution_log2) // 2, activation)] + for res in range(resolution_log2, 2, -1): + Dis_stg1.append(DisBlock(nf(res) // 2, nf(res - 1) // 2, activation)) + + if mbstd_num_channels > 0: + Dis_stg1.append( + MinibatchStdLayer( + group_size=mbstd_group_size, num_channels=mbstd_num_channels + ) + ) + Dis_stg1.append( + Conv2dLayer( + nf(2) // 2 + mbstd_num_channels, + nf(2) // 2, + kernel_size=3, + activation=activation, + ) + ) + self.Dis_stg1 = nn.Sequential(*Dis_stg1) + + self.fc0_stg1 = FullyConnectedLayer( + nf(2) // 2 * 4**2, nf(2) // 2, activation=activation + ) + self.fc1_stg1 = FullyConnectedLayer( + nf(2) // 2, 1 if cmap_dim == 0 else cmap_dim + ) + + def forward(self, images_in, masks_in, images_stg1, c): + x = self.Dis(torch.cat([masks_in - 0.5, images_in], dim=1)) + x = self.fc1(self.fc0(x.flatten(start_dim=1))) + + x_stg1 = self.Dis_stg1(torch.cat([masks_in - 0.5, images_stg1], dim=1)) + x_stg1 = self.fc1_stg1(self.fc0_stg1(x_stg1.flatten(start_dim=1))) + + if self.c_dim > 0: + cmap = self.mapping(None, c) + + if self.cmap_dim > 0: + x = (x * cmap).sum(dim=1, keepdim=True) * (1 / np.sqrt(self.cmap_dim)) + x_stg1 = (x_stg1 * cmap).sum(dim=1, keepdim=True) * ( + 1 / np.sqrt(self.cmap_dim) + ) + + return x, x_stg1 + + +MAT_MODEL_URL = os.environ.get( + "MAT_MODEL_URL", + "https://github.com/Sanster/models/releases/download/add_mat/Places_512_FullData_G.pth", +) + +MAT_MODEL_MD5 = os.environ.get("MAT_MODEL_MD5", "8ca927835fa3f5e21d65ffcb165377ed") + + +class MAT(InpaintModel): + name = "mat" + min_size = 512 + pad_mod = 512 + pad_to_square = True + is_erase_model = True + + def init_model(self, device, **kwargs): + seed = 240 # pick up a random number + set_seed(seed) + + fp16 = not kwargs.get("no_half", False) + use_gpu = "cuda" in str(device) and torch.cuda.is_available() + self.torch_dtype = torch.float16 if use_gpu and fp16 else torch.float32 + + G = Generator( + z_dim=512, + c_dim=0, + w_dim=512, + img_resolution=512, + img_channels=3, + mapping_kwargs={"torch_dtype": self.torch_dtype}, + ).to(self.torch_dtype) + # fmt: off + self.model = load_model(G, MAT_MODEL_URL, device, MAT_MODEL_MD5) + self.z = torch.from_numpy(np.random.randn(1, G.z_dim)).to(self.torch_dtype).to(device) + self.label = torch.zeros([1, self.model.c_dim], device=device).to(self.torch_dtype) + # fmt: on + + @staticmethod + def download(): + download_model(MAT_MODEL_URL, MAT_MODEL_MD5) + + @staticmethod + def is_downloaded() -> bool: + return os.path.exists(get_cache_path_by_url(MAT_MODEL_URL)) + + def forward(self, image, mask, config: InpaintRequest): + """Input images and output images have same size + images: [H, W, C] RGB + masks: [H, W] mask area == 255 + return: BGR IMAGE + """ + + image = norm_img(image) # [0, 1] + image = image * 2 - 1 # [0, 1] -> [-1, 1] + + mask = (mask > 127) * 255 + mask = 255 - mask + mask = norm_img(mask) + + image = ( + torch.from_numpy(image).unsqueeze(0).to(self.torch_dtype).to(self.device) + ) + mask = torch.from_numpy(mask).unsqueeze(0).to(self.torch_dtype).to(self.device) + + output = self.model( + image, mask, self.z, self.label, truncation_psi=1, noise_mode="none" + ) + output = ( + (output.permute(0, 2, 3, 1) * 127.5 + 127.5) + .round() + .clamp(0, 255) + .to(torch.uint8) + ) + output = output[0].cpu().numpy() + cur_res = cv2.cvtColor(output, cv2.COLOR_RGB2BGR) + return cur_res diff --git a/py/iopaint/model/mi_gan.py b/py/iopaint/model/mi_gan.py new file mode 100644 index 0000000..482acb4 --- /dev/null +++ b/py/iopaint/model/mi_gan.py @@ -0,0 +1,110 @@ +import os + +import cv2 +import torch + +from ..helper import ( + load_jit_model, + download_model, + get_cache_path_by_url, + boxes_from_mask, + resize_max_size, + norm_img, +) +from .base import InpaintModel +from ..schema import InpaintRequest + +MIGAN_MODEL_URL = os.environ.get( + "MIGAN_MODEL_URL", + "https://github.com/Sanster/models/releases/download/migan/migan_traced.pt", +) +MIGAN_MODEL_MD5 = os.environ.get("MIGAN_MODEL_MD5", "76eb3b1a71c400ee3290524f7a11b89c") + + +class MIGAN(InpaintModel): + name = "migan" + min_size = 512 + pad_mod = 512 + pad_to_square = True + is_erase_model = True + + def init_model(self, device, **kwargs): + self.model = load_jit_model(MIGAN_MODEL_URL, device, MIGAN_MODEL_MD5).eval() + + @staticmethod + def download(): + download_model(MIGAN_MODEL_URL, MIGAN_MODEL_MD5) + + @staticmethod + def is_downloaded() -> bool: + return os.path.exists(get_cache_path_by_url(MIGAN_MODEL_URL)) + + @torch.no_grad() + def __call__(self, image, mask, config: InpaintRequest): + """ + images: [H, W, C] RGB, not normalized + masks: [H, W] + return: BGR IMAGE + """ + if image.shape[0] == 512 and image.shape[1] == 512: + return self._pad_forward(image, mask, config) + + boxes = boxes_from_mask(mask) + crop_result = [] + config.hd_strategy_crop_margin = 128 + for box in boxes: + crop_image, crop_mask, crop_box = self._crop_box(image, mask, box, config) + origin_size = crop_image.shape[:2] + resize_image = resize_max_size(crop_image, size_limit=512) + resize_mask = resize_max_size(crop_mask, size_limit=512) + inpaint_result = self._pad_forward(resize_image, resize_mask, config) + + # only paste masked area result + inpaint_result = cv2.resize( + inpaint_result, + (origin_size[1], origin_size[0]), + interpolation=cv2.INTER_CUBIC, + ) + + original_pixel_indices = crop_mask < 127 + inpaint_result[original_pixel_indices] = crop_image[:, :, ::-1][ + original_pixel_indices + ] + + crop_result.append((inpaint_result, crop_box)) + + inpaint_result = image[:, :, ::-1].copy() + for crop_image, crop_box in crop_result: + x1, y1, x2, y2 = crop_box + inpaint_result[y1:y2, x1:x2, :] = crop_image + + return inpaint_result + + def forward(self, image, mask, config: InpaintRequest): + """Input images and output images have same size + images: [H, W, C] RGB + masks: [H, W] mask area == 255 + return: BGR IMAGE + """ + + image = norm_img(image) # [0, 1] + image = image * 2 - 1 # [0, 1] -> [-1, 1] + mask = (mask > 120) * 255 + mask = norm_img(mask) + + image = torch.from_numpy(image).unsqueeze(0).to(self.device) + mask = torch.from_numpy(mask).unsqueeze(0).to(self.device) + + erased_img = image * (1 - mask) + input_image = torch.cat([0.5 - mask, erased_img], dim=1) + + output = self.model(input_image) + output = ( + (output.permute(0, 2, 3, 1) * 127.5 + 127.5) + .round() + .clamp(0, 255) + .to(torch.uint8) + ) + output = output[0].cpu().numpy() + cur_res = cv2.cvtColor(output, cv2.COLOR_RGB2BGR) + return cur_res diff --git a/py/iopaint/model/opencv2.py b/py/iopaint/model/opencv2.py new file mode 100644 index 0000000..82582cb --- /dev/null +++ b/py/iopaint/model/opencv2.py @@ -0,0 +1,29 @@ +import cv2 +from .base import InpaintModel +from ..schema import InpaintRequest + +flag_map = {"INPAINT_NS": cv2.INPAINT_NS, "INPAINT_TELEA": cv2.INPAINT_TELEA} + + +class OpenCV2(InpaintModel): + name = "cv2" + pad_mod = 1 + is_erase_model = True + + @staticmethod + def is_downloaded() -> bool: + return True + + def forward(self, image, mask, config: InpaintRequest): + """Input image and output image have same size + image: [H, W, C] RGB + mask: [H, W, 1] + return: BGR IMAGE + """ + cur_res = cv2.inpaint( + image[:, :, ::-1], + mask, + inpaintRadius=config.cv2_radius, + flags=flag_map[config.cv2_flag], + ) + return cur_res diff --git a/py/iopaint/model/original_sd_configs/__init__.py b/py/iopaint/model/original_sd_configs/__init__.py new file mode 100644 index 0000000..23896a7 --- /dev/null +++ b/py/iopaint/model/original_sd_configs/__init__.py @@ -0,0 +1,19 @@ +from pathlib import Path +from typing import Dict + +CURRENT_DIR = Path(__file__).parent.absolute() + + +def get_config_files() -> Dict[str, Path]: + """ + - `v1`: Config file for Stable Diffusion v1 + - `v2`: Config file for Stable Diffusion v2 + - `xl`: Config file for Stable Diffusion XL + - `xl_refiner`: Config file for Stable Diffusion XL Refiner + """ + return { + "v1": CURRENT_DIR / "v1-inference.yaml", + "v2": CURRENT_DIR / "v2-inference-v.yaml", + "xl": CURRENT_DIR / "sd_xl_base.yaml", + "xl_refiner": CURRENT_DIR / "sd_xl_refiner.yaml", + } diff --git a/py/iopaint/model/original_sd_configs/sd_xl_base.yaml b/py/iopaint/model/original_sd_configs/sd_xl_base.yaml new file mode 100644 index 0000000..6047379 --- /dev/null +++ b/py/iopaint/model/original_sd_configs/sd_xl_base.yaml @@ -0,0 +1,93 @@ +model: + target: sgm.models.diffusion.DiffusionEngine + params: + scale_factor: 0.13025 + disable_first_stage_autocast: True + + denoiser_config: + target: sgm.modules.diffusionmodules.denoiser.DiscreteDenoiser + params: + num_idx: 1000 + + scaling_config: + target: sgm.modules.diffusionmodules.denoiser_scaling.EpsScaling + discretization_config: + target: sgm.modules.diffusionmodules.discretizer.LegacyDDPMDiscretization + + network_config: + target: sgm.modules.diffusionmodules.openaimodel.UNetModel + params: + adm_in_channels: 2816 + num_classes: sequential + use_checkpoint: True + in_channels: 4 + out_channels: 4 + model_channels: 320 + attention_resolutions: [4, 2] + num_res_blocks: 2 + channel_mult: [1, 2, 4] + num_head_channels: 64 + use_linear_in_transformer: True + transformer_depth: [1, 2, 10] + context_dim: 2048 + spatial_transformer_attn_type: softmax-xformers + + conditioner_config: + target: sgm.modules.GeneralConditioner + params: + emb_models: + - is_trainable: False + input_key: txt + target: sgm.modules.encoders.modules.FrozenCLIPEmbedder + params: + layer: hidden + layer_idx: 11 + + - is_trainable: False + input_key: txt + target: sgm.modules.encoders.modules.FrozenOpenCLIPEmbedder2 + params: + arch: ViT-bigG-14 + version: laion2b_s39b_b160k + freeze: True + layer: penultimate + always_return_pooled: True + legacy: False + + - is_trainable: False + input_key: original_size_as_tuple + target: sgm.modules.encoders.modules.ConcatTimestepEmbedderND + params: + outdim: 256 + + - is_trainable: False + input_key: crop_coords_top_left + target: sgm.modules.encoders.modules.ConcatTimestepEmbedderND + params: + outdim: 256 + + - is_trainable: False + input_key: target_size_as_tuple + target: sgm.modules.encoders.modules.ConcatTimestepEmbedderND + params: + outdim: 256 + + first_stage_config: + target: sgm.models.autoencoder.AutoencoderKL + params: + embed_dim: 4 + monitor: val/rec_loss + ddconfig: + attn_type: vanilla-xformers + double_z: true + z_channels: 4 + resolution: 256 + in_channels: 3 + out_ch: 3 + ch: 128 + ch_mult: [1, 2, 4, 4] + num_res_blocks: 2 + attn_resolutions: [] + dropout: 0.0 + lossconfig: + target: torch.nn.Identity diff --git a/py/iopaint/model/original_sd_configs/sd_xl_refiner.yaml b/py/iopaint/model/original_sd_configs/sd_xl_refiner.yaml new file mode 100644 index 0000000..2d5ab44 --- /dev/null +++ b/py/iopaint/model/original_sd_configs/sd_xl_refiner.yaml @@ -0,0 +1,86 @@ +model: + target: sgm.models.diffusion.DiffusionEngine + params: + scale_factor: 0.13025 + disable_first_stage_autocast: True + + denoiser_config: + target: sgm.modules.diffusionmodules.denoiser.DiscreteDenoiser + params: + num_idx: 1000 + + scaling_config: + target: sgm.modules.diffusionmodules.denoiser_scaling.EpsScaling + discretization_config: + target: sgm.modules.diffusionmodules.discretizer.LegacyDDPMDiscretization + + network_config: + target: sgm.modules.diffusionmodules.openaimodel.UNetModel + params: + adm_in_channels: 2560 + num_classes: sequential + use_checkpoint: True + in_channels: 4 + out_channels: 4 + model_channels: 384 + attention_resolutions: [4, 2] + num_res_blocks: 2 + channel_mult: [1, 2, 4, 4] + num_head_channels: 64 + use_linear_in_transformer: True + transformer_depth: 4 + context_dim: [1280, 1280, 1280, 1280] + spatial_transformer_attn_type: softmax-xformers + + conditioner_config: + target: sgm.modules.GeneralConditioner + params: + emb_models: + - is_trainable: False + input_key: txt + target: sgm.modules.encoders.modules.FrozenOpenCLIPEmbedder2 + params: + arch: ViT-bigG-14 + version: laion2b_s39b_b160k + legacy: False + freeze: True + layer: penultimate + always_return_pooled: True + + - is_trainable: False + input_key: original_size_as_tuple + target: sgm.modules.encoders.modules.ConcatTimestepEmbedderND + params: + outdim: 256 + + - is_trainable: False + input_key: crop_coords_top_left + target: sgm.modules.encoders.modules.ConcatTimestepEmbedderND + params: + outdim: 256 + + - is_trainable: False + input_key: aesthetic_score + target: sgm.modules.encoders.modules.ConcatTimestepEmbedderND + params: + outdim: 256 + + first_stage_config: + target: sgm.models.autoencoder.AutoencoderKL + params: + embed_dim: 4 + monitor: val/rec_loss + ddconfig: + attn_type: vanilla-xformers + double_z: true + z_channels: 4 + resolution: 256 + in_channels: 3 + out_ch: 3 + ch: 128 + ch_mult: [1, 2, 4, 4] + num_res_blocks: 2 + attn_resolutions: [] + dropout: 0.0 + lossconfig: + target: torch.nn.Identity diff --git a/py/iopaint/model/original_sd_configs/v1-inference.yaml b/py/iopaint/model/original_sd_configs/v1-inference.yaml new file mode 100644 index 0000000..d4effe5 --- /dev/null +++ b/py/iopaint/model/original_sd_configs/v1-inference.yaml @@ -0,0 +1,70 @@ +model: + base_learning_rate: 1.0e-04 + target: ldm.models.diffusion.ddpm.LatentDiffusion + params: + linear_start: 0.00085 + linear_end: 0.0120 + num_timesteps_cond: 1 + log_every_t: 200 + timesteps: 1000 + first_stage_key: "jpg" + cond_stage_key: "txt" + image_size: 64 + channels: 4 + cond_stage_trainable: false # Note: different from the one we trained before + conditioning_key: crossattn + monitor: val/loss_simple_ema + scale_factor: 0.18215 + use_ema: False + + scheduler_config: # 10000 warmup steps + target: ldm.lr_scheduler.LambdaLinearScheduler + params: + warm_up_steps: [ 10000 ] + cycle_lengths: [ 10000000000000 ] # incredibly large number to prevent corner cases + f_start: [ 1.e-6 ] + f_max: [ 1. ] + f_min: [ 1. ] + + unet_config: + target: ldm.modules.diffusionmodules.openaimodel.UNetModel + params: + image_size: 32 # unused + in_channels: 4 + out_channels: 4 + model_channels: 320 + attention_resolutions: [ 4, 2, 1 ] + num_res_blocks: 2 + channel_mult: [ 1, 2, 4, 4 ] + num_heads: 8 + use_spatial_transformer: True + transformer_depth: 1 + context_dim: 768 + use_checkpoint: True + legacy: False + + first_stage_config: + target: ldm.models.autoencoder.AutoencoderKL + params: + embed_dim: 4 + monitor: val/rec_loss + ddconfig: + double_z: true + z_channels: 4 + resolution: 256 + in_channels: 3 + out_ch: 3 + ch: 128 + ch_mult: + - 1 + - 2 + - 4 + - 4 + num_res_blocks: 2 + attn_resolutions: [] + dropout: 0.0 + lossconfig: + target: torch.nn.Identity + + cond_stage_config: + target: ldm.modules.encoders.modules.FrozenCLIPEmbedder diff --git a/py/iopaint/model/original_sd_configs/v2-inference-v.yaml b/py/iopaint/model/original_sd_configs/v2-inference-v.yaml new file mode 100644 index 0000000..8ec8dfb --- /dev/null +++ b/py/iopaint/model/original_sd_configs/v2-inference-v.yaml @@ -0,0 +1,68 @@ +model: + base_learning_rate: 1.0e-4 + target: ldm.models.diffusion.ddpm.LatentDiffusion + params: + parameterization: "v" + linear_start: 0.00085 + linear_end: 0.0120 + num_timesteps_cond: 1 + log_every_t: 200 + timesteps: 1000 + first_stage_key: "jpg" + cond_stage_key: "txt" + image_size: 64 + channels: 4 + cond_stage_trainable: false + conditioning_key: crossattn + monitor: val/loss_simple_ema + scale_factor: 0.18215 + use_ema: False # we set this to false because this is an inference only config + + unet_config: + target: ldm.modules.diffusionmodules.openaimodel.UNetModel + params: + use_checkpoint: True + use_fp16: True + image_size: 32 # unused + in_channels: 4 + out_channels: 4 + model_channels: 320 + attention_resolutions: [ 4, 2, 1 ] + num_res_blocks: 2 + channel_mult: [ 1, 2, 4, 4 ] + num_head_channels: 64 # need to fix for flash-attn + use_spatial_transformer: True + use_linear_in_transformer: True + transformer_depth: 1 + context_dim: 1024 + legacy: False + + first_stage_config: + target: ldm.models.autoencoder.AutoencoderKL + params: + embed_dim: 4 + monitor: val/rec_loss + ddconfig: + #attn_type: "vanilla-xformers" + double_z: true + z_channels: 4 + resolution: 256 + in_channels: 3 + out_ch: 3 + ch: 128 + ch_mult: + - 1 + - 2 + - 4 + - 4 + num_res_blocks: 2 + attn_resolutions: [] + dropout: 0.0 + lossconfig: + target: torch.nn.Identity + + cond_stage_config: + target: ldm.modules.encoders.modules.FrozenOpenCLIPEmbedder + params: + freeze: True + layer: "penultimate" diff --git a/py/iopaint/model/paint_by_example.py b/py/iopaint/model/paint_by_example.py new file mode 100644 index 0000000..cc670a9 --- /dev/null +++ b/py/iopaint/model/paint_by_example.py @@ -0,0 +1,68 @@ +import PIL +import PIL.Image +import cv2 +import torch +from loguru import logger + +from ..helper import decode_base64_to_image +from .base import DiffusionInpaintModel +from ..schema import InpaintRequest +from .utils import get_torch_dtype, enable_low_mem, is_local_files_only + + +class PaintByExample(DiffusionInpaintModel): + name = "Fantasy-Studio/Paint-by-Example" + pad_mod = 8 + min_size = 512 + + def init_model(self, device: torch.device, **kwargs): + from diffusers import DiffusionPipeline + + use_gpu, torch_dtype = get_torch_dtype(device, kwargs.get("no_half", False)) + model_kwargs = { + "local_files_only": is_local_files_only(**kwargs), + } + + if kwargs["disable_nsfw"] or kwargs.get("cpu_offload", False): + logger.info("Disable Paint By Example Model NSFW checker") + model_kwargs.update( + dict(safety_checker=None, requires_safety_checker=False) + ) + + self.model = DiffusionPipeline.from_pretrained( + self.name, torch_dtype=torch_dtype, **model_kwargs + ) + enable_low_mem(self.model, kwargs.get("low_mem", False)) + + # TODO: gpu_id + if kwargs.get("cpu_offload", False) and use_gpu: + self.model.image_encoder = self.model.image_encoder.to(device) + self.model.enable_sequential_cpu_offload(gpu_id=0) + else: + self.model = self.model.to(device) + + def forward(self, image, mask, config: InpaintRequest): + """Input image and output image have same size + image: [H, W, C] RGB + mask: [H, W, 1] 255 means area to repaint + return: BGR IMAGE + """ + if config.paint_by_example_example_image is None: + raise ValueError("paint_by_example_example_image is required") + example_image, _, _ = decode_base64_to_image( + config.paint_by_example_example_image + ) + output = self.model( + image=PIL.Image.fromarray(image), + mask_image=PIL.Image.fromarray(mask[:, :, -1], mode="L"), + example_image=PIL.Image.fromarray(example_image), + num_inference_steps=config.sd_steps, + guidance_scale=config.sd_guidance_scale, + negative_prompt="out of frame, lowres, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, disfigured, gross proportions, malformed limbs, watermark, signature", + output_type="np.array", + generator=torch.manual_seed(config.sd_seed), + ).images[0] + + output = (output * 255).round().astype("uint8") + output = cv2.cvtColor(output, cv2.COLOR_RGB2BGR) + return output diff --git a/py/iopaint/model/plms_sampler.py b/py/iopaint/model/plms_sampler.py new file mode 100644 index 0000000..131a8f4 --- /dev/null +++ b/py/iopaint/model/plms_sampler.py @@ -0,0 +1,225 @@ +# From: https://github.com/CompVis/latent-diffusion/blob/main/ldm/models/diffusion/plms.py +import torch +import numpy as np +from .utils import make_ddim_timesteps, make_ddim_sampling_parameters, noise_like +from tqdm import tqdm + + +class PLMSSampler(object): + def __init__(self, model, schedule="linear", **kwargs): + super().__init__() + self.model = model + self.ddpm_num_timesteps = model.num_timesteps + self.schedule = schedule + + def register_buffer(self, name, attr): + setattr(self, name, attr) + + def make_schedule(self, ddim_num_steps, ddim_discretize="uniform", ddim_eta=0., verbose=True): + if ddim_eta != 0: + raise ValueError('ddim_eta must be 0 for PLMS') + self.ddim_timesteps = make_ddim_timesteps(ddim_discr_method=ddim_discretize, num_ddim_timesteps=ddim_num_steps, + num_ddpm_timesteps=self.ddpm_num_timesteps, verbose=verbose) + alphas_cumprod = self.model.alphas_cumprod + assert alphas_cumprod.shape[0] == self.ddpm_num_timesteps, 'alphas have to be defined for each timestep' + to_torch = lambda x: x.clone().detach().to(torch.float32).to(self.model.device) + + self.register_buffer('betas', to_torch(self.model.betas)) + self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod)) + self.register_buffer('alphas_cumprod_prev', to_torch(self.model.alphas_cumprod_prev)) + + # calculations for diffusion q(x_t | x_{t-1}) and others + self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod.cpu()))) + self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod.cpu()))) + self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod.cpu()))) + self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu()))) + self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu() - 1))) + + # ddim sampling parameters + ddim_sigmas, ddim_alphas, ddim_alphas_prev = make_ddim_sampling_parameters(alphacums=alphas_cumprod.cpu(), + ddim_timesteps=self.ddim_timesteps, + eta=ddim_eta, verbose=verbose) + self.register_buffer('ddim_sigmas', ddim_sigmas) + self.register_buffer('ddim_alphas', ddim_alphas) + self.register_buffer('ddim_alphas_prev', ddim_alphas_prev) + self.register_buffer('ddim_sqrt_one_minus_alphas', np.sqrt(1. - ddim_alphas)) + sigmas_for_original_sampling_steps = ddim_eta * torch.sqrt( + (1 - self.alphas_cumprod_prev) / (1 - self.alphas_cumprod) * ( + 1 - self.alphas_cumprod / self.alphas_cumprod_prev)) + self.register_buffer('ddim_sigmas_for_original_num_steps', sigmas_for_original_sampling_steps) + + @torch.no_grad() + def sample(self, + steps, + batch_size, + shape, + conditioning=None, + callback=None, + normals_sequence=None, + img_callback=None, + quantize_x0=False, + eta=0., + mask=None, + x0=None, + temperature=1., + noise_dropout=0., + score_corrector=None, + corrector_kwargs=None, + verbose=False, + x_T=None, + log_every_t=100, + unconditional_guidance_scale=1., + unconditional_conditioning=None, + # this has to come in the same format as the conditioning, # e.g. as encoded tokens, ... + **kwargs + ): + if conditioning is not None: + if isinstance(conditioning, dict): + cbs = conditioning[list(conditioning.keys())[0]].shape[0] + if cbs != batch_size: + print(f"Warning: Got {cbs} conditionings but batch-size is {batch_size}") + else: + if conditioning.shape[0] != batch_size: + print(f"Warning: Got {conditioning.shape[0]} conditionings but batch-size is {batch_size}") + + self.make_schedule(ddim_num_steps=steps, ddim_eta=eta, verbose=verbose) + # sampling + C, H, W = shape + size = (batch_size, C, H, W) + print(f'Data shape for PLMS sampling is {size}') + + samples = self.plms_sampling(conditioning, size, + callback=callback, + img_callback=img_callback, + quantize_denoised=quantize_x0, + mask=mask, x0=x0, + ddim_use_original_steps=False, + noise_dropout=noise_dropout, + temperature=temperature, + score_corrector=score_corrector, + corrector_kwargs=corrector_kwargs, + x_T=x_T, + log_every_t=log_every_t, + unconditional_guidance_scale=unconditional_guidance_scale, + unconditional_conditioning=unconditional_conditioning, + ) + return samples + + @torch.no_grad() + def plms_sampling(self, cond, shape, + x_T=None, ddim_use_original_steps=False, + callback=None, timesteps=None, quantize_denoised=False, + mask=None, x0=None, img_callback=None, log_every_t=100, + temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None, + unconditional_guidance_scale=1., unconditional_conditioning=None, ): + device = self.model.betas.device + b = shape[0] + if x_T is None: + img = torch.randn(shape, device=device) + else: + img = x_T + + if timesteps is None: + timesteps = self.ddpm_num_timesteps if ddim_use_original_steps else self.ddim_timesteps + elif timesteps is not None and not ddim_use_original_steps: + subset_end = int(min(timesteps / self.ddim_timesteps.shape[0], 1) * self.ddim_timesteps.shape[0]) - 1 + timesteps = self.ddim_timesteps[:subset_end] + + time_range = list(reversed(range(0, timesteps))) if ddim_use_original_steps else np.flip(timesteps) + total_steps = timesteps if ddim_use_original_steps else timesteps.shape[0] + print(f"Running PLMS Sampling with {total_steps} timesteps") + + iterator = tqdm(time_range, desc='PLMS Sampler', total=total_steps) + old_eps = [] + + for i, step in enumerate(iterator): + index = total_steps - i - 1 + ts = torch.full((b,), step, device=device, dtype=torch.long) + ts_next = torch.full((b,), time_range[min(i + 1, len(time_range) - 1)], device=device, dtype=torch.long) + + if mask is not None: + assert x0 is not None + img_orig = self.model.q_sample(x0, ts) # TODO: deterministic forward pass? + img = img_orig * mask + (1. - mask) * img + + outs = self.p_sample_plms(img, cond, ts, index=index, use_original_steps=ddim_use_original_steps, + quantize_denoised=quantize_denoised, temperature=temperature, + noise_dropout=noise_dropout, score_corrector=score_corrector, + corrector_kwargs=corrector_kwargs, + unconditional_guidance_scale=unconditional_guidance_scale, + unconditional_conditioning=unconditional_conditioning, + old_eps=old_eps, t_next=ts_next) + img, pred_x0, e_t = outs + old_eps.append(e_t) + if len(old_eps) >= 4: + old_eps.pop(0) + if callback: callback(i) + if img_callback: img_callback(pred_x0, i) + + return img + + @torch.no_grad() + def p_sample_plms(self, x, c, t, index, repeat_noise=False, use_original_steps=False, quantize_denoised=False, + temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None, + unconditional_guidance_scale=1., unconditional_conditioning=None, old_eps=None, t_next=None): + b, *_, device = *x.shape, x.device + + def get_model_output(x, t): + if unconditional_conditioning is None or unconditional_guidance_scale == 1.: + e_t = self.model.apply_model(x, t, c) + else: + x_in = torch.cat([x] * 2) + t_in = torch.cat([t] * 2) + c_in = torch.cat([unconditional_conditioning, c]) + e_t_uncond, e_t = self.model.apply_model(x_in, t_in, c_in).chunk(2) + e_t = e_t_uncond + unconditional_guidance_scale * (e_t - e_t_uncond) + + if score_corrector is not None: + assert self.model.parameterization == "eps" + e_t = score_corrector.modify_score(self.model, e_t, x, t, c, **corrector_kwargs) + + return e_t + + alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas + alphas_prev = self.model.alphas_cumprod_prev if use_original_steps else self.ddim_alphas_prev + sqrt_one_minus_alphas = self.model.sqrt_one_minus_alphas_cumprod if use_original_steps else self.ddim_sqrt_one_minus_alphas + sigmas = self.model.ddim_sigmas_for_original_num_steps if use_original_steps else self.ddim_sigmas + + def get_x_prev_and_pred_x0(e_t, index): + # select parameters corresponding to the currently considered timestep + a_t = torch.full((b, 1, 1, 1), alphas[index], device=device) + a_prev = torch.full((b, 1, 1, 1), alphas_prev[index], device=device) + sigma_t = torch.full((b, 1, 1, 1), sigmas[index], device=device) + sqrt_one_minus_at = torch.full((b, 1, 1, 1), sqrt_one_minus_alphas[index], device=device) + + # current prediction for x_0 + pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt() + if quantize_denoised: + pred_x0, _, *_ = self.model.first_stage_model.quantize(pred_x0) + # direction pointing to x_t + dir_xt = (1. - a_prev - sigma_t ** 2).sqrt() * e_t + noise = sigma_t * noise_like(x.shape, device, repeat_noise) * temperature + if noise_dropout > 0.: + noise = torch.nn.functional.dropout(noise, p=noise_dropout) + x_prev = a_prev.sqrt() * pred_x0 + dir_xt + noise + return x_prev, pred_x0 + + e_t = get_model_output(x, t) + if len(old_eps) == 0: + # Pseudo Improved Euler (2nd order) + x_prev, pred_x0 = get_x_prev_and_pred_x0(e_t, index) + e_t_next = get_model_output(x_prev, t_next) + e_t_prime = (e_t + e_t_next) / 2 + elif len(old_eps) == 1: + # 2nd order Pseudo Linear Multistep (Adams-Bashforth) + e_t_prime = (3 * e_t - old_eps[-1]) / 2 + elif len(old_eps) == 2: + # 3nd order Pseudo Linear Multistep (Adams-Bashforth) + e_t_prime = (23 * e_t - 16 * old_eps[-1] + 5 * old_eps[-2]) / 12 + elif len(old_eps) >= 3: + # 4nd order Pseudo Linear Multistep (Adams-Bashforth) + e_t_prime = (55 * e_t - 59 * old_eps[-1] + 37 * old_eps[-2] - 9 * old_eps[-3]) / 24 + + x_prev, pred_x0 = get_x_prev_and_pred_x0(e_t_prime, index) + + return x_prev, pred_x0, e_t diff --git a/py/iopaint/model/power_paint/__init__.py b/py/iopaint/model/power_paint/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/py/iopaint/model/power_paint/pipeline_powerpaint.py b/py/iopaint/model/power_paint/pipeline_powerpaint.py new file mode 100644 index 0000000..13c1d27 --- /dev/null +++ b/py/iopaint/model/power_paint/pipeline_powerpaint.py @@ -0,0 +1,1243 @@ +# Copyright 2023 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import inspect +from typing import Any, Callable, Dict, List, Optional, Union + +import numpy as np +import PIL +import torch +from packaging import version +from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer +from diffusers.configuration_utils import FrozenDict +from diffusers.image_processor import VaeImageProcessor +from diffusers.loaders import ( + FromSingleFileMixin, + LoraLoaderMixin, + TextualInversionLoaderMixin, +) +from diffusers.models import ( + AsymmetricAutoencoderKL, + AutoencoderKL, + UNet2DConditionModel, +) +from diffusers.schedulers import KarrasDiffusionSchedulers +from diffusers.utils import ( + deprecate, + is_accelerate_available, + is_accelerate_version, + logging, +) +from diffusers.utils.torch_utils import randn_tensor +from diffusers.pipelines.pipeline_utils import DiffusionPipeline +from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput +from diffusers.pipelines.stable_diffusion.safety_checker import ( + StableDiffusionSafetyChecker, +) + + +logger = logging.get_logger(__name__) # pylint: disable=invalid-name + + +def prepare_mask_and_masked_image( + image, mask, height, width, return_image: bool = False +): + """ + Prepares a pair (image, mask) to be consumed by the Stable Diffusion pipeline. This means that those inputs will be + converted to ``torch.Tensor`` with shapes ``batch x channels x height x width`` where ``channels`` is ``3`` for the + ``image`` and ``1`` for the ``mask``. + + The ``image`` will be converted to ``torch.float32`` and normalized to be in ``[-1, 1]``. The ``mask`` will be + binarized (``mask > 0.5``) and cast to ``torch.float32`` too. + + Args: + image (Union[np.array, PIL.Image, torch.Tensor]): The image to inpaint. + It can be a ``PIL.Image``, or a ``height x width x 3`` ``np.array`` or a ``channels x height x width`` + ``torch.Tensor`` or a ``batch x channels x height x width`` ``torch.Tensor``. + mask (_type_): The mask to apply to the image, i.e. regions to inpaint. + It can be a ``PIL.Image``, or a ``height x width`` ``np.array`` or a ``1 x height x width`` + ``torch.Tensor`` or a ``batch x 1 x height x width`` ``torch.Tensor``. + + + Raises: + ValueError: ``torch.Tensor`` images should be in the ``[-1, 1]`` range. ValueError: ``torch.Tensor`` mask + should be in the ``[0, 1]`` range. ValueError: ``mask`` and ``image`` should have the same spatial dimensions. + TypeError: ``mask`` is a ``torch.Tensor`` but ``image`` is not + (ot the other way around). + + Returns: + tuple[torch.Tensor]: The pair (mask, masked_image) as ``torch.Tensor`` with 4 + dimensions: ``batch x channels x height x width``. + """ + + if image is None: + raise ValueError("`image` input cannot be undefined.") + + if mask is None: + raise ValueError("`mask_image` input cannot be undefined.") + + if isinstance(image, torch.Tensor): + if not isinstance(mask, torch.Tensor): + raise TypeError( + f"`image` is a torch.Tensor but `mask` (type: {type(mask)} is not" + ) + + # Batch single image + if image.ndim == 3: + assert ( + image.shape[0] == 3 + ), "Image outside a batch should be of shape (3, H, W)" + image = image.unsqueeze(0) + + # Batch and add channel dim for single mask + if mask.ndim == 2: + mask = mask.unsqueeze(0).unsqueeze(0) + + # Batch single mask or add channel dim + if mask.ndim == 3: + # Single batched mask, no channel dim or single mask not batched but channel dim + if mask.shape[0] == 1: + mask = mask.unsqueeze(0) + + # Batched masks no channel dim + else: + mask = mask.unsqueeze(1) + + assert ( + image.ndim == 4 and mask.ndim == 4 + ), "Image and Mask must have 4 dimensions" + assert ( + image.shape[-2:] == mask.shape[-2:] + ), "Image and Mask must have the same spatial dimensions" + assert ( + image.shape[0] == mask.shape[0] + ), "Image and Mask must have the same batch size" + + # Check image is in [-1, 1] + if image.min() < -1 or image.max() > 1: + raise ValueError("Image should be in [-1, 1] range") + + # Check mask is in [0, 1] + if mask.min() < 0 or mask.max() > 1: + raise ValueError("Mask should be in [0, 1] range") + + # Binarize mask + mask[mask < 0.5] = 0 + mask[mask >= 0.5] = 1 + + # Image as float32 + image = image.to(dtype=torch.float32) + elif isinstance(mask, torch.Tensor): + raise TypeError( + f"`mask` is a torch.Tensor but `image` (type: {type(image)} is not" + ) + else: + # preprocess image + if isinstance(image, (PIL.Image.Image, np.ndarray)): + image = [image] + if isinstance(image, list) and isinstance(image[0], PIL.Image.Image): + # resize all images w.r.t passed height an width + image = [ + i.resize((width, height), resample=PIL.Image.LANCZOS) for i in image + ] + image = [np.array(i.convert("RGB"))[None, :] for i in image] + image = np.concatenate(image, axis=0) + elif isinstance(image, list) and isinstance(image[0], np.ndarray): + image = np.concatenate([i[None, :] for i in image], axis=0) + + image = image.transpose(0, 3, 1, 2) + image = torch.from_numpy(image).to(dtype=torch.float32) / 127.5 - 1.0 + + # preprocess mask + if isinstance(mask, (PIL.Image.Image, np.ndarray)): + mask = [mask] + + if isinstance(mask, list) and isinstance(mask[0], PIL.Image.Image): + mask = [i.resize((width, height), resample=PIL.Image.LANCZOS) for i in mask] + mask = np.concatenate( + [np.array(m.convert("L"))[None, None, :] for m in mask], axis=0 + ) + mask = mask.astype(np.float32) / 255.0 + elif isinstance(mask, list) and isinstance(mask[0], np.ndarray): + mask = np.concatenate([m[None, None, :] for m in mask], axis=0) + + mask[mask < 0.5] = 0 + mask[mask >= 0.5] = 1 + mask = torch.from_numpy(mask) + + masked_image = image * (mask < 0.5) + + # n.b. ensure backwards compatibility as old function does not return image + if return_image: + return mask, masked_image, image + + return mask, masked_image + + +class StableDiffusionInpaintPipeline( + DiffusionPipeline, TextualInversionLoaderMixin, LoraLoaderMixin, FromSingleFileMixin +): + r""" + Pipeline for text-guided image inpainting using Stable Diffusion. + + This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods + implemented for all pipelines (downloading, saving, running on a particular device, etc.). + + The pipeline also inherits the following loading methods: + - [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings + - [`~loaders.LoraLoaderMixin.load_lora_weights`] for loading LoRA weights + - [`~loaders.LoraLoaderMixin.save_lora_weights`] for saving LoRA weights + + Args: + vae ([`AutoencoderKL`, `AsymmetricAutoencoderKL`]): + Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations. + text_encoder ([`CLIPTextModel`]): + Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)). + tokenizer ([`~transformers.CLIPTokenizer`]): + A `CLIPTokenizer` to tokenize text. + unet ([`UNet2DConditionModel`]): + A `UNet2DConditionModel` to denoise the encoded image latents. + scheduler ([`SchedulerMixin`]): + A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of + [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`]. + safety_checker ([`StableDiffusionSafetyChecker`]): + Classification module that estimates whether generated images could be considered offensive or harmful. + Please refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for more details + about a model's potential harms. + feature_extractor ([`~transformers.CLIPImageProcessor`]): + A `CLIPImageProcessor` to extract features from generated images; used as inputs to the `safety_checker`. + """ + _optional_components = ["safety_checker", "feature_extractor"] + + def __init__( + self, + vae: Union[AutoencoderKL, AsymmetricAutoencoderKL], + text_encoder: CLIPTextModel, + tokenizer: CLIPTokenizer, + unet: UNet2DConditionModel, + scheduler: KarrasDiffusionSchedulers, + safety_checker: StableDiffusionSafetyChecker, + feature_extractor: CLIPImageProcessor, + requires_safety_checker: bool = True, + ): + super().__init__() + + if ( + hasattr(scheduler.config, "steps_offset") + and scheduler.config.steps_offset != 1 + ): + deprecation_message = ( + f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`" + f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure " + "to update the config accordingly as leaving `steps_offset` might led to incorrect results" + " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub," + " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`" + " file" + ) + deprecate( + "steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False + ) + new_config = dict(scheduler.config) + new_config["steps_offset"] = 1 + scheduler._internal_dict = FrozenDict(new_config) + + if ( + hasattr(scheduler.config, "skip_prk_steps") + and scheduler.config.skip_prk_steps is False + ): + deprecation_message = ( + f"The configuration file of this scheduler: {scheduler} has not set the configuration" + " `skip_prk_steps`. `skip_prk_steps` should be set to True in the configuration file. Please make" + " sure to update the config accordingly as not setting `skip_prk_steps` in the config might lead to" + " incorrect results in future versions. If you have downloaded this checkpoint from the Hugging Face" + " Hub, it would be very nice if you could open a Pull request for the" + " `scheduler/scheduler_config.json` file" + ) + deprecate( + "skip_prk_steps not set", + "1.0.0", + deprecation_message, + standard_warn=False, + ) + new_config = dict(scheduler.config) + new_config["skip_prk_steps"] = True + scheduler._internal_dict = FrozenDict(new_config) + + if safety_checker is None and requires_safety_checker: + logger.warning( + f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure" + " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered" + " results in services or applications open to the public. Both the diffusers team and Hugging Face" + " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling" + " it only for use-cases that involve analyzing network behavior or auditing its results. For more" + " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ." + ) + + if safety_checker is not None and feature_extractor is None: + raise ValueError( + "Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety" + " checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead." + ) + + is_unet_version_less_0_9_0 = hasattr( + unet.config, "_diffusers_version" + ) and version.parse( + version.parse(unet.config._diffusers_version).base_version + ) < version.parse( + "0.9.0.dev0" + ) + is_unet_sample_size_less_64 = ( + hasattr(unet.config, "sample_size") and unet.config.sample_size < 64 + ) + if is_unet_version_less_0_9_0 and is_unet_sample_size_less_64: + deprecation_message = ( + "The configuration file of the unet has set the default `sample_size` to smaller than" + " 64 which seems highly unlikely .If you're checkpoint is a fine-tuned version of any of the" + " following: \n- CompVis/stable-diffusion-v1-4 \n- CompVis/stable-diffusion-v1-3 \n-" + " CompVis/stable-diffusion-v1-2 \n- CompVis/stable-diffusion-v1-1 \n- runwayml/stable-diffusion-v1-5" + " \n- runwayml/stable-diffusion-inpainting \n you should change 'sample_size' to 64 in the" + " configuration file. Please make sure to update the config accordingly as leaving `sample_size=32`" + " in the config might lead to incorrect results in future versions. If you have downloaded this" + " checkpoint from the Hugging Face Hub, it would be very nice if you could open a Pull request for" + " the `unet/config.json` file" + ) + deprecate( + "sample_size<64", "1.0.0", deprecation_message, standard_warn=False + ) + new_config = dict(unet.config) + new_config["sample_size"] = 64 + unet._internal_dict = FrozenDict(new_config) + + # Check shapes, assume num_channels_latents == 4, num_channels_mask == 1, num_channels_masked == 4 + if unet.config.in_channels != 9: + logger.info( + f"You have loaded a UNet with {unet.config.in_channels} input channels which." + ) + + self.register_modules( + vae=vae, + text_encoder=text_encoder, + tokenizer=tokenizer, + unet=unet, + scheduler=scheduler, + safety_checker=safety_checker, + feature_extractor=feature_extractor, + ) + self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1) + self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor) + self.register_to_config(requires_safety_checker=requires_safety_checker) + + # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.enable_model_cpu_offload + def enable_model_cpu_offload(self, gpu_id=0): + r""" + Offload all models to CPU to reduce memory usage with a low impact on performance. Moves one whole model at a + time to the GPU when its `forward` method is called, and the model remains in GPU until the next model runs. + Memory savings are lower than using `enable_sequential_cpu_offload`, but performance is much better due to the + iterative execution of the `unet`. + """ + if is_accelerate_available() and is_accelerate_version(">=", "0.17.0.dev0"): + from accelerate import cpu_offload_with_hook + else: + raise ImportError( + "`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher." + ) + + device = torch.device(f"cuda:{gpu_id}") + + if self.device.type != "cpu": + self.to("cpu", silence_dtype_warnings=True) + torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) + + hook = None + for cpu_offloaded_model in [self.text_encoder, self.unet, self.vae]: + _, hook = cpu_offload_with_hook( + cpu_offloaded_model, device, prev_module_hook=hook + ) + + if self.safety_checker is not None: + _, hook = cpu_offload_with_hook( + self.safety_checker, device, prev_module_hook=hook + ) + + # We'll offload the last model manually. + self.final_offload_hook = hook + + # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._encode_prompt + def _encode_prompt( + self, + promptA, + promptB, + t, + device, + num_images_per_prompt, + do_classifier_free_guidance, + negative_promptA=None, + negative_promptB=None, + t_nag=None, + prompt_embeds: Optional[torch.FloatTensor] = None, + negative_prompt_embeds: Optional[torch.FloatTensor] = None, + lora_scale: Optional[float] = None, + ): + r""" + Encodes the prompt into text encoder hidden states. + + Args: + prompt (`str` or `List[str]`, *optional*): + prompt to be encoded + device: (`torch.device`): + torch device + num_images_per_prompt (`int`): + number of images that should be generated per prompt + do_classifier_free_guidance (`bool`): + whether to use classifier free guidance or not + negative_prompt (`str` or `List[str]`, *optional*): + The prompt or prompts not to guide the image generation. If not defined, one has to pass + `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is + less than `1`). + prompt_embeds (`torch.FloatTensor`, *optional*): + Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not + provided, text embeddings will be generated from `prompt` input argument. + negative_prompt_embeds (`torch.FloatTensor`, *optional*): + Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt + weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input + argument. + lora_scale (`float`, *optional*): + A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded. + """ + # set lora scale so that monkey patched LoRA + # function of text encoder can correctly access it + if lora_scale is not None and isinstance(self, LoraLoaderMixin): + self._lora_scale = lora_scale + + prompt = promptA + negative_prompt = negative_promptA + + if promptA is not None and isinstance(promptA, str): + batch_size = 1 + elif promptA is not None and isinstance(promptA, list): + batch_size = len(promptA) + else: + batch_size = prompt_embeds.shape[0] + + if prompt_embeds is None: + # textual inversion: procecss multi-vector tokens if necessary + if isinstance(self, TextualInversionLoaderMixin): + promptA = self.maybe_convert_prompt(promptA, self.tokenizer) + + text_inputsA = self.tokenizer( + promptA, + padding="max_length", + max_length=self.tokenizer.model_max_length, + truncation=True, + return_tensors="pt", + ) + text_inputsB = self.tokenizer( + promptB, + padding="max_length", + max_length=self.tokenizer.model_max_length, + truncation=True, + return_tensors="pt", + ) + text_input_idsA = text_inputsA.input_ids + text_input_idsB = text_inputsB.input_ids + untruncated_ids = self.tokenizer( + promptA, padding="longest", return_tensors="pt" + ).input_ids + + if untruncated_ids.shape[-1] >= text_input_idsA.shape[ + -1 + ] and not torch.equal(text_input_idsA, untruncated_ids): + removed_text = self.tokenizer.batch_decode( + untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1] + ) + logger.warning( + "The following part of your input was truncated because CLIP can only handle sequences up to" + f" {self.tokenizer.model_max_length} tokens: {removed_text}" + ) + + if ( + hasattr(self.text_encoder.config, "use_attention_mask") + and self.text_encoder.config.use_attention_mask + ): + attention_mask = text_inputsA.attention_mask.to(device) + else: + attention_mask = None + + # print("text_input_idsA: ",text_input_idsA) + # print("text_input_idsB: ",text_input_idsB) + # print('t: ',t) + + prompt_embedsA = self.text_encoder( + text_input_idsA.to(device), + attention_mask=attention_mask, + ) + prompt_embedsA = prompt_embedsA[0] + + prompt_embedsB = self.text_encoder( + text_input_idsB.to(device), + attention_mask=attention_mask, + ) + prompt_embedsB = prompt_embedsB[0] + prompt_embeds = prompt_embedsA * (t) + (1 - t) * prompt_embedsB + # print("prompt_embeds: ",prompt_embeds) + + if self.text_encoder is not None: + prompt_embeds_dtype = self.text_encoder.dtype + elif self.unet is not None: + prompt_embeds_dtype = self.unet.dtype + else: + prompt_embeds_dtype = prompt_embeds.dtype + + prompt_embeds = prompt_embeds.to(dtype=prompt_embeds_dtype, device=device) + + bs_embed, seq_len, _ = prompt_embeds.shape + # duplicate text embeddings for each generation per prompt, using mps friendly method + prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1) + prompt_embeds = prompt_embeds.view( + bs_embed * num_images_per_prompt, seq_len, -1 + ) + + # get unconditional embeddings for classifier free guidance + if do_classifier_free_guidance and negative_prompt_embeds is None: + uncond_tokensA: List[str] + uncond_tokensB: List[str] + if negative_prompt is None: + uncond_tokensA = [""] * batch_size + uncond_tokensB = [""] * batch_size + elif prompt is not None and type(prompt) is not type(negative_prompt): + raise TypeError( + f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !=" + f" {type(prompt)}." + ) + elif isinstance(negative_prompt, str): + uncond_tokensA = [negative_promptA] + uncond_tokensB = [negative_promptB] + elif batch_size != len(negative_prompt): + raise ValueError( + f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:" + f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches" + " the batch size of `prompt`." + ) + else: + uncond_tokensA = negative_promptA + uncond_tokensB = negative_promptB + + # textual inversion: procecss multi-vector tokens if necessary + if isinstance(self, TextualInversionLoaderMixin): + uncond_tokensA = self.maybe_convert_prompt( + uncond_tokensA, self.tokenizer + ) + uncond_tokensB = self.maybe_convert_prompt( + uncond_tokensB, self.tokenizer + ) + + max_length = prompt_embeds.shape[1] + uncond_inputA = self.tokenizer( + uncond_tokensA, + padding="max_length", + max_length=max_length, + truncation=True, + return_tensors="pt", + ) + uncond_inputB = self.tokenizer( + uncond_tokensB, + padding="max_length", + max_length=max_length, + truncation=True, + return_tensors="pt", + ) + + if ( + hasattr(self.text_encoder.config, "use_attention_mask") + and self.text_encoder.config.use_attention_mask + ): + attention_mask = uncond_inputA.attention_mask.to(device) + else: + attention_mask = None + + negative_prompt_embedsA = self.text_encoder( + uncond_inputA.input_ids.to(device), + attention_mask=attention_mask, + ) + negative_prompt_embedsB = self.text_encoder( + uncond_inputB.input_ids.to(device), + attention_mask=attention_mask, + ) + negative_prompt_embeds = ( + negative_prompt_embedsA[0] * (t_nag) + + (1 - t_nag) * negative_prompt_embedsB[0] + ) + + # negative_prompt_embeds = negative_prompt_embeds[0] + + if do_classifier_free_guidance: + # duplicate unconditional embeddings for each generation per prompt, using mps friendly method + seq_len = negative_prompt_embeds.shape[1] + + negative_prompt_embeds = negative_prompt_embeds.to( + dtype=prompt_embeds_dtype, device=device + ) + + negative_prompt_embeds = negative_prompt_embeds.repeat( + 1, num_images_per_prompt, 1 + ) + negative_prompt_embeds = negative_prompt_embeds.view( + batch_size * num_images_per_prompt, seq_len, -1 + ) + + # For classifier free guidance, we need to do two forward passes. + # Here we concatenate the unconditional and text embeddings into a single batch + # to avoid doing two forward passes + # print("prompt_embeds: ",prompt_embeds) + prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds]) + + return prompt_embeds + + # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.run_safety_checker + def run_safety_checker(self, image, device, dtype): + if self.safety_checker is None: + has_nsfw_concept = None + else: + if torch.is_tensor(image): + feature_extractor_input = self.image_processor.postprocess( + image, output_type="pil" + ) + else: + feature_extractor_input = self.image_processor.numpy_to_pil(image) + safety_checker_input = self.feature_extractor( + feature_extractor_input, return_tensors="pt" + ).to(device) + image, has_nsfw_concept = self.safety_checker( + images=image, clip_input=safety_checker_input.pixel_values.to(dtype) + ) + return image, has_nsfw_concept + + # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs + def prepare_extra_step_kwargs(self, generator, eta): + # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature + # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. + # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 + # and should be between [0, 1] + + accepts_eta = "eta" in set( + inspect.signature(self.scheduler.step).parameters.keys() + ) + extra_step_kwargs = {} + if accepts_eta: + extra_step_kwargs["eta"] = eta + + # check if the scheduler accepts generator + accepts_generator = "generator" in set( + inspect.signature(self.scheduler.step).parameters.keys() + ) + if accepts_generator: + extra_step_kwargs["generator"] = generator + return extra_step_kwargs + + def check_inputs( + self, + prompt, + height, + width, + strength, + callback_steps, + negative_prompt=None, + prompt_embeds=None, + negative_prompt_embeds=None, + ): + if strength < 0 or strength > 1: + raise ValueError( + f"The value of strength should in [0.0, 1.0] but is {strength}" + ) + + if height % 8 != 0 or width % 8 != 0: + raise ValueError( + f"`height` and `width` have to be divisible by 8 but are {height} and {width}." + ) + + if (callback_steps is None) or ( + callback_steps is not None + and (not isinstance(callback_steps, int) or callback_steps <= 0) + ): + raise ValueError( + f"`callback_steps` has to be a positive integer but is {callback_steps} of type" + f" {type(callback_steps)}." + ) + + if prompt is not None and prompt_embeds is not None: + raise ValueError( + f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to" + " only forward one of the two." + ) + elif prompt is None and prompt_embeds is None: + raise ValueError( + "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined." + ) + elif prompt is not None and ( + not isinstance(prompt, str) and not isinstance(prompt, list) + ): + raise ValueError( + f"`prompt` has to be of type `str` or `list` but is {type(prompt)}" + ) + + if negative_prompt is not None and negative_prompt_embeds is not None: + raise ValueError( + f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:" + f" {negative_prompt_embeds}. Please make sure to only forward one of the two." + ) + + if prompt_embeds is not None and negative_prompt_embeds is not None: + if prompt_embeds.shape != negative_prompt_embeds.shape: + raise ValueError( + "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but" + f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`" + f" {negative_prompt_embeds.shape}." + ) + + def prepare_latents( + self, + batch_size, + num_channels_latents, + height, + width, + dtype, + device, + generator, + latents=None, + image=None, + timestep=None, + is_strength_max=True, + return_noise=False, + return_image_latents=False, + ): + shape = ( + batch_size, + num_channels_latents, + height // self.vae_scale_factor, + width // self.vae_scale_factor, + ) + if isinstance(generator, list) and len(generator) != batch_size: + raise ValueError( + f"You have passed a list of generators of length {len(generator)}, but requested an effective batch" + f" size of {batch_size}. Make sure the batch size matches the length of the generators." + ) + + if (image is None or timestep is None) and not is_strength_max: + raise ValueError( + "Since strength < 1. initial latents are to be initialised as a combination of Image + Noise." + "However, either the image or the noise timestep has not been provided." + ) + + if return_image_latents or (latents is None and not is_strength_max): + image = image.to(device=device, dtype=dtype) + image_latents = self._encode_vae_image(image=image, generator=generator) + + if latents is None: + noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype) + # if strength is 1. then initialise the latents to noise, else initial to image + noise + latents = ( + noise + if is_strength_max + else self.scheduler.add_noise(image_latents, noise, timestep) + ) + # if pure noise then scale the initial latents by the Scheduler's init sigma + latents = ( + latents * self.scheduler.init_noise_sigma + if is_strength_max + else latents + ) + else: + noise = latents.to(device) + latents = noise * self.scheduler.init_noise_sigma + + outputs = (latents,) + + if return_noise: + outputs += (noise,) + + if return_image_latents: + outputs += (image_latents,) + + return outputs + + def _encode_vae_image(self, image: torch.Tensor, generator: torch.Generator): + if isinstance(generator, list): + image_latents = [ + self.vae.encode(image[i : i + 1]).latent_dist.sample( + generator=generator[i] + ) + for i in range(image.shape[0]) + ] + image_latents = torch.cat(image_latents, dim=0) + else: + image_latents = self.vae.encode(image).latent_dist.sample( + generator=generator + ) + + image_latents = self.vae.config.scaling_factor * image_latents + + return image_latents + + def prepare_mask_latents( + self, + mask, + masked_image, + batch_size, + height, + width, + dtype, + device, + generator, + do_classifier_free_guidance, + ): + # resize the mask to latents shape as we concatenate the mask to the latents + # we do that before converting to dtype to avoid breaking in case we're using cpu_offload + # and half precision + mask = torch.nn.functional.interpolate( + mask, size=(height // self.vae_scale_factor, width // self.vae_scale_factor) + ) + mask = mask.to(device=device, dtype=dtype) + + masked_image = masked_image.to(device=device, dtype=dtype) + masked_image_latents = self._encode_vae_image(masked_image, generator=generator) + + # duplicate mask and masked_image_latents for each generation per prompt, using mps friendly method + if mask.shape[0] < batch_size: + if not batch_size % mask.shape[0] == 0: + raise ValueError( + "The passed mask and the required batch size don't match. Masks are supposed to be duplicated to" + f" a total batch size of {batch_size}, but {mask.shape[0]} masks were passed. Make sure the number" + " of masks that you pass is divisible by the total requested batch size." + ) + mask = mask.repeat(batch_size // mask.shape[0], 1, 1, 1) + if masked_image_latents.shape[0] < batch_size: + if not batch_size % masked_image_latents.shape[0] == 0: + raise ValueError( + "The passed images and the required batch size don't match. Images are supposed to be duplicated" + f" to a total batch size of {batch_size}, but {masked_image_latents.shape[0]} images were passed." + " Make sure the number of images that you pass is divisible by the total requested batch size." + ) + masked_image_latents = masked_image_latents.repeat( + batch_size // masked_image_latents.shape[0], 1, 1, 1 + ) + + mask = torch.cat([mask] * 2) if do_classifier_free_guidance else mask + masked_image_latents = ( + torch.cat([masked_image_latents] * 2) + if do_classifier_free_guidance + else masked_image_latents + ) + + # aligning device to prevent device errors when concating it with the latent model input + masked_image_latents = masked_image_latents.to(device=device, dtype=dtype) + return mask, masked_image_latents + + # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.StableDiffusionImg2ImgPipeline.get_timesteps + def get_timesteps(self, num_inference_steps, strength, device): + # get the original timestep using init_timestep + init_timestep = min(int(num_inference_steps * strength), num_inference_steps) + + t_start = max(num_inference_steps - init_timestep, 0) + timesteps = self.scheduler.timesteps[t_start * self.scheduler.order :] + + return timesteps, num_inference_steps - t_start + + @torch.no_grad() + def __call__( + self, + promptA: Union[str, List[str]] = None, + promptB: Union[str, List[str]] = None, + image: Union[torch.FloatTensor, PIL.Image.Image] = None, + mask_image: Union[torch.FloatTensor, PIL.Image.Image] = None, + height: Optional[int] = None, + width: Optional[int] = None, + strength: float = 1.0, + tradoff: float = 1.0, + tradoff_nag: float = 1.0, + num_inference_steps: int = 50, + guidance_scale: float = 7.5, + negative_promptA: Optional[Union[str, List[str]]] = None, + negative_promptB: Optional[Union[str, List[str]]] = None, + num_images_per_prompt: Optional[int] = 1, + eta: float = 0.0, + generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None, + latents: Optional[torch.FloatTensor] = None, + prompt_embeds: Optional[torch.FloatTensor] = None, + negative_prompt_embeds: Optional[torch.FloatTensor] = None, + output_type: Optional[str] = "pil", + return_dict: bool = True, + callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None, + callback_steps: int = 1, + cross_attention_kwargs: Optional[Dict[str, Any]] = None, + task_class: Union[torch.Tensor, float, int] = None, + ): + r""" + The call function to the pipeline for generation. + + Args: + prompt (`str` or `List[str]`, *optional*): + The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`. + image (`PIL.Image.Image`): + `Image` or tensor representing an image batch to be inpainted (which parts of the image to be masked + out with `mask_image` and repainted according to `prompt`). + mask_image (`PIL.Image.Image`): + `Image` or tensor representing an image batch to mask `image`. White pixels in the mask are repainted + while black pixels are preserved. If `mask_image` is a PIL image, it is converted to a single channel + (luminance) before use. If it's a tensor, it should contain one color channel (L) instead of 3, so the + expected shape would be `(B, H, W, 1)`. + height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`): + The height in pixels of the generated image. + width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`): + The width in pixels of the generated image. + strength (`float`, *optional*, defaults to 1.0): + Indicates extent to transform the reference `image`. Must be between 0 and 1. `image` is used as a + starting point and more noise is added the higher the `strength`. The number of denoising steps depends + on the amount of noise initially added. When `strength` is 1, added noise is maximum and the denoising + process runs for the full number of iterations specified in `num_inference_steps`. A value of 1 + essentially ignores `image`. + num_inference_steps (`int`, *optional*, defaults to 50): + The number of denoising steps. More denoising steps usually lead to a higher quality image at the + expense of slower inference. This parameter is modulated by `strength`. + guidance_scale (`float`, *optional*, defaults to 7.5): + A higher guidance scale value encourages the model to generate images closely linked to the text + `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`. + negative_prompt (`str` or `List[str]`, *optional*): + The prompt or prompts to guide what to not include in image generation. If not defined, you need to + pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`). + num_images_per_prompt (`int`, *optional*, defaults to 1): + The number of images to generate per prompt. + eta (`float`, *optional*, defaults to 0.0): + Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies + to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers. + generator (`torch.Generator` or `List[torch.Generator]`, *optional*): + A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make + generation deterministic. + latents (`torch.FloatTensor`, *optional*): + Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image + generation. Can be used to tweak the same generation with different prompts. If not provided, a latents + tensor is generated by sampling using the supplied random `generator`. + prompt_embeds (`torch.FloatTensor`, *optional*): + Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not + provided, text embeddings are generated from the `prompt` input argument. + negative_prompt_embeds (`torch.FloatTensor`, *optional*): + Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If + not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument. + output_type (`str`, *optional*, defaults to `"pil"`): + The output format of the generated image. Choose between `PIL.Image` or `np.array`. + return_dict (`bool`, *optional*, defaults to `True`): + Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a + plain tuple. + callback (`Callable`, *optional*): + A function that calls every `callback_steps` steps during inference. The function is called with the + following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`. + callback_steps (`int`, *optional*, defaults to 1): + The frequency at which the `callback` function is called. If not specified, the callback is called at + every step. + cross_attention_kwargs (`dict`, *optional*): + A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in + [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py). + + Examples: + + ```py + >>> import PIL + >>> import requests + >>> import torch + >>> from io import BytesIO + + >>> from diffusers import StableDiffusionInpaintPipeline + + + >>> def download_image(url): + ... response = requests.get(url) + ... return PIL.Image.open(BytesIO(response.content)).convert("RGB") + + + >>> img_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png" + >>> mask_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png" + + >>> init_image = download_image(img_url).resize((512, 512)) + >>> mask_image = download_image(mask_url).resize((512, 512)) + + >>> pipe = StableDiffusionInpaintPipeline.from_pretrained( + ... "runwayml/stable-diffusion-inpainting", torch_dtype=torch.float16 + ... ) + >>> pipe = pipe.to("cuda") + + >>> prompt = "Face of a yellow cat, high resolution, sitting on a park bench" + >>> image = pipe(prompt=prompt, image=init_image, mask_image=mask_image).images[0] + ``` + + Returns: + [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`: + If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned, + otherwise a `tuple` is returned where the first element is a list with the generated images and the + second element is a list of `bool`s indicating whether the corresponding generated image contains + "not-safe-for-work" (nsfw) content. + """ + # 0. Default height and width to unet + height = height or self.unet.config.sample_size * self.vae_scale_factor + width = width or self.unet.config.sample_size * self.vae_scale_factor + prompt = promptA + negative_prompt = negative_promptA + # 1. Check inputs + self.check_inputs( + prompt, + height, + width, + strength, + callback_steps, + negative_prompt, + prompt_embeds, + negative_prompt_embeds, + ) + + # 2. Define call parameters + if prompt is not None and isinstance(prompt, str): + batch_size = 1 + elif prompt is not None and isinstance(prompt, list): + batch_size = len(prompt) + else: + batch_size = prompt_embeds.shape[0] + + device = self._execution_device + # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) + # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` + # corresponds to doing no classifier free guidance. + do_classifier_free_guidance = guidance_scale > 1.0 + + # 3. Encode input prompt + text_encoder_lora_scale = ( + cross_attention_kwargs.get("scale", None) + if cross_attention_kwargs is not None + else None + ) + prompt_embeds = self._encode_prompt( + promptA, + promptB, + tradoff, + device, + num_images_per_prompt, + do_classifier_free_guidance, + negative_promptA, + negative_promptB, + tradoff_nag, + prompt_embeds=prompt_embeds, + negative_prompt_embeds=negative_prompt_embeds, + lora_scale=text_encoder_lora_scale, + ) + + # 4. set timesteps + self.scheduler.set_timesteps(num_inference_steps, device=device) + timesteps, num_inference_steps = self.get_timesteps( + num_inference_steps=num_inference_steps, strength=strength, device=device + ) + # check that number of inference steps is not < 1 - as this doesn't make sense + if num_inference_steps < 1: + raise ValueError( + f"After adjusting the num_inference_steps by strength parameter: {strength}, the number of pipeline" + f"steps is {num_inference_steps} which is < 1 and not appropriate for this pipeline." + ) + # at which timestep to set the initial noise (n.b. 50% if strength is 0.5) + latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt) + # create a boolean to check if the strength is set to 1. if so then initialise the latents with pure noise + is_strength_max = strength == 1.0 + + # 5. Preprocess mask and image + mask, masked_image, init_image = prepare_mask_and_masked_image( + image, mask_image, height, width, return_image=True + ) + mask_condition = mask.clone() + + # 6. Prepare latent variables + num_channels_latents = self.vae.config.latent_channels + num_channels_unet = self.unet.config.in_channels + return_image_latents = num_channels_unet == 4 + + latents_outputs = self.prepare_latents( + batch_size * num_images_per_prompt, + num_channels_latents, + height, + width, + prompt_embeds.dtype, + device, + generator, + latents, + image=init_image, + timestep=latent_timestep, + is_strength_max=is_strength_max, + return_noise=True, + return_image_latents=return_image_latents, + ) + + if return_image_latents: + latents, noise, image_latents = latents_outputs + else: + latents, noise = latents_outputs + + # 7. Prepare mask latent variables + mask, masked_image_latents = self.prepare_mask_latents( + mask, + masked_image, + batch_size * num_images_per_prompt, + height, + width, + prompt_embeds.dtype, + device, + generator, + do_classifier_free_guidance, + ) + + # 8. Check that sizes of mask, masked image and latents match + if num_channels_unet == 9: + # default case for runwayml/stable-diffusion-inpainting + num_channels_mask = mask.shape[1] + num_channels_masked_image = masked_image_latents.shape[1] + if ( + num_channels_latents + num_channels_mask + num_channels_masked_image + != self.unet.config.in_channels + ): + raise ValueError( + f"Incorrect configuration settings! The config of `pipeline.unet`: {self.unet.config} expects" + f" {self.unet.config.in_channels} but received `num_channels_latents`: {num_channels_latents} +" + f" `num_channels_mask`: {num_channels_mask} + `num_channels_masked_image`: {num_channels_masked_image}" + f" = {num_channels_latents+num_channels_masked_image+num_channels_mask}. Please verify the config of" + " `pipeline.unet` or your `mask_image` or `image` input." + ) + elif num_channels_unet != 4: + raise ValueError( + f"The unet {self.unet.__class__} should have either 4 or 9 input channels, not {self.unet.config.in_channels}." + ) + + # 9. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline + extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta) + + # 10. Denoising loop + num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order + with self.progress_bar(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 + ) + + # concat latents, mask, masked_image_latents in the channel dimension + latent_model_input = self.scheduler.scale_model_input( + latent_model_input, t + ) + + if num_channels_unet == 9: + latent_model_input = torch.cat( + [latent_model_input, mask, masked_image_latents], dim=1 + ) + + # predict the noise residual + if task_class is not None: + noise_pred = self.unet( + sample=latent_model_input, + timestep=t, + encoder_hidden_states=prompt_embeds, + cross_attention_kwargs=cross_attention_kwargs, + return_dict=False, + task_class=task_class, + )[0] + else: + noise_pred = self.unet( + latent_model_input, + t, + encoder_hidden_states=prompt_embeds, + cross_attention_kwargs=cross_attention_kwargs, + return_dict=False, + )[0] + + # perform guidance + if do_classifier_free_guidance: + noise_pred_uncond, noise_pred_text = noise_pred.chunk(2) + noise_pred = noise_pred_uncond + guidance_scale * ( + noise_pred_text - noise_pred_uncond + ) + + # compute the previous noisy sample x_t -> x_t-1 + latents = self.scheduler.step( + noise_pred, t, latents, **extra_step_kwargs, return_dict=False + )[0] + + if num_channels_unet == 4: + init_latents_proper = image_latents[:1] + init_mask = mask[:1] + + if i < len(timesteps) - 1: + noise_timestep = timesteps[i + 1] + init_latents_proper = self.scheduler.add_noise( + init_latents_proper, noise, torch.tensor([noise_timestep]) + ) + + latents = ( + 1 - init_mask + ) * init_latents_proper + init_mask * latents + + # call the callback, if provided + if i == len(timesteps) - 1 or ( + (i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0 + ): + progress_bar.update() + if callback is not None and i % callback_steps == 0: + callback(self, i, t, {}) + + if not output_type == "latent": + condition_kwargs = {} + if isinstance(self.vae, AsymmetricAutoencoderKL): + init_image = init_image.to( + device=device, dtype=masked_image_latents.dtype + ) + init_image_condition = init_image.clone() + init_image = self._encode_vae_image(init_image, generator=generator) + mask_condition = mask_condition.to( + device=device, dtype=masked_image_latents.dtype + ) + condition_kwargs = { + "image": init_image_condition, + "mask": mask_condition, + } + image = self.vae.decode( + latents / self.vae.config.scaling_factor, + return_dict=False, + **condition_kwargs, + )[0] + image, has_nsfw_concept = self.run_safety_checker( + image, device, prompt_embeds.dtype + ) + else: + image = latents + has_nsfw_concept = None + + if has_nsfw_concept is None: + do_denormalize = [True] * image.shape[0] + else: + do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept] + + image = self.image_processor.postprocess( + image, output_type=output_type, do_denormalize=do_denormalize + ) + + # Offload last model to CPU + if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None: + self.final_offload_hook.offload() + + if not return_dict: + return (image, has_nsfw_concept) + + return StableDiffusionPipelineOutput( + images=image, nsfw_content_detected=has_nsfw_concept + ) diff --git a/py/iopaint/model/power_paint/pipeline_powerpaint_controlnet.py b/py/iopaint/model/power_paint/pipeline_powerpaint_controlnet.py new file mode 100644 index 0000000..cba0f8f --- /dev/null +++ b/py/iopaint/model/power_paint/pipeline_powerpaint_controlnet.py @@ -0,0 +1,1775 @@ +# Copyright 2023 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# This model implementation is heavily inspired by https://github.com/haofanwang/ControlNet-for-Diffusers/ + +import inspect +import warnings +from typing import Any, Callable, Dict, List, Optional, Tuple, Union + +import numpy as np +import PIL.Image +import torch +import torch.nn.functional as F +from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer + +from diffusers.image_processor import VaeImageProcessor +from diffusers.loaders import FromSingleFileMixin, LoraLoaderMixin, TextualInversionLoaderMixin +from diffusers.models import AutoencoderKL, ControlNetModel, UNet2DConditionModel +from diffusers.schedulers import KarrasDiffusionSchedulers +from diffusers.utils import ( + is_accelerate_available, + is_accelerate_version, + logging, + replace_example_docstring, +) +from diffusers.utils.torch_utils import randn_tensor,is_compiled_module +from diffusers.pipelines.pipeline_utils import DiffusionPipeline +from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput +from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker +from diffusers.pipelines.controlnet import MultiControlNetModel + + + + +logger = logging.get_logger(__name__) # pylint: disable=invalid-name + + +EXAMPLE_DOC_STRING = """ + Examples: + ```py + >>> # !pip install transformers accelerate + >>> from diffusers import StableDiffusionControlNetInpaintPipeline, ControlNetModel, DDIMScheduler + >>> from diffusers.utils import load_image + >>> import numpy as np + >>> import torch + + >>> init_image = load_image( + ... "https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/stable_diffusion_inpaint/boy.png" + ... ) + >>> init_image = init_image.resize((512, 512)) + + >>> generator = torch.Generator(device="cpu").manual_seed(1) + + >>> mask_image = load_image( + ... "https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/stable_diffusion_inpaint/boy_mask.png" + ... ) + >>> mask_image = mask_image.resize((512, 512)) + + + >>> def make_inpaint_condition(image, image_mask): + ... image = np.array(image.convert("RGB")).astype(np.float32) / 255.0 + ... image_mask = np.array(image_mask.convert("L")).astype(np.float32) / 255.0 + + ... assert image.shape[0:1] == image_mask.shape[0:1], "image and image_mask must have the same image size" + ... image[image_mask > 0.5] = -1.0 # set as masked pixel + ... image = np.expand_dims(image, 0).transpose(0, 3, 1, 2) + ... image = torch.from_numpy(image) + ... return image + + + >>> control_image = make_inpaint_condition(init_image, mask_image) + + >>> controlnet = ControlNetModel.from_pretrained( + ... "lllyasviel/control_v11p_sd15_inpaint", torch_dtype=torch.float16 + ... ) + >>> pipe = StableDiffusionControlNetInpaintPipeline.from_pretrained( + ... "runwayml/stable-diffusion-v1-5", controlnet=controlnet, torch_dtype=torch.float16 + ... ) + + >>> pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config) + >>> pipe.enable_model_cpu_offload() + + >>> # generate image + >>> image = pipe( + ... "a handsome man with ray-ban sunglasses", + ... num_inference_steps=20, + ... generator=generator, + ... eta=1.0, + ... image=init_image, + ... mask_image=mask_image, + ... control_image=control_image, + ... ).images[0] + ``` +""" + + +# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_inpaint.prepare_mask_and_masked_image +def prepare_mask_and_masked_image(image, mask, height, width, return_image=False): + """ + Prepares a pair (image, mask) to be consumed by the Stable Diffusion pipeline. This means that those inputs will be + converted to ``torch.Tensor`` with shapes ``batch x channels x height x width`` where ``channels`` is ``3`` for the + ``image`` and ``1`` for the ``mask``. + + The ``image`` will be converted to ``torch.float32`` and normalized to be in ``[-1, 1]``. The ``mask`` will be + binarized (``mask > 0.5``) and cast to ``torch.float32`` too. + + Args: + image (Union[np.array, PIL.Image, torch.Tensor]): The image to inpaint. + It can be a ``PIL.Image``, or a ``height x width x 3`` ``np.array`` or a ``channels x height x width`` + ``torch.Tensor`` or a ``batch x channels x height x width`` ``torch.Tensor``. + mask (_type_): The mask to apply to the image, i.e. regions to inpaint. + It can be a ``PIL.Image``, or a ``height x width`` ``np.array`` or a ``1 x height x width`` + ``torch.Tensor`` or a ``batch x 1 x height x width`` ``torch.Tensor``. + + + Raises: + ValueError: ``torch.Tensor`` images should be in the ``[-1, 1]`` range. ValueError: ``torch.Tensor`` mask + should be in the ``[0, 1]`` range. ValueError: ``mask`` and ``image`` should have the same spatial dimensions. + TypeError: ``mask`` is a ``torch.Tensor`` but ``image`` is not + (ot the other way around). + + Returns: + tuple[torch.Tensor]: The pair (mask, masked_image) as ``torch.Tensor`` with 4 + dimensions: ``batch x channels x height x width``. + """ + + if image is None: + raise ValueError("`image` input cannot be undefined.") + + if mask is None: + raise ValueError("`mask_image` input cannot be undefined.") + + if isinstance(image, torch.Tensor): + if not isinstance(mask, torch.Tensor): + raise TypeError(f"`image` is a torch.Tensor but `mask` (type: {type(mask)} is not") + + # Batch single image + if image.ndim == 3: + assert image.shape[0] == 3, "Image outside a batch should be of shape (3, H, W)" + image = image.unsqueeze(0) + + # Batch and add channel dim for single mask + if mask.ndim == 2: + mask = mask.unsqueeze(0).unsqueeze(0) + + # Batch single mask or add channel dim + if mask.ndim == 3: + # Single batched mask, no channel dim or single mask not batched but channel dim + if mask.shape[0] == 1: + mask = mask.unsqueeze(0) + + # Batched masks no channel dim + else: + mask = mask.unsqueeze(1) + + assert image.ndim == 4 and mask.ndim == 4, "Image and Mask must have 4 dimensions" + assert image.shape[-2:] == mask.shape[-2:], "Image and Mask must have the same spatial dimensions" + assert image.shape[0] == mask.shape[0], "Image and Mask must have the same batch size" + + # Check image is in [-1, 1] + if image.min() < -1 or image.max() > 1: + raise ValueError("Image should be in [-1, 1] range") + + # Check mask is in [0, 1] + if mask.min() < 0 or mask.max() > 1: + raise ValueError("Mask should be in [0, 1] range") + + # Binarize mask + mask[mask < 0.5] = 0 + mask[mask >= 0.5] = 1 + + # Image as float32 + image = image.to(dtype=torch.float32) + elif isinstance(mask, torch.Tensor): + raise TypeError(f"`mask` is a torch.Tensor but `image` (type: {type(image)} is not") + else: + # preprocess image + if isinstance(image, (PIL.Image.Image, np.ndarray)): + image = [image] + if isinstance(image, list) and isinstance(image[0], PIL.Image.Image): + # resize all images w.r.t passed height an width + image = [i.resize((width, height), resample=PIL.Image.LANCZOS) for i in image] + image = [np.array(i.convert("RGB"))[None, :] for i in image] + image = np.concatenate(image, axis=0) + elif isinstance(image, list) and isinstance(image[0], np.ndarray): + image = np.concatenate([i[None, :] for i in image], axis=0) + + image = image.transpose(0, 3, 1, 2) + image = torch.from_numpy(image).to(dtype=torch.float32) / 127.5 - 1.0 + + # preprocess mask + if isinstance(mask, (PIL.Image.Image, np.ndarray)): + mask = [mask] + + if isinstance(mask, list) and isinstance(mask[0], PIL.Image.Image): + mask = [i.resize((width, height), resample=PIL.Image.LANCZOS) for i in mask] + mask = np.concatenate([np.array(m.convert("L"))[None, None, :] for m in mask], axis=0) + mask = mask.astype(np.float32) / 255.0 + elif isinstance(mask, list) and isinstance(mask[0], np.ndarray): + mask = np.concatenate([m[None, None, :] for m in mask], axis=0) + + mask[mask < 0.5] = 0 + mask[mask >= 0.5] = 1 + mask = torch.from_numpy(mask) + + masked_image = image * (mask < 0.5) + + # n.b. ensure backwards compatibility as old function does not return image + if return_image: + return mask, masked_image, image + + return mask, masked_image + + +class StableDiffusionControlNetInpaintPipeline( + DiffusionPipeline, TextualInversionLoaderMixin, LoraLoaderMixin, FromSingleFileMixin +): + r""" + Pipeline for text-to-image generation using Stable Diffusion with ControlNet guidance. + + This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the + library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.) + + In addition the pipeline inherits the following loading methods: + - *Textual-Inversion*: [`loaders.TextualInversionLoaderMixin.load_textual_inversion`] + + + + This pipeline can be used both with checkpoints that have been specifically fine-tuned for inpainting, such as + [runwayml/stable-diffusion-inpainting](https://huggingface.co/runwayml/stable-diffusion-inpainting) + as well as default text-to-image stable diffusion checkpoints, such as + [runwayml/stable-diffusion-v1-5](https://huggingface.co/runwayml/stable-diffusion-v1-5). + Default text-to-image stable diffusion checkpoints might be preferable for controlnets that have been fine-tuned on + those, such as [lllyasviel/control_v11p_sd15_inpaint](https://huggingface.co/lllyasviel/control_v11p_sd15_inpaint). + + + + Args: + vae ([`AutoencoderKL`]): + Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations. + text_encoder ([`CLIPTextModel`]): + Frozen text-encoder. Stable Diffusion uses the text portion of + [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically + the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant. + tokenizer (`CLIPTokenizer`): + Tokenizer of class + [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer). + unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents. + controlnet ([`ControlNetModel`] or `List[ControlNetModel]`): + Provides additional conditioning to the unet during the denoising process. If you set multiple ControlNets + as a list, the outputs from each ControlNet are added together to create one combined additional + conditioning. + scheduler ([`SchedulerMixin`]): + A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of + [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`]. + safety_checker ([`StableDiffusionSafetyChecker`]): + Classification module that estimates whether generated images could be considered offensive or harmful. + Please, refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for details. + feature_extractor ([`CLIPImageProcessor`]): + Model that extracts features from generated images to be used as inputs for the `safety_checker`. + """ + _optional_components = ["safety_checker", "feature_extractor"] + + def __init__( + self, + vae: AutoencoderKL, + text_encoder: CLIPTextModel, + tokenizer: CLIPTokenizer, + unet: UNet2DConditionModel, + controlnet: Union[ControlNetModel, List[ControlNetModel], Tuple[ControlNetModel], MultiControlNetModel], + scheduler: KarrasDiffusionSchedulers, + safety_checker: StableDiffusionSafetyChecker, + feature_extractor: CLIPImageProcessor, + requires_safety_checker: bool = True, + ): + super().__init__() + + if safety_checker is None and requires_safety_checker: + logger.warning( + f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure" + " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered" + " results in services or applications open to the public. Both the diffusers team and Hugging Face" + " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling" + " it only for use-cases that involve analyzing network behavior or auditing its results. For more" + " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ." + ) + + if safety_checker is not None and feature_extractor is None: + raise ValueError( + "Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety" + " checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead." + ) + + if isinstance(controlnet, (list, tuple)): + controlnet = MultiControlNetModel(controlnet) + + self.register_modules( + vae=vae, + text_encoder=text_encoder, + tokenizer=tokenizer, + unet=unet, + controlnet=controlnet, + scheduler=scheduler, + safety_checker=safety_checker, + feature_extractor=feature_extractor, + ) + self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1) + self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor) + self.control_image_processor = VaeImageProcessor( + vae_scale_factor=self.vae_scale_factor, do_convert_rgb=True, do_normalize=False + ) + self.register_to_config(requires_safety_checker=requires_safety_checker) + + # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.enable_vae_slicing + def enable_vae_slicing(self): + r""" + Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to + compute decoding in several steps. This is useful to save some memory and allow larger batch sizes. + """ + self.vae.enable_slicing() + + # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.disable_vae_slicing + def disable_vae_slicing(self): + r""" + Disable sliced VAE decoding. If `enable_vae_slicing` was previously enabled, this method will go back to + computing decoding in one step. + """ + self.vae.disable_slicing() + + # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.enable_vae_tiling + def enable_vae_tiling(self): + r""" + Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to + compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow + processing larger images. + """ + self.vae.enable_tiling() + + # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.disable_vae_tiling + def disable_vae_tiling(self): + r""" + Disable tiled VAE decoding. If `enable_vae_tiling` was previously enabled, this method will go back to + computing decoding in one step. + """ + self.vae.disable_tiling() + + def enable_model_cpu_offload(self, gpu_id=0): + r""" + Offloads all models to CPU using accelerate, reducing memory usage with a low impact on performance. Compared + to `enable_sequential_cpu_offload`, this method moves one whole model at a time to the GPU when its `forward` + method is called, and the model remains in GPU until the next model runs. Memory savings are lower than with + `enable_sequential_cpu_offload`, but performance is much better due to the iterative execution of the `unet`. + """ + if is_accelerate_available() and is_accelerate_version(">=", "0.17.0.dev0"): + from accelerate import cpu_offload_with_hook + else: + raise ImportError("`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.") + + device = torch.device(f"cuda:{gpu_id}") + + hook = None + for cpu_offloaded_model in [self.text_encoder, self.unet, self.vae]: + _, hook = cpu_offload_with_hook(cpu_offloaded_model, device, prev_module_hook=hook) + + if self.safety_checker is not None: + # the safety checker can offload the vae again + _, hook = cpu_offload_with_hook(self.safety_checker, device, prev_module_hook=hook) + + # control net hook has be manually offloaded as it alternates with unet + cpu_offload_with_hook(self.controlnet, device) + + # We'll offload the last model manually. + self.final_offload_hook = hook + + # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._encode_prompt + def _encode_prompt( + self, + promptA, + promptB, + t, + device, + num_images_per_prompt, + do_classifier_free_guidance, + negative_promptA=None, + negative_promptB=None, + t_nag = None, + prompt_embeds: Optional[torch.FloatTensor] = None, + negative_prompt_embeds: Optional[torch.FloatTensor] = None, + lora_scale: Optional[float] = None, + ): + r""" + Encodes the prompt into text encoder hidden states. + + Args: + prompt (`str` or `List[str]`, *optional*): + prompt to be encoded + device: (`torch.device`): + torch device + num_images_per_prompt (`int`): + number of images that should be generated per prompt + do_classifier_free_guidance (`bool`): + whether to use classifier free guidance or not + negative_prompt (`str` or `List[str]`, *optional*): + The prompt or prompts not to guide the image generation. If not defined, one has to pass + `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is + less than `1`). + prompt_embeds (`torch.FloatTensor`, *optional*): + Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not + provided, text embeddings will be generated from `prompt` input argument. + negative_prompt_embeds (`torch.FloatTensor`, *optional*): + Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt + weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input + argument. + lora_scale (`float`, *optional*): + A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded. + """ + # set lora scale so that monkey patched LoRA + # function of text encoder can correctly access it + if lora_scale is not None and isinstance(self, LoraLoaderMixin): + self._lora_scale = lora_scale + + prompt = promptA + negative_prompt = negative_promptA + + if promptA is not None and isinstance(promptA, str): + batch_size = 1 + elif promptA is not None and isinstance(promptA, list): + batch_size = len(promptA) + else: + batch_size = prompt_embeds.shape[0] + + if prompt_embeds is None: + # textual inversion: procecss multi-vector tokens if necessary + if isinstance(self, TextualInversionLoaderMixin): + promptA = self.maybe_convert_prompt(promptA, self.tokenizer) + + text_inputsA = self.tokenizer( + promptA, + padding="max_length", + max_length=self.tokenizer.model_max_length, + truncation=True, + return_tensors="pt", + ) + text_inputsB = self.tokenizer( + promptB, + padding="max_length", + max_length=self.tokenizer.model_max_length, + truncation=True, + return_tensors="pt", + ) + text_input_idsA = text_inputsA.input_ids + text_input_idsB = text_inputsB.input_ids + untruncated_ids = self.tokenizer(promptA, padding="longest", return_tensors="pt").input_ids + + if untruncated_ids.shape[-1] >= text_input_idsA.shape[-1] and not torch.equal( + text_input_idsA, untruncated_ids + ): + removed_text = self.tokenizer.batch_decode( + untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1] + ) + logger.warning( + "The following part of your input was truncated because CLIP can only handle sequences up to" + f" {self.tokenizer.model_max_length} tokens: {removed_text}" + ) + + if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask: + attention_mask = text_inputsA.attention_mask.to(device) + else: + attention_mask = None + + # print("text_input_idsA: ",text_input_idsA) + # print("text_input_idsB: ",text_input_idsB) + # print('t: ',t) + + prompt_embedsA = self.text_encoder( + text_input_idsA.to(device), + attention_mask=attention_mask, + ) + prompt_embedsA = prompt_embedsA[0] + + prompt_embedsB = self.text_encoder( + text_input_idsB.to(device), + attention_mask=attention_mask, + ) + prompt_embedsB = prompt_embedsB[0] + prompt_embeds = prompt_embedsA*(t)+(1-t)*prompt_embedsB + # print("prompt_embeds: ",prompt_embeds) + + if self.text_encoder is not None: + prompt_embeds_dtype = self.text_encoder.dtype + elif self.unet is not None: + prompt_embeds_dtype = self.unet.dtype + else: + prompt_embeds_dtype = prompt_embeds.dtype + + prompt_embeds = prompt_embeds.to(dtype=prompt_embeds_dtype, device=device) + + bs_embed, seq_len, _ = prompt_embeds.shape + # duplicate text embeddings for each generation per prompt, using mps friendly method + prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1) + prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1) + + # get unconditional embeddings for classifier free guidance + if do_classifier_free_guidance and negative_prompt_embeds is None: + uncond_tokensA: List[str] + uncond_tokensB: List[str] + if negative_prompt is None: + uncond_tokensA = [""] * batch_size + uncond_tokensB = [""] * batch_size + elif prompt is not None and type(prompt) is not type(negative_prompt): + raise TypeError( + f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !=" + f" {type(prompt)}." + ) + elif isinstance(negative_prompt, str): + uncond_tokensA = [negative_promptA] + uncond_tokensB = [negative_promptB] + elif batch_size != len(negative_prompt): + raise ValueError( + f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:" + f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches" + " the batch size of `prompt`." + ) + else: + uncond_tokensA = negative_promptA + uncond_tokensB = negative_promptB + + # textual inversion: procecss multi-vector tokens if necessary + if isinstance(self, TextualInversionLoaderMixin): + uncond_tokensA = self.maybe_convert_prompt(uncond_tokensA, self.tokenizer) + uncond_tokensB = self.maybe_convert_prompt(uncond_tokensB, self.tokenizer) + + max_length = prompt_embeds.shape[1] + uncond_inputA = self.tokenizer( + uncond_tokensA, + padding="max_length", + max_length=max_length, + truncation=True, + return_tensors="pt", + ) + uncond_inputB = self.tokenizer( + uncond_tokensB, + padding="max_length", + max_length=max_length, + truncation=True, + return_tensors="pt", + ) + + if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask: + attention_mask = uncond_inputA.attention_mask.to(device) + else: + attention_mask = None + + negative_prompt_embedsA = self.text_encoder( + uncond_inputA.input_ids.to(device), + attention_mask=attention_mask, + ) + negative_prompt_embedsB = self.text_encoder( + uncond_inputB.input_ids.to(device), + attention_mask=attention_mask, + ) + negative_prompt_embeds = negative_prompt_embedsA[0]*(t_nag)+(1-t_nag)*negative_prompt_embedsB[0] + + # negative_prompt_embeds = negative_prompt_embeds[0] + + if do_classifier_free_guidance: + # duplicate unconditional embeddings for each generation per prompt, using mps friendly method + seq_len = negative_prompt_embeds.shape[1] + + negative_prompt_embeds = negative_prompt_embeds.to(dtype=prompt_embeds_dtype, device=device) + + negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1) + negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1) + + # For classifier free guidance, we need to do two forward passes. + # Here we concatenate the unconditional and text embeddings into a single batch + # to avoid doing two forward passes + # print("prompt_embeds: ",prompt_embeds) + prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds]) + + return prompt_embeds + + # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.run_safety_checker + def run_safety_checker(self, image, device, dtype): + if self.safety_checker is None: + has_nsfw_concept = None + else: + if torch.is_tensor(image): + feature_extractor_input = self.image_processor.postprocess(image, output_type="pil") + else: + feature_extractor_input = self.image_processor.numpy_to_pil(image) + safety_checker_input = self.feature_extractor(feature_extractor_input, return_tensors="pt").to(device) + image, has_nsfw_concept = self.safety_checker( + images=image, clip_input=safety_checker_input.pixel_values.to(dtype) + ) + return image, has_nsfw_concept + + # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.decode_latents + def decode_latents(self, latents): + warnings.warn( + "The decode_latents method is deprecated and will be removed in a future version. Please" + " use VaeImageProcessor instead", + FutureWarning, + ) + latents = 1 / self.vae.config.scaling_factor * latents + image = self.vae.decode(latents, return_dict=False)[0] + image = (image / 2 + 0.5).clamp(0, 1) + # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16 + image = image.cpu().permute(0, 2, 3, 1).float().numpy() + return image + + # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs + def prepare_extra_step_kwargs(self, generator, eta): + # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature + # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. + # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 + # and should be between [0, 1] + + accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys()) + extra_step_kwargs = {} + if accepts_eta: + extra_step_kwargs["eta"] = eta + + # check if the scheduler accepts generator + accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys()) + if accepts_generator: + extra_step_kwargs["generator"] = generator + return extra_step_kwargs + + # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.StableDiffusionImg2ImgPipeline.get_timesteps + def get_timesteps(self, num_inference_steps, strength, device): + # get the original timestep using init_timestep + init_timestep = min(int(num_inference_steps * strength), num_inference_steps) + + t_start = max(num_inference_steps - init_timestep, 0) + timesteps = self.scheduler.timesteps[t_start * self.scheduler.order :] + + return timesteps, num_inference_steps - t_start + + def check_inputs( + self, + prompt, + image, + height, + width, + callback_steps, + negative_prompt=None, + prompt_embeds=None, + negative_prompt_embeds=None, + controlnet_conditioning_scale=1.0, + control_guidance_start=0.0, + control_guidance_end=1.0, + ): + if height % 8 != 0 or width % 8 != 0: + raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.") + + if (callback_steps is None) or ( + callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0) + ): + raise ValueError( + f"`callback_steps` has to be a positive integer but is {callback_steps} of type" + f" {type(callback_steps)}." + ) + + if prompt is not None and prompt_embeds is not None: + raise ValueError( + f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to" + " only forward one of the two." + ) + elif prompt is None and prompt_embeds is None: + raise ValueError( + "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined." + ) + elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)): + raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}") + + if negative_prompt is not None and negative_prompt_embeds is not None: + raise ValueError( + f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:" + f" {negative_prompt_embeds}. Please make sure to only forward one of the two." + ) + + if prompt_embeds is not None and negative_prompt_embeds is not None: + if prompt_embeds.shape != negative_prompt_embeds.shape: + raise ValueError( + "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but" + f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`" + f" {negative_prompt_embeds.shape}." + ) + + # `prompt` needs more sophisticated handling when there are multiple + # conditionings. + if isinstance(self.controlnet, MultiControlNetModel): + if isinstance(prompt, list): + logger.warning( + f"You have {len(self.controlnet.nets)} ControlNets and you have passed {len(prompt)}" + " prompts. The conditionings will be fixed across the prompts." + ) + + # Check `image` + is_compiled = hasattr(F, "scaled_dot_product_attention") and isinstance( + self.controlnet, torch._dynamo.eval_frame.OptimizedModule + ) + + if ( + isinstance(self.controlnet, ControlNetModel) + or is_compiled + and isinstance(self.controlnet._orig_mod, ControlNetModel) + ): + self.check_image(image, prompt, prompt_embeds) + elif ( + isinstance(self.controlnet, MultiControlNetModel) + or is_compiled + and isinstance(self.controlnet._orig_mod, MultiControlNetModel) + ): + if not isinstance(image, list): + raise TypeError("For multiple controlnets: `image` must be type `list`") + + # When `image` is a nested list: + # (e.g. [[canny_image_1, pose_image_1], [canny_image_2, pose_image_2]]) + elif any(isinstance(i, list) for i in image): + raise ValueError("A single batch of multiple conditionings are supported at the moment.") + elif len(image) != len(self.controlnet.nets): + raise ValueError( + f"For multiple controlnets: `image` must have the same length as the number of controlnets, but got {len(image)} images and {len(self.controlnet.nets)} ControlNets." + ) + + for image_ in image: + self.check_image(image_, prompt, prompt_embeds) + else: + assert False + + # Check `controlnet_conditioning_scale` + if ( + isinstance(self.controlnet, ControlNetModel) + or is_compiled + and isinstance(self.controlnet._orig_mod, ControlNetModel) + ): + if not isinstance(controlnet_conditioning_scale, float): + raise TypeError("For single controlnet: `controlnet_conditioning_scale` must be type `float`.") + elif ( + isinstance(self.controlnet, MultiControlNetModel) + or is_compiled + and isinstance(self.controlnet._orig_mod, MultiControlNetModel) + ): + if isinstance(controlnet_conditioning_scale, list): + if any(isinstance(i, list) for i in controlnet_conditioning_scale): + raise ValueError("A single batch of multiple conditionings are supported at the moment.") + elif isinstance(controlnet_conditioning_scale, list) and len(controlnet_conditioning_scale) != len( + self.controlnet.nets + ): + raise ValueError( + "For multiple controlnets: When `controlnet_conditioning_scale` is specified as `list`, it must have" + " the same length as the number of controlnets" + ) + else: + assert False + + if len(control_guidance_start) != len(control_guidance_end): + raise ValueError( + f"`control_guidance_start` has {len(control_guidance_start)} elements, but `control_guidance_end` has {len(control_guidance_end)} elements. Make sure to provide the same number of elements to each list." + ) + + if isinstance(self.controlnet, MultiControlNetModel): + if len(control_guidance_start) != len(self.controlnet.nets): + raise ValueError( + f"`control_guidance_start`: {control_guidance_start} has {len(control_guidance_start)} elements but there are {len(self.controlnet.nets)} controlnets available. Make sure to provide {len(self.controlnet.nets)}." + ) + + for start, end in zip(control_guidance_start, control_guidance_end): + if start >= end: + raise ValueError( + f"control guidance start: {start} cannot be larger or equal to control guidance end: {end}." + ) + if start < 0.0: + raise ValueError(f"control guidance start: {start} can't be smaller than 0.") + if end > 1.0: + raise ValueError(f"control guidance end: {end} can't be larger than 1.0.") + + # Copied from diffusers.pipelines.controlnet.pipeline_controlnet.StableDiffusionControlNetPipeline.check_image + def check_image(self, image, prompt, prompt_embeds): + image_is_pil = isinstance(image, PIL.Image.Image) + image_is_tensor = isinstance(image, torch.Tensor) + image_is_np = isinstance(image, np.ndarray) + image_is_pil_list = isinstance(image, list) and isinstance(image[0], PIL.Image.Image) + image_is_tensor_list = isinstance(image, list) and isinstance(image[0], torch.Tensor) + image_is_np_list = isinstance(image, list) and isinstance(image[0], np.ndarray) + + if ( + not image_is_pil + and not image_is_tensor + and not image_is_np + and not image_is_pil_list + and not image_is_tensor_list + and not image_is_np_list + ): + raise TypeError( + f"image must be passed and be one of PIL image, numpy array, torch tensor, list of PIL images, list of numpy arrays or list of torch tensors, but is {type(image)}" + ) + + if image_is_pil: + image_batch_size = 1 + else: + image_batch_size = len(image) + + if prompt is not None and isinstance(prompt, str): + prompt_batch_size = 1 + elif prompt is not None and isinstance(prompt, list): + prompt_batch_size = len(prompt) + elif prompt_embeds is not None: + prompt_batch_size = prompt_embeds.shape[0] + + if image_batch_size != 1 and image_batch_size != prompt_batch_size: + raise ValueError( + f"If image batch size is not 1, image batch size must be same as prompt batch size. image batch size: {image_batch_size}, prompt batch size: {prompt_batch_size}" + ) + + # Copied from diffusers.pipelines.controlnet.pipeline_controlnet.StableDiffusionControlNetPipeline.prepare_image + def prepare_control_image( + self, + image, + width, + height, + batch_size, + num_images_per_prompt, + device, + dtype, + do_classifier_free_guidance=False, + guess_mode=False, + ): + image = self.control_image_processor.preprocess(image, height=height, width=width).to(dtype=torch.float32) + image_batch_size = image.shape[0] + + if image_batch_size == 1: + repeat_by = batch_size + else: + # image batch size is the same as prompt batch size + repeat_by = num_images_per_prompt + + image = image.repeat_interleave(repeat_by, dim=0) + + image = image.to(device=device, dtype=dtype) + + if do_classifier_free_guidance and not guess_mode: + image = torch.cat([image] * 2) + + return image + + # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_inpaint.StableDiffusionInpaintPipeline.prepare_latents + def prepare_latents( + self, + batch_size, + num_channels_latents, + height, + width, + dtype, + device, + generator, + latents=None, + image=None, + timestep=None, + is_strength_max=True, + return_noise=False, + return_image_latents=False, + ): + shape = (batch_size, num_channels_latents, height // self.vae_scale_factor, width // self.vae_scale_factor) + if isinstance(generator, list) and len(generator) != batch_size: + raise ValueError( + f"You have passed a list of generators of length {len(generator)}, but requested an effective batch" + f" size of {batch_size}. Make sure the batch size matches the length of the generators." + ) + + if (image is None or timestep is None) and not is_strength_max: + raise ValueError( + "Since strength < 1. initial latents are to be initialised as a combination of Image + Noise." + "However, either the image or the noise timestep has not been provided." + ) + + if return_image_latents or (latents is None and not is_strength_max): + image = image.to(device=device, dtype=dtype) + image_latents = self._encode_vae_image(image=image, generator=generator) + + if latents is None: + noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype) + # if strength is 1. then initialise the latents to noise, else initial to image + noise + latents = noise if is_strength_max else self.scheduler.add_noise(image_latents, noise, timestep) + # if pure noise then scale the initial latents by the Scheduler's init sigma + latents = latents * self.scheduler.init_noise_sigma if is_strength_max else latents + else: + noise = latents.to(device) + latents = noise * self.scheduler.init_noise_sigma + + outputs = (latents,) + + if return_noise: + outputs += (noise,) + + if return_image_latents: + outputs += (image_latents,) + + return outputs + + def _default_height_width(self, height, width, image): + # NOTE: It is possible that a list of images have different + # dimensions for each image, so just checking the first image + # is not _exactly_ correct, but it is simple. + while isinstance(image, list): + image = image[0] + + if height is None: + if isinstance(image, PIL.Image.Image): + height = image.height + elif isinstance(image, torch.Tensor): + height = image.shape[2] + + height = (height // 8) * 8 # round down to nearest multiple of 8 + + if width is None: + if isinstance(image, PIL.Image.Image): + width = image.width + elif isinstance(image, torch.Tensor): + width = image.shape[3] + + width = (width // 8) * 8 # round down to nearest multiple of 8 + + return height, width + + # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_inpaint.StableDiffusionInpaintPipeline.prepare_mask_latents + def prepare_mask_latents( + self, mask, masked_image, batch_size, height, width, dtype, device, generator, do_classifier_free_guidance + ): + # resize the mask to latents shape as we concatenate the mask to the latents + # we do that before converting to dtype to avoid breaking in case we're using cpu_offload + # and half precision + mask = torch.nn.functional.interpolate( + mask, size=(height // self.vae_scale_factor, width // self.vae_scale_factor) + ) + mask = mask.to(device=device, dtype=dtype) + + masked_image = masked_image.to(device=device, dtype=dtype) + masked_image_latents = self._encode_vae_image(masked_image, generator=generator) + + # duplicate mask and masked_image_latents for each generation per prompt, using mps friendly method + if mask.shape[0] < batch_size: + if not batch_size % mask.shape[0] == 0: + raise ValueError( + "The passed mask and the required batch size don't match. Masks are supposed to be duplicated to" + f" a total batch size of {batch_size}, but {mask.shape[0]} masks were passed. Make sure the number" + " of masks that you pass is divisible by the total requested batch size." + ) + mask = mask.repeat(batch_size // mask.shape[0], 1, 1, 1) + if masked_image_latents.shape[0] < batch_size: + if not batch_size % masked_image_latents.shape[0] == 0: + raise ValueError( + "The passed images and the required batch size don't match. Images are supposed to be duplicated" + f" to a total batch size of {batch_size}, but {masked_image_latents.shape[0]} images were passed." + " Make sure the number of images that you pass is divisible by the total requested batch size." + ) + masked_image_latents = masked_image_latents.repeat(batch_size // masked_image_latents.shape[0], 1, 1, 1) + + mask = torch.cat([mask] * 2) if do_classifier_free_guidance else mask + masked_image_latents = ( + torch.cat([masked_image_latents] * 2) if do_classifier_free_guidance else masked_image_latents + ) + + # aligning device to prevent device errors when concating it with the latent model input + masked_image_latents = masked_image_latents.to(device=device, dtype=dtype) + return mask, masked_image_latents + + # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_inpaint.StableDiffusionInpaintPipeline._encode_vae_image + def _encode_vae_image(self, image: torch.Tensor, generator: torch.Generator): + if isinstance(generator, list): + image_latents = [ + self.vae.encode(image[i : i + 1]).latent_dist.sample(generator=generator[i]) + for i in range(image.shape[0]) + ] + image_latents = torch.cat(image_latents, dim=0) + else: + image_latents = self.vae.encode(image).latent_dist.sample(generator=generator) + + image_latents = self.vae.config.scaling_factor * image_latents + + return image_latents + + @torch.no_grad() + def predict_woControl( + self, + promptA: Union[str, List[str]] = None, + promptB: Union[str, List[str]] = None, + image: Union[torch.FloatTensor, PIL.Image.Image] = None, + mask_image: Union[torch.FloatTensor, PIL.Image.Image] = None, + height: Optional[int] = None, + width: Optional[int] = None, + strength: float = 1.0, + tradoff: float = 1.0, + tradoff_nag: float = 1.0, + num_inference_steps: int = 50, + guidance_scale: float = 7.5, + negative_promptA: Optional[Union[str, List[str]]] = None, + negative_promptB: Optional[Union[str, List[str]]] = None, + num_images_per_prompt: Optional[int] = 1, + eta: float = 0.0, + generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None, + latents: Optional[torch.FloatTensor] = None, + prompt_embeds: Optional[torch.FloatTensor] = None, + negative_prompt_embeds: Optional[torch.FloatTensor] = None, + output_type: Optional[str] = "pil", + return_dict: bool = True, + callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None, + callback_steps: int = 1, + cross_attention_kwargs: Optional[Dict[str, Any]] = None, + task_class: Union[torch.Tensor, float, int] = None, + ): + r""" + The call function to the pipeline for generation. + + Args: + prompt (`str` or `List[str]`, *optional*): + The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`. + image (`PIL.Image.Image`): + `Image` or tensor representing an image batch to be inpainted (which parts of the image to be masked + out with `mask_image` and repainted according to `prompt`). + mask_image (`PIL.Image.Image`): + `Image` or tensor representing an image batch to mask `image`. White pixels in the mask are repainted + while black pixels are preserved. If `mask_image` is a PIL image, it is converted to a single channel + (luminance) before use. If it's a tensor, it should contain one color channel (L) instead of 3, so the + expected shape would be `(B, H, W, 1)`. + height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`): + The height in pixels of the generated image. + width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`): + The width in pixels of the generated image. + strength (`float`, *optional*, defaults to 1.0): + Indicates extent to transform the reference `image`. Must be between 0 and 1. `image` is used as a + starting point and more noise is added the higher the `strength`. The number of denoising steps depends + on the amount of noise initially added. When `strength` is 1, added noise is maximum and the denoising + process runs for the full number of iterations specified in `num_inference_steps`. A value of 1 + essentially ignores `image`. + num_inference_steps (`int`, *optional*, defaults to 50): + The number of denoising steps. More denoising steps usually lead to a higher quality image at the + expense of slower inference. This parameter is modulated by `strength`. + guidance_scale (`float`, *optional*, defaults to 7.5): + A higher guidance scale value encourages the model to generate images closely linked to the text + `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`. + negative_prompt (`str` or `List[str]`, *optional*): + The prompt or prompts to guide what to not include in image generation. If not defined, you need to + pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`). + num_images_per_prompt (`int`, *optional*, defaults to 1): + The number of images to generate per prompt. + eta (`float`, *optional*, defaults to 0.0): + Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies + to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers. + generator (`torch.Generator` or `List[torch.Generator]`, *optional*): + A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make + generation deterministic. + latents (`torch.FloatTensor`, *optional*): + Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image + generation. Can be used to tweak the same generation with different prompts. If not provided, a latents + tensor is generated by sampling using the supplied random `generator`. + prompt_embeds (`torch.FloatTensor`, *optional*): + Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not + provided, text embeddings are generated from the `prompt` input argument. + negative_prompt_embeds (`torch.FloatTensor`, *optional*): + Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If + not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument. + output_type (`str`, *optional*, defaults to `"pil"`): + The output format of the generated image. Choose between `PIL.Image` or `np.array`. + return_dict (`bool`, *optional*, defaults to `True`): + Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a + plain tuple. + callback (`Callable`, *optional*): + A function that calls every `callback_steps` steps during inference. The function is called with the + following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`. + callback_steps (`int`, *optional*, defaults to 1): + The frequency at which the `callback` function is called. If not specified, the callback is called at + every step. + cross_attention_kwargs (`dict`, *optional*): + A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in + [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py). + + Examples: + + ```py + >>> import PIL + >>> import requests + >>> import torch + >>> from io import BytesIO + + >>> from diffusers import StableDiffusionInpaintPipeline + + + >>> def download_image(url): + ... response = requests.get(url) + ... return PIL.Image.open(BytesIO(response.content)).convert("RGB") + + + >>> img_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png" + >>> mask_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png" + + >>> init_image = download_image(img_url).resize((512, 512)) + >>> mask_image = download_image(mask_url).resize((512, 512)) + + >>> pipe = StableDiffusionInpaintPipeline.from_pretrained( + ... "runwayml/stable-diffusion-inpainting", torch_dtype=torch.float16 + ... ) + >>> pipe = pipe.to("cuda") + + >>> prompt = "Face of a yellow cat, high resolution, sitting on a park bench" + >>> image = pipe(prompt=prompt, image=init_image, mask_image=mask_image).images[0] + ``` + + Returns: + [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`: + If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned, + otherwise a `tuple` is returned where the first element is a list with the generated images and the + second element is a list of `bool`s indicating whether the corresponding generated image contains + "not-safe-for-work" (nsfw) content. + """ + # 0. Default height and width to unet + height = height or self.unet.config.sample_size * self.vae_scale_factor + width = width or self.unet.config.sample_size * self.vae_scale_factor + prompt = promptA + negative_prompt = negative_promptA + # 1. Check inputs + self.check_inputs( + prompt, + height, + width, + strength, + callback_steps, + negative_prompt, + prompt_embeds, + negative_prompt_embeds, + ) + + # 2. Define call parameters + if prompt is not None and isinstance(prompt, str): + batch_size = 1 + elif prompt is not None and isinstance(prompt, list): + batch_size = len(prompt) + else: + batch_size = prompt_embeds.shape[0] + + device = self._execution_device + # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) + # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` + # corresponds to doing no classifier free guidance. + do_classifier_free_guidance = guidance_scale > 1.0 + + # 3. Encode input prompt + text_encoder_lora_scale = ( + cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None + ) + prompt_embeds = self._encode_prompt( + promptA, + promptB, + tradoff, + device, + num_images_per_prompt, + do_classifier_free_guidance, + negative_promptA, + negative_promptB, + tradoff_nag, + prompt_embeds=prompt_embeds, + negative_prompt_embeds=negative_prompt_embeds, + lora_scale=text_encoder_lora_scale, + ) + + # 4. set timesteps + self.scheduler.set_timesteps(num_inference_steps, device=device) + timesteps, num_inference_steps = self.get_timesteps( + num_inference_steps=num_inference_steps, strength=strength, device=device + ) + # check that number of inference steps is not < 1 - as this doesn't make sense + if num_inference_steps < 1: + raise ValueError( + f"After adjusting the num_inference_steps by strength parameter: {strength}, the number of pipeline" + f"steps is {num_inference_steps} which is < 1 and not appropriate for this pipeline." + ) + # at which timestep to set the initial noise (n.b. 50% if strength is 0.5) + latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt) + # create a boolean to check if the strength is set to 1. if so then initialise the latents with pure noise + is_strength_max = strength == 1.0 + + # 5. Preprocess mask and image + mask, masked_image, init_image = prepare_mask_and_masked_image( + image, mask_image, height, width, return_image=True + ) + mask_condition = mask.clone() + + # 6. Prepare latent variables + num_channels_latents = self.vae.config.latent_channels + num_channels_unet = self.unet.config.in_channels + return_image_latents = num_channels_unet == 4 + + latents_outputs = self.prepare_latents( + batch_size * num_images_per_prompt, + num_channels_latents, + height, + width, + prompt_embeds.dtype, + device, + generator, + latents, + image=init_image, + timestep=latent_timestep, + is_strength_max=is_strength_max, + return_noise=True, + return_image_latents=return_image_latents, + ) + + if return_image_latents: + latents, noise, image_latents = latents_outputs + else: + latents, noise = latents_outputs + + # 7. Prepare mask latent variables + mask, masked_image_latents = self.prepare_mask_latents( + mask, + masked_image, + batch_size * num_images_per_prompt, + height, + width, + prompt_embeds.dtype, + device, + generator, + do_classifier_free_guidance, + ) + + # 8. Check that sizes of mask, masked image and latents match + if num_channels_unet == 9: + # default case for runwayml/stable-diffusion-inpainting + num_channels_mask = mask.shape[1] + num_channels_masked_image = masked_image_latents.shape[1] + if num_channels_latents + num_channels_mask + num_channels_masked_image != self.unet.config.in_channels: + raise ValueError( + f"Incorrect configuration settings! The config of `pipeline.unet`: {self.unet.config} expects" + f" {self.unet.config.in_channels} but received `num_channels_latents`: {num_channels_latents} +" + f" `num_channels_mask`: {num_channels_mask} + `num_channels_masked_image`: {num_channels_masked_image}" + f" = {num_channels_latents+num_channels_masked_image+num_channels_mask}. Please verify the config of" + " `pipeline.unet` or your `mask_image` or `image` input." + ) + elif num_channels_unet != 4: + raise ValueError( + f"The unet {self.unet.__class__} should have either 4 or 9 input channels, not {self.unet.config.in_channels}." + ) + + # 9. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline + extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta) + + # 10. Denoising loop + num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order + with self.progress_bar(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 + + # concat latents, mask, masked_image_latents in the channel dimension + latent_model_input = self.scheduler.scale_model_input(latent_model_input, t) + + if num_channels_unet == 9: + latent_model_input = torch.cat([latent_model_input, mask, masked_image_latents], dim=1) + + # predict the noise residual + if task_class is not None: + noise_pred = self.unet( + sample = latent_model_input, + timestep = t, + encoder_hidden_states=prompt_embeds, + cross_attention_kwargs=cross_attention_kwargs, + return_dict=False, + task_class = task_class, + )[0] + else: + noise_pred = self.unet( + latent_model_input, + t, + encoder_hidden_states=prompt_embeds, + cross_attention_kwargs=cross_attention_kwargs, + return_dict=False, + )[0] + + # perform guidance + if do_classifier_free_guidance: + noise_pred_uncond, noise_pred_text = noise_pred.chunk(2) + noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) + + # compute the previous noisy sample x_t -> x_t-1 + latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0] + + if num_channels_unet == 4: + init_latents_proper = image_latents[:1] + init_mask = mask[:1] + + if i < len(timesteps) - 1: + noise_timestep = timesteps[i + 1] + init_latents_proper = self.scheduler.add_noise( + init_latents_proper, noise, torch.tensor([noise_timestep]) + ) + + latents = (1 - init_mask) * init_latents_proper + init_mask * latents + + # call the callback, if provided + if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0): + progress_bar.update() + if callback is not None and i % callback_steps == 0: + callback(i, t, latents) + + if not output_type == "latent": + condition_kwargs = {} + if isinstance(self.vae, AsymmetricAutoencoderKL): + init_image = init_image.to(device=device, dtype=masked_image_latents.dtype) + init_image_condition = init_image.clone() + init_image = self._encode_vae_image(init_image, generator=generator) + mask_condition = mask_condition.to(device=device, dtype=masked_image_latents.dtype) + condition_kwargs = {"image": init_image_condition, "mask": mask_condition} + image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False, **condition_kwargs)[0] + image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype) + else: + image = latents + has_nsfw_concept = None + + if has_nsfw_concept is None: + do_denormalize = [True] * image.shape[0] + else: + do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept] + + image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize) + + # Offload last model to CPU + if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None: + self.final_offload_hook.offload() + + if not return_dict: + return (image, has_nsfw_concept) + + return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept) + + + @torch.no_grad() + @replace_example_docstring(EXAMPLE_DOC_STRING) + def __call__( + self, + promptA: Union[str, List[str]] = None, + promptB: Union[str, List[str]] = None, + image: Union[torch.Tensor, PIL.Image.Image] = None, + mask_image: Union[torch.Tensor, PIL.Image.Image] = None, + control_image: Union[ + torch.FloatTensor, + PIL.Image.Image, + np.ndarray, + List[torch.FloatTensor], + List[PIL.Image.Image], + List[np.ndarray], + ] = None, + height: Optional[int] = None, + width: Optional[int] = None, + strength: float = 1.0, + tradoff: float = 1.0, + tradoff_nag: float = 1.0, + num_inference_steps: int = 50, + guidance_scale: float = 7.5, + negative_promptA: Optional[Union[str, List[str]]] = None, + negative_promptB: Optional[Union[str, List[str]]] = None, + num_images_per_prompt: Optional[int] = 1, + eta: float = 0.0, + generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None, + latents: Optional[torch.FloatTensor] = None, + prompt_embeds: Optional[torch.FloatTensor] = None, + negative_prompt_embeds: Optional[torch.FloatTensor] = None, + output_type: Optional[str] = "pil", + return_dict: bool = True, + callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None, + callback_steps: int = 1, + cross_attention_kwargs: Optional[Dict[str, Any]] = None, + controlnet_conditioning_scale: Union[float, List[float]] = 0.5, + guess_mode: bool = False, + control_guidance_start: Union[float, List[float]] = 0.0, + control_guidance_end: Union[float, List[float]] = 1.0, + ): + r""" + Function invoked when calling the pipeline for generation. + + Args: + prompt (`str` or `List[str]`, *optional*): + The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`. + instead. + image (`torch.FloatTensor`, `PIL.Image.Image`, `List[torch.FloatTensor]`, `List[PIL.Image.Image]`, + `List[List[torch.FloatTensor]]`, or `List[List[PIL.Image.Image]]`): + The ControlNet input condition. ControlNet uses this input condition to generate guidance to Unet. If + the type is specified as `Torch.FloatTensor`, it is passed to ControlNet as is. `PIL.Image.Image` can + also be accepted as an image. The dimensions of the output image defaults to `image`'s dimensions. If + height and/or width are passed, `image` is resized according to them. If multiple ControlNets are + specified in init, images must be passed as a list such that each element of the list can be correctly + batched for input to a single controlnet. + height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor): + The height in pixels of the generated image. + width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor): + The width in pixels of the generated image. + strength (`float`, *optional*, defaults to 1.): + Conceptually, indicates how much to transform the masked portion of the reference `image`. Must be + between 0 and 1. `image` will be used as a starting point, adding more noise to it the larger the + `strength`. The number of denoising steps depends on the amount of noise initially added. When + `strength` is 1, added noise will be maximum and the denoising process will run for the full number of + iterations specified in `num_inference_steps`. A value of 1, therefore, essentially ignores the masked + portion of the reference `image`. + num_inference_steps (`int`, *optional*, defaults to 50): + The number of denoising steps. More denoising steps usually lead to a higher quality image at the + expense of slower inference. + guidance_scale (`float`, *optional*, defaults to 7.5): + Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598). + `guidance_scale` is defined as `w` of equation 2. of [Imagen + Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale > + 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`, + usually at the expense of lower image quality. + negative_prompt (`str` or `List[str]`, *optional*): + The prompt or prompts not to guide the image generation. If not defined, one has to pass + `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is + less than `1`). + num_images_per_prompt (`int`, *optional*, defaults to 1): + The number of images to generate per prompt. + eta (`float`, *optional*, defaults to 0.0): + Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to + [`schedulers.DDIMScheduler`], will be ignored for others. + generator (`torch.Generator` or `List[torch.Generator]`, *optional*): + One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html) + to make generation deterministic. + latents (`torch.FloatTensor`, *optional*): + Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image + generation. Can be used to tweak the same generation with different prompts. If not provided, a latents + tensor will ge generated by sampling using the supplied random `generator`. + prompt_embeds (`torch.FloatTensor`, *optional*): + Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not + provided, text embeddings will be generated from `prompt` input argument. + negative_prompt_embeds (`torch.FloatTensor`, *optional*): + Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt + weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input + argument. + output_type (`str`, *optional*, defaults to `"pil"`): + The output format of the generate image. Choose between + [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`. + return_dict (`bool`, *optional*, defaults to `True`): + Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a + plain tuple. + callback (`Callable`, *optional*): + A function that will be called every `callback_steps` steps during inference. The function will be + called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`. + callback_steps (`int`, *optional*, defaults to 1): + The frequency at which the `callback` function will be called. If not specified, the callback will be + called at every step. + cross_attention_kwargs (`dict`, *optional*): + A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under + `self.processor` in + [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py). + controlnet_conditioning_scale (`float` or `List[float]`, *optional*, defaults to 0.5): + The outputs of the controlnet are multiplied by `controlnet_conditioning_scale` before they are added + to the residual in the original unet. If multiple ControlNets are specified in init, you can set the + corresponding scale as a list. Note that by default, we use a smaller conditioning scale for inpainting + than for [`~StableDiffusionControlNetPipeline.__call__`]. + guess_mode (`bool`, *optional*, defaults to `False`): + In this mode, the ControlNet encoder will try best to recognize the content of the input image even if + you remove all prompts. The `guidance_scale` between 3.0 and 5.0 is recommended. + control_guidance_start (`float` or `List[float]`, *optional*, defaults to 0.0): + The percentage of total steps at which the controlnet starts applying. + control_guidance_end (`float` or `List[float]`, *optional*, defaults to 1.0): + The percentage of total steps at which the controlnet stops applying. + + Examples: + + Returns: + [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`: + [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple. + When returning a tuple, the first element is a list with the generated images, and the second element is a + list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work" + (nsfw) content, according to the `safety_checker`. + """ + controlnet = self.controlnet._orig_mod if is_compiled_module(self.controlnet) else self.controlnet + + # 0. Default height and width to unet + height, width = self._default_height_width(height, width, image) + + prompt = promptA + negative_prompt = negative_promptA + + # align format for control guidance + if not isinstance(control_guidance_start, list) and isinstance(control_guidance_end, list): + control_guidance_start = len(control_guidance_end) * [control_guidance_start] + elif not isinstance(control_guidance_end, list) and isinstance(control_guidance_start, list): + control_guidance_end = len(control_guidance_start) * [control_guidance_end] + elif not isinstance(control_guidance_start, list) and not isinstance(control_guidance_end, list): + mult = len(controlnet.nets) if isinstance(controlnet, MultiControlNetModel) else 1 + control_guidance_start, control_guidance_end = mult * [control_guidance_start], mult * [ + control_guidance_end + ] + + # 1. Check inputs. Raise error if not correct + self.check_inputs( + prompt, + control_image, + height, + width, + callback_steps, + negative_prompt, + prompt_embeds, + negative_prompt_embeds, + controlnet_conditioning_scale, + control_guidance_start, + control_guidance_end, + ) + + # 2. Define call parameters + if prompt is not None and isinstance(prompt, str): + batch_size = 1 + elif prompt is not None and isinstance(prompt, list): + batch_size = len(prompt) + else: + batch_size = prompt_embeds.shape[0] + + device = self._execution_device + # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) + # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` + # corresponds to doing no classifier free guidance. + do_classifier_free_guidance = guidance_scale > 1.0 + + if isinstance(controlnet, MultiControlNetModel) and isinstance(controlnet_conditioning_scale, float): + controlnet_conditioning_scale = [controlnet_conditioning_scale] * len(controlnet.nets) + + global_pool_conditions = ( + controlnet.config.global_pool_conditions + if isinstance(controlnet, ControlNetModel) + else controlnet.nets[0].config.global_pool_conditions + ) + guess_mode = guess_mode or global_pool_conditions + + # 3. Encode input prompt + text_encoder_lora_scale = ( + cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None + ) + prompt_embeds = self._encode_prompt( + promptA, + promptB, + tradoff, + device, + num_images_per_prompt, + do_classifier_free_guidance, + negative_promptA, + negative_promptB, + tradoff_nag, + prompt_embeds=prompt_embeds, + negative_prompt_embeds=negative_prompt_embeds, + lora_scale=text_encoder_lora_scale, + ) + + # 4. Prepare image + if isinstance(controlnet, ControlNetModel): + control_image = self.prepare_control_image( + image=control_image, + width=width, + height=height, + batch_size=batch_size * num_images_per_prompt, + num_images_per_prompt=num_images_per_prompt, + device=device, + dtype=controlnet.dtype, + do_classifier_free_guidance=do_classifier_free_guidance, + guess_mode=guess_mode, + ) + elif isinstance(controlnet, MultiControlNetModel): + control_images = [] + + for control_image_ in control_image: + control_image_ = self.prepare_control_image( + image=control_image_, + width=width, + height=height, + batch_size=batch_size * num_images_per_prompt, + num_images_per_prompt=num_images_per_prompt, + device=device, + dtype=controlnet.dtype, + do_classifier_free_guidance=do_classifier_free_guidance, + guess_mode=guess_mode, + ) + + control_images.append(control_image_) + + control_image = control_images + else: + assert False + + # 4. Preprocess mask and image - resizes image and mask w.r.t height and width + mask, masked_image, init_image = prepare_mask_and_masked_image( + image, mask_image, height, width, return_image=True + ) + + # 5. Prepare timesteps + self.scheduler.set_timesteps(num_inference_steps, device=device) + timesteps, num_inference_steps = self.get_timesteps( + num_inference_steps=num_inference_steps, strength=strength, device=device + ) + # at which timestep to set the initial noise (n.b. 50% if strength is 0.5) + latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt) + # create a boolean to check if the strength is set to 1. if so then initialise the latents with pure noise + is_strength_max = strength == 1.0 + + # 6. Prepare latent variables + num_channels_latents = self.vae.config.latent_channels + num_channels_unet = self.unet.config.in_channels + return_image_latents = num_channels_unet == 4 + latents_outputs = self.prepare_latents( + batch_size * num_images_per_prompt, + num_channels_latents, + height, + width, + prompt_embeds.dtype, + device, + generator, + latents, + image=init_image, + timestep=latent_timestep, + is_strength_max=is_strength_max, + return_noise=True, + return_image_latents=return_image_latents, + ) + + if return_image_latents: + latents, noise, image_latents = latents_outputs + else: + latents, noise = latents_outputs + + # 7. Prepare mask latent variables + mask, masked_image_latents = self.prepare_mask_latents( + mask, + masked_image, + batch_size * num_images_per_prompt, + height, + width, + prompt_embeds.dtype, + device, + generator, + do_classifier_free_guidance, + ) + + # 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline + extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta) + + # 7.1 Create tensor stating which controlnets to keep + controlnet_keep = [] + for i in range(len(timesteps)): + keeps = [ + 1.0 - float(i / len(timesteps) < s or (i + 1) / len(timesteps) > e) + for s, e in zip(control_guidance_start, control_guidance_end) + ] + controlnet_keep.append(keeps[0] if isinstance(controlnet, ControlNetModel) else keeps) + + # 8. Denoising loop + num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order + with self.progress_bar(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 = self.scheduler.scale_model_input(latent_model_input, t) + + # controlnet(s) inference + if guess_mode and do_classifier_free_guidance: + # Infer ControlNet only for the conditional batch. + control_model_input = latents + control_model_input = self.scheduler.scale_model_input(control_model_input, t) + controlnet_prompt_embeds = prompt_embeds.chunk(2)[1] + else: + control_model_input = latent_model_input + controlnet_prompt_embeds = prompt_embeds + + if isinstance(controlnet_keep[i], list): + cond_scale = [c * s for c, s in zip(controlnet_conditioning_scale, controlnet_keep[i])] + else: + controlnet_cond_scale = controlnet_conditioning_scale + if isinstance(controlnet_cond_scale, list): + controlnet_cond_scale = controlnet_cond_scale[0] + cond_scale = controlnet_cond_scale * controlnet_keep[i] + + down_block_res_samples, mid_block_res_sample = self.controlnet( + control_model_input, + t, + encoder_hidden_states=controlnet_prompt_embeds, + controlnet_cond=control_image, + conditioning_scale=cond_scale, + guess_mode=guess_mode, + return_dict=False, + ) + + if guess_mode and do_classifier_free_guidance: + # Infered ControlNet only for the conditional batch. + # To apply the output of ControlNet to both the unconditional and conditional batches, + # add 0 to the unconditional batch to keep it unchanged. + down_block_res_samples = [torch.cat([torch.zeros_like(d), d]) for d in down_block_res_samples] + mid_block_res_sample = torch.cat([torch.zeros_like(mid_block_res_sample), mid_block_res_sample]) + + # predict the noise residual + if num_channels_unet == 9: + latent_model_input = torch.cat([latent_model_input, mask, masked_image_latents], dim=1) + + noise_pred = self.unet( + latent_model_input, + t, + encoder_hidden_states=prompt_embeds, + cross_attention_kwargs=cross_attention_kwargs, + down_block_additional_residuals=down_block_res_samples, + mid_block_additional_residual=mid_block_res_sample, + return_dict=False, + )[0] + + # perform guidance + if do_classifier_free_guidance: + noise_pred_uncond, noise_pred_text = noise_pred.chunk(2) + noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) + + # compute the previous noisy sample x_t -> x_t-1 + latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0] + + if num_channels_unet == 4: + init_latents_proper = image_latents[:1] + init_mask = mask[:1] + + if i < len(timesteps) - 1: + noise_timestep = timesteps[i + 1] + init_latents_proper = self.scheduler.add_noise( + init_latents_proper, noise, torch.tensor([noise_timestep]) + ) + + latents = (1 - init_mask) * init_latents_proper + init_mask * latents + + # call the callback, if provided + if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0): + progress_bar.update() + if callback is not None and i % callback_steps == 0: + callback(i, t, latents) + + # If we do sequential model offloading, let's offload unet and controlnet + # manually for max memory savings + if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None: + self.unet.to("cpu") + self.controlnet.to("cpu") + torch.cuda.empty_cache() + + if not output_type == "latent": + image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0] + image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype) + else: + image = latents + has_nsfw_concept = None + + if has_nsfw_concept is None: + do_denormalize = [True] * image.shape[0] + else: + do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept] + + image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize) + + # Offload last model to CPU + if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None: + self.final_offload_hook.offload() + + if not return_dict: + return (image, has_nsfw_concept) + + return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept) diff --git a/py/iopaint/model/power_paint/power_paint.py b/py/iopaint/model/power_paint/power_paint.py new file mode 100644 index 0000000..eba6789 --- /dev/null +++ b/py/iopaint/model/power_paint/power_paint.py @@ -0,0 +1,101 @@ +from PIL import Image +import PIL.Image +import cv2 +import torch +from loguru import logger + +from ..base import DiffusionInpaintModel +from ..helper.cpu_text_encoder import CPUTextEncoderWrapper +from ..utils import ( + handle_from_pretrained_exceptions, + get_torch_dtype, + enable_low_mem, + is_local_files_only, +) +from ...schema import InpaintRequest +from .powerpaint_tokenizer import add_task_to_prompt +from ...const import POWERPAINT_NAME + + +class PowerPaint(DiffusionInpaintModel): + name = POWERPAINT_NAME + pad_mod = 8 + min_size = 512 + lcm_lora_id = "latent-consistency/lcm-lora-sdv1-5" + + def init_model(self, device: torch.device, **kwargs): + from .pipeline_powerpaint import StableDiffusionInpaintPipeline + from .powerpaint_tokenizer import PowerPaintTokenizer + + use_gpu, torch_dtype = get_torch_dtype(device, kwargs.get("no_half", False)) + model_kwargs = {"local_files_only": is_local_files_only(**kwargs)} + if kwargs["disable_nsfw"] or kwargs.get("cpu_offload", False): + logger.info("Disable Stable Diffusion Model NSFW checker") + model_kwargs.update( + dict( + safety_checker=None, + feature_extractor=None, + requires_safety_checker=False, + ) + ) + + self.model = handle_from_pretrained_exceptions( + StableDiffusionInpaintPipeline.from_pretrained, + pretrained_model_name_or_path=self.name, + variant="fp16", + torch_dtype=torch_dtype, + **model_kwargs, + ) + self.model.tokenizer = PowerPaintTokenizer(self.model.tokenizer) + + enable_low_mem(self.model, kwargs.get("low_mem", False)) + + if kwargs.get("cpu_offload", False) and use_gpu: + logger.info("Enable sequential cpu offload") + self.model.enable_sequential_cpu_offload(gpu_id=0) + else: + self.model = self.model.to(device) + if kwargs["sd_cpu_textencoder"]: + logger.info("Run Stable Diffusion TextEncoder on CPU") + self.model.text_encoder = CPUTextEncoderWrapper( + self.model.text_encoder, torch_dtype + ) + + self.callback = kwargs.pop("callback", None) + + def forward(self, image, mask, config: InpaintRequest): + """Input image and output image have same size + image: [H, W, C] RGB + mask: [H, W, 1] 255 means area to repaint + return: BGR IMAGE + """ + self.set_scheduler(config) + + img_h, img_w = image.shape[:2] + promptA, promptB, negative_promptA, negative_promptB = add_task_to_prompt( + config.prompt, config.negative_prompt, config.powerpaint_task + ) + + output = self.model( + image=PIL.Image.fromarray(image), + promptA=promptA, + promptB=promptB, + tradoff=config.fitting_degree, + tradoff_nag=config.fitting_degree, + negative_promptA=negative_promptA, + negative_promptB=negative_promptB, + mask_image=PIL.Image.fromarray(mask[:, :, -1], mode="L"), + num_inference_steps=config.sd_steps, + strength=config.sd_strength, + guidance_scale=config.sd_guidance_scale, + output_type="np", + callback=self.callback, + height=img_h, + width=img_w, + generator=torch.manual_seed(config.sd_seed), + callback_steps=1, + ).images[0] + + output = (output * 255).round().astype("uint8") + output = cv2.cvtColor(output, cv2.COLOR_RGB2BGR) + return output diff --git a/py/iopaint/model/power_paint/powerpaint_tokenizer.py b/py/iopaint/model/power_paint/powerpaint_tokenizer.py new file mode 100644 index 0000000..73bfddf --- /dev/null +++ b/py/iopaint/model/power_paint/powerpaint_tokenizer.py @@ -0,0 +1,540 @@ +import torch +import torch.nn as nn +import copy +import random +from typing import Any, List, Optional, Union +from transformers import CLIPTokenizer + +from ...schema import PowerPaintTask + + +def add_task_to_prompt(prompt, negative_prompt, task: PowerPaintTask): + if task == PowerPaintTask.object_remove: + promptA = prompt + " P_ctxt" + promptB = prompt + " P_ctxt" + negative_promptA = negative_prompt + " P_obj" + negative_promptB = negative_prompt + " P_obj" + elif task == PowerPaintTask.shape_guided: + promptA = prompt + " P_shape" + promptB = prompt + " P_ctxt" + negative_promptA = negative_prompt + negative_promptB = negative_prompt + elif task == PowerPaintTask.outpainting: + promptA = prompt + " P_ctxt" + promptB = prompt + " P_ctxt" + negative_promptA = negative_prompt + " P_obj" + negative_promptB = negative_prompt + " P_obj" + else: + promptA = prompt + " P_obj" + promptB = prompt + " P_obj" + negative_promptA = negative_prompt + negative_promptB = negative_prompt + + return promptA, promptB, negative_promptA, negative_promptB + + +class PowerPaintTokenizer: + def __init__(self, tokenizer: CLIPTokenizer): + self.wrapped = tokenizer + self.token_map = {} + placeholder_tokens = ["P_ctxt", "P_shape", "P_obj"] + num_vec_per_token = 10 + for placeholder_token in placeholder_tokens: + output = [] + for i in range(num_vec_per_token): + ith_token = placeholder_token + f"_{i}" + output.append(ith_token) + self.token_map[placeholder_token] = output + + def __getattr__(self, name: str) -> Any: + if name == "wrapped": + return super().__getattr__("wrapped") + + try: + return getattr(self.wrapped, name) + except AttributeError: + try: + return super().__getattr__(name) + except AttributeError: + raise AttributeError( + "'name' cannot be found in both " + f"'{self.__class__.__name__}' and " + f"'{self.__class__.__name__}.tokenizer'." + ) + + def try_adding_tokens(self, tokens: Union[str, List[str]], *args, **kwargs): + """Attempt to add tokens to the tokenizer. + + Args: + tokens (Union[str, List[str]]): The tokens to be added. + """ + num_added_tokens = self.wrapped.add_tokens(tokens, *args, **kwargs) + assert num_added_tokens != 0, ( + f"The tokenizer already contains the token {tokens}. Please pass " + "a different `placeholder_token` that is not already in the " + "tokenizer." + ) + + def get_token_info(self, token: str) -> dict: + """Get the information of a token, including its start and end index in + the current tokenizer. + + Args: + token (str): The token to be queried. + + Returns: + dict: The information of the token, including its start and end + index in current tokenizer. + """ + token_ids = self.__call__(token).input_ids + start, end = token_ids[1], token_ids[-2] + 1 + return {"name": token, "start": start, "end": end} + + def add_placeholder_token( + self, placeholder_token: str, *args, num_vec_per_token: int = 1, **kwargs + ): + """Add placeholder tokens to the tokenizer. + + Args: + placeholder_token (str): The placeholder token to be added. + num_vec_per_token (int, optional): The number of vectors of + the added placeholder token. + *args, **kwargs: The arguments for `self.wrapped.add_tokens`. + """ + output = [] + if num_vec_per_token == 1: + self.try_adding_tokens(placeholder_token, *args, **kwargs) + output.append(placeholder_token) + else: + output = [] + for i in range(num_vec_per_token): + ith_token = placeholder_token + f"_{i}" + self.try_adding_tokens(ith_token, *args, **kwargs) + output.append(ith_token) + + for token in self.token_map: + if token in placeholder_token: + raise ValueError( + f"The tokenizer already has placeholder token {token} " + f"that can get confused with {placeholder_token} " + "keep placeholder tokens independent" + ) + self.token_map[placeholder_token] = output + + def replace_placeholder_tokens_in_text( + self, + text: Union[str, List[str]], + vector_shuffle: bool = False, + prop_tokens_to_load: float = 1.0, + ) -> Union[str, List[str]]: + """Replace the keywords in text with placeholder tokens. This function + will be called in `self.__call__` and `self.encode`. + + Args: + text (Union[str, List[str]]): The text to be processed. + vector_shuffle (bool, optional): Whether to shuffle the vectors. + Defaults to False. + prop_tokens_to_load (float, optional): The proportion of tokens to + be loaded. If 1.0, all tokens will be loaded. Defaults to 1.0. + + Returns: + Union[str, List[str]]: The processed text. + """ + if isinstance(text, list): + output = [] + for i in range(len(text)): + output.append( + self.replace_placeholder_tokens_in_text( + text[i], vector_shuffle=vector_shuffle + ) + ) + return output + + for placeholder_token in self.token_map: + if placeholder_token in text: + tokens = self.token_map[placeholder_token] + tokens = tokens[: 1 + int(len(tokens) * prop_tokens_to_load)] + if vector_shuffle: + tokens = copy.copy(tokens) + random.shuffle(tokens) + text = text.replace(placeholder_token, " ".join(tokens)) + return text + + def replace_text_with_placeholder_tokens( + self, text: Union[str, List[str]] + ) -> Union[str, List[str]]: + """Replace the placeholder tokens in text with the original keywords. + This function will be called in `self.decode`. + + Args: + text (Union[str, List[str]]): The text to be processed. + + Returns: + Union[str, List[str]]: The processed text. + """ + if isinstance(text, list): + output = [] + for i in range(len(text)): + output.append(self.replace_text_with_placeholder_tokens(text[i])) + return output + + for placeholder_token, tokens in self.token_map.items(): + merged_tokens = " ".join(tokens) + if merged_tokens in text: + text = text.replace(merged_tokens, placeholder_token) + return text + + def __call__( + self, + text: Union[str, List[str]], + *args, + vector_shuffle: bool = False, + prop_tokens_to_load: float = 1.0, + **kwargs, + ): + """The call function of the wrapper. + + Args: + text (Union[str, List[str]]): The text to be tokenized. + vector_shuffle (bool, optional): Whether to shuffle the vectors. + Defaults to False. + prop_tokens_to_load (float, optional): The proportion of tokens to + be loaded. If 1.0, all tokens will be loaded. Defaults to 1.0 + *args, **kwargs: The arguments for `self.wrapped.__call__`. + """ + replaced_text = self.replace_placeholder_tokens_in_text( + text, vector_shuffle=vector_shuffle, prop_tokens_to_load=prop_tokens_to_load + ) + + return self.wrapped.__call__(replaced_text, *args, **kwargs) + + def encode(self, text: Union[str, List[str]], *args, **kwargs): + """Encode the passed text to token index. + + Args: + text (Union[str, List[str]]): The text to be encode. + *args, **kwargs: The arguments for `self.wrapped.__call__`. + """ + replaced_text = self.replace_placeholder_tokens_in_text(text) + return self.wrapped(replaced_text, *args, **kwargs) + + def decode( + self, token_ids, return_raw: bool = False, *args, **kwargs + ) -> Union[str, List[str]]: + """Decode the token index to text. + + Args: + token_ids: The token index to be decoded. + return_raw: Whether keep the placeholder token in the text. + Defaults to False. + *args, **kwargs: The arguments for `self.wrapped.decode`. + + Returns: + Union[str, List[str]]: The decoded text. + """ + text = self.wrapped.decode(token_ids, *args, **kwargs) + if return_raw: + return text + replaced_text = self.replace_text_with_placeholder_tokens(text) + return replaced_text + + +class EmbeddingLayerWithFixes(nn.Module): + """The revised embedding layer to support external embeddings. This design + of this class is inspired by https://github.com/AUTOMATIC1111/stable- + diffusion-webui/blob/22bcc7be428c94e9408f589966c2040187245d81/modules/sd_hi + jack.py#L224 # noqa. + + Args: + wrapped (nn.Emebdding): The embedding layer to be wrapped. + external_embeddings (Union[dict, List[dict]], optional): The external + embeddings added to this layer. Defaults to None. + """ + + def __init__( + self, + wrapped: nn.Embedding, + external_embeddings: Optional[Union[dict, List[dict]]] = None, + ): + super().__init__() + self.wrapped = wrapped + self.num_embeddings = wrapped.weight.shape[0] + + self.external_embeddings = [] + if external_embeddings: + self.add_embeddings(external_embeddings) + + self.trainable_embeddings = nn.ParameterDict() + + @property + def weight(self): + """Get the weight of wrapped embedding layer.""" + return self.wrapped.weight + + def check_duplicate_names(self, embeddings: List[dict]): + """Check whether duplicate names exist in list of 'external + embeddings'. + + Args: + embeddings (List[dict]): A list of embedding to be check. + """ + names = [emb["name"] for emb in embeddings] + assert len(names) == len(set(names)), ( + "Found duplicated names in 'external_embeddings'. Name list: " f"'{names}'" + ) + + def check_ids_overlap(self, embeddings): + """Check whether overlap exist in token ids of 'external_embeddings'. + + Args: + embeddings (List[dict]): A list of embedding to be check. + """ + ids_range = [[emb["start"], emb["end"], emb["name"]] for emb in embeddings] + ids_range.sort() # sort by 'start' + # check if 'end' has overlapping + for idx in range(len(ids_range) - 1): + name1, name2 = ids_range[idx][-1], ids_range[idx + 1][-1] + assert ids_range[idx][1] <= ids_range[idx + 1][0], ( + f"Found ids overlapping between embeddings '{name1}' " f"and '{name2}'." + ) + + def add_embeddings(self, embeddings: Optional[Union[dict, List[dict]]]): + """Add external embeddings to this layer. + + Use case: + + >>> 1. Add token to tokenizer and get the token id. + >>> tokenizer = TokenizerWrapper('openai/clip-vit-base-patch32') + >>> # 'how much' in kiswahili + >>> tokenizer.add_placeholder_tokens('ngapi', num_vec_per_token=4) + >>> + >>> 2. Add external embeddings to the model. + >>> new_embedding = { + >>> 'name': 'ngapi', # 'how much' in kiswahili + >>> 'embedding': torch.ones(1, 15) * 4, + >>> 'start': tokenizer.get_token_info('kwaheri')['start'], + >>> 'end': tokenizer.get_token_info('kwaheri')['end'], + >>> 'trainable': False # if True, will registry as a parameter + >>> } + >>> embedding_layer = nn.Embedding(10, 15) + >>> embedding_layer_wrapper = EmbeddingLayerWithFixes(embedding_layer) + >>> embedding_layer_wrapper.add_embeddings(new_embedding) + >>> + >>> 3. Forward tokenizer and embedding layer! + >>> input_text = ['hello, ngapi!', 'hello my friend, ngapi?'] + >>> input_ids = tokenizer( + >>> input_text, padding='max_length', truncation=True, + >>> return_tensors='pt')['input_ids'] + >>> out_feat = embedding_layer_wrapper(input_ids) + >>> + >>> 4. Let's validate the result! + >>> assert (out_feat[0, 3: 7] == 2.3).all() + >>> assert (out_feat[2, 5: 9] == 2.3).all() + + Args: + embeddings (Union[dict, list[dict]]): The external embeddings to + be added. Each dict must contain the following 4 fields: 'name' + (the name of this embedding), 'embedding' (the embedding + tensor), 'start' (the start token id of this embedding), 'end' + (the end token id of this embedding). For example: + `{name: NAME, start: START, end: END, embedding: torch.Tensor}` + """ + if isinstance(embeddings, dict): + embeddings = [embeddings] + + self.external_embeddings += embeddings + self.check_duplicate_names(self.external_embeddings) + self.check_ids_overlap(self.external_embeddings) + + # set for trainable + added_trainable_emb_info = [] + for embedding in embeddings: + trainable = embedding.get("trainable", False) + if trainable: + name = embedding["name"] + embedding["embedding"] = torch.nn.Parameter(embedding["embedding"]) + self.trainable_embeddings[name] = embedding["embedding"] + added_trainable_emb_info.append(name) + + added_emb_info = [emb["name"] for emb in embeddings] + added_emb_info = ", ".join(added_emb_info) + print(f"Successfully add external embeddings: {added_emb_info}.", "current") + + if added_trainable_emb_info: + added_trainable_emb_info = ", ".join(added_trainable_emb_info) + print( + "Successfully add trainable external embeddings: " + f"{added_trainable_emb_info}", + "current", + ) + + def replace_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor: + """Replace external input ids to 0. + + Args: + input_ids (torch.Tensor): The input ids to be replaced. + + Returns: + torch.Tensor: The replaced input ids. + """ + input_ids_fwd = input_ids.clone() + input_ids_fwd[input_ids_fwd >= self.num_embeddings] = 0 + return input_ids_fwd + + def replace_embeddings( + self, input_ids: torch.Tensor, embedding: torch.Tensor, external_embedding: dict + ) -> torch.Tensor: + """Replace external embedding to the embedding layer. Noted that, in + this function we use `torch.cat` to avoid inplace modification. + + Args: + input_ids (torch.Tensor): The original token ids. Shape like + [LENGTH, ]. + embedding (torch.Tensor): The embedding of token ids after + `replace_input_ids` function. + external_embedding (dict): The external embedding to be replaced. + + Returns: + torch.Tensor: The replaced embedding. + """ + new_embedding = [] + + name = external_embedding["name"] + start = external_embedding["start"] + end = external_embedding["end"] + target_ids_to_replace = [i for i in range(start, end)] + ext_emb = external_embedding["embedding"] + + # do not need to replace + if not (input_ids == start).any(): + return embedding + + # start replace + s_idx, e_idx = 0, 0 + while e_idx < len(input_ids): + if input_ids[e_idx] == start: + if e_idx != 0: + # add embedding do not need to replace + new_embedding.append(embedding[s_idx:e_idx]) + + # check if the next embedding need to replace is valid + actually_ids_to_replace = [ + int(i) for i in input_ids[e_idx : e_idx + end - start] + ] + assert actually_ids_to_replace == target_ids_to_replace, ( + f"Invalid 'input_ids' in position: {s_idx} to {e_idx}. " + f"Expect '{target_ids_to_replace}' for embedding " + f"'{name}' but found '{actually_ids_to_replace}'." + ) + + new_embedding.append(ext_emb) + + s_idx = e_idx + end - start + e_idx = s_idx + 1 + else: + e_idx += 1 + + if e_idx == len(input_ids): + new_embedding.append(embedding[s_idx:e_idx]) + + return torch.cat(new_embedding, dim=0) + + def forward( + self, input_ids: torch.Tensor, external_embeddings: Optional[List[dict]] = None + ): + """The forward function. + + Args: + input_ids (torch.Tensor): The token ids shape like [bz, LENGTH] or + [LENGTH, ]. + external_embeddings (Optional[List[dict]]): The external + embeddings. If not passed, only `self.external_embeddings` + will be used. Defaults to None. + + input_ids: shape like [bz, LENGTH] or [LENGTH]. + """ + assert input_ids.ndim in [1, 2] + if input_ids.ndim == 1: + input_ids = input_ids.unsqueeze(0) + + if external_embeddings is None and not self.external_embeddings: + return self.wrapped(input_ids) + + input_ids_fwd = self.replace_input_ids(input_ids) + inputs_embeds = self.wrapped(input_ids_fwd) + + vecs = [] + + if external_embeddings is None: + external_embeddings = [] + elif isinstance(external_embeddings, dict): + external_embeddings = [external_embeddings] + embeddings = self.external_embeddings + external_embeddings + + for input_id, embedding in zip(input_ids, inputs_embeds): + new_embedding = embedding + for external_embedding in embeddings: + new_embedding = self.replace_embeddings( + input_id, new_embedding, external_embedding + ) + vecs.append(new_embedding) + + return torch.stack(vecs) + + +def add_tokens( + tokenizer, + text_encoder, + placeholder_tokens: list, + initialize_tokens: list = None, + num_vectors_per_token: int = 1, +): + """Add token for training. + + # TODO: support add tokens as dict, then we can load pretrained tokens. + """ + if initialize_tokens is not None: + assert len(initialize_tokens) == len( + placeholder_tokens + ), "placeholder_token should be the same length as initialize_token" + for ii in range(len(placeholder_tokens)): + tokenizer.add_placeholder_token( + placeholder_tokens[ii], num_vec_per_token=num_vectors_per_token + ) + + # text_encoder.set_embedding_layer() + embedding_layer = text_encoder.text_model.embeddings.token_embedding + text_encoder.text_model.embeddings.token_embedding = EmbeddingLayerWithFixes( + embedding_layer + ) + embedding_layer = text_encoder.text_model.embeddings.token_embedding + + assert embedding_layer is not None, ( + "Do not support get embedding layer for current text encoder. " + "Please check your configuration." + ) + initialize_embedding = [] + if initialize_tokens is not None: + for ii in range(len(placeholder_tokens)): + init_id = tokenizer(initialize_tokens[ii]).input_ids[1] + temp_embedding = embedding_layer.weight[init_id] + initialize_embedding.append( + temp_embedding[None, ...].repeat(num_vectors_per_token, 1) + ) + else: + for ii in range(len(placeholder_tokens)): + init_id = tokenizer("a").input_ids[1] + temp_embedding = embedding_layer.weight[init_id] + len_emb = temp_embedding.shape[0] + init_weight = (torch.rand(num_vectors_per_token, len_emb) - 0.5) / 2.0 + initialize_embedding.append(init_weight) + + # initialize_embedding = torch.cat(initialize_embedding,dim=0) + + token_info_all = [] + for ii in range(len(placeholder_tokens)): + token_info = tokenizer.get_token_info(placeholder_tokens[ii]) + token_info["embedding"] = initialize_embedding[ii] + token_info["trainable"] = True + token_info_all.append(token_info) + embedding_layer.add_embeddings(token_info_all) diff --git a/py/iopaint/model/sd.py b/py/iopaint/model/sd.py new file mode 100644 index 0000000..dce44a7 --- /dev/null +++ b/py/iopaint/model/sd.py @@ -0,0 +1,129 @@ +import PIL.Image +import cv2 +import torch +from loguru import logger + +from .base import DiffusionInpaintModel +from .helper.cpu_text_encoder import CPUTextEncoderWrapper +from .original_sd_configs import get_config_files +from .utils import ( + handle_from_pretrained_exceptions, + get_torch_dtype, + enable_low_mem, + is_local_files_only, +) +from ..schema import InpaintRequest, ModelType + + +class SD(DiffusionInpaintModel): + pad_mod = 8 + min_size = 512 + lcm_lora_id = "latent-consistency/lcm-lora-sdv1-5" + + def init_model(self, device: torch.device, **kwargs): + from diffusers.pipelines.stable_diffusion import StableDiffusionInpaintPipeline + + use_gpu, torch_dtype = get_torch_dtype(device, kwargs.get("no_half", False)) + + model_kwargs = { + **kwargs.get("pipe_components", {}), + "local_files_only": is_local_files_only(**kwargs), + } + disable_nsfw_checker = kwargs["disable_nsfw"] or kwargs.get( + "cpu_offload", False + ) + if disable_nsfw_checker: + logger.info("Disable Stable Diffusion Model NSFW checker") + model_kwargs.update( + dict( + safety_checker=None, + feature_extractor=None, + requires_safety_checker=False, + ) + ) + + if self.model_info.is_single_file_diffusers: + if self.model_info.model_type == ModelType.DIFFUSERS_SD: + model_kwargs["num_in_channels"] = 4 + else: + model_kwargs["num_in_channels"] = 9 + + self.model = StableDiffusionInpaintPipeline.from_single_file( + self.model_id_or_path, + torch_dtype=torch_dtype, + load_safety_checker=not disable_nsfw_checker, + config_files=get_config_files(), + **model_kwargs, + ) + else: + self.model = handle_from_pretrained_exceptions( + StableDiffusionInpaintPipeline.from_pretrained, + pretrained_model_name_or_path=self.model_id_or_path, + variant="fp16", + torch_dtype=torch_dtype, + **model_kwargs, + ) + + enable_low_mem(self.model, kwargs.get("low_mem", False)) + + if kwargs.get("cpu_offload", False) and use_gpu: + logger.info("Enable sequential cpu offload") + self.model.enable_sequential_cpu_offload(gpu_id=0) + else: + self.model = self.model.to(device) + if kwargs["sd_cpu_textencoder"]: + logger.info("Run Stable Diffusion TextEncoder on CPU") + self.model.text_encoder = CPUTextEncoderWrapper( + self.model.text_encoder, torch_dtype + ) + + self.callback = kwargs.pop("callback", None) + + def forward(self, image, mask, config: InpaintRequest): + """Input image and output image have same size + image: [H, W, C] RGB + mask: [H, W, 1] 255 means area to repaint + return: BGR IMAGE + """ + self.set_scheduler(config) + + img_h, img_w = image.shape[:2] + + output = self.model( + image=PIL.Image.fromarray(image), + prompt=config.prompt, + negative_prompt=config.negative_prompt, + mask_image=PIL.Image.fromarray(mask[:, :, -1], mode="L"), + num_inference_steps=config.sd_steps, + strength=config.sd_strength, + guidance_scale=config.sd_guidance_scale, + output_type="np", + callback_on_step_end=self.callback, + height=img_h, + width=img_w, + generator=torch.manual_seed(config.sd_seed), + ).images[0] + + output = (output * 255).round().astype("uint8") + output = cv2.cvtColor(output, cv2.COLOR_RGB2BGR) + return output + + +class SD15(SD): + name = "runwayml/stable-diffusion-inpainting" + model_id_or_path = "runwayml/stable-diffusion-inpainting" + + +class Anything4(SD): + name = "Sanster/anything-4.0-inpainting" + model_id_or_path = "Sanster/anything-4.0-inpainting" + + +class RealisticVision14(SD): + name = "Sanster/Realistic_Vision_V1.4-inpainting" + model_id_or_path = "Sanster/Realistic_Vision_V1.4-inpainting" + + +class SD2(SD): + name = "stabilityai/stable-diffusion-2-inpainting" + model_id_or_path = "stabilityai/stable-diffusion-2-inpainting" diff --git a/py/iopaint/model/sdxl.py b/py/iopaint/model/sdxl.py new file mode 100644 index 0000000..53610cf --- /dev/null +++ b/py/iopaint/model/sdxl.py @@ -0,0 +1,110 @@ +import os + +import PIL.Image +import cv2 +import torch +from diffusers import AutoencoderKL +from loguru import logger + +from ..schema import InpaintRequest, ModelType + +from .base import DiffusionInpaintModel +from .helper.cpu_text_encoder import CPUTextEncoderWrapper +from .original_sd_configs import get_config_files +from .utils import ( + handle_from_pretrained_exceptions, + get_torch_dtype, + enable_low_mem, + is_local_files_only, +) + + +class SDXL(DiffusionInpaintModel): + name = "diffusers/stable-diffusion-xl-1.0-inpainting-0.1" + pad_mod = 8 + min_size = 512 + lcm_lora_id = "latent-consistency/lcm-lora-sdxl" + model_id_or_path = "diffusers/stable-diffusion-xl-1.0-inpainting-0.1" + + def init_model(self, device: torch.device, **kwargs): + from diffusers.pipelines import StableDiffusionXLInpaintPipeline + + use_gpu, torch_dtype = get_torch_dtype(device, kwargs.get("no_half", False)) + + if self.model_info.model_type == ModelType.DIFFUSERS_SDXL: + num_in_channels = 4 + else: + num_in_channels = 9 + + if os.path.isfile(self.model_id_or_path): + self.model = StableDiffusionXLInpaintPipeline.from_single_file( + self.model_id_or_path, + torch_dtype=torch_dtype, + num_in_channels=num_in_channels, + load_safety_checker=False, + config_files=get_config_files() + ) + else: + model_kwargs = { + **kwargs.get("pipe_components", {}), + "local_files_only": is_local_files_only(**kwargs), + } + if "vae" not in model_kwargs: + vae = AutoencoderKL.from_pretrained( + "madebyollin/sdxl-vae-fp16-fix", torch_dtype=torch_dtype + ) + model_kwargs["vae"] = vae + self.model = handle_from_pretrained_exceptions( + StableDiffusionXLInpaintPipeline.from_pretrained, + pretrained_model_name_or_path=self.model_id_or_path, + torch_dtype=torch_dtype, + variant="fp16", + **model_kwargs + ) + + enable_low_mem(self.model, kwargs.get("low_mem", False)) + + if kwargs.get("cpu_offload", False) and use_gpu: + logger.info("Enable sequential cpu offload") + self.model.enable_sequential_cpu_offload(gpu_id=0) + else: + self.model = self.model.to(device) + if kwargs["sd_cpu_textencoder"]: + logger.info("Run Stable Diffusion TextEncoder on CPU") + self.model.text_encoder = CPUTextEncoderWrapper( + self.model.text_encoder, torch_dtype + ) + self.model.text_encoder_2 = CPUTextEncoderWrapper( + self.model.text_encoder_2, torch_dtype + ) + + self.callback = kwargs.pop("callback", None) + + def forward(self, image, mask, config: InpaintRequest): + """Input image and output image have same size + image: [H, W, C] RGB + mask: [H, W, 1] 255 means area to repaint + return: BGR IMAGE + """ + self.set_scheduler(config) + + img_h, img_w = image.shape[:2] + + output = self.model( + image=PIL.Image.fromarray(image), + prompt=config.prompt, + negative_prompt=config.negative_prompt, + mask_image=PIL.Image.fromarray(mask[:, :, -1], mode="L"), + num_inference_steps=config.sd_steps, + strength=0.999 if config.sd_strength == 1.0 else config.sd_strength, + guidance_scale=config.sd_guidance_scale, + output_type="np", + callback_on_step_end=self.callback, + height=img_h, + width=img_w, + generator=torch.manual_seed(config.sd_seed), + ).images[0] + + output = (output * 255).round().astype("uint8") + output = cv2.cvtColor(output, cv2.COLOR_RGB2BGR) + return output diff --git a/py/iopaint/model/utils.py b/py/iopaint/model/utils.py new file mode 100644 index 0000000..adbc50d --- /dev/null +++ b/py/iopaint/model/utils.py @@ -0,0 +1,1033 @@ +import gc +import math +import random +import traceback +from typing import Any + +import torch +import numpy as np +import collections +from itertools import repeat + +from diffusers import ( + DDIMScheduler, + PNDMScheduler, + LMSDiscreteScheduler, + EulerDiscreteScheduler, + EulerAncestralDiscreteScheduler, + DPMSolverMultistepScheduler, + UniPCMultistepScheduler, + LCMScheduler, + DPMSolverSinglestepScheduler, + KDPM2DiscreteScheduler, + KDPM2AncestralDiscreteScheduler, + HeunDiscreteScheduler, +) +from loguru import logger + +from ..schema import SDSampler +from torch import conv2d, conv_transpose2d + + +def make_beta_schedule( + device, schedule, n_timestep, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3 +): + if schedule == "linear": + betas = ( + torch.linspace( + linear_start**0.5, linear_end**0.5, n_timestep, dtype=torch.float64 + ) + ** 2 + ) + + elif schedule == "cosine": + timesteps = ( + torch.arange(n_timestep + 1, dtype=torch.float64) / n_timestep + cosine_s + ).to(device) + alphas = timesteps / (1 + cosine_s) * np.pi / 2 + alphas = torch.cos(alphas).pow(2).to(device) + alphas = alphas / alphas[0] + betas = 1 - alphas[1:] / alphas[:-1] + betas = np.clip(betas, a_min=0, a_max=0.999) + + elif schedule == "sqrt_linear": + betas = torch.linspace( + linear_start, linear_end, n_timestep, dtype=torch.float64 + ) + elif schedule == "sqrt": + betas = ( + torch.linspace(linear_start, linear_end, n_timestep, dtype=torch.float64) + ** 0.5 + ) + else: + raise ValueError(f"schedule '{schedule}' unknown.") + return betas.numpy() + + +def make_ddim_sampling_parameters(alphacums, ddim_timesteps, eta, verbose=True): + # select alphas for computing the variance schedule + alphas = alphacums[ddim_timesteps] + alphas_prev = np.asarray([alphacums[0]] + alphacums[ddim_timesteps[:-1]].tolist()) + + # according the the formula provided in https://arxiv.org/abs/2010.02502 + sigmas = eta * np.sqrt( + (1 - alphas_prev) / (1 - alphas) * (1 - alphas / alphas_prev) + ) + if verbose: + print( + f"Selected alphas for ddim sampler: a_t: {alphas}; a_(t-1): {alphas_prev}" + ) + print( + f"For the chosen value of eta, which is {eta}, " + f"this results in the following sigma_t schedule for ddim sampler {sigmas}" + ) + return sigmas, alphas, alphas_prev + + +def make_ddim_timesteps( + ddim_discr_method, num_ddim_timesteps, num_ddpm_timesteps, verbose=True +): + if ddim_discr_method == "uniform": + c = num_ddpm_timesteps // num_ddim_timesteps + ddim_timesteps = np.asarray(list(range(0, num_ddpm_timesteps, c))) + elif ddim_discr_method == "quad": + ddim_timesteps = ( + (np.linspace(0, np.sqrt(num_ddpm_timesteps * 0.8), num_ddim_timesteps)) ** 2 + ).astype(int) + else: + raise NotImplementedError( + f'There is no ddim discretization method called "{ddim_discr_method}"' + ) + + # assert ddim_timesteps.shape[0] == num_ddim_timesteps + # add one to get the final alpha values right (the ones from first scale to data during sampling) + steps_out = ddim_timesteps + 1 + if verbose: + print(f"Selected timesteps for ddim sampler: {steps_out}") + return steps_out + + +def noise_like(shape, device, repeat=False): + repeat_noise = lambda: torch.randn((1, *shape[1:]), device=device).repeat( + shape[0], *((1,) * (len(shape) - 1)) + ) + noise = lambda: torch.randn(shape, device=device) + return repeat_noise() if repeat else noise() + + +def timestep_embedding(device, timesteps, dim, max_period=10000, repeat_only=False): + """ + Create sinusoidal timestep embeddings. + :param timesteps: a 1-D Tensor of N indices, one per batch element. + These may be fractional. + :param dim: the dimension of the output. + :param max_period: controls the minimum frequency of the embeddings. + :return: an [N x dim] Tensor of positional embeddings. + """ + half = dim // 2 + freqs = torch.exp( + -math.log(max_period) + * torch.arange(start=0, end=half, dtype=torch.float32) + / half + ).to(device=device) + + args = timesteps[:, None].float() * freqs[None] + + embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1) + if dim % 2: + embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1) + return embedding + + +###### MAT and FcF ####### + + +def normalize_2nd_moment(x, dim=1): + return ( + x * (x.square().mean(dim=dim, keepdim=True) + torch.finfo(x.dtype).eps).rsqrt() + ) + + +class EasyDict(dict): + """Convenience class that behaves like a dict but allows access with the attribute syntax.""" + + def __getattr__(self, name: str) -> Any: + try: + return self[name] + except KeyError: + raise AttributeError(name) + + def __setattr__(self, name: str, value: Any) -> None: + self[name] = value + + def __delattr__(self, name: str) -> None: + del self[name] + + +def _bias_act_ref(x, b=None, dim=1, act="linear", alpha=None, gain=None, clamp=None): + """Slow reference implementation of `bias_act()` using standard TensorFlow ops.""" + assert isinstance(x, torch.Tensor) + assert clamp is None or clamp >= 0 + spec = activation_funcs[act] + alpha = float(alpha if alpha is not None else spec.def_alpha) + gain = float(gain if gain is not None else spec.def_gain) + clamp = float(clamp if clamp is not None else -1) + + # Add bias. + if b is not None: + assert isinstance(b, torch.Tensor) and b.ndim == 1 + assert 0 <= dim < x.ndim + assert b.shape[0] == x.shape[dim] + x = x + b.reshape([-1 if i == dim else 1 for i in range(x.ndim)]) + + # Evaluate activation function. + alpha = float(alpha) + x = spec.func(x, alpha=alpha) + + # Scale by gain. + gain = float(gain) + if gain != 1: + x = x * gain + + # Clamp. + if clamp >= 0: + x = x.clamp(-clamp, clamp) # pylint: disable=invalid-unary-operand-type + return x + + +def bias_act( + x, b=None, dim=1, act="linear", alpha=None, gain=None, clamp=None, impl="ref" +): + r"""Fused bias and activation function. + + Adds bias `b` to activation tensor `x`, evaluates activation function `act`, + and scales the result by `gain`. Each of the steps is optional. In most cases, + the fused op is considerably more efficient than performing the same calculation + using standard PyTorch ops. It supports first and second order gradients, + but not third order gradients. + + Args: + x: Input activation tensor. Can be of any shape. + b: Bias vector, or `None` to disable. Must be a 1D tensor of the same type + as `x`. The shape must be known, and it must match the dimension of `x` + corresponding to `dim`. + dim: The dimension in `x` corresponding to the elements of `b`. + The value of `dim` is ignored if `b` is not specified. + act: Name of the activation function to evaluate, or `"linear"` to disable. + Can be e.g. `"relu"`, `"lrelu"`, `"tanh"`, `"sigmoid"`, `"swish"`, etc. + See `activation_funcs` for a full list. `None` is not allowed. + alpha: Shape parameter for the activation function, or `None` to use the default. + gain: Scaling factor for the output tensor, or `None` to use default. + See `activation_funcs` for the default scaling of each activation function. + If unsure, consider specifying 1. + clamp: Clamp the output values to `[-clamp, +clamp]`, or `None` to disable + the clamping (default). + impl: Name of the implementation to use. Can be `"ref"` or `"cuda"` (default). + + Returns: + Tensor of the same shape and datatype as `x`. + """ + assert isinstance(x, torch.Tensor) + assert impl in ["ref", "cuda"] + return _bias_act_ref( + x=x, b=b, dim=dim, act=act, alpha=alpha, gain=gain, clamp=clamp + ) + + +def _get_filter_size(f): + if f is None: + return 1, 1 + + assert isinstance(f, torch.Tensor) and f.ndim in [1, 2] + fw = f.shape[-1] + fh = f.shape[0] + + fw = int(fw) + fh = int(fh) + assert fw >= 1 and fh >= 1 + return fw, fh + + +def _get_weight_shape(w): + shape = [int(sz) for sz in w.shape] + return shape + + +def _parse_scaling(scaling): + if isinstance(scaling, int): + scaling = [scaling, scaling] + assert isinstance(scaling, (list, tuple)) + assert all(isinstance(x, int) for x in scaling) + sx, sy = scaling + assert sx >= 1 and sy >= 1 + return sx, sy + + +def _parse_padding(padding): + if isinstance(padding, int): + padding = [padding, padding] + assert isinstance(padding, (list, tuple)) + assert all(isinstance(x, int) for x in padding) + if len(padding) == 2: + padx, pady = padding + padding = [padx, padx, pady, pady] + padx0, padx1, pady0, pady1 = padding + return padx0, padx1, pady0, pady1 + + +def setup_filter( + f, + device=torch.device("cpu"), + normalize=True, + flip_filter=False, + gain=1, + separable=None, +): + r"""Convenience function to setup 2D FIR filter for `upfirdn2d()`. + + Args: + f: Torch tensor, numpy array, or python list of the shape + `[filter_height, filter_width]` (non-separable), + `[filter_taps]` (separable), + `[]` (impulse), or + `None` (identity). + device: Result device (default: cpu). + normalize: Normalize the filter so that it retains the magnitude + for constant input signal (DC)? (default: True). + flip_filter: Flip the filter? (default: False). + gain: Overall scaling factor for signal magnitude (default: 1). + separable: Return a separable filter? (default: select automatically). + + Returns: + Float32 tensor of the shape + `[filter_height, filter_width]` (non-separable) or + `[filter_taps]` (separable). + """ + # Validate. + if f is None: + f = 1 + f = torch.as_tensor(f, dtype=torch.float32) + assert f.ndim in [0, 1, 2] + assert f.numel() > 0 + if f.ndim == 0: + f = f[np.newaxis] + + # Separable? + if separable is None: + separable = f.ndim == 1 and f.numel() >= 8 + if f.ndim == 1 and not separable: + f = f.ger(f) + assert f.ndim == (1 if separable else 2) + + # Apply normalize, flip, gain, and device. + if normalize: + f /= f.sum() + if flip_filter: + f = f.flip(list(range(f.ndim))) + f = f * (gain ** (f.ndim / 2)) + f = f.to(device=device) + return f + + +def _ntuple(n): + def parse(x): + if isinstance(x, collections.abc.Iterable): + return x + return tuple(repeat(x, n)) + + return parse + + +to_2tuple = _ntuple(2) + +activation_funcs = { + "linear": EasyDict( + func=lambda x, **_: x, + def_alpha=0, + def_gain=1, + cuda_idx=1, + ref="", + has_2nd_grad=False, + ), + "relu": EasyDict( + func=lambda x, **_: torch.nn.functional.relu(x), + def_alpha=0, + def_gain=np.sqrt(2), + cuda_idx=2, + ref="y", + has_2nd_grad=False, + ), + "lrelu": EasyDict( + func=lambda x, alpha, **_: torch.nn.functional.leaky_relu(x, alpha), + def_alpha=0.2, + def_gain=np.sqrt(2), + cuda_idx=3, + ref="y", + has_2nd_grad=False, + ), + "tanh": EasyDict( + func=lambda x, **_: torch.tanh(x), + def_alpha=0, + def_gain=1, + cuda_idx=4, + ref="y", + has_2nd_grad=True, + ), + "sigmoid": EasyDict( + func=lambda x, **_: torch.sigmoid(x), + def_alpha=0, + def_gain=1, + cuda_idx=5, + ref="y", + has_2nd_grad=True, + ), + "elu": EasyDict( + func=lambda x, **_: torch.nn.functional.elu(x), + def_alpha=0, + def_gain=1, + cuda_idx=6, + ref="y", + has_2nd_grad=True, + ), + "selu": EasyDict( + func=lambda x, **_: torch.nn.functional.selu(x), + def_alpha=0, + def_gain=1, + cuda_idx=7, + ref="y", + has_2nd_grad=True, + ), + "softplus": EasyDict( + func=lambda x, **_: torch.nn.functional.softplus(x), + def_alpha=0, + def_gain=1, + cuda_idx=8, + ref="y", + has_2nd_grad=True, + ), + "swish": EasyDict( + func=lambda x, **_: torch.sigmoid(x) * x, + def_alpha=0, + def_gain=np.sqrt(2), + cuda_idx=9, + ref="x", + has_2nd_grad=True, + ), +} + + +def upfirdn2d(x, f, up=1, down=1, padding=0, flip_filter=False, gain=1, impl="cuda"): + r"""Pad, upsample, filter, and downsample a batch of 2D images. + + Performs the following sequence of operations for each channel: + + 1. Upsample the image by inserting N-1 zeros after each pixel (`up`). + + 2. Pad the image with the specified number of zeros on each side (`padding`). + Negative padding corresponds to cropping the image. + + 3. Convolve the image with the specified 2D FIR filter (`f`), shrinking it + so that the footprint of all output pixels lies within the input image. + + 4. Downsample the image by keeping every Nth pixel (`down`). + + This sequence of operations bears close resemblance to scipy.signal.upfirdn(). + The fused op is considerably more efficient than performing the same calculation + using standard PyTorch ops. It supports gradients of arbitrary order. + + Args: + x: Float32/float64/float16 input tensor of the shape + `[batch_size, num_channels, in_height, in_width]`. + f: Float32 FIR filter of the shape + `[filter_height, filter_width]` (non-separable), + `[filter_taps]` (separable), or + `None` (identity). + up: Integer upsampling factor. Can be a single int or a list/tuple + `[x, y]` (default: 1). + down: Integer downsampling factor. Can be a single int or a list/tuple + `[x, y]` (default: 1). + padding: Padding with respect to the upsampled image. Can be a single number + or a list/tuple `[x, y]` or `[x_before, x_after, y_before, y_after]` + (default: 0). + flip_filter: False = convolution, True = correlation (default: False). + gain: Overall scaling factor for signal magnitude (default: 1). + impl: Implementation to use. Can be `'ref'` or `'cuda'` (default: `'cuda'`). + + Returns: + Tensor of the shape `[batch_size, num_channels, out_height, out_width]`. + """ + # assert isinstance(x, torch.Tensor) + # assert impl in ['ref', 'cuda'] + return _upfirdn2d_ref( + x, f, up=up, down=down, padding=padding, flip_filter=flip_filter, gain=gain + ) + + +def _upfirdn2d_ref(x, f, up=1, down=1, padding=0, flip_filter=False, gain=1): + """Slow reference implementation of `upfirdn2d()` using standard PyTorch ops.""" + # Validate arguments. + assert isinstance(x, torch.Tensor) and x.ndim == 4 + if f is None: + f = torch.ones([1, 1], dtype=torch.float32, device=x.device) + assert isinstance(f, torch.Tensor) and f.ndim in [1, 2] + assert not f.requires_grad + batch_size, num_channels, in_height, in_width = x.shape + # upx, upy = _parse_scaling(up) + # downx, downy = _parse_scaling(down) + + upx, upy = up, up + downx, downy = down, down + + # padx0, padx1, pady0, pady1 = _parse_padding(padding) + padx0, padx1, pady0, pady1 = padding[0], padding[1], padding[2], padding[3] + + # Upsample by inserting zeros. + x = x.reshape([batch_size, num_channels, in_height, 1, in_width, 1]) + x = torch.nn.functional.pad(x, [0, upx - 1, 0, 0, 0, upy - 1]) + x = x.reshape([batch_size, num_channels, in_height * upy, in_width * upx]) + + # Pad or crop. + x = torch.nn.functional.pad( + x, [max(padx0, 0), max(padx1, 0), max(pady0, 0), max(pady1, 0)] + ) + x = x[ + :, + :, + max(-pady0, 0) : x.shape[2] - max(-pady1, 0), + max(-padx0, 0) : x.shape[3] - max(-padx1, 0), + ] + + # Setup filter. + f = f * (gain ** (f.ndim / 2)) + f = f.to(x.dtype) + if not flip_filter: + f = f.flip(list(range(f.ndim))) + + # Convolve with the filter. + f = f[np.newaxis, np.newaxis].repeat([num_channels, 1] + [1] * f.ndim) + if f.ndim == 4: + x = conv2d(input=x, weight=f, groups=num_channels) + else: + x = conv2d(input=x, weight=f.unsqueeze(2), groups=num_channels) + x = conv2d(input=x, weight=f.unsqueeze(3), groups=num_channels) + + # Downsample by throwing away pixels. + x = x[:, :, ::downy, ::downx] + return x + + +def downsample2d(x, f, down=2, padding=0, flip_filter=False, gain=1, impl="cuda"): + r"""Downsample a batch of 2D images using the given 2D FIR filter. + + By default, the result is padded so that its shape is a fraction of the input. + User-specified padding is applied on top of that, with negative values + indicating cropping. Pixels outside the image are assumed to be zero. + + Args: + x: Float32/float64/float16 input tensor of the shape + `[batch_size, num_channels, in_height, in_width]`. + f: Float32 FIR filter of the shape + `[filter_height, filter_width]` (non-separable), + `[filter_taps]` (separable), or + `None` (identity). + down: Integer downsampling factor. Can be a single int or a list/tuple + `[x, y]` (default: 1). + padding: Padding with respect to the input. Can be a single number or a + list/tuple `[x, y]` or `[x_before, x_after, y_before, y_after]` + (default: 0). + flip_filter: False = convolution, True = correlation (default: False). + gain: Overall scaling factor for signal magnitude (default: 1). + impl: Implementation to use. Can be `'ref'` or `'cuda'` (default: `'cuda'`). + + Returns: + Tensor of the shape `[batch_size, num_channels, out_height, out_width]`. + """ + downx, downy = _parse_scaling(down) + # padx0, padx1, pady0, pady1 = _parse_padding(padding) + padx0, padx1, pady0, pady1 = padding, padding, padding, padding + + fw, fh = _get_filter_size(f) + p = [ + padx0 + (fw - downx + 1) // 2, + padx1 + (fw - downx) // 2, + pady0 + (fh - downy + 1) // 2, + pady1 + (fh - downy) // 2, + ] + return upfirdn2d( + x, f, down=down, padding=p, flip_filter=flip_filter, gain=gain, impl=impl + ) + + +def upsample2d(x, f, up=2, padding=0, flip_filter=False, gain=1, impl="cuda"): + r"""Upsample a batch of 2D images using the given 2D FIR filter. + + By default, the result is padded so that its shape is a multiple of the input. + User-specified padding is applied on top of that, with negative values + indicating cropping. Pixels outside the image are assumed to be zero. + + Args: + x: Float32/float64/float16 input tensor of the shape + `[batch_size, num_channels, in_height, in_width]`. + f: Float32 FIR filter of the shape + `[filter_height, filter_width]` (non-separable), + `[filter_taps]` (separable), or + `None` (identity). + up: Integer upsampling factor. Can be a single int or a list/tuple + `[x, y]` (default: 1). + padding: Padding with respect to the output. Can be a single number or a + list/tuple `[x, y]` or `[x_before, x_after, y_before, y_after]` + (default: 0). + flip_filter: False = convolution, True = correlation (default: False). + gain: Overall scaling factor for signal magnitude (default: 1). + impl: Implementation to use. Can be `'ref'` or `'cuda'` (default: `'cuda'`). + + Returns: + Tensor of the shape `[batch_size, num_channels, out_height, out_width]`. + """ + upx, upy = _parse_scaling(up) + # upx, upy = up, up + padx0, padx1, pady0, pady1 = _parse_padding(padding) + # padx0, padx1, pady0, pady1 = padding, padding, padding, padding + fw, fh = _get_filter_size(f) + p = [ + padx0 + (fw + upx - 1) // 2, + padx1 + (fw - upx) // 2, + pady0 + (fh + upy - 1) // 2, + pady1 + (fh - upy) // 2, + ] + return upfirdn2d( + x, + f, + up=up, + padding=p, + flip_filter=flip_filter, + gain=gain * upx * upy, + impl=impl, + ) + + +class MinibatchStdLayer(torch.nn.Module): + def __init__(self, group_size, num_channels=1): + super().__init__() + self.group_size = group_size + self.num_channels = num_channels + + def forward(self, x): + N, C, H, W = x.shape + G = ( + torch.min(torch.as_tensor(self.group_size), torch.as_tensor(N)) + if self.group_size is not None + else N + ) + F = self.num_channels + c = C // F + + y = x.reshape( + G, -1, F, c, H, W + ) # [GnFcHW] Split minibatch N into n groups of size G, and channels C into F groups of size c. + y = y - y.mean(dim=0) # [GnFcHW] Subtract mean over group. + y = y.square().mean(dim=0) # [nFcHW] Calc variance over group. + y = (y + 1e-8).sqrt() # [nFcHW] Calc stddev over group. + y = y.mean(dim=[2, 3, 4]) # [nF] Take average over channels and pixels. + y = y.reshape(-1, F, 1, 1) # [nF11] Add missing dimensions. + y = y.repeat(G, 1, H, W) # [NFHW] Replicate over group and pixels. + x = torch.cat([x, y], dim=1) # [NCHW] Append to input as new channels. + return x + + +class FullyConnectedLayer(torch.nn.Module): + def __init__( + self, + in_features, # Number of input features. + out_features, # Number of output features. + bias=True, # Apply additive bias before the activation function? + activation="linear", # Activation function: 'relu', 'lrelu', etc. + lr_multiplier=1, # Learning rate multiplier. + bias_init=0, # Initial value for the additive bias. + ): + super().__init__() + self.weight = torch.nn.Parameter( + torch.randn([out_features, in_features]) / lr_multiplier + ) + self.bias = ( + torch.nn.Parameter(torch.full([out_features], np.float32(bias_init))) + if bias + else None + ) + self.activation = activation + + self.weight_gain = lr_multiplier / np.sqrt(in_features) + self.bias_gain = lr_multiplier + + def forward(self, x): + w = self.weight * self.weight_gain + b = self.bias + if b is not None and self.bias_gain != 1: + b = b * self.bias_gain + + if self.activation == "linear" and b is not None: + # out = torch.addmm(b.unsqueeze(0), x, w.t()) + x = x.matmul(w.t()) + out = x + b.reshape([-1 if i == x.ndim - 1 else 1 for i in range(x.ndim)]) + else: + x = x.matmul(w.t()) + out = bias_act(x, b, act=self.activation, dim=x.ndim - 1) + return out + + +def _conv2d_wrapper( + x, w, stride=1, padding=0, groups=1, transpose=False, flip_weight=True +): + """Wrapper for the underlying `conv2d()` and `conv_transpose2d()` implementations.""" + out_channels, in_channels_per_group, kh, kw = _get_weight_shape(w) + + # Flip weight if requested. + if ( + not flip_weight + ): # conv2d() actually performs correlation (flip_weight=True) not convolution (flip_weight=False). + w = w.flip([2, 3]) + + # Workaround performance pitfall in cuDNN 8.0.5, triggered when using + # 1x1 kernel + memory_format=channels_last + less than 64 channels. + if ( + kw == 1 + and kh == 1 + and stride == 1 + and padding in [0, [0, 0], (0, 0)] + and not transpose + ): + if x.stride()[1] == 1 and min(out_channels, in_channels_per_group) < 64: + if out_channels <= 4 and groups == 1: + in_shape = x.shape + x = w.squeeze(3).squeeze(2) @ x.reshape( + [in_shape[0], in_channels_per_group, -1] + ) + x = x.reshape([in_shape[0], out_channels, in_shape[2], in_shape[3]]) + else: + x = x.to(memory_format=torch.contiguous_format) + w = w.to(memory_format=torch.contiguous_format) + x = conv2d(x, w, groups=groups) + return x.to(memory_format=torch.channels_last) + + # Otherwise => execute using conv2d_gradfix. + op = conv_transpose2d if transpose else conv2d + return op(x, w, stride=stride, padding=padding, groups=groups) + + +def conv2d_resample( + x, w, f=None, up=1, down=1, padding=0, groups=1, flip_weight=True, flip_filter=False +): + r"""2D convolution with optional up/downsampling. + + Padding is performed only once at the beginning, not between the operations. + + Args: + x: Input tensor of shape + `[batch_size, in_channels, in_height, in_width]`. + w: Weight tensor of shape + `[out_channels, in_channels//groups, kernel_height, kernel_width]`. + f: Low-pass filter for up/downsampling. Must be prepared beforehand by + calling setup_filter(). None = identity (default). + up: Integer upsampling factor (default: 1). + down: Integer downsampling factor (default: 1). + padding: Padding with respect to the upsampled image. Can be a single number + or a list/tuple `[x, y]` or `[x_before, x_after, y_before, y_after]` + (default: 0). + groups: Split input channels into N groups (default: 1). + flip_weight: False = convolution, True = correlation (default: True). + flip_filter: False = convolution, True = correlation (default: False). + + Returns: + Tensor of the shape `[batch_size, num_channels, out_height, out_width]`. + """ + # Validate arguments. + assert isinstance(x, torch.Tensor) and (x.ndim == 4) + assert isinstance(w, torch.Tensor) and (w.ndim == 4) and (w.dtype == x.dtype) + assert f is None or (isinstance(f, torch.Tensor) and f.ndim in [1, 2]) + assert isinstance(up, int) and (up >= 1) + assert isinstance(down, int) and (down >= 1) + # assert isinstance(groups, int) and (groups >= 1), f"!!!!!! groups: {groups} isinstance(groups, int) {isinstance(groups, int)} {type(groups)}" + out_channels, in_channels_per_group, kh, kw = _get_weight_shape(w) + fw, fh = _get_filter_size(f) + # px0, px1, py0, py1 = _parse_padding(padding) + px0, px1, py0, py1 = padding, padding, padding, padding + + # Adjust padding to account for up/downsampling. + if up > 1: + px0 += (fw + up - 1) // 2 + px1 += (fw - up) // 2 + py0 += (fh + up - 1) // 2 + py1 += (fh - up) // 2 + if down > 1: + px0 += (fw - down + 1) // 2 + px1 += (fw - down) // 2 + py0 += (fh - down + 1) // 2 + py1 += (fh - down) // 2 + + # Fast path: 1x1 convolution with downsampling only => downsample first, then convolve. + if kw == 1 and kh == 1 and (down > 1 and up == 1): + x = upfirdn2d( + x=x, f=f, down=down, padding=[px0, px1, py0, py1], flip_filter=flip_filter + ) + x = _conv2d_wrapper(x=x, w=w, groups=groups, flip_weight=flip_weight) + return x + + # Fast path: 1x1 convolution with upsampling only => convolve first, then upsample. + if kw == 1 and kh == 1 and (up > 1 and down == 1): + x = _conv2d_wrapper(x=x, w=w, groups=groups, flip_weight=flip_weight) + x = upfirdn2d( + x=x, + f=f, + up=up, + padding=[px0, px1, py0, py1], + gain=up**2, + flip_filter=flip_filter, + ) + return x + + # Fast path: downsampling only => use strided convolution. + if down > 1 and up == 1: + x = upfirdn2d(x=x, f=f, padding=[px0, px1, py0, py1], flip_filter=flip_filter) + x = _conv2d_wrapper( + x=x, w=w, stride=down, groups=groups, flip_weight=flip_weight + ) + return x + + # Fast path: upsampling with optional downsampling => use transpose strided convolution. + if up > 1: + if groups == 1: + w = w.transpose(0, 1) + else: + w = w.reshape(groups, out_channels // groups, in_channels_per_group, kh, kw) + w = w.transpose(1, 2) + w = w.reshape( + groups * in_channels_per_group, out_channels // groups, kh, kw + ) + px0 -= kw - 1 + px1 -= kw - up + py0 -= kh - 1 + py1 -= kh - up + pxt = max(min(-px0, -px1), 0) + pyt = max(min(-py0, -py1), 0) + x = _conv2d_wrapper( + x=x, + w=w, + stride=up, + padding=[pyt, pxt], + groups=groups, + transpose=True, + flip_weight=(not flip_weight), + ) + x = upfirdn2d( + x=x, + f=f, + padding=[px0 + pxt, px1 + pxt, py0 + pyt, py1 + pyt], + gain=up**2, + flip_filter=flip_filter, + ) + if down > 1: + x = upfirdn2d(x=x, f=f, down=down, flip_filter=flip_filter) + return x + + # Fast path: no up/downsampling, padding supported by the underlying implementation => use plain conv2d. + if up == 1 and down == 1: + if px0 == px1 and py0 == py1 and px0 >= 0 and py0 >= 0: + return _conv2d_wrapper( + x=x, w=w, padding=[py0, px0], groups=groups, flip_weight=flip_weight + ) + + # Fallback: Generic reference implementation. + x = upfirdn2d( + x=x, + f=(f if up > 1 else None), + up=up, + padding=[px0, px1, py0, py1], + gain=up**2, + flip_filter=flip_filter, + ) + x = _conv2d_wrapper(x=x, w=w, groups=groups, flip_weight=flip_weight) + if down > 1: + x = upfirdn2d(x=x, f=f, down=down, flip_filter=flip_filter) + return x + + +class Conv2dLayer(torch.nn.Module): + def __init__( + self, + in_channels, # Number of input channels. + out_channels, # Number of output channels. + kernel_size, # Width and height of the convolution kernel. + bias=True, # Apply additive bias before the activation function? + activation="linear", # Activation function: 'relu', 'lrelu', etc. + up=1, # Integer upsampling factor. + down=1, # Integer downsampling factor. + resample_filter=[ + 1, + 3, + 3, + 1, + ], # Low-pass filter to apply when resampling activations. + conv_clamp=None, # Clamp the output to +-X, None = disable clamping. + channels_last=False, # Expect the input to have memory_format=channels_last? + trainable=True, # Update the weights of this layer during training? + ): + super().__init__() + self.activation = activation + self.up = up + self.down = down + self.register_buffer("resample_filter", setup_filter(resample_filter)) + self.conv_clamp = conv_clamp + self.padding = kernel_size // 2 + self.weight_gain = 1 / np.sqrt(in_channels * (kernel_size**2)) + self.act_gain = activation_funcs[activation].def_gain + + memory_format = ( + torch.channels_last if channels_last else torch.contiguous_format + ) + weight = torch.randn([out_channels, in_channels, kernel_size, kernel_size]).to( + memory_format=memory_format + ) + bias = torch.zeros([out_channels]) if bias else None + if trainable: + self.weight = torch.nn.Parameter(weight) + self.bias = torch.nn.Parameter(bias) if bias is not None else None + else: + self.register_buffer("weight", weight) + if bias is not None: + self.register_buffer("bias", bias) + else: + self.bias = None + + def forward(self, x, gain=1): + w = self.weight * self.weight_gain + x = conv2d_resample( + x=x, + w=w, + f=self.resample_filter, + up=self.up, + down=self.down, + padding=self.padding, + ) + + act_gain = self.act_gain * gain + act_clamp = self.conv_clamp * gain if self.conv_clamp is not None else None + out = bias_act( + x, self.bias, act=self.activation, gain=act_gain, clamp=act_clamp + ) + return out + + +def torch_gc(): + if torch.cuda.is_available(): + torch.cuda.empty_cache() + torch.cuda.ipc_collect() + gc.collect() + + +def set_seed(seed: int): + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + torch.cuda.manual_seed_all(seed) + + +def get_scheduler(sd_sampler, scheduler_config): + # https://github.com/huggingface/diffusers/issues/4167 + keys_to_pop = ["use_karras_sigmas", "algorithm_type"] + scheduler_config = dict(scheduler_config) + for it in keys_to_pop: + scheduler_config.pop(it, None) + + # fmt: off + samplers = { + SDSampler.dpm_plus_plus_2m: [DPMSolverMultistepScheduler], + SDSampler.dpm_plus_plus_2m_karras: [DPMSolverMultistepScheduler, dict(use_karras_sigmas=True)], + SDSampler.dpm_plus_plus_2m_sde: [DPMSolverMultistepScheduler, dict(algorithm_type="sde-dpmsolver++")], + SDSampler.dpm_plus_plus_2m_sde_karras: [DPMSolverMultistepScheduler, dict(algorithm_type="sde-dpmsolver++", use_karras_sigmas=True)], + SDSampler.dpm_plus_plus_sde: [DPMSolverSinglestepScheduler], + SDSampler.dpm_plus_plus_sde_karras: [DPMSolverSinglestepScheduler, dict(use_karras_sigmas=True)], + SDSampler.dpm2: [KDPM2DiscreteScheduler], + SDSampler.dpm2_karras: [KDPM2DiscreteScheduler, dict(use_karras_sigmas=True)], + SDSampler.dpm2_a: [KDPM2AncestralDiscreteScheduler], + SDSampler.dpm2_a_karras: [KDPM2AncestralDiscreteScheduler, dict(use_karras_sigmas=True)], + SDSampler.euler: [EulerDiscreteScheduler], + SDSampler.euler_a: [EulerAncestralDiscreteScheduler], + SDSampler.heun: [HeunDiscreteScheduler], + SDSampler.lms: [LMSDiscreteScheduler], + SDSampler.lms_karras: [LMSDiscreteScheduler, dict(use_karras_sigmas=True)], + SDSampler.ddim: [DDIMScheduler], + SDSampler.pndm: [PNDMScheduler], + SDSampler.uni_pc: [UniPCMultistepScheduler], + SDSampler.lcm: [LCMScheduler], + } + # fmt: on + if sd_sampler in samplers: + if len(samplers[sd_sampler]) == 2: + scheduler_cls, kwargs = samplers[sd_sampler] + else: + scheduler_cls, kwargs = samplers[sd_sampler][0], {} + return scheduler_cls.from_config(scheduler_config, **kwargs) + else: + raise ValueError(sd_sampler) + + +def is_local_files_only(**kwargs) -> bool: + from huggingface_hub.constants import HF_HUB_OFFLINE + + return HF_HUB_OFFLINE or kwargs.get("local_files_only", False) + + +def handle_from_pretrained_exceptions(func, **kwargs): + try: + return func(**kwargs) + except ValueError as e: + if "You are trying to load the model files of the `variant=fp16`" in str(e): + logger.info("variant=fp16 not found, try revision=fp16") + try: + return func(**{**kwargs, "variant": None, "revision": "fp16"}) + except Exception as e: + logger.info("revision=fp16 not found, try revision=main") + return func(**{**kwargs, "variant": None, "revision": "main"}) + raise e + except OSError as e: + previous_traceback = traceback.format_exc() + if "RevisionNotFoundError: 404 Client Error." in previous_traceback: + logger.info("revision=fp16 not found, try revision=main") + return func(**{**kwargs, "variant": None, "revision": "main"}) + elif "Max retries exceeded" in previous_traceback: + logger.exception( + "Fetching model from HuggingFace failed. " + "If this is your first time downloading the model, you may need to set up proxy in terminal." + "If the model has already been downloaded, you can add --local-files-only when starting." + ) + exit(-1) + raise e + except Exception as e: + raise e + + +def get_torch_dtype(device, no_half: bool): + device = str(device) + use_fp16 = not no_half + use_gpu = device == "cuda" + # https://github.com/huggingface/diffusers/issues/4480 + # pipe.enable_attention_slicing and float16 will cause black output on mps + # if device in ["cuda", "mps"] and use_fp16: + if device in ["cuda"] and use_fp16: + return use_gpu, torch.float16 + return use_gpu, torch.float32 + + +def enable_low_mem(pipe, enable: bool): + if torch.backends.mps.is_available(): + # https://huggingface.co/docs/diffusers/v0.25.0/en/api/pipelines/stable_diffusion/image_variation#diffusers.StableDiffusionImageVariationPipeline.enable_attention_slicing + # CUDA: Don't enable attention slicing if you're already using `scaled_dot_product_attention` (SDPA) from PyTorch 2.0 or xFormers. + if enable: + pipe.enable_attention_slicing("max") + else: + # https://huggingface.co/docs/diffusers/optimization/mps + # Devices with less than 64GB of memory are recommended to use enable_attention_slicing + pipe.enable_attention_slicing() + + if enable: + pipe.vae.enable_tiling() diff --git a/py/iopaint/model/zits.py b/py/iopaint/model/zits.py new file mode 100644 index 0000000..57c71ab --- /dev/null +++ b/py/iopaint/model/zits.py @@ -0,0 +1,476 @@ +import os +import time + +import cv2 +import torch +import torch.nn.functional as F + +from ..helper import get_cache_path_by_url, load_jit_model, download_model +from ..schema import InpaintRequest +import numpy as np + +from .base import InpaintModel + +ZITS_INPAINT_MODEL_URL = os.environ.get( + "ZITS_INPAINT_MODEL_URL", + "https://github.com/Sanster/models/releases/download/add_zits/zits-inpaint-0717.pt", +) +ZITS_INPAINT_MODEL_MD5 = os.environ.get( + "ZITS_INPAINT_MODEL_MD5", "9978cc7157dc29699e42308d675b2154" +) + +ZITS_EDGE_LINE_MODEL_URL = os.environ.get( + "ZITS_EDGE_LINE_MODEL_URL", + "https://github.com/Sanster/models/releases/download/add_zits/zits-edge-line-0717.pt", +) +ZITS_EDGE_LINE_MODEL_MD5 = os.environ.get( + "ZITS_EDGE_LINE_MODEL_MD5", "55e31af21ba96bbf0c80603c76ea8c5f" +) + +ZITS_STRUCTURE_UPSAMPLE_MODEL_URL = os.environ.get( + "ZITS_STRUCTURE_UPSAMPLE_MODEL_URL", + "https://github.com/Sanster/models/releases/download/add_zits/zits-structure-upsample-0717.pt", +) +ZITS_STRUCTURE_UPSAMPLE_MODEL_MD5 = os.environ.get( + "ZITS_STRUCTURE_UPSAMPLE_MODEL_MD5", "3d88a07211bd41b2ec8cc0d999f29927" +) + +ZITS_WIRE_FRAME_MODEL_URL = os.environ.get( + "ZITS_WIRE_FRAME_MODEL_URL", + "https://github.com/Sanster/models/releases/download/add_zits/zits-wireframe-0717.pt", +) +ZITS_WIRE_FRAME_MODEL_MD5 = os.environ.get( + "ZITS_WIRE_FRAME_MODEL_MD5", "a9727c63a8b48b65c905d351b21ce46b" +) + + +def resize(img, height, width, center_crop=False): + imgh, imgw = img.shape[0:2] + + if center_crop and imgh != imgw: + # center crop + side = np.minimum(imgh, imgw) + j = (imgh - side) // 2 + i = (imgw - side) // 2 + img = img[j : j + side, i : i + side, ...] + + if imgh > height and imgw > width: + inter = cv2.INTER_AREA + else: + inter = cv2.INTER_LINEAR + img = cv2.resize(img, (height, width), interpolation=inter) + + return img + + +def to_tensor(img, scale=True, norm=False): + if img.ndim == 2: + img = img[:, :, np.newaxis] + c = img.shape[-1] + + if scale: + img_t = torch.from_numpy(img).permute(2, 0, 1).float().div(255) + else: + img_t = torch.from_numpy(img).permute(2, 0, 1).float() + + if norm: + mean = torch.tensor([0.5, 0.5, 0.5]).reshape(c, 1, 1) + std = torch.tensor([0.5, 0.5, 0.5]).reshape(c, 1, 1) + img_t = (img_t - mean) / std + return img_t + + +def load_masked_position_encoding(mask): + ones_filter = np.ones((3, 3), dtype=np.float32) + d_filter1 = np.array([[1, 1, 0], [1, 1, 0], [0, 0, 0]], dtype=np.float32) + d_filter2 = np.array([[0, 0, 0], [1, 1, 0], [1, 1, 0]], dtype=np.float32) + d_filter3 = np.array([[0, 1, 1], [0, 1, 1], [0, 0, 0]], dtype=np.float32) + d_filter4 = np.array([[0, 0, 0], [0, 1, 1], [0, 1, 1]], dtype=np.float32) + str_size = 256 + pos_num = 128 + + ori_mask = mask.copy() + ori_h, ori_w = ori_mask.shape[0:2] + ori_mask = ori_mask / 255 + mask = cv2.resize(mask, (str_size, str_size), interpolation=cv2.INTER_AREA) + mask[mask > 0] = 255 + h, w = mask.shape[0:2] + mask3 = mask.copy() + mask3 = 1.0 - (mask3 / 255.0) + pos = np.zeros((h, w), dtype=np.int32) + direct = np.zeros((h, w, 4), dtype=np.int32) + i = 0 + while np.sum(1 - mask3) > 0: + i += 1 + mask3_ = cv2.filter2D(mask3, -1, ones_filter) + mask3_[mask3_ > 0] = 1 + sub_mask = mask3_ - mask3 + pos[sub_mask == 1] = i + + m = cv2.filter2D(mask3, -1, d_filter1) + m[m > 0] = 1 + m = m - mask3 + direct[m == 1, 0] = 1 + + m = cv2.filter2D(mask3, -1, d_filter2) + m[m > 0] = 1 + m = m - mask3 + direct[m == 1, 1] = 1 + + m = cv2.filter2D(mask3, -1, d_filter3) + m[m > 0] = 1 + m = m - mask3 + direct[m == 1, 2] = 1 + + m = cv2.filter2D(mask3, -1, d_filter4) + m[m > 0] = 1 + m = m - mask3 + direct[m == 1, 3] = 1 + + mask3 = mask3_ + + abs_pos = pos.copy() + rel_pos = pos / (str_size / 2) # to 0~1 maybe larger than 1 + rel_pos = (rel_pos * pos_num).astype(np.int32) + rel_pos = np.clip(rel_pos, 0, pos_num - 1) + + if ori_w != w or ori_h != h: + rel_pos = cv2.resize(rel_pos, (ori_w, ori_h), interpolation=cv2.INTER_NEAREST) + rel_pos[ori_mask == 0] = 0 + direct = cv2.resize(direct, (ori_w, ori_h), interpolation=cv2.INTER_NEAREST) + direct[ori_mask == 0, :] = 0 + + return rel_pos, abs_pos, direct + + +def load_image(img, mask, device, sigma256=3.0): + """ + Args: + img: [H, W, C] RGB + mask: [H, W] 255 为 masks 区域 + sigma256: + + Returns: + + """ + h, w, _ = img.shape + imgh, imgw = img.shape[0:2] + img_256 = resize(img, 256, 256) + + mask = (mask > 127).astype(np.uint8) * 255 + mask_256 = cv2.resize(mask, (256, 256), interpolation=cv2.INTER_AREA) + mask_256[mask_256 > 0] = 255 + + mask_512 = cv2.resize(mask, (512, 512), interpolation=cv2.INTER_AREA) + mask_512[mask_512 > 0] = 255 + + # original skimage implemention + # https://scikit-image.org/docs/stable/api/skimage.feature.html#skimage.feature.canny + # low_threshold: Lower bound for hysteresis thresholding (linking edges). If None, low_threshold is set to 10% of dtype’s max. + # high_threshold: Upper bound for hysteresis thresholding (linking edges). If None, high_threshold is set to 20% of dtype’s max. + + try: + import skimage + + gray_256 = skimage.color.rgb2gray(img_256) + edge_256 = skimage.feature.canny(gray_256, sigma=3.0, mask=None).astype(float) + # cv2.imwrite("skimage_gray.jpg", (gray_256*255).astype(np.uint8)) + # cv2.imwrite("skimage_edge.jpg", (edge_256*255).astype(np.uint8)) + except: + gray_256 = cv2.cvtColor(img_256, cv2.COLOR_RGB2GRAY) + gray_256_blured = cv2.GaussianBlur( + gray_256, ksize=(7, 7), sigmaX=sigma256, sigmaY=sigma256 + ) + edge_256 = cv2.Canny( + gray_256_blured, threshold1=int(255 * 0.1), threshold2=int(255 * 0.2) + ) + + # cv2.imwrite("opencv_edge.jpg", edge_256) + + # line + img_512 = resize(img, 512, 512) + + rel_pos, abs_pos, direct = load_masked_position_encoding(mask) + + batch = dict() + batch["images"] = to_tensor(img.copy()).unsqueeze(0).to(device) + batch["img_256"] = to_tensor(img_256, norm=True).unsqueeze(0).to(device) + batch["masks"] = to_tensor(mask).unsqueeze(0).to(device) + batch["mask_256"] = to_tensor(mask_256).unsqueeze(0).to(device) + batch["mask_512"] = to_tensor(mask_512).unsqueeze(0).to(device) + batch["edge_256"] = to_tensor(edge_256, scale=False).unsqueeze(0).to(device) + batch["img_512"] = to_tensor(img_512).unsqueeze(0).to(device) + batch["rel_pos"] = torch.LongTensor(rel_pos).unsqueeze(0).to(device) + batch["abs_pos"] = torch.LongTensor(abs_pos).unsqueeze(0).to(device) + batch["direct"] = torch.LongTensor(direct).unsqueeze(0).to(device) + batch["h"] = imgh + batch["w"] = imgw + + return batch + + +def to_device(data, device): + if isinstance(data, torch.Tensor): + return data.to(device) + if isinstance(data, dict): + for key in data: + if isinstance(data[key], torch.Tensor): + data[key] = data[key].to(device) + return data + if isinstance(data, list): + return [to_device(d, device) for d in data] + + +class ZITS(InpaintModel): + name = "zits" + min_size = 256 + pad_mod = 32 + pad_to_square = True + is_erase_model = True + + def __init__(self, device, **kwargs): + """ + + Args: + device: + """ + super().__init__(device) + self.device = device + self.sample_edge_line_iterations = 1 + + def init_model(self, device, **kwargs): + self.wireframe = load_jit_model( + ZITS_WIRE_FRAME_MODEL_URL, device, ZITS_WIRE_FRAME_MODEL_MD5 + ) + self.edge_line = load_jit_model( + ZITS_EDGE_LINE_MODEL_URL, device, ZITS_EDGE_LINE_MODEL_MD5 + ) + self.structure_upsample = load_jit_model( + ZITS_STRUCTURE_UPSAMPLE_MODEL_URL, device, ZITS_STRUCTURE_UPSAMPLE_MODEL_MD5 + ) + self.inpaint = load_jit_model( + ZITS_INPAINT_MODEL_URL, device, ZITS_INPAINT_MODEL_MD5 + ) + + @staticmethod + def download(): + download_model(ZITS_WIRE_FRAME_MODEL_URL, ZITS_WIRE_FRAME_MODEL_MD5) + download_model(ZITS_EDGE_LINE_MODEL_URL, ZITS_EDGE_LINE_MODEL_MD5) + download_model( + ZITS_STRUCTURE_UPSAMPLE_MODEL_URL, ZITS_STRUCTURE_UPSAMPLE_MODEL_MD5 + ) + download_model(ZITS_INPAINT_MODEL_URL, ZITS_INPAINT_MODEL_MD5) + + @staticmethod + def is_downloaded() -> bool: + model_paths = [ + get_cache_path_by_url(ZITS_WIRE_FRAME_MODEL_URL), + get_cache_path_by_url(ZITS_EDGE_LINE_MODEL_URL), + get_cache_path_by_url(ZITS_STRUCTURE_UPSAMPLE_MODEL_URL), + get_cache_path_by_url(ZITS_INPAINT_MODEL_URL), + ] + return all([os.path.exists(it) for it in model_paths]) + + def wireframe_edge_and_line(self, items, enable: bool): + # 最终向 items 中添加 edge 和 line key + if not enable: + items["edge"] = torch.zeros_like(items["masks"]) + items["line"] = torch.zeros_like(items["masks"]) + return + + start = time.time() + try: + line_256 = self.wireframe_forward( + items["img_512"], + h=256, + w=256, + masks=items["mask_512"], + mask_th=0.85, + ) + except: + line_256 = torch.zeros_like(items["mask_256"]) + + print(f"wireframe_forward time: {(time.time() - start) * 1000:.2f}ms") + + # np_line = (line[0][0].numpy() * 255).astype(np.uint8) + # cv2.imwrite("line.jpg", np_line) + + start = time.time() + edge_pred, line_pred = self.sample_edge_line_logits( + context=[items["img_256"], items["edge_256"], line_256], + mask=items["mask_256"].clone(), + iterations=self.sample_edge_line_iterations, + add_v=0.05, + mul_v=4, + ) + print(f"sample_edge_line_logits time: {(time.time() - start) * 1000:.2f}ms") + + # np_edge_pred = (edge_pred[0][0].numpy() * 255).astype(np.uint8) + # cv2.imwrite("edge_pred.jpg", np_edge_pred) + # np_line_pred = (line_pred[0][0].numpy() * 255).astype(np.uint8) + # cv2.imwrite("line_pred.jpg", np_line_pred) + # exit() + + input_size = min(items["h"], items["w"]) + if input_size != 256 and input_size > 256: + while edge_pred.shape[2] < input_size: + edge_pred = self.structure_upsample(edge_pred) + edge_pred = torch.sigmoid((edge_pred + 2) * 2) + + line_pred = self.structure_upsample(line_pred) + line_pred = torch.sigmoid((line_pred + 2) * 2) + + edge_pred = F.interpolate( + edge_pred, + size=(input_size, input_size), + mode="bilinear", + align_corners=False, + ) + line_pred = F.interpolate( + line_pred, + size=(input_size, input_size), + mode="bilinear", + align_corners=False, + ) + + # np_edge_pred = (edge_pred[0][0].numpy() * 255).astype(np.uint8) + # cv2.imwrite("edge_pred_upsample.jpg", np_edge_pred) + # np_line_pred = (line_pred[0][0].numpy() * 255).astype(np.uint8) + # cv2.imwrite("line_pred_upsample.jpg", np_line_pred) + # exit() + + items["edge"] = edge_pred.detach() + items["line"] = line_pred.detach() + + @torch.no_grad() + def forward(self, image, mask, config: InpaintRequest): + """Input images and output images have same size + images: [H, W, C] RGB + masks: [H, W] + return: BGR IMAGE + """ + mask = mask[:, :, 0] + items = load_image(image, mask, device=self.device) + + self.wireframe_edge_and_line(items, config.zits_wireframe) + + inpainted_image = self.inpaint( + items["images"], + items["masks"], + items["edge"], + items["line"], + items["rel_pos"], + items["direct"], + ) + + inpainted_image = inpainted_image * 255.0 + inpainted_image = ( + inpainted_image.cpu().permute(0, 2, 3, 1)[0].numpy().astype(np.uint8) + ) + inpainted_image = inpainted_image[:, :, ::-1] + + # cv2.imwrite("inpainted.jpg", inpainted_image) + # exit() + + return inpainted_image + + def wireframe_forward(self, images, h, w, masks, mask_th=0.925): + lcnn_mean = torch.tensor([109.730, 103.832, 98.681]).reshape(1, 3, 1, 1) + lcnn_std = torch.tensor([22.275, 22.124, 23.229]).reshape(1, 3, 1, 1) + images = images * 255.0 + # the masks value of lcnn is 127.5 + masked_images = images * (1 - masks) + torch.ones_like(images) * masks * 127.5 + masked_images = (masked_images - lcnn_mean) / lcnn_std + + def to_int(x): + return tuple(map(int, x)) + + lines_tensor = [] + lmap = np.zeros((h, w)) + + output_masked = self.wireframe(masked_images) + + output_masked = to_device(output_masked, "cpu") + if output_masked["num_proposals"] == 0: + lines_masked = [] + scores_masked = [] + else: + lines_masked = output_masked["lines_pred"].numpy() + lines_masked = [ + [line[1] * h, line[0] * w, line[3] * h, line[2] * w] + for line in lines_masked + ] + scores_masked = output_masked["lines_score"].numpy() + + for line, score in zip(lines_masked, scores_masked): + if score > mask_th: + try: + import skimage + + rr, cc, value = skimage.draw.line_aa( + *to_int(line[0:2]), *to_int(line[2:4]) + ) + lmap[rr, cc] = np.maximum(lmap[rr, cc], value) + except: + cv2.line( + lmap, + to_int(line[0:2][::-1]), + to_int(line[2:4][::-1]), + (1, 1, 1), + 1, + cv2.LINE_AA, + ) + + lmap = np.clip(lmap * 255, 0, 255).astype(np.uint8) + lines_tensor.append(to_tensor(lmap).unsqueeze(0)) + + lines_tensor = torch.cat(lines_tensor, dim=0) + return lines_tensor.detach().to(self.device) + + def sample_edge_line_logits( + self, context, mask=None, iterations=1, add_v=0, mul_v=4 + ): + [img, edge, line] = context + + img = img * (1 - mask) + edge = edge * (1 - mask) + line = line * (1 - mask) + + for i in range(iterations): + edge_logits, line_logits = self.edge_line(img, edge, line, masks=mask) + + edge_pred = torch.sigmoid(edge_logits) + line_pred = torch.sigmoid((line_logits + add_v) * mul_v) + edge = edge + edge_pred * mask + edge[edge >= 0.25] = 1 + edge[edge < 0.25] = 0 + line = line + line_pred * mask + + b, _, h, w = edge_pred.shape + edge_pred = edge_pred.reshape(b, -1, 1) + line_pred = line_pred.reshape(b, -1, 1) + mask = mask.reshape(b, -1) + + edge_probs = torch.cat([1 - edge_pred, edge_pred], dim=-1) + line_probs = torch.cat([1 - line_pred, line_pred], dim=-1) + edge_probs[:, :, 1] += 0.5 + line_probs[:, :, 1] += 0.5 + edge_max_probs = edge_probs.max(dim=-1)[0] + (1 - mask) * (-100) + line_max_probs = line_probs.max(dim=-1)[0] + (1 - mask) * (-100) + + indices = torch.sort( + edge_max_probs + line_max_probs, dim=-1, descending=True + )[1] + + for ii in range(b): + keep = int((i + 1) / iterations * torch.sum(mask[ii, ...])) + + assert torch.sum(mask[ii][indices[ii, :keep]]) == keep, "Error!!!" + mask[ii][indices[ii, :keep]] = 0 + + mask = mask.reshape(b, 1, h, w) + edge = edge * (1 - mask) + line = line * (1 - mask) + + edge, line = edge.to(torch.float32), line.to(torch.float32) + return edge, line diff --git a/py/iopaint/model_info.py b/py/iopaint/model_info.py new file mode 100644 index 0000000..5929543 --- /dev/null +++ b/py/iopaint/model_info.py @@ -0,0 +1,103 @@ +from typing import List + +from pydantic import computed_field, BaseModel + +from .const import ( + SDXL_CONTROLNET_CHOICES, + SD2_CONTROLNET_CHOICES, + SD_CONTROLNET_CHOICES, + INSTRUCT_PIX2PIX_NAME, + KANDINSKY22_NAME, + POWERPAINT_NAME, + ANYTEXT_NAME, +) +from .schema import ModelType + + +class ModelInfo(BaseModel): + name: str + path: str + model_type: ModelType + is_single_file_diffusers: bool = False + + @computed_field + @property + def need_prompt(self) -> bool: + return self.model_type in [ + ModelType.DIFFUSERS_SD, + ModelType.DIFFUSERS_SDXL, + ModelType.DIFFUSERS_SD_INPAINT, + ModelType.DIFFUSERS_SDXL_INPAINT, + ] or self.name in [ + INSTRUCT_PIX2PIX_NAME, + KANDINSKY22_NAME, + POWERPAINT_NAME, + ANYTEXT_NAME, + ] + + @computed_field + @property + def controlnets(self) -> List[str]: + if self.model_type in [ + ModelType.DIFFUSERS_SDXL, + ModelType.DIFFUSERS_SDXL_INPAINT, + ]: + return SDXL_CONTROLNET_CHOICES + if self.model_type in [ModelType.DIFFUSERS_SD, ModelType.DIFFUSERS_SD_INPAINT]: + if "sd2" in self.name.lower(): + return SD2_CONTROLNET_CHOICES + else: + return SD_CONTROLNET_CHOICES + if self.name == POWERPAINT_NAME: + return SD_CONTROLNET_CHOICES + return [] + + @computed_field + @property + def support_strength(self) -> bool: + return self.model_type in [ + ModelType.DIFFUSERS_SD, + ModelType.DIFFUSERS_SDXL, + ModelType.DIFFUSERS_SD_INPAINT, + ModelType.DIFFUSERS_SDXL_INPAINT, + ] or self.name in [POWERPAINT_NAME, ANYTEXT_NAME] + + @computed_field + @property + def support_outpainting(self) -> bool: + return self.model_type in [ + ModelType.DIFFUSERS_SD, + ModelType.DIFFUSERS_SDXL, + ModelType.DIFFUSERS_SD_INPAINT, + ModelType.DIFFUSERS_SDXL_INPAINT, + ] or self.name in [KANDINSKY22_NAME, POWERPAINT_NAME] + + @computed_field + @property + def support_lcm_lora(self) -> bool: + return self.model_type in [ + ModelType.DIFFUSERS_SD, + ModelType.DIFFUSERS_SDXL, + ModelType.DIFFUSERS_SD_INPAINT, + ModelType.DIFFUSERS_SDXL_INPAINT, + ] + + @computed_field + @property + def support_controlnet(self) -> bool: + return self.model_type in [ + ModelType.DIFFUSERS_SD, + ModelType.DIFFUSERS_SDXL, + ModelType.DIFFUSERS_SD_INPAINT, + ModelType.DIFFUSERS_SDXL_INPAINT, + ] + + @computed_field + @property + def support_freeu(self) -> bool: + return self.model_type in [ + ModelType.DIFFUSERS_SD, + ModelType.DIFFUSERS_SDXL, + ModelType.DIFFUSERS_SD_INPAINT, + ModelType.DIFFUSERS_SDXL_INPAINT, + ] or self.name in [INSTRUCT_PIX2PIX_NAME] diff --git a/py/iopaint/model_manager.py b/py/iopaint/model_manager.py new file mode 100644 index 0000000..374aabb --- /dev/null +++ b/py/iopaint/model_manager.py @@ -0,0 +1,196 @@ +from typing import List, Dict + +import torch +from loguru import logger +import numpy as np + +from .download import scan_models +from .helper import switch_mps_device +from .model import models, ControlNet, SD, SDXL +from .model.utils import torch_gc, is_local_files_only +from .schema import InpaintRequest, ModelInfo, ModelType + + +class ModelManager: + def __init__(self, name: str, device: torch.device, **kwargs): + self.name = name + self.device = device + self.kwargs = kwargs + self.available_models: Dict[str, ModelInfo] = {} + self.scan_models() + + self.enable_controlnet = kwargs.get("enable_controlnet", False) + controlnet_method = kwargs.get("controlnet_method", None) + if ( + controlnet_method is None + and name in self.available_models + and self.available_models[name].support_controlnet + ): + controlnet_method = self.available_models[name].controlnets[0] + self.controlnet_method = controlnet_method + self.model = self.init_model(name, device, **kwargs) + + @property + def current_model(self) -> ModelInfo: + return self.available_models[self.name] + + def init_model(self, name: str, device, **kwargs): + logger.info(f"Loading model: {name}") + if name not in self.available_models: + raise NotImplementedError( + f"Unsupported model: {name}. Available models: {list(self.available_models.keys())}" + ) + + model_info = self.available_models[name] + kwargs = { + **kwargs, + "model_info": model_info, + "enable_controlnet": self.enable_controlnet, + "controlnet_method": self.controlnet_method, + } + + if model_info.support_controlnet and self.enable_controlnet: + return ControlNet(device, **kwargs) + elif model_info.name in models: + return models[name](device, **kwargs) + else: + if model_info.model_type in [ + ModelType.DIFFUSERS_SD_INPAINT, + ModelType.DIFFUSERS_SD, + ]: + return SD(device, **kwargs) + + if model_info.model_type in [ + ModelType.DIFFUSERS_SDXL_INPAINT, + ModelType.DIFFUSERS_SDXL, + ]: + return SDXL(device, **kwargs) + + raise NotImplementedError(f"Unsupported model: {name}") + + @torch.inference_mode() + def __call__(self, image, mask, config: InpaintRequest): + """ + + Args: + image: [H, W, C] RGB + mask: [H, W, 1] 255 means area to repaint + config: + + Returns: + BGR image + """ + self.switch_controlnet_method(config) + self.enable_disable_freeu(config) + self.enable_disable_lcm_lora(config) + return self.model(image, mask, config).astype(np.uint8) + + def scan_models(self) -> List[ModelInfo]: + available_models = scan_models() + self.available_models = {it.name: it for it in available_models} + return available_models + + def switch(self, new_name: str): + if new_name == self.name: + return + + old_name = self.name + old_controlnet_method = self.controlnet_method + self.name = new_name + + if ( + self.available_models[new_name].support_controlnet + and self.controlnet_method + not in self.available_models[new_name].controlnets + ): + self.controlnet_method = self.available_models[new_name].controlnets[0] + try: + # TODO: enable/disable controlnet without reload model + del self.model + torch_gc() + + self.model = self.init_model( + new_name, switch_mps_device(new_name, self.device), **self.kwargs + ) + except Exception as e: + self.name = old_name + self.controlnet_method = old_controlnet_method + logger.info(f"Switch model from {old_name} to {new_name} failed, rollback") + self.model = self.init_model( + old_name, switch_mps_device(old_name, self.device), **self.kwargs + ) + raise e + + def switch_controlnet_method(self, config): + if not self.available_models[self.name].support_controlnet: + return + + if ( + self.enable_controlnet + and config.controlnet_method + and self.controlnet_method != config.controlnet_method + ): + old_controlnet_method = self.controlnet_method + self.controlnet_method = config.controlnet_method + self.model.switch_controlnet_method(config.controlnet_method) + logger.info( + f"Switch Controlnet method from {old_controlnet_method} to {config.controlnet_method}" + ) + elif self.enable_controlnet != config.enable_controlnet: + self.enable_controlnet = config.enable_controlnet + self.controlnet_method = config.controlnet_method + + pipe_components = { + "vae": self.model.model.vae, + "text_encoder": self.model.model.text_encoder, + "unet": self.model.model.unet, + } + if hasattr(self.model.model, "text_encoder_2"): + pipe_components["text_encoder_2"] = self.model.model.text_encoder_2 + + self.model = self.init_model( + self.name, + switch_mps_device(self.name, self.device), + pipe_components=pipe_components, + **self.kwargs, + ) + if not config.enable_controlnet: + logger.info(f"Disable controlnet") + else: + logger.info(f"Enable controlnet: {config.controlnet_method}") + + def enable_disable_freeu(self, config: InpaintRequest): + if str(self.model.device) == "mps": + return + + if self.available_models[self.name].support_freeu: + if config.sd_freeu: + freeu_config = config.sd_freeu_config + self.model.model.enable_freeu( + s1=freeu_config.s1, + s2=freeu_config.s2, + b1=freeu_config.b1, + b2=freeu_config.b2, + ) + else: + self.model.model.disable_freeu() + + def enable_disable_lcm_lora(self, config: InpaintRequest): + if self.available_models[self.name].support_lcm_lora: + # TODO: change this if load other lora is supported + lcm_lora_loaded = bool(self.model.model.get_list_adapters()) + if config.sd_lcm_lora: + if not lcm_lora_loaded: + logger.info("Load LCM LORA") + self.model.model.load_lora_weights( + self.model.lcm_lora_id, + weight_name="pytorch_lora_weights.safetensors", + local_files_only=is_local_files_only(), + ) + else: + logger.info("Enable LCM LORA") + self.model.model.enable_lora() + else: + if lcm_lora_loaded: + logger.info("Disable LCM LORA") + self.model.model.disable_lora() diff --git a/py/iopaint/plugins/__init__.py b/py/iopaint/plugins/__init__.py new file mode 100644 index 0000000..8128025 --- /dev/null +++ b/py/iopaint/plugins/__init__.py @@ -0,0 +1,74 @@ +from typing import Dict + +from loguru import logger + +from .anime_seg import AnimeSeg +from .gfpgan_plugin import GFPGANPlugin +from .interactive_seg import InteractiveSeg +from .realesrgan import RealESRGANUpscaler +from .remove_bg import RemoveBG +from .restoreformer import RestoreFormerPlugin +from ..schema import InteractiveSegModel, Device, RealESRGANModel + + +def build_plugins( + enable_interactive_seg: bool, + interactive_seg_model: InteractiveSegModel, + interactive_seg_device: Device, + enable_remove_bg: bool, + remove_bg_model: str, + enable_anime_seg: bool, + enable_realesrgan: bool, + realesrgan_device: Device, + realesrgan_model: RealESRGANModel, + enable_gfpgan: bool, + gfpgan_device: Device, + enable_restoreformer: bool, + restoreformer_device: Device, + no_half: bool, +) -> Dict: + plugins = {} + if enable_interactive_seg: + logger.info(f"Initialize {InteractiveSeg.name} plugin") + plugins[InteractiveSeg.name] = InteractiveSeg( + interactive_seg_model, interactive_seg_device + ) + + if enable_remove_bg: + logger.info(f"Initialize {RemoveBG.name} plugin") + plugins[RemoveBG.name] = RemoveBG(remove_bg_model) + + if enable_anime_seg: + logger.info(f"Initialize {AnimeSeg.name} plugin") + plugins[AnimeSeg.name] = AnimeSeg() + + if enable_realesrgan: + logger.info( + f"Initialize {RealESRGANUpscaler.name} plugin: {realesrgan_model}, {realesrgan_device}" + ) + plugins[RealESRGANUpscaler.name] = RealESRGANUpscaler( + realesrgan_model, + realesrgan_device, + no_half=no_half, + ) + + if enable_gfpgan: + logger.info(f"Initialize {GFPGANPlugin.name} plugin") + if enable_realesrgan: + logger.info("Use realesrgan as GFPGAN background upscaler") + else: + logger.info( + f"GFPGAN no background upscaler, use --enable-realesrgan to enable it" + ) + plugins[GFPGANPlugin.name] = GFPGANPlugin( + gfpgan_device, + upscaler=plugins.get(RealESRGANUpscaler.name, None), + ) + + if enable_restoreformer: + logger.info(f"Initialize {RestoreFormerPlugin.name} plugin") + plugins[RestoreFormerPlugin.name] = RestoreFormerPlugin( + restoreformer_device, + upscaler=plugins.get(RealESRGANUpscaler.name, None), + ) + return plugins diff --git a/py/iopaint/plugins/anime_seg.py b/py/iopaint/plugins/anime_seg.py new file mode 100644 index 0000000..4d1d28d --- /dev/null +++ b/py/iopaint/plugins/anime_seg.py @@ -0,0 +1,462 @@ +import cv2 +import torch +import torch.nn as nn +import torch.nn.functional as F +import numpy as np +from PIL import Image + +from ..helper import load_model +from ..plugins.base_plugin import BasePlugin +from ..schema import RunPluginRequest + + +class REBNCONV(nn.Module): + def __init__(self, in_ch=3, out_ch=3, dirate=1, stride=1): + super(REBNCONV, self).__init__() + + self.conv_s1 = nn.Conv2d( + in_ch, out_ch, 3, padding=1 * dirate, dilation=1 * dirate, stride=stride + ) + self.bn_s1 = nn.BatchNorm2d(out_ch) + self.relu_s1 = nn.ReLU(inplace=True) + + def forward(self, x): + hx = x + xout = self.relu_s1(self.bn_s1(self.conv_s1(hx))) + + return xout + + +## upsample tensor 'src' to have the same spatial size with tensor 'tar' +def _upsample_like(src, tar): + src = F.interpolate(src, size=tar.shape[2:], mode="bilinear", align_corners=False) + + return src + + +### RSU-7 ### +class RSU7(nn.Module): + def __init__(self, in_ch=3, mid_ch=12, out_ch=3, img_size=512): + super(RSU7, self).__init__() + + self.in_ch = in_ch + self.mid_ch = mid_ch + self.out_ch = out_ch + + self.rebnconvin = REBNCONV(in_ch, out_ch, dirate=1) ## 1 -> 1/2 + + self.rebnconv1 = REBNCONV(out_ch, mid_ch, dirate=1) + self.pool1 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.rebnconv2 = REBNCONV(mid_ch, mid_ch, dirate=1) + self.pool2 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.rebnconv3 = REBNCONV(mid_ch, mid_ch, dirate=1) + self.pool3 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.rebnconv4 = REBNCONV(mid_ch, mid_ch, dirate=1) + self.pool4 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.rebnconv5 = REBNCONV(mid_ch, mid_ch, dirate=1) + self.pool5 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.rebnconv6 = REBNCONV(mid_ch, mid_ch, dirate=1) + + self.rebnconv7 = REBNCONV(mid_ch, mid_ch, dirate=2) + + self.rebnconv6d = REBNCONV(mid_ch * 2, mid_ch, dirate=1) + self.rebnconv5d = REBNCONV(mid_ch * 2, mid_ch, dirate=1) + self.rebnconv4d = REBNCONV(mid_ch * 2, mid_ch, dirate=1) + self.rebnconv3d = REBNCONV(mid_ch * 2, mid_ch, dirate=1) + self.rebnconv2d = REBNCONV(mid_ch * 2, mid_ch, dirate=1) + self.rebnconv1d = REBNCONV(mid_ch * 2, out_ch, dirate=1) + + def forward(self, x): + b, c, h, w = x.shape + + hx = x + hxin = self.rebnconvin(hx) + + hx1 = self.rebnconv1(hxin) + hx = self.pool1(hx1) + + hx2 = self.rebnconv2(hx) + hx = self.pool2(hx2) + + hx3 = self.rebnconv3(hx) + hx = self.pool3(hx3) + + hx4 = self.rebnconv4(hx) + hx = self.pool4(hx4) + + hx5 = self.rebnconv5(hx) + hx = self.pool5(hx5) + + hx6 = self.rebnconv6(hx) + + hx7 = self.rebnconv7(hx6) + + hx6d = self.rebnconv6d(torch.cat((hx7, hx6), 1)) + hx6dup = _upsample_like(hx6d, hx5) + + hx5d = self.rebnconv5d(torch.cat((hx6dup, hx5), 1)) + hx5dup = _upsample_like(hx5d, hx4) + + hx4d = self.rebnconv4d(torch.cat((hx5dup, hx4), 1)) + hx4dup = _upsample_like(hx4d, hx3) + + hx3d = self.rebnconv3d(torch.cat((hx4dup, hx3), 1)) + hx3dup = _upsample_like(hx3d, hx2) + + hx2d = self.rebnconv2d(torch.cat((hx3dup, hx2), 1)) + hx2dup = _upsample_like(hx2d, hx1) + + hx1d = self.rebnconv1d(torch.cat((hx2dup, hx1), 1)) + + return hx1d + hxin + + +### RSU-6 ### +class RSU6(nn.Module): + def __init__(self, in_ch=3, mid_ch=12, out_ch=3): + super(RSU6, self).__init__() + + self.rebnconvin = REBNCONV(in_ch, out_ch, dirate=1) + + self.rebnconv1 = REBNCONV(out_ch, mid_ch, dirate=1) + self.pool1 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.rebnconv2 = REBNCONV(mid_ch, mid_ch, dirate=1) + self.pool2 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.rebnconv3 = REBNCONV(mid_ch, mid_ch, dirate=1) + self.pool3 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.rebnconv4 = REBNCONV(mid_ch, mid_ch, dirate=1) + self.pool4 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.rebnconv5 = REBNCONV(mid_ch, mid_ch, dirate=1) + + self.rebnconv6 = REBNCONV(mid_ch, mid_ch, dirate=2) + + self.rebnconv5d = REBNCONV(mid_ch * 2, mid_ch, dirate=1) + self.rebnconv4d = REBNCONV(mid_ch * 2, mid_ch, dirate=1) + self.rebnconv3d = REBNCONV(mid_ch * 2, mid_ch, dirate=1) + self.rebnconv2d = REBNCONV(mid_ch * 2, mid_ch, dirate=1) + self.rebnconv1d = REBNCONV(mid_ch * 2, out_ch, dirate=1) + + def forward(self, x): + hx = x + + hxin = self.rebnconvin(hx) + + hx1 = self.rebnconv1(hxin) + hx = self.pool1(hx1) + + hx2 = self.rebnconv2(hx) + hx = self.pool2(hx2) + + hx3 = self.rebnconv3(hx) + hx = self.pool3(hx3) + + hx4 = self.rebnconv4(hx) + hx = self.pool4(hx4) + + hx5 = self.rebnconv5(hx) + + hx6 = self.rebnconv6(hx5) + + hx5d = self.rebnconv5d(torch.cat((hx6, hx5), 1)) + hx5dup = _upsample_like(hx5d, hx4) + + hx4d = self.rebnconv4d(torch.cat((hx5dup, hx4), 1)) + hx4dup = _upsample_like(hx4d, hx3) + + hx3d = self.rebnconv3d(torch.cat((hx4dup, hx3), 1)) + hx3dup = _upsample_like(hx3d, hx2) + + hx2d = self.rebnconv2d(torch.cat((hx3dup, hx2), 1)) + hx2dup = _upsample_like(hx2d, hx1) + + hx1d = self.rebnconv1d(torch.cat((hx2dup, hx1), 1)) + + return hx1d + hxin + + +### RSU-5 ### +class RSU5(nn.Module): + def __init__(self, in_ch=3, mid_ch=12, out_ch=3): + super(RSU5, self).__init__() + + self.rebnconvin = REBNCONV(in_ch, out_ch, dirate=1) + + self.rebnconv1 = REBNCONV(out_ch, mid_ch, dirate=1) + self.pool1 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.rebnconv2 = REBNCONV(mid_ch, mid_ch, dirate=1) + self.pool2 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.rebnconv3 = REBNCONV(mid_ch, mid_ch, dirate=1) + self.pool3 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.rebnconv4 = REBNCONV(mid_ch, mid_ch, dirate=1) + + self.rebnconv5 = REBNCONV(mid_ch, mid_ch, dirate=2) + + self.rebnconv4d = REBNCONV(mid_ch * 2, mid_ch, dirate=1) + self.rebnconv3d = REBNCONV(mid_ch * 2, mid_ch, dirate=1) + self.rebnconv2d = REBNCONV(mid_ch * 2, mid_ch, dirate=1) + self.rebnconv1d = REBNCONV(mid_ch * 2, out_ch, dirate=1) + + def forward(self, x): + hx = x + + hxin = self.rebnconvin(hx) + + hx1 = self.rebnconv1(hxin) + hx = self.pool1(hx1) + + hx2 = self.rebnconv2(hx) + hx = self.pool2(hx2) + + hx3 = self.rebnconv3(hx) + hx = self.pool3(hx3) + + hx4 = self.rebnconv4(hx) + + hx5 = self.rebnconv5(hx4) + + hx4d = self.rebnconv4d(torch.cat((hx5, hx4), 1)) + hx4dup = _upsample_like(hx4d, hx3) + + hx3d = self.rebnconv3d(torch.cat((hx4dup, hx3), 1)) + hx3dup = _upsample_like(hx3d, hx2) + + hx2d = self.rebnconv2d(torch.cat((hx3dup, hx2), 1)) + hx2dup = _upsample_like(hx2d, hx1) + + hx1d = self.rebnconv1d(torch.cat((hx2dup, hx1), 1)) + + return hx1d + hxin + + +### RSU-4 ### +class RSU4(nn.Module): + def __init__(self, in_ch=3, mid_ch=12, out_ch=3): + super(RSU4, self).__init__() + + self.rebnconvin = REBNCONV(in_ch, out_ch, dirate=1) + + self.rebnconv1 = REBNCONV(out_ch, mid_ch, dirate=1) + self.pool1 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.rebnconv2 = REBNCONV(mid_ch, mid_ch, dirate=1) + self.pool2 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.rebnconv3 = REBNCONV(mid_ch, mid_ch, dirate=1) + + self.rebnconv4 = REBNCONV(mid_ch, mid_ch, dirate=2) + + self.rebnconv3d = REBNCONV(mid_ch * 2, mid_ch, dirate=1) + self.rebnconv2d = REBNCONV(mid_ch * 2, mid_ch, dirate=1) + self.rebnconv1d = REBNCONV(mid_ch * 2, out_ch, dirate=1) + + def forward(self, x): + hx = x + + hxin = self.rebnconvin(hx) + + hx1 = self.rebnconv1(hxin) + hx = self.pool1(hx1) + + hx2 = self.rebnconv2(hx) + hx = self.pool2(hx2) + + hx3 = self.rebnconv3(hx) + + hx4 = self.rebnconv4(hx3) + + hx3d = self.rebnconv3d(torch.cat((hx4, hx3), 1)) + hx3dup = _upsample_like(hx3d, hx2) + + hx2d = self.rebnconv2d(torch.cat((hx3dup, hx2), 1)) + hx2dup = _upsample_like(hx2d, hx1) + + hx1d = self.rebnconv1d(torch.cat((hx2dup, hx1), 1)) + + return hx1d + hxin + + +### RSU-4F ### +class RSU4F(nn.Module): + def __init__(self, in_ch=3, mid_ch=12, out_ch=3): + super(RSU4F, self).__init__() + + self.rebnconvin = REBNCONV(in_ch, out_ch, dirate=1) + + self.rebnconv1 = REBNCONV(out_ch, mid_ch, dirate=1) + self.rebnconv2 = REBNCONV(mid_ch, mid_ch, dirate=2) + self.rebnconv3 = REBNCONV(mid_ch, mid_ch, dirate=4) + + self.rebnconv4 = REBNCONV(mid_ch, mid_ch, dirate=8) + + self.rebnconv3d = REBNCONV(mid_ch * 2, mid_ch, dirate=4) + self.rebnconv2d = REBNCONV(mid_ch * 2, mid_ch, dirate=2) + self.rebnconv1d = REBNCONV(mid_ch * 2, out_ch, dirate=1) + + def forward(self, x): + hx = x + + hxin = self.rebnconvin(hx) + + hx1 = self.rebnconv1(hxin) + hx2 = self.rebnconv2(hx1) + hx3 = self.rebnconv3(hx2) + + hx4 = self.rebnconv4(hx3) + + hx3d = self.rebnconv3d(torch.cat((hx4, hx3), 1)) + hx2d = self.rebnconv2d(torch.cat((hx3d, hx2), 1)) + hx1d = self.rebnconv1d(torch.cat((hx2d, hx1), 1)) + + return hx1d + hxin + + +class ISNetDIS(nn.Module): + def __init__(self, in_ch=3, out_ch=1): + super(ISNetDIS, self).__init__() + + self.conv_in = nn.Conv2d(in_ch, 64, 3, stride=2, padding=1) + self.pool_in = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.stage1 = RSU7(64, 32, 64) + self.pool12 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.stage2 = RSU6(64, 32, 128) + self.pool23 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.stage3 = RSU5(128, 64, 256) + self.pool34 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.stage4 = RSU4(256, 128, 512) + self.pool45 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.stage5 = RSU4F(512, 256, 512) + self.pool56 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.stage6 = RSU4F(512, 256, 512) + + # decoder + self.stage5d = RSU4F(1024, 256, 512) + self.stage4d = RSU4(1024, 128, 256) + self.stage3d = RSU5(512, 64, 128) + self.stage2d = RSU6(256, 32, 64) + self.stage1d = RSU7(128, 16, 64) + + self.side1 = nn.Conv2d(64, out_ch, 3, padding=1) + + def forward(self, x): + hx = x + + hxin = self.conv_in(hx) + hx = self.pool_in(hxin) + + # stage 1 + hx1 = self.stage1(hxin) + hx = self.pool12(hx1) + + # stage 2 + hx2 = self.stage2(hx) + hx = self.pool23(hx2) + + # stage 3 + hx3 = self.stage3(hx) + hx = self.pool34(hx3) + + # stage 4 + hx4 = self.stage4(hx) + hx = self.pool45(hx4) + + # stage 5 + hx5 = self.stage5(hx) + hx = self.pool56(hx5) + + # stage 6 + hx6 = self.stage6(hx) + hx6up = _upsample_like(hx6, hx5) + + # -------------------- decoder -------------------- + hx5d = self.stage5d(torch.cat((hx6up, hx5), 1)) + hx5dup = _upsample_like(hx5d, hx4) + + hx4d = self.stage4d(torch.cat((hx5dup, hx4), 1)) + hx4dup = _upsample_like(hx4d, hx3) + + hx3d = self.stage3d(torch.cat((hx4dup, hx3), 1)) + hx3dup = _upsample_like(hx3d, hx2) + + hx2d = self.stage2d(torch.cat((hx3dup, hx2), 1)) + hx2dup = _upsample_like(hx2d, hx1) + + hx1d = self.stage1d(torch.cat((hx2dup, hx1), 1)) + + # side output + d1 = self.side1(hx1d) + d1 = _upsample_like(d1, x) + return d1.sigmoid() + + +# 从小到大 +ANIME_SEG_MODELS = { + "url": "https://github.com/Sanster/models/releases/download/isnetis/isnetis.pth", + "md5": "5f25479076b73074730ab8de9e8f2051", +} + + +class AnimeSeg(BasePlugin): + # Model from: https://github.com/SkyTNT/anime-segmentation + name = "AnimeSeg" + support_gen_image = True + support_gen_mask = True + + def __init__(self): + super().__init__() + self.model = load_model( + ISNetDIS(), + ANIME_SEG_MODELS["url"], + "cpu", + ANIME_SEG_MODELS["md5"], + ) + + def gen_image(self, rgb_np_img, req: RunPluginRequest) -> np.ndarray: + mask = self.forward(rgb_np_img) + mask = Image.fromarray(mask, mode="L") + h0, w0 = rgb_np_img.shape[0], rgb_np_img.shape[1] + empty = Image.new("RGBA", (w0, h0), 0) + img = Image.fromarray(rgb_np_img) + cutout = Image.composite(img, empty, mask) + return np.asarray(cutout) + + def gen_mask(self, rgb_np_img, req: RunPluginRequest) -> np.ndarray: + return self.forward(rgb_np_img) + + @torch.inference_mode() + def forward(self, rgb_np_img): + s = 1024 + + h0, w0 = h, w = rgb_np_img.shape[0], rgb_np_img.shape[1] + if h > w: + h, w = s, int(s * w / h) + else: + h, w = int(s * h / w), s + ph, pw = s - h, s - w + tmpImg = np.zeros([s, s, 3], dtype=np.float32) + tmpImg[ph // 2 : ph // 2 + h, pw // 2 : pw // 2 + w] = ( + cv2.resize(rgb_np_img, (w, h)) / 255 + ) + tmpImg = tmpImg.transpose((2, 0, 1)) + tmpImg = torch.from_numpy(tmpImg).unsqueeze(0).type(torch.FloatTensor) + mask = self.model(tmpImg) + mask = mask[0, :, ph // 2 : ph // 2 + h, pw // 2 : pw // 2 + w] + mask = cv2.resize(mask.cpu().numpy().transpose((1, 2, 0)), (w0, h0)) + return (mask * 255).astype("uint8") diff --git a/py/iopaint/plugins/base_plugin.py b/py/iopaint/plugins/base_plugin.py new file mode 100644 index 0000000..c951a83 --- /dev/null +++ b/py/iopaint/plugins/base_plugin.py @@ -0,0 +1,30 @@ +from loguru import logger +import numpy as np + +from ..schema import RunPluginRequest + + +class BasePlugin: + name: str + support_gen_image: bool = False + support_gen_mask: bool = False + + def __init__(self): + err_msg = self.check_dep() + if err_msg: + logger.error(err_msg) + exit(-1) + + def gen_image(self, rgb_np_img, req: RunPluginRequest) -> np.ndarray: + # return RGBA np image or BGR np image + ... + + def gen_mask(self, rgb_np_img, req: RunPluginRequest) -> np.ndarray: + # return GRAY or BGR np image, 255 means foreground, 0 means background + ... + + def check_dep(self): + ... + + def switch_model(self, new_model_name: str): + ... diff --git a/py/iopaint/plugins/briarmbg.py b/py/iopaint/plugins/briarmbg.py new file mode 100644 index 0000000..880f530 --- /dev/null +++ b/py/iopaint/plugins/briarmbg.py @@ -0,0 +1,512 @@ +# copy from: https://huggingface.co/spaces/briaai/BRIA-RMBG-1.4/blob/main/briarmbg.py +import cv2 +import torch +import torch.nn as nn +import torch.nn.functional as F +from PIL import Image +import numpy as np +from torchvision.transforms.functional import normalize + + +class REBNCONV(nn.Module): + def __init__(self, in_ch=3, out_ch=3, dirate=1, stride=1): + super(REBNCONV, self).__init__() + + self.conv_s1 = nn.Conv2d( + in_ch, out_ch, 3, padding=1 * dirate, dilation=1 * dirate, stride=stride + ) + self.bn_s1 = nn.BatchNorm2d(out_ch) + self.relu_s1 = nn.ReLU(inplace=True) + + def forward(self, x): + hx = x + xout = self.relu_s1(self.bn_s1(self.conv_s1(hx))) + + return xout + + +## upsample tensor 'src' to have the same spatial size with tensor 'tar' +def _upsample_like(src, tar): + src = F.interpolate(src, size=tar.shape[2:], mode="bilinear") + + return src + + +### RSU-7 ### +class RSU7(nn.Module): + def __init__(self, in_ch=3, mid_ch=12, out_ch=3, img_size=512): + super(RSU7, self).__init__() + + self.in_ch = in_ch + self.mid_ch = mid_ch + self.out_ch = out_ch + + self.rebnconvin = REBNCONV(in_ch, out_ch, dirate=1) ## 1 -> 1/2 + + self.rebnconv1 = REBNCONV(out_ch, mid_ch, dirate=1) + self.pool1 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.rebnconv2 = REBNCONV(mid_ch, mid_ch, dirate=1) + self.pool2 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.rebnconv3 = REBNCONV(mid_ch, mid_ch, dirate=1) + self.pool3 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.rebnconv4 = REBNCONV(mid_ch, mid_ch, dirate=1) + self.pool4 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.rebnconv5 = REBNCONV(mid_ch, mid_ch, dirate=1) + self.pool5 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.rebnconv6 = REBNCONV(mid_ch, mid_ch, dirate=1) + + self.rebnconv7 = REBNCONV(mid_ch, mid_ch, dirate=2) + + self.rebnconv6d = REBNCONV(mid_ch * 2, mid_ch, dirate=1) + self.rebnconv5d = REBNCONV(mid_ch * 2, mid_ch, dirate=1) + self.rebnconv4d = REBNCONV(mid_ch * 2, mid_ch, dirate=1) + self.rebnconv3d = REBNCONV(mid_ch * 2, mid_ch, dirate=1) + self.rebnconv2d = REBNCONV(mid_ch * 2, mid_ch, dirate=1) + self.rebnconv1d = REBNCONV(mid_ch * 2, out_ch, dirate=1) + + def forward(self, x): + b, c, h, w = x.shape + + hx = x + hxin = self.rebnconvin(hx) + + hx1 = self.rebnconv1(hxin) + hx = self.pool1(hx1) + + hx2 = self.rebnconv2(hx) + hx = self.pool2(hx2) + + hx3 = self.rebnconv3(hx) + hx = self.pool3(hx3) + + hx4 = self.rebnconv4(hx) + hx = self.pool4(hx4) + + hx5 = self.rebnconv5(hx) + hx = self.pool5(hx5) + + hx6 = self.rebnconv6(hx) + + hx7 = self.rebnconv7(hx6) + + hx6d = self.rebnconv6d(torch.cat((hx7, hx6), 1)) + hx6dup = _upsample_like(hx6d, hx5) + + hx5d = self.rebnconv5d(torch.cat((hx6dup, hx5), 1)) + hx5dup = _upsample_like(hx5d, hx4) + + hx4d = self.rebnconv4d(torch.cat((hx5dup, hx4), 1)) + hx4dup = _upsample_like(hx4d, hx3) + + hx3d = self.rebnconv3d(torch.cat((hx4dup, hx3), 1)) + hx3dup = _upsample_like(hx3d, hx2) + + hx2d = self.rebnconv2d(torch.cat((hx3dup, hx2), 1)) + hx2dup = _upsample_like(hx2d, hx1) + + hx1d = self.rebnconv1d(torch.cat((hx2dup, hx1), 1)) + + return hx1d + hxin + + +### RSU-6 ### +class RSU6(nn.Module): + def __init__(self, in_ch=3, mid_ch=12, out_ch=3): + super(RSU6, self).__init__() + + self.rebnconvin = REBNCONV(in_ch, out_ch, dirate=1) + + self.rebnconv1 = REBNCONV(out_ch, mid_ch, dirate=1) + self.pool1 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.rebnconv2 = REBNCONV(mid_ch, mid_ch, dirate=1) + self.pool2 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.rebnconv3 = REBNCONV(mid_ch, mid_ch, dirate=1) + self.pool3 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.rebnconv4 = REBNCONV(mid_ch, mid_ch, dirate=1) + self.pool4 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.rebnconv5 = REBNCONV(mid_ch, mid_ch, dirate=1) + + self.rebnconv6 = REBNCONV(mid_ch, mid_ch, dirate=2) + + self.rebnconv5d = REBNCONV(mid_ch * 2, mid_ch, dirate=1) + self.rebnconv4d = REBNCONV(mid_ch * 2, mid_ch, dirate=1) + self.rebnconv3d = REBNCONV(mid_ch * 2, mid_ch, dirate=1) + self.rebnconv2d = REBNCONV(mid_ch * 2, mid_ch, dirate=1) + self.rebnconv1d = REBNCONV(mid_ch * 2, out_ch, dirate=1) + + def forward(self, x): + hx = x + + hxin = self.rebnconvin(hx) + + hx1 = self.rebnconv1(hxin) + hx = self.pool1(hx1) + + hx2 = self.rebnconv2(hx) + hx = self.pool2(hx2) + + hx3 = self.rebnconv3(hx) + hx = self.pool3(hx3) + + hx4 = self.rebnconv4(hx) + hx = self.pool4(hx4) + + hx5 = self.rebnconv5(hx) + + hx6 = self.rebnconv6(hx5) + + hx5d = self.rebnconv5d(torch.cat((hx6, hx5), 1)) + hx5dup = _upsample_like(hx5d, hx4) + + hx4d = self.rebnconv4d(torch.cat((hx5dup, hx4), 1)) + hx4dup = _upsample_like(hx4d, hx3) + + hx3d = self.rebnconv3d(torch.cat((hx4dup, hx3), 1)) + hx3dup = _upsample_like(hx3d, hx2) + + hx2d = self.rebnconv2d(torch.cat((hx3dup, hx2), 1)) + hx2dup = _upsample_like(hx2d, hx1) + + hx1d = self.rebnconv1d(torch.cat((hx2dup, hx1), 1)) + + return hx1d + hxin + + +### RSU-5 ### +class RSU5(nn.Module): + def __init__(self, in_ch=3, mid_ch=12, out_ch=3): + super(RSU5, self).__init__() + + self.rebnconvin = REBNCONV(in_ch, out_ch, dirate=1) + + self.rebnconv1 = REBNCONV(out_ch, mid_ch, dirate=1) + self.pool1 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.rebnconv2 = REBNCONV(mid_ch, mid_ch, dirate=1) + self.pool2 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.rebnconv3 = REBNCONV(mid_ch, mid_ch, dirate=1) + self.pool3 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.rebnconv4 = REBNCONV(mid_ch, mid_ch, dirate=1) + + self.rebnconv5 = REBNCONV(mid_ch, mid_ch, dirate=2) + + self.rebnconv4d = REBNCONV(mid_ch * 2, mid_ch, dirate=1) + self.rebnconv3d = REBNCONV(mid_ch * 2, mid_ch, dirate=1) + self.rebnconv2d = REBNCONV(mid_ch * 2, mid_ch, dirate=1) + self.rebnconv1d = REBNCONV(mid_ch * 2, out_ch, dirate=1) + + def forward(self, x): + hx = x + + hxin = self.rebnconvin(hx) + + hx1 = self.rebnconv1(hxin) + hx = self.pool1(hx1) + + hx2 = self.rebnconv2(hx) + hx = self.pool2(hx2) + + hx3 = self.rebnconv3(hx) + hx = self.pool3(hx3) + + hx4 = self.rebnconv4(hx) + + hx5 = self.rebnconv5(hx4) + + hx4d = self.rebnconv4d(torch.cat((hx5, hx4), 1)) + hx4dup = _upsample_like(hx4d, hx3) + + hx3d = self.rebnconv3d(torch.cat((hx4dup, hx3), 1)) + hx3dup = _upsample_like(hx3d, hx2) + + hx2d = self.rebnconv2d(torch.cat((hx3dup, hx2), 1)) + hx2dup = _upsample_like(hx2d, hx1) + + hx1d = self.rebnconv1d(torch.cat((hx2dup, hx1), 1)) + + return hx1d + hxin + + +### RSU-4 ### +class RSU4(nn.Module): + def __init__(self, in_ch=3, mid_ch=12, out_ch=3): + super(RSU4, self).__init__() + + self.rebnconvin = REBNCONV(in_ch, out_ch, dirate=1) + + self.rebnconv1 = REBNCONV(out_ch, mid_ch, dirate=1) + self.pool1 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.rebnconv2 = REBNCONV(mid_ch, mid_ch, dirate=1) + self.pool2 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.rebnconv3 = REBNCONV(mid_ch, mid_ch, dirate=1) + + self.rebnconv4 = REBNCONV(mid_ch, mid_ch, dirate=2) + + self.rebnconv3d = REBNCONV(mid_ch * 2, mid_ch, dirate=1) + self.rebnconv2d = REBNCONV(mid_ch * 2, mid_ch, dirate=1) + self.rebnconv1d = REBNCONV(mid_ch * 2, out_ch, dirate=1) + + def forward(self, x): + hx = x + + hxin = self.rebnconvin(hx) + + hx1 = self.rebnconv1(hxin) + hx = self.pool1(hx1) + + hx2 = self.rebnconv2(hx) + hx = self.pool2(hx2) + + hx3 = self.rebnconv3(hx) + + hx4 = self.rebnconv4(hx3) + + hx3d = self.rebnconv3d(torch.cat((hx4, hx3), 1)) + hx3dup = _upsample_like(hx3d, hx2) + + hx2d = self.rebnconv2d(torch.cat((hx3dup, hx2), 1)) + hx2dup = _upsample_like(hx2d, hx1) + + hx1d = self.rebnconv1d(torch.cat((hx2dup, hx1), 1)) + + return hx1d + hxin + + +### RSU-4F ### +class RSU4F(nn.Module): + def __init__(self, in_ch=3, mid_ch=12, out_ch=3): + super(RSU4F, self).__init__() + + self.rebnconvin = REBNCONV(in_ch, out_ch, dirate=1) + + self.rebnconv1 = REBNCONV(out_ch, mid_ch, dirate=1) + self.rebnconv2 = REBNCONV(mid_ch, mid_ch, dirate=2) + self.rebnconv3 = REBNCONV(mid_ch, mid_ch, dirate=4) + + self.rebnconv4 = REBNCONV(mid_ch, mid_ch, dirate=8) + + self.rebnconv3d = REBNCONV(mid_ch * 2, mid_ch, dirate=4) + self.rebnconv2d = REBNCONV(mid_ch * 2, mid_ch, dirate=2) + self.rebnconv1d = REBNCONV(mid_ch * 2, out_ch, dirate=1) + + def forward(self, x): + hx = x + + hxin = self.rebnconvin(hx) + + hx1 = self.rebnconv1(hxin) + hx2 = self.rebnconv2(hx1) + hx3 = self.rebnconv3(hx2) + + hx4 = self.rebnconv4(hx3) + + hx3d = self.rebnconv3d(torch.cat((hx4, hx3), 1)) + hx2d = self.rebnconv2d(torch.cat((hx3d, hx2), 1)) + hx1d = self.rebnconv1d(torch.cat((hx2d, hx1), 1)) + + return hx1d + hxin + + +class myrebnconv(nn.Module): + def __init__( + self, + in_ch=3, + out_ch=1, + kernel_size=3, + stride=1, + padding=1, + dilation=1, + groups=1, + ): + super(myrebnconv, self).__init__() + + self.conv = nn.Conv2d( + in_ch, + out_ch, + kernel_size=kernel_size, + stride=stride, + padding=padding, + dilation=dilation, + groups=groups, + ) + self.bn = nn.BatchNorm2d(out_ch) + self.rl = nn.ReLU(inplace=True) + + def forward(self, x): + return self.rl(self.bn(self.conv(x))) + + +class BriaRMBG(nn.Module): + def __init__(self, in_ch=3, out_ch=1): + super(BriaRMBG, self).__init__() + + self.conv_in = nn.Conv2d(in_ch, 64, 3, stride=2, padding=1) + self.pool_in = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.stage1 = RSU7(64, 32, 64) + self.pool12 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.stage2 = RSU6(64, 32, 128) + self.pool23 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.stage3 = RSU5(128, 64, 256) + self.pool34 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.stage4 = RSU4(256, 128, 512) + self.pool45 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.stage5 = RSU4F(512, 256, 512) + self.pool56 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.stage6 = RSU4F(512, 256, 512) + + # decoder + self.stage5d = RSU4F(1024, 256, 512) + self.stage4d = RSU4(1024, 128, 256) + self.stage3d = RSU5(512, 64, 128) + self.stage2d = RSU6(256, 32, 64) + self.stage1d = RSU7(128, 16, 64) + + self.side1 = nn.Conv2d(64, out_ch, 3, padding=1) + self.side2 = nn.Conv2d(64, out_ch, 3, padding=1) + self.side3 = nn.Conv2d(128, out_ch, 3, padding=1) + self.side4 = nn.Conv2d(256, out_ch, 3, padding=1) + self.side5 = nn.Conv2d(512, out_ch, 3, padding=1) + self.side6 = nn.Conv2d(512, out_ch, 3, padding=1) + + # self.outconv = nn.Conv2d(6*out_ch,out_ch,1) + + def forward(self, x): + hx = x + + hxin = self.conv_in(hx) + # hx = self.pool_in(hxin) + + # stage 1 + hx1 = self.stage1(hxin) + hx = self.pool12(hx1) + + # stage 2 + hx2 = self.stage2(hx) + hx = self.pool23(hx2) + + # stage 3 + hx3 = self.stage3(hx) + hx = self.pool34(hx3) + + # stage 4 + hx4 = self.stage4(hx) + hx = self.pool45(hx4) + + # stage 5 + hx5 = self.stage5(hx) + hx = self.pool56(hx5) + + # stage 6 + hx6 = self.stage6(hx) + hx6up = _upsample_like(hx6, hx5) + + # -------------------- decoder -------------------- + hx5d = self.stage5d(torch.cat((hx6up, hx5), 1)) + hx5dup = _upsample_like(hx5d, hx4) + + hx4d = self.stage4d(torch.cat((hx5dup, hx4), 1)) + hx4dup = _upsample_like(hx4d, hx3) + + hx3d = self.stage3d(torch.cat((hx4dup, hx3), 1)) + hx3dup = _upsample_like(hx3d, hx2) + + hx2d = self.stage2d(torch.cat((hx3dup, hx2), 1)) + hx2dup = _upsample_like(hx2d, hx1) + + hx1d = self.stage1d(torch.cat((hx2dup, hx1), 1)) + + # side output + d1 = self.side1(hx1d) + d1 = _upsample_like(d1, x) + + d2 = self.side2(hx2d) + d2 = _upsample_like(d2, x) + + d3 = self.side3(hx3d) + d3 = _upsample_like(d3, x) + + d4 = self.side4(hx4d) + d4 = _upsample_like(d4, x) + + d5 = self.side5(hx5d) + d5 = _upsample_like(d5, x) + + d6 = self.side6(hx6) + d6 = _upsample_like(d6, x) + + return [ + F.sigmoid(d1), + F.sigmoid(d2), + F.sigmoid(d3), + F.sigmoid(d4), + F.sigmoid(d5), + F.sigmoid(d6), + ], [hx1d, hx2d, hx3d, hx4d, hx5d, hx6] + + +def resize_image(image): + image = image.convert("RGB") + model_input_size = (1024, 1024) + image = image.resize(model_input_size, Image.BILINEAR) + return image + + +def create_briarmbg_session(): + from huggingface_hub import hf_hub_download + + net = BriaRMBG() + model_path = hf_hub_download("briaai/RMBG-1.4", "model.pth") + net.load_state_dict(torch.load(model_path, map_location="cpu")) + net.eval() + return net + + +def briarmbg_process(bgr_np_image, session, only_mask=False): + # prepare input + orig_bgr_image = Image.fromarray(bgr_np_image) + w, h = orig_im_size = orig_bgr_image.size + image = resize_image(orig_bgr_image) + im_np = np.array(image) + im_tensor = torch.tensor(im_np, dtype=torch.float32).permute(2, 0, 1) + im_tensor = torch.unsqueeze(im_tensor, 0) + im_tensor = torch.divide(im_tensor, 255.0) + im_tensor = normalize(im_tensor, [0.5, 0.5, 0.5], [1.0, 1.0, 1.0]) + # inference + result = session(im_tensor) + # post process + result = torch.squeeze(F.interpolate(result[0][0], size=(h, w), mode="bilinear"), 0) + ma = torch.max(result) + mi = torch.min(result) + result = (result - mi) / (ma - mi) + # image to pil + im_array = (result * 255).cpu().data.numpy().astype(np.uint8) + + mask = np.squeeze(im_array) + if only_mask: + return mask + + pil_im = Image.fromarray(mask) + # paste the mask on the original image + new_im = Image.new("RGBA", pil_im.size, (0, 0, 0, 0)) + new_im.paste(orig_bgr_image, mask=pil_im) + rgba_np_img = np.asarray(new_im) + return rgba_np_img diff --git a/py/iopaint/plugins/gfpgan_plugin.py b/py/iopaint/plugins/gfpgan_plugin.py new file mode 100644 index 0000000..5787f71 --- /dev/null +++ b/py/iopaint/plugins/gfpgan_plugin.py @@ -0,0 +1,74 @@ +import cv2 +import numpy as np +from loguru import logger + +from ..helper import download_model +from ..plugins.base_plugin import BasePlugin +from ..schema import RunPluginRequest + + +class GFPGANPlugin(BasePlugin): + name = "GFPGAN" + support_gen_image = True + + def __init__(self, device, upscaler=None): + super().__init__() + from .gfpganer import MyGFPGANer + + url = "https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.4.pth" + model_md5 = "94d735072630ab734561130a47bc44f8" + model_path = download_model(url, model_md5) + logger.info(f"GFPGAN model path: {model_path}") + + import facexlib + + if hasattr(facexlib.detection.retinaface, "device"): + facexlib.detection.retinaface.device = device + + # Use GFPGAN for face enhancement + self.face_enhancer = MyGFPGANer( + model_path=model_path, + upscale=1, + arch="clean", + channel_multiplier=2, + device=device, + bg_upsampler=upscaler.model if upscaler is not None else None, + ) + self.face_enhancer.face_helper.face_det.mean_tensor.to(device) + self.face_enhancer.face_helper.face_det = ( + self.face_enhancer.face_helper.face_det.to(device) + ) + + def gen_image(self, rgb_np_img, req: RunPluginRequest) -> np.ndarray: + weight = 0.5 + bgr_np_img = cv2.cvtColor(rgb_np_img, cv2.COLOR_RGB2BGR) + logger.info(f"GFPGAN input shape: {bgr_np_img.shape}") + _, _, bgr_output = self.face_enhancer.enhance( + bgr_np_img, + has_aligned=False, + only_center_face=False, + paste_back=True, + weight=weight, + ) + logger.info(f"GFPGAN output shape: {bgr_output.shape}") + + # try: + # if scale != 2: + # interpolation = cv2.INTER_AREA if scale < 2 else cv2.INTER_LANCZOS4 + # h, w = img.shape[0:2] + # output = cv2.resize( + # output, + # (int(w * scale / 2), int(h * scale / 2)), + # interpolation=interpolation, + # ) + # except Exception as error: + # print("wrong scale input.", error) + return bgr_output + + def check_dep(self): + try: + import gfpgan + except ImportError: + return ( + "gfpgan is not installed, please install it first. pip install gfpgan" + ) diff --git a/py/iopaint/plugins/gfpganer.py b/py/iopaint/plugins/gfpganer.py new file mode 100644 index 0000000..75a575d --- /dev/null +++ b/py/iopaint/plugins/gfpganer.py @@ -0,0 +1,84 @@ +import os + +import torch +from facexlib.utils.face_restoration_helper import FaceRestoreHelper +from gfpgan import GFPGANv1Clean, GFPGANer +from torch.hub import get_dir + + +class MyGFPGANer(GFPGANer): + """Helper for restoration with GFPGAN. + + It will detect and crop faces, and then resize the faces to 512x512. + GFPGAN is used to restored the resized faces. + The background is upsampled with the bg_upsampler. + Finally, the faces will be pasted back to the upsample background image. + + Args: + model_path (str): The path to the GFPGAN model. It can be urls (will first download it automatically). + upscale (float): The upscale of the final output. Default: 2. + arch (str): The GFPGAN architecture. Option: clean | original. Default: clean. + channel_multiplier (int): Channel multiplier for large networks of StyleGAN2. Default: 2. + bg_upsampler (nn.Module): The upsampler for the background. Default: None. + """ + + def __init__( + self, + model_path, + upscale=2, + arch="clean", + channel_multiplier=2, + bg_upsampler=None, + device=None, + ): + self.upscale = upscale + self.bg_upsampler = bg_upsampler + + # initialize model + self.device = ( + torch.device("cuda" if torch.cuda.is_available() else "cpu") + if device is None + else device + ) + # initialize the GFP-GAN + if arch == "clean": + self.gfpgan = GFPGANv1Clean( + out_size=512, + num_style_feat=512, + channel_multiplier=channel_multiplier, + decoder_load_path=None, + fix_decoder=False, + num_mlp=8, + input_is_latent=True, + different_w=True, + narrow=1, + sft_half=True, + ) + elif arch == "RestoreFormer": + from gfpgan.archs.restoreformer_arch import RestoreFormer + + self.gfpgan = RestoreFormer() + + hub_dir = get_dir() + model_dir = os.path.join(hub_dir, "checkpoints") + + # initialize face helper + self.face_helper = FaceRestoreHelper( + upscale, + face_size=512, + crop_ratio=(1, 1), + det_model="retinaface_resnet50", + save_ext="png", + use_parse=True, + device=self.device, + model_rootpath=model_dir, + ) + + loadnet = torch.load(model_path) + if "params_ema" in loadnet: + keyname = "params_ema" + else: + keyname = "params" + self.gfpgan.load_state_dict(loadnet[keyname], strict=True) + self.gfpgan.eval() + self.gfpgan = self.gfpgan.to(self.device) diff --git a/py/iopaint/plugins/interactive_seg.py b/py/iopaint/plugins/interactive_seg.py new file mode 100644 index 0000000..b3a4424 --- /dev/null +++ b/py/iopaint/plugins/interactive_seg.py @@ -0,0 +1,107 @@ +import hashlib +from typing import List + +import numpy as np +import torch +from loguru import logger + +from ..helper import download_model +from ..plugins.base_plugin import BasePlugin +from ..plugins.segment_anything import SamPredictor, sam_model_registry +from ..plugins.segment_anything.predictor_hq import SamHQPredictor +from ..schema import RunPluginRequest + +# 从小到大 +SEGMENT_ANYTHING_MODELS = { + "vit_b": { + "url": "https://dl.fbaipublicfiles.com/segment_anything/sam_vit_b_01ec64.pth", + "md5": "01ec64d29a2fca3f0661936605ae66f8", + }, + "vit_l": { + "url": "https://dl.fbaipublicfiles.com/segment_anything/sam_vit_l_0b3195.pth", + "md5": "0b3195507c641ddb6910d2bb5adee89c", + }, + "vit_h": { + "url": "https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth", + "md5": "4b8939a88964f0f4ff5f5b2642c598a6", + }, + "mobile_sam": { + "url": "https://github.com/Sanster/models/releases/download/MobileSAM/mobile_sam.pt", + "md5": "f3c0d8cda613564d499310dab6c812cd", + }, + "sam_hq_vit_b": { + "url": "https://huggingface.co/lkeab/hq-sam/resolve/main/sam_hq_vit_b.pth", + "md5": "c6b8953247bcfdc8bb8ef91e36a6cacc", + }, + "sam_hq_vit_l": { + "url": "https://huggingface.co/lkeab/hq-sam/resolve/main/sam_hq_vit_l.pth", + "md5": "08947267966e4264fb39523eccc33f86", + }, + "sam_hq_vit_h": { + "url": "https://huggingface.co/lkeab/hq-sam/resolve/main/sam_hq_vit_h.pth", + "md5": "3560f6b6a5a6edacd814a1325c39640a", + }, +} + + +class InteractiveSeg(BasePlugin): + name = "InteractiveSeg" + support_gen_mask = True + + def __init__(self, model_name, device): + super().__init__() + self.model_name = model_name + self.device = device + self._init_session(model_name) + + def _init_session(self, model_name: str): + model_path = download_model( + SEGMENT_ANYTHING_MODELS[model_name]["url"], + SEGMENT_ANYTHING_MODELS[model_name]["md5"], + ) + logger.info(f"SegmentAnything model path: {model_path}") + if "sam_hq" in model_name: + self.predictor = SamHQPredictor( + sam_model_registry[model_name](checkpoint=model_path).to(self.device) + ) + else: + self.predictor = SamPredictor( + sam_model_registry[model_name](checkpoint=model_path).to(self.device) + ) + self.prev_img_md5 = None + + def switch_model(self, new_model_name): + if self.model_name == new_model_name: + return + + logger.info( + f"Switching InteractiveSeg model from {self.model_name} to {new_model_name}" + ) + self._init_session(new_model_name) + self.model_name = new_model_name + + def gen_mask(self, rgb_np_img, req: RunPluginRequest) -> np.ndarray: + img_md5 = hashlib.md5(req.image.encode("utf-8")).hexdigest() + return self.forward(rgb_np_img, req.clicks, img_md5) + + @torch.inference_mode() + def forward(self, rgb_np_img, clicks: List[List], img_md5: str): + input_point = [] + input_label = [] + for click in clicks: + x = click[0] + y = click[1] + input_point.append([x, y]) + input_label.append(click[2]) + + if img_md5 and img_md5 != self.prev_img_md5: + self.prev_img_md5 = img_md5 + self.predictor.set_image(rgb_np_img) + + masks, scores, _ = self.predictor.predict( + point_coords=np.array(input_point), + point_labels=np.array(input_label), + multimask_output=False, + ) + mask = masks[0].astype(np.uint8) * 255 + return mask diff --git a/py/iopaint/plugins/realesrgan.py b/py/iopaint/plugins/realesrgan.py new file mode 100644 index 0000000..c31db4e --- /dev/null +++ b/py/iopaint/plugins/realesrgan.py @@ -0,0 +1,109 @@ +import cv2 +import numpy as np +import torch +from loguru import logger + +from ..helper import download_model +from ..plugins.base_plugin import BasePlugin +from ..schema import RunPluginRequest, RealESRGANModel + + +class RealESRGANUpscaler(BasePlugin): + name = "RealESRGAN" + support_gen_image = True + + def __init__(self, name, device, no_half=False): + super().__init__() + self.model_name = name + self.device = device + self.no_half = no_half + self._init_model(name) + + def _init_model(self, name): + from basicsr.archs.rrdbnet_arch import RRDBNet + from realesrgan import RealESRGANer + from realesrgan.archs.srvgg_arch import SRVGGNetCompact + + REAL_ESRGAN_MODELS = { + RealESRGANModel.realesr_general_x4v3: { + "url": "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-general-x4v3.pth", + "scale": 4, + "model": lambda: SRVGGNetCompact( + num_in_ch=3, + num_out_ch=3, + num_feat=64, + num_conv=32, + upscale=4, + act_type="prelu", + ), + "model_md5": "91a7644643c884ee00737db24e478156", + }, + RealESRGANModel.RealESRGAN_x4plus: { + "url": "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth", + "scale": 4, + "model": lambda: RRDBNet( + num_in_ch=3, + num_out_ch=3, + num_feat=64, + num_block=23, + num_grow_ch=32, + scale=4, + ), + "model_md5": "99ec365d4afad750833258a1a24f44ca", + }, + RealESRGANModel.RealESRGAN_x4plus_anime_6B: { + "url": "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.4/RealESRGAN_x4plus_anime_6B.pth", + "scale": 4, + "model": lambda: RRDBNet( + num_in_ch=3, + num_out_ch=3, + num_feat=64, + num_block=6, + num_grow_ch=32, + scale=4, + ), + "model_md5": "d58ce384064ec1591c2ea7b79dbf47ba", + }, + } + if name not in REAL_ESRGAN_MODELS: + raise ValueError(f"Unknown RealESRGAN model name: {name}") + model_info = REAL_ESRGAN_MODELS[name] + + model_path = download_model(model_info["url"], model_info["model_md5"]) + logger.info(f"RealESRGAN model path: {model_path}") + + self.model = RealESRGANer( + scale=model_info["scale"], + model_path=model_path, + model=model_info["model"](), + half=True if "cuda" in str(self.device) and not self.no_half else False, + tile=512, + tile_pad=10, + pre_pad=10, + device=self.device, + ) + + def switch_model(self, new_model_name: str): + if self.model_name == new_model_name: + return + self._init_model(new_model_name) + self.model_name = new_model_name + + def gen_image(self, rgb_np_img, req: RunPluginRequest) -> np.ndarray: + bgr_np_img = cv2.cvtColor(rgb_np_img, cv2.COLOR_RGB2BGR) + logger.info(f"RealESRGAN input shape: {bgr_np_img.shape}, scale: {req.scale}") + result = self.forward(bgr_np_img, req.scale) + logger.info(f"RealESRGAN output shape: {result.shape}") + return result + + @torch.inference_mode() + def forward(self, bgr_np_img, scale: float): + # 输出是 BGR + upsampled = self.model.enhance(bgr_np_img, outscale=scale)[0] + return upsampled + + def check_dep(self): + try: + import realesrgan + except ImportError: + return "RealESRGAN is not installed, please install it first. pip install realesrgan" diff --git a/py/iopaint/plugins/remove_bg.py b/py/iopaint/plugins/remove_bg.py new file mode 100644 index 0000000..cc3ace8 --- /dev/null +++ b/py/iopaint/plugins/remove_bg.py @@ -0,0 +1,71 @@ +import os +import cv2 +import numpy as np +from loguru import logger +from torch.hub import get_dir + +from ..plugins.base_plugin import BasePlugin +from ..schema import RunPluginRequest, RemoveBGModel + + +class RemoveBG(BasePlugin): + name = "RemoveBG" + support_gen_mask = True + support_gen_image = True + + def __init__(self, model_name): + super().__init__() + self.model_name = model_name + + hub_dir = get_dir() + model_dir = os.path.join(hub_dir, "checkpoints") + os.environ["U2NET_HOME"] = model_dir + + self._init_session(model_name) + + def _init_session(self, model_name: str): + if model_name == RemoveBGModel.briaai_rmbg_1_4: + from iopaint.plugins.briarmbg import ( + create_briarmbg_session, + briarmbg_process, + ) + + self.session = create_briarmbg_session() + self.remove = briarmbg_process + else: + from rembg import new_session, remove + + self.session = new_session(model_name=model_name) + self.remove = remove + + def switch_model(self, new_model_name): + if self.model_name == new_model_name: + return + + logger.info( + f"Switching removebg model from {self.model_name} to {new_model_name}" + ) + self._init_session(new_model_name) + self.model_name = new_model_name + + def gen_image(self, rgb_np_img, req: RunPluginRequest) -> np.ndarray: + bgr_np_img = cv2.cvtColor(rgb_np_img, cv2.COLOR_RGB2BGR) + + # return BGRA image + output = self.remove(bgr_np_img, session=self.session) + return cv2.cvtColor(output, cv2.COLOR_BGRA2RGBA) + + def gen_mask(self, rgb_np_img, req: RunPluginRequest) -> np.ndarray: + bgr_np_img = cv2.cvtColor(rgb_np_img, cv2.COLOR_RGB2BGR) + + # return BGR image, 255 means foreground, 0 means background + output = self.remove(bgr_np_img, session=self.session, only_mask=True) + return output + + def check_dep(self): + try: + import rembg + except ImportError: + return ( + "RemoveBG is not installed, please install it first. pip install rembg" + ) diff --git a/py/iopaint/plugins/restoreformer.py b/py/iopaint/plugins/restoreformer.py new file mode 100644 index 0000000..64bac5d --- /dev/null +++ b/py/iopaint/plugins/restoreformer.py @@ -0,0 +1,57 @@ +import cv2 +import numpy as np +from loguru import logger + +from ..helper import download_model +from ..plugins.base_plugin import BasePlugin +from ..schema import RunPluginRequest + + +class RestoreFormerPlugin(BasePlugin): + name = "RestoreFormer" + support_gen_image = True + + def __init__(self, device, upscaler=None): + super().__init__() + from .gfpganer import MyGFPGANer + + url = "https://github.com/TencentARC/GFPGAN/releases/download/v1.3.4/RestoreFormer.pth" + model_md5 = "eaeeff6c4a1caa1673977cb374e6f699" + model_path = download_model(url, model_md5) + logger.info(f"RestoreFormer model path: {model_path}") + + import facexlib + + if hasattr(facexlib.detection.retinaface, "device"): + facexlib.detection.retinaface.device = device + + self.face_enhancer = MyGFPGANer( + model_path=model_path, + upscale=1, + arch="RestoreFormer", + channel_multiplier=2, + device=device, + bg_upsampler=upscaler.model if upscaler is not None else None, + ) + + def gen_image(self, rgb_np_img, req: RunPluginRequest) -> np.ndarray: + weight = 0.5 + bgr_np_img = cv2.cvtColor(rgb_np_img, cv2.COLOR_RGB2BGR) + logger.info(f"RestoreFormer input shape: {bgr_np_img.shape}") + _, _, bgr_output = self.face_enhancer.enhance( + bgr_np_img, + has_aligned=False, + only_center_face=False, + paste_back=True, + weight=weight, + ) + logger.info(f"RestoreFormer output shape: {bgr_output.shape}") + return bgr_output + + def check_dep(self): + try: + import gfpgan + except ImportError: + return ( + "gfpgan is not installed, please install it first. pip install gfpgan" + ) diff --git a/py/iopaint/plugins/segment_anything/__init__.py b/py/iopaint/plugins/segment_anything/__init__.py new file mode 100644 index 0000000..420f04b --- /dev/null +++ b/py/iopaint/plugins/segment_anything/__init__.py @@ -0,0 +1,16 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +from .build_sam import ( + build_sam_vit_h, + build_sam_vit_l, + build_sam_vit_b, + build_sam_vit_h_hq, + build_sam_vit_l_hq, + build_sam_vit_b_hq, + sam_model_registry, +) +from .predictor import SamPredictor diff --git a/py/iopaint/plugins/segment_anything/build_sam.py b/py/iopaint/plugins/segment_anything/build_sam.py new file mode 100644 index 0000000..aede07c --- /dev/null +++ b/py/iopaint/plugins/segment_anything/build_sam.py @@ -0,0 +1,269 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import torch + +from functools import partial + +from ...plugins.segment_anything.modeling.tiny_vit_sam import TinyViT + +from .modeling import ( + ImageEncoderViT, + MaskDecoder, + PromptEncoder, + Sam, + TwoWayTransformer, +) +from .modeling.image_encoder_hq import ImageEncoderViTHQ +from .modeling.mask_decoder import MaskDecoderHQ +from .modeling.sam_hq import SamHQ + + +def build_sam_vit_h(checkpoint=None): + return _build_sam( + encoder_embed_dim=1280, + encoder_depth=32, + encoder_num_heads=16, + encoder_global_attn_indexes=[7, 15, 23, 31], + checkpoint=checkpoint, + ) + + +def build_sam_vit_l(checkpoint=None): + return _build_sam( + encoder_embed_dim=1024, + encoder_depth=24, + encoder_num_heads=16, + encoder_global_attn_indexes=[5, 11, 17, 23], + checkpoint=checkpoint, + ) + + +def build_sam_vit_b(checkpoint=None): + return _build_sam( + encoder_embed_dim=768, + encoder_depth=12, + encoder_num_heads=12, + encoder_global_attn_indexes=[2, 5, 8, 11], + checkpoint=checkpoint, + ) + + +def build_sam_vit_t(checkpoint=None): + prompt_embed_dim = 256 + image_size = 1024 + vit_patch_size = 16 + image_embedding_size = image_size // vit_patch_size + mobile_sam = Sam( + image_encoder=TinyViT( + img_size=1024, + in_chans=3, + num_classes=1000, + embed_dims=[64, 128, 160, 320], + depths=[2, 2, 6, 2], + num_heads=[2, 4, 5, 10], + window_sizes=[7, 7, 14, 7], + mlp_ratio=4.0, + drop_rate=0.0, + drop_path_rate=0.0, + use_checkpoint=False, + mbconv_expand_ratio=4.0, + local_conv_size=3, + layer_lr_decay=0.8, + ), + prompt_encoder=PromptEncoder( + embed_dim=prompt_embed_dim, + image_embedding_size=(image_embedding_size, image_embedding_size), + input_image_size=(image_size, image_size), + mask_in_chans=16, + ), + mask_decoder=MaskDecoder( + num_multimask_outputs=3, + transformer=TwoWayTransformer( + depth=2, + embedding_dim=prompt_embed_dim, + mlp_dim=2048, + num_heads=8, + ), + transformer_dim=prompt_embed_dim, + iou_head_depth=3, + iou_head_hidden_dim=256, + ), + pixel_mean=[123.675, 116.28, 103.53], + pixel_std=[58.395, 57.12, 57.375], + ) + + mobile_sam.eval() + if checkpoint is not None: + with open(checkpoint, "rb") as f: + state_dict = torch.load(f) + mobile_sam.load_state_dict(state_dict) + return mobile_sam + + +def build_sam_vit_h_hq(checkpoint=None): + return _build_sam_hq( + encoder_embed_dim=1280, + encoder_depth=32, + encoder_num_heads=16, + encoder_global_attn_indexes=[7, 15, 23, 31], + checkpoint=checkpoint, + ) + + +def build_sam_vit_l_hq(checkpoint=None): + return _build_sam_hq( + encoder_embed_dim=1024, + encoder_depth=24, + encoder_num_heads=16, + encoder_global_attn_indexes=[5, 11, 17, 23], + checkpoint=checkpoint, + ) + + +def build_sam_vit_b_hq(checkpoint=None): + return _build_sam_hq( + encoder_embed_dim=768, + encoder_depth=12, + encoder_num_heads=12, + encoder_global_attn_indexes=[2, 5, 8, 11], + checkpoint=checkpoint, + ) + + +sam_model_registry = { + "default": build_sam_vit_h, + "vit_h": build_sam_vit_h, + "vit_l": build_sam_vit_l, + "vit_b": build_sam_vit_b, + "sam_hq_vit_h": build_sam_vit_h_hq, + "sam_hq_vit_l": build_sam_vit_l_hq, + "sam_hq_vit_b": build_sam_vit_b_hq, + "mobile_sam": build_sam_vit_t, +} + + +def _build_sam( + encoder_embed_dim, + encoder_depth, + encoder_num_heads, + encoder_global_attn_indexes, + checkpoint=None, +): + prompt_embed_dim = 256 + image_size = 1024 + vit_patch_size = 16 + image_embedding_size = image_size // vit_patch_size + sam = Sam( + image_encoder=ImageEncoderViT( + depth=encoder_depth, + embed_dim=encoder_embed_dim, + img_size=image_size, + mlp_ratio=4, + norm_layer=partial(torch.nn.LayerNorm, eps=1e-6), + num_heads=encoder_num_heads, + patch_size=vit_patch_size, + qkv_bias=True, + use_rel_pos=True, + global_attn_indexes=encoder_global_attn_indexes, + window_size=14, + out_chans=prompt_embed_dim, + ), + prompt_encoder=PromptEncoder( + embed_dim=prompt_embed_dim, + image_embedding_size=(image_embedding_size, image_embedding_size), + input_image_size=(image_size, image_size), + mask_in_chans=16, + ), + mask_decoder=MaskDecoder( + num_multimask_outputs=3, + transformer=TwoWayTransformer( + depth=2, + embedding_dim=prompt_embed_dim, + mlp_dim=2048, + num_heads=8, + ), + transformer_dim=prompt_embed_dim, + iou_head_depth=3, + iou_head_hidden_dim=256, + ), + pixel_mean=[123.675, 116.28, 103.53], + pixel_std=[58.395, 57.12, 57.375], + ) + sam.eval() + if checkpoint is not None: + with open(checkpoint, "rb") as f: + state_dict = torch.load(f) + sam.load_state_dict(state_dict) + return sam + + +def _build_sam_hq( + encoder_embed_dim, + encoder_depth, + encoder_num_heads, + encoder_global_attn_indexes, + checkpoint=None, +): + prompt_embed_dim = 256 + image_size = 1024 + vit_patch_size = 16 + image_embedding_size = image_size // vit_patch_size + sam = SamHQ( + image_encoder=ImageEncoderViTHQ( + depth=encoder_depth, + embed_dim=encoder_embed_dim, + img_size=image_size, + mlp_ratio=4, + norm_layer=partial(torch.nn.LayerNorm, eps=1e-6), + num_heads=encoder_num_heads, + patch_size=vit_patch_size, + qkv_bias=True, + use_rel_pos=True, + global_attn_indexes=encoder_global_attn_indexes, + window_size=14, + out_chans=prompt_embed_dim, + ), + prompt_encoder=PromptEncoder( + embed_dim=prompt_embed_dim, + image_embedding_size=(image_embedding_size, image_embedding_size), + input_image_size=(image_size, image_size), + mask_in_chans=16, + ), + mask_decoder=MaskDecoderHQ( + num_multimask_outputs=3, + transformer=TwoWayTransformer( + depth=2, + embedding_dim=prompt_embed_dim, + mlp_dim=2048, + num_heads=8, + ), + transformer_dim=prompt_embed_dim, + iou_head_depth=3, + iou_head_hidden_dim=256, + vit_dim=encoder_embed_dim, + ), + pixel_mean=[123.675, 116.28, 103.53], + pixel_std=[58.395, 57.12, 57.375], + ) + sam.eval() + if checkpoint is not None: + with open(checkpoint, "rb") as f: + device = "cuda" if torch.cuda.is_available() else "cpu" + state_dict = torch.load(f, map_location=device) + info = sam.load_state_dict(state_dict, strict=False) + print(info) + for n, p in sam.named_parameters(): + if ( + "hf_token" not in n + and "hf_mlp" not in n + and "compress_vit_feat" not in n + and "embedding_encoder" not in n + and "embedding_maskfeature" not in n + ): + p.requires_grad = False + + return sam diff --git a/py/iopaint/plugins/segment_anything/modeling/__init__.py b/py/iopaint/plugins/segment_anything/modeling/__init__.py new file mode 100644 index 0000000..38e9062 --- /dev/null +++ b/py/iopaint/plugins/segment_anything/modeling/__init__.py @@ -0,0 +1,11 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +from .sam import Sam +from .image_encoder import ImageEncoderViT +from .mask_decoder import MaskDecoder +from .prompt_encoder import PromptEncoder +from .transformer import TwoWayTransformer diff --git a/py/iopaint/plugins/segment_anything/modeling/common.py b/py/iopaint/plugins/segment_anything/modeling/common.py new file mode 100644 index 0000000..2bf1523 --- /dev/null +++ b/py/iopaint/plugins/segment_anything/modeling/common.py @@ -0,0 +1,43 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import torch +import torch.nn as nn + +from typing import Type + + +class MLPBlock(nn.Module): + def __init__( + self, + embedding_dim: int, + mlp_dim: int, + act: Type[nn.Module] = nn.GELU, + ) -> None: + super().__init__() + self.lin1 = nn.Linear(embedding_dim, mlp_dim) + self.lin2 = nn.Linear(mlp_dim, embedding_dim) + self.act = act() + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return self.lin2(self.act(self.lin1(x))) + + +# From https://github.com/facebookresearch/detectron2/blob/main/detectron2/layers/batch_norm.py # noqa +# Itself from https://github.com/facebookresearch/ConvNeXt/blob/d1fa8f6fef0a165b27399986cc2bdacc92777e40/models/convnext.py#L119 # noqa +class LayerNorm2d(nn.Module): + def __init__(self, num_channels: int, eps: float = 1e-6) -> None: + super().__init__() + self.weight = nn.Parameter(torch.ones(num_channels)) + self.bias = nn.Parameter(torch.zeros(num_channels)) + self.eps = eps + + def forward(self, x: torch.Tensor) -> torch.Tensor: + u = x.mean(1, keepdim=True) + s = (x - u).pow(2).mean(1, keepdim=True) + x = (x - u) / torch.sqrt(s + self.eps) + x = self.weight[:, None, None] * x + self.bias[:, None, None] + return x diff --git a/py/iopaint/plugins/segment_anything/modeling/image_encoder.py b/py/iopaint/plugins/segment_anything/modeling/image_encoder.py new file mode 100644 index 0000000..a6ad9ad --- /dev/null +++ b/py/iopaint/plugins/segment_anything/modeling/image_encoder.py @@ -0,0 +1,395 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import torch +import torch.nn as nn +import torch.nn.functional as F + +from typing import Optional, Tuple, Type + +from .common import LayerNorm2d, MLPBlock + + +# This class and its supporting functions below lightly adapted from the ViTDet backbone available at: https://github.com/facebookresearch/detectron2/blob/main/detectron2/modeling/backbone/vit.py # noqa +class ImageEncoderViT(nn.Module): + def __init__( + self, + img_size: int = 1024, + patch_size: int = 16, + in_chans: int = 3, + embed_dim: int = 768, + depth: int = 12, + num_heads: int = 12, + mlp_ratio: float = 4.0, + out_chans: int = 256, + qkv_bias: bool = True, + norm_layer: Type[nn.Module] = nn.LayerNorm, + act_layer: Type[nn.Module] = nn.GELU, + use_abs_pos: bool = True, + use_rel_pos: bool = False, + rel_pos_zero_init: bool = True, + window_size: int = 0, + global_attn_indexes: Tuple[int, ...] = (), + ) -> None: + """ + Args: + img_size (int): Input image size. + patch_size (int): Patch size. + in_chans (int): Number of input image channels. + embed_dim (int): Patch embedding dimension. + depth (int): Depth of ViT. + num_heads (int): Number of attention heads in each ViT block. + mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. + qkv_bias (bool): If True, add a learnable bias to query, key, value. + norm_layer (nn.Module): Normalization layer. + act_layer (nn.Module): Activation layer. + use_abs_pos (bool): If True, use absolute positional embeddings. + use_rel_pos (bool): If True, add relative positional embeddings to the attention map. + rel_pos_zero_init (bool): If True, zero initialize relative positional parameters. + window_size (int): Window size for window attention blocks. + global_attn_indexes (list): Indexes for blocks using global attention. + """ + super().__init__() + self.img_size = img_size + + self.patch_embed = PatchEmbed( + kernel_size=(patch_size, patch_size), + stride=(patch_size, patch_size), + in_chans=in_chans, + embed_dim=embed_dim, + ) + + self.pos_embed: Optional[nn.Parameter] = None + if use_abs_pos: + # Initialize absolute positional embedding with pretrain image size. + self.pos_embed = nn.Parameter( + torch.zeros(1, img_size // patch_size, img_size // patch_size, embed_dim) + ) + + self.blocks = nn.ModuleList() + for i in range(depth): + block = Block( + dim=embed_dim, + num_heads=num_heads, + mlp_ratio=mlp_ratio, + qkv_bias=qkv_bias, + norm_layer=norm_layer, + act_layer=act_layer, + use_rel_pos=use_rel_pos, + rel_pos_zero_init=rel_pos_zero_init, + window_size=window_size if i not in global_attn_indexes else 0, + input_size=(img_size // patch_size, img_size // patch_size), + ) + self.blocks.append(block) + + self.neck = nn.Sequential( + nn.Conv2d( + embed_dim, + out_chans, + kernel_size=1, + bias=False, + ), + LayerNorm2d(out_chans), + nn.Conv2d( + out_chans, + out_chans, + kernel_size=3, + padding=1, + bias=False, + ), + LayerNorm2d(out_chans), + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x = self.patch_embed(x) + if self.pos_embed is not None: + x = x + self.pos_embed + + for blk in self.blocks: + x = blk(x) + + x = self.neck(x.permute(0, 3, 1, 2)) + + return x + + +class Block(nn.Module): + """Transformer blocks with support of window attention and residual propagation blocks""" + + def __init__( + self, + dim: int, + num_heads: int, + mlp_ratio: float = 4.0, + qkv_bias: bool = True, + norm_layer: Type[nn.Module] = nn.LayerNorm, + act_layer: Type[nn.Module] = nn.GELU, + use_rel_pos: bool = False, + rel_pos_zero_init: bool = True, + window_size: int = 0, + input_size: Optional[Tuple[int, int]] = None, + ) -> None: + """ + Args: + dim (int): Number of input channels. + num_heads (int): Number of attention heads in each ViT block. + mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. + qkv_bias (bool): If True, add a learnable bias to query, key, value. + norm_layer (nn.Module): Normalization layer. + act_layer (nn.Module): Activation layer. + use_rel_pos (bool): If True, add relative positional embeddings to the attention map. + rel_pos_zero_init (bool): If True, zero initialize relative positional parameters. + window_size (int): Window size for window attention blocks. If it equals 0, then + use global attention. + input_size (int or None): Input resolution for calculating the relative positional + parameter size. + """ + super().__init__() + self.norm1 = norm_layer(dim) + self.attn = Attention( + dim, + num_heads=num_heads, + qkv_bias=qkv_bias, + use_rel_pos=use_rel_pos, + rel_pos_zero_init=rel_pos_zero_init, + input_size=input_size if window_size == 0 else (window_size, window_size), + ) + + self.norm2 = norm_layer(dim) + self.mlp = MLPBlock(embedding_dim=dim, mlp_dim=int(dim * mlp_ratio), act=act_layer) + + self.window_size = window_size + + def forward(self, x: torch.Tensor) -> torch.Tensor: + shortcut = x + x = self.norm1(x) + # Window partition + if self.window_size > 0: + H, W = x.shape[1], x.shape[2] + x, pad_hw = window_partition(x, self.window_size) + + x = self.attn(x) + # Reverse window partition + if self.window_size > 0: + x = window_unpartition(x, self.window_size, pad_hw, (H, W)) + + x = shortcut + x + x = x + self.mlp(self.norm2(x)) + + return x + + +class Attention(nn.Module): + """Multi-head Attention block with relative position embeddings.""" + + def __init__( + self, + dim: int, + num_heads: int = 8, + qkv_bias: bool = True, + use_rel_pos: bool = False, + rel_pos_zero_init: bool = True, + input_size: Optional[Tuple[int, int]] = None, + ) -> None: + """ + Args: + dim (int): Number of input channels. + num_heads (int): Number of attention heads. + qkv_bias (bool: If True, add a learnable bias to query, key, value. + rel_pos (bool): If True, add relative positional embeddings to the attention map. + rel_pos_zero_init (bool): If True, zero initialize relative positional parameters. + input_size (int or None): Input resolution for calculating the relative positional + parameter size. + """ + super().__init__() + self.num_heads = num_heads + head_dim = dim // num_heads + self.scale = head_dim**-0.5 + + self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) + self.proj = nn.Linear(dim, dim) + + self.use_rel_pos = use_rel_pos + if self.use_rel_pos: + assert ( + input_size is not None + ), "Input size must be provided if using relative positional encoding." + # initialize relative positional embeddings + self.rel_pos_h = nn.Parameter(torch.zeros(2 * input_size[0] - 1, head_dim)) + self.rel_pos_w = nn.Parameter(torch.zeros(2 * input_size[1] - 1, head_dim)) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + B, H, W, _ = x.shape + # qkv with shape (3, B, nHead, H * W, C) + qkv = self.qkv(x).reshape(B, H * W, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4) + # q, k, v with shape (B * nHead, H * W, C) + q, k, v = qkv.reshape(3, B * self.num_heads, H * W, -1).unbind(0) + + attn = (q * self.scale) @ k.transpose(-2, -1) + + if self.use_rel_pos: + attn = add_decomposed_rel_pos(attn, q, self.rel_pos_h, self.rel_pos_w, (H, W), (H, W)) + + attn = attn.softmax(dim=-1) + x = (attn @ v).view(B, self.num_heads, H, W, -1).permute(0, 2, 3, 1, 4).reshape(B, H, W, -1) + x = self.proj(x) + + return x + + +def window_partition(x: torch.Tensor, window_size: int) -> Tuple[torch.Tensor, Tuple[int, int]]: + """ + Partition into non-overlapping windows with padding if needed. + Args: + x (tensor): input tokens with [B, H, W, C]. + window_size (int): window size. + + Returns: + windows: windows after partition with [B * num_windows, window_size, window_size, C]. + (Hp, Wp): padded height and width before partition + """ + B, H, W, C = x.shape + + pad_h = (window_size - H % window_size) % window_size + pad_w = (window_size - W % window_size) % window_size + if pad_h > 0 or pad_w > 0: + x = F.pad(x, (0, 0, 0, pad_w, 0, pad_h)) + Hp, Wp = H + pad_h, W + pad_w + + x = x.view(B, Hp // window_size, window_size, Wp // window_size, window_size, C) + windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C) + return windows, (Hp, Wp) + + +def window_unpartition( + windows: torch.Tensor, window_size: int, pad_hw: Tuple[int, int], hw: Tuple[int, int] +) -> torch.Tensor: + """ + Window unpartition into original sequences and removing padding. + Args: + x (tensor): input tokens with [B * num_windows, window_size, window_size, C]. + window_size (int): window size. + pad_hw (Tuple): padded height and width (Hp, Wp). + hw (Tuple): original height and width (H, W) before padding. + + Returns: + x: unpartitioned sequences with [B, H, W, C]. + """ + Hp, Wp = pad_hw + H, W = hw + B = windows.shape[0] // (Hp * Wp // window_size // window_size) + x = windows.view(B, Hp // window_size, Wp // window_size, window_size, window_size, -1) + x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, Hp, Wp, -1) + + if Hp > H or Wp > W: + x = x[:, :H, :W, :].contiguous() + return x + + +def get_rel_pos(q_size: int, k_size: int, rel_pos: torch.Tensor) -> torch.Tensor: + """ + Get relative positional embeddings according to the relative positions of + query and key sizes. + Args: + q_size (int): size of query q. + k_size (int): size of key k. + rel_pos (Tensor): relative position embeddings (L, C). + + Returns: + Extracted positional embeddings according to relative positions. + """ + max_rel_dist = int(2 * max(q_size, k_size) - 1) + # Interpolate rel pos if needed. + if rel_pos.shape[0] != max_rel_dist: + # Interpolate rel pos. + rel_pos_resized = F.interpolate( + rel_pos.reshape(1, rel_pos.shape[0], -1).permute(0, 2, 1), + size=max_rel_dist, + mode="linear", + ) + rel_pos_resized = rel_pos_resized.reshape(-1, max_rel_dist).permute(1, 0) + else: + rel_pos_resized = rel_pos + + # Scale the coords with short length if shapes for q and k are different. + q_coords = torch.arange(q_size)[:, None] * max(k_size / q_size, 1.0) + k_coords = torch.arange(k_size)[None, :] * max(q_size / k_size, 1.0) + relative_coords = (q_coords - k_coords) + (k_size - 1) * max(q_size / k_size, 1.0) + + return rel_pos_resized[relative_coords.long()] + + +def add_decomposed_rel_pos( + attn: torch.Tensor, + q: torch.Tensor, + rel_pos_h: torch.Tensor, + rel_pos_w: torch.Tensor, + q_size: Tuple[int, int], + k_size: Tuple[int, int], +) -> torch.Tensor: + """ + Calculate decomposed Relative Positional Embeddings from :paper:`mvitv2`. + https://github.com/facebookresearch/mvit/blob/19786631e330df9f3622e5402b4a419a263a2c80/mvit/models/attention.py # noqa B950 + Args: + attn (Tensor): attention map. + q (Tensor): query q in the attention layer with shape (B, q_h * q_w, C). + rel_pos_h (Tensor): relative position embeddings (Lh, C) for height axis. + rel_pos_w (Tensor): relative position embeddings (Lw, C) for width axis. + q_size (Tuple): spatial sequence size of query q with (q_h, q_w). + k_size (Tuple): spatial sequence size of key k with (k_h, k_w). + + Returns: + attn (Tensor): attention map with added relative positional embeddings. + """ + q_h, q_w = q_size + k_h, k_w = k_size + Rh = get_rel_pos(q_h, k_h, rel_pos_h) + Rw = get_rel_pos(q_w, k_w, rel_pos_w) + + B, _, dim = q.shape + r_q = q.reshape(B, q_h, q_w, dim) + rel_h = torch.einsum("bhwc,hkc->bhwk", r_q, Rh) + rel_w = torch.einsum("bhwc,wkc->bhwk", r_q, Rw) + + attn = ( + attn.view(B, q_h, q_w, k_h, k_w) + rel_h[:, :, :, :, None] + rel_w[:, :, :, None, :] + ).view(B, q_h * q_w, k_h * k_w) + + return attn + + +class PatchEmbed(nn.Module): + """ + Image to Patch Embedding. + """ + + def __init__( + self, + kernel_size: Tuple[int, int] = (16, 16), + stride: Tuple[int, int] = (16, 16), + padding: Tuple[int, int] = (0, 0), + in_chans: int = 3, + embed_dim: int = 768, + ) -> None: + """ + Args: + kernel_size (Tuple): kernel size of the projection layer. + stride (Tuple): stride of the projection layer. + padding (Tuple): padding size of the projection layer. + in_chans (int): Number of input image channels. + embed_dim (int): embed_dim (int): Patch embedding dimension. + """ + super().__init__() + + self.proj = nn.Conv2d( + in_chans, embed_dim, kernel_size=kernel_size, stride=stride, padding=padding + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x = self.proj(x) + # B C H W -> B H W C + x = x.permute(0, 2, 3, 1) + return x diff --git a/py/iopaint/plugins/segment_anything/modeling/image_encoder_hq.py b/py/iopaint/plugins/segment_anything/modeling/image_encoder_hq.py new file mode 100644 index 0000000..f12803b --- /dev/null +++ b/py/iopaint/plugins/segment_anything/modeling/image_encoder_hq.py @@ -0,0 +1,422 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import torch +import torch.nn as nn +import torch.nn.functional as F + +from typing import Optional, Tuple, Type + +from .common import LayerNorm2d, MLPBlock + + +# This class and its supporting functions below lightly adapted from the ViTDet backbone available at: https://github.com/facebookresearch/detectron2/blob/main/detectron2/modeling/backbone/vit.py # noqa +class ImageEncoderViTHQ(nn.Module): + def __init__( + self, + img_size: int = 1024, + patch_size: int = 16, + in_chans: int = 3, + embed_dim: int = 768, + depth: int = 12, + num_heads: int = 12, + mlp_ratio: float = 4.0, + out_chans: int = 256, + qkv_bias: bool = True, + norm_layer: Type[nn.Module] = nn.LayerNorm, + act_layer: Type[nn.Module] = nn.GELU, + use_abs_pos: bool = True, + use_rel_pos: bool = False, + rel_pos_zero_init: bool = True, + window_size: int = 0, + global_attn_indexes: Tuple[int, ...] = (), + ) -> None: + """ + Args: + img_size (int): Input image size. + patch_size (int): Patch size. + in_chans (int): Number of input image channels. + embed_dim (int): Patch embedding dimension. + depth (int): Depth of ViT. + num_heads (int): Number of attention heads in each ViT block. + mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. + qkv_bias (bool): If True, add a learnable bias to query, key, value. + norm_layer (nn.Module): Normalization layer. + act_layer (nn.Module): Activation layer. + use_abs_pos (bool): If True, use absolute positional embeddings. + use_rel_pos (bool): If True, add relative positional embeddings to the attention map. + rel_pos_zero_init (bool): If True, zero initialize relative positional parameters. + window_size (int): Window size for window attention blocks. + global_attn_indexes (list): Indexes for blocks using global attention. + """ + super().__init__() + self.img_size = img_size + + self.patch_embed = PatchEmbed( + kernel_size=(patch_size, patch_size), + stride=(patch_size, patch_size), + in_chans=in_chans, + embed_dim=embed_dim, + ) + + self.pos_embed: Optional[nn.Parameter] = None + if use_abs_pos: + # Initialize absolute positional embedding with pretrain image size. + self.pos_embed = nn.Parameter( + torch.zeros( + 1, img_size // patch_size, img_size // patch_size, embed_dim + ) + ) + + self.blocks = nn.ModuleList() + for i in range(depth): + block = Block( + dim=embed_dim, + num_heads=num_heads, + mlp_ratio=mlp_ratio, + qkv_bias=qkv_bias, + norm_layer=norm_layer, + act_layer=act_layer, + use_rel_pos=use_rel_pos, + rel_pos_zero_init=rel_pos_zero_init, + window_size=window_size if i not in global_attn_indexes else 0, + input_size=(img_size // patch_size, img_size // patch_size), + ) + self.blocks.append(block) + + self.neck = nn.Sequential( + nn.Conv2d( + embed_dim, + out_chans, + kernel_size=1, + bias=False, + ), + LayerNorm2d(out_chans), + nn.Conv2d( + out_chans, + out_chans, + kernel_size=3, + padding=1, + bias=False, + ), + LayerNorm2d(out_chans), + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x = self.patch_embed(x) + if self.pos_embed is not None: + x = x + self.pos_embed + + interm_embeddings = [] + for blk in self.blocks: + x = blk(x) + if blk.window_size == 0: + interm_embeddings.append(x) + + x = self.neck(x.permute(0, 3, 1, 2)) + + return x, interm_embeddings + + +class Block(nn.Module): + """Transformer blocks with support of window attention and residual propagation blocks""" + + def __init__( + self, + dim: int, + num_heads: int, + mlp_ratio: float = 4.0, + qkv_bias: bool = True, + norm_layer: Type[nn.Module] = nn.LayerNorm, + act_layer: Type[nn.Module] = nn.GELU, + use_rel_pos: bool = False, + rel_pos_zero_init: bool = True, + window_size: int = 0, + input_size: Optional[Tuple[int, int]] = None, + ) -> None: + """ + Args: + dim (int): Number of input channels. + num_heads (int): Number of attention heads in each ViT block. + mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. + qkv_bias (bool): If True, add a learnable bias to query, key, value. + norm_layer (nn.Module): Normalization layer. + act_layer (nn.Module): Activation layer. + use_rel_pos (bool): If True, add relative positional embeddings to the attention map. + rel_pos_zero_init (bool): If True, zero initialize relative positional parameters. + window_size (int): Window size for window attention blocks. If it equals 0, then + use global attention. + input_size (tuple(int, int) or None): Input resolution for calculating the relative + positional parameter size. + """ + super().__init__() + self.norm1 = norm_layer(dim) + self.attn = Attention( + dim, + num_heads=num_heads, + qkv_bias=qkv_bias, + use_rel_pos=use_rel_pos, + rel_pos_zero_init=rel_pos_zero_init, + input_size=input_size if window_size == 0 else (window_size, window_size), + ) + + self.norm2 = norm_layer(dim) + self.mlp = MLPBlock( + embedding_dim=dim, mlp_dim=int(dim * mlp_ratio), act=act_layer + ) + + self.window_size = window_size + + def forward(self, x: torch.Tensor) -> torch.Tensor: + shortcut = x + x = self.norm1(x) + # Window partition + if self.window_size > 0: + H, W = x.shape[1], x.shape[2] + x, pad_hw = window_partition(x, self.window_size) + + x = self.attn(x) + # Reverse window partition + if self.window_size > 0: + x = window_unpartition(x, self.window_size, pad_hw, (H, W)) + + x = shortcut + x + x = x + self.mlp(self.norm2(x)) + + return x + + +class Attention(nn.Module): + """Multi-head Attention block with relative position embeddings.""" + + def __init__( + self, + dim: int, + num_heads: int = 8, + qkv_bias: bool = True, + use_rel_pos: bool = False, + rel_pos_zero_init: bool = True, + input_size: Optional[Tuple[int, int]] = None, + ) -> None: + """ + Args: + dim (int): Number of input channels. + num_heads (int): Number of attention heads. + qkv_bias (bool): If True, add a learnable bias to query, key, value. + rel_pos (bool): If True, add relative positional embeddings to the attention map. + rel_pos_zero_init (bool): If True, zero initialize relative positional parameters. + input_size (tuple(int, int) or None): Input resolution for calculating the relative + positional parameter size. + """ + super().__init__() + self.num_heads = num_heads + head_dim = dim // num_heads + self.scale = head_dim**-0.5 + + self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) + self.proj = nn.Linear(dim, dim) + + self.use_rel_pos = use_rel_pos + if self.use_rel_pos: + assert ( + input_size is not None + ), "Input size must be provided if using relative positional encoding." + # initialize relative positional embeddings + self.rel_pos_h = nn.Parameter(torch.zeros(2 * input_size[0] - 1, head_dim)) + self.rel_pos_w = nn.Parameter(torch.zeros(2 * input_size[1] - 1, head_dim)) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + B, H, W, _ = x.shape + # qkv with shape (3, B, nHead, H * W, C) + qkv = ( + self.qkv(x).reshape(B, H * W, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4) + ) + # q, k, v with shape (B * nHead, H * W, C) + q, k, v = qkv.reshape(3, B * self.num_heads, H * W, -1).unbind(0) + + attn = (q * self.scale) @ k.transpose(-2, -1) + + if self.use_rel_pos: + attn = add_decomposed_rel_pos( + attn, q, self.rel_pos_h, self.rel_pos_w, (H, W), (H, W) + ) + + attn = attn.softmax(dim=-1) + x = ( + (attn @ v) + .view(B, self.num_heads, H, W, -1) + .permute(0, 2, 3, 1, 4) + .reshape(B, H, W, -1) + ) + x = self.proj(x) + + return x + + +def window_partition( + x: torch.Tensor, window_size: int +) -> Tuple[torch.Tensor, Tuple[int, int]]: + """ + Partition into non-overlapping windows with padding if needed. + Args: + x (tensor): input tokens with [B, H, W, C]. + window_size (int): window size. + + Returns: + windows: windows after partition with [B * num_windows, window_size, window_size, C]. + (Hp, Wp): padded height and width before partition + """ + B, H, W, C = x.shape + + pad_h = (window_size - H % window_size) % window_size + pad_w = (window_size - W % window_size) % window_size + if pad_h > 0 or pad_w > 0: + x = F.pad(x, (0, 0, 0, pad_w, 0, pad_h)) + Hp, Wp = H + pad_h, W + pad_w + + x = x.view(B, Hp // window_size, window_size, Wp // window_size, window_size, C) + windows = ( + x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C) + ) + return windows, (Hp, Wp) + + +def window_unpartition( + windows: torch.Tensor, + window_size: int, + pad_hw: Tuple[int, int], + hw: Tuple[int, int], +) -> torch.Tensor: + """ + Window unpartition into original sequences and removing padding. + Args: + windows (tensor): input tokens with [B * num_windows, window_size, window_size, C]. + window_size (int): window size. + pad_hw (Tuple): padded height and width (Hp, Wp). + hw (Tuple): original height and width (H, W) before padding. + + Returns: + x: unpartitioned sequences with [B, H, W, C]. + """ + Hp, Wp = pad_hw + H, W = hw + B = windows.shape[0] // (Hp * Wp // window_size // window_size) + x = windows.view( + B, Hp // window_size, Wp // window_size, window_size, window_size, -1 + ) + x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, Hp, Wp, -1) + + if Hp > H or Wp > W: + x = x[:, :H, :W, :].contiguous() + return x + + +def get_rel_pos(q_size: int, k_size: int, rel_pos: torch.Tensor) -> torch.Tensor: + """ + Get relative positional embeddings according to the relative positions of + query and key sizes. + Args: + q_size (int): size of query q. + k_size (int): size of key k. + rel_pos (Tensor): relative position embeddings (L, C). + + Returns: + Extracted positional embeddings according to relative positions. + """ + max_rel_dist = int(2 * max(q_size, k_size) - 1) + # Interpolate rel pos if needed. + if rel_pos.shape[0] != max_rel_dist: + # Interpolate rel pos. + rel_pos_resized = F.interpolate( + rel_pos.reshape(1, rel_pos.shape[0], -1).permute(0, 2, 1), + size=max_rel_dist, + mode="linear", + ) + rel_pos_resized = rel_pos_resized.reshape(-1, max_rel_dist).permute(1, 0) + else: + rel_pos_resized = rel_pos + + # Scale the coords with short length if shapes for q and k are different. + q_coords = torch.arange(q_size)[:, None] * max(k_size / q_size, 1.0) + k_coords = torch.arange(k_size)[None, :] * max(q_size / k_size, 1.0) + relative_coords = (q_coords - k_coords) + (k_size - 1) * max(q_size / k_size, 1.0) + + return rel_pos_resized[relative_coords.long()] + + +def add_decomposed_rel_pos( + attn: torch.Tensor, + q: torch.Tensor, + rel_pos_h: torch.Tensor, + rel_pos_w: torch.Tensor, + q_size: Tuple[int, int], + k_size: Tuple[int, int], +) -> torch.Tensor: + """ + Calculate decomposed Relative Positional Embeddings from :paper:`mvitv2`. + https://github.com/facebookresearch/mvit/blob/19786631e330df9f3622e5402b4a419a263a2c80/mvit/models/attention.py # noqa B950 + Args: + attn (Tensor): attention map. + q (Tensor): query q in the attention layer with shape (B, q_h * q_w, C). + rel_pos_h (Tensor): relative position embeddings (Lh, C) for height axis. + rel_pos_w (Tensor): relative position embeddings (Lw, C) for width axis. + q_size (Tuple): spatial sequence size of query q with (q_h, q_w). + k_size (Tuple): spatial sequence size of key k with (k_h, k_w). + + Returns: + attn (Tensor): attention map with added relative positional embeddings. + """ + q_h, q_w = q_size + k_h, k_w = k_size + Rh = get_rel_pos(q_h, k_h, rel_pos_h) + Rw = get_rel_pos(q_w, k_w, rel_pos_w) + + B, _, dim = q.shape + r_q = q.reshape(B, q_h, q_w, dim) + rel_h = torch.einsum("bhwc,hkc->bhwk", r_q, Rh) + rel_w = torch.einsum("bhwc,wkc->bhwk", r_q, Rw) + + attn = ( + attn.view(B, q_h, q_w, k_h, k_w) + + rel_h[:, :, :, :, None] + + rel_w[:, :, :, None, :] + ).view(B, q_h * q_w, k_h * k_w) + + return attn + + +class PatchEmbed(nn.Module): + """ + Image to Patch Embedding. + """ + + def __init__( + self, + kernel_size: Tuple[int, int] = (16, 16), + stride: Tuple[int, int] = (16, 16), + padding: Tuple[int, int] = (0, 0), + in_chans: int = 3, + embed_dim: int = 768, + ) -> None: + """ + Args: + kernel_size (Tuple): kernel size of the projection layer. + stride (Tuple): stride of the projection layer. + padding (Tuple): padding size of the projection layer. + in_chans (int): Number of input image channels. + embed_dim (int): Patch embedding dimension. + """ + super().__init__() + + self.proj = nn.Conv2d( + in_chans, embed_dim, kernel_size=kernel_size, stride=stride, padding=padding + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x = self.proj(x) + # B C H W -> B H W C + x = x.permute(0, 2, 3, 1) + return x diff --git a/py/iopaint/plugins/segment_anything/modeling/mask_decoder.py b/py/iopaint/plugins/segment_anything/modeling/mask_decoder.py new file mode 100644 index 0000000..67e0f77 --- /dev/null +++ b/py/iopaint/plugins/segment_anything/modeling/mask_decoder.py @@ -0,0 +1,410 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import torch +from torch import nn +from torch.nn import functional as F + +from typing import List, Tuple, Type + +from .common import LayerNorm2d + + +class MaskDecoder(nn.Module): + def __init__( + self, + *, + transformer_dim: int, + transformer: nn.Module, + num_multimask_outputs: int = 3, + activation: Type[nn.Module] = nn.GELU, + iou_head_depth: int = 3, + iou_head_hidden_dim: int = 256, + ) -> None: + """ + Predicts masks given an image and prompt embeddings, using a + tranformer architecture. + + Arguments: + transformer_dim (int): the channel dimension of the transformer + transformer (nn.Module): the transformer used to predict masks + num_multimask_outputs (int): the number of masks to predict + when disambiguating masks + activation (nn.Module): the type of activation to use when + upscaling masks + iou_head_depth (int): the depth of the MLP used to predict + mask quality + iou_head_hidden_dim (int): the hidden dimension of the MLP + used to predict mask quality + """ + super().__init__() + self.transformer_dim = transformer_dim + self.transformer = transformer + + self.num_multimask_outputs = num_multimask_outputs + + self.iou_token = nn.Embedding(1, transformer_dim) + self.num_mask_tokens = num_multimask_outputs + 1 + self.mask_tokens = nn.Embedding(self.num_mask_tokens, transformer_dim) + + self.output_upscaling = nn.Sequential( + nn.ConvTranspose2d( + transformer_dim, transformer_dim // 4, kernel_size=2, stride=2 + ), + LayerNorm2d(transformer_dim // 4), + activation(), + nn.ConvTranspose2d( + transformer_dim // 4, transformer_dim // 8, kernel_size=2, stride=2 + ), + activation(), + ) + self.output_hypernetworks_mlps = nn.ModuleList( + [ + MLP(transformer_dim, transformer_dim, transformer_dim // 8, 3) + for i in range(self.num_mask_tokens) + ] + ) + + self.iou_prediction_head = MLP( + transformer_dim, iou_head_hidden_dim, self.num_mask_tokens, iou_head_depth + ) + + def forward( + self, + image_embeddings: torch.Tensor, + image_pe: torch.Tensor, + sparse_prompt_embeddings: torch.Tensor, + dense_prompt_embeddings: torch.Tensor, + multimask_output: bool, + ) -> Tuple[torch.Tensor, torch.Tensor]: + """ + Predict masks given image and prompt embeddings. + + Arguments: + image_embeddings (torch.Tensor): the embeddings from the image encoder + image_pe (torch.Tensor): positional encoding with the shape of image_embeddings + sparse_prompt_embeddings (torch.Tensor): the embeddings of the points and boxes + dense_prompt_embeddings (torch.Tensor): the embeddings of the mask inputs + multimask_output (bool): Whether to return multiple masks or a single + mask. + + Returns: + torch.Tensor: batched predicted masks + torch.Tensor: batched predictions of mask quality + """ + masks, iou_pred = self.predict_masks( + image_embeddings=image_embeddings, + image_pe=image_pe, + sparse_prompt_embeddings=sparse_prompt_embeddings, + dense_prompt_embeddings=dense_prompt_embeddings, + ) + + # Select the correct mask or masks for outptu + if multimask_output: + mask_slice = slice(1, None) + else: + mask_slice = slice(0, 1) + masks = masks[:, mask_slice, :, :] + iou_pred = iou_pred[:, mask_slice] + + # Prepare output + return masks, iou_pred + + def predict_masks( + self, + image_embeddings: torch.Tensor, + image_pe: torch.Tensor, + sparse_prompt_embeddings: torch.Tensor, + dense_prompt_embeddings: torch.Tensor, + ) -> Tuple[torch.Tensor, torch.Tensor]: + """Predicts masks. See 'forward' for more details.""" + # Concatenate output tokens + output_tokens = torch.cat( + [self.iou_token.weight, self.mask_tokens.weight], dim=0 + ) + output_tokens = output_tokens.unsqueeze(0).expand( + sparse_prompt_embeddings.size(0), -1, -1 + ) + tokens = torch.cat((output_tokens, sparse_prompt_embeddings), dim=1) + + # Expand per-image data in batch direction to be per-mask + src = torch.repeat_interleave(image_embeddings, tokens.shape[0], dim=0) + src = src + dense_prompt_embeddings + pos_src = torch.repeat_interleave(image_pe, tokens.shape[0], dim=0) + b, c, h, w = src.shape + + # Run the transformer + hs, src = self.transformer(src, pos_src, tokens) + iou_token_out = hs[:, 0, :] + mask_tokens_out = hs[:, 1 : (1 + self.num_mask_tokens), :] + + # Upscale mask embeddings and predict masks using the mask tokens + src = src.transpose(1, 2).view(b, c, h, w) + upscaled_embedding = self.output_upscaling(src) + hyper_in_list: List[torch.Tensor] = [] + for i in range(self.num_mask_tokens): + hyper_in_list.append( + self.output_hypernetworks_mlps[i](mask_tokens_out[:, i, :]) + ) + hyper_in = torch.stack(hyper_in_list, dim=1) + b, c, h, w = upscaled_embedding.shape + masks = (hyper_in @ upscaled_embedding.view(b, c, h * w)).view(b, -1, h, w) + + # Generate mask quality predictions + iou_pred = self.iou_prediction_head(iou_token_out) + + return masks, iou_pred + +# https://github.com/SysCV/sam-hq/blob/main/segment_anything/modeling/mask_decoder_hq.py#L17 +class MaskDecoderHQ(nn.Module): + def __init__( + self, + *, + transformer_dim: int, + transformer: nn.Module, + num_multimask_outputs: int = 3, + activation: Type[nn.Module] = nn.GELU, + iou_head_depth: int = 3, + iou_head_hidden_dim: int = 256, + vit_dim: int = 1024, + ) -> None: + """ + Predicts masks given an image and prompt embeddings, using a + transformer architecture. + + Arguments: + transformer_dim (int): the channel dimension of the transformer + transformer (nn.Module): the transformer used to predict masks + num_multimask_outputs (int): the number of masks to predict + when disambiguating masks + activation (nn.Module): the type of activation to use when + upscaling masks + iou_head_depth (int): the depth of the MLP used to predict + mask quality + iou_head_hidden_dim (int): the hidden dimension of the MLP + used to predict mask quality + """ + super().__init__() + self.transformer_dim = transformer_dim + self.transformer = transformer + + self.num_multimask_outputs = num_multimask_outputs + + self.iou_token = nn.Embedding(1, transformer_dim) + self.num_mask_tokens = num_multimask_outputs + 1 + self.mask_tokens = nn.Embedding(self.num_mask_tokens, transformer_dim) + + self.output_upscaling = nn.Sequential( + nn.ConvTranspose2d( + transformer_dim, transformer_dim // 4, kernel_size=2, stride=2 + ), + LayerNorm2d(transformer_dim // 4), + activation(), + nn.ConvTranspose2d( + transformer_dim // 4, transformer_dim // 8, kernel_size=2, stride=2 + ), + activation(), + ) + self.output_hypernetworks_mlps = nn.ModuleList( + [ + MLP(transformer_dim, transformer_dim, transformer_dim // 8, 3) + for i in range(self.num_mask_tokens) + ] + ) + + self.iou_prediction_head = MLP( + transformer_dim, iou_head_hidden_dim, self.num_mask_tokens, iou_head_depth + ) + + # HQ-SAM parameters + self.hf_token = nn.Embedding(1, transformer_dim) # HQ-Ouptput-Token + self.hf_mlp = MLP( + transformer_dim, transformer_dim, transformer_dim // 8, 3 + ) # corresponding new MLP layer for HQ-Ouptput-Token + self.num_mask_tokens = self.num_mask_tokens + 1 + + # three conv fusion layers for obtaining HQ-Feature + self.compress_vit_feat = nn.Sequential( + nn.ConvTranspose2d(vit_dim, transformer_dim, kernel_size=2, stride=2), + LayerNorm2d(transformer_dim), + nn.GELU(), + nn.ConvTranspose2d( + transformer_dim, transformer_dim // 8, kernel_size=2, stride=2 + ), + ) + + self.embedding_encoder = nn.Sequential( + nn.ConvTranspose2d( + transformer_dim, transformer_dim // 4, kernel_size=2, stride=2 + ), + LayerNorm2d(transformer_dim // 4), + nn.GELU(), + nn.ConvTranspose2d( + transformer_dim // 4, transformer_dim // 8, kernel_size=2, stride=2 + ), + ) + self.embedding_maskfeature = nn.Sequential( + nn.Conv2d(transformer_dim // 8, transformer_dim // 4, 3, 1, 1), + LayerNorm2d(transformer_dim // 4), + nn.GELU(), + nn.Conv2d(transformer_dim // 4, transformer_dim // 8, 3, 1, 1), + ) + + def forward( + self, + image_embeddings: torch.Tensor, + image_pe: torch.Tensor, + sparse_prompt_embeddings: torch.Tensor, + dense_prompt_embeddings: torch.Tensor, + multimask_output: bool, + hq_token_only: bool, + interm_embeddings: torch.Tensor, + ) -> Tuple[torch.Tensor, torch.Tensor]: + """ + Predict masks given image and prompt embeddings. + + Arguments: + image_embeddings (torch.Tensor): the embeddings from the ViT image encoder + image_pe (torch.Tensor): positional encoding with the shape of image_embeddings + sparse_prompt_embeddings (torch.Tensor): the embeddings of the points and boxes + dense_prompt_embeddings (torch.Tensor): the embeddings of the mask inputs + multimask_output (bool): Whether to return multiple masks or a single + mask. + + Returns: + torch.Tensor: batched predicted masks + torch.Tensor: batched predictions of mask quality + """ + vit_features = interm_embeddings[0].permute( + 0, 3, 1, 2 + ) # early-layer ViT feature, after 1st global attention block in ViT + hq_features = self.embedding_encoder(image_embeddings) + self.compress_vit_feat( + vit_features + ) + + masks, iou_pred = self.predict_masks( + image_embeddings=image_embeddings, + image_pe=image_pe, + sparse_prompt_embeddings=sparse_prompt_embeddings, + dense_prompt_embeddings=dense_prompt_embeddings, + hq_features=hq_features, + ) + + # Select the correct mask or masks for output + if multimask_output: + # mask with highest score + mask_slice = slice(1, self.num_mask_tokens - 1) + iou_pred = iou_pred[:, mask_slice] + iou_pred, max_iou_idx = torch.max(iou_pred, dim=1) + iou_pred = iou_pred.unsqueeze(1) + masks_multi = masks[:, mask_slice, :, :] + masks_sam = masks_multi[ + torch.arange(masks_multi.size(0)), max_iou_idx + ].unsqueeze(1) + else: + # singale mask output, default + mask_slice = slice(0, 1) + iou_pred = iou_pred[:, mask_slice] + masks_sam = masks[:, mask_slice] + + masks_hq = masks[:, slice(self.num_mask_tokens - 1, self.num_mask_tokens)] + if hq_token_only: + masks = masks_hq + else: + masks = masks_sam + masks_hq + # Prepare output + return masks, iou_pred + + def predict_masks( + self, + image_embeddings: torch.Tensor, + image_pe: torch.Tensor, + sparse_prompt_embeddings: torch.Tensor, + dense_prompt_embeddings: torch.Tensor, + hq_features: torch.Tensor, + ) -> Tuple[torch.Tensor, torch.Tensor]: + """Predicts masks. See 'forward' for more details.""" + # Concatenate output tokens + output_tokens = torch.cat( + [self.iou_token.weight, self.mask_tokens.weight, self.hf_token.weight], + dim=0, + ) + output_tokens = output_tokens.unsqueeze(0).expand( + sparse_prompt_embeddings.size(0), -1, -1 + ) + tokens = torch.cat((output_tokens, sparse_prompt_embeddings), dim=1) + + # Expand per-image data in batch direction to be per-mask + src = torch.repeat_interleave(image_embeddings, tokens.shape[0], dim=0) + src = src + dense_prompt_embeddings + pos_src = torch.repeat_interleave(image_pe, tokens.shape[0], dim=0) + b, c, h, w = src.shape + + # Run the transformer + hs, src = self.transformer(src, pos_src, tokens) + iou_token_out = hs[:, 0, :] + mask_tokens_out = hs[:, 1 : (1 + self.num_mask_tokens), :] + + # Upscale mask embeddings and predict masks using the mask tokens + src = src.transpose(1, 2).view(b, c, h, w) + + upscaled_embedding_sam = self.output_upscaling(src) + upscaled_embedding_hq = self.embedding_maskfeature( + upscaled_embedding_sam + ) + hq_features.repeat(b, 1, 1, 1) + + hyper_in_list: List[torch.Tensor] = [] + for i in range(self.num_mask_tokens): + if i < self.num_mask_tokens - 1: + hyper_in_list.append( + self.output_hypernetworks_mlps[i](mask_tokens_out[:, i, :]) + ) + else: + hyper_in_list.append(self.hf_mlp(mask_tokens_out[:, i, :])) + + hyper_in = torch.stack(hyper_in_list, dim=1) + b, c, h, w = upscaled_embedding_sam.shape + + masks_sam = ( + hyper_in[:, : self.num_mask_tokens - 1] + @ upscaled_embedding_sam.view(b, c, h * w) + ).view(b, -1, h, w) + masks_sam_hq = ( + hyper_in[:, self.num_mask_tokens - 1 :] + @ upscaled_embedding_hq.view(b, c, h * w) + ).view(b, -1, h, w) + masks = torch.cat([masks_sam, masks_sam_hq], dim=1) + # Generate mask quality predictions + iou_pred = self.iou_prediction_head(iou_token_out) + + return masks, iou_pred + + +# Lightly adapted from +# https://github.com/facebookresearch/MaskFormer/blob/main/mask_former/modeling/transformer/transformer_predictor.py # noqa +class MLP(nn.Module): + def __init__( + self, + input_dim: int, + hidden_dim: int, + output_dim: int, + num_layers: int, + sigmoid_output: bool = False, + ) -> None: + super().__init__() + self.num_layers = num_layers + h = [hidden_dim] * (num_layers - 1) + self.layers = nn.ModuleList( + nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim]) + ) + self.sigmoid_output = sigmoid_output + + def forward(self, x): + for i, layer in enumerate(self.layers): + x = F.relu(layer(x)) if i < self.num_layers - 1 else layer(x) + if self.sigmoid_output: + x = F.sigmoid(x) + return x diff --git a/py/iopaint/plugins/segment_anything/modeling/prompt_encoder.py b/py/iopaint/plugins/segment_anything/modeling/prompt_encoder.py new file mode 100644 index 0000000..c3143f4 --- /dev/null +++ b/py/iopaint/plugins/segment_anything/modeling/prompt_encoder.py @@ -0,0 +1,214 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import numpy as np +import torch +from torch import nn + +from typing import Any, Optional, Tuple, Type + +from .common import LayerNorm2d + + +class PromptEncoder(nn.Module): + def __init__( + self, + embed_dim: int, + image_embedding_size: Tuple[int, int], + input_image_size: Tuple[int, int], + mask_in_chans: int, + activation: Type[nn.Module] = nn.GELU, + ) -> None: + """ + Encodes prompts for input to SAM's mask decoder. + + Arguments: + embed_dim (int): The prompts' embedding dimension + image_embedding_size (tuple(int, int)): The spatial size of the + image embedding, as (H, W). + input_image_size (int): The padded size of the image as input + to the image encoder, as (H, W). + mask_in_chans (int): The number of hidden channels used for + encoding input masks. + activation (nn.Module): The activation to use when encoding + input masks. + """ + super().__init__() + self.embed_dim = embed_dim + self.input_image_size = input_image_size + self.image_embedding_size = image_embedding_size + self.pe_layer = PositionEmbeddingRandom(embed_dim // 2) + + self.num_point_embeddings: int = 4 # pos/neg point + 2 box corners + point_embeddings = [nn.Embedding(1, embed_dim) for i in range(self.num_point_embeddings)] + self.point_embeddings = nn.ModuleList(point_embeddings) + self.not_a_point_embed = nn.Embedding(1, embed_dim) + + self.mask_input_size = (4 * image_embedding_size[0], 4 * image_embedding_size[1]) + self.mask_downscaling = nn.Sequential( + nn.Conv2d(1, mask_in_chans // 4, kernel_size=2, stride=2), + LayerNorm2d(mask_in_chans // 4), + activation(), + nn.Conv2d(mask_in_chans // 4, mask_in_chans, kernel_size=2, stride=2), + LayerNorm2d(mask_in_chans), + activation(), + nn.Conv2d(mask_in_chans, embed_dim, kernel_size=1), + ) + self.no_mask_embed = nn.Embedding(1, embed_dim) + + def get_dense_pe(self) -> torch.Tensor: + """ + Returns the positional encoding used to encode point prompts, + applied to a dense set of points the shape of the image encoding. + + Returns: + torch.Tensor: Positional encoding with shape + 1x(embed_dim)x(embedding_h)x(embedding_w) + """ + return self.pe_layer(self.image_embedding_size).unsqueeze(0) + + def _embed_points( + self, + points: torch.Tensor, + labels: torch.Tensor, + pad: bool, + ) -> torch.Tensor: + """Embeds point prompts.""" + points = points + 0.5 # Shift to center of pixel + if pad: + padding_point = torch.zeros((points.shape[0], 1, 2), device=points.device) + padding_label = -torch.ones((labels.shape[0], 1), device=labels.device) + points = torch.cat([points, padding_point], dim=1) + labels = torch.cat([labels, padding_label], dim=1) + point_embedding = self.pe_layer.forward_with_coords(points, self.input_image_size) + point_embedding[labels == -1] = 0.0 + point_embedding[labels == -1] += self.not_a_point_embed.weight + point_embedding[labels == 0] += self.point_embeddings[0].weight + point_embedding[labels == 1] += self.point_embeddings[1].weight + return point_embedding + + def _embed_boxes(self, boxes: torch.Tensor) -> torch.Tensor: + """Embeds box prompts.""" + boxes = boxes + 0.5 # Shift to center of pixel + coords = boxes.reshape(-1, 2, 2) + corner_embedding = self.pe_layer.forward_with_coords(coords, self.input_image_size) + corner_embedding[:, 0, :] += self.point_embeddings[2].weight + corner_embedding[:, 1, :] += self.point_embeddings[3].weight + return corner_embedding + + def _embed_masks(self, masks: torch.Tensor) -> torch.Tensor: + """Embeds mask inputs.""" + mask_embedding = self.mask_downscaling(masks) + return mask_embedding + + def _get_batch_size( + self, + points: Optional[Tuple[torch.Tensor, torch.Tensor]], + boxes: Optional[torch.Tensor], + masks: Optional[torch.Tensor], + ) -> int: + """ + Gets the batch size of the output given the batch size of the input prompts. + """ + if points is not None: + return points[0].shape[0] + elif boxes is not None: + return boxes.shape[0] + elif masks is not None: + return masks.shape[0] + else: + return 1 + + def _get_device(self) -> torch.device: + return self.point_embeddings[0].weight.device + + def forward( + self, + points: Optional[Tuple[torch.Tensor, torch.Tensor]], + boxes: Optional[torch.Tensor], + masks: Optional[torch.Tensor], + ) -> Tuple[torch.Tensor, torch.Tensor]: + """ + Embeds different types of prompts, returning both sparse and dense + embeddings. + + Arguments: + points (tuple(torch.Tensor, torch.Tensor) or none): point coordinates + and labels to embed. + boxes (torch.Tensor or none): boxes to embed + masks (torch.Tensor or none): masks to embed + + Returns: + torch.Tensor: sparse embeddings for the points and boxes, with shape + BxNx(embed_dim), where N is determined by the number of input points + and boxes. + torch.Tensor: dense embeddings for the masks, in the shape + Bx(embed_dim)x(embed_H)x(embed_W) + """ + bs = self._get_batch_size(points, boxes, masks) + sparse_embeddings = torch.empty((bs, 0, self.embed_dim), device=self._get_device()) + if points is not None: + coords, labels = points + point_embeddings = self._embed_points(coords, labels, pad=(boxes is None)) + sparse_embeddings = torch.cat([sparse_embeddings, point_embeddings], dim=1) + if boxes is not None: + box_embeddings = self._embed_boxes(boxes) + sparse_embeddings = torch.cat([sparse_embeddings, box_embeddings], dim=1) + + if masks is not None: + dense_embeddings = self._embed_masks(masks) + else: + dense_embeddings = self.no_mask_embed.weight.reshape(1, -1, 1, 1).expand( + bs, -1, self.image_embedding_size[0], self.image_embedding_size[1] + ) + + return sparse_embeddings, dense_embeddings + + +class PositionEmbeddingRandom(nn.Module): + """ + Positional encoding using random spatial frequencies. + """ + + def __init__(self, num_pos_feats: int = 64, scale: Optional[float] = None) -> None: + super().__init__() + if scale is None or scale <= 0.0: + scale = 1.0 + self.register_buffer( + "positional_encoding_gaussian_matrix", + scale * torch.randn((2, num_pos_feats)), + ) + + def _pe_encoding(self, coords: torch.Tensor) -> torch.Tensor: + """Positionally encode points that are normalized to [0,1].""" + # assuming coords are in [0, 1]^2 square and have d_1 x ... x d_n x 2 shape + coords = 2 * coords - 1 + coords = coords @ self.positional_encoding_gaussian_matrix + coords = 2 * np.pi * coords + # outputs d_1 x ... x d_n x C shape + return torch.cat([torch.sin(coords), torch.cos(coords)], dim=-1) + + def forward(self, size: Tuple[int, int]) -> torch.Tensor: + """Generate positional encoding for a grid of the specified size.""" + h, w = size + device: Any = self.positional_encoding_gaussian_matrix.device + grid = torch.ones((h, w), device=device, dtype=torch.float32) + y_embed = grid.cumsum(dim=0) - 0.5 + x_embed = grid.cumsum(dim=1) - 0.5 + y_embed = y_embed / h + x_embed = x_embed / w + + pe = self._pe_encoding(torch.stack([x_embed, y_embed], dim=-1)) + return pe.permute(2, 0, 1) # C x H x W + + def forward_with_coords( + self, coords_input: torch.Tensor, image_size: Tuple[int, int] + ) -> torch.Tensor: + """Positionally encode points that are not normalized to [0,1].""" + coords = coords_input.clone() + coords[:, :, 0] = coords[:, :, 0] / image_size[1] + coords[:, :, 1] = coords[:, :, 1] / image_size[0] + return self._pe_encoding(coords.to(torch.float)) # B x N x C diff --git a/py/iopaint/plugins/segment_anything/modeling/sam.py b/py/iopaint/plugins/segment_anything/modeling/sam.py new file mode 100644 index 0000000..303bc2f --- /dev/null +++ b/py/iopaint/plugins/segment_anything/modeling/sam.py @@ -0,0 +1,174 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import torch +from torch import nn +from torch.nn import functional as F + +from typing import Any, Dict, List, Tuple + +from .image_encoder import ImageEncoderViT +from .mask_decoder import MaskDecoder +from .prompt_encoder import PromptEncoder + + +class Sam(nn.Module): + mask_threshold: float = 0.0 + image_format: str = "RGB" + + def __init__( + self, + image_encoder: ImageEncoderViT, + prompt_encoder: PromptEncoder, + mask_decoder: MaskDecoder, + pixel_mean: List[float] = [123.675, 116.28, 103.53], + pixel_std: List[float] = [58.395, 57.12, 57.375], + ) -> None: + """ + SAM predicts object masks from an image and input prompts. + + Arguments: + image_encoder (ImageEncoderViT): The backbone used to encode the + image into image embeddings that allow for efficient mask prediction. + prompt_encoder (PromptEncoder): Encodes various types of input prompts. + mask_decoder (MaskDecoder): Predicts masks from the image embeddings + and encoded prompts. + pixel_mean (list(float)): Mean values for normalizing pixels in the input image. + pixel_std (list(float)): Std values for normalizing pixels in the input image. + """ + super().__init__() + self.image_encoder = image_encoder + self.prompt_encoder = prompt_encoder + self.mask_decoder = mask_decoder + self.register_buffer("pixel_mean", torch.Tensor(pixel_mean).view(-1, 1, 1), False) + self.register_buffer("pixel_std", torch.Tensor(pixel_std).view(-1, 1, 1), False) + + @property + def device(self) -> Any: + return self.pixel_mean.device + + @torch.no_grad() + def forward( + self, + batched_input: List[Dict[str, Any]], + multimask_output: bool, + ) -> List[Dict[str, torch.Tensor]]: + """ + Predicts masks end-to-end from provided images and prompts. + If prompts are not known in advance, using SamPredictor is + recommended over calling the model directly. + + Arguments: + batched_input (list(dict)): A list over input images, each a + dictionary with the following keys. A prompt key can be + excluded if it is not present. + 'image': The image as a torch tensor in 3xHxW format, + already transformed for input to the model. + 'original_size': (tuple(int, int)) The original size of + the image before transformation, as (H, W). + 'point_coords': (torch.Tensor) Batched point prompts for + this image, with shape BxNx2. Already transformed to the + input frame of the model. + 'point_labels': (torch.Tensor) Batched labels for point prompts, + with shape BxN. + 'boxes': (torch.Tensor) Batched box inputs, with shape Bx4. + Already transformed to the input frame of the model. + 'mask_inputs': (torch.Tensor) Batched mask inputs to the model, + in the form Bx1xHxW. + multimask_output (bool): Whether the model should predict multiple + disambiguating masks, or return a single mask. + + Returns: + (list(dict)): A list over input images, where each element is + as dictionary with the following keys. + 'masks': (torch.Tensor) Batched binary mask predictions, + with shape BxCxHxW, where B is the number of input promts, + C is determiend by multimask_output, and (H, W) is the + original size of the image. + 'iou_predictions': (torch.Tensor) The model's predictions + of mask quality, in shape BxC. + 'low_res_logits': (torch.Tensor) Low resolution logits with + shape BxCxHxW, where H=W=256. Can be passed as mask input + to subsequent iterations of prediction. + """ + input_images = torch.stack([self.preprocess(x["image"]) for x in batched_input], dim=0) + image_embeddings = self.image_encoder(input_images) + + outputs = [] + for image_record, curr_embedding in zip(batched_input, image_embeddings): + if "point_coords" in image_record: + points = (image_record["point_coords"], image_record["point_labels"]) + else: + points = None + sparse_embeddings, dense_embeddings = self.prompt_encoder( + points=points, + boxes=image_record.get("boxes", None), + masks=image_record.get("mask_inputs", None), + ) + low_res_masks, iou_predictions = self.mask_decoder( + image_embeddings=curr_embedding.unsqueeze(0), + image_pe=self.prompt_encoder.get_dense_pe(), + sparse_prompt_embeddings=sparse_embeddings, + dense_prompt_embeddings=dense_embeddings, + multimask_output=multimask_output, + ) + masks = self.postprocess_masks( + low_res_masks, + input_size=image_record["image"].shape[-2:], + original_size=image_record["original_size"], + ) + masks = masks > self.mask_threshold + outputs.append( + { + "masks": masks, + "iou_predictions": iou_predictions, + "low_res_logits": low_res_masks, + } + ) + return outputs + + def postprocess_masks( + self, + masks: torch.Tensor, + input_size: Tuple[int, ...], + original_size: Tuple[int, ...], + ) -> torch.Tensor: + """ + Remove padding and upscale masks to the original image size. + + Arguments: + masks (torch.Tensor): Batched masks from the mask_decoder, + in BxCxHxW format. + input_size (tuple(int, int)): The size of the image input to the + model, in (H, W) format. Used to remove padding. + original_size (tuple(int, int)): The original size of the image + before resizing for input to the model, in (H, W) format. + + Returns: + (torch.Tensor): Batched masks in BxCxHxW format, where (H, W) + is given by original_size. + """ + masks = F.interpolate( + masks, + (self.image_encoder.img_size, self.image_encoder.img_size), + mode="bilinear", + align_corners=False, + ) + masks = masks[..., : input_size[0], : input_size[1]] + masks = F.interpolate(masks, original_size, mode="bilinear", align_corners=False) + return masks + + def preprocess(self, x: torch.Tensor) -> torch.Tensor: + """Normalize pixel values and pad to a square input.""" + # Normalize colors + x = (x - self.pixel_mean) / self.pixel_std + + # Pad + h, w = x.shape[-2:] + padh = self.image_encoder.img_size - h + padw = self.image_encoder.img_size - w + x = F.pad(x, (0, padw, 0, padh)) + return x diff --git a/py/iopaint/plugins/segment_anything/modeling/sam_hq.py b/py/iopaint/plugins/segment_anything/modeling/sam_hq.py new file mode 100644 index 0000000..d2ae3a3 --- /dev/null +++ b/py/iopaint/plugins/segment_anything/modeling/sam_hq.py @@ -0,0 +1,177 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import torch +from torch import nn +from torch.nn import functional as F + +from typing import Any, Dict, List, Tuple + +from .image_encoder import ImageEncoderViT +from .mask_decoder import MaskDecoder +from .prompt_encoder import PromptEncoder + + +class SamHQ(nn.Module): + mask_threshold: float = 0.0 + image_format: str = "RGB" + + def __init__( + self, + image_encoder: ImageEncoderViT, + prompt_encoder: PromptEncoder, + mask_decoder: MaskDecoder, + pixel_mean: List[float] = [123.675, 116.28, 103.53], + pixel_std: List[float] = [58.395, 57.12, 57.375], + ) -> None: + """ + SAM predicts object masks from an image and input prompts. + + Arguments: + image_encoder (ImageEncoderViT): The backbone used to encode the + image into image embeddings that allow for efficient mask prediction. + prompt_encoder (PromptEncoder): Encodes various types of input prompts. + mask_decoder (MaskDecoder): Predicts masks from the image embeddings + and encoded prompts. + pixel_mean (list(float)): Mean values for normalizing pixels in the input image. + pixel_std (list(float)): Std values for normalizing pixels in the input image. + """ + super().__init__() + self.image_encoder = image_encoder + self.prompt_encoder = prompt_encoder + self.mask_decoder = mask_decoder + self.register_buffer("pixel_mean", torch.Tensor(pixel_mean).view(-1, 1, 1), False) + self.register_buffer("pixel_std", torch.Tensor(pixel_std).view(-1, 1, 1), False) + + @property + def device(self) -> Any: + return self.pixel_mean.device + + def forward( + self, + batched_input: List[Dict[str, Any]], + multimask_output: bool, + hq_token_only: bool =False, + ) -> List[Dict[str, torch.Tensor]]: + """ + Predicts masks end-to-end from provided images and prompts. + If prompts are not known in advance, using SamPredictor is + recommended over calling the model directly. + + Arguments: + batched_input (list(dict)): A list over input images, each a + dictionary with the following keys. A prompt key can be + excluded if it is not present. + 'image': The image as a torch tensor in 3xHxW format, + already transformed for input to the model. + 'original_size': (tuple(int, int)) The original size of + the image before transformation, as (H, W). + 'point_coords': (torch.Tensor) Batched point prompts for + this image, with shape BxNx2. Already transformed to the + input frame of the model. + 'point_labels': (torch.Tensor) Batched labels for point prompts, + with shape BxN. + 'boxes': (torch.Tensor) Batched box inputs, with shape Bx4. + Already transformed to the input frame of the model. + 'mask_inputs': (torch.Tensor) Batched mask inputs to the model, + in the form Bx1xHxW. + multimask_output (bool): Whether the model should predict multiple + disambiguating masks, or return a single mask. + + Returns: + (list(dict)): A list over input images, where each element is + as dictionary with the following keys. + 'masks': (torch.Tensor) Batched binary mask predictions, + with shape BxCxHxW, where B is the number of input prompts, + C is determined by multimask_output, and (H, W) is the + original size of the image. + 'iou_predictions': (torch.Tensor) The model's predictions + of mask quality, in shape BxC. + 'low_res_logits': (torch.Tensor) Low resolution logits with + shape BxCxHxW, where H=W=256. Can be passed as mask input + to subsequent iterations of prediction. + """ + input_images = torch.stack([self.preprocess(x["image"]) for x in batched_input], dim=0) + image_embeddings, interm_embeddings = self.image_encoder(input_images) + interm_embeddings = interm_embeddings[0] # early layer + + outputs = [] + for image_record, curr_embedding, curr_interm in zip(batched_input, image_embeddings, interm_embeddings): + if "point_coords" in image_record: + points = (image_record["point_coords"], image_record["point_labels"]) + else: + points = None + sparse_embeddings, dense_embeddings = self.prompt_encoder( + points=points, + boxes=image_record.get("boxes", None), + masks=image_record.get("mask_inputs", None), + ) + low_res_masks, iou_predictions = self.mask_decoder( + image_embeddings=curr_embedding.unsqueeze(0), + image_pe=self.prompt_encoder.get_dense_pe(), + sparse_prompt_embeddings=sparse_embeddings, + dense_prompt_embeddings=dense_embeddings, + multimask_output=multimask_output, + hq_token_only=hq_token_only, + interm_embeddings=curr_interm.unsqueeze(0).unsqueeze(0), + ) + masks = self.postprocess_masks( + low_res_masks, + input_size=image_record["image"].shape[-2:], + original_size=image_record["original_size"], + ) + masks = masks > self.mask_threshold + outputs.append( + { + "masks": masks, + "iou_predictions": iou_predictions, + "low_res_logits": low_res_masks, + } + ) + return outputs + + def postprocess_masks( + self, + masks: torch.Tensor, + input_size: Tuple[int, ...], + original_size: Tuple[int, ...], + ) -> torch.Tensor: + """ + Remove padding and upscale masks to the original image size. + + Arguments: + masks (torch.Tensor): Batched masks from the mask_decoder, + in BxCxHxW format. + input_size (tuple(int, int)): The size of the image input to the + model, in (H, W) format. Used to remove padding. + original_size (tuple(int, int)): The original size of the image + before resizing for input to the model, in (H, W) format. + + Returns: + (torch.Tensor): Batched masks in BxCxHxW format, where (H, W) + is given by original_size. + """ + masks = F.interpolate( + masks, + (self.image_encoder.img_size, self.image_encoder.img_size), + mode="bilinear", + align_corners=False, + ) + masks = masks[..., : input_size[0], : input_size[1]] + masks = F.interpolate(masks, original_size, mode="bilinear", align_corners=False) + return masks + + def preprocess(self, x: torch.Tensor) -> torch.Tensor: + """Normalize pixel values and pad to a square input.""" + # Normalize colors + x = (x - self.pixel_mean) / self.pixel_std + + # Pad + h, w = x.shape[-2:] + padh = self.image_encoder.img_size - h + padw = self.image_encoder.img_size - w + x = F.pad(x, (0, padw, 0, padh)) + return x \ No newline at end of file diff --git a/py/iopaint/plugins/segment_anything/modeling/tiny_vit_sam.py b/py/iopaint/plugins/segment_anything/modeling/tiny_vit_sam.py new file mode 100644 index 0000000..a5127c7 --- /dev/null +++ b/py/iopaint/plugins/segment_anything/modeling/tiny_vit_sam.py @@ -0,0 +1,822 @@ +# -------------------------------------------------------- +# TinyViT Model Architecture +# Copyright (c) 2022 Microsoft +# Adapted from LeViT and Swin Transformer +# LeViT: (https://github.com/facebookresearch/levit) +# Swin: (https://github.com/microsoft/swin-transformer) +# Build the TinyViT Model +# -------------------------------------------------------- + +import collections +import itertools +import math +import warnings +import torch +import torch.nn as nn +import torch.nn.functional as F +import torch.utils.checkpoint as checkpoint +from typing import Tuple + + +def _ntuple(n): + def parse(x): + if isinstance(x, collections.abc.Iterable) and not isinstance(x, str): + return x + return tuple(itertools.repeat(x, n)) + + return parse + + +to_2tuple = _ntuple(2) + + +def _trunc_normal_(tensor, mean, std, a, b): + # Cut & paste from PyTorch official master until it's in a few official releases - RW + # Method based on https://people.sc.fsu.edu/~jburkardt/presentations/truncated_normal.pdf + def norm_cdf(x): + # Computes standard normal cumulative distribution function + return (1.0 + math.erf(x / math.sqrt(2.0))) / 2.0 + + if (mean < a - 2 * std) or (mean > b + 2 * std): + warnings.warn( + "mean is more than 2 std from [a, b] in nn.init.trunc_normal_. " + "The distribution of values may be incorrect.", + stacklevel=2, + ) + + # Values are generated by using a truncated uniform distribution and + # then using the inverse CDF for the normal distribution. + # Get upper and lower cdf values + l = norm_cdf((a - mean) / std) + u = norm_cdf((b - mean) / std) + + # Uniformly fill tensor with values from [l, u], then translate to + # [2l-1, 2u-1]. + tensor.uniform_(2 * l - 1, 2 * u - 1) + + # Use inverse cdf transform for normal distribution to get truncated + # standard normal + tensor.erfinv_() + + # Transform to proper mean, std + tensor.mul_(std * math.sqrt(2.0)) + tensor.add_(mean) + + # Clamp to ensure it's in the proper range + tensor.clamp_(min=a, max=b) + return tensor + + +def trunc_normal_(tensor, mean=0.0, std=1.0, a=-2.0, b=2.0): + # type: (Tensor, float, float, float, float) -> Tensor + r"""Fills the input Tensor with values drawn from a truncated + normal distribution. The values are effectively drawn from the + normal distribution :math:`\mathcal{N}(\text{mean}, \text{std}^2)` + with values outside :math:`[a, b]` redrawn until they are within + the bounds. The method used for generating the random values works + best when :math:`a \leq \text{mean} \leq b`. + + NOTE: this impl is similar to the PyTorch trunc_normal_, the bounds [a, b] are + applied while sampling the normal with mean/std applied, therefore a, b args + should be adjusted to match the range of mean, std args. + + Args: + tensor: an n-dimensional `torch.Tensor` + mean: the mean of the normal distribution + std: the standard deviation of the normal distribution + a: the minimum cutoff value + b: the maximum cutoff value + Examples: + >>> w = torch.empty(3, 5) + >>> nn.init.trunc_normal_(w) + """ + with torch.no_grad(): + return _trunc_normal_(tensor, mean, std, a, b) + + +def drop_path( + x, drop_prob: float = 0.0, training: bool = False, scale_by_keep: bool = True +): + """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). + + This is the same as the DropConnect impl I created for EfficientNet, etc networks, however, + the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper... + See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for + changing the layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use + 'survival rate' as the argument. + + """ + if drop_prob == 0.0 or not training: + return x + keep_prob = 1 - drop_prob + shape = (x.shape[0],) + (1,) * ( + x.ndim - 1 + ) # work with diff dim tensors, not just 2D ConvNets + random_tensor = x.new_empty(shape).bernoulli_(keep_prob) + if keep_prob > 0.0 and scale_by_keep: + random_tensor.div_(keep_prob) + return x * random_tensor + + +class TimmDropPath(nn.Module): + """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).""" + + def __init__(self, drop_prob: float = 0.0, scale_by_keep: bool = True): + super(TimmDropPath, self).__init__() + self.drop_prob = drop_prob + self.scale_by_keep = scale_by_keep + + def forward(self, x): + return drop_path(x, self.drop_prob, self.training, self.scale_by_keep) + + def extra_repr(self): + return f"drop_prob={round(self.drop_prob,3):0.3f}" + + +class Conv2d_BN(torch.nn.Sequential): + def __init__( + self, a, b, ks=1, stride=1, pad=0, dilation=1, groups=1, bn_weight_init=1 + ): + super().__init__() + self.add_module( + "c", torch.nn.Conv2d(a, b, ks, stride, pad, dilation, groups, bias=False) + ) + bn = torch.nn.BatchNorm2d(b) + torch.nn.init.constant_(bn.weight, bn_weight_init) + torch.nn.init.constant_(bn.bias, 0) + self.add_module("bn", bn) + + @torch.no_grad() + def fuse(self): + c, bn = self._modules.values() + w = bn.weight / (bn.running_var + bn.eps) ** 0.5 + w = c.weight * w[:, None, None, None] + b = bn.bias - bn.running_mean * bn.weight / (bn.running_var + bn.eps) ** 0.5 + m = torch.nn.Conv2d( + w.size(1) * self.c.groups, + w.size(0), + w.shape[2:], + stride=self.c.stride, + padding=self.c.padding, + dilation=self.c.dilation, + groups=self.c.groups, + ) + m.weight.data.copy_(w) + m.bias.data.copy_(b) + return m + + +class DropPath(TimmDropPath): + def __init__(self, drop_prob=None): + super().__init__(drop_prob=drop_prob) + self.drop_prob = drop_prob + + def __repr__(self): + msg = super().__repr__() + msg += f"(drop_prob={self.drop_prob})" + return msg + + +class PatchEmbed(nn.Module): + def __init__(self, in_chans, embed_dim, resolution, activation): + super().__init__() + img_size: Tuple[int, int] = to_2tuple(resolution) + self.patches_resolution = (img_size[0] // 4, img_size[1] // 4) + self.num_patches = self.patches_resolution[0] * self.patches_resolution[1] + self.in_chans = in_chans + self.embed_dim = embed_dim + n = embed_dim + self.seq = nn.Sequential( + Conv2d_BN(in_chans, n // 2, 3, 2, 1), + activation(), + Conv2d_BN(n // 2, n, 3, 2, 1), + ) + + def forward(self, x): + return self.seq(x) + + +class MBConv(nn.Module): + def __init__(self, in_chans, out_chans, expand_ratio, activation, drop_path): + super().__init__() + self.in_chans = in_chans + self.hidden_chans = int(in_chans * expand_ratio) + self.out_chans = out_chans + + self.conv1 = Conv2d_BN(in_chans, self.hidden_chans, ks=1) + self.act1 = activation() + + self.conv2 = Conv2d_BN( + self.hidden_chans, + self.hidden_chans, + ks=3, + stride=1, + pad=1, + groups=self.hidden_chans, + ) + self.act2 = activation() + + self.conv3 = Conv2d_BN(self.hidden_chans, out_chans, ks=1, bn_weight_init=0.0) + self.act3 = activation() + + self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity() + + def forward(self, x): + shortcut = x + + x = self.conv1(x) + x = self.act1(x) + + x = self.conv2(x) + x = self.act2(x) + + x = self.conv3(x) + + x = self.drop_path(x) + + x += shortcut + x = self.act3(x) + + return x + + +class PatchMerging(nn.Module): + def __init__(self, input_resolution, dim, out_dim, activation): + super().__init__() + + self.input_resolution = input_resolution + self.dim = dim + self.out_dim = out_dim + self.act = activation() + self.conv1 = Conv2d_BN(dim, out_dim, 1, 1, 0) + stride_c = 2 + if out_dim == 320 or out_dim == 448 or out_dim == 576: + stride_c = 1 + self.conv2 = Conv2d_BN(out_dim, out_dim, 3, stride_c, 1, groups=out_dim) + self.conv3 = Conv2d_BN(out_dim, out_dim, 1, 1, 0) + + def forward(self, x): + if x.ndim == 3: + H, W = self.input_resolution + B = len(x) + # (B, C, H, W) + x = x.view(B, H, W, -1).permute(0, 3, 1, 2) + + x = self.conv1(x) + x = self.act(x) + + x = self.conv2(x) + x = self.act(x) + x = self.conv3(x) + x = x.flatten(2).transpose(1, 2) + return x + + +class ConvLayer(nn.Module): + def __init__( + self, + dim, + input_resolution, + depth, + activation, + drop_path=0.0, + downsample=None, + use_checkpoint=False, + out_dim=None, + conv_expand_ratio=4.0, + ): + super().__init__() + self.dim = dim + self.input_resolution = input_resolution + self.depth = depth + self.use_checkpoint = use_checkpoint + + # build blocks + self.blocks = nn.ModuleList( + [ + MBConv( + dim, + dim, + conv_expand_ratio, + activation, + drop_path[i] if isinstance(drop_path, list) else drop_path, + ) + for i in range(depth) + ] + ) + + # patch merging layer + if downsample is not None: + self.downsample = downsample( + input_resolution, dim=dim, out_dim=out_dim, activation=activation + ) + else: + self.downsample = None + + def forward(self, x): + for blk in self.blocks: + if self.use_checkpoint: + x = checkpoint.checkpoint(blk, x) + else: + x = blk(x) + if self.downsample is not None: + x = self.downsample(x) + return x + + +class Mlp(nn.Module): + def __init__( + self, + in_features, + hidden_features=None, + out_features=None, + act_layer=nn.GELU, + drop=0.0, + ): + super().__init__() + out_features = out_features or in_features + hidden_features = hidden_features or in_features + self.norm = nn.LayerNorm(in_features) + self.fc1 = nn.Linear(in_features, hidden_features) + self.fc2 = nn.Linear(hidden_features, out_features) + self.act = act_layer() + self.drop = nn.Dropout(drop) + + def forward(self, x): + x = self.norm(x) + + x = self.fc1(x) + x = self.act(x) + x = self.drop(x) + x = self.fc2(x) + x = self.drop(x) + return x + + +class Attention(torch.nn.Module): + def __init__( + self, + dim, + key_dim, + num_heads=8, + attn_ratio=4, + resolution=(14, 14), + ): + super().__init__() + # (h, w) + assert isinstance(resolution, tuple) and len(resolution) == 2 + self.num_heads = num_heads + self.scale = key_dim**-0.5 + self.key_dim = key_dim + self.nh_kd = nh_kd = key_dim * num_heads + self.d = int(attn_ratio * key_dim) + self.dh = int(attn_ratio * key_dim) * num_heads + self.attn_ratio = attn_ratio + h = self.dh + nh_kd * 2 + + self.norm = nn.LayerNorm(dim) + self.qkv = nn.Linear(dim, h) + self.proj = nn.Linear(self.dh, dim) + + points = list(itertools.product(range(resolution[0]), range(resolution[1]))) + N = len(points) + attention_offsets = {} + idxs = [] + for p1 in points: + for p2 in points: + offset = (abs(p1[0] - p2[0]), abs(p1[1] - p2[1])) + if offset not in attention_offsets: + attention_offsets[offset] = len(attention_offsets) + idxs.append(attention_offsets[offset]) + self.attention_biases = torch.nn.Parameter( + torch.zeros(num_heads, len(attention_offsets)) + ) + self.register_buffer( + "attention_bias_idxs", torch.LongTensor(idxs).view(N, N), persistent=False + ) + + @torch.no_grad() + def train(self, mode=True): + super().train(mode) + if mode and hasattr(self, "ab"): + del self.ab + else: + self.register_buffer( + "ab", + self.attention_biases[:, self.attention_bias_idxs], + persistent=False, + ) + + def forward(self, x): # x (B,N,C) + B, N, _ = x.shape + + # Normalization + x = self.norm(x) + + qkv = self.qkv(x) + # (B, N, num_heads, d) + q, k, v = qkv.view(B, N, self.num_heads, -1).split( + [self.key_dim, self.key_dim, self.d], dim=3 + ) + # (B, num_heads, N, d) + q = q.permute(0, 2, 1, 3) + k = k.permute(0, 2, 1, 3) + v = v.permute(0, 2, 1, 3) + + attn = (q @ k.transpose(-2, -1)) * self.scale + ( + self.attention_biases[:, self.attention_bias_idxs] + if self.training + else self.ab + ) + attn = attn.softmax(dim=-1) + x = (attn @ v).transpose(1, 2).reshape(B, N, self.dh) + x = self.proj(x) + return x + + +class TinyViTBlock(nn.Module): + r"""TinyViT Block. + + Args: + dim (int): Number of input channels. + input_resolution (tuple[int, int]): Input resolution. + num_heads (int): Number of attention heads. + window_size (int): Window size. + mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. + drop (float, optional): Dropout rate. Default: 0.0 + drop_path (float, optional): Stochastic depth rate. Default: 0.0 + local_conv_size (int): the kernel size of the convolution between + Attention and MLP. Default: 3 + activation: the activation function. Default: nn.GELU + """ + + def __init__( + self, + dim, + input_resolution, + num_heads, + window_size=7, + mlp_ratio=4.0, + drop=0.0, + drop_path=0.0, + local_conv_size=3, + activation=nn.GELU, + ): + super().__init__() + self.dim = dim + self.input_resolution = input_resolution + self.num_heads = num_heads + assert window_size > 0, "window_size must be greater than 0" + self.window_size = window_size + self.mlp_ratio = mlp_ratio + + self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity() + + assert dim % num_heads == 0, "dim must be divisible by num_heads" + head_dim = dim // num_heads + + window_resolution = (window_size, window_size) + self.attn = Attention( + dim, head_dim, num_heads, attn_ratio=1, resolution=window_resolution + ) + + mlp_hidden_dim = int(dim * mlp_ratio) + mlp_activation = activation + self.mlp = Mlp( + in_features=dim, + hidden_features=mlp_hidden_dim, + act_layer=mlp_activation, + drop=drop, + ) + + pad = local_conv_size // 2 + self.local_conv = Conv2d_BN( + dim, dim, ks=local_conv_size, stride=1, pad=pad, groups=dim + ) + + def forward(self, x): + H, W = self.input_resolution + B, L, C = x.shape + assert L == H * W, "input feature has wrong size" + res_x = x + if H == self.window_size and W == self.window_size: + x = self.attn(x) + else: + x = x.view(B, H, W, C) + pad_b = (self.window_size - H % self.window_size) % self.window_size + pad_r = (self.window_size - W % self.window_size) % self.window_size + padding = pad_b > 0 or pad_r > 0 + + if padding: + x = F.pad(x, (0, 0, 0, pad_r, 0, pad_b)) + + pH, pW = H + pad_b, W + pad_r + nH = pH // self.window_size + nW = pW // self.window_size + # window partition + x = ( + x.view(B, nH, self.window_size, nW, self.window_size, C) + .transpose(2, 3) + .reshape(B * nH * nW, self.window_size * self.window_size, C) + ) + x = self.attn(x) + # window reverse + x = ( + x.view(B, nH, nW, self.window_size, self.window_size, C) + .transpose(2, 3) + .reshape(B, pH, pW, C) + ) + + if padding: + x = x[:, :H, :W].contiguous() + + x = x.view(B, L, C) + + x = res_x + self.drop_path(x) + + x = x.transpose(1, 2).reshape(B, C, H, W) + x = self.local_conv(x) + x = x.view(B, C, L).transpose(1, 2) + + x = x + self.drop_path(self.mlp(x)) + return x + + def extra_repr(self) -> str: + return ( + f"dim={self.dim}, input_resolution={self.input_resolution}, num_heads={self.num_heads}, " + f"window_size={self.window_size}, mlp_ratio={self.mlp_ratio}" + ) + + +class BasicLayer(nn.Module): + """A basic TinyViT layer for one stage. + + Args: + dim (int): Number of input channels. + input_resolution (tuple[int]): Input resolution. + depth (int): Number of blocks. + num_heads (int): Number of attention heads. + window_size (int): Local window size. + mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. + drop (float, optional): Dropout rate. Default: 0.0 + drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0 + downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None + use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False. + local_conv_size: the kernel size of the depthwise convolution between attention and MLP. Default: 3 + activation: the activation function. Default: nn.GELU + out_dim: the output dimension of the layer. Default: dim + """ + + def __init__( + self, + dim, + input_resolution, + depth, + num_heads, + window_size, + mlp_ratio=4.0, + drop=0.0, + drop_path=0.0, + downsample=None, + use_checkpoint=False, + local_conv_size=3, + activation=nn.GELU, + out_dim=None, + ): + super().__init__() + self.dim = dim + self.input_resolution = input_resolution + self.depth = depth + self.use_checkpoint = use_checkpoint + + # build blocks + self.blocks = nn.ModuleList( + [ + TinyViTBlock( + dim=dim, + input_resolution=input_resolution, + num_heads=num_heads, + window_size=window_size, + mlp_ratio=mlp_ratio, + drop=drop, + drop_path=drop_path[i] + if isinstance(drop_path, list) + else drop_path, + local_conv_size=local_conv_size, + activation=activation, + ) + for i in range(depth) + ] + ) + + # patch merging layer + if downsample is not None: + self.downsample = downsample( + input_resolution, dim=dim, out_dim=out_dim, activation=activation + ) + else: + self.downsample = None + + def forward(self, x): + for blk in self.blocks: + if self.use_checkpoint: + x = checkpoint.checkpoint(blk, x) + else: + x = blk(x) + if self.downsample is not None: + x = self.downsample(x) + return x + + def extra_repr(self) -> str: + return f"dim={self.dim}, input_resolution={self.input_resolution}, depth={self.depth}" + + +class LayerNorm2d(nn.Module): + def __init__(self, num_channels: int, eps: float = 1e-6) -> None: + super().__init__() + self.weight = nn.Parameter(torch.ones(num_channels)) + self.bias = nn.Parameter(torch.zeros(num_channels)) + self.eps = eps + + def forward(self, x: torch.Tensor) -> torch.Tensor: + u = x.mean(1, keepdim=True) + s = (x - u).pow(2).mean(1, keepdim=True) + x = (x - u) / torch.sqrt(s + self.eps) + x = self.weight[:, None, None] * x + self.bias[:, None, None] + return x + + +class TinyViT(nn.Module): + def __init__( + self, + img_size=224, + in_chans=3, + num_classes=1000, + embed_dims=[96, 192, 384, 768], + depths=[2, 2, 6, 2], + num_heads=[3, 6, 12, 24], + window_sizes=[7, 7, 14, 7], + mlp_ratio=4.0, + drop_rate=0.0, + drop_path_rate=0.1, + use_checkpoint=False, + mbconv_expand_ratio=4.0, + local_conv_size=3, + layer_lr_decay=1.0, + ): + super().__init__() + self.img_size = img_size + self.num_classes = num_classes + self.depths = depths + self.num_layers = len(depths) + self.mlp_ratio = mlp_ratio + + activation = nn.GELU + + self.patch_embed = PatchEmbed( + in_chans=in_chans, + embed_dim=embed_dims[0], + resolution=img_size, + activation=activation, + ) + + patches_resolution = self.patch_embed.patches_resolution + self.patches_resolution = patches_resolution + + # stochastic depth + dpr = [ + x.item() for x in torch.linspace(0, drop_path_rate, sum(depths)) + ] # stochastic depth decay rule + + # build layers + self.layers = nn.ModuleList() + for i_layer in range(self.num_layers): + kwargs = dict( + dim=embed_dims[i_layer], + input_resolution=( + patches_resolution[0] + // (2 ** (i_layer - 1 if i_layer == 3 else i_layer)), + patches_resolution[1] + // (2 ** (i_layer - 1 if i_layer == 3 else i_layer)), + ), + # input_resolution=(patches_resolution[0] // (2 ** i_layer), + # patches_resolution[1] // (2 ** i_layer)), + depth=depths[i_layer], + drop_path=dpr[sum(depths[:i_layer]) : sum(depths[: i_layer + 1])], + downsample=PatchMerging if (i_layer < self.num_layers - 1) else None, + use_checkpoint=use_checkpoint, + out_dim=embed_dims[min(i_layer + 1, len(embed_dims) - 1)], + activation=activation, + ) + if i_layer == 0: + layer = ConvLayer( + conv_expand_ratio=mbconv_expand_ratio, + **kwargs, + ) + else: + layer = BasicLayer( + num_heads=num_heads[i_layer], + window_size=window_sizes[i_layer], + mlp_ratio=self.mlp_ratio, + drop=drop_rate, + local_conv_size=local_conv_size, + **kwargs, + ) + self.layers.append(layer) + + # Classifier head + self.norm_head = nn.LayerNorm(embed_dims[-1]) + self.head = ( + nn.Linear(embed_dims[-1], num_classes) + if num_classes > 0 + else torch.nn.Identity() + ) + + # init weights + self.apply(self._init_weights) + self.set_layer_lr_decay(layer_lr_decay) + self.neck = nn.Sequential( + nn.Conv2d( + embed_dims[-1], + 256, + kernel_size=1, + bias=False, + ), + LayerNorm2d(256), + nn.Conv2d( + 256, + 256, + kernel_size=3, + padding=1, + bias=False, + ), + LayerNorm2d(256), + ) + + def set_layer_lr_decay(self, layer_lr_decay): + decay_rate = layer_lr_decay + + # layers -> blocks (depth) + depth = sum(self.depths) + lr_scales = [decay_rate ** (depth - i - 1) for i in range(depth)] + # print("LR SCALES:", lr_scales) + + def _set_lr_scale(m, scale): + for p in m.parameters(): + p.lr_scale = scale + + self.patch_embed.apply(lambda x: _set_lr_scale(x, lr_scales[0])) + i = 0 + for layer in self.layers: + for block in layer.blocks: + block.apply(lambda x: _set_lr_scale(x, lr_scales[i])) + i += 1 + if layer.downsample is not None: + layer.downsample.apply(lambda x: _set_lr_scale(x, lr_scales[i - 1])) + assert i == depth + for m in [self.norm_head, self.head]: + m.apply(lambda x: _set_lr_scale(x, lr_scales[-1])) + + for k, p in self.named_parameters(): + p.param_name = k + + def _check_lr_scale(m): + for p in m.parameters(): + assert hasattr(p, "lr_scale"), p.param_name + + self.apply(_check_lr_scale) + + def _init_weights(self, m): + if isinstance(m, nn.Linear): + trunc_normal_(m.weight, std=0.02) + if isinstance(m, nn.Linear) and m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.LayerNorm): + nn.init.constant_(m.bias, 0) + nn.init.constant_(m.weight, 1.0) + + @torch.jit.ignore + def no_weight_decay_keywords(self): + return {"attention_biases"} + + def forward_features(self, x): + # x: (N, C, H, W) + x = self.patch_embed(x) + + x = self.layers[0](x) + start_i = 1 + + for i in range(start_i, len(self.layers)): + layer = self.layers[i] + x = layer(x) + B, _, C = x.size() + x = x.view(B, 64, 64, C) + x = x.permute(0, 3, 1, 2) + x = self.neck(x) + return x + + def forward(self, x): + x = self.forward_features(x) + # x = self.norm_head(x) + # x = self.head(x) + return x diff --git a/py/iopaint/plugins/segment_anything/modeling/transformer.py b/py/iopaint/plugins/segment_anything/modeling/transformer.py new file mode 100644 index 0000000..f1a2812 --- /dev/null +++ b/py/iopaint/plugins/segment_anything/modeling/transformer.py @@ -0,0 +1,240 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import torch +from torch import Tensor, nn + +import math +from typing import Tuple, Type + +from .common import MLPBlock + + +class TwoWayTransformer(nn.Module): + def __init__( + self, + depth: int, + embedding_dim: int, + num_heads: int, + mlp_dim: int, + activation: Type[nn.Module] = nn.ReLU, + attention_downsample_rate: int = 2, + ) -> None: + """ + A transformer decoder that attends to an input image using + queries whose positional embedding is supplied. + + Args: + depth (int): number of layers in the transformer + embedding_dim (int): the channel dimension for the input embeddings + num_heads (int): the number of heads for multihead attention. Must + divide embedding_dim + mlp_dim (int): the channel dimension internal to the MLP block + activation (nn.Module): the activation to use in the MLP block + """ + super().__init__() + self.depth = depth + self.embedding_dim = embedding_dim + self.num_heads = num_heads + self.mlp_dim = mlp_dim + self.layers = nn.ModuleList() + + for i in range(depth): + self.layers.append( + TwoWayAttentionBlock( + embedding_dim=embedding_dim, + num_heads=num_heads, + mlp_dim=mlp_dim, + activation=activation, + attention_downsample_rate=attention_downsample_rate, + skip_first_layer_pe=(i == 0), + ) + ) + + self.final_attn_token_to_image = Attention( + embedding_dim, num_heads, downsample_rate=attention_downsample_rate + ) + self.norm_final_attn = nn.LayerNorm(embedding_dim) + + def forward( + self, + image_embedding: Tensor, + image_pe: Tensor, + point_embedding: Tensor, + ) -> Tuple[Tensor, Tensor]: + """ + Args: + image_embedding (torch.Tensor): image to attend to. Should be shape + B x embedding_dim x h x w for any h and w. + image_pe (torch.Tensor): the positional encoding to add to the image. Must + have the same shape as image_embedding. + point_embedding (torch.Tensor): the embedding to add to the query points. + Must have shape B x N_points x embedding_dim for any N_points. + + Returns: + torch.Tensor: the processed point_embedding + torch.Tensor: the processed image_embedding + """ + # BxCxHxW -> BxHWxC == B x N_image_tokens x C + bs, c, h, w = image_embedding.shape + image_embedding = image_embedding.flatten(2).permute(0, 2, 1) + image_pe = image_pe.flatten(2).permute(0, 2, 1) + + # Prepare queries + queries = point_embedding + keys = image_embedding + + # Apply transformer blocks and final layernorm + for layer in self.layers: + queries, keys = layer( + queries=queries, + keys=keys, + query_pe=point_embedding, + key_pe=image_pe, + ) + + # Apply the final attenion layer from the points to the image + q = queries + point_embedding + k = keys + image_pe + attn_out = self.final_attn_token_to_image(q=q, k=k, v=keys) + queries = queries + attn_out + queries = self.norm_final_attn(queries) + + return queries, keys + + +class TwoWayAttentionBlock(nn.Module): + def __init__( + self, + embedding_dim: int, + num_heads: int, + mlp_dim: int = 2048, + activation: Type[nn.Module] = nn.ReLU, + attention_downsample_rate: int = 2, + skip_first_layer_pe: bool = False, + ) -> None: + """ + A transformer block with four layers: (1) self-attention of sparse + inputs, (2) cross attention of sparse inputs to dense inputs, (3) mlp + block on sparse inputs, and (4) cross attention of dense inputs to sparse + inputs. + + Arguments: + embedding_dim (int): the channel dimension of the embeddings + num_heads (int): the number of heads in the attention layers + mlp_dim (int): the hidden dimension of the mlp block + activation (nn.Module): the activation of the mlp block + skip_first_layer_pe (bool): skip the PE on the first layer + """ + super().__init__() + self.self_attn = Attention(embedding_dim, num_heads) + self.norm1 = nn.LayerNorm(embedding_dim) + + self.cross_attn_token_to_image = Attention( + embedding_dim, num_heads, downsample_rate=attention_downsample_rate + ) + self.norm2 = nn.LayerNorm(embedding_dim) + + self.mlp = MLPBlock(embedding_dim, mlp_dim, activation) + self.norm3 = nn.LayerNorm(embedding_dim) + + self.norm4 = nn.LayerNorm(embedding_dim) + self.cross_attn_image_to_token = Attention( + embedding_dim, num_heads, downsample_rate=attention_downsample_rate + ) + + self.skip_first_layer_pe = skip_first_layer_pe + + def forward( + self, queries: Tensor, keys: Tensor, query_pe: Tensor, key_pe: Tensor + ) -> Tuple[Tensor, Tensor]: + # Self attention block + if self.skip_first_layer_pe: + queries = self.self_attn(q=queries, k=queries, v=queries) + else: + q = queries + query_pe + attn_out = self.self_attn(q=q, k=q, v=queries) + queries = queries + attn_out + queries = self.norm1(queries) + + # Cross attention block, tokens attending to image embedding + q = queries + query_pe + k = keys + key_pe + attn_out = self.cross_attn_token_to_image(q=q, k=k, v=keys) + queries = queries + attn_out + queries = self.norm2(queries) + + # MLP block + mlp_out = self.mlp(queries) + queries = queries + mlp_out + queries = self.norm3(queries) + + # Cross attention block, image embedding attending to tokens + q = queries + query_pe + k = keys + key_pe + attn_out = self.cross_attn_image_to_token(q=k, k=q, v=queries) + keys = keys + attn_out + keys = self.norm4(keys) + + return queries, keys + + +class Attention(nn.Module): + """ + An attention layer that allows for downscaling the size of the embedding + after projection to queries, keys, and values. + """ + + def __init__( + self, + embedding_dim: int, + num_heads: int, + downsample_rate: int = 1, + ) -> None: + super().__init__() + self.embedding_dim = embedding_dim + self.internal_dim = embedding_dim // downsample_rate + self.num_heads = num_heads + assert self.internal_dim % num_heads == 0, "num_heads must divide embedding_dim." + + self.q_proj = nn.Linear(embedding_dim, self.internal_dim) + self.k_proj = nn.Linear(embedding_dim, self.internal_dim) + self.v_proj = nn.Linear(embedding_dim, self.internal_dim) + self.out_proj = nn.Linear(self.internal_dim, embedding_dim) + + def _separate_heads(self, x: Tensor, num_heads: int) -> Tensor: + b, n, c = x.shape + x = x.reshape(b, n, num_heads, c // num_heads) + return x.transpose(1, 2) # B x N_heads x N_tokens x C_per_head + + def _recombine_heads(self, x: Tensor) -> Tensor: + b, n_heads, n_tokens, c_per_head = x.shape + x = x.transpose(1, 2) + return x.reshape(b, n_tokens, n_heads * c_per_head) # B x N_tokens x C + + def forward(self, q: Tensor, k: Tensor, v: Tensor) -> Tensor: + # Input projections + q = self.q_proj(q) + k = self.k_proj(k) + v = self.v_proj(v) + + # Separate into heads + q = self._separate_heads(q, self.num_heads) + k = self._separate_heads(k, self.num_heads) + v = self._separate_heads(v, self.num_heads) + + # Attention + _, _, _, c_per_head = q.shape + attn = q @ k.permute(0, 1, 3, 2) # B x N_heads x N_tokens x N_tokens + attn = attn / math.sqrt(c_per_head) + attn = torch.softmax(attn, dim=-1) + + # Get output + out = attn @ v + out = self._recombine_heads(out) + out = self.out_proj(out) + + return out diff --git a/py/iopaint/plugins/segment_anything/predictor.py b/py/iopaint/plugins/segment_anything/predictor.py new file mode 100644 index 0000000..23d0649 --- /dev/null +++ b/py/iopaint/plugins/segment_anything/predictor.py @@ -0,0 +1,285 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import numpy as np +import torch + +from .modeling import Sam + +from typing import Optional, Tuple + + +class SamPredictor: + def __init__( + self, + sam_model: Sam, + ) -> None: + """ + Uses SAM to calculate the image embedding for an image, and then + allow repeated, efficient mask prediction given prompts. + + Arguments: + sam_model (Sam): The model to use for mask prediction. + """ + super().__init__() + self.model = sam_model + from .utils.transforms import ResizeLongestSide + + self.transform = ResizeLongestSide(sam_model.image_encoder.img_size) + self.reset_image() + + def set_image( + self, + image: np.ndarray, + image_format: str = "RGB", + ) -> None: + """ + Calculates the image embeddings for the provided image, allowing + masks to be predicted with the 'predict' method. + + Arguments: + image (np.ndarray): The image for calculating masks. Expects an + image in HWC uint8 format, with pixel values in [0, 255]. + image_format (str): The color format of the image, in ['RGB', 'BGR']. + """ + assert image_format in [ + "RGB", + "BGR", + ], f"image_format must be in ['RGB', 'BGR'], is {image_format}." + if image_format != self.model.image_format: + image = image[..., ::-1] + + # Transform the image to the form expected by the model + input_image = self.transform.apply_image(image) + input_image_torch = torch.as_tensor(input_image, device=self.device) + input_image_torch = input_image_torch.permute(2, 0, 1).contiguous()[ + None, :, :, : + ] + + self.set_torch_image(input_image_torch, image.shape[:2]) + + @torch.no_grad() + def set_torch_image( + self, + transformed_image: torch.Tensor, + original_image_size: Tuple[int, ...], + ) -> None: + """ + Calculates the image embeddings for the provided image, allowing + masks to be predicted with the 'predict' method. Expects the input + image to be already transformed to the format expected by the model. + + Arguments: + transformed_image (torch.Tensor): The input image, with shape + 1x3xHxW, which has been transformed with ResizeLongestSide. + original_image_size (tuple(int, int)): The size of the image + before transformation, in (H, W) format. + """ + assert ( + len(transformed_image.shape) == 4 + and transformed_image.shape[1] == 3 + and max(*transformed_image.shape[2:]) == self.model.image_encoder.img_size + ), f"set_torch_image input must be BCHW with long side {self.model.image_encoder.img_size}." + self.reset_image() + + self.original_size = original_image_size + self.input_size = tuple(transformed_image.shape[-2:]) + input_image = self.model.preprocess(transformed_image) + self.features = self.model.image_encoder(input_image) + self.is_image_set = True + + def predict( + self, + point_coords: Optional[np.ndarray] = None, + point_labels: Optional[np.ndarray] = None, + box: Optional[np.ndarray] = None, + mask_input: Optional[np.ndarray] = None, + multimask_output: bool = True, + return_logits: bool = False, + ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """ + Predict masks for the given input prompts, using the currently set image. + + Arguments: + point_coords (np.ndarray or None): A Nx2 array of point prompts to the + model. Each point is in (X,Y) in pixels. + point_labels (np.ndarray or None): A length N array of labels for the + point prompts. 1 indicates a foreground point and 0 indicates a + background point. + box (np.ndarray or None): A length 4 array given a box prompt to the + model, in XYXY format. + mask_input (np.ndarray): A low resolution mask input to the model, typically + coming from a previous prediction iteration. Has form 1xHxW, where + for SAM, H=W=256. + multimask_output (bool): If true, the model will return three masks. + For ambiguous input prompts (such as a single click), this will often + produce better masks than a single prediction. If only a single + mask is needed, the model's predicted quality score can be used + to select the best mask. For non-ambiguous prompts, such as multiple + input prompts, multimask_output=False can give better results. + return_logits (bool): If true, returns un-thresholded masks logits + instead of a binary mask. + + Returns: + (np.ndarray): The output masks in CxHxW format, where C is the + number of masks, and (H, W) is the original image size. + (np.ndarray): An array of length C containing the model's + predictions for the quality of each mask. + (np.ndarray): An array of shape CxHxW, where C is the number + of masks and H=W=256. These low resolution logits can be passed to + a subsequent iteration as mask input. + """ + if not self.is_image_set: + raise RuntimeError( + "An image must be set with .set_image(...) before mask prediction." + ) + + # Transform input prompts + coords_torch, labels_torch, box_torch, mask_input_torch = None, None, None, None + if point_coords is not None: + assert ( + point_labels is not None + ), "point_labels must be supplied if point_coords is supplied." + point_coords = self.transform.apply_coords(point_coords, self.original_size) + coords_torch = torch.as_tensor( + point_coords, dtype=torch.float, device=self.device + ) + labels_torch = torch.as_tensor( + point_labels, dtype=torch.int, device=self.device + ) + coords_torch, labels_torch = coords_torch[None, :, :], labels_torch[None, :] + if box is not None: + box = self.transform.apply_boxes(box, self.original_size) + box_torch = torch.as_tensor(box, dtype=torch.float, device=self.device) + box_torch = box_torch[None, :] + if mask_input is not None: + mask_input_torch = torch.as_tensor( + mask_input, dtype=torch.float, device=self.device + ) + mask_input_torch = mask_input_torch[None, :, :, :] + + masks, iou_predictions, low_res_masks = self.predict_torch( + coords_torch, + labels_torch, + box_torch, + mask_input_torch, + multimask_output, + return_logits=return_logits, + ) + + masks = masks[0].detach().cpu().numpy() + iou_predictions = iou_predictions[0].detach().cpu().numpy() + low_res_masks = low_res_masks[0].detach().cpu().numpy() + return masks, iou_predictions, low_res_masks + + @torch.no_grad() + def predict_torch( + self, + point_coords: Optional[torch.Tensor], + point_labels: Optional[torch.Tensor], + boxes: Optional[torch.Tensor] = None, + mask_input: Optional[torch.Tensor] = None, + multimask_output: bool = True, + return_logits: bool = False, + ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """ + Predict masks for the given input prompts, using the currently set image. + Input prompts are batched torch tensors and are expected to already be + transformed to the input frame using ResizeLongestSide. + + Arguments: + point_coords (torch.Tensor or None): A BxNx2 array of point prompts to the + model. Each point is in (X,Y) in pixels. + point_labels (torch.Tensor or None): A BxN array of labels for the + point prompts. 1 indicates a foreground point and 0 indicates a + background point. + box (np.ndarray or None): A Bx4 array given a box prompt to the + model, in XYXY format. + mask_input (np.ndarray): A low resolution mask input to the model, typically + coming from a previous prediction iteration. Has form Bx1xHxW, where + for SAM, H=W=256. Masks returned by a previous iteration of the + predict method do not need further transformation. + multimask_output (bool): If true, the model will return three masks. + For ambiguous input prompts (such as a single click), this will often + produce better masks than a single prediction. If only a single + mask is needed, the model's predicted quality score can be used + to select the best mask. For non-ambiguous prompts, such as multiple + input prompts, multimask_output=False can give better results. + return_logits (bool): If true, returns un-thresholded masks logits + instead of a binary mask. + + Returns: + (torch.Tensor): The output masks in BxCxHxW format, where C is the + number of masks, and (H, W) is the original image size. + (torch.Tensor): An array of shape BxC containing the model's + predictions for the quality of each mask. + (torch.Tensor): An array of shape BxCxHxW, where C is the number + of masks and H=W=256. These low res logits can be passed to + a subsequent iteration as mask input. + """ + if not self.is_image_set: + raise RuntimeError( + "An image must be set with .set_image(...) before mask prediction." + ) + + if point_coords is not None: + points = (point_coords, point_labels) + else: + points = None + + # Embed prompts + sparse_embeddings, dense_embeddings = self.model.prompt_encoder( + points=points, + boxes=boxes, + masks=mask_input, + ) + + # Predict masks + low_res_masks, iou_predictions = self.model.mask_decoder( + image_embeddings=self.features, + image_pe=self.model.prompt_encoder.get_dense_pe(), + sparse_prompt_embeddings=sparse_embeddings, + dense_prompt_embeddings=dense_embeddings, + multimask_output=multimask_output, + ) + + # Upscale the masks to the original image resolution + masks = self.model.postprocess_masks( + low_res_masks, self.input_size, self.original_size + ) + + if not return_logits: + masks = masks > self.model.mask_threshold + + return masks, iou_predictions, low_res_masks + + def get_image_embedding(self) -> torch.Tensor: + """ + Returns the image embeddings for the currently set image, with + shape 1xCxHxW, where C is the embedding dimension and (H,W) are + the embedding spatial dimension of SAM (typically C=256, H=W=64). + """ + if not self.is_image_set: + raise RuntimeError( + "An image must be set with .set_image(...) to generate an embedding." + ) + assert ( + self.features is not None + ), "Features must exist if an image has been set." + return self.features + + @property + def device(self) -> torch.device: + return self.model.device + + def reset_image(self) -> None: + """Resets the currently set image.""" + self.is_image_set = False + self.features = None + self.orig_h = None + self.orig_w = None + self.input_h = None + self.input_w = None diff --git a/py/iopaint/plugins/segment_anything/predictor_hq.py b/py/iopaint/plugins/segment_anything/predictor_hq.py new file mode 100644 index 0000000..d8fd50f --- /dev/null +++ b/py/iopaint/plugins/segment_anything/predictor_hq.py @@ -0,0 +1,292 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import numpy as np +import torch + +from .modeling import Sam + +from typing import Optional, Tuple + +from .utils.transforms import ResizeLongestSide + + +class SamHQPredictor: + def __init__( + self, + sam_model: Sam, + ) -> None: + """ + Uses SAM to calculate the image embedding for an image, and then + allow repeated, efficient mask prediction given prompts. + + Arguments: + sam_model (Sam): The model to use for mask prediction. + """ + super().__init__() + self.model = sam_model + self.transform = ResizeLongestSide(sam_model.image_encoder.img_size) + self.reset_image() + + def set_image( + self, + image: np.ndarray, + image_format: str = "RGB", + ) -> None: + """ + Calculates the image embeddings for the provided image, allowing + masks to be predicted with the 'predict' method. + + Arguments: + image (np.ndarray): The image for calculating masks. Expects an + image in HWC uint8 format, with pixel values in [0, 255]. + image_format (str): The color format of the image, in ['RGB', 'BGR']. + """ + assert image_format in [ + "RGB", + "BGR", + ], f"image_format must be in ['RGB', 'BGR'], is {image_format}." + # import pdb;pdb.set_trace() + if image_format != self.model.image_format: + image = image[..., ::-1] + + # Transform the image to the form expected by the model + # import pdb;pdb.set_trace() + input_image = self.transform.apply_image(image) + input_image_torch = torch.as_tensor(input_image, device=self.device) + input_image_torch = input_image_torch.permute(2, 0, 1).contiguous()[ + None, :, :, : + ] + + self.set_torch_image(input_image_torch, image.shape[:2]) + + @torch.no_grad() + def set_torch_image( + self, + transformed_image: torch.Tensor, + original_image_size: Tuple[int, ...], + ) -> None: + """ + Calculates the image embeddings for the provided image, allowing + masks to be predicted with the 'predict' method. Expects the input + image to be already transformed to the format expected by the model. + + Arguments: + transformed_image (torch.Tensor): The input image, with shape + 1x3xHxW, which has been transformed with ResizeLongestSide. + original_image_size (tuple(int, int)): The size of the image + before transformation, in (H, W) format. + """ + assert ( + len(transformed_image.shape) == 4 + and transformed_image.shape[1] == 3 + and max(*transformed_image.shape[2:]) == self.model.image_encoder.img_size + ), f"set_torch_image input must be BCHW with long side {self.model.image_encoder.img_size}." + self.reset_image() + + self.original_size = original_image_size + self.input_size = tuple(transformed_image.shape[-2:]) + input_image = self.model.preprocess(transformed_image) + self.features, self.interm_features = self.model.image_encoder(input_image) + self.is_image_set = True + + def predict( + self, + point_coords: Optional[np.ndarray] = None, + point_labels: Optional[np.ndarray] = None, + box: Optional[np.ndarray] = None, + mask_input: Optional[np.ndarray] = None, + multimask_output: bool = True, + return_logits: bool = False, + hq_token_only: bool = False, + ) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: + """ + Predict masks for the given input prompts, using the currently set image. + + Arguments: + point_coords (np.ndarray or None): A Nx2 array of point prompts to the + model. Each point is in (X,Y) in pixels. + point_labels (np.ndarray or None): A length N array of labels for the + point prompts. 1 indicates a foreground point and 0 indicates a + background point. + box (np.ndarray or None): A length 4 array given a box prompt to the + model, in XYXY format. + mask_input (np.ndarray): A low resolution mask input to the model, typically + coming from a previous prediction iteration. Has form 1xHxW, where + for SAM, H=W=256. + multimask_output (bool): If true, the model will return three masks. + For ambiguous input prompts (such as a single click), this will often + produce better masks than a single prediction. If only a single + mask is needed, the model's predicted quality score can be used + to select the best mask. For non-ambiguous prompts, such as multiple + input prompts, multimask_output=False can give better results. + return_logits (bool): If true, returns un-thresholded masks logits + instead of a binary mask. + + Returns: + (np.ndarray): The output masks in CxHxW format, where C is the + number of masks, and (H, W) is the original image size. + (np.ndarray): An array of length C containing the model's + predictions for the quality of each mask. + (np.ndarray): An array of shape CxHxW, where C is the number + of masks and H=W=256. These low resolution logits can be passed to + a subsequent iteration as mask input. + """ + if not self.is_image_set: + raise RuntimeError( + "An image must be set with .set_image(...) before mask prediction." + ) + + # Transform input prompts + coords_torch, labels_torch, box_torch, mask_input_torch = None, None, None, None + if point_coords is not None: + assert ( + point_labels is not None + ), "point_labels must be supplied if point_coords is supplied." + point_coords = self.transform.apply_coords(point_coords, self.original_size) + coords_torch = torch.as_tensor( + point_coords, dtype=torch.float, device=self.device + ) + labels_torch = torch.as_tensor( + point_labels, dtype=torch.int, device=self.device + ) + coords_torch, labels_torch = coords_torch[None, :, :], labels_torch[None, :] + if box is not None: + box = self.transform.apply_boxes(box, self.original_size) + box_torch = torch.as_tensor(box, dtype=torch.float, device=self.device) + box_torch = box_torch[None, :] + if mask_input is not None: + mask_input_torch = torch.as_tensor( + mask_input, dtype=torch.float, device=self.device + ) + mask_input_torch = mask_input_torch[None, :, :, :] + + masks, iou_predictions, low_res_masks = self.predict_torch( + coords_torch, + labels_torch, + box_torch, + mask_input_torch, + multimask_output, + return_logits=return_logits, + hq_token_only=hq_token_only, + ) + + masks_np = masks[0].detach().cpu().numpy() + iou_predictions_np = iou_predictions[0].detach().cpu().numpy() + low_res_masks_np = low_res_masks[0].detach().cpu().numpy() + return masks_np, iou_predictions_np, low_res_masks_np + + @torch.no_grad() + def predict_torch( + self, + point_coords: Optional[torch.Tensor], + point_labels: Optional[torch.Tensor], + boxes: Optional[torch.Tensor] = None, + mask_input: Optional[torch.Tensor] = None, + multimask_output: bool = True, + return_logits: bool = False, + hq_token_only: bool = False, + ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """ + Predict masks for the given input prompts, using the currently set image. + Input prompts are batched torch tensors and are expected to already be + transformed to the input frame using ResizeLongestSide. + + Arguments: + point_coords (torch.Tensor or None): A BxNx2 array of point prompts to the + model. Each point is in (X,Y) in pixels. + point_labels (torch.Tensor or None): A BxN array of labels for the + point prompts. 1 indicates a foreground point and 0 indicates a + background point. + boxes (np.ndarray or None): A Bx4 array given a box prompt to the + model, in XYXY format. + mask_input (np.ndarray): A low resolution mask input to the model, typically + coming from a previous prediction iteration. Has form Bx1xHxW, where + for SAM, H=W=256. Masks returned by a previous iteration of the + predict method do not need further transformation. + multimask_output (bool): If true, the model will return three masks. + For ambiguous input prompts (such as a single click), this will often + produce better masks than a single prediction. If only a single + mask is needed, the model's predicted quality score can be used + to select the best mask. For non-ambiguous prompts, such as multiple + input prompts, multimask_output=False can give better results. + return_logits (bool): If true, returns un-thresholded masks logits + instead of a binary mask. + + Returns: + (torch.Tensor): The output masks in BxCxHxW format, where C is the + number of masks, and (H, W) is the original image size. + (torch.Tensor): An array of shape BxC containing the model's + predictions for the quality of each mask. + (torch.Tensor): An array of shape BxCxHxW, where C is the number + of masks and H=W=256. These low res logits can be passed to + a subsequent iteration as mask input. + """ + if not self.is_image_set: + raise RuntimeError( + "An image must be set with .set_image(...) before mask prediction." + ) + + if point_coords is not None: + points = (point_coords, point_labels) + else: + points = None + + # Embed prompts + sparse_embeddings, dense_embeddings = self.model.prompt_encoder( + points=points, + boxes=boxes, + masks=mask_input, + ) + + # Predict masks + low_res_masks, iou_predictions = self.model.mask_decoder( + image_embeddings=self.features, + image_pe=self.model.prompt_encoder.get_dense_pe(), + sparse_prompt_embeddings=sparse_embeddings, + dense_prompt_embeddings=dense_embeddings, + multimask_output=multimask_output, + hq_token_only=hq_token_only, + interm_embeddings=self.interm_features, + ) + + # Upscale the masks to the original image resolution + masks = self.model.postprocess_masks( + low_res_masks, self.input_size, self.original_size + ) + + if not return_logits: + masks = masks > self.model.mask_threshold + + return masks, iou_predictions, low_res_masks + + def get_image_embedding(self) -> torch.Tensor: + """ + Returns the image embeddings for the currently set image, with + shape 1xCxHxW, where C is the embedding dimension and (H,W) are + the embedding spatial dimension of SAM (typically C=256, H=W=64). + """ + if not self.is_image_set: + raise RuntimeError( + "An image must be set with .set_image(...) to generate an embedding." + ) + assert ( + self.features is not None + ), "Features must exist if an image has been set." + return self.features + + @property + def device(self) -> torch.device: + return self.model.device + + def reset_image(self) -> None: + """Resets the currently set image.""" + self.is_image_set = False + self.features = None + self.orig_h = None + self.orig_w = None + self.input_h = None + self.input_w = None diff --git a/py/iopaint/plugins/segment_anything/utils/__init__.py b/py/iopaint/plugins/segment_anything/utils/__init__.py new file mode 100644 index 0000000..5277f46 --- /dev/null +++ b/py/iopaint/plugins/segment_anything/utils/__init__.py @@ -0,0 +1,5 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. diff --git a/py/iopaint/plugins/segment_anything/utils/transforms.py b/py/iopaint/plugins/segment_anything/utils/transforms.py new file mode 100644 index 0000000..90f50ed --- /dev/null +++ b/py/iopaint/plugins/segment_anything/utils/transforms.py @@ -0,0 +1,112 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import numpy as np +import torch +from torch.nn import functional as F +from torchvision.transforms.functional import resize, to_pil_image # type: ignore + +from copy import deepcopy +from typing import Tuple + + +class ResizeLongestSide: + """ + Resizes images to longest side 'target_length', as well as provides + methods for resizing coordinates and boxes. Provides methods for + transforming both numpy array and batched torch tensors. + """ + + def __init__(self, target_length: int) -> None: + self.target_length = target_length + + def apply_image(self, image: np.ndarray) -> np.ndarray: + """ + Expects a numpy array with shape HxWxC in uint8 format. + """ + target_size = self.get_preprocess_shape( + image.shape[0], image.shape[1], self.target_length + ) + return np.array(resize(to_pil_image(image), target_size)) + + def apply_coords( + self, coords: np.ndarray, original_size: Tuple[int, ...] + ) -> np.ndarray: + """ + Expects a numpy array of length 2 in the final dimension. Requires the + original image size in (H, W) format. + """ + old_h, old_w = original_size + new_h, new_w = self.get_preprocess_shape( + original_size[0], original_size[1], self.target_length + ) + coords = deepcopy(coords).astype(float) + coords[..., 0] = coords[..., 0] * (new_w / old_w) + coords[..., 1] = coords[..., 1] * (new_h / old_h) + return coords + + def apply_boxes( + self, boxes: np.ndarray, original_size: Tuple[int, ...] + ) -> np.ndarray: + """ + Expects a numpy array shape Bx4. Requires the original image size + in (H, W) format. + """ + boxes = self.apply_coords(boxes.reshape(-1, 2, 2), original_size) + return boxes.reshape(-1, 4) + + def apply_image_torch(self, image: torch.Tensor) -> torch.Tensor: + """ + Expects batched images with shape BxCxHxW and float format. This + transformation may not exactly match apply_image. apply_image is + the transformation expected by the model. + """ + # Expects an image in BCHW format. May not exactly match apply_image. + target_size = self.get_preprocess_shape( + image.shape[0], image.shape[1], self.target_length + ) + return F.interpolate( + image, target_size, mode="bilinear", align_corners=False, antialias=True + ) + + def apply_coords_torch( + self, coords: torch.Tensor, original_size: Tuple[int, ...] + ) -> torch.Tensor: + """ + Expects a torch tensor with length 2 in the last dimension. Requires the + original image size in (H, W) format. + """ + old_h, old_w = original_size + new_h, new_w = self.get_preprocess_shape( + original_size[0], original_size[1], self.target_length + ) + coords = deepcopy(coords).to(torch.float) + coords[..., 0] = coords[..., 0] * (new_w / old_w) + coords[..., 1] = coords[..., 1] * (new_h / old_h) + return coords + + def apply_boxes_torch( + self, boxes: torch.Tensor, original_size: Tuple[int, ...] + ) -> torch.Tensor: + """ + Expects a torch tensor with shape Bx4. Requires the original image + size in (H, W) format. + """ + boxes = self.apply_coords_torch(boxes.reshape(-1, 2, 2), original_size) + return boxes.reshape(-1, 4) + + @staticmethod + def get_preprocess_shape( + oldh: int, oldw: int, long_side_length: int + ) -> Tuple[int, int]: + """ + Compute the output size given input size and target long side length. + """ + scale = long_side_length * 1.0 / max(oldh, oldw) + newh, neww = oldh * scale, oldw * scale + neww = int(neww + 0.5) + newh = int(newh + 0.5) + return (newh, neww) diff --git a/py/iopaint/runtime.py b/py/iopaint/runtime.py new file mode 100644 index 0000000..55266e1 --- /dev/null +++ b/py/iopaint/runtime.py @@ -0,0 +1,88 @@ +# https://github.com/huggingface/huggingface_hub/blob/5a12851f54bf614be39614034ed3a9031922d297/src/huggingface_hub/utils/_runtime.py +import os +import platform +import sys +from pathlib import Path + +import packaging.version +from .schema import Device +from loguru import logger +from rich import print +from typing import Dict, Any + + +# _PY_VERSION: str = sys.version.split()[0].rstrip("+") + +# if packaging.version.Version(_PY_VERSION) < packaging.version.Version("3.8.0"): +# import importlib_metadata # type: ignore +# else: +# import importlib.metadata as importlib_metadata # type: ignore + +# _package_versions = {} + +# _CANDIDATES = [ +# "torch", +# "torchvision", +# "Pillow", +# "diffusers", +# "transformers", +# "opencv-python", +# "accelerate", +# "iopaint", +# "rembg", +# "realesrgan", +# "gfpgan", +# ] +# Check once at runtime +# for name in _CANDIDATES: +# _package_versions[name] = "N/A" +# try: +# _package_versions[name] = importlib_metadata.version(name) +# except importlib_metadata.PackageNotFoundError: +# pass + + +def dump_environment_info() -> Dict[str, str]: + """Dump information about the machine to help debugging issues.""" + + # Generic machine info + info: Dict[str, Any] = { + "Platform": platform.platform(), + "Python version": platform.python_version(), + } + info.update(_package_versions) + print("\n".join([f"- {prop}: {val}" for prop, val in info.items()]) + "\n") + return info + + +def check_device(device: Device) -> Device: + if device == Device.cuda: + import platform + + if platform.system() == "Darwin": + logger.warning("MacOS does not support cuda, use cpu instead") + return Device.cpu + else: + import torch + + if not torch.cuda.is_available(): + logger.warning("CUDA is not available, use cpu instead") + return Device.cpu + elif device == Device.mps: + import torch + + if not torch.backends.mps.is_available(): + logger.warning("mps is not available, use cpu instead") + return Device.cpu + return device + + +def setup_model_dir(model_dir: Path): + model_dir = model_dir.expanduser().absolute() + logger.info(f"Model directory: {model_dir}") + os.environ["U2NET_HOME"] = str(model_dir) + os.environ["XDG_CACHE_HOME"] = str(model_dir) + if not model_dir.exists(): + logger.info(f"Create model directory: {model_dir}") + model_dir.mkdir(exist_ok=True, parents=True) + return model_dir diff --git a/py/iopaint/schema.py b/py/iopaint/schema.py new file mode 100644 index 0000000..7573286 --- /dev/null +++ b/py/iopaint/schema.py @@ -0,0 +1,470 @@ +import random +from enum import Enum +from pathlib import Path +from typing import Optional, Literal, List + +from .const import ( + INSTRUCT_PIX2PIX_NAME, + KANDINSKY22_NAME, + POWERPAINT_NAME, + ANYTEXT_NAME, + SDXL_CONTROLNET_CHOICES, + SD2_CONTROLNET_CHOICES, + SD_CONTROLNET_CHOICES, +) +from loguru import logger +from pydantic import BaseModel, Field, field_validator, computed_field + + +class ModelType(str, Enum): + INPAINT = "inpaint" # LaMa, MAT... + DIFFUSERS_SD = "diffusers_sd" + DIFFUSERS_SD_INPAINT = "diffusers_sd_inpaint" + DIFFUSERS_SDXL = "diffusers_sdxl" + DIFFUSERS_SDXL_INPAINT = "diffusers_sdxl_inpaint" + DIFFUSERS_OTHER = "diffusers_other" + + +class ModelInfo(BaseModel): + name: str + path: str + model_type: ModelType + is_single_file_diffusers: bool = False + + @computed_field + @property + def need_prompt(self) -> bool: + return self.model_type in [ + ModelType.DIFFUSERS_SD, + ModelType.DIFFUSERS_SDXL, + ModelType.DIFFUSERS_SD_INPAINT, + ModelType.DIFFUSERS_SDXL_INPAINT, + ] or self.name in [ + INSTRUCT_PIX2PIX_NAME, + KANDINSKY22_NAME, + POWERPAINT_NAME, + ANYTEXT_NAME, + ] + + @computed_field + @property + def controlnets(self) -> List[str]: + if self.model_type in [ + ModelType.DIFFUSERS_SDXL, + ModelType.DIFFUSERS_SDXL_INPAINT, + ]: + return SDXL_CONTROLNET_CHOICES + if self.model_type in [ModelType.DIFFUSERS_SD, ModelType.DIFFUSERS_SD_INPAINT]: + if "sd2" in self.name.lower(): + return SD2_CONTROLNET_CHOICES + else: + return SD_CONTROLNET_CHOICES + if self.name == POWERPAINT_NAME: + return SD_CONTROLNET_CHOICES + return [] + + @computed_field + @property + def support_strength(self) -> bool: + return self.model_type in [ + ModelType.DIFFUSERS_SD, + ModelType.DIFFUSERS_SDXL, + ModelType.DIFFUSERS_SD_INPAINT, + ModelType.DIFFUSERS_SDXL_INPAINT, + ] or self.name in [POWERPAINT_NAME, ANYTEXT_NAME] + + @computed_field + @property + def support_outpainting(self) -> bool: + return self.model_type in [ + ModelType.DIFFUSERS_SD, + ModelType.DIFFUSERS_SDXL, + ModelType.DIFFUSERS_SD_INPAINT, + ModelType.DIFFUSERS_SDXL_INPAINT, + ] or self.name in [KANDINSKY22_NAME, POWERPAINT_NAME] + + @computed_field + @property + def support_lcm_lora(self) -> bool: + return self.model_type in [ + ModelType.DIFFUSERS_SD, + ModelType.DIFFUSERS_SDXL, + ModelType.DIFFUSERS_SD_INPAINT, + ModelType.DIFFUSERS_SDXL_INPAINT, + ] + + @computed_field + @property + def support_controlnet(self) -> bool: + return self.model_type in [ + ModelType.DIFFUSERS_SD, + ModelType.DIFFUSERS_SDXL, + ModelType.DIFFUSERS_SD_INPAINT, + ModelType.DIFFUSERS_SDXL_INPAINT, + ] + + @computed_field + @property + def support_freeu(self) -> bool: + return self.model_type in [ + ModelType.DIFFUSERS_SD, + ModelType.DIFFUSERS_SDXL, + ModelType.DIFFUSERS_SD_INPAINT, + ModelType.DIFFUSERS_SDXL_INPAINT, + ] or self.name in [INSTRUCT_PIX2PIX_NAME] + + +class Choices(str, Enum): + @classmethod + def values(cls): + return [member.value for member in cls] + + +class RealESRGANModel(Choices): + realesr_general_x4v3 = "realesr-general-x4v3" + RealESRGAN_x4plus = "RealESRGAN_x4plus" + RealESRGAN_x4plus_anime_6B = "RealESRGAN_x4plus_anime_6B" + + +class RemoveBGModel(Choices): + u2net = "u2net" + u2netp = "u2netp" + u2net_human_seg = "u2net_human_seg" + u2net_cloth_seg = "u2net_cloth_seg" + silueta = "silueta" + isnet_general_use = "isnet-general-use" + briaai_rmbg_1_4 = "briaai/RMBG-1.4" + + +class Device(Choices): + cpu = "cpu" + cuda = "cuda" + mps = "mps" + + +class InteractiveSegModel(Choices): + vit_b = "vit_b" + vit_l = "vit_l" + vit_h = "vit_h" + sam_hq_vit_b = "sam_hq_vit_b" + sam_hq_vit_l = "sam_hq_vit_l" + sam_hq_vit_h = "sam_hq_vit_h" + mobile_sam = "mobile_sam" + + +class PluginInfo(BaseModel): + name: str + support_gen_image: bool = False + support_gen_mask: bool = False + + +class CV2Flag(str, Enum): + INPAINT_NS = "INPAINT_NS" + INPAINT_TELEA = "INPAINT_TELEA" + + +class HDStrategy(str, Enum): + # Use original image size + ORIGINAL = "Original" + # Resize the longer side of the image to a specific size(hd_strategy_resize_limit), + # then do inpainting on the resized image. Finally, resize the inpainting result to the original size. + # The area outside the mask will not lose quality. + RESIZE = "Resize" + # Crop masking area(with a margin controlled by hd_strategy_crop_margin) from the original image to do inpainting + CROP = "Crop" + + +class LDMSampler(str, Enum): + ddim = "ddim" + plms = "plms" + + +class SDSampler(str, Enum): + dpm_plus_plus_2m = "DPM++ 2M" + dpm_plus_plus_2m_karras = "DPM++ 2M Karras" + dpm_plus_plus_2m_sde = "DPM++ 2M SDE" + dpm_plus_plus_2m_sde_karras = "DPM++ 2M SDE Karras" + dpm_plus_plus_sde = "DPM++ SDE" + dpm_plus_plus_sde_karras = "DPM++ SDE Karras" + dpm2 = "DPM2" + dpm2_karras = "DPM2 Karras" + dpm2_a = "DPM2 a" + dpm2_a_karras = "DPM2 a Karras" + euler = "Euler" + euler_a = "Euler a" + heun = "Heun" + lms = "LMS" + lms_karras = "LMS Karras" + + ddim = "DDIM" + pndm = "PNDM" + uni_pc = "UniPC" + lcm = "LCM" + + +class FREEUConfig(BaseModel): + s1: float = 0.9 + s2: float = 0.2 + b1: float = 1.2 + b2: float = 1.4 + + +class PowerPaintTask(str, Enum): + text_guided = "text-guided" + shape_guided = "shape-guided" + object_remove = "object-remove" + outpainting = "outpainting" + + +class ApiConfig(BaseModel): + host: str + port: int + inbrowser: bool + model: str + no_half: bool + low_mem: bool + cpu_offload: bool + disable_nsfw_checker: bool + local_files_only: bool + cpu_textencoder: bool + device: Device + input: Optional[Path] + output_dir: Optional[Path] + quality: int + enable_interactive_seg: bool + interactive_seg_model: InteractiveSegModel + interactive_seg_device: Device + enable_remove_bg: bool + remove_bg_model: str + enable_anime_seg: bool + enable_realesrgan: bool + realesrgan_device: Device + realesrgan_model: RealESRGANModel + enable_gfpgan: bool + gfpgan_device: Device + enable_restoreformer: bool + restoreformer_device: Device + + +class InpaintRequest(BaseModel): + image: Optional[str] = Field(None, description="base64 encoded image") + mask: Optional[str] = Field(None, description="base64 encoded mask") + + ldm_steps: int = Field(20, description="Steps for ldm model.") + ldm_sampler: str = Field(LDMSampler.plms, discription="Sampler for ldm model.") + zits_wireframe: bool = Field(True, description="Enable wireframe for zits model.") + + hd_strategy: str = Field( + HDStrategy.CROP, + description="Different way to preprocess image, only used by erase models(e.g. lama/mat)", + ) + hd_strategy_crop_trigger_size: int = Field( + 800, + description="Crop trigger size for hd_strategy=CROP, if the longer side of the image is larger than this value, use crop strategy", + ) + hd_strategy_crop_margin: int = Field( + 128, description="Crop margin for hd_strategy=CROP" + ) + hd_strategy_resize_limit: int = Field( + 1280, description="Resize limit for hd_strategy=RESIZE" + ) + + prompt: str = Field("", description="Prompt for diffusion models.") + negative_prompt: str = Field( + "", description="Negative prompt for diffusion models." + ) + use_croper: bool = Field( + False, description="Crop image before doing diffusion inpainting" + ) + croper_x: int = Field(0, description="Crop x for croper") + croper_y: int = Field(0, description="Crop y for croper") + croper_height: int = Field(512, description="Crop height for croper") + croper_width: int = Field(512, description="Crop width for croper") + + use_extender: bool = Field( + False, description="Extend image before doing sd outpainting" + ) + extender_x: int = Field(0, description="Extend x for extender") + extender_y: int = Field(0, description="Extend y for extender") + extender_height: int = Field(640, description="Extend height for extender") + extender_width: int = Field(640, description="Extend width for extender") + + sd_scale: float = Field( + 1.0, + description="Resize the image before doing sd inpainting, the area outside the mask will not lose quality.", + gt=0.0, + le=1.0, + ) + sd_mask_blur: int = Field( + 11, + description="Blur the edge of mask area. The higher the number the smoother blend with the original image", + ) + sd_strength: float = Field( + 1.0, + description="Strength is a measure of how much noise is added to the base image, which influences how similar the output is to the base image. Higher value means more noise and more different from the base image", + le=1.0, + ) + sd_steps: int = Field( + 50, + description="The number of denoising steps. More denoising steps usually lead to a higher quality image at the expense of slower inference.", + ) + sd_guidance_scale: float = Field( + 7.5, + help="Higher guidance scale encourages to generate images that are closely linked to the text prompt, usually at the expense of lower image quality.", + ) + sd_sampler: str = Field( + SDSampler.uni_pc, description="Sampler for diffusion model." + ) + sd_seed: int = Field( + 42, + description="Seed for diffusion model. -1 mean random seed", + validate_default=True, + ) + sd_match_histograms: bool = Field( + False, + description="Match histograms between inpainting area and original image.", + ) + + sd_outpainting_softness: float = Field(20.0) + sd_outpainting_space: float = Field(20.0) + + sd_freeu: bool = Field( + False, + description="Enable freeu mode. https://huggingface.co/docs/diffusers/main/en/using-diffusers/freeu", + ) + sd_freeu_config: FREEUConfig = FREEUConfig() + + sd_lcm_lora: bool = Field( + False, + description="Enable lcm-lora mode. https://huggingface.co/docs/diffusers/main/en/using-diffusers/inference_with_lcm#texttoimage", + ) + + sd_keep_unmasked_area: bool = Field( + True, description="Keep unmasked area unchanged" + ) + + cv2_flag: CV2Flag = Field( + CV2Flag.INPAINT_NS, + description="Flag for opencv inpainting: https://docs.opencv.org/4.6.0/d7/d8b/group__photo__inpaint.html#gga8002a65f5a3328fbf15df81b842d3c3ca05e763003a805e6c11c673a9f4ba7d07", + ) + cv2_radius: int = Field( + 4, + description="Radius of a circular neighborhood of each point inpainted that is considered by the algorithm", + ) + + # Paint by Example + paint_by_example_example_image: Optional[str] = Field( + None, description="Base64 encoded example image for paint by example model" + ) + + # InstructPix2Pix + p2p_image_guidance_scale: float = Field(1.5, description="Image guidance scale") + + # ControlNet + enable_controlnet: bool = Field(False, description="Enable controlnet") + controlnet_conditioning_scale: float = Field( + 0.4, description="Conditioning scale", ge=0.0, le=1.0 + ) + controlnet_method: str = Field( + "lllyasviel/control_v11p_sd15_canny", description="Controlnet method" + ) + + # PowerPaint + powerpaint_task: PowerPaintTask = Field( + PowerPaintTask.text_guided, description="PowerPaint task" + ) + fitting_degree: float = Field( + 1.0, + description="Control the fitting degree of the generated objects to the mask shape.", + gt=0.0, + le=1.0, + ) + + @field_validator("sd_seed") + @classmethod + def sd_seed_validator(cls, v: int) -> int: + if v == -1: + return random.randint(1, 99999999) + return v + + @field_validator("controlnet_conditioning_scale") + @classmethod + def validate_field(cls, v: float, values): + use_extender = values.data["use_extender"] + enable_controlnet = values.data["enable_controlnet"] + if use_extender and enable_controlnet: + logger.info(f"Extender is enabled, set controlnet_conditioning_scale=0") + return 0 + return v + + @field_validator("sd_strength") + @classmethod + def validate_sd_strength(cls, v: float, values): + use_extender = values.data["use_extender"] + if use_extender: + logger.info(f"Extender is enabled, set sd_strength=1") + return 1.0 + return v + + +class RunPluginRequest(BaseModel): + name: str + image: str = Field(..., description="base64 encoded image") + clicks: List[List[int]] = Field( + [], description="Clicks for interactive seg, [[x,y,0/1], [x2,y2,0/1]]" + ) + scale: float = Field(2.0, description="Scale for upscaling") + + +MediaTab = Literal["input", "output"] + + +class MediasResponse(BaseModel): + name: str + height: int + width: int + ctime: float + mtime: float + + +class GenInfoResponse(BaseModel): + prompt: str = "" + negative_prompt: str = "" + + +class ServerConfigResponse(BaseModel): + plugins: List[PluginInfo] + modelInfos: List[ModelInfo] + removeBGModel: RemoveBGModel + removeBGModels: List[RemoveBGModel] + realesrganModel: RealESRGANModel + realesrganModels: List[RealESRGANModel] + interactiveSegModel: InteractiveSegModel + interactiveSegModels: List[InteractiveSegModel] + enableFileManager: bool + enableAutoSaving: bool + enableControlnet: bool + controlnetMethod: Optional[str] + disableModelSwitch: bool + isDesktop: bool + samplers: List[str] + + +class SwitchModelRequest(BaseModel): + name: str + + +class SwitchPluginModelRequest(BaseModel): + plugin_name: str + model_name: str + + +AdjustMaskOperate = Literal["expand", "shrink", "reverse"] + + +class AdjustMaskRequest(BaseModel): + mask: str = Field( + ..., description="base64 encoded mask. 255 means area to do inpaint" + ) + operate: AdjustMaskOperate = Field(..., description="expand/shrink/reverse") + kernel_size: int = Field(5, description="Kernel size for expanding mask") diff --git a/py/iopaint/tests/__init__.py b/py/iopaint/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/py/iopaint/tests/test_adjust_mask.py b/py/iopaint/tests/test_adjust_mask.py new file mode 100644 index 0000000..b538554 --- /dev/null +++ b/py/iopaint/tests/test_adjust_mask.py @@ -0,0 +1,17 @@ +import cv2 +from ..helper import adjust_mask +from ..tests.utils import current_dir, save_dir + +mask_p = current_dir / "overture-creations-5sI6fQgYIuo_mask.png" + + +def test_adjust_mask(): + mask = cv2.imread(str(mask_p), cv2.IMREAD_GRAYSCALE) + res_mask = adjust_mask(mask, 0, "expand") + cv2.imwrite(str(save_dir / "adjust_mask_original.png"), res_mask) + res_mask = adjust_mask(mask, 40, "expand") + cv2.imwrite(str(save_dir / "adjust_mask_expand.png"), res_mask) + res_mask = adjust_mask(mask, 20, "shrink") + cv2.imwrite(str(save_dir / "adjust_mask_shrink.png"), res_mask) + res_mask = adjust_mask(mask, 20, "reverse") + cv2.imwrite(str(save_dir / "adjust_mask_reverse.png"), res_mask) diff --git a/py/iopaint/tests/test_anytext.py b/py/iopaint/tests/test_anytext.py new file mode 100644 index 0000000..0fdc2cb --- /dev/null +++ b/py/iopaint/tests/test_anytext.py @@ -0,0 +1,45 @@ +import os + +from ..tests.utils import check_device, get_config, assert_equal + +os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1" +from pathlib import Path + +import pytest +import torch + +from ..model_manager import ModelManager +from ..schema import HDStrategy + +current_dir = Path(__file__).parent.absolute().resolve() +save_dir = current_dir / "result" +save_dir.mkdir(exist_ok=True, parents=True) + + +@pytest.mark.parametrize("device", ["cuda", "mps"]) +def test_anytext(device): + sd_steps = check_device(device) + model = ModelManager( + name="Sanster/AnyText", + device=torch.device(device), + disable_nsfw=True, + sd_cpu_textencoder=False, + ) + + cfg = get_config( + strategy=HDStrategy.ORIGINAL, + prompt='Characters written in chalk on the blackboard that says "DADDY", best quality, extremely detailed,4k, HD, supper legible text, clear text edges, clear strokes, neat writing, no watermarks', + negative_prompt="low-res, bad anatomy, extra digit, fewer digits, cropped, worst quality, low quality, watermark, unreadable text, messy words, distorted text, disorganized writing, advertising picture", + sd_steps=sd_steps, + sd_guidance_scale=9.0, + sd_seed=66273235, + sd_match_histograms=True + ) + + assert_equal( + model, + cfg, + f"anytext.png", + img_p=current_dir / "anytext_ref.jpg", + mask_p=current_dir / "anytext_mask.jpg", + ) diff --git a/py/iopaint/tests/test_controlnet.py b/py/iopaint/tests/test_controlnet.py new file mode 100644 index 0000000..295d9e6 --- /dev/null +++ b/py/iopaint/tests/test_controlnet.py @@ -0,0 +1,118 @@ +import os + +from ..const import SD_CONTROLNET_CHOICES +from ..tests.utils import current_dir, check_device, get_config, assert_equal + +os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1" +from pathlib import Path + +import pytest +import torch + +from ..model_manager import ModelManager +from ..schema import HDStrategy, SDSampler + + +model_name = "runwayml/stable-diffusion-inpainting" + + +def convert_controlnet_method_name(name): + return name.replace("/", "--") + + +@pytest.mark.parametrize("device", ["cuda", "mps", "cpu"]) +@pytest.mark.parametrize("controlnet_method", [SD_CONTROLNET_CHOICES[0]]) +def test_runway_sd_1_5(device, controlnet_method): + sd_steps = check_device(device) + + model = ModelManager( + name=model_name, + device=torch.device(device), + disable_nsfw=True, + sd_cpu_textencoder=device == "cuda", + enable_controlnet=True, + controlnet_method=controlnet_method, + ) + + cfg = get_config( + prompt="a fox sitting on a bench", + sd_steps=sd_steps, + enable_controlnet=True, + controlnet_conditioning_scale=0.5, + controlnet_method=controlnet_method, + ) + name = f"device_{device}" + + assert_equal( + model, + cfg, + f"sd_controlnet_{convert_controlnet_method_name(controlnet_method)}_{name}.png", + img_p=current_dir / "overture-creations-5sI6fQgYIuo.png", + mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png", + ) + + +@pytest.mark.parametrize("device", ["cuda", "mps", "cpu"]) +def test_controlnet_switch(device): + sd_steps = check_device(device) + model = ModelManager( + name=model_name, + device=torch.device(device), + disable_nsfw=True, + sd_cpu_textencoder=False, + cpu_offload=True, + enable_controlnet=True, + controlnet_method="lllyasviel/control_v11p_sd15_canny", + ) + cfg = get_config( + prompt="a fox sitting on a bench", + sd_steps=sd_steps, + enable_controlnet=True, + controlnet_method="lllyasviel/control_v11f1p_sd15_depth", + ) + + assert_equal( + model, + cfg, + f"controlnet_switch_canny_to_depth_device_{device}.png", + img_p=current_dir / "overture-creations-5sI6fQgYIuo.png", + mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png", + fx=1.2 + ) + + +@pytest.mark.parametrize("device", ["cuda", "mps", "cpu"]) +@pytest.mark.parametrize( + "local_file", ["sd-v1-5-inpainting.ckpt", "v1-5-pruned-emaonly.safetensors"] +) +def test_local_file_path(device, local_file): + sd_steps = check_device(device) + + controlnet_kwargs = dict( + enable_controlnet=True, + controlnet_method=SD_CONTROLNET_CHOICES[0], + ) + + model = ModelManager( + name=local_file, + device=torch.device(device), + disable_nsfw=True, + sd_cpu_textencoder=False, + cpu_offload=True, + **controlnet_kwargs, + ) + cfg = get_config( + prompt="a fox sitting on a bench", + sd_steps=sd_steps, + **controlnet_kwargs, + ) + + name = f"device_{device}" + + assert_equal( + model, + cfg, + f"{convert_controlnet_method_name(controlnet_kwargs['controlnet_method'])}_local_model_{name}.png", + img_p=current_dir / "overture-creations-5sI6fQgYIuo.png", + mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png", + ) diff --git a/py/iopaint/tests/test_instruct_pix2pix.py b/py/iopaint/tests/test_instruct_pix2pix.py new file mode 100644 index 0000000..ee10bf9 --- /dev/null +++ b/py/iopaint/tests/test_instruct_pix2pix.py @@ -0,0 +1,40 @@ +from pathlib import Path + +import pytest +import torch + +from ..model_manager import ModelManager +from ..schema import HDStrategy +from ..tests.utils import get_config, check_device, assert_equal, current_dir + +model_name = "timbrooks/instruct-pix2pix" + + +@pytest.mark.parametrize("device", ["cuda", "mps", "cpu"]) +@pytest.mark.parametrize("disable_nsfw", [True, False]) +@pytest.mark.parametrize("cpu_offload", [False, True]) +def test_instruct_pix2pix(device, disable_nsfw, cpu_offload): + sd_steps = check_device(device) + model = ModelManager( + name=model_name, + device=torch.device(device), + disable_nsfw=disable_nsfw, + sd_cpu_textencoder=False, + cpu_offload=cpu_offload, + ) + cfg = get_config( + strategy=HDStrategy.ORIGINAL, + prompt="What if it were snowing?", + sd_steps=sd_steps + ) + + name = f"device_{device}_disnsfw_{disable_nsfw}_cpu_offload_{cpu_offload}" + + assert_equal( + model, + cfg, + f"instruct_pix2pix_{name}.png", + img_p=current_dir / "overture-creations-5sI6fQgYIuo.png", + mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png", + fx=1.3, + ) diff --git a/py/iopaint/tests/test_load_img.py b/py/iopaint/tests/test_load_img.py new file mode 100644 index 0000000..29142cc --- /dev/null +++ b/py/iopaint/tests/test_load_img.py @@ -0,0 +1,19 @@ +from ..helper import load_img +from ..tests.utils import current_dir + +png_img_p = current_dir / "image.png" +jpg_img_p = current_dir / "bunny.jpeg" + + +def test_load_png_image(): + with open(png_img_p, "rb") as f: + np_img, alpha_channel = load_img(f.read()) + assert np_img.shape == (256, 256, 3) + assert alpha_channel.shape == (256, 256) + + +def test_load_jpg_image(): + with open(jpg_img_p, "rb") as f: + np_img, alpha_channel = load_img(f.read()) + assert np_img.shape == (394, 448, 3) + assert alpha_channel is None diff --git a/py/iopaint/tests/test_low_mem.py b/py/iopaint/tests/test_low_mem.py new file mode 100644 index 0000000..00d2ef2 --- /dev/null +++ b/py/iopaint/tests/test_low_mem.py @@ -0,0 +1,131 @@ +import os + +from loguru import logger + +from ..tests.utils import check_device, get_config, assert_equal, current_dir + +os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1" + +import pytest +import torch + +from ..model_manager import ModelManager +from ..schema import HDStrategy, SDSampler, FREEUConfig + + +@pytest.mark.parametrize("device", ["cuda", "mps"]) +def test_runway_sd_1_5_low_mem(device): + sd_steps = check_device(device) + model = ModelManager( + name="runwayml/stable-diffusion-inpainting", + device=torch.device(device), + disable_nsfw=True, + sd_cpu_textencoder=False, + low_mem=True, + ) + + all_samplers = [member.value for member in SDSampler.__members__.values()] + print(all_samplers) + cfg = get_config( + strategy=HDStrategy.ORIGINAL, + prompt="a fox sitting on a bench", + sd_steps=sd_steps, + sd_sampler=SDSampler.ddim, + ) + + name = f"device_{device}" + + assert_equal( + model, + cfg, + f"runway_sd_{name}_low_mem.png", + img_p=current_dir / "overture-creations-5sI6fQgYIuo.png", + mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png", + ) + + +@pytest.mark.parametrize("device", ["cuda", "mps", "cpu"]) +@pytest.mark.parametrize("sampler", [SDSampler.lcm]) +def test_runway_sd_lcm_lora_low_mem(device, sampler): + check_device(device) + + sd_steps = 5 + model = ModelManager( + name="runwayml/stable-diffusion-inpainting", + device=torch.device(device), + disable_nsfw=True, + sd_cpu_textencoder=False, + low_mem=True, + ) + cfg = get_config( + strategy=HDStrategy.ORIGINAL, + prompt="face of a fox, sitting on a bench", + sd_steps=sd_steps, + sd_guidance_scale=2, + sd_lcm_lora=True, + ) + cfg.sd_sampler = sampler + + assert_equal( + model, + cfg, + f"runway_sd_1_5_lcm_lora_device_{device}_low_mem.png", + img_p=current_dir / "overture-creations-5sI6fQgYIuo.png", + mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png", + ) + + +@pytest.mark.parametrize("device", ["cuda", "mps", "cpu"]) +@pytest.mark.parametrize("sampler", [SDSampler.ddim]) +def test_runway_sd_freeu(device, sampler): + sd_steps = check_device(device) + model = ModelManager( + name="runwayml/stable-diffusion-inpainting", + device=torch.device(device), + disable_nsfw=True, + sd_cpu_textencoder=False, + low_mem=True, + ) + cfg = get_config( + strategy=HDStrategy.ORIGINAL, + prompt="face of a fox, sitting on a bench", + sd_steps=sd_steps, + sd_guidance_scale=7.5, + sd_freeu=True, + sd_freeu_config=FREEUConfig(), + ) + cfg.sd_sampler = sampler + + assert_equal( + model, + cfg, + f"runway_sd_1_5_freeu_device_{device}_low_mem.png", + img_p=current_dir / "overture-creations-5sI6fQgYIuo.png", + mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png", + ) + + +@pytest.mark.parametrize("device", ["cuda", "mps", "cpu"]) +@pytest.mark.parametrize("strategy", [HDStrategy.ORIGINAL]) +@pytest.mark.parametrize("sampler", [SDSampler.ddim]) +def test_runway_norm_sd_model(device, strategy, sampler): + sd_steps = check_device(device) + model = ModelManager( + name="runwayml/stable-diffusion-v1-5", + device=torch.device(device), + disable_nsfw=True, + sd_cpu_textencoder=False, + low_mem=True, + ) + cfg = get_config( + strategy=strategy, prompt="face of a fox, sitting on a bench", sd_steps=sd_steps + ) + cfg.sd_sampler = sampler + + assert_equal( + model, + cfg, + f"runway_{device}_norm_sd_model_device_{device}_low_mem.png", + img_p=current_dir / "overture-creations-5sI6fQgYIuo.png", + mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png", + ) diff --git a/py/iopaint/tests/test_match_histograms.py b/py/iopaint/tests/test_match_histograms.py new file mode 100644 index 0000000..10dfb22 --- /dev/null +++ b/py/iopaint/tests/test_match_histograms.py @@ -0,0 +1,36 @@ +import pytest +import torch + +from ..model_manager import ModelManager +from ..schema import SDSampler, HDStrategy +from ..tests.utils import check_device, get_config, assert_equal, current_dir + + +@pytest.mark.parametrize("device", ["cuda", "mps"]) +@pytest.mark.parametrize("sampler", [SDSampler.ddim]) +def test_sd_match_histograms(device, sampler): + sd_steps = check_device(device) + + model = ModelManager( + name="runwayml/stable-diffusion-inpainting", + device=torch.device(device), + disable_nsfw=True, + sd_cpu_textencoder=False, + ) + cfg = get_config( + strategy=HDStrategy.ORIGINAL, + prompt="face of a fox, sitting on a bench", + sd_steps=sd_steps, + sd_guidance_scale=7.5, + sd_lcm_lora=False, + sd_match_histograms=True, + sd_sampler=sampler + ) + + assert_equal( + model, + cfg, + f"runway_sd_1_5_device_{device}_match_histograms.png", + img_p=current_dir / "overture-creations-5sI6fQgYIuo.png", + mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png", + ) diff --git a/py/iopaint/tests/test_model.py b/py/iopaint/tests/test_model.py new file mode 100644 index 0000000..92bdf79 --- /dev/null +++ b/py/iopaint/tests/test_model.py @@ -0,0 +1,160 @@ +import pytest +import torch + +from ..model_manager import ModelManager +from ..schema import HDStrategy, LDMSampler +from ..tests.utils import assert_equal, get_config, current_dir, check_device + + +@pytest.mark.parametrize("device", ["cuda", "mps", "cpu"]) +@pytest.mark.parametrize( + "strategy", [HDStrategy.ORIGINAL, HDStrategy.RESIZE, HDStrategy.CROP] +) +def test_lama(device, strategy): + check_device(device) + model = ModelManager(name="lama", device=device) + assert_equal( + model, + get_config(strategy=strategy), + f"lama_{strategy[0].upper() + strategy[1:]}_result.png", + ) + + fx = 1.3 + assert_equal( + model, + get_config(strategy=strategy), + f"lama_{strategy[0].upper() + strategy[1:]}_fx_{fx}_result.png", + fx=1.3, + ) + + +@pytest.mark.parametrize("device", ["cuda", "cpu"]) +@pytest.mark.parametrize( + "strategy", [HDStrategy.ORIGINAL, HDStrategy.RESIZE, HDStrategy.CROP] +) +@pytest.mark.parametrize("ldm_sampler", [LDMSampler.ddim, LDMSampler.plms]) +def test_ldm(device, strategy, ldm_sampler): + check_device(device) + model = ModelManager(name="ldm", device=device) + cfg = get_config(strategy=strategy, ldm_sampler=ldm_sampler) + assert_equal( + model, cfg, f"ldm_{strategy[0].upper() + strategy[1:]}_{ldm_sampler}_result.png" + ) + + fx = 1.3 + assert_equal( + model, + cfg, + f"ldm_{strategy[0].upper() + strategy[1:]}_{ldm_sampler}_fx_{fx}_result.png", + fx=fx, + ) + + +@pytest.mark.parametrize("device", ["cuda", "cpu"]) +@pytest.mark.parametrize( + "strategy", [HDStrategy.ORIGINAL, HDStrategy.RESIZE, HDStrategy.CROP] +) +@pytest.mark.parametrize("zits_wireframe", [False, True]) +def test_zits(device, strategy, zits_wireframe): + check_device(device) + model = ModelManager(name="zits", device=device) + cfg = get_config(strategy=strategy, zits_wireframe=zits_wireframe) + assert_equal( + model, + cfg, + f"zits_{strategy[0].upper() + strategy[1:]}_wireframe_{zits_wireframe}_result.png", + ) + + fx = 1.3 + assert_equal( + model, + cfg, + f"zits_{strategy.capitalize()}_wireframe_{zits_wireframe}_fx_{fx}_result.png", + fx=fx, + ) + + +@pytest.mark.parametrize("device", ["cuda", "cpu"]) +@pytest.mark.parametrize("strategy", [HDStrategy.ORIGINAL]) +@pytest.mark.parametrize("no_half", [True, False]) +def test_mat(device, strategy, no_half): + check_device(device) + model = ModelManager(name="mat", device=device, no_half=no_half) + cfg = get_config(strategy=strategy) + + assert_equal( + model, + cfg, + f"mat_{strategy.capitalize()}_result.png", + ) + + +@pytest.mark.parametrize("device", ["cuda", "cpu"]) +@pytest.mark.parametrize("strategy", [HDStrategy.ORIGINAL]) +def test_fcf(device, strategy): + check_device(device) + model = ModelManager(name="fcf", device=device) + cfg = get_config(strategy=strategy) + + assert_equal(model, cfg, f"fcf_{strategy.capitalize()}_result.png", fx=2, fy=2) + assert_equal(model, cfg, f"fcf_{strategy.capitalize()}_result.png", fx=3.8, fy=2) + + +@pytest.mark.parametrize( + "strategy", [HDStrategy.ORIGINAL, HDStrategy.RESIZE, HDStrategy.CROP] +) +@pytest.mark.parametrize("cv2_flag", ["INPAINT_NS", "INPAINT_TELEA"]) +@pytest.mark.parametrize("cv2_radius", [3, 15]) +def test_cv2(strategy, cv2_flag, cv2_radius): + model = ModelManager( + name="cv2", + device=torch.device("cpu"), + ) + cfg = get_config(strategy=strategy, cv2_flag=cv2_flag, cv2_radius=cv2_radius) + assert_equal( + model, + cfg, + f"cv2_{strategy.capitalize()}_{cv2_flag}_{cv2_radius}.png", + img_p=current_dir / "overture-creations-5sI6fQgYIuo.png", + mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png", + ) + + +@pytest.mark.parametrize("device", ["cuda", "cpu"]) +@pytest.mark.parametrize( + "strategy", [HDStrategy.ORIGINAL, HDStrategy.RESIZE, HDStrategy.CROP] +) +def test_manga(device, strategy): + check_device(device) + model = ModelManager( + name="manga", + device=torch.device(device), + ) + cfg = get_config(strategy=strategy) + assert_equal( + model, + cfg, + f"manga_{strategy.capitalize()}.png", + img_p=current_dir / "overture-creations-5sI6fQgYIuo.png", + mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png", + ) + + +@pytest.mark.parametrize("device", ["cuda", "mps", "cpu"]) +@pytest.mark.parametrize("strategy", [HDStrategy.ORIGINAL]) +def test_mi_gan(device, strategy): + check_device(device) + model = ModelManager( + name="migan", + device=torch.device(device), + ) + cfg = get_config(strategy=strategy) + assert_equal( + model, + cfg, + f"migan_device_{device}.png", + img_p=current_dir / "overture-creations-5sI6fQgYIuo.png", + mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png", + fx=1.5, + fy=1.7 + ) diff --git a/py/iopaint/tests/test_model_md5.py b/py/iopaint/tests/test_model_md5.py new file mode 100644 index 0000000..51cb2c1 --- /dev/null +++ b/py/iopaint/tests/test_model_md5.py @@ -0,0 +1,16 @@ +def test_load_model(): + from ..plugins import InteractiveSeg + from ..model_manager import ModelManager + + interactive_seg_model = InteractiveSeg("vit_l", "cpu") + + models = ["lama", "ldm", "zits", "mat", "fcf", "manga", "migan"] + for m in models: + ModelManager( + name=m, + device="cpu", + no_half=False, + disable_nsfw=False, + sd_cpu_textencoder=True, + cpu_offload=True, + ) diff --git a/py/iopaint/tests/test_model_switch.py b/py/iopaint/tests/test_model_switch.py new file mode 100644 index 0000000..233747c --- /dev/null +++ b/py/iopaint/tests/test_model_switch.py @@ -0,0 +1,70 @@ +import os + +from ..schema import InpaintRequest + +os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1" + +import torch + +from ..model_manager import ModelManager + + +def test_model_switch(): + model = ModelManager( + name="runwayml/stable-diffusion-inpainting", + enable_controlnet=True, + controlnet_method="lllyasviel/control_v11p_sd15_canny", + device=torch.device("mps"), + disable_nsfw=True, + sd_cpu_textencoder=True, + cpu_offload=False, + ) + + model.switch("lama") + + +def test_controlnet_switch_onoff(caplog): + name = "runwayml/stable-diffusion-inpainting" + model = ModelManager( + name=name, + enable_controlnet=True, + controlnet_method="lllyasviel/control_v11p_sd15_canny", + device=torch.device("mps"), + disable_nsfw=True, + sd_cpu_textencoder=True, + cpu_offload=False, + ) + + model.switch_controlnet_method( + InpaintRequest( + name=name, + enable_controlnet=False, + ) + ) + + assert "Disable controlnet" in caplog.text + + +def test_switch_controlnet_method(caplog): + name = "runwayml/stable-diffusion-inpainting" + old_method = "lllyasviel/control_v11p_sd15_canny" + new_method = "lllyasviel/control_v11p_sd15_openpose" + model = ModelManager( + name=name, + enable_controlnet=True, + controlnet_method=old_method, + device=torch.device("mps"), + disable_nsfw=True, + sd_cpu_textencoder=True, + cpu_offload=False, + ) + + model.switch_controlnet_method( + InpaintRequest( + name=name, + enable_controlnet=True, + controlnet_method=new_method, + ) + ) + + assert f"Switch Controlnet method from {old_method} to {new_method}" in caplog.text diff --git a/py/iopaint/tests/test_outpainting.py b/py/iopaint/tests/test_outpainting.py new file mode 100644 index 0000000..0d7eef6 --- /dev/null +++ b/py/iopaint/tests/test_outpainting.py @@ -0,0 +1,138 @@ +import os + +from ..tests.utils import current_dir, check_device + +os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1" +from pathlib import Path + +import pytest +import torch + +from ..model_manager import ModelManager +from ..schema import HDStrategy, SDSampler +from ..tests.test_model import get_config, assert_equal + + +@pytest.mark.parametrize("name", ["runwayml/stable-diffusion-inpainting"]) +@pytest.mark.parametrize("device", ["cuda", "mps", "cpu"]) +@pytest.mark.parametrize( + "rect", + [ + [0, -100, 512, 512 - 128 + 100], + [0, 128, 512, 512 - 128 + 100], + [128, 0, 512 - 128 + 100, 512], + [-100, 0, 512 - 128 + 100, 512], + [0, 0, 512, 512 + 200], + [0, 0, 512 + 200, 512], + [-100, -100, 512 + 200, 512 + 200], + ], +) +def test_outpainting(name, device, rect): + sd_steps = check_device(device) + + model = ModelManager( + name=name, + device=torch.device(device), + disable_nsfw=True, + sd_cpu_textencoder=False, + ) + cfg = get_config( + prompt="a dog sitting on a bench in the park", + sd_steps=sd_steps, + use_extender=True, + extender_x=rect[0], + extender_y=rect[1], + extender_width=rect[2], + extender_height=rect[3], + sd_guidance_scale=8.0, + sd_sampler=SDSampler.dpm_plus_plus_2m, + ) + + assert_equal( + model, + cfg, + f"{name.replace('/', '--')}_outpainting_{'_'.join(map(str, rect))}_device_{device}.png", + img_p=current_dir / "overture-creations-5sI6fQgYIuo.png", + mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png", + ) + + +@pytest.mark.parametrize("name", ["kandinsky-community/kandinsky-2-2-decoder-inpaint"]) +@pytest.mark.parametrize("device", ["cuda", "mps", "cpu"]) +@pytest.mark.parametrize( + "rect", + [ + [-128, -128, 768, 768], + ], +) +def test_kandinsky_outpainting(name, device, rect): + sd_steps = check_device(device) + + model = ModelManager( + name=name, + device=torch.device(device), + disable_nsfw=True, + sd_cpu_textencoder=False, + ) + cfg = get_config( + prompt="a cat", + negative_prompt="lowres, text, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, extra fingers, mutated hands, poorly drawn hands, poorly drawn face, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, cloned face, disfigured, gross proportions, malformed limbs, missing arms, missing legs, extra arms, extra legs, fused fingers, too many fingers, long neck, username, watermark, signature", + sd_steps=sd_steps, + use_extender=True, + extender_x=rect[0], + extender_y=rect[1], + extender_width=rect[2], + extender_height=rect[3], + sd_guidance_scale=7, + sd_sampler=SDSampler.dpm_plus_plus_2m, + ) + + assert_equal( + model, + cfg, + f"{name.replace('/', '--')}_outpainting_{'_'.join(map(str, rect))}_device_{device}.png", + img_p=current_dir / "cat.png", + mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png", + fx=1, + fy=1, + ) + + +@pytest.mark.parametrize("name", ["Sanster/PowerPaint-V1-stable-diffusion-inpainting"]) +@pytest.mark.parametrize("device", ["cuda", "mps", "cpu"]) +@pytest.mark.parametrize( + "rect", + [ + [-100, -100, 512 + 200, 512 + 200], + ], +) +def test_powerpaint_outpainting(name, device, rect): + sd_steps = check_device(device) + + model = ModelManager( + name=name, + device=torch.device(device), + disable_nsfw=True, + sd_cpu_textencoder=False, + low_mem=True + ) + cfg = get_config( + prompt="a dog sitting on a bench in the park", + sd_steps=sd_steps, + use_extender=True, + extender_x=rect[0], + extender_y=rect[1], + extender_width=rect[2], + extender_height=rect[3], + sd_guidance_scale=8.0, + sd_sampler=SDSampler.dpm_plus_plus_2m, + powerpaint_task="outpainting", + ) + + assert_equal( + model, + cfg, + f"{name.replace('/', '--')}_outpainting_{'_'.join(map(str, rect))}_device_{device}.png", + img_p=current_dir / "overture-creations-5sI6fQgYIuo.png", + mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png", + ) diff --git a/py/iopaint/tests/test_paint_by_example.py b/py/iopaint/tests/test_paint_by_example.py new file mode 100644 index 0000000..0f2479d --- /dev/null +++ b/py/iopaint/tests/test_paint_by_example.py @@ -0,0 +1,55 @@ +import cv2 +import pytest +from PIL import Image + +from ..model_manager import ModelManager +from ..schema import HDStrategy +from ..tests.utils import ( + current_dir, + get_config, + get_data, + save_dir, + check_device, +) + +model_name = "Fantasy-Studio/Paint-by-Example" + + +def assert_equal( + model, + config, + save_name: str, + fx: float = 1, + fy: float = 1, + img_p=current_dir / "overture-creations-5sI6fQgYIuo.png", + mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png", + example_p=current_dir / "bunny.jpeg", +): + img, mask = get_data(fx=fx, fy=fy, img_p=img_p, mask_p=mask_p) + + example_image = cv2.imread(str(example_p)) + example_image = cv2.cvtColor(example_image, cv2.COLOR_BGRA2RGB) + example_image = cv2.resize( + example_image, None, fx=fx, fy=fy, interpolation=cv2.INTER_AREA + ) + + print(f"Input image shape: {img.shape}, example_image: {example_image.shape}") + config.paint_by_example_example_image = Image.fromarray(example_image) + res = model(img, mask, config) + cv2.imwrite(str(save_dir / save_name), res) + + +@pytest.mark.parametrize("device", ["cuda", "mps", "cpu"]) +def test_paint_by_example(device): + sd_steps = check_device(device) + model = ModelManager(name=model_name, device=device, disable_nsfw=True) + cfg = get_config(strategy=HDStrategy.ORIGINAL, sd_steps=sd_steps) + assert_equal( + model, + cfg, + f"paint_by_example_device_{device}.png", + img_p=current_dir / "overture-creations-5sI6fQgYIuo.png", + mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png", + fy=0.9, + fx=1.3, + ) diff --git a/py/iopaint/tests/test_plugins.py b/py/iopaint/tests/test_plugins.py new file mode 100644 index 0000000..7dd5ee3 --- /dev/null +++ b/py/iopaint/tests/test_plugins.py @@ -0,0 +1,121 @@ +import hashlib +import os +import time +from PIL import Image + +from ..helper import encode_pil_to_base64, gen_frontend_mask +from ..plugins.anime_seg import AnimeSeg +from ..schema import RunPluginRequest, RemoveBGModel, InteractiveSegModel +from ..tests.utils import check_device, current_dir, save_dir + +os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1" + +import cv2 +import pytest + +from ..plugins import ( + RemoveBG, + RealESRGANUpscaler, + GFPGANPlugin, + RestoreFormerPlugin, + InteractiveSeg, +) + +img_p = current_dir / "bunny.jpeg" +img_bytes = open(img_p, "rb").read() +bgr_img = cv2.imread(str(img_p)) +rgb_img = cv2.cvtColor(bgr_img, cv2.COLOR_BGR2RGB) +rgb_img_base64 = encode_pil_to_base64(Image.fromarray(rgb_img), 100, {}) +bgr_img_base64 = encode_pil_to_base64(Image.fromarray(bgr_img), 100, {}) + + +def _save(img, name): + cv2.imwrite(str(save_dir / name), img) + + +def test_remove_bg(): + model = RemoveBG(RemoveBGModel.briaai_rmbg_1_4) + rgba_np_img = model.gen_image( + rgb_img, RunPluginRequest(name=RemoveBG.name, image=rgb_img_base64) + ) + res = cv2.cvtColor(rgba_np_img, cv2.COLOR_RGBA2BGRA) + _save(res, "test_remove_bg.png") + + bgr_np_img = model.gen_mask( + rgb_img, RunPluginRequest(name=RemoveBG.name, image=rgb_img_base64) + ) + + res_mask = gen_frontend_mask(bgr_np_img) + _save(res_mask, "test_remove_bg_frontend_mask.png") + + assert len(bgr_np_img.shape) == 2 + _save(bgr_np_img, "test_remove_bg_mask.jpeg") + + +def test_anime_seg(): + model = AnimeSeg() + img = cv2.imread(str(current_dir / "anime_test.png")) + img_base64 = encode_pil_to_base64(Image.fromarray(img), 100, {}) + res = model.gen_image(img, RunPluginRequest(name=AnimeSeg.name, image=img_base64)) + assert len(res.shape) == 3 + assert res.shape[-1] == 4 + _save(res, "test_anime_seg.png") + + res = model.gen_mask(img, RunPluginRequest(name=AnimeSeg.name, image=img_base64)) + assert len(res.shape) == 2 + _save(res, "test_anime_seg_mask.png") + + +@pytest.mark.parametrize("device", ["cuda", "cpu", "mps"]) +def test_upscale(device): + check_device(device) + model = RealESRGANUpscaler("realesr-general-x4v3", device) + res = model.gen_image( + rgb_img, + RunPluginRequest(name=RealESRGANUpscaler.name, image=rgb_img_base64, scale=2), + ) + _save(res, f"test_upscale_x2_{device}.png") + + res = model.gen_image( + rgb_img, + RunPluginRequest(name=RealESRGANUpscaler.name, image=rgb_img_base64, scale=4), + ) + _save(res, f"test_upscale_x4_{device}.png") + + +@pytest.mark.parametrize("device", ["cuda", "cpu", "mps"]) +def test_gfpgan(device): + check_device(device) + model = GFPGANPlugin(device) + res = model.gen_image( + rgb_img, RunPluginRequest(name=GFPGANPlugin.name, image=rgb_img_base64) + ) + _save(res, f"test_gfpgan_{device}.png") + + +@pytest.mark.parametrize("device", ["cuda", "cpu", "mps"]) +def test_restoreformer(device): + check_device(device) + model = RestoreFormerPlugin(device) + res = model.gen_image( + rgb_img, RunPluginRequest(name=RestoreFormerPlugin.name, image=rgb_img_base64) + ) + _save(res, f"test_restoreformer_{device}.png") + + +@pytest.mark.parametrize("name", InteractiveSegModel.values()) +@pytest.mark.parametrize("device", ["cuda", "cpu", "mps"]) +def test_segment_anything(name, device): + check_device(device) + model = InteractiveSeg(name, device) + new_mask = model.gen_mask( + rgb_img, + RunPluginRequest( + name=InteractiveSeg.name, + image=rgb_img_base64, + clicks=([[448 // 2, 394 // 2, 1]]), + ), + ) + + save_name = f"test_segment_anything_{name}_{device}.png" + _save(new_mask, save_name) diff --git a/py/iopaint/tests/test_save_exif.py b/py/iopaint/tests/test_save_exif.py new file mode 100644 index 0000000..284f90b --- /dev/null +++ b/py/iopaint/tests/test_save_exif.py @@ -0,0 +1,59 @@ +import io +import tempfile +from pathlib import Path +from typing import List + +from PIL import Image + +from ..helper import pil_to_bytes, load_img + +current_dir = Path(__file__).parent.absolute().resolve() + + +def print_exif(exif): + for k, v in exif.items(): + print(f"{k}: {v}") + + +def extra_info(img_p: Path): + ext = img_p.suffix.strip(".") + img_bytes = img_p.read_bytes() + np_img, _, infos = load_img(img_bytes, False, True) + res_pil_bytes = pil_to_bytes(Image.fromarray(np_img), ext=ext, infos=infos) + res_img = Image.open(io.BytesIO(res_pil_bytes)) + return infos, res_img.info, res_pil_bytes + + +def assert_keys(keys: List[str], infos, res_infos): + for k in keys: + assert k in infos + assert k in res_infos + assert infos[k] == res_infos[k] + + +def run_test(file_path, keys): + infos, res_infos, res_pil_bytes = extra_info(file_path) + assert_keys(keys, infos, res_infos) + with tempfile.NamedTemporaryFile("wb", suffix=file_path.suffix) as temp_file: + temp_file.write(res_pil_bytes) + temp_file.flush() + infos, res_infos, res_pil_bytes = extra_info(Path(temp_file.name)) + assert_keys(keys, infos, res_infos) + + +def test_png_icc_profile_png(): + run_test(current_dir / "icc_profile_test.png", ["icc_profile", "exif"]) + + +def test_png_icc_profile_jpeg(): + run_test(current_dir / "icc_profile_test.jpg", ["icc_profile", "exif"]) + + +def test_jpeg(): + jpg_img_p = current_dir / "bunny.jpeg" + run_test(jpg_img_p, ["dpi", "exif"]) + + +def test_png_parameter(): + jpg_img_p = current_dir / "png_parameter_test.png" + run_test(jpg_img_p, ["parameters"]) diff --git a/py/iopaint/tests/test_sd_model.py b/py/iopaint/tests/test_sd_model.py new file mode 100644 index 0000000..fcaf4ec --- /dev/null +++ b/py/iopaint/tests/test_sd_model.py @@ -0,0 +1,269 @@ +import os + +from loguru import logger + +from ..tests.utils import check_device, get_config, assert_equal + +os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1" +from pathlib import Path + +import pytest +import torch + +from ..model_manager import ModelManager +from ..schema import HDStrategy, SDSampler, FREEUConfig + +current_dir = Path(__file__).parent.absolute().resolve() +save_dir = current_dir / "result" +save_dir.mkdir(exist_ok=True, parents=True) + + +@pytest.mark.parametrize("device", ["cuda", "mps"]) +def test_runway_sd_1_5_all_samplers(device): + sd_steps = check_device(device) + model = ModelManager( + name="runwayml/stable-diffusion-inpainting", + device=torch.device(device), + disable_nsfw=True, + sd_cpu_textencoder=False, + ) + + all_samplers = [member.value for member in SDSampler.__members__.values()] + print(all_samplers) + for sampler in all_samplers: + print(f"Testing sampler {sampler}") + if ( + sampler + in [SDSampler.dpm2_karras, SDSampler.dpm2_a_karras, SDSampler.lms_karras] + and device == "mps" + ): + # diffusers 0.25.0 still has bug on these sampler on mps, wait main branch released to fix it + logger.warning( + "skip dpm2_karras on mps, diffusers does not support it on mps. TypeError: Cannot convert a MPS Tensor to float64 dtype as the MPS framework doesn't support float64. Please use float32 instead." + ) + continue + cfg = get_config( + strategy=HDStrategy.ORIGINAL, + prompt="a fox sitting on a bench", + sd_steps=sd_steps, + sd_sampler=sampler, + ) + + name = f"device_{device}_{sampler}" + + assert_equal( + model, + cfg, + f"runway_sd_{name}.png", + img_p=current_dir / "overture-creations-5sI6fQgYIuo.png", + mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png", + ) + + +@pytest.mark.parametrize("device", ["cuda", "mps", "cpu"]) +@pytest.mark.parametrize("sampler", [SDSampler.lcm]) +def test_runway_sd_lcm_lora(device, sampler): + check_device(device) + + sd_steps = 5 + model = ModelManager( + name="runwayml/stable-diffusion-inpainting", + device=torch.device(device), + disable_nsfw=True, + sd_cpu_textencoder=False, + ) + cfg = get_config( + strategy=HDStrategy.ORIGINAL, + prompt="face of a fox, sitting on a bench", + sd_steps=sd_steps, + sd_guidance_scale=2, + sd_lcm_lora=True, + ) + cfg.sd_sampler = sampler + + assert_equal( + model, + cfg, + f"runway_sd_1_5_lcm_lora_device_{device}.png", + img_p=current_dir / "overture-creations-5sI6fQgYIuo.png", + mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png", + ) + + +@pytest.mark.parametrize("device", ["cuda", "mps", "cpu"]) +@pytest.mark.parametrize("sampler", [SDSampler.ddim]) +def test_runway_sd_freeu(device, sampler): + sd_steps = check_device(device) + model = ModelManager( + name="runwayml/stable-diffusion-inpainting", + device=torch.device(device), + disable_nsfw=True, + sd_cpu_textencoder=False, + ) + cfg = get_config( + strategy=HDStrategy.ORIGINAL, + prompt="face of a fox, sitting on a bench", + sd_steps=sd_steps, + sd_guidance_scale=7.5, + sd_freeu=True, + sd_freeu_config=FREEUConfig(), + ) + cfg.sd_sampler = sampler + + assert_equal( + model, + cfg, + f"runway_sd_1_5_freeu_device_{device}.png", + img_p=current_dir / "overture-creations-5sI6fQgYIuo.png", + mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png", + ) + + +@pytest.mark.parametrize("device", ["cuda", "mps"]) +@pytest.mark.parametrize("strategy", [HDStrategy.ORIGINAL]) +@pytest.mark.parametrize("sampler", [SDSampler.ddim]) +def test_runway_sd_sd_strength(device, strategy, sampler): + sd_steps = check_device(device) + model = ModelManager( + name="runwayml/stable-diffusion-inpainting", + device=torch.device(device), + disable_nsfw=True, + sd_cpu_textencoder=False, + ) + cfg = get_config( + strategy=strategy, + prompt="a fox sitting on a bench", + sd_steps=sd_steps, + sd_strength=0.8, + ) + cfg.sd_sampler = sampler + + assert_equal( + model, + cfg, + f"runway_sd_strength_0.8_device_{device}.png", + img_p=current_dir / "overture-creations-5sI6fQgYIuo.png", + mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png", + ) + + +@pytest.mark.parametrize("device", ["cuda", "cpu"]) +@pytest.mark.parametrize("strategy", [HDStrategy.ORIGINAL]) +@pytest.mark.parametrize("sampler", [SDSampler.ddim]) +def test_runway_sd_cpu_textencoder(device, strategy, sampler): + sd_steps = check_device(device) + model = ModelManager( + name="runwayml/stable-diffusion-inpainting", + device=torch.device(device), + disable_nsfw=True, + sd_cpu_textencoder=True, + ) + cfg = get_config( + strategy=strategy, + prompt="a fox sitting on a bench", + sd_steps=sd_steps, + sd_sampler=sampler, + ) + + assert_equal( + model, + cfg, + f"runway_sd_device_{device}_cpu_textencoder.png", + img_p=current_dir / "overture-creations-5sI6fQgYIuo.png", + mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png", + ) + + +@pytest.mark.parametrize("device", ["cuda", "mps", "cpu"]) +@pytest.mark.parametrize("strategy", [HDStrategy.ORIGINAL]) +@pytest.mark.parametrize("sampler", [SDSampler.ddim]) +def test_runway_norm_sd_model(device, strategy, sampler): + sd_steps = check_device(device) + model = ModelManager( + name="runwayml/stable-diffusion-v1-5", + device=torch.device(device), + disable_nsfw=True, + sd_cpu_textencoder=False, + ) + cfg = get_config( + strategy=strategy, prompt="face of a fox, sitting on a bench", sd_steps=sd_steps + ) + cfg.sd_sampler = sampler + + assert_equal( + model, + cfg, + f"runway_{device}_norm_sd_model_device_{device}.png", + img_p=current_dir / "overture-creations-5sI6fQgYIuo.png", + mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png", + ) + + +@pytest.mark.parametrize("device", ["cuda"]) +@pytest.mark.parametrize("strategy", [HDStrategy.ORIGINAL]) +@pytest.mark.parametrize("sampler", [SDSampler.dpm_plus_plus_2m]) +def test_runway_sd_1_5_cpu_offload(device, strategy, sampler): + sd_steps = check_device(device) + model = ModelManager( + name="runwayml/stable-diffusion-inpainting", + device=torch.device(device), + disable_nsfw=True, + sd_cpu_textencoder=False, + cpu_offload=True, + ) + cfg = get_config( + strategy=strategy, prompt="a fox sitting on a bench", sd_steps=sd_steps + ) + cfg.sd_sampler = sampler + + name = f"device_{device}_{sampler}" + + assert_equal( + model, + cfg, + f"runway_sd_{strategy.capitalize()}_{name}_cpu_offload.png", + img_p=current_dir / "overture-creations-5sI6fQgYIuo.png", + mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png", + ) + + +@pytest.mark.parametrize("device", ["cuda", "mps", "cpu"]) +@pytest.mark.parametrize("sampler", [SDSampler.ddim]) +@pytest.mark.parametrize( + "name", + [ + "sd-v1-5-inpainting.safetensors", + "v1-5-pruned-emaonly.safetensors", + "sd_xl_base_1.0.safetensors", + "sd_xl_base_1.0_inpainting_0.1.safetensors", + ], +) +def test_local_file_path(device, sampler, name): + sd_steps = check_device(device) + model = ModelManager( + name=name, + device=torch.device(device), + disable_nsfw=True, + sd_cpu_textencoder=False, + cpu_offload=False, + ) + cfg = get_config( + strategy=HDStrategy.ORIGINAL, + prompt="a fox sitting on a bench", + sd_steps=sd_steps, + ) + cfg.sd_sampler = sampler + + name = f"device_{device}_{sampler}_{name}" + + is_sdxl = "sd_xl" in name + + assert_equal( + model, + cfg, + f"sd_local_model_{name}.png", + img_p=current_dir / "overture-creations-5sI6fQgYIuo.png", + mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png", + fx=1.5 if is_sdxl else 1, + fy=1.5 if is_sdxl else 1, + ) diff --git a/py/iopaint/tests/test_sdxl.py b/py/iopaint/tests/test_sdxl.py new file mode 100644 index 0000000..b4f116e --- /dev/null +++ b/py/iopaint/tests/test_sdxl.py @@ -0,0 +1,172 @@ +import os + +from ..tests.utils import check_device, current_dir + +os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1" + +import pytest +import torch + +from ..model_manager import ModelManager +from ..schema import HDStrategy, SDSampler, FREEUConfig +from ..tests.test_model import get_config, assert_equal + + +@pytest.mark.parametrize("device", ["cuda", "mps"]) +@pytest.mark.parametrize("strategy", [HDStrategy.ORIGINAL]) +@pytest.mark.parametrize("sampler", [SDSampler.ddim]) +def test_sdxl(device, strategy, sampler): + sd_steps = check_device(device) + + model = ModelManager( + name="diffusers/stable-diffusion-xl-1.0-inpainting-0.1", + device=torch.device(device), + disable_nsfw=True, + sd_cpu_textencoder=False, + ) + cfg = get_config( + strategy=strategy, + prompt="face of a fox, sitting on a bench", + sd_steps=sd_steps, + sd_strength=1.0, + sd_guidance_scale=7.0, + ) + cfg.sd_sampler = sampler + + assert_equal( + model, + cfg, + f"sdxl_device_{device}.png", + img_p=current_dir / "overture-creations-5sI6fQgYIuo.png", + mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png", + fx=2, + fy=2, + ) + + +@pytest.mark.parametrize("device", ["cuda", "cpu"]) +@pytest.mark.parametrize("strategy", [HDStrategy.ORIGINAL]) +@pytest.mark.parametrize("sampler", [SDSampler.ddim]) +def test_sdxl_cpu_text_encoder(device, strategy, sampler): + sd_steps = check_device(device) + + model = ModelManager( + name="diffusers/stable-diffusion-xl-1.0-inpainting-0.1", + device=torch.device(device), + disable_nsfw=True, + sd_cpu_textencoder=True, + ) + cfg = get_config( + strategy=strategy, + prompt="face of a fox, sitting on a bench", + sd_steps=sd_steps, + sd_strength=1.0, + sd_guidance_scale=7.0, + ) + cfg.sd_sampler = sampler + + assert_equal( + model, + cfg, + f"sdxl_device_{device}.png", + img_p=current_dir / "overture-creations-5sI6fQgYIuo.png", + mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png", + fx=2, + fy=2, + ) + + +@pytest.mark.parametrize("device", ["cuda", "mps"]) +@pytest.mark.parametrize("strategy", [HDStrategy.ORIGINAL]) +@pytest.mark.parametrize("sampler", [SDSampler.ddim]) +def test_sdxl_lcm_lora_and_freeu(device, strategy, sampler): + sd_steps = check_device(device) + + model = ModelManager( + name="diffusers/stable-diffusion-xl-1.0-inpainting-0.1", + device=torch.device(device), + disable_nsfw=True, + sd_cpu_textencoder=False, + ) + cfg = get_config( + strategy=strategy, + prompt="face of a fox, sitting on a bench", + sd_steps=sd_steps, + sd_strength=1.0, + sd_guidance_scale=2.0, + sd_lcm_lora=True, + ) + cfg.sd_sampler = sampler + + name = f"device_{device}_{sampler}" + + assert_equal( + model, + cfg, + f"sdxl_{name}_lcm_lora.png", + img_p=current_dir / "overture-creations-5sI6fQgYIuo.png", + mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png", + fx=2, + fy=2, + ) + + cfg = get_config( + strategy=strategy, + prompt="face of a fox, sitting on a bench", + sd_steps=sd_steps, + sd_guidance_scale=7.5, + sd_freeu=True, + sd_freeu_config=FREEUConfig(), + ) + + assert_equal( + model, + cfg, + f"sdxl_{name}_freeu_device_{device}.png", + img_p=current_dir / "overture-creations-5sI6fQgYIuo.png", + mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png", + fx=2, + fy=2, + ) + + +@pytest.mark.parametrize("device", ["cuda", "mps"]) +@pytest.mark.parametrize( + "rect", + [ + [-128, -128, 1024, 1024], + ], +) +def test_sdxl_outpainting(device, rect): + sd_steps = check_device(device) + + model = ModelManager( + name="diffusers/stable-diffusion-xl-1.0-inpainting-0.1", + device=torch.device(device), + disable_nsfw=True, + sd_cpu_textencoder=False, + ) + + cfg = get_config( + strategy=HDStrategy.ORIGINAL, + prompt="a dog sitting on a bench in the park", + sd_steps=sd_steps, + use_extender=True, + extender_x=rect[0], + extender_y=rect[1], + extender_width=rect[2], + extender_height=rect[3], + sd_strength=1.0, + sd_guidance_scale=8.0, + sd_sampler=SDSampler.ddim, + ) + + assert_equal( + model, + cfg, + f"sdxl_outpainting_dog_ddim_{'_'.join(map(str, rect))}_device_{device}.png", + img_p=current_dir / "overture-creations-5sI6fQgYIuo.png", + mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png", + fx=1.5, + fy=1.5, + ) diff --git a/py/iopaint/tests/utils.py b/py/iopaint/tests/utils.py new file mode 100644 index 0000000..171b0e8 --- /dev/null +++ b/py/iopaint/tests/utils.py @@ -0,0 +1,77 @@ +from pathlib import Path +import cv2 +import pytest +import torch + +from ..helper import encode_pil_to_base64 +from ..schema import LDMSampler, HDStrategy, InpaintRequest, SDSampler +from PIL import Image + +current_dir = Path(__file__).parent.absolute().resolve() +save_dir = current_dir / "result" +save_dir.mkdir(exist_ok=True, parents=True) + + +def check_device(device: str) -> int: + if device == "cuda" and not torch.cuda.is_available(): + pytest.skip("CUDA is not available, skip test on cuda") + if device == "mps" and not torch.backends.mps.is_available(): + pytest.skip("mps is not available, skip test on mps") + steps = 2 if device == "cpu" else 20 + return steps + + +def assert_equal( + model, + config: InpaintRequest, + gt_name, + fx: float = 1, + fy: float = 1, + img_p=current_dir / "image.png", + mask_p=current_dir / "mask.png", +): + img, mask = get_data(fx=fx, fy=fy, img_p=img_p, mask_p=mask_p) + print(f"Input image shape: {img.shape}") + res = model(img, mask, config) + ok = cv2.imwrite( + str(save_dir / gt_name), + res, + [int(cv2.IMWRITE_JPEG_QUALITY), 100, int(cv2.IMWRITE_PNG_COMPRESSION), 0], + ) + assert ok, save_dir / gt_name + + """ + Note that JPEG is lossy compression, so even if it is the highest quality 100, + when the saved images is reloaded, a difference occurs with the original pixel value. + If you want to save the original images as it is, save it as PNG or BMP. + """ + # gt = cv2.imread(str(current_dir / gt_name), cv2.IMREAD_UNCHANGED) + # assert np.array_equal(res, gt) + + +def get_data( + fx: float = 1, + fy: float = 1.0, + img_p=current_dir / "image.png", + mask_p=current_dir / "mask.png", +): + img = cv2.imread(str(img_p)) + img = cv2.cvtColor(img, cv2.COLOR_BGRA2RGB) + mask = cv2.imread(str(mask_p), cv2.IMREAD_GRAYSCALE) + img = cv2.resize(img, None, fx=fx, fy=fy, interpolation=cv2.INTER_AREA) + mask = cv2.resize(mask, None, fx=fx, fy=fy, interpolation=cv2.INTER_NEAREST) + return img, mask + + +def get_config(**kwargs): + data = dict( + sd_sampler=kwargs.get("sd_sampler", SDSampler.uni_pc), + ldm_steps=1, + ldm_sampler=LDMSampler.plms, + hd_strategy=kwargs.get("strategy", HDStrategy.ORIGINAL), + hd_strategy_crop_margin=32, + hd_strategy_crop_trigger_size=200, + hd_strategy_resize_limit=200, + ) + data.update(**kwargs) + return InpaintRequest(image="", mask="", **data) diff --git a/py/iopaint/web_app/assets/Inter-Black-jiII8dog.woff2 b/py/iopaint/web_app/assets/Inter-Black-jiII8dog.woff2 new file mode 100644 index 0000000..18b35db Binary files /dev/null and b/py/iopaint/web_app/assets/Inter-Black-jiII8dog.woff2 differ diff --git a/py/iopaint/web_app/assets/Inter-BlackItalic-1413vuen.woff2 b/py/iopaint/web_app/assets/Inter-BlackItalic-1413vuen.woff2 new file mode 100644 index 0000000..02c9d8e Binary files /dev/null and b/py/iopaint/web_app/assets/Inter-BlackItalic-1413vuen.woff2 differ diff --git a/py/iopaint/web_app/assets/Inter-Bold-srYz_-1B.woff2 b/py/iopaint/web_app/assets/Inter-Bold-srYz_-1B.woff2 new file mode 100644 index 0000000..0f1b157 Binary files /dev/null and b/py/iopaint/web_app/assets/Inter-Bold-srYz_-1B.woff2 differ diff --git a/py/iopaint/web_app/assets/Inter-BoldItalic-dE_gZyur.woff2 b/py/iopaint/web_app/assets/Inter-BoldItalic-dE_gZyur.woff2 new file mode 100644 index 0000000..bc50f24 Binary files /dev/null and b/py/iopaint/web_app/assets/Inter-BoldItalic-dE_gZyur.woff2 differ diff --git a/py/iopaint/web_app/assets/Inter-ExtraBold-TduDdwUu.woff2 b/py/iopaint/web_app/assets/Inter-ExtraBold-TduDdwUu.woff2 new file mode 100644 index 0000000..b113368 Binary files /dev/null and b/py/iopaint/web_app/assets/Inter-ExtraBold-TduDdwUu.woff2 differ diff --git a/py/iopaint/web_app/assets/Inter-ExtraBoldItalic-BJafRE5I.woff2 b/py/iopaint/web_app/assets/Inter-ExtraBoldItalic-BJafRE5I.woff2 new file mode 100644 index 0000000..a5b76ca Binary files /dev/null and b/py/iopaint/web_app/assets/Inter-ExtraBoldItalic-BJafRE5I.woff2 differ diff --git a/py/iopaint/web_app/assets/Inter-ExtraLight-w5HAp5iF.woff2 b/py/iopaint/web_app/assets/Inter-ExtraLight-w5HAp5iF.woff2 new file mode 100644 index 0000000..1d77ae8 Binary files /dev/null and b/py/iopaint/web_app/assets/Inter-ExtraLight-w5HAp5iF.woff2 differ diff --git a/py/iopaint/web_app/assets/Inter-ExtraLightItalic-ZptecSuc.woff2 b/py/iopaint/web_app/assets/Inter-ExtraLightItalic-ZptecSuc.woff2 new file mode 100644 index 0000000..8c68492 Binary files /dev/null and b/py/iopaint/web_app/assets/Inter-ExtraLightItalic-ZptecSuc.woff2 differ diff --git a/py/iopaint/web_app/assets/Inter-Italic-f6M78thn.woff2 b/py/iopaint/web_app/assets/Inter-Italic-f6M78thn.woff2 new file mode 100644 index 0000000..4c24ce2 Binary files /dev/null and b/py/iopaint/web_app/assets/Inter-Italic-f6M78thn.woff2 differ diff --git a/py/iopaint/web_app/assets/Inter-Light-DFhX0qo-.woff2 b/py/iopaint/web_app/assets/Inter-Light-DFhX0qo-.woff2 new file mode 100644 index 0000000..dbe6143 Binary files /dev/null and b/py/iopaint/web_app/assets/Inter-Light-DFhX0qo-.woff2 differ diff --git a/py/iopaint/web_app/assets/Inter-LightItalic-fu56_DRc.woff2 b/py/iopaint/web_app/assets/Inter-LightItalic-fu56_DRc.woff2 new file mode 100644 index 0000000..a40d042 Binary files /dev/null and b/py/iopaint/web_app/assets/Inter-LightItalic-fu56_DRc.woff2 differ diff --git a/py/iopaint/web_app/assets/Inter-Medium-dDRaJ8tM.woff2 b/py/iopaint/web_app/assets/Inter-Medium-dDRaJ8tM.woff2 new file mode 100644 index 0000000..0fd2ee7 Binary files /dev/null and b/py/iopaint/web_app/assets/Inter-Medium-dDRaJ8tM.woff2 differ diff --git a/py/iopaint/web_app/assets/Inter-MediumItalic-zr3roggP.woff2 b/py/iopaint/web_app/assets/Inter-MediumItalic-zr3roggP.woff2 new file mode 100644 index 0000000..9676715 Binary files /dev/null and b/py/iopaint/web_app/assets/Inter-MediumItalic-zr3roggP.woff2 differ diff --git a/py/iopaint/web_app/assets/Inter-Regular-dEFHw1tF.woff2 b/py/iopaint/web_app/assets/Inter-Regular-dEFHw1tF.woff2 new file mode 100644 index 0000000..b8699af Binary files /dev/null and b/py/iopaint/web_app/assets/Inter-Regular-dEFHw1tF.woff2 differ diff --git a/py/iopaint/web_app/assets/Inter-SemiBold-PyS8DO2L.woff2 b/py/iopaint/web_app/assets/Inter-SemiBold-PyS8DO2L.woff2 new file mode 100644 index 0000000..95c48b1 Binary files /dev/null and b/py/iopaint/web_app/assets/Inter-SemiBold-PyS8DO2L.woff2 differ diff --git a/py/iopaint/web_app/assets/Inter-SemiBoldItalic-uIDb7hsH.woff2 b/py/iopaint/web_app/assets/Inter-SemiBoldItalic-uIDb7hsH.woff2 new file mode 100644 index 0000000..ddfe19e Binary files /dev/null and b/py/iopaint/web_app/assets/Inter-SemiBoldItalic-uIDb7hsH.woff2 differ diff --git a/py/iopaint/web_app/assets/Inter-Thin-eKObIkJC.woff2 b/py/iopaint/web_app/assets/Inter-Thin-eKObIkJC.woff2 new file mode 100644 index 0000000..0790960 Binary files /dev/null and b/py/iopaint/web_app/assets/Inter-Thin-eKObIkJC.woff2 differ diff --git a/py/iopaint/web_app/assets/Inter-ThinItalic-L6uBn3RP.woff2 b/py/iopaint/web_app/assets/Inter-ThinItalic-L6uBn3RP.woff2 new file mode 100644 index 0000000..a7bf213 Binary files /dev/null and b/py/iopaint/web_app/assets/Inter-ThinItalic-L6uBn3RP.woff2 differ diff --git a/py/iopaint/web_app/assets/index-8BlaS7ws.js b/py/iopaint/web_app/assets/index-8BlaS7ws.js new file mode 100644 index 0000000..8ae5b4c --- /dev/null +++ b/py/iopaint/web_app/assets/index-8BlaS7ws.js @@ -0,0 +1,165 @@ +var Nv=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)};var z=(e,t,n)=>(Nv(e,t,"read from private field"),n?n.call(e):t.get(e)),Te=(e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)},ye=(e,t,n,r)=>(Nv(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n);var Ff=(e,t,n,r)=>({set _(o){ye(e,t,o,n)},get _(){return z(e,t,r)}}),tt=(e,t,n)=>(Nv(e,t,"access private method"),n);function SD(e,t){for(var n=0;nr[o]})}}}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 o of document.querySelectorAll('link[rel="modulepreload"]'))r(o);new MutationObserver(o=>{for(const i of o)if(i.type==="childList")for(const s of i.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&r(s)}).observe(document,{childList:!0,subtree:!0});function n(o){const i={};return o.integrity&&(i.integrity=o.integrity),o.referrerPolicy&&(i.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?i.credentials="include":o.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(o){if(o.ep)return;o.ep=!0;const i=n(o);fetch(o.href,i)}})();var Yc=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function lm(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var v$={exports:{}},cm={},y$={exports:{}},it={};/** + * @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 bd=Symbol.for("react.element"),ED=Symbol.for("react.portal"),CD=Symbol.for("react.fragment"),$D=Symbol.for("react.strict_mode"),kD=Symbol.for("react.profiler"),RD=Symbol.for("react.provider"),TD=Symbol.for("react.context"),PD=Symbol.for("react.forward_ref"),AD=Symbol.for("react.suspense"),OD=Symbol.for("react.memo"),MD=Symbol.for("react.lazy"),LS=Symbol.iterator;function ND(e){return e===null||typeof e!="object"?null:(e=LS&&e[LS]||e["@@iterator"],typeof e=="function"?e:null)}var w$={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},x$=Object.assign,b$={};function fc(e,t,n){this.props=e,this.context=t,this.refs=b$,this.updater=n||w$}fc.prototype.isReactComponent={};fc.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")};fc.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function _$(){}_$.prototype=fc.prototype;function ew(e,t,n){this.props=e,this.context=t,this.refs=b$,this.updater=n||w$}var tw=ew.prototype=new _$;tw.constructor=ew;x$(tw,fc.prototype);tw.isPureReactComponent=!0;var FS=Array.isArray,S$=Object.prototype.hasOwnProperty,nw={current:null},E$={key:!0,ref:!0,__self:!0,__source:!0};function C$(e,t,n){var r,o={},i=null,s=null;if(t!=null)for(r in t.ref!==void 0&&(s=t.ref),t.key!==void 0&&(i=""+t.key),t)S$.call(t,r)&&!E$.hasOwnProperty(r)&&(o[r]=t[r]);var l=arguments.length-2;if(l===1)o.children=n;else if(1>>1,ge=K[le];if(0>>1;leo(We,W))Meo(fe,We)?(K[le]=fe,K[Me]=W,le=Me):(K[le]=We,K[Ue]=W,le=Ue);else if(Meo(fe,W))K[le]=fe,K[Me]=W,le=Me;else break e}}return Q}function o(K,Q){var W=K.sortIndex-Q.sortIndex;return W!==0?W:K.id-Q.id}if(typeof performance=="object"&&typeof performance.now=="function"){var i=performance;e.unstable_now=function(){return i.now()}}else{var s=Date,l=s.now();e.unstable_now=function(){return s.now()-l}}var u=[],d=[],h=1,m=null,g=3,y=!1,x=!1,_=!1,C=typeof setTimeout=="function"?setTimeout:null,S=typeof clearTimeout=="function"?clearTimeout:null,b=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function E(K){for(var Q=n(d);Q!==null;){if(Q.callback===null)r(d);else if(Q.startTime<=K)r(d),Q.sortIndex=Q.expirationTime,t(u,Q);else break;Q=n(d)}}function k(K){if(_=!1,E(K),!x)if(n(u)!==null)x=!0,L(P);else{var Q=n(d);Q!==null&&ie(k,Q.startTime-K)}}function P(K,Q){x=!1,_&&(_=!1,S(O),O=-1),y=!0;var W=g;try{for(E(Q),m=n(u);m!==null&&(!(m.expirationTime>Q)||K&&!J());){var le=m.callback;if(typeof le=="function"){m.callback=null,g=m.priorityLevel;var ge=le(m.expirationTime<=Q);Q=e.unstable_now(),typeof ge=="function"?m.callback=ge:m===n(u)&&r(u),E(Q)}else r(u);m=n(u)}if(m!==null)var Ve=!0;else{var Ue=n(d);Ue!==null&&ie(k,Ue.startTime-Q),Ve=!1}return Ve}finally{m=null,g=W,y=!1}}var M=!1,A=null,O=-1,F=5,V=-1;function J(){return!(e.unstable_now()-VK||125le?(K.sortIndex=W,t(d,K),n(u)===null&&K===n(d)&&(_?(S(O),O=-1):_=!0,ie(k,W-le))):(K.sortIndex=ge,t(u,K),x||y||(x=!0,L(P))),K},e.unstable_shouldYield=J,e.unstable_wrapCallback=function(K){var Q=g;return function(){var W=g;g=Q;try{return K.apply(this,arguments)}finally{g=W}}}})(T$);R$.exports=T$;var KD=R$.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 P$=f,yr=KD;function ce(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"),B0=Object.prototype.hasOwnProperty,YD=/^[: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]*$/,zS={},BS={};function GD(e){return B0.call(BS,e)?!0:B0.call(zS,e)?!1:YD.test(e)?BS[e]=!0:(zS[e]=!0,!1)}function XD(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 ZD(e,t,n,r){if(t===null||typeof t>"u"||XD(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 Un(e,t,n,r,o,i,s){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=o,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=i,this.removeEmptyString=s}var wn={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){wn[e]=new Un(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];wn[t]=new Un(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){wn[e]=new Un(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){wn[e]=new Un(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){wn[e]=new Un(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){wn[e]=new Un(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){wn[e]=new Un(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){wn[e]=new Un(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){wn[e]=new Un(e,5,!1,e.toLowerCase(),null,!1,!1)});var ow=/[\-:]([a-z])/g;function iw(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(ow,iw);wn[t]=new Un(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(ow,iw);wn[t]=new Un(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(ow,iw);wn[t]=new Un(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){wn[e]=new Un(e,1,!1,e.toLowerCase(),null,!1,!1)});wn.xlinkHref=new Un("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){wn[e]=new Un(e,1,!1,e.toLowerCase(),null,!0,!0)});function sw(e,t,n,r){var o=wn.hasOwnProperty(t)?wn[t]:null;(o!==null?o.type!==0:r||!(2l||o[s]!==i[l]){var u=` +`+o[s].replace(" at new "," at ");return e.displayName&&u.includes("")&&(u=u.replace("",e.displayName)),u}while(1<=s&&0<=l);break}}}finally{Lv=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?uu(e):""}function qD(e){switch(e.tag){case 5:return uu(e.type);case 16:return uu("Lazy");case 13:return uu("Suspense");case 19:return uu("SuspenseList");case 0:case 2:case 15:return e=Fv(e.type,!1),e;case 11:return e=Fv(e.type.render,!1),e;case 1:return e=Fv(e.type,!0),e;default:return""}}function H0(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 ll:return"Fragment";case al:return"Portal";case U0:return"Profiler";case aw:return"StrictMode";case V0:return"Suspense";case W0:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case M$:return(e.displayName||"Context")+".Consumer";case O$:return(e._context.displayName||"Context")+".Provider";case lw:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case cw:return t=e.displayName||null,t!==null?t:H0(e.type)||"Memo";case Ki:t=e._payload,e=e._init;try{return H0(e(t))}catch{}}return null}function QD(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 H0(t);case 8:return t===aw?"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 Ss(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function D$(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function JD(e){var t=D$(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 o=n.get,i=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return o.call(this)},set:function(s){r=""+s,i.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 Bf(e){e._valueTracker||(e._valueTracker=JD(e))}function I$(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=D$(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function oh(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 K0(e,t){var n=t.checked;return zt({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function VS(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=Ss(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 L$(e,t){t=t.checked,t!=null&&sw(e,"checked",t,!1)}function Y0(e,t){L$(e,t);var n=Ss(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")?G0(e,t.type,n):t.hasOwnProperty("defaultValue")&&G0(e,t.type,Ss(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function WS(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 G0(e,t,n){(t!=="number"||oh(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var du=Array.isArray;function bl(e,t,n,r){if(e=e.options,t){t={};for(var o=0;o"+t.valueOf().toString()+"",t=Uf.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function Ou(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var vu={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},e9=["Webkit","ms","Moz","O"];Object.keys(vu).forEach(function(e){e9.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),vu[t]=vu[e]})});function B$(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||vu.hasOwnProperty(e)&&vu[e]?(""+t).trim():t+"px"}function U$(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,o=B$(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,o):e[n]=o}}var t9=zt({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 q0(e,t){if(t){if(t9[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(ce(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(ce(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(ce(61))}if(t.style!=null&&typeof t.style!="object")throw Error(ce(62))}}function Q0(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 J0=null;function uw(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var ey=null,_l=null,Sl=null;function YS(e){if(e=Ed(e)){if(typeof ey!="function")throw Error(ce(280));var t=e.stateNode;t&&(t=hm(t),ey(e.stateNode,e.type,t))}}function V$(e){_l?Sl?Sl.push(e):Sl=[e]:_l=e}function W$(){if(_l){var e=_l,t=Sl;if(Sl=_l=null,YS(e),t)for(e=0;e>>=0,e===0?32:31-(f9(e)/p9|0)|0}var Vf=64,Wf=4194304;function fu(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 lh(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,o=e.suspendedLanes,i=e.pingedLanes,s=n&268435455;if(s!==0){var l=s&~o;l!==0?r=fu(l):(i&=s,i!==0&&(r=fu(i)))}else s=n&~o,s!==0?r=fu(s):i!==0&&(r=fu(i));if(r===0)return 0;if(t!==0&&t!==r&&!(t&o)&&(o=r&-r,i=t&-t,o>=i||o===16&&(i&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 _d(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-go(t),e[t]=n}function v9(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=wu),nE=" ",rE=!1;function uk(e,t){switch(e){case"keyup":return H9.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function dk(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var cl=!1;function Y9(e,t){switch(e){case"compositionend":return dk(t);case"keypress":return t.which!==32?null:(rE=!0,nE);case"textInput":return e=t.data,e===nE&&rE?null:e;default:return null}}function G9(e,t){if(cl)return e==="compositionend"||!yw&&uk(e,t)?(e=lk(),$p=mw=rs=null,cl=!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=aE(n)}}function mk(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?mk(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function gk(){for(var e=window,t=oh();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=oh(e.document)}return t}function ww(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 rI(e){var t=gk(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&mk(n.ownerDocument.documentElement,n)){if(r!==null&&ww(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 o=n.textContent.length,i=Math.min(r.start,o);r=r.end===void 0?i:Math.min(r.end,o),!e.extend&&i>r&&(o=r,r=i,i=o),o=lE(n,i);var s=lE(n,r);o&&s&&(e.rangeCount!==1||e.anchorNode!==o.node||e.anchorOffset!==o.offset||e.focusNode!==s.node||e.focusOffset!==s.offset)&&(t=t.createRange(),t.setStart(o.node,o.offset),e.removeAllRanges(),i>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,ul=null,sy=null,bu=null,ay=!1;function cE(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;ay||ul==null||ul!==oh(r)||(r=ul,"selectionStart"in r&&ww(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}),bu&&Fu(bu,r)||(bu=r,r=dh(sy,"onSelect"),0pl||(e.current=py[pl],py[pl]=null,pl--)}function $t(e,t){pl++,py[pl]=e.current,e.current=t}var Es={},Tn=Ps(Es),Jn=Ps(!1),ba=Es;function Kl(e,t){var n=e.type.contextTypes;if(!n)return Es;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var o={},i;for(i in n)o[i]=t[i];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=o),o}function er(e){return e=e.childContextTypes,e!=null}function ph(){At(Jn),At(Tn)}function gE(e,t,n){if(Tn.current!==Es)throw Error(ce(168));$t(Tn,t),$t(Jn,n)}function Ck(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var o in r)if(!(o in t))throw Error(ce(108,QD(e)||"Unknown",o));return zt({},n,r)}function hh(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||Es,ba=Tn.current,$t(Tn,e),$t(Jn,Jn.current),!0}function vE(e,t,n){var r=e.stateNode;if(!r)throw Error(ce(169));n?(e=Ck(e,t,ba),r.__reactInternalMemoizedMergedChildContext=e,At(Jn),At(Tn),$t(Tn,e)):At(Jn),$t(Jn,n)}var li=null,mm=!1,Qv=!1;function $k(e){li===null?li=[e]:li.push(e)}function mI(e){mm=!0,$k(e)}function As(){if(!Qv&&li!==null){Qv=!0;var e=0,t=xt;try{var n=li;for(xt=1;e>=s,o-=s,ci=1<<32-go(t)+o|n<O?(F=A,A=null):F=A.sibling;var V=g(S,A,E[O],k);if(V===null){A===null&&(A=F);break}e&&A&&V.alternate===null&&t(S,A),b=i(V,b,O),M===null?P=V:M.sibling=V,M=V,A=F}if(O===E.length)return n(S,A),Dt&&qs(S,O),P;if(A===null){for(;OO?(F=A,A=null):F=A.sibling;var J=g(S,A,V.value,k);if(J===null){A===null&&(A=F);break}e&&A&&J.alternate===null&&t(S,A),b=i(J,b,O),M===null?P=J:M.sibling=J,M=J,A=F}if(V.done)return n(S,A),Dt&&qs(S,O),P;if(A===null){for(;!V.done;O++,V=E.next())V=m(S,V.value,k),V!==null&&(b=i(V,b,O),M===null?P=V:M.sibling=V,M=V);return Dt&&qs(S,O),P}for(A=r(S,A);!V.done;O++,V=E.next())V=y(A,S,O,V.value,k),V!==null&&(e&&V.alternate!==null&&A.delete(V.key===null?O:V.key),b=i(V,b,O),M===null?P=V:M.sibling=V,M=V);return e&&A.forEach(function(G){return t(S,G)}),Dt&&qs(S,O),P}function C(S,b,E,k){if(typeof E=="object"&&E!==null&&E.type===ll&&E.key===null&&(E=E.props.children),typeof E=="object"&&E!==null){switch(E.$$typeof){case zf:e:{for(var P=E.key,M=b;M!==null;){if(M.key===P){if(P=E.type,P===ll){if(M.tag===7){n(S,M.sibling),b=o(M,E.props.children),b.return=S,S=b;break e}}else if(M.elementType===P||typeof P=="object"&&P!==null&&P.$$typeof===Ki&&EE(P)===M.type){n(S,M.sibling),b=o(M,E.props),b.ref=Jc(S,M,E),b.return=S,S=b;break e}n(S,M);break}else t(S,M);M=M.sibling}E.type===ll?(b=xa(E.props.children,S.mode,k,E.key),b.return=S,S=b):(k=Np(E.type,E.key,E.props,null,S.mode,k),k.ref=Jc(S,b,E),k.return=S,S=k)}return s(S);case al:e:{for(M=E.key;b!==null;){if(b.key===M)if(b.tag===4&&b.stateNode.containerInfo===E.containerInfo&&b.stateNode.implementation===E.implementation){n(S,b.sibling),b=o(b,E.children||[]),b.return=S,S=b;break e}else{n(S,b);break}else t(S,b);b=b.sibling}b=s0(E,S.mode,k),b.return=S,S=b}return s(S);case Ki:return M=E._init,C(S,b,M(E._payload),k)}if(du(E))return x(S,b,E,k);if(Gc(E))return _(S,b,E,k);qf(S,E)}return typeof E=="string"&&E!==""||typeof E=="number"?(E=""+E,b!==null&&b.tag===6?(n(S,b.sibling),b=o(b,E),b.return=S,S=b):(n(S,b),b=i0(E,S.mode,k),b.return=S,S=b),s(S)):n(S,b)}return C}var Gl=Nk(!0),Dk=Nk(!1),Cd={},zo=Ps(Cd),Uu=Ps(Cd),Vu=Ps(Cd);function oa(e){if(e===Cd)throw Error(ce(174));return e}function Rw(e,t){switch($t(Vu,t),$t(Uu,e),$t(zo,Cd),e=t.nodeType,e){case 9:case 11:t=(t=t.documentElement)?t.namespaceURI:Z0(null,"");break;default:e=e===8?t.parentNode:t,t=e.namespaceURI||null,e=e.tagName,t=Z0(t,e)}At(zo),$t(zo,t)}function Xl(){At(zo),At(Uu),At(Vu)}function Ik(e){oa(Vu.current);var t=oa(zo.current),n=Z0(t,e.type);t!==n&&($t(Uu,e),$t(zo,n))}function Tw(e){Uu.current===e&&(At(zo),At(Uu))}var Lt=Ps(0);function xh(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 Jv=[];function Pw(){for(var e=0;en?n:4,e(!0);var r=e0.transition;e0.transition={};try{e(!1),t()}finally{xt=n,e0.transition=r}}function Qk(){return Gr().memoizedState}function wI(e,t,n){var r=ys(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},Jk(e))eR(t,n);else if(n=Pk(e,t,n,r),n!==null){var o=jn();vo(n,e,r,o),tR(n,t,r)}}function xI(e,t,n){var r=ys(e),o={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(Jk(e))eR(t,o);else{var i=e.alternate;if(e.lanes===0&&(i===null||i.lanes===0)&&(i=t.lastRenderedReducer,i!==null))try{var s=t.lastRenderedState,l=i(s,n);if(o.hasEagerState=!0,o.eagerState=l,wo(l,s)){var u=t.interleaved;u===null?(o.next=o,$w(t)):(o.next=u.next,u.next=o),t.interleaved=o;return}}catch{}finally{}n=Pk(e,t,o,r),n!==null&&(o=jn(),vo(n,e,r,o),tR(n,t,r))}}function Jk(e){var t=e.alternate;return e===jt||t!==null&&t===jt}function eR(e,t){_u=bh=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function tR(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,fw(e,n)}}var _h={readContext:Yr,useCallback:En,useContext:En,useEffect:En,useImperativeHandle:En,useInsertionEffect:En,useLayoutEffect:En,useMemo:En,useReducer:En,useRef:En,useState:En,useDebugValue:En,useDeferredValue:En,useTransition:En,useMutableSource:En,useSyncExternalStore:En,useId:En,unstable_isNewReconciler:!1},bI={readContext:Yr,useCallback:function(e,t){return ko().memoizedState=[e,t===void 0?null:t],e},useContext:Yr,useEffect:$E,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,Pp(4194308,4,Yk.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Pp(4194308,4,e,t)},useInsertionEffect:function(e,t){return Pp(4,2,e,t)},useMemo:function(e,t){var n=ko();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=ko();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=wI.bind(null,jt,e),[r.memoizedState,e]},useRef:function(e){var t=ko();return e={current:e},t.memoizedState=e},useState:CE,useDebugValue:Dw,useDeferredValue:function(e){return ko().memoizedState=e},useTransition:function(){var e=CE(!1),t=e[0];return e=yI.bind(null,e[1]),ko().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=jt,o=ko();if(Dt){if(n===void 0)throw Error(ce(407));n=n()}else{if(n=t(),dn===null)throw Error(ce(349));Sa&30||jk(r,t,n)}o.memoizedState=n;var i={value:n,getSnapshot:t};return o.queue=i,$E(Bk.bind(null,r,i,e),[e]),r.flags|=2048,Ku(9,zk.bind(null,r,i,n,t),void 0,null),n},useId:function(){var e=ko(),t=dn.identifierPrefix;if(Dt){var n=ui,r=ci;n=(r&~(1<<32-go(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=Wu++,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[Oo]=t,e[Bu]=r,uR(e,t,!1,!1),t.stateNode=e;e:{switch(s=Q0(n,r),n){case"dialog":Tt("cancel",e),Tt("close",e),o=r;break;case"iframe":case"object":case"embed":Tt("load",e),o=r;break;case"video":case"audio":for(o=0;oql&&(t.flags|=128,r=!0,eu(i,!1),t.lanes=4194304)}else{if(!r)if(e=xh(s),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),eu(i,!0),i.tail===null&&i.tailMode==="hidden"&&!s.alternate&&!Dt)return Cn(t),null}else 2*Zt()-i.renderingStartTime>ql&&n!==1073741824&&(t.flags|=128,r=!0,eu(i,!1),t.lanes=4194304);i.isBackwards?(s.sibling=t.child,t.child=s):(n=i.last,n!==null?n.sibling=s:t.child=s,i.last=s)}return i.tail!==null?(t=i.tail,i.rendering=t,i.tail=t.sibling,i.renderingStartTime=Zt(),t.sibling=null,n=Lt.current,$t(Lt,r?n&1|2:n&1),t):(Cn(t),null);case 22:case 23:return Bw(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?fr&1073741824&&(Cn(t),t.subtreeFlags&6&&(t.flags|=8192)):Cn(t),null;case 24:return null;case 25:return null}throw Error(ce(156,t.tag))}function TI(e,t){switch(bw(t),t.tag){case 1:return er(t.type)&&ph(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Xl(),At(Jn),At(Tn),Pw(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return Tw(t),null;case 13:if(At(Lt),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(ce(340));Yl()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return At(Lt),null;case 4:return Xl(),null;case 10:return Cw(t.type._context),null;case 22:case 23:return Bw(),null;case 24:return null;default:return null}}var Jf=!1,kn=!1,PI=typeof WeakSet=="function"?WeakSet:Set,Se=null;function vl(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){Wt(e,t,r)}else n.current=null}function Cy(e,t,n){try{n()}catch(r){Wt(e,t,r)}}var DE=!1;function AI(e,t){if(ly=ch,e=gk(),ww(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 o=r.anchorOffset,i=r.focusNode;r=r.focusOffset;try{n.nodeType,i.nodeType}catch{n=null;break e}var s=0,l=-1,u=-1,d=0,h=0,m=e,g=null;t:for(;;){for(var y;m!==n||o!==0&&m.nodeType!==3||(l=s+o),m!==i||r!==0&&m.nodeType!==3||(u=s+r),m.nodeType===3&&(s+=m.nodeValue.length),(y=m.firstChild)!==null;)g=m,m=y;for(;;){if(m===e)break t;if(g===n&&++d===o&&(l=s),g===i&&++h===r&&(u=s),(y=m.nextSibling)!==null)break;m=g,g=m.parentNode}m=y}n=l===-1||u===-1?null:{start:l,end:u}}else n=null}n=n||{start:0,end:0}}else n=null;for(cy={focusedElem:e,selectionRange:n},ch=!1,Se=t;Se!==null;)if(t=Se,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,Se=e;else for(;Se!==null;){t=Se;try{var x=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(x!==null){var _=x.memoizedProps,C=x.memoizedState,S=t.stateNode,b=S.getSnapshotBeforeUpdate(t.elementType===t.type?_:io(t.type,_),C);S.__reactInternalSnapshotBeforeUpdate=b}break;case 3:var E=t.stateNode.containerInfo;E.nodeType===1?E.textContent="":E.nodeType===9&&E.documentElement&&E.removeChild(E.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(ce(163))}}catch(k){Wt(t,t.return,k)}if(e=t.sibling,e!==null){e.return=t.return,Se=e;break}Se=t.return}return x=DE,DE=!1,x}function Su(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var o=r=r.next;do{if((o.tag&e)===e){var i=o.destroy;o.destroy=void 0,i!==void 0&&Cy(t,n,i)}o=o.next}while(o!==r)}}function ym(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 $y(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 pR(e){var t=e.alternate;t!==null&&(e.alternate=null,pR(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Oo],delete t[Bu],delete t[fy],delete t[pI],delete t[hI])),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 hR(e){return e.tag===5||e.tag===3||e.tag===4}function IE(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||hR(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 ky(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=fh));else if(r!==4&&(e=e.child,e!==null))for(ky(e,t,n),e=e.sibling;e!==null;)ky(e,t,n),e=e.sibling}function Ry(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(Ry(e,t,n),e=e.sibling;e!==null;)Ry(e,t,n),e=e.sibling}var mn=null,lo=!1;function ji(e,t,n){for(n=n.child;n!==null;)mR(e,t,n),n=n.sibling}function mR(e,t,n){if(jo&&typeof jo.onCommitFiberUnmount=="function")try{jo.onCommitFiberUnmount(um,n)}catch{}switch(n.tag){case 5:kn||vl(n,t);case 6:var r=mn,o=lo;mn=null,ji(e,t,n),mn=r,lo=o,mn!==null&&(lo?(e=mn,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):mn.removeChild(n.stateNode));break;case 18:mn!==null&&(lo?(e=mn,n=n.stateNode,e.nodeType===8?qv(e.parentNode,n):e.nodeType===1&&qv(e,n),Iu(e)):qv(mn,n.stateNode));break;case 4:r=mn,o=lo,mn=n.stateNode.containerInfo,lo=!0,ji(e,t,n),mn=r,lo=o;break;case 0:case 11:case 14:case 15:if(!kn&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){o=r=r.next;do{var i=o,s=i.destroy;i=i.tag,s!==void 0&&(i&2||i&4)&&Cy(n,t,s),o=o.next}while(o!==r)}ji(e,t,n);break;case 1:if(!kn&&(vl(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(l){Wt(n,t,l)}ji(e,t,n);break;case 21:ji(e,t,n);break;case 22:n.mode&1?(kn=(r=kn)||n.memoizedState!==null,ji(e,t,n),kn=r):ji(e,t,n);break;default:ji(e,t,n)}}function LE(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new PI),t.forEach(function(r){var o=zI.bind(null,e,r);n.has(r)||(n.add(r),r.then(o,o))})}}function ro(e,t){var n=t.deletions;if(n!==null)for(var r=0;ro&&(o=s),r&=~i}if(r=o,r=Zt()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*MI(r/1960))-r,10e?16:e,os===null)var r=!1;else{if(e=os,os=null,Ch=0,dt&6)throw Error(ce(331));var o=dt;for(dt|=4,Se=e.current;Se!==null;){var i=Se,s=i.child;if(Se.flags&16){var l=i.deletions;if(l!==null){for(var u=0;uZt()-jw?wa(e,0):Fw|=n),tr(e,t)}function SR(e,t){t===0&&(e.mode&1?(t=Wf,Wf<<=1,!(Wf&130023424)&&(Wf=4194304)):t=1);var n=jn();e=gi(e,t),e!==null&&(_d(e,t,n),tr(e,n))}function jI(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),SR(e,n)}function zI(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,o=e.memoizedState;o!==null&&(n=o.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(ce(314))}r!==null&&r.delete(t),SR(e,n)}var ER;ER=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||Jn.current)Qn=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return Qn=!1,kI(e,t,n);Qn=!!(e.flags&131072)}else Qn=!1,Dt&&t.flags&1048576&&kk(t,gh,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;Ap(e,t),e=t.pendingProps;var o=Kl(t,Tn.current);Cl(t,n),o=Ow(null,t,r,e,o,n);var i=Mw();return t.flags|=1,typeof o=="object"&&o!==null&&typeof o.render=="function"&&o.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,er(r)?(i=!0,hh(t)):i=!1,t.memoizedState=o.state!==null&&o.state!==void 0?o.state:null,kw(t),o.updater=gm,t.stateNode=o,o._reactInternals=t,yy(t,r,e,n),t=by(null,t,r,!0,i,n)):(t.tag=0,Dt&&i&&xw(t),Dn(null,t,o,n),t=t.child),t;case 16:r=t.elementType;e:{switch(Ap(e,t),e=t.pendingProps,o=r._init,r=o(r._payload),t.type=r,o=t.tag=UI(r),e=io(r,e),o){case 0:t=xy(null,t,r,e,n);break e;case 1:t=OE(null,t,r,e,n);break e;case 11:t=PE(null,t,r,e,n);break e;case 14:t=AE(null,t,r,io(r.type,e),n);break e}throw Error(ce(306,r,""))}return t;case 0:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),xy(e,t,r,o,n);case 1:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),OE(e,t,r,o,n);case 3:e:{if(aR(t),e===null)throw Error(ce(387));r=t.pendingProps,i=t.memoizedState,o=i.element,Ak(e,t),wh(t,r,null,n);var s=t.memoizedState;if(r=s.element,i.isDehydrated)if(i={element:r,isDehydrated:!1,cache:s.cache,pendingSuspenseBoundaries:s.pendingSuspenseBoundaries,transitions:s.transitions},t.updateQueue.baseState=i,t.memoizedState=i,t.flags&256){o=Zl(Error(ce(423)),t),t=ME(e,t,r,n,o);break e}else if(r!==o){o=Zl(Error(ce(424)),t),t=ME(e,t,r,n,o);break e}else for(mr=ms(t.stateNode.containerInfo.firstChild),gr=t,Dt=!0,po=null,n=Dk(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(Yl(),r===o){t=vi(e,t,n);break e}Dn(e,t,r,n)}t=t.child}return t;case 5:return Ik(t),e===null&&my(t),r=t.type,o=t.pendingProps,i=e!==null?e.memoizedProps:null,s=o.children,uy(r,o)?s=null:i!==null&&uy(r,i)&&(t.flags|=32),sR(e,t),Dn(e,t,s,n),t.child;case 6:return e===null&&my(t),null;case 13:return lR(e,t,n);case 4:return Rw(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=Gl(t,null,r,n):Dn(e,t,r,n),t.child;case 11:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),PE(e,t,r,o,n);case 7:return Dn(e,t,t.pendingProps,n),t.child;case 8:return Dn(e,t,t.pendingProps.children,n),t.child;case 12:return Dn(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,o=t.pendingProps,i=t.memoizedProps,s=o.value,$t(vh,r._currentValue),r._currentValue=s,i!==null)if(wo(i.value,s)){if(i.children===o.children&&!Jn.current){t=vi(e,t,n);break e}}else for(i=t.child,i!==null&&(i.return=t);i!==null;){var l=i.dependencies;if(l!==null){s=i.child;for(var u=l.firstContext;u!==null;){if(u.context===r){if(i.tag===1){u=fi(-1,n&-n),u.tag=2;var d=i.updateQueue;if(d!==null){d=d.shared;var h=d.pending;h===null?u.next=u:(u.next=h.next,h.next=u),d.pending=u}}i.lanes|=n,u=i.alternate,u!==null&&(u.lanes|=n),gy(i.return,n,t),l.lanes|=n;break}u=u.next}}else if(i.tag===10)s=i.type===t.type?null:i.child;else if(i.tag===18){if(s=i.return,s===null)throw Error(ce(341));s.lanes|=n,l=s.alternate,l!==null&&(l.lanes|=n),gy(s,n,t),s=i.sibling}else s=i.child;if(s!==null)s.return=i;else for(s=i;s!==null;){if(s===t){s=null;break}if(i=s.sibling,i!==null){i.return=s.return,s=i;break}s=s.return}i=s}Dn(e,t,o.children,n),t=t.child}return t;case 9:return o=t.type,r=t.pendingProps.children,Cl(t,n),o=Yr(o),r=r(o),t.flags|=1,Dn(e,t,r,n),t.child;case 14:return r=t.type,o=io(r,t.pendingProps),o=io(r.type,o),AE(e,t,r,o,n);case 15:return oR(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),Ap(e,t),t.tag=1,er(r)?(e=!0,hh(t)):e=!1,Cl(t,n),Mk(t,r,o),yy(t,r,o,n),by(null,t,r,!0,e,n);case 19:return cR(e,t,n);case 22:return iR(e,t,n)}throw Error(ce(156,t.tag))};function CR(e,t){return q$(e,t)}function BI(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 Ur(e,t,n,r){return new BI(e,t,n,r)}function Vw(e){return e=e.prototype,!(!e||!e.isReactComponent)}function UI(e){if(typeof e=="function")return Vw(e)?1:0;if(e!=null){if(e=e.$$typeof,e===lw)return 11;if(e===cw)return 14}return 2}function ws(e,t){var n=e.alternate;return n===null?(n=Ur(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 Np(e,t,n,r,o,i){var s=2;if(r=e,typeof e=="function")Vw(e)&&(s=1);else if(typeof e=="string")s=5;else e:switch(e){case ll:return xa(n.children,o,i,t);case aw:s=8,o|=8;break;case U0:return e=Ur(12,n,t,o|2),e.elementType=U0,e.lanes=i,e;case V0:return e=Ur(13,n,t,o),e.elementType=V0,e.lanes=i,e;case W0:return e=Ur(19,n,t,o),e.elementType=W0,e.lanes=i,e;case N$:return xm(n,o,i,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case O$:s=10;break e;case M$:s=9;break e;case lw:s=11;break e;case cw:s=14;break e;case Ki:s=16,r=null;break e}throw Error(ce(130,e==null?e:typeof e,""))}return t=Ur(s,n,t,o),t.elementType=e,t.type=r,t.lanes=i,t}function xa(e,t,n,r){return e=Ur(7,e,r,t),e.lanes=n,e}function xm(e,t,n,r){return e=Ur(22,e,r,t),e.elementType=N$,e.lanes=n,e.stateNode={isHidden:!1},e}function i0(e,t,n){return e=Ur(6,e,null,t),e.lanes=n,e}function s0(e,t,n){return t=Ur(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function VI(e,t,n,r,o){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=zv(0),this.expirationTimes=zv(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=zv(0),this.identifierPrefix=r,this.onRecoverableError=o,this.mutableSourceEagerHydrationData=null}function Ww(e,t,n,r,o,i,s,l,u){return e=new VI(e,t,n,l,u),t===1?(t=1,i===!0&&(t|=8)):t=0,i=Ur(3,null,null,t),e.current=i,i.stateNode=e,i.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},kw(i),e}function WI(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(TR)}catch(e){console.error(e)}}TR(),k$.exports=br;var Os=k$.exports;const XI=lm(Os);var HE=Os;z0.createRoot=HE.createRoot,z0.hydrateRoot=HE.hydrateRoot;var $d=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},Ql=typeof window>"u"||"Deno"in window;function Lr(){}function ZI(e,t){return typeof e=="function"?e(t):e}function My(e){return typeof e=="number"&&e>=0&&e!==1/0}function PR(e,t){return Math.max(e+(t||0)-Date.now(),0)}function KE(e,t){const{type:n="all",exact:r,fetchStatus:o,predicate:i,queryKey:s,stale:l}=e;if(s){if(r){if(t.queryHash!==Gw(s,t.options))return!1}else if(!Xu(t.queryKey,s))return!1}if(n!=="all"){const u=t.isActive();if(n==="active"&&!u||n==="inactive"&&u)return!1}return!(typeof l=="boolean"&&t.isStale()!==l||typeof o<"u"&&o!==t.state.fetchStatus||i&&!i(t))}function YE(e,t){const{exact:n,status:r,predicate:o,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(Gu(t.options.mutationKey)!==Gu(i))return!1}else if(!Xu(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||o&&!o(t))}function Gw(e,t){return((t==null?void 0:t.queryKeyHashFn)||Gu)(e)}function Gu(e){return JSON.stringify(e,(t,n)=>Dy(n)?Object.keys(n).sort().reduce((r,o)=>(r[o]=n[o],r),{}):n)}function Xu(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?!Object.keys(t).some(n=>!Xu(e[n],t[n])):!1}function AR(e,t){if(e===t)return e;const n=GE(e)&&GE(t);if(n||Dy(e)&&Dy(t)){const r=n?e.length:Object.keys(e).length,o=n?t:Object.keys(t),i=o.length,s=n?[]:{};let l=0;for(let u=0;u"u")return!0;const n=t.prototype;return!(!XE(n)||!n.hasOwnProperty("isPrototypeOf"))}function XE(e){return Object.prototype.toString.call(e)==="[object Object]"}function OR(e){return new Promise(t=>{setTimeout(t,e)})}function ZE(e){OR(0).then(e)}function Iy(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?AR(e,t):t}function qI(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function QI(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var ua,Zi,Pl,l$,JI=(l$=class extends $d{constructor(){super();Te(this,ua,void 0);Te(this,Zi,void 0);Te(this,Pl,void 0);ye(this,Pl,t=>{if(!Ql&&window.addEventListener){const n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){z(this,Zi)||this.setEventListener(z(this,Pl))}onUnsubscribe(){var t;this.hasListeners()||((t=z(this,Zi))==null||t.call(this),ye(this,Zi,void 0))}setEventListener(t){var n;ye(this,Pl,t),(n=z(this,Zi))==null||n.call(this),ye(this,Zi,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){z(this,ua)!==t&&(ye(this,ua,t),this.onFocus())}onFocus(){this.listeners.forEach(t=>{t()})}isFocused(){var t;return typeof z(this,ua)=="boolean"?z(this,ua):((t=globalThis.document)==null?void 0:t.visibilityState)!=="hidden"}},ua=new WeakMap,Zi=new WeakMap,Pl=new WeakMap,l$),Rh=new JI,Al,qi,Ol,c$,eL=(c$=class extends $d{constructor(){super();Te(this,Al,!0);Te(this,qi,void 0);Te(this,Ol,void 0);ye(this,Ol,t=>{if(!Ql&&window.addEventListener){const n=()=>t(!0),r=()=>t(!1);return window.addEventListener("online",n,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",r)}}})}onSubscribe(){z(this,qi)||this.setEventListener(z(this,Ol))}onUnsubscribe(){var t;this.hasListeners()||((t=z(this,qi))==null||t.call(this),ye(this,qi,void 0))}setEventListener(t){var n;ye(this,Ol,t),(n=z(this,qi))==null||n.call(this),ye(this,qi,t(this.setOnline.bind(this)))}setOnline(t){z(this,Al)!==t&&(ye(this,Al,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return z(this,Al)}},Al=new WeakMap,qi=new WeakMap,Ol=new WeakMap,c$),Th=new eL;function tL(e){return Math.min(1e3*2**e,3e4)}function Cm(e){return(e??"online")==="online"?Th.isOnline():!0}var MR=class{constructor(e){this.revert=e==null?void 0:e.revert,this.silent=e==null?void 0:e.silent}};function a0(e){return e instanceof MR}function NR(e){let t=!1,n=0,r=!1,o,i,s;const l=new Promise((C,S)=>{i=C,s=S}),u=C=>{var S;r||(y(new MR(C)),(S=e.abort)==null||S.call(e))},d=()=>{t=!0},h=()=>{t=!1},m=()=>!Rh.isFocused()||e.networkMode!=="always"&&!Th.isOnline(),g=C=>{var S;r||(r=!0,(S=e.onSuccess)==null||S.call(e,C),o==null||o(),i(C))},y=C=>{var S;r||(r=!0,(S=e.onError)==null||S.call(e,C),o==null||o(),s(C))},x=()=>new Promise(C=>{var S;o=b=>{const E=r||!m();return E&&C(b),E},(S=e.onPause)==null||S.call(e)}).then(()=>{var C;o=void 0,r||(C=e.onContinue)==null||C.call(e)}),_=()=>{if(r)return;let C;try{C=e.fn()}catch(S){C=Promise.reject(S)}Promise.resolve(C).then(g).catch(S=>{var M;if(r)return;const b=e.retry??(Ql?0:3),E=e.retryDelay??tL,k=typeof E=="function"?E(n,S):E,P=b===!0||typeof b=="number"&&n{if(m())return x()}).then(()=>{t?y(S):_()})})};return Cm(e.networkMode)?_():x().then(_),{promise:l,cancel:u,continue:()=>(o==null?void 0:o())?l:Promise.resolve(),cancelRetry:d,continueRetry:h}}function nL(){let e=[],t=0,n=h=>{h()},r=h=>{h()};const o=h=>{let m;t++;try{m=h()}finally{t--,t||l()}return m},i=h=>{t?e.push(h):ZE(()=>{n(h)})},s=h=>(...m)=>{i(()=>{h(...m)})},l=()=>{const h=e;e=[],h.length&&ZE(()=>{r(()=>{h.forEach(m=>{n(m)})})})};return{batch:o,batchCalls:s,schedule:i,setNotifyFunction:h=>{n=h},setBatchNotifyFunction:h=>{r=h}}}var gn=nL(),da,u$,DR=(u$=class{constructor(){Te(this,da,void 0)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),My(this.gcTime)&&ye(this,da,setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Ql?1/0:5*60*1e3))}clearGcTimeout(){z(this,da)&&(clearTimeout(z(this,da)),ye(this,da,void 0))}},da=new WeakMap,u$),Ml,Nl,Nr,Qi,Dr,cn,ud,fa,Dl,Dp,ao,ii,d$,rL=(d$=class extends DR{constructor(t){super();Te(this,Dl);Te(this,ao);Te(this,Ml,void 0);Te(this,Nl,void 0);Te(this,Nr,void 0);Te(this,Qi,void 0);Te(this,Dr,void 0);Te(this,cn,void 0);Te(this,ud,void 0);Te(this,fa,void 0);ye(this,fa,!1),ye(this,ud,t.defaultOptions),tt(this,Dl,Dp).call(this,t.options),ye(this,cn,[]),ye(this,Nr,t.cache),this.queryKey=t.queryKey,this.queryHash=t.queryHash,ye(this,Ml,t.state||oL(this.options)),this.state=z(this,Ml),this.scheduleGc()}get meta(){return this.options.meta}optionalRemove(){!z(this,cn).length&&this.state.fetchStatus==="idle"&&z(this,Nr).remove(this)}setData(t,n){const r=Iy(this.state.data,t,this.options);return tt(this,ao,ii).call(this,{data:r,type:"success",dataUpdatedAt:n==null?void 0:n.updatedAt,manual:n==null?void 0:n.manual}),r}setState(t,n){tt(this,ao,ii).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){var r;const n=z(this,Qi);return(r=z(this,Dr))==null||r.cancel(t),n?n.then(Lr).catch(Lr):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(z(this,Ml))}isActive(){return z(this,cn).some(t=>t.options.enabled!==!1)}isDisabled(){return this.getObserversCount()>0&&!this.isActive()}isStale(){return this.state.isInvalidated||!this.state.dataUpdatedAt||z(this,cn).some(t=>t.getCurrentResult().isStale)}isStaleByTime(t=0){return this.state.isInvalidated||!this.state.dataUpdatedAt||!PR(this.state.dataUpdatedAt,t)}onFocus(){var n;const t=z(this,cn).find(r=>r.shouldFetchOnWindowFocus());t==null||t.refetch({cancelRefetch:!1}),(n=z(this,Dr))==null||n.continue()}onOnline(){var n;const t=z(this,cn).find(r=>r.shouldFetchOnReconnect());t==null||t.refetch({cancelRefetch:!1}),(n=z(this,Dr))==null||n.continue()}addObserver(t){z(this,cn).includes(t)||(z(this,cn).push(t),this.clearGcTimeout(),z(this,Nr).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){z(this,cn).includes(t)&&(ye(this,cn,z(this,cn).filter(n=>n!==t)),z(this,cn).length||(z(this,Dr)&&(z(this,fa)?z(this,Dr).cancel({revert:!0}):z(this,Dr).cancelRetry()),this.scheduleGc()),z(this,Nr).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return z(this,cn).length}invalidate(){this.state.isInvalidated||tt(this,ao,ii).call(this,{type:"invalidate"})}fetch(t,n){var d,h,m,g;if(this.state.fetchStatus!=="idle"){if(this.state.dataUpdatedAt&&(n!=null&&n.cancelRefetch))this.cancel({silent:!0});else if(z(this,Qi))return(d=z(this,Dr))==null||d.continueRetry(),z(this,Qi)}if(t&&tt(this,Dl,Dp).call(this,t),!this.options.queryFn){const y=z(this,cn).find(x=>x.options.queryFn);y&&tt(this,Dl,Dp).call(this,y.options)}const r=new AbortController,o={queryKey:this.queryKey,meta:this.meta},i=y=>{Object.defineProperty(y,"signal",{enumerable:!0,get:()=>(ye(this,fa,!0),r.signal)})};i(o);const s=()=>this.options.queryFn?(ye(this,fa,!1),this.options.persister?this.options.persister(this.options.queryFn,o,this):this.options.queryFn(o)):Promise.reject(new Error(`Missing queryFn: '${this.options.queryHash}'`)),l={fetchOptions:n,options:this.options,queryKey:this.queryKey,state:this.state,fetchFn:s};i(l),(h=this.options.behavior)==null||h.onFetch(l,this),ye(this,Nl,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((m=l.fetchOptions)==null?void 0:m.meta))&&tt(this,ao,ii).call(this,{type:"fetch",meta:(g=l.fetchOptions)==null?void 0:g.meta});const u=y=>{var x,_,C,S;a0(y)&&y.silent||tt(this,ao,ii).call(this,{type:"error",error:y}),a0(y)||((_=(x=z(this,Nr).config).onError)==null||_.call(x,y,this),(S=(C=z(this,Nr).config).onSettled)==null||S.call(C,this.state.data,y,this)),this.isFetchingOptimistic||this.scheduleGc(),this.isFetchingOptimistic=!1};return ye(this,Dr,NR({fn:l.fetchFn,abort:r.abort.bind(r),onSuccess:y=>{var x,_,C,S;if(typeof y>"u"){u(new Error(`${this.queryHash} data is undefined`));return}this.setData(y),(_=(x=z(this,Nr).config).onSuccess)==null||_.call(x,y,this),(S=(C=z(this,Nr).config).onSettled)==null||S.call(C,y,this.state.error,this),this.isFetchingOptimistic||this.scheduleGc(),this.isFetchingOptimistic=!1},onError:u,onFail:(y,x)=>{tt(this,ao,ii).call(this,{type:"failed",failureCount:y,error:x})},onPause:()=>{tt(this,ao,ii).call(this,{type:"pause"})},onContinue:()=>{tt(this,ao,ii).call(this,{type:"continue"})},retry:l.options.retry,retryDelay:l.options.retryDelay,networkMode:l.options.networkMode})),ye(this,Qi,z(this,Dr).promise),z(this,Qi)}},Ml=new WeakMap,Nl=new WeakMap,Nr=new WeakMap,Qi=new WeakMap,Dr=new WeakMap,cn=new WeakMap,ud=new WeakMap,fa=new WeakMap,Dl=new WeakSet,Dp=function(t){this.options={...z(this,ud),...t},this.updateGcTime(this.options.gcTime)},ao=new WeakSet,ii=function(t){const n=r=>{switch(t.type){case"failed":return{...r,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...r,fetchStatus:"paused"};case"continue":return{...r,fetchStatus:"fetching"};case"fetch":return{...r,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:t.meta??null,fetchStatus:Cm(this.options.networkMode)?"fetching":"paused",...!r.dataUpdatedAt&&{error:null,status:"pending"}};case"success":return{...r,data:t.data,dataUpdateCount:r.dataUpdateCount+1,dataUpdatedAt:t.dataUpdatedAt??Date.now(),error:null,isInvalidated:!1,status:"success",...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};case"error":const o=t.error;return a0(o)&&o.revert&&z(this,Nl)?{...z(this,Nl),fetchStatus:"idle"}:{...r,error:o,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:o,fetchStatus:"idle",status:"error"};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...t.state}}};this.state=n(this.state),gn.batch(()=>{z(this,cn).forEach(r=>{r.onQueryUpdate()}),z(this,Nr).notify({query:this,type:"updated",action:t})})},d$);function oL(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=typeof t<"u",r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var Ro,f$,iL=(f$=class extends $d{constructor(t={}){super();Te(this,Ro,void 0);this.config=t,ye(this,Ro,new Map)}build(t,n,r){const o=n.queryKey,i=n.queryHash??Gw(o,n);let s=this.get(i);return s||(s=new rL({cache:this,queryKey:o,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(o)}),this.add(s)),s}add(t){z(this,Ro).has(t.queryHash)||(z(this,Ro).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){const n=z(this,Ro).get(t.queryHash);n&&(t.destroy(),n===t&&z(this,Ro).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){gn.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return z(this,Ro).get(t)}getAll(){return[...z(this,Ro).values()]}find(t){const n={exact:!0,...t};return this.getAll().find(r=>KE(n,r))}findAll(t={}){const n=this.getAll();return Object.keys(t).length>0?n.filter(r=>KE(t,r)):n}notify(t){gn.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){gn.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){gn.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},Ro=new WeakMap,f$),To,dd,dr,Il,Po,Wi,p$,sL=(p$=class extends DR{constructor(t){super();Te(this,Po);Te(this,To,void 0);Te(this,dd,void 0);Te(this,dr,void 0);Te(this,Il,void 0);this.mutationId=t.mutationId,ye(this,dd,t.defaultOptions),ye(this,dr,t.mutationCache),ye(this,To,[]),this.state=t.state||aL(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options={...z(this,dd),...t},this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){z(this,To).includes(t)||(z(this,To).push(t),this.clearGcTimeout(),z(this,dr).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){ye(this,To,z(this,To).filter(n=>n!==t)),this.scheduleGc(),z(this,dr).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){z(this,To).length||(this.state.status==="pending"?this.scheduleGc():z(this,dr).remove(this))}continue(){var t;return((t=z(this,Il))==null?void 0:t.continue())??this.execute(this.state.variables)}async execute(t){var o,i,s,l,u,d,h,m,g,y,x,_,C,S,b,E,k,P,M,A;const n=()=>(ye(this,Il,NR({fn:()=>this.options.mutationFn?this.options.mutationFn(t):Promise.reject(new Error("No mutationFn found")),onFail:(O,F)=>{tt(this,Po,Wi).call(this,{type:"failed",failureCount:O,error:F})},onPause:()=>{tt(this,Po,Wi).call(this,{type:"pause"})},onContinue:()=>{tt(this,Po,Wi).call(this,{type:"continue"})},retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode})),z(this,Il).promise),r=this.state.status==="pending";try{if(!r){tt(this,Po,Wi).call(this,{type:"pending",variables:t}),await((i=(o=z(this,dr).config).onMutate)==null?void 0:i.call(o,t,this));const F=await((l=(s=this.options).onMutate)==null?void 0:l.call(s,t));F!==this.state.context&&tt(this,Po,Wi).call(this,{type:"pending",context:F,variables:t})}const O=await n();return await((d=(u=z(this,dr).config).onSuccess)==null?void 0:d.call(u,O,t,this.state.context,this)),await((m=(h=this.options).onSuccess)==null?void 0:m.call(h,O,t,this.state.context)),await((y=(g=z(this,dr).config).onSettled)==null?void 0:y.call(g,O,null,this.state.variables,this.state.context,this)),await((_=(x=this.options).onSettled)==null?void 0:_.call(x,O,null,t,this.state.context)),tt(this,Po,Wi).call(this,{type:"success",data:O}),O}catch(O){try{throw await((S=(C=z(this,dr).config).onError)==null?void 0:S.call(C,O,t,this.state.context,this)),await((E=(b=this.options).onError)==null?void 0:E.call(b,O,t,this.state.context)),await((P=(k=z(this,dr).config).onSettled)==null?void 0:P.call(k,void 0,O,this.state.variables,this.state.context,this)),await((A=(M=this.options).onSettled)==null?void 0:A.call(M,void 0,O,t,this.state.context)),O}finally{tt(this,Po,Wi).call(this,{type:"error",error:O})}}}},To=new WeakMap,dd=new WeakMap,dr=new WeakMap,Il=new WeakMap,Po=new WeakSet,Wi=function(t){const n=r=>{switch(t.type){case"failed":return{...r,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};case"pending":return{...r,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:!Cm(this.options.networkMode),status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...r,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:t.error,failureCount:r.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}};this.state=n(this.state),gn.batch(()=>{z(this,To).forEach(r=>{r.onMutationUpdate(t)}),z(this,dr).notify({mutation:this,type:"updated",action:t})})},p$);function aL(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Ir,fd,pa,h$,lL=(h$=class extends $d{constructor(t={}){super();Te(this,Ir,void 0);Te(this,fd,void 0);Te(this,pa,void 0);this.config=t,ye(this,Ir,[]),ye(this,fd,0)}build(t,n,r){const o=new sL({mutationCache:this,mutationId:++Ff(this,fd)._,options:t.defaultMutationOptions(n),state:r});return this.add(o),o}add(t){z(this,Ir).push(t),this.notify({type:"added",mutation:t})}remove(t){ye(this,Ir,z(this,Ir).filter(n=>n!==t)),this.notify({type:"removed",mutation:t})}clear(){gn.batch(()=>{z(this,Ir).forEach(t=>{this.remove(t)})})}getAll(){return z(this,Ir)}find(t){const n={exact:!0,...t};return z(this,Ir).find(r=>YE(n,r))}findAll(t={}){return z(this,Ir).filter(n=>YE(t,n))}notify(t){gn.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){return ye(this,pa,(z(this,pa)??Promise.resolve()).then(()=>{const t=z(this,Ir).filter(n=>n.state.isPaused);return gn.batch(()=>t.reduce((n,r)=>n.then(()=>r.continue().catch(Lr)),Promise.resolve()))}).then(()=>{ye(this,pa,void 0)})),z(this,pa)}},Ir=new WeakMap,fd=new WeakMap,pa=new WeakMap,h$);function cL(e){return{onFetch:(t,n)=>{const r=async()=>{var x,_,C,S,b;const o=t.options,i=(C=(_=(x=t.fetchOptions)==null?void 0:x.meta)==null?void 0:_.fetchMore)==null?void 0:C.direction,s=((S=t.state.data)==null?void 0:S.pages)||[],l=((b=t.state.data)==null?void 0:b.pageParams)||[],u={pages:[],pageParams:[]};let d=!1;const h=E=>{Object.defineProperty(E,"signal",{enumerable:!0,get:()=>(t.signal.aborted?d=!0:t.signal.addEventListener("abort",()=>{d=!0}),t.signal)})},m=t.options.queryFn||(()=>Promise.reject(new Error(`Missing queryFn: '${t.options.queryHash}'`))),g=async(E,k,P)=>{if(d)return Promise.reject();if(k==null&&E.pages.length)return Promise.resolve(E);const M={queryKey:t.queryKey,pageParam:k,direction:P?"backward":"forward",meta:t.options.meta};h(M);const A=await m(M),{maxPages:O}=t.options,F=P?QI:qI;return{pages:F(E.pages,A,O),pageParams:F(E.pageParams,k,O)}};let y;if(i&&s.length){const E=i==="backward",k=E?uL:qE,P={pages:s,pageParams:l},M=k(o,P);y=await g(P,M,E)}else{y=await g(u,l[0]??o.initialPageParam);const E=e??s.length;for(let k=1;k{var o,i;return(i=(o=t.options).persister)==null?void 0:i.call(o,r,{queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n)}:t.fetchFn=r}}}function qE(e,{pages:t,pageParams:n}){const r=t.length-1;return e.getNextPageParam(t[r],t,n[r],n)}function uL(e,{pages:t,pageParams:n}){var r;return(r=e.getPreviousPageParam)==null?void 0:r.call(e,t[0],t,n[0],n)}var nn,Ji,es,Ll,Fl,ts,jl,zl,m$,dL=(m$=class{constructor(e={}){Te(this,nn,void 0);Te(this,Ji,void 0);Te(this,es,void 0);Te(this,Ll,void 0);Te(this,Fl,void 0);Te(this,ts,void 0);Te(this,jl,void 0);Te(this,zl,void 0);ye(this,nn,e.queryCache||new iL),ye(this,Ji,e.mutationCache||new lL),ye(this,es,e.defaultOptions||{}),ye(this,Ll,new Map),ye(this,Fl,new Map),ye(this,ts,0)}mount(){Ff(this,ts)._++,z(this,ts)===1&&(ye(this,jl,Rh.subscribe(()=>{Rh.isFocused()&&(this.resumePausedMutations(),z(this,nn).onFocus())})),ye(this,zl,Th.subscribe(()=>{Th.isOnline()&&(this.resumePausedMutations(),z(this,nn).onOnline())})))}unmount(){var e,t;Ff(this,ts)._--,z(this,ts)===0&&((e=z(this,jl))==null||e.call(this),ye(this,jl,void 0),(t=z(this,zl))==null||t.call(this),ye(this,zl,void 0))}isFetching(e){return z(this,nn).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return z(this,Ji).findAll({...e,status:"pending"}).length}getQueryData(e){var t;return(t=z(this,nn).find({queryKey:e}))==null?void 0:t.state.data}ensureQueryData(e){const t=this.getQueryData(e.queryKey);return t!==void 0?Promise.resolve(t):this.fetchQuery(e)}getQueriesData(e){return this.getQueryCache().findAll(e).map(({queryKey:t,state:n})=>{const r=n.data;return[t,r]})}setQueryData(e,t,n){const r=z(this,nn).find({queryKey:e}),o=r==null?void 0:r.state.data,i=ZI(t,o);if(typeof i>"u")return;const s=this.defaultQueryOptions({queryKey:e});return z(this,nn).build(this,s).setData(i,{...n,manual:!0})}setQueriesData(e,t,n){return gn.batch(()=>this.getQueryCache().findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){var t;return(t=z(this,nn).find({queryKey:e}))==null?void 0:t.state}removeQueries(e){const t=z(this,nn);gn.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=z(this,nn),r={type:"active",...e};return gn.batch(()=>(n.findAll(e).forEach(o=>{o.reset()}),this.refetchQueries(r,t)))}cancelQueries(e={},t={}){const n={revert:!0,...t},r=gn.batch(()=>z(this,nn).findAll(e).map(o=>o.cancel(n)));return Promise.all(r).then(Lr).catch(Lr)}invalidateQueries(e={},t={}){return gn.batch(()=>{if(z(this,nn).findAll(e).forEach(r=>{r.invalidate()}),e.refetchType==="none")return Promise.resolve();const n={...e,type:e.refetchType??e.type??"active"};return this.refetchQueries(n,t)})}refetchQueries(e={},t){const n={...t,cancelRefetch:(t==null?void 0:t.cancelRefetch)??!0},r=gn.batch(()=>z(this,nn).findAll(e).filter(o=>!o.isDisabled()).map(o=>{let i=o.fetch(void 0,n);return n.throwOnError||(i=i.catch(Lr)),o.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(Lr)}fetchQuery(e){const t=this.defaultQueryOptions(e);typeof t.retry>"u"&&(t.retry=!1);const n=z(this,nn).build(this,t);return n.isStaleByTime(t.staleTime)?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Lr).catch(Lr)}fetchInfiniteQuery(e){return e.behavior=cL(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Lr).catch(Lr)}resumePausedMutations(){return z(this,Ji).resumePausedMutations()}getQueryCache(){return z(this,nn)}getMutationCache(){return z(this,Ji)}getDefaultOptions(){return z(this,es)}setDefaultOptions(e){ye(this,es,e)}setQueryDefaults(e,t){z(this,Ll).set(Gu(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...z(this,Ll).values()];let n={};return t.forEach(r=>{Xu(e,r.queryKey)&&(n={...n,...r.defaultOptions})}),n}setMutationDefaults(e,t){z(this,Fl).set(Gu(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...z(this,Fl).values()];let n={};return t.forEach(r=>{Xu(e,r.mutationKey)&&(n={...n,...r.defaultOptions})}),n}defaultQueryOptions(e){if(e!=null&&e._defaulted)return e;const t={...z(this,es).queries,...(e==null?void 0:e.queryKey)&&this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Gw(t.queryKey,t)),typeof t.refetchOnReconnect>"u"&&(t.refetchOnReconnect=t.networkMode!=="always"),typeof t.throwOnError>"u"&&(t.throwOnError=!!t.suspense),typeof t.networkMode>"u"&&t.persister&&(t.networkMode="offlineFirst"),t}defaultMutationOptions(e){return e!=null&&e._defaulted?e:{...z(this,es).mutations,...(e==null?void 0:e.mutationKey)&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){z(this,nn).clear(),z(this,Ji).clear()}},nn=new WeakMap,Ji=new WeakMap,es=new WeakMap,Ll=new WeakMap,Fl=new WeakMap,ts=new WeakMap,jl=new WeakMap,zl=new WeakMap,m$),Xn,Ct,Bl,$n,ha,Ul,Ao,pd,Vl,Wl,ma,ga,ns,va,ya,hu,hd,Ly,md,Fy,gd,jy,vd,zy,yd,By,wd,Uy,xd,Vy,am,IR,g$,fL=(g$=class extends $d{constructor(t,n){super();Te(this,ya);Te(this,hd);Te(this,md);Te(this,gd);Te(this,vd);Te(this,yd);Te(this,wd);Te(this,xd);Te(this,am);Te(this,Xn,void 0);Te(this,Ct,void 0);Te(this,Bl,void 0);Te(this,$n,void 0);Te(this,ha,void 0);Te(this,Ul,void 0);Te(this,Ao,void 0);Te(this,pd,void 0);Te(this,Vl,void 0);Te(this,Wl,void 0);Te(this,ma,void 0);Te(this,ga,void 0);Te(this,ns,void 0);Te(this,va,void 0);ye(this,Ct,void 0),ye(this,Bl,void 0),ye(this,$n,void 0),ye(this,va,new Set),ye(this,Xn,t),this.options=n,ye(this,Ao,null),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(z(this,Ct).addObserver(this),QE(z(this,Ct),this.options)?tt(this,ya,hu).call(this):this.updateResult(),tt(this,vd,zy).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Wy(z(this,Ct),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Wy(z(this,Ct),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,tt(this,yd,By).call(this),tt(this,wd,Uy).call(this),z(this,Ct).removeObserver(this)}setOptions(t,n){const r=this.options,o=z(this,Ct);if(this.options=z(this,Xn).defaultQueryOptions(t),Ny(r,this.options)||z(this,Xn).getQueryCache().notify({type:"observerOptionsUpdated",query:z(this,Ct),observer:this}),typeof this.options.enabled<"u"&&typeof this.options.enabled!="boolean")throw new Error("Expected enabled to be a boolean");this.options.queryKey||(this.options.queryKey=r.queryKey),tt(this,xd,Vy).call(this);const i=this.hasListeners();i&&JE(z(this,Ct),o,this.options,r)&&tt(this,ya,hu).call(this),this.updateResult(n),i&&(z(this,Ct)!==o||this.options.enabled!==r.enabled||this.options.staleTime!==r.staleTime)&&tt(this,hd,Ly).call(this);const s=tt(this,md,Fy).call(this);i&&(z(this,Ct)!==o||this.options.enabled!==r.enabled||s!==z(this,ns))&&tt(this,gd,jy).call(this,s)}getOptimisticResult(t){const n=z(this,Xn).getQueryCache().build(z(this,Xn),t),r=this.createResult(n,t);return hL(this,r)&&(ye(this,$n,r),ye(this,Ul,this.options),ye(this,ha,z(this,Ct).state)),r}getCurrentResult(){return z(this,$n)}trackResult(t){const n={};return Object.keys(t).forEach(r=>{Object.defineProperty(n,r,{configurable:!1,enumerable:!0,get:()=>(z(this,va).add(r),t[r])})}),n}getCurrentQuery(){return z(this,Ct)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){const n=z(this,Xn).defaultQueryOptions(t),r=z(this,Xn).getQueryCache().build(z(this,Xn),n);return r.isFetchingOptimistic=!0,r.fetch().then(()=>this.createResult(r,n))}fetch(t){return tt(this,ya,hu).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),z(this,$n)))}createResult(t,n){var M;const r=z(this,Ct),o=this.options,i=z(this,$n),s=z(this,ha),l=z(this,Ul),d=t!==r?t.state:z(this,Bl),{state:h}=t;let{error:m,errorUpdatedAt:g,fetchStatus:y,status:x}=h,_=!1,C;if(n._optimisticResults){const A=this.hasListeners(),O=!A&&QE(t,n),F=A&&JE(t,r,n,o);(O||F)&&(y=Cm(t.options.networkMode)?"fetching":"paused",h.dataUpdatedAt||(x="pending")),n._optimisticResults==="isRestoring"&&(y="idle")}if(n.select&&typeof h.data<"u")if(i&&h.data===(s==null?void 0:s.data)&&n.select===z(this,pd))C=z(this,Vl);else try{ye(this,pd,n.select),C=n.select(h.data),C=Iy(i==null?void 0:i.data,C,n),ye(this,Vl,C),ye(this,Ao,null)}catch(A){ye(this,Ao,A)}else C=h.data;if(typeof n.placeholderData<"u"&&typeof C>"u"&&x==="pending"){let A;if(i!=null&&i.isPlaceholderData&&n.placeholderData===(l==null?void 0:l.placeholderData))A=i.data;else if(A=typeof n.placeholderData=="function"?n.placeholderData((M=z(this,Wl))==null?void 0:M.state.data,z(this,Wl)):n.placeholderData,n.select&&typeof A<"u")try{A=n.select(A),ye(this,Ao,null)}catch(O){ye(this,Ao,O)}typeof A<"u"&&(x="success",C=Iy(i==null?void 0:i.data,A,n),_=!0)}z(this,Ao)&&(m=z(this,Ao),C=z(this,Vl),g=Date.now(),x="error");const S=y==="fetching",b=x==="pending",E=x==="error",k=b&&S;return{status:x,fetchStatus:y,isPending:b,isSuccess:x==="success",isError:E,isInitialLoading:k,isLoading:k,data:C,dataUpdatedAt:h.dataUpdatedAt,error:m,errorUpdatedAt:g,failureCount:h.fetchFailureCount,failureReason:h.fetchFailureReason,errorUpdateCount:h.errorUpdateCount,isFetched:h.dataUpdateCount>0||h.errorUpdateCount>0,isFetchedAfterMount:h.dataUpdateCount>d.dataUpdateCount||h.errorUpdateCount>d.errorUpdateCount,isFetching:S,isRefetching:S&&!b,isLoadingError:E&&h.dataUpdatedAt===0,isPaused:y==="paused",isPlaceholderData:_,isRefetchError:E&&h.dataUpdatedAt!==0,isStale:Xw(t,n),refetch:this.refetch}}updateResult(t){const n=z(this,$n),r=this.createResult(z(this,Ct),this.options);if(ye(this,ha,z(this,Ct).state),ye(this,Ul,this.options),z(this,ha).data!==void 0&&ye(this,Wl,z(this,Ct)),Ny(r,n))return;ye(this,$n,r);const o={},i=()=>{if(!n)return!0;const{notifyOnChangeProps:s}=this.options,l=typeof s=="function"?s():s;if(l==="all"||!l&&!z(this,va).size)return!0;const u=new Set(l??z(this,va));return this.options.throwOnError&&u.add("error"),Object.keys(z(this,$n)).some(d=>{const h=d;return z(this,$n)[h]!==n[h]&&u.has(h)})};(t==null?void 0:t.listeners)!==!1&&i()&&(o.listeners=!0),tt(this,am,IR).call(this,{...o,...t})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&tt(this,vd,zy).call(this)}},Xn=new WeakMap,Ct=new WeakMap,Bl=new WeakMap,$n=new WeakMap,ha=new WeakMap,Ul=new WeakMap,Ao=new WeakMap,pd=new WeakMap,Vl=new WeakMap,Wl=new WeakMap,ma=new WeakMap,ga=new WeakMap,ns=new WeakMap,va=new WeakMap,ya=new WeakSet,hu=function(t){tt(this,xd,Vy).call(this);let n=z(this,Ct).fetch(this.options,t);return t!=null&&t.throwOnError||(n=n.catch(Lr)),n},hd=new WeakSet,Ly=function(){if(tt(this,yd,By).call(this),Ql||z(this,$n).isStale||!My(this.options.staleTime))return;const n=PR(z(this,$n).dataUpdatedAt,this.options.staleTime)+1;ye(this,ma,setTimeout(()=>{z(this,$n).isStale||this.updateResult()},n))},md=new WeakSet,Fy=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(z(this,Ct)):this.options.refetchInterval)??!1},gd=new WeakSet,jy=function(t){tt(this,wd,Uy).call(this),ye(this,ns,t),!(Ql||this.options.enabled===!1||!My(z(this,ns))||z(this,ns)===0)&&ye(this,ga,setInterval(()=>{(this.options.refetchIntervalInBackground||Rh.isFocused())&&tt(this,ya,hu).call(this)},z(this,ns)))},vd=new WeakSet,zy=function(){tt(this,hd,Ly).call(this),tt(this,gd,jy).call(this,tt(this,md,Fy).call(this))},yd=new WeakSet,By=function(){z(this,ma)&&(clearTimeout(z(this,ma)),ye(this,ma,void 0))},wd=new WeakSet,Uy=function(){z(this,ga)&&(clearInterval(z(this,ga)),ye(this,ga,void 0))},xd=new WeakSet,Vy=function(){const t=z(this,Xn).getQueryCache().build(z(this,Xn),this.options);if(t===z(this,Ct))return;const n=z(this,Ct);ye(this,Ct,t),ye(this,Bl,t.state),this.hasListeners()&&(n==null||n.removeObserver(this),t.addObserver(this))},am=new WeakSet,IR=function(t){gn.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(z(this,$n))}),z(this,Xn).getQueryCache().notify({query:z(this,Ct),type:"observerResultsUpdated"})})},g$);function pL(e,t){return t.enabled!==!1&&!e.state.dataUpdatedAt&&!(e.state.status==="error"&&t.retryOnMount===!1)}function QE(e,t){return pL(e,t)||e.state.dataUpdatedAt>0&&Wy(e,t,t.refetchOnMount)}function Wy(e,t,n){if(t.enabled!==!1){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&Xw(e,t)}return!1}function JE(e,t,n,r){return n.enabled!==!1&&(e!==t||r.enabled===!1)&&(!n.suspense||e.state.status!=="error")&&Xw(e,n)}function Xw(e,t){return e.isStaleByTime(t.staleTime)}function hL(e,t){return!Ny(e.getCurrentResult(),t)}var LR=f.createContext(void 0),mL=e=>{const t=f.useContext(LR);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},gL=({client:e,children:t})=>(f.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),f.createElement(LR.Provider,{value:e},t)),FR=f.createContext(!1),vL=()=>f.useContext(FR);FR.Provider;function yL(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var wL=f.createContext(yL()),xL=()=>f.useContext(wL);function bL(e,t){return typeof e=="function"?e(...t):!!e}var _L=(e,t)=>{(e.suspense||e.throwOnError)&&(t.isReset()||(e.retryOnMount=!1))},SL=e=>{f.useEffect(()=>{e.clearReset()},[e])},EL=({result:e,errorResetBoundary:t,throwOnError:n,query:r})=>e.isError&&!t.isReset()&&!e.isFetching&&bL(n,[e.error,r]),CL=e=>{e.suspense&&typeof e.staleTime!="number"&&(e.staleTime=1e3)},$L=(e,t)=>(e==null?void 0:e.suspense)&&t.isPending,kL=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function RL(e,t,n){const r=mL(n),o=vL(),i=xL(),s=r.defaultQueryOptions(e);s._optimisticResults=o?"isRestoring":"optimistic",CL(s),_L(s,i),SL(i);const[l]=f.useState(()=>new t(r,s)),u=l.getOptimisticResult(s);if(f.useSyncExternalStore(f.useCallback(d=>{const h=o?()=>{}:l.subscribe(gn.batchCalls(d));return l.updateResult(),h},[l,o]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),f.useEffect(()=>{l.setOptions(s,{listeners:!1})},[s,l]),$L(s,u))throw l.setOptions(s,{listeners:!1}),kL(s,l,i);if(EL({result:u,errorResetBoundary:i,throwOnError:s.throwOnError,query:l.getCurrentQuery()}))throw u.error;return s.notifyOnChangeProps?u:l.trackResult(u)}function TL(e,t){return RL(e,fL,t)}var jR=(e=>(e.RemoveBG="RemoveBG",e.AnimeSeg="AnimeSeg",e.RealESRGAN="RealESRGAN",e.GFPGAN="GFPGAN",e.RestoreFormer="RestoreFormer",e.InteractiveSeg="InteractiveSeg",e))(jR||{}),xs=(e=>(e.NAME="name",e.CTIME="ctime",e.MTIME="mtime",e))(xs||{}),$u=(e=>(e.DESCENDING="desc",e.ASCENDING="asc",e))($u||{}),Zw=(e=>(e.ddim="ddim",e.plms="plms",e))(Zw||{}),qw=(e=>(e.INPAINT_NS="INPAINT_NS",e.INPAINT_TELEA="INPAINT_TELEA",e))(qw||{}),In=(e=>(e.x="x",e.y="y",e.xy="xy",e))(In||{}),kl=(e=>(e.text_guided="text-guided",e.shape_guided="shape-guided",e.object_remove="object-remove",e.outpainting="outpainting",e))(kl||{});function zR(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;tl(i)))==null?void 0:s.classGroupId}const eC=/^\[(.+)\]$/;function AL(e){if(eC.test(e)){const t=eC.exec(e)[1],n=t==null?void 0:t.substring(0,t.indexOf(":"));if(n)return"arbitrary.."+n}}function OL(e){const{theme:t,prefix:n}=e,r={nextPart:new Map,validators:[]};return NL(Object.entries(e.classGroups),n).forEach(([i,s])=>{Hy(s,r,i,t)}),r}function Hy(e,t,n,r){e.forEach(o=>{if(typeof o=="string"){const i=o===""?t:tC(t,o);i.classGroupId=n;return}if(typeof o=="function"){if(ML(o)){Hy(o(r),t,n,r);return}t.validators.push({validator:o,classGroupId:n});return}Object.entries(o).forEach(([i,s])=>{Hy(s,tC(t,i),n,r)})})}function tC(e,t){let n=e;return t.split(Qw).forEach(r=>{n.nextPart.has(r)||n.nextPart.set(r,{nextPart:new Map,validators:[]}),n=n.nextPart.get(r)}),n}function ML(e){return e.isThemeGetter}function NL(e,t){return t?e.map(([n,r])=>{const o=r.map(i=>typeof i=="string"?t+i:typeof i=="object"?Object.fromEntries(Object.entries(i).map(([s,l])=>[t+s,l])):i);return[n,o]}):e}function DL(e){if(e<1)return{get:()=>{},set:()=>{}};let t=0,n=new Map,r=new Map;function o(i,s){n.set(i,s),t++,t>e&&(t=0,r=n,n=new Map)}return{get(i){let s=n.get(i);if(s!==void 0)return s;if((s=r.get(i))!==void 0)return o(i,s),s},set(i,s){n.has(i)?n.set(i,s):o(i,s)}}}const VR="!";function IL(e){const t=e.separator,n=t.length===1,r=t[0],o=t.length;return function(s){const l=[];let u=0,d=0,h;for(let _=0;_d?h-d:void 0;return{modifiers:l,hasImportantModifier:g,baseClassName:y,maybePostfixModifierPosition:x}}}function LL(e){if(e.length<=1)return e;const t=[];let n=[];return e.forEach(r=>{r[0]==="["?(t.push(...n.sort(),r),n=[]):n.push(r)}),t.push(...n.sort()),t}function FL(e){return{cache:DL(e.cacheSize),splitModifiers:IL(e),...PL(e)}}const jL=/\s+/;function zL(e,t){const{splitModifiers:n,getClassGroupId:r,getConflictingClassGroupIds:o}=t,i=new Set;return e.trim().split(jL).map(s=>{const{modifiers:l,hasImportantModifier:u,baseClassName:d,maybePostfixModifierPosition:h}=n(s);let m=r(h?d.substring(0,h):d),g=!!h;if(!m){if(!h)return{isTailwindClass:!1,originalClassName:s};if(m=r(d),!m)return{isTailwindClass:!1,originalClassName:s};g=!1}const y=LL(l).join(":");return{isTailwindClass:!0,modifierId:u?y+VR:y,classGroupId:m,originalClassName:s,hasPostfixModifier:g}}).reverse().filter(s=>{if(!s.isTailwindClass)return!0;const{modifierId:l,classGroupId:u,hasPostfixModifier:d}=s,h=l+u;return i.has(h)?!1:(i.add(h),o(u,d).forEach(m=>i.add(l+m)),!0)}).reverse().map(s=>s.originalClassName).join(" ")}function BL(){let e=0,t,n,r="";for(;em(h),e());return n=FL(d),r=n.cache.get,o=n.cache.set,i=l,l(u)}function l(u){const d=r(u);if(d)return d;const h=zL(u,n);return o(u,h),h}return function(){return i(BL.apply(null,arguments))}}function Rt(e){const t=n=>n[e]||[];return t.isThemeGetter=!0,t}const HR=/^\[(?:([a-z-]+):)?(.+)\]$/i,VL=/^\d+\/\d+$/,WL=new Set(["px","full","screen"]),HL=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,KL=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,YL=/^-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,GL=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/;function oo(e){return ia(e)||WL.has(e)||VL.test(e)}function zi(e){return mc(e,"length",nF)}function ia(e){return!!e&&!Number.isNaN(Number(e))}function np(e){return mc(e,"number",ia)}function nu(e){return!!e&&Number.isInteger(Number(e))}function XL(e){return e.endsWith("%")&&ia(e.slice(0,-1))}function Je(e){return HR.test(e)}function Bi(e){return HL.test(e)}const ZL=new Set(["length","size","percentage"]);function qL(e){return mc(e,ZL,KR)}function QL(e){return mc(e,"position",KR)}const JL=new Set(["image","url"]);function eF(e){return mc(e,JL,oF)}function tF(e){return mc(e,"",rF)}function ru(){return!0}function mc(e,t,n){const r=HR.exec(e);return r?r[1]?typeof t=="string"?r[1]===t:t.has(r[1]):n(r[2]):!1}function nF(e){return KL.test(e)}function KR(){return!1}function rF(e){return YL.test(e)}function oF(e){return GL.test(e)}function iF(){const e=Rt("colors"),t=Rt("spacing"),n=Rt("blur"),r=Rt("brightness"),o=Rt("borderColor"),i=Rt("borderRadius"),s=Rt("borderSpacing"),l=Rt("borderWidth"),u=Rt("contrast"),d=Rt("grayscale"),h=Rt("hueRotate"),m=Rt("invert"),g=Rt("gap"),y=Rt("gradientColorStops"),x=Rt("gradientColorStopPositions"),_=Rt("inset"),C=Rt("margin"),S=Rt("opacity"),b=Rt("padding"),E=Rt("saturate"),k=Rt("scale"),P=Rt("sepia"),M=Rt("skew"),A=Rt("space"),O=Rt("translate"),F=()=>["auto","contain","none"],V=()=>["auto","hidden","clip","visible","scroll"],J=()=>["auto",Je,t],G=()=>[Je,t],ae=()=>["",oo,zi],U=()=>["auto",ia,Je],te=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],L=()=>["solid","dashed","dotted","double","none"],ie=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity","plus-lighter"],K=()=>["start","end","center","between","around","evenly","stretch"],Q=()=>["","0",Je],W=()=>["auto","avoid","all","avoid-page","page","left","right","column"],le=()=>[ia,np],ge=()=>[ia,Je];return{cacheSize:500,separator:":",theme:{colors:[ru],spacing:[oo,zi],blur:["none","",Bi,Je],brightness:le(),borderColor:[e],borderRadius:["none","","full",Bi,Je],borderSpacing:G(),borderWidth:ae(),contrast:le(),grayscale:Q(),hueRotate:ge(),invert:Q(),gap:G(),gradientColorStops:[e],gradientColorStopPositions:[XL,zi],inset:J(),margin:J(),opacity:le(),padding:G(),saturate:le(),scale:le(),sepia:Q(),skew:ge(),space:G(),translate:G()},classGroups:{aspect:[{aspect:["auto","square","video",Je]}],container:["container"],columns:[{columns:[Bi]}],"break-after":[{"break-after":W()}],"break-before":[{"break-before":W()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],float:[{float:["right","left","none"]}],clear:[{clear:["left","right","both","none"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:[...te(),Je]}],overflow:[{overflow:V()}],"overflow-x":[{"overflow-x":V()}],"overflow-y":[{"overflow-y":V()}],overscroll:[{overscroll:F()}],"overscroll-x":[{"overscroll-x":F()}],"overscroll-y":[{"overscroll-y":F()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[_]}],"inset-x":[{"inset-x":[_]}],"inset-y":[{"inset-y":[_]}],start:[{start:[_]}],end:[{end:[_]}],top:[{top:[_]}],right:[{right:[_]}],bottom:[{bottom:[_]}],left:[{left:[_]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",nu,Je]}],basis:[{basis:J()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",Je]}],grow:[{grow:Q()}],shrink:[{shrink:Q()}],order:[{order:["first","last","none",nu,Je]}],"grid-cols":[{"grid-cols":[ru]}],"col-start-end":[{col:["auto",{span:["full",nu,Je]},Je]}],"col-start":[{"col-start":U()}],"col-end":[{"col-end":U()}],"grid-rows":[{"grid-rows":[ru]}],"row-start-end":[{row:["auto",{span:[nu,Je]},Je]}],"row-start":[{"row-start":U()}],"row-end":[{"row-end":U()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",Je]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",Je]}],gap:[{gap:[g]}],"gap-x":[{"gap-x":[g]}],"gap-y":[{"gap-y":[g]}],"justify-content":[{justify:["normal",...K()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...K(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...K(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[b]}],px:[{px:[b]}],py:[{py:[b]}],ps:[{ps:[b]}],pe:[{pe:[b]}],pt:[{pt:[b]}],pr:[{pr:[b]}],pb:[{pb:[b]}],pl:[{pl:[b]}],m:[{m:[C]}],mx:[{mx:[C]}],my:[{my:[C]}],ms:[{ms:[C]}],me:[{me:[C]}],mt:[{mt:[C]}],mr:[{mr:[C]}],mb:[{mb:[C]}],ml:[{ml:[C]}],"space-x":[{"space-x":[A]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[A]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit",Je,t]}],"min-w":[{"min-w":["min","max","fit",Je,oo]}],"max-w":[{"max-w":["0","none","full","min","max","fit","prose",{screen:[Bi]},Bi,Je]}],h:[{h:[Je,t,"auto","min","max","fit"]}],"min-h":[{"min-h":["min","max","fit",oo,Je]}],"max-h":[{"max-h":[Je,t,"min","max","fit"]}],"font-size":[{text:["base",Bi,zi]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",np]}],"font-family":[{font:[ru]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractons"],tracking:[{tracking:["tighter","tight","normal","wide","wider","widest",Je]}],"line-clamp":[{"line-clamp":["none",ia,np]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",oo,Je]}],"list-image":[{"list-image":["none",Je]}],"list-style-type":[{list:["none","disc","decimal",Je]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[e]}],"placeholder-opacity":[{"placeholder-opacity":[S]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[e]}],"text-opacity":[{"text-opacity":[S]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...L(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",oo,zi]}],"underline-offset":[{"underline-offset":["auto",oo,Je]}],"text-decoration-color":[{decoration:[e]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],indent:[{indent:G()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Je]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",Je]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[S]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...te(),QL]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",qL]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},eF]}],"bg-color":[{bg:[e]}],"gradient-from-pos":[{from:[x]}],"gradient-via-pos":[{via:[x]}],"gradient-to-pos":[{to:[x]}],"gradient-from":[{from:[y]}],"gradient-via":[{via:[y]}],"gradient-to":[{to:[y]}],rounded:[{rounded:[i]}],"rounded-s":[{"rounded-s":[i]}],"rounded-e":[{"rounded-e":[i]}],"rounded-t":[{"rounded-t":[i]}],"rounded-r":[{"rounded-r":[i]}],"rounded-b":[{"rounded-b":[i]}],"rounded-l":[{"rounded-l":[i]}],"rounded-ss":[{"rounded-ss":[i]}],"rounded-se":[{"rounded-se":[i]}],"rounded-ee":[{"rounded-ee":[i]}],"rounded-es":[{"rounded-es":[i]}],"rounded-tl":[{"rounded-tl":[i]}],"rounded-tr":[{"rounded-tr":[i]}],"rounded-br":[{"rounded-br":[i]}],"rounded-bl":[{"rounded-bl":[i]}],"border-w":[{border:[l]}],"border-w-x":[{"border-x":[l]}],"border-w-y":[{"border-y":[l]}],"border-w-s":[{"border-s":[l]}],"border-w-e":[{"border-e":[l]}],"border-w-t":[{"border-t":[l]}],"border-w-r":[{"border-r":[l]}],"border-w-b":[{"border-b":[l]}],"border-w-l":[{"border-l":[l]}],"border-opacity":[{"border-opacity":[S]}],"border-style":[{border:[...L(),"hidden"]}],"divide-x":[{"divide-x":[l]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[l]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[S]}],"divide-style":[{divide:L()}],"border-color":[{border:[o]}],"border-color-x":[{"border-x":[o]}],"border-color-y":[{"border-y":[o]}],"border-color-t":[{"border-t":[o]}],"border-color-r":[{"border-r":[o]}],"border-color-b":[{"border-b":[o]}],"border-color-l":[{"border-l":[o]}],"divide-color":[{divide:[o]}],"outline-style":[{outline:["",...L()]}],"outline-offset":[{"outline-offset":[oo,Je]}],"outline-w":[{outline:[oo,zi]}],"outline-color":[{outline:[e]}],"ring-w":[{ring:ae()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[e]}],"ring-opacity":[{"ring-opacity":[S]}],"ring-offset-w":[{"ring-offset":[oo,zi]}],"ring-offset-color":[{"ring-offset":[e]}],shadow:[{shadow:["","inner","none",Bi,tF]}],"shadow-color":[{shadow:[ru]}],opacity:[{opacity:[S]}],"mix-blend":[{"mix-blend":ie()}],"bg-blend":[{"bg-blend":ie()}],filter:[{filter:["","none"]}],blur:[{blur:[n]}],brightness:[{brightness:[r]}],contrast:[{contrast:[u]}],"drop-shadow":[{"drop-shadow":["","none",Bi,Je]}],grayscale:[{grayscale:[d]}],"hue-rotate":[{"hue-rotate":[h]}],invert:[{invert:[m]}],saturate:[{saturate:[E]}],sepia:[{sepia:[P]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[n]}],"backdrop-brightness":[{"backdrop-brightness":[r]}],"backdrop-contrast":[{"backdrop-contrast":[u]}],"backdrop-grayscale":[{"backdrop-grayscale":[d]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[h]}],"backdrop-invert":[{"backdrop-invert":[m]}],"backdrop-opacity":[{"backdrop-opacity":[S]}],"backdrop-saturate":[{"backdrop-saturate":[E]}],"backdrop-sepia":[{"backdrop-sepia":[P]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":[s]}],"border-spacing-x":[{"border-spacing-x":[s]}],"border-spacing-y":[{"border-spacing-y":[s]}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["none","all","","colors","opacity","shadow","transform",Je]}],duration:[{duration:ge()}],ease:[{ease:["linear","in","out","in-out",Je]}],delay:[{delay:ge()}],animate:[{animate:["none","spin","ping","pulse","bounce",Je]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[k]}],"scale-x":[{"scale-x":[k]}],"scale-y":[{"scale-y":[k]}],rotate:[{rotate:[nu,Je]}],"translate-x":[{"translate-x":[O]}],"translate-y":[{"translate-y":[O]}],"skew-x":[{"skew-x":[M]}],"skew-y":[{"skew-y":[M]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",Je]}],accent:[{accent:["auto",e]}],appearance:["appearance-none"],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",Je]}],"caret-color":[{caret:[e]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":G()}],"scroll-mx":[{"scroll-mx":G()}],"scroll-my":[{"scroll-my":G()}],"scroll-ms":[{"scroll-ms":G()}],"scroll-me":[{"scroll-me":G()}],"scroll-mt":[{"scroll-mt":G()}],"scroll-mr":[{"scroll-mr":G()}],"scroll-mb":[{"scroll-mb":G()}],"scroll-ml":[{"scroll-ml":G()}],"scroll-p":[{"scroll-p":G()}],"scroll-px":[{"scroll-px":G()}],"scroll-py":[{"scroll-py":G()}],"scroll-ps":[{"scroll-ps":G()}],"scroll-pe":[{"scroll-pe":G()}],"scroll-pt":[{"scroll-pt":G()}],"scroll-pr":[{"scroll-pr":G()}],"scroll-pb":[{"scroll-pb":G()}],"scroll-pl":[{"scroll-pl":G()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",Je]}],fill:[{fill:[e,"none"]}],"stroke-w":[{stroke:[oo,zi,np]}],stroke:[{stroke:[e,"none"]}],sr:["sr-only","not-sr-only"]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]}}}const Jw=UL(iF),sF=40,is="inpaint",rp="diffusers_sd",nC="diffusers_sdxl",op="diffusers_sd_inpaint",rC="diffusers_sdxl_inpaint",l0="diffusers_other",Ky="#ffcc00bb",oC="ldm",iC="cv2",YR="Fantasy-Studio/Paint-by-Example",aF="timbrooks/instruct-pix2pix",lF="Sanster/PowerPaint-V1-stable-diffusion-inpainting",cF="out of frame, lowres, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, disfigured, gross proportions, malformed limbs, watermark, signature";function Ce(...e){return Jw(BR(e))}function uF(){async function e(r=""){return(await fetch(r,{method:"GET",cache:"no-cache"})).json()}const t=()=>{const r=document.location;e(r+"/flaskwebgui-keep-server-alive").then(i=>i)},n=3*1e3;t(),setInterval(t,n)}function sC(e){const t=e.split(",")[0].split(":")[1].split(";")[0],n=atob(e.split(",")[1]),r=[];for(let o=0;o{const o=e.src,i=e;i.onload=n,i.onerror=s=>{i.src=o,r(s)},i.src=t})}async function dF(e){const t=URL.createObjectURL(e),n=new Image;return await Ip(n,t),n}function aC(e){return new Promise((t,n)=>{const r=new Image;r.addEventListener("load",()=>{t(r)}),r.addEventListener("error",o=>{n(o)}),r.src=e.toDataURL()})}function fF(e){return new Promise((t,n)=>{const r=new FileReader;r.onload=()=>{const o=new Image;o.onload=()=>{t(o)},o.onerror=()=>{n("无法加载图像。")},o.src=r.result},r.onerror=()=>{n("无法读取文件。")},r.readAsDataURL(e)})}function ku(e,t,n){return fetch(e).then(function(r){return r.arrayBuffer()}).then(function(r){return new File([r],t,{type:n})})}async function pF(){try{const{state:e}=await navigator.permissions.query({name:"clipboard-write"});return e==="granted"}catch{return!1}}function hF(e,t){return new Promise((n,r)=>e.toBlob(async o=>{o?n(o):r(new Error("Expected toBlob() to be defined"))},t))}const mF=async e=>{const t=[new ClipboardItem({[e.type]:e})];await navigator.clipboard.write(t)};function lC(e){return e.nativeEvent.button===2}function cC(e){return e.nativeEvent.button===1}async function gF(e){const t=await hF(e,"image/png");try{await mF(t)}catch{console.log("Copy image failed!")}}function vF(e,t){const n=document.createElement("a");n.href=e,n.download=t,n.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0,view:window})),setTimeout(()=>{n.remove()},100)}function c0(e){const t=e.nativeEvent;return{x:t.offsetX,y:t.offsetY}}function GR(e,t,n=Ky){e.strokeStyle=n,e.lineCap="round",e.lineJoin="round",t.forEach(r=>{!(r!=null&&r.pts.length)||!r.size||(e.lineWidth=r.size,e.beginPath(),e.moveTo(r.pts[0].x,r.pts[0].y),r.pts.forEach(o=>e.lineTo(o.x,o.y)),e.stroke())})}const Lp=(e,t,n,r=[],o="white")=>{const i=document.createElement("canvas");i.width=e,i.height=t;const s=i.getContext("2d");if(!s)throw new Error("could not retrieve mask canvas");return r.forEach(l=>{s.drawImage(l,0,0,e,t)}),n.forEach(l=>{GR(s,l,o)}),i},Ru=e=>new Promise((t,n)=>{const r=new FileReader;r.onload=o=>{var s;const i=(s=o.target)==null?void 0:s.result;t(i)},r.onerror=o=>{n(o)},r.readAsDataURL(e)});function XR(e,t){return function(){return e.apply(t,arguments)}}const{toString:yF}=Object.prototype,{getPrototypeOf:ex}=Object,$m=(e=>t=>{const n=yF.call(t);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),Go=e=>(e=e.toLowerCase(),t=>$m(t)===e),km=e=>t=>typeof t===e,{isArray:gc}=Array,Zu=km("undefined");function wF(e){return e!==null&&!Zu(e)&&e.constructor!==null&&!Zu(e.constructor)&&Kr(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const ZR=Go("ArrayBuffer");function xF(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&ZR(e.buffer),t}const bF=km("string"),Kr=km("function"),qR=km("number"),Rm=e=>e!==null&&typeof e=="object",_F=e=>e===!0||e===!1,Fp=e=>{if($m(e)!=="object")return!1;const t=ex(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},SF=Go("Date"),EF=Go("File"),CF=Go("Blob"),$F=Go("FileList"),kF=e=>Rm(e)&&Kr(e.pipe),RF=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||Kr(e.append)&&((t=$m(e))==="formdata"||t==="object"&&Kr(e.toString)&&e.toString()==="[object FormData]"))},TF=Go("URLSearchParams"),PF=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function kd(e,t,{allOwnKeys:n=!1}={}){if(e===null||typeof e>"u")return;let r,o;if(typeof e!="object"&&(e=[e]),gc(e))for(r=0,o=e.length;r0;)if(o=n[r],t===o.toLowerCase())return o;return null}const JR=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,eT=e=>!Zu(e)&&e!==JR;function Yy(){const{caseless:e}=eT(this)&&this||{},t={},n=(r,o)=>{const i=e&&QR(t,o)||o;Fp(t[i])&&Fp(r)?t[i]=Yy(t[i],r):Fp(r)?t[i]=Yy({},r):gc(r)?t[i]=r.slice():t[i]=r};for(let r=0,o=arguments.length;r(kd(t,(o,i)=>{n&&Kr(o)?e[i]=XR(o,n):e[i]=o},{allOwnKeys:r}),e),OF=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),MF=(e,t,n,r)=>{e.prototype=Object.create(t.prototype,r),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),n&&Object.assign(e.prototype,n)},NF=(e,t,n,r)=>{let o,i,s;const l={};if(t=t||{},e==null)return t;do{for(o=Object.getOwnPropertyNames(e),i=o.length;i-- >0;)s=o[i],(!r||r(s,e,t))&&!l[s]&&(t[s]=e[s],l[s]=!0);e=n!==!1&&ex(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},DF=(e,t,n)=>{e=String(e),(n===void 0||n>e.length)&&(n=e.length),n-=t.length;const r=e.indexOf(t,n);return r!==-1&&r===n},IF=e=>{if(!e)return null;if(gc(e))return e;let t=e.length;if(!qR(t))return null;const n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},LF=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&ex(Uint8Array)),FF=(e,t)=>{const r=(e&&e[Symbol.iterator]).call(e);let o;for(;(o=r.next())&&!o.done;){const i=o.value;t.call(e,i[0],i[1])}},jF=(e,t)=>{let n;const r=[];for(;(n=e.exec(t))!==null;)r.push(n);return r},zF=Go("HTMLFormElement"),BF=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,r,o){return r.toUpperCase()+o}),uC=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),UF=Go("RegExp"),tT=(e,t)=>{const n=Object.getOwnPropertyDescriptors(e),r={};kd(n,(o,i)=>{let s;(s=t(o,i,e))!==!1&&(r[i]=s||o)}),Object.defineProperties(e,r)},VF=e=>{tT(e,(t,n)=>{if(Kr(e)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;const r=e[n];if(Kr(r)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},WF=(e,t)=>{const n={},r=o=>{o.forEach(i=>{n[i]=!0})};return gc(e)?r(e):r(String(e).split(t)),n},HF=()=>{},KF=(e,t)=>(e=+e,Number.isFinite(e)?e:t),u0="abcdefghijklmnopqrstuvwxyz",dC="0123456789",nT={DIGIT:dC,ALPHA:u0,ALPHA_DIGIT:u0+u0.toUpperCase()+dC},YF=(e=16,t=nT.ALPHA_DIGIT)=>{let n="";const{length:r}=t;for(;e--;)n+=t[Math.random()*r|0];return n};function GF(e){return!!(e&&Kr(e.append)&&e[Symbol.toStringTag]==="FormData"&&e[Symbol.iterator])}const XF=e=>{const t=new Array(10),n=(r,o)=>{if(Rm(r)){if(t.indexOf(r)>=0)return;if(!("toJSON"in r)){t[o]=r;const i=gc(r)?[]:{};return kd(r,(s,l)=>{const u=n(s,o+1);!Zu(u)&&(i[l]=u)}),t[o]=void 0,i}}return r};return n(e,0)},ZF=Go("AsyncFunction"),qF=e=>e&&(Rm(e)||Kr(e))&&Kr(e.then)&&Kr(e.catch),oe={isArray:gc,isArrayBuffer:ZR,isBuffer:wF,isFormData:RF,isArrayBufferView:xF,isString:bF,isNumber:qR,isBoolean:_F,isObject:Rm,isPlainObject:Fp,isUndefined:Zu,isDate:SF,isFile:EF,isBlob:CF,isRegExp:UF,isFunction:Kr,isStream:kF,isURLSearchParams:TF,isTypedArray:LF,isFileList:$F,forEach:kd,merge:Yy,extend:AF,trim:PF,stripBOM:OF,inherits:MF,toFlatObject:NF,kindOf:$m,kindOfTest:Go,endsWith:DF,toArray:IF,forEachEntry:FF,matchAll:jF,isHTMLForm:zF,hasOwnProperty:uC,hasOwnProp:uC,reduceDescriptors:tT,freezeMethods:VF,toObjectSet:WF,toCamelCase:BF,noop:HF,toFiniteNumber:KF,findKey:QR,global:JR,isContextDefined:eT,ALPHABET:nT,generateString:YF,isSpecCompliantForm:GF,toJSONObject:XF,isAsyncFn:ZF,isThenable:qF};function ut(e,t,n,r,o){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),n&&(this.config=n),r&&(this.request=r),o&&(this.response=o)}oe.inherits(ut,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:oe.toJSONObject(this.config),code:this.code,status:this.response&&this.response.status?this.response.status:null}}});const rT=ut.prototype,oT={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{oT[e]={value:e}});Object.defineProperties(ut,oT);Object.defineProperty(rT,"isAxiosError",{value:!0});ut.from=(e,t,n,r,o,i)=>{const s=Object.create(rT);return oe.toFlatObject(e,s,function(u){return u!==Error.prototype},l=>l!=="isAxiosError"),ut.call(s,e.message,t,n,r,o),s.cause=e,s.name=e.name,i&&Object.assign(s,i),s};const QF=null;function Gy(e){return oe.isPlainObject(e)||oe.isArray(e)}function iT(e){return oe.endsWith(e,"[]")?e.slice(0,-2):e}function fC(e,t,n){return e?e.concat(t).map(function(o,i){return o=iT(o),!n&&i?"["+o+"]":o}).join(n?".":""):t}function JF(e){return oe.isArray(e)&&!e.some(Gy)}const ej=oe.toFlatObject(oe,{},null,function(t){return/^is[A-Z]/.test(t)});function Tm(e,t,n){if(!oe.isObject(e))throw new TypeError("target must be an object");t=t||new FormData,n=oe.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(_,C){return!oe.isUndefined(C[_])});const r=n.metaTokens,o=n.visitor||h,i=n.dots,s=n.indexes,u=(n.Blob||typeof Blob<"u"&&Blob)&&oe.isSpecCompliantForm(t);if(!oe.isFunction(o))throw new TypeError("visitor must be a function");function d(x){if(x===null)return"";if(oe.isDate(x))return x.toISOString();if(!u&&oe.isBlob(x))throw new ut("Blob is not supported. Use a Buffer instead.");return oe.isArrayBuffer(x)||oe.isTypedArray(x)?u&&typeof Blob=="function"?new Blob([x]):Buffer.from(x):x}function h(x,_,C){let S=x;if(x&&!C&&typeof x=="object"){if(oe.endsWith(_,"{}"))_=r?_:_.slice(0,-2),x=JSON.stringify(x);else if(oe.isArray(x)&&JF(x)||(oe.isFileList(x)||oe.endsWith(_,"[]"))&&(S=oe.toArray(x)))return _=iT(_),S.forEach(function(E,k){!(oe.isUndefined(E)||E===null)&&t.append(s===!0?fC([_],k,i):s===null?_:_+"[]",d(E))}),!1}return Gy(x)?!0:(t.append(fC(C,_,i),d(x)),!1)}const m=[],g=Object.assign(ej,{defaultVisitor:h,convertValue:d,isVisitable:Gy});function y(x,_){if(!oe.isUndefined(x)){if(m.indexOf(x)!==-1)throw Error("Circular reference detected in "+_.join("."));m.push(x),oe.forEach(x,function(S,b){(!(oe.isUndefined(S)||S===null)&&o.call(t,S,oe.isString(b)?b.trim():b,_,g))===!0&&y(S,_?_.concat(b):[b])}),m.pop()}}if(!oe.isObject(e))throw new TypeError("data must be an object");return y(e),t}function pC(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(r){return t[r]})}function tx(e,t){this._pairs=[],e&&Tm(e,this,t)}const sT=tx.prototype;sT.append=function(t,n){this._pairs.push([t,n])};sT.toString=function(t){const n=t?function(r){return t.call(this,r,pC)}:pC;return this._pairs.map(function(o){return n(o[0])+"="+n(o[1])},"").join("&")};function tj(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function aT(e,t,n){if(!t)return e;const r=n&&n.encode||tj,o=n&&n.serialize;let i;if(o?i=o(t,n):i=oe.isURLSearchParams(t)?t.toString():new tx(t,n).toString(r),i){const s=e.indexOf("#");s!==-1&&(e=e.slice(0,s)),e+=(e.indexOf("?")===-1?"?":"&")+i}return e}class nj{constructor(){this.handlers=[]}use(t,n,r){return this.handlers.push({fulfilled:t,rejected:n,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){oe.forEach(this.handlers,function(r){r!==null&&t(r)})}}const hC=nj,lT={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},rj=typeof URLSearchParams<"u"?URLSearchParams:tx,oj=typeof FormData<"u"?FormData:null,ij=typeof Blob<"u"?Blob:null,sj={isBrowser:!0,classes:{URLSearchParams:rj,FormData:oj,Blob:ij},protocols:["http","https","file","blob","url","data"]},cT=typeof window<"u"&&typeof document<"u",aj=(e=>cT&&["ReactNative","NativeScript","NS"].indexOf(e)<0)(typeof navigator<"u"&&navigator.product),lj=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",cj=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:cT,hasStandardBrowserEnv:aj,hasStandardBrowserWebWorkerEnv:lj},Symbol.toStringTag,{value:"Module"})),Io={...cj,...sj};function uj(e,t){return Tm(e,new Io.classes.URLSearchParams,Object.assign({visitor:function(n,r,o,i){return Io.isNode&&oe.isBuffer(n)?(this.append(r,n.toString("base64")),!1):i.defaultVisitor.apply(this,arguments)}},t))}function dj(e){return oe.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function fj(e){const t={},n=Object.keys(e);let r;const o=n.length;let i;for(r=0;r=n.length;return s=!s&&oe.isArray(o)?o.length:s,u?(oe.hasOwnProp(o,s)?o[s]=[o[s],r]:o[s]=r,!l):((!o[s]||!oe.isObject(o[s]))&&(o[s]=[]),t(n,r,o[s],i)&&oe.isArray(o[s])&&(o[s]=fj(o[s])),!l)}if(oe.isFormData(e)&&oe.isFunction(e.entries)){const n={};return oe.forEachEntry(e,(r,o)=>{t(dj(r),o,n,0)}),n}return null}function pj(e,t,n){if(oe.isString(e))try{return(t||JSON.parse)(e),oe.trim(e)}catch(r){if(r.name!=="SyntaxError")throw r}return(n||JSON.stringify)(e)}const nx={transitional:lT,adapter:["xhr","http"],transformRequest:[function(t,n){const r=n.getContentType()||"",o=r.indexOf("application/json")>-1,i=oe.isObject(t);if(i&&oe.isHTMLForm(t)&&(t=new FormData(t)),oe.isFormData(t))return o&&o?JSON.stringify(uT(t)):t;if(oe.isArrayBuffer(t)||oe.isBuffer(t)||oe.isStream(t)||oe.isFile(t)||oe.isBlob(t))return t;if(oe.isArrayBufferView(t))return t.buffer;if(oe.isURLSearchParams(t))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let l;if(i){if(r.indexOf("application/x-www-form-urlencoded")>-1)return uj(t,this.formSerializer).toString();if((l=oe.isFileList(t))||r.indexOf("multipart/form-data")>-1){const u=this.env&&this.env.FormData;return Tm(l?{"files[]":t}:t,u&&new u,this.formSerializer)}}return i||o?(n.setContentType("application/json",!1),pj(t)):t}],transformResponse:[function(t){const n=this.transitional||nx.transitional,r=n&&n.forcedJSONParsing,o=this.responseType==="json";if(t&&oe.isString(t)&&(r&&!this.responseType||o)){const s=!(n&&n.silentJSONParsing)&&o;try{return JSON.parse(t)}catch(l){if(s)throw l.name==="SyntaxError"?ut.from(l,ut.ERR_BAD_RESPONSE,this,null,this.response):l}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:Io.classes.FormData,Blob:Io.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};oe.forEach(["delete","get","head","post","put","patch"],e=>{nx.headers[e]={}});const rx=nx,hj=oe.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),mj=e=>{const t={};let n,r,o;return e&&e.split(` +`).forEach(function(s){o=s.indexOf(":"),n=s.substring(0,o).trim().toLowerCase(),r=s.substring(o+1).trim(),!(!n||t[n]&&hj[n])&&(n==="set-cookie"?t[n]?t[n].push(r):t[n]=[r]:t[n]=t[n]?t[n]+", "+r:r)}),t},mC=Symbol("internals");function ou(e){return e&&String(e).trim().toLowerCase()}function jp(e){return e===!1||e==null?e:oe.isArray(e)?e.map(jp):String(e)}function gj(e){const t=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=n.exec(e);)t[r[1]]=r[2];return t}const vj=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function d0(e,t,n,r,o){if(oe.isFunction(r))return r.call(this,t,n);if(o&&(t=n),!!oe.isString(t)){if(oe.isString(r))return t.indexOf(r)!==-1;if(oe.isRegExp(r))return r.test(t)}}function yj(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,n,r)=>n.toUpperCase()+r)}function wj(e,t){const n=oe.toCamelCase(" "+t);["get","set","has"].forEach(r=>{Object.defineProperty(e,r+n,{value:function(o,i,s){return this[r].call(this,t,o,i,s)},configurable:!0})})}class Pm{constructor(t){t&&this.set(t)}set(t,n,r){const o=this;function i(l,u,d){const h=ou(u);if(!h)throw new Error("header name must be a non-empty string");const m=oe.findKey(o,h);(!m||o[m]===void 0||d===!0||d===void 0&&o[m]!==!1)&&(o[m||u]=jp(l))}const s=(l,u)=>oe.forEach(l,(d,h)=>i(d,h,u));return oe.isPlainObject(t)||t instanceof this.constructor?s(t,n):oe.isString(t)&&(t=t.trim())&&!vj(t)?s(mj(t),n):t!=null&&i(n,t,r),this}get(t,n){if(t=ou(t),t){const r=oe.findKey(this,t);if(r){const o=this[r];if(!n)return o;if(n===!0)return gj(o);if(oe.isFunction(n))return n.call(this,o,r);if(oe.isRegExp(n))return n.exec(o);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,n){if(t=ou(t),t){const r=oe.findKey(this,t);return!!(r&&this[r]!==void 0&&(!n||d0(this,this[r],r,n)))}return!1}delete(t,n){const r=this;let o=!1;function i(s){if(s=ou(s),s){const l=oe.findKey(r,s);l&&(!n||d0(r,r[l],l,n))&&(delete r[l],o=!0)}}return oe.isArray(t)?t.forEach(i):i(t),o}clear(t){const n=Object.keys(this);let r=n.length,o=!1;for(;r--;){const i=n[r];(!t||d0(this,this[i],i,t,!0))&&(delete this[i],o=!0)}return o}normalize(t){const n=this,r={};return oe.forEach(this,(o,i)=>{const s=oe.findKey(r,i);if(s){n[s]=jp(o),delete n[i];return}const l=t?yj(i):String(i).trim();l!==i&&delete n[i],n[l]=jp(o),r[l]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){const n=Object.create(null);return oe.forEach(this,(r,o)=>{r!=null&&r!==!1&&(n[o]=t&&oe.isArray(r)?r.join(", "):r)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,n])=>t+": "+n).join(` +`)}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...n){const r=new this(t);return n.forEach(o=>r.set(o)),r}static accessor(t){const r=(this[mC]=this[mC]={accessors:{}}).accessors,o=this.prototype;function i(s){const l=ou(s);r[l]||(wj(o,s),r[l]=!0)}return oe.isArray(t)?t.forEach(i):i(t),this}}Pm.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);oe.reduceDescriptors(Pm.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(r){this[n]=r}}});oe.freezeMethods(Pm);const pi=Pm;function f0(e,t){const n=this||rx,r=t||n,o=pi.from(r.headers);let i=r.data;return oe.forEach(e,function(l){i=l.call(n,i,o.normalize(),t?t.status:void 0)}),o.normalize(),i}function dT(e){return!!(e&&e.__CANCEL__)}function Rd(e,t,n){ut.call(this,e??"canceled",ut.ERR_CANCELED,t,n),this.name="CanceledError"}oe.inherits(Rd,ut,{__CANCEL__:!0});function xj(e,t,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?e(n):t(new ut("Request failed with status code "+n.status,[ut.ERR_BAD_REQUEST,ut.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}const bj=Io.hasStandardBrowserEnv?{write(e,t,n,r,o,i){const s=[e+"="+encodeURIComponent(t)];oe.isNumber(n)&&s.push("expires="+new Date(n).toGMTString()),oe.isString(r)&&s.push("path="+r),oe.isString(o)&&s.push("domain="+o),i===!0&&s.push("secure"),document.cookie=s.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function _j(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function Sj(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e}function fT(e,t){return e&&!_j(t)?Sj(e,t):t}const Ej=Io.hasStandardBrowserEnv?function(){const t=/(msie|trident)/i.test(navigator.userAgent),n=document.createElement("a");let r;function o(i){let s=i;return t&&(n.setAttribute("href",s),s=n.href),n.setAttribute("href",s),{href:n.href,protocol:n.protocol?n.protocol.replace(/:$/,""):"",host:n.host,search:n.search?n.search.replace(/^\?/,""):"",hash:n.hash?n.hash.replace(/^#/,""):"",hostname:n.hostname,port:n.port,pathname:n.pathname.charAt(0)==="/"?n.pathname:"/"+n.pathname}}return r=o(window.location.href),function(s){const l=oe.isString(s)?o(s):s;return l.protocol===r.protocol&&l.host===r.host}}():function(){return function(){return!0}}();function Cj(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function $j(e,t){e=e||10;const n=new Array(e),r=new Array(e);let o=0,i=0,s;return t=t!==void 0?t:1e3,function(u){const d=Date.now(),h=r[i];s||(s=d),n[o]=u,r[o]=d;let m=i,g=0;for(;m!==o;)g+=n[m++],m=m%e;if(o=(o+1)%e,o===i&&(i=(i+1)%e),d-s{const i=o.loaded,s=o.lengthComputable?o.total:void 0,l=i-n,u=r(l),d=i<=s;n=i;const h={loaded:i,total:s,progress:s?i/s:void 0,bytes:l,rate:u||void 0,estimated:u&&s&&d?(s-i)/u:void 0,event:o};h[t?"download":"upload"]=!0,e(h)}}const kj=typeof XMLHttpRequest<"u",Rj=kj&&function(e){return new Promise(function(n,r){let o=e.data;const i=pi.from(e.headers).normalize();let{responseType:s,withXSRFToken:l}=e,u;function d(){e.cancelToken&&e.cancelToken.unsubscribe(u),e.signal&&e.signal.removeEventListener("abort",u)}let h;if(oe.isFormData(o)){if(Io.hasStandardBrowserEnv||Io.hasStandardBrowserWebWorkerEnv)i.setContentType(!1);else if((h=i.getContentType())!==!1){const[_,...C]=h?h.split(";").map(S=>S.trim()).filter(Boolean):[];i.setContentType([_||"multipart/form-data",...C].join("; "))}}let m=new XMLHttpRequest;if(e.auth){const _=e.auth.username||"",C=e.auth.password?unescape(encodeURIComponent(e.auth.password)):"";i.set("Authorization","Basic "+btoa(_+":"+C))}const g=fT(e.baseURL,e.url);m.open(e.method.toUpperCase(),aT(g,e.params,e.paramsSerializer),!0),m.timeout=e.timeout;function y(){if(!m)return;const _=pi.from("getAllResponseHeaders"in m&&m.getAllResponseHeaders()),S={data:!s||s==="text"||s==="json"?m.responseText:m.response,status:m.status,statusText:m.statusText,headers:_,config:e,request:m};xj(function(E){n(E),d()},function(E){r(E),d()},S),m=null}if("onloadend"in m?m.onloadend=y:m.onreadystatechange=function(){!m||m.readyState!==4||m.status===0&&!(m.responseURL&&m.responseURL.indexOf("file:")===0)||setTimeout(y)},m.onabort=function(){m&&(r(new ut("Request aborted",ut.ECONNABORTED,e,m)),m=null)},m.onerror=function(){r(new ut("Network Error",ut.ERR_NETWORK,e,m)),m=null},m.ontimeout=function(){let C=e.timeout?"timeout of "+e.timeout+"ms exceeded":"timeout exceeded";const S=e.transitional||lT;e.timeoutErrorMessage&&(C=e.timeoutErrorMessage),r(new ut(C,S.clarifyTimeoutError?ut.ETIMEDOUT:ut.ECONNABORTED,e,m)),m=null},Io.hasStandardBrowserEnv&&(l&&oe.isFunction(l)&&(l=l(e)),l||l!==!1&&Ej(g))){const _=e.xsrfHeaderName&&e.xsrfCookieName&&bj.read(e.xsrfCookieName);_&&i.set(e.xsrfHeaderName,_)}o===void 0&&i.setContentType(null),"setRequestHeader"in m&&oe.forEach(i.toJSON(),function(C,S){m.setRequestHeader(S,C)}),oe.isUndefined(e.withCredentials)||(m.withCredentials=!!e.withCredentials),s&&s!=="json"&&(m.responseType=e.responseType),typeof e.onDownloadProgress=="function"&&m.addEventListener("progress",gC(e.onDownloadProgress,!0)),typeof e.onUploadProgress=="function"&&m.upload&&m.upload.addEventListener("progress",gC(e.onUploadProgress)),(e.cancelToken||e.signal)&&(u=_=>{m&&(r(!_||_.type?new Rd(null,e,m):_),m.abort(),m=null)},e.cancelToken&&e.cancelToken.subscribe(u),e.signal&&(e.signal.aborted?u():e.signal.addEventListener("abort",u)));const x=Cj(g);if(x&&Io.protocols.indexOf(x)===-1){r(new ut("Unsupported protocol "+x+":",ut.ERR_BAD_REQUEST,e));return}m.send(o||null)})},Xy={http:QF,xhr:Rj};oe.forEach(Xy,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});const vC=e=>`- ${e}`,Tj=e=>oe.isFunction(e)||e===null||e===!1,pT={getAdapter:e=>{e=oe.isArray(e)?e:[e];const{length:t}=e;let n,r;const o={};for(let i=0;i`adapter ${l} `+(u===!1?"is not supported by the environment":"is not available in the build"));let s=t?i.length>1?`since : +`+i.map(vC).join(` +`):" "+vC(i[0]):"as no adapter specified";throw new ut("There is no suitable adapter to dispatch the request "+s,"ERR_NOT_SUPPORT")}return r},adapters:Xy};function p0(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Rd(null,e)}function yC(e){return p0(e),e.headers=pi.from(e.headers),e.data=f0.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),pT.getAdapter(e.adapter||rx.adapter)(e).then(function(r){return p0(e),r.data=f0.call(e,e.transformResponse,r),r.headers=pi.from(r.headers),r},function(r){return dT(r)||(p0(e),r&&r.response&&(r.response.data=f0.call(e,e.transformResponse,r.response),r.response.headers=pi.from(r.response.headers))),Promise.reject(r)})}const wC=e=>e instanceof pi?e.toJSON():e;function Jl(e,t){t=t||{};const n={};function r(d,h,m){return oe.isPlainObject(d)&&oe.isPlainObject(h)?oe.merge.call({caseless:m},d,h):oe.isPlainObject(h)?oe.merge({},h):oe.isArray(h)?h.slice():h}function o(d,h,m){if(oe.isUndefined(h)){if(!oe.isUndefined(d))return r(void 0,d,m)}else return r(d,h,m)}function i(d,h){if(!oe.isUndefined(h))return r(void 0,h)}function s(d,h){if(oe.isUndefined(h)){if(!oe.isUndefined(d))return r(void 0,d)}else return r(void 0,h)}function l(d,h,m){if(m in t)return r(d,h);if(m in e)return r(void 0,d)}const u={url:i,method:i,data:i,baseURL:s,transformRequest:s,transformResponse:s,paramsSerializer:s,timeout:s,timeoutMessage:s,withCredentials:s,withXSRFToken:s,adapter:s,responseType:s,xsrfCookieName:s,xsrfHeaderName:s,onUploadProgress:s,onDownloadProgress:s,decompress:s,maxContentLength:s,maxBodyLength:s,beforeRedirect:s,transport:s,httpAgent:s,httpsAgent:s,cancelToken:s,socketPath:s,responseEncoding:s,validateStatus:l,headers:(d,h)=>o(wC(d),wC(h),!0)};return oe.forEach(Object.keys(Object.assign({},e,t)),function(h){const m=u[h]||o,g=m(e[h],t[h],h);oe.isUndefined(g)&&m!==l||(n[h]=g)}),n}const hT="1.6.2",ox={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{ox[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const xC={};ox.transitional=function(t,n,r){function o(i,s){return"[Axios v"+hT+"] Transitional option '"+i+"'"+s+(r?". "+r:"")}return(i,s,l)=>{if(t===!1)throw new ut(o(s," has been removed"+(n?" in "+n:"")),ut.ERR_DEPRECATED);return n&&!xC[s]&&(xC[s]=!0,console.warn(o(s," has been deprecated since v"+n+" and will be removed in the near future"))),t?t(i,s,l):!0}};function Pj(e,t,n){if(typeof e!="object")throw new ut("options must be an object",ut.ERR_BAD_OPTION_VALUE);const r=Object.keys(e);let o=r.length;for(;o-- >0;){const i=r[o],s=t[i];if(s){const l=e[i],u=l===void 0||s(l,i,e);if(u!==!0)throw new ut("option "+i+" must be "+u,ut.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new ut("Unknown option "+i,ut.ERR_BAD_OPTION)}}const Zy={assertOptions:Pj,validators:ox},Ui=Zy.validators;class Ph{constructor(t){this.defaults=t,this.interceptors={request:new hC,response:new hC}}request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=Jl(this.defaults,n);const{transitional:r,paramsSerializer:o,headers:i}=n;r!==void 0&&Zy.assertOptions(r,{silentJSONParsing:Ui.transitional(Ui.boolean),forcedJSONParsing:Ui.transitional(Ui.boolean),clarifyTimeoutError:Ui.transitional(Ui.boolean)},!1),o!=null&&(oe.isFunction(o)?n.paramsSerializer={serialize:o}:Zy.assertOptions(o,{encode:Ui.function,serialize:Ui.function},!0)),n.method=(n.method||this.defaults.method||"get").toLowerCase();let s=i&&oe.merge(i.common,i[n.method]);i&&oe.forEach(["delete","get","head","post","put","patch","common"],x=>{delete i[x]}),n.headers=pi.concat(s,i);const l=[];let u=!0;this.interceptors.request.forEach(function(_){typeof _.runWhen=="function"&&_.runWhen(n)===!1||(u=u&&_.synchronous,l.unshift(_.fulfilled,_.rejected))});const d=[];this.interceptors.response.forEach(function(_){d.push(_.fulfilled,_.rejected)});let h,m=0,g;if(!u){const x=[yC.bind(this),void 0];for(x.unshift.apply(x,l),x.push.apply(x,d),g=x.length,h=Promise.resolve(n);m{if(!r._listeners)return;let i=r._listeners.length;for(;i-- >0;)r._listeners[i](o);r._listeners=null}),this.promise.then=o=>{let i;const s=new Promise(l=>{r.subscribe(l),i=l}).then(o);return s.cancel=function(){r.unsubscribe(i)},s},t(function(i,s,l){r.reason||(r.reason=new Rd(i,s,l),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}static source(){let t;return{token:new ix(function(o){t=o}),cancel:t}}}const Aj=ix;function Oj(e){return function(n){return e.apply(null,n)}}function Mj(e){return oe.isObject(e)&&e.isAxiosError===!0}const qy={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(qy).forEach(([e,t])=>{qy[t]=e});const Nj=qy;function mT(e){const t=new zp(e),n=XR(zp.prototype.request,t);return oe.extend(n,zp.prototype,t,{allOwnKeys:!0}),oe.extend(n,t,null,{allOwnKeys:!0}),n.create=function(o){return mT(Jl(e,o))},n}const Jt=mT(rx);Jt.Axios=zp;Jt.CanceledError=Rd;Jt.CancelToken=Aj;Jt.isCancel=dT;Jt.VERSION=hT;Jt.toFormData=Tm;Jt.AxiosError=ut;Jt.Cancel=Jt.CanceledError;Jt.all=function(t){return Promise.all(t)};Jt.spread=Oj;Jt.isAxiosError=Mj;Jt.mergeConfig=Jl;Jt.AxiosHeaders=pi;Jt.formToJSON=e=>uT(oe.isHTMLForm(e)?new FormData(e):e);Jt.getAdapter=pT.getAdapter;Jt.HttpStatusCode=Nj;Jt.default=Jt;const Dj=Jt,Ms="/api/v1",vc=Dj.create({baseURL:Ms});async function Ij(e,t,n,r,o,i=null){const s=await Ru(e),l=await Ru(o),u=i?await Ru(i):null,d=await fetch(`${Ms}/inpaint`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({image:s,mask:l,ldm_steps:t.ldmSteps,ldm_sampler:t.ldmSampler,zits_wireframe:t.zitsWireframe,cv2_flag:t.cv2Flag,cv2_radius:t.cv2Radius,hd_strategy:"Crop",hd_strategy_crop_triger_size:640,hd_strategy_crop_margin:128,hd_trategy_resize_imit:2048,prompt:t.prompt,negative_prompt:t.negativePrompt,use_croper:t.showCropper,croper_x:n.x,croper_y:n.y,croper_height:n.height,croper_width:n.width,use_extender:t.showExtender,extender_x:r.x,extender_y:r.y,extender_height:r.height,extender_width:r.width,sd_mask_blur:t.sdMaskBlur,sd_strength:t.sdStrength,sd_steps:t.sdSteps,sd_guidance_scale:t.sdGuidanceScale,sd_sampler:t.sdSampler,sd_seed:t.seedFixed?t.seed:-1,sd_match_histograms:t.sdMatchHistograms,sd_freeu:t.enableFreeu,sd_freeu_config:t.freeuConfig,sd_lcm_lora:t.enableLCMLora,paint_by_example_example_image:u,p2p_image_guidance_scale:t.p2pImageGuidanceScale,enable_controlnet:t.enableControlnet,controlnet_conditioning_scale:t.controlnetConditioningScale,controlnet_method:t.controlnetMethod?t.controlnetMethod:"",powerpaint_task:t.showExtender?kl.outpainting:t.powerpaintTask})});if(d.ok){const m=await d.blob();return{blob:URL.createObjectURL(m),seed:d.headers.get("X-Seed")}}const h=await d.json();throw new Error(`Something went wrong: ${h.errors}`)}async function Lj(){return(await vc.get("/server-config")).data}async function Fj(e){return(await vc.post("/model",{name:e})).data}async function jj(){return(await vc.get("/model")).data}function zj(){return vc.get("/models").then(e=>e.data)}async function gT(e,t,n,r,o){const i=await Ru(n),l=await fetch(`${Ms}/${e?"run_plugin_gen_mask":"run_plugin_gen_image"}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t,image:i,upscale:r,clicks:o})});if(l.ok){const d=await l.blob();return{blob:URL.createObjectURL(d)}}const u=await l.json();throw new Error(u)}async function Bj(e,t){const n=await fetch(`${Ms}/media_file?tab=${e}&filename=${encodeURIComponent(t)}`,{method:"GET"});if(n.ok){const o=await n.blob();return new File([o],t,{type:n.headers.get("Content-Type")??"image/png"})}const r=await n.json();throw new Error(r.errors)}async function Uj(e){return(await vc.get("medias",{params:{tab:e}})).data}async function Vj(e,t,n){const r=await ku(e.src,t,n),o=new FormData;o.append("file",r);try{const i=await fetch(`${Ms}/save_image`,{method:"POST",body:o});if(!i.ok){const s=await i.text();throw new Error(s)}}catch(i){throw new Error(`Something went wrong: ${i}`)}}async function Wj(e){const t=new FormData;return t.append("file",e),(await vc.post("/gen-info",t)).data}async function Hj(e,t,n){const r=await Ru(e),o=await fetch(`${Ms}/adjust_mask`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mask:r,operate:t,kernel_size:n})});if(o.ok)return await o.blob();const i=await o.json();throw new Error(i)}function Kj(){const[e,t]=f.useState(null),n=f.useCallback(()=>{const r=new Headers;r.append("pragma","no-cache"),r.append("cache-control","no-cache"),fetch(`${Ms}/inputimage`,{headers:r}).then(async o=>{var l;if(!o.ok)throw new Error("No input image found");const i=(l=o.headers.get("content-disposition"))==null?void 0:l.split("filename=")[1].split(";")[0],s=await o.blob();if(s&&s.type.startsWith("image")){const u=new File([s],i!==void 0?i:"inputImage");t(u)}}).catch(o=>{console.log(o)})},[t]);return f.useEffect(()=>{n()},[n]),e}function xo(e,t){if(e==null)return{};var n={},r=Object.keys(e),o,i;for(i=0;i=0)&&(n[o]=e[o]);return n}var Yj=["color"],Gj=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,Yj);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),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:r,fillRule:"evenodd",clipRule:"evenodd"}))}),Xj=["color"],vT=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,Xj);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M11.4669 3.72684C11.7558 3.91574 11.8369 4.30308 11.648 4.59198L7.39799 11.092C7.29783 11.2452 7.13556 11.3467 6.95402 11.3699C6.77247 11.3931 6.58989 11.3355 6.45446 11.2124L3.70446 8.71241C3.44905 8.48022 3.43023 8.08494 3.66242 7.82953C3.89461 7.57412 4.28989 7.55529 4.5453 7.78749L6.75292 9.79441L10.6018 3.90792C10.7907 3.61902 11.178 3.53795 11.4669 3.72684Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),Zj=["color"],qj=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,Zj);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M3.13523 6.15803C3.3241 5.95657 3.64052 5.94637 3.84197 6.13523L7.5 9.56464L11.158 6.13523C11.3595 5.94637 11.6759 5.95657 11.8648 6.15803C12.0536 6.35949 12.0434 6.67591 11.842 6.86477L7.84197 10.6148C7.64964 10.7951 7.35036 10.7951 7.15803 10.6148L3.15803 6.86477C2.95657 6.67591 2.94637 6.35949 3.13523 6.15803Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),Qj=["color"],Jj=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,Qj);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M6.1584 3.13508C6.35985 2.94621 6.67627 2.95642 6.86514 3.15788L10.6151 7.15788C10.7954 7.3502 10.7954 7.64949 10.6151 7.84182L6.86514 11.8418C6.67627 12.0433 6.35985 12.0535 6.1584 11.8646C5.95694 11.6757 5.94673 11.3593 6.1356 11.1579L9.565 7.49985L6.1356 3.84182C5.94673 3.64036 5.95694 3.32394 6.1584 3.13508Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),ez=["color"],tz=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,ez);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M3.13523 8.84197C3.3241 9.04343 3.64052 9.05363 3.84197 8.86477L7.5 5.43536L11.158 8.86477C11.3595 9.05363 11.6759 9.04343 11.8648 8.84197C12.0536 8.64051 12.0434 8.32409 11.842 8.13523L7.84197 4.38523C7.64964 4.20492 7.35036 4.20492 7.15803 4.38523L3.15803 8.13523C2.95657 8.32409 2.94637 8.64051 3.13523 8.84197Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),nz=["color"],yT=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,nz);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),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:r,fillRule:"evenodd",clipRule:"evenodd"}))}),rz=["color"],oz=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,rz);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M9.875 7.5C9.875 8.81168 8.81168 9.875 7.5 9.875C6.18832 9.875 5.125 8.81168 5.125 7.5C5.125 6.18832 6.18832 5.125 7.5 5.125C8.81168 5.125 9.875 6.18832 9.875 7.5Z",fill:r}))}),iz=["color"],sz=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,iz);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M10 6.5C10 8.433 8.433 10 6.5 10C4.567 10 3 8.433 3 6.5C3 4.567 4.567 3 6.5 3C8.433 3 10 4.567 10 6.5ZM9.30884 10.0159C8.53901 10.6318 7.56251 11 6.5 11C4.01472 11 2 8.98528 2 6.5C2 4.01472 4.01472 2 6.5 2C8.98528 2 11 4.01472 11 6.5C11 7.56251 10.6318 8.53901 10.0159 9.30884L12.8536 12.1464C13.0488 12.3417 13.0488 12.6583 12.8536 12.8536C12.6583 13.0488 12.3417 13.0488 12.1464 12.8536L9.30884 10.0159Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),az=["color"],lz=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,az);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M3.24182 2.32181C3.3919 2.23132 3.5784 2.22601 3.73338 2.30781L12.7334 7.05781C12.8974 7.14436 13 7.31457 13 7.5C13 7.68543 12.8974 7.85564 12.7334 7.94219L3.73338 12.6922C3.5784 12.774 3.3919 12.7687 3.24182 12.6782C3.09175 12.5877 3 12.4252 3 12.25V2.75C3 2.57476 3.09175 2.4123 3.24182 2.32181ZM4 3.57925V11.4207L11.4288 7.5L4 3.57925Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),cz=["color"],uz=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,cz);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M7 2H1.5C1.22386 2 1 2.22386 1 2.5V7H7V2ZM8 2V7H14V2.5C14 2.22386 13.7761 2 13.5 2H8ZM7 8H1V12.5C1 12.7761 1.22386 13 1.5 13H7V8ZM8 13V8H14V12.5C14 12.7761 13.7761 13 13.5 13H8ZM1.5 1C0.671573 1 0 1.67157 0 2.5V12.5C0 13.3284 0.671573 14 1.5 14H13.5C14.3284 14 15 13.3284 15 12.5V2.5C15 1.67157 14.3284 1 13.5 1H1.5Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),dz=["color"],fz=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,dz);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M1.5 2H13.5C13.7761 2 14 2.22386 14 2.5V7H1V2.5C1 2.22386 1.22386 2 1.5 2ZM1 8V12.5C1 12.7761 1.22386 13 1.5 13H13.5C13.7761 13 14 12.7761 14 12.5V8H1ZM0 2.5C0 1.67157 0.671573 1 1.5 1H13.5C14.3284 1 15 1.67157 15 2.5V12.5C15 13.3284 14.3284 14 13.5 14H1.5C0.671573 14 0 13.3284 0 12.5V2.5Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))});function Y(){return Y=Object.assign?Object.assign.bind():function(e){for(var t=1;te.forEach(n=>pz(n,t))}function Be(...e){return f.useCallback(Am(...e),e)}const Wo=f.forwardRef((e,t)=>{const{children:n,...r}=e,o=f.Children.toArray(n),i=o.find(hz);if(i){const s=i.props.children,l=o.map(u=>u===i?f.Children.count(s)>1?f.Children.only(null):f.isValidElement(s)?s.props.children:null:u);return f.createElement(Qy,Y({},r,{ref:t}),f.isValidElement(s)?f.cloneElement(s,void 0,l):null)}return f.createElement(Qy,Y({},r,{ref:t}),n)});Wo.displayName="Slot";const Qy=f.forwardRef((e,t)=>{const{children:n,...r}=e;return f.isValidElement(n)?f.cloneElement(n,{...mz(r,n.props),ref:t?Am(t,n.ref):n.ref}):f.Children.count(n)>1?f.Children.only(null):null});Qy.displayName="SlotClone";const sx=({children:e})=>f.createElement(f.Fragment,null,e);function hz(e){return f.isValidElement(e)&&e.type===sx}function mz(e,t){const n={...t};for(const r in t){const o=e[r],i=t[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...l)=>{i(...l),o(...l)}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...e,...n}}const bC=e=>typeof e=="boolean"?"".concat(e):e===0?"0":e,_C=BR,Om=(e,t)=>n=>{var r;if((t==null?void 0:t.variants)==null)return _C(e,n==null?void 0:n.class,n==null?void 0:n.className);const{variants:o,defaultVariants:i}=t,s=Object.keys(o).map(d=>{const h=n==null?void 0:n[d],m=i==null?void 0:i[d];if(h===null)return null;const g=bC(h)||bC(m);return o[d][g]}),l=n&&Object.entries(n).reduce((d,h)=>{let[m,g]=h;return g===void 0||(d[m]=g),d},{}),u=t==null||(r=t.compoundVariants)===null||r===void 0?void 0:r.reduce((d,h)=>{let{class:m,className:g,...y}=h;return Object.entries(y).every(x=>{let[_,C]=x;return Array.isArray(C)?C.includes({...i,...l}[_]):{...i,...l}[_]===C})?[...d,m,g]:d},[]);return _C(e,s,u,n==null?void 0:n.class,n==null?void 0:n.className)};var gz={VITE_BACKEND:"http://127.0.0.1:8080",BASE_URL:"/",MODE:"production",DEV:!1,PROD:!0,SSR:!1};function vz(e,t){let n;try{n=e()}catch{return}return{getItem:o=>{var i;const s=u=>u===null?null:JSON.parse(u,t==null?void 0:t.reviver),l=(i=n.getItem(o))!=null?i:null;return l instanceof Promise?l.then(s):s(l)},setItem:(o,i)=>n.setItem(o,JSON.stringify(i,t==null?void 0:t.replacer)),removeItem:o=>n.removeItem(o)}}const qu=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then(r){return qu(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return qu(r)(n)}}}},yz=(e,t)=>(n,r,o)=>{let i={getStorage:()=>localStorage,serialize:JSON.stringify,deserialize:JSON.parse,partialize:C=>C,version:0,merge:(C,S)=>({...S,...C}),...t},s=!1;const l=new Set,u=new Set;let d;try{d=i.getStorage()}catch{}if(!d)return e((...C)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),n(...C)},r,o);const h=qu(i.serialize),m=()=>{const C=i.partialize({...r()});let S;const b=h({state:C,version:i.version}).then(E=>d.setItem(i.name,E)).catch(E=>{S=E});if(S)throw S;return b},g=o.setState;o.setState=(C,S)=>{g(C,S),m()};const y=e((...C)=>{n(...C),m()},r,o);let x;const _=()=>{var C;if(!d)return;s=!1,l.forEach(b=>b(r()));const S=((C=i.onRehydrateStorage)==null?void 0:C.call(i,r()))||void 0;return qu(d.getItem.bind(d))(i.name).then(b=>{if(b)return i.deserialize(b)}).then(b=>{if(b)if(typeof b.version=="number"&&b.version!==i.version){if(i.migrate)return i.migrate(b.state,b.version);console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return b.state}).then(b=>{var E;return x=i.merge(b,(E=r())!=null?E:y),n(x,!0),m()}).then(()=>{S==null||S(x,void 0),s=!0,u.forEach(b=>b(x))}).catch(b=>{S==null||S(void 0,b)})};return o.persist={setOptions:C=>{i={...i,...C},C.getStorage&&(d=C.getStorage())},clearStorage:()=>{d==null||d.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>_(),hasHydrated:()=>s,onHydrate:C=>(l.add(C),()=>{l.delete(C)}),onFinishHydration:C=>(u.add(C),()=>{u.delete(C)})},_(),x||y},wz=(e,t)=>(n,r,o)=>{let i={storage:vz(()=>localStorage),partialize:_=>_,version:0,merge:(_,C)=>({...C,..._}),...t},s=!1;const l=new Set,u=new Set;let d=i.storage;if(!d)return e((..._)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),n(..._)},r,o);const h=()=>{const _=i.partialize({...r()});return d.setItem(i.name,{state:_,version:i.version})},m=o.setState;o.setState=(_,C)=>{m(_,C),h()};const g=e((..._)=>{n(..._),h()},r,o);let y;const x=()=>{var _,C;if(!d)return;s=!1,l.forEach(b=>{var E;return b((E=r())!=null?E:g)});const S=((C=i.onRehydrateStorage)==null?void 0:C.call(i,(_=r())!=null?_:g))||void 0;return qu(d.getItem.bind(d))(i.name).then(b=>{if(b)if(typeof b.version=="number"&&b.version!==i.version){if(i.migrate)return i.migrate(b.state,b.version);console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return b.state}).then(b=>{var E;return y=i.merge(b,(E=r())!=null?E:g),n(y,!0),h()}).then(()=>{S==null||S(y,void 0),y=r(),s=!0,u.forEach(b=>b(y))}).catch(b=>{S==null||S(void 0,b)})};return o.persist={setOptions:_=>{i={...i,..._},_.storage&&(d=_.storage)},clearStorage:()=>{d==null||d.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>x(),hasHydrated:()=>s,onHydrate:_=>(l.add(_),()=>{l.delete(_)}),onFinishHydration:_=>(u.add(_),()=>{u.delete(_)})},i.skipHydration||x(),y||g},xz=(e,t)=>"getStorage"in t||"serialize"in t||"deserialize"in t?((gz?"production":void 0)!=="production"&&console.warn("[DEPRECATED] `getStorage`, `serialize` and `deserialize` options are deprecated. Use `storage` option instead."),yz(e,t)):wz(e,t),bz=xz;function _z(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,o]of e)if(!Object.is(o,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{t(n,r,e)}):e.forEach((n,r)=>t(r,n,e))}function Mm(e){const t=e[wr];return t?t.type_:Array.isArray(e)?1:Nm(e)?2:Dm(e)?3:0}function Jy(e,t){return Mm(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function bT(e,t,n){const r=Mm(e);r===2?e.set(t,n):r===3?e.add(n):e[t]=n}function Ez(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function Nm(e){return e instanceof Map}function Dm(e){return e instanceof Set}function Js(e){return e.copy_||e.base_}function e1(e,t){if(Nm(e))return new Map(e);if(Dm(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);if(!t&&xT(e))return ec(e)?{...e}:Object.assign(Object.create(null),e);const n=Object.getOwnPropertyDescriptors(e);delete n[wr];let r=Reflect.ownKeys(n);for(let o=0;o1&&(e.set=e.add=e.clear=e.delete=Cz),Object.freeze(e),t&&Qu(e,(n,r)=>ax(r,!0))),e}function Cz(){ho(2)}function Im(e){return Object.isFrozen(e)}var $z={};function ka(e){const t=$z[e];return t||ho(0,e),t}var Ju;function _T(){return Ju}function kz(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function EC(e,t){t&&(ka("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function t1(e){n1(e),e.drafts_.forEach(Rz),e.drafts_=null}function n1(e){e===Ju&&(Ju=e.parent_)}function CC(e){return Ju=kz(Ju,e)}function Rz(e){const t=e[wr];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function $C(e,t){t.unfinalizedDrafts_=t.drafts_.length;const n=t.drafts_[0];return e!==void 0&&e!==n?(n[wr].modified_&&(t1(t),ho(4)),$a(e)&&(e=Ah(t,e),t.parent_||Oh(t,e)),t.patches_&&ka("Patches").generateReplacementPatches_(n[wr].base_,e,t.patches_,t.inversePatches_)):e=Ah(t,n,[]),t1(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==wT?e:void 0}function Ah(e,t,n){if(Im(t))return t;const r=t[wr];if(!r)return Qu(t,(o,i)=>kC(e,r,t,o,i,n)),t;if(r.scope_!==e)return t;if(!r.modified_)return Oh(e,r.base_,!0),r.base_;if(!r.finalized_){r.finalized_=!0,r.scope_.unfinalizedDrafts_--;const o=r.copy_;let i=o,s=!1;r.type_===3&&(i=new Set(o),o.clear(),s=!0),Qu(i,(l,u)=>kC(e,r,o,l,u,n,s)),Oh(e,o,!1),n&&e.patches_&&ka("Patches").generatePatches_(r,n,e.patches_,e.inversePatches_)}return r.copy_}function kC(e,t,n,r,o,i,s){if(tc(o)){const l=i&&t&&t.type_!==3&&!Jy(t.assigned_,r)?i.concat(r):void 0,u=Ah(e,o,l);if(bT(n,r,u),tc(u))e.canAutoFreeze_=!1;else return}else s&&n.add(o);if($a(o)&&!Im(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;Ah(e,o),(!t||!t.scope_.parent_)&&Oh(e,o)}}function Oh(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&ax(t,n)}function Tz(e,t){const n=Array.isArray(e),r={type_:n?1:0,scope_:t?t.scope_:_T(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1};let o=r,i=lx;n&&(o=[r],i=ed);const{revoke:s,proxy:l}=Proxy.revocable(o,i);return r.draft_=l,r.revoke_=s,l}var lx={get(e,t){if(t===wr)return e;const n=Js(e);if(!Jy(n,t))return Pz(e,n,t);const r=n[t];return e.finalized_||!$a(r)?r:r===h0(e.base_,t)?(m0(e),e.copy_[t]=o1(r,e)):r},has(e,t){return t in Js(e)},ownKeys(e){return Reflect.ownKeys(Js(e))},set(e,t,n){const r=ST(Js(e),t);if(r!=null&&r.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){const o=h0(Js(e),t),i=o==null?void 0:o[wr];if(i&&i.base_===n)return e.copy_[t]=n,e.assigned_[t]=!1,!0;if(Ez(n,o)&&(n!==void 0||Jy(e.base_,t)))return!0;m0(e),r1(e)}return e.copy_[t]===n&&(n!==void 0||t in e.copy_)||Number.isNaN(n)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=n,e.assigned_[t]=!0),!0},deleteProperty(e,t){return h0(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,m0(e),r1(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){const n=Js(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:r.enumerable,value:n[t]}},defineProperty(){ho(11)},getPrototypeOf(e){return ec(e.base_)},setPrototypeOf(){ho(12)}},ed={};Qu(lx,(e,t)=>{ed[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});ed.deleteProperty=function(e,t){return ed.set.call(this,e,t,void 0)};ed.set=function(e,t,n){return lx.set.call(this,e[0],t,n,e[0])};function h0(e,t){const n=e[wr];return(n?Js(n):e)[t]}function Pz(e,t,n){var o;const r=ST(t,n);return r?"value"in r?r.value:(o=r.get)==null?void 0:o.call(e.draft_):void 0}function ST(e,t){if(!(t in e))return;let n=ec(e);for(;n;){const r=Object.getOwnPropertyDescriptor(n,t);if(r)return r;n=ec(n)}}function r1(e){e.modified_||(e.modified_=!0,e.parent_&&r1(e.parent_))}function m0(e){e.copy_||(e.copy_=e1(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var Az=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(t,n,r)=>{if(typeof t=="function"&&typeof n!="function"){const i=n;n=t;const s=this;return function(u=i,...d){return s.produce(u,h=>n.call(this,h,...d))}}typeof n!="function"&&ho(6),r!==void 0&&typeof r!="function"&&ho(7);let o;if($a(t)){const i=CC(this),s=o1(t,void 0);let l=!0;try{o=n(s),l=!1}finally{l?t1(i):n1(i)}return EC(i,r),$C(o,i)}else if(!t||typeof t!="object"){if(o=n(t),o===void 0&&(o=t),o===wT&&(o=void 0),this.autoFreeze_&&ax(o,!0),r){const i=[],s=[];ka("Patches").generateReplacementPatches_(t,o,i,s),r(i,s)}return o}else ho(1,t)},this.produceWithPatches=(t,n)=>{if(typeof t=="function")return(s,...l)=>this.produceWithPatches(s,u=>t(u,...l));let r,o;return[this.produce(t,n,(s,l)=>{r=s,o=l}),r,o]},typeof(e==null?void 0:e.autoFreeze)=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof(e==null?void 0:e.useStrictShallowCopy)=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){$a(e)||ho(8),tc(e)&&(e=Oz(e));const t=CC(this),n=o1(e,void 0);return n[wr].isManual_=!0,n1(t),n}finishDraft(e,t){const n=e&&e[wr];(!n||!n.isManual_)&&ho(9);const{scope_:r}=n;return EC(r,t),$C(void 0,r)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let n;for(n=t.length-1;n>=0;n--){const o=t[n];if(o.path.length===0&&o.op==="replace"){e=o.value;break}}n>-1&&(t=t.slice(n+1));const r=ka("Patches").applyPatches_;return tc(e)?r(e,t):this.produce(e,o=>r(o,t))}};function o1(e,t){const n=Nm(e)?ka("MapSet").proxyMap_(e,t):Dm(e)?ka("MapSet").proxySet_(e,t):Tz(e,t);return(t?t.scope_:_T()).drafts_.push(n),n}function Oz(e){return tc(e)||ho(10,e),ET(e)}function ET(e){if(!$a(e)||Im(e))return e;const t=e[wr];let n;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=e1(e,t.scope_.immer_.useStrictShallowCopy_)}else n=e1(e,!0);return Qu(n,(r,o)=>{bT(n,r,ET(o))}),t&&(t.finalized_=!1),n}var xr=new Az,Mz=xr.produce;xr.produceWithPatches.bind(xr);xr.setAutoFreeze.bind(xr);xr.setUseStrictShallowCopy.bind(xr);xr.applyPatches.bind(xr);xr.createDraft.bind(xr);xr.finishDraft.bind(xr);const Nz=e=>(t,n,r)=>(r.setState=(o,i,...s)=>{const l=typeof o=="function"?Mz(o):o;return t(l,i,...s)},e(r.setState,n,r)),Dz=Nz;var CT={exports:{}},$T={},kT={exports:{}},RT={};/** + * @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 nc=f;function Iz(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var Lz=typeof Object.is=="function"?Object.is:Iz,Fz=nc.useState,jz=nc.useEffect,zz=nc.useLayoutEffect,Bz=nc.useDebugValue;function Uz(e,t){var n=t(),r=Fz({inst:{value:n,getSnapshot:t}}),o=r[0].inst,i=r[1];return zz(function(){o.value=n,o.getSnapshot=t,g0(o)&&i({inst:o})},[e,n,t]),jz(function(){return g0(o)&&i({inst:o}),e(function(){g0(o)&&i({inst:o})})},[e]),Bz(n),n}function g0(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!Lz(e,n)}catch{return!0}}function Vz(e,t){return t()}var Wz=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?Vz:Uz;RT.useSyncExternalStore=nc.useSyncExternalStore!==void 0?nc.useSyncExternalStore:Wz;kT.exports=RT;var Hz=kT.exports;/** + * @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 Lm=f,Kz=Hz;function Yz(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var Gz=typeof Object.is=="function"?Object.is:Yz,Xz=Kz.useSyncExternalStore,Zz=Lm.useRef,qz=Lm.useEffect,Qz=Lm.useMemo,Jz=Lm.useDebugValue;$T.useSyncExternalStoreWithSelector=function(e,t,n,r,o){var i=Zz(null);if(i.current===null){var s={hasValue:!1,value:null};i.current=s}else s=i.current;i=Qz(function(){function u(y){if(!d){if(d=!0,h=y,y=r(y),o!==void 0&&s.hasValue){var x=s.value;if(o(x,y))return m=x}return m=y}if(x=m,Gz(h,y))return x;var _=r(y);return o!==void 0&&o(x,_)?x:(h=y,m=_)}var d=!1,h,m,g=n===void 0?null:n;return[function(){return u(t())},g===null?void 0:function(){return u(g())}]},[t,n,r,o]);var l=Xz(e,i[0],i[1]);return qz(function(){s.hasValue=!0,s.value=l},[l]),Jz(l),l};CT.exports=$T;var eB=CT.exports;const tB=lm(eB);var nB={VITE_BACKEND:"http://127.0.0.1:8080",BASE_URL:"/",MODE:"production",DEV:!1,PROD:!0,SSR:!1};const RC=e=>{let t;const n=new Set,r=(u,d)=>{const h=typeof u=="function"?u(t):u;if(!Object.is(h,t)){const m=t;t=d??typeof h!="object"?h:Object.assign({},t,h),n.forEach(g=>g(t,m))}},o=()=>t,l={setState:r,getState:o,subscribe:u=>(n.add(u),()=>n.delete(u)),destroy:()=>{(nB?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),n.clear()}};return t=e(r,o,l),l},rB=e=>e?RC(e):RC,{useDebugValue:oB}=Fe,{useSyncExternalStoreWithSelector:iB}=tB;function sB(e,t=e.getState,n){const r=iB(e.subscribe,e.getState,e.getServerState||e.getState,t,n);return oB(r),r}const TC=(e,t)=>{const n=rB(e),r=(o,i=t)=>sB(n,o,i);return Object.assign(r,n),r},aB=(e,t)=>e?TC(e,t):TC,lB=1,cB=1e6;let v0=0;function uB(){return v0=(v0+1)%Number.MAX_VALUE,v0.toString()}const y0=new Map,PC=e=>{if(y0.has(e))return;const t=setTimeout(()=>{y0.delete(e),Tu({type:"REMOVE_TOAST",toastId:e})},cB);y0.set(e,t)},dB=(e,t)=>{switch(t.type){case"ADD_TOAST":return{...e,toasts:[t.toast,...e.toasts].slice(0,lB)};case"UPDATE_TOAST":return{...e,toasts:e.toasts.map(n=>n.id===t.toast.id?{...n,...t.toast}:n)};case"DISMISS_TOAST":{const{toastId:n}=t;return n?PC(n):e.toasts.forEach(r=>{PC(r.id)}),{...e,toasts:e.toasts.map(r=>r.id===n||n===void 0?{...r,open:!1}:r)}}case"REMOVE_TOAST":return t.toastId===void 0?{...e,toasts:[]}:{...e,toasts:e.toasts.filter(n=>n.id!==t.toastId)}}},Bp=[];let Up={toasts:[]};function Tu(e){Up=dB(Up,e),Bp.forEach(t=>{t(Up)})}function rl({...e}){const t=uB(),n=o=>Tu({type:"UPDATE_TOAST",toast:{...o,id:t}}),r=()=>Tu({type:"DISMISS_TOAST",toastId:t});return Tu({type:"ADD_TOAST",toast:{...e,id:t,open:!0,onOpenChange:o=>{o||r()}}}),{id:t,dismiss:r,update:n}}function Td(){const[e,t]=f.useState(Up);return f.useEffect(()=>(Bp.push(t),()=>{const n=Bp.indexOf(t);n>-1&&Bp.splice(n,1)}),[e]),{...e,toast:rl,dismiss:n=>Tu({type:"DISMISS_TOAST",toastId:n})}}const Zs={file:null,paintByExampleFile:null,customMask:null,imageHeight:0,imageWidth:0,isInpainting:!1,isPluginRunning:!1,isAdjustingMask:!1,disableShortCuts:!1,windowSize:{height:600,width:800},editorState:{baseBrushSize:sF,brushSizeScale:1,renders:[],extraMasks:[],prevExtraMasks:[],temporaryMasks:[],lineGroups:[],lastLineGroup:[],curLineGroup:[],redoRenders:[],redoCurLines:[],redoLineGroups:[]},interactiveSegState:{isInteractiveSeg:!1,tmpInteractiveSegMask:null,clicks:[]},cropperState:{x:0,y:0,width:512,height:512},extenderState:{x:0,y:0,width:512,height:512},isCropperExtenderResizing:!1,fileManagerState:{sortBy:xs.CTIME,sortOrder:$u.DESCENDING,layout:"masonry",searchText:"",inputDirectory:"",outputDirectory:""},serverConfig:{plugins:[],enableFileManager:!1,enableAutoSaving:!1,enableControlnet:!1,controlnetMethod:"lllyasviel/control_v11p_sd15_canny",disableModelSwitch:!1,isDesktop:!1,samplers:["DPM++ 2M"]},settings:{model:{name:"lama",path:"lama",model_type:"inpaint",support_controlnet:!1,support_strength:!1,support_outpainting:!1,controlnets:[],support_freeu:!1,support_lcm_lora:!1,is_single_file_diffusers:!1,need_prompt:!1},enableControlnet:!1,showCropper:!1,showExtender:!1,extenderDirection:In.xy,enableDownloadMask:!1,enableManualInpainting:!1,enableUploadMask:!1,enableAutoExtractPrompt:!0,ldmSteps:30,ldmSampler:Zw.ddim,zitsWireframe:!0,cv2Radius:5,cv2Flag:qw.INPAINT_NS,prompt:"",negativePrompt:cF,seed:42,seedFixed:!1,sdMaskBlur:35,sdStrength:1,sdSteps:50,sdGuidanceScale:7.5,sdSampler:"DPM++ 2M",sdMatchHistograms:!1,sdScale:1,p2pImageGuidanceScale:1.5,controlnetConditioningScale:.4,controlnetMethod:"lllyasviel/control_v11p_sd15_canny",enableLCMLora:!1,enableFreeu:!1,freeuConfig:{s1:.9,s2:.2,b1:1.2,b2:1.4},powerpaintTask:kl.text_guided,adjustMaskKernelSize:12}},bt=aB()(bz(Dz((e,t)=>({...Zs,showPrevMask:async()=>{if(t().settings.showExtender)return;const{lastLineGroup:n,curLineGroup:r,prevExtraMasks:o,extraMasks:i}=t().editorState;if(r.length!==0||i.length!==0)return;const{imageWidth:s,imageHeight:l}=t(),u=Lp(s,l,[n],o,Ky);try{const d=await aC(u);e(h=>{h.editorState.temporaryMasks.push(d)})}catch(d){console.error(d);return}},hidePrevMask:()=>{e(n=>{n.editorState.temporaryMasks=[]})},getCurrentTargetFile:async()=>{const n=t().file,r=t().editorState.renders;let o=n;if(r.length>0){const i=r[r.length-1];o=await ku(i.currentSrc,n.name,n.type)}return o},runInpainting:async()=>{const{isInpainting:n,file:r,paintByExampleFile:o,imageWidth:i,imageHeight:s,settings:l,cropperState:u,extenderState:d}=t();if(n||r===null||t().settings.model.support_outpainting&&l.showExtender&&d.height===s&&d.width===i)return;const{lastLineGroup:h,curLineGroup:m,lineGroups:g,renders:y,prevExtraMasks:x,extraMasks:_}=t().editorState,C=m.length===0&&_.length===0&&!l.showExtender;let S=[],b=[];if(C===!0?(b=h,S=x):(b=m,S=_),b.length===0&&S===null&&!l.showExtender){rl({variant:"destructive",description:"Please draw mask on picture"});return}const E=[...g,b];e(M=>{M.isInpainting=!0});let k=r;if(C===!0){if(y.length>1){const M=y[y.length-2];k=await ku(M.currentSrc,r.name,r.type)}}else if(y.length>0){const M=y[y.length-1];k=await ku(M.currentSrc,r.name,r.type)}const P=Lp(i,s,[b],S);if(C){const M=await aC(P);e(A=>{A.editorState.temporaryMasks=[M]})}try{const M=await Ij(k,l,u,d,sC(P.toDataURL()),o),{blob:A,seed:O}=M;O&&t().setSeed(parseInt(O,10));const F=new Image;await Ip(F,A);const V=[...y,F];t().setImageSize(F.width,F.height),t().updateEditorState({renders:V,lineGroups:E,lastLineGroup:b,curLineGroup:[],extraMasks:[],prevExtraMasks:S})}catch(M){rl({variant:"destructive",description:M.message?M.message:M.toString()})}t().resetRedoState(),e(M=>{M.isInpainting=!1,M.editorState.temporaryMasks=[]})},runRenderablePlugin:async(n,r,o={upscale:1})=>{const{renders:i,lineGroups:s}=t().editorState;e(l=>{l.isPluginRunning=!0});try{const l=new Date,u=await t().getCurrentTargetFile(),d=await gT(n,r,u,o.upscale),{blob:h}=d;if(n){const y=new Image;await Ip(y,h),e(x=>{x.editorState.extraMasks.push(y)})}else{const y=new Image;await Ip(y,h),t().setImageSize(y.width,y.height);const x=[...i,y],_=[...s,[]];t().updateEditorState({renders:x,lineGroups:_})}const g=new Date().getTime()-l.getTime();rl({description:`Run ${r} successfully in ${g/1e3}s`})}catch(l){rl({variant:"destructive",description:l.message?l.message:l.toString()})}e(l=>{l.isPluginRunning=!1})},updateEditorState:n=>{e(r=>{r.editorState={...r.editorState,...n}})},cleanCurLineGroup:()=>{t().updateEditorState({curLineGroup:[]})},handleCanvasMouseDown:n=>{let r=[];const o=t();o.runMannually()&&(r=[...o.editorState.curLineGroup]),r.push({size:o.getBrushSize(),pts:[n]}),e(i=>{i.editorState.curLineGroup=r})},handleCanvasMouseMove:n=>{e(r=>{const o=r.editorState.curLineGroup;o.length&&o[o.length-1].pts.push(n)})},runMannually:()=>{const n=t();return n.settings.enableManualInpainting||n.settings.model.model_type!==is},getIsProcessing:()=>t().isInpainting||t().isPluginRunning||t().isAdjustingMask,isSD:()=>t().settings.model.model_type!==is,undoDisabled:()=>{const n=t().editorState;if(n.renders.length>0)return!1;if(t().runMannually()){if(n.curLineGroup.length===0)return!0}else if(n.renders.length===0)return!0;return!1},undo:()=>{t().runMannually()&&t().editorState.curLineGroup.length!==0?e(n=>{const r=n.editorState;if(r.curLineGroup.length===0)return;r.lastLineGroup=[];const o=r.curLineGroup.pop();r.redoCurLines.push(o)}):e(n=>{const r=n.editorState;if(r.renders.length===0||r.lineGroups.length===0)return;const o=r.lineGroups.pop();r.redoLineGroups.push(o),r.redoCurLines=[],r.curLineGroup=[];const i=r.renders.pop();r.redoRenders.push(i)})},redoDisabled:()=>{const n=t().editorState;if(n.redoRenders.length>0)return!1;if(t().runMannually()){if(n.redoCurLines.length===0)return!0}else if(n.redoRenders.length===0)return!0;return!1},redo:()=>{t().runMannually()&&t().editorState.redoCurLines.length!==0?e(n=>{const r=n.editorState;if(r.redoCurLines.length===0)return;const o=r.redoCurLines.pop();r.curLineGroup.push(o)}):e(n=>{const r=n.editorState;if(r.redoRenders.length===0||r.redoLineGroups.length===0)return;const o=r.redoLineGroups.pop();r.lineGroups.push(o),r.curLineGroup=[];const i=r.redoRenders.pop();r.renders.push(i)})},resetRedoState:()=>{e(n=>{n.editorState.redoCurLines=[],n.editorState.redoLineGroups=[],n.editorState.redoRenders=[]})},updateAppState:n=>{e(()=>n)},getBrushSize:()=>t().editorState.baseBrushSize*t().editorState.brushSizeScale,showPromptInput:()=>{const n=t().settings.model;return n.model_type!==is&&n.name!==YR},setServerConfig:n=>{e(r=>{r.serverConfig=n,r.settings.enableControlnet=n.enableControlnet,r.settings.controlnetMethod=n.controlnetMethod})},updateSettings:n=>{e(r=>{r.settings={...r.settings,...n}})},setModel:n=>{e(r=>{r.settings.model=n,n.support_controlnet&&!n.controlnets.includes(r.settings.controlnetMethod)&&(r.settings.controlnetMethod=n.controlnets[0])})},updateFileManagerState:n=>{e(r=>{r.fileManagerState={...r.fileManagerState,...n}})},updateInteractiveSegState:n=>{e(r=>({...r,interactiveSegState:{...r.interactiveSegState,...n}}))},resetInteractiveSegState:()=>{t().updateInteractiveSegState(Zs.interactiveSegState)},handleInteractiveSegAccept:()=>{e(n=>{n.interactiveSegState.tmpInteractiveSegMask&&n.editorState.extraMasks.push(n.interactiveSegState.tmpInteractiveSegMask),n.interactiveSegState={...Zs.interactiveSegState}})},setIsInpainting:n=>e(r=>{r.isInpainting=n}),setFile:async n=>{if(t().settings.enableAutoExtractPrompt)try{const r=await Wj(n);r.prompt&&e(o=>{o.settings.prompt=r.prompt}),r.negative_prompt&&e(o=>{o.settings.negativePrompt=r.negative_prompt})}catch(r){rl({variant:"destructive",description:r.message?r.message:r.toString()})}e(r=>{r.file=n,r.interactiveSegState=Zs.interactiveSegState,r.editorState=Zs.editorState,r.cropperState=Zs.cropperState})},setCustomFile:n=>e(r=>{r.customMask=n}),setBaseBrushSize:n=>e(r=>{r.editorState.baseBrushSize=n}),setImageSize:(n,r)=>{e(o=>{o.imageWidth=n,o.imageHeight=r,o.editorState.brushSizeScale=Math.max(Math.min(n,r),512)/512}),t().resetExtender(n,r)},setCropperX:n=>e(r=>{r.cropperState.x=n}),setCropperY:n=>e(r=>{r.cropperState.y=n}),setCropperWidth:n=>e(r=>{r.cropperState.width=n}),setCropperHeight:n=>e(r=>{r.cropperState.height=n}),setExtenderX:n=>e(r=>{r.extenderState.x=n}),setExtenderY:n=>e(r=>{r.extenderState.y=n}),setExtenderWidth:n=>e(r=>{r.extenderState.width=n}),setExtenderHeight:n=>e(r=>{r.extenderState.height=n}),setIsCropperExtenderResizing:n=>e(r=>{r.isCropperExtenderResizing=n}),updateExtenderDirection:n=>{console.log(`updateExtenderDirection: ${JSON.stringify(t().extenderState)}`),e(r=>{r.settings.extenderDirection=n,r.extenderState.x=0,r.extenderState.y=0,r.extenderState.width=r.imageWidth,r.extenderState.height=r.imageHeight}),t().updateExtenderByBuiltIn(n,1.5)},updateExtenderByBuiltIn:(n,r)=>{const o={...Zs.extenderState};let{x:i,y:s,width:l,height:u}=o;const{imageWidth:d,imageHeight:h}=t();switch(l=d,u=h,n){case In.x:i=-Math.ceil(d*(r-1)/2),l=Math.ceil(d*r);break;case In.y:s=-Math.ceil(h*(r-1)/2),u=Math.ceil(h*r);break;case In.xy:i=-Math.ceil(d*(r-1)/2),s=-Math.ceil(h*(r-1)/2),l=Math.ceil(d*r),u=Math.ceil(h*r);break}e(m=>{m.extenderState.x=i,m.extenderState.y=s,m.extenderState.width=l,m.extenderState.height=u})},resetExtender:(n,r)=>{e(o=>{o.extenderState.x=0,o.extenderState.y=0,o.extenderState.width=n,o.extenderState.height=r})},setSeed:n=>e(r=>{r.settings.seed=n}),adjustMask:async n=>{const{imageWidth:r,imageHeight:o}=t(),{curLineGroup:i,extraMasks:s}=t().editorState,{adjustMaskKernelSize:l}=t().settings;if(i.length===0&&s.length===0)return;e(g=>{g.isAdjustingMask=!0});const u=Lp(r,o,[i],s,Ky),d=sC(u.toDataURL()),h=await Hj(d,n,l),m=await dF(h);e(g=>{g.editorState.extraMasks=[m],g.editorState.curLineGroup=[]}),e(g=>{g.isAdjustingMask=!1})},clearMask:()=>{e(n=>{n.editorState.extraMasks=[],n.editorState.curLineGroup=[]})}})),{name:"ZUSTAND_STATE",version:1,partialize:e=>Object.fromEntries(Object.entries(e).filter(([t])=>["fileManagerState","settings"].includes(t)))}),_z),Pd=f.forwardRef(({className:e,type:t,...n},r)=>{const o=bt(l=>l.updateAppState),i=()=>{o({disableShortCuts:!0})},s=()=>{o({disableShortCuts:!1})};return v.jsx("input",{type:t,className:Ce("flex h-8 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",e),ref:r,autoComplete:"off",tabIndex:-1,onFocus:i,onBlur:s,...n})});Pd.displayName="Input";const Gn=f.forwardRef(({numberValue:e,allowFloat:t,onNumberValueChange:n,...r},o)=>{const[i,s]=f.useState(e.toString());f.useEffect(()=>{i!==e.toString()+"."&&s(e.toString())},[e]);const l=u=>{let h=u.target.value;if(t){if(h=h.replace(/[^0-9.]/g,"").replace(/(\..*?)\..*/g,"$1"),h.length===0){n(0);return}n(parseFloat(h))}else{if(h=h.replace(/\D/g,""),h.length===0){n(0);return}n(parseInt(h,10))}s(h)};return v.jsx(Pd,{ref:o,value:i,onInput:l,...r})});function ue(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 fB(e,t){const n=f.createContext(t);function r(i){const{children:s,...l}=i,u=f.useMemo(()=>l,Object.values(l));return f.createElement(n.Provider,{value:u},s)}function o(i){const s=f.useContext(n);if(s)return s;if(t!==void 0)return t;throw new Error(`\`${i}\` must be used within \`${e}\``)}return r.displayName=e+"Provider",[r,o]}function An(e,t=[]){let n=[];function r(i,s){const l=f.createContext(s),u=n.length;n=[...n,s];function d(m){const{scope:g,children:y,...x}=m,_=(g==null?void 0:g[e][u])||l,C=f.useMemo(()=>x,Object.values(x));return f.createElement(_.Provider,{value:C},y)}function h(m,g){const y=(g==null?void 0:g[e][u])||l,x=f.useContext(y);if(x)return x;if(s!==void 0)return s;throw new Error(`\`${m}\` must be used within \`${i}\``)}return d.displayName=i+"Provider",[d,h]}const o=()=>{const i=n.map(s=>f.createContext(s));return function(l){const u=(l==null?void 0:l[e])||i;return f.useMemo(()=>({[`__scope${e}`]:{...l,[e]:u}}),[l,u])}};return o.scopeName=e,[r,pB(o,...t)]}function pB(...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(i){const s=r.reduce((l,{useScope:u,scopeName:d})=>{const m=u(i)[`__scope${d}`];return{...l,...m}},{});return f.useMemo(()=>({[`__scope${t.scopeName}`]:s}),[s])}};return n.scopeName=t.scopeName,n}const hB=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","span","svg","ul"],Pe=hB.reduce((e,t)=>{const n=f.forwardRef((r,o)=>{const{asChild:i,...s}=r,l=i?Wo:t;return f.useEffect(()=>{window[Symbol.for("radix-ui")]=!0},[]),f.createElement(l,Y({},s,{ref:o}))});return n.displayName=`Primitive.${t}`,{...e,[t]:n}},{});function cx(e,t){e&&Os.flushSync(()=>e.dispatchEvent(t))}function Ft(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)},[])}function mB(e,t=globalThis==null?void 0:globalThis.document){const n=Ft(e);f.useEffect(()=>{const r=o=>{o.key==="Escape"&&n(o)};return t.addEventListener("keydown",r),()=>t.removeEventListener("keydown",r)},[n,t])}const i1="dismissableLayer.update",gB="dismissableLayer.pointerDownOutside",vB="dismissableLayer.focusOutside";let AC;const TT=f.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),yc=f.forwardRef((e,t)=>{var n;const{disableOutsidePointerEvents:r=!1,onEscapeKeyDown:o,onPointerDownOutside:i,onFocusOutside:s,onInteractOutside:l,onDismiss:u,...d}=e,h=f.useContext(TT),[m,g]=f.useState(null),y=(n=m==null?void 0:m.ownerDocument)!==null&&n!==void 0?n:globalThis==null?void 0:globalThis.document,[,x]=f.useState({}),_=Be(t,O=>g(O)),C=Array.from(h.layers),[S]=[...h.layersWithOutsidePointerEventsDisabled].slice(-1),b=C.indexOf(S),E=m?C.indexOf(m):-1,k=h.layersWithOutsidePointerEventsDisabled.size>0,P=E>=b,M=wB(O=>{const F=O.target,V=[...h.branches].some(J=>J.contains(F));!P||V||(i==null||i(O),l==null||l(O),O.defaultPrevented||u==null||u())},y),A=xB(O=>{const F=O.target;[...h.branches].some(J=>J.contains(F))||(s==null||s(O),l==null||l(O),O.defaultPrevented||u==null||u())},y);return mB(O=>{E===h.layers.size-1&&(o==null||o(O),!O.defaultPrevented&&u&&(O.preventDefault(),u()))},y),f.useEffect(()=>{if(m)return r&&(h.layersWithOutsidePointerEventsDisabled.size===0&&(AC=y.body.style.pointerEvents,y.body.style.pointerEvents="none"),h.layersWithOutsidePointerEventsDisabled.add(m)),h.layers.add(m),OC(),()=>{r&&h.layersWithOutsidePointerEventsDisabled.size===1&&(y.body.style.pointerEvents=AC)}},[m,y,r,h]),f.useEffect(()=>()=>{m&&(h.layers.delete(m),h.layersWithOutsidePointerEventsDisabled.delete(m),OC())},[m,h]),f.useEffect(()=>{const O=()=>x({});return document.addEventListener(i1,O),()=>document.removeEventListener(i1,O)},[]),f.createElement(Pe.div,Y({},d,{ref:_,style:{pointerEvents:k?P?"auto":"none":void 0,...e.style},onFocusCapture:ue(e.onFocusCapture,A.onFocusCapture),onBlurCapture:ue(e.onBlurCapture,A.onBlurCapture),onPointerDownCapture:ue(e.onPointerDownCapture,M.onPointerDownCapture)}))}),yB=f.forwardRef((e,t)=>{const n=f.useContext(TT),r=f.useRef(null),o=Be(t,r);return f.useEffect(()=>{const i=r.current;if(i)return n.branches.add(i),()=>{n.branches.delete(i)}},[n.branches]),f.createElement(Pe.div,Y({},e,{ref:o}))});function wB(e,t=globalThis==null?void 0:globalThis.document){const n=Ft(e),r=f.useRef(!1),o=f.useRef(()=>{});return f.useEffect(()=>{const i=l=>{if(l.target&&!r.current){let h=function(){PT(gB,n,d,{discrete:!0})};var u=h;const d={originalEvent:l};l.pointerType==="touch"?(t.removeEventListener("click",o.current),o.current=h,t.addEventListener("click",o.current,{once:!0})):h()}else t.removeEventListener("click",o.current);r.current=!1},s=window.setTimeout(()=>{t.addEventListener("pointerdown",i)},0);return()=>{window.clearTimeout(s),t.removeEventListener("pointerdown",i),t.removeEventListener("click",o.current)}},[t,n]),{onPointerDownCapture:()=>r.current=!0}}function xB(e,t=globalThis==null?void 0:globalThis.document){const n=Ft(e),r=f.useRef(!1);return f.useEffect(()=>{const o=i=>{i.target&&!r.current&&PT(vB,n,{originalEvent:i},{discrete:!1})};return t.addEventListener("focusin",o),()=>t.removeEventListener("focusin",o)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function OC(){const e=new CustomEvent(i1);document.dispatchEvent(e)}function PT(e,t,n,{discrete:r}){const o=n.originalEvent.target,i=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&o.addEventListener(e,t,{once:!0}),r?cx(o,i):o.dispatchEvent(i)}const bB=yc,_B=yB,Pn=globalThis!=null&&globalThis.document?f.useLayoutEffect:()=>{},SB=jD.useId||(()=>{});let EB=0;function nr(e){const[t,n]=f.useState(SB());return Pn(()=>{e||n(r=>r??String(EB++))},[e]),e||(t?`radix-${t}`:"")}const CB=["top","right","bottom","left"],Cs=Math.min,pr=Math.max,Mh=Math.round,ip=Math.floor,$s=e=>({x:e,y:e}),$B={left:"right",right:"left",bottom:"top",top:"bottom"},kB={start:"end",end:"start"};function s1(e,t,n){return pr(e,Cs(t,n))}function yi(e,t){return typeof e=="function"?e(t):e}function wi(e){return e.split("-")[0]}function wc(e){return e.split("-")[1]}function ux(e){return e==="x"?"y":"x"}function dx(e){return e==="y"?"height":"width"}function xc(e){return["top","bottom"].includes(wi(e))?"y":"x"}function fx(e){return ux(xc(e))}function RB(e,t,n){n===void 0&&(n=!1);const r=wc(e),o=fx(e),i=dx(o);let s=o==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[i]>t.floating[i]&&(s=Nh(s)),[s,Nh(s)]}function TB(e){const t=Nh(e);return[a1(e),t,a1(t)]}function a1(e){return e.replace(/start|end/g,t=>kB[t])}function PB(e,t,n){const r=["left","right"],o=["right","left"],i=["top","bottom"],s=["bottom","top"];switch(e){case"top":case"bottom":return n?t?o:r:t?r:o;case"left":case"right":return t?i:s;default:return[]}}function AB(e,t,n,r){const o=wc(e);let i=PB(wi(e),n==="start",r);return o&&(i=i.map(s=>s+"-"+o),t&&(i=i.concat(i.map(a1)))),i}function Nh(e){return e.replace(/left|right|bottom|top/g,t=>$B[t])}function OB(e){return{top:0,right:0,bottom:0,left:0,...e}}function AT(e){return typeof e!="number"?OB(e):{top:e,right:e,bottom:e,left:e}}function Dh(e){return{...e,top:e.y,left:e.x,right:e.x+e.width,bottom:e.y+e.height}}function MC(e,t,n){let{reference:r,floating:o}=e;const i=xc(t),s=fx(t),l=dx(s),u=wi(t),d=i==="y",h=r.x+r.width/2-o.width/2,m=r.y+r.height/2-o.height/2,g=r[l]/2-o[l]/2;let y;switch(u){case"top":y={x:h,y:r.y-o.height};break;case"bottom":y={x:h,y:r.y+r.height};break;case"right":y={x:r.x+r.width,y:m};break;case"left":y={x:r.x-o.width,y:m};break;default:y={x:r.x,y:r.y}}switch(wc(t)){case"start":y[s]-=g*(n&&d?-1:1);break;case"end":y[s]+=g*(n&&d?-1:1);break}return y}const MB=async(e,t,n)=>{const{placement:r="bottom",strategy:o="absolute",middleware:i=[],platform:s}=n,l=i.filter(Boolean),u=await(s.isRTL==null?void 0:s.isRTL(t));let d=await s.getElementRects({reference:e,floating:t,strategy:o}),{x:h,y:m}=MC(d,r,u),g=r,y={},x=0;for(let _=0;_({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:o,rects:i,platform:s,elements:l,middlewareData:u}=t,{element:d,padding:h=0}=yi(e,t)||{};if(d==null)return{};const m=AT(h),g={x:n,y:r},y=fx(o),x=dx(y),_=await s.getDimensions(d),C=y==="y",S=C?"top":"left",b=C?"bottom":"right",E=C?"clientHeight":"clientWidth",k=i.reference[x]+i.reference[y]-g[y]-i.floating[x],P=g[y]-i.reference[y],M=await(s.getOffsetParent==null?void 0:s.getOffsetParent(d));let A=M?M[E]:0;(!A||!await(s.isElement==null?void 0:s.isElement(M)))&&(A=l.floating[E]||i.floating[x]);const O=k/2-P/2,F=A/2-_[x]/2-1,V=Cs(m[S],F),J=Cs(m[b],F),G=V,ae=A-_[x]-J,U=A/2-_[x]/2+O,te=s1(G,U,ae),L=!u.arrow&&wc(o)!=null&&U!=te&&i.reference[x]/2-(UG<=0)){var F,V;const G=(((F=i.flip)==null?void 0:F.index)||0)+1,ae=P[G];if(ae)return{data:{index:G,overflows:O},reset:{placement:ae}};let U=(V=O.filter(te=>te.overflows[0]<=0).sort((te,L)=>te.overflows[1]-L.overflows[1])[0])==null?void 0:V.placement;if(!U)switch(y){case"bestFit":{var J;const te=(J=O.map(L=>[L.placement,L.overflows.filter(ie=>ie>0).reduce((ie,K)=>ie+K,0)]).sort((L,ie)=>L[1]-ie[1])[0])==null?void 0:J[0];te&&(U=te);break}case"initialPlacement":U=l;break}if(o!==U)return{reset:{placement:U}}}return{}}}};function DC(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function IC(e){return CB.some(t=>e[t]>=0)}const DB=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n}=t,{strategy:r="referenceHidden",...o}=yi(e,t);switch(r){case"referenceHidden":{const i=await td(t,{...o,elementContext:"reference"}),s=DC(i,n.reference);return{data:{referenceHiddenOffsets:s,referenceHidden:IC(s)}}}case"escaped":{const i=await td(t,{...o,altBoundary:!0}),s=DC(i,n.floating);return{data:{escapedOffsets:s,escaped:IC(s)}}}default:return{}}}}};async function IB(e,t){const{placement:n,platform:r,elements:o}=e,i=await(r.isRTL==null?void 0:r.isRTL(o.floating)),s=wi(n),l=wc(n),u=xc(n)==="y",d=["left","top"].includes(s)?-1:1,h=i&&u?-1:1,m=yi(t,e);let{mainAxis:g,crossAxis:y,alignmentAxis:x}=typeof m=="number"?{mainAxis:m,crossAxis:0,alignmentAxis:null}:{mainAxis:0,crossAxis:0,alignmentAxis:null,...m};return l&&typeof x=="number"&&(y=l==="end"?x*-1:x),u?{x:y*h,y:g*d}:{x:g*d,y:y*h}}const LB=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){const{x:n,y:r}=t,o=await IB(t,e);return{x:n+o.x,y:r+o.y,data:o}}}},FB=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:o}=t,{mainAxis:i=!0,crossAxis:s=!1,limiter:l={fn:C=>{let{x:S,y:b}=C;return{x:S,y:b}}},...u}=yi(e,t),d={x:n,y:r},h=await td(t,u),m=xc(wi(o)),g=ux(m);let y=d[g],x=d[m];if(i){const C=g==="y"?"top":"left",S=g==="y"?"bottom":"right",b=y+h[C],E=y-h[S];y=s1(b,y,E)}if(s){const C=m==="y"?"top":"left",S=m==="y"?"bottom":"right",b=x+h[C],E=x-h[S];x=s1(b,x,E)}const _=l.fn({...t,[g]:y,[m]:x});return{..._,data:{x:_.x-n,y:_.y-r}}}}},jB=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:r,placement:o,rects:i,middlewareData:s}=t,{offset:l=0,mainAxis:u=!0,crossAxis:d=!0}=yi(e,t),h={x:n,y:r},m=xc(o),g=ux(m);let y=h[g],x=h[m];const _=yi(l,t),C=typeof _=="number"?{mainAxis:_,crossAxis:0}:{mainAxis:0,crossAxis:0,..._};if(u){const E=g==="y"?"height":"width",k=i.reference[g]-i.floating[E]+C.mainAxis,P=i.reference[g]+i.reference[E]-C.mainAxis;yP&&(y=P)}if(d){var S,b;const E=g==="y"?"width":"height",k=["top","left"].includes(wi(o)),P=i.reference[m]-i.floating[E]+(k&&((S=s.offset)==null?void 0:S[m])||0)+(k?0:C.crossAxis),M=i.reference[m]+i.reference[E]+(k?0:((b=s.offset)==null?void 0:b[m])||0)-(k?C.crossAxis:0);xM&&(x=M)}return{[g]:y,[m]:x}}}},zB=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){const{placement:n,rects:r,platform:o,elements:i}=t,{apply:s=()=>{},...l}=yi(e,t),u=await td(t,l),d=wi(n),h=wc(n),m=xc(n)==="y",{width:g,height:y}=r.floating;let x,_;d==="top"||d==="bottom"?(x=d,_=h===(await(o.isRTL==null?void 0:o.isRTL(i.floating))?"start":"end")?"left":"right"):(_=d,x=h==="end"?"top":"bottom");const C=y-u[x],S=g-u[_],b=!t.middlewareData.shift;let E=C,k=S;if(m){const M=g-u.left-u.right;k=h||b?Cs(S,M):M}else{const M=y-u.top-u.bottom;E=h||b?Cs(C,M):M}if(b&&!h){const M=pr(u.left,0),A=pr(u.right,0),O=pr(u.top,0),F=pr(u.bottom,0);m?k=g-2*(M!==0||A!==0?M+A:pr(u.left,u.right)):E=y-2*(O!==0||F!==0?O+F:pr(u.top,u.bottom))}await s({...t,availableWidth:k,availableHeight:E});const P=await o.getDimensions(i.floating);return g!==P.width||y!==P.height?{reset:{rects:!0}}:{}}}};function ks(e){return OT(e)?(e.nodeName||"").toLowerCase():"#document"}function vr(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Ci(e){var t;return(t=(OT(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function OT(e){return e instanceof Node||e instanceof vr(e).Node}function xi(e){return e instanceof Element||e instanceof vr(e).Element}function Ho(e){return e instanceof HTMLElement||e instanceof vr(e).HTMLElement}function LC(e){return typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof vr(e).ShadowRoot}function Ad(e){const{overflow:t,overflowX:n,overflowY:r,display:o}=Xr(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&!["inline","contents"].includes(o)}function BB(e){return["table","td","th"].includes(ks(e))}function px(e){const t=hx(),n=Xr(e);return n.transform!=="none"||n.perspective!=="none"||(n.containerType?n.containerType!=="normal":!1)||!t&&(n.backdropFilter?n.backdropFilter!=="none":!1)||!t&&(n.filter?n.filter!=="none":!1)||["transform","perspective","filter"].some(r=>(n.willChange||"").includes(r))||["paint","layout","strict","content"].some(r=>(n.contain||"").includes(r))}function UB(e){let t=rc(e);for(;Ho(t)&&!Fm(t);){if(px(t))return t;t=rc(t)}return null}function hx(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}function Fm(e){return["html","body","#document"].includes(ks(e))}function Xr(e){return vr(e).getComputedStyle(e)}function jm(e){return xi(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.pageXOffset,scrollTop:e.pageYOffset}}function rc(e){if(ks(e)==="html")return e;const t=e.assignedSlot||e.parentNode||LC(e)&&e.host||Ci(e);return LC(t)?t.host:t}function MT(e){const t=rc(e);return Fm(t)?e.ownerDocument?e.ownerDocument.body:e.body:Ho(t)&&Ad(t)?t:MT(t)}function nd(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const o=MT(e),i=o===((r=e.ownerDocument)==null?void 0:r.body),s=vr(o);return i?t.concat(s,s.visualViewport||[],Ad(o)?o:[],s.frameElement&&n?nd(s.frameElement):[]):t.concat(o,nd(o,[],n))}function NT(e){const t=Xr(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const o=Ho(e),i=o?e.offsetWidth:n,s=o?e.offsetHeight:r,l=Mh(n)!==i||Mh(r)!==s;return l&&(n=i,r=s),{width:n,height:r,$:l}}function mx(e){return xi(e)?e:e.contextElement}function Rl(e){const t=mx(e);if(!Ho(t))return $s(1);const n=t.getBoundingClientRect(),{width:r,height:o,$:i}=NT(t);let s=(i?Mh(n.width):n.width)/r,l=(i?Mh(n.height):n.height)/o;return(!s||!Number.isFinite(s))&&(s=1),(!l||!Number.isFinite(l))&&(l=1),{x:s,y:l}}const VB=$s(0);function DT(e){const t=vr(e);return!hx()||!t.visualViewport?VB:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function WB(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==vr(e)?!1:t}function Ra(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const o=e.getBoundingClientRect(),i=mx(e);let s=$s(1);t&&(r?xi(r)&&(s=Rl(r)):s=Rl(e));const l=WB(i,n,r)?DT(i):$s(0);let u=(o.left+l.x)/s.x,d=(o.top+l.y)/s.y,h=o.width/s.x,m=o.height/s.y;if(i){const g=vr(i),y=r&&xi(r)?vr(r):r;let x=g.frameElement;for(;x&&r&&y!==g;){const _=Rl(x),C=x.getBoundingClientRect(),S=Xr(x),b=C.left+(x.clientLeft+parseFloat(S.paddingLeft))*_.x,E=C.top+(x.clientTop+parseFloat(S.paddingTop))*_.y;u*=_.x,d*=_.y,h*=_.x,m*=_.y,u+=b,d+=E,x=vr(x).frameElement}}return Dh({width:h,height:m,x:u,y:d})}function HB(e){let{rect:t,offsetParent:n,strategy:r}=e;const o=Ho(n),i=Ci(n);if(n===i)return t;let s={scrollLeft:0,scrollTop:0},l=$s(1);const u=$s(0);if((o||!o&&r!=="fixed")&&((ks(n)!=="body"||Ad(i))&&(s=jm(n)),Ho(n))){const d=Ra(n);l=Rl(n),u.x=d.x+n.clientLeft,u.y=d.y+n.clientTop}return{width:t.width*l.x,height:t.height*l.y,x:t.x*l.x-s.scrollLeft*l.x+u.x,y:t.y*l.y-s.scrollTop*l.y+u.y}}function KB(e){return Array.from(e.getClientRects())}function IT(e){return Ra(Ci(e)).left+jm(e).scrollLeft}function YB(e){const t=Ci(e),n=jm(e),r=e.ownerDocument.body,o=pr(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),i=pr(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let s=-n.scrollLeft+IT(e);const l=-n.scrollTop;return Xr(r).direction==="rtl"&&(s+=pr(t.clientWidth,r.clientWidth)-o),{width:o,height:i,x:s,y:l}}function GB(e,t){const n=vr(e),r=Ci(e),o=n.visualViewport;let i=r.clientWidth,s=r.clientHeight,l=0,u=0;if(o){i=o.width,s=o.height;const d=hx();(!d||d&&t==="fixed")&&(l=o.offsetLeft,u=o.offsetTop)}return{width:i,height:s,x:l,y:u}}function XB(e,t){const n=Ra(e,!0,t==="fixed"),r=n.top+e.clientTop,o=n.left+e.clientLeft,i=Ho(e)?Rl(e):$s(1),s=e.clientWidth*i.x,l=e.clientHeight*i.y,u=o*i.x,d=r*i.y;return{width:s,height:l,x:u,y:d}}function FC(e,t,n){let r;if(t==="viewport")r=GB(e,n);else if(t==="document")r=YB(Ci(e));else if(xi(t))r=XB(t,n);else{const o=DT(e);r={...t,x:t.x-o.x,y:t.y-o.y}}return Dh(r)}function LT(e,t){const n=rc(e);return n===t||!xi(n)||Fm(n)?!1:Xr(n).position==="fixed"||LT(n,t)}function ZB(e,t){const n=t.get(e);if(n)return n;let r=nd(e,[],!1).filter(l=>xi(l)&&ks(l)!=="body"),o=null;const i=Xr(e).position==="fixed";let s=i?rc(e):e;for(;xi(s)&&!Fm(s);){const l=Xr(s),u=px(s);!u&&l.position==="fixed"&&(o=null),(i?!u&&!o:!u&&l.position==="static"&&!!o&&["absolute","fixed"].includes(o.position)||Ad(s)&&!u&<(e,s))?r=r.filter(h=>h!==s):o=l,s=rc(s)}return t.set(e,r),r}function qB(e){let{element:t,boundary:n,rootBoundary:r,strategy:o}=e;const s=[...n==="clippingAncestors"?ZB(t,this._c):[].concat(n),r],l=s[0],u=s.reduce((d,h)=>{const m=FC(t,h,o);return d.top=pr(m.top,d.top),d.right=Cs(m.right,d.right),d.bottom=Cs(m.bottom,d.bottom),d.left=pr(m.left,d.left),d},FC(t,l,o));return{width:u.right-u.left,height:u.bottom-u.top,x:u.left,y:u.top}}function QB(e){return NT(e)}function JB(e,t,n){const r=Ho(t),o=Ci(t),i=n==="fixed",s=Ra(e,!0,i,t);let l={scrollLeft:0,scrollTop:0};const u=$s(0);if(r||!r&&!i)if((ks(t)!=="body"||Ad(o))&&(l=jm(t)),r){const d=Ra(t,!0,i,t);u.x=d.x+t.clientLeft,u.y=d.y+t.clientTop}else o&&(u.x=IT(o));return{x:s.left+l.scrollLeft-u.x,y:s.top+l.scrollTop-u.y,width:s.width,height:s.height}}function jC(e,t){return!Ho(e)||Xr(e).position==="fixed"?null:t?t(e):e.offsetParent}function FT(e,t){const n=vr(e);if(!Ho(e))return n;let r=jC(e,t);for(;r&&BB(r)&&Xr(r).position==="static";)r=jC(r,t);return r&&(ks(r)==="html"||ks(r)==="body"&&Xr(r).position==="static"&&!px(r))?n:r||UB(e)||n}const eU=async function(e){let{reference:t,floating:n,strategy:r}=e;const o=this.getOffsetParent||FT,i=this.getDimensions;return{reference:JB(t,await o(n),r),floating:{x:0,y:0,...await i(n)}}};function tU(e){return Xr(e).direction==="rtl"}const nU={convertOffsetParentRelativeRectToViewportRelativeRect:HB,getDocumentElement:Ci,getClippingRect:qB,getOffsetParent:FT,getElementRects:eU,getClientRects:KB,getDimensions:QB,getScale:Rl,isElement:xi,isRTL:tU};function rU(e,t){let n=null,r;const o=Ci(e);function i(){clearTimeout(r),n&&n.disconnect(),n=null}function s(l,u){l===void 0&&(l=!1),u===void 0&&(u=1),i();const{left:d,top:h,width:m,height:g}=e.getBoundingClientRect();if(l||t(),!m||!g)return;const y=ip(h),x=ip(o.clientWidth-(d+m)),_=ip(o.clientHeight-(h+g)),C=ip(d),b={rootMargin:-y+"px "+-x+"px "+-_+"px "+-C+"px",threshold:pr(0,Cs(1,u))||1};let E=!0;function k(P){const M=P[0].intersectionRatio;if(M!==u){if(!E)return s();M?s(!1,M):r=setTimeout(()=>{s(!1,1e-7)},100)}E=!1}try{n=new IntersectionObserver(k,{...b,root:o.ownerDocument})}catch{n=new IntersectionObserver(k,b)}n.observe(e)}return s(!0),i}function oU(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:o=!0,ancestorResize:i=!0,elementResize:s=typeof ResizeObserver=="function",layoutShift:l=typeof IntersectionObserver=="function",animationFrame:u=!1}=r,d=mx(e),h=o||i?[...d?nd(d):[],...nd(t)]:[];h.forEach(S=>{o&&S.addEventListener("scroll",n,{passive:!0}),i&&S.addEventListener("resize",n)});const m=d&&l?rU(d,n):null;let g=-1,y=null;s&&(y=new ResizeObserver(S=>{let[b]=S;b&&b.target===d&&y&&(y.unobserve(t),cancelAnimationFrame(g),g=requestAnimationFrame(()=>{y&&y.observe(t)})),n()}),d&&!u&&y.observe(d),y.observe(t));let x,_=u?Ra(e):null;u&&C();function C(){const S=Ra(e);_&&(S.x!==_.x||S.y!==_.y||S.width!==_.width||S.height!==_.height)&&n(),_=S,x=requestAnimationFrame(C)}return n(),()=>{h.forEach(S=>{o&&S.removeEventListener("scroll",n),i&&S.removeEventListener("resize",n)}),m&&m(),y&&y.disconnect(),y=null,u&&cancelAnimationFrame(x)}}const iU=(e,t,n)=>{const r=new Map,o={platform:nU,...n},i={...o.platform,_c:r};return MB(e,t,{...o,platform:i})},sU=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:o}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?NC({element:r.current,padding:o}).fn(n):{}:r?NC({element:r,padding:o}).fn(n):{}}}};var Vp=typeof document<"u"?f.useLayoutEffect:f.useEffect;function Ih(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(!Ih(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(!{}.hasOwnProperty.call(t,o[r]))return!1;for(r=n;r--!==0;){const i=o[r];if(!(i==="_owner"&&e.$$typeof)&&!Ih(e[i],t[i]))return!1}return!0}return e!==e&&t!==t}function jT(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function zC(e,t){const n=jT(e);return Math.round(t*n)/n}function BC(e){const t=f.useRef(e);return Vp(()=>{t.current=e}),t}function aU(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:o,elements:{reference:i,floating:s}={},transform:l=!0,whileElementsMounted:u,open:d}=e,[h,m]=f.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[g,y]=f.useState(r);Ih(g,r)||y(r);const[x,_]=f.useState(null),[C,S]=f.useState(null),b=f.useCallback(L=>{L!=M.current&&(M.current=L,_(L))},[_]),E=f.useCallback(L=>{L!==A.current&&(A.current=L,S(L))},[S]),k=i||x,P=s||C,M=f.useRef(null),A=f.useRef(null),O=f.useRef(h),F=BC(u),V=BC(o),J=f.useCallback(()=>{if(!M.current||!A.current)return;const L={placement:t,strategy:n,middleware:g};V.current&&(L.platform=V.current),iU(M.current,A.current,L).then(ie=>{const K={...ie,isPositioned:!0};G.current&&!Ih(O.current,K)&&(O.current=K,Os.flushSync(()=>{m(K)}))})},[g,t,n,V]);Vp(()=>{d===!1&&O.current.isPositioned&&(O.current.isPositioned=!1,m(L=>({...L,isPositioned:!1})))},[d]);const G=f.useRef(!1);Vp(()=>(G.current=!0,()=>{G.current=!1}),[]),Vp(()=>{if(k&&(M.current=k),P&&(A.current=P),k&&P){if(F.current)return F.current(k,P,J);J()}},[k,P,J,F]);const ae=f.useMemo(()=>({reference:M,floating:A,setReference:b,setFloating:E}),[b,E]),U=f.useMemo(()=>({reference:k,floating:P}),[k,P]),te=f.useMemo(()=>{const L={position:n,left:0,top:0};if(!U.floating)return L;const ie=zC(U.floating,h.x),K=zC(U.floating,h.y);return l?{...L,transform:"translate("+ie+"px, "+K+"px)",...jT(U.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:ie,top:K}},[n,l,U.floating,h.x,h.y]);return f.useMemo(()=>({...h,update:J,refs:ae,elements:U,floatingStyles:te}),[h,J,ae,U,te])}function gx(e){const[t,n]=f.useState(void 0);return Pn(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(o=>{if(!Array.isArray(o)||!o.length)return;const i=o[0];let s,l;if("borderBoxSize"in i){const u=i.borderBoxSize,d=Array.isArray(u)?u[0]:u;s=d.inlineSize,l=d.blockSize}else s=e.offsetWidth,l=e.offsetHeight;n({width:s,height:l})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}const zT="Popper",[BT,Ns]=An(zT),[lU,UT]=BT(zT),cU=e=>{const{__scopePopper:t,children:n}=e,[r,o]=f.useState(null);return f.createElement(lU,{scope:t,anchor:r,onAnchorChange:o},n)},uU="PopperAnchor",dU=f.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...o}=e,i=UT(uU,n),s=f.useRef(null),l=Be(t,s);return f.useEffect(()=>{i.onAnchorChange((r==null?void 0:r.current)||s.current)}),r?null:f.createElement(Pe.div,Y({},o,{ref:l}))}),VT="PopperContent",[fU,hte]=BT(VT),pU=f.forwardRef((e,t)=>{var n,r,o,i,s,l,u,d;const{__scopePopper:h,side:m="bottom",sideOffset:g=0,align:y="center",alignOffset:x=0,arrowPadding:_=0,avoidCollisions:C=!0,collisionBoundary:S=[],collisionPadding:b=0,sticky:E="partial",hideWhenDetached:k=!1,updatePositionStrategy:P="optimized",onPlaced:M,...A}=e,O=UT(VT,h),[F,V]=f.useState(null),J=Be(t,Yt=>V(Yt)),[G,ae]=f.useState(null),U=gx(G),te=(n=U==null?void 0:U.width)!==null&&n!==void 0?n:0,L=(r=U==null?void 0:U.height)!==null&&r!==void 0?r:0,ie=m+(y!=="center"?"-"+y:""),K=typeof b=="number"?b:{top:0,right:0,bottom:0,left:0,...b},Q=Array.isArray(S)?S:[S],W=Q.length>0,le={padding:K,boundary:Q.filter(hU),altBoundary:W},{refs:ge,floatingStyles:Ve,placement:Ue,isPositioned:We,middlewareData:Me}=aU({strategy:"fixed",placement:ie,whileElementsMounted:(...Yt)=>oU(...Yt,{animationFrame:P==="always"}),elements:{reference:O.anchor},middleware:[LB({mainAxis:g+L,alignmentAxis:x}),C&&FB({mainAxis:!0,crossAxis:!1,limiter:E==="partial"?jB():void 0,...le}),C&&NB({...le}),zB({...le,apply:({elements:Yt,rects:Er,availableWidth:gt,availableHeight:js})=>{const{width:I,height:X}=Er.reference,Z=Yt.floating.style;Z.setProperty("--radix-popper-available-width",`${gt}px`),Z.setProperty("--radix-popper-available-height",`${js}px`),Z.setProperty("--radix-popper-anchor-width",`${I}px`),Z.setProperty("--radix-popper-anchor-height",`${X}px`)}}),G&&sU({element:G,padding:_}),mU({arrowWidth:te,arrowHeight:L}),k&&DB({strategy:"referenceHidden",...le})]}),[fe,xe]=WT(Ue),$e=Ft(M);Pn(()=>{We&&($e==null||$e())},[We,$e]);const Ae=(o=Me.arrow)===null||o===void 0?void 0:o.x,Oe=(i=Me.arrow)===null||i===void 0?void 0:i.y,je=((s=Me.arrow)===null||s===void 0?void 0:s.centerOffset)!==0,[Ot,ct]=f.useState();return Pn(()=>{F&&ct(window.getComputedStyle(F).zIndex)},[F]),f.createElement("div",{ref:ge.setFloating,"data-radix-popper-content-wrapper":"",style:{...Ve,transform:We?Ve.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:Ot,"--radix-popper-transform-origin":[(l=Me.transformOrigin)===null||l===void 0?void 0:l.x,(u=Me.transformOrigin)===null||u===void 0?void 0:u.y].join(" ")},dir:e.dir},f.createElement(fU,{scope:h,placedSide:fe,onArrowChange:ae,arrowX:Ae,arrowY:Oe,shouldHideArrow:je},f.createElement(Pe.div,Y({"data-side":fe,"data-align":xe},A,{ref:J,style:{...A.style,animation:We?void 0:"none",opacity:(d=Me.hide)!==null&&d!==void 0&&d.referenceHidden?0:void 0}}))))});function hU(e){return e!==null}const mU=e=>({name:"transformOrigin",options:e,fn(t){var n,r,o,i,s;const{placement:l,rects:u,middlewareData:d}=t,m=((n=d.arrow)===null||n===void 0?void 0:n.centerOffset)!==0,g=m?0:e.arrowWidth,y=m?0:e.arrowHeight,[x,_]=WT(l),C={start:"0%",center:"50%",end:"100%"}[_],S=((r=(o=d.arrow)===null||o===void 0?void 0:o.x)!==null&&r!==void 0?r:0)+g/2,b=((i=(s=d.arrow)===null||s===void 0?void 0:s.y)!==null&&i!==void 0?i:0)+y/2;let E="",k="";return x==="bottom"?(E=m?C:`${S}px`,k=`${-y}px`):x==="top"?(E=m?C:`${S}px`,k=`${u.floating.height+y}px`):x==="right"?(E=`${-y}px`,k=m?C:`${b}px`):x==="left"&&(E=`${u.floating.width+y}px`,k=m?C:`${b}px`),{data:{x:E,y:k}}}});function WT(e){const[t,n="center"]=e.split("-");return[t,n]}const Od=cU,zm=dU,Bm=pU,Md=f.forwardRef((e,t)=>{var n;const{container:r=globalThis==null||(n=globalThis.document)===null||n===void 0?void 0:n.body,...o}=e;return r?XI.createPortal(f.createElement(Pe.div,Y({},o,{ref:t})),r):null});function gU(e,t){return f.useReducer((n,r)=>{const o=t[n][r];return o??n},e)}const xn=e=>{const{present:t,children:n}=e,r=vU(t),o=typeof n=="function"?n({present:r.isPresent}):f.Children.only(n),i=Be(r.ref,o.ref);return typeof n=="function"||r.isPresent?f.cloneElement(o,{ref:i}):null};xn.displayName="Presence";function vU(e){const[t,n]=f.useState(),r=f.useRef({}),o=f.useRef(e),i=f.useRef("none"),s=e?"mounted":"unmounted",[l,u]=gU(s,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return f.useEffect(()=>{const d=sp(r.current);i.current=l==="mounted"?d:"none"},[l]),Pn(()=>{const d=r.current,h=o.current;if(h!==e){const g=i.current,y=sp(d);e?u("MOUNT"):y==="none"||(d==null?void 0:d.display)==="none"?u("UNMOUNT"):u(h&&g!==y?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,u]),Pn(()=>{if(t){const d=m=>{const y=sp(r.current).includes(m.animationName);m.target===t&&y&&Os.flushSync(()=>u("ANIMATION_END"))},h=m=>{m.target===t&&(i.current=sp(r.current))};return t.addEventListener("animationstart",h),t.addEventListener("animationcancel",d),t.addEventListener("animationend",d),()=>{t.removeEventListener("animationstart",h),t.removeEventListener("animationcancel",d),t.removeEventListener("animationend",d)}}else u("ANIMATION_END")},[t,u]),{isPresent:["mounted","unmountSuspended"].includes(l),ref:f.useCallback(d=>{d&&(r.current=getComputedStyle(d)),n(d)},[])}}function sp(e){return(e==null?void 0:e.animationName)||"none"}function Zr({prop:e,defaultProp:t,onChange:n=()=>{}}){const[r,o]=yU({defaultProp:t,onChange:n}),i=e!==void 0,s=i?e:r,l=Ft(n),u=f.useCallback(d=>{if(i){const m=typeof d=="function"?d(e):d;m!==e&&l(m)}else o(d)},[i,e,o,l]);return[s,u]}function yU({defaultProp:e,onChange:t}){const n=f.useState(e),[r]=n,o=f.useRef(r),i=Ft(t);return f.useEffect(()=>{o.current!==r&&(i(r),o.current=r)},[r,o,i]),n}const Um=f.forwardRef((e,t)=>f.createElement(Pe.span,Y({},e,{ref:t,style:{position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal",...e.style}}))),wU=Um,[Vm,mte]=An("Tooltip",[Ns]),vx=Ns(),xU="TooltipProvider",bU=700,l1="tooltip.open",[_U,yx]=Vm(xU),SU=e=>{const{__scopeTooltip:t,delayDuration:n=bU,skipDelayDuration:r=300,disableHoverableContent:o=!1,children:i}=e,[s,l]=f.useState(!0),u=f.useRef(!1),d=f.useRef(0);return f.useEffect(()=>{const h=d.current;return()=>window.clearTimeout(h)},[]),f.createElement(_U,{scope:t,isOpenDelayed:s,delayDuration:n,onOpen:f.useCallback(()=>{window.clearTimeout(d.current),l(!1)},[]),onClose:f.useCallback(()=>{window.clearTimeout(d.current),d.current=window.setTimeout(()=>l(!0),r)},[r]),isPointerInTransitRef:u,onPointerInTransitChange:f.useCallback(h=>{u.current=h},[]),disableHoverableContent:o},i)},wx="Tooltip",[EU,Wm]=Vm(wx),CU=e=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:o=!1,onOpenChange:i,disableHoverableContent:s,delayDuration:l}=e,u=yx(wx,e.__scopeTooltip),d=vx(t),[h,m]=f.useState(null),g=nr(),y=f.useRef(0),x=s??u.disableHoverableContent,_=l??u.delayDuration,C=f.useRef(!1),[S=!1,b]=Zr({prop:r,defaultProp:o,onChange:A=>{A?(u.onOpen(),document.dispatchEvent(new CustomEvent(l1))):u.onClose(),i==null||i(A)}}),E=f.useMemo(()=>S?C.current?"delayed-open":"instant-open":"closed",[S]),k=f.useCallback(()=>{window.clearTimeout(y.current),C.current=!1,b(!0)},[b]),P=f.useCallback(()=>{window.clearTimeout(y.current),b(!1)},[b]),M=f.useCallback(()=>{window.clearTimeout(y.current),y.current=window.setTimeout(()=>{C.current=!0,b(!0)},_)},[_,b]);return f.useEffect(()=>()=>window.clearTimeout(y.current),[]),f.createElement(Od,d,f.createElement(EU,{scope:t,contentId:g,open:S,stateAttribute:E,trigger:h,onTriggerChange:m,onTriggerEnter:f.useCallback(()=>{u.isOpenDelayed?M():k()},[u.isOpenDelayed,M,k]),onTriggerLeave:f.useCallback(()=>{x?P():window.clearTimeout(y.current)},[P,x]),onOpen:k,onClose:P,disableHoverableContent:x},n))},UC="TooltipTrigger",$U=f.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,o=Wm(UC,n),i=yx(UC,n),s=vx(n),l=f.useRef(null),u=Be(t,l,o.onTriggerChange),d=f.useRef(!1),h=f.useRef(!1),m=f.useCallback(()=>d.current=!1,[]);return f.useEffect(()=>()=>document.removeEventListener("pointerup",m),[m]),f.createElement(zm,Y({asChild:!0},s),f.createElement(Pe.button,Y({"aria-describedby":o.open?o.contentId:void 0,"data-state":o.stateAttribute},r,{ref:u,onPointerMove:ue(e.onPointerMove,g=>{g.pointerType!=="touch"&&!h.current&&!i.isPointerInTransitRef.current&&(o.onTriggerEnter(),h.current=!0)}),onPointerLeave:ue(e.onPointerLeave,()=>{o.onTriggerLeave(),h.current=!1}),onPointerDown:ue(e.onPointerDown,()=>{d.current=!0,document.addEventListener("pointerup",m,{once:!0})}),onFocus:ue(e.onFocus,()=>{d.current||o.onOpen()}),onBlur:ue(e.onBlur,o.onClose),onClick:ue(e.onClick,o.onClose)})))}),kU="TooltipPortal",[gte,RU]=Vm(kU,{forceMount:void 0}),rd="TooltipContent",TU=f.forwardRef((e,t)=>{const n=RU(rd,e.__scopeTooltip),{forceMount:r=n.forceMount,side:o="top",...i}=e,s=Wm(rd,e.__scopeTooltip);return f.createElement(xn,{present:r||s.open},s.disableHoverableContent?f.createElement(HT,Y({side:o},i,{ref:t})):f.createElement(PU,Y({side:o},i,{ref:t})))}),PU=f.forwardRef((e,t)=>{const n=Wm(rd,e.__scopeTooltip),r=yx(rd,e.__scopeTooltip),o=f.useRef(null),i=Be(t,o),[s,l]=f.useState(null),{trigger:u,onClose:d}=n,h=o.current,{onPointerInTransitChange:m}=r,g=f.useCallback(()=>{l(null),m(!1)},[m]),y=f.useCallback((x,_)=>{const C=x.currentTarget,S={x:x.clientX,y:x.clientY},b=OU(S,C.getBoundingClientRect()),E=MU(S,b),k=NU(_.getBoundingClientRect()),P=IU([...E,...k]);l(P),m(!0)},[m]);return f.useEffect(()=>()=>g(),[g]),f.useEffect(()=>{if(u&&h){const x=C=>y(C,h),_=C=>y(C,u);return u.addEventListener("pointerleave",x),h.addEventListener("pointerleave",_),()=>{u.removeEventListener("pointerleave",x),h.removeEventListener("pointerleave",_)}}},[u,h,y,g]),f.useEffect(()=>{if(s){const x=_=>{const C=_.target,S={x:_.clientX,y:_.clientY},b=(u==null?void 0:u.contains(C))||(h==null?void 0:h.contains(C)),E=!DU(S,s);b?g():E&&(g(),d())};return document.addEventListener("pointermove",x),()=>document.removeEventListener("pointermove",x)}},[u,h,s,d,g]),f.createElement(HT,Y({},e,{ref:i}))}),[AU,vte]=Vm(wx,{isInside:!1}),HT=f.forwardRef((e,t)=>{const{__scopeTooltip:n,children:r,"aria-label":o,onEscapeKeyDown:i,onPointerDownOutside:s,...l}=e,u=Wm(rd,n),d=vx(n),{onClose:h}=u;return f.useEffect(()=>(document.addEventListener(l1,h),()=>document.removeEventListener(l1,h)),[h]),f.useEffect(()=>{if(u.trigger){const m=g=>{const y=g.target;y!=null&&y.contains(u.trigger)&&h()};return window.addEventListener("scroll",m,{capture:!0}),()=>window.removeEventListener("scroll",m,{capture:!0})}},[u.trigger,h]),f.createElement(yc,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:i,onPointerDownOutside:s,onFocusOutside:m=>m.preventDefault(),onDismiss:h},f.createElement(Bm,Y({"data-state":u.stateAttribute},d,l,{ref:t,style:{...l.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"}}),f.createElement(sx,null,r),f.createElement(AU,{scope:n,isInside:!0},f.createElement(wU,{id:u.contentId,role:"tooltip"},o||r))))});function OU(e,t){const n=Math.abs(t.top-e.y),r=Math.abs(t.bottom-e.y),o=Math.abs(t.right-e.x),i=Math.abs(t.left-e.x);switch(Math.min(n,r,o,i)){case i:return"left";case o:return"right";case n:return"top";case r:return"bottom";default:throw new Error("unreachable")}}function MU(e,t,n=5){const r=[];switch(t){case"top":r.push({x:e.x-n,y:e.y+n},{x:e.x+n,y:e.y+n});break;case"bottom":r.push({x:e.x-n,y:e.y-n},{x:e.x+n,y:e.y-n});break;case"left":r.push({x:e.x+n,y:e.y-n},{x:e.x+n,y:e.y+n});break;case"right":r.push({x:e.x-n,y:e.y-n},{x:e.x-n,y:e.y+n});break}return r}function NU(e){const{top:t,right:n,bottom:r,left:o}=e;return[{x:o,y:t},{x:n,y:t},{x:n,y:r},{x:o,y:r}]}function DU(e,t){const{x:n,y:r}=e;let o=!1;for(let i=0,s=t.length-1;ir!=h>r&&n<(d-l)*(r-u)/(h-u)+l&&(o=!o)}return o}function IU(e){const t=e.slice();return t.sort((n,r)=>n.xr.x?1:n.yr.y?1:0),LU(t)}function LU(e){if(e.length<=1)return e.slice();const t=[];for(let r=0;r=2;){const i=t[t.length-1],s=t[t.length-2];if((i.x-s.x)*(o.y-s.y)>=(i.y-s.y)*(o.x-s.x))t.pop();else break}t.push(o)}t.pop();const n=[];for(let r=e.length-1;r>=0;r--){const o=e[r];for(;n.length>=2;){const i=n[n.length-1],s=n[n.length-2];if((i.x-s.x)*(o.y-s.y)>=(i.y-s.y)*(o.x-s.x))n.pop();else break}n.push(o)}return n.pop(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}const FU=SU,jU=CU,zU=$U,KT=TU,BU=FU,YT=jU,GT=zU,xx=f.forwardRef(({className:e,sideOffset:t=4,...n},r)=>v.jsx(KT,{ref:r,sideOffset:t,className:Ce("z-50 border overflow-hidden rounded-md bg-background text-foreground px-3 py-1.5 text-xs animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...n}));xx.displayName=KT.displayName;const bx=Om("inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50",{variants:{variant:{default:"bg-primary text-primary-foreground shadow hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",outline:"border border-input bg-transparent shadow-sm hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2",sm:"h-8 rounded-md px-3 text-xs",lg:"h-10 rounded-md px-8",icon:"h-9 w-9"}},defaultVariants:{variant:"default",size:"default"}}),Rn=f.forwardRef(({className:e,variant:t,size:n,asChild:r=!1,...o},i)=>{const s=r?Wo:"button";return v.jsx(s,{className:Ce(bx({variant:t,size:n,className:e}),"outline-none cursor-default"),ref:i,tabIndex:-1,...o})});Rn.displayName="Button";const vn=f.forwardRef(({tooltip:e,children:t,...n},r)=>v.jsxs(YT,{children:[v.jsx(GT,{asChild:!0,children:v.jsx(Rn,{variant:"ghost",size:"icon",...n,ref:r,tabIndex:-1,className:"cursor-default bg-background",children:v.jsx("div",{className:"icon-button-icon-wrapper",children:t})})}),v.jsx(xx,{children:v.jsx("p",{children:e})})]})),c1=e=>{const{onFileUpload:t,children:n,...r}=e,[o]=f.useState(`file-upload-${Math.random().toString()}`),i=s=>{var u;const l=(u=s.currentTarget.files)==null?void 0:u[0];l&&t(l)};return v.jsxs(v.Fragment,{children:[v.jsx("label",{htmlFor:o,children:v.jsx(vn,{...r,asChild:!0,children:n})}),v.jsx(Pd,{style:{display:"none"},id:o,name:o,type:"file",onChange:i,accept:"image/png, image/jpeg"})]})};var UU={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const VU=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Kt=(e,t)=>{const n=f.forwardRef(({color:r="currentColor",size:o=24,strokeWidth:i=2,absoluteStrokeWidth:s,children:l,...u},d)=>f.createElement("svg",{ref:d,...UU,width:o,height:o,stroke:r,strokeWidth:s?Number(i)*24/Number(o):i,className:`lucide lucide-${VU(e)}`,...u},[...t.map(([h,m])=>f.createElement(h,m)),...(Array.isArray(l)?l:[l])||[]]));return n.displayName=`${e}`,n},WU=Kt("Blocks",[["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["path",{d:"M10 21V8a1 1 0 0 0-1-1H4a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-5a1 1 0 0 0-1-1H3",key:"1fpvtg"}]]),HU=Kt("ChevronLeft",[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]]),KU=Kt("ChevronRight",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]),YU=Kt("Coffee",[["path",{d:"M17 8h1a4 4 0 1 1 0 8h-1",key:"jx4kbh"}],["path",{d:"M3 8h14v9a4 4 0 0 1-4 4H7a4 4 0 0 1-4-4Z",key:"1bxrl0"}],["line",{x1:"6",x2:"6",y1:"2",y2:"4",key:"1cr9l3"}],["line",{x1:"10",x2:"10",y1:"2",y2:"4",key:"170wym"}],["line",{x1:"14",x2:"14",y1:"2",y2:"4",key:"1c5f70"}]]),GU=Kt("Download",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"7 10 12 15 17 10",key:"2ggqvy"}],["line",{x1:"12",x2:"12",y1:"15",y2:"3",key:"1vk2je"}]]),XU=Kt("Eraser",[["path",{d:"m7 21-4.3-4.3c-1-1-1-2.5 0-3.4l9.6-9.6c1-1 2.5-1 3.4 0l5.6 5.6c1 1 1 2.5 0 3.4L13 21",key:"182aya"}],["path",{d:"M22 21H7",key:"t4ddhn"}],["path",{d:"m5 11 9 9",key:"1mo9qw"}]]),ZU=Kt("Expand",[["path",{d:"m21 21-6-6m6 6v-4.8m0 4.8h-4.8",key:"1c15vz"}],["path",{d:"M3 16.2V21m0 0h4.8M3 21l6-6",key:"1fsnz2"}],["path",{d:"M21 7.8V3m0 0h-4.8M21 3l-6 6",key:"hawz9i"}],["path",{d:"M3 7.8V3m0 0h4.8M3 3l6 6",key:"u9ee12"}]]),qU=Kt("Eye",[["path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z",key:"rwhkz3"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]),QU=Kt("FolderClosed",[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}],["path",{d:"M2 10h20",key:"1ir3d8"}]]),XT=Kt("Fullscreen",[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}],["rect",{width:"10",height:"8",x:"7",y:"8",rx:"1",key:"vys8me"}]]),JU=Kt("Image",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]]),eV=Kt("Keyboard",[["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",ry:"2",key:"15u882"}],["path",{d:"M6 8h.001",key:"1ej0i3"}],["path",{d:"M10 8h.001",key:"1x2st2"}],["path",{d:"M14 8h.001",key:"1vkmyp"}],["path",{d:"M18 8h.001",key:"kfsenl"}],["path",{d:"M8 12h.001",key:"1sjpby"}],["path",{d:"M12 12h.001",key:"al75ts"}],["path",{d:"M16 12h.001",key:"931bgk"}],["path",{d:"M7 16h10",key:"wp8him"}]]),tV=Kt("Minus",[["path",{d:"M5 12h14",key:"1ays0h"}]]),nV=Kt("MousePointerClick",[["path",{d:"m9 9 5 12 1.8-5.2L21 14Z",key:"1b76lo"}],["path",{d:"M7.2 2.2 8 5.1",key:"1cfko1"}],["path",{d:"m5.1 8-2.9-.8",key:"1go3kf"}],["path",{d:"M14 4.1 12 6",key:"ita8i4"}],["path",{d:"m6 12-1.9 2",key:"mnht97"}]]),rV=Kt("Plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]),oV=Kt("Redo",[["path",{d:"M21 7v6h-6",key:"3ptur4"}],["path",{d:"M3 17a9 9 0 0 1 9-9 9 9 0 0 1 6 2.3l3 2.7",key:"1kgawr"}]]),iV=Kt("RotateCw",[["path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8",key:"1p45f6"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}]]),sV=Kt("Settings",[["path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z",key:"1qme2f"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]),VC=Kt("Slice",[["path",{d:"m8 14-6 6h9v-3",key:"zo3j9a"}],["path",{d:"M18.37 3.63 8 14l3 3L21.37 6.63a2.12 2.12 0 1 0-3-3Z",key:"1dzx0j"}]]),WC=Kt("Smile",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 14s1.5 2 4 2 4-2 4-2",key:"1y1vjs"}],["line",{x1:"9",x2:"9.01",y1:"9",y2:"9",key:"yxxnd0"}],["line",{x1:"15",x2:"15.01",y1:"9",y2:"9",key:"1p4y9e"}]]),aV=Kt("Undo",[["path",{d:"M3 7v6h6",key:"1v2h90"}],["path",{d:"M21 17a9 9 0 0 0-9-9 9 9 0 0 0-6 2.3L3 13",key:"1r6uu6"}]]),ZT=Kt("Upload",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"17 8 12 3 7 8",key:"t8dd8p"}],["line",{x1:"12",x2:"12",y1:"3",y2:"15",key:"widbto"}]]);function lV(e,t){const[n,r]=f.useState(e);return f.useEffect(()=>{const o=setTimeout(()=>{r(e)},t);return()=>{clearTimeout(o)}},[e,t]),n}function u1(e){const[t,n]=f.useState(()=>typeof e=="boolean"?e:!!e),r=f.useCallback(o=>n(typeof o=="boolean"?o:i=>!i),[]);return[t,r]}const w0="focusScope.autoFocusOnMount",x0="focusScope.autoFocusOnUnmount",HC={bubbles:!1,cancelable:!0},Hm=f.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:o,onUnmountAutoFocus:i,...s}=e,[l,u]=f.useState(null),d=Ft(o),h=Ft(i),m=f.useRef(null),g=Be(t,_=>u(_)),y=f.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;f.useEffect(()=>{if(r){let b=function(M){if(y.paused||!l)return;const A=M.target;l.contains(A)?m.current=A:Hi(m.current,{select:!0})},E=function(M){if(y.paused||!l)return;const A=M.relatedTarget;A!==null&&(l.contains(A)||Hi(m.current,{select:!0}))},k=function(M){if(document.activeElement===document.body)for(const O of M)O.removedNodes.length>0&&Hi(l)};var _=b,C=E,S=k;document.addEventListener("focusin",b),document.addEventListener("focusout",E);const P=new MutationObserver(k);return l&&P.observe(l,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",b),document.removeEventListener("focusout",E),P.disconnect()}}},[r,l,y.paused]),f.useEffect(()=>{if(l){YC.add(y);const _=document.activeElement;if(!l.contains(_)){const S=new CustomEvent(w0,HC);l.addEventListener(w0,d),l.dispatchEvent(S),S.defaultPrevented||(cV(hV(qT(l)),{select:!0}),document.activeElement===_&&Hi(l))}return()=>{l.removeEventListener(w0,d),setTimeout(()=>{const S=new CustomEvent(x0,HC);l.addEventListener(x0,h),l.dispatchEvent(S),S.defaultPrevented||Hi(_??document.body,{select:!0}),l.removeEventListener(x0,h),YC.remove(y)},0)}}},[l,d,h,y]);const x=f.useCallback(_=>{if(!n&&!r||y.paused)return;const C=_.key==="Tab"&&!_.altKey&&!_.ctrlKey&&!_.metaKey,S=document.activeElement;if(C&&S){const b=_.currentTarget,[E,k]=uV(b);E&&k?!_.shiftKey&&S===k?(_.preventDefault(),n&&Hi(E,{select:!0})):_.shiftKey&&S===E&&(_.preventDefault(),n&&Hi(k,{select:!0})):S===b&&_.preventDefault()}},[n,r,y.paused]);return f.createElement(Pe.div,Y({tabIndex:-1},s,{ref:g,onKeyDown:x}))});function cV(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(Hi(r,{select:t}),document.activeElement!==n)return}function uV(e){const t=qT(e),n=KC(t,e),r=KC(t.reverse(),e);return[n,r]}function qT(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const o=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||o?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function KC(e,t){for(const n of e)if(!dV(n,{upTo:t}))return n}function dV(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function fV(e){return e instanceof HTMLInputElement&&"select"in e}function Hi(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&fV(e)&&t&&e.select()}}const YC=pV();function pV(){let e=[];return{add(t){const n=e[0];t!==n&&(n==null||n.pause()),e=GC(e,t),e.unshift(t)},remove(t){var n;e=GC(e,t),(n=e[0])===null||n===void 0||n.resume()}}}function GC(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function hV(e){return e.filter(t=>t.tagName!=="A")}let b0=0;function Km(){f.useEffect(()=>{var e,t;const n=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",(e=n[0])!==null&&e!==void 0?e:XC()),document.body.insertAdjacentElement("beforeend",(t=n[1])!==null&&t!==void 0?t:XC()),b0++,()=>{b0===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(r=>r.remove()),b0--}},[])}function XC(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.cssText="outline: none; opacity: 0; position: fixed; pointer-events: none",e}var Mo=function(){return Mo=Object.assign||function(t){for(var n,r=1,o=arguments.length;r"u")return AV;var t=OV(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])}},NV=tP(),DV=function(e,t,n,r){var o=e.left,i=e.top,s=e.right,l=e.gap;return n===void 0&&(n="margin"),` + .`.concat(gV,` { + overflow: hidden `).concat(r,`; + padding-right: `).concat(l,"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(i,`px; + padding-right: `).concat(s,`px; + margin-left:0; + margin-top:0; + margin-right: `).concat(l,"px ").concat(r,`; + `),n==="padding"&&"padding-right: ".concat(l,"px ").concat(r,";")].filter(Boolean).join(""),` + } + + .`).concat(Wp,` { + right: `).concat(l,"px ").concat(r,`; + } + + .`).concat(Hp,` { + margin-right: `).concat(l,"px ").concat(r,`; + } + + .`).concat(Wp," .").concat(Wp,` { + right: 0 `).concat(r,`; + } + + .`).concat(Hp," .").concat(Hp,` { + margin-right: 0 `).concat(r,`; + } + + body { + `).concat(vV,": ").concat(l,`px; + } +`)},IV=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,o=r===void 0?"margin":r,i=f.useMemo(function(){return MV(o)},[o]);return f.createElement(NV,{styles:DV(i,!t,o,n?"":"!important")})},d1=!1;if(typeof window<"u")try{var ap=Object.defineProperty({},"passive",{get:function(){return d1=!0,!0}});window.addEventListener("test",ap,ap),window.removeEventListener("test",ap,ap)}catch{d1=!1}var qa=d1?{passive:!1}:!1,LV=function(e){return e.tagName==="TEXTAREA"},nP=function(e,t){var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!LV(e)&&n[t]==="visible")},FV=function(e){return nP(e,"overflowY")},jV=function(e){return nP(e,"overflowX")},qC=function(e,t){var n=t;do{typeof ShadowRoot<"u"&&n instanceof ShadowRoot&&(n=n.host);var r=rP(e,n);if(r){var o=oP(e,n),i=o[1],s=o[2];if(i>s)return!0}n=n.parentNode}while(n&&n!==document.body);return!1},zV=function(e){var t=e.scrollTop,n=e.scrollHeight,r=e.clientHeight;return[t,n,r]},BV=function(e){var t=e.scrollLeft,n=e.scrollWidth,r=e.clientWidth;return[t,n,r]},rP=function(e,t){return e==="v"?FV(t):jV(t)},oP=function(e,t){return e==="v"?zV(t):BV(t)},UV=function(e,t){return e==="h"&&t==="rtl"?-1:1},VV=function(e,t,n,r,o){var i=UV(e,window.getComputedStyle(t).direction),s=i*r,l=n.target,u=t.contains(l),d=!1,h=s>0,m=0,g=0;do{var y=oP(e,l),x=y[0],_=y[1],C=y[2],S=_-C-i*x;(x||S)&&rP(e,l)&&(m+=S,g+=x),l=l.parentNode}while(!u&&l!==document.body||u&&(t.contains(l)||t===l));return(h&&(o&&m===0||!o&&s>m)||!h&&(o&&g===0||!o&&-s>g))&&(d=!0),d},lp=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},QC=function(e){return[e.deltaX,e.deltaY]},JC=function(e){return e&&"current"in e?e.current:e},WV=function(e,t){return e[0]===t[0]&&e[1]===t[1]},HV=function(e){return` + .block-interactivity-`.concat(e,` {pointer-events: none;} + .allow-interactivity-`).concat(e,` {pointer-events: all;} +`)},KV=0,Qa=[];function YV(e){var t=f.useRef([]),n=f.useRef([0,0]),r=f.useRef(),o=f.useState(KV++)[0],i=f.useState(function(){return tP()})[0],s=f.useRef(e);f.useEffect(function(){s.current=e},[e]),f.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(o));var _=mV([e.lockRef.current],(e.shards||[]).map(JC),!0).filter(Boolean);return _.forEach(function(C){return C.classList.add("allow-interactivity-".concat(o))}),function(){document.body.classList.remove("block-interactivity-".concat(o)),_.forEach(function(C){return C.classList.remove("allow-interactivity-".concat(o))})}}},[e.inert,e.lockRef.current,e.shards]);var l=f.useCallback(function(_,C){if("touches"in _&&_.touches.length===2)return!s.current.allowPinchZoom;var S=lp(_),b=n.current,E="deltaX"in _?_.deltaX:b[0]-S[0],k="deltaY"in _?_.deltaY:b[1]-S[1],P,M=_.target,A=Math.abs(E)>Math.abs(k)?"h":"v";if("touches"in _&&A==="h"&&M.type==="range")return!1;var O=qC(A,M);if(!O)return!0;if(O?P=A:(P=A==="v"?"h":"v",O=qC(A,M)),!O)return!1;if(!r.current&&"changedTouches"in _&&(E||k)&&(r.current=P),!P)return!0;var F=r.current||P;return VV(F,C,_,F==="h"?E:k,!0)},[]),u=f.useCallback(function(_){var C=_;if(!(!Qa.length||Qa[Qa.length-1]!==i)){var S="deltaY"in C?QC(C):lp(C),b=t.current.filter(function(P){return P.name===C.type&&P.target===C.target&&WV(P.delta,S)})[0];if(b&&b.should){C.cancelable&&C.preventDefault();return}if(!b){var E=(s.current.shards||[]).map(JC).filter(Boolean).filter(function(P){return P.contains(C.target)}),k=E.length>0?l(C,E[0]):!s.current.noIsolation;k&&C.cancelable&&C.preventDefault()}}},[]),d=f.useCallback(function(_,C,S,b){var E={name:_,delta:C,target:S,should:b};t.current.push(E),setTimeout(function(){t.current=t.current.filter(function(k){return k!==E})},1)},[]),h=f.useCallback(function(_){n.current=lp(_),r.current=void 0},[]),m=f.useCallback(function(_){d(_.type,QC(_),_.target,l(_,e.lockRef.current))},[]),g=f.useCallback(function(_){d(_.type,lp(_),_.target,l(_,e.lockRef.current))},[]);f.useEffect(function(){return Qa.push(i),e.setCallbacks({onScrollCapture:m,onWheelCapture:m,onTouchMoveCapture:g}),document.addEventListener("wheel",u,qa),document.addEventListener("touchmove",u,qa),document.addEventListener("touchstart",h,qa),function(){Qa=Qa.filter(function(_){return _!==i}),document.removeEventListener("wheel",u,qa),document.removeEventListener("touchmove",u,qa),document.removeEventListener("touchstart",h,qa)}},[]);var y=e.removeScrollBar,x=e.inert;return f.createElement(f.Fragment,null,x?f.createElement(i,{styles:HV(o)}):null,y?f.createElement(IV,{gapMode:"margin"}):null)}const GV=EV(eP,YV);var iP=f.forwardRef(function(e,t){return f.createElement(Ym,Mo({},e,{ref:t,sideCar:GV}))});iP.classNames=Ym.classNames;const Gm=iP;var XV=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},Ja=new WeakMap,cp=new WeakMap,up={},E0=0,sP=function(e){return e&&(e.host||sP(e.parentNode))},ZV=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=sP(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})},qV=function(e,t,n,r){var o=ZV(t,Array.isArray(e)?e:[e]);up[n]||(up[n]=new WeakMap);var i=up[n],s=[],l=new Set,u=new Set(o),d=function(m){!m||l.has(m)||(l.add(m),d(m.parentNode))};o.forEach(d);var h=function(m){!m||u.has(m)||Array.prototype.forEach.call(m.children,function(g){if(l.has(g))h(g);else{var y=g.getAttribute(r),x=y!==null&&y!=="false",_=(Ja.get(g)||0)+1,C=(i.get(g)||0)+1;Ja.set(g,_),i.set(g,C),s.push(g),_===1&&x&&cp.set(g,!0),C===1&&g.setAttribute(n,"true"),x||g.setAttribute(r,"true")}})};return h(t),l.clear(),E0++,function(){s.forEach(function(m){var g=Ja.get(m)-1,y=i.get(m)-1;Ja.set(m,g),i.set(m,y),g||(cp.has(m)||m.removeAttribute(r),cp.delete(m)),y||m.removeAttribute(n)}),E0--,E0||(Ja=new WeakMap,Ja=new WeakMap,cp=new WeakMap,up={})}},Xm=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),o=t||XV(e);return o?(r.push.apply(r,Array.from(o.querySelectorAll("[aria-live]"))),qV(r,o,n,"aria-hidden")):function(){return null}};const aP="Dialog",[lP,cP]=An(aP),[QV,bo]=lP(aP),JV=e=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:o,onOpenChange:i,modal:s=!0}=e,l=f.useRef(null),u=f.useRef(null),[d=!1,h]=Zr({prop:r,defaultProp:o,onChange:i});return f.createElement(QV,{scope:t,triggerRef:l,contentRef:u,contentId:nr(),titleId:nr(),descriptionId:nr(),open:d,onOpenChange:h,onOpenToggle:f.useCallback(()=>h(m=>!m),[h]),modal:s},n)},eW="DialogTrigger",uP=f.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=bo(eW,n),i=Be(t,o.triggerRef);return f.createElement(Pe.button,Y({type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":_x(o.open)},r,{ref:i,onClick:ue(e.onClick,o.onOpenToggle)}))}),dP="DialogPortal",[tW,fP]=lP(dP,{forceMount:void 0}),nW=e=>{const{__scopeDialog:t,forceMount:n,children:r,container:o}=e,i=bo(dP,t);return f.createElement(tW,{scope:t,forceMount:n},f.Children.map(r,s=>f.createElement(xn,{present:n||i.open},f.createElement(Md,{asChild:!0,container:o},s))))},f1="DialogOverlay",rW=f.forwardRef((e,t)=>{const n=fP(f1,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,i=bo(f1,e.__scopeDialog);return i.modal?f.createElement(xn,{present:r||i.open},f.createElement(oW,Y({},o,{ref:t}))):null}),oW=f.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=bo(f1,n);return f.createElement(Gm,{as:Wo,allowPinchZoom:!0,shards:[o.contentRef]},f.createElement(Pe.div,Y({"data-state":_x(o.open)},r,{ref:t,style:{pointerEvents:"auto",...r.style}})))}),oc="DialogContent",iW=f.forwardRef((e,t)=>{const n=fP(oc,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,i=bo(oc,e.__scopeDialog);return f.createElement(xn,{present:r||i.open},i.modal?f.createElement(sW,Y({},o,{ref:t})):f.createElement(aW,Y({},o,{ref:t})))}),sW=f.forwardRef((e,t)=>{const n=bo(oc,e.__scopeDialog),r=f.useRef(null),o=Be(t,n.contentRef,r);return f.useEffect(()=>{const i=r.current;if(i)return Xm(i)},[]),f.createElement(pP,Y({},e,{ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:ue(e.onCloseAutoFocus,i=>{var s;i.preventDefault(),(s=n.triggerRef.current)===null||s===void 0||s.focus()}),onPointerDownOutside:ue(e.onPointerDownOutside,i=>{const s=i.detail.originalEvent,l=s.button===0&&s.ctrlKey===!0;(s.button===2||l)&&i.preventDefault()}),onFocusOutside:ue(e.onFocusOutside,i=>i.preventDefault())}))}),aW=f.forwardRef((e,t)=>{const n=bo(oc,e.__scopeDialog),r=f.useRef(!1),o=f.useRef(!1);return f.createElement(pP,Y({},e,{ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var s;if((s=e.onCloseAutoFocus)===null||s===void 0||s.call(e,i),!i.defaultPrevented){var l;r.current||(l=n.triggerRef.current)===null||l===void 0||l.focus(),i.preventDefault()}r.current=!1,o.current=!1},onInteractOutside:i=>{var s,l;(s=e.onInteractOutside)===null||s===void 0||s.call(e,i),i.defaultPrevented||(r.current=!0,i.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const u=i.target;((l=n.triggerRef.current)===null||l===void 0?void 0:l.contains(u))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&o.current&&i.preventDefault()}}))}),pP=f.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:i,...s}=e,l=bo(oc,n),u=f.useRef(null),d=Be(t,u);return Km(),f.createElement(f.Fragment,null,f.createElement(Hm,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:i},f.createElement(yc,Y({role:"dialog",id:l.contentId,"aria-describedby":l.descriptionId,"aria-labelledby":l.titleId,"data-state":_x(l.open)},s,{ref:d,onDismiss:()=>l.onOpenChange(!1)}))),!1)}),hP="DialogTitle",lW=f.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=bo(hP,n);return f.createElement(Pe.h2,Y({id:o.titleId},r,{ref:t}))}),cW="DialogDescription",mP=f.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=bo(cW,n);return f.createElement(Pe.p,Y({id:o.descriptionId},r,{ref:t}))}),uW="DialogClose",dW=f.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=bo(uW,n);return f.createElement(Pe.button,Y({type:"button"},r,{ref:t,onClick:ue(e.onClick,()=>o.onOpenChange(!1))}))});function _x(e){return e?"open":"closed"}const fW="DialogTitleWarning",[pW,yte]=fB(fW,{contentName:oc,titleName:hP,docsSlug:"dialog"}),Sx=JV,gP=uP,Ex=nW,Nd=rW,Dd=iW,Id=lW,Ld=mP,Cx=dW,Zm=Sx,$x=gP,hW=Ex,vP=f.forwardRef(({className:e,...t},n)=>v.jsx(Nd,{ref:n,className:Ce("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t}));vP.displayName=Nd.displayName;const Fd=f.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(hW,{children:[v.jsx(vP,{}),v.jsxs(Dd,{ref:r,className:Ce("fixed left-[50%] top-[50%] z-50 flex flex-col w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",e,"outline-none"),onCloseAutoFocus:o=>o.preventDefault(),...n,children:[t,v.jsxs(Cx,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[v.jsx(yT,{className:"h-4 w-4"}),v.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Fd.displayName=Dd.displayName;const yP=({className:e,...t})=>v.jsx("div",{className:Ce("flex flex-col space-y-1.5 text-center sm:text-left",e),...t});yP.displayName="DialogHeader";const jd=f.forwardRef(({className:e,...t},n)=>v.jsx(Id,{ref:n,className:Ce("text-2xl font-semibold leading-none tracking-tight",e),...t}));jd.displayName=Id.displayName;const mW=f.forwardRef(({className:e,...t},n)=>v.jsx(Ld,{ref:n,className:Ce("text-sm text-muted-foreground",e),...t}));mW.displayName=Ld.displayName;function p1(){return p1=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 SW=function(t,n,r){r===void 0&&(r=!1);var o=n.alt,i=n.meta,s=n.mod,l=n.shift,u=n.ctrl,d=n.keys,h=t.key,m=t.code,g=t.ctrlKey,y=t.metaKey,x=t.shiftKey,_=t.altKey,C=ss(m),S=h.toLowerCase();if(!r){if(o===!_&&S!=="alt"||l===!x&&S!=="shift")return!1;if(s){if(!y&&!g)return!1}else if(i===!y&&S!=="meta"&&S!=="os"||u===!g&&S!=="ctrl"&&S!=="control")return!1}return d&&d.length===1&&(d.includes(S)||d.includes(C))?!0:d?yW(d):!d},EW=f.createContext(void 0),CW=function(){return f.useContext(EW)};function SP(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&&SP(e[r],t[r])},!0):e===t}var $W=f.createContext({hotkeys:[],enabledScopes:[],toggleScope:function(){},enableScope:function(){},disableScope:function(){}}),kW=function(){return f.useContext($W)};function RW(e){var t=f.useRef(void 0);return SP(t.current,e)||(t.current=e),t.current}var e2=function(t){t.stopPropagation(),t.preventDefault(),t.stopImmediatePropagation()},TW=typeof window<"u"?f.useLayoutEffect:f.useEffect;function PW(e,t,n,r){var o=f.useRef(null),i=f.useRef(!1),s=n instanceof Array?r instanceof Array?void 0:r:n,l=kx(e)?e.join(s==null?void 0:s.splitKey):e,u=n instanceof Array?n:r instanceof Array?r:void 0,d=f.useCallback(t,u??[]),h=f.useRef(d);u?h.current=d:h.current=t;var m=RW(s),g=kW(),y=g.enabledScopes,x=CW();return TW(function(){if(!((m==null?void 0:m.enabled)===!1||!_W(y,m==null?void 0:m.scopes))){var _=function(k,P){var M;if(P===void 0&&(P=!1),!(bW(k)&&!_P(k,m==null?void 0:m.enableOnFormTags))&&!(m!=null&&m.ignoreEventWhen!=null&&m.ignoreEventWhen(k))){if(o.current!==null&&document.activeElement!==o.current&&!o.current.contains(document.activeElement)){e2(k);return}(M=k.target)!=null&&M.isContentEditable&&!(m!=null&&m.enableOnContentEditable)||C0(l,m==null?void 0:m.splitKey).forEach(function(A){var O,F=$0(A,m==null?void 0:m.combinationKey);if(SW(k,F,m==null?void 0:m.ignoreModifiers)||(O=F.keys)!=null&&O.includes("*")){if(P&&i.current)return;if(wW(k,F,m==null?void 0:m.preventDefault),!xW(k,F,m==null?void 0:m.enabled)){e2(k);return}h.current(k,F),P||(i.current=!0)}})}},C=function(k){k.key!==void 0&&(xP(ss(k.code)),((m==null?void 0:m.keydown)===void 0&&(m==null?void 0:m.keyup)!==!0||m!=null&&m.keydown)&&_(k))},S=function(k){k.key!==void 0&&(bP(ss(k.code)),i.current=!1,m!=null&&m.keyup&&_(k,!0))},b=o.current||(s==null?void 0:s.document)||document;return b.addEventListener("keyup",S),b.addEventListener("keydown",C),x&&C0(l,m==null?void 0:m.splitKey).forEach(function(E){return x.addHotkey($0(E,m==null?void 0:m.combinationKey,m==null?void 0:m.description))}),function(){b.removeEventListener("keyup",S),b.removeEventListener("keydown",C),x&&C0(l,m==null?void 0:m.splitKey).forEach(function(E){return x.removeHotkey($0(E,m==null?void 0:m.combinationKey,m==null?void 0:m.description))})}}},[l,m,y]),o}const Zn=(e,t,n)=>{const r=bt(i=>i.disableShortCuts);return PW(e,t,{enabled:!r},n)};function ur(e){const{content:t,keys:n}=e;return v.jsxs("div",{className:"flex justify-between",children:[v.jsx("div",{children:t}),v.jsx("div",{className:"flex gap-[8px]",children:n.map(r=>v.jsx("div",{className:"border px-2 py-1 rounded-lg",children:r},r))})]})}const AW=function(){return/macintosh|mac os x/i.test(navigator.userAgent)},dp=()=>AW()?"Cmd":"Ctrl";function OW(){const[e,t]=u1(!1);return Zn("h",()=>{t()}),v.jsxs(Zm,{open:e,onOpenChange:t,children:[v.jsx($x,{asChild:!0,children:v.jsx(vn,{tooltip:"Hotkeys",children:v.jsx(eV,{})})}),v.jsx(Fd,{children:v.jsxs(yP,{children:[v.jsx(jd,{children:"Hotkeys"}),v.jsxs("div",{className:"flex gap-2 flex-col pt-4",children:[v.jsx(ur,{content:"Pan",keys:["Space + Drag"]}),v.jsx(ur,{content:"Reset Zoom/Pan",keys:["Esc"]}),v.jsx(ur,{content:"Decrease Brush Size",keys:["["]}),v.jsx(ur,{content:"Increase Brush Size",keys:["]"]}),v.jsx(ur,{content:"View Original Image",keys:["Hold Tab"]}),v.jsx(ur,{content:"Undo",keys:[dp(),"Z"]}),v.jsx(ur,{content:"Redo",keys:[dp(),"Shift","Z"]}),v.jsx(ur,{content:"Copy Result",keys:[dp(),"C"]}),v.jsx(ur,{content:"Paste Image",keys:[dp(),"V"]}),v.jsx(ur,{content:"Trigger Manually Inpainting",keys:["Shift","R"]}),v.jsx(ur,{content:"Toggle Hotkeys Dialog",keys:["H"]}),v.jsx(ur,{content:"Toggle Settings Dialog",keys:["S"]}),v.jsx(ur,{content:"Toggle File Manager",keys:["F"]})]})]})})]})}function Rx(e){const[t]=f.useState(new Image),[n,r]=f.useState(!1);return f.useEffect(()=>{if(e)return t.onload=()=>{r(!0)},r(!1),t.src=URL.createObjectURL(e),()=>{t.onload=null}},[e,t]),[t,n]}const EP="Popover",[CP,wte]=An(EP,[Ns]),Tx=Ns(),[MW,bc]=CP(EP),NW=e=>{const{__scopePopover:t,children:n,open:r,defaultOpen:o,onOpenChange:i,modal:s=!1}=e,l=Tx(t),u=f.useRef(null),[d,h]=f.useState(!1),[m=!1,g]=Zr({prop:r,defaultProp:o,onChange:i});return f.createElement(Od,l,f.createElement(MW,{scope:t,contentId:nr(),triggerRef:u,open:m,onOpenChange:g,onOpenToggle:f.useCallback(()=>g(y=>!y),[g]),hasCustomAnchor:d,onCustomAnchorAdd:f.useCallback(()=>h(!0),[]),onCustomAnchorRemove:f.useCallback(()=>h(!1),[]),modal:s},n))},DW="PopoverTrigger",IW=f.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,o=bc(DW,n),i=Tx(n),s=Be(t,o.triggerRef),l=f.createElement(Pe.button,Y({type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":RP(o.open)},r,{ref:s,onClick:ue(e.onClick,o.onOpenToggle)}));return o.hasCustomAnchor?l:f.createElement(zm,Y({asChild:!0},i),l)}),$P="PopoverPortal",[LW,FW]=CP($P,{forceMount:void 0}),jW=e=>{const{__scopePopover:t,forceMount:n,children:r,container:o}=e,i=bc($P,t);return f.createElement(LW,{scope:t,forceMount:n},f.createElement(xn,{present:n||i.open},f.createElement(Md,{asChild:!0,container:o},r)))},od="PopoverContent",zW=f.forwardRef((e,t)=>{const n=FW(od,e.__scopePopover),{forceMount:r=n.forceMount,...o}=e,i=bc(od,e.__scopePopover);return f.createElement(xn,{present:r||i.open},i.modal?f.createElement(BW,Y({},o,{ref:t})):f.createElement(UW,Y({},o,{ref:t})))}),BW=f.forwardRef((e,t)=>{const n=bc(od,e.__scopePopover),r=f.useRef(null),o=Be(t,r),i=f.useRef(!1);return f.useEffect(()=>{const s=r.current;if(s)return Xm(s)},[]),f.createElement(Gm,{as:Wo,allowPinchZoom:!0},f.createElement(kP,Y({},e,{ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:ue(e.onCloseAutoFocus,s=>{var l;s.preventDefault(),i.current||(l=n.triggerRef.current)===null||l===void 0||l.focus()}),onPointerDownOutside:ue(e.onPointerDownOutside,s=>{const l=s.detail.originalEvent,u=l.button===0&&l.ctrlKey===!0,d=l.button===2||u;i.current=d},{checkForDefaultPrevented:!1}),onFocusOutside:ue(e.onFocusOutside,s=>s.preventDefault(),{checkForDefaultPrevented:!1})})))}),UW=f.forwardRef((e,t)=>{const n=bc(od,e.__scopePopover),r=f.useRef(!1),o=f.useRef(!1);return f.createElement(kP,Y({},e,{ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var s;if((s=e.onCloseAutoFocus)===null||s===void 0||s.call(e,i),!i.defaultPrevented){var l;r.current||(l=n.triggerRef.current)===null||l===void 0||l.focus(),i.preventDefault()}r.current=!1,o.current=!1},onInteractOutside:i=>{var s,l;(s=e.onInteractOutside)===null||s===void 0||s.call(e,i),i.defaultPrevented||(r.current=!0,i.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const u=i.target;((l=n.triggerRef.current)===null||l===void 0?void 0:l.contains(u))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&o.current&&i.preventDefault()}}))}),kP=f.forwardRef((e,t)=>{const{__scopePopover:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:i,disableOutsidePointerEvents:s,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:d,onInteractOutside:h,...m}=e,g=bc(od,n),y=Tx(n);return Km(),f.createElement(Hm,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:i},f.createElement(yc,{asChild:!0,disableOutsidePointerEvents:s,onInteractOutside:h,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:d,onDismiss:()=>g.onOpenChange(!1)},f.createElement(Bm,Y({"data-state":RP(g.open),role:"dialog",id:g.contentId},y,m,{ref:t,style:{...m.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}}))))});function RP(e){return e?"open":"closed"}const VW=NW,WW=IW,HW=jW,TP=zW,KW=VW,YW=WW,PP=f.forwardRef(({className:e,align:t="center",sideOffset:n=4,...r},o)=>v.jsx(HW,{children:v.jsx(TP,{ref:o,align:t,tabIndex:-1,sideOffset:n,className:Ce("z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...r})}));PP.displayName=TP.displayName;function GW(){var e=f.useRef(!0);return e.current?(e.current=!1,!0):e.current}var XW=function(e,t){var n=GW();f.useEffect(function(){if(!n)return e()},t)};const ZW=XW;var qW=function(){};function Px(e){for(var t=[],n=1;n{const[e,t,n,r,o,i]=bt(g=>[g.getIsProcessing(),g.settings.prompt,g.updateSettings,g.runInpainting,g.showPrevMask,g.hidePrevMask]),s=f.useRef(null);OP(s,()=>{s!=null&&s.current&&s.current.blur()});const l=g=>{g.preventDefault(),g.stopPropagation();const y=g.target;n({prompt:y.value})},u=()=>{e||r()},d=g=>{g.key==="Enter"&&!e&&u()},h=()=>{o()},m=()=>{i()};return v.jsxs("div",{className:"flex gap-4 items-center",children:[v.jsx(Pd,{ref:s,className:"min-w-[500px]",value:t,onInput:l,onKeyUp:d,placeholder:"I want to repaint of..."}),v.jsx(Rn,{size:"sm",onClick:u,disabled:e,onMouseEnter:h,onMouseLeave:m,children:"Dream"})]})};var Lh={exports:{}};/** + * @license + * Lodash + * Copyright OpenJS Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */Lh.exports;(function(e,t){(function(){var n,r="4.17.21",o=200,i="Unsupported core-js use. Try https://npms.io/search?q=ponyfill.",s="Expected a function",l="Invalid `variable` option passed into `_.template`",u="__lodash_hash_undefined__",d=500,h="__lodash_placeholder__",m=1,g=2,y=4,x=1,_=2,C=1,S=2,b=4,E=8,k=16,P=32,M=64,A=128,O=256,F=512,V=30,J="...",G=800,ae=16,U=1,te=2,L=3,ie=1/0,K=9007199254740991,Q=17976931348623157e292,W=NaN,le=4294967295,ge=le-1,Ve=le>>>1,Ue=[["ary",A],["bind",C],["bindKey",S],["curry",E],["curryRight",k],["flip",F],["partial",P],["partialRight",M],["rearg",O]],We="[object Arguments]",Me="[object Array]",fe="[object AsyncFunction]",xe="[object Boolean]",$e="[object Date]",Ae="[object DOMException]",Oe="[object Error]",je="[object Function]",Ot="[object GeneratorFunction]",ct="[object Map]",Yt="[object Number]",Er="[object Null]",gt="[object Object]",js="[object Promise]",I="[object Proxy]",X="[object RegExp]",Z="[object Set]",we="[object String]",he="[object Symbol]",de="[object Undefined]",ke="[object WeakMap]",ft="[object WeakSet]",pt="[object ArrayBuffer]",bn="[object DataView]",Cr="[object Float32Array]",ki="[object Float64Array]",_o="[object Int8Array]",Vn="[object Int16Array]",Da="[object Int32Array]",Ri="[object Uint8Array]",zs="[object Uint8ClampedArray]",Ti="[object Uint16Array]",$c="[object Uint32Array]",yg=/\b__p \+= '';/g,wg=/\b(__p \+=) '' \+/g,Kd=/(__e\(.*?\)|\b__t\)) \+\n'';/g,kc=/&(?:amp|lt|gt|quot|#39);/g,Rc=/[&<>"']/g,Tc=RegExp(kc.source),xg=RegExp(Rc.source),Pc=/<%-([\s\S]+?)%>/g,Yd=/<%([\s\S]+?)%>/g,Ac=/<%=([\s\S]+?)%>/g,bg=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,_g=/^\w*$/,Sg=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,H=/[\\^$.*+?()[\]{}|]/g,Ge=RegExp(H.source),st=/^\s+/,Qr=/\s/,an=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,Gd=/\{\n\/\* \[wrapped with (.+)\] \*/,oO=/,? & /,iO=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,sO=/[()=,{}\[\]\/\s]/,aO=/\\(\\)?/g,lO=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,db=/\w*$/,cO=/^[-+]0x[0-9a-f]+$/i,uO=/^0b[01]+$/i,dO=/^\[object .+?Constructor\]$/,fO=/^0o[0-7]+$/i,pO=/^(?:0|[1-9]\d*)$/,hO=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,Xd=/($^)/,mO=/['\n\r\u2028\u2029\\]/g,Zd="\\ud800-\\udfff",gO="\\u0300-\\u036f",vO="\\ufe20-\\ufe2f",yO="\\u20d0-\\u20ff",fb=gO+vO+yO,pb="\\u2700-\\u27bf",hb="a-z\\xdf-\\xf6\\xf8-\\xff",wO="\\xac\\xb1\\xd7\\xf7",xO="\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf",bO="\\u2000-\\u206f",_O=" \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",mb="A-Z\\xc0-\\xd6\\xd8-\\xde",gb="\\ufe0e\\ufe0f",vb=wO+xO+bO+_O,Eg="['’]",SO="["+Zd+"]",yb="["+vb+"]",qd="["+fb+"]",wb="\\d+",EO="["+pb+"]",xb="["+hb+"]",bb="[^"+Zd+vb+wb+pb+hb+mb+"]",Cg="\\ud83c[\\udffb-\\udfff]",CO="(?:"+qd+"|"+Cg+")",_b="[^"+Zd+"]",$g="(?:\\ud83c[\\udde6-\\uddff]){2}",kg="[\\ud800-\\udbff][\\udc00-\\udfff]",Ia="["+mb+"]",Sb="\\u200d",Eb="(?:"+xb+"|"+bb+")",$O="(?:"+Ia+"|"+bb+")",Cb="(?:"+Eg+"(?:d|ll|m|re|s|t|ve))?",$b="(?:"+Eg+"(?:D|LL|M|RE|S|T|VE))?",kb=CO+"?",Rb="["+gb+"]?",kO="(?:"+Sb+"(?:"+[_b,$g,kg].join("|")+")"+Rb+kb+")*",RO="\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",TO="\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])",Tb=Rb+kb+kO,PO="(?:"+[EO,$g,kg].join("|")+")"+Tb,AO="(?:"+[_b+qd+"?",qd,$g,kg,SO].join("|")+")",OO=RegExp(Eg,"g"),MO=RegExp(qd,"g"),Rg=RegExp(Cg+"(?="+Cg+")|"+AO+Tb,"g"),NO=RegExp([Ia+"?"+xb+"+"+Cb+"(?="+[yb,Ia,"$"].join("|")+")",$O+"+"+$b+"(?="+[yb,Ia+Eb,"$"].join("|")+")",Ia+"?"+Eb+"+"+Cb,Ia+"+"+$b,TO,RO,wb,PO].join("|"),"g"),DO=RegExp("["+Sb+Zd+fb+gb+"]"),IO=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,LO=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],FO=-1,kt={};kt[Cr]=kt[ki]=kt[_o]=kt[Vn]=kt[Da]=kt[Ri]=kt[zs]=kt[Ti]=kt[$c]=!0,kt[We]=kt[Me]=kt[pt]=kt[xe]=kt[bn]=kt[$e]=kt[Oe]=kt[je]=kt[ct]=kt[Yt]=kt[gt]=kt[X]=kt[Z]=kt[we]=kt[ke]=!1;var Et={};Et[We]=Et[Me]=Et[pt]=Et[bn]=Et[xe]=Et[$e]=Et[Cr]=Et[ki]=Et[_o]=Et[Vn]=Et[Da]=Et[ct]=Et[Yt]=Et[gt]=Et[X]=Et[Z]=Et[we]=Et[he]=Et[Ri]=Et[zs]=Et[Ti]=Et[$c]=!0,Et[Oe]=Et[je]=Et[ke]=!1;var jO={À:"A",Á:"A",Â:"A",Ã:"A",Ä:"A",Å:"A",à:"a",á:"a",â:"a",ã:"a",ä:"a",å:"a",Ç:"C",ç:"c",Ð:"D",ð:"d",È:"E",É:"E",Ê:"E",Ë:"E",è:"e",é:"e",ê:"e",ë:"e",Ì:"I",Í:"I",Î:"I",Ï:"I",ì:"i",í:"i",î:"i",ï:"i",Ñ:"N",ñ:"n",Ò:"O",Ó:"O",Ô:"O",Õ:"O",Ö:"O",Ø:"O",ò:"o",ó:"o",ô:"o",õ:"o",ö:"o",ø:"o",Ù:"U",Ú:"U",Û:"U",Ü:"U",ù:"u",ú:"u",û:"u",ü:"u",Ý:"Y",ý:"y",ÿ:"y",Æ:"Ae",æ:"ae",Þ:"Th",þ:"th",ß:"ss",Ā:"A",Ă:"A",Ą:"A",ā:"a",ă:"a",ą:"a",Ć:"C",Ĉ:"C",Ċ:"C",Č:"C",ć:"c",ĉ:"c",ċ:"c",č:"c",Ď:"D",Đ:"D",ď:"d",đ:"d",Ē:"E",Ĕ:"E",Ė:"E",Ę:"E",Ě:"E",ē:"e",ĕ:"e",ė:"e",ę:"e",ě:"e",Ĝ:"G",Ğ:"G",Ġ:"G",Ģ:"G",ĝ:"g",ğ:"g",ġ:"g",ģ:"g",Ĥ:"H",Ħ:"H",ĥ:"h",ħ:"h",Ĩ:"I",Ī:"I",Ĭ:"I",Į:"I",İ:"I",ĩ:"i",ī:"i",ĭ:"i",į:"i",ı:"i",Ĵ:"J",ĵ:"j",Ķ:"K",ķ:"k",ĸ:"k",Ĺ:"L",Ļ:"L",Ľ:"L",Ŀ:"L",Ł:"L",ĺ:"l",ļ:"l",ľ:"l",ŀ:"l",ł:"l",Ń:"N",Ņ:"N",Ň:"N",Ŋ:"N",ń:"n",ņ:"n",ň:"n",ŋ:"n",Ō:"O",Ŏ:"O",Ő:"O",ō:"o",ŏ:"o",ő:"o",Ŕ:"R",Ŗ:"R",Ř:"R",ŕ:"r",ŗ:"r",ř:"r",Ś:"S",Ŝ:"S",Ş:"S",Š:"S",ś:"s",ŝ:"s",ş:"s",š:"s",Ţ:"T",Ť:"T",Ŧ:"T",ţ:"t",ť:"t",ŧ:"t",Ũ:"U",Ū:"U",Ŭ:"U",Ů:"U",Ű:"U",Ų:"U",ũ:"u",ū:"u",ŭ:"u",ů:"u",ű:"u",ų:"u",Ŵ:"W",ŵ:"w",Ŷ:"Y",ŷ:"y",Ÿ:"Y",Ź:"Z",Ż:"Z",Ž:"Z",ź:"z",ż:"z",ž:"z",IJ:"IJ",ij:"ij",Œ:"Oe",œ:"oe",ʼn:"'n",ſ:"s"},zO={"&":"&","<":"<",">":">",'"':""","'":"'"},BO={"&":"&","<":"<",">":">",""":'"',"'":"'"},UO={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},VO=parseFloat,WO=parseInt,Pb=typeof Yc=="object"&&Yc&&Yc.Object===Object&&Yc,HO=typeof self=="object"&&self&&self.Object===Object&&self,fn=Pb||HO||Function("return this")(),Tg=t&&!t.nodeType&&t,Bs=Tg&&!0&&e&&!e.nodeType&&e,Ab=Bs&&Bs.exports===Tg,Pg=Ab&&Pb.process,$r=function(){try{var j=Bs&&Bs.require&&Bs.require("util").types;return j||Pg&&Pg.binding&&Pg.binding("util")}catch{}}(),Ob=$r&&$r.isArrayBuffer,Mb=$r&&$r.isDate,Nb=$r&&$r.isMap,Db=$r&&$r.isRegExp,Ib=$r&&$r.isSet,Lb=$r&&$r.isTypedArray;function or(j,ee,q){switch(q.length){case 0:return j.call(ee);case 1:return j.call(ee,q[0]);case 2:return j.call(ee,q[0],q[1]);case 3:return j.call(ee,q[0],q[1],q[2])}return j.apply(ee,q)}function KO(j,ee,q,_e){for(var Ke=-1,ht=j==null?0:j.length;++Ke-1}function Ag(j,ee,q){for(var _e=-1,Ke=j==null?0:j.length;++_e-1;);return q}function Hb(j,ee){for(var q=j.length;q--&&La(ee,j[q],0)>-1;);return q}function t6(j,ee){for(var q=j.length,_e=0;q--;)j[q]===ee&&++_e;return _e}var n6=Dg(jO),r6=Dg(zO);function o6(j){return"\\"+UO[j]}function i6(j,ee){return j==null?n:j[ee]}function Fa(j){return DO.test(j)}function s6(j){return IO.test(j)}function a6(j){for(var ee,q=[];!(ee=j.next()).done;)q.push(ee.value);return q}function jg(j){var ee=-1,q=Array(j.size);return j.forEach(function(_e,Ke){q[++ee]=[Ke,_e]}),q}function Kb(j,ee){return function(q){return j(ee(q))}}function Oi(j,ee){for(var q=-1,_e=j.length,Ke=0,ht=[];++q<_e;){var en=j[q];(en===ee||en===h)&&(j[q]=h,ht[Ke++]=q)}return ht}function ef(j){var ee=-1,q=Array(j.size);return j.forEach(function(_e){q[++ee]=_e}),q}function l6(j){var ee=-1,q=Array(j.size);return j.forEach(function(_e){q[++ee]=[_e,_e]}),q}function c6(j,ee,q){for(var _e=q-1,Ke=j.length;++_e-1}function G6(a,c){var p=this.__data__,w=gf(p,a);return w<0?(++this.size,p.push([a,c])):p[w][1]=c,this}Xo.prototype.clear=W6,Xo.prototype.delete=H6,Xo.prototype.get=K6,Xo.prototype.has=Y6,Xo.prototype.set=G6;function Zo(a){var c=-1,p=a==null?0:a.length;for(this.clear();++c=c?a:c)),a}function Pr(a,c,p,w,$,T){var N,D=c&m,B=c&g,ne=c&y;if(p&&(N=$?p(a,w,$,T):p(a)),N!==n)return N;if(!It(a))return a;var re=Ye(a);if(re){if(N=QM(a),!D)return Wn(a,N)}else{var se=Sn(a),me=se==je||se==Ot;if(Fi(a))return R_(a,D);if(se==gt||se==We||me&&!$){if(N=B||me?{}:Y_(a),!D)return B?BM(a,uM(N,a)):zM(a,o_(N,a))}else{if(!Et[se])return $?a:{};N=JM(a,se,D)}}T||(T=new eo);var Re=T.get(a);if(Re)return Re;T.set(a,N),_S(a)?a.forEach(function(Le){N.add(Pr(Le,c,p,Le,a,T))}):xS(a)&&a.forEach(function(Le,nt){N.set(nt,Pr(Le,c,p,nt,a,T))});var Ie=ne?B?dv:uv:B?Kn:ln,Qe=re?n:Ie(a);return kr(Qe||a,function(Le,nt){Qe&&(nt=Le,Le=a[nt]),Fc(N,nt,Pr(Le,c,p,nt,a,T))}),N}function dM(a){var c=ln(a);return function(p){return i_(p,a,c)}}function i_(a,c,p){var w=p.length;if(a==null)return!w;for(a=_t(a);w--;){var $=p[w],T=c[$],N=a[$];if(N===n&&!($ in a)||!T(N))return!1}return!0}function s_(a,c,p){if(typeof a!="function")throw new Rr(s);return Hc(function(){a.apply(n,p)},c)}function jc(a,c,p,w){var $=-1,T=Qd,N=!0,D=a.length,B=[],ne=c.length;if(!D)return B;p&&(c=Mt(c,ir(p))),w?(T=Ag,N=!1):c.length>=o&&(T=Oc,N=!1,c=new Ws(c));e:for(;++$$?0:$+p),w=w===n||w>$?$:qe(w),w<0&&(w+=$),w=p>w?0:ES(w);p0&&p(D)?c>1?pn(D,c-1,p,w,$):Ai($,D):w||($[$.length]=D)}return $}var Kg=N_(),c_=N_(!0);function So(a,c){return a&&Kg(a,c,ln)}function Yg(a,c){return a&&c_(a,c,ln)}function yf(a,c){return Pi(c,function(p){return ti(a[p])})}function Ks(a,c){c=Ii(c,a);for(var p=0,w=c.length;a!=null&&pc}function hM(a,c){return a!=null&&yt.call(a,c)}function mM(a,c){return a!=null&&c in _t(a)}function gM(a,c,p){return a>=_n(c,p)&&a=120&&re.length>=120)?new Ws(N&&re):n}re=a[0];var se=-1,me=D[0];e:for(;++se<$&&ne.length-1;)D!==a&&cf.call(D,B,1),cf.call(a,B,1);return a}function x_(a,c){for(var p=a?c.length:0,w=p-1;p--;){var $=c[p];if(p==w||$!==T){var T=$;ei($)?cf.call(a,$,1):rv(a,$)}}return a}function ev(a,c){return a+ff(e_()*(c-a+1))}function TM(a,c,p,w){for(var $=-1,T=tn(df((c-a)/(p||1)),0),N=q(T);T--;)N[w?T:++$]=a,a+=p;return N}function tv(a,c){var p="";if(!a||c<1||c>K)return p;do c%2&&(p+=a),c=ff(c/2),c&&(a+=a);while(c);return p}function et(a,c){return yv(Z_(a,c,Yn),a+"")}function PM(a){return r_(Xa(a))}function AM(a,c){var p=Xa(a);return Tf(p,Hs(c,0,p.length))}function Uc(a,c,p,w){if(!It(a))return a;c=Ii(c,a);for(var $=-1,T=c.length,N=T-1,D=a;D!=null&&++$$?0:$+c),p=p>$?$:p,p<0&&(p+=$),$=c>p?0:p-c>>>0,c>>>=0;for(var T=q($);++w<$;)T[w]=a[w+c];return T}function NM(a,c){var p;return Ni(a,function(w,$,T){return p=c(w,$,T),!p}),!!p}function xf(a,c,p){var w=0,$=a==null?w:a.length;if(typeof c=="number"&&c===c&&$<=Ve){for(;w<$;){var T=w+$>>>1,N=a[T];N!==null&&!ar(N)&&(p?N<=c:N=o){var ne=c?null:HM(a);if(ne)return ef(ne);N=!1,$=Oc,B=new Ws}else B=c?[]:D;e:for(;++w=w?a:Ar(a,c,p)}var k_=_6||function(a){return fn.clearTimeout(a)};function R_(a,c){if(c)return a.slice();var p=a.length,w=Xb?Xb(p):new a.constructor(p);return a.copy(w),w}function av(a){var c=new a.constructor(a.byteLength);return new af(c).set(new af(a)),c}function IM(a,c){var p=c?av(a.buffer):a.buffer;return new a.constructor(p,a.byteOffset,a.byteLength)}function LM(a){var c=new a.constructor(a.source,db.exec(a));return c.lastIndex=a.lastIndex,c}function FM(a){return Lc?_t(Lc.call(a)):{}}function T_(a,c){var p=c?av(a.buffer):a.buffer;return new a.constructor(p,a.byteOffset,a.length)}function P_(a,c){if(a!==c){var p=a!==n,w=a===null,$=a===a,T=ar(a),N=c!==n,D=c===null,B=c===c,ne=ar(c);if(!D&&!ne&&!T&&a>c||T&&N&&B&&!D&&!ne||w&&N&&B||!p&&B||!$)return 1;if(!w&&!T&&!ne&&a=D)return B;var ne=p[w];return B*(ne=="desc"?-1:1)}}return a.index-c.index}function A_(a,c,p,w){for(var $=-1,T=a.length,N=p.length,D=-1,B=c.length,ne=tn(T-N,0),re=q(B+ne),se=!w;++D1?p[$-1]:n,N=$>2?p[2]:n;for(T=a.length>3&&typeof T=="function"?($--,T):n,N&&Mn(p[0],p[1],N)&&(T=$<3?n:T,$=1),c=_t(c);++w<$;){var D=p[w];D&&a(c,D,w,T)}return c})}function M_(a,c){return function(p,w){if(p==null)return p;if(!Hn(p))return a(p,w);for(var $=p.length,T=c?$:-1,N=_t(p);(c?T--:++T<$)&&w(N[T],T,N)!==!1;);return p}}function N_(a){return function(c,p,w){for(var $=-1,T=_t(c),N=w(c),D=N.length;D--;){var B=N[a?D:++$];if(p(T[B],B,T)===!1)break}return c}}function UM(a,c,p){var w=c&C,$=Vc(a);function T(){var N=this&&this!==fn&&this instanceof T?$:a;return N.apply(w?p:this,arguments)}return T}function D_(a){return function(c){c=vt(c);var p=Fa(c)?Jr(c):n,w=p?p[0]:c.charAt(0),$=p?Li(p,1).join(""):c.slice(1);return w[a]()+$}}function Ka(a){return function(c){return Og(MS(OS(c).replace(OO,"")),a,"")}}function Vc(a){return function(){var c=arguments;switch(c.length){case 0:return new a;case 1:return new a(c[0]);case 2:return new a(c[0],c[1]);case 3:return new a(c[0],c[1],c[2]);case 4:return new a(c[0],c[1],c[2],c[3]);case 5:return new a(c[0],c[1],c[2],c[3],c[4]);case 6:return new a(c[0],c[1],c[2],c[3],c[4],c[5]);case 7:return new a(c[0],c[1],c[2],c[3],c[4],c[5],c[6])}var p=Wa(a.prototype),w=a.apply(p,c);return It(w)?w:p}}function VM(a,c,p){var w=Vc(a);function $(){for(var T=arguments.length,N=q(T),D=T,B=Ya($);D--;)N[D]=arguments[D];var ne=T<3&&N[0]!==B&&N[T-1]!==B?[]:Oi(N,B);if(T-=ne.length,T-1?$[T?c[N]:N]:n}}function L_(a){return Jo(function(c){var p=c.length,w=p,$=Tr.prototype.thru;for(a&&c.reverse();w--;){var T=c[w];if(typeof T!="function")throw new Rr(s);if($&&!N&&kf(T)=="wrapper")var N=new Tr([],!0)}for(w=N?w:p;++w1&&at.reverse(),re&&BD))return!1;var ne=T.get(a),re=T.get(c);if(ne&&re)return ne==c&&re==a;var se=-1,me=!0,Re=p&_?new Ws:n;for(T.set(a,c),T.set(c,a);++se1?"& ":"")+c[w],c=c.join(p>2?", ":" "),a.replace(an,`{ +/* [wrapped with `+c+`] */ +`)}function tN(a){return Ye(a)||Xs(a)||!!(Qb&&a&&a[Qb])}function ei(a,c){var p=typeof a;return c=c??K,!!c&&(p=="number"||p!="symbol"&&pO.test(a))&&a>-1&&a%1==0&&a0){if(++c>=G)return arguments[0]}else c=0;return a.apply(n,arguments)}}function Tf(a,c){var p=-1,w=a.length,$=w-1;for(c=c===n?w:c;++p1?a[c-1]:n;return p=typeof p=="function"?(a.pop(),p):n,lS(a,p)});function cS(a){var c=R(a);return c.__chain__=!0,c}function f7(a,c){return c(a),a}function Pf(a,c){return c(a)}var p7=Jo(function(a){var c=a.length,p=c?a[0]:0,w=this.__wrapped__,$=function(T){return Hg(T,a)};return c>1||this.__actions__.length||!(w instanceof ot)||!ei(p)?this.thru($):(w=w.slice(p,+p+(c?1:0)),w.__actions__.push({func:Pf,args:[$],thisArg:n}),new Tr(w,this.__chain__).thru(function(T){return c&&!T.length&&T.push(n),T}))});function h7(){return cS(this)}function m7(){return new Tr(this.value(),this.__chain__)}function g7(){this.__values__===n&&(this.__values__=SS(this.value()));var a=this.__index__>=this.__values__.length,c=a?n:this.__values__[this.__index__++];return{done:a,value:c}}function v7(){return this}function y7(a){for(var c,p=this;p instanceof mf;){var w=nS(p);w.__index__=0,w.__values__=n,c?$.__wrapped__=w:c=w;var $=w;p=p.__wrapped__}return $.__wrapped__=a,c}function w7(){var a=this.__wrapped__;if(a instanceof ot){var c=a;return this.__actions__.length&&(c=new ot(this)),c=c.reverse(),c.__actions__.push({func:Pf,args:[wv],thisArg:n}),new Tr(c,this.__chain__)}return this.thru(wv)}function x7(){return C_(this.__wrapped__,this.__actions__)}var b7=_f(function(a,c,p){yt.call(a,p)?++a[p]:qo(a,p,1)});function _7(a,c,p){var w=Ye(a)?Fb:fM;return p&&Mn(a,c,p)&&(c=n),w(a,De(c,3))}function S7(a,c){var p=Ye(a)?Pi:l_;return p(a,De(c,3))}var E7=I_(rS),C7=I_(oS);function $7(a,c){return pn(Af(a,c),1)}function k7(a,c){return pn(Af(a,c),ie)}function R7(a,c,p){return p=p===n?1:qe(p),pn(Af(a,c),p)}function uS(a,c){var p=Ye(a)?kr:Ni;return p(a,De(c,3))}function dS(a,c){var p=Ye(a)?YO:a_;return p(a,De(c,3))}var T7=_f(function(a,c,p){yt.call(a,p)?a[p].push(c):qo(a,p,[c])});function P7(a,c,p,w){a=Hn(a)?a:Xa(a),p=p&&!w?qe(p):0;var $=a.length;return p<0&&(p=tn($+p,0)),If(a)?p<=$&&a.indexOf(c,p)>-1:!!$&&La(a,c,p)>-1}var A7=et(function(a,c,p){var w=-1,$=typeof c=="function",T=Hn(a)?q(a.length):[];return Ni(a,function(N){T[++w]=$?or(c,N,p):zc(N,c,p)}),T}),O7=_f(function(a,c,p){qo(a,p,c)});function Af(a,c){var p=Ye(a)?Mt:h_;return p(a,De(c,3))}function M7(a,c,p,w){return a==null?[]:(Ye(c)||(c=c==null?[]:[c]),p=w?n:p,Ye(p)||(p=p==null?[]:[p]),y_(a,c,p))}var N7=_f(function(a,c,p){a[p?0:1].push(c)},function(){return[[],[]]});function D7(a,c,p){var w=Ye(a)?Og:Ub,$=arguments.length<3;return w(a,De(c,4),p,$,Ni)}function I7(a,c,p){var w=Ye(a)?GO:Ub,$=arguments.length<3;return w(a,De(c,4),p,$,a_)}function L7(a,c){var p=Ye(a)?Pi:l_;return p(a,Nf(De(c,3)))}function F7(a){var c=Ye(a)?r_:PM;return c(a)}function j7(a,c,p){(p?Mn(a,c,p):c===n)?c=1:c=qe(c);var w=Ye(a)?aM:AM;return w(a,c)}function z7(a){var c=Ye(a)?lM:MM;return c(a)}function B7(a){if(a==null)return 0;if(Hn(a))return If(a)?ja(a):a.length;var c=Sn(a);return c==ct||c==Z?a.size:qg(a).length}function U7(a,c,p){var w=Ye(a)?Mg:NM;return p&&Mn(a,c,p)&&(c=n),w(a,De(c,3))}var V7=et(function(a,c){if(a==null)return[];var p=c.length;return p>1&&Mn(a,c[0],c[1])?c=[]:p>2&&Mn(c[0],c[1],c[2])&&(c=[c[0]]),y_(a,pn(c,1),[])}),Of=S6||function(){return fn.Date.now()};function W7(a,c){if(typeof c!="function")throw new Rr(s);return a=qe(a),function(){if(--a<1)return c.apply(this,arguments)}}function fS(a,c,p){return c=p?n:c,c=a&&c==null?a.length:c,Qo(a,A,n,n,n,n,c)}function pS(a,c){var p;if(typeof c!="function")throw new Rr(s);return a=qe(a),function(){return--a>0&&(p=c.apply(this,arguments)),a<=1&&(c=n),p}}var bv=et(function(a,c,p){var w=C;if(p.length){var $=Oi(p,Ya(bv));w|=P}return Qo(a,w,c,p,$)}),hS=et(function(a,c,p){var w=C|S;if(p.length){var $=Oi(p,Ya(hS));w|=P}return Qo(c,w,a,p,$)});function mS(a,c,p){c=p?n:c;var w=Qo(a,E,n,n,n,n,n,c);return w.placeholder=mS.placeholder,w}function gS(a,c,p){c=p?n:c;var w=Qo(a,k,n,n,n,n,n,c);return w.placeholder=gS.placeholder,w}function vS(a,c,p){var w,$,T,N,D,B,ne=0,re=!1,se=!1,me=!0;if(typeof a!="function")throw new Rr(s);c=Mr(c)||0,It(p)&&(re=!!p.leading,se="maxWait"in p,T=se?tn(Mr(p.maxWait)||0,c):T,me="trailing"in p?!!p.trailing:me);function Re(Xt){var no=w,ri=$;return w=$=n,ne=Xt,N=a.apply(ri,no),N}function Ie(Xt){return ne=Xt,D=Hc(nt,c),re?Re(Xt):N}function Qe(Xt){var no=Xt-B,ri=Xt-ne,IS=c-no;return se?_n(IS,T-ri):IS}function Le(Xt){var no=Xt-B,ri=Xt-ne;return B===n||no>=c||no<0||se&&ri>=T}function nt(){var Xt=Of();if(Le(Xt))return at(Xt);D=Hc(nt,Qe(Xt))}function at(Xt){return D=n,me&&w?Re(Xt):(w=$=n,N)}function lr(){D!==n&&k_(D),ne=0,w=B=$=D=n}function Nn(){return D===n?N:at(Of())}function cr(){var Xt=Of(),no=Le(Xt);if(w=arguments,$=this,B=Xt,no){if(D===n)return Ie(B);if(se)return k_(D),D=Hc(nt,c),Re(B)}return D===n&&(D=Hc(nt,c)),N}return cr.cancel=lr,cr.flush=Nn,cr}var H7=et(function(a,c){return s_(a,1,c)}),K7=et(function(a,c,p){return s_(a,Mr(c)||0,p)});function Y7(a){return Qo(a,F)}function Mf(a,c){if(typeof a!="function"||c!=null&&typeof c!="function")throw new Rr(s);var p=function(){var w=arguments,$=c?c.apply(this,w):w[0],T=p.cache;if(T.has($))return T.get($);var N=a.apply(this,w);return p.cache=T.set($,N)||T,N};return p.cache=new(Mf.Cache||Zo),p}Mf.Cache=Zo;function Nf(a){if(typeof a!="function")throw new Rr(s);return function(){var c=arguments;switch(c.length){case 0:return!a.call(this);case 1:return!a.call(this,c[0]);case 2:return!a.call(this,c[0],c[1]);case 3:return!a.call(this,c[0],c[1],c[2])}return!a.apply(this,c)}}function G7(a){return pS(2,a)}var X7=DM(function(a,c){c=c.length==1&&Ye(c[0])?Mt(c[0],ir(De())):Mt(pn(c,1),ir(De()));var p=c.length;return et(function(w){for(var $=-1,T=_n(w.length,p);++$=c}),Xs=d_(function(){return arguments}())?d_:function(a){return Bt(a)&&yt.call(a,"callee")&&!qb.call(a,"callee")},Ye=q.isArray,u4=Ob?ir(Ob):yM;function Hn(a){return a!=null&&Df(a.length)&&!ti(a)}function Gt(a){return Bt(a)&&Hn(a)}function d4(a){return a===!0||a===!1||Bt(a)&&On(a)==xe}var Fi=C6||Mv,f4=Mb?ir(Mb):wM;function p4(a){return Bt(a)&&a.nodeType===1&&!Kc(a)}function h4(a){if(a==null)return!0;if(Hn(a)&&(Ye(a)||typeof a=="string"||typeof a.splice=="function"||Fi(a)||Ga(a)||Xs(a)))return!a.length;var c=Sn(a);if(c==ct||c==Z)return!a.size;if(Wc(a))return!qg(a).length;for(var p in a)if(yt.call(a,p))return!1;return!0}function m4(a,c){return Bc(a,c)}function g4(a,c,p){p=typeof p=="function"?p:n;var w=p?p(a,c):n;return w===n?Bc(a,c,n,p):!!w}function Sv(a){if(!Bt(a))return!1;var c=On(a);return c==Oe||c==Ae||typeof a.message=="string"&&typeof a.name=="string"&&!Kc(a)}function v4(a){return typeof a=="number"&&Jb(a)}function ti(a){if(!It(a))return!1;var c=On(a);return c==je||c==Ot||c==fe||c==I}function wS(a){return typeof a=="number"&&a==qe(a)}function Df(a){return typeof a=="number"&&a>-1&&a%1==0&&a<=K}function It(a){var c=typeof a;return a!=null&&(c=="object"||c=="function")}function Bt(a){return a!=null&&typeof a=="object"}var xS=Nb?ir(Nb):bM;function y4(a,c){return a===c||Zg(a,c,pv(c))}function w4(a,c,p){return p=typeof p=="function"?p:n,Zg(a,c,pv(c),p)}function x4(a){return bS(a)&&a!=+a}function b4(a){if(oN(a))throw new Ke(i);return f_(a)}function _4(a){return a===null}function S4(a){return a==null}function bS(a){return typeof a=="number"||Bt(a)&&On(a)==Yt}function Kc(a){if(!Bt(a)||On(a)!=gt)return!1;var c=lf(a);if(c===null)return!0;var p=yt.call(c,"constructor")&&c.constructor;return typeof p=="function"&&p instanceof p&&rf.call(p)==w6}var Ev=Db?ir(Db):_M;function E4(a){return wS(a)&&a>=-K&&a<=K}var _S=Ib?ir(Ib):SM;function If(a){return typeof a=="string"||!Ye(a)&&Bt(a)&&On(a)==we}function ar(a){return typeof a=="symbol"||Bt(a)&&On(a)==he}var Ga=Lb?ir(Lb):EM;function C4(a){return a===n}function $4(a){return Bt(a)&&Sn(a)==ke}function k4(a){return Bt(a)&&On(a)==ft}var R4=$f(Qg),T4=$f(function(a,c){return a<=c});function SS(a){if(!a)return[];if(Hn(a))return If(a)?Jr(a):Wn(a);if(Mc&&a[Mc])return a6(a[Mc]());var c=Sn(a),p=c==ct?jg:c==Z?ef:Xa;return p(a)}function ni(a){if(!a)return a===0?a:0;if(a=Mr(a),a===ie||a===-ie){var c=a<0?-1:1;return c*Q}return a===a?a:0}function qe(a){var c=ni(a),p=c%1;return c===c?p?c-p:c:0}function ES(a){return a?Hs(qe(a),0,le):0}function Mr(a){if(typeof a=="number")return a;if(ar(a))return W;if(It(a)){var c=typeof a.valueOf=="function"?a.valueOf():a;a=It(c)?c+"":c}if(typeof a!="string")return a===0?a:+a;a=Vb(a);var p=uO.test(a);return p||fO.test(a)?WO(a.slice(2),p?2:8):cO.test(a)?W:+a}function CS(a){return Eo(a,Kn(a))}function P4(a){return a?Hs(qe(a),-K,K):a===0?a:0}function vt(a){return a==null?"":sr(a)}var A4=Ha(function(a,c){if(Wc(c)||Hn(c)){Eo(c,ln(c),a);return}for(var p in c)yt.call(c,p)&&Fc(a,p,c[p])}),$S=Ha(function(a,c){Eo(c,Kn(c),a)}),Lf=Ha(function(a,c,p,w){Eo(c,Kn(c),a,w)}),O4=Ha(function(a,c,p,w){Eo(c,ln(c),a,w)}),M4=Jo(Hg);function N4(a,c){var p=Wa(a);return c==null?p:o_(p,c)}var D4=et(function(a,c){a=_t(a);var p=-1,w=c.length,$=w>2?c[2]:n;for($&&Mn(c[0],c[1],$)&&(w=1);++p1),T}),Eo(a,dv(a),p),w&&(p=Pr(p,m|g|y,KM));for(var $=c.length;$--;)rv(p,c[$]);return p});function J4(a,c){return RS(a,Nf(De(c)))}var e8=Jo(function(a,c){return a==null?{}:kM(a,c)});function RS(a,c){if(a==null)return{};var p=Mt(dv(a),function(w){return[w]});return c=De(c),w_(a,p,function(w,$){return c(w,$[0])})}function t8(a,c,p){c=Ii(c,a);var w=-1,$=c.length;for($||($=1,a=n);++w<$;){var T=a==null?n:a[Co(c[w])];T===n&&(w=$,T=p),a=ti(T)?T.call(a):T}return a}function n8(a,c,p){return a==null?a:Uc(a,c,p)}function r8(a,c,p,w){return w=typeof w=="function"?w:n,a==null?a:Uc(a,c,p,w)}var TS=B_(ln),PS=B_(Kn);function o8(a,c,p){var w=Ye(a),$=w||Fi(a)||Ga(a);if(c=De(c,4),p==null){var T=a&&a.constructor;$?p=w?new T:[]:It(a)?p=ti(T)?Wa(lf(a)):{}:p={}}return($?kr:So)(a,function(N,D,B){return c(p,N,D,B)}),p}function i8(a,c){return a==null?!0:rv(a,c)}function s8(a,c,p){return a==null?a:E_(a,c,sv(p))}function a8(a,c,p,w){return w=typeof w=="function"?w:n,a==null?a:E_(a,c,sv(p),w)}function Xa(a){return a==null?[]:Fg(a,ln(a))}function l8(a){return a==null?[]:Fg(a,Kn(a))}function c8(a,c,p){return p===n&&(p=c,c=n),p!==n&&(p=Mr(p),p=p===p?p:0),c!==n&&(c=Mr(c),c=c===c?c:0),Hs(Mr(a),c,p)}function u8(a,c,p){return c=ni(c),p===n?(p=c,c=0):p=ni(p),a=Mr(a),gM(a,c,p)}function d8(a,c,p){if(p&&typeof p!="boolean"&&Mn(a,c,p)&&(c=p=n),p===n&&(typeof c=="boolean"?(p=c,c=n):typeof a=="boolean"&&(p=a,a=n)),a===n&&c===n?(a=0,c=1):(a=ni(a),c===n?(c=a,a=0):c=ni(c)),a>c){var w=a;a=c,c=w}if(p||a%1||c%1){var $=e_();return _n(a+$*(c-a+VO("1e-"+(($+"").length-1))),c)}return ev(a,c)}var f8=Ka(function(a,c,p){return c=c.toLowerCase(),a+(p?AS(c):c)});function AS(a){return kv(vt(a).toLowerCase())}function OS(a){return a=vt(a),a&&a.replace(hO,n6).replace(MO,"")}function p8(a,c,p){a=vt(a),c=sr(c);var w=a.length;p=p===n?w:Hs(qe(p),0,w);var $=p;return p-=c.length,p>=0&&a.slice(p,$)==c}function h8(a){return a=vt(a),a&&xg.test(a)?a.replace(Rc,r6):a}function m8(a){return a=vt(a),a&&Ge.test(a)?a.replace(H,"\\$&"):a}var g8=Ka(function(a,c,p){return a+(p?"-":"")+c.toLowerCase()}),v8=Ka(function(a,c,p){return a+(p?" ":"")+c.toLowerCase()}),y8=D_("toLowerCase");function w8(a,c,p){a=vt(a),c=qe(c);var w=c?ja(a):0;if(!c||w>=c)return a;var $=(c-w)/2;return Cf(ff($),p)+a+Cf(df($),p)}function x8(a,c,p){a=vt(a),c=qe(c);var w=c?ja(a):0;return c&&w>>0,p?(a=vt(a),a&&(typeof c=="string"||c!=null&&!Ev(c))&&(c=sr(c),!c&&Fa(a))?Li(Jr(a),0,p):a.split(c,p)):[]}var k8=Ka(function(a,c,p){return a+(p?" ":"")+kv(c)});function R8(a,c,p){return a=vt(a),p=p==null?0:Hs(qe(p),0,a.length),c=sr(c),a.slice(p,p+c.length)==c}function T8(a,c,p){var w=R.templateSettings;p&&Mn(a,c,p)&&(c=n),a=vt(a),c=Lf({},c,w,U_);var $=Lf({},c.imports,w.imports,U_),T=ln($),N=Fg($,T),D,B,ne=0,re=c.interpolate||Xd,se="__p += '",me=zg((c.escape||Xd).source+"|"+re.source+"|"+(re===Ac?lO:Xd).source+"|"+(c.evaluate||Xd).source+"|$","g"),Re="//# sourceURL="+(yt.call(c,"sourceURL")?(c.sourceURL+"").replace(/\s/g," "):"lodash.templateSources["+ ++FO+"]")+` +`;a.replace(me,function(Le,nt,at,lr,Nn,cr){return at||(at=lr),se+=a.slice(ne,cr).replace(mO,o6),nt&&(D=!0,se+=`' + +__e(`+nt+`) + +'`),Nn&&(B=!0,se+=`'; +`+Nn+`; +__p += '`),at&&(se+=`' + +((__t = (`+at+`)) == null ? '' : __t) + +'`),ne=cr+Le.length,Le}),se+=`'; +`;var Ie=yt.call(c,"variable")&&c.variable;if(!Ie)se=`with (obj) { +`+se+` +} +`;else if(sO.test(Ie))throw new Ke(l);se=(B?se.replace(yg,""):se).replace(wg,"$1").replace(Kd,"$1;"),se="function("+(Ie||"obj")+`) { +`+(Ie?"":`obj || (obj = {}); +`)+"var __t, __p = ''"+(D?", __e = _.escape":"")+(B?`, __j = Array.prototype.join; +function print() { __p += __j.call(arguments, '') } +`:`; +`)+se+`return __p +}`;var Qe=NS(function(){return ht(T,Re+"return "+se).apply(n,N)});if(Qe.source=se,Sv(Qe))throw Qe;return Qe}function P8(a){return vt(a).toLowerCase()}function A8(a){return vt(a).toUpperCase()}function O8(a,c,p){if(a=vt(a),a&&(p||c===n))return Vb(a);if(!a||!(c=sr(c)))return a;var w=Jr(a),$=Jr(c),T=Wb(w,$),N=Hb(w,$)+1;return Li(w,T,N).join("")}function M8(a,c,p){if(a=vt(a),a&&(p||c===n))return a.slice(0,Yb(a)+1);if(!a||!(c=sr(c)))return a;var w=Jr(a),$=Hb(w,Jr(c))+1;return Li(w,0,$).join("")}function N8(a,c,p){if(a=vt(a),a&&(p||c===n))return a.replace(st,"");if(!a||!(c=sr(c)))return a;var w=Jr(a),$=Wb(w,Jr(c));return Li(w,$).join("")}function D8(a,c){var p=V,w=J;if(It(c)){var $="separator"in c?c.separator:$;p="length"in c?qe(c.length):p,w="omission"in c?sr(c.omission):w}a=vt(a);var T=a.length;if(Fa(a)){var N=Jr(a);T=N.length}if(p>=T)return a;var D=p-ja(w);if(D<1)return w;var B=N?Li(N,0,D).join(""):a.slice(0,D);if($===n)return B+w;if(N&&(D+=B.length-D),Ev($)){if(a.slice(D).search($)){var ne,re=B;for($.global||($=zg($.source,vt(db.exec($))+"g")),$.lastIndex=0;ne=$.exec(re);)var se=ne.index;B=B.slice(0,se===n?D:se)}}else if(a.indexOf(sr($),D)!=D){var me=B.lastIndexOf($);me>-1&&(B=B.slice(0,me))}return B+w}function I8(a){return a=vt(a),a&&Tc.test(a)?a.replace(kc,d6):a}var L8=Ka(function(a,c,p){return a+(p?" ":"")+c.toUpperCase()}),kv=D_("toUpperCase");function MS(a,c,p){return a=vt(a),c=p?n:c,c===n?s6(a)?h6(a):qO(a):a.match(c)||[]}var NS=et(function(a,c){try{return or(a,n,c)}catch(p){return Sv(p)?p:new Ke(p)}}),F8=Jo(function(a,c){return kr(c,function(p){p=Co(p),qo(a,p,bv(a[p],a))}),a});function j8(a){var c=a==null?0:a.length,p=De();return a=c?Mt(a,function(w){if(typeof w[1]!="function")throw new Rr(s);return[p(w[0]),w[1]]}):[],et(function(w){for(var $=-1;++$K)return[];var p=le,w=_n(a,le);c=De(c),a-=le;for(var $=Lg(w,c);++p0||c<0)?new ot(p):(a<0?p=p.takeRight(-a):a&&(p=p.drop(a)),c!==n&&(c=qe(c),p=c<0?p.dropRight(-c):p.take(c-a)),p)},ot.prototype.takeRightWhile=function(a){return this.reverse().takeWhile(a).reverse()},ot.prototype.toArray=function(){return this.take(le)},So(ot.prototype,function(a,c){var p=/^(?:filter|find|map|reject)|While$/.test(c),w=/^(?:head|last)$/.test(c),$=R[w?"take"+(c=="last"?"Right":""):c],T=w||/^find/.test(c);$&&(R.prototype[c]=function(){var N=this.__wrapped__,D=w?[1]:arguments,B=N instanceof ot,ne=D[0],re=B||Ye(N),se=function(nt){var at=$.apply(R,Ai([nt],D));return w&&me?at[0]:at};re&&p&&typeof ne=="function"&&ne.length!=1&&(B=re=!1);var me=this.__chain__,Re=!!this.__actions__.length,Ie=T&&!me,Qe=B&&!Re;if(!T&&re){N=Qe?N:new ot(this);var Le=a.apply(N,D);return Le.__actions__.push({func:Pf,args:[se],thisArg:n}),new Tr(Le,me)}return Ie&&Qe?a.apply(this,D):(Le=this.thru(se),Ie?w?Le.value()[0]:Le.value():Le)})}),kr(["pop","push","shift","sort","splice","unshift"],function(a){var c=tf[a],p=/^(?:push|sort|unshift)$/.test(a)?"tap":"thru",w=/^(?:pop|shift)$/.test(a);R.prototype[a]=function(){var $=arguments;if(w&&!this.__chain__){var T=this.value();return c.apply(Ye(T)?T:[],$)}return this[p](function(N){return c.apply(Ye(N)?N:[],$)})}}),So(ot.prototype,function(a,c){var p=R[c];if(p){var w=p.name+"";yt.call(Va,w)||(Va[w]=[]),Va[w].push({name:c,func:p})}}),Va[Sf(n,S).name]=[{name:"wrapper",func:n}],ot.prototype.clone=I6,ot.prototype.reverse=L6,ot.prototype.value=F6,R.prototype.at=p7,R.prototype.chain=h7,R.prototype.commit=m7,R.prototype.next=g7,R.prototype.plant=y7,R.prototype.reverse=w7,R.prototype.toJSON=R.prototype.valueOf=R.prototype.value=x7,R.prototype.first=R.prototype.head,Mc&&(R.prototype[Mc]=v7),R},za=m6();Bs?((Bs.exports=za)._=za,Tg._=za):fn._=za}).call(Yc)})(Lh,Lh.exports);var wH=Lh.exports;const xH=lm(wH);function Vr({width:e,height:t}){return e/t}function Fh(e,t=0){const n=10**t;return Math.round((e+Number.EPSILON)*n)/n}function bH(e){return(t,n)=>e(n)-e(t)}class _H{constructor(t){this.comparator=t,this.heap=[],this.n=0}greater(t,n){return this.comparator(this.heap[t],this.heap[n])<0}swap(t,n){const r=this.heap[t];this.heap[t]=this.heap[n],this.heap[n]=r}swim(t){let n=t,r=Math.floor(n/2);for(;n>1&&this.greater(r,n);)this.swap(r,n),n=r,r=Math.floor(n/2)}sink(t){let n=t,r=n*2;for(;r<=this.n&&(rl.weight));for(s.push({id:t,weight:0});s.size()>0;){const{id:l,weight:u}=s.pop();if(!o.has(l)){const d=e(l);o.add(l),d.forEach((h,m)=>{const g=u+h,y=r.get(m),x=i.get(m);(x===void 0||x>g&&(x/g>1.005||y!==void 0&&yMath.min(Vr(i),o),Number.MAX_VALUE);return Fh(n/t/r)+2}function MP(e,t,n,r){const o=t-(e.length-1)*n-2*r*e.length,i=e.reduce((s,l)=>s+Vr(l),0);return o/i}function kH(e,t,n,r,o,i,s){const l=e.slice(t,n),u=MP(l,r,i,s);return u>0?(u-o)**2*l.length:void 0}function RH({photos:e,layoutOptions:t,targetRowHeight:n,limitNodeSearch:r,rowConstraints:o}){return i=>{var s,l;const{containerWidth:u,spacing:d,padding:h}=t,m=new Map;m.set(i,0);const g=(s=o==null?void 0:o.minPhotos)!=null?s:1,y=Math.min(r,(l=o==null?void 0:o.maxPhotos)!=null?l:1/0);for(let x=i+g;xy);x+=1){const _=kH(e,i,x,u,n,d,h);if(_===void 0)break;m.set(x,_)}return m}}function TH({photos:e,layoutOptions:t}){const{spacing:n,padding:r,containerWidth:o,targetRowHeight:i,rowConstraints:s}=t,l=$H({photos:e,containerWidth:o,targetRowHeight:i}),u=RH({photos:e,layoutOptions:t,targetRowHeight:i,limitNodeSearch:l,rowConstraints:s}),d=CH(u,0,e.length);if(d===void 0)return;const h=[];for(let m=1;m({photo:x,index:_})).slice(d[m-1],d[m]),y=MP(g.map(({photo:x})=>x),o,n,r);h.push(g.map(({photo:x,index:_},C)=>({photo:x,layout:{height:y,width:y*Vr(x),index:_,photoIndex:C,photosCount:g.length}})))}return h}function qm(...e){return[...e].filter(t=>!!t).join(" ")}function NP(e,{width:t,photosCount:n},{spacing:r,padding:o,containerWidth:i}){const s=r*(n-1)+2*o*n;return`calc((${e} - ${s}px) / ${Fh((i-s)/t,5)})`}function PH(e,t){return t.layout!=="rows"?`calc(100% - ${2*t.padding}px)`:NP("100%",e,t)}function i2(e,t,n){var r,o;return NP((o=(r=e.match(/calc\((.*)\)/))==null?void 0:r[1])!=null?o:e,t,n)}function AH(e,t,n){let r,o;const i=e.srcSet||e.images;return i&&i.length>0&&(r=i.concat(i.find(({width:s})=>s===e.width)?[]:[{src:e.src,width:e.width,height:e.height}]).sort((s,l)=>s.width-l.width).map(s=>`${s.src} ${s.width}w`).join(", ")),n.sizes?o=(n.sizes.sizes||[]).map(({viewport:s,size:l})=>`${s} ${i2(l,t,n)}`).concat(i2(n.sizes.size,t,n)).join(", "):r&&(o=`${Math.ceil(t.width/n.containerWidth*100)}vw`),{srcSet:r,sizes:o}}function Ox(e){var t,n;const{photo:r,layout:o,layoutOptions:i,imageProps:{style:s,className:l,...u}={},renderPhoto:d}=e,{onClick:h}=i,m={display:"block",boxSizing:"content-box",width:PH(o,i),height:"auto",aspectRatio:`${r.width} / ${r.height}`,...i.padding?{padding:`${i.padding}px`}:null,...(i.layout==="columns"||i.layout==="masonry")&&o.photoIndex{h({event:C,photo:r,index:o.index})}:void 0,y={src:r.src,alt:(t=r.alt)!=null?t:"",title:r.title,onClick:g,style:m,className:qm("react-photo-album--photo",l),loading:"lazy",decoding:"async",...AH(r,o,i),...u},x=C=>{const{src:S,alt:b,srcSet:E,sizes:k,style:P,...M}=y;return f.createElement("img",{alt:b,...E?{srcSet:E,sizes:k}:null,src:S,style:C!=null&&C.wrapped?{display:"block",width:"100%",height:"100%"}:P,...M})},_=(({display:C,boxSizing:S,width:b,aspectRatio:E,padding:k,marginBottom:P,cursor:M})=>({display:C,boxSizing:S,width:b,aspectRatio:E,padding:k,marginBottom:P,cursor:M}))(m);return f.createElement(f.Fragment,null,(n=d==null?void 0:d({photo:r,layout:o,layoutOptions:i,imageProps:y,renderDefaultPhoto:x,wrapperStyle:_}))!=null?n:x())}function OH({rowContainerProps:e,children:t}){return f.createElement("div",{...e},t)}function MH(e){const{layoutOptions:t,rowIndex:n,rowsCount:r,renderRowContainer:o,rowContainerProps:{style:i,className:s,...l}={},children:u}=e,d={className:qm("react-photo-album--row",s),style:{display:"flex",flexDirection:"row",flexWrap:"nowrap",alignItems:"flex-start",justifyContent:"space-between",...nf.createElement(MH,{key:`row-${d}`,layoutOptions:n,rowIndex:d,rowsCount:l.length,renderRowContainer:o,rowContainerProps:s},u.map(({photo:h,layout:m})=>f.createElement(Ox,{key:h.key||h.src,photo:h,layout:m,layoutOptions:n,renderPhoto:r,imageProps:i}))))):null}function DH(e,t,n,r){const o=new Map,i=new Set;i.add(n);for(let s=0;s{const d=s>0?o.get(u)[s].weight:0;e(u).forEach(({neighbor:h,weight:m})=>{let g=o.get(h);g||(g=[],o.set(h,g));const y=d+m,x=g[s+1];(!x||x.weight>y&&(x.weight/y>1.0001||u0;i-=1)o=e.get(o)[i].node,r.push(o);return r.reverse()}function LH(e,t,n,r){return IH(DH(e,t,n,r),t,r)}function FH({photos:e,spacing:t,padding:n,targetColumnWidth:r,targetColumnHeight:o}){return i=>{const s=[],l=o*1.5;let u=r/Vr(e[i])+2*n;for(let d=i+1;dl||d===e.length));d+=1)u+=r/Vr(e[d])+t+2*n;return s}}function s2({path:e,photos:t,containerWidth:n,columnsGaps:r,columnsRatios:o,spacing:i,padding:s}){const l=[],u=o.reduce((d,h)=>d+h,0);for(let d=0;d({photo:y,index:x})).slice(e[d],e[d+1]),m=o.reduce((y,x,_)=>y+(r[d]-r[_])*x,0),g=(n-(e.length-2)*i-2*(e.length-1)*s-m)*o[d]/u;l.push(h.map(({photo:y,index:x},_)=>({photo:y,layout:{width:g,height:g/Vr(y),index:x,photoIndex:_,photosCount:h.length}})))}return l}function jH({photos:e,layoutOptions:t,targetColumnWidth:n}){const{columns:r,spacing:o,padding:i,containerWidth:s}=t,l=[],u=[];if(e.length<=r){const y=e.length>0?e.reduce((_,C)=>_+Vr(C),0)/e.length:1;for(let _=0;_Math.min(C,e.length)),photos:e,columnsRatios:u,columnsGaps:l,containerWidth:s,spacing:o,padding:i});return{columnsGaps:l,columnsRatios:u,columnsModel:x}}const d=(e.reduce((y,x)=>y+n/Vr(x),0)+o*(e.length-r)+2*i*e.length)/r,h=FH({photos:e,targetColumnWidth:n,targetColumnHeight:d,spacing:o,padding:i}),m=LH(h,r,0,e.length);for(let y=0;y_+1/Vr(C),0)}const g=s2({path:m,photos:e,columnsRatios:u,columnsGaps:l,containerWidth:s,spacing:o,padding:i});return{columnsGaps:l,columnsRatios:u,columnsModel:g}}function DP(e){const{photos:t,layoutOptions:n}=e,{columns:r,spacing:o,padding:i,containerWidth:s}=n,l=(s-o*(r-1)-2*i*r)/r,{columnsGaps:u,columnsRatios:d,columnsModel:h}=jH({photos:t,layoutOptions:n,targetColumnWidth:l});return h.findIndex(m=>m.findIndex(({layout:{width:g,height:y}})=>g<0||y<0)>=0)>=0?r>1?DP({photos:t,layoutOptions:{...n,columns:r-1}}):void 0:{columnsModel:h,columnsGaps:u,columnsRatios:d}}function zH({photos:e,layoutOptions:t}){return DP({photos:e,layoutOptions:t})}function BH({columnContainerProps:e,children:t}){return f.createElement("div",{...e},t)}function UH(e){const{layoutOptions:t,columnIndex:n,columnsCount:r,columnsGaps:o,columnsRatios:i}=e,{layout:s,spacing:l,padding:u}=t;if(s==="masonry"||!o||!i)return`calc((100% - ${l*(r-1)}px) / ${r})`;const d=i.reduce((m,g)=>m+g,0),h=i.reduce((m,g,y)=>m+(o[n]-o[y])*g,0);return`calc((100% - ${Fh((r-1)*l+2*r*u+h,3)}px) * ${Fh(i[n]/d,5)} + ${2*u}px)`}function IP(e){const{layoutOptions:t,renderColumnContainer:n,children:r,columnContainerProps:{style:o,className:i,...s}={},...l}=e,u={className:qm("react-photo-album--column",i),style:{display:"flex",flexDirection:"column",flexWrap:"nowrap",alignItems:"flex-start",width:UH(e),justifyContent:t.layout==="columns"?"space-between":"flex-start",...o},...s};return f.createElement(f.Fragment,null,(n??BH)({layoutOptions:t,columnContainerProps:u,children:r,...l}))}function VH(e){const{photos:t,layoutOptions:n,renderPhoto:r,renderColumnContainer:o,componentsProps:{imageProps:i,columnContainerProps:s}}=e,l=zH({photos:t,layoutOptions:n});if(!l)return null;const{columnsModel:u,columnsRatios:d,columnsGaps:h}=l;return f.createElement(f.Fragment,null,u.map((m,g)=>f.createElement(IP,{key:`column-${g}`,layoutOptions:n,columnIndex:g,columnsCount:u.length,columnsGaps:h,columnsRatios:d,renderColumnContainer:o,columnContainerProps:s},m.map(({photo:y,layout:x})=>f.createElement(Ox,{key:y.key||y.src,photo:y,layout:x,layoutOptions:n,renderPhoto:r,imageProps:i})))))}function LP(e){const{photos:t,layoutOptions:n}=e,{columns:r,spacing:o,padding:i,containerWidth:s}=n,l=(s-o*(r-1)-2*i*r)/r;if(l<=0)return r>1?LP({...e,layoutOptions:{...n,columns:r-1}}):void 0;const u=[];for(let h=0;h{const y=u.reduce((x,_,C)=>_[])).map(h=>h.map(({photo:m,index:g},y)=>({photo:m,layout:{width:l,height:l/Vr(m),index:g,photoIndex:y,photosCount:h.length}})))}function WH(e){const{photos:t,layoutOptions:n,renderPhoto:r,renderColumnContainer:o,componentsProps:{imageProps:i,columnContainerProps:s}}=e,l=LP({photos:t,layoutOptions:n});return l?f.createElement(f.Fragment,null,l.map((u,d)=>f.createElement(IP,{key:`masonry-column-${d}`,layoutOptions:n,columnsCount:l.length,columnIndex:d,renderColumnContainer:o,columnContainerProps:s},u.map(({photo:h,layout:m})=>f.createElement(Ox,{key:h.key||h.src,photo:h,layout:m,layoutOptions:n,renderPhoto:r,imageProps:i}))))):null}function HH({containerProps:e,children:t,containerRef:n}){return f.createElement("div",{ref:n,...e},t)}function KH(e){const{layout:t,renderContainer:n,children:r,containerRef:o,containerProps:{style:i,className:s,...l}={}}=e,u={className:qm("react-photo-album",`react-photo-album--${t}`,s),style:{display:"flex",flexWrap:"nowrap",justifyContent:"space-between",flexDirection:t==="rows"?"column":"row",...i},...l};return f.createElement(f.Fragment,null,(n??HH)({containerProps:u,containerRef:o,layout:t,children:r}))}function YH(e){const t=f.useRef(e);return(!e||!t.current||e.join()!==t.current.join())&&(t.current=e),t.current}function GH(e,{newContainerWidth:t,newScrollbarWidth:n}){const{containerWidth:r,scrollbarWidth:o}=e;return r!==void 0&&o!==void 0&&t!==void 0&&n!==void 0&&t>r&&t-r<=20&&n0){const r=[...t.filter(i=>i>0)].sort((i,s)=>s-i);r.push(Math.floor(r[r.length-1]/2));const o=n;n=r.find((i,s)=>i<=o||s===r.length-1)}return n}function ZH(e,t){const[{containerWidth:n},r]=f.useReducer(GH,{containerWidth:t}),o=f.useRef(null),i=f.useRef();return{containerRef:f.useCallback(l=>{var u;(u=i.current)==null||u.disconnect(),i.current=void 0,o.current=l;const d=()=>r({newContainerWidth:XH(o.current,e),newScrollbarWidth:window.innerWidth-document.documentElement.clientWidth});d(),l&&typeof ResizeObserver<"u"&&(i.current=new ResizeObserver(d),i.current.observe(l))},[e]),containerWidth:n}}const qH=Object.freeze([1200,600,300,0]);function Mx(e,t){return typeof e=="function"?e(t):e}function FP(e,t){return typeof e<"u"?Mx(e,t):void 0}function QH(e,t){const n=qH.findIndex(r=>r<=t);return Mx(e[n>=0?n:0],t)}function fp(e,t,n,r=0){const o=FP(e,t);return Math.round(Math.max(o===void 0?QH(n,t):o,r))}function JH({layout:e,onClick:t,containerWidth:n,targetRowHeight:r,rowConstraints:o,columns:i,spacing:s,padding:l,sizes:u}){return{layout:e,onClick:t,containerWidth:n,columns:fp(i,n,[5,4,3,2],1),spacing:fp(s,n,[20,15,10,5]),padding:fp(l,n,[0,0,0,0,0]),targetRowHeight:fp(r,n,[d=>d/5,d=>d/4,d=>d/3,d=>d/2]),rowConstraints:FP(o,n),sizes:u}}function eK(e,t,n){const{photos:r,componentsProps:o}=e,i=Mx(o,t)||{};if(n){const{layout:s,spacing:l,padding:u,rowConstraints:d}=n;if(s==="rows"){const{singleRowMaxHeight:h}=d||{};if(h){const m=Math.floor(r.reduce((g,{width:y,height:x})=>g+y/x*h-2*u,u*r.length*2+l*(r.length-1)));m>0&&(i.containerProps=i.containerProps||{},i.containerProps.style={maxWidth:m,...i.containerProps.style})}}}return i}function tK(e,t,n){const{photos:r,layout:o,renderPhoto:i,renderRowContainer:s,renderColumnContainer:l}=e,u={photos:r,renderPhoto:i,componentsProps:t};return o==="rows"?f.createElement(NH,{layoutOptions:n,renderRowContainer:s,...u}):o==="columns"?f.createElement(VH,{layoutOptions:n,renderColumnContainer:l,...u}):f.createElement(WH,{layoutOptions:n,renderColumnContainer:l,...u})}function nK(e){const{photos:t,layout:n,renderContainer:r,defaultContainerWidth:o,breakpoints:i}=e,{containerRef:s,containerWidth:l}=ZH(YH(i),o);if(!n||!["rows","columns","masonry"].includes(n)||!Array.isArray(t))return null;const u=l?JH({containerWidth:l,...e}):void 0,d=eK(e,l,u);return f.createElement(KH,{layout:n,containerRef:s,renderContainer:r,containerProps:d.containerProps},u&&tK(e,d,u))}function rK({title:e,titleId:t,...n},r){return f.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true",ref:r,"aria-labelledby":t},n),e?f.createElement("title",{id:t},e):null,f.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3 4.5h14.25M3 9h9.75M3 13.5h9.75m4.5-4.5v12m0 0l-3.75-3.75M17.25 21L21 17.25"}))}const oK=f.forwardRef(rK),iK=oK;function sK({title:e,titleId:t,...n},r){return f.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true",ref:r,"aria-labelledby":t},n),e?f.createElement("title",{id:t},e):null,f.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3 4.5h14.25M3 9h9.75M3 13.5h5.25m5.25-.75L17.25 9m0 0L21 12.75M17.25 9v12"}))}const aK=f.forwardRef(sK),lK=aK;function cK({title:e,titleId:t,...n},r){return f.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true",ref:r,"aria-labelledby":t},n),e?f.createElement("title",{id:t},e):null,f.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15.042 21.672L13.684 16.6m0 0l-2.51 2.225.569-9.47 5.227 7.917-3.286-.672zM12 2.25V4.5m5.834.166l-1.591 1.591M20.25 10.5H18M7.757 14.743l-1.59 1.59M6 10.5H3.75m4.007-4.243l-1.59-1.59"}))}const uK=f.forwardRef(cK),dK=uK;function bi(e){return Array.isArray?Array.isArray(e):BP(e)==="[object Array]"}const fK=1/0;function pK(e){if(typeof e=="string")return e;let t=e+"";return t=="0"&&1/e==-fK?"-0":t}function hK(e){return e==null?"":pK(e)}function Lo(e){return typeof e=="string"}function jP(e){return typeof e=="number"}function mK(e){return e===!0||e===!1||gK(e)&&BP(e)=="[object Boolean]"}function zP(e){return typeof e=="object"}function gK(e){return zP(e)&&e!==null}function hr(e){return e!=null}function k0(e){return!e.trim().length}function BP(e){return e==null?e===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}const vK="Incorrect 'index' type",yK=e=>`Invalid value for key ${e}`,wK=e=>`Pattern length exceeds max of ${e}.`,xK=e=>`Missing ${e} property in key`,bK=e=>`Property 'weight' in key '${e}' must be a positive integer`,a2=Object.prototype.hasOwnProperty;class _K{constructor(t){this._keys=[],this._keyMap={};let n=0;t.forEach(r=>{let o=UP(r);this._keys.push(o),this._keyMap[o.id]=o,n+=o.weight}),this._keys.forEach(r=>{r.weight/=n})}get(t){return this._keyMap[t]}keys(){return this._keys}toJSON(){return JSON.stringify(this._keys)}}function UP(e){let t=null,n=null,r=null,o=1,i=null;if(Lo(e)||bi(e))r=e,t=l2(e),n=h1(e);else{if(!a2.call(e,"name"))throw new Error(xK("name"));const s=e.name;if(r=s,a2.call(e,"weight")&&(o=e.weight,o<=0))throw new Error(bK(s));t=l2(s),n=h1(s),i=e.getFn}return{path:t,id:n,weight:o,src:r,getFn:i}}function l2(e){return bi(e)?e:e.split(".")}function h1(e){return bi(e)?e.join("."):e}function SK(e,t){let n=[],r=!1;const o=(i,s,l)=>{if(hr(i))if(!s[l])n.push(i);else{let u=s[l];const d=i[u];if(!hr(d))return;if(l===s.length-1&&(Lo(d)||jP(d)||mK(d)))n.push(hK(d));else if(bi(d)){r=!0;for(let h=0,m=d.length;he.score===t.score?e.idx{this._keysMap[n.id]=r})}create(){this.isCreated||!this.docs.length||(this.isCreated=!0,Lo(this.docs[0])?this.docs.forEach((t,n)=>{this._addString(t,n)}):this.docs.forEach((t,n)=>{this._addObject(t,n)}),this.norm.clear())}add(t){const n=this.size();Lo(t)?this._addString(t,n):this._addObject(t,n)}removeAt(t){this.records.splice(t,1);for(let n=t,r=this.size();n{let s=o.getFn?o.getFn(t):this.getFn(t,o.path);if(hr(s)){if(bi(s)){let l=[];const u=[{nestedArrIndex:-1,value:s}];for(;u.length;){const{nestedArrIndex:d,value:h}=u.pop();if(hr(h))if(Lo(h)&&!k0(h)){let m={v:h,i:d,n:this.norm.get(h)};l.push(m)}else bi(h)&&h.forEach((m,g)=>{u.push({nestedArrIndex:g,value:m})})}r.$[i]=l}else if(Lo(s)&&!k0(s)){let l={v:s,n:this.norm.get(s)};r.$[i]=l}}}),this.records.push(r)}toJSON(){return{keys:this.keys,records:this.records}}}function VP(e,t,{getFn:n=He.getFn,fieldNormWeight:r=He.fieldNormWeight}={}){const o=new Nx({getFn:n,fieldNormWeight:r});return o.setKeys(e.map(UP)),o.setSources(t),o.create(),o}function PK(e,{getFn:t=He.getFn,fieldNormWeight:n=He.fieldNormWeight}={}){const{keys:r,records:o}=e,i=new Nx({getFn:t,fieldNormWeight:n});return i.setKeys(r),i.setIndexRecords(o),i}function pp(e,{errors:t=0,currentLocation:n=0,expectedLocation:r=0,distance:o=He.distance,ignoreLocation:i=He.ignoreLocation}={}){const s=t/e.length;if(i)return s;const l=Math.abs(r-n);return o?s+l/o:l?1:s}function AK(e=[],t=He.minMatchCharLength){let n=[],r=-1,o=-1,i=0;for(let s=e.length;i=t&&n.push([r,o]),r=-1)}return e[i-1]&&i-r>=t&&n.push([r,i-1]),n}const ea=32;function OK(e,t,n,{location:r=He.location,distance:o=He.distance,threshold:i=He.threshold,findAllMatches:s=He.findAllMatches,minMatchCharLength:l=He.minMatchCharLength,includeMatches:u=He.includeMatches,ignoreLocation:d=He.ignoreLocation}={}){if(t.length>ea)throw new Error(wK(ea));const h=t.length,m=e.length,g=Math.max(0,Math.min(r,m));let y=i,x=g;const _=l>1||u,C=_?Array(m):[];let S;for(;(S=e.indexOf(t,x))>-1;){let A=pp(t,{currentLocation:S,expectedLocation:g,distance:o,ignoreLocation:d});if(y=Math.min(A,y),x=S+h,_){let O=0;for(;O=V;U-=1){let te=U-1,L=n[e.charAt(te)];if(_&&(C[te]=+!!L),G[U]=(G[U+1]<<1|1)&L,A&&(G[U]|=(b[U+1]|b[U])<<1|1|b[U+1]),G[U]&P&&(E=pp(t,{errors:A,currentLocation:te,expectedLocation:g,distance:o,ignoreLocation:d}),E<=y)){if(y=E,x=te,x<=g)break;V=Math.max(1,2*g-x)}}if(pp(t,{errors:A+1,currentLocation:g,expectedLocation:g,distance:o,ignoreLocation:d})>y)break;b=G}const M={isMatch:x>=0,score:Math.max(.001,E)};if(_){const A=AK(C,l);A.length?u&&(M.indices=A):M.isMatch=!1}return M}function MK(e){let t={};for(let n=0,r=e.length;n{this.chunks.push({pattern:g,alphabet:MK(g),startIndex:y})},m=this.pattern.length;if(m>ea){let g=0;const y=m%ea,x=m-y;for(;g{const{isMatch:S,score:b,indices:E}=OK(t,x,_,{location:o+C,distance:i,threshold:s,findAllMatches:l,minMatchCharLength:u,includeMatches:r,ignoreLocation:d});S&&(g=!0),m+=b,S&&E&&(h=[...h,...E])});let y={isMatch:g,score:g?m/this.chunks.length:1};return g&&r&&(y.indices=h),y}}class Ds{constructor(t){this.pattern=t}static isMultiMatch(t){return c2(t,this.multiRegex)}static isSingleMatch(t){return c2(t,this.singleRegex)}search(){}}function c2(e,t){const n=e.match(t);return n?n[1]:null}class NK extends Ds{constructor(t){super(t)}static get type(){return"exact"}static get multiRegex(){return/^="(.*)"$/}static get singleRegex(){return/^=(.*)$/}search(t){const n=t===this.pattern;return{isMatch:n,score:n?0:1,indices:[0,this.pattern.length-1]}}}class DK extends Ds{constructor(t){super(t)}static get type(){return"inverse-exact"}static get multiRegex(){return/^!"(.*)"$/}static get singleRegex(){return/^!(.*)$/}search(t){const r=t.indexOf(this.pattern)===-1;return{isMatch:r,score:r?0:1,indices:[0,t.length-1]}}}class IK extends Ds{constructor(t){super(t)}static get type(){return"prefix-exact"}static get multiRegex(){return/^\^"(.*)"$/}static get singleRegex(){return/^\^(.*)$/}search(t){const n=t.startsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[0,this.pattern.length-1]}}}class LK extends Ds{constructor(t){super(t)}static get type(){return"inverse-prefix-exact"}static get multiRegex(){return/^!\^"(.*)"$/}static get singleRegex(){return/^!\^(.*)$/}search(t){const n=!t.startsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[0,t.length-1]}}}class FK extends Ds{constructor(t){super(t)}static get type(){return"suffix-exact"}static get multiRegex(){return/^"(.*)"\$$/}static get singleRegex(){return/^(.*)\$$/}search(t){const n=t.endsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[t.length-this.pattern.length,t.length-1]}}}class jK extends Ds{constructor(t){super(t)}static get type(){return"inverse-suffix-exact"}static get multiRegex(){return/^!"(.*)"\$$/}static get singleRegex(){return/^!(.*)\$$/}search(t){const n=!t.endsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[0,t.length-1]}}}class HP extends Ds{constructor(t,{location:n=He.location,threshold:r=He.threshold,distance:o=He.distance,includeMatches:i=He.includeMatches,findAllMatches:s=He.findAllMatches,minMatchCharLength:l=He.minMatchCharLength,isCaseSensitive:u=He.isCaseSensitive,ignoreLocation:d=He.ignoreLocation}={}){super(t),this._bitapSearch=new WP(t,{location:n,threshold:r,distance:o,includeMatches:i,findAllMatches:s,minMatchCharLength:l,isCaseSensitive:u,ignoreLocation:d})}static get type(){return"fuzzy"}static get multiRegex(){return/^"(.*)"$/}static get singleRegex(){return/^(.*)$/}search(t){return this._bitapSearch.searchIn(t)}}class KP extends Ds{constructor(t){super(t)}static get type(){return"include"}static get multiRegex(){return/^'"(.*)"$/}static get singleRegex(){return/^'(.*)$/}search(t){let n=0,r;const o=[],i=this.pattern.length;for(;(r=t.indexOf(this.pattern,n))>-1;)n=r+i,o.push([r,n-1]);const s=!!o.length;return{isMatch:s,score:s?0:1,indices:o}}}const m1=[NK,KP,IK,LK,jK,FK,DK,HP],u2=m1.length,zK=/ +(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/,BK="|";function UK(e,t={}){return e.split(BK).map(n=>{let r=n.trim().split(zK).filter(i=>i&&!!i.trim()),o=[];for(let i=0,s=r.length;i!!(e[jh.AND]||e[jh.OR]),KK=e=>!!e[y1.PATH],YK=e=>!bi(e)&&zP(e)&&!w1(e),d2=e=>({[jh.AND]:Object.keys(e).map(t=>({[t]:e[t]}))});function YP(e,t,{auto:n=!0}={}){const r=o=>{let i=Object.keys(o);const s=KK(o);if(!s&&i.length>1&&!w1(o))return r(d2(o));if(YK(o)){const u=s?o[y1.PATH]:i[0],d=s?o[y1.PATTERN]:o[u];if(!Lo(d))throw new Error(yK(u));const h={keyId:h1(u),pattern:d};return n&&(h.searcher=v1(d,t)),h}let l={children:[],operator:i[0]};return i.forEach(u=>{const d=o[u];bi(d)&&d.forEach(h=>{l.children.push(r(h))})}),l};return w1(e)||(e=d2(e)),r(e)}function GK(e,{ignoreFieldNorm:t=He.ignoreFieldNorm}){e.forEach(n=>{let r=1;n.matches.forEach(({key:o,norm:i,score:s})=>{const l=o?o.weight:null;r*=Math.pow(s===0&&l?Number.EPSILON:s,(l||1)*(t?1:i))}),n.score=r})}function XK(e,t){const n=e.matches;t.matches=[],hr(n)&&n.forEach(r=>{if(!hr(r.indices)||!r.indices.length)return;const{indices:o,value:i}=r;let s={indices:o,value:i};r.key&&(s.key=r.key.src),r.idx>-1&&(s.refIndex=r.idx),t.matches.push(s)})}function ZK(e,t){t.score=e.score}function qK(e,t,{includeMatches:n=He.includeMatches,includeScore:r=He.includeScore}={}){const o=[];return n&&o.push(XK),r&&o.push(ZK),e.map(i=>{const{idx:s}=i,l={item:t[s],refIndex:s};return o.length&&o.forEach(u=>{u(i,l)}),l})}class _c{constructor(t,n={},r){this.options={...He,...n},this.options.useExtendedSearch,this._keyStore=new _K(this.options.keys),this.setCollection(t,r)}setCollection(t,n){if(this._docs=t,n&&!(n instanceof Nx))throw new Error(vK);this._myIndex=n||VP(this.options.keys,this._docs,{getFn:this.options.getFn,fieldNormWeight:this.options.fieldNormWeight})}add(t){hr(t)&&(this._docs.push(t),this._myIndex.add(t))}remove(t=()=>!1){const n=[];for(let r=0,o=this._docs.length;r-1&&(u=u.slice(0,n)),qK(u,this._docs,{includeMatches:r,includeScore:o})}_searchStringList(t){const n=v1(t,this.options),{records:r}=this._myIndex,o=[];return r.forEach(({v:i,i:s,n:l})=>{if(!hr(i))return;const{isMatch:u,score:d,indices:h}=n.searchIn(i);u&&o.push({item:i,idx:s,matches:[{score:d,value:i,norm:l,indices:h}]})}),o}_searchLogical(t){const n=YP(t,this.options),r=(l,u,d)=>{if(!l.children){const{keyId:m,searcher:g}=l,y=this._findMatches({key:this._keyStore.get(m),value:this._myIndex.getValueForItemAtKeyId(u,m),searcher:g});return y&&y.length?[{idx:d,item:u,matches:y}]:[]}const h=[];for(let m=0,g=l.children.length;m{if(hr(l)){let d=r(n,l,u);d.length&&(i[u]||(i[u]={idx:u,item:l,matches:[]},s.push(i[u])),d.forEach(({matches:h})=>{i[u].matches.push(...h)}))}}),s}_searchObjectList(t){const n=v1(t,this.options),{keys:r,records:o}=this._myIndex,i=[];return o.forEach(({$:s,i:l})=>{if(!hr(s))return;let u=[];r.forEach((d,h)=>{u.push(...this._findMatches({key:d,value:s[h],searcher:n}))}),u.length&&i.push({idx:l,item:s,matches:u})}),i}_findMatches({key:t,value:n,searcher:r}){if(!hr(n))return[];let o=[];if(bi(n))n.forEach(({v:i,i:s,n:l})=>{if(!hr(i))return;const{isMatch:u,score:d,indices:h}=r.searchIn(i);u&&o.push({score:d,key:t,value:i,idx:s,norm:l,indices:h})});else{const{v:i,n:s}=n,{isMatch:l,score:u,indices:d}=r.searchIn(i);l&&o.push({score:u,key:t,value:i,norm:s,indices:d})}return o}}_c.version="7.0.0";_c.createIndex=VP;_c.parseIndex=PK;_c.config=He;_c.parseQuery=YP;HK(WK);function zd(e){const t=e+"CollectionProvider",[n,r]=An(t),[o,i]=n(t,{collectionRef:{current:null},itemMap:new Map}),s=y=>{const{scope:x,children:_}=y,C=Fe.useRef(null),S=Fe.useRef(new Map).current;return Fe.createElement(o,{scope:x,itemMap:S,collectionRef:C},_)},l=e+"CollectionSlot",u=Fe.forwardRef((y,x)=>{const{scope:_,children:C}=y,S=i(l,_),b=Be(x,S.collectionRef);return Fe.createElement(Wo,{ref:b},C)}),d=e+"CollectionItemSlot",h="data-radix-collection-item",m=Fe.forwardRef((y,x)=>{const{scope:_,children:C,...S}=y,b=Fe.useRef(null),E=Be(x,b),k=i(d,_);return Fe.useEffect(()=>(k.itemMap.set(b,{ref:b,...S}),()=>void k.itemMap.delete(b))),Fe.createElement(Wo,{[h]:"",ref:E},C)});function g(y){const x=i(e+"CollectionConsumer",y);return Fe.useCallback(()=>{const C=x.collectionRef.current;if(!C)return[];const S=Array.from(C.querySelectorAll(`[${h}]`));return Array.from(x.itemMap.values()).sort((k,P)=>S.indexOf(k.ref.current)-S.indexOf(P.ref.current))},[x.collectionRef,x.itemMap])}return[{Provider:s,Slot:u,ItemSlot:m},g,r]}const QK=f.createContext(void 0);function Sc(e){const t=f.useContext(QK);return e||t||"ltr"}const R0="rovingFocusGroup.onEntryFocus",JK={bubbles:!1,cancelable:!0},Dx="RovingFocusGroup",[x1,GP,eY]=zd(Dx),[tY,Qm]=An(Dx,[eY]),[nY,rY]=tY(Dx),oY=f.forwardRef((e,t)=>f.createElement(x1.Provider,{scope:e.__scopeRovingFocusGroup},f.createElement(x1.Slot,{scope:e.__scopeRovingFocusGroup},f.createElement(iY,Y({},e,{ref:t}))))),iY=f.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:o=!1,dir:i,currentTabStopId:s,defaultCurrentTabStopId:l,onCurrentTabStopIdChange:u,onEntryFocus:d,...h}=e,m=f.useRef(null),g=Be(t,m),y=Sc(i),[x=null,_]=Zr({prop:s,defaultProp:l,onChange:u}),[C,S]=f.useState(!1),b=Ft(d),E=GP(n),k=f.useRef(!1),[P,M]=f.useState(0);return f.useEffect(()=>{const A=m.current;if(A)return A.addEventListener(R0,b),()=>A.removeEventListener(R0,b)},[b]),f.createElement(nY,{scope:n,orientation:r,dir:y,loop:o,currentTabStopId:x,onItemFocus:f.useCallback(A=>_(A),[_]),onItemShiftTab:f.useCallback(()=>S(!0),[]),onFocusableItemAdd:f.useCallback(()=>M(A=>A+1),[]),onFocusableItemRemove:f.useCallback(()=>M(A=>A-1),[])},f.createElement(Pe.div,Y({tabIndex:C||P===0?-1:0,"data-orientation":r},h,{ref:g,style:{outline:"none",...e.style},onMouseDown:ue(e.onMouseDown,()=>{k.current=!0}),onFocus:ue(e.onFocus,A=>{const O=!k.current;if(A.target===A.currentTarget&&O&&!C){const F=new CustomEvent(R0,JK);if(A.currentTarget.dispatchEvent(F),!F.defaultPrevented){const V=E().filter(te=>te.focusable),J=V.find(te=>te.active),G=V.find(te=>te.id===x),U=[J,G,...V].filter(Boolean).map(te=>te.ref.current);XP(U)}}k.current=!1}),onBlur:ue(e.onBlur,()=>S(!1))})))}),sY="RovingFocusGroupItem",aY=f.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:o=!1,tabStopId:i,...s}=e,l=nr(),u=i||l,d=rY(sY,n),h=d.currentTabStopId===u,m=GP(n),{onFocusableItemAdd:g,onFocusableItemRemove:y}=d;return f.useEffect(()=>{if(r)return g(),()=>y()},[r,g,y]),f.createElement(x1.ItemSlot,{scope:n,id:u,focusable:r,active:o},f.createElement(Pe.span,Y({tabIndex:h?0:-1,"data-orientation":d.orientation},s,{ref:t,onMouseDown:ue(e.onMouseDown,x=>{r?d.onItemFocus(u):x.preventDefault()}),onFocus:ue(e.onFocus,()=>d.onItemFocus(u)),onKeyDown:ue(e.onKeyDown,x=>{if(x.key==="Tab"&&x.shiftKey){d.onItemShiftTab();return}if(x.target!==x.currentTarget)return;const _=uY(x,d.orientation,d.dir);if(_!==void 0){x.preventDefault();let S=m().filter(b=>b.focusable).map(b=>b.ref.current);if(_==="last")S.reverse();else if(_==="prev"||_==="next"){_==="prev"&&S.reverse();const b=S.indexOf(x.currentTarget);S=d.loop?dY(S,b+1):S.slice(b+1)}setTimeout(()=>XP(S))}})})))}),lY={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function cY(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function uY(e,t,n){const r=cY(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return lY[r]}function XP(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function dY(e,t){return e.map((n,r)=>e[(t+r)%e.length])}const ZP=oY,qP=aY,QP="Tabs",[fY,xte]=An(QP,[Qm]),JP=Qm(),[pY,Ix]=fY(QP),hY=f.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,onValueChange:o,defaultValue:i,orientation:s="horizontal",dir:l,activationMode:u="automatic",...d}=e,h=Sc(l),[m,g]=Zr({prop:r,onChange:o,defaultProp:i});return f.createElement(pY,{scope:n,baseId:nr(),value:m,onValueChange:g,orientation:s,dir:h,activationMode:u},f.createElement(Pe.div,Y({dir:h,"data-orientation":s},d,{ref:t})))}),mY="TabsList",gY=f.forwardRef((e,t)=>{const{__scopeTabs:n,loop:r=!0,...o}=e,i=Ix(mY,n),s=JP(n);return f.createElement(ZP,Y({asChild:!0},s,{orientation:i.orientation,dir:i.dir,loop:r}),f.createElement(Pe.div,Y({role:"tablist","aria-orientation":i.orientation},o,{ref:t})))}),vY="TabsTrigger",yY=f.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,disabled:o=!1,...i}=e,s=Ix(vY,n),l=JP(n),u=e5(s.baseId,r),d=t5(s.baseId,r),h=r===s.value;return f.createElement(qP,Y({asChild:!0},l,{focusable:!o,active:h}),f.createElement(Pe.button,Y({type:"button",role:"tab","aria-selected":h,"aria-controls":d,"data-state":h?"active":"inactive","data-disabled":o?"":void 0,disabled:o,id:u},i,{ref:t,onMouseDown:ue(e.onMouseDown,m=>{!o&&m.button===0&&m.ctrlKey===!1?s.onValueChange(r):m.preventDefault()}),onKeyDown:ue(e.onKeyDown,m=>{[" ","Enter"].includes(m.key)&&s.onValueChange(r)}),onFocus:ue(e.onFocus,()=>{const m=s.activationMode!=="manual";!h&&!o&&m&&s.onValueChange(r)})})))}),wY="TabsContent",xY=f.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,forceMount:o,children:i,...s}=e,l=Ix(wY,n),u=e5(l.baseId,r),d=t5(l.baseId,r),h=r===l.value,m=f.useRef(h);return f.useEffect(()=>{const g=requestAnimationFrame(()=>m.current=!1);return()=>cancelAnimationFrame(g)},[]),f.createElement(xn,{present:o||h},({present:g})=>f.createElement(Pe.div,Y({"data-state":h?"active":"inactive","data-orientation":l.orientation,role:"tabpanel","aria-labelledby":u,hidden:!g,id:d,tabIndex:0},s,{ref:t,style:{...e.style,animationDuration:m.current?"0s":void 0}}),g&&i))});function e5(e,t){return`${e}-trigger-${t}`}function t5(e,t){return`${e}-content-${t}`}const bY=hY,n5=gY,r5=yY,o5=xY,i5=bY,Lx=f.forwardRef(({className:e,...t},n)=>v.jsx(n5,{ref:n,className:Ce("inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground",e),tabIndex:-1,...t}));Lx.displayName=n5.displayName;const sa=f.forwardRef(({className:e,...t},n)=>v.jsx(r5,{ref:n,className:Ce("inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow",e),tabIndex:-1,...t}));sa.displayName=r5.displayName;const mu=f.forwardRef(({className:e,...t},n)=>v.jsx(o5,{ref:n,className:Ce("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",e),tabIndex:-1,...t}));mu.displayName=o5.displayName;function id(e,[t,n]){return Math.min(n,Math.max(t,e))}function Fx(e){const t=f.useRef({value:e,previous:e});return f.useMemo(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}const _Y=[" ","Enter","ArrowUp","ArrowDown"],SY=[" ","Enter"],Jm="Select",[eg,tg,EY]=zd(Jm),[Ec,bte]=An(Jm,[EY,Ns]),jx=Ns(),[CY,Oa]=Ec(Jm),[$Y,kY]=Ec(Jm),RY=e=>{const{__scopeSelect:t,children:n,open:r,defaultOpen:o,onOpenChange:i,value:s,defaultValue:l,onValueChange:u,dir:d,name:h,autoComplete:m,disabled:g,required:y}=e,x=jx(t),[_,C]=f.useState(null),[S,b]=f.useState(null),[E,k]=f.useState(!1),P=Sc(d),[M=!1,A]=Zr({prop:r,defaultProp:o,onChange:i}),[O,F]=Zr({prop:s,defaultProp:l,onChange:u}),V=f.useRef(null),J=_?!!_.closest("form"):!0,[G,ae]=f.useState(new Set),U=Array.from(G).map(te=>te.props.value).join(";");return f.createElement(Od,x,f.createElement(CY,{required:y,scope:t,trigger:_,onTriggerChange:C,valueNode:S,onValueNodeChange:b,valueNodeHasChildren:E,onValueNodeHasChildrenChange:k,contentId:nr(),value:O,onValueChange:F,open:M,onOpenChange:A,dir:P,triggerPointerDownPosRef:V,disabled:g},f.createElement(eg.Provider,{scope:t},f.createElement($Y,{scope:e.__scopeSelect,onNativeOptionAdd:f.useCallback(te=>{ae(L=>new Set(L).add(te))},[]),onNativeOptionRemove:f.useCallback(te=>{ae(L=>{const ie=new Set(L);return ie.delete(te),ie})},[])},n)),J?f.createElement(u5,{key:U,"aria-hidden":!0,required:y,tabIndex:-1,name:h,autoComplete:m,value:O,onChange:te=>F(te.target.value),disabled:g},O===void 0?f.createElement("option",{value:""}):null,Array.from(G)):null))},TY="SelectTrigger",PY=f.forwardRef((e,t)=>{const{__scopeSelect:n,disabled:r=!1,...o}=e,i=jx(n),s=Oa(TY,n),l=s.disabled||r,u=Be(t,s.onTriggerChange),d=tg(n),[h,m,g]=d5(x=>{const _=d().filter(b=>!b.disabled),C=_.find(b=>b.value===s.value),S=f5(_,x,C);S!==void 0&&s.onValueChange(S.value)}),y=()=>{l||(s.onOpenChange(!0),g())};return f.createElement(zm,Y({asChild:!0},i),f.createElement(Pe.button,Y({type:"button",role:"combobox","aria-controls":s.contentId,"aria-expanded":s.open,"aria-required":s.required,"aria-autocomplete":"none",dir:s.dir,"data-state":s.open?"open":"closed",disabled:l,"data-disabled":l?"":void 0,"data-placeholder":c5(s.value)?"":void 0},o,{ref:u,onClick:ue(o.onClick,x=>{x.currentTarget.focus()}),onPointerDown:ue(o.onPointerDown,x=>{const _=x.target;_.hasPointerCapture(x.pointerId)&&_.releasePointerCapture(x.pointerId),x.button===0&&x.ctrlKey===!1&&(y(),s.triggerPointerDownPosRef.current={x:Math.round(x.pageX),y:Math.round(x.pageY)},x.preventDefault())}),onKeyDown:ue(o.onKeyDown,x=>{const _=h.current!=="";!(x.ctrlKey||x.altKey||x.metaKey)&&x.key.length===1&&m(x.key),!(_&&x.key===" ")&&_Y.includes(x.key)&&(y(),x.preventDefault())})})))}),AY="SelectValue",OY=f.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,children:i,placeholder:s="",...l}=e,u=Oa(AY,n),{onValueNodeHasChildrenChange:d}=u,h=i!==void 0,m=Be(t,u.onValueNodeChange);return Pn(()=>{d(h)},[d,h]),f.createElement(Pe.span,Y({},l,{ref:m,style:{pointerEvents:"none"}}),c5(u.value)?f.createElement(f.Fragment,null,s):i)}),MY=f.forwardRef((e,t)=>{const{__scopeSelect:n,children:r,...o}=e;return f.createElement(Pe.span,Y({"aria-hidden":!0},o,{ref:t}),r||"▼")}),NY=e=>f.createElement(Md,Y({asChild:!0},e)),ic="SelectContent",DY=f.forwardRef((e,t)=>{const n=Oa(ic,e.__scopeSelect),[r,o]=f.useState();if(Pn(()=>{o(new DocumentFragment)},[]),!n.open){const i=r;return i?Os.createPortal(f.createElement(s5,{scope:e.__scopeSelect},f.createElement(eg.Slot,{scope:e.__scopeSelect},f.createElement("div",null,e.children))),i):null}return f.createElement(IY,Y({},e,{ref:t}))}),ai=10,[s5,Ma]=Ec(ic),IY=f.forwardRef((e,t)=>{const{__scopeSelect:n,position:r="item-aligned",onCloseAutoFocus:o,onEscapeKeyDown:i,onPointerDownOutside:s,side:l,sideOffset:u,align:d,alignOffset:h,arrowPadding:m,collisionBoundary:g,collisionPadding:y,sticky:x,hideWhenDetached:_,avoidCollisions:C,...S}=e,b=Oa(ic,n),[E,k]=f.useState(null),[P,M]=f.useState(null),A=Be(t,fe=>k(fe)),[O,F]=f.useState(null),[V,J]=f.useState(null),G=tg(n),[ae,U]=f.useState(!1),te=f.useRef(!1);f.useEffect(()=>{if(E)return Xm(E)},[E]),Km();const L=f.useCallback(fe=>{const[xe,...$e]=G().map(je=>je.ref.current),[Ae]=$e.slice(-1),Oe=document.activeElement;for(const je of fe)if(je===Oe||(je==null||je.scrollIntoView({block:"nearest"}),je===xe&&P&&(P.scrollTop=0),je===Ae&&P&&(P.scrollTop=P.scrollHeight),je==null||je.focus(),document.activeElement!==Oe))return},[G,P]),ie=f.useCallback(()=>L([O,E]),[L,O,E]);f.useEffect(()=>{ae&&ie()},[ae,ie]);const{onOpenChange:K,triggerPointerDownPosRef:Q}=b;f.useEffect(()=>{if(E){let fe={x:0,y:0};const xe=Ae=>{var Oe,je,Ot,ct;fe={x:Math.abs(Math.round(Ae.pageX)-((Oe=(je=Q.current)===null||je===void 0?void 0:je.x)!==null&&Oe!==void 0?Oe:0)),y:Math.abs(Math.round(Ae.pageY)-((Ot=(ct=Q.current)===null||ct===void 0?void 0:ct.y)!==null&&Ot!==void 0?Ot:0))}},$e=Ae=>{fe.x<=10&&fe.y<=10?Ae.preventDefault():E.contains(Ae.target)||K(!1),document.removeEventListener("pointermove",xe),Q.current=null};return Q.current!==null&&(document.addEventListener("pointermove",xe),document.addEventListener("pointerup",$e,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",xe),document.removeEventListener("pointerup",$e,{capture:!0})}}},[E,K,Q]),f.useEffect(()=>{const fe=()=>K(!1);return window.addEventListener("blur",fe),window.addEventListener("resize",fe),()=>{window.removeEventListener("blur",fe),window.removeEventListener("resize",fe)}},[K]);const[W,le]=d5(fe=>{const xe=G().filter(Oe=>!Oe.disabled),$e=xe.find(Oe=>Oe.ref.current===document.activeElement),Ae=f5(xe,fe,$e);Ae&&setTimeout(()=>Ae.ref.current.focus())}),ge=f.useCallback((fe,xe,$e)=>{const Ae=!te.current&&!$e;(b.value!==void 0&&b.value===xe||Ae)&&(F(fe),Ae&&(te.current=!0))},[b.value]),Ve=f.useCallback(()=>E==null?void 0:E.focus(),[E]),Ue=f.useCallback((fe,xe,$e)=>{const Ae=!te.current&&!$e;(b.value!==void 0&&b.value===xe||Ae)&&J(fe)},[b.value]),We=r==="popper"?f2:LY,Me=We===f2?{side:l,sideOffset:u,align:d,alignOffset:h,arrowPadding:m,collisionBoundary:g,collisionPadding:y,sticky:x,hideWhenDetached:_,avoidCollisions:C}:{};return f.createElement(s5,{scope:n,content:E,viewport:P,onViewportChange:M,itemRefCallback:ge,selectedItem:O,onItemLeave:Ve,itemTextRefCallback:Ue,focusSelectedItem:ie,selectedItemText:V,position:r,isPositioned:ae,searchRef:W},f.createElement(Gm,{as:Wo,allowPinchZoom:!0},f.createElement(Hm,{asChild:!0,trapped:b.open,onMountAutoFocus:fe=>{fe.preventDefault()},onUnmountAutoFocus:ue(o,fe=>{var xe;(xe=b.trigger)===null||xe===void 0||xe.focus({preventScroll:!0}),fe.preventDefault()})},f.createElement(yc,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:i,onPointerDownOutside:s,onFocusOutside:fe=>fe.preventDefault(),onDismiss:()=>b.onOpenChange(!1)},f.createElement(We,Y({role:"listbox",id:b.contentId,"data-state":b.open?"open":"closed",dir:b.dir,onContextMenu:fe=>fe.preventDefault()},S,Me,{onPlaced:()=>U(!0),ref:A,style:{display:"flex",flexDirection:"column",outline:"none",...S.style},onKeyDown:ue(S.onKeyDown,fe=>{const xe=fe.ctrlKey||fe.altKey||fe.metaKey;if(fe.key==="Tab"&&fe.preventDefault(),!xe&&fe.key.length===1&&le(fe.key),["ArrowUp","ArrowDown","Home","End"].includes(fe.key)){let Ae=G().filter(Oe=>!Oe.disabled).map(Oe=>Oe.ref.current);if(["ArrowUp","End"].includes(fe.key)&&(Ae=Ae.slice().reverse()),["ArrowUp","ArrowDown"].includes(fe.key)){const Oe=fe.target,je=Ae.indexOf(Oe);Ae=Ae.slice(je+1)}setTimeout(()=>L(Ae)),fe.preventDefault()}})}))))))}),LY=f.forwardRef((e,t)=>{const{__scopeSelect:n,onPlaced:r,...o}=e,i=Oa(ic,n),s=Ma(ic,n),[l,u]=f.useState(null),[d,h]=f.useState(null),m=Be(t,A=>h(A)),g=tg(n),y=f.useRef(!1),x=f.useRef(!0),{viewport:_,selectedItem:C,selectedItemText:S,focusSelectedItem:b}=s,E=f.useCallback(()=>{if(i.trigger&&i.valueNode&&l&&d&&_&&C&&S){const A=i.trigger.getBoundingClientRect(),O=d.getBoundingClientRect(),F=i.valueNode.getBoundingClientRect(),V=S.getBoundingClientRect();if(i.dir!=="rtl"){const Oe=V.left-O.left,je=F.left-Oe,Ot=A.left-je,ct=A.width+Ot,Yt=Math.max(ct,O.width),Er=window.innerWidth-ai,gt=id(je,[ai,Er-Yt]);l.style.minWidth=ct+"px",l.style.left=gt+"px"}else{const Oe=O.right-V.right,je=window.innerWidth-F.right-Oe,Ot=window.innerWidth-A.right-je,ct=A.width+Ot,Yt=Math.max(ct,O.width),Er=window.innerWidth-ai,gt=id(je,[ai,Er-Yt]);l.style.minWidth=ct+"px",l.style.right=gt+"px"}const J=g(),G=window.innerHeight-ai*2,ae=_.scrollHeight,U=window.getComputedStyle(d),te=parseInt(U.borderTopWidth,10),L=parseInt(U.paddingTop,10),ie=parseInt(U.borderBottomWidth,10),K=parseInt(U.paddingBottom,10),Q=te+L+ae+K+ie,W=Math.min(C.offsetHeight*5,Q),le=window.getComputedStyle(_),ge=parseInt(le.paddingTop,10),Ve=parseInt(le.paddingBottom,10),Ue=A.top+A.height/2-ai,We=G-Ue,Me=C.offsetHeight/2,fe=C.offsetTop+Me,xe=te+L+fe,$e=Q-xe;if(xe<=Ue){const Oe=C===J[J.length-1].ref.current;l.style.bottom="0px";const je=d.clientHeight-_.offsetTop-_.offsetHeight,Ot=Math.max(We,Me+(Oe?Ve:0)+je+ie),ct=xe+Ot;l.style.height=ct+"px"}else{const Oe=C===J[0].ref.current;l.style.top="0px";const Ot=Math.max(Ue,te+_.offsetTop+(Oe?ge:0)+Me)+$e;l.style.height=Ot+"px",_.scrollTop=xe-Ue+_.offsetTop}l.style.margin=`${ai}px 0`,l.style.minHeight=W+"px",l.style.maxHeight=G+"px",r==null||r(),requestAnimationFrame(()=>y.current=!0)}},[g,i.trigger,i.valueNode,l,d,_,C,S,i.dir,r]);Pn(()=>E(),[E]);const[k,P]=f.useState();Pn(()=>{d&&P(window.getComputedStyle(d).zIndex)},[d]);const M=f.useCallback(A=>{A&&x.current===!0&&(E(),b==null||b(),x.current=!1)},[E,b]);return f.createElement(FY,{scope:n,contentWrapper:l,shouldExpandOnScrollRef:y,onScrollButtonChange:M},f.createElement("div",{ref:u,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:k}},f.createElement(Pe.div,Y({},o,{ref:m,style:{boxSizing:"border-box",maxHeight:"100%",...o.style}}))))}),f2=f.forwardRef((e,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:o=ai,...i}=e,s=jx(n);return f.createElement(Bm,Y({},s,i,{ref:t,align:r,collisionPadding:o,style:{boxSizing:"border-box",...i.style,"--radix-select-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-select-content-available-width":"var(--radix-popper-available-width)","--radix-select-content-available-height":"var(--radix-popper-available-height)","--radix-select-trigger-width":"var(--radix-popper-anchor-width)","--radix-select-trigger-height":"var(--radix-popper-anchor-height)"}}))}),[FY,zx]=Ec(ic,{}),p2="SelectViewport",jY=f.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=Ma(p2,n),i=zx(p2,n),s=Be(t,o.onViewportChange),l=f.useRef(0);return f.createElement(f.Fragment,null,f.createElement("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"}}),f.createElement(eg.Slot,{scope:n},f.createElement(Pe.div,Y({"data-radix-select-viewport":"",role:"presentation"},r,{ref:s,style:{position:"relative",flex:1,overflow:"auto",...r.style},onScroll:ue(r.onScroll,u=>{const d=u.currentTarget,{contentWrapper:h,shouldExpandOnScrollRef:m}=i;if(m!=null&&m.current&&h){const g=Math.abs(l.current-d.scrollTop);if(g>0){const y=window.innerHeight-ai*2,x=parseFloat(h.style.minHeight),_=parseFloat(h.style.height),C=Math.max(x,_);if(C0?E:0,h.style.justifyContent="flex-end")}}}l.current=d.scrollTop})}))))}),zY="SelectGroup",[BY,UY]=Ec(zY),VY=f.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=nr();return f.createElement(BY,{scope:n,id:o},f.createElement(Pe.div,Y({role:"group","aria-labelledby":o},r,{ref:t})))}),WY="SelectLabel",HY=f.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=UY(WY,n);return f.createElement(Pe.div,Y({id:o.id},r,{ref:t}))}),b1="SelectItem",[KY,a5]=Ec(b1),YY=f.forwardRef((e,t)=>{const{__scopeSelect:n,value:r,disabled:o=!1,textValue:i,...s}=e,l=Oa(b1,n),u=Ma(b1,n),d=l.value===r,[h,m]=f.useState(i??""),[g,y]=f.useState(!1),x=Be(t,S=>{var b;return(b=u.itemRefCallback)===null||b===void 0?void 0:b.call(u,S,r,o)}),_=nr(),C=()=>{o||(l.onValueChange(r),l.onOpenChange(!1))};if(r==="")throw new Error("A must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.");return f.createElement(KY,{scope:n,value:r,disabled:o,textId:_,isSelected:d,onItemTextChange:f.useCallback(S=>{m(b=>{var E;return b||((E=S==null?void 0:S.textContent)!==null&&E!==void 0?E:"").trim()})},[])},f.createElement(eg.ItemSlot,{scope:n,value:r,disabled:o,textValue:h},f.createElement(Pe.div,Y({role:"option","aria-labelledby":_,"data-highlighted":g?"":void 0,"aria-selected":d&&g,"data-state":d?"checked":"unchecked","aria-disabled":o||void 0,"data-disabled":o?"":void 0,tabIndex:o?void 0:-1},s,{ref:x,onFocus:ue(s.onFocus,()=>y(!0)),onBlur:ue(s.onBlur,()=>y(!1)),onPointerUp:ue(s.onPointerUp,C),onPointerMove:ue(s.onPointerMove,S=>{if(o){var b;(b=u.onItemLeave)===null||b===void 0||b.call(u)}else S.currentTarget.focus({preventScroll:!0})}),onPointerLeave:ue(s.onPointerLeave,S=>{if(S.currentTarget===document.activeElement){var b;(b=u.onItemLeave)===null||b===void 0||b.call(u)}}),onKeyDown:ue(s.onKeyDown,S=>{var b;((b=u.searchRef)===null||b===void 0?void 0:b.current)!==""&&S.key===" "||(SY.includes(S.key)&&C(),S.key===" "&&S.preventDefault())})}))))}),hp="SelectItemText",GY=f.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,...i}=e,s=Oa(hp,n),l=Ma(hp,n),u=a5(hp,n),d=kY(hp,n),[h,m]=f.useState(null),g=Be(t,S=>m(S),u.onItemTextChange,S=>{var b;return(b=l.itemTextRefCallback)===null||b===void 0?void 0:b.call(l,S,u.value,u.disabled)}),y=h==null?void 0:h.textContent,x=f.useMemo(()=>f.createElement("option",{key:u.value,value:u.value,disabled:u.disabled},y),[u.disabled,u.value,y]),{onNativeOptionAdd:_,onNativeOptionRemove:C}=d;return Pn(()=>(_(x),()=>C(x)),[_,C,x]),f.createElement(f.Fragment,null,f.createElement(Pe.span,Y({id:u.textId},i,{ref:g})),u.isSelected&&s.valueNode&&!s.valueNodeHasChildren?Os.createPortal(i.children,s.valueNode):null)}),XY="SelectItemIndicator",ZY=f.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return a5(XY,n).isSelected?f.createElement(Pe.span,Y({"aria-hidden":!0},r,{ref:t})):null}),h2="SelectScrollUpButton",qY=f.forwardRef((e,t)=>{const n=Ma(h2,e.__scopeSelect),r=zx(h2,e.__scopeSelect),[o,i]=f.useState(!1),s=Be(t,r.onScrollButtonChange);return Pn(()=>{if(n.viewport&&n.isPositioned){let d=function(){const h=u.scrollTop>0;i(h)};var l=d;const u=n.viewport;return d(),u.addEventListener("scroll",d),()=>u.removeEventListener("scroll",d)}},[n.viewport,n.isPositioned]),o?f.createElement(l5,Y({},e,{ref:s,onAutoScroll:()=>{const{viewport:l,selectedItem:u}=n;l&&u&&(l.scrollTop=l.scrollTop-u.offsetHeight)}})):null}),m2="SelectScrollDownButton",QY=f.forwardRef((e,t)=>{const n=Ma(m2,e.__scopeSelect),r=zx(m2,e.__scopeSelect),[o,i]=f.useState(!1),s=Be(t,r.onScrollButtonChange);return Pn(()=>{if(n.viewport&&n.isPositioned){let d=function(){const h=u.scrollHeight-u.clientHeight,m=Math.ceil(u.scrollTop)u.removeEventListener("scroll",d)}},[n.viewport,n.isPositioned]),o?f.createElement(l5,Y({},e,{ref:s,onAutoScroll:()=>{const{viewport:l,selectedItem:u}=n;l&&u&&(l.scrollTop=l.scrollTop+u.offsetHeight)}})):null}),l5=f.forwardRef((e,t)=>{const{__scopeSelect:n,onAutoScroll:r,...o}=e,i=Ma("SelectScrollButton",n),s=f.useRef(null),l=tg(n),u=f.useCallback(()=>{s.current!==null&&(window.clearInterval(s.current),s.current=null)},[]);return f.useEffect(()=>()=>u(),[u]),Pn(()=>{var d;const h=l().find(m=>m.ref.current===document.activeElement);h==null||(d=h.ref.current)===null||d===void 0||d.scrollIntoView({block:"nearest"})},[l]),f.createElement(Pe.div,Y({"aria-hidden":!0},o,{ref:t,style:{flexShrink:0,...o.style},onPointerDown:ue(o.onPointerDown,()=>{s.current===null&&(s.current=window.setInterval(r,50))}),onPointerMove:ue(o.onPointerMove,()=>{var d;(d=i.onItemLeave)===null||d===void 0||d.call(i),s.current===null&&(s.current=window.setInterval(r,50))}),onPointerLeave:ue(o.onPointerLeave,()=>{u()})}))}),JY=f.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return f.createElement(Pe.div,Y({"aria-hidden":!0},r,{ref:t}))});function c5(e){return e===""||e===void 0}const u5=f.forwardRef((e,t)=>{const{value:n,...r}=e,o=f.useRef(null),i=Be(t,o),s=Fx(n);return f.useEffect(()=>{const l=o.current,u=window.HTMLSelectElement.prototype,h=Object.getOwnPropertyDescriptor(u,"value").set;if(s!==n&&h){const m=new Event("change",{bubbles:!0});h.call(l,n),l.dispatchEvent(m)}},[s,n]),f.createElement(Um,{asChild:!0},f.createElement("select",Y({},r,{ref:i,defaultValue:n})))});u5.displayName="BubbleSelect";function d5(e){const t=Ft(e),n=f.useRef(""),r=f.useRef(0),o=f.useCallback(s=>{const l=n.current+s;t(l),function u(d){n.current=d,window.clearTimeout(r.current),d!==""&&(r.current=window.setTimeout(()=>u(""),1e3))}(l)},[t]),i=f.useCallback(()=>{n.current="",window.clearTimeout(r.current)},[]);return f.useEffect(()=>()=>window.clearTimeout(r.current),[]),[n,o,i]}function f5(e,t,n){const o=t.length>1&&Array.from(t).every(d=>d===t[0])?t[0]:t,i=n?e.indexOf(n):-1;let s=eG(e,Math.max(i,0));o.length===1&&(s=s.filter(d=>d!==n));const u=s.find(d=>d.textValue.toLowerCase().startsWith(o.toLowerCase()));return u!==n?u:void 0}function eG(e,t){return e.map((n,r)=>e[(t+r)%e.length])}const tG=RY,p5=PY,nG=OY,rG=MY,oG=NY,h5=DY,iG=jY,sG=VY,m5=HY,g5=YY,aG=GY,lG=ZY,v5=qY,y5=QY,w5=JY,aa=tG,wl=sG,la=nG,ls=f.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(p5,{ref:r,className:Ce("flex h-9 w-full items-center justify-between whitespace-nowrap rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",e),tabIndex:-1,...n,children:[t,v.jsx(rG,{asChild:!0,children:v.jsx(Gj,{className:"h-4 w-4 opacity-50"})})]}));ls.displayName=p5.displayName;const x5=f.forwardRef(({className:e,...t},n)=>v.jsx(v5,{ref:n,className:Ce("flex cursor-default items-center justify-center py-1",e),...t,children:v.jsx(tz,{})}));x5.displayName=v5.displayName;const b5=f.forwardRef(({className:e,...t},n)=>v.jsx(y5,{ref:n,className:Ce("flex cursor-default items-center justify-center py-1",e),...t,children:v.jsx(qj,{})}));b5.displayName=y5.displayName;const cs=f.forwardRef(({className:e,children:t,position:n="popper",...r},o)=>v.jsx(oG,{children:v.jsxs(h5,{ref:o,className:Ce("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",n==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:n,onCloseAutoFocus:i=>i.preventDefault(),...r,children:[v.jsx(x5,{}),v.jsx(iG,{className:Ce("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),v.jsx(b5,{})]})}));cs.displayName=h5.displayName;const cG=f.forwardRef(({className:e,...t},n)=>v.jsx(m5,{ref:n,className:Ce("px-2 py-1.5 text-sm font-semibold",e),...t}));cG.displayName=m5.displayName;const us=f.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(g5,{ref:r,className:Ce("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-2 pr-8 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[v.jsx("span",{className:"absolute right-2 flex h-3.5 w-3.5 items-center justify-center",children:v.jsx(lG,{children:v.jsx(vT,{className:"h-4 w-4"})})}),v.jsx(aG,{children:t})]}));us.displayName=g5.displayName;const uG=f.forwardRef(({className:e,...t},n)=>v.jsx(w5,{ref:n,className:Ce("-mx-1 my-1 h-px bg-muted",e),...t}));uG.displayName=w5.displayName;function dG(e,t){return f.useReducer((n,r)=>{const o=t[n][r];return o??n},e)}const _5="ScrollArea",[S5,_te]=An(_5),[fG,qr]=S5(_5),pG=f.forwardRef((e,t)=>{const{__scopeScrollArea:n,type:r="hover",dir:o,scrollHideDelay:i=600,...s}=e,[l,u]=f.useState(null),[d,h]=f.useState(null),[m,g]=f.useState(null),[y,x]=f.useState(null),[_,C]=f.useState(null),[S,b]=f.useState(0),[E,k]=f.useState(0),[P,M]=f.useState(!1),[A,O]=f.useState(!1),F=Be(t,J=>u(J)),V=Sc(o);return f.createElement(fG,{scope:n,type:r,dir:V,scrollHideDelay:i,scrollArea:l,viewport:d,onViewportChange:h,content:m,onContentChange:g,scrollbarX:y,onScrollbarXChange:x,scrollbarXEnabled:P,onScrollbarXEnabledChange:M,scrollbarY:_,onScrollbarYChange:C,scrollbarYEnabled:A,onScrollbarYEnabledChange:O,onCornerWidthChange:b,onCornerHeightChange:k},f.createElement(Pe.div,Y({dir:V},s,{ref:F,style:{position:"relative","--radix-scroll-area-corner-width":S+"px","--radix-scroll-area-corner-height":E+"px",...e.style}})))}),hG="ScrollAreaViewport",mG=f.forwardRef((e,t)=>{const{__scopeScrollArea:n,children:r,...o}=e,i=qr(hG,n),s=f.useRef(null),l=Be(t,s,i.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(Pe.div,Y({"data-radix-scroll-area-viewport":""},o,{ref:l,style:{overflowX:i.scrollbarXEnabled?"scroll":"hidden",overflowY:i.scrollbarYEnabled?"scroll":"hidden",...e.style}}),f.createElement("div",{ref:i.onContentChange,style:{minWidth:"100%",display:"table"}},r)))}),$i="ScrollAreaScrollbar",E5=f.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=qr($i,e.__scopeScrollArea),{onScrollbarXEnabledChange:i,onScrollbarYEnabledChange:s}=o,l=e.orientation==="horizontal";return f.useEffect(()=>(l?i(!0):s(!0),()=>{l?i(!1):s(!1)}),[l,i,s]),o.type==="hover"?f.createElement(gG,Y({},r,{ref:t,forceMount:n})):o.type==="scroll"?f.createElement(vG,Y({},r,{ref:t,forceMount:n})):o.type==="auto"?f.createElement(C5,Y({},r,{ref:t,forceMount:n})):o.type==="always"?f.createElement(Bx,Y({},r,{ref:t})):null}),gG=f.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=qr($i,e.__scopeScrollArea),[i,s]=f.useState(!1);return f.useEffect(()=>{const l=o.scrollArea;let u=0;if(l){const d=()=>{window.clearTimeout(u),s(!0)},h=()=>{u=window.setTimeout(()=>s(!1),o.scrollHideDelay)};return l.addEventListener("pointerenter",d),l.addEventListener("pointerleave",h),()=>{window.clearTimeout(u),l.removeEventListener("pointerenter",d),l.removeEventListener("pointerleave",h)}}},[o.scrollArea,o.scrollHideDelay]),f.createElement(xn,{present:n||i},f.createElement(C5,Y({"data-state":i?"visible":"hidden"},r,{ref:t})))}),vG=f.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=qr($i,e.__scopeScrollArea),i=e.orientation==="horizontal",s=rg(()=>u("SCROLL_END"),100),[l,u]=dG("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(l==="idle"){const d=window.setTimeout(()=>u("HIDE"),o.scrollHideDelay);return()=>window.clearTimeout(d)}},[l,o.scrollHideDelay,u]),f.useEffect(()=>{const d=o.viewport,h=i?"scrollLeft":"scrollTop";if(d){let m=d[h];const g=()=>{const y=d[h];m!==y&&(u("SCROLL"),s()),m=y};return d.addEventListener("scroll",g),()=>d.removeEventListener("scroll",g)}},[o.viewport,i,u,s]),f.createElement(xn,{present:n||l!=="hidden"},f.createElement(Bx,Y({"data-state":l==="hidden"?"hidden":"visible"},r,{ref:t,onPointerEnter:ue(e.onPointerEnter,()=>u("POINTER_ENTER")),onPointerLeave:ue(e.onPointerLeave,()=>u("POINTER_LEAVE"))})))}),C5=f.forwardRef((e,t)=>{const n=qr($i,e.__scopeScrollArea),{forceMount:r,...o}=e,[i,s]=f.useState(!1),l=e.orientation==="horizontal",u=rg(()=>{if(n.viewport){const d=n.viewport.offsetWidth{const{orientation:n="vertical",...r}=e,o=qr($i,e.__scopeScrollArea),i=f.useRef(null),s=f.useRef(0),[l,u]=f.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),d=T5(l.viewport,l.content),h={...r,sizes:l,onSizesChange:u,hasThumb:d>0&&d<1,onThumbChange:g=>i.current=g,onThumbPointerUp:()=>s.current=0,onThumbPointerDown:g=>s.current=g};function m(g,y){return CG(g,s.current,l,y)}return n==="horizontal"?f.createElement(yG,Y({},h,{ref:t,onThumbPositionChange:()=>{if(o.viewport&&i.current){const g=o.viewport.scrollLeft,y=g2(g,l,o.dir);i.current.style.transform=`translate3d(${y}px, 0, 0)`}},onWheelScroll:g=>{o.viewport&&(o.viewport.scrollLeft=g)},onDragScroll:g=>{o.viewport&&(o.viewport.scrollLeft=m(g,o.dir))}})):n==="vertical"?f.createElement(wG,Y({},h,{ref:t,onThumbPositionChange:()=>{if(o.viewport&&i.current){const g=o.viewport.scrollTop,y=g2(g,l);i.current.style.transform=`translate3d(0, ${y}px, 0)`}},onWheelScroll:g=>{o.viewport&&(o.viewport.scrollTop=g)},onDragScroll:g=>{o.viewport&&(o.viewport.scrollTop=m(g))}})):null}),yG=f.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,i=qr($i,e.__scopeScrollArea),[s,l]=f.useState(),u=f.useRef(null),d=Be(t,u,i.onScrollbarXChange);return f.useEffect(()=>{u.current&&l(getComputedStyle(u.current))},[u]),f.createElement(k5,Y({"data-orientation":"horizontal"},o,{ref:d,sizes:n,style:{bottom:0,left:i.dir==="rtl"?"var(--radix-scroll-area-corner-width)":0,right:i.dir==="ltr"?"var(--radix-scroll-area-corner-width)":0,"--radix-scroll-area-thumb-width":ng(n)+"px",...e.style},onThumbPointerDown:h=>e.onThumbPointerDown(h.x),onDragScroll:h=>e.onDragScroll(h.x),onWheelScroll:(h,m)=>{if(i.viewport){const g=i.viewport.scrollLeft+h.deltaX;e.onWheelScroll(g),A5(g,m)&&h.preventDefault()}},onResize:()=>{u.current&&i.viewport&&s&&r({content:i.viewport.scrollWidth,viewport:i.viewport.offsetWidth,scrollbar:{size:u.current.clientWidth,paddingStart:zh(s.paddingLeft),paddingEnd:zh(s.paddingRight)}})}}))}),wG=f.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,i=qr($i,e.__scopeScrollArea),[s,l]=f.useState(),u=f.useRef(null),d=Be(t,u,i.onScrollbarYChange);return f.useEffect(()=>{u.current&&l(getComputedStyle(u.current))},[u]),f.createElement(k5,Y({"data-orientation":"vertical"},o,{ref:d,sizes:n,style:{top:0,right:i.dir==="ltr"?0:void 0,left:i.dir==="rtl"?0:void 0,bottom:"var(--radix-scroll-area-corner-height)","--radix-scroll-area-thumb-height":ng(n)+"px",...e.style},onThumbPointerDown:h=>e.onThumbPointerDown(h.y),onDragScroll:h=>e.onDragScroll(h.y),onWheelScroll:(h,m)=>{if(i.viewport){const g=i.viewport.scrollTop+h.deltaY;e.onWheelScroll(g),A5(g,m)&&h.preventDefault()}},onResize:()=>{u.current&&i.viewport&&s&&r({content:i.viewport.scrollHeight,viewport:i.viewport.offsetHeight,scrollbar:{size:u.current.clientHeight,paddingStart:zh(s.paddingTop),paddingEnd:zh(s.paddingBottom)}})}}))}),[xG,$5]=S5($i),k5=f.forwardRef((e,t)=>{const{__scopeScrollArea:n,sizes:r,hasThumb:o,onThumbChange:i,onThumbPointerUp:s,onThumbPointerDown:l,onThumbPositionChange:u,onDragScroll:d,onWheelScroll:h,onResize:m,...g}=e,y=qr($i,n),[x,_]=f.useState(null),C=Be(t,F=>_(F)),S=f.useRef(null),b=f.useRef(""),E=y.viewport,k=r.content-r.viewport,P=Ft(h),M=Ft(u),A=rg(m,10);function O(F){if(S.current){const V=F.clientX-S.current.left,J=F.clientY-S.current.top;d({x:V,y:J})}}return f.useEffect(()=>{const F=V=>{const J=V.target;(x==null?void 0:x.contains(J))&&P(V,k)};return document.addEventListener("wheel",F,{passive:!1}),()=>document.removeEventListener("wheel",F,{passive:!1})},[E,x,k,P]),f.useEffect(M,[r,M]),sc(x,A),sc(y.content,A),f.createElement(xG,{scope:n,scrollbar:x,hasThumb:o,onThumbChange:Ft(i),onThumbPointerUp:Ft(s),onThumbPositionChange:M,onThumbPointerDown:Ft(l)},f.createElement(Pe.div,Y({},g,{ref:C,style:{position:"absolute",...g.style},onPointerDown:ue(e.onPointerDown,F=>{F.button===0&&(F.target.setPointerCapture(F.pointerId),S.current=x.getBoundingClientRect(),b.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",y.viewport&&(y.viewport.style.scrollBehavior="auto"),O(F))}),onPointerMove:ue(e.onPointerMove,O),onPointerUp:ue(e.onPointerUp,F=>{const V=F.target;V.hasPointerCapture(F.pointerId)&&V.releasePointerCapture(F.pointerId),document.body.style.webkitUserSelect=b.current,y.viewport&&(y.viewport.style.scrollBehavior=""),S.current=null})})))}),_1="ScrollAreaThumb",bG=f.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=$5(_1,e.__scopeScrollArea);return f.createElement(xn,{present:n||o.hasThumb},f.createElement(_G,Y({ref:t},r)))}),_G=f.forwardRef((e,t)=>{const{__scopeScrollArea:n,style:r,...o}=e,i=qr(_1,n),s=$5(_1,n),{onThumbPositionChange:l}=s,u=Be(t,m=>s.onThumbChange(m)),d=f.useRef(),h=rg(()=>{d.current&&(d.current(),d.current=void 0)},100);return f.useEffect(()=>{const m=i.viewport;if(m){const g=()=>{if(h(),!d.current){const y=$G(m,l);d.current=y,l()}};return l(),m.addEventListener("scroll",g),()=>m.removeEventListener("scroll",g)}},[i.viewport,h,l]),f.createElement(Pe.div,Y({"data-state":s.hasThumb?"visible":"hidden"},o,{ref:u,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...r},onPointerDownCapture:ue(e.onPointerDownCapture,m=>{const y=m.target.getBoundingClientRect(),x=m.clientX-y.left,_=m.clientY-y.top;s.onThumbPointerDown({x,y:_})}),onPointerUp:ue(e.onPointerUp,s.onThumbPointerUp)}))}),R5="ScrollAreaCorner",SG=f.forwardRef((e,t)=>{const n=qr(R5,e.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?f.createElement(EG,Y({},e,{ref:t})):null}),EG=f.forwardRef((e,t)=>{const{__scopeScrollArea:n,...r}=e,o=qr(R5,n),[i,s]=f.useState(0),[l,u]=f.useState(0),d=!!(i&&l);return sc(o.scrollbarX,()=>{var h;const m=((h=o.scrollbarX)===null||h===void 0?void 0:h.offsetHeight)||0;o.onCornerHeightChange(m),u(m)}),sc(o.scrollbarY,()=>{var h;const m=((h=o.scrollbarY)===null||h===void 0?void 0:h.offsetWidth)||0;o.onCornerWidthChange(m),s(m)}),d?f.createElement(Pe.div,Y({},r,{ref:t,style:{width:i,height:l,position:"absolute",right:o.dir==="ltr"?0:void 0,left:o.dir==="rtl"?0:void 0,bottom:0,...e.style}})):null});function zh(e){return e?parseInt(e,10):0}function T5(e,t){const n=e/t;return isNaN(n)?0:n}function ng(e){const t=T5(e.viewport,e.content),n=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,r=(e.scrollbar.size-n)*t;return Math.max(r,18)}function CG(e,t,n,r="ltr"){const o=ng(n),i=o/2,s=t||i,l=o-s,u=n.scrollbar.paddingStart+s,d=n.scrollbar.size-n.scrollbar.paddingEnd-l,h=n.content-n.viewport,m=r==="ltr"?[0,h]:[h*-1,0];return P5([u,d],m)(e)}function g2(e,t,n="ltr"){const r=ng(t),o=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,i=t.scrollbar.size-o,s=t.content-t.viewport,l=i-r,u=n==="ltr"?[0,s]:[s*-1,0],d=id(e,u);return P5([0,s],[0,l])(d)}function P5(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 A5(e,t){return e>0&&e{})=>{let n={left:e.scrollLeft,top:e.scrollTop},r=0;return function o(){const i={left:e.scrollLeft,top:e.scrollTop},s=n.left!==i.left,l=n.top!==i.top;(s||l)&&t(),n=i,r=window.requestAnimationFrame(o)}(),()=>window.cancelAnimationFrame(r)};function rg(e,t){const n=Ft(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 sc(e,t){const n=Ft(t);Pn(()=>{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 O5=pG,kG=mG,RG=SG,og=f.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(O5,{ref:r,className:Ce("relative overflow-hidden",e),scrollHideDelay:400,...n,children:[v.jsx(kG,{className:"h-full w-full rounded-[inherit]",children:t}),v.jsx(M5,{}),v.jsx(RG,{})]}));og.displayName=O5.displayName;const M5=f.forwardRef(({className:e,orientation:t="vertical",...n},r)=>v.jsx(E5,{ref:r,orientation:t,className:Ce("flex touch-none select-none transition-colors",t==="vertical"&&"h-full w-2.5 border-l border-l-transparent p-[1px]",t==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",e),...n,children:v.jsx(bG,{className:"relative flex-1 rounded-full bg-border"})}));M5.displayName=E5.displayName;const N5="Name",D5="Created time",I5="Modified time",v2="input",TG="output",y2={[xs.NAME]:N5,[xs.CTIME]:D5,[xs.MTIME]:I5};function PG(e){const{onPhotoClick:t,photoWidth:n}=e,[r,o]=AP(!1),[i,s]=bt(V=>[V.fileManagerState,V.updateFileManagerState]),{toast:l}=Td(),[u,d]=f.useState(0),[h,m]=f.useState(0),g=f.useRef(null),y=lV(i.searchText,300),[x,_]=f.useState(v2),[C,S]=f.useState([]),[b,E]=f.useState([]),[k,P]=f.useState(0);Zn("f",()=>{o()}),Zn("left",()=>{let V=k;k>0&&(V=k-1),P(V),t(x,b[V].name)},[k,b]),Zn("right",()=>{let V=k;k{r||m(u)},[r,u]);const M=f.useCallback(V=>{V!==null&&r&&setTimeout(()=>{V.scrollTo({top:h,left:0})},100)},[r,h]);f.useEffect(()=>{(async()=>{try{const J=await Uj(x);S(J)}catch(J){l({variant:"destructive",title:"Uh oh! Something went wrong.",description:J.message?J.message:J.toString()})}})()},[x]),f.useEffect(()=>{if(!r)return;(async()=>{try{let J=C;y&&(J=new _c(J,{keys:["name"]}).search(y).map(te=>J[te.refIndex])),J=xH.orderBy(J,i.sortBy,i.sortOrder);const G=J.map(ae=>{const U=n,te=ae.height*(U/ae.width);return{src:`${Ms}/media_thumbnail_file?tab=${x}&filename=${encodeURIComponent(ae.name)}&width=${Math.ceil(U)}&height=${Math.ceil(te)}`,height:te,width:U,name:ae.name}});E(G)}catch(J){l({variant:"destructive",title:"Uh oh! Something went wrong.",description:J.message?J.message:J.toString()})}})()},[C,y,i,n,r]);const A=V=>{d(V.currentTarget.scrollTop)},O=({index:V})=>{o(),P(V),t(x,b[V].name)},F=()=>v.jsxs("div",{className:"flex justify-start items-center gap-[12px]",children:[v.jsx("div",{children:`Images (${b.length})`}),v.jsxs("div",{className:"flex",children:[v.jsx(vn,{tooltip:"Rows layout",onClick:()=>{s({layout:"rows"})},children:v.jsx(fz,{className:i.layout!=="rows"?"opacity-50":""})}),v.jsx(vn,{tooltip:"Grid layout",onClick:()=>{s({layout:"masonry"})},children:v.jsx(uz,{className:i.layout!=="masonry"?"opacity-50":""})})]})]});return v.jsxs(Zm,{open:r,onOpenChange:o,children:[v.jsx(uP,{asChild:!0,children:v.jsx(vn,{tooltip:"File Manager",children:v.jsx(QU,{})})}),v.jsxs(Fd,{className:"h-4/5 max-w-6xl",children:[v.jsx(jd,{children:F()}),v.jsxs("div",{className:"flex justify-between gap-8 items-center",children:[v.jsxs("div",{className:"flex relative justify-start items-center",children:[v.jsx(sz,{className:"absolute left-[8px]"}),v.jsx(Pd,{ref:g,value:i.searchText,className:"w-[250px] pl-[30px]",tabIndex:-1,onInput:V=>{V.preventDefault(),V.stopPropagation();const J=V.target;s({searchText:J.value})},placeholder:"Search by file name"})]}),v.jsx(i5,{defaultValue:x,onValueChange:V=>_(V),children:v.jsxs(Lx,{"aria-label":"Manage your account",children:[v.jsx(sa,{value:v2,children:"Image Directory"}),v.jsx(sa,{value:TG,children:"Output Directory"})]})}),v.jsx("div",{className:"flex gap-2",children:v.jsxs("div",{className:"flex gap-1",children:[v.jsxs(aa,{value:y2[i.sortBy],onValueChange:V=>{switch(V){case N5:s({sortBy:xs.NAME});break;case D5:s({sortBy:xs.CTIME});break;case I5:s({sortBy:xs.MTIME});break}},children:[v.jsx(ls,{className:"w-[140px]",children:v.jsx(la,{})}),v.jsx(cs,{children:Object.values(y2).map(V=>v.jsx(us,{value:V,children:V},V))})]}),i.sortOrder===$u.DESCENDING?v.jsx(vn,{tooltip:"Descending Order",onClick:()=>{s({sortOrder:$u.ASCENDING})},children:v.jsx(iK,{})}):v.jsx(vn,{tooltip:"Ascending Order",onClick:()=>{s({sortOrder:$u.DESCENDING})},children:v.jsx(lK,{})})]})})]}),v.jsx(og,{className:"w-full h-full rounded-md",onScroll:A,ref:M,children:v.jsx(nK,{layout:i.layout,photos:b,spacing:12,padding:0,onClick:O})})]})]})}var Bd=e=>e.type==="checkbox",xl=e=>e instanceof Date,Ln=e=>e==null;const L5=e=>typeof e=="object";var sn=e=>!Ln(e)&&!Array.isArray(e)&&L5(e)&&!xl(e),F5=e=>sn(e)&&e.target?Bd(e.target)?e.target.checked:e.target.value:e,AG=e=>e.substring(0,e.search(/\.\d+(\.|$)/))||e,j5=(e,t)=>e.has(AG(t)),OG=e=>{const t=e.constructor&&e.constructor.prototype;return sn(t)&&t.hasOwnProperty("isPrototypeOf")},Ux=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function so(e){let t;const n=Array.isArray(e);if(e instanceof Date)t=new Date(e);else if(e instanceof Set)t=new Set(e);else if(!(Ux&&(e instanceof Blob||e instanceof FileList))&&(n||sn(e)))if(t=n?[]:{},!n&&!OG(e))t=e;else for(const r in e)e.hasOwnProperty(r)&&(t[r]=so(e[r]));else return e;return t}var Ud=e=>Array.isArray(e)?e.filter(Boolean):[],Ht=e=>e===void 0,ve=(e,t,n)=>{if(!t||!sn(e))return n;const r=Ud(t.split(/[,[\].]+?/)).reduce((o,i)=>Ln(o)?o:o[i],e);return Ht(r)||r===e?Ht(e[t])?n:e[t]:r},No=e=>typeof e=="boolean";const Bh={BLUR:"blur",FOCUS_OUT:"focusout",CHANGE:"change"},mo={onBlur:"onBlur",onChange:"onChange",onSubmit:"onSubmit",onTouched:"onTouched",all:"all"},oi={max:"max",min:"min",maxLength:"maxLength",minLength:"minLength",pattern:"pattern",required:"required",validate:"validate"},z5=Fe.createContext(null),ig=()=>Fe.useContext(z5),MG=e=>{const{children:t,...n}=e;return Fe.createElement(z5.Provider,{value:n},t)};var B5=(e,t,n,r=!0)=>{const o={defaultValues:t._defaultValues};for(const i in e)Object.defineProperty(o,i,{get:()=>{const s=i;return t._proxyFormState[s]!==mo.all&&(t._proxyFormState[s]=!r||mo.all),n&&(n[s]=!0),e[s]}});return o},Fr=e=>sn(e)&&!Object.keys(e).length,U5=(e,t,n,r)=>{n(e);const{name:o,...i}=e;return Fr(i)||Object.keys(i).length>=Object.keys(t).length||Object.keys(i).find(s=>t[s]===(!r||mo.all))},Yp=e=>Array.isArray(e)?e:[e],V5=(e,t,n)=>!e||!t||e===t||Yp(e).some(r=>r&&(n?r===t:r.startsWith(t)||t.startsWith(r)));function Vx(e){const t=Fe.useRef(e);t.current=e,Fe.useEffect(()=>{const n=!e.disabled&&t.current.subject&&t.current.subject.subscribe({next:t.current.next});return()=>{n&&n.unsubscribe()}},[e.disabled])}function NG(e){const t=ig(),{control:n=t.control,disabled:r,name:o,exact:i}=e||{},[s,l]=Fe.useState(n._formState),u=Fe.useRef(!0),d=Fe.useRef({isDirty:!1,isLoading:!1,dirtyFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1}),h=Fe.useRef(o);return h.current=o,Vx({disabled:r,next:m=>u.current&&V5(h.current,m.name,i)&&U5(m,d.current,n._updateFormState)&&l({...n._formState,...m}),subject:n._subjects.state}),Fe.useEffect(()=>(u.current=!0,d.current.isValid&&n._updateValid(!0),()=>{u.current=!1}),[n]),B5(s,n,d.current,!1)}var Fo=e=>typeof e=="string",W5=(e,t,n,r,o)=>Fo(e)?(r&&t.watch.add(e),ve(n,e,o)):Array.isArray(e)?e.map(i=>(r&&t.watch.add(i),ve(n,i))):(r&&(t.watchAll=!0),n);function DG(e){const t=ig(),{control:n=t.control,name:r,defaultValue:o,disabled:i,exact:s}=e||{},l=Fe.useRef(r);l.current=r,Vx({disabled:i,subject:n._subjects.values,next:h=>{V5(l.current,h.name,s)&&d(so(W5(l.current,n._names,h.values||n._formValues,!1,o)))}});const[u,d]=Fe.useState(n._getWatch(r,o));return Fe.useEffect(()=>n._removeUnmounted()),u}var Wx=e=>/^\w*$/.test(e),H5=e=>Ud(e.replace(/["|']|\]/g,"").split(/\.|\[/));function wt(e,t,n){let r=-1;const o=Wx(t)?[t]:H5(t),i=o.length,s=i-1;for(;++r{const h=o._options.shouldUnregister||i,m=(g,y)=>{const x=ve(o._fields,g);x&&(x._f.mount=y)};if(m(n,!0),h){const g=so(ve(o._options.defaultValues,n));wt(o._defaultValues,n,g),Ht(ve(o._formValues,n))&&wt(o._formValues,n,g)}return()=>{(s?h&&!o._state.action:h)?o.unregister(n):m(n,!1)}},[n,o,s,i]),Fe.useEffect(()=>{ve(o._fields,n)&&o._updateDisabledField({disabled:r,fields:o._fields,name:n,value:ve(o._fields,n)._f.value})},[r,n,o]),{field:{name:n,value:l,...No(r)||No(u.disabled)?{disabled:u.disabled||r}:{},onChange:Fe.useCallback(h=>d.current.onChange({target:{value:F5(h),name:n},type:Bh.CHANGE}),[n]),onBlur:Fe.useCallback(()=>d.current.onBlur({target:{value:ve(o._formValues,n),name:n},type:Bh.BLUR}),[n,o]),ref:h=>{const m=ve(o._fields,n);m&&h&&(m._f.ref={focus:()=>h.focus(),select:()=>h.select(),setCustomValidity:g=>h.setCustomValidity(g),reportValidity:()=>h.reportValidity()})}},formState:u,fieldState:Object.defineProperties({},{invalid:{enumerable:!0,get:()=>!!ve(u.errors,n)},isDirty:{enumerable:!0,get:()=>!!ve(u.dirtyFields,n)},isTouched:{enumerable:!0,get:()=>!!ve(u.touchedFields,n)},error:{enumerable:!0,get:()=>ve(u.errors,n)}})}}const LG=e=>e.render(IG(e));var K5=(e,t,n,r,o)=>t?{...n[e],types:{...n[e]&&n[e].types?n[e].types:{},[r]:o||!0}}:{},w2=e=>({isOnSubmit:!e||e===mo.onSubmit,isOnBlur:e===mo.onBlur,isOnChange:e===mo.onChange,isOnAll:e===mo.all,isOnTouch:e===mo.onTouched}),x2=(e,t,n)=>!n&&(t.watchAll||t.watch.has(e)||[...t.watch].some(r=>e.startsWith(r)&&/^\.\w+/.test(e.slice(r.length))));const Gp=(e,t,n,r)=>{for(const o of n||Object.keys(e)){const i=ve(e,o);if(i){const{_f:s,...l}=i;if(s){if(s.refs&&s.refs[0]&&t(s.refs[0],o)&&!r)break;if(s.ref&&t(s.ref,s.name)&&!r)break}else sn(l)&&Gp(l,t)}}};var FG=(e,t,n)=>{const r=Ud(ve(e,n));return wt(r,"root",t[n]),wt(e,n,r),e},Hx=e=>e.type==="file",ds=e=>typeof e=="function",Uh=e=>{if(!Ux)return!1;const t=e?e.ownerDocument:0;return e instanceof(t&&t.defaultView?t.defaultView.HTMLElement:HTMLElement)},Xp=e=>Fo(e),Kx=e=>e.type==="radio",Vh=e=>e instanceof RegExp;const b2={value:!1,isValid:!1},_2={value:!0,isValid:!0};var Y5=e=>{if(Array.isArray(e)){if(e.length>1){const t=e.filter(n=>n&&n.checked&&!n.disabled).map(n=>n.value);return{value:t,isValid:!!t.length}}return e[0].checked&&!e[0].disabled?e[0].attributes&&!Ht(e[0].attributes.value)?Ht(e[0].value)||e[0].value===""?_2:{value:e[0].value,isValid:!0}:_2:b2}return b2};const S2={isValid:!1,value:null};var G5=e=>Array.isArray(e)?e.reduce((t,n)=>n&&n.checked&&!n.disabled?{isValid:!0,value:n.value}:t,S2):S2;function E2(e,t,n="validate"){if(Xp(e)||Array.isArray(e)&&e.every(Xp)||No(e)&&!e)return{type:n,message:Xp(e)?e:"",ref:t}}var el=e=>sn(e)&&!Vh(e)?e:{value:e,message:""},C2=async(e,t,n,r,o)=>{const{ref:i,refs:s,required:l,maxLength:u,minLength:d,min:h,max:m,pattern:g,validate:y,name:x,valueAsNumber:_,mount:C,disabled:S}=e._f,b=ve(t,x);if(!C||S)return{};const E=s?s[0]:i,k=G=>{r&&E.reportValidity&&(E.setCustomValidity(No(G)?"":G||""),E.reportValidity())},P={},M=Kx(i),A=Bd(i),O=M||A,F=(_||Hx(i))&&Ht(i.value)&&Ht(b)||Uh(i)&&i.value===""||b===""||Array.isArray(b)&&!b.length,V=K5.bind(null,x,n,P),J=(G,ae,U,te=oi.maxLength,L=oi.minLength)=>{const ie=G?ae:U;P[x]={type:G?te:L,message:ie,ref:i,...V(G?te:L,ie)}};if(o?!Array.isArray(b)||!b.length:l&&(!O&&(F||Ln(b))||No(b)&&!b||A&&!Y5(s).isValid||M&&!G5(s).isValid)){const{value:G,message:ae}=Xp(l)?{value:!!l,message:l}:el(l);if(G&&(P[x]={type:oi.required,message:ae,ref:E,...V(oi.required,ae)},!n))return k(ae),P}if(!F&&(!Ln(h)||!Ln(m))){let G,ae;const U=el(m),te=el(h);if(!Ln(b)&&!isNaN(b)){const L=i.valueAsNumber||b&&+b;Ln(U.value)||(G=L>U.value),Ln(te.value)||(ae=Lnew Date(new Date().toDateString()+" "+W),K=i.type=="time",Q=i.type=="week";Fo(U.value)&&b&&(G=K?ie(b)>ie(U.value):Q?b>U.value:L>new Date(U.value)),Fo(te.value)&&b&&(ae=K?ie(b)+G.value,te=!Ln(ae.value)&&b.length<+ae.value;if((U||te)&&(J(U,G.message,ae.message),!n))return k(P[x].message),P}if(g&&!F&&Fo(b)){const{value:G,message:ae}=el(g);if(Vh(G)&&!b.match(G)&&(P[x]={type:oi.pattern,message:ae,ref:i,...V(oi.pattern,ae)},!n))return k(ae),P}if(y){if(ds(y)){const G=await y(b,t),ae=E2(G,E);if(ae&&(P[x]={...ae,...V(oi.validate,ae.message)},!n))return k(ae.message),P}else if(sn(y)){let G={};for(const ae in y){if(!Fr(G)&&!n)break;const U=E2(await y[ae](b,t),E,ae);U&&(G={...U,...V(ae,U.message)},k(U.message),n&&(P[x]=G))}if(!Fr(G)&&(P[x]={ref:E,...G},!n))return P}}return k(!0),P};function jG(e,t){const n=t.slice(0,-1).length;let r=0;for(;r{for(const i of e)i.next&&i.next(o)},subscribe:o=>(e.push(o),{unsubscribe:()=>{e=e.filter(i=>i!==o)}}),unsubscribe:()=>{e=[]}}}var Wh=e=>Ln(e)||!L5(e);function ca(e,t){if(Wh(e)||Wh(t))return e===t;if(xl(e)&&xl(t))return e.getTime()===t.getTime();const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(const o of n){const i=e[o];if(!r.includes(o))return!1;if(o!=="ref"){const s=t[o];if(xl(i)&&xl(s)||sn(i)&&sn(s)||Array.isArray(i)&&Array.isArray(s)?!ca(i,s):i!==s)return!1}}return!0}var X5=e=>e.type==="select-multiple",BG=e=>Kx(e)||Bd(e),P0=e=>Uh(e)&&e.isConnected,Z5=e=>{for(const t in e)if(ds(e[t]))return!0;return!1};function Hh(e,t={}){const n=Array.isArray(e);if(sn(e)||n)for(const r in e)Array.isArray(e[r])||sn(e[r])&&!Z5(e[r])?(t[r]=Array.isArray(e[r])?[]:{},Hh(e[r],t[r])):Ln(e[r])||(t[r]=!0);return t}function q5(e,t,n){const r=Array.isArray(e);if(sn(e)||r)for(const o in e)Array.isArray(e[o])||sn(e[o])&&!Z5(e[o])?Ht(t)||Wh(n[o])?n[o]=Array.isArray(e[o])?Hh(e[o],[]):{...Hh(e[o])}:q5(e[o],Ln(t)?{}:t[o],n[o]):n[o]=!ca(e[o],t[o]);return n}var A0=(e,t)=>q5(e,t,Hh(t)),Q5=(e,{valueAsNumber:t,valueAsDate:n,setValueAs:r})=>Ht(e)?e:t?e===""?NaN:e&&+e:n&&Fo(e)?new Date(e):r?r(e):e;function O0(e){const t=e.ref;if(!(e.refs?e.refs.every(n=>n.disabled):t.disabled))return Hx(t)?t.files:Kx(t)?G5(e.refs).value:X5(t)?[...t.selectedOptions].map(({value:n})=>n):Bd(t)?Y5(e.refs).value:Q5(Ht(t.value)?e.ref.value:t.value,e)}var UG=(e,t,n,r)=>{const o={};for(const i of e){const s=ve(t,i);s&&wt(o,i,s._f)}return{criteriaMode:n,names:[...e],fields:o,shouldUseNativeValidation:r}},iu=e=>Ht(e)?e:Vh(e)?e.source:sn(e)?Vh(e.value)?e.value.source:e.value:e,VG=e=>e.mount&&(e.required||e.min||e.max||e.maxLength||e.minLength||e.pattern||e.validate);function $2(e,t,n){const r=ve(e,n);if(r||Wx(n))return{error:r,name:n};const o=n.split(".");for(;o.length;){const i=o.join("."),s=ve(t,i),l=ve(e,i);if(s&&!Array.isArray(s)&&n!==i)return{name:n};if(l&&l.type)return{name:i,error:l};o.pop()}return{name:n}}var WG=(e,t,n,r,o)=>o.isOnAll?!1:!n&&o.isOnTouch?!(t||e):(n?r.isOnBlur:o.isOnBlur)?!e:(n?r.isOnChange:o.isOnChange)?e:!0,HG=(e,t)=>!Ud(ve(e,t)).length&&hn(e,t);const KG={mode:mo.onSubmit,reValidateMode:mo.onChange,shouldFocusError:!0};function YG(e={},t){let n={...KG,...e},r={submitCount:0,isDirty:!1,isLoading:ds(n.defaultValues),isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},errors:{},disabled:!1},o={},i=sn(n.defaultValues)||sn(n.values)?so(n.defaultValues||n.values)||{}:{},s=n.shouldUnregister?{}:so(i),l={action:!1,mount:!1,watch:!1},u={mount:new Set,unMount:new Set,array:new Set,watch:new Set},d,h=0;const m={isDirty:!1,dirtyFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1},g={values:T0(),array:T0(),state:T0()},y=e.resetOptions&&e.resetOptions.keepDirtyValues,x=w2(n.mode),_=w2(n.reValidateMode),C=n.criteriaMode===mo.all,S=I=>X=>{clearTimeout(h),h=setTimeout(I,X)},b=async I=>{if(m.isValid||I){const X=n.resolver?Fr((await F()).errors):await J(o,!0);X!==r.isValid&&g.state.next({isValid:X})}},E=I=>m.isValidating&&g.state.next({isValidating:I}),k=(I,X=[],Z,we,he=!0,de=!0)=>{if(we&&Z){if(l.action=!0,de&&Array.isArray(ve(o,I))){const ke=Z(ve(o,I),we.argA,we.argB);he&&wt(o,I,ke)}if(de&&Array.isArray(ve(r.errors,I))){const ke=Z(ve(r.errors,I),we.argA,we.argB);he&&wt(r.errors,I,ke),HG(r.errors,I)}if(m.touchedFields&&de&&Array.isArray(ve(r.touchedFields,I))){const ke=Z(ve(r.touchedFields,I),we.argA,we.argB);he&&wt(r.touchedFields,I,ke)}m.dirtyFields&&(r.dirtyFields=A0(i,s)),g.state.next({name:I,isDirty:ae(I,X),dirtyFields:r.dirtyFields,errors:r.errors,isValid:r.isValid})}else wt(s,I,X)},P=(I,X)=>{wt(r.errors,I,X),g.state.next({errors:r.errors})},M=(I,X,Z,we)=>{const he=ve(o,I);if(he){const de=ve(s,I,Ht(Z)?ve(i,I):Z);Ht(de)||we&&we.defaultChecked||X?wt(s,I,X?de:O0(he._f)):L(I,de),l.mount&&b()}},A=(I,X,Z,we,he)=>{let de=!1,ke=!1;const ft={name:I};if(!Z||we){m.isDirty&&(ke=r.isDirty,r.isDirty=ft.isDirty=ae(),de=ke!==ft.isDirty);const pt=ca(ve(i,I),X);ke=ve(r.dirtyFields,I),pt?hn(r.dirtyFields,I):wt(r.dirtyFields,I,!0),ft.dirtyFields=r.dirtyFields,de=de||m.dirtyFields&&ke!==!pt}if(Z){const pt=ve(r.touchedFields,I);pt||(wt(r.touchedFields,I,Z),ft.touchedFields=r.touchedFields,de=de||m.touchedFields&&pt!==Z)}return de&&he&&g.state.next(ft),de?ft:{}},O=(I,X,Z,we)=>{const he=ve(r.errors,I),de=m.isValid&&No(X)&&r.isValid!==X;if(e.delayError&&Z?(d=S(()=>P(I,Z)),d(e.delayError)):(clearTimeout(h),d=null,Z?wt(r.errors,I,Z):hn(r.errors,I)),(Z?!ca(he,Z):he)||!Fr(we)||de){const ke={...we,...de&&No(X)?{isValid:X}:{},errors:r.errors,name:I};r={...r,...ke},g.state.next(ke)}E(!1)},F=async I=>n.resolver(s,n.context,UG(I||u.mount,o,n.criteriaMode,n.shouldUseNativeValidation)),V=async I=>{const{errors:X}=await F(I);if(I)for(const Z of I){const we=ve(X,Z);we?wt(r.errors,Z,we):hn(r.errors,Z)}else r.errors=X;return X},J=async(I,X,Z={valid:!0})=>{for(const we in I){const he=I[we];if(he){const{_f:de,...ke}=he;if(de){const ft=u.array.has(de.name),pt=await C2(he,s,C,n.shouldUseNativeValidation&&!X,ft);if(pt[de.name]&&(Z.valid=!1,X))break;!X&&(ve(pt,de.name)?ft?FG(r.errors,pt,de.name):wt(r.errors,de.name,pt[de.name]):hn(r.errors,de.name))}ke&&await J(ke,X,Z)}}return Z.valid},G=()=>{for(const I of u.unMount){const X=ve(o,I);X&&(X._f.refs?X._f.refs.every(Z=>!P0(Z)):!P0(X._f.ref))&&fe(I)}u.unMount=new Set},ae=(I,X)=>(I&&X&&wt(s,I,X),!ca(ge(),i)),U=(I,X,Z)=>W5(I,u,{...l.mount?s:Ht(X)?i:Fo(I)?{[I]:X}:X},Z,X),te=I=>Ud(ve(l.mount?s:i,I,e.shouldUnregister?ve(i,I,[]):[])),L=(I,X,Z={})=>{const we=ve(o,I);let he=X;if(we){const de=we._f;de&&(!de.disabled&&wt(s,I,Q5(X,de)),he=Uh(de.ref)&&Ln(X)?"":X,X5(de.ref)?[...de.ref.options].forEach(ke=>ke.selected=he.includes(ke.value)):de.refs?Bd(de.ref)?de.refs.length>1?de.refs.forEach(ke=>(!ke.defaultChecked||!ke.disabled)&&(ke.checked=Array.isArray(he)?!!he.find(ft=>ft===ke.value):he===ke.value)):de.refs[0]&&(de.refs[0].checked=!!he):de.refs.forEach(ke=>ke.checked=ke.value===he):Hx(de.ref)?de.ref.value="":(de.ref.value=he,de.ref.type||g.values.next({name:I,values:{...s}})))}(Z.shouldDirty||Z.shouldTouch)&&A(I,he,Z.shouldTouch,Z.shouldDirty,!0),Z.shouldValidate&&le(I)},ie=(I,X,Z)=>{for(const we in X){const he=X[we],de=`${I}.${we}`,ke=ve(o,de);(u.array.has(I)||!Wh(he)||ke&&!ke._f)&&!xl(he)?ie(de,he,Z):L(de,he,Z)}},K=(I,X,Z={})=>{const we=ve(o,I),he=u.array.has(I),de=so(X);wt(s,I,de),he?(g.array.next({name:I,values:{...s}}),(m.isDirty||m.dirtyFields)&&Z.shouldDirty&&g.state.next({name:I,dirtyFields:A0(i,s),isDirty:ae(I,de)})):we&&!we._f&&!Ln(de)?ie(I,de,Z):L(I,de,Z),x2(I,u)&&g.state.next({...r}),g.values.next({name:I,values:{...s}}),!l.mount&&t()},Q=async I=>{const X=I.target;let Z=X.name,we=!0;const he=ve(o,Z),de=()=>X.type?O0(he._f):F5(I),ke=ft=>{we=Number.isNaN(ft)||ft===ve(s,Z,ft)};if(he){let ft,pt;const bn=de(),Cr=I.type===Bh.BLUR||I.type===Bh.FOCUS_OUT,ki=!VG(he._f)&&!n.resolver&&!ve(r.errors,Z)&&!he._f.deps||WG(Cr,ve(r.touchedFields,Z),r.isSubmitted,_,x),_o=x2(Z,u,Cr);wt(s,Z,bn),Cr?(he._f.onBlur&&he._f.onBlur(I),d&&d(0)):he._f.onChange&&he._f.onChange(I);const Vn=A(Z,bn,Cr,!1),Da=!Fr(Vn)||_o;if(!Cr&&g.values.next({name:Z,type:I.type,values:{...s}}),ki)return m.isValid&&b(),Da&&g.state.next({name:Z,..._o?{}:Vn});if(!Cr&&_o&&g.state.next({...r}),E(!0),n.resolver){const{errors:Ri}=await F([Z]);if(ke(bn),we){const zs=$2(r.errors,o,Z),Ti=$2(Ri,o,zs.name||Z);ft=Ti.error,Z=Ti.name,pt=Fr(Ri)}}else ft=(await C2(he,s,C,n.shouldUseNativeValidation))[Z],ke(bn),we&&(ft?pt=!1:m.isValid&&(pt=await J(o,!0)));we&&(he._f.deps&&le(he._f.deps),O(Z,pt,ft,Vn))}},W=(I,X)=>{if(ve(r.errors,X)&&I.focus)return I.focus(),1},le=async(I,X={})=>{let Z,we;const he=Yp(I);if(E(!0),n.resolver){const de=await V(Ht(I)?I:he);Z=Fr(de),we=I?!he.some(ke=>ve(de,ke)):Z}else I?(we=(await Promise.all(he.map(async de=>{const ke=ve(o,de);return await J(ke&&ke._f?{[de]:ke}:ke)}))).every(Boolean),!(!we&&!r.isValid)&&b()):we=Z=await J(o);return g.state.next({...!Fo(I)||m.isValid&&Z!==r.isValid?{}:{name:I},...n.resolver||!I?{isValid:Z}:{},errors:r.errors,isValidating:!1}),X.shouldFocus&&!we&&Gp(o,W,I?he:u.mount),we},ge=I=>{const X={...i,...l.mount?s:{}};return Ht(I)?X:Fo(I)?ve(X,I):I.map(Z=>ve(X,Z))},Ve=(I,X)=>({invalid:!!ve((X||r).errors,I),isDirty:!!ve((X||r).dirtyFields,I),isTouched:!!ve((X||r).touchedFields,I),error:ve((X||r).errors,I)}),Ue=I=>{I&&Yp(I).forEach(X=>hn(r.errors,X)),g.state.next({errors:I?r.errors:{}})},We=(I,X,Z)=>{const we=(ve(o,I,{_f:{}})._f||{}).ref;wt(r.errors,I,{...X,ref:we}),g.state.next({name:I,errors:r.errors,isValid:!1}),Z&&Z.shouldFocus&&we&&we.focus&&we.focus()},Me=(I,X)=>ds(I)?g.values.subscribe({next:Z=>I(U(void 0,X),Z)}):U(I,X,!0),fe=(I,X={})=>{for(const Z of I?Yp(I):u.mount)u.mount.delete(Z),u.array.delete(Z),X.keepValue||(hn(o,Z),hn(s,Z)),!X.keepError&&hn(r.errors,Z),!X.keepDirty&&hn(r.dirtyFields,Z),!X.keepTouched&&hn(r.touchedFields,Z),!n.shouldUnregister&&!X.keepDefaultValue&&hn(i,Z);g.values.next({values:{...s}}),g.state.next({...r,...X.keepDirty?{isDirty:ae()}:{}}),!X.keepIsValid&&b()},xe=({disabled:I,name:X,field:Z,fields:we,value:he})=>{if(No(I)){const de=I?void 0:Ht(he)?O0(Z?Z._f:ve(we,X)._f):he;wt(s,X,de),A(X,de,!1,!1,!0)}},$e=(I,X={})=>{let Z=ve(o,I);const we=No(X.disabled);return wt(o,I,{...Z||{},_f:{...Z&&Z._f?Z._f:{ref:{name:I}},name:I,mount:!0,...X}}),u.mount.add(I),Z?xe({field:Z,disabled:X.disabled,name:I}):M(I,!0,X.value),{...we?{disabled:X.disabled}:{},...n.progressive?{required:!!X.required,min:iu(X.min),max:iu(X.max),minLength:iu(X.minLength),maxLength:iu(X.maxLength),pattern:iu(X.pattern)}:{},name:I,onChange:Q,onBlur:Q,ref:he=>{if(he){$e(I,X),Z=ve(o,I);const de=Ht(he.value)&&he.querySelectorAll&&he.querySelectorAll("input,select,textarea")[0]||he,ke=BG(de),ft=Z._f.refs||[];if(ke?ft.find(pt=>pt===de):de===Z._f.ref)return;wt(o,I,{_f:{...Z._f,...ke?{refs:[...ft.filter(P0),de,...Array.isArray(ve(i,I))?[{}]:[]],ref:{type:de.type,name:I}}:{ref:de}}}),M(I,!1,void 0,de)}else Z=ve(o,I,{}),Z._f&&(Z._f.mount=!1),(n.shouldUnregister||X.shouldUnregister)&&!(j5(u.array,I)&&l.action)&&u.unMount.add(I)}}},Ae=()=>n.shouldFocusError&&Gp(o,W,u.mount),Oe=I=>{No(I)&&(g.state.next({disabled:I}),Gp(o,X=>{X.disabled=I},0,!1))},je=(I,X)=>async Z=>{Z&&(Z.preventDefault&&Z.preventDefault(),Z.persist&&Z.persist());let we=so(s);if(g.state.next({isSubmitting:!0}),n.resolver){const{errors:he,values:de}=await F();r.errors=he,we=de}else await J(o);hn(r.errors,"root"),Fr(r.errors)?(g.state.next({errors:{}}),await I(we,Z)):(X&&await X({...r.errors},Z),Ae(),setTimeout(Ae)),g.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:Fr(r.errors),submitCount:r.submitCount+1,errors:r.errors})},Ot=(I,X={})=>{ve(o,I)&&(Ht(X.defaultValue)?K(I,ve(i,I)):(K(I,X.defaultValue),wt(i,I,X.defaultValue)),X.keepTouched||hn(r.touchedFields,I),X.keepDirty||(hn(r.dirtyFields,I),r.isDirty=X.defaultValue?ae(I,ve(i,I)):ae()),X.keepError||(hn(r.errors,I),m.isValid&&b()),g.state.next({...r}))},ct=(I,X={})=>{const Z=I?so(I):i,we=so(Z),he=I&&!Fr(I)?we:i;if(X.keepDefaultValues||(i=Z),!X.keepValues){if(X.keepDirtyValues||y)for(const de of u.mount)ve(r.dirtyFields,de)?wt(he,de,ve(s,de)):K(de,ve(he,de));else{if(Ux&&Ht(I))for(const de of u.mount){const ke=ve(o,de);if(ke&&ke._f){const ft=Array.isArray(ke._f.refs)?ke._f.refs[0]:ke._f.ref;if(Uh(ft)){const pt=ft.closest("form");if(pt){pt.reset();break}}}}o={}}s=e.shouldUnregister?X.keepDefaultValues?so(i):{}:so(he),g.array.next({values:{...he}}),g.values.next({values:{...he}})}u={mount:new Set,unMount:new Set,array:new Set,watch:new Set,watchAll:!1,focus:""},!l.mount&&t(),l.mount=!m.isValid||!!X.keepIsValid,l.watch=!!e.shouldUnregister,g.state.next({submitCount:X.keepSubmitCount?r.submitCount:0,isDirty:X.keepDirty?r.isDirty:!!(X.keepDefaultValues&&!ca(I,i)),isSubmitted:X.keepIsSubmitted?r.isSubmitted:!1,dirtyFields:X.keepDirtyValues?r.dirtyFields:X.keepDefaultValues&&I?A0(i,I):{},touchedFields:X.keepTouched?r.touchedFields:{},errors:X.keepErrors?r.errors:{},isSubmitSuccessful:X.keepIsSubmitSuccessful?r.isSubmitSuccessful:!1,isSubmitting:!1})},Yt=(I,X)=>ct(ds(I)?I(s):I,X);return{control:{register:$e,unregister:fe,getFieldState:Ve,handleSubmit:je,setError:We,_executeSchema:F,_getWatch:U,_getDirty:ae,_updateValid:b,_removeUnmounted:G,_updateFieldArray:k,_updateDisabledField:xe,_getFieldArray:te,_reset:ct,_resetDefaultValues:()=>ds(n.defaultValues)&&n.defaultValues().then(I=>{Yt(I,n.resetOptions),g.state.next({isLoading:!1})}),_updateFormState:I=>{r={...r,...I}},_disableForm:Oe,_subjects:g,_proxyFormState:m,get _fields(){return o},get _formValues(){return s},get _state(){return l},set _state(I){l=I},get _defaultValues(){return i},get _names(){return u},set _names(I){u=I},get _formState(){return r},set _formState(I){r=I},get _options(){return n},set _options(I){n={...n,...I}}},trigger:le,register:$e,handleSubmit:je,watch:Me,setValue:K,getValues:ge,reset:Yt,resetField:Ot,clearErrors:Ue,unregister:fe,setError:We,setFocus:(I,X={})=>{const Z=ve(o,I),we=Z&&Z._f;if(we){const he=we.refs?we.refs[0]:we.ref;he.focus&&(he.focus(),X.shouldSelect&&he.select())}},getFieldState:Ve}}function GG(e={}){const t=Fe.useRef(),n=Fe.useRef(),[r,o]=Fe.useState({isDirty:!1,isValidating:!1,isLoading:ds(e.defaultValues),isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,submitCount:0,dirtyFields:{},touchedFields:{},errors:{},disabled:!1,defaultValues:ds(e.defaultValues)?void 0:e.defaultValues});t.current||(t.current={...YG(e,()=>o(s=>({...s}))),formState:r});const i=t.current.control;return i._options=e,Vx({subject:i._subjects.state,next:s=>{U5(s,i._proxyFormState,i._updateFormState,!0)&&o({...i._formState})}}),Fe.useEffect(()=>i._disableForm(e.disabled),[i,e.disabled]),Fe.useEffect(()=>{if(i._proxyFormState.isDirty){const s=i._getDirty();s!==r.isDirty&&i._subjects.state.next({isDirty:s})}},[i,r.isDirty]),Fe.useEffect(()=>{e.values&&!ca(e.values,n.current)?(i._reset(e.values,i._options.resetOptions),n.current=e.values):i._resetDefaultValues()},[e.values,i]),Fe.useEffect(()=>{i._state.mount||(i._updateValid(),i._state.mount=!0),i._state.watch&&(i._state.watch=!1,i._subjects.state.next({...i._formState})),i._removeUnmounted()}),t.current.formState=B5(r,i),t.current}var k2=function(e,t,n){if(e&&"reportValidity"in e){var r=ve(n,t);e.setCustomValidity(r&&r.message||""),e.reportValidity()}},J5=function(e,t){var n=function(o){var i=t.fields[o];i&&i.ref&&"reportValidity"in i.ref?k2(i.ref,o,e):i.refs&&i.refs.forEach(function(s){return k2(s,o,e)})};for(var r in t.fields)n(r)},XG=function(e,t){t.shouldUseNativeValidation&&J5(e,t);var n={};for(var r in e){var o=ve(t.fields,r),i=Object.assign(e[r]||{},{ref:o&&o.ref});if(qG(t.names||Object.keys(e),r)){var s=Object.assign({},ZG(ve(n,r)));wt(s,"root",i),wt(n,r,s)}else wt(n,r,i)}return n},ZG=function(e){return Array.isArray(e)?e.filter(Boolean):[]},qG=function(e,t){return e.some(function(n){return n.startsWith(t+".")})},QG=function(e,t){for(var n={};e.length;){var r=e[0],o=r.code,i=r.message,s=r.path.join(".");if(!n[s])if("unionErrors"in r){var l=r.unionErrors[0].errors[0];n[s]={message:l.message,type:l.code}}else n[s]={message:i,type:o};if("unionErrors"in r&&r.unionErrors.forEach(function(h){return h.errors.forEach(function(m){return e.push(m)})}),t){var u=n[s].types,d=u&&u[r.code];n[s]=K5(s,t,n,o,d?[].concat(d,r.message):r.message)}e.shift()}return n},JG=function(e,t,n){return n===void 0&&(n={}),function(r,o,i){try{return Promise.resolve(function(s,l){try{var u=Promise.resolve(e[n.mode==="sync"?"parse":"parseAsync"](r,t)).then(function(d){return i.shouldUseNativeValidation&&J5({},i),{errors:{},values:n.raw?r:d}})}catch(d){return l(d)}return u&&u.then?u.then(void 0,l):u}(0,function(s){if(function(l){return l.errors!=null}(s))return{values:{},errors:XG(QG(s.errors,!i.shouldUseNativeValidation&&i.criteriaMode==="all"),i)};throw s}))}catch(s){return Promise.reject(s)}}},mt;(function(e){e.assertEqual=o=>o;function t(o){}e.assertIs=t;function n(o){throw new Error}e.assertNever=n,e.arrayToEnum=o=>{const i={};for(const s of o)i[s]=s;return i},e.getValidEnumValues=o=>{const i=e.objectKeys(o).filter(l=>typeof o[o[l]]!="number"),s={};for(const l of i)s[l]=o[l];return e.objectValues(s)},e.objectValues=o=>e.objectKeys(o).map(function(i){return o[i]}),e.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{const i=[];for(const s in o)Object.prototype.hasOwnProperty.call(o,s)&&i.push(s);return i},e.find=(o,i)=>{for(const s of o)if(i(s))return s},e.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&isFinite(o)&&Math.floor(o)===o;function r(o,i=" | "){return o.map(s=>typeof s=="string"?`'${s}'`:s).join(i)}e.joinValues=r,e.jsonStringifyReplacer=(o,i)=>typeof i=="bigint"?i.toString():i})(mt||(mt={}));var R2;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(R2||(R2={}));const be=mt.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ta=e=>{switch(typeof e){case"undefined":return be.undefined;case"string":return be.string;case"number":return isNaN(e)?be.nan:be.number;case"boolean":return be.boolean;case"function":return be.function;case"bigint":return be.bigint;case"symbol":return be.symbol;case"object":return Array.isArray(e)?be.array:e===null?be.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?be.promise:typeof Map<"u"&&e instanceof Map?be.map:typeof Set<"u"&&e instanceof Set?be.set:typeof Date<"u"&&e instanceof Date?be.date:be.object;default:return be.unknown}},pe=mt.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"]);class Bo 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(i){return i.message},r={_errors:[]},o=i=>{for(const s of i.issues)if(s.code==="invalid_union")s.unionErrors.map(o);else if(s.code==="invalid_return_type")o(s.returnTypeError);else if(s.code==="invalid_arguments")o(s.argumentsError);else if(s.path.length===0)r._errors.push(n(s));else{let l=r,u=0;for(;un.message){const n={},r=[];for(const o of this.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(t(o))):r.push(t(o));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}}Bo.create=e=>new Bo(e);const Kh=(e,t)=>{let n;switch(e.code){case pe.invalid_type:e.received===be.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case pe.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,mt.jsonStringifyReplacer)}`;break;case pe.unrecognized_keys:n=`Unrecognized key(s) in object: ${mt.joinValues(e.keys,", ")}`;break;case pe.invalid_union:n="Invalid input";break;case pe.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${mt.joinValues(e.options)}`;break;case pe.invalid_enum_value:n=`Invalid enum value. Expected ${mt.joinValues(e.options)}, received '${e.received}'`;break;case pe.invalid_arguments:n="Invalid function arguments";break;case pe.invalid_return_type:n="Invalid function return type";break;case pe.invalid_date:n="Invalid date";break;case pe.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}"`:mt.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case pe.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 pe.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 pe.custom:n="Invalid input";break;case pe.invalid_intersection_types:n="Intersection results could not be merged";break;case pe.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case pe.not_finite:n="Number must be finite";break;default:n=t.defaultError,mt.assertNever(e)}return{message:n}};let eX=Kh;function S1(){return eX}const E1=e=>{const{data:t,path:n,errorMaps:r,issueData:o}=e,i=[...n,...o.path||[]],s={...o,path:i};let l="";const u=r.filter(d=>!!d).slice().reverse();for(const d of u)l=d(s,{data:t,defaultError:l}).message;return{...o,path:i,message:o.message||l}};function Ee(e,t){const n=E1({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,S1(),Kh].filter(r=>!!r)});e.common.issues.push(n)}class zn{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 o of n){if(o.status==="aborted")return Ze;o.status==="dirty"&&t.dirty(),r.push(o.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){const r=[];for(const o of n)r.push({key:await o.key,value:await o.value});return zn.mergeObjectSync(t,r)}static mergeObjectSync(t,n){const r={};for(const o of n){const{key:i,value:s}=o;if(i.status==="aborted"||s.status==="aborted")return Ze;i.status==="dirty"&&t.dirty(),s.status==="dirty"&&t.dirty(),i.value!=="__proto__"&&(typeof s.value<"u"||o.alwaysSet)&&(r[i.value]=s.value)}return{status:t.value,value:r}}}const Ze=Object.freeze({status:"aborted"}),tX=e=>({status:"dirty",value:e}),rr=e=>({status:"valid",value:e}),T2=e=>e.status==="aborted",P2=e=>e.status==="dirty",Yh=e=>e.status==="valid",C1=e=>typeof Promise<"u"&&e instanceof Promise;var Ne;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t==null?void 0:t.message})(Ne||(Ne={}));class Ko{constructor(t,n,r,o){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=o}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 A2=(e,t)=>{if(Yh(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 Bo(e.common.issues);return this._error=n,this._error}}};function Xe(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:r,description:o}=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:o}:{errorMap:(s,l)=>s.code!=="invalid_type"?{message:l.defaultError}:typeof l.data>"u"?{message:r??l.defaultError}:{message:n??l.defaultError},description:o}}class rt{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.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this)}get description(){return this._def.description}_getType(t){return ta(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:ta(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new zn,ctx:{common:t.parent.common,data:t.data,parsedType:ta(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const n=this._parse(t);if(C1(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 o={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:ta(t)},i=this._parseSync({data:t,path:o.path,parent:o});return A2(o,i)}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:ta(t)},o=this._parse({data:t,path:r.path,parent:r}),i=await(C1(o)?o:Promise.resolve(o));return A2(r,i)}refine(t,n){const r=o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n;return this._refinement((o,i)=>{const s=t(o),l=()=>i.addIssue({code:pe.custom,...r(o)});return typeof Promise<"u"&&s instanceof Promise?s.then(u=>u?!0:(l(),!1)):s?!0:(l(),!1)})}refinement(t,n){return this._refinement((r,o)=>t(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(t){return new Si({schema:this,typeName:ze.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}optional(){return bs.create(this,this._def)}nullable(){return uc.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Uo.create(this,this._def)}promise(){return ad.create(this,this._def)}or(t){return Zh.create([this,t],this._def)}and(t){return qh.create(this,t,this._def)}transform(t){return new Si({...Xe(this._def),schema:this,typeName:ze.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const n=typeof t=="function"?t:()=>t;return new nm({...Xe(this._def),innerType:this,defaultValue:n,typeName:ze.ZodDefault})}brand(){return new pX({typeName:ze.ZodBranded,type:this,...Xe(this._def)})}catch(t){const n=typeof t=="function"?t:()=>t;return new O1({...Xe(this._def),innerType:this,catchValue:n,typeName:ze.ZodCatch})}describe(t){const n=this.constructor;return new n({...this._def,description:t})}pipe(t){return sg.create(this,t)}readonly(){return N1.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const nX=/^c[^\s-]{8,}$/i,rX=/^[a-z][a-z0-9]*$/,oX=/^[0-9A-HJKMNP-TV-Z]{26}$/,iX=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,sX=/^(?!\.)(?!.*\.\.)([A-Z0-9_+-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,aX="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let M0;const lX=/^(((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}))$/,cX=/^(([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})))$/,uX=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 dX(e,t){return!!((t==="v4"||!t)&&lX.test(e)||(t==="v6"||!t)&&cX.test(e))}class di extends rt{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==be.string){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_type,expected:be.string,received:i.parsedType}),Ze}const r=new zn;let o;for(const i of this._def.checks)if(i.kind==="min")t.data.lengthi.value&&(o=this._getOrReturnCtx(t,o),Ee(o,{code:pe.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){const s=t.data.length>i.value,l=t.data.lengtht.test(o),{validation:n,code:pe.invalid_string,...Ne.errToObj(r)})}_addCheck(t){return new di({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...Ne.errToObj(t)})}url(t){return this._addCheck({kind:"url",...Ne.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...Ne.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...Ne.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...Ne.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...Ne.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...Ne.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...Ne.errToObj(t)})}datetime(t){var n;return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof(t==null?void 0:t.precision)>"u"?null:t==null?void 0:t.precision,offset:(n=t==null?void 0:t.offset)!==null&&n!==void 0?n:!1,...Ne.errToObj(t==null?void 0:t.message)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...Ne.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n==null?void 0:n.position,...Ne.errToObj(n==null?void 0:n.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...Ne.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...Ne.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...Ne.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...Ne.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...Ne.errToObj(n)})}nonempty(t){return this.min(1,Ne.errToObj(t))}trim(){return new di({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new di({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new di({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}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 di({checks:[],typeName:ze.ZodString,coerce:(t=e==null?void 0:e.coerce)!==null&&t!==void 0?t:!1,...Xe(e)})};function fX(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,o=n>r?n:r,i=parseInt(e.toFixed(o).replace(".","")),s=parseInt(t.toFixed(o).replace(".",""));return i%s/Math.pow(10,o)}class ac extends rt{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)!==be.number){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_type,expected:be.number,received:i.parsedType}),Ze}let r;const o=new zn;for(const i of this._def.checks)i.kind==="int"?mt.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.invalid_type,expected:"integer",received:"float",message:i.message}),o.dirty()):i.kind==="min"?(i.inclusive?t.datai.value:t.data>=i.value)&&(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),o.dirty()):i.kind==="multipleOf"?fX(t.data,i.value)!==0&&(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):i.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.not_finite,message:i.message}),o.dirty()):mt.assertNever(i);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,Ne.toString(n))}gt(t,n){return this.setLimit("min",t,!1,Ne.toString(n))}lte(t,n){return this.setLimit("max",t,!0,Ne.toString(n))}lt(t,n){return this.setLimit("max",t,!1,Ne.toString(n))}setLimit(t,n,r,o){return new ac({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:Ne.toString(o)}]})}_addCheck(t){return new ac({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:Ne.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Ne.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Ne.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Ne.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Ne.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:Ne.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:Ne.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Ne.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Ne.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"&&mt.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 ac({checks:[],typeName:ze.ZodNumber,coerce:(e==null?void 0:e.coerce)||!1,...Xe(e)});class lc extends rt{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)!==be.bigint){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_type,expected:be.bigint,received:i.parsedType}),Ze}let r;const o=new zn;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?t.datai.value:t.data>=i.value)&&(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),o.dirty()):i.kind==="multipleOf"?t.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):mt.assertNever(i);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,Ne.toString(n))}gt(t,n){return this.setLimit("min",t,!1,Ne.toString(n))}lte(t,n){return this.setLimit("max",t,!0,Ne.toString(n))}lt(t,n){return this.setLimit("max",t,!1,Ne.toString(n))}setLimit(t,n,r,o){return new lc({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:Ne.toString(o)}]})}_addCheck(t){return new lc({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Ne.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Ne.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Ne.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Ne.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:Ne.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 lc({checks:[],typeName:ze.ZodBigInt,coerce:(t=e==null?void 0:e.coerce)!==null&&t!==void 0?t:!1,...Xe(e)})};class $1 extends rt{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==be.boolean){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.boolean,received:r.parsedType}),Ze}return rr(t.data)}}$1.create=e=>new $1({typeName:ze.ZodBoolean,coerce:(e==null?void 0:e.coerce)||!1,...Xe(e)});class sd extends rt{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==be.date){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_type,expected:be.date,received:i.parsedType}),Ze}if(isNaN(t.data.getTime())){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_date}),Ze}const r=new zn;let o;for(const i of this._def.checks)i.kind==="min"?t.data.getTime()i.value&&(o=this._getOrReturnCtx(t,o),Ee(o,{code:pe.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):mt.assertNever(i);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new sd({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:Ne.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:Ne.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 sd({checks:[],coerce:(e==null?void 0:e.coerce)||!1,typeName:ze.ZodDate,...Xe(e)});class k1 extends rt{_parse(t){if(this._getType(t)!==be.symbol){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.symbol,received:r.parsedType}),Ze}return rr(t.data)}}k1.create=e=>new k1({typeName:ze.ZodSymbol,...Xe(e)});class Gh extends rt{_parse(t){if(this._getType(t)!==be.undefined){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.undefined,received:r.parsedType}),Ze}return rr(t.data)}}Gh.create=e=>new Gh({typeName:ze.ZodUndefined,...Xe(e)});class Xh extends rt{_parse(t){if(this._getType(t)!==be.null){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.null,received:r.parsedType}),Ze}return rr(t.data)}}Xh.create=e=>new Xh({typeName:ze.ZodNull,...Xe(e)});class R1 extends rt{constructor(){super(...arguments),this._any=!0}_parse(t){return rr(t.data)}}R1.create=e=>new R1({typeName:ze.ZodAny,...Xe(e)});class Tl extends rt{constructor(){super(...arguments),this._unknown=!0}_parse(t){return rr(t.data)}}Tl.create=e=>new Tl({typeName:ze.ZodUnknown,...Xe(e)});class Rs extends rt{_parse(t){const n=this._getOrReturnCtx(t);return Ee(n,{code:pe.invalid_type,expected:be.never,received:n.parsedType}),Ze}}Rs.create=e=>new Rs({typeName:ze.ZodNever,...Xe(e)});class T1 extends rt{_parse(t){if(this._getType(t)!==be.undefined){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.void,received:r.parsedType}),Ze}return rr(t.data)}}T1.create=e=>new T1({typeName:ze.ZodVoid,...Xe(e)});class Uo extends rt{_parse(t){const{ctx:n,status:r}=this._processInputParams(t),o=this._def;if(n.parsedType!==be.array)return Ee(n,{code:pe.invalid_type,expected:be.array,received:n.parsedType}),Ze;if(o.exactLength!==null){const s=n.data.length>o.exactLength.value,l=n.data.lengtho.maxLength.value&&(Ee(n,{code:pe.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((s,l)=>o.type._parseAsync(new Ko(n,s,n.path,l)))).then(s=>zn.mergeArray(r,s));const i=[...n.data].map((s,l)=>o.type._parseSync(new Ko(n,s,n.path,l)));return zn.mergeArray(r,i)}get element(){return this._def.type}min(t,n){return new Uo({...this._def,minLength:{value:t,message:Ne.toString(n)}})}max(t,n){return new Uo({...this._def,maxLength:{value:t,message:Ne.toString(n)}})}length(t,n){return new Uo({...this._def,exactLength:{value:t,message:Ne.toString(n)}})}nonempty(t){return this.min(1,t)}}Uo.create=(e,t)=>new Uo({type:e,minLength:null,maxLength:null,exactLength:null,typeName:ze.ZodArray,...Xe(t)});function ol(e){if(e instanceof Vt){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=bs.create(ol(r))}return new Vt({...e._def,shape:()=>t})}else return e instanceof Uo?new Uo({...e._def,type:ol(e.element)}):e instanceof bs?bs.create(ol(e.unwrap())):e instanceof uc?uc.create(ol(e.unwrap())):e instanceof _i?_i.create(e.items.map(t=>ol(t))):e}class Vt extends rt{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=mt.objectKeys(t);return this._cached={shape:t,keys:n}}_parse(t){if(this._getType(t)!==be.object){const d=this._getOrReturnCtx(t);return Ee(d,{code:pe.invalid_type,expected:be.object,received:d.parsedType}),Ze}const{status:r,ctx:o}=this._processInputParams(t),{shape:i,keys:s}=this._getCached(),l=[];if(!(this._def.catchall instanceof Rs&&this._def.unknownKeys==="strip"))for(const d in o.data)s.includes(d)||l.push(d);const u=[];for(const d of s){const h=i[d],m=o.data[d];u.push({key:{status:"valid",value:d},value:h._parse(new Ko(o,m,o.path,d)),alwaysSet:d in o.data})}if(this._def.catchall instanceof Rs){const d=this._def.unknownKeys;if(d==="passthrough")for(const h of l)u.push({key:{status:"valid",value:h},value:{status:"valid",value:o.data[h]}});else if(d==="strict")l.length>0&&(Ee(o,{code:pe.unrecognized_keys,keys:l}),r.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const d=this._def.catchall;for(const h of l){const m=o.data[h];u.push({key:{status:"valid",value:h},value:d._parse(new Ko(o,m,o.path,h)),alwaysSet:h in o.data})}}return o.common.async?Promise.resolve().then(async()=>{const d=[];for(const h of u){const m=await h.key;d.push({key:m,value:await h.value,alwaysSet:h.alwaysSet})}return d}).then(d=>zn.mergeObjectSync(r,d)):zn.mergeObjectSync(r,u)}get shape(){return this._def.shape()}strict(t){return Ne.errToObj,new Vt({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{var o,i,s,l;const u=(s=(i=(o=this._def).errorMap)===null||i===void 0?void 0:i.call(o,n,r).message)!==null&&s!==void 0?s:r.defaultError;return n.code==="unrecognized_keys"?{message:(l=Ne.errToObj(t).message)!==null&&l!==void 0?l:u}:{message:u}}}:{}})}strip(){return new Vt({...this._def,unknownKeys:"strip"})}passthrough(){return new Vt({...this._def,unknownKeys:"passthrough"})}extend(t){return new Vt({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new Vt({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:ze.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new Vt({...this._def,catchall:t})}pick(t){const n={};return mt.objectKeys(t).forEach(r=>{t[r]&&this.shape[r]&&(n[r]=this.shape[r])}),new Vt({...this._def,shape:()=>n})}omit(t){const n={};return mt.objectKeys(this.shape).forEach(r=>{t[r]||(n[r]=this.shape[r])}),new Vt({...this._def,shape:()=>n})}deepPartial(){return ol(this)}partial(t){const n={};return mt.objectKeys(this.shape).forEach(r=>{const o=this.shape[r];t&&!t[r]?n[r]=o:n[r]=o.optional()}),new Vt({...this._def,shape:()=>n})}required(t){const n={};return mt.objectKeys(this.shape).forEach(r=>{if(t&&!t[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof bs;)i=i._def.innerType;n[r]=i}}),new Vt({...this._def,shape:()=>n})}keyof(){return e3(mt.objectKeys(this.shape))}}Vt.create=(e,t)=>new Vt({shape:()=>e,unknownKeys:"strip",catchall:Rs.create(),typeName:ze.ZodObject,...Xe(t)});Vt.strictCreate=(e,t)=>new Vt({shape:()=>e,unknownKeys:"strict",catchall:Rs.create(),typeName:ze.ZodObject,...Xe(t)});Vt.lazycreate=(e,t)=>new Vt({shape:e,unknownKeys:"strip",catchall:Rs.create(),typeName:ze.ZodObject,...Xe(t)});class Zh extends rt{_parse(t){const{ctx:n}=this._processInputParams(t),r=this._def.options;function o(i){for(const l of i)if(l.result.status==="valid")return l.result;for(const l of i)if(l.result.status==="dirty")return n.common.issues.push(...l.ctx.common.issues),l.result;const s=i.map(l=>new Bo(l.ctx.common.issues));return Ee(n,{code:pe.invalid_union,unionErrors:s}),Ze}if(n.common.async)return Promise.all(r.map(async i=>{const s={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:s}),ctx:s}})).then(o);{let i;const s=[];for(const u of r){const d={...n,common:{...n.common,issues:[]},parent:null},h=u._parseSync({data:n.data,path:n.path,parent:d});if(h.status==="valid")return h;h.status==="dirty"&&!i&&(i={result:h,ctx:d}),d.common.issues.length&&s.push(d.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;const l=s.map(u=>new Bo(u));return Ee(n,{code:pe.invalid_union,unionErrors:l}),Ze}}get options(){return this._def.options}}Zh.create=(e,t)=>new Zh({options:e,typeName:ze.ZodUnion,...Xe(t)});const Zp=e=>e instanceof Jh?Zp(e.schema):e instanceof Si?Zp(e.innerType()):e instanceof em?[e.value]:e instanceof Ta?e.options:e instanceof tm?Object.keys(e.enum):e instanceof nm?Zp(e._def.innerType):e instanceof Gh?[void 0]:e instanceof Xh?[null]:null;class Yx extends rt{_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.object)return Ee(n,{code:pe.invalid_type,expected:be.object,received:n.parsedType}),Ze;const r=this.discriminator,o=n.data[r],i=this.optionsMap.get(o);return i?n.common.async?i._parseAsync({data:n.data,path:n.path,parent:n}):i._parseSync({data:n.data,path:n.path,parent:n}):(Ee(n,{code:pe.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),Ze)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){const o=new Map;for(const i of n){const s=Zp(i.shape[t]);if(!s)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const l of s){if(o.has(l))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(l)}`);o.set(l,i)}}return new Yx({typeName:ze.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:o,...Xe(r)})}}function P1(e,t){const n=ta(e),r=ta(t);if(e===t)return{valid:!0,data:e};if(n===be.object&&r===be.object){const o=mt.objectKeys(t),i=mt.objectKeys(e).filter(l=>o.indexOf(l)!==-1),s={...e,...t};for(const l of i){const u=P1(e[l],t[l]);if(!u.valid)return{valid:!1};s[l]=u.data}return{valid:!0,data:s}}else if(n===be.array&&r===be.array){if(e.length!==t.length)return{valid:!1};const o=[];for(let i=0;i{if(T2(i)||T2(s))return Ze;const l=P1(i.value,s.value);return l.valid?((P2(i)||P2(s))&&n.dirty(),{status:n.value,value:l.data}):(Ee(r,{code:pe.invalid_intersection_types}),Ze)};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(([i,s])=>o(i,s)):o(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}qh.create=(e,t,n)=>new qh({left:e,right:t,typeName:ze.ZodIntersection,...Xe(n)});class _i extends rt{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.array)return Ee(r,{code:pe.invalid_type,expected:be.array,received:r.parsedType}),Ze;if(r.data.lengththis._def.items.length&&(Ee(r,{code:pe.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const i=[...r.data].map((s,l)=>{const u=this._def.items[l]||this._def.rest;return u?u._parse(new Ko(r,s,r.path,l)):null}).filter(s=>!!s);return r.common.async?Promise.all(i).then(s=>zn.mergeArray(n,s)):zn.mergeArray(n,i)}get items(){return this._def.items}rest(t){return new _i({...this._def,rest:t})}}_i.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new _i({items:e,typeName:ze.ZodTuple,rest:null,...Xe(t)})};class Qh extends rt{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!==be.object)return Ee(r,{code:pe.invalid_type,expected:be.object,received:r.parsedType}),Ze;const o=[],i=this._def.keyType,s=this._def.valueType;for(const l in r.data)o.push({key:i._parse(new Ko(r,l,r.path,l)),value:s._parse(new Ko(r,r.data[l],r.path,l))});return r.common.async?zn.mergeObjectAsync(n,o):zn.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof rt?new Qh({keyType:t,valueType:n,typeName:ze.ZodRecord,...Xe(r)}):new Qh({keyType:di.create(),valueType:t,typeName:ze.ZodRecord,...Xe(n)})}}class A1 extends rt{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!==be.map)return Ee(r,{code:pe.invalid_type,expected:be.map,received:r.parsedType}),Ze;const o=this._def.keyType,i=this._def.valueType,s=[...r.data.entries()].map(([l,u],d)=>({key:o._parse(new Ko(r,l,r.path,[d,"key"])),value:i._parse(new Ko(r,u,r.path,[d,"value"]))}));if(r.common.async){const l=new Map;return Promise.resolve().then(async()=>{for(const u of s){const d=await u.key,h=await u.value;if(d.status==="aborted"||h.status==="aborted")return Ze;(d.status==="dirty"||h.status==="dirty")&&n.dirty(),l.set(d.value,h.value)}return{status:n.value,value:l}})}else{const l=new Map;for(const u of s){const d=u.key,h=u.value;if(d.status==="aborted"||h.status==="aborted")return Ze;(d.status==="dirty"||h.status==="dirty")&&n.dirty(),l.set(d.value,h.value)}return{status:n.value,value:l}}}}A1.create=(e,t,n)=>new A1({valueType:t,keyType:e,typeName:ze.ZodMap,...Xe(n)});class cc extends rt{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.set)return Ee(r,{code:pe.invalid_type,expected:be.set,received:r.parsedType}),Ze;const o=this._def;o.minSize!==null&&r.data.sizeo.maxSize.value&&(Ee(r,{code:pe.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());const i=this._def.valueType;function s(u){const d=new Set;for(const h of u){if(h.status==="aborted")return Ze;h.status==="dirty"&&n.dirty(),d.add(h.value)}return{status:n.value,value:d}}const l=[...r.data.values()].map((u,d)=>i._parse(new Ko(r,u,r.path,d)));return r.common.async?Promise.all(l).then(u=>s(u)):s(l)}min(t,n){return new cc({...this._def,minSize:{value:t,message:Ne.toString(n)}})}max(t,n){return new cc({...this._def,maxSize:{value:t,message:Ne.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}}cc.create=(e,t)=>new cc({valueType:e,minSize:null,maxSize:null,typeName:ze.ZodSet,...Xe(t)});class Pu extends rt{constructor(){super(...arguments),this.validate=this.implement}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.function)return Ee(n,{code:pe.invalid_type,expected:be.function,received:n.parsedType}),Ze;function r(l,u){return E1({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,S1(),Kh].filter(d=>!!d),issueData:{code:pe.invalid_arguments,argumentsError:u}})}function o(l,u){return E1({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,S1(),Kh].filter(d=>!!d),issueData:{code:pe.invalid_return_type,returnTypeError:u}})}const i={errorMap:n.common.contextualErrorMap},s=n.data;if(this._def.returns instanceof ad){const l=this;return rr(async function(...u){const d=new Bo([]),h=await l._def.args.parseAsync(u,i).catch(y=>{throw d.addIssue(r(u,y)),d}),m=await Reflect.apply(s,this,h);return await l._def.returns._def.type.parseAsync(m,i).catch(y=>{throw d.addIssue(o(m,y)),d})})}else{const l=this;return rr(function(...u){const d=l._def.args.safeParse(u,i);if(!d.success)throw new Bo([r(u,d.error)]);const h=Reflect.apply(s,this,d.data),m=l._def.returns.safeParse(h,i);if(!m.success)throw new Bo([o(h,m.error)]);return m.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new Pu({...this._def,args:_i.create(t).rest(Tl.create())})}returns(t){return new Pu({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new Pu({args:t||_i.create([]).rest(Tl.create()),returns:n||Tl.create(),typeName:ze.ZodFunction,...Xe(r)})}}class Jh extends rt{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})}}Jh.create=(e,t)=>new Jh({getter:e,typeName:ze.ZodLazy,...Xe(t)});class em extends rt{_parse(t){if(t.data!==this._def.value){const n=this._getOrReturnCtx(t);return Ee(n,{received:n.data,code:pe.invalid_literal,expected:this._def.value}),Ze}return{status:"valid",value:t.data}}get value(){return this._def.value}}em.create=(e,t)=>new em({value:e,typeName:ze.ZodLiteral,...Xe(t)});function e3(e,t){return new Ta({values:e,typeName:ze.ZodEnum,...Xe(t)})}class Ta extends rt{_parse(t){if(typeof t.data!="string"){const n=this._getOrReturnCtx(t),r=this._def.values;return Ee(n,{expected:mt.joinValues(r),received:n.parsedType,code:pe.invalid_type}),Ze}if(this._def.values.indexOf(t.data)===-1){const n=this._getOrReturnCtx(t),r=this._def.values;return Ee(n,{received:n.data,code:pe.invalid_enum_value,options:r}),Ze}return rr(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 Ta.create(t)}exclude(t){return Ta.create(this.options.filter(n=>!t.includes(n)))}}Ta.create=e3;class tm extends rt{_parse(t){const n=mt.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==be.string&&r.parsedType!==be.number){const o=mt.objectValues(n);return Ee(r,{expected:mt.joinValues(o),received:r.parsedType,code:pe.invalid_type}),Ze}if(n.indexOf(t.data)===-1){const o=mt.objectValues(n);return Ee(r,{received:r.data,code:pe.invalid_enum_value,options:o}),Ze}return rr(t.data)}get enum(){return this._def.values}}tm.create=(e,t)=>new tm({values:e,typeName:ze.ZodNativeEnum,...Xe(t)});class ad extends rt{unwrap(){return this._def.type}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.promise&&n.common.async===!1)return Ee(n,{code:pe.invalid_type,expected:be.promise,received:n.parsedType}),Ze;const r=n.parsedType===be.promise?n.data:Promise.resolve(n.data);return rr(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}}ad.create=(e,t)=>new ad({type:e,typeName:ze.ZodPromise,...Xe(t)});class Si extends rt{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ze.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:n,ctx:r}=this._processInputParams(t),o=this._def.effect||null,i={addIssue:s=>{Ee(r,s),s.fatal?n.abort():n.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),o.type==="preprocess"){const s=o.transform(r.data,i);return r.common.issues.length?{status:"dirty",value:r.data}:r.common.async?Promise.resolve(s).then(l=>this._def.schema._parseAsync({data:l,path:r.path,parent:r})):this._def.schema._parseSync({data:s,path:r.path,parent:r})}if(o.type==="refinement"){const s=l=>{const u=o.refinement(l,i);if(r.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return l};if(r.common.async===!1){const l=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return l.status==="aborted"?Ze:(l.status==="dirty"&&n.dirty(),s(l.value),{status:n.value,value:l.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(l=>l.status==="aborted"?Ze:(l.status==="dirty"&&n.dirty(),s(l.value).then(()=>({status:n.value,value:l.value}))))}if(o.type==="transform")if(r.common.async===!1){const s=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Yh(s))return s;const l=o.transform(s.value,i);if(l instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:l}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(s=>Yh(s)?Promise.resolve(o.transform(s.value,i)).then(l=>({status:n.value,value:l})):s);mt.assertNever(o)}}Si.create=(e,t,n)=>new Si({schema:e,typeName:ze.ZodEffects,effect:t,...Xe(n)});Si.createWithPreprocess=(e,t,n)=>new Si({schema:t,effect:{type:"preprocess",transform:e},typeName:ze.ZodEffects,...Xe(n)});class bs extends rt{_parse(t){return this._getType(t)===be.undefined?rr(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}bs.create=(e,t)=>new bs({innerType:e,typeName:ze.ZodOptional,...Xe(t)});class uc extends rt{_parse(t){return this._getType(t)===be.null?rr(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}uc.create=(e,t)=>new uc({innerType:e,typeName:ze.ZodNullable,...Xe(t)});class nm extends rt{_parse(t){const{ctx:n}=this._processInputParams(t);let r=n.data;return n.parsedType===be.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}nm.create=(e,t)=>new nm({innerType:e,typeName:ze.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Xe(t)});class O1 extends rt{_parse(t){const{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return C1(o)?o.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Bo(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Bo(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}O1.create=(e,t)=>new O1({innerType:e,typeName:ze.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Xe(t)});class M1 extends rt{_parse(t){if(this._getType(t)!==be.nan){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.nan,received:r.parsedType}),Ze}return{status:"valid",value:t.data}}}M1.create=e=>new M1({typeName:ze.ZodNaN,...Xe(e)});class pX extends rt{_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 sg extends rt{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?Ze:i.status==="dirty"?(n.dirty(),tX(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{const o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?Ze:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(t,n){return new sg({in:t,out:n,typeName:ze.ZodPipeline})}}class N1 extends rt{_parse(t){const n=this._def.innerType._parse(t);return Yh(n)&&(n.value=Object.freeze(n.value)),n}}N1.create=(e,t)=>new N1({innerType:e,typeName:ze.ZodReadonly,...Xe(t)});Vt.lazycreate;var ze;(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",e.ZodReadonly="ZodReadonly"})(ze||(ze={}));const O2=di.create;ac.create;M1.create;lc.create;const su=$1.create;sd.create;k1.create;Gh.create;Xh.create;R1.create;Tl.create;Rs.create;T1.create;Uo.create;const hX=Vt.create;Vt.strictCreate;Zh.create;Yx.create;qh.create;_i.create;Qh.create;A1.create;cc.create;Pu.create;Jh.create;em.create;Ta.create;tm.create;ad.create;Si.create;bs.create;uc.create;Si.createWithPreprocess;sg.create;const D1="horizontal",mX=["horizontal","vertical"],t3=f.forwardRef((e,t)=>{const{decorative:n,orientation:r=D1,...o}=e,i=n3(r)?r:D1,l=n?{role:"none"}:{"aria-orientation":i==="vertical"?i:void 0,role:"separator"};return f.createElement(Pe.div,Y({"data-orientation":i},l,o,{ref:t}))});t3.propTypes={orientation(e,t,n){const r=e[t],o=String(r);return r&&!n3(r)?new Error(gX(o,n)):null}};function gX(e,t){return`Invalid prop \`orientation\` of value \`${e}\` supplied to \`${t}\`, expected one of: + - horizontal + - vertical + +Defaulting to \`${D1}\`.`}function n3(e){return mX.includes(e)}const r3=t3,Fn=f.forwardRef(({className:e,orientation:t="horizontal",decorative:n=!0,...r},o)=>v.jsx(r3,{ref:o,decorative:n,orientation:t,className:Ce("shrink-0 bg-border",t==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",e),...r}));Fn.displayName=r3.displayName;const vX=f.forwardRef((e,t)=>f.createElement(Pe.label,Y({},e,{ref:t,onMouseDown:n=>{var r;(r=e.onMouseDown)===null||r===void 0||r.call(e,n),!n.defaultPrevented&&n.detail>1&&n.preventDefault()}}))),o3=vX,yX=Om("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),Gx=f.forwardRef(({className:e,disabled:t,...n},r)=>v.jsx(o3,{ref:r,className:Ce(yX(),e,t?"opacity-50":"","select-none"),...n}));Gx.displayName=o3.displayName;const wX=MG,i3=f.createContext({}),N0=({...e})=>v.jsx(i3.Provider,{value:{name:e.name},children:v.jsx(LG,{...e})}),ag=()=>{const e=f.useContext(i3),t=f.useContext(s3),{getFieldState:n,formState:r}=ig(),o=n(e.name,r);if(!e)throw new Error("useFormField should be used within ");const{id:i}=t;return{id:i,name:e.name,formItemId:`${i}-form-item`,formDescriptionId:`${i}-form-item-description`,formMessageId:`${i}-form-item-message`,...o}},s3=f.createContext({}),qp=f.forwardRef(({className:e,...t},n)=>{const r=f.useId();return v.jsx(s3.Provider,{value:{id:r},children:v.jsx("div",{ref:n,className:Ce("space-y-2",e),...t})})});qp.displayName="FormItem";const Qp=f.forwardRef(({className:e,...t},n)=>{const{error:r,formItemId:o}=ag();return v.jsx(Gx,{ref:n,className:Ce(r&&"text-destructive","text-sm",e),htmlFor:o,...t})});Qp.displayName="FormLabel";const Jp=f.forwardRef(({...e},t)=>{const{error:n,formItemId:r,formDescriptionId:o,formMessageId:i}=ag();return v.jsx(Wo,{ref:t,id:r,"aria-describedby":n?`${o} ${i}`:`${o}`,"aria-invalid":!!n,...e})});Jp.displayName="FormControl";const eh=f.forwardRef(({className:e,...t},n)=>{const{formDescriptionId:r}=ag();return v.jsx("p",{ref:n,id:r,className:Ce("text-[0.8rem] text-muted-foreground",e),...t})});eh.displayName="FormDescription";const xX=f.forwardRef(({className:e,children:t,...n},r)=>{const{error:o,formMessageId:i}=ag(),s=o?String(o==null?void 0:o.message):t;return s?v.jsx("p",{ref:r,id:i,className:Ce("text-[0.8rem] font-medium text-destructive",e),...n,children:s}):null});xX.displayName="FormMessage";const a3="Switch",[bX,Ste]=An(a3),[_X,SX]=bX(a3),EX=f.forwardRef((e,t)=>{const{__scopeSwitch:n,name:r,checked:o,defaultChecked:i,required:s,disabled:l,value:u="on",onCheckedChange:d,...h}=e,[m,g]=f.useState(null),y=Be(t,b=>g(b)),x=f.useRef(!1),_=m?!!m.closest("form"):!0,[C=!1,S]=Zr({prop:o,defaultProp:i,onChange:d});return f.createElement(_X,{scope:n,checked:C,disabled:l},f.createElement(Pe.button,Y({type:"button",role:"switch","aria-checked":C,"aria-required":s,"data-state":l3(C),"data-disabled":l?"":void 0,disabled:l,value:u},h,{ref:y,onClick:ue(e.onClick,b=>{S(E=>!E),_&&(x.current=b.isPropagationStopped(),x.current||b.stopPropagation())})})),_&&f.createElement(kX,{control:m,bubbles:!x.current,name:r,value:u,checked:C,required:s,disabled:l,style:{transform:"translateX(-100%)"}}))}),CX="SwitchThumb",$X=f.forwardRef((e,t)=>{const{__scopeSwitch:n,...r}=e,o=SX(CX,n);return f.createElement(Pe.span,Y({"data-state":l3(o.checked),"data-disabled":o.disabled?"":void 0},r,{ref:t}))}),kX=e=>{const{control:t,checked:n,bubbles:r=!0,...o}=e,i=f.useRef(null),s=Fx(n),l=gx(t);return f.useEffect(()=>{const u=i.current,d=window.HTMLInputElement.prototype,m=Object.getOwnPropertyDescriptor(d,"checked").set;if(s!==n&&m){const g=new Event("click",{bubbles:r});m.call(u,n),u.dispatchEvent(g)}},[s,n,r]),f.createElement("input",Y({type:"checkbox","aria-hidden":!0,defaultChecked:n},o,{tabIndex:-1,ref:i,style:{...e.style,...l,position:"absolute",pointerEvents:"none",opacity:0,margin:0}}))};function l3(e){return e?"checked":"unchecked"}const c3=EX,RX=$X,co=f.forwardRef(({className:e,...t},n)=>v.jsx(c3,{className:Ce("peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",e),tabIndex:-1,...t,ref:n,children:v.jsx(RX,{className:Ce("pointer-events-none block h-4 w-4 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0")})}));co.displayName=c3.displayName;const TX="AlertDialog",[PX,Ete]=An(TX,[cP]),Is=cP(),AX=e=>{const{__scopeAlertDialog:t,...n}=e,r=Is(t);return f.createElement(Sx,Y({},r,n,{modal:!0}))},OX=e=>{const{__scopeAlertDialog:t,...n}=e,r=Is(t);return f.createElement(Ex,Y({},r,n))},MX=f.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=Is(n);return f.createElement(Nd,Y({},o,r,{ref:t}))}),u3="AlertDialogContent",[NX,DX]=PX(u3),IX=f.forwardRef((e,t)=>{const{__scopeAlertDialog:n,children:r,...o}=e,i=Is(n),s=f.useRef(null),l=Be(t,s),u=f.useRef(null);return f.createElement(pW,{contentName:u3,titleName:LX,docsSlug:"alert-dialog"},f.createElement(NX,{scope:n,cancelRef:u},f.createElement(Dd,Y({role:"alertdialog"},i,o,{ref:l,onOpenAutoFocus:ue(o.onOpenAutoFocus,d=>{var h;d.preventDefault(),(h=u.current)===null||h===void 0||h.focus({preventScroll:!0})}),onPointerDownOutside:d=>d.preventDefault(),onInteractOutside:d=>d.preventDefault()}),f.createElement(sx,null,r),!1)))}),LX="AlertDialogTitle",FX=f.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=Is(n);return f.createElement(Id,Y({},o,r,{ref:t}))}),jX=f.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=Is(n);return f.createElement(Ld,Y({},o,r,{ref:t}))}),zX=f.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=Is(n);return f.createElement(Cx,Y({},o,r,{ref:t}))}),BX="AlertDialogCancel",UX=f.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,{cancelRef:o}=DX(BX,n),i=Is(n),s=Be(t,o);return f.createElement(Cx,Y({},i,r,{ref:s}))}),VX=AX,WX=OX,d3=MX,f3=IX,p3=zX,h3=UX,m3=FX,g3=jX,HX=VX,KX=WX,v3=f.forwardRef(({className:e,...t},n)=>v.jsx(d3,{className:Ce("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t,ref:n}));v3.displayName=d3.displayName;const y3=f.forwardRef(({className:e,...t},n)=>v.jsxs(KX,{children:[v.jsx(v3,{}),v.jsx(f3,{ref:n,className:Ce("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",e),...t})]}));y3.displayName=f3.displayName;const w3=({className:e,...t})=>v.jsx("div",{className:Ce("flex flex-col space-y-2 text-center sm:text-left",e),...t});w3.displayName="AlertDialogHeader";const YX=f.forwardRef(({className:e,...t},n)=>v.jsx(m3,{ref:n,className:Ce("text-lg font-semibold",e),...t}));YX.displayName=m3.displayName;const GX=f.forwardRef(({className:e,...t},n)=>v.jsx(g3,{ref:n,className:Ce("text-sm text-muted-foreground",e),...t}));GX.displayName=g3.displayName;const XX=f.forwardRef(({className:e,...t},n)=>v.jsx(p3,{ref:n,className:Ce(bx(),e),...t}));XX.displayName=p3.displayName;const ZX=f.forwardRef(({className:e,...t},n)=>v.jsx(h3,{ref:n,className:Ce(bx({variant:"outline"}),"mt-2 sm:mt-0",e),...t}));ZX.displayName=h3.displayName;const qX=hX({enableFileManager:su(),inputDirectory:O2(),outputDirectory:O2(),enableDownloadMask:su(),enableManualInpainting:su(),enableUploadMask:su(),enableAutoExtractPrompt:su()}),x3="General",I1="Model",QX=[I1,x3];function JX(){const[e,t]=u1(!1),[n,r]=u1(!1),[o,i]=f.useState(I1),[s,l,u,d,h,m]=bt(O=>[O.updateAppState,O.settings,O.updateSettings,O.fileManagerState,O.updateFileManagerState,O.setModel]),{toast:g}=Td(),[y,x]=f.useState(l.model);f.useEffect(()=>{x(l.model)},[l.model]);const{data:_,status:C}=TL({queryKey:["modelInfos"],queryFn:zj}),S=GG({resolver:JG(qX),defaultValues:{enableDownloadMask:l.enableDownloadMask,enableManualInpainting:l.enableManualInpainting,enableUploadMask:l.enableUploadMask,enableAutoExtractPrompt:l.enableAutoExtractPrompt,inputDirectory:d.inputDirectory,outputDirectory:d.outputDirectory}});async function b(O){if(u({enableDownloadMask:O.enableDownloadMask,enableManualInpainting:O.enableManualInpainting,enableUploadMask:O.enableUploadMask,enableAutoExtractPrompt:O.enableAutoExtractPrompt}),h({inputDirectory:O.inputDirectory,outputDirectory:O.outputDirectory}),y.name!==l.model.name){r(),s({disableShortCuts:!0});try{const F=await Fj(y.name);g({title:`Switch to ${F.name} success`}),m(y)}catch(F){g({variant:"destructive",title:`Switch to ${y.name} failed: ${F}`}),x(l.model)}finally{r(),s({disableShortCuts:!1})}}}Zn("s",()=>{t(),e&&b(S.getValues())},[e,S,y]);function E(O){t(),O||b(S.getValues())}function k(O){x(O)}function P(O){return _?_.filter(F=>O.includes(F.model_type)).map(F=>v.jsxs("div",{onClick:()=>k(F),className:"px-2",children:[v.jsx("div",{className:Ce([F.name===y.name?"bg-muted":"hover:bg-muted","rounded-md px-2 py-2","cursor-default"]),children:v.jsx("div",{className:"text-base",children:F.name})}),v.jsx(Fn,{className:"my-1"})]},F.name)):v.jsx("div",{children:"Please download model first"})}function M(){if(C!=="success")return v.jsx(v.Fragment,{});let O=is;for(let F of _)if(y.name===F.name){O=F.model_type,O===nC&&(O=rp),O===rC&&(O=op);break}return v.jsxs("div",{className:"flex flex-col gap-4 w-[510px]",children:[v.jsxs("div",{className:"flex flex-col gap-4 rounded-md",children:[v.jsx("div",{className:"font-medium",children:"Current Model"}),v.jsx("div",{children:y.name})]}),v.jsx(Fn,{}),v.jsxs("div",{className:"space-y-4 rounded-md",children:[v.jsx("div",{className:"flex gap-1 items-center justify-start",children:v.jsx("div",{className:"font-medium",children:"Available models"})}),v.jsxs(i5,{defaultValue:O,children:[v.jsxs(Lx,{children:[v.jsx(sa,{value:is,children:"Inpaint"}),v.jsx(sa,{value:rp,children:"Stable Diffusion"}),v.jsx(sa,{value:op,children:"Stable Diffusion Inpaint"}),v.jsx(sa,{value:l0,children:"Other Diffusion"})]}),v.jsxs(og,{className:"h-[240px] w-full mt-2 outline-none border rounded-lg",children:[v.jsx(mu,{value:is,children:P([is])}),v.jsx(mu,{value:rp,children:P([rp,nC])}),v.jsx(mu,{value:op,children:P([op,rC])}),v.jsx(mu,{value:l0,children:P([l0])})]})]})]})]})}function A(){return v.jsxs("div",{className:"space-y-4 w-[510px]",children:[v.jsx(N0,{control:S.control,name:"enableManualInpainting",render:({field:O})=>v.jsxs(qp,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(Qp,{children:"Enable manual inpainting"}),v.jsx(eh,{children:"For erase model, click a button to trigger inpainting after draw mask."})]}),v.jsx(Jp,{children:v.jsx(co,{checked:O.value,onCheckedChange:O.onChange})})]})}),v.jsx(Fn,{}),v.jsx(N0,{control:S.control,name:"enableDownloadMask",render:({field:O})=>v.jsxs(qp,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(Qp,{children:"Enable download mask"}),v.jsx(eh,{children:"Also download the mask after save the inpainting result."})]}),v.jsx(Jp,{children:v.jsx(co,{checked:O.value,onCheckedChange:O.onChange})})]})}),v.jsx(Fn,{}),v.jsx(N0,{control:S.control,name:"enableAutoExtractPrompt",render:({field:O})=>v.jsxs(qp,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(Qp,{children:"Enable auto extract prompt"}),v.jsx(eh,{children:"Automatically extract prompt/negativate prompt from the image meta."})]}),v.jsx(Jp,{children:v.jsx(co,{checked:O.value,onCheckedChange:O.onChange})})]})})]})}return v.jsxs(v.Fragment,{children:[v.jsx(HX,{open:n,children:v.jsx(y3,{children:v.jsx(w3,{children:v.jsxs("div",{className:"flex flex-col justify-center items-center gap-4",children:[v.jsxs("div",{role:"status",children:[v.jsxs("svg",{"aria-hidden":"true",className:"w-8 h-8 text-gray-200 animate-spin dark:text-gray-600 fill-primary",viewBox:"0 0 100 101",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[v.jsx("path",{d:"M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z",fill:"currentColor"}),v.jsx("path",{d:"M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z",fill:"currentFill"})]}),v.jsx("span",{className:"sr-only",children:"Loading..."})]}),v.jsxs("div",{children:["Switching to ",y.name]})]})})})}),v.jsxs(Zm,{open:e,onOpenChange:E,children:[v.jsx($x,{asChild:!0,children:v.jsx(vn,{tooltip:"Settings",children:v.jsx(sV,{})})}),v.jsxs(Fd,{className:"max-w-3xl h-[600px]",onOpenAutoFocus:O=>O.preventDefault(),children:[v.jsx(jd,{children:"Settings"}),v.jsx(Fn,{}),v.jsxs("div",{className:"flex flex-row space-x-8 h-full",children:[v.jsx("div",{className:"flex flex-col space-y-1",children:QX.map(O=>v.jsx(Rn,{variant:"ghost",onClick:()=>i(O),className:Ce(o===O?"bg-muted ":"hover:bg-muted","justify-start"),children:O},O))}),v.jsx(Fn,{orientation:"vertical"}),v.jsx(wX,{...S,children:v.jsx("div",{className:"flex w-full justify-center",children:v.jsxs("form",{onSubmit:S.handleSubmit(b),children:[o===I1?M():v.jsx(v.Fragment,{}),o===x3?A():v.jsx(v.Fragment,{}),v.jsx("div",{className:"absolute right-10 bottom-6",children:v.jsx(Rn,{onClick:()=>E(!1),children:"Ok"})})]})})})]})]})]})]})}const eZ="/assets/kofi_button_black-XI_Dr2zg.png";function tZ(){return v.jsxs(Zm,{children:[v.jsx($x,{asChild:!0,children:v.jsx(vn,{tooltip:"Buy me a coffee",children:v.jsx(YU,{})})}),v.jsxs(Fd,{children:[v.jsx(jd,{children:"Buy me a coffee"}),v.jsx(mP,{className:"mb-8",children:"Hi, if you found my project is useful, please conside buy me a coffee to support my work. Thanks!"}),v.jsx("div",{className:"w-full flex items-center justify-center",children:v.jsx("a",{href:"https://ko-fi.com/Z8Z1CZJGY",target:"_blank",rel:"noreferrer",children:v.jsx("img",{src:eZ,className:"h-[32px]"})})})]})]})}const nZ=()=>{const[e,t,n,r,o,i,s,l,u,d,h,m,g,y]=bt(M=>[M.file,M.customMask,M.isInpainting,M.serverConfig,M.runMannually(),M.settings.enableUploadMask,M.settings.model,M.setFile,M.setCustomFile,M.runInpainting,M.showPrevMask,M.hidePrevMask,M.imageHeight,M.imageWidth]),{toast:x}=Td(),[_,C]=Rx(t),[S,b]=f.useState(!1),E=()=>{d()},k=()=>{h()},P=()=>{m()};return v.jsxs("header",{className:"h-[60px] px-6 py-4 absolute top-[0] flex justify-between items-center w-full z-20 border-b backdrop-filter backdrop-blur-md bg-background/70",children:[v.jsxs("div",{className:"flex items-center gap-1",children:[r.enableFileManager?v.jsx(PG,{photoWidth:512,onPhotoClick:async(M,A)=>{try{const O=await Bj(M,A);l(O)}catch(O){x({variant:"destructive",description:O.message?O.message:O.toString()});return}}}):v.jsx(v.Fragment,{}),v.jsx(c1,{disabled:n,tooltip:"Upload image",onFileUpload:M=>{l(M)},children:v.jsx(JU,{})}),v.jsxs("div",{className:Ce(["flex items-center gap-1",e&&i?"visible":"hidden"]),children:[v.jsx(c1,{disabled:n,tooltip:"Upload custom mask",onFileUpload:async M=>{let A=null;try{A=await fF(M)}catch(O){x({variant:"destructive",description:O.message?O.message:O.toString()});return}if(A.naturalHeight!==g||A.naturalWidth!==y){x({variant:"destructive",description:`The size of the mask must same as image: ${y}x${g}`});return}u(M),o||d()},children:v.jsx(ZT,{})}),t?v.jsxs(KW,{open:S,children:[v.jsx(YW,{className:"btn-primary side-panel-trigger",onMouseEnter:()=>b(!0),onMouseLeave:()=>b(!1),style:{visibility:t?"visible":"hidden",outline:"none"},onClick:()=>{},children:v.jsx(vn,{tooltip:"Run custom mask",children:v.jsx(lz,{})})}),v.jsx(PP,{children:C?v.jsx("img",{src:_.src,alt:"Custom mask"}):v.jsx(v.Fragment,{})})]}):v.jsx(v.Fragment,{})]}),e&&!s.need_prompt?v.jsx(vn,{disabled:n,tooltip:"Rerun previous mask",onClick:E,onMouseEnter:k,onMouseLeave:P,children:v.jsx(iV,{})}):v.jsx(v.Fragment,{})]}),s.need_prompt?v.jsx(yH,{}):v.jsx(v.Fragment,{}),v.jsxs("div",{className:"flex gap-1",children:[v.jsx(tZ,{}),v.jsx(OW,{}),r.disableModelSwitch?v.jsx(v.Fragment,{}):v.jsx(JX,{})]})]})};var Wr=function(e,t){return Number(e.toFixed(t))},rZ=function(e,t){return typeof e=="number"?e:t},Nt=function(e,t,n){n&&typeof n=="function"&&n(e,t)},oZ=function(e){return-Math.cos(e*Math.PI)/2+.5},iZ=function(e){return e},sZ=function(e){return e*e},aZ=function(e){return e*(2-e)},lZ=function(e){return e<.5?2*e*e:-1+(4-2*e)*e},cZ=function(e){return e*e*e},uZ=function(e){return--e*e*e+1},dZ=function(e){return e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1},fZ=function(e){return e*e*e*e},pZ=function(e){return 1- --e*e*e*e},hZ=function(e){return e<.5?8*e*e*e*e:1-8*--e*e*e*e},mZ=function(e){return e*e*e*e*e},gZ=function(e){return 1+--e*e*e*e*e},vZ=function(e){return e<.5?16*e*e*e*e*e:1+16*--e*e*e*e*e},b3={easeOut:oZ,linear:iZ,easeInQuad:sZ,easeOutQuad:aZ,easeInOutQuad:lZ,easeInCubic:cZ,easeOutCubic:uZ,easeInOutCubic:dZ,easeInQuart:fZ,easeOutQuart:pZ,easeInOutQuart:hZ,easeInQuint:mZ,easeOutQuint:gZ,easeInOutQuint:vZ},_3=function(e){typeof e=="number"&&cancelAnimationFrame(e)},Do=function(e){e.mounted&&(_3(e.animation),e.animate=!1,e.animation=null,e.velocity=null)};function S3(e,t,n,r){if(e.mounted){var o=new Date().getTime(),i=1;Do(e),e.animation=function(){if(!e.mounted)return _3(e.animation);var s=new Date().getTime()-o,l=s/n,u=b3[t],d=u(l);s>=n?(r(i),e.animation=null):e.animation&&(r(d),requestAnimationFrame(e.animation))},requestAnimationFrame(e.animation)}}function yZ(e){var t=e.scale,n=e.positionX,r=e.positionY;return!(Number.isNaN(t)||Number.isNaN(n)||Number.isNaN(r))}function Ls(e,t,n,r){var o=yZ(t);if(!(!e.mounted||!o)){var i=e.setTransformState,s=e.transformState,l=s.scale,u=s.positionX,d=s.positionY,h=t.scale-l,m=t.positionX-u,g=t.positionY-d;n===0?i(t.scale,t.positionX,t.positionY):S3(e,r,n,function(y){var x=l+h*y,_=u+m*y,C=d+g*y;i(x,_,C)})}}function wZ(e,t,n){var r=e.offsetWidth,o=e.offsetHeight,i=t.offsetWidth,s=t.offsetHeight,l=i*n,u=s*n,d=r-l,h=o-u;return{wrapperWidth:r,wrapperHeight:o,newContentWidth:l,newDiffWidth:d,newContentHeight:u,newDiffHeight:h}}var xZ=function(e,t,n,r,o,i,s){var l=e>t?n*(s?1:.5):0,u=r>o?i*(s?1:.5):0,d=e-t-l,h=l,m=r-o-u,g=u;return{minPositionX:d,maxPositionX:h,minPositionY:m,maxPositionY:g}},Xx=function(e,t){var n=e.wrapperComponent,r=e.contentComponent,o=e.setup.centerZoomedOut;if(!n||!r)throw new Error("Components are not mounted");var i=wZ(n,r,t),s=i.wrapperWidth,l=i.wrapperHeight,u=i.newContentWidth,d=i.newDiffWidth,h=i.newContentHeight,m=i.newDiffHeight,g=xZ(s,u,d,l,h,m,!!o);return g},L1=function(e,t,n,r){return r?en?Wr(n,2):Wr(e,2):Wr(e,2)},dc=function(e,t){var n=Xx(e,t);return e.bounds=n,n};function lg(e,t,n,r,o,i,s){var l=n.minPositionX,u=n.minPositionY,d=n.maxPositionX,h=n.maxPositionY,m=0,g=0;s&&(m=o,g=i);var y=L1(e,l-m,d+m,r),x=L1(t,u-g,h+g,r);return{x:y,y:x}}function cg(e,t,n,r,o,i){var s=e.transformState,l=s.scale,u=s.positionX,d=s.positionY,h=r-l;if(typeof t!="number"||typeof n!="number")return console.error("Mouse X and Y position were not provided!"),{x:u,y:d};var m=u-t*h,g=d-n*h,y=lg(m,g,o,i,0,0,null);return y}function Vd(e,t,n,r,o){var i=o?r:0,s=t-i;return!Number.isNaN(n)&&e>=n?n:!Number.isNaN(t)&&e<=s?s:e}var M2=function(e,t){var n=e.setup.panning.excluded,r=e.isInitialized,o=e.wrapperComponent,i=t.target,s=o==null?void 0:o.contains(i),l=r&&i&&s;if(!l)return!1;var u=ug(i,n);return!u},N2=function(e){var t=e.isInitialized,n=e.isPanning,r=e.setup,o=r.panning.disabled,i=t&&n&&!o;return!!i},bZ=function(e,t){var n=e.transformState,r=n.positionX,o=n.positionY;e.isPanning=!0;var i=t.clientX,s=t.clientY;e.startCoords={x:i-r,y:s-o}},_Z=function(e,t){var n=t.touches,r=e.transformState,o=r.positionX,i=r.positionY;e.isPanning=!0;var s=n.length===1;if(s){var l=n[0].clientX,u=n[0].clientY;e.startCoords={x:l-o,y:u-i}}};function SZ(e){var t=e.transformState,n=t.positionX,r=t.positionY,o=t.scale,i=e.setup,s=i.disabled,l=i.limitToBounds,u=i.centerZoomedOut,d=e.wrapperComponent;if(!(s||!d||!e.bounds)){var h=e.bounds,m=h.maxPositionX,g=h.minPositionX,y=h.maxPositionY,x=h.minPositionY,_=n>m||ny||rm?d.offsetWidth:e.setup.minPositionX||0,b=r>y?d.offsetHeight:e.setup.minPositionY||0,E=cg(e,S,b,o,e.bounds,l||u),k=E.x,P=E.y;return{scale:o,positionX:_?k:n,positionY:C?P:r}}}function EZ(e,t,n,r,o){var i=e.setup.limitToBounds,s=e.wrapperComponent,l=e.bounds,u=e.transformState,d=u.scale,h=u.positionX,m=u.positionY;if(!(s===null||l===null||t===h&&n===m)){var g=lg(t,n,l,i,r,o,s),y=g.x,x=g.y;e.setTransformState(d,y,x)}}var CZ=function(e,t,n){var r=e.startCoords,o=e.transformState,i=e.setup.panning,s=i.lockAxisX,l=i.lockAxisY,u=o.positionX,d=o.positionY;if(!r)return{x:u,y:d};var h=t-r.x,m=n-r.y,g=s?u:h,y=l?d:m;return{x:g,y}},rm=function(e,t){var n=e.setup,r=e.transformState,o=r.scale,i=n.minScale,s=n.disablePadding;return t>0&&o>=i&&!s?t:0},$Z=function(e){var t=e.mounted,n=e.setup,r=n.disabled,o=n.velocityAnimation,i=e.transformState.scale,s=o.disabled,l=!s||i>1||!r||t;return!!l},kZ=function(e){var t=e.mounted,n=e.velocity,r=e.bounds,o=e.setup,i=o.disabled,s=o.velocityAnimation,l=e.transformState.scale,u=s.disabled,d=!u||l>1||!i||t;return!(!d||!n||!r)};function RZ(e,t){var n=e.setup.velocityAnimation,r=n.equalToMove,o=n.animationTime,i=n.sensitivity;return r?o*t*i:o}function D2(e,t,n,r,o,i,s,l,u,d){if(o){if(t>s&&n>s){var h=s+(e-s)*d;return h>u?u:hi?i:h}}return r?t:L1(e,i,s,o)}function TZ(e,t){var n=1;return t?Math.min(n,e.offsetWidth/window.innerWidth):n}function PZ(e,t){var n=$Z(e);if(n){var r=e.lastMousePosition,o=e.velocityTime,i=e.setup,s=e.wrapperComponent,l=i.velocityAnimation.equalToMove,u=Date.now();if(r&&o&&s){var d=TZ(s,l),h=t.x-r.x,m=t.y-r.y,g=h/d,y=m/d,x=u-o,_=h*h+m*m,C=Math.sqrt(_)/x;e.velocity={velocityX:g,velocityY:y,total:C}}e.lastMousePosition=t,e.velocityTime=u}}function AZ(e){var t=e.velocity,n=e.bounds,r=e.setup,o=e.wrapperComponent,i=kZ(e);if(!(!i||!t||!n||!o)){var s=t.velocityX,l=t.velocityY,u=t.total,d=n.maxPositionX,h=n.minPositionX,m=n.maxPositionY,g=n.minPositionY,y=r.limitToBounds,x=r.alignmentAnimation,_=r.zoomAnimation,C=r.panning,S=C.lockAxisY,b=C.lockAxisX,E=_.animationType,k=x.sizeX,P=x.sizeY,M=x.velocityAlignmentTime,A=M,O=RZ(e,u),F=Math.max(O,A),V=rm(e,k),J=rm(e,P),G=V*o.offsetWidth/100,ae=J*o.offsetHeight/100,U=d+G,te=h-G,L=m+ae,ie=g-ae,K=e.transformState,Q=new Date().getTime();S3(e,E,F,function(W){var le=e.transformState,ge=le.scale,Ve=le.positionX,Ue=le.positionY,We=new Date().getTime()-Q,Me=We/A,fe=b3[x.animationType],xe=1-fe(Math.min(1,Me)),$e=1-W,Ae=Ve+s*$e,Oe=Ue+l*$e,je=D2(Ae,K.positionX,Ve,b,y,h,d,te,U,xe),Ot=D2(Oe,K.positionY,Ue,S,y,g,m,ie,L,xe);(Ve!==Ae||Ue!==Oe)&&e.setTransformState(ge,je,Ot)})}}function I2(e,t){var n=e.transformState.scale;Do(e),dc(e,n),window.TouchEvent!==void 0&&t instanceof TouchEvent?_Z(e,t):bZ(e,t)}function E3(e){var t=e.transformState.scale,n=e.setup,r=n.minScale,o=n.alignmentAnimation,i=o.disabled,s=o.sizeX,l=o.sizeY,u=o.animationTime,d=o.animationType,h=i||t.1&&m;g?AZ(e):E3(e)}}function Zx(e,t,n,r){var o=e.setup,i=o.minScale,s=o.maxScale,l=o.limitToBounds,u=Vd(Wr(t,2),i,s,0,!1),d=dc(e,u),h=cg(e,n,r,u,d,l),m=h.x,g=h.y;return{scale:u,positionX:m,positionY:g}}function C3(e,t,n){var r=e.transformState.scale,o=e.wrapperComponent,i=e.setup,s=i.minScale,l=i.limitToBounds,u=i.zoomAnimation,d=u.disabled,h=u.animationTime,m=u.animationType,g=d||r>=s;if((r>=1||l)&&E3(e),!(g||!o||!e.mounted)){var y=t||o.offsetWidth/2,x=n||o.offsetHeight/2,_=Zx(e,s,y,x);_&&Ls(e,_,h,m)}}var _s=function(){return _s=Object.assign||function(t){for(var n,r=1,o=arguments.length;rs||Math.sign(n.deltaY)!==Math.sign(t.deltaY)||n.deltaY>0&&n.deltaYt.deltaY||Math.sign(n.deltaY)!==Math.sign(t.deltaY):!1},XZ=function(e,t){var n=e.setup.pinch,r=n.disabled,o=n.excluded,i=e.isInitialized,s=t.target,l=i&&!r&&s;if(!l)return!1;var u=ug(s,o);return!u},ZZ=function(e){var t=e.setup.pinch.disabled,n=e.isInitialized,r=e.pinchStartDistance,o=n&&!t&&r;return!!o},qZ=function(e,t,n){var r=n.getBoundingClientRect(),o=e.touches,i=Wr(o[0].clientX-r.left,5),s=Wr(o[0].clientY-r.top,5),l=Wr(o[1].clientX-r.left,5),u=Wr(o[1].clientY-r.top,5);return{x:(i+l)/2/t,y:(s+u)/2/t}},O3=function(e){return Math.sqrt(Math.pow(e.touches[0].pageX-e.touches[1].pageX,2)+Math.pow(e.touches[0].pageY-e.touches[1].pageY,2))},QZ=function(e,t){var n=e.pinchStartScale,r=e.pinchStartDistance,o=e.setup,i=o.maxScale,s=o.minScale,l=o.zoomAnimation,u=o.disablePadding,d=l.size,h=l.disabled;if(!n||r===null||!t)throw new Error("Pinch touches distance was not provided");if(t<0)return e.transformState.scale;var m=t/r,g=m*n;return Vd(Wr(g,2),s,i,d,!h&&!u)},JZ=160,eq=100,tq=function(e,t){var n=e.props,r=n.onWheelStart,o=n.onZoomStart;e.wheelStopEventTimer||(Do(e),Nt(St(e),t,r),Nt(St(e),t,o))},nq=function(e,t){var n=e.props,r=n.onWheel,o=n.onZoom,i=e.contentComponent,s=e.setup,l=e.transformState,u=l.scale,d=s.limitToBounds,h=s.centerZoomedOut,m=s.zoomAnimation,g=s.wheel,y=s.disablePadding,x=s.smooth,_=m.size,C=m.disabled,S=g.step,b=g.smoothStep;if(!i)throw new Error("Component not mounted");t.preventDefault(),t.stopPropagation();var E=KZ(t,null),k=x?b*Math.abs(t.deltaY):S,P=YZ(e,E,k,!t.ctrlKey);if(u!==P){var M=dc(e,P),A=A3(t,i,u),O=C||_===0||h||y,F=d&&O,V=cg(e,A.x,A.y,P,M,F),J=V.x,G=V.y;e.previousWheelEvent=t,e.setTransformState(P,J,G),Nt(St(e),t,r),Nt(St(e),t,o)}},rq=function(e,t){var n=e.props,r=n.onWheelStop,o=n.onZoomStop;j1(e.wheelAnimationTimer),e.wheelAnimationTimer=setTimeout(function(){e.mounted&&(C3(e,t.x,t.y),e.wheelAnimationTimer=null)},eq);var i=GZ(e,t);i&&(j1(e.wheelStopEventTimer),e.wheelStopEventTimer=setTimeout(function(){e.mounted&&(e.wheelStopEventTimer=null,Nt(St(e),t,r),Nt(St(e),t,o))},JZ))},oq=function(e,t){var n=O3(t);e.pinchStartDistance=n,e.lastDistance=n,e.pinchStartScale=e.transformState.scale,e.isPanning=!1,Do(e)},iq=function(e,t){var n=e.contentComponent,r=e.pinchStartDistance,o=e.transformState.scale,i=e.setup,s=i.limitToBounds,l=i.centerZoomedOut,u=i.zoomAnimation,d=u.disabled,h=u.size;if(!(r===null||!n)){var m=qZ(t,o,n);if(!(!Number.isFinite(m.x)||!Number.isFinite(m.y))){var g=O3(t),y=QZ(e,g);if(y!==o){var x=dc(e,y),_=d||h===0||l,C=s&&_,S=cg(e,m.x,m.y,y,x,C),b=S.x,E=S.y;e.pinchMidpoint=m,e.lastDistance=g,e.setTransformState(y,b,E)}}}},sq=function(e){var t=e.pinchMidpoint;e.velocity=null,e.lastDistance=null,e.pinchMidpoint=null,e.pinchStartScale=null,e.pinchStartDistance=null,C3(e,t==null?void 0:t.x,t==null?void 0:t.y)},M3=function(e,t){var n=e.props.onZoomStop,r=e.setup.doubleClick.animationTime;j1(e.doubleClickStopEventTimer),e.doubleClickStopEventTimer=setTimeout(function(){e.doubleClickStopEventTimer=null,Nt(St(e),t,n)},r)},aq=function(e,t){var n=e.props,r=n.onZoomStart,o=n.onZoom,i=e.setup.doubleClick,s=i.animationTime,l=i.animationType;Nt(St(e),t,r),T3(e,s,l,function(){return Nt(St(e),t,o)}),M3(e,t)};function lq(e,t){var n=e.setup,r=e.doubleClickStopEventTimer,o=e.transformState,i=e.contentComponent,s=o.scale,l=e.props,u=l.onZoomStart,d=l.onZoom,h=n.doubleClick,m=h.disabled,g=h.mode,y=h.step,x=h.animationTime,_=h.animationType;if(!m&&!r){if(g==="reset")return aq(e,t);if(!i)return console.error("No ContentComponent found");var C=g==="zoomOut"?-1:1,S=k3(e,C,y);if(s!==S){Nt(St(e),t,u);var b=A3(t,i,s),E=Zx(e,S,b.x,b.y);if(!E)return console.error("Error during zoom event. New transformation state was not calculated.");Nt(St(e),t,d),Ls(e,E,x,_),M3(e,t)}}}var cq=function(e,t){var n=e.isInitialized,r=e.setup,o=e.wrapperComponent,i=r.doubleClick,s=i.disabled,l=i.excluded,u=t.target,d=o==null?void 0:o.contains(u),h=n&&u&&d&&!s;if(!h)return!1;var m=ug(u,l);return!m},uq=function(){function e(t){var n=this;this.mounted=!0,this.onChangeCallbacks=new Set,this.onInitCallbacks=new Set,this.wrapperComponent=null,this.contentComponent=null,this.isInitialized=!1,this.bounds=null,this.previousWheelEvent=null,this.wheelStopEventTimer=null,this.wheelAnimationTimer=null,this.isPanning=!1,this.startCoords=null,this.lastTouch=null,this.distance=null,this.lastDistance=null,this.pinchStartDistance=null,this.pinchStartScale=null,this.pinchMidpoint=null,this.doubleClickStopEventTimer=null,this.velocity=null,this.velocityTime=null,this.lastMousePosition=null,this.animate=!1,this.animation=null,this.maxBounds=null,this.pressedKeys={},this.mount=function(){n.initializeWindowEvents()},this.unmount=function(){n.cleanupWindowEvents()},this.update=function(r){dc(n,n.transformState.scale),n.setup=j2(r)},this.initializeWindowEvents=function(){var r,o=I0(),i=(r=n.wrapperComponent)===null||r===void 0?void 0:r.ownerDocument,s=i==null?void 0:i.defaultView;s==null||s.addEventListener("mousedown",n.onPanningStart,o),s==null||s.addEventListener("mousemove",n.onPanning,o),s==null||s.addEventListener("mouseup",n.onPanningStop,o),i==null||i.addEventListener("mouseleave",n.clearPanning,o),s==null||s.addEventListener("keyup",n.setKeyUnPressed,o),s==null||s.addEventListener("keydown",n.setKeyPressed,o)},this.cleanupWindowEvents=function(){var r,o,i=I0(),s=(r=n.wrapperComponent)===null||r===void 0?void 0:r.ownerDocument,l=s==null?void 0:s.defaultView;l==null||l.removeEventListener("mousedown",n.onPanningStart,i),l==null||l.removeEventListener("mousemove",n.onPanning,i),l==null||l.removeEventListener("mouseup",n.onPanningStop,i),s==null||s.removeEventListener("mouseleave",n.clearPanning,i),l==null||l.removeEventListener("keyup",n.setKeyUnPressed,i),l==null||l.removeEventListener("keydown",n.setKeyPressed,i),document.removeEventListener("mouseleave",n.clearPanning,i),Do(n),(o=n.observer)===null||o===void 0||o.disconnect()},this.handleInitializeWrapperEvents=function(r){var o=I0();r.addEventListener("wheel",n.onWheelZoom,o),r.addEventListener("dblclick",n.onDoubleClick,o),r.addEventListener("touchstart",n.onTouchPanningStart,o),r.addEventListener("touchmove",n.onTouchPanning,o),r.addEventListener("touchend",n.onTouchPanningStop,o)},this.handleInitialize=function(r){var o=n.setup.centerOnInit;n.applyTransformation(),n.onInitCallbacks.forEach(function(i){return i(St(n))}),o&&(n.setCenter(),n.observer=new ResizeObserver(function(){var i;n.onInitCallbacks.forEach(function(s){return s(St(n))}),n.setCenter(),(i=n.observer)===null||i===void 0||i.disconnect()}),n.observer.observe(r))},this.onWheelZoom=function(r){var o=n.setup.disabled;if(!o){var i=WZ(n,r);if(i){var s=n.isPressingKeys(n.setup.wheel.activationKeys);s&&(tq(n,r),nq(n,r),rq(n,r))}}},this.onPanningStart=function(r){var o=n.setup.disabled,i=n.props.onPanningStart;if(!o){var s=M2(n,r);if(s){var l=n.isPressingKeys(n.setup.panning.activationKeys);l&&(r.button===0&&!n.setup.panning.allowLeftClickPan||r.button===1&&!n.setup.panning.allowMiddleClickPan||r.button===2&&!n.setup.panning.allowRightClickPan||(r.preventDefault(),r.stopPropagation(),Do(n),I2(n,r),Nt(St(n),r,i)))}}},this.onPanning=function(r){var o=n.setup.disabled,i=n.props.onPanning;if(!o){var s=N2(n);if(s){var l=n.isPressingKeys(n.setup.panning.activationKeys);l&&(r.preventDefault(),r.stopPropagation(),L2(n,r.clientX,r.clientY),Nt(St(n),r,i))}}},this.onPanningStop=function(r){var o=n.props.onPanningStop;n.isPanning&&(OZ(n),Nt(St(n),r,o))},this.onPinchStart=function(r){var o=n.setup.disabled,i=n.props,s=i.onPinchingStart,l=i.onZoomStart;if(!o){var u=XZ(n,r);u&&(oq(n,r),Do(n),Nt(St(n),r,s),Nt(St(n),r,l))}},this.onPinch=function(r){var o=n.setup.disabled,i=n.props,s=i.onPinching,l=i.onZoom;if(!o){var u=ZZ(n);u&&(r.preventDefault(),r.stopPropagation(),iq(n,r),Nt(St(n),r,s),Nt(St(n),r,l))}},this.onPinchStop=function(r){var o=n.props,i=o.onPinchingStop,s=o.onZoomStop;n.pinchStartScale&&(sq(n),Nt(St(n),r,i),Nt(St(n),r,s))},this.onTouchPanningStart=function(r){var o=n.setup.disabled,i=n.props.onPanningStart;if(!o){var s=M2(n,r);if(s){var l=n.lastTouch&&+new Date-n.lastTouch<200;if(l&&r.touches.length===1)n.onDoubleClick(r);else{n.lastTouch=+new Date,Do(n);var u=r.touches,d=u.length===1,h=u.length===2;d&&(Do(n),I2(n,r),Nt(St(n),r,i)),h&&n.onPinchStart(r)}}}},this.onTouchPanning=function(r){var o=n.setup.disabled,i=n.props.onPanning;if(n.isPanning&&r.touches.length===1){if(o)return;var s=N2(n);if(!s)return;r.preventDefault(),r.stopPropagation();var l=r.touches[0];L2(n,l.clientX,l.clientY),Nt(St(n),r,i)}else r.touches.length>1&&n.onPinch(r)},this.onTouchPanningStop=function(r){n.onPanningStop(r),n.onPinchStop(r)},this.onDoubleClick=function(r){var o=n.setup.disabled;if(!o){var i=cq(n,r);i&&lq(n,r)}},this.clearPanning=function(r){n.isPanning&&n.onPanningStop(r)},this.setKeyPressed=function(r){n.pressedKeys[r.key]=!0},this.setKeyUnPressed=function(r){n.pressedKeys[r.key]=!1},this.isPressingKeys=function(r){return r.length?!!r.find(function(o){return n.pressedKeys[o]}):!0},this.setTransformState=function(r,o,i){var s=n.props.onTransformed;if(!Number.isNaN(r)&&!Number.isNaN(o)&&!Number.isNaN(i)){r!==n.transformState.scale&&(n.transformState.previousScale=n.transformState.scale,n.transformState.scale=r),n.transformState.positionX=o,n.transformState.positionY=i,n.applyTransformation();var l=St(n);n.onChangeCallbacks.forEach(function(u){return u(l)}),Nt(l,{scale:r,positionX:o,positionY:i},s)}else console.error("Detected NaN set state values")},this.setCenter=function(){if(n.wrapperComponent&&n.contentComponent){var r=P3(n.transformState.scale,n.wrapperComponent,n.contentComponent);n.setTransformState(r.scale,r.positionX,r.positionY)}},this.handleTransformStyles=function(r,o,i){return n.props.customTransform?n.props.customTransform(r,o,i):UZ(r,o,i)},this.applyTransformation=function(){if(!(!n.mounted||!n.contentComponent)){var r=n.transformState,o=r.scale,i=r.positionX,s=r.positionY,l=n.handleTransformStyles(i,s,o);n.contentComponent.style.transform=l}},this.getContext=function(){return St(n)},this.onChange=function(r){return n.onChangeCallbacks.has(r)||n.onChangeCallbacks.add(r),function(){n.onChangeCallbacks.delete(r)}},this.onInit=function(r){return n.onInitCallbacks.has(r)||n.onInitCallbacks.add(r),function(){n.onInitCallbacks.delete(r)}},this.init=function(r,o){n.cleanupWindowEvents(),n.wrapperComponent=r,n.contentComponent=o,dc(n,n.transformState.scale),n.handleInitializeWrapperEvents(r),n.handleInitialize(o),n.initializeWindowEvents(),n.isInitialized=!0;var i=St(n);Nt(i,void 0,n.props.onInit)},this.props=t,this.setup=j2(this.props),this.transformState=$3(this.props)}return e}(),qx=Fe.createContext(null),dq=function(e,t){return typeof e=="function"?e(t):e},fq=Fe.forwardRef(function(e,t){var n=f.useRef(new uq(e)).current,r=dq(e.children,F1(n));return f.useImperativeHandle(t,function(){return F1(n)},[n]),f.useEffect(function(){n.update(e)},[n,e]),Fe.createElement(qx.Provider,{value:n},r)});Fe.forwardRef(function(e,t){var n=f.useRef(null),r=f.useContext(qx);return f.useEffect(function(){return r.onChange(function(o){if(n.current){var i=0,s=0;n.current.style.transform=r.handleTransformStyles(i,s,1/o.instance.transformState.scale)}})},[r]),Fe.createElement("div",_s({},e,{ref:VZ([n,t])}))});function pq(e,t){t===void 0&&(t={});var n=t.insertAt;if(!(!e||typeof document>"u")){var r=document.head||document.getElementsByTagName("head")[0],o=document.createElement("style");o.type="text/css",n==="top"&&r.firstChild?r.insertBefore(o,r.firstChild):r.appendChild(o),o.styleSheet?o.styleSheet.cssText=e:o.appendChild(document.createTextNode(e))}}var hq=`.transform-component-module_wrapper__SPB86 { + position: relative; + width: -moz-fit-content; + width: fit-content; + height: -moz-fit-content; + height: fit-content; + overflow: hidden; + -webkit-touch-callout: none; /* iOS Safari */ + -webkit-user-select: none; /* Safari */ + -khtml-user-select: none; /* Konqueror HTML */ + -moz-user-select: none; /* Firefox */ + -ms-user-select: none; /* Internet Explorer/Edge */ + user-select: none; + margin: 0; + padding: 0; +} +.transform-component-module_content__FBWxo { + display: flex; + flex-wrap: wrap; + width: -moz-fit-content; + width: fit-content; + height: -moz-fit-content; + height: fit-content; + margin: 0; + padding: 0; + transform-origin: 0% 0%; +} +.transform-component-module_content__FBWxo img { + pointer-events: none; +} +`,z2={wrapper:"transform-component-module_wrapper__SPB86",content:"transform-component-module_content__FBWxo"};pq(hq);var mq=function(e){var t=e.children,n=e.wrapperClass,r=n===void 0?"":n,o=e.contentClass,i=o===void 0?"":o,s=e.wrapperStyle,l=e.contentStyle,u=e.wrapperProps,d=u===void 0?{}:u,h=e.contentProps,m=h===void 0?{}:h,g=f.useContext(qx),y=g.init,x=g.cleanupWindowEvents,_=f.useRef(null),C=f.useRef(null);return f.useEffect(function(){var S=_.current,b=C.current;return S!==null&&b!==null&&y&&(y==null||y(S,b)),function(){x==null||x()}},[]),Fe.createElement("div",_s({},d,{ref:_,className:"react-transform-wrapper ".concat(z2.wrapper," ").concat(r),style:s}),Fe.createElement("div",_s({},m,{ref:C,className:"react-transform-component ".concat(z2.content," ").concat(i),style:l}),t))};const N3=["PageUp","PageDown"],D3=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],I3={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},Wd="Slider",[z1,gq,vq]=zd(Wd),[L3,Cte]=An(Wd,[vq]),[yq,dg]=L3(Wd),wq=f.forwardRef((e,t)=>{const{name:n,min:r=0,max:o=100,step:i=1,orientation:s="horizontal",disabled:l=!1,minStepsBetweenThumbs:u=0,defaultValue:d=[r],value:h,onValueChange:m=()=>{},onValueCommit:g=()=>{},inverted:y=!1,...x}=e,[_,C]=f.useState(null),S=Be(t,U=>C(U)),b=f.useRef(new Set),E=f.useRef(0),k=s==="horizontal",P=_?!!_.closest("form"):!0,M=k?xq:bq,[A=[],O]=Zr({prop:h,defaultProp:d,onChange:U=>{var te;(te=[...b.current][E.current])===null||te===void 0||te.focus(),m(U)}}),F=f.useRef(A);function V(U){const te=Pq(A,U);ae(U,te)}function J(U){ae(U,E.current)}function G(){const U=F.current[E.current];A[E.current]!==U&&g(A)}function ae(U,te,{commit:L}={commit:!1}){const ie=Nq(i),K=Dq(Math.round((U-r)/i)*i+r,ie),Q=id(K,[r,o]);O((W=[])=>{const le=Rq(W,Q,te);if(Mq(le,u*i)){E.current=le.indexOf(Q);const ge=String(le)!==String(W);return ge&&L&&g(le),ge?le:W}else return W})}return f.createElement(yq,{scope:e.__scopeSlider,disabled:l,min:r,max:o,valueIndexToChangeRef:E,thumbs:b.current,values:A,orientation:s},f.createElement(z1.Provider,{scope:e.__scopeSlider},f.createElement(z1.Slot,{scope:e.__scopeSlider},f.createElement(M,Y({"aria-disabled":l,"data-disabled":l?"":void 0},x,{ref:S,onPointerDown:ue(x.onPointerDown,()=>{l||(F.current=A)}),min:r,max:o,inverted:y,onSlideStart:l?void 0:V,onSlideMove:l?void 0:J,onSlideEnd:l?void 0:G,onHomeKeyDown:()=>!l&&ae(r,0,{commit:!0}),onEndKeyDown:()=>!l&&ae(o,A.length-1,{commit:!0}),onStepKeyDown:({event:U,direction:te})=>{if(!l){const K=N3.includes(U.key)||U.shiftKey&&D3.includes(U.key)?10:1,Q=E.current,W=A[Q],le=i*K*te;ae(W+le,Q,{commit:!0})}}})))),P&&A.map((U,te)=>f.createElement(kq,{key:te,name:n?n+(A.length>1?"[]":""):void 0,value:U})))}),[F3,j3]=L3(Wd,{startEdge:"left",endEdge:"right",size:"width",direction:1}),xq=f.forwardRef((e,t)=>{const{min:n,max:r,dir:o,inverted:i,onSlideStart:s,onSlideMove:l,onSlideEnd:u,onStepKeyDown:d,...h}=e,[m,g]=f.useState(null),y=Be(t,E=>g(E)),x=f.useRef(),_=Sc(o),C=_==="ltr",S=C&&!i||!C&&i;function b(E){const k=x.current||m.getBoundingClientRect(),P=[0,k.width],A=Qx(P,S?[n,r]:[r,n]);return x.current=k,A(E-k.left)}return f.createElement(F3,{scope:e.__scopeSlider,startEdge:S?"left":"right",endEdge:S?"right":"left",direction:S?1:-1,size:"width"},f.createElement(z3,Y({dir:_,"data-orientation":"horizontal"},h,{ref:y,style:{...h.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:E=>{const k=b(E.clientX);s==null||s(k)},onSlideMove:E=>{const k=b(E.clientX);l==null||l(k)},onSlideEnd:()=>{x.current=void 0,u==null||u()},onStepKeyDown:E=>{const P=I3[S?"from-left":"from-right"].includes(E.key);d==null||d({event:E,direction:P?-1:1})}})))}),bq=f.forwardRef((e,t)=>{const{min:n,max:r,inverted:o,onSlideStart:i,onSlideMove:s,onSlideEnd:l,onStepKeyDown:u,...d}=e,h=f.useRef(null),m=Be(t,h),g=f.useRef(),y=!o;function x(_){const C=g.current||h.current.getBoundingClientRect(),S=[0,C.height],E=Qx(S,y?[r,n]:[n,r]);return g.current=C,E(_-C.top)}return f.createElement(F3,{scope:e.__scopeSlider,startEdge:y?"bottom":"top",endEdge:y?"top":"bottom",size:"height",direction:y?1:-1},f.createElement(z3,Y({"data-orientation":"vertical"},d,{ref:m,style:{...d.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:_=>{const C=x(_.clientY);i==null||i(C)},onSlideMove:_=>{const C=x(_.clientY);s==null||s(C)},onSlideEnd:()=>{g.current=void 0,l==null||l()},onStepKeyDown:_=>{const S=I3[y?"from-bottom":"from-top"].includes(_.key);u==null||u({event:_,direction:S?-1:1})}})))}),z3=f.forwardRef((e,t)=>{const{__scopeSlider:n,onSlideStart:r,onSlideMove:o,onSlideEnd:i,onHomeKeyDown:s,onEndKeyDown:l,onStepKeyDown:u,...d}=e,h=dg(Wd,n);return f.createElement(Pe.span,Y({},d,{ref:t,onKeyDown:ue(e.onKeyDown,m=>{m.key==="Home"?(s(m),m.preventDefault()):m.key==="End"?(l(m),m.preventDefault()):N3.concat(D3).includes(m.key)&&(u(m),m.preventDefault())}),onPointerDown:ue(e.onPointerDown,m=>{const g=m.target;g.setPointerCapture(m.pointerId),m.preventDefault(),h.thumbs.has(g)?g.focus():r(m)}),onPointerMove:ue(e.onPointerMove,m=>{m.target.hasPointerCapture(m.pointerId)&&o(m)}),onPointerUp:ue(e.onPointerUp,m=>{const g=m.target;g.hasPointerCapture(m.pointerId)&&(g.releasePointerCapture(m.pointerId),i(m))})}))}),_q="SliderTrack",Sq=f.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,o=dg(_q,n);return f.createElement(Pe.span,Y({"data-disabled":o.disabled?"":void 0,"data-orientation":o.orientation},r,{ref:t}))}),B2="SliderRange",Eq=f.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,o=dg(B2,n),i=j3(B2,n),s=f.useRef(null),l=Be(t,s),u=o.values.length,d=o.values.map(g=>B3(g,o.min,o.max)),h=u>1?Math.min(...d):0,m=100-Math.max(...d);return f.createElement(Pe.span,Y({"data-orientation":o.orientation,"data-disabled":o.disabled?"":void 0},r,{ref:l,style:{...e.style,[i.startEdge]:h+"%",[i.endEdge]:m+"%"}}))}),U2="SliderThumb",Cq=f.forwardRef((e,t)=>{const n=gq(e.__scopeSlider),[r,o]=f.useState(null),i=Be(t,l=>o(l)),s=f.useMemo(()=>r?n().findIndex(l=>l.ref.current===r):-1,[n,r]);return f.createElement($q,Y({},e,{ref:i,index:s}))}),$q=f.forwardRef((e,t)=>{const{__scopeSlider:n,index:r,...o}=e,i=dg(U2,n),s=j3(U2,n),[l,u]=f.useState(null),d=Be(t,C=>u(C)),h=gx(l),m=i.values[r],g=m===void 0?0:B3(m,i.min,i.max),y=Tq(r,i.values.length),x=h==null?void 0:h[s.size],_=x?Aq(x,g,s.direction):0;return f.useEffect(()=>{if(l)return i.thumbs.add(l),()=>{i.thumbs.delete(l)}},[l,i.thumbs]),f.createElement("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[s.startEdge]:`calc(${g}% + ${_}px)`}},f.createElement(z1.ItemSlot,{scope:e.__scopeSlider},f.createElement(Pe.span,Y({role:"slider","aria-label":e["aria-label"]||y,"aria-valuemin":i.min,"aria-valuenow":m,"aria-valuemax":i.max,"aria-orientation":i.orientation,"data-orientation":i.orientation,"data-disabled":i.disabled?"":void 0,tabIndex:i.disabled?void 0:0},o,{ref:d,style:m===void 0?{display:"none"}:e.style,onFocus:ue(e.onFocus,()=>{i.valueIndexToChangeRef.current=r})}))))}),kq=e=>{const{value:t,...n}=e,r=f.useRef(null),o=Fx(t);return f.useEffect(()=>{const i=r.current,s=window.HTMLInputElement.prototype,u=Object.getOwnPropertyDescriptor(s,"value").set;if(o!==t&&u){const d=new Event("input",{bubbles:!0});u.call(i,t),i.dispatchEvent(d)}},[o,t]),f.createElement("input",Y({style:{display:"none"}},n,{ref:r,defaultValue:t}))};function Rq(e=[],t,n){const r=[...e];return r[n]=t,r.sort((o,i)=>o-i)}function B3(e,t,n){const i=100/(n-t)*(e-t);return id(i,[0,100])}function Tq(e,t){return t>2?`Value ${e+1} of ${t}`:t===2?["Minimum","Maximum"][e]:void 0}function Pq(e,t){if(e.length===1)return 0;const n=e.map(o=>Math.abs(o-t)),r=Math.min(...n);return n.indexOf(r)}function Aq(e,t,n){const r=e/2,i=Qx([0,50],[0,r]);return(r-i(t)*n)*n}function Oq(e){return e.slice(0,-1).map((t,n)=>e[n+1]-t)}function Mq(e,t){if(t>0){const n=Oq(e);return Math.min(...n)>=t}return!0}function Qx(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 Nq(e){return(String(e).split(".")[1]||"").length}function Dq(e,t){const n=Math.pow(10,t);return Math.round(e*n)/n}const U3=wq,Iq=Sq,Lq=Eq,Fq=Cq,uo=f.forwardRef(({className:e,...t},n)=>v.jsxs(U3,{ref:n,className:Ce("relative flex w-full touch-none select-none items-center",e),tabIndex:-1,...t,children:[v.jsx(Iq,{className:"relative h-1.5 w-full grow overflow-hidden rounded-full bg-primary/20 data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50",children:v.jsx(Lq,{className:"absolute h-full bg-primary data-[disabled]:cursor-not-allowed "})}),v.jsx(Fq,{tabIndex:-1,className:"block h-4 w-4 rounded-full border border-primary/60 bg-background shadow transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring data-[disabled]:cursor-not-allowed"})]}));uo.displayName=U3.displayName;const tl={capture:!0,passive:!1},jq=2,V2=(e,t,n,r,o,i)=>{if(e!==n&&t===r){if(e<0)return[0,r];if(e+t>i)return[i-r,r]}else{if(ti)return[e,i-e]}return[e,t]},zq=e=>{const{minHeight:t,minWidth:n,maxHeight:r,maxWidth:o,scale:i,show:s}=e,[l,u,d,h,{x:m,y:g,width:y,height:x},_,C,S,b,E,k]=bt(W=>[W.imageWidth,W.imageHeight,W.isInpainting,W.isSD(),W.cropperState,W.setCropperX,W.setCropperY,W.setCropperWidth,W.setCropperHeight,W.isCropperExtenderResizing,W.setIsCropperExtenderResizing]),[P,M]=f.useState(!1);f.useEffect(()=>{_(Math.round((o-512)/2)),C(Math.round((r-512)/2))},[r,o,l,u]);const[A,O]=f.useState({initX:0,initY:0,initHeight:0,initWidth:0,startResizeX:0,startResizeY:0,ord:"top"}),F=()=>{},V=(W,le)=>V2(W,le,m,y,n,o),J=(W,le)=>V2(W,le,g,x,t,r),G=W=>{if(d)return;const le=W.clientX,ge=W.clientY,Ve=Math.round((ge-A.startResizeY)/i),Ue=Math.round((le-A.startResizeX)/i),We=()=>{const $e=A.initHeight-Ve,Ae=A.initY+Ve,[Oe,je]=J(Ae,$e);b(je),C(Oe)},Me=()=>{const $e=A.initHeight+Ve,[Ae,Oe]=J(A.initY,$e);b(Oe),C(Ae)},fe=()=>{const $e=A.initWidth-Ue,Ae=A.initX+Ue,[Oe,je]=V(Ae,$e);S(je),_(Oe)},xe=()=>{const $e=A.initWidth+Ue,[Ae,Oe]=V(A.initX,$e);S(Oe),_(Ae)};if(E)switch(A.ord){case"topleft":{We(),fe();break}case"topright":{We(),xe();break}case"bottomleft":{Me(),fe();break}case"bottomright":{Me(),xe();break}case"top":{We();break}case"right":{xe();break}case"bottom":{Me();break}case"left":{fe();break}}if(P){const $e=A.initX+Ue,Ae=A.initY+Ve,[Oe,je]=V($e,A.initWidth),[Ot,ct]=J(Ae,A.initHeight);S(je),b(ct),_(Oe),C(Ot)}},ae=()=>{E&&k(!1),P&&M(!1)};f.useEffect(()=>{if(E||P)return document.addEventListener("pointermove",G,tl),document.addEventListener("pointerup",ae,tl),document.addEventListener("pointercancel",ae,tl),()=>{document.removeEventListener("pointermove",G,tl),document.removeEventListener("pointerup",ae,tl),document.removeEventListener("pointercancel",ae,tl)}},[E,P,y,x,A]);const U=W=>{const{ord:le}=W.target.dataset;le&&(k(!0),O({initX:m,initY:g,initHeight:x,initWidth:y,startResizeX:W.clientX,startResizeY:W.clientY,ord:le}))},te=(W,le,ge)=>{const We="w-[12px] h-[12px] z-[4] absolute content-[''] block border-2 border-primary borde pointer-events-auto hover:bg-primary";let Me="0",fe="0",xe=ge,$e="-6px";return ge===""&&($e="50%",le==="left"||le==="right"?(xe="top",fe="-50%"):(xe="left",Me="-50%")),v.jsx("div",{className:Ce(We,W),style:{[le]:-6,[xe]:$e,transform:`translate(${Me}, ${fe}) scale(${1/i})`},"data-ord":le+ge,"aria-label":le+ge,tabIndex:-1,role:"button"})},L=()=>v.jsxs("div",{onFocus:F,onPointerDown:U,className:"absolute top-0 h-full w-full",children:[v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 w-full cursor-ns-resize h-[12px] mt-[-6px]","data-ord":"top"}),v.jsx("div",{className:"absolute pointer-events-auto top-0 right-0 h-full cursor-ew-resize w-[12px] mr-[-6px]","data-ord":"right"}),v.jsx("div",{className:"absolute pointer-events-auto bottom-0 left-0 w-full cursor-ns-resize h-[12px] mb-[-6px]","data-ord":"bottom"}),v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 h-full cursor-ew-resize w-[12px] ml-[-6px]","data-ord":"left"}),te("cursor-nw-resize","top","left"),te("cursor-ne-resize","top","right"),te("cursor-sw-resize","bottom","left"),te("cursor-se-resize","bottom","right"),te("cursor-ns-resize","top",""),te("cursor-ns-resize","bottom",""),te("cursor-ew-resize","left",""),te("cursor-ew-resize","right","")]}),ie=W=>{M(!0),O({initX:m,initY:g,initHeight:x,initWidth:y,startResizeX:W.clientX,startResizeY:W.clientY,ord:""})},K=()=>v.jsxs("div",{className:Jw("border absolute pointer-events-auto px-2 py-1 rounded-full hover:cursor-move bg-background","origin-top-left top-0 left-0"),style:{transform:`scale(${1/i*.8})`},onPointerDown:ie,children:[y," x ",x]}),Q=()=>v.jsx("div",{className:"outline-dashed outline-primary",style:{height:x,width:y,outlineWidth:`${jq/i*1.3}px`}});return s===!1||!h?null:v.jsx("div",{className:"absolute h-full w-full overflow-hidden pointer-events-none z-[2]",children:v.jsxs("div",{className:"relative pointer-events-none z-[2] [box-shadow:0_0_0_9999px_rgba(0,_0,_0,_0.5)]",style:{height:x,width:y,left:m,top:g},children:[Q(),K(),L()]})})},Bq=()=>{const[e,t,n]=bt(r=>[r.interactiveSegState,r.resetInteractiveSegState,r.handleInteractiveSegAccept]);return e.isInteractiveSeg?v.jsxs("div",{className:"z-10 absolute top-[68px] rounded-xl border-solid border p-[8px] left-1/2 translate-x-[-50%] flex justify-center items-center gap-[8px] bg-background",children:[v.jsx(Rn,{onClick:()=>{t()},size:"sm",variant:"secondary",children:"Cancel"}),v.jsx(Rn,{size:"sm",onClick:()=>{n()},children:"Accept"})]}):null},Uq=e=>{const{x:t,y:n,positive:r}=e,o=r?"bg-[rgba(21,_215,_121,_0.936)] outline-[rgba(98,255,179,0.31)]":"bg-[rgba(237,_49,_55,_0.942)] outline-[rgba(255,89,95,0.31)]";return v.jsx("div",{className:`absolute h-[10px] w-[10px] rounded-[50%] ${o} outline-8 outline`,style:{left:t,top:n,transform:"translate(-50%, -50%)"}})},Vq=()=>{const e=bt(t=>t.interactiveSegState.clicks);return v.jsx("div",{className:"absolute h-full w-full overflow-hidden pointer-events-none",children:e.map(t=>v.jsx(Uq,{x:t[0],y:t[1],positive:t[2]===1},t[3]))})},Wq=()=>v.jsx("div",{children:v.jsx(Bq,{})}),nl={capture:!0,passive:!1},Hq=2,W2=(e,t,n,r)=>t{const{minHeight:t,minWidth:n,scale:r,show:o}=e,[i,s,l,u,{x:d,y:h,width:m,height:g},y,x,_,C,S,b,E]=bt(ie=>[ie.isInpainting,ie.imageHeight,ie.imageWidth,ie.isSD(),ie.extenderState,ie.setExtenderX,ie.setExtenderY,ie.setExtenderWidth,ie.setExtenderHeight,ie.settings.extenderDirection,ie.isCropperExtenderResizing,ie.setIsCropperExtenderResizing]),[k,P]=f.useState({initX:0,initY:0,initHeight:0,initWidth:0,startResizeX:0,startResizeY:0,ord:"top"}),M=()=>{},A=(ie,K)=>W2(ie,K,d,n),O=(ie,K)=>W2(ie,K,h,t),F=ie=>{if(i)return;const K=ie.clientX,Q=ie.clientY,W=Math.round((Q-k.startResizeY)/r),le=Math.round((K-k.startResizeX)/r),ge=()=>{const Me=k.initHeight-W,fe=k.initY+W;let xe=fe,$e=Me;if(S===In.xy)xe>0&&(xe=0,$e=k.initHeight-Math.abs(k.initY));else{const Ae=O(fe,Me);xe=Ae[0],$e=Ae[1]}C($e),x(xe)},Ve=()=>{const Me=k.initHeight+W;let[fe,xe]=O(k.initY,Me);S===In.xy&&xe{const Me=k.initWidth-le,fe=k.initX+le;let xe=fe,$e=Me;if(S===In.xy)xe>0&&(xe=0,$e=k.initWidth-Math.abs(k.initX));else{const Ae=A(fe,Me);xe=Ae[0],$e=Ae[1]}_($e),y(xe)},We=()=>{const Me=k.initWidth+le;let[fe,xe]=A(k.initX,Me);S===In.xy&&xe{b&&E(!1)};f.useEffect(()=>{if(b)return document.addEventListener("pointermove",F,nl),document.addEventListener("pointerup",V,nl),document.addEventListener("pointercancel",V,nl),()=>{document.removeEventListener("pointermove",F,nl),document.removeEventListener("pointerup",V,nl),document.removeEventListener("pointercancel",V,nl)}},[b,m,g,k]);const J=ie=>{const{ord:K}=ie.target.dataset;K&&(E(!0),P({initX:d,initY:h,initHeight:g,initWidth:m,startResizeX:ie.clientX,startResizeY:ie.clientY,ord:K}))},G=(ie,K,Q)=>{const ge="w-[12px] h-[12px] z-[4] absolute content-[''] block border-2 border-primary borde pointer-events-auto hover:bg-primary";let Ve="0",Ue="0",We=Q,Me="-6px";return Q===""&&(Me="50%",K==="left"||K==="right"?(We="top",Ue="-50%"):(We="left",Ve="-50%")),v.jsx("div",{className:Ce(ge,ie),style:{[K]:-6,[We]:Me,transform:`translate(${Ve}, ${Ue}) scale(${1/r})`},"data-ord":K+Q,"aria-label":K+Q,tabIndex:-1,role:"button"})},ae=()=>v.jsxs("div",{onFocus:M,onPointerDown:J,className:"absolute top-0 h-full w-full",children:[[In.y,In.xy].includes(S)?v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 w-full cursor-ns-resize h-[12px] mt-[-6px]","data-ord":"top"}),v.jsx("div",{className:"absolute pointer-events-auto bottom-0 left-0 w-full cursor-ns-resize h-[12px] mb-[-6px]","data-ord":"bottom"}),G("cursor-ns-resize","top",""),G("cursor-ns-resize","bottom","")]}):v.jsx(v.Fragment,{}),[In.x,In.xy].includes(S)?v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"absolute pointer-events-auto top-0 right-0 h-full cursor-ew-resize w-[12px] mr-[-6px]","data-ord":"right"}),v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 h-full cursor-ew-resize w-[12px] ml-[-6px]","data-ord":"left"}),G("cursor-ew-resize","left",""),G("cursor-ew-resize","right","")]}):v.jsx(v.Fragment,{}),S===In.xy?v.jsxs(v.Fragment,{children:[G("cursor-nw-resize","top","left"),G("cursor-ne-resize","top","right"),G("cursor-sw-resize","bottom","left"),G("cursor-se-resize","bottom","right")]}):v.jsx(v.Fragment,{})]}),U=ie=>{P({initX:d,initY:h,initHeight:g,initWidth:m,startResizeX:ie.clientX,startResizeY:ie.clientY,ord:""})},te=()=>v.jsxs("div",{className:Jw("border absolute pointer-events-auto px-2 py-1 rounded-full bg-background","origin-top-left top-0 left-0"),style:{transform:`scale(${1/r*.8})`},onPointerDown:U,children:[m," x ",g]}),L=()=>v.jsx("div",{className:Ce("outline-dashed outline-primary"),style:{height:g,width:m,outlineWidth:`${Hq/r*1.3}px`}});return o===!1||!u?null:v.jsx("div",{className:"absolute h-full w-full pointer-events-none z-[2]",children:v.jsxs("div",{className:"relative pointer-events-none z-[2] [box-shadow:0_0_0_9999px_rgba(0,_0,_0,_0.5)]",style:{height:g,width:m,left:d,top:h},children:[L(),te(),ae()]})})},Yq=200,Gq=10,Xq=200,lu=300;function Zq(e){const{file:t}=e,{toast:n}=Td(),[r,o,i,s,l,u,d,h,m,g,y,x,_,C,S,b,E,k,P,M,A,O]=bt(H=>[H.disableShortCuts,H.windowSize,H.isInpainting,H.imageWidth,H.imageHeight,H.settings,H.serverConfig.enableAutoSaving,H.setImageSize,H.setBaseBrushSize,H.interactiveSegState,H.updateInteractiveSegState,H.handleCanvasMouseDown,H.handleCanvasMouseMove,H.undo,H.redo,H.undoDisabled(),H.redoDisabled(),H.getIsProcessing(),H.updateAppState,H.runMannually(),H.runInpainting,H.isCropperExtenderResizing]),F=bt(H=>H.editorState.baseBrushSize),V=bt(H=>H.getBrushSize()),J=bt(H=>H.editorState.renders),G=bt(H=>H.editorState.extraMasks),ae=bt(H=>H.editorState.temporaryMasks),U=bt(H=>H.editorState.lineGroups),te=bt(H=>H.editorState.curLineGroup),[L,ie]=f.useState(!1),[K,Q]=Rx(t),[W,le]=f.useState(),[ge,Ve]=f.useState(),[{x:Ue,y:We},Me]=f.useState({x:-1,y:-1}),[fe,xe]=f.useState(!1),[$e,Ae]=f.useState(!1),[Oe,je]=f.useState(!1),[Ot,ct]=f.useState(1),[Yt,Er]=f.useState(!1),[gt,js]=f.useState(1),I=o.width/2,X=o.height/2,Z=f.useRef(null),[we,he]=f.useState(!1),[de,ke]=f.useState(!1),[ft,pt]=f.useState(0),bn=f.useCallback(()=>te.length!==0,[te]);f.useEffect(()=>{if(!ge||!Q||s===0||l===0)return;const H=J.length===0?K:J[J.length-1];ge.canvas.width=s,ge.canvas.height=l,ge.clearRect(0,0,ge.canvas.width,ge.canvas.height),ge.drawImage(H,0,0,s,l)},[J,K,Q,ge,l,s]),f.useEffect(()=>{!W||!Q||s===0||l===0||(W.canvas.width=s,W.canvas.height=l,W.clearRect(0,0,W.canvas.width,W.canvas.height),ae.forEach(H=>{W.drawImage(H,0,0,s,l)}),G.forEach(H=>{W.drawImage(H,0,0,s,l)}),g.isInteractiveSeg&&g.tmpInteractiveSegMask&&W.drawImage(g.tmpInteractiveSegMask,0,0,s,l),GR(W,te))},[ae,G,Q,g,W,te,l,s]);const Cr=f.useCallback(async()=>{let H=t;if(J.length>0){const Ge=J[J.length-1];H=await ku(Ge.currentSrc,t.name,t.type)}return H},[t,J]),ki=()=>J.length!==0,_o=f.useCallback(()=>{let H=512,Ge=512;return Q?(J.length===0?(H=K.naturalWidth,Ge=K.naturalHeight):J.length!==0&&(H=J[J.length-1].width,Ge=J[J.length-1].height),[H,Ge]):[H,Ge]},[K,Q,J]);f.useEffect(()=>{var Gd;if(!Q)return;const[H,Ge]=_o();(H!==s||Ge!==l)&&h(H,Ge);const st=o.width/H,Qr=(o.height-Yq)/Ge;let an=1;(st<1||Qr<1)&&(an=Math.min(st,Qr)),js(an),ct(an),console.log(`[on file load] image size: ${H}x${Ge}, scale: ${an}, initialCentered: ${we}`),W!=null&&W.canvas&&(console.log("[on file load] set canvas size"),H!=W.canvas.width&&(W.canvas.width=H),Ge!=W.canvas.height&&(W.canvas.height=Ge)),we||((Gd=Z.current)==null||Gd.centerView(an,1),console.log("[on file load] centerView"),he(!0))},[Z,l,s,K,Q,o,we,_o]),f.useEffect(()=>{var H;console.log("[useEffect] centerView"),(H=Z==null?void 0:Z.current)==null||H.centerView(gt,1)},[l,s,Z,gt]);const Vn=f.useCallback(()=>{if(!gt||!o)return;const H=Z.current;if(!H)return;const Ge=(o.width-s*gt)/2,st=(o.height-l*gt)/2;H.setTransform(Ge,st,gt,200,"easeOutQuad"),H.instance.transformState.scale&&(H.instance.transformState.scale=gt),ct(gt),Er(!1)},[Z,o,l,s,o.height,gt]);f.useEffect(()=>(window.addEventListener("resize",()=>{Vn()}),()=>{window.removeEventListener("resize",()=>{Vn()})}),[o,Vn]),Zn("Escape",()=>{k||(de?ke(!1):Vn())},[de,i,Vn]);const Ri=H=>{const Ge=H.nativeEvent;Me({x:Ge.pageX,y:Ge.pageY})},zs=H=>{k||g.isInteractiveSeg||Oe||de&&te.length!==0&&_(c0(H))},Ti=async H=>{P({isPluginRunning:!0});const Ge=await Cr();try{const st=await gT(!0,jR.InteractiveSeg,Ge,void 0,H),{blob:Qr}=st,an=new Image;an.onload=()=>{y({tmpInteractiveSegMask:an})},an.src=Qr}catch(st){n({variant:"destructive",description:st.message?st.message:st.toString()})}P({isPluginRunning:!1})},$c=H=>{if(!bn())return;if(cC(H)){je(!1);return}g.isInteractiveSeg||Oe||!K.src||!(W!=null&&W.canvas)||i||de&&(M?ke(!1):A())},yg=H=>{if(g.isInteractiveSeg){const Ge=c0(H),st=[...g.clicks];lC(H)?st.push([Ge.x,Ge.y,0,st.length]):st.push([Ge.x,Ge.y,1,st.length]),Ti(st),y({clicks:st})}},wg=H=>{if(!(k||g.isInteractiveSeg||Oe||!Q||!(W!=null&&W.canvas))&&!lC(H)){if(cC(H)){je(!0);return}ke(!0),x(c0(H))}},Kd=H=>{H.preventDefault(),C()};Zn("meta+z,ctrl+z",Kd);const kc=H=>{H.preventDefault(),S()};Zn("shift+ctrl+z,shift+meta+z",kc),o2("Tab",H=>{H==null||H.preventDefault(),H==null||H.stopPropagation(),ki()&&ie(()=>(window.setTimeout(()=>{pt(100)},10),!0))},H=>{H==null||H.preventDefault(),H==null||H.stopPropagation(),ki()&&(window.setTimeout(()=>{pt(0)},10),window.setTimeout(()=>{ie(!1)},lu))});const Rc=f.useCallback(async()=>{if(t===void 0)return;if(d&&J.length>0){try{await Vj(J[J.length-1],t.name,t.type),n({description:"Save image success"})}catch(st){n({variant:"destructive",title:"Uh oh! Something went wrong.",description:st.message?st.message:st.toString()})}return}const H=t.name.replace(/(\.[\w\d_-]+)$/i,"_cleanup$1"),Ge=J[J.length-1];if(vF(Ge.currentSrc,H),u.enableDownloadMask){let st=t.name.replace(/(\.[\w\d_-]+)$/i,"_mask$1");st=st.replace(/\.[^/.]+$/,".jpg");const Qr=Lp(s,l,U),an=document.createElement("a");an.download=st,an.href=Qr.toDataURL("image/jpeg"),an.click()}},[t,d,J,u,l,s,U]);Zn("meta+s,ctrl+s",Rc);const Tc=H=>{H!==fe&&!Oe&&!O&&xe(H)},xg=f.useCallback(()=>{if(k)return"default";if(Oe)return"grab";if(fe)return"none"},[fe,Oe,k]);Zn("[",()=>{let H=F;F>10&&(H=F-10),F<=10&&F>0&&(H=F-5),m(H)},[F]),Zn("]",()=>{m(F+10)},[F]),Zn("shift+r",()=>{M&&bn()&&A()},[M,A,bn]),Zn("ctrl+c,meta+c",async()=>{await pF()&&J.length>0&&W!=null&&W.canvas&&(await gF(W==null?void 0:W.canvas),n({title:"Copy inpainting result to clipboard"}))},[J,W]),o2(" ",H=>{r||(H==null||H.preventDefault(),H==null||H.stopPropagation(),xe(!1),je(!0))},H=>{r||(H==null||H.preventDefault(),H==null||H.stopPropagation(),xe(!0),je(!1))});const Pc=()=>{var Ge,st,Qr,an;let H=gt;return((st=(Ge=Z.current)==null?void 0:Ge.instance)==null?void 0:st.transformState.scale)!==void 0&&(H=(an=(Qr=Z.current)==null?void 0:Qr.instance)==null?void 0:an.transformState.scale),H},Yd=(H,Ge)=>{const st=Pc();return{width:`${V*st}px`,height:`${V*st}px`,left:`${H}px`,top:`${Ge}px`,transform:"translate(-50%, -50%)"}},Ac=H=>v.jsx("div",{className:"absolute rounded-[50%] border-[1px] border-[solid] border-[#ffcc00] pointer-events-none bg-[#ffcc00bb]",style:H}),bg=H=>{m(H),$e||(Ae(!0),window.setTimeout(()=>{Ae(!1)},1e4))},_g=()=>v.jsx("div",{className:"absolute h-[20px] w-[20px] pointer-events-none rounded-[50%] bg-[rgba(21,_215,_121,_0.936)] [box-shadow:0_0_0_0_rgba(21,_215,_121,_0.936)] animate-pulse",style:{left:`${Ue}px`,top:`${We}px`,transform:"translate(-50%, -50%)"},children:v.jsx(dK,{})}),Sg=()=>v.jsx(fq,{ref:H=>{H&&(Z.current=H)},panning:{disabled:!Oe,velocityDisabled:!0},wheel:{step:.05},centerZoomedOut:!0,alignmentAnimation:{disabled:!0},centerOnInit:!0,limitToBounds:!1,doubleClick:{disabled:!0},initialScale:gt,minScale:gt*.3,onPanning:()=>{Yt||Er(!0)},onZoom:H=>{ct(H.state.scale)},children:v.jsxs(mq,{contentStyle:{visibility:we?"visible":"hidden"},children:[v.jsxs("div",{className:"grid [grid-template-areas:'editor-content'] gap-y-4",children:[v.jsx("canvas",{className:"[grid-area:editor-content]",style:{clipPath:`inset(0 ${ft}% 0 0)`,transition:`clip-path ${lu}ms`},ref:H=>{if(H&&!ge){const Ge=H.getContext("2d");Ge&&Ve(Ge)}}}),v.jsx("canvas",{className:Ce("[grid-area:editor-content]",k?"pointer-events-none animate-pulse duration-600":""),style:{cursor:xg(),clipPath:`inset(0 ${ft}% 0 0)`,transition:`clip-path ${lu}ms`},onContextMenu:H=>{H.preventDefault()},onMouseOver:()=>{Tc(!0),Ae(!1)},onFocus:()=>Tc(!0),onMouseLeave:()=>Tc(!1),onMouseDown:wg,onMouseUp:yg,onMouseMove:zs,ref:H=>{if(H&&!W){const Ge=H.getContext("2d");Ge&&le(Ge)}}}),v.jsx("div",{className:"[grid-area:editor-content] pointer-events-none grid [grid-template-areas:'original-image-content']",style:{width:`${s}px`,height:`${l}px`},children:L&&v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"[grid-area:original-image-content] z-10 bg-primary h-full w-[6px] justify-self-end",style:{marginRight:`${ft}%`,transition:`margin-right ${lu}ms`}}),v.jsx("img",{className:"[grid-area:original-image-content]",src:K.src,alt:"original",style:{width:`${s}px`,height:`${l}px`}})]})})]}),v.jsx(zq,{maxHeight:l,maxWidth:s,minHeight:Math.min(512,l),minWidth:Math.min(512,s),scale:Pc(),show:u.showCropper}),v.jsx(Kq,{minHeight:Math.min(512,l),minWidth:Math.min(512,s),scale:Pc(),show:u.showExtender}),g.isInteractiveSeg?v.jsx(Vq,{}):v.jsx(v.Fragment,{})]})});return v.jsxs("div",{className:"flex w-screen h-screen justify-center items-center","aria-hidden":"true",onMouseMove:Ri,onMouseUp:$c,children:[Sg(),fe&&!i&&!Oe&&(g.isInteractiveSeg?_g():Ac(Yd(Ue,We))),$e&&Ac(Yd(I,X)),v.jsxs("div",{className:" overflow-hidden fixed flex bottom-5 border px-4 py-2 rounded-[3rem] gap-8 items-center justify-center backdrop-filter backdrop-blur-md bg-background/70",children:[v.jsx(uo,{className:"w-48",defaultValue:[50],min:Gq,max:Xq,step:1,tabIndex:-1,value:[F],onValueChange:H=>bg(H[0]),onClick:()=>Ae(!1)}),v.jsxs("div",{className:"flex gap-2",children:[v.jsx(vn,{tooltip:"Reset zoom & pan",disabled:Ot===gt&&Yt===!1,onClick:Vn,children:v.jsx(ZU,{})}),v.jsx(vn,{tooltip:"Undo",onClick:Kd,disabled:b,children:v.jsx(aV,{})}),v.jsx(vn,{tooltip:"Redo",onClick:kc,disabled:E,children:v.jsx(oV,{})}),v.jsx(vn,{tooltip:"Show original image",onPointerDown:H=>{H.preventDefault(),ie(()=>(window.setTimeout(()=>{pt(100)},10),!0))},onPointerUp:()=>{window.setTimeout(()=>{pt(0)},10),window.setTimeout(()=>{ie(!1)},lu)},disabled:J.length===0,children:v.jsx(qU,{})}),v.jsx(vn,{tooltip:"Save Image",disabled:!J.length,onClick:Rc,children:v.jsx(GU,{})}),u.enableManualInpainting&&u.model.model_type==="inpaint"?v.jsx(vn,{tooltip:"Run Inpainting",disabled:k||!bn()&&G.length===0,onClick:()=>{A()},children:v.jsx(XU,{})}):v.jsx(v.Fragment,{})]})]})]})}const qq=()=>{const[e,t]=bt(n=>[n.imageWidth,n.imageHeight]);return!e||!t?null:v.jsxs("div",{className:"border rounded-lg px-2 py-[6px] z-10 bg-background",children:[e,"x",t]})},B1=["Enter"," "],Qq=["ArrowDown","PageUp","Home"],V3=["ArrowUp","PageDown","End"],Jq=[...Qq,...V3],eQ={ltr:[...B1,"ArrowRight"],rtl:[...B1,"ArrowLeft"]},tQ={ltr:["ArrowLeft"],rtl:["ArrowRight"]},fg="Menu",[ld,nQ,rQ]=zd(fg),[Na,W3]=An(fg,[rQ,Ns,Qm]),pg=Ns(),H3=Qm(),[K3,Fs]=Na(fg),[oQ,Hd]=Na(fg),iQ=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:o,onOpenChange:i,modal:s=!0}=e,l=pg(t),[u,d]=f.useState(null),h=f.useRef(!1),m=Ft(i),g=Sc(o);return f.useEffect(()=>{const y=()=>{h.current=!0,document.addEventListener("pointerdown",x,{capture:!0,once:!0}),document.addEventListener("pointermove",x,{capture:!0,once:!0})},x=()=>h.current=!1;return document.addEventListener("keydown",y,{capture:!0}),()=>{document.removeEventListener("keydown",y,{capture:!0}),document.removeEventListener("pointerdown",x,{capture:!0}),document.removeEventListener("pointermove",x,{capture:!0})}},[]),f.createElement(Od,l,f.createElement(K3,{scope:t,open:n,onOpenChange:m,content:u,onContentChange:d},f.createElement(oQ,{scope:t,onClose:f.useCallback(()=>m(!1),[m]),isUsingKeyboardRef:h,dir:g,modal:s},r)))},Y3=f.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,o=pg(n);return f.createElement(zm,Y({},o,r,{ref:t}))}),G3="MenuPortal",[sQ,X3]=Na(G3,{forceMount:void 0}),aQ=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:o}=e,i=Fs(G3,t);return f.createElement(sQ,{scope:t,forceMount:n},f.createElement(xn,{present:n||i.open},f.createElement(Md,{asChild:!0,container:o},r)))},yo="MenuContent",[lQ,Jx]=Na(yo),cQ=f.forwardRef((e,t)=>{const n=X3(yo,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,i=Fs(yo,e.__scopeMenu),s=Hd(yo,e.__scopeMenu);return f.createElement(ld.Provider,{scope:e.__scopeMenu},f.createElement(xn,{present:r||i.open},f.createElement(ld.Slot,{scope:e.__scopeMenu},s.modal?f.createElement(uQ,Y({},o,{ref:t})):f.createElement(dQ,Y({},o,{ref:t})))))}),uQ=f.forwardRef((e,t)=>{const n=Fs(yo,e.__scopeMenu),r=f.useRef(null),o=Be(t,r);return f.useEffect(()=>{const i=r.current;if(i)return Xm(i)},[]),f.createElement(eb,Y({},e,{ref:o,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:ue(e.onFocusOutside,i=>i.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)}))}),dQ=f.forwardRef((e,t)=>{const n=Fs(yo,e.__scopeMenu);return f.createElement(eb,Y({},e,{ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)}))}),eb=f.forwardRef((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:o,onOpenAutoFocus:i,onCloseAutoFocus:s,disableOutsidePointerEvents:l,onEntryFocus:u,onEscapeKeyDown:d,onPointerDownOutside:h,onFocusOutside:m,onInteractOutside:g,onDismiss:y,disableOutsideScroll:x,..._}=e,C=Fs(yo,n),S=Hd(yo,n),b=pg(n),E=H3(n),k=nQ(n),[P,M]=f.useState(null),A=f.useRef(null),O=Be(t,A,C.onContentChange),F=f.useRef(0),V=f.useRef(""),J=f.useRef(0),G=f.useRef(null),ae=f.useRef("right"),U=f.useRef(0),te=x?Gm:f.Fragment,L=x?{as:Wo,allowPinchZoom:!0}:void 0,ie=Q=>{var W,le;const ge=V.current+Q,Ve=k().filter($e=>!$e.disabled),Ue=document.activeElement,We=(W=Ve.find($e=>$e.ref.current===Ue))===null||W===void 0?void 0:W.textValue,Me=Ve.map($e=>$e.textValue),fe=RQ(Me,ge,We),xe=(le=Ve.find($e=>$e.textValue===fe))===null||le===void 0?void 0:le.ref.current;(function $e(Ae){V.current=Ae,window.clearTimeout(F.current),Ae!==""&&(F.current=window.setTimeout(()=>$e(""),1e3))})(ge),xe&&setTimeout(()=>xe.focus())};f.useEffect(()=>()=>window.clearTimeout(F.current),[]),Km();const K=f.useCallback(Q=>{var W,le;return ae.current===((W=G.current)===null||W===void 0?void 0:W.side)&&PQ(Q,(le=G.current)===null||le===void 0?void 0:le.area)},[]);return f.createElement(lQ,{scope:n,searchRef:V,onItemEnter:f.useCallback(Q=>{K(Q)&&Q.preventDefault()},[K]),onItemLeave:f.useCallback(Q=>{var W;K(Q)||((W=A.current)===null||W===void 0||W.focus(),M(null))},[K]),onTriggerLeave:f.useCallback(Q=>{K(Q)&&Q.preventDefault()},[K]),pointerGraceTimerRef:J,onPointerGraceIntentChange:f.useCallback(Q=>{G.current=Q},[])},f.createElement(te,L,f.createElement(Hm,{asChild:!0,trapped:o,onMountAutoFocus:ue(i,Q=>{var W;Q.preventDefault(),(W=A.current)===null||W===void 0||W.focus()}),onUnmountAutoFocus:s},f.createElement(yc,{asChild:!0,disableOutsidePointerEvents:l,onEscapeKeyDown:d,onPointerDownOutside:h,onFocusOutside:m,onInteractOutside:g,onDismiss:y},f.createElement(ZP,Y({asChild:!0},E,{dir:S.dir,orientation:"vertical",loop:r,currentTabStopId:P,onCurrentTabStopIdChange:M,onEntryFocus:ue(u,Q=>{S.isUsingKeyboardRef.current||Q.preventDefault()})}),f.createElement(Bm,Y({role:"menu","aria-orientation":"vertical","data-state":tA(C.open),"data-radix-menu-content":"",dir:S.dir},b,_,{ref:O,style:{outline:"none",..._.style},onKeyDown:ue(_.onKeyDown,Q=>{const le=Q.target.closest("[data-radix-menu-content]")===Q.currentTarget,ge=Q.ctrlKey||Q.altKey||Q.metaKey,Ve=Q.key.length===1;le&&(Q.key==="Tab"&&Q.preventDefault(),!ge&&Ve&&ie(Q.key));const Ue=A.current;if(Q.target!==Ue||!Jq.includes(Q.key))return;Q.preventDefault();const Me=k().filter(fe=>!fe.disabled).map(fe=>fe.ref.current);V3.includes(Q.key)&&Me.reverse(),$Q(Me)}),onBlur:ue(e.onBlur,Q=>{Q.currentTarget.contains(Q.target)||(window.clearTimeout(F.current),V.current="")}),onPointerMove:ue(e.onPointerMove,cd(Q=>{const W=Q.target,le=U.current!==Q.clientX;if(Q.currentTarget.contains(W)&&le){const ge=Q.clientX>U.current?"right":"left";ae.current=ge,U.current=Q.clientX}}))})))))))}),fQ=f.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return f.createElement(Pe.div,Y({},r,{ref:t}))}),U1="MenuItem",H2="menu.itemSelect",tb=f.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...o}=e,i=f.useRef(null),s=Hd(U1,e.__scopeMenu),l=Jx(U1,e.__scopeMenu),u=Be(t,i),d=f.useRef(!1),h=()=>{const m=i.current;if(!n&&m){const g=new CustomEvent(H2,{bubbles:!0,cancelable:!0});m.addEventListener(H2,y=>r==null?void 0:r(y),{once:!0}),cx(m,g),g.defaultPrevented?d.current=!1:s.onClose()}};return f.createElement(Z3,Y({},o,{ref:u,disabled:n,onClick:ue(e.onClick,h),onPointerDown:m=>{var g;(g=e.onPointerDown)===null||g===void 0||g.call(e,m),d.current=!0},onPointerUp:ue(e.onPointerUp,m=>{var g;d.current||(g=m.currentTarget)===null||g===void 0||g.click()}),onKeyDown:ue(e.onKeyDown,m=>{const g=l.searchRef.current!=="";n||g&&m.key===" "||B1.includes(m.key)&&(m.currentTarget.click(),m.preventDefault())})}))}),Z3=f.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:o,...i}=e,s=Jx(U1,n),l=H3(n),u=f.useRef(null),d=Be(t,u),[h,m]=f.useState(!1),[g,y]=f.useState("");return f.useEffect(()=>{const x=u.current;if(x){var _;y(((_=x.textContent)!==null&&_!==void 0?_:"").trim())}},[i.children]),f.createElement(ld.ItemSlot,{scope:n,disabled:r,textValue:o??g},f.createElement(qP,Y({asChild:!0},l,{focusable:!r}),f.createElement(Pe.div,Y({role:"menuitem","data-highlighted":h?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0},i,{ref:d,onPointerMove:ue(e.onPointerMove,cd(x=>{r?s.onItemLeave(x):(s.onItemEnter(x),x.defaultPrevented||x.currentTarget.focus())})),onPointerLeave:ue(e.onPointerLeave,cd(x=>s.onItemLeave(x))),onFocus:ue(e.onFocus,()=>m(!0)),onBlur:ue(e.onBlur,()=>m(!1))}))))}),pQ=f.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...o}=e;return f.createElement(Q3,{scope:e.__scopeMenu,checked:n},f.createElement(tb,Y({role:"menuitemcheckbox","aria-checked":om(n)?"mixed":n},o,{ref:t,"data-state":nb(n),onSelect:ue(o.onSelect,()=>r==null?void 0:r(om(n)?!0:!n),{checkForDefaultPrevented:!1})})))}),hQ="MenuRadioGroup",[$te,mQ]=Na(hQ,{value:void 0,onValueChange:()=>{}}),gQ="MenuRadioItem",vQ=f.forwardRef((e,t)=>{const{value:n,...r}=e,o=mQ(gQ,e.__scopeMenu),i=n===o.value;return f.createElement(Q3,{scope:e.__scopeMenu,checked:i},f.createElement(tb,Y({role:"menuitemradio","aria-checked":i},r,{ref:t,"data-state":nb(i),onSelect:ue(r.onSelect,()=>{var s;return(s=o.onValueChange)===null||s===void 0?void 0:s.call(o,n)},{checkForDefaultPrevented:!1})})))}),q3="MenuItemIndicator",[Q3,yQ]=Na(q3,{checked:!1}),wQ=f.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...o}=e,i=yQ(q3,n);return f.createElement(xn,{present:r||om(i.checked)||i.checked===!0},f.createElement(Pe.span,Y({},o,{ref:t,"data-state":nb(i.checked)})))}),xQ=f.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return f.createElement(Pe.div,Y({role:"separator","aria-orientation":"horizontal"},r,{ref:t}))}),J3="MenuSub",[bQ,eA]=Na(J3),_Q=e=>{const{__scopeMenu:t,children:n,open:r=!1,onOpenChange:o}=e,i=Fs(J3,t),s=pg(t),[l,u]=f.useState(null),[d,h]=f.useState(null),m=Ft(o);return f.useEffect(()=>(i.open===!1&&m(!1),()=>m(!1)),[i.open,m]),f.createElement(Od,s,f.createElement(K3,{scope:t,open:r,onOpenChange:m,content:d,onContentChange:h},f.createElement(bQ,{scope:t,contentId:nr(),triggerId:nr(),trigger:l,onTriggerChange:u},n)))},gp="MenuSubTrigger",SQ=f.forwardRef((e,t)=>{const n=Fs(gp,e.__scopeMenu),r=Hd(gp,e.__scopeMenu),o=eA(gp,e.__scopeMenu),i=Jx(gp,e.__scopeMenu),s=f.useRef(null),{pointerGraceTimerRef:l,onPointerGraceIntentChange:u}=i,d={__scopeMenu:e.__scopeMenu},h=f.useCallback(()=>{s.current&&window.clearTimeout(s.current),s.current=null},[]);return f.useEffect(()=>h,[h]),f.useEffect(()=>{const m=l.current;return()=>{window.clearTimeout(m),u(null)}},[l,u]),f.createElement(Y3,Y({asChild:!0},d),f.createElement(Z3,Y({id:o.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":o.contentId,"data-state":tA(n.open)},e,{ref:Am(t,o.onTriggerChange),onClick:m=>{var g;(g=e.onClick)===null||g===void 0||g.call(e,m),!(e.disabled||m.defaultPrevented)&&(m.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:ue(e.onPointerMove,cd(m=>{i.onItemEnter(m),!m.defaultPrevented&&!e.disabled&&!n.open&&!s.current&&(i.onPointerGraceIntentChange(null),s.current=window.setTimeout(()=>{n.onOpenChange(!0),h()},100))})),onPointerLeave:ue(e.onPointerLeave,cd(m=>{var g;h();const y=(g=n.content)===null||g===void 0?void 0:g.getBoundingClientRect();if(y){var x;const _=(x=n.content)===null||x===void 0?void 0:x.dataset.side,C=_==="right",S=C?-5:5,b=y[C?"left":"right"],E=y[C?"right":"left"];i.onPointerGraceIntentChange({area:[{x:m.clientX+S,y:m.clientY},{x:b,y:y.top},{x:E,y:y.top},{x:E,y:y.bottom},{x:b,y:y.bottom}],side:_}),window.clearTimeout(l.current),l.current=window.setTimeout(()=>i.onPointerGraceIntentChange(null),300)}else{if(i.onTriggerLeave(m),m.defaultPrevented)return;i.onPointerGraceIntentChange(null)}})),onKeyDown:ue(e.onKeyDown,m=>{const g=i.searchRef.current!=="";if(!(e.disabled||g&&m.key===" ")&&eQ[r.dir].includes(m.key)){var y;n.onOpenChange(!0),(y=n.content)===null||y===void 0||y.focus(),m.preventDefault()}})})))}),EQ="MenuSubContent",CQ=f.forwardRef((e,t)=>{const n=X3(yo,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,i=Fs(yo,e.__scopeMenu),s=Hd(yo,e.__scopeMenu),l=eA(EQ,e.__scopeMenu),u=f.useRef(null),d=Be(t,u);return f.createElement(ld.Provider,{scope:e.__scopeMenu},f.createElement(xn,{present:r||i.open},f.createElement(ld.Slot,{scope:e.__scopeMenu},f.createElement(eb,Y({id:l.contentId,"aria-labelledby":l.triggerId},o,{ref:d,align:"start",side:s.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:h=>{var m;s.isUsingKeyboardRef.current&&((m=u.current)===null||m===void 0||m.focus()),h.preventDefault()},onCloseAutoFocus:h=>h.preventDefault(),onFocusOutside:ue(e.onFocusOutside,h=>{h.target!==l.trigger&&i.onOpenChange(!1)}),onEscapeKeyDown:ue(e.onEscapeKeyDown,h=>{s.onClose(),h.preventDefault()}),onKeyDown:ue(e.onKeyDown,h=>{const m=h.currentTarget.contains(h.target),g=tQ[s.dir].includes(h.key);if(m&&g){var y;i.onOpenChange(!1),(y=l.trigger)===null||y===void 0||y.focus(),h.preventDefault()}})})))))});function tA(e){return e?"open":"closed"}function om(e){return e==="indeterminate"}function nb(e){return om(e)?"indeterminate":e?"checked":"unchecked"}function $Q(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function kQ(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function RQ(e,t,n){const o=t.length>1&&Array.from(t).every(d=>d===t[0])?t[0]:t,i=n?e.indexOf(n):-1;let s=kQ(e,Math.max(i,0));o.length===1&&(s=s.filter(d=>d!==n));const u=s.find(d=>d.toLowerCase().startsWith(o.toLowerCase()));return u!==n?u:void 0}function TQ(e,t){const{x:n,y:r}=e;let o=!1;for(let i=0,s=t.length-1;ir!=h>r&&n<(d-l)*(r-u)/(h-u)+l&&(o=!o)}return o}function PQ(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return TQ(n,t)}function cd(e){return t=>t.pointerType==="mouse"?e(t):void 0}const AQ=iQ,OQ=Y3,MQ=aQ,NQ=cQ,DQ=fQ,IQ=tb,LQ=pQ,FQ=vQ,jQ=wQ,zQ=xQ,BQ=_Q,UQ=SQ,VQ=CQ,nA="DropdownMenu",[WQ,kte]=An(nA,[W3]),Sr=W3(),[HQ,rA]=WQ(nA),KQ=e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:o,defaultOpen:i,onOpenChange:s,modal:l=!0}=e,u=Sr(t),d=f.useRef(null),[h=!1,m]=Zr({prop:o,defaultProp:i,onChange:s});return f.createElement(HQ,{scope:t,triggerId:nr(),triggerRef:d,contentId:nr(),open:h,onOpenChange:m,onOpenToggle:f.useCallback(()=>m(g=>!g),[m]),modal:l},f.createElement(AQ,Y({},u,{open:h,onOpenChange:m,dir:r,modal:l}),n))},YQ="DropdownMenuTrigger",GQ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...o}=e,i=rA(YQ,n),s=Sr(n);return f.createElement(OQ,Y({asChild:!0},s),f.createElement(Pe.button,Y({type:"button",id:i.triggerId,"aria-haspopup":"menu","aria-expanded":i.open,"aria-controls":i.open?i.contentId:void 0,"data-state":i.open?"open":"closed","data-disabled":r?"":void 0,disabled:r},o,{ref:Am(t,i.triggerRef),onPointerDown:ue(e.onPointerDown,l=>{!r&&l.button===0&&l.ctrlKey===!1&&(i.onOpenToggle(),i.open||l.preventDefault())}),onKeyDown:ue(e.onKeyDown,l=>{r||(["Enter"," "].includes(l.key)&&i.onOpenToggle(),l.key==="ArrowDown"&&i.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(l.key)&&l.preventDefault())})})))}),XQ=e=>{const{__scopeDropdownMenu:t,...n}=e,r=Sr(t);return f.createElement(MQ,Y({},r,n))},ZQ="DropdownMenuContent",qQ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=rA(ZQ,n),i=Sr(n),s=f.useRef(!1);return f.createElement(NQ,Y({id:o.contentId,"aria-labelledby":o.triggerId},i,r,{ref:t,onCloseAutoFocus:ue(e.onCloseAutoFocus,l=>{var u;s.current||(u=o.triggerRef.current)===null||u===void 0||u.focus(),s.current=!1,l.preventDefault()}),onInteractOutside:ue(e.onInteractOutside,l=>{const u=l.detail.originalEvent,d=u.button===0&&u.ctrlKey===!0,h=u.button===2||d;(!o.modal||h)&&(s.current=!0)}),style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}}))}),QQ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(DQ,Y({},o,r,{ref:t}))}),JQ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(IQ,Y({},o,r,{ref:t}))}),eJ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(LQ,Y({},o,r,{ref:t}))}),tJ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(FQ,Y({},o,r,{ref:t}))}),nJ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(jQ,Y({},o,r,{ref:t}))}),rJ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(zQ,Y({},o,r,{ref:t}))}),oJ=e=>{const{__scopeDropdownMenu:t,children:n,open:r,onOpenChange:o,defaultOpen:i}=e,s=Sr(t),[l=!1,u]=Zr({prop:r,defaultProp:i,onChange:o});return f.createElement(BQ,Y({},s,{open:l,onOpenChange:u}),n)},iJ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(UQ,Y({},o,r,{ref:t}))}),sJ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(VQ,Y({},o,r,{ref:t,style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}}))}),aJ=KQ,lJ=GQ,cJ=XQ,oA=qQ,iA=QQ,sA=JQ,aA=eJ,lA=tJ,cA=nJ,uA=rJ,uJ=oJ,dA=iJ,fA=sJ,dJ=aJ,fJ=lJ,K2=uJ,V1=f.forwardRef(({className:e,inset:t,children:n,...r},o)=>v.jsxs(dA,{ref:o,className:Ce("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",e),...r,children:[n,v.jsx(Jj,{className:"ml-auto h-4 w-4"})]}));V1.displayName=dA.displayName;const W1=f.forwardRef(({className:e,...t},n)=>v.jsx(fA,{ref:n,className:Ce("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...t}));W1.displayName=fA.displayName;const pA=f.forwardRef(({className:e,sideOffset:t=4,...n},r)=>v.jsx(cJ,{children:v.jsx(oA,{ref:r,sideOffset:t,className:Ce("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md","data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),onCloseAutoFocus:o=>o.preventDefault(),...n})}));pA.displayName=oA.displayName;const il=f.forwardRef(({className:e,inset:t,...n},r)=>v.jsx(sA,{ref:r,className:Ce("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",e),...n}));il.displayName=sA.displayName;const pJ=f.forwardRef(({className:e,children:t,checked:n,...r},o)=>v.jsxs(aA,{ref:o,className:Ce("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),checked:n,...r,children:[v.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:v.jsx(cA,{children:v.jsx(vT,{className:"h-4 w-4"})})}),t]}));pJ.displayName=aA.displayName;const hJ=f.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(lA,{ref:r,className:Ce("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[v.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:v.jsx(cA,{children:v.jsx(oz,{className:"h-4 w-4 fill-current"})})}),t]}));hJ.displayName=lA.displayName;const mJ=f.forwardRef(({className:e,inset:t,...n},r)=>v.jsx(iA,{ref:r,className:Ce("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",e),...n}));mJ.displayName=iA.displayName;const gJ=f.forwardRef(({className:e,...t},n)=>v.jsx(uA,{ref:n,className:Ce("-mx-1 my-1 h-px bg-muted",e),...t}));gJ.displayName=uA.displayName;const Y2={RemoveBG:{IconClass:VC,showName:"RemoveBG"},AnimeSeg:{IconClass:VC,showName:"Anime Segmentation"},RealESRGAN:{IconClass:XT,showName:"RealESRGAN"},GFPGAN:{IconClass:WC,showName:"GFPGAN"},RestoreFormer:{IconClass:WC,showName:"RestoreFormer"},InteractiveSeg:{IconClass:nV,showName:"Interactive Segmentation"}},vJ=()=>{const[e,t,n,r]=bt(d=>[d.file,d.serverConfig.plugins,d.updateInteractiveSegState,d.runRenderablePlugin]),o=!e;if(t.length===0)return null;const i=(d,h)=>{h==="InteractiveSeg"?n({isInteractiveSeg:!0}):r(d,h)},s=()=>v.jsxs(K2,{children:[v.jsx(V1,{disabled:o,children:v.jsxs("div",{className:"flex gap-2 items-center",children:[v.jsx(XT,{}),"RealESRGAN"]})}),v.jsxs(W1,{children:[v.jsx(il,{onClick:()=>r(!1,"RealESRGAN",{upscale:2}),children:"upscale 2x"}),v.jsx(il,{onClick:()=>r(!1,"RealESRGAN",{upscale:4}),children:"upscale 4x"})]})]},"RealESRGAN"),l=d=>{const{IconClass:h,showName:m}=Y2[d.name];return v.jsxs(K2,{children:[v.jsx(V1,{disabled:o,children:v.jsxs("div",{className:"flex gap-2 items-center",children:[v.jsx(h,{className:"p-1"}),m]})}),v.jsxs(W1,{children:[v.jsx(il,{onClick:()=>i(!1,d.name),children:"Remove Background"}),v.jsx(il,{onClick:()=>i(!0,d.name),children:"Generate Mask"})]})]},d.name)},u=()=>t.map(d=>{const{IconClass:h,showName:m}=Y2[d.name];return d.name==="RealESRGAN"?s():d.name==="RemoveBG"||d.name==="AnimeSeg"?l(d):v.jsx(il,{onClick:()=>i(!1,d.name),disabled:o,children:v.jsxs("div",{className:"flex gap-2 items-center",children:[v.jsx(h,{className:"p-1"}),m]})},d.name)});return v.jsxs(dJ,{modal:!1,children:[v.jsx(fJ,{className:"border rounded-lg z-10 bg-background outline-none",tabIndex:-1,children:v.jsx(Rn,{variant:"ghost",size:"icon",asChild:!0,className:"p-1.5",children:v.jsx(WU,{strokeWidth:1})})}),v.jsx(pA,{side:"bottom",align:"start",children:u()})]})},yJ=Sx,wJ=gP,xJ=Ex,hA=f.forwardRef(({className:e,...t},n)=>v.jsx(Nd,{className:Ce("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t,ref:n}));hA.displayName=Nd.displayName;const bJ=Om("fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=closed]:duration-200 data-[state=open]:duration-300",{variants:{side:{top:"inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",bottom:"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",left:"inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",right:"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm"}},defaultVariants:{side:"right"}}),mA=f.forwardRef(({side:e="right",className:t,children:n,...r},o)=>v.jsxs(xJ,{children:[v.jsx(hA,{}),v.jsx(Dd,{ref:o,className:Ce(bJ({side:e}),t),...r,children:n})]}));mA.displayName=Dd.displayName;const gA=({className:e,...t})=>v.jsx("div",{className:Ce("flex flex-col space-y-2 text-center sm:text-left",e),...t});gA.displayName="SheetHeader";const _J=f.forwardRef(({className:e,...t},n)=>v.jsx(Id,{ref:n,className:Ce("text-lg font-semibold text-foreground",e),...t}));_J.displayName=Id.displayName;const SJ=f.forwardRef(({className:e,...t},n)=>v.jsx(Ld,{ref:n,className:Ce("text-sm text-muted-foreground",e),...t}));SJ.displayName=Ld.displayName;const Ut=({children:e})=>v.jsx("div",{className:"flex justify-between items-center pr-2",children:e}),Pt=({text:e,toolTip:t="",url:n,htmlFor:r,disabled:o=!1})=>v.jsxs(YT,{children:[v.jsx(GT,{asChild:!0,children:v.jsx(Gx,{htmlFor:r||e.toLowerCase().replace(" ","-"),className:"font-medium",disabled:o,children:e})}),t||n?v.jsxs(xx,{className:"flex flex-col max-w-xs text-sm",side:"left",children:[v.jsx("p",{children:t}),n?v.jsx(Rn,{variant:"link",className:"justify-end",children:v.jsx("a",{href:n,target:"_blank",children:"More info"})}):v.jsx(v.Fragment,{})]}):v.jsx(v.Fragment,{})]}),EJ=()=>{const[e,t]=bt(n=>[n.settings,n.updateSettings]);return v.jsxs("div",{className:"flex flex-col gap-4 mt-4",children:[v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{htmlFor:"steps",text:"Steps",toolTip:"The number of denoising steps. More denoising steps usually lead to a higher quality image at the expense of slower inference."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[30],min:1,max:100,step:1,value:[Math.floor(e.ldmSteps)],onValueChange:n=>t({ldmSteps:n[0]})}),v.jsx(Gn,{id:"steps",className:"w-[60px] rounded-full",numberValue:e.ldmSteps,allowFloat:!1,onNumberValueChange:n=>{t({ldmSteps:n})}})]})]}),v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Sampler"}),v.jsxs(aa,{value:e.ldmSampler,onValueChange:n=>{t({ldmSampler:n})},children:[v.jsx(ls,{className:"w-[100px]",children:v.jsx(la,{placeholder:"Select sampler"})}),v.jsx(cs,{align:"end",children:v.jsx(wl,{children:Object.values(Zw).map(n=>v.jsx(us,{value:n,children:n},n))})})]})]})]})},vA=f.forwardRef(({className:e,...t},n)=>v.jsx("textarea",{className:Ce("flex min-h-[60px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",e,"overflow-auto"),tabIndex:-1,ref:n,...t}));vA.displayName="Textarea";const vp=({text:e,onClick:t})=>{const[n]=bt(r=>[r.settings.showExtender]);return v.jsx(Rn,{variant:"outline",className:"p-1 h-8",disabled:!n,onClick:t,children:v.jsx("div",{className:"flex items-center gap-1",children:e})})},CJ=()=>{const[e,t,n,r,o,i,s,l,u,d,h]=bt(L=>[L.serverConfig.samplers,L.settings,L.paintByExampleFile,L.getIsProcessing(),L.updateSettings,L.runInpainting,L.updateAppState,L.updateExtenderByBuiltIn,L.updateExtenderDirection,L.adjustMask,L.clearMask]),[m,g]=Rx(n),y=f.useRef(null);OP(y,()=>{y!=null&&y.current&&y.current.blur()});const x=L=>{L.key==="Enter"&&L.ctrlKey&&t.prompt.length!==0&&i()},_=()=>v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Cropper",toolTip:"Inpainting on part of image, improve inference speed and reduce memory usage."}),v.jsx(co,{id:"cropper",checked:t.showCropper,onCheckedChange:L=>{o({showCropper:L}),L&&o({showExtender:!1})}})]}),C=()=>t.model.support_controlnet?v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex justify-between items-center pr-2",children:[v.jsx(Pt,{text:"ControlNet",toolTip:"Using an additional conditioning image to control how an image is generated",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#controlnet"}),v.jsx(co,{id:"controlnet",checked:t.enableControlnet,onCheckedChange:L=>{o({enableControlnet:L})}})]}),v.jsx("div",{className:"flex flex-col gap-1",children:v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[100],min:1,max:100,step:1,disabled:!t.enableControlnet,value:[Math.floor(t.controlnetConditioningScale*100)],onValueChange:L=>o({controlnetConditioningScale:L[0]/100})}),v.jsx(Gn,{id:"controlnet-weight",className:"w-[60px] rounded-full",disabled:!t.enableControlnet,numberValue:t.controlnetConditioningScale,allowFloat:!1,onNumberValueChange:L=>{o({controlnetConditioningScale:L})}})]})}),v.jsx("div",{className:"pr-2",children:v.jsxs(aa,{defaultValue:t.controlnetMethod,value:t.controlnetMethod,onValueChange:L=>{o({controlnetMethod:L})},disabled:!t.enableControlnet,children:[v.jsx(ls,{children:v.jsx(la,{placeholder:"Select control method"})}),v.jsx(cs,{align:"end",children:v.jsx(wl,{children:Object.values(t.model.controlnets).map(L=>v.jsx(us,{value:L,children:L.split("/")[1]},L))})})]})})]}),v.jsx(Fn,{})]}):null,S=()=>t.model.support_lcm_lora?v.jsxs(v.Fragment,{children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"LCM Lora",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inference_with_lcm_lora",toolTip:"Enable quality image generation in typically 2-4 steps. Suggest disabling guidance_scale by setting it to 0. You can also try values between 1.0 and 2.0. When LCM Lora is enabled, LCMSampler will be used automatically."}),v.jsx(co,{id:"lcm-lora",checked:t.enableLCMLora,onCheckedChange:L=>{o({enableLCMLora:L})}})]}),v.jsx(Fn,{})]}):null,b=()=>t.model.support_freeu?v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex justify-between items-center pr-2",children:[v.jsx(Pt,{text:"FreeU",toolTip:"FreeU is a technique for improving image quality. Different models may require different FreeU-specific hyperparameters, which can be viewed in the more info section.",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/freeu"}),v.jsx(co,{id:"freeu",checked:t.enableFreeu,onCheckedChange:L=>{o({enableFreeu:L})}})]}),v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex justify-center gap-6",children:[v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-s1",text:"s1",disabled:!t.enableFreeu}),v.jsx(Gn,{id:"freeu-s1",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.s1,allowFloat:!0,onNumberValueChange:L=>{o({freeuConfig:{...t.freeuConfig,s1:L}})}})]}),v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-s2",text:"s2",disabled:!t.enableFreeu}),v.jsx(Gn,{id:"freeu-s2",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.s2,allowFloat:!0,onNumberValueChange:L=>{o({freeuConfig:{...t.freeuConfig,s2:L}})}})]})]}),v.jsxs("div",{className:"flex justify-center gap-6",children:[v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-b1",text:"b1",disabled:!t.enableFreeu}),v.jsx(Gn,{id:"freeu-b1",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.b1,allowFloat:!0,onNumberValueChange:L=>{o({freeuConfig:{...t.freeuConfig,b1:L}})}})]}),v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-b2",text:"b2",disabled:!t.enableFreeu}),v.jsx(Gn,{id:"freeu-b2",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.b2,allowFloat:!0,onNumberValueChange:L=>{o({freeuConfig:{...t.freeuConfig,b2:L}})}})]})]})]}),v.jsx(Fn,{})]}):null,E=()=>t.model.need_prompt?v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsx(Pt,{text:"Negative prompt",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#negative-prompt",toolTip:"Negative prompt guides the model away from generating certain things in an image"}),v.jsx("div",{className:"pl-2 pr-4",children:v.jsx(vA,{ref:y,rows:4,onKeyUp:x,className:"max-h-[8rem] overflow-y-auto mb-2",placeholder:"",id:"negative-prompt",value:t.negativePrompt,onInput:L=>{L.preventDefault(),L.stopPropagation();const ie=L.target;o({negativePrompt:ie.value})}})})]}):null,k=()=>t.model.name!==YR?null:v.jsxs("div",{children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Example Image",toolTip:"An example image to guide image generation."}),v.jsx(c1,{tooltip:"Upload example image",onFileUpload:L=>{s({paintByExampleFile:L})},children:v.jsx(ZT,{})})]}),g?v.jsx("div",{className:"flex justify-center items-center",children:v.jsx("img",{src:m.src,alt:"example",className:"max-w-[200px] max-h-[200px] m-3"})}):v.jsx(v.Fragment,{}),v.jsx(Rn,{variant:"default",className:"w-full",disabled:r||!g,onClick:()=>{i()},children:"Paint"})]}),P=()=>t.model.name!==aF?null:v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Image guidance scale",toolTip:"Push the generated image towards the inital image. Higher image guidance scale encourages generated images that are closely linked to the source image, usually at the expense of lower image quality.",url:"https://huggingface.co/docs/diffusers/main/en/api/pipelines/pix2pix"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[150],min:100,max:1e3,step:1,value:[Math.floor(t.p2pImageGuidanceScale*100)],onValueChange:L=>o({p2pImageGuidanceScale:L[0]/100})}),v.jsx(Gn,{id:"image-guidance-scale",className:"w-[60px] rounded-full",numberValue:t.p2pImageGuidanceScale,allowFloat:!0,onNumberValueChange:L=>{o({p2pImageGuidanceScale:L})}})]})]}),M=()=>t.model.support_strength?v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Strength",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#strength",toolTip:"Strength is a measure of how much noise is added to the base image, which influences how similar the output is to the base image. Higher value means more noise and more different from the base image"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[100],min:10,max:100,step:1,value:[Math.floor(t.sdStrength*100)],onValueChange:L=>o({sdStrength:L[0]/100})}),v.jsx(Gn,{id:"strength",className:"w-[60px] rounded-full",numberValue:t.sdStrength,allowFloat:!0,onNumberValueChange:L=>{o({sdStrength:L})}})]})]}):null,A=()=>t.model.support_outpainting?v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Extender",toolTip:"Perform outpainting on images to expand it's content."}),v.jsx(co,{id:"extender",checked:t.showExtender,onCheckedChange:L=>{o({showExtender:L}),L&&o({showCropper:!1})}})]}),v.jsxs(Ut,{children:[v.jsxs(aa,{defaultValue:t.extenderDirection,value:t.extenderDirection,onValueChange:L=>{u(L)},children:[v.jsx(ls,{className:"w-[65px] h-7",disabled:!t.showExtender,children:v.jsx(la,{placeholder:"Select axis"})}),v.jsx(cs,{align:"end",children:v.jsx(wl,{children:Object.values(In).map(L=>v.jsx(us,{value:L,children:L},L))})})]}),v.jsxs("div",{className:"flex gap-1 justify-center mt-0",children:[v.jsx(vp,{text:"1.25x",onClick:()=>l(t.extenderDirection,1.25)}),v.jsx(vp,{text:"1.5x",onClick:()=>l(t.extenderDirection,1.5)}),v.jsx(vp,{text:"1.75x",onClick:()=>l(t.extenderDirection,1.75)}),v.jsx(vp,{text:"2.0x",onClick:()=>l(t.extenderDirection,2)})]})]})]}),v.jsx(Fn,{})]}):null,O=()=>t.model.name!==lF?null:v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Task",toolTip:"PowerPaint task. When using extender, image-outpainting task will be auto used. For object-removal and image-outpainting, it is recommended to set the guidance_scale at 10 or above."}),v.jsxs(aa,{defaultValue:t.powerpaintTask,value:t.powerpaintTask,onValueChange:L=>{o({powerpaintTask:L})},disabled:t.showExtender,children:[v.jsx(ls,{className:"w-[140px]",children:v.jsx(la,{placeholder:"Select task"})}),v.jsx(cs,{align:"end",children:v.jsx(wl,{children:[kl.text_guided,kl.object_remove,kl.shape_guided].map(L=>v.jsx(us,{value:L,children:L},L))})})]})]}),F=()=>v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{htmlFor:"steps",text:"Steps",toolTip:"The number of denoising steps. More denoising steps usually lead to a higher quality image at the expense of slower inference."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[30],min:1,max:100,step:1,value:[Math.floor(t.sdSteps)],onValueChange:L=>o({sdSteps:L[0]})}),v.jsx(Gn,{id:"steps",className:"w-[60px] rounded-full",numberValue:t.sdSteps,allowFloat:!1,onNumberValueChange:L=>{o({sdSteps:L})}})]})]}),V=()=>v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Guidance scale",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#guidance-scale",toolTip:"Guidance scale affects how aligned the text prompt and generated image are. Higher value means the prompt and generated image are closely aligned, so the output is a stricter interpretation of the prompt"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[750],min:0,max:1500,step:1,value:[Math.floor(t.sdGuidanceScale*100)],onValueChange:L=>o({sdGuidanceScale:L[0]/100})}),v.jsx(Gn,{id:"guidance-scale",className:"w-[60px] rounded-full",numberValue:t.sdGuidanceScale,allowFloat:!0,onNumberValueChange:L=>{o({sdGuidanceScale:L})}})]})]}),J=()=>v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Sampler"}),v.jsxs(aa,{defaultValue:t.sdSampler,value:t.sdSampler,onValueChange:L=>{o({sdSampler:L})},children:[v.jsx(ls,{className:"w-[175px] text-xs",children:v.jsx(la,{placeholder:"Select sampler"})}),v.jsx(cs,{align:"end",children:v.jsx(wl,{children:e.map(L=>v.jsx(us,{value:L,className:"text-xs",children:L},L))})})]})]}),G=()=>v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Seed",toolTip:"Using same parameters and a fixed seed can generate same result image."}),v.jsxs("div",{className:"flex gap-2 justify-center items-center",children:[v.jsx(co,{id:"seed",checked:t.seedFixed,onCheckedChange:L=>{o({seedFixed:L})}}),v.jsx(Gn,{id:"seed",className:"w-[100px]",disabled:!t.seedFixed,numberValue:t.seed,allowFloat:!1,onNumberValueChange:L=>{o({seed:L})}})]})]}),ae=()=>v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Mask blur",toolTip:"How much to blur the mask before processing, in pixels."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[t.sdMaskBlur],min:0,max:96,step:1,value:[Math.floor(t.sdMaskBlur)],onValueChange:L=>o({sdMaskBlur:L[0]})}),v.jsx(Gn,{id:"mask-blur",className:"w-[60px] rounded-full",numberValue:t.sdMaskBlur,allowFloat:!1,onNumberValueChange:L=>{o({sdMaskBlur:L})}})]})]}),U=()=>v.jsxs(v.Fragment,{children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Match histograms",toolTip:"Match the inpainting result histogram to the source image histogram",url:"https://github.com/Sanster/lama-cleaner/pull/143#issuecomment-1325859307"}),v.jsx(co,{id:"match-histograms",checked:t.sdMatchHistograms,onCheckedChange:L=>{o({sdMatchHistograms:L})}})]}),v.jsx(Fn,{})]}),te=()=>v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{htmlFor:"adjustMaskKernelSize",text:"Adjust Mask",toolTip:"Expand or shrink mask. Using the slider to adjust the kernel size for dilation or erosion."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[12],min:1,max:100,step:1,value:[Math.floor(t.adjustMaskKernelSize)],onValueChange:L=>o({adjustMaskKernelSize:L[0]})}),v.jsx(Gn,{id:"adjustMaskKernelSize",className:"w-[60px] rounded-full",numberValue:t.adjustMaskKernelSize,allowFloat:!1,onNumberValueChange:L=>{o({adjustMaskKernelSize:L})}})]}),v.jsxs(Ut,{children:[v.jsxs("div",{className:"flex gap-1 justify-start",children:[v.jsx(Rn,{variant:"outline",className:"p-1 h-8",onClick:()=>d("expand"),disabled:r,children:v.jsxs("div",{className:"flex items-center gap-1 select-none",children:[v.jsx(rV,{size:16}),"expand"]})}),v.jsx(Rn,{variant:"outline",className:"p-1 h-8",onClick:()=>d("shrink"),disabled:r,children:v.jsxs("div",{className:"flex items-center gap-1 select-none",children:[v.jsx(tV,{size:16}),"Shrink"]})})]}),v.jsx(Rn,{variant:"outline",className:"p-1 h-8 justify-self-end",onClick:h,disabled:r,children:v.jsx("div",{className:"flex items-center gap-1 select-none",children:"Clear"})})]})]}),v.jsx(Fn,{})]});return v.jsxs("div",{className:"flex flex-col gap-4 mt-4",children:[_(),A(),te(),O(),F(),V(),P(),M(),J(),G(),E(),v.jsx(Fn,{}),C(),S(),ae(),U(),b(),k()]})},$J=()=>{const[e,t]=bt(n=>[n.settings,n.updateSettings]);return v.jsxs("div",{className:"flex flex-col gap-4 mt-4",children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"CV2 Flag",url:"https://docs.opencv.org/4.8.0/d7/d8b/group__photo__inpaint.html#gga8002a65f5a3328fbf15df81b842d3c3ca892824c38e258feb5e72f308a358d52e"}),v.jsxs(aa,{value:e.cv2Flag,onValueChange:n=>{t({cv2Flag:n})},children:[v.jsx(ls,{className:"w-[160px]",children:v.jsx(la,{placeholder:"Select flag"})}),v.jsx(cs,{align:"end",children:v.jsx(wl,{children:Object.values(qw).map(n=>v.jsx(us,{value:n,children:n},n))})})]})]}),v.jsx(Pt,{text:"CV2 Radius",url:"https://docs.opencv.org/4.8.0/d7/d8b/group__photo__inpaint.html#gga8002a65f5a3328fbf15df81b842d3c3ca892824c38e258feb5e72f308a358d52e"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[5],min:1,max:100,step:1,value:[Math.floor(e.cv2Radius)],onValueChange:n=>t({cv2Radius:n[0]})}),v.jsx(Gn,{id:"cv2-radius",className:"w-[60px] rounded-full",numberValue:e.cv2Radius,allowFloat:!1,onNumberValueChange:n=>{t({cv2Radius:n})}})]})]})},kJ=()=>{const[e,t]=bt(i=>[i.settings,i.windowSize]),[n,r]=AP(!0);if(Zn("c",()=>{r()}),e.model.name!==oC&&e.model.name!==iC&&e.model.model_type===is)return null;const o=()=>e.model.name===oC?v.jsx(EJ,{}):e.model.name===iC?v.jsx($J,{}):v.jsx(CJ,{});return v.jsxs(yJ,{open:n,modal:!1,children:[v.jsx(wJ,{tabIndex:-1,className:"z-10 outline-none absolute top-[68px] right-6 rounded-lg border bg-background",children:v.jsx(Rn,{variant:"ghost",size:"icon",asChild:!0,className:"p-1.5",onClick:r,children:v.jsx(HU,{strokeWidth:1})})}),v.jsxs(mA,{side:"right",className:"w-[300px] mt-[60px] outline-none pl-4 pr-1",onOpenAutoFocus:i=>i.preventDefault(),onPointerDownOutside:i=>i.preventDefault(),children:[v.jsxs(gA,{children:[v.jsxs(Ut,{children:[v.jsx("div",{className:"overflow-hidden mr-8",children:e.model.name.split("/")[e.model.name.split("/").length-1]}),v.jsx(Rn,{variant:"ghost",size:"icon",className:"border h-6 w-6",onClick:r,children:v.jsx(KU,{strokeWidth:1})})]}),v.jsx(Fn,{})]}),v.jsx(og,{style:{height:t.height-160},className:"pr-3",children:o()})]})]})},Yo=Object.create(null);Yo.open="0";Yo.close="1";Yo.ping="2";Yo.pong="3";Yo.message="4";Yo.upgrade="5";Yo.noop="6";const th=Object.create(null);Object.keys(Yo).forEach(e=>{th[Yo[e]]=e});const H1={type:"error",data:"parser error"},yA=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",wA=typeof ArrayBuffer=="function",xA=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,rb=({type:e,data:t},n,r)=>yA&&t instanceof Blob?n?r(t):G2(t,r):wA&&(t instanceof ArrayBuffer||xA(t))?n?r(t):G2(new Blob([t]),r):r(Yo[e]+(t||"")),G2=(e,t)=>{const n=new FileReader;return n.onload=function(){const r=n.result.split(",")[1];t("b"+(r||""))},n.readAsDataURL(e)};function X2(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let L0;function RJ(e,t){if(yA&&e.data instanceof Blob)return e.data.arrayBuffer().then(X2).then(t);if(wA&&(e.data instanceof ArrayBuffer||xA(e.data)))return t(X2(e.data));rb(e,!1,n=>{L0||(L0=new TextEncoder),t(L0.encode(n))})}const Z2="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",gu=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let e=0;e{let t=e.length*.75,n=e.length,r,o=0,i,s,l,u;e[e.length-1]==="="&&(t--,e[e.length-2]==="="&&t--);const d=new ArrayBuffer(t),h=new Uint8Array(d);for(r=0;r>4,h[o++]=(s&15)<<4|l>>2,h[o++]=(l&3)<<6|u&63;return d},PJ=typeof ArrayBuffer=="function",ob=(e,t)=>{if(typeof e!="string")return{type:"message",data:bA(e,t)};const n=e.charAt(0);return n==="b"?{type:"message",data:AJ(e.substring(1),t)}:th[n]?e.length>1?{type:th[n],data:e.substring(1)}:{type:th[n]}:H1},AJ=(e,t)=>{if(PJ){const n=TJ(e);return bA(n,t)}else return{base64:!0,data:e}},bA=(e,t)=>{switch(t){case"blob":return e instanceof Blob?e:new Blob([e]);case"arraybuffer":default:return e instanceof ArrayBuffer?e:e.buffer}},_A="",OJ=(e,t)=>{const n=e.length,r=new Array(n);let o=0;e.forEach((i,s)=>{rb(i,!1,l=>{r[s]=l,++o===n&&t(r.join(_A))})})},MJ=(e,t)=>{const n=e.split(_A),r=[];for(let o=0;o{const r=n.length;let o;if(r<126)o=new Uint8Array(1),new DataView(o.buffer).setUint8(0,r);else if(r<65536){o=new Uint8Array(3);const i=new DataView(o.buffer);i.setUint8(0,126),i.setUint16(1,r)}else{o=new Uint8Array(9);const i=new DataView(o.buffer);i.setUint8(0,127),i.setBigUint64(1,BigInt(r))}e.data&&typeof e.data!="string"&&(o[0]|=128),t.enqueue(o),t.enqueue(n)})}})}let F0;function yp(e){return e.reduce((t,n)=>t+n.length,0)}function wp(e,t){if(e[0].length===t)return e.shift();const n=new Uint8Array(t);let r=0;for(let o=0;oMath.pow(2,21)-1){l.enqueue(H1);break}o=h*Math.pow(2,32)+d.getUint32(4),r=3}else{if(yp(n)e){l.enqueue(H1);break}}}})}const SA=4;function Qt(e){if(e)return IJ(e)}function IJ(e){for(var t in Qt.prototype)e[t]=Qt.prototype[t];return e}Qt.prototype.on=Qt.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this};Qt.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this};Qt.prototype.off=Qt.prototype.removeListener=Qt.prototype.removeAllListeners=Qt.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,o=0;o(e.hasOwnProperty(r)&&(n[r]=e[r]),n),{})}const LJ=Br.setTimeout,FJ=Br.clearTimeout;function hg(e,t){t.useNativeTimers?(e.setTimeoutFn=LJ.bind(Br),e.clearTimeoutFn=FJ.bind(Br)):(e.setTimeoutFn=Br.setTimeout.bind(Br),e.clearTimeoutFn=Br.clearTimeout.bind(Br))}const jJ=1.33;function zJ(e){return typeof e=="string"?BJ(e):Math.ceil((e.byteLength||e.size)*jJ)}function BJ(e){let t=0,n=0;for(let r=0,o=e.length;r=57344?n+=3:(r++,n+=4);return n}function UJ(e){let t="";for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+="&"),t+=encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t}function VJ(e){let t={},n=e.split("&");for(let r=0,o=n.length;r0);return t}function $A(){const e=J2(+new Date);return e!==Q2?(q2=0,Q2=e):e+"."+J2(q2++)}for(;xp{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)};MJ(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,OJ(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]=$A()),!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 Vo(this.uri(),t)}doWrite(t,n){const r=this.request({method:"POST",data:t});r.on("success",n),r.on("error",(o,i)=>{this.onError("xhr post error",o,i)})}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}}class Vo extends Qt{constructor(t,n){super(),hg(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=EA(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");n.xdomain=!!this.opts.xd;const r=this.xhr=new RA(n);try{r.open(this.method,this.uri,!0);try{if(this.opts.extraHeaders){r.setDisableHeaderCheck&&r.setDisableHeaderCheck(!0);for(let o in this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(o)&&r.setRequestHeader(o,this.opts.extraHeaders[o])}}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 o;r.readyState===3&&((o=this.opts.cookieJar)===null||o===void 0||o.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(o){this.setTimeoutFn(()=>{this.onError(o)},0);return}typeof document<"u"&&(this.index=Vo.requestsCount++,Vo.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=YJ,t)try{this.xhr.abort()}catch{}typeof document<"u"&&delete Vo.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()}}Vo.requestsCount=0;Vo.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",e$);else if(typeof addEventListener=="function"){const e="onpagehide"in Br?"pagehide":"unload";addEventListener(e,e$,!1)}}function e$(){for(let e in Vo.requests)Vo.requests.hasOwnProperty(e)&&Vo.requests[e].abort()}const sb=typeof Promise=="function"&&typeof Promise.resolve=="function"?t=>Promise.resolve().then(t):(t,n)=>n(t,0),bp=Br.WebSocket||Br.MozWebSocket,t$=!0,ZJ="arraybuffer",n$=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class qJ extends ib{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=n$?{}:EA(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=t$&&!n$?n?new bp(t,n):new bp(t):new bp(t,n,r)}catch(o){return this.emitReserved("error",o)}this.ws.binaryType=this.socket.binaryType,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{t$&&this.ws.send(i)}catch{}o&&sb(()=>{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]=$A()),this.supportsBinary||(n.b64=1),this.createUri(t,n)}check(){return!!bp}}class QJ extends ib{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=DJ(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=t.readable.pipeThrough(n).getReader(),o=NJ();o.readable.pipeTo(t.writable),this.writer=o.writable.getWriter();const i=()=>{r.read().then(({done:l,value:u})=>{l||(this.onPacket(u),i())}).catch(l=>{})};i();const s={type:"open"};this.query.sid&&(s.data=`{"sid":"${this.query.sid}"}`),this.writer.write(s).then(()=>this.onOpen())})}))}write(t){this.writable=!1;for(let n=0;n{o&&sb(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;(t=this.transport)===null||t===void 0||t.close()}}const JJ={websocket:qJ,webtransport:QJ,polling:XJ},eee=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,tee=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Y1(e){if(e.length>2e3)throw"URI too long";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 o=eee.exec(e||""),i={},s=14;for(;s--;)i[tee[s]]=o[s]||"";return n!=-1&&r!=-1&&(i.source=t,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=nee(i,i.path),i.queryKey=ree(i,i.query),i}function nee(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 ree(e,t){const n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(r,o,i){o&&(n[o]=i)}),n}let TA=class sl extends Qt{constructor(t,n={}){super(),this.binaryType=ZJ,this.writeBuffer=[],t&&typeof t=="object"&&(n=t,t=null),t?(t=Y1(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=Y1(n.host).host),hg(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=VJ(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=SA,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 JJ[t](r)}open(){let t;if(this.opts.rememberUpgrade&&sl.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;sl.priorWebsocketSuccess=!1;const o=()=>{r||(n.send([{type:"ping",data:"probe"}]),n.once("packet",m=>{if(!r)if(m.type==="pong"&&m.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",n),!n)return;sl.priorWebsocketSuccess=n.name==="websocket",this.transport.pause(()=>{r||this.readyState!=="closed"&&(h(),this.setTransport(n),n.send([{type:"upgrade"}]),this.emitReserved("upgrade",n),n=null,this.upgrading=!1,this.flush())})}else{const g=new Error("probe error");g.transport=n.name,this.emitReserved("upgradeError",g)}}))};function i(){r||(r=!0,h(),n.close(),n=null)}const s=m=>{const g=new Error("probe error: "+m);g.transport=n.name,i(),this.emitReserved("upgradeError",g)};function l(){s("transport closed")}function u(){s("socket closed")}function d(m){n&&m.name!==n.name&&i()}const h=()=>{n.removeListener("open",o),n.removeListener("error",s),n.removeListener("close",l),this.off("close",u),this.off("upgrading",d)};n.once("open",o),n.once("error",s),n.once("close",l),this.once("close",u),this.once("upgrading",d),this.upgrades.indexOf("webtransport")!==-1&&t!=="webtransport"?this.setTimeoutFn(()=>{r||n.open()},200):n.open()}onOpen(){if(this.readyState="open",sl.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,o){if(typeof n=="function"&&(o=n,n=void 0),typeof r=="function"&&(o=r,r=null),this.readyState==="closing"||this.readyState==="closed")return;r=r||{},r.compress=r.compress!==!1;const i={type:t,data:n,options:r};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),o&&this.once("flush",o),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){sl.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 o=t.length;for(;rtypeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,PA=Object.prototype.toString,aee=typeof Blob=="function"||typeof Blob<"u"&&PA.call(Blob)==="[object BlobConstructor]",lee=typeof File=="function"||typeof File<"u"&&PA.call(File)==="[object FileConstructor]";function ab(e){return iee&&(e instanceof ArrayBuffer||see(e))||aee&&e instanceof Blob||lee&&e instanceof File}function nh(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(i),n.apply(this,[null,...s])}}emitWithAck(t,...n){const r=this.flags.timeout!==void 0||this._opts.ackTimeout!==void 0;return new Promise((o,i)=>{n.push((s,l)=>r?s?i(s):o(l):o(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((o,...i)=>r!==this._queue[0]?void 0:(o!==null?r.tryCount>this._opts.retries&&(this._queue.shift(),n&&n(o)):(this._queue.shift(),n&&n(null,...i)),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:lt.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 lt.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 lt.EVENT:case lt.BINARY_EVENT:this.onevent(t);break;case lt.ACK:case lt.BINARY_ACK:this.onack(t);break;case lt.DISCONNECT:this.ondisconnect();break;case lt.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(...o){r||(r=!0,n.packet({type:lt.ACK,id:t,data:o}))}}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:lt.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}Cc.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};Cc.prototype.reset=function(){this.attempts=0};Cc.prototype.setMin=function(e){this.ms=e};Cc.prototype.setMax=function(e){this.max=e};Cc.prototype.setJitter=function(e){this.jitter=e};class Z1 extends Qt{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,hg(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 Cc({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(n.timeout==null?2e4:n.timeout),this._readyState="closed",this.uri=t;const o=n.parser||mee;this.encoder=new o.Encoder,this.decoder=new o.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 TA(this.uri,this.opts);const n=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;const o=fo(n,"open",function(){r.onopen(),t&&t()}),i=l=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",l),t?t(l):this.maybeReconnectOnOpen()},s=fo(n,"error",i);if(this._timeout!==!1){const l=this._timeout,u=this.setTimeoutFn(()=>{o(),i(new Error("timeout")),n.close()},l);this.opts.autoUnref&&u.unref(),this.subs.push(()=>{this.clearTimeoutFn(u)})}return this.subs.push(o),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(fo(t,"ping",this.onping.bind(this)),fo(t,"data",this.ondata.bind(this)),fo(t,"error",this.onerror.bind(this)),fo(t,"close",this.onclose.bind(this)),fo(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){sb(()=>{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 AA(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(o=>{o?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",o)):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 cu={};function rh(e,t){typeof e=="object"&&(t=e,e=void 0),t=t||{};const n=oee(e,t.path||"/socket.io"),r=n.source,o=n.id,i=n.path,s=cu[o]&&i in cu[o].nsps,l=t.forceNew||t["force new connection"]||t.multiplex===!1||s;let u;return l?u=new Z1(r,t):(cu[o]||(cu[o]=new Z1(r,t)),u=cu[o]),n.query&&!t.query&&(t.query=n.queryKey),u.socket(n.path,t)}Object.assign(rh,{Manager:Z1,Socket:AA,io:rh,connect:rh});const OA="Progress",mg=100,[vee,Rte]=An(OA),[yee,wee]=vee(OA),MA=f.forwardRef((e,t)=>{const{__scopeProgress:n,value:r,max:o,getValueLabel:i=_ee,...s}=e,l=q1(o)?o:mg,u=DA(r,l)?r:null,d=im(u)?i(u,l):void 0;return f.createElement(yee,{scope:n,value:u,max:l},f.createElement(Pe.div,Y({"aria-valuemax":l,"aria-valuemin":0,"aria-valuenow":im(u)?u:void 0,"aria-valuetext":d,role:"progressbar","data-state":NA(u,l),"data-value":u??void 0,"data-max":l},s,{ref:t})))});MA.propTypes={max(e,t,n){const r=e[t],o=String(r);return r&&!q1(r)?new Error(See(o,n)):null},value(e,t,n){const r=e[t],o=String(r),i=q1(e.max)?e.max:mg;return r!=null&&!DA(r,i)?new Error(Eee(o,n)):null}};const xee="ProgressIndicator",bee=f.forwardRef((e,t)=>{var n;const{__scopeProgress:r,...o}=e,i=wee(xee,r);return f.createElement(Pe.div,Y({"data-state":NA(i.value,i.max),"data-value":(n=i.value)!==null&&n!==void 0?n:void 0,"data-max":i.max},o,{ref:t}))});function _ee(e,t){return`${Math.round(e/t*100)}%`}function NA(e,t){return e==null?"indeterminate":e===t?"complete":"loading"}function im(e){return typeof e=="number"}function q1(e){return im(e)&&!isNaN(e)&&e>0}function DA(e,t){return im(e)&&!isNaN(e)&&e<=t&&e>=0}function See(e,t){return`Invalid prop \`max\` of value \`${e}\` supplied to \`${t}\`. Only numbers greater than 0 are valid max values. Defaulting to \`${mg}\`.`}function Eee(e,t){return`Invalid prop \`value\` of value \`${e}\` supplied to \`${t}\`. The \`value\` prop must be: + - a positive number + - less than the value passed to \`max\` (or ${mg} if no \`max\` prop is set) + - \`null\` if the progress is indeterminate. + +Defaulting to \`null\`.`}const IA=MA,Cee=bee,LA=f.forwardRef(({className:e,value:t,...n},r)=>v.jsx(IA,{ref:r,className:Ce("relative h-2 w-full overflow-hidden rounded-full bg-primary/20",e),...n,children:v.jsx(Cee,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(t||0)}%)`}})}));LA.displayName=IA.displayName;const $ee="",Vi=rh($ee),kee=()=>{const[e,t,n]=bt(u=>[u.settings,u.isInpainting,u.isSD()]),[r,o]=f.useState(!1),[i,s]=f.useState(0),l=Math.min(Math.round(i/e.sdSteps*100),100);return f.useEffect(()=>{if(n)return Vi.on("connect",()=>{o(!0)}),Vi.on("disconnect",()=>{o(!1)}),Vi.on("diffusion_progress",u=>{u&&s(u.step+1)}),Vi.on("diffusion_finish",()=>{s(0)}),()=>{Vi.off("connect"),Vi.off("disconnect"),Vi.off("diffusion_progress"),Vi.off("diffusion_finish")}},[n]),v.jsxs("div",{className:"z-10 fixed bg-background w-[220px] left-1/2 -translate-x-1/2 top-[68px] h-[32px] flex justify-center items-center gap-[18px] border-[1px] border-[solid] rounded-[14px] pl-[8px] pr-[8px]",style:{visibility:r&&t&&n?"visible":"hidden"},children:[v.jsx(LA,{value:l}),v.jsxs("div",{className:"w-[45px] flex justify-center font-nums",children:[l,"%"]})]})},Ree=()=>{const[e,t]=bt(n=>[n.file,n.updateSettings]);return f.useEffect(()=>{(async()=>{const r=await jj();t({model:r})})()},[]),v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"flex gap-3 absolute top-[68px] left-[24px] items-center",children:[v.jsx(vJ,{}),v.jsx(qq,{})]}),v.jsx(Wq,{}),v.jsx(kee,{}),v.jsx(kJ,{}),e?v.jsx(Zq,{file:e}):v.jsx(v.Fragment,{})]})},Tee=()=>{const[e,t]=f.useState(window.innerWidth),n=f.useCallback(()=>{t(window.innerWidth)},[]);if(f.useEffect(()=>(window.addEventListener("resize",n),()=>{window.removeEventListener("resize",n)})),e<768)return"mobile";if(e>=768&&e<1224)return"tablet";if(e>=1224)return"desktop"};function Pee(e){const{onSelection:t}=e,[n]=f.useState(`file-upload-${Math.random().toString()}`),r=Tee();function o(i){if(!(!i||!i.type.match("image.*")))try{if(i.size>20*1024*1024)throw new Error("file too large");t(i)}catch(l){alert(`error: ${l.message}`)}}return v.jsx("div",{className:"absolute flex w-screen h-screen justify-center items-center pointer-events-none",children:v.jsx("label",{htmlFor:n,className:"grid bg-background border-[2px] border-[dashed] rounded-lg min-w-[600px] hover:bg-primary hover:text-primary-foreground pointer-events-auto",children:v.jsxs("div",{className:"grid p-16 w-full h-full",onDragOver:i=>{i.stopPropagation(),i.preventDefault()},children:[v.jsx("input",{className:"hidden",id:n,name:n,type:"file",onChange:i=>{var l;const s=(l=i.currentTarget.files)==null?void 0:l[0];s&&o(s)},accept:"image/png, image/jpeg"}),v.jsx("p",{className:"text-center",children:r==="desktop"?"Click here or drag an image file":"Tap here to load your picture"})]})})})}const FA="ToastProvider",[cb,Aee,Oee]=zd("Toast"),[jA,Tte]=An("Toast",[Oee]),[Mee,gg]=jA(FA),zA=e=>{const{__scopeToast:t,label:n="Notification",duration:r=5e3,swipeDirection:o="right",swipeThreshold:i=50,children:s}=e,[l,u]=f.useState(null),[d,h]=f.useState(0),m=f.useRef(!1),g=f.useRef(!1);return f.createElement(cb.Provider,{scope:t},f.createElement(Mee,{scope:t,label:n,duration:r,swipeDirection:o,swipeThreshold:i,toastCount:d,viewport:l,onViewportChange:u,onToastAdd:f.useCallback(()=>h(y=>y+1),[]),onToastRemove:f.useCallback(()=>h(y=>y-1),[]),isFocusedToastEscapeKeyDownRef:m,isClosePausedRef:g},s))};zA.propTypes={label(e){if(e.label&&typeof e.label=="string"&&!e.label.trim()){const t=`Invalid prop \`label\` supplied to \`${FA}\`. Expected non-empty \`string\`.`;return new Error(t)}return null}};const Nee="ToastViewport",Dee=["F8"],Q1="toast.viewportPause",J1="toast.viewportResume",Iee=f.forwardRef((e,t)=>{const{__scopeToast:n,hotkey:r=Dee,label:o="Notifications ({hotkey})",...i}=e,s=gg(Nee,n),l=Aee(n),u=f.useRef(null),d=f.useRef(null),h=f.useRef(null),m=f.useRef(null),g=Be(t,m,s.onViewportChange),y=r.join("+").replace(/Key/g,"").replace(/Digit/g,""),x=s.toastCount>0;f.useEffect(()=>{const C=S=>{var b;r.every(k=>S[k]||S.code===k)&&((b=m.current)===null||b===void 0||b.focus())};return document.addEventListener("keydown",C),()=>document.removeEventListener("keydown",C)},[r]),f.useEffect(()=>{const C=u.current,S=m.current;if(x&&C&&S){const b=()=>{if(!s.isClosePausedRef.current){const M=new CustomEvent(Q1);S.dispatchEvent(M),s.isClosePausedRef.current=!0}},E=()=>{if(s.isClosePausedRef.current){const M=new CustomEvent(J1);S.dispatchEvent(M),s.isClosePausedRef.current=!1}},k=M=>{!C.contains(M.relatedTarget)&&E()},P=()=>{C.contains(document.activeElement)||E()};return C.addEventListener("focusin",b),C.addEventListener("focusout",k),C.addEventListener("pointermove",b),C.addEventListener("pointerleave",P),window.addEventListener("blur",b),window.addEventListener("focus",E),()=>{C.removeEventListener("focusin",b),C.removeEventListener("focusout",k),C.removeEventListener("pointermove",b),C.removeEventListener("pointerleave",P),window.removeEventListener("blur",b),window.removeEventListener("focus",E)}}},[x,s.isClosePausedRef]);const _=f.useCallback(({tabbingDirection:C})=>{const b=l().map(E=>{const k=E.ref.current,P=[k,...Qee(k)];return C==="forwards"?P:P.reverse()});return(C==="forwards"?b.reverse():b).flat()},[l]);return f.useEffect(()=>{const C=m.current;if(C){const S=b=>{const E=b.altKey||b.ctrlKey||b.metaKey;if(b.key==="Tab"&&!E){const O=document.activeElement,F=b.shiftKey;if(b.target===C&&F){var P;(P=d.current)===null||P===void 0||P.focus();return}const G=_({tabbingDirection:F?"backwards":"forwards"}),ae=G.findIndex(U=>U===O);if(j0(G.slice(ae+1)))b.preventDefault();else{var M,A;F?(M=d.current)===null||M===void 0||M.focus():(A=h.current)===null||A===void 0||A.focus()}}};return C.addEventListener("keydown",S),()=>C.removeEventListener("keydown",S)}},[l,_]),f.createElement(_B,{ref:u,role:"region","aria-label":o.replace("{hotkey}",y),tabIndex:-1,style:{pointerEvents:x?void 0:"none"}},x&&f.createElement(o$,{ref:d,onFocusFromOutsideViewport:()=>{const C=_({tabbingDirection:"forwards"});j0(C)}}),f.createElement(cb.Slot,{scope:n},f.createElement(Pe.ol,Y({tabIndex:-1},i,{ref:g}))),x&&f.createElement(o$,{ref:h,onFocusFromOutsideViewport:()=>{const C=_({tabbingDirection:"backwards"});j0(C)}}))}),Lee="ToastFocusProxy",o$=f.forwardRef((e,t)=>{const{__scopeToast:n,onFocusFromOutsideViewport:r,...o}=e,i=gg(Lee,n);return f.createElement(Um,Y({"aria-hidden":!0,tabIndex:0},o,{ref:t,style:{position:"fixed"},onFocus:s=>{var l;const u=s.relatedTarget;!((l=i.viewport)!==null&&l!==void 0&&l.contains(u))&&r()}}))}),vg="Toast",Fee="toast.swipeStart",jee="toast.swipeMove",zee="toast.swipeCancel",Bee="toast.swipeEnd",Uee=f.forwardRef((e,t)=>{const{forceMount:n,open:r,defaultOpen:o,onOpenChange:i,...s}=e,[l=!0,u]=Zr({prop:r,defaultProp:o,onChange:i});return f.createElement(xn,{present:n||l},f.createElement(BA,Y({open:l},s,{ref:t,onClose:()=>u(!1),onPause:Ft(e.onPause),onResume:Ft(e.onResume),onSwipeStart:ue(e.onSwipeStart,d=>{d.currentTarget.setAttribute("data-swipe","start")}),onSwipeMove:ue(e.onSwipeMove,d=>{const{x:h,y:m}=d.detail.delta;d.currentTarget.setAttribute("data-swipe","move"),d.currentTarget.style.setProperty("--radix-toast-swipe-move-x",`${h}px`),d.currentTarget.style.setProperty("--radix-toast-swipe-move-y",`${m}px`)}),onSwipeCancel:ue(e.onSwipeCancel,d=>{d.currentTarget.setAttribute("data-swipe","cancel"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),d.currentTarget.style.removeProperty("--radix-toast-swipe-end-x"),d.currentTarget.style.removeProperty("--radix-toast-swipe-end-y")}),onSwipeEnd:ue(e.onSwipeEnd,d=>{const{x:h,y:m}=d.detail.delta;d.currentTarget.setAttribute("data-swipe","end"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),d.currentTarget.style.setProperty("--radix-toast-swipe-end-x",`${h}px`),d.currentTarget.style.setProperty("--radix-toast-swipe-end-y",`${m}px`),u(!1)})})))}),[Vee,Wee]=jA(vg,{onClose(){}}),BA=f.forwardRef((e,t)=>{const{__scopeToast:n,type:r="foreground",duration:o,open:i,onClose:s,onEscapeKeyDown:l,onPause:u,onResume:d,onSwipeStart:h,onSwipeMove:m,onSwipeCancel:g,onSwipeEnd:y,...x}=e,_=gg(vg,n),[C,S]=f.useState(null),b=Be(t,U=>S(U)),E=f.useRef(null),k=f.useRef(null),P=o||_.duration,M=f.useRef(0),A=f.useRef(P),O=f.useRef(0),{onToastAdd:F,onToastRemove:V}=_,J=Ft(()=>{var U;(C==null?void 0:C.contains(document.activeElement))&&((U=_.viewport)===null||U===void 0||U.focus()),s()}),G=f.useCallback(U=>{!U||U===1/0||(window.clearTimeout(O.current),M.current=new Date().getTime(),O.current=window.setTimeout(J,U))},[J]);f.useEffect(()=>{const U=_.viewport;if(U){const te=()=>{G(A.current),d==null||d()},L=()=>{const ie=new Date().getTime()-M.current;A.current=A.current-ie,window.clearTimeout(O.current),u==null||u()};return U.addEventListener(Q1,L),U.addEventListener(J1,te),()=>{U.removeEventListener(Q1,L),U.removeEventListener(J1,te)}}},[_.viewport,P,u,d,G]),f.useEffect(()=>{i&&!_.isClosePausedRef.current&&G(P)},[i,P,_.isClosePausedRef,G]),f.useEffect(()=>(F(),()=>V()),[F,V]);const ae=f.useMemo(()=>C?HA(C):null,[C]);return _.viewport?f.createElement(f.Fragment,null,ae&&f.createElement(Hee,{__scopeToast:n,role:"status","aria-live":r==="foreground"?"assertive":"polite","aria-atomic":!0},ae),f.createElement(Vee,{scope:n,onClose:J},Os.createPortal(f.createElement(cb.ItemSlot,{scope:n},f.createElement(bB,{asChild:!0,onEscapeKeyDown:ue(l,()=>{_.isFocusedToastEscapeKeyDownRef.current||J(),_.isFocusedToastEscapeKeyDownRef.current=!1})},f.createElement(Pe.li,Y({role:"status","aria-live":"off","aria-atomic":!0,tabIndex:0,"data-state":i?"open":"closed","data-swipe-direction":_.swipeDirection},x,{ref:b,style:{userSelect:"none",touchAction:"none",...e.style},onKeyDown:ue(e.onKeyDown,U=>{U.key==="Escape"&&(l==null||l(U.nativeEvent),U.nativeEvent.defaultPrevented||(_.isFocusedToastEscapeKeyDownRef.current=!0,J()))}),onPointerDown:ue(e.onPointerDown,U=>{U.button===0&&(E.current={x:U.clientX,y:U.clientY})}),onPointerMove:ue(e.onPointerMove,U=>{if(!E.current)return;const te=U.clientX-E.current.x,L=U.clientY-E.current.y,ie=!!k.current,K=["left","right"].includes(_.swipeDirection),Q=["left","up"].includes(_.swipeDirection)?Math.min:Math.max,W=K?Q(0,te):0,le=K?0:Q(0,L),ge=U.pointerType==="touch"?10:2,Ve={x:W,y:le},Ue={originalEvent:U,delta:Ve};ie?(k.current=Ve,_p(jee,m,Ue,{discrete:!1})):i$(Ve,_.swipeDirection,ge)?(k.current=Ve,_p(Fee,h,Ue,{discrete:!1}),U.target.setPointerCapture(U.pointerId)):(Math.abs(te)>ge||Math.abs(L)>ge)&&(E.current=null)}),onPointerUp:ue(e.onPointerUp,U=>{const te=k.current,L=U.target;if(L.hasPointerCapture(U.pointerId)&&L.releasePointerCapture(U.pointerId),k.current=null,E.current=null,te){const ie=U.currentTarget,K={originalEvent:U,delta:te};i$(te,_.swipeDirection,_.swipeThreshold)?_p(Bee,y,K,{discrete:!0}):_p(zee,g,K,{discrete:!0}),ie.addEventListener("click",Q=>Q.preventDefault(),{once:!0})}})})))),_.viewport))):null});BA.propTypes={type(e){if(e.type&&!["foreground","background"].includes(e.type)){const t=`Invalid prop \`type\` supplied to \`${vg}\`. Expected \`foreground | background\`.`;return new Error(t)}return null}};const Hee=e=>{const{__scopeToast:t,children:n,...r}=e,o=gg(vg,t),[i,s]=f.useState(!1),[l,u]=f.useState(!1);return Zee(()=>s(!0)),f.useEffect(()=>{const d=window.setTimeout(()=>u(!0),1e3);return()=>window.clearTimeout(d)},[]),l?null:f.createElement(Md,{asChild:!0},f.createElement(Um,r,i&&f.createElement(f.Fragment,null,o.label," ",n)))},Kee=f.forwardRef((e,t)=>{const{__scopeToast:n,...r}=e;return f.createElement(Pe.div,Y({},r,{ref:t}))}),Yee=f.forwardRef((e,t)=>{const{__scopeToast:n,...r}=e;return f.createElement(Pe.div,Y({},r,{ref:t}))}),Gee="ToastAction",UA=f.forwardRef((e,t)=>{const{altText:n,...r}=e;return n?f.createElement(WA,{altText:n,asChild:!0},f.createElement(VA,Y({},r,{ref:t}))):null});UA.propTypes={altText(e){return e.altText?null:new Error(`Missing prop \`altText\` expected on \`${Gee}\``)}};const Xee="ToastClose",VA=f.forwardRef((e,t)=>{const{__scopeToast:n,...r}=e,o=Wee(Xee,n);return f.createElement(WA,{asChild:!0},f.createElement(Pe.button,Y({type:"button"},r,{ref:t,onClick:ue(e.onClick,o.onClose)})))}),WA=f.forwardRef((e,t)=>{const{__scopeToast:n,altText:r,...o}=e;return f.createElement(Pe.div,Y({"data-radix-toast-announce-exclude":"","data-radix-toast-announce-alt":r||void 0},o,{ref:t}))});function HA(e){const t=[];return Array.from(e.childNodes).forEach(r=>{if(r.nodeType===r.TEXT_NODE&&r.textContent&&t.push(r.textContent),qee(r)){const o=r.ariaHidden||r.hidden||r.style.display==="none",i=r.dataset.radixToastAnnounceExclude==="";if(!o)if(i){const s=r.dataset.radixToastAnnounceAlt;s&&t.push(s)}else t.push(...HA(r))}}),t}function _p(e,t,n,{discrete:r}){const o=n.originalEvent.currentTarget,i=new CustomEvent(e,{bubbles:!0,cancelable:!0,detail:n});t&&o.addEventListener(e,t,{once:!0}),r?cx(o,i):o.dispatchEvent(i)}const i$=(e,t,n=0)=>{const r=Math.abs(e.x),o=Math.abs(e.y),i=r>o;return t==="left"||t==="right"?i&&r>n:!i&&o>n};function Zee(e=()=>{}){const t=Ft(e);Pn(()=>{let n=0,r=0;return n=window.requestAnimationFrame(()=>r=window.requestAnimationFrame(t)),()=>{window.cancelAnimationFrame(n),window.cancelAnimationFrame(r)}},[t])}function qee(e){return e.nodeType===e.ELEMENT_NODE}function Qee(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const o=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||o?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function j0(e){const t=document.activeElement;return e.some(n=>n===t?!0:(n.focus(),document.activeElement!==t))}const Jee=zA,KA=Iee,YA=Uee,GA=Kee,XA=Yee,ZA=UA,qA=VA,ete=Jee,QA=f.forwardRef(({className:e,...t},n)=>v.jsx(KA,{ref:n,className:Ce("fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]",e),tabIndex:-1,...t}));QA.displayName=KA.displayName;const tte=Om("group pointer-events-auto relative flex w-full items-center justify-between space-x-2 overflow-hidden rounded-md border p-4 pr-6 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full",{variants:{variant:{default:"border bg-background text-foreground",destructive:"destructive group border-destructive bg-destructive text-destructive-foreground"}},defaultVariants:{variant:"default"}}),JA=f.forwardRef(({className:e,variant:t,...n},r)=>v.jsx(YA,{ref:r,className:Ce(tte({variant:t}),e),tabIndex:-1,...n}));JA.displayName=YA.displayName;const nte=f.forwardRef(({className:e,...t},n)=>v.jsx(ZA,{ref:n,className:Ce("inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium transition-colors hover:bg-secondary focus:outline-none focus:ring-1 focus:ring-ring disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive",e),tabIndex:-1,...t}));nte.displayName=ZA.displayName;const eO=f.forwardRef(({className:e,...t},n)=>v.jsx(qA,{ref:n,className:Ce("absolute right-1 top-1 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-1 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600",e),"toast-close":"",tabIndex:-1,...t,children:v.jsx(yT,{className:"h-4 w-4"})}));eO.displayName=qA.displayName;const tO=f.forwardRef(({className:e,...t},n)=>v.jsx(GA,{ref:n,className:Ce("text-sm font-semibold [&+div]:text-xs",e),tabIndex:-1,...t}));tO.displayName=GA.displayName;const nO=f.forwardRef(({className:e,...t},n)=>v.jsx(XA,{ref:n,className:Ce("text-sm opacity-90",e),...t,tabIndex:-1}));nO.displayName=XA.displayName;function rte(){const{toasts:e}=Td();return v.jsxs(ete,{children:[e.map(function({id:t,title:n,description:r,action:o,...i}){return v.jsxs(JA,{...i,children:[v.jsxs("div",{className:"grid gap-1",children:[n&&v.jsx(tO,{children:n}),r&&v.jsx(nO,{children:r})]}),o,v.jsx(eO,{})]},t)}),v.jsx(QA,{})]})}const ote=["image/jpeg","image/png","image/webp","image/bmp","image/tiff"];function ite(){const[e,t,n,r]=bt(g=>[g.file,g.updateAppState,g.setServerConfig,g.setFile]),o=Kj(),i=vH();f.useEffect(()=>{o&&r(o)},[o,r]),f.useEffect(()=>{t({windowSize:i})},[i]),f.useEffect(()=>{(async()=>{const y=await Lj();n(y),y.isDesktop&&uF()})()},[]);const s=f.useRef(0),l=f.useCallback(g=>{g.preventDefault(),g.stopPropagation()},[]),u=f.useCallback(g=>{g.preventDefault(),g.stopPropagation(),s.current+=1},[]),d=f.useCallback(g=>{g.preventDefault(),g.stopPropagation(),s.current-=1,s.current>0},[]),h=f.useCallback(g=>{if(g.preventDefault(),g.stopPropagation(),g.dataTransfer.files&&g.dataTransfer.files.length>0){if(!(g.dataTransfer.files.length>1)){const y=g.dataTransfer.files[0],x=y.type;ote.includes(x)&&r(y)}g.dataTransfer.clearData()}},[]),m=f.useCallback(g=>{if(!g.clipboardData)return;const y=g.clipboardData.items,x=[].slice.call(y).filter(S=>S.type.indexOf("image")!==-1);if(x.length===0)return;g.preventDefault(),g.stopPropagation();const C=x[0].getAsFile();C&&r(C)},[]);return f.useEffect(()=>(window.addEventListener("dragenter",u),window.addEventListener("dragleave",d),window.addEventListener("dragover",l),window.addEventListener("drop",h),window.addEventListener("paste",m),function(){window.removeEventListener("dragenter",u),window.removeEventListener("dragleave",d),window.removeEventListener("dragover",l),window.removeEventListener("drop",h),window.removeEventListener("paste",m)})),v.jsxs("main",{className:"flex min-h-screen flex-col items-center justify-between w-full bg-[radial-gradient(circle_at_1px_1px,_#8e8e8e8e_1px,_transparent_0)] [background-size:20px_20px] bg-repeat",children:[v.jsx(rte,{}),v.jsx(nZ,{}),v.jsx(Ree,{}),e?v.jsx(v.Fragment,{}):v.jsx(Pee,{onSelection:async g=>{r(g)}})]})}const sm=["light","dark"],ub="(prefers-color-scheme: dark)",ste=typeof window>"u",rO=f.createContext(void 0),ate=e=>f.useContext(rO)?Fe.createElement(f.Fragment,null,e.children):Fe.createElement(cte,e),lte=["light","dark"],cte=({forcedTheme:e,disableTransitionOnChange:t=!1,enableSystem:n=!0,enableColorScheme:r=!0,storageKey:o="theme",themes:i=lte,defaultTheme:s=n?"system":"light",attribute:l="data-theme",value:u,children:d,nonce:h})=>{const[m,g]=f.useState(()=>s$(o,s)),[y,x]=f.useState(()=>s$(o)),_=u?Object.values(u):i,C=f.useCallback(k=>{let P=k;if(!P)return;k==="system"&&n&&(P=a$());const M=u?u[P]:P,A=t?dte():null,O=document.documentElement;if(l==="class"?(O.classList.remove(..._),M&&O.classList.add(M)):M?O.setAttribute(l,M):O.removeAttribute(l),r){const F=sm.includes(s)?s:null,V=sm.includes(P)?P:F;O.style.colorScheme=V}A==null||A()},[]),S=f.useCallback(k=>{g(k);try{localStorage.setItem(o,k)}catch{}},[e]),b=f.useCallback(k=>{const P=a$(k);x(P),m==="system"&&n&&!e&&C("system")},[m,e]);f.useEffect(()=>{const k=window.matchMedia(ub);return k.addListener(b),b(k),()=>k.removeListener(b)},[b]),f.useEffect(()=>{const k=P=>{P.key===o&&S(P.newValue||s)};return window.addEventListener("storage",k),()=>window.removeEventListener("storage",k)},[S]),f.useEffect(()=>{C(e??m)},[e,m]);const E=f.useMemo(()=>({theme:m,setTheme:S,forcedTheme:e,resolvedTheme:m==="system"?y:m,themes:n?[...i,"system"]:i,systemTheme:n?y:void 0}),[m,S,e,y,n,i]);return Fe.createElement(rO.Provider,{value:E},Fe.createElement(ute,{forcedTheme:e,disableTransitionOnChange:t,enableSystem:n,enableColorScheme:r,storageKey:o,themes:i,defaultTheme:s,attribute:l,value:u,children:d,attrs:_,nonce:h}),d)},ute=f.memo(({forcedTheme:e,storageKey:t,attribute:n,enableSystem:r,enableColorScheme:o,defaultTheme:i,value:s,attrs:l,nonce:u})=>{const d=i==="system",h=n==="class"?`var d=document.documentElement,c=d.classList;c.remove(${l.map(x=>`'${x}'`).join(",")});`:`var d=document.documentElement,n='${n}',s='setAttribute';`,m=o?sm.includes(i)&&i?`if(e==='light'||e==='dark'||!e)d.style.colorScheme=e||'${i}'`:"if(e==='light'||e==='dark')d.style.colorScheme=e":"",g=(x,_=!1,C=!0)=>{const S=s?s[x]:x,b=_?x+"|| ''":`'${S}'`;let E="";return o&&C&&!_&&sm.includes(x)&&(E+=`d.style.colorScheme = '${x}';`),n==="class"?E+=_||S?`c.add(${b})`:"null":S&&(E+=`d[s](n,${b})`),E},y=e?`!function(){${h}${g(e)}}()`:r?`!function(){try{${h}var e=localStorage.getItem('${t}');if('system'===e||(!e&&${d})){var t='${ub}',m=window.matchMedia(t);if(m.media!==t||m.matches){${g("dark")}}else{${g("light")}}}else if(e){${s?`var x=${JSON.stringify(s)};`:""}${g(s?"x[e]":"e",!0)}}${d?"":"else{"+g(i,!1,!1)+"}"}${m}}catch(e){}}()`:`!function(){try{${h}var e=localStorage.getItem('${t}');if(e){${s?`var x=${JSON.stringify(s)};`:""}${g(s?"x[e]":"e",!0)}}else{${g(i,!1,!1)};}${m}}catch(t){}}();`;return Fe.createElement("script",{nonce:u,dangerouslySetInnerHTML:{__html:y}})},()=>!0),s$=(e,t)=>{if(ste)return;let n;try{n=localStorage.getItem(e)||void 0}catch{}return n||t},dte=()=>{const e=document.createElement("style");return e.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(e),()=>{window.getComputedStyle(document.body),setTimeout(()=>{document.head.removeChild(e)},1)}},a$=e=>(e||(e=window.matchMedia(ub)),e.matches?"dark":"light"),fte=new dL;z0.createRoot(document.getElementById("root")).render(v.jsx(Fe.StrictMode,{children:v.jsx(gL,{client:fte,children:v.jsx(ate,{defaultTheme:"dark",disableTransitionOnChange:!0,children:v.jsx(BU,{children:v.jsx(ite,{})})})})})); diff --git a/py/iopaint/web_app/assets/index-CXO-mkQB.js b/py/iopaint/web_app/assets/index-CXO-mkQB.js new file mode 100644 index 0000000..ef6cf80 --- /dev/null +++ b/py/iopaint/web_app/assets/index-CXO-mkQB.js @@ -0,0 +1,165 @@ +var Nv=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)};var z=(e,t,n)=>(Nv(e,t,"read from private field"),n?n.call(e):t.get(e)),Te=(e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)},ye=(e,t,n,r)=>(Nv(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n);var Ff=(e,t,n,r)=>({set _(o){ye(e,t,o,n)},get _(){return z(e,t,r)}}),tt=(e,t,n)=>(Nv(e,t,"access private method"),n);function SD(e,t){for(var n=0;nr[o]})}}}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 o of document.querySelectorAll('link[rel="modulepreload"]'))r(o);new MutationObserver(o=>{for(const i of o)if(i.type==="childList")for(const s of i.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&r(s)}).observe(document,{childList:!0,subtree:!0});function n(o){const i={};return o.integrity&&(i.integrity=o.integrity),o.referrerPolicy&&(i.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?i.credentials="include":o.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(o){if(o.ep)return;o.ep=!0;const i=n(o);fetch(o.href,i)}})();var Yc=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function lm(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var v$={exports:{}},cm={},y$={exports:{}},it={};/** + * @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 bd=Symbol.for("react.element"),ED=Symbol.for("react.portal"),CD=Symbol.for("react.fragment"),$D=Symbol.for("react.strict_mode"),kD=Symbol.for("react.profiler"),RD=Symbol.for("react.provider"),TD=Symbol.for("react.context"),PD=Symbol.for("react.forward_ref"),AD=Symbol.for("react.suspense"),OD=Symbol.for("react.memo"),MD=Symbol.for("react.lazy"),LS=Symbol.iterator;function ND(e){return e===null||typeof e!="object"?null:(e=LS&&e[LS]||e["@@iterator"],typeof e=="function"?e:null)}var w$={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},x$=Object.assign,b$={};function fc(e,t,n){this.props=e,this.context=t,this.refs=b$,this.updater=n||w$}fc.prototype.isReactComponent={};fc.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")};fc.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function _$(){}_$.prototype=fc.prototype;function ew(e,t,n){this.props=e,this.context=t,this.refs=b$,this.updater=n||w$}var tw=ew.prototype=new _$;tw.constructor=ew;x$(tw,fc.prototype);tw.isPureReactComponent=!0;var FS=Array.isArray,S$=Object.prototype.hasOwnProperty,nw={current:null},E$={key:!0,ref:!0,__self:!0,__source:!0};function C$(e,t,n){var r,o={},i=null,s=null;if(t!=null)for(r in t.ref!==void 0&&(s=t.ref),t.key!==void 0&&(i=""+t.key),t)S$.call(t,r)&&!E$.hasOwnProperty(r)&&(o[r]=t[r]);var l=arguments.length-2;if(l===1)o.children=n;else if(1>>1,ge=K[le];if(0>>1;leo(We,W))Meo(fe,We)?(K[le]=fe,K[Me]=W,le=Me):(K[le]=We,K[Ue]=W,le=Ue);else if(Meo(fe,W))K[le]=fe,K[Me]=W,le=Me;else break e}}return Q}function o(K,Q){var W=K.sortIndex-Q.sortIndex;return W!==0?W:K.id-Q.id}if(typeof performance=="object"&&typeof performance.now=="function"){var i=performance;e.unstable_now=function(){return i.now()}}else{var s=Date,l=s.now();e.unstable_now=function(){return s.now()-l}}var u=[],d=[],h=1,m=null,g=3,y=!1,x=!1,_=!1,C=typeof setTimeout=="function"?setTimeout:null,S=typeof clearTimeout=="function"?clearTimeout:null,b=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function E(K){for(var Q=n(d);Q!==null;){if(Q.callback===null)r(d);else if(Q.startTime<=K)r(d),Q.sortIndex=Q.expirationTime,t(u,Q);else break;Q=n(d)}}function k(K){if(_=!1,E(K),!x)if(n(u)!==null)x=!0,L(P);else{var Q=n(d);Q!==null&&ie(k,Q.startTime-K)}}function P(K,Q){x=!1,_&&(_=!1,S(O),O=-1),y=!0;var W=g;try{for(E(Q),m=n(u);m!==null&&(!(m.expirationTime>Q)||K&&!J());){var le=m.callback;if(typeof le=="function"){m.callback=null,g=m.priorityLevel;var ge=le(m.expirationTime<=Q);Q=e.unstable_now(),typeof ge=="function"?m.callback=ge:m===n(u)&&r(u),E(Q)}else r(u);m=n(u)}if(m!==null)var Ve=!0;else{var Ue=n(d);Ue!==null&&ie(k,Ue.startTime-Q),Ve=!1}return Ve}finally{m=null,g=W,y=!1}}var M=!1,A=null,O=-1,F=5,V=-1;function J(){return!(e.unstable_now()-VK||125le?(K.sortIndex=W,t(d,K),n(u)===null&&K===n(d)&&(_?(S(O),O=-1):_=!0,ie(k,W-le))):(K.sortIndex=ge,t(u,K),x||y||(x=!0,L(P))),K},e.unstable_shouldYield=J,e.unstable_wrapCallback=function(K){var Q=g;return function(){var W=g;g=Q;try{return K.apply(this,arguments)}finally{g=W}}}})(T$);R$.exports=T$;var KD=R$.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 P$=f,yr=KD;function ce(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"),B0=Object.prototype.hasOwnProperty,YD=/^[: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]*$/,zS={},BS={};function GD(e){return B0.call(BS,e)?!0:B0.call(zS,e)?!1:YD.test(e)?BS[e]=!0:(zS[e]=!0,!1)}function XD(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 ZD(e,t,n,r){if(t===null||typeof t>"u"||XD(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 Un(e,t,n,r,o,i,s){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=o,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=i,this.removeEmptyString=s}var wn={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){wn[e]=new Un(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];wn[t]=new Un(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){wn[e]=new Un(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){wn[e]=new Un(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){wn[e]=new Un(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){wn[e]=new Un(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){wn[e]=new Un(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){wn[e]=new Un(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){wn[e]=new Un(e,5,!1,e.toLowerCase(),null,!1,!1)});var ow=/[\-:]([a-z])/g;function iw(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(ow,iw);wn[t]=new Un(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(ow,iw);wn[t]=new Un(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(ow,iw);wn[t]=new Un(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){wn[e]=new Un(e,1,!1,e.toLowerCase(),null,!1,!1)});wn.xlinkHref=new Un("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){wn[e]=new Un(e,1,!1,e.toLowerCase(),null,!0,!0)});function sw(e,t,n,r){var o=wn.hasOwnProperty(t)?wn[t]:null;(o!==null?o.type!==0:r||!(2l||o[s]!==i[l]){var u=` +`+o[s].replace(" at new "," at ");return e.displayName&&u.includes("")&&(u=u.replace("",e.displayName)),u}while(1<=s&&0<=l);break}}}finally{Lv=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?uu(e):""}function qD(e){switch(e.tag){case 5:return uu(e.type);case 16:return uu("Lazy");case 13:return uu("Suspense");case 19:return uu("SuspenseList");case 0:case 2:case 15:return e=Fv(e.type,!1),e;case 11:return e=Fv(e.type.render,!1),e;case 1:return e=Fv(e.type,!0),e;default:return""}}function H0(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 ll:return"Fragment";case al:return"Portal";case U0:return"Profiler";case aw:return"StrictMode";case V0:return"Suspense";case W0:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case M$:return(e.displayName||"Context")+".Consumer";case O$:return(e._context.displayName||"Context")+".Provider";case lw:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case cw:return t=e.displayName||null,t!==null?t:H0(e.type)||"Memo";case Ki:t=e._payload,e=e._init;try{return H0(e(t))}catch{}}return null}function QD(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 H0(t);case 8:return t===aw?"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 Ss(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function D$(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function JD(e){var t=D$(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 o=n.get,i=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return o.call(this)},set:function(s){r=""+s,i.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 Bf(e){e._valueTracker||(e._valueTracker=JD(e))}function I$(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=D$(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function oh(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 K0(e,t){var n=t.checked;return zt({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function VS(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=Ss(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 L$(e,t){t=t.checked,t!=null&&sw(e,"checked",t,!1)}function Y0(e,t){L$(e,t);var n=Ss(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")?G0(e,t.type,n):t.hasOwnProperty("defaultValue")&&G0(e,t.type,Ss(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function WS(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 G0(e,t,n){(t!=="number"||oh(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var du=Array.isArray;function bl(e,t,n,r){if(e=e.options,t){t={};for(var o=0;o"+t.valueOf().toString()+"",t=Uf.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function Ou(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var vu={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},e9=["Webkit","ms","Moz","O"];Object.keys(vu).forEach(function(e){e9.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),vu[t]=vu[e]})});function B$(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||vu.hasOwnProperty(e)&&vu[e]?(""+t).trim():t+"px"}function U$(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,o=B$(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,o):e[n]=o}}var t9=zt({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 q0(e,t){if(t){if(t9[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(ce(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(ce(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(ce(61))}if(t.style!=null&&typeof t.style!="object")throw Error(ce(62))}}function Q0(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 J0=null;function uw(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var ey=null,_l=null,Sl=null;function YS(e){if(e=Ed(e)){if(typeof ey!="function")throw Error(ce(280));var t=e.stateNode;t&&(t=hm(t),ey(e.stateNode,e.type,t))}}function V$(e){_l?Sl?Sl.push(e):Sl=[e]:_l=e}function W$(){if(_l){var e=_l,t=Sl;if(Sl=_l=null,YS(e),t)for(e=0;e>>=0,e===0?32:31-(f9(e)/p9|0)|0}var Vf=64,Wf=4194304;function fu(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 lh(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,o=e.suspendedLanes,i=e.pingedLanes,s=n&268435455;if(s!==0){var l=s&~o;l!==0?r=fu(l):(i&=s,i!==0&&(r=fu(i)))}else s=n&~o,s!==0?r=fu(s):i!==0&&(r=fu(i));if(r===0)return 0;if(t!==0&&t!==r&&!(t&o)&&(o=r&-r,i=t&-t,o>=i||o===16&&(i&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 _d(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-go(t),e[t]=n}function v9(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=wu),nE=" ",rE=!1;function uk(e,t){switch(e){case"keyup":return H9.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function dk(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var cl=!1;function Y9(e,t){switch(e){case"compositionend":return dk(t);case"keypress":return t.which!==32?null:(rE=!0,nE);case"textInput":return e=t.data,e===nE&&rE?null:e;default:return null}}function G9(e,t){if(cl)return e==="compositionend"||!yw&&uk(e,t)?(e=lk(),$p=mw=rs=null,cl=!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=aE(n)}}function mk(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?mk(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function gk(){for(var e=window,t=oh();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=oh(e.document)}return t}function ww(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 rI(e){var t=gk(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&mk(n.ownerDocument.documentElement,n)){if(r!==null&&ww(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 o=n.textContent.length,i=Math.min(r.start,o);r=r.end===void 0?i:Math.min(r.end,o),!e.extend&&i>r&&(o=r,r=i,i=o),o=lE(n,i);var s=lE(n,r);o&&s&&(e.rangeCount!==1||e.anchorNode!==o.node||e.anchorOffset!==o.offset||e.focusNode!==s.node||e.focusOffset!==s.offset)&&(t=t.createRange(),t.setStart(o.node,o.offset),e.removeAllRanges(),i>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,ul=null,sy=null,bu=null,ay=!1;function cE(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;ay||ul==null||ul!==oh(r)||(r=ul,"selectionStart"in r&&ww(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}),bu&&Fu(bu,r)||(bu=r,r=dh(sy,"onSelect"),0pl||(e.current=py[pl],py[pl]=null,pl--)}function $t(e,t){pl++,py[pl]=e.current,e.current=t}var Es={},Tn=Ps(Es),Jn=Ps(!1),ba=Es;function Kl(e,t){var n=e.type.contextTypes;if(!n)return Es;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var o={},i;for(i in n)o[i]=t[i];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=o),o}function er(e){return e=e.childContextTypes,e!=null}function ph(){At(Jn),At(Tn)}function gE(e,t,n){if(Tn.current!==Es)throw Error(ce(168));$t(Tn,t),$t(Jn,n)}function Ck(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var o in r)if(!(o in t))throw Error(ce(108,QD(e)||"Unknown",o));return zt({},n,r)}function hh(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||Es,ba=Tn.current,$t(Tn,e),$t(Jn,Jn.current),!0}function vE(e,t,n){var r=e.stateNode;if(!r)throw Error(ce(169));n?(e=Ck(e,t,ba),r.__reactInternalMemoizedMergedChildContext=e,At(Jn),At(Tn),$t(Tn,e)):At(Jn),$t(Jn,n)}var li=null,mm=!1,Qv=!1;function $k(e){li===null?li=[e]:li.push(e)}function mI(e){mm=!0,$k(e)}function As(){if(!Qv&&li!==null){Qv=!0;var e=0,t=xt;try{var n=li;for(xt=1;e>=s,o-=s,ci=1<<32-go(t)+o|n<O?(F=A,A=null):F=A.sibling;var V=g(S,A,E[O],k);if(V===null){A===null&&(A=F);break}e&&A&&V.alternate===null&&t(S,A),b=i(V,b,O),M===null?P=V:M.sibling=V,M=V,A=F}if(O===E.length)return n(S,A),Dt&&qs(S,O),P;if(A===null){for(;OO?(F=A,A=null):F=A.sibling;var J=g(S,A,V.value,k);if(J===null){A===null&&(A=F);break}e&&A&&J.alternate===null&&t(S,A),b=i(J,b,O),M===null?P=J:M.sibling=J,M=J,A=F}if(V.done)return n(S,A),Dt&&qs(S,O),P;if(A===null){for(;!V.done;O++,V=E.next())V=m(S,V.value,k),V!==null&&(b=i(V,b,O),M===null?P=V:M.sibling=V,M=V);return Dt&&qs(S,O),P}for(A=r(S,A);!V.done;O++,V=E.next())V=y(A,S,O,V.value,k),V!==null&&(e&&V.alternate!==null&&A.delete(V.key===null?O:V.key),b=i(V,b,O),M===null?P=V:M.sibling=V,M=V);return e&&A.forEach(function(G){return t(S,G)}),Dt&&qs(S,O),P}function C(S,b,E,k){if(typeof E=="object"&&E!==null&&E.type===ll&&E.key===null&&(E=E.props.children),typeof E=="object"&&E!==null){switch(E.$$typeof){case zf:e:{for(var P=E.key,M=b;M!==null;){if(M.key===P){if(P=E.type,P===ll){if(M.tag===7){n(S,M.sibling),b=o(M,E.props.children),b.return=S,S=b;break e}}else if(M.elementType===P||typeof P=="object"&&P!==null&&P.$$typeof===Ki&&EE(P)===M.type){n(S,M.sibling),b=o(M,E.props),b.ref=Jc(S,M,E),b.return=S,S=b;break e}n(S,M);break}else t(S,M);M=M.sibling}E.type===ll?(b=xa(E.props.children,S.mode,k,E.key),b.return=S,S=b):(k=Np(E.type,E.key,E.props,null,S.mode,k),k.ref=Jc(S,b,E),k.return=S,S=k)}return s(S);case al:e:{for(M=E.key;b!==null;){if(b.key===M)if(b.tag===4&&b.stateNode.containerInfo===E.containerInfo&&b.stateNode.implementation===E.implementation){n(S,b.sibling),b=o(b,E.children||[]),b.return=S,S=b;break e}else{n(S,b);break}else t(S,b);b=b.sibling}b=s0(E,S.mode,k),b.return=S,S=b}return s(S);case Ki:return M=E._init,C(S,b,M(E._payload),k)}if(du(E))return x(S,b,E,k);if(Gc(E))return _(S,b,E,k);qf(S,E)}return typeof E=="string"&&E!==""||typeof E=="number"?(E=""+E,b!==null&&b.tag===6?(n(S,b.sibling),b=o(b,E),b.return=S,S=b):(n(S,b),b=i0(E,S.mode,k),b.return=S,S=b),s(S)):n(S,b)}return C}var Gl=Nk(!0),Dk=Nk(!1),Cd={},zo=Ps(Cd),Uu=Ps(Cd),Vu=Ps(Cd);function oa(e){if(e===Cd)throw Error(ce(174));return e}function Rw(e,t){switch($t(Vu,t),$t(Uu,e),$t(zo,Cd),e=t.nodeType,e){case 9:case 11:t=(t=t.documentElement)?t.namespaceURI:Z0(null,"");break;default:e=e===8?t.parentNode:t,t=e.namespaceURI||null,e=e.tagName,t=Z0(t,e)}At(zo),$t(zo,t)}function Xl(){At(zo),At(Uu),At(Vu)}function Ik(e){oa(Vu.current);var t=oa(zo.current),n=Z0(t,e.type);t!==n&&($t(Uu,e),$t(zo,n))}function Tw(e){Uu.current===e&&(At(zo),At(Uu))}var Lt=Ps(0);function xh(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 Jv=[];function Pw(){for(var e=0;en?n:4,e(!0);var r=e0.transition;e0.transition={};try{e(!1),t()}finally{xt=n,e0.transition=r}}function Qk(){return Gr().memoizedState}function wI(e,t,n){var r=ys(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},Jk(e))eR(t,n);else if(n=Pk(e,t,n,r),n!==null){var o=jn();vo(n,e,r,o),tR(n,t,r)}}function xI(e,t,n){var r=ys(e),o={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(Jk(e))eR(t,o);else{var i=e.alternate;if(e.lanes===0&&(i===null||i.lanes===0)&&(i=t.lastRenderedReducer,i!==null))try{var s=t.lastRenderedState,l=i(s,n);if(o.hasEagerState=!0,o.eagerState=l,wo(l,s)){var u=t.interleaved;u===null?(o.next=o,$w(t)):(o.next=u.next,u.next=o),t.interleaved=o;return}}catch{}finally{}n=Pk(e,t,o,r),n!==null&&(o=jn(),vo(n,e,r,o),tR(n,t,r))}}function Jk(e){var t=e.alternate;return e===jt||t!==null&&t===jt}function eR(e,t){_u=bh=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function tR(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,fw(e,n)}}var _h={readContext:Yr,useCallback:En,useContext:En,useEffect:En,useImperativeHandle:En,useInsertionEffect:En,useLayoutEffect:En,useMemo:En,useReducer:En,useRef:En,useState:En,useDebugValue:En,useDeferredValue:En,useTransition:En,useMutableSource:En,useSyncExternalStore:En,useId:En,unstable_isNewReconciler:!1},bI={readContext:Yr,useCallback:function(e,t){return ko().memoizedState=[e,t===void 0?null:t],e},useContext:Yr,useEffect:$E,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,Pp(4194308,4,Yk.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Pp(4194308,4,e,t)},useInsertionEffect:function(e,t){return Pp(4,2,e,t)},useMemo:function(e,t){var n=ko();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=ko();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=wI.bind(null,jt,e),[r.memoizedState,e]},useRef:function(e){var t=ko();return e={current:e},t.memoizedState=e},useState:CE,useDebugValue:Dw,useDeferredValue:function(e){return ko().memoizedState=e},useTransition:function(){var e=CE(!1),t=e[0];return e=yI.bind(null,e[1]),ko().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=jt,o=ko();if(Dt){if(n===void 0)throw Error(ce(407));n=n()}else{if(n=t(),dn===null)throw Error(ce(349));Sa&30||jk(r,t,n)}o.memoizedState=n;var i={value:n,getSnapshot:t};return o.queue=i,$E(Bk.bind(null,r,i,e),[e]),r.flags|=2048,Ku(9,zk.bind(null,r,i,n,t),void 0,null),n},useId:function(){var e=ko(),t=dn.identifierPrefix;if(Dt){var n=ui,r=ci;n=(r&~(1<<32-go(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=Wu++,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[Oo]=t,e[Bu]=r,uR(e,t,!1,!1),t.stateNode=e;e:{switch(s=Q0(n,r),n){case"dialog":Tt("cancel",e),Tt("close",e),o=r;break;case"iframe":case"object":case"embed":Tt("load",e),o=r;break;case"video":case"audio":for(o=0;oql&&(t.flags|=128,r=!0,eu(i,!1),t.lanes=4194304)}else{if(!r)if(e=xh(s),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),eu(i,!0),i.tail===null&&i.tailMode==="hidden"&&!s.alternate&&!Dt)return Cn(t),null}else 2*Zt()-i.renderingStartTime>ql&&n!==1073741824&&(t.flags|=128,r=!0,eu(i,!1),t.lanes=4194304);i.isBackwards?(s.sibling=t.child,t.child=s):(n=i.last,n!==null?n.sibling=s:t.child=s,i.last=s)}return i.tail!==null?(t=i.tail,i.rendering=t,i.tail=t.sibling,i.renderingStartTime=Zt(),t.sibling=null,n=Lt.current,$t(Lt,r?n&1|2:n&1),t):(Cn(t),null);case 22:case 23:return Bw(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?fr&1073741824&&(Cn(t),t.subtreeFlags&6&&(t.flags|=8192)):Cn(t),null;case 24:return null;case 25:return null}throw Error(ce(156,t.tag))}function TI(e,t){switch(bw(t),t.tag){case 1:return er(t.type)&&ph(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Xl(),At(Jn),At(Tn),Pw(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return Tw(t),null;case 13:if(At(Lt),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(ce(340));Yl()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return At(Lt),null;case 4:return Xl(),null;case 10:return Cw(t.type._context),null;case 22:case 23:return Bw(),null;case 24:return null;default:return null}}var Jf=!1,kn=!1,PI=typeof WeakSet=="function"?WeakSet:Set,Se=null;function vl(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){Wt(e,t,r)}else n.current=null}function Cy(e,t,n){try{n()}catch(r){Wt(e,t,r)}}var DE=!1;function AI(e,t){if(ly=ch,e=gk(),ww(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 o=r.anchorOffset,i=r.focusNode;r=r.focusOffset;try{n.nodeType,i.nodeType}catch{n=null;break e}var s=0,l=-1,u=-1,d=0,h=0,m=e,g=null;t:for(;;){for(var y;m!==n||o!==0&&m.nodeType!==3||(l=s+o),m!==i||r!==0&&m.nodeType!==3||(u=s+r),m.nodeType===3&&(s+=m.nodeValue.length),(y=m.firstChild)!==null;)g=m,m=y;for(;;){if(m===e)break t;if(g===n&&++d===o&&(l=s),g===i&&++h===r&&(u=s),(y=m.nextSibling)!==null)break;m=g,g=m.parentNode}m=y}n=l===-1||u===-1?null:{start:l,end:u}}else n=null}n=n||{start:0,end:0}}else n=null;for(cy={focusedElem:e,selectionRange:n},ch=!1,Se=t;Se!==null;)if(t=Se,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,Se=e;else for(;Se!==null;){t=Se;try{var x=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(x!==null){var _=x.memoizedProps,C=x.memoizedState,S=t.stateNode,b=S.getSnapshotBeforeUpdate(t.elementType===t.type?_:io(t.type,_),C);S.__reactInternalSnapshotBeforeUpdate=b}break;case 3:var E=t.stateNode.containerInfo;E.nodeType===1?E.textContent="":E.nodeType===9&&E.documentElement&&E.removeChild(E.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(ce(163))}}catch(k){Wt(t,t.return,k)}if(e=t.sibling,e!==null){e.return=t.return,Se=e;break}Se=t.return}return x=DE,DE=!1,x}function Su(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var o=r=r.next;do{if((o.tag&e)===e){var i=o.destroy;o.destroy=void 0,i!==void 0&&Cy(t,n,i)}o=o.next}while(o!==r)}}function ym(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 $y(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 pR(e){var t=e.alternate;t!==null&&(e.alternate=null,pR(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Oo],delete t[Bu],delete t[fy],delete t[pI],delete t[hI])),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 hR(e){return e.tag===5||e.tag===3||e.tag===4}function IE(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||hR(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 ky(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=fh));else if(r!==4&&(e=e.child,e!==null))for(ky(e,t,n),e=e.sibling;e!==null;)ky(e,t,n),e=e.sibling}function Ry(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(Ry(e,t,n),e=e.sibling;e!==null;)Ry(e,t,n),e=e.sibling}var mn=null,lo=!1;function ji(e,t,n){for(n=n.child;n!==null;)mR(e,t,n),n=n.sibling}function mR(e,t,n){if(jo&&typeof jo.onCommitFiberUnmount=="function")try{jo.onCommitFiberUnmount(um,n)}catch{}switch(n.tag){case 5:kn||vl(n,t);case 6:var r=mn,o=lo;mn=null,ji(e,t,n),mn=r,lo=o,mn!==null&&(lo?(e=mn,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):mn.removeChild(n.stateNode));break;case 18:mn!==null&&(lo?(e=mn,n=n.stateNode,e.nodeType===8?qv(e.parentNode,n):e.nodeType===1&&qv(e,n),Iu(e)):qv(mn,n.stateNode));break;case 4:r=mn,o=lo,mn=n.stateNode.containerInfo,lo=!0,ji(e,t,n),mn=r,lo=o;break;case 0:case 11:case 14:case 15:if(!kn&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){o=r=r.next;do{var i=o,s=i.destroy;i=i.tag,s!==void 0&&(i&2||i&4)&&Cy(n,t,s),o=o.next}while(o!==r)}ji(e,t,n);break;case 1:if(!kn&&(vl(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(l){Wt(n,t,l)}ji(e,t,n);break;case 21:ji(e,t,n);break;case 22:n.mode&1?(kn=(r=kn)||n.memoizedState!==null,ji(e,t,n),kn=r):ji(e,t,n);break;default:ji(e,t,n)}}function LE(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new PI),t.forEach(function(r){var o=zI.bind(null,e,r);n.has(r)||(n.add(r),r.then(o,o))})}}function ro(e,t){var n=t.deletions;if(n!==null)for(var r=0;ro&&(o=s),r&=~i}if(r=o,r=Zt()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*MI(r/1960))-r,10e?16:e,os===null)var r=!1;else{if(e=os,os=null,Ch=0,dt&6)throw Error(ce(331));var o=dt;for(dt|=4,Se=e.current;Se!==null;){var i=Se,s=i.child;if(Se.flags&16){var l=i.deletions;if(l!==null){for(var u=0;uZt()-jw?wa(e,0):Fw|=n),tr(e,t)}function SR(e,t){t===0&&(e.mode&1?(t=Wf,Wf<<=1,!(Wf&130023424)&&(Wf=4194304)):t=1);var n=jn();e=gi(e,t),e!==null&&(_d(e,t,n),tr(e,n))}function jI(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),SR(e,n)}function zI(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,o=e.memoizedState;o!==null&&(n=o.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(ce(314))}r!==null&&r.delete(t),SR(e,n)}var ER;ER=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||Jn.current)Qn=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return Qn=!1,kI(e,t,n);Qn=!!(e.flags&131072)}else Qn=!1,Dt&&t.flags&1048576&&kk(t,gh,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;Ap(e,t),e=t.pendingProps;var o=Kl(t,Tn.current);Cl(t,n),o=Ow(null,t,r,e,o,n);var i=Mw();return t.flags|=1,typeof o=="object"&&o!==null&&typeof o.render=="function"&&o.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,er(r)?(i=!0,hh(t)):i=!1,t.memoizedState=o.state!==null&&o.state!==void 0?o.state:null,kw(t),o.updater=gm,t.stateNode=o,o._reactInternals=t,yy(t,r,e,n),t=by(null,t,r,!0,i,n)):(t.tag=0,Dt&&i&&xw(t),Dn(null,t,o,n),t=t.child),t;case 16:r=t.elementType;e:{switch(Ap(e,t),e=t.pendingProps,o=r._init,r=o(r._payload),t.type=r,o=t.tag=UI(r),e=io(r,e),o){case 0:t=xy(null,t,r,e,n);break e;case 1:t=OE(null,t,r,e,n);break e;case 11:t=PE(null,t,r,e,n);break e;case 14:t=AE(null,t,r,io(r.type,e),n);break e}throw Error(ce(306,r,""))}return t;case 0:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),xy(e,t,r,o,n);case 1:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),OE(e,t,r,o,n);case 3:e:{if(aR(t),e===null)throw Error(ce(387));r=t.pendingProps,i=t.memoizedState,o=i.element,Ak(e,t),wh(t,r,null,n);var s=t.memoizedState;if(r=s.element,i.isDehydrated)if(i={element:r,isDehydrated:!1,cache:s.cache,pendingSuspenseBoundaries:s.pendingSuspenseBoundaries,transitions:s.transitions},t.updateQueue.baseState=i,t.memoizedState=i,t.flags&256){o=Zl(Error(ce(423)),t),t=ME(e,t,r,n,o);break e}else if(r!==o){o=Zl(Error(ce(424)),t),t=ME(e,t,r,n,o);break e}else for(mr=ms(t.stateNode.containerInfo.firstChild),gr=t,Dt=!0,po=null,n=Dk(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(Yl(),r===o){t=vi(e,t,n);break e}Dn(e,t,r,n)}t=t.child}return t;case 5:return Ik(t),e===null&&my(t),r=t.type,o=t.pendingProps,i=e!==null?e.memoizedProps:null,s=o.children,uy(r,o)?s=null:i!==null&&uy(r,i)&&(t.flags|=32),sR(e,t),Dn(e,t,s,n),t.child;case 6:return e===null&&my(t),null;case 13:return lR(e,t,n);case 4:return Rw(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=Gl(t,null,r,n):Dn(e,t,r,n),t.child;case 11:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),PE(e,t,r,o,n);case 7:return Dn(e,t,t.pendingProps,n),t.child;case 8:return Dn(e,t,t.pendingProps.children,n),t.child;case 12:return Dn(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,o=t.pendingProps,i=t.memoizedProps,s=o.value,$t(vh,r._currentValue),r._currentValue=s,i!==null)if(wo(i.value,s)){if(i.children===o.children&&!Jn.current){t=vi(e,t,n);break e}}else for(i=t.child,i!==null&&(i.return=t);i!==null;){var l=i.dependencies;if(l!==null){s=i.child;for(var u=l.firstContext;u!==null;){if(u.context===r){if(i.tag===1){u=fi(-1,n&-n),u.tag=2;var d=i.updateQueue;if(d!==null){d=d.shared;var h=d.pending;h===null?u.next=u:(u.next=h.next,h.next=u),d.pending=u}}i.lanes|=n,u=i.alternate,u!==null&&(u.lanes|=n),gy(i.return,n,t),l.lanes|=n;break}u=u.next}}else if(i.tag===10)s=i.type===t.type?null:i.child;else if(i.tag===18){if(s=i.return,s===null)throw Error(ce(341));s.lanes|=n,l=s.alternate,l!==null&&(l.lanes|=n),gy(s,n,t),s=i.sibling}else s=i.child;if(s!==null)s.return=i;else for(s=i;s!==null;){if(s===t){s=null;break}if(i=s.sibling,i!==null){i.return=s.return,s=i;break}s=s.return}i=s}Dn(e,t,o.children,n),t=t.child}return t;case 9:return o=t.type,r=t.pendingProps.children,Cl(t,n),o=Yr(o),r=r(o),t.flags|=1,Dn(e,t,r,n),t.child;case 14:return r=t.type,o=io(r,t.pendingProps),o=io(r.type,o),AE(e,t,r,o,n);case 15:return oR(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),Ap(e,t),t.tag=1,er(r)?(e=!0,hh(t)):e=!1,Cl(t,n),Mk(t,r,o),yy(t,r,o,n),by(null,t,r,!0,e,n);case 19:return cR(e,t,n);case 22:return iR(e,t,n)}throw Error(ce(156,t.tag))};function CR(e,t){return q$(e,t)}function BI(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 Ur(e,t,n,r){return new BI(e,t,n,r)}function Vw(e){return e=e.prototype,!(!e||!e.isReactComponent)}function UI(e){if(typeof e=="function")return Vw(e)?1:0;if(e!=null){if(e=e.$$typeof,e===lw)return 11;if(e===cw)return 14}return 2}function ws(e,t){var n=e.alternate;return n===null?(n=Ur(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 Np(e,t,n,r,o,i){var s=2;if(r=e,typeof e=="function")Vw(e)&&(s=1);else if(typeof e=="string")s=5;else e:switch(e){case ll:return xa(n.children,o,i,t);case aw:s=8,o|=8;break;case U0:return e=Ur(12,n,t,o|2),e.elementType=U0,e.lanes=i,e;case V0:return e=Ur(13,n,t,o),e.elementType=V0,e.lanes=i,e;case W0:return e=Ur(19,n,t,o),e.elementType=W0,e.lanes=i,e;case N$:return xm(n,o,i,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case O$:s=10;break e;case M$:s=9;break e;case lw:s=11;break e;case cw:s=14;break e;case Ki:s=16,r=null;break e}throw Error(ce(130,e==null?e:typeof e,""))}return t=Ur(s,n,t,o),t.elementType=e,t.type=r,t.lanes=i,t}function xa(e,t,n,r){return e=Ur(7,e,r,t),e.lanes=n,e}function xm(e,t,n,r){return e=Ur(22,e,r,t),e.elementType=N$,e.lanes=n,e.stateNode={isHidden:!1},e}function i0(e,t,n){return e=Ur(6,e,null,t),e.lanes=n,e}function s0(e,t,n){return t=Ur(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function VI(e,t,n,r,o){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=zv(0),this.expirationTimes=zv(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=zv(0),this.identifierPrefix=r,this.onRecoverableError=o,this.mutableSourceEagerHydrationData=null}function Ww(e,t,n,r,o,i,s,l,u){return e=new VI(e,t,n,l,u),t===1?(t=1,i===!0&&(t|=8)):t=0,i=Ur(3,null,null,t),e.current=i,i.stateNode=e,i.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},kw(i),e}function WI(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(TR)}catch(e){console.error(e)}}TR(),k$.exports=br;var Os=k$.exports;const XI=lm(Os);var HE=Os;z0.createRoot=HE.createRoot,z0.hydrateRoot=HE.hydrateRoot;var $d=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},Ql=typeof window>"u"||"Deno"in window;function Lr(){}function ZI(e,t){return typeof e=="function"?e(t):e}function My(e){return typeof e=="number"&&e>=0&&e!==1/0}function PR(e,t){return Math.max(e+(t||0)-Date.now(),0)}function KE(e,t){const{type:n="all",exact:r,fetchStatus:o,predicate:i,queryKey:s,stale:l}=e;if(s){if(r){if(t.queryHash!==Gw(s,t.options))return!1}else if(!Xu(t.queryKey,s))return!1}if(n!=="all"){const u=t.isActive();if(n==="active"&&!u||n==="inactive"&&u)return!1}return!(typeof l=="boolean"&&t.isStale()!==l||typeof o<"u"&&o!==t.state.fetchStatus||i&&!i(t))}function YE(e,t){const{exact:n,status:r,predicate:o,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(Gu(t.options.mutationKey)!==Gu(i))return!1}else if(!Xu(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||o&&!o(t))}function Gw(e,t){return((t==null?void 0:t.queryKeyHashFn)||Gu)(e)}function Gu(e){return JSON.stringify(e,(t,n)=>Dy(n)?Object.keys(n).sort().reduce((r,o)=>(r[o]=n[o],r),{}):n)}function Xu(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?!Object.keys(t).some(n=>!Xu(e[n],t[n])):!1}function AR(e,t){if(e===t)return e;const n=GE(e)&&GE(t);if(n||Dy(e)&&Dy(t)){const r=n?e.length:Object.keys(e).length,o=n?t:Object.keys(t),i=o.length,s=n?[]:{};let l=0;for(let u=0;u"u")return!0;const n=t.prototype;return!(!XE(n)||!n.hasOwnProperty("isPrototypeOf"))}function XE(e){return Object.prototype.toString.call(e)==="[object Object]"}function OR(e){return new Promise(t=>{setTimeout(t,e)})}function ZE(e){OR(0).then(e)}function Iy(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?AR(e,t):t}function qI(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function QI(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var ua,Zi,Pl,l$,JI=(l$=class extends $d{constructor(){super();Te(this,ua,void 0);Te(this,Zi,void 0);Te(this,Pl,void 0);ye(this,Pl,t=>{if(!Ql&&window.addEventListener){const n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){z(this,Zi)||this.setEventListener(z(this,Pl))}onUnsubscribe(){var t;this.hasListeners()||((t=z(this,Zi))==null||t.call(this),ye(this,Zi,void 0))}setEventListener(t){var n;ye(this,Pl,t),(n=z(this,Zi))==null||n.call(this),ye(this,Zi,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){z(this,ua)!==t&&(ye(this,ua,t),this.onFocus())}onFocus(){this.listeners.forEach(t=>{t()})}isFocused(){var t;return typeof z(this,ua)=="boolean"?z(this,ua):((t=globalThis.document)==null?void 0:t.visibilityState)!=="hidden"}},ua=new WeakMap,Zi=new WeakMap,Pl=new WeakMap,l$),Rh=new JI,Al,qi,Ol,c$,eL=(c$=class extends $d{constructor(){super();Te(this,Al,!0);Te(this,qi,void 0);Te(this,Ol,void 0);ye(this,Ol,t=>{if(!Ql&&window.addEventListener){const n=()=>t(!0),r=()=>t(!1);return window.addEventListener("online",n,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",r)}}})}onSubscribe(){z(this,qi)||this.setEventListener(z(this,Ol))}onUnsubscribe(){var t;this.hasListeners()||((t=z(this,qi))==null||t.call(this),ye(this,qi,void 0))}setEventListener(t){var n;ye(this,Ol,t),(n=z(this,qi))==null||n.call(this),ye(this,qi,t(this.setOnline.bind(this)))}setOnline(t){z(this,Al)!==t&&(ye(this,Al,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return z(this,Al)}},Al=new WeakMap,qi=new WeakMap,Ol=new WeakMap,c$),Th=new eL;function tL(e){return Math.min(1e3*2**e,3e4)}function Cm(e){return(e??"online")==="online"?Th.isOnline():!0}var MR=class{constructor(e){this.revert=e==null?void 0:e.revert,this.silent=e==null?void 0:e.silent}};function a0(e){return e instanceof MR}function NR(e){let t=!1,n=0,r=!1,o,i,s;const l=new Promise((C,S)=>{i=C,s=S}),u=C=>{var S;r||(y(new MR(C)),(S=e.abort)==null||S.call(e))},d=()=>{t=!0},h=()=>{t=!1},m=()=>!Rh.isFocused()||e.networkMode!=="always"&&!Th.isOnline(),g=C=>{var S;r||(r=!0,(S=e.onSuccess)==null||S.call(e,C),o==null||o(),i(C))},y=C=>{var S;r||(r=!0,(S=e.onError)==null||S.call(e,C),o==null||o(),s(C))},x=()=>new Promise(C=>{var S;o=b=>{const E=r||!m();return E&&C(b),E},(S=e.onPause)==null||S.call(e)}).then(()=>{var C;o=void 0,r||(C=e.onContinue)==null||C.call(e)}),_=()=>{if(r)return;let C;try{C=e.fn()}catch(S){C=Promise.reject(S)}Promise.resolve(C).then(g).catch(S=>{var M;if(r)return;const b=e.retry??(Ql?0:3),E=e.retryDelay??tL,k=typeof E=="function"?E(n,S):E,P=b===!0||typeof b=="number"&&n{if(m())return x()}).then(()=>{t?y(S):_()})})};return Cm(e.networkMode)?_():x().then(_),{promise:l,cancel:u,continue:()=>(o==null?void 0:o())?l:Promise.resolve(),cancelRetry:d,continueRetry:h}}function nL(){let e=[],t=0,n=h=>{h()},r=h=>{h()};const o=h=>{let m;t++;try{m=h()}finally{t--,t||l()}return m},i=h=>{t?e.push(h):ZE(()=>{n(h)})},s=h=>(...m)=>{i(()=>{h(...m)})},l=()=>{const h=e;e=[],h.length&&ZE(()=>{r(()=>{h.forEach(m=>{n(m)})})})};return{batch:o,batchCalls:s,schedule:i,setNotifyFunction:h=>{n=h},setBatchNotifyFunction:h=>{r=h}}}var gn=nL(),da,u$,DR=(u$=class{constructor(){Te(this,da,void 0)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),My(this.gcTime)&&ye(this,da,setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Ql?1/0:5*60*1e3))}clearGcTimeout(){z(this,da)&&(clearTimeout(z(this,da)),ye(this,da,void 0))}},da=new WeakMap,u$),Ml,Nl,Nr,Qi,Dr,cn,ud,fa,Dl,Dp,ao,ii,d$,rL=(d$=class extends DR{constructor(t){super();Te(this,Dl);Te(this,ao);Te(this,Ml,void 0);Te(this,Nl,void 0);Te(this,Nr,void 0);Te(this,Qi,void 0);Te(this,Dr,void 0);Te(this,cn,void 0);Te(this,ud,void 0);Te(this,fa,void 0);ye(this,fa,!1),ye(this,ud,t.defaultOptions),tt(this,Dl,Dp).call(this,t.options),ye(this,cn,[]),ye(this,Nr,t.cache),this.queryKey=t.queryKey,this.queryHash=t.queryHash,ye(this,Ml,t.state||oL(this.options)),this.state=z(this,Ml),this.scheduleGc()}get meta(){return this.options.meta}optionalRemove(){!z(this,cn).length&&this.state.fetchStatus==="idle"&&z(this,Nr).remove(this)}setData(t,n){const r=Iy(this.state.data,t,this.options);return tt(this,ao,ii).call(this,{data:r,type:"success",dataUpdatedAt:n==null?void 0:n.updatedAt,manual:n==null?void 0:n.manual}),r}setState(t,n){tt(this,ao,ii).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){var r;const n=z(this,Qi);return(r=z(this,Dr))==null||r.cancel(t),n?n.then(Lr).catch(Lr):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(z(this,Ml))}isActive(){return z(this,cn).some(t=>t.options.enabled!==!1)}isDisabled(){return this.getObserversCount()>0&&!this.isActive()}isStale(){return this.state.isInvalidated||!this.state.dataUpdatedAt||z(this,cn).some(t=>t.getCurrentResult().isStale)}isStaleByTime(t=0){return this.state.isInvalidated||!this.state.dataUpdatedAt||!PR(this.state.dataUpdatedAt,t)}onFocus(){var n;const t=z(this,cn).find(r=>r.shouldFetchOnWindowFocus());t==null||t.refetch({cancelRefetch:!1}),(n=z(this,Dr))==null||n.continue()}onOnline(){var n;const t=z(this,cn).find(r=>r.shouldFetchOnReconnect());t==null||t.refetch({cancelRefetch:!1}),(n=z(this,Dr))==null||n.continue()}addObserver(t){z(this,cn).includes(t)||(z(this,cn).push(t),this.clearGcTimeout(),z(this,Nr).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){z(this,cn).includes(t)&&(ye(this,cn,z(this,cn).filter(n=>n!==t)),z(this,cn).length||(z(this,Dr)&&(z(this,fa)?z(this,Dr).cancel({revert:!0}):z(this,Dr).cancelRetry()),this.scheduleGc()),z(this,Nr).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return z(this,cn).length}invalidate(){this.state.isInvalidated||tt(this,ao,ii).call(this,{type:"invalidate"})}fetch(t,n){var d,h,m,g;if(this.state.fetchStatus!=="idle"){if(this.state.dataUpdatedAt&&(n!=null&&n.cancelRefetch))this.cancel({silent:!0});else if(z(this,Qi))return(d=z(this,Dr))==null||d.continueRetry(),z(this,Qi)}if(t&&tt(this,Dl,Dp).call(this,t),!this.options.queryFn){const y=z(this,cn).find(x=>x.options.queryFn);y&&tt(this,Dl,Dp).call(this,y.options)}const r=new AbortController,o={queryKey:this.queryKey,meta:this.meta},i=y=>{Object.defineProperty(y,"signal",{enumerable:!0,get:()=>(ye(this,fa,!0),r.signal)})};i(o);const s=()=>this.options.queryFn?(ye(this,fa,!1),this.options.persister?this.options.persister(this.options.queryFn,o,this):this.options.queryFn(o)):Promise.reject(new Error(`Missing queryFn: '${this.options.queryHash}'`)),l={fetchOptions:n,options:this.options,queryKey:this.queryKey,state:this.state,fetchFn:s};i(l),(h=this.options.behavior)==null||h.onFetch(l,this),ye(this,Nl,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((m=l.fetchOptions)==null?void 0:m.meta))&&tt(this,ao,ii).call(this,{type:"fetch",meta:(g=l.fetchOptions)==null?void 0:g.meta});const u=y=>{var x,_,C,S;a0(y)&&y.silent||tt(this,ao,ii).call(this,{type:"error",error:y}),a0(y)||((_=(x=z(this,Nr).config).onError)==null||_.call(x,y,this),(S=(C=z(this,Nr).config).onSettled)==null||S.call(C,this.state.data,y,this)),this.isFetchingOptimistic||this.scheduleGc(),this.isFetchingOptimistic=!1};return ye(this,Dr,NR({fn:l.fetchFn,abort:r.abort.bind(r),onSuccess:y=>{var x,_,C,S;if(typeof y>"u"){u(new Error(`${this.queryHash} data is undefined`));return}this.setData(y),(_=(x=z(this,Nr).config).onSuccess)==null||_.call(x,y,this),(S=(C=z(this,Nr).config).onSettled)==null||S.call(C,y,this.state.error,this),this.isFetchingOptimistic||this.scheduleGc(),this.isFetchingOptimistic=!1},onError:u,onFail:(y,x)=>{tt(this,ao,ii).call(this,{type:"failed",failureCount:y,error:x})},onPause:()=>{tt(this,ao,ii).call(this,{type:"pause"})},onContinue:()=>{tt(this,ao,ii).call(this,{type:"continue"})},retry:l.options.retry,retryDelay:l.options.retryDelay,networkMode:l.options.networkMode})),ye(this,Qi,z(this,Dr).promise),z(this,Qi)}},Ml=new WeakMap,Nl=new WeakMap,Nr=new WeakMap,Qi=new WeakMap,Dr=new WeakMap,cn=new WeakMap,ud=new WeakMap,fa=new WeakMap,Dl=new WeakSet,Dp=function(t){this.options={...z(this,ud),...t},this.updateGcTime(this.options.gcTime)},ao=new WeakSet,ii=function(t){const n=r=>{switch(t.type){case"failed":return{...r,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...r,fetchStatus:"paused"};case"continue":return{...r,fetchStatus:"fetching"};case"fetch":return{...r,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:t.meta??null,fetchStatus:Cm(this.options.networkMode)?"fetching":"paused",...!r.dataUpdatedAt&&{error:null,status:"pending"}};case"success":return{...r,data:t.data,dataUpdateCount:r.dataUpdateCount+1,dataUpdatedAt:t.dataUpdatedAt??Date.now(),error:null,isInvalidated:!1,status:"success",...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};case"error":const o=t.error;return a0(o)&&o.revert&&z(this,Nl)?{...z(this,Nl),fetchStatus:"idle"}:{...r,error:o,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:o,fetchStatus:"idle",status:"error"};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...t.state}}};this.state=n(this.state),gn.batch(()=>{z(this,cn).forEach(r=>{r.onQueryUpdate()}),z(this,Nr).notify({query:this,type:"updated",action:t})})},d$);function oL(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=typeof t<"u",r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var Ro,f$,iL=(f$=class extends $d{constructor(t={}){super();Te(this,Ro,void 0);this.config=t,ye(this,Ro,new Map)}build(t,n,r){const o=n.queryKey,i=n.queryHash??Gw(o,n);let s=this.get(i);return s||(s=new rL({cache:this,queryKey:o,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(o)}),this.add(s)),s}add(t){z(this,Ro).has(t.queryHash)||(z(this,Ro).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){const n=z(this,Ro).get(t.queryHash);n&&(t.destroy(),n===t&&z(this,Ro).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){gn.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return z(this,Ro).get(t)}getAll(){return[...z(this,Ro).values()]}find(t){const n={exact:!0,...t};return this.getAll().find(r=>KE(n,r))}findAll(t={}){const n=this.getAll();return Object.keys(t).length>0?n.filter(r=>KE(t,r)):n}notify(t){gn.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){gn.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){gn.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},Ro=new WeakMap,f$),To,dd,dr,Il,Po,Wi,p$,sL=(p$=class extends DR{constructor(t){super();Te(this,Po);Te(this,To,void 0);Te(this,dd,void 0);Te(this,dr,void 0);Te(this,Il,void 0);this.mutationId=t.mutationId,ye(this,dd,t.defaultOptions),ye(this,dr,t.mutationCache),ye(this,To,[]),this.state=t.state||aL(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options={...z(this,dd),...t},this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){z(this,To).includes(t)||(z(this,To).push(t),this.clearGcTimeout(),z(this,dr).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){ye(this,To,z(this,To).filter(n=>n!==t)),this.scheduleGc(),z(this,dr).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){z(this,To).length||(this.state.status==="pending"?this.scheduleGc():z(this,dr).remove(this))}continue(){var t;return((t=z(this,Il))==null?void 0:t.continue())??this.execute(this.state.variables)}async execute(t){var o,i,s,l,u,d,h,m,g,y,x,_,C,S,b,E,k,P,M,A;const n=()=>(ye(this,Il,NR({fn:()=>this.options.mutationFn?this.options.mutationFn(t):Promise.reject(new Error("No mutationFn found")),onFail:(O,F)=>{tt(this,Po,Wi).call(this,{type:"failed",failureCount:O,error:F})},onPause:()=>{tt(this,Po,Wi).call(this,{type:"pause"})},onContinue:()=>{tt(this,Po,Wi).call(this,{type:"continue"})},retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode})),z(this,Il).promise),r=this.state.status==="pending";try{if(!r){tt(this,Po,Wi).call(this,{type:"pending",variables:t}),await((i=(o=z(this,dr).config).onMutate)==null?void 0:i.call(o,t,this));const F=await((l=(s=this.options).onMutate)==null?void 0:l.call(s,t));F!==this.state.context&&tt(this,Po,Wi).call(this,{type:"pending",context:F,variables:t})}const O=await n();return await((d=(u=z(this,dr).config).onSuccess)==null?void 0:d.call(u,O,t,this.state.context,this)),await((m=(h=this.options).onSuccess)==null?void 0:m.call(h,O,t,this.state.context)),await((y=(g=z(this,dr).config).onSettled)==null?void 0:y.call(g,O,null,this.state.variables,this.state.context,this)),await((_=(x=this.options).onSettled)==null?void 0:_.call(x,O,null,t,this.state.context)),tt(this,Po,Wi).call(this,{type:"success",data:O}),O}catch(O){try{throw await((S=(C=z(this,dr).config).onError)==null?void 0:S.call(C,O,t,this.state.context,this)),await((E=(b=this.options).onError)==null?void 0:E.call(b,O,t,this.state.context)),await((P=(k=z(this,dr).config).onSettled)==null?void 0:P.call(k,void 0,O,this.state.variables,this.state.context,this)),await((A=(M=this.options).onSettled)==null?void 0:A.call(M,void 0,O,t,this.state.context)),O}finally{tt(this,Po,Wi).call(this,{type:"error",error:O})}}}},To=new WeakMap,dd=new WeakMap,dr=new WeakMap,Il=new WeakMap,Po=new WeakSet,Wi=function(t){const n=r=>{switch(t.type){case"failed":return{...r,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};case"pending":return{...r,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:!Cm(this.options.networkMode),status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...r,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:t.error,failureCount:r.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}};this.state=n(this.state),gn.batch(()=>{z(this,To).forEach(r=>{r.onMutationUpdate(t)}),z(this,dr).notify({mutation:this,type:"updated",action:t})})},p$);function aL(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Ir,fd,pa,h$,lL=(h$=class extends $d{constructor(t={}){super();Te(this,Ir,void 0);Te(this,fd,void 0);Te(this,pa,void 0);this.config=t,ye(this,Ir,[]),ye(this,fd,0)}build(t,n,r){const o=new sL({mutationCache:this,mutationId:++Ff(this,fd)._,options:t.defaultMutationOptions(n),state:r});return this.add(o),o}add(t){z(this,Ir).push(t),this.notify({type:"added",mutation:t})}remove(t){ye(this,Ir,z(this,Ir).filter(n=>n!==t)),this.notify({type:"removed",mutation:t})}clear(){gn.batch(()=>{z(this,Ir).forEach(t=>{this.remove(t)})})}getAll(){return z(this,Ir)}find(t){const n={exact:!0,...t};return z(this,Ir).find(r=>YE(n,r))}findAll(t={}){return z(this,Ir).filter(n=>YE(t,n))}notify(t){gn.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){return ye(this,pa,(z(this,pa)??Promise.resolve()).then(()=>{const t=z(this,Ir).filter(n=>n.state.isPaused);return gn.batch(()=>t.reduce((n,r)=>n.then(()=>r.continue().catch(Lr)),Promise.resolve()))}).then(()=>{ye(this,pa,void 0)})),z(this,pa)}},Ir=new WeakMap,fd=new WeakMap,pa=new WeakMap,h$);function cL(e){return{onFetch:(t,n)=>{const r=async()=>{var x,_,C,S,b;const o=t.options,i=(C=(_=(x=t.fetchOptions)==null?void 0:x.meta)==null?void 0:_.fetchMore)==null?void 0:C.direction,s=((S=t.state.data)==null?void 0:S.pages)||[],l=((b=t.state.data)==null?void 0:b.pageParams)||[],u={pages:[],pageParams:[]};let d=!1;const h=E=>{Object.defineProperty(E,"signal",{enumerable:!0,get:()=>(t.signal.aborted?d=!0:t.signal.addEventListener("abort",()=>{d=!0}),t.signal)})},m=t.options.queryFn||(()=>Promise.reject(new Error(`Missing queryFn: '${t.options.queryHash}'`))),g=async(E,k,P)=>{if(d)return Promise.reject();if(k==null&&E.pages.length)return Promise.resolve(E);const M={queryKey:t.queryKey,pageParam:k,direction:P?"backward":"forward",meta:t.options.meta};h(M);const A=await m(M),{maxPages:O}=t.options,F=P?QI:qI;return{pages:F(E.pages,A,O),pageParams:F(E.pageParams,k,O)}};let y;if(i&&s.length){const E=i==="backward",k=E?uL:qE,P={pages:s,pageParams:l},M=k(o,P);y=await g(P,M,E)}else{y=await g(u,l[0]??o.initialPageParam);const E=e??s.length;for(let k=1;k{var o,i;return(i=(o=t.options).persister)==null?void 0:i.call(o,r,{queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n)}:t.fetchFn=r}}}function qE(e,{pages:t,pageParams:n}){const r=t.length-1;return e.getNextPageParam(t[r],t,n[r],n)}function uL(e,{pages:t,pageParams:n}){var r;return(r=e.getPreviousPageParam)==null?void 0:r.call(e,t[0],t,n[0],n)}var nn,Ji,es,Ll,Fl,ts,jl,zl,m$,dL=(m$=class{constructor(e={}){Te(this,nn,void 0);Te(this,Ji,void 0);Te(this,es,void 0);Te(this,Ll,void 0);Te(this,Fl,void 0);Te(this,ts,void 0);Te(this,jl,void 0);Te(this,zl,void 0);ye(this,nn,e.queryCache||new iL),ye(this,Ji,e.mutationCache||new lL),ye(this,es,e.defaultOptions||{}),ye(this,Ll,new Map),ye(this,Fl,new Map),ye(this,ts,0)}mount(){Ff(this,ts)._++,z(this,ts)===1&&(ye(this,jl,Rh.subscribe(()=>{Rh.isFocused()&&(this.resumePausedMutations(),z(this,nn).onFocus())})),ye(this,zl,Th.subscribe(()=>{Th.isOnline()&&(this.resumePausedMutations(),z(this,nn).onOnline())})))}unmount(){var e,t;Ff(this,ts)._--,z(this,ts)===0&&((e=z(this,jl))==null||e.call(this),ye(this,jl,void 0),(t=z(this,zl))==null||t.call(this),ye(this,zl,void 0))}isFetching(e){return z(this,nn).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return z(this,Ji).findAll({...e,status:"pending"}).length}getQueryData(e){var t;return(t=z(this,nn).find({queryKey:e}))==null?void 0:t.state.data}ensureQueryData(e){const t=this.getQueryData(e.queryKey);return t!==void 0?Promise.resolve(t):this.fetchQuery(e)}getQueriesData(e){return this.getQueryCache().findAll(e).map(({queryKey:t,state:n})=>{const r=n.data;return[t,r]})}setQueryData(e,t,n){const r=z(this,nn).find({queryKey:e}),o=r==null?void 0:r.state.data,i=ZI(t,o);if(typeof i>"u")return;const s=this.defaultQueryOptions({queryKey:e});return z(this,nn).build(this,s).setData(i,{...n,manual:!0})}setQueriesData(e,t,n){return gn.batch(()=>this.getQueryCache().findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){var t;return(t=z(this,nn).find({queryKey:e}))==null?void 0:t.state}removeQueries(e){const t=z(this,nn);gn.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=z(this,nn),r={type:"active",...e};return gn.batch(()=>(n.findAll(e).forEach(o=>{o.reset()}),this.refetchQueries(r,t)))}cancelQueries(e={},t={}){const n={revert:!0,...t},r=gn.batch(()=>z(this,nn).findAll(e).map(o=>o.cancel(n)));return Promise.all(r).then(Lr).catch(Lr)}invalidateQueries(e={},t={}){return gn.batch(()=>{if(z(this,nn).findAll(e).forEach(r=>{r.invalidate()}),e.refetchType==="none")return Promise.resolve();const n={...e,type:e.refetchType??e.type??"active"};return this.refetchQueries(n,t)})}refetchQueries(e={},t){const n={...t,cancelRefetch:(t==null?void 0:t.cancelRefetch)??!0},r=gn.batch(()=>z(this,nn).findAll(e).filter(o=>!o.isDisabled()).map(o=>{let i=o.fetch(void 0,n);return n.throwOnError||(i=i.catch(Lr)),o.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(Lr)}fetchQuery(e){const t=this.defaultQueryOptions(e);typeof t.retry>"u"&&(t.retry=!1);const n=z(this,nn).build(this,t);return n.isStaleByTime(t.staleTime)?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Lr).catch(Lr)}fetchInfiniteQuery(e){return e.behavior=cL(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Lr).catch(Lr)}resumePausedMutations(){return z(this,Ji).resumePausedMutations()}getQueryCache(){return z(this,nn)}getMutationCache(){return z(this,Ji)}getDefaultOptions(){return z(this,es)}setDefaultOptions(e){ye(this,es,e)}setQueryDefaults(e,t){z(this,Ll).set(Gu(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...z(this,Ll).values()];let n={};return t.forEach(r=>{Xu(e,r.queryKey)&&(n={...n,...r.defaultOptions})}),n}setMutationDefaults(e,t){z(this,Fl).set(Gu(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...z(this,Fl).values()];let n={};return t.forEach(r=>{Xu(e,r.mutationKey)&&(n={...n,...r.defaultOptions})}),n}defaultQueryOptions(e){if(e!=null&&e._defaulted)return e;const t={...z(this,es).queries,...(e==null?void 0:e.queryKey)&&this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Gw(t.queryKey,t)),typeof t.refetchOnReconnect>"u"&&(t.refetchOnReconnect=t.networkMode!=="always"),typeof t.throwOnError>"u"&&(t.throwOnError=!!t.suspense),typeof t.networkMode>"u"&&t.persister&&(t.networkMode="offlineFirst"),t}defaultMutationOptions(e){return e!=null&&e._defaulted?e:{...z(this,es).mutations,...(e==null?void 0:e.mutationKey)&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){z(this,nn).clear(),z(this,Ji).clear()}},nn=new WeakMap,Ji=new WeakMap,es=new WeakMap,Ll=new WeakMap,Fl=new WeakMap,ts=new WeakMap,jl=new WeakMap,zl=new WeakMap,m$),Xn,Ct,Bl,$n,ha,Ul,Ao,pd,Vl,Wl,ma,ga,ns,va,ya,hu,hd,Ly,md,Fy,gd,jy,vd,zy,yd,By,wd,Uy,xd,Vy,am,IR,g$,fL=(g$=class extends $d{constructor(t,n){super();Te(this,ya);Te(this,hd);Te(this,md);Te(this,gd);Te(this,vd);Te(this,yd);Te(this,wd);Te(this,xd);Te(this,am);Te(this,Xn,void 0);Te(this,Ct,void 0);Te(this,Bl,void 0);Te(this,$n,void 0);Te(this,ha,void 0);Te(this,Ul,void 0);Te(this,Ao,void 0);Te(this,pd,void 0);Te(this,Vl,void 0);Te(this,Wl,void 0);Te(this,ma,void 0);Te(this,ga,void 0);Te(this,ns,void 0);Te(this,va,void 0);ye(this,Ct,void 0),ye(this,Bl,void 0),ye(this,$n,void 0),ye(this,va,new Set),ye(this,Xn,t),this.options=n,ye(this,Ao,null),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(z(this,Ct).addObserver(this),QE(z(this,Ct),this.options)?tt(this,ya,hu).call(this):this.updateResult(),tt(this,vd,zy).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Wy(z(this,Ct),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Wy(z(this,Ct),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,tt(this,yd,By).call(this),tt(this,wd,Uy).call(this),z(this,Ct).removeObserver(this)}setOptions(t,n){const r=this.options,o=z(this,Ct);if(this.options=z(this,Xn).defaultQueryOptions(t),Ny(r,this.options)||z(this,Xn).getQueryCache().notify({type:"observerOptionsUpdated",query:z(this,Ct),observer:this}),typeof this.options.enabled<"u"&&typeof this.options.enabled!="boolean")throw new Error("Expected enabled to be a boolean");this.options.queryKey||(this.options.queryKey=r.queryKey),tt(this,xd,Vy).call(this);const i=this.hasListeners();i&&JE(z(this,Ct),o,this.options,r)&&tt(this,ya,hu).call(this),this.updateResult(n),i&&(z(this,Ct)!==o||this.options.enabled!==r.enabled||this.options.staleTime!==r.staleTime)&&tt(this,hd,Ly).call(this);const s=tt(this,md,Fy).call(this);i&&(z(this,Ct)!==o||this.options.enabled!==r.enabled||s!==z(this,ns))&&tt(this,gd,jy).call(this,s)}getOptimisticResult(t){const n=z(this,Xn).getQueryCache().build(z(this,Xn),t),r=this.createResult(n,t);return hL(this,r)&&(ye(this,$n,r),ye(this,Ul,this.options),ye(this,ha,z(this,Ct).state)),r}getCurrentResult(){return z(this,$n)}trackResult(t){const n={};return Object.keys(t).forEach(r=>{Object.defineProperty(n,r,{configurable:!1,enumerable:!0,get:()=>(z(this,va).add(r),t[r])})}),n}getCurrentQuery(){return z(this,Ct)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){const n=z(this,Xn).defaultQueryOptions(t),r=z(this,Xn).getQueryCache().build(z(this,Xn),n);return r.isFetchingOptimistic=!0,r.fetch().then(()=>this.createResult(r,n))}fetch(t){return tt(this,ya,hu).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),z(this,$n)))}createResult(t,n){var M;const r=z(this,Ct),o=this.options,i=z(this,$n),s=z(this,ha),l=z(this,Ul),d=t!==r?t.state:z(this,Bl),{state:h}=t;let{error:m,errorUpdatedAt:g,fetchStatus:y,status:x}=h,_=!1,C;if(n._optimisticResults){const A=this.hasListeners(),O=!A&&QE(t,n),F=A&&JE(t,r,n,o);(O||F)&&(y=Cm(t.options.networkMode)?"fetching":"paused",h.dataUpdatedAt||(x="pending")),n._optimisticResults==="isRestoring"&&(y="idle")}if(n.select&&typeof h.data<"u")if(i&&h.data===(s==null?void 0:s.data)&&n.select===z(this,pd))C=z(this,Vl);else try{ye(this,pd,n.select),C=n.select(h.data),C=Iy(i==null?void 0:i.data,C,n),ye(this,Vl,C),ye(this,Ao,null)}catch(A){ye(this,Ao,A)}else C=h.data;if(typeof n.placeholderData<"u"&&typeof C>"u"&&x==="pending"){let A;if(i!=null&&i.isPlaceholderData&&n.placeholderData===(l==null?void 0:l.placeholderData))A=i.data;else if(A=typeof n.placeholderData=="function"?n.placeholderData((M=z(this,Wl))==null?void 0:M.state.data,z(this,Wl)):n.placeholderData,n.select&&typeof A<"u")try{A=n.select(A),ye(this,Ao,null)}catch(O){ye(this,Ao,O)}typeof A<"u"&&(x="success",C=Iy(i==null?void 0:i.data,A,n),_=!0)}z(this,Ao)&&(m=z(this,Ao),C=z(this,Vl),g=Date.now(),x="error");const S=y==="fetching",b=x==="pending",E=x==="error",k=b&&S;return{status:x,fetchStatus:y,isPending:b,isSuccess:x==="success",isError:E,isInitialLoading:k,isLoading:k,data:C,dataUpdatedAt:h.dataUpdatedAt,error:m,errorUpdatedAt:g,failureCount:h.fetchFailureCount,failureReason:h.fetchFailureReason,errorUpdateCount:h.errorUpdateCount,isFetched:h.dataUpdateCount>0||h.errorUpdateCount>0,isFetchedAfterMount:h.dataUpdateCount>d.dataUpdateCount||h.errorUpdateCount>d.errorUpdateCount,isFetching:S,isRefetching:S&&!b,isLoadingError:E&&h.dataUpdatedAt===0,isPaused:y==="paused",isPlaceholderData:_,isRefetchError:E&&h.dataUpdatedAt!==0,isStale:Xw(t,n),refetch:this.refetch}}updateResult(t){const n=z(this,$n),r=this.createResult(z(this,Ct),this.options);if(ye(this,ha,z(this,Ct).state),ye(this,Ul,this.options),z(this,ha).data!==void 0&&ye(this,Wl,z(this,Ct)),Ny(r,n))return;ye(this,$n,r);const o={},i=()=>{if(!n)return!0;const{notifyOnChangeProps:s}=this.options,l=typeof s=="function"?s():s;if(l==="all"||!l&&!z(this,va).size)return!0;const u=new Set(l??z(this,va));return this.options.throwOnError&&u.add("error"),Object.keys(z(this,$n)).some(d=>{const h=d;return z(this,$n)[h]!==n[h]&&u.has(h)})};(t==null?void 0:t.listeners)!==!1&&i()&&(o.listeners=!0),tt(this,am,IR).call(this,{...o,...t})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&tt(this,vd,zy).call(this)}},Xn=new WeakMap,Ct=new WeakMap,Bl=new WeakMap,$n=new WeakMap,ha=new WeakMap,Ul=new WeakMap,Ao=new WeakMap,pd=new WeakMap,Vl=new WeakMap,Wl=new WeakMap,ma=new WeakMap,ga=new WeakMap,ns=new WeakMap,va=new WeakMap,ya=new WeakSet,hu=function(t){tt(this,xd,Vy).call(this);let n=z(this,Ct).fetch(this.options,t);return t!=null&&t.throwOnError||(n=n.catch(Lr)),n},hd=new WeakSet,Ly=function(){if(tt(this,yd,By).call(this),Ql||z(this,$n).isStale||!My(this.options.staleTime))return;const n=PR(z(this,$n).dataUpdatedAt,this.options.staleTime)+1;ye(this,ma,setTimeout(()=>{z(this,$n).isStale||this.updateResult()},n))},md=new WeakSet,Fy=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(z(this,Ct)):this.options.refetchInterval)??!1},gd=new WeakSet,jy=function(t){tt(this,wd,Uy).call(this),ye(this,ns,t),!(Ql||this.options.enabled===!1||!My(z(this,ns))||z(this,ns)===0)&&ye(this,ga,setInterval(()=>{(this.options.refetchIntervalInBackground||Rh.isFocused())&&tt(this,ya,hu).call(this)},z(this,ns)))},vd=new WeakSet,zy=function(){tt(this,hd,Ly).call(this),tt(this,gd,jy).call(this,tt(this,md,Fy).call(this))},yd=new WeakSet,By=function(){z(this,ma)&&(clearTimeout(z(this,ma)),ye(this,ma,void 0))},wd=new WeakSet,Uy=function(){z(this,ga)&&(clearInterval(z(this,ga)),ye(this,ga,void 0))},xd=new WeakSet,Vy=function(){const t=z(this,Xn).getQueryCache().build(z(this,Xn),this.options);if(t===z(this,Ct))return;const n=z(this,Ct);ye(this,Ct,t),ye(this,Bl,t.state),this.hasListeners()&&(n==null||n.removeObserver(this),t.addObserver(this))},am=new WeakSet,IR=function(t){gn.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(z(this,$n))}),z(this,Xn).getQueryCache().notify({query:z(this,Ct),type:"observerResultsUpdated"})})},g$);function pL(e,t){return t.enabled!==!1&&!e.state.dataUpdatedAt&&!(e.state.status==="error"&&t.retryOnMount===!1)}function QE(e,t){return pL(e,t)||e.state.dataUpdatedAt>0&&Wy(e,t,t.refetchOnMount)}function Wy(e,t,n){if(t.enabled!==!1){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&Xw(e,t)}return!1}function JE(e,t,n,r){return n.enabled!==!1&&(e!==t||r.enabled===!1)&&(!n.suspense||e.state.status!=="error")&&Xw(e,n)}function Xw(e,t){return e.isStaleByTime(t.staleTime)}function hL(e,t){return!Ny(e.getCurrentResult(),t)}var LR=f.createContext(void 0),mL=e=>{const t=f.useContext(LR);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},gL=({client:e,children:t})=>(f.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),f.createElement(LR.Provider,{value:e},t)),FR=f.createContext(!1),vL=()=>f.useContext(FR);FR.Provider;function yL(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var wL=f.createContext(yL()),xL=()=>f.useContext(wL);function bL(e,t){return typeof e=="function"?e(...t):!!e}var _L=(e,t)=>{(e.suspense||e.throwOnError)&&(t.isReset()||(e.retryOnMount=!1))},SL=e=>{f.useEffect(()=>{e.clearReset()},[e])},EL=({result:e,errorResetBoundary:t,throwOnError:n,query:r})=>e.isError&&!t.isReset()&&!e.isFetching&&bL(n,[e.error,r]),CL=e=>{e.suspense&&typeof e.staleTime!="number"&&(e.staleTime=1e3)},$L=(e,t)=>(e==null?void 0:e.suspense)&&t.isPending,kL=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function RL(e,t,n){const r=mL(n),o=vL(),i=xL(),s=r.defaultQueryOptions(e);s._optimisticResults=o?"isRestoring":"optimistic",CL(s),_L(s,i),SL(i);const[l]=f.useState(()=>new t(r,s)),u=l.getOptimisticResult(s);if(f.useSyncExternalStore(f.useCallback(d=>{const h=o?()=>{}:l.subscribe(gn.batchCalls(d));return l.updateResult(),h},[l,o]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),f.useEffect(()=>{l.setOptions(s,{listeners:!1})},[s,l]),$L(s,u))throw l.setOptions(s,{listeners:!1}),kL(s,l,i);if(EL({result:u,errorResetBoundary:i,throwOnError:s.throwOnError,query:l.getCurrentQuery()}))throw u.error;return s.notifyOnChangeProps?u:l.trackResult(u)}function TL(e,t){return RL(e,fL,t)}var jR=(e=>(e.RemoveBG="RemoveBG",e.AnimeSeg="AnimeSeg",e.RealESRGAN="RealESRGAN",e.GFPGAN="GFPGAN",e.RestoreFormer="RestoreFormer",e.InteractiveSeg="InteractiveSeg",e))(jR||{}),xs=(e=>(e.NAME="name",e.CTIME="ctime",e.MTIME="mtime",e))(xs||{}),$u=(e=>(e.DESCENDING="desc",e.ASCENDING="asc",e))($u||{}),Zw=(e=>(e.ddim="ddim",e.plms="plms",e))(Zw||{}),qw=(e=>(e.INPAINT_NS="INPAINT_NS",e.INPAINT_TELEA="INPAINT_TELEA",e))(qw||{}),In=(e=>(e.x="x",e.y="y",e.xy="xy",e))(In||{}),kl=(e=>(e.text_guided="text-guided",e.shape_guided="shape-guided",e.object_remove="object-remove",e.outpainting="outpainting",e))(kl||{});function zR(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;tl(i)))==null?void 0:s.classGroupId}const eC=/^\[(.+)\]$/;function AL(e){if(eC.test(e)){const t=eC.exec(e)[1],n=t==null?void 0:t.substring(0,t.indexOf(":"));if(n)return"arbitrary.."+n}}function OL(e){const{theme:t,prefix:n}=e,r={nextPart:new Map,validators:[]};return NL(Object.entries(e.classGroups),n).forEach(([i,s])=>{Hy(s,r,i,t)}),r}function Hy(e,t,n,r){e.forEach(o=>{if(typeof o=="string"){const i=o===""?t:tC(t,o);i.classGroupId=n;return}if(typeof o=="function"){if(ML(o)){Hy(o(r),t,n,r);return}t.validators.push({validator:o,classGroupId:n});return}Object.entries(o).forEach(([i,s])=>{Hy(s,tC(t,i),n,r)})})}function tC(e,t){let n=e;return t.split(Qw).forEach(r=>{n.nextPart.has(r)||n.nextPart.set(r,{nextPart:new Map,validators:[]}),n=n.nextPart.get(r)}),n}function ML(e){return e.isThemeGetter}function NL(e,t){return t?e.map(([n,r])=>{const o=r.map(i=>typeof i=="string"?t+i:typeof i=="object"?Object.fromEntries(Object.entries(i).map(([s,l])=>[t+s,l])):i);return[n,o]}):e}function DL(e){if(e<1)return{get:()=>{},set:()=>{}};let t=0,n=new Map,r=new Map;function o(i,s){n.set(i,s),t++,t>e&&(t=0,r=n,n=new Map)}return{get(i){let s=n.get(i);if(s!==void 0)return s;if((s=r.get(i))!==void 0)return o(i,s),s},set(i,s){n.has(i)?n.set(i,s):o(i,s)}}}const VR="!";function IL(e){const t=e.separator,n=t.length===1,r=t[0],o=t.length;return function(s){const l=[];let u=0,d=0,h;for(let _=0;_d?h-d:void 0;return{modifiers:l,hasImportantModifier:g,baseClassName:y,maybePostfixModifierPosition:x}}}function LL(e){if(e.length<=1)return e;const t=[];let n=[];return e.forEach(r=>{r[0]==="["?(t.push(...n.sort(),r),n=[]):n.push(r)}),t.push(...n.sort()),t}function FL(e){return{cache:DL(e.cacheSize),splitModifiers:IL(e),...PL(e)}}const jL=/\s+/;function zL(e,t){const{splitModifiers:n,getClassGroupId:r,getConflictingClassGroupIds:o}=t,i=new Set;return e.trim().split(jL).map(s=>{const{modifiers:l,hasImportantModifier:u,baseClassName:d,maybePostfixModifierPosition:h}=n(s);let m=r(h?d.substring(0,h):d),g=!!h;if(!m){if(!h)return{isTailwindClass:!1,originalClassName:s};if(m=r(d),!m)return{isTailwindClass:!1,originalClassName:s};g=!1}const y=LL(l).join(":");return{isTailwindClass:!0,modifierId:u?y+VR:y,classGroupId:m,originalClassName:s,hasPostfixModifier:g}}).reverse().filter(s=>{if(!s.isTailwindClass)return!0;const{modifierId:l,classGroupId:u,hasPostfixModifier:d}=s,h=l+u;return i.has(h)?!1:(i.add(h),o(u,d).forEach(m=>i.add(l+m)),!0)}).reverse().map(s=>s.originalClassName).join(" ")}function BL(){let e=0,t,n,r="";for(;em(h),e());return n=FL(d),r=n.cache.get,o=n.cache.set,i=l,l(u)}function l(u){const d=r(u);if(d)return d;const h=zL(u,n);return o(u,h),h}return function(){return i(BL.apply(null,arguments))}}function Rt(e){const t=n=>n[e]||[];return t.isThemeGetter=!0,t}const HR=/^\[(?:([a-z-]+):)?(.+)\]$/i,VL=/^\d+\/\d+$/,WL=new Set(["px","full","screen"]),HL=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,KL=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,YL=/^-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,GL=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/;function oo(e){return ia(e)||WL.has(e)||VL.test(e)}function zi(e){return mc(e,"length",nF)}function ia(e){return!!e&&!Number.isNaN(Number(e))}function np(e){return mc(e,"number",ia)}function nu(e){return!!e&&Number.isInteger(Number(e))}function XL(e){return e.endsWith("%")&&ia(e.slice(0,-1))}function Je(e){return HR.test(e)}function Bi(e){return HL.test(e)}const ZL=new Set(["length","size","percentage"]);function qL(e){return mc(e,ZL,KR)}function QL(e){return mc(e,"position",KR)}const JL=new Set(["image","url"]);function eF(e){return mc(e,JL,oF)}function tF(e){return mc(e,"",rF)}function ru(){return!0}function mc(e,t,n){const r=HR.exec(e);return r?r[1]?typeof t=="string"?r[1]===t:t.has(r[1]):n(r[2]):!1}function nF(e){return KL.test(e)}function KR(){return!1}function rF(e){return YL.test(e)}function oF(e){return GL.test(e)}function iF(){const e=Rt("colors"),t=Rt("spacing"),n=Rt("blur"),r=Rt("brightness"),o=Rt("borderColor"),i=Rt("borderRadius"),s=Rt("borderSpacing"),l=Rt("borderWidth"),u=Rt("contrast"),d=Rt("grayscale"),h=Rt("hueRotate"),m=Rt("invert"),g=Rt("gap"),y=Rt("gradientColorStops"),x=Rt("gradientColorStopPositions"),_=Rt("inset"),C=Rt("margin"),S=Rt("opacity"),b=Rt("padding"),E=Rt("saturate"),k=Rt("scale"),P=Rt("sepia"),M=Rt("skew"),A=Rt("space"),O=Rt("translate"),F=()=>["auto","contain","none"],V=()=>["auto","hidden","clip","visible","scroll"],J=()=>["auto",Je,t],G=()=>[Je,t],ae=()=>["",oo,zi],U=()=>["auto",ia,Je],te=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],L=()=>["solid","dashed","dotted","double","none"],ie=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity","plus-lighter"],K=()=>["start","end","center","between","around","evenly","stretch"],Q=()=>["","0",Je],W=()=>["auto","avoid","all","avoid-page","page","left","right","column"],le=()=>[ia,np],ge=()=>[ia,Je];return{cacheSize:500,separator:":",theme:{colors:[ru],spacing:[oo,zi],blur:["none","",Bi,Je],brightness:le(),borderColor:[e],borderRadius:["none","","full",Bi,Je],borderSpacing:G(),borderWidth:ae(),contrast:le(),grayscale:Q(),hueRotate:ge(),invert:Q(),gap:G(),gradientColorStops:[e],gradientColorStopPositions:[XL,zi],inset:J(),margin:J(),opacity:le(),padding:G(),saturate:le(),scale:le(),sepia:Q(),skew:ge(),space:G(),translate:G()},classGroups:{aspect:[{aspect:["auto","square","video",Je]}],container:["container"],columns:[{columns:[Bi]}],"break-after":[{"break-after":W()}],"break-before":[{"break-before":W()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],float:[{float:["right","left","none"]}],clear:[{clear:["left","right","both","none"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:[...te(),Je]}],overflow:[{overflow:V()}],"overflow-x":[{"overflow-x":V()}],"overflow-y":[{"overflow-y":V()}],overscroll:[{overscroll:F()}],"overscroll-x":[{"overscroll-x":F()}],"overscroll-y":[{"overscroll-y":F()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[_]}],"inset-x":[{"inset-x":[_]}],"inset-y":[{"inset-y":[_]}],start:[{start:[_]}],end:[{end:[_]}],top:[{top:[_]}],right:[{right:[_]}],bottom:[{bottom:[_]}],left:[{left:[_]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",nu,Je]}],basis:[{basis:J()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",Je]}],grow:[{grow:Q()}],shrink:[{shrink:Q()}],order:[{order:["first","last","none",nu,Je]}],"grid-cols":[{"grid-cols":[ru]}],"col-start-end":[{col:["auto",{span:["full",nu,Je]},Je]}],"col-start":[{"col-start":U()}],"col-end":[{"col-end":U()}],"grid-rows":[{"grid-rows":[ru]}],"row-start-end":[{row:["auto",{span:[nu,Je]},Je]}],"row-start":[{"row-start":U()}],"row-end":[{"row-end":U()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",Je]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",Je]}],gap:[{gap:[g]}],"gap-x":[{"gap-x":[g]}],"gap-y":[{"gap-y":[g]}],"justify-content":[{justify:["normal",...K()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...K(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...K(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[b]}],px:[{px:[b]}],py:[{py:[b]}],ps:[{ps:[b]}],pe:[{pe:[b]}],pt:[{pt:[b]}],pr:[{pr:[b]}],pb:[{pb:[b]}],pl:[{pl:[b]}],m:[{m:[C]}],mx:[{mx:[C]}],my:[{my:[C]}],ms:[{ms:[C]}],me:[{me:[C]}],mt:[{mt:[C]}],mr:[{mr:[C]}],mb:[{mb:[C]}],ml:[{ml:[C]}],"space-x":[{"space-x":[A]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[A]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit",Je,t]}],"min-w":[{"min-w":["min","max","fit",Je,oo]}],"max-w":[{"max-w":["0","none","full","min","max","fit","prose",{screen:[Bi]},Bi,Je]}],h:[{h:[Je,t,"auto","min","max","fit"]}],"min-h":[{"min-h":["min","max","fit",oo,Je]}],"max-h":[{"max-h":[Je,t,"min","max","fit"]}],"font-size":[{text:["base",Bi,zi]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",np]}],"font-family":[{font:[ru]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractons"],tracking:[{tracking:["tighter","tight","normal","wide","wider","widest",Je]}],"line-clamp":[{"line-clamp":["none",ia,np]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",oo,Je]}],"list-image":[{"list-image":["none",Je]}],"list-style-type":[{list:["none","disc","decimal",Je]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[e]}],"placeholder-opacity":[{"placeholder-opacity":[S]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[e]}],"text-opacity":[{"text-opacity":[S]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...L(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",oo,zi]}],"underline-offset":[{"underline-offset":["auto",oo,Je]}],"text-decoration-color":[{decoration:[e]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],indent:[{indent:G()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Je]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",Je]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[S]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...te(),QL]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",qL]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},eF]}],"bg-color":[{bg:[e]}],"gradient-from-pos":[{from:[x]}],"gradient-via-pos":[{via:[x]}],"gradient-to-pos":[{to:[x]}],"gradient-from":[{from:[y]}],"gradient-via":[{via:[y]}],"gradient-to":[{to:[y]}],rounded:[{rounded:[i]}],"rounded-s":[{"rounded-s":[i]}],"rounded-e":[{"rounded-e":[i]}],"rounded-t":[{"rounded-t":[i]}],"rounded-r":[{"rounded-r":[i]}],"rounded-b":[{"rounded-b":[i]}],"rounded-l":[{"rounded-l":[i]}],"rounded-ss":[{"rounded-ss":[i]}],"rounded-se":[{"rounded-se":[i]}],"rounded-ee":[{"rounded-ee":[i]}],"rounded-es":[{"rounded-es":[i]}],"rounded-tl":[{"rounded-tl":[i]}],"rounded-tr":[{"rounded-tr":[i]}],"rounded-br":[{"rounded-br":[i]}],"rounded-bl":[{"rounded-bl":[i]}],"border-w":[{border:[l]}],"border-w-x":[{"border-x":[l]}],"border-w-y":[{"border-y":[l]}],"border-w-s":[{"border-s":[l]}],"border-w-e":[{"border-e":[l]}],"border-w-t":[{"border-t":[l]}],"border-w-r":[{"border-r":[l]}],"border-w-b":[{"border-b":[l]}],"border-w-l":[{"border-l":[l]}],"border-opacity":[{"border-opacity":[S]}],"border-style":[{border:[...L(),"hidden"]}],"divide-x":[{"divide-x":[l]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[l]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[S]}],"divide-style":[{divide:L()}],"border-color":[{border:[o]}],"border-color-x":[{"border-x":[o]}],"border-color-y":[{"border-y":[o]}],"border-color-t":[{"border-t":[o]}],"border-color-r":[{"border-r":[o]}],"border-color-b":[{"border-b":[o]}],"border-color-l":[{"border-l":[o]}],"divide-color":[{divide:[o]}],"outline-style":[{outline:["",...L()]}],"outline-offset":[{"outline-offset":[oo,Je]}],"outline-w":[{outline:[oo,zi]}],"outline-color":[{outline:[e]}],"ring-w":[{ring:ae()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[e]}],"ring-opacity":[{"ring-opacity":[S]}],"ring-offset-w":[{"ring-offset":[oo,zi]}],"ring-offset-color":[{"ring-offset":[e]}],shadow:[{shadow:["","inner","none",Bi,tF]}],"shadow-color":[{shadow:[ru]}],opacity:[{opacity:[S]}],"mix-blend":[{"mix-blend":ie()}],"bg-blend":[{"bg-blend":ie()}],filter:[{filter:["","none"]}],blur:[{blur:[n]}],brightness:[{brightness:[r]}],contrast:[{contrast:[u]}],"drop-shadow":[{"drop-shadow":["","none",Bi,Je]}],grayscale:[{grayscale:[d]}],"hue-rotate":[{"hue-rotate":[h]}],invert:[{invert:[m]}],saturate:[{saturate:[E]}],sepia:[{sepia:[P]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[n]}],"backdrop-brightness":[{"backdrop-brightness":[r]}],"backdrop-contrast":[{"backdrop-contrast":[u]}],"backdrop-grayscale":[{"backdrop-grayscale":[d]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[h]}],"backdrop-invert":[{"backdrop-invert":[m]}],"backdrop-opacity":[{"backdrop-opacity":[S]}],"backdrop-saturate":[{"backdrop-saturate":[E]}],"backdrop-sepia":[{"backdrop-sepia":[P]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":[s]}],"border-spacing-x":[{"border-spacing-x":[s]}],"border-spacing-y":[{"border-spacing-y":[s]}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["none","all","","colors","opacity","shadow","transform",Je]}],duration:[{duration:ge()}],ease:[{ease:["linear","in","out","in-out",Je]}],delay:[{delay:ge()}],animate:[{animate:["none","spin","ping","pulse","bounce",Je]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[k]}],"scale-x":[{"scale-x":[k]}],"scale-y":[{"scale-y":[k]}],rotate:[{rotate:[nu,Je]}],"translate-x":[{"translate-x":[O]}],"translate-y":[{"translate-y":[O]}],"skew-x":[{"skew-x":[M]}],"skew-y":[{"skew-y":[M]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",Je]}],accent:[{accent:["auto",e]}],appearance:["appearance-none"],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",Je]}],"caret-color":[{caret:[e]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":G()}],"scroll-mx":[{"scroll-mx":G()}],"scroll-my":[{"scroll-my":G()}],"scroll-ms":[{"scroll-ms":G()}],"scroll-me":[{"scroll-me":G()}],"scroll-mt":[{"scroll-mt":G()}],"scroll-mr":[{"scroll-mr":G()}],"scroll-mb":[{"scroll-mb":G()}],"scroll-ml":[{"scroll-ml":G()}],"scroll-p":[{"scroll-p":G()}],"scroll-px":[{"scroll-px":G()}],"scroll-py":[{"scroll-py":G()}],"scroll-ps":[{"scroll-ps":G()}],"scroll-pe":[{"scroll-pe":G()}],"scroll-pt":[{"scroll-pt":G()}],"scroll-pr":[{"scroll-pr":G()}],"scroll-pb":[{"scroll-pb":G()}],"scroll-pl":[{"scroll-pl":G()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",Je]}],fill:[{fill:[e,"none"]}],"stroke-w":[{stroke:[oo,zi,np]}],stroke:[{stroke:[e,"none"]}],sr:["sr-only","not-sr-only"]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]}}}const Jw=UL(iF),sF=40,is="inpaint",rp="diffusers_sd",nC="diffusers_sdxl",op="diffusers_sd_inpaint",rC="diffusers_sdxl_inpaint",l0="diffusers_other",Ky="#ffcc00bb",oC="ldm",iC="cv2",YR="Fantasy-Studio/Paint-by-Example",aF="timbrooks/instruct-pix2pix",lF="Sanster/PowerPaint-V1-stable-diffusion-inpainting",cF="Sanster/AnyText",uF="out of frame, lowres, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, disfigured, gross proportions, malformed limbs, watermark, signature";function Ce(...e){return Jw(BR(e))}function dF(){async function e(r=""){return(await fetch(r,{method:"GET",cache:"no-cache"})).json()}const t=()=>{const r=document.location;e(r+"/flaskwebgui-keep-server-alive").then(i=>i)},n=3*1e3;t(),setInterval(t,n)}function sC(e){const t=e.split(",")[0].split(":")[1].split(";")[0],n=atob(e.split(",")[1]),r=[];for(let o=0;o{const o=e.src,i=e;i.onload=n,i.onerror=s=>{i.src=o,r(s)},i.src=t})}async function fF(e){const t=URL.createObjectURL(e),n=new Image;return await Ip(n,t),n}function aC(e){return new Promise((t,n)=>{const r=new Image;r.addEventListener("load",()=>{t(r)}),r.addEventListener("error",o=>{n(o)}),r.src=e.toDataURL()})}function pF(e){return new Promise((t,n)=>{const r=new FileReader;r.onload=()=>{const o=new Image;o.onload=()=>{t(o)},o.onerror=()=>{n("无法加载图像。")},o.src=r.result},r.onerror=()=>{n("无法读取文件。")},r.readAsDataURL(e)})}function ku(e,t,n){return fetch(e).then(function(r){return r.arrayBuffer()}).then(function(r){return new File([r],t,{type:n})})}async function hF(){try{const{state:e}=await navigator.permissions.query({name:"clipboard-write"});return e==="granted"}catch{return!1}}function mF(e,t){return new Promise((n,r)=>e.toBlob(async o=>{o?n(o):r(new Error("Expected toBlob() to be defined"))},t))}const gF=async e=>{const t=[new ClipboardItem({[e.type]:e})];await navigator.clipboard.write(t)};function lC(e){return e.nativeEvent.button===2}function cC(e){return e.nativeEvent.button===1}async function vF(e){const t=await mF(e,"image/png");try{await gF(t)}catch{console.log("Copy image failed!")}}function yF(e,t){const n=document.createElement("a");n.href=e,n.download=t,n.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0,view:window})),setTimeout(()=>{n.remove()},100)}function c0(e){const t=e.nativeEvent;return{x:t.offsetX,y:t.offsetY}}function GR(e,t,n=Ky){e.strokeStyle=n,e.lineCap="round",e.lineJoin="round",t.forEach(r=>{!(r!=null&&r.pts.length)||!r.size||(e.lineWidth=r.size,e.beginPath(),e.moveTo(r.pts[0].x,r.pts[0].y),r.pts.forEach(o=>e.lineTo(o.x,o.y)),e.stroke())})}const Lp=(e,t,n,r=[],o="white")=>{const i=document.createElement("canvas");i.width=e,i.height=t;const s=i.getContext("2d");if(!s)throw new Error("could not retrieve mask canvas");return r.forEach(l=>{s.drawImage(l,0,0,e,t)}),n.forEach(l=>{GR(s,l,o)}),i},Ru=e=>new Promise((t,n)=>{const r=new FileReader;r.onload=o=>{var s;const i=(s=o.target)==null?void 0:s.result;t(i)},r.onerror=o=>{n(o)},r.readAsDataURL(e)});function XR(e,t){return function(){return e.apply(t,arguments)}}const{toString:wF}=Object.prototype,{getPrototypeOf:ex}=Object,$m=(e=>t=>{const n=wF.call(t);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),Go=e=>(e=e.toLowerCase(),t=>$m(t)===e),km=e=>t=>typeof t===e,{isArray:gc}=Array,Zu=km("undefined");function xF(e){return e!==null&&!Zu(e)&&e.constructor!==null&&!Zu(e.constructor)&&Kr(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const ZR=Go("ArrayBuffer");function bF(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&ZR(e.buffer),t}const _F=km("string"),Kr=km("function"),qR=km("number"),Rm=e=>e!==null&&typeof e=="object",SF=e=>e===!0||e===!1,Fp=e=>{if($m(e)!=="object")return!1;const t=ex(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},EF=Go("Date"),CF=Go("File"),$F=Go("Blob"),kF=Go("FileList"),RF=e=>Rm(e)&&Kr(e.pipe),TF=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||Kr(e.append)&&((t=$m(e))==="formdata"||t==="object"&&Kr(e.toString)&&e.toString()==="[object FormData]"))},PF=Go("URLSearchParams"),AF=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function kd(e,t,{allOwnKeys:n=!1}={}){if(e===null||typeof e>"u")return;let r,o;if(typeof e!="object"&&(e=[e]),gc(e))for(r=0,o=e.length;r0;)if(o=n[r],t===o.toLowerCase())return o;return null}const JR=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,eT=e=>!Zu(e)&&e!==JR;function Yy(){const{caseless:e}=eT(this)&&this||{},t={},n=(r,o)=>{const i=e&&QR(t,o)||o;Fp(t[i])&&Fp(r)?t[i]=Yy(t[i],r):Fp(r)?t[i]=Yy({},r):gc(r)?t[i]=r.slice():t[i]=r};for(let r=0,o=arguments.length;r(kd(t,(o,i)=>{n&&Kr(o)?e[i]=XR(o,n):e[i]=o},{allOwnKeys:r}),e),MF=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),NF=(e,t,n,r)=>{e.prototype=Object.create(t.prototype,r),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),n&&Object.assign(e.prototype,n)},DF=(e,t,n,r)=>{let o,i,s;const l={};if(t=t||{},e==null)return t;do{for(o=Object.getOwnPropertyNames(e),i=o.length;i-- >0;)s=o[i],(!r||r(s,e,t))&&!l[s]&&(t[s]=e[s],l[s]=!0);e=n!==!1&&ex(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},IF=(e,t,n)=>{e=String(e),(n===void 0||n>e.length)&&(n=e.length),n-=t.length;const r=e.indexOf(t,n);return r!==-1&&r===n},LF=e=>{if(!e)return null;if(gc(e))return e;let t=e.length;if(!qR(t))return null;const n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},FF=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&ex(Uint8Array)),jF=(e,t)=>{const r=(e&&e[Symbol.iterator]).call(e);let o;for(;(o=r.next())&&!o.done;){const i=o.value;t.call(e,i[0],i[1])}},zF=(e,t)=>{let n;const r=[];for(;(n=e.exec(t))!==null;)r.push(n);return r},BF=Go("HTMLFormElement"),UF=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,r,o){return r.toUpperCase()+o}),uC=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),VF=Go("RegExp"),tT=(e,t)=>{const n=Object.getOwnPropertyDescriptors(e),r={};kd(n,(o,i)=>{let s;(s=t(o,i,e))!==!1&&(r[i]=s||o)}),Object.defineProperties(e,r)},WF=e=>{tT(e,(t,n)=>{if(Kr(e)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;const r=e[n];if(Kr(r)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},HF=(e,t)=>{const n={},r=o=>{o.forEach(i=>{n[i]=!0})};return gc(e)?r(e):r(String(e).split(t)),n},KF=()=>{},YF=(e,t)=>(e=+e,Number.isFinite(e)?e:t),u0="abcdefghijklmnopqrstuvwxyz",dC="0123456789",nT={DIGIT:dC,ALPHA:u0,ALPHA_DIGIT:u0+u0.toUpperCase()+dC},GF=(e=16,t=nT.ALPHA_DIGIT)=>{let n="";const{length:r}=t;for(;e--;)n+=t[Math.random()*r|0];return n};function XF(e){return!!(e&&Kr(e.append)&&e[Symbol.toStringTag]==="FormData"&&e[Symbol.iterator])}const ZF=e=>{const t=new Array(10),n=(r,o)=>{if(Rm(r)){if(t.indexOf(r)>=0)return;if(!("toJSON"in r)){t[o]=r;const i=gc(r)?[]:{};return kd(r,(s,l)=>{const u=n(s,o+1);!Zu(u)&&(i[l]=u)}),t[o]=void 0,i}}return r};return n(e,0)},qF=Go("AsyncFunction"),QF=e=>e&&(Rm(e)||Kr(e))&&Kr(e.then)&&Kr(e.catch),oe={isArray:gc,isArrayBuffer:ZR,isBuffer:xF,isFormData:TF,isArrayBufferView:bF,isString:_F,isNumber:qR,isBoolean:SF,isObject:Rm,isPlainObject:Fp,isUndefined:Zu,isDate:EF,isFile:CF,isBlob:$F,isRegExp:VF,isFunction:Kr,isStream:RF,isURLSearchParams:PF,isTypedArray:FF,isFileList:kF,forEach:kd,merge:Yy,extend:OF,trim:AF,stripBOM:MF,inherits:NF,toFlatObject:DF,kindOf:$m,kindOfTest:Go,endsWith:IF,toArray:LF,forEachEntry:jF,matchAll:zF,isHTMLForm:BF,hasOwnProperty:uC,hasOwnProp:uC,reduceDescriptors:tT,freezeMethods:WF,toObjectSet:HF,toCamelCase:UF,noop:KF,toFiniteNumber:YF,findKey:QR,global:JR,isContextDefined:eT,ALPHABET:nT,generateString:GF,isSpecCompliantForm:XF,toJSONObject:ZF,isAsyncFn:qF,isThenable:QF};function ut(e,t,n,r,o){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),n&&(this.config=n),r&&(this.request=r),o&&(this.response=o)}oe.inherits(ut,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:oe.toJSONObject(this.config),code:this.code,status:this.response&&this.response.status?this.response.status:null}}});const rT=ut.prototype,oT={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{oT[e]={value:e}});Object.defineProperties(ut,oT);Object.defineProperty(rT,"isAxiosError",{value:!0});ut.from=(e,t,n,r,o,i)=>{const s=Object.create(rT);return oe.toFlatObject(e,s,function(u){return u!==Error.prototype},l=>l!=="isAxiosError"),ut.call(s,e.message,t,n,r,o),s.cause=e,s.name=e.name,i&&Object.assign(s,i),s};const JF=null;function Gy(e){return oe.isPlainObject(e)||oe.isArray(e)}function iT(e){return oe.endsWith(e,"[]")?e.slice(0,-2):e}function fC(e,t,n){return e?e.concat(t).map(function(o,i){return o=iT(o),!n&&i?"["+o+"]":o}).join(n?".":""):t}function ej(e){return oe.isArray(e)&&!e.some(Gy)}const tj=oe.toFlatObject(oe,{},null,function(t){return/^is[A-Z]/.test(t)});function Tm(e,t,n){if(!oe.isObject(e))throw new TypeError("target must be an object");t=t||new FormData,n=oe.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(_,C){return!oe.isUndefined(C[_])});const r=n.metaTokens,o=n.visitor||h,i=n.dots,s=n.indexes,u=(n.Blob||typeof Blob<"u"&&Blob)&&oe.isSpecCompliantForm(t);if(!oe.isFunction(o))throw new TypeError("visitor must be a function");function d(x){if(x===null)return"";if(oe.isDate(x))return x.toISOString();if(!u&&oe.isBlob(x))throw new ut("Blob is not supported. Use a Buffer instead.");return oe.isArrayBuffer(x)||oe.isTypedArray(x)?u&&typeof Blob=="function"?new Blob([x]):Buffer.from(x):x}function h(x,_,C){let S=x;if(x&&!C&&typeof x=="object"){if(oe.endsWith(_,"{}"))_=r?_:_.slice(0,-2),x=JSON.stringify(x);else if(oe.isArray(x)&&ej(x)||(oe.isFileList(x)||oe.endsWith(_,"[]"))&&(S=oe.toArray(x)))return _=iT(_),S.forEach(function(E,k){!(oe.isUndefined(E)||E===null)&&t.append(s===!0?fC([_],k,i):s===null?_:_+"[]",d(E))}),!1}return Gy(x)?!0:(t.append(fC(C,_,i),d(x)),!1)}const m=[],g=Object.assign(tj,{defaultVisitor:h,convertValue:d,isVisitable:Gy});function y(x,_){if(!oe.isUndefined(x)){if(m.indexOf(x)!==-1)throw Error("Circular reference detected in "+_.join("."));m.push(x),oe.forEach(x,function(S,b){(!(oe.isUndefined(S)||S===null)&&o.call(t,S,oe.isString(b)?b.trim():b,_,g))===!0&&y(S,_?_.concat(b):[b])}),m.pop()}}if(!oe.isObject(e))throw new TypeError("data must be an object");return y(e),t}function pC(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(r){return t[r]})}function tx(e,t){this._pairs=[],e&&Tm(e,this,t)}const sT=tx.prototype;sT.append=function(t,n){this._pairs.push([t,n])};sT.toString=function(t){const n=t?function(r){return t.call(this,r,pC)}:pC;return this._pairs.map(function(o){return n(o[0])+"="+n(o[1])},"").join("&")};function nj(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function aT(e,t,n){if(!t)return e;const r=n&&n.encode||nj,o=n&&n.serialize;let i;if(o?i=o(t,n):i=oe.isURLSearchParams(t)?t.toString():new tx(t,n).toString(r),i){const s=e.indexOf("#");s!==-1&&(e=e.slice(0,s)),e+=(e.indexOf("?")===-1?"?":"&")+i}return e}class rj{constructor(){this.handlers=[]}use(t,n,r){return this.handlers.push({fulfilled:t,rejected:n,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){oe.forEach(this.handlers,function(r){r!==null&&t(r)})}}const hC=rj,lT={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},oj=typeof URLSearchParams<"u"?URLSearchParams:tx,ij=typeof FormData<"u"?FormData:null,sj=typeof Blob<"u"?Blob:null,aj={isBrowser:!0,classes:{URLSearchParams:oj,FormData:ij,Blob:sj},protocols:["http","https","file","blob","url","data"]},cT=typeof window<"u"&&typeof document<"u",lj=(e=>cT&&["ReactNative","NativeScript","NS"].indexOf(e)<0)(typeof navigator<"u"&&navigator.product),cj=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",uj=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:cT,hasStandardBrowserEnv:lj,hasStandardBrowserWebWorkerEnv:cj},Symbol.toStringTag,{value:"Module"})),Io={...uj,...aj};function dj(e,t){return Tm(e,new Io.classes.URLSearchParams,Object.assign({visitor:function(n,r,o,i){return Io.isNode&&oe.isBuffer(n)?(this.append(r,n.toString("base64")),!1):i.defaultVisitor.apply(this,arguments)}},t))}function fj(e){return oe.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function pj(e){const t={},n=Object.keys(e);let r;const o=n.length;let i;for(r=0;r=n.length;return s=!s&&oe.isArray(o)?o.length:s,u?(oe.hasOwnProp(o,s)?o[s]=[o[s],r]:o[s]=r,!l):((!o[s]||!oe.isObject(o[s]))&&(o[s]=[]),t(n,r,o[s],i)&&oe.isArray(o[s])&&(o[s]=pj(o[s])),!l)}if(oe.isFormData(e)&&oe.isFunction(e.entries)){const n={};return oe.forEachEntry(e,(r,o)=>{t(fj(r),o,n,0)}),n}return null}function hj(e,t,n){if(oe.isString(e))try{return(t||JSON.parse)(e),oe.trim(e)}catch(r){if(r.name!=="SyntaxError")throw r}return(n||JSON.stringify)(e)}const nx={transitional:lT,adapter:["xhr","http"],transformRequest:[function(t,n){const r=n.getContentType()||"",o=r.indexOf("application/json")>-1,i=oe.isObject(t);if(i&&oe.isHTMLForm(t)&&(t=new FormData(t)),oe.isFormData(t))return o&&o?JSON.stringify(uT(t)):t;if(oe.isArrayBuffer(t)||oe.isBuffer(t)||oe.isStream(t)||oe.isFile(t)||oe.isBlob(t))return t;if(oe.isArrayBufferView(t))return t.buffer;if(oe.isURLSearchParams(t))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let l;if(i){if(r.indexOf("application/x-www-form-urlencoded")>-1)return dj(t,this.formSerializer).toString();if((l=oe.isFileList(t))||r.indexOf("multipart/form-data")>-1){const u=this.env&&this.env.FormData;return Tm(l?{"files[]":t}:t,u&&new u,this.formSerializer)}}return i||o?(n.setContentType("application/json",!1),hj(t)):t}],transformResponse:[function(t){const n=this.transitional||nx.transitional,r=n&&n.forcedJSONParsing,o=this.responseType==="json";if(t&&oe.isString(t)&&(r&&!this.responseType||o)){const s=!(n&&n.silentJSONParsing)&&o;try{return JSON.parse(t)}catch(l){if(s)throw l.name==="SyntaxError"?ut.from(l,ut.ERR_BAD_RESPONSE,this,null,this.response):l}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:Io.classes.FormData,Blob:Io.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};oe.forEach(["delete","get","head","post","put","patch"],e=>{nx.headers[e]={}});const rx=nx,mj=oe.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),gj=e=>{const t={};let n,r,o;return e&&e.split(` +`).forEach(function(s){o=s.indexOf(":"),n=s.substring(0,o).trim().toLowerCase(),r=s.substring(o+1).trim(),!(!n||t[n]&&mj[n])&&(n==="set-cookie"?t[n]?t[n].push(r):t[n]=[r]:t[n]=t[n]?t[n]+", "+r:r)}),t},mC=Symbol("internals");function ou(e){return e&&String(e).trim().toLowerCase()}function jp(e){return e===!1||e==null?e:oe.isArray(e)?e.map(jp):String(e)}function vj(e){const t=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=n.exec(e);)t[r[1]]=r[2];return t}const yj=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function d0(e,t,n,r,o){if(oe.isFunction(r))return r.call(this,t,n);if(o&&(t=n),!!oe.isString(t)){if(oe.isString(r))return t.indexOf(r)!==-1;if(oe.isRegExp(r))return r.test(t)}}function wj(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,n,r)=>n.toUpperCase()+r)}function xj(e,t){const n=oe.toCamelCase(" "+t);["get","set","has"].forEach(r=>{Object.defineProperty(e,r+n,{value:function(o,i,s){return this[r].call(this,t,o,i,s)},configurable:!0})})}class Pm{constructor(t){t&&this.set(t)}set(t,n,r){const o=this;function i(l,u,d){const h=ou(u);if(!h)throw new Error("header name must be a non-empty string");const m=oe.findKey(o,h);(!m||o[m]===void 0||d===!0||d===void 0&&o[m]!==!1)&&(o[m||u]=jp(l))}const s=(l,u)=>oe.forEach(l,(d,h)=>i(d,h,u));return oe.isPlainObject(t)||t instanceof this.constructor?s(t,n):oe.isString(t)&&(t=t.trim())&&!yj(t)?s(gj(t),n):t!=null&&i(n,t,r),this}get(t,n){if(t=ou(t),t){const r=oe.findKey(this,t);if(r){const o=this[r];if(!n)return o;if(n===!0)return vj(o);if(oe.isFunction(n))return n.call(this,o,r);if(oe.isRegExp(n))return n.exec(o);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,n){if(t=ou(t),t){const r=oe.findKey(this,t);return!!(r&&this[r]!==void 0&&(!n||d0(this,this[r],r,n)))}return!1}delete(t,n){const r=this;let o=!1;function i(s){if(s=ou(s),s){const l=oe.findKey(r,s);l&&(!n||d0(r,r[l],l,n))&&(delete r[l],o=!0)}}return oe.isArray(t)?t.forEach(i):i(t),o}clear(t){const n=Object.keys(this);let r=n.length,o=!1;for(;r--;){const i=n[r];(!t||d0(this,this[i],i,t,!0))&&(delete this[i],o=!0)}return o}normalize(t){const n=this,r={};return oe.forEach(this,(o,i)=>{const s=oe.findKey(r,i);if(s){n[s]=jp(o),delete n[i];return}const l=t?wj(i):String(i).trim();l!==i&&delete n[i],n[l]=jp(o),r[l]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){const n=Object.create(null);return oe.forEach(this,(r,o)=>{r!=null&&r!==!1&&(n[o]=t&&oe.isArray(r)?r.join(", "):r)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,n])=>t+": "+n).join(` +`)}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...n){const r=new this(t);return n.forEach(o=>r.set(o)),r}static accessor(t){const r=(this[mC]=this[mC]={accessors:{}}).accessors,o=this.prototype;function i(s){const l=ou(s);r[l]||(xj(o,s),r[l]=!0)}return oe.isArray(t)?t.forEach(i):i(t),this}}Pm.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);oe.reduceDescriptors(Pm.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(r){this[n]=r}}});oe.freezeMethods(Pm);const pi=Pm;function f0(e,t){const n=this||rx,r=t||n,o=pi.from(r.headers);let i=r.data;return oe.forEach(e,function(l){i=l.call(n,i,o.normalize(),t?t.status:void 0)}),o.normalize(),i}function dT(e){return!!(e&&e.__CANCEL__)}function Rd(e,t,n){ut.call(this,e??"canceled",ut.ERR_CANCELED,t,n),this.name="CanceledError"}oe.inherits(Rd,ut,{__CANCEL__:!0});function bj(e,t,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?e(n):t(new ut("Request failed with status code "+n.status,[ut.ERR_BAD_REQUEST,ut.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}const _j=Io.hasStandardBrowserEnv?{write(e,t,n,r,o,i){const s=[e+"="+encodeURIComponent(t)];oe.isNumber(n)&&s.push("expires="+new Date(n).toGMTString()),oe.isString(r)&&s.push("path="+r),oe.isString(o)&&s.push("domain="+o),i===!0&&s.push("secure"),document.cookie=s.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function Sj(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function Ej(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e}function fT(e,t){return e&&!Sj(t)?Ej(e,t):t}const Cj=Io.hasStandardBrowserEnv?function(){const t=/(msie|trident)/i.test(navigator.userAgent),n=document.createElement("a");let r;function o(i){let s=i;return t&&(n.setAttribute("href",s),s=n.href),n.setAttribute("href",s),{href:n.href,protocol:n.protocol?n.protocol.replace(/:$/,""):"",host:n.host,search:n.search?n.search.replace(/^\?/,""):"",hash:n.hash?n.hash.replace(/^#/,""):"",hostname:n.hostname,port:n.port,pathname:n.pathname.charAt(0)==="/"?n.pathname:"/"+n.pathname}}return r=o(window.location.href),function(s){const l=oe.isString(s)?o(s):s;return l.protocol===r.protocol&&l.host===r.host}}():function(){return function(){return!0}}();function $j(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function kj(e,t){e=e||10;const n=new Array(e),r=new Array(e);let o=0,i=0,s;return t=t!==void 0?t:1e3,function(u){const d=Date.now(),h=r[i];s||(s=d),n[o]=u,r[o]=d;let m=i,g=0;for(;m!==o;)g+=n[m++],m=m%e;if(o=(o+1)%e,o===i&&(i=(i+1)%e),d-s{const i=o.loaded,s=o.lengthComputable?o.total:void 0,l=i-n,u=r(l),d=i<=s;n=i;const h={loaded:i,total:s,progress:s?i/s:void 0,bytes:l,rate:u||void 0,estimated:u&&s&&d?(s-i)/u:void 0,event:o};h[t?"download":"upload"]=!0,e(h)}}const Rj=typeof XMLHttpRequest<"u",Tj=Rj&&function(e){return new Promise(function(n,r){let o=e.data;const i=pi.from(e.headers).normalize();let{responseType:s,withXSRFToken:l}=e,u;function d(){e.cancelToken&&e.cancelToken.unsubscribe(u),e.signal&&e.signal.removeEventListener("abort",u)}let h;if(oe.isFormData(o)){if(Io.hasStandardBrowserEnv||Io.hasStandardBrowserWebWorkerEnv)i.setContentType(!1);else if((h=i.getContentType())!==!1){const[_,...C]=h?h.split(";").map(S=>S.trim()).filter(Boolean):[];i.setContentType([_||"multipart/form-data",...C].join("; "))}}let m=new XMLHttpRequest;if(e.auth){const _=e.auth.username||"",C=e.auth.password?unescape(encodeURIComponent(e.auth.password)):"";i.set("Authorization","Basic "+btoa(_+":"+C))}const g=fT(e.baseURL,e.url);m.open(e.method.toUpperCase(),aT(g,e.params,e.paramsSerializer),!0),m.timeout=e.timeout;function y(){if(!m)return;const _=pi.from("getAllResponseHeaders"in m&&m.getAllResponseHeaders()),S={data:!s||s==="text"||s==="json"?m.responseText:m.response,status:m.status,statusText:m.statusText,headers:_,config:e,request:m};bj(function(E){n(E),d()},function(E){r(E),d()},S),m=null}if("onloadend"in m?m.onloadend=y:m.onreadystatechange=function(){!m||m.readyState!==4||m.status===0&&!(m.responseURL&&m.responseURL.indexOf("file:")===0)||setTimeout(y)},m.onabort=function(){m&&(r(new ut("Request aborted",ut.ECONNABORTED,e,m)),m=null)},m.onerror=function(){r(new ut("Network Error",ut.ERR_NETWORK,e,m)),m=null},m.ontimeout=function(){let C=e.timeout?"timeout of "+e.timeout+"ms exceeded":"timeout exceeded";const S=e.transitional||lT;e.timeoutErrorMessage&&(C=e.timeoutErrorMessage),r(new ut(C,S.clarifyTimeoutError?ut.ETIMEDOUT:ut.ECONNABORTED,e,m)),m=null},Io.hasStandardBrowserEnv&&(l&&oe.isFunction(l)&&(l=l(e)),l||l!==!1&&Cj(g))){const _=e.xsrfHeaderName&&e.xsrfCookieName&&_j.read(e.xsrfCookieName);_&&i.set(e.xsrfHeaderName,_)}o===void 0&&i.setContentType(null),"setRequestHeader"in m&&oe.forEach(i.toJSON(),function(C,S){m.setRequestHeader(S,C)}),oe.isUndefined(e.withCredentials)||(m.withCredentials=!!e.withCredentials),s&&s!=="json"&&(m.responseType=e.responseType),typeof e.onDownloadProgress=="function"&&m.addEventListener("progress",gC(e.onDownloadProgress,!0)),typeof e.onUploadProgress=="function"&&m.upload&&m.upload.addEventListener("progress",gC(e.onUploadProgress)),(e.cancelToken||e.signal)&&(u=_=>{m&&(r(!_||_.type?new Rd(null,e,m):_),m.abort(),m=null)},e.cancelToken&&e.cancelToken.subscribe(u),e.signal&&(e.signal.aborted?u():e.signal.addEventListener("abort",u)));const x=$j(g);if(x&&Io.protocols.indexOf(x)===-1){r(new ut("Unsupported protocol "+x+":",ut.ERR_BAD_REQUEST,e));return}m.send(o||null)})},Xy={http:JF,xhr:Tj};oe.forEach(Xy,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});const vC=e=>`- ${e}`,Pj=e=>oe.isFunction(e)||e===null||e===!1,pT={getAdapter:e=>{e=oe.isArray(e)?e:[e];const{length:t}=e;let n,r;const o={};for(let i=0;i`adapter ${l} `+(u===!1?"is not supported by the environment":"is not available in the build"));let s=t?i.length>1?`since : +`+i.map(vC).join(` +`):" "+vC(i[0]):"as no adapter specified";throw new ut("There is no suitable adapter to dispatch the request "+s,"ERR_NOT_SUPPORT")}return r},adapters:Xy};function p0(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Rd(null,e)}function yC(e){return p0(e),e.headers=pi.from(e.headers),e.data=f0.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),pT.getAdapter(e.adapter||rx.adapter)(e).then(function(r){return p0(e),r.data=f0.call(e,e.transformResponse,r),r.headers=pi.from(r.headers),r},function(r){return dT(r)||(p0(e),r&&r.response&&(r.response.data=f0.call(e,e.transformResponse,r.response),r.response.headers=pi.from(r.response.headers))),Promise.reject(r)})}const wC=e=>e instanceof pi?e.toJSON():e;function Jl(e,t){t=t||{};const n={};function r(d,h,m){return oe.isPlainObject(d)&&oe.isPlainObject(h)?oe.merge.call({caseless:m},d,h):oe.isPlainObject(h)?oe.merge({},h):oe.isArray(h)?h.slice():h}function o(d,h,m){if(oe.isUndefined(h)){if(!oe.isUndefined(d))return r(void 0,d,m)}else return r(d,h,m)}function i(d,h){if(!oe.isUndefined(h))return r(void 0,h)}function s(d,h){if(oe.isUndefined(h)){if(!oe.isUndefined(d))return r(void 0,d)}else return r(void 0,h)}function l(d,h,m){if(m in t)return r(d,h);if(m in e)return r(void 0,d)}const u={url:i,method:i,data:i,baseURL:s,transformRequest:s,transformResponse:s,paramsSerializer:s,timeout:s,timeoutMessage:s,withCredentials:s,withXSRFToken:s,adapter:s,responseType:s,xsrfCookieName:s,xsrfHeaderName:s,onUploadProgress:s,onDownloadProgress:s,decompress:s,maxContentLength:s,maxBodyLength:s,beforeRedirect:s,transport:s,httpAgent:s,httpsAgent:s,cancelToken:s,socketPath:s,responseEncoding:s,validateStatus:l,headers:(d,h)=>o(wC(d),wC(h),!0)};return oe.forEach(Object.keys(Object.assign({},e,t)),function(h){const m=u[h]||o,g=m(e[h],t[h],h);oe.isUndefined(g)&&m!==l||(n[h]=g)}),n}const hT="1.6.2",ox={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{ox[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const xC={};ox.transitional=function(t,n,r){function o(i,s){return"[Axios v"+hT+"] Transitional option '"+i+"'"+s+(r?". "+r:"")}return(i,s,l)=>{if(t===!1)throw new ut(o(s," has been removed"+(n?" in "+n:"")),ut.ERR_DEPRECATED);return n&&!xC[s]&&(xC[s]=!0,console.warn(o(s," has been deprecated since v"+n+" and will be removed in the near future"))),t?t(i,s,l):!0}};function Aj(e,t,n){if(typeof e!="object")throw new ut("options must be an object",ut.ERR_BAD_OPTION_VALUE);const r=Object.keys(e);let o=r.length;for(;o-- >0;){const i=r[o],s=t[i];if(s){const l=e[i],u=l===void 0||s(l,i,e);if(u!==!0)throw new ut("option "+i+" must be "+u,ut.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new ut("Unknown option "+i,ut.ERR_BAD_OPTION)}}const Zy={assertOptions:Aj,validators:ox},Ui=Zy.validators;class Ph{constructor(t){this.defaults=t,this.interceptors={request:new hC,response:new hC}}request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=Jl(this.defaults,n);const{transitional:r,paramsSerializer:o,headers:i}=n;r!==void 0&&Zy.assertOptions(r,{silentJSONParsing:Ui.transitional(Ui.boolean),forcedJSONParsing:Ui.transitional(Ui.boolean),clarifyTimeoutError:Ui.transitional(Ui.boolean)},!1),o!=null&&(oe.isFunction(o)?n.paramsSerializer={serialize:o}:Zy.assertOptions(o,{encode:Ui.function,serialize:Ui.function},!0)),n.method=(n.method||this.defaults.method||"get").toLowerCase();let s=i&&oe.merge(i.common,i[n.method]);i&&oe.forEach(["delete","get","head","post","put","patch","common"],x=>{delete i[x]}),n.headers=pi.concat(s,i);const l=[];let u=!0;this.interceptors.request.forEach(function(_){typeof _.runWhen=="function"&&_.runWhen(n)===!1||(u=u&&_.synchronous,l.unshift(_.fulfilled,_.rejected))});const d=[];this.interceptors.response.forEach(function(_){d.push(_.fulfilled,_.rejected)});let h,m=0,g;if(!u){const x=[yC.bind(this),void 0];for(x.unshift.apply(x,l),x.push.apply(x,d),g=x.length,h=Promise.resolve(n);m{if(!r._listeners)return;let i=r._listeners.length;for(;i-- >0;)r._listeners[i](o);r._listeners=null}),this.promise.then=o=>{let i;const s=new Promise(l=>{r.subscribe(l),i=l}).then(o);return s.cancel=function(){r.unsubscribe(i)},s},t(function(i,s,l){r.reason||(r.reason=new Rd(i,s,l),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}static source(){let t;return{token:new ix(function(o){t=o}),cancel:t}}}const Oj=ix;function Mj(e){return function(n){return e.apply(null,n)}}function Nj(e){return oe.isObject(e)&&e.isAxiosError===!0}const qy={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(qy).forEach(([e,t])=>{qy[t]=e});const Dj=qy;function mT(e){const t=new zp(e),n=XR(zp.prototype.request,t);return oe.extend(n,zp.prototype,t,{allOwnKeys:!0}),oe.extend(n,t,null,{allOwnKeys:!0}),n.create=function(o){return mT(Jl(e,o))},n}const Jt=mT(rx);Jt.Axios=zp;Jt.CanceledError=Rd;Jt.CancelToken=Oj;Jt.isCancel=dT;Jt.VERSION=hT;Jt.toFormData=Tm;Jt.AxiosError=ut;Jt.Cancel=Jt.CanceledError;Jt.all=function(t){return Promise.all(t)};Jt.spread=Mj;Jt.isAxiosError=Nj;Jt.mergeConfig=Jl;Jt.AxiosHeaders=pi;Jt.formToJSON=e=>uT(oe.isHTMLForm(e)?new FormData(e):e);Jt.getAdapter=pT.getAdapter;Jt.HttpStatusCode=Dj;Jt.default=Jt;const Ij=Jt,Ms="/api/v1",vc=Ij.create({baseURL:Ms});async function Lj(e,t,n,r,o,i=null){const s=await Ru(e),l=await Ru(o),u=i?await Ru(i):null,d=await fetch(`${Ms}/inpaint`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({image:s,mask:l,ldm_steps:t.ldmSteps,ldm_sampler:t.ldmSampler,zits_wireframe:t.zitsWireframe,cv2_flag:t.cv2Flag,cv2_radius:t.cv2Radius,hd_strategy:"Crop",hd_strategy_crop_triger_size:640,hd_strategy_crop_margin:128,hd_trategy_resize_imit:2048,prompt:t.prompt,negative_prompt:t.negativePrompt,use_croper:t.showCropper,croper_x:n.x,croper_y:n.y,croper_height:n.height,croper_width:n.width,use_extender:t.showExtender,extender_x:r.x,extender_y:r.y,extender_height:r.height,extender_width:r.width,sd_mask_blur:t.sdMaskBlur,sd_strength:t.sdStrength,sd_steps:t.sdSteps,sd_guidance_scale:t.sdGuidanceScale,sd_sampler:t.sdSampler,sd_seed:t.seedFixed?t.seed:-1,sd_match_histograms:t.sdMatchHistograms,sd_freeu:t.enableFreeu,sd_freeu_config:t.freeuConfig,sd_lcm_lora:t.enableLCMLora,paint_by_example_example_image:u,p2p_image_guidance_scale:t.p2pImageGuidanceScale,enable_controlnet:t.enableControlnet,controlnet_conditioning_scale:t.controlnetConditioningScale,controlnet_method:t.controlnetMethod?t.controlnetMethod:"",powerpaint_task:t.showExtender?kl.outpainting:t.powerpaintTask})});if(d.ok){const m=await d.blob();return{blob:URL.createObjectURL(m),seed:d.headers.get("X-Seed")}}const h=await d.json();throw new Error(`Something went wrong: ${h.errors}`)}async function Fj(){return(await vc.get("/server-config")).data}async function jj(e){return(await vc.post("/model",{name:e})).data}async function zj(){return(await vc.get("/model")).data}function Bj(){return vc.get("/models").then(e=>e.data)}async function gT(e,t,n,r,o){const i=await Ru(n),l=await fetch(`${Ms}/${e?"run_plugin_gen_mask":"run_plugin_gen_image"}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t,image:i,upscale:r,clicks:o})});if(l.ok){const d=await l.blob();return{blob:URL.createObjectURL(d)}}const u=await l.json();throw new Error(u)}async function Uj(e,t){const n=await fetch(`${Ms}/media_file?tab=${e}&filename=${encodeURIComponent(t)}`,{method:"GET"});if(n.ok){const o=await n.blob();return new File([o],t,{type:n.headers.get("Content-Type")??"image/png"})}const r=await n.json();throw new Error(r.errors)}async function Vj(e){return(await vc.get("medias",{params:{tab:e}})).data}async function Wj(e,t,n){const r=await ku(e.src,t,n),o=new FormData;o.append("file",r);try{const i=await fetch(`${Ms}/save_image`,{method:"POST",body:o});if(!i.ok){const s=await i.text();throw new Error(s)}}catch(i){throw new Error(`Something went wrong: ${i}`)}}async function Hj(e){const t=new FormData;return t.append("file",e),(await vc.post("/gen-info",t)).data}async function Kj(e,t,n){const r=await Ru(e),o=await fetch(`${Ms}/adjust_mask`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mask:r,operate:t,kernel_size:n})});if(o.ok)return await o.blob();const i=await o.json();throw new Error(i)}function Yj(){const[e,t]=f.useState(null),n=f.useCallback(()=>{const r=new Headers;r.append("pragma","no-cache"),r.append("cache-control","no-cache"),fetch(`${Ms}/inputimage`,{headers:r}).then(async o=>{var l;if(!o.ok)throw new Error("No input image found");const i=(l=o.headers.get("content-disposition"))==null?void 0:l.split("filename=")[1].split(";")[0],s=await o.blob();if(s&&s.type.startsWith("image")){const u=new File([s],i!==void 0?i:"inputImage");t(u)}}).catch(o=>{console.log(o)})},[t]);return f.useEffect(()=>{n()},[n]),e}function xo(e,t){if(e==null)return{};var n={},r=Object.keys(e),o,i;for(i=0;i=0)&&(n[o]=e[o]);return n}var Gj=["color"],Xj=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,Gj);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),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:r,fillRule:"evenodd",clipRule:"evenodd"}))}),Zj=["color"],vT=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,Zj);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M11.4669 3.72684C11.7558 3.91574 11.8369 4.30308 11.648 4.59198L7.39799 11.092C7.29783 11.2452 7.13556 11.3467 6.95402 11.3699C6.77247 11.3931 6.58989 11.3355 6.45446 11.2124L3.70446 8.71241C3.44905 8.48022 3.43023 8.08494 3.66242 7.82953C3.89461 7.57412 4.28989 7.55529 4.5453 7.78749L6.75292 9.79441L10.6018 3.90792C10.7907 3.61902 11.178 3.53795 11.4669 3.72684Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),qj=["color"],Qj=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,qj);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M3.13523 6.15803C3.3241 5.95657 3.64052 5.94637 3.84197 6.13523L7.5 9.56464L11.158 6.13523C11.3595 5.94637 11.6759 5.95657 11.8648 6.15803C12.0536 6.35949 12.0434 6.67591 11.842 6.86477L7.84197 10.6148C7.64964 10.7951 7.35036 10.7951 7.15803 10.6148L3.15803 6.86477C2.95657 6.67591 2.94637 6.35949 3.13523 6.15803Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),Jj=["color"],ez=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,Jj);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M6.1584 3.13508C6.35985 2.94621 6.67627 2.95642 6.86514 3.15788L10.6151 7.15788C10.7954 7.3502 10.7954 7.64949 10.6151 7.84182L6.86514 11.8418C6.67627 12.0433 6.35985 12.0535 6.1584 11.8646C5.95694 11.6757 5.94673 11.3593 6.1356 11.1579L9.565 7.49985L6.1356 3.84182C5.94673 3.64036 5.95694 3.32394 6.1584 3.13508Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),tz=["color"],nz=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,tz);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M3.13523 8.84197C3.3241 9.04343 3.64052 9.05363 3.84197 8.86477L7.5 5.43536L11.158 8.86477C11.3595 9.05363 11.6759 9.04343 11.8648 8.84197C12.0536 8.64051 12.0434 8.32409 11.842 8.13523L7.84197 4.38523C7.64964 4.20492 7.35036 4.20492 7.15803 4.38523L3.15803 8.13523C2.95657 8.32409 2.94637 8.64051 3.13523 8.84197Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),rz=["color"],yT=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,rz);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),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:r,fillRule:"evenodd",clipRule:"evenodd"}))}),oz=["color"],iz=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,oz);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M9.875 7.5C9.875 8.81168 8.81168 9.875 7.5 9.875C6.18832 9.875 5.125 8.81168 5.125 7.5C5.125 6.18832 6.18832 5.125 7.5 5.125C8.81168 5.125 9.875 6.18832 9.875 7.5Z",fill:r}))}),sz=["color"],az=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,sz);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M10 6.5C10 8.433 8.433 10 6.5 10C4.567 10 3 8.433 3 6.5C3 4.567 4.567 3 6.5 3C8.433 3 10 4.567 10 6.5ZM9.30884 10.0159C8.53901 10.6318 7.56251 11 6.5 11C4.01472 11 2 8.98528 2 6.5C2 4.01472 4.01472 2 6.5 2C8.98528 2 11 4.01472 11 6.5C11 7.56251 10.6318 8.53901 10.0159 9.30884L12.8536 12.1464C13.0488 12.3417 13.0488 12.6583 12.8536 12.8536C12.6583 13.0488 12.3417 13.0488 12.1464 12.8536L9.30884 10.0159Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),lz=["color"],cz=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,lz);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M3.24182 2.32181C3.3919 2.23132 3.5784 2.22601 3.73338 2.30781L12.7334 7.05781C12.8974 7.14436 13 7.31457 13 7.5C13 7.68543 12.8974 7.85564 12.7334 7.94219L3.73338 12.6922C3.5784 12.774 3.3919 12.7687 3.24182 12.6782C3.09175 12.5877 3 12.4252 3 12.25V2.75C3 2.57476 3.09175 2.4123 3.24182 2.32181ZM4 3.57925V11.4207L11.4288 7.5L4 3.57925Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),uz=["color"],dz=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,uz);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M7 2H1.5C1.22386 2 1 2.22386 1 2.5V7H7V2ZM8 2V7H14V2.5C14 2.22386 13.7761 2 13.5 2H8ZM7 8H1V12.5C1 12.7761 1.22386 13 1.5 13H7V8ZM8 13V8H14V12.5C14 12.7761 13.7761 13 13.5 13H8ZM1.5 1C0.671573 1 0 1.67157 0 2.5V12.5C0 13.3284 0.671573 14 1.5 14H13.5C14.3284 14 15 13.3284 15 12.5V2.5C15 1.67157 14.3284 1 13.5 1H1.5Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),fz=["color"],pz=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,fz);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M1.5 2H13.5C13.7761 2 14 2.22386 14 2.5V7H1V2.5C1 2.22386 1.22386 2 1.5 2ZM1 8V12.5C1 12.7761 1.22386 13 1.5 13H13.5C13.7761 13 14 12.7761 14 12.5V8H1ZM0 2.5C0 1.67157 0.671573 1 1.5 1H13.5C14.3284 1 15 1.67157 15 2.5V12.5C15 13.3284 14.3284 14 13.5 14H1.5C0.671573 14 0 13.3284 0 12.5V2.5Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))});function Y(){return Y=Object.assign?Object.assign.bind():function(e){for(var t=1;te.forEach(n=>hz(n,t))}function Be(...e){return f.useCallback(Am(...e),e)}const Wo=f.forwardRef((e,t)=>{const{children:n,...r}=e,o=f.Children.toArray(n),i=o.find(mz);if(i){const s=i.props.children,l=o.map(u=>u===i?f.Children.count(s)>1?f.Children.only(null):f.isValidElement(s)?s.props.children:null:u);return f.createElement(Qy,Y({},r,{ref:t}),f.isValidElement(s)?f.cloneElement(s,void 0,l):null)}return f.createElement(Qy,Y({},r,{ref:t}),n)});Wo.displayName="Slot";const Qy=f.forwardRef((e,t)=>{const{children:n,...r}=e;return f.isValidElement(n)?f.cloneElement(n,{...gz(r,n.props),ref:t?Am(t,n.ref):n.ref}):f.Children.count(n)>1?f.Children.only(null):null});Qy.displayName="SlotClone";const sx=({children:e})=>f.createElement(f.Fragment,null,e);function mz(e){return f.isValidElement(e)&&e.type===sx}function gz(e,t){const n={...t};for(const r in t){const o=e[r],i=t[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...l)=>{i(...l),o(...l)}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...e,...n}}const bC=e=>typeof e=="boolean"?"".concat(e):e===0?"0":e,_C=BR,Om=(e,t)=>n=>{var r;if((t==null?void 0:t.variants)==null)return _C(e,n==null?void 0:n.class,n==null?void 0:n.className);const{variants:o,defaultVariants:i}=t,s=Object.keys(o).map(d=>{const h=n==null?void 0:n[d],m=i==null?void 0:i[d];if(h===null)return null;const g=bC(h)||bC(m);return o[d][g]}),l=n&&Object.entries(n).reduce((d,h)=>{let[m,g]=h;return g===void 0||(d[m]=g),d},{}),u=t==null||(r=t.compoundVariants)===null||r===void 0?void 0:r.reduce((d,h)=>{let{class:m,className:g,...y}=h;return Object.entries(y).every(x=>{let[_,C]=x;return Array.isArray(C)?C.includes({...i,...l}[_]):{...i,...l}[_]===C})?[...d,m,g]:d},[]);return _C(e,s,u,n==null?void 0:n.class,n==null?void 0:n.className)};var vz={VITE_BACKEND:"http://127.0.0.1:8080",BASE_URL:"/",MODE:"production",DEV:!1,PROD:!0,SSR:!1};function yz(e,t){let n;try{n=e()}catch{return}return{getItem:o=>{var i;const s=u=>u===null?null:JSON.parse(u,t==null?void 0:t.reviver),l=(i=n.getItem(o))!=null?i:null;return l instanceof Promise?l.then(s):s(l)},setItem:(o,i)=>n.setItem(o,JSON.stringify(i,t==null?void 0:t.replacer)),removeItem:o=>n.removeItem(o)}}const qu=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then(r){return qu(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return qu(r)(n)}}}},wz=(e,t)=>(n,r,o)=>{let i={getStorage:()=>localStorage,serialize:JSON.stringify,deserialize:JSON.parse,partialize:C=>C,version:0,merge:(C,S)=>({...S,...C}),...t},s=!1;const l=new Set,u=new Set;let d;try{d=i.getStorage()}catch{}if(!d)return e((...C)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),n(...C)},r,o);const h=qu(i.serialize),m=()=>{const C=i.partialize({...r()});let S;const b=h({state:C,version:i.version}).then(E=>d.setItem(i.name,E)).catch(E=>{S=E});if(S)throw S;return b},g=o.setState;o.setState=(C,S)=>{g(C,S),m()};const y=e((...C)=>{n(...C),m()},r,o);let x;const _=()=>{var C;if(!d)return;s=!1,l.forEach(b=>b(r()));const S=((C=i.onRehydrateStorage)==null?void 0:C.call(i,r()))||void 0;return qu(d.getItem.bind(d))(i.name).then(b=>{if(b)return i.deserialize(b)}).then(b=>{if(b)if(typeof b.version=="number"&&b.version!==i.version){if(i.migrate)return i.migrate(b.state,b.version);console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return b.state}).then(b=>{var E;return x=i.merge(b,(E=r())!=null?E:y),n(x,!0),m()}).then(()=>{S==null||S(x,void 0),s=!0,u.forEach(b=>b(x))}).catch(b=>{S==null||S(void 0,b)})};return o.persist={setOptions:C=>{i={...i,...C},C.getStorage&&(d=C.getStorage())},clearStorage:()=>{d==null||d.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>_(),hasHydrated:()=>s,onHydrate:C=>(l.add(C),()=>{l.delete(C)}),onFinishHydration:C=>(u.add(C),()=>{u.delete(C)})},_(),x||y},xz=(e,t)=>(n,r,o)=>{let i={storage:yz(()=>localStorage),partialize:_=>_,version:0,merge:(_,C)=>({...C,..._}),...t},s=!1;const l=new Set,u=new Set;let d=i.storage;if(!d)return e((..._)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),n(..._)},r,o);const h=()=>{const _=i.partialize({...r()});return d.setItem(i.name,{state:_,version:i.version})},m=o.setState;o.setState=(_,C)=>{m(_,C),h()};const g=e((..._)=>{n(..._),h()},r,o);let y;const x=()=>{var _,C;if(!d)return;s=!1,l.forEach(b=>{var E;return b((E=r())!=null?E:g)});const S=((C=i.onRehydrateStorage)==null?void 0:C.call(i,(_=r())!=null?_:g))||void 0;return qu(d.getItem.bind(d))(i.name).then(b=>{if(b)if(typeof b.version=="number"&&b.version!==i.version){if(i.migrate)return i.migrate(b.state,b.version);console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return b.state}).then(b=>{var E;return y=i.merge(b,(E=r())!=null?E:g),n(y,!0),h()}).then(()=>{S==null||S(y,void 0),y=r(),s=!0,u.forEach(b=>b(y))}).catch(b=>{S==null||S(void 0,b)})};return o.persist={setOptions:_=>{i={...i,..._},_.storage&&(d=_.storage)},clearStorage:()=>{d==null||d.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>x(),hasHydrated:()=>s,onHydrate:_=>(l.add(_),()=>{l.delete(_)}),onFinishHydration:_=>(u.add(_),()=>{u.delete(_)})},i.skipHydration||x(),y||g},bz=(e,t)=>"getStorage"in t||"serialize"in t||"deserialize"in t?((vz?"production":void 0)!=="production"&&console.warn("[DEPRECATED] `getStorage`, `serialize` and `deserialize` options are deprecated. Use `storage` option instead."),wz(e,t)):xz(e,t),_z=bz;function Sz(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,o]of e)if(!Object.is(o,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{t(n,r,e)}):e.forEach((n,r)=>t(r,n,e))}function Mm(e){const t=e[wr];return t?t.type_:Array.isArray(e)?1:Nm(e)?2:Dm(e)?3:0}function Jy(e,t){return Mm(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function bT(e,t,n){const r=Mm(e);r===2?e.set(t,n):r===3?e.add(n):e[t]=n}function Cz(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function Nm(e){return e instanceof Map}function Dm(e){return e instanceof Set}function Js(e){return e.copy_||e.base_}function e1(e,t){if(Nm(e))return new Map(e);if(Dm(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);if(!t&&xT(e))return ec(e)?{...e}:Object.assign(Object.create(null),e);const n=Object.getOwnPropertyDescriptors(e);delete n[wr];let r=Reflect.ownKeys(n);for(let o=0;o1&&(e.set=e.add=e.clear=e.delete=$z),Object.freeze(e),t&&Qu(e,(n,r)=>ax(r,!0))),e}function $z(){ho(2)}function Im(e){return Object.isFrozen(e)}var kz={};function ka(e){const t=kz[e];return t||ho(0,e),t}var Ju;function _T(){return Ju}function Rz(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function EC(e,t){t&&(ka("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function t1(e){n1(e),e.drafts_.forEach(Tz),e.drafts_=null}function n1(e){e===Ju&&(Ju=e.parent_)}function CC(e){return Ju=Rz(Ju,e)}function Tz(e){const t=e[wr];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function $C(e,t){t.unfinalizedDrafts_=t.drafts_.length;const n=t.drafts_[0];return e!==void 0&&e!==n?(n[wr].modified_&&(t1(t),ho(4)),$a(e)&&(e=Ah(t,e),t.parent_||Oh(t,e)),t.patches_&&ka("Patches").generateReplacementPatches_(n[wr].base_,e,t.patches_,t.inversePatches_)):e=Ah(t,n,[]),t1(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==wT?e:void 0}function Ah(e,t,n){if(Im(t))return t;const r=t[wr];if(!r)return Qu(t,(o,i)=>kC(e,r,t,o,i,n)),t;if(r.scope_!==e)return t;if(!r.modified_)return Oh(e,r.base_,!0),r.base_;if(!r.finalized_){r.finalized_=!0,r.scope_.unfinalizedDrafts_--;const o=r.copy_;let i=o,s=!1;r.type_===3&&(i=new Set(o),o.clear(),s=!0),Qu(i,(l,u)=>kC(e,r,o,l,u,n,s)),Oh(e,o,!1),n&&e.patches_&&ka("Patches").generatePatches_(r,n,e.patches_,e.inversePatches_)}return r.copy_}function kC(e,t,n,r,o,i,s){if(tc(o)){const l=i&&t&&t.type_!==3&&!Jy(t.assigned_,r)?i.concat(r):void 0,u=Ah(e,o,l);if(bT(n,r,u),tc(u))e.canAutoFreeze_=!1;else return}else s&&n.add(o);if($a(o)&&!Im(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;Ah(e,o),(!t||!t.scope_.parent_)&&Oh(e,o)}}function Oh(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&ax(t,n)}function Pz(e,t){const n=Array.isArray(e),r={type_:n?1:0,scope_:t?t.scope_:_T(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1};let o=r,i=lx;n&&(o=[r],i=ed);const{revoke:s,proxy:l}=Proxy.revocable(o,i);return r.draft_=l,r.revoke_=s,l}var lx={get(e,t){if(t===wr)return e;const n=Js(e);if(!Jy(n,t))return Az(e,n,t);const r=n[t];return e.finalized_||!$a(r)?r:r===h0(e.base_,t)?(m0(e),e.copy_[t]=o1(r,e)):r},has(e,t){return t in Js(e)},ownKeys(e){return Reflect.ownKeys(Js(e))},set(e,t,n){const r=ST(Js(e),t);if(r!=null&&r.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){const o=h0(Js(e),t),i=o==null?void 0:o[wr];if(i&&i.base_===n)return e.copy_[t]=n,e.assigned_[t]=!1,!0;if(Cz(n,o)&&(n!==void 0||Jy(e.base_,t)))return!0;m0(e),r1(e)}return e.copy_[t]===n&&(n!==void 0||t in e.copy_)||Number.isNaN(n)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=n,e.assigned_[t]=!0),!0},deleteProperty(e,t){return h0(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,m0(e),r1(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){const n=Js(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:r.enumerable,value:n[t]}},defineProperty(){ho(11)},getPrototypeOf(e){return ec(e.base_)},setPrototypeOf(){ho(12)}},ed={};Qu(lx,(e,t)=>{ed[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});ed.deleteProperty=function(e,t){return ed.set.call(this,e,t,void 0)};ed.set=function(e,t,n){return lx.set.call(this,e[0],t,n,e[0])};function h0(e,t){const n=e[wr];return(n?Js(n):e)[t]}function Az(e,t,n){var o;const r=ST(t,n);return r?"value"in r?r.value:(o=r.get)==null?void 0:o.call(e.draft_):void 0}function ST(e,t){if(!(t in e))return;let n=ec(e);for(;n;){const r=Object.getOwnPropertyDescriptor(n,t);if(r)return r;n=ec(n)}}function r1(e){e.modified_||(e.modified_=!0,e.parent_&&r1(e.parent_))}function m0(e){e.copy_||(e.copy_=e1(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var Oz=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(t,n,r)=>{if(typeof t=="function"&&typeof n!="function"){const i=n;n=t;const s=this;return function(u=i,...d){return s.produce(u,h=>n.call(this,h,...d))}}typeof n!="function"&&ho(6),r!==void 0&&typeof r!="function"&&ho(7);let o;if($a(t)){const i=CC(this),s=o1(t,void 0);let l=!0;try{o=n(s),l=!1}finally{l?t1(i):n1(i)}return EC(i,r),$C(o,i)}else if(!t||typeof t!="object"){if(o=n(t),o===void 0&&(o=t),o===wT&&(o=void 0),this.autoFreeze_&&ax(o,!0),r){const i=[],s=[];ka("Patches").generateReplacementPatches_(t,o,i,s),r(i,s)}return o}else ho(1,t)},this.produceWithPatches=(t,n)=>{if(typeof t=="function")return(s,...l)=>this.produceWithPatches(s,u=>t(u,...l));let r,o;return[this.produce(t,n,(s,l)=>{r=s,o=l}),r,o]},typeof(e==null?void 0:e.autoFreeze)=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof(e==null?void 0:e.useStrictShallowCopy)=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){$a(e)||ho(8),tc(e)&&(e=Mz(e));const t=CC(this),n=o1(e,void 0);return n[wr].isManual_=!0,n1(t),n}finishDraft(e,t){const n=e&&e[wr];(!n||!n.isManual_)&&ho(9);const{scope_:r}=n;return EC(r,t),$C(void 0,r)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let n;for(n=t.length-1;n>=0;n--){const o=t[n];if(o.path.length===0&&o.op==="replace"){e=o.value;break}}n>-1&&(t=t.slice(n+1));const r=ka("Patches").applyPatches_;return tc(e)?r(e,t):this.produce(e,o=>r(o,t))}};function o1(e,t){const n=Nm(e)?ka("MapSet").proxyMap_(e,t):Dm(e)?ka("MapSet").proxySet_(e,t):Pz(e,t);return(t?t.scope_:_T()).drafts_.push(n),n}function Mz(e){return tc(e)||ho(10,e),ET(e)}function ET(e){if(!$a(e)||Im(e))return e;const t=e[wr];let n;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=e1(e,t.scope_.immer_.useStrictShallowCopy_)}else n=e1(e,!0);return Qu(n,(r,o)=>{bT(n,r,ET(o))}),t&&(t.finalized_=!1),n}var xr=new Oz,Nz=xr.produce;xr.produceWithPatches.bind(xr);xr.setAutoFreeze.bind(xr);xr.setUseStrictShallowCopy.bind(xr);xr.applyPatches.bind(xr);xr.createDraft.bind(xr);xr.finishDraft.bind(xr);const Dz=e=>(t,n,r)=>(r.setState=(o,i,...s)=>{const l=typeof o=="function"?Nz(o):o;return t(l,i,...s)},e(r.setState,n,r)),Iz=Dz;var CT={exports:{}},$T={},kT={exports:{}},RT={};/** + * @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 nc=f;function Lz(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var Fz=typeof Object.is=="function"?Object.is:Lz,jz=nc.useState,zz=nc.useEffect,Bz=nc.useLayoutEffect,Uz=nc.useDebugValue;function Vz(e,t){var n=t(),r=jz({inst:{value:n,getSnapshot:t}}),o=r[0].inst,i=r[1];return Bz(function(){o.value=n,o.getSnapshot=t,g0(o)&&i({inst:o})},[e,n,t]),zz(function(){return g0(o)&&i({inst:o}),e(function(){g0(o)&&i({inst:o})})},[e]),Uz(n),n}function g0(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!Fz(e,n)}catch{return!0}}function Wz(e,t){return t()}var Hz=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?Wz:Vz;RT.useSyncExternalStore=nc.useSyncExternalStore!==void 0?nc.useSyncExternalStore:Hz;kT.exports=RT;var Kz=kT.exports;/** + * @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 Lm=f,Yz=Kz;function Gz(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var Xz=typeof Object.is=="function"?Object.is:Gz,Zz=Yz.useSyncExternalStore,qz=Lm.useRef,Qz=Lm.useEffect,Jz=Lm.useMemo,eB=Lm.useDebugValue;$T.useSyncExternalStoreWithSelector=function(e,t,n,r,o){var i=qz(null);if(i.current===null){var s={hasValue:!1,value:null};i.current=s}else s=i.current;i=Jz(function(){function u(y){if(!d){if(d=!0,h=y,y=r(y),o!==void 0&&s.hasValue){var x=s.value;if(o(x,y))return m=x}return m=y}if(x=m,Xz(h,y))return x;var _=r(y);return o!==void 0&&o(x,_)?x:(h=y,m=_)}var d=!1,h,m,g=n===void 0?null:n;return[function(){return u(t())},g===null?void 0:function(){return u(g())}]},[t,n,r,o]);var l=Zz(e,i[0],i[1]);return Qz(function(){s.hasValue=!0,s.value=l},[l]),eB(l),l};CT.exports=$T;var tB=CT.exports;const nB=lm(tB);var rB={VITE_BACKEND:"http://127.0.0.1:8080",BASE_URL:"/",MODE:"production",DEV:!1,PROD:!0,SSR:!1};const RC=e=>{let t;const n=new Set,r=(u,d)=>{const h=typeof u=="function"?u(t):u;if(!Object.is(h,t)){const m=t;t=d??typeof h!="object"?h:Object.assign({},t,h),n.forEach(g=>g(t,m))}},o=()=>t,l={setState:r,getState:o,subscribe:u=>(n.add(u),()=>n.delete(u)),destroy:()=>{(rB?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),n.clear()}};return t=e(r,o,l),l},oB=e=>e?RC(e):RC,{useDebugValue:iB}=Fe,{useSyncExternalStoreWithSelector:sB}=nB;function aB(e,t=e.getState,n){const r=sB(e.subscribe,e.getState,e.getServerState||e.getState,t,n);return iB(r),r}const TC=(e,t)=>{const n=oB(e),r=(o,i=t)=>aB(n,o,i);return Object.assign(r,n),r},lB=(e,t)=>e?TC(e,t):TC,cB=1,uB=1e6;let v0=0;function dB(){return v0=(v0+1)%Number.MAX_VALUE,v0.toString()}const y0=new Map,PC=e=>{if(y0.has(e))return;const t=setTimeout(()=>{y0.delete(e),Tu({type:"REMOVE_TOAST",toastId:e})},uB);y0.set(e,t)},fB=(e,t)=>{switch(t.type){case"ADD_TOAST":return{...e,toasts:[t.toast,...e.toasts].slice(0,cB)};case"UPDATE_TOAST":return{...e,toasts:e.toasts.map(n=>n.id===t.toast.id?{...n,...t.toast}:n)};case"DISMISS_TOAST":{const{toastId:n}=t;return n?PC(n):e.toasts.forEach(r=>{PC(r.id)}),{...e,toasts:e.toasts.map(r=>r.id===n||n===void 0?{...r,open:!1}:r)}}case"REMOVE_TOAST":return t.toastId===void 0?{...e,toasts:[]}:{...e,toasts:e.toasts.filter(n=>n.id!==t.toastId)}}},Bp=[];let Up={toasts:[]};function Tu(e){Up=fB(Up,e),Bp.forEach(t=>{t(Up)})}function rl({...e}){const t=dB(),n=o=>Tu({type:"UPDATE_TOAST",toast:{...o,id:t}}),r=()=>Tu({type:"DISMISS_TOAST",toastId:t});return Tu({type:"ADD_TOAST",toast:{...e,id:t,open:!0,onOpenChange:o=>{o||r()}}}),{id:t,dismiss:r,update:n}}function Td(){const[e,t]=f.useState(Up);return f.useEffect(()=>(Bp.push(t),()=>{const n=Bp.indexOf(t);n>-1&&Bp.splice(n,1)}),[e]),{...e,toast:rl,dismiss:n=>Tu({type:"DISMISS_TOAST",toastId:n})}}const Zs={file:null,paintByExampleFile:null,customMask:null,imageHeight:0,imageWidth:0,isInpainting:!1,isPluginRunning:!1,isAdjustingMask:!1,disableShortCuts:!1,windowSize:{height:600,width:800},editorState:{baseBrushSize:sF,brushSizeScale:1,renders:[],extraMasks:[],prevExtraMasks:[],temporaryMasks:[],lineGroups:[],lastLineGroup:[],curLineGroup:[],redoRenders:[],redoCurLines:[],redoLineGroups:[]},interactiveSegState:{isInteractiveSeg:!1,tmpInteractiveSegMask:null,clicks:[]},cropperState:{x:0,y:0,width:512,height:512},extenderState:{x:0,y:0,width:512,height:512},isCropperExtenderResizing:!1,fileManagerState:{sortBy:xs.CTIME,sortOrder:$u.DESCENDING,layout:"masonry",searchText:"",inputDirectory:"",outputDirectory:""},serverConfig:{plugins:[],enableFileManager:!1,enableAutoSaving:!1,enableControlnet:!1,controlnetMethod:"lllyasviel/control_v11p_sd15_canny",disableModelSwitch:!1,isDesktop:!1,samplers:["DPM++ 2M"]},settings:{model:{name:"lama",path:"lama",model_type:"inpaint",support_controlnet:!1,support_strength:!1,support_outpainting:!1,controlnets:[],support_freeu:!1,support_lcm_lora:!1,is_single_file_diffusers:!1,need_prompt:!1},enableControlnet:!1,showCropper:!1,showExtender:!1,extenderDirection:In.xy,enableDownloadMask:!1,enableManualInpainting:!1,enableUploadMask:!1,enableAutoExtractPrompt:!0,ldmSteps:30,ldmSampler:Zw.ddim,zitsWireframe:!0,cv2Radius:5,cv2Flag:qw.INPAINT_NS,prompt:"",negativePrompt:uF,seed:42,seedFixed:!1,sdMaskBlur:35,sdStrength:1,sdSteps:50,sdGuidanceScale:7.5,sdSampler:"DPM++ 2M",sdMatchHistograms:!1,sdScale:1,p2pImageGuidanceScale:1.5,controlnetConditioningScale:.4,controlnetMethod:"lllyasviel/control_v11p_sd15_canny",enableLCMLora:!1,enableFreeu:!1,freeuConfig:{s1:.9,s2:.2,b1:1.2,b2:1.4},powerpaintTask:kl.text_guided,adjustMaskKernelSize:12}},bt=lB()(_z(Iz((e,t)=>({...Zs,showPrevMask:async()=>{if(t().settings.showExtender)return;const{lastLineGroup:n,curLineGroup:r,prevExtraMasks:o,extraMasks:i}=t().editorState;if(r.length!==0||i.length!==0)return;const{imageWidth:s,imageHeight:l}=t(),u=Lp(s,l,[n],o,Ky);try{const d=await aC(u);e(h=>{h.editorState.temporaryMasks.push(d)})}catch(d){console.error(d);return}},hidePrevMask:()=>{e(n=>{n.editorState.temporaryMasks=[]})},getCurrentTargetFile:async()=>{const n=t().file,r=t().editorState.renders;let o=n;if(r.length>0){const i=r[r.length-1];o=await ku(i.currentSrc,n.name,n.type)}return o},runInpainting:async()=>{const{isInpainting:n,file:r,paintByExampleFile:o,imageWidth:i,imageHeight:s,settings:l,cropperState:u,extenderState:d}=t();if(n||r===null||t().settings.model.support_outpainting&&l.showExtender&&d.height===s&&d.width===i)return;const{lastLineGroup:h,curLineGroup:m,lineGroups:g,renders:y,prevExtraMasks:x,extraMasks:_}=t().editorState,C=m.length===0&&_.length===0&&!l.showExtender;let S=[],b=[];if(C===!0?(b=h,S=x):(b=m,S=_),b.length===0&&S===null&&!l.showExtender){rl({variant:"destructive",description:"Please draw mask on picture"});return}const E=[...g,b];e(M=>{M.isInpainting=!0});let k=r;if(C===!0){if(y.length>1){const M=y[y.length-2];k=await ku(M.currentSrc,r.name,r.type)}}else if(y.length>0){const M=y[y.length-1];k=await ku(M.currentSrc,r.name,r.type)}const P=Lp(i,s,[b],S);if(C){const M=await aC(P);e(A=>{A.editorState.temporaryMasks=[M]})}try{const M=await Lj(k,l,u,d,sC(P.toDataURL()),o),{blob:A,seed:O}=M;O&&t().setSeed(parseInt(O,10));const F=new Image;await Ip(F,A);const V=[...y,F];t().setImageSize(F.width,F.height),t().updateEditorState({renders:V,lineGroups:E,lastLineGroup:b,curLineGroup:[],extraMasks:[],prevExtraMasks:S})}catch(M){rl({variant:"destructive",description:M.message?M.message:M.toString()})}t().resetRedoState(),e(M=>{M.isInpainting=!1,M.editorState.temporaryMasks=[]})},runRenderablePlugin:async(n,r,o={upscale:1})=>{const{renders:i,lineGroups:s}=t().editorState;e(l=>{l.isPluginRunning=!0});try{const l=new Date,u=await t().getCurrentTargetFile(),d=await gT(n,r,u,o.upscale),{blob:h}=d;if(n){const y=new Image;await Ip(y,h),e(x=>{x.editorState.extraMasks.push(y)})}else{const y=new Image;await Ip(y,h),t().setImageSize(y.width,y.height);const x=[...i,y],_=[...s,[]];t().updateEditorState({renders:x,lineGroups:_})}const g=new Date().getTime()-l.getTime();rl({description:`Run ${r} successfully in ${g/1e3}s`})}catch(l){rl({variant:"destructive",description:l.message?l.message:l.toString()})}e(l=>{l.isPluginRunning=!1})},updateEditorState:n=>{e(r=>{r.editorState={...r.editorState,...n}})},cleanCurLineGroup:()=>{t().updateEditorState({curLineGroup:[]})},handleCanvasMouseDown:n=>{let r=[];const o=t();o.runMannually()&&(r=[...o.editorState.curLineGroup]),r.push({size:o.getBrushSize(),pts:[n]}),e(i=>{i.editorState.curLineGroup=r})},handleCanvasMouseMove:n=>{e(r=>{const o=r.editorState.curLineGroup;o.length&&o[o.length-1].pts.push(n)})},runMannually:()=>{const n=t();return n.settings.enableManualInpainting||n.settings.model.model_type!==is},getIsProcessing:()=>t().isInpainting||t().isPluginRunning||t().isAdjustingMask,isSD:()=>t().settings.model.model_type!==is,undoDisabled:()=>{const n=t().editorState;if(n.renders.length>0)return!1;if(t().runMannually()){if(n.curLineGroup.length===0)return!0}else if(n.renders.length===0)return!0;return!1},undo:()=>{t().runMannually()&&t().editorState.curLineGroup.length!==0?e(n=>{const r=n.editorState;if(r.curLineGroup.length===0)return;r.lastLineGroup=[];const o=r.curLineGroup.pop();r.redoCurLines.push(o)}):e(n=>{const r=n.editorState;if(r.renders.length===0||r.lineGroups.length===0)return;const o=r.lineGroups.pop();r.redoLineGroups.push(o),r.redoCurLines=[],r.curLineGroup=[];const i=r.renders.pop();r.redoRenders.push(i)})},redoDisabled:()=>{const n=t().editorState;if(n.redoRenders.length>0)return!1;if(t().runMannually()){if(n.redoCurLines.length===0)return!0}else if(n.redoRenders.length===0)return!0;return!1},redo:()=>{t().runMannually()&&t().editorState.redoCurLines.length!==0?e(n=>{const r=n.editorState;if(r.redoCurLines.length===0)return;const o=r.redoCurLines.pop();r.curLineGroup.push(o)}):e(n=>{const r=n.editorState;if(r.redoRenders.length===0||r.redoLineGroups.length===0)return;const o=r.redoLineGroups.pop();r.lineGroups.push(o),r.curLineGroup=[];const i=r.redoRenders.pop();r.renders.push(i)})},resetRedoState:()=>{e(n=>{n.editorState.redoCurLines=[],n.editorState.redoLineGroups=[],n.editorState.redoRenders=[]})},updateAppState:n=>{e(()=>n)},getBrushSize:()=>t().editorState.baseBrushSize*t().editorState.brushSizeScale,showPromptInput:()=>{const n=t().settings.model;return n.model_type!==is&&n.name!==YR},setServerConfig:n=>{e(r=>{r.serverConfig=n,r.settings.enableControlnet=n.enableControlnet,r.settings.controlnetMethod=n.controlnetMethod})},updateSettings:n=>{e(r=>{r.settings={...r.settings,...n}})},setModel:n=>{e(r=>{r.settings.model=n,n.support_controlnet&&!n.controlnets.includes(r.settings.controlnetMethod)&&(r.settings.controlnetMethod=n.controlnets[0])})},updateFileManagerState:n=>{e(r=>{r.fileManagerState={...r.fileManagerState,...n}})},updateInteractiveSegState:n=>{e(r=>({...r,interactiveSegState:{...r.interactiveSegState,...n}}))},resetInteractiveSegState:()=>{t().updateInteractiveSegState(Zs.interactiveSegState)},handleInteractiveSegAccept:()=>{e(n=>{n.interactiveSegState.tmpInteractiveSegMask&&n.editorState.extraMasks.push(n.interactiveSegState.tmpInteractiveSegMask),n.interactiveSegState={...Zs.interactiveSegState}})},setIsInpainting:n=>e(r=>{r.isInpainting=n}),setFile:async n=>{if(t().settings.enableAutoExtractPrompt)try{const r=await Hj(n);r.prompt&&e(o=>{o.settings.prompt=r.prompt}),r.negative_prompt&&e(o=>{o.settings.negativePrompt=r.negative_prompt})}catch(r){rl({variant:"destructive",description:r.message?r.message:r.toString()})}e(r=>{r.file=n,r.interactiveSegState=Zs.interactiveSegState,r.editorState=Zs.editorState,r.cropperState=Zs.cropperState})},setCustomFile:n=>e(r=>{r.customMask=n}),setBaseBrushSize:n=>e(r=>{r.editorState.baseBrushSize=n}),setImageSize:(n,r)=>{e(o=>{o.imageWidth=n,o.imageHeight=r,o.editorState.brushSizeScale=Math.max(Math.min(n,r),512)/512}),t().resetExtender(n,r)},setCropperX:n=>e(r=>{r.cropperState.x=n}),setCropperY:n=>e(r=>{r.cropperState.y=n}),setCropperWidth:n=>e(r=>{r.cropperState.width=n}),setCropperHeight:n=>e(r=>{r.cropperState.height=n}),setExtenderX:n=>e(r=>{r.extenderState.x=n}),setExtenderY:n=>e(r=>{r.extenderState.y=n}),setExtenderWidth:n=>e(r=>{r.extenderState.width=n}),setExtenderHeight:n=>e(r=>{r.extenderState.height=n}),setIsCropperExtenderResizing:n=>e(r=>{r.isCropperExtenderResizing=n}),updateExtenderDirection:n=>{console.log(`updateExtenderDirection: ${JSON.stringify(t().extenderState)}`),e(r=>{r.settings.extenderDirection=n,r.extenderState.x=0,r.extenderState.y=0,r.extenderState.width=r.imageWidth,r.extenderState.height=r.imageHeight}),t().updateExtenderByBuiltIn(n,1.5)},updateExtenderByBuiltIn:(n,r)=>{const o={...Zs.extenderState};let{x:i,y:s,width:l,height:u}=o;const{imageWidth:d,imageHeight:h}=t();switch(l=d,u=h,n){case In.x:i=-Math.ceil(d*(r-1)/2),l=Math.ceil(d*r);break;case In.y:s=-Math.ceil(h*(r-1)/2),u=Math.ceil(h*r);break;case In.xy:i=-Math.ceil(d*(r-1)/2),s=-Math.ceil(h*(r-1)/2),l=Math.ceil(d*r),u=Math.ceil(h*r);break}e(m=>{m.extenderState.x=i,m.extenderState.y=s,m.extenderState.width=l,m.extenderState.height=u})},resetExtender:(n,r)=>{e(o=>{o.extenderState.x=0,o.extenderState.y=0,o.extenderState.width=n,o.extenderState.height=r})},setSeed:n=>e(r=>{r.settings.seed=n}),adjustMask:async n=>{const{imageWidth:r,imageHeight:o}=t(),{curLineGroup:i,extraMasks:s}=t().editorState,{adjustMaskKernelSize:l}=t().settings;if(i.length===0&&s.length===0)return;e(g=>{g.isAdjustingMask=!0});const u=Lp(r,o,[i],s,Ky),d=sC(u.toDataURL()),h=await Kj(d,n,l),m=await fF(h);e(g=>{g.editorState.extraMasks=[m],g.editorState.curLineGroup=[]}),e(g=>{g.isAdjustingMask=!1})},clearMask:()=>{e(n=>{n.editorState.extraMasks=[],n.editorState.curLineGroup=[]})}})),{name:"ZUSTAND_STATE",version:1,partialize:e=>Object.fromEntries(Object.entries(e).filter(([t])=>["fileManagerState","settings"].includes(t)))}),Sz),Pd=f.forwardRef(({className:e,type:t,...n},r)=>{const o=bt(l=>l.updateAppState),i=()=>{o({disableShortCuts:!0})},s=()=>{o({disableShortCuts:!1})};return v.jsx("input",{type:t,className:Ce("flex h-8 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",e),ref:r,autoComplete:"off",tabIndex:-1,onFocus:i,onBlur:s,...n})});Pd.displayName="Input";const Gn=f.forwardRef(({numberValue:e,allowFloat:t,onNumberValueChange:n,...r},o)=>{const[i,s]=f.useState(e.toString());f.useEffect(()=>{i!==e.toString()+"."&&s(e.toString())},[e]);const l=u=>{let h=u.target.value;if(t){if(h=h.replace(/[^0-9.]/g,"").replace(/(\..*?)\..*/g,"$1"),h.length===0){n(0);return}n(parseFloat(h))}else{if(h=h.replace(/\D/g,""),h.length===0){n(0);return}n(parseInt(h,10))}s(h)};return v.jsx(Pd,{ref:o,value:i,onInput:l,...r})});function ue(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 pB(e,t){const n=f.createContext(t);function r(i){const{children:s,...l}=i,u=f.useMemo(()=>l,Object.values(l));return f.createElement(n.Provider,{value:u},s)}function o(i){const s=f.useContext(n);if(s)return s;if(t!==void 0)return t;throw new Error(`\`${i}\` must be used within \`${e}\``)}return r.displayName=e+"Provider",[r,o]}function An(e,t=[]){let n=[];function r(i,s){const l=f.createContext(s),u=n.length;n=[...n,s];function d(m){const{scope:g,children:y,...x}=m,_=(g==null?void 0:g[e][u])||l,C=f.useMemo(()=>x,Object.values(x));return f.createElement(_.Provider,{value:C},y)}function h(m,g){const y=(g==null?void 0:g[e][u])||l,x=f.useContext(y);if(x)return x;if(s!==void 0)return s;throw new Error(`\`${m}\` must be used within \`${i}\``)}return d.displayName=i+"Provider",[d,h]}const o=()=>{const i=n.map(s=>f.createContext(s));return function(l){const u=(l==null?void 0:l[e])||i;return f.useMemo(()=>({[`__scope${e}`]:{...l,[e]:u}}),[l,u])}};return o.scopeName=e,[r,hB(o,...t)]}function hB(...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(i){const s=r.reduce((l,{useScope:u,scopeName:d})=>{const m=u(i)[`__scope${d}`];return{...l,...m}},{});return f.useMemo(()=>({[`__scope${t.scopeName}`]:s}),[s])}};return n.scopeName=t.scopeName,n}const mB=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","span","svg","ul"],Pe=mB.reduce((e,t)=>{const n=f.forwardRef((r,o)=>{const{asChild:i,...s}=r,l=i?Wo:t;return f.useEffect(()=>{window[Symbol.for("radix-ui")]=!0},[]),f.createElement(l,Y({},s,{ref:o}))});return n.displayName=`Primitive.${t}`,{...e,[t]:n}},{});function cx(e,t){e&&Os.flushSync(()=>e.dispatchEvent(t))}function Ft(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)},[])}function gB(e,t=globalThis==null?void 0:globalThis.document){const n=Ft(e);f.useEffect(()=>{const r=o=>{o.key==="Escape"&&n(o)};return t.addEventListener("keydown",r),()=>t.removeEventListener("keydown",r)},[n,t])}const i1="dismissableLayer.update",vB="dismissableLayer.pointerDownOutside",yB="dismissableLayer.focusOutside";let AC;const TT=f.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),yc=f.forwardRef((e,t)=>{var n;const{disableOutsidePointerEvents:r=!1,onEscapeKeyDown:o,onPointerDownOutside:i,onFocusOutside:s,onInteractOutside:l,onDismiss:u,...d}=e,h=f.useContext(TT),[m,g]=f.useState(null),y=(n=m==null?void 0:m.ownerDocument)!==null&&n!==void 0?n:globalThis==null?void 0:globalThis.document,[,x]=f.useState({}),_=Be(t,O=>g(O)),C=Array.from(h.layers),[S]=[...h.layersWithOutsidePointerEventsDisabled].slice(-1),b=C.indexOf(S),E=m?C.indexOf(m):-1,k=h.layersWithOutsidePointerEventsDisabled.size>0,P=E>=b,M=xB(O=>{const F=O.target,V=[...h.branches].some(J=>J.contains(F));!P||V||(i==null||i(O),l==null||l(O),O.defaultPrevented||u==null||u())},y),A=bB(O=>{const F=O.target;[...h.branches].some(J=>J.contains(F))||(s==null||s(O),l==null||l(O),O.defaultPrevented||u==null||u())},y);return gB(O=>{E===h.layers.size-1&&(o==null||o(O),!O.defaultPrevented&&u&&(O.preventDefault(),u()))},y),f.useEffect(()=>{if(m)return r&&(h.layersWithOutsidePointerEventsDisabled.size===0&&(AC=y.body.style.pointerEvents,y.body.style.pointerEvents="none"),h.layersWithOutsidePointerEventsDisabled.add(m)),h.layers.add(m),OC(),()=>{r&&h.layersWithOutsidePointerEventsDisabled.size===1&&(y.body.style.pointerEvents=AC)}},[m,y,r,h]),f.useEffect(()=>()=>{m&&(h.layers.delete(m),h.layersWithOutsidePointerEventsDisabled.delete(m),OC())},[m,h]),f.useEffect(()=>{const O=()=>x({});return document.addEventListener(i1,O),()=>document.removeEventListener(i1,O)},[]),f.createElement(Pe.div,Y({},d,{ref:_,style:{pointerEvents:k?P?"auto":"none":void 0,...e.style},onFocusCapture:ue(e.onFocusCapture,A.onFocusCapture),onBlurCapture:ue(e.onBlurCapture,A.onBlurCapture),onPointerDownCapture:ue(e.onPointerDownCapture,M.onPointerDownCapture)}))}),wB=f.forwardRef((e,t)=>{const n=f.useContext(TT),r=f.useRef(null),o=Be(t,r);return f.useEffect(()=>{const i=r.current;if(i)return n.branches.add(i),()=>{n.branches.delete(i)}},[n.branches]),f.createElement(Pe.div,Y({},e,{ref:o}))});function xB(e,t=globalThis==null?void 0:globalThis.document){const n=Ft(e),r=f.useRef(!1),o=f.useRef(()=>{});return f.useEffect(()=>{const i=l=>{if(l.target&&!r.current){let h=function(){PT(vB,n,d,{discrete:!0})};var u=h;const d={originalEvent:l};l.pointerType==="touch"?(t.removeEventListener("click",o.current),o.current=h,t.addEventListener("click",o.current,{once:!0})):h()}else t.removeEventListener("click",o.current);r.current=!1},s=window.setTimeout(()=>{t.addEventListener("pointerdown",i)},0);return()=>{window.clearTimeout(s),t.removeEventListener("pointerdown",i),t.removeEventListener("click",o.current)}},[t,n]),{onPointerDownCapture:()=>r.current=!0}}function bB(e,t=globalThis==null?void 0:globalThis.document){const n=Ft(e),r=f.useRef(!1);return f.useEffect(()=>{const o=i=>{i.target&&!r.current&&PT(yB,n,{originalEvent:i},{discrete:!1})};return t.addEventListener("focusin",o),()=>t.removeEventListener("focusin",o)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function OC(){const e=new CustomEvent(i1);document.dispatchEvent(e)}function PT(e,t,n,{discrete:r}){const o=n.originalEvent.target,i=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&o.addEventListener(e,t,{once:!0}),r?cx(o,i):o.dispatchEvent(i)}const _B=yc,SB=wB,Pn=globalThis!=null&&globalThis.document?f.useLayoutEffect:()=>{},EB=jD.useId||(()=>{});let CB=0;function nr(e){const[t,n]=f.useState(EB());return Pn(()=>{e||n(r=>r??String(CB++))},[e]),e||(t?`radix-${t}`:"")}const $B=["top","right","bottom","left"],Cs=Math.min,pr=Math.max,Mh=Math.round,ip=Math.floor,$s=e=>({x:e,y:e}),kB={left:"right",right:"left",bottom:"top",top:"bottom"},RB={start:"end",end:"start"};function s1(e,t,n){return pr(e,Cs(t,n))}function yi(e,t){return typeof e=="function"?e(t):e}function wi(e){return e.split("-")[0]}function wc(e){return e.split("-")[1]}function ux(e){return e==="x"?"y":"x"}function dx(e){return e==="y"?"height":"width"}function xc(e){return["top","bottom"].includes(wi(e))?"y":"x"}function fx(e){return ux(xc(e))}function TB(e,t,n){n===void 0&&(n=!1);const r=wc(e),o=fx(e),i=dx(o);let s=o==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[i]>t.floating[i]&&(s=Nh(s)),[s,Nh(s)]}function PB(e){const t=Nh(e);return[a1(e),t,a1(t)]}function a1(e){return e.replace(/start|end/g,t=>RB[t])}function AB(e,t,n){const r=["left","right"],o=["right","left"],i=["top","bottom"],s=["bottom","top"];switch(e){case"top":case"bottom":return n?t?o:r:t?r:o;case"left":case"right":return t?i:s;default:return[]}}function OB(e,t,n,r){const o=wc(e);let i=AB(wi(e),n==="start",r);return o&&(i=i.map(s=>s+"-"+o),t&&(i=i.concat(i.map(a1)))),i}function Nh(e){return e.replace(/left|right|bottom|top/g,t=>kB[t])}function MB(e){return{top:0,right:0,bottom:0,left:0,...e}}function AT(e){return typeof e!="number"?MB(e):{top:e,right:e,bottom:e,left:e}}function Dh(e){return{...e,top:e.y,left:e.x,right:e.x+e.width,bottom:e.y+e.height}}function MC(e,t,n){let{reference:r,floating:o}=e;const i=xc(t),s=fx(t),l=dx(s),u=wi(t),d=i==="y",h=r.x+r.width/2-o.width/2,m=r.y+r.height/2-o.height/2,g=r[l]/2-o[l]/2;let y;switch(u){case"top":y={x:h,y:r.y-o.height};break;case"bottom":y={x:h,y:r.y+r.height};break;case"right":y={x:r.x+r.width,y:m};break;case"left":y={x:r.x-o.width,y:m};break;default:y={x:r.x,y:r.y}}switch(wc(t)){case"start":y[s]-=g*(n&&d?-1:1);break;case"end":y[s]+=g*(n&&d?-1:1);break}return y}const NB=async(e,t,n)=>{const{placement:r="bottom",strategy:o="absolute",middleware:i=[],platform:s}=n,l=i.filter(Boolean),u=await(s.isRTL==null?void 0:s.isRTL(t));let d=await s.getElementRects({reference:e,floating:t,strategy:o}),{x:h,y:m}=MC(d,r,u),g=r,y={},x=0;for(let _=0;_({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:o,rects:i,platform:s,elements:l,middlewareData:u}=t,{element:d,padding:h=0}=yi(e,t)||{};if(d==null)return{};const m=AT(h),g={x:n,y:r},y=fx(o),x=dx(y),_=await s.getDimensions(d),C=y==="y",S=C?"top":"left",b=C?"bottom":"right",E=C?"clientHeight":"clientWidth",k=i.reference[x]+i.reference[y]-g[y]-i.floating[x],P=g[y]-i.reference[y],M=await(s.getOffsetParent==null?void 0:s.getOffsetParent(d));let A=M?M[E]:0;(!A||!await(s.isElement==null?void 0:s.isElement(M)))&&(A=l.floating[E]||i.floating[x]);const O=k/2-P/2,F=A/2-_[x]/2-1,V=Cs(m[S],F),J=Cs(m[b],F),G=V,ae=A-_[x]-J,U=A/2-_[x]/2+O,te=s1(G,U,ae),L=!u.arrow&&wc(o)!=null&&U!=te&&i.reference[x]/2-(UG<=0)){var F,V;const G=(((F=i.flip)==null?void 0:F.index)||0)+1,ae=P[G];if(ae)return{data:{index:G,overflows:O},reset:{placement:ae}};let U=(V=O.filter(te=>te.overflows[0]<=0).sort((te,L)=>te.overflows[1]-L.overflows[1])[0])==null?void 0:V.placement;if(!U)switch(y){case"bestFit":{var J;const te=(J=O.map(L=>[L.placement,L.overflows.filter(ie=>ie>0).reduce((ie,K)=>ie+K,0)]).sort((L,ie)=>L[1]-ie[1])[0])==null?void 0:J[0];te&&(U=te);break}case"initialPlacement":U=l;break}if(o!==U)return{reset:{placement:U}}}return{}}}};function DC(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function IC(e){return $B.some(t=>e[t]>=0)}const IB=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n}=t,{strategy:r="referenceHidden",...o}=yi(e,t);switch(r){case"referenceHidden":{const i=await td(t,{...o,elementContext:"reference"}),s=DC(i,n.reference);return{data:{referenceHiddenOffsets:s,referenceHidden:IC(s)}}}case"escaped":{const i=await td(t,{...o,altBoundary:!0}),s=DC(i,n.floating);return{data:{escapedOffsets:s,escaped:IC(s)}}}default:return{}}}}};async function LB(e,t){const{placement:n,platform:r,elements:o}=e,i=await(r.isRTL==null?void 0:r.isRTL(o.floating)),s=wi(n),l=wc(n),u=xc(n)==="y",d=["left","top"].includes(s)?-1:1,h=i&&u?-1:1,m=yi(t,e);let{mainAxis:g,crossAxis:y,alignmentAxis:x}=typeof m=="number"?{mainAxis:m,crossAxis:0,alignmentAxis:null}:{mainAxis:0,crossAxis:0,alignmentAxis:null,...m};return l&&typeof x=="number"&&(y=l==="end"?x*-1:x),u?{x:y*h,y:g*d}:{x:g*d,y:y*h}}const FB=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){const{x:n,y:r}=t,o=await LB(t,e);return{x:n+o.x,y:r+o.y,data:o}}}},jB=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:o}=t,{mainAxis:i=!0,crossAxis:s=!1,limiter:l={fn:C=>{let{x:S,y:b}=C;return{x:S,y:b}}},...u}=yi(e,t),d={x:n,y:r},h=await td(t,u),m=xc(wi(o)),g=ux(m);let y=d[g],x=d[m];if(i){const C=g==="y"?"top":"left",S=g==="y"?"bottom":"right",b=y+h[C],E=y-h[S];y=s1(b,y,E)}if(s){const C=m==="y"?"top":"left",S=m==="y"?"bottom":"right",b=x+h[C],E=x-h[S];x=s1(b,x,E)}const _=l.fn({...t,[g]:y,[m]:x});return{..._,data:{x:_.x-n,y:_.y-r}}}}},zB=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:r,placement:o,rects:i,middlewareData:s}=t,{offset:l=0,mainAxis:u=!0,crossAxis:d=!0}=yi(e,t),h={x:n,y:r},m=xc(o),g=ux(m);let y=h[g],x=h[m];const _=yi(l,t),C=typeof _=="number"?{mainAxis:_,crossAxis:0}:{mainAxis:0,crossAxis:0,..._};if(u){const E=g==="y"?"height":"width",k=i.reference[g]-i.floating[E]+C.mainAxis,P=i.reference[g]+i.reference[E]-C.mainAxis;yP&&(y=P)}if(d){var S,b;const E=g==="y"?"width":"height",k=["top","left"].includes(wi(o)),P=i.reference[m]-i.floating[E]+(k&&((S=s.offset)==null?void 0:S[m])||0)+(k?0:C.crossAxis),M=i.reference[m]+i.reference[E]+(k?0:((b=s.offset)==null?void 0:b[m])||0)-(k?C.crossAxis:0);xM&&(x=M)}return{[g]:y,[m]:x}}}},BB=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){const{placement:n,rects:r,platform:o,elements:i}=t,{apply:s=()=>{},...l}=yi(e,t),u=await td(t,l),d=wi(n),h=wc(n),m=xc(n)==="y",{width:g,height:y}=r.floating;let x,_;d==="top"||d==="bottom"?(x=d,_=h===(await(o.isRTL==null?void 0:o.isRTL(i.floating))?"start":"end")?"left":"right"):(_=d,x=h==="end"?"top":"bottom");const C=y-u[x],S=g-u[_],b=!t.middlewareData.shift;let E=C,k=S;if(m){const M=g-u.left-u.right;k=h||b?Cs(S,M):M}else{const M=y-u.top-u.bottom;E=h||b?Cs(C,M):M}if(b&&!h){const M=pr(u.left,0),A=pr(u.right,0),O=pr(u.top,0),F=pr(u.bottom,0);m?k=g-2*(M!==0||A!==0?M+A:pr(u.left,u.right)):E=y-2*(O!==0||F!==0?O+F:pr(u.top,u.bottom))}await s({...t,availableWidth:k,availableHeight:E});const P=await o.getDimensions(i.floating);return g!==P.width||y!==P.height?{reset:{rects:!0}}:{}}}};function ks(e){return OT(e)?(e.nodeName||"").toLowerCase():"#document"}function vr(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Ci(e){var t;return(t=(OT(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function OT(e){return e instanceof Node||e instanceof vr(e).Node}function xi(e){return e instanceof Element||e instanceof vr(e).Element}function Ho(e){return e instanceof HTMLElement||e instanceof vr(e).HTMLElement}function LC(e){return typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof vr(e).ShadowRoot}function Ad(e){const{overflow:t,overflowX:n,overflowY:r,display:o}=Xr(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&!["inline","contents"].includes(o)}function UB(e){return["table","td","th"].includes(ks(e))}function px(e){const t=hx(),n=Xr(e);return n.transform!=="none"||n.perspective!=="none"||(n.containerType?n.containerType!=="normal":!1)||!t&&(n.backdropFilter?n.backdropFilter!=="none":!1)||!t&&(n.filter?n.filter!=="none":!1)||["transform","perspective","filter"].some(r=>(n.willChange||"").includes(r))||["paint","layout","strict","content"].some(r=>(n.contain||"").includes(r))}function VB(e){let t=rc(e);for(;Ho(t)&&!Fm(t);){if(px(t))return t;t=rc(t)}return null}function hx(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}function Fm(e){return["html","body","#document"].includes(ks(e))}function Xr(e){return vr(e).getComputedStyle(e)}function jm(e){return xi(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.pageXOffset,scrollTop:e.pageYOffset}}function rc(e){if(ks(e)==="html")return e;const t=e.assignedSlot||e.parentNode||LC(e)&&e.host||Ci(e);return LC(t)?t.host:t}function MT(e){const t=rc(e);return Fm(t)?e.ownerDocument?e.ownerDocument.body:e.body:Ho(t)&&Ad(t)?t:MT(t)}function nd(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const o=MT(e),i=o===((r=e.ownerDocument)==null?void 0:r.body),s=vr(o);return i?t.concat(s,s.visualViewport||[],Ad(o)?o:[],s.frameElement&&n?nd(s.frameElement):[]):t.concat(o,nd(o,[],n))}function NT(e){const t=Xr(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const o=Ho(e),i=o?e.offsetWidth:n,s=o?e.offsetHeight:r,l=Mh(n)!==i||Mh(r)!==s;return l&&(n=i,r=s),{width:n,height:r,$:l}}function mx(e){return xi(e)?e:e.contextElement}function Rl(e){const t=mx(e);if(!Ho(t))return $s(1);const n=t.getBoundingClientRect(),{width:r,height:o,$:i}=NT(t);let s=(i?Mh(n.width):n.width)/r,l=(i?Mh(n.height):n.height)/o;return(!s||!Number.isFinite(s))&&(s=1),(!l||!Number.isFinite(l))&&(l=1),{x:s,y:l}}const WB=$s(0);function DT(e){const t=vr(e);return!hx()||!t.visualViewport?WB:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function HB(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==vr(e)?!1:t}function Ra(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const o=e.getBoundingClientRect(),i=mx(e);let s=$s(1);t&&(r?xi(r)&&(s=Rl(r)):s=Rl(e));const l=HB(i,n,r)?DT(i):$s(0);let u=(o.left+l.x)/s.x,d=(o.top+l.y)/s.y,h=o.width/s.x,m=o.height/s.y;if(i){const g=vr(i),y=r&&xi(r)?vr(r):r;let x=g.frameElement;for(;x&&r&&y!==g;){const _=Rl(x),C=x.getBoundingClientRect(),S=Xr(x),b=C.left+(x.clientLeft+parseFloat(S.paddingLeft))*_.x,E=C.top+(x.clientTop+parseFloat(S.paddingTop))*_.y;u*=_.x,d*=_.y,h*=_.x,m*=_.y,u+=b,d+=E,x=vr(x).frameElement}}return Dh({width:h,height:m,x:u,y:d})}function KB(e){let{rect:t,offsetParent:n,strategy:r}=e;const o=Ho(n),i=Ci(n);if(n===i)return t;let s={scrollLeft:0,scrollTop:0},l=$s(1);const u=$s(0);if((o||!o&&r!=="fixed")&&((ks(n)!=="body"||Ad(i))&&(s=jm(n)),Ho(n))){const d=Ra(n);l=Rl(n),u.x=d.x+n.clientLeft,u.y=d.y+n.clientTop}return{width:t.width*l.x,height:t.height*l.y,x:t.x*l.x-s.scrollLeft*l.x+u.x,y:t.y*l.y-s.scrollTop*l.y+u.y}}function YB(e){return Array.from(e.getClientRects())}function IT(e){return Ra(Ci(e)).left+jm(e).scrollLeft}function GB(e){const t=Ci(e),n=jm(e),r=e.ownerDocument.body,o=pr(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),i=pr(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let s=-n.scrollLeft+IT(e);const l=-n.scrollTop;return Xr(r).direction==="rtl"&&(s+=pr(t.clientWidth,r.clientWidth)-o),{width:o,height:i,x:s,y:l}}function XB(e,t){const n=vr(e),r=Ci(e),o=n.visualViewport;let i=r.clientWidth,s=r.clientHeight,l=0,u=0;if(o){i=o.width,s=o.height;const d=hx();(!d||d&&t==="fixed")&&(l=o.offsetLeft,u=o.offsetTop)}return{width:i,height:s,x:l,y:u}}function ZB(e,t){const n=Ra(e,!0,t==="fixed"),r=n.top+e.clientTop,o=n.left+e.clientLeft,i=Ho(e)?Rl(e):$s(1),s=e.clientWidth*i.x,l=e.clientHeight*i.y,u=o*i.x,d=r*i.y;return{width:s,height:l,x:u,y:d}}function FC(e,t,n){let r;if(t==="viewport")r=XB(e,n);else if(t==="document")r=GB(Ci(e));else if(xi(t))r=ZB(t,n);else{const o=DT(e);r={...t,x:t.x-o.x,y:t.y-o.y}}return Dh(r)}function LT(e,t){const n=rc(e);return n===t||!xi(n)||Fm(n)?!1:Xr(n).position==="fixed"||LT(n,t)}function qB(e,t){const n=t.get(e);if(n)return n;let r=nd(e,[],!1).filter(l=>xi(l)&&ks(l)!=="body"),o=null;const i=Xr(e).position==="fixed";let s=i?rc(e):e;for(;xi(s)&&!Fm(s);){const l=Xr(s),u=px(s);!u&&l.position==="fixed"&&(o=null),(i?!u&&!o:!u&&l.position==="static"&&!!o&&["absolute","fixed"].includes(o.position)||Ad(s)&&!u&<(e,s))?r=r.filter(h=>h!==s):o=l,s=rc(s)}return t.set(e,r),r}function QB(e){let{element:t,boundary:n,rootBoundary:r,strategy:o}=e;const s=[...n==="clippingAncestors"?qB(t,this._c):[].concat(n),r],l=s[0],u=s.reduce((d,h)=>{const m=FC(t,h,o);return d.top=pr(m.top,d.top),d.right=Cs(m.right,d.right),d.bottom=Cs(m.bottom,d.bottom),d.left=pr(m.left,d.left),d},FC(t,l,o));return{width:u.right-u.left,height:u.bottom-u.top,x:u.left,y:u.top}}function JB(e){return NT(e)}function eU(e,t,n){const r=Ho(t),o=Ci(t),i=n==="fixed",s=Ra(e,!0,i,t);let l={scrollLeft:0,scrollTop:0};const u=$s(0);if(r||!r&&!i)if((ks(t)!=="body"||Ad(o))&&(l=jm(t)),r){const d=Ra(t,!0,i,t);u.x=d.x+t.clientLeft,u.y=d.y+t.clientTop}else o&&(u.x=IT(o));return{x:s.left+l.scrollLeft-u.x,y:s.top+l.scrollTop-u.y,width:s.width,height:s.height}}function jC(e,t){return!Ho(e)||Xr(e).position==="fixed"?null:t?t(e):e.offsetParent}function FT(e,t){const n=vr(e);if(!Ho(e))return n;let r=jC(e,t);for(;r&&UB(r)&&Xr(r).position==="static";)r=jC(r,t);return r&&(ks(r)==="html"||ks(r)==="body"&&Xr(r).position==="static"&&!px(r))?n:r||VB(e)||n}const tU=async function(e){let{reference:t,floating:n,strategy:r}=e;const o=this.getOffsetParent||FT,i=this.getDimensions;return{reference:eU(t,await o(n),r),floating:{x:0,y:0,...await i(n)}}};function nU(e){return Xr(e).direction==="rtl"}const rU={convertOffsetParentRelativeRectToViewportRelativeRect:KB,getDocumentElement:Ci,getClippingRect:QB,getOffsetParent:FT,getElementRects:tU,getClientRects:YB,getDimensions:JB,getScale:Rl,isElement:xi,isRTL:nU};function oU(e,t){let n=null,r;const o=Ci(e);function i(){clearTimeout(r),n&&n.disconnect(),n=null}function s(l,u){l===void 0&&(l=!1),u===void 0&&(u=1),i();const{left:d,top:h,width:m,height:g}=e.getBoundingClientRect();if(l||t(),!m||!g)return;const y=ip(h),x=ip(o.clientWidth-(d+m)),_=ip(o.clientHeight-(h+g)),C=ip(d),b={rootMargin:-y+"px "+-x+"px "+-_+"px "+-C+"px",threshold:pr(0,Cs(1,u))||1};let E=!0;function k(P){const M=P[0].intersectionRatio;if(M!==u){if(!E)return s();M?s(!1,M):r=setTimeout(()=>{s(!1,1e-7)},100)}E=!1}try{n=new IntersectionObserver(k,{...b,root:o.ownerDocument})}catch{n=new IntersectionObserver(k,b)}n.observe(e)}return s(!0),i}function iU(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:o=!0,ancestorResize:i=!0,elementResize:s=typeof ResizeObserver=="function",layoutShift:l=typeof IntersectionObserver=="function",animationFrame:u=!1}=r,d=mx(e),h=o||i?[...d?nd(d):[],...nd(t)]:[];h.forEach(S=>{o&&S.addEventListener("scroll",n,{passive:!0}),i&&S.addEventListener("resize",n)});const m=d&&l?oU(d,n):null;let g=-1,y=null;s&&(y=new ResizeObserver(S=>{let[b]=S;b&&b.target===d&&y&&(y.unobserve(t),cancelAnimationFrame(g),g=requestAnimationFrame(()=>{y&&y.observe(t)})),n()}),d&&!u&&y.observe(d),y.observe(t));let x,_=u?Ra(e):null;u&&C();function C(){const S=Ra(e);_&&(S.x!==_.x||S.y!==_.y||S.width!==_.width||S.height!==_.height)&&n(),_=S,x=requestAnimationFrame(C)}return n(),()=>{h.forEach(S=>{o&&S.removeEventListener("scroll",n),i&&S.removeEventListener("resize",n)}),m&&m(),y&&y.disconnect(),y=null,u&&cancelAnimationFrame(x)}}const sU=(e,t,n)=>{const r=new Map,o={platform:rU,...n},i={...o.platform,_c:r};return NB(e,t,{...o,platform:i})},aU=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:o}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?NC({element:r.current,padding:o}).fn(n):{}:r?NC({element:r,padding:o}).fn(n):{}}}};var Vp=typeof document<"u"?f.useLayoutEffect:f.useEffect;function Ih(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(!Ih(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(!{}.hasOwnProperty.call(t,o[r]))return!1;for(r=n;r--!==0;){const i=o[r];if(!(i==="_owner"&&e.$$typeof)&&!Ih(e[i],t[i]))return!1}return!0}return e!==e&&t!==t}function jT(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function zC(e,t){const n=jT(e);return Math.round(t*n)/n}function BC(e){const t=f.useRef(e);return Vp(()=>{t.current=e}),t}function lU(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:o,elements:{reference:i,floating:s}={},transform:l=!0,whileElementsMounted:u,open:d}=e,[h,m]=f.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[g,y]=f.useState(r);Ih(g,r)||y(r);const[x,_]=f.useState(null),[C,S]=f.useState(null),b=f.useCallback(L=>{L!=M.current&&(M.current=L,_(L))},[_]),E=f.useCallback(L=>{L!==A.current&&(A.current=L,S(L))},[S]),k=i||x,P=s||C,M=f.useRef(null),A=f.useRef(null),O=f.useRef(h),F=BC(u),V=BC(o),J=f.useCallback(()=>{if(!M.current||!A.current)return;const L={placement:t,strategy:n,middleware:g};V.current&&(L.platform=V.current),sU(M.current,A.current,L).then(ie=>{const K={...ie,isPositioned:!0};G.current&&!Ih(O.current,K)&&(O.current=K,Os.flushSync(()=>{m(K)}))})},[g,t,n,V]);Vp(()=>{d===!1&&O.current.isPositioned&&(O.current.isPositioned=!1,m(L=>({...L,isPositioned:!1})))},[d]);const G=f.useRef(!1);Vp(()=>(G.current=!0,()=>{G.current=!1}),[]),Vp(()=>{if(k&&(M.current=k),P&&(A.current=P),k&&P){if(F.current)return F.current(k,P,J);J()}},[k,P,J,F]);const ae=f.useMemo(()=>({reference:M,floating:A,setReference:b,setFloating:E}),[b,E]),U=f.useMemo(()=>({reference:k,floating:P}),[k,P]),te=f.useMemo(()=>{const L={position:n,left:0,top:0};if(!U.floating)return L;const ie=zC(U.floating,h.x),K=zC(U.floating,h.y);return l?{...L,transform:"translate("+ie+"px, "+K+"px)",...jT(U.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:ie,top:K}},[n,l,U.floating,h.x,h.y]);return f.useMemo(()=>({...h,update:J,refs:ae,elements:U,floatingStyles:te}),[h,J,ae,U,te])}function gx(e){const[t,n]=f.useState(void 0);return Pn(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(o=>{if(!Array.isArray(o)||!o.length)return;const i=o[0];let s,l;if("borderBoxSize"in i){const u=i.borderBoxSize,d=Array.isArray(u)?u[0]:u;s=d.inlineSize,l=d.blockSize}else s=e.offsetWidth,l=e.offsetHeight;n({width:s,height:l})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}const zT="Popper",[BT,Ns]=An(zT),[cU,UT]=BT(zT),uU=e=>{const{__scopePopper:t,children:n}=e,[r,o]=f.useState(null);return f.createElement(cU,{scope:t,anchor:r,onAnchorChange:o},n)},dU="PopperAnchor",fU=f.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...o}=e,i=UT(dU,n),s=f.useRef(null),l=Be(t,s);return f.useEffect(()=>{i.onAnchorChange((r==null?void 0:r.current)||s.current)}),r?null:f.createElement(Pe.div,Y({},o,{ref:l}))}),VT="PopperContent",[pU,mte]=BT(VT),hU=f.forwardRef((e,t)=>{var n,r,o,i,s,l,u,d;const{__scopePopper:h,side:m="bottom",sideOffset:g=0,align:y="center",alignOffset:x=0,arrowPadding:_=0,avoidCollisions:C=!0,collisionBoundary:S=[],collisionPadding:b=0,sticky:E="partial",hideWhenDetached:k=!1,updatePositionStrategy:P="optimized",onPlaced:M,...A}=e,O=UT(VT,h),[F,V]=f.useState(null),J=Be(t,Yt=>V(Yt)),[G,ae]=f.useState(null),U=gx(G),te=(n=U==null?void 0:U.width)!==null&&n!==void 0?n:0,L=(r=U==null?void 0:U.height)!==null&&r!==void 0?r:0,ie=m+(y!=="center"?"-"+y:""),K=typeof b=="number"?b:{top:0,right:0,bottom:0,left:0,...b},Q=Array.isArray(S)?S:[S],W=Q.length>0,le={padding:K,boundary:Q.filter(mU),altBoundary:W},{refs:ge,floatingStyles:Ve,placement:Ue,isPositioned:We,middlewareData:Me}=lU({strategy:"fixed",placement:ie,whileElementsMounted:(...Yt)=>iU(...Yt,{animationFrame:P==="always"}),elements:{reference:O.anchor},middleware:[FB({mainAxis:g+L,alignmentAxis:x}),C&&jB({mainAxis:!0,crossAxis:!1,limiter:E==="partial"?zB():void 0,...le}),C&&DB({...le}),BB({...le,apply:({elements:Yt,rects:Er,availableWidth:gt,availableHeight:js})=>{const{width:I,height:X}=Er.reference,Z=Yt.floating.style;Z.setProperty("--radix-popper-available-width",`${gt}px`),Z.setProperty("--radix-popper-available-height",`${js}px`),Z.setProperty("--radix-popper-anchor-width",`${I}px`),Z.setProperty("--radix-popper-anchor-height",`${X}px`)}}),G&&aU({element:G,padding:_}),gU({arrowWidth:te,arrowHeight:L}),k&&IB({strategy:"referenceHidden",...le})]}),[fe,xe]=WT(Ue),$e=Ft(M);Pn(()=>{We&&($e==null||$e())},[We,$e]);const Ae=(o=Me.arrow)===null||o===void 0?void 0:o.x,Oe=(i=Me.arrow)===null||i===void 0?void 0:i.y,je=((s=Me.arrow)===null||s===void 0?void 0:s.centerOffset)!==0,[Ot,ct]=f.useState();return Pn(()=>{F&&ct(window.getComputedStyle(F).zIndex)},[F]),f.createElement("div",{ref:ge.setFloating,"data-radix-popper-content-wrapper":"",style:{...Ve,transform:We?Ve.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:Ot,"--radix-popper-transform-origin":[(l=Me.transformOrigin)===null||l===void 0?void 0:l.x,(u=Me.transformOrigin)===null||u===void 0?void 0:u.y].join(" ")},dir:e.dir},f.createElement(pU,{scope:h,placedSide:fe,onArrowChange:ae,arrowX:Ae,arrowY:Oe,shouldHideArrow:je},f.createElement(Pe.div,Y({"data-side":fe,"data-align":xe},A,{ref:J,style:{...A.style,animation:We?void 0:"none",opacity:(d=Me.hide)!==null&&d!==void 0&&d.referenceHidden?0:void 0}}))))});function mU(e){return e!==null}const gU=e=>({name:"transformOrigin",options:e,fn(t){var n,r,o,i,s;const{placement:l,rects:u,middlewareData:d}=t,m=((n=d.arrow)===null||n===void 0?void 0:n.centerOffset)!==0,g=m?0:e.arrowWidth,y=m?0:e.arrowHeight,[x,_]=WT(l),C={start:"0%",center:"50%",end:"100%"}[_],S=((r=(o=d.arrow)===null||o===void 0?void 0:o.x)!==null&&r!==void 0?r:0)+g/2,b=((i=(s=d.arrow)===null||s===void 0?void 0:s.y)!==null&&i!==void 0?i:0)+y/2;let E="",k="";return x==="bottom"?(E=m?C:`${S}px`,k=`${-y}px`):x==="top"?(E=m?C:`${S}px`,k=`${u.floating.height+y}px`):x==="right"?(E=`${-y}px`,k=m?C:`${b}px`):x==="left"&&(E=`${u.floating.width+y}px`,k=m?C:`${b}px`),{data:{x:E,y:k}}}});function WT(e){const[t,n="center"]=e.split("-");return[t,n]}const Od=uU,zm=fU,Bm=hU,Md=f.forwardRef((e,t)=>{var n;const{container:r=globalThis==null||(n=globalThis.document)===null||n===void 0?void 0:n.body,...o}=e;return r?XI.createPortal(f.createElement(Pe.div,Y({},o,{ref:t})),r):null});function vU(e,t){return f.useReducer((n,r)=>{const o=t[n][r];return o??n},e)}const xn=e=>{const{present:t,children:n}=e,r=yU(t),o=typeof n=="function"?n({present:r.isPresent}):f.Children.only(n),i=Be(r.ref,o.ref);return typeof n=="function"||r.isPresent?f.cloneElement(o,{ref:i}):null};xn.displayName="Presence";function yU(e){const[t,n]=f.useState(),r=f.useRef({}),o=f.useRef(e),i=f.useRef("none"),s=e?"mounted":"unmounted",[l,u]=vU(s,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return f.useEffect(()=>{const d=sp(r.current);i.current=l==="mounted"?d:"none"},[l]),Pn(()=>{const d=r.current,h=o.current;if(h!==e){const g=i.current,y=sp(d);e?u("MOUNT"):y==="none"||(d==null?void 0:d.display)==="none"?u("UNMOUNT"):u(h&&g!==y?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,u]),Pn(()=>{if(t){const d=m=>{const y=sp(r.current).includes(m.animationName);m.target===t&&y&&Os.flushSync(()=>u("ANIMATION_END"))},h=m=>{m.target===t&&(i.current=sp(r.current))};return t.addEventListener("animationstart",h),t.addEventListener("animationcancel",d),t.addEventListener("animationend",d),()=>{t.removeEventListener("animationstart",h),t.removeEventListener("animationcancel",d),t.removeEventListener("animationend",d)}}else u("ANIMATION_END")},[t,u]),{isPresent:["mounted","unmountSuspended"].includes(l),ref:f.useCallback(d=>{d&&(r.current=getComputedStyle(d)),n(d)},[])}}function sp(e){return(e==null?void 0:e.animationName)||"none"}function Zr({prop:e,defaultProp:t,onChange:n=()=>{}}){const[r,o]=wU({defaultProp:t,onChange:n}),i=e!==void 0,s=i?e:r,l=Ft(n),u=f.useCallback(d=>{if(i){const m=typeof d=="function"?d(e):d;m!==e&&l(m)}else o(d)},[i,e,o,l]);return[s,u]}function wU({defaultProp:e,onChange:t}){const n=f.useState(e),[r]=n,o=f.useRef(r),i=Ft(t);return f.useEffect(()=>{o.current!==r&&(i(r),o.current=r)},[r,o,i]),n}const Um=f.forwardRef((e,t)=>f.createElement(Pe.span,Y({},e,{ref:t,style:{position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal",...e.style}}))),xU=Um,[Vm,gte]=An("Tooltip",[Ns]),vx=Ns(),bU="TooltipProvider",_U=700,l1="tooltip.open",[SU,yx]=Vm(bU),EU=e=>{const{__scopeTooltip:t,delayDuration:n=_U,skipDelayDuration:r=300,disableHoverableContent:o=!1,children:i}=e,[s,l]=f.useState(!0),u=f.useRef(!1),d=f.useRef(0);return f.useEffect(()=>{const h=d.current;return()=>window.clearTimeout(h)},[]),f.createElement(SU,{scope:t,isOpenDelayed:s,delayDuration:n,onOpen:f.useCallback(()=>{window.clearTimeout(d.current),l(!1)},[]),onClose:f.useCallback(()=>{window.clearTimeout(d.current),d.current=window.setTimeout(()=>l(!0),r)},[r]),isPointerInTransitRef:u,onPointerInTransitChange:f.useCallback(h=>{u.current=h},[]),disableHoverableContent:o},i)},wx="Tooltip",[CU,Wm]=Vm(wx),$U=e=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:o=!1,onOpenChange:i,disableHoverableContent:s,delayDuration:l}=e,u=yx(wx,e.__scopeTooltip),d=vx(t),[h,m]=f.useState(null),g=nr(),y=f.useRef(0),x=s??u.disableHoverableContent,_=l??u.delayDuration,C=f.useRef(!1),[S=!1,b]=Zr({prop:r,defaultProp:o,onChange:A=>{A?(u.onOpen(),document.dispatchEvent(new CustomEvent(l1))):u.onClose(),i==null||i(A)}}),E=f.useMemo(()=>S?C.current?"delayed-open":"instant-open":"closed",[S]),k=f.useCallback(()=>{window.clearTimeout(y.current),C.current=!1,b(!0)},[b]),P=f.useCallback(()=>{window.clearTimeout(y.current),b(!1)},[b]),M=f.useCallback(()=>{window.clearTimeout(y.current),y.current=window.setTimeout(()=>{C.current=!0,b(!0)},_)},[_,b]);return f.useEffect(()=>()=>window.clearTimeout(y.current),[]),f.createElement(Od,d,f.createElement(CU,{scope:t,contentId:g,open:S,stateAttribute:E,trigger:h,onTriggerChange:m,onTriggerEnter:f.useCallback(()=>{u.isOpenDelayed?M():k()},[u.isOpenDelayed,M,k]),onTriggerLeave:f.useCallback(()=>{x?P():window.clearTimeout(y.current)},[P,x]),onOpen:k,onClose:P,disableHoverableContent:x},n))},UC="TooltipTrigger",kU=f.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,o=Wm(UC,n),i=yx(UC,n),s=vx(n),l=f.useRef(null),u=Be(t,l,o.onTriggerChange),d=f.useRef(!1),h=f.useRef(!1),m=f.useCallback(()=>d.current=!1,[]);return f.useEffect(()=>()=>document.removeEventListener("pointerup",m),[m]),f.createElement(zm,Y({asChild:!0},s),f.createElement(Pe.button,Y({"aria-describedby":o.open?o.contentId:void 0,"data-state":o.stateAttribute},r,{ref:u,onPointerMove:ue(e.onPointerMove,g=>{g.pointerType!=="touch"&&!h.current&&!i.isPointerInTransitRef.current&&(o.onTriggerEnter(),h.current=!0)}),onPointerLeave:ue(e.onPointerLeave,()=>{o.onTriggerLeave(),h.current=!1}),onPointerDown:ue(e.onPointerDown,()=>{d.current=!0,document.addEventListener("pointerup",m,{once:!0})}),onFocus:ue(e.onFocus,()=>{d.current||o.onOpen()}),onBlur:ue(e.onBlur,o.onClose),onClick:ue(e.onClick,o.onClose)})))}),RU="TooltipPortal",[vte,TU]=Vm(RU,{forceMount:void 0}),rd="TooltipContent",PU=f.forwardRef((e,t)=>{const n=TU(rd,e.__scopeTooltip),{forceMount:r=n.forceMount,side:o="top",...i}=e,s=Wm(rd,e.__scopeTooltip);return f.createElement(xn,{present:r||s.open},s.disableHoverableContent?f.createElement(HT,Y({side:o},i,{ref:t})):f.createElement(AU,Y({side:o},i,{ref:t})))}),AU=f.forwardRef((e,t)=>{const n=Wm(rd,e.__scopeTooltip),r=yx(rd,e.__scopeTooltip),o=f.useRef(null),i=Be(t,o),[s,l]=f.useState(null),{trigger:u,onClose:d}=n,h=o.current,{onPointerInTransitChange:m}=r,g=f.useCallback(()=>{l(null),m(!1)},[m]),y=f.useCallback((x,_)=>{const C=x.currentTarget,S={x:x.clientX,y:x.clientY},b=MU(S,C.getBoundingClientRect()),E=NU(S,b),k=DU(_.getBoundingClientRect()),P=LU([...E,...k]);l(P),m(!0)},[m]);return f.useEffect(()=>()=>g(),[g]),f.useEffect(()=>{if(u&&h){const x=C=>y(C,h),_=C=>y(C,u);return u.addEventListener("pointerleave",x),h.addEventListener("pointerleave",_),()=>{u.removeEventListener("pointerleave",x),h.removeEventListener("pointerleave",_)}}},[u,h,y,g]),f.useEffect(()=>{if(s){const x=_=>{const C=_.target,S={x:_.clientX,y:_.clientY},b=(u==null?void 0:u.contains(C))||(h==null?void 0:h.contains(C)),E=!IU(S,s);b?g():E&&(g(),d())};return document.addEventListener("pointermove",x),()=>document.removeEventListener("pointermove",x)}},[u,h,s,d,g]),f.createElement(HT,Y({},e,{ref:i}))}),[OU,yte]=Vm(wx,{isInside:!1}),HT=f.forwardRef((e,t)=>{const{__scopeTooltip:n,children:r,"aria-label":o,onEscapeKeyDown:i,onPointerDownOutside:s,...l}=e,u=Wm(rd,n),d=vx(n),{onClose:h}=u;return f.useEffect(()=>(document.addEventListener(l1,h),()=>document.removeEventListener(l1,h)),[h]),f.useEffect(()=>{if(u.trigger){const m=g=>{const y=g.target;y!=null&&y.contains(u.trigger)&&h()};return window.addEventListener("scroll",m,{capture:!0}),()=>window.removeEventListener("scroll",m,{capture:!0})}},[u.trigger,h]),f.createElement(yc,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:i,onPointerDownOutside:s,onFocusOutside:m=>m.preventDefault(),onDismiss:h},f.createElement(Bm,Y({"data-state":u.stateAttribute},d,l,{ref:t,style:{...l.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"}}),f.createElement(sx,null,r),f.createElement(OU,{scope:n,isInside:!0},f.createElement(xU,{id:u.contentId,role:"tooltip"},o||r))))});function MU(e,t){const n=Math.abs(t.top-e.y),r=Math.abs(t.bottom-e.y),o=Math.abs(t.right-e.x),i=Math.abs(t.left-e.x);switch(Math.min(n,r,o,i)){case i:return"left";case o:return"right";case n:return"top";case r:return"bottom";default:throw new Error("unreachable")}}function NU(e,t,n=5){const r=[];switch(t){case"top":r.push({x:e.x-n,y:e.y+n},{x:e.x+n,y:e.y+n});break;case"bottom":r.push({x:e.x-n,y:e.y-n},{x:e.x+n,y:e.y-n});break;case"left":r.push({x:e.x+n,y:e.y-n},{x:e.x+n,y:e.y+n});break;case"right":r.push({x:e.x-n,y:e.y-n},{x:e.x-n,y:e.y+n});break}return r}function DU(e){const{top:t,right:n,bottom:r,left:o}=e;return[{x:o,y:t},{x:n,y:t},{x:n,y:r},{x:o,y:r}]}function IU(e,t){const{x:n,y:r}=e;let o=!1;for(let i=0,s=t.length-1;ir!=h>r&&n<(d-l)*(r-u)/(h-u)+l&&(o=!o)}return o}function LU(e){const t=e.slice();return t.sort((n,r)=>n.xr.x?1:n.yr.y?1:0),FU(t)}function FU(e){if(e.length<=1)return e.slice();const t=[];for(let r=0;r=2;){const i=t[t.length-1],s=t[t.length-2];if((i.x-s.x)*(o.y-s.y)>=(i.y-s.y)*(o.x-s.x))t.pop();else break}t.push(o)}t.pop();const n=[];for(let r=e.length-1;r>=0;r--){const o=e[r];for(;n.length>=2;){const i=n[n.length-1],s=n[n.length-2];if((i.x-s.x)*(o.y-s.y)>=(i.y-s.y)*(o.x-s.x))n.pop();else break}n.push(o)}return n.pop(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}const jU=EU,zU=$U,BU=kU,KT=PU,UU=jU,YT=zU,GT=BU,xx=f.forwardRef(({className:e,sideOffset:t=4,...n},r)=>v.jsx(KT,{ref:r,sideOffset:t,className:Ce("z-50 border overflow-hidden rounded-md bg-background text-foreground px-3 py-1.5 text-xs animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...n}));xx.displayName=KT.displayName;const bx=Om("inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50",{variants:{variant:{default:"bg-primary text-primary-foreground shadow hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",outline:"border border-input bg-transparent shadow-sm hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2",sm:"h-8 rounded-md px-3 text-xs",lg:"h-10 rounded-md px-8",icon:"h-9 w-9"}},defaultVariants:{variant:"default",size:"default"}}),Rn=f.forwardRef(({className:e,variant:t,size:n,asChild:r=!1,...o},i)=>{const s=r?Wo:"button";return v.jsx(s,{className:Ce(bx({variant:t,size:n,className:e}),"outline-none cursor-default"),ref:i,tabIndex:-1,...o})});Rn.displayName="Button";const vn=f.forwardRef(({tooltip:e,children:t,...n},r)=>v.jsxs(YT,{children:[v.jsx(GT,{asChild:!0,children:v.jsx(Rn,{variant:"ghost",size:"icon",...n,ref:r,tabIndex:-1,className:"cursor-default bg-background",children:v.jsx("div",{className:"icon-button-icon-wrapper",children:t})})}),v.jsx(xx,{children:v.jsx("p",{children:e})})]})),c1=e=>{const{onFileUpload:t,children:n,...r}=e,[o]=f.useState(`file-upload-${Math.random().toString()}`),i=s=>{var u;const l=(u=s.currentTarget.files)==null?void 0:u[0];l&&t(l)};return v.jsxs(v.Fragment,{children:[v.jsx("label",{htmlFor:o,children:v.jsx(vn,{...r,asChild:!0,children:n})}),v.jsx(Pd,{style:{display:"none"},id:o,name:o,type:"file",onChange:i,accept:"image/png, image/jpeg"})]})};var VU={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const WU=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Kt=(e,t)=>{const n=f.forwardRef(({color:r="currentColor",size:o=24,strokeWidth:i=2,absoluteStrokeWidth:s,children:l,...u},d)=>f.createElement("svg",{ref:d,...VU,width:o,height:o,stroke:r,strokeWidth:s?Number(i)*24/Number(o):i,className:`lucide lucide-${WU(e)}`,...u},[...t.map(([h,m])=>f.createElement(h,m)),...(Array.isArray(l)?l:[l])||[]]));return n.displayName=`${e}`,n},HU=Kt("Blocks",[["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["path",{d:"M10 21V8a1 1 0 0 0-1-1H4a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-5a1 1 0 0 0-1-1H3",key:"1fpvtg"}]]),KU=Kt("ChevronLeft",[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]]),YU=Kt("ChevronRight",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]),GU=Kt("Coffee",[["path",{d:"M17 8h1a4 4 0 1 1 0 8h-1",key:"jx4kbh"}],["path",{d:"M3 8h14v9a4 4 0 0 1-4 4H7a4 4 0 0 1-4-4Z",key:"1bxrl0"}],["line",{x1:"6",x2:"6",y1:"2",y2:"4",key:"1cr9l3"}],["line",{x1:"10",x2:"10",y1:"2",y2:"4",key:"170wym"}],["line",{x1:"14",x2:"14",y1:"2",y2:"4",key:"1c5f70"}]]),XU=Kt("Download",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"7 10 12 15 17 10",key:"2ggqvy"}],["line",{x1:"12",x2:"12",y1:"15",y2:"3",key:"1vk2je"}]]),ZU=Kt("Eraser",[["path",{d:"m7 21-4.3-4.3c-1-1-1-2.5 0-3.4l9.6-9.6c1-1 2.5-1 3.4 0l5.6 5.6c1 1 1 2.5 0 3.4L13 21",key:"182aya"}],["path",{d:"M22 21H7",key:"t4ddhn"}],["path",{d:"m5 11 9 9",key:"1mo9qw"}]]),qU=Kt("Expand",[["path",{d:"m21 21-6-6m6 6v-4.8m0 4.8h-4.8",key:"1c15vz"}],["path",{d:"M3 16.2V21m0 0h4.8M3 21l6-6",key:"1fsnz2"}],["path",{d:"M21 7.8V3m0 0h-4.8M21 3l-6 6",key:"hawz9i"}],["path",{d:"M3 7.8V3m0 0h4.8M3 3l6 6",key:"u9ee12"}]]),QU=Kt("Eye",[["path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z",key:"rwhkz3"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]),JU=Kt("FolderClosed",[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}],["path",{d:"M2 10h20",key:"1ir3d8"}]]),XT=Kt("Fullscreen",[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}],["rect",{width:"10",height:"8",x:"7",y:"8",rx:"1",key:"vys8me"}]]),eV=Kt("Image",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]]),tV=Kt("Keyboard",[["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",ry:"2",key:"15u882"}],["path",{d:"M6 8h.001",key:"1ej0i3"}],["path",{d:"M10 8h.001",key:"1x2st2"}],["path",{d:"M14 8h.001",key:"1vkmyp"}],["path",{d:"M18 8h.001",key:"kfsenl"}],["path",{d:"M8 12h.001",key:"1sjpby"}],["path",{d:"M12 12h.001",key:"al75ts"}],["path",{d:"M16 12h.001",key:"931bgk"}],["path",{d:"M7 16h10",key:"wp8him"}]]),nV=Kt("Minus",[["path",{d:"M5 12h14",key:"1ays0h"}]]),rV=Kt("MousePointerClick",[["path",{d:"m9 9 5 12 1.8-5.2L21 14Z",key:"1b76lo"}],["path",{d:"M7.2 2.2 8 5.1",key:"1cfko1"}],["path",{d:"m5.1 8-2.9-.8",key:"1go3kf"}],["path",{d:"M14 4.1 12 6",key:"ita8i4"}],["path",{d:"m6 12-1.9 2",key:"mnht97"}]]),oV=Kt("Plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]),iV=Kt("Redo",[["path",{d:"M21 7v6h-6",key:"3ptur4"}],["path",{d:"M3 17a9 9 0 0 1 9-9 9 9 0 0 1 6 2.3l3 2.7",key:"1kgawr"}]]),sV=Kt("RotateCw",[["path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8",key:"1p45f6"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}]]),aV=Kt("Settings",[["path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z",key:"1qme2f"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]),VC=Kt("Slice",[["path",{d:"m8 14-6 6h9v-3",key:"zo3j9a"}],["path",{d:"M18.37 3.63 8 14l3 3L21.37 6.63a2.12 2.12 0 1 0-3-3Z",key:"1dzx0j"}]]),WC=Kt("Smile",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 14s1.5 2 4 2 4-2 4-2",key:"1y1vjs"}],["line",{x1:"9",x2:"9.01",y1:"9",y2:"9",key:"yxxnd0"}],["line",{x1:"15",x2:"15.01",y1:"9",y2:"9",key:"1p4y9e"}]]),lV=Kt("Undo",[["path",{d:"M3 7v6h6",key:"1v2h90"}],["path",{d:"M21 17a9 9 0 0 0-9-9 9 9 0 0 0-6 2.3L3 13",key:"1r6uu6"}]]),ZT=Kt("Upload",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"17 8 12 3 7 8",key:"t8dd8p"}],["line",{x1:"12",x2:"12",y1:"3",y2:"15",key:"widbto"}]]);function cV(e,t){const[n,r]=f.useState(e);return f.useEffect(()=>{const o=setTimeout(()=>{r(e)},t);return()=>{clearTimeout(o)}},[e,t]),n}function u1(e){const[t,n]=f.useState(()=>typeof e=="boolean"?e:!!e),r=f.useCallback(o=>n(typeof o=="boolean"?o:i=>!i),[]);return[t,r]}const w0="focusScope.autoFocusOnMount",x0="focusScope.autoFocusOnUnmount",HC={bubbles:!1,cancelable:!0},Hm=f.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:o,onUnmountAutoFocus:i,...s}=e,[l,u]=f.useState(null),d=Ft(o),h=Ft(i),m=f.useRef(null),g=Be(t,_=>u(_)),y=f.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;f.useEffect(()=>{if(r){let b=function(M){if(y.paused||!l)return;const A=M.target;l.contains(A)?m.current=A:Hi(m.current,{select:!0})},E=function(M){if(y.paused||!l)return;const A=M.relatedTarget;A!==null&&(l.contains(A)||Hi(m.current,{select:!0}))},k=function(M){if(document.activeElement===document.body)for(const O of M)O.removedNodes.length>0&&Hi(l)};var _=b,C=E,S=k;document.addEventListener("focusin",b),document.addEventListener("focusout",E);const P=new MutationObserver(k);return l&&P.observe(l,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",b),document.removeEventListener("focusout",E),P.disconnect()}}},[r,l,y.paused]),f.useEffect(()=>{if(l){YC.add(y);const _=document.activeElement;if(!l.contains(_)){const S=new CustomEvent(w0,HC);l.addEventListener(w0,d),l.dispatchEvent(S),S.defaultPrevented||(uV(mV(qT(l)),{select:!0}),document.activeElement===_&&Hi(l))}return()=>{l.removeEventListener(w0,d),setTimeout(()=>{const S=new CustomEvent(x0,HC);l.addEventListener(x0,h),l.dispatchEvent(S),S.defaultPrevented||Hi(_??document.body,{select:!0}),l.removeEventListener(x0,h),YC.remove(y)},0)}}},[l,d,h,y]);const x=f.useCallback(_=>{if(!n&&!r||y.paused)return;const C=_.key==="Tab"&&!_.altKey&&!_.ctrlKey&&!_.metaKey,S=document.activeElement;if(C&&S){const b=_.currentTarget,[E,k]=dV(b);E&&k?!_.shiftKey&&S===k?(_.preventDefault(),n&&Hi(E,{select:!0})):_.shiftKey&&S===E&&(_.preventDefault(),n&&Hi(k,{select:!0})):S===b&&_.preventDefault()}},[n,r,y.paused]);return f.createElement(Pe.div,Y({tabIndex:-1},s,{ref:g,onKeyDown:x}))});function uV(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(Hi(r,{select:t}),document.activeElement!==n)return}function dV(e){const t=qT(e),n=KC(t,e),r=KC(t.reverse(),e);return[n,r]}function qT(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const o=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||o?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function KC(e,t){for(const n of e)if(!fV(n,{upTo:t}))return n}function fV(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function pV(e){return e instanceof HTMLInputElement&&"select"in e}function Hi(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&pV(e)&&t&&e.select()}}const YC=hV();function hV(){let e=[];return{add(t){const n=e[0];t!==n&&(n==null||n.pause()),e=GC(e,t),e.unshift(t)},remove(t){var n;e=GC(e,t),(n=e[0])===null||n===void 0||n.resume()}}}function GC(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function mV(e){return e.filter(t=>t.tagName!=="A")}let b0=0;function Km(){f.useEffect(()=>{var e,t;const n=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",(e=n[0])!==null&&e!==void 0?e:XC()),document.body.insertAdjacentElement("beforeend",(t=n[1])!==null&&t!==void 0?t:XC()),b0++,()=>{b0===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(r=>r.remove()),b0--}},[])}function XC(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.cssText="outline: none; opacity: 0; position: fixed; pointer-events: none",e}var Mo=function(){return Mo=Object.assign||function(t){for(var n,r=1,o=arguments.length;r"u")return OV;var t=MV(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])}},DV=tP(),IV=function(e,t,n,r){var o=e.left,i=e.top,s=e.right,l=e.gap;return n===void 0&&(n="margin"),` + .`.concat(vV,` { + overflow: hidden `).concat(r,`; + padding-right: `).concat(l,"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(i,`px; + padding-right: `).concat(s,`px; + margin-left:0; + margin-top:0; + margin-right: `).concat(l,"px ").concat(r,`; + `),n==="padding"&&"padding-right: ".concat(l,"px ").concat(r,";")].filter(Boolean).join(""),` + } + + .`).concat(Wp,` { + right: `).concat(l,"px ").concat(r,`; + } + + .`).concat(Hp,` { + margin-right: `).concat(l,"px ").concat(r,`; + } + + .`).concat(Wp," .").concat(Wp,` { + right: 0 `).concat(r,`; + } + + .`).concat(Hp," .").concat(Hp,` { + margin-right: 0 `).concat(r,`; + } + + body { + `).concat(yV,": ").concat(l,`px; + } +`)},LV=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,o=r===void 0?"margin":r,i=f.useMemo(function(){return NV(o)},[o]);return f.createElement(DV,{styles:IV(i,!t,o,n?"":"!important")})},d1=!1;if(typeof window<"u")try{var ap=Object.defineProperty({},"passive",{get:function(){return d1=!0,!0}});window.addEventListener("test",ap,ap),window.removeEventListener("test",ap,ap)}catch{d1=!1}var qa=d1?{passive:!1}:!1,FV=function(e){return e.tagName==="TEXTAREA"},nP=function(e,t){var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!FV(e)&&n[t]==="visible")},jV=function(e){return nP(e,"overflowY")},zV=function(e){return nP(e,"overflowX")},qC=function(e,t){var n=t;do{typeof ShadowRoot<"u"&&n instanceof ShadowRoot&&(n=n.host);var r=rP(e,n);if(r){var o=oP(e,n),i=o[1],s=o[2];if(i>s)return!0}n=n.parentNode}while(n&&n!==document.body);return!1},BV=function(e){var t=e.scrollTop,n=e.scrollHeight,r=e.clientHeight;return[t,n,r]},UV=function(e){var t=e.scrollLeft,n=e.scrollWidth,r=e.clientWidth;return[t,n,r]},rP=function(e,t){return e==="v"?jV(t):zV(t)},oP=function(e,t){return e==="v"?BV(t):UV(t)},VV=function(e,t){return e==="h"&&t==="rtl"?-1:1},WV=function(e,t,n,r,o){var i=VV(e,window.getComputedStyle(t).direction),s=i*r,l=n.target,u=t.contains(l),d=!1,h=s>0,m=0,g=0;do{var y=oP(e,l),x=y[0],_=y[1],C=y[2],S=_-C-i*x;(x||S)&&rP(e,l)&&(m+=S,g+=x),l=l.parentNode}while(!u&&l!==document.body||u&&(t.contains(l)||t===l));return(h&&(o&&m===0||!o&&s>m)||!h&&(o&&g===0||!o&&-s>g))&&(d=!0),d},lp=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},QC=function(e){return[e.deltaX,e.deltaY]},JC=function(e){return e&&"current"in e?e.current:e},HV=function(e,t){return e[0]===t[0]&&e[1]===t[1]},KV=function(e){return` + .block-interactivity-`.concat(e,` {pointer-events: none;} + .allow-interactivity-`).concat(e,` {pointer-events: all;} +`)},YV=0,Qa=[];function GV(e){var t=f.useRef([]),n=f.useRef([0,0]),r=f.useRef(),o=f.useState(YV++)[0],i=f.useState(function(){return tP()})[0],s=f.useRef(e);f.useEffect(function(){s.current=e},[e]),f.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(o));var _=gV([e.lockRef.current],(e.shards||[]).map(JC),!0).filter(Boolean);return _.forEach(function(C){return C.classList.add("allow-interactivity-".concat(o))}),function(){document.body.classList.remove("block-interactivity-".concat(o)),_.forEach(function(C){return C.classList.remove("allow-interactivity-".concat(o))})}}},[e.inert,e.lockRef.current,e.shards]);var l=f.useCallback(function(_,C){if("touches"in _&&_.touches.length===2)return!s.current.allowPinchZoom;var S=lp(_),b=n.current,E="deltaX"in _?_.deltaX:b[0]-S[0],k="deltaY"in _?_.deltaY:b[1]-S[1],P,M=_.target,A=Math.abs(E)>Math.abs(k)?"h":"v";if("touches"in _&&A==="h"&&M.type==="range")return!1;var O=qC(A,M);if(!O)return!0;if(O?P=A:(P=A==="v"?"h":"v",O=qC(A,M)),!O)return!1;if(!r.current&&"changedTouches"in _&&(E||k)&&(r.current=P),!P)return!0;var F=r.current||P;return WV(F,C,_,F==="h"?E:k,!0)},[]),u=f.useCallback(function(_){var C=_;if(!(!Qa.length||Qa[Qa.length-1]!==i)){var S="deltaY"in C?QC(C):lp(C),b=t.current.filter(function(P){return P.name===C.type&&P.target===C.target&&HV(P.delta,S)})[0];if(b&&b.should){C.cancelable&&C.preventDefault();return}if(!b){var E=(s.current.shards||[]).map(JC).filter(Boolean).filter(function(P){return P.contains(C.target)}),k=E.length>0?l(C,E[0]):!s.current.noIsolation;k&&C.cancelable&&C.preventDefault()}}},[]),d=f.useCallback(function(_,C,S,b){var E={name:_,delta:C,target:S,should:b};t.current.push(E),setTimeout(function(){t.current=t.current.filter(function(k){return k!==E})},1)},[]),h=f.useCallback(function(_){n.current=lp(_),r.current=void 0},[]),m=f.useCallback(function(_){d(_.type,QC(_),_.target,l(_,e.lockRef.current))},[]),g=f.useCallback(function(_){d(_.type,lp(_),_.target,l(_,e.lockRef.current))},[]);f.useEffect(function(){return Qa.push(i),e.setCallbacks({onScrollCapture:m,onWheelCapture:m,onTouchMoveCapture:g}),document.addEventListener("wheel",u,qa),document.addEventListener("touchmove",u,qa),document.addEventListener("touchstart",h,qa),function(){Qa=Qa.filter(function(_){return _!==i}),document.removeEventListener("wheel",u,qa),document.removeEventListener("touchmove",u,qa),document.removeEventListener("touchstart",h,qa)}},[]);var y=e.removeScrollBar,x=e.inert;return f.createElement(f.Fragment,null,x?f.createElement(i,{styles:KV(o)}):null,y?f.createElement(LV,{gapMode:"margin"}):null)}const XV=CV(eP,GV);var iP=f.forwardRef(function(e,t){return f.createElement(Ym,Mo({},e,{ref:t,sideCar:XV}))});iP.classNames=Ym.classNames;const Gm=iP;var ZV=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},Ja=new WeakMap,cp=new WeakMap,up={},E0=0,sP=function(e){return e&&(e.host||sP(e.parentNode))},qV=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=sP(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})},QV=function(e,t,n,r){var o=qV(t,Array.isArray(e)?e:[e]);up[n]||(up[n]=new WeakMap);var i=up[n],s=[],l=new Set,u=new Set(o),d=function(m){!m||l.has(m)||(l.add(m),d(m.parentNode))};o.forEach(d);var h=function(m){!m||u.has(m)||Array.prototype.forEach.call(m.children,function(g){if(l.has(g))h(g);else{var y=g.getAttribute(r),x=y!==null&&y!=="false",_=(Ja.get(g)||0)+1,C=(i.get(g)||0)+1;Ja.set(g,_),i.set(g,C),s.push(g),_===1&&x&&cp.set(g,!0),C===1&&g.setAttribute(n,"true"),x||g.setAttribute(r,"true")}})};return h(t),l.clear(),E0++,function(){s.forEach(function(m){var g=Ja.get(m)-1,y=i.get(m)-1;Ja.set(m,g),i.set(m,y),g||(cp.has(m)||m.removeAttribute(r),cp.delete(m)),y||m.removeAttribute(n)}),E0--,E0||(Ja=new WeakMap,Ja=new WeakMap,cp=new WeakMap,up={})}},Xm=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),o=t||ZV(e);return o?(r.push.apply(r,Array.from(o.querySelectorAll("[aria-live]"))),QV(r,o,n,"aria-hidden")):function(){return null}};const aP="Dialog",[lP,cP]=An(aP),[JV,bo]=lP(aP),eW=e=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:o,onOpenChange:i,modal:s=!0}=e,l=f.useRef(null),u=f.useRef(null),[d=!1,h]=Zr({prop:r,defaultProp:o,onChange:i});return f.createElement(JV,{scope:t,triggerRef:l,contentRef:u,contentId:nr(),titleId:nr(),descriptionId:nr(),open:d,onOpenChange:h,onOpenToggle:f.useCallback(()=>h(m=>!m),[h]),modal:s},n)},tW="DialogTrigger",uP=f.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=bo(tW,n),i=Be(t,o.triggerRef);return f.createElement(Pe.button,Y({type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":_x(o.open)},r,{ref:i,onClick:ue(e.onClick,o.onOpenToggle)}))}),dP="DialogPortal",[nW,fP]=lP(dP,{forceMount:void 0}),rW=e=>{const{__scopeDialog:t,forceMount:n,children:r,container:o}=e,i=bo(dP,t);return f.createElement(nW,{scope:t,forceMount:n},f.Children.map(r,s=>f.createElement(xn,{present:n||i.open},f.createElement(Md,{asChild:!0,container:o},s))))},f1="DialogOverlay",oW=f.forwardRef((e,t)=>{const n=fP(f1,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,i=bo(f1,e.__scopeDialog);return i.modal?f.createElement(xn,{present:r||i.open},f.createElement(iW,Y({},o,{ref:t}))):null}),iW=f.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=bo(f1,n);return f.createElement(Gm,{as:Wo,allowPinchZoom:!0,shards:[o.contentRef]},f.createElement(Pe.div,Y({"data-state":_x(o.open)},r,{ref:t,style:{pointerEvents:"auto",...r.style}})))}),oc="DialogContent",sW=f.forwardRef((e,t)=>{const n=fP(oc,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,i=bo(oc,e.__scopeDialog);return f.createElement(xn,{present:r||i.open},i.modal?f.createElement(aW,Y({},o,{ref:t})):f.createElement(lW,Y({},o,{ref:t})))}),aW=f.forwardRef((e,t)=>{const n=bo(oc,e.__scopeDialog),r=f.useRef(null),o=Be(t,n.contentRef,r);return f.useEffect(()=>{const i=r.current;if(i)return Xm(i)},[]),f.createElement(pP,Y({},e,{ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:ue(e.onCloseAutoFocus,i=>{var s;i.preventDefault(),(s=n.triggerRef.current)===null||s===void 0||s.focus()}),onPointerDownOutside:ue(e.onPointerDownOutside,i=>{const s=i.detail.originalEvent,l=s.button===0&&s.ctrlKey===!0;(s.button===2||l)&&i.preventDefault()}),onFocusOutside:ue(e.onFocusOutside,i=>i.preventDefault())}))}),lW=f.forwardRef((e,t)=>{const n=bo(oc,e.__scopeDialog),r=f.useRef(!1),o=f.useRef(!1);return f.createElement(pP,Y({},e,{ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var s;if((s=e.onCloseAutoFocus)===null||s===void 0||s.call(e,i),!i.defaultPrevented){var l;r.current||(l=n.triggerRef.current)===null||l===void 0||l.focus(),i.preventDefault()}r.current=!1,o.current=!1},onInteractOutside:i=>{var s,l;(s=e.onInteractOutside)===null||s===void 0||s.call(e,i),i.defaultPrevented||(r.current=!0,i.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const u=i.target;((l=n.triggerRef.current)===null||l===void 0?void 0:l.contains(u))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&o.current&&i.preventDefault()}}))}),pP=f.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:i,...s}=e,l=bo(oc,n),u=f.useRef(null),d=Be(t,u);return Km(),f.createElement(f.Fragment,null,f.createElement(Hm,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:i},f.createElement(yc,Y({role:"dialog",id:l.contentId,"aria-describedby":l.descriptionId,"aria-labelledby":l.titleId,"data-state":_x(l.open)},s,{ref:d,onDismiss:()=>l.onOpenChange(!1)}))),!1)}),hP="DialogTitle",cW=f.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=bo(hP,n);return f.createElement(Pe.h2,Y({id:o.titleId},r,{ref:t}))}),uW="DialogDescription",mP=f.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=bo(uW,n);return f.createElement(Pe.p,Y({id:o.descriptionId},r,{ref:t}))}),dW="DialogClose",fW=f.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=bo(dW,n);return f.createElement(Pe.button,Y({type:"button"},r,{ref:t,onClick:ue(e.onClick,()=>o.onOpenChange(!1))}))});function _x(e){return e?"open":"closed"}const pW="DialogTitleWarning",[hW,wte]=pB(pW,{contentName:oc,titleName:hP,docsSlug:"dialog"}),Sx=eW,gP=uP,Ex=rW,Nd=oW,Dd=sW,Id=cW,Ld=mP,Cx=fW,Zm=Sx,$x=gP,mW=Ex,vP=f.forwardRef(({className:e,...t},n)=>v.jsx(Nd,{ref:n,className:Ce("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t}));vP.displayName=Nd.displayName;const Fd=f.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(mW,{children:[v.jsx(vP,{}),v.jsxs(Dd,{ref:r,className:Ce("fixed left-[50%] top-[50%] z-50 flex flex-col w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",e,"outline-none"),onCloseAutoFocus:o=>o.preventDefault(),...n,children:[t,v.jsxs(Cx,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[v.jsx(yT,{className:"h-4 w-4"}),v.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Fd.displayName=Dd.displayName;const yP=({className:e,...t})=>v.jsx("div",{className:Ce("flex flex-col space-y-1.5 text-center sm:text-left",e),...t});yP.displayName="DialogHeader";const jd=f.forwardRef(({className:e,...t},n)=>v.jsx(Id,{ref:n,className:Ce("text-2xl font-semibold leading-none tracking-tight",e),...t}));jd.displayName=Id.displayName;const gW=f.forwardRef(({className:e,...t},n)=>v.jsx(Ld,{ref:n,className:Ce("text-sm text-muted-foreground",e),...t}));gW.displayName=Ld.displayName;function p1(){return p1=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 EW=function(t,n,r){r===void 0&&(r=!1);var o=n.alt,i=n.meta,s=n.mod,l=n.shift,u=n.ctrl,d=n.keys,h=t.key,m=t.code,g=t.ctrlKey,y=t.metaKey,x=t.shiftKey,_=t.altKey,C=ss(m),S=h.toLowerCase();if(!r){if(o===!_&&S!=="alt"||l===!x&&S!=="shift")return!1;if(s){if(!y&&!g)return!1}else if(i===!y&&S!=="meta"&&S!=="os"||u===!g&&S!=="ctrl"&&S!=="control")return!1}return d&&d.length===1&&(d.includes(S)||d.includes(C))?!0:d?wW(d):!d},CW=f.createContext(void 0),$W=function(){return f.useContext(CW)};function SP(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&&SP(e[r],t[r])},!0):e===t}var kW=f.createContext({hotkeys:[],enabledScopes:[],toggleScope:function(){},enableScope:function(){},disableScope:function(){}}),RW=function(){return f.useContext(kW)};function TW(e){var t=f.useRef(void 0);return SP(t.current,e)||(t.current=e),t.current}var e2=function(t){t.stopPropagation(),t.preventDefault(),t.stopImmediatePropagation()},PW=typeof window<"u"?f.useLayoutEffect:f.useEffect;function AW(e,t,n,r){var o=f.useRef(null),i=f.useRef(!1),s=n instanceof Array?r instanceof Array?void 0:r:n,l=kx(e)?e.join(s==null?void 0:s.splitKey):e,u=n instanceof Array?n:r instanceof Array?r:void 0,d=f.useCallback(t,u??[]),h=f.useRef(d);u?h.current=d:h.current=t;var m=TW(s),g=RW(),y=g.enabledScopes,x=$W();return PW(function(){if(!((m==null?void 0:m.enabled)===!1||!SW(y,m==null?void 0:m.scopes))){var _=function(k,P){var M;if(P===void 0&&(P=!1),!(_W(k)&&!_P(k,m==null?void 0:m.enableOnFormTags))&&!(m!=null&&m.ignoreEventWhen!=null&&m.ignoreEventWhen(k))){if(o.current!==null&&document.activeElement!==o.current&&!o.current.contains(document.activeElement)){e2(k);return}(M=k.target)!=null&&M.isContentEditable&&!(m!=null&&m.enableOnContentEditable)||C0(l,m==null?void 0:m.splitKey).forEach(function(A){var O,F=$0(A,m==null?void 0:m.combinationKey);if(EW(k,F,m==null?void 0:m.ignoreModifiers)||(O=F.keys)!=null&&O.includes("*")){if(P&&i.current)return;if(xW(k,F,m==null?void 0:m.preventDefault),!bW(k,F,m==null?void 0:m.enabled)){e2(k);return}h.current(k,F),P||(i.current=!0)}})}},C=function(k){k.key!==void 0&&(xP(ss(k.code)),((m==null?void 0:m.keydown)===void 0&&(m==null?void 0:m.keyup)!==!0||m!=null&&m.keydown)&&_(k))},S=function(k){k.key!==void 0&&(bP(ss(k.code)),i.current=!1,m!=null&&m.keyup&&_(k,!0))},b=o.current||(s==null?void 0:s.document)||document;return b.addEventListener("keyup",S),b.addEventListener("keydown",C),x&&C0(l,m==null?void 0:m.splitKey).forEach(function(E){return x.addHotkey($0(E,m==null?void 0:m.combinationKey,m==null?void 0:m.description))}),function(){b.removeEventListener("keyup",S),b.removeEventListener("keydown",C),x&&C0(l,m==null?void 0:m.splitKey).forEach(function(E){return x.removeHotkey($0(E,m==null?void 0:m.combinationKey,m==null?void 0:m.description))})}}},[l,m,y]),o}const Zn=(e,t,n)=>{const r=bt(i=>i.disableShortCuts);return AW(e,t,{enabled:!r},n)};function ur(e){const{content:t,keys:n}=e;return v.jsxs("div",{className:"flex justify-between",children:[v.jsx("div",{children:t}),v.jsx("div",{className:"flex gap-[8px]",children:n.map(r=>v.jsx("div",{className:"border px-2 py-1 rounded-lg",children:r},r))})]})}const OW=function(){return/macintosh|mac os x/i.test(navigator.userAgent)},dp=()=>OW()?"Cmd":"Ctrl";function MW(){const[e,t]=u1(!1);return Zn("h",()=>{t()}),v.jsxs(Zm,{open:e,onOpenChange:t,children:[v.jsx($x,{asChild:!0,children:v.jsx(vn,{tooltip:"Hotkeys",children:v.jsx(tV,{})})}),v.jsx(Fd,{children:v.jsxs(yP,{children:[v.jsx(jd,{children:"Hotkeys"}),v.jsxs("div",{className:"flex gap-2 flex-col pt-4",children:[v.jsx(ur,{content:"Pan",keys:["Space + Drag"]}),v.jsx(ur,{content:"Reset Zoom/Pan",keys:["Esc"]}),v.jsx(ur,{content:"Decrease Brush Size",keys:["["]}),v.jsx(ur,{content:"Increase Brush Size",keys:["]"]}),v.jsx(ur,{content:"View Original Image",keys:["Hold Tab"]}),v.jsx(ur,{content:"Undo",keys:[dp(),"Z"]}),v.jsx(ur,{content:"Redo",keys:[dp(),"Shift","Z"]}),v.jsx(ur,{content:"Copy Result",keys:[dp(),"C"]}),v.jsx(ur,{content:"Paste Image",keys:[dp(),"V"]}),v.jsx(ur,{content:"Trigger Manually Inpainting",keys:["Shift","R"]}),v.jsx(ur,{content:"Toggle Hotkeys Dialog",keys:["H"]}),v.jsx(ur,{content:"Toggle Settings Dialog",keys:["S"]}),v.jsx(ur,{content:"Toggle File Manager",keys:["F"]})]})]})})]})}function Rx(e){const[t]=f.useState(new Image),[n,r]=f.useState(!1);return f.useEffect(()=>{if(e)return t.onload=()=>{r(!0)},r(!1),t.src=URL.createObjectURL(e),()=>{t.onload=null}},[e,t]),[t,n]}const EP="Popover",[CP,xte]=An(EP,[Ns]),Tx=Ns(),[NW,bc]=CP(EP),DW=e=>{const{__scopePopover:t,children:n,open:r,defaultOpen:o,onOpenChange:i,modal:s=!1}=e,l=Tx(t),u=f.useRef(null),[d,h]=f.useState(!1),[m=!1,g]=Zr({prop:r,defaultProp:o,onChange:i});return f.createElement(Od,l,f.createElement(NW,{scope:t,contentId:nr(),triggerRef:u,open:m,onOpenChange:g,onOpenToggle:f.useCallback(()=>g(y=>!y),[g]),hasCustomAnchor:d,onCustomAnchorAdd:f.useCallback(()=>h(!0),[]),onCustomAnchorRemove:f.useCallback(()=>h(!1),[]),modal:s},n))},IW="PopoverTrigger",LW=f.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,o=bc(IW,n),i=Tx(n),s=Be(t,o.triggerRef),l=f.createElement(Pe.button,Y({type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":RP(o.open)},r,{ref:s,onClick:ue(e.onClick,o.onOpenToggle)}));return o.hasCustomAnchor?l:f.createElement(zm,Y({asChild:!0},i),l)}),$P="PopoverPortal",[FW,jW]=CP($P,{forceMount:void 0}),zW=e=>{const{__scopePopover:t,forceMount:n,children:r,container:o}=e,i=bc($P,t);return f.createElement(FW,{scope:t,forceMount:n},f.createElement(xn,{present:n||i.open},f.createElement(Md,{asChild:!0,container:o},r)))},od="PopoverContent",BW=f.forwardRef((e,t)=>{const n=jW(od,e.__scopePopover),{forceMount:r=n.forceMount,...o}=e,i=bc(od,e.__scopePopover);return f.createElement(xn,{present:r||i.open},i.modal?f.createElement(UW,Y({},o,{ref:t})):f.createElement(VW,Y({},o,{ref:t})))}),UW=f.forwardRef((e,t)=>{const n=bc(od,e.__scopePopover),r=f.useRef(null),o=Be(t,r),i=f.useRef(!1);return f.useEffect(()=>{const s=r.current;if(s)return Xm(s)},[]),f.createElement(Gm,{as:Wo,allowPinchZoom:!0},f.createElement(kP,Y({},e,{ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:ue(e.onCloseAutoFocus,s=>{var l;s.preventDefault(),i.current||(l=n.triggerRef.current)===null||l===void 0||l.focus()}),onPointerDownOutside:ue(e.onPointerDownOutside,s=>{const l=s.detail.originalEvent,u=l.button===0&&l.ctrlKey===!0,d=l.button===2||u;i.current=d},{checkForDefaultPrevented:!1}),onFocusOutside:ue(e.onFocusOutside,s=>s.preventDefault(),{checkForDefaultPrevented:!1})})))}),VW=f.forwardRef((e,t)=>{const n=bc(od,e.__scopePopover),r=f.useRef(!1),o=f.useRef(!1);return f.createElement(kP,Y({},e,{ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var s;if((s=e.onCloseAutoFocus)===null||s===void 0||s.call(e,i),!i.defaultPrevented){var l;r.current||(l=n.triggerRef.current)===null||l===void 0||l.focus(),i.preventDefault()}r.current=!1,o.current=!1},onInteractOutside:i=>{var s,l;(s=e.onInteractOutside)===null||s===void 0||s.call(e,i),i.defaultPrevented||(r.current=!0,i.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const u=i.target;((l=n.triggerRef.current)===null||l===void 0?void 0:l.contains(u))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&o.current&&i.preventDefault()}}))}),kP=f.forwardRef((e,t)=>{const{__scopePopover:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:i,disableOutsidePointerEvents:s,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:d,onInteractOutside:h,...m}=e,g=bc(od,n),y=Tx(n);return Km(),f.createElement(Hm,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:i},f.createElement(yc,{asChild:!0,disableOutsidePointerEvents:s,onInteractOutside:h,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:d,onDismiss:()=>g.onOpenChange(!1)},f.createElement(Bm,Y({"data-state":RP(g.open),role:"dialog",id:g.contentId},y,m,{ref:t,style:{...m.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}}))))});function RP(e){return e?"open":"closed"}const WW=DW,HW=LW,KW=zW,TP=BW,YW=WW,GW=HW,PP=f.forwardRef(({className:e,align:t="center",sideOffset:n=4,...r},o)=>v.jsx(KW,{children:v.jsx(TP,{ref:o,align:t,tabIndex:-1,sideOffset:n,className:Ce("z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...r})}));PP.displayName=TP.displayName;function XW(){var e=f.useRef(!0);return e.current?(e.current=!1,!0):e.current}var ZW=function(e,t){var n=XW();f.useEffect(function(){if(!n)return e()},t)};const qW=ZW;var QW=function(){};function Px(e){for(var t=[],n=1;n{const[e,t,n,r,o,i]=bt(g=>[g.getIsProcessing(),g.settings.prompt,g.updateSettings,g.runInpainting,g.showPrevMask,g.hidePrevMask]),s=f.useRef(null);OP(s,()=>{s!=null&&s.current&&s.current.blur()});const l=g=>{g.preventDefault(),g.stopPropagation();const y=g.target;n({prompt:y.value})},u=()=>{e||r()},d=g=>{g.key==="Enter"&&!e&&u()},h=()=>{o()},m=()=>{i()};return v.jsxs("div",{className:"flex gap-4 items-center",children:[v.jsx(Pd,{ref:s,className:"min-w-[500px]",value:t,onInput:l,onKeyUp:d,placeholder:"I want to repaint of..."}),v.jsx(Rn,{size:"sm",onClick:u,disabled:e,onMouseEnter:h,onMouseLeave:m,children:"Paint"})]})};var Lh={exports:{}};/** + * @license + * Lodash + * Copyright OpenJS Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */Lh.exports;(function(e,t){(function(){var n,r="4.17.21",o=200,i="Unsupported core-js use. Try https://npms.io/search?q=ponyfill.",s="Expected a function",l="Invalid `variable` option passed into `_.template`",u="__lodash_hash_undefined__",d=500,h="__lodash_placeholder__",m=1,g=2,y=4,x=1,_=2,C=1,S=2,b=4,E=8,k=16,P=32,M=64,A=128,O=256,F=512,V=30,J="...",G=800,ae=16,U=1,te=2,L=3,ie=1/0,K=9007199254740991,Q=17976931348623157e292,W=NaN,le=4294967295,ge=le-1,Ve=le>>>1,Ue=[["ary",A],["bind",C],["bindKey",S],["curry",E],["curryRight",k],["flip",F],["partial",P],["partialRight",M],["rearg",O]],We="[object Arguments]",Me="[object Array]",fe="[object AsyncFunction]",xe="[object Boolean]",$e="[object Date]",Ae="[object DOMException]",Oe="[object Error]",je="[object Function]",Ot="[object GeneratorFunction]",ct="[object Map]",Yt="[object Number]",Er="[object Null]",gt="[object Object]",js="[object Promise]",I="[object Proxy]",X="[object RegExp]",Z="[object Set]",we="[object String]",he="[object Symbol]",de="[object Undefined]",ke="[object WeakMap]",ft="[object WeakSet]",pt="[object ArrayBuffer]",bn="[object DataView]",Cr="[object Float32Array]",ki="[object Float64Array]",_o="[object Int8Array]",Vn="[object Int16Array]",Da="[object Int32Array]",Ri="[object Uint8Array]",zs="[object Uint8ClampedArray]",Ti="[object Uint16Array]",$c="[object Uint32Array]",yg=/\b__p \+= '';/g,wg=/\b(__p \+=) '' \+/g,Kd=/(__e\(.*?\)|\b__t\)) \+\n'';/g,kc=/&(?:amp|lt|gt|quot|#39);/g,Rc=/[&<>"']/g,Tc=RegExp(kc.source),xg=RegExp(Rc.source),Pc=/<%-([\s\S]+?)%>/g,Yd=/<%([\s\S]+?)%>/g,Ac=/<%=([\s\S]+?)%>/g,bg=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,_g=/^\w*$/,Sg=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,H=/[\\^$.*+?()[\]{}|]/g,Ge=RegExp(H.source),st=/^\s+/,Qr=/\s/,an=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,Gd=/\{\n\/\* \[wrapped with (.+)\] \*/,oO=/,? & /,iO=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,sO=/[()=,{}\[\]\/\s]/,aO=/\\(\\)?/g,lO=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,db=/\w*$/,cO=/^[-+]0x[0-9a-f]+$/i,uO=/^0b[01]+$/i,dO=/^\[object .+?Constructor\]$/,fO=/^0o[0-7]+$/i,pO=/^(?:0|[1-9]\d*)$/,hO=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,Xd=/($^)/,mO=/['\n\r\u2028\u2029\\]/g,Zd="\\ud800-\\udfff",gO="\\u0300-\\u036f",vO="\\ufe20-\\ufe2f",yO="\\u20d0-\\u20ff",fb=gO+vO+yO,pb="\\u2700-\\u27bf",hb="a-z\\xdf-\\xf6\\xf8-\\xff",wO="\\xac\\xb1\\xd7\\xf7",xO="\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf",bO="\\u2000-\\u206f",_O=" \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",mb="A-Z\\xc0-\\xd6\\xd8-\\xde",gb="\\ufe0e\\ufe0f",vb=wO+xO+bO+_O,Eg="['’]",SO="["+Zd+"]",yb="["+vb+"]",qd="["+fb+"]",wb="\\d+",EO="["+pb+"]",xb="["+hb+"]",bb="[^"+Zd+vb+wb+pb+hb+mb+"]",Cg="\\ud83c[\\udffb-\\udfff]",CO="(?:"+qd+"|"+Cg+")",_b="[^"+Zd+"]",$g="(?:\\ud83c[\\udde6-\\uddff]){2}",kg="[\\ud800-\\udbff][\\udc00-\\udfff]",Ia="["+mb+"]",Sb="\\u200d",Eb="(?:"+xb+"|"+bb+")",$O="(?:"+Ia+"|"+bb+")",Cb="(?:"+Eg+"(?:d|ll|m|re|s|t|ve))?",$b="(?:"+Eg+"(?:D|LL|M|RE|S|T|VE))?",kb=CO+"?",Rb="["+gb+"]?",kO="(?:"+Sb+"(?:"+[_b,$g,kg].join("|")+")"+Rb+kb+")*",RO="\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",TO="\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])",Tb=Rb+kb+kO,PO="(?:"+[EO,$g,kg].join("|")+")"+Tb,AO="(?:"+[_b+qd+"?",qd,$g,kg,SO].join("|")+")",OO=RegExp(Eg,"g"),MO=RegExp(qd,"g"),Rg=RegExp(Cg+"(?="+Cg+")|"+AO+Tb,"g"),NO=RegExp([Ia+"?"+xb+"+"+Cb+"(?="+[yb,Ia,"$"].join("|")+")",$O+"+"+$b+"(?="+[yb,Ia+Eb,"$"].join("|")+")",Ia+"?"+Eb+"+"+Cb,Ia+"+"+$b,TO,RO,wb,PO].join("|"),"g"),DO=RegExp("["+Sb+Zd+fb+gb+"]"),IO=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,LO=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],FO=-1,kt={};kt[Cr]=kt[ki]=kt[_o]=kt[Vn]=kt[Da]=kt[Ri]=kt[zs]=kt[Ti]=kt[$c]=!0,kt[We]=kt[Me]=kt[pt]=kt[xe]=kt[bn]=kt[$e]=kt[Oe]=kt[je]=kt[ct]=kt[Yt]=kt[gt]=kt[X]=kt[Z]=kt[we]=kt[ke]=!1;var Et={};Et[We]=Et[Me]=Et[pt]=Et[bn]=Et[xe]=Et[$e]=Et[Cr]=Et[ki]=Et[_o]=Et[Vn]=Et[Da]=Et[ct]=Et[Yt]=Et[gt]=Et[X]=Et[Z]=Et[we]=Et[he]=Et[Ri]=Et[zs]=Et[Ti]=Et[$c]=!0,Et[Oe]=Et[je]=Et[ke]=!1;var jO={À:"A",Á:"A",Â:"A",Ã:"A",Ä:"A",Å:"A",à:"a",á:"a",â:"a",ã:"a",ä:"a",å:"a",Ç:"C",ç:"c",Ð:"D",ð:"d",È:"E",É:"E",Ê:"E",Ë:"E",è:"e",é:"e",ê:"e",ë:"e",Ì:"I",Í:"I",Î:"I",Ï:"I",ì:"i",í:"i",î:"i",ï:"i",Ñ:"N",ñ:"n",Ò:"O",Ó:"O",Ô:"O",Õ:"O",Ö:"O",Ø:"O",ò:"o",ó:"o",ô:"o",õ:"o",ö:"o",ø:"o",Ù:"U",Ú:"U",Û:"U",Ü:"U",ù:"u",ú:"u",û:"u",ü:"u",Ý:"Y",ý:"y",ÿ:"y",Æ:"Ae",æ:"ae",Þ:"Th",þ:"th",ß:"ss",Ā:"A",Ă:"A",Ą:"A",ā:"a",ă:"a",ą:"a",Ć:"C",Ĉ:"C",Ċ:"C",Č:"C",ć:"c",ĉ:"c",ċ:"c",č:"c",Ď:"D",Đ:"D",ď:"d",đ:"d",Ē:"E",Ĕ:"E",Ė:"E",Ę:"E",Ě:"E",ē:"e",ĕ:"e",ė:"e",ę:"e",ě:"e",Ĝ:"G",Ğ:"G",Ġ:"G",Ģ:"G",ĝ:"g",ğ:"g",ġ:"g",ģ:"g",Ĥ:"H",Ħ:"H",ĥ:"h",ħ:"h",Ĩ:"I",Ī:"I",Ĭ:"I",Į:"I",İ:"I",ĩ:"i",ī:"i",ĭ:"i",į:"i",ı:"i",Ĵ:"J",ĵ:"j",Ķ:"K",ķ:"k",ĸ:"k",Ĺ:"L",Ļ:"L",Ľ:"L",Ŀ:"L",Ł:"L",ĺ:"l",ļ:"l",ľ:"l",ŀ:"l",ł:"l",Ń:"N",Ņ:"N",Ň:"N",Ŋ:"N",ń:"n",ņ:"n",ň:"n",ŋ:"n",Ō:"O",Ŏ:"O",Ő:"O",ō:"o",ŏ:"o",ő:"o",Ŕ:"R",Ŗ:"R",Ř:"R",ŕ:"r",ŗ:"r",ř:"r",Ś:"S",Ŝ:"S",Ş:"S",Š:"S",ś:"s",ŝ:"s",ş:"s",š:"s",Ţ:"T",Ť:"T",Ŧ:"T",ţ:"t",ť:"t",ŧ:"t",Ũ:"U",Ū:"U",Ŭ:"U",Ů:"U",Ű:"U",Ų:"U",ũ:"u",ū:"u",ŭ:"u",ů:"u",ű:"u",ų:"u",Ŵ:"W",ŵ:"w",Ŷ:"Y",ŷ:"y",Ÿ:"Y",Ź:"Z",Ż:"Z",Ž:"Z",ź:"z",ż:"z",ž:"z",IJ:"IJ",ij:"ij",Œ:"Oe",œ:"oe",ʼn:"'n",ſ:"s"},zO={"&":"&","<":"<",">":">",'"':""","'":"'"},BO={"&":"&","<":"<",">":">",""":'"',"'":"'"},UO={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},VO=parseFloat,WO=parseInt,Pb=typeof Yc=="object"&&Yc&&Yc.Object===Object&&Yc,HO=typeof self=="object"&&self&&self.Object===Object&&self,fn=Pb||HO||Function("return this")(),Tg=t&&!t.nodeType&&t,Bs=Tg&&!0&&e&&!e.nodeType&&e,Ab=Bs&&Bs.exports===Tg,Pg=Ab&&Pb.process,$r=function(){try{var j=Bs&&Bs.require&&Bs.require("util").types;return j||Pg&&Pg.binding&&Pg.binding("util")}catch{}}(),Ob=$r&&$r.isArrayBuffer,Mb=$r&&$r.isDate,Nb=$r&&$r.isMap,Db=$r&&$r.isRegExp,Ib=$r&&$r.isSet,Lb=$r&&$r.isTypedArray;function or(j,ee,q){switch(q.length){case 0:return j.call(ee);case 1:return j.call(ee,q[0]);case 2:return j.call(ee,q[0],q[1]);case 3:return j.call(ee,q[0],q[1],q[2])}return j.apply(ee,q)}function KO(j,ee,q,_e){for(var Ke=-1,ht=j==null?0:j.length;++Ke-1}function Ag(j,ee,q){for(var _e=-1,Ke=j==null?0:j.length;++_e-1;);return q}function Hb(j,ee){for(var q=j.length;q--&&La(ee,j[q],0)>-1;);return q}function t6(j,ee){for(var q=j.length,_e=0;q--;)j[q]===ee&&++_e;return _e}var n6=Dg(jO),r6=Dg(zO);function o6(j){return"\\"+UO[j]}function i6(j,ee){return j==null?n:j[ee]}function Fa(j){return DO.test(j)}function s6(j){return IO.test(j)}function a6(j){for(var ee,q=[];!(ee=j.next()).done;)q.push(ee.value);return q}function jg(j){var ee=-1,q=Array(j.size);return j.forEach(function(_e,Ke){q[++ee]=[Ke,_e]}),q}function Kb(j,ee){return function(q){return j(ee(q))}}function Oi(j,ee){for(var q=-1,_e=j.length,Ke=0,ht=[];++q<_e;){var en=j[q];(en===ee||en===h)&&(j[q]=h,ht[Ke++]=q)}return ht}function ef(j){var ee=-1,q=Array(j.size);return j.forEach(function(_e){q[++ee]=_e}),q}function l6(j){var ee=-1,q=Array(j.size);return j.forEach(function(_e){q[++ee]=[_e,_e]}),q}function c6(j,ee,q){for(var _e=q-1,Ke=j.length;++_e-1}function G6(a,c){var p=this.__data__,w=gf(p,a);return w<0?(++this.size,p.push([a,c])):p[w][1]=c,this}Xo.prototype.clear=W6,Xo.prototype.delete=H6,Xo.prototype.get=K6,Xo.prototype.has=Y6,Xo.prototype.set=G6;function Zo(a){var c=-1,p=a==null?0:a.length;for(this.clear();++c=c?a:c)),a}function Pr(a,c,p,w,$,T){var N,D=c&m,B=c&g,ne=c&y;if(p&&(N=$?p(a,w,$,T):p(a)),N!==n)return N;if(!It(a))return a;var re=Ye(a);if(re){if(N=QM(a),!D)return Wn(a,N)}else{var se=Sn(a),me=se==je||se==Ot;if(Fi(a))return R_(a,D);if(se==gt||se==We||me&&!$){if(N=B||me?{}:Y_(a),!D)return B?BM(a,uM(N,a)):zM(a,o_(N,a))}else{if(!Et[se])return $?a:{};N=JM(a,se,D)}}T||(T=new eo);var Re=T.get(a);if(Re)return Re;T.set(a,N),_S(a)?a.forEach(function(Le){N.add(Pr(Le,c,p,Le,a,T))}):xS(a)&&a.forEach(function(Le,nt){N.set(nt,Pr(Le,c,p,nt,a,T))});var Ie=ne?B?dv:uv:B?Kn:ln,Qe=re?n:Ie(a);return kr(Qe||a,function(Le,nt){Qe&&(nt=Le,Le=a[nt]),Fc(N,nt,Pr(Le,c,p,nt,a,T))}),N}function dM(a){var c=ln(a);return function(p){return i_(p,a,c)}}function i_(a,c,p){var w=p.length;if(a==null)return!w;for(a=_t(a);w--;){var $=p[w],T=c[$],N=a[$];if(N===n&&!($ in a)||!T(N))return!1}return!0}function s_(a,c,p){if(typeof a!="function")throw new Rr(s);return Hc(function(){a.apply(n,p)},c)}function jc(a,c,p,w){var $=-1,T=Qd,N=!0,D=a.length,B=[],ne=c.length;if(!D)return B;p&&(c=Mt(c,ir(p))),w?(T=Ag,N=!1):c.length>=o&&(T=Oc,N=!1,c=new Ws(c));e:for(;++$$?0:$+p),w=w===n||w>$?$:qe(w),w<0&&(w+=$),w=p>w?0:ES(w);p0&&p(D)?c>1?pn(D,c-1,p,w,$):Ai($,D):w||($[$.length]=D)}return $}var Kg=N_(),c_=N_(!0);function So(a,c){return a&&Kg(a,c,ln)}function Yg(a,c){return a&&c_(a,c,ln)}function yf(a,c){return Pi(c,function(p){return ti(a[p])})}function Ks(a,c){c=Ii(c,a);for(var p=0,w=c.length;a!=null&&pc}function hM(a,c){return a!=null&&yt.call(a,c)}function mM(a,c){return a!=null&&c in _t(a)}function gM(a,c,p){return a>=_n(c,p)&&a=120&&re.length>=120)?new Ws(N&&re):n}re=a[0];var se=-1,me=D[0];e:for(;++se<$&&ne.length-1;)D!==a&&cf.call(D,B,1),cf.call(a,B,1);return a}function x_(a,c){for(var p=a?c.length:0,w=p-1;p--;){var $=c[p];if(p==w||$!==T){var T=$;ei($)?cf.call(a,$,1):rv(a,$)}}return a}function ev(a,c){return a+ff(e_()*(c-a+1))}function TM(a,c,p,w){for(var $=-1,T=tn(df((c-a)/(p||1)),0),N=q(T);T--;)N[w?T:++$]=a,a+=p;return N}function tv(a,c){var p="";if(!a||c<1||c>K)return p;do c%2&&(p+=a),c=ff(c/2),c&&(a+=a);while(c);return p}function et(a,c){return yv(Z_(a,c,Yn),a+"")}function PM(a){return r_(Xa(a))}function AM(a,c){var p=Xa(a);return Tf(p,Hs(c,0,p.length))}function Uc(a,c,p,w){if(!It(a))return a;c=Ii(c,a);for(var $=-1,T=c.length,N=T-1,D=a;D!=null&&++$$?0:$+c),p=p>$?$:p,p<0&&(p+=$),$=c>p?0:p-c>>>0,c>>>=0;for(var T=q($);++w<$;)T[w]=a[w+c];return T}function NM(a,c){var p;return Ni(a,function(w,$,T){return p=c(w,$,T),!p}),!!p}function xf(a,c,p){var w=0,$=a==null?w:a.length;if(typeof c=="number"&&c===c&&$<=Ve){for(;w<$;){var T=w+$>>>1,N=a[T];N!==null&&!ar(N)&&(p?N<=c:N=o){var ne=c?null:HM(a);if(ne)return ef(ne);N=!1,$=Oc,B=new Ws}else B=c?[]:D;e:for(;++w=w?a:Ar(a,c,p)}var k_=_6||function(a){return fn.clearTimeout(a)};function R_(a,c){if(c)return a.slice();var p=a.length,w=Xb?Xb(p):new a.constructor(p);return a.copy(w),w}function av(a){var c=new a.constructor(a.byteLength);return new af(c).set(new af(a)),c}function IM(a,c){var p=c?av(a.buffer):a.buffer;return new a.constructor(p,a.byteOffset,a.byteLength)}function LM(a){var c=new a.constructor(a.source,db.exec(a));return c.lastIndex=a.lastIndex,c}function FM(a){return Lc?_t(Lc.call(a)):{}}function T_(a,c){var p=c?av(a.buffer):a.buffer;return new a.constructor(p,a.byteOffset,a.length)}function P_(a,c){if(a!==c){var p=a!==n,w=a===null,$=a===a,T=ar(a),N=c!==n,D=c===null,B=c===c,ne=ar(c);if(!D&&!ne&&!T&&a>c||T&&N&&B&&!D&&!ne||w&&N&&B||!p&&B||!$)return 1;if(!w&&!T&&!ne&&a=D)return B;var ne=p[w];return B*(ne=="desc"?-1:1)}}return a.index-c.index}function A_(a,c,p,w){for(var $=-1,T=a.length,N=p.length,D=-1,B=c.length,ne=tn(T-N,0),re=q(B+ne),se=!w;++D1?p[$-1]:n,N=$>2?p[2]:n;for(T=a.length>3&&typeof T=="function"?($--,T):n,N&&Mn(p[0],p[1],N)&&(T=$<3?n:T,$=1),c=_t(c);++w<$;){var D=p[w];D&&a(c,D,w,T)}return c})}function M_(a,c){return function(p,w){if(p==null)return p;if(!Hn(p))return a(p,w);for(var $=p.length,T=c?$:-1,N=_t(p);(c?T--:++T<$)&&w(N[T],T,N)!==!1;);return p}}function N_(a){return function(c,p,w){for(var $=-1,T=_t(c),N=w(c),D=N.length;D--;){var B=N[a?D:++$];if(p(T[B],B,T)===!1)break}return c}}function UM(a,c,p){var w=c&C,$=Vc(a);function T(){var N=this&&this!==fn&&this instanceof T?$:a;return N.apply(w?p:this,arguments)}return T}function D_(a){return function(c){c=vt(c);var p=Fa(c)?Jr(c):n,w=p?p[0]:c.charAt(0),$=p?Li(p,1).join(""):c.slice(1);return w[a]()+$}}function Ka(a){return function(c){return Og(MS(OS(c).replace(OO,"")),a,"")}}function Vc(a){return function(){var c=arguments;switch(c.length){case 0:return new a;case 1:return new a(c[0]);case 2:return new a(c[0],c[1]);case 3:return new a(c[0],c[1],c[2]);case 4:return new a(c[0],c[1],c[2],c[3]);case 5:return new a(c[0],c[1],c[2],c[3],c[4]);case 6:return new a(c[0],c[1],c[2],c[3],c[4],c[5]);case 7:return new a(c[0],c[1],c[2],c[3],c[4],c[5],c[6])}var p=Wa(a.prototype),w=a.apply(p,c);return It(w)?w:p}}function VM(a,c,p){var w=Vc(a);function $(){for(var T=arguments.length,N=q(T),D=T,B=Ya($);D--;)N[D]=arguments[D];var ne=T<3&&N[0]!==B&&N[T-1]!==B?[]:Oi(N,B);if(T-=ne.length,T-1?$[T?c[N]:N]:n}}function L_(a){return Jo(function(c){var p=c.length,w=p,$=Tr.prototype.thru;for(a&&c.reverse();w--;){var T=c[w];if(typeof T!="function")throw new Rr(s);if($&&!N&&kf(T)=="wrapper")var N=new Tr([],!0)}for(w=N?w:p;++w1&&at.reverse(),re&&BD))return!1;var ne=T.get(a),re=T.get(c);if(ne&&re)return ne==c&&re==a;var se=-1,me=!0,Re=p&_?new Ws:n;for(T.set(a,c),T.set(c,a);++se1?"& ":"")+c[w],c=c.join(p>2?", ":" "),a.replace(an,`{ +/* [wrapped with `+c+`] */ +`)}function tN(a){return Ye(a)||Xs(a)||!!(Qb&&a&&a[Qb])}function ei(a,c){var p=typeof a;return c=c??K,!!c&&(p=="number"||p!="symbol"&&pO.test(a))&&a>-1&&a%1==0&&a0){if(++c>=G)return arguments[0]}else c=0;return a.apply(n,arguments)}}function Tf(a,c){var p=-1,w=a.length,$=w-1;for(c=c===n?w:c;++p1?a[c-1]:n;return p=typeof p=="function"?(a.pop(),p):n,lS(a,p)});function cS(a){var c=R(a);return c.__chain__=!0,c}function f7(a,c){return c(a),a}function Pf(a,c){return c(a)}var p7=Jo(function(a){var c=a.length,p=c?a[0]:0,w=this.__wrapped__,$=function(T){return Hg(T,a)};return c>1||this.__actions__.length||!(w instanceof ot)||!ei(p)?this.thru($):(w=w.slice(p,+p+(c?1:0)),w.__actions__.push({func:Pf,args:[$],thisArg:n}),new Tr(w,this.__chain__).thru(function(T){return c&&!T.length&&T.push(n),T}))});function h7(){return cS(this)}function m7(){return new Tr(this.value(),this.__chain__)}function g7(){this.__values__===n&&(this.__values__=SS(this.value()));var a=this.__index__>=this.__values__.length,c=a?n:this.__values__[this.__index__++];return{done:a,value:c}}function v7(){return this}function y7(a){for(var c,p=this;p instanceof mf;){var w=nS(p);w.__index__=0,w.__values__=n,c?$.__wrapped__=w:c=w;var $=w;p=p.__wrapped__}return $.__wrapped__=a,c}function w7(){var a=this.__wrapped__;if(a instanceof ot){var c=a;return this.__actions__.length&&(c=new ot(this)),c=c.reverse(),c.__actions__.push({func:Pf,args:[wv],thisArg:n}),new Tr(c,this.__chain__)}return this.thru(wv)}function x7(){return C_(this.__wrapped__,this.__actions__)}var b7=_f(function(a,c,p){yt.call(a,p)?++a[p]:qo(a,p,1)});function _7(a,c,p){var w=Ye(a)?Fb:fM;return p&&Mn(a,c,p)&&(c=n),w(a,De(c,3))}function S7(a,c){var p=Ye(a)?Pi:l_;return p(a,De(c,3))}var E7=I_(rS),C7=I_(oS);function $7(a,c){return pn(Af(a,c),1)}function k7(a,c){return pn(Af(a,c),ie)}function R7(a,c,p){return p=p===n?1:qe(p),pn(Af(a,c),p)}function uS(a,c){var p=Ye(a)?kr:Ni;return p(a,De(c,3))}function dS(a,c){var p=Ye(a)?YO:a_;return p(a,De(c,3))}var T7=_f(function(a,c,p){yt.call(a,p)?a[p].push(c):qo(a,p,[c])});function P7(a,c,p,w){a=Hn(a)?a:Xa(a),p=p&&!w?qe(p):0;var $=a.length;return p<0&&(p=tn($+p,0)),If(a)?p<=$&&a.indexOf(c,p)>-1:!!$&&La(a,c,p)>-1}var A7=et(function(a,c,p){var w=-1,$=typeof c=="function",T=Hn(a)?q(a.length):[];return Ni(a,function(N){T[++w]=$?or(c,N,p):zc(N,c,p)}),T}),O7=_f(function(a,c,p){qo(a,p,c)});function Af(a,c){var p=Ye(a)?Mt:h_;return p(a,De(c,3))}function M7(a,c,p,w){return a==null?[]:(Ye(c)||(c=c==null?[]:[c]),p=w?n:p,Ye(p)||(p=p==null?[]:[p]),y_(a,c,p))}var N7=_f(function(a,c,p){a[p?0:1].push(c)},function(){return[[],[]]});function D7(a,c,p){var w=Ye(a)?Og:Ub,$=arguments.length<3;return w(a,De(c,4),p,$,Ni)}function I7(a,c,p){var w=Ye(a)?GO:Ub,$=arguments.length<3;return w(a,De(c,4),p,$,a_)}function L7(a,c){var p=Ye(a)?Pi:l_;return p(a,Nf(De(c,3)))}function F7(a){var c=Ye(a)?r_:PM;return c(a)}function j7(a,c,p){(p?Mn(a,c,p):c===n)?c=1:c=qe(c);var w=Ye(a)?aM:AM;return w(a,c)}function z7(a){var c=Ye(a)?lM:MM;return c(a)}function B7(a){if(a==null)return 0;if(Hn(a))return If(a)?ja(a):a.length;var c=Sn(a);return c==ct||c==Z?a.size:qg(a).length}function U7(a,c,p){var w=Ye(a)?Mg:NM;return p&&Mn(a,c,p)&&(c=n),w(a,De(c,3))}var V7=et(function(a,c){if(a==null)return[];var p=c.length;return p>1&&Mn(a,c[0],c[1])?c=[]:p>2&&Mn(c[0],c[1],c[2])&&(c=[c[0]]),y_(a,pn(c,1),[])}),Of=S6||function(){return fn.Date.now()};function W7(a,c){if(typeof c!="function")throw new Rr(s);return a=qe(a),function(){if(--a<1)return c.apply(this,arguments)}}function fS(a,c,p){return c=p?n:c,c=a&&c==null?a.length:c,Qo(a,A,n,n,n,n,c)}function pS(a,c){var p;if(typeof c!="function")throw new Rr(s);return a=qe(a),function(){return--a>0&&(p=c.apply(this,arguments)),a<=1&&(c=n),p}}var bv=et(function(a,c,p){var w=C;if(p.length){var $=Oi(p,Ya(bv));w|=P}return Qo(a,w,c,p,$)}),hS=et(function(a,c,p){var w=C|S;if(p.length){var $=Oi(p,Ya(hS));w|=P}return Qo(c,w,a,p,$)});function mS(a,c,p){c=p?n:c;var w=Qo(a,E,n,n,n,n,n,c);return w.placeholder=mS.placeholder,w}function gS(a,c,p){c=p?n:c;var w=Qo(a,k,n,n,n,n,n,c);return w.placeholder=gS.placeholder,w}function vS(a,c,p){var w,$,T,N,D,B,ne=0,re=!1,se=!1,me=!0;if(typeof a!="function")throw new Rr(s);c=Mr(c)||0,It(p)&&(re=!!p.leading,se="maxWait"in p,T=se?tn(Mr(p.maxWait)||0,c):T,me="trailing"in p?!!p.trailing:me);function Re(Xt){var no=w,ri=$;return w=$=n,ne=Xt,N=a.apply(ri,no),N}function Ie(Xt){return ne=Xt,D=Hc(nt,c),re?Re(Xt):N}function Qe(Xt){var no=Xt-B,ri=Xt-ne,IS=c-no;return se?_n(IS,T-ri):IS}function Le(Xt){var no=Xt-B,ri=Xt-ne;return B===n||no>=c||no<0||se&&ri>=T}function nt(){var Xt=Of();if(Le(Xt))return at(Xt);D=Hc(nt,Qe(Xt))}function at(Xt){return D=n,me&&w?Re(Xt):(w=$=n,N)}function lr(){D!==n&&k_(D),ne=0,w=B=$=D=n}function Nn(){return D===n?N:at(Of())}function cr(){var Xt=Of(),no=Le(Xt);if(w=arguments,$=this,B=Xt,no){if(D===n)return Ie(B);if(se)return k_(D),D=Hc(nt,c),Re(B)}return D===n&&(D=Hc(nt,c)),N}return cr.cancel=lr,cr.flush=Nn,cr}var H7=et(function(a,c){return s_(a,1,c)}),K7=et(function(a,c,p){return s_(a,Mr(c)||0,p)});function Y7(a){return Qo(a,F)}function Mf(a,c){if(typeof a!="function"||c!=null&&typeof c!="function")throw new Rr(s);var p=function(){var w=arguments,$=c?c.apply(this,w):w[0],T=p.cache;if(T.has($))return T.get($);var N=a.apply(this,w);return p.cache=T.set($,N)||T,N};return p.cache=new(Mf.Cache||Zo),p}Mf.Cache=Zo;function Nf(a){if(typeof a!="function")throw new Rr(s);return function(){var c=arguments;switch(c.length){case 0:return!a.call(this);case 1:return!a.call(this,c[0]);case 2:return!a.call(this,c[0],c[1]);case 3:return!a.call(this,c[0],c[1],c[2])}return!a.apply(this,c)}}function G7(a){return pS(2,a)}var X7=DM(function(a,c){c=c.length==1&&Ye(c[0])?Mt(c[0],ir(De())):Mt(pn(c,1),ir(De()));var p=c.length;return et(function(w){for(var $=-1,T=_n(w.length,p);++$=c}),Xs=d_(function(){return arguments}())?d_:function(a){return Bt(a)&&yt.call(a,"callee")&&!qb.call(a,"callee")},Ye=q.isArray,u4=Ob?ir(Ob):yM;function Hn(a){return a!=null&&Df(a.length)&&!ti(a)}function Gt(a){return Bt(a)&&Hn(a)}function d4(a){return a===!0||a===!1||Bt(a)&&On(a)==xe}var Fi=C6||Mv,f4=Mb?ir(Mb):wM;function p4(a){return Bt(a)&&a.nodeType===1&&!Kc(a)}function h4(a){if(a==null)return!0;if(Hn(a)&&(Ye(a)||typeof a=="string"||typeof a.splice=="function"||Fi(a)||Ga(a)||Xs(a)))return!a.length;var c=Sn(a);if(c==ct||c==Z)return!a.size;if(Wc(a))return!qg(a).length;for(var p in a)if(yt.call(a,p))return!1;return!0}function m4(a,c){return Bc(a,c)}function g4(a,c,p){p=typeof p=="function"?p:n;var w=p?p(a,c):n;return w===n?Bc(a,c,n,p):!!w}function Sv(a){if(!Bt(a))return!1;var c=On(a);return c==Oe||c==Ae||typeof a.message=="string"&&typeof a.name=="string"&&!Kc(a)}function v4(a){return typeof a=="number"&&Jb(a)}function ti(a){if(!It(a))return!1;var c=On(a);return c==je||c==Ot||c==fe||c==I}function wS(a){return typeof a=="number"&&a==qe(a)}function Df(a){return typeof a=="number"&&a>-1&&a%1==0&&a<=K}function It(a){var c=typeof a;return a!=null&&(c=="object"||c=="function")}function Bt(a){return a!=null&&typeof a=="object"}var xS=Nb?ir(Nb):bM;function y4(a,c){return a===c||Zg(a,c,pv(c))}function w4(a,c,p){return p=typeof p=="function"?p:n,Zg(a,c,pv(c),p)}function x4(a){return bS(a)&&a!=+a}function b4(a){if(oN(a))throw new Ke(i);return f_(a)}function _4(a){return a===null}function S4(a){return a==null}function bS(a){return typeof a=="number"||Bt(a)&&On(a)==Yt}function Kc(a){if(!Bt(a)||On(a)!=gt)return!1;var c=lf(a);if(c===null)return!0;var p=yt.call(c,"constructor")&&c.constructor;return typeof p=="function"&&p instanceof p&&rf.call(p)==w6}var Ev=Db?ir(Db):_M;function E4(a){return wS(a)&&a>=-K&&a<=K}var _S=Ib?ir(Ib):SM;function If(a){return typeof a=="string"||!Ye(a)&&Bt(a)&&On(a)==we}function ar(a){return typeof a=="symbol"||Bt(a)&&On(a)==he}var Ga=Lb?ir(Lb):EM;function C4(a){return a===n}function $4(a){return Bt(a)&&Sn(a)==ke}function k4(a){return Bt(a)&&On(a)==ft}var R4=$f(Qg),T4=$f(function(a,c){return a<=c});function SS(a){if(!a)return[];if(Hn(a))return If(a)?Jr(a):Wn(a);if(Mc&&a[Mc])return a6(a[Mc]());var c=Sn(a),p=c==ct?jg:c==Z?ef:Xa;return p(a)}function ni(a){if(!a)return a===0?a:0;if(a=Mr(a),a===ie||a===-ie){var c=a<0?-1:1;return c*Q}return a===a?a:0}function qe(a){var c=ni(a),p=c%1;return c===c?p?c-p:c:0}function ES(a){return a?Hs(qe(a),0,le):0}function Mr(a){if(typeof a=="number")return a;if(ar(a))return W;if(It(a)){var c=typeof a.valueOf=="function"?a.valueOf():a;a=It(c)?c+"":c}if(typeof a!="string")return a===0?a:+a;a=Vb(a);var p=uO.test(a);return p||fO.test(a)?WO(a.slice(2),p?2:8):cO.test(a)?W:+a}function CS(a){return Eo(a,Kn(a))}function P4(a){return a?Hs(qe(a),-K,K):a===0?a:0}function vt(a){return a==null?"":sr(a)}var A4=Ha(function(a,c){if(Wc(c)||Hn(c)){Eo(c,ln(c),a);return}for(var p in c)yt.call(c,p)&&Fc(a,p,c[p])}),$S=Ha(function(a,c){Eo(c,Kn(c),a)}),Lf=Ha(function(a,c,p,w){Eo(c,Kn(c),a,w)}),O4=Ha(function(a,c,p,w){Eo(c,ln(c),a,w)}),M4=Jo(Hg);function N4(a,c){var p=Wa(a);return c==null?p:o_(p,c)}var D4=et(function(a,c){a=_t(a);var p=-1,w=c.length,$=w>2?c[2]:n;for($&&Mn(c[0],c[1],$)&&(w=1);++p1),T}),Eo(a,dv(a),p),w&&(p=Pr(p,m|g|y,KM));for(var $=c.length;$--;)rv(p,c[$]);return p});function J4(a,c){return RS(a,Nf(De(c)))}var e8=Jo(function(a,c){return a==null?{}:kM(a,c)});function RS(a,c){if(a==null)return{};var p=Mt(dv(a),function(w){return[w]});return c=De(c),w_(a,p,function(w,$){return c(w,$[0])})}function t8(a,c,p){c=Ii(c,a);var w=-1,$=c.length;for($||($=1,a=n);++w<$;){var T=a==null?n:a[Co(c[w])];T===n&&(w=$,T=p),a=ti(T)?T.call(a):T}return a}function n8(a,c,p){return a==null?a:Uc(a,c,p)}function r8(a,c,p,w){return w=typeof w=="function"?w:n,a==null?a:Uc(a,c,p,w)}var TS=B_(ln),PS=B_(Kn);function o8(a,c,p){var w=Ye(a),$=w||Fi(a)||Ga(a);if(c=De(c,4),p==null){var T=a&&a.constructor;$?p=w?new T:[]:It(a)?p=ti(T)?Wa(lf(a)):{}:p={}}return($?kr:So)(a,function(N,D,B){return c(p,N,D,B)}),p}function i8(a,c){return a==null?!0:rv(a,c)}function s8(a,c,p){return a==null?a:E_(a,c,sv(p))}function a8(a,c,p,w){return w=typeof w=="function"?w:n,a==null?a:E_(a,c,sv(p),w)}function Xa(a){return a==null?[]:Fg(a,ln(a))}function l8(a){return a==null?[]:Fg(a,Kn(a))}function c8(a,c,p){return p===n&&(p=c,c=n),p!==n&&(p=Mr(p),p=p===p?p:0),c!==n&&(c=Mr(c),c=c===c?c:0),Hs(Mr(a),c,p)}function u8(a,c,p){return c=ni(c),p===n?(p=c,c=0):p=ni(p),a=Mr(a),gM(a,c,p)}function d8(a,c,p){if(p&&typeof p!="boolean"&&Mn(a,c,p)&&(c=p=n),p===n&&(typeof c=="boolean"?(p=c,c=n):typeof a=="boolean"&&(p=a,a=n)),a===n&&c===n?(a=0,c=1):(a=ni(a),c===n?(c=a,a=0):c=ni(c)),a>c){var w=a;a=c,c=w}if(p||a%1||c%1){var $=e_();return _n(a+$*(c-a+VO("1e-"+(($+"").length-1))),c)}return ev(a,c)}var f8=Ka(function(a,c,p){return c=c.toLowerCase(),a+(p?AS(c):c)});function AS(a){return kv(vt(a).toLowerCase())}function OS(a){return a=vt(a),a&&a.replace(hO,n6).replace(MO,"")}function p8(a,c,p){a=vt(a),c=sr(c);var w=a.length;p=p===n?w:Hs(qe(p),0,w);var $=p;return p-=c.length,p>=0&&a.slice(p,$)==c}function h8(a){return a=vt(a),a&&xg.test(a)?a.replace(Rc,r6):a}function m8(a){return a=vt(a),a&&Ge.test(a)?a.replace(H,"\\$&"):a}var g8=Ka(function(a,c,p){return a+(p?"-":"")+c.toLowerCase()}),v8=Ka(function(a,c,p){return a+(p?" ":"")+c.toLowerCase()}),y8=D_("toLowerCase");function w8(a,c,p){a=vt(a),c=qe(c);var w=c?ja(a):0;if(!c||w>=c)return a;var $=(c-w)/2;return Cf(ff($),p)+a+Cf(df($),p)}function x8(a,c,p){a=vt(a),c=qe(c);var w=c?ja(a):0;return c&&w>>0,p?(a=vt(a),a&&(typeof c=="string"||c!=null&&!Ev(c))&&(c=sr(c),!c&&Fa(a))?Li(Jr(a),0,p):a.split(c,p)):[]}var k8=Ka(function(a,c,p){return a+(p?" ":"")+kv(c)});function R8(a,c,p){return a=vt(a),p=p==null?0:Hs(qe(p),0,a.length),c=sr(c),a.slice(p,p+c.length)==c}function T8(a,c,p){var w=R.templateSettings;p&&Mn(a,c,p)&&(c=n),a=vt(a),c=Lf({},c,w,U_);var $=Lf({},c.imports,w.imports,U_),T=ln($),N=Fg($,T),D,B,ne=0,re=c.interpolate||Xd,se="__p += '",me=zg((c.escape||Xd).source+"|"+re.source+"|"+(re===Ac?lO:Xd).source+"|"+(c.evaluate||Xd).source+"|$","g"),Re="//# sourceURL="+(yt.call(c,"sourceURL")?(c.sourceURL+"").replace(/\s/g," "):"lodash.templateSources["+ ++FO+"]")+` +`;a.replace(me,function(Le,nt,at,lr,Nn,cr){return at||(at=lr),se+=a.slice(ne,cr).replace(mO,o6),nt&&(D=!0,se+=`' + +__e(`+nt+`) + +'`),Nn&&(B=!0,se+=`'; +`+Nn+`; +__p += '`),at&&(se+=`' + +((__t = (`+at+`)) == null ? '' : __t) + +'`),ne=cr+Le.length,Le}),se+=`'; +`;var Ie=yt.call(c,"variable")&&c.variable;if(!Ie)se=`with (obj) { +`+se+` +} +`;else if(sO.test(Ie))throw new Ke(l);se=(B?se.replace(yg,""):se).replace(wg,"$1").replace(Kd,"$1;"),se="function("+(Ie||"obj")+`) { +`+(Ie?"":`obj || (obj = {}); +`)+"var __t, __p = ''"+(D?", __e = _.escape":"")+(B?`, __j = Array.prototype.join; +function print() { __p += __j.call(arguments, '') } +`:`; +`)+se+`return __p +}`;var Qe=NS(function(){return ht(T,Re+"return "+se).apply(n,N)});if(Qe.source=se,Sv(Qe))throw Qe;return Qe}function P8(a){return vt(a).toLowerCase()}function A8(a){return vt(a).toUpperCase()}function O8(a,c,p){if(a=vt(a),a&&(p||c===n))return Vb(a);if(!a||!(c=sr(c)))return a;var w=Jr(a),$=Jr(c),T=Wb(w,$),N=Hb(w,$)+1;return Li(w,T,N).join("")}function M8(a,c,p){if(a=vt(a),a&&(p||c===n))return a.slice(0,Yb(a)+1);if(!a||!(c=sr(c)))return a;var w=Jr(a),$=Hb(w,Jr(c))+1;return Li(w,0,$).join("")}function N8(a,c,p){if(a=vt(a),a&&(p||c===n))return a.replace(st,"");if(!a||!(c=sr(c)))return a;var w=Jr(a),$=Wb(w,Jr(c));return Li(w,$).join("")}function D8(a,c){var p=V,w=J;if(It(c)){var $="separator"in c?c.separator:$;p="length"in c?qe(c.length):p,w="omission"in c?sr(c.omission):w}a=vt(a);var T=a.length;if(Fa(a)){var N=Jr(a);T=N.length}if(p>=T)return a;var D=p-ja(w);if(D<1)return w;var B=N?Li(N,0,D).join(""):a.slice(0,D);if($===n)return B+w;if(N&&(D+=B.length-D),Ev($)){if(a.slice(D).search($)){var ne,re=B;for($.global||($=zg($.source,vt(db.exec($))+"g")),$.lastIndex=0;ne=$.exec(re);)var se=ne.index;B=B.slice(0,se===n?D:se)}}else if(a.indexOf(sr($),D)!=D){var me=B.lastIndexOf($);me>-1&&(B=B.slice(0,me))}return B+w}function I8(a){return a=vt(a),a&&Tc.test(a)?a.replace(kc,d6):a}var L8=Ka(function(a,c,p){return a+(p?" ":"")+c.toUpperCase()}),kv=D_("toUpperCase");function MS(a,c,p){return a=vt(a),c=p?n:c,c===n?s6(a)?h6(a):qO(a):a.match(c)||[]}var NS=et(function(a,c){try{return or(a,n,c)}catch(p){return Sv(p)?p:new Ke(p)}}),F8=Jo(function(a,c){return kr(c,function(p){p=Co(p),qo(a,p,bv(a[p],a))}),a});function j8(a){var c=a==null?0:a.length,p=De();return a=c?Mt(a,function(w){if(typeof w[1]!="function")throw new Rr(s);return[p(w[0]),w[1]]}):[],et(function(w){for(var $=-1;++$K)return[];var p=le,w=_n(a,le);c=De(c),a-=le;for(var $=Lg(w,c);++p0||c<0)?new ot(p):(a<0?p=p.takeRight(-a):a&&(p=p.drop(a)),c!==n&&(c=qe(c),p=c<0?p.dropRight(-c):p.take(c-a)),p)},ot.prototype.takeRightWhile=function(a){return this.reverse().takeWhile(a).reverse()},ot.prototype.toArray=function(){return this.take(le)},So(ot.prototype,function(a,c){var p=/^(?:filter|find|map|reject)|While$/.test(c),w=/^(?:head|last)$/.test(c),$=R[w?"take"+(c=="last"?"Right":""):c],T=w||/^find/.test(c);$&&(R.prototype[c]=function(){var N=this.__wrapped__,D=w?[1]:arguments,B=N instanceof ot,ne=D[0],re=B||Ye(N),se=function(nt){var at=$.apply(R,Ai([nt],D));return w&&me?at[0]:at};re&&p&&typeof ne=="function"&&ne.length!=1&&(B=re=!1);var me=this.__chain__,Re=!!this.__actions__.length,Ie=T&&!me,Qe=B&&!Re;if(!T&&re){N=Qe?N:new ot(this);var Le=a.apply(N,D);return Le.__actions__.push({func:Pf,args:[se],thisArg:n}),new Tr(Le,me)}return Ie&&Qe?a.apply(this,D):(Le=this.thru(se),Ie?w?Le.value()[0]:Le.value():Le)})}),kr(["pop","push","shift","sort","splice","unshift"],function(a){var c=tf[a],p=/^(?:push|sort|unshift)$/.test(a)?"tap":"thru",w=/^(?:pop|shift)$/.test(a);R.prototype[a]=function(){var $=arguments;if(w&&!this.__chain__){var T=this.value();return c.apply(Ye(T)?T:[],$)}return this[p](function(N){return c.apply(Ye(N)?N:[],$)})}}),So(ot.prototype,function(a,c){var p=R[c];if(p){var w=p.name+"";yt.call(Va,w)||(Va[w]=[]),Va[w].push({name:c,func:p})}}),Va[Sf(n,S).name]=[{name:"wrapper",func:n}],ot.prototype.clone=I6,ot.prototype.reverse=L6,ot.prototype.value=F6,R.prototype.at=p7,R.prototype.chain=h7,R.prototype.commit=m7,R.prototype.next=g7,R.prototype.plant=y7,R.prototype.reverse=w7,R.prototype.toJSON=R.prototype.valueOf=R.prototype.value=x7,R.prototype.first=R.prototype.head,Mc&&(R.prototype[Mc]=v7),R},za=m6();Bs?((Bs.exports=za)._=za,Tg._=za):fn._=za}).call(Yc)})(Lh,Lh.exports);var xH=Lh.exports;const bH=lm(xH);function Vr({width:e,height:t}){return e/t}function Fh(e,t=0){const n=10**t;return Math.round((e+Number.EPSILON)*n)/n}function _H(e){return(t,n)=>e(n)-e(t)}class SH{constructor(t){this.comparator=t,this.heap=[],this.n=0}greater(t,n){return this.comparator(this.heap[t],this.heap[n])<0}swap(t,n){const r=this.heap[t];this.heap[t]=this.heap[n],this.heap[n]=r}swim(t){let n=t,r=Math.floor(n/2);for(;n>1&&this.greater(r,n);)this.swap(r,n),n=r,r=Math.floor(n/2)}sink(t){let n=t,r=n*2;for(;r<=this.n&&(rl.weight));for(s.push({id:t,weight:0});s.size()>0;){const{id:l,weight:u}=s.pop();if(!o.has(l)){const d=e(l);o.add(l),d.forEach((h,m)=>{const g=u+h,y=r.get(m),x=i.get(m);(x===void 0||x>g&&(x/g>1.005||y!==void 0&&yMath.min(Vr(i),o),Number.MAX_VALUE);return Fh(n/t/r)+2}function MP(e,t,n,r){const o=t-(e.length-1)*n-2*r*e.length,i=e.reduce((s,l)=>s+Vr(l),0);return o/i}function RH(e,t,n,r,o,i,s){const l=e.slice(t,n),u=MP(l,r,i,s);return u>0?(u-o)**2*l.length:void 0}function TH({photos:e,layoutOptions:t,targetRowHeight:n,limitNodeSearch:r,rowConstraints:o}){return i=>{var s,l;const{containerWidth:u,spacing:d,padding:h}=t,m=new Map;m.set(i,0);const g=(s=o==null?void 0:o.minPhotos)!=null?s:1,y=Math.min(r,(l=o==null?void 0:o.maxPhotos)!=null?l:1/0);for(let x=i+g;xy);x+=1){const _=RH(e,i,x,u,n,d,h);if(_===void 0)break;m.set(x,_)}return m}}function PH({photos:e,layoutOptions:t}){const{spacing:n,padding:r,containerWidth:o,targetRowHeight:i,rowConstraints:s}=t,l=kH({photos:e,containerWidth:o,targetRowHeight:i}),u=TH({photos:e,layoutOptions:t,targetRowHeight:i,limitNodeSearch:l,rowConstraints:s}),d=$H(u,0,e.length);if(d===void 0)return;const h=[];for(let m=1;m({photo:x,index:_})).slice(d[m-1],d[m]),y=MP(g.map(({photo:x})=>x),o,n,r);h.push(g.map(({photo:x,index:_},C)=>({photo:x,layout:{height:y,width:y*Vr(x),index:_,photoIndex:C,photosCount:g.length}})))}return h}function qm(...e){return[...e].filter(t=>!!t).join(" ")}function NP(e,{width:t,photosCount:n},{spacing:r,padding:o,containerWidth:i}){const s=r*(n-1)+2*o*n;return`calc((${e} - ${s}px) / ${Fh((i-s)/t,5)})`}function AH(e,t){return t.layout!=="rows"?`calc(100% - ${2*t.padding}px)`:NP("100%",e,t)}function i2(e,t,n){var r,o;return NP((o=(r=e.match(/calc\((.*)\)/))==null?void 0:r[1])!=null?o:e,t,n)}function OH(e,t,n){let r,o;const i=e.srcSet||e.images;return i&&i.length>0&&(r=i.concat(i.find(({width:s})=>s===e.width)?[]:[{src:e.src,width:e.width,height:e.height}]).sort((s,l)=>s.width-l.width).map(s=>`${s.src} ${s.width}w`).join(", ")),n.sizes?o=(n.sizes.sizes||[]).map(({viewport:s,size:l})=>`${s} ${i2(l,t,n)}`).concat(i2(n.sizes.size,t,n)).join(", "):r&&(o=`${Math.ceil(t.width/n.containerWidth*100)}vw`),{srcSet:r,sizes:o}}function Ox(e){var t,n;const{photo:r,layout:o,layoutOptions:i,imageProps:{style:s,className:l,...u}={},renderPhoto:d}=e,{onClick:h}=i,m={display:"block",boxSizing:"content-box",width:AH(o,i),height:"auto",aspectRatio:`${r.width} / ${r.height}`,...i.padding?{padding:`${i.padding}px`}:null,...(i.layout==="columns"||i.layout==="masonry")&&o.photoIndex{h({event:C,photo:r,index:o.index})}:void 0,y={src:r.src,alt:(t=r.alt)!=null?t:"",title:r.title,onClick:g,style:m,className:qm("react-photo-album--photo",l),loading:"lazy",decoding:"async",...OH(r,o,i),...u},x=C=>{const{src:S,alt:b,srcSet:E,sizes:k,style:P,...M}=y;return f.createElement("img",{alt:b,...E?{srcSet:E,sizes:k}:null,src:S,style:C!=null&&C.wrapped?{display:"block",width:"100%",height:"100%"}:P,...M})},_=(({display:C,boxSizing:S,width:b,aspectRatio:E,padding:k,marginBottom:P,cursor:M})=>({display:C,boxSizing:S,width:b,aspectRatio:E,padding:k,marginBottom:P,cursor:M}))(m);return f.createElement(f.Fragment,null,(n=d==null?void 0:d({photo:r,layout:o,layoutOptions:i,imageProps:y,renderDefaultPhoto:x,wrapperStyle:_}))!=null?n:x())}function MH({rowContainerProps:e,children:t}){return f.createElement("div",{...e},t)}function NH(e){const{layoutOptions:t,rowIndex:n,rowsCount:r,renderRowContainer:o,rowContainerProps:{style:i,className:s,...l}={},children:u}=e,d={className:qm("react-photo-album--row",s),style:{display:"flex",flexDirection:"row",flexWrap:"nowrap",alignItems:"flex-start",justifyContent:"space-between",...nf.createElement(NH,{key:`row-${d}`,layoutOptions:n,rowIndex:d,rowsCount:l.length,renderRowContainer:o,rowContainerProps:s},u.map(({photo:h,layout:m})=>f.createElement(Ox,{key:h.key||h.src,photo:h,layout:m,layoutOptions:n,renderPhoto:r,imageProps:i}))))):null}function IH(e,t,n,r){const o=new Map,i=new Set;i.add(n);for(let s=0;s{const d=s>0?o.get(u)[s].weight:0;e(u).forEach(({neighbor:h,weight:m})=>{let g=o.get(h);g||(g=[],o.set(h,g));const y=d+m,x=g[s+1];(!x||x.weight>y&&(x.weight/y>1.0001||u0;i-=1)o=e.get(o)[i].node,r.push(o);return r.reverse()}function FH(e,t,n,r){return LH(IH(e,t,n,r),t,r)}function jH({photos:e,spacing:t,padding:n,targetColumnWidth:r,targetColumnHeight:o}){return i=>{const s=[],l=o*1.5;let u=r/Vr(e[i])+2*n;for(let d=i+1;dl||d===e.length));d+=1)u+=r/Vr(e[d])+t+2*n;return s}}function s2({path:e,photos:t,containerWidth:n,columnsGaps:r,columnsRatios:o,spacing:i,padding:s}){const l=[],u=o.reduce((d,h)=>d+h,0);for(let d=0;d({photo:y,index:x})).slice(e[d],e[d+1]),m=o.reduce((y,x,_)=>y+(r[d]-r[_])*x,0),g=(n-(e.length-2)*i-2*(e.length-1)*s-m)*o[d]/u;l.push(h.map(({photo:y,index:x},_)=>({photo:y,layout:{width:g,height:g/Vr(y),index:x,photoIndex:_,photosCount:h.length}})))}return l}function zH({photos:e,layoutOptions:t,targetColumnWidth:n}){const{columns:r,spacing:o,padding:i,containerWidth:s}=t,l=[],u=[];if(e.length<=r){const y=e.length>0?e.reduce((_,C)=>_+Vr(C),0)/e.length:1;for(let _=0;_Math.min(C,e.length)),photos:e,columnsRatios:u,columnsGaps:l,containerWidth:s,spacing:o,padding:i});return{columnsGaps:l,columnsRatios:u,columnsModel:x}}const d=(e.reduce((y,x)=>y+n/Vr(x),0)+o*(e.length-r)+2*i*e.length)/r,h=jH({photos:e,targetColumnWidth:n,targetColumnHeight:d,spacing:o,padding:i}),m=FH(h,r,0,e.length);for(let y=0;y_+1/Vr(C),0)}const g=s2({path:m,photos:e,columnsRatios:u,columnsGaps:l,containerWidth:s,spacing:o,padding:i});return{columnsGaps:l,columnsRatios:u,columnsModel:g}}function DP(e){const{photos:t,layoutOptions:n}=e,{columns:r,spacing:o,padding:i,containerWidth:s}=n,l=(s-o*(r-1)-2*i*r)/r,{columnsGaps:u,columnsRatios:d,columnsModel:h}=zH({photos:t,layoutOptions:n,targetColumnWidth:l});return h.findIndex(m=>m.findIndex(({layout:{width:g,height:y}})=>g<0||y<0)>=0)>=0?r>1?DP({photos:t,layoutOptions:{...n,columns:r-1}}):void 0:{columnsModel:h,columnsGaps:u,columnsRatios:d}}function BH({photos:e,layoutOptions:t}){return DP({photos:e,layoutOptions:t})}function UH({columnContainerProps:e,children:t}){return f.createElement("div",{...e},t)}function VH(e){const{layoutOptions:t,columnIndex:n,columnsCount:r,columnsGaps:o,columnsRatios:i}=e,{layout:s,spacing:l,padding:u}=t;if(s==="masonry"||!o||!i)return`calc((100% - ${l*(r-1)}px) / ${r})`;const d=i.reduce((m,g)=>m+g,0),h=i.reduce((m,g,y)=>m+(o[n]-o[y])*g,0);return`calc((100% - ${Fh((r-1)*l+2*r*u+h,3)}px) * ${Fh(i[n]/d,5)} + ${2*u}px)`}function IP(e){const{layoutOptions:t,renderColumnContainer:n,children:r,columnContainerProps:{style:o,className:i,...s}={},...l}=e,u={className:qm("react-photo-album--column",i),style:{display:"flex",flexDirection:"column",flexWrap:"nowrap",alignItems:"flex-start",width:VH(e),justifyContent:t.layout==="columns"?"space-between":"flex-start",...o},...s};return f.createElement(f.Fragment,null,(n??UH)({layoutOptions:t,columnContainerProps:u,children:r,...l}))}function WH(e){const{photos:t,layoutOptions:n,renderPhoto:r,renderColumnContainer:o,componentsProps:{imageProps:i,columnContainerProps:s}}=e,l=BH({photos:t,layoutOptions:n});if(!l)return null;const{columnsModel:u,columnsRatios:d,columnsGaps:h}=l;return f.createElement(f.Fragment,null,u.map((m,g)=>f.createElement(IP,{key:`column-${g}`,layoutOptions:n,columnIndex:g,columnsCount:u.length,columnsGaps:h,columnsRatios:d,renderColumnContainer:o,columnContainerProps:s},m.map(({photo:y,layout:x})=>f.createElement(Ox,{key:y.key||y.src,photo:y,layout:x,layoutOptions:n,renderPhoto:r,imageProps:i})))))}function LP(e){const{photos:t,layoutOptions:n}=e,{columns:r,spacing:o,padding:i,containerWidth:s}=n,l=(s-o*(r-1)-2*i*r)/r;if(l<=0)return r>1?LP({...e,layoutOptions:{...n,columns:r-1}}):void 0;const u=[];for(let h=0;h{const y=u.reduce((x,_,C)=>_[])).map(h=>h.map(({photo:m,index:g},y)=>({photo:m,layout:{width:l,height:l/Vr(m),index:g,photoIndex:y,photosCount:h.length}})))}function HH(e){const{photos:t,layoutOptions:n,renderPhoto:r,renderColumnContainer:o,componentsProps:{imageProps:i,columnContainerProps:s}}=e,l=LP({photos:t,layoutOptions:n});return l?f.createElement(f.Fragment,null,l.map((u,d)=>f.createElement(IP,{key:`masonry-column-${d}`,layoutOptions:n,columnsCount:l.length,columnIndex:d,renderColumnContainer:o,columnContainerProps:s},u.map(({photo:h,layout:m})=>f.createElement(Ox,{key:h.key||h.src,photo:h,layout:m,layoutOptions:n,renderPhoto:r,imageProps:i}))))):null}function KH({containerProps:e,children:t,containerRef:n}){return f.createElement("div",{ref:n,...e},t)}function YH(e){const{layout:t,renderContainer:n,children:r,containerRef:o,containerProps:{style:i,className:s,...l}={}}=e,u={className:qm("react-photo-album",`react-photo-album--${t}`,s),style:{display:"flex",flexWrap:"nowrap",justifyContent:"space-between",flexDirection:t==="rows"?"column":"row",...i},...l};return f.createElement(f.Fragment,null,(n??KH)({containerProps:u,containerRef:o,layout:t,children:r}))}function GH(e){const t=f.useRef(e);return(!e||!t.current||e.join()!==t.current.join())&&(t.current=e),t.current}function XH(e,{newContainerWidth:t,newScrollbarWidth:n}){const{containerWidth:r,scrollbarWidth:o}=e;return r!==void 0&&o!==void 0&&t!==void 0&&n!==void 0&&t>r&&t-r<=20&&n0){const r=[...t.filter(i=>i>0)].sort((i,s)=>s-i);r.push(Math.floor(r[r.length-1]/2));const o=n;n=r.find((i,s)=>i<=o||s===r.length-1)}return n}function qH(e,t){const[{containerWidth:n},r]=f.useReducer(XH,{containerWidth:t}),o=f.useRef(null),i=f.useRef();return{containerRef:f.useCallback(l=>{var u;(u=i.current)==null||u.disconnect(),i.current=void 0,o.current=l;const d=()=>r({newContainerWidth:ZH(o.current,e),newScrollbarWidth:window.innerWidth-document.documentElement.clientWidth});d(),l&&typeof ResizeObserver<"u"&&(i.current=new ResizeObserver(d),i.current.observe(l))},[e]),containerWidth:n}}const QH=Object.freeze([1200,600,300,0]);function Mx(e,t){return typeof e=="function"?e(t):e}function FP(e,t){return typeof e<"u"?Mx(e,t):void 0}function JH(e,t){const n=QH.findIndex(r=>r<=t);return Mx(e[n>=0?n:0],t)}function fp(e,t,n,r=0){const o=FP(e,t);return Math.round(Math.max(o===void 0?JH(n,t):o,r))}function eK({layout:e,onClick:t,containerWidth:n,targetRowHeight:r,rowConstraints:o,columns:i,spacing:s,padding:l,sizes:u}){return{layout:e,onClick:t,containerWidth:n,columns:fp(i,n,[5,4,3,2],1),spacing:fp(s,n,[20,15,10,5]),padding:fp(l,n,[0,0,0,0,0]),targetRowHeight:fp(r,n,[d=>d/5,d=>d/4,d=>d/3,d=>d/2]),rowConstraints:FP(o,n),sizes:u}}function tK(e,t,n){const{photos:r,componentsProps:o}=e,i=Mx(o,t)||{};if(n){const{layout:s,spacing:l,padding:u,rowConstraints:d}=n;if(s==="rows"){const{singleRowMaxHeight:h}=d||{};if(h){const m=Math.floor(r.reduce((g,{width:y,height:x})=>g+y/x*h-2*u,u*r.length*2+l*(r.length-1)));m>0&&(i.containerProps=i.containerProps||{},i.containerProps.style={maxWidth:m,...i.containerProps.style})}}}return i}function nK(e,t,n){const{photos:r,layout:o,renderPhoto:i,renderRowContainer:s,renderColumnContainer:l}=e,u={photos:r,renderPhoto:i,componentsProps:t};return o==="rows"?f.createElement(DH,{layoutOptions:n,renderRowContainer:s,...u}):o==="columns"?f.createElement(WH,{layoutOptions:n,renderColumnContainer:l,...u}):f.createElement(HH,{layoutOptions:n,renderColumnContainer:l,...u})}function rK(e){const{photos:t,layout:n,renderContainer:r,defaultContainerWidth:o,breakpoints:i}=e,{containerRef:s,containerWidth:l}=qH(GH(i),o);if(!n||!["rows","columns","masonry"].includes(n)||!Array.isArray(t))return null;const u=l?eK({containerWidth:l,...e}):void 0,d=tK(e,l,u);return f.createElement(YH,{layout:n,containerRef:s,renderContainer:r,containerProps:d.containerProps},u&&nK(e,d,u))}function oK({title:e,titleId:t,...n},r){return f.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true",ref:r,"aria-labelledby":t},n),e?f.createElement("title",{id:t},e):null,f.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3 4.5h14.25M3 9h9.75M3 13.5h9.75m4.5-4.5v12m0 0l-3.75-3.75M17.25 21L21 17.25"}))}const iK=f.forwardRef(oK),sK=iK;function aK({title:e,titleId:t,...n},r){return f.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true",ref:r,"aria-labelledby":t},n),e?f.createElement("title",{id:t},e):null,f.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3 4.5h14.25M3 9h9.75M3 13.5h5.25m5.25-.75L17.25 9m0 0L21 12.75M17.25 9v12"}))}const lK=f.forwardRef(aK),cK=lK;function uK({title:e,titleId:t,...n},r){return f.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true",ref:r,"aria-labelledby":t},n),e?f.createElement("title",{id:t},e):null,f.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15.042 21.672L13.684 16.6m0 0l-2.51 2.225.569-9.47 5.227 7.917-3.286-.672zM12 2.25V4.5m5.834.166l-1.591 1.591M20.25 10.5H18M7.757 14.743l-1.59 1.59M6 10.5H3.75m4.007-4.243l-1.59-1.59"}))}const dK=f.forwardRef(uK),fK=dK;function bi(e){return Array.isArray?Array.isArray(e):BP(e)==="[object Array]"}const pK=1/0;function hK(e){if(typeof e=="string")return e;let t=e+"";return t=="0"&&1/e==-pK?"-0":t}function mK(e){return e==null?"":hK(e)}function Lo(e){return typeof e=="string"}function jP(e){return typeof e=="number"}function gK(e){return e===!0||e===!1||vK(e)&&BP(e)=="[object Boolean]"}function zP(e){return typeof e=="object"}function vK(e){return zP(e)&&e!==null}function hr(e){return e!=null}function k0(e){return!e.trim().length}function BP(e){return e==null?e===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}const yK="Incorrect 'index' type",wK=e=>`Invalid value for key ${e}`,xK=e=>`Pattern length exceeds max of ${e}.`,bK=e=>`Missing ${e} property in key`,_K=e=>`Property 'weight' in key '${e}' must be a positive integer`,a2=Object.prototype.hasOwnProperty;class SK{constructor(t){this._keys=[],this._keyMap={};let n=0;t.forEach(r=>{let o=UP(r);this._keys.push(o),this._keyMap[o.id]=o,n+=o.weight}),this._keys.forEach(r=>{r.weight/=n})}get(t){return this._keyMap[t]}keys(){return this._keys}toJSON(){return JSON.stringify(this._keys)}}function UP(e){let t=null,n=null,r=null,o=1,i=null;if(Lo(e)||bi(e))r=e,t=l2(e),n=h1(e);else{if(!a2.call(e,"name"))throw new Error(bK("name"));const s=e.name;if(r=s,a2.call(e,"weight")&&(o=e.weight,o<=0))throw new Error(_K(s));t=l2(s),n=h1(s),i=e.getFn}return{path:t,id:n,weight:o,src:r,getFn:i}}function l2(e){return bi(e)?e:e.split(".")}function h1(e){return bi(e)?e.join("."):e}function EK(e,t){let n=[],r=!1;const o=(i,s,l)=>{if(hr(i))if(!s[l])n.push(i);else{let u=s[l];const d=i[u];if(!hr(d))return;if(l===s.length-1&&(Lo(d)||jP(d)||gK(d)))n.push(mK(d));else if(bi(d)){r=!0;for(let h=0,m=d.length;he.score===t.score?e.idx{this._keysMap[n.id]=r})}create(){this.isCreated||!this.docs.length||(this.isCreated=!0,Lo(this.docs[0])?this.docs.forEach((t,n)=>{this._addString(t,n)}):this.docs.forEach((t,n)=>{this._addObject(t,n)}),this.norm.clear())}add(t){const n=this.size();Lo(t)?this._addString(t,n):this._addObject(t,n)}removeAt(t){this.records.splice(t,1);for(let n=t,r=this.size();n{let s=o.getFn?o.getFn(t):this.getFn(t,o.path);if(hr(s)){if(bi(s)){let l=[];const u=[{nestedArrIndex:-1,value:s}];for(;u.length;){const{nestedArrIndex:d,value:h}=u.pop();if(hr(h))if(Lo(h)&&!k0(h)){let m={v:h,i:d,n:this.norm.get(h)};l.push(m)}else bi(h)&&h.forEach((m,g)=>{u.push({nestedArrIndex:g,value:m})})}r.$[i]=l}else if(Lo(s)&&!k0(s)){let l={v:s,n:this.norm.get(s)};r.$[i]=l}}}),this.records.push(r)}toJSON(){return{keys:this.keys,records:this.records}}}function VP(e,t,{getFn:n=He.getFn,fieldNormWeight:r=He.fieldNormWeight}={}){const o=new Nx({getFn:n,fieldNormWeight:r});return o.setKeys(e.map(UP)),o.setSources(t),o.create(),o}function AK(e,{getFn:t=He.getFn,fieldNormWeight:n=He.fieldNormWeight}={}){const{keys:r,records:o}=e,i=new Nx({getFn:t,fieldNormWeight:n});return i.setKeys(r),i.setIndexRecords(o),i}function pp(e,{errors:t=0,currentLocation:n=0,expectedLocation:r=0,distance:o=He.distance,ignoreLocation:i=He.ignoreLocation}={}){const s=t/e.length;if(i)return s;const l=Math.abs(r-n);return o?s+l/o:l?1:s}function OK(e=[],t=He.minMatchCharLength){let n=[],r=-1,o=-1,i=0;for(let s=e.length;i=t&&n.push([r,o]),r=-1)}return e[i-1]&&i-r>=t&&n.push([r,i-1]),n}const ea=32;function MK(e,t,n,{location:r=He.location,distance:o=He.distance,threshold:i=He.threshold,findAllMatches:s=He.findAllMatches,minMatchCharLength:l=He.minMatchCharLength,includeMatches:u=He.includeMatches,ignoreLocation:d=He.ignoreLocation}={}){if(t.length>ea)throw new Error(xK(ea));const h=t.length,m=e.length,g=Math.max(0,Math.min(r,m));let y=i,x=g;const _=l>1||u,C=_?Array(m):[];let S;for(;(S=e.indexOf(t,x))>-1;){let A=pp(t,{currentLocation:S,expectedLocation:g,distance:o,ignoreLocation:d});if(y=Math.min(A,y),x=S+h,_){let O=0;for(;O=V;U-=1){let te=U-1,L=n[e.charAt(te)];if(_&&(C[te]=+!!L),G[U]=(G[U+1]<<1|1)&L,A&&(G[U]|=(b[U+1]|b[U])<<1|1|b[U+1]),G[U]&P&&(E=pp(t,{errors:A,currentLocation:te,expectedLocation:g,distance:o,ignoreLocation:d}),E<=y)){if(y=E,x=te,x<=g)break;V=Math.max(1,2*g-x)}}if(pp(t,{errors:A+1,currentLocation:g,expectedLocation:g,distance:o,ignoreLocation:d})>y)break;b=G}const M={isMatch:x>=0,score:Math.max(.001,E)};if(_){const A=OK(C,l);A.length?u&&(M.indices=A):M.isMatch=!1}return M}function NK(e){let t={};for(let n=0,r=e.length;n{this.chunks.push({pattern:g,alphabet:NK(g),startIndex:y})},m=this.pattern.length;if(m>ea){let g=0;const y=m%ea,x=m-y;for(;g{const{isMatch:S,score:b,indices:E}=MK(t,x,_,{location:o+C,distance:i,threshold:s,findAllMatches:l,minMatchCharLength:u,includeMatches:r,ignoreLocation:d});S&&(g=!0),m+=b,S&&E&&(h=[...h,...E])});let y={isMatch:g,score:g?m/this.chunks.length:1};return g&&r&&(y.indices=h),y}}class Ds{constructor(t){this.pattern=t}static isMultiMatch(t){return c2(t,this.multiRegex)}static isSingleMatch(t){return c2(t,this.singleRegex)}search(){}}function c2(e,t){const n=e.match(t);return n?n[1]:null}class DK extends Ds{constructor(t){super(t)}static get type(){return"exact"}static get multiRegex(){return/^="(.*)"$/}static get singleRegex(){return/^=(.*)$/}search(t){const n=t===this.pattern;return{isMatch:n,score:n?0:1,indices:[0,this.pattern.length-1]}}}class IK extends Ds{constructor(t){super(t)}static get type(){return"inverse-exact"}static get multiRegex(){return/^!"(.*)"$/}static get singleRegex(){return/^!(.*)$/}search(t){const r=t.indexOf(this.pattern)===-1;return{isMatch:r,score:r?0:1,indices:[0,t.length-1]}}}class LK extends Ds{constructor(t){super(t)}static get type(){return"prefix-exact"}static get multiRegex(){return/^\^"(.*)"$/}static get singleRegex(){return/^\^(.*)$/}search(t){const n=t.startsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[0,this.pattern.length-1]}}}class FK extends Ds{constructor(t){super(t)}static get type(){return"inverse-prefix-exact"}static get multiRegex(){return/^!\^"(.*)"$/}static get singleRegex(){return/^!\^(.*)$/}search(t){const n=!t.startsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[0,t.length-1]}}}class jK extends Ds{constructor(t){super(t)}static get type(){return"suffix-exact"}static get multiRegex(){return/^"(.*)"\$$/}static get singleRegex(){return/^(.*)\$$/}search(t){const n=t.endsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[t.length-this.pattern.length,t.length-1]}}}class zK extends Ds{constructor(t){super(t)}static get type(){return"inverse-suffix-exact"}static get multiRegex(){return/^!"(.*)"\$$/}static get singleRegex(){return/^!(.*)\$$/}search(t){const n=!t.endsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[0,t.length-1]}}}class HP extends Ds{constructor(t,{location:n=He.location,threshold:r=He.threshold,distance:o=He.distance,includeMatches:i=He.includeMatches,findAllMatches:s=He.findAllMatches,minMatchCharLength:l=He.minMatchCharLength,isCaseSensitive:u=He.isCaseSensitive,ignoreLocation:d=He.ignoreLocation}={}){super(t),this._bitapSearch=new WP(t,{location:n,threshold:r,distance:o,includeMatches:i,findAllMatches:s,minMatchCharLength:l,isCaseSensitive:u,ignoreLocation:d})}static get type(){return"fuzzy"}static get multiRegex(){return/^"(.*)"$/}static get singleRegex(){return/^(.*)$/}search(t){return this._bitapSearch.searchIn(t)}}class KP extends Ds{constructor(t){super(t)}static get type(){return"include"}static get multiRegex(){return/^'"(.*)"$/}static get singleRegex(){return/^'(.*)$/}search(t){let n=0,r;const o=[],i=this.pattern.length;for(;(r=t.indexOf(this.pattern,n))>-1;)n=r+i,o.push([r,n-1]);const s=!!o.length;return{isMatch:s,score:s?0:1,indices:o}}}const m1=[DK,KP,LK,FK,zK,jK,IK,HP],u2=m1.length,BK=/ +(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/,UK="|";function VK(e,t={}){return e.split(UK).map(n=>{let r=n.trim().split(BK).filter(i=>i&&!!i.trim()),o=[];for(let i=0,s=r.length;i!!(e[jh.AND]||e[jh.OR]),YK=e=>!!e[y1.PATH],GK=e=>!bi(e)&&zP(e)&&!w1(e),d2=e=>({[jh.AND]:Object.keys(e).map(t=>({[t]:e[t]}))});function YP(e,t,{auto:n=!0}={}){const r=o=>{let i=Object.keys(o);const s=YK(o);if(!s&&i.length>1&&!w1(o))return r(d2(o));if(GK(o)){const u=s?o[y1.PATH]:i[0],d=s?o[y1.PATTERN]:o[u];if(!Lo(d))throw new Error(wK(u));const h={keyId:h1(u),pattern:d};return n&&(h.searcher=v1(d,t)),h}let l={children:[],operator:i[0]};return i.forEach(u=>{const d=o[u];bi(d)&&d.forEach(h=>{l.children.push(r(h))})}),l};return w1(e)||(e=d2(e)),r(e)}function XK(e,{ignoreFieldNorm:t=He.ignoreFieldNorm}){e.forEach(n=>{let r=1;n.matches.forEach(({key:o,norm:i,score:s})=>{const l=o?o.weight:null;r*=Math.pow(s===0&&l?Number.EPSILON:s,(l||1)*(t?1:i))}),n.score=r})}function ZK(e,t){const n=e.matches;t.matches=[],hr(n)&&n.forEach(r=>{if(!hr(r.indices)||!r.indices.length)return;const{indices:o,value:i}=r;let s={indices:o,value:i};r.key&&(s.key=r.key.src),r.idx>-1&&(s.refIndex=r.idx),t.matches.push(s)})}function qK(e,t){t.score=e.score}function QK(e,t,{includeMatches:n=He.includeMatches,includeScore:r=He.includeScore}={}){const o=[];return n&&o.push(ZK),r&&o.push(qK),e.map(i=>{const{idx:s}=i,l={item:t[s],refIndex:s};return o.length&&o.forEach(u=>{u(i,l)}),l})}class _c{constructor(t,n={},r){this.options={...He,...n},this.options.useExtendedSearch,this._keyStore=new SK(this.options.keys),this.setCollection(t,r)}setCollection(t,n){if(this._docs=t,n&&!(n instanceof Nx))throw new Error(yK);this._myIndex=n||VP(this.options.keys,this._docs,{getFn:this.options.getFn,fieldNormWeight:this.options.fieldNormWeight})}add(t){hr(t)&&(this._docs.push(t),this._myIndex.add(t))}remove(t=()=>!1){const n=[];for(let r=0,o=this._docs.length;r-1&&(u=u.slice(0,n)),QK(u,this._docs,{includeMatches:r,includeScore:o})}_searchStringList(t){const n=v1(t,this.options),{records:r}=this._myIndex,o=[];return r.forEach(({v:i,i:s,n:l})=>{if(!hr(i))return;const{isMatch:u,score:d,indices:h}=n.searchIn(i);u&&o.push({item:i,idx:s,matches:[{score:d,value:i,norm:l,indices:h}]})}),o}_searchLogical(t){const n=YP(t,this.options),r=(l,u,d)=>{if(!l.children){const{keyId:m,searcher:g}=l,y=this._findMatches({key:this._keyStore.get(m),value:this._myIndex.getValueForItemAtKeyId(u,m),searcher:g});return y&&y.length?[{idx:d,item:u,matches:y}]:[]}const h=[];for(let m=0,g=l.children.length;m{if(hr(l)){let d=r(n,l,u);d.length&&(i[u]||(i[u]={idx:u,item:l,matches:[]},s.push(i[u])),d.forEach(({matches:h})=>{i[u].matches.push(...h)}))}}),s}_searchObjectList(t){const n=v1(t,this.options),{keys:r,records:o}=this._myIndex,i=[];return o.forEach(({$:s,i:l})=>{if(!hr(s))return;let u=[];r.forEach((d,h)=>{u.push(...this._findMatches({key:d,value:s[h],searcher:n}))}),u.length&&i.push({idx:l,item:s,matches:u})}),i}_findMatches({key:t,value:n,searcher:r}){if(!hr(n))return[];let o=[];if(bi(n))n.forEach(({v:i,i:s,n:l})=>{if(!hr(i))return;const{isMatch:u,score:d,indices:h}=r.searchIn(i);u&&o.push({score:d,key:t,value:i,idx:s,norm:l,indices:h})});else{const{v:i,n:s}=n,{isMatch:l,score:u,indices:d}=r.searchIn(i);l&&o.push({score:u,key:t,value:i,norm:s,indices:d})}return o}}_c.version="7.0.0";_c.createIndex=VP;_c.parseIndex=AK;_c.config=He;_c.parseQuery=YP;KK(HK);function zd(e){const t=e+"CollectionProvider",[n,r]=An(t),[o,i]=n(t,{collectionRef:{current:null},itemMap:new Map}),s=y=>{const{scope:x,children:_}=y,C=Fe.useRef(null),S=Fe.useRef(new Map).current;return Fe.createElement(o,{scope:x,itemMap:S,collectionRef:C},_)},l=e+"CollectionSlot",u=Fe.forwardRef((y,x)=>{const{scope:_,children:C}=y,S=i(l,_),b=Be(x,S.collectionRef);return Fe.createElement(Wo,{ref:b},C)}),d=e+"CollectionItemSlot",h="data-radix-collection-item",m=Fe.forwardRef((y,x)=>{const{scope:_,children:C,...S}=y,b=Fe.useRef(null),E=Be(x,b),k=i(d,_);return Fe.useEffect(()=>(k.itemMap.set(b,{ref:b,...S}),()=>void k.itemMap.delete(b))),Fe.createElement(Wo,{[h]:"",ref:E},C)});function g(y){const x=i(e+"CollectionConsumer",y);return Fe.useCallback(()=>{const C=x.collectionRef.current;if(!C)return[];const S=Array.from(C.querySelectorAll(`[${h}]`));return Array.from(x.itemMap.values()).sort((k,P)=>S.indexOf(k.ref.current)-S.indexOf(P.ref.current))},[x.collectionRef,x.itemMap])}return[{Provider:s,Slot:u,ItemSlot:m},g,r]}const JK=f.createContext(void 0);function Sc(e){const t=f.useContext(JK);return e||t||"ltr"}const R0="rovingFocusGroup.onEntryFocus",eY={bubbles:!1,cancelable:!0},Dx="RovingFocusGroup",[x1,GP,tY]=zd(Dx),[nY,Qm]=An(Dx,[tY]),[rY,oY]=nY(Dx),iY=f.forwardRef((e,t)=>f.createElement(x1.Provider,{scope:e.__scopeRovingFocusGroup},f.createElement(x1.Slot,{scope:e.__scopeRovingFocusGroup},f.createElement(sY,Y({},e,{ref:t}))))),sY=f.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:o=!1,dir:i,currentTabStopId:s,defaultCurrentTabStopId:l,onCurrentTabStopIdChange:u,onEntryFocus:d,...h}=e,m=f.useRef(null),g=Be(t,m),y=Sc(i),[x=null,_]=Zr({prop:s,defaultProp:l,onChange:u}),[C,S]=f.useState(!1),b=Ft(d),E=GP(n),k=f.useRef(!1),[P,M]=f.useState(0);return f.useEffect(()=>{const A=m.current;if(A)return A.addEventListener(R0,b),()=>A.removeEventListener(R0,b)},[b]),f.createElement(rY,{scope:n,orientation:r,dir:y,loop:o,currentTabStopId:x,onItemFocus:f.useCallback(A=>_(A),[_]),onItemShiftTab:f.useCallback(()=>S(!0),[]),onFocusableItemAdd:f.useCallback(()=>M(A=>A+1),[]),onFocusableItemRemove:f.useCallback(()=>M(A=>A-1),[])},f.createElement(Pe.div,Y({tabIndex:C||P===0?-1:0,"data-orientation":r},h,{ref:g,style:{outline:"none",...e.style},onMouseDown:ue(e.onMouseDown,()=>{k.current=!0}),onFocus:ue(e.onFocus,A=>{const O=!k.current;if(A.target===A.currentTarget&&O&&!C){const F=new CustomEvent(R0,eY);if(A.currentTarget.dispatchEvent(F),!F.defaultPrevented){const V=E().filter(te=>te.focusable),J=V.find(te=>te.active),G=V.find(te=>te.id===x),U=[J,G,...V].filter(Boolean).map(te=>te.ref.current);XP(U)}}k.current=!1}),onBlur:ue(e.onBlur,()=>S(!1))})))}),aY="RovingFocusGroupItem",lY=f.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:o=!1,tabStopId:i,...s}=e,l=nr(),u=i||l,d=oY(aY,n),h=d.currentTabStopId===u,m=GP(n),{onFocusableItemAdd:g,onFocusableItemRemove:y}=d;return f.useEffect(()=>{if(r)return g(),()=>y()},[r,g,y]),f.createElement(x1.ItemSlot,{scope:n,id:u,focusable:r,active:o},f.createElement(Pe.span,Y({tabIndex:h?0:-1,"data-orientation":d.orientation},s,{ref:t,onMouseDown:ue(e.onMouseDown,x=>{r?d.onItemFocus(u):x.preventDefault()}),onFocus:ue(e.onFocus,()=>d.onItemFocus(u)),onKeyDown:ue(e.onKeyDown,x=>{if(x.key==="Tab"&&x.shiftKey){d.onItemShiftTab();return}if(x.target!==x.currentTarget)return;const _=dY(x,d.orientation,d.dir);if(_!==void 0){x.preventDefault();let S=m().filter(b=>b.focusable).map(b=>b.ref.current);if(_==="last")S.reverse();else if(_==="prev"||_==="next"){_==="prev"&&S.reverse();const b=S.indexOf(x.currentTarget);S=d.loop?fY(S,b+1):S.slice(b+1)}setTimeout(()=>XP(S))}})})))}),cY={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function uY(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function dY(e,t,n){const r=uY(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return cY[r]}function XP(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function fY(e,t){return e.map((n,r)=>e[(t+r)%e.length])}const ZP=iY,qP=lY,QP="Tabs",[pY,bte]=An(QP,[Qm]),JP=Qm(),[hY,Ix]=pY(QP),mY=f.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,onValueChange:o,defaultValue:i,orientation:s="horizontal",dir:l,activationMode:u="automatic",...d}=e,h=Sc(l),[m,g]=Zr({prop:r,onChange:o,defaultProp:i});return f.createElement(hY,{scope:n,baseId:nr(),value:m,onValueChange:g,orientation:s,dir:h,activationMode:u},f.createElement(Pe.div,Y({dir:h,"data-orientation":s},d,{ref:t})))}),gY="TabsList",vY=f.forwardRef((e,t)=>{const{__scopeTabs:n,loop:r=!0,...o}=e,i=Ix(gY,n),s=JP(n);return f.createElement(ZP,Y({asChild:!0},s,{orientation:i.orientation,dir:i.dir,loop:r}),f.createElement(Pe.div,Y({role:"tablist","aria-orientation":i.orientation},o,{ref:t})))}),yY="TabsTrigger",wY=f.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,disabled:o=!1,...i}=e,s=Ix(yY,n),l=JP(n),u=e5(s.baseId,r),d=t5(s.baseId,r),h=r===s.value;return f.createElement(qP,Y({asChild:!0},l,{focusable:!o,active:h}),f.createElement(Pe.button,Y({type:"button",role:"tab","aria-selected":h,"aria-controls":d,"data-state":h?"active":"inactive","data-disabled":o?"":void 0,disabled:o,id:u},i,{ref:t,onMouseDown:ue(e.onMouseDown,m=>{!o&&m.button===0&&m.ctrlKey===!1?s.onValueChange(r):m.preventDefault()}),onKeyDown:ue(e.onKeyDown,m=>{[" ","Enter"].includes(m.key)&&s.onValueChange(r)}),onFocus:ue(e.onFocus,()=>{const m=s.activationMode!=="manual";!h&&!o&&m&&s.onValueChange(r)})})))}),xY="TabsContent",bY=f.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,forceMount:o,children:i,...s}=e,l=Ix(xY,n),u=e5(l.baseId,r),d=t5(l.baseId,r),h=r===l.value,m=f.useRef(h);return f.useEffect(()=>{const g=requestAnimationFrame(()=>m.current=!1);return()=>cancelAnimationFrame(g)},[]),f.createElement(xn,{present:o||h},({present:g})=>f.createElement(Pe.div,Y({"data-state":h?"active":"inactive","data-orientation":l.orientation,role:"tabpanel","aria-labelledby":u,hidden:!g,id:d,tabIndex:0},s,{ref:t,style:{...e.style,animationDuration:m.current?"0s":void 0}}),g&&i))});function e5(e,t){return`${e}-trigger-${t}`}function t5(e,t){return`${e}-content-${t}`}const _Y=mY,n5=vY,r5=wY,o5=bY,i5=_Y,Lx=f.forwardRef(({className:e,...t},n)=>v.jsx(n5,{ref:n,className:Ce("inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground",e),tabIndex:-1,...t}));Lx.displayName=n5.displayName;const sa=f.forwardRef(({className:e,...t},n)=>v.jsx(r5,{ref:n,className:Ce("inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow",e),tabIndex:-1,...t}));sa.displayName=r5.displayName;const mu=f.forwardRef(({className:e,...t},n)=>v.jsx(o5,{ref:n,className:Ce("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",e),tabIndex:-1,...t}));mu.displayName=o5.displayName;function id(e,[t,n]){return Math.min(n,Math.max(t,e))}function Fx(e){const t=f.useRef({value:e,previous:e});return f.useMemo(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}const SY=[" ","Enter","ArrowUp","ArrowDown"],EY=[" ","Enter"],Jm="Select",[eg,tg,CY]=zd(Jm),[Ec,_te]=An(Jm,[CY,Ns]),jx=Ns(),[$Y,Oa]=Ec(Jm),[kY,RY]=Ec(Jm),TY=e=>{const{__scopeSelect:t,children:n,open:r,defaultOpen:o,onOpenChange:i,value:s,defaultValue:l,onValueChange:u,dir:d,name:h,autoComplete:m,disabled:g,required:y}=e,x=jx(t),[_,C]=f.useState(null),[S,b]=f.useState(null),[E,k]=f.useState(!1),P=Sc(d),[M=!1,A]=Zr({prop:r,defaultProp:o,onChange:i}),[O,F]=Zr({prop:s,defaultProp:l,onChange:u}),V=f.useRef(null),J=_?!!_.closest("form"):!0,[G,ae]=f.useState(new Set),U=Array.from(G).map(te=>te.props.value).join(";");return f.createElement(Od,x,f.createElement($Y,{required:y,scope:t,trigger:_,onTriggerChange:C,valueNode:S,onValueNodeChange:b,valueNodeHasChildren:E,onValueNodeHasChildrenChange:k,contentId:nr(),value:O,onValueChange:F,open:M,onOpenChange:A,dir:P,triggerPointerDownPosRef:V,disabled:g},f.createElement(eg.Provider,{scope:t},f.createElement(kY,{scope:e.__scopeSelect,onNativeOptionAdd:f.useCallback(te=>{ae(L=>new Set(L).add(te))},[]),onNativeOptionRemove:f.useCallback(te=>{ae(L=>{const ie=new Set(L);return ie.delete(te),ie})},[])},n)),J?f.createElement(u5,{key:U,"aria-hidden":!0,required:y,tabIndex:-1,name:h,autoComplete:m,value:O,onChange:te=>F(te.target.value),disabled:g},O===void 0?f.createElement("option",{value:""}):null,Array.from(G)):null))},PY="SelectTrigger",AY=f.forwardRef((e,t)=>{const{__scopeSelect:n,disabled:r=!1,...o}=e,i=jx(n),s=Oa(PY,n),l=s.disabled||r,u=Be(t,s.onTriggerChange),d=tg(n),[h,m,g]=d5(x=>{const _=d().filter(b=>!b.disabled),C=_.find(b=>b.value===s.value),S=f5(_,x,C);S!==void 0&&s.onValueChange(S.value)}),y=()=>{l||(s.onOpenChange(!0),g())};return f.createElement(zm,Y({asChild:!0},i),f.createElement(Pe.button,Y({type:"button",role:"combobox","aria-controls":s.contentId,"aria-expanded":s.open,"aria-required":s.required,"aria-autocomplete":"none",dir:s.dir,"data-state":s.open?"open":"closed",disabled:l,"data-disabled":l?"":void 0,"data-placeholder":c5(s.value)?"":void 0},o,{ref:u,onClick:ue(o.onClick,x=>{x.currentTarget.focus()}),onPointerDown:ue(o.onPointerDown,x=>{const _=x.target;_.hasPointerCapture(x.pointerId)&&_.releasePointerCapture(x.pointerId),x.button===0&&x.ctrlKey===!1&&(y(),s.triggerPointerDownPosRef.current={x:Math.round(x.pageX),y:Math.round(x.pageY)},x.preventDefault())}),onKeyDown:ue(o.onKeyDown,x=>{const _=h.current!=="";!(x.ctrlKey||x.altKey||x.metaKey)&&x.key.length===1&&m(x.key),!(_&&x.key===" ")&&SY.includes(x.key)&&(y(),x.preventDefault())})})))}),OY="SelectValue",MY=f.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,children:i,placeholder:s="",...l}=e,u=Oa(OY,n),{onValueNodeHasChildrenChange:d}=u,h=i!==void 0,m=Be(t,u.onValueNodeChange);return Pn(()=>{d(h)},[d,h]),f.createElement(Pe.span,Y({},l,{ref:m,style:{pointerEvents:"none"}}),c5(u.value)?f.createElement(f.Fragment,null,s):i)}),NY=f.forwardRef((e,t)=>{const{__scopeSelect:n,children:r,...o}=e;return f.createElement(Pe.span,Y({"aria-hidden":!0},o,{ref:t}),r||"▼")}),DY=e=>f.createElement(Md,Y({asChild:!0},e)),ic="SelectContent",IY=f.forwardRef((e,t)=>{const n=Oa(ic,e.__scopeSelect),[r,o]=f.useState();if(Pn(()=>{o(new DocumentFragment)},[]),!n.open){const i=r;return i?Os.createPortal(f.createElement(s5,{scope:e.__scopeSelect},f.createElement(eg.Slot,{scope:e.__scopeSelect},f.createElement("div",null,e.children))),i):null}return f.createElement(LY,Y({},e,{ref:t}))}),ai=10,[s5,Ma]=Ec(ic),LY=f.forwardRef((e,t)=>{const{__scopeSelect:n,position:r="item-aligned",onCloseAutoFocus:o,onEscapeKeyDown:i,onPointerDownOutside:s,side:l,sideOffset:u,align:d,alignOffset:h,arrowPadding:m,collisionBoundary:g,collisionPadding:y,sticky:x,hideWhenDetached:_,avoidCollisions:C,...S}=e,b=Oa(ic,n),[E,k]=f.useState(null),[P,M]=f.useState(null),A=Be(t,fe=>k(fe)),[O,F]=f.useState(null),[V,J]=f.useState(null),G=tg(n),[ae,U]=f.useState(!1),te=f.useRef(!1);f.useEffect(()=>{if(E)return Xm(E)},[E]),Km();const L=f.useCallback(fe=>{const[xe,...$e]=G().map(je=>je.ref.current),[Ae]=$e.slice(-1),Oe=document.activeElement;for(const je of fe)if(je===Oe||(je==null||je.scrollIntoView({block:"nearest"}),je===xe&&P&&(P.scrollTop=0),je===Ae&&P&&(P.scrollTop=P.scrollHeight),je==null||je.focus(),document.activeElement!==Oe))return},[G,P]),ie=f.useCallback(()=>L([O,E]),[L,O,E]);f.useEffect(()=>{ae&&ie()},[ae,ie]);const{onOpenChange:K,triggerPointerDownPosRef:Q}=b;f.useEffect(()=>{if(E){let fe={x:0,y:0};const xe=Ae=>{var Oe,je,Ot,ct;fe={x:Math.abs(Math.round(Ae.pageX)-((Oe=(je=Q.current)===null||je===void 0?void 0:je.x)!==null&&Oe!==void 0?Oe:0)),y:Math.abs(Math.round(Ae.pageY)-((Ot=(ct=Q.current)===null||ct===void 0?void 0:ct.y)!==null&&Ot!==void 0?Ot:0))}},$e=Ae=>{fe.x<=10&&fe.y<=10?Ae.preventDefault():E.contains(Ae.target)||K(!1),document.removeEventListener("pointermove",xe),Q.current=null};return Q.current!==null&&(document.addEventListener("pointermove",xe),document.addEventListener("pointerup",$e,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",xe),document.removeEventListener("pointerup",$e,{capture:!0})}}},[E,K,Q]),f.useEffect(()=>{const fe=()=>K(!1);return window.addEventListener("blur",fe),window.addEventListener("resize",fe),()=>{window.removeEventListener("blur",fe),window.removeEventListener("resize",fe)}},[K]);const[W,le]=d5(fe=>{const xe=G().filter(Oe=>!Oe.disabled),$e=xe.find(Oe=>Oe.ref.current===document.activeElement),Ae=f5(xe,fe,$e);Ae&&setTimeout(()=>Ae.ref.current.focus())}),ge=f.useCallback((fe,xe,$e)=>{const Ae=!te.current&&!$e;(b.value!==void 0&&b.value===xe||Ae)&&(F(fe),Ae&&(te.current=!0))},[b.value]),Ve=f.useCallback(()=>E==null?void 0:E.focus(),[E]),Ue=f.useCallback((fe,xe,$e)=>{const Ae=!te.current&&!$e;(b.value!==void 0&&b.value===xe||Ae)&&J(fe)},[b.value]),We=r==="popper"?f2:FY,Me=We===f2?{side:l,sideOffset:u,align:d,alignOffset:h,arrowPadding:m,collisionBoundary:g,collisionPadding:y,sticky:x,hideWhenDetached:_,avoidCollisions:C}:{};return f.createElement(s5,{scope:n,content:E,viewport:P,onViewportChange:M,itemRefCallback:ge,selectedItem:O,onItemLeave:Ve,itemTextRefCallback:Ue,focusSelectedItem:ie,selectedItemText:V,position:r,isPositioned:ae,searchRef:W},f.createElement(Gm,{as:Wo,allowPinchZoom:!0},f.createElement(Hm,{asChild:!0,trapped:b.open,onMountAutoFocus:fe=>{fe.preventDefault()},onUnmountAutoFocus:ue(o,fe=>{var xe;(xe=b.trigger)===null||xe===void 0||xe.focus({preventScroll:!0}),fe.preventDefault()})},f.createElement(yc,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:i,onPointerDownOutside:s,onFocusOutside:fe=>fe.preventDefault(),onDismiss:()=>b.onOpenChange(!1)},f.createElement(We,Y({role:"listbox",id:b.contentId,"data-state":b.open?"open":"closed",dir:b.dir,onContextMenu:fe=>fe.preventDefault()},S,Me,{onPlaced:()=>U(!0),ref:A,style:{display:"flex",flexDirection:"column",outline:"none",...S.style},onKeyDown:ue(S.onKeyDown,fe=>{const xe=fe.ctrlKey||fe.altKey||fe.metaKey;if(fe.key==="Tab"&&fe.preventDefault(),!xe&&fe.key.length===1&&le(fe.key),["ArrowUp","ArrowDown","Home","End"].includes(fe.key)){let Ae=G().filter(Oe=>!Oe.disabled).map(Oe=>Oe.ref.current);if(["ArrowUp","End"].includes(fe.key)&&(Ae=Ae.slice().reverse()),["ArrowUp","ArrowDown"].includes(fe.key)){const Oe=fe.target,je=Ae.indexOf(Oe);Ae=Ae.slice(je+1)}setTimeout(()=>L(Ae)),fe.preventDefault()}})}))))))}),FY=f.forwardRef((e,t)=>{const{__scopeSelect:n,onPlaced:r,...o}=e,i=Oa(ic,n),s=Ma(ic,n),[l,u]=f.useState(null),[d,h]=f.useState(null),m=Be(t,A=>h(A)),g=tg(n),y=f.useRef(!1),x=f.useRef(!0),{viewport:_,selectedItem:C,selectedItemText:S,focusSelectedItem:b}=s,E=f.useCallback(()=>{if(i.trigger&&i.valueNode&&l&&d&&_&&C&&S){const A=i.trigger.getBoundingClientRect(),O=d.getBoundingClientRect(),F=i.valueNode.getBoundingClientRect(),V=S.getBoundingClientRect();if(i.dir!=="rtl"){const Oe=V.left-O.left,je=F.left-Oe,Ot=A.left-je,ct=A.width+Ot,Yt=Math.max(ct,O.width),Er=window.innerWidth-ai,gt=id(je,[ai,Er-Yt]);l.style.minWidth=ct+"px",l.style.left=gt+"px"}else{const Oe=O.right-V.right,je=window.innerWidth-F.right-Oe,Ot=window.innerWidth-A.right-je,ct=A.width+Ot,Yt=Math.max(ct,O.width),Er=window.innerWidth-ai,gt=id(je,[ai,Er-Yt]);l.style.minWidth=ct+"px",l.style.right=gt+"px"}const J=g(),G=window.innerHeight-ai*2,ae=_.scrollHeight,U=window.getComputedStyle(d),te=parseInt(U.borderTopWidth,10),L=parseInt(U.paddingTop,10),ie=parseInt(U.borderBottomWidth,10),K=parseInt(U.paddingBottom,10),Q=te+L+ae+K+ie,W=Math.min(C.offsetHeight*5,Q),le=window.getComputedStyle(_),ge=parseInt(le.paddingTop,10),Ve=parseInt(le.paddingBottom,10),Ue=A.top+A.height/2-ai,We=G-Ue,Me=C.offsetHeight/2,fe=C.offsetTop+Me,xe=te+L+fe,$e=Q-xe;if(xe<=Ue){const Oe=C===J[J.length-1].ref.current;l.style.bottom="0px";const je=d.clientHeight-_.offsetTop-_.offsetHeight,Ot=Math.max(We,Me+(Oe?Ve:0)+je+ie),ct=xe+Ot;l.style.height=ct+"px"}else{const Oe=C===J[0].ref.current;l.style.top="0px";const Ot=Math.max(Ue,te+_.offsetTop+(Oe?ge:0)+Me)+$e;l.style.height=Ot+"px",_.scrollTop=xe-Ue+_.offsetTop}l.style.margin=`${ai}px 0`,l.style.minHeight=W+"px",l.style.maxHeight=G+"px",r==null||r(),requestAnimationFrame(()=>y.current=!0)}},[g,i.trigger,i.valueNode,l,d,_,C,S,i.dir,r]);Pn(()=>E(),[E]);const[k,P]=f.useState();Pn(()=>{d&&P(window.getComputedStyle(d).zIndex)},[d]);const M=f.useCallback(A=>{A&&x.current===!0&&(E(),b==null||b(),x.current=!1)},[E,b]);return f.createElement(jY,{scope:n,contentWrapper:l,shouldExpandOnScrollRef:y,onScrollButtonChange:M},f.createElement("div",{ref:u,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:k}},f.createElement(Pe.div,Y({},o,{ref:m,style:{boxSizing:"border-box",maxHeight:"100%",...o.style}}))))}),f2=f.forwardRef((e,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:o=ai,...i}=e,s=jx(n);return f.createElement(Bm,Y({},s,i,{ref:t,align:r,collisionPadding:o,style:{boxSizing:"border-box",...i.style,"--radix-select-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-select-content-available-width":"var(--radix-popper-available-width)","--radix-select-content-available-height":"var(--radix-popper-available-height)","--radix-select-trigger-width":"var(--radix-popper-anchor-width)","--radix-select-trigger-height":"var(--radix-popper-anchor-height)"}}))}),[jY,zx]=Ec(ic,{}),p2="SelectViewport",zY=f.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=Ma(p2,n),i=zx(p2,n),s=Be(t,o.onViewportChange),l=f.useRef(0);return f.createElement(f.Fragment,null,f.createElement("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"}}),f.createElement(eg.Slot,{scope:n},f.createElement(Pe.div,Y({"data-radix-select-viewport":"",role:"presentation"},r,{ref:s,style:{position:"relative",flex:1,overflow:"auto",...r.style},onScroll:ue(r.onScroll,u=>{const d=u.currentTarget,{contentWrapper:h,shouldExpandOnScrollRef:m}=i;if(m!=null&&m.current&&h){const g=Math.abs(l.current-d.scrollTop);if(g>0){const y=window.innerHeight-ai*2,x=parseFloat(h.style.minHeight),_=parseFloat(h.style.height),C=Math.max(x,_);if(C0?E:0,h.style.justifyContent="flex-end")}}}l.current=d.scrollTop})}))))}),BY="SelectGroup",[UY,VY]=Ec(BY),WY=f.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=nr();return f.createElement(UY,{scope:n,id:o},f.createElement(Pe.div,Y({role:"group","aria-labelledby":o},r,{ref:t})))}),HY="SelectLabel",KY=f.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=VY(HY,n);return f.createElement(Pe.div,Y({id:o.id},r,{ref:t}))}),b1="SelectItem",[YY,a5]=Ec(b1),GY=f.forwardRef((e,t)=>{const{__scopeSelect:n,value:r,disabled:o=!1,textValue:i,...s}=e,l=Oa(b1,n),u=Ma(b1,n),d=l.value===r,[h,m]=f.useState(i??""),[g,y]=f.useState(!1),x=Be(t,S=>{var b;return(b=u.itemRefCallback)===null||b===void 0?void 0:b.call(u,S,r,o)}),_=nr(),C=()=>{o||(l.onValueChange(r),l.onOpenChange(!1))};if(r==="")throw new Error("A must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.");return f.createElement(YY,{scope:n,value:r,disabled:o,textId:_,isSelected:d,onItemTextChange:f.useCallback(S=>{m(b=>{var E;return b||((E=S==null?void 0:S.textContent)!==null&&E!==void 0?E:"").trim()})},[])},f.createElement(eg.ItemSlot,{scope:n,value:r,disabled:o,textValue:h},f.createElement(Pe.div,Y({role:"option","aria-labelledby":_,"data-highlighted":g?"":void 0,"aria-selected":d&&g,"data-state":d?"checked":"unchecked","aria-disabled":o||void 0,"data-disabled":o?"":void 0,tabIndex:o?void 0:-1},s,{ref:x,onFocus:ue(s.onFocus,()=>y(!0)),onBlur:ue(s.onBlur,()=>y(!1)),onPointerUp:ue(s.onPointerUp,C),onPointerMove:ue(s.onPointerMove,S=>{if(o){var b;(b=u.onItemLeave)===null||b===void 0||b.call(u)}else S.currentTarget.focus({preventScroll:!0})}),onPointerLeave:ue(s.onPointerLeave,S=>{if(S.currentTarget===document.activeElement){var b;(b=u.onItemLeave)===null||b===void 0||b.call(u)}}),onKeyDown:ue(s.onKeyDown,S=>{var b;((b=u.searchRef)===null||b===void 0?void 0:b.current)!==""&&S.key===" "||(EY.includes(S.key)&&C(),S.key===" "&&S.preventDefault())})}))))}),hp="SelectItemText",XY=f.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,...i}=e,s=Oa(hp,n),l=Ma(hp,n),u=a5(hp,n),d=RY(hp,n),[h,m]=f.useState(null),g=Be(t,S=>m(S),u.onItemTextChange,S=>{var b;return(b=l.itemTextRefCallback)===null||b===void 0?void 0:b.call(l,S,u.value,u.disabled)}),y=h==null?void 0:h.textContent,x=f.useMemo(()=>f.createElement("option",{key:u.value,value:u.value,disabled:u.disabled},y),[u.disabled,u.value,y]),{onNativeOptionAdd:_,onNativeOptionRemove:C}=d;return Pn(()=>(_(x),()=>C(x)),[_,C,x]),f.createElement(f.Fragment,null,f.createElement(Pe.span,Y({id:u.textId},i,{ref:g})),u.isSelected&&s.valueNode&&!s.valueNodeHasChildren?Os.createPortal(i.children,s.valueNode):null)}),ZY="SelectItemIndicator",qY=f.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return a5(ZY,n).isSelected?f.createElement(Pe.span,Y({"aria-hidden":!0},r,{ref:t})):null}),h2="SelectScrollUpButton",QY=f.forwardRef((e,t)=>{const n=Ma(h2,e.__scopeSelect),r=zx(h2,e.__scopeSelect),[o,i]=f.useState(!1),s=Be(t,r.onScrollButtonChange);return Pn(()=>{if(n.viewport&&n.isPositioned){let d=function(){const h=u.scrollTop>0;i(h)};var l=d;const u=n.viewport;return d(),u.addEventListener("scroll",d),()=>u.removeEventListener("scroll",d)}},[n.viewport,n.isPositioned]),o?f.createElement(l5,Y({},e,{ref:s,onAutoScroll:()=>{const{viewport:l,selectedItem:u}=n;l&&u&&(l.scrollTop=l.scrollTop-u.offsetHeight)}})):null}),m2="SelectScrollDownButton",JY=f.forwardRef((e,t)=>{const n=Ma(m2,e.__scopeSelect),r=zx(m2,e.__scopeSelect),[o,i]=f.useState(!1),s=Be(t,r.onScrollButtonChange);return Pn(()=>{if(n.viewport&&n.isPositioned){let d=function(){const h=u.scrollHeight-u.clientHeight,m=Math.ceil(u.scrollTop)u.removeEventListener("scroll",d)}},[n.viewport,n.isPositioned]),o?f.createElement(l5,Y({},e,{ref:s,onAutoScroll:()=>{const{viewport:l,selectedItem:u}=n;l&&u&&(l.scrollTop=l.scrollTop+u.offsetHeight)}})):null}),l5=f.forwardRef((e,t)=>{const{__scopeSelect:n,onAutoScroll:r,...o}=e,i=Ma("SelectScrollButton",n),s=f.useRef(null),l=tg(n),u=f.useCallback(()=>{s.current!==null&&(window.clearInterval(s.current),s.current=null)},[]);return f.useEffect(()=>()=>u(),[u]),Pn(()=>{var d;const h=l().find(m=>m.ref.current===document.activeElement);h==null||(d=h.ref.current)===null||d===void 0||d.scrollIntoView({block:"nearest"})},[l]),f.createElement(Pe.div,Y({"aria-hidden":!0},o,{ref:t,style:{flexShrink:0,...o.style},onPointerDown:ue(o.onPointerDown,()=>{s.current===null&&(s.current=window.setInterval(r,50))}),onPointerMove:ue(o.onPointerMove,()=>{var d;(d=i.onItemLeave)===null||d===void 0||d.call(i),s.current===null&&(s.current=window.setInterval(r,50))}),onPointerLeave:ue(o.onPointerLeave,()=>{u()})}))}),eG=f.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return f.createElement(Pe.div,Y({"aria-hidden":!0},r,{ref:t}))});function c5(e){return e===""||e===void 0}const u5=f.forwardRef((e,t)=>{const{value:n,...r}=e,o=f.useRef(null),i=Be(t,o),s=Fx(n);return f.useEffect(()=>{const l=o.current,u=window.HTMLSelectElement.prototype,h=Object.getOwnPropertyDescriptor(u,"value").set;if(s!==n&&h){const m=new Event("change",{bubbles:!0});h.call(l,n),l.dispatchEvent(m)}},[s,n]),f.createElement(Um,{asChild:!0},f.createElement("select",Y({},r,{ref:i,defaultValue:n})))});u5.displayName="BubbleSelect";function d5(e){const t=Ft(e),n=f.useRef(""),r=f.useRef(0),o=f.useCallback(s=>{const l=n.current+s;t(l),function u(d){n.current=d,window.clearTimeout(r.current),d!==""&&(r.current=window.setTimeout(()=>u(""),1e3))}(l)},[t]),i=f.useCallback(()=>{n.current="",window.clearTimeout(r.current)},[]);return f.useEffect(()=>()=>window.clearTimeout(r.current),[]),[n,o,i]}function f5(e,t,n){const o=t.length>1&&Array.from(t).every(d=>d===t[0])?t[0]:t,i=n?e.indexOf(n):-1;let s=tG(e,Math.max(i,0));o.length===1&&(s=s.filter(d=>d!==n));const u=s.find(d=>d.textValue.toLowerCase().startsWith(o.toLowerCase()));return u!==n?u:void 0}function tG(e,t){return e.map((n,r)=>e[(t+r)%e.length])}const nG=TY,p5=AY,rG=MY,oG=NY,iG=DY,h5=IY,sG=zY,aG=WY,m5=KY,g5=GY,lG=XY,cG=qY,v5=QY,y5=JY,w5=eG,aa=nG,wl=aG,la=rG,ls=f.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(p5,{ref:r,className:Ce("flex h-9 w-full items-center justify-between whitespace-nowrap rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",e),tabIndex:-1,...n,children:[t,v.jsx(oG,{asChild:!0,children:v.jsx(Xj,{className:"h-4 w-4 opacity-50"})})]}));ls.displayName=p5.displayName;const x5=f.forwardRef(({className:e,...t},n)=>v.jsx(v5,{ref:n,className:Ce("flex cursor-default items-center justify-center py-1",e),...t,children:v.jsx(nz,{})}));x5.displayName=v5.displayName;const b5=f.forwardRef(({className:e,...t},n)=>v.jsx(y5,{ref:n,className:Ce("flex cursor-default items-center justify-center py-1",e),...t,children:v.jsx(Qj,{})}));b5.displayName=y5.displayName;const cs=f.forwardRef(({className:e,children:t,position:n="popper",...r},o)=>v.jsx(iG,{children:v.jsxs(h5,{ref:o,className:Ce("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",n==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:n,onCloseAutoFocus:i=>i.preventDefault(),...r,children:[v.jsx(x5,{}),v.jsx(sG,{className:Ce("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),v.jsx(b5,{})]})}));cs.displayName=h5.displayName;const uG=f.forwardRef(({className:e,...t},n)=>v.jsx(m5,{ref:n,className:Ce("px-2 py-1.5 text-sm font-semibold",e),...t}));uG.displayName=m5.displayName;const us=f.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(g5,{ref:r,className:Ce("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-2 pr-8 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[v.jsx("span",{className:"absolute right-2 flex h-3.5 w-3.5 items-center justify-center",children:v.jsx(cG,{children:v.jsx(vT,{className:"h-4 w-4"})})}),v.jsx(lG,{children:t})]}));us.displayName=g5.displayName;const dG=f.forwardRef(({className:e,...t},n)=>v.jsx(w5,{ref:n,className:Ce("-mx-1 my-1 h-px bg-muted",e),...t}));dG.displayName=w5.displayName;function fG(e,t){return f.useReducer((n,r)=>{const o=t[n][r];return o??n},e)}const _5="ScrollArea",[S5,Ste]=An(_5),[pG,qr]=S5(_5),hG=f.forwardRef((e,t)=>{const{__scopeScrollArea:n,type:r="hover",dir:o,scrollHideDelay:i=600,...s}=e,[l,u]=f.useState(null),[d,h]=f.useState(null),[m,g]=f.useState(null),[y,x]=f.useState(null),[_,C]=f.useState(null),[S,b]=f.useState(0),[E,k]=f.useState(0),[P,M]=f.useState(!1),[A,O]=f.useState(!1),F=Be(t,J=>u(J)),V=Sc(o);return f.createElement(pG,{scope:n,type:r,dir:V,scrollHideDelay:i,scrollArea:l,viewport:d,onViewportChange:h,content:m,onContentChange:g,scrollbarX:y,onScrollbarXChange:x,scrollbarXEnabled:P,onScrollbarXEnabledChange:M,scrollbarY:_,onScrollbarYChange:C,scrollbarYEnabled:A,onScrollbarYEnabledChange:O,onCornerWidthChange:b,onCornerHeightChange:k},f.createElement(Pe.div,Y({dir:V},s,{ref:F,style:{position:"relative","--radix-scroll-area-corner-width":S+"px","--radix-scroll-area-corner-height":E+"px",...e.style}})))}),mG="ScrollAreaViewport",gG=f.forwardRef((e,t)=>{const{__scopeScrollArea:n,children:r,...o}=e,i=qr(mG,n),s=f.useRef(null),l=Be(t,s,i.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(Pe.div,Y({"data-radix-scroll-area-viewport":""},o,{ref:l,style:{overflowX:i.scrollbarXEnabled?"scroll":"hidden",overflowY:i.scrollbarYEnabled?"scroll":"hidden",...e.style}}),f.createElement("div",{ref:i.onContentChange,style:{minWidth:"100%",display:"table"}},r)))}),$i="ScrollAreaScrollbar",E5=f.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=qr($i,e.__scopeScrollArea),{onScrollbarXEnabledChange:i,onScrollbarYEnabledChange:s}=o,l=e.orientation==="horizontal";return f.useEffect(()=>(l?i(!0):s(!0),()=>{l?i(!1):s(!1)}),[l,i,s]),o.type==="hover"?f.createElement(vG,Y({},r,{ref:t,forceMount:n})):o.type==="scroll"?f.createElement(yG,Y({},r,{ref:t,forceMount:n})):o.type==="auto"?f.createElement(C5,Y({},r,{ref:t,forceMount:n})):o.type==="always"?f.createElement(Bx,Y({},r,{ref:t})):null}),vG=f.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=qr($i,e.__scopeScrollArea),[i,s]=f.useState(!1);return f.useEffect(()=>{const l=o.scrollArea;let u=0;if(l){const d=()=>{window.clearTimeout(u),s(!0)},h=()=>{u=window.setTimeout(()=>s(!1),o.scrollHideDelay)};return l.addEventListener("pointerenter",d),l.addEventListener("pointerleave",h),()=>{window.clearTimeout(u),l.removeEventListener("pointerenter",d),l.removeEventListener("pointerleave",h)}}},[o.scrollArea,o.scrollHideDelay]),f.createElement(xn,{present:n||i},f.createElement(C5,Y({"data-state":i?"visible":"hidden"},r,{ref:t})))}),yG=f.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=qr($i,e.__scopeScrollArea),i=e.orientation==="horizontal",s=rg(()=>u("SCROLL_END"),100),[l,u]=fG("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(l==="idle"){const d=window.setTimeout(()=>u("HIDE"),o.scrollHideDelay);return()=>window.clearTimeout(d)}},[l,o.scrollHideDelay,u]),f.useEffect(()=>{const d=o.viewport,h=i?"scrollLeft":"scrollTop";if(d){let m=d[h];const g=()=>{const y=d[h];m!==y&&(u("SCROLL"),s()),m=y};return d.addEventListener("scroll",g),()=>d.removeEventListener("scroll",g)}},[o.viewport,i,u,s]),f.createElement(xn,{present:n||l!=="hidden"},f.createElement(Bx,Y({"data-state":l==="hidden"?"hidden":"visible"},r,{ref:t,onPointerEnter:ue(e.onPointerEnter,()=>u("POINTER_ENTER")),onPointerLeave:ue(e.onPointerLeave,()=>u("POINTER_LEAVE"))})))}),C5=f.forwardRef((e,t)=>{const n=qr($i,e.__scopeScrollArea),{forceMount:r,...o}=e,[i,s]=f.useState(!1),l=e.orientation==="horizontal",u=rg(()=>{if(n.viewport){const d=n.viewport.offsetWidth{const{orientation:n="vertical",...r}=e,o=qr($i,e.__scopeScrollArea),i=f.useRef(null),s=f.useRef(0),[l,u]=f.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),d=T5(l.viewport,l.content),h={...r,sizes:l,onSizesChange:u,hasThumb:d>0&&d<1,onThumbChange:g=>i.current=g,onThumbPointerUp:()=>s.current=0,onThumbPointerDown:g=>s.current=g};function m(g,y){return $G(g,s.current,l,y)}return n==="horizontal"?f.createElement(wG,Y({},h,{ref:t,onThumbPositionChange:()=>{if(o.viewport&&i.current){const g=o.viewport.scrollLeft,y=g2(g,l,o.dir);i.current.style.transform=`translate3d(${y}px, 0, 0)`}},onWheelScroll:g=>{o.viewport&&(o.viewport.scrollLeft=g)},onDragScroll:g=>{o.viewport&&(o.viewport.scrollLeft=m(g,o.dir))}})):n==="vertical"?f.createElement(xG,Y({},h,{ref:t,onThumbPositionChange:()=>{if(o.viewport&&i.current){const g=o.viewport.scrollTop,y=g2(g,l);i.current.style.transform=`translate3d(0, ${y}px, 0)`}},onWheelScroll:g=>{o.viewport&&(o.viewport.scrollTop=g)},onDragScroll:g=>{o.viewport&&(o.viewport.scrollTop=m(g))}})):null}),wG=f.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,i=qr($i,e.__scopeScrollArea),[s,l]=f.useState(),u=f.useRef(null),d=Be(t,u,i.onScrollbarXChange);return f.useEffect(()=>{u.current&&l(getComputedStyle(u.current))},[u]),f.createElement(k5,Y({"data-orientation":"horizontal"},o,{ref:d,sizes:n,style:{bottom:0,left:i.dir==="rtl"?"var(--radix-scroll-area-corner-width)":0,right:i.dir==="ltr"?"var(--radix-scroll-area-corner-width)":0,"--radix-scroll-area-thumb-width":ng(n)+"px",...e.style},onThumbPointerDown:h=>e.onThumbPointerDown(h.x),onDragScroll:h=>e.onDragScroll(h.x),onWheelScroll:(h,m)=>{if(i.viewport){const g=i.viewport.scrollLeft+h.deltaX;e.onWheelScroll(g),A5(g,m)&&h.preventDefault()}},onResize:()=>{u.current&&i.viewport&&s&&r({content:i.viewport.scrollWidth,viewport:i.viewport.offsetWidth,scrollbar:{size:u.current.clientWidth,paddingStart:zh(s.paddingLeft),paddingEnd:zh(s.paddingRight)}})}}))}),xG=f.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,i=qr($i,e.__scopeScrollArea),[s,l]=f.useState(),u=f.useRef(null),d=Be(t,u,i.onScrollbarYChange);return f.useEffect(()=>{u.current&&l(getComputedStyle(u.current))},[u]),f.createElement(k5,Y({"data-orientation":"vertical"},o,{ref:d,sizes:n,style:{top:0,right:i.dir==="ltr"?0:void 0,left:i.dir==="rtl"?0:void 0,bottom:"var(--radix-scroll-area-corner-height)","--radix-scroll-area-thumb-height":ng(n)+"px",...e.style},onThumbPointerDown:h=>e.onThumbPointerDown(h.y),onDragScroll:h=>e.onDragScroll(h.y),onWheelScroll:(h,m)=>{if(i.viewport){const g=i.viewport.scrollTop+h.deltaY;e.onWheelScroll(g),A5(g,m)&&h.preventDefault()}},onResize:()=>{u.current&&i.viewport&&s&&r({content:i.viewport.scrollHeight,viewport:i.viewport.offsetHeight,scrollbar:{size:u.current.clientHeight,paddingStart:zh(s.paddingTop),paddingEnd:zh(s.paddingBottom)}})}}))}),[bG,$5]=S5($i),k5=f.forwardRef((e,t)=>{const{__scopeScrollArea:n,sizes:r,hasThumb:o,onThumbChange:i,onThumbPointerUp:s,onThumbPointerDown:l,onThumbPositionChange:u,onDragScroll:d,onWheelScroll:h,onResize:m,...g}=e,y=qr($i,n),[x,_]=f.useState(null),C=Be(t,F=>_(F)),S=f.useRef(null),b=f.useRef(""),E=y.viewport,k=r.content-r.viewport,P=Ft(h),M=Ft(u),A=rg(m,10);function O(F){if(S.current){const V=F.clientX-S.current.left,J=F.clientY-S.current.top;d({x:V,y:J})}}return f.useEffect(()=>{const F=V=>{const J=V.target;(x==null?void 0:x.contains(J))&&P(V,k)};return document.addEventListener("wheel",F,{passive:!1}),()=>document.removeEventListener("wheel",F,{passive:!1})},[E,x,k,P]),f.useEffect(M,[r,M]),sc(x,A),sc(y.content,A),f.createElement(bG,{scope:n,scrollbar:x,hasThumb:o,onThumbChange:Ft(i),onThumbPointerUp:Ft(s),onThumbPositionChange:M,onThumbPointerDown:Ft(l)},f.createElement(Pe.div,Y({},g,{ref:C,style:{position:"absolute",...g.style},onPointerDown:ue(e.onPointerDown,F=>{F.button===0&&(F.target.setPointerCapture(F.pointerId),S.current=x.getBoundingClientRect(),b.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",y.viewport&&(y.viewport.style.scrollBehavior="auto"),O(F))}),onPointerMove:ue(e.onPointerMove,O),onPointerUp:ue(e.onPointerUp,F=>{const V=F.target;V.hasPointerCapture(F.pointerId)&&V.releasePointerCapture(F.pointerId),document.body.style.webkitUserSelect=b.current,y.viewport&&(y.viewport.style.scrollBehavior=""),S.current=null})})))}),_1="ScrollAreaThumb",_G=f.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=$5(_1,e.__scopeScrollArea);return f.createElement(xn,{present:n||o.hasThumb},f.createElement(SG,Y({ref:t},r)))}),SG=f.forwardRef((e,t)=>{const{__scopeScrollArea:n,style:r,...o}=e,i=qr(_1,n),s=$5(_1,n),{onThumbPositionChange:l}=s,u=Be(t,m=>s.onThumbChange(m)),d=f.useRef(),h=rg(()=>{d.current&&(d.current(),d.current=void 0)},100);return f.useEffect(()=>{const m=i.viewport;if(m){const g=()=>{if(h(),!d.current){const y=kG(m,l);d.current=y,l()}};return l(),m.addEventListener("scroll",g),()=>m.removeEventListener("scroll",g)}},[i.viewport,h,l]),f.createElement(Pe.div,Y({"data-state":s.hasThumb?"visible":"hidden"},o,{ref:u,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...r},onPointerDownCapture:ue(e.onPointerDownCapture,m=>{const y=m.target.getBoundingClientRect(),x=m.clientX-y.left,_=m.clientY-y.top;s.onThumbPointerDown({x,y:_})}),onPointerUp:ue(e.onPointerUp,s.onThumbPointerUp)}))}),R5="ScrollAreaCorner",EG=f.forwardRef((e,t)=>{const n=qr(R5,e.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?f.createElement(CG,Y({},e,{ref:t})):null}),CG=f.forwardRef((e,t)=>{const{__scopeScrollArea:n,...r}=e,o=qr(R5,n),[i,s]=f.useState(0),[l,u]=f.useState(0),d=!!(i&&l);return sc(o.scrollbarX,()=>{var h;const m=((h=o.scrollbarX)===null||h===void 0?void 0:h.offsetHeight)||0;o.onCornerHeightChange(m),u(m)}),sc(o.scrollbarY,()=>{var h;const m=((h=o.scrollbarY)===null||h===void 0?void 0:h.offsetWidth)||0;o.onCornerWidthChange(m),s(m)}),d?f.createElement(Pe.div,Y({},r,{ref:t,style:{width:i,height:l,position:"absolute",right:o.dir==="ltr"?0:void 0,left:o.dir==="rtl"?0:void 0,bottom:0,...e.style}})):null});function zh(e){return e?parseInt(e,10):0}function T5(e,t){const n=e/t;return isNaN(n)?0:n}function ng(e){const t=T5(e.viewport,e.content),n=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,r=(e.scrollbar.size-n)*t;return Math.max(r,18)}function $G(e,t,n,r="ltr"){const o=ng(n),i=o/2,s=t||i,l=o-s,u=n.scrollbar.paddingStart+s,d=n.scrollbar.size-n.scrollbar.paddingEnd-l,h=n.content-n.viewport,m=r==="ltr"?[0,h]:[h*-1,0];return P5([u,d],m)(e)}function g2(e,t,n="ltr"){const r=ng(t),o=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,i=t.scrollbar.size-o,s=t.content-t.viewport,l=i-r,u=n==="ltr"?[0,s]:[s*-1,0],d=id(e,u);return P5([0,s],[0,l])(d)}function P5(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 A5(e,t){return e>0&&e{})=>{let n={left:e.scrollLeft,top:e.scrollTop},r=0;return function o(){const i={left:e.scrollLeft,top:e.scrollTop},s=n.left!==i.left,l=n.top!==i.top;(s||l)&&t(),n=i,r=window.requestAnimationFrame(o)}(),()=>window.cancelAnimationFrame(r)};function rg(e,t){const n=Ft(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 sc(e,t){const n=Ft(t);Pn(()=>{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 O5=hG,RG=gG,TG=EG,og=f.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(O5,{ref:r,className:Ce("relative overflow-hidden",e),scrollHideDelay:400,...n,children:[v.jsx(RG,{className:"h-full w-full rounded-[inherit]",children:t}),v.jsx(M5,{}),v.jsx(TG,{})]}));og.displayName=O5.displayName;const M5=f.forwardRef(({className:e,orientation:t="vertical",...n},r)=>v.jsx(E5,{ref:r,orientation:t,className:Ce("flex touch-none select-none transition-colors",t==="vertical"&&"h-full w-2.5 border-l border-l-transparent p-[1px]",t==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",e),...n,children:v.jsx(_G,{className:"relative flex-1 rounded-full bg-border"})}));M5.displayName=E5.displayName;const N5="Name",D5="Created time",I5="Modified time",v2="input",PG="output",y2={[xs.NAME]:N5,[xs.CTIME]:D5,[xs.MTIME]:I5};function AG(e){const{onPhotoClick:t,photoWidth:n}=e,[r,o]=AP(!1),[i,s]=bt(V=>[V.fileManagerState,V.updateFileManagerState]),{toast:l}=Td(),[u,d]=f.useState(0),[h,m]=f.useState(0),g=f.useRef(null),y=cV(i.searchText,300),[x,_]=f.useState(v2),[C,S]=f.useState([]),[b,E]=f.useState([]),[k,P]=f.useState(0);Zn("f",()=>{o()}),Zn("left",()=>{let V=k;k>0&&(V=k-1),P(V),t(x,b[V].name)},[k,b]),Zn("right",()=>{let V=k;k{r||m(u)},[r,u]);const M=f.useCallback(V=>{V!==null&&r&&setTimeout(()=>{V.scrollTo({top:h,left:0})},100)},[r,h]);f.useEffect(()=>{(async()=>{try{const J=await Vj(x);S(J)}catch(J){l({variant:"destructive",title:"Uh oh! Something went wrong.",description:J.message?J.message:J.toString()})}})()},[x]),f.useEffect(()=>{if(!r)return;(async()=>{try{let J=C;y&&(J=new _c(J,{keys:["name"]}).search(y).map(te=>J[te.refIndex])),J=bH.orderBy(J,i.sortBy,i.sortOrder);const G=J.map(ae=>{const U=n,te=ae.height*(U/ae.width);return{src:`${Ms}/media_thumbnail_file?tab=${x}&filename=${encodeURIComponent(ae.name)}&width=${Math.ceil(U)}&height=${Math.ceil(te)}`,height:te,width:U,name:ae.name}});E(G)}catch(J){l({variant:"destructive",title:"Uh oh! Something went wrong.",description:J.message?J.message:J.toString()})}})()},[C,y,i,n,r]);const A=V=>{d(V.currentTarget.scrollTop)},O=({index:V})=>{o(),P(V),t(x,b[V].name)},F=()=>v.jsxs("div",{className:"flex justify-start items-center gap-[12px]",children:[v.jsx("div",{children:`Images (${b.length})`}),v.jsxs("div",{className:"flex",children:[v.jsx(vn,{tooltip:"Rows layout",onClick:()=>{s({layout:"rows"})},children:v.jsx(pz,{className:i.layout!=="rows"?"opacity-50":""})}),v.jsx(vn,{tooltip:"Grid layout",onClick:()=>{s({layout:"masonry"})},children:v.jsx(dz,{className:i.layout!=="masonry"?"opacity-50":""})})]})]});return v.jsxs(Zm,{open:r,onOpenChange:o,children:[v.jsx(uP,{asChild:!0,children:v.jsx(vn,{tooltip:"File Manager",children:v.jsx(JU,{})})}),v.jsxs(Fd,{className:"h-4/5 max-w-6xl",children:[v.jsx(jd,{children:F()}),v.jsxs("div",{className:"flex justify-between gap-8 items-center",children:[v.jsxs("div",{className:"flex relative justify-start items-center",children:[v.jsx(az,{className:"absolute left-[8px]"}),v.jsx(Pd,{ref:g,value:i.searchText,className:"w-[250px] pl-[30px]",tabIndex:-1,onInput:V=>{V.preventDefault(),V.stopPropagation();const J=V.target;s({searchText:J.value})},placeholder:"Search by file name"})]}),v.jsx(i5,{defaultValue:x,onValueChange:V=>_(V),children:v.jsxs(Lx,{"aria-label":"Manage your account",children:[v.jsx(sa,{value:v2,children:"Image Directory"}),v.jsx(sa,{value:PG,children:"Output Directory"})]})}),v.jsx("div",{className:"flex gap-2",children:v.jsxs("div",{className:"flex gap-1",children:[v.jsxs(aa,{value:y2[i.sortBy],onValueChange:V=>{switch(V){case N5:s({sortBy:xs.NAME});break;case D5:s({sortBy:xs.CTIME});break;case I5:s({sortBy:xs.MTIME});break}},children:[v.jsx(ls,{className:"w-[140px]",children:v.jsx(la,{})}),v.jsx(cs,{children:Object.values(y2).map(V=>v.jsx(us,{value:V,children:V},V))})]}),i.sortOrder===$u.DESCENDING?v.jsx(vn,{tooltip:"Descending Order",onClick:()=>{s({sortOrder:$u.ASCENDING})},children:v.jsx(sK,{})}):v.jsx(vn,{tooltip:"Ascending Order",onClick:()=>{s({sortOrder:$u.DESCENDING})},children:v.jsx(cK,{})})]})})]}),v.jsx(og,{className:"w-full h-full rounded-md",onScroll:A,ref:M,children:v.jsx(rK,{layout:i.layout,photos:b,spacing:12,padding:0,onClick:O})})]})]})}var Bd=e=>e.type==="checkbox",xl=e=>e instanceof Date,Ln=e=>e==null;const L5=e=>typeof e=="object";var sn=e=>!Ln(e)&&!Array.isArray(e)&&L5(e)&&!xl(e),F5=e=>sn(e)&&e.target?Bd(e.target)?e.target.checked:e.target.value:e,OG=e=>e.substring(0,e.search(/\.\d+(\.|$)/))||e,j5=(e,t)=>e.has(OG(t)),MG=e=>{const t=e.constructor&&e.constructor.prototype;return sn(t)&&t.hasOwnProperty("isPrototypeOf")},Ux=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function so(e){let t;const n=Array.isArray(e);if(e instanceof Date)t=new Date(e);else if(e instanceof Set)t=new Set(e);else if(!(Ux&&(e instanceof Blob||e instanceof FileList))&&(n||sn(e)))if(t=n?[]:{},!n&&!MG(e))t=e;else for(const r in e)e.hasOwnProperty(r)&&(t[r]=so(e[r]));else return e;return t}var Ud=e=>Array.isArray(e)?e.filter(Boolean):[],Ht=e=>e===void 0,ve=(e,t,n)=>{if(!t||!sn(e))return n;const r=Ud(t.split(/[,[\].]+?/)).reduce((o,i)=>Ln(o)?o:o[i],e);return Ht(r)||r===e?Ht(e[t])?n:e[t]:r},No=e=>typeof e=="boolean";const Bh={BLUR:"blur",FOCUS_OUT:"focusout",CHANGE:"change"},mo={onBlur:"onBlur",onChange:"onChange",onSubmit:"onSubmit",onTouched:"onTouched",all:"all"},oi={max:"max",min:"min",maxLength:"maxLength",minLength:"minLength",pattern:"pattern",required:"required",validate:"validate"},z5=Fe.createContext(null),ig=()=>Fe.useContext(z5),NG=e=>{const{children:t,...n}=e;return Fe.createElement(z5.Provider,{value:n},t)};var B5=(e,t,n,r=!0)=>{const o={defaultValues:t._defaultValues};for(const i in e)Object.defineProperty(o,i,{get:()=>{const s=i;return t._proxyFormState[s]!==mo.all&&(t._proxyFormState[s]=!r||mo.all),n&&(n[s]=!0),e[s]}});return o},Fr=e=>sn(e)&&!Object.keys(e).length,U5=(e,t,n,r)=>{n(e);const{name:o,...i}=e;return Fr(i)||Object.keys(i).length>=Object.keys(t).length||Object.keys(i).find(s=>t[s]===(!r||mo.all))},Yp=e=>Array.isArray(e)?e:[e],V5=(e,t,n)=>!e||!t||e===t||Yp(e).some(r=>r&&(n?r===t:r.startsWith(t)||t.startsWith(r)));function Vx(e){const t=Fe.useRef(e);t.current=e,Fe.useEffect(()=>{const n=!e.disabled&&t.current.subject&&t.current.subject.subscribe({next:t.current.next});return()=>{n&&n.unsubscribe()}},[e.disabled])}function DG(e){const t=ig(),{control:n=t.control,disabled:r,name:o,exact:i}=e||{},[s,l]=Fe.useState(n._formState),u=Fe.useRef(!0),d=Fe.useRef({isDirty:!1,isLoading:!1,dirtyFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1}),h=Fe.useRef(o);return h.current=o,Vx({disabled:r,next:m=>u.current&&V5(h.current,m.name,i)&&U5(m,d.current,n._updateFormState)&&l({...n._formState,...m}),subject:n._subjects.state}),Fe.useEffect(()=>(u.current=!0,d.current.isValid&&n._updateValid(!0),()=>{u.current=!1}),[n]),B5(s,n,d.current,!1)}var Fo=e=>typeof e=="string",W5=(e,t,n,r,o)=>Fo(e)?(r&&t.watch.add(e),ve(n,e,o)):Array.isArray(e)?e.map(i=>(r&&t.watch.add(i),ve(n,i))):(r&&(t.watchAll=!0),n);function IG(e){const t=ig(),{control:n=t.control,name:r,defaultValue:o,disabled:i,exact:s}=e||{},l=Fe.useRef(r);l.current=r,Vx({disabled:i,subject:n._subjects.values,next:h=>{V5(l.current,h.name,s)&&d(so(W5(l.current,n._names,h.values||n._formValues,!1,o)))}});const[u,d]=Fe.useState(n._getWatch(r,o));return Fe.useEffect(()=>n._removeUnmounted()),u}var Wx=e=>/^\w*$/.test(e),H5=e=>Ud(e.replace(/["|']|\]/g,"").split(/\.|\[/));function wt(e,t,n){let r=-1;const o=Wx(t)?[t]:H5(t),i=o.length,s=i-1;for(;++r{const h=o._options.shouldUnregister||i,m=(g,y)=>{const x=ve(o._fields,g);x&&(x._f.mount=y)};if(m(n,!0),h){const g=so(ve(o._options.defaultValues,n));wt(o._defaultValues,n,g),Ht(ve(o._formValues,n))&&wt(o._formValues,n,g)}return()=>{(s?h&&!o._state.action:h)?o.unregister(n):m(n,!1)}},[n,o,s,i]),Fe.useEffect(()=>{ve(o._fields,n)&&o._updateDisabledField({disabled:r,fields:o._fields,name:n,value:ve(o._fields,n)._f.value})},[r,n,o]),{field:{name:n,value:l,...No(r)||No(u.disabled)?{disabled:u.disabled||r}:{},onChange:Fe.useCallback(h=>d.current.onChange({target:{value:F5(h),name:n},type:Bh.CHANGE}),[n]),onBlur:Fe.useCallback(()=>d.current.onBlur({target:{value:ve(o._formValues,n),name:n},type:Bh.BLUR}),[n,o]),ref:h=>{const m=ve(o._fields,n);m&&h&&(m._f.ref={focus:()=>h.focus(),select:()=>h.select(),setCustomValidity:g=>h.setCustomValidity(g),reportValidity:()=>h.reportValidity()})}},formState:u,fieldState:Object.defineProperties({},{invalid:{enumerable:!0,get:()=>!!ve(u.errors,n)},isDirty:{enumerable:!0,get:()=>!!ve(u.dirtyFields,n)},isTouched:{enumerable:!0,get:()=>!!ve(u.touchedFields,n)},error:{enumerable:!0,get:()=>ve(u.errors,n)}})}}const FG=e=>e.render(LG(e));var K5=(e,t,n,r,o)=>t?{...n[e],types:{...n[e]&&n[e].types?n[e].types:{},[r]:o||!0}}:{},w2=e=>({isOnSubmit:!e||e===mo.onSubmit,isOnBlur:e===mo.onBlur,isOnChange:e===mo.onChange,isOnAll:e===mo.all,isOnTouch:e===mo.onTouched}),x2=(e,t,n)=>!n&&(t.watchAll||t.watch.has(e)||[...t.watch].some(r=>e.startsWith(r)&&/^\.\w+/.test(e.slice(r.length))));const Gp=(e,t,n,r)=>{for(const o of n||Object.keys(e)){const i=ve(e,o);if(i){const{_f:s,...l}=i;if(s){if(s.refs&&s.refs[0]&&t(s.refs[0],o)&&!r)break;if(s.ref&&t(s.ref,s.name)&&!r)break}else sn(l)&&Gp(l,t)}}};var jG=(e,t,n)=>{const r=Ud(ve(e,n));return wt(r,"root",t[n]),wt(e,n,r),e},Hx=e=>e.type==="file",ds=e=>typeof e=="function",Uh=e=>{if(!Ux)return!1;const t=e?e.ownerDocument:0;return e instanceof(t&&t.defaultView?t.defaultView.HTMLElement:HTMLElement)},Xp=e=>Fo(e),Kx=e=>e.type==="radio",Vh=e=>e instanceof RegExp;const b2={value:!1,isValid:!1},_2={value:!0,isValid:!0};var Y5=e=>{if(Array.isArray(e)){if(e.length>1){const t=e.filter(n=>n&&n.checked&&!n.disabled).map(n=>n.value);return{value:t,isValid:!!t.length}}return e[0].checked&&!e[0].disabled?e[0].attributes&&!Ht(e[0].attributes.value)?Ht(e[0].value)||e[0].value===""?_2:{value:e[0].value,isValid:!0}:_2:b2}return b2};const S2={isValid:!1,value:null};var G5=e=>Array.isArray(e)?e.reduce((t,n)=>n&&n.checked&&!n.disabled?{isValid:!0,value:n.value}:t,S2):S2;function E2(e,t,n="validate"){if(Xp(e)||Array.isArray(e)&&e.every(Xp)||No(e)&&!e)return{type:n,message:Xp(e)?e:"",ref:t}}var el=e=>sn(e)&&!Vh(e)?e:{value:e,message:""},C2=async(e,t,n,r,o)=>{const{ref:i,refs:s,required:l,maxLength:u,minLength:d,min:h,max:m,pattern:g,validate:y,name:x,valueAsNumber:_,mount:C,disabled:S}=e._f,b=ve(t,x);if(!C||S)return{};const E=s?s[0]:i,k=G=>{r&&E.reportValidity&&(E.setCustomValidity(No(G)?"":G||""),E.reportValidity())},P={},M=Kx(i),A=Bd(i),O=M||A,F=(_||Hx(i))&&Ht(i.value)&&Ht(b)||Uh(i)&&i.value===""||b===""||Array.isArray(b)&&!b.length,V=K5.bind(null,x,n,P),J=(G,ae,U,te=oi.maxLength,L=oi.minLength)=>{const ie=G?ae:U;P[x]={type:G?te:L,message:ie,ref:i,...V(G?te:L,ie)}};if(o?!Array.isArray(b)||!b.length:l&&(!O&&(F||Ln(b))||No(b)&&!b||A&&!Y5(s).isValid||M&&!G5(s).isValid)){const{value:G,message:ae}=Xp(l)?{value:!!l,message:l}:el(l);if(G&&(P[x]={type:oi.required,message:ae,ref:E,...V(oi.required,ae)},!n))return k(ae),P}if(!F&&(!Ln(h)||!Ln(m))){let G,ae;const U=el(m),te=el(h);if(!Ln(b)&&!isNaN(b)){const L=i.valueAsNumber||b&&+b;Ln(U.value)||(G=L>U.value),Ln(te.value)||(ae=Lnew Date(new Date().toDateString()+" "+W),K=i.type=="time",Q=i.type=="week";Fo(U.value)&&b&&(G=K?ie(b)>ie(U.value):Q?b>U.value:L>new Date(U.value)),Fo(te.value)&&b&&(ae=K?ie(b)+G.value,te=!Ln(ae.value)&&b.length<+ae.value;if((U||te)&&(J(U,G.message,ae.message),!n))return k(P[x].message),P}if(g&&!F&&Fo(b)){const{value:G,message:ae}=el(g);if(Vh(G)&&!b.match(G)&&(P[x]={type:oi.pattern,message:ae,ref:i,...V(oi.pattern,ae)},!n))return k(ae),P}if(y){if(ds(y)){const G=await y(b,t),ae=E2(G,E);if(ae&&(P[x]={...ae,...V(oi.validate,ae.message)},!n))return k(ae.message),P}else if(sn(y)){let G={};for(const ae in y){if(!Fr(G)&&!n)break;const U=E2(await y[ae](b,t),E,ae);U&&(G={...U,...V(ae,U.message)},k(U.message),n&&(P[x]=G))}if(!Fr(G)&&(P[x]={ref:E,...G},!n))return P}}return k(!0),P};function zG(e,t){const n=t.slice(0,-1).length;let r=0;for(;r{for(const i of e)i.next&&i.next(o)},subscribe:o=>(e.push(o),{unsubscribe:()=>{e=e.filter(i=>i!==o)}}),unsubscribe:()=>{e=[]}}}var Wh=e=>Ln(e)||!L5(e);function ca(e,t){if(Wh(e)||Wh(t))return e===t;if(xl(e)&&xl(t))return e.getTime()===t.getTime();const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(const o of n){const i=e[o];if(!r.includes(o))return!1;if(o!=="ref"){const s=t[o];if(xl(i)&&xl(s)||sn(i)&&sn(s)||Array.isArray(i)&&Array.isArray(s)?!ca(i,s):i!==s)return!1}}return!0}var X5=e=>e.type==="select-multiple",UG=e=>Kx(e)||Bd(e),P0=e=>Uh(e)&&e.isConnected,Z5=e=>{for(const t in e)if(ds(e[t]))return!0;return!1};function Hh(e,t={}){const n=Array.isArray(e);if(sn(e)||n)for(const r in e)Array.isArray(e[r])||sn(e[r])&&!Z5(e[r])?(t[r]=Array.isArray(e[r])?[]:{},Hh(e[r],t[r])):Ln(e[r])||(t[r]=!0);return t}function q5(e,t,n){const r=Array.isArray(e);if(sn(e)||r)for(const o in e)Array.isArray(e[o])||sn(e[o])&&!Z5(e[o])?Ht(t)||Wh(n[o])?n[o]=Array.isArray(e[o])?Hh(e[o],[]):{...Hh(e[o])}:q5(e[o],Ln(t)?{}:t[o],n[o]):n[o]=!ca(e[o],t[o]);return n}var A0=(e,t)=>q5(e,t,Hh(t)),Q5=(e,{valueAsNumber:t,valueAsDate:n,setValueAs:r})=>Ht(e)?e:t?e===""?NaN:e&&+e:n&&Fo(e)?new Date(e):r?r(e):e;function O0(e){const t=e.ref;if(!(e.refs?e.refs.every(n=>n.disabled):t.disabled))return Hx(t)?t.files:Kx(t)?G5(e.refs).value:X5(t)?[...t.selectedOptions].map(({value:n})=>n):Bd(t)?Y5(e.refs).value:Q5(Ht(t.value)?e.ref.value:t.value,e)}var VG=(e,t,n,r)=>{const o={};for(const i of e){const s=ve(t,i);s&&wt(o,i,s._f)}return{criteriaMode:n,names:[...e],fields:o,shouldUseNativeValidation:r}},iu=e=>Ht(e)?e:Vh(e)?e.source:sn(e)?Vh(e.value)?e.value.source:e.value:e,WG=e=>e.mount&&(e.required||e.min||e.max||e.maxLength||e.minLength||e.pattern||e.validate);function $2(e,t,n){const r=ve(e,n);if(r||Wx(n))return{error:r,name:n};const o=n.split(".");for(;o.length;){const i=o.join("."),s=ve(t,i),l=ve(e,i);if(s&&!Array.isArray(s)&&n!==i)return{name:n};if(l&&l.type)return{name:i,error:l};o.pop()}return{name:n}}var HG=(e,t,n,r,o)=>o.isOnAll?!1:!n&&o.isOnTouch?!(t||e):(n?r.isOnBlur:o.isOnBlur)?!e:(n?r.isOnChange:o.isOnChange)?e:!0,KG=(e,t)=>!Ud(ve(e,t)).length&&hn(e,t);const YG={mode:mo.onSubmit,reValidateMode:mo.onChange,shouldFocusError:!0};function GG(e={},t){let n={...YG,...e},r={submitCount:0,isDirty:!1,isLoading:ds(n.defaultValues),isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},errors:{},disabled:!1},o={},i=sn(n.defaultValues)||sn(n.values)?so(n.defaultValues||n.values)||{}:{},s=n.shouldUnregister?{}:so(i),l={action:!1,mount:!1,watch:!1},u={mount:new Set,unMount:new Set,array:new Set,watch:new Set},d,h=0;const m={isDirty:!1,dirtyFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1},g={values:T0(),array:T0(),state:T0()},y=e.resetOptions&&e.resetOptions.keepDirtyValues,x=w2(n.mode),_=w2(n.reValidateMode),C=n.criteriaMode===mo.all,S=I=>X=>{clearTimeout(h),h=setTimeout(I,X)},b=async I=>{if(m.isValid||I){const X=n.resolver?Fr((await F()).errors):await J(o,!0);X!==r.isValid&&g.state.next({isValid:X})}},E=I=>m.isValidating&&g.state.next({isValidating:I}),k=(I,X=[],Z,we,he=!0,de=!0)=>{if(we&&Z){if(l.action=!0,de&&Array.isArray(ve(o,I))){const ke=Z(ve(o,I),we.argA,we.argB);he&&wt(o,I,ke)}if(de&&Array.isArray(ve(r.errors,I))){const ke=Z(ve(r.errors,I),we.argA,we.argB);he&&wt(r.errors,I,ke),KG(r.errors,I)}if(m.touchedFields&&de&&Array.isArray(ve(r.touchedFields,I))){const ke=Z(ve(r.touchedFields,I),we.argA,we.argB);he&&wt(r.touchedFields,I,ke)}m.dirtyFields&&(r.dirtyFields=A0(i,s)),g.state.next({name:I,isDirty:ae(I,X),dirtyFields:r.dirtyFields,errors:r.errors,isValid:r.isValid})}else wt(s,I,X)},P=(I,X)=>{wt(r.errors,I,X),g.state.next({errors:r.errors})},M=(I,X,Z,we)=>{const he=ve(o,I);if(he){const de=ve(s,I,Ht(Z)?ve(i,I):Z);Ht(de)||we&&we.defaultChecked||X?wt(s,I,X?de:O0(he._f)):L(I,de),l.mount&&b()}},A=(I,X,Z,we,he)=>{let de=!1,ke=!1;const ft={name:I};if(!Z||we){m.isDirty&&(ke=r.isDirty,r.isDirty=ft.isDirty=ae(),de=ke!==ft.isDirty);const pt=ca(ve(i,I),X);ke=ve(r.dirtyFields,I),pt?hn(r.dirtyFields,I):wt(r.dirtyFields,I,!0),ft.dirtyFields=r.dirtyFields,de=de||m.dirtyFields&&ke!==!pt}if(Z){const pt=ve(r.touchedFields,I);pt||(wt(r.touchedFields,I,Z),ft.touchedFields=r.touchedFields,de=de||m.touchedFields&&pt!==Z)}return de&&he&&g.state.next(ft),de?ft:{}},O=(I,X,Z,we)=>{const he=ve(r.errors,I),de=m.isValid&&No(X)&&r.isValid!==X;if(e.delayError&&Z?(d=S(()=>P(I,Z)),d(e.delayError)):(clearTimeout(h),d=null,Z?wt(r.errors,I,Z):hn(r.errors,I)),(Z?!ca(he,Z):he)||!Fr(we)||de){const ke={...we,...de&&No(X)?{isValid:X}:{},errors:r.errors,name:I};r={...r,...ke},g.state.next(ke)}E(!1)},F=async I=>n.resolver(s,n.context,VG(I||u.mount,o,n.criteriaMode,n.shouldUseNativeValidation)),V=async I=>{const{errors:X}=await F(I);if(I)for(const Z of I){const we=ve(X,Z);we?wt(r.errors,Z,we):hn(r.errors,Z)}else r.errors=X;return X},J=async(I,X,Z={valid:!0})=>{for(const we in I){const he=I[we];if(he){const{_f:de,...ke}=he;if(de){const ft=u.array.has(de.name),pt=await C2(he,s,C,n.shouldUseNativeValidation&&!X,ft);if(pt[de.name]&&(Z.valid=!1,X))break;!X&&(ve(pt,de.name)?ft?jG(r.errors,pt,de.name):wt(r.errors,de.name,pt[de.name]):hn(r.errors,de.name))}ke&&await J(ke,X,Z)}}return Z.valid},G=()=>{for(const I of u.unMount){const X=ve(o,I);X&&(X._f.refs?X._f.refs.every(Z=>!P0(Z)):!P0(X._f.ref))&&fe(I)}u.unMount=new Set},ae=(I,X)=>(I&&X&&wt(s,I,X),!ca(ge(),i)),U=(I,X,Z)=>W5(I,u,{...l.mount?s:Ht(X)?i:Fo(I)?{[I]:X}:X},Z,X),te=I=>Ud(ve(l.mount?s:i,I,e.shouldUnregister?ve(i,I,[]):[])),L=(I,X,Z={})=>{const we=ve(o,I);let he=X;if(we){const de=we._f;de&&(!de.disabled&&wt(s,I,Q5(X,de)),he=Uh(de.ref)&&Ln(X)?"":X,X5(de.ref)?[...de.ref.options].forEach(ke=>ke.selected=he.includes(ke.value)):de.refs?Bd(de.ref)?de.refs.length>1?de.refs.forEach(ke=>(!ke.defaultChecked||!ke.disabled)&&(ke.checked=Array.isArray(he)?!!he.find(ft=>ft===ke.value):he===ke.value)):de.refs[0]&&(de.refs[0].checked=!!he):de.refs.forEach(ke=>ke.checked=ke.value===he):Hx(de.ref)?de.ref.value="":(de.ref.value=he,de.ref.type||g.values.next({name:I,values:{...s}})))}(Z.shouldDirty||Z.shouldTouch)&&A(I,he,Z.shouldTouch,Z.shouldDirty,!0),Z.shouldValidate&&le(I)},ie=(I,X,Z)=>{for(const we in X){const he=X[we],de=`${I}.${we}`,ke=ve(o,de);(u.array.has(I)||!Wh(he)||ke&&!ke._f)&&!xl(he)?ie(de,he,Z):L(de,he,Z)}},K=(I,X,Z={})=>{const we=ve(o,I),he=u.array.has(I),de=so(X);wt(s,I,de),he?(g.array.next({name:I,values:{...s}}),(m.isDirty||m.dirtyFields)&&Z.shouldDirty&&g.state.next({name:I,dirtyFields:A0(i,s),isDirty:ae(I,de)})):we&&!we._f&&!Ln(de)?ie(I,de,Z):L(I,de,Z),x2(I,u)&&g.state.next({...r}),g.values.next({name:I,values:{...s}}),!l.mount&&t()},Q=async I=>{const X=I.target;let Z=X.name,we=!0;const he=ve(o,Z),de=()=>X.type?O0(he._f):F5(I),ke=ft=>{we=Number.isNaN(ft)||ft===ve(s,Z,ft)};if(he){let ft,pt;const bn=de(),Cr=I.type===Bh.BLUR||I.type===Bh.FOCUS_OUT,ki=!WG(he._f)&&!n.resolver&&!ve(r.errors,Z)&&!he._f.deps||HG(Cr,ve(r.touchedFields,Z),r.isSubmitted,_,x),_o=x2(Z,u,Cr);wt(s,Z,bn),Cr?(he._f.onBlur&&he._f.onBlur(I),d&&d(0)):he._f.onChange&&he._f.onChange(I);const Vn=A(Z,bn,Cr,!1),Da=!Fr(Vn)||_o;if(!Cr&&g.values.next({name:Z,type:I.type,values:{...s}}),ki)return m.isValid&&b(),Da&&g.state.next({name:Z,..._o?{}:Vn});if(!Cr&&_o&&g.state.next({...r}),E(!0),n.resolver){const{errors:Ri}=await F([Z]);if(ke(bn),we){const zs=$2(r.errors,o,Z),Ti=$2(Ri,o,zs.name||Z);ft=Ti.error,Z=Ti.name,pt=Fr(Ri)}}else ft=(await C2(he,s,C,n.shouldUseNativeValidation))[Z],ke(bn),we&&(ft?pt=!1:m.isValid&&(pt=await J(o,!0)));we&&(he._f.deps&&le(he._f.deps),O(Z,pt,ft,Vn))}},W=(I,X)=>{if(ve(r.errors,X)&&I.focus)return I.focus(),1},le=async(I,X={})=>{let Z,we;const he=Yp(I);if(E(!0),n.resolver){const de=await V(Ht(I)?I:he);Z=Fr(de),we=I?!he.some(ke=>ve(de,ke)):Z}else I?(we=(await Promise.all(he.map(async de=>{const ke=ve(o,de);return await J(ke&&ke._f?{[de]:ke}:ke)}))).every(Boolean),!(!we&&!r.isValid)&&b()):we=Z=await J(o);return g.state.next({...!Fo(I)||m.isValid&&Z!==r.isValid?{}:{name:I},...n.resolver||!I?{isValid:Z}:{},errors:r.errors,isValidating:!1}),X.shouldFocus&&!we&&Gp(o,W,I?he:u.mount),we},ge=I=>{const X={...i,...l.mount?s:{}};return Ht(I)?X:Fo(I)?ve(X,I):I.map(Z=>ve(X,Z))},Ve=(I,X)=>({invalid:!!ve((X||r).errors,I),isDirty:!!ve((X||r).dirtyFields,I),isTouched:!!ve((X||r).touchedFields,I),error:ve((X||r).errors,I)}),Ue=I=>{I&&Yp(I).forEach(X=>hn(r.errors,X)),g.state.next({errors:I?r.errors:{}})},We=(I,X,Z)=>{const we=(ve(o,I,{_f:{}})._f||{}).ref;wt(r.errors,I,{...X,ref:we}),g.state.next({name:I,errors:r.errors,isValid:!1}),Z&&Z.shouldFocus&&we&&we.focus&&we.focus()},Me=(I,X)=>ds(I)?g.values.subscribe({next:Z=>I(U(void 0,X),Z)}):U(I,X,!0),fe=(I,X={})=>{for(const Z of I?Yp(I):u.mount)u.mount.delete(Z),u.array.delete(Z),X.keepValue||(hn(o,Z),hn(s,Z)),!X.keepError&&hn(r.errors,Z),!X.keepDirty&&hn(r.dirtyFields,Z),!X.keepTouched&&hn(r.touchedFields,Z),!n.shouldUnregister&&!X.keepDefaultValue&&hn(i,Z);g.values.next({values:{...s}}),g.state.next({...r,...X.keepDirty?{isDirty:ae()}:{}}),!X.keepIsValid&&b()},xe=({disabled:I,name:X,field:Z,fields:we,value:he})=>{if(No(I)){const de=I?void 0:Ht(he)?O0(Z?Z._f:ve(we,X)._f):he;wt(s,X,de),A(X,de,!1,!1,!0)}},$e=(I,X={})=>{let Z=ve(o,I);const we=No(X.disabled);return wt(o,I,{...Z||{},_f:{...Z&&Z._f?Z._f:{ref:{name:I}},name:I,mount:!0,...X}}),u.mount.add(I),Z?xe({field:Z,disabled:X.disabled,name:I}):M(I,!0,X.value),{...we?{disabled:X.disabled}:{},...n.progressive?{required:!!X.required,min:iu(X.min),max:iu(X.max),minLength:iu(X.minLength),maxLength:iu(X.maxLength),pattern:iu(X.pattern)}:{},name:I,onChange:Q,onBlur:Q,ref:he=>{if(he){$e(I,X),Z=ve(o,I);const de=Ht(he.value)&&he.querySelectorAll&&he.querySelectorAll("input,select,textarea")[0]||he,ke=UG(de),ft=Z._f.refs||[];if(ke?ft.find(pt=>pt===de):de===Z._f.ref)return;wt(o,I,{_f:{...Z._f,...ke?{refs:[...ft.filter(P0),de,...Array.isArray(ve(i,I))?[{}]:[]],ref:{type:de.type,name:I}}:{ref:de}}}),M(I,!1,void 0,de)}else Z=ve(o,I,{}),Z._f&&(Z._f.mount=!1),(n.shouldUnregister||X.shouldUnregister)&&!(j5(u.array,I)&&l.action)&&u.unMount.add(I)}}},Ae=()=>n.shouldFocusError&&Gp(o,W,u.mount),Oe=I=>{No(I)&&(g.state.next({disabled:I}),Gp(o,X=>{X.disabled=I},0,!1))},je=(I,X)=>async Z=>{Z&&(Z.preventDefault&&Z.preventDefault(),Z.persist&&Z.persist());let we=so(s);if(g.state.next({isSubmitting:!0}),n.resolver){const{errors:he,values:de}=await F();r.errors=he,we=de}else await J(o);hn(r.errors,"root"),Fr(r.errors)?(g.state.next({errors:{}}),await I(we,Z)):(X&&await X({...r.errors},Z),Ae(),setTimeout(Ae)),g.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:Fr(r.errors),submitCount:r.submitCount+1,errors:r.errors})},Ot=(I,X={})=>{ve(o,I)&&(Ht(X.defaultValue)?K(I,ve(i,I)):(K(I,X.defaultValue),wt(i,I,X.defaultValue)),X.keepTouched||hn(r.touchedFields,I),X.keepDirty||(hn(r.dirtyFields,I),r.isDirty=X.defaultValue?ae(I,ve(i,I)):ae()),X.keepError||(hn(r.errors,I),m.isValid&&b()),g.state.next({...r}))},ct=(I,X={})=>{const Z=I?so(I):i,we=so(Z),he=I&&!Fr(I)?we:i;if(X.keepDefaultValues||(i=Z),!X.keepValues){if(X.keepDirtyValues||y)for(const de of u.mount)ve(r.dirtyFields,de)?wt(he,de,ve(s,de)):K(de,ve(he,de));else{if(Ux&&Ht(I))for(const de of u.mount){const ke=ve(o,de);if(ke&&ke._f){const ft=Array.isArray(ke._f.refs)?ke._f.refs[0]:ke._f.ref;if(Uh(ft)){const pt=ft.closest("form");if(pt){pt.reset();break}}}}o={}}s=e.shouldUnregister?X.keepDefaultValues?so(i):{}:so(he),g.array.next({values:{...he}}),g.values.next({values:{...he}})}u={mount:new Set,unMount:new Set,array:new Set,watch:new Set,watchAll:!1,focus:""},!l.mount&&t(),l.mount=!m.isValid||!!X.keepIsValid,l.watch=!!e.shouldUnregister,g.state.next({submitCount:X.keepSubmitCount?r.submitCount:0,isDirty:X.keepDirty?r.isDirty:!!(X.keepDefaultValues&&!ca(I,i)),isSubmitted:X.keepIsSubmitted?r.isSubmitted:!1,dirtyFields:X.keepDirtyValues?r.dirtyFields:X.keepDefaultValues&&I?A0(i,I):{},touchedFields:X.keepTouched?r.touchedFields:{},errors:X.keepErrors?r.errors:{},isSubmitSuccessful:X.keepIsSubmitSuccessful?r.isSubmitSuccessful:!1,isSubmitting:!1})},Yt=(I,X)=>ct(ds(I)?I(s):I,X);return{control:{register:$e,unregister:fe,getFieldState:Ve,handleSubmit:je,setError:We,_executeSchema:F,_getWatch:U,_getDirty:ae,_updateValid:b,_removeUnmounted:G,_updateFieldArray:k,_updateDisabledField:xe,_getFieldArray:te,_reset:ct,_resetDefaultValues:()=>ds(n.defaultValues)&&n.defaultValues().then(I=>{Yt(I,n.resetOptions),g.state.next({isLoading:!1})}),_updateFormState:I=>{r={...r,...I}},_disableForm:Oe,_subjects:g,_proxyFormState:m,get _fields(){return o},get _formValues(){return s},get _state(){return l},set _state(I){l=I},get _defaultValues(){return i},get _names(){return u},set _names(I){u=I},get _formState(){return r},set _formState(I){r=I},get _options(){return n},set _options(I){n={...n,...I}}},trigger:le,register:$e,handleSubmit:je,watch:Me,setValue:K,getValues:ge,reset:Yt,resetField:Ot,clearErrors:Ue,unregister:fe,setError:We,setFocus:(I,X={})=>{const Z=ve(o,I),we=Z&&Z._f;if(we){const he=we.refs?we.refs[0]:we.ref;he.focus&&(he.focus(),X.shouldSelect&&he.select())}},getFieldState:Ve}}function XG(e={}){const t=Fe.useRef(),n=Fe.useRef(),[r,o]=Fe.useState({isDirty:!1,isValidating:!1,isLoading:ds(e.defaultValues),isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,submitCount:0,dirtyFields:{},touchedFields:{},errors:{},disabled:!1,defaultValues:ds(e.defaultValues)?void 0:e.defaultValues});t.current||(t.current={...GG(e,()=>o(s=>({...s}))),formState:r});const i=t.current.control;return i._options=e,Vx({subject:i._subjects.state,next:s=>{U5(s,i._proxyFormState,i._updateFormState,!0)&&o({...i._formState})}}),Fe.useEffect(()=>i._disableForm(e.disabled),[i,e.disabled]),Fe.useEffect(()=>{if(i._proxyFormState.isDirty){const s=i._getDirty();s!==r.isDirty&&i._subjects.state.next({isDirty:s})}},[i,r.isDirty]),Fe.useEffect(()=>{e.values&&!ca(e.values,n.current)?(i._reset(e.values,i._options.resetOptions),n.current=e.values):i._resetDefaultValues()},[e.values,i]),Fe.useEffect(()=>{i._state.mount||(i._updateValid(),i._state.mount=!0),i._state.watch&&(i._state.watch=!1,i._subjects.state.next({...i._formState})),i._removeUnmounted()}),t.current.formState=B5(r,i),t.current}var k2=function(e,t,n){if(e&&"reportValidity"in e){var r=ve(n,t);e.setCustomValidity(r&&r.message||""),e.reportValidity()}},J5=function(e,t){var n=function(o){var i=t.fields[o];i&&i.ref&&"reportValidity"in i.ref?k2(i.ref,o,e):i.refs&&i.refs.forEach(function(s){return k2(s,o,e)})};for(var r in t.fields)n(r)},ZG=function(e,t){t.shouldUseNativeValidation&&J5(e,t);var n={};for(var r in e){var o=ve(t.fields,r),i=Object.assign(e[r]||{},{ref:o&&o.ref});if(QG(t.names||Object.keys(e),r)){var s=Object.assign({},qG(ve(n,r)));wt(s,"root",i),wt(n,r,s)}else wt(n,r,i)}return n},qG=function(e){return Array.isArray(e)?e.filter(Boolean):[]},QG=function(e,t){return e.some(function(n){return n.startsWith(t+".")})},JG=function(e,t){for(var n={};e.length;){var r=e[0],o=r.code,i=r.message,s=r.path.join(".");if(!n[s])if("unionErrors"in r){var l=r.unionErrors[0].errors[0];n[s]={message:l.message,type:l.code}}else n[s]={message:i,type:o};if("unionErrors"in r&&r.unionErrors.forEach(function(h){return h.errors.forEach(function(m){return e.push(m)})}),t){var u=n[s].types,d=u&&u[r.code];n[s]=K5(s,t,n,o,d?[].concat(d,r.message):r.message)}e.shift()}return n},eX=function(e,t,n){return n===void 0&&(n={}),function(r,o,i){try{return Promise.resolve(function(s,l){try{var u=Promise.resolve(e[n.mode==="sync"?"parse":"parseAsync"](r,t)).then(function(d){return i.shouldUseNativeValidation&&J5({},i),{errors:{},values:n.raw?r:d}})}catch(d){return l(d)}return u&&u.then?u.then(void 0,l):u}(0,function(s){if(function(l){return l.errors!=null}(s))return{values:{},errors:ZG(JG(s.errors,!i.shouldUseNativeValidation&&i.criteriaMode==="all"),i)};throw s}))}catch(s){return Promise.reject(s)}}},mt;(function(e){e.assertEqual=o=>o;function t(o){}e.assertIs=t;function n(o){throw new Error}e.assertNever=n,e.arrayToEnum=o=>{const i={};for(const s of o)i[s]=s;return i},e.getValidEnumValues=o=>{const i=e.objectKeys(o).filter(l=>typeof o[o[l]]!="number"),s={};for(const l of i)s[l]=o[l];return e.objectValues(s)},e.objectValues=o=>e.objectKeys(o).map(function(i){return o[i]}),e.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{const i=[];for(const s in o)Object.prototype.hasOwnProperty.call(o,s)&&i.push(s);return i},e.find=(o,i)=>{for(const s of o)if(i(s))return s},e.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&isFinite(o)&&Math.floor(o)===o;function r(o,i=" | "){return o.map(s=>typeof s=="string"?`'${s}'`:s).join(i)}e.joinValues=r,e.jsonStringifyReplacer=(o,i)=>typeof i=="bigint"?i.toString():i})(mt||(mt={}));var R2;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(R2||(R2={}));const be=mt.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ta=e=>{switch(typeof e){case"undefined":return be.undefined;case"string":return be.string;case"number":return isNaN(e)?be.nan:be.number;case"boolean":return be.boolean;case"function":return be.function;case"bigint":return be.bigint;case"symbol":return be.symbol;case"object":return Array.isArray(e)?be.array:e===null?be.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?be.promise:typeof Map<"u"&&e instanceof Map?be.map:typeof Set<"u"&&e instanceof Set?be.set:typeof Date<"u"&&e instanceof Date?be.date:be.object;default:return be.unknown}},pe=mt.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"]);class Bo 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(i){return i.message},r={_errors:[]},o=i=>{for(const s of i.issues)if(s.code==="invalid_union")s.unionErrors.map(o);else if(s.code==="invalid_return_type")o(s.returnTypeError);else if(s.code==="invalid_arguments")o(s.argumentsError);else if(s.path.length===0)r._errors.push(n(s));else{let l=r,u=0;for(;un.message){const n={},r=[];for(const o of this.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(t(o))):r.push(t(o));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}}Bo.create=e=>new Bo(e);const Kh=(e,t)=>{let n;switch(e.code){case pe.invalid_type:e.received===be.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case pe.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,mt.jsonStringifyReplacer)}`;break;case pe.unrecognized_keys:n=`Unrecognized key(s) in object: ${mt.joinValues(e.keys,", ")}`;break;case pe.invalid_union:n="Invalid input";break;case pe.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${mt.joinValues(e.options)}`;break;case pe.invalid_enum_value:n=`Invalid enum value. Expected ${mt.joinValues(e.options)}, received '${e.received}'`;break;case pe.invalid_arguments:n="Invalid function arguments";break;case pe.invalid_return_type:n="Invalid function return type";break;case pe.invalid_date:n="Invalid date";break;case pe.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}"`:mt.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case pe.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 pe.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 pe.custom:n="Invalid input";break;case pe.invalid_intersection_types:n="Intersection results could not be merged";break;case pe.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case pe.not_finite:n="Number must be finite";break;default:n=t.defaultError,mt.assertNever(e)}return{message:n}};let tX=Kh;function S1(){return tX}const E1=e=>{const{data:t,path:n,errorMaps:r,issueData:o}=e,i=[...n,...o.path||[]],s={...o,path:i};let l="";const u=r.filter(d=>!!d).slice().reverse();for(const d of u)l=d(s,{data:t,defaultError:l}).message;return{...o,path:i,message:o.message||l}};function Ee(e,t){const n=E1({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,S1(),Kh].filter(r=>!!r)});e.common.issues.push(n)}class zn{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 o of n){if(o.status==="aborted")return Ze;o.status==="dirty"&&t.dirty(),r.push(o.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){const r=[];for(const o of n)r.push({key:await o.key,value:await o.value});return zn.mergeObjectSync(t,r)}static mergeObjectSync(t,n){const r={};for(const o of n){const{key:i,value:s}=o;if(i.status==="aborted"||s.status==="aborted")return Ze;i.status==="dirty"&&t.dirty(),s.status==="dirty"&&t.dirty(),i.value!=="__proto__"&&(typeof s.value<"u"||o.alwaysSet)&&(r[i.value]=s.value)}return{status:t.value,value:r}}}const Ze=Object.freeze({status:"aborted"}),nX=e=>({status:"dirty",value:e}),rr=e=>({status:"valid",value:e}),T2=e=>e.status==="aborted",P2=e=>e.status==="dirty",Yh=e=>e.status==="valid",C1=e=>typeof Promise<"u"&&e instanceof Promise;var Ne;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t==null?void 0:t.message})(Ne||(Ne={}));class Ko{constructor(t,n,r,o){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=o}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 A2=(e,t)=>{if(Yh(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 Bo(e.common.issues);return this._error=n,this._error}}};function Xe(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:r,description:o}=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:o}:{errorMap:(s,l)=>s.code!=="invalid_type"?{message:l.defaultError}:typeof l.data>"u"?{message:r??l.defaultError}:{message:n??l.defaultError},description:o}}class rt{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.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this)}get description(){return this._def.description}_getType(t){return ta(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:ta(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new zn,ctx:{common:t.parent.common,data:t.data,parsedType:ta(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const n=this._parse(t);if(C1(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 o={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:ta(t)},i=this._parseSync({data:t,path:o.path,parent:o});return A2(o,i)}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:ta(t)},o=this._parse({data:t,path:r.path,parent:r}),i=await(C1(o)?o:Promise.resolve(o));return A2(r,i)}refine(t,n){const r=o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n;return this._refinement((o,i)=>{const s=t(o),l=()=>i.addIssue({code:pe.custom,...r(o)});return typeof Promise<"u"&&s instanceof Promise?s.then(u=>u?!0:(l(),!1)):s?!0:(l(),!1)})}refinement(t,n){return this._refinement((r,o)=>t(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(t){return new Si({schema:this,typeName:ze.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}optional(){return bs.create(this,this._def)}nullable(){return uc.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Uo.create(this,this._def)}promise(){return ad.create(this,this._def)}or(t){return Zh.create([this,t],this._def)}and(t){return qh.create(this,t,this._def)}transform(t){return new Si({...Xe(this._def),schema:this,typeName:ze.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const n=typeof t=="function"?t:()=>t;return new nm({...Xe(this._def),innerType:this,defaultValue:n,typeName:ze.ZodDefault})}brand(){return new hX({typeName:ze.ZodBranded,type:this,...Xe(this._def)})}catch(t){const n=typeof t=="function"?t:()=>t;return new O1({...Xe(this._def),innerType:this,catchValue:n,typeName:ze.ZodCatch})}describe(t){const n=this.constructor;return new n({...this._def,description:t})}pipe(t){return sg.create(this,t)}readonly(){return N1.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const rX=/^c[^\s-]{8,}$/i,oX=/^[a-z][a-z0-9]*$/,iX=/^[0-9A-HJKMNP-TV-Z]{26}$/,sX=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,aX=/^(?!\.)(?!.*\.\.)([A-Z0-9_+-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,lX="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let M0;const cX=/^(((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}))$/,uX=/^(([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})))$/,dX=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 fX(e,t){return!!((t==="v4"||!t)&&cX.test(e)||(t==="v6"||!t)&&uX.test(e))}class di extends rt{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==be.string){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_type,expected:be.string,received:i.parsedType}),Ze}const r=new zn;let o;for(const i of this._def.checks)if(i.kind==="min")t.data.lengthi.value&&(o=this._getOrReturnCtx(t,o),Ee(o,{code:pe.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){const s=t.data.length>i.value,l=t.data.lengtht.test(o),{validation:n,code:pe.invalid_string,...Ne.errToObj(r)})}_addCheck(t){return new di({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...Ne.errToObj(t)})}url(t){return this._addCheck({kind:"url",...Ne.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...Ne.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...Ne.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...Ne.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...Ne.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...Ne.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...Ne.errToObj(t)})}datetime(t){var n;return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof(t==null?void 0:t.precision)>"u"?null:t==null?void 0:t.precision,offset:(n=t==null?void 0:t.offset)!==null&&n!==void 0?n:!1,...Ne.errToObj(t==null?void 0:t.message)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...Ne.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n==null?void 0:n.position,...Ne.errToObj(n==null?void 0:n.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...Ne.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...Ne.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...Ne.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...Ne.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...Ne.errToObj(n)})}nonempty(t){return this.min(1,Ne.errToObj(t))}trim(){return new di({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new di({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new di({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}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 di({checks:[],typeName:ze.ZodString,coerce:(t=e==null?void 0:e.coerce)!==null&&t!==void 0?t:!1,...Xe(e)})};function pX(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,o=n>r?n:r,i=parseInt(e.toFixed(o).replace(".","")),s=parseInt(t.toFixed(o).replace(".",""));return i%s/Math.pow(10,o)}class ac extends rt{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)!==be.number){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_type,expected:be.number,received:i.parsedType}),Ze}let r;const o=new zn;for(const i of this._def.checks)i.kind==="int"?mt.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.invalid_type,expected:"integer",received:"float",message:i.message}),o.dirty()):i.kind==="min"?(i.inclusive?t.datai.value:t.data>=i.value)&&(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),o.dirty()):i.kind==="multipleOf"?pX(t.data,i.value)!==0&&(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):i.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.not_finite,message:i.message}),o.dirty()):mt.assertNever(i);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,Ne.toString(n))}gt(t,n){return this.setLimit("min",t,!1,Ne.toString(n))}lte(t,n){return this.setLimit("max",t,!0,Ne.toString(n))}lt(t,n){return this.setLimit("max",t,!1,Ne.toString(n))}setLimit(t,n,r,o){return new ac({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:Ne.toString(o)}]})}_addCheck(t){return new ac({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:Ne.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Ne.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Ne.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Ne.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Ne.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:Ne.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:Ne.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Ne.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Ne.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"&&mt.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 ac({checks:[],typeName:ze.ZodNumber,coerce:(e==null?void 0:e.coerce)||!1,...Xe(e)});class lc extends rt{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)!==be.bigint){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_type,expected:be.bigint,received:i.parsedType}),Ze}let r;const o=new zn;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?t.datai.value:t.data>=i.value)&&(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),o.dirty()):i.kind==="multipleOf"?t.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):mt.assertNever(i);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,Ne.toString(n))}gt(t,n){return this.setLimit("min",t,!1,Ne.toString(n))}lte(t,n){return this.setLimit("max",t,!0,Ne.toString(n))}lt(t,n){return this.setLimit("max",t,!1,Ne.toString(n))}setLimit(t,n,r,o){return new lc({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:Ne.toString(o)}]})}_addCheck(t){return new lc({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Ne.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Ne.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Ne.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Ne.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:Ne.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 lc({checks:[],typeName:ze.ZodBigInt,coerce:(t=e==null?void 0:e.coerce)!==null&&t!==void 0?t:!1,...Xe(e)})};class $1 extends rt{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==be.boolean){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.boolean,received:r.parsedType}),Ze}return rr(t.data)}}$1.create=e=>new $1({typeName:ze.ZodBoolean,coerce:(e==null?void 0:e.coerce)||!1,...Xe(e)});class sd extends rt{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==be.date){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_type,expected:be.date,received:i.parsedType}),Ze}if(isNaN(t.data.getTime())){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_date}),Ze}const r=new zn;let o;for(const i of this._def.checks)i.kind==="min"?t.data.getTime()i.value&&(o=this._getOrReturnCtx(t,o),Ee(o,{code:pe.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):mt.assertNever(i);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new sd({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:Ne.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:Ne.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 sd({checks:[],coerce:(e==null?void 0:e.coerce)||!1,typeName:ze.ZodDate,...Xe(e)});class k1 extends rt{_parse(t){if(this._getType(t)!==be.symbol){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.symbol,received:r.parsedType}),Ze}return rr(t.data)}}k1.create=e=>new k1({typeName:ze.ZodSymbol,...Xe(e)});class Gh extends rt{_parse(t){if(this._getType(t)!==be.undefined){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.undefined,received:r.parsedType}),Ze}return rr(t.data)}}Gh.create=e=>new Gh({typeName:ze.ZodUndefined,...Xe(e)});class Xh extends rt{_parse(t){if(this._getType(t)!==be.null){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.null,received:r.parsedType}),Ze}return rr(t.data)}}Xh.create=e=>new Xh({typeName:ze.ZodNull,...Xe(e)});class R1 extends rt{constructor(){super(...arguments),this._any=!0}_parse(t){return rr(t.data)}}R1.create=e=>new R1({typeName:ze.ZodAny,...Xe(e)});class Tl extends rt{constructor(){super(...arguments),this._unknown=!0}_parse(t){return rr(t.data)}}Tl.create=e=>new Tl({typeName:ze.ZodUnknown,...Xe(e)});class Rs extends rt{_parse(t){const n=this._getOrReturnCtx(t);return Ee(n,{code:pe.invalid_type,expected:be.never,received:n.parsedType}),Ze}}Rs.create=e=>new Rs({typeName:ze.ZodNever,...Xe(e)});class T1 extends rt{_parse(t){if(this._getType(t)!==be.undefined){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.void,received:r.parsedType}),Ze}return rr(t.data)}}T1.create=e=>new T1({typeName:ze.ZodVoid,...Xe(e)});class Uo extends rt{_parse(t){const{ctx:n,status:r}=this._processInputParams(t),o=this._def;if(n.parsedType!==be.array)return Ee(n,{code:pe.invalid_type,expected:be.array,received:n.parsedType}),Ze;if(o.exactLength!==null){const s=n.data.length>o.exactLength.value,l=n.data.lengtho.maxLength.value&&(Ee(n,{code:pe.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((s,l)=>o.type._parseAsync(new Ko(n,s,n.path,l)))).then(s=>zn.mergeArray(r,s));const i=[...n.data].map((s,l)=>o.type._parseSync(new Ko(n,s,n.path,l)));return zn.mergeArray(r,i)}get element(){return this._def.type}min(t,n){return new Uo({...this._def,minLength:{value:t,message:Ne.toString(n)}})}max(t,n){return new Uo({...this._def,maxLength:{value:t,message:Ne.toString(n)}})}length(t,n){return new Uo({...this._def,exactLength:{value:t,message:Ne.toString(n)}})}nonempty(t){return this.min(1,t)}}Uo.create=(e,t)=>new Uo({type:e,minLength:null,maxLength:null,exactLength:null,typeName:ze.ZodArray,...Xe(t)});function ol(e){if(e instanceof Vt){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=bs.create(ol(r))}return new Vt({...e._def,shape:()=>t})}else return e instanceof Uo?new Uo({...e._def,type:ol(e.element)}):e instanceof bs?bs.create(ol(e.unwrap())):e instanceof uc?uc.create(ol(e.unwrap())):e instanceof _i?_i.create(e.items.map(t=>ol(t))):e}class Vt extends rt{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=mt.objectKeys(t);return this._cached={shape:t,keys:n}}_parse(t){if(this._getType(t)!==be.object){const d=this._getOrReturnCtx(t);return Ee(d,{code:pe.invalid_type,expected:be.object,received:d.parsedType}),Ze}const{status:r,ctx:o}=this._processInputParams(t),{shape:i,keys:s}=this._getCached(),l=[];if(!(this._def.catchall instanceof Rs&&this._def.unknownKeys==="strip"))for(const d in o.data)s.includes(d)||l.push(d);const u=[];for(const d of s){const h=i[d],m=o.data[d];u.push({key:{status:"valid",value:d},value:h._parse(new Ko(o,m,o.path,d)),alwaysSet:d in o.data})}if(this._def.catchall instanceof Rs){const d=this._def.unknownKeys;if(d==="passthrough")for(const h of l)u.push({key:{status:"valid",value:h},value:{status:"valid",value:o.data[h]}});else if(d==="strict")l.length>0&&(Ee(o,{code:pe.unrecognized_keys,keys:l}),r.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const d=this._def.catchall;for(const h of l){const m=o.data[h];u.push({key:{status:"valid",value:h},value:d._parse(new Ko(o,m,o.path,h)),alwaysSet:h in o.data})}}return o.common.async?Promise.resolve().then(async()=>{const d=[];for(const h of u){const m=await h.key;d.push({key:m,value:await h.value,alwaysSet:h.alwaysSet})}return d}).then(d=>zn.mergeObjectSync(r,d)):zn.mergeObjectSync(r,u)}get shape(){return this._def.shape()}strict(t){return Ne.errToObj,new Vt({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{var o,i,s,l;const u=(s=(i=(o=this._def).errorMap)===null||i===void 0?void 0:i.call(o,n,r).message)!==null&&s!==void 0?s:r.defaultError;return n.code==="unrecognized_keys"?{message:(l=Ne.errToObj(t).message)!==null&&l!==void 0?l:u}:{message:u}}}:{}})}strip(){return new Vt({...this._def,unknownKeys:"strip"})}passthrough(){return new Vt({...this._def,unknownKeys:"passthrough"})}extend(t){return new Vt({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new Vt({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:ze.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new Vt({...this._def,catchall:t})}pick(t){const n={};return mt.objectKeys(t).forEach(r=>{t[r]&&this.shape[r]&&(n[r]=this.shape[r])}),new Vt({...this._def,shape:()=>n})}omit(t){const n={};return mt.objectKeys(this.shape).forEach(r=>{t[r]||(n[r]=this.shape[r])}),new Vt({...this._def,shape:()=>n})}deepPartial(){return ol(this)}partial(t){const n={};return mt.objectKeys(this.shape).forEach(r=>{const o=this.shape[r];t&&!t[r]?n[r]=o:n[r]=o.optional()}),new Vt({...this._def,shape:()=>n})}required(t){const n={};return mt.objectKeys(this.shape).forEach(r=>{if(t&&!t[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof bs;)i=i._def.innerType;n[r]=i}}),new Vt({...this._def,shape:()=>n})}keyof(){return e3(mt.objectKeys(this.shape))}}Vt.create=(e,t)=>new Vt({shape:()=>e,unknownKeys:"strip",catchall:Rs.create(),typeName:ze.ZodObject,...Xe(t)});Vt.strictCreate=(e,t)=>new Vt({shape:()=>e,unknownKeys:"strict",catchall:Rs.create(),typeName:ze.ZodObject,...Xe(t)});Vt.lazycreate=(e,t)=>new Vt({shape:e,unknownKeys:"strip",catchall:Rs.create(),typeName:ze.ZodObject,...Xe(t)});class Zh extends rt{_parse(t){const{ctx:n}=this._processInputParams(t),r=this._def.options;function o(i){for(const l of i)if(l.result.status==="valid")return l.result;for(const l of i)if(l.result.status==="dirty")return n.common.issues.push(...l.ctx.common.issues),l.result;const s=i.map(l=>new Bo(l.ctx.common.issues));return Ee(n,{code:pe.invalid_union,unionErrors:s}),Ze}if(n.common.async)return Promise.all(r.map(async i=>{const s={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:s}),ctx:s}})).then(o);{let i;const s=[];for(const u of r){const d={...n,common:{...n.common,issues:[]},parent:null},h=u._parseSync({data:n.data,path:n.path,parent:d});if(h.status==="valid")return h;h.status==="dirty"&&!i&&(i={result:h,ctx:d}),d.common.issues.length&&s.push(d.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;const l=s.map(u=>new Bo(u));return Ee(n,{code:pe.invalid_union,unionErrors:l}),Ze}}get options(){return this._def.options}}Zh.create=(e,t)=>new Zh({options:e,typeName:ze.ZodUnion,...Xe(t)});const Zp=e=>e instanceof Jh?Zp(e.schema):e instanceof Si?Zp(e.innerType()):e instanceof em?[e.value]:e instanceof Ta?e.options:e instanceof tm?Object.keys(e.enum):e instanceof nm?Zp(e._def.innerType):e instanceof Gh?[void 0]:e instanceof Xh?[null]:null;class Yx extends rt{_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.object)return Ee(n,{code:pe.invalid_type,expected:be.object,received:n.parsedType}),Ze;const r=this.discriminator,o=n.data[r],i=this.optionsMap.get(o);return i?n.common.async?i._parseAsync({data:n.data,path:n.path,parent:n}):i._parseSync({data:n.data,path:n.path,parent:n}):(Ee(n,{code:pe.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),Ze)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){const o=new Map;for(const i of n){const s=Zp(i.shape[t]);if(!s)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const l of s){if(o.has(l))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(l)}`);o.set(l,i)}}return new Yx({typeName:ze.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:o,...Xe(r)})}}function P1(e,t){const n=ta(e),r=ta(t);if(e===t)return{valid:!0,data:e};if(n===be.object&&r===be.object){const o=mt.objectKeys(t),i=mt.objectKeys(e).filter(l=>o.indexOf(l)!==-1),s={...e,...t};for(const l of i){const u=P1(e[l],t[l]);if(!u.valid)return{valid:!1};s[l]=u.data}return{valid:!0,data:s}}else if(n===be.array&&r===be.array){if(e.length!==t.length)return{valid:!1};const o=[];for(let i=0;i{if(T2(i)||T2(s))return Ze;const l=P1(i.value,s.value);return l.valid?((P2(i)||P2(s))&&n.dirty(),{status:n.value,value:l.data}):(Ee(r,{code:pe.invalid_intersection_types}),Ze)};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(([i,s])=>o(i,s)):o(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}qh.create=(e,t,n)=>new qh({left:e,right:t,typeName:ze.ZodIntersection,...Xe(n)});class _i extends rt{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.array)return Ee(r,{code:pe.invalid_type,expected:be.array,received:r.parsedType}),Ze;if(r.data.lengththis._def.items.length&&(Ee(r,{code:pe.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const i=[...r.data].map((s,l)=>{const u=this._def.items[l]||this._def.rest;return u?u._parse(new Ko(r,s,r.path,l)):null}).filter(s=>!!s);return r.common.async?Promise.all(i).then(s=>zn.mergeArray(n,s)):zn.mergeArray(n,i)}get items(){return this._def.items}rest(t){return new _i({...this._def,rest:t})}}_i.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new _i({items:e,typeName:ze.ZodTuple,rest:null,...Xe(t)})};class Qh extends rt{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!==be.object)return Ee(r,{code:pe.invalid_type,expected:be.object,received:r.parsedType}),Ze;const o=[],i=this._def.keyType,s=this._def.valueType;for(const l in r.data)o.push({key:i._parse(new Ko(r,l,r.path,l)),value:s._parse(new Ko(r,r.data[l],r.path,l))});return r.common.async?zn.mergeObjectAsync(n,o):zn.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof rt?new Qh({keyType:t,valueType:n,typeName:ze.ZodRecord,...Xe(r)}):new Qh({keyType:di.create(),valueType:t,typeName:ze.ZodRecord,...Xe(n)})}}class A1 extends rt{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!==be.map)return Ee(r,{code:pe.invalid_type,expected:be.map,received:r.parsedType}),Ze;const o=this._def.keyType,i=this._def.valueType,s=[...r.data.entries()].map(([l,u],d)=>({key:o._parse(new Ko(r,l,r.path,[d,"key"])),value:i._parse(new Ko(r,u,r.path,[d,"value"]))}));if(r.common.async){const l=new Map;return Promise.resolve().then(async()=>{for(const u of s){const d=await u.key,h=await u.value;if(d.status==="aborted"||h.status==="aborted")return Ze;(d.status==="dirty"||h.status==="dirty")&&n.dirty(),l.set(d.value,h.value)}return{status:n.value,value:l}})}else{const l=new Map;for(const u of s){const d=u.key,h=u.value;if(d.status==="aborted"||h.status==="aborted")return Ze;(d.status==="dirty"||h.status==="dirty")&&n.dirty(),l.set(d.value,h.value)}return{status:n.value,value:l}}}}A1.create=(e,t,n)=>new A1({valueType:t,keyType:e,typeName:ze.ZodMap,...Xe(n)});class cc extends rt{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.set)return Ee(r,{code:pe.invalid_type,expected:be.set,received:r.parsedType}),Ze;const o=this._def;o.minSize!==null&&r.data.sizeo.maxSize.value&&(Ee(r,{code:pe.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());const i=this._def.valueType;function s(u){const d=new Set;for(const h of u){if(h.status==="aborted")return Ze;h.status==="dirty"&&n.dirty(),d.add(h.value)}return{status:n.value,value:d}}const l=[...r.data.values()].map((u,d)=>i._parse(new Ko(r,u,r.path,d)));return r.common.async?Promise.all(l).then(u=>s(u)):s(l)}min(t,n){return new cc({...this._def,minSize:{value:t,message:Ne.toString(n)}})}max(t,n){return new cc({...this._def,maxSize:{value:t,message:Ne.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}}cc.create=(e,t)=>new cc({valueType:e,minSize:null,maxSize:null,typeName:ze.ZodSet,...Xe(t)});class Pu extends rt{constructor(){super(...arguments),this.validate=this.implement}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.function)return Ee(n,{code:pe.invalid_type,expected:be.function,received:n.parsedType}),Ze;function r(l,u){return E1({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,S1(),Kh].filter(d=>!!d),issueData:{code:pe.invalid_arguments,argumentsError:u}})}function o(l,u){return E1({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,S1(),Kh].filter(d=>!!d),issueData:{code:pe.invalid_return_type,returnTypeError:u}})}const i={errorMap:n.common.contextualErrorMap},s=n.data;if(this._def.returns instanceof ad){const l=this;return rr(async function(...u){const d=new Bo([]),h=await l._def.args.parseAsync(u,i).catch(y=>{throw d.addIssue(r(u,y)),d}),m=await Reflect.apply(s,this,h);return await l._def.returns._def.type.parseAsync(m,i).catch(y=>{throw d.addIssue(o(m,y)),d})})}else{const l=this;return rr(function(...u){const d=l._def.args.safeParse(u,i);if(!d.success)throw new Bo([r(u,d.error)]);const h=Reflect.apply(s,this,d.data),m=l._def.returns.safeParse(h,i);if(!m.success)throw new Bo([o(h,m.error)]);return m.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new Pu({...this._def,args:_i.create(t).rest(Tl.create())})}returns(t){return new Pu({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new Pu({args:t||_i.create([]).rest(Tl.create()),returns:n||Tl.create(),typeName:ze.ZodFunction,...Xe(r)})}}class Jh extends rt{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})}}Jh.create=(e,t)=>new Jh({getter:e,typeName:ze.ZodLazy,...Xe(t)});class em extends rt{_parse(t){if(t.data!==this._def.value){const n=this._getOrReturnCtx(t);return Ee(n,{received:n.data,code:pe.invalid_literal,expected:this._def.value}),Ze}return{status:"valid",value:t.data}}get value(){return this._def.value}}em.create=(e,t)=>new em({value:e,typeName:ze.ZodLiteral,...Xe(t)});function e3(e,t){return new Ta({values:e,typeName:ze.ZodEnum,...Xe(t)})}class Ta extends rt{_parse(t){if(typeof t.data!="string"){const n=this._getOrReturnCtx(t),r=this._def.values;return Ee(n,{expected:mt.joinValues(r),received:n.parsedType,code:pe.invalid_type}),Ze}if(this._def.values.indexOf(t.data)===-1){const n=this._getOrReturnCtx(t),r=this._def.values;return Ee(n,{received:n.data,code:pe.invalid_enum_value,options:r}),Ze}return rr(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 Ta.create(t)}exclude(t){return Ta.create(this.options.filter(n=>!t.includes(n)))}}Ta.create=e3;class tm extends rt{_parse(t){const n=mt.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==be.string&&r.parsedType!==be.number){const o=mt.objectValues(n);return Ee(r,{expected:mt.joinValues(o),received:r.parsedType,code:pe.invalid_type}),Ze}if(n.indexOf(t.data)===-1){const o=mt.objectValues(n);return Ee(r,{received:r.data,code:pe.invalid_enum_value,options:o}),Ze}return rr(t.data)}get enum(){return this._def.values}}tm.create=(e,t)=>new tm({values:e,typeName:ze.ZodNativeEnum,...Xe(t)});class ad extends rt{unwrap(){return this._def.type}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.promise&&n.common.async===!1)return Ee(n,{code:pe.invalid_type,expected:be.promise,received:n.parsedType}),Ze;const r=n.parsedType===be.promise?n.data:Promise.resolve(n.data);return rr(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}}ad.create=(e,t)=>new ad({type:e,typeName:ze.ZodPromise,...Xe(t)});class Si extends rt{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ze.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:n,ctx:r}=this._processInputParams(t),o=this._def.effect||null,i={addIssue:s=>{Ee(r,s),s.fatal?n.abort():n.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),o.type==="preprocess"){const s=o.transform(r.data,i);return r.common.issues.length?{status:"dirty",value:r.data}:r.common.async?Promise.resolve(s).then(l=>this._def.schema._parseAsync({data:l,path:r.path,parent:r})):this._def.schema._parseSync({data:s,path:r.path,parent:r})}if(o.type==="refinement"){const s=l=>{const u=o.refinement(l,i);if(r.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return l};if(r.common.async===!1){const l=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return l.status==="aborted"?Ze:(l.status==="dirty"&&n.dirty(),s(l.value),{status:n.value,value:l.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(l=>l.status==="aborted"?Ze:(l.status==="dirty"&&n.dirty(),s(l.value).then(()=>({status:n.value,value:l.value}))))}if(o.type==="transform")if(r.common.async===!1){const s=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Yh(s))return s;const l=o.transform(s.value,i);if(l instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:l}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(s=>Yh(s)?Promise.resolve(o.transform(s.value,i)).then(l=>({status:n.value,value:l})):s);mt.assertNever(o)}}Si.create=(e,t,n)=>new Si({schema:e,typeName:ze.ZodEffects,effect:t,...Xe(n)});Si.createWithPreprocess=(e,t,n)=>new Si({schema:t,effect:{type:"preprocess",transform:e},typeName:ze.ZodEffects,...Xe(n)});class bs extends rt{_parse(t){return this._getType(t)===be.undefined?rr(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}bs.create=(e,t)=>new bs({innerType:e,typeName:ze.ZodOptional,...Xe(t)});class uc extends rt{_parse(t){return this._getType(t)===be.null?rr(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}uc.create=(e,t)=>new uc({innerType:e,typeName:ze.ZodNullable,...Xe(t)});class nm extends rt{_parse(t){const{ctx:n}=this._processInputParams(t);let r=n.data;return n.parsedType===be.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}nm.create=(e,t)=>new nm({innerType:e,typeName:ze.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Xe(t)});class O1 extends rt{_parse(t){const{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return C1(o)?o.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Bo(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Bo(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}O1.create=(e,t)=>new O1({innerType:e,typeName:ze.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Xe(t)});class M1 extends rt{_parse(t){if(this._getType(t)!==be.nan){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.nan,received:r.parsedType}),Ze}return{status:"valid",value:t.data}}}M1.create=e=>new M1({typeName:ze.ZodNaN,...Xe(e)});class hX extends rt{_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 sg extends rt{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?Ze:i.status==="dirty"?(n.dirty(),nX(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{const o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?Ze:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(t,n){return new sg({in:t,out:n,typeName:ze.ZodPipeline})}}class N1 extends rt{_parse(t){const n=this._def.innerType._parse(t);return Yh(n)&&(n.value=Object.freeze(n.value)),n}}N1.create=(e,t)=>new N1({innerType:e,typeName:ze.ZodReadonly,...Xe(t)});Vt.lazycreate;var ze;(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",e.ZodReadonly="ZodReadonly"})(ze||(ze={}));const O2=di.create;ac.create;M1.create;lc.create;const su=$1.create;sd.create;k1.create;Gh.create;Xh.create;R1.create;Tl.create;Rs.create;T1.create;Uo.create;const mX=Vt.create;Vt.strictCreate;Zh.create;Yx.create;qh.create;_i.create;Qh.create;A1.create;cc.create;Pu.create;Jh.create;em.create;Ta.create;tm.create;ad.create;Si.create;bs.create;uc.create;Si.createWithPreprocess;sg.create;const D1="horizontal",gX=["horizontal","vertical"],t3=f.forwardRef((e,t)=>{const{decorative:n,orientation:r=D1,...o}=e,i=n3(r)?r:D1,l=n?{role:"none"}:{"aria-orientation":i==="vertical"?i:void 0,role:"separator"};return f.createElement(Pe.div,Y({"data-orientation":i},l,o,{ref:t}))});t3.propTypes={orientation(e,t,n){const r=e[t],o=String(r);return r&&!n3(r)?new Error(vX(o,n)):null}};function vX(e,t){return`Invalid prop \`orientation\` of value \`${e}\` supplied to \`${t}\`, expected one of: + - horizontal + - vertical + +Defaulting to \`${D1}\`.`}function n3(e){return gX.includes(e)}const r3=t3,Fn=f.forwardRef(({className:e,orientation:t="horizontal",decorative:n=!0,...r},o)=>v.jsx(r3,{ref:o,decorative:n,orientation:t,className:Ce("shrink-0 bg-border",t==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",e),...r}));Fn.displayName=r3.displayName;const yX=f.forwardRef((e,t)=>f.createElement(Pe.label,Y({},e,{ref:t,onMouseDown:n=>{var r;(r=e.onMouseDown)===null||r===void 0||r.call(e,n),!n.defaultPrevented&&n.detail>1&&n.preventDefault()}}))),o3=yX,wX=Om("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),Gx=f.forwardRef(({className:e,disabled:t,...n},r)=>v.jsx(o3,{ref:r,className:Ce(wX(),e,t?"opacity-50":"","select-none"),...n}));Gx.displayName=o3.displayName;const xX=NG,i3=f.createContext({}),N0=({...e})=>v.jsx(i3.Provider,{value:{name:e.name},children:v.jsx(FG,{...e})}),ag=()=>{const e=f.useContext(i3),t=f.useContext(s3),{getFieldState:n,formState:r}=ig(),o=n(e.name,r);if(!e)throw new Error("useFormField should be used within ");const{id:i}=t;return{id:i,name:e.name,formItemId:`${i}-form-item`,formDescriptionId:`${i}-form-item-description`,formMessageId:`${i}-form-item-message`,...o}},s3=f.createContext({}),qp=f.forwardRef(({className:e,...t},n)=>{const r=f.useId();return v.jsx(s3.Provider,{value:{id:r},children:v.jsx("div",{ref:n,className:Ce("space-y-2",e),...t})})});qp.displayName="FormItem";const Qp=f.forwardRef(({className:e,...t},n)=>{const{error:r,formItemId:o}=ag();return v.jsx(Gx,{ref:n,className:Ce(r&&"text-destructive","text-sm",e),htmlFor:o,...t})});Qp.displayName="FormLabel";const Jp=f.forwardRef(({...e},t)=>{const{error:n,formItemId:r,formDescriptionId:o,formMessageId:i}=ag();return v.jsx(Wo,{ref:t,id:r,"aria-describedby":n?`${o} ${i}`:`${o}`,"aria-invalid":!!n,...e})});Jp.displayName="FormControl";const eh=f.forwardRef(({className:e,...t},n)=>{const{formDescriptionId:r}=ag();return v.jsx("p",{ref:n,id:r,className:Ce("text-[0.8rem] text-muted-foreground",e),...t})});eh.displayName="FormDescription";const bX=f.forwardRef(({className:e,children:t,...n},r)=>{const{error:o,formMessageId:i}=ag(),s=o?String(o==null?void 0:o.message):t;return s?v.jsx("p",{ref:r,id:i,className:Ce("text-[0.8rem] font-medium text-destructive",e),...n,children:s}):null});bX.displayName="FormMessage";const a3="Switch",[_X,Ete]=An(a3),[SX,EX]=_X(a3),CX=f.forwardRef((e,t)=>{const{__scopeSwitch:n,name:r,checked:o,defaultChecked:i,required:s,disabled:l,value:u="on",onCheckedChange:d,...h}=e,[m,g]=f.useState(null),y=Be(t,b=>g(b)),x=f.useRef(!1),_=m?!!m.closest("form"):!0,[C=!1,S]=Zr({prop:o,defaultProp:i,onChange:d});return f.createElement(SX,{scope:n,checked:C,disabled:l},f.createElement(Pe.button,Y({type:"button",role:"switch","aria-checked":C,"aria-required":s,"data-state":l3(C),"data-disabled":l?"":void 0,disabled:l,value:u},h,{ref:y,onClick:ue(e.onClick,b=>{S(E=>!E),_&&(x.current=b.isPropagationStopped(),x.current||b.stopPropagation())})})),_&&f.createElement(RX,{control:m,bubbles:!x.current,name:r,value:u,checked:C,required:s,disabled:l,style:{transform:"translateX(-100%)"}}))}),$X="SwitchThumb",kX=f.forwardRef((e,t)=>{const{__scopeSwitch:n,...r}=e,o=EX($X,n);return f.createElement(Pe.span,Y({"data-state":l3(o.checked),"data-disabled":o.disabled?"":void 0},r,{ref:t}))}),RX=e=>{const{control:t,checked:n,bubbles:r=!0,...o}=e,i=f.useRef(null),s=Fx(n),l=gx(t);return f.useEffect(()=>{const u=i.current,d=window.HTMLInputElement.prototype,m=Object.getOwnPropertyDescriptor(d,"checked").set;if(s!==n&&m){const g=new Event("click",{bubbles:r});m.call(u,n),u.dispatchEvent(g)}},[s,n,r]),f.createElement("input",Y({type:"checkbox","aria-hidden":!0,defaultChecked:n},o,{tabIndex:-1,ref:i,style:{...e.style,...l,position:"absolute",pointerEvents:"none",opacity:0,margin:0}}))};function l3(e){return e?"checked":"unchecked"}const c3=CX,TX=kX,co=f.forwardRef(({className:e,...t},n)=>v.jsx(c3,{className:Ce("peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",e),tabIndex:-1,...t,ref:n,children:v.jsx(TX,{className:Ce("pointer-events-none block h-4 w-4 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0")})}));co.displayName=c3.displayName;const PX="AlertDialog",[AX,Cte]=An(PX,[cP]),Is=cP(),OX=e=>{const{__scopeAlertDialog:t,...n}=e,r=Is(t);return f.createElement(Sx,Y({},r,n,{modal:!0}))},MX=e=>{const{__scopeAlertDialog:t,...n}=e,r=Is(t);return f.createElement(Ex,Y({},r,n))},NX=f.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=Is(n);return f.createElement(Nd,Y({},o,r,{ref:t}))}),u3="AlertDialogContent",[DX,IX]=AX(u3),LX=f.forwardRef((e,t)=>{const{__scopeAlertDialog:n,children:r,...o}=e,i=Is(n),s=f.useRef(null),l=Be(t,s),u=f.useRef(null);return f.createElement(hW,{contentName:u3,titleName:FX,docsSlug:"alert-dialog"},f.createElement(DX,{scope:n,cancelRef:u},f.createElement(Dd,Y({role:"alertdialog"},i,o,{ref:l,onOpenAutoFocus:ue(o.onOpenAutoFocus,d=>{var h;d.preventDefault(),(h=u.current)===null||h===void 0||h.focus({preventScroll:!0})}),onPointerDownOutside:d=>d.preventDefault(),onInteractOutside:d=>d.preventDefault()}),f.createElement(sx,null,r),!1)))}),FX="AlertDialogTitle",jX=f.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=Is(n);return f.createElement(Id,Y({},o,r,{ref:t}))}),zX=f.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=Is(n);return f.createElement(Ld,Y({},o,r,{ref:t}))}),BX=f.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=Is(n);return f.createElement(Cx,Y({},o,r,{ref:t}))}),UX="AlertDialogCancel",VX=f.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,{cancelRef:o}=IX(UX,n),i=Is(n),s=Be(t,o);return f.createElement(Cx,Y({},i,r,{ref:s}))}),WX=OX,HX=MX,d3=NX,f3=LX,p3=BX,h3=VX,m3=jX,g3=zX,KX=WX,YX=HX,v3=f.forwardRef(({className:e,...t},n)=>v.jsx(d3,{className:Ce("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t,ref:n}));v3.displayName=d3.displayName;const y3=f.forwardRef(({className:e,...t},n)=>v.jsxs(YX,{children:[v.jsx(v3,{}),v.jsx(f3,{ref:n,className:Ce("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",e),...t})]}));y3.displayName=f3.displayName;const w3=({className:e,...t})=>v.jsx("div",{className:Ce("flex flex-col space-y-2 text-center sm:text-left",e),...t});w3.displayName="AlertDialogHeader";const GX=f.forwardRef(({className:e,...t},n)=>v.jsx(m3,{ref:n,className:Ce("text-lg font-semibold",e),...t}));GX.displayName=m3.displayName;const XX=f.forwardRef(({className:e,...t},n)=>v.jsx(g3,{ref:n,className:Ce("text-sm text-muted-foreground",e),...t}));XX.displayName=g3.displayName;const ZX=f.forwardRef(({className:e,...t},n)=>v.jsx(p3,{ref:n,className:Ce(bx(),e),...t}));ZX.displayName=p3.displayName;const qX=f.forwardRef(({className:e,...t},n)=>v.jsx(h3,{ref:n,className:Ce(bx({variant:"outline"}),"mt-2 sm:mt-0",e),...t}));qX.displayName=h3.displayName;const QX=mX({enableFileManager:su(),inputDirectory:O2(),outputDirectory:O2(),enableDownloadMask:su(),enableManualInpainting:su(),enableUploadMask:su(),enableAutoExtractPrompt:su()}),x3="General",I1="Model",JX=[I1,x3];function eZ(){const[e,t]=u1(!1),[n,r]=u1(!1),[o,i]=f.useState(I1),[s,l,u,d,h,m]=bt(O=>[O.updateAppState,O.settings,O.updateSettings,O.fileManagerState,O.updateFileManagerState,O.setModel]),{toast:g}=Td(),[y,x]=f.useState(l.model);f.useEffect(()=>{x(l.model)},[l.model]);const{data:_,status:C}=TL({queryKey:["modelInfos"],queryFn:Bj}),S=XG({resolver:eX(QX),defaultValues:{enableDownloadMask:l.enableDownloadMask,enableManualInpainting:l.enableManualInpainting,enableUploadMask:l.enableUploadMask,enableAutoExtractPrompt:l.enableAutoExtractPrompt,inputDirectory:d.inputDirectory,outputDirectory:d.outputDirectory}});async function b(O){if(u({enableDownloadMask:O.enableDownloadMask,enableManualInpainting:O.enableManualInpainting,enableUploadMask:O.enableUploadMask,enableAutoExtractPrompt:O.enableAutoExtractPrompt}),h({inputDirectory:O.inputDirectory,outputDirectory:O.outputDirectory}),y.name!==l.model.name){r(),s({disableShortCuts:!0});try{const F=await jj(y.name);g({title:`Switch to ${F.name} success`}),m(y)}catch(F){g({variant:"destructive",title:`Switch to ${y.name} failed: ${F}`}),x(l.model)}finally{r(),s({disableShortCuts:!1})}}}Zn("s",()=>{t(),e&&b(S.getValues())},[e,S,y]);function E(O){t(),O||b(S.getValues())}function k(O){x(O)}function P(O){return _?_.filter(F=>O.includes(F.model_type)).map(F=>v.jsxs("div",{onClick:()=>k(F),className:"px-2",children:[v.jsx("div",{className:Ce([F.name===y.name?"bg-muted":"hover:bg-muted","rounded-md px-2 py-2","cursor-default"]),children:v.jsx("div",{className:"text-base",children:F.name})}),v.jsx(Fn,{className:"my-1"})]},F.name)):v.jsx("div",{children:"Please download model first"})}function M(){if(C!=="success")return v.jsx(v.Fragment,{});let O=is;for(let F of _)if(y.name===F.name){O=F.model_type,O===nC&&(O=rp),O===rC&&(O=op);break}return v.jsxs("div",{className:"flex flex-col gap-4 w-[510px]",children:[v.jsxs("div",{className:"flex flex-col gap-4 rounded-md",children:[v.jsx("div",{className:"font-medium",children:"Current Model"}),v.jsx("div",{children:y.name})]}),v.jsx(Fn,{}),v.jsxs("div",{className:"space-y-4 rounded-md",children:[v.jsx("div",{className:"flex gap-1 items-center justify-start",children:v.jsx("div",{className:"font-medium",children:"Available models"})}),v.jsxs(i5,{defaultValue:O,children:[v.jsxs(Lx,{children:[v.jsx(sa,{value:is,children:"Inpaint"}),v.jsx(sa,{value:rp,children:"Stable Diffusion"}),v.jsx(sa,{value:op,children:"Stable Diffusion Inpaint"}),v.jsx(sa,{value:l0,children:"Other Diffusion"})]}),v.jsxs(og,{className:"h-[240px] w-full mt-2 outline-none border rounded-lg",children:[v.jsx(mu,{value:is,children:P([is])}),v.jsx(mu,{value:rp,children:P([rp,nC])}),v.jsx(mu,{value:op,children:P([op,rC])}),v.jsx(mu,{value:l0,children:P([l0])})]})]})]})]})}function A(){return v.jsxs("div",{className:"space-y-4 w-[510px]",children:[v.jsx(N0,{control:S.control,name:"enableManualInpainting",render:({field:O})=>v.jsxs(qp,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(Qp,{children:"Enable manual inpainting"}),v.jsx(eh,{children:"For erase model, click a button to trigger inpainting after draw mask."})]}),v.jsx(Jp,{children:v.jsx(co,{checked:O.value,onCheckedChange:O.onChange})})]})}),v.jsx(Fn,{}),v.jsx(N0,{control:S.control,name:"enableDownloadMask",render:({field:O})=>v.jsxs(qp,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(Qp,{children:"Enable download mask"}),v.jsx(eh,{children:"Also download the mask after save the inpainting result."})]}),v.jsx(Jp,{children:v.jsx(co,{checked:O.value,onCheckedChange:O.onChange})})]})}),v.jsx(Fn,{}),v.jsx(N0,{control:S.control,name:"enableAutoExtractPrompt",render:({field:O})=>v.jsxs(qp,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(Qp,{children:"Enable auto extract prompt"}),v.jsx(eh,{children:"Automatically extract prompt/negativate prompt from the image meta."})]}),v.jsx(Jp,{children:v.jsx(co,{checked:O.value,onCheckedChange:O.onChange})})]})})]})}return v.jsxs(v.Fragment,{children:[v.jsx(KX,{open:n,children:v.jsx(y3,{children:v.jsx(w3,{children:v.jsxs("div",{className:"flex flex-col justify-center items-center gap-4",children:[v.jsxs("div",{role:"status",children:[v.jsxs("svg",{"aria-hidden":"true",className:"w-8 h-8 text-gray-200 animate-spin dark:text-gray-600 fill-primary",viewBox:"0 0 100 101",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[v.jsx("path",{d:"M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z",fill:"currentColor"}),v.jsx("path",{d:"M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z",fill:"currentFill"})]}),v.jsx("span",{className:"sr-only",children:"Loading..."})]}),v.jsxs("div",{children:["Switching to ",y.name]})]})})})}),v.jsxs(Zm,{open:e,onOpenChange:E,children:[v.jsx($x,{asChild:!0,children:v.jsx(vn,{tooltip:"Settings",children:v.jsx(aV,{})})}),v.jsxs(Fd,{className:"max-w-3xl h-[600px]",onOpenAutoFocus:O=>O.preventDefault(),children:[v.jsx(jd,{children:"Settings"}),v.jsx(Fn,{}),v.jsxs("div",{className:"flex flex-row space-x-8 h-full",children:[v.jsx("div",{className:"flex flex-col space-y-1",children:JX.map(O=>v.jsx(Rn,{variant:"ghost",onClick:()=>i(O),className:Ce(o===O?"bg-muted ":"hover:bg-muted","justify-start"),children:O},O))}),v.jsx(Fn,{orientation:"vertical"}),v.jsx(xX,{...S,children:v.jsx("div",{className:"flex w-full justify-center",children:v.jsxs("form",{onSubmit:S.handleSubmit(b),children:[o===I1?M():v.jsx(v.Fragment,{}),o===x3?A():v.jsx(v.Fragment,{}),v.jsx("div",{className:"absolute right-10 bottom-6",children:v.jsx(Rn,{onClick:()=>E(!1),children:"Ok"})})]})})})]})]})]})]})}const tZ="/assets/kofi_button_black-XI_Dr2zg.png";function nZ(){return v.jsxs(Zm,{children:[v.jsx($x,{asChild:!0,children:v.jsx(vn,{tooltip:"Buy me a coffee",children:v.jsx(GU,{})})}),v.jsxs(Fd,{children:[v.jsx(jd,{children:"Buy me a coffee"}),v.jsx(mP,{className:"mb-8",children:"Hi, if you found my project is useful, please conside buy me a coffee to support my work. Thanks!"}),v.jsx("div",{className:"w-full flex items-center justify-center",children:v.jsx("a",{href:"https://ko-fi.com/Z8Z1CZJGY",target:"_blank",rel:"noreferrer",children:v.jsx("img",{src:tZ,className:"h-[32px]"})})})]})]})}const rZ=()=>{const[e,t,n,r,o,i,s,l,u,d,h,m,g,y]=bt(M=>[M.file,M.customMask,M.isInpainting,M.serverConfig,M.runMannually(),M.settings.enableUploadMask,M.settings.model,M.setFile,M.setCustomFile,M.runInpainting,M.showPrevMask,M.hidePrevMask,M.imageHeight,M.imageWidth]),{toast:x}=Td(),[_,C]=Rx(t),[S,b]=f.useState(!1),E=()=>{d()},k=()=>{h()},P=()=>{m()};return v.jsxs("header",{className:"h-[60px] px-6 py-4 absolute top-[0] flex justify-between items-center w-full z-20 border-b backdrop-filter backdrop-blur-md bg-background/70",children:[v.jsxs("div",{className:"flex items-center gap-1",children:[r.enableFileManager?v.jsx(AG,{photoWidth:512,onPhotoClick:async(M,A)=>{try{const O=await Uj(M,A);l(O)}catch(O){x({variant:"destructive",description:O.message?O.message:O.toString()});return}}}):v.jsx(v.Fragment,{}),v.jsx(c1,{disabled:n,tooltip:"Upload image",onFileUpload:M=>{l(M)},children:v.jsx(eV,{})}),v.jsxs("div",{className:Ce(["flex items-center gap-1",e&&i?"visible":"hidden"]),children:[v.jsx(c1,{disabled:n,tooltip:"Upload custom mask",onFileUpload:async M=>{let A=null;try{A=await pF(M)}catch(O){x({variant:"destructive",description:O.message?O.message:O.toString()});return}if(A.naturalHeight!==g||A.naturalWidth!==y){x({variant:"destructive",description:`The size of the mask must same as image: ${y}x${g}`});return}u(M),o||d()},children:v.jsx(ZT,{})}),t?v.jsxs(YW,{open:S,children:[v.jsx(GW,{className:"btn-primary side-panel-trigger",onMouseEnter:()=>b(!0),onMouseLeave:()=>b(!1),style:{visibility:t?"visible":"hidden",outline:"none"},onClick:()=>{},children:v.jsx(vn,{tooltip:"Run custom mask",children:v.jsx(cz,{})})}),v.jsx(PP,{children:C?v.jsx("img",{src:_.src,alt:"Custom mask"}):v.jsx(v.Fragment,{})})]}):v.jsx(v.Fragment,{})]}),e&&!s.need_prompt?v.jsx(vn,{disabled:n,tooltip:"Rerun previous mask",onClick:E,onMouseEnter:k,onMouseLeave:P,children:v.jsx(sV,{})}):v.jsx(v.Fragment,{})]}),s.need_prompt?v.jsx(wH,{}):v.jsx(v.Fragment,{}),v.jsxs("div",{className:"flex gap-1",children:[v.jsx(nZ,{}),v.jsx(MW,{}),r.disableModelSwitch?v.jsx(v.Fragment,{}):v.jsx(eZ,{})]})]})};var Wr=function(e,t){return Number(e.toFixed(t))},oZ=function(e,t){return typeof e=="number"?e:t},Nt=function(e,t,n){n&&typeof n=="function"&&n(e,t)},iZ=function(e){return-Math.cos(e*Math.PI)/2+.5},sZ=function(e){return e},aZ=function(e){return e*e},lZ=function(e){return e*(2-e)},cZ=function(e){return e<.5?2*e*e:-1+(4-2*e)*e},uZ=function(e){return e*e*e},dZ=function(e){return--e*e*e+1},fZ=function(e){return e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1},pZ=function(e){return e*e*e*e},hZ=function(e){return 1- --e*e*e*e},mZ=function(e){return e<.5?8*e*e*e*e:1-8*--e*e*e*e},gZ=function(e){return e*e*e*e*e},vZ=function(e){return 1+--e*e*e*e*e},yZ=function(e){return e<.5?16*e*e*e*e*e:1+16*--e*e*e*e*e},b3={easeOut:iZ,linear:sZ,easeInQuad:aZ,easeOutQuad:lZ,easeInOutQuad:cZ,easeInCubic:uZ,easeOutCubic:dZ,easeInOutCubic:fZ,easeInQuart:pZ,easeOutQuart:hZ,easeInOutQuart:mZ,easeInQuint:gZ,easeOutQuint:vZ,easeInOutQuint:yZ},_3=function(e){typeof e=="number"&&cancelAnimationFrame(e)},Do=function(e){e.mounted&&(_3(e.animation),e.animate=!1,e.animation=null,e.velocity=null)};function S3(e,t,n,r){if(e.mounted){var o=new Date().getTime(),i=1;Do(e),e.animation=function(){if(!e.mounted)return _3(e.animation);var s=new Date().getTime()-o,l=s/n,u=b3[t],d=u(l);s>=n?(r(i),e.animation=null):e.animation&&(r(d),requestAnimationFrame(e.animation))},requestAnimationFrame(e.animation)}}function wZ(e){var t=e.scale,n=e.positionX,r=e.positionY;return!(Number.isNaN(t)||Number.isNaN(n)||Number.isNaN(r))}function Ls(e,t,n,r){var o=wZ(t);if(!(!e.mounted||!o)){var i=e.setTransformState,s=e.transformState,l=s.scale,u=s.positionX,d=s.positionY,h=t.scale-l,m=t.positionX-u,g=t.positionY-d;n===0?i(t.scale,t.positionX,t.positionY):S3(e,r,n,function(y){var x=l+h*y,_=u+m*y,C=d+g*y;i(x,_,C)})}}function xZ(e,t,n){var r=e.offsetWidth,o=e.offsetHeight,i=t.offsetWidth,s=t.offsetHeight,l=i*n,u=s*n,d=r-l,h=o-u;return{wrapperWidth:r,wrapperHeight:o,newContentWidth:l,newDiffWidth:d,newContentHeight:u,newDiffHeight:h}}var bZ=function(e,t,n,r,o,i,s){var l=e>t?n*(s?1:.5):0,u=r>o?i*(s?1:.5):0,d=e-t-l,h=l,m=r-o-u,g=u;return{minPositionX:d,maxPositionX:h,minPositionY:m,maxPositionY:g}},Xx=function(e,t){var n=e.wrapperComponent,r=e.contentComponent,o=e.setup.centerZoomedOut;if(!n||!r)throw new Error("Components are not mounted");var i=xZ(n,r,t),s=i.wrapperWidth,l=i.wrapperHeight,u=i.newContentWidth,d=i.newDiffWidth,h=i.newContentHeight,m=i.newDiffHeight,g=bZ(s,u,d,l,h,m,!!o);return g},L1=function(e,t,n,r){return r?en?Wr(n,2):Wr(e,2):Wr(e,2)},dc=function(e,t){var n=Xx(e,t);return e.bounds=n,n};function lg(e,t,n,r,o,i,s){var l=n.minPositionX,u=n.minPositionY,d=n.maxPositionX,h=n.maxPositionY,m=0,g=0;s&&(m=o,g=i);var y=L1(e,l-m,d+m,r),x=L1(t,u-g,h+g,r);return{x:y,y:x}}function cg(e,t,n,r,o,i){var s=e.transformState,l=s.scale,u=s.positionX,d=s.positionY,h=r-l;if(typeof t!="number"||typeof n!="number")return console.error("Mouse X and Y position were not provided!"),{x:u,y:d};var m=u-t*h,g=d-n*h,y=lg(m,g,o,i,0,0,null);return y}function Vd(e,t,n,r,o){var i=o?r:0,s=t-i;return!Number.isNaN(n)&&e>=n?n:!Number.isNaN(t)&&e<=s?s:e}var M2=function(e,t){var n=e.setup.panning.excluded,r=e.isInitialized,o=e.wrapperComponent,i=t.target,s=o==null?void 0:o.contains(i),l=r&&i&&s;if(!l)return!1;var u=ug(i,n);return!u},N2=function(e){var t=e.isInitialized,n=e.isPanning,r=e.setup,o=r.panning.disabled,i=t&&n&&!o;return!!i},_Z=function(e,t){var n=e.transformState,r=n.positionX,o=n.positionY;e.isPanning=!0;var i=t.clientX,s=t.clientY;e.startCoords={x:i-r,y:s-o}},SZ=function(e,t){var n=t.touches,r=e.transformState,o=r.positionX,i=r.positionY;e.isPanning=!0;var s=n.length===1;if(s){var l=n[0].clientX,u=n[0].clientY;e.startCoords={x:l-o,y:u-i}}};function EZ(e){var t=e.transformState,n=t.positionX,r=t.positionY,o=t.scale,i=e.setup,s=i.disabled,l=i.limitToBounds,u=i.centerZoomedOut,d=e.wrapperComponent;if(!(s||!d||!e.bounds)){var h=e.bounds,m=h.maxPositionX,g=h.minPositionX,y=h.maxPositionY,x=h.minPositionY,_=n>m||ny||rm?d.offsetWidth:e.setup.minPositionX||0,b=r>y?d.offsetHeight:e.setup.minPositionY||0,E=cg(e,S,b,o,e.bounds,l||u),k=E.x,P=E.y;return{scale:o,positionX:_?k:n,positionY:C?P:r}}}function CZ(e,t,n,r,o){var i=e.setup.limitToBounds,s=e.wrapperComponent,l=e.bounds,u=e.transformState,d=u.scale,h=u.positionX,m=u.positionY;if(!(s===null||l===null||t===h&&n===m)){var g=lg(t,n,l,i,r,o,s),y=g.x,x=g.y;e.setTransformState(d,y,x)}}var $Z=function(e,t,n){var r=e.startCoords,o=e.transformState,i=e.setup.panning,s=i.lockAxisX,l=i.lockAxisY,u=o.positionX,d=o.positionY;if(!r)return{x:u,y:d};var h=t-r.x,m=n-r.y,g=s?u:h,y=l?d:m;return{x:g,y}},rm=function(e,t){var n=e.setup,r=e.transformState,o=r.scale,i=n.minScale,s=n.disablePadding;return t>0&&o>=i&&!s?t:0},kZ=function(e){var t=e.mounted,n=e.setup,r=n.disabled,o=n.velocityAnimation,i=e.transformState.scale,s=o.disabled,l=!s||i>1||!r||t;return!!l},RZ=function(e){var t=e.mounted,n=e.velocity,r=e.bounds,o=e.setup,i=o.disabled,s=o.velocityAnimation,l=e.transformState.scale,u=s.disabled,d=!u||l>1||!i||t;return!(!d||!n||!r)};function TZ(e,t){var n=e.setup.velocityAnimation,r=n.equalToMove,o=n.animationTime,i=n.sensitivity;return r?o*t*i:o}function D2(e,t,n,r,o,i,s,l,u,d){if(o){if(t>s&&n>s){var h=s+(e-s)*d;return h>u?u:hi?i:h}}return r?t:L1(e,i,s,o)}function PZ(e,t){var n=1;return t?Math.min(n,e.offsetWidth/window.innerWidth):n}function AZ(e,t){var n=kZ(e);if(n){var r=e.lastMousePosition,o=e.velocityTime,i=e.setup,s=e.wrapperComponent,l=i.velocityAnimation.equalToMove,u=Date.now();if(r&&o&&s){var d=PZ(s,l),h=t.x-r.x,m=t.y-r.y,g=h/d,y=m/d,x=u-o,_=h*h+m*m,C=Math.sqrt(_)/x;e.velocity={velocityX:g,velocityY:y,total:C}}e.lastMousePosition=t,e.velocityTime=u}}function OZ(e){var t=e.velocity,n=e.bounds,r=e.setup,o=e.wrapperComponent,i=RZ(e);if(!(!i||!t||!n||!o)){var s=t.velocityX,l=t.velocityY,u=t.total,d=n.maxPositionX,h=n.minPositionX,m=n.maxPositionY,g=n.minPositionY,y=r.limitToBounds,x=r.alignmentAnimation,_=r.zoomAnimation,C=r.panning,S=C.lockAxisY,b=C.lockAxisX,E=_.animationType,k=x.sizeX,P=x.sizeY,M=x.velocityAlignmentTime,A=M,O=TZ(e,u),F=Math.max(O,A),V=rm(e,k),J=rm(e,P),G=V*o.offsetWidth/100,ae=J*o.offsetHeight/100,U=d+G,te=h-G,L=m+ae,ie=g-ae,K=e.transformState,Q=new Date().getTime();S3(e,E,F,function(W){var le=e.transformState,ge=le.scale,Ve=le.positionX,Ue=le.positionY,We=new Date().getTime()-Q,Me=We/A,fe=b3[x.animationType],xe=1-fe(Math.min(1,Me)),$e=1-W,Ae=Ve+s*$e,Oe=Ue+l*$e,je=D2(Ae,K.positionX,Ve,b,y,h,d,te,U,xe),Ot=D2(Oe,K.positionY,Ue,S,y,g,m,ie,L,xe);(Ve!==Ae||Ue!==Oe)&&e.setTransformState(ge,je,Ot)})}}function I2(e,t){var n=e.transformState.scale;Do(e),dc(e,n),window.TouchEvent!==void 0&&t instanceof TouchEvent?SZ(e,t):_Z(e,t)}function E3(e){var t=e.transformState.scale,n=e.setup,r=n.minScale,o=n.alignmentAnimation,i=o.disabled,s=o.sizeX,l=o.sizeY,u=o.animationTime,d=o.animationType,h=i||t.1&&m;g?OZ(e):E3(e)}}function Zx(e,t,n,r){var o=e.setup,i=o.minScale,s=o.maxScale,l=o.limitToBounds,u=Vd(Wr(t,2),i,s,0,!1),d=dc(e,u),h=cg(e,n,r,u,d,l),m=h.x,g=h.y;return{scale:u,positionX:m,positionY:g}}function C3(e,t,n){var r=e.transformState.scale,o=e.wrapperComponent,i=e.setup,s=i.minScale,l=i.limitToBounds,u=i.zoomAnimation,d=u.disabled,h=u.animationTime,m=u.animationType,g=d||r>=s;if((r>=1||l)&&E3(e),!(g||!o||!e.mounted)){var y=t||o.offsetWidth/2,x=n||o.offsetHeight/2,_=Zx(e,s,y,x);_&&Ls(e,_,h,m)}}var _s=function(){return _s=Object.assign||function(t){for(var n,r=1,o=arguments.length;rs||Math.sign(n.deltaY)!==Math.sign(t.deltaY)||n.deltaY>0&&n.deltaYt.deltaY||Math.sign(n.deltaY)!==Math.sign(t.deltaY):!1},ZZ=function(e,t){var n=e.setup.pinch,r=n.disabled,o=n.excluded,i=e.isInitialized,s=t.target,l=i&&!r&&s;if(!l)return!1;var u=ug(s,o);return!u},qZ=function(e){var t=e.setup.pinch.disabled,n=e.isInitialized,r=e.pinchStartDistance,o=n&&!t&&r;return!!o},QZ=function(e,t,n){var r=n.getBoundingClientRect(),o=e.touches,i=Wr(o[0].clientX-r.left,5),s=Wr(o[0].clientY-r.top,5),l=Wr(o[1].clientX-r.left,5),u=Wr(o[1].clientY-r.top,5);return{x:(i+l)/2/t,y:(s+u)/2/t}},O3=function(e){return Math.sqrt(Math.pow(e.touches[0].pageX-e.touches[1].pageX,2)+Math.pow(e.touches[0].pageY-e.touches[1].pageY,2))},JZ=function(e,t){var n=e.pinchStartScale,r=e.pinchStartDistance,o=e.setup,i=o.maxScale,s=o.minScale,l=o.zoomAnimation,u=o.disablePadding,d=l.size,h=l.disabled;if(!n||r===null||!t)throw new Error("Pinch touches distance was not provided");if(t<0)return e.transformState.scale;var m=t/r,g=m*n;return Vd(Wr(g,2),s,i,d,!h&&!u)},eq=160,tq=100,nq=function(e,t){var n=e.props,r=n.onWheelStart,o=n.onZoomStart;e.wheelStopEventTimer||(Do(e),Nt(St(e),t,r),Nt(St(e),t,o))},rq=function(e,t){var n=e.props,r=n.onWheel,o=n.onZoom,i=e.contentComponent,s=e.setup,l=e.transformState,u=l.scale,d=s.limitToBounds,h=s.centerZoomedOut,m=s.zoomAnimation,g=s.wheel,y=s.disablePadding,x=s.smooth,_=m.size,C=m.disabled,S=g.step,b=g.smoothStep;if(!i)throw new Error("Component not mounted");t.preventDefault(),t.stopPropagation();var E=YZ(t,null),k=x?b*Math.abs(t.deltaY):S,P=GZ(e,E,k,!t.ctrlKey);if(u!==P){var M=dc(e,P),A=A3(t,i,u),O=C||_===0||h||y,F=d&&O,V=cg(e,A.x,A.y,P,M,F),J=V.x,G=V.y;e.previousWheelEvent=t,e.setTransformState(P,J,G),Nt(St(e),t,r),Nt(St(e),t,o)}},oq=function(e,t){var n=e.props,r=n.onWheelStop,o=n.onZoomStop;j1(e.wheelAnimationTimer),e.wheelAnimationTimer=setTimeout(function(){e.mounted&&(C3(e,t.x,t.y),e.wheelAnimationTimer=null)},tq);var i=XZ(e,t);i&&(j1(e.wheelStopEventTimer),e.wheelStopEventTimer=setTimeout(function(){e.mounted&&(e.wheelStopEventTimer=null,Nt(St(e),t,r),Nt(St(e),t,o))},eq))},iq=function(e,t){var n=O3(t);e.pinchStartDistance=n,e.lastDistance=n,e.pinchStartScale=e.transformState.scale,e.isPanning=!1,Do(e)},sq=function(e,t){var n=e.contentComponent,r=e.pinchStartDistance,o=e.transformState.scale,i=e.setup,s=i.limitToBounds,l=i.centerZoomedOut,u=i.zoomAnimation,d=u.disabled,h=u.size;if(!(r===null||!n)){var m=QZ(t,o,n);if(!(!Number.isFinite(m.x)||!Number.isFinite(m.y))){var g=O3(t),y=JZ(e,g);if(y!==o){var x=dc(e,y),_=d||h===0||l,C=s&&_,S=cg(e,m.x,m.y,y,x,C),b=S.x,E=S.y;e.pinchMidpoint=m,e.lastDistance=g,e.setTransformState(y,b,E)}}}},aq=function(e){var t=e.pinchMidpoint;e.velocity=null,e.lastDistance=null,e.pinchMidpoint=null,e.pinchStartScale=null,e.pinchStartDistance=null,C3(e,t==null?void 0:t.x,t==null?void 0:t.y)},M3=function(e,t){var n=e.props.onZoomStop,r=e.setup.doubleClick.animationTime;j1(e.doubleClickStopEventTimer),e.doubleClickStopEventTimer=setTimeout(function(){e.doubleClickStopEventTimer=null,Nt(St(e),t,n)},r)},lq=function(e,t){var n=e.props,r=n.onZoomStart,o=n.onZoom,i=e.setup.doubleClick,s=i.animationTime,l=i.animationType;Nt(St(e),t,r),T3(e,s,l,function(){return Nt(St(e),t,o)}),M3(e,t)};function cq(e,t){var n=e.setup,r=e.doubleClickStopEventTimer,o=e.transformState,i=e.contentComponent,s=o.scale,l=e.props,u=l.onZoomStart,d=l.onZoom,h=n.doubleClick,m=h.disabled,g=h.mode,y=h.step,x=h.animationTime,_=h.animationType;if(!m&&!r){if(g==="reset")return lq(e,t);if(!i)return console.error("No ContentComponent found");var C=g==="zoomOut"?-1:1,S=k3(e,C,y);if(s!==S){Nt(St(e),t,u);var b=A3(t,i,s),E=Zx(e,S,b.x,b.y);if(!E)return console.error("Error during zoom event. New transformation state was not calculated.");Nt(St(e),t,d),Ls(e,E,x,_),M3(e,t)}}}var uq=function(e,t){var n=e.isInitialized,r=e.setup,o=e.wrapperComponent,i=r.doubleClick,s=i.disabled,l=i.excluded,u=t.target,d=o==null?void 0:o.contains(u),h=n&&u&&d&&!s;if(!h)return!1;var m=ug(u,l);return!m},dq=function(){function e(t){var n=this;this.mounted=!0,this.onChangeCallbacks=new Set,this.onInitCallbacks=new Set,this.wrapperComponent=null,this.contentComponent=null,this.isInitialized=!1,this.bounds=null,this.previousWheelEvent=null,this.wheelStopEventTimer=null,this.wheelAnimationTimer=null,this.isPanning=!1,this.startCoords=null,this.lastTouch=null,this.distance=null,this.lastDistance=null,this.pinchStartDistance=null,this.pinchStartScale=null,this.pinchMidpoint=null,this.doubleClickStopEventTimer=null,this.velocity=null,this.velocityTime=null,this.lastMousePosition=null,this.animate=!1,this.animation=null,this.maxBounds=null,this.pressedKeys={},this.mount=function(){n.initializeWindowEvents()},this.unmount=function(){n.cleanupWindowEvents()},this.update=function(r){dc(n,n.transformState.scale),n.setup=j2(r)},this.initializeWindowEvents=function(){var r,o=I0(),i=(r=n.wrapperComponent)===null||r===void 0?void 0:r.ownerDocument,s=i==null?void 0:i.defaultView;s==null||s.addEventListener("mousedown",n.onPanningStart,o),s==null||s.addEventListener("mousemove",n.onPanning,o),s==null||s.addEventListener("mouseup",n.onPanningStop,o),i==null||i.addEventListener("mouseleave",n.clearPanning,o),s==null||s.addEventListener("keyup",n.setKeyUnPressed,o),s==null||s.addEventListener("keydown",n.setKeyPressed,o)},this.cleanupWindowEvents=function(){var r,o,i=I0(),s=(r=n.wrapperComponent)===null||r===void 0?void 0:r.ownerDocument,l=s==null?void 0:s.defaultView;l==null||l.removeEventListener("mousedown",n.onPanningStart,i),l==null||l.removeEventListener("mousemove",n.onPanning,i),l==null||l.removeEventListener("mouseup",n.onPanningStop,i),s==null||s.removeEventListener("mouseleave",n.clearPanning,i),l==null||l.removeEventListener("keyup",n.setKeyUnPressed,i),l==null||l.removeEventListener("keydown",n.setKeyPressed,i),document.removeEventListener("mouseleave",n.clearPanning,i),Do(n),(o=n.observer)===null||o===void 0||o.disconnect()},this.handleInitializeWrapperEvents=function(r){var o=I0();r.addEventListener("wheel",n.onWheelZoom,o),r.addEventListener("dblclick",n.onDoubleClick,o),r.addEventListener("touchstart",n.onTouchPanningStart,o),r.addEventListener("touchmove",n.onTouchPanning,o),r.addEventListener("touchend",n.onTouchPanningStop,o)},this.handleInitialize=function(r){var o=n.setup.centerOnInit;n.applyTransformation(),n.onInitCallbacks.forEach(function(i){return i(St(n))}),o&&(n.setCenter(),n.observer=new ResizeObserver(function(){var i;n.onInitCallbacks.forEach(function(s){return s(St(n))}),n.setCenter(),(i=n.observer)===null||i===void 0||i.disconnect()}),n.observer.observe(r))},this.onWheelZoom=function(r){var o=n.setup.disabled;if(!o){var i=HZ(n,r);if(i){var s=n.isPressingKeys(n.setup.wheel.activationKeys);s&&(nq(n,r),rq(n,r),oq(n,r))}}},this.onPanningStart=function(r){var o=n.setup.disabled,i=n.props.onPanningStart;if(!o){var s=M2(n,r);if(s){var l=n.isPressingKeys(n.setup.panning.activationKeys);l&&(r.button===0&&!n.setup.panning.allowLeftClickPan||r.button===1&&!n.setup.panning.allowMiddleClickPan||r.button===2&&!n.setup.panning.allowRightClickPan||(r.preventDefault(),r.stopPropagation(),Do(n),I2(n,r),Nt(St(n),r,i)))}}},this.onPanning=function(r){var o=n.setup.disabled,i=n.props.onPanning;if(!o){var s=N2(n);if(s){var l=n.isPressingKeys(n.setup.panning.activationKeys);l&&(r.preventDefault(),r.stopPropagation(),L2(n,r.clientX,r.clientY),Nt(St(n),r,i))}}},this.onPanningStop=function(r){var o=n.props.onPanningStop;n.isPanning&&(MZ(n),Nt(St(n),r,o))},this.onPinchStart=function(r){var o=n.setup.disabled,i=n.props,s=i.onPinchingStart,l=i.onZoomStart;if(!o){var u=ZZ(n,r);u&&(iq(n,r),Do(n),Nt(St(n),r,s),Nt(St(n),r,l))}},this.onPinch=function(r){var o=n.setup.disabled,i=n.props,s=i.onPinching,l=i.onZoom;if(!o){var u=qZ(n);u&&(r.preventDefault(),r.stopPropagation(),sq(n,r),Nt(St(n),r,s),Nt(St(n),r,l))}},this.onPinchStop=function(r){var o=n.props,i=o.onPinchingStop,s=o.onZoomStop;n.pinchStartScale&&(aq(n),Nt(St(n),r,i),Nt(St(n),r,s))},this.onTouchPanningStart=function(r){var o=n.setup.disabled,i=n.props.onPanningStart;if(!o){var s=M2(n,r);if(s){var l=n.lastTouch&&+new Date-n.lastTouch<200;if(l&&r.touches.length===1)n.onDoubleClick(r);else{n.lastTouch=+new Date,Do(n);var u=r.touches,d=u.length===1,h=u.length===2;d&&(Do(n),I2(n,r),Nt(St(n),r,i)),h&&n.onPinchStart(r)}}}},this.onTouchPanning=function(r){var o=n.setup.disabled,i=n.props.onPanning;if(n.isPanning&&r.touches.length===1){if(o)return;var s=N2(n);if(!s)return;r.preventDefault(),r.stopPropagation();var l=r.touches[0];L2(n,l.clientX,l.clientY),Nt(St(n),r,i)}else r.touches.length>1&&n.onPinch(r)},this.onTouchPanningStop=function(r){n.onPanningStop(r),n.onPinchStop(r)},this.onDoubleClick=function(r){var o=n.setup.disabled;if(!o){var i=uq(n,r);i&&cq(n,r)}},this.clearPanning=function(r){n.isPanning&&n.onPanningStop(r)},this.setKeyPressed=function(r){n.pressedKeys[r.key]=!0},this.setKeyUnPressed=function(r){n.pressedKeys[r.key]=!1},this.isPressingKeys=function(r){return r.length?!!r.find(function(o){return n.pressedKeys[o]}):!0},this.setTransformState=function(r,o,i){var s=n.props.onTransformed;if(!Number.isNaN(r)&&!Number.isNaN(o)&&!Number.isNaN(i)){r!==n.transformState.scale&&(n.transformState.previousScale=n.transformState.scale,n.transformState.scale=r),n.transformState.positionX=o,n.transformState.positionY=i,n.applyTransformation();var l=St(n);n.onChangeCallbacks.forEach(function(u){return u(l)}),Nt(l,{scale:r,positionX:o,positionY:i},s)}else console.error("Detected NaN set state values")},this.setCenter=function(){if(n.wrapperComponent&&n.contentComponent){var r=P3(n.transformState.scale,n.wrapperComponent,n.contentComponent);n.setTransformState(r.scale,r.positionX,r.positionY)}},this.handleTransformStyles=function(r,o,i){return n.props.customTransform?n.props.customTransform(r,o,i):VZ(r,o,i)},this.applyTransformation=function(){if(!(!n.mounted||!n.contentComponent)){var r=n.transformState,o=r.scale,i=r.positionX,s=r.positionY,l=n.handleTransformStyles(i,s,o);n.contentComponent.style.transform=l}},this.getContext=function(){return St(n)},this.onChange=function(r){return n.onChangeCallbacks.has(r)||n.onChangeCallbacks.add(r),function(){n.onChangeCallbacks.delete(r)}},this.onInit=function(r){return n.onInitCallbacks.has(r)||n.onInitCallbacks.add(r),function(){n.onInitCallbacks.delete(r)}},this.init=function(r,o){n.cleanupWindowEvents(),n.wrapperComponent=r,n.contentComponent=o,dc(n,n.transformState.scale),n.handleInitializeWrapperEvents(r),n.handleInitialize(o),n.initializeWindowEvents(),n.isInitialized=!0;var i=St(n);Nt(i,void 0,n.props.onInit)},this.props=t,this.setup=j2(this.props),this.transformState=$3(this.props)}return e}(),qx=Fe.createContext(null),fq=function(e,t){return typeof e=="function"?e(t):e},pq=Fe.forwardRef(function(e,t){var n=f.useRef(new dq(e)).current,r=fq(e.children,F1(n));return f.useImperativeHandle(t,function(){return F1(n)},[n]),f.useEffect(function(){n.update(e)},[n,e]),Fe.createElement(qx.Provider,{value:n},r)});Fe.forwardRef(function(e,t){var n=f.useRef(null),r=f.useContext(qx);return f.useEffect(function(){return r.onChange(function(o){if(n.current){var i=0,s=0;n.current.style.transform=r.handleTransformStyles(i,s,1/o.instance.transformState.scale)}})},[r]),Fe.createElement("div",_s({},e,{ref:WZ([n,t])}))});function hq(e,t){t===void 0&&(t={});var n=t.insertAt;if(!(!e||typeof document>"u")){var r=document.head||document.getElementsByTagName("head")[0],o=document.createElement("style");o.type="text/css",n==="top"&&r.firstChild?r.insertBefore(o,r.firstChild):r.appendChild(o),o.styleSheet?o.styleSheet.cssText=e:o.appendChild(document.createTextNode(e))}}var mq=`.transform-component-module_wrapper__SPB86 { + position: relative; + width: -moz-fit-content; + width: fit-content; + height: -moz-fit-content; + height: fit-content; + overflow: hidden; + -webkit-touch-callout: none; /* iOS Safari */ + -webkit-user-select: none; /* Safari */ + -khtml-user-select: none; /* Konqueror HTML */ + -moz-user-select: none; /* Firefox */ + -ms-user-select: none; /* Internet Explorer/Edge */ + user-select: none; + margin: 0; + padding: 0; +} +.transform-component-module_content__FBWxo { + display: flex; + flex-wrap: wrap; + width: -moz-fit-content; + width: fit-content; + height: -moz-fit-content; + height: fit-content; + margin: 0; + padding: 0; + transform-origin: 0% 0%; +} +.transform-component-module_content__FBWxo img { + pointer-events: none; +} +`,z2={wrapper:"transform-component-module_wrapper__SPB86",content:"transform-component-module_content__FBWxo"};hq(mq);var gq=function(e){var t=e.children,n=e.wrapperClass,r=n===void 0?"":n,o=e.contentClass,i=o===void 0?"":o,s=e.wrapperStyle,l=e.contentStyle,u=e.wrapperProps,d=u===void 0?{}:u,h=e.contentProps,m=h===void 0?{}:h,g=f.useContext(qx),y=g.init,x=g.cleanupWindowEvents,_=f.useRef(null),C=f.useRef(null);return f.useEffect(function(){var S=_.current,b=C.current;return S!==null&&b!==null&&y&&(y==null||y(S,b)),function(){x==null||x()}},[]),Fe.createElement("div",_s({},d,{ref:_,className:"react-transform-wrapper ".concat(z2.wrapper," ").concat(r),style:s}),Fe.createElement("div",_s({},m,{ref:C,className:"react-transform-component ".concat(z2.content," ").concat(i),style:l}),t))};const N3=["PageUp","PageDown"],D3=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],I3={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},Wd="Slider",[z1,vq,yq]=zd(Wd),[L3,$te]=An(Wd,[yq]),[wq,dg]=L3(Wd),xq=f.forwardRef((e,t)=>{const{name:n,min:r=0,max:o=100,step:i=1,orientation:s="horizontal",disabled:l=!1,minStepsBetweenThumbs:u=0,defaultValue:d=[r],value:h,onValueChange:m=()=>{},onValueCommit:g=()=>{},inverted:y=!1,...x}=e,[_,C]=f.useState(null),S=Be(t,U=>C(U)),b=f.useRef(new Set),E=f.useRef(0),k=s==="horizontal",P=_?!!_.closest("form"):!0,M=k?bq:_q,[A=[],O]=Zr({prop:h,defaultProp:d,onChange:U=>{var te;(te=[...b.current][E.current])===null||te===void 0||te.focus(),m(U)}}),F=f.useRef(A);function V(U){const te=Aq(A,U);ae(U,te)}function J(U){ae(U,E.current)}function G(){const U=F.current[E.current];A[E.current]!==U&&g(A)}function ae(U,te,{commit:L}={commit:!1}){const ie=Dq(i),K=Iq(Math.round((U-r)/i)*i+r,ie),Q=id(K,[r,o]);O((W=[])=>{const le=Tq(W,Q,te);if(Nq(le,u*i)){E.current=le.indexOf(Q);const ge=String(le)!==String(W);return ge&&L&&g(le),ge?le:W}else return W})}return f.createElement(wq,{scope:e.__scopeSlider,disabled:l,min:r,max:o,valueIndexToChangeRef:E,thumbs:b.current,values:A,orientation:s},f.createElement(z1.Provider,{scope:e.__scopeSlider},f.createElement(z1.Slot,{scope:e.__scopeSlider},f.createElement(M,Y({"aria-disabled":l,"data-disabled":l?"":void 0},x,{ref:S,onPointerDown:ue(x.onPointerDown,()=>{l||(F.current=A)}),min:r,max:o,inverted:y,onSlideStart:l?void 0:V,onSlideMove:l?void 0:J,onSlideEnd:l?void 0:G,onHomeKeyDown:()=>!l&&ae(r,0,{commit:!0}),onEndKeyDown:()=>!l&&ae(o,A.length-1,{commit:!0}),onStepKeyDown:({event:U,direction:te})=>{if(!l){const K=N3.includes(U.key)||U.shiftKey&&D3.includes(U.key)?10:1,Q=E.current,W=A[Q],le=i*K*te;ae(W+le,Q,{commit:!0})}}})))),P&&A.map((U,te)=>f.createElement(Rq,{key:te,name:n?n+(A.length>1?"[]":""):void 0,value:U})))}),[F3,j3]=L3(Wd,{startEdge:"left",endEdge:"right",size:"width",direction:1}),bq=f.forwardRef((e,t)=>{const{min:n,max:r,dir:o,inverted:i,onSlideStart:s,onSlideMove:l,onSlideEnd:u,onStepKeyDown:d,...h}=e,[m,g]=f.useState(null),y=Be(t,E=>g(E)),x=f.useRef(),_=Sc(o),C=_==="ltr",S=C&&!i||!C&&i;function b(E){const k=x.current||m.getBoundingClientRect(),P=[0,k.width],A=Qx(P,S?[n,r]:[r,n]);return x.current=k,A(E-k.left)}return f.createElement(F3,{scope:e.__scopeSlider,startEdge:S?"left":"right",endEdge:S?"right":"left",direction:S?1:-1,size:"width"},f.createElement(z3,Y({dir:_,"data-orientation":"horizontal"},h,{ref:y,style:{...h.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:E=>{const k=b(E.clientX);s==null||s(k)},onSlideMove:E=>{const k=b(E.clientX);l==null||l(k)},onSlideEnd:()=>{x.current=void 0,u==null||u()},onStepKeyDown:E=>{const P=I3[S?"from-left":"from-right"].includes(E.key);d==null||d({event:E,direction:P?-1:1})}})))}),_q=f.forwardRef((e,t)=>{const{min:n,max:r,inverted:o,onSlideStart:i,onSlideMove:s,onSlideEnd:l,onStepKeyDown:u,...d}=e,h=f.useRef(null),m=Be(t,h),g=f.useRef(),y=!o;function x(_){const C=g.current||h.current.getBoundingClientRect(),S=[0,C.height],E=Qx(S,y?[r,n]:[n,r]);return g.current=C,E(_-C.top)}return f.createElement(F3,{scope:e.__scopeSlider,startEdge:y?"bottom":"top",endEdge:y?"top":"bottom",size:"height",direction:y?1:-1},f.createElement(z3,Y({"data-orientation":"vertical"},d,{ref:m,style:{...d.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:_=>{const C=x(_.clientY);i==null||i(C)},onSlideMove:_=>{const C=x(_.clientY);s==null||s(C)},onSlideEnd:()=>{g.current=void 0,l==null||l()},onStepKeyDown:_=>{const S=I3[y?"from-bottom":"from-top"].includes(_.key);u==null||u({event:_,direction:S?-1:1})}})))}),z3=f.forwardRef((e,t)=>{const{__scopeSlider:n,onSlideStart:r,onSlideMove:o,onSlideEnd:i,onHomeKeyDown:s,onEndKeyDown:l,onStepKeyDown:u,...d}=e,h=dg(Wd,n);return f.createElement(Pe.span,Y({},d,{ref:t,onKeyDown:ue(e.onKeyDown,m=>{m.key==="Home"?(s(m),m.preventDefault()):m.key==="End"?(l(m),m.preventDefault()):N3.concat(D3).includes(m.key)&&(u(m),m.preventDefault())}),onPointerDown:ue(e.onPointerDown,m=>{const g=m.target;g.setPointerCapture(m.pointerId),m.preventDefault(),h.thumbs.has(g)?g.focus():r(m)}),onPointerMove:ue(e.onPointerMove,m=>{m.target.hasPointerCapture(m.pointerId)&&o(m)}),onPointerUp:ue(e.onPointerUp,m=>{const g=m.target;g.hasPointerCapture(m.pointerId)&&(g.releasePointerCapture(m.pointerId),i(m))})}))}),Sq="SliderTrack",Eq=f.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,o=dg(Sq,n);return f.createElement(Pe.span,Y({"data-disabled":o.disabled?"":void 0,"data-orientation":o.orientation},r,{ref:t}))}),B2="SliderRange",Cq=f.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,o=dg(B2,n),i=j3(B2,n),s=f.useRef(null),l=Be(t,s),u=o.values.length,d=o.values.map(g=>B3(g,o.min,o.max)),h=u>1?Math.min(...d):0,m=100-Math.max(...d);return f.createElement(Pe.span,Y({"data-orientation":o.orientation,"data-disabled":o.disabled?"":void 0},r,{ref:l,style:{...e.style,[i.startEdge]:h+"%",[i.endEdge]:m+"%"}}))}),U2="SliderThumb",$q=f.forwardRef((e,t)=>{const n=vq(e.__scopeSlider),[r,o]=f.useState(null),i=Be(t,l=>o(l)),s=f.useMemo(()=>r?n().findIndex(l=>l.ref.current===r):-1,[n,r]);return f.createElement(kq,Y({},e,{ref:i,index:s}))}),kq=f.forwardRef((e,t)=>{const{__scopeSlider:n,index:r,...o}=e,i=dg(U2,n),s=j3(U2,n),[l,u]=f.useState(null),d=Be(t,C=>u(C)),h=gx(l),m=i.values[r],g=m===void 0?0:B3(m,i.min,i.max),y=Pq(r,i.values.length),x=h==null?void 0:h[s.size],_=x?Oq(x,g,s.direction):0;return f.useEffect(()=>{if(l)return i.thumbs.add(l),()=>{i.thumbs.delete(l)}},[l,i.thumbs]),f.createElement("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[s.startEdge]:`calc(${g}% + ${_}px)`}},f.createElement(z1.ItemSlot,{scope:e.__scopeSlider},f.createElement(Pe.span,Y({role:"slider","aria-label":e["aria-label"]||y,"aria-valuemin":i.min,"aria-valuenow":m,"aria-valuemax":i.max,"aria-orientation":i.orientation,"data-orientation":i.orientation,"data-disabled":i.disabled?"":void 0,tabIndex:i.disabled?void 0:0},o,{ref:d,style:m===void 0?{display:"none"}:e.style,onFocus:ue(e.onFocus,()=>{i.valueIndexToChangeRef.current=r})}))))}),Rq=e=>{const{value:t,...n}=e,r=f.useRef(null),o=Fx(t);return f.useEffect(()=>{const i=r.current,s=window.HTMLInputElement.prototype,u=Object.getOwnPropertyDescriptor(s,"value").set;if(o!==t&&u){const d=new Event("input",{bubbles:!0});u.call(i,t),i.dispatchEvent(d)}},[o,t]),f.createElement("input",Y({style:{display:"none"}},n,{ref:r,defaultValue:t}))};function Tq(e=[],t,n){const r=[...e];return r[n]=t,r.sort((o,i)=>o-i)}function B3(e,t,n){const i=100/(n-t)*(e-t);return id(i,[0,100])}function Pq(e,t){return t>2?`Value ${e+1} of ${t}`:t===2?["Minimum","Maximum"][e]:void 0}function Aq(e,t){if(e.length===1)return 0;const n=e.map(o=>Math.abs(o-t)),r=Math.min(...n);return n.indexOf(r)}function Oq(e,t,n){const r=e/2,i=Qx([0,50],[0,r]);return(r-i(t)*n)*n}function Mq(e){return e.slice(0,-1).map((t,n)=>e[n+1]-t)}function Nq(e,t){if(t>0){const n=Mq(e);return Math.min(...n)>=t}return!0}function Qx(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 Dq(e){return(String(e).split(".")[1]||"").length}function Iq(e,t){const n=Math.pow(10,t);return Math.round(e*n)/n}const U3=xq,Lq=Eq,Fq=Cq,jq=$q,uo=f.forwardRef(({className:e,...t},n)=>v.jsxs(U3,{ref:n,className:Ce("relative flex w-full touch-none select-none items-center",e),tabIndex:-1,...t,children:[v.jsx(Lq,{className:"relative h-1.5 w-full grow overflow-hidden rounded-full bg-primary/20 data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50",children:v.jsx(Fq,{className:"absolute h-full bg-primary data-[disabled]:cursor-not-allowed "})}),v.jsx(jq,{tabIndex:-1,className:"block h-4 w-4 rounded-full border border-primary/60 bg-background shadow transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring data-[disabled]:cursor-not-allowed"})]}));uo.displayName=U3.displayName;const tl={capture:!0,passive:!1},zq=2,V2=(e,t,n,r,o,i)=>{if(e!==n&&t===r){if(e<0)return[0,r];if(e+t>i)return[i-r,r]}else{if(ti)return[e,i-e]}return[e,t]},Bq=e=>{const{minHeight:t,minWidth:n,maxHeight:r,maxWidth:o,scale:i,show:s}=e,[l,u,d,h,{x:m,y:g,width:y,height:x},_,C,S,b,E,k]=bt(W=>[W.imageWidth,W.imageHeight,W.isInpainting,W.isSD(),W.cropperState,W.setCropperX,W.setCropperY,W.setCropperWidth,W.setCropperHeight,W.isCropperExtenderResizing,W.setIsCropperExtenderResizing]),[P,M]=f.useState(!1);f.useEffect(()=>{_(Math.round((o-512)/2)),C(Math.round((r-512)/2))},[r,o,l,u]);const[A,O]=f.useState({initX:0,initY:0,initHeight:0,initWidth:0,startResizeX:0,startResizeY:0,ord:"top"}),F=()=>{},V=(W,le)=>V2(W,le,m,y,n,o),J=(W,le)=>V2(W,le,g,x,t,r),G=W=>{if(d)return;const le=W.clientX,ge=W.clientY,Ve=Math.round((ge-A.startResizeY)/i),Ue=Math.round((le-A.startResizeX)/i),We=()=>{const $e=A.initHeight-Ve,Ae=A.initY+Ve,[Oe,je]=J(Ae,$e);b(je),C(Oe)},Me=()=>{const $e=A.initHeight+Ve,[Ae,Oe]=J(A.initY,$e);b(Oe),C(Ae)},fe=()=>{const $e=A.initWidth-Ue,Ae=A.initX+Ue,[Oe,je]=V(Ae,$e);S(je),_(Oe)},xe=()=>{const $e=A.initWidth+Ue,[Ae,Oe]=V(A.initX,$e);S(Oe),_(Ae)};if(E)switch(A.ord){case"topleft":{We(),fe();break}case"topright":{We(),xe();break}case"bottomleft":{Me(),fe();break}case"bottomright":{Me(),xe();break}case"top":{We();break}case"right":{xe();break}case"bottom":{Me();break}case"left":{fe();break}}if(P){const $e=A.initX+Ue,Ae=A.initY+Ve,[Oe,je]=V($e,A.initWidth),[Ot,ct]=J(Ae,A.initHeight);S(je),b(ct),_(Oe),C(Ot)}},ae=()=>{E&&k(!1),P&&M(!1)};f.useEffect(()=>{if(E||P)return document.addEventListener("pointermove",G,tl),document.addEventListener("pointerup",ae,tl),document.addEventListener("pointercancel",ae,tl),()=>{document.removeEventListener("pointermove",G,tl),document.removeEventListener("pointerup",ae,tl),document.removeEventListener("pointercancel",ae,tl)}},[E,P,y,x,A]);const U=W=>{const{ord:le}=W.target.dataset;le&&(k(!0),O({initX:m,initY:g,initHeight:x,initWidth:y,startResizeX:W.clientX,startResizeY:W.clientY,ord:le}))},te=(W,le,ge)=>{const We="w-[12px] h-[12px] z-[4] absolute content-[''] block border-2 border-primary borde pointer-events-auto hover:bg-primary";let Me="0",fe="0",xe=ge,$e="-6px";return ge===""&&($e="50%",le==="left"||le==="right"?(xe="top",fe="-50%"):(xe="left",Me="-50%")),v.jsx("div",{className:Ce(We,W),style:{[le]:-6,[xe]:$e,transform:`translate(${Me}, ${fe}) scale(${1/i})`},"data-ord":le+ge,"aria-label":le+ge,tabIndex:-1,role:"button"})},L=()=>v.jsxs("div",{onFocus:F,onPointerDown:U,className:"absolute top-0 h-full w-full",children:[v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 w-full cursor-ns-resize h-[12px] mt-[-6px]","data-ord":"top"}),v.jsx("div",{className:"absolute pointer-events-auto top-0 right-0 h-full cursor-ew-resize w-[12px] mr-[-6px]","data-ord":"right"}),v.jsx("div",{className:"absolute pointer-events-auto bottom-0 left-0 w-full cursor-ns-resize h-[12px] mb-[-6px]","data-ord":"bottom"}),v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 h-full cursor-ew-resize w-[12px] ml-[-6px]","data-ord":"left"}),te("cursor-nw-resize","top","left"),te("cursor-ne-resize","top","right"),te("cursor-sw-resize","bottom","left"),te("cursor-se-resize","bottom","right"),te("cursor-ns-resize","top",""),te("cursor-ns-resize","bottom",""),te("cursor-ew-resize","left",""),te("cursor-ew-resize","right","")]}),ie=W=>{M(!0),O({initX:m,initY:g,initHeight:x,initWidth:y,startResizeX:W.clientX,startResizeY:W.clientY,ord:""})},K=()=>v.jsxs("div",{className:Jw("border absolute pointer-events-auto px-2 py-1 rounded-full hover:cursor-move bg-background","origin-top-left top-0 left-0"),style:{transform:`scale(${1/i*.8})`},onPointerDown:ie,children:[y," x ",x]}),Q=()=>v.jsx("div",{className:"outline-dashed outline-primary",style:{height:x,width:y,outlineWidth:`${zq/i*1.3}px`}});return s===!1||!h?null:v.jsx("div",{className:"absolute h-full w-full overflow-hidden pointer-events-none z-[2]",children:v.jsxs("div",{className:"relative pointer-events-none z-[2] [box-shadow:0_0_0_9999px_rgba(0,_0,_0,_0.5)]",style:{height:x,width:y,left:m,top:g},children:[Q(),K(),L()]})})},Uq=()=>{const[e,t,n]=bt(r=>[r.interactiveSegState,r.resetInteractiveSegState,r.handleInteractiveSegAccept]);return e.isInteractiveSeg?v.jsxs("div",{className:"z-10 absolute top-[68px] rounded-xl border-solid border p-[8px] left-1/2 translate-x-[-50%] flex justify-center items-center gap-[8px] bg-background",children:[v.jsx(Rn,{onClick:()=>{t()},size:"sm",variant:"secondary",children:"Cancel"}),v.jsx(Rn,{size:"sm",onClick:()=>{n()},children:"Accept"})]}):null},Vq=e=>{const{x:t,y:n,positive:r}=e,o=r?"bg-[rgba(21,_215,_121,_0.936)] outline-[rgba(98,255,179,0.31)]":"bg-[rgba(237,_49,_55,_0.942)] outline-[rgba(255,89,95,0.31)]";return v.jsx("div",{className:`absolute h-[10px] w-[10px] rounded-[50%] ${o} outline-8 outline`,style:{left:t,top:n,transform:"translate(-50%, -50%)"}})},Wq=()=>{const e=bt(t=>t.interactiveSegState.clicks);return v.jsx("div",{className:"absolute h-full w-full overflow-hidden pointer-events-none",children:e.map(t=>v.jsx(Vq,{x:t[0],y:t[1],positive:t[2]===1},t[3]))})},Hq=()=>v.jsx("div",{children:v.jsx(Uq,{})}),nl={capture:!0,passive:!1},Kq=2,W2=(e,t,n,r)=>t{const{minHeight:t,minWidth:n,scale:r,show:o}=e,[i,s,l,u,{x:d,y:h,width:m,height:g},y,x,_,C,S,b,E]=bt(ie=>[ie.isInpainting,ie.imageHeight,ie.imageWidth,ie.isSD(),ie.extenderState,ie.setExtenderX,ie.setExtenderY,ie.setExtenderWidth,ie.setExtenderHeight,ie.settings.extenderDirection,ie.isCropperExtenderResizing,ie.setIsCropperExtenderResizing]),[k,P]=f.useState({initX:0,initY:0,initHeight:0,initWidth:0,startResizeX:0,startResizeY:0,ord:"top"}),M=()=>{},A=(ie,K)=>W2(ie,K,d,n),O=(ie,K)=>W2(ie,K,h,t),F=ie=>{if(i)return;const K=ie.clientX,Q=ie.clientY,W=Math.round((Q-k.startResizeY)/r),le=Math.round((K-k.startResizeX)/r),ge=()=>{const Me=k.initHeight-W,fe=k.initY+W;let xe=fe,$e=Me;if(S===In.xy)xe>0&&(xe=0,$e=k.initHeight-Math.abs(k.initY));else{const Ae=O(fe,Me);xe=Ae[0],$e=Ae[1]}C($e),x(xe)},Ve=()=>{const Me=k.initHeight+W;let[fe,xe]=O(k.initY,Me);S===In.xy&&xe{const Me=k.initWidth-le,fe=k.initX+le;let xe=fe,$e=Me;if(S===In.xy)xe>0&&(xe=0,$e=k.initWidth-Math.abs(k.initX));else{const Ae=A(fe,Me);xe=Ae[0],$e=Ae[1]}_($e),y(xe)},We=()=>{const Me=k.initWidth+le;let[fe,xe]=A(k.initX,Me);S===In.xy&&xe{b&&E(!1)};f.useEffect(()=>{if(b)return document.addEventListener("pointermove",F,nl),document.addEventListener("pointerup",V,nl),document.addEventListener("pointercancel",V,nl),()=>{document.removeEventListener("pointermove",F,nl),document.removeEventListener("pointerup",V,nl),document.removeEventListener("pointercancel",V,nl)}},[b,m,g,k]);const J=ie=>{const{ord:K}=ie.target.dataset;K&&(E(!0),P({initX:d,initY:h,initHeight:g,initWidth:m,startResizeX:ie.clientX,startResizeY:ie.clientY,ord:K}))},G=(ie,K,Q)=>{const ge="w-[12px] h-[12px] z-[4] absolute content-[''] block border-2 border-primary borde pointer-events-auto hover:bg-primary";let Ve="0",Ue="0",We=Q,Me="-6px";return Q===""&&(Me="50%",K==="left"||K==="right"?(We="top",Ue="-50%"):(We="left",Ve="-50%")),v.jsx("div",{className:Ce(ge,ie),style:{[K]:-6,[We]:Me,transform:`translate(${Ve}, ${Ue}) scale(${1/r})`},"data-ord":K+Q,"aria-label":K+Q,tabIndex:-1,role:"button"})},ae=()=>v.jsxs("div",{onFocus:M,onPointerDown:J,className:"absolute top-0 h-full w-full",children:[[In.y,In.xy].includes(S)?v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 w-full cursor-ns-resize h-[12px] mt-[-6px]","data-ord":"top"}),v.jsx("div",{className:"absolute pointer-events-auto bottom-0 left-0 w-full cursor-ns-resize h-[12px] mb-[-6px]","data-ord":"bottom"}),G("cursor-ns-resize","top",""),G("cursor-ns-resize","bottom","")]}):v.jsx(v.Fragment,{}),[In.x,In.xy].includes(S)?v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"absolute pointer-events-auto top-0 right-0 h-full cursor-ew-resize w-[12px] mr-[-6px]","data-ord":"right"}),v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 h-full cursor-ew-resize w-[12px] ml-[-6px]","data-ord":"left"}),G("cursor-ew-resize","left",""),G("cursor-ew-resize","right","")]}):v.jsx(v.Fragment,{}),S===In.xy?v.jsxs(v.Fragment,{children:[G("cursor-nw-resize","top","left"),G("cursor-ne-resize","top","right"),G("cursor-sw-resize","bottom","left"),G("cursor-se-resize","bottom","right")]}):v.jsx(v.Fragment,{})]}),U=ie=>{P({initX:d,initY:h,initHeight:g,initWidth:m,startResizeX:ie.clientX,startResizeY:ie.clientY,ord:""})},te=()=>v.jsxs("div",{className:Jw("border absolute pointer-events-auto px-2 py-1 rounded-full bg-background","origin-top-left top-0 left-0"),style:{transform:`scale(${1/r*.8})`},onPointerDown:U,children:[m," x ",g]}),L=()=>v.jsx("div",{className:Ce("outline-dashed outline-primary"),style:{height:g,width:m,outlineWidth:`${Kq/r*1.3}px`}});return o===!1||!u?null:v.jsx("div",{className:"absolute h-full w-full pointer-events-none z-[2]",children:v.jsxs("div",{className:"relative pointer-events-none z-[2] [box-shadow:0_0_0_9999px_rgba(0,_0,_0,_0.5)]",style:{height:g,width:m,left:d,top:h},children:[L(),te(),ae()]})})},Gq=200,Xq=10,Zq=200,lu=300;function qq(e){const{file:t}=e,{toast:n}=Td(),[r,o,i,s,l,u,d,h,m,g,y,x,_,C,S,b,E,k,P,M,A,O]=bt(H=>[H.disableShortCuts,H.windowSize,H.isInpainting,H.imageWidth,H.imageHeight,H.settings,H.serverConfig.enableAutoSaving,H.setImageSize,H.setBaseBrushSize,H.interactiveSegState,H.updateInteractiveSegState,H.handleCanvasMouseDown,H.handleCanvasMouseMove,H.undo,H.redo,H.undoDisabled(),H.redoDisabled(),H.getIsProcessing(),H.updateAppState,H.runMannually(),H.runInpainting,H.isCropperExtenderResizing]),F=bt(H=>H.editorState.baseBrushSize),V=bt(H=>H.getBrushSize()),J=bt(H=>H.editorState.renders),G=bt(H=>H.editorState.extraMasks),ae=bt(H=>H.editorState.temporaryMasks),U=bt(H=>H.editorState.lineGroups),te=bt(H=>H.editorState.curLineGroup),[L,ie]=f.useState(!1),[K,Q]=Rx(t),[W,le]=f.useState(),[ge,Ve]=f.useState(),[{x:Ue,y:We},Me]=f.useState({x:-1,y:-1}),[fe,xe]=f.useState(!1),[$e,Ae]=f.useState(!1),[Oe,je]=f.useState(!1),[Ot,ct]=f.useState(1),[Yt,Er]=f.useState(!1),[gt,js]=f.useState(1),I=o.width/2,X=o.height/2,Z=f.useRef(null),[we,he]=f.useState(!1),[de,ke]=f.useState(!1),[ft,pt]=f.useState(0),bn=f.useCallback(()=>te.length!==0,[te]);f.useEffect(()=>{if(!ge||!Q||s===0||l===0)return;const H=J.length===0?K:J[J.length-1];ge.canvas.width=s,ge.canvas.height=l,ge.clearRect(0,0,ge.canvas.width,ge.canvas.height),ge.drawImage(H,0,0,s,l)},[J,K,Q,ge,l,s]),f.useEffect(()=>{!W||!Q||s===0||l===0||(W.canvas.width=s,W.canvas.height=l,W.clearRect(0,0,W.canvas.width,W.canvas.height),ae.forEach(H=>{W.drawImage(H,0,0,s,l)}),G.forEach(H=>{W.drawImage(H,0,0,s,l)}),g.isInteractiveSeg&&g.tmpInteractiveSegMask&&W.drawImage(g.tmpInteractiveSegMask,0,0,s,l),GR(W,te))},[ae,G,Q,g,W,te,l,s]);const Cr=f.useCallback(async()=>{let H=t;if(J.length>0){const Ge=J[J.length-1];H=await ku(Ge.currentSrc,t.name,t.type)}return H},[t,J]),ki=()=>J.length!==0,_o=f.useCallback(()=>{let H=512,Ge=512;return Q?(J.length===0?(H=K.naturalWidth,Ge=K.naturalHeight):J.length!==0&&(H=J[J.length-1].width,Ge=J[J.length-1].height),[H,Ge]):[H,Ge]},[K,Q,J]);f.useEffect(()=>{var Gd;if(!Q)return;const[H,Ge]=_o();(H!==s||Ge!==l)&&h(H,Ge);const st=o.width/H,Qr=(o.height-Gq)/Ge;let an=1;(st<1||Qr<1)&&(an=Math.min(st,Qr)),js(an),ct(an),console.log(`[on file load] image size: ${H}x${Ge}, scale: ${an}, initialCentered: ${we}`),W!=null&&W.canvas&&(console.log("[on file load] set canvas size"),H!=W.canvas.width&&(W.canvas.width=H),Ge!=W.canvas.height&&(W.canvas.height=Ge)),we||((Gd=Z.current)==null||Gd.centerView(an,1),console.log("[on file load] centerView"),he(!0))},[Z,l,s,K,Q,o,we,_o]),f.useEffect(()=>{var H;console.log("[useEffect] centerView"),(H=Z==null?void 0:Z.current)==null||H.centerView(gt,1)},[l,s,Z,gt]);const Vn=f.useCallback(()=>{if(!gt||!o)return;const H=Z.current;if(!H)return;const Ge=(o.width-s*gt)/2,st=(o.height-l*gt)/2;H.setTransform(Ge,st,gt,200,"easeOutQuad"),H.instance.transformState.scale&&(H.instance.transformState.scale=gt),ct(gt),Er(!1)},[Z,o,l,s,o.height,gt]);f.useEffect(()=>(window.addEventListener("resize",()=>{Vn()}),()=>{window.removeEventListener("resize",()=>{Vn()})}),[o,Vn]),Zn("Escape",()=>{k||(de?ke(!1):Vn())},[de,i,Vn]);const Ri=H=>{const Ge=H.nativeEvent;Me({x:Ge.pageX,y:Ge.pageY})},zs=H=>{k||g.isInteractiveSeg||Oe||de&&te.length!==0&&_(c0(H))},Ti=async H=>{P({isPluginRunning:!0});const Ge=await Cr();try{const st=await gT(!0,jR.InteractiveSeg,Ge,void 0,H),{blob:Qr}=st,an=new Image;an.onload=()=>{y({tmpInteractiveSegMask:an})},an.src=Qr}catch(st){n({variant:"destructive",description:st.message?st.message:st.toString()})}P({isPluginRunning:!1})},$c=H=>{if(!bn())return;if(cC(H)){je(!1);return}g.isInteractiveSeg||Oe||!K.src||!(W!=null&&W.canvas)||i||de&&(M?ke(!1):A())},yg=H=>{if(g.isInteractiveSeg){const Ge=c0(H),st=[...g.clicks];lC(H)?st.push([Ge.x,Ge.y,0,st.length]):st.push([Ge.x,Ge.y,1,st.length]),Ti(st),y({clicks:st})}},wg=H=>{if(!(k||g.isInteractiveSeg||Oe||!Q||!(W!=null&&W.canvas))&&!lC(H)){if(cC(H)){je(!0);return}ke(!0),x(c0(H))}},Kd=H=>{H.preventDefault(),C()};Zn("meta+z,ctrl+z",Kd);const kc=H=>{H.preventDefault(),S()};Zn("shift+ctrl+z,shift+meta+z",kc),o2("Tab",H=>{H==null||H.preventDefault(),H==null||H.stopPropagation(),ki()&&ie(()=>(window.setTimeout(()=>{pt(100)},10),!0))},H=>{H==null||H.preventDefault(),H==null||H.stopPropagation(),ki()&&(window.setTimeout(()=>{pt(0)},10),window.setTimeout(()=>{ie(!1)},lu))});const Rc=f.useCallback(async()=>{if(t===void 0)return;if(d&&J.length>0){try{await Wj(J[J.length-1],t.name,t.type),n({description:"Save image success"})}catch(st){n({variant:"destructive",title:"Uh oh! Something went wrong.",description:st.message?st.message:st.toString()})}return}const H=t.name.replace(/(\.[\w\d_-]+)$/i,"_cleanup$1"),Ge=J[J.length-1];if(yF(Ge.currentSrc,H),u.enableDownloadMask){let st=t.name.replace(/(\.[\w\d_-]+)$/i,"_mask$1");st=st.replace(/\.[^/.]+$/,".jpg");const Qr=Lp(s,l,U),an=document.createElement("a");an.download=st,an.href=Qr.toDataURL("image/jpeg"),an.click()}},[t,d,J,u,l,s,U]);Zn("meta+s,ctrl+s",Rc);const Tc=H=>{H!==fe&&!Oe&&!O&&xe(H)},xg=f.useCallback(()=>{if(k)return"default";if(Oe)return"grab";if(fe)return"none"},[fe,Oe,k]);Zn("[",()=>{let H=F;F>10&&(H=F-10),F<=10&&F>0&&(H=F-5),m(H)},[F]),Zn("]",()=>{m(F+10)},[F]),Zn("shift+r",()=>{M&&bn()&&A()},[M,A,bn]),Zn("ctrl+c,meta+c",async()=>{await hF()&&J.length>0&&W!=null&&W.canvas&&(await vF(W==null?void 0:W.canvas),n({title:"Copy inpainting result to clipboard"}))},[J,W]),o2(" ",H=>{r||(H==null||H.preventDefault(),H==null||H.stopPropagation(),xe(!1),je(!0))},H=>{r||(H==null||H.preventDefault(),H==null||H.stopPropagation(),xe(!0),je(!1))});const Pc=()=>{var Ge,st,Qr,an;let H=gt;return((st=(Ge=Z.current)==null?void 0:Ge.instance)==null?void 0:st.transformState.scale)!==void 0&&(H=(an=(Qr=Z.current)==null?void 0:Qr.instance)==null?void 0:an.transformState.scale),H},Yd=(H,Ge)=>{const st=Pc();return{width:`${V*st}px`,height:`${V*st}px`,left:`${H}px`,top:`${Ge}px`,transform:"translate(-50%, -50%)"}},Ac=H=>v.jsx("div",{className:"absolute rounded-[50%] border-[1px] border-[solid] border-[#ffcc00] pointer-events-none bg-[#ffcc00bb]",style:H}),bg=H=>{m(H),$e||(Ae(!0),window.setTimeout(()=>{Ae(!1)},1e4))},_g=()=>v.jsx("div",{className:"absolute h-[20px] w-[20px] pointer-events-none rounded-[50%] bg-[rgba(21,_215,_121,_0.936)] [box-shadow:0_0_0_0_rgba(21,_215,_121,_0.936)] animate-pulse",style:{left:`${Ue}px`,top:`${We}px`,transform:"translate(-50%, -50%)"},children:v.jsx(fK,{})}),Sg=()=>v.jsx(pq,{ref:H=>{H&&(Z.current=H)},panning:{disabled:!Oe,velocityDisabled:!0},wheel:{step:.05},centerZoomedOut:!0,alignmentAnimation:{disabled:!0},centerOnInit:!0,limitToBounds:!1,doubleClick:{disabled:!0},initialScale:gt,minScale:gt*.3,onPanning:()=>{Yt||Er(!0)},onZoom:H=>{ct(H.state.scale)},children:v.jsxs(gq,{contentStyle:{visibility:we?"visible":"hidden"},children:[v.jsxs("div",{className:"grid [grid-template-areas:'editor-content'] gap-y-4",children:[v.jsx("canvas",{className:"[grid-area:editor-content]",style:{clipPath:`inset(0 ${ft}% 0 0)`,transition:`clip-path ${lu}ms`},ref:H=>{if(H&&!ge){const Ge=H.getContext("2d");Ge&&Ve(Ge)}}}),v.jsx("canvas",{className:Ce("[grid-area:editor-content]",k?"pointer-events-none animate-pulse duration-600":""),style:{cursor:xg(),clipPath:`inset(0 ${ft}% 0 0)`,transition:`clip-path ${lu}ms`},onContextMenu:H=>{H.preventDefault()},onMouseOver:()=>{Tc(!0),Ae(!1)},onFocus:()=>Tc(!0),onMouseLeave:()=>Tc(!1),onMouseDown:wg,onMouseUp:yg,onMouseMove:zs,ref:H=>{if(H&&!W){const Ge=H.getContext("2d");Ge&&le(Ge)}}}),v.jsx("div",{className:"[grid-area:editor-content] pointer-events-none grid [grid-template-areas:'original-image-content']",style:{width:`${s}px`,height:`${l}px`},children:L&&v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"[grid-area:original-image-content] z-10 bg-primary h-full w-[6px] justify-self-end",style:{marginRight:`${ft}%`,transition:`margin-right ${lu}ms`}}),v.jsx("img",{className:"[grid-area:original-image-content]",src:K.src,alt:"original",style:{width:`${s}px`,height:`${l}px`}})]})})]}),v.jsx(Bq,{maxHeight:l,maxWidth:s,minHeight:Math.min(512,l),minWidth:Math.min(512,s),scale:Pc(),show:u.showCropper}),v.jsx(Yq,{minHeight:Math.min(512,l),minWidth:Math.min(512,s),scale:Pc(),show:u.showExtender}),g.isInteractiveSeg?v.jsx(Wq,{}):v.jsx(v.Fragment,{})]})});return v.jsxs("div",{className:"flex w-screen h-screen justify-center items-center","aria-hidden":"true",onMouseMove:Ri,onMouseUp:$c,children:[Sg(),fe&&!i&&!Oe&&(g.isInteractiveSeg?_g():Ac(Yd(Ue,We))),$e&&Ac(Yd(I,X)),v.jsxs("div",{className:" overflow-hidden fixed flex bottom-5 border px-4 py-2 rounded-[3rem] gap-8 items-center justify-center backdrop-filter backdrop-blur-md bg-background/70",children:[v.jsx(uo,{className:"w-48",defaultValue:[50],min:Xq,max:Zq,step:1,tabIndex:-1,value:[F],onValueChange:H=>bg(H[0]),onClick:()=>Ae(!1)}),v.jsxs("div",{className:"flex gap-2",children:[v.jsx(vn,{tooltip:"Reset zoom & pan",disabled:Ot===gt&&Yt===!1,onClick:Vn,children:v.jsx(qU,{})}),v.jsx(vn,{tooltip:"Undo",onClick:Kd,disabled:b,children:v.jsx(lV,{})}),v.jsx(vn,{tooltip:"Redo",onClick:kc,disabled:E,children:v.jsx(iV,{})}),v.jsx(vn,{tooltip:"Show original image",onPointerDown:H=>{H.preventDefault(),ie(()=>(window.setTimeout(()=>{pt(100)},10),!0))},onPointerUp:()=>{window.setTimeout(()=>{pt(0)},10),window.setTimeout(()=>{ie(!1)},lu)},disabled:J.length===0,children:v.jsx(QU,{})}),v.jsx(vn,{tooltip:"Save Image",disabled:!J.length,onClick:Rc,children:v.jsx(XU,{})}),u.enableManualInpainting&&u.model.model_type==="inpaint"?v.jsx(vn,{tooltip:"Run Inpainting",disabled:k||!bn()&&G.length===0,onClick:()=>{A()},children:v.jsx(ZU,{})}):v.jsx(v.Fragment,{})]})]})]})}const Qq=()=>{const[e,t]=bt(n=>[n.imageWidth,n.imageHeight]);return!e||!t?null:v.jsxs("div",{className:"border rounded-lg px-2 py-[6px] z-10 bg-background",children:[e,"x",t]})},B1=["Enter"," "],Jq=["ArrowDown","PageUp","Home"],V3=["ArrowUp","PageDown","End"],eQ=[...Jq,...V3],tQ={ltr:[...B1,"ArrowRight"],rtl:[...B1,"ArrowLeft"]},nQ={ltr:["ArrowLeft"],rtl:["ArrowRight"]},fg="Menu",[ld,rQ,oQ]=zd(fg),[Na,W3]=An(fg,[oQ,Ns,Qm]),pg=Ns(),H3=Qm(),[K3,Fs]=Na(fg),[iQ,Hd]=Na(fg),sQ=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:o,onOpenChange:i,modal:s=!0}=e,l=pg(t),[u,d]=f.useState(null),h=f.useRef(!1),m=Ft(i),g=Sc(o);return f.useEffect(()=>{const y=()=>{h.current=!0,document.addEventListener("pointerdown",x,{capture:!0,once:!0}),document.addEventListener("pointermove",x,{capture:!0,once:!0})},x=()=>h.current=!1;return document.addEventListener("keydown",y,{capture:!0}),()=>{document.removeEventListener("keydown",y,{capture:!0}),document.removeEventListener("pointerdown",x,{capture:!0}),document.removeEventListener("pointermove",x,{capture:!0})}},[]),f.createElement(Od,l,f.createElement(K3,{scope:t,open:n,onOpenChange:m,content:u,onContentChange:d},f.createElement(iQ,{scope:t,onClose:f.useCallback(()=>m(!1),[m]),isUsingKeyboardRef:h,dir:g,modal:s},r)))},Y3=f.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,o=pg(n);return f.createElement(zm,Y({},o,r,{ref:t}))}),G3="MenuPortal",[aQ,X3]=Na(G3,{forceMount:void 0}),lQ=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:o}=e,i=Fs(G3,t);return f.createElement(aQ,{scope:t,forceMount:n},f.createElement(xn,{present:n||i.open},f.createElement(Md,{asChild:!0,container:o},r)))},yo="MenuContent",[cQ,Jx]=Na(yo),uQ=f.forwardRef((e,t)=>{const n=X3(yo,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,i=Fs(yo,e.__scopeMenu),s=Hd(yo,e.__scopeMenu);return f.createElement(ld.Provider,{scope:e.__scopeMenu},f.createElement(xn,{present:r||i.open},f.createElement(ld.Slot,{scope:e.__scopeMenu},s.modal?f.createElement(dQ,Y({},o,{ref:t})):f.createElement(fQ,Y({},o,{ref:t})))))}),dQ=f.forwardRef((e,t)=>{const n=Fs(yo,e.__scopeMenu),r=f.useRef(null),o=Be(t,r);return f.useEffect(()=>{const i=r.current;if(i)return Xm(i)},[]),f.createElement(eb,Y({},e,{ref:o,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:ue(e.onFocusOutside,i=>i.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)}))}),fQ=f.forwardRef((e,t)=>{const n=Fs(yo,e.__scopeMenu);return f.createElement(eb,Y({},e,{ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)}))}),eb=f.forwardRef((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:o,onOpenAutoFocus:i,onCloseAutoFocus:s,disableOutsidePointerEvents:l,onEntryFocus:u,onEscapeKeyDown:d,onPointerDownOutside:h,onFocusOutside:m,onInteractOutside:g,onDismiss:y,disableOutsideScroll:x,..._}=e,C=Fs(yo,n),S=Hd(yo,n),b=pg(n),E=H3(n),k=rQ(n),[P,M]=f.useState(null),A=f.useRef(null),O=Be(t,A,C.onContentChange),F=f.useRef(0),V=f.useRef(""),J=f.useRef(0),G=f.useRef(null),ae=f.useRef("right"),U=f.useRef(0),te=x?Gm:f.Fragment,L=x?{as:Wo,allowPinchZoom:!0}:void 0,ie=Q=>{var W,le;const ge=V.current+Q,Ve=k().filter($e=>!$e.disabled),Ue=document.activeElement,We=(W=Ve.find($e=>$e.ref.current===Ue))===null||W===void 0?void 0:W.textValue,Me=Ve.map($e=>$e.textValue),fe=TQ(Me,ge,We),xe=(le=Ve.find($e=>$e.textValue===fe))===null||le===void 0?void 0:le.ref.current;(function $e(Ae){V.current=Ae,window.clearTimeout(F.current),Ae!==""&&(F.current=window.setTimeout(()=>$e(""),1e3))})(ge),xe&&setTimeout(()=>xe.focus())};f.useEffect(()=>()=>window.clearTimeout(F.current),[]),Km();const K=f.useCallback(Q=>{var W,le;return ae.current===((W=G.current)===null||W===void 0?void 0:W.side)&&AQ(Q,(le=G.current)===null||le===void 0?void 0:le.area)},[]);return f.createElement(cQ,{scope:n,searchRef:V,onItemEnter:f.useCallback(Q=>{K(Q)&&Q.preventDefault()},[K]),onItemLeave:f.useCallback(Q=>{var W;K(Q)||((W=A.current)===null||W===void 0||W.focus(),M(null))},[K]),onTriggerLeave:f.useCallback(Q=>{K(Q)&&Q.preventDefault()},[K]),pointerGraceTimerRef:J,onPointerGraceIntentChange:f.useCallback(Q=>{G.current=Q},[])},f.createElement(te,L,f.createElement(Hm,{asChild:!0,trapped:o,onMountAutoFocus:ue(i,Q=>{var W;Q.preventDefault(),(W=A.current)===null||W===void 0||W.focus()}),onUnmountAutoFocus:s},f.createElement(yc,{asChild:!0,disableOutsidePointerEvents:l,onEscapeKeyDown:d,onPointerDownOutside:h,onFocusOutside:m,onInteractOutside:g,onDismiss:y},f.createElement(ZP,Y({asChild:!0},E,{dir:S.dir,orientation:"vertical",loop:r,currentTabStopId:P,onCurrentTabStopIdChange:M,onEntryFocus:ue(u,Q=>{S.isUsingKeyboardRef.current||Q.preventDefault()})}),f.createElement(Bm,Y({role:"menu","aria-orientation":"vertical","data-state":tA(C.open),"data-radix-menu-content":"",dir:S.dir},b,_,{ref:O,style:{outline:"none",..._.style},onKeyDown:ue(_.onKeyDown,Q=>{const le=Q.target.closest("[data-radix-menu-content]")===Q.currentTarget,ge=Q.ctrlKey||Q.altKey||Q.metaKey,Ve=Q.key.length===1;le&&(Q.key==="Tab"&&Q.preventDefault(),!ge&&Ve&&ie(Q.key));const Ue=A.current;if(Q.target!==Ue||!eQ.includes(Q.key))return;Q.preventDefault();const Me=k().filter(fe=>!fe.disabled).map(fe=>fe.ref.current);V3.includes(Q.key)&&Me.reverse(),kQ(Me)}),onBlur:ue(e.onBlur,Q=>{Q.currentTarget.contains(Q.target)||(window.clearTimeout(F.current),V.current="")}),onPointerMove:ue(e.onPointerMove,cd(Q=>{const W=Q.target,le=U.current!==Q.clientX;if(Q.currentTarget.contains(W)&&le){const ge=Q.clientX>U.current?"right":"left";ae.current=ge,U.current=Q.clientX}}))})))))))}),pQ=f.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return f.createElement(Pe.div,Y({},r,{ref:t}))}),U1="MenuItem",H2="menu.itemSelect",tb=f.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...o}=e,i=f.useRef(null),s=Hd(U1,e.__scopeMenu),l=Jx(U1,e.__scopeMenu),u=Be(t,i),d=f.useRef(!1),h=()=>{const m=i.current;if(!n&&m){const g=new CustomEvent(H2,{bubbles:!0,cancelable:!0});m.addEventListener(H2,y=>r==null?void 0:r(y),{once:!0}),cx(m,g),g.defaultPrevented?d.current=!1:s.onClose()}};return f.createElement(Z3,Y({},o,{ref:u,disabled:n,onClick:ue(e.onClick,h),onPointerDown:m=>{var g;(g=e.onPointerDown)===null||g===void 0||g.call(e,m),d.current=!0},onPointerUp:ue(e.onPointerUp,m=>{var g;d.current||(g=m.currentTarget)===null||g===void 0||g.click()}),onKeyDown:ue(e.onKeyDown,m=>{const g=l.searchRef.current!=="";n||g&&m.key===" "||B1.includes(m.key)&&(m.currentTarget.click(),m.preventDefault())})}))}),Z3=f.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:o,...i}=e,s=Jx(U1,n),l=H3(n),u=f.useRef(null),d=Be(t,u),[h,m]=f.useState(!1),[g,y]=f.useState("");return f.useEffect(()=>{const x=u.current;if(x){var _;y(((_=x.textContent)!==null&&_!==void 0?_:"").trim())}},[i.children]),f.createElement(ld.ItemSlot,{scope:n,disabled:r,textValue:o??g},f.createElement(qP,Y({asChild:!0},l,{focusable:!r}),f.createElement(Pe.div,Y({role:"menuitem","data-highlighted":h?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0},i,{ref:d,onPointerMove:ue(e.onPointerMove,cd(x=>{r?s.onItemLeave(x):(s.onItemEnter(x),x.defaultPrevented||x.currentTarget.focus())})),onPointerLeave:ue(e.onPointerLeave,cd(x=>s.onItemLeave(x))),onFocus:ue(e.onFocus,()=>m(!0)),onBlur:ue(e.onBlur,()=>m(!1))}))))}),hQ=f.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...o}=e;return f.createElement(Q3,{scope:e.__scopeMenu,checked:n},f.createElement(tb,Y({role:"menuitemcheckbox","aria-checked":om(n)?"mixed":n},o,{ref:t,"data-state":nb(n),onSelect:ue(o.onSelect,()=>r==null?void 0:r(om(n)?!0:!n),{checkForDefaultPrevented:!1})})))}),mQ="MenuRadioGroup",[kte,gQ]=Na(mQ,{value:void 0,onValueChange:()=>{}}),vQ="MenuRadioItem",yQ=f.forwardRef((e,t)=>{const{value:n,...r}=e,o=gQ(vQ,e.__scopeMenu),i=n===o.value;return f.createElement(Q3,{scope:e.__scopeMenu,checked:i},f.createElement(tb,Y({role:"menuitemradio","aria-checked":i},r,{ref:t,"data-state":nb(i),onSelect:ue(r.onSelect,()=>{var s;return(s=o.onValueChange)===null||s===void 0?void 0:s.call(o,n)},{checkForDefaultPrevented:!1})})))}),q3="MenuItemIndicator",[Q3,wQ]=Na(q3,{checked:!1}),xQ=f.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...o}=e,i=wQ(q3,n);return f.createElement(xn,{present:r||om(i.checked)||i.checked===!0},f.createElement(Pe.span,Y({},o,{ref:t,"data-state":nb(i.checked)})))}),bQ=f.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return f.createElement(Pe.div,Y({role:"separator","aria-orientation":"horizontal"},r,{ref:t}))}),J3="MenuSub",[_Q,eA]=Na(J3),SQ=e=>{const{__scopeMenu:t,children:n,open:r=!1,onOpenChange:o}=e,i=Fs(J3,t),s=pg(t),[l,u]=f.useState(null),[d,h]=f.useState(null),m=Ft(o);return f.useEffect(()=>(i.open===!1&&m(!1),()=>m(!1)),[i.open,m]),f.createElement(Od,s,f.createElement(K3,{scope:t,open:r,onOpenChange:m,content:d,onContentChange:h},f.createElement(_Q,{scope:t,contentId:nr(),triggerId:nr(),trigger:l,onTriggerChange:u},n)))},gp="MenuSubTrigger",EQ=f.forwardRef((e,t)=>{const n=Fs(gp,e.__scopeMenu),r=Hd(gp,e.__scopeMenu),o=eA(gp,e.__scopeMenu),i=Jx(gp,e.__scopeMenu),s=f.useRef(null),{pointerGraceTimerRef:l,onPointerGraceIntentChange:u}=i,d={__scopeMenu:e.__scopeMenu},h=f.useCallback(()=>{s.current&&window.clearTimeout(s.current),s.current=null},[]);return f.useEffect(()=>h,[h]),f.useEffect(()=>{const m=l.current;return()=>{window.clearTimeout(m),u(null)}},[l,u]),f.createElement(Y3,Y({asChild:!0},d),f.createElement(Z3,Y({id:o.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":o.contentId,"data-state":tA(n.open)},e,{ref:Am(t,o.onTriggerChange),onClick:m=>{var g;(g=e.onClick)===null||g===void 0||g.call(e,m),!(e.disabled||m.defaultPrevented)&&(m.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:ue(e.onPointerMove,cd(m=>{i.onItemEnter(m),!m.defaultPrevented&&!e.disabled&&!n.open&&!s.current&&(i.onPointerGraceIntentChange(null),s.current=window.setTimeout(()=>{n.onOpenChange(!0),h()},100))})),onPointerLeave:ue(e.onPointerLeave,cd(m=>{var g;h();const y=(g=n.content)===null||g===void 0?void 0:g.getBoundingClientRect();if(y){var x;const _=(x=n.content)===null||x===void 0?void 0:x.dataset.side,C=_==="right",S=C?-5:5,b=y[C?"left":"right"],E=y[C?"right":"left"];i.onPointerGraceIntentChange({area:[{x:m.clientX+S,y:m.clientY},{x:b,y:y.top},{x:E,y:y.top},{x:E,y:y.bottom},{x:b,y:y.bottom}],side:_}),window.clearTimeout(l.current),l.current=window.setTimeout(()=>i.onPointerGraceIntentChange(null),300)}else{if(i.onTriggerLeave(m),m.defaultPrevented)return;i.onPointerGraceIntentChange(null)}})),onKeyDown:ue(e.onKeyDown,m=>{const g=i.searchRef.current!=="";if(!(e.disabled||g&&m.key===" ")&&tQ[r.dir].includes(m.key)){var y;n.onOpenChange(!0),(y=n.content)===null||y===void 0||y.focus(),m.preventDefault()}})})))}),CQ="MenuSubContent",$Q=f.forwardRef((e,t)=>{const n=X3(yo,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,i=Fs(yo,e.__scopeMenu),s=Hd(yo,e.__scopeMenu),l=eA(CQ,e.__scopeMenu),u=f.useRef(null),d=Be(t,u);return f.createElement(ld.Provider,{scope:e.__scopeMenu},f.createElement(xn,{present:r||i.open},f.createElement(ld.Slot,{scope:e.__scopeMenu},f.createElement(eb,Y({id:l.contentId,"aria-labelledby":l.triggerId},o,{ref:d,align:"start",side:s.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:h=>{var m;s.isUsingKeyboardRef.current&&((m=u.current)===null||m===void 0||m.focus()),h.preventDefault()},onCloseAutoFocus:h=>h.preventDefault(),onFocusOutside:ue(e.onFocusOutside,h=>{h.target!==l.trigger&&i.onOpenChange(!1)}),onEscapeKeyDown:ue(e.onEscapeKeyDown,h=>{s.onClose(),h.preventDefault()}),onKeyDown:ue(e.onKeyDown,h=>{const m=h.currentTarget.contains(h.target),g=nQ[s.dir].includes(h.key);if(m&&g){var y;i.onOpenChange(!1),(y=l.trigger)===null||y===void 0||y.focus(),h.preventDefault()}})})))))});function tA(e){return e?"open":"closed"}function om(e){return e==="indeterminate"}function nb(e){return om(e)?"indeterminate":e?"checked":"unchecked"}function kQ(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function RQ(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function TQ(e,t,n){const o=t.length>1&&Array.from(t).every(d=>d===t[0])?t[0]:t,i=n?e.indexOf(n):-1;let s=RQ(e,Math.max(i,0));o.length===1&&(s=s.filter(d=>d!==n));const u=s.find(d=>d.toLowerCase().startsWith(o.toLowerCase()));return u!==n?u:void 0}function PQ(e,t){const{x:n,y:r}=e;let o=!1;for(let i=0,s=t.length-1;ir!=h>r&&n<(d-l)*(r-u)/(h-u)+l&&(o=!o)}return o}function AQ(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return PQ(n,t)}function cd(e){return t=>t.pointerType==="mouse"?e(t):void 0}const OQ=sQ,MQ=Y3,NQ=lQ,DQ=uQ,IQ=pQ,LQ=tb,FQ=hQ,jQ=yQ,zQ=xQ,BQ=bQ,UQ=SQ,VQ=EQ,WQ=$Q,nA="DropdownMenu",[HQ,Rte]=An(nA,[W3]),Sr=W3(),[KQ,rA]=HQ(nA),YQ=e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:o,defaultOpen:i,onOpenChange:s,modal:l=!0}=e,u=Sr(t),d=f.useRef(null),[h=!1,m]=Zr({prop:o,defaultProp:i,onChange:s});return f.createElement(KQ,{scope:t,triggerId:nr(),triggerRef:d,contentId:nr(),open:h,onOpenChange:m,onOpenToggle:f.useCallback(()=>m(g=>!g),[m]),modal:l},f.createElement(OQ,Y({},u,{open:h,onOpenChange:m,dir:r,modal:l}),n))},GQ="DropdownMenuTrigger",XQ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...o}=e,i=rA(GQ,n),s=Sr(n);return f.createElement(MQ,Y({asChild:!0},s),f.createElement(Pe.button,Y({type:"button",id:i.triggerId,"aria-haspopup":"menu","aria-expanded":i.open,"aria-controls":i.open?i.contentId:void 0,"data-state":i.open?"open":"closed","data-disabled":r?"":void 0,disabled:r},o,{ref:Am(t,i.triggerRef),onPointerDown:ue(e.onPointerDown,l=>{!r&&l.button===0&&l.ctrlKey===!1&&(i.onOpenToggle(),i.open||l.preventDefault())}),onKeyDown:ue(e.onKeyDown,l=>{r||(["Enter"," "].includes(l.key)&&i.onOpenToggle(),l.key==="ArrowDown"&&i.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(l.key)&&l.preventDefault())})})))}),ZQ=e=>{const{__scopeDropdownMenu:t,...n}=e,r=Sr(t);return f.createElement(NQ,Y({},r,n))},qQ="DropdownMenuContent",QQ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=rA(qQ,n),i=Sr(n),s=f.useRef(!1);return f.createElement(DQ,Y({id:o.contentId,"aria-labelledby":o.triggerId},i,r,{ref:t,onCloseAutoFocus:ue(e.onCloseAutoFocus,l=>{var u;s.current||(u=o.triggerRef.current)===null||u===void 0||u.focus(),s.current=!1,l.preventDefault()}),onInteractOutside:ue(e.onInteractOutside,l=>{const u=l.detail.originalEvent,d=u.button===0&&u.ctrlKey===!0,h=u.button===2||d;(!o.modal||h)&&(s.current=!0)}),style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}}))}),JQ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(IQ,Y({},o,r,{ref:t}))}),eJ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(LQ,Y({},o,r,{ref:t}))}),tJ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(FQ,Y({},o,r,{ref:t}))}),nJ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(jQ,Y({},o,r,{ref:t}))}),rJ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(zQ,Y({},o,r,{ref:t}))}),oJ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(BQ,Y({},o,r,{ref:t}))}),iJ=e=>{const{__scopeDropdownMenu:t,children:n,open:r,onOpenChange:o,defaultOpen:i}=e,s=Sr(t),[l=!1,u]=Zr({prop:r,defaultProp:i,onChange:o});return f.createElement(UQ,Y({},s,{open:l,onOpenChange:u}),n)},sJ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(VQ,Y({},o,r,{ref:t}))}),aJ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(WQ,Y({},o,r,{ref:t,style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}}))}),lJ=YQ,cJ=XQ,uJ=ZQ,oA=QQ,iA=JQ,sA=eJ,aA=tJ,lA=nJ,cA=rJ,uA=oJ,dJ=iJ,dA=sJ,fA=aJ,fJ=lJ,pJ=cJ,K2=dJ,V1=f.forwardRef(({className:e,inset:t,children:n,...r},o)=>v.jsxs(dA,{ref:o,className:Ce("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",e),...r,children:[n,v.jsx(ez,{className:"ml-auto h-4 w-4"})]}));V1.displayName=dA.displayName;const W1=f.forwardRef(({className:e,...t},n)=>v.jsx(fA,{ref:n,className:Ce("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...t}));W1.displayName=fA.displayName;const pA=f.forwardRef(({className:e,sideOffset:t=4,...n},r)=>v.jsx(uJ,{children:v.jsx(oA,{ref:r,sideOffset:t,className:Ce("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md","data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),onCloseAutoFocus:o=>o.preventDefault(),...n})}));pA.displayName=oA.displayName;const il=f.forwardRef(({className:e,inset:t,...n},r)=>v.jsx(sA,{ref:r,className:Ce("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",e),...n}));il.displayName=sA.displayName;const hJ=f.forwardRef(({className:e,children:t,checked:n,...r},o)=>v.jsxs(aA,{ref:o,className:Ce("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),checked:n,...r,children:[v.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:v.jsx(cA,{children:v.jsx(vT,{className:"h-4 w-4"})})}),t]}));hJ.displayName=aA.displayName;const mJ=f.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(lA,{ref:r,className:Ce("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[v.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:v.jsx(cA,{children:v.jsx(iz,{className:"h-4 w-4 fill-current"})})}),t]}));mJ.displayName=lA.displayName;const gJ=f.forwardRef(({className:e,inset:t,...n},r)=>v.jsx(iA,{ref:r,className:Ce("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",e),...n}));gJ.displayName=iA.displayName;const vJ=f.forwardRef(({className:e,...t},n)=>v.jsx(uA,{ref:n,className:Ce("-mx-1 my-1 h-px bg-muted",e),...t}));vJ.displayName=uA.displayName;const Y2={RemoveBG:{IconClass:VC,showName:"RemoveBG"},AnimeSeg:{IconClass:VC,showName:"Anime Segmentation"},RealESRGAN:{IconClass:XT,showName:"RealESRGAN"},GFPGAN:{IconClass:WC,showName:"GFPGAN"},RestoreFormer:{IconClass:WC,showName:"RestoreFormer"},InteractiveSeg:{IconClass:rV,showName:"Interactive Segmentation"}},yJ=()=>{const[e,t,n,r]=bt(d=>[d.file,d.serverConfig.plugins,d.updateInteractiveSegState,d.runRenderablePlugin]),o=!e;if(t.length===0)return null;const i=(d,h)=>{h==="InteractiveSeg"?n({isInteractiveSeg:!0}):r(d,h)},s=()=>v.jsxs(K2,{children:[v.jsx(V1,{disabled:o,children:v.jsxs("div",{className:"flex gap-2 items-center",children:[v.jsx(XT,{}),"RealESRGAN"]})}),v.jsxs(W1,{children:[v.jsx(il,{onClick:()=>r(!1,"RealESRGAN",{upscale:2}),children:"upscale 2x"}),v.jsx(il,{onClick:()=>r(!1,"RealESRGAN",{upscale:4}),children:"upscale 4x"})]})]},"RealESRGAN"),l=d=>{const{IconClass:h,showName:m}=Y2[d.name];return v.jsxs(K2,{children:[v.jsx(V1,{disabled:o,children:v.jsxs("div",{className:"flex gap-2 items-center",children:[v.jsx(h,{className:"p-1"}),m]})}),v.jsxs(W1,{children:[v.jsx(il,{onClick:()=>i(!1,d.name),children:"Remove Background"}),v.jsx(il,{onClick:()=>i(!0,d.name),children:"Generate Mask"})]})]},d.name)},u=()=>t.map(d=>{const{IconClass:h,showName:m}=Y2[d.name];return d.name==="RealESRGAN"?s():d.name==="RemoveBG"||d.name==="AnimeSeg"?l(d):v.jsx(il,{onClick:()=>i(!1,d.name),disabled:o,children:v.jsxs("div",{className:"flex gap-2 items-center",children:[v.jsx(h,{className:"p-1"}),m]})},d.name)});return v.jsxs(fJ,{modal:!1,children:[v.jsx(pJ,{className:"border rounded-lg z-10 bg-background outline-none",tabIndex:-1,children:v.jsx(Rn,{variant:"ghost",size:"icon",asChild:!0,className:"p-1.5",children:v.jsx(HU,{strokeWidth:1})})}),v.jsx(pA,{side:"bottom",align:"start",children:u()})]})},wJ=Sx,xJ=gP,bJ=Ex,hA=f.forwardRef(({className:e,...t},n)=>v.jsx(Nd,{className:Ce("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t,ref:n}));hA.displayName=Nd.displayName;const _J=Om("fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=closed]:duration-200 data-[state=open]:duration-300",{variants:{side:{top:"inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",bottom:"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",left:"inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",right:"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm"}},defaultVariants:{side:"right"}}),mA=f.forwardRef(({side:e="right",className:t,children:n,...r},o)=>v.jsxs(bJ,{children:[v.jsx(hA,{}),v.jsx(Dd,{ref:o,className:Ce(_J({side:e}),t),...r,children:n})]}));mA.displayName=Dd.displayName;const gA=({className:e,...t})=>v.jsx("div",{className:Ce("flex flex-col space-y-2 text-center sm:text-left",e),...t});gA.displayName="SheetHeader";const SJ=f.forwardRef(({className:e,...t},n)=>v.jsx(Id,{ref:n,className:Ce("text-lg font-semibold text-foreground",e),...t}));SJ.displayName=Id.displayName;const EJ=f.forwardRef(({className:e,...t},n)=>v.jsx(Ld,{ref:n,className:Ce("text-sm text-muted-foreground",e),...t}));EJ.displayName=Ld.displayName;const Ut=({children:e})=>v.jsx("div",{className:"flex justify-between items-center pr-2",children:e}),Pt=({text:e,toolTip:t="",url:n,htmlFor:r,disabled:o=!1})=>v.jsxs(YT,{children:[v.jsx(GT,{asChild:!0,children:v.jsx(Gx,{htmlFor:r||e.toLowerCase().replace(" ","-"),className:"font-medium",disabled:o,children:e})}),t||n?v.jsxs(xx,{className:"flex flex-col max-w-xs text-sm",side:"left",children:[v.jsx("p",{children:t}),n?v.jsx(Rn,{variant:"link",className:"justify-end",children:v.jsx("a",{href:n,target:"_blank",children:"More info"})}):v.jsx(v.Fragment,{})]}):v.jsx(v.Fragment,{})]}),CJ=()=>{const[e,t]=bt(n=>[n.settings,n.updateSettings]);return v.jsxs("div",{className:"flex flex-col gap-4 mt-4",children:[v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{htmlFor:"steps",text:"Steps",toolTip:"The number of denoising steps. More denoising steps usually lead to a higher quality image at the expense of slower inference."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[30],min:1,max:100,step:1,value:[Math.floor(e.ldmSteps)],onValueChange:n=>t({ldmSteps:n[0]})}),v.jsx(Gn,{id:"steps",className:"w-[60px] rounded-full",numberValue:e.ldmSteps,allowFloat:!1,onNumberValueChange:n=>{t({ldmSteps:n})}})]})]}),v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Sampler"}),v.jsxs(aa,{value:e.ldmSampler,onValueChange:n=>{t({ldmSampler:n})},children:[v.jsx(ls,{className:"w-[100px]",children:v.jsx(la,{placeholder:"Select sampler"})}),v.jsx(cs,{align:"end",children:v.jsx(wl,{children:Object.values(Zw).map(n=>v.jsx(us,{value:n,children:n},n))})})]})]})]})},vA=f.forwardRef(({className:e,...t},n)=>v.jsx("textarea",{className:Ce("flex min-h-[60px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",e,"overflow-auto"),tabIndex:-1,ref:n,...t}));vA.displayName="Textarea";const vp=({text:e,onClick:t})=>{const[n]=bt(r=>[r.settings.showExtender]);return v.jsx(Rn,{variant:"outline",className:"p-1 h-8",disabled:!n,onClick:t,children:v.jsx("div",{className:"flex items-center gap-1",children:e})})},$J=()=>{const[e,t,n,r,o,i,s,l,u,d,h]=bt(L=>[L.serverConfig.samplers,L.settings,L.paintByExampleFile,L.getIsProcessing(),L.updateSettings,L.runInpainting,L.updateAppState,L.updateExtenderByBuiltIn,L.updateExtenderDirection,L.adjustMask,L.clearMask]),[m,g]=Rx(n),y=f.useRef(null);OP(y,()=>{y!=null&&y.current&&y.current.blur()});const x=L=>{L.key==="Enter"&&L.ctrlKey&&t.prompt.length!==0&&i()},_=()=>v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Cropper",toolTip:"Inpainting on part of image, improve inference speed and reduce memory usage."}),v.jsx(co,{id:"cropper",checked:t.showCropper,onCheckedChange:L=>{o({showCropper:L}),L&&o({showExtender:!1})}})]}),C=()=>t.model.support_controlnet?v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex justify-between items-center pr-2",children:[v.jsx(Pt,{text:"ControlNet",toolTip:"Using an additional conditioning image to control how an image is generated",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#controlnet"}),v.jsx(co,{id:"controlnet",checked:t.enableControlnet,onCheckedChange:L=>{o({enableControlnet:L})}})]}),v.jsx("div",{className:"flex flex-col gap-1",children:v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[100],min:1,max:100,step:1,disabled:!t.enableControlnet,value:[Math.floor(t.controlnetConditioningScale*100)],onValueChange:L=>o({controlnetConditioningScale:L[0]/100})}),v.jsx(Gn,{id:"controlnet-weight",className:"w-[60px] rounded-full",disabled:!t.enableControlnet,numberValue:t.controlnetConditioningScale,allowFloat:!1,onNumberValueChange:L=>{o({controlnetConditioningScale:L})}})]})}),v.jsx("div",{className:"pr-2",children:v.jsxs(aa,{defaultValue:t.controlnetMethod,value:t.controlnetMethod,onValueChange:L=>{o({controlnetMethod:L})},disabled:!t.enableControlnet,children:[v.jsx(ls,{children:v.jsx(la,{placeholder:"Select control method"})}),v.jsx(cs,{align:"end",children:v.jsx(wl,{children:Object.values(t.model.controlnets).map(L=>v.jsx(us,{value:L,children:L.split("/")[1]},L))})})]})})]}),v.jsx(Fn,{})]}):null,S=()=>t.model.support_lcm_lora?v.jsxs(v.Fragment,{children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"LCM LoRA",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inference_with_lcm_lora",toolTip:"Enable quality image generation in typically 2-4 steps. Suggest disabling guidance_scale by setting it to 0. You can also try values between 1.0 and 2.0. When LCM Lora is enabled, LCMSampler will be used automatically."}),v.jsx(co,{id:"lcm-lora",checked:t.enableLCMLora,onCheckedChange:L=>{o({enableLCMLora:L})}})]}),v.jsx(Fn,{})]}):null,b=()=>t.model.support_freeu?v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex justify-between items-center pr-2",children:[v.jsx(Pt,{text:"FreeU",toolTip:"FreeU is a technique for improving image quality. Different models may require different FreeU-specific hyperparameters, which can be viewed in the more info section.",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/freeu"}),v.jsx(co,{id:"freeu",checked:t.enableFreeu,onCheckedChange:L=>{o({enableFreeu:L})}})]}),v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex justify-center gap-6",children:[v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-s1",text:"s1",disabled:!t.enableFreeu}),v.jsx(Gn,{id:"freeu-s1",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.s1,allowFloat:!0,onNumberValueChange:L=>{o({freeuConfig:{...t.freeuConfig,s1:L}})}})]}),v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-s2",text:"s2",disabled:!t.enableFreeu}),v.jsx(Gn,{id:"freeu-s2",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.s2,allowFloat:!0,onNumberValueChange:L=>{o({freeuConfig:{...t.freeuConfig,s2:L}})}})]})]}),v.jsxs("div",{className:"flex justify-center gap-6",children:[v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-b1",text:"b1",disabled:!t.enableFreeu}),v.jsx(Gn,{id:"freeu-b1",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.b1,allowFloat:!0,onNumberValueChange:L=>{o({freeuConfig:{...t.freeuConfig,b1:L}})}})]}),v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-b2",text:"b2",disabled:!t.enableFreeu}),v.jsx(Gn,{id:"freeu-b2",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.b2,allowFloat:!0,onNumberValueChange:L=>{o({freeuConfig:{...t.freeuConfig,b2:L}})}})]})]})]}),v.jsx(Fn,{})]}):null,E=()=>t.model.need_prompt?v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsx(Pt,{text:"Negative prompt",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#negative-prompt",toolTip:"Negative prompt guides the model away from generating certain things in an image"}),v.jsx("div",{className:"pl-2 pr-4",children:v.jsx(vA,{ref:y,rows:4,onKeyUp:x,className:"max-h-[8rem] overflow-y-auto mb-2",placeholder:"",id:"negative-prompt",value:t.negativePrompt,onInput:L=>{L.preventDefault(),L.stopPropagation();const ie=L.target;o({negativePrompt:ie.value})}})})]}):null,k=()=>t.model.name!==YR?null:v.jsxs("div",{children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Example Image",toolTip:"An example image to guide image generation."}),v.jsx(c1,{tooltip:"Upload example image",onFileUpload:L=>{s({paintByExampleFile:L})},children:v.jsx(ZT,{})})]}),g?v.jsx("div",{className:"flex justify-center items-center",children:v.jsx("img",{src:m.src,alt:"example",className:"max-w-[200px] max-h-[200px] m-3"})}):v.jsx(v.Fragment,{}),v.jsx(Rn,{variant:"default",className:"w-full",disabled:r||!g,onClick:()=>{i()},children:"Paint"})]}),P=()=>t.model.name!==aF?null:v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Image guidance scale",toolTip:"Push the generated image towards the inital image. Higher image guidance scale encourages generated images that are closely linked to the source image, usually at the expense of lower image quality.",url:"https://huggingface.co/docs/diffusers/main/en/api/pipelines/pix2pix"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[150],min:100,max:1e3,step:1,value:[Math.floor(t.p2pImageGuidanceScale*100)],onValueChange:L=>o({p2pImageGuidanceScale:L[0]/100})}),v.jsx(Gn,{id:"image-guidance-scale",className:"w-[60px] rounded-full",numberValue:t.p2pImageGuidanceScale,allowFloat:!0,onNumberValueChange:L=>{o({p2pImageGuidanceScale:L})}})]})]}),M=()=>t.model.support_strength?v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Strength",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#strength",toolTip:"Strength is a measure of how much noise is added to the base image, which influences how similar the output is to the base image. Higher value means more noise and more different from the base image"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[100],min:10,max:100,step:1,value:[Math.floor(t.sdStrength*100)],onValueChange:L=>o({sdStrength:L[0]/100})}),v.jsx(Gn,{id:"strength",className:"w-[60px] rounded-full",numberValue:t.sdStrength,allowFloat:!0,onNumberValueChange:L=>{o({sdStrength:L})}})]})]}):null,A=()=>t.model.support_outpainting?v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Extender",toolTip:"Perform outpainting on images to expand it's content."}),v.jsx(co,{id:"extender",checked:t.showExtender,onCheckedChange:L=>{o({showExtender:L}),L&&o({showCropper:!1})}})]}),v.jsxs(Ut,{children:[v.jsxs(aa,{defaultValue:t.extenderDirection,value:t.extenderDirection,onValueChange:L=>{u(L)},children:[v.jsx(ls,{className:"w-[65px] h-7",disabled:!t.showExtender,children:v.jsx(la,{placeholder:"Select axis"})}),v.jsx(cs,{align:"end",children:v.jsx(wl,{children:Object.values(In).map(L=>v.jsx(us,{value:L,children:L},L))})})]}),v.jsxs("div",{className:"flex gap-1 justify-center mt-0",children:[v.jsx(vp,{text:"1.25x",onClick:()=>l(t.extenderDirection,1.25)}),v.jsx(vp,{text:"1.5x",onClick:()=>l(t.extenderDirection,1.5)}),v.jsx(vp,{text:"1.75x",onClick:()=>l(t.extenderDirection,1.75)}),v.jsx(vp,{text:"2.0x",onClick:()=>l(t.extenderDirection,2)})]})]})]}),v.jsx(Fn,{})]}):null,O=()=>t.model.name!==lF?null:v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Task",toolTip:"PowerPaint task. When using extender, image-outpainting task will be auto used. For object-removal and image-outpainting, it is recommended to set the guidance_scale at 10 or above."}),v.jsxs(aa,{defaultValue:t.powerpaintTask,value:t.powerpaintTask,onValueChange:L=>{o({powerpaintTask:L})},disabled:t.showExtender,children:[v.jsx(ls,{className:"w-[140px]",children:v.jsx(la,{placeholder:"Select task"})}),v.jsx(cs,{align:"end",children:v.jsx(wl,{children:[kl.text_guided,kl.object_remove,kl.shape_guided].map(L=>v.jsx(us,{value:L,children:L},L))})})]})]}),F=()=>v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{htmlFor:"steps",text:"Steps",toolTip:"The number of denoising steps. More denoising steps usually lead to a higher quality image at the expense of slower inference."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[30],min:1,max:100,step:1,value:[Math.floor(t.sdSteps)],onValueChange:L=>o({sdSteps:L[0]})}),v.jsx(Gn,{id:"steps",className:"w-[60px] rounded-full",numberValue:t.sdSteps,allowFloat:!1,onNumberValueChange:L=>{o({sdSteps:L})}})]})]}),V=()=>v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Guidance scale",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#guidance-scale",toolTip:"Guidance scale affects how aligned the text prompt and generated image are. Higher value means the prompt and generated image are closely aligned, so the output is a stricter interpretation of the prompt"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[750],min:0,max:1500,step:1,value:[Math.floor(t.sdGuidanceScale*100)],onValueChange:L=>o({sdGuidanceScale:L[0]/100})}),v.jsx(Gn,{id:"guidance-scale",className:"w-[60px] rounded-full",numberValue:t.sdGuidanceScale,allowFloat:!0,onNumberValueChange:L=>{o({sdGuidanceScale:L})}})]})]}),J=()=>t.model.name===cF?null:v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Sampler"}),v.jsxs(aa,{defaultValue:t.sdSampler,value:t.sdSampler,onValueChange:L=>{o({sdSampler:L})},children:[v.jsx(ls,{className:"w-[175px] text-xs",children:v.jsx(la,{placeholder:"Select sampler"})}),v.jsx(cs,{align:"end",children:v.jsx(wl,{children:e.map(L=>v.jsx(us,{value:L,className:"text-xs",children:L},L))})})]})]}),G=()=>v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Seed",toolTip:"Using same parameters and a fixed seed can generate same result image."}),v.jsxs("div",{className:"flex gap-2 justify-center items-center",children:[v.jsx(co,{id:"seed",checked:t.seedFixed,onCheckedChange:L=>{o({seedFixed:L})}}),v.jsx(Gn,{id:"seed",className:"w-[100px]",disabled:!t.seedFixed,numberValue:t.seed,allowFloat:!1,onNumberValueChange:L=>{o({seed:L})}})]})]}),ae=()=>v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Mask blur",toolTip:"How much to blur the mask before processing, in pixels."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[t.sdMaskBlur],min:0,max:96,step:1,value:[Math.floor(t.sdMaskBlur)],onValueChange:L=>o({sdMaskBlur:L[0]})}),v.jsx(Gn,{id:"mask-blur",className:"w-[60px] rounded-full",numberValue:t.sdMaskBlur,allowFloat:!1,onNumberValueChange:L=>{o({sdMaskBlur:L})}})]})]}),U=()=>v.jsxs(v.Fragment,{children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Match histograms",toolTip:"Match the inpainting result histogram to the source image histogram",url:"https://github.com/Sanster/lama-cleaner/pull/143#issuecomment-1325859307"}),v.jsx(co,{id:"match-histograms",checked:t.sdMatchHistograms,onCheckedChange:L=>{o({sdMatchHistograms:L})}})]}),v.jsx(Fn,{})]}),te=()=>v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{htmlFor:"adjustMaskKernelSize",text:"Adjust Mask",toolTip:"Expand or shrink mask. Using the slider to adjust the kernel size for dilation or erosion."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[12],min:1,max:100,step:1,value:[Math.floor(t.adjustMaskKernelSize)],onValueChange:L=>o({adjustMaskKernelSize:L[0]})}),v.jsx(Gn,{id:"adjustMaskKernelSize",className:"w-[60px] rounded-full",numberValue:t.adjustMaskKernelSize,allowFloat:!1,onNumberValueChange:L=>{o({adjustMaskKernelSize:L})}})]}),v.jsxs(Ut,{children:[v.jsxs("div",{className:"flex gap-1 justify-start",children:[v.jsx(Rn,{variant:"outline",className:"p-1 h-8",onClick:()=>d("expand"),disabled:r,children:v.jsxs("div",{className:"flex items-center gap-1 select-none",children:[v.jsx(oV,{size:16}),"expand"]})}),v.jsx(Rn,{variant:"outline",className:"p-1 h-8",onClick:()=>d("shrink"),disabled:r,children:v.jsxs("div",{className:"flex items-center gap-1 select-none",children:[v.jsx(nV,{size:16}),"Shrink"]})})]}),v.jsx(Rn,{variant:"outline",className:"p-1 h-8 justify-self-end",onClick:h,disabled:r,children:v.jsx("div",{className:"flex items-center gap-1 select-none",children:"Clear"})})]})]}),v.jsx(Fn,{})]});return v.jsxs("div",{className:"flex flex-col gap-4 mt-4",children:[_(),A(),te(),O(),F(),V(),P(),M(),J(),G(),E(),v.jsx(Fn,{}),C(),S(),ae(),U(),b(),k()]})},kJ=()=>{const[e,t]=bt(n=>[n.settings,n.updateSettings]);return v.jsxs("div",{className:"flex flex-col gap-4 mt-4",children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"CV2 Flag",url:"https://docs.opencv.org/4.8.0/d7/d8b/group__photo__inpaint.html#gga8002a65f5a3328fbf15df81b842d3c3ca892824c38e258feb5e72f308a358d52e"}),v.jsxs(aa,{value:e.cv2Flag,onValueChange:n=>{t({cv2Flag:n})},children:[v.jsx(ls,{className:"w-[160px]",children:v.jsx(la,{placeholder:"Select flag"})}),v.jsx(cs,{align:"end",children:v.jsx(wl,{children:Object.values(qw).map(n=>v.jsx(us,{value:n,children:n},n))})})]})]}),v.jsx(Pt,{text:"CV2 Radius",url:"https://docs.opencv.org/4.8.0/d7/d8b/group__photo__inpaint.html#gga8002a65f5a3328fbf15df81b842d3c3ca892824c38e258feb5e72f308a358d52e"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[5],min:1,max:100,step:1,value:[Math.floor(e.cv2Radius)],onValueChange:n=>t({cv2Radius:n[0]})}),v.jsx(Gn,{id:"cv2-radius",className:"w-[60px] rounded-full",numberValue:e.cv2Radius,allowFloat:!1,onNumberValueChange:n=>{t({cv2Radius:n})}})]})]})},RJ=()=>{const[e,t]=bt(i=>[i.settings,i.windowSize]),[n,r]=AP(!0);if(Zn("c",()=>{r()}),e.model.name!==oC&&e.model.name!==iC&&e.model.model_type===is)return null;const o=()=>e.model.name===oC?v.jsx(CJ,{}):e.model.name===iC?v.jsx(kJ,{}):v.jsx($J,{});return v.jsxs(wJ,{open:n,modal:!1,children:[v.jsx(xJ,{tabIndex:-1,className:"z-10 outline-none absolute top-[68px] right-6 rounded-lg border bg-background",children:v.jsx(Rn,{variant:"ghost",size:"icon",asChild:!0,className:"p-1.5",onClick:r,children:v.jsx(KU,{strokeWidth:1})})}),v.jsxs(mA,{side:"right",className:"w-[300px] mt-[60px] outline-none pl-4 pr-1",onOpenAutoFocus:i=>i.preventDefault(),onPointerDownOutside:i=>i.preventDefault(),children:[v.jsxs(gA,{children:[v.jsxs(Ut,{children:[v.jsx("div",{className:"overflow-hidden mr-8",children:e.model.name.split("/")[e.model.name.split("/").length-1]}),v.jsx(Rn,{variant:"ghost",size:"icon",className:"border h-6 w-6",onClick:r,children:v.jsx(YU,{strokeWidth:1})})]}),v.jsx(Fn,{})]}),v.jsx(og,{style:{height:t.height-160},className:"pr-3",children:o()})]})]})},Yo=Object.create(null);Yo.open="0";Yo.close="1";Yo.ping="2";Yo.pong="3";Yo.message="4";Yo.upgrade="5";Yo.noop="6";const th=Object.create(null);Object.keys(Yo).forEach(e=>{th[Yo[e]]=e});const H1={type:"error",data:"parser error"},yA=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",wA=typeof ArrayBuffer=="function",xA=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,rb=({type:e,data:t},n,r)=>yA&&t instanceof Blob?n?r(t):G2(t,r):wA&&(t instanceof ArrayBuffer||xA(t))?n?r(t):G2(new Blob([t]),r):r(Yo[e]+(t||"")),G2=(e,t)=>{const n=new FileReader;return n.onload=function(){const r=n.result.split(",")[1];t("b"+(r||""))},n.readAsDataURL(e)};function X2(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let L0;function TJ(e,t){if(yA&&e.data instanceof Blob)return e.data.arrayBuffer().then(X2).then(t);if(wA&&(e.data instanceof ArrayBuffer||xA(e.data)))return t(X2(e.data));rb(e,!1,n=>{L0||(L0=new TextEncoder),t(L0.encode(n))})}const Z2="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",gu=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let e=0;e{let t=e.length*.75,n=e.length,r,o=0,i,s,l,u;e[e.length-1]==="="&&(t--,e[e.length-2]==="="&&t--);const d=new ArrayBuffer(t),h=new Uint8Array(d);for(r=0;r>4,h[o++]=(s&15)<<4|l>>2,h[o++]=(l&3)<<6|u&63;return d},AJ=typeof ArrayBuffer=="function",ob=(e,t)=>{if(typeof e!="string")return{type:"message",data:bA(e,t)};const n=e.charAt(0);return n==="b"?{type:"message",data:OJ(e.substring(1),t)}:th[n]?e.length>1?{type:th[n],data:e.substring(1)}:{type:th[n]}:H1},OJ=(e,t)=>{if(AJ){const n=PJ(e);return bA(n,t)}else return{base64:!0,data:e}},bA=(e,t)=>{switch(t){case"blob":return e instanceof Blob?e:new Blob([e]);case"arraybuffer":default:return e instanceof ArrayBuffer?e:e.buffer}},_A="",MJ=(e,t)=>{const n=e.length,r=new Array(n);let o=0;e.forEach((i,s)=>{rb(i,!1,l=>{r[s]=l,++o===n&&t(r.join(_A))})})},NJ=(e,t)=>{const n=e.split(_A),r=[];for(let o=0;o{const r=n.length;let o;if(r<126)o=new Uint8Array(1),new DataView(o.buffer).setUint8(0,r);else if(r<65536){o=new Uint8Array(3);const i=new DataView(o.buffer);i.setUint8(0,126),i.setUint16(1,r)}else{o=new Uint8Array(9);const i=new DataView(o.buffer);i.setUint8(0,127),i.setBigUint64(1,BigInt(r))}e.data&&typeof e.data!="string"&&(o[0]|=128),t.enqueue(o),t.enqueue(n)})}})}let F0;function yp(e){return e.reduce((t,n)=>t+n.length,0)}function wp(e,t){if(e[0].length===t)return e.shift();const n=new Uint8Array(t);let r=0;for(let o=0;oMath.pow(2,21)-1){l.enqueue(H1);break}o=h*Math.pow(2,32)+d.getUint32(4),r=3}else{if(yp(n)e){l.enqueue(H1);break}}}})}const SA=4;function Qt(e){if(e)return LJ(e)}function LJ(e){for(var t in Qt.prototype)e[t]=Qt.prototype[t];return e}Qt.prototype.on=Qt.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this};Qt.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this};Qt.prototype.off=Qt.prototype.removeListener=Qt.prototype.removeAllListeners=Qt.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,o=0;o(e.hasOwnProperty(r)&&(n[r]=e[r]),n),{})}const FJ=Br.setTimeout,jJ=Br.clearTimeout;function hg(e,t){t.useNativeTimers?(e.setTimeoutFn=FJ.bind(Br),e.clearTimeoutFn=jJ.bind(Br)):(e.setTimeoutFn=Br.setTimeout.bind(Br),e.clearTimeoutFn=Br.clearTimeout.bind(Br))}const zJ=1.33;function BJ(e){return typeof e=="string"?UJ(e):Math.ceil((e.byteLength||e.size)*zJ)}function UJ(e){let t=0,n=0;for(let r=0,o=e.length;r=57344?n+=3:(r++,n+=4);return n}function VJ(e){let t="";for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+="&"),t+=encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t}function WJ(e){let t={},n=e.split("&");for(let r=0,o=n.length;r0);return t}function $A(){const e=J2(+new Date);return e!==Q2?(q2=0,Q2=e):e+"."+J2(q2++)}for(;xp{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)};NJ(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,MJ(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]=$A()),!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 Vo(this.uri(),t)}doWrite(t,n){const r=this.request({method:"POST",data:t});r.on("success",n),r.on("error",(o,i)=>{this.onError("xhr post error",o,i)})}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}}class Vo extends Qt{constructor(t,n){super(),hg(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=EA(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");n.xdomain=!!this.opts.xd;const r=this.xhr=new RA(n);try{r.open(this.method,this.uri,!0);try{if(this.opts.extraHeaders){r.setDisableHeaderCheck&&r.setDisableHeaderCheck(!0);for(let o in this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(o)&&r.setRequestHeader(o,this.opts.extraHeaders[o])}}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 o;r.readyState===3&&((o=this.opts.cookieJar)===null||o===void 0||o.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(o){this.setTimeoutFn(()=>{this.onError(o)},0);return}typeof document<"u"&&(this.index=Vo.requestsCount++,Vo.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=GJ,t)try{this.xhr.abort()}catch{}typeof document<"u"&&delete Vo.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()}}Vo.requestsCount=0;Vo.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",e$);else if(typeof addEventListener=="function"){const e="onpagehide"in Br?"pagehide":"unload";addEventListener(e,e$,!1)}}function e$(){for(let e in Vo.requests)Vo.requests.hasOwnProperty(e)&&Vo.requests[e].abort()}const sb=typeof Promise=="function"&&typeof Promise.resolve=="function"?t=>Promise.resolve().then(t):(t,n)=>n(t,0),bp=Br.WebSocket||Br.MozWebSocket,t$=!0,qJ="arraybuffer",n$=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class QJ extends ib{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=n$?{}:EA(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=t$&&!n$?n?new bp(t,n):new bp(t):new bp(t,n,r)}catch(o){return this.emitReserved("error",o)}this.ws.binaryType=this.socket.binaryType,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{t$&&this.ws.send(i)}catch{}o&&sb(()=>{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]=$A()),this.supportsBinary||(n.b64=1),this.createUri(t,n)}check(){return!!bp}}class JJ extends ib{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=IJ(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=t.readable.pipeThrough(n).getReader(),o=DJ();o.readable.pipeTo(t.writable),this.writer=o.writable.getWriter();const i=()=>{r.read().then(({done:l,value:u})=>{l||(this.onPacket(u),i())}).catch(l=>{})};i();const s={type:"open"};this.query.sid&&(s.data=`{"sid":"${this.query.sid}"}`),this.writer.write(s).then(()=>this.onOpen())})}))}write(t){this.writable=!1;for(let n=0;n{o&&sb(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;(t=this.transport)===null||t===void 0||t.close()}}const eee={websocket:QJ,webtransport:JJ,polling:ZJ},tee=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,nee=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Y1(e){if(e.length>2e3)throw"URI too long";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 o=tee.exec(e||""),i={},s=14;for(;s--;)i[nee[s]]=o[s]||"";return n!=-1&&r!=-1&&(i.source=t,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=ree(i,i.path),i.queryKey=oee(i,i.query),i}function ree(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 oee(e,t){const n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(r,o,i){o&&(n[o]=i)}),n}let TA=class sl extends Qt{constructor(t,n={}){super(),this.binaryType=qJ,this.writeBuffer=[],t&&typeof t=="object"&&(n=t,t=null),t?(t=Y1(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=Y1(n.host).host),hg(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=WJ(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=SA,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 eee[t](r)}open(){let t;if(this.opts.rememberUpgrade&&sl.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;sl.priorWebsocketSuccess=!1;const o=()=>{r||(n.send([{type:"ping",data:"probe"}]),n.once("packet",m=>{if(!r)if(m.type==="pong"&&m.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",n),!n)return;sl.priorWebsocketSuccess=n.name==="websocket",this.transport.pause(()=>{r||this.readyState!=="closed"&&(h(),this.setTransport(n),n.send([{type:"upgrade"}]),this.emitReserved("upgrade",n),n=null,this.upgrading=!1,this.flush())})}else{const g=new Error("probe error");g.transport=n.name,this.emitReserved("upgradeError",g)}}))};function i(){r||(r=!0,h(),n.close(),n=null)}const s=m=>{const g=new Error("probe error: "+m);g.transport=n.name,i(),this.emitReserved("upgradeError",g)};function l(){s("transport closed")}function u(){s("socket closed")}function d(m){n&&m.name!==n.name&&i()}const h=()=>{n.removeListener("open",o),n.removeListener("error",s),n.removeListener("close",l),this.off("close",u),this.off("upgrading",d)};n.once("open",o),n.once("error",s),n.once("close",l),this.once("close",u),this.once("upgrading",d),this.upgrades.indexOf("webtransport")!==-1&&t!=="webtransport"?this.setTimeoutFn(()=>{r||n.open()},200):n.open()}onOpen(){if(this.readyState="open",sl.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,o){if(typeof n=="function"&&(o=n,n=void 0),typeof r=="function"&&(o=r,r=null),this.readyState==="closing"||this.readyState==="closed")return;r=r||{},r.compress=r.compress!==!1;const i={type:t,data:n,options:r};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),o&&this.once("flush",o),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){sl.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 o=t.length;for(;rtypeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,PA=Object.prototype.toString,lee=typeof Blob=="function"||typeof Blob<"u"&&PA.call(Blob)==="[object BlobConstructor]",cee=typeof File=="function"||typeof File<"u"&&PA.call(File)==="[object FileConstructor]";function ab(e){return see&&(e instanceof ArrayBuffer||aee(e))||lee&&e instanceof Blob||cee&&e instanceof File}function nh(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(i),n.apply(this,[null,...s])}}emitWithAck(t,...n){const r=this.flags.timeout!==void 0||this._opts.ackTimeout!==void 0;return new Promise((o,i)=>{n.push((s,l)=>r?s?i(s):o(l):o(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((o,...i)=>r!==this._queue[0]?void 0:(o!==null?r.tryCount>this._opts.retries&&(this._queue.shift(),n&&n(o)):(this._queue.shift(),n&&n(null,...i)),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:lt.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 lt.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 lt.EVENT:case lt.BINARY_EVENT:this.onevent(t);break;case lt.ACK:case lt.BINARY_ACK:this.onack(t);break;case lt.DISCONNECT:this.ondisconnect();break;case lt.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(...o){r||(r=!0,n.packet({type:lt.ACK,id:t,data:o}))}}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:lt.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}Cc.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};Cc.prototype.reset=function(){this.attempts=0};Cc.prototype.setMin=function(e){this.ms=e};Cc.prototype.setMax=function(e){this.max=e};Cc.prototype.setJitter=function(e){this.jitter=e};class Z1 extends Qt{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,hg(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 Cc({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(n.timeout==null?2e4:n.timeout),this._readyState="closed",this.uri=t;const o=n.parser||gee;this.encoder=new o.Encoder,this.decoder=new o.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 TA(this.uri,this.opts);const n=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;const o=fo(n,"open",function(){r.onopen(),t&&t()}),i=l=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",l),t?t(l):this.maybeReconnectOnOpen()},s=fo(n,"error",i);if(this._timeout!==!1){const l=this._timeout,u=this.setTimeoutFn(()=>{o(),i(new Error("timeout")),n.close()},l);this.opts.autoUnref&&u.unref(),this.subs.push(()=>{this.clearTimeoutFn(u)})}return this.subs.push(o),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(fo(t,"ping",this.onping.bind(this)),fo(t,"data",this.ondata.bind(this)),fo(t,"error",this.onerror.bind(this)),fo(t,"close",this.onclose.bind(this)),fo(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){sb(()=>{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 AA(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(o=>{o?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",o)):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 cu={};function rh(e,t){typeof e=="object"&&(t=e,e=void 0),t=t||{};const n=iee(e,t.path||"/socket.io"),r=n.source,o=n.id,i=n.path,s=cu[o]&&i in cu[o].nsps,l=t.forceNew||t["force new connection"]||t.multiplex===!1||s;let u;return l?u=new Z1(r,t):(cu[o]||(cu[o]=new Z1(r,t)),u=cu[o]),n.query&&!t.query&&(t.query=n.queryKey),u.socket(n.path,t)}Object.assign(rh,{Manager:Z1,Socket:AA,io:rh,connect:rh});const OA="Progress",mg=100,[yee,Tte]=An(OA),[wee,xee]=yee(OA),MA=f.forwardRef((e,t)=>{const{__scopeProgress:n,value:r,max:o,getValueLabel:i=See,...s}=e,l=q1(o)?o:mg,u=DA(r,l)?r:null,d=im(u)?i(u,l):void 0;return f.createElement(wee,{scope:n,value:u,max:l},f.createElement(Pe.div,Y({"aria-valuemax":l,"aria-valuemin":0,"aria-valuenow":im(u)?u:void 0,"aria-valuetext":d,role:"progressbar","data-state":NA(u,l),"data-value":u??void 0,"data-max":l},s,{ref:t})))});MA.propTypes={max(e,t,n){const r=e[t],o=String(r);return r&&!q1(r)?new Error(Eee(o,n)):null},value(e,t,n){const r=e[t],o=String(r),i=q1(e.max)?e.max:mg;return r!=null&&!DA(r,i)?new Error(Cee(o,n)):null}};const bee="ProgressIndicator",_ee=f.forwardRef((e,t)=>{var n;const{__scopeProgress:r,...o}=e,i=xee(bee,r);return f.createElement(Pe.div,Y({"data-state":NA(i.value,i.max),"data-value":(n=i.value)!==null&&n!==void 0?n:void 0,"data-max":i.max},o,{ref:t}))});function See(e,t){return`${Math.round(e/t*100)}%`}function NA(e,t){return e==null?"indeterminate":e===t?"complete":"loading"}function im(e){return typeof e=="number"}function q1(e){return im(e)&&!isNaN(e)&&e>0}function DA(e,t){return im(e)&&!isNaN(e)&&e<=t&&e>=0}function Eee(e,t){return`Invalid prop \`max\` of value \`${e}\` supplied to \`${t}\`. Only numbers greater than 0 are valid max values. Defaulting to \`${mg}\`.`}function Cee(e,t){return`Invalid prop \`value\` of value \`${e}\` supplied to \`${t}\`. The \`value\` prop must be: + - a positive number + - less than the value passed to \`max\` (or ${mg} if no \`max\` prop is set) + - \`null\` if the progress is indeterminate. + +Defaulting to \`null\`.`}const IA=MA,$ee=_ee,LA=f.forwardRef(({className:e,value:t,...n},r)=>v.jsx(IA,{ref:r,className:Ce("relative h-2 w-full overflow-hidden rounded-full bg-primary/20",e),...n,children:v.jsx($ee,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(t||0)}%)`}})}));LA.displayName=IA.displayName;const kee="",Vi=rh(kee),Ree=()=>{const[e,t,n]=bt(u=>[u.settings,u.isInpainting,u.isSD()]),[r,o]=f.useState(!1),[i,s]=f.useState(0),l=Math.min(Math.round(i/e.sdSteps*100),100);return f.useEffect(()=>(Vi.on("connect",()=>{o(!0)}),Vi.on("disconnect",()=>{o(!1)}),Vi.on("diffusion_progress",u=>{u&&s(u.step+1)}),Vi.on("diffusion_finish",()=>{s(0)}),()=>{Vi.off("connect"),Vi.off("disconnect"),Vi.off("diffusion_progress"),Vi.off("diffusion_finish")}),[]),v.jsxs("div",{className:"z-10 fixed bg-background w-[220px] left-1/2 -translate-x-1/2 top-[68px] h-[32px] flex justify-center items-center gap-[18px] border-[1px] border-[solid] rounded-[14px] pl-[8px] pr-[8px]",style:{visibility:r&&t&&n?"visible":"hidden"},children:[v.jsx(LA,{value:l}),v.jsxs("div",{className:"w-[45px] flex justify-center font-nums",children:[l,"%"]})]})},Tee=()=>{const[e,t]=bt(n=>[n.file,n.updateSettings]);return f.useEffect(()=>{(async()=>{const r=await zj();t({model:r})})()},[]),v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"flex gap-3 absolute top-[68px] left-[24px] items-center",children:[v.jsx(yJ,{}),v.jsx(Qq,{})]}),v.jsx(Hq,{}),v.jsx(Ree,{}),v.jsx(RJ,{}),e?v.jsx(qq,{file:e}):v.jsx(v.Fragment,{})]})},Pee=()=>{const[e,t]=f.useState(window.innerWidth),n=f.useCallback(()=>{t(window.innerWidth)},[]);if(f.useEffect(()=>(window.addEventListener("resize",n),()=>{window.removeEventListener("resize",n)})),e<768)return"mobile";if(e>=768&&e<1224)return"tablet";if(e>=1224)return"desktop"};function Aee(e){const{onSelection:t}=e,[n]=f.useState(`file-upload-${Math.random().toString()}`),r=Pee();function o(i){if(!(!i||!i.type.match("image.*")))try{if(i.size>20*1024*1024)throw new Error("file too large");t(i)}catch(l){alert(`error: ${l.message}`)}}return v.jsx("div",{className:"absolute flex w-screen h-screen justify-center items-center pointer-events-none",children:v.jsx("label",{htmlFor:n,className:"grid bg-background border-[2px] border-[dashed] rounded-lg min-w-[600px] hover:bg-primary hover:text-primary-foreground pointer-events-auto",children:v.jsxs("div",{className:"grid p-16 w-full h-full",onDragOver:i=>{i.stopPropagation(),i.preventDefault()},children:[v.jsx("input",{className:"hidden",id:n,name:n,type:"file",onChange:i=>{var l;const s=(l=i.currentTarget.files)==null?void 0:l[0];s&&o(s)},accept:"image/png, image/jpeg"}),v.jsx("p",{className:"text-center",children:r==="desktop"?"Click here or drag an image file":"Tap here to load your picture"})]})})})}const FA="ToastProvider",[cb,Oee,Mee]=zd("Toast"),[jA,Pte]=An("Toast",[Mee]),[Nee,gg]=jA(FA),zA=e=>{const{__scopeToast:t,label:n="Notification",duration:r=5e3,swipeDirection:o="right",swipeThreshold:i=50,children:s}=e,[l,u]=f.useState(null),[d,h]=f.useState(0),m=f.useRef(!1),g=f.useRef(!1);return f.createElement(cb.Provider,{scope:t},f.createElement(Nee,{scope:t,label:n,duration:r,swipeDirection:o,swipeThreshold:i,toastCount:d,viewport:l,onViewportChange:u,onToastAdd:f.useCallback(()=>h(y=>y+1),[]),onToastRemove:f.useCallback(()=>h(y=>y-1),[]),isFocusedToastEscapeKeyDownRef:m,isClosePausedRef:g},s))};zA.propTypes={label(e){if(e.label&&typeof e.label=="string"&&!e.label.trim()){const t=`Invalid prop \`label\` supplied to \`${FA}\`. Expected non-empty \`string\`.`;return new Error(t)}return null}};const Dee="ToastViewport",Iee=["F8"],Q1="toast.viewportPause",J1="toast.viewportResume",Lee=f.forwardRef((e,t)=>{const{__scopeToast:n,hotkey:r=Iee,label:o="Notifications ({hotkey})",...i}=e,s=gg(Dee,n),l=Oee(n),u=f.useRef(null),d=f.useRef(null),h=f.useRef(null),m=f.useRef(null),g=Be(t,m,s.onViewportChange),y=r.join("+").replace(/Key/g,"").replace(/Digit/g,""),x=s.toastCount>0;f.useEffect(()=>{const C=S=>{var b;r.every(k=>S[k]||S.code===k)&&((b=m.current)===null||b===void 0||b.focus())};return document.addEventListener("keydown",C),()=>document.removeEventListener("keydown",C)},[r]),f.useEffect(()=>{const C=u.current,S=m.current;if(x&&C&&S){const b=()=>{if(!s.isClosePausedRef.current){const M=new CustomEvent(Q1);S.dispatchEvent(M),s.isClosePausedRef.current=!0}},E=()=>{if(s.isClosePausedRef.current){const M=new CustomEvent(J1);S.dispatchEvent(M),s.isClosePausedRef.current=!1}},k=M=>{!C.contains(M.relatedTarget)&&E()},P=()=>{C.contains(document.activeElement)||E()};return C.addEventListener("focusin",b),C.addEventListener("focusout",k),C.addEventListener("pointermove",b),C.addEventListener("pointerleave",P),window.addEventListener("blur",b),window.addEventListener("focus",E),()=>{C.removeEventListener("focusin",b),C.removeEventListener("focusout",k),C.removeEventListener("pointermove",b),C.removeEventListener("pointerleave",P),window.removeEventListener("blur",b),window.removeEventListener("focus",E)}}},[x,s.isClosePausedRef]);const _=f.useCallback(({tabbingDirection:C})=>{const b=l().map(E=>{const k=E.ref.current,P=[k,...Jee(k)];return C==="forwards"?P:P.reverse()});return(C==="forwards"?b.reverse():b).flat()},[l]);return f.useEffect(()=>{const C=m.current;if(C){const S=b=>{const E=b.altKey||b.ctrlKey||b.metaKey;if(b.key==="Tab"&&!E){const O=document.activeElement,F=b.shiftKey;if(b.target===C&&F){var P;(P=d.current)===null||P===void 0||P.focus();return}const G=_({tabbingDirection:F?"backwards":"forwards"}),ae=G.findIndex(U=>U===O);if(j0(G.slice(ae+1)))b.preventDefault();else{var M,A;F?(M=d.current)===null||M===void 0||M.focus():(A=h.current)===null||A===void 0||A.focus()}}};return C.addEventListener("keydown",S),()=>C.removeEventListener("keydown",S)}},[l,_]),f.createElement(SB,{ref:u,role:"region","aria-label":o.replace("{hotkey}",y),tabIndex:-1,style:{pointerEvents:x?void 0:"none"}},x&&f.createElement(o$,{ref:d,onFocusFromOutsideViewport:()=>{const C=_({tabbingDirection:"forwards"});j0(C)}}),f.createElement(cb.Slot,{scope:n},f.createElement(Pe.ol,Y({tabIndex:-1},i,{ref:g}))),x&&f.createElement(o$,{ref:h,onFocusFromOutsideViewport:()=>{const C=_({tabbingDirection:"backwards"});j0(C)}}))}),Fee="ToastFocusProxy",o$=f.forwardRef((e,t)=>{const{__scopeToast:n,onFocusFromOutsideViewport:r,...o}=e,i=gg(Fee,n);return f.createElement(Um,Y({"aria-hidden":!0,tabIndex:0},o,{ref:t,style:{position:"fixed"},onFocus:s=>{var l;const u=s.relatedTarget;!((l=i.viewport)!==null&&l!==void 0&&l.contains(u))&&r()}}))}),vg="Toast",jee="toast.swipeStart",zee="toast.swipeMove",Bee="toast.swipeCancel",Uee="toast.swipeEnd",Vee=f.forwardRef((e,t)=>{const{forceMount:n,open:r,defaultOpen:o,onOpenChange:i,...s}=e,[l=!0,u]=Zr({prop:r,defaultProp:o,onChange:i});return f.createElement(xn,{present:n||l},f.createElement(BA,Y({open:l},s,{ref:t,onClose:()=>u(!1),onPause:Ft(e.onPause),onResume:Ft(e.onResume),onSwipeStart:ue(e.onSwipeStart,d=>{d.currentTarget.setAttribute("data-swipe","start")}),onSwipeMove:ue(e.onSwipeMove,d=>{const{x:h,y:m}=d.detail.delta;d.currentTarget.setAttribute("data-swipe","move"),d.currentTarget.style.setProperty("--radix-toast-swipe-move-x",`${h}px`),d.currentTarget.style.setProperty("--radix-toast-swipe-move-y",`${m}px`)}),onSwipeCancel:ue(e.onSwipeCancel,d=>{d.currentTarget.setAttribute("data-swipe","cancel"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),d.currentTarget.style.removeProperty("--radix-toast-swipe-end-x"),d.currentTarget.style.removeProperty("--radix-toast-swipe-end-y")}),onSwipeEnd:ue(e.onSwipeEnd,d=>{const{x:h,y:m}=d.detail.delta;d.currentTarget.setAttribute("data-swipe","end"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),d.currentTarget.style.setProperty("--radix-toast-swipe-end-x",`${h}px`),d.currentTarget.style.setProperty("--radix-toast-swipe-end-y",`${m}px`),u(!1)})})))}),[Wee,Hee]=jA(vg,{onClose(){}}),BA=f.forwardRef((e,t)=>{const{__scopeToast:n,type:r="foreground",duration:o,open:i,onClose:s,onEscapeKeyDown:l,onPause:u,onResume:d,onSwipeStart:h,onSwipeMove:m,onSwipeCancel:g,onSwipeEnd:y,...x}=e,_=gg(vg,n),[C,S]=f.useState(null),b=Be(t,U=>S(U)),E=f.useRef(null),k=f.useRef(null),P=o||_.duration,M=f.useRef(0),A=f.useRef(P),O=f.useRef(0),{onToastAdd:F,onToastRemove:V}=_,J=Ft(()=>{var U;(C==null?void 0:C.contains(document.activeElement))&&((U=_.viewport)===null||U===void 0||U.focus()),s()}),G=f.useCallback(U=>{!U||U===1/0||(window.clearTimeout(O.current),M.current=new Date().getTime(),O.current=window.setTimeout(J,U))},[J]);f.useEffect(()=>{const U=_.viewport;if(U){const te=()=>{G(A.current),d==null||d()},L=()=>{const ie=new Date().getTime()-M.current;A.current=A.current-ie,window.clearTimeout(O.current),u==null||u()};return U.addEventListener(Q1,L),U.addEventListener(J1,te),()=>{U.removeEventListener(Q1,L),U.removeEventListener(J1,te)}}},[_.viewport,P,u,d,G]),f.useEffect(()=>{i&&!_.isClosePausedRef.current&&G(P)},[i,P,_.isClosePausedRef,G]),f.useEffect(()=>(F(),()=>V()),[F,V]);const ae=f.useMemo(()=>C?HA(C):null,[C]);return _.viewport?f.createElement(f.Fragment,null,ae&&f.createElement(Kee,{__scopeToast:n,role:"status","aria-live":r==="foreground"?"assertive":"polite","aria-atomic":!0},ae),f.createElement(Wee,{scope:n,onClose:J},Os.createPortal(f.createElement(cb.ItemSlot,{scope:n},f.createElement(_B,{asChild:!0,onEscapeKeyDown:ue(l,()=>{_.isFocusedToastEscapeKeyDownRef.current||J(),_.isFocusedToastEscapeKeyDownRef.current=!1})},f.createElement(Pe.li,Y({role:"status","aria-live":"off","aria-atomic":!0,tabIndex:0,"data-state":i?"open":"closed","data-swipe-direction":_.swipeDirection},x,{ref:b,style:{userSelect:"none",touchAction:"none",...e.style},onKeyDown:ue(e.onKeyDown,U=>{U.key==="Escape"&&(l==null||l(U.nativeEvent),U.nativeEvent.defaultPrevented||(_.isFocusedToastEscapeKeyDownRef.current=!0,J()))}),onPointerDown:ue(e.onPointerDown,U=>{U.button===0&&(E.current={x:U.clientX,y:U.clientY})}),onPointerMove:ue(e.onPointerMove,U=>{if(!E.current)return;const te=U.clientX-E.current.x,L=U.clientY-E.current.y,ie=!!k.current,K=["left","right"].includes(_.swipeDirection),Q=["left","up"].includes(_.swipeDirection)?Math.min:Math.max,W=K?Q(0,te):0,le=K?0:Q(0,L),ge=U.pointerType==="touch"?10:2,Ve={x:W,y:le},Ue={originalEvent:U,delta:Ve};ie?(k.current=Ve,_p(zee,m,Ue,{discrete:!1})):i$(Ve,_.swipeDirection,ge)?(k.current=Ve,_p(jee,h,Ue,{discrete:!1}),U.target.setPointerCapture(U.pointerId)):(Math.abs(te)>ge||Math.abs(L)>ge)&&(E.current=null)}),onPointerUp:ue(e.onPointerUp,U=>{const te=k.current,L=U.target;if(L.hasPointerCapture(U.pointerId)&&L.releasePointerCapture(U.pointerId),k.current=null,E.current=null,te){const ie=U.currentTarget,K={originalEvent:U,delta:te};i$(te,_.swipeDirection,_.swipeThreshold)?_p(Uee,y,K,{discrete:!0}):_p(Bee,g,K,{discrete:!0}),ie.addEventListener("click",Q=>Q.preventDefault(),{once:!0})}})})))),_.viewport))):null});BA.propTypes={type(e){if(e.type&&!["foreground","background"].includes(e.type)){const t=`Invalid prop \`type\` supplied to \`${vg}\`. Expected \`foreground | background\`.`;return new Error(t)}return null}};const Kee=e=>{const{__scopeToast:t,children:n,...r}=e,o=gg(vg,t),[i,s]=f.useState(!1),[l,u]=f.useState(!1);return qee(()=>s(!0)),f.useEffect(()=>{const d=window.setTimeout(()=>u(!0),1e3);return()=>window.clearTimeout(d)},[]),l?null:f.createElement(Md,{asChild:!0},f.createElement(Um,r,i&&f.createElement(f.Fragment,null,o.label," ",n)))},Yee=f.forwardRef((e,t)=>{const{__scopeToast:n,...r}=e;return f.createElement(Pe.div,Y({},r,{ref:t}))}),Gee=f.forwardRef((e,t)=>{const{__scopeToast:n,...r}=e;return f.createElement(Pe.div,Y({},r,{ref:t}))}),Xee="ToastAction",UA=f.forwardRef((e,t)=>{const{altText:n,...r}=e;return n?f.createElement(WA,{altText:n,asChild:!0},f.createElement(VA,Y({},r,{ref:t}))):null});UA.propTypes={altText(e){return e.altText?null:new Error(`Missing prop \`altText\` expected on \`${Xee}\``)}};const Zee="ToastClose",VA=f.forwardRef((e,t)=>{const{__scopeToast:n,...r}=e,o=Hee(Zee,n);return f.createElement(WA,{asChild:!0},f.createElement(Pe.button,Y({type:"button"},r,{ref:t,onClick:ue(e.onClick,o.onClose)})))}),WA=f.forwardRef((e,t)=>{const{__scopeToast:n,altText:r,...o}=e;return f.createElement(Pe.div,Y({"data-radix-toast-announce-exclude":"","data-radix-toast-announce-alt":r||void 0},o,{ref:t}))});function HA(e){const t=[];return Array.from(e.childNodes).forEach(r=>{if(r.nodeType===r.TEXT_NODE&&r.textContent&&t.push(r.textContent),Qee(r)){const o=r.ariaHidden||r.hidden||r.style.display==="none",i=r.dataset.radixToastAnnounceExclude==="";if(!o)if(i){const s=r.dataset.radixToastAnnounceAlt;s&&t.push(s)}else t.push(...HA(r))}}),t}function _p(e,t,n,{discrete:r}){const o=n.originalEvent.currentTarget,i=new CustomEvent(e,{bubbles:!0,cancelable:!0,detail:n});t&&o.addEventListener(e,t,{once:!0}),r?cx(o,i):o.dispatchEvent(i)}const i$=(e,t,n=0)=>{const r=Math.abs(e.x),o=Math.abs(e.y),i=r>o;return t==="left"||t==="right"?i&&r>n:!i&&o>n};function qee(e=()=>{}){const t=Ft(e);Pn(()=>{let n=0,r=0;return n=window.requestAnimationFrame(()=>r=window.requestAnimationFrame(t)),()=>{window.cancelAnimationFrame(n),window.cancelAnimationFrame(r)}},[t])}function Qee(e){return e.nodeType===e.ELEMENT_NODE}function Jee(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const o=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||o?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function j0(e){const t=document.activeElement;return e.some(n=>n===t?!0:(n.focus(),document.activeElement!==t))}const ete=zA,KA=Lee,YA=Vee,GA=Yee,XA=Gee,ZA=UA,qA=VA,tte=ete,QA=f.forwardRef(({className:e,...t},n)=>v.jsx(KA,{ref:n,className:Ce("fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]",e),tabIndex:-1,...t}));QA.displayName=KA.displayName;const nte=Om("group pointer-events-auto relative flex w-full items-center justify-between space-x-2 overflow-hidden rounded-md border p-4 pr-6 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full",{variants:{variant:{default:"border bg-background text-foreground",destructive:"destructive group border-destructive bg-destructive text-destructive-foreground"}},defaultVariants:{variant:"default"}}),JA=f.forwardRef(({className:e,variant:t,...n},r)=>v.jsx(YA,{ref:r,className:Ce(nte({variant:t}),e),tabIndex:-1,...n}));JA.displayName=YA.displayName;const rte=f.forwardRef(({className:e,...t},n)=>v.jsx(ZA,{ref:n,className:Ce("inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium transition-colors hover:bg-secondary focus:outline-none focus:ring-1 focus:ring-ring disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive",e),tabIndex:-1,...t}));rte.displayName=ZA.displayName;const eO=f.forwardRef(({className:e,...t},n)=>v.jsx(qA,{ref:n,className:Ce("absolute right-1 top-1 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-1 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600",e),"toast-close":"",tabIndex:-1,...t,children:v.jsx(yT,{className:"h-4 w-4"})}));eO.displayName=qA.displayName;const tO=f.forwardRef(({className:e,...t},n)=>v.jsx(GA,{ref:n,className:Ce("text-sm font-semibold [&+div]:text-xs",e),tabIndex:-1,...t}));tO.displayName=GA.displayName;const nO=f.forwardRef(({className:e,...t},n)=>v.jsx(XA,{ref:n,className:Ce("text-sm opacity-90",e),...t,tabIndex:-1}));nO.displayName=XA.displayName;function ote(){const{toasts:e}=Td();return v.jsxs(tte,{children:[e.map(function({id:t,title:n,description:r,action:o,...i}){return v.jsxs(JA,{...i,children:[v.jsxs("div",{className:"grid gap-1",children:[n&&v.jsx(tO,{children:n}),r&&v.jsx(nO,{children:r})]}),o,v.jsx(eO,{})]},t)}),v.jsx(QA,{})]})}const ite=["image/jpeg","image/png","image/webp","image/bmp","image/tiff"];function ste(){const[e,t,n,r]=bt(g=>[g.file,g.updateAppState,g.setServerConfig,g.setFile]),o=Yj(),i=yH();f.useEffect(()=>{o&&r(o)},[o,r]),f.useEffect(()=>{t({windowSize:i})},[i]),f.useEffect(()=>{(async()=>{const y=await Fj();n(y),y.isDesktop&&dF()})()},[]);const s=f.useRef(0),l=f.useCallback(g=>{g.preventDefault(),g.stopPropagation()},[]),u=f.useCallback(g=>{g.preventDefault(),g.stopPropagation(),s.current+=1},[]),d=f.useCallback(g=>{g.preventDefault(),g.stopPropagation(),s.current-=1,s.current>0},[]),h=f.useCallback(g=>{if(g.preventDefault(),g.stopPropagation(),g.dataTransfer.files&&g.dataTransfer.files.length>0){if(!(g.dataTransfer.files.length>1)){const y=g.dataTransfer.files[0],x=y.type;ite.includes(x)&&r(y)}g.dataTransfer.clearData()}},[]),m=f.useCallback(g=>{if(!g.clipboardData)return;const y=g.clipboardData.items,x=[].slice.call(y).filter(S=>S.type.indexOf("image")!==-1);if(x.length===0)return;g.preventDefault(),g.stopPropagation();const C=x[0].getAsFile();C&&r(C)},[]);return f.useEffect(()=>(window.addEventListener("dragenter",u),window.addEventListener("dragleave",d),window.addEventListener("dragover",l),window.addEventListener("drop",h),window.addEventListener("paste",m),function(){window.removeEventListener("dragenter",u),window.removeEventListener("dragleave",d),window.removeEventListener("dragover",l),window.removeEventListener("drop",h),window.removeEventListener("paste",m)})),v.jsxs("main",{className:"flex min-h-screen flex-col items-center justify-between w-full bg-[radial-gradient(circle_at_1px_1px,_#8e8e8e8e_1px,_transparent_0)] [background-size:20px_20px] bg-repeat",children:[v.jsx(ote,{}),v.jsx(rZ,{}),v.jsx(Tee,{}),e?v.jsx(v.Fragment,{}):v.jsx(Aee,{onSelection:async g=>{r(g)}})]})}const sm=["light","dark"],ub="(prefers-color-scheme: dark)",ate=typeof window>"u",rO=f.createContext(void 0),lte=e=>f.useContext(rO)?Fe.createElement(f.Fragment,null,e.children):Fe.createElement(ute,e),cte=["light","dark"],ute=({forcedTheme:e,disableTransitionOnChange:t=!1,enableSystem:n=!0,enableColorScheme:r=!0,storageKey:o="theme",themes:i=cte,defaultTheme:s=n?"system":"light",attribute:l="data-theme",value:u,children:d,nonce:h})=>{const[m,g]=f.useState(()=>s$(o,s)),[y,x]=f.useState(()=>s$(o)),_=u?Object.values(u):i,C=f.useCallback(k=>{let P=k;if(!P)return;k==="system"&&n&&(P=a$());const M=u?u[P]:P,A=t?fte():null,O=document.documentElement;if(l==="class"?(O.classList.remove(..._),M&&O.classList.add(M)):M?O.setAttribute(l,M):O.removeAttribute(l),r){const F=sm.includes(s)?s:null,V=sm.includes(P)?P:F;O.style.colorScheme=V}A==null||A()},[]),S=f.useCallback(k=>{g(k);try{localStorage.setItem(o,k)}catch{}},[e]),b=f.useCallback(k=>{const P=a$(k);x(P),m==="system"&&n&&!e&&C("system")},[m,e]);f.useEffect(()=>{const k=window.matchMedia(ub);return k.addListener(b),b(k),()=>k.removeListener(b)},[b]),f.useEffect(()=>{const k=P=>{P.key===o&&S(P.newValue||s)};return window.addEventListener("storage",k),()=>window.removeEventListener("storage",k)},[S]),f.useEffect(()=>{C(e??m)},[e,m]);const E=f.useMemo(()=>({theme:m,setTheme:S,forcedTheme:e,resolvedTheme:m==="system"?y:m,themes:n?[...i,"system"]:i,systemTheme:n?y:void 0}),[m,S,e,y,n,i]);return Fe.createElement(rO.Provider,{value:E},Fe.createElement(dte,{forcedTheme:e,disableTransitionOnChange:t,enableSystem:n,enableColorScheme:r,storageKey:o,themes:i,defaultTheme:s,attribute:l,value:u,children:d,attrs:_,nonce:h}),d)},dte=f.memo(({forcedTheme:e,storageKey:t,attribute:n,enableSystem:r,enableColorScheme:o,defaultTheme:i,value:s,attrs:l,nonce:u})=>{const d=i==="system",h=n==="class"?`var d=document.documentElement,c=d.classList;c.remove(${l.map(x=>`'${x}'`).join(",")});`:`var d=document.documentElement,n='${n}',s='setAttribute';`,m=o?sm.includes(i)&&i?`if(e==='light'||e==='dark'||!e)d.style.colorScheme=e||'${i}'`:"if(e==='light'||e==='dark')d.style.colorScheme=e":"",g=(x,_=!1,C=!0)=>{const S=s?s[x]:x,b=_?x+"|| ''":`'${S}'`;let E="";return o&&C&&!_&&sm.includes(x)&&(E+=`d.style.colorScheme = '${x}';`),n==="class"?E+=_||S?`c.add(${b})`:"null":S&&(E+=`d[s](n,${b})`),E},y=e?`!function(){${h}${g(e)}}()`:r?`!function(){try{${h}var e=localStorage.getItem('${t}');if('system'===e||(!e&&${d})){var t='${ub}',m=window.matchMedia(t);if(m.media!==t||m.matches){${g("dark")}}else{${g("light")}}}else if(e){${s?`var x=${JSON.stringify(s)};`:""}${g(s?"x[e]":"e",!0)}}${d?"":"else{"+g(i,!1,!1)+"}"}${m}}catch(e){}}()`:`!function(){try{${h}var e=localStorage.getItem('${t}');if(e){${s?`var x=${JSON.stringify(s)};`:""}${g(s?"x[e]":"e",!0)}}else{${g(i,!1,!1)};}${m}}catch(t){}}();`;return Fe.createElement("script",{nonce:u,dangerouslySetInnerHTML:{__html:y}})},()=>!0),s$=(e,t)=>{if(ate)return;let n;try{n=localStorage.getItem(e)||void 0}catch{}return n||t},fte=()=>{const e=document.createElement("style");return e.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(e),()=>{window.getComputedStyle(document.body),setTimeout(()=>{document.head.removeChild(e)},1)}},a$=e=>(e||(e=window.matchMedia(ub)),e.matches?"dark":"light"),pte=new dL;z0.createRoot(document.getElementById("root")).render(v.jsx(Fe.StrictMode,{children:v.jsx(gL,{client:pte,children:v.jsx(lte,{defaultTheme:"dark",disableTransitionOnChange:!0,children:v.jsx(UU,{children:v.jsx(ste,{})})})})})); diff --git a/py/iopaint/web_app/assets/index-NQyCh9rO.js b/py/iopaint/web_app/assets/index-NQyCh9rO.js new file mode 100644 index 0000000..b7e3c1d --- /dev/null +++ b/py/iopaint/web_app/assets/index-NQyCh9rO.js @@ -0,0 +1,165 @@ +var Nv=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)};var z=(e,t,n)=>(Nv(e,t,"read from private field"),n?n.call(e):t.get(e)),Te=(e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)},ye=(e,t,n,r)=>(Nv(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n);var Ff=(e,t,n,r)=>({set _(o){ye(e,t,o,n)},get _(){return z(e,t,r)}}),tt=(e,t,n)=>(Nv(e,t,"access private method"),n);function SD(e,t){for(var n=0;nr[o]})}}}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 o of document.querySelectorAll('link[rel="modulepreload"]'))r(o);new MutationObserver(o=>{for(const i of o)if(i.type==="childList")for(const s of i.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&r(s)}).observe(document,{childList:!0,subtree:!0});function n(o){const i={};return o.integrity&&(i.integrity=o.integrity),o.referrerPolicy&&(i.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?i.credentials="include":o.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(o){if(o.ep)return;o.ep=!0;const i=n(o);fetch(o.href,i)}})();var Yc=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function lm(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var v$={exports:{}},cm={},y$={exports:{}},it={};/** + * @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 bd=Symbol.for("react.element"),ED=Symbol.for("react.portal"),CD=Symbol.for("react.fragment"),$D=Symbol.for("react.strict_mode"),kD=Symbol.for("react.profiler"),RD=Symbol.for("react.provider"),TD=Symbol.for("react.context"),PD=Symbol.for("react.forward_ref"),AD=Symbol.for("react.suspense"),OD=Symbol.for("react.memo"),MD=Symbol.for("react.lazy"),LS=Symbol.iterator;function ND(e){return e===null||typeof e!="object"?null:(e=LS&&e[LS]||e["@@iterator"],typeof e=="function"?e:null)}var w$={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},x$=Object.assign,b$={};function fc(e,t,n){this.props=e,this.context=t,this.refs=b$,this.updater=n||w$}fc.prototype.isReactComponent={};fc.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")};fc.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function _$(){}_$.prototype=fc.prototype;function ew(e,t,n){this.props=e,this.context=t,this.refs=b$,this.updater=n||w$}var tw=ew.prototype=new _$;tw.constructor=ew;x$(tw,fc.prototype);tw.isPureReactComponent=!0;var FS=Array.isArray,S$=Object.prototype.hasOwnProperty,nw={current:null},E$={key:!0,ref:!0,__self:!0,__source:!0};function C$(e,t,n){var r,o={},i=null,s=null;if(t!=null)for(r in t.ref!==void 0&&(s=t.ref),t.key!==void 0&&(i=""+t.key),t)S$.call(t,r)&&!E$.hasOwnProperty(r)&&(o[r]=t[r]);var l=arguments.length-2;if(l===1)o.children=n;else if(1>>1,ge=K[le];if(0>>1;leo(We,W))Meo(fe,We)?(K[le]=fe,K[Me]=W,le=Me):(K[le]=We,K[Ue]=W,le=Ue);else if(Meo(fe,W))K[le]=fe,K[Me]=W,le=Me;else break e}}return Q}function o(K,Q){var W=K.sortIndex-Q.sortIndex;return W!==0?W:K.id-Q.id}if(typeof performance=="object"&&typeof performance.now=="function"){var i=performance;e.unstable_now=function(){return i.now()}}else{var s=Date,l=s.now();e.unstable_now=function(){return s.now()-l}}var u=[],d=[],h=1,m=null,g=3,y=!1,x=!1,_=!1,C=typeof setTimeout=="function"?setTimeout:null,S=typeof clearTimeout=="function"?clearTimeout:null,b=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function E(K){for(var Q=n(d);Q!==null;){if(Q.callback===null)r(d);else if(Q.startTime<=K)r(d),Q.sortIndex=Q.expirationTime,t(u,Q);else break;Q=n(d)}}function k(K){if(_=!1,E(K),!x)if(n(u)!==null)x=!0,L(P);else{var Q=n(d);Q!==null&&ie(k,Q.startTime-K)}}function P(K,Q){x=!1,_&&(_=!1,S(O),O=-1),y=!0;var W=g;try{for(E(Q),m=n(u);m!==null&&(!(m.expirationTime>Q)||K&&!J());){var le=m.callback;if(typeof le=="function"){m.callback=null,g=m.priorityLevel;var ge=le(m.expirationTime<=Q);Q=e.unstable_now(),typeof ge=="function"?m.callback=ge:m===n(u)&&r(u),E(Q)}else r(u);m=n(u)}if(m!==null)var Ve=!0;else{var Ue=n(d);Ue!==null&&ie(k,Ue.startTime-Q),Ve=!1}return Ve}finally{m=null,g=W,y=!1}}var M=!1,A=null,O=-1,F=5,V=-1;function J(){return!(e.unstable_now()-VK||125le?(K.sortIndex=W,t(d,K),n(u)===null&&K===n(d)&&(_?(S(O),O=-1):_=!0,ie(k,W-le))):(K.sortIndex=ge,t(u,K),x||y||(x=!0,L(P))),K},e.unstable_shouldYield=J,e.unstable_wrapCallback=function(K){var Q=g;return function(){var W=g;g=Q;try{return K.apply(this,arguments)}finally{g=W}}}})(T$);R$.exports=T$;var KD=R$.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 P$=f,yr=KD;function ce(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"),B0=Object.prototype.hasOwnProperty,YD=/^[: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]*$/,zS={},BS={};function GD(e){return B0.call(BS,e)?!0:B0.call(zS,e)?!1:YD.test(e)?BS[e]=!0:(zS[e]=!0,!1)}function XD(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 ZD(e,t,n,r){if(t===null||typeof t>"u"||XD(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 Un(e,t,n,r,o,i,s){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=o,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=i,this.removeEmptyString=s}var xn={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){xn[e]=new Un(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];xn[t]=new Un(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){xn[e]=new Un(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){xn[e]=new Un(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){xn[e]=new Un(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){xn[e]=new Un(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){xn[e]=new Un(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){xn[e]=new Un(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){xn[e]=new Un(e,5,!1,e.toLowerCase(),null,!1,!1)});var ow=/[\-:]([a-z])/g;function iw(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(ow,iw);xn[t]=new Un(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(ow,iw);xn[t]=new Un(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(ow,iw);xn[t]=new Un(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){xn[e]=new Un(e,1,!1,e.toLowerCase(),null,!1,!1)});xn.xlinkHref=new Un("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){xn[e]=new Un(e,1,!1,e.toLowerCase(),null,!0,!0)});function sw(e,t,n,r){var o=xn.hasOwnProperty(t)?xn[t]:null;(o!==null?o.type!==0:r||!(2l||o[s]!==i[l]){var u=` +`+o[s].replace(" at new "," at ");return e.displayName&&u.includes("")&&(u=u.replace("",e.displayName)),u}while(1<=s&&0<=l);break}}}finally{Lv=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?uu(e):""}function qD(e){switch(e.tag){case 5:return uu(e.type);case 16:return uu("Lazy");case 13:return uu("Suspense");case 19:return uu("SuspenseList");case 0:case 2:case 15:return e=Fv(e.type,!1),e;case 11:return e=Fv(e.type.render,!1),e;case 1:return e=Fv(e.type,!0),e;default:return""}}function H0(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 ll:return"Fragment";case al:return"Portal";case U0:return"Profiler";case aw:return"StrictMode";case V0:return"Suspense";case W0:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case M$:return(e.displayName||"Context")+".Consumer";case O$:return(e._context.displayName||"Context")+".Provider";case lw:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case cw:return t=e.displayName||null,t!==null?t:H0(e.type)||"Memo";case Ki:t=e._payload,e=e._init;try{return H0(e(t))}catch{}}return null}function QD(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 H0(t);case 8:return t===aw?"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 Ss(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function D$(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function JD(e){var t=D$(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 o=n.get,i=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return o.call(this)},set:function(s){r=""+s,i.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 Bf(e){e._valueTracker||(e._valueTracker=JD(e))}function I$(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=D$(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function oh(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 K0(e,t){var n=t.checked;return zt({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function VS(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=Ss(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 L$(e,t){t=t.checked,t!=null&&sw(e,"checked",t,!1)}function Y0(e,t){L$(e,t);var n=Ss(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")?G0(e,t.type,n):t.hasOwnProperty("defaultValue")&&G0(e,t.type,Ss(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function WS(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 G0(e,t,n){(t!=="number"||oh(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var du=Array.isArray;function bl(e,t,n,r){if(e=e.options,t){t={};for(var o=0;o"+t.valueOf().toString()+"",t=Uf.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function Ou(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var vu={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},e9=["Webkit","ms","Moz","O"];Object.keys(vu).forEach(function(e){e9.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),vu[t]=vu[e]})});function B$(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||vu.hasOwnProperty(e)&&vu[e]?(""+t).trim():t+"px"}function U$(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,o=B$(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,o):e[n]=o}}var t9=zt({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 q0(e,t){if(t){if(t9[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(ce(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(ce(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(ce(61))}if(t.style!=null&&typeof t.style!="object")throw Error(ce(62))}}function Q0(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 J0=null;function uw(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var ey=null,_l=null,Sl=null;function YS(e){if(e=Ed(e)){if(typeof ey!="function")throw Error(ce(280));var t=e.stateNode;t&&(t=hm(t),ey(e.stateNode,e.type,t))}}function V$(e){_l?Sl?Sl.push(e):Sl=[e]:_l=e}function W$(){if(_l){var e=_l,t=Sl;if(Sl=_l=null,YS(e),t)for(e=0;e>>=0,e===0?32:31-(f9(e)/p9|0)|0}var Vf=64,Wf=4194304;function fu(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 lh(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,o=e.suspendedLanes,i=e.pingedLanes,s=n&268435455;if(s!==0){var l=s&~o;l!==0?r=fu(l):(i&=s,i!==0&&(r=fu(i)))}else s=n&~o,s!==0?r=fu(s):i!==0&&(r=fu(i));if(r===0)return 0;if(t!==0&&t!==r&&!(t&o)&&(o=r&-r,i=t&-t,o>=i||o===16&&(i&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 _d(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-go(t),e[t]=n}function v9(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=wu),nE=" ",rE=!1;function uk(e,t){switch(e){case"keyup":return H9.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function dk(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var cl=!1;function Y9(e,t){switch(e){case"compositionend":return dk(t);case"keypress":return t.which!==32?null:(rE=!0,nE);case"textInput":return e=t.data,e===nE&&rE?null:e;default:return null}}function G9(e,t){if(cl)return e==="compositionend"||!yw&&uk(e,t)?(e=lk(),$p=mw=rs=null,cl=!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=aE(n)}}function mk(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?mk(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function gk(){for(var e=window,t=oh();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=oh(e.document)}return t}function ww(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 rI(e){var t=gk(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&mk(n.ownerDocument.documentElement,n)){if(r!==null&&ww(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 o=n.textContent.length,i=Math.min(r.start,o);r=r.end===void 0?i:Math.min(r.end,o),!e.extend&&i>r&&(o=r,r=i,i=o),o=lE(n,i);var s=lE(n,r);o&&s&&(e.rangeCount!==1||e.anchorNode!==o.node||e.anchorOffset!==o.offset||e.focusNode!==s.node||e.focusOffset!==s.offset)&&(t=t.createRange(),t.setStart(o.node,o.offset),e.removeAllRanges(),i>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,ul=null,sy=null,bu=null,ay=!1;function cE(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;ay||ul==null||ul!==oh(r)||(r=ul,"selectionStart"in r&&ww(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}),bu&&Fu(bu,r)||(bu=r,r=dh(sy,"onSelect"),0pl||(e.current=py[pl],py[pl]=null,pl--)}function $t(e,t){pl++,py[pl]=e.current,e.current=t}var Es={},Tn=Ps(Es),Jn=Ps(!1),ba=Es;function Kl(e,t){var n=e.type.contextTypes;if(!n)return Es;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var o={},i;for(i in n)o[i]=t[i];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=o),o}function er(e){return e=e.childContextTypes,e!=null}function ph(){At(Jn),At(Tn)}function gE(e,t,n){if(Tn.current!==Es)throw Error(ce(168));$t(Tn,t),$t(Jn,n)}function Ck(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var o in r)if(!(o in t))throw Error(ce(108,QD(e)||"Unknown",o));return zt({},n,r)}function hh(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||Es,ba=Tn.current,$t(Tn,e),$t(Jn,Jn.current),!0}function vE(e,t,n){var r=e.stateNode;if(!r)throw Error(ce(169));n?(e=Ck(e,t,ba),r.__reactInternalMemoizedMergedChildContext=e,At(Jn),At(Tn),$t(Tn,e)):At(Jn),$t(Jn,n)}var li=null,mm=!1,Qv=!1;function $k(e){li===null?li=[e]:li.push(e)}function mI(e){mm=!0,$k(e)}function As(){if(!Qv&&li!==null){Qv=!0;var e=0,t=xt;try{var n=li;for(xt=1;e>=s,o-=s,ci=1<<32-go(t)+o|n<O?(F=A,A=null):F=A.sibling;var V=g(S,A,E[O],k);if(V===null){A===null&&(A=F);break}e&&A&&V.alternate===null&&t(S,A),b=i(V,b,O),M===null?P=V:M.sibling=V,M=V,A=F}if(O===E.length)return n(S,A),Dt&&qs(S,O),P;if(A===null){for(;OO?(F=A,A=null):F=A.sibling;var J=g(S,A,V.value,k);if(J===null){A===null&&(A=F);break}e&&A&&J.alternate===null&&t(S,A),b=i(J,b,O),M===null?P=J:M.sibling=J,M=J,A=F}if(V.done)return n(S,A),Dt&&qs(S,O),P;if(A===null){for(;!V.done;O++,V=E.next())V=m(S,V.value,k),V!==null&&(b=i(V,b,O),M===null?P=V:M.sibling=V,M=V);return Dt&&qs(S,O),P}for(A=r(S,A);!V.done;O++,V=E.next())V=y(A,S,O,V.value,k),V!==null&&(e&&V.alternate!==null&&A.delete(V.key===null?O:V.key),b=i(V,b,O),M===null?P=V:M.sibling=V,M=V);return e&&A.forEach(function(G){return t(S,G)}),Dt&&qs(S,O),P}function C(S,b,E,k){if(typeof E=="object"&&E!==null&&E.type===ll&&E.key===null&&(E=E.props.children),typeof E=="object"&&E!==null){switch(E.$$typeof){case zf:e:{for(var P=E.key,M=b;M!==null;){if(M.key===P){if(P=E.type,P===ll){if(M.tag===7){n(S,M.sibling),b=o(M,E.props.children),b.return=S,S=b;break e}}else if(M.elementType===P||typeof P=="object"&&P!==null&&P.$$typeof===Ki&&EE(P)===M.type){n(S,M.sibling),b=o(M,E.props),b.ref=Jc(S,M,E),b.return=S,S=b;break e}n(S,M);break}else t(S,M);M=M.sibling}E.type===ll?(b=xa(E.props.children,S.mode,k,E.key),b.return=S,S=b):(k=Np(E.type,E.key,E.props,null,S.mode,k),k.ref=Jc(S,b,E),k.return=S,S=k)}return s(S);case al:e:{for(M=E.key;b!==null;){if(b.key===M)if(b.tag===4&&b.stateNode.containerInfo===E.containerInfo&&b.stateNode.implementation===E.implementation){n(S,b.sibling),b=o(b,E.children||[]),b.return=S,S=b;break e}else{n(S,b);break}else t(S,b);b=b.sibling}b=s0(E,S.mode,k),b.return=S,S=b}return s(S);case Ki:return M=E._init,C(S,b,M(E._payload),k)}if(du(E))return x(S,b,E,k);if(Gc(E))return _(S,b,E,k);qf(S,E)}return typeof E=="string"&&E!==""||typeof E=="number"?(E=""+E,b!==null&&b.tag===6?(n(S,b.sibling),b=o(b,E),b.return=S,S=b):(n(S,b),b=i0(E,S.mode,k),b.return=S,S=b),s(S)):n(S,b)}return C}var Gl=Nk(!0),Dk=Nk(!1),Cd={},zo=Ps(Cd),Uu=Ps(Cd),Vu=Ps(Cd);function oa(e){if(e===Cd)throw Error(ce(174));return e}function Rw(e,t){switch($t(Vu,t),$t(Uu,e),$t(zo,Cd),e=t.nodeType,e){case 9:case 11:t=(t=t.documentElement)?t.namespaceURI:Z0(null,"");break;default:e=e===8?t.parentNode:t,t=e.namespaceURI||null,e=e.tagName,t=Z0(t,e)}At(zo),$t(zo,t)}function Xl(){At(zo),At(Uu),At(Vu)}function Ik(e){oa(Vu.current);var t=oa(zo.current),n=Z0(t,e.type);t!==n&&($t(Uu,e),$t(zo,n))}function Tw(e){Uu.current===e&&(At(zo),At(Uu))}var Lt=Ps(0);function xh(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 Jv=[];function Pw(){for(var e=0;en?n:4,e(!0);var r=e0.transition;e0.transition={};try{e(!1),t()}finally{xt=n,e0.transition=r}}function Qk(){return Gr().memoizedState}function wI(e,t,n){var r=ys(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},Jk(e))eR(t,n);else if(n=Pk(e,t,n,r),n!==null){var o=jn();vo(n,e,r,o),tR(n,t,r)}}function xI(e,t,n){var r=ys(e),o={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(Jk(e))eR(t,o);else{var i=e.alternate;if(e.lanes===0&&(i===null||i.lanes===0)&&(i=t.lastRenderedReducer,i!==null))try{var s=t.lastRenderedState,l=i(s,n);if(o.hasEagerState=!0,o.eagerState=l,wo(l,s)){var u=t.interleaved;u===null?(o.next=o,$w(t)):(o.next=u.next,u.next=o),t.interleaved=o;return}}catch{}finally{}n=Pk(e,t,o,r),n!==null&&(o=jn(),vo(n,e,r,o),tR(n,t,r))}}function Jk(e){var t=e.alternate;return e===jt||t!==null&&t===jt}function eR(e,t){_u=bh=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function tR(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,fw(e,n)}}var _h={readContext:Yr,useCallback:Cn,useContext:Cn,useEffect:Cn,useImperativeHandle:Cn,useInsertionEffect:Cn,useLayoutEffect:Cn,useMemo:Cn,useReducer:Cn,useRef:Cn,useState:Cn,useDebugValue:Cn,useDeferredValue:Cn,useTransition:Cn,useMutableSource:Cn,useSyncExternalStore:Cn,useId:Cn,unstable_isNewReconciler:!1},bI={readContext:Yr,useCallback:function(e,t){return ko().memoizedState=[e,t===void 0?null:t],e},useContext:Yr,useEffect:$E,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,Pp(4194308,4,Yk.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Pp(4194308,4,e,t)},useInsertionEffect:function(e,t){return Pp(4,2,e,t)},useMemo:function(e,t){var n=ko();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=ko();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=wI.bind(null,jt,e),[r.memoizedState,e]},useRef:function(e){var t=ko();return e={current:e},t.memoizedState=e},useState:CE,useDebugValue:Dw,useDeferredValue:function(e){return ko().memoizedState=e},useTransition:function(){var e=CE(!1),t=e[0];return e=yI.bind(null,e[1]),ko().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=jt,o=ko();if(Dt){if(n===void 0)throw Error(ce(407));n=n()}else{if(n=t(),dn===null)throw Error(ce(349));Sa&30||jk(r,t,n)}o.memoizedState=n;var i={value:n,getSnapshot:t};return o.queue=i,$E(Bk.bind(null,r,i,e),[e]),r.flags|=2048,Ku(9,zk.bind(null,r,i,n,t),void 0,null),n},useId:function(){var e=ko(),t=dn.identifierPrefix;if(Dt){var n=ui,r=ci;n=(r&~(1<<32-go(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=Wu++,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[Oo]=t,e[Bu]=r,uR(e,t,!1,!1),t.stateNode=e;e:{switch(s=Q0(n,r),n){case"dialog":Tt("cancel",e),Tt("close",e),o=r;break;case"iframe":case"object":case"embed":Tt("load",e),o=r;break;case"video":case"audio":for(o=0;oql&&(t.flags|=128,r=!0,eu(i,!1),t.lanes=4194304)}else{if(!r)if(e=xh(s),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),eu(i,!0),i.tail===null&&i.tailMode==="hidden"&&!s.alternate&&!Dt)return $n(t),null}else 2*Xt()-i.renderingStartTime>ql&&n!==1073741824&&(t.flags|=128,r=!0,eu(i,!1),t.lanes=4194304);i.isBackwards?(s.sibling=t.child,t.child=s):(n=i.last,n!==null?n.sibling=s:t.child=s,i.last=s)}return i.tail!==null?(t=i.tail,i.rendering=t,i.tail=t.sibling,i.renderingStartTime=Xt(),t.sibling=null,n=Lt.current,$t(Lt,r?n&1|2:n&1),t):($n(t),null);case 22:case 23:return Bw(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?fr&1073741824&&($n(t),t.subtreeFlags&6&&(t.flags|=8192)):$n(t),null;case 24:return null;case 25:return null}throw Error(ce(156,t.tag))}function TI(e,t){switch(bw(t),t.tag){case 1:return er(t.type)&&ph(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Xl(),At(Jn),At(Tn),Pw(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return Tw(t),null;case 13:if(At(Lt),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(ce(340));Yl()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return At(Lt),null;case 4:return Xl(),null;case 10:return Cw(t.type._context),null;case 22:case 23:return Bw(),null;case 24:return null;default:return null}}var Jf=!1,Rn=!1,PI=typeof WeakSet=="function"?WeakSet:Set,Se=null;function vl(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){Wt(e,t,r)}else n.current=null}function Cy(e,t,n){try{n()}catch(r){Wt(e,t,r)}}var DE=!1;function AI(e,t){if(ly=ch,e=gk(),ww(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 o=r.anchorOffset,i=r.focusNode;r=r.focusOffset;try{n.nodeType,i.nodeType}catch{n=null;break e}var s=0,l=-1,u=-1,d=0,h=0,m=e,g=null;t:for(;;){for(var y;m!==n||o!==0&&m.nodeType!==3||(l=s+o),m!==i||r!==0&&m.nodeType!==3||(u=s+r),m.nodeType===3&&(s+=m.nodeValue.length),(y=m.firstChild)!==null;)g=m,m=y;for(;;){if(m===e)break t;if(g===n&&++d===o&&(l=s),g===i&&++h===r&&(u=s),(y=m.nextSibling)!==null)break;m=g,g=m.parentNode}m=y}n=l===-1||u===-1?null:{start:l,end:u}}else n=null}n=n||{start:0,end:0}}else n=null;for(cy={focusedElem:e,selectionRange:n},ch=!1,Se=t;Se!==null;)if(t=Se,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,Se=e;else for(;Se!==null;){t=Se;try{var x=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(x!==null){var _=x.memoizedProps,C=x.memoizedState,S=t.stateNode,b=S.getSnapshotBeforeUpdate(t.elementType===t.type?_:io(t.type,_),C);S.__reactInternalSnapshotBeforeUpdate=b}break;case 3:var E=t.stateNode.containerInfo;E.nodeType===1?E.textContent="":E.nodeType===9&&E.documentElement&&E.removeChild(E.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(ce(163))}}catch(k){Wt(t,t.return,k)}if(e=t.sibling,e!==null){e.return=t.return,Se=e;break}Se=t.return}return x=DE,DE=!1,x}function Su(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var o=r=r.next;do{if((o.tag&e)===e){var i=o.destroy;o.destroy=void 0,i!==void 0&&Cy(t,n,i)}o=o.next}while(o!==r)}}function ym(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 $y(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 pR(e){var t=e.alternate;t!==null&&(e.alternate=null,pR(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Oo],delete t[Bu],delete t[fy],delete t[pI],delete t[hI])),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 hR(e){return e.tag===5||e.tag===3||e.tag===4}function IE(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||hR(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 ky(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=fh));else if(r!==4&&(e=e.child,e!==null))for(ky(e,t,n),e=e.sibling;e!==null;)ky(e,t,n),e=e.sibling}function Ry(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(Ry(e,t,n),e=e.sibling;e!==null;)Ry(e,t,n),e=e.sibling}var mn=null,lo=!1;function ji(e,t,n){for(n=n.child;n!==null;)mR(e,t,n),n=n.sibling}function mR(e,t,n){if(jo&&typeof jo.onCommitFiberUnmount=="function")try{jo.onCommitFiberUnmount(um,n)}catch{}switch(n.tag){case 5:Rn||vl(n,t);case 6:var r=mn,o=lo;mn=null,ji(e,t,n),mn=r,lo=o,mn!==null&&(lo?(e=mn,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):mn.removeChild(n.stateNode));break;case 18:mn!==null&&(lo?(e=mn,n=n.stateNode,e.nodeType===8?qv(e.parentNode,n):e.nodeType===1&&qv(e,n),Iu(e)):qv(mn,n.stateNode));break;case 4:r=mn,o=lo,mn=n.stateNode.containerInfo,lo=!0,ji(e,t,n),mn=r,lo=o;break;case 0:case 11:case 14:case 15:if(!Rn&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){o=r=r.next;do{var i=o,s=i.destroy;i=i.tag,s!==void 0&&(i&2||i&4)&&Cy(n,t,s),o=o.next}while(o!==r)}ji(e,t,n);break;case 1:if(!Rn&&(vl(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(l){Wt(n,t,l)}ji(e,t,n);break;case 21:ji(e,t,n);break;case 22:n.mode&1?(Rn=(r=Rn)||n.memoizedState!==null,ji(e,t,n),Rn=r):ji(e,t,n);break;default:ji(e,t,n)}}function LE(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new PI),t.forEach(function(r){var o=zI.bind(null,e,r);n.has(r)||(n.add(r),r.then(o,o))})}}function ro(e,t){var n=t.deletions;if(n!==null)for(var r=0;ro&&(o=s),r&=~i}if(r=o,r=Xt()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*MI(r/1960))-r,10e?16:e,os===null)var r=!1;else{if(e=os,os=null,Ch=0,dt&6)throw Error(ce(331));var o=dt;for(dt|=4,Se=e.current;Se!==null;){var i=Se,s=i.child;if(Se.flags&16){var l=i.deletions;if(l!==null){for(var u=0;uXt()-jw?wa(e,0):Fw|=n),tr(e,t)}function SR(e,t){t===0&&(e.mode&1?(t=Wf,Wf<<=1,!(Wf&130023424)&&(Wf=4194304)):t=1);var n=jn();e=gi(e,t),e!==null&&(_d(e,t,n),tr(e,n))}function jI(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),SR(e,n)}function zI(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,o=e.memoizedState;o!==null&&(n=o.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(ce(314))}r!==null&&r.delete(t),SR(e,n)}var ER;ER=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||Jn.current)Qn=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return Qn=!1,kI(e,t,n);Qn=!!(e.flags&131072)}else Qn=!1,Dt&&t.flags&1048576&&kk(t,gh,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;Ap(e,t),e=t.pendingProps;var o=Kl(t,Tn.current);Cl(t,n),o=Ow(null,t,r,e,o,n);var i=Mw();return t.flags|=1,typeof o=="object"&&o!==null&&typeof o.render=="function"&&o.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,er(r)?(i=!0,hh(t)):i=!1,t.memoizedState=o.state!==null&&o.state!==void 0?o.state:null,kw(t),o.updater=gm,t.stateNode=o,o._reactInternals=t,yy(t,r,e,n),t=by(null,t,r,!0,i,n)):(t.tag=0,Dt&&i&&xw(t),Dn(null,t,o,n),t=t.child),t;case 16:r=t.elementType;e:{switch(Ap(e,t),e=t.pendingProps,o=r._init,r=o(r._payload),t.type=r,o=t.tag=UI(r),e=io(r,e),o){case 0:t=xy(null,t,r,e,n);break e;case 1:t=OE(null,t,r,e,n);break e;case 11:t=PE(null,t,r,e,n);break e;case 14:t=AE(null,t,r,io(r.type,e),n);break e}throw Error(ce(306,r,""))}return t;case 0:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),xy(e,t,r,o,n);case 1:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),OE(e,t,r,o,n);case 3:e:{if(aR(t),e===null)throw Error(ce(387));r=t.pendingProps,i=t.memoizedState,o=i.element,Ak(e,t),wh(t,r,null,n);var s=t.memoizedState;if(r=s.element,i.isDehydrated)if(i={element:r,isDehydrated:!1,cache:s.cache,pendingSuspenseBoundaries:s.pendingSuspenseBoundaries,transitions:s.transitions},t.updateQueue.baseState=i,t.memoizedState=i,t.flags&256){o=Zl(Error(ce(423)),t),t=ME(e,t,r,n,o);break e}else if(r!==o){o=Zl(Error(ce(424)),t),t=ME(e,t,r,n,o);break e}else for(mr=ms(t.stateNode.containerInfo.firstChild),gr=t,Dt=!0,po=null,n=Dk(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(Yl(),r===o){t=vi(e,t,n);break e}Dn(e,t,r,n)}t=t.child}return t;case 5:return Ik(t),e===null&&my(t),r=t.type,o=t.pendingProps,i=e!==null?e.memoizedProps:null,s=o.children,uy(r,o)?s=null:i!==null&&uy(r,i)&&(t.flags|=32),sR(e,t),Dn(e,t,s,n),t.child;case 6:return e===null&&my(t),null;case 13:return lR(e,t,n);case 4:return Rw(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=Gl(t,null,r,n):Dn(e,t,r,n),t.child;case 11:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),PE(e,t,r,o,n);case 7:return Dn(e,t,t.pendingProps,n),t.child;case 8:return Dn(e,t,t.pendingProps.children,n),t.child;case 12:return Dn(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,o=t.pendingProps,i=t.memoizedProps,s=o.value,$t(vh,r._currentValue),r._currentValue=s,i!==null)if(wo(i.value,s)){if(i.children===o.children&&!Jn.current){t=vi(e,t,n);break e}}else for(i=t.child,i!==null&&(i.return=t);i!==null;){var l=i.dependencies;if(l!==null){s=i.child;for(var u=l.firstContext;u!==null;){if(u.context===r){if(i.tag===1){u=fi(-1,n&-n),u.tag=2;var d=i.updateQueue;if(d!==null){d=d.shared;var h=d.pending;h===null?u.next=u:(u.next=h.next,h.next=u),d.pending=u}}i.lanes|=n,u=i.alternate,u!==null&&(u.lanes|=n),gy(i.return,n,t),l.lanes|=n;break}u=u.next}}else if(i.tag===10)s=i.type===t.type?null:i.child;else if(i.tag===18){if(s=i.return,s===null)throw Error(ce(341));s.lanes|=n,l=s.alternate,l!==null&&(l.lanes|=n),gy(s,n,t),s=i.sibling}else s=i.child;if(s!==null)s.return=i;else for(s=i;s!==null;){if(s===t){s=null;break}if(i=s.sibling,i!==null){i.return=s.return,s=i;break}s=s.return}i=s}Dn(e,t,o.children,n),t=t.child}return t;case 9:return o=t.type,r=t.pendingProps.children,Cl(t,n),o=Yr(o),r=r(o),t.flags|=1,Dn(e,t,r,n),t.child;case 14:return r=t.type,o=io(r,t.pendingProps),o=io(r.type,o),AE(e,t,r,o,n);case 15:return oR(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),Ap(e,t),t.tag=1,er(r)?(e=!0,hh(t)):e=!1,Cl(t,n),Mk(t,r,o),yy(t,r,o,n),by(null,t,r,!0,e,n);case 19:return cR(e,t,n);case 22:return iR(e,t,n)}throw Error(ce(156,t.tag))};function CR(e,t){return q$(e,t)}function BI(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 Ur(e,t,n,r){return new BI(e,t,n,r)}function Vw(e){return e=e.prototype,!(!e||!e.isReactComponent)}function UI(e){if(typeof e=="function")return Vw(e)?1:0;if(e!=null){if(e=e.$$typeof,e===lw)return 11;if(e===cw)return 14}return 2}function ws(e,t){var n=e.alternate;return n===null?(n=Ur(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 Np(e,t,n,r,o,i){var s=2;if(r=e,typeof e=="function")Vw(e)&&(s=1);else if(typeof e=="string")s=5;else e:switch(e){case ll:return xa(n.children,o,i,t);case aw:s=8,o|=8;break;case U0:return e=Ur(12,n,t,o|2),e.elementType=U0,e.lanes=i,e;case V0:return e=Ur(13,n,t,o),e.elementType=V0,e.lanes=i,e;case W0:return e=Ur(19,n,t,o),e.elementType=W0,e.lanes=i,e;case N$:return xm(n,o,i,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case O$:s=10;break e;case M$:s=9;break e;case lw:s=11;break e;case cw:s=14;break e;case Ki:s=16,r=null;break e}throw Error(ce(130,e==null?e:typeof e,""))}return t=Ur(s,n,t,o),t.elementType=e,t.type=r,t.lanes=i,t}function xa(e,t,n,r){return e=Ur(7,e,r,t),e.lanes=n,e}function xm(e,t,n,r){return e=Ur(22,e,r,t),e.elementType=N$,e.lanes=n,e.stateNode={isHidden:!1},e}function i0(e,t,n){return e=Ur(6,e,null,t),e.lanes=n,e}function s0(e,t,n){return t=Ur(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function VI(e,t,n,r,o){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=zv(0),this.expirationTimes=zv(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=zv(0),this.identifierPrefix=r,this.onRecoverableError=o,this.mutableSourceEagerHydrationData=null}function Ww(e,t,n,r,o,i,s,l,u){return e=new VI(e,t,n,l,u),t===1?(t=1,i===!0&&(t|=8)):t=0,i=Ur(3,null,null,t),e.current=i,i.stateNode=e,i.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},kw(i),e}function WI(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(TR)}catch(e){console.error(e)}}TR(),k$.exports=br;var Os=k$.exports;const XI=lm(Os);var HE=Os;z0.createRoot=HE.createRoot,z0.hydrateRoot=HE.hydrateRoot;var $d=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},Ql=typeof window>"u"||"Deno"in window;function Lr(){}function ZI(e,t){return typeof e=="function"?e(t):e}function My(e){return typeof e=="number"&&e>=0&&e!==1/0}function PR(e,t){return Math.max(e+(t||0)-Date.now(),0)}function KE(e,t){const{type:n="all",exact:r,fetchStatus:o,predicate:i,queryKey:s,stale:l}=e;if(s){if(r){if(t.queryHash!==Gw(s,t.options))return!1}else if(!Xu(t.queryKey,s))return!1}if(n!=="all"){const u=t.isActive();if(n==="active"&&!u||n==="inactive"&&u)return!1}return!(typeof l=="boolean"&&t.isStale()!==l||typeof o<"u"&&o!==t.state.fetchStatus||i&&!i(t))}function YE(e,t){const{exact:n,status:r,predicate:o,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(Gu(t.options.mutationKey)!==Gu(i))return!1}else if(!Xu(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||o&&!o(t))}function Gw(e,t){return((t==null?void 0:t.queryKeyHashFn)||Gu)(e)}function Gu(e){return JSON.stringify(e,(t,n)=>Dy(n)?Object.keys(n).sort().reduce((r,o)=>(r[o]=n[o],r),{}):n)}function Xu(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?!Object.keys(t).some(n=>!Xu(e[n],t[n])):!1}function AR(e,t){if(e===t)return e;const n=GE(e)&&GE(t);if(n||Dy(e)&&Dy(t)){const r=n?e.length:Object.keys(e).length,o=n?t:Object.keys(t),i=o.length,s=n?[]:{};let l=0;for(let u=0;u"u")return!0;const n=t.prototype;return!(!XE(n)||!n.hasOwnProperty("isPrototypeOf"))}function XE(e){return Object.prototype.toString.call(e)==="[object Object]"}function OR(e){return new Promise(t=>{setTimeout(t,e)})}function ZE(e){OR(0).then(e)}function Iy(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?AR(e,t):t}function qI(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function QI(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var ua,Zi,Pl,l$,JI=(l$=class extends $d{constructor(){super();Te(this,ua,void 0);Te(this,Zi,void 0);Te(this,Pl,void 0);ye(this,Pl,t=>{if(!Ql&&window.addEventListener){const n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){z(this,Zi)||this.setEventListener(z(this,Pl))}onUnsubscribe(){var t;this.hasListeners()||((t=z(this,Zi))==null||t.call(this),ye(this,Zi,void 0))}setEventListener(t){var n;ye(this,Pl,t),(n=z(this,Zi))==null||n.call(this),ye(this,Zi,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){z(this,ua)!==t&&(ye(this,ua,t),this.onFocus())}onFocus(){this.listeners.forEach(t=>{t()})}isFocused(){var t;return typeof z(this,ua)=="boolean"?z(this,ua):((t=globalThis.document)==null?void 0:t.visibilityState)!=="hidden"}},ua=new WeakMap,Zi=new WeakMap,Pl=new WeakMap,l$),Rh=new JI,Al,qi,Ol,c$,eL=(c$=class extends $d{constructor(){super();Te(this,Al,!0);Te(this,qi,void 0);Te(this,Ol,void 0);ye(this,Ol,t=>{if(!Ql&&window.addEventListener){const n=()=>t(!0),r=()=>t(!1);return window.addEventListener("online",n,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",r)}}})}onSubscribe(){z(this,qi)||this.setEventListener(z(this,Ol))}onUnsubscribe(){var t;this.hasListeners()||((t=z(this,qi))==null||t.call(this),ye(this,qi,void 0))}setEventListener(t){var n;ye(this,Ol,t),(n=z(this,qi))==null||n.call(this),ye(this,qi,t(this.setOnline.bind(this)))}setOnline(t){z(this,Al)!==t&&(ye(this,Al,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return z(this,Al)}},Al=new WeakMap,qi=new WeakMap,Ol=new WeakMap,c$),Th=new eL;function tL(e){return Math.min(1e3*2**e,3e4)}function Cm(e){return(e??"online")==="online"?Th.isOnline():!0}var MR=class{constructor(e){this.revert=e==null?void 0:e.revert,this.silent=e==null?void 0:e.silent}};function a0(e){return e instanceof MR}function NR(e){let t=!1,n=0,r=!1,o,i,s;const l=new Promise((C,S)=>{i=C,s=S}),u=C=>{var S;r||(y(new MR(C)),(S=e.abort)==null||S.call(e))},d=()=>{t=!0},h=()=>{t=!1},m=()=>!Rh.isFocused()||e.networkMode!=="always"&&!Th.isOnline(),g=C=>{var S;r||(r=!0,(S=e.onSuccess)==null||S.call(e,C),o==null||o(),i(C))},y=C=>{var S;r||(r=!0,(S=e.onError)==null||S.call(e,C),o==null||o(),s(C))},x=()=>new Promise(C=>{var S;o=b=>{const E=r||!m();return E&&C(b),E},(S=e.onPause)==null||S.call(e)}).then(()=>{var C;o=void 0,r||(C=e.onContinue)==null||C.call(e)}),_=()=>{if(r)return;let C;try{C=e.fn()}catch(S){C=Promise.reject(S)}Promise.resolve(C).then(g).catch(S=>{var M;if(r)return;const b=e.retry??(Ql?0:3),E=e.retryDelay??tL,k=typeof E=="function"?E(n,S):E,P=b===!0||typeof b=="number"&&n{if(m())return x()}).then(()=>{t?y(S):_()})})};return Cm(e.networkMode)?_():x().then(_),{promise:l,cancel:u,continue:()=>(o==null?void 0:o())?l:Promise.resolve(),cancelRetry:d,continueRetry:h}}function nL(){let e=[],t=0,n=h=>{h()},r=h=>{h()};const o=h=>{let m;t++;try{m=h()}finally{t--,t||l()}return m},i=h=>{t?e.push(h):ZE(()=>{n(h)})},s=h=>(...m)=>{i(()=>{h(...m)})},l=()=>{const h=e;e=[],h.length&&ZE(()=>{r(()=>{h.forEach(m=>{n(m)})})})};return{batch:o,batchCalls:s,schedule:i,setNotifyFunction:h=>{n=h},setBatchNotifyFunction:h=>{r=h}}}var gn=nL(),da,u$,DR=(u$=class{constructor(){Te(this,da,void 0)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),My(this.gcTime)&&ye(this,da,setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Ql?1/0:5*60*1e3))}clearGcTimeout(){z(this,da)&&(clearTimeout(z(this,da)),ye(this,da,void 0))}},da=new WeakMap,u$),Ml,Nl,Nr,Qi,Dr,cn,ud,fa,Dl,Dp,ao,ii,d$,rL=(d$=class extends DR{constructor(t){super();Te(this,Dl);Te(this,ao);Te(this,Ml,void 0);Te(this,Nl,void 0);Te(this,Nr,void 0);Te(this,Qi,void 0);Te(this,Dr,void 0);Te(this,cn,void 0);Te(this,ud,void 0);Te(this,fa,void 0);ye(this,fa,!1),ye(this,ud,t.defaultOptions),tt(this,Dl,Dp).call(this,t.options),ye(this,cn,[]),ye(this,Nr,t.cache),this.queryKey=t.queryKey,this.queryHash=t.queryHash,ye(this,Ml,t.state||oL(this.options)),this.state=z(this,Ml),this.scheduleGc()}get meta(){return this.options.meta}optionalRemove(){!z(this,cn).length&&this.state.fetchStatus==="idle"&&z(this,Nr).remove(this)}setData(t,n){const r=Iy(this.state.data,t,this.options);return tt(this,ao,ii).call(this,{data:r,type:"success",dataUpdatedAt:n==null?void 0:n.updatedAt,manual:n==null?void 0:n.manual}),r}setState(t,n){tt(this,ao,ii).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){var r;const n=z(this,Qi);return(r=z(this,Dr))==null||r.cancel(t),n?n.then(Lr).catch(Lr):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(z(this,Ml))}isActive(){return z(this,cn).some(t=>t.options.enabled!==!1)}isDisabled(){return this.getObserversCount()>0&&!this.isActive()}isStale(){return this.state.isInvalidated||!this.state.dataUpdatedAt||z(this,cn).some(t=>t.getCurrentResult().isStale)}isStaleByTime(t=0){return this.state.isInvalidated||!this.state.dataUpdatedAt||!PR(this.state.dataUpdatedAt,t)}onFocus(){var n;const t=z(this,cn).find(r=>r.shouldFetchOnWindowFocus());t==null||t.refetch({cancelRefetch:!1}),(n=z(this,Dr))==null||n.continue()}onOnline(){var n;const t=z(this,cn).find(r=>r.shouldFetchOnReconnect());t==null||t.refetch({cancelRefetch:!1}),(n=z(this,Dr))==null||n.continue()}addObserver(t){z(this,cn).includes(t)||(z(this,cn).push(t),this.clearGcTimeout(),z(this,Nr).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){z(this,cn).includes(t)&&(ye(this,cn,z(this,cn).filter(n=>n!==t)),z(this,cn).length||(z(this,Dr)&&(z(this,fa)?z(this,Dr).cancel({revert:!0}):z(this,Dr).cancelRetry()),this.scheduleGc()),z(this,Nr).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return z(this,cn).length}invalidate(){this.state.isInvalidated||tt(this,ao,ii).call(this,{type:"invalidate"})}fetch(t,n){var d,h,m,g;if(this.state.fetchStatus!=="idle"){if(this.state.dataUpdatedAt&&(n!=null&&n.cancelRefetch))this.cancel({silent:!0});else if(z(this,Qi))return(d=z(this,Dr))==null||d.continueRetry(),z(this,Qi)}if(t&&tt(this,Dl,Dp).call(this,t),!this.options.queryFn){const y=z(this,cn).find(x=>x.options.queryFn);y&&tt(this,Dl,Dp).call(this,y.options)}const r=new AbortController,o={queryKey:this.queryKey,meta:this.meta},i=y=>{Object.defineProperty(y,"signal",{enumerable:!0,get:()=>(ye(this,fa,!0),r.signal)})};i(o);const s=()=>this.options.queryFn?(ye(this,fa,!1),this.options.persister?this.options.persister(this.options.queryFn,o,this):this.options.queryFn(o)):Promise.reject(new Error(`Missing queryFn: '${this.options.queryHash}'`)),l={fetchOptions:n,options:this.options,queryKey:this.queryKey,state:this.state,fetchFn:s};i(l),(h=this.options.behavior)==null||h.onFetch(l,this),ye(this,Nl,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((m=l.fetchOptions)==null?void 0:m.meta))&&tt(this,ao,ii).call(this,{type:"fetch",meta:(g=l.fetchOptions)==null?void 0:g.meta});const u=y=>{var x,_,C,S;a0(y)&&y.silent||tt(this,ao,ii).call(this,{type:"error",error:y}),a0(y)||((_=(x=z(this,Nr).config).onError)==null||_.call(x,y,this),(S=(C=z(this,Nr).config).onSettled)==null||S.call(C,this.state.data,y,this)),this.isFetchingOptimistic||this.scheduleGc(),this.isFetchingOptimistic=!1};return ye(this,Dr,NR({fn:l.fetchFn,abort:r.abort.bind(r),onSuccess:y=>{var x,_,C,S;if(typeof y>"u"){u(new Error(`${this.queryHash} data is undefined`));return}this.setData(y),(_=(x=z(this,Nr).config).onSuccess)==null||_.call(x,y,this),(S=(C=z(this,Nr).config).onSettled)==null||S.call(C,y,this.state.error,this),this.isFetchingOptimistic||this.scheduleGc(),this.isFetchingOptimistic=!1},onError:u,onFail:(y,x)=>{tt(this,ao,ii).call(this,{type:"failed",failureCount:y,error:x})},onPause:()=>{tt(this,ao,ii).call(this,{type:"pause"})},onContinue:()=>{tt(this,ao,ii).call(this,{type:"continue"})},retry:l.options.retry,retryDelay:l.options.retryDelay,networkMode:l.options.networkMode})),ye(this,Qi,z(this,Dr).promise),z(this,Qi)}},Ml=new WeakMap,Nl=new WeakMap,Nr=new WeakMap,Qi=new WeakMap,Dr=new WeakMap,cn=new WeakMap,ud=new WeakMap,fa=new WeakMap,Dl=new WeakSet,Dp=function(t){this.options={...z(this,ud),...t},this.updateGcTime(this.options.gcTime)},ao=new WeakSet,ii=function(t){const n=r=>{switch(t.type){case"failed":return{...r,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...r,fetchStatus:"paused"};case"continue":return{...r,fetchStatus:"fetching"};case"fetch":return{...r,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:t.meta??null,fetchStatus:Cm(this.options.networkMode)?"fetching":"paused",...!r.dataUpdatedAt&&{error:null,status:"pending"}};case"success":return{...r,data:t.data,dataUpdateCount:r.dataUpdateCount+1,dataUpdatedAt:t.dataUpdatedAt??Date.now(),error:null,isInvalidated:!1,status:"success",...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};case"error":const o=t.error;return a0(o)&&o.revert&&z(this,Nl)?{...z(this,Nl),fetchStatus:"idle"}:{...r,error:o,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:o,fetchStatus:"idle",status:"error"};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...t.state}}};this.state=n(this.state),gn.batch(()=>{z(this,cn).forEach(r=>{r.onQueryUpdate()}),z(this,Nr).notify({query:this,type:"updated",action:t})})},d$);function oL(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=typeof t<"u",r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var Ro,f$,iL=(f$=class extends $d{constructor(t={}){super();Te(this,Ro,void 0);this.config=t,ye(this,Ro,new Map)}build(t,n,r){const o=n.queryKey,i=n.queryHash??Gw(o,n);let s=this.get(i);return s||(s=new rL({cache:this,queryKey:o,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(o)}),this.add(s)),s}add(t){z(this,Ro).has(t.queryHash)||(z(this,Ro).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){const n=z(this,Ro).get(t.queryHash);n&&(t.destroy(),n===t&&z(this,Ro).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){gn.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return z(this,Ro).get(t)}getAll(){return[...z(this,Ro).values()]}find(t){const n={exact:!0,...t};return this.getAll().find(r=>KE(n,r))}findAll(t={}){const n=this.getAll();return Object.keys(t).length>0?n.filter(r=>KE(t,r)):n}notify(t){gn.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){gn.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){gn.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},Ro=new WeakMap,f$),To,dd,dr,Il,Po,Wi,p$,sL=(p$=class extends DR{constructor(t){super();Te(this,Po);Te(this,To,void 0);Te(this,dd,void 0);Te(this,dr,void 0);Te(this,Il,void 0);this.mutationId=t.mutationId,ye(this,dd,t.defaultOptions),ye(this,dr,t.mutationCache),ye(this,To,[]),this.state=t.state||aL(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options={...z(this,dd),...t},this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){z(this,To).includes(t)||(z(this,To).push(t),this.clearGcTimeout(),z(this,dr).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){ye(this,To,z(this,To).filter(n=>n!==t)),this.scheduleGc(),z(this,dr).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){z(this,To).length||(this.state.status==="pending"?this.scheduleGc():z(this,dr).remove(this))}continue(){var t;return((t=z(this,Il))==null?void 0:t.continue())??this.execute(this.state.variables)}async execute(t){var o,i,s,l,u,d,h,m,g,y,x,_,C,S,b,E,k,P,M,A;const n=()=>(ye(this,Il,NR({fn:()=>this.options.mutationFn?this.options.mutationFn(t):Promise.reject(new Error("No mutationFn found")),onFail:(O,F)=>{tt(this,Po,Wi).call(this,{type:"failed",failureCount:O,error:F})},onPause:()=>{tt(this,Po,Wi).call(this,{type:"pause"})},onContinue:()=>{tt(this,Po,Wi).call(this,{type:"continue"})},retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode})),z(this,Il).promise),r=this.state.status==="pending";try{if(!r){tt(this,Po,Wi).call(this,{type:"pending",variables:t}),await((i=(o=z(this,dr).config).onMutate)==null?void 0:i.call(o,t,this));const F=await((l=(s=this.options).onMutate)==null?void 0:l.call(s,t));F!==this.state.context&&tt(this,Po,Wi).call(this,{type:"pending",context:F,variables:t})}const O=await n();return await((d=(u=z(this,dr).config).onSuccess)==null?void 0:d.call(u,O,t,this.state.context,this)),await((m=(h=this.options).onSuccess)==null?void 0:m.call(h,O,t,this.state.context)),await((y=(g=z(this,dr).config).onSettled)==null?void 0:y.call(g,O,null,this.state.variables,this.state.context,this)),await((_=(x=this.options).onSettled)==null?void 0:_.call(x,O,null,t,this.state.context)),tt(this,Po,Wi).call(this,{type:"success",data:O}),O}catch(O){try{throw await((S=(C=z(this,dr).config).onError)==null?void 0:S.call(C,O,t,this.state.context,this)),await((E=(b=this.options).onError)==null?void 0:E.call(b,O,t,this.state.context)),await((P=(k=z(this,dr).config).onSettled)==null?void 0:P.call(k,void 0,O,this.state.variables,this.state.context,this)),await((A=(M=this.options).onSettled)==null?void 0:A.call(M,void 0,O,t,this.state.context)),O}finally{tt(this,Po,Wi).call(this,{type:"error",error:O})}}}},To=new WeakMap,dd=new WeakMap,dr=new WeakMap,Il=new WeakMap,Po=new WeakSet,Wi=function(t){const n=r=>{switch(t.type){case"failed":return{...r,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};case"pending":return{...r,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:!Cm(this.options.networkMode),status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...r,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:t.error,failureCount:r.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}};this.state=n(this.state),gn.batch(()=>{z(this,To).forEach(r=>{r.onMutationUpdate(t)}),z(this,dr).notify({mutation:this,type:"updated",action:t})})},p$);function aL(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Ir,fd,pa,h$,lL=(h$=class extends $d{constructor(t={}){super();Te(this,Ir,void 0);Te(this,fd,void 0);Te(this,pa,void 0);this.config=t,ye(this,Ir,[]),ye(this,fd,0)}build(t,n,r){const o=new sL({mutationCache:this,mutationId:++Ff(this,fd)._,options:t.defaultMutationOptions(n),state:r});return this.add(o),o}add(t){z(this,Ir).push(t),this.notify({type:"added",mutation:t})}remove(t){ye(this,Ir,z(this,Ir).filter(n=>n!==t)),this.notify({type:"removed",mutation:t})}clear(){gn.batch(()=>{z(this,Ir).forEach(t=>{this.remove(t)})})}getAll(){return z(this,Ir)}find(t){const n={exact:!0,...t};return z(this,Ir).find(r=>YE(n,r))}findAll(t={}){return z(this,Ir).filter(n=>YE(t,n))}notify(t){gn.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){return ye(this,pa,(z(this,pa)??Promise.resolve()).then(()=>{const t=z(this,Ir).filter(n=>n.state.isPaused);return gn.batch(()=>t.reduce((n,r)=>n.then(()=>r.continue().catch(Lr)),Promise.resolve()))}).then(()=>{ye(this,pa,void 0)})),z(this,pa)}},Ir=new WeakMap,fd=new WeakMap,pa=new WeakMap,h$);function cL(e){return{onFetch:(t,n)=>{const r=async()=>{var x,_,C,S,b;const o=t.options,i=(C=(_=(x=t.fetchOptions)==null?void 0:x.meta)==null?void 0:_.fetchMore)==null?void 0:C.direction,s=((S=t.state.data)==null?void 0:S.pages)||[],l=((b=t.state.data)==null?void 0:b.pageParams)||[],u={pages:[],pageParams:[]};let d=!1;const h=E=>{Object.defineProperty(E,"signal",{enumerable:!0,get:()=>(t.signal.aborted?d=!0:t.signal.addEventListener("abort",()=>{d=!0}),t.signal)})},m=t.options.queryFn||(()=>Promise.reject(new Error(`Missing queryFn: '${t.options.queryHash}'`))),g=async(E,k,P)=>{if(d)return Promise.reject();if(k==null&&E.pages.length)return Promise.resolve(E);const M={queryKey:t.queryKey,pageParam:k,direction:P?"backward":"forward",meta:t.options.meta};h(M);const A=await m(M),{maxPages:O}=t.options,F=P?QI:qI;return{pages:F(E.pages,A,O),pageParams:F(E.pageParams,k,O)}};let y;if(i&&s.length){const E=i==="backward",k=E?uL:qE,P={pages:s,pageParams:l},M=k(o,P);y=await g(P,M,E)}else{y=await g(u,l[0]??o.initialPageParam);const E=e??s.length;for(let k=1;k{var o,i;return(i=(o=t.options).persister)==null?void 0:i.call(o,r,{queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n)}:t.fetchFn=r}}}function qE(e,{pages:t,pageParams:n}){const r=t.length-1;return e.getNextPageParam(t[r],t,n[r],n)}function uL(e,{pages:t,pageParams:n}){var r;return(r=e.getPreviousPageParam)==null?void 0:r.call(e,t[0],t,n[0],n)}var nn,Ji,es,Ll,Fl,ts,jl,zl,m$,dL=(m$=class{constructor(e={}){Te(this,nn,void 0);Te(this,Ji,void 0);Te(this,es,void 0);Te(this,Ll,void 0);Te(this,Fl,void 0);Te(this,ts,void 0);Te(this,jl,void 0);Te(this,zl,void 0);ye(this,nn,e.queryCache||new iL),ye(this,Ji,e.mutationCache||new lL),ye(this,es,e.defaultOptions||{}),ye(this,Ll,new Map),ye(this,Fl,new Map),ye(this,ts,0)}mount(){Ff(this,ts)._++,z(this,ts)===1&&(ye(this,jl,Rh.subscribe(()=>{Rh.isFocused()&&(this.resumePausedMutations(),z(this,nn).onFocus())})),ye(this,zl,Th.subscribe(()=>{Th.isOnline()&&(this.resumePausedMutations(),z(this,nn).onOnline())})))}unmount(){var e,t;Ff(this,ts)._--,z(this,ts)===0&&((e=z(this,jl))==null||e.call(this),ye(this,jl,void 0),(t=z(this,zl))==null||t.call(this),ye(this,zl,void 0))}isFetching(e){return z(this,nn).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return z(this,Ji).findAll({...e,status:"pending"}).length}getQueryData(e){var t;return(t=z(this,nn).find({queryKey:e}))==null?void 0:t.state.data}ensureQueryData(e){const t=this.getQueryData(e.queryKey);return t!==void 0?Promise.resolve(t):this.fetchQuery(e)}getQueriesData(e){return this.getQueryCache().findAll(e).map(({queryKey:t,state:n})=>{const r=n.data;return[t,r]})}setQueryData(e,t,n){const r=z(this,nn).find({queryKey:e}),o=r==null?void 0:r.state.data,i=ZI(t,o);if(typeof i>"u")return;const s=this.defaultQueryOptions({queryKey:e});return z(this,nn).build(this,s).setData(i,{...n,manual:!0})}setQueriesData(e,t,n){return gn.batch(()=>this.getQueryCache().findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){var t;return(t=z(this,nn).find({queryKey:e}))==null?void 0:t.state}removeQueries(e){const t=z(this,nn);gn.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=z(this,nn),r={type:"active",...e};return gn.batch(()=>(n.findAll(e).forEach(o=>{o.reset()}),this.refetchQueries(r,t)))}cancelQueries(e={},t={}){const n={revert:!0,...t},r=gn.batch(()=>z(this,nn).findAll(e).map(o=>o.cancel(n)));return Promise.all(r).then(Lr).catch(Lr)}invalidateQueries(e={},t={}){return gn.batch(()=>{if(z(this,nn).findAll(e).forEach(r=>{r.invalidate()}),e.refetchType==="none")return Promise.resolve();const n={...e,type:e.refetchType??e.type??"active"};return this.refetchQueries(n,t)})}refetchQueries(e={},t){const n={...t,cancelRefetch:(t==null?void 0:t.cancelRefetch)??!0},r=gn.batch(()=>z(this,nn).findAll(e).filter(o=>!o.isDisabled()).map(o=>{let i=o.fetch(void 0,n);return n.throwOnError||(i=i.catch(Lr)),o.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(Lr)}fetchQuery(e){const t=this.defaultQueryOptions(e);typeof t.retry>"u"&&(t.retry=!1);const n=z(this,nn).build(this,t);return n.isStaleByTime(t.staleTime)?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Lr).catch(Lr)}fetchInfiniteQuery(e){return e.behavior=cL(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Lr).catch(Lr)}resumePausedMutations(){return z(this,Ji).resumePausedMutations()}getQueryCache(){return z(this,nn)}getMutationCache(){return z(this,Ji)}getDefaultOptions(){return z(this,es)}setDefaultOptions(e){ye(this,es,e)}setQueryDefaults(e,t){z(this,Ll).set(Gu(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...z(this,Ll).values()];let n={};return t.forEach(r=>{Xu(e,r.queryKey)&&(n={...n,...r.defaultOptions})}),n}setMutationDefaults(e,t){z(this,Fl).set(Gu(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...z(this,Fl).values()];let n={};return t.forEach(r=>{Xu(e,r.mutationKey)&&(n={...n,...r.defaultOptions})}),n}defaultQueryOptions(e){if(e!=null&&e._defaulted)return e;const t={...z(this,es).queries,...(e==null?void 0:e.queryKey)&&this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Gw(t.queryKey,t)),typeof t.refetchOnReconnect>"u"&&(t.refetchOnReconnect=t.networkMode!=="always"),typeof t.throwOnError>"u"&&(t.throwOnError=!!t.suspense),typeof t.networkMode>"u"&&t.persister&&(t.networkMode="offlineFirst"),t}defaultMutationOptions(e){return e!=null&&e._defaulted?e:{...z(this,es).mutations,...(e==null?void 0:e.mutationKey)&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){z(this,nn).clear(),z(this,Ji).clear()}},nn=new WeakMap,Ji=new WeakMap,es=new WeakMap,Ll=new WeakMap,Fl=new WeakMap,ts=new WeakMap,jl=new WeakMap,zl=new WeakMap,m$),Xn,Ct,Bl,kn,ha,Ul,Ao,pd,Vl,Wl,ma,ga,ns,va,ya,hu,hd,Ly,md,Fy,gd,jy,vd,zy,yd,By,wd,Uy,xd,Vy,am,IR,g$,fL=(g$=class extends $d{constructor(t,n){super();Te(this,ya);Te(this,hd);Te(this,md);Te(this,gd);Te(this,vd);Te(this,yd);Te(this,wd);Te(this,xd);Te(this,am);Te(this,Xn,void 0);Te(this,Ct,void 0);Te(this,Bl,void 0);Te(this,kn,void 0);Te(this,ha,void 0);Te(this,Ul,void 0);Te(this,Ao,void 0);Te(this,pd,void 0);Te(this,Vl,void 0);Te(this,Wl,void 0);Te(this,ma,void 0);Te(this,ga,void 0);Te(this,ns,void 0);Te(this,va,void 0);ye(this,Ct,void 0),ye(this,Bl,void 0),ye(this,kn,void 0),ye(this,va,new Set),ye(this,Xn,t),this.options=n,ye(this,Ao,null),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(z(this,Ct).addObserver(this),QE(z(this,Ct),this.options)?tt(this,ya,hu).call(this):this.updateResult(),tt(this,vd,zy).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Wy(z(this,Ct),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Wy(z(this,Ct),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,tt(this,yd,By).call(this),tt(this,wd,Uy).call(this),z(this,Ct).removeObserver(this)}setOptions(t,n){const r=this.options,o=z(this,Ct);if(this.options=z(this,Xn).defaultQueryOptions(t),Ny(r,this.options)||z(this,Xn).getQueryCache().notify({type:"observerOptionsUpdated",query:z(this,Ct),observer:this}),typeof this.options.enabled<"u"&&typeof this.options.enabled!="boolean")throw new Error("Expected enabled to be a boolean");this.options.queryKey||(this.options.queryKey=r.queryKey),tt(this,xd,Vy).call(this);const i=this.hasListeners();i&&JE(z(this,Ct),o,this.options,r)&&tt(this,ya,hu).call(this),this.updateResult(n),i&&(z(this,Ct)!==o||this.options.enabled!==r.enabled||this.options.staleTime!==r.staleTime)&&tt(this,hd,Ly).call(this);const s=tt(this,md,Fy).call(this);i&&(z(this,Ct)!==o||this.options.enabled!==r.enabled||s!==z(this,ns))&&tt(this,gd,jy).call(this,s)}getOptimisticResult(t){const n=z(this,Xn).getQueryCache().build(z(this,Xn),t),r=this.createResult(n,t);return hL(this,r)&&(ye(this,kn,r),ye(this,Ul,this.options),ye(this,ha,z(this,Ct).state)),r}getCurrentResult(){return z(this,kn)}trackResult(t){const n={};return Object.keys(t).forEach(r=>{Object.defineProperty(n,r,{configurable:!1,enumerable:!0,get:()=>(z(this,va).add(r),t[r])})}),n}getCurrentQuery(){return z(this,Ct)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){const n=z(this,Xn).defaultQueryOptions(t),r=z(this,Xn).getQueryCache().build(z(this,Xn),n);return r.isFetchingOptimistic=!0,r.fetch().then(()=>this.createResult(r,n))}fetch(t){return tt(this,ya,hu).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),z(this,kn)))}createResult(t,n){var M;const r=z(this,Ct),o=this.options,i=z(this,kn),s=z(this,ha),l=z(this,Ul),d=t!==r?t.state:z(this,Bl),{state:h}=t;let{error:m,errorUpdatedAt:g,fetchStatus:y,status:x}=h,_=!1,C;if(n._optimisticResults){const A=this.hasListeners(),O=!A&&QE(t,n),F=A&&JE(t,r,n,o);(O||F)&&(y=Cm(t.options.networkMode)?"fetching":"paused",h.dataUpdatedAt||(x="pending")),n._optimisticResults==="isRestoring"&&(y="idle")}if(n.select&&typeof h.data<"u")if(i&&h.data===(s==null?void 0:s.data)&&n.select===z(this,pd))C=z(this,Vl);else try{ye(this,pd,n.select),C=n.select(h.data),C=Iy(i==null?void 0:i.data,C,n),ye(this,Vl,C),ye(this,Ao,null)}catch(A){ye(this,Ao,A)}else C=h.data;if(typeof n.placeholderData<"u"&&typeof C>"u"&&x==="pending"){let A;if(i!=null&&i.isPlaceholderData&&n.placeholderData===(l==null?void 0:l.placeholderData))A=i.data;else if(A=typeof n.placeholderData=="function"?n.placeholderData((M=z(this,Wl))==null?void 0:M.state.data,z(this,Wl)):n.placeholderData,n.select&&typeof A<"u")try{A=n.select(A),ye(this,Ao,null)}catch(O){ye(this,Ao,O)}typeof A<"u"&&(x="success",C=Iy(i==null?void 0:i.data,A,n),_=!0)}z(this,Ao)&&(m=z(this,Ao),C=z(this,Vl),g=Date.now(),x="error");const S=y==="fetching",b=x==="pending",E=x==="error",k=b&&S;return{status:x,fetchStatus:y,isPending:b,isSuccess:x==="success",isError:E,isInitialLoading:k,isLoading:k,data:C,dataUpdatedAt:h.dataUpdatedAt,error:m,errorUpdatedAt:g,failureCount:h.fetchFailureCount,failureReason:h.fetchFailureReason,errorUpdateCount:h.errorUpdateCount,isFetched:h.dataUpdateCount>0||h.errorUpdateCount>0,isFetchedAfterMount:h.dataUpdateCount>d.dataUpdateCount||h.errorUpdateCount>d.errorUpdateCount,isFetching:S,isRefetching:S&&!b,isLoadingError:E&&h.dataUpdatedAt===0,isPaused:y==="paused",isPlaceholderData:_,isRefetchError:E&&h.dataUpdatedAt!==0,isStale:Xw(t,n),refetch:this.refetch}}updateResult(t){const n=z(this,kn),r=this.createResult(z(this,Ct),this.options);if(ye(this,ha,z(this,Ct).state),ye(this,Ul,this.options),z(this,ha).data!==void 0&&ye(this,Wl,z(this,Ct)),Ny(r,n))return;ye(this,kn,r);const o={},i=()=>{if(!n)return!0;const{notifyOnChangeProps:s}=this.options,l=typeof s=="function"?s():s;if(l==="all"||!l&&!z(this,va).size)return!0;const u=new Set(l??z(this,va));return this.options.throwOnError&&u.add("error"),Object.keys(z(this,kn)).some(d=>{const h=d;return z(this,kn)[h]!==n[h]&&u.has(h)})};(t==null?void 0:t.listeners)!==!1&&i()&&(o.listeners=!0),tt(this,am,IR).call(this,{...o,...t})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&tt(this,vd,zy).call(this)}},Xn=new WeakMap,Ct=new WeakMap,Bl=new WeakMap,kn=new WeakMap,ha=new WeakMap,Ul=new WeakMap,Ao=new WeakMap,pd=new WeakMap,Vl=new WeakMap,Wl=new WeakMap,ma=new WeakMap,ga=new WeakMap,ns=new WeakMap,va=new WeakMap,ya=new WeakSet,hu=function(t){tt(this,xd,Vy).call(this);let n=z(this,Ct).fetch(this.options,t);return t!=null&&t.throwOnError||(n=n.catch(Lr)),n},hd=new WeakSet,Ly=function(){if(tt(this,yd,By).call(this),Ql||z(this,kn).isStale||!My(this.options.staleTime))return;const n=PR(z(this,kn).dataUpdatedAt,this.options.staleTime)+1;ye(this,ma,setTimeout(()=>{z(this,kn).isStale||this.updateResult()},n))},md=new WeakSet,Fy=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(z(this,Ct)):this.options.refetchInterval)??!1},gd=new WeakSet,jy=function(t){tt(this,wd,Uy).call(this),ye(this,ns,t),!(Ql||this.options.enabled===!1||!My(z(this,ns))||z(this,ns)===0)&&ye(this,ga,setInterval(()=>{(this.options.refetchIntervalInBackground||Rh.isFocused())&&tt(this,ya,hu).call(this)},z(this,ns)))},vd=new WeakSet,zy=function(){tt(this,hd,Ly).call(this),tt(this,gd,jy).call(this,tt(this,md,Fy).call(this))},yd=new WeakSet,By=function(){z(this,ma)&&(clearTimeout(z(this,ma)),ye(this,ma,void 0))},wd=new WeakSet,Uy=function(){z(this,ga)&&(clearInterval(z(this,ga)),ye(this,ga,void 0))},xd=new WeakSet,Vy=function(){const t=z(this,Xn).getQueryCache().build(z(this,Xn),this.options);if(t===z(this,Ct))return;const n=z(this,Ct);ye(this,Ct,t),ye(this,Bl,t.state),this.hasListeners()&&(n==null||n.removeObserver(this),t.addObserver(this))},am=new WeakSet,IR=function(t){gn.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(z(this,kn))}),z(this,Xn).getQueryCache().notify({query:z(this,Ct),type:"observerResultsUpdated"})})},g$);function pL(e,t){return t.enabled!==!1&&!e.state.dataUpdatedAt&&!(e.state.status==="error"&&t.retryOnMount===!1)}function QE(e,t){return pL(e,t)||e.state.dataUpdatedAt>0&&Wy(e,t,t.refetchOnMount)}function Wy(e,t,n){if(t.enabled!==!1){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&Xw(e,t)}return!1}function JE(e,t,n,r){return n.enabled!==!1&&(e!==t||r.enabled===!1)&&(!n.suspense||e.state.status!=="error")&&Xw(e,n)}function Xw(e,t){return e.isStaleByTime(t.staleTime)}function hL(e,t){return!Ny(e.getCurrentResult(),t)}var LR=f.createContext(void 0),mL=e=>{const t=f.useContext(LR);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},gL=({client:e,children:t})=>(f.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),f.createElement(LR.Provider,{value:e},t)),FR=f.createContext(!1),vL=()=>f.useContext(FR);FR.Provider;function yL(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var wL=f.createContext(yL()),xL=()=>f.useContext(wL);function bL(e,t){return typeof e=="function"?e(...t):!!e}var _L=(e,t)=>{(e.suspense||e.throwOnError)&&(t.isReset()||(e.retryOnMount=!1))},SL=e=>{f.useEffect(()=>{e.clearReset()},[e])},EL=({result:e,errorResetBoundary:t,throwOnError:n,query:r})=>e.isError&&!t.isReset()&&!e.isFetching&&bL(n,[e.error,r]),CL=e=>{e.suspense&&typeof e.staleTime!="number"&&(e.staleTime=1e3)},$L=(e,t)=>(e==null?void 0:e.suspense)&&t.isPending,kL=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function RL(e,t,n){const r=mL(n),o=vL(),i=xL(),s=r.defaultQueryOptions(e);s._optimisticResults=o?"isRestoring":"optimistic",CL(s),_L(s,i),SL(i);const[l]=f.useState(()=>new t(r,s)),u=l.getOptimisticResult(s);if(f.useSyncExternalStore(f.useCallback(d=>{const h=o?()=>{}:l.subscribe(gn.batchCalls(d));return l.updateResult(),h},[l,o]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),f.useEffect(()=>{l.setOptions(s,{listeners:!1})},[s,l]),$L(s,u))throw l.setOptions(s,{listeners:!1}),kL(s,l,i);if(EL({result:u,errorResetBoundary:i,throwOnError:s.throwOnError,query:l.getCurrentQuery()}))throw u.error;return s.notifyOnChangeProps?u:l.trackResult(u)}function TL(e,t){return RL(e,fL,t)}var jR=(e=>(e.RemoveBG="RemoveBG",e.AnimeSeg="AnimeSeg",e.RealESRGAN="RealESRGAN",e.GFPGAN="GFPGAN",e.RestoreFormer="RestoreFormer",e.InteractiveSeg="InteractiveSeg",e))(jR||{}),xs=(e=>(e.NAME="name",e.CTIME="ctime",e.MTIME="mtime",e))(xs||{}),$u=(e=>(e.DESCENDING="desc",e.ASCENDING="asc",e))($u||{}),Zw=(e=>(e.ddim="ddim",e.plms="plms",e))(Zw||{}),qw=(e=>(e.INPAINT_NS="INPAINT_NS",e.INPAINT_TELEA="INPAINT_TELEA",e))(qw||{}),In=(e=>(e.x="x",e.y="y",e.xy="xy",e))(In||{}),kl=(e=>(e.text_guided="text-guided",e.shape_guided="shape-guided",e.object_remove="object-remove",e.outpainting="outpainting",e))(kl||{});function zR(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;tl(i)))==null?void 0:s.classGroupId}const eC=/^\[(.+)\]$/;function AL(e){if(eC.test(e)){const t=eC.exec(e)[1],n=t==null?void 0:t.substring(0,t.indexOf(":"));if(n)return"arbitrary.."+n}}function OL(e){const{theme:t,prefix:n}=e,r={nextPart:new Map,validators:[]};return NL(Object.entries(e.classGroups),n).forEach(([i,s])=>{Hy(s,r,i,t)}),r}function Hy(e,t,n,r){e.forEach(o=>{if(typeof o=="string"){const i=o===""?t:tC(t,o);i.classGroupId=n;return}if(typeof o=="function"){if(ML(o)){Hy(o(r),t,n,r);return}t.validators.push({validator:o,classGroupId:n});return}Object.entries(o).forEach(([i,s])=>{Hy(s,tC(t,i),n,r)})})}function tC(e,t){let n=e;return t.split(Qw).forEach(r=>{n.nextPart.has(r)||n.nextPart.set(r,{nextPart:new Map,validators:[]}),n=n.nextPart.get(r)}),n}function ML(e){return e.isThemeGetter}function NL(e,t){return t?e.map(([n,r])=>{const o=r.map(i=>typeof i=="string"?t+i:typeof i=="object"?Object.fromEntries(Object.entries(i).map(([s,l])=>[t+s,l])):i);return[n,o]}):e}function DL(e){if(e<1)return{get:()=>{},set:()=>{}};let t=0,n=new Map,r=new Map;function o(i,s){n.set(i,s),t++,t>e&&(t=0,r=n,n=new Map)}return{get(i){let s=n.get(i);if(s!==void 0)return s;if((s=r.get(i))!==void 0)return o(i,s),s},set(i,s){n.has(i)?n.set(i,s):o(i,s)}}}const VR="!";function IL(e){const t=e.separator,n=t.length===1,r=t[0],o=t.length;return function(s){const l=[];let u=0,d=0,h;for(let _=0;_d?h-d:void 0;return{modifiers:l,hasImportantModifier:g,baseClassName:y,maybePostfixModifierPosition:x}}}function LL(e){if(e.length<=1)return e;const t=[];let n=[];return e.forEach(r=>{r[0]==="["?(t.push(...n.sort(),r),n=[]):n.push(r)}),t.push(...n.sort()),t}function FL(e){return{cache:DL(e.cacheSize),splitModifiers:IL(e),...PL(e)}}const jL=/\s+/;function zL(e,t){const{splitModifiers:n,getClassGroupId:r,getConflictingClassGroupIds:o}=t,i=new Set;return e.trim().split(jL).map(s=>{const{modifiers:l,hasImportantModifier:u,baseClassName:d,maybePostfixModifierPosition:h}=n(s);let m=r(h?d.substring(0,h):d),g=!!h;if(!m){if(!h)return{isTailwindClass:!1,originalClassName:s};if(m=r(d),!m)return{isTailwindClass:!1,originalClassName:s};g=!1}const y=LL(l).join(":");return{isTailwindClass:!0,modifierId:u?y+VR:y,classGroupId:m,originalClassName:s,hasPostfixModifier:g}}).reverse().filter(s=>{if(!s.isTailwindClass)return!0;const{modifierId:l,classGroupId:u,hasPostfixModifier:d}=s,h=l+u;return i.has(h)?!1:(i.add(h),o(u,d).forEach(m=>i.add(l+m)),!0)}).reverse().map(s=>s.originalClassName).join(" ")}function BL(){let e=0,t,n,r="";for(;em(h),e());return n=FL(d),r=n.cache.get,o=n.cache.set,i=l,l(u)}function l(u){const d=r(u);if(d)return d;const h=zL(u,n);return o(u,h),h}return function(){return i(BL.apply(null,arguments))}}function Rt(e){const t=n=>n[e]||[];return t.isThemeGetter=!0,t}const HR=/^\[(?:([a-z-]+):)?(.+)\]$/i,VL=/^\d+\/\d+$/,WL=new Set(["px","full","screen"]),HL=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,KL=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,YL=/^-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,GL=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/;function oo(e){return ia(e)||WL.has(e)||VL.test(e)}function zi(e){return mc(e,"length",nF)}function ia(e){return!!e&&!Number.isNaN(Number(e))}function np(e){return mc(e,"number",ia)}function nu(e){return!!e&&Number.isInteger(Number(e))}function XL(e){return e.endsWith("%")&&ia(e.slice(0,-1))}function Je(e){return HR.test(e)}function Bi(e){return HL.test(e)}const ZL=new Set(["length","size","percentage"]);function qL(e){return mc(e,ZL,KR)}function QL(e){return mc(e,"position",KR)}const JL=new Set(["image","url"]);function eF(e){return mc(e,JL,oF)}function tF(e){return mc(e,"",rF)}function ru(){return!0}function mc(e,t,n){const r=HR.exec(e);return r?r[1]?typeof t=="string"?r[1]===t:t.has(r[1]):n(r[2]):!1}function nF(e){return KL.test(e)}function KR(){return!1}function rF(e){return YL.test(e)}function oF(e){return GL.test(e)}function iF(){const e=Rt("colors"),t=Rt("spacing"),n=Rt("blur"),r=Rt("brightness"),o=Rt("borderColor"),i=Rt("borderRadius"),s=Rt("borderSpacing"),l=Rt("borderWidth"),u=Rt("contrast"),d=Rt("grayscale"),h=Rt("hueRotate"),m=Rt("invert"),g=Rt("gap"),y=Rt("gradientColorStops"),x=Rt("gradientColorStopPositions"),_=Rt("inset"),C=Rt("margin"),S=Rt("opacity"),b=Rt("padding"),E=Rt("saturate"),k=Rt("scale"),P=Rt("sepia"),M=Rt("skew"),A=Rt("space"),O=Rt("translate"),F=()=>["auto","contain","none"],V=()=>["auto","hidden","clip","visible","scroll"],J=()=>["auto",Je,t],G=()=>[Je,t],ae=()=>["",oo,zi],U=()=>["auto",ia,Je],te=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],L=()=>["solid","dashed","dotted","double","none"],ie=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity","plus-lighter"],K=()=>["start","end","center","between","around","evenly","stretch"],Q=()=>["","0",Je],W=()=>["auto","avoid","all","avoid-page","page","left","right","column"],le=()=>[ia,np],ge=()=>[ia,Je];return{cacheSize:500,separator:":",theme:{colors:[ru],spacing:[oo,zi],blur:["none","",Bi,Je],brightness:le(),borderColor:[e],borderRadius:["none","","full",Bi,Je],borderSpacing:G(),borderWidth:ae(),contrast:le(),grayscale:Q(),hueRotate:ge(),invert:Q(),gap:G(),gradientColorStops:[e],gradientColorStopPositions:[XL,zi],inset:J(),margin:J(),opacity:le(),padding:G(),saturate:le(),scale:le(),sepia:Q(),skew:ge(),space:G(),translate:G()},classGroups:{aspect:[{aspect:["auto","square","video",Je]}],container:["container"],columns:[{columns:[Bi]}],"break-after":[{"break-after":W()}],"break-before":[{"break-before":W()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],float:[{float:["right","left","none"]}],clear:[{clear:["left","right","both","none"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:[...te(),Je]}],overflow:[{overflow:V()}],"overflow-x":[{"overflow-x":V()}],"overflow-y":[{"overflow-y":V()}],overscroll:[{overscroll:F()}],"overscroll-x":[{"overscroll-x":F()}],"overscroll-y":[{"overscroll-y":F()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[_]}],"inset-x":[{"inset-x":[_]}],"inset-y":[{"inset-y":[_]}],start:[{start:[_]}],end:[{end:[_]}],top:[{top:[_]}],right:[{right:[_]}],bottom:[{bottom:[_]}],left:[{left:[_]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",nu,Je]}],basis:[{basis:J()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",Je]}],grow:[{grow:Q()}],shrink:[{shrink:Q()}],order:[{order:["first","last","none",nu,Je]}],"grid-cols":[{"grid-cols":[ru]}],"col-start-end":[{col:["auto",{span:["full",nu,Je]},Je]}],"col-start":[{"col-start":U()}],"col-end":[{"col-end":U()}],"grid-rows":[{"grid-rows":[ru]}],"row-start-end":[{row:["auto",{span:[nu,Je]},Je]}],"row-start":[{"row-start":U()}],"row-end":[{"row-end":U()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",Je]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",Je]}],gap:[{gap:[g]}],"gap-x":[{"gap-x":[g]}],"gap-y":[{"gap-y":[g]}],"justify-content":[{justify:["normal",...K()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...K(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...K(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[b]}],px:[{px:[b]}],py:[{py:[b]}],ps:[{ps:[b]}],pe:[{pe:[b]}],pt:[{pt:[b]}],pr:[{pr:[b]}],pb:[{pb:[b]}],pl:[{pl:[b]}],m:[{m:[C]}],mx:[{mx:[C]}],my:[{my:[C]}],ms:[{ms:[C]}],me:[{me:[C]}],mt:[{mt:[C]}],mr:[{mr:[C]}],mb:[{mb:[C]}],ml:[{ml:[C]}],"space-x":[{"space-x":[A]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[A]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit",Je,t]}],"min-w":[{"min-w":["min","max","fit",Je,oo]}],"max-w":[{"max-w":["0","none","full","min","max","fit","prose",{screen:[Bi]},Bi,Je]}],h:[{h:[Je,t,"auto","min","max","fit"]}],"min-h":[{"min-h":["min","max","fit",oo,Je]}],"max-h":[{"max-h":[Je,t,"min","max","fit"]}],"font-size":[{text:["base",Bi,zi]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",np]}],"font-family":[{font:[ru]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractons"],tracking:[{tracking:["tighter","tight","normal","wide","wider","widest",Je]}],"line-clamp":[{"line-clamp":["none",ia,np]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",oo,Je]}],"list-image":[{"list-image":["none",Je]}],"list-style-type":[{list:["none","disc","decimal",Je]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[e]}],"placeholder-opacity":[{"placeholder-opacity":[S]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[e]}],"text-opacity":[{"text-opacity":[S]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...L(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",oo,zi]}],"underline-offset":[{"underline-offset":["auto",oo,Je]}],"text-decoration-color":[{decoration:[e]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],indent:[{indent:G()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Je]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",Je]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[S]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...te(),QL]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",qL]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},eF]}],"bg-color":[{bg:[e]}],"gradient-from-pos":[{from:[x]}],"gradient-via-pos":[{via:[x]}],"gradient-to-pos":[{to:[x]}],"gradient-from":[{from:[y]}],"gradient-via":[{via:[y]}],"gradient-to":[{to:[y]}],rounded:[{rounded:[i]}],"rounded-s":[{"rounded-s":[i]}],"rounded-e":[{"rounded-e":[i]}],"rounded-t":[{"rounded-t":[i]}],"rounded-r":[{"rounded-r":[i]}],"rounded-b":[{"rounded-b":[i]}],"rounded-l":[{"rounded-l":[i]}],"rounded-ss":[{"rounded-ss":[i]}],"rounded-se":[{"rounded-se":[i]}],"rounded-ee":[{"rounded-ee":[i]}],"rounded-es":[{"rounded-es":[i]}],"rounded-tl":[{"rounded-tl":[i]}],"rounded-tr":[{"rounded-tr":[i]}],"rounded-br":[{"rounded-br":[i]}],"rounded-bl":[{"rounded-bl":[i]}],"border-w":[{border:[l]}],"border-w-x":[{"border-x":[l]}],"border-w-y":[{"border-y":[l]}],"border-w-s":[{"border-s":[l]}],"border-w-e":[{"border-e":[l]}],"border-w-t":[{"border-t":[l]}],"border-w-r":[{"border-r":[l]}],"border-w-b":[{"border-b":[l]}],"border-w-l":[{"border-l":[l]}],"border-opacity":[{"border-opacity":[S]}],"border-style":[{border:[...L(),"hidden"]}],"divide-x":[{"divide-x":[l]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[l]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[S]}],"divide-style":[{divide:L()}],"border-color":[{border:[o]}],"border-color-x":[{"border-x":[o]}],"border-color-y":[{"border-y":[o]}],"border-color-t":[{"border-t":[o]}],"border-color-r":[{"border-r":[o]}],"border-color-b":[{"border-b":[o]}],"border-color-l":[{"border-l":[o]}],"divide-color":[{divide:[o]}],"outline-style":[{outline:["",...L()]}],"outline-offset":[{"outline-offset":[oo,Je]}],"outline-w":[{outline:[oo,zi]}],"outline-color":[{outline:[e]}],"ring-w":[{ring:ae()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[e]}],"ring-opacity":[{"ring-opacity":[S]}],"ring-offset-w":[{"ring-offset":[oo,zi]}],"ring-offset-color":[{"ring-offset":[e]}],shadow:[{shadow:["","inner","none",Bi,tF]}],"shadow-color":[{shadow:[ru]}],opacity:[{opacity:[S]}],"mix-blend":[{"mix-blend":ie()}],"bg-blend":[{"bg-blend":ie()}],filter:[{filter:["","none"]}],blur:[{blur:[n]}],brightness:[{brightness:[r]}],contrast:[{contrast:[u]}],"drop-shadow":[{"drop-shadow":["","none",Bi,Je]}],grayscale:[{grayscale:[d]}],"hue-rotate":[{"hue-rotate":[h]}],invert:[{invert:[m]}],saturate:[{saturate:[E]}],sepia:[{sepia:[P]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[n]}],"backdrop-brightness":[{"backdrop-brightness":[r]}],"backdrop-contrast":[{"backdrop-contrast":[u]}],"backdrop-grayscale":[{"backdrop-grayscale":[d]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[h]}],"backdrop-invert":[{"backdrop-invert":[m]}],"backdrop-opacity":[{"backdrop-opacity":[S]}],"backdrop-saturate":[{"backdrop-saturate":[E]}],"backdrop-sepia":[{"backdrop-sepia":[P]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":[s]}],"border-spacing-x":[{"border-spacing-x":[s]}],"border-spacing-y":[{"border-spacing-y":[s]}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["none","all","","colors","opacity","shadow","transform",Je]}],duration:[{duration:ge()}],ease:[{ease:["linear","in","out","in-out",Je]}],delay:[{delay:ge()}],animate:[{animate:["none","spin","ping","pulse","bounce",Je]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[k]}],"scale-x":[{"scale-x":[k]}],"scale-y":[{"scale-y":[k]}],rotate:[{rotate:[nu,Je]}],"translate-x":[{"translate-x":[O]}],"translate-y":[{"translate-y":[O]}],"skew-x":[{"skew-x":[M]}],"skew-y":[{"skew-y":[M]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",Je]}],accent:[{accent:["auto",e]}],appearance:["appearance-none"],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",Je]}],"caret-color":[{caret:[e]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":G()}],"scroll-mx":[{"scroll-mx":G()}],"scroll-my":[{"scroll-my":G()}],"scroll-ms":[{"scroll-ms":G()}],"scroll-me":[{"scroll-me":G()}],"scroll-mt":[{"scroll-mt":G()}],"scroll-mr":[{"scroll-mr":G()}],"scroll-mb":[{"scroll-mb":G()}],"scroll-ml":[{"scroll-ml":G()}],"scroll-p":[{"scroll-p":G()}],"scroll-px":[{"scroll-px":G()}],"scroll-py":[{"scroll-py":G()}],"scroll-ps":[{"scroll-ps":G()}],"scroll-pe":[{"scroll-pe":G()}],"scroll-pt":[{"scroll-pt":G()}],"scroll-pr":[{"scroll-pr":G()}],"scroll-pb":[{"scroll-pb":G()}],"scroll-pl":[{"scroll-pl":G()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",Je]}],fill:[{fill:[e,"none"]}],"stroke-w":[{stroke:[oo,zi,np]}],stroke:[{stroke:[e,"none"]}],sr:["sr-only","not-sr-only"]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]}}}const Jw=UL(iF),sF=40,is="inpaint",rp="diffusers_sd",nC="diffusers_sdxl",op="diffusers_sd_inpaint",rC="diffusers_sdxl_inpaint",l0="diffusers_other",Ky="#ffcc00bb",oC="ldm",iC="cv2",YR="Fantasy-Studio/Paint-by-Example",aF="timbrooks/instruct-pix2pix",lF="Sanster/PowerPaint-V1-stable-diffusion-inpainting",cF="Sanster/AnyText",uF="out of frame, lowres, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, disfigured, gross proportions, malformed limbs, watermark, signature";function Ce(...e){return Jw(BR(e))}function dF(){async function e(r=""){return(await fetch(r,{method:"GET",cache:"no-cache"})).json()}const t=()=>{const r=document.location;e(r+"/flaskwebgui-keep-server-alive").then(i=>i)},n=3*1e3;t(),setInterval(t,n)}function sC(e){const t=e.split(",")[0].split(":")[1].split(";")[0],n=atob(e.split(",")[1]),r=[];for(let o=0;o{const o=e.src,i=e;i.onload=n,i.onerror=s=>{i.src=o,r(s)},i.src=t})}async function fF(e){const t=URL.createObjectURL(e),n=new Image;return await Ip(n,t),n}function aC(e){return new Promise((t,n)=>{const r=new Image;r.addEventListener("load",()=>{t(r)}),r.addEventListener("error",o=>{n(o)}),r.src=e.toDataURL()})}function pF(e){return new Promise((t,n)=>{const r=new FileReader;r.onload=()=>{const o=new Image;o.onload=()=>{t(o)},o.onerror=()=>{n("无法加载图像。")},o.src=r.result},r.onerror=()=>{n("无法读取文件。")},r.readAsDataURL(e)})}function ku(e,t,n){return fetch(e).then(function(r){return r.arrayBuffer()}).then(function(r){return new File([r],t,{type:n})})}async function hF(){try{const{state:e}=await navigator.permissions.query({name:"clipboard-write"});return e==="granted"}catch{return!1}}function mF(e,t){return new Promise((n,r)=>e.toBlob(async o=>{o?n(o):r(new Error("Expected toBlob() to be defined"))},t))}const gF=async e=>{const t=[new ClipboardItem({[e.type]:e})];await navigator.clipboard.write(t)};function lC(e){return e.nativeEvent.button===2}function cC(e){return e.nativeEvent.button===1}async function vF(e){const t=await mF(e,"image/png");try{await gF(t)}catch{console.log("Copy image failed!")}}function yF(e,t){const n=document.createElement("a");n.href=e,n.download=t,n.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0,view:window})),setTimeout(()=>{n.remove()},100)}function c0(e){const t=e.nativeEvent;return{x:t.offsetX,y:t.offsetY}}function GR(e,t,n=Ky){e.strokeStyle=n,e.lineCap="round",e.lineJoin="round",t.forEach(r=>{!(r!=null&&r.pts.length)||!r.size||(e.lineWidth=r.size,e.beginPath(),e.moveTo(r.pts[0].x,r.pts[0].y),r.pts.forEach(o=>e.lineTo(o.x,o.y)),e.stroke())})}const Lp=(e,t,n,r=[],o="white")=>{const i=document.createElement("canvas");i.width=e,i.height=t;const s=i.getContext("2d");if(!s)throw new Error("could not retrieve mask canvas");return r.forEach(l=>{s.drawImage(l,0,0,e,t)}),n.forEach(l=>{GR(s,l,o)}),i},Ru=e=>new Promise((t,n)=>{const r=new FileReader;r.onload=o=>{var s;const i=(s=o.target)==null?void 0:s.result;t(i)},r.onerror=o=>{n(o)},r.readAsDataURL(e)});function XR(e,t){return function(){return e.apply(t,arguments)}}const{toString:wF}=Object.prototype,{getPrototypeOf:ex}=Object,$m=(e=>t=>{const n=wF.call(t);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),Go=e=>(e=e.toLowerCase(),t=>$m(t)===e),km=e=>t=>typeof t===e,{isArray:gc}=Array,Zu=km("undefined");function xF(e){return e!==null&&!Zu(e)&&e.constructor!==null&&!Zu(e.constructor)&&Kr(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const ZR=Go("ArrayBuffer");function bF(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&ZR(e.buffer),t}const _F=km("string"),Kr=km("function"),qR=km("number"),Rm=e=>e!==null&&typeof e=="object",SF=e=>e===!0||e===!1,Fp=e=>{if($m(e)!=="object")return!1;const t=ex(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},EF=Go("Date"),CF=Go("File"),$F=Go("Blob"),kF=Go("FileList"),RF=e=>Rm(e)&&Kr(e.pipe),TF=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||Kr(e.append)&&((t=$m(e))==="formdata"||t==="object"&&Kr(e.toString)&&e.toString()==="[object FormData]"))},PF=Go("URLSearchParams"),AF=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function kd(e,t,{allOwnKeys:n=!1}={}){if(e===null||typeof e>"u")return;let r,o;if(typeof e!="object"&&(e=[e]),gc(e))for(r=0,o=e.length;r0;)if(o=n[r],t===o.toLowerCase())return o;return null}const JR=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,eT=e=>!Zu(e)&&e!==JR;function Yy(){const{caseless:e}=eT(this)&&this||{},t={},n=(r,o)=>{const i=e&&QR(t,o)||o;Fp(t[i])&&Fp(r)?t[i]=Yy(t[i],r):Fp(r)?t[i]=Yy({},r):gc(r)?t[i]=r.slice():t[i]=r};for(let r=0,o=arguments.length;r(kd(t,(o,i)=>{n&&Kr(o)?e[i]=XR(o,n):e[i]=o},{allOwnKeys:r}),e),MF=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),NF=(e,t,n,r)=>{e.prototype=Object.create(t.prototype,r),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),n&&Object.assign(e.prototype,n)},DF=(e,t,n,r)=>{let o,i,s;const l={};if(t=t||{},e==null)return t;do{for(o=Object.getOwnPropertyNames(e),i=o.length;i-- >0;)s=o[i],(!r||r(s,e,t))&&!l[s]&&(t[s]=e[s],l[s]=!0);e=n!==!1&&ex(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},IF=(e,t,n)=>{e=String(e),(n===void 0||n>e.length)&&(n=e.length),n-=t.length;const r=e.indexOf(t,n);return r!==-1&&r===n},LF=e=>{if(!e)return null;if(gc(e))return e;let t=e.length;if(!qR(t))return null;const n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},FF=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&ex(Uint8Array)),jF=(e,t)=>{const r=(e&&e[Symbol.iterator]).call(e);let o;for(;(o=r.next())&&!o.done;){const i=o.value;t.call(e,i[0],i[1])}},zF=(e,t)=>{let n;const r=[];for(;(n=e.exec(t))!==null;)r.push(n);return r},BF=Go("HTMLFormElement"),UF=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,r,o){return r.toUpperCase()+o}),uC=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),VF=Go("RegExp"),tT=(e,t)=>{const n=Object.getOwnPropertyDescriptors(e),r={};kd(n,(o,i)=>{let s;(s=t(o,i,e))!==!1&&(r[i]=s||o)}),Object.defineProperties(e,r)},WF=e=>{tT(e,(t,n)=>{if(Kr(e)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;const r=e[n];if(Kr(r)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},HF=(e,t)=>{const n={},r=o=>{o.forEach(i=>{n[i]=!0})};return gc(e)?r(e):r(String(e).split(t)),n},KF=()=>{},YF=(e,t)=>(e=+e,Number.isFinite(e)?e:t),u0="abcdefghijklmnopqrstuvwxyz",dC="0123456789",nT={DIGIT:dC,ALPHA:u0,ALPHA_DIGIT:u0+u0.toUpperCase()+dC},GF=(e=16,t=nT.ALPHA_DIGIT)=>{let n="";const{length:r}=t;for(;e--;)n+=t[Math.random()*r|0];return n};function XF(e){return!!(e&&Kr(e.append)&&e[Symbol.toStringTag]==="FormData"&&e[Symbol.iterator])}const ZF=e=>{const t=new Array(10),n=(r,o)=>{if(Rm(r)){if(t.indexOf(r)>=0)return;if(!("toJSON"in r)){t[o]=r;const i=gc(r)?[]:{};return kd(r,(s,l)=>{const u=n(s,o+1);!Zu(u)&&(i[l]=u)}),t[o]=void 0,i}}return r};return n(e,0)},qF=Go("AsyncFunction"),QF=e=>e&&(Rm(e)||Kr(e))&&Kr(e.then)&&Kr(e.catch),oe={isArray:gc,isArrayBuffer:ZR,isBuffer:xF,isFormData:TF,isArrayBufferView:bF,isString:_F,isNumber:qR,isBoolean:SF,isObject:Rm,isPlainObject:Fp,isUndefined:Zu,isDate:EF,isFile:CF,isBlob:$F,isRegExp:VF,isFunction:Kr,isStream:RF,isURLSearchParams:PF,isTypedArray:FF,isFileList:kF,forEach:kd,merge:Yy,extend:OF,trim:AF,stripBOM:MF,inherits:NF,toFlatObject:DF,kindOf:$m,kindOfTest:Go,endsWith:IF,toArray:LF,forEachEntry:jF,matchAll:zF,isHTMLForm:BF,hasOwnProperty:uC,hasOwnProp:uC,reduceDescriptors:tT,freezeMethods:WF,toObjectSet:HF,toCamelCase:UF,noop:KF,toFiniteNumber:YF,findKey:QR,global:JR,isContextDefined:eT,ALPHABET:nT,generateString:GF,isSpecCompliantForm:XF,toJSONObject:ZF,isAsyncFn:qF,isThenable:QF};function ut(e,t,n,r,o){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),n&&(this.config=n),r&&(this.request=r),o&&(this.response=o)}oe.inherits(ut,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:oe.toJSONObject(this.config),code:this.code,status:this.response&&this.response.status?this.response.status:null}}});const rT=ut.prototype,oT={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{oT[e]={value:e}});Object.defineProperties(ut,oT);Object.defineProperty(rT,"isAxiosError",{value:!0});ut.from=(e,t,n,r,o,i)=>{const s=Object.create(rT);return oe.toFlatObject(e,s,function(u){return u!==Error.prototype},l=>l!=="isAxiosError"),ut.call(s,e.message,t,n,r,o),s.cause=e,s.name=e.name,i&&Object.assign(s,i),s};const JF=null;function Gy(e){return oe.isPlainObject(e)||oe.isArray(e)}function iT(e){return oe.endsWith(e,"[]")?e.slice(0,-2):e}function fC(e,t,n){return e?e.concat(t).map(function(o,i){return o=iT(o),!n&&i?"["+o+"]":o}).join(n?".":""):t}function ej(e){return oe.isArray(e)&&!e.some(Gy)}const tj=oe.toFlatObject(oe,{},null,function(t){return/^is[A-Z]/.test(t)});function Tm(e,t,n){if(!oe.isObject(e))throw new TypeError("target must be an object");t=t||new FormData,n=oe.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(_,C){return!oe.isUndefined(C[_])});const r=n.metaTokens,o=n.visitor||h,i=n.dots,s=n.indexes,u=(n.Blob||typeof Blob<"u"&&Blob)&&oe.isSpecCompliantForm(t);if(!oe.isFunction(o))throw new TypeError("visitor must be a function");function d(x){if(x===null)return"";if(oe.isDate(x))return x.toISOString();if(!u&&oe.isBlob(x))throw new ut("Blob is not supported. Use a Buffer instead.");return oe.isArrayBuffer(x)||oe.isTypedArray(x)?u&&typeof Blob=="function"?new Blob([x]):Buffer.from(x):x}function h(x,_,C){let S=x;if(x&&!C&&typeof x=="object"){if(oe.endsWith(_,"{}"))_=r?_:_.slice(0,-2),x=JSON.stringify(x);else if(oe.isArray(x)&&ej(x)||(oe.isFileList(x)||oe.endsWith(_,"[]"))&&(S=oe.toArray(x)))return _=iT(_),S.forEach(function(E,k){!(oe.isUndefined(E)||E===null)&&t.append(s===!0?fC([_],k,i):s===null?_:_+"[]",d(E))}),!1}return Gy(x)?!0:(t.append(fC(C,_,i),d(x)),!1)}const m=[],g=Object.assign(tj,{defaultVisitor:h,convertValue:d,isVisitable:Gy});function y(x,_){if(!oe.isUndefined(x)){if(m.indexOf(x)!==-1)throw Error("Circular reference detected in "+_.join("."));m.push(x),oe.forEach(x,function(S,b){(!(oe.isUndefined(S)||S===null)&&o.call(t,S,oe.isString(b)?b.trim():b,_,g))===!0&&y(S,_?_.concat(b):[b])}),m.pop()}}if(!oe.isObject(e))throw new TypeError("data must be an object");return y(e),t}function pC(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(r){return t[r]})}function tx(e,t){this._pairs=[],e&&Tm(e,this,t)}const sT=tx.prototype;sT.append=function(t,n){this._pairs.push([t,n])};sT.toString=function(t){const n=t?function(r){return t.call(this,r,pC)}:pC;return this._pairs.map(function(o){return n(o[0])+"="+n(o[1])},"").join("&")};function nj(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function aT(e,t,n){if(!t)return e;const r=n&&n.encode||nj,o=n&&n.serialize;let i;if(o?i=o(t,n):i=oe.isURLSearchParams(t)?t.toString():new tx(t,n).toString(r),i){const s=e.indexOf("#");s!==-1&&(e=e.slice(0,s)),e+=(e.indexOf("?")===-1?"?":"&")+i}return e}class rj{constructor(){this.handlers=[]}use(t,n,r){return this.handlers.push({fulfilled:t,rejected:n,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){oe.forEach(this.handlers,function(r){r!==null&&t(r)})}}const hC=rj,lT={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},oj=typeof URLSearchParams<"u"?URLSearchParams:tx,ij=typeof FormData<"u"?FormData:null,sj=typeof Blob<"u"?Blob:null,aj={isBrowser:!0,classes:{URLSearchParams:oj,FormData:ij,Blob:sj},protocols:["http","https","file","blob","url","data"]},cT=typeof window<"u"&&typeof document<"u",lj=(e=>cT&&["ReactNative","NativeScript","NS"].indexOf(e)<0)(typeof navigator<"u"&&navigator.product),cj=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",uj=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:cT,hasStandardBrowserEnv:lj,hasStandardBrowserWebWorkerEnv:cj},Symbol.toStringTag,{value:"Module"})),Io={...uj,...aj};function dj(e,t){return Tm(e,new Io.classes.URLSearchParams,Object.assign({visitor:function(n,r,o,i){return Io.isNode&&oe.isBuffer(n)?(this.append(r,n.toString("base64")),!1):i.defaultVisitor.apply(this,arguments)}},t))}function fj(e){return oe.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function pj(e){const t={},n=Object.keys(e);let r;const o=n.length;let i;for(r=0;r=n.length;return s=!s&&oe.isArray(o)?o.length:s,u?(oe.hasOwnProp(o,s)?o[s]=[o[s],r]:o[s]=r,!l):((!o[s]||!oe.isObject(o[s]))&&(o[s]=[]),t(n,r,o[s],i)&&oe.isArray(o[s])&&(o[s]=pj(o[s])),!l)}if(oe.isFormData(e)&&oe.isFunction(e.entries)){const n={};return oe.forEachEntry(e,(r,o)=>{t(fj(r),o,n,0)}),n}return null}function hj(e,t,n){if(oe.isString(e))try{return(t||JSON.parse)(e),oe.trim(e)}catch(r){if(r.name!=="SyntaxError")throw r}return(n||JSON.stringify)(e)}const nx={transitional:lT,adapter:["xhr","http"],transformRequest:[function(t,n){const r=n.getContentType()||"",o=r.indexOf("application/json")>-1,i=oe.isObject(t);if(i&&oe.isHTMLForm(t)&&(t=new FormData(t)),oe.isFormData(t))return o&&o?JSON.stringify(uT(t)):t;if(oe.isArrayBuffer(t)||oe.isBuffer(t)||oe.isStream(t)||oe.isFile(t)||oe.isBlob(t))return t;if(oe.isArrayBufferView(t))return t.buffer;if(oe.isURLSearchParams(t))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let l;if(i){if(r.indexOf("application/x-www-form-urlencoded")>-1)return dj(t,this.formSerializer).toString();if((l=oe.isFileList(t))||r.indexOf("multipart/form-data")>-1){const u=this.env&&this.env.FormData;return Tm(l?{"files[]":t}:t,u&&new u,this.formSerializer)}}return i||o?(n.setContentType("application/json",!1),hj(t)):t}],transformResponse:[function(t){const n=this.transitional||nx.transitional,r=n&&n.forcedJSONParsing,o=this.responseType==="json";if(t&&oe.isString(t)&&(r&&!this.responseType||o)){const s=!(n&&n.silentJSONParsing)&&o;try{return JSON.parse(t)}catch(l){if(s)throw l.name==="SyntaxError"?ut.from(l,ut.ERR_BAD_RESPONSE,this,null,this.response):l}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:Io.classes.FormData,Blob:Io.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};oe.forEach(["delete","get","head","post","put","patch"],e=>{nx.headers[e]={}});const rx=nx,mj=oe.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),gj=e=>{const t={};let n,r,o;return e&&e.split(` +`).forEach(function(s){o=s.indexOf(":"),n=s.substring(0,o).trim().toLowerCase(),r=s.substring(o+1).trim(),!(!n||t[n]&&mj[n])&&(n==="set-cookie"?t[n]?t[n].push(r):t[n]=[r]:t[n]=t[n]?t[n]+", "+r:r)}),t},mC=Symbol("internals");function ou(e){return e&&String(e).trim().toLowerCase()}function jp(e){return e===!1||e==null?e:oe.isArray(e)?e.map(jp):String(e)}function vj(e){const t=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=n.exec(e);)t[r[1]]=r[2];return t}const yj=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function d0(e,t,n,r,o){if(oe.isFunction(r))return r.call(this,t,n);if(o&&(t=n),!!oe.isString(t)){if(oe.isString(r))return t.indexOf(r)!==-1;if(oe.isRegExp(r))return r.test(t)}}function wj(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,n,r)=>n.toUpperCase()+r)}function xj(e,t){const n=oe.toCamelCase(" "+t);["get","set","has"].forEach(r=>{Object.defineProperty(e,r+n,{value:function(o,i,s){return this[r].call(this,t,o,i,s)},configurable:!0})})}class Pm{constructor(t){t&&this.set(t)}set(t,n,r){const o=this;function i(l,u,d){const h=ou(u);if(!h)throw new Error("header name must be a non-empty string");const m=oe.findKey(o,h);(!m||o[m]===void 0||d===!0||d===void 0&&o[m]!==!1)&&(o[m||u]=jp(l))}const s=(l,u)=>oe.forEach(l,(d,h)=>i(d,h,u));return oe.isPlainObject(t)||t instanceof this.constructor?s(t,n):oe.isString(t)&&(t=t.trim())&&!yj(t)?s(gj(t),n):t!=null&&i(n,t,r),this}get(t,n){if(t=ou(t),t){const r=oe.findKey(this,t);if(r){const o=this[r];if(!n)return o;if(n===!0)return vj(o);if(oe.isFunction(n))return n.call(this,o,r);if(oe.isRegExp(n))return n.exec(o);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,n){if(t=ou(t),t){const r=oe.findKey(this,t);return!!(r&&this[r]!==void 0&&(!n||d0(this,this[r],r,n)))}return!1}delete(t,n){const r=this;let o=!1;function i(s){if(s=ou(s),s){const l=oe.findKey(r,s);l&&(!n||d0(r,r[l],l,n))&&(delete r[l],o=!0)}}return oe.isArray(t)?t.forEach(i):i(t),o}clear(t){const n=Object.keys(this);let r=n.length,o=!1;for(;r--;){const i=n[r];(!t||d0(this,this[i],i,t,!0))&&(delete this[i],o=!0)}return o}normalize(t){const n=this,r={};return oe.forEach(this,(o,i)=>{const s=oe.findKey(r,i);if(s){n[s]=jp(o),delete n[i];return}const l=t?wj(i):String(i).trim();l!==i&&delete n[i],n[l]=jp(o),r[l]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){const n=Object.create(null);return oe.forEach(this,(r,o)=>{r!=null&&r!==!1&&(n[o]=t&&oe.isArray(r)?r.join(", "):r)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,n])=>t+": "+n).join(` +`)}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...n){const r=new this(t);return n.forEach(o=>r.set(o)),r}static accessor(t){const r=(this[mC]=this[mC]={accessors:{}}).accessors,o=this.prototype;function i(s){const l=ou(s);r[l]||(xj(o,s),r[l]=!0)}return oe.isArray(t)?t.forEach(i):i(t),this}}Pm.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);oe.reduceDescriptors(Pm.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(r){this[n]=r}}});oe.freezeMethods(Pm);const pi=Pm;function f0(e,t){const n=this||rx,r=t||n,o=pi.from(r.headers);let i=r.data;return oe.forEach(e,function(l){i=l.call(n,i,o.normalize(),t?t.status:void 0)}),o.normalize(),i}function dT(e){return!!(e&&e.__CANCEL__)}function Rd(e,t,n){ut.call(this,e??"canceled",ut.ERR_CANCELED,t,n),this.name="CanceledError"}oe.inherits(Rd,ut,{__CANCEL__:!0});function bj(e,t,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?e(n):t(new ut("Request failed with status code "+n.status,[ut.ERR_BAD_REQUEST,ut.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}const _j=Io.hasStandardBrowserEnv?{write(e,t,n,r,o,i){const s=[e+"="+encodeURIComponent(t)];oe.isNumber(n)&&s.push("expires="+new Date(n).toGMTString()),oe.isString(r)&&s.push("path="+r),oe.isString(o)&&s.push("domain="+o),i===!0&&s.push("secure"),document.cookie=s.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function Sj(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function Ej(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e}function fT(e,t){return e&&!Sj(t)?Ej(e,t):t}const Cj=Io.hasStandardBrowserEnv?function(){const t=/(msie|trident)/i.test(navigator.userAgent),n=document.createElement("a");let r;function o(i){let s=i;return t&&(n.setAttribute("href",s),s=n.href),n.setAttribute("href",s),{href:n.href,protocol:n.protocol?n.protocol.replace(/:$/,""):"",host:n.host,search:n.search?n.search.replace(/^\?/,""):"",hash:n.hash?n.hash.replace(/^#/,""):"",hostname:n.hostname,port:n.port,pathname:n.pathname.charAt(0)==="/"?n.pathname:"/"+n.pathname}}return r=o(window.location.href),function(s){const l=oe.isString(s)?o(s):s;return l.protocol===r.protocol&&l.host===r.host}}():function(){return function(){return!0}}();function $j(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function kj(e,t){e=e||10;const n=new Array(e),r=new Array(e);let o=0,i=0,s;return t=t!==void 0?t:1e3,function(u){const d=Date.now(),h=r[i];s||(s=d),n[o]=u,r[o]=d;let m=i,g=0;for(;m!==o;)g+=n[m++],m=m%e;if(o=(o+1)%e,o===i&&(i=(i+1)%e),d-s{const i=o.loaded,s=o.lengthComputable?o.total:void 0,l=i-n,u=r(l),d=i<=s;n=i;const h={loaded:i,total:s,progress:s?i/s:void 0,bytes:l,rate:u||void 0,estimated:u&&s&&d?(s-i)/u:void 0,event:o};h[t?"download":"upload"]=!0,e(h)}}const Rj=typeof XMLHttpRequest<"u",Tj=Rj&&function(e){return new Promise(function(n,r){let o=e.data;const i=pi.from(e.headers).normalize();let{responseType:s,withXSRFToken:l}=e,u;function d(){e.cancelToken&&e.cancelToken.unsubscribe(u),e.signal&&e.signal.removeEventListener("abort",u)}let h;if(oe.isFormData(o)){if(Io.hasStandardBrowserEnv||Io.hasStandardBrowserWebWorkerEnv)i.setContentType(!1);else if((h=i.getContentType())!==!1){const[_,...C]=h?h.split(";").map(S=>S.trim()).filter(Boolean):[];i.setContentType([_||"multipart/form-data",...C].join("; "))}}let m=new XMLHttpRequest;if(e.auth){const _=e.auth.username||"",C=e.auth.password?unescape(encodeURIComponent(e.auth.password)):"";i.set("Authorization","Basic "+btoa(_+":"+C))}const g=fT(e.baseURL,e.url);m.open(e.method.toUpperCase(),aT(g,e.params,e.paramsSerializer),!0),m.timeout=e.timeout;function y(){if(!m)return;const _=pi.from("getAllResponseHeaders"in m&&m.getAllResponseHeaders()),S={data:!s||s==="text"||s==="json"?m.responseText:m.response,status:m.status,statusText:m.statusText,headers:_,config:e,request:m};bj(function(E){n(E),d()},function(E){r(E),d()},S),m=null}if("onloadend"in m?m.onloadend=y:m.onreadystatechange=function(){!m||m.readyState!==4||m.status===0&&!(m.responseURL&&m.responseURL.indexOf("file:")===0)||setTimeout(y)},m.onabort=function(){m&&(r(new ut("Request aborted",ut.ECONNABORTED,e,m)),m=null)},m.onerror=function(){r(new ut("Network Error",ut.ERR_NETWORK,e,m)),m=null},m.ontimeout=function(){let C=e.timeout?"timeout of "+e.timeout+"ms exceeded":"timeout exceeded";const S=e.transitional||lT;e.timeoutErrorMessage&&(C=e.timeoutErrorMessage),r(new ut(C,S.clarifyTimeoutError?ut.ETIMEDOUT:ut.ECONNABORTED,e,m)),m=null},Io.hasStandardBrowserEnv&&(l&&oe.isFunction(l)&&(l=l(e)),l||l!==!1&&Cj(g))){const _=e.xsrfHeaderName&&e.xsrfCookieName&&_j.read(e.xsrfCookieName);_&&i.set(e.xsrfHeaderName,_)}o===void 0&&i.setContentType(null),"setRequestHeader"in m&&oe.forEach(i.toJSON(),function(C,S){m.setRequestHeader(S,C)}),oe.isUndefined(e.withCredentials)||(m.withCredentials=!!e.withCredentials),s&&s!=="json"&&(m.responseType=e.responseType),typeof e.onDownloadProgress=="function"&&m.addEventListener("progress",gC(e.onDownloadProgress,!0)),typeof e.onUploadProgress=="function"&&m.upload&&m.upload.addEventListener("progress",gC(e.onUploadProgress)),(e.cancelToken||e.signal)&&(u=_=>{m&&(r(!_||_.type?new Rd(null,e,m):_),m.abort(),m=null)},e.cancelToken&&e.cancelToken.subscribe(u),e.signal&&(e.signal.aborted?u():e.signal.addEventListener("abort",u)));const x=$j(g);if(x&&Io.protocols.indexOf(x)===-1){r(new ut("Unsupported protocol "+x+":",ut.ERR_BAD_REQUEST,e));return}m.send(o||null)})},Xy={http:JF,xhr:Tj};oe.forEach(Xy,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});const vC=e=>`- ${e}`,Pj=e=>oe.isFunction(e)||e===null||e===!1,pT={getAdapter:e=>{e=oe.isArray(e)?e:[e];const{length:t}=e;let n,r;const o={};for(let i=0;i`adapter ${l} `+(u===!1?"is not supported by the environment":"is not available in the build"));let s=t?i.length>1?`since : +`+i.map(vC).join(` +`):" "+vC(i[0]):"as no adapter specified";throw new ut("There is no suitable adapter to dispatch the request "+s,"ERR_NOT_SUPPORT")}return r},adapters:Xy};function p0(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Rd(null,e)}function yC(e){return p0(e),e.headers=pi.from(e.headers),e.data=f0.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),pT.getAdapter(e.adapter||rx.adapter)(e).then(function(r){return p0(e),r.data=f0.call(e,e.transformResponse,r),r.headers=pi.from(r.headers),r},function(r){return dT(r)||(p0(e),r&&r.response&&(r.response.data=f0.call(e,e.transformResponse,r.response),r.response.headers=pi.from(r.response.headers))),Promise.reject(r)})}const wC=e=>e instanceof pi?e.toJSON():e;function Jl(e,t){t=t||{};const n={};function r(d,h,m){return oe.isPlainObject(d)&&oe.isPlainObject(h)?oe.merge.call({caseless:m},d,h):oe.isPlainObject(h)?oe.merge({},h):oe.isArray(h)?h.slice():h}function o(d,h,m){if(oe.isUndefined(h)){if(!oe.isUndefined(d))return r(void 0,d,m)}else return r(d,h,m)}function i(d,h){if(!oe.isUndefined(h))return r(void 0,h)}function s(d,h){if(oe.isUndefined(h)){if(!oe.isUndefined(d))return r(void 0,d)}else return r(void 0,h)}function l(d,h,m){if(m in t)return r(d,h);if(m in e)return r(void 0,d)}const u={url:i,method:i,data:i,baseURL:s,transformRequest:s,transformResponse:s,paramsSerializer:s,timeout:s,timeoutMessage:s,withCredentials:s,withXSRFToken:s,adapter:s,responseType:s,xsrfCookieName:s,xsrfHeaderName:s,onUploadProgress:s,onDownloadProgress:s,decompress:s,maxContentLength:s,maxBodyLength:s,beforeRedirect:s,transport:s,httpAgent:s,httpsAgent:s,cancelToken:s,socketPath:s,responseEncoding:s,validateStatus:l,headers:(d,h)=>o(wC(d),wC(h),!0)};return oe.forEach(Object.keys(Object.assign({},e,t)),function(h){const m=u[h]||o,g=m(e[h],t[h],h);oe.isUndefined(g)&&m!==l||(n[h]=g)}),n}const hT="1.6.2",ox={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{ox[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const xC={};ox.transitional=function(t,n,r){function o(i,s){return"[Axios v"+hT+"] Transitional option '"+i+"'"+s+(r?". "+r:"")}return(i,s,l)=>{if(t===!1)throw new ut(o(s," has been removed"+(n?" in "+n:"")),ut.ERR_DEPRECATED);return n&&!xC[s]&&(xC[s]=!0,console.warn(o(s," has been deprecated since v"+n+" and will be removed in the near future"))),t?t(i,s,l):!0}};function Aj(e,t,n){if(typeof e!="object")throw new ut("options must be an object",ut.ERR_BAD_OPTION_VALUE);const r=Object.keys(e);let o=r.length;for(;o-- >0;){const i=r[o],s=t[i];if(s){const l=e[i],u=l===void 0||s(l,i,e);if(u!==!0)throw new ut("option "+i+" must be "+u,ut.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new ut("Unknown option "+i,ut.ERR_BAD_OPTION)}}const Zy={assertOptions:Aj,validators:ox},Ui=Zy.validators;class Ph{constructor(t){this.defaults=t,this.interceptors={request:new hC,response:new hC}}request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=Jl(this.defaults,n);const{transitional:r,paramsSerializer:o,headers:i}=n;r!==void 0&&Zy.assertOptions(r,{silentJSONParsing:Ui.transitional(Ui.boolean),forcedJSONParsing:Ui.transitional(Ui.boolean),clarifyTimeoutError:Ui.transitional(Ui.boolean)},!1),o!=null&&(oe.isFunction(o)?n.paramsSerializer={serialize:o}:Zy.assertOptions(o,{encode:Ui.function,serialize:Ui.function},!0)),n.method=(n.method||this.defaults.method||"get").toLowerCase();let s=i&&oe.merge(i.common,i[n.method]);i&&oe.forEach(["delete","get","head","post","put","patch","common"],x=>{delete i[x]}),n.headers=pi.concat(s,i);const l=[];let u=!0;this.interceptors.request.forEach(function(_){typeof _.runWhen=="function"&&_.runWhen(n)===!1||(u=u&&_.synchronous,l.unshift(_.fulfilled,_.rejected))});const d=[];this.interceptors.response.forEach(function(_){d.push(_.fulfilled,_.rejected)});let h,m=0,g;if(!u){const x=[yC.bind(this),void 0];for(x.unshift.apply(x,l),x.push.apply(x,d),g=x.length,h=Promise.resolve(n);m{if(!r._listeners)return;let i=r._listeners.length;for(;i-- >0;)r._listeners[i](o);r._listeners=null}),this.promise.then=o=>{let i;const s=new Promise(l=>{r.subscribe(l),i=l}).then(o);return s.cancel=function(){r.unsubscribe(i)},s},t(function(i,s,l){r.reason||(r.reason=new Rd(i,s,l),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}static source(){let t;return{token:new ix(function(o){t=o}),cancel:t}}}const Oj=ix;function Mj(e){return function(n){return e.apply(null,n)}}function Nj(e){return oe.isObject(e)&&e.isAxiosError===!0}const qy={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(qy).forEach(([e,t])=>{qy[t]=e});const Dj=qy;function mT(e){const t=new zp(e),n=XR(zp.prototype.request,t);return oe.extend(n,zp.prototype,t,{allOwnKeys:!0}),oe.extend(n,t,null,{allOwnKeys:!0}),n.create=function(o){return mT(Jl(e,o))},n}const Qt=mT(rx);Qt.Axios=zp;Qt.CanceledError=Rd;Qt.CancelToken=Oj;Qt.isCancel=dT;Qt.VERSION=hT;Qt.toFormData=Tm;Qt.AxiosError=ut;Qt.Cancel=Qt.CanceledError;Qt.all=function(t){return Promise.all(t)};Qt.spread=Mj;Qt.isAxiosError=Nj;Qt.mergeConfig=Jl;Qt.AxiosHeaders=pi;Qt.formToJSON=e=>uT(oe.isHTMLForm(e)?new FormData(e):e);Qt.getAdapter=pT.getAdapter;Qt.HttpStatusCode=Dj;Qt.default=Qt;const Ij=Qt,Ms="/api/v1",vc=Ij.create({baseURL:Ms});async function Lj(e,t,n,r,o,i=null){const s=await Ru(e),l=await Ru(o),u=i?await Ru(i):null,d=await fetch(`${Ms}/inpaint`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({image:s,mask:l,ldm_steps:t.ldmSteps,ldm_sampler:t.ldmSampler,zits_wireframe:t.zitsWireframe,cv2_flag:t.cv2Flag,cv2_radius:t.cv2Radius,hd_strategy:"Crop",hd_strategy_crop_triger_size:640,hd_strategy_crop_margin:128,hd_trategy_resize_imit:2048,prompt:t.prompt,negative_prompt:t.negativePrompt,use_croper:t.showCropper,croper_x:n.x,croper_y:n.y,croper_height:n.height,croper_width:n.width,use_extender:t.showExtender,extender_x:r.x,extender_y:r.y,extender_height:r.height,extender_width:r.width,sd_mask_blur:t.sdMaskBlur,sd_strength:t.sdStrength,sd_steps:t.sdSteps,sd_guidance_scale:t.sdGuidanceScale,sd_sampler:t.sdSampler,sd_seed:t.seedFixed?t.seed:-1,sd_match_histograms:t.sdMatchHistograms,sd_freeu:t.enableFreeu,sd_freeu_config:t.freeuConfig,sd_lcm_lora:t.enableLCMLora,paint_by_example_example_image:u,p2p_image_guidance_scale:t.p2pImageGuidanceScale,enable_controlnet:t.enableControlnet,controlnet_conditioning_scale:t.controlnetConditioningScale,controlnet_method:t.controlnetMethod?t.controlnetMethod:"",powerpaint_task:t.showExtender?kl.outpainting:t.powerpaintTask})});if(d.ok){const m=await d.blob();return{blob:URL.createObjectURL(m),seed:d.headers.get("X-Seed")}}const h=await d.json();throw new Error(`Something went wrong: ${h.errors}`)}async function Fj(){return(await vc.get("/server-config")).data}async function jj(e){return(await vc.post("/model",{name:e})).data}async function zj(){return(await vc.get("/model")).data}function Bj(){return vc.get("/models").then(e=>e.data)}async function gT(e,t,n,r,o){const i=await Ru(n),l=await fetch(`${Ms}/${e?"run_plugin_gen_mask":"run_plugin_gen_image"}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t,image:i,upscale:r,clicks:o})});if(l.ok){const d=await l.blob();return{blob:URL.createObjectURL(d)}}const u=await l.json();throw new Error(u)}async function Uj(e,t){const n=await fetch(`${Ms}/media_file?tab=${e}&filename=${encodeURIComponent(t)}`,{method:"GET"});if(n.ok){const o=await n.blob();return new File([o],t,{type:n.headers.get("Content-Type")??"image/png"})}const r=await n.json();throw new Error(r.errors)}async function Vj(e){return(await vc.get("medias",{params:{tab:e}})).data}async function Wj(e,t,n){const r=await ku(e.src,t,n),o=new FormData;o.append("file",r);try{const i=await fetch(`${Ms}/save_image`,{method:"POST",body:o});if(!i.ok){const s=await i.text();throw new Error(s)}}catch(i){throw new Error(`Something went wrong: ${i}`)}}async function Hj(e){const t=new FormData;return t.append("file",e),(await vc.post("/gen-info",t)).data}async function Kj(e,t,n){const r=await Ru(e),o=await fetch(`${Ms}/adjust_mask`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mask:r,operate:t,kernel_size:n})});if(o.ok)return await o.blob();const i=await o.json();throw new Error(i)}function Yj(){const[e,t]=f.useState(null),n=f.useCallback(()=>{const r=new Headers;r.append("pragma","no-cache"),r.append("cache-control","no-cache"),fetch(`${Ms}/inputimage`,{headers:r}).then(async o=>{var l;if(!o.ok)throw new Error("No input image found");const i=(l=o.headers.get("content-disposition"))==null?void 0:l.split("filename=")[1].split(";")[0],s=await o.blob();if(s&&s.type.startsWith("image")){const u=new File([s],i!==void 0?i:"inputImage");t(u)}}).catch(o=>{console.log(o)})},[t]);return f.useEffect(()=>{n()},[n]),e}function xo(e,t){if(e==null)return{};var n={},r=Object.keys(e),o,i;for(i=0;i=0)&&(n[o]=e[o]);return n}var Gj=["color"],Xj=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,Gj);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),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:r,fillRule:"evenodd",clipRule:"evenodd"}))}),Zj=["color"],vT=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,Zj);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M11.4669 3.72684C11.7558 3.91574 11.8369 4.30308 11.648 4.59198L7.39799 11.092C7.29783 11.2452 7.13556 11.3467 6.95402 11.3699C6.77247 11.3931 6.58989 11.3355 6.45446 11.2124L3.70446 8.71241C3.44905 8.48022 3.43023 8.08494 3.66242 7.82953C3.89461 7.57412 4.28989 7.55529 4.5453 7.78749L6.75292 9.79441L10.6018 3.90792C10.7907 3.61902 11.178 3.53795 11.4669 3.72684Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),qj=["color"],Qj=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,qj);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M3.13523 6.15803C3.3241 5.95657 3.64052 5.94637 3.84197 6.13523L7.5 9.56464L11.158 6.13523C11.3595 5.94637 11.6759 5.95657 11.8648 6.15803C12.0536 6.35949 12.0434 6.67591 11.842 6.86477L7.84197 10.6148C7.64964 10.7951 7.35036 10.7951 7.15803 10.6148L3.15803 6.86477C2.95657 6.67591 2.94637 6.35949 3.13523 6.15803Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),Jj=["color"],ez=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,Jj);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M6.1584 3.13508C6.35985 2.94621 6.67627 2.95642 6.86514 3.15788L10.6151 7.15788C10.7954 7.3502 10.7954 7.64949 10.6151 7.84182L6.86514 11.8418C6.67627 12.0433 6.35985 12.0535 6.1584 11.8646C5.95694 11.6757 5.94673 11.3593 6.1356 11.1579L9.565 7.49985L6.1356 3.84182C5.94673 3.64036 5.95694 3.32394 6.1584 3.13508Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),tz=["color"],nz=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,tz);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M3.13523 8.84197C3.3241 9.04343 3.64052 9.05363 3.84197 8.86477L7.5 5.43536L11.158 8.86477C11.3595 9.05363 11.6759 9.04343 11.8648 8.84197C12.0536 8.64051 12.0434 8.32409 11.842 8.13523L7.84197 4.38523C7.64964 4.20492 7.35036 4.20492 7.15803 4.38523L3.15803 8.13523C2.95657 8.32409 2.94637 8.64051 3.13523 8.84197Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),rz=["color"],yT=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,rz);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),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:r,fillRule:"evenodd",clipRule:"evenodd"}))}),oz=["color"],iz=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,oz);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M9.875 7.5C9.875 8.81168 8.81168 9.875 7.5 9.875C6.18832 9.875 5.125 8.81168 5.125 7.5C5.125 6.18832 6.18832 5.125 7.5 5.125C8.81168 5.125 9.875 6.18832 9.875 7.5Z",fill:r}))}),sz=["color"],az=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,sz);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M10 6.5C10 8.433 8.433 10 6.5 10C4.567 10 3 8.433 3 6.5C3 4.567 4.567 3 6.5 3C8.433 3 10 4.567 10 6.5ZM9.30884 10.0159C8.53901 10.6318 7.56251 11 6.5 11C4.01472 11 2 8.98528 2 6.5C2 4.01472 4.01472 2 6.5 2C8.98528 2 11 4.01472 11 6.5C11 7.56251 10.6318 8.53901 10.0159 9.30884L12.8536 12.1464C13.0488 12.3417 13.0488 12.6583 12.8536 12.8536C12.6583 13.0488 12.3417 13.0488 12.1464 12.8536L9.30884 10.0159Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),lz=["color"],cz=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,lz);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M3.24182 2.32181C3.3919 2.23132 3.5784 2.22601 3.73338 2.30781L12.7334 7.05781C12.8974 7.14436 13 7.31457 13 7.5C13 7.68543 12.8974 7.85564 12.7334 7.94219L3.73338 12.6922C3.5784 12.774 3.3919 12.7687 3.24182 12.6782C3.09175 12.5877 3 12.4252 3 12.25V2.75C3 2.57476 3.09175 2.4123 3.24182 2.32181ZM4 3.57925V11.4207L11.4288 7.5L4 3.57925Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),uz=["color"],dz=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,uz);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M7 2H1.5C1.22386 2 1 2.22386 1 2.5V7H7V2ZM8 2V7H14V2.5C14 2.22386 13.7761 2 13.5 2H8ZM7 8H1V12.5C1 12.7761 1.22386 13 1.5 13H7V8ZM8 13V8H14V12.5C14 12.7761 13.7761 13 13.5 13H8ZM1.5 1C0.671573 1 0 1.67157 0 2.5V12.5C0 13.3284 0.671573 14 1.5 14H13.5C14.3284 14 15 13.3284 15 12.5V2.5C15 1.67157 14.3284 1 13.5 1H1.5Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),fz=["color"],pz=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,fz);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M1.5 2H13.5C13.7761 2 14 2.22386 14 2.5V7H1V2.5C1 2.22386 1.22386 2 1.5 2ZM1 8V12.5C1 12.7761 1.22386 13 1.5 13H13.5C13.7761 13 14 12.7761 14 12.5V8H1ZM0 2.5C0 1.67157 0.671573 1 1.5 1H13.5C14.3284 1 15 1.67157 15 2.5V12.5C15 13.3284 14.3284 14 13.5 14H1.5C0.671573 14 0 13.3284 0 12.5V2.5Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))});function Y(){return Y=Object.assign?Object.assign.bind():function(e){for(var t=1;te.forEach(n=>hz(n,t))}function Be(...e){return f.useCallback(Am(...e),e)}const Wo=f.forwardRef((e,t)=>{const{children:n,...r}=e,o=f.Children.toArray(n),i=o.find(mz);if(i){const s=i.props.children,l=o.map(u=>u===i?f.Children.count(s)>1?f.Children.only(null):f.isValidElement(s)?s.props.children:null:u);return f.createElement(Qy,Y({},r,{ref:t}),f.isValidElement(s)?f.cloneElement(s,void 0,l):null)}return f.createElement(Qy,Y({},r,{ref:t}),n)});Wo.displayName="Slot";const Qy=f.forwardRef((e,t)=>{const{children:n,...r}=e;return f.isValidElement(n)?f.cloneElement(n,{...gz(r,n.props),ref:t?Am(t,n.ref):n.ref}):f.Children.count(n)>1?f.Children.only(null):null});Qy.displayName="SlotClone";const sx=({children:e})=>f.createElement(f.Fragment,null,e);function mz(e){return f.isValidElement(e)&&e.type===sx}function gz(e,t){const n={...t};for(const r in t){const o=e[r],i=t[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...l)=>{i(...l),o(...l)}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...e,...n}}const bC=e=>typeof e=="boolean"?"".concat(e):e===0?"0":e,_C=BR,Om=(e,t)=>n=>{var r;if((t==null?void 0:t.variants)==null)return _C(e,n==null?void 0:n.class,n==null?void 0:n.className);const{variants:o,defaultVariants:i}=t,s=Object.keys(o).map(d=>{const h=n==null?void 0:n[d],m=i==null?void 0:i[d];if(h===null)return null;const g=bC(h)||bC(m);return o[d][g]}),l=n&&Object.entries(n).reduce((d,h)=>{let[m,g]=h;return g===void 0||(d[m]=g),d},{}),u=t==null||(r=t.compoundVariants)===null||r===void 0?void 0:r.reduce((d,h)=>{let{class:m,className:g,...y}=h;return Object.entries(y).every(x=>{let[_,C]=x;return Array.isArray(C)?C.includes({...i,...l}[_]):{...i,...l}[_]===C})?[...d,m,g]:d},[]);return _C(e,s,u,n==null?void 0:n.class,n==null?void 0:n.className)};var vz={VITE_BACKEND:"http://127.0.0.1:8080",BASE_URL:"/",MODE:"production",DEV:!1,PROD:!0,SSR:!1};function yz(e,t){let n;try{n=e()}catch{return}return{getItem:o=>{var i;const s=u=>u===null?null:JSON.parse(u,t==null?void 0:t.reviver),l=(i=n.getItem(o))!=null?i:null;return l instanceof Promise?l.then(s):s(l)},setItem:(o,i)=>n.setItem(o,JSON.stringify(i,t==null?void 0:t.replacer)),removeItem:o=>n.removeItem(o)}}const qu=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then(r){return qu(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return qu(r)(n)}}}},wz=(e,t)=>(n,r,o)=>{let i={getStorage:()=>localStorage,serialize:JSON.stringify,deserialize:JSON.parse,partialize:C=>C,version:0,merge:(C,S)=>({...S,...C}),...t},s=!1;const l=new Set,u=new Set;let d;try{d=i.getStorage()}catch{}if(!d)return e((...C)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),n(...C)},r,o);const h=qu(i.serialize),m=()=>{const C=i.partialize({...r()});let S;const b=h({state:C,version:i.version}).then(E=>d.setItem(i.name,E)).catch(E=>{S=E});if(S)throw S;return b},g=o.setState;o.setState=(C,S)=>{g(C,S),m()};const y=e((...C)=>{n(...C),m()},r,o);let x;const _=()=>{var C;if(!d)return;s=!1,l.forEach(b=>b(r()));const S=((C=i.onRehydrateStorage)==null?void 0:C.call(i,r()))||void 0;return qu(d.getItem.bind(d))(i.name).then(b=>{if(b)return i.deserialize(b)}).then(b=>{if(b)if(typeof b.version=="number"&&b.version!==i.version){if(i.migrate)return i.migrate(b.state,b.version);console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return b.state}).then(b=>{var E;return x=i.merge(b,(E=r())!=null?E:y),n(x,!0),m()}).then(()=>{S==null||S(x,void 0),s=!0,u.forEach(b=>b(x))}).catch(b=>{S==null||S(void 0,b)})};return o.persist={setOptions:C=>{i={...i,...C},C.getStorage&&(d=C.getStorage())},clearStorage:()=>{d==null||d.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>_(),hasHydrated:()=>s,onHydrate:C=>(l.add(C),()=>{l.delete(C)}),onFinishHydration:C=>(u.add(C),()=>{u.delete(C)})},_(),x||y},xz=(e,t)=>(n,r,o)=>{let i={storage:yz(()=>localStorage),partialize:_=>_,version:0,merge:(_,C)=>({...C,..._}),...t},s=!1;const l=new Set,u=new Set;let d=i.storage;if(!d)return e((..._)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),n(..._)},r,o);const h=()=>{const _=i.partialize({...r()});return d.setItem(i.name,{state:_,version:i.version})},m=o.setState;o.setState=(_,C)=>{m(_,C),h()};const g=e((..._)=>{n(..._),h()},r,o);let y;const x=()=>{var _,C;if(!d)return;s=!1,l.forEach(b=>{var E;return b((E=r())!=null?E:g)});const S=((C=i.onRehydrateStorage)==null?void 0:C.call(i,(_=r())!=null?_:g))||void 0;return qu(d.getItem.bind(d))(i.name).then(b=>{if(b)if(typeof b.version=="number"&&b.version!==i.version){if(i.migrate)return i.migrate(b.state,b.version);console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return b.state}).then(b=>{var E;return y=i.merge(b,(E=r())!=null?E:g),n(y,!0),h()}).then(()=>{S==null||S(y,void 0),y=r(),s=!0,u.forEach(b=>b(y))}).catch(b=>{S==null||S(void 0,b)})};return o.persist={setOptions:_=>{i={...i,..._},_.storage&&(d=_.storage)},clearStorage:()=>{d==null||d.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>x(),hasHydrated:()=>s,onHydrate:_=>(l.add(_),()=>{l.delete(_)}),onFinishHydration:_=>(u.add(_),()=>{u.delete(_)})},i.skipHydration||x(),y||g},bz=(e,t)=>"getStorage"in t||"serialize"in t||"deserialize"in t?((vz?"production":void 0)!=="production"&&console.warn("[DEPRECATED] `getStorage`, `serialize` and `deserialize` options are deprecated. Use `storage` option instead."),wz(e,t)):xz(e,t),_z=bz;function Sz(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,o]of e)if(!Object.is(o,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{t(n,r,e)}):e.forEach((n,r)=>t(r,n,e))}function Mm(e){const t=e[wr];return t?t.type_:Array.isArray(e)?1:Nm(e)?2:Dm(e)?3:0}function Jy(e,t){return Mm(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function bT(e,t,n){const r=Mm(e);r===2?e.set(t,n):r===3?e.add(n):e[t]=n}function Cz(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function Nm(e){return e instanceof Map}function Dm(e){return e instanceof Set}function Js(e){return e.copy_||e.base_}function e1(e,t){if(Nm(e))return new Map(e);if(Dm(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);if(!t&&xT(e))return ec(e)?{...e}:Object.assign(Object.create(null),e);const n=Object.getOwnPropertyDescriptors(e);delete n[wr];let r=Reflect.ownKeys(n);for(let o=0;o1&&(e.set=e.add=e.clear=e.delete=$z),Object.freeze(e),t&&Qu(e,(n,r)=>ax(r,!0))),e}function $z(){ho(2)}function Im(e){return Object.isFrozen(e)}var kz={};function ka(e){const t=kz[e];return t||ho(0,e),t}var Ju;function _T(){return Ju}function Rz(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function EC(e,t){t&&(ka("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function t1(e){n1(e),e.drafts_.forEach(Tz),e.drafts_=null}function n1(e){e===Ju&&(Ju=e.parent_)}function CC(e){return Ju=Rz(Ju,e)}function Tz(e){const t=e[wr];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function $C(e,t){t.unfinalizedDrafts_=t.drafts_.length;const n=t.drafts_[0];return e!==void 0&&e!==n?(n[wr].modified_&&(t1(t),ho(4)),$a(e)&&(e=Ah(t,e),t.parent_||Oh(t,e)),t.patches_&&ka("Patches").generateReplacementPatches_(n[wr].base_,e,t.patches_,t.inversePatches_)):e=Ah(t,n,[]),t1(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==wT?e:void 0}function Ah(e,t,n){if(Im(t))return t;const r=t[wr];if(!r)return Qu(t,(o,i)=>kC(e,r,t,o,i,n)),t;if(r.scope_!==e)return t;if(!r.modified_)return Oh(e,r.base_,!0),r.base_;if(!r.finalized_){r.finalized_=!0,r.scope_.unfinalizedDrafts_--;const o=r.copy_;let i=o,s=!1;r.type_===3&&(i=new Set(o),o.clear(),s=!0),Qu(i,(l,u)=>kC(e,r,o,l,u,n,s)),Oh(e,o,!1),n&&e.patches_&&ka("Patches").generatePatches_(r,n,e.patches_,e.inversePatches_)}return r.copy_}function kC(e,t,n,r,o,i,s){if(tc(o)){const l=i&&t&&t.type_!==3&&!Jy(t.assigned_,r)?i.concat(r):void 0,u=Ah(e,o,l);if(bT(n,r,u),tc(u))e.canAutoFreeze_=!1;else return}else s&&n.add(o);if($a(o)&&!Im(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;Ah(e,o),(!t||!t.scope_.parent_)&&Oh(e,o)}}function Oh(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&ax(t,n)}function Pz(e,t){const n=Array.isArray(e),r={type_:n?1:0,scope_:t?t.scope_:_T(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1};let o=r,i=lx;n&&(o=[r],i=ed);const{revoke:s,proxy:l}=Proxy.revocable(o,i);return r.draft_=l,r.revoke_=s,l}var lx={get(e,t){if(t===wr)return e;const n=Js(e);if(!Jy(n,t))return Az(e,n,t);const r=n[t];return e.finalized_||!$a(r)?r:r===h0(e.base_,t)?(m0(e),e.copy_[t]=o1(r,e)):r},has(e,t){return t in Js(e)},ownKeys(e){return Reflect.ownKeys(Js(e))},set(e,t,n){const r=ST(Js(e),t);if(r!=null&&r.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){const o=h0(Js(e),t),i=o==null?void 0:o[wr];if(i&&i.base_===n)return e.copy_[t]=n,e.assigned_[t]=!1,!0;if(Cz(n,o)&&(n!==void 0||Jy(e.base_,t)))return!0;m0(e),r1(e)}return e.copy_[t]===n&&(n!==void 0||t in e.copy_)||Number.isNaN(n)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=n,e.assigned_[t]=!0),!0},deleteProperty(e,t){return h0(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,m0(e),r1(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){const n=Js(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:r.enumerable,value:n[t]}},defineProperty(){ho(11)},getPrototypeOf(e){return ec(e.base_)},setPrototypeOf(){ho(12)}},ed={};Qu(lx,(e,t)=>{ed[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});ed.deleteProperty=function(e,t){return ed.set.call(this,e,t,void 0)};ed.set=function(e,t,n){return lx.set.call(this,e[0],t,n,e[0])};function h0(e,t){const n=e[wr];return(n?Js(n):e)[t]}function Az(e,t,n){var o;const r=ST(t,n);return r?"value"in r?r.value:(o=r.get)==null?void 0:o.call(e.draft_):void 0}function ST(e,t){if(!(t in e))return;let n=ec(e);for(;n;){const r=Object.getOwnPropertyDescriptor(n,t);if(r)return r;n=ec(n)}}function r1(e){e.modified_||(e.modified_=!0,e.parent_&&r1(e.parent_))}function m0(e){e.copy_||(e.copy_=e1(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var Oz=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(t,n,r)=>{if(typeof t=="function"&&typeof n!="function"){const i=n;n=t;const s=this;return function(u=i,...d){return s.produce(u,h=>n.call(this,h,...d))}}typeof n!="function"&&ho(6),r!==void 0&&typeof r!="function"&&ho(7);let o;if($a(t)){const i=CC(this),s=o1(t,void 0);let l=!0;try{o=n(s),l=!1}finally{l?t1(i):n1(i)}return EC(i,r),$C(o,i)}else if(!t||typeof t!="object"){if(o=n(t),o===void 0&&(o=t),o===wT&&(o=void 0),this.autoFreeze_&&ax(o,!0),r){const i=[],s=[];ka("Patches").generateReplacementPatches_(t,o,i,s),r(i,s)}return o}else ho(1,t)},this.produceWithPatches=(t,n)=>{if(typeof t=="function")return(s,...l)=>this.produceWithPatches(s,u=>t(u,...l));let r,o;return[this.produce(t,n,(s,l)=>{r=s,o=l}),r,o]},typeof(e==null?void 0:e.autoFreeze)=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof(e==null?void 0:e.useStrictShallowCopy)=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){$a(e)||ho(8),tc(e)&&(e=Mz(e));const t=CC(this),n=o1(e,void 0);return n[wr].isManual_=!0,n1(t),n}finishDraft(e,t){const n=e&&e[wr];(!n||!n.isManual_)&&ho(9);const{scope_:r}=n;return EC(r,t),$C(void 0,r)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let n;for(n=t.length-1;n>=0;n--){const o=t[n];if(o.path.length===0&&o.op==="replace"){e=o.value;break}}n>-1&&(t=t.slice(n+1));const r=ka("Patches").applyPatches_;return tc(e)?r(e,t):this.produce(e,o=>r(o,t))}};function o1(e,t){const n=Nm(e)?ka("MapSet").proxyMap_(e,t):Dm(e)?ka("MapSet").proxySet_(e,t):Pz(e,t);return(t?t.scope_:_T()).drafts_.push(n),n}function Mz(e){return tc(e)||ho(10,e),ET(e)}function ET(e){if(!$a(e)||Im(e))return e;const t=e[wr];let n;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=e1(e,t.scope_.immer_.useStrictShallowCopy_)}else n=e1(e,!0);return Qu(n,(r,o)=>{bT(n,r,ET(o))}),t&&(t.finalized_=!1),n}var xr=new Oz,Nz=xr.produce;xr.produceWithPatches.bind(xr);xr.setAutoFreeze.bind(xr);xr.setUseStrictShallowCopy.bind(xr);xr.applyPatches.bind(xr);xr.createDraft.bind(xr);xr.finishDraft.bind(xr);const Dz=e=>(t,n,r)=>(r.setState=(o,i,...s)=>{const l=typeof o=="function"?Nz(o):o;return t(l,i,...s)},e(r.setState,n,r)),Iz=Dz;var CT={exports:{}},$T={},kT={exports:{}},RT={};/** + * @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 nc=f;function Lz(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var Fz=typeof Object.is=="function"?Object.is:Lz,jz=nc.useState,zz=nc.useEffect,Bz=nc.useLayoutEffect,Uz=nc.useDebugValue;function Vz(e,t){var n=t(),r=jz({inst:{value:n,getSnapshot:t}}),o=r[0].inst,i=r[1];return Bz(function(){o.value=n,o.getSnapshot=t,g0(o)&&i({inst:o})},[e,n,t]),zz(function(){return g0(o)&&i({inst:o}),e(function(){g0(o)&&i({inst:o})})},[e]),Uz(n),n}function g0(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!Fz(e,n)}catch{return!0}}function Wz(e,t){return t()}var Hz=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?Wz:Vz;RT.useSyncExternalStore=nc.useSyncExternalStore!==void 0?nc.useSyncExternalStore:Hz;kT.exports=RT;var Kz=kT.exports;/** + * @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 Lm=f,Yz=Kz;function Gz(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var Xz=typeof Object.is=="function"?Object.is:Gz,Zz=Yz.useSyncExternalStore,qz=Lm.useRef,Qz=Lm.useEffect,Jz=Lm.useMemo,eB=Lm.useDebugValue;$T.useSyncExternalStoreWithSelector=function(e,t,n,r,o){var i=qz(null);if(i.current===null){var s={hasValue:!1,value:null};i.current=s}else s=i.current;i=Jz(function(){function u(y){if(!d){if(d=!0,h=y,y=r(y),o!==void 0&&s.hasValue){var x=s.value;if(o(x,y))return m=x}return m=y}if(x=m,Xz(h,y))return x;var _=r(y);return o!==void 0&&o(x,_)?x:(h=y,m=_)}var d=!1,h,m,g=n===void 0?null:n;return[function(){return u(t())},g===null?void 0:function(){return u(g())}]},[t,n,r,o]);var l=Zz(e,i[0],i[1]);return Qz(function(){s.hasValue=!0,s.value=l},[l]),eB(l),l};CT.exports=$T;var tB=CT.exports;const nB=lm(tB);var rB={VITE_BACKEND:"http://127.0.0.1:8080",BASE_URL:"/",MODE:"production",DEV:!1,PROD:!0,SSR:!1};const RC=e=>{let t;const n=new Set,r=(u,d)=>{const h=typeof u=="function"?u(t):u;if(!Object.is(h,t)){const m=t;t=d??typeof h!="object"?h:Object.assign({},t,h),n.forEach(g=>g(t,m))}},o=()=>t,l={setState:r,getState:o,subscribe:u=>(n.add(u),()=>n.delete(u)),destroy:()=>{(rB?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),n.clear()}};return t=e(r,o,l),l},oB=e=>e?RC(e):RC,{useDebugValue:iB}=Fe,{useSyncExternalStoreWithSelector:sB}=nB;function aB(e,t=e.getState,n){const r=sB(e.subscribe,e.getState,e.getServerState||e.getState,t,n);return iB(r),r}const TC=(e,t)=>{const n=oB(e),r=(o,i=t)=>aB(n,o,i);return Object.assign(r,n),r},lB=(e,t)=>e?TC(e,t):TC,cB=1,uB=1e6;let v0=0;function dB(){return v0=(v0+1)%Number.MAX_VALUE,v0.toString()}const y0=new Map,PC=e=>{if(y0.has(e))return;const t=setTimeout(()=>{y0.delete(e),Tu({type:"REMOVE_TOAST",toastId:e})},uB);y0.set(e,t)},fB=(e,t)=>{switch(t.type){case"ADD_TOAST":return{...e,toasts:[t.toast,...e.toasts].slice(0,cB)};case"UPDATE_TOAST":return{...e,toasts:e.toasts.map(n=>n.id===t.toast.id?{...n,...t.toast}:n)};case"DISMISS_TOAST":{const{toastId:n}=t;return n?PC(n):e.toasts.forEach(r=>{PC(r.id)}),{...e,toasts:e.toasts.map(r=>r.id===n||n===void 0?{...r,open:!1}:r)}}case"REMOVE_TOAST":return t.toastId===void 0?{...e,toasts:[]}:{...e,toasts:e.toasts.filter(n=>n.id!==t.toastId)}}},Bp=[];let Up={toasts:[]};function Tu(e){Up=fB(Up,e),Bp.forEach(t=>{t(Up)})}function rl({...e}){const t=dB(),n=o=>Tu({type:"UPDATE_TOAST",toast:{...o,id:t}}),r=()=>Tu({type:"DISMISS_TOAST",toastId:t});return Tu({type:"ADD_TOAST",toast:{...e,id:t,open:!0,onOpenChange:o=>{o||r()}}}),{id:t,dismiss:r,update:n}}function Td(){const[e,t]=f.useState(Up);return f.useEffect(()=>(Bp.push(t),()=>{const n=Bp.indexOf(t);n>-1&&Bp.splice(n,1)}),[e]),{...e,toast:rl,dismiss:n=>Tu({type:"DISMISS_TOAST",toastId:n})}}const Zs={file:null,paintByExampleFile:null,customMask:null,imageHeight:0,imageWidth:0,isInpainting:!1,isPluginRunning:!1,isAdjustingMask:!1,disableShortCuts:!1,windowSize:{height:600,width:800},editorState:{baseBrushSize:sF,brushSizeScale:1,renders:[],extraMasks:[],prevExtraMasks:[],temporaryMasks:[],lineGroups:[],lastLineGroup:[],curLineGroup:[],redoRenders:[],redoCurLines:[],redoLineGroups:[]},interactiveSegState:{isInteractiveSeg:!1,tmpInteractiveSegMask:null,clicks:[]},cropperState:{x:0,y:0,width:512,height:512},extenderState:{x:0,y:0,width:512,height:512},isCropperExtenderResizing:!1,fileManagerState:{sortBy:xs.CTIME,sortOrder:$u.DESCENDING,layout:"masonry",searchText:"",inputDirectory:"",outputDirectory:""},serverConfig:{plugins:[],enableFileManager:!1,enableAutoSaving:!1,enableControlnet:!1,controlnetMethod:"lllyasviel/control_v11p_sd15_canny",disableModelSwitch:!1,isDesktop:!1,samplers:["DPM++ 2M"]},settings:{model:{name:"lama",path:"lama",model_type:"inpaint",support_controlnet:!1,support_strength:!1,support_outpainting:!1,controlnets:[],support_freeu:!1,support_lcm_lora:!1,is_single_file_diffusers:!1,need_prompt:!1},enableControlnet:!1,showCropper:!1,showExtender:!1,extenderDirection:In.xy,enableDownloadMask:!1,enableManualInpainting:!1,enableUploadMask:!1,enableAutoExtractPrompt:!0,ldmSteps:30,ldmSampler:Zw.ddim,zitsWireframe:!0,cv2Radius:5,cv2Flag:qw.INPAINT_NS,prompt:"",negativePrompt:uF,seed:42,seedFixed:!1,sdMaskBlur:35,sdStrength:1,sdSteps:50,sdGuidanceScale:7.5,sdSampler:"DPM++ 2M",sdMatchHistograms:!1,sdScale:1,p2pImageGuidanceScale:1.5,controlnetConditioningScale:.4,controlnetMethod:"lllyasviel/control_v11p_sd15_canny",enableLCMLora:!1,enableFreeu:!1,freeuConfig:{s1:.9,s2:.2,b1:1.2,b2:1.4},powerpaintTask:kl.text_guided,adjustMaskKernelSize:12}},bt=lB()(_z(Iz((e,t)=>({...Zs,showPrevMask:async()=>{if(t().settings.showExtender)return;const{lastLineGroup:n,curLineGroup:r,prevExtraMasks:o,extraMasks:i}=t().editorState;if(r.length!==0||i.length!==0)return;const{imageWidth:s,imageHeight:l}=t(),u=Lp(s,l,[n],o,Ky);try{const d=await aC(u);e(h=>{h.editorState.temporaryMasks.push(d)})}catch(d){console.error(d);return}},hidePrevMask:()=>{e(n=>{n.editorState.temporaryMasks=[]})},getCurrentTargetFile:async()=>{const n=t().file,r=t().editorState.renders;let o=n;if(r.length>0){const i=r[r.length-1];o=await ku(i.currentSrc,n.name,n.type)}return o},runInpainting:async()=>{const{isInpainting:n,file:r,paintByExampleFile:o,imageWidth:i,imageHeight:s,settings:l,cropperState:u,extenderState:d}=t();if(n||r===null||t().settings.model.support_outpainting&&l.showExtender&&d.height===s&&d.width===i)return;const{lastLineGroup:h,curLineGroup:m,lineGroups:g,renders:y,prevExtraMasks:x,extraMasks:_}=t().editorState,C=m.length===0&&_.length===0&&!l.showExtender;let S=[],b=[];if(C===!0?(b=h,S=x):(b=m,S=_),b.length===0&&S===null&&!l.showExtender){rl({variant:"destructive",description:"Please draw mask on picture"});return}const E=[...g,b];e(M=>{M.isInpainting=!0});let k=r;if(C===!0){if(y.length>1){const M=y[y.length-2];k=await ku(M.currentSrc,r.name,r.type)}}else if(y.length>0){const M=y[y.length-1];k=await ku(M.currentSrc,r.name,r.type)}const P=Lp(i,s,[b],S);if(C){const M=await aC(P);e(A=>{A.editorState.temporaryMasks=[M]})}try{const M=await Lj(k,l,u,d,sC(P.toDataURL()),o),{blob:A,seed:O}=M;O&&t().setSeed(parseInt(O,10));const F=new Image;await Ip(F,A);const V=[...y,F];t().setImageSize(F.width,F.height),t().updateEditorState({renders:V,lineGroups:E,lastLineGroup:b,curLineGroup:[],extraMasks:[],prevExtraMasks:S})}catch(M){rl({variant:"destructive",description:M.message?M.message:M.toString()})}t().resetRedoState(),e(M=>{M.isInpainting=!1,M.editorState.temporaryMasks=[]})},runRenderablePlugin:async(n,r,o={upscale:1})=>{const{renders:i,lineGroups:s}=t().editorState;e(l=>{l.isPluginRunning=!0});try{const l=new Date,u=await t().getCurrentTargetFile(),d=await gT(n,r,u,o.upscale),{blob:h}=d;if(n){const y=new Image;await Ip(y,h),e(x=>{x.editorState.extraMasks.push(y)})}else{const y=new Image;await Ip(y,h),t().setImageSize(y.width,y.height);const x=[...i,y],_=[...s,[]];t().updateEditorState({renders:x,lineGroups:_})}const g=new Date().getTime()-l.getTime();rl({description:`Run ${r} successfully in ${g/1e3}s`})}catch(l){rl({variant:"destructive",description:l.message?l.message:l.toString()})}e(l=>{l.isPluginRunning=!1})},updateEditorState:n=>{e(r=>{r.editorState={...r.editorState,...n}})},cleanCurLineGroup:()=>{t().updateEditorState({curLineGroup:[]})},handleCanvasMouseDown:n=>{let r=[];const o=t();o.runMannually()&&(r=[...o.editorState.curLineGroup]),r.push({size:o.getBrushSize(),pts:[n]}),e(i=>{i.editorState.curLineGroup=r})},handleCanvasMouseMove:n=>{e(r=>{const o=r.editorState.curLineGroup;o.length&&o[o.length-1].pts.push(n)})},runMannually:()=>{const n=t();return n.settings.enableManualInpainting||n.settings.model.model_type!==is},getIsProcessing:()=>t().isInpainting||t().isPluginRunning||t().isAdjustingMask,isSD:()=>t().settings.model.model_type!==is,undoDisabled:()=>{const n=t().editorState;if(n.renders.length>0)return!1;if(t().runMannually()){if(n.curLineGroup.length===0)return!0}else if(n.renders.length===0)return!0;return!1},undo:()=>{t().runMannually()&&t().editorState.curLineGroup.length!==0?e(n=>{const r=n.editorState;if(r.curLineGroup.length===0)return;r.lastLineGroup=[];const o=r.curLineGroup.pop();r.redoCurLines.push(o)}):e(n=>{const r=n.editorState;if(r.renders.length===0||r.lineGroups.length===0)return;const o=r.lineGroups.pop();r.redoLineGroups.push(o),r.redoCurLines=[],r.curLineGroup=[];const i=r.renders.pop();r.redoRenders.push(i)})},redoDisabled:()=>{const n=t().editorState;if(n.redoRenders.length>0)return!1;if(t().runMannually()){if(n.redoCurLines.length===0)return!0}else if(n.redoRenders.length===0)return!0;return!1},redo:()=>{t().runMannually()&&t().editorState.redoCurLines.length!==0?e(n=>{const r=n.editorState;if(r.redoCurLines.length===0)return;const o=r.redoCurLines.pop();r.curLineGroup.push(o)}):e(n=>{const r=n.editorState;if(r.redoRenders.length===0||r.redoLineGroups.length===0)return;const o=r.redoLineGroups.pop();r.lineGroups.push(o),r.curLineGroup=[];const i=r.redoRenders.pop();r.renders.push(i)})},resetRedoState:()=>{e(n=>{n.editorState.redoCurLines=[],n.editorState.redoLineGroups=[],n.editorState.redoRenders=[]})},updateAppState:n=>{e(()=>n)},getBrushSize:()=>t().editorState.baseBrushSize*t().editorState.brushSizeScale,showPromptInput:()=>{const n=t().settings.model;return n.model_type!==is&&n.name!==YR},setServerConfig:n=>{e(r=>{r.serverConfig=n,r.settings.enableControlnet=n.enableControlnet,r.settings.controlnetMethod=n.controlnetMethod})},updateSettings:n=>{e(r=>{r.settings={...r.settings,...n}})},setModel:n=>{e(r=>{r.settings.model=n,n.support_controlnet&&!n.controlnets.includes(r.settings.controlnetMethod)&&(r.settings.controlnetMethod=n.controlnets[0])})},updateFileManagerState:n=>{e(r=>{r.fileManagerState={...r.fileManagerState,...n}})},updateInteractiveSegState:n=>{e(r=>({...r,interactiveSegState:{...r.interactiveSegState,...n}}))},resetInteractiveSegState:()=>{t().updateInteractiveSegState(Zs.interactiveSegState)},handleInteractiveSegAccept:()=>{e(n=>{n.interactiveSegState.tmpInteractiveSegMask&&n.editorState.extraMasks.push(n.interactiveSegState.tmpInteractiveSegMask),n.interactiveSegState={...Zs.interactiveSegState}})},setIsInpainting:n=>e(r=>{r.isInpainting=n}),setFile:async n=>{if(t().settings.enableAutoExtractPrompt)try{const r=await Hj(n);r.prompt&&e(o=>{o.settings.prompt=r.prompt}),r.negative_prompt&&e(o=>{o.settings.negativePrompt=r.negative_prompt})}catch(r){rl({variant:"destructive",description:r.message?r.message:r.toString()})}e(r=>{r.file=n,r.interactiveSegState=Zs.interactiveSegState,r.editorState=Zs.editorState,r.cropperState=Zs.cropperState})},setCustomFile:n=>e(r=>{r.customMask=n}),setBaseBrushSize:n=>e(r=>{r.editorState.baseBrushSize=n}),setImageSize:(n,r)=>{e(o=>{o.imageWidth=n,o.imageHeight=r,o.editorState.brushSizeScale=Math.max(Math.min(n,r),512)/512}),t().resetExtender(n,r)},setCropperX:n=>e(r=>{r.cropperState.x=n}),setCropperY:n=>e(r=>{r.cropperState.y=n}),setCropperWidth:n=>e(r=>{r.cropperState.width=n}),setCropperHeight:n=>e(r=>{r.cropperState.height=n}),setExtenderX:n=>e(r=>{r.extenderState.x=n}),setExtenderY:n=>e(r=>{r.extenderState.y=n}),setExtenderWidth:n=>e(r=>{r.extenderState.width=n}),setExtenderHeight:n=>e(r=>{r.extenderState.height=n}),setIsCropperExtenderResizing:n=>e(r=>{r.isCropperExtenderResizing=n}),updateExtenderDirection:n=>{console.log(`updateExtenderDirection: ${JSON.stringify(t().extenderState)}`),e(r=>{r.settings.extenderDirection=n,r.extenderState.x=0,r.extenderState.y=0,r.extenderState.width=r.imageWidth,r.extenderState.height=r.imageHeight}),t().updateExtenderByBuiltIn(n,1.5)},updateExtenderByBuiltIn:(n,r)=>{const o={...Zs.extenderState};let{x:i,y:s,width:l,height:u}=o;const{imageWidth:d,imageHeight:h}=t();switch(l=d,u=h,n){case In.x:i=-Math.ceil(d*(r-1)/2),l=Math.ceil(d*r);break;case In.y:s=-Math.ceil(h*(r-1)/2),u=Math.ceil(h*r);break;case In.xy:i=-Math.ceil(d*(r-1)/2),s=-Math.ceil(h*(r-1)/2),l=Math.ceil(d*r),u=Math.ceil(h*r);break}e(m=>{m.extenderState.x=i,m.extenderState.y=s,m.extenderState.width=l,m.extenderState.height=u})},resetExtender:(n,r)=>{e(o=>{o.extenderState.x=0,o.extenderState.y=0,o.extenderState.width=n,o.extenderState.height=r})},setSeed:n=>e(r=>{r.settings.seed=n}),adjustMask:async n=>{const{imageWidth:r,imageHeight:o}=t(),{curLineGroup:i,extraMasks:s}=t().editorState,{adjustMaskKernelSize:l}=t().settings;if(i.length===0&&s.length===0)return;e(g=>{g.isAdjustingMask=!0});const u=Lp(r,o,[i],s,Ky),d=sC(u.toDataURL()),h=await Kj(d,n,l),m=await fF(h);e(g=>{g.editorState.extraMasks=[m],g.editorState.curLineGroup=[]}),e(g=>{g.isAdjustingMask=!1})},clearMask:()=>{e(n=>{n.editorState.extraMasks=[],n.editorState.curLineGroup=[]})}})),{name:"ZUSTAND_STATE",version:1,partialize:e=>Object.fromEntries(Object.entries(e).filter(([t])=>["fileManagerState","settings"].includes(t)))}),Sz),Pd=f.forwardRef(({className:e,type:t,...n},r)=>{const o=bt(l=>l.updateAppState),i=()=>{o({disableShortCuts:!0})},s=()=>{o({disableShortCuts:!1})};return v.jsx("input",{type:t,className:Ce("flex h-8 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",e),ref:r,autoComplete:"off",tabIndex:-1,onFocus:i,onBlur:s,...n})});Pd.displayName="Input";const Gn=f.forwardRef(({numberValue:e,allowFloat:t,onNumberValueChange:n,...r},o)=>{const[i,s]=f.useState(e.toString());f.useEffect(()=>{i!==e.toString()+"."&&s(e.toString())},[e]);const l=u=>{let h=u.target.value;if(t){if(h=h.replace(/[^0-9.]/g,"").replace(/(\..*?)\..*/g,"$1"),h.length===0){n(0);return}n(parseFloat(h))}else{if(h=h.replace(/\D/g,""),h.length===0){n(0);return}n(parseInt(h,10))}s(h)};return v.jsx(Pd,{ref:o,value:i,onInput:l,...r})});function ue(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 pB(e,t){const n=f.createContext(t);function r(i){const{children:s,...l}=i,u=f.useMemo(()=>l,Object.values(l));return f.createElement(n.Provider,{value:u},s)}function o(i){const s=f.useContext(n);if(s)return s;if(t!==void 0)return t;throw new Error(`\`${i}\` must be used within \`${e}\``)}return r.displayName=e+"Provider",[r,o]}function An(e,t=[]){let n=[];function r(i,s){const l=f.createContext(s),u=n.length;n=[...n,s];function d(m){const{scope:g,children:y,...x}=m,_=(g==null?void 0:g[e][u])||l,C=f.useMemo(()=>x,Object.values(x));return f.createElement(_.Provider,{value:C},y)}function h(m,g){const y=(g==null?void 0:g[e][u])||l,x=f.useContext(y);if(x)return x;if(s!==void 0)return s;throw new Error(`\`${m}\` must be used within \`${i}\``)}return d.displayName=i+"Provider",[d,h]}const o=()=>{const i=n.map(s=>f.createContext(s));return function(l){const u=(l==null?void 0:l[e])||i;return f.useMemo(()=>({[`__scope${e}`]:{...l,[e]:u}}),[l,u])}};return o.scopeName=e,[r,hB(o,...t)]}function hB(...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(i){const s=r.reduce((l,{useScope:u,scopeName:d})=>{const m=u(i)[`__scope${d}`];return{...l,...m}},{});return f.useMemo(()=>({[`__scope${t.scopeName}`]:s}),[s])}};return n.scopeName=t.scopeName,n}const mB=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","span","svg","ul"],Pe=mB.reduce((e,t)=>{const n=f.forwardRef((r,o)=>{const{asChild:i,...s}=r,l=i?Wo:t;return f.useEffect(()=>{window[Symbol.for("radix-ui")]=!0},[]),f.createElement(l,Y({},s,{ref:o}))});return n.displayName=`Primitive.${t}`,{...e,[t]:n}},{});function cx(e,t){e&&Os.flushSync(()=>e.dispatchEvent(t))}function Ft(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)},[])}function gB(e,t=globalThis==null?void 0:globalThis.document){const n=Ft(e);f.useEffect(()=>{const r=o=>{o.key==="Escape"&&n(o)};return t.addEventListener("keydown",r),()=>t.removeEventListener("keydown",r)},[n,t])}const i1="dismissableLayer.update",vB="dismissableLayer.pointerDownOutside",yB="dismissableLayer.focusOutside";let AC;const TT=f.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),yc=f.forwardRef((e,t)=>{var n;const{disableOutsidePointerEvents:r=!1,onEscapeKeyDown:o,onPointerDownOutside:i,onFocusOutside:s,onInteractOutside:l,onDismiss:u,...d}=e,h=f.useContext(TT),[m,g]=f.useState(null),y=(n=m==null?void 0:m.ownerDocument)!==null&&n!==void 0?n:globalThis==null?void 0:globalThis.document,[,x]=f.useState({}),_=Be(t,O=>g(O)),C=Array.from(h.layers),[S]=[...h.layersWithOutsidePointerEventsDisabled].slice(-1),b=C.indexOf(S),E=m?C.indexOf(m):-1,k=h.layersWithOutsidePointerEventsDisabled.size>0,P=E>=b,M=xB(O=>{const F=O.target,V=[...h.branches].some(J=>J.contains(F));!P||V||(i==null||i(O),l==null||l(O),O.defaultPrevented||u==null||u())},y),A=bB(O=>{const F=O.target;[...h.branches].some(J=>J.contains(F))||(s==null||s(O),l==null||l(O),O.defaultPrevented||u==null||u())},y);return gB(O=>{E===h.layers.size-1&&(o==null||o(O),!O.defaultPrevented&&u&&(O.preventDefault(),u()))},y),f.useEffect(()=>{if(m)return r&&(h.layersWithOutsidePointerEventsDisabled.size===0&&(AC=y.body.style.pointerEvents,y.body.style.pointerEvents="none"),h.layersWithOutsidePointerEventsDisabled.add(m)),h.layers.add(m),OC(),()=>{r&&h.layersWithOutsidePointerEventsDisabled.size===1&&(y.body.style.pointerEvents=AC)}},[m,y,r,h]),f.useEffect(()=>()=>{m&&(h.layers.delete(m),h.layersWithOutsidePointerEventsDisabled.delete(m),OC())},[m,h]),f.useEffect(()=>{const O=()=>x({});return document.addEventListener(i1,O),()=>document.removeEventListener(i1,O)},[]),f.createElement(Pe.div,Y({},d,{ref:_,style:{pointerEvents:k?P?"auto":"none":void 0,...e.style},onFocusCapture:ue(e.onFocusCapture,A.onFocusCapture),onBlurCapture:ue(e.onBlurCapture,A.onBlurCapture),onPointerDownCapture:ue(e.onPointerDownCapture,M.onPointerDownCapture)}))}),wB=f.forwardRef((e,t)=>{const n=f.useContext(TT),r=f.useRef(null),o=Be(t,r);return f.useEffect(()=>{const i=r.current;if(i)return n.branches.add(i),()=>{n.branches.delete(i)}},[n.branches]),f.createElement(Pe.div,Y({},e,{ref:o}))});function xB(e,t=globalThis==null?void 0:globalThis.document){const n=Ft(e),r=f.useRef(!1),o=f.useRef(()=>{});return f.useEffect(()=>{const i=l=>{if(l.target&&!r.current){let h=function(){PT(vB,n,d,{discrete:!0})};var u=h;const d={originalEvent:l};l.pointerType==="touch"?(t.removeEventListener("click",o.current),o.current=h,t.addEventListener("click",o.current,{once:!0})):h()}else t.removeEventListener("click",o.current);r.current=!1},s=window.setTimeout(()=>{t.addEventListener("pointerdown",i)},0);return()=>{window.clearTimeout(s),t.removeEventListener("pointerdown",i),t.removeEventListener("click",o.current)}},[t,n]),{onPointerDownCapture:()=>r.current=!0}}function bB(e,t=globalThis==null?void 0:globalThis.document){const n=Ft(e),r=f.useRef(!1);return f.useEffect(()=>{const o=i=>{i.target&&!r.current&&PT(yB,n,{originalEvent:i},{discrete:!1})};return t.addEventListener("focusin",o),()=>t.removeEventListener("focusin",o)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function OC(){const e=new CustomEvent(i1);document.dispatchEvent(e)}function PT(e,t,n,{discrete:r}){const o=n.originalEvent.target,i=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&o.addEventListener(e,t,{once:!0}),r?cx(o,i):o.dispatchEvent(i)}const _B=yc,SB=wB,Pn=globalThis!=null&&globalThis.document?f.useLayoutEffect:()=>{},EB=jD.useId||(()=>{});let CB=0;function nr(e){const[t,n]=f.useState(EB());return Pn(()=>{e||n(r=>r??String(CB++))},[e]),e||(t?`radix-${t}`:"")}const $B=["top","right","bottom","left"],Cs=Math.min,pr=Math.max,Mh=Math.round,ip=Math.floor,$s=e=>({x:e,y:e}),kB={left:"right",right:"left",bottom:"top",top:"bottom"},RB={start:"end",end:"start"};function s1(e,t,n){return pr(e,Cs(t,n))}function yi(e,t){return typeof e=="function"?e(t):e}function wi(e){return e.split("-")[0]}function wc(e){return e.split("-")[1]}function ux(e){return e==="x"?"y":"x"}function dx(e){return e==="y"?"height":"width"}function xc(e){return["top","bottom"].includes(wi(e))?"y":"x"}function fx(e){return ux(xc(e))}function TB(e,t,n){n===void 0&&(n=!1);const r=wc(e),o=fx(e),i=dx(o);let s=o==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[i]>t.floating[i]&&(s=Nh(s)),[s,Nh(s)]}function PB(e){const t=Nh(e);return[a1(e),t,a1(t)]}function a1(e){return e.replace(/start|end/g,t=>RB[t])}function AB(e,t,n){const r=["left","right"],o=["right","left"],i=["top","bottom"],s=["bottom","top"];switch(e){case"top":case"bottom":return n?t?o:r:t?r:o;case"left":case"right":return t?i:s;default:return[]}}function OB(e,t,n,r){const o=wc(e);let i=AB(wi(e),n==="start",r);return o&&(i=i.map(s=>s+"-"+o),t&&(i=i.concat(i.map(a1)))),i}function Nh(e){return e.replace(/left|right|bottom|top/g,t=>kB[t])}function MB(e){return{top:0,right:0,bottom:0,left:0,...e}}function AT(e){return typeof e!="number"?MB(e):{top:e,right:e,bottom:e,left:e}}function Dh(e){return{...e,top:e.y,left:e.x,right:e.x+e.width,bottom:e.y+e.height}}function MC(e,t,n){let{reference:r,floating:o}=e;const i=xc(t),s=fx(t),l=dx(s),u=wi(t),d=i==="y",h=r.x+r.width/2-o.width/2,m=r.y+r.height/2-o.height/2,g=r[l]/2-o[l]/2;let y;switch(u){case"top":y={x:h,y:r.y-o.height};break;case"bottom":y={x:h,y:r.y+r.height};break;case"right":y={x:r.x+r.width,y:m};break;case"left":y={x:r.x-o.width,y:m};break;default:y={x:r.x,y:r.y}}switch(wc(t)){case"start":y[s]-=g*(n&&d?-1:1);break;case"end":y[s]+=g*(n&&d?-1:1);break}return y}const NB=async(e,t,n)=>{const{placement:r="bottom",strategy:o="absolute",middleware:i=[],platform:s}=n,l=i.filter(Boolean),u=await(s.isRTL==null?void 0:s.isRTL(t));let d=await s.getElementRects({reference:e,floating:t,strategy:o}),{x:h,y:m}=MC(d,r,u),g=r,y={},x=0;for(let _=0;_({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:o,rects:i,platform:s,elements:l,middlewareData:u}=t,{element:d,padding:h=0}=yi(e,t)||{};if(d==null)return{};const m=AT(h),g={x:n,y:r},y=fx(o),x=dx(y),_=await s.getDimensions(d),C=y==="y",S=C?"top":"left",b=C?"bottom":"right",E=C?"clientHeight":"clientWidth",k=i.reference[x]+i.reference[y]-g[y]-i.floating[x],P=g[y]-i.reference[y],M=await(s.getOffsetParent==null?void 0:s.getOffsetParent(d));let A=M?M[E]:0;(!A||!await(s.isElement==null?void 0:s.isElement(M)))&&(A=l.floating[E]||i.floating[x]);const O=k/2-P/2,F=A/2-_[x]/2-1,V=Cs(m[S],F),J=Cs(m[b],F),G=V,ae=A-_[x]-J,U=A/2-_[x]/2+O,te=s1(G,U,ae),L=!u.arrow&&wc(o)!=null&&U!=te&&i.reference[x]/2-(UG<=0)){var F,V;const G=(((F=i.flip)==null?void 0:F.index)||0)+1,ae=P[G];if(ae)return{data:{index:G,overflows:O},reset:{placement:ae}};let U=(V=O.filter(te=>te.overflows[0]<=0).sort((te,L)=>te.overflows[1]-L.overflows[1])[0])==null?void 0:V.placement;if(!U)switch(y){case"bestFit":{var J;const te=(J=O.map(L=>[L.placement,L.overflows.filter(ie=>ie>0).reduce((ie,K)=>ie+K,0)]).sort((L,ie)=>L[1]-ie[1])[0])==null?void 0:J[0];te&&(U=te);break}case"initialPlacement":U=l;break}if(o!==U)return{reset:{placement:U}}}return{}}}};function DC(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function IC(e){return $B.some(t=>e[t]>=0)}const IB=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n}=t,{strategy:r="referenceHidden",...o}=yi(e,t);switch(r){case"referenceHidden":{const i=await td(t,{...o,elementContext:"reference"}),s=DC(i,n.reference);return{data:{referenceHiddenOffsets:s,referenceHidden:IC(s)}}}case"escaped":{const i=await td(t,{...o,altBoundary:!0}),s=DC(i,n.floating);return{data:{escapedOffsets:s,escaped:IC(s)}}}default:return{}}}}};async function LB(e,t){const{placement:n,platform:r,elements:o}=e,i=await(r.isRTL==null?void 0:r.isRTL(o.floating)),s=wi(n),l=wc(n),u=xc(n)==="y",d=["left","top"].includes(s)?-1:1,h=i&&u?-1:1,m=yi(t,e);let{mainAxis:g,crossAxis:y,alignmentAxis:x}=typeof m=="number"?{mainAxis:m,crossAxis:0,alignmentAxis:null}:{mainAxis:0,crossAxis:0,alignmentAxis:null,...m};return l&&typeof x=="number"&&(y=l==="end"?x*-1:x),u?{x:y*h,y:g*d}:{x:g*d,y:y*h}}const FB=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){const{x:n,y:r}=t,o=await LB(t,e);return{x:n+o.x,y:r+o.y,data:o}}}},jB=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:o}=t,{mainAxis:i=!0,crossAxis:s=!1,limiter:l={fn:C=>{let{x:S,y:b}=C;return{x:S,y:b}}},...u}=yi(e,t),d={x:n,y:r},h=await td(t,u),m=xc(wi(o)),g=ux(m);let y=d[g],x=d[m];if(i){const C=g==="y"?"top":"left",S=g==="y"?"bottom":"right",b=y+h[C],E=y-h[S];y=s1(b,y,E)}if(s){const C=m==="y"?"top":"left",S=m==="y"?"bottom":"right",b=x+h[C],E=x-h[S];x=s1(b,x,E)}const _=l.fn({...t,[g]:y,[m]:x});return{..._,data:{x:_.x-n,y:_.y-r}}}}},zB=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:r,placement:o,rects:i,middlewareData:s}=t,{offset:l=0,mainAxis:u=!0,crossAxis:d=!0}=yi(e,t),h={x:n,y:r},m=xc(o),g=ux(m);let y=h[g],x=h[m];const _=yi(l,t),C=typeof _=="number"?{mainAxis:_,crossAxis:0}:{mainAxis:0,crossAxis:0,..._};if(u){const E=g==="y"?"height":"width",k=i.reference[g]-i.floating[E]+C.mainAxis,P=i.reference[g]+i.reference[E]-C.mainAxis;yP&&(y=P)}if(d){var S,b;const E=g==="y"?"width":"height",k=["top","left"].includes(wi(o)),P=i.reference[m]-i.floating[E]+(k&&((S=s.offset)==null?void 0:S[m])||0)+(k?0:C.crossAxis),M=i.reference[m]+i.reference[E]+(k?0:((b=s.offset)==null?void 0:b[m])||0)-(k?C.crossAxis:0);xM&&(x=M)}return{[g]:y,[m]:x}}}},BB=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){const{placement:n,rects:r,platform:o,elements:i}=t,{apply:s=()=>{},...l}=yi(e,t),u=await td(t,l),d=wi(n),h=wc(n),m=xc(n)==="y",{width:g,height:y}=r.floating;let x,_;d==="top"||d==="bottom"?(x=d,_=h===(await(o.isRTL==null?void 0:o.isRTL(i.floating))?"start":"end")?"left":"right"):(_=d,x=h==="end"?"top":"bottom");const C=y-u[x],S=g-u[_],b=!t.middlewareData.shift;let E=C,k=S;if(m){const M=g-u.left-u.right;k=h||b?Cs(S,M):M}else{const M=y-u.top-u.bottom;E=h||b?Cs(C,M):M}if(b&&!h){const M=pr(u.left,0),A=pr(u.right,0),O=pr(u.top,0),F=pr(u.bottom,0);m?k=g-2*(M!==0||A!==0?M+A:pr(u.left,u.right)):E=y-2*(O!==0||F!==0?O+F:pr(u.top,u.bottom))}await s({...t,availableWidth:k,availableHeight:E});const P=await o.getDimensions(i.floating);return g!==P.width||y!==P.height?{reset:{rects:!0}}:{}}}};function ks(e){return OT(e)?(e.nodeName||"").toLowerCase():"#document"}function vr(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Ci(e){var t;return(t=(OT(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function OT(e){return e instanceof Node||e instanceof vr(e).Node}function xi(e){return e instanceof Element||e instanceof vr(e).Element}function Ho(e){return e instanceof HTMLElement||e instanceof vr(e).HTMLElement}function LC(e){return typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof vr(e).ShadowRoot}function Ad(e){const{overflow:t,overflowX:n,overflowY:r,display:o}=Xr(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&!["inline","contents"].includes(o)}function UB(e){return["table","td","th"].includes(ks(e))}function px(e){const t=hx(),n=Xr(e);return n.transform!=="none"||n.perspective!=="none"||(n.containerType?n.containerType!=="normal":!1)||!t&&(n.backdropFilter?n.backdropFilter!=="none":!1)||!t&&(n.filter?n.filter!=="none":!1)||["transform","perspective","filter"].some(r=>(n.willChange||"").includes(r))||["paint","layout","strict","content"].some(r=>(n.contain||"").includes(r))}function VB(e){let t=rc(e);for(;Ho(t)&&!Fm(t);){if(px(t))return t;t=rc(t)}return null}function hx(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}function Fm(e){return["html","body","#document"].includes(ks(e))}function Xr(e){return vr(e).getComputedStyle(e)}function jm(e){return xi(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.pageXOffset,scrollTop:e.pageYOffset}}function rc(e){if(ks(e)==="html")return e;const t=e.assignedSlot||e.parentNode||LC(e)&&e.host||Ci(e);return LC(t)?t.host:t}function MT(e){const t=rc(e);return Fm(t)?e.ownerDocument?e.ownerDocument.body:e.body:Ho(t)&&Ad(t)?t:MT(t)}function nd(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const o=MT(e),i=o===((r=e.ownerDocument)==null?void 0:r.body),s=vr(o);return i?t.concat(s,s.visualViewport||[],Ad(o)?o:[],s.frameElement&&n?nd(s.frameElement):[]):t.concat(o,nd(o,[],n))}function NT(e){const t=Xr(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const o=Ho(e),i=o?e.offsetWidth:n,s=o?e.offsetHeight:r,l=Mh(n)!==i||Mh(r)!==s;return l&&(n=i,r=s),{width:n,height:r,$:l}}function mx(e){return xi(e)?e:e.contextElement}function Rl(e){const t=mx(e);if(!Ho(t))return $s(1);const n=t.getBoundingClientRect(),{width:r,height:o,$:i}=NT(t);let s=(i?Mh(n.width):n.width)/r,l=(i?Mh(n.height):n.height)/o;return(!s||!Number.isFinite(s))&&(s=1),(!l||!Number.isFinite(l))&&(l=1),{x:s,y:l}}const WB=$s(0);function DT(e){const t=vr(e);return!hx()||!t.visualViewport?WB:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function HB(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==vr(e)?!1:t}function Ra(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const o=e.getBoundingClientRect(),i=mx(e);let s=$s(1);t&&(r?xi(r)&&(s=Rl(r)):s=Rl(e));const l=HB(i,n,r)?DT(i):$s(0);let u=(o.left+l.x)/s.x,d=(o.top+l.y)/s.y,h=o.width/s.x,m=o.height/s.y;if(i){const g=vr(i),y=r&&xi(r)?vr(r):r;let x=g.frameElement;for(;x&&r&&y!==g;){const _=Rl(x),C=x.getBoundingClientRect(),S=Xr(x),b=C.left+(x.clientLeft+parseFloat(S.paddingLeft))*_.x,E=C.top+(x.clientTop+parseFloat(S.paddingTop))*_.y;u*=_.x,d*=_.y,h*=_.x,m*=_.y,u+=b,d+=E,x=vr(x).frameElement}}return Dh({width:h,height:m,x:u,y:d})}function KB(e){let{rect:t,offsetParent:n,strategy:r}=e;const o=Ho(n),i=Ci(n);if(n===i)return t;let s={scrollLeft:0,scrollTop:0},l=$s(1);const u=$s(0);if((o||!o&&r!=="fixed")&&((ks(n)!=="body"||Ad(i))&&(s=jm(n)),Ho(n))){const d=Ra(n);l=Rl(n),u.x=d.x+n.clientLeft,u.y=d.y+n.clientTop}return{width:t.width*l.x,height:t.height*l.y,x:t.x*l.x-s.scrollLeft*l.x+u.x,y:t.y*l.y-s.scrollTop*l.y+u.y}}function YB(e){return Array.from(e.getClientRects())}function IT(e){return Ra(Ci(e)).left+jm(e).scrollLeft}function GB(e){const t=Ci(e),n=jm(e),r=e.ownerDocument.body,o=pr(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),i=pr(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let s=-n.scrollLeft+IT(e);const l=-n.scrollTop;return Xr(r).direction==="rtl"&&(s+=pr(t.clientWidth,r.clientWidth)-o),{width:o,height:i,x:s,y:l}}function XB(e,t){const n=vr(e),r=Ci(e),o=n.visualViewport;let i=r.clientWidth,s=r.clientHeight,l=0,u=0;if(o){i=o.width,s=o.height;const d=hx();(!d||d&&t==="fixed")&&(l=o.offsetLeft,u=o.offsetTop)}return{width:i,height:s,x:l,y:u}}function ZB(e,t){const n=Ra(e,!0,t==="fixed"),r=n.top+e.clientTop,o=n.left+e.clientLeft,i=Ho(e)?Rl(e):$s(1),s=e.clientWidth*i.x,l=e.clientHeight*i.y,u=o*i.x,d=r*i.y;return{width:s,height:l,x:u,y:d}}function FC(e,t,n){let r;if(t==="viewport")r=XB(e,n);else if(t==="document")r=GB(Ci(e));else if(xi(t))r=ZB(t,n);else{const o=DT(e);r={...t,x:t.x-o.x,y:t.y-o.y}}return Dh(r)}function LT(e,t){const n=rc(e);return n===t||!xi(n)||Fm(n)?!1:Xr(n).position==="fixed"||LT(n,t)}function qB(e,t){const n=t.get(e);if(n)return n;let r=nd(e,[],!1).filter(l=>xi(l)&&ks(l)!=="body"),o=null;const i=Xr(e).position==="fixed";let s=i?rc(e):e;for(;xi(s)&&!Fm(s);){const l=Xr(s),u=px(s);!u&&l.position==="fixed"&&(o=null),(i?!u&&!o:!u&&l.position==="static"&&!!o&&["absolute","fixed"].includes(o.position)||Ad(s)&&!u&<(e,s))?r=r.filter(h=>h!==s):o=l,s=rc(s)}return t.set(e,r),r}function QB(e){let{element:t,boundary:n,rootBoundary:r,strategy:o}=e;const s=[...n==="clippingAncestors"?qB(t,this._c):[].concat(n),r],l=s[0],u=s.reduce((d,h)=>{const m=FC(t,h,o);return d.top=pr(m.top,d.top),d.right=Cs(m.right,d.right),d.bottom=Cs(m.bottom,d.bottom),d.left=pr(m.left,d.left),d},FC(t,l,o));return{width:u.right-u.left,height:u.bottom-u.top,x:u.left,y:u.top}}function JB(e){return NT(e)}function eU(e,t,n){const r=Ho(t),o=Ci(t),i=n==="fixed",s=Ra(e,!0,i,t);let l={scrollLeft:0,scrollTop:0};const u=$s(0);if(r||!r&&!i)if((ks(t)!=="body"||Ad(o))&&(l=jm(t)),r){const d=Ra(t,!0,i,t);u.x=d.x+t.clientLeft,u.y=d.y+t.clientTop}else o&&(u.x=IT(o));return{x:s.left+l.scrollLeft-u.x,y:s.top+l.scrollTop-u.y,width:s.width,height:s.height}}function jC(e,t){return!Ho(e)||Xr(e).position==="fixed"?null:t?t(e):e.offsetParent}function FT(e,t){const n=vr(e);if(!Ho(e))return n;let r=jC(e,t);for(;r&&UB(r)&&Xr(r).position==="static";)r=jC(r,t);return r&&(ks(r)==="html"||ks(r)==="body"&&Xr(r).position==="static"&&!px(r))?n:r||VB(e)||n}const tU=async function(e){let{reference:t,floating:n,strategy:r}=e;const o=this.getOffsetParent||FT,i=this.getDimensions;return{reference:eU(t,await o(n),r),floating:{x:0,y:0,...await i(n)}}};function nU(e){return Xr(e).direction==="rtl"}const rU={convertOffsetParentRelativeRectToViewportRelativeRect:KB,getDocumentElement:Ci,getClippingRect:QB,getOffsetParent:FT,getElementRects:tU,getClientRects:YB,getDimensions:JB,getScale:Rl,isElement:xi,isRTL:nU};function oU(e,t){let n=null,r;const o=Ci(e);function i(){clearTimeout(r),n&&n.disconnect(),n=null}function s(l,u){l===void 0&&(l=!1),u===void 0&&(u=1),i();const{left:d,top:h,width:m,height:g}=e.getBoundingClientRect();if(l||t(),!m||!g)return;const y=ip(h),x=ip(o.clientWidth-(d+m)),_=ip(o.clientHeight-(h+g)),C=ip(d),b={rootMargin:-y+"px "+-x+"px "+-_+"px "+-C+"px",threshold:pr(0,Cs(1,u))||1};let E=!0;function k(P){const M=P[0].intersectionRatio;if(M!==u){if(!E)return s();M?s(!1,M):r=setTimeout(()=>{s(!1,1e-7)},100)}E=!1}try{n=new IntersectionObserver(k,{...b,root:o.ownerDocument})}catch{n=new IntersectionObserver(k,b)}n.observe(e)}return s(!0),i}function iU(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:o=!0,ancestorResize:i=!0,elementResize:s=typeof ResizeObserver=="function",layoutShift:l=typeof IntersectionObserver=="function",animationFrame:u=!1}=r,d=mx(e),h=o||i?[...d?nd(d):[],...nd(t)]:[];h.forEach(S=>{o&&S.addEventListener("scroll",n,{passive:!0}),i&&S.addEventListener("resize",n)});const m=d&&l?oU(d,n):null;let g=-1,y=null;s&&(y=new ResizeObserver(S=>{let[b]=S;b&&b.target===d&&y&&(y.unobserve(t),cancelAnimationFrame(g),g=requestAnimationFrame(()=>{y&&y.observe(t)})),n()}),d&&!u&&y.observe(d),y.observe(t));let x,_=u?Ra(e):null;u&&C();function C(){const S=Ra(e);_&&(S.x!==_.x||S.y!==_.y||S.width!==_.width||S.height!==_.height)&&n(),_=S,x=requestAnimationFrame(C)}return n(),()=>{h.forEach(S=>{o&&S.removeEventListener("scroll",n),i&&S.removeEventListener("resize",n)}),m&&m(),y&&y.disconnect(),y=null,u&&cancelAnimationFrame(x)}}const sU=(e,t,n)=>{const r=new Map,o={platform:rU,...n},i={...o.platform,_c:r};return NB(e,t,{...o,platform:i})},aU=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:o}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?NC({element:r.current,padding:o}).fn(n):{}:r?NC({element:r,padding:o}).fn(n):{}}}};var Vp=typeof document<"u"?f.useLayoutEffect:f.useEffect;function Ih(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(!Ih(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(!{}.hasOwnProperty.call(t,o[r]))return!1;for(r=n;r--!==0;){const i=o[r];if(!(i==="_owner"&&e.$$typeof)&&!Ih(e[i],t[i]))return!1}return!0}return e!==e&&t!==t}function jT(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function zC(e,t){const n=jT(e);return Math.round(t*n)/n}function BC(e){const t=f.useRef(e);return Vp(()=>{t.current=e}),t}function lU(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:o,elements:{reference:i,floating:s}={},transform:l=!0,whileElementsMounted:u,open:d}=e,[h,m]=f.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[g,y]=f.useState(r);Ih(g,r)||y(r);const[x,_]=f.useState(null),[C,S]=f.useState(null),b=f.useCallback(L=>{L!=M.current&&(M.current=L,_(L))},[_]),E=f.useCallback(L=>{L!==A.current&&(A.current=L,S(L))},[S]),k=i||x,P=s||C,M=f.useRef(null),A=f.useRef(null),O=f.useRef(h),F=BC(u),V=BC(o),J=f.useCallback(()=>{if(!M.current||!A.current)return;const L={placement:t,strategy:n,middleware:g};V.current&&(L.platform=V.current),sU(M.current,A.current,L).then(ie=>{const K={...ie,isPositioned:!0};G.current&&!Ih(O.current,K)&&(O.current=K,Os.flushSync(()=>{m(K)}))})},[g,t,n,V]);Vp(()=>{d===!1&&O.current.isPositioned&&(O.current.isPositioned=!1,m(L=>({...L,isPositioned:!1})))},[d]);const G=f.useRef(!1);Vp(()=>(G.current=!0,()=>{G.current=!1}),[]),Vp(()=>{if(k&&(M.current=k),P&&(A.current=P),k&&P){if(F.current)return F.current(k,P,J);J()}},[k,P,J,F]);const ae=f.useMemo(()=>({reference:M,floating:A,setReference:b,setFloating:E}),[b,E]),U=f.useMemo(()=>({reference:k,floating:P}),[k,P]),te=f.useMemo(()=>{const L={position:n,left:0,top:0};if(!U.floating)return L;const ie=zC(U.floating,h.x),K=zC(U.floating,h.y);return l?{...L,transform:"translate("+ie+"px, "+K+"px)",...jT(U.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:ie,top:K}},[n,l,U.floating,h.x,h.y]);return f.useMemo(()=>({...h,update:J,refs:ae,elements:U,floatingStyles:te}),[h,J,ae,U,te])}function gx(e){const[t,n]=f.useState(void 0);return Pn(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(o=>{if(!Array.isArray(o)||!o.length)return;const i=o[0];let s,l;if("borderBoxSize"in i){const u=i.borderBoxSize,d=Array.isArray(u)?u[0]:u;s=d.inlineSize,l=d.blockSize}else s=e.offsetWidth,l=e.offsetHeight;n({width:s,height:l})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}const zT="Popper",[BT,Ns]=An(zT),[cU,UT]=BT(zT),uU=e=>{const{__scopePopper:t,children:n}=e,[r,o]=f.useState(null);return f.createElement(cU,{scope:t,anchor:r,onAnchorChange:o},n)},dU="PopperAnchor",fU=f.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...o}=e,i=UT(dU,n),s=f.useRef(null),l=Be(t,s);return f.useEffect(()=>{i.onAnchorChange((r==null?void 0:r.current)||s.current)}),r?null:f.createElement(Pe.div,Y({},o,{ref:l}))}),VT="PopperContent",[pU,pte]=BT(VT),hU=f.forwardRef((e,t)=>{var n,r,o,i,s,l,u,d;const{__scopePopper:h,side:m="bottom",sideOffset:g=0,align:y="center",alignOffset:x=0,arrowPadding:_=0,avoidCollisions:C=!0,collisionBoundary:S=[],collisionPadding:b=0,sticky:E="partial",hideWhenDetached:k=!1,updatePositionStrategy:P="optimized",onPlaced:M,...A}=e,O=UT(VT,h),[F,V]=f.useState(null),J=Be(t,Kt=>V(Kt)),[G,ae]=f.useState(null),U=gx(G),te=(n=U==null?void 0:U.width)!==null&&n!==void 0?n:0,L=(r=U==null?void 0:U.height)!==null&&r!==void 0?r:0,ie=m+(y!=="center"?"-"+y:""),K=typeof b=="number"?b:{top:0,right:0,bottom:0,left:0,...b},Q=Array.isArray(S)?S:[S],W=Q.length>0,le={padding:K,boundary:Q.filter(mU),altBoundary:W},{refs:ge,floatingStyles:Ve,placement:Ue,isPositioned:We,middlewareData:Me}=lU({strategy:"fixed",placement:ie,whileElementsMounted:(...Kt)=>iU(...Kt,{animationFrame:P==="always"}),elements:{reference:O.anchor},middleware:[FB({mainAxis:g+L,alignmentAxis:x}),C&&jB({mainAxis:!0,crossAxis:!1,limiter:E==="partial"?zB():void 0,...le}),C&&DB({...le}),BB({...le,apply:({elements:Kt,rects:Er,availableWidth:gt,availableHeight:js})=>{const{width:I,height:X}=Er.reference,Z=Kt.floating.style;Z.setProperty("--radix-popper-available-width",`${gt}px`),Z.setProperty("--radix-popper-available-height",`${js}px`),Z.setProperty("--radix-popper-anchor-width",`${I}px`),Z.setProperty("--radix-popper-anchor-height",`${X}px`)}}),G&&aU({element:G,padding:_}),gU({arrowWidth:te,arrowHeight:L}),k&&IB({strategy:"referenceHidden",...le})]}),[fe,xe]=WT(Ue),$e=Ft(M);Pn(()=>{We&&($e==null||$e())},[We,$e]);const Ae=(o=Me.arrow)===null||o===void 0?void 0:o.x,Oe=(i=Me.arrow)===null||i===void 0?void 0:i.y,je=((s=Me.arrow)===null||s===void 0?void 0:s.centerOffset)!==0,[Ot,ct]=f.useState();return Pn(()=>{F&&ct(window.getComputedStyle(F).zIndex)},[F]),f.createElement("div",{ref:ge.setFloating,"data-radix-popper-content-wrapper":"",style:{...Ve,transform:We?Ve.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:Ot,"--radix-popper-transform-origin":[(l=Me.transformOrigin)===null||l===void 0?void 0:l.x,(u=Me.transformOrigin)===null||u===void 0?void 0:u.y].join(" ")},dir:e.dir},f.createElement(pU,{scope:h,placedSide:fe,onArrowChange:ae,arrowX:Ae,arrowY:Oe,shouldHideArrow:je},f.createElement(Pe.div,Y({"data-side":fe,"data-align":xe},A,{ref:J,style:{...A.style,animation:We?void 0:"none",opacity:(d=Me.hide)!==null&&d!==void 0&&d.referenceHidden?0:void 0}}))))});function mU(e){return e!==null}const gU=e=>({name:"transformOrigin",options:e,fn(t){var n,r,o,i,s;const{placement:l,rects:u,middlewareData:d}=t,m=((n=d.arrow)===null||n===void 0?void 0:n.centerOffset)!==0,g=m?0:e.arrowWidth,y=m?0:e.arrowHeight,[x,_]=WT(l),C={start:"0%",center:"50%",end:"100%"}[_],S=((r=(o=d.arrow)===null||o===void 0?void 0:o.x)!==null&&r!==void 0?r:0)+g/2,b=((i=(s=d.arrow)===null||s===void 0?void 0:s.y)!==null&&i!==void 0?i:0)+y/2;let E="",k="";return x==="bottom"?(E=m?C:`${S}px`,k=`${-y}px`):x==="top"?(E=m?C:`${S}px`,k=`${u.floating.height+y}px`):x==="right"?(E=`${-y}px`,k=m?C:`${b}px`):x==="left"&&(E=`${u.floating.width+y}px`,k=m?C:`${b}px`),{data:{x:E,y:k}}}});function WT(e){const[t,n="center"]=e.split("-");return[t,n]}const Od=uU,zm=fU,Bm=hU,Md=f.forwardRef((e,t)=>{var n;const{container:r=globalThis==null||(n=globalThis.document)===null||n===void 0?void 0:n.body,...o}=e;return r?XI.createPortal(f.createElement(Pe.div,Y({},o,{ref:t})),r):null});function vU(e,t){return f.useReducer((n,r)=>{const o=t[n][r];return o??n},e)}const bn=e=>{const{present:t,children:n}=e,r=yU(t),o=typeof n=="function"?n({present:r.isPresent}):f.Children.only(n),i=Be(r.ref,o.ref);return typeof n=="function"||r.isPresent?f.cloneElement(o,{ref:i}):null};bn.displayName="Presence";function yU(e){const[t,n]=f.useState(),r=f.useRef({}),o=f.useRef(e),i=f.useRef("none"),s=e?"mounted":"unmounted",[l,u]=vU(s,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return f.useEffect(()=>{const d=sp(r.current);i.current=l==="mounted"?d:"none"},[l]),Pn(()=>{const d=r.current,h=o.current;if(h!==e){const g=i.current,y=sp(d);e?u("MOUNT"):y==="none"||(d==null?void 0:d.display)==="none"?u("UNMOUNT"):u(h&&g!==y?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,u]),Pn(()=>{if(t){const d=m=>{const y=sp(r.current).includes(m.animationName);m.target===t&&y&&Os.flushSync(()=>u("ANIMATION_END"))},h=m=>{m.target===t&&(i.current=sp(r.current))};return t.addEventListener("animationstart",h),t.addEventListener("animationcancel",d),t.addEventListener("animationend",d),()=>{t.removeEventListener("animationstart",h),t.removeEventListener("animationcancel",d),t.removeEventListener("animationend",d)}}else u("ANIMATION_END")},[t,u]),{isPresent:["mounted","unmountSuspended"].includes(l),ref:f.useCallback(d=>{d&&(r.current=getComputedStyle(d)),n(d)},[])}}function sp(e){return(e==null?void 0:e.animationName)||"none"}function Zr({prop:e,defaultProp:t,onChange:n=()=>{}}){const[r,o]=wU({defaultProp:t,onChange:n}),i=e!==void 0,s=i?e:r,l=Ft(n),u=f.useCallback(d=>{if(i){const m=typeof d=="function"?d(e):d;m!==e&&l(m)}else o(d)},[i,e,o,l]);return[s,u]}function wU({defaultProp:e,onChange:t}){const n=f.useState(e),[r]=n,o=f.useRef(r),i=Ft(t);return f.useEffect(()=>{o.current!==r&&(i(r),o.current=r)},[r,o,i]),n}const Um=f.forwardRef((e,t)=>f.createElement(Pe.span,Y({},e,{ref:t,style:{position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal",...e.style}}))),xU=Um,[Vm,hte]=An("Tooltip",[Ns]),vx=Ns(),bU="TooltipProvider",_U=700,l1="tooltip.open",[SU,yx]=Vm(bU),EU=e=>{const{__scopeTooltip:t,delayDuration:n=_U,skipDelayDuration:r=300,disableHoverableContent:o=!1,children:i}=e,[s,l]=f.useState(!0),u=f.useRef(!1),d=f.useRef(0);return f.useEffect(()=>{const h=d.current;return()=>window.clearTimeout(h)},[]),f.createElement(SU,{scope:t,isOpenDelayed:s,delayDuration:n,onOpen:f.useCallback(()=>{window.clearTimeout(d.current),l(!1)},[]),onClose:f.useCallback(()=>{window.clearTimeout(d.current),d.current=window.setTimeout(()=>l(!0),r)},[r]),isPointerInTransitRef:u,onPointerInTransitChange:f.useCallback(h=>{u.current=h},[]),disableHoverableContent:o},i)},wx="Tooltip",[CU,Wm]=Vm(wx),$U=e=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:o=!1,onOpenChange:i,disableHoverableContent:s,delayDuration:l}=e,u=yx(wx,e.__scopeTooltip),d=vx(t),[h,m]=f.useState(null),g=nr(),y=f.useRef(0),x=s??u.disableHoverableContent,_=l??u.delayDuration,C=f.useRef(!1),[S=!1,b]=Zr({prop:r,defaultProp:o,onChange:A=>{A?(u.onOpen(),document.dispatchEvent(new CustomEvent(l1))):u.onClose(),i==null||i(A)}}),E=f.useMemo(()=>S?C.current?"delayed-open":"instant-open":"closed",[S]),k=f.useCallback(()=>{window.clearTimeout(y.current),C.current=!1,b(!0)},[b]),P=f.useCallback(()=>{window.clearTimeout(y.current),b(!1)},[b]),M=f.useCallback(()=>{window.clearTimeout(y.current),y.current=window.setTimeout(()=>{C.current=!0,b(!0)},_)},[_,b]);return f.useEffect(()=>()=>window.clearTimeout(y.current),[]),f.createElement(Od,d,f.createElement(CU,{scope:t,contentId:g,open:S,stateAttribute:E,trigger:h,onTriggerChange:m,onTriggerEnter:f.useCallback(()=>{u.isOpenDelayed?M():k()},[u.isOpenDelayed,M,k]),onTriggerLeave:f.useCallback(()=>{x?P():window.clearTimeout(y.current)},[P,x]),onOpen:k,onClose:P,disableHoverableContent:x},n))},UC="TooltipTrigger",kU=f.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,o=Wm(UC,n),i=yx(UC,n),s=vx(n),l=f.useRef(null),u=Be(t,l,o.onTriggerChange),d=f.useRef(!1),h=f.useRef(!1),m=f.useCallback(()=>d.current=!1,[]);return f.useEffect(()=>()=>document.removeEventListener("pointerup",m),[m]),f.createElement(zm,Y({asChild:!0},s),f.createElement(Pe.button,Y({"aria-describedby":o.open?o.contentId:void 0,"data-state":o.stateAttribute},r,{ref:u,onPointerMove:ue(e.onPointerMove,g=>{g.pointerType!=="touch"&&!h.current&&!i.isPointerInTransitRef.current&&(o.onTriggerEnter(),h.current=!0)}),onPointerLeave:ue(e.onPointerLeave,()=>{o.onTriggerLeave(),h.current=!1}),onPointerDown:ue(e.onPointerDown,()=>{d.current=!0,document.addEventListener("pointerup",m,{once:!0})}),onFocus:ue(e.onFocus,()=>{d.current||o.onOpen()}),onBlur:ue(e.onBlur,o.onClose),onClick:ue(e.onClick,o.onClose)})))}),RU="TooltipPortal",[mte,TU]=Vm(RU,{forceMount:void 0}),rd="TooltipContent",PU=f.forwardRef((e,t)=>{const n=TU(rd,e.__scopeTooltip),{forceMount:r=n.forceMount,side:o="top",...i}=e,s=Wm(rd,e.__scopeTooltip);return f.createElement(bn,{present:r||s.open},s.disableHoverableContent?f.createElement(HT,Y({side:o},i,{ref:t})):f.createElement(AU,Y({side:o},i,{ref:t})))}),AU=f.forwardRef((e,t)=>{const n=Wm(rd,e.__scopeTooltip),r=yx(rd,e.__scopeTooltip),o=f.useRef(null),i=Be(t,o),[s,l]=f.useState(null),{trigger:u,onClose:d}=n,h=o.current,{onPointerInTransitChange:m}=r,g=f.useCallback(()=>{l(null),m(!1)},[m]),y=f.useCallback((x,_)=>{const C=x.currentTarget,S={x:x.clientX,y:x.clientY},b=MU(S,C.getBoundingClientRect()),E=NU(S,b),k=DU(_.getBoundingClientRect()),P=LU([...E,...k]);l(P),m(!0)},[m]);return f.useEffect(()=>()=>g(),[g]),f.useEffect(()=>{if(u&&h){const x=C=>y(C,h),_=C=>y(C,u);return u.addEventListener("pointerleave",x),h.addEventListener("pointerleave",_),()=>{u.removeEventListener("pointerleave",x),h.removeEventListener("pointerleave",_)}}},[u,h,y,g]),f.useEffect(()=>{if(s){const x=_=>{const C=_.target,S={x:_.clientX,y:_.clientY},b=(u==null?void 0:u.contains(C))||(h==null?void 0:h.contains(C)),E=!IU(S,s);b?g():E&&(g(),d())};return document.addEventListener("pointermove",x),()=>document.removeEventListener("pointermove",x)}},[u,h,s,d,g]),f.createElement(HT,Y({},e,{ref:i}))}),[OU,gte]=Vm(wx,{isInside:!1}),HT=f.forwardRef((e,t)=>{const{__scopeTooltip:n,children:r,"aria-label":o,onEscapeKeyDown:i,onPointerDownOutside:s,...l}=e,u=Wm(rd,n),d=vx(n),{onClose:h}=u;return f.useEffect(()=>(document.addEventListener(l1,h),()=>document.removeEventListener(l1,h)),[h]),f.useEffect(()=>{if(u.trigger){const m=g=>{const y=g.target;y!=null&&y.contains(u.trigger)&&h()};return window.addEventListener("scroll",m,{capture:!0}),()=>window.removeEventListener("scroll",m,{capture:!0})}},[u.trigger,h]),f.createElement(yc,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:i,onPointerDownOutside:s,onFocusOutside:m=>m.preventDefault(),onDismiss:h},f.createElement(Bm,Y({"data-state":u.stateAttribute},d,l,{ref:t,style:{...l.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"}}),f.createElement(sx,null,r),f.createElement(OU,{scope:n,isInside:!0},f.createElement(xU,{id:u.contentId,role:"tooltip"},o||r))))});function MU(e,t){const n=Math.abs(t.top-e.y),r=Math.abs(t.bottom-e.y),o=Math.abs(t.right-e.x),i=Math.abs(t.left-e.x);switch(Math.min(n,r,o,i)){case i:return"left";case o:return"right";case n:return"top";case r:return"bottom";default:throw new Error("unreachable")}}function NU(e,t,n=5){const r=[];switch(t){case"top":r.push({x:e.x-n,y:e.y+n},{x:e.x+n,y:e.y+n});break;case"bottom":r.push({x:e.x-n,y:e.y-n},{x:e.x+n,y:e.y-n});break;case"left":r.push({x:e.x+n,y:e.y-n},{x:e.x+n,y:e.y+n});break;case"right":r.push({x:e.x-n,y:e.y-n},{x:e.x-n,y:e.y+n});break}return r}function DU(e){const{top:t,right:n,bottom:r,left:o}=e;return[{x:o,y:t},{x:n,y:t},{x:n,y:r},{x:o,y:r}]}function IU(e,t){const{x:n,y:r}=e;let o=!1;for(let i=0,s=t.length-1;ir!=h>r&&n<(d-l)*(r-u)/(h-u)+l&&(o=!o)}return o}function LU(e){const t=e.slice();return t.sort((n,r)=>n.xr.x?1:n.yr.y?1:0),FU(t)}function FU(e){if(e.length<=1)return e.slice();const t=[];for(let r=0;r=2;){const i=t[t.length-1],s=t[t.length-2];if((i.x-s.x)*(o.y-s.y)>=(i.y-s.y)*(o.x-s.x))t.pop();else break}t.push(o)}t.pop();const n=[];for(let r=e.length-1;r>=0;r--){const o=e[r];for(;n.length>=2;){const i=n[n.length-1],s=n[n.length-2];if((i.x-s.x)*(o.y-s.y)>=(i.y-s.y)*(o.x-s.x))n.pop();else break}n.push(o)}return n.pop(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}const jU=EU,zU=$U,BU=kU,KT=PU,UU=jU,YT=zU,GT=BU,xx=f.forwardRef(({className:e,sideOffset:t=4,...n},r)=>v.jsx(KT,{ref:r,sideOffset:t,className:Ce("z-50 border overflow-hidden rounded-md bg-background text-foreground px-3 py-1.5 text-xs animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...n}));xx.displayName=KT.displayName;const bx=Om("inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50",{variants:{variant:{default:"bg-primary text-primary-foreground shadow hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",outline:"border border-input bg-transparent shadow-sm hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2",sm:"h-8 rounded-md px-3 text-xs",lg:"h-10 rounded-md px-8",icon:"h-9 w-9"}},defaultVariants:{variant:"default",size:"default"}}),yn=f.forwardRef(({className:e,variant:t,size:n,asChild:r=!1,...o},i)=>{const s=r?Wo:"button";return v.jsx(s,{className:Ce(bx({variant:t,size:n,className:e}),"outline-none cursor-default"),ref:i,tabIndex:-1,...o})});yn.displayName="Button";const vn=f.forwardRef(({tooltip:e,children:t,...n},r)=>v.jsxs(YT,{children:[v.jsx(GT,{asChild:!0,children:v.jsx(yn,{variant:"ghost",size:"icon",...n,ref:r,tabIndex:-1,className:"cursor-default bg-background",children:v.jsx("div",{className:"icon-button-icon-wrapper",children:t})})}),v.jsx(xx,{children:v.jsx("p",{children:e})})]})),c1=e=>{const{onFileUpload:t,children:n,...r}=e,[o]=f.useState(`file-upload-${Math.random().toString()}`),i=s=>{var u;const l=(u=s.currentTarget.files)==null?void 0:u[0];l&&t(l)};return v.jsxs(v.Fragment,{children:[v.jsx("label",{htmlFor:o,children:v.jsx(vn,{...r,asChild:!0,children:n})}),v.jsx(Pd,{style:{display:"none"},id:o,name:o,type:"file",onChange:i,accept:"image/png, image/jpeg"})]})};var VU={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const WU=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Jt=(e,t)=>{const n=f.forwardRef(({color:r="currentColor",size:o=24,strokeWidth:i=2,absoluteStrokeWidth:s,children:l,...u},d)=>f.createElement("svg",{ref:d,...VU,width:o,height:o,stroke:r,strokeWidth:s?Number(i)*24/Number(o):i,className:`lucide lucide-${WU(e)}`,...u},[...t.map(([h,m])=>f.createElement(h,m)),...(Array.isArray(l)?l:[l])||[]]));return n.displayName=`${e}`,n},HU=Jt("Blocks",[["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["path",{d:"M10 21V8a1 1 0 0 0-1-1H4a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-5a1 1 0 0 0-1-1H3",key:"1fpvtg"}]]),KU=Jt("ChevronLeft",[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]]),YU=Jt("ChevronRight",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]),GU=Jt("Coffee",[["path",{d:"M17 8h1a4 4 0 1 1 0 8h-1",key:"jx4kbh"}],["path",{d:"M3 8h14v9a4 4 0 0 1-4 4H7a4 4 0 0 1-4-4Z",key:"1bxrl0"}],["line",{x1:"6",x2:"6",y1:"2",y2:"4",key:"1cr9l3"}],["line",{x1:"10",x2:"10",y1:"2",y2:"4",key:"170wym"}],["line",{x1:"14",x2:"14",y1:"2",y2:"4",key:"1c5f70"}]]),XU=Jt("Download",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"7 10 12 15 17 10",key:"2ggqvy"}],["line",{x1:"12",x2:"12",y1:"15",y2:"3",key:"1vk2je"}]]),ZU=Jt("Eraser",[["path",{d:"m7 21-4.3-4.3c-1-1-1-2.5 0-3.4l9.6-9.6c1-1 2.5-1 3.4 0l5.6 5.6c1 1 1 2.5 0 3.4L13 21",key:"182aya"}],["path",{d:"M22 21H7",key:"t4ddhn"}],["path",{d:"m5 11 9 9",key:"1mo9qw"}]]),qU=Jt("Expand",[["path",{d:"m21 21-6-6m6 6v-4.8m0 4.8h-4.8",key:"1c15vz"}],["path",{d:"M3 16.2V21m0 0h4.8M3 21l6-6",key:"1fsnz2"}],["path",{d:"M21 7.8V3m0 0h-4.8M21 3l-6 6",key:"hawz9i"}],["path",{d:"M3 7.8V3m0 0h4.8M3 3l6 6",key:"u9ee12"}]]),QU=Jt("Eye",[["path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z",key:"rwhkz3"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]),JU=Jt("FolderClosed",[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}],["path",{d:"M2 10h20",key:"1ir3d8"}]]),XT=Jt("Fullscreen",[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}],["rect",{width:"10",height:"8",x:"7",y:"8",rx:"1",key:"vys8me"}]]),eV=Jt("Image",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]]),tV=Jt("Keyboard",[["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",ry:"2",key:"15u882"}],["path",{d:"M6 8h.001",key:"1ej0i3"}],["path",{d:"M10 8h.001",key:"1x2st2"}],["path",{d:"M14 8h.001",key:"1vkmyp"}],["path",{d:"M18 8h.001",key:"kfsenl"}],["path",{d:"M8 12h.001",key:"1sjpby"}],["path",{d:"M12 12h.001",key:"al75ts"}],["path",{d:"M16 12h.001",key:"931bgk"}],["path",{d:"M7 16h10",key:"wp8him"}]]),nV=Jt("MousePointerClick",[["path",{d:"m9 9 5 12 1.8-5.2L21 14Z",key:"1b76lo"}],["path",{d:"M7.2 2.2 8 5.1",key:"1cfko1"}],["path",{d:"m5.1 8-2.9-.8",key:"1go3kf"}],["path",{d:"M14 4.1 12 6",key:"ita8i4"}],["path",{d:"m6 12-1.9 2",key:"mnht97"}]]),rV=Jt("Redo",[["path",{d:"M21 7v6h-6",key:"3ptur4"}],["path",{d:"M3 17a9 9 0 0 1 9-9 9 9 0 0 1 6 2.3l3 2.7",key:"1kgawr"}]]),oV=Jt("RotateCw",[["path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8",key:"1p45f6"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}]]),iV=Jt("Settings",[["path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z",key:"1qme2f"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]),VC=Jt("Slice",[["path",{d:"m8 14-6 6h9v-3",key:"zo3j9a"}],["path",{d:"M18.37 3.63 8 14l3 3L21.37 6.63a2.12 2.12 0 1 0-3-3Z",key:"1dzx0j"}]]),WC=Jt("Smile",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 14s1.5 2 4 2 4-2 4-2",key:"1y1vjs"}],["line",{x1:"9",x2:"9.01",y1:"9",y2:"9",key:"yxxnd0"}],["line",{x1:"15",x2:"15.01",y1:"9",y2:"9",key:"1p4y9e"}]]),sV=Jt("Undo",[["path",{d:"M3 7v6h6",key:"1v2h90"}],["path",{d:"M21 17a9 9 0 0 0-9-9 9 9 0 0 0-6 2.3L3 13",key:"1r6uu6"}]]),ZT=Jt("Upload",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"17 8 12 3 7 8",key:"t8dd8p"}],["line",{x1:"12",x2:"12",y1:"3",y2:"15",key:"widbto"}]]);function aV(e,t){const[n,r]=f.useState(e);return f.useEffect(()=>{const o=setTimeout(()=>{r(e)},t);return()=>{clearTimeout(o)}},[e,t]),n}function u1(e){const[t,n]=f.useState(()=>typeof e=="boolean"?e:!!e),r=f.useCallback(o=>n(typeof o=="boolean"?o:i=>!i),[]);return[t,r]}const w0="focusScope.autoFocusOnMount",x0="focusScope.autoFocusOnUnmount",HC={bubbles:!1,cancelable:!0},Hm=f.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:o,onUnmountAutoFocus:i,...s}=e,[l,u]=f.useState(null),d=Ft(o),h=Ft(i),m=f.useRef(null),g=Be(t,_=>u(_)),y=f.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;f.useEffect(()=>{if(r){let b=function(M){if(y.paused||!l)return;const A=M.target;l.contains(A)?m.current=A:Hi(m.current,{select:!0})},E=function(M){if(y.paused||!l)return;const A=M.relatedTarget;A!==null&&(l.contains(A)||Hi(m.current,{select:!0}))},k=function(M){if(document.activeElement===document.body)for(const O of M)O.removedNodes.length>0&&Hi(l)};var _=b,C=E,S=k;document.addEventListener("focusin",b),document.addEventListener("focusout",E);const P=new MutationObserver(k);return l&&P.observe(l,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",b),document.removeEventListener("focusout",E),P.disconnect()}}},[r,l,y.paused]),f.useEffect(()=>{if(l){YC.add(y);const _=document.activeElement;if(!l.contains(_)){const S=new CustomEvent(w0,HC);l.addEventListener(w0,d),l.dispatchEvent(S),S.defaultPrevented||(lV(pV(qT(l)),{select:!0}),document.activeElement===_&&Hi(l))}return()=>{l.removeEventListener(w0,d),setTimeout(()=>{const S=new CustomEvent(x0,HC);l.addEventListener(x0,h),l.dispatchEvent(S),S.defaultPrevented||Hi(_??document.body,{select:!0}),l.removeEventListener(x0,h),YC.remove(y)},0)}}},[l,d,h,y]);const x=f.useCallback(_=>{if(!n&&!r||y.paused)return;const C=_.key==="Tab"&&!_.altKey&&!_.ctrlKey&&!_.metaKey,S=document.activeElement;if(C&&S){const b=_.currentTarget,[E,k]=cV(b);E&&k?!_.shiftKey&&S===k?(_.preventDefault(),n&&Hi(E,{select:!0})):_.shiftKey&&S===E&&(_.preventDefault(),n&&Hi(k,{select:!0})):S===b&&_.preventDefault()}},[n,r,y.paused]);return f.createElement(Pe.div,Y({tabIndex:-1},s,{ref:g,onKeyDown:x}))});function lV(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(Hi(r,{select:t}),document.activeElement!==n)return}function cV(e){const t=qT(e),n=KC(t,e),r=KC(t.reverse(),e);return[n,r]}function qT(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const o=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||o?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function KC(e,t){for(const n of e)if(!uV(n,{upTo:t}))return n}function uV(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function dV(e){return e instanceof HTMLInputElement&&"select"in e}function Hi(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&dV(e)&&t&&e.select()}}const YC=fV();function fV(){let e=[];return{add(t){const n=e[0];t!==n&&(n==null||n.pause()),e=GC(e,t),e.unshift(t)},remove(t){var n;e=GC(e,t),(n=e[0])===null||n===void 0||n.resume()}}}function GC(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function pV(e){return e.filter(t=>t.tagName!=="A")}let b0=0;function Km(){f.useEffect(()=>{var e,t;const n=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",(e=n[0])!==null&&e!==void 0?e:XC()),document.body.insertAdjacentElement("beforeend",(t=n[1])!==null&&t!==void 0?t:XC()),b0++,()=>{b0===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(r=>r.remove()),b0--}},[])}function XC(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.cssText="outline: none; opacity: 0; position: fixed; pointer-events: none",e}var Mo=function(){return Mo=Object.assign||function(t){for(var n,r=1,o=arguments.length;r"u")return PV;var t=AV(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])}},MV=tP(),NV=function(e,t,n,r){var o=e.left,i=e.top,s=e.right,l=e.gap;return n===void 0&&(n="margin"),` + .`.concat(mV,` { + overflow: hidden `).concat(r,`; + padding-right: `).concat(l,"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(i,`px; + padding-right: `).concat(s,`px; + margin-left:0; + margin-top:0; + margin-right: `).concat(l,"px ").concat(r,`; + `),n==="padding"&&"padding-right: ".concat(l,"px ").concat(r,";")].filter(Boolean).join(""),` + } + + .`).concat(Wp,` { + right: `).concat(l,"px ").concat(r,`; + } + + .`).concat(Hp,` { + margin-right: `).concat(l,"px ").concat(r,`; + } + + .`).concat(Wp," .").concat(Wp,` { + right: 0 `).concat(r,`; + } + + .`).concat(Hp," .").concat(Hp,` { + margin-right: 0 `).concat(r,`; + } + + body { + `).concat(gV,": ").concat(l,`px; + } +`)},DV=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,o=r===void 0?"margin":r,i=f.useMemo(function(){return OV(o)},[o]);return f.createElement(MV,{styles:NV(i,!t,o,n?"":"!important")})},d1=!1;if(typeof window<"u")try{var ap=Object.defineProperty({},"passive",{get:function(){return d1=!0,!0}});window.addEventListener("test",ap,ap),window.removeEventListener("test",ap,ap)}catch{d1=!1}var qa=d1?{passive:!1}:!1,IV=function(e){return e.tagName==="TEXTAREA"},nP=function(e,t){var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!IV(e)&&n[t]==="visible")},LV=function(e){return nP(e,"overflowY")},FV=function(e){return nP(e,"overflowX")},qC=function(e,t){var n=t;do{typeof ShadowRoot<"u"&&n instanceof ShadowRoot&&(n=n.host);var r=rP(e,n);if(r){var o=oP(e,n),i=o[1],s=o[2];if(i>s)return!0}n=n.parentNode}while(n&&n!==document.body);return!1},jV=function(e){var t=e.scrollTop,n=e.scrollHeight,r=e.clientHeight;return[t,n,r]},zV=function(e){var t=e.scrollLeft,n=e.scrollWidth,r=e.clientWidth;return[t,n,r]},rP=function(e,t){return e==="v"?LV(t):FV(t)},oP=function(e,t){return e==="v"?jV(t):zV(t)},BV=function(e,t){return e==="h"&&t==="rtl"?-1:1},UV=function(e,t,n,r,o){var i=BV(e,window.getComputedStyle(t).direction),s=i*r,l=n.target,u=t.contains(l),d=!1,h=s>0,m=0,g=0;do{var y=oP(e,l),x=y[0],_=y[1],C=y[2],S=_-C-i*x;(x||S)&&rP(e,l)&&(m+=S,g+=x),l=l.parentNode}while(!u&&l!==document.body||u&&(t.contains(l)||t===l));return(h&&(o&&m===0||!o&&s>m)||!h&&(o&&g===0||!o&&-s>g))&&(d=!0),d},lp=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},QC=function(e){return[e.deltaX,e.deltaY]},JC=function(e){return e&&"current"in e?e.current:e},VV=function(e,t){return e[0]===t[0]&&e[1]===t[1]},WV=function(e){return` + .block-interactivity-`.concat(e,` {pointer-events: none;} + .allow-interactivity-`).concat(e,` {pointer-events: all;} +`)},HV=0,Qa=[];function KV(e){var t=f.useRef([]),n=f.useRef([0,0]),r=f.useRef(),o=f.useState(HV++)[0],i=f.useState(function(){return tP()})[0],s=f.useRef(e);f.useEffect(function(){s.current=e},[e]),f.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(o));var _=hV([e.lockRef.current],(e.shards||[]).map(JC),!0).filter(Boolean);return _.forEach(function(C){return C.classList.add("allow-interactivity-".concat(o))}),function(){document.body.classList.remove("block-interactivity-".concat(o)),_.forEach(function(C){return C.classList.remove("allow-interactivity-".concat(o))})}}},[e.inert,e.lockRef.current,e.shards]);var l=f.useCallback(function(_,C){if("touches"in _&&_.touches.length===2)return!s.current.allowPinchZoom;var S=lp(_),b=n.current,E="deltaX"in _?_.deltaX:b[0]-S[0],k="deltaY"in _?_.deltaY:b[1]-S[1],P,M=_.target,A=Math.abs(E)>Math.abs(k)?"h":"v";if("touches"in _&&A==="h"&&M.type==="range")return!1;var O=qC(A,M);if(!O)return!0;if(O?P=A:(P=A==="v"?"h":"v",O=qC(A,M)),!O)return!1;if(!r.current&&"changedTouches"in _&&(E||k)&&(r.current=P),!P)return!0;var F=r.current||P;return UV(F,C,_,F==="h"?E:k,!0)},[]),u=f.useCallback(function(_){var C=_;if(!(!Qa.length||Qa[Qa.length-1]!==i)){var S="deltaY"in C?QC(C):lp(C),b=t.current.filter(function(P){return P.name===C.type&&P.target===C.target&&VV(P.delta,S)})[0];if(b&&b.should){C.cancelable&&C.preventDefault();return}if(!b){var E=(s.current.shards||[]).map(JC).filter(Boolean).filter(function(P){return P.contains(C.target)}),k=E.length>0?l(C,E[0]):!s.current.noIsolation;k&&C.cancelable&&C.preventDefault()}}},[]),d=f.useCallback(function(_,C,S,b){var E={name:_,delta:C,target:S,should:b};t.current.push(E),setTimeout(function(){t.current=t.current.filter(function(k){return k!==E})},1)},[]),h=f.useCallback(function(_){n.current=lp(_),r.current=void 0},[]),m=f.useCallback(function(_){d(_.type,QC(_),_.target,l(_,e.lockRef.current))},[]),g=f.useCallback(function(_){d(_.type,lp(_),_.target,l(_,e.lockRef.current))},[]);f.useEffect(function(){return Qa.push(i),e.setCallbacks({onScrollCapture:m,onWheelCapture:m,onTouchMoveCapture:g}),document.addEventListener("wheel",u,qa),document.addEventListener("touchmove",u,qa),document.addEventListener("touchstart",h,qa),function(){Qa=Qa.filter(function(_){return _!==i}),document.removeEventListener("wheel",u,qa),document.removeEventListener("touchmove",u,qa),document.removeEventListener("touchstart",h,qa)}},[]);var y=e.removeScrollBar,x=e.inert;return f.createElement(f.Fragment,null,x?f.createElement(i,{styles:WV(o)}):null,y?f.createElement(DV,{gapMode:"margin"}):null)}const YV=SV(eP,KV);var iP=f.forwardRef(function(e,t){return f.createElement(Ym,Mo({},e,{ref:t,sideCar:YV}))});iP.classNames=Ym.classNames;const Gm=iP;var GV=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},Ja=new WeakMap,cp=new WeakMap,up={},E0=0,sP=function(e){return e&&(e.host||sP(e.parentNode))},XV=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=sP(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})},ZV=function(e,t,n,r){var o=XV(t,Array.isArray(e)?e:[e]);up[n]||(up[n]=new WeakMap);var i=up[n],s=[],l=new Set,u=new Set(o),d=function(m){!m||l.has(m)||(l.add(m),d(m.parentNode))};o.forEach(d);var h=function(m){!m||u.has(m)||Array.prototype.forEach.call(m.children,function(g){if(l.has(g))h(g);else{var y=g.getAttribute(r),x=y!==null&&y!=="false",_=(Ja.get(g)||0)+1,C=(i.get(g)||0)+1;Ja.set(g,_),i.set(g,C),s.push(g),_===1&&x&&cp.set(g,!0),C===1&&g.setAttribute(n,"true"),x||g.setAttribute(r,"true")}})};return h(t),l.clear(),E0++,function(){s.forEach(function(m){var g=Ja.get(m)-1,y=i.get(m)-1;Ja.set(m,g),i.set(m,y),g||(cp.has(m)||m.removeAttribute(r),cp.delete(m)),y||m.removeAttribute(n)}),E0--,E0||(Ja=new WeakMap,Ja=new WeakMap,cp=new WeakMap,up={})}},Xm=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),o=t||GV(e);return o?(r.push.apply(r,Array.from(o.querySelectorAll("[aria-live]"))),ZV(r,o,n,"aria-hidden")):function(){return null}};const aP="Dialog",[lP,cP]=An(aP),[qV,bo]=lP(aP),QV=e=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:o,onOpenChange:i,modal:s=!0}=e,l=f.useRef(null),u=f.useRef(null),[d=!1,h]=Zr({prop:r,defaultProp:o,onChange:i});return f.createElement(qV,{scope:t,triggerRef:l,contentRef:u,contentId:nr(),titleId:nr(),descriptionId:nr(),open:d,onOpenChange:h,onOpenToggle:f.useCallback(()=>h(m=>!m),[h]),modal:s},n)},JV="DialogTrigger",uP=f.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=bo(JV,n),i=Be(t,o.triggerRef);return f.createElement(Pe.button,Y({type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":_x(o.open)},r,{ref:i,onClick:ue(e.onClick,o.onOpenToggle)}))}),dP="DialogPortal",[eW,fP]=lP(dP,{forceMount:void 0}),tW=e=>{const{__scopeDialog:t,forceMount:n,children:r,container:o}=e,i=bo(dP,t);return f.createElement(eW,{scope:t,forceMount:n},f.Children.map(r,s=>f.createElement(bn,{present:n||i.open},f.createElement(Md,{asChild:!0,container:o},s))))},f1="DialogOverlay",nW=f.forwardRef((e,t)=>{const n=fP(f1,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,i=bo(f1,e.__scopeDialog);return i.modal?f.createElement(bn,{present:r||i.open},f.createElement(rW,Y({},o,{ref:t}))):null}),rW=f.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=bo(f1,n);return f.createElement(Gm,{as:Wo,allowPinchZoom:!0,shards:[o.contentRef]},f.createElement(Pe.div,Y({"data-state":_x(o.open)},r,{ref:t,style:{pointerEvents:"auto",...r.style}})))}),oc="DialogContent",oW=f.forwardRef((e,t)=>{const n=fP(oc,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,i=bo(oc,e.__scopeDialog);return f.createElement(bn,{present:r||i.open},i.modal?f.createElement(iW,Y({},o,{ref:t})):f.createElement(sW,Y({},o,{ref:t})))}),iW=f.forwardRef((e,t)=>{const n=bo(oc,e.__scopeDialog),r=f.useRef(null),o=Be(t,n.contentRef,r);return f.useEffect(()=>{const i=r.current;if(i)return Xm(i)},[]),f.createElement(pP,Y({},e,{ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:ue(e.onCloseAutoFocus,i=>{var s;i.preventDefault(),(s=n.triggerRef.current)===null||s===void 0||s.focus()}),onPointerDownOutside:ue(e.onPointerDownOutside,i=>{const s=i.detail.originalEvent,l=s.button===0&&s.ctrlKey===!0;(s.button===2||l)&&i.preventDefault()}),onFocusOutside:ue(e.onFocusOutside,i=>i.preventDefault())}))}),sW=f.forwardRef((e,t)=>{const n=bo(oc,e.__scopeDialog),r=f.useRef(!1),o=f.useRef(!1);return f.createElement(pP,Y({},e,{ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var s;if((s=e.onCloseAutoFocus)===null||s===void 0||s.call(e,i),!i.defaultPrevented){var l;r.current||(l=n.triggerRef.current)===null||l===void 0||l.focus(),i.preventDefault()}r.current=!1,o.current=!1},onInteractOutside:i=>{var s,l;(s=e.onInteractOutside)===null||s===void 0||s.call(e,i),i.defaultPrevented||(r.current=!0,i.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const u=i.target;((l=n.triggerRef.current)===null||l===void 0?void 0:l.contains(u))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&o.current&&i.preventDefault()}}))}),pP=f.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:i,...s}=e,l=bo(oc,n),u=f.useRef(null),d=Be(t,u);return Km(),f.createElement(f.Fragment,null,f.createElement(Hm,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:i},f.createElement(yc,Y({role:"dialog",id:l.contentId,"aria-describedby":l.descriptionId,"aria-labelledby":l.titleId,"data-state":_x(l.open)},s,{ref:d,onDismiss:()=>l.onOpenChange(!1)}))),!1)}),hP="DialogTitle",aW=f.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=bo(hP,n);return f.createElement(Pe.h2,Y({id:o.titleId},r,{ref:t}))}),lW="DialogDescription",mP=f.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=bo(lW,n);return f.createElement(Pe.p,Y({id:o.descriptionId},r,{ref:t}))}),cW="DialogClose",uW=f.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=bo(cW,n);return f.createElement(Pe.button,Y({type:"button"},r,{ref:t,onClick:ue(e.onClick,()=>o.onOpenChange(!1))}))});function _x(e){return e?"open":"closed"}const dW="DialogTitleWarning",[fW,vte]=pB(dW,{contentName:oc,titleName:hP,docsSlug:"dialog"}),Sx=QV,gP=uP,Ex=tW,Nd=nW,Dd=oW,Id=aW,Ld=mP,Cx=uW,Zm=Sx,$x=gP,pW=Ex,vP=f.forwardRef(({className:e,...t},n)=>v.jsx(Nd,{ref:n,className:Ce("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t}));vP.displayName=Nd.displayName;const Fd=f.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(pW,{children:[v.jsx(vP,{}),v.jsxs(Dd,{ref:r,className:Ce("fixed left-[50%] top-[50%] z-50 flex flex-col w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",e,"outline-none"),onCloseAutoFocus:o=>o.preventDefault(),...n,children:[t,v.jsxs(Cx,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[v.jsx(yT,{className:"h-4 w-4"}),v.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Fd.displayName=Dd.displayName;const yP=({className:e,...t})=>v.jsx("div",{className:Ce("flex flex-col space-y-1.5 text-center sm:text-left",e),...t});yP.displayName="DialogHeader";const jd=f.forwardRef(({className:e,...t},n)=>v.jsx(Id,{ref:n,className:Ce("text-2xl font-semibold leading-none tracking-tight",e),...t}));jd.displayName=Id.displayName;const hW=f.forwardRef(({className:e,...t},n)=>v.jsx(Ld,{ref:n,className:Ce("text-sm text-muted-foreground",e),...t}));hW.displayName=Ld.displayName;function p1(){return p1=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 _W=function(t,n,r){r===void 0&&(r=!1);var o=n.alt,i=n.meta,s=n.mod,l=n.shift,u=n.ctrl,d=n.keys,h=t.key,m=t.code,g=t.ctrlKey,y=t.metaKey,x=t.shiftKey,_=t.altKey,C=ss(m),S=h.toLowerCase();if(!r){if(o===!_&&S!=="alt"||l===!x&&S!=="shift")return!1;if(s){if(!y&&!g)return!1}else if(i===!y&&S!=="meta"&&S!=="os"||u===!g&&S!=="ctrl"&&S!=="control")return!1}return d&&d.length===1&&(d.includes(S)||d.includes(C))?!0:d?vW(d):!d},SW=f.createContext(void 0),EW=function(){return f.useContext(SW)};function SP(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&&SP(e[r],t[r])},!0):e===t}var CW=f.createContext({hotkeys:[],enabledScopes:[],toggleScope:function(){},enableScope:function(){},disableScope:function(){}}),$W=function(){return f.useContext(CW)};function kW(e){var t=f.useRef(void 0);return SP(t.current,e)||(t.current=e),t.current}var e2=function(t){t.stopPropagation(),t.preventDefault(),t.stopImmediatePropagation()},RW=typeof window<"u"?f.useLayoutEffect:f.useEffect;function TW(e,t,n,r){var o=f.useRef(null),i=f.useRef(!1),s=n instanceof Array?r instanceof Array?void 0:r:n,l=kx(e)?e.join(s==null?void 0:s.splitKey):e,u=n instanceof Array?n:r instanceof Array?r:void 0,d=f.useCallback(t,u??[]),h=f.useRef(d);u?h.current=d:h.current=t;var m=kW(s),g=$W(),y=g.enabledScopes,x=EW();return RW(function(){if(!((m==null?void 0:m.enabled)===!1||!bW(y,m==null?void 0:m.scopes))){var _=function(k,P){var M;if(P===void 0&&(P=!1),!(xW(k)&&!_P(k,m==null?void 0:m.enableOnFormTags))&&!(m!=null&&m.ignoreEventWhen!=null&&m.ignoreEventWhen(k))){if(o.current!==null&&document.activeElement!==o.current&&!o.current.contains(document.activeElement)){e2(k);return}(M=k.target)!=null&&M.isContentEditable&&!(m!=null&&m.enableOnContentEditable)||C0(l,m==null?void 0:m.splitKey).forEach(function(A){var O,F=$0(A,m==null?void 0:m.combinationKey);if(_W(k,F,m==null?void 0:m.ignoreModifiers)||(O=F.keys)!=null&&O.includes("*")){if(P&&i.current)return;if(yW(k,F,m==null?void 0:m.preventDefault),!wW(k,F,m==null?void 0:m.enabled)){e2(k);return}h.current(k,F),P||(i.current=!0)}})}},C=function(k){k.key!==void 0&&(xP(ss(k.code)),((m==null?void 0:m.keydown)===void 0&&(m==null?void 0:m.keyup)!==!0||m!=null&&m.keydown)&&_(k))},S=function(k){k.key!==void 0&&(bP(ss(k.code)),i.current=!1,m!=null&&m.keyup&&_(k,!0))},b=o.current||(s==null?void 0:s.document)||document;return b.addEventListener("keyup",S),b.addEventListener("keydown",C),x&&C0(l,m==null?void 0:m.splitKey).forEach(function(E){return x.addHotkey($0(E,m==null?void 0:m.combinationKey,m==null?void 0:m.description))}),function(){b.removeEventListener("keyup",S),b.removeEventListener("keydown",C),x&&C0(l,m==null?void 0:m.splitKey).forEach(function(E){return x.removeHotkey($0(E,m==null?void 0:m.combinationKey,m==null?void 0:m.description))})}}},[l,m,y]),o}const Zn=(e,t,n)=>{const r=bt(i=>i.disableShortCuts);return TW(e,t,{enabled:!r},n)};function ur(e){const{content:t,keys:n}=e;return v.jsxs("div",{className:"flex justify-between",children:[v.jsx("div",{children:t}),v.jsx("div",{className:"flex gap-[8px]",children:n.map(r=>v.jsx("div",{className:"border px-2 py-1 rounded-lg",children:r},r))})]})}const PW=function(){return/macintosh|mac os x/i.test(navigator.userAgent)},dp=()=>PW()?"Cmd":"Ctrl";function AW(){const[e,t]=u1(!1);return Zn("h",()=>{t()}),v.jsxs(Zm,{open:e,onOpenChange:t,children:[v.jsx($x,{asChild:!0,children:v.jsx(vn,{tooltip:"Hotkeys",children:v.jsx(tV,{})})}),v.jsx(Fd,{children:v.jsxs(yP,{children:[v.jsx(jd,{children:"Hotkeys"}),v.jsxs("div",{className:"flex gap-2 flex-col pt-4",children:[v.jsx(ur,{content:"Pan",keys:["Space + Drag"]}),v.jsx(ur,{content:"Reset Zoom/Pan",keys:["Esc"]}),v.jsx(ur,{content:"Decrease Brush Size",keys:["["]}),v.jsx(ur,{content:"Increase Brush Size",keys:["]"]}),v.jsx(ur,{content:"View Original Image",keys:["Hold Tab"]}),v.jsx(ur,{content:"Undo",keys:[dp(),"Z"]}),v.jsx(ur,{content:"Redo",keys:[dp(),"Shift","Z"]}),v.jsx(ur,{content:"Copy Result",keys:[dp(),"C"]}),v.jsx(ur,{content:"Paste Image",keys:[dp(),"V"]}),v.jsx(ur,{content:"Trigger Manually Inpainting",keys:["Shift","R"]}),v.jsx(ur,{content:"Toggle Hotkeys Dialog",keys:["H"]}),v.jsx(ur,{content:"Toggle Settings Dialog",keys:["S"]}),v.jsx(ur,{content:"Toggle File Manager",keys:["F"]})]})]})})]})}function Rx(e){const[t]=f.useState(new Image),[n,r]=f.useState(!1);return f.useEffect(()=>{if(e)return t.onload=()=>{r(!0)},r(!1),t.src=URL.createObjectURL(e),()=>{t.onload=null}},[e,t]),[t,n]}const EP="Popover",[CP,yte]=An(EP,[Ns]),Tx=Ns(),[OW,bc]=CP(EP),MW=e=>{const{__scopePopover:t,children:n,open:r,defaultOpen:o,onOpenChange:i,modal:s=!1}=e,l=Tx(t),u=f.useRef(null),[d,h]=f.useState(!1),[m=!1,g]=Zr({prop:r,defaultProp:o,onChange:i});return f.createElement(Od,l,f.createElement(OW,{scope:t,contentId:nr(),triggerRef:u,open:m,onOpenChange:g,onOpenToggle:f.useCallback(()=>g(y=>!y),[g]),hasCustomAnchor:d,onCustomAnchorAdd:f.useCallback(()=>h(!0),[]),onCustomAnchorRemove:f.useCallback(()=>h(!1),[]),modal:s},n))},NW="PopoverTrigger",DW=f.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,o=bc(NW,n),i=Tx(n),s=Be(t,o.triggerRef),l=f.createElement(Pe.button,Y({type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":RP(o.open)},r,{ref:s,onClick:ue(e.onClick,o.onOpenToggle)}));return o.hasCustomAnchor?l:f.createElement(zm,Y({asChild:!0},i),l)}),$P="PopoverPortal",[IW,LW]=CP($P,{forceMount:void 0}),FW=e=>{const{__scopePopover:t,forceMount:n,children:r,container:o}=e,i=bc($P,t);return f.createElement(IW,{scope:t,forceMount:n},f.createElement(bn,{present:n||i.open},f.createElement(Md,{asChild:!0,container:o},r)))},od="PopoverContent",jW=f.forwardRef((e,t)=>{const n=LW(od,e.__scopePopover),{forceMount:r=n.forceMount,...o}=e,i=bc(od,e.__scopePopover);return f.createElement(bn,{present:r||i.open},i.modal?f.createElement(zW,Y({},o,{ref:t})):f.createElement(BW,Y({},o,{ref:t})))}),zW=f.forwardRef((e,t)=>{const n=bc(od,e.__scopePopover),r=f.useRef(null),o=Be(t,r),i=f.useRef(!1);return f.useEffect(()=>{const s=r.current;if(s)return Xm(s)},[]),f.createElement(Gm,{as:Wo,allowPinchZoom:!0},f.createElement(kP,Y({},e,{ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:ue(e.onCloseAutoFocus,s=>{var l;s.preventDefault(),i.current||(l=n.triggerRef.current)===null||l===void 0||l.focus()}),onPointerDownOutside:ue(e.onPointerDownOutside,s=>{const l=s.detail.originalEvent,u=l.button===0&&l.ctrlKey===!0,d=l.button===2||u;i.current=d},{checkForDefaultPrevented:!1}),onFocusOutside:ue(e.onFocusOutside,s=>s.preventDefault(),{checkForDefaultPrevented:!1})})))}),BW=f.forwardRef((e,t)=>{const n=bc(od,e.__scopePopover),r=f.useRef(!1),o=f.useRef(!1);return f.createElement(kP,Y({},e,{ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var s;if((s=e.onCloseAutoFocus)===null||s===void 0||s.call(e,i),!i.defaultPrevented){var l;r.current||(l=n.triggerRef.current)===null||l===void 0||l.focus(),i.preventDefault()}r.current=!1,o.current=!1},onInteractOutside:i=>{var s,l;(s=e.onInteractOutside)===null||s===void 0||s.call(e,i),i.defaultPrevented||(r.current=!0,i.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const u=i.target;((l=n.triggerRef.current)===null||l===void 0?void 0:l.contains(u))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&o.current&&i.preventDefault()}}))}),kP=f.forwardRef((e,t)=>{const{__scopePopover:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:i,disableOutsidePointerEvents:s,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:d,onInteractOutside:h,...m}=e,g=bc(od,n),y=Tx(n);return Km(),f.createElement(Hm,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:i},f.createElement(yc,{asChild:!0,disableOutsidePointerEvents:s,onInteractOutside:h,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:d,onDismiss:()=>g.onOpenChange(!1)},f.createElement(Bm,Y({"data-state":RP(g.open),role:"dialog",id:g.contentId},y,m,{ref:t,style:{...m.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}}))))});function RP(e){return e?"open":"closed"}const UW=MW,VW=DW,WW=FW,TP=jW,HW=UW,KW=VW,PP=f.forwardRef(({className:e,align:t="center",sideOffset:n=4,...r},o)=>v.jsx(WW,{children:v.jsx(TP,{ref:o,align:t,tabIndex:-1,sideOffset:n,className:Ce("z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...r})}));PP.displayName=TP.displayName;function YW(){var e=f.useRef(!0);return e.current?(e.current=!1,!0):e.current}var GW=function(e,t){var n=YW();f.useEffect(function(){if(!n)return e()},t)};const XW=GW;var ZW=function(){};function Px(e){for(var t=[],n=1;n{const[e,t,n,r,o,i]=bt(g=>[g.getIsProcessing(),g.settings.prompt,g.updateSettings,g.runInpainting,g.showPrevMask,g.hidePrevMask]),s=f.useRef(null);OP(s,()=>{s!=null&&s.current&&s.current.blur()});const l=g=>{g.preventDefault(),g.stopPropagation();const y=g.target;n({prompt:y.value})},u=()=>{e||r()},d=g=>{g.key==="Enter"&&!e&&u()},h=()=>{o()},m=()=>{i()};return v.jsxs("div",{className:"flex gap-4 items-center",children:[v.jsx(Pd,{ref:s,className:"min-w-[500px]",value:t,onInput:l,onKeyUp:d,placeholder:"I want to repaint of..."}),v.jsx(yn,{size:"sm",onClick:u,disabled:e,onMouseEnter:h,onMouseLeave:m,children:"Paint"})]})};var Lh={exports:{}};/** + * @license + * Lodash + * Copyright OpenJS Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */Lh.exports;(function(e,t){(function(){var n,r="4.17.21",o=200,i="Unsupported core-js use. Try https://npms.io/search?q=ponyfill.",s="Expected a function",l="Invalid `variable` option passed into `_.template`",u="__lodash_hash_undefined__",d=500,h="__lodash_placeholder__",m=1,g=2,y=4,x=1,_=2,C=1,S=2,b=4,E=8,k=16,P=32,M=64,A=128,O=256,F=512,V=30,J="...",G=800,ae=16,U=1,te=2,L=3,ie=1/0,K=9007199254740991,Q=17976931348623157e292,W=NaN,le=4294967295,ge=le-1,Ve=le>>>1,Ue=[["ary",A],["bind",C],["bindKey",S],["curry",E],["curryRight",k],["flip",F],["partial",P],["partialRight",M],["rearg",O]],We="[object Arguments]",Me="[object Array]",fe="[object AsyncFunction]",xe="[object Boolean]",$e="[object Date]",Ae="[object DOMException]",Oe="[object Error]",je="[object Function]",Ot="[object GeneratorFunction]",ct="[object Map]",Kt="[object Number]",Er="[object Null]",gt="[object Object]",js="[object Promise]",I="[object Proxy]",X="[object RegExp]",Z="[object Set]",we="[object String]",he="[object Symbol]",de="[object Undefined]",ke="[object WeakMap]",ft="[object WeakSet]",pt="[object ArrayBuffer]",_n="[object DataView]",Cr="[object Float32Array]",ki="[object Float64Array]",_o="[object Int8Array]",Vn="[object Int16Array]",Da="[object Int32Array]",Ri="[object Uint8Array]",zs="[object Uint8ClampedArray]",Ti="[object Uint16Array]",$c="[object Uint32Array]",yg=/\b__p \+= '';/g,wg=/\b(__p \+=) '' \+/g,Kd=/(__e\(.*?\)|\b__t\)) \+\n'';/g,kc=/&(?:amp|lt|gt|quot|#39);/g,Rc=/[&<>"']/g,Tc=RegExp(kc.source),xg=RegExp(Rc.source),Pc=/<%-([\s\S]+?)%>/g,Yd=/<%([\s\S]+?)%>/g,Ac=/<%=([\s\S]+?)%>/g,bg=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,_g=/^\w*$/,Sg=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,H=/[\\^$.*+?()[\]{}|]/g,Ge=RegExp(H.source),st=/^\s+/,Qr=/\s/,an=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,Gd=/\{\n\/\* \[wrapped with (.+)\] \*/,oO=/,? & /,iO=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,sO=/[()=,{}\[\]\/\s]/,aO=/\\(\\)?/g,lO=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,db=/\w*$/,cO=/^[-+]0x[0-9a-f]+$/i,uO=/^0b[01]+$/i,dO=/^\[object .+?Constructor\]$/,fO=/^0o[0-7]+$/i,pO=/^(?:0|[1-9]\d*)$/,hO=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,Xd=/($^)/,mO=/['\n\r\u2028\u2029\\]/g,Zd="\\ud800-\\udfff",gO="\\u0300-\\u036f",vO="\\ufe20-\\ufe2f",yO="\\u20d0-\\u20ff",fb=gO+vO+yO,pb="\\u2700-\\u27bf",hb="a-z\\xdf-\\xf6\\xf8-\\xff",wO="\\xac\\xb1\\xd7\\xf7",xO="\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf",bO="\\u2000-\\u206f",_O=" \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",mb="A-Z\\xc0-\\xd6\\xd8-\\xde",gb="\\ufe0e\\ufe0f",vb=wO+xO+bO+_O,Eg="['’]",SO="["+Zd+"]",yb="["+vb+"]",qd="["+fb+"]",wb="\\d+",EO="["+pb+"]",xb="["+hb+"]",bb="[^"+Zd+vb+wb+pb+hb+mb+"]",Cg="\\ud83c[\\udffb-\\udfff]",CO="(?:"+qd+"|"+Cg+")",_b="[^"+Zd+"]",$g="(?:\\ud83c[\\udde6-\\uddff]){2}",kg="[\\ud800-\\udbff][\\udc00-\\udfff]",Ia="["+mb+"]",Sb="\\u200d",Eb="(?:"+xb+"|"+bb+")",$O="(?:"+Ia+"|"+bb+")",Cb="(?:"+Eg+"(?:d|ll|m|re|s|t|ve))?",$b="(?:"+Eg+"(?:D|LL|M|RE|S|T|VE))?",kb=CO+"?",Rb="["+gb+"]?",kO="(?:"+Sb+"(?:"+[_b,$g,kg].join("|")+")"+Rb+kb+")*",RO="\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",TO="\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])",Tb=Rb+kb+kO,PO="(?:"+[EO,$g,kg].join("|")+")"+Tb,AO="(?:"+[_b+qd+"?",qd,$g,kg,SO].join("|")+")",OO=RegExp(Eg,"g"),MO=RegExp(qd,"g"),Rg=RegExp(Cg+"(?="+Cg+")|"+AO+Tb,"g"),NO=RegExp([Ia+"?"+xb+"+"+Cb+"(?="+[yb,Ia,"$"].join("|")+")",$O+"+"+$b+"(?="+[yb,Ia+Eb,"$"].join("|")+")",Ia+"?"+Eb+"+"+Cb,Ia+"+"+$b,TO,RO,wb,PO].join("|"),"g"),DO=RegExp("["+Sb+Zd+fb+gb+"]"),IO=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,LO=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],FO=-1,kt={};kt[Cr]=kt[ki]=kt[_o]=kt[Vn]=kt[Da]=kt[Ri]=kt[zs]=kt[Ti]=kt[$c]=!0,kt[We]=kt[Me]=kt[pt]=kt[xe]=kt[_n]=kt[$e]=kt[Oe]=kt[je]=kt[ct]=kt[Kt]=kt[gt]=kt[X]=kt[Z]=kt[we]=kt[ke]=!1;var Et={};Et[We]=Et[Me]=Et[pt]=Et[_n]=Et[xe]=Et[$e]=Et[Cr]=Et[ki]=Et[_o]=Et[Vn]=Et[Da]=Et[ct]=Et[Kt]=Et[gt]=Et[X]=Et[Z]=Et[we]=Et[he]=Et[Ri]=Et[zs]=Et[Ti]=Et[$c]=!0,Et[Oe]=Et[je]=Et[ke]=!1;var jO={À:"A",Á:"A",Â:"A",Ã:"A",Ä:"A",Å:"A",à:"a",á:"a",â:"a",ã:"a",ä:"a",å:"a",Ç:"C",ç:"c",Ð:"D",ð:"d",È:"E",É:"E",Ê:"E",Ë:"E",è:"e",é:"e",ê:"e",ë:"e",Ì:"I",Í:"I",Î:"I",Ï:"I",ì:"i",í:"i",î:"i",ï:"i",Ñ:"N",ñ:"n",Ò:"O",Ó:"O",Ô:"O",Õ:"O",Ö:"O",Ø:"O",ò:"o",ó:"o",ô:"o",õ:"o",ö:"o",ø:"o",Ù:"U",Ú:"U",Û:"U",Ü:"U",ù:"u",ú:"u",û:"u",ü:"u",Ý:"Y",ý:"y",ÿ:"y",Æ:"Ae",æ:"ae",Þ:"Th",þ:"th",ß:"ss",Ā:"A",Ă:"A",Ą:"A",ā:"a",ă:"a",ą:"a",Ć:"C",Ĉ:"C",Ċ:"C",Č:"C",ć:"c",ĉ:"c",ċ:"c",č:"c",Ď:"D",Đ:"D",ď:"d",đ:"d",Ē:"E",Ĕ:"E",Ė:"E",Ę:"E",Ě:"E",ē:"e",ĕ:"e",ė:"e",ę:"e",ě:"e",Ĝ:"G",Ğ:"G",Ġ:"G",Ģ:"G",ĝ:"g",ğ:"g",ġ:"g",ģ:"g",Ĥ:"H",Ħ:"H",ĥ:"h",ħ:"h",Ĩ:"I",Ī:"I",Ĭ:"I",Į:"I",İ:"I",ĩ:"i",ī:"i",ĭ:"i",į:"i",ı:"i",Ĵ:"J",ĵ:"j",Ķ:"K",ķ:"k",ĸ:"k",Ĺ:"L",Ļ:"L",Ľ:"L",Ŀ:"L",Ł:"L",ĺ:"l",ļ:"l",ľ:"l",ŀ:"l",ł:"l",Ń:"N",Ņ:"N",Ň:"N",Ŋ:"N",ń:"n",ņ:"n",ň:"n",ŋ:"n",Ō:"O",Ŏ:"O",Ő:"O",ō:"o",ŏ:"o",ő:"o",Ŕ:"R",Ŗ:"R",Ř:"R",ŕ:"r",ŗ:"r",ř:"r",Ś:"S",Ŝ:"S",Ş:"S",Š:"S",ś:"s",ŝ:"s",ş:"s",š:"s",Ţ:"T",Ť:"T",Ŧ:"T",ţ:"t",ť:"t",ŧ:"t",Ũ:"U",Ū:"U",Ŭ:"U",Ů:"U",Ű:"U",Ų:"U",ũ:"u",ū:"u",ŭ:"u",ů:"u",ű:"u",ų:"u",Ŵ:"W",ŵ:"w",Ŷ:"Y",ŷ:"y",Ÿ:"Y",Ź:"Z",Ż:"Z",Ž:"Z",ź:"z",ż:"z",ž:"z",IJ:"IJ",ij:"ij",Œ:"Oe",œ:"oe",ʼn:"'n",ſ:"s"},zO={"&":"&","<":"<",">":">",'"':""","'":"'"},BO={"&":"&","<":"<",">":">",""":'"',"'":"'"},UO={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},VO=parseFloat,WO=parseInt,Pb=typeof Yc=="object"&&Yc&&Yc.Object===Object&&Yc,HO=typeof self=="object"&&self&&self.Object===Object&&self,fn=Pb||HO||Function("return this")(),Tg=t&&!t.nodeType&&t,Bs=Tg&&!0&&e&&!e.nodeType&&e,Ab=Bs&&Bs.exports===Tg,Pg=Ab&&Pb.process,$r=function(){try{var j=Bs&&Bs.require&&Bs.require("util").types;return j||Pg&&Pg.binding&&Pg.binding("util")}catch{}}(),Ob=$r&&$r.isArrayBuffer,Mb=$r&&$r.isDate,Nb=$r&&$r.isMap,Db=$r&&$r.isRegExp,Ib=$r&&$r.isSet,Lb=$r&&$r.isTypedArray;function or(j,ee,q){switch(q.length){case 0:return j.call(ee);case 1:return j.call(ee,q[0]);case 2:return j.call(ee,q[0],q[1]);case 3:return j.call(ee,q[0],q[1],q[2])}return j.apply(ee,q)}function KO(j,ee,q,_e){for(var Ke=-1,ht=j==null?0:j.length;++Ke-1}function Ag(j,ee,q){for(var _e=-1,Ke=j==null?0:j.length;++_e-1;);return q}function Hb(j,ee){for(var q=j.length;q--&&La(ee,j[q],0)>-1;);return q}function t6(j,ee){for(var q=j.length,_e=0;q--;)j[q]===ee&&++_e;return _e}var n6=Dg(jO),r6=Dg(zO);function o6(j){return"\\"+UO[j]}function i6(j,ee){return j==null?n:j[ee]}function Fa(j){return DO.test(j)}function s6(j){return IO.test(j)}function a6(j){for(var ee,q=[];!(ee=j.next()).done;)q.push(ee.value);return q}function jg(j){var ee=-1,q=Array(j.size);return j.forEach(function(_e,Ke){q[++ee]=[Ke,_e]}),q}function Kb(j,ee){return function(q){return j(ee(q))}}function Oi(j,ee){for(var q=-1,_e=j.length,Ke=0,ht=[];++q<_e;){var en=j[q];(en===ee||en===h)&&(j[q]=h,ht[Ke++]=q)}return ht}function ef(j){var ee=-1,q=Array(j.size);return j.forEach(function(_e){q[++ee]=_e}),q}function l6(j){var ee=-1,q=Array(j.size);return j.forEach(function(_e){q[++ee]=[_e,_e]}),q}function c6(j,ee,q){for(var _e=q-1,Ke=j.length;++_e-1}function G6(a,c){var p=this.__data__,w=gf(p,a);return w<0?(++this.size,p.push([a,c])):p[w][1]=c,this}Xo.prototype.clear=W6,Xo.prototype.delete=H6,Xo.prototype.get=K6,Xo.prototype.has=Y6,Xo.prototype.set=G6;function Zo(a){var c=-1,p=a==null?0:a.length;for(this.clear();++c=c?a:c)),a}function Pr(a,c,p,w,$,T){var N,D=c&m,B=c&g,ne=c&y;if(p&&(N=$?p(a,w,$,T):p(a)),N!==n)return N;if(!It(a))return a;var re=Ye(a);if(re){if(N=QM(a),!D)return Wn(a,N)}else{var se=En(a),me=se==je||se==Ot;if(Fi(a))return R_(a,D);if(se==gt||se==We||me&&!$){if(N=B||me?{}:Y_(a),!D)return B?BM(a,uM(N,a)):zM(a,o_(N,a))}else{if(!Et[se])return $?a:{};N=JM(a,se,D)}}T||(T=new eo);var Re=T.get(a);if(Re)return Re;T.set(a,N),_S(a)?a.forEach(function(Le){N.add(Pr(Le,c,p,Le,a,T))}):xS(a)&&a.forEach(function(Le,nt){N.set(nt,Pr(Le,c,p,nt,a,T))});var Ie=ne?B?dv:uv:B?Kn:ln,Qe=re?n:Ie(a);return kr(Qe||a,function(Le,nt){Qe&&(nt=Le,Le=a[nt]),Fc(N,nt,Pr(Le,c,p,nt,a,T))}),N}function dM(a){var c=ln(a);return function(p){return i_(p,a,c)}}function i_(a,c,p){var w=p.length;if(a==null)return!w;for(a=_t(a);w--;){var $=p[w],T=c[$],N=a[$];if(N===n&&!($ in a)||!T(N))return!1}return!0}function s_(a,c,p){if(typeof a!="function")throw new Rr(s);return Hc(function(){a.apply(n,p)},c)}function jc(a,c,p,w){var $=-1,T=Qd,N=!0,D=a.length,B=[],ne=c.length;if(!D)return B;p&&(c=Mt(c,ir(p))),w?(T=Ag,N=!1):c.length>=o&&(T=Oc,N=!1,c=new Ws(c));e:for(;++$$?0:$+p),w=w===n||w>$?$:qe(w),w<0&&(w+=$),w=p>w?0:ES(w);p0&&p(D)?c>1?pn(D,c-1,p,w,$):Ai($,D):w||($[$.length]=D)}return $}var Kg=N_(),c_=N_(!0);function So(a,c){return a&&Kg(a,c,ln)}function Yg(a,c){return a&&c_(a,c,ln)}function yf(a,c){return Pi(c,function(p){return ti(a[p])})}function Ks(a,c){c=Ii(c,a);for(var p=0,w=c.length;a!=null&&pc}function hM(a,c){return a!=null&&yt.call(a,c)}function mM(a,c){return a!=null&&c in _t(a)}function gM(a,c,p){return a>=Sn(c,p)&&a=120&&re.length>=120)?new Ws(N&&re):n}re=a[0];var se=-1,me=D[0];e:for(;++se<$&&ne.length-1;)D!==a&&cf.call(D,B,1),cf.call(a,B,1);return a}function x_(a,c){for(var p=a?c.length:0,w=p-1;p--;){var $=c[p];if(p==w||$!==T){var T=$;ei($)?cf.call(a,$,1):rv(a,$)}}return a}function ev(a,c){return a+ff(e_()*(c-a+1))}function TM(a,c,p,w){for(var $=-1,T=tn(df((c-a)/(p||1)),0),N=q(T);T--;)N[w?T:++$]=a,a+=p;return N}function tv(a,c){var p="";if(!a||c<1||c>K)return p;do c%2&&(p+=a),c=ff(c/2),c&&(a+=a);while(c);return p}function et(a,c){return yv(Z_(a,c,Yn),a+"")}function PM(a){return r_(Xa(a))}function AM(a,c){var p=Xa(a);return Tf(p,Hs(c,0,p.length))}function Uc(a,c,p,w){if(!It(a))return a;c=Ii(c,a);for(var $=-1,T=c.length,N=T-1,D=a;D!=null&&++$$?0:$+c),p=p>$?$:p,p<0&&(p+=$),$=c>p?0:p-c>>>0,c>>>=0;for(var T=q($);++w<$;)T[w]=a[w+c];return T}function NM(a,c){var p;return Ni(a,function(w,$,T){return p=c(w,$,T),!p}),!!p}function xf(a,c,p){var w=0,$=a==null?w:a.length;if(typeof c=="number"&&c===c&&$<=Ve){for(;w<$;){var T=w+$>>>1,N=a[T];N!==null&&!ar(N)&&(p?N<=c:N=o){var ne=c?null:HM(a);if(ne)return ef(ne);N=!1,$=Oc,B=new Ws}else B=c?[]:D;e:for(;++w=w?a:Ar(a,c,p)}var k_=_6||function(a){return fn.clearTimeout(a)};function R_(a,c){if(c)return a.slice();var p=a.length,w=Xb?Xb(p):new a.constructor(p);return a.copy(w),w}function av(a){var c=new a.constructor(a.byteLength);return new af(c).set(new af(a)),c}function IM(a,c){var p=c?av(a.buffer):a.buffer;return new a.constructor(p,a.byteOffset,a.byteLength)}function LM(a){var c=new a.constructor(a.source,db.exec(a));return c.lastIndex=a.lastIndex,c}function FM(a){return Lc?_t(Lc.call(a)):{}}function T_(a,c){var p=c?av(a.buffer):a.buffer;return new a.constructor(p,a.byteOffset,a.length)}function P_(a,c){if(a!==c){var p=a!==n,w=a===null,$=a===a,T=ar(a),N=c!==n,D=c===null,B=c===c,ne=ar(c);if(!D&&!ne&&!T&&a>c||T&&N&&B&&!D&&!ne||w&&N&&B||!p&&B||!$)return 1;if(!w&&!T&&!ne&&a=D)return B;var ne=p[w];return B*(ne=="desc"?-1:1)}}return a.index-c.index}function A_(a,c,p,w){for(var $=-1,T=a.length,N=p.length,D=-1,B=c.length,ne=tn(T-N,0),re=q(B+ne),se=!w;++D1?p[$-1]:n,N=$>2?p[2]:n;for(T=a.length>3&&typeof T=="function"?($--,T):n,N&&Mn(p[0],p[1],N)&&(T=$<3?n:T,$=1),c=_t(c);++w<$;){var D=p[w];D&&a(c,D,w,T)}return c})}function M_(a,c){return function(p,w){if(p==null)return p;if(!Hn(p))return a(p,w);for(var $=p.length,T=c?$:-1,N=_t(p);(c?T--:++T<$)&&w(N[T],T,N)!==!1;);return p}}function N_(a){return function(c,p,w){for(var $=-1,T=_t(c),N=w(c),D=N.length;D--;){var B=N[a?D:++$];if(p(T[B],B,T)===!1)break}return c}}function UM(a,c,p){var w=c&C,$=Vc(a);function T(){var N=this&&this!==fn&&this instanceof T?$:a;return N.apply(w?p:this,arguments)}return T}function D_(a){return function(c){c=vt(c);var p=Fa(c)?Jr(c):n,w=p?p[0]:c.charAt(0),$=p?Li(p,1).join(""):c.slice(1);return w[a]()+$}}function Ka(a){return function(c){return Og(MS(OS(c).replace(OO,"")),a,"")}}function Vc(a){return function(){var c=arguments;switch(c.length){case 0:return new a;case 1:return new a(c[0]);case 2:return new a(c[0],c[1]);case 3:return new a(c[0],c[1],c[2]);case 4:return new a(c[0],c[1],c[2],c[3]);case 5:return new a(c[0],c[1],c[2],c[3],c[4]);case 6:return new a(c[0],c[1],c[2],c[3],c[4],c[5]);case 7:return new a(c[0],c[1],c[2],c[3],c[4],c[5],c[6])}var p=Wa(a.prototype),w=a.apply(p,c);return It(w)?w:p}}function VM(a,c,p){var w=Vc(a);function $(){for(var T=arguments.length,N=q(T),D=T,B=Ya($);D--;)N[D]=arguments[D];var ne=T<3&&N[0]!==B&&N[T-1]!==B?[]:Oi(N,B);if(T-=ne.length,T-1?$[T?c[N]:N]:n}}function L_(a){return Jo(function(c){var p=c.length,w=p,$=Tr.prototype.thru;for(a&&c.reverse();w--;){var T=c[w];if(typeof T!="function")throw new Rr(s);if($&&!N&&kf(T)=="wrapper")var N=new Tr([],!0)}for(w=N?w:p;++w1&&at.reverse(),re&&BD))return!1;var ne=T.get(a),re=T.get(c);if(ne&&re)return ne==c&&re==a;var se=-1,me=!0,Re=p&_?new Ws:n;for(T.set(a,c),T.set(c,a);++se1?"& ":"")+c[w],c=c.join(p>2?", ":" "),a.replace(an,`{ +/* [wrapped with `+c+`] */ +`)}function tN(a){return Ye(a)||Xs(a)||!!(Qb&&a&&a[Qb])}function ei(a,c){var p=typeof a;return c=c??K,!!c&&(p=="number"||p!="symbol"&&pO.test(a))&&a>-1&&a%1==0&&a0){if(++c>=G)return arguments[0]}else c=0;return a.apply(n,arguments)}}function Tf(a,c){var p=-1,w=a.length,$=w-1;for(c=c===n?w:c;++p1?a[c-1]:n;return p=typeof p=="function"?(a.pop(),p):n,lS(a,p)});function cS(a){var c=R(a);return c.__chain__=!0,c}function f7(a,c){return c(a),a}function Pf(a,c){return c(a)}var p7=Jo(function(a){var c=a.length,p=c?a[0]:0,w=this.__wrapped__,$=function(T){return Hg(T,a)};return c>1||this.__actions__.length||!(w instanceof ot)||!ei(p)?this.thru($):(w=w.slice(p,+p+(c?1:0)),w.__actions__.push({func:Pf,args:[$],thisArg:n}),new Tr(w,this.__chain__).thru(function(T){return c&&!T.length&&T.push(n),T}))});function h7(){return cS(this)}function m7(){return new Tr(this.value(),this.__chain__)}function g7(){this.__values__===n&&(this.__values__=SS(this.value()));var a=this.__index__>=this.__values__.length,c=a?n:this.__values__[this.__index__++];return{done:a,value:c}}function v7(){return this}function y7(a){for(var c,p=this;p instanceof mf;){var w=nS(p);w.__index__=0,w.__values__=n,c?$.__wrapped__=w:c=w;var $=w;p=p.__wrapped__}return $.__wrapped__=a,c}function w7(){var a=this.__wrapped__;if(a instanceof ot){var c=a;return this.__actions__.length&&(c=new ot(this)),c=c.reverse(),c.__actions__.push({func:Pf,args:[wv],thisArg:n}),new Tr(c,this.__chain__)}return this.thru(wv)}function x7(){return C_(this.__wrapped__,this.__actions__)}var b7=_f(function(a,c,p){yt.call(a,p)?++a[p]:qo(a,p,1)});function _7(a,c,p){var w=Ye(a)?Fb:fM;return p&&Mn(a,c,p)&&(c=n),w(a,De(c,3))}function S7(a,c){var p=Ye(a)?Pi:l_;return p(a,De(c,3))}var E7=I_(rS),C7=I_(oS);function $7(a,c){return pn(Af(a,c),1)}function k7(a,c){return pn(Af(a,c),ie)}function R7(a,c,p){return p=p===n?1:qe(p),pn(Af(a,c),p)}function uS(a,c){var p=Ye(a)?kr:Ni;return p(a,De(c,3))}function dS(a,c){var p=Ye(a)?YO:a_;return p(a,De(c,3))}var T7=_f(function(a,c,p){yt.call(a,p)?a[p].push(c):qo(a,p,[c])});function P7(a,c,p,w){a=Hn(a)?a:Xa(a),p=p&&!w?qe(p):0;var $=a.length;return p<0&&(p=tn($+p,0)),If(a)?p<=$&&a.indexOf(c,p)>-1:!!$&&La(a,c,p)>-1}var A7=et(function(a,c,p){var w=-1,$=typeof c=="function",T=Hn(a)?q(a.length):[];return Ni(a,function(N){T[++w]=$?or(c,N,p):zc(N,c,p)}),T}),O7=_f(function(a,c,p){qo(a,p,c)});function Af(a,c){var p=Ye(a)?Mt:h_;return p(a,De(c,3))}function M7(a,c,p,w){return a==null?[]:(Ye(c)||(c=c==null?[]:[c]),p=w?n:p,Ye(p)||(p=p==null?[]:[p]),y_(a,c,p))}var N7=_f(function(a,c,p){a[p?0:1].push(c)},function(){return[[],[]]});function D7(a,c,p){var w=Ye(a)?Og:Ub,$=arguments.length<3;return w(a,De(c,4),p,$,Ni)}function I7(a,c,p){var w=Ye(a)?GO:Ub,$=arguments.length<3;return w(a,De(c,4),p,$,a_)}function L7(a,c){var p=Ye(a)?Pi:l_;return p(a,Nf(De(c,3)))}function F7(a){var c=Ye(a)?r_:PM;return c(a)}function j7(a,c,p){(p?Mn(a,c,p):c===n)?c=1:c=qe(c);var w=Ye(a)?aM:AM;return w(a,c)}function z7(a){var c=Ye(a)?lM:MM;return c(a)}function B7(a){if(a==null)return 0;if(Hn(a))return If(a)?ja(a):a.length;var c=En(a);return c==ct||c==Z?a.size:qg(a).length}function U7(a,c,p){var w=Ye(a)?Mg:NM;return p&&Mn(a,c,p)&&(c=n),w(a,De(c,3))}var V7=et(function(a,c){if(a==null)return[];var p=c.length;return p>1&&Mn(a,c[0],c[1])?c=[]:p>2&&Mn(c[0],c[1],c[2])&&(c=[c[0]]),y_(a,pn(c,1),[])}),Of=S6||function(){return fn.Date.now()};function W7(a,c){if(typeof c!="function")throw new Rr(s);return a=qe(a),function(){if(--a<1)return c.apply(this,arguments)}}function fS(a,c,p){return c=p?n:c,c=a&&c==null?a.length:c,Qo(a,A,n,n,n,n,c)}function pS(a,c){var p;if(typeof c!="function")throw new Rr(s);return a=qe(a),function(){return--a>0&&(p=c.apply(this,arguments)),a<=1&&(c=n),p}}var bv=et(function(a,c,p){var w=C;if(p.length){var $=Oi(p,Ya(bv));w|=P}return Qo(a,w,c,p,$)}),hS=et(function(a,c,p){var w=C|S;if(p.length){var $=Oi(p,Ya(hS));w|=P}return Qo(c,w,a,p,$)});function mS(a,c,p){c=p?n:c;var w=Qo(a,E,n,n,n,n,n,c);return w.placeholder=mS.placeholder,w}function gS(a,c,p){c=p?n:c;var w=Qo(a,k,n,n,n,n,n,c);return w.placeholder=gS.placeholder,w}function vS(a,c,p){var w,$,T,N,D,B,ne=0,re=!1,se=!1,me=!0;if(typeof a!="function")throw new Rr(s);c=Mr(c)||0,It(p)&&(re=!!p.leading,se="maxWait"in p,T=se?tn(Mr(p.maxWait)||0,c):T,me="trailing"in p?!!p.trailing:me);function Re(Gt){var no=w,ri=$;return w=$=n,ne=Gt,N=a.apply(ri,no),N}function Ie(Gt){return ne=Gt,D=Hc(nt,c),re?Re(Gt):N}function Qe(Gt){var no=Gt-B,ri=Gt-ne,IS=c-no;return se?Sn(IS,T-ri):IS}function Le(Gt){var no=Gt-B,ri=Gt-ne;return B===n||no>=c||no<0||se&&ri>=T}function nt(){var Gt=Of();if(Le(Gt))return at(Gt);D=Hc(nt,Qe(Gt))}function at(Gt){return D=n,me&&w?Re(Gt):(w=$=n,N)}function lr(){D!==n&&k_(D),ne=0,w=B=$=D=n}function Nn(){return D===n?N:at(Of())}function cr(){var Gt=Of(),no=Le(Gt);if(w=arguments,$=this,B=Gt,no){if(D===n)return Ie(B);if(se)return k_(D),D=Hc(nt,c),Re(B)}return D===n&&(D=Hc(nt,c)),N}return cr.cancel=lr,cr.flush=Nn,cr}var H7=et(function(a,c){return s_(a,1,c)}),K7=et(function(a,c,p){return s_(a,Mr(c)||0,p)});function Y7(a){return Qo(a,F)}function Mf(a,c){if(typeof a!="function"||c!=null&&typeof c!="function")throw new Rr(s);var p=function(){var w=arguments,$=c?c.apply(this,w):w[0],T=p.cache;if(T.has($))return T.get($);var N=a.apply(this,w);return p.cache=T.set($,N)||T,N};return p.cache=new(Mf.Cache||Zo),p}Mf.Cache=Zo;function Nf(a){if(typeof a!="function")throw new Rr(s);return function(){var c=arguments;switch(c.length){case 0:return!a.call(this);case 1:return!a.call(this,c[0]);case 2:return!a.call(this,c[0],c[1]);case 3:return!a.call(this,c[0],c[1],c[2])}return!a.apply(this,c)}}function G7(a){return pS(2,a)}var X7=DM(function(a,c){c=c.length==1&&Ye(c[0])?Mt(c[0],ir(De())):Mt(pn(c,1),ir(De()));var p=c.length;return et(function(w){for(var $=-1,T=Sn(w.length,p);++$=c}),Xs=d_(function(){return arguments}())?d_:function(a){return Bt(a)&&yt.call(a,"callee")&&!qb.call(a,"callee")},Ye=q.isArray,u4=Ob?ir(Ob):yM;function Hn(a){return a!=null&&Df(a.length)&&!ti(a)}function Yt(a){return Bt(a)&&Hn(a)}function d4(a){return a===!0||a===!1||Bt(a)&&On(a)==xe}var Fi=C6||Mv,f4=Mb?ir(Mb):wM;function p4(a){return Bt(a)&&a.nodeType===1&&!Kc(a)}function h4(a){if(a==null)return!0;if(Hn(a)&&(Ye(a)||typeof a=="string"||typeof a.splice=="function"||Fi(a)||Ga(a)||Xs(a)))return!a.length;var c=En(a);if(c==ct||c==Z)return!a.size;if(Wc(a))return!qg(a).length;for(var p in a)if(yt.call(a,p))return!1;return!0}function m4(a,c){return Bc(a,c)}function g4(a,c,p){p=typeof p=="function"?p:n;var w=p?p(a,c):n;return w===n?Bc(a,c,n,p):!!w}function Sv(a){if(!Bt(a))return!1;var c=On(a);return c==Oe||c==Ae||typeof a.message=="string"&&typeof a.name=="string"&&!Kc(a)}function v4(a){return typeof a=="number"&&Jb(a)}function ti(a){if(!It(a))return!1;var c=On(a);return c==je||c==Ot||c==fe||c==I}function wS(a){return typeof a=="number"&&a==qe(a)}function Df(a){return typeof a=="number"&&a>-1&&a%1==0&&a<=K}function It(a){var c=typeof a;return a!=null&&(c=="object"||c=="function")}function Bt(a){return a!=null&&typeof a=="object"}var xS=Nb?ir(Nb):bM;function y4(a,c){return a===c||Zg(a,c,pv(c))}function w4(a,c,p){return p=typeof p=="function"?p:n,Zg(a,c,pv(c),p)}function x4(a){return bS(a)&&a!=+a}function b4(a){if(oN(a))throw new Ke(i);return f_(a)}function _4(a){return a===null}function S4(a){return a==null}function bS(a){return typeof a=="number"||Bt(a)&&On(a)==Kt}function Kc(a){if(!Bt(a)||On(a)!=gt)return!1;var c=lf(a);if(c===null)return!0;var p=yt.call(c,"constructor")&&c.constructor;return typeof p=="function"&&p instanceof p&&rf.call(p)==w6}var Ev=Db?ir(Db):_M;function E4(a){return wS(a)&&a>=-K&&a<=K}var _S=Ib?ir(Ib):SM;function If(a){return typeof a=="string"||!Ye(a)&&Bt(a)&&On(a)==we}function ar(a){return typeof a=="symbol"||Bt(a)&&On(a)==he}var Ga=Lb?ir(Lb):EM;function C4(a){return a===n}function $4(a){return Bt(a)&&En(a)==ke}function k4(a){return Bt(a)&&On(a)==ft}var R4=$f(Qg),T4=$f(function(a,c){return a<=c});function SS(a){if(!a)return[];if(Hn(a))return If(a)?Jr(a):Wn(a);if(Mc&&a[Mc])return a6(a[Mc]());var c=En(a),p=c==ct?jg:c==Z?ef:Xa;return p(a)}function ni(a){if(!a)return a===0?a:0;if(a=Mr(a),a===ie||a===-ie){var c=a<0?-1:1;return c*Q}return a===a?a:0}function qe(a){var c=ni(a),p=c%1;return c===c?p?c-p:c:0}function ES(a){return a?Hs(qe(a),0,le):0}function Mr(a){if(typeof a=="number")return a;if(ar(a))return W;if(It(a)){var c=typeof a.valueOf=="function"?a.valueOf():a;a=It(c)?c+"":c}if(typeof a!="string")return a===0?a:+a;a=Vb(a);var p=uO.test(a);return p||fO.test(a)?WO(a.slice(2),p?2:8):cO.test(a)?W:+a}function CS(a){return Eo(a,Kn(a))}function P4(a){return a?Hs(qe(a),-K,K):a===0?a:0}function vt(a){return a==null?"":sr(a)}var A4=Ha(function(a,c){if(Wc(c)||Hn(c)){Eo(c,ln(c),a);return}for(var p in c)yt.call(c,p)&&Fc(a,p,c[p])}),$S=Ha(function(a,c){Eo(c,Kn(c),a)}),Lf=Ha(function(a,c,p,w){Eo(c,Kn(c),a,w)}),O4=Ha(function(a,c,p,w){Eo(c,ln(c),a,w)}),M4=Jo(Hg);function N4(a,c){var p=Wa(a);return c==null?p:o_(p,c)}var D4=et(function(a,c){a=_t(a);var p=-1,w=c.length,$=w>2?c[2]:n;for($&&Mn(c[0],c[1],$)&&(w=1);++p1),T}),Eo(a,dv(a),p),w&&(p=Pr(p,m|g|y,KM));for(var $=c.length;$--;)rv(p,c[$]);return p});function J4(a,c){return RS(a,Nf(De(c)))}var e8=Jo(function(a,c){return a==null?{}:kM(a,c)});function RS(a,c){if(a==null)return{};var p=Mt(dv(a),function(w){return[w]});return c=De(c),w_(a,p,function(w,$){return c(w,$[0])})}function t8(a,c,p){c=Ii(c,a);var w=-1,$=c.length;for($||($=1,a=n);++w<$;){var T=a==null?n:a[Co(c[w])];T===n&&(w=$,T=p),a=ti(T)?T.call(a):T}return a}function n8(a,c,p){return a==null?a:Uc(a,c,p)}function r8(a,c,p,w){return w=typeof w=="function"?w:n,a==null?a:Uc(a,c,p,w)}var TS=B_(ln),PS=B_(Kn);function o8(a,c,p){var w=Ye(a),$=w||Fi(a)||Ga(a);if(c=De(c,4),p==null){var T=a&&a.constructor;$?p=w?new T:[]:It(a)?p=ti(T)?Wa(lf(a)):{}:p={}}return($?kr:So)(a,function(N,D,B){return c(p,N,D,B)}),p}function i8(a,c){return a==null?!0:rv(a,c)}function s8(a,c,p){return a==null?a:E_(a,c,sv(p))}function a8(a,c,p,w){return w=typeof w=="function"?w:n,a==null?a:E_(a,c,sv(p),w)}function Xa(a){return a==null?[]:Fg(a,ln(a))}function l8(a){return a==null?[]:Fg(a,Kn(a))}function c8(a,c,p){return p===n&&(p=c,c=n),p!==n&&(p=Mr(p),p=p===p?p:0),c!==n&&(c=Mr(c),c=c===c?c:0),Hs(Mr(a),c,p)}function u8(a,c,p){return c=ni(c),p===n?(p=c,c=0):p=ni(p),a=Mr(a),gM(a,c,p)}function d8(a,c,p){if(p&&typeof p!="boolean"&&Mn(a,c,p)&&(c=p=n),p===n&&(typeof c=="boolean"?(p=c,c=n):typeof a=="boolean"&&(p=a,a=n)),a===n&&c===n?(a=0,c=1):(a=ni(a),c===n?(c=a,a=0):c=ni(c)),a>c){var w=a;a=c,c=w}if(p||a%1||c%1){var $=e_();return Sn(a+$*(c-a+VO("1e-"+(($+"").length-1))),c)}return ev(a,c)}var f8=Ka(function(a,c,p){return c=c.toLowerCase(),a+(p?AS(c):c)});function AS(a){return kv(vt(a).toLowerCase())}function OS(a){return a=vt(a),a&&a.replace(hO,n6).replace(MO,"")}function p8(a,c,p){a=vt(a),c=sr(c);var w=a.length;p=p===n?w:Hs(qe(p),0,w);var $=p;return p-=c.length,p>=0&&a.slice(p,$)==c}function h8(a){return a=vt(a),a&&xg.test(a)?a.replace(Rc,r6):a}function m8(a){return a=vt(a),a&&Ge.test(a)?a.replace(H,"\\$&"):a}var g8=Ka(function(a,c,p){return a+(p?"-":"")+c.toLowerCase()}),v8=Ka(function(a,c,p){return a+(p?" ":"")+c.toLowerCase()}),y8=D_("toLowerCase");function w8(a,c,p){a=vt(a),c=qe(c);var w=c?ja(a):0;if(!c||w>=c)return a;var $=(c-w)/2;return Cf(ff($),p)+a+Cf(df($),p)}function x8(a,c,p){a=vt(a),c=qe(c);var w=c?ja(a):0;return c&&w>>0,p?(a=vt(a),a&&(typeof c=="string"||c!=null&&!Ev(c))&&(c=sr(c),!c&&Fa(a))?Li(Jr(a),0,p):a.split(c,p)):[]}var k8=Ka(function(a,c,p){return a+(p?" ":"")+kv(c)});function R8(a,c,p){return a=vt(a),p=p==null?0:Hs(qe(p),0,a.length),c=sr(c),a.slice(p,p+c.length)==c}function T8(a,c,p){var w=R.templateSettings;p&&Mn(a,c,p)&&(c=n),a=vt(a),c=Lf({},c,w,U_);var $=Lf({},c.imports,w.imports,U_),T=ln($),N=Fg($,T),D,B,ne=0,re=c.interpolate||Xd,se="__p += '",me=zg((c.escape||Xd).source+"|"+re.source+"|"+(re===Ac?lO:Xd).source+"|"+(c.evaluate||Xd).source+"|$","g"),Re="//# sourceURL="+(yt.call(c,"sourceURL")?(c.sourceURL+"").replace(/\s/g," "):"lodash.templateSources["+ ++FO+"]")+` +`;a.replace(me,function(Le,nt,at,lr,Nn,cr){return at||(at=lr),se+=a.slice(ne,cr).replace(mO,o6),nt&&(D=!0,se+=`' + +__e(`+nt+`) + +'`),Nn&&(B=!0,se+=`'; +`+Nn+`; +__p += '`),at&&(se+=`' + +((__t = (`+at+`)) == null ? '' : __t) + +'`),ne=cr+Le.length,Le}),se+=`'; +`;var Ie=yt.call(c,"variable")&&c.variable;if(!Ie)se=`with (obj) { +`+se+` +} +`;else if(sO.test(Ie))throw new Ke(l);se=(B?se.replace(yg,""):se).replace(wg,"$1").replace(Kd,"$1;"),se="function("+(Ie||"obj")+`) { +`+(Ie?"":`obj || (obj = {}); +`)+"var __t, __p = ''"+(D?", __e = _.escape":"")+(B?`, __j = Array.prototype.join; +function print() { __p += __j.call(arguments, '') } +`:`; +`)+se+`return __p +}`;var Qe=NS(function(){return ht(T,Re+"return "+se).apply(n,N)});if(Qe.source=se,Sv(Qe))throw Qe;return Qe}function P8(a){return vt(a).toLowerCase()}function A8(a){return vt(a).toUpperCase()}function O8(a,c,p){if(a=vt(a),a&&(p||c===n))return Vb(a);if(!a||!(c=sr(c)))return a;var w=Jr(a),$=Jr(c),T=Wb(w,$),N=Hb(w,$)+1;return Li(w,T,N).join("")}function M8(a,c,p){if(a=vt(a),a&&(p||c===n))return a.slice(0,Yb(a)+1);if(!a||!(c=sr(c)))return a;var w=Jr(a),$=Hb(w,Jr(c))+1;return Li(w,0,$).join("")}function N8(a,c,p){if(a=vt(a),a&&(p||c===n))return a.replace(st,"");if(!a||!(c=sr(c)))return a;var w=Jr(a),$=Wb(w,Jr(c));return Li(w,$).join("")}function D8(a,c){var p=V,w=J;if(It(c)){var $="separator"in c?c.separator:$;p="length"in c?qe(c.length):p,w="omission"in c?sr(c.omission):w}a=vt(a);var T=a.length;if(Fa(a)){var N=Jr(a);T=N.length}if(p>=T)return a;var D=p-ja(w);if(D<1)return w;var B=N?Li(N,0,D).join(""):a.slice(0,D);if($===n)return B+w;if(N&&(D+=B.length-D),Ev($)){if(a.slice(D).search($)){var ne,re=B;for($.global||($=zg($.source,vt(db.exec($))+"g")),$.lastIndex=0;ne=$.exec(re);)var se=ne.index;B=B.slice(0,se===n?D:se)}}else if(a.indexOf(sr($),D)!=D){var me=B.lastIndexOf($);me>-1&&(B=B.slice(0,me))}return B+w}function I8(a){return a=vt(a),a&&Tc.test(a)?a.replace(kc,d6):a}var L8=Ka(function(a,c,p){return a+(p?" ":"")+c.toUpperCase()}),kv=D_("toUpperCase");function MS(a,c,p){return a=vt(a),c=p?n:c,c===n?s6(a)?h6(a):qO(a):a.match(c)||[]}var NS=et(function(a,c){try{return or(a,n,c)}catch(p){return Sv(p)?p:new Ke(p)}}),F8=Jo(function(a,c){return kr(c,function(p){p=Co(p),qo(a,p,bv(a[p],a))}),a});function j8(a){var c=a==null?0:a.length,p=De();return a=c?Mt(a,function(w){if(typeof w[1]!="function")throw new Rr(s);return[p(w[0]),w[1]]}):[],et(function(w){for(var $=-1;++$K)return[];var p=le,w=Sn(a,le);c=De(c),a-=le;for(var $=Lg(w,c);++p0||c<0)?new ot(p):(a<0?p=p.takeRight(-a):a&&(p=p.drop(a)),c!==n&&(c=qe(c),p=c<0?p.dropRight(-c):p.take(c-a)),p)},ot.prototype.takeRightWhile=function(a){return this.reverse().takeWhile(a).reverse()},ot.prototype.toArray=function(){return this.take(le)},So(ot.prototype,function(a,c){var p=/^(?:filter|find|map|reject)|While$/.test(c),w=/^(?:head|last)$/.test(c),$=R[w?"take"+(c=="last"?"Right":""):c],T=w||/^find/.test(c);$&&(R.prototype[c]=function(){var N=this.__wrapped__,D=w?[1]:arguments,B=N instanceof ot,ne=D[0],re=B||Ye(N),se=function(nt){var at=$.apply(R,Ai([nt],D));return w&&me?at[0]:at};re&&p&&typeof ne=="function"&&ne.length!=1&&(B=re=!1);var me=this.__chain__,Re=!!this.__actions__.length,Ie=T&&!me,Qe=B&&!Re;if(!T&&re){N=Qe?N:new ot(this);var Le=a.apply(N,D);return Le.__actions__.push({func:Pf,args:[se],thisArg:n}),new Tr(Le,me)}return Ie&&Qe?a.apply(this,D):(Le=this.thru(se),Ie?w?Le.value()[0]:Le.value():Le)})}),kr(["pop","push","shift","sort","splice","unshift"],function(a){var c=tf[a],p=/^(?:push|sort|unshift)$/.test(a)?"tap":"thru",w=/^(?:pop|shift)$/.test(a);R.prototype[a]=function(){var $=arguments;if(w&&!this.__chain__){var T=this.value();return c.apply(Ye(T)?T:[],$)}return this[p](function(N){return c.apply(Ye(N)?N:[],$)})}}),So(ot.prototype,function(a,c){var p=R[c];if(p){var w=p.name+"";yt.call(Va,w)||(Va[w]=[]),Va[w].push({name:c,func:p})}}),Va[Sf(n,S).name]=[{name:"wrapper",func:n}],ot.prototype.clone=I6,ot.prototype.reverse=L6,ot.prototype.value=F6,R.prototype.at=p7,R.prototype.chain=h7,R.prototype.commit=m7,R.prototype.next=g7,R.prototype.plant=y7,R.prototype.reverse=w7,R.prototype.toJSON=R.prototype.valueOf=R.prototype.value=x7,R.prototype.first=R.prototype.head,Mc&&(R.prototype[Mc]=v7),R},za=m6();Bs?((Bs.exports=za)._=za,Tg._=za):fn._=za}).call(Yc)})(Lh,Lh.exports);var yH=Lh.exports;const wH=lm(yH);function Vr({width:e,height:t}){return e/t}function Fh(e,t=0){const n=10**t;return Math.round((e+Number.EPSILON)*n)/n}function xH(e){return(t,n)=>e(n)-e(t)}class bH{constructor(t){this.comparator=t,this.heap=[],this.n=0}greater(t,n){return this.comparator(this.heap[t],this.heap[n])<0}swap(t,n){const r=this.heap[t];this.heap[t]=this.heap[n],this.heap[n]=r}swim(t){let n=t,r=Math.floor(n/2);for(;n>1&&this.greater(r,n);)this.swap(r,n),n=r,r=Math.floor(n/2)}sink(t){let n=t,r=n*2;for(;r<=this.n&&(rl.weight));for(s.push({id:t,weight:0});s.size()>0;){const{id:l,weight:u}=s.pop();if(!o.has(l)){const d=e(l);o.add(l),d.forEach((h,m)=>{const g=u+h,y=r.get(m),x=i.get(m);(x===void 0||x>g&&(x/g>1.005||y!==void 0&&yMath.min(Vr(i),o),Number.MAX_VALUE);return Fh(n/t/r)+2}function MP(e,t,n,r){const o=t-(e.length-1)*n-2*r*e.length,i=e.reduce((s,l)=>s+Vr(l),0);return o/i}function $H(e,t,n,r,o,i,s){const l=e.slice(t,n),u=MP(l,r,i,s);return u>0?(u-o)**2*l.length:void 0}function kH({photos:e,layoutOptions:t,targetRowHeight:n,limitNodeSearch:r,rowConstraints:o}){return i=>{var s,l;const{containerWidth:u,spacing:d,padding:h}=t,m=new Map;m.set(i,0);const g=(s=o==null?void 0:o.minPhotos)!=null?s:1,y=Math.min(r,(l=o==null?void 0:o.maxPhotos)!=null?l:1/0);for(let x=i+g;xy);x+=1){const _=$H(e,i,x,u,n,d,h);if(_===void 0)break;m.set(x,_)}return m}}function RH({photos:e,layoutOptions:t}){const{spacing:n,padding:r,containerWidth:o,targetRowHeight:i,rowConstraints:s}=t,l=CH({photos:e,containerWidth:o,targetRowHeight:i}),u=kH({photos:e,layoutOptions:t,targetRowHeight:i,limitNodeSearch:l,rowConstraints:s}),d=EH(u,0,e.length);if(d===void 0)return;const h=[];for(let m=1;m({photo:x,index:_})).slice(d[m-1],d[m]),y=MP(g.map(({photo:x})=>x),o,n,r);h.push(g.map(({photo:x,index:_},C)=>({photo:x,layout:{height:y,width:y*Vr(x),index:_,photoIndex:C,photosCount:g.length}})))}return h}function qm(...e){return[...e].filter(t=>!!t).join(" ")}function NP(e,{width:t,photosCount:n},{spacing:r,padding:o,containerWidth:i}){const s=r*(n-1)+2*o*n;return`calc((${e} - ${s}px) / ${Fh((i-s)/t,5)})`}function TH(e,t){return t.layout!=="rows"?`calc(100% - ${2*t.padding}px)`:NP("100%",e,t)}function i2(e,t,n){var r,o;return NP((o=(r=e.match(/calc\((.*)\)/))==null?void 0:r[1])!=null?o:e,t,n)}function PH(e,t,n){let r,o;const i=e.srcSet||e.images;return i&&i.length>0&&(r=i.concat(i.find(({width:s})=>s===e.width)?[]:[{src:e.src,width:e.width,height:e.height}]).sort((s,l)=>s.width-l.width).map(s=>`${s.src} ${s.width}w`).join(", ")),n.sizes?o=(n.sizes.sizes||[]).map(({viewport:s,size:l})=>`${s} ${i2(l,t,n)}`).concat(i2(n.sizes.size,t,n)).join(", "):r&&(o=`${Math.ceil(t.width/n.containerWidth*100)}vw`),{srcSet:r,sizes:o}}function Ox(e){var t,n;const{photo:r,layout:o,layoutOptions:i,imageProps:{style:s,className:l,...u}={},renderPhoto:d}=e,{onClick:h}=i,m={display:"block",boxSizing:"content-box",width:TH(o,i),height:"auto",aspectRatio:`${r.width} / ${r.height}`,...i.padding?{padding:`${i.padding}px`}:null,...(i.layout==="columns"||i.layout==="masonry")&&o.photoIndex{h({event:C,photo:r,index:o.index})}:void 0,y={src:r.src,alt:(t=r.alt)!=null?t:"",title:r.title,onClick:g,style:m,className:qm("react-photo-album--photo",l),loading:"lazy",decoding:"async",...PH(r,o,i),...u},x=C=>{const{src:S,alt:b,srcSet:E,sizes:k,style:P,...M}=y;return f.createElement("img",{alt:b,...E?{srcSet:E,sizes:k}:null,src:S,style:C!=null&&C.wrapped?{display:"block",width:"100%",height:"100%"}:P,...M})},_=(({display:C,boxSizing:S,width:b,aspectRatio:E,padding:k,marginBottom:P,cursor:M})=>({display:C,boxSizing:S,width:b,aspectRatio:E,padding:k,marginBottom:P,cursor:M}))(m);return f.createElement(f.Fragment,null,(n=d==null?void 0:d({photo:r,layout:o,layoutOptions:i,imageProps:y,renderDefaultPhoto:x,wrapperStyle:_}))!=null?n:x())}function AH({rowContainerProps:e,children:t}){return f.createElement("div",{...e},t)}function OH(e){const{layoutOptions:t,rowIndex:n,rowsCount:r,renderRowContainer:o,rowContainerProps:{style:i,className:s,...l}={},children:u}=e,d={className:qm("react-photo-album--row",s),style:{display:"flex",flexDirection:"row",flexWrap:"nowrap",alignItems:"flex-start",justifyContent:"space-between",...nf.createElement(OH,{key:`row-${d}`,layoutOptions:n,rowIndex:d,rowsCount:l.length,renderRowContainer:o,rowContainerProps:s},u.map(({photo:h,layout:m})=>f.createElement(Ox,{key:h.key||h.src,photo:h,layout:m,layoutOptions:n,renderPhoto:r,imageProps:i}))))):null}function NH(e,t,n,r){const o=new Map,i=new Set;i.add(n);for(let s=0;s{const d=s>0?o.get(u)[s].weight:0;e(u).forEach(({neighbor:h,weight:m})=>{let g=o.get(h);g||(g=[],o.set(h,g));const y=d+m,x=g[s+1];(!x||x.weight>y&&(x.weight/y>1.0001||u0;i-=1)o=e.get(o)[i].node,r.push(o);return r.reverse()}function IH(e,t,n,r){return DH(NH(e,t,n,r),t,r)}function LH({photos:e,spacing:t,padding:n,targetColumnWidth:r,targetColumnHeight:o}){return i=>{const s=[],l=o*1.5;let u=r/Vr(e[i])+2*n;for(let d=i+1;dl||d===e.length));d+=1)u+=r/Vr(e[d])+t+2*n;return s}}function s2({path:e,photos:t,containerWidth:n,columnsGaps:r,columnsRatios:o,spacing:i,padding:s}){const l=[],u=o.reduce((d,h)=>d+h,0);for(let d=0;d({photo:y,index:x})).slice(e[d],e[d+1]),m=o.reduce((y,x,_)=>y+(r[d]-r[_])*x,0),g=(n-(e.length-2)*i-2*(e.length-1)*s-m)*o[d]/u;l.push(h.map(({photo:y,index:x},_)=>({photo:y,layout:{width:g,height:g/Vr(y),index:x,photoIndex:_,photosCount:h.length}})))}return l}function FH({photos:e,layoutOptions:t,targetColumnWidth:n}){const{columns:r,spacing:o,padding:i,containerWidth:s}=t,l=[],u=[];if(e.length<=r){const y=e.length>0?e.reduce((_,C)=>_+Vr(C),0)/e.length:1;for(let _=0;_Math.min(C,e.length)),photos:e,columnsRatios:u,columnsGaps:l,containerWidth:s,spacing:o,padding:i});return{columnsGaps:l,columnsRatios:u,columnsModel:x}}const d=(e.reduce((y,x)=>y+n/Vr(x),0)+o*(e.length-r)+2*i*e.length)/r,h=LH({photos:e,targetColumnWidth:n,targetColumnHeight:d,spacing:o,padding:i}),m=IH(h,r,0,e.length);for(let y=0;y_+1/Vr(C),0)}const g=s2({path:m,photos:e,columnsRatios:u,columnsGaps:l,containerWidth:s,spacing:o,padding:i});return{columnsGaps:l,columnsRatios:u,columnsModel:g}}function DP(e){const{photos:t,layoutOptions:n}=e,{columns:r,spacing:o,padding:i,containerWidth:s}=n,l=(s-o*(r-1)-2*i*r)/r,{columnsGaps:u,columnsRatios:d,columnsModel:h}=FH({photos:t,layoutOptions:n,targetColumnWidth:l});return h.findIndex(m=>m.findIndex(({layout:{width:g,height:y}})=>g<0||y<0)>=0)>=0?r>1?DP({photos:t,layoutOptions:{...n,columns:r-1}}):void 0:{columnsModel:h,columnsGaps:u,columnsRatios:d}}function jH({photos:e,layoutOptions:t}){return DP({photos:e,layoutOptions:t})}function zH({columnContainerProps:e,children:t}){return f.createElement("div",{...e},t)}function BH(e){const{layoutOptions:t,columnIndex:n,columnsCount:r,columnsGaps:o,columnsRatios:i}=e,{layout:s,spacing:l,padding:u}=t;if(s==="masonry"||!o||!i)return`calc((100% - ${l*(r-1)}px) / ${r})`;const d=i.reduce((m,g)=>m+g,0),h=i.reduce((m,g,y)=>m+(o[n]-o[y])*g,0);return`calc((100% - ${Fh((r-1)*l+2*r*u+h,3)}px) * ${Fh(i[n]/d,5)} + ${2*u}px)`}function IP(e){const{layoutOptions:t,renderColumnContainer:n,children:r,columnContainerProps:{style:o,className:i,...s}={},...l}=e,u={className:qm("react-photo-album--column",i),style:{display:"flex",flexDirection:"column",flexWrap:"nowrap",alignItems:"flex-start",width:BH(e),justifyContent:t.layout==="columns"?"space-between":"flex-start",...o},...s};return f.createElement(f.Fragment,null,(n??zH)({layoutOptions:t,columnContainerProps:u,children:r,...l}))}function UH(e){const{photos:t,layoutOptions:n,renderPhoto:r,renderColumnContainer:o,componentsProps:{imageProps:i,columnContainerProps:s}}=e,l=jH({photos:t,layoutOptions:n});if(!l)return null;const{columnsModel:u,columnsRatios:d,columnsGaps:h}=l;return f.createElement(f.Fragment,null,u.map((m,g)=>f.createElement(IP,{key:`column-${g}`,layoutOptions:n,columnIndex:g,columnsCount:u.length,columnsGaps:h,columnsRatios:d,renderColumnContainer:o,columnContainerProps:s},m.map(({photo:y,layout:x})=>f.createElement(Ox,{key:y.key||y.src,photo:y,layout:x,layoutOptions:n,renderPhoto:r,imageProps:i})))))}function LP(e){const{photos:t,layoutOptions:n}=e,{columns:r,spacing:o,padding:i,containerWidth:s}=n,l=(s-o*(r-1)-2*i*r)/r;if(l<=0)return r>1?LP({...e,layoutOptions:{...n,columns:r-1}}):void 0;const u=[];for(let h=0;h{const y=u.reduce((x,_,C)=>_[])).map(h=>h.map(({photo:m,index:g},y)=>({photo:m,layout:{width:l,height:l/Vr(m),index:g,photoIndex:y,photosCount:h.length}})))}function VH(e){const{photos:t,layoutOptions:n,renderPhoto:r,renderColumnContainer:o,componentsProps:{imageProps:i,columnContainerProps:s}}=e,l=LP({photos:t,layoutOptions:n});return l?f.createElement(f.Fragment,null,l.map((u,d)=>f.createElement(IP,{key:`masonry-column-${d}`,layoutOptions:n,columnsCount:l.length,columnIndex:d,renderColumnContainer:o,columnContainerProps:s},u.map(({photo:h,layout:m})=>f.createElement(Ox,{key:h.key||h.src,photo:h,layout:m,layoutOptions:n,renderPhoto:r,imageProps:i}))))):null}function WH({containerProps:e,children:t,containerRef:n}){return f.createElement("div",{ref:n,...e},t)}function HH(e){const{layout:t,renderContainer:n,children:r,containerRef:o,containerProps:{style:i,className:s,...l}={}}=e,u={className:qm("react-photo-album",`react-photo-album--${t}`,s),style:{display:"flex",flexWrap:"nowrap",justifyContent:"space-between",flexDirection:t==="rows"?"column":"row",...i},...l};return f.createElement(f.Fragment,null,(n??WH)({containerProps:u,containerRef:o,layout:t,children:r}))}function KH(e){const t=f.useRef(e);return(!e||!t.current||e.join()!==t.current.join())&&(t.current=e),t.current}function YH(e,{newContainerWidth:t,newScrollbarWidth:n}){const{containerWidth:r,scrollbarWidth:o}=e;return r!==void 0&&o!==void 0&&t!==void 0&&n!==void 0&&t>r&&t-r<=20&&n0){const r=[...t.filter(i=>i>0)].sort((i,s)=>s-i);r.push(Math.floor(r[r.length-1]/2));const o=n;n=r.find((i,s)=>i<=o||s===r.length-1)}return n}function XH(e,t){const[{containerWidth:n},r]=f.useReducer(YH,{containerWidth:t}),o=f.useRef(null),i=f.useRef();return{containerRef:f.useCallback(l=>{var u;(u=i.current)==null||u.disconnect(),i.current=void 0,o.current=l;const d=()=>r({newContainerWidth:GH(o.current,e),newScrollbarWidth:window.innerWidth-document.documentElement.clientWidth});d(),l&&typeof ResizeObserver<"u"&&(i.current=new ResizeObserver(d),i.current.observe(l))},[e]),containerWidth:n}}const ZH=Object.freeze([1200,600,300,0]);function Mx(e,t){return typeof e=="function"?e(t):e}function FP(e,t){return typeof e<"u"?Mx(e,t):void 0}function qH(e,t){const n=ZH.findIndex(r=>r<=t);return Mx(e[n>=0?n:0],t)}function fp(e,t,n,r=0){const o=FP(e,t);return Math.round(Math.max(o===void 0?qH(n,t):o,r))}function QH({layout:e,onClick:t,containerWidth:n,targetRowHeight:r,rowConstraints:o,columns:i,spacing:s,padding:l,sizes:u}){return{layout:e,onClick:t,containerWidth:n,columns:fp(i,n,[5,4,3,2],1),spacing:fp(s,n,[20,15,10,5]),padding:fp(l,n,[0,0,0,0,0]),targetRowHeight:fp(r,n,[d=>d/5,d=>d/4,d=>d/3,d=>d/2]),rowConstraints:FP(o,n),sizes:u}}function JH(e,t,n){const{photos:r,componentsProps:o}=e,i=Mx(o,t)||{};if(n){const{layout:s,spacing:l,padding:u,rowConstraints:d}=n;if(s==="rows"){const{singleRowMaxHeight:h}=d||{};if(h){const m=Math.floor(r.reduce((g,{width:y,height:x})=>g+y/x*h-2*u,u*r.length*2+l*(r.length-1)));m>0&&(i.containerProps=i.containerProps||{},i.containerProps.style={maxWidth:m,...i.containerProps.style})}}}return i}function eK(e,t,n){const{photos:r,layout:o,renderPhoto:i,renderRowContainer:s,renderColumnContainer:l}=e,u={photos:r,renderPhoto:i,componentsProps:t};return o==="rows"?f.createElement(MH,{layoutOptions:n,renderRowContainer:s,...u}):o==="columns"?f.createElement(UH,{layoutOptions:n,renderColumnContainer:l,...u}):f.createElement(VH,{layoutOptions:n,renderColumnContainer:l,...u})}function tK(e){const{photos:t,layout:n,renderContainer:r,defaultContainerWidth:o,breakpoints:i}=e,{containerRef:s,containerWidth:l}=XH(KH(i),o);if(!n||!["rows","columns","masonry"].includes(n)||!Array.isArray(t))return null;const u=l?QH({containerWidth:l,...e}):void 0,d=JH(e,l,u);return f.createElement(HH,{layout:n,containerRef:s,renderContainer:r,containerProps:d.containerProps},u&&eK(e,d,u))}function nK({title:e,titleId:t,...n},r){return f.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true",ref:r,"aria-labelledby":t},n),e?f.createElement("title",{id:t},e):null,f.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3 4.5h14.25M3 9h9.75M3 13.5h9.75m4.5-4.5v12m0 0l-3.75-3.75M17.25 21L21 17.25"}))}const rK=f.forwardRef(nK),oK=rK;function iK({title:e,titleId:t,...n},r){return f.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true",ref:r,"aria-labelledby":t},n),e?f.createElement("title",{id:t},e):null,f.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3 4.5h14.25M3 9h9.75M3 13.5h5.25m5.25-.75L17.25 9m0 0L21 12.75M17.25 9v12"}))}const sK=f.forwardRef(iK),aK=sK;function lK({title:e,titleId:t,...n},r){return f.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true",ref:r,"aria-labelledby":t},n),e?f.createElement("title",{id:t},e):null,f.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15.042 21.672L13.684 16.6m0 0l-2.51 2.225.569-9.47 5.227 7.917-3.286-.672zM12 2.25V4.5m5.834.166l-1.591 1.591M20.25 10.5H18M7.757 14.743l-1.59 1.59M6 10.5H3.75m4.007-4.243l-1.59-1.59"}))}const cK=f.forwardRef(lK),uK=cK;function bi(e){return Array.isArray?Array.isArray(e):BP(e)==="[object Array]"}const dK=1/0;function fK(e){if(typeof e=="string")return e;let t=e+"";return t=="0"&&1/e==-dK?"-0":t}function pK(e){return e==null?"":fK(e)}function Lo(e){return typeof e=="string"}function jP(e){return typeof e=="number"}function hK(e){return e===!0||e===!1||mK(e)&&BP(e)=="[object Boolean]"}function zP(e){return typeof e=="object"}function mK(e){return zP(e)&&e!==null}function hr(e){return e!=null}function k0(e){return!e.trim().length}function BP(e){return e==null?e===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}const gK="Incorrect 'index' type",vK=e=>`Invalid value for key ${e}`,yK=e=>`Pattern length exceeds max of ${e}.`,wK=e=>`Missing ${e} property in key`,xK=e=>`Property 'weight' in key '${e}' must be a positive integer`,a2=Object.prototype.hasOwnProperty;class bK{constructor(t){this._keys=[],this._keyMap={};let n=0;t.forEach(r=>{let o=UP(r);this._keys.push(o),this._keyMap[o.id]=o,n+=o.weight}),this._keys.forEach(r=>{r.weight/=n})}get(t){return this._keyMap[t]}keys(){return this._keys}toJSON(){return JSON.stringify(this._keys)}}function UP(e){let t=null,n=null,r=null,o=1,i=null;if(Lo(e)||bi(e))r=e,t=l2(e),n=h1(e);else{if(!a2.call(e,"name"))throw new Error(wK("name"));const s=e.name;if(r=s,a2.call(e,"weight")&&(o=e.weight,o<=0))throw new Error(xK(s));t=l2(s),n=h1(s),i=e.getFn}return{path:t,id:n,weight:o,src:r,getFn:i}}function l2(e){return bi(e)?e:e.split(".")}function h1(e){return bi(e)?e.join("."):e}function _K(e,t){let n=[],r=!1;const o=(i,s,l)=>{if(hr(i))if(!s[l])n.push(i);else{let u=s[l];const d=i[u];if(!hr(d))return;if(l===s.length-1&&(Lo(d)||jP(d)||hK(d)))n.push(pK(d));else if(bi(d)){r=!0;for(let h=0,m=d.length;he.score===t.score?e.idx{this._keysMap[n.id]=r})}create(){this.isCreated||!this.docs.length||(this.isCreated=!0,Lo(this.docs[0])?this.docs.forEach((t,n)=>{this._addString(t,n)}):this.docs.forEach((t,n)=>{this._addObject(t,n)}),this.norm.clear())}add(t){const n=this.size();Lo(t)?this._addString(t,n):this._addObject(t,n)}removeAt(t){this.records.splice(t,1);for(let n=t,r=this.size();n{let s=o.getFn?o.getFn(t):this.getFn(t,o.path);if(hr(s)){if(bi(s)){let l=[];const u=[{nestedArrIndex:-1,value:s}];for(;u.length;){const{nestedArrIndex:d,value:h}=u.pop();if(hr(h))if(Lo(h)&&!k0(h)){let m={v:h,i:d,n:this.norm.get(h)};l.push(m)}else bi(h)&&h.forEach((m,g)=>{u.push({nestedArrIndex:g,value:m})})}r.$[i]=l}else if(Lo(s)&&!k0(s)){let l={v:s,n:this.norm.get(s)};r.$[i]=l}}}),this.records.push(r)}toJSON(){return{keys:this.keys,records:this.records}}}function VP(e,t,{getFn:n=He.getFn,fieldNormWeight:r=He.fieldNormWeight}={}){const o=new Nx({getFn:n,fieldNormWeight:r});return o.setKeys(e.map(UP)),o.setSources(t),o.create(),o}function TK(e,{getFn:t=He.getFn,fieldNormWeight:n=He.fieldNormWeight}={}){const{keys:r,records:o}=e,i=new Nx({getFn:t,fieldNormWeight:n});return i.setKeys(r),i.setIndexRecords(o),i}function pp(e,{errors:t=0,currentLocation:n=0,expectedLocation:r=0,distance:o=He.distance,ignoreLocation:i=He.ignoreLocation}={}){const s=t/e.length;if(i)return s;const l=Math.abs(r-n);return o?s+l/o:l?1:s}function PK(e=[],t=He.minMatchCharLength){let n=[],r=-1,o=-1,i=0;for(let s=e.length;i=t&&n.push([r,o]),r=-1)}return e[i-1]&&i-r>=t&&n.push([r,i-1]),n}const ea=32;function AK(e,t,n,{location:r=He.location,distance:o=He.distance,threshold:i=He.threshold,findAllMatches:s=He.findAllMatches,minMatchCharLength:l=He.minMatchCharLength,includeMatches:u=He.includeMatches,ignoreLocation:d=He.ignoreLocation}={}){if(t.length>ea)throw new Error(yK(ea));const h=t.length,m=e.length,g=Math.max(0,Math.min(r,m));let y=i,x=g;const _=l>1||u,C=_?Array(m):[];let S;for(;(S=e.indexOf(t,x))>-1;){let A=pp(t,{currentLocation:S,expectedLocation:g,distance:o,ignoreLocation:d});if(y=Math.min(A,y),x=S+h,_){let O=0;for(;O=V;U-=1){let te=U-1,L=n[e.charAt(te)];if(_&&(C[te]=+!!L),G[U]=(G[U+1]<<1|1)&L,A&&(G[U]|=(b[U+1]|b[U])<<1|1|b[U+1]),G[U]&P&&(E=pp(t,{errors:A,currentLocation:te,expectedLocation:g,distance:o,ignoreLocation:d}),E<=y)){if(y=E,x=te,x<=g)break;V=Math.max(1,2*g-x)}}if(pp(t,{errors:A+1,currentLocation:g,expectedLocation:g,distance:o,ignoreLocation:d})>y)break;b=G}const M={isMatch:x>=0,score:Math.max(.001,E)};if(_){const A=PK(C,l);A.length?u&&(M.indices=A):M.isMatch=!1}return M}function OK(e){let t={};for(let n=0,r=e.length;n{this.chunks.push({pattern:g,alphabet:OK(g),startIndex:y})},m=this.pattern.length;if(m>ea){let g=0;const y=m%ea,x=m-y;for(;g{const{isMatch:S,score:b,indices:E}=AK(t,x,_,{location:o+C,distance:i,threshold:s,findAllMatches:l,minMatchCharLength:u,includeMatches:r,ignoreLocation:d});S&&(g=!0),m+=b,S&&E&&(h=[...h,...E])});let y={isMatch:g,score:g?m/this.chunks.length:1};return g&&r&&(y.indices=h),y}}class Ds{constructor(t){this.pattern=t}static isMultiMatch(t){return c2(t,this.multiRegex)}static isSingleMatch(t){return c2(t,this.singleRegex)}search(){}}function c2(e,t){const n=e.match(t);return n?n[1]:null}class MK extends Ds{constructor(t){super(t)}static get type(){return"exact"}static get multiRegex(){return/^="(.*)"$/}static get singleRegex(){return/^=(.*)$/}search(t){const n=t===this.pattern;return{isMatch:n,score:n?0:1,indices:[0,this.pattern.length-1]}}}class NK extends Ds{constructor(t){super(t)}static get type(){return"inverse-exact"}static get multiRegex(){return/^!"(.*)"$/}static get singleRegex(){return/^!(.*)$/}search(t){const r=t.indexOf(this.pattern)===-1;return{isMatch:r,score:r?0:1,indices:[0,t.length-1]}}}class DK extends Ds{constructor(t){super(t)}static get type(){return"prefix-exact"}static get multiRegex(){return/^\^"(.*)"$/}static get singleRegex(){return/^\^(.*)$/}search(t){const n=t.startsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[0,this.pattern.length-1]}}}class IK extends Ds{constructor(t){super(t)}static get type(){return"inverse-prefix-exact"}static get multiRegex(){return/^!\^"(.*)"$/}static get singleRegex(){return/^!\^(.*)$/}search(t){const n=!t.startsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[0,t.length-1]}}}class LK extends Ds{constructor(t){super(t)}static get type(){return"suffix-exact"}static get multiRegex(){return/^"(.*)"\$$/}static get singleRegex(){return/^(.*)\$$/}search(t){const n=t.endsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[t.length-this.pattern.length,t.length-1]}}}class FK extends Ds{constructor(t){super(t)}static get type(){return"inverse-suffix-exact"}static get multiRegex(){return/^!"(.*)"\$$/}static get singleRegex(){return/^!(.*)\$$/}search(t){const n=!t.endsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[0,t.length-1]}}}class HP extends Ds{constructor(t,{location:n=He.location,threshold:r=He.threshold,distance:o=He.distance,includeMatches:i=He.includeMatches,findAllMatches:s=He.findAllMatches,minMatchCharLength:l=He.minMatchCharLength,isCaseSensitive:u=He.isCaseSensitive,ignoreLocation:d=He.ignoreLocation}={}){super(t),this._bitapSearch=new WP(t,{location:n,threshold:r,distance:o,includeMatches:i,findAllMatches:s,minMatchCharLength:l,isCaseSensitive:u,ignoreLocation:d})}static get type(){return"fuzzy"}static get multiRegex(){return/^"(.*)"$/}static get singleRegex(){return/^(.*)$/}search(t){return this._bitapSearch.searchIn(t)}}class KP extends Ds{constructor(t){super(t)}static get type(){return"include"}static get multiRegex(){return/^'"(.*)"$/}static get singleRegex(){return/^'(.*)$/}search(t){let n=0,r;const o=[],i=this.pattern.length;for(;(r=t.indexOf(this.pattern,n))>-1;)n=r+i,o.push([r,n-1]);const s=!!o.length;return{isMatch:s,score:s?0:1,indices:o}}}const m1=[MK,KP,DK,IK,FK,LK,NK,HP],u2=m1.length,jK=/ +(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/,zK="|";function BK(e,t={}){return e.split(zK).map(n=>{let r=n.trim().split(jK).filter(i=>i&&!!i.trim()),o=[];for(let i=0,s=r.length;i!!(e[jh.AND]||e[jh.OR]),HK=e=>!!e[y1.PATH],KK=e=>!bi(e)&&zP(e)&&!w1(e),d2=e=>({[jh.AND]:Object.keys(e).map(t=>({[t]:e[t]}))});function YP(e,t,{auto:n=!0}={}){const r=o=>{let i=Object.keys(o);const s=HK(o);if(!s&&i.length>1&&!w1(o))return r(d2(o));if(KK(o)){const u=s?o[y1.PATH]:i[0],d=s?o[y1.PATTERN]:o[u];if(!Lo(d))throw new Error(vK(u));const h={keyId:h1(u),pattern:d};return n&&(h.searcher=v1(d,t)),h}let l={children:[],operator:i[0]};return i.forEach(u=>{const d=o[u];bi(d)&&d.forEach(h=>{l.children.push(r(h))})}),l};return w1(e)||(e=d2(e)),r(e)}function YK(e,{ignoreFieldNorm:t=He.ignoreFieldNorm}){e.forEach(n=>{let r=1;n.matches.forEach(({key:o,norm:i,score:s})=>{const l=o?o.weight:null;r*=Math.pow(s===0&&l?Number.EPSILON:s,(l||1)*(t?1:i))}),n.score=r})}function GK(e,t){const n=e.matches;t.matches=[],hr(n)&&n.forEach(r=>{if(!hr(r.indices)||!r.indices.length)return;const{indices:o,value:i}=r;let s={indices:o,value:i};r.key&&(s.key=r.key.src),r.idx>-1&&(s.refIndex=r.idx),t.matches.push(s)})}function XK(e,t){t.score=e.score}function ZK(e,t,{includeMatches:n=He.includeMatches,includeScore:r=He.includeScore}={}){const o=[];return n&&o.push(GK),r&&o.push(XK),e.map(i=>{const{idx:s}=i,l={item:t[s],refIndex:s};return o.length&&o.forEach(u=>{u(i,l)}),l})}class _c{constructor(t,n={},r){this.options={...He,...n},this.options.useExtendedSearch,this._keyStore=new bK(this.options.keys),this.setCollection(t,r)}setCollection(t,n){if(this._docs=t,n&&!(n instanceof Nx))throw new Error(gK);this._myIndex=n||VP(this.options.keys,this._docs,{getFn:this.options.getFn,fieldNormWeight:this.options.fieldNormWeight})}add(t){hr(t)&&(this._docs.push(t),this._myIndex.add(t))}remove(t=()=>!1){const n=[];for(let r=0,o=this._docs.length;r-1&&(u=u.slice(0,n)),ZK(u,this._docs,{includeMatches:r,includeScore:o})}_searchStringList(t){const n=v1(t,this.options),{records:r}=this._myIndex,o=[];return r.forEach(({v:i,i:s,n:l})=>{if(!hr(i))return;const{isMatch:u,score:d,indices:h}=n.searchIn(i);u&&o.push({item:i,idx:s,matches:[{score:d,value:i,norm:l,indices:h}]})}),o}_searchLogical(t){const n=YP(t,this.options),r=(l,u,d)=>{if(!l.children){const{keyId:m,searcher:g}=l,y=this._findMatches({key:this._keyStore.get(m),value:this._myIndex.getValueForItemAtKeyId(u,m),searcher:g});return y&&y.length?[{idx:d,item:u,matches:y}]:[]}const h=[];for(let m=0,g=l.children.length;m{if(hr(l)){let d=r(n,l,u);d.length&&(i[u]||(i[u]={idx:u,item:l,matches:[]},s.push(i[u])),d.forEach(({matches:h})=>{i[u].matches.push(...h)}))}}),s}_searchObjectList(t){const n=v1(t,this.options),{keys:r,records:o}=this._myIndex,i=[];return o.forEach(({$:s,i:l})=>{if(!hr(s))return;let u=[];r.forEach((d,h)=>{u.push(...this._findMatches({key:d,value:s[h],searcher:n}))}),u.length&&i.push({idx:l,item:s,matches:u})}),i}_findMatches({key:t,value:n,searcher:r}){if(!hr(n))return[];let o=[];if(bi(n))n.forEach(({v:i,i:s,n:l})=>{if(!hr(i))return;const{isMatch:u,score:d,indices:h}=r.searchIn(i);u&&o.push({score:d,key:t,value:i,idx:s,norm:l,indices:h})});else{const{v:i,n:s}=n,{isMatch:l,score:u,indices:d}=r.searchIn(i);l&&o.push({score:u,key:t,value:i,norm:s,indices:d})}return o}}_c.version="7.0.0";_c.createIndex=VP;_c.parseIndex=TK;_c.config=He;_c.parseQuery=YP;WK(VK);function zd(e){const t=e+"CollectionProvider",[n,r]=An(t),[o,i]=n(t,{collectionRef:{current:null},itemMap:new Map}),s=y=>{const{scope:x,children:_}=y,C=Fe.useRef(null),S=Fe.useRef(new Map).current;return Fe.createElement(o,{scope:x,itemMap:S,collectionRef:C},_)},l=e+"CollectionSlot",u=Fe.forwardRef((y,x)=>{const{scope:_,children:C}=y,S=i(l,_),b=Be(x,S.collectionRef);return Fe.createElement(Wo,{ref:b},C)}),d=e+"CollectionItemSlot",h="data-radix-collection-item",m=Fe.forwardRef((y,x)=>{const{scope:_,children:C,...S}=y,b=Fe.useRef(null),E=Be(x,b),k=i(d,_);return Fe.useEffect(()=>(k.itemMap.set(b,{ref:b,...S}),()=>void k.itemMap.delete(b))),Fe.createElement(Wo,{[h]:"",ref:E},C)});function g(y){const x=i(e+"CollectionConsumer",y);return Fe.useCallback(()=>{const C=x.collectionRef.current;if(!C)return[];const S=Array.from(C.querySelectorAll(`[${h}]`));return Array.from(x.itemMap.values()).sort((k,P)=>S.indexOf(k.ref.current)-S.indexOf(P.ref.current))},[x.collectionRef,x.itemMap])}return[{Provider:s,Slot:u,ItemSlot:m},g,r]}const qK=f.createContext(void 0);function Sc(e){const t=f.useContext(qK);return e||t||"ltr"}const R0="rovingFocusGroup.onEntryFocus",QK={bubbles:!1,cancelable:!0},Dx="RovingFocusGroup",[x1,GP,JK]=zd(Dx),[eY,Qm]=An(Dx,[JK]),[tY,nY]=eY(Dx),rY=f.forwardRef((e,t)=>f.createElement(x1.Provider,{scope:e.__scopeRovingFocusGroup},f.createElement(x1.Slot,{scope:e.__scopeRovingFocusGroup},f.createElement(oY,Y({},e,{ref:t}))))),oY=f.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:o=!1,dir:i,currentTabStopId:s,defaultCurrentTabStopId:l,onCurrentTabStopIdChange:u,onEntryFocus:d,...h}=e,m=f.useRef(null),g=Be(t,m),y=Sc(i),[x=null,_]=Zr({prop:s,defaultProp:l,onChange:u}),[C,S]=f.useState(!1),b=Ft(d),E=GP(n),k=f.useRef(!1),[P,M]=f.useState(0);return f.useEffect(()=>{const A=m.current;if(A)return A.addEventListener(R0,b),()=>A.removeEventListener(R0,b)},[b]),f.createElement(tY,{scope:n,orientation:r,dir:y,loop:o,currentTabStopId:x,onItemFocus:f.useCallback(A=>_(A),[_]),onItemShiftTab:f.useCallback(()=>S(!0),[]),onFocusableItemAdd:f.useCallback(()=>M(A=>A+1),[]),onFocusableItemRemove:f.useCallback(()=>M(A=>A-1),[])},f.createElement(Pe.div,Y({tabIndex:C||P===0?-1:0,"data-orientation":r},h,{ref:g,style:{outline:"none",...e.style},onMouseDown:ue(e.onMouseDown,()=>{k.current=!0}),onFocus:ue(e.onFocus,A=>{const O=!k.current;if(A.target===A.currentTarget&&O&&!C){const F=new CustomEvent(R0,QK);if(A.currentTarget.dispatchEvent(F),!F.defaultPrevented){const V=E().filter(te=>te.focusable),J=V.find(te=>te.active),G=V.find(te=>te.id===x),U=[J,G,...V].filter(Boolean).map(te=>te.ref.current);XP(U)}}k.current=!1}),onBlur:ue(e.onBlur,()=>S(!1))})))}),iY="RovingFocusGroupItem",sY=f.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:o=!1,tabStopId:i,...s}=e,l=nr(),u=i||l,d=nY(iY,n),h=d.currentTabStopId===u,m=GP(n),{onFocusableItemAdd:g,onFocusableItemRemove:y}=d;return f.useEffect(()=>{if(r)return g(),()=>y()},[r,g,y]),f.createElement(x1.ItemSlot,{scope:n,id:u,focusable:r,active:o},f.createElement(Pe.span,Y({tabIndex:h?0:-1,"data-orientation":d.orientation},s,{ref:t,onMouseDown:ue(e.onMouseDown,x=>{r?d.onItemFocus(u):x.preventDefault()}),onFocus:ue(e.onFocus,()=>d.onItemFocus(u)),onKeyDown:ue(e.onKeyDown,x=>{if(x.key==="Tab"&&x.shiftKey){d.onItemShiftTab();return}if(x.target!==x.currentTarget)return;const _=cY(x,d.orientation,d.dir);if(_!==void 0){x.preventDefault();let S=m().filter(b=>b.focusable).map(b=>b.ref.current);if(_==="last")S.reverse();else if(_==="prev"||_==="next"){_==="prev"&&S.reverse();const b=S.indexOf(x.currentTarget);S=d.loop?uY(S,b+1):S.slice(b+1)}setTimeout(()=>XP(S))}})})))}),aY={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function lY(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function cY(e,t,n){const r=lY(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return aY[r]}function XP(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function uY(e,t){return e.map((n,r)=>e[(t+r)%e.length])}const ZP=rY,qP=sY,QP="Tabs",[dY,wte]=An(QP,[Qm]),JP=Qm(),[fY,Ix]=dY(QP),pY=f.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,onValueChange:o,defaultValue:i,orientation:s="horizontal",dir:l,activationMode:u="automatic",...d}=e,h=Sc(l),[m,g]=Zr({prop:r,onChange:o,defaultProp:i});return f.createElement(fY,{scope:n,baseId:nr(),value:m,onValueChange:g,orientation:s,dir:h,activationMode:u},f.createElement(Pe.div,Y({dir:h,"data-orientation":s},d,{ref:t})))}),hY="TabsList",mY=f.forwardRef((e,t)=>{const{__scopeTabs:n,loop:r=!0,...o}=e,i=Ix(hY,n),s=JP(n);return f.createElement(ZP,Y({asChild:!0},s,{orientation:i.orientation,dir:i.dir,loop:r}),f.createElement(Pe.div,Y({role:"tablist","aria-orientation":i.orientation},o,{ref:t})))}),gY="TabsTrigger",vY=f.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,disabled:o=!1,...i}=e,s=Ix(gY,n),l=JP(n),u=e5(s.baseId,r),d=t5(s.baseId,r),h=r===s.value;return f.createElement(qP,Y({asChild:!0},l,{focusable:!o,active:h}),f.createElement(Pe.button,Y({type:"button",role:"tab","aria-selected":h,"aria-controls":d,"data-state":h?"active":"inactive","data-disabled":o?"":void 0,disabled:o,id:u},i,{ref:t,onMouseDown:ue(e.onMouseDown,m=>{!o&&m.button===0&&m.ctrlKey===!1?s.onValueChange(r):m.preventDefault()}),onKeyDown:ue(e.onKeyDown,m=>{[" ","Enter"].includes(m.key)&&s.onValueChange(r)}),onFocus:ue(e.onFocus,()=>{const m=s.activationMode!=="manual";!h&&!o&&m&&s.onValueChange(r)})})))}),yY="TabsContent",wY=f.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,forceMount:o,children:i,...s}=e,l=Ix(yY,n),u=e5(l.baseId,r),d=t5(l.baseId,r),h=r===l.value,m=f.useRef(h);return f.useEffect(()=>{const g=requestAnimationFrame(()=>m.current=!1);return()=>cancelAnimationFrame(g)},[]),f.createElement(bn,{present:o||h},({present:g})=>f.createElement(Pe.div,Y({"data-state":h?"active":"inactive","data-orientation":l.orientation,role:"tabpanel","aria-labelledby":u,hidden:!g,id:d,tabIndex:0},s,{ref:t,style:{...e.style,animationDuration:m.current?"0s":void 0}}),g&&i))});function e5(e,t){return`${e}-trigger-${t}`}function t5(e,t){return`${e}-content-${t}`}const xY=pY,n5=mY,r5=vY,o5=wY,i5=xY,Lx=f.forwardRef(({className:e,...t},n)=>v.jsx(n5,{ref:n,className:Ce("inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground",e),tabIndex:-1,...t}));Lx.displayName=n5.displayName;const sa=f.forwardRef(({className:e,...t},n)=>v.jsx(r5,{ref:n,className:Ce("inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow",e),tabIndex:-1,...t}));sa.displayName=r5.displayName;const mu=f.forwardRef(({className:e,...t},n)=>v.jsx(o5,{ref:n,className:Ce("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",e),tabIndex:-1,...t}));mu.displayName=o5.displayName;function id(e,[t,n]){return Math.min(n,Math.max(t,e))}function Fx(e){const t=f.useRef({value:e,previous:e});return f.useMemo(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}const bY=[" ","Enter","ArrowUp","ArrowDown"],_Y=[" ","Enter"],Jm="Select",[eg,tg,SY]=zd(Jm),[Ec,xte]=An(Jm,[SY,Ns]),jx=Ns(),[EY,Oa]=Ec(Jm),[CY,$Y]=Ec(Jm),kY=e=>{const{__scopeSelect:t,children:n,open:r,defaultOpen:o,onOpenChange:i,value:s,defaultValue:l,onValueChange:u,dir:d,name:h,autoComplete:m,disabled:g,required:y}=e,x=jx(t),[_,C]=f.useState(null),[S,b]=f.useState(null),[E,k]=f.useState(!1),P=Sc(d),[M=!1,A]=Zr({prop:r,defaultProp:o,onChange:i}),[O,F]=Zr({prop:s,defaultProp:l,onChange:u}),V=f.useRef(null),J=_?!!_.closest("form"):!0,[G,ae]=f.useState(new Set),U=Array.from(G).map(te=>te.props.value).join(";");return f.createElement(Od,x,f.createElement(EY,{required:y,scope:t,trigger:_,onTriggerChange:C,valueNode:S,onValueNodeChange:b,valueNodeHasChildren:E,onValueNodeHasChildrenChange:k,contentId:nr(),value:O,onValueChange:F,open:M,onOpenChange:A,dir:P,triggerPointerDownPosRef:V,disabled:g},f.createElement(eg.Provider,{scope:t},f.createElement(CY,{scope:e.__scopeSelect,onNativeOptionAdd:f.useCallback(te=>{ae(L=>new Set(L).add(te))},[]),onNativeOptionRemove:f.useCallback(te=>{ae(L=>{const ie=new Set(L);return ie.delete(te),ie})},[])},n)),J?f.createElement(u5,{key:U,"aria-hidden":!0,required:y,tabIndex:-1,name:h,autoComplete:m,value:O,onChange:te=>F(te.target.value),disabled:g},O===void 0?f.createElement("option",{value:""}):null,Array.from(G)):null))},RY="SelectTrigger",TY=f.forwardRef((e,t)=>{const{__scopeSelect:n,disabled:r=!1,...o}=e,i=jx(n),s=Oa(RY,n),l=s.disabled||r,u=Be(t,s.onTriggerChange),d=tg(n),[h,m,g]=d5(x=>{const _=d().filter(b=>!b.disabled),C=_.find(b=>b.value===s.value),S=f5(_,x,C);S!==void 0&&s.onValueChange(S.value)}),y=()=>{l||(s.onOpenChange(!0),g())};return f.createElement(zm,Y({asChild:!0},i),f.createElement(Pe.button,Y({type:"button",role:"combobox","aria-controls":s.contentId,"aria-expanded":s.open,"aria-required":s.required,"aria-autocomplete":"none",dir:s.dir,"data-state":s.open?"open":"closed",disabled:l,"data-disabled":l?"":void 0,"data-placeholder":c5(s.value)?"":void 0},o,{ref:u,onClick:ue(o.onClick,x=>{x.currentTarget.focus()}),onPointerDown:ue(o.onPointerDown,x=>{const _=x.target;_.hasPointerCapture(x.pointerId)&&_.releasePointerCapture(x.pointerId),x.button===0&&x.ctrlKey===!1&&(y(),s.triggerPointerDownPosRef.current={x:Math.round(x.pageX),y:Math.round(x.pageY)},x.preventDefault())}),onKeyDown:ue(o.onKeyDown,x=>{const _=h.current!=="";!(x.ctrlKey||x.altKey||x.metaKey)&&x.key.length===1&&m(x.key),!(_&&x.key===" ")&&bY.includes(x.key)&&(y(),x.preventDefault())})})))}),PY="SelectValue",AY=f.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,children:i,placeholder:s="",...l}=e,u=Oa(PY,n),{onValueNodeHasChildrenChange:d}=u,h=i!==void 0,m=Be(t,u.onValueNodeChange);return Pn(()=>{d(h)},[d,h]),f.createElement(Pe.span,Y({},l,{ref:m,style:{pointerEvents:"none"}}),c5(u.value)?f.createElement(f.Fragment,null,s):i)}),OY=f.forwardRef((e,t)=>{const{__scopeSelect:n,children:r,...o}=e;return f.createElement(Pe.span,Y({"aria-hidden":!0},o,{ref:t}),r||"▼")}),MY=e=>f.createElement(Md,Y({asChild:!0},e)),ic="SelectContent",NY=f.forwardRef((e,t)=>{const n=Oa(ic,e.__scopeSelect),[r,o]=f.useState();if(Pn(()=>{o(new DocumentFragment)},[]),!n.open){const i=r;return i?Os.createPortal(f.createElement(s5,{scope:e.__scopeSelect},f.createElement(eg.Slot,{scope:e.__scopeSelect},f.createElement("div",null,e.children))),i):null}return f.createElement(DY,Y({},e,{ref:t}))}),ai=10,[s5,Ma]=Ec(ic),DY=f.forwardRef((e,t)=>{const{__scopeSelect:n,position:r="item-aligned",onCloseAutoFocus:o,onEscapeKeyDown:i,onPointerDownOutside:s,side:l,sideOffset:u,align:d,alignOffset:h,arrowPadding:m,collisionBoundary:g,collisionPadding:y,sticky:x,hideWhenDetached:_,avoidCollisions:C,...S}=e,b=Oa(ic,n),[E,k]=f.useState(null),[P,M]=f.useState(null),A=Be(t,fe=>k(fe)),[O,F]=f.useState(null),[V,J]=f.useState(null),G=tg(n),[ae,U]=f.useState(!1),te=f.useRef(!1);f.useEffect(()=>{if(E)return Xm(E)},[E]),Km();const L=f.useCallback(fe=>{const[xe,...$e]=G().map(je=>je.ref.current),[Ae]=$e.slice(-1),Oe=document.activeElement;for(const je of fe)if(je===Oe||(je==null||je.scrollIntoView({block:"nearest"}),je===xe&&P&&(P.scrollTop=0),je===Ae&&P&&(P.scrollTop=P.scrollHeight),je==null||je.focus(),document.activeElement!==Oe))return},[G,P]),ie=f.useCallback(()=>L([O,E]),[L,O,E]);f.useEffect(()=>{ae&&ie()},[ae,ie]);const{onOpenChange:K,triggerPointerDownPosRef:Q}=b;f.useEffect(()=>{if(E){let fe={x:0,y:0};const xe=Ae=>{var Oe,je,Ot,ct;fe={x:Math.abs(Math.round(Ae.pageX)-((Oe=(je=Q.current)===null||je===void 0?void 0:je.x)!==null&&Oe!==void 0?Oe:0)),y:Math.abs(Math.round(Ae.pageY)-((Ot=(ct=Q.current)===null||ct===void 0?void 0:ct.y)!==null&&Ot!==void 0?Ot:0))}},$e=Ae=>{fe.x<=10&&fe.y<=10?Ae.preventDefault():E.contains(Ae.target)||K(!1),document.removeEventListener("pointermove",xe),Q.current=null};return Q.current!==null&&(document.addEventListener("pointermove",xe),document.addEventListener("pointerup",$e,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",xe),document.removeEventListener("pointerup",$e,{capture:!0})}}},[E,K,Q]),f.useEffect(()=>{const fe=()=>K(!1);return window.addEventListener("blur",fe),window.addEventListener("resize",fe),()=>{window.removeEventListener("blur",fe),window.removeEventListener("resize",fe)}},[K]);const[W,le]=d5(fe=>{const xe=G().filter(Oe=>!Oe.disabled),$e=xe.find(Oe=>Oe.ref.current===document.activeElement),Ae=f5(xe,fe,$e);Ae&&setTimeout(()=>Ae.ref.current.focus())}),ge=f.useCallback((fe,xe,$e)=>{const Ae=!te.current&&!$e;(b.value!==void 0&&b.value===xe||Ae)&&(F(fe),Ae&&(te.current=!0))},[b.value]),Ve=f.useCallback(()=>E==null?void 0:E.focus(),[E]),Ue=f.useCallback((fe,xe,$e)=>{const Ae=!te.current&&!$e;(b.value!==void 0&&b.value===xe||Ae)&&J(fe)},[b.value]),We=r==="popper"?f2:IY,Me=We===f2?{side:l,sideOffset:u,align:d,alignOffset:h,arrowPadding:m,collisionBoundary:g,collisionPadding:y,sticky:x,hideWhenDetached:_,avoidCollisions:C}:{};return f.createElement(s5,{scope:n,content:E,viewport:P,onViewportChange:M,itemRefCallback:ge,selectedItem:O,onItemLeave:Ve,itemTextRefCallback:Ue,focusSelectedItem:ie,selectedItemText:V,position:r,isPositioned:ae,searchRef:W},f.createElement(Gm,{as:Wo,allowPinchZoom:!0},f.createElement(Hm,{asChild:!0,trapped:b.open,onMountAutoFocus:fe=>{fe.preventDefault()},onUnmountAutoFocus:ue(o,fe=>{var xe;(xe=b.trigger)===null||xe===void 0||xe.focus({preventScroll:!0}),fe.preventDefault()})},f.createElement(yc,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:i,onPointerDownOutside:s,onFocusOutside:fe=>fe.preventDefault(),onDismiss:()=>b.onOpenChange(!1)},f.createElement(We,Y({role:"listbox",id:b.contentId,"data-state":b.open?"open":"closed",dir:b.dir,onContextMenu:fe=>fe.preventDefault()},S,Me,{onPlaced:()=>U(!0),ref:A,style:{display:"flex",flexDirection:"column",outline:"none",...S.style},onKeyDown:ue(S.onKeyDown,fe=>{const xe=fe.ctrlKey||fe.altKey||fe.metaKey;if(fe.key==="Tab"&&fe.preventDefault(),!xe&&fe.key.length===1&&le(fe.key),["ArrowUp","ArrowDown","Home","End"].includes(fe.key)){let Ae=G().filter(Oe=>!Oe.disabled).map(Oe=>Oe.ref.current);if(["ArrowUp","End"].includes(fe.key)&&(Ae=Ae.slice().reverse()),["ArrowUp","ArrowDown"].includes(fe.key)){const Oe=fe.target,je=Ae.indexOf(Oe);Ae=Ae.slice(je+1)}setTimeout(()=>L(Ae)),fe.preventDefault()}})}))))))}),IY=f.forwardRef((e,t)=>{const{__scopeSelect:n,onPlaced:r,...o}=e,i=Oa(ic,n),s=Ma(ic,n),[l,u]=f.useState(null),[d,h]=f.useState(null),m=Be(t,A=>h(A)),g=tg(n),y=f.useRef(!1),x=f.useRef(!0),{viewport:_,selectedItem:C,selectedItemText:S,focusSelectedItem:b}=s,E=f.useCallback(()=>{if(i.trigger&&i.valueNode&&l&&d&&_&&C&&S){const A=i.trigger.getBoundingClientRect(),O=d.getBoundingClientRect(),F=i.valueNode.getBoundingClientRect(),V=S.getBoundingClientRect();if(i.dir!=="rtl"){const Oe=V.left-O.left,je=F.left-Oe,Ot=A.left-je,ct=A.width+Ot,Kt=Math.max(ct,O.width),Er=window.innerWidth-ai,gt=id(je,[ai,Er-Kt]);l.style.minWidth=ct+"px",l.style.left=gt+"px"}else{const Oe=O.right-V.right,je=window.innerWidth-F.right-Oe,Ot=window.innerWidth-A.right-je,ct=A.width+Ot,Kt=Math.max(ct,O.width),Er=window.innerWidth-ai,gt=id(je,[ai,Er-Kt]);l.style.minWidth=ct+"px",l.style.right=gt+"px"}const J=g(),G=window.innerHeight-ai*2,ae=_.scrollHeight,U=window.getComputedStyle(d),te=parseInt(U.borderTopWidth,10),L=parseInt(U.paddingTop,10),ie=parseInt(U.borderBottomWidth,10),K=parseInt(U.paddingBottom,10),Q=te+L+ae+K+ie,W=Math.min(C.offsetHeight*5,Q),le=window.getComputedStyle(_),ge=parseInt(le.paddingTop,10),Ve=parseInt(le.paddingBottom,10),Ue=A.top+A.height/2-ai,We=G-Ue,Me=C.offsetHeight/2,fe=C.offsetTop+Me,xe=te+L+fe,$e=Q-xe;if(xe<=Ue){const Oe=C===J[J.length-1].ref.current;l.style.bottom="0px";const je=d.clientHeight-_.offsetTop-_.offsetHeight,Ot=Math.max(We,Me+(Oe?Ve:0)+je+ie),ct=xe+Ot;l.style.height=ct+"px"}else{const Oe=C===J[0].ref.current;l.style.top="0px";const Ot=Math.max(Ue,te+_.offsetTop+(Oe?ge:0)+Me)+$e;l.style.height=Ot+"px",_.scrollTop=xe-Ue+_.offsetTop}l.style.margin=`${ai}px 0`,l.style.minHeight=W+"px",l.style.maxHeight=G+"px",r==null||r(),requestAnimationFrame(()=>y.current=!0)}},[g,i.trigger,i.valueNode,l,d,_,C,S,i.dir,r]);Pn(()=>E(),[E]);const[k,P]=f.useState();Pn(()=>{d&&P(window.getComputedStyle(d).zIndex)},[d]);const M=f.useCallback(A=>{A&&x.current===!0&&(E(),b==null||b(),x.current=!1)},[E,b]);return f.createElement(LY,{scope:n,contentWrapper:l,shouldExpandOnScrollRef:y,onScrollButtonChange:M},f.createElement("div",{ref:u,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:k}},f.createElement(Pe.div,Y({},o,{ref:m,style:{boxSizing:"border-box",maxHeight:"100%",...o.style}}))))}),f2=f.forwardRef((e,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:o=ai,...i}=e,s=jx(n);return f.createElement(Bm,Y({},s,i,{ref:t,align:r,collisionPadding:o,style:{boxSizing:"border-box",...i.style,"--radix-select-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-select-content-available-width":"var(--radix-popper-available-width)","--radix-select-content-available-height":"var(--radix-popper-available-height)","--radix-select-trigger-width":"var(--radix-popper-anchor-width)","--radix-select-trigger-height":"var(--radix-popper-anchor-height)"}}))}),[LY,zx]=Ec(ic,{}),p2="SelectViewport",FY=f.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=Ma(p2,n),i=zx(p2,n),s=Be(t,o.onViewportChange),l=f.useRef(0);return f.createElement(f.Fragment,null,f.createElement("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"}}),f.createElement(eg.Slot,{scope:n},f.createElement(Pe.div,Y({"data-radix-select-viewport":"",role:"presentation"},r,{ref:s,style:{position:"relative",flex:1,overflow:"auto",...r.style},onScroll:ue(r.onScroll,u=>{const d=u.currentTarget,{contentWrapper:h,shouldExpandOnScrollRef:m}=i;if(m!=null&&m.current&&h){const g=Math.abs(l.current-d.scrollTop);if(g>0){const y=window.innerHeight-ai*2,x=parseFloat(h.style.minHeight),_=parseFloat(h.style.height),C=Math.max(x,_);if(C0?E:0,h.style.justifyContent="flex-end")}}}l.current=d.scrollTop})}))))}),jY="SelectGroup",[zY,BY]=Ec(jY),UY=f.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=nr();return f.createElement(zY,{scope:n,id:o},f.createElement(Pe.div,Y({role:"group","aria-labelledby":o},r,{ref:t})))}),VY="SelectLabel",WY=f.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=BY(VY,n);return f.createElement(Pe.div,Y({id:o.id},r,{ref:t}))}),b1="SelectItem",[HY,a5]=Ec(b1),KY=f.forwardRef((e,t)=>{const{__scopeSelect:n,value:r,disabled:o=!1,textValue:i,...s}=e,l=Oa(b1,n),u=Ma(b1,n),d=l.value===r,[h,m]=f.useState(i??""),[g,y]=f.useState(!1),x=Be(t,S=>{var b;return(b=u.itemRefCallback)===null||b===void 0?void 0:b.call(u,S,r,o)}),_=nr(),C=()=>{o||(l.onValueChange(r),l.onOpenChange(!1))};if(r==="")throw new Error("A must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.");return f.createElement(HY,{scope:n,value:r,disabled:o,textId:_,isSelected:d,onItemTextChange:f.useCallback(S=>{m(b=>{var E;return b||((E=S==null?void 0:S.textContent)!==null&&E!==void 0?E:"").trim()})},[])},f.createElement(eg.ItemSlot,{scope:n,value:r,disabled:o,textValue:h},f.createElement(Pe.div,Y({role:"option","aria-labelledby":_,"data-highlighted":g?"":void 0,"aria-selected":d&&g,"data-state":d?"checked":"unchecked","aria-disabled":o||void 0,"data-disabled":o?"":void 0,tabIndex:o?void 0:-1},s,{ref:x,onFocus:ue(s.onFocus,()=>y(!0)),onBlur:ue(s.onBlur,()=>y(!1)),onPointerUp:ue(s.onPointerUp,C),onPointerMove:ue(s.onPointerMove,S=>{if(o){var b;(b=u.onItemLeave)===null||b===void 0||b.call(u)}else S.currentTarget.focus({preventScroll:!0})}),onPointerLeave:ue(s.onPointerLeave,S=>{if(S.currentTarget===document.activeElement){var b;(b=u.onItemLeave)===null||b===void 0||b.call(u)}}),onKeyDown:ue(s.onKeyDown,S=>{var b;((b=u.searchRef)===null||b===void 0?void 0:b.current)!==""&&S.key===" "||(_Y.includes(S.key)&&C(),S.key===" "&&S.preventDefault())})}))))}),hp="SelectItemText",YY=f.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,...i}=e,s=Oa(hp,n),l=Ma(hp,n),u=a5(hp,n),d=$Y(hp,n),[h,m]=f.useState(null),g=Be(t,S=>m(S),u.onItemTextChange,S=>{var b;return(b=l.itemTextRefCallback)===null||b===void 0?void 0:b.call(l,S,u.value,u.disabled)}),y=h==null?void 0:h.textContent,x=f.useMemo(()=>f.createElement("option",{key:u.value,value:u.value,disabled:u.disabled},y),[u.disabled,u.value,y]),{onNativeOptionAdd:_,onNativeOptionRemove:C}=d;return Pn(()=>(_(x),()=>C(x)),[_,C,x]),f.createElement(f.Fragment,null,f.createElement(Pe.span,Y({id:u.textId},i,{ref:g})),u.isSelected&&s.valueNode&&!s.valueNodeHasChildren?Os.createPortal(i.children,s.valueNode):null)}),GY="SelectItemIndicator",XY=f.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return a5(GY,n).isSelected?f.createElement(Pe.span,Y({"aria-hidden":!0},r,{ref:t})):null}),h2="SelectScrollUpButton",ZY=f.forwardRef((e,t)=>{const n=Ma(h2,e.__scopeSelect),r=zx(h2,e.__scopeSelect),[o,i]=f.useState(!1),s=Be(t,r.onScrollButtonChange);return Pn(()=>{if(n.viewport&&n.isPositioned){let d=function(){const h=u.scrollTop>0;i(h)};var l=d;const u=n.viewport;return d(),u.addEventListener("scroll",d),()=>u.removeEventListener("scroll",d)}},[n.viewport,n.isPositioned]),o?f.createElement(l5,Y({},e,{ref:s,onAutoScroll:()=>{const{viewport:l,selectedItem:u}=n;l&&u&&(l.scrollTop=l.scrollTop-u.offsetHeight)}})):null}),m2="SelectScrollDownButton",qY=f.forwardRef((e,t)=>{const n=Ma(m2,e.__scopeSelect),r=zx(m2,e.__scopeSelect),[o,i]=f.useState(!1),s=Be(t,r.onScrollButtonChange);return Pn(()=>{if(n.viewport&&n.isPositioned){let d=function(){const h=u.scrollHeight-u.clientHeight,m=Math.ceil(u.scrollTop)u.removeEventListener("scroll",d)}},[n.viewport,n.isPositioned]),o?f.createElement(l5,Y({},e,{ref:s,onAutoScroll:()=>{const{viewport:l,selectedItem:u}=n;l&&u&&(l.scrollTop=l.scrollTop+u.offsetHeight)}})):null}),l5=f.forwardRef((e,t)=>{const{__scopeSelect:n,onAutoScroll:r,...o}=e,i=Ma("SelectScrollButton",n),s=f.useRef(null),l=tg(n),u=f.useCallback(()=>{s.current!==null&&(window.clearInterval(s.current),s.current=null)},[]);return f.useEffect(()=>()=>u(),[u]),Pn(()=>{var d;const h=l().find(m=>m.ref.current===document.activeElement);h==null||(d=h.ref.current)===null||d===void 0||d.scrollIntoView({block:"nearest"})},[l]),f.createElement(Pe.div,Y({"aria-hidden":!0},o,{ref:t,style:{flexShrink:0,...o.style},onPointerDown:ue(o.onPointerDown,()=>{s.current===null&&(s.current=window.setInterval(r,50))}),onPointerMove:ue(o.onPointerMove,()=>{var d;(d=i.onItemLeave)===null||d===void 0||d.call(i),s.current===null&&(s.current=window.setInterval(r,50))}),onPointerLeave:ue(o.onPointerLeave,()=>{u()})}))}),QY=f.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return f.createElement(Pe.div,Y({"aria-hidden":!0},r,{ref:t}))});function c5(e){return e===""||e===void 0}const u5=f.forwardRef((e,t)=>{const{value:n,...r}=e,o=f.useRef(null),i=Be(t,o),s=Fx(n);return f.useEffect(()=>{const l=o.current,u=window.HTMLSelectElement.prototype,h=Object.getOwnPropertyDescriptor(u,"value").set;if(s!==n&&h){const m=new Event("change",{bubbles:!0});h.call(l,n),l.dispatchEvent(m)}},[s,n]),f.createElement(Um,{asChild:!0},f.createElement("select",Y({},r,{ref:i,defaultValue:n})))});u5.displayName="BubbleSelect";function d5(e){const t=Ft(e),n=f.useRef(""),r=f.useRef(0),o=f.useCallback(s=>{const l=n.current+s;t(l),function u(d){n.current=d,window.clearTimeout(r.current),d!==""&&(r.current=window.setTimeout(()=>u(""),1e3))}(l)},[t]),i=f.useCallback(()=>{n.current="",window.clearTimeout(r.current)},[]);return f.useEffect(()=>()=>window.clearTimeout(r.current),[]),[n,o,i]}function f5(e,t,n){const o=t.length>1&&Array.from(t).every(d=>d===t[0])?t[0]:t,i=n?e.indexOf(n):-1;let s=JY(e,Math.max(i,0));o.length===1&&(s=s.filter(d=>d!==n));const u=s.find(d=>d.textValue.toLowerCase().startsWith(o.toLowerCase()));return u!==n?u:void 0}function JY(e,t){return e.map((n,r)=>e[(t+r)%e.length])}const eG=kY,p5=TY,tG=AY,nG=OY,rG=MY,h5=NY,oG=FY,iG=UY,m5=WY,g5=KY,sG=YY,aG=XY,v5=ZY,y5=qY,w5=QY,aa=eG,wl=iG,la=tG,ls=f.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(p5,{ref:r,className:Ce("flex h-9 w-full items-center justify-between whitespace-nowrap rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",e),tabIndex:-1,...n,children:[t,v.jsx(nG,{asChild:!0,children:v.jsx(Xj,{className:"h-4 w-4 opacity-50"})})]}));ls.displayName=p5.displayName;const x5=f.forwardRef(({className:e,...t},n)=>v.jsx(v5,{ref:n,className:Ce("flex cursor-default items-center justify-center py-1",e),...t,children:v.jsx(nz,{})}));x5.displayName=v5.displayName;const b5=f.forwardRef(({className:e,...t},n)=>v.jsx(y5,{ref:n,className:Ce("flex cursor-default items-center justify-center py-1",e),...t,children:v.jsx(Qj,{})}));b5.displayName=y5.displayName;const cs=f.forwardRef(({className:e,children:t,position:n="popper",...r},o)=>v.jsx(rG,{children:v.jsxs(h5,{ref:o,className:Ce("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",n==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:n,onCloseAutoFocus:i=>i.preventDefault(),...r,children:[v.jsx(x5,{}),v.jsx(oG,{className:Ce("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),v.jsx(b5,{})]})}));cs.displayName=h5.displayName;const lG=f.forwardRef(({className:e,...t},n)=>v.jsx(m5,{ref:n,className:Ce("px-2 py-1.5 text-sm font-semibold",e),...t}));lG.displayName=m5.displayName;const us=f.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(g5,{ref:r,className:Ce("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-2 pr-8 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[v.jsx("span",{className:"absolute right-2 flex h-3.5 w-3.5 items-center justify-center",children:v.jsx(aG,{children:v.jsx(vT,{className:"h-4 w-4"})})}),v.jsx(sG,{children:t})]}));us.displayName=g5.displayName;const cG=f.forwardRef(({className:e,...t},n)=>v.jsx(w5,{ref:n,className:Ce("-mx-1 my-1 h-px bg-muted",e),...t}));cG.displayName=w5.displayName;function uG(e,t){return f.useReducer((n,r)=>{const o=t[n][r];return o??n},e)}const _5="ScrollArea",[S5,bte]=An(_5),[dG,qr]=S5(_5),fG=f.forwardRef((e,t)=>{const{__scopeScrollArea:n,type:r="hover",dir:o,scrollHideDelay:i=600,...s}=e,[l,u]=f.useState(null),[d,h]=f.useState(null),[m,g]=f.useState(null),[y,x]=f.useState(null),[_,C]=f.useState(null),[S,b]=f.useState(0),[E,k]=f.useState(0),[P,M]=f.useState(!1),[A,O]=f.useState(!1),F=Be(t,J=>u(J)),V=Sc(o);return f.createElement(dG,{scope:n,type:r,dir:V,scrollHideDelay:i,scrollArea:l,viewport:d,onViewportChange:h,content:m,onContentChange:g,scrollbarX:y,onScrollbarXChange:x,scrollbarXEnabled:P,onScrollbarXEnabledChange:M,scrollbarY:_,onScrollbarYChange:C,scrollbarYEnabled:A,onScrollbarYEnabledChange:O,onCornerWidthChange:b,onCornerHeightChange:k},f.createElement(Pe.div,Y({dir:V},s,{ref:F,style:{position:"relative","--radix-scroll-area-corner-width":S+"px","--radix-scroll-area-corner-height":E+"px",...e.style}})))}),pG="ScrollAreaViewport",hG=f.forwardRef((e,t)=>{const{__scopeScrollArea:n,children:r,...o}=e,i=qr(pG,n),s=f.useRef(null),l=Be(t,s,i.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(Pe.div,Y({"data-radix-scroll-area-viewport":""},o,{ref:l,style:{overflowX:i.scrollbarXEnabled?"scroll":"hidden",overflowY:i.scrollbarYEnabled?"scroll":"hidden",...e.style}}),f.createElement("div",{ref:i.onContentChange,style:{minWidth:"100%",display:"table"}},r)))}),$i="ScrollAreaScrollbar",E5=f.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=qr($i,e.__scopeScrollArea),{onScrollbarXEnabledChange:i,onScrollbarYEnabledChange:s}=o,l=e.orientation==="horizontal";return f.useEffect(()=>(l?i(!0):s(!0),()=>{l?i(!1):s(!1)}),[l,i,s]),o.type==="hover"?f.createElement(mG,Y({},r,{ref:t,forceMount:n})):o.type==="scroll"?f.createElement(gG,Y({},r,{ref:t,forceMount:n})):o.type==="auto"?f.createElement(C5,Y({},r,{ref:t,forceMount:n})):o.type==="always"?f.createElement(Bx,Y({},r,{ref:t})):null}),mG=f.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=qr($i,e.__scopeScrollArea),[i,s]=f.useState(!1);return f.useEffect(()=>{const l=o.scrollArea;let u=0;if(l){const d=()=>{window.clearTimeout(u),s(!0)},h=()=>{u=window.setTimeout(()=>s(!1),o.scrollHideDelay)};return l.addEventListener("pointerenter",d),l.addEventListener("pointerleave",h),()=>{window.clearTimeout(u),l.removeEventListener("pointerenter",d),l.removeEventListener("pointerleave",h)}}},[o.scrollArea,o.scrollHideDelay]),f.createElement(bn,{present:n||i},f.createElement(C5,Y({"data-state":i?"visible":"hidden"},r,{ref:t})))}),gG=f.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=qr($i,e.__scopeScrollArea),i=e.orientation==="horizontal",s=rg(()=>u("SCROLL_END"),100),[l,u]=uG("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(l==="idle"){const d=window.setTimeout(()=>u("HIDE"),o.scrollHideDelay);return()=>window.clearTimeout(d)}},[l,o.scrollHideDelay,u]),f.useEffect(()=>{const d=o.viewport,h=i?"scrollLeft":"scrollTop";if(d){let m=d[h];const g=()=>{const y=d[h];m!==y&&(u("SCROLL"),s()),m=y};return d.addEventListener("scroll",g),()=>d.removeEventListener("scroll",g)}},[o.viewport,i,u,s]),f.createElement(bn,{present:n||l!=="hidden"},f.createElement(Bx,Y({"data-state":l==="hidden"?"hidden":"visible"},r,{ref:t,onPointerEnter:ue(e.onPointerEnter,()=>u("POINTER_ENTER")),onPointerLeave:ue(e.onPointerLeave,()=>u("POINTER_LEAVE"))})))}),C5=f.forwardRef((e,t)=>{const n=qr($i,e.__scopeScrollArea),{forceMount:r,...o}=e,[i,s]=f.useState(!1),l=e.orientation==="horizontal",u=rg(()=>{if(n.viewport){const d=n.viewport.offsetWidth{const{orientation:n="vertical",...r}=e,o=qr($i,e.__scopeScrollArea),i=f.useRef(null),s=f.useRef(0),[l,u]=f.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),d=T5(l.viewport,l.content),h={...r,sizes:l,onSizesChange:u,hasThumb:d>0&&d<1,onThumbChange:g=>i.current=g,onThumbPointerUp:()=>s.current=0,onThumbPointerDown:g=>s.current=g};function m(g,y){return EG(g,s.current,l,y)}return n==="horizontal"?f.createElement(vG,Y({},h,{ref:t,onThumbPositionChange:()=>{if(o.viewport&&i.current){const g=o.viewport.scrollLeft,y=g2(g,l,o.dir);i.current.style.transform=`translate3d(${y}px, 0, 0)`}},onWheelScroll:g=>{o.viewport&&(o.viewport.scrollLeft=g)},onDragScroll:g=>{o.viewport&&(o.viewport.scrollLeft=m(g,o.dir))}})):n==="vertical"?f.createElement(yG,Y({},h,{ref:t,onThumbPositionChange:()=>{if(o.viewport&&i.current){const g=o.viewport.scrollTop,y=g2(g,l);i.current.style.transform=`translate3d(0, ${y}px, 0)`}},onWheelScroll:g=>{o.viewport&&(o.viewport.scrollTop=g)},onDragScroll:g=>{o.viewport&&(o.viewport.scrollTop=m(g))}})):null}),vG=f.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,i=qr($i,e.__scopeScrollArea),[s,l]=f.useState(),u=f.useRef(null),d=Be(t,u,i.onScrollbarXChange);return f.useEffect(()=>{u.current&&l(getComputedStyle(u.current))},[u]),f.createElement(k5,Y({"data-orientation":"horizontal"},o,{ref:d,sizes:n,style:{bottom:0,left:i.dir==="rtl"?"var(--radix-scroll-area-corner-width)":0,right:i.dir==="ltr"?"var(--radix-scroll-area-corner-width)":0,"--radix-scroll-area-thumb-width":ng(n)+"px",...e.style},onThumbPointerDown:h=>e.onThumbPointerDown(h.x),onDragScroll:h=>e.onDragScroll(h.x),onWheelScroll:(h,m)=>{if(i.viewport){const g=i.viewport.scrollLeft+h.deltaX;e.onWheelScroll(g),A5(g,m)&&h.preventDefault()}},onResize:()=>{u.current&&i.viewport&&s&&r({content:i.viewport.scrollWidth,viewport:i.viewport.offsetWidth,scrollbar:{size:u.current.clientWidth,paddingStart:zh(s.paddingLeft),paddingEnd:zh(s.paddingRight)}})}}))}),yG=f.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,i=qr($i,e.__scopeScrollArea),[s,l]=f.useState(),u=f.useRef(null),d=Be(t,u,i.onScrollbarYChange);return f.useEffect(()=>{u.current&&l(getComputedStyle(u.current))},[u]),f.createElement(k5,Y({"data-orientation":"vertical"},o,{ref:d,sizes:n,style:{top:0,right:i.dir==="ltr"?0:void 0,left:i.dir==="rtl"?0:void 0,bottom:"var(--radix-scroll-area-corner-height)","--radix-scroll-area-thumb-height":ng(n)+"px",...e.style},onThumbPointerDown:h=>e.onThumbPointerDown(h.y),onDragScroll:h=>e.onDragScroll(h.y),onWheelScroll:(h,m)=>{if(i.viewport){const g=i.viewport.scrollTop+h.deltaY;e.onWheelScroll(g),A5(g,m)&&h.preventDefault()}},onResize:()=>{u.current&&i.viewport&&s&&r({content:i.viewport.scrollHeight,viewport:i.viewport.offsetHeight,scrollbar:{size:u.current.clientHeight,paddingStart:zh(s.paddingTop),paddingEnd:zh(s.paddingBottom)}})}}))}),[wG,$5]=S5($i),k5=f.forwardRef((e,t)=>{const{__scopeScrollArea:n,sizes:r,hasThumb:o,onThumbChange:i,onThumbPointerUp:s,onThumbPointerDown:l,onThumbPositionChange:u,onDragScroll:d,onWheelScroll:h,onResize:m,...g}=e,y=qr($i,n),[x,_]=f.useState(null),C=Be(t,F=>_(F)),S=f.useRef(null),b=f.useRef(""),E=y.viewport,k=r.content-r.viewport,P=Ft(h),M=Ft(u),A=rg(m,10);function O(F){if(S.current){const V=F.clientX-S.current.left,J=F.clientY-S.current.top;d({x:V,y:J})}}return f.useEffect(()=>{const F=V=>{const J=V.target;(x==null?void 0:x.contains(J))&&P(V,k)};return document.addEventListener("wheel",F,{passive:!1}),()=>document.removeEventListener("wheel",F,{passive:!1})},[E,x,k,P]),f.useEffect(M,[r,M]),sc(x,A),sc(y.content,A),f.createElement(wG,{scope:n,scrollbar:x,hasThumb:o,onThumbChange:Ft(i),onThumbPointerUp:Ft(s),onThumbPositionChange:M,onThumbPointerDown:Ft(l)},f.createElement(Pe.div,Y({},g,{ref:C,style:{position:"absolute",...g.style},onPointerDown:ue(e.onPointerDown,F=>{F.button===0&&(F.target.setPointerCapture(F.pointerId),S.current=x.getBoundingClientRect(),b.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",y.viewport&&(y.viewport.style.scrollBehavior="auto"),O(F))}),onPointerMove:ue(e.onPointerMove,O),onPointerUp:ue(e.onPointerUp,F=>{const V=F.target;V.hasPointerCapture(F.pointerId)&&V.releasePointerCapture(F.pointerId),document.body.style.webkitUserSelect=b.current,y.viewport&&(y.viewport.style.scrollBehavior=""),S.current=null})})))}),_1="ScrollAreaThumb",xG=f.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=$5(_1,e.__scopeScrollArea);return f.createElement(bn,{present:n||o.hasThumb},f.createElement(bG,Y({ref:t},r)))}),bG=f.forwardRef((e,t)=>{const{__scopeScrollArea:n,style:r,...o}=e,i=qr(_1,n),s=$5(_1,n),{onThumbPositionChange:l}=s,u=Be(t,m=>s.onThumbChange(m)),d=f.useRef(),h=rg(()=>{d.current&&(d.current(),d.current=void 0)},100);return f.useEffect(()=>{const m=i.viewport;if(m){const g=()=>{if(h(),!d.current){const y=CG(m,l);d.current=y,l()}};return l(),m.addEventListener("scroll",g),()=>m.removeEventListener("scroll",g)}},[i.viewport,h,l]),f.createElement(Pe.div,Y({"data-state":s.hasThumb?"visible":"hidden"},o,{ref:u,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...r},onPointerDownCapture:ue(e.onPointerDownCapture,m=>{const y=m.target.getBoundingClientRect(),x=m.clientX-y.left,_=m.clientY-y.top;s.onThumbPointerDown({x,y:_})}),onPointerUp:ue(e.onPointerUp,s.onThumbPointerUp)}))}),R5="ScrollAreaCorner",_G=f.forwardRef((e,t)=>{const n=qr(R5,e.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?f.createElement(SG,Y({},e,{ref:t})):null}),SG=f.forwardRef((e,t)=>{const{__scopeScrollArea:n,...r}=e,o=qr(R5,n),[i,s]=f.useState(0),[l,u]=f.useState(0),d=!!(i&&l);return sc(o.scrollbarX,()=>{var h;const m=((h=o.scrollbarX)===null||h===void 0?void 0:h.offsetHeight)||0;o.onCornerHeightChange(m),u(m)}),sc(o.scrollbarY,()=>{var h;const m=((h=o.scrollbarY)===null||h===void 0?void 0:h.offsetWidth)||0;o.onCornerWidthChange(m),s(m)}),d?f.createElement(Pe.div,Y({},r,{ref:t,style:{width:i,height:l,position:"absolute",right:o.dir==="ltr"?0:void 0,left:o.dir==="rtl"?0:void 0,bottom:0,...e.style}})):null});function zh(e){return e?parseInt(e,10):0}function T5(e,t){const n=e/t;return isNaN(n)?0:n}function ng(e){const t=T5(e.viewport,e.content),n=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,r=(e.scrollbar.size-n)*t;return Math.max(r,18)}function EG(e,t,n,r="ltr"){const o=ng(n),i=o/2,s=t||i,l=o-s,u=n.scrollbar.paddingStart+s,d=n.scrollbar.size-n.scrollbar.paddingEnd-l,h=n.content-n.viewport,m=r==="ltr"?[0,h]:[h*-1,0];return P5([u,d],m)(e)}function g2(e,t,n="ltr"){const r=ng(t),o=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,i=t.scrollbar.size-o,s=t.content-t.viewport,l=i-r,u=n==="ltr"?[0,s]:[s*-1,0],d=id(e,u);return P5([0,s],[0,l])(d)}function P5(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 A5(e,t){return e>0&&e{})=>{let n={left:e.scrollLeft,top:e.scrollTop},r=0;return function o(){const i={left:e.scrollLeft,top:e.scrollTop},s=n.left!==i.left,l=n.top!==i.top;(s||l)&&t(),n=i,r=window.requestAnimationFrame(o)}(),()=>window.cancelAnimationFrame(r)};function rg(e,t){const n=Ft(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 sc(e,t){const n=Ft(t);Pn(()=>{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 O5=fG,$G=hG,kG=_G,og=f.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(O5,{ref:r,className:Ce("relative overflow-hidden",e),scrollHideDelay:400,...n,children:[v.jsx($G,{className:"h-full w-full rounded-[inherit]",children:t}),v.jsx(M5,{}),v.jsx(kG,{})]}));og.displayName=O5.displayName;const M5=f.forwardRef(({className:e,orientation:t="vertical",...n},r)=>v.jsx(E5,{ref:r,orientation:t,className:Ce("flex touch-none select-none transition-colors",t==="vertical"&&"h-full w-2.5 border-l border-l-transparent p-[1px]",t==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",e),...n,children:v.jsx(xG,{className:"relative flex-1 rounded-full bg-border"})}));M5.displayName=E5.displayName;const N5="Name",D5="Created time",I5="Modified time",v2="input",RG="output",y2={[xs.NAME]:N5,[xs.CTIME]:D5,[xs.MTIME]:I5};function TG(e){const{onPhotoClick:t,photoWidth:n}=e,[r,o]=AP(!1),[i,s]=bt(V=>[V.fileManagerState,V.updateFileManagerState]),{toast:l}=Td(),[u,d]=f.useState(0),[h,m]=f.useState(0),g=f.useRef(null),y=aV(i.searchText,300),[x,_]=f.useState(v2),[C,S]=f.useState([]),[b,E]=f.useState([]),[k,P]=f.useState(0);Zn("f",()=>{o()}),Zn("left",()=>{let V=k;k>0&&(V=k-1),P(V),t(x,b[V].name)},[k,b]),Zn("right",()=>{let V=k;k{r||m(u)},[r,u]);const M=f.useCallback(V=>{V!==null&&r&&setTimeout(()=>{V.scrollTo({top:h,left:0})},100)},[r,h]);f.useEffect(()=>{(async()=>{try{const J=await Vj(x);S(J)}catch(J){l({variant:"destructive",title:"Uh oh! Something went wrong.",description:J.message?J.message:J.toString()})}})()},[x]),f.useEffect(()=>{if(!r)return;(async()=>{try{let J=C;y&&(J=new _c(J,{keys:["name"]}).search(y).map(te=>J[te.refIndex])),J=wH.orderBy(J,i.sortBy,i.sortOrder);const G=J.map(ae=>{const U=n,te=ae.height*(U/ae.width);return{src:`${Ms}/media_thumbnail_file?tab=${x}&filename=${encodeURIComponent(ae.name)}&width=${Math.ceil(U)}&height=${Math.ceil(te)}`,height:te,width:U,name:ae.name}});E(G)}catch(J){l({variant:"destructive",title:"Uh oh! Something went wrong.",description:J.message?J.message:J.toString()})}})()},[C,y,i,n,r]);const A=V=>{d(V.currentTarget.scrollTop)},O=({index:V})=>{o(),P(V),t(x,b[V].name)},F=()=>v.jsxs("div",{className:"flex justify-start items-center gap-[12px]",children:[v.jsx("div",{children:`Images (${b.length})`}),v.jsxs("div",{className:"flex",children:[v.jsx(vn,{tooltip:"Rows layout",onClick:()=>{s({layout:"rows"})},children:v.jsx(pz,{className:i.layout!=="rows"?"opacity-50":""})}),v.jsx(vn,{tooltip:"Grid layout",onClick:()=>{s({layout:"masonry"})},children:v.jsx(dz,{className:i.layout!=="masonry"?"opacity-50":""})})]})]});return v.jsxs(Zm,{open:r,onOpenChange:o,children:[v.jsx(uP,{asChild:!0,children:v.jsx(vn,{tooltip:"File Manager",children:v.jsx(JU,{})})}),v.jsxs(Fd,{className:"h-4/5 max-w-6xl",children:[v.jsx(jd,{children:F()}),v.jsxs("div",{className:"flex justify-between gap-8 items-center",children:[v.jsxs("div",{className:"flex relative justify-start items-center",children:[v.jsx(az,{className:"absolute left-[8px]"}),v.jsx(Pd,{ref:g,value:i.searchText,className:"w-[250px] pl-[30px]",tabIndex:-1,onInput:V=>{V.preventDefault(),V.stopPropagation();const J=V.target;s({searchText:J.value})},placeholder:"Search by file name"})]}),v.jsx(i5,{defaultValue:x,onValueChange:V=>_(V),children:v.jsxs(Lx,{"aria-label":"Manage your account",children:[v.jsx(sa,{value:v2,children:"Image Directory"}),v.jsx(sa,{value:RG,children:"Output Directory"})]})}),v.jsx("div",{className:"flex gap-2",children:v.jsxs("div",{className:"flex gap-1",children:[v.jsxs(aa,{value:y2[i.sortBy],onValueChange:V=>{switch(V){case N5:s({sortBy:xs.NAME});break;case D5:s({sortBy:xs.CTIME});break;case I5:s({sortBy:xs.MTIME});break}},children:[v.jsx(ls,{className:"w-[140px]",children:v.jsx(la,{})}),v.jsx(cs,{children:Object.values(y2).map(V=>v.jsx(us,{value:V,children:V},V))})]}),i.sortOrder===$u.DESCENDING?v.jsx(vn,{tooltip:"Descending Order",onClick:()=>{s({sortOrder:$u.ASCENDING})},children:v.jsx(oK,{})}):v.jsx(vn,{tooltip:"Ascending Order",onClick:()=>{s({sortOrder:$u.DESCENDING})},children:v.jsx(aK,{})})]})})]}),v.jsx(og,{className:"w-full h-full rounded-md",onScroll:A,ref:M,children:v.jsx(tK,{layout:i.layout,photos:b,spacing:12,padding:0,onClick:O})})]})]})}var Bd=e=>e.type==="checkbox",xl=e=>e instanceof Date,Ln=e=>e==null;const L5=e=>typeof e=="object";var sn=e=>!Ln(e)&&!Array.isArray(e)&&L5(e)&&!xl(e),F5=e=>sn(e)&&e.target?Bd(e.target)?e.target.checked:e.target.value:e,PG=e=>e.substring(0,e.search(/\.\d+(\.|$)/))||e,j5=(e,t)=>e.has(PG(t)),AG=e=>{const t=e.constructor&&e.constructor.prototype;return sn(t)&&t.hasOwnProperty("isPrototypeOf")},Ux=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function so(e){let t;const n=Array.isArray(e);if(e instanceof Date)t=new Date(e);else if(e instanceof Set)t=new Set(e);else if(!(Ux&&(e instanceof Blob||e instanceof FileList))&&(n||sn(e)))if(t=n?[]:{},!n&&!AG(e))t=e;else for(const r in e)e.hasOwnProperty(r)&&(t[r]=so(e[r]));else return e;return t}var Ud=e=>Array.isArray(e)?e.filter(Boolean):[],Ht=e=>e===void 0,ve=(e,t,n)=>{if(!t||!sn(e))return n;const r=Ud(t.split(/[,[\].]+?/)).reduce((o,i)=>Ln(o)?o:o[i],e);return Ht(r)||r===e?Ht(e[t])?n:e[t]:r},No=e=>typeof e=="boolean";const Bh={BLUR:"blur",FOCUS_OUT:"focusout",CHANGE:"change"},mo={onBlur:"onBlur",onChange:"onChange",onSubmit:"onSubmit",onTouched:"onTouched",all:"all"},oi={max:"max",min:"min",maxLength:"maxLength",minLength:"minLength",pattern:"pattern",required:"required",validate:"validate"},z5=Fe.createContext(null),ig=()=>Fe.useContext(z5),OG=e=>{const{children:t,...n}=e;return Fe.createElement(z5.Provider,{value:n},t)};var B5=(e,t,n,r=!0)=>{const o={defaultValues:t._defaultValues};for(const i in e)Object.defineProperty(o,i,{get:()=>{const s=i;return t._proxyFormState[s]!==mo.all&&(t._proxyFormState[s]=!r||mo.all),n&&(n[s]=!0),e[s]}});return o},Fr=e=>sn(e)&&!Object.keys(e).length,U5=(e,t,n,r)=>{n(e);const{name:o,...i}=e;return Fr(i)||Object.keys(i).length>=Object.keys(t).length||Object.keys(i).find(s=>t[s]===(!r||mo.all))},Yp=e=>Array.isArray(e)?e:[e],V5=(e,t,n)=>!e||!t||e===t||Yp(e).some(r=>r&&(n?r===t:r.startsWith(t)||t.startsWith(r)));function Vx(e){const t=Fe.useRef(e);t.current=e,Fe.useEffect(()=>{const n=!e.disabled&&t.current.subject&&t.current.subject.subscribe({next:t.current.next});return()=>{n&&n.unsubscribe()}},[e.disabled])}function MG(e){const t=ig(),{control:n=t.control,disabled:r,name:o,exact:i}=e||{},[s,l]=Fe.useState(n._formState),u=Fe.useRef(!0),d=Fe.useRef({isDirty:!1,isLoading:!1,dirtyFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1}),h=Fe.useRef(o);return h.current=o,Vx({disabled:r,next:m=>u.current&&V5(h.current,m.name,i)&&U5(m,d.current,n._updateFormState)&&l({...n._formState,...m}),subject:n._subjects.state}),Fe.useEffect(()=>(u.current=!0,d.current.isValid&&n._updateValid(!0),()=>{u.current=!1}),[n]),B5(s,n,d.current,!1)}var Fo=e=>typeof e=="string",W5=(e,t,n,r,o)=>Fo(e)?(r&&t.watch.add(e),ve(n,e,o)):Array.isArray(e)?e.map(i=>(r&&t.watch.add(i),ve(n,i))):(r&&(t.watchAll=!0),n);function NG(e){const t=ig(),{control:n=t.control,name:r,defaultValue:o,disabled:i,exact:s}=e||{},l=Fe.useRef(r);l.current=r,Vx({disabled:i,subject:n._subjects.values,next:h=>{V5(l.current,h.name,s)&&d(so(W5(l.current,n._names,h.values||n._formValues,!1,o)))}});const[u,d]=Fe.useState(n._getWatch(r,o));return Fe.useEffect(()=>n._removeUnmounted()),u}var Wx=e=>/^\w*$/.test(e),H5=e=>Ud(e.replace(/["|']|\]/g,"").split(/\.|\[/));function wt(e,t,n){let r=-1;const o=Wx(t)?[t]:H5(t),i=o.length,s=i-1;for(;++r{const h=o._options.shouldUnregister||i,m=(g,y)=>{const x=ve(o._fields,g);x&&(x._f.mount=y)};if(m(n,!0),h){const g=so(ve(o._options.defaultValues,n));wt(o._defaultValues,n,g),Ht(ve(o._formValues,n))&&wt(o._formValues,n,g)}return()=>{(s?h&&!o._state.action:h)?o.unregister(n):m(n,!1)}},[n,o,s,i]),Fe.useEffect(()=>{ve(o._fields,n)&&o._updateDisabledField({disabled:r,fields:o._fields,name:n,value:ve(o._fields,n)._f.value})},[r,n,o]),{field:{name:n,value:l,...No(r)||No(u.disabled)?{disabled:u.disabled||r}:{},onChange:Fe.useCallback(h=>d.current.onChange({target:{value:F5(h),name:n},type:Bh.CHANGE}),[n]),onBlur:Fe.useCallback(()=>d.current.onBlur({target:{value:ve(o._formValues,n),name:n},type:Bh.BLUR}),[n,o]),ref:h=>{const m=ve(o._fields,n);m&&h&&(m._f.ref={focus:()=>h.focus(),select:()=>h.select(),setCustomValidity:g=>h.setCustomValidity(g),reportValidity:()=>h.reportValidity()})}},formState:u,fieldState:Object.defineProperties({},{invalid:{enumerable:!0,get:()=>!!ve(u.errors,n)},isDirty:{enumerable:!0,get:()=>!!ve(u.dirtyFields,n)},isTouched:{enumerable:!0,get:()=>!!ve(u.touchedFields,n)},error:{enumerable:!0,get:()=>ve(u.errors,n)}})}}const IG=e=>e.render(DG(e));var K5=(e,t,n,r,o)=>t?{...n[e],types:{...n[e]&&n[e].types?n[e].types:{},[r]:o||!0}}:{},w2=e=>({isOnSubmit:!e||e===mo.onSubmit,isOnBlur:e===mo.onBlur,isOnChange:e===mo.onChange,isOnAll:e===mo.all,isOnTouch:e===mo.onTouched}),x2=(e,t,n)=>!n&&(t.watchAll||t.watch.has(e)||[...t.watch].some(r=>e.startsWith(r)&&/^\.\w+/.test(e.slice(r.length))));const Gp=(e,t,n,r)=>{for(const o of n||Object.keys(e)){const i=ve(e,o);if(i){const{_f:s,...l}=i;if(s){if(s.refs&&s.refs[0]&&t(s.refs[0],o)&&!r)break;if(s.ref&&t(s.ref,s.name)&&!r)break}else sn(l)&&Gp(l,t)}}};var LG=(e,t,n)=>{const r=Ud(ve(e,n));return wt(r,"root",t[n]),wt(e,n,r),e},Hx=e=>e.type==="file",ds=e=>typeof e=="function",Uh=e=>{if(!Ux)return!1;const t=e?e.ownerDocument:0;return e instanceof(t&&t.defaultView?t.defaultView.HTMLElement:HTMLElement)},Xp=e=>Fo(e),Kx=e=>e.type==="radio",Vh=e=>e instanceof RegExp;const b2={value:!1,isValid:!1},_2={value:!0,isValid:!0};var Y5=e=>{if(Array.isArray(e)){if(e.length>1){const t=e.filter(n=>n&&n.checked&&!n.disabled).map(n=>n.value);return{value:t,isValid:!!t.length}}return e[0].checked&&!e[0].disabled?e[0].attributes&&!Ht(e[0].attributes.value)?Ht(e[0].value)||e[0].value===""?_2:{value:e[0].value,isValid:!0}:_2:b2}return b2};const S2={isValid:!1,value:null};var G5=e=>Array.isArray(e)?e.reduce((t,n)=>n&&n.checked&&!n.disabled?{isValid:!0,value:n.value}:t,S2):S2;function E2(e,t,n="validate"){if(Xp(e)||Array.isArray(e)&&e.every(Xp)||No(e)&&!e)return{type:n,message:Xp(e)?e:"",ref:t}}var el=e=>sn(e)&&!Vh(e)?e:{value:e,message:""},C2=async(e,t,n,r,o)=>{const{ref:i,refs:s,required:l,maxLength:u,minLength:d,min:h,max:m,pattern:g,validate:y,name:x,valueAsNumber:_,mount:C,disabled:S}=e._f,b=ve(t,x);if(!C||S)return{};const E=s?s[0]:i,k=G=>{r&&E.reportValidity&&(E.setCustomValidity(No(G)?"":G||""),E.reportValidity())},P={},M=Kx(i),A=Bd(i),O=M||A,F=(_||Hx(i))&&Ht(i.value)&&Ht(b)||Uh(i)&&i.value===""||b===""||Array.isArray(b)&&!b.length,V=K5.bind(null,x,n,P),J=(G,ae,U,te=oi.maxLength,L=oi.minLength)=>{const ie=G?ae:U;P[x]={type:G?te:L,message:ie,ref:i,...V(G?te:L,ie)}};if(o?!Array.isArray(b)||!b.length:l&&(!O&&(F||Ln(b))||No(b)&&!b||A&&!Y5(s).isValid||M&&!G5(s).isValid)){const{value:G,message:ae}=Xp(l)?{value:!!l,message:l}:el(l);if(G&&(P[x]={type:oi.required,message:ae,ref:E,...V(oi.required,ae)},!n))return k(ae),P}if(!F&&(!Ln(h)||!Ln(m))){let G,ae;const U=el(m),te=el(h);if(!Ln(b)&&!isNaN(b)){const L=i.valueAsNumber||b&&+b;Ln(U.value)||(G=L>U.value),Ln(te.value)||(ae=Lnew Date(new Date().toDateString()+" "+W),K=i.type=="time",Q=i.type=="week";Fo(U.value)&&b&&(G=K?ie(b)>ie(U.value):Q?b>U.value:L>new Date(U.value)),Fo(te.value)&&b&&(ae=K?ie(b)+G.value,te=!Ln(ae.value)&&b.length<+ae.value;if((U||te)&&(J(U,G.message,ae.message),!n))return k(P[x].message),P}if(g&&!F&&Fo(b)){const{value:G,message:ae}=el(g);if(Vh(G)&&!b.match(G)&&(P[x]={type:oi.pattern,message:ae,ref:i,...V(oi.pattern,ae)},!n))return k(ae),P}if(y){if(ds(y)){const G=await y(b,t),ae=E2(G,E);if(ae&&(P[x]={...ae,...V(oi.validate,ae.message)},!n))return k(ae.message),P}else if(sn(y)){let G={};for(const ae in y){if(!Fr(G)&&!n)break;const U=E2(await y[ae](b,t),E,ae);U&&(G={...U,...V(ae,U.message)},k(U.message),n&&(P[x]=G))}if(!Fr(G)&&(P[x]={ref:E,...G},!n))return P}}return k(!0),P};function FG(e,t){const n=t.slice(0,-1).length;let r=0;for(;r{for(const i of e)i.next&&i.next(o)},subscribe:o=>(e.push(o),{unsubscribe:()=>{e=e.filter(i=>i!==o)}}),unsubscribe:()=>{e=[]}}}var Wh=e=>Ln(e)||!L5(e);function ca(e,t){if(Wh(e)||Wh(t))return e===t;if(xl(e)&&xl(t))return e.getTime()===t.getTime();const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(const o of n){const i=e[o];if(!r.includes(o))return!1;if(o!=="ref"){const s=t[o];if(xl(i)&&xl(s)||sn(i)&&sn(s)||Array.isArray(i)&&Array.isArray(s)?!ca(i,s):i!==s)return!1}}return!0}var X5=e=>e.type==="select-multiple",zG=e=>Kx(e)||Bd(e),P0=e=>Uh(e)&&e.isConnected,Z5=e=>{for(const t in e)if(ds(e[t]))return!0;return!1};function Hh(e,t={}){const n=Array.isArray(e);if(sn(e)||n)for(const r in e)Array.isArray(e[r])||sn(e[r])&&!Z5(e[r])?(t[r]=Array.isArray(e[r])?[]:{},Hh(e[r],t[r])):Ln(e[r])||(t[r]=!0);return t}function q5(e,t,n){const r=Array.isArray(e);if(sn(e)||r)for(const o in e)Array.isArray(e[o])||sn(e[o])&&!Z5(e[o])?Ht(t)||Wh(n[o])?n[o]=Array.isArray(e[o])?Hh(e[o],[]):{...Hh(e[o])}:q5(e[o],Ln(t)?{}:t[o],n[o]):n[o]=!ca(e[o],t[o]);return n}var A0=(e,t)=>q5(e,t,Hh(t)),Q5=(e,{valueAsNumber:t,valueAsDate:n,setValueAs:r})=>Ht(e)?e:t?e===""?NaN:e&&+e:n&&Fo(e)?new Date(e):r?r(e):e;function O0(e){const t=e.ref;if(!(e.refs?e.refs.every(n=>n.disabled):t.disabled))return Hx(t)?t.files:Kx(t)?G5(e.refs).value:X5(t)?[...t.selectedOptions].map(({value:n})=>n):Bd(t)?Y5(e.refs).value:Q5(Ht(t.value)?e.ref.value:t.value,e)}var BG=(e,t,n,r)=>{const o={};for(const i of e){const s=ve(t,i);s&&wt(o,i,s._f)}return{criteriaMode:n,names:[...e],fields:o,shouldUseNativeValidation:r}},iu=e=>Ht(e)?e:Vh(e)?e.source:sn(e)?Vh(e.value)?e.value.source:e.value:e,UG=e=>e.mount&&(e.required||e.min||e.max||e.maxLength||e.minLength||e.pattern||e.validate);function $2(e,t,n){const r=ve(e,n);if(r||Wx(n))return{error:r,name:n};const o=n.split(".");for(;o.length;){const i=o.join("."),s=ve(t,i),l=ve(e,i);if(s&&!Array.isArray(s)&&n!==i)return{name:n};if(l&&l.type)return{name:i,error:l};o.pop()}return{name:n}}var VG=(e,t,n,r,o)=>o.isOnAll?!1:!n&&o.isOnTouch?!(t||e):(n?r.isOnBlur:o.isOnBlur)?!e:(n?r.isOnChange:o.isOnChange)?e:!0,WG=(e,t)=>!Ud(ve(e,t)).length&&hn(e,t);const HG={mode:mo.onSubmit,reValidateMode:mo.onChange,shouldFocusError:!0};function KG(e={},t){let n={...HG,...e},r={submitCount:0,isDirty:!1,isLoading:ds(n.defaultValues),isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},errors:{},disabled:!1},o={},i=sn(n.defaultValues)||sn(n.values)?so(n.defaultValues||n.values)||{}:{},s=n.shouldUnregister?{}:so(i),l={action:!1,mount:!1,watch:!1},u={mount:new Set,unMount:new Set,array:new Set,watch:new Set},d,h=0;const m={isDirty:!1,dirtyFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1},g={values:T0(),array:T0(),state:T0()},y=e.resetOptions&&e.resetOptions.keepDirtyValues,x=w2(n.mode),_=w2(n.reValidateMode),C=n.criteriaMode===mo.all,S=I=>X=>{clearTimeout(h),h=setTimeout(I,X)},b=async I=>{if(m.isValid||I){const X=n.resolver?Fr((await F()).errors):await J(o,!0);X!==r.isValid&&g.state.next({isValid:X})}},E=I=>m.isValidating&&g.state.next({isValidating:I}),k=(I,X=[],Z,we,he=!0,de=!0)=>{if(we&&Z){if(l.action=!0,de&&Array.isArray(ve(o,I))){const ke=Z(ve(o,I),we.argA,we.argB);he&&wt(o,I,ke)}if(de&&Array.isArray(ve(r.errors,I))){const ke=Z(ve(r.errors,I),we.argA,we.argB);he&&wt(r.errors,I,ke),WG(r.errors,I)}if(m.touchedFields&&de&&Array.isArray(ve(r.touchedFields,I))){const ke=Z(ve(r.touchedFields,I),we.argA,we.argB);he&&wt(r.touchedFields,I,ke)}m.dirtyFields&&(r.dirtyFields=A0(i,s)),g.state.next({name:I,isDirty:ae(I,X),dirtyFields:r.dirtyFields,errors:r.errors,isValid:r.isValid})}else wt(s,I,X)},P=(I,X)=>{wt(r.errors,I,X),g.state.next({errors:r.errors})},M=(I,X,Z,we)=>{const he=ve(o,I);if(he){const de=ve(s,I,Ht(Z)?ve(i,I):Z);Ht(de)||we&&we.defaultChecked||X?wt(s,I,X?de:O0(he._f)):L(I,de),l.mount&&b()}},A=(I,X,Z,we,he)=>{let de=!1,ke=!1;const ft={name:I};if(!Z||we){m.isDirty&&(ke=r.isDirty,r.isDirty=ft.isDirty=ae(),de=ke!==ft.isDirty);const pt=ca(ve(i,I),X);ke=ve(r.dirtyFields,I),pt?hn(r.dirtyFields,I):wt(r.dirtyFields,I,!0),ft.dirtyFields=r.dirtyFields,de=de||m.dirtyFields&&ke!==!pt}if(Z){const pt=ve(r.touchedFields,I);pt||(wt(r.touchedFields,I,Z),ft.touchedFields=r.touchedFields,de=de||m.touchedFields&&pt!==Z)}return de&&he&&g.state.next(ft),de?ft:{}},O=(I,X,Z,we)=>{const he=ve(r.errors,I),de=m.isValid&&No(X)&&r.isValid!==X;if(e.delayError&&Z?(d=S(()=>P(I,Z)),d(e.delayError)):(clearTimeout(h),d=null,Z?wt(r.errors,I,Z):hn(r.errors,I)),(Z?!ca(he,Z):he)||!Fr(we)||de){const ke={...we,...de&&No(X)?{isValid:X}:{},errors:r.errors,name:I};r={...r,...ke},g.state.next(ke)}E(!1)},F=async I=>n.resolver(s,n.context,BG(I||u.mount,o,n.criteriaMode,n.shouldUseNativeValidation)),V=async I=>{const{errors:X}=await F(I);if(I)for(const Z of I){const we=ve(X,Z);we?wt(r.errors,Z,we):hn(r.errors,Z)}else r.errors=X;return X},J=async(I,X,Z={valid:!0})=>{for(const we in I){const he=I[we];if(he){const{_f:de,...ke}=he;if(de){const ft=u.array.has(de.name),pt=await C2(he,s,C,n.shouldUseNativeValidation&&!X,ft);if(pt[de.name]&&(Z.valid=!1,X))break;!X&&(ve(pt,de.name)?ft?LG(r.errors,pt,de.name):wt(r.errors,de.name,pt[de.name]):hn(r.errors,de.name))}ke&&await J(ke,X,Z)}}return Z.valid},G=()=>{for(const I of u.unMount){const X=ve(o,I);X&&(X._f.refs?X._f.refs.every(Z=>!P0(Z)):!P0(X._f.ref))&&fe(I)}u.unMount=new Set},ae=(I,X)=>(I&&X&&wt(s,I,X),!ca(ge(),i)),U=(I,X,Z)=>W5(I,u,{...l.mount?s:Ht(X)?i:Fo(I)?{[I]:X}:X},Z,X),te=I=>Ud(ve(l.mount?s:i,I,e.shouldUnregister?ve(i,I,[]):[])),L=(I,X,Z={})=>{const we=ve(o,I);let he=X;if(we){const de=we._f;de&&(!de.disabled&&wt(s,I,Q5(X,de)),he=Uh(de.ref)&&Ln(X)?"":X,X5(de.ref)?[...de.ref.options].forEach(ke=>ke.selected=he.includes(ke.value)):de.refs?Bd(de.ref)?de.refs.length>1?de.refs.forEach(ke=>(!ke.defaultChecked||!ke.disabled)&&(ke.checked=Array.isArray(he)?!!he.find(ft=>ft===ke.value):he===ke.value)):de.refs[0]&&(de.refs[0].checked=!!he):de.refs.forEach(ke=>ke.checked=ke.value===he):Hx(de.ref)?de.ref.value="":(de.ref.value=he,de.ref.type||g.values.next({name:I,values:{...s}})))}(Z.shouldDirty||Z.shouldTouch)&&A(I,he,Z.shouldTouch,Z.shouldDirty,!0),Z.shouldValidate&&le(I)},ie=(I,X,Z)=>{for(const we in X){const he=X[we],de=`${I}.${we}`,ke=ve(o,de);(u.array.has(I)||!Wh(he)||ke&&!ke._f)&&!xl(he)?ie(de,he,Z):L(de,he,Z)}},K=(I,X,Z={})=>{const we=ve(o,I),he=u.array.has(I),de=so(X);wt(s,I,de),he?(g.array.next({name:I,values:{...s}}),(m.isDirty||m.dirtyFields)&&Z.shouldDirty&&g.state.next({name:I,dirtyFields:A0(i,s),isDirty:ae(I,de)})):we&&!we._f&&!Ln(de)?ie(I,de,Z):L(I,de,Z),x2(I,u)&&g.state.next({...r}),g.values.next({name:I,values:{...s}}),!l.mount&&t()},Q=async I=>{const X=I.target;let Z=X.name,we=!0;const he=ve(o,Z),de=()=>X.type?O0(he._f):F5(I),ke=ft=>{we=Number.isNaN(ft)||ft===ve(s,Z,ft)};if(he){let ft,pt;const _n=de(),Cr=I.type===Bh.BLUR||I.type===Bh.FOCUS_OUT,ki=!UG(he._f)&&!n.resolver&&!ve(r.errors,Z)&&!he._f.deps||VG(Cr,ve(r.touchedFields,Z),r.isSubmitted,_,x),_o=x2(Z,u,Cr);wt(s,Z,_n),Cr?(he._f.onBlur&&he._f.onBlur(I),d&&d(0)):he._f.onChange&&he._f.onChange(I);const Vn=A(Z,_n,Cr,!1),Da=!Fr(Vn)||_o;if(!Cr&&g.values.next({name:Z,type:I.type,values:{...s}}),ki)return m.isValid&&b(),Da&&g.state.next({name:Z,..._o?{}:Vn});if(!Cr&&_o&&g.state.next({...r}),E(!0),n.resolver){const{errors:Ri}=await F([Z]);if(ke(_n),we){const zs=$2(r.errors,o,Z),Ti=$2(Ri,o,zs.name||Z);ft=Ti.error,Z=Ti.name,pt=Fr(Ri)}}else ft=(await C2(he,s,C,n.shouldUseNativeValidation))[Z],ke(_n),we&&(ft?pt=!1:m.isValid&&(pt=await J(o,!0)));we&&(he._f.deps&&le(he._f.deps),O(Z,pt,ft,Vn))}},W=(I,X)=>{if(ve(r.errors,X)&&I.focus)return I.focus(),1},le=async(I,X={})=>{let Z,we;const he=Yp(I);if(E(!0),n.resolver){const de=await V(Ht(I)?I:he);Z=Fr(de),we=I?!he.some(ke=>ve(de,ke)):Z}else I?(we=(await Promise.all(he.map(async de=>{const ke=ve(o,de);return await J(ke&&ke._f?{[de]:ke}:ke)}))).every(Boolean),!(!we&&!r.isValid)&&b()):we=Z=await J(o);return g.state.next({...!Fo(I)||m.isValid&&Z!==r.isValid?{}:{name:I},...n.resolver||!I?{isValid:Z}:{},errors:r.errors,isValidating:!1}),X.shouldFocus&&!we&&Gp(o,W,I?he:u.mount),we},ge=I=>{const X={...i,...l.mount?s:{}};return Ht(I)?X:Fo(I)?ve(X,I):I.map(Z=>ve(X,Z))},Ve=(I,X)=>({invalid:!!ve((X||r).errors,I),isDirty:!!ve((X||r).dirtyFields,I),isTouched:!!ve((X||r).touchedFields,I),error:ve((X||r).errors,I)}),Ue=I=>{I&&Yp(I).forEach(X=>hn(r.errors,X)),g.state.next({errors:I?r.errors:{}})},We=(I,X,Z)=>{const we=(ve(o,I,{_f:{}})._f||{}).ref;wt(r.errors,I,{...X,ref:we}),g.state.next({name:I,errors:r.errors,isValid:!1}),Z&&Z.shouldFocus&&we&&we.focus&&we.focus()},Me=(I,X)=>ds(I)?g.values.subscribe({next:Z=>I(U(void 0,X),Z)}):U(I,X,!0),fe=(I,X={})=>{for(const Z of I?Yp(I):u.mount)u.mount.delete(Z),u.array.delete(Z),X.keepValue||(hn(o,Z),hn(s,Z)),!X.keepError&&hn(r.errors,Z),!X.keepDirty&&hn(r.dirtyFields,Z),!X.keepTouched&&hn(r.touchedFields,Z),!n.shouldUnregister&&!X.keepDefaultValue&&hn(i,Z);g.values.next({values:{...s}}),g.state.next({...r,...X.keepDirty?{isDirty:ae()}:{}}),!X.keepIsValid&&b()},xe=({disabled:I,name:X,field:Z,fields:we,value:he})=>{if(No(I)){const de=I?void 0:Ht(he)?O0(Z?Z._f:ve(we,X)._f):he;wt(s,X,de),A(X,de,!1,!1,!0)}},$e=(I,X={})=>{let Z=ve(o,I);const we=No(X.disabled);return wt(o,I,{...Z||{},_f:{...Z&&Z._f?Z._f:{ref:{name:I}},name:I,mount:!0,...X}}),u.mount.add(I),Z?xe({field:Z,disabled:X.disabled,name:I}):M(I,!0,X.value),{...we?{disabled:X.disabled}:{},...n.progressive?{required:!!X.required,min:iu(X.min),max:iu(X.max),minLength:iu(X.minLength),maxLength:iu(X.maxLength),pattern:iu(X.pattern)}:{},name:I,onChange:Q,onBlur:Q,ref:he=>{if(he){$e(I,X),Z=ve(o,I);const de=Ht(he.value)&&he.querySelectorAll&&he.querySelectorAll("input,select,textarea")[0]||he,ke=zG(de),ft=Z._f.refs||[];if(ke?ft.find(pt=>pt===de):de===Z._f.ref)return;wt(o,I,{_f:{...Z._f,...ke?{refs:[...ft.filter(P0),de,...Array.isArray(ve(i,I))?[{}]:[]],ref:{type:de.type,name:I}}:{ref:de}}}),M(I,!1,void 0,de)}else Z=ve(o,I,{}),Z._f&&(Z._f.mount=!1),(n.shouldUnregister||X.shouldUnregister)&&!(j5(u.array,I)&&l.action)&&u.unMount.add(I)}}},Ae=()=>n.shouldFocusError&&Gp(o,W,u.mount),Oe=I=>{No(I)&&(g.state.next({disabled:I}),Gp(o,X=>{X.disabled=I},0,!1))},je=(I,X)=>async Z=>{Z&&(Z.preventDefault&&Z.preventDefault(),Z.persist&&Z.persist());let we=so(s);if(g.state.next({isSubmitting:!0}),n.resolver){const{errors:he,values:de}=await F();r.errors=he,we=de}else await J(o);hn(r.errors,"root"),Fr(r.errors)?(g.state.next({errors:{}}),await I(we,Z)):(X&&await X({...r.errors},Z),Ae(),setTimeout(Ae)),g.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:Fr(r.errors),submitCount:r.submitCount+1,errors:r.errors})},Ot=(I,X={})=>{ve(o,I)&&(Ht(X.defaultValue)?K(I,ve(i,I)):(K(I,X.defaultValue),wt(i,I,X.defaultValue)),X.keepTouched||hn(r.touchedFields,I),X.keepDirty||(hn(r.dirtyFields,I),r.isDirty=X.defaultValue?ae(I,ve(i,I)):ae()),X.keepError||(hn(r.errors,I),m.isValid&&b()),g.state.next({...r}))},ct=(I,X={})=>{const Z=I?so(I):i,we=so(Z),he=I&&!Fr(I)?we:i;if(X.keepDefaultValues||(i=Z),!X.keepValues){if(X.keepDirtyValues||y)for(const de of u.mount)ve(r.dirtyFields,de)?wt(he,de,ve(s,de)):K(de,ve(he,de));else{if(Ux&&Ht(I))for(const de of u.mount){const ke=ve(o,de);if(ke&&ke._f){const ft=Array.isArray(ke._f.refs)?ke._f.refs[0]:ke._f.ref;if(Uh(ft)){const pt=ft.closest("form");if(pt){pt.reset();break}}}}o={}}s=e.shouldUnregister?X.keepDefaultValues?so(i):{}:so(he),g.array.next({values:{...he}}),g.values.next({values:{...he}})}u={mount:new Set,unMount:new Set,array:new Set,watch:new Set,watchAll:!1,focus:""},!l.mount&&t(),l.mount=!m.isValid||!!X.keepIsValid,l.watch=!!e.shouldUnregister,g.state.next({submitCount:X.keepSubmitCount?r.submitCount:0,isDirty:X.keepDirty?r.isDirty:!!(X.keepDefaultValues&&!ca(I,i)),isSubmitted:X.keepIsSubmitted?r.isSubmitted:!1,dirtyFields:X.keepDirtyValues?r.dirtyFields:X.keepDefaultValues&&I?A0(i,I):{},touchedFields:X.keepTouched?r.touchedFields:{},errors:X.keepErrors?r.errors:{},isSubmitSuccessful:X.keepIsSubmitSuccessful?r.isSubmitSuccessful:!1,isSubmitting:!1})},Kt=(I,X)=>ct(ds(I)?I(s):I,X);return{control:{register:$e,unregister:fe,getFieldState:Ve,handleSubmit:je,setError:We,_executeSchema:F,_getWatch:U,_getDirty:ae,_updateValid:b,_removeUnmounted:G,_updateFieldArray:k,_updateDisabledField:xe,_getFieldArray:te,_reset:ct,_resetDefaultValues:()=>ds(n.defaultValues)&&n.defaultValues().then(I=>{Kt(I,n.resetOptions),g.state.next({isLoading:!1})}),_updateFormState:I=>{r={...r,...I}},_disableForm:Oe,_subjects:g,_proxyFormState:m,get _fields(){return o},get _formValues(){return s},get _state(){return l},set _state(I){l=I},get _defaultValues(){return i},get _names(){return u},set _names(I){u=I},get _formState(){return r},set _formState(I){r=I},get _options(){return n},set _options(I){n={...n,...I}}},trigger:le,register:$e,handleSubmit:je,watch:Me,setValue:K,getValues:ge,reset:Kt,resetField:Ot,clearErrors:Ue,unregister:fe,setError:We,setFocus:(I,X={})=>{const Z=ve(o,I),we=Z&&Z._f;if(we){const he=we.refs?we.refs[0]:we.ref;he.focus&&(he.focus(),X.shouldSelect&&he.select())}},getFieldState:Ve}}function YG(e={}){const t=Fe.useRef(),n=Fe.useRef(),[r,o]=Fe.useState({isDirty:!1,isValidating:!1,isLoading:ds(e.defaultValues),isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,submitCount:0,dirtyFields:{},touchedFields:{},errors:{},disabled:!1,defaultValues:ds(e.defaultValues)?void 0:e.defaultValues});t.current||(t.current={...KG(e,()=>o(s=>({...s}))),formState:r});const i=t.current.control;return i._options=e,Vx({subject:i._subjects.state,next:s=>{U5(s,i._proxyFormState,i._updateFormState,!0)&&o({...i._formState})}}),Fe.useEffect(()=>i._disableForm(e.disabled),[i,e.disabled]),Fe.useEffect(()=>{if(i._proxyFormState.isDirty){const s=i._getDirty();s!==r.isDirty&&i._subjects.state.next({isDirty:s})}},[i,r.isDirty]),Fe.useEffect(()=>{e.values&&!ca(e.values,n.current)?(i._reset(e.values,i._options.resetOptions),n.current=e.values):i._resetDefaultValues()},[e.values,i]),Fe.useEffect(()=>{i._state.mount||(i._updateValid(),i._state.mount=!0),i._state.watch&&(i._state.watch=!1,i._subjects.state.next({...i._formState})),i._removeUnmounted()}),t.current.formState=B5(r,i),t.current}var k2=function(e,t,n){if(e&&"reportValidity"in e){var r=ve(n,t);e.setCustomValidity(r&&r.message||""),e.reportValidity()}},J5=function(e,t){var n=function(o){var i=t.fields[o];i&&i.ref&&"reportValidity"in i.ref?k2(i.ref,o,e):i.refs&&i.refs.forEach(function(s){return k2(s,o,e)})};for(var r in t.fields)n(r)},GG=function(e,t){t.shouldUseNativeValidation&&J5(e,t);var n={};for(var r in e){var o=ve(t.fields,r),i=Object.assign(e[r]||{},{ref:o&&o.ref});if(ZG(t.names||Object.keys(e),r)){var s=Object.assign({},XG(ve(n,r)));wt(s,"root",i),wt(n,r,s)}else wt(n,r,i)}return n},XG=function(e){return Array.isArray(e)?e.filter(Boolean):[]},ZG=function(e,t){return e.some(function(n){return n.startsWith(t+".")})},qG=function(e,t){for(var n={};e.length;){var r=e[0],o=r.code,i=r.message,s=r.path.join(".");if(!n[s])if("unionErrors"in r){var l=r.unionErrors[0].errors[0];n[s]={message:l.message,type:l.code}}else n[s]={message:i,type:o};if("unionErrors"in r&&r.unionErrors.forEach(function(h){return h.errors.forEach(function(m){return e.push(m)})}),t){var u=n[s].types,d=u&&u[r.code];n[s]=K5(s,t,n,o,d?[].concat(d,r.message):r.message)}e.shift()}return n},QG=function(e,t,n){return n===void 0&&(n={}),function(r,o,i){try{return Promise.resolve(function(s,l){try{var u=Promise.resolve(e[n.mode==="sync"?"parse":"parseAsync"](r,t)).then(function(d){return i.shouldUseNativeValidation&&J5({},i),{errors:{},values:n.raw?r:d}})}catch(d){return l(d)}return u&&u.then?u.then(void 0,l):u}(0,function(s){if(function(l){return l.errors!=null}(s))return{values:{},errors:GG(qG(s.errors,!i.shouldUseNativeValidation&&i.criteriaMode==="all"),i)};throw s}))}catch(s){return Promise.reject(s)}}},mt;(function(e){e.assertEqual=o=>o;function t(o){}e.assertIs=t;function n(o){throw new Error}e.assertNever=n,e.arrayToEnum=o=>{const i={};for(const s of o)i[s]=s;return i},e.getValidEnumValues=o=>{const i=e.objectKeys(o).filter(l=>typeof o[o[l]]!="number"),s={};for(const l of i)s[l]=o[l];return e.objectValues(s)},e.objectValues=o=>e.objectKeys(o).map(function(i){return o[i]}),e.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{const i=[];for(const s in o)Object.prototype.hasOwnProperty.call(o,s)&&i.push(s);return i},e.find=(o,i)=>{for(const s of o)if(i(s))return s},e.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&isFinite(o)&&Math.floor(o)===o;function r(o,i=" | "){return o.map(s=>typeof s=="string"?`'${s}'`:s).join(i)}e.joinValues=r,e.jsonStringifyReplacer=(o,i)=>typeof i=="bigint"?i.toString():i})(mt||(mt={}));var R2;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(R2||(R2={}));const be=mt.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ta=e=>{switch(typeof e){case"undefined":return be.undefined;case"string":return be.string;case"number":return isNaN(e)?be.nan:be.number;case"boolean":return be.boolean;case"function":return be.function;case"bigint":return be.bigint;case"symbol":return be.symbol;case"object":return Array.isArray(e)?be.array:e===null?be.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?be.promise:typeof Map<"u"&&e instanceof Map?be.map:typeof Set<"u"&&e instanceof Set?be.set:typeof Date<"u"&&e instanceof Date?be.date:be.object;default:return be.unknown}},pe=mt.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"]);class Bo 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(i){return i.message},r={_errors:[]},o=i=>{for(const s of i.issues)if(s.code==="invalid_union")s.unionErrors.map(o);else if(s.code==="invalid_return_type")o(s.returnTypeError);else if(s.code==="invalid_arguments")o(s.argumentsError);else if(s.path.length===0)r._errors.push(n(s));else{let l=r,u=0;for(;un.message){const n={},r=[];for(const o of this.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(t(o))):r.push(t(o));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}}Bo.create=e=>new Bo(e);const Kh=(e,t)=>{let n;switch(e.code){case pe.invalid_type:e.received===be.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case pe.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,mt.jsonStringifyReplacer)}`;break;case pe.unrecognized_keys:n=`Unrecognized key(s) in object: ${mt.joinValues(e.keys,", ")}`;break;case pe.invalid_union:n="Invalid input";break;case pe.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${mt.joinValues(e.options)}`;break;case pe.invalid_enum_value:n=`Invalid enum value. Expected ${mt.joinValues(e.options)}, received '${e.received}'`;break;case pe.invalid_arguments:n="Invalid function arguments";break;case pe.invalid_return_type:n="Invalid function return type";break;case pe.invalid_date:n="Invalid date";break;case pe.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}"`:mt.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case pe.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 pe.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 pe.custom:n="Invalid input";break;case pe.invalid_intersection_types:n="Intersection results could not be merged";break;case pe.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case pe.not_finite:n="Number must be finite";break;default:n=t.defaultError,mt.assertNever(e)}return{message:n}};let JG=Kh;function S1(){return JG}const E1=e=>{const{data:t,path:n,errorMaps:r,issueData:o}=e,i=[...n,...o.path||[]],s={...o,path:i};let l="";const u=r.filter(d=>!!d).slice().reverse();for(const d of u)l=d(s,{data:t,defaultError:l}).message;return{...o,path:i,message:o.message||l}};function Ee(e,t){const n=E1({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,S1(),Kh].filter(r=>!!r)});e.common.issues.push(n)}class zn{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 o of n){if(o.status==="aborted")return Ze;o.status==="dirty"&&t.dirty(),r.push(o.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){const r=[];for(const o of n)r.push({key:await o.key,value:await o.value});return zn.mergeObjectSync(t,r)}static mergeObjectSync(t,n){const r={};for(const o of n){const{key:i,value:s}=o;if(i.status==="aborted"||s.status==="aborted")return Ze;i.status==="dirty"&&t.dirty(),s.status==="dirty"&&t.dirty(),i.value!=="__proto__"&&(typeof s.value<"u"||o.alwaysSet)&&(r[i.value]=s.value)}return{status:t.value,value:r}}}const Ze=Object.freeze({status:"aborted"}),eX=e=>({status:"dirty",value:e}),rr=e=>({status:"valid",value:e}),T2=e=>e.status==="aborted",P2=e=>e.status==="dirty",Yh=e=>e.status==="valid",C1=e=>typeof Promise<"u"&&e instanceof Promise;var Ne;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t==null?void 0:t.message})(Ne||(Ne={}));class Ko{constructor(t,n,r,o){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=o}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 A2=(e,t)=>{if(Yh(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 Bo(e.common.issues);return this._error=n,this._error}}};function Xe(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:r,description:o}=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:o}:{errorMap:(s,l)=>s.code!=="invalid_type"?{message:l.defaultError}:typeof l.data>"u"?{message:r??l.defaultError}:{message:n??l.defaultError},description:o}}class rt{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.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this)}get description(){return this._def.description}_getType(t){return ta(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:ta(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new zn,ctx:{common:t.parent.common,data:t.data,parsedType:ta(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const n=this._parse(t);if(C1(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 o={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:ta(t)},i=this._parseSync({data:t,path:o.path,parent:o});return A2(o,i)}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:ta(t)},o=this._parse({data:t,path:r.path,parent:r}),i=await(C1(o)?o:Promise.resolve(o));return A2(r,i)}refine(t,n){const r=o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n;return this._refinement((o,i)=>{const s=t(o),l=()=>i.addIssue({code:pe.custom,...r(o)});return typeof Promise<"u"&&s instanceof Promise?s.then(u=>u?!0:(l(),!1)):s?!0:(l(),!1)})}refinement(t,n){return this._refinement((r,o)=>t(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(t){return new Si({schema:this,typeName:ze.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}optional(){return bs.create(this,this._def)}nullable(){return uc.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Uo.create(this,this._def)}promise(){return ad.create(this,this._def)}or(t){return Zh.create([this,t],this._def)}and(t){return qh.create(this,t,this._def)}transform(t){return new Si({...Xe(this._def),schema:this,typeName:ze.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const n=typeof t=="function"?t:()=>t;return new nm({...Xe(this._def),innerType:this,defaultValue:n,typeName:ze.ZodDefault})}brand(){return new fX({typeName:ze.ZodBranded,type:this,...Xe(this._def)})}catch(t){const n=typeof t=="function"?t:()=>t;return new O1({...Xe(this._def),innerType:this,catchValue:n,typeName:ze.ZodCatch})}describe(t){const n=this.constructor;return new n({...this._def,description:t})}pipe(t){return sg.create(this,t)}readonly(){return N1.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const tX=/^c[^\s-]{8,}$/i,nX=/^[a-z][a-z0-9]*$/,rX=/^[0-9A-HJKMNP-TV-Z]{26}$/,oX=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,iX=/^(?!\.)(?!.*\.\.)([A-Z0-9_+-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,sX="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let M0;const aX=/^(((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}))$/,lX=/^(([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})))$/,cX=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 uX(e,t){return!!((t==="v4"||!t)&&aX.test(e)||(t==="v6"||!t)&&lX.test(e))}class di extends rt{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==be.string){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_type,expected:be.string,received:i.parsedType}),Ze}const r=new zn;let o;for(const i of this._def.checks)if(i.kind==="min")t.data.lengthi.value&&(o=this._getOrReturnCtx(t,o),Ee(o,{code:pe.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){const s=t.data.length>i.value,l=t.data.lengtht.test(o),{validation:n,code:pe.invalid_string,...Ne.errToObj(r)})}_addCheck(t){return new di({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...Ne.errToObj(t)})}url(t){return this._addCheck({kind:"url",...Ne.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...Ne.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...Ne.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...Ne.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...Ne.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...Ne.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...Ne.errToObj(t)})}datetime(t){var n;return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof(t==null?void 0:t.precision)>"u"?null:t==null?void 0:t.precision,offset:(n=t==null?void 0:t.offset)!==null&&n!==void 0?n:!1,...Ne.errToObj(t==null?void 0:t.message)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...Ne.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n==null?void 0:n.position,...Ne.errToObj(n==null?void 0:n.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...Ne.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...Ne.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...Ne.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...Ne.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...Ne.errToObj(n)})}nonempty(t){return this.min(1,Ne.errToObj(t))}trim(){return new di({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new di({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new di({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}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 di({checks:[],typeName:ze.ZodString,coerce:(t=e==null?void 0:e.coerce)!==null&&t!==void 0?t:!1,...Xe(e)})};function dX(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,o=n>r?n:r,i=parseInt(e.toFixed(o).replace(".","")),s=parseInt(t.toFixed(o).replace(".",""));return i%s/Math.pow(10,o)}class ac extends rt{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)!==be.number){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_type,expected:be.number,received:i.parsedType}),Ze}let r;const o=new zn;for(const i of this._def.checks)i.kind==="int"?mt.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.invalid_type,expected:"integer",received:"float",message:i.message}),o.dirty()):i.kind==="min"?(i.inclusive?t.datai.value:t.data>=i.value)&&(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),o.dirty()):i.kind==="multipleOf"?dX(t.data,i.value)!==0&&(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):i.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.not_finite,message:i.message}),o.dirty()):mt.assertNever(i);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,Ne.toString(n))}gt(t,n){return this.setLimit("min",t,!1,Ne.toString(n))}lte(t,n){return this.setLimit("max",t,!0,Ne.toString(n))}lt(t,n){return this.setLimit("max",t,!1,Ne.toString(n))}setLimit(t,n,r,o){return new ac({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:Ne.toString(o)}]})}_addCheck(t){return new ac({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:Ne.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Ne.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Ne.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Ne.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Ne.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:Ne.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:Ne.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Ne.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Ne.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"&&mt.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 ac({checks:[],typeName:ze.ZodNumber,coerce:(e==null?void 0:e.coerce)||!1,...Xe(e)});class lc extends rt{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)!==be.bigint){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_type,expected:be.bigint,received:i.parsedType}),Ze}let r;const o=new zn;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?t.datai.value:t.data>=i.value)&&(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),o.dirty()):i.kind==="multipleOf"?t.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):mt.assertNever(i);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,Ne.toString(n))}gt(t,n){return this.setLimit("min",t,!1,Ne.toString(n))}lte(t,n){return this.setLimit("max",t,!0,Ne.toString(n))}lt(t,n){return this.setLimit("max",t,!1,Ne.toString(n))}setLimit(t,n,r,o){return new lc({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:Ne.toString(o)}]})}_addCheck(t){return new lc({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Ne.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Ne.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Ne.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Ne.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:Ne.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 lc({checks:[],typeName:ze.ZodBigInt,coerce:(t=e==null?void 0:e.coerce)!==null&&t!==void 0?t:!1,...Xe(e)})};class $1 extends rt{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==be.boolean){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.boolean,received:r.parsedType}),Ze}return rr(t.data)}}$1.create=e=>new $1({typeName:ze.ZodBoolean,coerce:(e==null?void 0:e.coerce)||!1,...Xe(e)});class sd extends rt{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==be.date){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_type,expected:be.date,received:i.parsedType}),Ze}if(isNaN(t.data.getTime())){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_date}),Ze}const r=new zn;let o;for(const i of this._def.checks)i.kind==="min"?t.data.getTime()i.value&&(o=this._getOrReturnCtx(t,o),Ee(o,{code:pe.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):mt.assertNever(i);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new sd({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:Ne.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:Ne.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 sd({checks:[],coerce:(e==null?void 0:e.coerce)||!1,typeName:ze.ZodDate,...Xe(e)});class k1 extends rt{_parse(t){if(this._getType(t)!==be.symbol){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.symbol,received:r.parsedType}),Ze}return rr(t.data)}}k1.create=e=>new k1({typeName:ze.ZodSymbol,...Xe(e)});class Gh extends rt{_parse(t){if(this._getType(t)!==be.undefined){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.undefined,received:r.parsedType}),Ze}return rr(t.data)}}Gh.create=e=>new Gh({typeName:ze.ZodUndefined,...Xe(e)});class Xh extends rt{_parse(t){if(this._getType(t)!==be.null){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.null,received:r.parsedType}),Ze}return rr(t.data)}}Xh.create=e=>new Xh({typeName:ze.ZodNull,...Xe(e)});class R1 extends rt{constructor(){super(...arguments),this._any=!0}_parse(t){return rr(t.data)}}R1.create=e=>new R1({typeName:ze.ZodAny,...Xe(e)});class Tl extends rt{constructor(){super(...arguments),this._unknown=!0}_parse(t){return rr(t.data)}}Tl.create=e=>new Tl({typeName:ze.ZodUnknown,...Xe(e)});class Rs extends rt{_parse(t){const n=this._getOrReturnCtx(t);return Ee(n,{code:pe.invalid_type,expected:be.never,received:n.parsedType}),Ze}}Rs.create=e=>new Rs({typeName:ze.ZodNever,...Xe(e)});class T1 extends rt{_parse(t){if(this._getType(t)!==be.undefined){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.void,received:r.parsedType}),Ze}return rr(t.data)}}T1.create=e=>new T1({typeName:ze.ZodVoid,...Xe(e)});class Uo extends rt{_parse(t){const{ctx:n,status:r}=this._processInputParams(t),o=this._def;if(n.parsedType!==be.array)return Ee(n,{code:pe.invalid_type,expected:be.array,received:n.parsedType}),Ze;if(o.exactLength!==null){const s=n.data.length>o.exactLength.value,l=n.data.lengtho.maxLength.value&&(Ee(n,{code:pe.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((s,l)=>o.type._parseAsync(new Ko(n,s,n.path,l)))).then(s=>zn.mergeArray(r,s));const i=[...n.data].map((s,l)=>o.type._parseSync(new Ko(n,s,n.path,l)));return zn.mergeArray(r,i)}get element(){return this._def.type}min(t,n){return new Uo({...this._def,minLength:{value:t,message:Ne.toString(n)}})}max(t,n){return new Uo({...this._def,maxLength:{value:t,message:Ne.toString(n)}})}length(t,n){return new Uo({...this._def,exactLength:{value:t,message:Ne.toString(n)}})}nonempty(t){return this.min(1,t)}}Uo.create=(e,t)=>new Uo({type:e,minLength:null,maxLength:null,exactLength:null,typeName:ze.ZodArray,...Xe(t)});function ol(e){if(e instanceof Vt){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=bs.create(ol(r))}return new Vt({...e._def,shape:()=>t})}else return e instanceof Uo?new Uo({...e._def,type:ol(e.element)}):e instanceof bs?bs.create(ol(e.unwrap())):e instanceof uc?uc.create(ol(e.unwrap())):e instanceof _i?_i.create(e.items.map(t=>ol(t))):e}class Vt extends rt{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=mt.objectKeys(t);return this._cached={shape:t,keys:n}}_parse(t){if(this._getType(t)!==be.object){const d=this._getOrReturnCtx(t);return Ee(d,{code:pe.invalid_type,expected:be.object,received:d.parsedType}),Ze}const{status:r,ctx:o}=this._processInputParams(t),{shape:i,keys:s}=this._getCached(),l=[];if(!(this._def.catchall instanceof Rs&&this._def.unknownKeys==="strip"))for(const d in o.data)s.includes(d)||l.push(d);const u=[];for(const d of s){const h=i[d],m=o.data[d];u.push({key:{status:"valid",value:d},value:h._parse(new Ko(o,m,o.path,d)),alwaysSet:d in o.data})}if(this._def.catchall instanceof Rs){const d=this._def.unknownKeys;if(d==="passthrough")for(const h of l)u.push({key:{status:"valid",value:h},value:{status:"valid",value:o.data[h]}});else if(d==="strict")l.length>0&&(Ee(o,{code:pe.unrecognized_keys,keys:l}),r.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const d=this._def.catchall;for(const h of l){const m=o.data[h];u.push({key:{status:"valid",value:h},value:d._parse(new Ko(o,m,o.path,h)),alwaysSet:h in o.data})}}return o.common.async?Promise.resolve().then(async()=>{const d=[];for(const h of u){const m=await h.key;d.push({key:m,value:await h.value,alwaysSet:h.alwaysSet})}return d}).then(d=>zn.mergeObjectSync(r,d)):zn.mergeObjectSync(r,u)}get shape(){return this._def.shape()}strict(t){return Ne.errToObj,new Vt({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{var o,i,s,l;const u=(s=(i=(o=this._def).errorMap)===null||i===void 0?void 0:i.call(o,n,r).message)!==null&&s!==void 0?s:r.defaultError;return n.code==="unrecognized_keys"?{message:(l=Ne.errToObj(t).message)!==null&&l!==void 0?l:u}:{message:u}}}:{}})}strip(){return new Vt({...this._def,unknownKeys:"strip"})}passthrough(){return new Vt({...this._def,unknownKeys:"passthrough"})}extend(t){return new Vt({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new Vt({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:ze.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new Vt({...this._def,catchall:t})}pick(t){const n={};return mt.objectKeys(t).forEach(r=>{t[r]&&this.shape[r]&&(n[r]=this.shape[r])}),new Vt({...this._def,shape:()=>n})}omit(t){const n={};return mt.objectKeys(this.shape).forEach(r=>{t[r]||(n[r]=this.shape[r])}),new Vt({...this._def,shape:()=>n})}deepPartial(){return ol(this)}partial(t){const n={};return mt.objectKeys(this.shape).forEach(r=>{const o=this.shape[r];t&&!t[r]?n[r]=o:n[r]=o.optional()}),new Vt({...this._def,shape:()=>n})}required(t){const n={};return mt.objectKeys(this.shape).forEach(r=>{if(t&&!t[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof bs;)i=i._def.innerType;n[r]=i}}),new Vt({...this._def,shape:()=>n})}keyof(){return e3(mt.objectKeys(this.shape))}}Vt.create=(e,t)=>new Vt({shape:()=>e,unknownKeys:"strip",catchall:Rs.create(),typeName:ze.ZodObject,...Xe(t)});Vt.strictCreate=(e,t)=>new Vt({shape:()=>e,unknownKeys:"strict",catchall:Rs.create(),typeName:ze.ZodObject,...Xe(t)});Vt.lazycreate=(e,t)=>new Vt({shape:e,unknownKeys:"strip",catchall:Rs.create(),typeName:ze.ZodObject,...Xe(t)});class Zh extends rt{_parse(t){const{ctx:n}=this._processInputParams(t),r=this._def.options;function o(i){for(const l of i)if(l.result.status==="valid")return l.result;for(const l of i)if(l.result.status==="dirty")return n.common.issues.push(...l.ctx.common.issues),l.result;const s=i.map(l=>new Bo(l.ctx.common.issues));return Ee(n,{code:pe.invalid_union,unionErrors:s}),Ze}if(n.common.async)return Promise.all(r.map(async i=>{const s={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:s}),ctx:s}})).then(o);{let i;const s=[];for(const u of r){const d={...n,common:{...n.common,issues:[]},parent:null},h=u._parseSync({data:n.data,path:n.path,parent:d});if(h.status==="valid")return h;h.status==="dirty"&&!i&&(i={result:h,ctx:d}),d.common.issues.length&&s.push(d.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;const l=s.map(u=>new Bo(u));return Ee(n,{code:pe.invalid_union,unionErrors:l}),Ze}}get options(){return this._def.options}}Zh.create=(e,t)=>new Zh({options:e,typeName:ze.ZodUnion,...Xe(t)});const Zp=e=>e instanceof Jh?Zp(e.schema):e instanceof Si?Zp(e.innerType()):e instanceof em?[e.value]:e instanceof Ta?e.options:e instanceof tm?Object.keys(e.enum):e instanceof nm?Zp(e._def.innerType):e instanceof Gh?[void 0]:e instanceof Xh?[null]:null;class Yx extends rt{_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.object)return Ee(n,{code:pe.invalid_type,expected:be.object,received:n.parsedType}),Ze;const r=this.discriminator,o=n.data[r],i=this.optionsMap.get(o);return i?n.common.async?i._parseAsync({data:n.data,path:n.path,parent:n}):i._parseSync({data:n.data,path:n.path,parent:n}):(Ee(n,{code:pe.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),Ze)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){const o=new Map;for(const i of n){const s=Zp(i.shape[t]);if(!s)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const l of s){if(o.has(l))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(l)}`);o.set(l,i)}}return new Yx({typeName:ze.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:o,...Xe(r)})}}function P1(e,t){const n=ta(e),r=ta(t);if(e===t)return{valid:!0,data:e};if(n===be.object&&r===be.object){const o=mt.objectKeys(t),i=mt.objectKeys(e).filter(l=>o.indexOf(l)!==-1),s={...e,...t};for(const l of i){const u=P1(e[l],t[l]);if(!u.valid)return{valid:!1};s[l]=u.data}return{valid:!0,data:s}}else if(n===be.array&&r===be.array){if(e.length!==t.length)return{valid:!1};const o=[];for(let i=0;i{if(T2(i)||T2(s))return Ze;const l=P1(i.value,s.value);return l.valid?((P2(i)||P2(s))&&n.dirty(),{status:n.value,value:l.data}):(Ee(r,{code:pe.invalid_intersection_types}),Ze)};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(([i,s])=>o(i,s)):o(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}qh.create=(e,t,n)=>new qh({left:e,right:t,typeName:ze.ZodIntersection,...Xe(n)});class _i extends rt{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.array)return Ee(r,{code:pe.invalid_type,expected:be.array,received:r.parsedType}),Ze;if(r.data.lengththis._def.items.length&&(Ee(r,{code:pe.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const i=[...r.data].map((s,l)=>{const u=this._def.items[l]||this._def.rest;return u?u._parse(new Ko(r,s,r.path,l)):null}).filter(s=>!!s);return r.common.async?Promise.all(i).then(s=>zn.mergeArray(n,s)):zn.mergeArray(n,i)}get items(){return this._def.items}rest(t){return new _i({...this._def,rest:t})}}_i.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new _i({items:e,typeName:ze.ZodTuple,rest:null,...Xe(t)})};class Qh extends rt{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!==be.object)return Ee(r,{code:pe.invalid_type,expected:be.object,received:r.parsedType}),Ze;const o=[],i=this._def.keyType,s=this._def.valueType;for(const l in r.data)o.push({key:i._parse(new Ko(r,l,r.path,l)),value:s._parse(new Ko(r,r.data[l],r.path,l))});return r.common.async?zn.mergeObjectAsync(n,o):zn.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof rt?new Qh({keyType:t,valueType:n,typeName:ze.ZodRecord,...Xe(r)}):new Qh({keyType:di.create(),valueType:t,typeName:ze.ZodRecord,...Xe(n)})}}class A1 extends rt{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!==be.map)return Ee(r,{code:pe.invalid_type,expected:be.map,received:r.parsedType}),Ze;const o=this._def.keyType,i=this._def.valueType,s=[...r.data.entries()].map(([l,u],d)=>({key:o._parse(new Ko(r,l,r.path,[d,"key"])),value:i._parse(new Ko(r,u,r.path,[d,"value"]))}));if(r.common.async){const l=new Map;return Promise.resolve().then(async()=>{for(const u of s){const d=await u.key,h=await u.value;if(d.status==="aborted"||h.status==="aborted")return Ze;(d.status==="dirty"||h.status==="dirty")&&n.dirty(),l.set(d.value,h.value)}return{status:n.value,value:l}})}else{const l=new Map;for(const u of s){const d=u.key,h=u.value;if(d.status==="aborted"||h.status==="aborted")return Ze;(d.status==="dirty"||h.status==="dirty")&&n.dirty(),l.set(d.value,h.value)}return{status:n.value,value:l}}}}A1.create=(e,t,n)=>new A1({valueType:t,keyType:e,typeName:ze.ZodMap,...Xe(n)});class cc extends rt{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.set)return Ee(r,{code:pe.invalid_type,expected:be.set,received:r.parsedType}),Ze;const o=this._def;o.minSize!==null&&r.data.sizeo.maxSize.value&&(Ee(r,{code:pe.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());const i=this._def.valueType;function s(u){const d=new Set;for(const h of u){if(h.status==="aborted")return Ze;h.status==="dirty"&&n.dirty(),d.add(h.value)}return{status:n.value,value:d}}const l=[...r.data.values()].map((u,d)=>i._parse(new Ko(r,u,r.path,d)));return r.common.async?Promise.all(l).then(u=>s(u)):s(l)}min(t,n){return new cc({...this._def,minSize:{value:t,message:Ne.toString(n)}})}max(t,n){return new cc({...this._def,maxSize:{value:t,message:Ne.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}}cc.create=(e,t)=>new cc({valueType:e,minSize:null,maxSize:null,typeName:ze.ZodSet,...Xe(t)});class Pu extends rt{constructor(){super(...arguments),this.validate=this.implement}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.function)return Ee(n,{code:pe.invalid_type,expected:be.function,received:n.parsedType}),Ze;function r(l,u){return E1({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,S1(),Kh].filter(d=>!!d),issueData:{code:pe.invalid_arguments,argumentsError:u}})}function o(l,u){return E1({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,S1(),Kh].filter(d=>!!d),issueData:{code:pe.invalid_return_type,returnTypeError:u}})}const i={errorMap:n.common.contextualErrorMap},s=n.data;if(this._def.returns instanceof ad){const l=this;return rr(async function(...u){const d=new Bo([]),h=await l._def.args.parseAsync(u,i).catch(y=>{throw d.addIssue(r(u,y)),d}),m=await Reflect.apply(s,this,h);return await l._def.returns._def.type.parseAsync(m,i).catch(y=>{throw d.addIssue(o(m,y)),d})})}else{const l=this;return rr(function(...u){const d=l._def.args.safeParse(u,i);if(!d.success)throw new Bo([r(u,d.error)]);const h=Reflect.apply(s,this,d.data),m=l._def.returns.safeParse(h,i);if(!m.success)throw new Bo([o(h,m.error)]);return m.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new Pu({...this._def,args:_i.create(t).rest(Tl.create())})}returns(t){return new Pu({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new Pu({args:t||_i.create([]).rest(Tl.create()),returns:n||Tl.create(),typeName:ze.ZodFunction,...Xe(r)})}}class Jh extends rt{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})}}Jh.create=(e,t)=>new Jh({getter:e,typeName:ze.ZodLazy,...Xe(t)});class em extends rt{_parse(t){if(t.data!==this._def.value){const n=this._getOrReturnCtx(t);return Ee(n,{received:n.data,code:pe.invalid_literal,expected:this._def.value}),Ze}return{status:"valid",value:t.data}}get value(){return this._def.value}}em.create=(e,t)=>new em({value:e,typeName:ze.ZodLiteral,...Xe(t)});function e3(e,t){return new Ta({values:e,typeName:ze.ZodEnum,...Xe(t)})}class Ta extends rt{_parse(t){if(typeof t.data!="string"){const n=this._getOrReturnCtx(t),r=this._def.values;return Ee(n,{expected:mt.joinValues(r),received:n.parsedType,code:pe.invalid_type}),Ze}if(this._def.values.indexOf(t.data)===-1){const n=this._getOrReturnCtx(t),r=this._def.values;return Ee(n,{received:n.data,code:pe.invalid_enum_value,options:r}),Ze}return rr(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 Ta.create(t)}exclude(t){return Ta.create(this.options.filter(n=>!t.includes(n)))}}Ta.create=e3;class tm extends rt{_parse(t){const n=mt.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==be.string&&r.parsedType!==be.number){const o=mt.objectValues(n);return Ee(r,{expected:mt.joinValues(o),received:r.parsedType,code:pe.invalid_type}),Ze}if(n.indexOf(t.data)===-1){const o=mt.objectValues(n);return Ee(r,{received:r.data,code:pe.invalid_enum_value,options:o}),Ze}return rr(t.data)}get enum(){return this._def.values}}tm.create=(e,t)=>new tm({values:e,typeName:ze.ZodNativeEnum,...Xe(t)});class ad extends rt{unwrap(){return this._def.type}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.promise&&n.common.async===!1)return Ee(n,{code:pe.invalid_type,expected:be.promise,received:n.parsedType}),Ze;const r=n.parsedType===be.promise?n.data:Promise.resolve(n.data);return rr(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}}ad.create=(e,t)=>new ad({type:e,typeName:ze.ZodPromise,...Xe(t)});class Si extends rt{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ze.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:n,ctx:r}=this._processInputParams(t),o=this._def.effect||null,i={addIssue:s=>{Ee(r,s),s.fatal?n.abort():n.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),o.type==="preprocess"){const s=o.transform(r.data,i);return r.common.issues.length?{status:"dirty",value:r.data}:r.common.async?Promise.resolve(s).then(l=>this._def.schema._parseAsync({data:l,path:r.path,parent:r})):this._def.schema._parseSync({data:s,path:r.path,parent:r})}if(o.type==="refinement"){const s=l=>{const u=o.refinement(l,i);if(r.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return l};if(r.common.async===!1){const l=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return l.status==="aborted"?Ze:(l.status==="dirty"&&n.dirty(),s(l.value),{status:n.value,value:l.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(l=>l.status==="aborted"?Ze:(l.status==="dirty"&&n.dirty(),s(l.value).then(()=>({status:n.value,value:l.value}))))}if(o.type==="transform")if(r.common.async===!1){const s=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Yh(s))return s;const l=o.transform(s.value,i);if(l instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:l}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(s=>Yh(s)?Promise.resolve(o.transform(s.value,i)).then(l=>({status:n.value,value:l})):s);mt.assertNever(o)}}Si.create=(e,t,n)=>new Si({schema:e,typeName:ze.ZodEffects,effect:t,...Xe(n)});Si.createWithPreprocess=(e,t,n)=>new Si({schema:t,effect:{type:"preprocess",transform:e},typeName:ze.ZodEffects,...Xe(n)});class bs extends rt{_parse(t){return this._getType(t)===be.undefined?rr(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}bs.create=(e,t)=>new bs({innerType:e,typeName:ze.ZodOptional,...Xe(t)});class uc extends rt{_parse(t){return this._getType(t)===be.null?rr(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}uc.create=(e,t)=>new uc({innerType:e,typeName:ze.ZodNullable,...Xe(t)});class nm extends rt{_parse(t){const{ctx:n}=this._processInputParams(t);let r=n.data;return n.parsedType===be.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}nm.create=(e,t)=>new nm({innerType:e,typeName:ze.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Xe(t)});class O1 extends rt{_parse(t){const{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return C1(o)?o.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Bo(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Bo(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}O1.create=(e,t)=>new O1({innerType:e,typeName:ze.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Xe(t)});class M1 extends rt{_parse(t){if(this._getType(t)!==be.nan){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.nan,received:r.parsedType}),Ze}return{status:"valid",value:t.data}}}M1.create=e=>new M1({typeName:ze.ZodNaN,...Xe(e)});class fX extends rt{_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 sg extends rt{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?Ze:i.status==="dirty"?(n.dirty(),eX(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{const o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?Ze:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(t,n){return new sg({in:t,out:n,typeName:ze.ZodPipeline})}}class N1 extends rt{_parse(t){const n=this._def.innerType._parse(t);return Yh(n)&&(n.value=Object.freeze(n.value)),n}}N1.create=(e,t)=>new N1({innerType:e,typeName:ze.ZodReadonly,...Xe(t)});Vt.lazycreate;var ze;(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",e.ZodReadonly="ZodReadonly"})(ze||(ze={}));const O2=di.create;ac.create;M1.create;lc.create;const su=$1.create;sd.create;k1.create;Gh.create;Xh.create;R1.create;Tl.create;Rs.create;T1.create;Uo.create;const pX=Vt.create;Vt.strictCreate;Zh.create;Yx.create;qh.create;_i.create;Qh.create;A1.create;cc.create;Pu.create;Jh.create;em.create;Ta.create;tm.create;ad.create;Si.create;bs.create;uc.create;Si.createWithPreprocess;sg.create;const D1="horizontal",hX=["horizontal","vertical"],t3=f.forwardRef((e,t)=>{const{decorative:n,orientation:r=D1,...o}=e,i=n3(r)?r:D1,l=n?{role:"none"}:{"aria-orientation":i==="vertical"?i:void 0,role:"separator"};return f.createElement(Pe.div,Y({"data-orientation":i},l,o,{ref:t}))});t3.propTypes={orientation(e,t,n){const r=e[t],o=String(r);return r&&!n3(r)?new Error(mX(o,n)):null}};function mX(e,t){return`Invalid prop \`orientation\` of value \`${e}\` supplied to \`${t}\`, expected one of: + - horizontal + - vertical + +Defaulting to \`${D1}\`.`}function n3(e){return hX.includes(e)}const r3=t3,Fn=f.forwardRef(({className:e,orientation:t="horizontal",decorative:n=!0,...r},o)=>v.jsx(r3,{ref:o,decorative:n,orientation:t,className:Ce("shrink-0 bg-border",t==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",e),...r}));Fn.displayName=r3.displayName;const gX=f.forwardRef((e,t)=>f.createElement(Pe.label,Y({},e,{ref:t,onMouseDown:n=>{var r;(r=e.onMouseDown)===null||r===void 0||r.call(e,n),!n.defaultPrevented&&n.detail>1&&n.preventDefault()}}))),o3=gX,vX=Om("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),Gx=f.forwardRef(({className:e,disabled:t,...n},r)=>v.jsx(o3,{ref:r,className:Ce(vX(),e,t?"opacity-50":"","select-none"),...n}));Gx.displayName=o3.displayName;const yX=OG,i3=f.createContext({}),N0=({...e})=>v.jsx(i3.Provider,{value:{name:e.name},children:v.jsx(IG,{...e})}),ag=()=>{const e=f.useContext(i3),t=f.useContext(s3),{getFieldState:n,formState:r}=ig(),o=n(e.name,r);if(!e)throw new Error("useFormField should be used within ");const{id:i}=t;return{id:i,name:e.name,formItemId:`${i}-form-item`,formDescriptionId:`${i}-form-item-description`,formMessageId:`${i}-form-item-message`,...o}},s3=f.createContext({}),qp=f.forwardRef(({className:e,...t},n)=>{const r=f.useId();return v.jsx(s3.Provider,{value:{id:r},children:v.jsx("div",{ref:n,className:Ce("space-y-2",e),...t})})});qp.displayName="FormItem";const Qp=f.forwardRef(({className:e,...t},n)=>{const{error:r,formItemId:o}=ag();return v.jsx(Gx,{ref:n,className:Ce(r&&"text-destructive","text-sm",e),htmlFor:o,...t})});Qp.displayName="FormLabel";const Jp=f.forwardRef(({...e},t)=>{const{error:n,formItemId:r,formDescriptionId:o,formMessageId:i}=ag();return v.jsx(Wo,{ref:t,id:r,"aria-describedby":n?`${o} ${i}`:`${o}`,"aria-invalid":!!n,...e})});Jp.displayName="FormControl";const eh=f.forwardRef(({className:e,...t},n)=>{const{formDescriptionId:r}=ag();return v.jsx("p",{ref:n,id:r,className:Ce("text-[0.8rem] text-muted-foreground",e),...t})});eh.displayName="FormDescription";const wX=f.forwardRef(({className:e,children:t,...n},r)=>{const{error:o,formMessageId:i}=ag(),s=o?String(o==null?void 0:o.message):t;return s?v.jsx("p",{ref:r,id:i,className:Ce("text-[0.8rem] font-medium text-destructive",e),...n,children:s}):null});wX.displayName="FormMessage";const a3="Switch",[xX,_te]=An(a3),[bX,_X]=xX(a3),SX=f.forwardRef((e,t)=>{const{__scopeSwitch:n,name:r,checked:o,defaultChecked:i,required:s,disabled:l,value:u="on",onCheckedChange:d,...h}=e,[m,g]=f.useState(null),y=Be(t,b=>g(b)),x=f.useRef(!1),_=m?!!m.closest("form"):!0,[C=!1,S]=Zr({prop:o,defaultProp:i,onChange:d});return f.createElement(bX,{scope:n,checked:C,disabled:l},f.createElement(Pe.button,Y({type:"button",role:"switch","aria-checked":C,"aria-required":s,"data-state":l3(C),"data-disabled":l?"":void 0,disabled:l,value:u},h,{ref:y,onClick:ue(e.onClick,b=>{S(E=>!E),_&&(x.current=b.isPropagationStopped(),x.current||b.stopPropagation())})})),_&&f.createElement($X,{control:m,bubbles:!x.current,name:r,value:u,checked:C,required:s,disabled:l,style:{transform:"translateX(-100%)"}}))}),EX="SwitchThumb",CX=f.forwardRef((e,t)=>{const{__scopeSwitch:n,...r}=e,o=_X(EX,n);return f.createElement(Pe.span,Y({"data-state":l3(o.checked),"data-disabled":o.disabled?"":void 0},r,{ref:t}))}),$X=e=>{const{control:t,checked:n,bubbles:r=!0,...o}=e,i=f.useRef(null),s=Fx(n),l=gx(t);return f.useEffect(()=>{const u=i.current,d=window.HTMLInputElement.prototype,m=Object.getOwnPropertyDescriptor(d,"checked").set;if(s!==n&&m){const g=new Event("click",{bubbles:r});m.call(u,n),u.dispatchEvent(g)}},[s,n,r]),f.createElement("input",Y({type:"checkbox","aria-hidden":!0,defaultChecked:n},o,{tabIndex:-1,ref:i,style:{...e.style,...l,position:"absolute",pointerEvents:"none",opacity:0,margin:0}}))};function l3(e){return e?"checked":"unchecked"}const c3=SX,kX=CX,co=f.forwardRef(({className:e,...t},n)=>v.jsx(c3,{className:Ce("peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",e),tabIndex:-1,...t,ref:n,children:v.jsx(kX,{className:Ce("pointer-events-none block h-4 w-4 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0")})}));co.displayName=c3.displayName;const RX="AlertDialog",[TX,Ste]=An(RX,[cP]),Is=cP(),PX=e=>{const{__scopeAlertDialog:t,...n}=e,r=Is(t);return f.createElement(Sx,Y({},r,n,{modal:!0}))},AX=e=>{const{__scopeAlertDialog:t,...n}=e,r=Is(t);return f.createElement(Ex,Y({},r,n))},OX=f.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=Is(n);return f.createElement(Nd,Y({},o,r,{ref:t}))}),u3="AlertDialogContent",[MX,NX]=TX(u3),DX=f.forwardRef((e,t)=>{const{__scopeAlertDialog:n,children:r,...o}=e,i=Is(n),s=f.useRef(null),l=Be(t,s),u=f.useRef(null);return f.createElement(fW,{contentName:u3,titleName:IX,docsSlug:"alert-dialog"},f.createElement(MX,{scope:n,cancelRef:u},f.createElement(Dd,Y({role:"alertdialog"},i,o,{ref:l,onOpenAutoFocus:ue(o.onOpenAutoFocus,d=>{var h;d.preventDefault(),(h=u.current)===null||h===void 0||h.focus({preventScroll:!0})}),onPointerDownOutside:d=>d.preventDefault(),onInteractOutside:d=>d.preventDefault()}),f.createElement(sx,null,r),!1)))}),IX="AlertDialogTitle",LX=f.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=Is(n);return f.createElement(Id,Y({},o,r,{ref:t}))}),FX=f.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=Is(n);return f.createElement(Ld,Y({},o,r,{ref:t}))}),jX=f.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=Is(n);return f.createElement(Cx,Y({},o,r,{ref:t}))}),zX="AlertDialogCancel",BX=f.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,{cancelRef:o}=NX(zX,n),i=Is(n),s=Be(t,o);return f.createElement(Cx,Y({},i,r,{ref:s}))}),UX=PX,VX=AX,d3=OX,f3=DX,p3=jX,h3=BX,m3=LX,g3=FX,WX=UX,HX=VX,v3=f.forwardRef(({className:e,...t},n)=>v.jsx(d3,{className:Ce("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t,ref:n}));v3.displayName=d3.displayName;const y3=f.forwardRef(({className:e,...t},n)=>v.jsxs(HX,{children:[v.jsx(v3,{}),v.jsx(f3,{ref:n,className:Ce("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",e),...t})]}));y3.displayName=f3.displayName;const w3=({className:e,...t})=>v.jsx("div",{className:Ce("flex flex-col space-y-2 text-center sm:text-left",e),...t});w3.displayName="AlertDialogHeader";const KX=f.forwardRef(({className:e,...t},n)=>v.jsx(m3,{ref:n,className:Ce("text-lg font-semibold",e),...t}));KX.displayName=m3.displayName;const YX=f.forwardRef(({className:e,...t},n)=>v.jsx(g3,{ref:n,className:Ce("text-sm text-muted-foreground",e),...t}));YX.displayName=g3.displayName;const GX=f.forwardRef(({className:e,...t},n)=>v.jsx(p3,{ref:n,className:Ce(bx(),e),...t}));GX.displayName=p3.displayName;const XX=f.forwardRef(({className:e,...t},n)=>v.jsx(h3,{ref:n,className:Ce(bx({variant:"outline"}),"mt-2 sm:mt-0",e),...t}));XX.displayName=h3.displayName;const ZX=pX({enableFileManager:su(),inputDirectory:O2(),outputDirectory:O2(),enableDownloadMask:su(),enableManualInpainting:su(),enableUploadMask:su(),enableAutoExtractPrompt:su()}),x3="General",I1="Model",qX=[I1,x3];function QX(){const[e,t]=u1(!1),[n,r]=u1(!1),[o,i]=f.useState(I1),[s,l,u,d,h,m]=bt(O=>[O.updateAppState,O.settings,O.updateSettings,O.fileManagerState,O.updateFileManagerState,O.setModel]),{toast:g}=Td(),[y,x]=f.useState(l.model);f.useEffect(()=>{x(l.model)},[l.model]);const{data:_,status:C}=TL({queryKey:["modelInfos"],queryFn:Bj}),S=YG({resolver:QG(ZX),defaultValues:{enableDownloadMask:l.enableDownloadMask,enableManualInpainting:l.enableManualInpainting,enableUploadMask:l.enableUploadMask,enableAutoExtractPrompt:l.enableAutoExtractPrompt,inputDirectory:d.inputDirectory,outputDirectory:d.outputDirectory}});async function b(O){if(u({enableDownloadMask:O.enableDownloadMask,enableManualInpainting:O.enableManualInpainting,enableUploadMask:O.enableUploadMask,enableAutoExtractPrompt:O.enableAutoExtractPrompt}),h({inputDirectory:O.inputDirectory,outputDirectory:O.outputDirectory}),y.name!==l.model.name){r(),s({disableShortCuts:!0});try{const F=await jj(y.name);g({title:`Switch to ${F.name} success`}),m(y)}catch(F){g({variant:"destructive",title:`Switch to ${y.name} failed: ${F}`}),x(l.model)}finally{r(),s({disableShortCuts:!1})}}}Zn("s",()=>{t(),e&&b(S.getValues())},[e,S,y]);function E(O){t(),O||b(S.getValues())}function k(O){x(O)}function P(O){return _?_.filter(F=>O.includes(F.model_type)).map(F=>v.jsxs("div",{onClick:()=>k(F),className:"px-2",children:[v.jsx("div",{className:Ce([F.name===y.name?"bg-muted":"hover:bg-muted","rounded-md px-2 py-2","cursor-default"]),children:v.jsx("div",{className:"text-base",children:F.name})}),v.jsx(Fn,{className:"my-1"})]},F.name)):v.jsx("div",{children:"Please download model first"})}function M(){if(C!=="success")return v.jsx(v.Fragment,{});let O=is;for(let F of _)if(y.name===F.name){O=F.model_type,O===nC&&(O=rp),O===rC&&(O=op);break}return v.jsxs("div",{className:"flex flex-col gap-4 w-[510px]",children:[v.jsxs("div",{className:"flex flex-col gap-4 rounded-md",children:[v.jsx("div",{className:"font-medium",children:"Current Model"}),v.jsx("div",{children:y.name})]}),v.jsx(Fn,{}),v.jsxs("div",{className:"space-y-4 rounded-md",children:[v.jsx("div",{className:"flex gap-1 items-center justify-start",children:v.jsx("div",{className:"font-medium",children:"Available models"})}),v.jsxs(i5,{defaultValue:O,children:[v.jsxs(Lx,{children:[v.jsx(sa,{value:is,children:"Inpaint"}),v.jsx(sa,{value:rp,children:"Stable Diffusion"}),v.jsx(sa,{value:op,children:"Stable Diffusion Inpaint"}),v.jsx(sa,{value:l0,children:"Other Diffusion"})]}),v.jsxs(og,{className:"h-[240px] w-full mt-2 outline-none border rounded-lg",children:[v.jsx(mu,{value:is,children:P([is])}),v.jsx(mu,{value:rp,children:P([rp,nC])}),v.jsx(mu,{value:op,children:P([op,rC])}),v.jsx(mu,{value:l0,children:P([l0])})]})]})]})]})}function A(){return v.jsxs("div",{className:"space-y-4 w-[510px]",children:[v.jsx(N0,{control:S.control,name:"enableManualInpainting",render:({field:O})=>v.jsxs(qp,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(Qp,{children:"Enable manual inpainting"}),v.jsx(eh,{children:"For erase model, click a button to trigger inpainting after draw mask."})]}),v.jsx(Jp,{children:v.jsx(co,{checked:O.value,onCheckedChange:O.onChange})})]})}),v.jsx(Fn,{}),v.jsx(N0,{control:S.control,name:"enableDownloadMask",render:({field:O})=>v.jsxs(qp,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(Qp,{children:"Enable download mask"}),v.jsx(eh,{children:"Also download the mask after save the inpainting result."})]}),v.jsx(Jp,{children:v.jsx(co,{checked:O.value,onCheckedChange:O.onChange})})]})}),v.jsx(Fn,{}),v.jsx(N0,{control:S.control,name:"enableAutoExtractPrompt",render:({field:O})=>v.jsxs(qp,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(Qp,{children:"Enable auto extract prompt"}),v.jsx(eh,{children:"Automatically extract prompt/negativate prompt from the image meta."})]}),v.jsx(Jp,{children:v.jsx(co,{checked:O.value,onCheckedChange:O.onChange})})]})})]})}return v.jsxs(v.Fragment,{children:[v.jsx(WX,{open:n,children:v.jsx(y3,{children:v.jsx(w3,{children:v.jsxs("div",{className:"flex flex-col justify-center items-center gap-4",children:[v.jsxs("div",{role:"status",children:[v.jsxs("svg",{"aria-hidden":"true",className:"w-8 h-8 text-gray-200 animate-spin dark:text-gray-600 fill-primary",viewBox:"0 0 100 101",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[v.jsx("path",{d:"M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z",fill:"currentColor"}),v.jsx("path",{d:"M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z",fill:"currentFill"})]}),v.jsx("span",{className:"sr-only",children:"Loading..."})]}),v.jsxs("div",{children:["Switching to ",y.name]})]})})})}),v.jsxs(Zm,{open:e,onOpenChange:E,children:[v.jsx($x,{asChild:!0,children:v.jsx(vn,{tooltip:"Settings",children:v.jsx(iV,{})})}),v.jsxs(Fd,{className:"max-w-3xl h-[600px]",onOpenAutoFocus:O=>O.preventDefault(),children:[v.jsx(jd,{children:"Settings"}),v.jsx(Fn,{}),v.jsxs("div",{className:"flex flex-row space-x-8 h-full",children:[v.jsx("div",{className:"flex flex-col space-y-1",children:qX.map(O=>v.jsx(yn,{variant:"ghost",onClick:()=>i(O),className:Ce(o===O?"bg-muted ":"hover:bg-muted","justify-start"),children:O},O))}),v.jsx(Fn,{orientation:"vertical"}),v.jsx(yX,{...S,children:v.jsx("div",{className:"flex w-full justify-center",children:v.jsxs("form",{onSubmit:S.handleSubmit(b),children:[o===I1?M():v.jsx(v.Fragment,{}),o===x3?A():v.jsx(v.Fragment,{}),v.jsx("div",{className:"absolute right-10 bottom-6",children:v.jsx(yn,{onClick:()=>E(!1),children:"Ok"})})]})})})]})]})]})]})}const JX="/assets/kofi_button_black-XI_Dr2zg.png";function eZ(){return v.jsxs(Zm,{children:[v.jsx($x,{asChild:!0,children:v.jsx(vn,{tooltip:"Buy me a coffee",children:v.jsx(GU,{})})}),v.jsxs(Fd,{children:[v.jsx(jd,{children:"Buy me a coffee"}),v.jsx(mP,{className:"mb-8",children:"Hi, if you found my project is useful, please conside buy me a coffee to support my work. Thanks!"}),v.jsx("div",{className:"w-full flex items-center justify-center",children:v.jsx("a",{href:"https://ko-fi.com/Z8Z1CZJGY",target:"_blank",rel:"noreferrer",children:v.jsx("img",{src:JX,className:"h-[32px]"})})})]})]})}const tZ=()=>{const[e,t,n,r,o,i,s,l,u,d,h,m,g,y]=bt(M=>[M.file,M.customMask,M.isInpainting,M.serverConfig,M.runMannually(),M.settings.enableUploadMask,M.settings.model,M.setFile,M.setCustomFile,M.runInpainting,M.showPrevMask,M.hidePrevMask,M.imageHeight,M.imageWidth]),{toast:x}=Td(),[_,C]=Rx(t),[S,b]=f.useState(!1),E=()=>{d()},k=()=>{h()},P=()=>{m()};return v.jsxs("header",{className:"h-[60px] px-6 py-4 absolute top-[0] flex justify-between items-center w-full z-20 border-b backdrop-filter backdrop-blur-md bg-background/70",children:[v.jsxs("div",{className:"flex items-center gap-1",children:[r.enableFileManager?v.jsx(TG,{photoWidth:512,onPhotoClick:async(M,A)=>{try{const O=await Uj(M,A);l(O)}catch(O){x({variant:"destructive",description:O.message?O.message:O.toString()});return}}}):v.jsx(v.Fragment,{}),v.jsx(c1,{disabled:n,tooltip:"Upload image",onFileUpload:M=>{l(M)},children:v.jsx(eV,{})}),v.jsxs("div",{className:Ce(["flex items-center gap-1",e&&i?"visible":"hidden"]),children:[v.jsx(c1,{disabled:n,tooltip:"Upload custom mask",onFileUpload:async M=>{let A=null;try{A=await pF(M)}catch(O){x({variant:"destructive",description:O.message?O.message:O.toString()});return}if(A.naturalHeight!==g||A.naturalWidth!==y){x({variant:"destructive",description:`The size of the mask must same as image: ${y}x${g}`});return}u(M),o||d()},children:v.jsx(ZT,{})}),t?v.jsxs(HW,{open:S,children:[v.jsx(KW,{className:"btn-primary side-panel-trigger",onMouseEnter:()=>b(!0),onMouseLeave:()=>b(!1),style:{visibility:t?"visible":"hidden",outline:"none"},onClick:()=>{},children:v.jsx(vn,{tooltip:"Run custom mask",children:v.jsx(cz,{})})}),v.jsx(PP,{children:C?v.jsx("img",{src:_.src,alt:"Custom mask"}):v.jsx(v.Fragment,{})})]}):v.jsx(v.Fragment,{})]}),e&&!s.need_prompt?v.jsx(vn,{disabled:n,tooltip:"Rerun previous mask",onClick:E,onMouseEnter:k,onMouseLeave:P,children:v.jsx(oV,{})}):v.jsx(v.Fragment,{})]}),s.need_prompt?v.jsx(vH,{}):v.jsx(v.Fragment,{}),v.jsxs("div",{className:"flex gap-1",children:[v.jsx(eZ,{}),v.jsx(AW,{}),r.disableModelSwitch?v.jsx(v.Fragment,{}):v.jsx(QX,{})]})]})};var Wr=function(e,t){return Number(e.toFixed(t))},nZ=function(e,t){return typeof e=="number"?e:t},Nt=function(e,t,n){n&&typeof n=="function"&&n(e,t)},rZ=function(e){return-Math.cos(e*Math.PI)/2+.5},oZ=function(e){return e},iZ=function(e){return e*e},sZ=function(e){return e*(2-e)},aZ=function(e){return e<.5?2*e*e:-1+(4-2*e)*e},lZ=function(e){return e*e*e},cZ=function(e){return--e*e*e+1},uZ=function(e){return e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1},dZ=function(e){return e*e*e*e},fZ=function(e){return 1- --e*e*e*e},pZ=function(e){return e<.5?8*e*e*e*e:1-8*--e*e*e*e},hZ=function(e){return e*e*e*e*e},mZ=function(e){return 1+--e*e*e*e*e},gZ=function(e){return e<.5?16*e*e*e*e*e:1+16*--e*e*e*e*e},b3={easeOut:rZ,linear:oZ,easeInQuad:iZ,easeOutQuad:sZ,easeInOutQuad:aZ,easeInCubic:lZ,easeOutCubic:cZ,easeInOutCubic:uZ,easeInQuart:dZ,easeOutQuart:fZ,easeInOutQuart:pZ,easeInQuint:hZ,easeOutQuint:mZ,easeInOutQuint:gZ},_3=function(e){typeof e=="number"&&cancelAnimationFrame(e)},Do=function(e){e.mounted&&(_3(e.animation),e.animate=!1,e.animation=null,e.velocity=null)};function S3(e,t,n,r){if(e.mounted){var o=new Date().getTime(),i=1;Do(e),e.animation=function(){if(!e.mounted)return _3(e.animation);var s=new Date().getTime()-o,l=s/n,u=b3[t],d=u(l);s>=n?(r(i),e.animation=null):e.animation&&(r(d),requestAnimationFrame(e.animation))},requestAnimationFrame(e.animation)}}function vZ(e){var t=e.scale,n=e.positionX,r=e.positionY;return!(Number.isNaN(t)||Number.isNaN(n)||Number.isNaN(r))}function Ls(e,t,n,r){var o=vZ(t);if(!(!e.mounted||!o)){var i=e.setTransformState,s=e.transformState,l=s.scale,u=s.positionX,d=s.positionY,h=t.scale-l,m=t.positionX-u,g=t.positionY-d;n===0?i(t.scale,t.positionX,t.positionY):S3(e,r,n,function(y){var x=l+h*y,_=u+m*y,C=d+g*y;i(x,_,C)})}}function yZ(e,t,n){var r=e.offsetWidth,o=e.offsetHeight,i=t.offsetWidth,s=t.offsetHeight,l=i*n,u=s*n,d=r-l,h=o-u;return{wrapperWidth:r,wrapperHeight:o,newContentWidth:l,newDiffWidth:d,newContentHeight:u,newDiffHeight:h}}var wZ=function(e,t,n,r,o,i,s){var l=e>t?n*(s?1:.5):0,u=r>o?i*(s?1:.5):0,d=e-t-l,h=l,m=r-o-u,g=u;return{minPositionX:d,maxPositionX:h,minPositionY:m,maxPositionY:g}},Xx=function(e,t){var n=e.wrapperComponent,r=e.contentComponent,o=e.setup.centerZoomedOut;if(!n||!r)throw new Error("Components are not mounted");var i=yZ(n,r,t),s=i.wrapperWidth,l=i.wrapperHeight,u=i.newContentWidth,d=i.newDiffWidth,h=i.newContentHeight,m=i.newDiffHeight,g=wZ(s,u,d,l,h,m,!!o);return g},L1=function(e,t,n,r){return r?en?Wr(n,2):Wr(e,2):Wr(e,2)},dc=function(e,t){var n=Xx(e,t);return e.bounds=n,n};function lg(e,t,n,r,o,i,s){var l=n.minPositionX,u=n.minPositionY,d=n.maxPositionX,h=n.maxPositionY,m=0,g=0;s&&(m=o,g=i);var y=L1(e,l-m,d+m,r),x=L1(t,u-g,h+g,r);return{x:y,y:x}}function cg(e,t,n,r,o,i){var s=e.transformState,l=s.scale,u=s.positionX,d=s.positionY,h=r-l;if(typeof t!="number"||typeof n!="number")return console.error("Mouse X and Y position were not provided!"),{x:u,y:d};var m=u-t*h,g=d-n*h,y=lg(m,g,o,i,0,0,null);return y}function Vd(e,t,n,r,o){var i=o?r:0,s=t-i;return!Number.isNaN(n)&&e>=n?n:!Number.isNaN(t)&&e<=s?s:e}var M2=function(e,t){var n=e.setup.panning.excluded,r=e.isInitialized,o=e.wrapperComponent,i=t.target,s=o==null?void 0:o.contains(i),l=r&&i&&s;if(!l)return!1;var u=ug(i,n);return!u},N2=function(e){var t=e.isInitialized,n=e.isPanning,r=e.setup,o=r.panning.disabled,i=t&&n&&!o;return!!i},xZ=function(e,t){var n=e.transformState,r=n.positionX,o=n.positionY;e.isPanning=!0;var i=t.clientX,s=t.clientY;e.startCoords={x:i-r,y:s-o}},bZ=function(e,t){var n=t.touches,r=e.transformState,o=r.positionX,i=r.positionY;e.isPanning=!0;var s=n.length===1;if(s){var l=n[0].clientX,u=n[0].clientY;e.startCoords={x:l-o,y:u-i}}};function _Z(e){var t=e.transformState,n=t.positionX,r=t.positionY,o=t.scale,i=e.setup,s=i.disabled,l=i.limitToBounds,u=i.centerZoomedOut,d=e.wrapperComponent;if(!(s||!d||!e.bounds)){var h=e.bounds,m=h.maxPositionX,g=h.minPositionX,y=h.maxPositionY,x=h.minPositionY,_=n>m||ny||rm?d.offsetWidth:e.setup.minPositionX||0,b=r>y?d.offsetHeight:e.setup.minPositionY||0,E=cg(e,S,b,o,e.bounds,l||u),k=E.x,P=E.y;return{scale:o,positionX:_?k:n,positionY:C?P:r}}}function SZ(e,t,n,r,o){var i=e.setup.limitToBounds,s=e.wrapperComponent,l=e.bounds,u=e.transformState,d=u.scale,h=u.positionX,m=u.positionY;if(!(s===null||l===null||t===h&&n===m)){var g=lg(t,n,l,i,r,o,s),y=g.x,x=g.y;e.setTransformState(d,y,x)}}var EZ=function(e,t,n){var r=e.startCoords,o=e.transformState,i=e.setup.panning,s=i.lockAxisX,l=i.lockAxisY,u=o.positionX,d=o.positionY;if(!r)return{x:u,y:d};var h=t-r.x,m=n-r.y,g=s?u:h,y=l?d:m;return{x:g,y}},rm=function(e,t){var n=e.setup,r=e.transformState,o=r.scale,i=n.minScale,s=n.disablePadding;return t>0&&o>=i&&!s?t:0},CZ=function(e){var t=e.mounted,n=e.setup,r=n.disabled,o=n.velocityAnimation,i=e.transformState.scale,s=o.disabled,l=!s||i>1||!r||t;return!!l},$Z=function(e){var t=e.mounted,n=e.velocity,r=e.bounds,o=e.setup,i=o.disabled,s=o.velocityAnimation,l=e.transformState.scale,u=s.disabled,d=!u||l>1||!i||t;return!(!d||!n||!r)};function kZ(e,t){var n=e.setup.velocityAnimation,r=n.equalToMove,o=n.animationTime,i=n.sensitivity;return r?o*t*i:o}function D2(e,t,n,r,o,i,s,l,u,d){if(o){if(t>s&&n>s){var h=s+(e-s)*d;return h>u?u:hi?i:h}}return r?t:L1(e,i,s,o)}function RZ(e,t){var n=1;return t?Math.min(n,e.offsetWidth/window.innerWidth):n}function TZ(e,t){var n=CZ(e);if(n){var r=e.lastMousePosition,o=e.velocityTime,i=e.setup,s=e.wrapperComponent,l=i.velocityAnimation.equalToMove,u=Date.now();if(r&&o&&s){var d=RZ(s,l),h=t.x-r.x,m=t.y-r.y,g=h/d,y=m/d,x=u-o,_=h*h+m*m,C=Math.sqrt(_)/x;e.velocity={velocityX:g,velocityY:y,total:C}}e.lastMousePosition=t,e.velocityTime=u}}function PZ(e){var t=e.velocity,n=e.bounds,r=e.setup,o=e.wrapperComponent,i=$Z(e);if(!(!i||!t||!n||!o)){var s=t.velocityX,l=t.velocityY,u=t.total,d=n.maxPositionX,h=n.minPositionX,m=n.maxPositionY,g=n.minPositionY,y=r.limitToBounds,x=r.alignmentAnimation,_=r.zoomAnimation,C=r.panning,S=C.lockAxisY,b=C.lockAxisX,E=_.animationType,k=x.sizeX,P=x.sizeY,M=x.velocityAlignmentTime,A=M,O=kZ(e,u),F=Math.max(O,A),V=rm(e,k),J=rm(e,P),G=V*o.offsetWidth/100,ae=J*o.offsetHeight/100,U=d+G,te=h-G,L=m+ae,ie=g-ae,K=e.transformState,Q=new Date().getTime();S3(e,E,F,function(W){var le=e.transformState,ge=le.scale,Ve=le.positionX,Ue=le.positionY,We=new Date().getTime()-Q,Me=We/A,fe=b3[x.animationType],xe=1-fe(Math.min(1,Me)),$e=1-W,Ae=Ve+s*$e,Oe=Ue+l*$e,je=D2(Ae,K.positionX,Ve,b,y,h,d,te,U,xe),Ot=D2(Oe,K.positionY,Ue,S,y,g,m,ie,L,xe);(Ve!==Ae||Ue!==Oe)&&e.setTransformState(ge,je,Ot)})}}function I2(e,t){var n=e.transformState.scale;Do(e),dc(e,n),window.TouchEvent!==void 0&&t instanceof TouchEvent?bZ(e,t):xZ(e,t)}function E3(e){var t=e.transformState.scale,n=e.setup,r=n.minScale,o=n.alignmentAnimation,i=o.disabled,s=o.sizeX,l=o.sizeY,u=o.animationTime,d=o.animationType,h=i||t.1&&m;g?PZ(e):E3(e)}}function Zx(e,t,n,r){var o=e.setup,i=o.minScale,s=o.maxScale,l=o.limitToBounds,u=Vd(Wr(t,2),i,s,0,!1),d=dc(e,u),h=cg(e,n,r,u,d,l),m=h.x,g=h.y;return{scale:u,positionX:m,positionY:g}}function C3(e,t,n){var r=e.transformState.scale,o=e.wrapperComponent,i=e.setup,s=i.minScale,l=i.limitToBounds,u=i.zoomAnimation,d=u.disabled,h=u.animationTime,m=u.animationType,g=d||r>=s;if((r>=1||l)&&E3(e),!(g||!o||!e.mounted)){var y=t||o.offsetWidth/2,x=n||o.offsetHeight/2,_=Zx(e,s,y,x);_&&Ls(e,_,h,m)}}var _s=function(){return _s=Object.assign||function(t){for(var n,r=1,o=arguments.length;rs||Math.sign(n.deltaY)!==Math.sign(t.deltaY)||n.deltaY>0&&n.deltaYt.deltaY||Math.sign(n.deltaY)!==Math.sign(t.deltaY):!1},GZ=function(e,t){var n=e.setup.pinch,r=n.disabled,o=n.excluded,i=e.isInitialized,s=t.target,l=i&&!r&&s;if(!l)return!1;var u=ug(s,o);return!u},XZ=function(e){var t=e.setup.pinch.disabled,n=e.isInitialized,r=e.pinchStartDistance,o=n&&!t&&r;return!!o},ZZ=function(e,t,n){var r=n.getBoundingClientRect(),o=e.touches,i=Wr(o[0].clientX-r.left,5),s=Wr(o[0].clientY-r.top,5),l=Wr(o[1].clientX-r.left,5),u=Wr(o[1].clientY-r.top,5);return{x:(i+l)/2/t,y:(s+u)/2/t}},O3=function(e){return Math.sqrt(Math.pow(e.touches[0].pageX-e.touches[1].pageX,2)+Math.pow(e.touches[0].pageY-e.touches[1].pageY,2))},qZ=function(e,t){var n=e.pinchStartScale,r=e.pinchStartDistance,o=e.setup,i=o.maxScale,s=o.minScale,l=o.zoomAnimation,u=o.disablePadding,d=l.size,h=l.disabled;if(!n||r===null||!t)throw new Error("Pinch touches distance was not provided");if(t<0)return e.transformState.scale;var m=t/r,g=m*n;return Vd(Wr(g,2),s,i,d,!h&&!u)},QZ=160,JZ=100,eq=function(e,t){var n=e.props,r=n.onWheelStart,o=n.onZoomStart;e.wheelStopEventTimer||(Do(e),Nt(St(e),t,r),Nt(St(e),t,o))},tq=function(e,t){var n=e.props,r=n.onWheel,o=n.onZoom,i=e.contentComponent,s=e.setup,l=e.transformState,u=l.scale,d=s.limitToBounds,h=s.centerZoomedOut,m=s.zoomAnimation,g=s.wheel,y=s.disablePadding,x=s.smooth,_=m.size,C=m.disabled,S=g.step,b=g.smoothStep;if(!i)throw new Error("Component not mounted");t.preventDefault(),t.stopPropagation();var E=HZ(t,null),k=x?b*Math.abs(t.deltaY):S,P=KZ(e,E,k,!t.ctrlKey);if(u!==P){var M=dc(e,P),A=A3(t,i,u),O=C||_===0||h||y,F=d&&O,V=cg(e,A.x,A.y,P,M,F),J=V.x,G=V.y;e.previousWheelEvent=t,e.setTransformState(P,J,G),Nt(St(e),t,r),Nt(St(e),t,o)}},nq=function(e,t){var n=e.props,r=n.onWheelStop,o=n.onZoomStop;j1(e.wheelAnimationTimer),e.wheelAnimationTimer=setTimeout(function(){e.mounted&&(C3(e,t.x,t.y),e.wheelAnimationTimer=null)},JZ);var i=YZ(e,t);i&&(j1(e.wheelStopEventTimer),e.wheelStopEventTimer=setTimeout(function(){e.mounted&&(e.wheelStopEventTimer=null,Nt(St(e),t,r),Nt(St(e),t,o))},QZ))},rq=function(e,t){var n=O3(t);e.pinchStartDistance=n,e.lastDistance=n,e.pinchStartScale=e.transformState.scale,e.isPanning=!1,Do(e)},oq=function(e,t){var n=e.contentComponent,r=e.pinchStartDistance,o=e.transformState.scale,i=e.setup,s=i.limitToBounds,l=i.centerZoomedOut,u=i.zoomAnimation,d=u.disabled,h=u.size;if(!(r===null||!n)){var m=ZZ(t,o,n);if(!(!Number.isFinite(m.x)||!Number.isFinite(m.y))){var g=O3(t),y=qZ(e,g);if(y!==o){var x=dc(e,y),_=d||h===0||l,C=s&&_,S=cg(e,m.x,m.y,y,x,C),b=S.x,E=S.y;e.pinchMidpoint=m,e.lastDistance=g,e.setTransformState(y,b,E)}}}},iq=function(e){var t=e.pinchMidpoint;e.velocity=null,e.lastDistance=null,e.pinchMidpoint=null,e.pinchStartScale=null,e.pinchStartDistance=null,C3(e,t==null?void 0:t.x,t==null?void 0:t.y)},M3=function(e,t){var n=e.props.onZoomStop,r=e.setup.doubleClick.animationTime;j1(e.doubleClickStopEventTimer),e.doubleClickStopEventTimer=setTimeout(function(){e.doubleClickStopEventTimer=null,Nt(St(e),t,n)},r)},sq=function(e,t){var n=e.props,r=n.onZoomStart,o=n.onZoom,i=e.setup.doubleClick,s=i.animationTime,l=i.animationType;Nt(St(e),t,r),T3(e,s,l,function(){return Nt(St(e),t,o)}),M3(e,t)};function aq(e,t){var n=e.setup,r=e.doubleClickStopEventTimer,o=e.transformState,i=e.contentComponent,s=o.scale,l=e.props,u=l.onZoomStart,d=l.onZoom,h=n.doubleClick,m=h.disabled,g=h.mode,y=h.step,x=h.animationTime,_=h.animationType;if(!m&&!r){if(g==="reset")return sq(e,t);if(!i)return console.error("No ContentComponent found");var C=g==="zoomOut"?-1:1,S=k3(e,C,y);if(s!==S){Nt(St(e),t,u);var b=A3(t,i,s),E=Zx(e,S,b.x,b.y);if(!E)return console.error("Error during zoom event. New transformation state was not calculated.");Nt(St(e),t,d),Ls(e,E,x,_),M3(e,t)}}}var lq=function(e,t){var n=e.isInitialized,r=e.setup,o=e.wrapperComponent,i=r.doubleClick,s=i.disabled,l=i.excluded,u=t.target,d=o==null?void 0:o.contains(u),h=n&&u&&d&&!s;if(!h)return!1;var m=ug(u,l);return!m},cq=function(){function e(t){var n=this;this.mounted=!0,this.onChangeCallbacks=new Set,this.onInitCallbacks=new Set,this.wrapperComponent=null,this.contentComponent=null,this.isInitialized=!1,this.bounds=null,this.previousWheelEvent=null,this.wheelStopEventTimer=null,this.wheelAnimationTimer=null,this.isPanning=!1,this.startCoords=null,this.lastTouch=null,this.distance=null,this.lastDistance=null,this.pinchStartDistance=null,this.pinchStartScale=null,this.pinchMidpoint=null,this.doubleClickStopEventTimer=null,this.velocity=null,this.velocityTime=null,this.lastMousePosition=null,this.animate=!1,this.animation=null,this.maxBounds=null,this.pressedKeys={},this.mount=function(){n.initializeWindowEvents()},this.unmount=function(){n.cleanupWindowEvents()},this.update=function(r){dc(n,n.transformState.scale),n.setup=j2(r)},this.initializeWindowEvents=function(){var r,o=I0(),i=(r=n.wrapperComponent)===null||r===void 0?void 0:r.ownerDocument,s=i==null?void 0:i.defaultView;s==null||s.addEventListener("mousedown",n.onPanningStart,o),s==null||s.addEventListener("mousemove",n.onPanning,o),s==null||s.addEventListener("mouseup",n.onPanningStop,o),i==null||i.addEventListener("mouseleave",n.clearPanning,o),s==null||s.addEventListener("keyup",n.setKeyUnPressed,o),s==null||s.addEventListener("keydown",n.setKeyPressed,o)},this.cleanupWindowEvents=function(){var r,o,i=I0(),s=(r=n.wrapperComponent)===null||r===void 0?void 0:r.ownerDocument,l=s==null?void 0:s.defaultView;l==null||l.removeEventListener("mousedown",n.onPanningStart,i),l==null||l.removeEventListener("mousemove",n.onPanning,i),l==null||l.removeEventListener("mouseup",n.onPanningStop,i),s==null||s.removeEventListener("mouseleave",n.clearPanning,i),l==null||l.removeEventListener("keyup",n.setKeyUnPressed,i),l==null||l.removeEventListener("keydown",n.setKeyPressed,i),document.removeEventListener("mouseleave",n.clearPanning,i),Do(n),(o=n.observer)===null||o===void 0||o.disconnect()},this.handleInitializeWrapperEvents=function(r){var o=I0();r.addEventListener("wheel",n.onWheelZoom,o),r.addEventListener("dblclick",n.onDoubleClick,o),r.addEventListener("touchstart",n.onTouchPanningStart,o),r.addEventListener("touchmove",n.onTouchPanning,o),r.addEventListener("touchend",n.onTouchPanningStop,o)},this.handleInitialize=function(r){var o=n.setup.centerOnInit;n.applyTransformation(),n.onInitCallbacks.forEach(function(i){return i(St(n))}),o&&(n.setCenter(),n.observer=new ResizeObserver(function(){var i;n.onInitCallbacks.forEach(function(s){return s(St(n))}),n.setCenter(),(i=n.observer)===null||i===void 0||i.disconnect()}),n.observer.observe(r))},this.onWheelZoom=function(r){var o=n.setup.disabled;if(!o){var i=VZ(n,r);if(i){var s=n.isPressingKeys(n.setup.wheel.activationKeys);s&&(eq(n,r),tq(n,r),nq(n,r))}}},this.onPanningStart=function(r){var o=n.setup.disabled,i=n.props.onPanningStart;if(!o){var s=M2(n,r);if(s){var l=n.isPressingKeys(n.setup.panning.activationKeys);l&&(r.button===0&&!n.setup.panning.allowLeftClickPan||r.button===1&&!n.setup.panning.allowMiddleClickPan||r.button===2&&!n.setup.panning.allowRightClickPan||(r.preventDefault(),r.stopPropagation(),Do(n),I2(n,r),Nt(St(n),r,i)))}}},this.onPanning=function(r){var o=n.setup.disabled,i=n.props.onPanning;if(!o){var s=N2(n);if(s){var l=n.isPressingKeys(n.setup.panning.activationKeys);l&&(r.preventDefault(),r.stopPropagation(),L2(n,r.clientX,r.clientY),Nt(St(n),r,i))}}},this.onPanningStop=function(r){var o=n.props.onPanningStop;n.isPanning&&(AZ(n),Nt(St(n),r,o))},this.onPinchStart=function(r){var o=n.setup.disabled,i=n.props,s=i.onPinchingStart,l=i.onZoomStart;if(!o){var u=GZ(n,r);u&&(rq(n,r),Do(n),Nt(St(n),r,s),Nt(St(n),r,l))}},this.onPinch=function(r){var o=n.setup.disabled,i=n.props,s=i.onPinching,l=i.onZoom;if(!o){var u=XZ(n);u&&(r.preventDefault(),r.stopPropagation(),oq(n,r),Nt(St(n),r,s),Nt(St(n),r,l))}},this.onPinchStop=function(r){var o=n.props,i=o.onPinchingStop,s=o.onZoomStop;n.pinchStartScale&&(iq(n),Nt(St(n),r,i),Nt(St(n),r,s))},this.onTouchPanningStart=function(r){var o=n.setup.disabled,i=n.props.onPanningStart;if(!o){var s=M2(n,r);if(s){var l=n.lastTouch&&+new Date-n.lastTouch<200;if(l&&r.touches.length===1)n.onDoubleClick(r);else{n.lastTouch=+new Date,Do(n);var u=r.touches,d=u.length===1,h=u.length===2;d&&(Do(n),I2(n,r),Nt(St(n),r,i)),h&&n.onPinchStart(r)}}}},this.onTouchPanning=function(r){var o=n.setup.disabled,i=n.props.onPanning;if(n.isPanning&&r.touches.length===1){if(o)return;var s=N2(n);if(!s)return;r.preventDefault(),r.stopPropagation();var l=r.touches[0];L2(n,l.clientX,l.clientY),Nt(St(n),r,i)}else r.touches.length>1&&n.onPinch(r)},this.onTouchPanningStop=function(r){n.onPanningStop(r),n.onPinchStop(r)},this.onDoubleClick=function(r){var o=n.setup.disabled;if(!o){var i=lq(n,r);i&&aq(n,r)}},this.clearPanning=function(r){n.isPanning&&n.onPanningStop(r)},this.setKeyPressed=function(r){n.pressedKeys[r.key]=!0},this.setKeyUnPressed=function(r){n.pressedKeys[r.key]=!1},this.isPressingKeys=function(r){return r.length?!!r.find(function(o){return n.pressedKeys[o]}):!0},this.setTransformState=function(r,o,i){var s=n.props.onTransformed;if(!Number.isNaN(r)&&!Number.isNaN(o)&&!Number.isNaN(i)){r!==n.transformState.scale&&(n.transformState.previousScale=n.transformState.scale,n.transformState.scale=r),n.transformState.positionX=o,n.transformState.positionY=i,n.applyTransformation();var l=St(n);n.onChangeCallbacks.forEach(function(u){return u(l)}),Nt(l,{scale:r,positionX:o,positionY:i},s)}else console.error("Detected NaN set state values")},this.setCenter=function(){if(n.wrapperComponent&&n.contentComponent){var r=P3(n.transformState.scale,n.wrapperComponent,n.contentComponent);n.setTransformState(r.scale,r.positionX,r.positionY)}},this.handleTransformStyles=function(r,o,i){return n.props.customTransform?n.props.customTransform(r,o,i):BZ(r,o,i)},this.applyTransformation=function(){if(!(!n.mounted||!n.contentComponent)){var r=n.transformState,o=r.scale,i=r.positionX,s=r.positionY,l=n.handleTransformStyles(i,s,o);n.contentComponent.style.transform=l}},this.getContext=function(){return St(n)},this.onChange=function(r){return n.onChangeCallbacks.has(r)||n.onChangeCallbacks.add(r),function(){n.onChangeCallbacks.delete(r)}},this.onInit=function(r){return n.onInitCallbacks.has(r)||n.onInitCallbacks.add(r),function(){n.onInitCallbacks.delete(r)}},this.init=function(r,o){n.cleanupWindowEvents(),n.wrapperComponent=r,n.contentComponent=o,dc(n,n.transformState.scale),n.handleInitializeWrapperEvents(r),n.handleInitialize(o),n.initializeWindowEvents(),n.isInitialized=!0;var i=St(n);Nt(i,void 0,n.props.onInit)},this.props=t,this.setup=j2(this.props),this.transformState=$3(this.props)}return e}(),qx=Fe.createContext(null),uq=function(e,t){return typeof e=="function"?e(t):e},dq=Fe.forwardRef(function(e,t){var n=f.useRef(new cq(e)).current,r=uq(e.children,F1(n));return f.useImperativeHandle(t,function(){return F1(n)},[n]),f.useEffect(function(){n.update(e)},[n,e]),Fe.createElement(qx.Provider,{value:n},r)});Fe.forwardRef(function(e,t){var n=f.useRef(null),r=f.useContext(qx);return f.useEffect(function(){return r.onChange(function(o){if(n.current){var i=0,s=0;n.current.style.transform=r.handleTransformStyles(i,s,1/o.instance.transformState.scale)}})},[r]),Fe.createElement("div",_s({},e,{ref:UZ([n,t])}))});function fq(e,t){t===void 0&&(t={});var n=t.insertAt;if(!(!e||typeof document>"u")){var r=document.head||document.getElementsByTagName("head")[0],o=document.createElement("style");o.type="text/css",n==="top"&&r.firstChild?r.insertBefore(o,r.firstChild):r.appendChild(o),o.styleSheet?o.styleSheet.cssText=e:o.appendChild(document.createTextNode(e))}}var pq=`.transform-component-module_wrapper__SPB86 { + position: relative; + width: -moz-fit-content; + width: fit-content; + height: -moz-fit-content; + height: fit-content; + overflow: hidden; + -webkit-touch-callout: none; /* iOS Safari */ + -webkit-user-select: none; /* Safari */ + -khtml-user-select: none; /* Konqueror HTML */ + -moz-user-select: none; /* Firefox */ + -ms-user-select: none; /* Internet Explorer/Edge */ + user-select: none; + margin: 0; + padding: 0; +} +.transform-component-module_content__FBWxo { + display: flex; + flex-wrap: wrap; + width: -moz-fit-content; + width: fit-content; + height: -moz-fit-content; + height: fit-content; + margin: 0; + padding: 0; + transform-origin: 0% 0%; +} +.transform-component-module_content__FBWxo img { + pointer-events: none; +} +`,z2={wrapper:"transform-component-module_wrapper__SPB86",content:"transform-component-module_content__FBWxo"};fq(pq);var hq=function(e){var t=e.children,n=e.wrapperClass,r=n===void 0?"":n,o=e.contentClass,i=o===void 0?"":o,s=e.wrapperStyle,l=e.contentStyle,u=e.wrapperProps,d=u===void 0?{}:u,h=e.contentProps,m=h===void 0?{}:h,g=f.useContext(qx),y=g.init,x=g.cleanupWindowEvents,_=f.useRef(null),C=f.useRef(null);return f.useEffect(function(){var S=_.current,b=C.current;return S!==null&&b!==null&&y&&(y==null||y(S,b)),function(){x==null||x()}},[]),Fe.createElement("div",_s({},d,{ref:_,className:"react-transform-wrapper ".concat(z2.wrapper," ").concat(r),style:s}),Fe.createElement("div",_s({},m,{ref:C,className:"react-transform-component ".concat(z2.content," ").concat(i),style:l}),t))};const N3=["PageUp","PageDown"],D3=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],I3={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},Wd="Slider",[z1,mq,gq]=zd(Wd),[L3,Ete]=An(Wd,[gq]),[vq,dg]=L3(Wd),yq=f.forwardRef((e,t)=>{const{name:n,min:r=0,max:o=100,step:i=1,orientation:s="horizontal",disabled:l=!1,minStepsBetweenThumbs:u=0,defaultValue:d=[r],value:h,onValueChange:m=()=>{},onValueCommit:g=()=>{},inverted:y=!1,...x}=e,[_,C]=f.useState(null),S=Be(t,U=>C(U)),b=f.useRef(new Set),E=f.useRef(0),k=s==="horizontal",P=_?!!_.closest("form"):!0,M=k?wq:xq,[A=[],O]=Zr({prop:h,defaultProp:d,onChange:U=>{var te;(te=[...b.current][E.current])===null||te===void 0||te.focus(),m(U)}}),F=f.useRef(A);function V(U){const te=Tq(A,U);ae(U,te)}function J(U){ae(U,E.current)}function G(){const U=F.current[E.current];A[E.current]!==U&&g(A)}function ae(U,te,{commit:L}={commit:!1}){const ie=Mq(i),K=Nq(Math.round((U-r)/i)*i+r,ie),Q=id(K,[r,o]);O((W=[])=>{const le=kq(W,Q,te);if(Oq(le,u*i)){E.current=le.indexOf(Q);const ge=String(le)!==String(W);return ge&&L&&g(le),ge?le:W}else return W})}return f.createElement(vq,{scope:e.__scopeSlider,disabled:l,min:r,max:o,valueIndexToChangeRef:E,thumbs:b.current,values:A,orientation:s},f.createElement(z1.Provider,{scope:e.__scopeSlider},f.createElement(z1.Slot,{scope:e.__scopeSlider},f.createElement(M,Y({"aria-disabled":l,"data-disabled":l?"":void 0},x,{ref:S,onPointerDown:ue(x.onPointerDown,()=>{l||(F.current=A)}),min:r,max:o,inverted:y,onSlideStart:l?void 0:V,onSlideMove:l?void 0:J,onSlideEnd:l?void 0:G,onHomeKeyDown:()=>!l&&ae(r,0,{commit:!0}),onEndKeyDown:()=>!l&&ae(o,A.length-1,{commit:!0}),onStepKeyDown:({event:U,direction:te})=>{if(!l){const K=N3.includes(U.key)||U.shiftKey&&D3.includes(U.key)?10:1,Q=E.current,W=A[Q],le=i*K*te;ae(W+le,Q,{commit:!0})}}})))),P&&A.map((U,te)=>f.createElement($q,{key:te,name:n?n+(A.length>1?"[]":""):void 0,value:U})))}),[F3,j3]=L3(Wd,{startEdge:"left",endEdge:"right",size:"width",direction:1}),wq=f.forwardRef((e,t)=>{const{min:n,max:r,dir:o,inverted:i,onSlideStart:s,onSlideMove:l,onSlideEnd:u,onStepKeyDown:d,...h}=e,[m,g]=f.useState(null),y=Be(t,E=>g(E)),x=f.useRef(),_=Sc(o),C=_==="ltr",S=C&&!i||!C&&i;function b(E){const k=x.current||m.getBoundingClientRect(),P=[0,k.width],A=Qx(P,S?[n,r]:[r,n]);return x.current=k,A(E-k.left)}return f.createElement(F3,{scope:e.__scopeSlider,startEdge:S?"left":"right",endEdge:S?"right":"left",direction:S?1:-1,size:"width"},f.createElement(z3,Y({dir:_,"data-orientation":"horizontal"},h,{ref:y,style:{...h.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:E=>{const k=b(E.clientX);s==null||s(k)},onSlideMove:E=>{const k=b(E.clientX);l==null||l(k)},onSlideEnd:()=>{x.current=void 0,u==null||u()},onStepKeyDown:E=>{const P=I3[S?"from-left":"from-right"].includes(E.key);d==null||d({event:E,direction:P?-1:1})}})))}),xq=f.forwardRef((e,t)=>{const{min:n,max:r,inverted:o,onSlideStart:i,onSlideMove:s,onSlideEnd:l,onStepKeyDown:u,...d}=e,h=f.useRef(null),m=Be(t,h),g=f.useRef(),y=!o;function x(_){const C=g.current||h.current.getBoundingClientRect(),S=[0,C.height],E=Qx(S,y?[r,n]:[n,r]);return g.current=C,E(_-C.top)}return f.createElement(F3,{scope:e.__scopeSlider,startEdge:y?"bottom":"top",endEdge:y?"top":"bottom",size:"height",direction:y?1:-1},f.createElement(z3,Y({"data-orientation":"vertical"},d,{ref:m,style:{...d.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:_=>{const C=x(_.clientY);i==null||i(C)},onSlideMove:_=>{const C=x(_.clientY);s==null||s(C)},onSlideEnd:()=>{g.current=void 0,l==null||l()},onStepKeyDown:_=>{const S=I3[y?"from-bottom":"from-top"].includes(_.key);u==null||u({event:_,direction:S?-1:1})}})))}),z3=f.forwardRef((e,t)=>{const{__scopeSlider:n,onSlideStart:r,onSlideMove:o,onSlideEnd:i,onHomeKeyDown:s,onEndKeyDown:l,onStepKeyDown:u,...d}=e,h=dg(Wd,n);return f.createElement(Pe.span,Y({},d,{ref:t,onKeyDown:ue(e.onKeyDown,m=>{m.key==="Home"?(s(m),m.preventDefault()):m.key==="End"?(l(m),m.preventDefault()):N3.concat(D3).includes(m.key)&&(u(m),m.preventDefault())}),onPointerDown:ue(e.onPointerDown,m=>{const g=m.target;g.setPointerCapture(m.pointerId),m.preventDefault(),h.thumbs.has(g)?g.focus():r(m)}),onPointerMove:ue(e.onPointerMove,m=>{m.target.hasPointerCapture(m.pointerId)&&o(m)}),onPointerUp:ue(e.onPointerUp,m=>{const g=m.target;g.hasPointerCapture(m.pointerId)&&(g.releasePointerCapture(m.pointerId),i(m))})}))}),bq="SliderTrack",_q=f.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,o=dg(bq,n);return f.createElement(Pe.span,Y({"data-disabled":o.disabled?"":void 0,"data-orientation":o.orientation},r,{ref:t}))}),B2="SliderRange",Sq=f.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,o=dg(B2,n),i=j3(B2,n),s=f.useRef(null),l=Be(t,s),u=o.values.length,d=o.values.map(g=>B3(g,o.min,o.max)),h=u>1?Math.min(...d):0,m=100-Math.max(...d);return f.createElement(Pe.span,Y({"data-orientation":o.orientation,"data-disabled":o.disabled?"":void 0},r,{ref:l,style:{...e.style,[i.startEdge]:h+"%",[i.endEdge]:m+"%"}}))}),U2="SliderThumb",Eq=f.forwardRef((e,t)=>{const n=mq(e.__scopeSlider),[r,o]=f.useState(null),i=Be(t,l=>o(l)),s=f.useMemo(()=>r?n().findIndex(l=>l.ref.current===r):-1,[n,r]);return f.createElement(Cq,Y({},e,{ref:i,index:s}))}),Cq=f.forwardRef((e,t)=>{const{__scopeSlider:n,index:r,...o}=e,i=dg(U2,n),s=j3(U2,n),[l,u]=f.useState(null),d=Be(t,C=>u(C)),h=gx(l),m=i.values[r],g=m===void 0?0:B3(m,i.min,i.max),y=Rq(r,i.values.length),x=h==null?void 0:h[s.size],_=x?Pq(x,g,s.direction):0;return f.useEffect(()=>{if(l)return i.thumbs.add(l),()=>{i.thumbs.delete(l)}},[l,i.thumbs]),f.createElement("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[s.startEdge]:`calc(${g}% + ${_}px)`}},f.createElement(z1.ItemSlot,{scope:e.__scopeSlider},f.createElement(Pe.span,Y({role:"slider","aria-label":e["aria-label"]||y,"aria-valuemin":i.min,"aria-valuenow":m,"aria-valuemax":i.max,"aria-orientation":i.orientation,"data-orientation":i.orientation,"data-disabled":i.disabled?"":void 0,tabIndex:i.disabled?void 0:0},o,{ref:d,style:m===void 0?{display:"none"}:e.style,onFocus:ue(e.onFocus,()=>{i.valueIndexToChangeRef.current=r})}))))}),$q=e=>{const{value:t,...n}=e,r=f.useRef(null),o=Fx(t);return f.useEffect(()=>{const i=r.current,s=window.HTMLInputElement.prototype,u=Object.getOwnPropertyDescriptor(s,"value").set;if(o!==t&&u){const d=new Event("input",{bubbles:!0});u.call(i,t),i.dispatchEvent(d)}},[o,t]),f.createElement("input",Y({style:{display:"none"}},n,{ref:r,defaultValue:t}))};function kq(e=[],t,n){const r=[...e];return r[n]=t,r.sort((o,i)=>o-i)}function B3(e,t,n){const i=100/(n-t)*(e-t);return id(i,[0,100])}function Rq(e,t){return t>2?`Value ${e+1} of ${t}`:t===2?["Minimum","Maximum"][e]:void 0}function Tq(e,t){if(e.length===1)return 0;const n=e.map(o=>Math.abs(o-t)),r=Math.min(...n);return n.indexOf(r)}function Pq(e,t,n){const r=e/2,i=Qx([0,50],[0,r]);return(r-i(t)*n)*n}function Aq(e){return e.slice(0,-1).map((t,n)=>e[n+1]-t)}function Oq(e,t){if(t>0){const n=Aq(e);return Math.min(...n)>=t}return!0}function Qx(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 Mq(e){return(String(e).split(".")[1]||"").length}function Nq(e,t){const n=Math.pow(10,t);return Math.round(e*n)/n}const U3=yq,Dq=_q,Iq=Sq,Lq=Eq,uo=f.forwardRef(({className:e,...t},n)=>v.jsxs(U3,{ref:n,className:Ce("relative flex w-full touch-none select-none items-center",e),tabIndex:-1,...t,children:[v.jsx(Dq,{className:"relative h-1.5 w-full grow overflow-hidden rounded-full bg-primary/20 data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50",children:v.jsx(Iq,{className:"absolute h-full bg-primary data-[disabled]:cursor-not-allowed "})}),v.jsx(Lq,{tabIndex:-1,className:"block h-4 w-4 rounded-full border border-primary/60 bg-background shadow transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring data-[disabled]:cursor-not-allowed"})]}));uo.displayName=U3.displayName;const tl={capture:!0,passive:!1},Fq=2,V2=(e,t,n,r,o,i)=>{if(e!==n&&t===r){if(e<0)return[0,r];if(e+t>i)return[i-r,r]}else{if(ti)return[e,i-e]}return[e,t]},jq=e=>{const{minHeight:t,minWidth:n,maxHeight:r,maxWidth:o,scale:i,show:s}=e,[l,u,d,h,{x:m,y:g,width:y,height:x},_,C,S,b,E,k]=bt(W=>[W.imageWidth,W.imageHeight,W.isInpainting,W.isSD(),W.cropperState,W.setCropperX,W.setCropperY,W.setCropperWidth,W.setCropperHeight,W.isCropperExtenderResizing,W.setIsCropperExtenderResizing]),[P,M]=f.useState(!1);f.useEffect(()=>{_(Math.round((o-512)/2)),C(Math.round((r-512)/2))},[r,o,l,u]);const[A,O]=f.useState({initX:0,initY:0,initHeight:0,initWidth:0,startResizeX:0,startResizeY:0,ord:"top"}),F=()=>{},V=(W,le)=>V2(W,le,m,y,n,o),J=(W,le)=>V2(W,le,g,x,t,r),G=W=>{if(d)return;const le=W.clientX,ge=W.clientY,Ve=Math.round((ge-A.startResizeY)/i),Ue=Math.round((le-A.startResizeX)/i),We=()=>{const $e=A.initHeight-Ve,Ae=A.initY+Ve,[Oe,je]=J(Ae,$e);b(je),C(Oe)},Me=()=>{const $e=A.initHeight+Ve,[Ae,Oe]=J(A.initY,$e);b(Oe),C(Ae)},fe=()=>{const $e=A.initWidth-Ue,Ae=A.initX+Ue,[Oe,je]=V(Ae,$e);S(je),_(Oe)},xe=()=>{const $e=A.initWidth+Ue,[Ae,Oe]=V(A.initX,$e);S(Oe),_(Ae)};if(E)switch(A.ord){case"topleft":{We(),fe();break}case"topright":{We(),xe();break}case"bottomleft":{Me(),fe();break}case"bottomright":{Me(),xe();break}case"top":{We();break}case"right":{xe();break}case"bottom":{Me();break}case"left":{fe();break}}if(P){const $e=A.initX+Ue,Ae=A.initY+Ve,[Oe,je]=V($e,A.initWidth),[Ot,ct]=J(Ae,A.initHeight);S(je),b(ct),_(Oe),C(Ot)}},ae=()=>{E&&k(!1),P&&M(!1)};f.useEffect(()=>{if(E||P)return document.addEventListener("pointermove",G,tl),document.addEventListener("pointerup",ae,tl),document.addEventListener("pointercancel",ae,tl),()=>{document.removeEventListener("pointermove",G,tl),document.removeEventListener("pointerup",ae,tl),document.removeEventListener("pointercancel",ae,tl)}},[E,P,y,x,A]);const U=W=>{const{ord:le}=W.target.dataset;le&&(k(!0),O({initX:m,initY:g,initHeight:x,initWidth:y,startResizeX:W.clientX,startResizeY:W.clientY,ord:le}))},te=(W,le,ge)=>{const We="w-[12px] h-[12px] z-[4] absolute content-[''] block border-2 border-primary borde pointer-events-auto hover:bg-primary";let Me="0",fe="0",xe=ge,$e="-6px";return ge===""&&($e="50%",le==="left"||le==="right"?(xe="top",fe="-50%"):(xe="left",Me="-50%")),v.jsx("div",{className:Ce(We,W),style:{[le]:-6,[xe]:$e,transform:`translate(${Me}, ${fe}) scale(${1/i})`},"data-ord":le+ge,"aria-label":le+ge,tabIndex:-1,role:"button"})},L=()=>v.jsxs("div",{onFocus:F,onPointerDown:U,className:"absolute top-0 h-full w-full",children:[v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 w-full cursor-ns-resize h-[12px] mt-[-6px]","data-ord":"top"}),v.jsx("div",{className:"absolute pointer-events-auto top-0 right-0 h-full cursor-ew-resize w-[12px] mr-[-6px]","data-ord":"right"}),v.jsx("div",{className:"absolute pointer-events-auto bottom-0 left-0 w-full cursor-ns-resize h-[12px] mb-[-6px]","data-ord":"bottom"}),v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 h-full cursor-ew-resize w-[12px] ml-[-6px]","data-ord":"left"}),te("cursor-nw-resize","top","left"),te("cursor-ne-resize","top","right"),te("cursor-sw-resize","bottom","left"),te("cursor-se-resize","bottom","right"),te("cursor-ns-resize","top",""),te("cursor-ns-resize","bottom",""),te("cursor-ew-resize","left",""),te("cursor-ew-resize","right","")]}),ie=W=>{M(!0),O({initX:m,initY:g,initHeight:x,initWidth:y,startResizeX:W.clientX,startResizeY:W.clientY,ord:""})},K=()=>v.jsxs("div",{className:Jw("border absolute pointer-events-auto px-2 py-1 rounded-full hover:cursor-move bg-background","origin-top-left top-0 left-0"),style:{transform:`scale(${1/i*.8})`},onPointerDown:ie,children:[y," x ",x]}),Q=()=>v.jsx("div",{className:"outline-dashed outline-primary",style:{height:x,width:y,outlineWidth:`${Fq/i*1.3}px`}});return s===!1||!h?null:v.jsx("div",{className:"absolute h-full w-full overflow-hidden pointer-events-none z-[2]",children:v.jsxs("div",{className:"relative pointer-events-none z-[2] [box-shadow:0_0_0_9999px_rgba(0,_0,_0,_0.5)]",style:{height:x,width:y,left:m,top:g},children:[Q(),K(),L()]})})},zq=()=>{const[e,t,n]=bt(r=>[r.interactiveSegState,r.resetInteractiveSegState,r.handleInteractiveSegAccept]);return e.isInteractiveSeg?v.jsxs("div",{className:"z-10 absolute top-[68px] rounded-xl border-solid border p-[8px] left-1/2 translate-x-[-50%] flex justify-center items-center gap-[8px] bg-background",children:[v.jsx(yn,{onClick:()=>{t()},size:"sm",variant:"secondary",children:"Cancel"}),v.jsx(yn,{size:"sm",onClick:()=>{n()},children:"Accept"})]}):null},Bq=e=>{const{x:t,y:n,positive:r}=e,o=r?"bg-[rgba(21,_215,_121,_0.936)] outline-[rgba(98,255,179,0.31)]":"bg-[rgba(237,_49,_55,_0.942)] outline-[rgba(255,89,95,0.31)]";return v.jsx("div",{className:`absolute h-[10px] w-[10px] rounded-[50%] ${o} outline-8 outline`,style:{left:t,top:n,transform:"translate(-50%, -50%)"}})},Uq=()=>{const e=bt(t=>t.interactiveSegState.clicks);return v.jsx("div",{className:"absolute h-full w-full overflow-hidden pointer-events-none",children:e.map(t=>v.jsx(Bq,{x:t[0],y:t[1],positive:t[2]===1},t[3]))})},Vq=()=>v.jsx("div",{children:v.jsx(zq,{})}),nl={capture:!0,passive:!1},Wq=2,W2=(e,t,n,r)=>t{const{minHeight:t,minWidth:n,scale:r,show:o}=e,[i,s,l,u,{x:d,y:h,width:m,height:g},y,x,_,C,S,b,E]=bt(ie=>[ie.isInpainting,ie.imageHeight,ie.imageWidth,ie.isSD(),ie.extenderState,ie.setExtenderX,ie.setExtenderY,ie.setExtenderWidth,ie.setExtenderHeight,ie.settings.extenderDirection,ie.isCropperExtenderResizing,ie.setIsCropperExtenderResizing]),[k,P]=f.useState({initX:0,initY:0,initHeight:0,initWidth:0,startResizeX:0,startResizeY:0,ord:"top"}),M=()=>{},A=(ie,K)=>W2(ie,K,d,n),O=(ie,K)=>W2(ie,K,h,t),F=ie=>{if(i)return;const K=ie.clientX,Q=ie.clientY,W=Math.round((Q-k.startResizeY)/r),le=Math.round((K-k.startResizeX)/r),ge=()=>{const Me=k.initHeight-W,fe=k.initY+W;let xe=fe,$e=Me;if(S===In.xy)xe>0&&(xe=0,$e=k.initHeight-Math.abs(k.initY));else{const Ae=O(fe,Me);xe=Ae[0],$e=Ae[1]}C($e),x(xe)},Ve=()=>{const Me=k.initHeight+W;let[fe,xe]=O(k.initY,Me);S===In.xy&&xe{const Me=k.initWidth-le,fe=k.initX+le;let xe=fe,$e=Me;if(S===In.xy)xe>0&&(xe=0,$e=k.initWidth-Math.abs(k.initX));else{const Ae=A(fe,Me);xe=Ae[0],$e=Ae[1]}_($e),y(xe)},We=()=>{const Me=k.initWidth+le;let[fe,xe]=A(k.initX,Me);S===In.xy&&xe{b&&E(!1)};f.useEffect(()=>{if(b)return document.addEventListener("pointermove",F,nl),document.addEventListener("pointerup",V,nl),document.addEventListener("pointercancel",V,nl),()=>{document.removeEventListener("pointermove",F,nl),document.removeEventListener("pointerup",V,nl),document.removeEventListener("pointercancel",V,nl)}},[b,m,g,k]);const J=ie=>{const{ord:K}=ie.target.dataset;K&&(E(!0),P({initX:d,initY:h,initHeight:g,initWidth:m,startResizeX:ie.clientX,startResizeY:ie.clientY,ord:K}))},G=(ie,K,Q)=>{const ge="w-[12px] h-[12px] z-[4] absolute content-[''] block border-2 border-primary borde pointer-events-auto hover:bg-primary";let Ve="0",Ue="0",We=Q,Me="-6px";return Q===""&&(Me="50%",K==="left"||K==="right"?(We="top",Ue="-50%"):(We="left",Ve="-50%")),v.jsx("div",{className:Ce(ge,ie),style:{[K]:-6,[We]:Me,transform:`translate(${Ve}, ${Ue}) scale(${1/r})`},"data-ord":K+Q,"aria-label":K+Q,tabIndex:-1,role:"button"})},ae=()=>v.jsxs("div",{onFocus:M,onPointerDown:J,className:"absolute top-0 h-full w-full",children:[[In.y,In.xy].includes(S)?v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 w-full cursor-ns-resize h-[12px] mt-[-6px]","data-ord":"top"}),v.jsx("div",{className:"absolute pointer-events-auto bottom-0 left-0 w-full cursor-ns-resize h-[12px] mb-[-6px]","data-ord":"bottom"}),G("cursor-ns-resize","top",""),G("cursor-ns-resize","bottom","")]}):v.jsx(v.Fragment,{}),[In.x,In.xy].includes(S)?v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"absolute pointer-events-auto top-0 right-0 h-full cursor-ew-resize w-[12px] mr-[-6px]","data-ord":"right"}),v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 h-full cursor-ew-resize w-[12px] ml-[-6px]","data-ord":"left"}),G("cursor-ew-resize","left",""),G("cursor-ew-resize","right","")]}):v.jsx(v.Fragment,{}),S===In.xy?v.jsxs(v.Fragment,{children:[G("cursor-nw-resize","top","left"),G("cursor-ne-resize","top","right"),G("cursor-sw-resize","bottom","left"),G("cursor-se-resize","bottom","right")]}):v.jsx(v.Fragment,{})]}),U=ie=>{P({initX:d,initY:h,initHeight:g,initWidth:m,startResizeX:ie.clientX,startResizeY:ie.clientY,ord:""})},te=()=>v.jsxs("div",{className:Jw("border absolute pointer-events-auto px-2 py-1 rounded-full bg-background","origin-top-left top-0 left-0"),style:{transform:`scale(${1/r*.8})`},onPointerDown:U,children:[m," x ",g]}),L=()=>v.jsx("div",{className:Ce("outline-dashed outline-primary"),style:{height:g,width:m,outlineWidth:`${Wq/r*1.3}px`}});return o===!1||!u?null:v.jsx("div",{className:"absolute h-full w-full pointer-events-none z-[2]",children:v.jsxs("div",{className:"relative pointer-events-none z-[2] [box-shadow:0_0_0_9999px_rgba(0,_0,_0,_0.5)]",style:{height:g,width:m,left:d,top:h},children:[L(),te(),ae()]})})},Kq=200,Yq=10,Gq=200,lu=300;function Xq(e){const{file:t}=e,{toast:n}=Td(),[r,o,i,s,l,u,d,h,m,g,y,x,_,C,S,b,E,k,P,M,A,O]=bt(H=>[H.disableShortCuts,H.windowSize,H.isInpainting,H.imageWidth,H.imageHeight,H.settings,H.serverConfig.enableAutoSaving,H.setImageSize,H.setBaseBrushSize,H.interactiveSegState,H.updateInteractiveSegState,H.handleCanvasMouseDown,H.handleCanvasMouseMove,H.undo,H.redo,H.undoDisabled(),H.redoDisabled(),H.getIsProcessing(),H.updateAppState,H.runMannually(),H.runInpainting,H.isCropperExtenderResizing]),F=bt(H=>H.editorState.baseBrushSize),V=bt(H=>H.getBrushSize()),J=bt(H=>H.editorState.renders),G=bt(H=>H.editorState.extraMasks),ae=bt(H=>H.editorState.temporaryMasks),U=bt(H=>H.editorState.lineGroups),te=bt(H=>H.editorState.curLineGroup),[L,ie]=f.useState(!1),[K,Q]=Rx(t),[W,le]=f.useState(),[ge,Ve]=f.useState(),[{x:Ue,y:We},Me]=f.useState({x:-1,y:-1}),[fe,xe]=f.useState(!1),[$e,Ae]=f.useState(!1),[Oe,je]=f.useState(!1),[Ot,ct]=f.useState(1),[Kt,Er]=f.useState(!1),[gt,js]=f.useState(1),I=o.width/2,X=o.height/2,Z=f.useRef(null),[we,he]=f.useState(!1),[de,ke]=f.useState(!1),[ft,pt]=f.useState(0),_n=f.useCallback(()=>te.length!==0,[te]);f.useEffect(()=>{if(!ge||!Q||s===0||l===0)return;const H=J.length===0?K:J[J.length-1];ge.canvas.width=s,ge.canvas.height=l,ge.clearRect(0,0,ge.canvas.width,ge.canvas.height),ge.drawImage(H,0,0,s,l)},[J,K,Q,ge,l,s]),f.useEffect(()=>{!W||!Q||s===0||l===0||(W.canvas.width=s,W.canvas.height=l,W.clearRect(0,0,W.canvas.width,W.canvas.height),ae.forEach(H=>{W.drawImage(H,0,0,s,l)}),G.forEach(H=>{W.drawImage(H,0,0,s,l)}),g.isInteractiveSeg&&g.tmpInteractiveSegMask&&W.drawImage(g.tmpInteractiveSegMask,0,0,s,l),GR(W,te))},[ae,G,Q,g,W,te,l,s]);const Cr=f.useCallback(async()=>{let H=t;if(J.length>0){const Ge=J[J.length-1];H=await ku(Ge.currentSrc,t.name,t.type)}return H},[t,J]),ki=()=>J.length!==0,_o=f.useCallback(()=>{let H=512,Ge=512;return Q?(J.length===0?(H=K.naturalWidth,Ge=K.naturalHeight):J.length!==0&&(H=J[J.length-1].width,Ge=J[J.length-1].height),[H,Ge]):[H,Ge]},[K,Q,J]);f.useEffect(()=>{var Gd;if(!Q)return;const[H,Ge]=_o();(H!==s||Ge!==l)&&h(H,Ge);const st=o.width/H,Qr=(o.height-Kq)/Ge;let an=1;(st<1||Qr<1)&&(an=Math.min(st,Qr)),js(an),ct(an),console.log(`[on file load] image size: ${H}x${Ge}, scale: ${an}, initialCentered: ${we}`),W!=null&&W.canvas&&(console.log("[on file load] set canvas size"),H!=W.canvas.width&&(W.canvas.width=H),Ge!=W.canvas.height&&(W.canvas.height=Ge)),we||((Gd=Z.current)==null||Gd.centerView(an,1),console.log("[on file load] centerView"),he(!0))},[Z,l,s,K,Q,o,we,_o]),f.useEffect(()=>{var H;console.log("[useEffect] centerView"),(H=Z==null?void 0:Z.current)==null||H.centerView(gt,1)},[l,s,Z,gt]);const Vn=f.useCallback(()=>{if(!gt||!o)return;const H=Z.current;if(!H)return;const Ge=(o.width-s*gt)/2,st=(o.height-l*gt)/2;H.setTransform(Ge,st,gt,200,"easeOutQuad"),H.instance.transformState.scale&&(H.instance.transformState.scale=gt),ct(gt),Er(!1)},[Z,o,l,s,o.height,gt]);f.useEffect(()=>(window.addEventListener("resize",()=>{Vn()}),()=>{window.removeEventListener("resize",()=>{Vn()})}),[o,Vn]),Zn("Escape",()=>{k||(de?ke(!1):Vn())},[de,i,Vn]);const Ri=H=>{const Ge=H.nativeEvent;Me({x:Ge.pageX,y:Ge.pageY})},zs=H=>{k||g.isInteractiveSeg||Oe||de&&te.length!==0&&_(c0(H))},Ti=async H=>{P({isPluginRunning:!0});const Ge=await Cr();try{const st=await gT(!0,jR.InteractiveSeg,Ge,void 0,H),{blob:Qr}=st,an=new Image;an.onload=()=>{y({tmpInteractiveSegMask:an})},an.src=Qr}catch(st){n({variant:"destructive",description:st.message?st.message:st.toString()})}P({isPluginRunning:!1})},$c=H=>{if(cC(H)){je(!1);return}!_n()||g.isInteractiveSeg||Oe||!K.src||!(W!=null&&W.canvas)||i||de&&(M?ke(!1):A())},yg=H=>{if(g.isInteractiveSeg){const Ge=c0(H),st=[...g.clicks];lC(H)?st.push([Ge.x,Ge.y,0,st.length]):st.push([Ge.x,Ge.y,1,st.length]),Ti(st),y({clicks:st})}},wg=H=>{if(!(k||g.isInteractiveSeg||Oe||!Q||!(W!=null&&W.canvas))&&!lC(H)){if(cC(H)){je(!0);return}ke(!0),x(c0(H))}},Kd=H=>{H.preventDefault(),C()};Zn("meta+z,ctrl+z",Kd);const kc=H=>{H.preventDefault(),S()};Zn("shift+ctrl+z,shift+meta+z",kc),o2("Tab",H=>{H==null||H.preventDefault(),H==null||H.stopPropagation(),ki()&&ie(()=>(window.setTimeout(()=>{pt(100)},10),!0))},H=>{H==null||H.preventDefault(),H==null||H.stopPropagation(),ki()&&(window.setTimeout(()=>{pt(0)},10),window.setTimeout(()=>{ie(!1)},lu))});const Rc=f.useCallback(async()=>{if(t===void 0)return;if(d&&J.length>0){try{await Wj(J[J.length-1],t.name,t.type),n({description:"Save image success"})}catch(st){n({variant:"destructive",title:"Uh oh! Something went wrong.",description:st.message?st.message:st.toString()})}return}const H=t.name.replace(/(\.[\w\d_-]+)$/i,"_cleanup$1"),Ge=J[J.length-1];if(yF(Ge.currentSrc,H),u.enableDownloadMask){let st=t.name.replace(/(\.[\w\d_-]+)$/i,"_mask$1");st=st.replace(/\.[^/.]+$/,".jpg");const Qr=Lp(s,l,U),an=document.createElement("a");an.download=st,an.href=Qr.toDataURL("image/jpeg"),an.click()}},[t,d,J,u,l,s,U]);Zn("meta+s,ctrl+s",Rc);const Tc=H=>{H!==fe&&!Oe&&!O&&xe(H)},xg=f.useCallback(()=>{if(k)return"default";if(Oe)return"grab";if(fe)return"none"},[fe,Oe,k]);Zn("[",()=>{let H=F;F>10&&(H=F-10),F<=10&&F>0&&(H=F-5),m(H)},[F]),Zn("]",()=>{m(F+10)},[F]),Zn("shift+r",()=>{M&&_n()&&A()},[M,A,_n]),Zn("ctrl+c,meta+c",async()=>{await hF()&&J.length>0&&W!=null&&W.canvas&&(await vF(W==null?void 0:W.canvas),n({title:"Copy inpainting result to clipboard"}))},[J,W]),o2(" ",H=>{r||(H==null||H.preventDefault(),H==null||H.stopPropagation(),xe(!1),je(!0))},H=>{r||(H==null||H.preventDefault(),H==null||H.stopPropagation(),xe(!0),je(!1))});const Pc=()=>{var Ge,st,Qr,an;let H=gt;return((st=(Ge=Z.current)==null?void 0:Ge.instance)==null?void 0:st.transformState.scale)!==void 0&&(H=(an=(Qr=Z.current)==null?void 0:Qr.instance)==null?void 0:an.transformState.scale),H},Yd=(H,Ge)=>{const st=Pc();return{width:`${V*st}px`,height:`${V*st}px`,left:`${H}px`,top:`${Ge}px`,transform:"translate(-50%, -50%)"}},Ac=H=>v.jsx("div",{className:"absolute rounded-[50%] border-[1px] border-[solid] border-[#ffcc00] pointer-events-none bg-[#ffcc00bb]",style:H}),bg=H=>{m(H),$e||(Ae(!0),window.setTimeout(()=>{Ae(!1)},1e4))},_g=()=>v.jsx("div",{className:"absolute h-[20px] w-[20px] pointer-events-none rounded-[50%] bg-[rgba(21,_215,_121,_0.936)] [box-shadow:0_0_0_0_rgba(21,_215,_121,_0.936)] animate-pulse",style:{left:`${Ue}px`,top:`${We}px`,transform:"translate(-50%, -50%)"},children:v.jsx(uK,{})}),Sg=()=>v.jsx(dq,{ref:H=>{H&&(Z.current=H)},panning:{disabled:!Oe,velocityDisabled:!0},wheel:{step:.05},centerZoomedOut:!0,alignmentAnimation:{disabled:!0},centerOnInit:!0,limitToBounds:!1,doubleClick:{disabled:!0},initialScale:gt,minScale:gt*.3,onPanning:()=>{Kt||Er(!0)},onZoom:H=>{ct(H.state.scale)},children:v.jsxs(hq,{contentStyle:{visibility:we?"visible":"hidden"},children:[v.jsxs("div",{className:"grid [grid-template-areas:'editor-content'] gap-y-4",children:[v.jsx("canvas",{className:"[grid-area:editor-content]",style:{clipPath:`inset(0 ${ft}% 0 0)`,transition:`clip-path ${lu}ms`},ref:H=>{if(H&&!ge){const Ge=H.getContext("2d");Ge&&Ve(Ge)}}}),v.jsx("canvas",{className:Ce("[grid-area:editor-content]",k?"pointer-events-none animate-pulse duration-600":""),style:{cursor:xg(),clipPath:`inset(0 ${ft}% 0 0)`,transition:`clip-path ${lu}ms`},onContextMenu:H=>{H.preventDefault()},onMouseOver:()=>{Tc(!0),Ae(!1)},onFocus:()=>Tc(!0),onMouseLeave:()=>Tc(!1),onMouseDown:wg,onMouseUp:yg,onMouseMove:zs,ref:H=>{if(H&&!W){const Ge=H.getContext("2d");Ge&&le(Ge)}}}),v.jsx("div",{className:"[grid-area:editor-content] pointer-events-none grid [grid-template-areas:'original-image-content']",style:{width:`${s}px`,height:`${l}px`},children:L&&v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"[grid-area:original-image-content] z-10 bg-primary h-full w-[6px] justify-self-end",style:{marginRight:`${ft}%`,transition:`margin-right ${lu}ms`}}),v.jsx("img",{className:"[grid-area:original-image-content]",src:K.src,alt:"original",style:{width:`${s}px`,height:`${l}px`}})]})})]}),v.jsx(jq,{maxHeight:l,maxWidth:s,minHeight:Math.min(512,l),minWidth:Math.min(512,s),scale:Pc(),show:u.showCropper}),v.jsx(Hq,{minHeight:Math.min(512,l),minWidth:Math.min(512,s),scale:Pc(),show:u.showExtender}),g.isInteractiveSeg?v.jsx(Uq,{}):v.jsx(v.Fragment,{})]})});return v.jsxs("div",{className:"flex w-screen h-screen justify-center items-center","aria-hidden":"true",onMouseMove:Ri,onMouseUp:$c,children:[Sg(),fe&&!i&&!Oe&&(g.isInteractiveSeg?_g():Ac(Yd(Ue,We))),$e&&Ac(Yd(I,X)),v.jsxs("div",{className:" overflow-hidden fixed flex bottom-5 border px-4 py-2 rounded-[3rem] gap-8 items-center justify-center backdrop-filter backdrop-blur-md bg-background/70",children:[v.jsx(uo,{className:"w-48",defaultValue:[50],min:Yq,max:Gq,step:1,tabIndex:-1,value:[F],onValueChange:H=>bg(H[0]),onClick:()=>Ae(!1)}),v.jsxs("div",{className:"flex gap-2",children:[v.jsx(vn,{tooltip:"Reset zoom & pan",disabled:Ot===gt&&Kt===!1,onClick:Vn,children:v.jsx(qU,{})}),v.jsx(vn,{tooltip:"Undo",onClick:Kd,disabled:b,children:v.jsx(sV,{})}),v.jsx(vn,{tooltip:"Redo",onClick:kc,disabled:E,children:v.jsx(rV,{})}),v.jsx(vn,{tooltip:"Show original image",onPointerDown:H=>{H.preventDefault(),ie(()=>(window.setTimeout(()=>{pt(100)},10),!0))},onPointerUp:()=>{window.setTimeout(()=>{pt(0)},10),window.setTimeout(()=>{ie(!1)},lu)},disabled:J.length===0,children:v.jsx(QU,{})}),v.jsx(vn,{tooltip:"Save Image",disabled:!J.length,onClick:Rc,children:v.jsx(XU,{})}),u.enableManualInpainting&&u.model.model_type==="inpaint"?v.jsx(vn,{tooltip:"Run Inpainting",disabled:k||!_n()&&G.length===0,onClick:()=>{A()},children:v.jsx(ZU,{})}):v.jsx(v.Fragment,{})]})]})]})}const Zq=()=>{const[e,t]=bt(n=>[n.imageWidth,n.imageHeight]);return!e||!t?null:v.jsxs("div",{className:"border rounded-lg px-2 py-[6px] z-10 bg-background",children:[e,"x",t]})},B1=["Enter"," "],qq=["ArrowDown","PageUp","Home"],V3=["ArrowUp","PageDown","End"],Qq=[...qq,...V3],Jq={ltr:[...B1,"ArrowRight"],rtl:[...B1,"ArrowLeft"]},eQ={ltr:["ArrowLeft"],rtl:["ArrowRight"]},fg="Menu",[ld,tQ,nQ]=zd(fg),[Na,W3]=An(fg,[nQ,Ns,Qm]),pg=Ns(),H3=Qm(),[K3,Fs]=Na(fg),[rQ,Hd]=Na(fg),oQ=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:o,onOpenChange:i,modal:s=!0}=e,l=pg(t),[u,d]=f.useState(null),h=f.useRef(!1),m=Ft(i),g=Sc(o);return f.useEffect(()=>{const y=()=>{h.current=!0,document.addEventListener("pointerdown",x,{capture:!0,once:!0}),document.addEventListener("pointermove",x,{capture:!0,once:!0})},x=()=>h.current=!1;return document.addEventListener("keydown",y,{capture:!0}),()=>{document.removeEventListener("keydown",y,{capture:!0}),document.removeEventListener("pointerdown",x,{capture:!0}),document.removeEventListener("pointermove",x,{capture:!0})}},[]),f.createElement(Od,l,f.createElement(K3,{scope:t,open:n,onOpenChange:m,content:u,onContentChange:d},f.createElement(rQ,{scope:t,onClose:f.useCallback(()=>m(!1),[m]),isUsingKeyboardRef:h,dir:g,modal:s},r)))},Y3=f.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,o=pg(n);return f.createElement(zm,Y({},o,r,{ref:t}))}),G3="MenuPortal",[iQ,X3]=Na(G3,{forceMount:void 0}),sQ=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:o}=e,i=Fs(G3,t);return f.createElement(iQ,{scope:t,forceMount:n},f.createElement(bn,{present:n||i.open},f.createElement(Md,{asChild:!0,container:o},r)))},yo="MenuContent",[aQ,Jx]=Na(yo),lQ=f.forwardRef((e,t)=>{const n=X3(yo,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,i=Fs(yo,e.__scopeMenu),s=Hd(yo,e.__scopeMenu);return f.createElement(ld.Provider,{scope:e.__scopeMenu},f.createElement(bn,{present:r||i.open},f.createElement(ld.Slot,{scope:e.__scopeMenu},s.modal?f.createElement(cQ,Y({},o,{ref:t})):f.createElement(uQ,Y({},o,{ref:t})))))}),cQ=f.forwardRef((e,t)=>{const n=Fs(yo,e.__scopeMenu),r=f.useRef(null),o=Be(t,r);return f.useEffect(()=>{const i=r.current;if(i)return Xm(i)},[]),f.createElement(eb,Y({},e,{ref:o,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:ue(e.onFocusOutside,i=>i.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)}))}),uQ=f.forwardRef((e,t)=>{const n=Fs(yo,e.__scopeMenu);return f.createElement(eb,Y({},e,{ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)}))}),eb=f.forwardRef((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:o,onOpenAutoFocus:i,onCloseAutoFocus:s,disableOutsidePointerEvents:l,onEntryFocus:u,onEscapeKeyDown:d,onPointerDownOutside:h,onFocusOutside:m,onInteractOutside:g,onDismiss:y,disableOutsideScroll:x,..._}=e,C=Fs(yo,n),S=Hd(yo,n),b=pg(n),E=H3(n),k=tQ(n),[P,M]=f.useState(null),A=f.useRef(null),O=Be(t,A,C.onContentChange),F=f.useRef(0),V=f.useRef(""),J=f.useRef(0),G=f.useRef(null),ae=f.useRef("right"),U=f.useRef(0),te=x?Gm:f.Fragment,L=x?{as:Wo,allowPinchZoom:!0}:void 0,ie=Q=>{var W,le;const ge=V.current+Q,Ve=k().filter($e=>!$e.disabled),Ue=document.activeElement,We=(W=Ve.find($e=>$e.ref.current===Ue))===null||W===void 0?void 0:W.textValue,Me=Ve.map($e=>$e.textValue),fe=kQ(Me,ge,We),xe=(le=Ve.find($e=>$e.textValue===fe))===null||le===void 0?void 0:le.ref.current;(function $e(Ae){V.current=Ae,window.clearTimeout(F.current),Ae!==""&&(F.current=window.setTimeout(()=>$e(""),1e3))})(ge),xe&&setTimeout(()=>xe.focus())};f.useEffect(()=>()=>window.clearTimeout(F.current),[]),Km();const K=f.useCallback(Q=>{var W,le;return ae.current===((W=G.current)===null||W===void 0?void 0:W.side)&&TQ(Q,(le=G.current)===null||le===void 0?void 0:le.area)},[]);return f.createElement(aQ,{scope:n,searchRef:V,onItemEnter:f.useCallback(Q=>{K(Q)&&Q.preventDefault()},[K]),onItemLeave:f.useCallback(Q=>{var W;K(Q)||((W=A.current)===null||W===void 0||W.focus(),M(null))},[K]),onTriggerLeave:f.useCallback(Q=>{K(Q)&&Q.preventDefault()},[K]),pointerGraceTimerRef:J,onPointerGraceIntentChange:f.useCallback(Q=>{G.current=Q},[])},f.createElement(te,L,f.createElement(Hm,{asChild:!0,trapped:o,onMountAutoFocus:ue(i,Q=>{var W;Q.preventDefault(),(W=A.current)===null||W===void 0||W.focus()}),onUnmountAutoFocus:s},f.createElement(yc,{asChild:!0,disableOutsidePointerEvents:l,onEscapeKeyDown:d,onPointerDownOutside:h,onFocusOutside:m,onInteractOutside:g,onDismiss:y},f.createElement(ZP,Y({asChild:!0},E,{dir:S.dir,orientation:"vertical",loop:r,currentTabStopId:P,onCurrentTabStopIdChange:M,onEntryFocus:ue(u,Q=>{S.isUsingKeyboardRef.current||Q.preventDefault()})}),f.createElement(Bm,Y({role:"menu","aria-orientation":"vertical","data-state":tA(C.open),"data-radix-menu-content":"",dir:S.dir},b,_,{ref:O,style:{outline:"none",..._.style},onKeyDown:ue(_.onKeyDown,Q=>{const le=Q.target.closest("[data-radix-menu-content]")===Q.currentTarget,ge=Q.ctrlKey||Q.altKey||Q.metaKey,Ve=Q.key.length===1;le&&(Q.key==="Tab"&&Q.preventDefault(),!ge&&Ve&&ie(Q.key));const Ue=A.current;if(Q.target!==Ue||!Qq.includes(Q.key))return;Q.preventDefault();const Me=k().filter(fe=>!fe.disabled).map(fe=>fe.ref.current);V3.includes(Q.key)&&Me.reverse(),CQ(Me)}),onBlur:ue(e.onBlur,Q=>{Q.currentTarget.contains(Q.target)||(window.clearTimeout(F.current),V.current="")}),onPointerMove:ue(e.onPointerMove,cd(Q=>{const W=Q.target,le=U.current!==Q.clientX;if(Q.currentTarget.contains(W)&&le){const ge=Q.clientX>U.current?"right":"left";ae.current=ge,U.current=Q.clientX}}))})))))))}),dQ=f.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return f.createElement(Pe.div,Y({},r,{ref:t}))}),U1="MenuItem",H2="menu.itemSelect",tb=f.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...o}=e,i=f.useRef(null),s=Hd(U1,e.__scopeMenu),l=Jx(U1,e.__scopeMenu),u=Be(t,i),d=f.useRef(!1),h=()=>{const m=i.current;if(!n&&m){const g=new CustomEvent(H2,{bubbles:!0,cancelable:!0});m.addEventListener(H2,y=>r==null?void 0:r(y),{once:!0}),cx(m,g),g.defaultPrevented?d.current=!1:s.onClose()}};return f.createElement(Z3,Y({},o,{ref:u,disabled:n,onClick:ue(e.onClick,h),onPointerDown:m=>{var g;(g=e.onPointerDown)===null||g===void 0||g.call(e,m),d.current=!0},onPointerUp:ue(e.onPointerUp,m=>{var g;d.current||(g=m.currentTarget)===null||g===void 0||g.click()}),onKeyDown:ue(e.onKeyDown,m=>{const g=l.searchRef.current!=="";n||g&&m.key===" "||B1.includes(m.key)&&(m.currentTarget.click(),m.preventDefault())})}))}),Z3=f.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:o,...i}=e,s=Jx(U1,n),l=H3(n),u=f.useRef(null),d=Be(t,u),[h,m]=f.useState(!1),[g,y]=f.useState("");return f.useEffect(()=>{const x=u.current;if(x){var _;y(((_=x.textContent)!==null&&_!==void 0?_:"").trim())}},[i.children]),f.createElement(ld.ItemSlot,{scope:n,disabled:r,textValue:o??g},f.createElement(qP,Y({asChild:!0},l,{focusable:!r}),f.createElement(Pe.div,Y({role:"menuitem","data-highlighted":h?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0},i,{ref:d,onPointerMove:ue(e.onPointerMove,cd(x=>{r?s.onItemLeave(x):(s.onItemEnter(x),x.defaultPrevented||x.currentTarget.focus())})),onPointerLeave:ue(e.onPointerLeave,cd(x=>s.onItemLeave(x))),onFocus:ue(e.onFocus,()=>m(!0)),onBlur:ue(e.onBlur,()=>m(!1))}))))}),fQ=f.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...o}=e;return f.createElement(Q3,{scope:e.__scopeMenu,checked:n},f.createElement(tb,Y({role:"menuitemcheckbox","aria-checked":om(n)?"mixed":n},o,{ref:t,"data-state":nb(n),onSelect:ue(o.onSelect,()=>r==null?void 0:r(om(n)?!0:!n),{checkForDefaultPrevented:!1})})))}),pQ="MenuRadioGroup",[Cte,hQ]=Na(pQ,{value:void 0,onValueChange:()=>{}}),mQ="MenuRadioItem",gQ=f.forwardRef((e,t)=>{const{value:n,...r}=e,o=hQ(mQ,e.__scopeMenu),i=n===o.value;return f.createElement(Q3,{scope:e.__scopeMenu,checked:i},f.createElement(tb,Y({role:"menuitemradio","aria-checked":i},r,{ref:t,"data-state":nb(i),onSelect:ue(r.onSelect,()=>{var s;return(s=o.onValueChange)===null||s===void 0?void 0:s.call(o,n)},{checkForDefaultPrevented:!1})})))}),q3="MenuItemIndicator",[Q3,vQ]=Na(q3,{checked:!1}),yQ=f.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...o}=e,i=vQ(q3,n);return f.createElement(bn,{present:r||om(i.checked)||i.checked===!0},f.createElement(Pe.span,Y({},o,{ref:t,"data-state":nb(i.checked)})))}),wQ=f.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return f.createElement(Pe.div,Y({role:"separator","aria-orientation":"horizontal"},r,{ref:t}))}),J3="MenuSub",[xQ,eA]=Na(J3),bQ=e=>{const{__scopeMenu:t,children:n,open:r=!1,onOpenChange:o}=e,i=Fs(J3,t),s=pg(t),[l,u]=f.useState(null),[d,h]=f.useState(null),m=Ft(o);return f.useEffect(()=>(i.open===!1&&m(!1),()=>m(!1)),[i.open,m]),f.createElement(Od,s,f.createElement(K3,{scope:t,open:r,onOpenChange:m,content:d,onContentChange:h},f.createElement(xQ,{scope:t,contentId:nr(),triggerId:nr(),trigger:l,onTriggerChange:u},n)))},gp="MenuSubTrigger",_Q=f.forwardRef((e,t)=>{const n=Fs(gp,e.__scopeMenu),r=Hd(gp,e.__scopeMenu),o=eA(gp,e.__scopeMenu),i=Jx(gp,e.__scopeMenu),s=f.useRef(null),{pointerGraceTimerRef:l,onPointerGraceIntentChange:u}=i,d={__scopeMenu:e.__scopeMenu},h=f.useCallback(()=>{s.current&&window.clearTimeout(s.current),s.current=null},[]);return f.useEffect(()=>h,[h]),f.useEffect(()=>{const m=l.current;return()=>{window.clearTimeout(m),u(null)}},[l,u]),f.createElement(Y3,Y({asChild:!0},d),f.createElement(Z3,Y({id:o.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":o.contentId,"data-state":tA(n.open)},e,{ref:Am(t,o.onTriggerChange),onClick:m=>{var g;(g=e.onClick)===null||g===void 0||g.call(e,m),!(e.disabled||m.defaultPrevented)&&(m.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:ue(e.onPointerMove,cd(m=>{i.onItemEnter(m),!m.defaultPrevented&&!e.disabled&&!n.open&&!s.current&&(i.onPointerGraceIntentChange(null),s.current=window.setTimeout(()=>{n.onOpenChange(!0),h()},100))})),onPointerLeave:ue(e.onPointerLeave,cd(m=>{var g;h();const y=(g=n.content)===null||g===void 0?void 0:g.getBoundingClientRect();if(y){var x;const _=(x=n.content)===null||x===void 0?void 0:x.dataset.side,C=_==="right",S=C?-5:5,b=y[C?"left":"right"],E=y[C?"right":"left"];i.onPointerGraceIntentChange({area:[{x:m.clientX+S,y:m.clientY},{x:b,y:y.top},{x:E,y:y.top},{x:E,y:y.bottom},{x:b,y:y.bottom}],side:_}),window.clearTimeout(l.current),l.current=window.setTimeout(()=>i.onPointerGraceIntentChange(null),300)}else{if(i.onTriggerLeave(m),m.defaultPrevented)return;i.onPointerGraceIntentChange(null)}})),onKeyDown:ue(e.onKeyDown,m=>{const g=i.searchRef.current!=="";if(!(e.disabled||g&&m.key===" ")&&Jq[r.dir].includes(m.key)){var y;n.onOpenChange(!0),(y=n.content)===null||y===void 0||y.focus(),m.preventDefault()}})})))}),SQ="MenuSubContent",EQ=f.forwardRef((e,t)=>{const n=X3(yo,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,i=Fs(yo,e.__scopeMenu),s=Hd(yo,e.__scopeMenu),l=eA(SQ,e.__scopeMenu),u=f.useRef(null),d=Be(t,u);return f.createElement(ld.Provider,{scope:e.__scopeMenu},f.createElement(bn,{present:r||i.open},f.createElement(ld.Slot,{scope:e.__scopeMenu},f.createElement(eb,Y({id:l.contentId,"aria-labelledby":l.triggerId},o,{ref:d,align:"start",side:s.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:h=>{var m;s.isUsingKeyboardRef.current&&((m=u.current)===null||m===void 0||m.focus()),h.preventDefault()},onCloseAutoFocus:h=>h.preventDefault(),onFocusOutside:ue(e.onFocusOutside,h=>{h.target!==l.trigger&&i.onOpenChange(!1)}),onEscapeKeyDown:ue(e.onEscapeKeyDown,h=>{s.onClose(),h.preventDefault()}),onKeyDown:ue(e.onKeyDown,h=>{const m=h.currentTarget.contains(h.target),g=eQ[s.dir].includes(h.key);if(m&&g){var y;i.onOpenChange(!1),(y=l.trigger)===null||y===void 0||y.focus(),h.preventDefault()}})})))))});function tA(e){return e?"open":"closed"}function om(e){return e==="indeterminate"}function nb(e){return om(e)?"indeterminate":e?"checked":"unchecked"}function CQ(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function $Q(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function kQ(e,t,n){const o=t.length>1&&Array.from(t).every(d=>d===t[0])?t[0]:t,i=n?e.indexOf(n):-1;let s=$Q(e,Math.max(i,0));o.length===1&&(s=s.filter(d=>d!==n));const u=s.find(d=>d.toLowerCase().startsWith(o.toLowerCase()));return u!==n?u:void 0}function RQ(e,t){const{x:n,y:r}=e;let o=!1;for(let i=0,s=t.length-1;ir!=h>r&&n<(d-l)*(r-u)/(h-u)+l&&(o=!o)}return o}function TQ(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return RQ(n,t)}function cd(e){return t=>t.pointerType==="mouse"?e(t):void 0}const PQ=oQ,AQ=Y3,OQ=sQ,MQ=lQ,NQ=dQ,DQ=tb,IQ=fQ,LQ=gQ,FQ=yQ,jQ=wQ,zQ=bQ,BQ=_Q,UQ=EQ,nA="DropdownMenu",[VQ,$te]=An(nA,[W3]),Sr=W3(),[WQ,rA]=VQ(nA),HQ=e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:o,defaultOpen:i,onOpenChange:s,modal:l=!0}=e,u=Sr(t),d=f.useRef(null),[h=!1,m]=Zr({prop:o,defaultProp:i,onChange:s});return f.createElement(WQ,{scope:t,triggerId:nr(),triggerRef:d,contentId:nr(),open:h,onOpenChange:m,onOpenToggle:f.useCallback(()=>m(g=>!g),[m]),modal:l},f.createElement(PQ,Y({},u,{open:h,onOpenChange:m,dir:r,modal:l}),n))},KQ="DropdownMenuTrigger",YQ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...o}=e,i=rA(KQ,n),s=Sr(n);return f.createElement(AQ,Y({asChild:!0},s),f.createElement(Pe.button,Y({type:"button",id:i.triggerId,"aria-haspopup":"menu","aria-expanded":i.open,"aria-controls":i.open?i.contentId:void 0,"data-state":i.open?"open":"closed","data-disabled":r?"":void 0,disabled:r},o,{ref:Am(t,i.triggerRef),onPointerDown:ue(e.onPointerDown,l=>{!r&&l.button===0&&l.ctrlKey===!1&&(i.onOpenToggle(),i.open||l.preventDefault())}),onKeyDown:ue(e.onKeyDown,l=>{r||(["Enter"," "].includes(l.key)&&i.onOpenToggle(),l.key==="ArrowDown"&&i.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(l.key)&&l.preventDefault())})})))}),GQ=e=>{const{__scopeDropdownMenu:t,...n}=e,r=Sr(t);return f.createElement(OQ,Y({},r,n))},XQ="DropdownMenuContent",ZQ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=rA(XQ,n),i=Sr(n),s=f.useRef(!1);return f.createElement(MQ,Y({id:o.contentId,"aria-labelledby":o.triggerId},i,r,{ref:t,onCloseAutoFocus:ue(e.onCloseAutoFocus,l=>{var u;s.current||(u=o.triggerRef.current)===null||u===void 0||u.focus(),s.current=!1,l.preventDefault()}),onInteractOutside:ue(e.onInteractOutside,l=>{const u=l.detail.originalEvent,d=u.button===0&&u.ctrlKey===!0,h=u.button===2||d;(!o.modal||h)&&(s.current=!0)}),style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}}))}),qQ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(NQ,Y({},o,r,{ref:t}))}),QQ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(DQ,Y({},o,r,{ref:t}))}),JQ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(IQ,Y({},o,r,{ref:t}))}),eJ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(LQ,Y({},o,r,{ref:t}))}),tJ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(FQ,Y({},o,r,{ref:t}))}),nJ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(jQ,Y({},o,r,{ref:t}))}),rJ=e=>{const{__scopeDropdownMenu:t,children:n,open:r,onOpenChange:o,defaultOpen:i}=e,s=Sr(t),[l=!1,u]=Zr({prop:r,defaultProp:i,onChange:o});return f.createElement(zQ,Y({},s,{open:l,onOpenChange:u}),n)},oJ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(BQ,Y({},o,r,{ref:t}))}),iJ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(UQ,Y({},o,r,{ref:t,style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}}))}),sJ=HQ,aJ=YQ,lJ=GQ,oA=ZQ,iA=qQ,sA=QQ,aA=JQ,lA=eJ,cA=tJ,uA=nJ,cJ=rJ,dA=oJ,fA=iJ,uJ=sJ,dJ=aJ,K2=cJ,V1=f.forwardRef(({className:e,inset:t,children:n,...r},o)=>v.jsxs(dA,{ref:o,className:Ce("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",e),...r,children:[n,v.jsx(ez,{className:"ml-auto h-4 w-4"})]}));V1.displayName=dA.displayName;const W1=f.forwardRef(({className:e,...t},n)=>v.jsx(fA,{ref:n,className:Ce("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...t}));W1.displayName=fA.displayName;const pA=f.forwardRef(({className:e,sideOffset:t=4,...n},r)=>v.jsx(lJ,{children:v.jsx(oA,{ref:r,sideOffset:t,className:Ce("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md","data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),onCloseAutoFocus:o=>o.preventDefault(),...n})}));pA.displayName=oA.displayName;const il=f.forwardRef(({className:e,inset:t,...n},r)=>v.jsx(sA,{ref:r,className:Ce("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",e),...n}));il.displayName=sA.displayName;const fJ=f.forwardRef(({className:e,children:t,checked:n,...r},o)=>v.jsxs(aA,{ref:o,className:Ce("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),checked:n,...r,children:[v.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:v.jsx(cA,{children:v.jsx(vT,{className:"h-4 w-4"})})}),t]}));fJ.displayName=aA.displayName;const pJ=f.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(lA,{ref:r,className:Ce("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[v.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:v.jsx(cA,{children:v.jsx(iz,{className:"h-4 w-4 fill-current"})})}),t]}));pJ.displayName=lA.displayName;const hJ=f.forwardRef(({className:e,inset:t,...n},r)=>v.jsx(iA,{ref:r,className:Ce("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",e),...n}));hJ.displayName=iA.displayName;const mJ=f.forwardRef(({className:e,...t},n)=>v.jsx(uA,{ref:n,className:Ce("-mx-1 my-1 h-px bg-muted",e),...t}));mJ.displayName=uA.displayName;const Y2={RemoveBG:{IconClass:VC,showName:"RemoveBG"},AnimeSeg:{IconClass:VC,showName:"Anime Segmentation"},RealESRGAN:{IconClass:XT,showName:"RealESRGAN"},GFPGAN:{IconClass:WC,showName:"GFPGAN"},RestoreFormer:{IconClass:WC,showName:"RestoreFormer"},InteractiveSeg:{IconClass:nV,showName:"Interactive Segmentation"}},gJ=()=>{const[e,t,n,r]=bt(d=>[d.file,d.serverConfig.plugins,d.updateInteractiveSegState,d.runRenderablePlugin]),o=!e;if(t.length===0)return null;const i=(d,h)=>{h==="InteractiveSeg"?n({isInteractiveSeg:!0}):r(d,h)},s=()=>v.jsxs(K2,{children:[v.jsx(V1,{disabled:o,children:v.jsxs("div",{className:"flex gap-2 items-center",children:[v.jsx(XT,{}),"RealESRGAN"]})}),v.jsxs(W1,{children:[v.jsx(il,{onClick:()=>r(!1,"RealESRGAN",{upscale:2}),children:"upscale 2x"}),v.jsx(il,{onClick:()=>r(!1,"RealESRGAN",{upscale:4}),children:"upscale 4x"})]})]},"RealESRGAN"),l=d=>{const{IconClass:h,showName:m}=Y2[d.name];return v.jsxs(K2,{children:[v.jsx(V1,{disabled:o,children:v.jsxs("div",{className:"flex gap-2 items-center",children:[v.jsx(h,{className:"p-1"}),m]})}),v.jsxs(W1,{children:[v.jsx(il,{onClick:()=>i(!1,d.name),children:"Remove Background"}),v.jsx(il,{onClick:()=>i(!0,d.name),children:"Generate Mask"})]})]},d.name)},u=()=>t.map(d=>{const{IconClass:h,showName:m}=Y2[d.name];return d.name==="RealESRGAN"?s():d.name==="RemoveBG"||d.name==="AnimeSeg"?l(d):v.jsx(il,{onClick:()=>i(!1,d.name),disabled:o,children:v.jsxs("div",{className:"flex gap-2 items-center",children:[v.jsx(h,{className:"p-1"}),m]})},d.name)});return v.jsxs(uJ,{modal:!1,children:[v.jsx(dJ,{className:"border rounded-lg z-10 bg-background outline-none",tabIndex:-1,children:v.jsx(yn,{variant:"ghost",size:"icon",asChild:!0,className:"p-1.5",children:v.jsx(HU,{strokeWidth:1})})}),v.jsx(pA,{side:"bottom",align:"start",children:u()})]})},vJ=Sx,yJ=gP,wJ=Ex,hA=f.forwardRef(({className:e,...t},n)=>v.jsx(Nd,{className:Ce("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t,ref:n}));hA.displayName=Nd.displayName;const xJ=Om("fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=closed]:duration-200 data-[state=open]:duration-300",{variants:{side:{top:"inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",bottom:"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",left:"inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",right:"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm"}},defaultVariants:{side:"right"}}),mA=f.forwardRef(({side:e="right",className:t,children:n,...r},o)=>v.jsxs(wJ,{children:[v.jsx(hA,{}),v.jsx(Dd,{ref:o,className:Ce(xJ({side:e}),t),...r,children:n})]}));mA.displayName=Dd.displayName;const gA=({className:e,...t})=>v.jsx("div",{className:Ce("flex flex-col space-y-2 text-center sm:text-left",e),...t});gA.displayName="SheetHeader";const bJ=f.forwardRef(({className:e,...t},n)=>v.jsx(Id,{ref:n,className:Ce("text-lg font-semibold text-foreground",e),...t}));bJ.displayName=Id.displayName;const _J=f.forwardRef(({className:e,...t},n)=>v.jsx(Ld,{ref:n,className:Ce("text-sm text-muted-foreground",e),...t}));_J.displayName=Ld.displayName;const Ut=({children:e})=>v.jsx("div",{className:"flex justify-between items-center pr-2",children:e}),Pt=({text:e,toolTip:t="",url:n,htmlFor:r,disabled:o=!1})=>v.jsxs(YT,{children:[v.jsx(GT,{asChild:!0,children:v.jsx(Gx,{htmlFor:r||e.toLowerCase().replace(" ","-"),className:"font-medium",disabled:o,children:e})}),t||n?v.jsxs(xx,{className:"flex flex-col max-w-xs text-sm",side:"left",children:[v.jsx("p",{children:t}),n?v.jsx(yn,{variant:"link",className:"justify-end",children:v.jsx("a",{href:n,target:"_blank",children:"More info"})}):v.jsx(v.Fragment,{})]}):v.jsx(v.Fragment,{})]}),SJ=()=>{const[e,t]=bt(n=>[n.settings,n.updateSettings]);return v.jsxs("div",{className:"flex flex-col gap-4 mt-4",children:[v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{htmlFor:"steps",text:"Steps",toolTip:"The number of denoising steps. More denoising steps usually lead to a higher quality image at the expense of slower inference."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[30],min:1,max:100,step:1,value:[Math.floor(e.ldmSteps)],onValueChange:n=>t({ldmSteps:n[0]})}),v.jsx(Gn,{id:"steps",className:"w-[60px] rounded-full",numberValue:e.ldmSteps,allowFloat:!1,onNumberValueChange:n=>{t({ldmSteps:n})}})]})]}),v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Sampler"}),v.jsxs(aa,{value:e.ldmSampler,onValueChange:n=>{t({ldmSampler:n})},children:[v.jsx(ls,{className:"w-[100px]",children:v.jsx(la,{placeholder:"Select sampler"})}),v.jsx(cs,{align:"end",children:v.jsx(wl,{children:Object.values(Zw).map(n=>v.jsx(us,{value:n,children:n},n))})})]})]})]})},vA=f.forwardRef(({className:e,...t},n)=>v.jsx("textarea",{className:Ce("flex min-h-[60px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",e,"overflow-auto"),tabIndex:-1,ref:n,...t}));vA.displayName="Textarea";const vp=({text:e,onClick:t})=>{const[n]=bt(r=>[r.settings.showExtender]);return v.jsx(yn,{variant:"outline",className:"p-1 h-8",disabled:!n,onClick:t,children:v.jsx("div",{className:"flex items-center gap-1",children:e})})},EJ=()=>{const[e,t,n,r,o,i,s,l,u,d,h]=bt(L=>[L.serverConfig.samplers,L.settings,L.paintByExampleFile,L.getIsProcessing(),L.updateSettings,L.runInpainting,L.updateAppState,L.updateExtenderByBuiltIn,L.updateExtenderDirection,L.adjustMask,L.clearMask]),[m,g]=Rx(n),y=f.useRef(null);OP(y,()=>{y!=null&&y.current&&y.current.blur()});const x=L=>{L.key==="Enter"&&L.ctrlKey&&t.prompt.length!==0&&i()},_=()=>v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Cropper",toolTip:"Inpainting on part of image, improve inference speed and reduce memory usage."}),v.jsx(co,{id:"cropper",checked:t.showCropper,onCheckedChange:L=>{o({showCropper:L}),L&&o({showExtender:!1})}})]}),C=()=>t.model.support_controlnet?v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex justify-between items-center pr-2",children:[v.jsx(Pt,{text:"ControlNet",toolTip:"Using an additional conditioning image to control how an image is generated",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#controlnet"}),v.jsx(co,{id:"controlnet",checked:t.enableControlnet,onCheckedChange:L=>{o({enableControlnet:L})}})]}),v.jsx("div",{className:"flex flex-col gap-1",children:v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[100],min:1,max:100,step:1,disabled:!t.enableControlnet,value:[Math.floor(t.controlnetConditioningScale*100)],onValueChange:L=>o({controlnetConditioningScale:L[0]/100})}),v.jsx(Gn,{id:"controlnet-weight",className:"w-[60px] rounded-full",disabled:!t.enableControlnet,numberValue:t.controlnetConditioningScale,allowFloat:!1,onNumberValueChange:L=>{o({controlnetConditioningScale:L})}})]})}),v.jsx("div",{className:"pr-2",children:v.jsxs(aa,{defaultValue:t.controlnetMethod,value:t.controlnetMethod,onValueChange:L=>{o({controlnetMethod:L})},disabled:!t.enableControlnet,children:[v.jsx(ls,{children:v.jsx(la,{placeholder:"Select control method"})}),v.jsx(cs,{align:"end",children:v.jsx(wl,{children:Object.values(t.model.controlnets).map(L=>v.jsx(us,{value:L,children:L.split("/")[1]},L))})})]})})]}),v.jsx(Fn,{})]}):null,S=()=>t.model.support_lcm_lora?v.jsxs(v.Fragment,{children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"LCM LoRA",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inference_with_lcm_lora",toolTip:"Enable quality image generation in typically 2-4 steps. Suggest disabling guidance_scale by setting it to 0. You can also try values between 1.0 and 2.0. When LCM Lora is enabled, LCMSampler will be used automatically."}),v.jsx(co,{id:"lcm-lora",checked:t.enableLCMLora,onCheckedChange:L=>{o({enableLCMLora:L})}})]}),v.jsx(Fn,{})]}):null,b=()=>t.model.support_freeu?v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex justify-between items-center pr-2",children:[v.jsx(Pt,{text:"FreeU",toolTip:"FreeU is a technique for improving image quality. Different models may require different FreeU-specific hyperparameters, which can be viewed in the more info section.",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/freeu"}),v.jsx(co,{id:"freeu",checked:t.enableFreeu,onCheckedChange:L=>{o({enableFreeu:L})}})]}),v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex justify-center gap-6",children:[v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-s1",text:"s1",disabled:!t.enableFreeu}),v.jsx(Gn,{id:"freeu-s1",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.s1,allowFloat:!0,onNumberValueChange:L=>{o({freeuConfig:{...t.freeuConfig,s1:L}})}})]}),v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-s2",text:"s2",disabled:!t.enableFreeu}),v.jsx(Gn,{id:"freeu-s2",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.s2,allowFloat:!0,onNumberValueChange:L=>{o({freeuConfig:{...t.freeuConfig,s2:L}})}})]})]}),v.jsxs("div",{className:"flex justify-center gap-6",children:[v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-b1",text:"b1",disabled:!t.enableFreeu}),v.jsx(Gn,{id:"freeu-b1",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.b1,allowFloat:!0,onNumberValueChange:L=>{o({freeuConfig:{...t.freeuConfig,b1:L}})}})]}),v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-b2",text:"b2",disabled:!t.enableFreeu}),v.jsx(Gn,{id:"freeu-b2",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.b2,allowFloat:!0,onNumberValueChange:L=>{o({freeuConfig:{...t.freeuConfig,b2:L}})}})]})]})]}),v.jsx(Fn,{})]}):null,E=()=>t.model.need_prompt?v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsx(Pt,{text:"Negative prompt",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#negative-prompt",toolTip:"Negative prompt guides the model away from generating certain things in an image"}),v.jsx("div",{className:"pl-2 pr-4",children:v.jsx(vA,{ref:y,rows:4,onKeyUp:x,className:"max-h-[8rem] overflow-y-auto mb-2",placeholder:"",id:"negative-prompt",value:t.negativePrompt,onInput:L=>{L.preventDefault(),L.stopPropagation();const ie=L.target;o({negativePrompt:ie.value})}})})]}):null,k=()=>t.model.name!==YR?null:v.jsxs("div",{children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Example Image",toolTip:"An example image to guide image generation."}),v.jsx(c1,{tooltip:"Upload example image",onFileUpload:L=>{s({paintByExampleFile:L})},children:v.jsx(ZT,{})})]}),g?v.jsx("div",{className:"flex justify-center items-center",children:v.jsx("img",{src:m.src,alt:"example",className:"max-w-[200px] max-h-[200px] m-3"})}):v.jsx(v.Fragment,{}),v.jsx(yn,{variant:"default",className:"w-full",disabled:r||!g,onClick:()=>{i()},children:"Paint"})]}),P=()=>t.model.name!==aF?null:v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Image guidance scale",toolTip:"Push the generated image towards the inital image. Higher image guidance scale encourages generated images that are closely linked to the source image, usually at the expense of lower image quality.",url:"https://huggingface.co/docs/diffusers/main/en/api/pipelines/pix2pix"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[150],min:100,max:1e3,step:1,value:[Math.floor(t.p2pImageGuidanceScale*100)],onValueChange:L=>o({p2pImageGuidanceScale:L[0]/100})}),v.jsx(Gn,{id:"image-guidance-scale",className:"w-[60px] rounded-full",numberValue:t.p2pImageGuidanceScale,allowFloat:!0,onNumberValueChange:L=>{o({p2pImageGuidanceScale:L})}})]})]}),M=()=>t.model.support_strength?v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Strength",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#strength",toolTip:"Strength is a measure of how much noise is added to the base image, which influences how similar the output is to the base image. Higher value means more noise and more different from the base image"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[100],min:10,max:100,step:1,value:[Math.floor(t.sdStrength*100)],onValueChange:L=>o({sdStrength:L[0]/100})}),v.jsx(Gn,{id:"strength",className:"w-[60px] rounded-full",numberValue:t.sdStrength,allowFloat:!0,onNumberValueChange:L=>{o({sdStrength:L})}})]})]}):null,A=()=>t.model.support_outpainting?v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Extender",toolTip:"Perform outpainting on images to expand it's content."}),v.jsx(co,{id:"extender",checked:t.showExtender,onCheckedChange:L=>{o({showExtender:L}),L&&o({showCropper:!1})}})]}),v.jsxs(Ut,{children:[v.jsxs(aa,{defaultValue:t.extenderDirection,value:t.extenderDirection,onValueChange:L=>{u(L)},children:[v.jsx(ls,{className:"w-[65px] h-7",disabled:!t.showExtender,children:v.jsx(la,{placeholder:"Select axis"})}),v.jsx(cs,{align:"end",children:v.jsx(wl,{children:Object.values(In).map(L=>v.jsx(us,{value:L,children:L},L))})})]}),v.jsxs("div",{className:"flex gap-1 justify-center mt-0",children:[v.jsx(vp,{text:"1.25x",onClick:()=>l(t.extenderDirection,1.25)}),v.jsx(vp,{text:"1.5x",onClick:()=>l(t.extenderDirection,1.5)}),v.jsx(vp,{text:"1.75x",onClick:()=>l(t.extenderDirection,1.75)}),v.jsx(vp,{text:"2.0x",onClick:()=>l(t.extenderDirection,2)})]})]})]}),v.jsx(Fn,{})]}):null,O=()=>t.model.name!==lF?null:v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Task",toolTip:"PowerPaint task. When using extender, image-outpainting task will be auto used. For object-removal and image-outpainting, it is recommended to set the guidance_scale at 10 or above."}),v.jsxs(aa,{defaultValue:t.powerpaintTask,value:t.powerpaintTask,onValueChange:L=>{o({powerpaintTask:L})},disabled:t.showExtender,children:[v.jsx(ls,{className:"w-[140px]",children:v.jsx(la,{placeholder:"Select task"})}),v.jsx(cs,{align:"end",children:v.jsx(wl,{children:[kl.text_guided,kl.object_remove,kl.shape_guided].map(L=>v.jsx(us,{value:L,children:L},L))})})]})]}),F=()=>v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{htmlFor:"steps",text:"Steps",toolTip:"The number of denoising steps. More denoising steps usually lead to a higher quality image at the expense of slower inference."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[30],min:1,max:100,step:1,value:[Math.floor(t.sdSteps)],onValueChange:L=>o({sdSteps:L[0]})}),v.jsx(Gn,{id:"steps",className:"w-[60px] rounded-full",numberValue:t.sdSteps,allowFloat:!1,onNumberValueChange:L=>{o({sdSteps:L})}})]})]}),V=()=>v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Guidance scale",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#guidance-scale",toolTip:"Guidance scale affects how aligned the text prompt and generated image are. Higher value means the prompt and generated image are closely aligned, so the output is a stricter interpretation of the prompt"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[750],min:0,max:1500,step:1,value:[Math.floor(t.sdGuidanceScale*100)],onValueChange:L=>o({sdGuidanceScale:L[0]/100})}),v.jsx(Gn,{id:"guidance-scale",className:"w-[60px] rounded-full",numberValue:t.sdGuidanceScale,allowFloat:!0,onNumberValueChange:L=>{o({sdGuidanceScale:L})}})]})]}),J=()=>t.model.name===cF?null:v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Sampler"}),v.jsxs(aa,{defaultValue:t.sdSampler,value:t.sdSampler,onValueChange:L=>{o({sdSampler:L})},children:[v.jsx(ls,{className:"w-[175px] text-xs",children:v.jsx(la,{placeholder:"Select sampler"})}),v.jsx(cs,{align:"end",children:v.jsx(wl,{children:e.map(L=>v.jsx(us,{value:L,className:"text-xs",children:L},L))})})]})]}),G=()=>v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Seed",toolTip:"Using same parameters and a fixed seed can generate same result image."}),v.jsxs("div",{className:"flex gap-2 justify-center items-center",children:[v.jsx(co,{id:"seed",checked:t.seedFixed,onCheckedChange:L=>{o({seedFixed:L})}}),v.jsx(Gn,{id:"seed",className:"w-[100px]",disabled:!t.seedFixed,numberValue:t.seed,allowFloat:!1,onNumberValueChange:L=>{o({seed:L})}})]})]}),ae=()=>v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Mask blur",toolTip:"How much to blur the mask before processing, in pixels. Make the generated inpainting boundaries appear more natural."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[t.sdMaskBlur],min:0,max:96,step:1,value:[Math.floor(t.sdMaskBlur)],onValueChange:L=>o({sdMaskBlur:L[0]})}),v.jsx(Gn,{id:"mask-blur",className:"w-[60px] rounded-full",numberValue:t.sdMaskBlur,allowFloat:!1,onNumberValueChange:L=>{o({sdMaskBlur:L})}})]})]}),U=()=>v.jsxs(v.Fragment,{children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Match histograms",toolTip:"Match the inpainting result histogram to the source image histogram",url:"https://github.com/Sanster/lama-cleaner/pull/143#issuecomment-1325859307"}),v.jsx(co,{id:"match-histograms",checked:t.sdMatchHistograms,onCheckedChange:L=>{o({sdMatchHistograms:L})}})]}),v.jsx(Fn,{})]}),te=()=>v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{htmlFor:"adjustMaskKernelSize",text:"Adjust Mask",toolTip:"Expand or shrink mask. Using the slider to adjust the kernel size for dilation or erosion."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[12],min:1,max:100,step:1,value:[Math.floor(t.adjustMaskKernelSize)],onValueChange:L=>o({adjustMaskKernelSize:L[0]})}),v.jsx(Gn,{id:"adjustMaskKernelSize",className:"w-[60px] rounded-full",numberValue:t.adjustMaskKernelSize,allowFloat:!1,onNumberValueChange:L=>{o({adjustMaskKernelSize:L})}})]}),v.jsxs(Ut,{children:[v.jsxs("div",{className:"flex gap-1 justify-start",children:[v.jsx(yn,{variant:"outline",className:"p-1 h-8",onClick:()=>d("expand"),disabled:r,children:v.jsx("div",{className:"flex items-center gap-1 select-none",children:"expand"})}),v.jsx(yn,{variant:"outline",className:"p-1 h-8",onClick:()=>d("shrink"),disabled:r,children:v.jsx("div",{className:"flex items-center gap-1 select-none",children:"Shrink"})}),v.jsx(yn,{variant:"outline",className:"p-1 h-8",onClick:()=>d("reverse"),disabled:r,children:v.jsx("div",{className:"flex items-center gap-1 select-none",children:"Reverse"})})]}),v.jsx(yn,{variant:"outline",className:"p-1 h-8 justify-self-end",onClick:h,disabled:r,children:v.jsx("div",{className:"flex items-center gap-1 select-none",children:"Clear"})})]})]}),v.jsx(Fn,{})]});return v.jsxs("div",{className:"flex flex-col gap-4 mt-4",children:[_(),A(),te(),O(),F(),V(),P(),M(),J(),G(),E(),v.jsx(Fn,{}),C(),S(),ae(),U(),b(),k()]})},CJ=()=>{const[e,t]=bt(n=>[n.settings,n.updateSettings]);return v.jsxs("div",{className:"flex flex-col gap-4 mt-4",children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"CV2 Flag",url:"https://docs.opencv.org/4.8.0/d7/d8b/group__photo__inpaint.html#gga8002a65f5a3328fbf15df81b842d3c3ca892824c38e258feb5e72f308a358d52e"}),v.jsxs(aa,{value:e.cv2Flag,onValueChange:n=>{t({cv2Flag:n})},children:[v.jsx(ls,{className:"w-[160px]",children:v.jsx(la,{placeholder:"Select flag"})}),v.jsx(cs,{align:"end",children:v.jsx(wl,{children:Object.values(qw).map(n=>v.jsx(us,{value:n,children:n},n))})})]})]}),v.jsx(Pt,{text:"CV2 Radius",url:"https://docs.opencv.org/4.8.0/d7/d8b/group__photo__inpaint.html#gga8002a65f5a3328fbf15df81b842d3c3ca892824c38e258feb5e72f308a358d52e"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[5],min:1,max:100,step:1,value:[Math.floor(e.cv2Radius)],onValueChange:n=>t({cv2Radius:n[0]})}),v.jsx(Gn,{id:"cv2-radius",className:"w-[60px] rounded-full",numberValue:e.cv2Radius,allowFloat:!1,onNumberValueChange:n=>{t({cv2Radius:n})}})]})]})},$J=()=>{const[e,t]=bt(i=>[i.settings,i.windowSize]),[n,r]=AP(!0);if(Zn("c",()=>{r()}),e.model.name!==oC&&e.model.name!==iC&&e.model.model_type===is)return null;const o=()=>e.model.name===oC?v.jsx(SJ,{}):e.model.name===iC?v.jsx(CJ,{}):v.jsx(EJ,{});return v.jsxs(vJ,{open:n,modal:!1,children:[v.jsx(yJ,{tabIndex:-1,className:"z-10 outline-none absolute top-[68px] right-6 rounded-lg border bg-background",children:v.jsx(yn,{variant:"ghost",size:"icon",asChild:!0,className:"p-1.5",onClick:r,children:v.jsx(KU,{strokeWidth:1})})}),v.jsxs(mA,{side:"right",className:"w-[300px] mt-[60px] outline-none pl-4 pr-1",onOpenAutoFocus:i=>i.preventDefault(),onPointerDownOutside:i=>i.preventDefault(),children:[v.jsxs(gA,{children:[v.jsxs(Ut,{children:[v.jsx("div",{className:"overflow-hidden mr-8",children:e.model.name.split("/")[e.model.name.split("/").length-1]}),v.jsx(yn,{variant:"ghost",size:"icon",className:"border h-6 w-6",onClick:r,children:v.jsx(YU,{strokeWidth:1})})]}),v.jsx(Fn,{})]}),v.jsx(og,{style:{height:t.height-160},className:"pr-3",children:o()})]})]})},Yo=Object.create(null);Yo.open="0";Yo.close="1";Yo.ping="2";Yo.pong="3";Yo.message="4";Yo.upgrade="5";Yo.noop="6";const th=Object.create(null);Object.keys(Yo).forEach(e=>{th[Yo[e]]=e});const H1={type:"error",data:"parser error"},yA=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",wA=typeof ArrayBuffer=="function",xA=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,rb=({type:e,data:t},n,r)=>yA&&t instanceof Blob?n?r(t):G2(t,r):wA&&(t instanceof ArrayBuffer||xA(t))?n?r(t):G2(new Blob([t]),r):r(Yo[e]+(t||"")),G2=(e,t)=>{const n=new FileReader;return n.onload=function(){const r=n.result.split(",")[1];t("b"+(r||""))},n.readAsDataURL(e)};function X2(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let L0;function kJ(e,t){if(yA&&e.data instanceof Blob)return e.data.arrayBuffer().then(X2).then(t);if(wA&&(e.data instanceof ArrayBuffer||xA(e.data)))return t(X2(e.data));rb(e,!1,n=>{L0||(L0=new TextEncoder),t(L0.encode(n))})}const Z2="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",gu=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let e=0;e{let t=e.length*.75,n=e.length,r,o=0,i,s,l,u;e[e.length-1]==="="&&(t--,e[e.length-2]==="="&&t--);const d=new ArrayBuffer(t),h=new Uint8Array(d);for(r=0;r>4,h[o++]=(s&15)<<4|l>>2,h[o++]=(l&3)<<6|u&63;return d},TJ=typeof ArrayBuffer=="function",ob=(e,t)=>{if(typeof e!="string")return{type:"message",data:bA(e,t)};const n=e.charAt(0);return n==="b"?{type:"message",data:PJ(e.substring(1),t)}:th[n]?e.length>1?{type:th[n],data:e.substring(1)}:{type:th[n]}:H1},PJ=(e,t)=>{if(TJ){const n=RJ(e);return bA(n,t)}else return{base64:!0,data:e}},bA=(e,t)=>{switch(t){case"blob":return e instanceof Blob?e:new Blob([e]);case"arraybuffer":default:return e instanceof ArrayBuffer?e:e.buffer}},_A="",AJ=(e,t)=>{const n=e.length,r=new Array(n);let o=0;e.forEach((i,s)=>{rb(i,!1,l=>{r[s]=l,++o===n&&t(r.join(_A))})})},OJ=(e,t)=>{const n=e.split(_A),r=[];for(let o=0;o{const r=n.length;let o;if(r<126)o=new Uint8Array(1),new DataView(o.buffer).setUint8(0,r);else if(r<65536){o=new Uint8Array(3);const i=new DataView(o.buffer);i.setUint8(0,126),i.setUint16(1,r)}else{o=new Uint8Array(9);const i=new DataView(o.buffer);i.setUint8(0,127),i.setBigUint64(1,BigInt(r))}e.data&&typeof e.data!="string"&&(o[0]|=128),t.enqueue(o),t.enqueue(n)})}})}let F0;function yp(e){return e.reduce((t,n)=>t+n.length,0)}function wp(e,t){if(e[0].length===t)return e.shift();const n=new Uint8Array(t);let r=0;for(let o=0;oMath.pow(2,21)-1){l.enqueue(H1);break}o=h*Math.pow(2,32)+d.getUint32(4),r=3}else{if(yp(n)e){l.enqueue(H1);break}}}})}const SA=4;function qt(e){if(e)return DJ(e)}function DJ(e){for(var t in qt.prototype)e[t]=qt.prototype[t];return e}qt.prototype.on=qt.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this};qt.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this};qt.prototype.off=qt.prototype.removeListener=qt.prototype.removeAllListeners=qt.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,o=0;o(e.hasOwnProperty(r)&&(n[r]=e[r]),n),{})}const IJ=Br.setTimeout,LJ=Br.clearTimeout;function hg(e,t){t.useNativeTimers?(e.setTimeoutFn=IJ.bind(Br),e.clearTimeoutFn=LJ.bind(Br)):(e.setTimeoutFn=Br.setTimeout.bind(Br),e.clearTimeoutFn=Br.clearTimeout.bind(Br))}const FJ=1.33;function jJ(e){return typeof e=="string"?zJ(e):Math.ceil((e.byteLength||e.size)*FJ)}function zJ(e){let t=0,n=0;for(let r=0,o=e.length;r=57344?n+=3:(r++,n+=4);return n}function BJ(e){let t="";for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+="&"),t+=encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t}function UJ(e){let t={},n=e.split("&");for(let r=0,o=n.length;r0);return t}function $A(){const e=J2(+new Date);return e!==Q2?(q2=0,Q2=e):e+"."+J2(q2++)}for(;xp{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)};OJ(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,AJ(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]=$A()),!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 Vo(this.uri(),t)}doWrite(t,n){const r=this.request({method:"POST",data:t});r.on("success",n),r.on("error",(o,i)=>{this.onError("xhr post error",o,i)})}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}}class Vo extends qt{constructor(t,n){super(),hg(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=EA(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");n.xdomain=!!this.opts.xd;const r=this.xhr=new RA(n);try{r.open(this.method,this.uri,!0);try{if(this.opts.extraHeaders){r.setDisableHeaderCheck&&r.setDisableHeaderCheck(!0);for(let o in this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(o)&&r.setRequestHeader(o,this.opts.extraHeaders[o])}}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 o;r.readyState===3&&((o=this.opts.cookieJar)===null||o===void 0||o.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(o){this.setTimeoutFn(()=>{this.onError(o)},0);return}typeof document<"u"&&(this.index=Vo.requestsCount++,Vo.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=KJ,t)try{this.xhr.abort()}catch{}typeof document<"u"&&delete Vo.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()}}Vo.requestsCount=0;Vo.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",e$);else if(typeof addEventListener=="function"){const e="onpagehide"in Br?"pagehide":"unload";addEventListener(e,e$,!1)}}function e$(){for(let e in Vo.requests)Vo.requests.hasOwnProperty(e)&&Vo.requests[e].abort()}const sb=typeof Promise=="function"&&typeof Promise.resolve=="function"?t=>Promise.resolve().then(t):(t,n)=>n(t,0),bp=Br.WebSocket||Br.MozWebSocket,t$=!0,XJ="arraybuffer",n$=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class ZJ extends ib{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=n$?{}:EA(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=t$&&!n$?n?new bp(t,n):new bp(t):new bp(t,n,r)}catch(o){return this.emitReserved("error",o)}this.ws.binaryType=this.socket.binaryType,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{t$&&this.ws.send(i)}catch{}o&&sb(()=>{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]=$A()),this.supportsBinary||(n.b64=1),this.createUri(t,n)}check(){return!!bp}}class qJ extends ib{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=NJ(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=t.readable.pipeThrough(n).getReader(),o=MJ();o.readable.pipeTo(t.writable),this.writer=o.writable.getWriter();const i=()=>{r.read().then(({done:l,value:u})=>{l||(this.onPacket(u),i())}).catch(l=>{})};i();const s={type:"open"};this.query.sid&&(s.data=`{"sid":"${this.query.sid}"}`),this.writer.write(s).then(()=>this.onOpen())})}))}write(t){this.writable=!1;for(let n=0;n{o&&sb(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;(t=this.transport)===null||t===void 0||t.close()}}const QJ={websocket:ZJ,webtransport:qJ,polling:GJ},JJ=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,eee=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Y1(e){if(e.length>2e3)throw"URI too long";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 o=JJ.exec(e||""),i={},s=14;for(;s--;)i[eee[s]]=o[s]||"";return n!=-1&&r!=-1&&(i.source=t,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=tee(i,i.path),i.queryKey=nee(i,i.query),i}function tee(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 nee(e,t){const n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(r,o,i){o&&(n[o]=i)}),n}let TA=class sl extends qt{constructor(t,n={}){super(),this.binaryType=XJ,this.writeBuffer=[],t&&typeof t=="object"&&(n=t,t=null),t?(t=Y1(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=Y1(n.host).host),hg(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=UJ(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=SA,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 QJ[t](r)}open(){let t;if(this.opts.rememberUpgrade&&sl.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;sl.priorWebsocketSuccess=!1;const o=()=>{r||(n.send([{type:"ping",data:"probe"}]),n.once("packet",m=>{if(!r)if(m.type==="pong"&&m.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",n),!n)return;sl.priorWebsocketSuccess=n.name==="websocket",this.transport.pause(()=>{r||this.readyState!=="closed"&&(h(),this.setTransport(n),n.send([{type:"upgrade"}]),this.emitReserved("upgrade",n),n=null,this.upgrading=!1,this.flush())})}else{const g=new Error("probe error");g.transport=n.name,this.emitReserved("upgradeError",g)}}))};function i(){r||(r=!0,h(),n.close(),n=null)}const s=m=>{const g=new Error("probe error: "+m);g.transport=n.name,i(),this.emitReserved("upgradeError",g)};function l(){s("transport closed")}function u(){s("socket closed")}function d(m){n&&m.name!==n.name&&i()}const h=()=>{n.removeListener("open",o),n.removeListener("error",s),n.removeListener("close",l),this.off("close",u),this.off("upgrading",d)};n.once("open",o),n.once("error",s),n.once("close",l),this.once("close",u),this.once("upgrading",d),this.upgrades.indexOf("webtransport")!==-1&&t!=="webtransport"?this.setTimeoutFn(()=>{r||n.open()},200):n.open()}onOpen(){if(this.readyState="open",sl.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,o){if(typeof n=="function"&&(o=n,n=void 0),typeof r=="function"&&(o=r,r=null),this.readyState==="closing"||this.readyState==="closed")return;r=r||{},r.compress=r.compress!==!1;const i={type:t,data:n,options:r};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),o&&this.once("flush",o),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){sl.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 o=t.length;for(;rtypeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,PA=Object.prototype.toString,see=typeof Blob=="function"||typeof Blob<"u"&&PA.call(Blob)==="[object BlobConstructor]",aee=typeof File=="function"||typeof File<"u"&&PA.call(File)==="[object FileConstructor]";function ab(e){return oee&&(e instanceof ArrayBuffer||iee(e))||see&&e instanceof Blob||aee&&e instanceof File}function nh(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(i),n.apply(this,[null,...s])}}emitWithAck(t,...n){const r=this.flags.timeout!==void 0||this._opts.ackTimeout!==void 0;return new Promise((o,i)=>{n.push((s,l)=>r?s?i(s):o(l):o(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((o,...i)=>r!==this._queue[0]?void 0:(o!==null?r.tryCount>this._opts.retries&&(this._queue.shift(),n&&n(o)):(this._queue.shift(),n&&n(null,...i)),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:lt.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 lt.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 lt.EVENT:case lt.BINARY_EVENT:this.onevent(t);break;case lt.ACK:case lt.BINARY_ACK:this.onack(t);break;case lt.DISCONNECT:this.ondisconnect();break;case lt.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(...o){r||(r=!0,n.packet({type:lt.ACK,id:t,data:o}))}}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:lt.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}Cc.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};Cc.prototype.reset=function(){this.attempts=0};Cc.prototype.setMin=function(e){this.ms=e};Cc.prototype.setMax=function(e){this.max=e};Cc.prototype.setJitter=function(e){this.jitter=e};class Z1 extends qt{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,hg(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 Cc({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(n.timeout==null?2e4:n.timeout),this._readyState="closed",this.uri=t;const o=n.parser||hee;this.encoder=new o.Encoder,this.decoder=new o.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 TA(this.uri,this.opts);const n=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;const o=fo(n,"open",function(){r.onopen(),t&&t()}),i=l=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",l),t?t(l):this.maybeReconnectOnOpen()},s=fo(n,"error",i);if(this._timeout!==!1){const l=this._timeout,u=this.setTimeoutFn(()=>{o(),i(new Error("timeout")),n.close()},l);this.opts.autoUnref&&u.unref(),this.subs.push(()=>{this.clearTimeoutFn(u)})}return this.subs.push(o),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(fo(t,"ping",this.onping.bind(this)),fo(t,"data",this.ondata.bind(this)),fo(t,"error",this.onerror.bind(this)),fo(t,"close",this.onclose.bind(this)),fo(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){sb(()=>{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 AA(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(o=>{o?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",o)):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 cu={};function rh(e,t){typeof e=="object"&&(t=e,e=void 0),t=t||{};const n=ree(e,t.path||"/socket.io"),r=n.source,o=n.id,i=n.path,s=cu[o]&&i in cu[o].nsps,l=t.forceNew||t["force new connection"]||t.multiplex===!1||s;let u;return l?u=new Z1(r,t):(cu[o]||(cu[o]=new Z1(r,t)),u=cu[o]),n.query&&!t.query&&(t.query=n.queryKey),u.socket(n.path,t)}Object.assign(rh,{Manager:Z1,Socket:AA,io:rh,connect:rh});const OA="Progress",mg=100,[gee,kte]=An(OA),[vee,yee]=gee(OA),MA=f.forwardRef((e,t)=>{const{__scopeProgress:n,value:r,max:o,getValueLabel:i=bee,...s}=e,l=q1(o)?o:mg,u=DA(r,l)?r:null,d=im(u)?i(u,l):void 0;return f.createElement(vee,{scope:n,value:u,max:l},f.createElement(Pe.div,Y({"aria-valuemax":l,"aria-valuemin":0,"aria-valuenow":im(u)?u:void 0,"aria-valuetext":d,role:"progressbar","data-state":NA(u,l),"data-value":u??void 0,"data-max":l},s,{ref:t})))});MA.propTypes={max(e,t,n){const r=e[t],o=String(r);return r&&!q1(r)?new Error(_ee(o,n)):null},value(e,t,n){const r=e[t],o=String(r),i=q1(e.max)?e.max:mg;return r!=null&&!DA(r,i)?new Error(See(o,n)):null}};const wee="ProgressIndicator",xee=f.forwardRef((e,t)=>{var n;const{__scopeProgress:r,...o}=e,i=yee(wee,r);return f.createElement(Pe.div,Y({"data-state":NA(i.value,i.max),"data-value":(n=i.value)!==null&&n!==void 0?n:void 0,"data-max":i.max},o,{ref:t}))});function bee(e,t){return`${Math.round(e/t*100)}%`}function NA(e,t){return e==null?"indeterminate":e===t?"complete":"loading"}function im(e){return typeof e=="number"}function q1(e){return im(e)&&!isNaN(e)&&e>0}function DA(e,t){return im(e)&&!isNaN(e)&&e<=t&&e>=0}function _ee(e,t){return`Invalid prop \`max\` of value \`${e}\` supplied to \`${t}\`. Only numbers greater than 0 are valid max values. Defaulting to \`${mg}\`.`}function See(e,t){return`Invalid prop \`value\` of value \`${e}\` supplied to \`${t}\`. The \`value\` prop must be: + - a positive number + - less than the value passed to \`max\` (or ${mg} if no \`max\` prop is set) + - \`null\` if the progress is indeterminate. + +Defaulting to \`null\`.`}const IA=MA,Eee=xee,LA=f.forwardRef(({className:e,value:t,...n},r)=>v.jsx(IA,{ref:r,className:Ce("relative h-2 w-full overflow-hidden rounded-full bg-primary/20",e),...n,children:v.jsx(Eee,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(t||0)}%)`}})}));LA.displayName=IA.displayName;const Cee="",Vi=rh(Cee),$ee=()=>{const[e,t,n]=bt(u=>[u.settings,u.isInpainting,u.isSD()]),[r,o]=f.useState(!1),[i,s]=f.useState(0),l=Math.min(Math.round(i/e.sdSteps*100),100);return f.useEffect(()=>(Vi.on("connect",()=>{o(!0)}),Vi.on("disconnect",()=>{o(!1)}),Vi.on("diffusion_progress",u=>{u&&s(u.step+1)}),Vi.on("diffusion_finish",()=>{s(0)}),()=>{Vi.off("connect"),Vi.off("disconnect"),Vi.off("diffusion_progress"),Vi.off("diffusion_finish")}),[]),v.jsxs("div",{className:"z-10 fixed bg-background w-[220px] left-1/2 -translate-x-1/2 top-[68px] h-[32px] flex justify-center items-center gap-[18px] border-[1px] border-[solid] rounded-[14px] pl-[8px] pr-[8px]",style:{visibility:r&&t&&n?"visible":"hidden"},children:[v.jsx(LA,{value:l}),v.jsxs("div",{className:"w-[45px] flex justify-center font-nums",children:[l,"%"]})]})},kee=()=>{const[e,t]=bt(n=>[n.file,n.updateSettings]);return f.useEffect(()=>{(async()=>{const r=await zj();t({model:r})})()},[]),v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"flex gap-3 absolute top-[68px] left-[24px] items-center",children:[v.jsx(gJ,{}),v.jsx(Zq,{})]}),v.jsx(Vq,{}),v.jsx($ee,{}),v.jsx($J,{}),e?v.jsx(Xq,{file:e}):v.jsx(v.Fragment,{})]})},Ree=()=>{const[e,t]=f.useState(window.innerWidth),n=f.useCallback(()=>{t(window.innerWidth)},[]);if(f.useEffect(()=>(window.addEventListener("resize",n),()=>{window.removeEventListener("resize",n)})),e<768)return"mobile";if(e>=768&&e<1224)return"tablet";if(e>=1224)return"desktop"};function Tee(e){const{onSelection:t}=e,[n]=f.useState(`file-upload-${Math.random().toString()}`),r=Ree();function o(i){if(!(!i||!i.type.match("image.*")))try{if(i.size>20*1024*1024)throw new Error("file too large");t(i)}catch(l){alert(`error: ${l.message}`)}}return v.jsx("div",{className:"absolute flex w-screen h-screen justify-center items-center pointer-events-none",children:v.jsx("label",{htmlFor:n,className:"grid bg-background border-[2px] border-[dashed] rounded-lg min-w-[600px] hover:bg-primary hover:text-primary-foreground pointer-events-auto",children:v.jsxs("div",{className:"grid p-16 w-full h-full",onDragOver:i=>{i.stopPropagation(),i.preventDefault()},children:[v.jsx("input",{className:"hidden",id:n,name:n,type:"file",onChange:i=>{var l;const s=(l=i.currentTarget.files)==null?void 0:l[0];s&&o(s)},accept:"image/png, image/jpeg"}),v.jsx("p",{className:"text-center",children:r==="desktop"?"Click here or drag an image file":"Tap here to load your picture"})]})})})}const FA="ToastProvider",[cb,Pee,Aee]=zd("Toast"),[jA,Rte]=An("Toast",[Aee]),[Oee,gg]=jA(FA),zA=e=>{const{__scopeToast:t,label:n="Notification",duration:r=5e3,swipeDirection:o="right",swipeThreshold:i=50,children:s}=e,[l,u]=f.useState(null),[d,h]=f.useState(0),m=f.useRef(!1),g=f.useRef(!1);return f.createElement(cb.Provider,{scope:t},f.createElement(Oee,{scope:t,label:n,duration:r,swipeDirection:o,swipeThreshold:i,toastCount:d,viewport:l,onViewportChange:u,onToastAdd:f.useCallback(()=>h(y=>y+1),[]),onToastRemove:f.useCallback(()=>h(y=>y-1),[]),isFocusedToastEscapeKeyDownRef:m,isClosePausedRef:g},s))};zA.propTypes={label(e){if(e.label&&typeof e.label=="string"&&!e.label.trim()){const t=`Invalid prop \`label\` supplied to \`${FA}\`. Expected non-empty \`string\`.`;return new Error(t)}return null}};const Mee="ToastViewport",Nee=["F8"],Q1="toast.viewportPause",J1="toast.viewportResume",Dee=f.forwardRef((e,t)=>{const{__scopeToast:n,hotkey:r=Nee,label:o="Notifications ({hotkey})",...i}=e,s=gg(Mee,n),l=Pee(n),u=f.useRef(null),d=f.useRef(null),h=f.useRef(null),m=f.useRef(null),g=Be(t,m,s.onViewportChange),y=r.join("+").replace(/Key/g,"").replace(/Digit/g,""),x=s.toastCount>0;f.useEffect(()=>{const C=S=>{var b;r.every(k=>S[k]||S.code===k)&&((b=m.current)===null||b===void 0||b.focus())};return document.addEventListener("keydown",C),()=>document.removeEventListener("keydown",C)},[r]),f.useEffect(()=>{const C=u.current,S=m.current;if(x&&C&&S){const b=()=>{if(!s.isClosePausedRef.current){const M=new CustomEvent(Q1);S.dispatchEvent(M),s.isClosePausedRef.current=!0}},E=()=>{if(s.isClosePausedRef.current){const M=new CustomEvent(J1);S.dispatchEvent(M),s.isClosePausedRef.current=!1}},k=M=>{!C.contains(M.relatedTarget)&&E()},P=()=>{C.contains(document.activeElement)||E()};return C.addEventListener("focusin",b),C.addEventListener("focusout",k),C.addEventListener("pointermove",b),C.addEventListener("pointerleave",P),window.addEventListener("blur",b),window.addEventListener("focus",E),()=>{C.removeEventListener("focusin",b),C.removeEventListener("focusout",k),C.removeEventListener("pointermove",b),C.removeEventListener("pointerleave",P),window.removeEventListener("blur",b),window.removeEventListener("focus",E)}}},[x,s.isClosePausedRef]);const _=f.useCallback(({tabbingDirection:C})=>{const b=l().map(E=>{const k=E.ref.current,P=[k,...qee(k)];return C==="forwards"?P:P.reverse()});return(C==="forwards"?b.reverse():b).flat()},[l]);return f.useEffect(()=>{const C=m.current;if(C){const S=b=>{const E=b.altKey||b.ctrlKey||b.metaKey;if(b.key==="Tab"&&!E){const O=document.activeElement,F=b.shiftKey;if(b.target===C&&F){var P;(P=d.current)===null||P===void 0||P.focus();return}const G=_({tabbingDirection:F?"backwards":"forwards"}),ae=G.findIndex(U=>U===O);if(j0(G.slice(ae+1)))b.preventDefault();else{var M,A;F?(M=d.current)===null||M===void 0||M.focus():(A=h.current)===null||A===void 0||A.focus()}}};return C.addEventListener("keydown",S),()=>C.removeEventListener("keydown",S)}},[l,_]),f.createElement(SB,{ref:u,role:"region","aria-label":o.replace("{hotkey}",y),tabIndex:-1,style:{pointerEvents:x?void 0:"none"}},x&&f.createElement(o$,{ref:d,onFocusFromOutsideViewport:()=>{const C=_({tabbingDirection:"forwards"});j0(C)}}),f.createElement(cb.Slot,{scope:n},f.createElement(Pe.ol,Y({tabIndex:-1},i,{ref:g}))),x&&f.createElement(o$,{ref:h,onFocusFromOutsideViewport:()=>{const C=_({tabbingDirection:"backwards"});j0(C)}}))}),Iee="ToastFocusProxy",o$=f.forwardRef((e,t)=>{const{__scopeToast:n,onFocusFromOutsideViewport:r,...o}=e,i=gg(Iee,n);return f.createElement(Um,Y({"aria-hidden":!0,tabIndex:0},o,{ref:t,style:{position:"fixed"},onFocus:s=>{var l;const u=s.relatedTarget;!((l=i.viewport)!==null&&l!==void 0&&l.contains(u))&&r()}}))}),vg="Toast",Lee="toast.swipeStart",Fee="toast.swipeMove",jee="toast.swipeCancel",zee="toast.swipeEnd",Bee=f.forwardRef((e,t)=>{const{forceMount:n,open:r,defaultOpen:o,onOpenChange:i,...s}=e,[l=!0,u]=Zr({prop:r,defaultProp:o,onChange:i});return f.createElement(bn,{present:n||l},f.createElement(BA,Y({open:l},s,{ref:t,onClose:()=>u(!1),onPause:Ft(e.onPause),onResume:Ft(e.onResume),onSwipeStart:ue(e.onSwipeStart,d=>{d.currentTarget.setAttribute("data-swipe","start")}),onSwipeMove:ue(e.onSwipeMove,d=>{const{x:h,y:m}=d.detail.delta;d.currentTarget.setAttribute("data-swipe","move"),d.currentTarget.style.setProperty("--radix-toast-swipe-move-x",`${h}px`),d.currentTarget.style.setProperty("--radix-toast-swipe-move-y",`${m}px`)}),onSwipeCancel:ue(e.onSwipeCancel,d=>{d.currentTarget.setAttribute("data-swipe","cancel"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),d.currentTarget.style.removeProperty("--radix-toast-swipe-end-x"),d.currentTarget.style.removeProperty("--radix-toast-swipe-end-y")}),onSwipeEnd:ue(e.onSwipeEnd,d=>{const{x:h,y:m}=d.detail.delta;d.currentTarget.setAttribute("data-swipe","end"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),d.currentTarget.style.setProperty("--radix-toast-swipe-end-x",`${h}px`),d.currentTarget.style.setProperty("--radix-toast-swipe-end-y",`${m}px`),u(!1)})})))}),[Uee,Vee]=jA(vg,{onClose(){}}),BA=f.forwardRef((e,t)=>{const{__scopeToast:n,type:r="foreground",duration:o,open:i,onClose:s,onEscapeKeyDown:l,onPause:u,onResume:d,onSwipeStart:h,onSwipeMove:m,onSwipeCancel:g,onSwipeEnd:y,...x}=e,_=gg(vg,n),[C,S]=f.useState(null),b=Be(t,U=>S(U)),E=f.useRef(null),k=f.useRef(null),P=o||_.duration,M=f.useRef(0),A=f.useRef(P),O=f.useRef(0),{onToastAdd:F,onToastRemove:V}=_,J=Ft(()=>{var U;(C==null?void 0:C.contains(document.activeElement))&&((U=_.viewport)===null||U===void 0||U.focus()),s()}),G=f.useCallback(U=>{!U||U===1/0||(window.clearTimeout(O.current),M.current=new Date().getTime(),O.current=window.setTimeout(J,U))},[J]);f.useEffect(()=>{const U=_.viewport;if(U){const te=()=>{G(A.current),d==null||d()},L=()=>{const ie=new Date().getTime()-M.current;A.current=A.current-ie,window.clearTimeout(O.current),u==null||u()};return U.addEventListener(Q1,L),U.addEventListener(J1,te),()=>{U.removeEventListener(Q1,L),U.removeEventListener(J1,te)}}},[_.viewport,P,u,d,G]),f.useEffect(()=>{i&&!_.isClosePausedRef.current&&G(P)},[i,P,_.isClosePausedRef,G]),f.useEffect(()=>(F(),()=>V()),[F,V]);const ae=f.useMemo(()=>C?HA(C):null,[C]);return _.viewport?f.createElement(f.Fragment,null,ae&&f.createElement(Wee,{__scopeToast:n,role:"status","aria-live":r==="foreground"?"assertive":"polite","aria-atomic":!0},ae),f.createElement(Uee,{scope:n,onClose:J},Os.createPortal(f.createElement(cb.ItemSlot,{scope:n},f.createElement(_B,{asChild:!0,onEscapeKeyDown:ue(l,()=>{_.isFocusedToastEscapeKeyDownRef.current||J(),_.isFocusedToastEscapeKeyDownRef.current=!1})},f.createElement(Pe.li,Y({role:"status","aria-live":"off","aria-atomic":!0,tabIndex:0,"data-state":i?"open":"closed","data-swipe-direction":_.swipeDirection},x,{ref:b,style:{userSelect:"none",touchAction:"none",...e.style},onKeyDown:ue(e.onKeyDown,U=>{U.key==="Escape"&&(l==null||l(U.nativeEvent),U.nativeEvent.defaultPrevented||(_.isFocusedToastEscapeKeyDownRef.current=!0,J()))}),onPointerDown:ue(e.onPointerDown,U=>{U.button===0&&(E.current={x:U.clientX,y:U.clientY})}),onPointerMove:ue(e.onPointerMove,U=>{if(!E.current)return;const te=U.clientX-E.current.x,L=U.clientY-E.current.y,ie=!!k.current,K=["left","right"].includes(_.swipeDirection),Q=["left","up"].includes(_.swipeDirection)?Math.min:Math.max,W=K?Q(0,te):0,le=K?0:Q(0,L),ge=U.pointerType==="touch"?10:2,Ve={x:W,y:le},Ue={originalEvent:U,delta:Ve};ie?(k.current=Ve,_p(Fee,m,Ue,{discrete:!1})):i$(Ve,_.swipeDirection,ge)?(k.current=Ve,_p(Lee,h,Ue,{discrete:!1}),U.target.setPointerCapture(U.pointerId)):(Math.abs(te)>ge||Math.abs(L)>ge)&&(E.current=null)}),onPointerUp:ue(e.onPointerUp,U=>{const te=k.current,L=U.target;if(L.hasPointerCapture(U.pointerId)&&L.releasePointerCapture(U.pointerId),k.current=null,E.current=null,te){const ie=U.currentTarget,K={originalEvent:U,delta:te};i$(te,_.swipeDirection,_.swipeThreshold)?_p(zee,y,K,{discrete:!0}):_p(jee,g,K,{discrete:!0}),ie.addEventListener("click",Q=>Q.preventDefault(),{once:!0})}})})))),_.viewport))):null});BA.propTypes={type(e){if(e.type&&!["foreground","background"].includes(e.type)){const t=`Invalid prop \`type\` supplied to \`${vg}\`. Expected \`foreground | background\`.`;return new Error(t)}return null}};const Wee=e=>{const{__scopeToast:t,children:n,...r}=e,o=gg(vg,t),[i,s]=f.useState(!1),[l,u]=f.useState(!1);return Xee(()=>s(!0)),f.useEffect(()=>{const d=window.setTimeout(()=>u(!0),1e3);return()=>window.clearTimeout(d)},[]),l?null:f.createElement(Md,{asChild:!0},f.createElement(Um,r,i&&f.createElement(f.Fragment,null,o.label," ",n)))},Hee=f.forwardRef((e,t)=>{const{__scopeToast:n,...r}=e;return f.createElement(Pe.div,Y({},r,{ref:t}))}),Kee=f.forwardRef((e,t)=>{const{__scopeToast:n,...r}=e;return f.createElement(Pe.div,Y({},r,{ref:t}))}),Yee="ToastAction",UA=f.forwardRef((e,t)=>{const{altText:n,...r}=e;return n?f.createElement(WA,{altText:n,asChild:!0},f.createElement(VA,Y({},r,{ref:t}))):null});UA.propTypes={altText(e){return e.altText?null:new Error(`Missing prop \`altText\` expected on \`${Yee}\``)}};const Gee="ToastClose",VA=f.forwardRef((e,t)=>{const{__scopeToast:n,...r}=e,o=Vee(Gee,n);return f.createElement(WA,{asChild:!0},f.createElement(Pe.button,Y({type:"button"},r,{ref:t,onClick:ue(e.onClick,o.onClose)})))}),WA=f.forwardRef((e,t)=>{const{__scopeToast:n,altText:r,...o}=e;return f.createElement(Pe.div,Y({"data-radix-toast-announce-exclude":"","data-radix-toast-announce-alt":r||void 0},o,{ref:t}))});function HA(e){const t=[];return Array.from(e.childNodes).forEach(r=>{if(r.nodeType===r.TEXT_NODE&&r.textContent&&t.push(r.textContent),Zee(r)){const o=r.ariaHidden||r.hidden||r.style.display==="none",i=r.dataset.radixToastAnnounceExclude==="";if(!o)if(i){const s=r.dataset.radixToastAnnounceAlt;s&&t.push(s)}else t.push(...HA(r))}}),t}function _p(e,t,n,{discrete:r}){const o=n.originalEvent.currentTarget,i=new CustomEvent(e,{bubbles:!0,cancelable:!0,detail:n});t&&o.addEventListener(e,t,{once:!0}),r?cx(o,i):o.dispatchEvent(i)}const i$=(e,t,n=0)=>{const r=Math.abs(e.x),o=Math.abs(e.y),i=r>o;return t==="left"||t==="right"?i&&r>n:!i&&o>n};function Xee(e=()=>{}){const t=Ft(e);Pn(()=>{let n=0,r=0;return n=window.requestAnimationFrame(()=>r=window.requestAnimationFrame(t)),()=>{window.cancelAnimationFrame(n),window.cancelAnimationFrame(r)}},[t])}function Zee(e){return e.nodeType===e.ELEMENT_NODE}function qee(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const o=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||o?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function j0(e){const t=document.activeElement;return e.some(n=>n===t?!0:(n.focus(),document.activeElement!==t))}const Qee=zA,KA=Dee,YA=Bee,GA=Hee,XA=Kee,ZA=UA,qA=VA,Jee=Qee,QA=f.forwardRef(({className:e,...t},n)=>v.jsx(KA,{ref:n,className:Ce("fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]",e),tabIndex:-1,...t}));QA.displayName=KA.displayName;const ete=Om("group pointer-events-auto relative flex w-full items-center justify-between space-x-2 overflow-hidden rounded-md border p-4 pr-6 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full",{variants:{variant:{default:"border bg-background text-foreground",destructive:"destructive group border-destructive bg-destructive text-destructive-foreground"}},defaultVariants:{variant:"default"}}),JA=f.forwardRef(({className:e,variant:t,...n},r)=>v.jsx(YA,{ref:r,className:Ce(ete({variant:t}),e),tabIndex:-1,...n}));JA.displayName=YA.displayName;const tte=f.forwardRef(({className:e,...t},n)=>v.jsx(ZA,{ref:n,className:Ce("inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium transition-colors hover:bg-secondary focus:outline-none focus:ring-1 focus:ring-ring disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive",e),tabIndex:-1,...t}));tte.displayName=ZA.displayName;const eO=f.forwardRef(({className:e,...t},n)=>v.jsx(qA,{ref:n,className:Ce("absolute right-1 top-1 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-1 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600",e),"toast-close":"",tabIndex:-1,...t,children:v.jsx(yT,{className:"h-4 w-4"})}));eO.displayName=qA.displayName;const tO=f.forwardRef(({className:e,...t},n)=>v.jsx(GA,{ref:n,className:Ce("text-sm font-semibold [&+div]:text-xs",e),tabIndex:-1,...t}));tO.displayName=GA.displayName;const nO=f.forwardRef(({className:e,...t},n)=>v.jsx(XA,{ref:n,className:Ce("text-sm opacity-90",e),...t,tabIndex:-1}));nO.displayName=XA.displayName;function nte(){const{toasts:e}=Td();return v.jsxs(Jee,{children:[e.map(function({id:t,title:n,description:r,action:o,...i}){return v.jsxs(JA,{...i,children:[v.jsxs("div",{className:"grid gap-1",children:[n&&v.jsx(tO,{children:n}),r&&v.jsx(nO,{children:r})]}),o,v.jsx(eO,{})]},t)}),v.jsx(QA,{})]})}const rte=["image/jpeg","image/png","image/webp","image/bmp","image/tiff"];function ote(){const[e,t,n,r]=bt(g=>[g.file,g.updateAppState,g.setServerConfig,g.setFile]),o=Yj(),i=gH();f.useEffect(()=>{o&&r(o)},[o,r]),f.useEffect(()=>{t({windowSize:i})},[i]),f.useEffect(()=>{(async()=>{const y=await Fj();n(y),y.isDesktop&&dF()})()},[]);const s=f.useRef(0),l=f.useCallback(g=>{g.preventDefault(),g.stopPropagation()},[]),u=f.useCallback(g=>{g.preventDefault(),g.stopPropagation(),s.current+=1},[]),d=f.useCallback(g=>{g.preventDefault(),g.stopPropagation(),s.current-=1,s.current>0},[]),h=f.useCallback(g=>{if(g.preventDefault(),g.stopPropagation(),g.dataTransfer.files&&g.dataTransfer.files.length>0){if(!(g.dataTransfer.files.length>1)){const y=g.dataTransfer.files[0],x=y.type;rte.includes(x)&&r(y)}g.dataTransfer.clearData()}},[]),m=f.useCallback(g=>{if(!g.clipboardData)return;const y=g.clipboardData.items,x=[].slice.call(y).filter(S=>S.type.indexOf("image")!==-1);if(x.length===0)return;g.preventDefault(),g.stopPropagation();const C=x[0].getAsFile();C&&r(C)},[]);return f.useEffect(()=>(window.addEventListener("dragenter",u),window.addEventListener("dragleave",d),window.addEventListener("dragover",l),window.addEventListener("drop",h),window.addEventListener("paste",m),function(){window.removeEventListener("dragenter",u),window.removeEventListener("dragleave",d),window.removeEventListener("dragover",l),window.removeEventListener("drop",h),window.removeEventListener("paste",m)})),v.jsxs("main",{className:"flex min-h-screen flex-col items-center justify-between w-full bg-[radial-gradient(circle_at_1px_1px,_#8e8e8e8e_1px,_transparent_0)] [background-size:20px_20px] bg-repeat",children:[v.jsx(nte,{}),v.jsx(tZ,{}),v.jsx(kee,{}),e?v.jsx(v.Fragment,{}):v.jsx(Tee,{onSelection:async g=>{r(g)}})]})}const sm=["light","dark"],ub="(prefers-color-scheme: dark)",ite=typeof window>"u",rO=f.createContext(void 0),ste=e=>f.useContext(rO)?Fe.createElement(f.Fragment,null,e.children):Fe.createElement(lte,e),ate=["light","dark"],lte=({forcedTheme:e,disableTransitionOnChange:t=!1,enableSystem:n=!0,enableColorScheme:r=!0,storageKey:o="theme",themes:i=ate,defaultTheme:s=n?"system":"light",attribute:l="data-theme",value:u,children:d,nonce:h})=>{const[m,g]=f.useState(()=>s$(o,s)),[y,x]=f.useState(()=>s$(o)),_=u?Object.values(u):i,C=f.useCallback(k=>{let P=k;if(!P)return;k==="system"&&n&&(P=a$());const M=u?u[P]:P,A=t?ute():null,O=document.documentElement;if(l==="class"?(O.classList.remove(..._),M&&O.classList.add(M)):M?O.setAttribute(l,M):O.removeAttribute(l),r){const F=sm.includes(s)?s:null,V=sm.includes(P)?P:F;O.style.colorScheme=V}A==null||A()},[]),S=f.useCallback(k=>{g(k);try{localStorage.setItem(o,k)}catch{}},[e]),b=f.useCallback(k=>{const P=a$(k);x(P),m==="system"&&n&&!e&&C("system")},[m,e]);f.useEffect(()=>{const k=window.matchMedia(ub);return k.addListener(b),b(k),()=>k.removeListener(b)},[b]),f.useEffect(()=>{const k=P=>{P.key===o&&S(P.newValue||s)};return window.addEventListener("storage",k),()=>window.removeEventListener("storage",k)},[S]),f.useEffect(()=>{C(e??m)},[e,m]);const E=f.useMemo(()=>({theme:m,setTheme:S,forcedTheme:e,resolvedTheme:m==="system"?y:m,themes:n?[...i,"system"]:i,systemTheme:n?y:void 0}),[m,S,e,y,n,i]);return Fe.createElement(rO.Provider,{value:E},Fe.createElement(cte,{forcedTheme:e,disableTransitionOnChange:t,enableSystem:n,enableColorScheme:r,storageKey:o,themes:i,defaultTheme:s,attribute:l,value:u,children:d,attrs:_,nonce:h}),d)},cte=f.memo(({forcedTheme:e,storageKey:t,attribute:n,enableSystem:r,enableColorScheme:o,defaultTheme:i,value:s,attrs:l,nonce:u})=>{const d=i==="system",h=n==="class"?`var d=document.documentElement,c=d.classList;c.remove(${l.map(x=>`'${x}'`).join(",")});`:`var d=document.documentElement,n='${n}',s='setAttribute';`,m=o?sm.includes(i)&&i?`if(e==='light'||e==='dark'||!e)d.style.colorScheme=e||'${i}'`:"if(e==='light'||e==='dark')d.style.colorScheme=e":"",g=(x,_=!1,C=!0)=>{const S=s?s[x]:x,b=_?x+"|| ''":`'${S}'`;let E="";return o&&C&&!_&&sm.includes(x)&&(E+=`d.style.colorScheme = '${x}';`),n==="class"?E+=_||S?`c.add(${b})`:"null":S&&(E+=`d[s](n,${b})`),E},y=e?`!function(){${h}${g(e)}}()`:r?`!function(){try{${h}var e=localStorage.getItem('${t}');if('system'===e||(!e&&${d})){var t='${ub}',m=window.matchMedia(t);if(m.media!==t||m.matches){${g("dark")}}else{${g("light")}}}else if(e){${s?`var x=${JSON.stringify(s)};`:""}${g(s?"x[e]":"e",!0)}}${d?"":"else{"+g(i,!1,!1)+"}"}${m}}catch(e){}}()`:`!function(){try{${h}var e=localStorage.getItem('${t}');if(e){${s?`var x=${JSON.stringify(s)};`:""}${g(s?"x[e]":"e",!0)}}else{${g(i,!1,!1)};}${m}}catch(t){}}();`;return Fe.createElement("script",{nonce:u,dangerouslySetInnerHTML:{__html:y}})},()=>!0),s$=(e,t)=>{if(ite)return;let n;try{n=localStorage.getItem(e)||void 0}catch{}return n||t},ute=()=>{const e=document.createElement("style");return e.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(e),()=>{window.getComputedStyle(document.body),setTimeout(()=>{document.head.removeChild(e)},1)}},a$=e=>(e||(e=window.matchMedia(ub)),e.matches?"dark":"light"),dte=new dL;z0.createRoot(document.getElementById("root")).render(v.jsx(Fe.StrictMode,{children:v.jsx(gL,{client:dte,children:v.jsx(ste,{defaultTheme:"dark",disableTransitionOnChange:!0,children:v.jsx(UU,{children:v.jsx(ote,{})})})})})); diff --git a/py/iopaint/web_app/assets/index-QuEBEP4v.js b/py/iopaint/web_app/assets/index-QuEBEP4v.js new file mode 100644 index 0000000..9f09c0b --- /dev/null +++ b/py/iopaint/web_app/assets/index-QuEBEP4v.js @@ -0,0 +1,165 @@ +var Fv=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)};var j=(e,t,n)=>(Fv(e,t,"read from private field"),n?n.call(e):t.get(e)),Pe=(e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)},ye=(e,t,n,r)=>(Fv(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n);var Wf=(e,t,n,r)=>({set _(o){ye(e,t,o,n)},get _(){return j(e,t,r)}}),tt=(e,t,n)=>(Fv(e,t,"access private method"),n);function $9(e,t){for(var n=0;nr[o]})}}}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 o of document.querySelectorAll('link[rel="modulepreload"]'))r(o);new MutationObserver(o=>{for(const i of o)if(i.type==="childList")for(const s of i.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&r(s)}).observe(document,{childList:!0,subtree:!0});function n(o){const i={};return o.integrity&&(i.integrity=o.integrity),o.referrerPolicy&&(i.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?i.credentials="include":o.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(o){if(o.ep)return;o.ep=!0;const i=n(o);fetch(o.href,i)}})();var Jc=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function dm(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var x$={exports:{}},fm={},b$={exports:{}},it={};/** + * @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 kd=Symbol.for("react.element"),R9=Symbol.for("react.portal"),k9=Symbol.for("react.fragment"),T9=Symbol.for("react.strict_mode"),P9=Symbol.for("react.profiler"),A9=Symbol.for("react.provider"),M9=Symbol.for("react.context"),O9=Symbol.for("react.forward_ref"),N9=Symbol.for("react.suspense"),D9=Symbol.for("react.memo"),I9=Symbol.for("react.lazy"),B_=Symbol.iterator;function L9(e){return e===null||typeof e!="object"?null:(e=B_&&e[B_]||e["@@iterator"],typeof e=="function"?e:null)}var S$={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},_$=Object.assign,E$={};function yc(e,t,n){this.props=e,this.context=t,this.refs=E$,this.updater=n||S$}yc.prototype.isReactComponent={};yc.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")};yc.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function C$(){}C$.prototype=yc.prototype;function nw(e,t,n){this.props=e,this.context=t,this.refs=E$,this.updater=n||S$}var rw=nw.prototype=new C$;rw.constructor=nw;_$(rw,yc.prototype);rw.isPureReactComponent=!0;var U_=Array.isArray,$$=Object.prototype.hasOwnProperty,ow={current:null},R$={key:!0,ref:!0,__self:!0,__source:!0};function k$(e,t,n){var r,o={},i=null,s=null;if(t!=null)for(r in t.ref!==void 0&&(s=t.ref),t.key!==void 0&&(i=""+t.key),t)$$.call(t,r)&&!R$.hasOwnProperty(r)&&(o[r]=t[r]);var l=arguments.length-2;if(l===1)o.children=n;else if(1>>1,pe=H[le];if(0>>1;le<$e;){var Ve=2*(le+1)-1,We=H[Ve],Ne=Ve+1,fe=H[Ne];if(0>o(We,W))Neo(fe,We)?(H[le]=fe,H[Ne]=W,le=Ne):(H[le]=We,H[Ve]=W,le=Ve);else if(Neo(fe,W))H[le]=fe,H[Ne]=W,le=Ne;else break e}}return X}function o(H,X){var W=H.sortIndex-X.sortIndex;return W!==0?W:H.id-X.id}if(typeof performance=="object"&&typeof performance.now=="function"){var i=performance;e.unstable_now=function(){return i.now()}}else{var s=Date,l=s.now();e.unstable_now=function(){return s.now()-l}}var u=[],f=[],p=1,m=null,g=3,y=!1,x=!1,S=!1,E=typeof setTimeout=="function"?setTimeout:null,_=typeof clearTimeout=="function"?clearTimeout:null,b=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function C(H){for(var X=n(f);X!==null;){if(X.callback===null)r(f);else if(X.startTime<=H)r(f),X.sortIndex=X.expirationTime,t(u,X);else break;X=n(f)}}function R(H){if(S=!1,C(H),!x)if(n(u)!==null)x=!0,M(P);else{var X=n(f);X!==null&&ee(R,X.startTime-H)}}function P(H,X){x=!1,S&&(S=!1,_(D),D=-1),y=!0;var W=g;try{for(C(X),m=n(u);m!==null&&(!(m.expirationTime>X)||H&&!J());){var le=m.callback;if(typeof le=="function"){m.callback=null,g=m.priorityLevel;var pe=le(m.expirationTime<=X);X=e.unstable_now(),typeof pe=="function"?m.callback=pe:m===n(u)&&r(u),C(X)}else r(u);m=n(u)}if(m!==null)var $e=!0;else{var Ve=n(f);Ve!==null&&ee(R,Ve.startTime-X),$e=!1}return $e}finally{m=null,g=W,y=!1}}var O=!1,A=null,D=-1,B=5,V=-1;function J(){return!(e.unstable_now()-VH||125le?(H.sortIndex=W,t(f,H),n(u)===null&&H===n(f)&&(S?(_(D),D=-1):S=!0,ee(R,W-le))):(H.sortIndex=pe,t(u,H),x||y||(x=!0,M(P))),H},e.unstable_shouldYield=J,e.unstable_wrapCallback=function(H){var X=g;return function(){var W=g;g=X;try{return H.apply(this,arguments)}finally{g=W}}}})(M$);A$.exports=M$;var X9=A$.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 O$=d,yr=X9;function ce(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"),H0=Object.prototype.hasOwnProperty,Z9=/^[: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]*$/,W_={},H_={};function q9(e){return H0.call(H_,e)?!0:H0.call(W_,e)?!1:Z9.test(e)?H_[e]=!0:(W_[e]=!0,!1)}function Q9(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 J9(e,t,n,r){if(t===null||typeof t>"u"||Q9(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 Un(e,t,n,r,o,i,s){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=o,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=i,this.removeEmptyString=s}var bn={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){bn[e]=new Un(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];bn[t]=new Un(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){bn[e]=new Un(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){bn[e]=new Un(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){bn[e]=new Un(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){bn[e]=new Un(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){bn[e]=new Un(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){bn[e]=new Un(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){bn[e]=new Un(e,5,!1,e.toLowerCase(),null,!1,!1)});var sw=/[\-:]([a-z])/g;function aw(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(sw,aw);bn[t]=new Un(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(sw,aw);bn[t]=new Un(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(sw,aw);bn[t]=new Un(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){bn[e]=new Un(e,1,!1,e.toLowerCase(),null,!1,!1)});bn.xlinkHref=new Un("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){bn[e]=new Un(e,1,!1,e.toLowerCase(),null,!0,!0)});function lw(e,t,n,r){var o=bn.hasOwnProperty(t)?bn[t]:null;(o!==null?o.type!==0:r||!(2l||o[s]!==i[l]){var u=` +`+o[s].replace(" at new "," at ");return e.displayName&&u.includes("")&&(u=u.replace("",e.displayName)),u}while(1<=s&&0<=l);break}}}finally{Bv=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?vu(e):""}function eD(e){switch(e.tag){case 5:return vu(e.type);case 16:return vu("Lazy");case 13:return vu("Suspense");case 19:return vu("SuspenseList");case 0:case 2:case 15:return e=Uv(e.type,!1),e;case 11:return e=Uv(e.type.render,!1),e;case 1:return e=Uv(e.type,!0),e;default:return""}}function X0(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 ml:return"Fragment";case pl:return"Portal";case K0:return"Profiler";case cw:return"StrictMode";case G0:return"Suspense";case Y0:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case I$:return(e.displayName||"Context")+".Consumer";case D$:return(e._context.displayName||"Context")+".Provider";case uw:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case dw:return t=e.displayName||null,t!==null?t:X0(e.type)||"Memo";case Ji:t=e._payload,e=e._init;try{return X0(e(t))}catch{}}return null}function tD(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 X0(t);case 8:return t===cw?"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 Rs(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function F$(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function nD(e){var t=F$(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 o=n.get,i=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return o.call(this)},set:function(s){r=""+s,i.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 Gf(e){e._valueTracker||(e._valueTracker=nD(e))}function j$(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=F$(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function ap(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 Z0(e,t){var n=t.checked;return zt({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function G_(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=Rs(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 z$(e,t){t=t.checked,t!=null&&lw(e,"checked",t,!1)}function q0(e,t){z$(e,t);var n=Rs(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")?Q0(e,t.type,n):t.hasOwnProperty("defaultValue")&&Q0(e,t.type,Rs(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function Y_(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 Q0(e,t,n){(t!=="number"||ap(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var yu=Array.isArray;function Rl(e,t,n,r){if(e=e.options,t){t={};for(var o=0;o"+t.valueOf().toString()+"",t=Yf.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function ju(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var Eu={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},rD=["Webkit","ms","Moz","O"];Object.keys(Eu).forEach(function(e){rD.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),Eu[t]=Eu[e]})});function W$(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||Eu.hasOwnProperty(e)&&Eu[e]?(""+t).trim():t+"px"}function H$(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,o=W$(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,o):e[n]=o}}var oD=zt({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 ty(e,t){if(t){if(oD[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(ce(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(ce(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(ce(61))}if(t.style!=null&&typeof t.style!="object")throw Error(ce(62))}}function ny(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 ry=null;function fw(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var oy=null,kl=null,Tl=null;function q_(e){if(e=Ad(e)){if(typeof oy!="function")throw Error(ce(280));var t=e.stateNode;t&&(t=vm(t),oy(e.stateNode,e.type,t))}}function K$(e){kl?Tl?Tl.push(e):Tl=[e]:kl=e}function G$(){if(kl){var e=kl,t=Tl;if(Tl=kl=null,q_(e),t)for(e=0;e>>=0,e===0?32:31-(mD(e)/gD|0)|0}var Xf=64,Zf=4194304;function wu(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 dp(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,o=e.suspendedLanes,i=e.pingedLanes,s=n&268435455;if(s!==0){var l=s&~o;l!==0?r=wu(l):(i&=s,i!==0&&(r=wu(i)))}else s=n&~o,s!==0?r=wu(s):i!==0&&(r=wu(i));if(r===0)return 0;if(t!==0&&t!==r&&!(t&o)&&(o=r&-r,i=t&-t,o>=i||o===16&&(i&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 Td(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-wo(t),e[t]=n}function xD(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=$u),sE=" ",aE=!1;function h5(e,t){switch(e){case"keyup":return YD.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function p5(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var gl=!1;function ZD(e,t){switch(e){case"compositionend":return p5(t);case"keypress":return t.which!==32?null:(aE=!0,sE);case"textInput":return e=t.data,e===sE&&aE?null:e;default:return null}}function qD(e,t){if(gl)return e==="compositionend"||!xw&&h5(e,t)?(e=d5(),Mh=vw=us=null,gl=!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=dE(n)}}function y5(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?y5(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function w5(){for(var e=window,t=ap();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=ap(e.document)}return t}function bw(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 sI(e){var t=w5(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&y5(n.ownerDocument.documentElement,n)){if(r!==null&&bw(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 o=n.textContent.length,i=Math.min(r.start,o);r=r.end===void 0?i:Math.min(r.end,o),!e.extend&&i>r&&(o=r,r=i,i=o),o=fE(n,i);var s=fE(n,r);o&&s&&(e.rangeCount!==1||e.anchorNode!==o.node||e.anchorOffset!==o.offset||e.focusNode!==s.node||e.focusOffset!==s.offset)&&(t=t.createRange(),t.setStart(o.node,o.offset),e.removeAllRanges(),i>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,vl=null,uy=null,ku=null,dy=!1;function hE(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;dy||vl==null||vl!==ap(r)||(r=vl,"selectionStart"in r&&bw(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}),ku&&Hu(ku,r)||(ku=r,r=pp(uy,"onSelect"),0xl||(e.current=vy[xl],vy[xl]=null,xl--)}function $t(e,t){xl++,vy[xl]=e.current,e.current=t}var ks={},Pn=Ns(ks),Jn=Ns(!1),Ra=ks;function Ql(e,t){var n=e.type.contextTypes;if(!n)return ks;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var o={},i;for(i in n)o[i]=t[i];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=o),o}function er(e){return e=e.childContextTypes,e!=null}function gp(){At(Jn),At(Pn)}function xE(e,t,n){if(Pn.current!==ks)throw Error(ce(168));$t(Pn,t),$t(Jn,n)}function k5(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var o in r)if(!(o in t))throw Error(ce(108,tD(e)||"Unknown",o));return zt({},n,r)}function vp(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||ks,Ra=Pn.current,$t(Pn,e),$t(Jn,Jn.current),!0}function bE(e,t,n){var r=e.stateNode;if(!r)throw Error(ce(169));n?(e=k5(e,t,Ra),r.__reactInternalMemoizedMergedChildContext=e,At(Jn),At(Pn),$t(Pn,e)):At(Jn),$t(Jn,n)}var pi=null,ym=!1,n0=!1;function T5(e){pi===null?pi=[e]:pi.push(e)}function yI(e){ym=!0,T5(e)}function Ds(){if(!n0&&pi!==null){n0=!0;var e=0,t=bt;try{var n=pi;for(bt=1;e>=s,o-=s,mi=1<<32-wo(t)+o|n<D?(B=A,A=null):B=A.sibling;var V=g(_,A,C[D],R);if(V===null){A===null&&(A=B);break}e&&A&&V.alternate===null&&t(_,A),b=i(V,b,D),O===null?P=V:O.sibling=V,O=V,A=B}if(D===C.length)return n(_,A),Dt&&ta(_,D),P;if(A===null){for(;DD?(B=A,A=null):B=A.sibling;var J=g(_,A,V.value,R);if(J===null){A===null&&(A=B);break}e&&A&&J.alternate===null&&t(_,A),b=i(J,b,D),O===null?P=J:O.sibling=J,O=J,A=B}if(V.done)return n(_,A),Dt&&ta(_,D),P;if(A===null){for(;!V.done;D++,V=C.next())V=m(_,V.value,R),V!==null&&(b=i(V,b,D),O===null?P=V:O.sibling=V,O=V);return Dt&&ta(_,D),P}for(A=r(_,A);!V.done;D++,V=C.next())V=y(A,_,D,V.value,R),V!==null&&(e&&V.alternate!==null&&A.delete(V.key===null?D:V.key),b=i(V,b,D),O===null?P=V:O.sibling=V,O=V);return e&&A.forEach(function(G){return t(_,G)}),Dt&&ta(_,D),P}function E(_,b,C,R){if(typeof C=="object"&&C!==null&&C.type===ml&&C.key===null&&(C=C.props.children),typeof C=="object"&&C!==null){switch(C.$$typeof){case Kf:e:{for(var P=C.key,O=b;O!==null;){if(O.key===P){if(P=C.type,P===ml){if(O.tag===7){n(_,O.sibling),b=o(O,C.props.children),b.return=_,_=b;break e}}else if(O.elementType===P||typeof P=="object"&&P!==null&&P.$$typeof===Ji&&kE(P)===O.type){n(_,O.sibling),b=o(O,C.props),b.ref=iu(_,O,C),b.return=_,_=b;break e}n(_,O);break}else t(_,O);O=O.sibling}C.type===ml?(b=$a(C.props.children,_.mode,R,C.key),b.return=_,_=b):(R=zh(C.type,C.key,C.props,null,_.mode,R),R.ref=iu(_,b,C),R.return=_,_=R)}return s(_);case pl:e:{for(O=C.key;b!==null;){if(b.key===O)if(b.tag===4&&b.stateNode.containerInfo===C.containerInfo&&b.stateNode.implementation===C.implementation){n(_,b.sibling),b=o(b,C.children||[]),b.return=_,_=b;break e}else{n(_,b);break}else t(_,b);b=b.sibling}b=u0(C,_.mode,R),b.return=_,_=b}return s(_);case Ji:return O=C._init,E(_,b,O(C._payload),R)}if(yu(C))return x(_,b,C,R);if(eu(C))return S(_,b,C,R);rh(_,C)}return typeof C=="string"&&C!==""||typeof C=="number"?(C=""+C,b!==null&&b.tag===6?(n(_,b.sibling),b=o(b,C),b.return=_,_=b):(n(_,b),b=c0(C,_.mode,R),b.return=_,_=b),s(_)):n(_,b)}return E}var ec=L5(!0),F5=L5(!1),Md={},Ko=Ns(Md),Xu=Ns(Md),Zu=Ns(Md);function fa(e){if(e===Md)throw Error(ce(174));return e}function Pw(e,t){switch($t(Zu,t),$t(Xu,e),$t(Ko,Md),e=t.nodeType,e){case 9:case 11:t=(t=t.documentElement)?t.namespaceURI:ey(null,"");break;default:e=e===8?t.parentNode:t,t=e.namespaceURI||null,e=e.tagName,t=ey(t,e)}At(Ko),$t(Ko,t)}function tc(){At(Ko),At(Xu),At(Zu)}function j5(e){fa(Zu.current);var t=fa(Ko.current),n=ey(t,e.type);t!==n&&($t(Xu,e),$t(Ko,n))}function Aw(e){Xu.current===e&&(At(Ko),At(Xu))}var Lt=Ns(0);function _p(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 r0=[];function Mw(){for(var e=0;en?n:4,e(!0);var r=o0.transition;o0.transition={};try{e(!1),t()}finally{bt=n,o0.transition=r}}function tR(){return Yr().memoizedState}function SI(e,t,n){var r=Ss(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},nR(e))rR(t,n);else if(n=O5(e,t,n,r),n!==null){var o=jn();xo(n,e,r,o),oR(n,t,r)}}function _I(e,t,n){var r=Ss(e),o={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(nR(e))rR(t,o);else{var i=e.alternate;if(e.lanes===0&&(i===null||i.lanes===0)&&(i=t.lastRenderedReducer,i!==null))try{var s=t.lastRenderedState,l=i(s,n);if(o.hasEagerState=!0,o.eagerState=l,So(l,s)){var u=t.interleaved;u===null?(o.next=o,kw(t)):(o.next=u.next,u.next=o),t.interleaved=o;return}}catch{}finally{}n=O5(e,t,o,r),n!==null&&(o=jn(),xo(n,e,r,o),oR(n,t,r))}}function nR(e){var t=e.alternate;return e===jt||t!==null&&t===jt}function rR(e,t){Tu=Ep=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function oR(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,pw(e,n)}}var Cp={readContext:Gr,useCallback:$n,useContext:$n,useEffect:$n,useImperativeHandle:$n,useInsertionEffect:$n,useLayoutEffect:$n,useMemo:$n,useReducer:$n,useRef:$n,useState:$n,useDebugValue:$n,useDeferredValue:$n,useTransition:$n,useMutableSource:$n,useSyncExternalStore:$n,useId:$n,unstable_isNewReconciler:!1},EI={readContext:Gr,useCallback:function(e,t){return Po().memoizedState=[e,t===void 0?null:t],e},useContext:Gr,useEffect:PE,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,Ih(4194308,4,Z5.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Ih(4194308,4,e,t)},useInsertionEffect:function(e,t){return Ih(4,2,e,t)},useMemo:function(e,t){var n=Po();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=Po();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=SI.bind(null,jt,e),[r.memoizedState,e]},useRef:function(e){var t=Po();return e={current:e},t.memoizedState=e},useState:TE,useDebugValue:Lw,useDeferredValue:function(e){return Po().memoizedState=e},useTransition:function(){var e=TE(!1),t=e[0];return e=bI.bind(null,e[1]),Po().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=jt,o=Po();if(Dt){if(n===void 0)throw Error(ce(407));n=n()}else{if(n=t(),dn===null)throw Error(ce(349));Ta&30||U5(r,t,n)}o.memoizedState=n;var i={value:n,getSnapshot:t};return o.queue=i,PE(W5.bind(null,r,i,e),[e]),r.flags|=2048,Ju(9,V5.bind(null,r,i,n,t),void 0,null),n},useId:function(){var e=Po(),t=dn.identifierPrefix;if(Dt){var n=gi,r=mi;n=(r&~(1<<32-wo(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=qu++,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[Io]=t,e[Yu]=r,hR(e,t,!1,!1),t.stateNode=e;e:{switch(s=ny(n,r),n){case"dialog":Tt("cancel",e),Tt("close",e),o=r;break;case"iframe":case"object":case"embed":Tt("load",e),o=r;break;case"video":case"audio":for(o=0;orc&&(t.flags|=128,r=!0,su(i,!1),t.lanes=4194304)}else{if(!r)if(e=_p(s),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),su(i,!0),i.tail===null&&i.tailMode==="hidden"&&!s.alternate&&!Dt)return Rn(t),null}else 2*Xt()-i.renderingStartTime>rc&&n!==1073741824&&(t.flags|=128,r=!0,su(i,!1),t.lanes=4194304);i.isBackwards?(s.sibling=t.child,t.child=s):(n=i.last,n!==null?n.sibling=s:t.child=s,i.last=s)}return i.tail!==null?(t=i.tail,i.rendering=t,i.tail=t.sibling,i.renderingStartTime=Xt(),t.sibling=null,n=Lt.current,$t(Lt,r?n&1|2:n&1),t):(Rn(t),null);case 22:case 23:return Vw(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?fr&1073741824&&(Rn(t),t.subtreeFlags&6&&(t.flags|=8192)):Rn(t),null;case 24:return null;case 25:return null}throw Error(ce(156,t.tag))}function MI(e,t){switch(_w(t),t.tag){case 1:return er(t.type)&&gp(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return tc(),At(Jn),At(Pn),Mw(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return Aw(t),null;case 13:if(At(Lt),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(ce(340));Jl()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return At(Lt),null;case 4:return tc(),null;case 10:return Rw(t.type._context),null;case 22:case 23:return Vw(),null;case 24:return null;default:return null}}var ih=!1,Tn=!1,OI=typeof WeakSet=="function"?WeakSet:Set,Ee=null;function El(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){Wt(e,t,r)}else n.current=null}function Ty(e,t,n){try{n()}catch(r){Wt(e,t,r)}}var jE=!1;function NI(e,t){if(fy=fp,e=w5(),bw(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 o=r.anchorOffset,i=r.focusNode;r=r.focusOffset;try{n.nodeType,i.nodeType}catch{n=null;break e}var s=0,l=-1,u=-1,f=0,p=0,m=e,g=null;t:for(;;){for(var y;m!==n||o!==0&&m.nodeType!==3||(l=s+o),m!==i||r!==0&&m.nodeType!==3||(u=s+r),m.nodeType===3&&(s+=m.nodeValue.length),(y=m.firstChild)!==null;)g=m,m=y;for(;;){if(m===e)break t;if(g===n&&++f===o&&(l=s),g===i&&++p===r&&(u=s),(y=m.nextSibling)!==null)break;m=g,g=m.parentNode}m=y}n=l===-1||u===-1?null:{start:l,end:u}}else n=null}n=n||{start:0,end:0}}else n=null;for(hy={focusedElem:e,selectionRange:n},fp=!1,Ee=t;Ee!==null;)if(t=Ee,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,Ee=e;else for(;Ee!==null;){t=Ee;try{var x=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(x!==null){var S=x.memoizedProps,E=x.memoizedState,_=t.stateNode,b=_.getSnapshotBeforeUpdate(t.elementType===t.type?S:io(t.type,S),E);_.__reactInternalSnapshotBeforeUpdate=b}break;case 3:var C=t.stateNode.containerInfo;C.nodeType===1?C.textContent="":C.nodeType===9&&C.documentElement&&C.removeChild(C.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(ce(163))}}catch(R){Wt(t,t.return,R)}if(e=t.sibling,e!==null){e.return=t.return,Ee=e;break}Ee=t.return}return x=jE,jE=!1,x}function Pu(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var o=r=r.next;do{if((o.tag&e)===e){var i=o.destroy;o.destroy=void 0,i!==void 0&&Ty(t,n,i)}o=o.next}while(o!==r)}}function bm(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 Py(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 gR(e){var t=e.alternate;t!==null&&(e.alternate=null,gR(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Io],delete t[Yu],delete t[gy],delete t[gI],delete t[vI])),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 vR(e){return e.tag===5||e.tag===3||e.tag===4}function zE(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||vR(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 Ay(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=mp));else if(r!==4&&(e=e.child,e!==null))for(Ay(e,t,n),e=e.sibling;e!==null;)Ay(e,t,n),e=e.sibling}function My(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(My(e,t,n),e=e.sibling;e!==null;)My(e,t,n),e=e.sibling}var mn=null,lo=!1;function Ki(e,t,n){for(n=n.child;n!==null;)yR(e,t,n),n=n.sibling}function yR(e,t,n){if(Ho&&typeof Ho.onCommitFiberUnmount=="function")try{Ho.onCommitFiberUnmount(hm,n)}catch{}switch(n.tag){case 5:Tn||El(n,t);case 6:var r=mn,o=lo;mn=null,Ki(e,t,n),mn=r,lo=o,mn!==null&&(lo?(e=mn,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):mn.removeChild(n.stateNode));break;case 18:mn!==null&&(lo?(e=mn,n=n.stateNode,e.nodeType===8?t0(e.parentNode,n):e.nodeType===1&&t0(e,n),Vu(e)):t0(mn,n.stateNode));break;case 4:r=mn,o=lo,mn=n.stateNode.containerInfo,lo=!0,Ki(e,t,n),mn=r,lo=o;break;case 0:case 11:case 14:case 15:if(!Tn&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){o=r=r.next;do{var i=o,s=i.destroy;i=i.tag,s!==void 0&&(i&2||i&4)&&Ty(n,t,s),o=o.next}while(o!==r)}Ki(e,t,n);break;case 1:if(!Tn&&(El(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(l){Wt(n,t,l)}Ki(e,t,n);break;case 21:Ki(e,t,n);break;case 22:n.mode&1?(Tn=(r=Tn)||n.memoizedState!==null,Ki(e,t,n),Tn=r):Ki(e,t,n);break;default:Ki(e,t,n)}}function BE(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new OI),t.forEach(function(r){var o=VI.bind(null,e,r);n.has(r)||(n.add(r),r.then(o,o))})}}function ro(e,t){var n=t.deletions;if(n!==null)for(var r=0;ro&&(o=s),r&=~i}if(r=o,r=Xt()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*II(r/1960))-r,10e?16:e,ds===null)var r=!1;else{if(e=ds,ds=null,kp=0,dt&6)throw Error(ce(331));var o=dt;for(dt|=4,Ee=e.current;Ee!==null;){var i=Ee,s=i.child;if(Ee.flags&16){var l=i.deletions;if(l!==null){for(var u=0;uXt()-Bw?Ca(e,0):zw|=n),tr(e,t)}function $R(e,t){t===0&&(e.mode&1?(t=Zf,Zf<<=1,!(Zf&130023424)&&(Zf=4194304)):t=1);var n=jn();e=_i(e,t),e!==null&&(Td(e,t,n),tr(e,n))}function UI(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),$R(e,n)}function VI(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,o=e.memoizedState;o!==null&&(n=o.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(ce(314))}r!==null&&r.delete(t),$R(e,n)}var RR;RR=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||Jn.current)Qn=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return Qn=!1,PI(e,t,n);Qn=!!(e.flags&131072)}else Qn=!1,Dt&&t.flags&1048576&&P5(t,wp,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;Lh(e,t),e=t.pendingProps;var o=Ql(t,Pn.current);Al(t,n),o=Nw(null,t,r,e,o,n);var i=Dw();return t.flags|=1,typeof o=="object"&&o!==null&&typeof o.render=="function"&&o.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,er(r)?(i=!0,vp(t)):i=!1,t.memoizedState=o.state!==null&&o.state!==void 0?o.state:null,Tw(t),o.updater=wm,t.stateNode=o,o._reactInternals=t,Sy(t,r,e,n),t=Cy(null,t,r,!0,i,n)):(t.tag=0,Dt&&i&&Sw(t),In(null,t,o,n),t=t.child),t;case 16:r=t.elementType;e:{switch(Lh(e,t),e=t.pendingProps,o=r._init,r=o(r._payload),t.type=r,o=t.tag=HI(r),e=io(r,e),o){case 0:t=Ey(null,t,r,e,n);break e;case 1:t=IE(null,t,r,e,n);break e;case 11:t=NE(null,t,r,e,n);break e;case 14:t=DE(null,t,r,io(r.type,e),n);break e}throw Error(ce(306,r,""))}return t;case 0:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),Ey(e,t,r,o,n);case 1:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),IE(e,t,r,o,n);case 3:e:{if(uR(t),e===null)throw Error(ce(387));r=t.pendingProps,i=t.memoizedState,o=i.element,N5(e,t),Sp(t,r,null,n);var s=t.memoizedState;if(r=s.element,i.isDehydrated)if(i={element:r,isDehydrated:!1,cache:s.cache,pendingSuspenseBoundaries:s.pendingSuspenseBoundaries,transitions:s.transitions},t.updateQueue.baseState=i,t.memoizedState=i,t.flags&256){o=nc(Error(ce(423)),t),t=LE(e,t,r,n,o);break e}else if(r!==o){o=nc(Error(ce(424)),t),t=LE(e,t,r,n,o);break e}else for(mr=ws(t.stateNode.containerInfo.firstChild),gr=t,Dt=!0,ho=null,n=F5(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(Jl(),r===o){t=Ei(e,t,n);break e}In(e,t,r,n)}t=t.child}return t;case 5:return j5(t),e===null&&wy(t),r=t.type,o=t.pendingProps,i=e!==null?e.memoizedProps:null,s=o.children,py(r,o)?s=null:i!==null&&py(r,i)&&(t.flags|=32),cR(e,t),In(e,t,s,n),t.child;case 6:return e===null&&wy(t),null;case 13:return dR(e,t,n);case 4:return Pw(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=ec(t,null,r,n):In(e,t,r,n),t.child;case 11:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),NE(e,t,r,o,n);case 7:return In(e,t,t.pendingProps,n),t.child;case 8:return In(e,t,t.pendingProps.children,n),t.child;case 12:return In(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,o=t.pendingProps,i=t.memoizedProps,s=o.value,$t(xp,r._currentValue),r._currentValue=s,i!==null)if(So(i.value,s)){if(i.children===o.children&&!Jn.current){t=Ei(e,t,n);break e}}else for(i=t.child,i!==null&&(i.return=t);i!==null;){var l=i.dependencies;if(l!==null){s=i.child;for(var u=l.firstContext;u!==null;){if(u.context===r){if(i.tag===1){u=wi(-1,n&-n),u.tag=2;var f=i.updateQueue;if(f!==null){f=f.shared;var p=f.pending;p===null?u.next=u:(u.next=p.next,p.next=u),f.pending=u}}i.lanes|=n,u=i.alternate,u!==null&&(u.lanes|=n),xy(i.return,n,t),l.lanes|=n;break}u=u.next}}else if(i.tag===10)s=i.type===t.type?null:i.child;else if(i.tag===18){if(s=i.return,s===null)throw Error(ce(341));s.lanes|=n,l=s.alternate,l!==null&&(l.lanes|=n),xy(s,n,t),s=i.sibling}else s=i.child;if(s!==null)s.return=i;else for(s=i;s!==null;){if(s===t){s=null;break}if(i=s.sibling,i!==null){i.return=s.return,s=i;break}s=s.return}i=s}In(e,t,o.children,n),t=t.child}return t;case 9:return o=t.type,r=t.pendingProps.children,Al(t,n),o=Gr(o),r=r(o),t.flags|=1,In(e,t,r,n),t.child;case 14:return r=t.type,o=io(r,t.pendingProps),o=io(r.type,o),DE(e,t,r,o,n);case 15:return aR(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),Lh(e,t),t.tag=1,er(r)?(e=!0,vp(t)):e=!1,Al(t,n),I5(t,r,o),Sy(t,r,o,n),Cy(null,t,r,!0,e,n);case 19:return fR(e,t,n);case 22:return lR(e,t,n)}throw Error(ce(156,t.tag))};function kR(e,t){return e5(e,t)}function WI(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 Ur(e,t,n,r){return new WI(e,t,n,r)}function Hw(e){return e=e.prototype,!(!e||!e.isReactComponent)}function HI(e){if(typeof e=="function")return Hw(e)?1:0;if(e!=null){if(e=e.$$typeof,e===uw)return 11;if(e===dw)return 14}return 2}function _s(e,t){var n=e.alternate;return n===null?(n=Ur(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 zh(e,t,n,r,o,i){var s=2;if(r=e,typeof e=="function")Hw(e)&&(s=1);else if(typeof e=="string")s=5;else e:switch(e){case ml:return $a(n.children,o,i,t);case cw:s=8,o|=8;break;case K0:return e=Ur(12,n,t,o|2),e.elementType=K0,e.lanes=i,e;case G0:return e=Ur(13,n,t,o),e.elementType=G0,e.lanes=i,e;case Y0:return e=Ur(19,n,t,o),e.elementType=Y0,e.lanes=i,e;case L$:return _m(n,o,i,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case D$:s=10;break e;case I$:s=9;break e;case uw:s=11;break e;case dw:s=14;break e;case Ji:s=16,r=null;break e}throw Error(ce(130,e==null?e:typeof e,""))}return t=Ur(s,n,t,o),t.elementType=e,t.type=r,t.lanes=i,t}function $a(e,t,n,r){return e=Ur(7,e,r,t),e.lanes=n,e}function _m(e,t,n,r){return e=Ur(22,e,r,t),e.elementType=L$,e.lanes=n,e.stateNode={isHidden:!1},e}function c0(e,t,n){return e=Ur(6,e,null,t),e.lanes=n,e}function u0(e,t,n){return t=Ur(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function KI(e,t,n,r,o){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=Wv(0),this.expirationTimes=Wv(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Wv(0),this.identifierPrefix=r,this.onRecoverableError=o,this.mutableSourceEagerHydrationData=null}function Kw(e,t,n,r,o,i,s,l,u){return e=new KI(e,t,n,l,u),t===1?(t=1,i===!0&&(t|=8)):t=0,i=Ur(3,null,null,t),e.current=i,i.stateNode=e,i.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},Tw(i),e}function GI(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(MR)}catch(e){console.error(e)}}MR(),P$.exports=br;var Is=P$.exports;const QI=dm(Is);var XE=Is;W0.createRoot=XE.createRoot,W0.hydrateRoot=XE.hydrateRoot;var Od=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},oc=typeof window>"u"||"Deno"in window;function Lr(){}function JI(e,t){return typeof e=="function"?e(t):e}function Ly(e){return typeof e=="number"&&e>=0&&e!==1/0}function OR(e,t){return Math.max(e+(t||0)-Date.now(),0)}function ZE(e,t){const{type:n="all",exact:r,fetchStatus:o,predicate:i,queryKey:s,stale:l}=e;if(s){if(r){if(t.queryHash!==Zw(s,t.options))return!1}else if(!nd(t.queryKey,s))return!1}if(n!=="all"){const u=t.isActive();if(n==="active"&&!u||n==="inactive"&&u)return!1}return!(typeof l=="boolean"&&t.isStale()!==l||typeof o<"u"&&o!==t.state.fetchStatus||i&&!i(t))}function qE(e,t){const{exact:n,status:r,predicate:o,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(td(t.options.mutationKey)!==td(i))return!1}else if(!nd(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||o&&!o(t))}function Zw(e,t){return((t==null?void 0:t.queryKeyHashFn)||td)(e)}function td(e){return JSON.stringify(e,(t,n)=>jy(n)?Object.keys(n).sort().reduce((r,o)=>(r[o]=n[o],r),{}):n)}function nd(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?!Object.keys(t).some(n=>!nd(e[n],t[n])):!1}function NR(e,t){if(e===t)return e;const n=QE(e)&&QE(t);if(n||jy(e)&&jy(t)){const r=n?e.length:Object.keys(e).length,o=n?t:Object.keys(t),i=o.length,s=n?[]:{};let l=0;for(let u=0;u"u")return!0;const n=t.prototype;return!(!JE(n)||!n.hasOwnProperty("isPrototypeOf"))}function JE(e){return Object.prototype.toString.call(e)==="[object Object]"}function DR(e){return new Promise(t=>{setTimeout(t,e)})}function eC(e){DR(0).then(e)}function zy(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?NR(e,t):t}function eL(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function tL(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var ga,rs,Il,d$,nL=(d$=class extends Od{constructor(){super();Pe(this,ga,void 0);Pe(this,rs,void 0);Pe(this,Il,void 0);ye(this,Il,t=>{if(!oc&&window.addEventListener){const n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){j(this,rs)||this.setEventListener(j(this,Il))}onUnsubscribe(){var t;this.hasListeners()||((t=j(this,rs))==null||t.call(this),ye(this,rs,void 0))}setEventListener(t){var n;ye(this,Il,t),(n=j(this,rs))==null||n.call(this),ye(this,rs,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){j(this,ga)!==t&&(ye(this,ga,t),this.onFocus())}onFocus(){this.listeners.forEach(t=>{t()})}isFocused(){var t;return typeof j(this,ga)=="boolean"?j(this,ga):((t=globalThis.document)==null?void 0:t.visibilityState)!=="hidden"}},ga=new WeakMap,rs=new WeakMap,Il=new WeakMap,d$),Ap=new nL,Ll,os,Fl,f$,rL=(f$=class extends Od{constructor(){super();Pe(this,Ll,!0);Pe(this,os,void 0);Pe(this,Fl,void 0);ye(this,Fl,t=>{if(!oc&&window.addEventListener){const n=()=>t(!0),r=()=>t(!1);return window.addEventListener("online",n,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",r)}}})}onSubscribe(){j(this,os)||this.setEventListener(j(this,Fl))}onUnsubscribe(){var t;this.hasListeners()||((t=j(this,os))==null||t.call(this),ye(this,os,void 0))}setEventListener(t){var n;ye(this,Fl,t),(n=j(this,os))==null||n.call(this),ye(this,os,t(this.setOnline.bind(this)))}setOnline(t){j(this,Ll)!==t&&(ye(this,Ll,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return j(this,Ll)}},Ll=new WeakMap,os=new WeakMap,Fl=new WeakMap,f$),Mp=new rL;function oL(e){return Math.min(1e3*2**e,3e4)}function km(e){return(e??"online")==="online"?Mp.isOnline():!0}var IR=class{constructor(e){this.revert=e==null?void 0:e.revert,this.silent=e==null?void 0:e.silent}};function d0(e){return e instanceof IR}function LR(e){let t=!1,n=0,r=!1,o,i,s;const l=new Promise((E,_)=>{i=E,s=_}),u=E=>{var _;r||(y(new IR(E)),(_=e.abort)==null||_.call(e))},f=()=>{t=!0},p=()=>{t=!1},m=()=>!Ap.isFocused()||e.networkMode!=="always"&&!Mp.isOnline(),g=E=>{var _;r||(r=!0,(_=e.onSuccess)==null||_.call(e,E),o==null||o(),i(E))},y=E=>{var _;r||(r=!0,(_=e.onError)==null||_.call(e,E),o==null||o(),s(E))},x=()=>new Promise(E=>{var _;o=b=>{const C=r||!m();return C&&E(b),C},(_=e.onPause)==null||_.call(e)}).then(()=>{var E;o=void 0,r||(E=e.onContinue)==null||E.call(e)}),S=()=>{if(r)return;let E;try{E=e.fn()}catch(_){E=Promise.reject(_)}Promise.resolve(E).then(g).catch(_=>{var O;if(r)return;const b=e.retry??(oc?0:3),C=e.retryDelay??oL,R=typeof C=="function"?C(n,_):C,P=b===!0||typeof b=="number"&&n{if(m())return x()}).then(()=>{t?y(_):S()})})};return km(e.networkMode)?S():x().then(S),{promise:l,cancel:u,continue:()=>(o==null?void 0:o())?l:Promise.resolve(),cancelRetry:f,continueRetry:p}}function iL(){let e=[],t=0,n=p=>{p()},r=p=>{p()};const o=p=>{let m;t++;try{m=p()}finally{t--,t||l()}return m},i=p=>{t?e.push(p):eC(()=>{n(p)})},s=p=>(...m)=>{i(()=>{p(...m)})},l=()=>{const p=e;e=[],p.length&&eC(()=>{r(()=>{p.forEach(m=>{n(m)})})})};return{batch:o,batchCalls:s,schedule:i,setNotifyFunction:p=>{n=p},setBatchNotifyFunction:p=>{r=p}}}var vn=iL(),va,h$,FR=(h$=class{constructor(){Pe(this,va,void 0)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Ly(this.gcTime)&&ye(this,va,setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(oc?1/0:5*60*1e3))}clearGcTimeout(){j(this,va)&&(clearTimeout(j(this,va)),ye(this,va,void 0))}},va=new WeakMap,h$),jl,zl,Nr,is,Dr,cn,vd,ya,Bl,Bh,ao,di,p$,sL=(p$=class extends FR{constructor(t){super();Pe(this,Bl);Pe(this,ao);Pe(this,jl,void 0);Pe(this,zl,void 0);Pe(this,Nr,void 0);Pe(this,is,void 0);Pe(this,Dr,void 0);Pe(this,cn,void 0);Pe(this,vd,void 0);Pe(this,ya,void 0);ye(this,ya,!1),ye(this,vd,t.defaultOptions),tt(this,Bl,Bh).call(this,t.options),ye(this,cn,[]),ye(this,Nr,t.cache),this.queryKey=t.queryKey,this.queryHash=t.queryHash,ye(this,jl,t.state||aL(this.options)),this.state=j(this,jl),this.scheduleGc()}get meta(){return this.options.meta}optionalRemove(){!j(this,cn).length&&this.state.fetchStatus==="idle"&&j(this,Nr).remove(this)}setData(t,n){const r=zy(this.state.data,t,this.options);return tt(this,ao,di).call(this,{data:r,type:"success",dataUpdatedAt:n==null?void 0:n.updatedAt,manual:n==null?void 0:n.manual}),r}setState(t,n){tt(this,ao,di).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){var r;const n=j(this,is);return(r=j(this,Dr))==null||r.cancel(t),n?n.then(Lr).catch(Lr):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(j(this,jl))}isActive(){return j(this,cn).some(t=>t.options.enabled!==!1)}isDisabled(){return this.getObserversCount()>0&&!this.isActive()}isStale(){return this.state.isInvalidated||!this.state.dataUpdatedAt||j(this,cn).some(t=>t.getCurrentResult().isStale)}isStaleByTime(t=0){return this.state.isInvalidated||!this.state.dataUpdatedAt||!OR(this.state.dataUpdatedAt,t)}onFocus(){var n;const t=j(this,cn).find(r=>r.shouldFetchOnWindowFocus());t==null||t.refetch({cancelRefetch:!1}),(n=j(this,Dr))==null||n.continue()}onOnline(){var n;const t=j(this,cn).find(r=>r.shouldFetchOnReconnect());t==null||t.refetch({cancelRefetch:!1}),(n=j(this,Dr))==null||n.continue()}addObserver(t){j(this,cn).includes(t)||(j(this,cn).push(t),this.clearGcTimeout(),j(this,Nr).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){j(this,cn).includes(t)&&(ye(this,cn,j(this,cn).filter(n=>n!==t)),j(this,cn).length||(j(this,Dr)&&(j(this,ya)?j(this,Dr).cancel({revert:!0}):j(this,Dr).cancelRetry()),this.scheduleGc()),j(this,Nr).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return j(this,cn).length}invalidate(){this.state.isInvalidated||tt(this,ao,di).call(this,{type:"invalidate"})}fetch(t,n){var f,p,m,g;if(this.state.fetchStatus!=="idle"){if(this.state.dataUpdatedAt&&(n!=null&&n.cancelRefetch))this.cancel({silent:!0});else if(j(this,is))return(f=j(this,Dr))==null||f.continueRetry(),j(this,is)}if(t&&tt(this,Bl,Bh).call(this,t),!this.options.queryFn){const y=j(this,cn).find(x=>x.options.queryFn);y&&tt(this,Bl,Bh).call(this,y.options)}const r=new AbortController,o={queryKey:this.queryKey,meta:this.meta},i=y=>{Object.defineProperty(y,"signal",{enumerable:!0,get:()=>(ye(this,ya,!0),r.signal)})};i(o);const s=()=>this.options.queryFn?(ye(this,ya,!1),this.options.persister?this.options.persister(this.options.queryFn,o,this):this.options.queryFn(o)):Promise.reject(new Error(`Missing queryFn: '${this.options.queryHash}'`)),l={fetchOptions:n,options:this.options,queryKey:this.queryKey,state:this.state,fetchFn:s};i(l),(p=this.options.behavior)==null||p.onFetch(l,this),ye(this,zl,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((m=l.fetchOptions)==null?void 0:m.meta))&&tt(this,ao,di).call(this,{type:"fetch",meta:(g=l.fetchOptions)==null?void 0:g.meta});const u=y=>{var x,S,E,_;d0(y)&&y.silent||tt(this,ao,di).call(this,{type:"error",error:y}),d0(y)||((S=(x=j(this,Nr).config).onError)==null||S.call(x,y,this),(_=(E=j(this,Nr).config).onSettled)==null||_.call(E,this.state.data,y,this)),this.isFetchingOptimistic||this.scheduleGc(),this.isFetchingOptimistic=!1};return ye(this,Dr,LR({fn:l.fetchFn,abort:r.abort.bind(r),onSuccess:y=>{var x,S,E,_;if(typeof y>"u"){u(new Error(`${this.queryHash} data is undefined`));return}this.setData(y),(S=(x=j(this,Nr).config).onSuccess)==null||S.call(x,y,this),(_=(E=j(this,Nr).config).onSettled)==null||_.call(E,y,this.state.error,this),this.isFetchingOptimistic||this.scheduleGc(),this.isFetchingOptimistic=!1},onError:u,onFail:(y,x)=>{tt(this,ao,di).call(this,{type:"failed",failureCount:y,error:x})},onPause:()=>{tt(this,ao,di).call(this,{type:"pause"})},onContinue:()=>{tt(this,ao,di).call(this,{type:"continue"})},retry:l.options.retry,retryDelay:l.options.retryDelay,networkMode:l.options.networkMode})),ye(this,is,j(this,Dr).promise),j(this,is)}},jl=new WeakMap,zl=new WeakMap,Nr=new WeakMap,is=new WeakMap,Dr=new WeakMap,cn=new WeakMap,vd=new WeakMap,ya=new WeakMap,Bl=new WeakSet,Bh=function(t){this.options={...j(this,vd),...t},this.updateGcTime(this.options.gcTime)},ao=new WeakSet,di=function(t){const n=r=>{switch(t.type){case"failed":return{...r,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...r,fetchStatus:"paused"};case"continue":return{...r,fetchStatus:"fetching"};case"fetch":return{...r,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:t.meta??null,fetchStatus:km(this.options.networkMode)?"fetching":"paused",...!r.dataUpdatedAt&&{error:null,status:"pending"}};case"success":return{...r,data:t.data,dataUpdateCount:r.dataUpdateCount+1,dataUpdatedAt:t.dataUpdatedAt??Date.now(),error:null,isInvalidated:!1,status:"success",...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};case"error":const o=t.error;return d0(o)&&o.revert&&j(this,zl)?{...j(this,zl),fetchStatus:"idle"}:{...r,error:o,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:o,fetchStatus:"idle",status:"error"};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...t.state}}};this.state=n(this.state),vn.batch(()=>{j(this,cn).forEach(r=>{r.onQueryUpdate()}),j(this,Nr).notify({query:this,type:"updated",action:t})})},p$);function aL(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=typeof t<"u",r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var Mo,m$,lL=(m$=class extends Od{constructor(t={}){super();Pe(this,Mo,void 0);this.config=t,ye(this,Mo,new Map)}build(t,n,r){const o=n.queryKey,i=n.queryHash??Zw(o,n);let s=this.get(i);return s||(s=new sL({cache:this,queryKey:o,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(o)}),this.add(s)),s}add(t){j(this,Mo).has(t.queryHash)||(j(this,Mo).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){const n=j(this,Mo).get(t.queryHash);n&&(t.destroy(),n===t&&j(this,Mo).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){vn.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return j(this,Mo).get(t)}getAll(){return[...j(this,Mo).values()]}find(t){const n={exact:!0,...t};return this.getAll().find(r=>ZE(n,r))}findAll(t={}){const n=this.getAll();return Object.keys(t).length>0?n.filter(r=>ZE(t,r)):n}notify(t){vn.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){vn.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){vn.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},Mo=new WeakMap,m$),Oo,yd,dr,Ul,No,qi,g$,cL=(g$=class extends FR{constructor(t){super();Pe(this,No);Pe(this,Oo,void 0);Pe(this,yd,void 0);Pe(this,dr,void 0);Pe(this,Ul,void 0);this.mutationId=t.mutationId,ye(this,yd,t.defaultOptions),ye(this,dr,t.mutationCache),ye(this,Oo,[]),this.state=t.state||uL(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options={...j(this,yd),...t},this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){j(this,Oo).includes(t)||(j(this,Oo).push(t),this.clearGcTimeout(),j(this,dr).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){ye(this,Oo,j(this,Oo).filter(n=>n!==t)),this.scheduleGc(),j(this,dr).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){j(this,Oo).length||(this.state.status==="pending"?this.scheduleGc():j(this,dr).remove(this))}continue(){var t;return((t=j(this,Ul))==null?void 0:t.continue())??this.execute(this.state.variables)}async execute(t){var o,i,s,l,u,f,p,m,g,y,x,S,E,_,b,C,R,P,O,A;const n=()=>(ye(this,Ul,LR({fn:()=>this.options.mutationFn?this.options.mutationFn(t):Promise.reject(new Error("No mutationFn found")),onFail:(D,B)=>{tt(this,No,qi).call(this,{type:"failed",failureCount:D,error:B})},onPause:()=>{tt(this,No,qi).call(this,{type:"pause"})},onContinue:()=>{tt(this,No,qi).call(this,{type:"continue"})},retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode})),j(this,Ul).promise),r=this.state.status==="pending";try{if(!r){tt(this,No,qi).call(this,{type:"pending",variables:t}),await((i=(o=j(this,dr).config).onMutate)==null?void 0:i.call(o,t,this));const B=await((l=(s=this.options).onMutate)==null?void 0:l.call(s,t));B!==this.state.context&&tt(this,No,qi).call(this,{type:"pending",context:B,variables:t})}const D=await n();return await((f=(u=j(this,dr).config).onSuccess)==null?void 0:f.call(u,D,t,this.state.context,this)),await((m=(p=this.options).onSuccess)==null?void 0:m.call(p,D,t,this.state.context)),await((y=(g=j(this,dr).config).onSettled)==null?void 0:y.call(g,D,null,this.state.variables,this.state.context,this)),await((S=(x=this.options).onSettled)==null?void 0:S.call(x,D,null,t,this.state.context)),tt(this,No,qi).call(this,{type:"success",data:D}),D}catch(D){try{throw await((_=(E=j(this,dr).config).onError)==null?void 0:_.call(E,D,t,this.state.context,this)),await((C=(b=this.options).onError)==null?void 0:C.call(b,D,t,this.state.context)),await((P=(R=j(this,dr).config).onSettled)==null?void 0:P.call(R,void 0,D,this.state.variables,this.state.context,this)),await((A=(O=this.options).onSettled)==null?void 0:A.call(O,void 0,D,t,this.state.context)),D}finally{tt(this,No,qi).call(this,{type:"error",error:D})}}}},Oo=new WeakMap,yd=new WeakMap,dr=new WeakMap,Ul=new WeakMap,No=new WeakSet,qi=function(t){const n=r=>{switch(t.type){case"failed":return{...r,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};case"pending":return{...r,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:!km(this.options.networkMode),status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...r,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:t.error,failureCount:r.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}};this.state=n(this.state),vn.batch(()=>{j(this,Oo).forEach(r=>{r.onMutationUpdate(t)}),j(this,dr).notify({mutation:this,type:"updated",action:t})})},g$);function uL(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Ir,wd,wa,v$,dL=(v$=class extends Od{constructor(t={}){super();Pe(this,Ir,void 0);Pe(this,wd,void 0);Pe(this,wa,void 0);this.config=t,ye(this,Ir,[]),ye(this,wd,0)}build(t,n,r){const o=new cL({mutationCache:this,mutationId:++Wf(this,wd)._,options:t.defaultMutationOptions(n),state:r});return this.add(o),o}add(t){j(this,Ir).push(t),this.notify({type:"added",mutation:t})}remove(t){ye(this,Ir,j(this,Ir).filter(n=>n!==t)),this.notify({type:"removed",mutation:t})}clear(){vn.batch(()=>{j(this,Ir).forEach(t=>{this.remove(t)})})}getAll(){return j(this,Ir)}find(t){const n={exact:!0,...t};return j(this,Ir).find(r=>qE(n,r))}findAll(t={}){return j(this,Ir).filter(n=>qE(t,n))}notify(t){vn.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){return ye(this,wa,(j(this,wa)??Promise.resolve()).then(()=>{const t=j(this,Ir).filter(n=>n.state.isPaused);return vn.batch(()=>t.reduce((n,r)=>n.then(()=>r.continue().catch(Lr)),Promise.resolve()))}).then(()=>{ye(this,wa,void 0)})),j(this,wa)}},Ir=new WeakMap,wd=new WeakMap,wa=new WeakMap,v$);function fL(e){return{onFetch:(t,n)=>{const r=async()=>{var x,S,E,_,b;const o=t.options,i=(E=(S=(x=t.fetchOptions)==null?void 0:x.meta)==null?void 0:S.fetchMore)==null?void 0:E.direction,s=((_=t.state.data)==null?void 0:_.pages)||[],l=((b=t.state.data)==null?void 0:b.pageParams)||[],u={pages:[],pageParams:[]};let f=!1;const p=C=>{Object.defineProperty(C,"signal",{enumerable:!0,get:()=>(t.signal.aborted?f=!0:t.signal.addEventListener("abort",()=>{f=!0}),t.signal)})},m=t.options.queryFn||(()=>Promise.reject(new Error(`Missing queryFn: '${t.options.queryHash}'`))),g=async(C,R,P)=>{if(f)return Promise.reject();if(R==null&&C.pages.length)return Promise.resolve(C);const O={queryKey:t.queryKey,pageParam:R,direction:P?"backward":"forward",meta:t.options.meta};p(O);const A=await m(O),{maxPages:D}=t.options,B=P?tL:eL;return{pages:B(C.pages,A,D),pageParams:B(C.pageParams,R,D)}};let y;if(i&&s.length){const C=i==="backward",R=C?hL:tC,P={pages:s,pageParams:l},O=R(o,P);y=await g(P,O,C)}else{y=await g(u,l[0]??o.initialPageParam);const C=e??s.length;for(let R=1;R{var o,i;return(i=(o=t.options).persister)==null?void 0:i.call(o,r,{queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n)}:t.fetchFn=r}}}function tC(e,{pages:t,pageParams:n}){const r=t.length-1;return e.getNextPageParam(t[r],t,n[r],n)}function hL(e,{pages:t,pageParams:n}){var r;return(r=e.getPreviousPageParam)==null?void 0:r.call(e,t[0],t,n[0],n)}var nn,ss,as,Vl,Wl,ls,Hl,Kl,y$,pL=(y$=class{constructor(e={}){Pe(this,nn,void 0);Pe(this,ss,void 0);Pe(this,as,void 0);Pe(this,Vl,void 0);Pe(this,Wl,void 0);Pe(this,ls,void 0);Pe(this,Hl,void 0);Pe(this,Kl,void 0);ye(this,nn,e.queryCache||new lL),ye(this,ss,e.mutationCache||new dL),ye(this,as,e.defaultOptions||{}),ye(this,Vl,new Map),ye(this,Wl,new Map),ye(this,ls,0)}mount(){Wf(this,ls)._++,j(this,ls)===1&&(ye(this,Hl,Ap.subscribe(()=>{Ap.isFocused()&&(this.resumePausedMutations(),j(this,nn).onFocus())})),ye(this,Kl,Mp.subscribe(()=>{Mp.isOnline()&&(this.resumePausedMutations(),j(this,nn).onOnline())})))}unmount(){var e,t;Wf(this,ls)._--,j(this,ls)===0&&((e=j(this,Hl))==null||e.call(this),ye(this,Hl,void 0),(t=j(this,Kl))==null||t.call(this),ye(this,Kl,void 0))}isFetching(e){return j(this,nn).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return j(this,ss).findAll({...e,status:"pending"}).length}getQueryData(e){var t;return(t=j(this,nn).find({queryKey:e}))==null?void 0:t.state.data}ensureQueryData(e){const t=this.getQueryData(e.queryKey);return t!==void 0?Promise.resolve(t):this.fetchQuery(e)}getQueriesData(e){return this.getQueryCache().findAll(e).map(({queryKey:t,state:n})=>{const r=n.data;return[t,r]})}setQueryData(e,t,n){const r=j(this,nn).find({queryKey:e}),o=r==null?void 0:r.state.data,i=JI(t,o);if(typeof i>"u")return;const s=this.defaultQueryOptions({queryKey:e});return j(this,nn).build(this,s).setData(i,{...n,manual:!0})}setQueriesData(e,t,n){return vn.batch(()=>this.getQueryCache().findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){var t;return(t=j(this,nn).find({queryKey:e}))==null?void 0:t.state}removeQueries(e){const t=j(this,nn);vn.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=j(this,nn),r={type:"active",...e};return vn.batch(()=>(n.findAll(e).forEach(o=>{o.reset()}),this.refetchQueries(r,t)))}cancelQueries(e={},t={}){const n={revert:!0,...t},r=vn.batch(()=>j(this,nn).findAll(e).map(o=>o.cancel(n)));return Promise.all(r).then(Lr).catch(Lr)}invalidateQueries(e={},t={}){return vn.batch(()=>{if(j(this,nn).findAll(e).forEach(r=>{r.invalidate()}),e.refetchType==="none")return Promise.resolve();const n={...e,type:e.refetchType??e.type??"active"};return this.refetchQueries(n,t)})}refetchQueries(e={},t){const n={...t,cancelRefetch:(t==null?void 0:t.cancelRefetch)??!0},r=vn.batch(()=>j(this,nn).findAll(e).filter(o=>!o.isDisabled()).map(o=>{let i=o.fetch(void 0,n);return n.throwOnError||(i=i.catch(Lr)),o.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(Lr)}fetchQuery(e){const t=this.defaultQueryOptions(e);typeof t.retry>"u"&&(t.retry=!1);const n=j(this,nn).build(this,t);return n.isStaleByTime(t.staleTime)?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Lr).catch(Lr)}fetchInfiniteQuery(e){return e.behavior=fL(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Lr).catch(Lr)}resumePausedMutations(){return j(this,ss).resumePausedMutations()}getQueryCache(){return j(this,nn)}getMutationCache(){return j(this,ss)}getDefaultOptions(){return j(this,as)}setDefaultOptions(e){ye(this,as,e)}setQueryDefaults(e,t){j(this,Vl).set(td(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...j(this,Vl).values()];let n={};return t.forEach(r=>{nd(e,r.queryKey)&&(n={...n,...r.defaultOptions})}),n}setMutationDefaults(e,t){j(this,Wl).set(td(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...j(this,Wl).values()];let n={};return t.forEach(r=>{nd(e,r.mutationKey)&&(n={...n,...r.defaultOptions})}),n}defaultQueryOptions(e){if(e!=null&&e._defaulted)return e;const t={...j(this,as).queries,...(e==null?void 0:e.queryKey)&&this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Zw(t.queryKey,t)),typeof t.refetchOnReconnect>"u"&&(t.refetchOnReconnect=t.networkMode!=="always"),typeof t.throwOnError>"u"&&(t.throwOnError=!!t.suspense),typeof t.networkMode>"u"&&t.persister&&(t.networkMode="offlineFirst"),t}defaultMutationOptions(e){return e!=null&&e._defaulted?e:{...j(this,as).mutations,...(e==null?void 0:e.mutationKey)&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){j(this,nn).clear(),j(this,ss).clear()}},nn=new WeakMap,ss=new WeakMap,as=new WeakMap,Vl=new WeakMap,Wl=new WeakMap,ls=new WeakMap,Hl=new WeakMap,Kl=new WeakMap,y$),Xn,Ct,Gl,kn,xa,Yl,Do,xd,Xl,Zl,ba,Sa,cs,_a,Ea,bu,bd,By,Sd,Uy,_d,Vy,Ed,Wy,Cd,Hy,$d,Ky,Rd,Gy,um,jR,w$,mL=(w$=class extends Od{constructor(t,n){super();Pe(this,Ea);Pe(this,bd);Pe(this,Sd);Pe(this,_d);Pe(this,Ed);Pe(this,Cd);Pe(this,$d);Pe(this,Rd);Pe(this,um);Pe(this,Xn,void 0);Pe(this,Ct,void 0);Pe(this,Gl,void 0);Pe(this,kn,void 0);Pe(this,xa,void 0);Pe(this,Yl,void 0);Pe(this,Do,void 0);Pe(this,xd,void 0);Pe(this,Xl,void 0);Pe(this,Zl,void 0);Pe(this,ba,void 0);Pe(this,Sa,void 0);Pe(this,cs,void 0);Pe(this,_a,void 0);ye(this,Ct,void 0),ye(this,Gl,void 0),ye(this,kn,void 0),ye(this,_a,new Set),ye(this,Xn,t),this.options=n,ye(this,Do,null),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(j(this,Ct).addObserver(this),nC(j(this,Ct),this.options)?tt(this,Ea,bu).call(this):this.updateResult(),tt(this,Ed,Wy).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Yy(j(this,Ct),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Yy(j(this,Ct),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,tt(this,Cd,Hy).call(this),tt(this,$d,Ky).call(this),j(this,Ct).removeObserver(this)}setOptions(t,n){const r=this.options,o=j(this,Ct);if(this.options=j(this,Xn).defaultQueryOptions(t),Fy(r,this.options)||j(this,Xn).getQueryCache().notify({type:"observerOptionsUpdated",query:j(this,Ct),observer:this}),typeof this.options.enabled<"u"&&typeof this.options.enabled!="boolean")throw new Error("Expected enabled to be a boolean");this.options.queryKey||(this.options.queryKey=r.queryKey),tt(this,Rd,Gy).call(this);const i=this.hasListeners();i&&rC(j(this,Ct),o,this.options,r)&&tt(this,Ea,bu).call(this),this.updateResult(n),i&&(j(this,Ct)!==o||this.options.enabled!==r.enabled||this.options.staleTime!==r.staleTime)&&tt(this,bd,By).call(this);const s=tt(this,Sd,Uy).call(this);i&&(j(this,Ct)!==o||this.options.enabled!==r.enabled||s!==j(this,cs))&&tt(this,_d,Vy).call(this,s)}getOptimisticResult(t){const n=j(this,Xn).getQueryCache().build(j(this,Xn),t),r=this.createResult(n,t);return vL(this,r)&&(ye(this,kn,r),ye(this,Yl,this.options),ye(this,xa,j(this,Ct).state)),r}getCurrentResult(){return j(this,kn)}trackResult(t){const n={};return Object.keys(t).forEach(r=>{Object.defineProperty(n,r,{configurable:!1,enumerable:!0,get:()=>(j(this,_a).add(r),t[r])})}),n}getCurrentQuery(){return j(this,Ct)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){const n=j(this,Xn).defaultQueryOptions(t),r=j(this,Xn).getQueryCache().build(j(this,Xn),n);return r.isFetchingOptimistic=!0,r.fetch().then(()=>this.createResult(r,n))}fetch(t){return tt(this,Ea,bu).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),j(this,kn)))}createResult(t,n){var O;const r=j(this,Ct),o=this.options,i=j(this,kn),s=j(this,xa),l=j(this,Yl),f=t!==r?t.state:j(this,Gl),{state:p}=t;let{error:m,errorUpdatedAt:g,fetchStatus:y,status:x}=p,S=!1,E;if(n._optimisticResults){const A=this.hasListeners(),D=!A&&nC(t,n),B=A&&rC(t,r,n,o);(D||B)&&(y=km(t.options.networkMode)?"fetching":"paused",p.dataUpdatedAt||(x="pending")),n._optimisticResults==="isRestoring"&&(y="idle")}if(n.select&&typeof p.data<"u")if(i&&p.data===(s==null?void 0:s.data)&&n.select===j(this,xd))E=j(this,Xl);else try{ye(this,xd,n.select),E=n.select(p.data),E=zy(i==null?void 0:i.data,E,n),ye(this,Xl,E),ye(this,Do,null)}catch(A){ye(this,Do,A)}else E=p.data;if(typeof n.placeholderData<"u"&&typeof E>"u"&&x==="pending"){let A;if(i!=null&&i.isPlaceholderData&&n.placeholderData===(l==null?void 0:l.placeholderData))A=i.data;else if(A=typeof n.placeholderData=="function"?n.placeholderData((O=j(this,Zl))==null?void 0:O.state.data,j(this,Zl)):n.placeholderData,n.select&&typeof A<"u")try{A=n.select(A),ye(this,Do,null)}catch(D){ye(this,Do,D)}typeof A<"u"&&(x="success",E=zy(i==null?void 0:i.data,A,n),S=!0)}j(this,Do)&&(m=j(this,Do),E=j(this,Xl),g=Date.now(),x="error");const _=y==="fetching",b=x==="pending",C=x==="error",R=b&&_;return{status:x,fetchStatus:y,isPending:b,isSuccess:x==="success",isError:C,isInitialLoading:R,isLoading:R,data:E,dataUpdatedAt:p.dataUpdatedAt,error:m,errorUpdatedAt:g,failureCount:p.fetchFailureCount,failureReason:p.fetchFailureReason,errorUpdateCount:p.errorUpdateCount,isFetched:p.dataUpdateCount>0||p.errorUpdateCount>0,isFetchedAfterMount:p.dataUpdateCount>f.dataUpdateCount||p.errorUpdateCount>f.errorUpdateCount,isFetching:_,isRefetching:_&&!b,isLoadingError:C&&p.dataUpdatedAt===0,isPaused:y==="paused",isPlaceholderData:S,isRefetchError:C&&p.dataUpdatedAt!==0,isStale:qw(t,n),refetch:this.refetch}}updateResult(t){const n=j(this,kn),r=this.createResult(j(this,Ct),this.options);if(ye(this,xa,j(this,Ct).state),ye(this,Yl,this.options),j(this,xa).data!==void 0&&ye(this,Zl,j(this,Ct)),Fy(r,n))return;ye(this,kn,r);const o={},i=()=>{if(!n)return!0;const{notifyOnChangeProps:s}=this.options,l=typeof s=="function"?s():s;if(l==="all"||!l&&!j(this,_a).size)return!0;const u=new Set(l??j(this,_a));return this.options.throwOnError&&u.add("error"),Object.keys(j(this,kn)).some(f=>{const p=f;return j(this,kn)[p]!==n[p]&&u.has(p)})};(t==null?void 0:t.listeners)!==!1&&i()&&(o.listeners=!0),tt(this,um,jR).call(this,{...o,...t})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&tt(this,Ed,Wy).call(this)}},Xn=new WeakMap,Ct=new WeakMap,Gl=new WeakMap,kn=new WeakMap,xa=new WeakMap,Yl=new WeakMap,Do=new WeakMap,xd=new WeakMap,Xl=new WeakMap,Zl=new WeakMap,ba=new WeakMap,Sa=new WeakMap,cs=new WeakMap,_a=new WeakMap,Ea=new WeakSet,bu=function(t){tt(this,Rd,Gy).call(this);let n=j(this,Ct).fetch(this.options,t);return t!=null&&t.throwOnError||(n=n.catch(Lr)),n},bd=new WeakSet,By=function(){if(tt(this,Cd,Hy).call(this),oc||j(this,kn).isStale||!Ly(this.options.staleTime))return;const n=OR(j(this,kn).dataUpdatedAt,this.options.staleTime)+1;ye(this,ba,setTimeout(()=>{j(this,kn).isStale||this.updateResult()},n))},Sd=new WeakSet,Uy=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(j(this,Ct)):this.options.refetchInterval)??!1},_d=new WeakSet,Vy=function(t){tt(this,$d,Ky).call(this),ye(this,cs,t),!(oc||this.options.enabled===!1||!Ly(j(this,cs))||j(this,cs)===0)&&ye(this,Sa,setInterval(()=>{(this.options.refetchIntervalInBackground||Ap.isFocused())&&tt(this,Ea,bu).call(this)},j(this,cs)))},Ed=new WeakSet,Wy=function(){tt(this,bd,By).call(this),tt(this,_d,Vy).call(this,tt(this,Sd,Uy).call(this))},Cd=new WeakSet,Hy=function(){j(this,ba)&&(clearTimeout(j(this,ba)),ye(this,ba,void 0))},$d=new WeakSet,Ky=function(){j(this,Sa)&&(clearInterval(j(this,Sa)),ye(this,Sa,void 0))},Rd=new WeakSet,Gy=function(){const t=j(this,Xn).getQueryCache().build(j(this,Xn),this.options);if(t===j(this,Ct))return;const n=j(this,Ct);ye(this,Ct,t),ye(this,Gl,t.state),this.hasListeners()&&(n==null||n.removeObserver(this),t.addObserver(this))},um=new WeakSet,jR=function(t){vn.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(j(this,kn))}),j(this,Xn).getQueryCache().notify({query:j(this,Ct),type:"observerResultsUpdated"})})},w$);function gL(e,t){return t.enabled!==!1&&!e.state.dataUpdatedAt&&!(e.state.status==="error"&&t.retryOnMount===!1)}function nC(e,t){return gL(e,t)||e.state.dataUpdatedAt>0&&Yy(e,t,t.refetchOnMount)}function Yy(e,t,n){if(t.enabled!==!1){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&qw(e,t)}return!1}function rC(e,t,n,r){return n.enabled!==!1&&(e!==t||r.enabled===!1)&&(!n.suspense||e.state.status!=="error")&&qw(e,n)}function qw(e,t){return e.isStaleByTime(t.staleTime)}function vL(e,t){return!Fy(e.getCurrentResult(),t)}var zR=d.createContext(void 0),yL=e=>{const t=d.useContext(zR);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},wL=({client:e,children:t})=>(d.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),d.createElement(zR.Provider,{value:e},t)),BR=d.createContext(!1),xL=()=>d.useContext(BR);BR.Provider;function bL(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var SL=d.createContext(bL()),_L=()=>d.useContext(SL);function EL(e,t){return typeof e=="function"?e(...t):!!e}var CL=(e,t)=>{(e.suspense||e.throwOnError)&&(t.isReset()||(e.retryOnMount=!1))},$L=e=>{d.useEffect(()=>{e.clearReset()},[e])},RL=({result:e,errorResetBoundary:t,throwOnError:n,query:r})=>e.isError&&!t.isReset()&&!e.isFetching&&EL(n,[e.error,r]),kL=e=>{e.suspense&&typeof e.staleTime!="number"&&(e.staleTime=1e3)},TL=(e,t)=>(e==null?void 0:e.suspense)&&t.isPending,PL=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function AL(e,t,n){const r=yL(n),o=xL(),i=_L(),s=r.defaultQueryOptions(e);s._optimisticResults=o?"isRestoring":"optimistic",kL(s),CL(s,i),$L(i);const[l]=d.useState(()=>new t(r,s)),u=l.getOptimisticResult(s);if(d.useSyncExternalStore(d.useCallback(f=>{const p=o?()=>{}:l.subscribe(vn.batchCalls(f));return l.updateResult(),p},[l,o]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),d.useEffect(()=>{l.setOptions(s,{listeners:!1})},[s,l]),TL(s,u))throw l.setOptions(s,{listeners:!1}),PL(s,l,i);if(RL({result:u,errorResetBoundary:i,throwOnError:s.throwOnError,query:l.getCurrentQuery()}))throw u.error;return s.notifyOnChangeProps?u:l.trackResult(u)}function ML(e,t){return AL(e,mL,t)}var Ao=(e=>(e.RemoveBG="RemoveBG",e.AnimeSeg="AnimeSeg",e.RealESRGAN="RealESRGAN",e.GFPGAN="GFPGAN",e.RestoreFormer="RestoreFormer",e.InteractiveSeg="InteractiveSeg",e))(Ao||{}),Es=(e=>(e.NAME="name",e.CTIME="ctime",e.MTIME="mtime",e))(Es||{}),Ou=(e=>(e.DESCENDING="desc",e.ASCENDING="asc",e))(Ou||{}),Qw=(e=>(e.ddim="ddim",e.plms="plms",e))(Qw||{}),Jw=(e=>(e.INPAINT_NS="INPAINT_NS",e.INPAINT_TELEA="INPAINT_TELEA",e))(Jw||{}),Ln=(e=>(e.x="x",e.y="y",e.xy="xy",e))(Ln||{}),Ol=(e=>(e.text_guided="text-guided",e.shape_guided="shape-guided",e.object_remove="object-remove",e.outpainting="outpainting",e))(Ol||{});function UR(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;tl(i)))==null?void 0:s.classGroupId}const oC=/^\[(.+)\]$/;function NL(e){if(oC.test(e)){const t=oC.exec(e)[1],n=t==null?void 0:t.substring(0,t.indexOf(":"));if(n)return"arbitrary.."+n}}function DL(e){const{theme:t,prefix:n}=e,r={nextPart:new Map,validators:[]};return LL(Object.entries(e.classGroups),n).forEach(([i,s])=>{Xy(s,r,i,t)}),r}function Xy(e,t,n,r){e.forEach(o=>{if(typeof o=="string"){const i=o===""?t:iC(t,o);i.classGroupId=n;return}if(typeof o=="function"){if(IL(o)){Xy(o(r),t,n,r);return}t.validators.push({validator:o,classGroupId:n});return}Object.entries(o).forEach(([i,s])=>{Xy(s,iC(t,i),n,r)})})}function iC(e,t){let n=e;return t.split(ex).forEach(r=>{n.nextPart.has(r)||n.nextPart.set(r,{nextPart:new Map,validators:[]}),n=n.nextPart.get(r)}),n}function IL(e){return e.isThemeGetter}function LL(e,t){return t?e.map(([n,r])=>{const o=r.map(i=>typeof i=="string"?t+i:typeof i=="object"?Object.fromEntries(Object.entries(i).map(([s,l])=>[t+s,l])):i);return[n,o]}):e}function FL(e){if(e<1)return{get:()=>{},set:()=>{}};let t=0,n=new Map,r=new Map;function o(i,s){n.set(i,s),t++,t>e&&(t=0,r=n,n=new Map)}return{get(i){let s=n.get(i);if(s!==void 0)return s;if((s=r.get(i))!==void 0)return o(i,s),s},set(i,s){n.has(i)?n.set(i,s):o(i,s)}}}const HR="!";function jL(e){const t=e.separator,n=t.length===1,r=t[0],o=t.length;return function(s){const l=[];let u=0,f=0,p;for(let S=0;Sf?p-f:void 0;return{modifiers:l,hasImportantModifier:g,baseClassName:y,maybePostfixModifierPosition:x}}}function zL(e){if(e.length<=1)return e;const t=[];let n=[];return e.forEach(r=>{r[0]==="["?(t.push(...n.sort(),r),n=[]):n.push(r)}),t.push(...n.sort()),t}function BL(e){return{cache:FL(e.cacheSize),splitModifiers:jL(e),...OL(e)}}const UL=/\s+/;function VL(e,t){const{splitModifiers:n,getClassGroupId:r,getConflictingClassGroupIds:o}=t,i=new Set;return e.trim().split(UL).map(s=>{const{modifiers:l,hasImportantModifier:u,baseClassName:f,maybePostfixModifierPosition:p}=n(s);let m=r(p?f.substring(0,p):f),g=!!p;if(!m){if(!p)return{isTailwindClass:!1,originalClassName:s};if(m=r(f),!m)return{isTailwindClass:!1,originalClassName:s};g=!1}const y=zL(l).join(":");return{isTailwindClass:!0,modifierId:u?y+HR:y,classGroupId:m,originalClassName:s,hasPostfixModifier:g}}).reverse().filter(s=>{if(!s.isTailwindClass)return!0;const{modifierId:l,classGroupId:u,hasPostfixModifier:f}=s,p=l+u;return i.has(p)?!1:(i.add(p),o(u,f).forEach(m=>i.add(l+m)),!0)}).reverse().map(s=>s.originalClassName).join(" ")}function WL(){let e=0,t,n,r="";for(;em(p),e());return n=BL(f),r=n.cache.get,o=n.cache.set,i=l,l(u)}function l(u){const f=r(u);if(f)return f;const p=VL(u,n);return o(u,p),p}return function(){return i(WL.apply(null,arguments))}}function kt(e){const t=n=>n[e]||[];return t.isThemeGetter=!0,t}const GR=/^\[(?:([a-z-]+):)?(.+)\]$/i,KL=/^\d+\/\d+$/,GL=new Set(["px","full","screen"]),YL=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,XL=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,ZL=/^-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,qL=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/;function oo(e){return ha(e)||GL.has(e)||KL.test(e)}function Gi(e){return bc(e,"length",iF)}function ha(e){return!!e&&!Number.isNaN(Number(e))}function lh(e){return bc(e,"number",ha)}function lu(e){return!!e&&Number.isInteger(Number(e))}function QL(e){return e.endsWith("%")&&ha(e.slice(0,-1))}function Je(e){return GR.test(e)}function Yi(e){return YL.test(e)}const JL=new Set(["length","size","percentage"]);function eF(e){return bc(e,JL,YR)}function tF(e){return bc(e,"position",YR)}const nF=new Set(["image","url"]);function rF(e){return bc(e,nF,aF)}function oF(e){return bc(e,"",sF)}function cu(){return!0}function bc(e,t,n){const r=GR.exec(e);return r?r[1]?typeof t=="string"?r[1]===t:t.has(r[1]):n(r[2]):!1}function iF(e){return XL.test(e)}function YR(){return!1}function sF(e){return ZL.test(e)}function aF(e){return qL.test(e)}function lF(){const e=kt("colors"),t=kt("spacing"),n=kt("blur"),r=kt("brightness"),o=kt("borderColor"),i=kt("borderRadius"),s=kt("borderSpacing"),l=kt("borderWidth"),u=kt("contrast"),f=kt("grayscale"),p=kt("hueRotate"),m=kt("invert"),g=kt("gap"),y=kt("gradientColorStops"),x=kt("gradientColorStopPositions"),S=kt("inset"),E=kt("margin"),_=kt("opacity"),b=kt("padding"),C=kt("saturate"),R=kt("scale"),P=kt("sepia"),O=kt("skew"),A=kt("space"),D=kt("translate"),B=()=>["auto","contain","none"],V=()=>["auto","hidden","clip","visible","scroll"],J=()=>["auto",Je,t],G=()=>[Je,t],se=()=>["",oo,Gi],U=()=>["auto",ha,Je],ne=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],M=()=>["solid","dashed","dotted","double","none"],ee=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity","plus-lighter"],H=()=>["start","end","center","between","around","evenly","stretch"],X=()=>["","0",Je],W=()=>["auto","avoid","all","avoid-page","page","left","right","column"],le=()=>[ha,lh],pe=()=>[ha,Je];return{cacheSize:500,separator:":",theme:{colors:[cu],spacing:[oo,Gi],blur:["none","",Yi,Je],brightness:le(),borderColor:[e],borderRadius:["none","","full",Yi,Je],borderSpacing:G(),borderWidth:se(),contrast:le(),grayscale:X(),hueRotate:pe(),invert:X(),gap:G(),gradientColorStops:[e],gradientColorStopPositions:[QL,Gi],inset:J(),margin:J(),opacity:le(),padding:G(),saturate:le(),scale:le(),sepia:X(),skew:pe(),space:G(),translate:G()},classGroups:{aspect:[{aspect:["auto","square","video",Je]}],container:["container"],columns:[{columns:[Yi]}],"break-after":[{"break-after":W()}],"break-before":[{"break-before":W()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],float:[{float:["right","left","none"]}],clear:[{clear:["left","right","both","none"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:[...ne(),Je]}],overflow:[{overflow:V()}],"overflow-x":[{"overflow-x":V()}],"overflow-y":[{"overflow-y":V()}],overscroll:[{overscroll:B()}],"overscroll-x":[{"overscroll-x":B()}],"overscroll-y":[{"overscroll-y":B()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[S]}],"inset-x":[{"inset-x":[S]}],"inset-y":[{"inset-y":[S]}],start:[{start:[S]}],end:[{end:[S]}],top:[{top:[S]}],right:[{right:[S]}],bottom:[{bottom:[S]}],left:[{left:[S]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",lu,Je]}],basis:[{basis:J()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",Je]}],grow:[{grow:X()}],shrink:[{shrink:X()}],order:[{order:["first","last","none",lu,Je]}],"grid-cols":[{"grid-cols":[cu]}],"col-start-end":[{col:["auto",{span:["full",lu,Je]},Je]}],"col-start":[{"col-start":U()}],"col-end":[{"col-end":U()}],"grid-rows":[{"grid-rows":[cu]}],"row-start-end":[{row:["auto",{span:[lu,Je]},Je]}],"row-start":[{"row-start":U()}],"row-end":[{"row-end":U()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",Je]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",Je]}],gap:[{gap:[g]}],"gap-x":[{"gap-x":[g]}],"gap-y":[{"gap-y":[g]}],"justify-content":[{justify:["normal",...H()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...H(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...H(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[b]}],px:[{px:[b]}],py:[{py:[b]}],ps:[{ps:[b]}],pe:[{pe:[b]}],pt:[{pt:[b]}],pr:[{pr:[b]}],pb:[{pb:[b]}],pl:[{pl:[b]}],m:[{m:[E]}],mx:[{mx:[E]}],my:[{my:[E]}],ms:[{ms:[E]}],me:[{me:[E]}],mt:[{mt:[E]}],mr:[{mr:[E]}],mb:[{mb:[E]}],ml:[{ml:[E]}],"space-x":[{"space-x":[A]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[A]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit",Je,t]}],"min-w":[{"min-w":["min","max","fit",Je,oo]}],"max-w":[{"max-w":["0","none","full","min","max","fit","prose",{screen:[Yi]},Yi,Je]}],h:[{h:[Je,t,"auto","min","max","fit"]}],"min-h":[{"min-h":["min","max","fit",oo,Je]}],"max-h":[{"max-h":[Je,t,"min","max","fit"]}],"font-size":[{text:["base",Yi,Gi]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",lh]}],"font-family":[{font:[cu]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractons"],tracking:[{tracking:["tighter","tight","normal","wide","wider","widest",Je]}],"line-clamp":[{"line-clamp":["none",ha,lh]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",oo,Je]}],"list-image":[{"list-image":["none",Je]}],"list-style-type":[{list:["none","disc","decimal",Je]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[e]}],"placeholder-opacity":[{"placeholder-opacity":[_]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[e]}],"text-opacity":[{"text-opacity":[_]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...M(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",oo,Gi]}],"underline-offset":[{"underline-offset":["auto",oo,Je]}],"text-decoration-color":[{decoration:[e]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],indent:[{indent:G()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Je]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",Je]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[_]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...ne(),tF]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",eF]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},rF]}],"bg-color":[{bg:[e]}],"gradient-from-pos":[{from:[x]}],"gradient-via-pos":[{via:[x]}],"gradient-to-pos":[{to:[x]}],"gradient-from":[{from:[y]}],"gradient-via":[{via:[y]}],"gradient-to":[{to:[y]}],rounded:[{rounded:[i]}],"rounded-s":[{"rounded-s":[i]}],"rounded-e":[{"rounded-e":[i]}],"rounded-t":[{"rounded-t":[i]}],"rounded-r":[{"rounded-r":[i]}],"rounded-b":[{"rounded-b":[i]}],"rounded-l":[{"rounded-l":[i]}],"rounded-ss":[{"rounded-ss":[i]}],"rounded-se":[{"rounded-se":[i]}],"rounded-ee":[{"rounded-ee":[i]}],"rounded-es":[{"rounded-es":[i]}],"rounded-tl":[{"rounded-tl":[i]}],"rounded-tr":[{"rounded-tr":[i]}],"rounded-br":[{"rounded-br":[i]}],"rounded-bl":[{"rounded-bl":[i]}],"border-w":[{border:[l]}],"border-w-x":[{"border-x":[l]}],"border-w-y":[{"border-y":[l]}],"border-w-s":[{"border-s":[l]}],"border-w-e":[{"border-e":[l]}],"border-w-t":[{"border-t":[l]}],"border-w-r":[{"border-r":[l]}],"border-w-b":[{"border-b":[l]}],"border-w-l":[{"border-l":[l]}],"border-opacity":[{"border-opacity":[_]}],"border-style":[{border:[...M(),"hidden"]}],"divide-x":[{"divide-x":[l]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[l]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[_]}],"divide-style":[{divide:M()}],"border-color":[{border:[o]}],"border-color-x":[{"border-x":[o]}],"border-color-y":[{"border-y":[o]}],"border-color-t":[{"border-t":[o]}],"border-color-r":[{"border-r":[o]}],"border-color-b":[{"border-b":[o]}],"border-color-l":[{"border-l":[o]}],"divide-color":[{divide:[o]}],"outline-style":[{outline:["",...M()]}],"outline-offset":[{"outline-offset":[oo,Je]}],"outline-w":[{outline:[oo,Gi]}],"outline-color":[{outline:[e]}],"ring-w":[{ring:se()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[e]}],"ring-opacity":[{"ring-opacity":[_]}],"ring-offset-w":[{"ring-offset":[oo,Gi]}],"ring-offset-color":[{"ring-offset":[e]}],shadow:[{shadow:["","inner","none",Yi,oF]}],"shadow-color":[{shadow:[cu]}],opacity:[{opacity:[_]}],"mix-blend":[{"mix-blend":ee()}],"bg-blend":[{"bg-blend":ee()}],filter:[{filter:["","none"]}],blur:[{blur:[n]}],brightness:[{brightness:[r]}],contrast:[{contrast:[u]}],"drop-shadow":[{"drop-shadow":["","none",Yi,Je]}],grayscale:[{grayscale:[f]}],"hue-rotate":[{"hue-rotate":[p]}],invert:[{invert:[m]}],saturate:[{saturate:[C]}],sepia:[{sepia:[P]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[n]}],"backdrop-brightness":[{"backdrop-brightness":[r]}],"backdrop-contrast":[{"backdrop-contrast":[u]}],"backdrop-grayscale":[{"backdrop-grayscale":[f]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[p]}],"backdrop-invert":[{"backdrop-invert":[m]}],"backdrop-opacity":[{"backdrop-opacity":[_]}],"backdrop-saturate":[{"backdrop-saturate":[C]}],"backdrop-sepia":[{"backdrop-sepia":[P]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":[s]}],"border-spacing-x":[{"border-spacing-x":[s]}],"border-spacing-y":[{"border-spacing-y":[s]}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["none","all","","colors","opacity","shadow","transform",Je]}],duration:[{duration:pe()}],ease:[{ease:["linear","in","out","in-out",Je]}],delay:[{delay:pe()}],animate:[{animate:["none","spin","ping","pulse","bounce",Je]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[R]}],"scale-x":[{"scale-x":[R]}],"scale-y":[{"scale-y":[R]}],rotate:[{rotate:[lu,Je]}],"translate-x":[{"translate-x":[D]}],"translate-y":[{"translate-y":[D]}],"skew-x":[{"skew-x":[O]}],"skew-y":[{"skew-y":[O]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",Je]}],accent:[{accent:["auto",e]}],appearance:["appearance-none"],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",Je]}],"caret-color":[{caret:[e]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":G()}],"scroll-mx":[{"scroll-mx":G()}],"scroll-my":[{"scroll-my":G()}],"scroll-ms":[{"scroll-ms":G()}],"scroll-me":[{"scroll-me":G()}],"scroll-mt":[{"scroll-mt":G()}],"scroll-mr":[{"scroll-mr":G()}],"scroll-mb":[{"scroll-mb":G()}],"scroll-ml":[{"scroll-ml":G()}],"scroll-p":[{"scroll-p":G()}],"scroll-px":[{"scroll-px":G()}],"scroll-py":[{"scroll-py":G()}],"scroll-ps":[{"scroll-ps":G()}],"scroll-pe":[{"scroll-pe":G()}],"scroll-pt":[{"scroll-pt":G()}],"scroll-pr":[{"scroll-pr":G()}],"scroll-pb":[{"scroll-pb":G()}],"scroll-pl":[{"scroll-pl":G()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",Je]}],fill:[{fill:[e,"none"]}],"stroke-w":[{stroke:[oo,Gi,lh]}],stroke:[{stroke:[e,"none"]}],sr:["sr-only","not-sr-only"]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]}}}const tx=HL(lF),cF=40,fs="inpaint",ch="diffusers_sd",sC="diffusers_sdxl",uh="diffusers_sd_inpaint",aC="diffusers_sdxl_inpaint",f0="diffusers_other",Uh="#ffcc00bb",lC="ldm",cC="cv2",XR="Fantasy-Studio/Paint-by-Example",uF="timbrooks/instruct-pix2pix",dF="Sanster/PowerPaint-V1-stable-diffusion-inpainting",fF="Sanster/AnyText",hF="out of frame, lowres, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, disfigured, gross proportions, malformed limbs, watermark, signature";function _e(...e){return tx(VR(e))}function pF(){async function e(r=""){return(await fetch(r,{method:"GET",cache:"no-cache"})).json()}const t=()=>{const r=document.location;e(r+"/flaskwebgui-keep-server-alive").then(i=>i)},n=3*1e3;t(),setInterval(t,n)}function uC(e){const t=e.split(",")[0].split(":")[1].split(";")[0],n=atob(e.split(",")[1]),r=[];for(let o=0;o{const o=e.src,i=e;i.onload=n,i.onerror=s=>{i.src=o,r(s)},i.src=t})}async function mF(e){const t=URL.createObjectURL(e),n=new Image;return await Vh(n,t),n}function dC(e){return new Promise((t,n)=>{const r=new Image;r.addEventListener("load",()=>{t(r)}),r.addEventListener("error",o=>{n(o)}),r.src=e.toDataURL()})}function gF(e){return new Promise((t,n)=>{const r=new FileReader;r.onload=()=>{const o=new Image;o.onload=()=>{t(o)},o.onerror=()=>{n("无法加载图像。")},o.src=r.result},r.onerror=()=>{n("无法读取文件。")},r.readAsDataURL(e)})}function Nu(e,t,n){return fetch(e).then(function(r){return r.arrayBuffer()}).then(function(r){return new File([r],t,{type:n})})}async function vF(){try{const{state:e}=await navigator.permissions.query({name:"clipboard-write"});return e==="granted"}catch{return!1}}function yF(e,t){return new Promise((n,r)=>e.toBlob(async o=>{o?n(o):r(new Error("Expected toBlob() to be defined"))},t))}const wF=async e=>{const t=[new ClipboardItem({[e.type]:e})];await navigator.clipboard.write(t)};function fC(e){return e.nativeEvent.button===2}function hC(e){return e.nativeEvent.button===1}async function xF(e){const t=await yF(e,"image/png");try{await wF(t)}catch{console.log("Copy image failed!")}}function bF(e,t){const n=document.createElement("a");n.href=e,n.download=t,n.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0,view:window})),setTimeout(()=>{n.remove()},100)}function h0(e){const t=e.nativeEvent;return{x:t.offsetX,y:t.offsetY}}function ZR(e,t,n=Uh){e.strokeStyle=n,e.lineCap="round",e.lineJoin="round",t.forEach(r=>{!(r!=null&&r.pts.length)||!r.size||(e.lineWidth=r.size,e.beginPath(),e.moveTo(r.pts[0].x,r.pts[0].y),r.pts.forEach(o=>e.lineTo(o.x,o.y)),e.stroke())})}const Wh=(e,t,n,r=[],o="white")=>{const i=document.createElement("canvas");i.width=e,i.height=t;const s=i.getContext("2d");if(!s)throw new Error("could not retrieve mask canvas");return r.forEach(l=>{s.drawImage(l,0,0,e,t)}),n.forEach(l=>{ZR(s,l,o)}),i},Du=e=>new Promise((t,n)=>{const r=new FileReader;r.onload=o=>{var s;const i=(s=o.target)==null?void 0:s.result;t(i)},r.onerror=o=>{n(o)},r.readAsDataURL(e)});function qR(e,t){return function(){return e.apply(t,arguments)}}const{toString:SF}=Object.prototype,{getPrototypeOf:nx}=Object,Tm=(e=>t=>{const n=SF.call(t);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),ei=e=>(e=e.toLowerCase(),t=>Tm(t)===e),Pm=e=>t=>typeof t===e,{isArray:Sc}=Array,rd=Pm("undefined");function _F(e){return e!==null&&!rd(e)&&e.constructor!==null&&!rd(e.constructor)&&Kr(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const QR=ei("ArrayBuffer");function EF(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&QR(e.buffer),t}const CF=Pm("string"),Kr=Pm("function"),JR=Pm("number"),Am=e=>e!==null&&typeof e=="object",$F=e=>e===!0||e===!1,Hh=e=>{if(Tm(e)!=="object")return!1;const t=nx(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},RF=ei("Date"),kF=ei("File"),TF=ei("Blob"),PF=ei("FileList"),AF=e=>Am(e)&&Kr(e.pipe),MF=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||Kr(e.append)&&((t=Tm(e))==="formdata"||t==="object"&&Kr(e.toString)&&e.toString()==="[object FormData]"))},OF=ei("URLSearchParams"),NF=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function Nd(e,t,{allOwnKeys:n=!1}={}){if(e===null||typeof e>"u")return;let r,o;if(typeof e!="object"&&(e=[e]),Sc(e))for(r=0,o=e.length;r0;)if(o=n[r],t===o.toLowerCase())return o;return null}const tk=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,nk=e=>!rd(e)&&e!==tk;function Zy(){const{caseless:e}=nk(this)&&this||{},t={},n=(r,o)=>{const i=e&&ek(t,o)||o;Hh(t[i])&&Hh(r)?t[i]=Zy(t[i],r):Hh(r)?t[i]=Zy({},r):Sc(r)?t[i]=r.slice():t[i]=r};for(let r=0,o=arguments.length;r(Nd(t,(o,i)=>{n&&Kr(o)?e[i]=qR(o,n):e[i]=o},{allOwnKeys:r}),e),IF=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),LF=(e,t,n,r)=>{e.prototype=Object.create(t.prototype,r),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),n&&Object.assign(e.prototype,n)},FF=(e,t,n,r)=>{let o,i,s;const l={};if(t=t||{},e==null)return t;do{for(o=Object.getOwnPropertyNames(e),i=o.length;i-- >0;)s=o[i],(!r||r(s,e,t))&&!l[s]&&(t[s]=e[s],l[s]=!0);e=n!==!1&&nx(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},jF=(e,t,n)=>{e=String(e),(n===void 0||n>e.length)&&(n=e.length),n-=t.length;const r=e.indexOf(t,n);return r!==-1&&r===n},zF=e=>{if(!e)return null;if(Sc(e))return e;let t=e.length;if(!JR(t))return null;const n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},BF=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&nx(Uint8Array)),UF=(e,t)=>{const r=(e&&e[Symbol.iterator]).call(e);let o;for(;(o=r.next())&&!o.done;){const i=o.value;t.call(e,i[0],i[1])}},VF=(e,t)=>{let n;const r=[];for(;(n=e.exec(t))!==null;)r.push(n);return r},WF=ei("HTMLFormElement"),HF=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,r,o){return r.toUpperCase()+o}),pC=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),KF=ei("RegExp"),rk=(e,t)=>{const n=Object.getOwnPropertyDescriptors(e),r={};Nd(n,(o,i)=>{let s;(s=t(o,i,e))!==!1&&(r[i]=s||o)}),Object.defineProperties(e,r)},GF=e=>{rk(e,(t,n)=>{if(Kr(e)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;const r=e[n];if(Kr(r)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},YF=(e,t)=>{const n={},r=o=>{o.forEach(i=>{n[i]=!0})};return Sc(e)?r(e):r(String(e).split(t)),n},XF=()=>{},ZF=(e,t)=>(e=+e,Number.isFinite(e)?e:t),p0="abcdefghijklmnopqrstuvwxyz",mC="0123456789",ok={DIGIT:mC,ALPHA:p0,ALPHA_DIGIT:p0+p0.toUpperCase()+mC},qF=(e=16,t=ok.ALPHA_DIGIT)=>{let n="";const{length:r}=t;for(;e--;)n+=t[Math.random()*r|0];return n};function QF(e){return!!(e&&Kr(e.append)&&e[Symbol.toStringTag]==="FormData"&&e[Symbol.iterator])}const JF=e=>{const t=new Array(10),n=(r,o)=>{if(Am(r)){if(t.indexOf(r)>=0)return;if(!("toJSON"in r)){t[o]=r;const i=Sc(r)?[]:{};return Nd(r,(s,l)=>{const u=n(s,o+1);!rd(u)&&(i[l]=u)}),t[o]=void 0,i}}return r};return n(e,0)},ej=ei("AsyncFunction"),tj=e=>e&&(Am(e)||Kr(e))&&Kr(e.then)&&Kr(e.catch),ie={isArray:Sc,isArrayBuffer:QR,isBuffer:_F,isFormData:MF,isArrayBufferView:EF,isString:CF,isNumber:JR,isBoolean:$F,isObject:Am,isPlainObject:Hh,isUndefined:rd,isDate:RF,isFile:kF,isBlob:TF,isRegExp:KF,isFunction:Kr,isStream:AF,isURLSearchParams:OF,isTypedArray:BF,isFileList:PF,forEach:Nd,merge:Zy,extend:DF,trim:NF,stripBOM:IF,inherits:LF,toFlatObject:FF,kindOf:Tm,kindOfTest:ei,endsWith:jF,toArray:zF,forEachEntry:UF,matchAll:VF,isHTMLForm:WF,hasOwnProperty:pC,hasOwnProp:pC,reduceDescriptors:rk,freezeMethods:GF,toObjectSet:YF,toCamelCase:HF,noop:XF,toFiniteNumber:ZF,findKey:ek,global:tk,isContextDefined:nk,ALPHABET:ok,generateString:qF,isSpecCompliantForm:QF,toJSONObject:JF,isAsyncFn:ej,isThenable:tj};function ut(e,t,n,r,o){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),n&&(this.config=n),r&&(this.request=r),o&&(this.response=o)}ie.inherits(ut,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:ie.toJSONObject(this.config),code:this.code,status:this.response&&this.response.status?this.response.status:null}}});const ik=ut.prototype,sk={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{sk[e]={value:e}});Object.defineProperties(ut,sk);Object.defineProperty(ik,"isAxiosError",{value:!0});ut.from=(e,t,n,r,o,i)=>{const s=Object.create(ik);return ie.toFlatObject(e,s,function(u){return u!==Error.prototype},l=>l!=="isAxiosError"),ut.call(s,e.message,t,n,r,o),s.cause=e,s.name=e.name,i&&Object.assign(s,i),s};const nj=null;function qy(e){return ie.isPlainObject(e)||ie.isArray(e)}function ak(e){return ie.endsWith(e,"[]")?e.slice(0,-2):e}function gC(e,t,n){return e?e.concat(t).map(function(o,i){return o=ak(o),!n&&i?"["+o+"]":o}).join(n?".":""):t}function rj(e){return ie.isArray(e)&&!e.some(qy)}const oj=ie.toFlatObject(ie,{},null,function(t){return/^is[A-Z]/.test(t)});function Mm(e,t,n){if(!ie.isObject(e))throw new TypeError("target must be an object");t=t||new FormData,n=ie.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(S,E){return!ie.isUndefined(E[S])});const r=n.metaTokens,o=n.visitor||p,i=n.dots,s=n.indexes,u=(n.Blob||typeof Blob<"u"&&Blob)&&ie.isSpecCompliantForm(t);if(!ie.isFunction(o))throw new TypeError("visitor must be a function");function f(x){if(x===null)return"";if(ie.isDate(x))return x.toISOString();if(!u&&ie.isBlob(x))throw new ut("Blob is not supported. Use a Buffer instead.");return ie.isArrayBuffer(x)||ie.isTypedArray(x)?u&&typeof Blob=="function"?new Blob([x]):Buffer.from(x):x}function p(x,S,E){let _=x;if(x&&!E&&typeof x=="object"){if(ie.endsWith(S,"{}"))S=r?S:S.slice(0,-2),x=JSON.stringify(x);else if(ie.isArray(x)&&rj(x)||(ie.isFileList(x)||ie.endsWith(S,"[]"))&&(_=ie.toArray(x)))return S=ak(S),_.forEach(function(C,R){!(ie.isUndefined(C)||C===null)&&t.append(s===!0?gC([S],R,i):s===null?S:S+"[]",f(C))}),!1}return qy(x)?!0:(t.append(gC(E,S,i),f(x)),!1)}const m=[],g=Object.assign(oj,{defaultVisitor:p,convertValue:f,isVisitable:qy});function y(x,S){if(!ie.isUndefined(x)){if(m.indexOf(x)!==-1)throw Error("Circular reference detected in "+S.join("."));m.push(x),ie.forEach(x,function(_,b){(!(ie.isUndefined(_)||_===null)&&o.call(t,_,ie.isString(b)?b.trim():b,S,g))===!0&&y(_,S?S.concat(b):[b])}),m.pop()}}if(!ie.isObject(e))throw new TypeError("data must be an object");return y(e),t}function vC(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(r){return t[r]})}function rx(e,t){this._pairs=[],e&&Mm(e,this,t)}const lk=rx.prototype;lk.append=function(t,n){this._pairs.push([t,n])};lk.toString=function(t){const n=t?function(r){return t.call(this,r,vC)}:vC;return this._pairs.map(function(o){return n(o[0])+"="+n(o[1])},"").join("&")};function ij(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function ck(e,t,n){if(!t)return e;const r=n&&n.encode||ij,o=n&&n.serialize;let i;if(o?i=o(t,n):i=ie.isURLSearchParams(t)?t.toString():new rx(t,n).toString(r),i){const s=e.indexOf("#");s!==-1&&(e=e.slice(0,s)),e+=(e.indexOf("?")===-1?"?":"&")+i}return e}class sj{constructor(){this.handlers=[]}use(t,n,r){return this.handlers.push({fulfilled:t,rejected:n,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){ie.forEach(this.handlers,function(r){r!==null&&t(r)})}}const yC=sj,uk={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},aj=typeof URLSearchParams<"u"?URLSearchParams:rx,lj=typeof FormData<"u"?FormData:null,cj=typeof Blob<"u"?Blob:null,uj={isBrowser:!0,classes:{URLSearchParams:aj,FormData:lj,Blob:cj},protocols:["http","https","file","blob","url","data"]},dk=typeof window<"u"&&typeof document<"u",dj=(e=>dk&&["ReactNative","NativeScript","NS"].indexOf(e)<0)(typeof navigator<"u"&&navigator.product),fj=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",hj=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:dk,hasStandardBrowserEnv:dj,hasStandardBrowserWebWorkerEnv:fj},Symbol.toStringTag,{value:"Module"})),zo={...hj,...uj};function pj(e,t){return Mm(e,new zo.classes.URLSearchParams,Object.assign({visitor:function(n,r,o,i){return zo.isNode&&ie.isBuffer(n)?(this.append(r,n.toString("base64")),!1):i.defaultVisitor.apply(this,arguments)}},t))}function mj(e){return ie.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function gj(e){const t={},n=Object.keys(e);let r;const o=n.length;let i;for(r=0;r=n.length;return s=!s&&ie.isArray(o)?o.length:s,u?(ie.hasOwnProp(o,s)?o[s]=[o[s],r]:o[s]=r,!l):((!o[s]||!ie.isObject(o[s]))&&(o[s]=[]),t(n,r,o[s],i)&&ie.isArray(o[s])&&(o[s]=gj(o[s])),!l)}if(ie.isFormData(e)&&ie.isFunction(e.entries)){const n={};return ie.forEachEntry(e,(r,o)=>{t(mj(r),o,n,0)}),n}return null}function vj(e,t,n){if(ie.isString(e))try{return(t||JSON.parse)(e),ie.trim(e)}catch(r){if(r.name!=="SyntaxError")throw r}return(n||JSON.stringify)(e)}const ox={transitional:uk,adapter:["xhr","http"],transformRequest:[function(t,n){const r=n.getContentType()||"",o=r.indexOf("application/json")>-1,i=ie.isObject(t);if(i&&ie.isHTMLForm(t)&&(t=new FormData(t)),ie.isFormData(t))return o&&o?JSON.stringify(fk(t)):t;if(ie.isArrayBuffer(t)||ie.isBuffer(t)||ie.isStream(t)||ie.isFile(t)||ie.isBlob(t))return t;if(ie.isArrayBufferView(t))return t.buffer;if(ie.isURLSearchParams(t))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let l;if(i){if(r.indexOf("application/x-www-form-urlencoded")>-1)return pj(t,this.formSerializer).toString();if((l=ie.isFileList(t))||r.indexOf("multipart/form-data")>-1){const u=this.env&&this.env.FormData;return Mm(l?{"files[]":t}:t,u&&new u,this.formSerializer)}}return i||o?(n.setContentType("application/json",!1),vj(t)):t}],transformResponse:[function(t){const n=this.transitional||ox.transitional,r=n&&n.forcedJSONParsing,o=this.responseType==="json";if(t&&ie.isString(t)&&(r&&!this.responseType||o)){const s=!(n&&n.silentJSONParsing)&&o;try{return JSON.parse(t)}catch(l){if(s)throw l.name==="SyntaxError"?ut.from(l,ut.ERR_BAD_RESPONSE,this,null,this.response):l}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:zo.classes.FormData,Blob:zo.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};ie.forEach(["delete","get","head","post","put","patch"],e=>{ox.headers[e]={}});const ix=ox,yj=ie.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),wj=e=>{const t={};let n,r,o;return e&&e.split(` +`).forEach(function(s){o=s.indexOf(":"),n=s.substring(0,o).trim().toLowerCase(),r=s.substring(o+1).trim(),!(!n||t[n]&&yj[n])&&(n==="set-cookie"?t[n]?t[n].push(r):t[n]=[r]:t[n]=t[n]?t[n]+", "+r:r)}),t},wC=Symbol("internals");function uu(e){return e&&String(e).trim().toLowerCase()}function Kh(e){return e===!1||e==null?e:ie.isArray(e)?e.map(Kh):String(e)}function xj(e){const t=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=n.exec(e);)t[r[1]]=r[2];return t}const bj=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function m0(e,t,n,r,o){if(ie.isFunction(r))return r.call(this,t,n);if(o&&(t=n),!!ie.isString(t)){if(ie.isString(r))return t.indexOf(r)!==-1;if(ie.isRegExp(r))return r.test(t)}}function Sj(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,n,r)=>n.toUpperCase()+r)}function _j(e,t){const n=ie.toCamelCase(" "+t);["get","set","has"].forEach(r=>{Object.defineProperty(e,r+n,{value:function(o,i,s){return this[r].call(this,t,o,i,s)},configurable:!0})})}class Om{constructor(t){t&&this.set(t)}set(t,n,r){const o=this;function i(l,u,f){const p=uu(u);if(!p)throw new Error("header name must be a non-empty string");const m=ie.findKey(o,p);(!m||o[m]===void 0||f===!0||f===void 0&&o[m]!==!1)&&(o[m||u]=Kh(l))}const s=(l,u)=>ie.forEach(l,(f,p)=>i(f,p,u));return ie.isPlainObject(t)||t instanceof this.constructor?s(t,n):ie.isString(t)&&(t=t.trim())&&!bj(t)?s(wj(t),n):t!=null&&i(n,t,r),this}get(t,n){if(t=uu(t),t){const r=ie.findKey(this,t);if(r){const o=this[r];if(!n)return o;if(n===!0)return xj(o);if(ie.isFunction(n))return n.call(this,o,r);if(ie.isRegExp(n))return n.exec(o);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,n){if(t=uu(t),t){const r=ie.findKey(this,t);return!!(r&&this[r]!==void 0&&(!n||m0(this,this[r],r,n)))}return!1}delete(t,n){const r=this;let o=!1;function i(s){if(s=uu(s),s){const l=ie.findKey(r,s);l&&(!n||m0(r,r[l],l,n))&&(delete r[l],o=!0)}}return ie.isArray(t)?t.forEach(i):i(t),o}clear(t){const n=Object.keys(this);let r=n.length,o=!1;for(;r--;){const i=n[r];(!t||m0(this,this[i],i,t,!0))&&(delete this[i],o=!0)}return o}normalize(t){const n=this,r={};return ie.forEach(this,(o,i)=>{const s=ie.findKey(r,i);if(s){n[s]=Kh(o),delete n[i];return}const l=t?Sj(i):String(i).trim();l!==i&&delete n[i],n[l]=Kh(o),r[l]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){const n=Object.create(null);return ie.forEach(this,(r,o)=>{r!=null&&r!==!1&&(n[o]=t&&ie.isArray(r)?r.join(", "):r)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,n])=>t+": "+n).join(` +`)}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...n){const r=new this(t);return n.forEach(o=>r.set(o)),r}static accessor(t){const r=(this[wC]=this[wC]={accessors:{}}).accessors,o=this.prototype;function i(s){const l=uu(s);r[l]||(_j(o,s),r[l]=!0)}return ie.isArray(t)?t.forEach(i):i(t),this}}Om.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);ie.reduceDescriptors(Om.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(r){this[n]=r}}});ie.freezeMethods(Om);const xi=Om;function g0(e,t){const n=this||ix,r=t||n,o=xi.from(r.headers);let i=r.data;return ie.forEach(e,function(l){i=l.call(n,i,o.normalize(),t?t.status:void 0)}),o.normalize(),i}function hk(e){return!!(e&&e.__CANCEL__)}function Dd(e,t,n){ut.call(this,e??"canceled",ut.ERR_CANCELED,t,n),this.name="CanceledError"}ie.inherits(Dd,ut,{__CANCEL__:!0});function Ej(e,t,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?e(n):t(new ut("Request failed with status code "+n.status,[ut.ERR_BAD_REQUEST,ut.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}const Cj=zo.hasStandardBrowserEnv?{write(e,t,n,r,o,i){const s=[e+"="+encodeURIComponent(t)];ie.isNumber(n)&&s.push("expires="+new Date(n).toGMTString()),ie.isString(r)&&s.push("path="+r),ie.isString(o)&&s.push("domain="+o),i===!0&&s.push("secure"),document.cookie=s.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function $j(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function Rj(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e}function pk(e,t){return e&&!$j(t)?Rj(e,t):t}const kj=zo.hasStandardBrowserEnv?function(){const t=/(msie|trident)/i.test(navigator.userAgent),n=document.createElement("a");let r;function o(i){let s=i;return t&&(n.setAttribute("href",s),s=n.href),n.setAttribute("href",s),{href:n.href,protocol:n.protocol?n.protocol.replace(/:$/,""):"",host:n.host,search:n.search?n.search.replace(/^\?/,""):"",hash:n.hash?n.hash.replace(/^#/,""):"",hostname:n.hostname,port:n.port,pathname:n.pathname.charAt(0)==="/"?n.pathname:"/"+n.pathname}}return r=o(window.location.href),function(s){const l=ie.isString(s)?o(s):s;return l.protocol===r.protocol&&l.host===r.host}}():function(){return function(){return!0}}();function Tj(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function Pj(e,t){e=e||10;const n=new Array(e),r=new Array(e);let o=0,i=0,s;return t=t!==void 0?t:1e3,function(u){const f=Date.now(),p=r[i];s||(s=f),n[o]=u,r[o]=f;let m=i,g=0;for(;m!==o;)g+=n[m++],m=m%e;if(o=(o+1)%e,o===i&&(i=(i+1)%e),f-s{const i=o.loaded,s=o.lengthComputable?o.total:void 0,l=i-n,u=r(l),f=i<=s;n=i;const p={loaded:i,total:s,progress:s?i/s:void 0,bytes:l,rate:u||void 0,estimated:u&&s&&f?(s-i)/u:void 0,event:o};p[t?"download":"upload"]=!0,e(p)}}const Aj=typeof XMLHttpRequest<"u",Mj=Aj&&function(e){return new Promise(function(n,r){let o=e.data;const i=xi.from(e.headers).normalize();let{responseType:s,withXSRFToken:l}=e,u;function f(){e.cancelToken&&e.cancelToken.unsubscribe(u),e.signal&&e.signal.removeEventListener("abort",u)}let p;if(ie.isFormData(o)){if(zo.hasStandardBrowserEnv||zo.hasStandardBrowserWebWorkerEnv)i.setContentType(!1);else if((p=i.getContentType())!==!1){const[S,...E]=p?p.split(";").map(_=>_.trim()).filter(Boolean):[];i.setContentType([S||"multipart/form-data",...E].join("; "))}}let m=new XMLHttpRequest;if(e.auth){const S=e.auth.username||"",E=e.auth.password?unescape(encodeURIComponent(e.auth.password)):"";i.set("Authorization","Basic "+btoa(S+":"+E))}const g=pk(e.baseURL,e.url);m.open(e.method.toUpperCase(),ck(g,e.params,e.paramsSerializer),!0),m.timeout=e.timeout;function y(){if(!m)return;const S=xi.from("getAllResponseHeaders"in m&&m.getAllResponseHeaders()),_={data:!s||s==="text"||s==="json"?m.responseText:m.response,status:m.status,statusText:m.statusText,headers:S,config:e,request:m};Ej(function(C){n(C),f()},function(C){r(C),f()},_),m=null}if("onloadend"in m?m.onloadend=y:m.onreadystatechange=function(){!m||m.readyState!==4||m.status===0&&!(m.responseURL&&m.responseURL.indexOf("file:")===0)||setTimeout(y)},m.onabort=function(){m&&(r(new ut("Request aborted",ut.ECONNABORTED,e,m)),m=null)},m.onerror=function(){r(new ut("Network Error",ut.ERR_NETWORK,e,m)),m=null},m.ontimeout=function(){let E=e.timeout?"timeout of "+e.timeout+"ms exceeded":"timeout exceeded";const _=e.transitional||uk;e.timeoutErrorMessage&&(E=e.timeoutErrorMessage),r(new ut(E,_.clarifyTimeoutError?ut.ETIMEDOUT:ut.ECONNABORTED,e,m)),m=null},zo.hasStandardBrowserEnv&&(l&&ie.isFunction(l)&&(l=l(e)),l||l!==!1&&kj(g))){const S=e.xsrfHeaderName&&e.xsrfCookieName&&Cj.read(e.xsrfCookieName);S&&i.set(e.xsrfHeaderName,S)}o===void 0&&i.setContentType(null),"setRequestHeader"in m&&ie.forEach(i.toJSON(),function(E,_){m.setRequestHeader(_,E)}),ie.isUndefined(e.withCredentials)||(m.withCredentials=!!e.withCredentials),s&&s!=="json"&&(m.responseType=e.responseType),typeof e.onDownloadProgress=="function"&&m.addEventListener("progress",xC(e.onDownloadProgress,!0)),typeof e.onUploadProgress=="function"&&m.upload&&m.upload.addEventListener("progress",xC(e.onUploadProgress)),(e.cancelToken||e.signal)&&(u=S=>{m&&(r(!S||S.type?new Dd(null,e,m):S),m.abort(),m=null)},e.cancelToken&&e.cancelToken.subscribe(u),e.signal&&(e.signal.aborted?u():e.signal.addEventListener("abort",u)));const x=Tj(g);if(x&&zo.protocols.indexOf(x)===-1){r(new ut("Unsupported protocol "+x+":",ut.ERR_BAD_REQUEST,e));return}m.send(o||null)})},Qy={http:nj,xhr:Mj};ie.forEach(Qy,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});const bC=e=>`- ${e}`,Oj=e=>ie.isFunction(e)||e===null||e===!1,mk={getAdapter:e=>{e=ie.isArray(e)?e:[e];const{length:t}=e;let n,r;const o={};for(let i=0;i`adapter ${l} `+(u===!1?"is not supported by the environment":"is not available in the build"));let s=t?i.length>1?`since : +`+i.map(bC).join(` +`):" "+bC(i[0]):"as no adapter specified";throw new ut("There is no suitable adapter to dispatch the request "+s,"ERR_NOT_SUPPORT")}return r},adapters:Qy};function v0(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Dd(null,e)}function SC(e){return v0(e),e.headers=xi.from(e.headers),e.data=g0.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),mk.getAdapter(e.adapter||ix.adapter)(e).then(function(r){return v0(e),r.data=g0.call(e,e.transformResponse,r),r.headers=xi.from(r.headers),r},function(r){return hk(r)||(v0(e),r&&r.response&&(r.response.data=g0.call(e,e.transformResponse,r.response),r.response.headers=xi.from(r.response.headers))),Promise.reject(r)})}const _C=e=>e instanceof xi?e.toJSON():e;function ic(e,t){t=t||{};const n={};function r(f,p,m){return ie.isPlainObject(f)&&ie.isPlainObject(p)?ie.merge.call({caseless:m},f,p):ie.isPlainObject(p)?ie.merge({},p):ie.isArray(p)?p.slice():p}function o(f,p,m){if(ie.isUndefined(p)){if(!ie.isUndefined(f))return r(void 0,f,m)}else return r(f,p,m)}function i(f,p){if(!ie.isUndefined(p))return r(void 0,p)}function s(f,p){if(ie.isUndefined(p)){if(!ie.isUndefined(f))return r(void 0,f)}else return r(void 0,p)}function l(f,p,m){if(m in t)return r(f,p);if(m in e)return r(void 0,f)}const u={url:i,method:i,data:i,baseURL:s,transformRequest:s,transformResponse:s,paramsSerializer:s,timeout:s,timeoutMessage:s,withCredentials:s,withXSRFToken:s,adapter:s,responseType:s,xsrfCookieName:s,xsrfHeaderName:s,onUploadProgress:s,onDownloadProgress:s,decompress:s,maxContentLength:s,maxBodyLength:s,beforeRedirect:s,transport:s,httpAgent:s,httpsAgent:s,cancelToken:s,socketPath:s,responseEncoding:s,validateStatus:l,headers:(f,p)=>o(_C(f),_C(p),!0)};return ie.forEach(Object.keys(Object.assign({},e,t)),function(p){const m=u[p]||o,g=m(e[p],t[p],p);ie.isUndefined(g)&&m!==l||(n[p]=g)}),n}const gk="1.6.2",sx={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{sx[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const EC={};sx.transitional=function(t,n,r){function o(i,s){return"[Axios v"+gk+"] Transitional option '"+i+"'"+s+(r?". "+r:"")}return(i,s,l)=>{if(t===!1)throw new ut(o(s," has been removed"+(n?" in "+n:"")),ut.ERR_DEPRECATED);return n&&!EC[s]&&(EC[s]=!0,console.warn(o(s," has been deprecated since v"+n+" and will be removed in the near future"))),t?t(i,s,l):!0}};function Nj(e,t,n){if(typeof e!="object")throw new ut("options must be an object",ut.ERR_BAD_OPTION_VALUE);const r=Object.keys(e);let o=r.length;for(;o-- >0;){const i=r[o],s=t[i];if(s){const l=e[i],u=l===void 0||s(l,i,e);if(u!==!0)throw new ut("option "+i+" must be "+u,ut.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new ut("Unknown option "+i,ut.ERR_BAD_OPTION)}}const Jy={assertOptions:Nj,validators:sx},Xi=Jy.validators;class Op{constructor(t){this.defaults=t,this.interceptors={request:new yC,response:new yC}}request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=ic(this.defaults,n);const{transitional:r,paramsSerializer:o,headers:i}=n;r!==void 0&&Jy.assertOptions(r,{silentJSONParsing:Xi.transitional(Xi.boolean),forcedJSONParsing:Xi.transitional(Xi.boolean),clarifyTimeoutError:Xi.transitional(Xi.boolean)},!1),o!=null&&(ie.isFunction(o)?n.paramsSerializer={serialize:o}:Jy.assertOptions(o,{encode:Xi.function,serialize:Xi.function},!0)),n.method=(n.method||this.defaults.method||"get").toLowerCase();let s=i&&ie.merge(i.common,i[n.method]);i&&ie.forEach(["delete","get","head","post","put","patch","common"],x=>{delete i[x]}),n.headers=xi.concat(s,i);const l=[];let u=!0;this.interceptors.request.forEach(function(S){typeof S.runWhen=="function"&&S.runWhen(n)===!1||(u=u&&S.synchronous,l.unshift(S.fulfilled,S.rejected))});const f=[];this.interceptors.response.forEach(function(S){f.push(S.fulfilled,S.rejected)});let p,m=0,g;if(!u){const x=[SC.bind(this),void 0];for(x.unshift.apply(x,l),x.push.apply(x,f),g=x.length,p=Promise.resolve(n);m{if(!r._listeners)return;let i=r._listeners.length;for(;i-- >0;)r._listeners[i](o);r._listeners=null}),this.promise.then=o=>{let i;const s=new Promise(l=>{r.subscribe(l),i=l}).then(o);return s.cancel=function(){r.unsubscribe(i)},s},t(function(i,s,l){r.reason||(r.reason=new Dd(i,s,l),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}static source(){let t;return{token:new ax(function(o){t=o}),cancel:t}}}const Dj=ax;function Ij(e){return function(n){return e.apply(null,n)}}function Lj(e){return ie.isObject(e)&&e.isAxiosError===!0}const e1={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(e1).forEach(([e,t])=>{e1[t]=e});const Fj=e1;function vk(e){const t=new Gh(e),n=qR(Gh.prototype.request,t);return ie.extend(n,Gh.prototype,t,{allOwnKeys:!0}),ie.extend(n,t,null,{allOwnKeys:!0}),n.create=function(o){return vk(ic(e,o))},n}const Qt=vk(ix);Qt.Axios=Gh;Qt.CanceledError=Dd;Qt.CancelToken=Dj;Qt.isCancel=hk;Qt.VERSION=gk;Qt.toFormData=Mm;Qt.AxiosError=ut;Qt.Cancel=Qt.CanceledError;Qt.all=function(t){return Promise.all(t)};Qt.spread=Ij;Qt.isAxiosError=Lj;Qt.mergeConfig=ic;Qt.AxiosHeaders=xi;Qt.formToJSON=e=>fk(ie.isHTMLForm(e)?new FormData(e):e);Qt.getAdapter=mk.getAdapter;Qt.HttpStatusCode=Fj;Qt.default=Qt;const jj=Qt,Ls="/api/v1",_c=jj.create({baseURL:Ls});async function zj(e,t,n,r,o,i=null){const s=await Du(e),l=await Du(o),u=i?await Du(i):null,f=await fetch(`${Ls}/inpaint`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({image:s,mask:l,ldm_steps:t.ldmSteps,ldm_sampler:t.ldmSampler,zits_wireframe:t.zitsWireframe,cv2_flag:t.cv2Flag,cv2_radius:t.cv2Radius,hd_strategy:"Crop",hd_strategy_crop_triger_size:640,hd_strategy_crop_margin:128,hd_trategy_resize_imit:2048,prompt:t.prompt,negative_prompt:t.negativePrompt,use_croper:t.showCropper,croper_x:n.x,croper_y:n.y,croper_height:n.height,croper_width:n.width,use_extender:t.showExtender,extender_x:r.x,extender_y:r.y,extender_height:r.height,extender_width:r.width,sd_mask_blur:t.sdMaskBlur,sd_strength:t.sdStrength,sd_steps:t.sdSteps,sd_guidance_scale:t.sdGuidanceScale,sd_sampler:t.sdSampler,sd_seed:t.seedFixed?t.seed:-1,sd_match_histograms:t.sdMatchHistograms,sd_freeu:t.enableFreeu,sd_freeu_config:t.freeuConfig,sd_lcm_lora:t.enableLCMLora,paint_by_example_example_image:u,p2p_image_guidance_scale:t.p2pImageGuidanceScale,enable_controlnet:t.enableControlnet,controlnet_conditioning_scale:t.controlnetConditioningScale,controlnet_method:t.controlnetMethod?t.controlnetMethod:"",powerpaint_task:t.showExtender?Ol.outpainting:t.powerpaintTask})});if(f.ok){const m=await f.blob();return{blob:URL.createObjectURL(m),seed:f.headers.get("X-Seed")}}const p=await f.json();throw new Error(`Something went wrong: ${p.errors}`)}async function yk(){return(await _c.get("/server-config")).data}async function Bj(e){return(await _c.post("/model",{name:e})).data}async function y0(e,t){return _c.post("/switch_plugin_model",{plugin_name:e,model_name:t})}async function Uj(){return(await _c.get("/model")).data}async function wk(e,t,n,r,o){const i=await Du(n),l=await fetch(`${Ls}/${e?"run_plugin_gen_mask":"run_plugin_gen_image"}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t,image:i,upscale:r,clicks:o})});if(l.ok){const f=await l.blob();return{blob:URL.createObjectURL(f)}}const u=await l.json();throw new Error(u)}async function Vj(e,t){const n=await fetch(`${Ls}/media_file?tab=${e}&filename=${encodeURIComponent(t)}`,{method:"GET"});if(n.ok){const o=await n.blob();return new File([o],t,{type:n.headers.get("Content-Type")??"image/png"})}const r=await n.json();throw new Error(r.errors)}async function Wj(e){return(await _c.get("medias",{params:{tab:e}})).data}async function Hj(e,t,n){const r=await Nu(e.src,t,n),o=new FormData;o.append("file",r);try{const i=await fetch(`${Ls}/save_image`,{method:"POST",body:o});if(!i.ok){const s=await i.text();throw new Error(s)}}catch(i){throw new Error(`Something went wrong: ${i}`)}}async function Kj(e){const t=new FormData;return t.append("file",e),(await _c.post("/gen-info",t)).data}async function Gj(e,t,n){const r=await Du(e),o=await fetch(`${Ls}/adjust_mask`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mask:r,operate:t,kernel_size:n})});if(o.ok)return await o.blob();const i=await o.json();throw new Error(i)}function Yj(){const[e,t]=d.useState(null),n=d.useCallback(()=>{const r=new Headers;r.append("pragma","no-cache"),r.append("cache-control","no-cache"),fetch(`${Ls}/inputimage`,{headers:r}).then(async o=>{var l;if(!o.ok)return;const i=(l=o.headers.get("content-disposition"))==null?void 0:l.split("filename=")[1].split(";")[0],s=await o.blob();if(s&&s.type.startsWith("image")){const u=new File([s],i!==void 0?i:"inputImage");t(u)}}).catch(o=>{console.log(o)})},[t]);return d.useEffect(()=>{n()},[n]),e}function _o(e,t){if(e==null)return{};var n={},r=Object.keys(e),o,i;for(i=0;i=0)&&(n[o]=e[o]);return n}var Xj=["color"],Zj=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,Xj);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.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:r,fillRule:"evenodd",clipRule:"evenodd"}))}),qj=["color"],xk=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,qj);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M11.4669 3.72684C11.7558 3.91574 11.8369 4.30308 11.648 4.59198L7.39799 11.092C7.29783 11.2452 7.13556 11.3467 6.95402 11.3699C6.77247 11.3931 6.58989 11.3355 6.45446 11.2124L3.70446 8.71241C3.44905 8.48022 3.43023 8.08494 3.66242 7.82953C3.89461 7.57412 4.28989 7.55529 4.5453 7.78749L6.75292 9.79441L10.6018 3.90792C10.7907 3.61902 11.178 3.53795 11.4669 3.72684Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),Qj=["color"],Jj=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,Qj);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M3.13523 6.15803C3.3241 5.95657 3.64052 5.94637 3.84197 6.13523L7.5 9.56464L11.158 6.13523C11.3595 5.94637 11.6759 5.95657 11.8648 6.15803C12.0536 6.35949 12.0434 6.67591 11.842 6.86477L7.84197 10.6148C7.64964 10.7951 7.35036 10.7951 7.15803 10.6148L3.15803 6.86477C2.95657 6.67591 2.94637 6.35949 3.13523 6.15803Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),ez=["color"],tz=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,ez);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M6.1584 3.13508C6.35985 2.94621 6.67627 2.95642 6.86514 3.15788L10.6151 7.15788C10.7954 7.3502 10.7954 7.64949 10.6151 7.84182L6.86514 11.8418C6.67627 12.0433 6.35985 12.0535 6.1584 11.8646C5.95694 11.6757 5.94673 11.3593 6.1356 11.1579L9.565 7.49985L6.1356 3.84182C5.94673 3.64036 5.95694 3.32394 6.1584 3.13508Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),nz=["color"],rz=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,nz);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M3.13523 8.84197C3.3241 9.04343 3.64052 9.05363 3.84197 8.86477L7.5 5.43536L11.158 8.86477C11.3595 9.05363 11.6759 9.04343 11.8648 8.84197C12.0536 8.64051 12.0434 8.32409 11.842 8.13523L7.84197 4.38523C7.64964 4.20492 7.35036 4.20492 7.15803 4.38523L3.15803 8.13523C2.95657 8.32409 2.94637 8.64051 3.13523 8.84197Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),oz=["color"],bk=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,oz);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.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:r,fillRule:"evenodd",clipRule:"evenodd"}))}),iz=["color"],sz=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,iz);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M9.875 7.5C9.875 8.81168 8.81168 9.875 7.5 9.875C6.18832 9.875 5.125 8.81168 5.125 7.5C5.125 6.18832 6.18832 5.125 7.5 5.125C8.81168 5.125 9.875 6.18832 9.875 7.5Z",fill:r}))}),az=["color"],lz=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,az);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M10 6.5C10 8.433 8.433 10 6.5 10C4.567 10 3 8.433 3 6.5C3 4.567 4.567 3 6.5 3C8.433 3 10 4.567 10 6.5ZM9.30884 10.0159C8.53901 10.6318 7.56251 11 6.5 11C4.01472 11 2 8.98528 2 6.5C2 4.01472 4.01472 2 6.5 2C8.98528 2 11 4.01472 11 6.5C11 7.56251 10.6318 8.53901 10.0159 9.30884L12.8536 12.1464C13.0488 12.3417 13.0488 12.6583 12.8536 12.8536C12.6583 13.0488 12.3417 13.0488 12.1464 12.8536L9.30884 10.0159Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),cz=["color"],uz=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,cz);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M3.24182 2.32181C3.3919 2.23132 3.5784 2.22601 3.73338 2.30781L12.7334 7.05781C12.8974 7.14436 13 7.31457 13 7.5C13 7.68543 12.8974 7.85564 12.7334 7.94219L3.73338 12.6922C3.5784 12.774 3.3919 12.7687 3.24182 12.6782C3.09175 12.5877 3 12.4252 3 12.25V2.75C3 2.57476 3.09175 2.4123 3.24182 2.32181ZM4 3.57925V11.4207L11.4288 7.5L4 3.57925Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),dz=["color"],fz=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,dz);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M7 2H1.5C1.22386 2 1 2.22386 1 2.5V7H7V2ZM8 2V7H14V2.5C14 2.22386 13.7761 2 13.5 2H8ZM7 8H1V12.5C1 12.7761 1.22386 13 1.5 13H7V8ZM8 13V8H14V12.5C14 12.7761 13.7761 13 13.5 13H8ZM1.5 1C0.671573 1 0 1.67157 0 2.5V12.5C0 13.3284 0.671573 14 1.5 14H13.5C14.3284 14 15 13.3284 15 12.5V2.5C15 1.67157 14.3284 1 13.5 1H1.5Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),hz=["color"],pz=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,hz);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M1.5 2H13.5C13.7761 2 14 2.22386 14 2.5V7H1V2.5C1 2.22386 1.22386 2 1.5 2ZM1 8V12.5C1 12.7761 1.22386 13 1.5 13H13.5C13.7761 13 14 12.7761 14 12.5V8H1ZM0 2.5C0 1.67157 0.671573 1 1.5 1H13.5C14.3284 1 15 1.67157 15 2.5V12.5C15 13.3284 14.3284 14 13.5 14H1.5C0.671573 14 0 13.3284 0 12.5V2.5Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))});function Y(){return Y=Object.assign?Object.assign.bind():function(e){for(var t=1;te.forEach(n=>mz(n,t))}function Ue(...e){return d.useCallback(Nm(...e),e)}const Zo=d.forwardRef((e,t)=>{const{children:n,...r}=e,o=d.Children.toArray(n),i=o.find(gz);if(i){const s=i.props.children,l=o.map(u=>u===i?d.Children.count(s)>1?d.Children.only(null):d.isValidElement(s)?s.props.children:null:u);return d.createElement(t1,Y({},r,{ref:t}),d.isValidElement(s)?d.cloneElement(s,void 0,l):null)}return d.createElement(t1,Y({},r,{ref:t}),n)});Zo.displayName="Slot";const t1=d.forwardRef((e,t)=>{const{children:n,...r}=e;return d.isValidElement(n)?d.cloneElement(n,{...vz(r,n.props),ref:t?Nm(t,n.ref):n.ref}):d.Children.count(n)>1?d.Children.only(null):null});t1.displayName="SlotClone";const lx=({children:e})=>d.createElement(d.Fragment,null,e);function gz(e){return d.isValidElement(e)&&e.type===lx}function vz(e,t){const n={...t};for(const r in t){const o=e[r],i=t[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...l)=>{i(...l),o(...l)}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...e,...n}}const CC=e=>typeof e=="boolean"?"".concat(e):e===0?"0":e,$C=VR,Dm=(e,t)=>n=>{var r;if((t==null?void 0:t.variants)==null)return $C(e,n==null?void 0:n.class,n==null?void 0:n.className);const{variants:o,defaultVariants:i}=t,s=Object.keys(o).map(f=>{const p=n==null?void 0:n[f],m=i==null?void 0:i[f];if(p===null)return null;const g=CC(p)||CC(m);return o[f][g]}),l=n&&Object.entries(n).reduce((f,p)=>{let[m,g]=p;return g===void 0||(f[m]=g),f},{}),u=t==null||(r=t.compoundVariants)===null||r===void 0?void 0:r.reduce((f,p)=>{let{class:m,className:g,...y}=p;return Object.entries(y).every(x=>{let[S,E]=x;return Array.isArray(E)?E.includes({...i,...l}[S]):{...i,...l}[S]===E})?[...f,m,g]:f},[]);return $C(e,s,u,n==null?void 0:n.class,n==null?void 0:n.className)};var yz={VITE_BACKEND:"http://127.0.0.1:8080",BASE_URL:"/",MODE:"production",DEV:!1,PROD:!0,SSR:!1};function wz(e,t){let n;try{n=e()}catch{return}return{getItem:o=>{var i;const s=u=>u===null?null:JSON.parse(u,t==null?void 0:t.reviver),l=(i=n.getItem(o))!=null?i:null;return l instanceof Promise?l.then(s):s(l)},setItem:(o,i)=>n.setItem(o,JSON.stringify(i,t==null?void 0:t.replacer)),removeItem:o=>n.removeItem(o)}}const od=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then(r){return od(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return od(r)(n)}}}},xz=(e,t)=>(n,r,o)=>{let i={getStorage:()=>localStorage,serialize:JSON.stringify,deserialize:JSON.parse,partialize:E=>E,version:0,merge:(E,_)=>({..._,...E}),...t},s=!1;const l=new Set,u=new Set;let f;try{f=i.getStorage()}catch{}if(!f)return e((...E)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),n(...E)},r,o);const p=od(i.serialize),m=()=>{const E=i.partialize({...r()});let _;const b=p({state:E,version:i.version}).then(C=>f.setItem(i.name,C)).catch(C=>{_=C});if(_)throw _;return b},g=o.setState;o.setState=(E,_)=>{g(E,_),m()};const y=e((...E)=>{n(...E),m()},r,o);let x;const S=()=>{var E;if(!f)return;s=!1,l.forEach(b=>b(r()));const _=((E=i.onRehydrateStorage)==null?void 0:E.call(i,r()))||void 0;return od(f.getItem.bind(f))(i.name).then(b=>{if(b)return i.deserialize(b)}).then(b=>{if(b)if(typeof b.version=="number"&&b.version!==i.version){if(i.migrate)return i.migrate(b.state,b.version);console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return b.state}).then(b=>{var C;return x=i.merge(b,(C=r())!=null?C:y),n(x,!0),m()}).then(()=>{_==null||_(x,void 0),s=!0,u.forEach(b=>b(x))}).catch(b=>{_==null||_(void 0,b)})};return o.persist={setOptions:E=>{i={...i,...E},E.getStorage&&(f=E.getStorage())},clearStorage:()=>{f==null||f.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>S(),hasHydrated:()=>s,onHydrate:E=>(l.add(E),()=>{l.delete(E)}),onFinishHydration:E=>(u.add(E),()=>{u.delete(E)})},S(),x||y},bz=(e,t)=>(n,r,o)=>{let i={storage:wz(()=>localStorage),partialize:S=>S,version:0,merge:(S,E)=>({...E,...S}),...t},s=!1;const l=new Set,u=new Set;let f=i.storage;if(!f)return e((...S)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),n(...S)},r,o);const p=()=>{const S=i.partialize({...r()});return f.setItem(i.name,{state:S,version:i.version})},m=o.setState;o.setState=(S,E)=>{m(S,E),p()};const g=e((...S)=>{n(...S),p()},r,o);let y;const x=()=>{var S,E;if(!f)return;s=!1,l.forEach(b=>{var C;return b((C=r())!=null?C:g)});const _=((E=i.onRehydrateStorage)==null?void 0:E.call(i,(S=r())!=null?S:g))||void 0;return od(f.getItem.bind(f))(i.name).then(b=>{if(b)if(typeof b.version=="number"&&b.version!==i.version){if(i.migrate)return i.migrate(b.state,b.version);console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return b.state}).then(b=>{var C;return y=i.merge(b,(C=r())!=null?C:g),n(y,!0),p()}).then(()=>{_==null||_(y,void 0),y=r(),s=!0,u.forEach(b=>b(y))}).catch(b=>{_==null||_(void 0,b)})};return o.persist={setOptions:S=>{i={...i,...S},S.storage&&(f=S.storage)},clearStorage:()=>{f==null||f.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>x(),hasHydrated:()=>s,onHydrate:S=>(l.add(S),()=>{l.delete(S)}),onFinishHydration:S=>(u.add(S),()=>{u.delete(S)})},i.skipHydration||x(),y||g},Sz=(e,t)=>"getStorage"in t||"serialize"in t||"deserialize"in t?((yz?"production":void 0)!=="production"&&console.warn("[DEPRECATED] `getStorage`, `serialize` and `deserialize` options are deprecated. Use `storage` option instead."),xz(e,t)):bz(e,t),_z=Sz;function Ez(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,o]of e)if(!Object.is(o,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{t(n,r,e)}):e.forEach((n,r)=>t(r,n,e))}function Im(e){const t=e[wr];return t?t.type_:Array.isArray(e)?1:Lm(e)?2:Fm(e)?3:0}function n1(e,t){return Im(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function Ek(e,t,n){const r=Im(e);r===2?e.set(t,n):r===3?e.add(n):e[t]=n}function $z(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function Lm(e){return e instanceof Map}function Fm(e){return e instanceof Set}function ra(e){return e.copy_||e.base_}function r1(e,t){if(Lm(e))return new Map(e);if(Fm(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);if(!t&&_k(e))return sc(e)?{...e}:Object.assign(Object.create(null),e);const n=Object.getOwnPropertyDescriptors(e);delete n[wr];let r=Reflect.ownKeys(n);for(let o=0;o1&&(e.set=e.add=e.clear=e.delete=Rz),Object.freeze(e),t&&id(e,(n,r)=>cx(r,!0))),e}function Rz(){po(2)}function jm(e){return Object.isFrozen(e)}var kz={};function Oa(e){const t=kz[e];return t||po(0,e),t}var sd;function Ck(){return sd}function Tz(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function kC(e,t){t&&(Oa("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function o1(e){i1(e),e.drafts_.forEach(Pz),e.drafts_=null}function i1(e){e===sd&&(sd=e.parent_)}function TC(e){return sd=Tz(sd,e)}function Pz(e){const t=e[wr];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function PC(e,t){t.unfinalizedDrafts_=t.drafts_.length;const n=t.drafts_[0];return e!==void 0&&e!==n?(n[wr].modified_&&(o1(t),po(4)),Ma(e)&&(e=Np(t,e),t.parent_||Dp(t,e)),t.patches_&&Oa("Patches").generateReplacementPatches_(n[wr].base_,e,t.patches_,t.inversePatches_)):e=Np(t,n,[]),o1(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==Sk?e:void 0}function Np(e,t,n){if(jm(t))return t;const r=t[wr];if(!r)return id(t,(o,i)=>AC(e,r,t,o,i,n)),t;if(r.scope_!==e)return t;if(!r.modified_)return Dp(e,r.base_,!0),r.base_;if(!r.finalized_){r.finalized_=!0,r.scope_.unfinalizedDrafts_--;const o=r.copy_;let i=o,s=!1;r.type_===3&&(i=new Set(o),o.clear(),s=!0),id(i,(l,u)=>AC(e,r,o,l,u,n,s)),Dp(e,o,!1),n&&e.patches_&&Oa("Patches").generatePatches_(r,n,e.patches_,e.inversePatches_)}return r.copy_}function AC(e,t,n,r,o,i,s){if(ac(o)){const l=i&&t&&t.type_!==3&&!n1(t.assigned_,r)?i.concat(r):void 0,u=Np(e,o,l);if(Ek(n,r,u),ac(u))e.canAutoFreeze_=!1;else return}else s&&n.add(o);if(Ma(o)&&!jm(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;Np(e,o),(!t||!t.scope_.parent_)&&Dp(e,o)}}function Dp(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&cx(t,n)}function Az(e,t){const n=Array.isArray(e),r={type_:n?1:0,scope_:t?t.scope_:Ck(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1};let o=r,i=ux;n&&(o=[r],i=ad);const{revoke:s,proxy:l}=Proxy.revocable(o,i);return r.draft_=l,r.revoke_=s,l}var ux={get(e,t){if(t===wr)return e;const n=ra(e);if(!n1(n,t))return Mz(e,n,t);const r=n[t];return e.finalized_||!Ma(r)?r:r===w0(e.base_,t)?(x0(e),e.copy_[t]=a1(r,e)):r},has(e,t){return t in ra(e)},ownKeys(e){return Reflect.ownKeys(ra(e))},set(e,t,n){const r=$k(ra(e),t);if(r!=null&&r.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){const o=w0(ra(e),t),i=o==null?void 0:o[wr];if(i&&i.base_===n)return e.copy_[t]=n,e.assigned_[t]=!1,!0;if($z(n,o)&&(n!==void 0||n1(e.base_,t)))return!0;x0(e),s1(e)}return e.copy_[t]===n&&(n!==void 0||t in e.copy_)||Number.isNaN(n)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=n,e.assigned_[t]=!0),!0},deleteProperty(e,t){return w0(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,x0(e),s1(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){const n=ra(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:r.enumerable,value:n[t]}},defineProperty(){po(11)},getPrototypeOf(e){return sc(e.base_)},setPrototypeOf(){po(12)}},ad={};id(ux,(e,t)=>{ad[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});ad.deleteProperty=function(e,t){return ad.set.call(this,e,t,void 0)};ad.set=function(e,t,n){return ux.set.call(this,e[0],t,n,e[0])};function w0(e,t){const n=e[wr];return(n?ra(n):e)[t]}function Mz(e,t,n){var o;const r=$k(t,n);return r?"value"in r?r.value:(o=r.get)==null?void 0:o.call(e.draft_):void 0}function $k(e,t){if(!(t in e))return;let n=sc(e);for(;n;){const r=Object.getOwnPropertyDescriptor(n,t);if(r)return r;n=sc(n)}}function s1(e){e.modified_||(e.modified_=!0,e.parent_&&s1(e.parent_))}function x0(e){e.copy_||(e.copy_=r1(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var Oz=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(t,n,r)=>{if(typeof t=="function"&&typeof n!="function"){const i=n;n=t;const s=this;return function(u=i,...f){return s.produce(u,p=>n.call(this,p,...f))}}typeof n!="function"&&po(6),r!==void 0&&typeof r!="function"&&po(7);let o;if(Ma(t)){const i=TC(this),s=a1(t,void 0);let l=!0;try{o=n(s),l=!1}finally{l?o1(i):i1(i)}return kC(i,r),PC(o,i)}else if(!t||typeof t!="object"){if(o=n(t),o===void 0&&(o=t),o===Sk&&(o=void 0),this.autoFreeze_&&cx(o,!0),r){const i=[],s=[];Oa("Patches").generateReplacementPatches_(t,o,i,s),r(i,s)}return o}else po(1,t)},this.produceWithPatches=(t,n)=>{if(typeof t=="function")return(s,...l)=>this.produceWithPatches(s,u=>t(u,...l));let r,o;return[this.produce(t,n,(s,l)=>{r=s,o=l}),r,o]},typeof(e==null?void 0:e.autoFreeze)=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof(e==null?void 0:e.useStrictShallowCopy)=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){Ma(e)||po(8),ac(e)&&(e=Nz(e));const t=TC(this),n=a1(e,void 0);return n[wr].isManual_=!0,i1(t),n}finishDraft(e,t){const n=e&&e[wr];(!n||!n.isManual_)&&po(9);const{scope_:r}=n;return kC(r,t),PC(void 0,r)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let n;for(n=t.length-1;n>=0;n--){const o=t[n];if(o.path.length===0&&o.op==="replace"){e=o.value;break}}n>-1&&(t=t.slice(n+1));const r=Oa("Patches").applyPatches_;return ac(e)?r(e,t):this.produce(e,o=>r(o,t))}};function a1(e,t){const n=Lm(e)?Oa("MapSet").proxyMap_(e,t):Fm(e)?Oa("MapSet").proxySet_(e,t):Az(e,t);return(t?t.scope_:Ck()).drafts_.push(n),n}function Nz(e){return ac(e)||po(10,e),Rk(e)}function Rk(e){if(!Ma(e)||jm(e))return e;const t=e[wr];let n;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=r1(e,t.scope_.immer_.useStrictShallowCopy_)}else n=r1(e,!0);return id(n,(r,o)=>{Ek(n,r,Rk(o))}),t&&(t.finalized_=!1),n}var xr=new Oz,Dz=xr.produce;xr.produceWithPatches.bind(xr);xr.setAutoFreeze.bind(xr);xr.setUseStrictShallowCopy.bind(xr);xr.applyPatches.bind(xr);xr.createDraft.bind(xr);xr.finishDraft.bind(xr);const Iz=e=>(t,n,r)=>(r.setState=(o,i,...s)=>{const l=typeof o=="function"?Dz(o):o;return t(l,i,...s)},e(r.setState,n,r)),Lz=Iz;var kk={exports:{}},Tk={},Pk={exports:{}},Ak={};/** + * @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 lc=d;function Fz(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var jz=typeof Object.is=="function"?Object.is:Fz,zz=lc.useState,Bz=lc.useEffect,Uz=lc.useLayoutEffect,Vz=lc.useDebugValue;function Wz(e,t){var n=t(),r=zz({inst:{value:n,getSnapshot:t}}),o=r[0].inst,i=r[1];return Uz(function(){o.value=n,o.getSnapshot=t,b0(o)&&i({inst:o})},[e,n,t]),Bz(function(){return b0(o)&&i({inst:o}),e(function(){b0(o)&&i({inst:o})})},[e]),Vz(n),n}function b0(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!jz(e,n)}catch{return!0}}function Hz(e,t){return t()}var Kz=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?Hz:Wz;Ak.useSyncExternalStore=lc.useSyncExternalStore!==void 0?lc.useSyncExternalStore:Kz;Pk.exports=Ak;var Gz=Pk.exports;/** + * @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 zm=d,Yz=Gz;function Xz(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var Zz=typeof Object.is=="function"?Object.is:Xz,qz=Yz.useSyncExternalStore,Qz=zm.useRef,Jz=zm.useEffect,eB=zm.useMemo,tB=zm.useDebugValue;Tk.useSyncExternalStoreWithSelector=function(e,t,n,r,o){var i=Qz(null);if(i.current===null){var s={hasValue:!1,value:null};i.current=s}else s=i.current;i=eB(function(){function u(y){if(!f){if(f=!0,p=y,y=r(y),o!==void 0&&s.hasValue){var x=s.value;if(o(x,y))return m=x}return m=y}if(x=m,Zz(p,y))return x;var S=r(y);return o!==void 0&&o(x,S)?x:(p=y,m=S)}var f=!1,p,m,g=n===void 0?null:n;return[function(){return u(t())},g===null?void 0:function(){return u(g())}]},[t,n,r,o]);var l=qz(e,i[0],i[1]);return Jz(function(){s.hasValue=!0,s.value=l},[l]),tB(l),l};kk.exports=Tk;var nB=kk.exports;const rB=dm(nB);var oB={VITE_BACKEND:"http://127.0.0.1:8080",BASE_URL:"/",MODE:"production",DEV:!1,PROD:!0,SSR:!1};const MC=e=>{let t;const n=new Set,r=(u,f)=>{const p=typeof u=="function"?u(t):u;if(!Object.is(p,t)){const m=t;t=f??typeof p!="object"?p:Object.assign({},t,p),n.forEach(g=>g(t,m))}},o=()=>t,l={setState:r,getState:o,subscribe:u=>(n.add(u),()=>n.delete(u)),destroy:()=>{(oB?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),n.clear()}};return t=e(r,o,l),l},iB=e=>e?MC(e):MC,{useDebugValue:sB}=je,{useSyncExternalStoreWithSelector:aB}=rB;function lB(e,t=e.getState,n){const r=aB(e.subscribe,e.getState,e.getServerState||e.getState,t,n);return sB(r),r}const OC=(e,t)=>{const n=iB(e),r=(o,i=t)=>lB(n,o,i);return Object.assign(r,n),r},cB=(e,t)=>e?OC(e,t):OC,uB=1,dB=1e6;let S0=0;function fB(){return S0=(S0+1)%Number.MAX_VALUE,S0.toString()}const _0=new Map,NC=e=>{if(_0.has(e))return;const t=setTimeout(()=>{_0.delete(e),Iu({type:"REMOVE_TOAST",toastId:e})},dB);_0.set(e,t)},hB=(e,t)=>{switch(t.type){case"ADD_TOAST":return{...e,toasts:[t.toast,...e.toasts].slice(0,uB)};case"UPDATE_TOAST":return{...e,toasts:e.toasts.map(n=>n.id===t.toast.id?{...n,...t.toast}:n)};case"DISMISS_TOAST":{const{toastId:n}=t;return n?NC(n):e.toasts.forEach(r=>{NC(r.id)}),{...e,toasts:e.toasts.map(r=>r.id===n||n===void 0?{...r,open:!1}:r)}}case"REMOVE_TOAST":return t.toastId===void 0?{...e,toasts:[]}:{...e,toasts:e.toasts.filter(n=>n.id!==t.toastId)}}},Yh=[];let Xh={toasts:[]};function Iu(e){Xh=hB(Xh,e),Yh.forEach(t=>{t(Xh)})}function ul({...e}){const t=fB(),n=o=>Iu({type:"UPDATE_TOAST",toast:{...o,id:t}}),r=()=>Iu({type:"DISMISS_TOAST",toastId:t});return Iu({type:"ADD_TOAST",toast:{...e,id:t,open:!0,onOpenChange:o=>{o||r()}}}),{id:t,dismiss:r,update:n}}function Id(){const[e,t]=d.useState(Xh);return d.useEffect(()=>(Yh.push(t),()=>{const n=Yh.indexOf(t);n>-1&&Yh.splice(n,1)}),[e]),{...e,toast:ul,dismiss:n=>Iu({type:"DISMISS_TOAST",toastId:n})}}const ea={file:null,paintByExampleFile:null,customMask:null,imageHeight:0,imageWidth:0,isInpainting:!1,isPluginRunning:!1,isAdjustingMask:!1,disableShortCuts:!1,windowSize:{height:600,width:800},editorState:{baseBrushSize:cF,brushSizeScale:1,renders:[],extraMasks:[],prevExtraMasks:[],temporaryMasks:[],lineGroups:[],lastLineGroup:[],curLineGroup:[],redoRenders:[],redoCurLines:[],redoLineGroups:[]},interactiveSegState:{isInteractiveSeg:!1,tmpInteractiveSegMask:null,clicks:[]},cropperState:{x:0,y:0,width:512,height:512},extenderState:{x:0,y:0,width:512,height:512},isCropperExtenderResizing:!1,fileManagerState:{sortBy:Es.CTIME,sortOrder:Ou.DESCENDING,layout:"masonry",searchText:"",inputDirectory:"",outputDirectory:""},serverConfig:{plugins:[],modelInfos:[],removeBGModel:"briaai/RMBG-1.4",removeBGModels:[],realesrganModel:"realesr-general-x4v3",realesrganModels:[],interactiveSegModel:"vit_b",interactiveSegModels:[],enableFileManager:!1,enableAutoSaving:!1,enableControlnet:!1,controlnetMethod:"lllyasviel/control_v11p_sd15_canny",disableModelSwitch:!1,isDesktop:!1,samplers:["DPM++ 2M SDE Karras"]},settings:{model:{name:"lama",path:"lama",model_type:"inpaint",support_controlnet:!1,support_strength:!1,support_outpainting:!1,controlnets:[],support_freeu:!1,support_lcm_lora:!1,is_single_file_diffusers:!1,need_prompt:!1},enableControlnet:!1,showCropper:!1,showExtender:!1,extenderDirection:Ln.xy,enableDownloadMask:!1,enableManualInpainting:!1,enableUploadMask:!1,enableAutoExtractPrompt:!0,ldmSteps:30,ldmSampler:Qw.ddim,zitsWireframe:!0,cv2Radius:5,cv2Flag:Jw.INPAINT_NS,prompt:"",negativePrompt:hF,seed:42,seedFixed:!1,sdMaskBlur:12,sdStrength:1,sdSteps:50,sdGuidanceScale:7.5,sdSampler:"DPM++ 2M",sdMatchHistograms:!1,sdScale:1,p2pImageGuidanceScale:1.5,controlnetConditioningScale:.4,controlnetMethod:"lllyasviel/control_v11p_sd15_canny",enableLCMLora:!1,enableFreeu:!1,freeuConfig:{s1:.9,s2:.2,b1:1.2,b2:1.4},powerpaintTask:Ol.text_guided,adjustMaskKernelSize:12}},xt=cB()(_z(Lz((e,t)=>({...ea,showPrevMask:async()=>{if(t().settings.showExtender)return;const{lastLineGroup:n,curLineGroup:r,prevExtraMasks:o,extraMasks:i}=t().editorState;if(r.length!==0||i.length!==0)return;const{imageWidth:s,imageHeight:l}=t(),u=Wh(s,l,[n],o,Uh);try{const f=await dC(u);e(p=>{p.editorState.temporaryMasks.push(f)})}catch(f){console.error(f);return}},hidePrevMask:()=>{e(n=>{n.editorState.temporaryMasks=[]})},getCurrentTargetFile:async()=>{const n=t().file,r=t().editorState.renders;let o=n;if(r.length>0){const i=r[r.length-1];o=await Nu(i.currentSrc,n.name,n.type)}return o},runInpainting:async()=>{const{isInpainting:n,file:r,paintByExampleFile:o,imageWidth:i,imageHeight:s,settings:l,cropperState:u,extenderState:f}=t();if(n||r===null||t().settings.model.support_outpainting&&l.showExtender&&f.height===s&&f.width===i)return;const{lastLineGroup:p,curLineGroup:m,lineGroups:g,renders:y,prevExtraMasks:x,extraMasks:S}=t().editorState,E=m.length===0&&S.length===0&&!l.showExtender;let _=[],b=[];if(E===!0?(b=p,_=x):(b=m,_=S),b.length===0&&_===null&&!l.showExtender){ul({variant:"destructive",description:"Please draw mask on picture"});return}const C=[...g,b];e(O=>{O.isInpainting=!0});let R=r;if(E===!0){if(y.length>1){const O=y[y.length-2];R=await Nu(O.currentSrc,r.name,r.type)}}else if(y.length>0){const O=y[y.length-1];R=await Nu(O.currentSrc,r.name,r.type)}const P=Wh(i,s,[b],_,Uh);if(E){const O=await dC(P);e(A=>{A.editorState.temporaryMasks=[O]})}try{const O=await zj(R,l,u,f,uC(P.toDataURL()),o),{blob:A,seed:D}=O;D&&t().setSeed(parseInt(D,10));const B=new Image;await Vh(B,A);const V=[...y,B];t().setImageSize(B.width,B.height),t().updateEditorState({renders:V,lineGroups:C,lastLineGroup:b,curLineGroup:[],extraMasks:[],prevExtraMasks:_})}catch(O){ul({variant:"destructive",description:O.message?O.message:O.toString()})}t().resetRedoState(),e(O=>{O.isInpainting=!1,O.editorState.temporaryMasks=[]})},runRenderablePlugin:async(n,r,o={upscale:1})=>{const{renders:i,lineGroups:s}=t().editorState;e(l=>{l.isPluginRunning=!0});try{const l=new Date,u=await t().getCurrentTargetFile(),f=await wk(n,r,u,o.upscale),{blob:p}=f;if(n){const y=new Image;await Vh(y,p),e(x=>{x.editorState.extraMasks.push(y)})}else{const y=new Image;await Vh(y,p),t().setImageSize(y.width,y.height);const x=[...i,y],S=[...s,[]];t().updateEditorState({renders:x,lineGroups:S})}const g=new Date().getTime()-l.getTime();ul({description:`Run ${r} successfully in ${g/1e3}s`})}catch(l){ul({variant:"destructive",description:l.message?l.message:l.toString()})}e(l=>{l.isPluginRunning=!1})},updateEditorState:n=>{e(r=>{r.editorState={...r.editorState,...n}})},cleanCurLineGroup:()=>{t().updateEditorState({curLineGroup:[]})},handleCanvasMouseDown:n=>{let r=[];const o=t();o.runMannually()&&(r=[...o.editorState.curLineGroup]),r.push({size:o.getBrushSize(),pts:[n]}),e(i=>{i.editorState.curLineGroup=r})},handleCanvasMouseMove:n=>{e(r=>{const o=r.editorState.curLineGroup;o.length&&o[o.length-1].pts.push(n)})},runMannually:()=>{const n=t();return n.settings.enableManualInpainting||n.settings.model.model_type!==fs},getIsProcessing:()=>t().isInpainting||t().isPluginRunning||t().isAdjustingMask,isSD:()=>t().settings.model.model_type!==fs,undoDisabled:()=>{const n=t().editorState;if(n.renders.length>0)return!1;if(t().runMannually()){if(n.curLineGroup.length===0)return!0}else if(n.renders.length===0)return!0;return!1},undo:()=>{t().runMannually()&&t().editorState.curLineGroup.length!==0?e(n=>{const r=n.editorState;if(r.curLineGroup.length===0)return;r.lastLineGroup=[];const o=r.curLineGroup.pop();r.redoCurLines.push(o)}):e(n=>{const r=n.editorState;if(r.renders.length===0||r.lineGroups.length===0)return;const o=r.lineGroups.pop();r.redoLineGroups.push(o),r.redoCurLines=[],r.curLineGroup=[];const i=r.renders.pop();r.redoRenders.push(i)})},redoDisabled:()=>{const n=t().editorState;if(n.redoRenders.length>0)return!1;if(t().runMannually()){if(n.redoCurLines.length===0)return!0}else if(n.redoRenders.length===0)return!0;return!1},redo:()=>{t().runMannually()&&t().editorState.redoCurLines.length!==0?e(n=>{const r=n.editorState;if(r.redoCurLines.length===0)return;const o=r.redoCurLines.pop();r.curLineGroup.push(o)}):e(n=>{const r=n.editorState;if(r.redoRenders.length===0||r.redoLineGroups.length===0)return;const o=r.redoLineGroups.pop();r.lineGroups.push(o),r.curLineGroup=[];const i=r.redoRenders.pop();r.renders.push(i)})},resetRedoState:()=>{e(n=>{n.editorState.redoCurLines=[],n.editorState.redoLineGroups=[],n.editorState.redoRenders=[]})},updateAppState:n=>{e(()=>n)},getBrushSize:()=>t().editorState.baseBrushSize*t().editorState.brushSizeScale,showPromptInput:()=>{const n=t().settings.model;return n.model_type!==fs&&n.name!==XR},setServerConfig:n=>{e(r=>{r.serverConfig=n,r.settings.enableControlnet=n.enableControlnet,r.settings.controlnetMethod=n.controlnetMethod})},updateSettings:n=>{e(r=>{r.settings={...r.settings,...n}})},setModel:n=>{e(r=>{r.settings.model=n,n.support_controlnet&&!n.controlnets.includes(r.settings.controlnetMethod)&&(r.settings.controlnetMethod=n.controlnets[0])})},updateFileManagerState:n=>{e(r=>{r.fileManagerState={...r.fileManagerState,...n}})},updateInteractiveSegState:n=>{e(r=>({...r,interactiveSegState:{...r.interactiveSegState,...n}}))},resetInteractiveSegState:()=>{t().updateInteractiveSegState(ea.interactiveSegState)},handleInteractiveSegAccept:()=>{e(n=>{n.interactiveSegState.tmpInteractiveSegMask&&n.editorState.extraMasks.push(n.interactiveSegState.tmpInteractiveSegMask),n.interactiveSegState={...ea.interactiveSegState}})},setIsInpainting:n=>e(r=>{r.isInpainting=n}),setFile:async n=>{if(t().settings.enableAutoExtractPrompt)try{const r=await Kj(n);r.prompt&&e(o=>{o.settings.prompt=r.prompt}),r.negative_prompt&&e(o=>{o.settings.negativePrompt=r.negative_prompt})}catch(r){ul({variant:"destructive",description:r.message?r.message:r.toString()})}e(r=>{r.file=n,r.interactiveSegState=ea.interactiveSegState,r.editorState=ea.editorState,r.cropperState=ea.cropperState})},setCustomFile:n=>e(r=>{r.customMask=n}),setBaseBrushSize:n=>e(r=>{r.editorState.baseBrushSize=n}),setImageSize:(n,r)=>{e(o=>{o.imageWidth=n,o.imageHeight=r,o.editorState.brushSizeScale=Math.max(Math.min(n,r),512)/512}),t().resetExtender(n,r)},setCropperX:n=>e(r=>{r.cropperState.x=n}),setCropperY:n=>e(r=>{r.cropperState.y=n}),setCropperWidth:n=>e(r=>{r.cropperState.width=n}),setCropperHeight:n=>e(r=>{r.cropperState.height=n}),setExtenderX:n=>e(r=>{r.extenderState.x=n}),setExtenderY:n=>e(r=>{r.extenderState.y=n}),setExtenderWidth:n=>e(r=>{r.extenderState.width=n}),setExtenderHeight:n=>e(r=>{r.extenderState.height=n}),setIsCropperExtenderResizing:n=>e(r=>{r.isCropperExtenderResizing=n}),updateExtenderDirection:n=>{console.log(`updateExtenderDirection: ${JSON.stringify(t().extenderState)}`),e(r=>{r.settings.extenderDirection=n,r.extenderState.x=0,r.extenderState.y=0,r.extenderState.width=r.imageWidth,r.extenderState.height=r.imageHeight}),t().updateExtenderByBuiltIn(n,1.5)},updateExtenderByBuiltIn:(n,r)=>{const o={...ea.extenderState};let{x:i,y:s,width:l,height:u}=o;const{imageWidth:f,imageHeight:p}=t();switch(l=f,u=p,n){case Ln.x:i=-Math.ceil(f*(r-1)/2),l=Math.ceil(f*r);break;case Ln.y:s=-Math.ceil(p*(r-1)/2),u=Math.ceil(p*r);break;case Ln.xy:i=-Math.ceil(f*(r-1)/2),s=-Math.ceil(p*(r-1)/2),l=Math.ceil(f*r),u=Math.ceil(p*r);break}e(m=>{m.extenderState.x=i,m.extenderState.y=s,m.extenderState.width=l,m.extenderState.height=u})},resetExtender:(n,r)=>{e(o=>{o.extenderState.x=0,o.extenderState.y=0,o.extenderState.width=n,o.extenderState.height=r})},setSeed:n=>e(r=>{r.settings.seed=n}),adjustMask:async n=>{const{imageWidth:r,imageHeight:o}=t(),{curLineGroup:i,extraMasks:s}=t().editorState,{adjustMaskKernelSize:l}=t().settings;if(i.length===0&&s.length===0)return;e(g=>{g.isAdjustingMask=!0});const u=Wh(r,o,[i],s,Uh),f=uC(u.toDataURL()),p=await Gj(f,n,l),m=await mF(p);e(g=>{g.editorState.extraMasks=[m],g.editorState.curLineGroup=[]}),e(g=>{g.isAdjustingMask=!1})},clearMask:()=>{e(n=>{n.editorState.extraMasks=[],n.editorState.curLineGroup=[]})}})),{name:"ZUSTAND_STATE",version:1,partialize:e=>Object.fromEntries(Object.entries(e).filter(([t])=>["fileManagerState","settings"].includes(t)))}),Ez),Bm=d.forwardRef(({className:e,type:t,...n},r)=>{const o=xt(l=>l.updateAppState),i=()=>{o({disableShortCuts:!0})},s=()=>{o({disableShortCuts:!1})};return v.jsx("input",{type:t,className:_e("flex h-8 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",e),ref:r,autoComplete:"off",tabIndex:-1,onFocus:i,onBlur:s,...n})});Bm.displayName="Input";const Yn=d.forwardRef(({numberValue:e,allowFloat:t,onNumberValueChange:n,...r},o)=>{const[i,s]=d.useState(e.toString());d.useEffect(()=>{i!==e.toString()+"."&&s(e.toString())},[e]);const l=u=>{let p=u.target.value;if(t){if(p=p.replace(/[^0-9.]/g,"").replace(/(\..*?)\..*/g,"$1"),p.length===0){n(0);return}n(parseFloat(p))}else{if(p=p.replace(/\D/g,""),p.length===0){n(0);return}n(parseInt(p,10))}s(p)};return v.jsx(Bm,{ref:o,value:i,onInput:l,...r})});function ue(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 pB(e,t){const n=d.createContext(t);function r(i){const{children:s,...l}=i,u=d.useMemo(()=>l,Object.values(l));return d.createElement(n.Provider,{value:u},s)}function o(i){const s=d.useContext(n);if(s)return s;if(t!==void 0)return t;throw new Error(`\`${i}\` must be used within \`${e}\``)}return r.displayName=e+"Provider",[r,o]}function Mn(e,t=[]){let n=[];function r(i,s){const l=d.createContext(s),u=n.length;n=[...n,s];function f(m){const{scope:g,children:y,...x}=m,S=(g==null?void 0:g[e][u])||l,E=d.useMemo(()=>x,Object.values(x));return d.createElement(S.Provider,{value:E},y)}function p(m,g){const y=(g==null?void 0:g[e][u])||l,x=d.useContext(y);if(x)return x;if(s!==void 0)return s;throw new Error(`\`${m}\` must be used within \`${i}\``)}return f.displayName=i+"Provider",[f,p]}const o=()=>{const i=n.map(s=>d.createContext(s));return function(l){const u=(l==null?void 0:l[e])||i;return d.useMemo(()=>({[`__scope${e}`]:{...l,[e]:u}}),[l,u])}};return o.scopeName=e,[r,mB(o,...t)]}function mB(...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(i){const s=r.reduce((l,{useScope:u,scopeName:f})=>{const m=u(i)[`__scope${f}`];return{...l,...m}},{});return d.useMemo(()=>({[`__scope${t.scopeName}`]:s}),[s])}};return n.scopeName=t.scopeName,n}const gB=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","span","svg","ul"],Ae=gB.reduce((e,t)=>{const n=d.forwardRef((r,o)=>{const{asChild:i,...s}=r,l=i?Zo:t;return d.useEffect(()=>{window[Symbol.for("radix-ui")]=!0},[]),d.createElement(l,Y({},s,{ref:o}))});return n.displayName=`Primitive.${t}`,{...e,[t]:n}},{});function dx(e,t){e&&Is.flushSync(()=>e.dispatchEvent(t))}function Ft(e){const t=d.useRef(e);return d.useEffect(()=>{t.current=e}),d.useMemo(()=>(...n)=>{var r;return(r=t.current)===null||r===void 0?void 0:r.call(t,...n)},[])}function vB(e,t=globalThis==null?void 0:globalThis.document){const n=Ft(e);d.useEffect(()=>{const r=o=>{o.key==="Escape"&&n(o)};return t.addEventListener("keydown",r),()=>t.removeEventListener("keydown",r)},[n,t])}const l1="dismissableLayer.update",yB="dismissableLayer.pointerDownOutside",wB="dismissableLayer.focusOutside";let DC;const Mk=d.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),Ec=d.forwardRef((e,t)=>{var n;const{disableOutsidePointerEvents:r=!1,onEscapeKeyDown:o,onPointerDownOutside:i,onFocusOutside:s,onInteractOutside:l,onDismiss:u,...f}=e,p=d.useContext(Mk),[m,g]=d.useState(null),y=(n=m==null?void 0:m.ownerDocument)!==null&&n!==void 0?n:globalThis==null?void 0:globalThis.document,[,x]=d.useState({}),S=Ue(t,D=>g(D)),E=Array.from(p.layers),[_]=[...p.layersWithOutsidePointerEventsDisabled].slice(-1),b=E.indexOf(_),C=m?E.indexOf(m):-1,R=p.layersWithOutsidePointerEventsDisabled.size>0,P=C>=b,O=bB(D=>{const B=D.target,V=[...p.branches].some(J=>J.contains(B));!P||V||(i==null||i(D),l==null||l(D),D.defaultPrevented||u==null||u())},y),A=SB(D=>{const B=D.target;[...p.branches].some(J=>J.contains(B))||(s==null||s(D),l==null||l(D),D.defaultPrevented||u==null||u())},y);return vB(D=>{C===p.layers.size-1&&(o==null||o(D),!D.defaultPrevented&&u&&(D.preventDefault(),u()))},y),d.useEffect(()=>{if(m)return r&&(p.layersWithOutsidePointerEventsDisabled.size===0&&(DC=y.body.style.pointerEvents,y.body.style.pointerEvents="none"),p.layersWithOutsidePointerEventsDisabled.add(m)),p.layers.add(m),IC(),()=>{r&&p.layersWithOutsidePointerEventsDisabled.size===1&&(y.body.style.pointerEvents=DC)}},[m,y,r,p]),d.useEffect(()=>()=>{m&&(p.layers.delete(m),p.layersWithOutsidePointerEventsDisabled.delete(m),IC())},[m,p]),d.useEffect(()=>{const D=()=>x({});return document.addEventListener(l1,D),()=>document.removeEventListener(l1,D)},[]),d.createElement(Ae.div,Y({},f,{ref:S,style:{pointerEvents:R?P?"auto":"none":void 0,...e.style},onFocusCapture:ue(e.onFocusCapture,A.onFocusCapture),onBlurCapture:ue(e.onBlurCapture,A.onBlurCapture),onPointerDownCapture:ue(e.onPointerDownCapture,O.onPointerDownCapture)}))}),xB=d.forwardRef((e,t)=>{const n=d.useContext(Mk),r=d.useRef(null),o=Ue(t,r);return d.useEffect(()=>{const i=r.current;if(i)return n.branches.add(i),()=>{n.branches.delete(i)}},[n.branches]),d.createElement(Ae.div,Y({},e,{ref:o}))});function bB(e,t=globalThis==null?void 0:globalThis.document){const n=Ft(e),r=d.useRef(!1),o=d.useRef(()=>{});return d.useEffect(()=>{const i=l=>{if(l.target&&!r.current){let p=function(){Ok(yB,n,f,{discrete:!0})};var u=p;const f={originalEvent:l};l.pointerType==="touch"?(t.removeEventListener("click",o.current),o.current=p,t.addEventListener("click",o.current,{once:!0})):p()}else t.removeEventListener("click",o.current);r.current=!1},s=window.setTimeout(()=>{t.addEventListener("pointerdown",i)},0);return()=>{window.clearTimeout(s),t.removeEventListener("pointerdown",i),t.removeEventListener("click",o.current)}},[t,n]),{onPointerDownCapture:()=>r.current=!0}}function SB(e,t=globalThis==null?void 0:globalThis.document){const n=Ft(e),r=d.useRef(!1);return d.useEffect(()=>{const o=i=>{i.target&&!r.current&&Ok(wB,n,{originalEvent:i},{discrete:!1})};return t.addEventListener("focusin",o),()=>t.removeEventListener("focusin",o)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function IC(){const e=new CustomEvent(l1);document.dispatchEvent(e)}function Ok(e,t,n,{discrete:r}){const o=n.originalEvent.target,i=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&o.addEventListener(e,t,{once:!0}),r?dx(o,i):o.dispatchEvent(i)}const _B=Ec,EB=xB,An=globalThis!=null&&globalThis.document?d.useLayoutEffect:()=>{},CB=U9.useId||(()=>{});let $B=0;function nr(e){const[t,n]=d.useState(CB());return An(()=>{e||n(r=>r??String($B++))},[e]),e||(t?`radix-${t}`:"")}const RB=["top","right","bottom","left"],Ts=Math.min,hr=Math.max,Ip=Math.round,dh=Math.floor,Ps=e=>({x:e,y:e}),kB={left:"right",right:"left",bottom:"top",top:"bottom"},TB={start:"end",end:"start"};function c1(e,t,n){return hr(e,Ts(t,n))}function Ci(e,t){return typeof e=="function"?e(t):e}function $i(e){return e.split("-")[0]}function Cc(e){return e.split("-")[1]}function fx(e){return e==="x"?"y":"x"}function hx(e){return e==="y"?"height":"width"}function $c(e){return["top","bottom"].includes($i(e))?"y":"x"}function px(e){return fx($c(e))}function PB(e,t,n){n===void 0&&(n=!1);const r=Cc(e),o=px(e),i=hx(o);let s=o==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[i]>t.floating[i]&&(s=Lp(s)),[s,Lp(s)]}function AB(e){const t=Lp(e);return[u1(e),t,u1(t)]}function u1(e){return e.replace(/start|end/g,t=>TB[t])}function MB(e,t,n){const r=["left","right"],o=["right","left"],i=["top","bottom"],s=["bottom","top"];switch(e){case"top":case"bottom":return n?t?o:r:t?r:o;case"left":case"right":return t?i:s;default:return[]}}function OB(e,t,n,r){const o=Cc(e);let i=MB($i(e),n==="start",r);return o&&(i=i.map(s=>s+"-"+o),t&&(i=i.concat(i.map(u1)))),i}function Lp(e){return e.replace(/left|right|bottom|top/g,t=>kB[t])}function NB(e){return{top:0,right:0,bottom:0,left:0,...e}}function Nk(e){return typeof e!="number"?NB(e):{top:e,right:e,bottom:e,left:e}}function Fp(e){return{...e,top:e.y,left:e.x,right:e.x+e.width,bottom:e.y+e.height}}function LC(e,t,n){let{reference:r,floating:o}=e;const i=$c(t),s=px(t),l=hx(s),u=$i(t),f=i==="y",p=r.x+r.width/2-o.width/2,m=r.y+r.height/2-o.height/2,g=r[l]/2-o[l]/2;let y;switch(u){case"top":y={x:p,y:r.y-o.height};break;case"bottom":y={x:p,y:r.y+r.height};break;case"right":y={x:r.x+r.width,y:m};break;case"left":y={x:r.x-o.width,y:m};break;default:y={x:r.x,y:r.y}}switch(Cc(t)){case"start":y[s]-=g*(n&&f?-1:1);break;case"end":y[s]+=g*(n&&f?-1:1);break}return y}const DB=async(e,t,n)=>{const{placement:r="bottom",strategy:o="absolute",middleware:i=[],platform:s}=n,l=i.filter(Boolean),u=await(s.isRTL==null?void 0:s.isRTL(t));let f=await s.getElementRects({reference:e,floating:t,strategy:o}),{x:p,y:m}=LC(f,r,u),g=r,y={},x=0;for(let S=0;S({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:o,rects:i,platform:s,elements:l,middlewareData:u}=t,{element:f,padding:p=0}=Ci(e,t)||{};if(f==null)return{};const m=Nk(p),g={x:n,y:r},y=px(o),x=hx(y),S=await s.getDimensions(f),E=y==="y",_=E?"top":"left",b=E?"bottom":"right",C=E?"clientHeight":"clientWidth",R=i.reference[x]+i.reference[y]-g[y]-i.floating[x],P=g[y]-i.reference[y],O=await(s.getOffsetParent==null?void 0:s.getOffsetParent(f));let A=O?O[C]:0;(!A||!await(s.isElement==null?void 0:s.isElement(O)))&&(A=l.floating[C]||i.floating[x]);const D=R/2-P/2,B=A/2-S[x]/2-1,V=Ts(m[_],B),J=Ts(m[b],B),G=V,se=A-S[x]-J,U=A/2-S[x]/2+D,ne=c1(G,U,se),M=!u.arrow&&Cc(o)!=null&&U!=ne&&i.reference[x]/2-(UG<=0)){var B,V;const G=(((B=i.flip)==null?void 0:B.index)||0)+1,se=P[G];if(se)return{data:{index:G,overflows:D},reset:{placement:se}};let U=(V=D.filter(ne=>ne.overflows[0]<=0).sort((ne,M)=>ne.overflows[1]-M.overflows[1])[0])==null?void 0:V.placement;if(!U)switch(y){case"bestFit":{var J;const ne=(J=D.map(M=>[M.placement,M.overflows.filter(ee=>ee>0).reduce((ee,H)=>ee+H,0)]).sort((M,ee)=>M[1]-ee[1])[0])==null?void 0:J[0];ne&&(U=ne);break}case"initialPlacement":U=l;break}if(o!==U)return{reset:{placement:U}}}return{}}}};function jC(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function zC(e){return RB.some(t=>e[t]>=0)}const LB=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n}=t,{strategy:r="referenceHidden",...o}=Ci(e,t);switch(r){case"referenceHidden":{const i=await ld(t,{...o,elementContext:"reference"}),s=jC(i,n.reference);return{data:{referenceHiddenOffsets:s,referenceHidden:zC(s)}}}case"escaped":{const i=await ld(t,{...o,altBoundary:!0}),s=jC(i,n.floating);return{data:{escapedOffsets:s,escaped:zC(s)}}}default:return{}}}}};async function FB(e,t){const{placement:n,platform:r,elements:o}=e,i=await(r.isRTL==null?void 0:r.isRTL(o.floating)),s=$i(n),l=Cc(n),u=$c(n)==="y",f=["left","top"].includes(s)?-1:1,p=i&&u?-1:1,m=Ci(t,e);let{mainAxis:g,crossAxis:y,alignmentAxis:x}=typeof m=="number"?{mainAxis:m,crossAxis:0,alignmentAxis:null}:{mainAxis:0,crossAxis:0,alignmentAxis:null,...m};return l&&typeof x=="number"&&(y=l==="end"?x*-1:x),u?{x:y*p,y:g*f}:{x:g*f,y:y*p}}const jB=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){const{x:n,y:r}=t,o=await FB(t,e);return{x:n+o.x,y:r+o.y,data:o}}}},zB=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:o}=t,{mainAxis:i=!0,crossAxis:s=!1,limiter:l={fn:E=>{let{x:_,y:b}=E;return{x:_,y:b}}},...u}=Ci(e,t),f={x:n,y:r},p=await ld(t,u),m=$c($i(o)),g=fx(m);let y=f[g],x=f[m];if(i){const E=g==="y"?"top":"left",_=g==="y"?"bottom":"right",b=y+p[E],C=y-p[_];y=c1(b,y,C)}if(s){const E=m==="y"?"top":"left",_=m==="y"?"bottom":"right",b=x+p[E],C=x-p[_];x=c1(b,x,C)}const S=l.fn({...t,[g]:y,[m]:x});return{...S,data:{x:S.x-n,y:S.y-r}}}}},BB=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:r,placement:o,rects:i,middlewareData:s}=t,{offset:l=0,mainAxis:u=!0,crossAxis:f=!0}=Ci(e,t),p={x:n,y:r},m=$c(o),g=fx(m);let y=p[g],x=p[m];const S=Ci(l,t),E=typeof S=="number"?{mainAxis:S,crossAxis:0}:{mainAxis:0,crossAxis:0,...S};if(u){const C=g==="y"?"height":"width",R=i.reference[g]-i.floating[C]+E.mainAxis,P=i.reference[g]+i.reference[C]-E.mainAxis;yP&&(y=P)}if(f){var _,b;const C=g==="y"?"width":"height",R=["top","left"].includes($i(o)),P=i.reference[m]-i.floating[C]+(R&&((_=s.offset)==null?void 0:_[m])||0)+(R?0:E.crossAxis),O=i.reference[m]+i.reference[C]+(R?0:((b=s.offset)==null?void 0:b[m])||0)-(R?E.crossAxis:0);xO&&(x=O)}return{[g]:y,[m]:x}}}},UB=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){const{placement:n,rects:r,platform:o,elements:i}=t,{apply:s=()=>{},...l}=Ci(e,t),u=await ld(t,l),f=$i(n),p=Cc(n),m=$c(n)==="y",{width:g,height:y}=r.floating;let x,S;f==="top"||f==="bottom"?(x=f,S=p===(await(o.isRTL==null?void 0:o.isRTL(i.floating))?"start":"end")?"left":"right"):(S=f,x=p==="end"?"top":"bottom");const E=y-u[x],_=g-u[S],b=!t.middlewareData.shift;let C=E,R=_;if(m){const O=g-u.left-u.right;R=p||b?Ts(_,O):O}else{const O=y-u.top-u.bottom;C=p||b?Ts(E,O):O}if(b&&!p){const O=hr(u.left,0),A=hr(u.right,0),D=hr(u.top,0),B=hr(u.bottom,0);m?R=g-2*(O!==0||A!==0?O+A:hr(u.left,u.right)):C=y-2*(D!==0||B!==0?D+B:hr(u.top,u.bottom))}await s({...t,availableWidth:R,availableHeight:C});const P=await o.getDimensions(i.floating);return g!==P.width||y!==P.height?{reset:{rects:!0}}:{}}}};function As(e){return Dk(e)?(e.nodeName||"").toLowerCase():"#document"}function vr(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Mi(e){var t;return(t=(Dk(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function Dk(e){return e instanceof Node||e instanceof vr(e).Node}function Ri(e){return e instanceof Element||e instanceof vr(e).Element}function qo(e){return e instanceof HTMLElement||e instanceof vr(e).HTMLElement}function BC(e){return typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof vr(e).ShadowRoot}function Ld(e){const{overflow:t,overflowX:n,overflowY:r,display:o}=Xr(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&!["inline","contents"].includes(o)}function VB(e){return["table","td","th"].includes(As(e))}function mx(e){const t=gx(),n=Xr(e);return n.transform!=="none"||n.perspective!=="none"||(n.containerType?n.containerType!=="normal":!1)||!t&&(n.backdropFilter?n.backdropFilter!=="none":!1)||!t&&(n.filter?n.filter!=="none":!1)||["transform","perspective","filter"].some(r=>(n.willChange||"").includes(r))||["paint","layout","strict","content"].some(r=>(n.contain||"").includes(r))}function WB(e){let t=cc(e);for(;qo(t)&&!Um(t);){if(mx(t))return t;t=cc(t)}return null}function gx(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}function Um(e){return["html","body","#document"].includes(As(e))}function Xr(e){return vr(e).getComputedStyle(e)}function Vm(e){return Ri(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.pageXOffset,scrollTop:e.pageYOffset}}function cc(e){if(As(e)==="html")return e;const t=e.assignedSlot||e.parentNode||BC(e)&&e.host||Mi(e);return BC(t)?t.host:t}function Ik(e){const t=cc(e);return Um(t)?e.ownerDocument?e.ownerDocument.body:e.body:qo(t)&&Ld(t)?t:Ik(t)}function cd(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const o=Ik(e),i=o===((r=e.ownerDocument)==null?void 0:r.body),s=vr(o);return i?t.concat(s,s.visualViewport||[],Ld(o)?o:[],s.frameElement&&n?cd(s.frameElement):[]):t.concat(o,cd(o,[],n))}function Lk(e){const t=Xr(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const o=qo(e),i=o?e.offsetWidth:n,s=o?e.offsetHeight:r,l=Ip(n)!==i||Ip(r)!==s;return l&&(n=i,r=s),{width:n,height:r,$:l}}function vx(e){return Ri(e)?e:e.contextElement}function Nl(e){const t=vx(e);if(!qo(t))return Ps(1);const n=t.getBoundingClientRect(),{width:r,height:o,$:i}=Lk(t);let s=(i?Ip(n.width):n.width)/r,l=(i?Ip(n.height):n.height)/o;return(!s||!Number.isFinite(s))&&(s=1),(!l||!Number.isFinite(l))&&(l=1),{x:s,y:l}}const HB=Ps(0);function Fk(e){const t=vr(e);return!gx()||!t.visualViewport?HB:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function KB(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==vr(e)?!1:t}function Na(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const o=e.getBoundingClientRect(),i=vx(e);let s=Ps(1);t&&(r?Ri(r)&&(s=Nl(r)):s=Nl(e));const l=KB(i,n,r)?Fk(i):Ps(0);let u=(o.left+l.x)/s.x,f=(o.top+l.y)/s.y,p=o.width/s.x,m=o.height/s.y;if(i){const g=vr(i),y=r&&Ri(r)?vr(r):r;let x=g.frameElement;for(;x&&r&&y!==g;){const S=Nl(x),E=x.getBoundingClientRect(),_=Xr(x),b=E.left+(x.clientLeft+parseFloat(_.paddingLeft))*S.x,C=E.top+(x.clientTop+parseFloat(_.paddingTop))*S.y;u*=S.x,f*=S.y,p*=S.x,m*=S.y,u+=b,f+=C,x=vr(x).frameElement}}return Fp({width:p,height:m,x:u,y:f})}function GB(e){let{rect:t,offsetParent:n,strategy:r}=e;const o=qo(n),i=Mi(n);if(n===i)return t;let s={scrollLeft:0,scrollTop:0},l=Ps(1);const u=Ps(0);if((o||!o&&r!=="fixed")&&((As(n)!=="body"||Ld(i))&&(s=Vm(n)),qo(n))){const f=Na(n);l=Nl(n),u.x=f.x+n.clientLeft,u.y=f.y+n.clientTop}return{width:t.width*l.x,height:t.height*l.y,x:t.x*l.x-s.scrollLeft*l.x+u.x,y:t.y*l.y-s.scrollTop*l.y+u.y}}function YB(e){return Array.from(e.getClientRects())}function jk(e){return Na(Mi(e)).left+Vm(e).scrollLeft}function XB(e){const t=Mi(e),n=Vm(e),r=e.ownerDocument.body,o=hr(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),i=hr(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let s=-n.scrollLeft+jk(e);const l=-n.scrollTop;return Xr(r).direction==="rtl"&&(s+=hr(t.clientWidth,r.clientWidth)-o),{width:o,height:i,x:s,y:l}}function ZB(e,t){const n=vr(e),r=Mi(e),o=n.visualViewport;let i=r.clientWidth,s=r.clientHeight,l=0,u=0;if(o){i=o.width,s=o.height;const f=gx();(!f||f&&t==="fixed")&&(l=o.offsetLeft,u=o.offsetTop)}return{width:i,height:s,x:l,y:u}}function qB(e,t){const n=Na(e,!0,t==="fixed"),r=n.top+e.clientTop,o=n.left+e.clientLeft,i=qo(e)?Nl(e):Ps(1),s=e.clientWidth*i.x,l=e.clientHeight*i.y,u=o*i.x,f=r*i.y;return{width:s,height:l,x:u,y:f}}function UC(e,t,n){let r;if(t==="viewport")r=ZB(e,n);else if(t==="document")r=XB(Mi(e));else if(Ri(t))r=qB(t,n);else{const o=Fk(e);r={...t,x:t.x-o.x,y:t.y-o.y}}return Fp(r)}function zk(e,t){const n=cc(e);return n===t||!Ri(n)||Um(n)?!1:Xr(n).position==="fixed"||zk(n,t)}function QB(e,t){const n=t.get(e);if(n)return n;let r=cd(e,[],!1).filter(l=>Ri(l)&&As(l)!=="body"),o=null;const i=Xr(e).position==="fixed";let s=i?cc(e):e;for(;Ri(s)&&!Um(s);){const l=Xr(s),u=mx(s);!u&&l.position==="fixed"&&(o=null),(i?!u&&!o:!u&&l.position==="static"&&!!o&&["absolute","fixed"].includes(o.position)||Ld(s)&&!u&&zk(e,s))?r=r.filter(p=>p!==s):o=l,s=cc(s)}return t.set(e,r),r}function JB(e){let{element:t,boundary:n,rootBoundary:r,strategy:o}=e;const s=[...n==="clippingAncestors"?QB(t,this._c):[].concat(n),r],l=s[0],u=s.reduce((f,p)=>{const m=UC(t,p,o);return f.top=hr(m.top,f.top),f.right=Ts(m.right,f.right),f.bottom=Ts(m.bottom,f.bottom),f.left=hr(m.left,f.left),f},UC(t,l,o));return{width:u.right-u.left,height:u.bottom-u.top,x:u.left,y:u.top}}function eU(e){return Lk(e)}function tU(e,t,n){const r=qo(t),o=Mi(t),i=n==="fixed",s=Na(e,!0,i,t);let l={scrollLeft:0,scrollTop:0};const u=Ps(0);if(r||!r&&!i)if((As(t)!=="body"||Ld(o))&&(l=Vm(t)),r){const f=Na(t,!0,i,t);u.x=f.x+t.clientLeft,u.y=f.y+t.clientTop}else o&&(u.x=jk(o));return{x:s.left+l.scrollLeft-u.x,y:s.top+l.scrollTop-u.y,width:s.width,height:s.height}}function VC(e,t){return!qo(e)||Xr(e).position==="fixed"?null:t?t(e):e.offsetParent}function Bk(e,t){const n=vr(e);if(!qo(e))return n;let r=VC(e,t);for(;r&&VB(r)&&Xr(r).position==="static";)r=VC(r,t);return r&&(As(r)==="html"||As(r)==="body"&&Xr(r).position==="static"&&!mx(r))?n:r||WB(e)||n}const nU=async function(e){let{reference:t,floating:n,strategy:r}=e;const o=this.getOffsetParent||Bk,i=this.getDimensions;return{reference:tU(t,await o(n),r),floating:{x:0,y:0,...await i(n)}}};function rU(e){return Xr(e).direction==="rtl"}const oU={convertOffsetParentRelativeRectToViewportRelativeRect:GB,getDocumentElement:Mi,getClippingRect:JB,getOffsetParent:Bk,getElementRects:nU,getClientRects:YB,getDimensions:eU,getScale:Nl,isElement:Ri,isRTL:rU};function iU(e,t){let n=null,r;const o=Mi(e);function i(){clearTimeout(r),n&&n.disconnect(),n=null}function s(l,u){l===void 0&&(l=!1),u===void 0&&(u=1),i();const{left:f,top:p,width:m,height:g}=e.getBoundingClientRect();if(l||t(),!m||!g)return;const y=dh(p),x=dh(o.clientWidth-(f+m)),S=dh(o.clientHeight-(p+g)),E=dh(f),b={rootMargin:-y+"px "+-x+"px "+-S+"px "+-E+"px",threshold:hr(0,Ts(1,u))||1};let C=!0;function R(P){const O=P[0].intersectionRatio;if(O!==u){if(!C)return s();O?s(!1,O):r=setTimeout(()=>{s(!1,1e-7)},100)}C=!1}try{n=new IntersectionObserver(R,{...b,root:o.ownerDocument})}catch{n=new IntersectionObserver(R,b)}n.observe(e)}return s(!0),i}function sU(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:o=!0,ancestorResize:i=!0,elementResize:s=typeof ResizeObserver=="function",layoutShift:l=typeof IntersectionObserver=="function",animationFrame:u=!1}=r,f=vx(e),p=o||i?[...f?cd(f):[],...cd(t)]:[];p.forEach(_=>{o&&_.addEventListener("scroll",n,{passive:!0}),i&&_.addEventListener("resize",n)});const m=f&&l?iU(f,n):null;let g=-1,y=null;s&&(y=new ResizeObserver(_=>{let[b]=_;b&&b.target===f&&y&&(y.unobserve(t),cancelAnimationFrame(g),g=requestAnimationFrame(()=>{y&&y.observe(t)})),n()}),f&&!u&&y.observe(f),y.observe(t));let x,S=u?Na(e):null;u&&E();function E(){const _=Na(e);S&&(_.x!==S.x||_.y!==S.y||_.width!==S.width||_.height!==S.height)&&n(),S=_,x=requestAnimationFrame(E)}return n(),()=>{p.forEach(_=>{o&&_.removeEventListener("scroll",n),i&&_.removeEventListener("resize",n)}),m&&m(),y&&y.disconnect(),y=null,u&&cancelAnimationFrame(x)}}const aU=(e,t,n)=>{const r=new Map,o={platform:oU,...n},i={...o.platform,_c:r};return DB(e,t,{...o,platform:i})},lU=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:o}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?FC({element:r.current,padding:o}).fn(n):{}:r?FC({element:r,padding:o}).fn(n):{}}}};var Zh=typeof document<"u"?d.useLayoutEffect:d.useEffect;function jp(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(!jp(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(!{}.hasOwnProperty.call(t,o[r]))return!1;for(r=n;r--!==0;){const i=o[r];if(!(i==="_owner"&&e.$$typeof)&&!jp(e[i],t[i]))return!1}return!0}return e!==e&&t!==t}function Uk(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function WC(e,t){const n=Uk(e);return Math.round(t*n)/n}function HC(e){const t=d.useRef(e);return Zh(()=>{t.current=e}),t}function cU(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:o,elements:{reference:i,floating:s}={},transform:l=!0,whileElementsMounted:u,open:f}=e,[p,m]=d.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[g,y]=d.useState(r);jp(g,r)||y(r);const[x,S]=d.useState(null),[E,_]=d.useState(null),b=d.useCallback(M=>{M!=O.current&&(O.current=M,S(M))},[S]),C=d.useCallback(M=>{M!==A.current&&(A.current=M,_(M))},[_]),R=i||x,P=s||E,O=d.useRef(null),A=d.useRef(null),D=d.useRef(p),B=HC(u),V=HC(o),J=d.useCallback(()=>{if(!O.current||!A.current)return;const M={placement:t,strategy:n,middleware:g};V.current&&(M.platform=V.current),aU(O.current,A.current,M).then(ee=>{const H={...ee,isPositioned:!0};G.current&&!jp(D.current,H)&&(D.current=H,Is.flushSync(()=>{m(H)}))})},[g,t,n,V]);Zh(()=>{f===!1&&D.current.isPositioned&&(D.current.isPositioned=!1,m(M=>({...M,isPositioned:!1})))},[f]);const G=d.useRef(!1);Zh(()=>(G.current=!0,()=>{G.current=!1}),[]),Zh(()=>{if(R&&(O.current=R),P&&(A.current=P),R&&P){if(B.current)return B.current(R,P,J);J()}},[R,P,J,B]);const se=d.useMemo(()=>({reference:O,floating:A,setReference:b,setFloating:C}),[b,C]),U=d.useMemo(()=>({reference:R,floating:P}),[R,P]),ne=d.useMemo(()=>{const M={position:n,left:0,top:0};if(!U.floating)return M;const ee=WC(U.floating,p.x),H=WC(U.floating,p.y);return l?{...M,transform:"translate("+ee+"px, "+H+"px)",...Uk(U.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:ee,top:H}},[n,l,U.floating,p.x,p.y]);return d.useMemo(()=>({...p,update:J,refs:se,elements:U,floatingStyles:ne}),[p,J,se,U,ne])}function yx(e){const[t,n]=d.useState(void 0);return An(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(o=>{if(!Array.isArray(o)||!o.length)return;const i=o[0];let s,l;if("borderBoxSize"in i){const u=i.borderBoxSize,f=Array.isArray(u)?u[0]:u;s=f.inlineSize,l=f.blockSize}else s=e.offsetWidth,l=e.offsetHeight;n({width:s,height:l})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}const Vk="Popper",[Wk,Fs]=Mn(Vk),[uU,Hk]=Wk(Vk),dU=e=>{const{__scopePopper:t,children:n}=e,[r,o]=d.useState(null);return d.createElement(uU,{scope:t,anchor:r,onAnchorChange:o},n)},fU="PopperAnchor",hU=d.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...o}=e,i=Hk(fU,n),s=d.useRef(null),l=Ue(t,s);return d.useEffect(()=>{i.onAnchorChange((r==null?void 0:r.current)||s.current)}),r?null:d.createElement(Ae.div,Y({},o,{ref:l}))}),Kk="PopperContent",[pU,pte]=Wk(Kk),mU=d.forwardRef((e,t)=>{var n,r,o,i,s,l,u,f;const{__scopePopper:p,side:m="bottom",sideOffset:g=0,align:y="center",alignOffset:x=0,arrowPadding:S=0,avoidCollisions:E=!0,collisionBoundary:_=[],collisionPadding:b=0,sticky:C="partial",hideWhenDetached:R=!1,updatePositionStrategy:P="optimized",onPlaced:O,...A}=e,D=Hk(Kk,p),[B,V]=d.useState(null),J=Ue(t,Kt=>V(Kt)),[G,se]=d.useState(null),U=yx(G),ne=(n=U==null?void 0:U.width)!==null&&n!==void 0?n:0,M=(r=U==null?void 0:U.height)!==null&&r!==void 0?r:0,ee=m+(y!=="center"?"-"+y:""),H=typeof b=="number"?b:{top:0,right:0,bottom:0,left:0,...b},X=Array.isArray(_)?_:[_],W=X.length>0,le={padding:H,boundary:X.filter(gU),altBoundary:W},{refs:pe,floatingStyles:$e,placement:Ve,isPositioned:We,middlewareData:Ne}=cU({strategy:"fixed",placement:ee,whileElementsMounted:(...Kt)=>sU(...Kt,{animationFrame:P==="always"}),elements:{reference:D.anchor},middleware:[jB({mainAxis:g+M,alignmentAxis:x}),E&&zB({mainAxis:!0,crossAxis:!1,limiter:C==="partial"?BB():void 0,...le}),E&&IB({...le}),UB({...le,apply:({elements:Kt,rects:Er,availableWidth:gt,availableHeight:Vs})=>{const{width:L,height:Z}=Er.reference,q=Kt.floating.style;q.setProperty("--radix-popper-available-width",`${gt}px`),q.setProperty("--radix-popper-available-height",`${Vs}px`),q.setProperty("--radix-popper-anchor-width",`${L}px`),q.setProperty("--radix-popper-anchor-height",`${Z}px`)}}),G&&lU({element:G,padding:S}),vU({arrowWidth:ne,arrowHeight:M}),R&&LB({strategy:"referenceHidden",...le})]}),[fe,xe]=Gk(Ve),Re=Ft(O);An(()=>{We&&(Re==null||Re())},[We,Re]);const Me=(o=Ne.arrow)===null||o===void 0?void 0:o.x,Oe=(i=Ne.arrow)===null||i===void 0?void 0:i.y,ze=((s=Ne.arrow)===null||s===void 0?void 0:s.centerOffset)!==0,[Mt,ct]=d.useState();return An(()=>{B&&ct(window.getComputedStyle(B).zIndex)},[B]),d.createElement("div",{ref:pe.setFloating,"data-radix-popper-content-wrapper":"",style:{...$e,transform:We?$e.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:Mt,"--radix-popper-transform-origin":[(l=Ne.transformOrigin)===null||l===void 0?void 0:l.x,(u=Ne.transformOrigin)===null||u===void 0?void 0:u.y].join(" ")},dir:e.dir},d.createElement(pU,{scope:p,placedSide:fe,onArrowChange:se,arrowX:Me,arrowY:Oe,shouldHideArrow:ze},d.createElement(Ae.div,Y({"data-side":fe,"data-align":xe},A,{ref:J,style:{...A.style,animation:We?void 0:"none",opacity:(f=Ne.hide)!==null&&f!==void 0&&f.referenceHidden?0:void 0}}))))});function gU(e){return e!==null}const vU=e=>({name:"transformOrigin",options:e,fn(t){var n,r,o,i,s;const{placement:l,rects:u,middlewareData:f}=t,m=((n=f.arrow)===null||n===void 0?void 0:n.centerOffset)!==0,g=m?0:e.arrowWidth,y=m?0:e.arrowHeight,[x,S]=Gk(l),E={start:"0%",center:"50%",end:"100%"}[S],_=((r=(o=f.arrow)===null||o===void 0?void 0:o.x)!==null&&r!==void 0?r:0)+g/2,b=((i=(s=f.arrow)===null||s===void 0?void 0:s.y)!==null&&i!==void 0?i:0)+y/2;let C="",R="";return x==="bottom"?(C=m?E:`${_}px`,R=`${-y}px`):x==="top"?(C=m?E:`${_}px`,R=`${u.floating.height+y}px`):x==="right"?(C=`${-y}px`,R=m?E:`${b}px`):x==="left"&&(C=`${u.floating.width+y}px`,R=m?E:`${b}px`),{data:{x:C,y:R}}}});function Gk(e){const[t,n="center"]=e.split("-");return[t,n]}const Fd=dU,Wm=hU,Hm=mU,jd=d.forwardRef((e,t)=>{var n;const{container:r=globalThis==null||(n=globalThis.document)===null||n===void 0?void 0:n.body,...o}=e;return r?QI.createPortal(d.createElement(Ae.div,Y({},o,{ref:t})),r):null});function yU(e,t){return d.useReducer((n,r)=>{const o=t[n][r];return o??n},e)}const Sn=e=>{const{present:t,children:n}=e,r=wU(t),o=typeof n=="function"?n({present:r.isPresent}):d.Children.only(n),i=Ue(r.ref,o.ref);return typeof n=="function"||r.isPresent?d.cloneElement(o,{ref:i}):null};Sn.displayName="Presence";function wU(e){const[t,n]=d.useState(),r=d.useRef({}),o=d.useRef(e),i=d.useRef("none"),s=e?"mounted":"unmounted",[l,u]=yU(s,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return d.useEffect(()=>{const f=fh(r.current);i.current=l==="mounted"?f:"none"},[l]),An(()=>{const f=r.current,p=o.current;if(p!==e){const g=i.current,y=fh(f);e?u("MOUNT"):y==="none"||(f==null?void 0:f.display)==="none"?u("UNMOUNT"):u(p&&g!==y?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,u]),An(()=>{if(t){const f=m=>{const y=fh(r.current).includes(m.animationName);m.target===t&&y&&Is.flushSync(()=>u("ANIMATION_END"))},p=m=>{m.target===t&&(i.current=fh(r.current))};return t.addEventListener("animationstart",p),t.addEventListener("animationcancel",f),t.addEventListener("animationend",f),()=>{t.removeEventListener("animationstart",p),t.removeEventListener("animationcancel",f),t.removeEventListener("animationend",f)}}else u("ANIMATION_END")},[t,u]),{isPresent:["mounted","unmountSuspended"].includes(l),ref:d.useCallback(f=>{f&&(r.current=getComputedStyle(f)),n(f)},[])}}function fh(e){return(e==null?void 0:e.animationName)||"none"}function Zr({prop:e,defaultProp:t,onChange:n=()=>{}}){const[r,o]=xU({defaultProp:t,onChange:n}),i=e!==void 0,s=i?e:r,l=Ft(n),u=d.useCallback(f=>{if(i){const m=typeof f=="function"?f(e):f;m!==e&&l(m)}else o(f)},[i,e,o,l]);return[s,u]}function xU({defaultProp:e,onChange:t}){const n=d.useState(e),[r]=n,o=d.useRef(r),i=Ft(t);return d.useEffect(()=>{o.current!==r&&(i(r),o.current=r)},[r,o,i]),n}const Km=d.forwardRef((e,t)=>d.createElement(Ae.span,Y({},e,{ref:t,style:{position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal",...e.style}}))),bU=Km,[Gm,mte]=Mn("Tooltip",[Fs]),wx=Fs(),SU="TooltipProvider",_U=700,d1="tooltip.open",[EU,xx]=Gm(SU),CU=e=>{const{__scopeTooltip:t,delayDuration:n=_U,skipDelayDuration:r=300,disableHoverableContent:o=!1,children:i}=e,[s,l]=d.useState(!0),u=d.useRef(!1),f=d.useRef(0);return d.useEffect(()=>{const p=f.current;return()=>window.clearTimeout(p)},[]),d.createElement(EU,{scope:t,isOpenDelayed:s,delayDuration:n,onOpen:d.useCallback(()=>{window.clearTimeout(f.current),l(!1)},[]),onClose:d.useCallback(()=>{window.clearTimeout(f.current),f.current=window.setTimeout(()=>l(!0),r)},[r]),isPointerInTransitRef:u,onPointerInTransitChange:d.useCallback(p=>{u.current=p},[]),disableHoverableContent:o},i)},bx="Tooltip",[$U,Ym]=Gm(bx),RU=e=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:o=!1,onOpenChange:i,disableHoverableContent:s,delayDuration:l}=e,u=xx(bx,e.__scopeTooltip),f=wx(t),[p,m]=d.useState(null),g=nr(),y=d.useRef(0),x=s??u.disableHoverableContent,S=l??u.delayDuration,E=d.useRef(!1),[_=!1,b]=Zr({prop:r,defaultProp:o,onChange:A=>{A?(u.onOpen(),document.dispatchEvent(new CustomEvent(d1))):u.onClose(),i==null||i(A)}}),C=d.useMemo(()=>_?E.current?"delayed-open":"instant-open":"closed",[_]),R=d.useCallback(()=>{window.clearTimeout(y.current),E.current=!1,b(!0)},[b]),P=d.useCallback(()=>{window.clearTimeout(y.current),b(!1)},[b]),O=d.useCallback(()=>{window.clearTimeout(y.current),y.current=window.setTimeout(()=>{E.current=!0,b(!0)},S)},[S,b]);return d.useEffect(()=>()=>window.clearTimeout(y.current),[]),d.createElement(Fd,f,d.createElement($U,{scope:t,contentId:g,open:_,stateAttribute:C,trigger:p,onTriggerChange:m,onTriggerEnter:d.useCallback(()=>{u.isOpenDelayed?O():R()},[u.isOpenDelayed,O,R]),onTriggerLeave:d.useCallback(()=>{x?P():window.clearTimeout(y.current)},[P,x]),onOpen:R,onClose:P,disableHoverableContent:x},n))},KC="TooltipTrigger",kU=d.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,o=Ym(KC,n),i=xx(KC,n),s=wx(n),l=d.useRef(null),u=Ue(t,l,o.onTriggerChange),f=d.useRef(!1),p=d.useRef(!1),m=d.useCallback(()=>f.current=!1,[]);return d.useEffect(()=>()=>document.removeEventListener("pointerup",m),[m]),d.createElement(Wm,Y({asChild:!0},s),d.createElement(Ae.button,Y({"aria-describedby":o.open?o.contentId:void 0,"data-state":o.stateAttribute},r,{ref:u,onPointerMove:ue(e.onPointerMove,g=>{g.pointerType!=="touch"&&!p.current&&!i.isPointerInTransitRef.current&&(o.onTriggerEnter(),p.current=!0)}),onPointerLeave:ue(e.onPointerLeave,()=>{o.onTriggerLeave(),p.current=!1}),onPointerDown:ue(e.onPointerDown,()=>{f.current=!0,document.addEventListener("pointerup",m,{once:!0})}),onFocus:ue(e.onFocus,()=>{f.current||o.onOpen()}),onBlur:ue(e.onBlur,o.onClose),onClick:ue(e.onClick,o.onClose)})))}),TU="TooltipPortal",[gte,PU]=Gm(TU,{forceMount:void 0}),ud="TooltipContent",AU=d.forwardRef((e,t)=>{const n=PU(ud,e.__scopeTooltip),{forceMount:r=n.forceMount,side:o="top",...i}=e,s=Ym(ud,e.__scopeTooltip);return d.createElement(Sn,{present:r||s.open},s.disableHoverableContent?d.createElement(Yk,Y({side:o},i,{ref:t})):d.createElement(MU,Y({side:o},i,{ref:t})))}),MU=d.forwardRef((e,t)=>{const n=Ym(ud,e.__scopeTooltip),r=xx(ud,e.__scopeTooltip),o=d.useRef(null),i=Ue(t,o),[s,l]=d.useState(null),{trigger:u,onClose:f}=n,p=o.current,{onPointerInTransitChange:m}=r,g=d.useCallback(()=>{l(null),m(!1)},[m]),y=d.useCallback((x,S)=>{const E=x.currentTarget,_={x:x.clientX,y:x.clientY},b=NU(_,E.getBoundingClientRect()),C=DU(_,b),R=IU(S.getBoundingClientRect()),P=FU([...C,...R]);l(P),m(!0)},[m]);return d.useEffect(()=>()=>g(),[g]),d.useEffect(()=>{if(u&&p){const x=E=>y(E,p),S=E=>y(E,u);return u.addEventListener("pointerleave",x),p.addEventListener("pointerleave",S),()=>{u.removeEventListener("pointerleave",x),p.removeEventListener("pointerleave",S)}}},[u,p,y,g]),d.useEffect(()=>{if(s){const x=S=>{const E=S.target,_={x:S.clientX,y:S.clientY},b=(u==null?void 0:u.contains(E))||(p==null?void 0:p.contains(E)),C=!LU(_,s);b?g():C&&(g(),f())};return document.addEventListener("pointermove",x),()=>document.removeEventListener("pointermove",x)}},[u,p,s,f,g]),d.createElement(Yk,Y({},e,{ref:i}))}),[OU,vte]=Gm(bx,{isInside:!1}),Yk=d.forwardRef((e,t)=>{const{__scopeTooltip:n,children:r,"aria-label":o,onEscapeKeyDown:i,onPointerDownOutside:s,...l}=e,u=Ym(ud,n),f=wx(n),{onClose:p}=u;return d.useEffect(()=>(document.addEventListener(d1,p),()=>document.removeEventListener(d1,p)),[p]),d.useEffect(()=>{if(u.trigger){const m=g=>{const y=g.target;y!=null&&y.contains(u.trigger)&&p()};return window.addEventListener("scroll",m,{capture:!0}),()=>window.removeEventListener("scroll",m,{capture:!0})}},[u.trigger,p]),d.createElement(Ec,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:i,onPointerDownOutside:s,onFocusOutside:m=>m.preventDefault(),onDismiss:p},d.createElement(Hm,Y({"data-state":u.stateAttribute},f,l,{ref:t,style:{...l.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"}}),d.createElement(lx,null,r),d.createElement(OU,{scope:n,isInside:!0},d.createElement(bU,{id:u.contentId,role:"tooltip"},o||r))))});function NU(e,t){const n=Math.abs(t.top-e.y),r=Math.abs(t.bottom-e.y),o=Math.abs(t.right-e.x),i=Math.abs(t.left-e.x);switch(Math.min(n,r,o,i)){case i:return"left";case o:return"right";case n:return"top";case r:return"bottom";default:throw new Error("unreachable")}}function DU(e,t,n=5){const r=[];switch(t){case"top":r.push({x:e.x-n,y:e.y+n},{x:e.x+n,y:e.y+n});break;case"bottom":r.push({x:e.x-n,y:e.y-n},{x:e.x+n,y:e.y-n});break;case"left":r.push({x:e.x+n,y:e.y-n},{x:e.x+n,y:e.y+n});break;case"right":r.push({x:e.x-n,y:e.y-n},{x:e.x-n,y:e.y+n});break}return r}function IU(e){const{top:t,right:n,bottom:r,left:o}=e;return[{x:o,y:t},{x:n,y:t},{x:n,y:r},{x:o,y:r}]}function LU(e,t){const{x:n,y:r}=e;let o=!1;for(let i=0,s=t.length-1;ir!=p>r&&n<(f-l)*(r-u)/(p-u)+l&&(o=!o)}return o}function FU(e){const t=e.slice();return t.sort((n,r)=>n.xr.x?1:n.yr.y?1:0),jU(t)}function jU(e){if(e.length<=1)return e.slice();const t=[];for(let r=0;r=2;){const i=t[t.length-1],s=t[t.length-2];if((i.x-s.x)*(o.y-s.y)>=(i.y-s.y)*(o.x-s.x))t.pop();else break}t.push(o)}t.pop();const n=[];for(let r=e.length-1;r>=0;r--){const o=e[r];for(;n.length>=2;){const i=n[n.length-1],s=n[n.length-2];if((i.x-s.x)*(o.y-s.y)>=(i.y-s.y)*(o.x-s.x))n.pop();else break}n.push(o)}return n.pop(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}const zU=CU,BU=RU,UU=kU,Xk=AU,VU=zU,Zk=BU,qk=UU,Sx=d.forwardRef(({className:e,sideOffset:t=4,...n},r)=>v.jsx(Xk,{ref:r,sideOffset:t,className:_e("z-50 border overflow-hidden rounded-md bg-background text-foreground px-3 py-1.5 text-xs animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...n}));Sx.displayName=Xk.displayName;const _x=Dm("inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50",{variants:{variant:{default:"bg-primary text-primary-foreground shadow hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",outline:"border border-input bg-transparent shadow-sm hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2",sm:"h-8 rounded-md px-3 text-xs",lg:"h-10 rounded-md px-8",icon:"h-9 w-9"}},defaultVariants:{variant:"default",size:"default"}}),wn=d.forwardRef(({className:e,variant:t,size:n,asChild:r=!1,...o},i)=>{const s=r?Zo:"button";return v.jsx(s,{className:_e(_x({variant:t,size:n,className:e}),"outline-none cursor-default select-none"),ref:i,tabIndex:-1,...o})});wn.displayName="Button";const yn=d.forwardRef(({tooltip:e,children:t,...n},r)=>v.jsxs(Zk,{children:[v.jsx(qk,{asChild:!0,children:v.jsx(wn,{variant:"ghost",size:"icon",...n,ref:r,tabIndex:-1,className:"cursor-default bg-background",children:v.jsx("div",{className:"icon-button-icon-wrapper",children:t})})}),v.jsx(Sx,{children:v.jsx("p",{children:e})})]})),f1=e=>{const{onFileUpload:t,children:n,...r}=e,[o]=d.useState(`file-upload-${Math.random().toString()}`),i=s=>{var u;const l=(u=s.currentTarget.files)==null?void 0:u[0];l&&t(l)};return v.jsxs(v.Fragment,{children:[v.jsx("label",{htmlFor:o,children:v.jsx(yn,{...r,asChild:!0,children:n})}),v.jsx(Bm,{style:{display:"none"},id:o,name:o,type:"file",onChange:i,accept:"image/png, image/jpeg"})]})};var WU={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const HU=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Jt=(e,t)=>{const n=d.forwardRef(({color:r="currentColor",size:o=24,strokeWidth:i=2,absoluteStrokeWidth:s,children:l,...u},f)=>d.createElement("svg",{ref:f,...WU,width:o,height:o,stroke:r,strokeWidth:s?Number(i)*24/Number(o):i,className:`lucide lucide-${HU(e)}`,...u},[...t.map(([p,m])=>d.createElement(p,m)),...(Array.isArray(l)?l:[l])||[]]));return n.displayName=`${e}`,n},KU=Jt("Blocks",[["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["path",{d:"M10 21V8a1 1 0 0 0-1-1H4a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-5a1 1 0 0 0-1-1H3",key:"1fpvtg"}]]),GU=Jt("ChevronLeft",[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]]),YU=Jt("ChevronRight",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]),XU=Jt("Coffee",[["path",{d:"M17 8h1a4 4 0 1 1 0 8h-1",key:"jx4kbh"}],["path",{d:"M3 8h14v9a4 4 0 0 1-4 4H7a4 4 0 0 1-4-4Z",key:"1bxrl0"}],["line",{x1:"6",x2:"6",y1:"2",y2:"4",key:"1cr9l3"}],["line",{x1:"10",x2:"10",y1:"2",y2:"4",key:"170wym"}],["line",{x1:"14",x2:"14",y1:"2",y2:"4",key:"1c5f70"}]]),ZU=Jt("Download",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"7 10 12 15 17 10",key:"2ggqvy"}],["line",{x1:"12",x2:"12",y1:"15",y2:"3",key:"1vk2je"}]]),qU=Jt("Eraser",[["path",{d:"m7 21-4.3-4.3c-1-1-1-2.5 0-3.4l9.6-9.6c1-1 2.5-1 3.4 0l5.6 5.6c1 1 1 2.5 0 3.4L13 21",key:"182aya"}],["path",{d:"M22 21H7",key:"t4ddhn"}],["path",{d:"m5 11 9 9",key:"1mo9qw"}]]),QU=Jt("Expand",[["path",{d:"m21 21-6-6m6 6v-4.8m0 4.8h-4.8",key:"1c15vz"}],["path",{d:"M3 16.2V21m0 0h4.8M3 21l6-6",key:"1fsnz2"}],["path",{d:"M21 7.8V3m0 0h-4.8M21 3l-6 6",key:"hawz9i"}],["path",{d:"M3 7.8V3m0 0h4.8M3 3l6 6",key:"u9ee12"}]]),JU=Jt("Eye",[["path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z",key:"rwhkz3"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]),eV=Jt("FolderClosed",[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}],["path",{d:"M2 10h20",key:"1ir3d8"}]]),Qk=Jt("Fullscreen",[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}],["rect",{width:"10",height:"8",x:"7",y:"8",rx:"1",key:"vys8me"}]]),tV=Jt("Image",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]]),nV=Jt("Keyboard",[["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",ry:"2",key:"15u882"}],["path",{d:"M6 8h.001",key:"1ej0i3"}],["path",{d:"M10 8h.001",key:"1x2st2"}],["path",{d:"M14 8h.001",key:"1vkmyp"}],["path",{d:"M18 8h.001",key:"kfsenl"}],["path",{d:"M8 12h.001",key:"1sjpby"}],["path",{d:"M12 12h.001",key:"al75ts"}],["path",{d:"M16 12h.001",key:"931bgk"}],["path",{d:"M7 16h10",key:"wp8him"}]]),rV=Jt("MousePointerClick",[["path",{d:"m9 9 5 12 1.8-5.2L21 14Z",key:"1b76lo"}],["path",{d:"M7.2 2.2 8 5.1",key:"1cfko1"}],["path",{d:"m5.1 8-2.9-.8",key:"1go3kf"}],["path",{d:"M14 4.1 12 6",key:"ita8i4"}],["path",{d:"m6 12-1.9 2",key:"mnht97"}]]),oV=Jt("Redo",[["path",{d:"M21 7v6h-6",key:"3ptur4"}],["path",{d:"M3 17a9 9 0 0 1 9-9 9 9 0 0 1 6 2.3l3 2.7",key:"1kgawr"}]]),iV=Jt("RotateCw",[["path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8",key:"1p45f6"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}]]),sV=Jt("Settings",[["path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z",key:"1qme2f"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]),GC=Jt("Slice",[["path",{d:"m8 14-6 6h9v-3",key:"zo3j9a"}],["path",{d:"M18.37 3.63 8 14l3 3L21.37 6.63a2.12 2.12 0 1 0-3-3Z",key:"1dzx0j"}]]),YC=Jt("Smile",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 14s1.5 2 4 2 4-2 4-2",key:"1y1vjs"}],["line",{x1:"9",x2:"9.01",y1:"9",y2:"9",key:"yxxnd0"}],["line",{x1:"15",x2:"15.01",y1:"9",y2:"9",key:"1p4y9e"}]]),aV=Jt("Undo",[["path",{d:"M3 7v6h6",key:"1v2h90"}],["path",{d:"M21 17a9 9 0 0 0-9-9 9 9 0 0 0-6 2.3L3 13",key:"1r6uu6"}]]),Jk=Jt("Upload",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"17 8 12 3 7 8",key:"t8dd8p"}],["line",{x1:"12",x2:"12",y1:"3",y2:"15",key:"widbto"}]]);function lV(e,t){const[n,r]=d.useState(e);return d.useEffect(()=>{const o=setTimeout(()=>{r(e)},t);return()=>{clearTimeout(o)}},[e,t]),n}function eT(e){const[t,n]=d.useState(()=>typeof e=="boolean"?e:!!e),r=d.useCallback(o=>n(typeof o=="boolean"?o:i=>!i),[]);return[t,r]}const E0="focusScope.autoFocusOnMount",C0="focusScope.autoFocusOnUnmount",XC={bubbles:!1,cancelable:!0},Xm=d.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:o,onUnmountAutoFocus:i,...s}=e,[l,u]=d.useState(null),f=Ft(o),p=Ft(i),m=d.useRef(null),g=Ue(t,S=>u(S)),y=d.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;d.useEffect(()=>{if(r){let b=function(O){if(y.paused||!l)return;const A=O.target;l.contains(A)?m.current=A:Qi(m.current,{select:!0})},C=function(O){if(y.paused||!l)return;const A=O.relatedTarget;A!==null&&(l.contains(A)||Qi(m.current,{select:!0}))},R=function(O){if(document.activeElement===document.body)for(const D of O)D.removedNodes.length>0&&Qi(l)};var S=b,E=C,_=R;document.addEventListener("focusin",b),document.addEventListener("focusout",C);const P=new MutationObserver(R);return l&&P.observe(l,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",b),document.removeEventListener("focusout",C),P.disconnect()}}},[r,l,y.paused]),d.useEffect(()=>{if(l){qC.add(y);const S=document.activeElement;if(!l.contains(S)){const _=new CustomEvent(E0,XC);l.addEventListener(E0,f),l.dispatchEvent(_),_.defaultPrevented||(cV(pV(tT(l)),{select:!0}),document.activeElement===S&&Qi(l))}return()=>{l.removeEventListener(E0,f),setTimeout(()=>{const _=new CustomEvent(C0,XC);l.addEventListener(C0,p),l.dispatchEvent(_),_.defaultPrevented||Qi(S??document.body,{select:!0}),l.removeEventListener(C0,p),qC.remove(y)},0)}}},[l,f,p,y]);const x=d.useCallback(S=>{if(!n&&!r||y.paused)return;const E=S.key==="Tab"&&!S.altKey&&!S.ctrlKey&&!S.metaKey,_=document.activeElement;if(E&&_){const b=S.currentTarget,[C,R]=uV(b);C&&R?!S.shiftKey&&_===R?(S.preventDefault(),n&&Qi(C,{select:!0})):S.shiftKey&&_===C&&(S.preventDefault(),n&&Qi(R,{select:!0})):_===b&&S.preventDefault()}},[n,r,y.paused]);return d.createElement(Ae.div,Y({tabIndex:-1},s,{ref:g,onKeyDown:x}))});function cV(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(Qi(r,{select:t}),document.activeElement!==n)return}function uV(e){const t=tT(e),n=ZC(t,e),r=ZC(t.reverse(),e);return[n,r]}function tT(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const o=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||o?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function ZC(e,t){for(const n of e)if(!dV(n,{upTo:t}))return n}function dV(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function fV(e){return e instanceof HTMLInputElement&&"select"in e}function Qi(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&fV(e)&&t&&e.select()}}const qC=hV();function hV(){let e=[];return{add(t){const n=e[0];t!==n&&(n==null||n.pause()),e=QC(e,t),e.unshift(t)},remove(t){var n;e=QC(e,t),(n=e[0])===null||n===void 0||n.resume()}}}function QC(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function pV(e){return e.filter(t=>t.tagName!=="A")}let $0=0;function Zm(){d.useEffect(()=>{var e,t;const n=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",(e=n[0])!==null&&e!==void 0?e:JC()),document.body.insertAdjacentElement("beforeend",(t=n[1])!==null&&t!==void 0?t:JC()),$0++,()=>{$0===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(r=>r.remove()),$0--}},[])}function JC(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.cssText="outline: none; opacity: 0; position: fixed; pointer-events: none",e}var Lo=function(){return Lo=Object.assign||function(t){for(var n,r=1,o=arguments.length;r"u")return AV;var t=MV(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])}},NV=iT(),DV=function(e,t,n,r){var o=e.left,i=e.top,s=e.right,l=e.gap;return n===void 0&&(n="margin"),` + .`.concat(gV,` { + overflow: hidden `).concat(r,`; + padding-right: `).concat(l,"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(i,`px; + padding-right: `).concat(s,`px; + margin-left:0; + margin-top:0; + margin-right: `).concat(l,"px ").concat(r,`; + `),n==="padding"&&"padding-right: ".concat(l,"px ").concat(r,";")].filter(Boolean).join(""),` + } + + .`).concat(qh,` { + right: `).concat(l,"px ").concat(r,`; + } + + .`).concat(Qh,` { + margin-right: `).concat(l,"px ").concat(r,`; + } + + .`).concat(qh," .").concat(qh,` { + right: 0 `).concat(r,`; + } + + .`).concat(Qh," .").concat(Qh,` { + margin-right: 0 `).concat(r,`; + } + + body { + `).concat(vV,": ").concat(l,`px; + } +`)},IV=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,o=r===void 0?"margin":r,i=d.useMemo(function(){return OV(o)},[o]);return d.createElement(NV,{styles:DV(i,!t,o,n?"":"!important")})},h1=!1;if(typeof window<"u")try{var hh=Object.defineProperty({},"passive",{get:function(){return h1=!0,!0}});window.addEventListener("test",hh,hh),window.removeEventListener("test",hh,hh)}catch{h1=!1}var rl=h1?{passive:!1}:!1,LV=function(e){return e.tagName==="TEXTAREA"},sT=function(e,t){var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!LV(e)&&n[t]==="visible")},FV=function(e){return sT(e,"overflowY")},jV=function(e){return sT(e,"overflowX")},t2=function(e,t){var n=t;do{typeof ShadowRoot<"u"&&n instanceof ShadowRoot&&(n=n.host);var r=aT(e,n);if(r){var o=lT(e,n),i=o[1],s=o[2];if(i>s)return!0}n=n.parentNode}while(n&&n!==document.body);return!1},zV=function(e){var t=e.scrollTop,n=e.scrollHeight,r=e.clientHeight;return[t,n,r]},BV=function(e){var t=e.scrollLeft,n=e.scrollWidth,r=e.clientWidth;return[t,n,r]},aT=function(e,t){return e==="v"?FV(t):jV(t)},lT=function(e,t){return e==="v"?zV(t):BV(t)},UV=function(e,t){return e==="h"&&t==="rtl"?-1:1},VV=function(e,t,n,r,o){var i=UV(e,window.getComputedStyle(t).direction),s=i*r,l=n.target,u=t.contains(l),f=!1,p=s>0,m=0,g=0;do{var y=lT(e,l),x=y[0],S=y[1],E=y[2],_=S-E-i*x;(x||_)&&aT(e,l)&&(m+=_,g+=x),l=l.parentNode}while(!u&&l!==document.body||u&&(t.contains(l)||t===l));return(p&&(o&&m===0||!o&&s>m)||!p&&(o&&g===0||!o&&-s>g))&&(f=!0),f},ph=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},n2=function(e){return[e.deltaX,e.deltaY]},r2=function(e){return e&&"current"in e?e.current:e},WV=function(e,t){return e[0]===t[0]&&e[1]===t[1]},HV=function(e){return` + .block-interactivity-`.concat(e,` {pointer-events: none;} + .allow-interactivity-`).concat(e,` {pointer-events: all;} +`)},KV=0,ol=[];function GV(e){var t=d.useRef([]),n=d.useRef([0,0]),r=d.useRef(),o=d.useState(KV++)[0],i=d.useState(function(){return iT()})[0],s=d.useRef(e);d.useEffect(function(){s.current=e},[e]),d.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(o));var S=mV([e.lockRef.current],(e.shards||[]).map(r2),!0).filter(Boolean);return S.forEach(function(E){return E.classList.add("allow-interactivity-".concat(o))}),function(){document.body.classList.remove("block-interactivity-".concat(o)),S.forEach(function(E){return E.classList.remove("allow-interactivity-".concat(o))})}}},[e.inert,e.lockRef.current,e.shards]);var l=d.useCallback(function(S,E){if("touches"in S&&S.touches.length===2)return!s.current.allowPinchZoom;var _=ph(S),b=n.current,C="deltaX"in S?S.deltaX:b[0]-_[0],R="deltaY"in S?S.deltaY:b[1]-_[1],P,O=S.target,A=Math.abs(C)>Math.abs(R)?"h":"v";if("touches"in S&&A==="h"&&O.type==="range")return!1;var D=t2(A,O);if(!D)return!0;if(D?P=A:(P=A==="v"?"h":"v",D=t2(A,O)),!D)return!1;if(!r.current&&"changedTouches"in S&&(C||R)&&(r.current=P),!P)return!0;var B=r.current||P;return VV(B,E,S,B==="h"?C:R,!0)},[]),u=d.useCallback(function(S){var E=S;if(!(!ol.length||ol[ol.length-1]!==i)){var _="deltaY"in E?n2(E):ph(E),b=t.current.filter(function(P){return P.name===E.type&&P.target===E.target&&WV(P.delta,_)})[0];if(b&&b.should){E.cancelable&&E.preventDefault();return}if(!b){var C=(s.current.shards||[]).map(r2).filter(Boolean).filter(function(P){return P.contains(E.target)}),R=C.length>0?l(E,C[0]):!s.current.noIsolation;R&&E.cancelable&&E.preventDefault()}}},[]),f=d.useCallback(function(S,E,_,b){var C={name:S,delta:E,target:_,should:b};t.current.push(C),setTimeout(function(){t.current=t.current.filter(function(R){return R!==C})},1)},[]),p=d.useCallback(function(S){n.current=ph(S),r.current=void 0},[]),m=d.useCallback(function(S){f(S.type,n2(S),S.target,l(S,e.lockRef.current))},[]),g=d.useCallback(function(S){f(S.type,ph(S),S.target,l(S,e.lockRef.current))},[]);d.useEffect(function(){return ol.push(i),e.setCallbacks({onScrollCapture:m,onWheelCapture:m,onTouchMoveCapture:g}),document.addEventListener("wheel",u,rl),document.addEventListener("touchmove",u,rl),document.addEventListener("touchstart",p,rl),function(){ol=ol.filter(function(S){return S!==i}),document.removeEventListener("wheel",u,rl),document.removeEventListener("touchmove",u,rl),document.removeEventListener("touchstart",p,rl)}},[]);var y=e.removeScrollBar,x=e.inert;return d.createElement(d.Fragment,null,x?d.createElement(i,{styles:HV(o)}):null,y?d.createElement(IV,{gapMode:"margin"}):null)}const YV=EV(oT,GV);var cT=d.forwardRef(function(e,t){return d.createElement(qm,Lo({},e,{ref:t,sideCar:YV}))});cT.classNames=qm.classNames;const Qm=cT;var XV=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},il=new WeakMap,mh=new WeakMap,gh={},T0=0,uT=function(e){return e&&(e.host||uT(e.parentNode))},ZV=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=uT(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})},qV=function(e,t,n,r){var o=ZV(t,Array.isArray(e)?e:[e]);gh[n]||(gh[n]=new WeakMap);var i=gh[n],s=[],l=new Set,u=new Set(o),f=function(m){!m||l.has(m)||(l.add(m),f(m.parentNode))};o.forEach(f);var p=function(m){!m||u.has(m)||Array.prototype.forEach.call(m.children,function(g){if(l.has(g))p(g);else{var y=g.getAttribute(r),x=y!==null&&y!=="false",S=(il.get(g)||0)+1,E=(i.get(g)||0)+1;il.set(g,S),i.set(g,E),s.push(g),S===1&&x&&mh.set(g,!0),E===1&&g.setAttribute(n,"true"),x||g.setAttribute(r,"true")}})};return p(t),l.clear(),T0++,function(){s.forEach(function(m){var g=il.get(m)-1,y=i.get(m)-1;il.set(m,g),i.set(m,y),g||(mh.has(m)||m.removeAttribute(r),mh.delete(m)),y||m.removeAttribute(n)}),T0--,T0||(il=new WeakMap,il=new WeakMap,mh=new WeakMap,gh={})}},Jm=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),o=t||XV(e);return o?(r.push.apply(r,Array.from(o.querySelectorAll("[aria-live]"))),qV(r,o,n,"aria-hidden")):function(){return null}};const dT="Dialog",[fT,hT]=Mn(dT),[QV,Eo]=fT(dT),JV=e=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:o,onOpenChange:i,modal:s=!0}=e,l=d.useRef(null),u=d.useRef(null),[f=!1,p]=Zr({prop:r,defaultProp:o,onChange:i});return d.createElement(QV,{scope:t,triggerRef:l,contentRef:u,contentId:nr(),titleId:nr(),descriptionId:nr(),open:f,onOpenChange:p,onOpenToggle:d.useCallback(()=>p(m=>!m),[p]),modal:s},n)},eW="DialogTrigger",pT=d.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=Eo(eW,n),i=Ue(t,o.triggerRef);return d.createElement(Ae.button,Y({type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":Ex(o.open)},r,{ref:i,onClick:ue(e.onClick,o.onOpenToggle)}))}),mT="DialogPortal",[tW,gT]=fT(mT,{forceMount:void 0}),nW=e=>{const{__scopeDialog:t,forceMount:n,children:r,container:o}=e,i=Eo(mT,t);return d.createElement(tW,{scope:t,forceMount:n},d.Children.map(r,s=>d.createElement(Sn,{present:n||i.open},d.createElement(jd,{asChild:!0,container:o},s))))},p1="DialogOverlay",rW=d.forwardRef((e,t)=>{const n=gT(p1,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,i=Eo(p1,e.__scopeDialog);return i.modal?d.createElement(Sn,{present:r||i.open},d.createElement(oW,Y({},o,{ref:t}))):null}),oW=d.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=Eo(p1,n);return d.createElement(Qm,{as:Zo,allowPinchZoom:!0,shards:[o.contentRef]},d.createElement(Ae.div,Y({"data-state":Ex(o.open)},r,{ref:t,style:{pointerEvents:"auto",...r.style}})))}),uc="DialogContent",iW=d.forwardRef((e,t)=>{const n=gT(uc,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,i=Eo(uc,e.__scopeDialog);return d.createElement(Sn,{present:r||i.open},i.modal?d.createElement(sW,Y({},o,{ref:t})):d.createElement(aW,Y({},o,{ref:t})))}),sW=d.forwardRef((e,t)=>{const n=Eo(uc,e.__scopeDialog),r=d.useRef(null),o=Ue(t,n.contentRef,r);return d.useEffect(()=>{const i=r.current;if(i)return Jm(i)},[]),d.createElement(vT,Y({},e,{ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:ue(e.onCloseAutoFocus,i=>{var s;i.preventDefault(),(s=n.triggerRef.current)===null||s===void 0||s.focus()}),onPointerDownOutside:ue(e.onPointerDownOutside,i=>{const s=i.detail.originalEvent,l=s.button===0&&s.ctrlKey===!0;(s.button===2||l)&&i.preventDefault()}),onFocusOutside:ue(e.onFocusOutside,i=>i.preventDefault())}))}),aW=d.forwardRef((e,t)=>{const n=Eo(uc,e.__scopeDialog),r=d.useRef(!1),o=d.useRef(!1);return d.createElement(vT,Y({},e,{ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var s;if((s=e.onCloseAutoFocus)===null||s===void 0||s.call(e,i),!i.defaultPrevented){var l;r.current||(l=n.triggerRef.current)===null||l===void 0||l.focus(),i.preventDefault()}r.current=!1,o.current=!1},onInteractOutside:i=>{var s,l;(s=e.onInteractOutside)===null||s===void 0||s.call(e,i),i.defaultPrevented||(r.current=!0,i.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const u=i.target;((l=n.triggerRef.current)===null||l===void 0?void 0:l.contains(u))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&o.current&&i.preventDefault()}}))}),vT=d.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:i,...s}=e,l=Eo(uc,n),u=d.useRef(null),f=Ue(t,u);return Zm(),d.createElement(d.Fragment,null,d.createElement(Xm,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:i},d.createElement(Ec,Y({role:"dialog",id:l.contentId,"aria-describedby":l.descriptionId,"aria-labelledby":l.titleId,"data-state":Ex(l.open)},s,{ref:f,onDismiss:()=>l.onOpenChange(!1)}))),!1)}),yT="DialogTitle",lW=d.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=Eo(yT,n);return d.createElement(Ae.h2,Y({id:o.titleId},r,{ref:t}))}),cW="DialogDescription",wT=d.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=Eo(cW,n);return d.createElement(Ae.p,Y({id:o.descriptionId},r,{ref:t}))}),uW="DialogClose",dW=d.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=Eo(uW,n);return d.createElement(Ae.button,Y({type:"button"},r,{ref:t,onClick:ue(e.onClick,()=>o.onOpenChange(!1))}))});function Ex(e){return e?"open":"closed"}const fW="DialogTitleWarning",[hW,yte]=pB(fW,{contentName:uc,titleName:yT,docsSlug:"dialog"}),Cx=JV,xT=pT,$x=nW,zd=rW,Bd=iW,Ud=lW,Vd=wT,Rx=dW,eg=Cx,kx=xT,pW=$x,bT=d.forwardRef(({className:e,...t},n)=>v.jsx(zd,{ref:n,className:_e("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t}));bT.displayName=zd.displayName;const Wd=d.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(pW,{children:[v.jsx(bT,{}),v.jsxs(Bd,{ref:r,className:_e("fixed left-[50%] top-[50%] z-50 flex flex-col w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",e,"outline-none"),onCloseAutoFocus:o=>o.preventDefault(),...n,children:[t,v.jsxs(Rx,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[v.jsx(bk,{className:"h-4 w-4"}),v.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Wd.displayName=Bd.displayName;const ST=({className:e,...t})=>v.jsx("div",{className:_e("flex flex-col space-y-1.5 text-center sm:text-left",e),...t});ST.displayName="DialogHeader";const Hd=d.forwardRef(({className:e,...t},n)=>v.jsx(Ud,{ref:n,className:_e("text-2xl font-semibold leading-none tracking-tight",e),...t}));Hd.displayName=Ud.displayName;const mW=d.forwardRef(({className:e,...t},n)=>v.jsx(Vd,{ref:n,className:_e("text-sm text-muted-foreground",e),...t}));mW.displayName=Vd.displayName;function m1(){return m1=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 _W=function(t,n,r){r===void 0&&(r=!1);var o=n.alt,i=n.meta,s=n.mod,l=n.shift,u=n.ctrl,f=n.keys,p=t.key,m=t.code,g=t.ctrlKey,y=t.metaKey,x=t.shiftKey,S=t.altKey,E=hs(m),_=p.toLowerCase();if(!r){if(o===!S&&_!=="alt"||l===!x&&_!=="shift")return!1;if(s){if(!y&&!g)return!1}else if(i===!y&&_!=="meta"&&_!=="os"||u===!g&&_!=="ctrl"&&_!=="control")return!1}return f&&f.length===1&&(f.includes(_)||f.includes(E))?!0:f?yW(f):!f},EW=d.createContext(void 0),CW=function(){return d.useContext(EW)};function RT(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&&RT(e[r],t[r])},!0):e===t}var $W=d.createContext({hotkeys:[],enabledScopes:[],toggleScope:function(){},enableScope:function(){},disableScope:function(){}}),RW=function(){return d.useContext($W)};function kW(e){var t=d.useRef(void 0);return RT(t.current,e)||(t.current=e),t.current}var o2=function(t){t.stopPropagation(),t.preventDefault(),t.stopImmediatePropagation()},TW=typeof window<"u"?d.useLayoutEffect:d.useEffect;function PW(e,t,n,r){var o=d.useRef(null),i=d.useRef(!1),s=n instanceof Array?r instanceof Array?void 0:r:n,l=Tx(e)?e.join(s==null?void 0:s.splitKey):e,u=n instanceof Array?n:r instanceof Array?r:void 0,f=d.useCallback(t,u??[]),p=d.useRef(f);u?p.current=f:p.current=t;var m=kW(s),g=RW(),y=g.enabledScopes,x=CW();return TW(function(){if(!((m==null?void 0:m.enabled)===!1||!SW(y,m==null?void 0:m.scopes))){var S=function(R,P){var O;if(P===void 0&&(P=!1),!(bW(R)&&!$T(R,m==null?void 0:m.enableOnFormTags))&&!(m!=null&&m.ignoreEventWhen!=null&&m.ignoreEventWhen(R))){if(o.current!==null&&document.activeElement!==o.current&&!o.current.contains(document.activeElement)){o2(R);return}(O=R.target)!=null&&O.isContentEditable&&!(m!=null&&m.enableOnContentEditable)||P0(l,m==null?void 0:m.splitKey).forEach(function(A){var D,B=A0(A,m==null?void 0:m.combinationKey);if(_W(R,B,m==null?void 0:m.ignoreModifiers)||(D=B.keys)!=null&&D.includes("*")){if(P&&i.current)return;if(wW(R,B,m==null?void 0:m.preventDefault),!xW(R,B,m==null?void 0:m.enabled)){o2(R);return}p.current(R,B),P||(i.current=!0)}})}},E=function(R){R.key!==void 0&&(ET(hs(R.code)),((m==null?void 0:m.keydown)===void 0&&(m==null?void 0:m.keyup)!==!0||m!=null&&m.keydown)&&S(R))},_=function(R){R.key!==void 0&&(CT(hs(R.code)),i.current=!1,m!=null&&m.keyup&&S(R,!0))},b=o.current||(s==null?void 0:s.document)||document;return b.addEventListener("keyup",_),b.addEventListener("keydown",E),x&&P0(l,m==null?void 0:m.splitKey).forEach(function(C){return x.addHotkey(A0(C,m==null?void 0:m.combinationKey,m==null?void 0:m.description))}),function(){b.removeEventListener("keyup",_),b.removeEventListener("keydown",E),x&&P0(l,m==null?void 0:m.splitKey).forEach(function(C){return x.removeHotkey(A0(C,m==null?void 0:m.combinationKey,m==null?void 0:m.description))})}}},[l,m,y]),o}const Zn=(e,t,n)=>{const r=xt(i=>i.disableShortCuts);return PW(e,t,{enabled:!r},n)};function ur(e){const{content:t,keys:n}=e;return v.jsxs("div",{className:"flex justify-between",children:[v.jsx("div",{children:t}),v.jsx("div",{className:"flex gap-[8px]",children:n.map(r=>v.jsx("div",{className:"border px-2 py-1 rounded-lg",children:r},r))})]})}const AW=function(){return/macintosh|mac os x/i.test(navigator.userAgent)},vh=()=>AW()?"Cmd":"Ctrl";function MW(){const[e,t]=eT(!1);return Zn("h",()=>{t()}),v.jsxs(eg,{open:e,onOpenChange:t,children:[v.jsx(kx,{asChild:!0,children:v.jsx(yn,{tooltip:"Hotkeys",children:v.jsx(nV,{})})}),v.jsx(Wd,{children:v.jsxs(ST,{children:[v.jsx(Hd,{children:"Hotkeys"}),v.jsxs("div",{className:"flex gap-2 flex-col pt-4",children:[v.jsx(ur,{content:"Pan",keys:["Space + Drag"]}),v.jsx(ur,{content:"Reset Zoom/Pan",keys:["Esc"]}),v.jsx(ur,{content:"Decrease Brush Size",keys:["["]}),v.jsx(ur,{content:"Increase Brush Size",keys:["]"]}),v.jsx(ur,{content:"View Original Image",keys:["Hold Tab"]}),v.jsx(ur,{content:"Undo",keys:[vh(),"Z"]}),v.jsx(ur,{content:"Redo",keys:[vh(),"Shift","Z"]}),v.jsx(ur,{content:"Copy Result",keys:[vh(),"C"]}),v.jsx(ur,{content:"Paste Image",keys:[vh(),"V"]}),v.jsx(ur,{content:"Trigger Manually Inpainting",keys:["Shift","R"]}),v.jsx(ur,{content:"Toggle Hotkeys Dialog",keys:["H"]}),v.jsx(ur,{content:"Toggle Settings Dialog",keys:["S"]}),v.jsx(ur,{content:"Toggle File Manager",keys:["F"]})]})]})})]})}function Px(e){const[t]=d.useState(new Image),[n,r]=d.useState(!1);return d.useEffect(()=>{if(e)return t.onload=()=>{r(!0)},r(!1),t.src=URL.createObjectURL(e),()=>{t.onload=null}},[e,t]),[t,n]}const kT="Popover",[TT,wte]=Mn(kT,[Fs]),Ax=Fs(),[OW,Rc]=TT(kT),NW=e=>{const{__scopePopover:t,children:n,open:r,defaultOpen:o,onOpenChange:i,modal:s=!1}=e,l=Ax(t),u=d.useRef(null),[f,p]=d.useState(!1),[m=!1,g]=Zr({prop:r,defaultProp:o,onChange:i});return d.createElement(Fd,l,d.createElement(OW,{scope:t,contentId:nr(),triggerRef:u,open:m,onOpenChange:g,onOpenToggle:d.useCallback(()=>g(y=>!y),[g]),hasCustomAnchor:f,onCustomAnchorAdd:d.useCallback(()=>p(!0),[]),onCustomAnchorRemove:d.useCallback(()=>p(!1),[]),modal:s},n))},DW="PopoverTrigger",IW=d.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,o=Rc(DW,n),i=Ax(n),s=Ue(t,o.triggerRef),l=d.createElement(Ae.button,Y({type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":MT(o.open)},r,{ref:s,onClick:ue(e.onClick,o.onOpenToggle)}));return o.hasCustomAnchor?l:d.createElement(Wm,Y({asChild:!0},i),l)}),PT="PopoverPortal",[LW,FW]=TT(PT,{forceMount:void 0}),jW=e=>{const{__scopePopover:t,forceMount:n,children:r,container:o}=e,i=Rc(PT,t);return d.createElement(LW,{scope:t,forceMount:n},d.createElement(Sn,{present:n||i.open},d.createElement(jd,{asChild:!0,container:o},r)))},dd="PopoverContent",zW=d.forwardRef((e,t)=>{const n=FW(dd,e.__scopePopover),{forceMount:r=n.forceMount,...o}=e,i=Rc(dd,e.__scopePopover);return d.createElement(Sn,{present:r||i.open},i.modal?d.createElement(BW,Y({},o,{ref:t})):d.createElement(UW,Y({},o,{ref:t})))}),BW=d.forwardRef((e,t)=>{const n=Rc(dd,e.__scopePopover),r=d.useRef(null),o=Ue(t,r),i=d.useRef(!1);return d.useEffect(()=>{const s=r.current;if(s)return Jm(s)},[]),d.createElement(Qm,{as:Zo,allowPinchZoom:!0},d.createElement(AT,Y({},e,{ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:ue(e.onCloseAutoFocus,s=>{var l;s.preventDefault(),i.current||(l=n.triggerRef.current)===null||l===void 0||l.focus()}),onPointerDownOutside:ue(e.onPointerDownOutside,s=>{const l=s.detail.originalEvent,u=l.button===0&&l.ctrlKey===!0,f=l.button===2||u;i.current=f},{checkForDefaultPrevented:!1}),onFocusOutside:ue(e.onFocusOutside,s=>s.preventDefault(),{checkForDefaultPrevented:!1})})))}),UW=d.forwardRef((e,t)=>{const n=Rc(dd,e.__scopePopover),r=d.useRef(!1),o=d.useRef(!1);return d.createElement(AT,Y({},e,{ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var s;if((s=e.onCloseAutoFocus)===null||s===void 0||s.call(e,i),!i.defaultPrevented){var l;r.current||(l=n.triggerRef.current)===null||l===void 0||l.focus(),i.preventDefault()}r.current=!1,o.current=!1},onInteractOutside:i=>{var s,l;(s=e.onInteractOutside)===null||s===void 0||s.call(e,i),i.defaultPrevented||(r.current=!0,i.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const u=i.target;((l=n.triggerRef.current)===null||l===void 0?void 0:l.contains(u))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&o.current&&i.preventDefault()}}))}),AT=d.forwardRef((e,t)=>{const{__scopePopover:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:i,disableOutsidePointerEvents:s,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:f,onInteractOutside:p,...m}=e,g=Rc(dd,n),y=Ax(n);return Zm(),d.createElement(Xm,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:i},d.createElement(Ec,{asChild:!0,disableOutsidePointerEvents:s,onInteractOutside:p,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:f,onDismiss:()=>g.onOpenChange(!1)},d.createElement(Hm,Y({"data-state":MT(g.open),role:"dialog",id:g.contentId},y,m,{ref:t,style:{...m.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}}))))});function MT(e){return e?"open":"closed"}const VW=NW,WW=IW,HW=jW,OT=zW,KW=VW,GW=WW,NT=d.forwardRef(({className:e,align:t="center",sideOffset:n=4,...r},o)=>v.jsx(HW,{children:v.jsx(OT,{ref:o,align:t,tabIndex:-1,sideOffset:n,className:_e("z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...r})}));NT.displayName=OT.displayName;function YW(){var e=d.useRef(!0);return e.current?(e.current=!1,!0):e.current}var XW=function(e,t){var n=YW();d.useEffect(function(){if(!n)return e()},t)};const ZW=XW;var qW=function(){};function Mx(e){for(var t=[],n=1;n{const r=xt(s=>s.updateAppState),o=()=>{r({disableShortCuts:!0})},i=()=>{r({disableShortCuts:!1})};return v.jsx("textarea",{className:_e("flex min-h-[60px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50","overflow-auto",e),tabIndex:-1,ref:n,onFocus:o,onBlur:i,...t})});Dx.displayName="Textarea";const yH=()=>{const[e,t,n,r,o,i]=xt(x=>[x.getIsProcessing(),x.settings.prompt,x.updateSettings,x.runInpainting,x.showPrevMask,x.hidePrevMask]),[s,l]=Nx(!1),u=d.useRef(null);DT(u,()=>{u!=null&&u.current&&u.current.blur()});const f=x=>{x.preventDefault(),x.stopPropagation();const S=x.target;n({prompt:S.value})},p=()=>{e||r()},m=x=>{x.key==="Enter"&&x.ctrlKey&&t.length!==0&&p()},g=()=>{o()},y=()=>{i()};return v.jsx("div",{className:"flex gap-4 relative w-full justify-center h-full",children:v.jsxs("div",{className:"absolute flex gap-4",children:[v.jsx(Dx,{ref:u,placeholder:"I want to repaint of...",className:_e(s?"focus:overflow-y-auto":"overflow-y-hidden","min-h-[32px] h-[32px] overflow-x-hidden focus:h-[120px] overflow-y-hidden transition-[height] w-[500px] py-1 px-3 bg-background resize-none"),style:{scrollbarGutter:"stable"},value:t,onInput:f,onKeyUp:m,onTransitionEnd:l}),v.jsx(wn,{size:"sm",onClick:p,disabled:e,onMouseEnter:g,onMouseLeave:y,children:"Paint"})]})})};var zp={exports:{}};/** + * @license + * Lodash + * Copyright OpenJS Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */zp.exports;(function(e,t){(function(){var n,r="4.17.21",o=200,i="Unsupported core-js use. Try https://npms.io/search?q=ponyfill.",s="Expected a function",l="Invalid `variable` option passed into `_.template`",u="__lodash_hash_undefined__",f=500,p="__lodash_placeholder__",m=1,g=2,y=4,x=1,S=2,E=1,_=2,b=4,C=8,R=16,P=32,O=64,A=128,D=256,B=512,V=30,J="...",G=800,se=16,U=1,ne=2,M=3,ee=1/0,H=9007199254740991,X=17976931348623157e292,W=NaN,le=4294967295,pe=le-1,$e=le>>>1,Ve=[["ary",A],["bind",E],["bindKey",_],["curry",C],["curryRight",R],["flip",B],["partial",P],["partialRight",O],["rearg",D]],We="[object Arguments]",Ne="[object Array]",fe="[object AsyncFunction]",xe="[object Boolean]",Re="[object Date]",Me="[object DOMException]",Oe="[object Error]",ze="[object Function]",Mt="[object GeneratorFunction]",ct="[object Map]",Kt="[object Number]",Er="[object Null]",gt="[object Object]",Vs="[object Promise]",L="[object Proxy]",Z="[object RegExp]",q="[object Set]",we="[object String]",me="[object Symbol]",de="[object Undefined]",ke="[object WeakMap]",ft="[object WeakSet]",ht="[object ArrayBuffer]",_n="[object DataView]",Cr="[object Float32Array]",Ni="[object Float64Array]",Co="[object Int8Array]",Vn="[object Int16Array]",Ba="[object Int32Array]",Di="[object Uint8Array]",Ws="[object Uint8ClampedArray]",Ii="[object Uint16Array]",Mc="[object Uint32Array]",Sg=/\b__p \+= '';/g,_g=/\b(__p \+=) '' \+/g,Qd=/(__e\(.*?\)|\b__t\)) \+\n'';/g,Oc=/&(?:amp|lt|gt|quot|#39);/g,Nc=/[&<>"']/g,Dc=RegExp(Oc.source),Eg=RegExp(Nc.source),Ic=/<%-([\s\S]+?)%>/g,Jd=/<%([\s\S]+?)%>/g,Lc=/<%=([\s\S]+?)%>/g,Cg=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,$g=/^\w*$/,Rg=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,K=/[\\^$.*+?()[\]{}|]/g,Ye=RegExp(K.source),st=/^\s+/,Qr=/\s/,an=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,ef=/\{\n\/\* \[wrapped with (.+)\] \*/,a6=/,? & /,l6=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,c6=/[()=,{}\[\]\/\s]/,u6=/\\(\\)?/g,d6=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,mb=/\w*$/,f6=/^[-+]0x[0-9a-f]+$/i,h6=/^0b[01]+$/i,p6=/^\[object .+?Constructor\]$/,m6=/^0o[0-7]+$/i,g6=/^(?:0|[1-9]\d*)$/,v6=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,tf=/($^)/,y6=/['\n\r\u2028\u2029\\]/g,nf="\\ud800-\\udfff",w6="\\u0300-\\u036f",x6="\\ufe20-\\ufe2f",b6="\\u20d0-\\u20ff",gb=w6+x6+b6,vb="\\u2700-\\u27bf",yb="a-z\\xdf-\\xf6\\xf8-\\xff",S6="\\xac\\xb1\\xd7\\xf7",_6="\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf",E6="\\u2000-\\u206f",C6=" \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",wb="A-Z\\xc0-\\xd6\\xd8-\\xde",xb="\\ufe0e\\ufe0f",bb=S6+_6+E6+C6,kg="['’]",$6="["+nf+"]",Sb="["+bb+"]",rf="["+gb+"]",_b="\\d+",R6="["+vb+"]",Eb="["+yb+"]",Cb="[^"+nf+bb+_b+vb+yb+wb+"]",Tg="\\ud83c[\\udffb-\\udfff]",k6="(?:"+rf+"|"+Tg+")",$b="[^"+nf+"]",Pg="(?:\\ud83c[\\udde6-\\uddff]){2}",Ag="[\\ud800-\\udbff][\\udc00-\\udfff]",Ua="["+wb+"]",Rb="\\u200d",kb="(?:"+Eb+"|"+Cb+")",T6="(?:"+Ua+"|"+Cb+")",Tb="(?:"+kg+"(?:d|ll|m|re|s|t|ve))?",Pb="(?:"+kg+"(?:D|LL|M|RE|S|T|VE))?",Ab=k6+"?",Mb="["+xb+"]?",P6="(?:"+Rb+"(?:"+[$b,Pg,Ag].join("|")+")"+Mb+Ab+")*",A6="\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",M6="\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])",Ob=Mb+Ab+P6,O6="(?:"+[R6,Pg,Ag].join("|")+")"+Ob,N6="(?:"+[$b+rf+"?",rf,Pg,Ag,$6].join("|")+")",D6=RegExp(kg,"g"),I6=RegExp(rf,"g"),Mg=RegExp(Tg+"(?="+Tg+")|"+N6+Ob,"g"),L6=RegExp([Ua+"?"+Eb+"+"+Tb+"(?="+[Sb,Ua,"$"].join("|")+")",T6+"+"+Pb+"(?="+[Sb,Ua+kb,"$"].join("|")+")",Ua+"?"+kb+"+"+Tb,Ua+"+"+Pb,M6,A6,_b,O6].join("|"),"g"),F6=RegExp("["+Rb+nf+gb+xb+"]"),j6=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,z6=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],B6=-1,Rt={};Rt[Cr]=Rt[Ni]=Rt[Co]=Rt[Vn]=Rt[Ba]=Rt[Di]=Rt[Ws]=Rt[Ii]=Rt[Mc]=!0,Rt[We]=Rt[Ne]=Rt[ht]=Rt[xe]=Rt[_n]=Rt[Re]=Rt[Oe]=Rt[ze]=Rt[ct]=Rt[Kt]=Rt[gt]=Rt[Z]=Rt[q]=Rt[we]=Rt[ke]=!1;var Et={};Et[We]=Et[Ne]=Et[ht]=Et[_n]=Et[xe]=Et[Re]=Et[Cr]=Et[Ni]=Et[Co]=Et[Vn]=Et[Ba]=Et[ct]=Et[Kt]=Et[gt]=Et[Z]=Et[q]=Et[we]=Et[me]=Et[Di]=Et[Ws]=Et[Ii]=Et[Mc]=!0,Et[Oe]=Et[ze]=Et[ke]=!1;var U6={À:"A",Á:"A",Â:"A",Ã:"A",Ä:"A",Å:"A",à:"a",á:"a",â:"a",ã:"a",ä:"a",å:"a",Ç:"C",ç:"c",Ð:"D",ð:"d",È:"E",É:"E",Ê:"E",Ë:"E",è:"e",é:"e",ê:"e",ë:"e",Ì:"I",Í:"I",Î:"I",Ï:"I",ì:"i",í:"i",î:"i",ï:"i",Ñ:"N",ñ:"n",Ò:"O",Ó:"O",Ô:"O",Õ:"O",Ö:"O",Ø:"O",ò:"o",ó:"o",ô:"o",õ:"o",ö:"o",ø:"o",Ù:"U",Ú:"U",Û:"U",Ü:"U",ù:"u",ú:"u",û:"u",ü:"u",Ý:"Y",ý:"y",ÿ:"y",Æ:"Ae",æ:"ae",Þ:"Th",þ:"th",ß:"ss",Ā:"A",Ă:"A",Ą:"A",ā:"a",ă:"a",ą:"a",Ć:"C",Ĉ:"C",Ċ:"C",Č:"C",ć:"c",ĉ:"c",ċ:"c",č:"c",Ď:"D",Đ:"D",ď:"d",đ:"d",Ē:"E",Ĕ:"E",Ė:"E",Ę:"E",Ě:"E",ē:"e",ĕ:"e",ė:"e",ę:"e",ě:"e",Ĝ:"G",Ğ:"G",Ġ:"G",Ģ:"G",ĝ:"g",ğ:"g",ġ:"g",ģ:"g",Ĥ:"H",Ħ:"H",ĥ:"h",ħ:"h",Ĩ:"I",Ī:"I",Ĭ:"I",Į:"I",İ:"I",ĩ:"i",ī:"i",ĭ:"i",į:"i",ı:"i",Ĵ:"J",ĵ:"j",Ķ:"K",ķ:"k",ĸ:"k",Ĺ:"L",Ļ:"L",Ľ:"L",Ŀ:"L",Ł:"L",ĺ:"l",ļ:"l",ľ:"l",ŀ:"l",ł:"l",Ń:"N",Ņ:"N",Ň:"N",Ŋ:"N",ń:"n",ņ:"n",ň:"n",ŋ:"n",Ō:"O",Ŏ:"O",Ő:"O",ō:"o",ŏ:"o",ő:"o",Ŕ:"R",Ŗ:"R",Ř:"R",ŕ:"r",ŗ:"r",ř:"r",Ś:"S",Ŝ:"S",Ş:"S",Š:"S",ś:"s",ŝ:"s",ş:"s",š:"s",Ţ:"T",Ť:"T",Ŧ:"T",ţ:"t",ť:"t",ŧ:"t",Ũ:"U",Ū:"U",Ŭ:"U",Ů:"U",Ű:"U",Ų:"U",ũ:"u",ū:"u",ŭ:"u",ů:"u",ű:"u",ų:"u",Ŵ:"W",ŵ:"w",Ŷ:"Y",ŷ:"y",Ÿ:"Y",Ź:"Z",Ż:"Z",Ž:"Z",ź:"z",ż:"z",ž:"z",IJ:"IJ",ij:"ij",Œ:"Oe",œ:"oe",ʼn:"'n",ſ:"s"},V6={"&":"&","<":"<",">":">",'"':""","'":"'"},W6={"&":"&","<":"<",">":">",""":'"',"'":"'"},H6={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},K6=parseFloat,G6=parseInt,Nb=typeof Jc=="object"&&Jc&&Jc.Object===Object&&Jc,Y6=typeof self=="object"&&self&&self.Object===Object&&self,fn=Nb||Y6||Function("return this")(),Og=t&&!t.nodeType&&t,Hs=Og&&!0&&e&&!e.nodeType&&e,Db=Hs&&Hs.exports===Og,Ng=Db&&Nb.process,$r=function(){try{var F=Hs&&Hs.require&&Hs.require("util").types;return F||Ng&&Ng.binding&&Ng.binding("util")}catch{}}(),Ib=$r&&$r.isArrayBuffer,Lb=$r&&$r.isDate,Fb=$r&&$r.isMap,jb=$r&&$r.isRegExp,zb=$r&&$r.isSet,Bb=$r&&$r.isTypedArray;function or(F,te,Q){switch(Q.length){case 0:return F.call(te);case 1:return F.call(te,Q[0]);case 2:return F.call(te,Q[0],Q[1]);case 3:return F.call(te,Q[0],Q[1],Q[2])}return F.apply(te,Q)}function X6(F,te,Q,Se){for(var Ke=-1,pt=F==null?0:F.length;++Ke-1}function Dg(F,te,Q){for(var Se=-1,Ke=F==null?0:F.length;++Se-1;);return Q}function Xb(F,te){for(var Q=F.length;Q--&&Va(te,F[Q],0)>-1;);return Q}function oM(F,te){for(var Q=F.length,Se=0;Q--;)F[Q]===te&&++Se;return Se}var iM=jg(U6),sM=jg(V6);function aM(F){return"\\"+H6[F]}function lM(F,te){return F==null?n:F[te]}function Wa(F){return F6.test(F)}function cM(F){return j6.test(F)}function uM(F){for(var te,Q=[];!(te=F.next()).done;)Q.push(te.value);return Q}function Vg(F){var te=-1,Q=Array(F.size);return F.forEach(function(Se,Ke){Q[++te]=[Ke,Se]}),Q}function Zb(F,te){return function(Q){return F(te(Q))}}function ji(F,te){for(var Q=-1,Se=F.length,Ke=0,pt=[];++Q-1}function qM(a,c){var h=this.__data__,w=Sf(h,a);return w<0?(++this.size,h.push([a,c])):h[w][1]=c,this}ti.prototype.clear=GM,ti.prototype.delete=YM,ti.prototype.get=XM,ti.prototype.has=ZM,ti.prototype.set=qM;function ni(a){var c=-1,h=a==null?0:a.length;for(this.clear();++c=c?a:c)),a}function Pr(a,c,h,w,$,T){var N,I=c&m,z=c&g,re=c&y;if(h&&(N=$?h(a,w,$,T):h(a)),N!==n)return N;if(!It(a))return a;var oe=Ge(a);if(oe){if(N=tO(a),!I)return Wn(a,N)}else{var ae=Cn(a),ge=ae==ze||ae==Mt;if(Hi(a))return MS(a,I);if(ae==gt||ae==We||ge&&!$){if(N=z||ge?{}:qS(a),!I)return z?W7(a,h7(N,a)):V7(a,lS(N,a))}else{if(!Et[ae])return $?a:{};N=nO(a,ae,I)}}T||(T=new eo);var Te=T.get(a);if(Te)return Te;T.set(a,N),$_(a)?a.forEach(function(Fe){N.add(Pr(Fe,c,h,Fe,a,T))}):E_(a)&&a.forEach(function(Fe,nt){N.set(nt,Pr(Fe,c,h,nt,a,T))});var Le=re?z?mv:pv:z?Kn:ln,Qe=oe?n:Le(a);return Rr(Qe||a,function(Fe,nt){Qe&&(nt=Fe,Fe=a[nt]),Wc(N,nt,Pr(Fe,c,h,nt,a,T))}),N}function p7(a){var c=ln(a);return function(h){return cS(h,a,c)}}function cS(a,c,h){var w=h.length;if(a==null)return!w;for(a=St(a);w--;){var $=h[w],T=c[$],N=a[$];if(N===n&&!($ in a)||!T(N))return!1}return!0}function uS(a,c,h){if(typeof a!="function")throw new kr(s);return qc(function(){a.apply(n,h)},c)}function Hc(a,c,h,w){var $=-1,T=of,N=!0,I=a.length,z=[],re=c.length;if(!I)return z;h&&(c=Ot(c,ir(h))),w?(T=Dg,N=!1):c.length>=o&&(T=Fc,N=!1,c=new Ys(c));e:for(;++$$?0:$+h),w=w===n||w>$?$:qe(w),w<0&&(w+=$),w=h>w?0:k_(w);h0&&h(I)?c>1?hn(I,c-1,h,w,$):Fi($,I):w||($[$.length]=I)}return $}var Zg=FS(),hS=FS(!0);function $o(a,c){return a&&Zg(a,c,ln)}function qg(a,c){return a&&hS(a,c,ln)}function Ef(a,c){return Li(c,function(h){return ai(a[h])})}function Zs(a,c){c=Vi(c,a);for(var h=0,w=c.length;a!=null&&hc}function v7(a,c){return a!=null&&yt.call(a,c)}function y7(a,c){return a!=null&&c in St(a)}function w7(a,c,h){return a>=En(c,h)&&a=120&&oe.length>=120)?new Ys(N&&oe):n}oe=a[0];var ae=-1,ge=I[0];e:for(;++ae<$&&re.length-1;)I!==a&&mf.call(I,z,1),mf.call(a,z,1);return a}function ES(a,c){for(var h=a?c.length:0,w=h-1;h--;){var $=c[h];if(h==w||$!==T){var T=$;si($)?mf.call(a,$,1):av(a,$)}}return a}function ov(a,c){return a+yf(oS()*(c-a+1))}function M7(a,c,h,w){for(var $=-1,T=tn(vf((c-a)/(h||1)),0),N=Q(T);T--;)N[w?T:++$]=a,a+=h;return N}function iv(a,c){var h="";if(!a||c<1||c>H)return h;do c%2&&(h+=a),c=yf(c/2),c&&(a+=a);while(c);return h}function et(a,c){return Sv(e_(a,c,Gn),a+"")}function O7(a){return aS(tl(a))}function N7(a,c){var h=tl(a);return Df(h,Xs(c,0,h.length))}function Yc(a,c,h,w){if(!It(a))return a;c=Vi(c,a);for(var $=-1,T=c.length,N=T-1,I=a;I!=null&&++$$?0:$+c),h=h>$?$:h,h<0&&(h+=$),$=c>h?0:h-c>>>0,c>>>=0;for(var T=Q($);++w<$;)T[w]=a[w+c];return T}function L7(a,c){var h;return Bi(a,function(w,$,T){return h=c(w,$,T),!h}),!!h}function $f(a,c,h){var w=0,$=a==null?w:a.length;if(typeof c=="number"&&c===c&&$<=$e){for(;w<$;){var T=w+$>>>1,N=a[T];N!==null&&!ar(N)&&(h?N<=c:N=o){var re=c?null:Y7(a);if(re)return af(re);N=!1,$=Fc,z=new Ys}else z=c?[]:I;e:for(;++w=w?a:Ar(a,c,h)}var AS=CM||function(a){return fn.clearTimeout(a)};function MS(a,c){if(c)return a.slice();var h=a.length,w=Jb?Jb(h):new a.constructor(h);return a.copy(w),w}function dv(a){var c=new a.constructor(a.byteLength);return new hf(c).set(new hf(a)),c}function j7(a,c){var h=c?dv(a.buffer):a.buffer;return new a.constructor(h,a.byteOffset,a.byteLength)}function z7(a){var c=new a.constructor(a.source,mb.exec(a));return c.lastIndex=a.lastIndex,c}function B7(a){return Vc?St(Vc.call(a)):{}}function OS(a,c){var h=c?dv(a.buffer):a.buffer;return new a.constructor(h,a.byteOffset,a.length)}function NS(a,c){if(a!==c){var h=a!==n,w=a===null,$=a===a,T=ar(a),N=c!==n,I=c===null,z=c===c,re=ar(c);if(!I&&!re&&!T&&a>c||T&&N&&z&&!I&&!re||w&&N&&z||!h&&z||!$)return 1;if(!w&&!T&&!re&&a=I)return z;var re=h[w];return z*(re=="desc"?-1:1)}}return a.index-c.index}function DS(a,c,h,w){for(var $=-1,T=a.length,N=h.length,I=-1,z=c.length,re=tn(T-N,0),oe=Q(z+re),ae=!w;++I1?h[$-1]:n,N=$>2?h[2]:n;for(T=a.length>3&&typeof T=="function"?($--,T):n,N&&Nn(h[0],h[1],N)&&(T=$<3?n:T,$=1),c=St(c);++w<$;){var I=h[w];I&&a(c,I,w,T)}return c})}function LS(a,c){return function(h,w){if(h==null)return h;if(!Hn(h))return a(h,w);for(var $=h.length,T=c?$:-1,N=St(h);(c?T--:++T<$)&&w(N[T],T,N)!==!1;);return h}}function FS(a){return function(c,h,w){for(var $=-1,T=St(c),N=w(c),I=N.length;I--;){var z=N[a?I:++$];if(h(T[z],z,T)===!1)break}return c}}function H7(a,c,h){var w=c&E,$=Xc(a);function T(){var N=this&&this!==fn&&this instanceof T?$:a;return N.apply(w?h:this,arguments)}return T}function jS(a){return function(c){c=vt(c);var h=Wa(c)?Jr(c):n,w=h?h[0]:c.charAt(0),$=h?Wi(h,1).join(""):c.slice(1);return w[a]()+$}}function Qa(a){return function(c){return Ig(L_(I_(c).replace(D6,"")),a,"")}}function Xc(a){return function(){var c=arguments;switch(c.length){case 0:return new a;case 1:return new a(c[0]);case 2:return new a(c[0],c[1]);case 3:return new a(c[0],c[1],c[2]);case 4:return new a(c[0],c[1],c[2],c[3]);case 5:return new a(c[0],c[1],c[2],c[3],c[4]);case 6:return new a(c[0],c[1],c[2],c[3],c[4],c[5]);case 7:return new a(c[0],c[1],c[2],c[3],c[4],c[5],c[6])}var h=Za(a.prototype),w=a.apply(h,c);return It(w)?w:h}}function K7(a,c,h){var w=Xc(a);function $(){for(var T=arguments.length,N=Q(T),I=T,z=Ja($);I--;)N[I]=arguments[I];var re=T<3&&N[0]!==z&&N[T-1]!==z?[]:ji(N,z);if(T-=re.length,T-1?$[T?c[N]:N]:n}}function BS(a){return ii(function(c){var h=c.length,w=h,$=Tr.prototype.thru;for(a&&c.reverse();w--;){var T=c[w];if(typeof T!="function")throw new kr(s);if($&&!N&&Of(T)=="wrapper")var N=new Tr([],!0)}for(w=N?w:h;++w1&&at.reverse(),oe&&zI))return!1;var re=T.get(a),oe=T.get(c);if(re&&oe)return re==c&&oe==a;var ae=-1,ge=!0,Te=h&S?new Ys:n;for(T.set(a,c),T.set(c,a);++ae1?"& ":"")+c[w],c=c.join(h>2?", ":" "),a.replace(an,`{ +/* [wrapped with `+c+`] */ +`)}function oO(a){return Ge(a)||Js(a)||!!(nS&&a&&a[nS])}function si(a,c){var h=typeof a;return c=c??H,!!c&&(h=="number"||h!="symbol"&&g6.test(a))&&a>-1&&a%1==0&&a0){if(++c>=G)return arguments[0]}else c=0;return a.apply(n,arguments)}}function Df(a,c){var h=-1,w=a.length,$=w-1;for(c=c===n?w:c;++h1?a[c-1]:n;return h=typeof h=="function"?(a.pop(),h):n,f_(a,h)});function h_(a){var c=k(a);return c.__chain__=!0,c}function m4(a,c){return c(a),a}function If(a,c){return c(a)}var g4=ii(function(a){var c=a.length,h=c?a[0]:0,w=this.__wrapped__,$=function(T){return Xg(T,a)};return c>1||this.__actions__.length||!(w instanceof ot)||!si(h)?this.thru($):(w=w.slice(h,+h+(c?1:0)),w.__actions__.push({func:If,args:[$],thisArg:n}),new Tr(w,this.__chain__).thru(function(T){return c&&!T.length&&T.push(n),T}))});function v4(){return h_(this)}function y4(){return new Tr(this.value(),this.__chain__)}function w4(){this.__values__===n&&(this.__values__=R_(this.value()));var a=this.__index__>=this.__values__.length,c=a?n:this.__values__[this.__index__++];return{done:a,value:c}}function x4(){return this}function b4(a){for(var c,h=this;h instanceof bf;){var w=s_(h);w.__index__=0,w.__values__=n,c?$.__wrapped__=w:c=w;var $=w;h=h.__wrapped__}return $.__wrapped__=a,c}function S4(){var a=this.__wrapped__;if(a instanceof ot){var c=a;return this.__actions__.length&&(c=new ot(this)),c=c.reverse(),c.__actions__.push({func:If,args:[_v],thisArg:n}),new Tr(c,this.__chain__)}return this.thru(_v)}function _4(){return TS(this.__wrapped__,this.__actions__)}var E4=kf(function(a,c,h){yt.call(a,h)?++a[h]:ri(a,h,1)});function C4(a,c,h){var w=Ge(a)?Ub:m7;return h&&Nn(a,c,h)&&(c=n),w(a,Ie(c,3))}function $4(a,c){var h=Ge(a)?Li:fS;return h(a,Ie(c,3))}var R4=zS(a_),k4=zS(l_);function T4(a,c){return hn(Lf(a,c),1)}function P4(a,c){return hn(Lf(a,c),ee)}function A4(a,c,h){return h=h===n?1:qe(h),hn(Lf(a,c),h)}function p_(a,c){var h=Ge(a)?Rr:Bi;return h(a,Ie(c,3))}function m_(a,c){var h=Ge(a)?Z6:dS;return h(a,Ie(c,3))}var M4=kf(function(a,c,h){yt.call(a,h)?a[h].push(c):ri(a,h,[c])});function O4(a,c,h,w){a=Hn(a)?a:tl(a),h=h&&!w?qe(h):0;var $=a.length;return h<0&&(h=tn($+h,0)),Uf(a)?h<=$&&a.indexOf(c,h)>-1:!!$&&Va(a,c,h)>-1}var N4=et(function(a,c,h){var w=-1,$=typeof c=="function",T=Hn(a)?Q(a.length):[];return Bi(a,function(N){T[++w]=$?or(c,N,h):Kc(N,c,h)}),T}),D4=kf(function(a,c,h){ri(a,h,c)});function Lf(a,c){var h=Ge(a)?Ot:yS;return h(a,Ie(c,3))}function I4(a,c,h,w){return a==null?[]:(Ge(c)||(c=c==null?[]:[c]),h=w?n:h,Ge(h)||(h=h==null?[]:[h]),SS(a,c,h))}var L4=kf(function(a,c,h){a[h?0:1].push(c)},function(){return[[],[]]});function F4(a,c,h){var w=Ge(a)?Ig:Kb,$=arguments.length<3;return w(a,Ie(c,4),h,$,Bi)}function j4(a,c,h){var w=Ge(a)?q6:Kb,$=arguments.length<3;return w(a,Ie(c,4),h,$,dS)}function z4(a,c){var h=Ge(a)?Li:fS;return h(a,zf(Ie(c,3)))}function B4(a){var c=Ge(a)?aS:O7;return c(a)}function U4(a,c,h){(h?Nn(a,c,h):c===n)?c=1:c=qe(c);var w=Ge(a)?u7:N7;return w(a,c)}function V4(a){var c=Ge(a)?d7:I7;return c(a)}function W4(a){if(a==null)return 0;if(Hn(a))return Uf(a)?Ha(a):a.length;var c=Cn(a);return c==ct||c==q?a.size:tv(a).length}function H4(a,c,h){var w=Ge(a)?Lg:L7;return h&&Nn(a,c,h)&&(c=n),w(a,Ie(c,3))}var K4=et(function(a,c){if(a==null)return[];var h=c.length;return h>1&&Nn(a,c[0],c[1])?c=[]:h>2&&Nn(c[0],c[1],c[2])&&(c=[c[0]]),SS(a,hn(c,1),[])}),Ff=$M||function(){return fn.Date.now()};function G4(a,c){if(typeof c!="function")throw new kr(s);return a=qe(a),function(){if(--a<1)return c.apply(this,arguments)}}function g_(a,c,h){return c=h?n:c,c=a&&c==null?a.length:c,oi(a,A,n,n,n,n,c)}function v_(a,c){var h;if(typeof c!="function")throw new kr(s);return a=qe(a),function(){return--a>0&&(h=c.apply(this,arguments)),a<=1&&(c=n),h}}var Cv=et(function(a,c,h){var w=E;if(h.length){var $=ji(h,Ja(Cv));w|=P}return oi(a,w,c,h,$)}),y_=et(function(a,c,h){var w=E|_;if(h.length){var $=ji(h,Ja(y_));w|=P}return oi(c,w,a,h,$)});function w_(a,c,h){c=h?n:c;var w=oi(a,C,n,n,n,n,n,c);return w.placeholder=w_.placeholder,w}function x_(a,c,h){c=h?n:c;var w=oi(a,R,n,n,n,n,n,c);return w.placeholder=x_.placeholder,w}function b_(a,c,h){var w,$,T,N,I,z,re=0,oe=!1,ae=!1,ge=!0;if(typeof a!="function")throw new kr(s);c=Or(c)||0,It(h)&&(oe=!!h.leading,ae="maxWait"in h,T=ae?tn(Or(h.maxWait)||0,c):T,ge="trailing"in h?!!h.trailing:ge);function Te(Yt){var no=w,ci=$;return w=$=n,re=Yt,N=a.apply(ci,no),N}function Le(Yt){return re=Yt,I=qc(nt,c),oe?Te(Yt):N}function Qe(Yt){var no=Yt-z,ci=Yt-re,z_=c-no;return ae?En(z_,T-ci):z_}function Fe(Yt){var no=Yt-z,ci=Yt-re;return z===n||no>=c||no<0||ae&&ci>=T}function nt(){var Yt=Ff();if(Fe(Yt))return at(Yt);I=qc(nt,Qe(Yt))}function at(Yt){return I=n,ge&&w?Te(Yt):(w=$=n,N)}function lr(){I!==n&&AS(I),re=0,w=z=$=I=n}function Dn(){return I===n?N:at(Ff())}function cr(){var Yt=Ff(),no=Fe(Yt);if(w=arguments,$=this,z=Yt,no){if(I===n)return Le(z);if(ae)return AS(I),I=qc(nt,c),Te(z)}return I===n&&(I=qc(nt,c)),N}return cr.cancel=lr,cr.flush=Dn,cr}var Y4=et(function(a,c){return uS(a,1,c)}),X4=et(function(a,c,h){return uS(a,Or(c)||0,h)});function Z4(a){return oi(a,B)}function jf(a,c){if(typeof a!="function"||c!=null&&typeof c!="function")throw new kr(s);var h=function(){var w=arguments,$=c?c.apply(this,w):w[0],T=h.cache;if(T.has($))return T.get($);var N=a.apply(this,w);return h.cache=T.set($,N)||T,N};return h.cache=new(jf.Cache||ni),h}jf.Cache=ni;function zf(a){if(typeof a!="function")throw new kr(s);return function(){var c=arguments;switch(c.length){case 0:return!a.call(this);case 1:return!a.call(this,c[0]);case 2:return!a.call(this,c[0],c[1]);case 3:return!a.call(this,c[0],c[1],c[2])}return!a.apply(this,c)}}function q4(a){return v_(2,a)}var Q4=F7(function(a,c){c=c.length==1&&Ge(c[0])?Ot(c[0],ir(Ie())):Ot(hn(c,1),ir(Ie()));var h=c.length;return et(function(w){for(var $=-1,T=En(w.length,h);++$=c}),Js=mS(function(){return arguments}())?mS:function(a){return Bt(a)&&yt.call(a,"callee")&&!tS.call(a,"callee")},Ge=Q.isArray,hN=Ib?ir(Ib):b7;function Hn(a){return a!=null&&Bf(a.length)&&!ai(a)}function Gt(a){return Bt(a)&&Hn(a)}function pN(a){return a===!0||a===!1||Bt(a)&&On(a)==xe}var Hi=kM||Lv,mN=Lb?ir(Lb):S7;function gN(a){return Bt(a)&&a.nodeType===1&&!Qc(a)}function vN(a){if(a==null)return!0;if(Hn(a)&&(Ge(a)||typeof a=="string"||typeof a.splice=="function"||Hi(a)||el(a)||Js(a)))return!a.length;var c=Cn(a);if(c==ct||c==q)return!a.size;if(Zc(a))return!tv(a).length;for(var h in a)if(yt.call(a,h))return!1;return!0}function yN(a,c){return Gc(a,c)}function wN(a,c,h){h=typeof h=="function"?h:n;var w=h?h(a,c):n;return w===n?Gc(a,c,n,h):!!w}function Rv(a){if(!Bt(a))return!1;var c=On(a);return c==Oe||c==Me||typeof a.message=="string"&&typeof a.name=="string"&&!Qc(a)}function xN(a){return typeof a=="number"&&rS(a)}function ai(a){if(!It(a))return!1;var c=On(a);return c==ze||c==Mt||c==fe||c==L}function __(a){return typeof a=="number"&&a==qe(a)}function Bf(a){return typeof a=="number"&&a>-1&&a%1==0&&a<=H}function It(a){var c=typeof a;return a!=null&&(c=="object"||c=="function")}function Bt(a){return a!=null&&typeof a=="object"}var E_=Fb?ir(Fb):E7;function bN(a,c){return a===c||ev(a,c,vv(c))}function SN(a,c,h){return h=typeof h=="function"?h:n,ev(a,c,vv(c),h)}function _N(a){return C_(a)&&a!=+a}function EN(a){if(aO(a))throw new Ke(i);return gS(a)}function CN(a){return a===null}function $N(a){return a==null}function C_(a){return typeof a=="number"||Bt(a)&&On(a)==Kt}function Qc(a){if(!Bt(a)||On(a)!=gt)return!1;var c=pf(a);if(c===null)return!0;var h=yt.call(c,"constructor")&&c.constructor;return typeof h=="function"&&h instanceof h&&uf.call(h)==SM}var kv=jb?ir(jb):C7;function RN(a){return __(a)&&a>=-H&&a<=H}var $_=zb?ir(zb):$7;function Uf(a){return typeof a=="string"||!Ge(a)&&Bt(a)&&On(a)==we}function ar(a){return typeof a=="symbol"||Bt(a)&&On(a)==me}var el=Bb?ir(Bb):R7;function kN(a){return a===n}function TN(a){return Bt(a)&&Cn(a)==ke}function PN(a){return Bt(a)&&On(a)==ft}var AN=Mf(nv),MN=Mf(function(a,c){return a<=c});function R_(a){if(!a)return[];if(Hn(a))return Uf(a)?Jr(a):Wn(a);if(jc&&a[jc])return uM(a[jc]());var c=Cn(a),h=c==ct?Vg:c==q?af:tl;return h(a)}function li(a){if(!a)return a===0?a:0;if(a=Or(a),a===ee||a===-ee){var c=a<0?-1:1;return c*X}return a===a?a:0}function qe(a){var c=li(a),h=c%1;return c===c?h?c-h:c:0}function k_(a){return a?Xs(qe(a),0,le):0}function Or(a){if(typeof a=="number")return a;if(ar(a))return W;if(It(a)){var c=typeof a.valueOf=="function"?a.valueOf():a;a=It(c)?c+"":c}if(typeof a!="string")return a===0?a:+a;a=Gb(a);var h=h6.test(a);return h||m6.test(a)?G6(a.slice(2),h?2:8):f6.test(a)?W:+a}function T_(a){return Ro(a,Kn(a))}function ON(a){return a?Xs(qe(a),-H,H):a===0?a:0}function vt(a){return a==null?"":sr(a)}var NN=qa(function(a,c){if(Zc(c)||Hn(c)){Ro(c,ln(c),a);return}for(var h in c)yt.call(c,h)&&Wc(a,h,c[h])}),P_=qa(function(a,c){Ro(c,Kn(c),a)}),Vf=qa(function(a,c,h,w){Ro(c,Kn(c),a,w)}),DN=qa(function(a,c,h,w){Ro(c,ln(c),a,w)}),IN=ii(Xg);function LN(a,c){var h=Za(a);return c==null?h:lS(h,c)}var FN=et(function(a,c){a=St(a);var h=-1,w=c.length,$=w>2?c[2]:n;for($&&Nn(c[0],c[1],$)&&(w=1);++h1),T}),Ro(a,mv(a),h),w&&(h=Pr(h,m|g|y,X7));for(var $=c.length;$--;)av(h,c[$]);return h});function n8(a,c){return M_(a,zf(Ie(c)))}var r8=ii(function(a,c){return a==null?{}:P7(a,c)});function M_(a,c){if(a==null)return{};var h=Ot(mv(a),function(w){return[w]});return c=Ie(c),_S(a,h,function(w,$){return c(w,$[0])})}function o8(a,c,h){c=Vi(c,a);var w=-1,$=c.length;for($||($=1,a=n);++w<$;){var T=a==null?n:a[ko(c[w])];T===n&&(w=$,T=h),a=ai(T)?T.call(a):T}return a}function i8(a,c,h){return a==null?a:Yc(a,c,h)}function s8(a,c,h,w){return w=typeof w=="function"?w:n,a==null?a:Yc(a,c,h,w)}var O_=HS(ln),N_=HS(Kn);function a8(a,c,h){var w=Ge(a),$=w||Hi(a)||el(a);if(c=Ie(c,4),h==null){var T=a&&a.constructor;$?h=w?new T:[]:It(a)?h=ai(T)?Za(pf(a)):{}:h={}}return($?Rr:$o)(a,function(N,I,z){return c(h,N,I,z)}),h}function l8(a,c){return a==null?!0:av(a,c)}function c8(a,c,h){return a==null?a:kS(a,c,uv(h))}function u8(a,c,h,w){return w=typeof w=="function"?w:n,a==null?a:kS(a,c,uv(h),w)}function tl(a){return a==null?[]:Ug(a,ln(a))}function d8(a){return a==null?[]:Ug(a,Kn(a))}function f8(a,c,h){return h===n&&(h=c,c=n),h!==n&&(h=Or(h),h=h===h?h:0),c!==n&&(c=Or(c),c=c===c?c:0),Xs(Or(a),c,h)}function h8(a,c,h){return c=li(c),h===n?(h=c,c=0):h=li(h),a=Or(a),w7(a,c,h)}function p8(a,c,h){if(h&&typeof h!="boolean"&&Nn(a,c,h)&&(c=h=n),h===n&&(typeof c=="boolean"?(h=c,c=n):typeof a=="boolean"&&(h=a,a=n)),a===n&&c===n?(a=0,c=1):(a=li(a),c===n?(c=a,a=0):c=li(c)),a>c){var w=a;a=c,c=w}if(h||a%1||c%1){var $=oS();return En(a+$*(c-a+K6("1e-"+(($+"").length-1))),c)}return ov(a,c)}var m8=Qa(function(a,c,h){return c=c.toLowerCase(),a+(h?D_(c):c)});function D_(a){return Av(vt(a).toLowerCase())}function I_(a){return a=vt(a),a&&a.replace(v6,iM).replace(I6,"")}function g8(a,c,h){a=vt(a),c=sr(c);var w=a.length;h=h===n?w:Xs(qe(h),0,w);var $=h;return h-=c.length,h>=0&&a.slice(h,$)==c}function v8(a){return a=vt(a),a&&Eg.test(a)?a.replace(Nc,sM):a}function y8(a){return a=vt(a),a&&Ye.test(a)?a.replace(K,"\\$&"):a}var w8=Qa(function(a,c,h){return a+(h?"-":"")+c.toLowerCase()}),x8=Qa(function(a,c,h){return a+(h?" ":"")+c.toLowerCase()}),b8=jS("toLowerCase");function S8(a,c,h){a=vt(a),c=qe(c);var w=c?Ha(a):0;if(!c||w>=c)return a;var $=(c-w)/2;return Af(yf($),h)+a+Af(vf($),h)}function _8(a,c,h){a=vt(a),c=qe(c);var w=c?Ha(a):0;return c&&w>>0,h?(a=vt(a),a&&(typeof c=="string"||c!=null&&!kv(c))&&(c=sr(c),!c&&Wa(a))?Wi(Jr(a),0,h):a.split(c,h)):[]}var P8=Qa(function(a,c,h){return a+(h?" ":"")+Av(c)});function A8(a,c,h){return a=vt(a),h=h==null?0:Xs(qe(h),0,a.length),c=sr(c),a.slice(h,h+c.length)==c}function M8(a,c,h){var w=k.templateSettings;h&&Nn(a,c,h)&&(c=n),a=vt(a),c=Vf({},c,w,KS);var $=Vf({},c.imports,w.imports,KS),T=ln($),N=Ug($,T),I,z,re=0,oe=c.interpolate||tf,ae="__p += '",ge=Wg((c.escape||tf).source+"|"+oe.source+"|"+(oe===Lc?d6:tf).source+"|"+(c.evaluate||tf).source+"|$","g"),Te="//# sourceURL="+(yt.call(c,"sourceURL")?(c.sourceURL+"").replace(/\s/g," "):"lodash.templateSources["+ ++B6+"]")+` +`;a.replace(ge,function(Fe,nt,at,lr,Dn,cr){return at||(at=lr),ae+=a.slice(re,cr).replace(y6,aM),nt&&(I=!0,ae+=`' + +__e(`+nt+`) + +'`),Dn&&(z=!0,ae+=`'; +`+Dn+`; +__p += '`),at&&(ae+=`' + +((__t = (`+at+`)) == null ? '' : __t) + +'`),re=cr+Fe.length,Fe}),ae+=`'; +`;var Le=yt.call(c,"variable")&&c.variable;if(!Le)ae=`with (obj) { +`+ae+` +} +`;else if(c6.test(Le))throw new Ke(l);ae=(z?ae.replace(Sg,""):ae).replace(_g,"$1").replace(Qd,"$1;"),ae="function("+(Le||"obj")+`) { +`+(Le?"":`obj || (obj = {}); +`)+"var __t, __p = ''"+(I?", __e = _.escape":"")+(z?`, __j = Array.prototype.join; +function print() { __p += __j.call(arguments, '') } +`:`; +`)+ae+`return __p +}`;var Qe=F_(function(){return pt(T,Te+"return "+ae).apply(n,N)});if(Qe.source=ae,Rv(Qe))throw Qe;return Qe}function O8(a){return vt(a).toLowerCase()}function N8(a){return vt(a).toUpperCase()}function D8(a,c,h){if(a=vt(a),a&&(h||c===n))return Gb(a);if(!a||!(c=sr(c)))return a;var w=Jr(a),$=Jr(c),T=Yb(w,$),N=Xb(w,$)+1;return Wi(w,T,N).join("")}function I8(a,c,h){if(a=vt(a),a&&(h||c===n))return a.slice(0,qb(a)+1);if(!a||!(c=sr(c)))return a;var w=Jr(a),$=Xb(w,Jr(c))+1;return Wi(w,0,$).join("")}function L8(a,c,h){if(a=vt(a),a&&(h||c===n))return a.replace(st,"");if(!a||!(c=sr(c)))return a;var w=Jr(a),$=Yb(w,Jr(c));return Wi(w,$).join("")}function F8(a,c){var h=V,w=J;if(It(c)){var $="separator"in c?c.separator:$;h="length"in c?qe(c.length):h,w="omission"in c?sr(c.omission):w}a=vt(a);var T=a.length;if(Wa(a)){var N=Jr(a);T=N.length}if(h>=T)return a;var I=h-Ha(w);if(I<1)return w;var z=N?Wi(N,0,I).join(""):a.slice(0,I);if($===n)return z+w;if(N&&(I+=z.length-I),kv($)){if(a.slice(I).search($)){var re,oe=z;for($.global||($=Wg($.source,vt(mb.exec($))+"g")),$.lastIndex=0;re=$.exec(oe);)var ae=re.index;z=z.slice(0,ae===n?I:ae)}}else if(a.indexOf(sr($),I)!=I){var ge=z.lastIndexOf($);ge>-1&&(z=z.slice(0,ge))}return z+w}function j8(a){return a=vt(a),a&&Dc.test(a)?a.replace(Oc,pM):a}var z8=Qa(function(a,c,h){return a+(h?" ":"")+c.toUpperCase()}),Av=jS("toUpperCase");function L_(a,c,h){return a=vt(a),c=h?n:c,c===n?cM(a)?vM(a):eM(a):a.match(c)||[]}var F_=et(function(a,c){try{return or(a,n,c)}catch(h){return Rv(h)?h:new Ke(h)}}),B8=ii(function(a,c){return Rr(c,function(h){h=ko(h),ri(a,h,Cv(a[h],a))}),a});function U8(a){var c=a==null?0:a.length,h=Ie();return a=c?Ot(a,function(w){if(typeof w[1]!="function")throw new kr(s);return[h(w[0]),w[1]]}):[],et(function(w){for(var $=-1;++$H)return[];var h=le,w=En(a,le);c=Ie(c),a-=le;for(var $=Bg(w,c);++h0||c<0)?new ot(h):(a<0?h=h.takeRight(-a):a&&(h=h.drop(a)),c!==n&&(c=qe(c),h=c<0?h.dropRight(-c):h.take(c-a)),h)},ot.prototype.takeRightWhile=function(a){return this.reverse().takeWhile(a).reverse()},ot.prototype.toArray=function(){return this.take(le)},$o(ot.prototype,function(a,c){var h=/^(?:filter|find|map|reject)|While$/.test(c),w=/^(?:head|last)$/.test(c),$=k[w?"take"+(c=="last"?"Right":""):c],T=w||/^find/.test(c);$&&(k.prototype[c]=function(){var N=this.__wrapped__,I=w?[1]:arguments,z=N instanceof ot,re=I[0],oe=z||Ge(N),ae=function(nt){var at=$.apply(k,Fi([nt],I));return w&&ge?at[0]:at};oe&&h&&typeof re=="function"&&re.length!=1&&(z=oe=!1);var ge=this.__chain__,Te=!!this.__actions__.length,Le=T&&!ge,Qe=z&&!Te;if(!T&&oe){N=Qe?N:new ot(this);var Fe=a.apply(N,I);return Fe.__actions__.push({func:If,args:[ae],thisArg:n}),new Tr(Fe,ge)}return Le&&Qe?a.apply(this,I):(Fe=this.thru(ae),Le?w?Fe.value()[0]:Fe.value():Fe)})}),Rr(["pop","push","shift","sort","splice","unshift"],function(a){var c=lf[a],h=/^(?:push|sort|unshift)$/.test(a)?"tap":"thru",w=/^(?:pop|shift)$/.test(a);k.prototype[a]=function(){var $=arguments;if(w&&!this.__chain__){var T=this.value();return c.apply(Ge(T)?T:[],$)}return this[h](function(N){return c.apply(Ge(N)?N:[],$)})}}),$o(ot.prototype,function(a,c){var h=k[c];if(h){var w=h.name+"";yt.call(Xa,w)||(Xa[w]=[]),Xa[w].push({name:c,func:h})}}),Xa[Tf(n,_).name]=[{name:"wrapper",func:n}],ot.prototype.clone=jM,ot.prototype.reverse=zM,ot.prototype.value=BM,k.prototype.at=g4,k.prototype.chain=v4,k.prototype.commit=y4,k.prototype.next=w4,k.prototype.plant=b4,k.prototype.reverse=S4,k.prototype.toJSON=k.prototype.valueOf=k.prototype.value=_4,k.prototype.first=k.prototype.head,jc&&(k.prototype[jc]=x4),k},Ka=yM();Hs?((Hs.exports=Ka)._=Ka,Og._=Ka):fn._=Ka}).call(Jc)})(zp,zp.exports);var wH=zp.exports;const xH=dm(wH);function Vr({width:e,height:t}){return e/t}function Bp(e,t=0){const n=10**t;return Math.round((e+Number.EPSILON)*n)/n}function bH(e){return(t,n)=>e(n)-e(t)}class SH{constructor(t){this.comparator=t,this.heap=[],this.n=0}greater(t,n){return this.comparator(this.heap[t],this.heap[n])<0}swap(t,n){const r=this.heap[t];this.heap[t]=this.heap[n],this.heap[n]=r}swim(t){let n=t,r=Math.floor(n/2);for(;n>1&&this.greater(r,n);)this.swap(r,n),n=r,r=Math.floor(n/2)}sink(t){let n=t,r=n*2;for(;r<=this.n&&(rl.weight));for(s.push({id:t,weight:0});s.size()>0;){const{id:l,weight:u}=s.pop();if(!o.has(l)){const f=e(l);o.add(l),f.forEach((p,m)=>{const g=u+p,y=r.get(m),x=i.get(m);(x===void 0||x>g&&(x/g>1.005||y!==void 0&&yMath.min(Vr(i),o),Number.MAX_VALUE);return Bp(n/t/r)+2}function IT(e,t,n,r){const o=t-(e.length-1)*n-2*r*e.length,i=e.reduce((s,l)=>s+Vr(l),0);return o/i}function RH(e,t,n,r,o,i,s){const l=e.slice(t,n),u=IT(l,r,i,s);return u>0?(u-o)**2*l.length:void 0}function kH({photos:e,layoutOptions:t,targetRowHeight:n,limitNodeSearch:r,rowConstraints:o}){return i=>{var s,l;const{containerWidth:u,spacing:f,padding:p}=t,m=new Map;m.set(i,0);const g=(s=o==null?void 0:o.minPhotos)!=null?s:1,y=Math.min(r,(l=o==null?void 0:o.maxPhotos)!=null?l:1/0);for(let x=i+g;xy);x+=1){const S=RH(e,i,x,u,n,f,p);if(S===void 0)break;m.set(x,S)}return m}}function TH({photos:e,layoutOptions:t}){const{spacing:n,padding:r,containerWidth:o,targetRowHeight:i,rowConstraints:s}=t,l=$H({photos:e,containerWidth:o,targetRowHeight:i}),u=kH({photos:e,layoutOptions:t,targetRowHeight:i,limitNodeSearch:l,rowConstraints:s}),f=CH(u,0,e.length);if(f===void 0)return;const p=[];for(let m=1;m({photo:x,index:S})).slice(f[m-1],f[m]),y=IT(g.map(({photo:x})=>x),o,n,r);p.push(g.map(({photo:x,index:S},E)=>({photo:x,layout:{height:y,width:y*Vr(x),index:S,photoIndex:E,photosCount:g.length}})))}return p}function tg(...e){return[...e].filter(t=>!!t).join(" ")}function LT(e,{width:t,photosCount:n},{spacing:r,padding:o,containerWidth:i}){const s=r*(n-1)+2*o*n;return`calc((${e} - ${s}px) / ${Bp((i-s)/t,5)})`}function PH(e,t){return t.layout!=="rows"?`calc(100% - ${2*t.padding}px)`:LT("100%",e,t)}function c2(e,t,n){var r,o;return LT((o=(r=e.match(/calc\((.*)\)/))==null?void 0:r[1])!=null?o:e,t,n)}function AH(e,t,n){let r,o;const i=e.srcSet||e.images;return i&&i.length>0&&(r=i.concat(i.find(({width:s})=>s===e.width)?[]:[{src:e.src,width:e.width,height:e.height}]).sort((s,l)=>s.width-l.width).map(s=>`${s.src} ${s.width}w`).join(", ")),n.sizes?o=(n.sizes.sizes||[]).map(({viewport:s,size:l})=>`${s} ${c2(l,t,n)}`).concat(c2(n.sizes.size,t,n)).join(", "):r&&(o=`${Math.ceil(t.width/n.containerWidth*100)}vw`),{srcSet:r,sizes:o}}function Ix(e){var t,n;const{photo:r,layout:o,layoutOptions:i,imageProps:{style:s,className:l,...u}={},renderPhoto:f}=e,{onClick:p}=i,m={display:"block",boxSizing:"content-box",width:PH(o,i),height:"auto",aspectRatio:`${r.width} / ${r.height}`,...i.padding?{padding:`${i.padding}px`}:null,...(i.layout==="columns"||i.layout==="masonry")&&o.photoIndex{p({event:E,photo:r,index:o.index})}:void 0,y={src:r.src,alt:(t=r.alt)!=null?t:"",title:r.title,onClick:g,style:m,className:tg("react-photo-album--photo",l),loading:"lazy",decoding:"async",...AH(r,o,i),...u},x=E=>{const{src:_,alt:b,srcSet:C,sizes:R,style:P,...O}=y;return d.createElement("img",{alt:b,...C?{srcSet:C,sizes:R}:null,src:_,style:E!=null&&E.wrapped?{display:"block",width:"100%",height:"100%"}:P,...O})},S=(({display:E,boxSizing:_,width:b,aspectRatio:C,padding:R,marginBottom:P,cursor:O})=>({display:E,boxSizing:_,width:b,aspectRatio:C,padding:R,marginBottom:P,cursor:O}))(m);return d.createElement(d.Fragment,null,(n=f==null?void 0:f({photo:r,layout:o,layoutOptions:i,imageProps:y,renderDefaultPhoto:x,wrapperStyle:S}))!=null?n:x())}function MH({rowContainerProps:e,children:t}){return d.createElement("div",{...e},t)}function OH(e){const{layoutOptions:t,rowIndex:n,rowsCount:r,renderRowContainer:o,rowContainerProps:{style:i,className:s,...l}={},children:u}=e,f={className:tg("react-photo-album--row",s),style:{display:"flex",flexDirection:"row",flexWrap:"nowrap",alignItems:"flex-start",justifyContent:"space-between",...nd.createElement(OH,{key:`row-${f}`,layoutOptions:n,rowIndex:f,rowsCount:l.length,renderRowContainer:o,rowContainerProps:s},u.map(({photo:p,layout:m})=>d.createElement(Ix,{key:p.key||p.src,photo:p,layout:m,layoutOptions:n,renderPhoto:r,imageProps:i}))))):null}function DH(e,t,n,r){const o=new Map,i=new Set;i.add(n);for(let s=0;s{const f=s>0?o.get(u)[s].weight:0;e(u).forEach(({neighbor:p,weight:m})=>{let g=o.get(p);g||(g=[],o.set(p,g));const y=f+m,x=g[s+1];(!x||x.weight>y&&(x.weight/y>1.0001||u0;i-=1)o=e.get(o)[i].node,r.push(o);return r.reverse()}function LH(e,t,n,r){return IH(DH(e,t,n,r),t,r)}function FH({photos:e,spacing:t,padding:n,targetColumnWidth:r,targetColumnHeight:o}){return i=>{const s=[],l=o*1.5;let u=r/Vr(e[i])+2*n;for(let f=i+1;fl||f===e.length));f+=1)u+=r/Vr(e[f])+t+2*n;return s}}function u2({path:e,photos:t,containerWidth:n,columnsGaps:r,columnsRatios:o,spacing:i,padding:s}){const l=[],u=o.reduce((f,p)=>f+p,0);for(let f=0;f({photo:y,index:x})).slice(e[f],e[f+1]),m=o.reduce((y,x,S)=>y+(r[f]-r[S])*x,0),g=(n-(e.length-2)*i-2*(e.length-1)*s-m)*o[f]/u;l.push(p.map(({photo:y,index:x},S)=>({photo:y,layout:{width:g,height:g/Vr(y),index:x,photoIndex:S,photosCount:p.length}})))}return l}function jH({photos:e,layoutOptions:t,targetColumnWidth:n}){const{columns:r,spacing:o,padding:i,containerWidth:s}=t,l=[],u=[];if(e.length<=r){const y=e.length>0?e.reduce((S,E)=>S+Vr(E),0)/e.length:1;for(let S=0;SMath.min(E,e.length)),photos:e,columnsRatios:u,columnsGaps:l,containerWidth:s,spacing:o,padding:i});return{columnsGaps:l,columnsRatios:u,columnsModel:x}}const f=(e.reduce((y,x)=>y+n/Vr(x),0)+o*(e.length-r)+2*i*e.length)/r,p=FH({photos:e,targetColumnWidth:n,targetColumnHeight:f,spacing:o,padding:i}),m=LH(p,r,0,e.length);for(let y=0;yS+1/Vr(E),0)}const g=u2({path:m,photos:e,columnsRatios:u,columnsGaps:l,containerWidth:s,spacing:o,padding:i});return{columnsGaps:l,columnsRatios:u,columnsModel:g}}function FT(e){const{photos:t,layoutOptions:n}=e,{columns:r,spacing:o,padding:i,containerWidth:s}=n,l=(s-o*(r-1)-2*i*r)/r,{columnsGaps:u,columnsRatios:f,columnsModel:p}=jH({photos:t,layoutOptions:n,targetColumnWidth:l});return p.findIndex(m=>m.findIndex(({layout:{width:g,height:y}})=>g<0||y<0)>=0)>=0?r>1?FT({photos:t,layoutOptions:{...n,columns:r-1}}):void 0:{columnsModel:p,columnsGaps:u,columnsRatios:f}}function zH({photos:e,layoutOptions:t}){return FT({photos:e,layoutOptions:t})}function BH({columnContainerProps:e,children:t}){return d.createElement("div",{...e},t)}function UH(e){const{layoutOptions:t,columnIndex:n,columnsCount:r,columnsGaps:o,columnsRatios:i}=e,{layout:s,spacing:l,padding:u}=t;if(s==="masonry"||!o||!i)return`calc((100% - ${l*(r-1)}px) / ${r})`;const f=i.reduce((m,g)=>m+g,0),p=i.reduce((m,g,y)=>m+(o[n]-o[y])*g,0);return`calc((100% - ${Bp((r-1)*l+2*r*u+p,3)}px) * ${Bp(i[n]/f,5)} + ${2*u}px)`}function jT(e){const{layoutOptions:t,renderColumnContainer:n,children:r,columnContainerProps:{style:o,className:i,...s}={},...l}=e,u={className:tg("react-photo-album--column",i),style:{display:"flex",flexDirection:"column",flexWrap:"nowrap",alignItems:"flex-start",width:UH(e),justifyContent:t.layout==="columns"?"space-between":"flex-start",...o},...s};return d.createElement(d.Fragment,null,(n??BH)({layoutOptions:t,columnContainerProps:u,children:r,...l}))}function VH(e){const{photos:t,layoutOptions:n,renderPhoto:r,renderColumnContainer:o,componentsProps:{imageProps:i,columnContainerProps:s}}=e,l=zH({photos:t,layoutOptions:n});if(!l)return null;const{columnsModel:u,columnsRatios:f,columnsGaps:p}=l;return d.createElement(d.Fragment,null,u.map((m,g)=>d.createElement(jT,{key:`column-${g}`,layoutOptions:n,columnIndex:g,columnsCount:u.length,columnsGaps:p,columnsRatios:f,renderColumnContainer:o,columnContainerProps:s},m.map(({photo:y,layout:x})=>d.createElement(Ix,{key:y.key||y.src,photo:y,layout:x,layoutOptions:n,renderPhoto:r,imageProps:i})))))}function zT(e){const{photos:t,layoutOptions:n}=e,{columns:r,spacing:o,padding:i,containerWidth:s}=n,l=(s-o*(r-1)-2*i*r)/r;if(l<=0)return r>1?zT({...e,layoutOptions:{...n,columns:r-1}}):void 0;const u=[];for(let p=0;p{const y=u.reduce((x,S,E)=>S[])).map(p=>p.map(({photo:m,index:g},y)=>({photo:m,layout:{width:l,height:l/Vr(m),index:g,photoIndex:y,photosCount:p.length}})))}function WH(e){const{photos:t,layoutOptions:n,renderPhoto:r,renderColumnContainer:o,componentsProps:{imageProps:i,columnContainerProps:s}}=e,l=zT({photos:t,layoutOptions:n});return l?d.createElement(d.Fragment,null,l.map((u,f)=>d.createElement(jT,{key:`masonry-column-${f}`,layoutOptions:n,columnsCount:l.length,columnIndex:f,renderColumnContainer:o,columnContainerProps:s},u.map(({photo:p,layout:m})=>d.createElement(Ix,{key:p.key||p.src,photo:p,layout:m,layoutOptions:n,renderPhoto:r,imageProps:i}))))):null}function HH({containerProps:e,children:t,containerRef:n}){return d.createElement("div",{ref:n,...e},t)}function KH(e){const{layout:t,renderContainer:n,children:r,containerRef:o,containerProps:{style:i,className:s,...l}={}}=e,u={className:tg("react-photo-album",`react-photo-album--${t}`,s),style:{display:"flex",flexWrap:"nowrap",justifyContent:"space-between",flexDirection:t==="rows"?"column":"row",...i},...l};return d.createElement(d.Fragment,null,(n??HH)({containerProps:u,containerRef:o,layout:t,children:r}))}function GH(e){const t=d.useRef(e);return(!e||!t.current||e.join()!==t.current.join())&&(t.current=e),t.current}function YH(e,{newContainerWidth:t,newScrollbarWidth:n}){const{containerWidth:r,scrollbarWidth:o}=e;return r!==void 0&&o!==void 0&&t!==void 0&&n!==void 0&&t>r&&t-r<=20&&n0){const r=[...t.filter(i=>i>0)].sort((i,s)=>s-i);r.push(Math.floor(r[r.length-1]/2));const o=n;n=r.find((i,s)=>i<=o||s===r.length-1)}return n}function ZH(e,t){const[{containerWidth:n},r]=d.useReducer(YH,{containerWidth:t}),o=d.useRef(null),i=d.useRef();return{containerRef:d.useCallback(l=>{var u;(u=i.current)==null||u.disconnect(),i.current=void 0,o.current=l;const f=()=>r({newContainerWidth:XH(o.current,e),newScrollbarWidth:window.innerWidth-document.documentElement.clientWidth});f(),l&&typeof ResizeObserver<"u"&&(i.current=new ResizeObserver(f),i.current.observe(l))},[e]),containerWidth:n}}const qH=Object.freeze([1200,600,300,0]);function Lx(e,t){return typeof e=="function"?e(t):e}function BT(e,t){return typeof e<"u"?Lx(e,t):void 0}function QH(e,t){const n=qH.findIndex(r=>r<=t);return Lx(e[n>=0?n:0],t)}function yh(e,t,n,r=0){const o=BT(e,t);return Math.round(Math.max(o===void 0?QH(n,t):o,r))}function JH({layout:e,onClick:t,containerWidth:n,targetRowHeight:r,rowConstraints:o,columns:i,spacing:s,padding:l,sizes:u}){return{layout:e,onClick:t,containerWidth:n,columns:yh(i,n,[5,4,3,2],1),spacing:yh(s,n,[20,15,10,5]),padding:yh(l,n,[0,0,0,0,0]),targetRowHeight:yh(r,n,[f=>f/5,f=>f/4,f=>f/3,f=>f/2]),rowConstraints:BT(o,n),sizes:u}}function eK(e,t,n){const{photos:r,componentsProps:o}=e,i=Lx(o,t)||{};if(n){const{layout:s,spacing:l,padding:u,rowConstraints:f}=n;if(s==="rows"){const{singleRowMaxHeight:p}=f||{};if(p){const m=Math.floor(r.reduce((g,{width:y,height:x})=>g+y/x*p-2*u,u*r.length*2+l*(r.length-1)));m>0&&(i.containerProps=i.containerProps||{},i.containerProps.style={maxWidth:m,...i.containerProps.style})}}}return i}function tK(e,t,n){const{photos:r,layout:o,renderPhoto:i,renderRowContainer:s,renderColumnContainer:l}=e,u={photos:r,renderPhoto:i,componentsProps:t};return o==="rows"?d.createElement(NH,{layoutOptions:n,renderRowContainer:s,...u}):o==="columns"?d.createElement(VH,{layoutOptions:n,renderColumnContainer:l,...u}):d.createElement(WH,{layoutOptions:n,renderColumnContainer:l,...u})}function nK(e){const{photos:t,layout:n,renderContainer:r,defaultContainerWidth:o,breakpoints:i}=e,{containerRef:s,containerWidth:l}=ZH(GH(i),o);if(!n||!["rows","columns","masonry"].includes(n)||!Array.isArray(t))return null;const u=l?JH({containerWidth:l,...e}):void 0,f=eK(e,l,u);return d.createElement(KH,{layout:n,containerRef:s,renderContainer:r,containerProps:f.containerProps},u&&tK(e,f,u))}function rK({title:e,titleId:t,...n},r){return d.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true",ref:r,"aria-labelledby":t},n),e?d.createElement("title",{id:t},e):null,d.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3 4.5h14.25M3 9h9.75M3 13.5h9.75m4.5-4.5v12m0 0l-3.75-3.75M17.25 21L21 17.25"}))}const oK=d.forwardRef(rK),iK=oK;function sK({title:e,titleId:t,...n},r){return d.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true",ref:r,"aria-labelledby":t},n),e?d.createElement("title",{id:t},e):null,d.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3 4.5h14.25M3 9h9.75M3 13.5h5.25m5.25-.75L17.25 9m0 0L21 12.75M17.25 9v12"}))}const aK=d.forwardRef(sK),lK=aK;function cK({title:e,titleId:t,...n},r){return d.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true",ref:r,"aria-labelledby":t},n),e?d.createElement("title",{id:t},e):null,d.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15.042 21.672L13.684 16.6m0 0l-2.51 2.225.569-9.47 5.227 7.917-3.286-.672zM12 2.25V4.5m5.834.166l-1.591 1.591M20.25 10.5H18M7.757 14.743l-1.59 1.59M6 10.5H3.75m4.007-4.243l-1.59-1.59"}))}const uK=d.forwardRef(cK),dK=uK;function ki(e){return Array.isArray?Array.isArray(e):WT(e)==="[object Array]"}const fK=1/0;function hK(e){if(typeof e=="string")return e;let t=e+"";return t=="0"&&1/e==-fK?"-0":t}function pK(e){return e==null?"":hK(e)}function Bo(e){return typeof e=="string"}function UT(e){return typeof e=="number"}function mK(e){return e===!0||e===!1||gK(e)&&WT(e)=="[object Boolean]"}function VT(e){return typeof e=="object"}function gK(e){return VT(e)&&e!==null}function pr(e){return e!=null}function M0(e){return!e.trim().length}function WT(e){return e==null?e===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}const vK="Incorrect 'index' type",yK=e=>`Invalid value for key ${e}`,wK=e=>`Pattern length exceeds max of ${e}.`,xK=e=>`Missing ${e} property in key`,bK=e=>`Property 'weight' in key '${e}' must be a positive integer`,d2=Object.prototype.hasOwnProperty;class SK{constructor(t){this._keys=[],this._keyMap={};let n=0;t.forEach(r=>{let o=HT(r);this._keys.push(o),this._keyMap[o.id]=o,n+=o.weight}),this._keys.forEach(r=>{r.weight/=n})}get(t){return this._keyMap[t]}keys(){return this._keys}toJSON(){return JSON.stringify(this._keys)}}function HT(e){let t=null,n=null,r=null,o=1,i=null;if(Bo(e)||ki(e))r=e,t=f2(e),n=g1(e);else{if(!d2.call(e,"name"))throw new Error(xK("name"));const s=e.name;if(r=s,d2.call(e,"weight")&&(o=e.weight,o<=0))throw new Error(bK(s));t=f2(s),n=g1(s),i=e.getFn}return{path:t,id:n,weight:o,src:r,getFn:i}}function f2(e){return ki(e)?e:e.split(".")}function g1(e){return ki(e)?e.join("."):e}function _K(e,t){let n=[],r=!1;const o=(i,s,l)=>{if(pr(i))if(!s[l])n.push(i);else{let u=s[l];const f=i[u];if(!pr(f))return;if(l===s.length-1&&(Bo(f)||UT(f)||mK(f)))n.push(pK(f));else if(ki(f)){r=!0;for(let p=0,m=f.length;pe.score===t.score?e.idx{this._keysMap[n.id]=r})}create(){this.isCreated||!this.docs.length||(this.isCreated=!0,Bo(this.docs[0])?this.docs.forEach((t,n)=>{this._addString(t,n)}):this.docs.forEach((t,n)=>{this._addObject(t,n)}),this.norm.clear())}add(t){const n=this.size();Bo(t)?this._addString(t,n):this._addObject(t,n)}removeAt(t){this.records.splice(t,1);for(let n=t,r=this.size();n{let s=o.getFn?o.getFn(t):this.getFn(t,o.path);if(pr(s)){if(ki(s)){let l=[];const u=[{nestedArrIndex:-1,value:s}];for(;u.length;){const{nestedArrIndex:f,value:p}=u.pop();if(pr(p))if(Bo(p)&&!M0(p)){let m={v:p,i:f,n:this.norm.get(p)};l.push(m)}else ki(p)&&p.forEach((m,g)=>{u.push({nestedArrIndex:g,value:m})})}r.$[i]=l}else if(Bo(s)&&!M0(s)){let l={v:s,n:this.norm.get(s)};r.$[i]=l}}}),this.records.push(r)}toJSON(){return{keys:this.keys,records:this.records}}}function KT(e,t,{getFn:n=He.getFn,fieldNormWeight:r=He.fieldNormWeight}={}){const o=new Fx({getFn:n,fieldNormWeight:r});return o.setKeys(e.map(HT)),o.setSources(t),o.create(),o}function PK(e,{getFn:t=He.getFn,fieldNormWeight:n=He.fieldNormWeight}={}){const{keys:r,records:o}=e,i=new Fx({getFn:t,fieldNormWeight:n});return i.setKeys(r),i.setIndexRecords(o),i}function wh(e,{errors:t=0,currentLocation:n=0,expectedLocation:r=0,distance:o=He.distance,ignoreLocation:i=He.ignoreLocation}={}){const s=t/e.length;if(i)return s;const l=Math.abs(r-n);return o?s+l/o:l?1:s}function AK(e=[],t=He.minMatchCharLength){let n=[],r=-1,o=-1,i=0;for(let s=e.length;i=t&&n.push([r,o]),r=-1)}return e[i-1]&&i-r>=t&&n.push([r,i-1]),n}const la=32;function MK(e,t,n,{location:r=He.location,distance:o=He.distance,threshold:i=He.threshold,findAllMatches:s=He.findAllMatches,minMatchCharLength:l=He.minMatchCharLength,includeMatches:u=He.includeMatches,ignoreLocation:f=He.ignoreLocation}={}){if(t.length>la)throw new Error(wK(la));const p=t.length,m=e.length,g=Math.max(0,Math.min(r,m));let y=i,x=g;const S=l>1||u,E=S?Array(m):[];let _;for(;(_=e.indexOf(t,x))>-1;){let A=wh(t,{currentLocation:_,expectedLocation:g,distance:o,ignoreLocation:f});if(y=Math.min(A,y),x=_+p,S){let D=0;for(;D=V;U-=1){let ne=U-1,M=n[e.charAt(ne)];if(S&&(E[ne]=+!!M),G[U]=(G[U+1]<<1|1)&M,A&&(G[U]|=(b[U+1]|b[U])<<1|1|b[U+1]),G[U]&P&&(C=wh(t,{errors:A,currentLocation:ne,expectedLocation:g,distance:o,ignoreLocation:f}),C<=y)){if(y=C,x=ne,x<=g)break;V=Math.max(1,2*g-x)}}if(wh(t,{errors:A+1,currentLocation:g,expectedLocation:g,distance:o,ignoreLocation:f})>y)break;b=G}const O={isMatch:x>=0,score:Math.max(.001,C)};if(S){const A=AK(E,l);A.length?u&&(O.indices=A):O.isMatch=!1}return O}function OK(e){let t={};for(let n=0,r=e.length;n{this.chunks.push({pattern:g,alphabet:OK(g),startIndex:y})},m=this.pattern.length;if(m>la){let g=0;const y=m%la,x=m-y;for(;g{const{isMatch:_,score:b,indices:C}=MK(t,x,S,{location:o+E,distance:i,threshold:s,findAllMatches:l,minMatchCharLength:u,includeMatches:r,ignoreLocation:f});_&&(g=!0),m+=b,_&&C&&(p=[...p,...C])});let y={isMatch:g,score:g?m/this.chunks.length:1};return g&&r&&(y.indices=p),y}}class js{constructor(t){this.pattern=t}static isMultiMatch(t){return h2(t,this.multiRegex)}static isSingleMatch(t){return h2(t,this.singleRegex)}search(){}}function h2(e,t){const n=e.match(t);return n?n[1]:null}class NK extends js{constructor(t){super(t)}static get type(){return"exact"}static get multiRegex(){return/^="(.*)"$/}static get singleRegex(){return/^=(.*)$/}search(t){const n=t===this.pattern;return{isMatch:n,score:n?0:1,indices:[0,this.pattern.length-1]}}}class DK extends js{constructor(t){super(t)}static get type(){return"inverse-exact"}static get multiRegex(){return/^!"(.*)"$/}static get singleRegex(){return/^!(.*)$/}search(t){const r=t.indexOf(this.pattern)===-1;return{isMatch:r,score:r?0:1,indices:[0,t.length-1]}}}class IK extends js{constructor(t){super(t)}static get type(){return"prefix-exact"}static get multiRegex(){return/^\^"(.*)"$/}static get singleRegex(){return/^\^(.*)$/}search(t){const n=t.startsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[0,this.pattern.length-1]}}}class LK extends js{constructor(t){super(t)}static get type(){return"inverse-prefix-exact"}static get multiRegex(){return/^!\^"(.*)"$/}static get singleRegex(){return/^!\^(.*)$/}search(t){const n=!t.startsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[0,t.length-1]}}}class FK extends js{constructor(t){super(t)}static get type(){return"suffix-exact"}static get multiRegex(){return/^"(.*)"\$$/}static get singleRegex(){return/^(.*)\$$/}search(t){const n=t.endsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[t.length-this.pattern.length,t.length-1]}}}class jK extends js{constructor(t){super(t)}static get type(){return"inverse-suffix-exact"}static get multiRegex(){return/^!"(.*)"\$$/}static get singleRegex(){return/^!(.*)\$$/}search(t){const n=!t.endsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[0,t.length-1]}}}class YT extends js{constructor(t,{location:n=He.location,threshold:r=He.threshold,distance:o=He.distance,includeMatches:i=He.includeMatches,findAllMatches:s=He.findAllMatches,minMatchCharLength:l=He.minMatchCharLength,isCaseSensitive:u=He.isCaseSensitive,ignoreLocation:f=He.ignoreLocation}={}){super(t),this._bitapSearch=new GT(t,{location:n,threshold:r,distance:o,includeMatches:i,findAllMatches:s,minMatchCharLength:l,isCaseSensitive:u,ignoreLocation:f})}static get type(){return"fuzzy"}static get multiRegex(){return/^"(.*)"$/}static get singleRegex(){return/^(.*)$/}search(t){return this._bitapSearch.searchIn(t)}}class XT extends js{constructor(t){super(t)}static get type(){return"include"}static get multiRegex(){return/^'"(.*)"$/}static get singleRegex(){return/^'(.*)$/}search(t){let n=0,r;const o=[],i=this.pattern.length;for(;(r=t.indexOf(this.pattern,n))>-1;)n=r+i,o.push([r,n-1]);const s=!!o.length;return{isMatch:s,score:s?0:1,indices:o}}}const v1=[NK,XT,IK,LK,jK,FK,DK,YT],p2=v1.length,zK=/ +(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/,BK="|";function UK(e,t={}){return e.split(BK).map(n=>{let r=n.trim().split(zK).filter(i=>i&&!!i.trim()),o=[];for(let i=0,s=r.length;i!!(e[Up.AND]||e[Up.OR]),KK=e=>!!e[x1.PATH],GK=e=>!ki(e)&&VT(e)&&!b1(e),m2=e=>({[Up.AND]:Object.keys(e).map(t=>({[t]:e[t]}))});function ZT(e,t,{auto:n=!0}={}){const r=o=>{let i=Object.keys(o);const s=KK(o);if(!s&&i.length>1&&!b1(o))return r(m2(o));if(GK(o)){const u=s?o[x1.PATH]:i[0],f=s?o[x1.PATTERN]:o[u];if(!Bo(f))throw new Error(yK(u));const p={keyId:g1(u),pattern:f};return n&&(p.searcher=w1(f,t)),p}let l={children:[],operator:i[0]};return i.forEach(u=>{const f=o[u];ki(f)&&f.forEach(p=>{l.children.push(r(p))})}),l};return b1(e)||(e=m2(e)),r(e)}function YK(e,{ignoreFieldNorm:t=He.ignoreFieldNorm}){e.forEach(n=>{let r=1;n.matches.forEach(({key:o,norm:i,score:s})=>{const l=o?o.weight:null;r*=Math.pow(s===0&&l?Number.EPSILON:s,(l||1)*(t?1:i))}),n.score=r})}function XK(e,t){const n=e.matches;t.matches=[],pr(n)&&n.forEach(r=>{if(!pr(r.indices)||!r.indices.length)return;const{indices:o,value:i}=r;let s={indices:o,value:i};r.key&&(s.key=r.key.src),r.idx>-1&&(s.refIndex=r.idx),t.matches.push(s)})}function ZK(e,t){t.score=e.score}function qK(e,t,{includeMatches:n=He.includeMatches,includeScore:r=He.includeScore}={}){const o=[];return n&&o.push(XK),r&&o.push(ZK),e.map(i=>{const{idx:s}=i,l={item:t[s],refIndex:s};return o.length&&o.forEach(u=>{u(i,l)}),l})}class kc{constructor(t,n={},r){this.options={...He,...n},this.options.useExtendedSearch,this._keyStore=new SK(this.options.keys),this.setCollection(t,r)}setCollection(t,n){if(this._docs=t,n&&!(n instanceof Fx))throw new Error(vK);this._myIndex=n||KT(this.options.keys,this._docs,{getFn:this.options.getFn,fieldNormWeight:this.options.fieldNormWeight})}add(t){pr(t)&&(this._docs.push(t),this._myIndex.add(t))}remove(t=()=>!1){const n=[];for(let r=0,o=this._docs.length;r-1&&(u=u.slice(0,n)),qK(u,this._docs,{includeMatches:r,includeScore:o})}_searchStringList(t){const n=w1(t,this.options),{records:r}=this._myIndex,o=[];return r.forEach(({v:i,i:s,n:l})=>{if(!pr(i))return;const{isMatch:u,score:f,indices:p}=n.searchIn(i);u&&o.push({item:i,idx:s,matches:[{score:f,value:i,norm:l,indices:p}]})}),o}_searchLogical(t){const n=ZT(t,this.options),r=(l,u,f)=>{if(!l.children){const{keyId:m,searcher:g}=l,y=this._findMatches({key:this._keyStore.get(m),value:this._myIndex.getValueForItemAtKeyId(u,m),searcher:g});return y&&y.length?[{idx:f,item:u,matches:y}]:[]}const p=[];for(let m=0,g=l.children.length;m{if(pr(l)){let f=r(n,l,u);f.length&&(i[u]||(i[u]={idx:u,item:l,matches:[]},s.push(i[u])),f.forEach(({matches:p})=>{i[u].matches.push(...p)}))}}),s}_searchObjectList(t){const n=w1(t,this.options),{keys:r,records:o}=this._myIndex,i=[];return o.forEach(({$:s,i:l})=>{if(!pr(s))return;let u=[];r.forEach((f,p)=>{u.push(...this._findMatches({key:f,value:s[p],searcher:n}))}),u.length&&i.push({idx:l,item:s,matches:u})}),i}_findMatches({key:t,value:n,searcher:r}){if(!pr(n))return[];let o=[];if(ki(n))n.forEach(({v:i,i:s,n:l})=>{if(!pr(i))return;const{isMatch:u,score:f,indices:p}=r.searchIn(i);u&&o.push({score:f,key:t,value:i,idx:s,norm:l,indices:p})});else{const{v:i,n:s}=n,{isMatch:l,score:u,indices:f}=r.searchIn(i);l&&o.push({score:u,key:t,value:i,norm:s,indices:f})}return o}}kc.version="7.0.0";kc.createIndex=KT;kc.parseIndex=PK;kc.config=He;kc.parseQuery=ZT;HK(WK);function Kd(e){const t=e+"CollectionProvider",[n,r]=Mn(t),[o,i]=n(t,{collectionRef:{current:null},itemMap:new Map}),s=y=>{const{scope:x,children:S}=y,E=je.useRef(null),_=je.useRef(new Map).current;return je.createElement(o,{scope:x,itemMap:_,collectionRef:E},S)},l=e+"CollectionSlot",u=je.forwardRef((y,x)=>{const{scope:S,children:E}=y,_=i(l,S),b=Ue(x,_.collectionRef);return je.createElement(Zo,{ref:b},E)}),f=e+"CollectionItemSlot",p="data-radix-collection-item",m=je.forwardRef((y,x)=>{const{scope:S,children:E,..._}=y,b=je.useRef(null),C=Ue(x,b),R=i(f,S);return je.useEffect(()=>(R.itemMap.set(b,{ref:b,..._}),()=>void R.itemMap.delete(b))),je.createElement(Zo,{[p]:"",ref:C},E)});function g(y){const x=i(e+"CollectionConsumer",y);return je.useCallback(()=>{const E=x.collectionRef.current;if(!E)return[];const _=Array.from(E.querySelectorAll(`[${p}]`));return Array.from(x.itemMap.values()).sort((R,P)=>_.indexOf(R.ref.current)-_.indexOf(P.ref.current))},[x.collectionRef,x.itemMap])}return[{Provider:s,Slot:u,ItemSlot:m},g,r]}const QK=d.createContext(void 0);function Tc(e){const t=d.useContext(QK);return e||t||"ltr"}const O0="rovingFocusGroup.onEntryFocus",JK={bubbles:!1,cancelable:!0},jx="RovingFocusGroup",[S1,qT,eG]=Kd(jx),[tG,ng]=Mn(jx,[eG]),[nG,rG]=tG(jx),oG=d.forwardRef((e,t)=>d.createElement(S1.Provider,{scope:e.__scopeRovingFocusGroup},d.createElement(S1.Slot,{scope:e.__scopeRovingFocusGroup},d.createElement(iG,Y({},e,{ref:t}))))),iG=d.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:o=!1,dir:i,currentTabStopId:s,defaultCurrentTabStopId:l,onCurrentTabStopIdChange:u,onEntryFocus:f,...p}=e,m=d.useRef(null),g=Ue(t,m),y=Tc(i),[x=null,S]=Zr({prop:s,defaultProp:l,onChange:u}),[E,_]=d.useState(!1),b=Ft(f),C=qT(n),R=d.useRef(!1),[P,O]=d.useState(0);return d.useEffect(()=>{const A=m.current;if(A)return A.addEventListener(O0,b),()=>A.removeEventListener(O0,b)},[b]),d.createElement(nG,{scope:n,orientation:r,dir:y,loop:o,currentTabStopId:x,onItemFocus:d.useCallback(A=>S(A),[S]),onItemShiftTab:d.useCallback(()=>_(!0),[]),onFocusableItemAdd:d.useCallback(()=>O(A=>A+1),[]),onFocusableItemRemove:d.useCallback(()=>O(A=>A-1),[])},d.createElement(Ae.div,Y({tabIndex:E||P===0?-1:0,"data-orientation":r},p,{ref:g,style:{outline:"none",...e.style},onMouseDown:ue(e.onMouseDown,()=>{R.current=!0}),onFocus:ue(e.onFocus,A=>{const D=!R.current;if(A.target===A.currentTarget&&D&&!E){const B=new CustomEvent(O0,JK);if(A.currentTarget.dispatchEvent(B),!B.defaultPrevented){const V=C().filter(ne=>ne.focusable),J=V.find(ne=>ne.active),G=V.find(ne=>ne.id===x),U=[J,G,...V].filter(Boolean).map(ne=>ne.ref.current);QT(U)}}R.current=!1}),onBlur:ue(e.onBlur,()=>_(!1))})))}),sG="RovingFocusGroupItem",aG=d.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:o=!1,tabStopId:i,...s}=e,l=nr(),u=i||l,f=rG(sG,n),p=f.currentTabStopId===u,m=qT(n),{onFocusableItemAdd:g,onFocusableItemRemove:y}=f;return d.useEffect(()=>{if(r)return g(),()=>y()},[r,g,y]),d.createElement(S1.ItemSlot,{scope:n,id:u,focusable:r,active:o},d.createElement(Ae.span,Y({tabIndex:p?0:-1,"data-orientation":f.orientation},s,{ref:t,onMouseDown:ue(e.onMouseDown,x=>{r?f.onItemFocus(u):x.preventDefault()}),onFocus:ue(e.onFocus,()=>f.onItemFocus(u)),onKeyDown:ue(e.onKeyDown,x=>{if(x.key==="Tab"&&x.shiftKey){f.onItemShiftTab();return}if(x.target!==x.currentTarget)return;const S=uG(x,f.orientation,f.dir);if(S!==void 0){x.preventDefault();let _=m().filter(b=>b.focusable).map(b=>b.ref.current);if(S==="last")_.reverse();else if(S==="prev"||S==="next"){S==="prev"&&_.reverse();const b=_.indexOf(x.currentTarget);_=f.loop?dG(_,b+1):_.slice(b+1)}setTimeout(()=>QT(_))}})})))}),lG={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function cG(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function uG(e,t,n){const r=cG(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return lG[r]}function QT(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function dG(e,t){return e.map((n,r)=>e[(t+r)%e.length])}const JT=oG,e3=aG,t3="Tabs",[fG,xte]=Mn(t3,[ng]),n3=ng(),[hG,zx]=fG(t3),pG=d.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,onValueChange:o,defaultValue:i,orientation:s="horizontal",dir:l,activationMode:u="automatic",...f}=e,p=Tc(l),[m,g]=Zr({prop:r,onChange:o,defaultProp:i});return d.createElement(hG,{scope:n,baseId:nr(),value:m,onValueChange:g,orientation:s,dir:p,activationMode:u},d.createElement(Ae.div,Y({dir:p,"data-orientation":s},f,{ref:t})))}),mG="TabsList",gG=d.forwardRef((e,t)=>{const{__scopeTabs:n,loop:r=!0,...o}=e,i=zx(mG,n),s=n3(n);return d.createElement(JT,Y({asChild:!0},s,{orientation:i.orientation,dir:i.dir,loop:r}),d.createElement(Ae.div,Y({role:"tablist","aria-orientation":i.orientation},o,{ref:t})))}),vG="TabsTrigger",yG=d.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,disabled:o=!1,...i}=e,s=zx(vG,n),l=n3(n),u=r3(s.baseId,r),f=o3(s.baseId,r),p=r===s.value;return d.createElement(e3,Y({asChild:!0},l,{focusable:!o,active:p}),d.createElement(Ae.button,Y({type:"button",role:"tab","aria-selected":p,"aria-controls":f,"data-state":p?"active":"inactive","data-disabled":o?"":void 0,disabled:o,id:u},i,{ref:t,onMouseDown:ue(e.onMouseDown,m=>{!o&&m.button===0&&m.ctrlKey===!1?s.onValueChange(r):m.preventDefault()}),onKeyDown:ue(e.onKeyDown,m=>{[" ","Enter"].includes(m.key)&&s.onValueChange(r)}),onFocus:ue(e.onFocus,()=>{const m=s.activationMode!=="manual";!p&&!o&&m&&s.onValueChange(r)})})))}),wG="TabsContent",xG=d.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,forceMount:o,children:i,...s}=e,l=zx(wG,n),u=r3(l.baseId,r),f=o3(l.baseId,r),p=r===l.value,m=d.useRef(p);return d.useEffect(()=>{const g=requestAnimationFrame(()=>m.current=!1);return()=>cancelAnimationFrame(g)},[]),d.createElement(Sn,{present:o||p},({present:g})=>d.createElement(Ae.div,Y({"data-state":p?"active":"inactive","data-orientation":l.orientation,role:"tabpanel","aria-labelledby":u,hidden:!g,id:f,tabIndex:0},s,{ref:t,style:{...e.style,animationDuration:m.current?"0s":void 0}}),g&&i))});function r3(e,t){return`${e}-trigger-${t}`}function o3(e,t){return`${e}-content-${t}`}const bG=pG,i3=gG,s3=yG,a3=xG,l3=bG,Bx=d.forwardRef(({className:e,...t},n)=>v.jsx(i3,{ref:n,className:_e("inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground",e),tabIndex:-1,...t}));Bx.displayName=i3.displayName;const pa=d.forwardRef(({className:e,...t},n)=>v.jsx(s3,{ref:n,className:_e("inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow",e),tabIndex:-1,...t}));pa.displayName=s3.displayName;const Su=d.forwardRef(({className:e,...t},n)=>v.jsx(a3,{ref:n,className:_e("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",e),tabIndex:-1,...t}));Su.displayName=a3.displayName;function fd(e,[t,n]){return Math.min(n,Math.max(t,e))}function Ux(e){const t=d.useRef({value:e,previous:e});return d.useMemo(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}const SG=[" ","Enter","ArrowUp","ArrowDown"],_G=[" ","Enter"],rg="Select",[og,ig,EG]=Kd(rg),[Pc,bte]=Mn(rg,[EG,Fs]),Vx=Fs(),[CG,Fa]=Pc(rg),[$G,RG]=Pc(rg),kG=e=>{const{__scopeSelect:t,children:n,open:r,defaultOpen:o,onOpenChange:i,value:s,defaultValue:l,onValueChange:u,dir:f,name:p,autoComplete:m,disabled:g,required:y}=e,x=Vx(t),[S,E]=d.useState(null),[_,b]=d.useState(null),[C,R]=d.useState(!1),P=Tc(f),[O=!1,A]=Zr({prop:r,defaultProp:o,onChange:i}),[D,B]=Zr({prop:s,defaultProp:l,onChange:u}),V=d.useRef(null),J=S?!!S.closest("form"):!0,[G,se]=d.useState(new Set),U=Array.from(G).map(ne=>ne.props.value).join(";");return d.createElement(Fd,x,d.createElement(CG,{required:y,scope:t,trigger:S,onTriggerChange:E,valueNode:_,onValueNodeChange:b,valueNodeHasChildren:C,onValueNodeHasChildrenChange:R,contentId:nr(),value:D,onValueChange:B,open:O,onOpenChange:A,dir:P,triggerPointerDownPosRef:V,disabled:g},d.createElement(og.Provider,{scope:t},d.createElement($G,{scope:e.__scopeSelect,onNativeOptionAdd:d.useCallback(ne=>{se(M=>new Set(M).add(ne))},[]),onNativeOptionRemove:d.useCallback(ne=>{se(M=>{const ee=new Set(M);return ee.delete(ne),ee})},[])},n)),J?d.createElement(h3,{key:U,"aria-hidden":!0,required:y,tabIndex:-1,name:p,autoComplete:m,value:D,onChange:ne=>B(ne.target.value),disabled:g},D===void 0?d.createElement("option",{value:""}):null,Array.from(G)):null))},TG="SelectTrigger",PG=d.forwardRef((e,t)=>{const{__scopeSelect:n,disabled:r=!1,...o}=e,i=Vx(n),s=Fa(TG,n),l=s.disabled||r,u=Ue(t,s.onTriggerChange),f=ig(n),[p,m,g]=p3(x=>{const S=f().filter(b=>!b.disabled),E=S.find(b=>b.value===s.value),_=m3(S,x,E);_!==void 0&&s.onValueChange(_.value)}),y=()=>{l||(s.onOpenChange(!0),g())};return d.createElement(Wm,Y({asChild:!0},i),d.createElement(Ae.button,Y({type:"button",role:"combobox","aria-controls":s.contentId,"aria-expanded":s.open,"aria-required":s.required,"aria-autocomplete":"none",dir:s.dir,"data-state":s.open?"open":"closed",disabled:l,"data-disabled":l?"":void 0,"data-placeholder":f3(s.value)?"":void 0},o,{ref:u,onClick:ue(o.onClick,x=>{x.currentTarget.focus()}),onPointerDown:ue(o.onPointerDown,x=>{const S=x.target;S.hasPointerCapture(x.pointerId)&&S.releasePointerCapture(x.pointerId),x.button===0&&x.ctrlKey===!1&&(y(),s.triggerPointerDownPosRef.current={x:Math.round(x.pageX),y:Math.round(x.pageY)},x.preventDefault())}),onKeyDown:ue(o.onKeyDown,x=>{const S=p.current!=="";!(x.ctrlKey||x.altKey||x.metaKey)&&x.key.length===1&&m(x.key),!(S&&x.key===" ")&&SG.includes(x.key)&&(y(),x.preventDefault())})})))}),AG="SelectValue",MG=d.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,children:i,placeholder:s="",...l}=e,u=Fa(AG,n),{onValueNodeHasChildrenChange:f}=u,p=i!==void 0,m=Ue(t,u.onValueNodeChange);return An(()=>{f(p)},[f,p]),d.createElement(Ae.span,Y({},l,{ref:m,style:{pointerEvents:"none"}}),f3(u.value)?d.createElement(d.Fragment,null,s):i)}),OG=d.forwardRef((e,t)=>{const{__scopeSelect:n,children:r,...o}=e;return d.createElement(Ae.span,Y({"aria-hidden":!0},o,{ref:t}),r||"▼")}),NG=e=>d.createElement(jd,Y({asChild:!0},e)),dc="SelectContent",DG=d.forwardRef((e,t)=>{const n=Fa(dc,e.__scopeSelect),[r,o]=d.useState();if(An(()=>{o(new DocumentFragment)},[]),!n.open){const i=r;return i?Is.createPortal(d.createElement(c3,{scope:e.__scopeSelect},d.createElement(og.Slot,{scope:e.__scopeSelect},d.createElement("div",null,e.children))),i):null}return d.createElement(IG,Y({},e,{ref:t}))}),hi=10,[c3,ja]=Pc(dc),IG=d.forwardRef((e,t)=>{const{__scopeSelect:n,position:r="item-aligned",onCloseAutoFocus:o,onEscapeKeyDown:i,onPointerDownOutside:s,side:l,sideOffset:u,align:f,alignOffset:p,arrowPadding:m,collisionBoundary:g,collisionPadding:y,sticky:x,hideWhenDetached:S,avoidCollisions:E,..._}=e,b=Fa(dc,n),[C,R]=d.useState(null),[P,O]=d.useState(null),A=Ue(t,fe=>R(fe)),[D,B]=d.useState(null),[V,J]=d.useState(null),G=ig(n),[se,U]=d.useState(!1),ne=d.useRef(!1);d.useEffect(()=>{if(C)return Jm(C)},[C]),Zm();const M=d.useCallback(fe=>{const[xe,...Re]=G().map(ze=>ze.ref.current),[Me]=Re.slice(-1),Oe=document.activeElement;for(const ze of fe)if(ze===Oe||(ze==null||ze.scrollIntoView({block:"nearest"}),ze===xe&&P&&(P.scrollTop=0),ze===Me&&P&&(P.scrollTop=P.scrollHeight),ze==null||ze.focus(),document.activeElement!==Oe))return},[G,P]),ee=d.useCallback(()=>M([D,C]),[M,D,C]);d.useEffect(()=>{se&&ee()},[se,ee]);const{onOpenChange:H,triggerPointerDownPosRef:X}=b;d.useEffect(()=>{if(C){let fe={x:0,y:0};const xe=Me=>{var Oe,ze,Mt,ct;fe={x:Math.abs(Math.round(Me.pageX)-((Oe=(ze=X.current)===null||ze===void 0?void 0:ze.x)!==null&&Oe!==void 0?Oe:0)),y:Math.abs(Math.round(Me.pageY)-((Mt=(ct=X.current)===null||ct===void 0?void 0:ct.y)!==null&&Mt!==void 0?Mt:0))}},Re=Me=>{fe.x<=10&&fe.y<=10?Me.preventDefault():C.contains(Me.target)||H(!1),document.removeEventListener("pointermove",xe),X.current=null};return X.current!==null&&(document.addEventListener("pointermove",xe),document.addEventListener("pointerup",Re,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",xe),document.removeEventListener("pointerup",Re,{capture:!0})}}},[C,H,X]),d.useEffect(()=>{const fe=()=>H(!1);return window.addEventListener("blur",fe),window.addEventListener("resize",fe),()=>{window.removeEventListener("blur",fe),window.removeEventListener("resize",fe)}},[H]);const[W,le]=p3(fe=>{const xe=G().filter(Oe=>!Oe.disabled),Re=xe.find(Oe=>Oe.ref.current===document.activeElement),Me=m3(xe,fe,Re);Me&&setTimeout(()=>Me.ref.current.focus())}),pe=d.useCallback((fe,xe,Re)=>{const Me=!ne.current&&!Re;(b.value!==void 0&&b.value===xe||Me)&&(B(fe),Me&&(ne.current=!0))},[b.value]),$e=d.useCallback(()=>C==null?void 0:C.focus(),[C]),Ve=d.useCallback((fe,xe,Re)=>{const Me=!ne.current&&!Re;(b.value!==void 0&&b.value===xe||Me)&&J(fe)},[b.value]),We=r==="popper"?g2:LG,Ne=We===g2?{side:l,sideOffset:u,align:f,alignOffset:p,arrowPadding:m,collisionBoundary:g,collisionPadding:y,sticky:x,hideWhenDetached:S,avoidCollisions:E}:{};return d.createElement(c3,{scope:n,content:C,viewport:P,onViewportChange:O,itemRefCallback:pe,selectedItem:D,onItemLeave:$e,itemTextRefCallback:Ve,focusSelectedItem:ee,selectedItemText:V,position:r,isPositioned:se,searchRef:W},d.createElement(Qm,{as:Zo,allowPinchZoom:!0},d.createElement(Xm,{asChild:!0,trapped:b.open,onMountAutoFocus:fe=>{fe.preventDefault()},onUnmountAutoFocus:ue(o,fe=>{var xe;(xe=b.trigger)===null||xe===void 0||xe.focus({preventScroll:!0}),fe.preventDefault()})},d.createElement(Ec,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:i,onPointerDownOutside:s,onFocusOutside:fe=>fe.preventDefault(),onDismiss:()=>b.onOpenChange(!1)},d.createElement(We,Y({role:"listbox",id:b.contentId,"data-state":b.open?"open":"closed",dir:b.dir,onContextMenu:fe=>fe.preventDefault()},_,Ne,{onPlaced:()=>U(!0),ref:A,style:{display:"flex",flexDirection:"column",outline:"none",..._.style},onKeyDown:ue(_.onKeyDown,fe=>{const xe=fe.ctrlKey||fe.altKey||fe.metaKey;if(fe.key==="Tab"&&fe.preventDefault(),!xe&&fe.key.length===1&&le(fe.key),["ArrowUp","ArrowDown","Home","End"].includes(fe.key)){let Me=G().filter(Oe=>!Oe.disabled).map(Oe=>Oe.ref.current);if(["ArrowUp","End"].includes(fe.key)&&(Me=Me.slice().reverse()),["ArrowUp","ArrowDown"].includes(fe.key)){const Oe=fe.target,ze=Me.indexOf(Oe);Me=Me.slice(ze+1)}setTimeout(()=>M(Me)),fe.preventDefault()}})}))))))}),LG=d.forwardRef((e,t)=>{const{__scopeSelect:n,onPlaced:r,...o}=e,i=Fa(dc,n),s=ja(dc,n),[l,u]=d.useState(null),[f,p]=d.useState(null),m=Ue(t,A=>p(A)),g=ig(n),y=d.useRef(!1),x=d.useRef(!0),{viewport:S,selectedItem:E,selectedItemText:_,focusSelectedItem:b}=s,C=d.useCallback(()=>{if(i.trigger&&i.valueNode&&l&&f&&S&&E&&_){const A=i.trigger.getBoundingClientRect(),D=f.getBoundingClientRect(),B=i.valueNode.getBoundingClientRect(),V=_.getBoundingClientRect();if(i.dir!=="rtl"){const Oe=V.left-D.left,ze=B.left-Oe,Mt=A.left-ze,ct=A.width+Mt,Kt=Math.max(ct,D.width),Er=window.innerWidth-hi,gt=fd(ze,[hi,Er-Kt]);l.style.minWidth=ct+"px",l.style.left=gt+"px"}else{const Oe=D.right-V.right,ze=window.innerWidth-B.right-Oe,Mt=window.innerWidth-A.right-ze,ct=A.width+Mt,Kt=Math.max(ct,D.width),Er=window.innerWidth-hi,gt=fd(ze,[hi,Er-Kt]);l.style.minWidth=ct+"px",l.style.right=gt+"px"}const J=g(),G=window.innerHeight-hi*2,se=S.scrollHeight,U=window.getComputedStyle(f),ne=parseInt(U.borderTopWidth,10),M=parseInt(U.paddingTop,10),ee=parseInt(U.borderBottomWidth,10),H=parseInt(U.paddingBottom,10),X=ne+M+se+H+ee,W=Math.min(E.offsetHeight*5,X),le=window.getComputedStyle(S),pe=parseInt(le.paddingTop,10),$e=parseInt(le.paddingBottom,10),Ve=A.top+A.height/2-hi,We=G-Ve,Ne=E.offsetHeight/2,fe=E.offsetTop+Ne,xe=ne+M+fe,Re=X-xe;if(xe<=Ve){const Oe=E===J[J.length-1].ref.current;l.style.bottom="0px";const ze=f.clientHeight-S.offsetTop-S.offsetHeight,Mt=Math.max(We,Ne+(Oe?$e:0)+ze+ee),ct=xe+Mt;l.style.height=ct+"px"}else{const Oe=E===J[0].ref.current;l.style.top="0px";const Mt=Math.max(Ve,ne+S.offsetTop+(Oe?pe:0)+Ne)+Re;l.style.height=Mt+"px",S.scrollTop=xe-Ve+S.offsetTop}l.style.margin=`${hi}px 0`,l.style.minHeight=W+"px",l.style.maxHeight=G+"px",r==null||r(),requestAnimationFrame(()=>y.current=!0)}},[g,i.trigger,i.valueNode,l,f,S,E,_,i.dir,r]);An(()=>C(),[C]);const[R,P]=d.useState();An(()=>{f&&P(window.getComputedStyle(f).zIndex)},[f]);const O=d.useCallback(A=>{A&&x.current===!0&&(C(),b==null||b(),x.current=!1)},[C,b]);return d.createElement(FG,{scope:n,contentWrapper:l,shouldExpandOnScrollRef:y,onScrollButtonChange:O},d.createElement("div",{ref:u,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:R}},d.createElement(Ae.div,Y({},o,{ref:m,style:{boxSizing:"border-box",maxHeight:"100%",...o.style}}))))}),g2=d.forwardRef((e,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:o=hi,...i}=e,s=Vx(n);return d.createElement(Hm,Y({},s,i,{ref:t,align:r,collisionPadding:o,style:{boxSizing:"border-box",...i.style,"--radix-select-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-select-content-available-width":"var(--radix-popper-available-width)","--radix-select-content-available-height":"var(--radix-popper-available-height)","--radix-select-trigger-width":"var(--radix-popper-anchor-width)","--radix-select-trigger-height":"var(--radix-popper-anchor-height)"}}))}),[FG,Wx]=Pc(dc,{}),v2="SelectViewport",jG=d.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=ja(v2,n),i=Wx(v2,n),s=Ue(t,o.onViewportChange),l=d.useRef(0);return d.createElement(d.Fragment,null,d.createElement("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"}}),d.createElement(og.Slot,{scope:n},d.createElement(Ae.div,Y({"data-radix-select-viewport":"",role:"presentation"},r,{ref:s,style:{position:"relative",flex:1,overflow:"auto",...r.style},onScroll:ue(r.onScroll,u=>{const f=u.currentTarget,{contentWrapper:p,shouldExpandOnScrollRef:m}=i;if(m!=null&&m.current&&p){const g=Math.abs(l.current-f.scrollTop);if(g>0){const y=window.innerHeight-hi*2,x=parseFloat(p.style.minHeight),S=parseFloat(p.style.height),E=Math.max(x,S);if(E0?C:0,p.style.justifyContent="flex-end")}}}l.current=f.scrollTop})}))))}),zG="SelectGroup",[BG,UG]=Pc(zG),VG=d.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=nr();return d.createElement(BG,{scope:n,id:o},d.createElement(Ae.div,Y({role:"group","aria-labelledby":o},r,{ref:t})))}),WG="SelectLabel",HG=d.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=UG(WG,n);return d.createElement(Ae.div,Y({id:o.id},r,{ref:t}))}),_1="SelectItem",[KG,u3]=Pc(_1),GG=d.forwardRef((e,t)=>{const{__scopeSelect:n,value:r,disabled:o=!1,textValue:i,...s}=e,l=Fa(_1,n),u=ja(_1,n),f=l.value===r,[p,m]=d.useState(i??""),[g,y]=d.useState(!1),x=Ue(t,_=>{var b;return(b=u.itemRefCallback)===null||b===void 0?void 0:b.call(u,_,r,o)}),S=nr(),E=()=>{o||(l.onValueChange(r),l.onOpenChange(!1))};if(r==="")throw new Error("A must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.");return d.createElement(KG,{scope:n,value:r,disabled:o,textId:S,isSelected:f,onItemTextChange:d.useCallback(_=>{m(b=>{var C;return b||((C=_==null?void 0:_.textContent)!==null&&C!==void 0?C:"").trim()})},[])},d.createElement(og.ItemSlot,{scope:n,value:r,disabled:o,textValue:p},d.createElement(Ae.div,Y({role:"option","aria-labelledby":S,"data-highlighted":g?"":void 0,"aria-selected":f&&g,"data-state":f?"checked":"unchecked","aria-disabled":o||void 0,"data-disabled":o?"":void 0,tabIndex:o?void 0:-1},s,{ref:x,onFocus:ue(s.onFocus,()=>y(!0)),onBlur:ue(s.onBlur,()=>y(!1)),onPointerUp:ue(s.onPointerUp,E),onPointerMove:ue(s.onPointerMove,_=>{if(o){var b;(b=u.onItemLeave)===null||b===void 0||b.call(u)}else _.currentTarget.focus({preventScroll:!0})}),onPointerLeave:ue(s.onPointerLeave,_=>{if(_.currentTarget===document.activeElement){var b;(b=u.onItemLeave)===null||b===void 0||b.call(u)}}),onKeyDown:ue(s.onKeyDown,_=>{var b;((b=u.searchRef)===null||b===void 0?void 0:b.current)!==""&&_.key===" "||(_G.includes(_.key)&&E(),_.key===" "&&_.preventDefault())})}))))}),xh="SelectItemText",YG=d.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,...i}=e,s=Fa(xh,n),l=ja(xh,n),u=u3(xh,n),f=RG(xh,n),[p,m]=d.useState(null),g=Ue(t,_=>m(_),u.onItemTextChange,_=>{var b;return(b=l.itemTextRefCallback)===null||b===void 0?void 0:b.call(l,_,u.value,u.disabled)}),y=p==null?void 0:p.textContent,x=d.useMemo(()=>d.createElement("option",{key:u.value,value:u.value,disabled:u.disabled},y),[u.disabled,u.value,y]),{onNativeOptionAdd:S,onNativeOptionRemove:E}=f;return An(()=>(S(x),()=>E(x)),[S,E,x]),d.createElement(d.Fragment,null,d.createElement(Ae.span,Y({id:u.textId},i,{ref:g})),u.isSelected&&s.valueNode&&!s.valueNodeHasChildren?Is.createPortal(i.children,s.valueNode):null)}),XG="SelectItemIndicator",ZG=d.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return u3(XG,n).isSelected?d.createElement(Ae.span,Y({"aria-hidden":!0},r,{ref:t})):null}),y2="SelectScrollUpButton",qG=d.forwardRef((e,t)=>{const n=ja(y2,e.__scopeSelect),r=Wx(y2,e.__scopeSelect),[o,i]=d.useState(!1),s=Ue(t,r.onScrollButtonChange);return An(()=>{if(n.viewport&&n.isPositioned){let f=function(){const p=u.scrollTop>0;i(p)};var l=f;const u=n.viewport;return f(),u.addEventListener("scroll",f),()=>u.removeEventListener("scroll",f)}},[n.viewport,n.isPositioned]),o?d.createElement(d3,Y({},e,{ref:s,onAutoScroll:()=>{const{viewport:l,selectedItem:u}=n;l&&u&&(l.scrollTop=l.scrollTop-u.offsetHeight)}})):null}),w2="SelectScrollDownButton",QG=d.forwardRef((e,t)=>{const n=ja(w2,e.__scopeSelect),r=Wx(w2,e.__scopeSelect),[o,i]=d.useState(!1),s=Ue(t,r.onScrollButtonChange);return An(()=>{if(n.viewport&&n.isPositioned){let f=function(){const p=u.scrollHeight-u.clientHeight,m=Math.ceil(u.scrollTop)u.removeEventListener("scroll",f)}},[n.viewport,n.isPositioned]),o?d.createElement(d3,Y({},e,{ref:s,onAutoScroll:()=>{const{viewport:l,selectedItem:u}=n;l&&u&&(l.scrollTop=l.scrollTop+u.offsetHeight)}})):null}),d3=d.forwardRef((e,t)=>{const{__scopeSelect:n,onAutoScroll:r,...o}=e,i=ja("SelectScrollButton",n),s=d.useRef(null),l=ig(n),u=d.useCallback(()=>{s.current!==null&&(window.clearInterval(s.current),s.current=null)},[]);return d.useEffect(()=>()=>u(),[u]),An(()=>{var f;const p=l().find(m=>m.ref.current===document.activeElement);p==null||(f=p.ref.current)===null||f===void 0||f.scrollIntoView({block:"nearest"})},[l]),d.createElement(Ae.div,Y({"aria-hidden":!0},o,{ref:t,style:{flexShrink:0,...o.style},onPointerDown:ue(o.onPointerDown,()=>{s.current===null&&(s.current=window.setInterval(r,50))}),onPointerMove:ue(o.onPointerMove,()=>{var f;(f=i.onItemLeave)===null||f===void 0||f.call(i),s.current===null&&(s.current=window.setInterval(r,50))}),onPointerLeave:ue(o.onPointerLeave,()=>{u()})}))}),JG=d.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return d.createElement(Ae.div,Y({"aria-hidden":!0},r,{ref:t}))});function f3(e){return e===""||e===void 0}const h3=d.forwardRef((e,t)=>{const{value:n,...r}=e,o=d.useRef(null),i=Ue(t,o),s=Ux(n);return d.useEffect(()=>{const l=o.current,u=window.HTMLSelectElement.prototype,p=Object.getOwnPropertyDescriptor(u,"value").set;if(s!==n&&p){const m=new Event("change",{bubbles:!0});p.call(l,n),l.dispatchEvent(m)}},[s,n]),d.createElement(Km,{asChild:!0},d.createElement("select",Y({},r,{ref:i,defaultValue:n})))});h3.displayName="BubbleSelect";function p3(e){const t=Ft(e),n=d.useRef(""),r=d.useRef(0),o=d.useCallback(s=>{const l=n.current+s;t(l),function u(f){n.current=f,window.clearTimeout(r.current),f!==""&&(r.current=window.setTimeout(()=>u(""),1e3))}(l)},[t]),i=d.useCallback(()=>{n.current="",window.clearTimeout(r.current)},[]);return d.useEffect(()=>()=>window.clearTimeout(r.current),[]),[n,o,i]}function m3(e,t,n){const o=t.length>1&&Array.from(t).every(f=>f===t[0])?t[0]:t,i=n?e.indexOf(n):-1;let s=eY(e,Math.max(i,0));o.length===1&&(s=s.filter(f=>f!==n));const u=s.find(f=>f.textValue.toLowerCase().startsWith(o.toLowerCase()));return u!==n?u:void 0}function eY(e,t){return e.map((n,r)=>e[(t+r)%e.length])}const tY=kG,g3=PG,nY=MG,rY=OG,oY=NG,v3=DG,iY=jG,sY=VG,y3=HG,w3=GG,aY=YG,lY=ZG,x3=qG,b3=QG,S3=JG,Uo=tY,vi=sY,Vo=nY,go=d.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(g3,{ref:r,className:_e("flex h-9 w-full items-center justify-between whitespace-nowrap rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",e),tabIndex:-1,...n,children:[t,v.jsx(rY,{asChild:!0,children:v.jsx(Zj,{className:"h-4 w-4 opacity-50"})})]}));go.displayName=g3.displayName;const _3=d.forwardRef(({className:e,...t},n)=>v.jsx(x3,{ref:n,className:_e("flex cursor-default items-center justify-center py-1",e),...t,children:v.jsx(rz,{})}));_3.displayName=x3.displayName;const E3=d.forwardRef(({className:e,...t},n)=>v.jsx(b3,{ref:n,className:_e("flex cursor-default items-center justify-center py-1",e),...t,children:v.jsx(Jj,{})}));E3.displayName=b3.displayName;const vo=d.forwardRef(({className:e,children:t,position:n="popper",...r},o)=>v.jsx(oY,{children:v.jsxs(v3,{ref:o,className:_e("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",n==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:n,onCloseAutoFocus:i=>i.preventDefault(),...r,children:[v.jsx(_3,{}),v.jsx(iY,{className:_e("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),v.jsx(E3,{})]})}));vo.displayName=v3.displayName;const cY=d.forwardRef(({className:e,...t},n)=>v.jsx(y3,{ref:n,className:_e("px-2 py-1.5 text-sm font-semibold",e),...t}));cY.displayName=y3.displayName;const yo=d.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(w3,{ref:r,className:_e("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-2 pr-8 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[v.jsx("span",{className:"absolute right-2 flex h-3.5 w-3.5 items-center justify-center",children:v.jsx(lY,{children:v.jsx(xk,{className:"h-4 w-4"})})}),v.jsx(aY,{children:t})]}));yo.displayName=w3.displayName;const uY=d.forwardRef(({className:e,...t},n)=>v.jsx(S3,{ref:n,className:_e("-mx-1 my-1 h-px bg-muted",e),...t}));uY.displayName=S3.displayName;function dY(e,t){return d.useReducer((n,r)=>{const o=t[n][r];return o??n},e)}const C3="ScrollArea",[$3,Ste]=Mn(C3),[fY,qr]=$3(C3),hY=d.forwardRef((e,t)=>{const{__scopeScrollArea:n,type:r="hover",dir:o,scrollHideDelay:i=600,...s}=e,[l,u]=d.useState(null),[f,p]=d.useState(null),[m,g]=d.useState(null),[y,x]=d.useState(null),[S,E]=d.useState(null),[_,b]=d.useState(0),[C,R]=d.useState(0),[P,O]=d.useState(!1),[A,D]=d.useState(!1),B=Ue(t,J=>u(J)),V=Tc(o);return d.createElement(fY,{scope:n,type:r,dir:V,scrollHideDelay:i,scrollArea:l,viewport:f,onViewportChange:p,content:m,onContentChange:g,scrollbarX:y,onScrollbarXChange:x,scrollbarXEnabled:P,onScrollbarXEnabledChange:O,scrollbarY:S,onScrollbarYChange:E,scrollbarYEnabled:A,onScrollbarYEnabledChange:D,onCornerWidthChange:b,onCornerHeightChange:R},d.createElement(Ae.div,Y({dir:V},s,{ref:B,style:{position:"relative","--radix-scroll-area-corner-width":_+"px","--radix-scroll-area-corner-height":C+"px",...e.style}})))}),pY="ScrollAreaViewport",mY=d.forwardRef((e,t)=>{const{__scopeScrollArea:n,children:r,...o}=e,i=qr(pY,n),s=d.useRef(null),l=Ue(t,s,i.onViewportChange);return d.createElement(d.Fragment,null,d.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}"}}),d.createElement(Ae.div,Y({"data-radix-scroll-area-viewport":""},o,{ref:l,style:{overflowX:i.scrollbarXEnabled?"scroll":"hidden",overflowY:i.scrollbarYEnabled?"scroll":"hidden",...e.style}}),d.createElement("div",{ref:i.onContentChange,style:{minWidth:"100%",display:"table"}},r)))}),Oi="ScrollAreaScrollbar",R3=d.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=qr(Oi,e.__scopeScrollArea),{onScrollbarXEnabledChange:i,onScrollbarYEnabledChange:s}=o,l=e.orientation==="horizontal";return d.useEffect(()=>(l?i(!0):s(!0),()=>{l?i(!1):s(!1)}),[l,i,s]),o.type==="hover"?d.createElement(gY,Y({},r,{ref:t,forceMount:n})):o.type==="scroll"?d.createElement(vY,Y({},r,{ref:t,forceMount:n})):o.type==="auto"?d.createElement(k3,Y({},r,{ref:t,forceMount:n})):o.type==="always"?d.createElement(Hx,Y({},r,{ref:t})):null}),gY=d.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=qr(Oi,e.__scopeScrollArea),[i,s]=d.useState(!1);return d.useEffect(()=>{const l=o.scrollArea;let u=0;if(l){const f=()=>{window.clearTimeout(u),s(!0)},p=()=>{u=window.setTimeout(()=>s(!1),o.scrollHideDelay)};return l.addEventListener("pointerenter",f),l.addEventListener("pointerleave",p),()=>{window.clearTimeout(u),l.removeEventListener("pointerenter",f),l.removeEventListener("pointerleave",p)}}},[o.scrollArea,o.scrollHideDelay]),d.createElement(Sn,{present:n||i},d.createElement(k3,Y({"data-state":i?"visible":"hidden"},r,{ref:t})))}),vY=d.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=qr(Oi,e.__scopeScrollArea),i=e.orientation==="horizontal",s=ag(()=>u("SCROLL_END"),100),[l,u]=dY("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 d.useEffect(()=>{if(l==="idle"){const f=window.setTimeout(()=>u("HIDE"),o.scrollHideDelay);return()=>window.clearTimeout(f)}},[l,o.scrollHideDelay,u]),d.useEffect(()=>{const f=o.viewport,p=i?"scrollLeft":"scrollTop";if(f){let m=f[p];const g=()=>{const y=f[p];m!==y&&(u("SCROLL"),s()),m=y};return f.addEventListener("scroll",g),()=>f.removeEventListener("scroll",g)}},[o.viewport,i,u,s]),d.createElement(Sn,{present:n||l!=="hidden"},d.createElement(Hx,Y({"data-state":l==="hidden"?"hidden":"visible"},r,{ref:t,onPointerEnter:ue(e.onPointerEnter,()=>u("POINTER_ENTER")),onPointerLeave:ue(e.onPointerLeave,()=>u("POINTER_LEAVE"))})))}),k3=d.forwardRef((e,t)=>{const n=qr(Oi,e.__scopeScrollArea),{forceMount:r,...o}=e,[i,s]=d.useState(!1),l=e.orientation==="horizontal",u=ag(()=>{if(n.viewport){const f=n.viewport.offsetWidth{const{orientation:n="vertical",...r}=e,o=qr(Oi,e.__scopeScrollArea),i=d.useRef(null),s=d.useRef(0),[l,u]=d.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),f=M3(l.viewport,l.content),p={...r,sizes:l,onSizesChange:u,hasThumb:f>0&&f<1,onThumbChange:g=>i.current=g,onThumbPointerUp:()=>s.current=0,onThumbPointerDown:g=>s.current=g};function m(g,y){return CY(g,s.current,l,y)}return n==="horizontal"?d.createElement(yY,Y({},p,{ref:t,onThumbPositionChange:()=>{if(o.viewport&&i.current){const g=o.viewport.scrollLeft,y=x2(g,l,o.dir);i.current.style.transform=`translate3d(${y}px, 0, 0)`}},onWheelScroll:g=>{o.viewport&&(o.viewport.scrollLeft=g)},onDragScroll:g=>{o.viewport&&(o.viewport.scrollLeft=m(g,o.dir))}})):n==="vertical"?d.createElement(wY,Y({},p,{ref:t,onThumbPositionChange:()=>{if(o.viewport&&i.current){const g=o.viewport.scrollTop,y=x2(g,l);i.current.style.transform=`translate3d(0, ${y}px, 0)`}},onWheelScroll:g=>{o.viewport&&(o.viewport.scrollTop=g)},onDragScroll:g=>{o.viewport&&(o.viewport.scrollTop=m(g))}})):null}),yY=d.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,i=qr(Oi,e.__scopeScrollArea),[s,l]=d.useState(),u=d.useRef(null),f=Ue(t,u,i.onScrollbarXChange);return d.useEffect(()=>{u.current&&l(getComputedStyle(u.current))},[u]),d.createElement(P3,Y({"data-orientation":"horizontal"},o,{ref:f,sizes:n,style:{bottom:0,left:i.dir==="rtl"?"var(--radix-scroll-area-corner-width)":0,right:i.dir==="ltr"?"var(--radix-scroll-area-corner-width)":0,"--radix-scroll-area-thumb-width":sg(n)+"px",...e.style},onThumbPointerDown:p=>e.onThumbPointerDown(p.x),onDragScroll:p=>e.onDragScroll(p.x),onWheelScroll:(p,m)=>{if(i.viewport){const g=i.viewport.scrollLeft+p.deltaX;e.onWheelScroll(g),N3(g,m)&&p.preventDefault()}},onResize:()=>{u.current&&i.viewport&&s&&r({content:i.viewport.scrollWidth,viewport:i.viewport.offsetWidth,scrollbar:{size:u.current.clientWidth,paddingStart:Vp(s.paddingLeft),paddingEnd:Vp(s.paddingRight)}})}}))}),wY=d.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,i=qr(Oi,e.__scopeScrollArea),[s,l]=d.useState(),u=d.useRef(null),f=Ue(t,u,i.onScrollbarYChange);return d.useEffect(()=>{u.current&&l(getComputedStyle(u.current))},[u]),d.createElement(P3,Y({"data-orientation":"vertical"},o,{ref:f,sizes:n,style:{top:0,right:i.dir==="ltr"?0:void 0,left:i.dir==="rtl"?0:void 0,bottom:"var(--radix-scroll-area-corner-height)","--radix-scroll-area-thumb-height":sg(n)+"px",...e.style},onThumbPointerDown:p=>e.onThumbPointerDown(p.y),onDragScroll:p=>e.onDragScroll(p.y),onWheelScroll:(p,m)=>{if(i.viewport){const g=i.viewport.scrollTop+p.deltaY;e.onWheelScroll(g),N3(g,m)&&p.preventDefault()}},onResize:()=>{u.current&&i.viewport&&s&&r({content:i.viewport.scrollHeight,viewport:i.viewport.offsetHeight,scrollbar:{size:u.current.clientHeight,paddingStart:Vp(s.paddingTop),paddingEnd:Vp(s.paddingBottom)}})}}))}),[xY,T3]=$3(Oi),P3=d.forwardRef((e,t)=>{const{__scopeScrollArea:n,sizes:r,hasThumb:o,onThumbChange:i,onThumbPointerUp:s,onThumbPointerDown:l,onThumbPositionChange:u,onDragScroll:f,onWheelScroll:p,onResize:m,...g}=e,y=qr(Oi,n),[x,S]=d.useState(null),E=Ue(t,B=>S(B)),_=d.useRef(null),b=d.useRef(""),C=y.viewport,R=r.content-r.viewport,P=Ft(p),O=Ft(u),A=ag(m,10);function D(B){if(_.current){const V=B.clientX-_.current.left,J=B.clientY-_.current.top;f({x:V,y:J})}}return d.useEffect(()=>{const B=V=>{const J=V.target;(x==null?void 0:x.contains(J))&&P(V,R)};return document.addEventListener("wheel",B,{passive:!1}),()=>document.removeEventListener("wheel",B,{passive:!1})},[C,x,R,P]),d.useEffect(O,[r,O]),fc(x,A),fc(y.content,A),d.createElement(xY,{scope:n,scrollbar:x,hasThumb:o,onThumbChange:Ft(i),onThumbPointerUp:Ft(s),onThumbPositionChange:O,onThumbPointerDown:Ft(l)},d.createElement(Ae.div,Y({},g,{ref:E,style:{position:"absolute",...g.style},onPointerDown:ue(e.onPointerDown,B=>{B.button===0&&(B.target.setPointerCapture(B.pointerId),_.current=x.getBoundingClientRect(),b.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",y.viewport&&(y.viewport.style.scrollBehavior="auto"),D(B))}),onPointerMove:ue(e.onPointerMove,D),onPointerUp:ue(e.onPointerUp,B=>{const V=B.target;V.hasPointerCapture(B.pointerId)&&V.releasePointerCapture(B.pointerId),document.body.style.webkitUserSelect=b.current,y.viewport&&(y.viewport.style.scrollBehavior=""),_.current=null})})))}),E1="ScrollAreaThumb",bY=d.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=T3(E1,e.__scopeScrollArea);return d.createElement(Sn,{present:n||o.hasThumb},d.createElement(SY,Y({ref:t},r)))}),SY=d.forwardRef((e,t)=>{const{__scopeScrollArea:n,style:r,...o}=e,i=qr(E1,n),s=T3(E1,n),{onThumbPositionChange:l}=s,u=Ue(t,m=>s.onThumbChange(m)),f=d.useRef(),p=ag(()=>{f.current&&(f.current(),f.current=void 0)},100);return d.useEffect(()=>{const m=i.viewport;if(m){const g=()=>{if(p(),!f.current){const y=$Y(m,l);f.current=y,l()}};return l(),m.addEventListener("scroll",g),()=>m.removeEventListener("scroll",g)}},[i.viewport,p,l]),d.createElement(Ae.div,Y({"data-state":s.hasThumb?"visible":"hidden"},o,{ref:u,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...r},onPointerDownCapture:ue(e.onPointerDownCapture,m=>{const y=m.target.getBoundingClientRect(),x=m.clientX-y.left,S=m.clientY-y.top;s.onThumbPointerDown({x,y:S})}),onPointerUp:ue(e.onPointerUp,s.onThumbPointerUp)}))}),A3="ScrollAreaCorner",_Y=d.forwardRef((e,t)=>{const n=qr(A3,e.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?d.createElement(EY,Y({},e,{ref:t})):null}),EY=d.forwardRef((e,t)=>{const{__scopeScrollArea:n,...r}=e,o=qr(A3,n),[i,s]=d.useState(0),[l,u]=d.useState(0),f=!!(i&&l);return fc(o.scrollbarX,()=>{var p;const m=((p=o.scrollbarX)===null||p===void 0?void 0:p.offsetHeight)||0;o.onCornerHeightChange(m),u(m)}),fc(o.scrollbarY,()=>{var p;const m=((p=o.scrollbarY)===null||p===void 0?void 0:p.offsetWidth)||0;o.onCornerWidthChange(m),s(m)}),f?d.createElement(Ae.div,Y({},r,{ref:t,style:{width:i,height:l,position:"absolute",right:o.dir==="ltr"?0:void 0,left:o.dir==="rtl"?0:void 0,bottom:0,...e.style}})):null});function Vp(e){return e?parseInt(e,10):0}function M3(e,t){const n=e/t;return isNaN(n)?0:n}function sg(e){const t=M3(e.viewport,e.content),n=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,r=(e.scrollbar.size-n)*t;return Math.max(r,18)}function CY(e,t,n,r="ltr"){const o=sg(n),i=o/2,s=t||i,l=o-s,u=n.scrollbar.paddingStart+s,f=n.scrollbar.size-n.scrollbar.paddingEnd-l,p=n.content-n.viewport,m=r==="ltr"?[0,p]:[p*-1,0];return O3([u,f],m)(e)}function x2(e,t,n="ltr"){const r=sg(t),o=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,i=t.scrollbar.size-o,s=t.content-t.viewport,l=i-r,u=n==="ltr"?[0,s]:[s*-1,0],f=fd(e,u);return O3([0,s],[0,l])(f)}function O3(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 N3(e,t){return e>0&&e{})=>{let n={left:e.scrollLeft,top:e.scrollTop},r=0;return function o(){const i={left:e.scrollLeft,top:e.scrollTop},s=n.left!==i.left,l=n.top!==i.top;(s||l)&&t(),n=i,r=window.requestAnimationFrame(o)}(),()=>window.cancelAnimationFrame(r)};function ag(e,t){const n=Ft(e),r=d.useRef(0);return d.useEffect(()=>()=>window.clearTimeout(r.current),[]),d.useCallback(()=>{window.clearTimeout(r.current),r.current=window.setTimeout(n,t)},[n,t])}function fc(e,t){const n=Ft(t);An(()=>{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 D3=hY,RY=mY,kY=_Y,lg=d.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(D3,{ref:r,className:_e("relative overflow-hidden",e),scrollHideDelay:400,...n,children:[v.jsx(RY,{className:"h-full w-full rounded-[inherit]",children:t}),v.jsx(I3,{}),v.jsx(kY,{})]}));lg.displayName=D3.displayName;const I3=d.forwardRef(({className:e,orientation:t="vertical",...n},r)=>v.jsx(R3,{ref:r,orientation:t,className:_e("flex touch-none select-none transition-colors",t==="vertical"&&"h-full w-2.5 border-l border-l-transparent p-[1px]",t==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",e),...n,children:v.jsx(bY,{className:"relative flex-1 rounded-full bg-border"})}));I3.displayName=R3.displayName;const L3="Name",F3="Created time",j3="Modified time",b2="input",TY="output",S2={[Es.NAME]:L3,[Es.CTIME]:F3,[Es.MTIME]:j3};function PY(e){const{onPhotoClick:t,photoWidth:n}=e,[r,o]=Nx(!1),[i,s]=xt(V=>[V.fileManagerState,V.updateFileManagerState]),{toast:l}=Id(),[u,f]=d.useState(0),[p,m]=d.useState(0),g=d.useRef(null),y=lV(i.searchText,300),[x,S]=d.useState(b2),[E,_]=d.useState([]),[b,C]=d.useState([]),[R,P]=d.useState(0);Zn("f",()=>{o()}),Zn("left",()=>{let V=R;R>0&&(V=R-1),P(V),t(x,b[V].name)},[R,b]),Zn("right",()=>{let V=R;R{r||m(u)},[r,u]);const O=d.useCallback(V=>{V!==null&&r&&setTimeout(()=>{V.scrollTo({top:p,left:0})},100)},[r,p]);d.useEffect(()=>{(async()=>{try{const J=await Wj(x);_(J)}catch(J){l({variant:"destructive",title:"Uh oh! Something went wrong.",description:J.message?J.message:J.toString()})}})()},[x]),d.useEffect(()=>{if(!r)return;(async()=>{try{let J=E;y&&(J=new kc(J,{keys:["name"]}).search(y).map(ne=>J[ne.refIndex])),J=xH.orderBy(J,i.sortBy,i.sortOrder);const G=J.map(se=>{const U=n,ne=se.height*(U/se.width);return{src:`${Ls}/media_thumbnail_file?tab=${x}&filename=${encodeURIComponent(se.name)}&width=${Math.ceil(U)}&height=${Math.ceil(ne)}`,height:ne,width:U,name:se.name}});C(G)}catch(J){l({variant:"destructive",title:"Uh oh! Something went wrong.",description:J.message?J.message:J.toString()})}})()},[E,y,i,n,r]);const A=V=>{f(V.currentTarget.scrollTop)},D=({index:V})=>{o(),P(V),t(x,b[V].name)},B=()=>v.jsxs("div",{className:"flex justify-start items-center gap-[12px]",children:[v.jsx("div",{children:`Images (${b.length})`}),v.jsxs("div",{className:"flex",children:[v.jsx(yn,{tooltip:"Rows layout",onClick:()=>{s({layout:"rows"})},children:v.jsx(pz,{className:i.layout!=="rows"?"opacity-50":""})}),v.jsx(yn,{tooltip:"Grid layout",onClick:()=>{s({layout:"masonry"})},children:v.jsx(fz,{className:i.layout!=="masonry"?"opacity-50":""})})]})]});return v.jsxs(eg,{open:r,onOpenChange:o,children:[v.jsx(pT,{asChild:!0,children:v.jsx(yn,{tooltip:"File Manager",children:v.jsx(eV,{})})}),v.jsxs(Wd,{className:"h-4/5 max-w-6xl",children:[v.jsx(Hd,{children:B()}),v.jsxs("div",{className:"flex justify-between gap-8 items-center",children:[v.jsxs("div",{className:"flex relative justify-start items-center",children:[v.jsx(lz,{className:"absolute left-[8px]"}),v.jsx(Bm,{ref:g,value:i.searchText,className:"w-[250px] pl-[30px]",tabIndex:-1,onInput:V=>{V.preventDefault(),V.stopPropagation();const J=V.target;s({searchText:J.value})},placeholder:"Search by file name"})]}),v.jsx(l3,{defaultValue:x,onValueChange:V=>S(V),children:v.jsxs(Bx,{"aria-label":"Manage your account",children:[v.jsx(pa,{value:b2,children:"Image Directory"}),v.jsx(pa,{value:TY,children:"Output Directory"})]})}),v.jsx("div",{className:"flex gap-2",children:v.jsxs("div",{className:"flex gap-1",children:[v.jsxs(Uo,{value:S2[i.sortBy],onValueChange:V=>{switch(V){case L3:s({sortBy:Es.NAME});break;case F3:s({sortBy:Es.CTIME});break;case j3:s({sortBy:Es.MTIME});break}},children:[v.jsx(go,{className:"w-[140px]",children:v.jsx(Vo,{})}),v.jsx(vo,{children:Object.values(S2).map(V=>v.jsx(yo,{value:V,children:V},V))})]}),i.sortOrder===Ou.DESCENDING?v.jsx(yn,{tooltip:"Descending Order",onClick:()=>{s({sortOrder:Ou.ASCENDING})},children:v.jsx(iK,{})}):v.jsx(yn,{tooltip:"Ascending Order",onClick:()=>{s({sortOrder:Ou.DESCENDING})},children:v.jsx(lK,{})})]})})]}),v.jsx(lg,{className:"w-full h-full rounded-md",onScroll:A,ref:O,children:v.jsx(nK,{layout:i.layout,photos:b,spacing:12,padding:0,onClick:D})})]})]})}var Gd=e=>e.type==="checkbox",$l=e=>e instanceof Date,Fn=e=>e==null;const z3=e=>typeof e=="object";var sn=e=>!Fn(e)&&!Array.isArray(e)&&z3(e)&&!$l(e),B3=e=>sn(e)&&e.target?Gd(e.target)?e.target.checked:e.target.value:e,AY=e=>e.substring(0,e.search(/\.\d+(\.|$)/))||e,U3=(e,t)=>e.has(AY(t)),MY=e=>{const t=e.constructor&&e.constructor.prototype;return sn(t)&&t.hasOwnProperty("isPrototypeOf")},Kx=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function so(e){let t;const n=Array.isArray(e);if(e instanceof Date)t=new Date(e);else if(e instanceof Set)t=new Set(e);else if(!(Kx&&(e instanceof Blob||e instanceof FileList))&&(n||sn(e)))if(t=n?[]:{},!n&&!MY(e))t=e;else for(const r in e)e.hasOwnProperty(r)&&(t[r]=so(e[r]));else return e;return t}var Yd=e=>Array.isArray(e)?e.filter(Boolean):[],Ht=e=>e===void 0,ve=(e,t,n)=>{if(!t||!sn(e))return n;const r=Yd(t.split(/[,[\].]+?/)).reduce((o,i)=>Fn(o)?o:o[i],e);return Ht(r)||r===e?Ht(e[t])?n:e[t]:r},Fo=e=>typeof e=="boolean";const Wp={BLUR:"blur",FOCUS_OUT:"focusout",CHANGE:"change"},mo={onBlur:"onBlur",onChange:"onChange",onSubmit:"onSubmit",onTouched:"onTouched",all:"all"},ui={max:"max",min:"min",maxLength:"maxLength",minLength:"minLength",pattern:"pattern",required:"required",validate:"validate"},V3=je.createContext(null),cg=()=>je.useContext(V3),OY=e=>{const{children:t,...n}=e;return je.createElement(V3.Provider,{value:n},t)};var W3=(e,t,n,r=!0)=>{const o={defaultValues:t._defaultValues};for(const i in e)Object.defineProperty(o,i,{get:()=>{const s=i;return t._proxyFormState[s]!==mo.all&&(t._proxyFormState[s]=!r||mo.all),n&&(n[s]=!0),e[s]}});return o},Fr=e=>sn(e)&&!Object.keys(e).length,H3=(e,t,n,r)=>{n(e);const{name:o,...i}=e;return Fr(i)||Object.keys(i).length>=Object.keys(t).length||Object.keys(i).find(s=>t[s]===(!r||mo.all))},ep=e=>Array.isArray(e)?e:[e],K3=(e,t,n)=>!e||!t||e===t||ep(e).some(r=>r&&(n?r===t:r.startsWith(t)||t.startsWith(r)));function Gx(e){const t=je.useRef(e);t.current=e,je.useEffect(()=>{const n=!e.disabled&&t.current.subject&&t.current.subject.subscribe({next:t.current.next});return()=>{n&&n.unsubscribe()}},[e.disabled])}function NY(e){const t=cg(),{control:n=t.control,disabled:r,name:o,exact:i}=e||{},[s,l]=je.useState(n._formState),u=je.useRef(!0),f=je.useRef({isDirty:!1,isLoading:!1,dirtyFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1}),p=je.useRef(o);return p.current=o,Gx({disabled:r,next:m=>u.current&&K3(p.current,m.name,i)&&H3(m,f.current,n._updateFormState)&&l({...n._formState,...m}),subject:n._subjects.state}),je.useEffect(()=>(u.current=!0,f.current.isValid&&n._updateValid(!0),()=>{u.current=!1}),[n]),W3(s,n,f.current,!1)}var Wo=e=>typeof e=="string",G3=(e,t,n,r,o)=>Wo(e)?(r&&t.watch.add(e),ve(n,e,o)):Array.isArray(e)?e.map(i=>(r&&t.watch.add(i),ve(n,i))):(r&&(t.watchAll=!0),n);function DY(e){const t=cg(),{control:n=t.control,name:r,defaultValue:o,disabled:i,exact:s}=e||{},l=je.useRef(r);l.current=r,Gx({disabled:i,subject:n._subjects.values,next:p=>{K3(l.current,p.name,s)&&f(so(G3(l.current,n._names,p.values||n._formValues,!1,o)))}});const[u,f]=je.useState(n._getWatch(r,o));return je.useEffect(()=>n._removeUnmounted()),u}var Yx=e=>/^\w*$/.test(e),Y3=e=>Yd(e.replace(/["|']|\]/g,"").split(/\.|\[/));function wt(e,t,n){let r=-1;const o=Yx(t)?[t]:Y3(t),i=o.length,s=i-1;for(;++r{const p=o._options.shouldUnregister||i,m=(g,y)=>{const x=ve(o._fields,g);x&&(x._f.mount=y)};if(m(n,!0),p){const g=so(ve(o._options.defaultValues,n));wt(o._defaultValues,n,g),Ht(ve(o._formValues,n))&&wt(o._formValues,n,g)}return()=>{(s?p&&!o._state.action:p)?o.unregister(n):m(n,!1)}},[n,o,s,i]),je.useEffect(()=>{ve(o._fields,n)&&o._updateDisabledField({disabled:r,fields:o._fields,name:n,value:ve(o._fields,n)._f.value})},[r,n,o]),{field:{name:n,value:l,...Fo(r)||Fo(u.disabled)?{disabled:u.disabled||r}:{},onChange:je.useCallback(p=>f.current.onChange({target:{value:B3(p),name:n},type:Wp.CHANGE}),[n]),onBlur:je.useCallback(()=>f.current.onBlur({target:{value:ve(o._formValues,n),name:n},type:Wp.BLUR}),[n,o]),ref:p=>{const m=ve(o._fields,n);m&&p&&(m._f.ref={focus:()=>p.focus(),select:()=>p.select(),setCustomValidity:g=>p.setCustomValidity(g),reportValidity:()=>p.reportValidity()})}},formState:u,fieldState:Object.defineProperties({},{invalid:{enumerable:!0,get:()=>!!ve(u.errors,n)},isDirty:{enumerable:!0,get:()=>!!ve(u.dirtyFields,n)},isTouched:{enumerable:!0,get:()=>!!ve(u.touchedFields,n)},error:{enumerable:!0,get:()=>ve(u.errors,n)}})}}const LY=e=>e.render(IY(e));var X3=(e,t,n,r,o)=>t?{...n[e],types:{...n[e]&&n[e].types?n[e].types:{},[r]:o||!0}}:{},_2=e=>({isOnSubmit:!e||e===mo.onSubmit,isOnBlur:e===mo.onBlur,isOnChange:e===mo.onChange,isOnAll:e===mo.all,isOnTouch:e===mo.onTouched}),E2=(e,t,n)=>!n&&(t.watchAll||t.watch.has(e)||[...t.watch].some(r=>e.startsWith(r)&&/^\.\w+/.test(e.slice(r.length))));const tp=(e,t,n,r)=>{for(const o of n||Object.keys(e)){const i=ve(e,o);if(i){const{_f:s,...l}=i;if(s){if(s.refs&&s.refs[0]&&t(s.refs[0],o)&&!r)break;if(s.ref&&t(s.ref,s.name)&&!r)break}else sn(l)&&tp(l,t)}}};var FY=(e,t,n)=>{const r=Yd(ve(e,n));return wt(r,"root",t[n]),wt(e,n,r),e},Xx=e=>e.type==="file",ms=e=>typeof e=="function",Hp=e=>{if(!Kx)return!1;const t=e?e.ownerDocument:0;return e instanceof(t&&t.defaultView?t.defaultView.HTMLElement:HTMLElement)},np=e=>Wo(e),Zx=e=>e.type==="radio",Kp=e=>e instanceof RegExp;const C2={value:!1,isValid:!1},$2={value:!0,isValid:!0};var Z3=e=>{if(Array.isArray(e)){if(e.length>1){const t=e.filter(n=>n&&n.checked&&!n.disabled).map(n=>n.value);return{value:t,isValid:!!t.length}}return e[0].checked&&!e[0].disabled?e[0].attributes&&!Ht(e[0].attributes.value)?Ht(e[0].value)||e[0].value===""?$2:{value:e[0].value,isValid:!0}:$2:C2}return C2};const R2={isValid:!1,value:null};var q3=e=>Array.isArray(e)?e.reduce((t,n)=>n&&n.checked&&!n.disabled?{isValid:!0,value:n.value}:t,R2):R2;function k2(e,t,n="validate"){if(np(e)||Array.isArray(e)&&e.every(np)||Fo(e)&&!e)return{type:n,message:np(e)?e:"",ref:t}}var sl=e=>sn(e)&&!Kp(e)?e:{value:e,message:""},T2=async(e,t,n,r,o)=>{const{ref:i,refs:s,required:l,maxLength:u,minLength:f,min:p,max:m,pattern:g,validate:y,name:x,valueAsNumber:S,mount:E,disabled:_}=e._f,b=ve(t,x);if(!E||_)return{};const C=s?s[0]:i,R=G=>{r&&C.reportValidity&&(C.setCustomValidity(Fo(G)?"":G||""),C.reportValidity())},P={},O=Zx(i),A=Gd(i),D=O||A,B=(S||Xx(i))&&Ht(i.value)&&Ht(b)||Hp(i)&&i.value===""||b===""||Array.isArray(b)&&!b.length,V=X3.bind(null,x,n,P),J=(G,se,U,ne=ui.maxLength,M=ui.minLength)=>{const ee=G?se:U;P[x]={type:G?ne:M,message:ee,ref:i,...V(G?ne:M,ee)}};if(o?!Array.isArray(b)||!b.length:l&&(!D&&(B||Fn(b))||Fo(b)&&!b||A&&!Z3(s).isValid||O&&!q3(s).isValid)){const{value:G,message:se}=np(l)?{value:!!l,message:l}:sl(l);if(G&&(P[x]={type:ui.required,message:se,ref:C,...V(ui.required,se)},!n))return R(se),P}if(!B&&(!Fn(p)||!Fn(m))){let G,se;const U=sl(m),ne=sl(p);if(!Fn(b)&&!isNaN(b)){const M=i.valueAsNumber||b&&+b;Fn(U.value)||(G=M>U.value),Fn(ne.value)||(se=Mnew Date(new Date().toDateString()+" "+W),H=i.type=="time",X=i.type=="week";Wo(U.value)&&b&&(G=H?ee(b)>ee(U.value):X?b>U.value:M>new Date(U.value)),Wo(ne.value)&&b&&(se=H?ee(b)+G.value,ne=!Fn(se.value)&&b.length<+se.value;if((U||ne)&&(J(U,G.message,se.message),!n))return R(P[x].message),P}if(g&&!B&&Wo(b)){const{value:G,message:se}=sl(g);if(Kp(G)&&!b.match(G)&&(P[x]={type:ui.pattern,message:se,ref:i,...V(ui.pattern,se)},!n))return R(se),P}if(y){if(ms(y)){const G=await y(b,t),se=k2(G,C);if(se&&(P[x]={...se,...V(ui.validate,se.message)},!n))return R(se.message),P}else if(sn(y)){let G={};for(const se in y){if(!Fr(G)&&!n)break;const U=k2(await y[se](b,t),C,se);U&&(G={...U,...V(se,U.message)},R(U.message),n&&(P[x]=G))}if(!Fr(G)&&(P[x]={ref:C,...G},!n))return P}}return R(!0),P};function jY(e,t){const n=t.slice(0,-1).length;let r=0;for(;r{for(const i of e)i.next&&i.next(o)},subscribe:o=>(e.push(o),{unsubscribe:()=>{e=e.filter(i=>i!==o)}}),unsubscribe:()=>{e=[]}}}var Gp=e=>Fn(e)||!z3(e);function ma(e,t){if(Gp(e)||Gp(t))return e===t;if($l(e)&&$l(t))return e.getTime()===t.getTime();const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(const o of n){const i=e[o];if(!r.includes(o))return!1;if(o!=="ref"){const s=t[o];if($l(i)&&$l(s)||sn(i)&&sn(s)||Array.isArray(i)&&Array.isArray(s)?!ma(i,s):i!==s)return!1}}return!0}var Q3=e=>e.type==="select-multiple",BY=e=>Zx(e)||Gd(e),D0=e=>Hp(e)&&e.isConnected,J3=e=>{for(const t in e)if(ms(e[t]))return!0;return!1};function Yp(e,t={}){const n=Array.isArray(e);if(sn(e)||n)for(const r in e)Array.isArray(e[r])||sn(e[r])&&!J3(e[r])?(t[r]=Array.isArray(e[r])?[]:{},Yp(e[r],t[r])):Fn(e[r])||(t[r]=!0);return t}function eP(e,t,n){const r=Array.isArray(e);if(sn(e)||r)for(const o in e)Array.isArray(e[o])||sn(e[o])&&!J3(e[o])?Ht(t)||Gp(n[o])?n[o]=Array.isArray(e[o])?Yp(e[o],[]):{...Yp(e[o])}:eP(e[o],Fn(t)?{}:t[o],n[o]):n[o]=!ma(e[o],t[o]);return n}var I0=(e,t)=>eP(e,t,Yp(t)),tP=(e,{valueAsNumber:t,valueAsDate:n,setValueAs:r})=>Ht(e)?e:t?e===""?NaN:e&&+e:n&&Wo(e)?new Date(e):r?r(e):e;function L0(e){const t=e.ref;if(!(e.refs?e.refs.every(n=>n.disabled):t.disabled))return Xx(t)?t.files:Zx(t)?q3(e.refs).value:Q3(t)?[...t.selectedOptions].map(({value:n})=>n):Gd(t)?Z3(e.refs).value:tP(Ht(t.value)?e.ref.value:t.value,e)}var UY=(e,t,n,r)=>{const o={};for(const i of e){const s=ve(t,i);s&&wt(o,i,s._f)}return{criteriaMode:n,names:[...e],fields:o,shouldUseNativeValidation:r}},du=e=>Ht(e)?e:Kp(e)?e.source:sn(e)?Kp(e.value)?e.value.source:e.value:e,VY=e=>e.mount&&(e.required||e.min||e.max||e.maxLength||e.minLength||e.pattern||e.validate);function P2(e,t,n){const r=ve(e,n);if(r||Yx(n))return{error:r,name:n};const o=n.split(".");for(;o.length;){const i=o.join("."),s=ve(t,i),l=ve(e,i);if(s&&!Array.isArray(s)&&n!==i)return{name:n};if(l&&l.type)return{name:i,error:l};o.pop()}return{name:n}}var WY=(e,t,n,r,o)=>o.isOnAll?!1:!n&&o.isOnTouch?!(t||e):(n?r.isOnBlur:o.isOnBlur)?!e:(n?r.isOnChange:o.isOnChange)?e:!0,HY=(e,t)=>!Yd(ve(e,t)).length&&pn(e,t);const KY={mode:mo.onSubmit,reValidateMode:mo.onChange,shouldFocusError:!0};function GY(e={},t){let n={...KY,...e},r={submitCount:0,isDirty:!1,isLoading:ms(n.defaultValues),isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},errors:{},disabled:!1},o={},i=sn(n.defaultValues)||sn(n.values)?so(n.defaultValues||n.values)||{}:{},s=n.shouldUnregister?{}:so(i),l={action:!1,mount:!1,watch:!1},u={mount:new Set,unMount:new Set,array:new Set,watch:new Set},f,p=0;const m={isDirty:!1,dirtyFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1},g={values:N0(),array:N0(),state:N0()},y=e.resetOptions&&e.resetOptions.keepDirtyValues,x=_2(n.mode),S=_2(n.reValidateMode),E=n.criteriaMode===mo.all,_=L=>Z=>{clearTimeout(p),p=setTimeout(L,Z)},b=async L=>{if(m.isValid||L){const Z=n.resolver?Fr((await B()).errors):await J(o,!0);Z!==r.isValid&&g.state.next({isValid:Z})}},C=L=>m.isValidating&&g.state.next({isValidating:L}),R=(L,Z=[],q,we,me=!0,de=!0)=>{if(we&&q){if(l.action=!0,de&&Array.isArray(ve(o,L))){const ke=q(ve(o,L),we.argA,we.argB);me&&wt(o,L,ke)}if(de&&Array.isArray(ve(r.errors,L))){const ke=q(ve(r.errors,L),we.argA,we.argB);me&&wt(r.errors,L,ke),HY(r.errors,L)}if(m.touchedFields&&de&&Array.isArray(ve(r.touchedFields,L))){const ke=q(ve(r.touchedFields,L),we.argA,we.argB);me&&wt(r.touchedFields,L,ke)}m.dirtyFields&&(r.dirtyFields=I0(i,s)),g.state.next({name:L,isDirty:se(L,Z),dirtyFields:r.dirtyFields,errors:r.errors,isValid:r.isValid})}else wt(s,L,Z)},P=(L,Z)=>{wt(r.errors,L,Z),g.state.next({errors:r.errors})},O=(L,Z,q,we)=>{const me=ve(o,L);if(me){const de=ve(s,L,Ht(q)?ve(i,L):q);Ht(de)||we&&we.defaultChecked||Z?wt(s,L,Z?de:L0(me._f)):M(L,de),l.mount&&b()}},A=(L,Z,q,we,me)=>{let de=!1,ke=!1;const ft={name:L};if(!q||we){m.isDirty&&(ke=r.isDirty,r.isDirty=ft.isDirty=se(),de=ke!==ft.isDirty);const ht=ma(ve(i,L),Z);ke=ve(r.dirtyFields,L),ht?pn(r.dirtyFields,L):wt(r.dirtyFields,L,!0),ft.dirtyFields=r.dirtyFields,de=de||m.dirtyFields&&ke!==!ht}if(q){const ht=ve(r.touchedFields,L);ht||(wt(r.touchedFields,L,q),ft.touchedFields=r.touchedFields,de=de||m.touchedFields&&ht!==q)}return de&&me&&g.state.next(ft),de?ft:{}},D=(L,Z,q,we)=>{const me=ve(r.errors,L),de=m.isValid&&Fo(Z)&&r.isValid!==Z;if(e.delayError&&q?(f=_(()=>P(L,q)),f(e.delayError)):(clearTimeout(p),f=null,q?wt(r.errors,L,q):pn(r.errors,L)),(q?!ma(me,q):me)||!Fr(we)||de){const ke={...we,...de&&Fo(Z)?{isValid:Z}:{},errors:r.errors,name:L};r={...r,...ke},g.state.next(ke)}C(!1)},B=async L=>n.resolver(s,n.context,UY(L||u.mount,o,n.criteriaMode,n.shouldUseNativeValidation)),V=async L=>{const{errors:Z}=await B(L);if(L)for(const q of L){const we=ve(Z,q);we?wt(r.errors,q,we):pn(r.errors,q)}else r.errors=Z;return Z},J=async(L,Z,q={valid:!0})=>{for(const we in L){const me=L[we];if(me){const{_f:de,...ke}=me;if(de){const ft=u.array.has(de.name),ht=await T2(me,s,E,n.shouldUseNativeValidation&&!Z,ft);if(ht[de.name]&&(q.valid=!1,Z))break;!Z&&(ve(ht,de.name)?ft?FY(r.errors,ht,de.name):wt(r.errors,de.name,ht[de.name]):pn(r.errors,de.name))}ke&&await J(ke,Z,q)}}return q.valid},G=()=>{for(const L of u.unMount){const Z=ve(o,L);Z&&(Z._f.refs?Z._f.refs.every(q=>!D0(q)):!D0(Z._f.ref))&&fe(L)}u.unMount=new Set},se=(L,Z)=>(L&&Z&&wt(s,L,Z),!ma(pe(),i)),U=(L,Z,q)=>G3(L,u,{...l.mount?s:Ht(Z)?i:Wo(L)?{[L]:Z}:Z},q,Z),ne=L=>Yd(ve(l.mount?s:i,L,e.shouldUnregister?ve(i,L,[]):[])),M=(L,Z,q={})=>{const we=ve(o,L);let me=Z;if(we){const de=we._f;de&&(!de.disabled&&wt(s,L,tP(Z,de)),me=Hp(de.ref)&&Fn(Z)?"":Z,Q3(de.ref)?[...de.ref.options].forEach(ke=>ke.selected=me.includes(ke.value)):de.refs?Gd(de.ref)?de.refs.length>1?de.refs.forEach(ke=>(!ke.defaultChecked||!ke.disabled)&&(ke.checked=Array.isArray(me)?!!me.find(ft=>ft===ke.value):me===ke.value)):de.refs[0]&&(de.refs[0].checked=!!me):de.refs.forEach(ke=>ke.checked=ke.value===me):Xx(de.ref)?de.ref.value="":(de.ref.value=me,de.ref.type||g.values.next({name:L,values:{...s}})))}(q.shouldDirty||q.shouldTouch)&&A(L,me,q.shouldTouch,q.shouldDirty,!0),q.shouldValidate&&le(L)},ee=(L,Z,q)=>{for(const we in Z){const me=Z[we],de=`${L}.${we}`,ke=ve(o,de);(u.array.has(L)||!Gp(me)||ke&&!ke._f)&&!$l(me)?ee(de,me,q):M(de,me,q)}},H=(L,Z,q={})=>{const we=ve(o,L),me=u.array.has(L),de=so(Z);wt(s,L,de),me?(g.array.next({name:L,values:{...s}}),(m.isDirty||m.dirtyFields)&&q.shouldDirty&&g.state.next({name:L,dirtyFields:I0(i,s),isDirty:se(L,de)})):we&&!we._f&&!Fn(de)?ee(L,de,q):M(L,de,q),E2(L,u)&&g.state.next({...r}),g.values.next({name:L,values:{...s}}),!l.mount&&t()},X=async L=>{const Z=L.target;let q=Z.name,we=!0;const me=ve(o,q),de=()=>Z.type?L0(me._f):B3(L),ke=ft=>{we=Number.isNaN(ft)||ft===ve(s,q,ft)};if(me){let ft,ht;const _n=de(),Cr=L.type===Wp.BLUR||L.type===Wp.FOCUS_OUT,Ni=!VY(me._f)&&!n.resolver&&!ve(r.errors,q)&&!me._f.deps||WY(Cr,ve(r.touchedFields,q),r.isSubmitted,S,x),Co=E2(q,u,Cr);wt(s,q,_n),Cr?(me._f.onBlur&&me._f.onBlur(L),f&&f(0)):me._f.onChange&&me._f.onChange(L);const Vn=A(q,_n,Cr,!1),Ba=!Fr(Vn)||Co;if(!Cr&&g.values.next({name:q,type:L.type,values:{...s}}),Ni)return m.isValid&&b(),Ba&&g.state.next({name:q,...Co?{}:Vn});if(!Cr&&Co&&g.state.next({...r}),C(!0),n.resolver){const{errors:Di}=await B([q]);if(ke(_n),we){const Ws=P2(r.errors,o,q),Ii=P2(Di,o,Ws.name||q);ft=Ii.error,q=Ii.name,ht=Fr(Di)}}else ft=(await T2(me,s,E,n.shouldUseNativeValidation))[q],ke(_n),we&&(ft?ht=!1:m.isValid&&(ht=await J(o,!0)));we&&(me._f.deps&&le(me._f.deps),D(q,ht,ft,Vn))}},W=(L,Z)=>{if(ve(r.errors,Z)&&L.focus)return L.focus(),1},le=async(L,Z={})=>{let q,we;const me=ep(L);if(C(!0),n.resolver){const de=await V(Ht(L)?L:me);q=Fr(de),we=L?!me.some(ke=>ve(de,ke)):q}else L?(we=(await Promise.all(me.map(async de=>{const ke=ve(o,de);return await J(ke&&ke._f?{[de]:ke}:ke)}))).every(Boolean),!(!we&&!r.isValid)&&b()):we=q=await J(o);return g.state.next({...!Wo(L)||m.isValid&&q!==r.isValid?{}:{name:L},...n.resolver||!L?{isValid:q}:{},errors:r.errors,isValidating:!1}),Z.shouldFocus&&!we&&tp(o,W,L?me:u.mount),we},pe=L=>{const Z={...i,...l.mount?s:{}};return Ht(L)?Z:Wo(L)?ve(Z,L):L.map(q=>ve(Z,q))},$e=(L,Z)=>({invalid:!!ve((Z||r).errors,L),isDirty:!!ve((Z||r).dirtyFields,L),isTouched:!!ve((Z||r).touchedFields,L),error:ve((Z||r).errors,L)}),Ve=L=>{L&&ep(L).forEach(Z=>pn(r.errors,Z)),g.state.next({errors:L?r.errors:{}})},We=(L,Z,q)=>{const we=(ve(o,L,{_f:{}})._f||{}).ref;wt(r.errors,L,{...Z,ref:we}),g.state.next({name:L,errors:r.errors,isValid:!1}),q&&q.shouldFocus&&we&&we.focus&&we.focus()},Ne=(L,Z)=>ms(L)?g.values.subscribe({next:q=>L(U(void 0,Z),q)}):U(L,Z,!0),fe=(L,Z={})=>{for(const q of L?ep(L):u.mount)u.mount.delete(q),u.array.delete(q),Z.keepValue||(pn(o,q),pn(s,q)),!Z.keepError&&pn(r.errors,q),!Z.keepDirty&&pn(r.dirtyFields,q),!Z.keepTouched&&pn(r.touchedFields,q),!n.shouldUnregister&&!Z.keepDefaultValue&&pn(i,q);g.values.next({values:{...s}}),g.state.next({...r,...Z.keepDirty?{isDirty:se()}:{}}),!Z.keepIsValid&&b()},xe=({disabled:L,name:Z,field:q,fields:we,value:me})=>{if(Fo(L)){const de=L?void 0:Ht(me)?L0(q?q._f:ve(we,Z)._f):me;wt(s,Z,de),A(Z,de,!1,!1,!0)}},Re=(L,Z={})=>{let q=ve(o,L);const we=Fo(Z.disabled);return wt(o,L,{...q||{},_f:{...q&&q._f?q._f:{ref:{name:L}},name:L,mount:!0,...Z}}),u.mount.add(L),q?xe({field:q,disabled:Z.disabled,name:L}):O(L,!0,Z.value),{...we?{disabled:Z.disabled}:{},...n.progressive?{required:!!Z.required,min:du(Z.min),max:du(Z.max),minLength:du(Z.minLength),maxLength:du(Z.maxLength),pattern:du(Z.pattern)}:{},name:L,onChange:X,onBlur:X,ref:me=>{if(me){Re(L,Z),q=ve(o,L);const de=Ht(me.value)&&me.querySelectorAll&&me.querySelectorAll("input,select,textarea")[0]||me,ke=BY(de),ft=q._f.refs||[];if(ke?ft.find(ht=>ht===de):de===q._f.ref)return;wt(o,L,{_f:{...q._f,...ke?{refs:[...ft.filter(D0),de,...Array.isArray(ve(i,L))?[{}]:[]],ref:{type:de.type,name:L}}:{ref:de}}}),O(L,!1,void 0,de)}else q=ve(o,L,{}),q._f&&(q._f.mount=!1),(n.shouldUnregister||Z.shouldUnregister)&&!(U3(u.array,L)&&l.action)&&u.unMount.add(L)}}},Me=()=>n.shouldFocusError&&tp(o,W,u.mount),Oe=L=>{Fo(L)&&(g.state.next({disabled:L}),tp(o,Z=>{Z.disabled=L},0,!1))},ze=(L,Z)=>async q=>{q&&(q.preventDefault&&q.preventDefault(),q.persist&&q.persist());let we=so(s);if(g.state.next({isSubmitting:!0}),n.resolver){const{errors:me,values:de}=await B();r.errors=me,we=de}else await J(o);pn(r.errors,"root"),Fr(r.errors)?(g.state.next({errors:{}}),await L(we,q)):(Z&&await Z({...r.errors},q),Me(),setTimeout(Me)),g.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:Fr(r.errors),submitCount:r.submitCount+1,errors:r.errors})},Mt=(L,Z={})=>{ve(o,L)&&(Ht(Z.defaultValue)?H(L,ve(i,L)):(H(L,Z.defaultValue),wt(i,L,Z.defaultValue)),Z.keepTouched||pn(r.touchedFields,L),Z.keepDirty||(pn(r.dirtyFields,L),r.isDirty=Z.defaultValue?se(L,ve(i,L)):se()),Z.keepError||(pn(r.errors,L),m.isValid&&b()),g.state.next({...r}))},ct=(L,Z={})=>{const q=L?so(L):i,we=so(q),me=L&&!Fr(L)?we:i;if(Z.keepDefaultValues||(i=q),!Z.keepValues){if(Z.keepDirtyValues||y)for(const de of u.mount)ve(r.dirtyFields,de)?wt(me,de,ve(s,de)):H(de,ve(me,de));else{if(Kx&&Ht(L))for(const de of u.mount){const ke=ve(o,de);if(ke&&ke._f){const ft=Array.isArray(ke._f.refs)?ke._f.refs[0]:ke._f.ref;if(Hp(ft)){const ht=ft.closest("form");if(ht){ht.reset();break}}}}o={}}s=e.shouldUnregister?Z.keepDefaultValues?so(i):{}:so(me),g.array.next({values:{...me}}),g.values.next({values:{...me}})}u={mount:new Set,unMount:new Set,array:new Set,watch:new Set,watchAll:!1,focus:""},!l.mount&&t(),l.mount=!m.isValid||!!Z.keepIsValid,l.watch=!!e.shouldUnregister,g.state.next({submitCount:Z.keepSubmitCount?r.submitCount:0,isDirty:Z.keepDirty?r.isDirty:!!(Z.keepDefaultValues&&!ma(L,i)),isSubmitted:Z.keepIsSubmitted?r.isSubmitted:!1,dirtyFields:Z.keepDirtyValues?r.dirtyFields:Z.keepDefaultValues&&L?I0(i,L):{},touchedFields:Z.keepTouched?r.touchedFields:{},errors:Z.keepErrors?r.errors:{},isSubmitSuccessful:Z.keepIsSubmitSuccessful?r.isSubmitSuccessful:!1,isSubmitting:!1})},Kt=(L,Z)=>ct(ms(L)?L(s):L,Z);return{control:{register:Re,unregister:fe,getFieldState:$e,handleSubmit:ze,setError:We,_executeSchema:B,_getWatch:U,_getDirty:se,_updateValid:b,_removeUnmounted:G,_updateFieldArray:R,_updateDisabledField:xe,_getFieldArray:ne,_reset:ct,_resetDefaultValues:()=>ms(n.defaultValues)&&n.defaultValues().then(L=>{Kt(L,n.resetOptions),g.state.next({isLoading:!1})}),_updateFormState:L=>{r={...r,...L}},_disableForm:Oe,_subjects:g,_proxyFormState:m,get _fields(){return o},get _formValues(){return s},get _state(){return l},set _state(L){l=L},get _defaultValues(){return i},get _names(){return u},set _names(L){u=L},get _formState(){return r},set _formState(L){r=L},get _options(){return n},set _options(L){n={...n,...L}}},trigger:le,register:Re,handleSubmit:ze,watch:Ne,setValue:H,getValues:pe,reset:Kt,resetField:Mt,clearErrors:Ve,unregister:fe,setError:We,setFocus:(L,Z={})=>{const q=ve(o,L),we=q&&q._f;if(we){const me=we.refs?we.refs[0]:we.ref;me.focus&&(me.focus(),Z.shouldSelect&&me.select())}},getFieldState:$e}}function YY(e={}){const t=je.useRef(),n=je.useRef(),[r,o]=je.useState({isDirty:!1,isValidating:!1,isLoading:ms(e.defaultValues),isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,submitCount:0,dirtyFields:{},touchedFields:{},errors:{},disabled:!1,defaultValues:ms(e.defaultValues)?void 0:e.defaultValues});t.current||(t.current={...GY(e,()=>o(s=>({...s}))),formState:r});const i=t.current.control;return i._options=e,Gx({subject:i._subjects.state,next:s=>{H3(s,i._proxyFormState,i._updateFormState,!0)&&o({...i._formState})}}),je.useEffect(()=>i._disableForm(e.disabled),[i,e.disabled]),je.useEffect(()=>{if(i._proxyFormState.isDirty){const s=i._getDirty();s!==r.isDirty&&i._subjects.state.next({isDirty:s})}},[i,r.isDirty]),je.useEffect(()=>{e.values&&!ma(e.values,n.current)?(i._reset(e.values,i._options.resetOptions),n.current=e.values):i._resetDefaultValues()},[e.values,i]),je.useEffect(()=>{i._state.mount||(i._updateValid(),i._state.mount=!0),i._state.watch&&(i._state.watch=!1,i._subjects.state.next({...i._formState})),i._removeUnmounted()}),t.current.formState=W3(r,i),t.current}var A2=function(e,t,n){if(e&&"reportValidity"in e){var r=ve(n,t);e.setCustomValidity(r&&r.message||""),e.reportValidity()}},nP=function(e,t){var n=function(o){var i=t.fields[o];i&&i.ref&&"reportValidity"in i.ref?A2(i.ref,o,e):i.refs&&i.refs.forEach(function(s){return A2(s,o,e)})};for(var r in t.fields)n(r)},XY=function(e,t){t.shouldUseNativeValidation&&nP(e,t);var n={};for(var r in e){var o=ve(t.fields,r),i=Object.assign(e[r]||{},{ref:o&&o.ref});if(qY(t.names||Object.keys(e),r)){var s=Object.assign({},ZY(ve(n,r)));wt(s,"root",i),wt(n,r,s)}else wt(n,r,i)}return n},ZY=function(e){return Array.isArray(e)?e.filter(Boolean):[]},qY=function(e,t){return e.some(function(n){return n.startsWith(t+".")})},QY=function(e,t){for(var n={};e.length;){var r=e[0],o=r.code,i=r.message,s=r.path.join(".");if(!n[s])if("unionErrors"in r){var l=r.unionErrors[0].errors[0];n[s]={message:l.message,type:l.code}}else n[s]={message:i,type:o};if("unionErrors"in r&&r.unionErrors.forEach(function(p){return p.errors.forEach(function(m){return e.push(m)})}),t){var u=n[s].types,f=u&&u[r.code];n[s]=X3(s,t,n,o,f?[].concat(f,r.message):r.message)}e.shift()}return n},JY=function(e,t,n){return n===void 0&&(n={}),function(r,o,i){try{return Promise.resolve(function(s,l){try{var u=Promise.resolve(e[n.mode==="sync"?"parse":"parseAsync"](r,t)).then(function(f){return i.shouldUseNativeValidation&&nP({},i),{errors:{},values:n.raw?r:f}})}catch(f){return l(f)}return u&&u.then?u.then(void 0,l):u}(0,function(s){if(function(l){return l.errors!=null}(s))return{values:{},errors:XY(QY(s.errors,!i.shouldUseNativeValidation&&i.criteriaMode==="all"),i)};throw s}))}catch(s){return Promise.reject(s)}}},mt;(function(e){e.assertEqual=o=>o;function t(o){}e.assertIs=t;function n(o){throw new Error}e.assertNever=n,e.arrayToEnum=o=>{const i={};for(const s of o)i[s]=s;return i},e.getValidEnumValues=o=>{const i=e.objectKeys(o).filter(l=>typeof o[o[l]]!="number"),s={};for(const l of i)s[l]=o[l];return e.objectValues(s)},e.objectValues=o=>e.objectKeys(o).map(function(i){return o[i]}),e.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{const i=[];for(const s in o)Object.prototype.hasOwnProperty.call(o,s)&&i.push(s);return i},e.find=(o,i)=>{for(const s of o)if(i(s))return s},e.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&isFinite(o)&&Math.floor(o)===o;function r(o,i=" | "){return o.map(s=>typeof s=="string"?`'${s}'`:s).join(i)}e.joinValues=r,e.jsonStringifyReplacer=(o,i)=>typeof i=="bigint"?i.toString():i})(mt||(mt={}));var M2;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(M2||(M2={}));const be=mt.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ca=e=>{switch(typeof e){case"undefined":return be.undefined;case"string":return be.string;case"number":return isNaN(e)?be.nan:be.number;case"boolean":return be.boolean;case"function":return be.function;case"bigint":return be.bigint;case"symbol":return be.symbol;case"object":return Array.isArray(e)?be.array:e===null?be.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?be.promise:typeof Map<"u"&&e instanceof Map?be.map:typeof Set<"u"&&e instanceof Set?be.set:typeof Date<"u"&&e instanceof Date?be.date:be.object;default:return be.unknown}},he=mt.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"]);class Go 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(i){return i.message},r={_errors:[]},o=i=>{for(const s of i.issues)if(s.code==="invalid_union")s.unionErrors.map(o);else if(s.code==="invalid_return_type")o(s.returnTypeError);else if(s.code==="invalid_arguments")o(s.argumentsError);else if(s.path.length===0)r._errors.push(n(s));else{let l=r,u=0;for(;un.message){const n={},r=[];for(const o of this.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(t(o))):r.push(t(o));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}}Go.create=e=>new Go(e);const Xp=(e,t)=>{let n;switch(e.code){case he.invalid_type:e.received===be.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case he.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,mt.jsonStringifyReplacer)}`;break;case he.unrecognized_keys:n=`Unrecognized key(s) in object: ${mt.joinValues(e.keys,", ")}`;break;case he.invalid_union:n="Invalid input";break;case he.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${mt.joinValues(e.options)}`;break;case he.invalid_enum_value:n=`Invalid enum value. Expected ${mt.joinValues(e.options)}, received '${e.received}'`;break;case he.invalid_arguments:n="Invalid function arguments";break;case he.invalid_return_type:n="Invalid function return type";break;case he.invalid_date:n="Invalid date";break;case he.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}"`:mt.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case he.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 he.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 he.custom:n="Invalid input";break;case he.invalid_intersection_types:n="Intersection results could not be merged";break;case he.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case he.not_finite:n="Number must be finite";break;default:n=t.defaultError,mt.assertNever(e)}return{message:n}};let eX=Xp;function C1(){return eX}const $1=e=>{const{data:t,path:n,errorMaps:r,issueData:o}=e,i=[...n,...o.path||[]],s={...o,path:i};let l="";const u=r.filter(f=>!!f).slice().reverse();for(const f of u)l=f(s,{data:t,defaultError:l}).message;return{...o,path:i,message:o.message||l}};function Ce(e,t){const n=$1({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,C1(),Xp].filter(r=>!!r)});e.common.issues.push(n)}class zn{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 o of n){if(o.status==="aborted")return Ze;o.status==="dirty"&&t.dirty(),r.push(o.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){const r=[];for(const o of n)r.push({key:await o.key,value:await o.value});return zn.mergeObjectSync(t,r)}static mergeObjectSync(t,n){const r={};for(const o of n){const{key:i,value:s}=o;if(i.status==="aborted"||s.status==="aborted")return Ze;i.status==="dirty"&&t.dirty(),s.status==="dirty"&&t.dirty(),i.value!=="__proto__"&&(typeof s.value<"u"||o.alwaysSet)&&(r[i.value]=s.value)}return{status:t.value,value:r}}}const Ze=Object.freeze({status:"aborted"}),tX=e=>({status:"dirty",value:e}),rr=e=>({status:"valid",value:e}),O2=e=>e.status==="aborted",N2=e=>e.status==="dirty",Zp=e=>e.status==="valid",R1=e=>typeof Promise<"u"&&e instanceof Promise;var De;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t==null?void 0:t.message})(De||(De={}));class Qo{constructor(t,n,r,o){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=o}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 D2=(e,t)=>{if(Zp(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 Go(e.common.issues);return this._error=n,this._error}}};function Xe(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:r,description:o}=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:o}:{errorMap:(s,l)=>s.code!=="invalid_type"?{message:l.defaultError}:typeof l.data>"u"?{message:r??l.defaultError}:{message:n??l.defaultError},description:o}}class rt{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.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this)}get description(){return this._def.description}_getType(t){return ca(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:ca(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new zn,ctx:{common:t.parent.common,data:t.data,parsedType:ca(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const n=this._parse(t);if(R1(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 o={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:ca(t)},i=this._parseSync({data:t,path:o.path,parent:o});return D2(o,i)}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:ca(t)},o=this._parse({data:t,path:r.path,parent:r}),i=await(R1(o)?o:Promise.resolve(o));return D2(r,i)}refine(t,n){const r=o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n;return this._refinement((o,i)=>{const s=t(o),l=()=>i.addIssue({code:he.custom,...r(o)});return typeof Promise<"u"&&s instanceof Promise?s.then(u=>u?!0:(l(),!1)):s?!0:(l(),!1)})}refinement(t,n){return this._refinement((r,o)=>t(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(t){return new Pi({schema:this,typeName:Be.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}optional(){return Cs.create(this,this._def)}nullable(){return gc.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Yo.create(this,this._def)}promise(){return pd.create(this,this._def)}or(t){return Jp.create([this,t],this._def)}and(t){return em.create(this,t,this._def)}transform(t){return new Pi({...Xe(this._def),schema:this,typeName:Be.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const n=typeof t=="function"?t:()=>t;return new im({...Xe(this._def),innerType:this,defaultValue:n,typeName:Be.ZodDefault})}brand(){return new hX({typeName:Be.ZodBranded,type:this,...Xe(this._def)})}catch(t){const n=typeof t=="function"?t:()=>t;return new N1({...Xe(this._def),innerType:this,catchValue:n,typeName:Be.ZodCatch})}describe(t){const n=this.constructor;return new n({...this._def,description:t})}pipe(t){return ug.create(this,t)}readonly(){return I1.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const nX=/^c[^\s-]{8,}$/i,rX=/^[a-z][a-z0-9]*$/,oX=/^[0-9A-HJKMNP-TV-Z]{26}$/,iX=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,sX=/^(?!\.)(?!.*\.\.)([A-Z0-9_+-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,aX="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let F0;const lX=/^(((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}))$/,cX=/^(([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})))$/,uX=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 dX(e,t){return!!((t==="v4"||!t)&&lX.test(e)||(t==="v6"||!t)&&cX.test(e))}class yi extends rt{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==be.string){const i=this._getOrReturnCtx(t);return Ce(i,{code:he.invalid_type,expected:be.string,received:i.parsedType}),Ze}const r=new zn;let o;for(const i of this._def.checks)if(i.kind==="min")t.data.lengthi.value&&(o=this._getOrReturnCtx(t,o),Ce(o,{code:he.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){const s=t.data.length>i.value,l=t.data.lengtht.test(o),{validation:n,code:he.invalid_string,...De.errToObj(r)})}_addCheck(t){return new yi({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...De.errToObj(t)})}url(t){return this._addCheck({kind:"url",...De.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...De.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...De.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...De.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...De.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...De.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...De.errToObj(t)})}datetime(t){var n;return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof(t==null?void 0:t.precision)>"u"?null:t==null?void 0:t.precision,offset:(n=t==null?void 0:t.offset)!==null&&n!==void 0?n:!1,...De.errToObj(t==null?void 0:t.message)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...De.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n==null?void 0:n.position,...De.errToObj(n==null?void 0:n.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...De.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...De.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...De.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...De.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...De.errToObj(n)})}nonempty(t){return this.min(1,De.errToObj(t))}trim(){return new yi({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new yi({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new yi({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}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 yi({checks:[],typeName:Be.ZodString,coerce:(t=e==null?void 0:e.coerce)!==null&&t!==void 0?t:!1,...Xe(e)})};function fX(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,o=n>r?n:r,i=parseInt(e.toFixed(o).replace(".","")),s=parseInt(t.toFixed(o).replace(".",""));return i%s/Math.pow(10,o)}class hc extends rt{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)!==be.number){const i=this._getOrReturnCtx(t);return Ce(i,{code:he.invalid_type,expected:be.number,received:i.parsedType}),Ze}let r;const o=new zn;for(const i of this._def.checks)i.kind==="int"?mt.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),Ce(r,{code:he.invalid_type,expected:"integer",received:"float",message:i.message}),o.dirty()):i.kind==="min"?(i.inclusive?t.datai.value:t.data>=i.value)&&(r=this._getOrReturnCtx(t,r),Ce(r,{code:he.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),o.dirty()):i.kind==="multipleOf"?fX(t.data,i.value)!==0&&(r=this._getOrReturnCtx(t,r),Ce(r,{code:he.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):i.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),Ce(r,{code:he.not_finite,message:i.message}),o.dirty()):mt.assertNever(i);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,De.toString(n))}gt(t,n){return this.setLimit("min",t,!1,De.toString(n))}lte(t,n){return this.setLimit("max",t,!0,De.toString(n))}lt(t,n){return this.setLimit("max",t,!1,De.toString(n))}setLimit(t,n,r,o){return new hc({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:De.toString(o)}]})}_addCheck(t){return new hc({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:De.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:De.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:De.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:De.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:De.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:De.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:De.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:De.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:De.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"&&mt.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 hc({checks:[],typeName:Be.ZodNumber,coerce:(e==null?void 0:e.coerce)||!1,...Xe(e)});class pc extends rt{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)!==be.bigint){const i=this._getOrReturnCtx(t);return Ce(i,{code:he.invalid_type,expected:be.bigint,received:i.parsedType}),Ze}let r;const o=new zn;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?t.datai.value:t.data>=i.value)&&(r=this._getOrReturnCtx(t,r),Ce(r,{code:he.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),o.dirty()):i.kind==="multipleOf"?t.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),Ce(r,{code:he.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):mt.assertNever(i);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,De.toString(n))}gt(t,n){return this.setLimit("min",t,!1,De.toString(n))}lte(t,n){return this.setLimit("max",t,!0,De.toString(n))}lt(t,n){return this.setLimit("max",t,!1,De.toString(n))}setLimit(t,n,r,o){return new pc({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:De.toString(o)}]})}_addCheck(t){return new pc({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:De.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:De.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:De.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:De.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:De.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 pc({checks:[],typeName:Be.ZodBigInt,coerce:(t=e==null?void 0:e.coerce)!==null&&t!==void 0?t:!1,...Xe(e)})};class k1 extends rt{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==be.boolean){const r=this._getOrReturnCtx(t);return Ce(r,{code:he.invalid_type,expected:be.boolean,received:r.parsedType}),Ze}return rr(t.data)}}k1.create=e=>new k1({typeName:Be.ZodBoolean,coerce:(e==null?void 0:e.coerce)||!1,...Xe(e)});class hd extends rt{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==be.date){const i=this._getOrReturnCtx(t);return Ce(i,{code:he.invalid_type,expected:be.date,received:i.parsedType}),Ze}if(isNaN(t.data.getTime())){const i=this._getOrReturnCtx(t);return Ce(i,{code:he.invalid_date}),Ze}const r=new zn;let o;for(const i of this._def.checks)i.kind==="min"?t.data.getTime()i.value&&(o=this._getOrReturnCtx(t,o),Ce(o,{code:he.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):mt.assertNever(i);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new hd({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:De.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:De.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 hd({checks:[],coerce:(e==null?void 0:e.coerce)||!1,typeName:Be.ZodDate,...Xe(e)});class T1 extends rt{_parse(t){if(this._getType(t)!==be.symbol){const r=this._getOrReturnCtx(t);return Ce(r,{code:he.invalid_type,expected:be.symbol,received:r.parsedType}),Ze}return rr(t.data)}}T1.create=e=>new T1({typeName:Be.ZodSymbol,...Xe(e)});class qp extends rt{_parse(t){if(this._getType(t)!==be.undefined){const r=this._getOrReturnCtx(t);return Ce(r,{code:he.invalid_type,expected:be.undefined,received:r.parsedType}),Ze}return rr(t.data)}}qp.create=e=>new qp({typeName:Be.ZodUndefined,...Xe(e)});class Qp extends rt{_parse(t){if(this._getType(t)!==be.null){const r=this._getOrReturnCtx(t);return Ce(r,{code:he.invalid_type,expected:be.null,received:r.parsedType}),Ze}return rr(t.data)}}Qp.create=e=>new Qp({typeName:Be.ZodNull,...Xe(e)});class P1 extends rt{constructor(){super(...arguments),this._any=!0}_parse(t){return rr(t.data)}}P1.create=e=>new P1({typeName:Be.ZodAny,...Xe(e)});class Dl extends rt{constructor(){super(...arguments),this._unknown=!0}_parse(t){return rr(t.data)}}Dl.create=e=>new Dl({typeName:Be.ZodUnknown,...Xe(e)});class Ms extends rt{_parse(t){const n=this._getOrReturnCtx(t);return Ce(n,{code:he.invalid_type,expected:be.never,received:n.parsedType}),Ze}}Ms.create=e=>new Ms({typeName:Be.ZodNever,...Xe(e)});class A1 extends rt{_parse(t){if(this._getType(t)!==be.undefined){const r=this._getOrReturnCtx(t);return Ce(r,{code:he.invalid_type,expected:be.void,received:r.parsedType}),Ze}return rr(t.data)}}A1.create=e=>new A1({typeName:Be.ZodVoid,...Xe(e)});class Yo extends rt{_parse(t){const{ctx:n,status:r}=this._processInputParams(t),o=this._def;if(n.parsedType!==be.array)return Ce(n,{code:he.invalid_type,expected:be.array,received:n.parsedType}),Ze;if(o.exactLength!==null){const s=n.data.length>o.exactLength.value,l=n.data.lengtho.maxLength.value&&(Ce(n,{code:he.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((s,l)=>o.type._parseAsync(new Qo(n,s,n.path,l)))).then(s=>zn.mergeArray(r,s));const i=[...n.data].map((s,l)=>o.type._parseSync(new Qo(n,s,n.path,l)));return zn.mergeArray(r,i)}get element(){return this._def.type}min(t,n){return new Yo({...this._def,minLength:{value:t,message:De.toString(n)}})}max(t,n){return new Yo({...this._def,maxLength:{value:t,message:De.toString(n)}})}length(t,n){return new Yo({...this._def,exactLength:{value:t,message:De.toString(n)}})}nonempty(t){return this.min(1,t)}}Yo.create=(e,t)=>new Yo({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Be.ZodArray,...Xe(t)});function dl(e){if(e instanceof Vt){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=Cs.create(dl(r))}return new Vt({...e._def,shape:()=>t})}else return e instanceof Yo?new Yo({...e._def,type:dl(e.element)}):e instanceof Cs?Cs.create(dl(e.unwrap())):e instanceof gc?gc.create(dl(e.unwrap())):e instanceof Ti?Ti.create(e.items.map(t=>dl(t))):e}class Vt extends rt{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=mt.objectKeys(t);return this._cached={shape:t,keys:n}}_parse(t){if(this._getType(t)!==be.object){const f=this._getOrReturnCtx(t);return Ce(f,{code:he.invalid_type,expected:be.object,received:f.parsedType}),Ze}const{status:r,ctx:o}=this._processInputParams(t),{shape:i,keys:s}=this._getCached(),l=[];if(!(this._def.catchall instanceof Ms&&this._def.unknownKeys==="strip"))for(const f in o.data)s.includes(f)||l.push(f);const u=[];for(const f of s){const p=i[f],m=o.data[f];u.push({key:{status:"valid",value:f},value:p._parse(new Qo(o,m,o.path,f)),alwaysSet:f in o.data})}if(this._def.catchall instanceof Ms){const f=this._def.unknownKeys;if(f==="passthrough")for(const p of l)u.push({key:{status:"valid",value:p},value:{status:"valid",value:o.data[p]}});else if(f==="strict")l.length>0&&(Ce(o,{code:he.unrecognized_keys,keys:l}),r.dirty());else if(f!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const f=this._def.catchall;for(const p of l){const m=o.data[p];u.push({key:{status:"valid",value:p},value:f._parse(new Qo(o,m,o.path,p)),alwaysSet:p in o.data})}}return o.common.async?Promise.resolve().then(async()=>{const f=[];for(const p of u){const m=await p.key;f.push({key:m,value:await p.value,alwaysSet:p.alwaysSet})}return f}).then(f=>zn.mergeObjectSync(r,f)):zn.mergeObjectSync(r,u)}get shape(){return this._def.shape()}strict(t){return De.errToObj,new Vt({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{var o,i,s,l;const u=(s=(i=(o=this._def).errorMap)===null||i===void 0?void 0:i.call(o,n,r).message)!==null&&s!==void 0?s:r.defaultError;return n.code==="unrecognized_keys"?{message:(l=De.errToObj(t).message)!==null&&l!==void 0?l:u}:{message:u}}}:{}})}strip(){return new Vt({...this._def,unknownKeys:"strip"})}passthrough(){return new Vt({...this._def,unknownKeys:"passthrough"})}extend(t){return new Vt({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new Vt({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:Be.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new Vt({...this._def,catchall:t})}pick(t){const n={};return mt.objectKeys(t).forEach(r=>{t[r]&&this.shape[r]&&(n[r]=this.shape[r])}),new Vt({...this._def,shape:()=>n})}omit(t){const n={};return mt.objectKeys(this.shape).forEach(r=>{t[r]||(n[r]=this.shape[r])}),new Vt({...this._def,shape:()=>n})}deepPartial(){return dl(this)}partial(t){const n={};return mt.objectKeys(this.shape).forEach(r=>{const o=this.shape[r];t&&!t[r]?n[r]=o:n[r]=o.optional()}),new Vt({...this._def,shape:()=>n})}required(t){const n={};return mt.objectKeys(this.shape).forEach(r=>{if(t&&!t[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof Cs;)i=i._def.innerType;n[r]=i}}),new Vt({...this._def,shape:()=>n})}keyof(){return rP(mt.objectKeys(this.shape))}}Vt.create=(e,t)=>new Vt({shape:()=>e,unknownKeys:"strip",catchall:Ms.create(),typeName:Be.ZodObject,...Xe(t)});Vt.strictCreate=(e,t)=>new Vt({shape:()=>e,unknownKeys:"strict",catchall:Ms.create(),typeName:Be.ZodObject,...Xe(t)});Vt.lazycreate=(e,t)=>new Vt({shape:e,unknownKeys:"strip",catchall:Ms.create(),typeName:Be.ZodObject,...Xe(t)});class Jp extends rt{_parse(t){const{ctx:n}=this._processInputParams(t),r=this._def.options;function o(i){for(const l of i)if(l.result.status==="valid")return l.result;for(const l of i)if(l.result.status==="dirty")return n.common.issues.push(...l.ctx.common.issues),l.result;const s=i.map(l=>new Go(l.ctx.common.issues));return Ce(n,{code:he.invalid_union,unionErrors:s}),Ze}if(n.common.async)return Promise.all(r.map(async i=>{const s={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:s}),ctx:s}})).then(o);{let i;const s=[];for(const u of r){const f={...n,common:{...n.common,issues:[]},parent:null},p=u._parseSync({data:n.data,path:n.path,parent:f});if(p.status==="valid")return p;p.status==="dirty"&&!i&&(i={result:p,ctx:f}),f.common.issues.length&&s.push(f.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;const l=s.map(u=>new Go(u));return Ce(n,{code:he.invalid_union,unionErrors:l}),Ze}}get options(){return this._def.options}}Jp.create=(e,t)=>new Jp({options:e,typeName:Be.ZodUnion,...Xe(t)});const rp=e=>e instanceof nm?rp(e.schema):e instanceof Pi?rp(e.innerType()):e instanceof rm?[e.value]:e instanceof Da?e.options:e instanceof om?Object.keys(e.enum):e instanceof im?rp(e._def.innerType):e instanceof qp?[void 0]:e instanceof Qp?[null]:null;class qx extends rt{_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.object)return Ce(n,{code:he.invalid_type,expected:be.object,received:n.parsedType}),Ze;const r=this.discriminator,o=n.data[r],i=this.optionsMap.get(o);return i?n.common.async?i._parseAsync({data:n.data,path:n.path,parent:n}):i._parseSync({data:n.data,path:n.path,parent:n}):(Ce(n,{code:he.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),Ze)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){const o=new Map;for(const i of n){const s=rp(i.shape[t]);if(!s)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const l of s){if(o.has(l))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(l)}`);o.set(l,i)}}return new qx({typeName:Be.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:o,...Xe(r)})}}function M1(e,t){const n=ca(e),r=ca(t);if(e===t)return{valid:!0,data:e};if(n===be.object&&r===be.object){const o=mt.objectKeys(t),i=mt.objectKeys(e).filter(l=>o.indexOf(l)!==-1),s={...e,...t};for(const l of i){const u=M1(e[l],t[l]);if(!u.valid)return{valid:!1};s[l]=u.data}return{valid:!0,data:s}}else if(n===be.array&&r===be.array){if(e.length!==t.length)return{valid:!1};const o=[];for(let i=0;i{if(O2(i)||O2(s))return Ze;const l=M1(i.value,s.value);return l.valid?((N2(i)||N2(s))&&n.dirty(),{status:n.value,value:l.data}):(Ce(r,{code:he.invalid_intersection_types}),Ze)};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(([i,s])=>o(i,s)):o(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}em.create=(e,t,n)=>new em({left:e,right:t,typeName:Be.ZodIntersection,...Xe(n)});class Ti extends rt{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.array)return Ce(r,{code:he.invalid_type,expected:be.array,received:r.parsedType}),Ze;if(r.data.lengththis._def.items.length&&(Ce(r,{code:he.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const i=[...r.data].map((s,l)=>{const u=this._def.items[l]||this._def.rest;return u?u._parse(new Qo(r,s,r.path,l)):null}).filter(s=>!!s);return r.common.async?Promise.all(i).then(s=>zn.mergeArray(n,s)):zn.mergeArray(n,i)}get items(){return this._def.items}rest(t){return new Ti({...this._def,rest:t})}}Ti.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ti({items:e,typeName:Be.ZodTuple,rest:null,...Xe(t)})};class tm extends rt{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!==be.object)return Ce(r,{code:he.invalid_type,expected:be.object,received:r.parsedType}),Ze;const o=[],i=this._def.keyType,s=this._def.valueType;for(const l in r.data)o.push({key:i._parse(new Qo(r,l,r.path,l)),value:s._parse(new Qo(r,r.data[l],r.path,l))});return r.common.async?zn.mergeObjectAsync(n,o):zn.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof rt?new tm({keyType:t,valueType:n,typeName:Be.ZodRecord,...Xe(r)}):new tm({keyType:yi.create(),valueType:t,typeName:Be.ZodRecord,...Xe(n)})}}class O1 extends rt{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!==be.map)return Ce(r,{code:he.invalid_type,expected:be.map,received:r.parsedType}),Ze;const o=this._def.keyType,i=this._def.valueType,s=[...r.data.entries()].map(([l,u],f)=>({key:o._parse(new Qo(r,l,r.path,[f,"key"])),value:i._parse(new Qo(r,u,r.path,[f,"value"]))}));if(r.common.async){const l=new Map;return Promise.resolve().then(async()=>{for(const u of s){const f=await u.key,p=await u.value;if(f.status==="aborted"||p.status==="aborted")return Ze;(f.status==="dirty"||p.status==="dirty")&&n.dirty(),l.set(f.value,p.value)}return{status:n.value,value:l}})}else{const l=new Map;for(const u of s){const f=u.key,p=u.value;if(f.status==="aborted"||p.status==="aborted")return Ze;(f.status==="dirty"||p.status==="dirty")&&n.dirty(),l.set(f.value,p.value)}return{status:n.value,value:l}}}}O1.create=(e,t,n)=>new O1({valueType:t,keyType:e,typeName:Be.ZodMap,...Xe(n)});class mc extends rt{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.set)return Ce(r,{code:he.invalid_type,expected:be.set,received:r.parsedType}),Ze;const o=this._def;o.minSize!==null&&r.data.sizeo.maxSize.value&&(Ce(r,{code:he.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());const i=this._def.valueType;function s(u){const f=new Set;for(const p of u){if(p.status==="aborted")return Ze;p.status==="dirty"&&n.dirty(),f.add(p.value)}return{status:n.value,value:f}}const l=[...r.data.values()].map((u,f)=>i._parse(new Qo(r,u,r.path,f)));return r.common.async?Promise.all(l).then(u=>s(u)):s(l)}min(t,n){return new mc({...this._def,minSize:{value:t,message:De.toString(n)}})}max(t,n){return new mc({...this._def,maxSize:{value:t,message:De.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}}mc.create=(e,t)=>new mc({valueType:e,minSize:null,maxSize:null,typeName:Be.ZodSet,...Xe(t)});class Lu extends rt{constructor(){super(...arguments),this.validate=this.implement}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.function)return Ce(n,{code:he.invalid_type,expected:be.function,received:n.parsedType}),Ze;function r(l,u){return $1({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,C1(),Xp].filter(f=>!!f),issueData:{code:he.invalid_arguments,argumentsError:u}})}function o(l,u){return $1({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,C1(),Xp].filter(f=>!!f),issueData:{code:he.invalid_return_type,returnTypeError:u}})}const i={errorMap:n.common.contextualErrorMap},s=n.data;if(this._def.returns instanceof pd){const l=this;return rr(async function(...u){const f=new Go([]),p=await l._def.args.parseAsync(u,i).catch(y=>{throw f.addIssue(r(u,y)),f}),m=await Reflect.apply(s,this,p);return await l._def.returns._def.type.parseAsync(m,i).catch(y=>{throw f.addIssue(o(m,y)),f})})}else{const l=this;return rr(function(...u){const f=l._def.args.safeParse(u,i);if(!f.success)throw new Go([r(u,f.error)]);const p=Reflect.apply(s,this,f.data),m=l._def.returns.safeParse(p,i);if(!m.success)throw new Go([o(p,m.error)]);return m.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new Lu({...this._def,args:Ti.create(t).rest(Dl.create())})}returns(t){return new Lu({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new Lu({args:t||Ti.create([]).rest(Dl.create()),returns:n||Dl.create(),typeName:Be.ZodFunction,...Xe(r)})}}class nm extends rt{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})}}nm.create=(e,t)=>new nm({getter:e,typeName:Be.ZodLazy,...Xe(t)});class rm extends rt{_parse(t){if(t.data!==this._def.value){const n=this._getOrReturnCtx(t);return Ce(n,{received:n.data,code:he.invalid_literal,expected:this._def.value}),Ze}return{status:"valid",value:t.data}}get value(){return this._def.value}}rm.create=(e,t)=>new rm({value:e,typeName:Be.ZodLiteral,...Xe(t)});function rP(e,t){return new Da({values:e,typeName:Be.ZodEnum,...Xe(t)})}class Da extends rt{_parse(t){if(typeof t.data!="string"){const n=this._getOrReturnCtx(t),r=this._def.values;return Ce(n,{expected:mt.joinValues(r),received:n.parsedType,code:he.invalid_type}),Ze}if(this._def.values.indexOf(t.data)===-1){const n=this._getOrReturnCtx(t),r=this._def.values;return Ce(n,{received:n.data,code:he.invalid_enum_value,options:r}),Ze}return rr(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 Da.create(t)}exclude(t){return Da.create(this.options.filter(n=>!t.includes(n)))}}Da.create=rP;class om extends rt{_parse(t){const n=mt.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==be.string&&r.parsedType!==be.number){const o=mt.objectValues(n);return Ce(r,{expected:mt.joinValues(o),received:r.parsedType,code:he.invalid_type}),Ze}if(n.indexOf(t.data)===-1){const o=mt.objectValues(n);return Ce(r,{received:r.data,code:he.invalid_enum_value,options:o}),Ze}return rr(t.data)}get enum(){return this._def.values}}om.create=(e,t)=>new om({values:e,typeName:Be.ZodNativeEnum,...Xe(t)});class pd extends rt{unwrap(){return this._def.type}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.promise&&n.common.async===!1)return Ce(n,{code:he.invalid_type,expected:be.promise,received:n.parsedType}),Ze;const r=n.parsedType===be.promise?n.data:Promise.resolve(n.data);return rr(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}}pd.create=(e,t)=>new pd({type:e,typeName:Be.ZodPromise,...Xe(t)});class Pi extends rt{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Be.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:n,ctx:r}=this._processInputParams(t),o=this._def.effect||null,i={addIssue:s=>{Ce(r,s),s.fatal?n.abort():n.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),o.type==="preprocess"){const s=o.transform(r.data,i);return r.common.issues.length?{status:"dirty",value:r.data}:r.common.async?Promise.resolve(s).then(l=>this._def.schema._parseAsync({data:l,path:r.path,parent:r})):this._def.schema._parseSync({data:s,path:r.path,parent:r})}if(o.type==="refinement"){const s=l=>{const u=o.refinement(l,i);if(r.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return l};if(r.common.async===!1){const l=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return l.status==="aborted"?Ze:(l.status==="dirty"&&n.dirty(),s(l.value),{status:n.value,value:l.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(l=>l.status==="aborted"?Ze:(l.status==="dirty"&&n.dirty(),s(l.value).then(()=>({status:n.value,value:l.value}))))}if(o.type==="transform")if(r.common.async===!1){const s=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Zp(s))return s;const l=o.transform(s.value,i);if(l instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:l}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(s=>Zp(s)?Promise.resolve(o.transform(s.value,i)).then(l=>({status:n.value,value:l})):s);mt.assertNever(o)}}Pi.create=(e,t,n)=>new Pi({schema:e,typeName:Be.ZodEffects,effect:t,...Xe(n)});Pi.createWithPreprocess=(e,t,n)=>new Pi({schema:t,effect:{type:"preprocess",transform:e},typeName:Be.ZodEffects,...Xe(n)});class Cs extends rt{_parse(t){return this._getType(t)===be.undefined?rr(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Cs.create=(e,t)=>new Cs({innerType:e,typeName:Be.ZodOptional,...Xe(t)});class gc extends rt{_parse(t){return this._getType(t)===be.null?rr(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}gc.create=(e,t)=>new gc({innerType:e,typeName:Be.ZodNullable,...Xe(t)});class im extends rt{_parse(t){const{ctx:n}=this._processInputParams(t);let r=n.data;return n.parsedType===be.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}im.create=(e,t)=>new im({innerType:e,typeName:Be.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Xe(t)});class N1 extends rt{_parse(t){const{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return R1(o)?o.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Go(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Go(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}N1.create=(e,t)=>new N1({innerType:e,typeName:Be.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Xe(t)});class D1 extends rt{_parse(t){if(this._getType(t)!==be.nan){const r=this._getOrReturnCtx(t);return Ce(r,{code:he.invalid_type,expected:be.nan,received:r.parsedType}),Ze}return{status:"valid",value:t.data}}}D1.create=e=>new D1({typeName:Be.ZodNaN,...Xe(e)});class hX extends rt{_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 ug extends rt{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?Ze:i.status==="dirty"?(n.dirty(),tX(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{const o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?Ze:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(t,n){return new ug({in:t,out:n,typeName:Be.ZodPipeline})}}class I1 extends rt{_parse(t){const n=this._def.innerType._parse(t);return Zp(n)&&(n.value=Object.freeze(n.value)),n}}I1.create=(e,t)=>new I1({innerType:e,typeName:Be.ZodReadonly,...Xe(t)});Vt.lazycreate;var Be;(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",e.ZodReadonly="ZodReadonly"})(Be||(Be={}));const fu=yi.create;hc.create;D1.create;pc.create;const hu=k1.create;hd.create;T1.create;qp.create;Qp.create;P1.create;Dl.create;Ms.create;A1.create;Yo.create;const pX=Vt.create;Vt.strictCreate;Jp.create;qx.create;em.create;Ti.create;tm.create;O1.create;mc.create;Lu.create;nm.create;rm.create;Da.create;om.create;pd.create;Pi.create;Cs.create;gc.create;Pi.createWithPreprocess;ug.create;const L1="horizontal",mX=["horizontal","vertical"],oP=d.forwardRef((e,t)=>{const{decorative:n,orientation:r=L1,...o}=e,i=iP(r)?r:L1,l=n?{role:"none"}:{"aria-orientation":i==="vertical"?i:void 0,role:"separator"};return d.createElement(Ae.div,Y({"data-orientation":i},l,o,{ref:t}))});oP.propTypes={orientation(e,t,n){const r=e[t],o=String(r);return r&&!iP(r)?new Error(gX(o,n)):null}};function gX(e,t){return`Invalid prop \`orientation\` of value \`${e}\` supplied to \`${t}\`, expected one of: + - horizontal + - vertical + +Defaulting to \`${L1}\`.`}function iP(e){return mX.includes(e)}const sP=oP,gn=d.forwardRef(({className:e,orientation:t="horizontal",decorative:n=!0,...r},o)=>v.jsx(sP,{ref:o,decorative:n,orientation:t,className:_e("shrink-0 bg-border",t==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",e),...r}));gn.displayName=sP.displayName;const vX=d.forwardRef((e,t)=>d.createElement(Ae.label,Y({},e,{ref:t,onMouseDown:n=>{var r;(r=e.onMouseDown)===null||r===void 0||r.call(e,n),!n.defaultPrevented&&n.detail>1&&n.preventDefault()}}))),aP=vX,yX=Dm("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),Qx=d.forwardRef(({className:e,disabled:t,...n},r)=>v.jsx(aP,{ref:r,className:_e(yX(),e,t?"opacity-50":"","select-none"),...n}));Qx.displayName=aP.displayName;const wX=OY,lP=d.createContext({}),al=({...e})=>v.jsx(lP.Provider,{value:{name:e.name},children:v.jsx(LY,{...e})}),dg=()=>{const e=d.useContext(lP),t=d.useContext(cP),{getFieldState:n,formState:r}=cg(),o=n(e.name,r);if(!e)throw new Error("useFormField should be used within ");const{id:i}=t;return{id:i,name:e.name,formItemId:`${i}-form-item`,formDescriptionId:`${i}-form-item-description`,formMessageId:`${i}-form-item-message`,...o}},cP=d.createContext({}),oa=d.forwardRef(({className:e,...t},n)=>{const r=d.useId();return v.jsx(cP.Provider,{value:{id:r},children:v.jsx("div",{ref:n,className:_e("space-y-2",e),...t})})});oa.displayName="FormItem";const ia=d.forwardRef(({className:e,...t},n)=>{const{error:r,formItemId:o}=dg();return v.jsx(Qx,{ref:n,className:_e(r&&"text-destructive","text-sm",e),htmlFor:o,...t})});ia.displayName="FormLabel";const sa=d.forwardRef(({...e},t)=>{const{error:n,formItemId:r,formDescriptionId:o,formMessageId:i}=dg();return v.jsx(Zo,{ref:t,id:r,"aria-describedby":n?`${o} ${i}`:`${o}`,"aria-invalid":!!n,...e})});sa.displayName="FormControl";const aa=d.forwardRef(({className:e,...t},n)=>{const{formDescriptionId:r}=dg();return v.jsx("p",{ref:n,id:r,className:_e("text-[0.8rem] text-muted-foreground",e),...t})});aa.displayName="FormDescription";const xX=d.forwardRef(({className:e,children:t,...n},r)=>{const{error:o,formMessageId:i}=dg(),s=o?String(o==null?void 0:o.message):t;return s?v.jsx("p",{ref:r,id:i,className:_e("text-[0.8rem] font-medium text-destructive",e),...n,children:s}):null});xX.displayName="FormMessage";const uP="Switch",[bX,_te]=Mn(uP),[SX,_X]=bX(uP),EX=d.forwardRef((e,t)=>{const{__scopeSwitch:n,name:r,checked:o,defaultChecked:i,required:s,disabled:l,value:u="on",onCheckedChange:f,...p}=e,[m,g]=d.useState(null),y=Ue(t,b=>g(b)),x=d.useRef(!1),S=m?!!m.closest("form"):!0,[E=!1,_]=Zr({prop:o,defaultProp:i,onChange:f});return d.createElement(SX,{scope:n,checked:E,disabled:l},d.createElement(Ae.button,Y({type:"button",role:"switch","aria-checked":E,"aria-required":s,"data-state":dP(E),"data-disabled":l?"":void 0,disabled:l,value:u},p,{ref:y,onClick:ue(e.onClick,b=>{_(C=>!C),S&&(x.current=b.isPropagationStopped(),x.current||b.stopPropagation())})})),S&&d.createElement(RX,{control:m,bubbles:!x.current,name:r,value:u,checked:E,required:s,disabled:l,style:{transform:"translateX(-100%)"}}))}),CX="SwitchThumb",$X=d.forwardRef((e,t)=>{const{__scopeSwitch:n,...r}=e,o=_X(CX,n);return d.createElement(Ae.span,Y({"data-state":dP(o.checked),"data-disabled":o.disabled?"":void 0},r,{ref:t}))}),RX=e=>{const{control:t,checked:n,bubbles:r=!0,...o}=e,i=d.useRef(null),s=Ux(n),l=yx(t);return d.useEffect(()=>{const u=i.current,f=window.HTMLInputElement.prototype,m=Object.getOwnPropertyDescriptor(f,"checked").set;if(s!==n&&m){const g=new Event("click",{bubbles:r});m.call(u,n),u.dispatchEvent(g)}},[s,n,r]),d.createElement("input",Y({type:"checkbox","aria-hidden":!0,defaultChecked:n},o,{tabIndex:-1,ref:i,style:{...e.style,...l,position:"absolute",pointerEvents:"none",opacity:0,margin:0}}))};function dP(e){return e?"checked":"unchecked"}const fP=EX,kX=$X,co=d.forwardRef(({className:e,...t},n)=>v.jsx(fP,{className:_e("peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",e),tabIndex:-1,...t,ref:n,children:v.jsx(kX,{className:_e("pointer-events-none block h-4 w-4 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0")})}));co.displayName=fP.displayName;const TX="AlertDialog",[PX,Ete]=Mn(TX,[hT]),zs=hT(),AX=e=>{const{__scopeAlertDialog:t,...n}=e,r=zs(t);return d.createElement(Cx,Y({},r,n,{modal:!0}))},MX=e=>{const{__scopeAlertDialog:t,...n}=e,r=zs(t);return d.createElement($x,Y({},r,n))},OX=d.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=zs(n);return d.createElement(zd,Y({},o,r,{ref:t}))}),hP="AlertDialogContent",[NX,DX]=PX(hP),IX=d.forwardRef((e,t)=>{const{__scopeAlertDialog:n,children:r,...o}=e,i=zs(n),s=d.useRef(null),l=Ue(t,s),u=d.useRef(null);return d.createElement(hW,{contentName:hP,titleName:LX,docsSlug:"alert-dialog"},d.createElement(NX,{scope:n,cancelRef:u},d.createElement(Bd,Y({role:"alertdialog"},i,o,{ref:l,onOpenAutoFocus:ue(o.onOpenAutoFocus,f=>{var p;f.preventDefault(),(p=u.current)===null||p===void 0||p.focus({preventScroll:!0})}),onPointerDownOutside:f=>f.preventDefault(),onInteractOutside:f=>f.preventDefault()}),d.createElement(lx,null,r),!1)))}),LX="AlertDialogTitle",FX=d.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=zs(n);return d.createElement(Ud,Y({},o,r,{ref:t}))}),jX=d.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=zs(n);return d.createElement(Vd,Y({},o,r,{ref:t}))}),zX=d.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=zs(n);return d.createElement(Rx,Y({},o,r,{ref:t}))}),BX="AlertDialogCancel",UX=d.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,{cancelRef:o}=DX(BX,n),i=zs(n),s=Ue(t,o);return d.createElement(Rx,Y({},i,r,{ref:s}))}),VX=AX,WX=MX,pP=OX,mP=IX,gP=zX,vP=UX,yP=FX,wP=jX,HX=VX,KX=WX,xP=d.forwardRef(({className:e,...t},n)=>v.jsx(pP,{className:_e("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t,ref:n}));xP.displayName=pP.displayName;const bP=d.forwardRef(({className:e,...t},n)=>v.jsxs(KX,{children:[v.jsx(xP,{}),v.jsx(mP,{ref:n,className:_e("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",e),...t})]}));bP.displayName=mP.displayName;const SP=({className:e,...t})=>v.jsx("div",{className:_e("flex flex-col space-y-2 text-center sm:text-left",e),...t});SP.displayName="AlertDialogHeader";const GX=d.forwardRef(({className:e,...t},n)=>v.jsx(yP,{ref:n,className:_e("text-lg font-semibold",e),...t}));GX.displayName=yP.displayName;const YX=d.forwardRef(({className:e,...t},n)=>v.jsx(wP,{ref:n,className:_e("text-sm text-muted-foreground",e),...t}));YX.displayName=wP.displayName;const XX=d.forwardRef(({className:e,...t},n)=>v.jsx(gP,{ref:n,className:_e(_x(),e),...t}));XX.displayName=gP.displayName;const ZX=d.forwardRef(({className:e,...t},n)=>v.jsx(vP,{ref:n,className:_e(_x({variant:"outline"}),"mt-2 sm:mt-0",e),...t}));ZX.displayName=vP.displayName;const qX=pX({enableFileManager:hu(),inputDirectory:fu(),outputDirectory:fu(),enableDownloadMask:hu(),enableManualInpainting:hu(),enableUploadMask:hu(),enableAutoExtractPrompt:hu(),removeBGModel:fu(),realesrganModel:fu(),interactiveSegModel:fu()}),_P="General",F1="Model",EP="Plugins",QX=[F1,_P,EP];function JX(){const[e,t]=eT(!1),[n,r]=d.useState(F1),[o,i,s,l,u,f]=xt(M=>[M.updateAppState,M.settings,M.updateSettings,M.fileManagerState,M.setModel,M.setServerConfig]),{toast:p}=Id(),[m,g]=d.useState(i.model),[y,x]=d.useState([]),S=y.length>0;d.useEffect(()=>{g(i.model)},[i.model]);const{data:E,status:_,refetch:b}=ML({queryKey:["serverConfig"],queryFn:yk}),C=YY({resolver:JY(qX),defaultValues:{enableDownloadMask:i.enableDownloadMask,enableManualInpainting:i.enableManualInpainting,enableUploadMask:i.enableUploadMask,enableAutoExtractPrompt:i.enableAutoExtractPrompt,inputDirectory:l.inputDirectory,outputDirectory:l.outputDirectory,removeBGModel:E==null?void 0:E.removeBGModel,realesrganModel:E==null?void 0:E.realesrganModel,interactiveSegModel:E==null?void 0:E.interactiveSegModel}});d.useEffect(()=>{E&&(f(E),C.setValue("removeBGModel",E.removeBGModel),C.setValue("realesrganModel",E.realesrganModel),C.setValue("interactiveSegModel",E.interactiveSegModel))},[C,E]);async function R(M){s({enableDownloadMask:M.enableDownloadMask,enableManualInpainting:M.enableManualInpainting,enableUploadMask:M.enableUploadMask,enableAutoExtractPrompt:M.enableAutoExtractPrompt});const ee=m.name!==i.model.name,H=(E==null?void 0:E.removeBGModel)!==M.removeBGModel&&A,X=(E==null?void 0:E.realesrganModel)!==M.realesrganModel&&D,W=(E==null?void 0:E.interactiveSegModel)!==M.interactiveSegModel&&B;if(ee||H||X||W){const pe=[];if(ee&&pe.push(`Switching model from ${i.model.name} to ${m.name}`),H&&pe.push(`Switching RemoveBG model from ${E==null?void 0:E.removeBGModel} to ${M.removeBGModel}`),X&&pe.push(`Switching RealESRGAN model from ${E==null?void 0:E.realesrganModel} to ${M.realesrganModel}`),W&&pe.push(`Switching ${Ao.InteractiveSeg} model from ${E==null?void 0:E.interactiveSegModel} to ${M.interactiveSegModel}`),x(pe),o({disableShortCuts:!0}),ee)try{const $e=await Bj(m.name);p({title:`Switch to ${$e.name} success`}),u(m)}catch($e){p({variant:"destructive",title:`Switch to ${m.name} failed: ${$e}`}),g(i.model)}if(H)try{const $e=await y0(Ao.RemoveBG,M.removeBGModel);if($e.status!==200)throw new Error($e.statusText)}catch($e){p({variant:"destructive",title:`Switch RemoveBG model to ${M.removeBGModel} failed: ${$e}`})}if(X)try{const $e=await y0(Ao.RealESRGAN,M.realesrganModel);if($e.status!==200)throw new Error($e.statusText)}catch($e){p({variant:"destructive",title:`Switch RealESRGAN model to ${M.realesrganModel} failed: ${$e}`})}if(W)try{const $e=await y0(Ao.InteractiveSeg,M.interactiveSegModel);if($e.status!==200)throw new Error($e.statusText)}catch($e){p({variant:"destructive",title:`Switch ${Ao.InteractiveSeg} model to ${M.interactiveSegModel} failed: ${$e}`})}x([]),o({disableShortCuts:!1}),b()}}if(Zn("s",()=>{t(),e&&R(C.getValues())},[e,C,m,E]),_!=="success")return v.jsx(v.Fragment,{});const P=E.modelInfos,O=E.plugins,A=O.some(M=>M.name===Ao.RemoveBG),D=O.some(M=>M.name===Ao.RealESRGAN),B=O.some(M=>M.name===Ao.InteractiveSeg);function V(M){t(),M||R(C.getValues())}function J(M){g(M)}function G(M){return P?P.filter(ee=>M.includes(ee.model_type)).map(ee=>v.jsxs("div",{onClick:()=>J(ee),className:"px-2",children:[v.jsx("div",{className:_e([ee.name===m.name?"bg-muted":"hover:bg-muted","rounded-md px-2 py-2","cursor-default"]),children:v.jsx("div",{className:"text-base",children:ee.name})}),v.jsx(gn,{className:"my-1"})]},ee.name)):v.jsx("div",{children:"Please download model first"})}function se(){let M=fs;for(let ee of P)if(m.name===ee.name){M=ee.model_type,M===sC&&(M=ch),M===aC&&(M=uh);break}return v.jsxs("div",{className:"flex flex-col gap-4 w-[510px]",children:[v.jsxs("div",{className:"flex flex-col gap-4 rounded-md",children:[v.jsx("div",{className:"font-medium",children:"Current Model"}),v.jsx("div",{children:m.name})]}),v.jsx(gn,{}),v.jsxs("div",{className:"space-y-4 rounded-md",children:[v.jsx("div",{className:"flex gap-1 items-center justify-start",children:v.jsx("div",{className:"font-medium",children:"Available models"})}),v.jsxs(l3,{defaultValue:M,children:[v.jsxs(Bx,{children:[v.jsx(pa,{value:fs,children:"Inpaint"}),v.jsx(pa,{value:ch,children:"Stable Diffusion"}),v.jsx(pa,{value:uh,children:"Stable Diffusion Inpaint"}),v.jsx(pa,{value:f0,children:"Other Diffusion"})]}),v.jsxs(lg,{className:"h-[240px] w-full mt-2 outline-none border rounded-lg",children:[v.jsx(Su,{value:fs,children:G([fs])}),v.jsx(Su,{value:ch,children:G([ch,sC])}),v.jsx(Su,{value:uh,children:G([uh,aC])}),v.jsx(Su,{value:f0,children:G([f0])})]})]})]})]})}function U(){return v.jsxs("div",{className:"space-y-4 w-[510px]",children:[v.jsx(al,{control:C.control,name:"enableManualInpainting",render:({field:M})=>v.jsxs(oa,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(ia,{children:"Enable manual inpainting"}),v.jsx(aa,{children:"For erase model, click a button to trigger inpainting after draw mask."})]}),v.jsx(sa,{children:v.jsx(co,{checked:M.value,onCheckedChange:M.onChange})})]})}),v.jsx(gn,{}),v.jsx(al,{control:C.control,name:"enableDownloadMask",render:({field:M})=>v.jsxs(oa,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(ia,{children:"Enable download mask"}),v.jsx(aa,{children:"Also download the mask after save the inpainting result."})]}),v.jsx(sa,{children:v.jsx(co,{checked:M.value,onCheckedChange:M.onChange})})]})}),v.jsx(gn,{}),v.jsx(al,{control:C.control,name:"enableAutoExtractPrompt",render:({field:M})=>v.jsxs(oa,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(ia,{children:"Enable auto extract prompt"}),v.jsx(aa,{children:"Automatically extract prompt/negativate prompt from the image meta."})]}),v.jsx(sa,{children:v.jsx(co,{checked:M.value,onCheckedChange:M.onChange})})]})})]})}function ne(){return v.jsxs("div",{className:"space-y-4 w-[510px]",children:[v.jsx(al,{control:C.control,name:"removeBGModel",render:({field:M})=>v.jsxs(oa,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(ia,{children:"Remove Background"}),v.jsx(aa,{children:"Remove background model"})]}),v.jsxs(Uo,{onValueChange:M.onChange,defaultValue:M.value,disabled:!A,children:[v.jsx(sa,{children:v.jsx(go,{className:"w-auto",children:v.jsx(Vo,{placeholder:"Select removebg model"})})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:E==null?void 0:E.removeBGModels.map(ee=>v.jsx(yo,{value:ee,children:ee},ee))})})]})]})}),v.jsx(gn,{}),v.jsx(al,{control:C.control,name:"realesrganModel",render:({field:M})=>v.jsxs(oa,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(ia,{children:"RealESRGAN"}),v.jsx(aa,{children:"RealESRGAN Model"})]}),v.jsxs(Uo,{onValueChange:M.onChange,defaultValue:M.value,disabled:!D,children:[v.jsx(sa,{children:v.jsx(go,{className:"w-auto",children:v.jsx(Vo,{placeholder:"Select RealESRGAN model"})})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:E==null?void 0:E.realesrganModels.map(ee=>v.jsx(yo,{value:ee,children:ee},ee))})})]})]})}),v.jsx(gn,{}),v.jsx(al,{control:C.control,name:"interactiveSegModel",render:({field:M})=>v.jsxs(oa,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(ia,{children:"Interactive Segmentation"}),v.jsx(aa,{children:"Interactive Segmentation Model"})]}),v.jsxs(Uo,{onValueChange:M.onChange,defaultValue:M.value,disabled:!B,children:[v.jsx(sa,{children:v.jsx(go,{className:"w-auto",children:v.jsx(Vo,{placeholder:"Select interactive segmentation model"})})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:E==null?void 0:E.interactiveSegModels.map(ee=>v.jsx(yo,{value:ee,children:ee},ee))})})]})]})})]})}return v.jsxs(v.Fragment,{children:[v.jsx(HX,{open:S,children:v.jsx(bP,{children:v.jsx(SP,{children:v.jsxs("div",{className:"flex flex-col justify-center items-center gap-4",children:[v.jsxs("div",{role:"status",children:[v.jsxs("svg",{"aria-hidden":"true",className:"w-8 h-8 text-gray-200 animate-spin dark:text-gray-600 fill-primary",viewBox:"0 0 100 101",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[v.jsx("path",{d:"M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z",fill:"currentColor"}),v.jsx("path",{d:"M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z",fill:"currentFill"})]}),v.jsx("span",{className:"sr-only",children:"Loading..."})]}),y?v.jsx("div",{className:"flex flex-col",children:y.map((M,ee)=>v.jsx("div",{children:M},ee))}):v.jsx(v.Fragment,{})]})})})}),v.jsxs(eg,{open:e,onOpenChange:V,children:[v.jsx(kx,{asChild:!0,children:v.jsx(yn,{tooltip:"Settings",children:v.jsx(sV,{})})}),v.jsxs(Wd,{className:"max-w-3xl h-[600px]",onOpenAutoFocus:M=>M.preventDefault(),children:[v.jsx(Hd,{children:"Settings"}),v.jsx(gn,{}),v.jsxs("div",{className:"flex flex-row space-x-8 h-full",children:[v.jsx("div",{className:"flex flex-col space-y-1",children:QX.map(M=>v.jsx(wn,{variant:"ghost",onClick:()=>r(M),className:_e(n===M?"bg-muted ":"hover:bg-muted","justify-start"),children:M},M))}),v.jsx(gn,{orientation:"vertical"}),v.jsx(wX,{...C,children:v.jsx("div",{className:"flex w-full justify-center",children:v.jsxs("form",{onSubmit:C.handleSubmit(R),children:[n===F1?se():v.jsx(v.Fragment,{}),n===_P?U():v.jsx(v.Fragment,{}),n===EP?ne():v.jsx(v.Fragment,{}),v.jsx("div",{className:"absolute right-10 bottom-6",children:v.jsx(wn,{onClick:()=>V(!1),children:"Ok"})})]})})})]})]})]})]})}const eZ="/assets/kofi_button_black-XI_Dr2zg.png";function tZ(){return v.jsxs(eg,{children:[v.jsx(kx,{asChild:!0,children:v.jsx(yn,{tooltip:"Buy me a coffee",children:v.jsx(XU,{})})}),v.jsxs(Wd,{children:[v.jsx(Hd,{children:"Buy me a coffee"}),v.jsx(wT,{className:"mb-8",children:"Hi, if you found my project is useful, please conside buy me a coffee to support my work. Thanks!"}),v.jsx("div",{className:"w-full flex items-center justify-center",children:v.jsx("a",{href:"https://ko-fi.com/Z8Z1CZJGY",target:"_blank",rel:"noreferrer",children:v.jsx("img",{src:eZ,className:"h-[32px]"})})})]})]})}const nZ=()=>{const[e,t,n,r,o,i,s,l,u,f,p,m,g,y]=xt(O=>[O.file,O.customMask,O.isInpainting,O.serverConfig,O.runMannually(),O.settings.enableUploadMask,O.settings.model,O.setFile,O.setCustomFile,O.runInpainting,O.showPrevMask,O.hidePrevMask,O.imageHeight,O.imageWidth]),{toast:x}=Id(),[S,E]=Px(t),[_,b]=d.useState(!1),C=()=>{f()},R=()=>{p()},P=()=>{m()};return v.jsxs("header",{className:"h-[60px] px-6 py-4 absolute top-[0] flex justify-between items-center w-full z-20 border-b backdrop-filter backdrop-blur-md bg-background/70",children:[v.jsxs("div",{className:"flex items-center gap-1",children:[r.enableFileManager?v.jsx(PY,{photoWidth:512,onPhotoClick:async(O,A)=>{try{const D=await Vj(O,A);l(D)}catch(D){x({variant:"destructive",description:D.message?D.message:D.toString()});return}}}):v.jsx(v.Fragment,{}),v.jsx(f1,{disabled:n,tooltip:"Upload image",onFileUpload:O=>{l(O)},children:v.jsx(tV,{})}),v.jsxs("div",{className:_e(["flex items-center gap-1",e&&i?"visible":"hidden"]),children:[v.jsx(f1,{disabled:n,tooltip:"Upload custom mask",onFileUpload:async O=>{let A=null;try{A=await gF(O)}catch(D){x({variant:"destructive",description:D.message?D.message:D.toString()});return}if(A.naturalHeight!==g||A.naturalWidth!==y){x({variant:"destructive",description:`The size of the mask must same as image: ${y}x${g}`});return}u(O),o||f()},children:v.jsx(Jk,{})}),t?v.jsxs(KW,{open:_,children:[v.jsx(GW,{className:"btn-primary side-panel-trigger",onMouseEnter:()=>b(!0),onMouseLeave:()=>b(!1),style:{visibility:t?"visible":"hidden",outline:"none"},onClick:()=>{},children:v.jsx(yn,{tooltip:"Run custom mask",children:v.jsx(uz,{})})}),v.jsx(NT,{children:E?v.jsx("img",{src:S.src,alt:"Custom mask"}):v.jsx(v.Fragment,{})})]}):v.jsx(v.Fragment,{})]}),e&&!s.need_prompt?v.jsx(yn,{disabled:n,tooltip:"Rerun previous mask",onClick:C,onMouseEnter:R,onMouseLeave:P,children:v.jsx(iV,{})}):v.jsx(v.Fragment,{})]}),s.need_prompt?v.jsx(yH,{}):v.jsx(v.Fragment,{}),v.jsxs("div",{className:"flex gap-1",children:[v.jsx(tZ,{}),v.jsx(MW,{}),r.disableModelSwitch?v.jsx(v.Fragment,{}):v.jsx(JX,{})]})]})};var Wr=function(e,t){return Number(e.toFixed(t))},rZ=function(e,t){return typeof e=="number"?e:t},Nt=function(e,t,n){n&&typeof n=="function"&&n(e,t)},oZ=function(e){return-Math.cos(e*Math.PI)/2+.5},iZ=function(e){return e},sZ=function(e){return e*e},aZ=function(e){return e*(2-e)},lZ=function(e){return e<.5?2*e*e:-1+(4-2*e)*e},cZ=function(e){return e*e*e},uZ=function(e){return--e*e*e+1},dZ=function(e){return e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1},fZ=function(e){return e*e*e*e},hZ=function(e){return 1- --e*e*e*e},pZ=function(e){return e<.5?8*e*e*e*e:1-8*--e*e*e*e},mZ=function(e){return e*e*e*e*e},gZ=function(e){return 1+--e*e*e*e*e},vZ=function(e){return e<.5?16*e*e*e*e*e:1+16*--e*e*e*e*e},CP={easeOut:oZ,linear:iZ,easeInQuad:sZ,easeOutQuad:aZ,easeInOutQuad:lZ,easeInCubic:cZ,easeOutCubic:uZ,easeInOutCubic:dZ,easeInQuart:fZ,easeOutQuart:hZ,easeInOutQuart:pZ,easeInQuint:mZ,easeOutQuint:gZ,easeInOutQuint:vZ},$P=function(e){typeof e=="number"&&cancelAnimationFrame(e)},jo=function(e){e.mounted&&($P(e.animation),e.animate=!1,e.animation=null,e.velocity=null)};function RP(e,t,n,r){if(e.mounted){var o=new Date().getTime(),i=1;jo(e),e.animation=function(){if(!e.mounted)return $P(e.animation);var s=new Date().getTime()-o,l=s/n,u=CP[t],f=u(l);s>=n?(r(i),e.animation=null):e.animation&&(r(f),requestAnimationFrame(e.animation))},requestAnimationFrame(e.animation)}}function yZ(e){var t=e.scale,n=e.positionX,r=e.positionY;return!(Number.isNaN(t)||Number.isNaN(n)||Number.isNaN(r))}function Bs(e,t,n,r){var o=yZ(t);if(!(!e.mounted||!o)){var i=e.setTransformState,s=e.transformState,l=s.scale,u=s.positionX,f=s.positionY,p=t.scale-l,m=t.positionX-u,g=t.positionY-f;n===0?i(t.scale,t.positionX,t.positionY):RP(e,r,n,function(y){var x=l+p*y,S=u+m*y,E=f+g*y;i(x,S,E)})}}function wZ(e,t,n){var r=e.offsetWidth,o=e.offsetHeight,i=t.offsetWidth,s=t.offsetHeight,l=i*n,u=s*n,f=r-l,p=o-u;return{wrapperWidth:r,wrapperHeight:o,newContentWidth:l,newDiffWidth:f,newContentHeight:u,newDiffHeight:p}}var xZ=function(e,t,n,r,o,i,s){var l=e>t?n*(s?1:.5):0,u=r>o?i*(s?1:.5):0,f=e-t-l,p=l,m=r-o-u,g=u;return{minPositionX:f,maxPositionX:p,minPositionY:m,maxPositionY:g}},Jx=function(e,t){var n=e.wrapperComponent,r=e.contentComponent,o=e.setup.centerZoomedOut;if(!n||!r)throw new Error("Components are not mounted");var i=wZ(n,r,t),s=i.wrapperWidth,l=i.wrapperHeight,u=i.newContentWidth,f=i.newDiffWidth,p=i.newContentHeight,m=i.newDiffHeight,g=xZ(s,u,f,l,p,m,!!o);return g},j1=function(e,t,n,r){return r?en?Wr(n,2):Wr(e,2):Wr(e,2)},vc=function(e,t){var n=Jx(e,t);return e.bounds=n,n};function fg(e,t,n,r,o,i,s){var l=n.minPositionX,u=n.minPositionY,f=n.maxPositionX,p=n.maxPositionY,m=0,g=0;s&&(m=o,g=i);var y=j1(e,l-m,f+m,r),x=j1(t,u-g,p+g,r);return{x:y,y:x}}function hg(e,t,n,r,o,i){var s=e.transformState,l=s.scale,u=s.positionX,f=s.positionY,p=r-l;if(typeof t!="number"||typeof n!="number")return console.error("Mouse X and Y position were not provided!"),{x:u,y:f};var m=u-t*p,g=f-n*p,y=fg(m,g,o,i,0,0,null);return y}function Xd(e,t,n,r,o){var i=o?r:0,s=t-i;return!Number.isNaN(n)&&e>=n?n:!Number.isNaN(t)&&e<=s?s:e}var I2=function(e,t){var n=e.setup.panning.excluded,r=e.isInitialized,o=e.wrapperComponent,i=t.target,s=o==null?void 0:o.contains(i),l=r&&i&&s;if(!l)return!1;var u=pg(i,n);return!u},L2=function(e){var t=e.isInitialized,n=e.isPanning,r=e.setup,o=r.panning.disabled,i=t&&n&&!o;return!!i},bZ=function(e,t){var n=e.transformState,r=n.positionX,o=n.positionY;e.isPanning=!0;var i=t.clientX,s=t.clientY;e.startCoords={x:i-r,y:s-o}},SZ=function(e,t){var n=t.touches,r=e.transformState,o=r.positionX,i=r.positionY;e.isPanning=!0;var s=n.length===1;if(s){var l=n[0].clientX,u=n[0].clientY;e.startCoords={x:l-o,y:u-i}}};function _Z(e){var t=e.transformState,n=t.positionX,r=t.positionY,o=t.scale,i=e.setup,s=i.disabled,l=i.limitToBounds,u=i.centerZoomedOut,f=e.wrapperComponent;if(!(s||!f||!e.bounds)){var p=e.bounds,m=p.maxPositionX,g=p.minPositionX,y=p.maxPositionY,x=p.minPositionY,S=n>m||ny||rm?f.offsetWidth:e.setup.minPositionX||0,b=r>y?f.offsetHeight:e.setup.minPositionY||0,C=hg(e,_,b,o,e.bounds,l||u),R=C.x,P=C.y;return{scale:o,positionX:S?R:n,positionY:E?P:r}}}function EZ(e,t,n,r,o){var i=e.setup.limitToBounds,s=e.wrapperComponent,l=e.bounds,u=e.transformState,f=u.scale,p=u.positionX,m=u.positionY;if(!(s===null||l===null||t===p&&n===m)){var g=fg(t,n,l,i,r,o,s),y=g.x,x=g.y;e.setTransformState(f,y,x)}}var CZ=function(e,t,n){var r=e.startCoords,o=e.transformState,i=e.setup.panning,s=i.lockAxisX,l=i.lockAxisY,u=o.positionX,f=o.positionY;if(!r)return{x:u,y:f};var p=t-r.x,m=n-r.y,g=s?u:p,y=l?f:m;return{x:g,y}},sm=function(e,t){var n=e.setup,r=e.transformState,o=r.scale,i=n.minScale,s=n.disablePadding;return t>0&&o>=i&&!s?t:0},$Z=function(e){var t=e.mounted,n=e.setup,r=n.disabled,o=n.velocityAnimation,i=e.transformState.scale,s=o.disabled,l=!s||i>1||!r||t;return!!l},RZ=function(e){var t=e.mounted,n=e.velocity,r=e.bounds,o=e.setup,i=o.disabled,s=o.velocityAnimation,l=e.transformState.scale,u=s.disabled,f=!u||l>1||!i||t;return!(!f||!n||!r)};function kZ(e,t){var n=e.setup.velocityAnimation,r=n.equalToMove,o=n.animationTime,i=n.sensitivity;return r?o*t*i:o}function F2(e,t,n,r,o,i,s,l,u,f){if(o){if(t>s&&n>s){var p=s+(e-s)*f;return p>u?u:pi?i:p}}return r?t:j1(e,i,s,o)}function TZ(e,t){var n=1;return t?Math.min(n,e.offsetWidth/window.innerWidth):n}function PZ(e,t){var n=$Z(e);if(n){var r=e.lastMousePosition,o=e.velocityTime,i=e.setup,s=e.wrapperComponent,l=i.velocityAnimation.equalToMove,u=Date.now();if(r&&o&&s){var f=TZ(s,l),p=t.x-r.x,m=t.y-r.y,g=p/f,y=m/f,x=u-o,S=p*p+m*m,E=Math.sqrt(S)/x;e.velocity={velocityX:g,velocityY:y,total:E}}e.lastMousePosition=t,e.velocityTime=u}}function AZ(e){var t=e.velocity,n=e.bounds,r=e.setup,o=e.wrapperComponent,i=RZ(e);if(!(!i||!t||!n||!o)){var s=t.velocityX,l=t.velocityY,u=t.total,f=n.maxPositionX,p=n.minPositionX,m=n.maxPositionY,g=n.minPositionY,y=r.limitToBounds,x=r.alignmentAnimation,S=r.zoomAnimation,E=r.panning,_=E.lockAxisY,b=E.lockAxisX,C=S.animationType,R=x.sizeX,P=x.sizeY,O=x.velocityAlignmentTime,A=O,D=kZ(e,u),B=Math.max(D,A),V=sm(e,R),J=sm(e,P),G=V*o.offsetWidth/100,se=J*o.offsetHeight/100,U=f+G,ne=p-G,M=m+se,ee=g-se,H=e.transformState,X=new Date().getTime();RP(e,C,B,function(W){var le=e.transformState,pe=le.scale,$e=le.positionX,Ve=le.positionY,We=new Date().getTime()-X,Ne=We/A,fe=CP[x.animationType],xe=1-fe(Math.min(1,Ne)),Re=1-W,Me=$e+s*Re,Oe=Ve+l*Re,ze=F2(Me,H.positionX,$e,b,y,p,f,ne,U,xe),Mt=F2(Oe,H.positionY,Ve,_,y,g,m,ee,M,xe);($e!==Me||Ve!==Oe)&&e.setTransformState(pe,ze,Mt)})}}function j2(e,t){var n=e.transformState.scale;jo(e),vc(e,n),window.TouchEvent!==void 0&&t instanceof TouchEvent?SZ(e,t):bZ(e,t)}function kP(e){var t=e.transformState.scale,n=e.setup,r=n.minScale,o=n.alignmentAnimation,i=o.disabled,s=o.sizeX,l=o.sizeY,u=o.animationTime,f=o.animationType,p=i||t.1&&m;g?AZ(e):kP(e)}}function eb(e,t,n,r){var o=e.setup,i=o.minScale,s=o.maxScale,l=o.limitToBounds,u=Xd(Wr(t,2),i,s,0,!1),f=vc(e,u),p=hg(e,n,r,u,f,l),m=p.x,g=p.y;return{scale:u,positionX:m,positionY:g}}function TP(e,t,n){var r=e.transformState.scale,o=e.wrapperComponent,i=e.setup,s=i.minScale,l=i.limitToBounds,u=i.zoomAnimation,f=u.disabled,p=u.animationTime,m=u.animationType,g=f||r>=s;if((r>=1||l)&&kP(e),!(g||!o||!e.mounted)){var y=t||o.offsetWidth/2,x=n||o.offsetHeight/2,S=eb(e,s,y,x);S&&Bs(e,S,p,m)}}var $s=function(){return $s=Object.assign||function(t){for(var n,r=1,o=arguments.length;rs||Math.sign(n.deltaY)!==Math.sign(t.deltaY)||n.deltaY>0&&n.deltaYt.deltaY||Math.sign(n.deltaY)!==Math.sign(t.deltaY):!1},XZ=function(e,t){var n=e.setup.pinch,r=n.disabled,o=n.excluded,i=e.isInitialized,s=t.target,l=i&&!r&&s;if(!l)return!1;var u=pg(s,o);return!u},ZZ=function(e){var t=e.setup.pinch.disabled,n=e.isInitialized,r=e.pinchStartDistance,o=n&&!t&&r;return!!o},qZ=function(e,t,n){var r=n.getBoundingClientRect(),o=e.touches,i=Wr(o[0].clientX-r.left,5),s=Wr(o[0].clientY-r.top,5),l=Wr(o[1].clientX-r.left,5),u=Wr(o[1].clientY-r.top,5);return{x:(i+l)/2/t,y:(s+u)/2/t}},IP=function(e){return Math.sqrt(Math.pow(e.touches[0].pageX-e.touches[1].pageX,2)+Math.pow(e.touches[0].pageY-e.touches[1].pageY,2))},QZ=function(e,t){var n=e.pinchStartScale,r=e.pinchStartDistance,o=e.setup,i=o.maxScale,s=o.minScale,l=o.zoomAnimation,u=o.disablePadding,f=l.size,p=l.disabled;if(!n||r===null||!t)throw new Error("Pinch touches distance was not provided");if(t<0)return e.transformState.scale;var m=t/r,g=m*n;return Xd(Wr(g,2),s,i,f,!p&&!u)},JZ=160,eq=100,tq=function(e,t){var n=e.props,r=n.onWheelStart,o=n.onZoomStart;e.wheelStopEventTimer||(jo(e),Nt(_t(e),t,r),Nt(_t(e),t,o))},nq=function(e,t){var n=e.props,r=n.onWheel,o=n.onZoom,i=e.contentComponent,s=e.setup,l=e.transformState,u=l.scale,f=s.limitToBounds,p=s.centerZoomedOut,m=s.zoomAnimation,g=s.wheel,y=s.disablePadding,x=s.smooth,S=m.size,E=m.disabled,_=g.step,b=g.smoothStep;if(!i)throw new Error("Component not mounted");t.preventDefault(),t.stopPropagation();var C=KZ(t,null),R=x?b*Math.abs(t.deltaY):_,P=GZ(e,C,R,!t.ctrlKey);if(u!==P){var O=vc(e,P),A=DP(t,i,u),D=E||S===0||p||y,B=f&&D,V=hg(e,A.x,A.y,P,O,B),J=V.x,G=V.y;e.previousWheelEvent=t,e.setTransformState(P,J,G),Nt(_t(e),t,r),Nt(_t(e),t,o)}},rq=function(e,t){var n=e.props,r=n.onWheelStop,o=n.onZoomStop;B1(e.wheelAnimationTimer),e.wheelAnimationTimer=setTimeout(function(){e.mounted&&(TP(e,t.x,t.y),e.wheelAnimationTimer=null)},eq);var i=YZ(e,t);i&&(B1(e.wheelStopEventTimer),e.wheelStopEventTimer=setTimeout(function(){e.mounted&&(e.wheelStopEventTimer=null,Nt(_t(e),t,r),Nt(_t(e),t,o))},JZ))},oq=function(e,t){var n=IP(t);e.pinchStartDistance=n,e.lastDistance=n,e.pinchStartScale=e.transformState.scale,e.isPanning=!1,jo(e)},iq=function(e,t){var n=e.contentComponent,r=e.pinchStartDistance,o=e.transformState.scale,i=e.setup,s=i.limitToBounds,l=i.centerZoomedOut,u=i.zoomAnimation,f=u.disabled,p=u.size;if(!(r===null||!n)){var m=qZ(t,o,n);if(!(!Number.isFinite(m.x)||!Number.isFinite(m.y))){var g=IP(t),y=QZ(e,g);if(y!==o){var x=vc(e,y),S=f||p===0||l,E=s&&S,_=hg(e,m.x,m.y,y,x,E),b=_.x,C=_.y;e.pinchMidpoint=m,e.lastDistance=g,e.setTransformState(y,b,C)}}}},sq=function(e){var t=e.pinchMidpoint;e.velocity=null,e.lastDistance=null,e.pinchMidpoint=null,e.pinchStartScale=null,e.pinchStartDistance=null,TP(e,t==null?void 0:t.x,t==null?void 0:t.y)},LP=function(e,t){var n=e.props.onZoomStop,r=e.setup.doubleClick.animationTime;B1(e.doubleClickStopEventTimer),e.doubleClickStopEventTimer=setTimeout(function(){e.doubleClickStopEventTimer=null,Nt(_t(e),t,n)},r)},aq=function(e,t){var n=e.props,r=n.onZoomStart,o=n.onZoom,i=e.setup.doubleClick,s=i.animationTime,l=i.animationType;Nt(_t(e),t,r),OP(e,s,l,function(){return Nt(_t(e),t,o)}),LP(e,t)};function lq(e,t){var n=e.setup,r=e.doubleClickStopEventTimer,o=e.transformState,i=e.contentComponent,s=o.scale,l=e.props,u=l.onZoomStart,f=l.onZoom,p=n.doubleClick,m=p.disabled,g=p.mode,y=p.step,x=p.animationTime,S=p.animationType;if(!m&&!r){if(g==="reset")return aq(e,t);if(!i)return console.error("No ContentComponent found");var E=g==="zoomOut"?-1:1,_=AP(e,E,y);if(s!==_){Nt(_t(e),t,u);var b=DP(t,i,s),C=eb(e,_,b.x,b.y);if(!C)return console.error("Error during zoom event. New transformation state was not calculated.");Nt(_t(e),t,f),Bs(e,C,x,S),LP(e,t)}}}var cq=function(e,t){var n=e.isInitialized,r=e.setup,o=e.wrapperComponent,i=r.doubleClick,s=i.disabled,l=i.excluded,u=t.target,f=o==null?void 0:o.contains(u),p=n&&u&&f&&!s;if(!p)return!1;var m=pg(u,l);return!m},uq=function(){function e(t){var n=this;this.mounted=!0,this.onChangeCallbacks=new Set,this.onInitCallbacks=new Set,this.wrapperComponent=null,this.contentComponent=null,this.isInitialized=!1,this.bounds=null,this.previousWheelEvent=null,this.wheelStopEventTimer=null,this.wheelAnimationTimer=null,this.isPanning=!1,this.startCoords=null,this.lastTouch=null,this.distance=null,this.lastDistance=null,this.pinchStartDistance=null,this.pinchStartScale=null,this.pinchMidpoint=null,this.doubleClickStopEventTimer=null,this.velocity=null,this.velocityTime=null,this.lastMousePosition=null,this.animate=!1,this.animation=null,this.maxBounds=null,this.pressedKeys={},this.mount=function(){n.initializeWindowEvents()},this.unmount=function(){n.cleanupWindowEvents()},this.update=function(r){vc(n,n.transformState.scale),n.setup=U2(r)},this.initializeWindowEvents=function(){var r,o=z0(),i=(r=n.wrapperComponent)===null||r===void 0?void 0:r.ownerDocument,s=i==null?void 0:i.defaultView;s==null||s.addEventListener("mousedown",n.onPanningStart,o),s==null||s.addEventListener("mousemove",n.onPanning,o),s==null||s.addEventListener("mouseup",n.onPanningStop,o),i==null||i.addEventListener("mouseleave",n.clearPanning,o),s==null||s.addEventListener("keyup",n.setKeyUnPressed,o),s==null||s.addEventListener("keydown",n.setKeyPressed,o)},this.cleanupWindowEvents=function(){var r,o,i=z0(),s=(r=n.wrapperComponent)===null||r===void 0?void 0:r.ownerDocument,l=s==null?void 0:s.defaultView;l==null||l.removeEventListener("mousedown",n.onPanningStart,i),l==null||l.removeEventListener("mousemove",n.onPanning,i),l==null||l.removeEventListener("mouseup",n.onPanningStop,i),s==null||s.removeEventListener("mouseleave",n.clearPanning,i),l==null||l.removeEventListener("keyup",n.setKeyUnPressed,i),l==null||l.removeEventListener("keydown",n.setKeyPressed,i),document.removeEventListener("mouseleave",n.clearPanning,i),jo(n),(o=n.observer)===null||o===void 0||o.disconnect()},this.handleInitializeWrapperEvents=function(r){var o=z0();r.addEventListener("wheel",n.onWheelZoom,o),r.addEventListener("dblclick",n.onDoubleClick,o),r.addEventListener("touchstart",n.onTouchPanningStart,o),r.addEventListener("touchmove",n.onTouchPanning,o),r.addEventListener("touchend",n.onTouchPanningStop,o)},this.handleInitialize=function(r){var o=n.setup.centerOnInit;n.applyTransformation(),n.onInitCallbacks.forEach(function(i){return i(_t(n))}),o&&(n.setCenter(),n.observer=new ResizeObserver(function(){var i;n.onInitCallbacks.forEach(function(s){return s(_t(n))}),n.setCenter(),(i=n.observer)===null||i===void 0||i.disconnect()}),n.observer.observe(r))},this.onWheelZoom=function(r){var o=n.setup.disabled;if(!o){var i=WZ(n,r);if(i){var s=n.isPressingKeys(n.setup.wheel.activationKeys);s&&(tq(n,r),nq(n,r),rq(n,r))}}},this.onPanningStart=function(r){var o=n.setup.disabled,i=n.props.onPanningStart;if(!o){var s=I2(n,r);if(s){var l=n.isPressingKeys(n.setup.panning.activationKeys);l&&(r.button===0&&!n.setup.panning.allowLeftClickPan||r.button===1&&!n.setup.panning.allowMiddleClickPan||r.button===2&&!n.setup.panning.allowRightClickPan||(r.preventDefault(),r.stopPropagation(),jo(n),j2(n,r),Nt(_t(n),r,i)))}}},this.onPanning=function(r){var o=n.setup.disabled,i=n.props.onPanning;if(!o){var s=L2(n);if(s){var l=n.isPressingKeys(n.setup.panning.activationKeys);l&&(r.preventDefault(),r.stopPropagation(),z2(n,r.clientX,r.clientY),Nt(_t(n),r,i))}}},this.onPanningStop=function(r){var o=n.props.onPanningStop;n.isPanning&&(MZ(n),Nt(_t(n),r,o))},this.onPinchStart=function(r){var o=n.setup.disabled,i=n.props,s=i.onPinchingStart,l=i.onZoomStart;if(!o){var u=XZ(n,r);u&&(oq(n,r),jo(n),Nt(_t(n),r,s),Nt(_t(n),r,l))}},this.onPinch=function(r){var o=n.setup.disabled,i=n.props,s=i.onPinching,l=i.onZoom;if(!o){var u=ZZ(n);u&&(r.preventDefault(),r.stopPropagation(),iq(n,r),Nt(_t(n),r,s),Nt(_t(n),r,l))}},this.onPinchStop=function(r){var o=n.props,i=o.onPinchingStop,s=o.onZoomStop;n.pinchStartScale&&(sq(n),Nt(_t(n),r,i),Nt(_t(n),r,s))},this.onTouchPanningStart=function(r){var o=n.setup.disabled,i=n.props.onPanningStart;if(!o){var s=I2(n,r);if(s){var l=n.lastTouch&&+new Date-n.lastTouch<200;if(l&&r.touches.length===1)n.onDoubleClick(r);else{n.lastTouch=+new Date,jo(n);var u=r.touches,f=u.length===1,p=u.length===2;f&&(jo(n),j2(n,r),Nt(_t(n),r,i)),p&&n.onPinchStart(r)}}}},this.onTouchPanning=function(r){var o=n.setup.disabled,i=n.props.onPanning;if(n.isPanning&&r.touches.length===1){if(o)return;var s=L2(n);if(!s)return;r.preventDefault(),r.stopPropagation();var l=r.touches[0];z2(n,l.clientX,l.clientY),Nt(_t(n),r,i)}else r.touches.length>1&&n.onPinch(r)},this.onTouchPanningStop=function(r){n.onPanningStop(r),n.onPinchStop(r)},this.onDoubleClick=function(r){var o=n.setup.disabled;if(!o){var i=cq(n,r);i&&lq(n,r)}},this.clearPanning=function(r){n.isPanning&&n.onPanningStop(r)},this.setKeyPressed=function(r){n.pressedKeys[r.key]=!0},this.setKeyUnPressed=function(r){n.pressedKeys[r.key]=!1},this.isPressingKeys=function(r){return r.length?!!r.find(function(o){return n.pressedKeys[o]}):!0},this.setTransformState=function(r,o,i){var s=n.props.onTransformed;if(!Number.isNaN(r)&&!Number.isNaN(o)&&!Number.isNaN(i)){r!==n.transformState.scale&&(n.transformState.previousScale=n.transformState.scale,n.transformState.scale=r),n.transformState.positionX=o,n.transformState.positionY=i,n.applyTransformation();var l=_t(n);n.onChangeCallbacks.forEach(function(u){return u(l)}),Nt(l,{scale:r,positionX:o,positionY:i},s)}else console.error("Detected NaN set state values")},this.setCenter=function(){if(n.wrapperComponent&&n.contentComponent){var r=NP(n.transformState.scale,n.wrapperComponent,n.contentComponent);n.setTransformState(r.scale,r.positionX,r.positionY)}},this.handleTransformStyles=function(r,o,i){return n.props.customTransform?n.props.customTransform(r,o,i):UZ(r,o,i)},this.applyTransformation=function(){if(!(!n.mounted||!n.contentComponent)){var r=n.transformState,o=r.scale,i=r.positionX,s=r.positionY,l=n.handleTransformStyles(i,s,o);n.contentComponent.style.transform=l}},this.getContext=function(){return _t(n)},this.onChange=function(r){return n.onChangeCallbacks.has(r)||n.onChangeCallbacks.add(r),function(){n.onChangeCallbacks.delete(r)}},this.onInit=function(r){return n.onInitCallbacks.has(r)||n.onInitCallbacks.add(r),function(){n.onInitCallbacks.delete(r)}},this.init=function(r,o){n.cleanupWindowEvents(),n.wrapperComponent=r,n.contentComponent=o,vc(n,n.transformState.scale),n.handleInitializeWrapperEvents(r),n.handleInitialize(o),n.initializeWindowEvents(),n.isInitialized=!0;var i=_t(n);Nt(i,void 0,n.props.onInit)},this.props=t,this.setup=U2(this.props),this.transformState=PP(this.props)}return e}(),tb=je.createContext(null),dq=function(e,t){return typeof e=="function"?e(t):e},fq=je.forwardRef(function(e,t){var n=d.useRef(new uq(e)).current,r=dq(e.children,z1(n));return d.useImperativeHandle(t,function(){return z1(n)},[n]),d.useEffect(function(){n.update(e)},[n,e]),je.createElement(tb.Provider,{value:n},r)});je.forwardRef(function(e,t){var n=d.useRef(null),r=d.useContext(tb);return d.useEffect(function(){return r.onChange(function(o){if(n.current){var i=0,s=0;n.current.style.transform=r.handleTransformStyles(i,s,1/o.instance.transformState.scale)}})},[r]),je.createElement("div",$s({},e,{ref:VZ([n,t])}))});function hq(e,t){t===void 0&&(t={});var n=t.insertAt;if(!(!e||typeof document>"u")){var r=document.head||document.getElementsByTagName("head")[0],o=document.createElement("style");o.type="text/css",n==="top"&&r.firstChild?r.insertBefore(o,r.firstChild):r.appendChild(o),o.styleSheet?o.styleSheet.cssText=e:o.appendChild(document.createTextNode(e))}}var pq=`.transform-component-module_wrapper__SPB86 { + position: relative; + width: -moz-fit-content; + width: fit-content; + height: -moz-fit-content; + height: fit-content; + overflow: hidden; + -webkit-touch-callout: none; /* iOS Safari */ + -webkit-user-select: none; /* Safari */ + -khtml-user-select: none; /* Konqueror HTML */ + -moz-user-select: none; /* Firefox */ + -ms-user-select: none; /* Internet Explorer/Edge */ + user-select: none; + margin: 0; + padding: 0; +} +.transform-component-module_content__FBWxo { + display: flex; + flex-wrap: wrap; + width: -moz-fit-content; + width: fit-content; + height: -moz-fit-content; + height: fit-content; + margin: 0; + padding: 0; + transform-origin: 0% 0%; +} +.transform-component-module_content__FBWxo img { + pointer-events: none; +} +`,V2={wrapper:"transform-component-module_wrapper__SPB86",content:"transform-component-module_content__FBWxo"};hq(pq);var mq=function(e){var t=e.children,n=e.wrapperClass,r=n===void 0?"":n,o=e.contentClass,i=o===void 0?"":o,s=e.wrapperStyle,l=e.contentStyle,u=e.wrapperProps,f=u===void 0?{}:u,p=e.contentProps,m=p===void 0?{}:p,g=d.useContext(tb),y=g.init,x=g.cleanupWindowEvents,S=d.useRef(null),E=d.useRef(null);return d.useEffect(function(){var _=S.current,b=E.current;return _!==null&&b!==null&&y&&(y==null||y(_,b)),function(){x==null||x()}},[]),je.createElement("div",$s({},f,{ref:S,className:"react-transform-wrapper ".concat(V2.wrapper," ").concat(r),style:s}),je.createElement("div",$s({},m,{ref:E,className:"react-transform-component ".concat(V2.content," ").concat(i),style:l}),t))};const FP=["PageUp","PageDown"],jP=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],zP={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},Zd="Slider",[U1,gq,vq]=Kd(Zd),[BP,Cte]=Mn(Zd,[vq]),[yq,mg]=BP(Zd),wq=d.forwardRef((e,t)=>{const{name:n,min:r=0,max:o=100,step:i=1,orientation:s="horizontal",disabled:l=!1,minStepsBetweenThumbs:u=0,defaultValue:f=[r],value:p,onValueChange:m=()=>{},onValueCommit:g=()=>{},inverted:y=!1,...x}=e,[S,E]=d.useState(null),_=Ue(t,U=>E(U)),b=d.useRef(new Set),C=d.useRef(0),R=s==="horizontal",P=S?!!S.closest("form"):!0,O=R?xq:bq,[A=[],D]=Zr({prop:p,defaultProp:f,onChange:U=>{var ne;(ne=[...b.current][C.current])===null||ne===void 0||ne.focus(),m(U)}}),B=d.useRef(A);function V(U){const ne=Pq(A,U);se(U,ne)}function J(U){se(U,C.current)}function G(){const U=B.current[C.current];A[C.current]!==U&&g(A)}function se(U,ne,{commit:M}={commit:!1}){const ee=Nq(i),H=Dq(Math.round((U-r)/i)*i+r,ee),X=fd(H,[r,o]);D((W=[])=>{const le=kq(W,X,ne);if(Oq(le,u*i)){C.current=le.indexOf(X);const pe=String(le)!==String(W);return pe&&M&&g(le),pe?le:W}else return W})}return d.createElement(yq,{scope:e.__scopeSlider,disabled:l,min:r,max:o,valueIndexToChangeRef:C,thumbs:b.current,values:A,orientation:s},d.createElement(U1.Provider,{scope:e.__scopeSlider},d.createElement(U1.Slot,{scope:e.__scopeSlider},d.createElement(O,Y({"aria-disabled":l,"data-disabled":l?"":void 0},x,{ref:_,onPointerDown:ue(x.onPointerDown,()=>{l||(B.current=A)}),min:r,max:o,inverted:y,onSlideStart:l?void 0:V,onSlideMove:l?void 0:J,onSlideEnd:l?void 0:G,onHomeKeyDown:()=>!l&&se(r,0,{commit:!0}),onEndKeyDown:()=>!l&&se(o,A.length-1,{commit:!0}),onStepKeyDown:({event:U,direction:ne})=>{if(!l){const H=FP.includes(U.key)||U.shiftKey&&jP.includes(U.key)?10:1,X=C.current,W=A[X],le=i*H*ne;se(W+le,X,{commit:!0})}}})))),P&&A.map((U,ne)=>d.createElement(Rq,{key:ne,name:n?n+(A.length>1?"[]":""):void 0,value:U})))}),[UP,VP]=BP(Zd,{startEdge:"left",endEdge:"right",size:"width",direction:1}),xq=d.forwardRef((e,t)=>{const{min:n,max:r,dir:o,inverted:i,onSlideStart:s,onSlideMove:l,onSlideEnd:u,onStepKeyDown:f,...p}=e,[m,g]=d.useState(null),y=Ue(t,C=>g(C)),x=d.useRef(),S=Tc(o),E=S==="ltr",_=E&&!i||!E&&i;function b(C){const R=x.current||m.getBoundingClientRect(),P=[0,R.width],A=nb(P,_?[n,r]:[r,n]);return x.current=R,A(C-R.left)}return d.createElement(UP,{scope:e.__scopeSlider,startEdge:_?"left":"right",endEdge:_?"right":"left",direction:_?1:-1,size:"width"},d.createElement(WP,Y({dir:S,"data-orientation":"horizontal"},p,{ref:y,style:{...p.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:C=>{const R=b(C.clientX);s==null||s(R)},onSlideMove:C=>{const R=b(C.clientX);l==null||l(R)},onSlideEnd:()=>{x.current=void 0,u==null||u()},onStepKeyDown:C=>{const P=zP[_?"from-left":"from-right"].includes(C.key);f==null||f({event:C,direction:P?-1:1})}})))}),bq=d.forwardRef((e,t)=>{const{min:n,max:r,inverted:o,onSlideStart:i,onSlideMove:s,onSlideEnd:l,onStepKeyDown:u,...f}=e,p=d.useRef(null),m=Ue(t,p),g=d.useRef(),y=!o;function x(S){const E=g.current||p.current.getBoundingClientRect(),_=[0,E.height],C=nb(_,y?[r,n]:[n,r]);return g.current=E,C(S-E.top)}return d.createElement(UP,{scope:e.__scopeSlider,startEdge:y?"bottom":"top",endEdge:y?"top":"bottom",size:"height",direction:y?1:-1},d.createElement(WP,Y({"data-orientation":"vertical"},f,{ref:m,style:{...f.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:S=>{const E=x(S.clientY);i==null||i(E)},onSlideMove:S=>{const E=x(S.clientY);s==null||s(E)},onSlideEnd:()=>{g.current=void 0,l==null||l()},onStepKeyDown:S=>{const _=zP[y?"from-bottom":"from-top"].includes(S.key);u==null||u({event:S,direction:_?-1:1})}})))}),WP=d.forwardRef((e,t)=>{const{__scopeSlider:n,onSlideStart:r,onSlideMove:o,onSlideEnd:i,onHomeKeyDown:s,onEndKeyDown:l,onStepKeyDown:u,...f}=e,p=mg(Zd,n);return d.createElement(Ae.span,Y({},f,{ref:t,onKeyDown:ue(e.onKeyDown,m=>{m.key==="Home"?(s(m),m.preventDefault()):m.key==="End"?(l(m),m.preventDefault()):FP.concat(jP).includes(m.key)&&(u(m),m.preventDefault())}),onPointerDown:ue(e.onPointerDown,m=>{const g=m.target;g.setPointerCapture(m.pointerId),m.preventDefault(),p.thumbs.has(g)?g.focus():r(m)}),onPointerMove:ue(e.onPointerMove,m=>{m.target.hasPointerCapture(m.pointerId)&&o(m)}),onPointerUp:ue(e.onPointerUp,m=>{const g=m.target;g.hasPointerCapture(m.pointerId)&&(g.releasePointerCapture(m.pointerId),i(m))})}))}),Sq="SliderTrack",_q=d.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,o=mg(Sq,n);return d.createElement(Ae.span,Y({"data-disabled":o.disabled?"":void 0,"data-orientation":o.orientation},r,{ref:t}))}),W2="SliderRange",Eq=d.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,o=mg(W2,n),i=VP(W2,n),s=d.useRef(null),l=Ue(t,s),u=o.values.length,f=o.values.map(g=>HP(g,o.min,o.max)),p=u>1?Math.min(...f):0,m=100-Math.max(...f);return d.createElement(Ae.span,Y({"data-orientation":o.orientation,"data-disabled":o.disabled?"":void 0},r,{ref:l,style:{...e.style,[i.startEdge]:p+"%",[i.endEdge]:m+"%"}}))}),H2="SliderThumb",Cq=d.forwardRef((e,t)=>{const n=gq(e.__scopeSlider),[r,o]=d.useState(null),i=Ue(t,l=>o(l)),s=d.useMemo(()=>r?n().findIndex(l=>l.ref.current===r):-1,[n,r]);return d.createElement($q,Y({},e,{ref:i,index:s}))}),$q=d.forwardRef((e,t)=>{const{__scopeSlider:n,index:r,...o}=e,i=mg(H2,n),s=VP(H2,n),[l,u]=d.useState(null),f=Ue(t,E=>u(E)),p=yx(l),m=i.values[r],g=m===void 0?0:HP(m,i.min,i.max),y=Tq(r,i.values.length),x=p==null?void 0:p[s.size],S=x?Aq(x,g,s.direction):0;return d.useEffect(()=>{if(l)return i.thumbs.add(l),()=>{i.thumbs.delete(l)}},[l,i.thumbs]),d.createElement("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[s.startEdge]:`calc(${g}% + ${S}px)`}},d.createElement(U1.ItemSlot,{scope:e.__scopeSlider},d.createElement(Ae.span,Y({role:"slider","aria-label":e["aria-label"]||y,"aria-valuemin":i.min,"aria-valuenow":m,"aria-valuemax":i.max,"aria-orientation":i.orientation,"data-orientation":i.orientation,"data-disabled":i.disabled?"":void 0,tabIndex:i.disabled?void 0:0},o,{ref:f,style:m===void 0?{display:"none"}:e.style,onFocus:ue(e.onFocus,()=>{i.valueIndexToChangeRef.current=r})}))))}),Rq=e=>{const{value:t,...n}=e,r=d.useRef(null),o=Ux(t);return d.useEffect(()=>{const i=r.current,s=window.HTMLInputElement.prototype,u=Object.getOwnPropertyDescriptor(s,"value").set;if(o!==t&&u){const f=new Event("input",{bubbles:!0});u.call(i,t),i.dispatchEvent(f)}},[o,t]),d.createElement("input",Y({style:{display:"none"}},n,{ref:r,defaultValue:t}))};function kq(e=[],t,n){const r=[...e];return r[n]=t,r.sort((o,i)=>o-i)}function HP(e,t,n){const i=100/(n-t)*(e-t);return fd(i,[0,100])}function Tq(e,t){return t>2?`Value ${e+1} of ${t}`:t===2?["Minimum","Maximum"][e]:void 0}function Pq(e,t){if(e.length===1)return 0;const n=e.map(o=>Math.abs(o-t)),r=Math.min(...n);return n.indexOf(r)}function Aq(e,t,n){const r=e/2,i=nb([0,50],[0,r]);return(r-i(t)*n)*n}function Mq(e){return e.slice(0,-1).map((t,n)=>e[n+1]-t)}function Oq(e,t){if(t>0){const n=Mq(e);return Math.min(...n)>=t}return!0}function nb(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 Nq(e){return(String(e).split(".")[1]||"").length}function Dq(e,t){const n=Math.pow(10,t);return Math.round(e*n)/n}const KP=wq,Iq=_q,Lq=Eq,Fq=Cq,uo=d.forwardRef(({className:e,...t},n)=>v.jsxs(KP,{ref:n,className:_e("relative flex w-full touch-none select-none items-center",e),tabIndex:-1,...t,children:[v.jsx(Iq,{className:"relative h-1.5 w-full grow overflow-hidden rounded-full bg-primary/20 data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50",children:v.jsx(Lq,{className:"absolute h-full bg-primary data-[disabled]:cursor-not-allowed "})}),v.jsx(Fq,{tabIndex:-1,className:"block h-4 w-4 rounded-full border border-primary/60 bg-background shadow transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring data-[disabled]:cursor-not-allowed"})]}));uo.displayName=KP.displayName;const ll={capture:!0,passive:!1},jq=2,K2=(e,t,n,r,o,i)=>{if(e!==n&&t===r){if(e<0)return[0,r];if(e+t>i)return[i-r,r]}else{if(ti)return[e,i-e]}return[e,t]},zq=e=>{const{minHeight:t,minWidth:n,maxHeight:r,maxWidth:o,scale:i,show:s}=e,[l,u,f,p,{x:m,y:g,width:y,height:x},S,E,_,b,C,R]=xt(W=>[W.imageWidth,W.imageHeight,W.isInpainting,W.isSD(),W.cropperState,W.setCropperX,W.setCropperY,W.setCropperWidth,W.setCropperHeight,W.isCropperExtenderResizing,W.setIsCropperExtenderResizing]),[P,O]=d.useState(!1);d.useEffect(()=>{S(Math.round((o-512)/2)),E(Math.round((r-512)/2))},[r,o,l,u]);const[A,D]=d.useState({initX:0,initY:0,initHeight:0,initWidth:0,startResizeX:0,startResizeY:0,ord:"top"}),B=()=>{},V=(W,le)=>K2(W,le,m,y,n,o),J=(W,le)=>K2(W,le,g,x,t,r),G=W=>{if(f)return;const le=W.clientX,pe=W.clientY,$e=Math.round((pe-A.startResizeY)/i),Ve=Math.round((le-A.startResizeX)/i),We=()=>{const Re=A.initHeight-$e,Me=A.initY+$e,[Oe,ze]=J(Me,Re);b(ze),E(Oe)},Ne=()=>{const Re=A.initHeight+$e,[Me,Oe]=J(A.initY,Re);b(Oe),E(Me)},fe=()=>{const Re=A.initWidth-Ve,Me=A.initX+Ve,[Oe,ze]=V(Me,Re);_(ze),S(Oe)},xe=()=>{const Re=A.initWidth+Ve,[Me,Oe]=V(A.initX,Re);_(Oe),S(Me)};if(C)switch(A.ord){case"topleft":{We(),fe();break}case"topright":{We(),xe();break}case"bottomleft":{Ne(),fe();break}case"bottomright":{Ne(),xe();break}case"top":{We();break}case"right":{xe();break}case"bottom":{Ne();break}case"left":{fe();break}}if(P){const Re=A.initX+Ve,Me=A.initY+$e,[Oe,ze]=V(Re,A.initWidth),[Mt,ct]=J(Me,A.initHeight);_(ze),b(ct),S(Oe),E(Mt)}},se=()=>{C&&R(!1),P&&O(!1)};d.useEffect(()=>{if(C||P)return document.addEventListener("pointermove",G,ll),document.addEventListener("pointerup",se,ll),document.addEventListener("pointercancel",se,ll),()=>{document.removeEventListener("pointermove",G,ll),document.removeEventListener("pointerup",se,ll),document.removeEventListener("pointercancel",se,ll)}},[C,P,y,x,A]);const U=W=>{const{ord:le}=W.target.dataset;le&&(R(!0),D({initX:m,initY:g,initHeight:x,initWidth:y,startResizeX:W.clientX,startResizeY:W.clientY,ord:le}))},ne=(W,le,pe)=>{const We="w-[12px] h-[12px] z-[4] absolute content-[''] block border-2 border-primary borde pointer-events-auto hover:bg-primary";let Ne="0",fe="0",xe=pe,Re="-6px";return pe===""&&(Re="50%",le==="left"||le==="right"?(xe="top",fe="-50%"):(xe="left",Ne="-50%")),v.jsx("div",{className:_e(We,W),style:{[le]:-6,[xe]:Re,transform:`translate(${Ne}, ${fe}) scale(${1/i})`},"data-ord":le+pe,"aria-label":le+pe,tabIndex:-1,role:"button"})},M=()=>v.jsxs("div",{onFocus:B,onPointerDown:U,className:"absolute top-0 h-full w-full",children:[v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 w-full cursor-ns-resize h-[12px] mt-[-6px]","data-ord":"top"}),v.jsx("div",{className:"absolute pointer-events-auto top-0 right-0 h-full cursor-ew-resize w-[12px] mr-[-6px]","data-ord":"right"}),v.jsx("div",{className:"absolute pointer-events-auto bottom-0 left-0 w-full cursor-ns-resize h-[12px] mb-[-6px]","data-ord":"bottom"}),v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 h-full cursor-ew-resize w-[12px] ml-[-6px]","data-ord":"left"}),ne("cursor-nw-resize","top","left"),ne("cursor-ne-resize","top","right"),ne("cursor-sw-resize","bottom","left"),ne("cursor-se-resize","bottom","right"),ne("cursor-ns-resize","top",""),ne("cursor-ns-resize","bottom",""),ne("cursor-ew-resize","left",""),ne("cursor-ew-resize","right","")]}),ee=W=>{O(!0),D({initX:m,initY:g,initHeight:x,initWidth:y,startResizeX:W.clientX,startResizeY:W.clientY,ord:""})},H=()=>v.jsxs("div",{className:tx("border absolute pointer-events-auto px-2 py-1 rounded-full hover:cursor-move bg-background","origin-top-left top-0 left-0"),style:{transform:`scale(${1/i*.8})`},onPointerDown:ee,children:[y," x ",x]}),X=()=>v.jsx("div",{className:"outline-dashed outline-primary",style:{height:x,width:y,outlineWidth:`${jq/i*1.3}px`}});return s===!1||!p?null:v.jsx("div",{className:"absolute h-full w-full overflow-hidden pointer-events-none z-[2]",children:v.jsxs("div",{className:"relative pointer-events-none z-[2] [box-shadow:0_0_0_9999px_rgba(0,_0,_0,_0.5)]",style:{height:x,width:y,left:m,top:g},children:[X(),H(),M()]})})},Bq=()=>{const[e,t,n]=xt(r=>[r.interactiveSegState,r.resetInteractiveSegState,r.handleInteractiveSegAccept]);return e.isInteractiveSeg?v.jsxs("div",{className:"z-10 absolute top-[68px] rounded-xl border-solid border p-[8px] left-1/2 translate-x-[-50%] flex justify-center items-center gap-[8px] bg-background",children:[v.jsx(wn,{onClick:()=>{t()},size:"sm",variant:"secondary",children:"Cancel"}),v.jsx(wn,{size:"sm",onClick:()=>{n()},children:"Accept"})]}):null},Uq=e=>{const{x:t,y:n,positive:r}=e,o=r?"bg-[rgba(21,_215,_121,_0.936)] outline-[rgba(98,255,179,0.31)]":"bg-[rgba(237,_49,_55,_0.942)] outline-[rgba(255,89,95,0.31)]";return v.jsx("div",{className:`absolute h-[10px] w-[10px] rounded-[50%] ${o} outline-8 outline`,style:{left:t,top:n,transform:"translate(-50%, -50%)"}})},Vq=()=>{const e=xt(t=>t.interactiveSegState.clicks);return v.jsx("div",{className:"absolute h-full w-full overflow-hidden pointer-events-none",children:e.map(t=>v.jsx(Uq,{x:t[0],y:t[1],positive:t[2]===1},t[3]))})},Wq=()=>v.jsx("div",{children:v.jsx(Bq,{})}),cl={capture:!0,passive:!1},Hq=2,G2=(e,t,n,r)=>t{const{minHeight:t,minWidth:n,scale:r,show:o}=e,[i,s,l,u,{x:f,y:p,width:m,height:g},y,x,S,E,_,b,C]=xt(ee=>[ee.isInpainting,ee.imageHeight,ee.imageWidth,ee.isSD(),ee.extenderState,ee.setExtenderX,ee.setExtenderY,ee.setExtenderWidth,ee.setExtenderHeight,ee.settings.extenderDirection,ee.isCropperExtenderResizing,ee.setIsCropperExtenderResizing]),[R,P]=d.useState({initX:0,initY:0,initHeight:0,initWidth:0,startResizeX:0,startResizeY:0,ord:"top"}),O=()=>{},A=(ee,H)=>G2(ee,H,f,n),D=(ee,H)=>G2(ee,H,p,t),B=ee=>{if(i)return;const H=ee.clientX,X=ee.clientY,W=Math.round((X-R.startResizeY)/r),le=Math.round((H-R.startResizeX)/r),pe=()=>{const Ne=R.initHeight-W,fe=R.initY+W;let xe=fe,Re=Ne;if(_===Ln.xy)xe>0&&(xe=0,Re=R.initHeight-Math.abs(R.initY));else{const Me=D(fe,Ne);xe=Me[0],Re=Me[1]}E(Re),x(xe)},$e=()=>{const Ne=R.initHeight+W;let[fe,xe]=D(R.initY,Ne);_===Ln.xy&&xe{const Ne=R.initWidth-le,fe=R.initX+le;let xe=fe,Re=Ne;if(_===Ln.xy)xe>0&&(xe=0,Re=R.initWidth-Math.abs(R.initX));else{const Me=A(fe,Ne);xe=Me[0],Re=Me[1]}S(Re),y(xe)},We=()=>{const Ne=R.initWidth+le;let[fe,xe]=A(R.initX,Ne);_===Ln.xy&&xe{b&&C(!1)};d.useEffect(()=>{if(b)return document.addEventListener("pointermove",B,cl),document.addEventListener("pointerup",V,cl),document.addEventListener("pointercancel",V,cl),()=>{document.removeEventListener("pointermove",B,cl),document.removeEventListener("pointerup",V,cl),document.removeEventListener("pointercancel",V,cl)}},[b,m,g,R]);const J=ee=>{const{ord:H}=ee.target.dataset;H&&(C(!0),P({initX:f,initY:p,initHeight:g,initWidth:m,startResizeX:ee.clientX,startResizeY:ee.clientY,ord:H}))},G=(ee,H,X)=>{const pe="w-[12px] h-[12px] z-[4] absolute content-[''] block border-2 border-primary borde pointer-events-auto hover:bg-primary";let $e="0",Ve="0",We=X,Ne="-6px";return X===""&&(Ne="50%",H==="left"||H==="right"?(We="top",Ve="-50%"):(We="left",$e="-50%")),v.jsx("div",{className:_e(pe,ee),style:{[H]:-6,[We]:Ne,transform:`translate(${$e}, ${Ve}) scale(${1/r})`},"data-ord":H+X,"aria-label":H+X,tabIndex:-1,role:"button"})},se=()=>v.jsxs("div",{onFocus:O,onPointerDown:J,className:"absolute top-0 h-full w-full",children:[[Ln.y,Ln.xy].includes(_)?v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 w-full cursor-ns-resize h-[12px] mt-[-6px]","data-ord":"top"}),v.jsx("div",{className:"absolute pointer-events-auto bottom-0 left-0 w-full cursor-ns-resize h-[12px] mb-[-6px]","data-ord":"bottom"}),G("cursor-ns-resize","top",""),G("cursor-ns-resize","bottom","")]}):v.jsx(v.Fragment,{}),[Ln.x,Ln.xy].includes(_)?v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"absolute pointer-events-auto top-0 right-0 h-full cursor-ew-resize w-[12px] mr-[-6px]","data-ord":"right"}),v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 h-full cursor-ew-resize w-[12px] ml-[-6px]","data-ord":"left"}),G("cursor-ew-resize","left",""),G("cursor-ew-resize","right","")]}):v.jsx(v.Fragment,{}),_===Ln.xy?v.jsxs(v.Fragment,{children:[G("cursor-nw-resize","top","left"),G("cursor-ne-resize","top","right"),G("cursor-sw-resize","bottom","left"),G("cursor-se-resize","bottom","right")]}):v.jsx(v.Fragment,{})]}),U=ee=>{P({initX:f,initY:p,initHeight:g,initWidth:m,startResizeX:ee.clientX,startResizeY:ee.clientY,ord:""})},ne=()=>v.jsxs("div",{className:tx("border absolute pointer-events-auto px-2 py-1 rounded-full bg-background","origin-top-left top-0 left-0"),style:{transform:`scale(${1/r*.8})`},onPointerDown:U,children:[m," x ",g]}),M=()=>v.jsx("div",{className:_e("outline-dashed outline-primary"),style:{height:g,width:m,outlineWidth:`${Hq/r*1.3}px`}});return o===!1||!u?null:v.jsx("div",{className:"absolute h-full w-full pointer-events-none z-[2]",children:v.jsxs("div",{className:"relative pointer-events-none z-[2] [box-shadow:0_0_0_9999px_rgba(0,_0,_0,_0.5)]",style:{height:g,width:m,left:f,top:p},children:[M(),ne(),se()]})})},Gq=200,Yq=3,Xq=200,mu=300;function Zq(e){const{file:t}=e,{toast:n}=Id(),[r,o,i,s,l,u,f,p,m,g,y,x,S,E,_,b,C,R,P,O,A,D]=xt(K=>[K.disableShortCuts,K.windowSize,K.isInpainting,K.imageWidth,K.imageHeight,K.settings,K.serverConfig.enableAutoSaving,K.setImageSize,K.setBaseBrushSize,K.interactiveSegState,K.updateInteractiveSegState,K.handleCanvasMouseDown,K.handleCanvasMouseMove,K.undo,K.redo,K.undoDisabled(),K.redoDisabled(),K.getIsProcessing(),K.updateAppState,K.runMannually(),K.runInpainting,K.isCropperExtenderResizing]),B=xt(K=>K.editorState.baseBrushSize),V=xt(K=>K.getBrushSize()),J=xt(K=>K.editorState.renders),G=xt(K=>K.editorState.extraMasks),se=xt(K=>K.editorState.temporaryMasks),U=xt(K=>K.editorState.lineGroups),ne=xt(K=>K.editorState.curLineGroup),[M,ee]=d.useState(!1),[H,X]=Px(t),[W,le]=d.useState(),[pe,$e]=d.useState(),[{x:Ve,y:We},Ne]=d.useState({x:-1,y:-1}),[fe,xe]=d.useState(!1),[Re,Me]=d.useState(!1),[Oe,ze]=d.useState(!1),[Mt,ct]=d.useState(1),[Kt,Er]=d.useState(!1),[gt,Vs]=d.useState(1),L=o.width/2,Z=o.height/2,q=d.useRef(null),[we,me]=d.useState(!1),[de,ke]=d.useState(!1),[ft,ht]=d.useState(0),_n=d.useCallback(()=>ne.length!==0,[ne]);d.useEffect(()=>{if(!pe||!X||s===0||l===0)return;const K=J.length===0?H:J[J.length-1];pe.canvas.width=s,pe.canvas.height=l,pe.clearRect(0,0,pe.canvas.width,pe.canvas.height),pe.drawImage(K,0,0,s,l)},[J,H,X,pe,l,s]),d.useEffect(()=>{!W||!X||s===0||l===0||(W.canvas.width=s,W.canvas.height=l,W.clearRect(0,0,W.canvas.width,W.canvas.height),se.forEach(K=>{W.drawImage(K,0,0,s,l)}),G.forEach(K=>{W.drawImage(K,0,0,s,l)}),g.isInteractiveSeg&&g.tmpInteractiveSegMask&&W.drawImage(g.tmpInteractiveSegMask,0,0,s,l),ZR(W,ne))},[se,G,X,g,W,ne,l,s]);const Cr=d.useCallback(async()=>{let K=t;if(J.length>0){const Ye=J[J.length-1];K=await Nu(Ye.currentSrc,t.name,t.type)}return K},[t,J]),Ni=()=>J.length!==0,Co=d.useCallback(()=>{let K=512,Ye=512;return X?(J.length===0?(K=H.naturalWidth,Ye=H.naturalHeight):J.length!==0&&(K=J[J.length-1].width,Ye=J[J.length-1].height),[K,Ye]):[K,Ye]},[H,X,J]);d.useEffect(()=>{var ef;if(!X)return;const[K,Ye]=Co();(K!==s||Ye!==l)&&p(K,Ye);const st=o.width/K,Qr=(o.height-Gq)/Ye;let an=1;(st<1||Qr<1)&&(an=Math.min(st,Qr)),Vs(an),ct(an),console.log(`[on file load] image size: ${K}x${Ye}, scale: ${an}, initialCentered: ${we}`),W!=null&&W.canvas&&(console.log("[on file load] set canvas size"),K!=W.canvas.width&&(W.canvas.width=K),Ye!=W.canvas.height&&(W.canvas.height=Ye)),we||((ef=q.current)==null||ef.centerView(an,1),console.log("[on file load] centerView"),me(!0))},[q,l,s,H,X,o,we,Co]),d.useEffect(()=>{var K;console.log("[useEffect] centerView"),(K=q==null?void 0:q.current)==null||K.centerView(gt,1)},[l,s,q,gt]);const Vn=d.useCallback(()=>{if(!gt||!o)return;const K=q.current;if(!K)return;const Ye=(o.width-s*gt)/2,st=(o.height-l*gt)/2;K.setTransform(Ye,st,gt,200,"easeOutQuad"),K.instance.transformState.scale&&(K.instance.transformState.scale=gt),ct(gt),Er(!1)},[q,o,l,s,o.height,gt]);d.useEffect(()=>(window.addEventListener("resize",()=>{Vn()}),()=>{window.removeEventListener("resize",()=>{Vn()})}),[o,Vn]),Zn("Escape",()=>{R||(de?ke(!1):Vn())},[de,i,Vn]);const Di=K=>{const Ye=K.nativeEvent;Ne({x:Ye.pageX,y:Ye.pageY})},Ws=K=>{R||g.isInteractiveSeg||Oe||de&&ne.length!==0&&S(h0(K))},Ii=async K=>{P({isPluginRunning:!0});const Ye=await Cr();try{const st=await wk(!0,Ao.InteractiveSeg,Ye,void 0,K),{blob:Qr}=st,an=new Image;an.onload=()=>{y({tmpInteractiveSegMask:an})},an.src=Qr}catch(st){n({variant:"destructive",description:st.message?st.message:st.toString()})}P({isPluginRunning:!1})},Mc=K=>{if(hC(K)){ze(!1);return}!_n()||g.isInteractiveSeg||Oe||!H.src||!(W!=null&&W.canvas)||i||de&&(O?ke(!1):A())},Sg=K=>{if(g.isInteractiveSeg){const Ye=h0(K),st=[...g.clicks];fC(K)?st.push([Ye.x,Ye.y,0,st.length]):st.push([Ye.x,Ye.y,1,st.length]),Ii(st),y({clicks:st})}},_g=K=>{if(!(R||g.isInteractiveSeg||Oe||!X||!(W!=null&&W.canvas))&&!fC(K)){if(hC(K)){ze(!0);return}ke(!0),x(h0(K))}},Qd=K=>{K.preventDefault(),E()};Zn("meta+z,ctrl+z",Qd);const Oc=K=>{K.preventDefault(),_()};Zn("shift+ctrl+z,shift+meta+z",Oc),l2("Tab",K=>{K==null||K.preventDefault(),K==null||K.stopPropagation(),Ni()&&ee(()=>(window.setTimeout(()=>{ht(100)},10),!0))},K=>{K==null||K.preventDefault(),K==null||K.stopPropagation(),Ni()&&(window.setTimeout(()=>{ht(0)},10),window.setTimeout(()=>{ee(!1)},mu))});const Nc=d.useCallback(async()=>{if(t===void 0)return;if(f&&J.length>0){try{await Hj(J[J.length-1],t.name,t.type),n({description:"Save image success"})}catch(st){n({variant:"destructive",title:"Uh oh! Something went wrong.",description:st.message?st.message:st.toString()})}return}const K=t.name.replace(/(\.[\w\d_-]+)$/i,"_cleanup$1"),Ye=J[J.length-1];if(bF(Ye.currentSrc,K),u.enableDownloadMask){let st=t.name.replace(/(\.[\w\d_-]+)$/i,"_mask$1");st=st.replace(/\.[^/.]+$/,".jpg");const Qr=Wh(s,l,U),an=document.createElement("a");an.download=st,an.href=Qr.toDataURL("image/jpeg"),an.click()}},[t,f,J,u,l,s,U]);Zn("meta+s,ctrl+s",Nc);const Dc=K=>{K!==fe&&!Oe&&!D&&xe(K)},Eg=d.useCallback(()=>{if(R)return"default";if(Oe)return"grab";if(fe)return"none"},[fe,Oe,R]);Zn("[",()=>{let K=B;B>10&&(K=B-10),B<=10&&B>0&&(K=B-3),m(K)},[B]),Zn("]",()=>{m(B+10)},[B]),Zn("shift+r",()=>{O&&_n()&&A()},[O,A,_n]),Zn("ctrl+c,meta+c",async()=>{await vF()&&J.length>0&&W!=null&&W.canvas&&(await xF(W==null?void 0:W.canvas),n({title:"Copy inpainting result to clipboard"}))},[J,W]),l2(" ",K=>{r||(K==null||K.preventDefault(),K==null||K.stopPropagation(),xe(!1),ze(!0))},K=>{r||(K==null||K.preventDefault(),K==null||K.stopPropagation(),xe(!0),ze(!1))});const Ic=()=>{var Ye,st,Qr,an;let K=gt;return((st=(Ye=q.current)==null?void 0:Ye.instance)==null?void 0:st.transformState.scale)!==void 0&&(K=(an=(Qr=q.current)==null?void 0:Qr.instance)==null?void 0:an.transformState.scale),K},Jd=(K,Ye)=>{const st=Ic();return{width:`${V*st}px`,height:`${V*st}px`,left:`${K}px`,top:`${Ye}px`,transform:"translate(-50%, -50%)"}},Lc=K=>v.jsx("div",{className:"absolute rounded-[50%] border-[1px] border-[solid] border-[#ffcc00] pointer-events-none bg-[#ffcc00bb]",style:K}),Cg=K=>{m(K),Re||(Me(!0),window.setTimeout(()=>{Me(!1)},1e4))},$g=()=>v.jsx("div",{className:"absolute h-[20px] w-[20px] pointer-events-none rounded-[50%] bg-[rgba(21,_215,_121,_0.936)] [box-shadow:0_0_0_0_rgba(21,_215,_121,_0.936)] animate-pulse",style:{left:`${Ve}px`,top:`${We}px`,transform:"translate(-50%, -50%)"},children:v.jsx(dK,{})}),Rg=()=>v.jsx(fq,{ref:K=>{K&&(q.current=K)},panning:{disabled:!Oe,velocityDisabled:!0},wheel:{step:.05},centerZoomedOut:!0,alignmentAnimation:{disabled:!0},centerOnInit:!0,limitToBounds:!1,doubleClick:{disabled:!0},initialScale:gt,minScale:gt*.3,onPanning:()=>{Kt||Er(!0)},onZoom:K=>{ct(K.state.scale)},children:v.jsxs(mq,{contentStyle:{visibility:we?"visible":"hidden"},children:[v.jsxs("div",{className:"grid [grid-template-areas:'editor-content'] gap-y-4",children:[v.jsx("canvas",{className:"[grid-area:editor-content]",style:{clipPath:`inset(0 ${ft}% 0 0)`,transition:`clip-path ${mu}ms`},ref:K=>{if(K&&!pe){const Ye=K.getContext("2d");Ye&&$e(Ye)}}}),v.jsx("canvas",{className:_e("[grid-area:editor-content]",R?"pointer-events-none animate-pulse duration-600":""),style:{cursor:Eg(),clipPath:`inset(0 ${ft}% 0 0)`,transition:`clip-path ${mu}ms`},onContextMenu:K=>{K.preventDefault()},onMouseOver:()=>{Dc(!0),Me(!1)},onFocus:()=>Dc(!0),onMouseLeave:()=>Dc(!1),onMouseDown:_g,onMouseUp:Sg,onMouseMove:Ws,ref:K=>{if(K&&!W){const Ye=K.getContext("2d");Ye&&le(Ye)}}}),v.jsx("div",{className:"[grid-area:editor-content] pointer-events-none grid [grid-template-areas:'original-image-content']",style:{width:`${s}px`,height:`${l}px`},children:M&&v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"[grid-area:original-image-content] z-10 bg-primary h-full w-[6px] justify-self-end",style:{marginRight:`${ft}%`,transition:`margin-right ${mu}ms`}}),v.jsx("img",{className:"[grid-area:original-image-content]",src:H.src,alt:"original",style:{width:`${s}px`,height:`${l}px`}})]})})]}),v.jsx(zq,{maxHeight:l,maxWidth:s,minHeight:Math.min(512,l),minWidth:Math.min(512,s),scale:Ic(),show:u.showCropper}),v.jsx(Kq,{minHeight:Math.min(512,l),minWidth:Math.min(512,s),scale:Ic(),show:u.showExtender}),g.isInteractiveSeg?v.jsx(Vq,{}):v.jsx(v.Fragment,{})]})});return v.jsxs("div",{className:"flex w-screen h-screen justify-center items-center","aria-hidden":"true",onMouseMove:Di,onMouseUp:Mc,children:[Rg(),fe&&!i&&!Oe&&(g.isInteractiveSeg?$g():Lc(Jd(Ve,We))),Re&&Lc(Jd(L,Z)),v.jsxs("div",{className:"fixed flex bottom-5 border px-4 py-2 rounded-[3rem] gap-8 items-center justify-center backdrop-filter backdrop-blur-md bg-background/70",children:[v.jsx(uo,{className:"w-48",defaultValue:[50],min:Yq,max:Xq,step:1,tabIndex:-1,value:[B],onValueChange:K=>Cg(K[0]),onClick:()=>Me(!1)}),v.jsxs("div",{className:"flex gap-2",children:[v.jsx(yn,{tooltip:"Reset zoom & pan",disabled:Mt===gt&&Kt===!1,onClick:Vn,children:v.jsx(QU,{})}),v.jsx(yn,{tooltip:"Undo",onClick:Qd,disabled:b,children:v.jsx(aV,{})}),v.jsx(yn,{tooltip:"Redo",onClick:Oc,disabled:C,children:v.jsx(oV,{})}),v.jsx(yn,{tooltip:"Show original image",onPointerDown:K=>{K.preventDefault(),ee(()=>(window.setTimeout(()=>{ht(100)},10),!0))},onPointerUp:()=>{window.setTimeout(()=>{ht(0)},10),window.setTimeout(()=>{ee(!1)},mu)},disabled:J.length===0,children:v.jsx(JU,{})}),v.jsx(yn,{tooltip:"Save Image",disabled:!J.length,onClick:Nc,children:v.jsx(ZU,{})}),u.enableManualInpainting&&u.model.model_type==="inpaint"?v.jsx(yn,{tooltip:"Run Inpainting",disabled:R||!_n()&&G.length===0,onClick:()=>{A()},children:v.jsx(qU,{})}):v.jsx(v.Fragment,{})]})]})]})}const qq=()=>{const[e,t]=xt(n=>[n.imageWidth,n.imageHeight]);return!e||!t?null:v.jsxs("div",{className:"border rounded-lg px-2 py-[6px] z-10 bg-background",children:[e,"x",t]})},V1=["Enter"," "],Qq=["ArrowDown","PageUp","Home"],GP=["ArrowUp","PageDown","End"],Jq=[...Qq,...GP],eQ={ltr:[...V1,"ArrowRight"],rtl:[...V1,"ArrowLeft"]},tQ={ltr:["ArrowLeft"],rtl:["ArrowRight"]},gg="Menu",[md,nQ,rQ]=Kd(gg),[za,YP]=Mn(gg,[rQ,Fs,ng]),vg=Fs(),XP=ng(),[ZP,Us]=za(gg),[oQ,qd]=za(gg),iQ=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:o,onOpenChange:i,modal:s=!0}=e,l=vg(t),[u,f]=d.useState(null),p=d.useRef(!1),m=Ft(i),g=Tc(o);return d.useEffect(()=>{const y=()=>{p.current=!0,document.addEventListener("pointerdown",x,{capture:!0,once:!0}),document.addEventListener("pointermove",x,{capture:!0,once:!0})},x=()=>p.current=!1;return document.addEventListener("keydown",y,{capture:!0}),()=>{document.removeEventListener("keydown",y,{capture:!0}),document.removeEventListener("pointerdown",x,{capture:!0}),document.removeEventListener("pointermove",x,{capture:!0})}},[]),d.createElement(Fd,l,d.createElement(ZP,{scope:t,open:n,onOpenChange:m,content:u,onContentChange:f},d.createElement(oQ,{scope:t,onClose:d.useCallback(()=>m(!1),[m]),isUsingKeyboardRef:p,dir:g,modal:s},r)))},qP=d.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,o=vg(n);return d.createElement(Wm,Y({},o,r,{ref:t}))}),QP="MenuPortal",[sQ,JP]=za(QP,{forceMount:void 0}),aQ=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:o}=e,i=Us(QP,t);return d.createElement(sQ,{scope:t,forceMount:n},d.createElement(Sn,{present:n||i.open},d.createElement(jd,{asChild:!0,container:o},r)))},bo="MenuContent",[lQ,rb]=za(bo),cQ=d.forwardRef((e,t)=>{const n=JP(bo,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,i=Us(bo,e.__scopeMenu),s=qd(bo,e.__scopeMenu);return d.createElement(md.Provider,{scope:e.__scopeMenu},d.createElement(Sn,{present:r||i.open},d.createElement(md.Slot,{scope:e.__scopeMenu},s.modal?d.createElement(uQ,Y({},o,{ref:t})):d.createElement(dQ,Y({},o,{ref:t})))))}),uQ=d.forwardRef((e,t)=>{const n=Us(bo,e.__scopeMenu),r=d.useRef(null),o=Ue(t,r);return d.useEffect(()=>{const i=r.current;if(i)return Jm(i)},[]),d.createElement(ob,Y({},e,{ref:o,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:ue(e.onFocusOutside,i=>i.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)}))}),dQ=d.forwardRef((e,t)=>{const n=Us(bo,e.__scopeMenu);return d.createElement(ob,Y({},e,{ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)}))}),ob=d.forwardRef((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:o,onOpenAutoFocus:i,onCloseAutoFocus:s,disableOutsidePointerEvents:l,onEntryFocus:u,onEscapeKeyDown:f,onPointerDownOutside:p,onFocusOutside:m,onInteractOutside:g,onDismiss:y,disableOutsideScroll:x,...S}=e,E=Us(bo,n),_=qd(bo,n),b=vg(n),C=XP(n),R=nQ(n),[P,O]=d.useState(null),A=d.useRef(null),D=Ue(t,A,E.onContentChange),B=d.useRef(0),V=d.useRef(""),J=d.useRef(0),G=d.useRef(null),se=d.useRef("right"),U=d.useRef(0),ne=x?Qm:d.Fragment,M=x?{as:Zo,allowPinchZoom:!0}:void 0,ee=X=>{var W,le;const pe=V.current+X,$e=R().filter(Re=>!Re.disabled),Ve=document.activeElement,We=(W=$e.find(Re=>Re.ref.current===Ve))===null||W===void 0?void 0:W.textValue,Ne=$e.map(Re=>Re.textValue),fe=kQ(Ne,pe,We),xe=(le=$e.find(Re=>Re.textValue===fe))===null||le===void 0?void 0:le.ref.current;(function Re(Me){V.current=Me,window.clearTimeout(B.current),Me!==""&&(B.current=window.setTimeout(()=>Re(""),1e3))})(pe),xe&&setTimeout(()=>xe.focus())};d.useEffect(()=>()=>window.clearTimeout(B.current),[]),Zm();const H=d.useCallback(X=>{var W,le;return se.current===((W=G.current)===null||W===void 0?void 0:W.side)&&PQ(X,(le=G.current)===null||le===void 0?void 0:le.area)},[]);return d.createElement(lQ,{scope:n,searchRef:V,onItemEnter:d.useCallback(X=>{H(X)&&X.preventDefault()},[H]),onItemLeave:d.useCallback(X=>{var W;H(X)||((W=A.current)===null||W===void 0||W.focus(),O(null))},[H]),onTriggerLeave:d.useCallback(X=>{H(X)&&X.preventDefault()},[H]),pointerGraceTimerRef:J,onPointerGraceIntentChange:d.useCallback(X=>{G.current=X},[])},d.createElement(ne,M,d.createElement(Xm,{asChild:!0,trapped:o,onMountAutoFocus:ue(i,X=>{var W;X.preventDefault(),(W=A.current)===null||W===void 0||W.focus()}),onUnmountAutoFocus:s},d.createElement(Ec,{asChild:!0,disableOutsidePointerEvents:l,onEscapeKeyDown:f,onPointerDownOutside:p,onFocusOutside:m,onInteractOutside:g,onDismiss:y},d.createElement(JT,Y({asChild:!0},C,{dir:_.dir,orientation:"vertical",loop:r,currentTabStopId:P,onCurrentTabStopIdChange:O,onEntryFocus:ue(u,X=>{_.isUsingKeyboardRef.current||X.preventDefault()})}),d.createElement(Hm,Y({role:"menu","aria-orientation":"vertical","data-state":iA(E.open),"data-radix-menu-content":"",dir:_.dir},b,S,{ref:D,style:{outline:"none",...S.style},onKeyDown:ue(S.onKeyDown,X=>{const le=X.target.closest("[data-radix-menu-content]")===X.currentTarget,pe=X.ctrlKey||X.altKey||X.metaKey,$e=X.key.length===1;le&&(X.key==="Tab"&&X.preventDefault(),!pe&&$e&&ee(X.key));const Ve=A.current;if(X.target!==Ve||!Jq.includes(X.key))return;X.preventDefault();const Ne=R().filter(fe=>!fe.disabled).map(fe=>fe.ref.current);GP.includes(X.key)&&Ne.reverse(),$Q(Ne)}),onBlur:ue(e.onBlur,X=>{X.currentTarget.contains(X.target)||(window.clearTimeout(B.current),V.current="")}),onPointerMove:ue(e.onPointerMove,gd(X=>{const W=X.target,le=U.current!==X.clientX;if(X.currentTarget.contains(W)&&le){const pe=X.clientX>U.current?"right":"left";se.current=pe,U.current=X.clientX}}))})))))))}),fQ=d.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return d.createElement(Ae.div,Y({},r,{ref:t}))}),W1="MenuItem",Y2="menu.itemSelect",ib=d.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...o}=e,i=d.useRef(null),s=qd(W1,e.__scopeMenu),l=rb(W1,e.__scopeMenu),u=Ue(t,i),f=d.useRef(!1),p=()=>{const m=i.current;if(!n&&m){const g=new CustomEvent(Y2,{bubbles:!0,cancelable:!0});m.addEventListener(Y2,y=>r==null?void 0:r(y),{once:!0}),dx(m,g),g.defaultPrevented?f.current=!1:s.onClose()}};return d.createElement(eA,Y({},o,{ref:u,disabled:n,onClick:ue(e.onClick,p),onPointerDown:m=>{var g;(g=e.onPointerDown)===null||g===void 0||g.call(e,m),f.current=!0},onPointerUp:ue(e.onPointerUp,m=>{var g;f.current||(g=m.currentTarget)===null||g===void 0||g.click()}),onKeyDown:ue(e.onKeyDown,m=>{const g=l.searchRef.current!=="";n||g&&m.key===" "||V1.includes(m.key)&&(m.currentTarget.click(),m.preventDefault())})}))}),eA=d.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:o,...i}=e,s=rb(W1,n),l=XP(n),u=d.useRef(null),f=Ue(t,u),[p,m]=d.useState(!1),[g,y]=d.useState("");return d.useEffect(()=>{const x=u.current;if(x){var S;y(((S=x.textContent)!==null&&S!==void 0?S:"").trim())}},[i.children]),d.createElement(md.ItemSlot,{scope:n,disabled:r,textValue:o??g},d.createElement(e3,Y({asChild:!0},l,{focusable:!r}),d.createElement(Ae.div,Y({role:"menuitem","data-highlighted":p?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0},i,{ref:f,onPointerMove:ue(e.onPointerMove,gd(x=>{r?s.onItemLeave(x):(s.onItemEnter(x),x.defaultPrevented||x.currentTarget.focus())})),onPointerLeave:ue(e.onPointerLeave,gd(x=>s.onItemLeave(x))),onFocus:ue(e.onFocus,()=>m(!0)),onBlur:ue(e.onBlur,()=>m(!1))}))))}),hQ=d.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...o}=e;return d.createElement(nA,{scope:e.__scopeMenu,checked:n},d.createElement(ib,Y({role:"menuitemcheckbox","aria-checked":am(n)?"mixed":n},o,{ref:t,"data-state":sb(n),onSelect:ue(o.onSelect,()=>r==null?void 0:r(am(n)?!0:!n),{checkForDefaultPrevented:!1})})))}),pQ="MenuRadioGroup",[$te,mQ]=za(pQ,{value:void 0,onValueChange:()=>{}}),gQ="MenuRadioItem",vQ=d.forwardRef((e,t)=>{const{value:n,...r}=e,o=mQ(gQ,e.__scopeMenu),i=n===o.value;return d.createElement(nA,{scope:e.__scopeMenu,checked:i},d.createElement(ib,Y({role:"menuitemradio","aria-checked":i},r,{ref:t,"data-state":sb(i),onSelect:ue(r.onSelect,()=>{var s;return(s=o.onValueChange)===null||s===void 0?void 0:s.call(o,n)},{checkForDefaultPrevented:!1})})))}),tA="MenuItemIndicator",[nA,yQ]=za(tA,{checked:!1}),wQ=d.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...o}=e,i=yQ(tA,n);return d.createElement(Sn,{present:r||am(i.checked)||i.checked===!0},d.createElement(Ae.span,Y({},o,{ref:t,"data-state":sb(i.checked)})))}),xQ=d.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return d.createElement(Ae.div,Y({role:"separator","aria-orientation":"horizontal"},r,{ref:t}))}),rA="MenuSub",[bQ,oA]=za(rA),SQ=e=>{const{__scopeMenu:t,children:n,open:r=!1,onOpenChange:o}=e,i=Us(rA,t),s=vg(t),[l,u]=d.useState(null),[f,p]=d.useState(null),m=Ft(o);return d.useEffect(()=>(i.open===!1&&m(!1),()=>m(!1)),[i.open,m]),d.createElement(Fd,s,d.createElement(ZP,{scope:t,open:r,onOpenChange:m,content:f,onContentChange:p},d.createElement(bQ,{scope:t,contentId:nr(),triggerId:nr(),trigger:l,onTriggerChange:u},n)))},Sh="MenuSubTrigger",_Q=d.forwardRef((e,t)=>{const n=Us(Sh,e.__scopeMenu),r=qd(Sh,e.__scopeMenu),o=oA(Sh,e.__scopeMenu),i=rb(Sh,e.__scopeMenu),s=d.useRef(null),{pointerGraceTimerRef:l,onPointerGraceIntentChange:u}=i,f={__scopeMenu:e.__scopeMenu},p=d.useCallback(()=>{s.current&&window.clearTimeout(s.current),s.current=null},[]);return d.useEffect(()=>p,[p]),d.useEffect(()=>{const m=l.current;return()=>{window.clearTimeout(m),u(null)}},[l,u]),d.createElement(qP,Y({asChild:!0},f),d.createElement(eA,Y({id:o.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":o.contentId,"data-state":iA(n.open)},e,{ref:Nm(t,o.onTriggerChange),onClick:m=>{var g;(g=e.onClick)===null||g===void 0||g.call(e,m),!(e.disabled||m.defaultPrevented)&&(m.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:ue(e.onPointerMove,gd(m=>{i.onItemEnter(m),!m.defaultPrevented&&!e.disabled&&!n.open&&!s.current&&(i.onPointerGraceIntentChange(null),s.current=window.setTimeout(()=>{n.onOpenChange(!0),p()},100))})),onPointerLeave:ue(e.onPointerLeave,gd(m=>{var g;p();const y=(g=n.content)===null||g===void 0?void 0:g.getBoundingClientRect();if(y){var x;const S=(x=n.content)===null||x===void 0?void 0:x.dataset.side,E=S==="right",_=E?-5:5,b=y[E?"left":"right"],C=y[E?"right":"left"];i.onPointerGraceIntentChange({area:[{x:m.clientX+_,y:m.clientY},{x:b,y:y.top},{x:C,y:y.top},{x:C,y:y.bottom},{x:b,y:y.bottom}],side:S}),window.clearTimeout(l.current),l.current=window.setTimeout(()=>i.onPointerGraceIntentChange(null),300)}else{if(i.onTriggerLeave(m),m.defaultPrevented)return;i.onPointerGraceIntentChange(null)}})),onKeyDown:ue(e.onKeyDown,m=>{const g=i.searchRef.current!=="";if(!(e.disabled||g&&m.key===" ")&&eQ[r.dir].includes(m.key)){var y;n.onOpenChange(!0),(y=n.content)===null||y===void 0||y.focus(),m.preventDefault()}})})))}),EQ="MenuSubContent",CQ=d.forwardRef((e,t)=>{const n=JP(bo,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,i=Us(bo,e.__scopeMenu),s=qd(bo,e.__scopeMenu),l=oA(EQ,e.__scopeMenu),u=d.useRef(null),f=Ue(t,u);return d.createElement(md.Provider,{scope:e.__scopeMenu},d.createElement(Sn,{present:r||i.open},d.createElement(md.Slot,{scope:e.__scopeMenu},d.createElement(ob,Y({id:l.contentId,"aria-labelledby":l.triggerId},o,{ref:f,align:"start",side:s.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:p=>{var m;s.isUsingKeyboardRef.current&&((m=u.current)===null||m===void 0||m.focus()),p.preventDefault()},onCloseAutoFocus:p=>p.preventDefault(),onFocusOutside:ue(e.onFocusOutside,p=>{p.target!==l.trigger&&i.onOpenChange(!1)}),onEscapeKeyDown:ue(e.onEscapeKeyDown,p=>{s.onClose(),p.preventDefault()}),onKeyDown:ue(e.onKeyDown,p=>{const m=p.currentTarget.contains(p.target),g=tQ[s.dir].includes(p.key);if(m&&g){var y;i.onOpenChange(!1),(y=l.trigger)===null||y===void 0||y.focus(),p.preventDefault()}})})))))});function iA(e){return e?"open":"closed"}function am(e){return e==="indeterminate"}function sb(e){return am(e)?"indeterminate":e?"checked":"unchecked"}function $Q(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function RQ(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function kQ(e,t,n){const o=t.length>1&&Array.from(t).every(f=>f===t[0])?t[0]:t,i=n?e.indexOf(n):-1;let s=RQ(e,Math.max(i,0));o.length===1&&(s=s.filter(f=>f!==n));const u=s.find(f=>f.toLowerCase().startsWith(o.toLowerCase()));return u!==n?u:void 0}function TQ(e,t){const{x:n,y:r}=e;let o=!1;for(let i=0,s=t.length-1;ir!=p>r&&n<(f-l)*(r-u)/(p-u)+l&&(o=!o)}return o}function PQ(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return TQ(n,t)}function gd(e){return t=>t.pointerType==="mouse"?e(t):void 0}const AQ=iQ,MQ=qP,OQ=aQ,NQ=cQ,DQ=fQ,IQ=ib,LQ=hQ,FQ=vQ,jQ=wQ,zQ=xQ,BQ=SQ,UQ=_Q,VQ=CQ,sA="DropdownMenu",[WQ,Rte]=Mn(sA,[YP]),_r=YP(),[HQ,aA]=WQ(sA),KQ=e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:o,defaultOpen:i,onOpenChange:s,modal:l=!0}=e,u=_r(t),f=d.useRef(null),[p=!1,m]=Zr({prop:o,defaultProp:i,onChange:s});return d.createElement(HQ,{scope:t,triggerId:nr(),triggerRef:f,contentId:nr(),open:p,onOpenChange:m,onOpenToggle:d.useCallback(()=>m(g=>!g),[m]),modal:l},d.createElement(AQ,Y({},u,{open:p,onOpenChange:m,dir:r,modal:l}),n))},GQ="DropdownMenuTrigger",YQ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...o}=e,i=aA(GQ,n),s=_r(n);return d.createElement(MQ,Y({asChild:!0},s),d.createElement(Ae.button,Y({type:"button",id:i.triggerId,"aria-haspopup":"menu","aria-expanded":i.open,"aria-controls":i.open?i.contentId:void 0,"data-state":i.open?"open":"closed","data-disabled":r?"":void 0,disabled:r},o,{ref:Nm(t,i.triggerRef),onPointerDown:ue(e.onPointerDown,l=>{!r&&l.button===0&&l.ctrlKey===!1&&(i.onOpenToggle(),i.open||l.preventDefault())}),onKeyDown:ue(e.onKeyDown,l=>{r||(["Enter"," "].includes(l.key)&&i.onOpenToggle(),l.key==="ArrowDown"&&i.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(l.key)&&l.preventDefault())})})))}),XQ=e=>{const{__scopeDropdownMenu:t,...n}=e,r=_r(t);return d.createElement(OQ,Y({},r,n))},ZQ="DropdownMenuContent",qQ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=aA(ZQ,n),i=_r(n),s=d.useRef(!1);return d.createElement(NQ,Y({id:o.contentId,"aria-labelledby":o.triggerId},i,r,{ref:t,onCloseAutoFocus:ue(e.onCloseAutoFocus,l=>{var u;s.current||(u=o.triggerRef.current)===null||u===void 0||u.focus(),s.current=!1,l.preventDefault()}),onInteractOutside:ue(e.onInteractOutside,l=>{const u=l.detail.originalEvent,f=u.button===0&&u.ctrlKey===!0,p=u.button===2||f;(!o.modal||p)&&(s.current=!0)}),style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}}))}),QQ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(DQ,Y({},o,r,{ref:t}))}),JQ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(IQ,Y({},o,r,{ref:t}))}),eJ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(LQ,Y({},o,r,{ref:t}))}),tJ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(FQ,Y({},o,r,{ref:t}))}),nJ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(jQ,Y({},o,r,{ref:t}))}),rJ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(zQ,Y({},o,r,{ref:t}))}),oJ=e=>{const{__scopeDropdownMenu:t,children:n,open:r,onOpenChange:o,defaultOpen:i}=e,s=_r(t),[l=!1,u]=Zr({prop:r,defaultProp:i,onChange:o});return d.createElement(BQ,Y({},s,{open:l,onOpenChange:u}),n)},iJ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(UQ,Y({},o,r,{ref:t}))}),sJ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(VQ,Y({},o,r,{ref:t,style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}}))}),aJ=KQ,lJ=YQ,cJ=XQ,lA=qQ,cA=QQ,uA=JQ,dA=eJ,fA=tJ,hA=nJ,pA=rJ,uJ=oJ,mA=iJ,gA=sJ,dJ=aJ,fJ=lJ,X2=uJ,H1=d.forwardRef(({className:e,inset:t,children:n,...r},o)=>v.jsxs(mA,{ref:o,className:_e("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",e),...r,children:[n,v.jsx(tz,{className:"ml-auto h-4 w-4"})]}));H1.displayName=mA.displayName;const K1=d.forwardRef(({className:e,...t},n)=>v.jsx(gA,{ref:n,className:_e("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...t}));K1.displayName=gA.displayName;const vA=d.forwardRef(({className:e,sideOffset:t=4,...n},r)=>v.jsx(cJ,{children:v.jsx(lA,{ref:r,sideOffset:t,className:_e("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md","data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),onCloseAutoFocus:o=>o.preventDefault(),...n})}));vA.displayName=lA.displayName;const fl=d.forwardRef(({className:e,inset:t,...n},r)=>v.jsx(uA,{ref:r,className:_e("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",e),...n}));fl.displayName=uA.displayName;const hJ=d.forwardRef(({className:e,children:t,checked:n,...r},o)=>v.jsxs(dA,{ref:o,className:_e("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),checked:n,...r,children:[v.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:v.jsx(hA,{children:v.jsx(xk,{className:"h-4 w-4"})})}),t]}));hJ.displayName=dA.displayName;const pJ=d.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(fA,{ref:r,className:_e("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[v.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:v.jsx(hA,{children:v.jsx(sz,{className:"h-4 w-4 fill-current"})})}),t]}));pJ.displayName=fA.displayName;const mJ=d.forwardRef(({className:e,inset:t,...n},r)=>v.jsx(cA,{ref:r,className:_e("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",e),...n}));mJ.displayName=cA.displayName;const gJ=d.forwardRef(({className:e,...t},n)=>v.jsx(pA,{ref:n,className:_e("-mx-1 my-1 h-px bg-muted",e),...t}));gJ.displayName=pA.displayName;const Z2={RemoveBG:{IconClass:GC,showName:"RemoveBG"},AnimeSeg:{IconClass:GC,showName:"Anime Segmentation"},RealESRGAN:{IconClass:Qk,showName:"RealESRGAN"},GFPGAN:{IconClass:YC,showName:"GFPGAN"},RestoreFormer:{IconClass:YC,showName:"RestoreFormer"},InteractiveSeg:{IconClass:rV,showName:"Interactive Segmentation"}},vJ=()=>{const[e,t,n,r,o]=xt(p=>[p.file,p.serverConfig.plugins,p.isPluginRunning,p.updateInteractiveSegState,p.runRenderablePlugin]),i=!e;if(t.length===0)return null;const s=(p,m)=>{m==="InteractiveSeg"?r({isInteractiveSeg:!0}):o(p,m)},l=()=>v.jsxs(X2,{children:[v.jsx(H1,{disabled:i,children:v.jsxs("div",{className:"flex gap-2 items-center",children:[v.jsx(Qk,{}),"RealESRGAN"]})}),v.jsxs(K1,{children:[v.jsx(fl,{onClick:()=>o(!1,"RealESRGAN",{upscale:2}),children:"upscale 2x"}),v.jsx(fl,{onClick:()=>o(!1,"RealESRGAN",{upscale:4}),children:"upscale 4x"})]})]},"RealESRGAN"),u=p=>{const{IconClass:m,showName:g}=Z2[p.name];return v.jsxs(X2,{children:[v.jsx(H1,{disabled:i,children:v.jsxs("div",{className:"flex gap-2 items-center",children:[v.jsx(m,{className:"p-1"}),g]})}),v.jsxs(K1,{children:[v.jsx(fl,{onClick:()=>s(!1,p.name),children:"Remove Background"}),v.jsx(fl,{onClick:()=>s(!0,p.name),children:"Generate Mask"})]})]},p.name)},f=()=>t.map(p=>{const{IconClass:m,showName:g}=Z2[p.name];return p.name==="RealESRGAN"?l():p.name==="RemoveBG"||p.name==="AnimeSeg"?u(p):v.jsx(fl,{onClick:()=>s(!1,p.name),disabled:i,children:v.jsxs("div",{className:"flex gap-2 items-center",children:[v.jsx(m,{className:"p-1"}),g]})},p.name)});return v.jsxs(dJ,{modal:!1,children:[v.jsx(fJ,{className:"border rounded-lg z-10 bg-background outline-none",tabIndex:-1,children:v.jsx(wn,{variant:"ghost",size:"icon",asChild:!0,className:"p-1.5",children:n?v.jsx("div",{role:"status",children:v.jsxs("svg",{"aria-hidden":"true",className:"w-5 h-5 animate-spin fill-primary",viewBox:"0 0 100 101",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[v.jsx("path",{d:"M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z",fill:"currentColor"}),v.jsx("path",{d:"M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z",fill:"currentFill"})]})}):v.jsx(KU,{strokeWidth:1})})}),v.jsx(vA,{side:"bottom",align:"start",children:f()})]})},yJ=Cx,wJ=xT,xJ=$x,yA=d.forwardRef(({className:e,...t},n)=>v.jsx(zd,{className:_e("fixed inset-0 bg-background/80 backdrop-blur-sm data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t,ref:n}));yA.displayName=zd.displayName;const bJ=Dm("fixed gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=closed]:duration-200 data-[state=open]:duration-300",{variants:{side:{top:"inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",bottom:"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",left:"inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",right:"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm"}},defaultVariants:{side:"right"}}),wA=d.forwardRef(({side:e="right",className:t,children:n,...r},o)=>v.jsxs(xJ,{children:[v.jsx(yA,{}),v.jsx(Bd,{ref:o,className:_e(bJ({side:e}),t),...r,children:n})]}));wA.displayName=Bd.displayName;const xA=({className:e,...t})=>v.jsx("div",{className:_e("flex flex-col space-y-2 text-center sm:text-left",e),...t});xA.displayName="SheetHeader";const SJ=d.forwardRef(({className:e,...t},n)=>v.jsx(Ud,{ref:n,className:_e("text-lg font-semibold text-foreground",e),...t}));SJ.displayName=Ud.displayName;const _J=d.forwardRef(({className:e,...t},n)=>v.jsx(Vd,{ref:n,className:_e("text-sm text-muted-foreground",e),...t}));_J.displayName=Vd.displayName;const Ut=({children:e})=>v.jsx("div",{className:"flex justify-between items-center pr-2",children:e}),Pt=({text:e,toolTip:t="",url:n,htmlFor:r,disabled:o=!1})=>v.jsxs(Zk,{children:[v.jsx(qk,{asChild:!0,children:v.jsx(Qx,{htmlFor:r||e.toLowerCase().replace(" ","-"),className:"font-medium",disabled:o,children:e})}),t||n?v.jsxs(Sx,{className:"flex flex-col max-w-xs text-sm",side:"left",children:[v.jsx("p",{children:t}),n?v.jsx(wn,{variant:"link",className:"justify-end",children:v.jsx("a",{href:n,target:"_blank",children:"More info"})}):v.jsx(v.Fragment,{})]}):v.jsx(v.Fragment,{})]}),EJ=()=>{const[e,t]=xt(n=>[n.settings,n.updateSettings]);return v.jsxs("div",{className:"flex flex-col gap-4 mt-4",children:[v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{htmlFor:"steps",text:"Steps",toolTip:"The number of denoising steps. More denoising steps usually lead to a higher quality image at the expense of slower inference."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[30],min:1,max:100,step:1,value:[Math.floor(e.ldmSteps)],onValueChange:n=>t({ldmSteps:n[0]})}),v.jsx(Yn,{id:"steps",className:"w-[60px] rounded-full",numberValue:e.ldmSteps,allowFloat:!1,onNumberValueChange:n=>{t({ldmSteps:n})}})]})]}),v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Sampler"}),v.jsxs(Uo,{value:e.ldmSampler,onValueChange:n=>{t({ldmSampler:n})},children:[v.jsx(go,{className:"w-[100px]",children:v.jsx(Vo,{placeholder:"Select sampler"})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:Object.values(Qw).map(n=>v.jsx(yo,{value:n,children:n},n))})})]})]})]})},_h=({text:e,onClick:t})=>{const[n]=xt(r=>[r.settings.showExtender]);return v.jsx(wn,{variant:"outline",className:"p-1 h-8",disabled:!n,onClick:t,children:v.jsx("div",{className:"flex items-center gap-1",children:e})})},CJ=()=>{const[e,t,n,r,o,i,s,l,u,f,p]=xt(M=>[M.serverConfig.samplers,M.settings,M.paintByExampleFile,M.getIsProcessing(),M.updateSettings,M.runInpainting,M.updateAppState,M.updateExtenderByBuiltIn,M.updateExtenderDirection,M.adjustMask,M.clearMask]),[m,g]=Px(n),y=d.useRef(null);DT(y,()=>{y!=null&&y.current&&y.current.blur()});const x=M=>{M.key==="Enter"&&M.ctrlKey&&t.prompt.length!==0&&i()},S=()=>v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Cropper",toolTip:"Inpainting on part of image, improve inference speed and reduce memory usage."}),v.jsx(co,{id:"cropper",checked:t.showCropper,onCheckedChange:M=>{o({showCropper:M}),M&&o({showExtender:!1})}})]}),E=()=>t.model.support_controlnet?v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex justify-between items-center pr-2",children:[v.jsx(Pt,{text:"ControlNet",toolTip:"Using an additional conditioning image to control how an image is generated",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#controlnet"}),v.jsx(co,{id:"controlnet",checked:t.enableControlnet,onCheckedChange:M=>{o({enableControlnet:M})}})]}),v.jsx("div",{className:"flex flex-col gap-1",children:v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[100],min:1,max:100,step:1,disabled:!t.enableControlnet,value:[Math.floor(t.controlnetConditioningScale*100)],onValueChange:M=>o({controlnetConditioningScale:M[0]/100})}),v.jsx(Yn,{id:"controlnet-weight",className:"w-[60px] rounded-full",disabled:!t.enableControlnet,numberValue:t.controlnetConditioningScale,allowFloat:!1,onNumberValueChange:M=>{o({controlnetConditioningScale:M})}})]})}),v.jsx("div",{className:"pr-2",children:v.jsxs(Uo,{defaultValue:t.controlnetMethod,value:t.controlnetMethod,onValueChange:M=>{o({controlnetMethod:M})},disabled:!t.enableControlnet,children:[v.jsx(go,{children:v.jsx(Vo,{placeholder:"Select control method"})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:Object.values(t.model.controlnets).map(M=>v.jsx(yo,{value:M,children:M.split("/")[1]},M))})})]})})]}),v.jsx(gn,{})]}):null,_=()=>t.model.support_lcm_lora?v.jsxs(v.Fragment,{children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"LCM LoRA",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inference_with_lcm_lora",toolTip:"Enable quality image generation in typically 2-4 steps. Suggest disabling guidance_scale by setting it to 0. You can also try values between 1.0 and 2.0. When LCM Lora is enabled, LCMSampler will be used automatically."}),v.jsx(co,{id:"lcm-lora",checked:t.enableLCMLora,onCheckedChange:M=>{o({enableLCMLora:M})}})]}),v.jsx(gn,{})]}):null,b=()=>t.model.support_freeu?v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex justify-between items-center pr-2",children:[v.jsx(Pt,{text:"FreeU",toolTip:"FreeU is a technique for improving image quality. Different models may require different FreeU-specific hyperparameters, which can be viewed in the more info section.",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/freeu"}),v.jsx(co,{id:"freeu",checked:t.enableFreeu,onCheckedChange:M=>{o({enableFreeu:M})}})]}),v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex justify-center gap-6",children:[v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-s1",text:"s1",disabled:!t.enableFreeu}),v.jsx(Yn,{id:"freeu-s1",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.s1,allowFloat:!0,onNumberValueChange:M=>{o({freeuConfig:{...t.freeuConfig,s1:M}})}})]}),v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-s2",text:"s2",disabled:!t.enableFreeu}),v.jsx(Yn,{id:"freeu-s2",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.s2,allowFloat:!0,onNumberValueChange:M=>{o({freeuConfig:{...t.freeuConfig,s2:M}})}})]})]}),v.jsxs("div",{className:"flex justify-center gap-6",children:[v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-b1",text:"b1",disabled:!t.enableFreeu}),v.jsx(Yn,{id:"freeu-b1",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.b1,allowFloat:!0,onNumberValueChange:M=>{o({freeuConfig:{...t.freeuConfig,b1:M}})}})]}),v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-b2",text:"b2",disabled:!t.enableFreeu}),v.jsx(Yn,{id:"freeu-b2",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.b2,allowFloat:!0,onNumberValueChange:M=>{o({freeuConfig:{...t.freeuConfig,b2:M}})}})]})]})]}),v.jsx(gn,{})]}):null,C=()=>t.model.need_prompt?v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsx(Pt,{text:"Negative prompt",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#negative-prompt",toolTip:"Negative prompt guides the model away from generating certain things in an image"}),v.jsx("div",{className:"pl-2 pr-4",children:v.jsx(Dx,{ref:y,rows:4,onKeyUp:x,className:"max-h-[8rem] overflow-y-auto mb-2",placeholder:"",id:"negative-prompt",value:t.negativePrompt,onInput:M=>{M.preventDefault(),M.stopPropagation();const ee=M.target;o({negativePrompt:ee.value})}})})]}):null,R=()=>t.model.name!==XR?null:v.jsxs("div",{children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Example Image",toolTip:"An example image to guide image generation."}),v.jsx(f1,{tooltip:"Upload example image",onFileUpload:M=>{s({paintByExampleFile:M})},children:v.jsx(Jk,{})})]}),g?v.jsx("div",{className:"flex justify-center items-center",children:v.jsx("img",{src:m.src,alt:"example",className:"max-w-[200px] max-h-[200px] m-3"})}):v.jsx(v.Fragment,{}),v.jsx(wn,{variant:"default",className:"w-full",disabled:r||!g,onClick:()=>{i()},children:"Paint"})]}),P=()=>t.model.name!==uF?null:v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Image guidance scale",toolTip:"Push the generated image towards the inital image. Higher image guidance scale encourages generated images that are closely linked to the source image, usually at the expense of lower image quality.",url:"https://huggingface.co/docs/diffusers/main/en/api/pipelines/pix2pix"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[150],min:100,max:1e3,step:1,value:[Math.floor(t.p2pImageGuidanceScale*100)],onValueChange:M=>o({p2pImageGuidanceScale:M[0]/100})}),v.jsx(Yn,{id:"image-guidance-scale",className:"w-[60px] rounded-full",numberValue:t.p2pImageGuidanceScale,allowFloat:!0,onNumberValueChange:M=>{o({p2pImageGuidanceScale:M})}})]})]}),O=()=>t.model.support_strength?v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Strength",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#strength",toolTip:"Strength is a measure of how much noise is added to the base image, which influences how similar the output is to the base image. Higher value means more noise and more different from the base image"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[100],min:10,max:100,step:1,value:[Math.floor(t.sdStrength*100)],onValueChange:M=>o({sdStrength:M[0]/100})}),v.jsx(Yn,{id:"strength",className:"w-[60px] rounded-full",numberValue:t.sdStrength,allowFloat:!0,onNumberValueChange:M=>{o({sdStrength:M})}})]})]}):null,A=()=>t.model.support_outpainting?v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Extender",toolTip:"Perform outpainting on images to expand it's content."}),v.jsx(co,{id:"extender",checked:t.showExtender,onCheckedChange:M=>{o({showExtender:M}),M&&o({showCropper:!1})}})]}),v.jsxs(Ut,{children:[v.jsxs(Uo,{defaultValue:t.extenderDirection,value:t.extenderDirection,onValueChange:M=>{u(M)},children:[v.jsx(go,{className:"w-[65px] h-7",disabled:!t.showExtender,children:v.jsx(Vo,{placeholder:"Select axis"})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:Object.values(Ln).map(M=>v.jsx(yo,{value:M,children:M},M))})})]}),v.jsxs("div",{className:"flex gap-1 justify-center mt-0",children:[v.jsx(_h,{text:"1.25x",onClick:()=>l(t.extenderDirection,1.25)}),v.jsx(_h,{text:"1.5x",onClick:()=>l(t.extenderDirection,1.5)}),v.jsx(_h,{text:"1.75x",onClick:()=>l(t.extenderDirection,1.75)}),v.jsx(_h,{text:"2.0x",onClick:()=>l(t.extenderDirection,2)})]})]})]}),v.jsx(gn,{})]}):null,D=()=>t.model.name!==dF?null:v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Task",toolTip:"PowerPaint task. When using extender, image-outpainting task will be auto used. For object-removal and image-outpainting, it is recommended to set the guidance_scale at 10 or above."}),v.jsxs(Uo,{defaultValue:t.powerpaintTask,value:t.powerpaintTask,onValueChange:M=>{o({powerpaintTask:M})},disabled:t.showExtender,children:[v.jsx(go,{className:"w-[140px]",children:v.jsx(Vo,{placeholder:"Select task"})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:[Ol.text_guided,Ol.object_remove,Ol.shape_guided].map(M=>v.jsx(yo,{value:M,children:M},M))})})]})]}),B=()=>v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{htmlFor:"steps",text:"Steps",toolTip:"The number of denoising steps. More denoising steps usually lead to a higher quality image at the expense of slower inference."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[30],min:1,max:100,step:1,value:[Math.floor(t.sdSteps)],onValueChange:M=>o({sdSteps:M[0]})}),v.jsx(Yn,{id:"steps",className:"w-[60px] rounded-full",numberValue:t.sdSteps,allowFloat:!1,onNumberValueChange:M=>{o({sdSteps:M})}})]})]}),V=()=>v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Guidance scale",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#guidance-scale",toolTip:"Guidance scale affects how aligned the text prompt and generated image are. Higher value means the prompt and generated image are closely aligned, so the output is a stricter interpretation of the prompt"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[750],min:0,max:1500,step:1,value:[Math.floor(t.sdGuidanceScale*100)],onValueChange:M=>o({sdGuidanceScale:M[0]/100})}),v.jsx(Yn,{id:"guidance-scale",className:"w-[60px] rounded-full",numberValue:t.sdGuidanceScale,allowFloat:!0,onNumberValueChange:M=>{o({sdGuidanceScale:M})}})]})]}),J=()=>t.model.name===fF?null:v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Sampler"}),v.jsxs(Uo,{defaultValue:t.sdSampler,value:t.sdSampler,onValueChange:M=>{o({sdSampler:M})},children:[v.jsx(go,{className:"w-[175px] text-xs",children:v.jsx(Vo,{placeholder:"Select sampler"})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:e.map(M=>v.jsx(yo,{value:M,className:"text-xs",children:M},M))})})]})]}),G=()=>v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Seed",toolTip:"Using same parameters and a fixed seed can generate same result image."}),v.jsxs("div",{className:"flex gap-2 justify-center items-center",children:[v.jsx(co,{id:"seed",checked:t.seedFixed,onCheckedChange:M=>{o({seedFixed:M})}}),v.jsx(Yn,{id:"seed",className:"w-[100px]",disabled:!t.seedFixed,numberValue:t.seed,allowFloat:!1,onNumberValueChange:M=>{o({seed:M})}})]})]}),se=()=>v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Mask blur",toolTip:"How much to blur the mask before processing, in pixels. Make the generated inpainting boundaries appear more natural."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[t.sdMaskBlur],min:0,max:96,step:1,value:[Math.floor(t.sdMaskBlur)],onValueChange:M=>o({sdMaskBlur:M[0]})}),v.jsx(Yn,{id:"mask-blur",className:"w-[60px] rounded-full",numberValue:t.sdMaskBlur,allowFloat:!1,onNumberValueChange:M=>{o({sdMaskBlur:M})}})]})]}),U=()=>v.jsxs(v.Fragment,{children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Match histograms",toolTip:"Match the inpainting result histogram to the source image histogram",url:"https://github.com/Sanster/lama-cleaner/pull/143#issuecomment-1325859307"}),v.jsx(co,{id:"match-histograms",checked:t.sdMatchHistograms,onCheckedChange:M=>{o({sdMatchHistograms:M})}})]}),v.jsx(gn,{})]}),ne=()=>v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{htmlFor:"adjustMaskKernelSize",text:"Adjust Mask",toolTip:"Expand or shrink mask. Using the slider to adjust the kernel size for dilation or erosion."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[12],min:1,max:100,step:1,value:[Math.floor(t.adjustMaskKernelSize)],onValueChange:M=>o({adjustMaskKernelSize:M[0]})}),v.jsx(Yn,{id:"adjustMaskKernelSize",className:"w-[60px] rounded-full",numberValue:t.adjustMaskKernelSize,allowFloat:!1,onNumberValueChange:M=>{o({adjustMaskKernelSize:M})}})]}),v.jsxs(Ut,{children:[v.jsxs("div",{className:"flex gap-1 justify-start",children:[v.jsx(wn,{variant:"outline",className:"p-1 h-8",onClick:()=>f("expand"),disabled:r,children:v.jsx("div",{className:"flex items-center gap-1 select-none",children:"Expand"})}),v.jsx(wn,{variant:"outline",className:"p-1 h-8",onClick:()=>f("shrink"),disabled:r,children:v.jsx("div",{className:"flex items-center gap-1 select-none",children:"Shrink"})}),v.jsx(wn,{variant:"outline",className:"p-1 h-8",onClick:()=>f("reverse"),disabled:r,children:v.jsx("div",{className:"flex items-center gap-1 select-none",children:"Reverse"})})]}),v.jsx(wn,{variant:"outline",className:"p-1 h-8 justify-self-end",onClick:p,disabled:r,children:v.jsx("div",{className:"flex items-center gap-1 select-none",children:"Clear"})})]})]}),v.jsx(gn,{})]});return v.jsxs("div",{className:"flex flex-col gap-4 mt-4",children:[S(),A(),ne(),D(),B(),V(),P(),O(),J(),G(),C(),v.jsx(gn,{}),E(),_(),se(),U(),b(),R()]})},$J=()=>{const[e,t]=xt(n=>[n.settings,n.updateSettings]);return v.jsxs("div",{className:"flex flex-col gap-4 mt-4",children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"CV2 Flag",url:"https://docs.opencv.org/4.8.0/d7/d8b/group__photo__inpaint.html#gga8002a65f5a3328fbf15df81b842d3c3ca892824c38e258feb5e72f308a358d52e"}),v.jsxs(Uo,{value:e.cv2Flag,onValueChange:n=>{t({cv2Flag:n})},children:[v.jsx(go,{className:"w-[160px]",children:v.jsx(Vo,{placeholder:"Select flag"})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:Object.values(Jw).map(n=>v.jsx(yo,{value:n,children:n},n))})})]})]}),v.jsx(Pt,{text:"CV2 Radius",url:"https://docs.opencv.org/4.8.0/d7/d8b/group__photo__inpaint.html#gga8002a65f5a3328fbf15df81b842d3c3ca892824c38e258feb5e72f308a358d52e"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[5],min:1,max:100,step:1,value:[Math.floor(e.cv2Radius)],onValueChange:n=>t({cv2Radius:n[0]})}),v.jsx(Yn,{id:"cv2-radius",className:"w-[60px] rounded-full",numberValue:e.cv2Radius,allowFloat:!1,onNumberValueChange:n=>{t({cv2Radius:n})}})]})]})},RJ=()=>{const[e,t]=xt(i=>[i.settings,i.windowSize]),[n,r]=Nx(!0);if(Zn("c",()=>{r()}),e.model.name!==lC&&e.model.name!==cC&&e.model.model_type===fs)return null;const o=()=>e.model.name===lC?v.jsx(EJ,{}):e.model.name===cC?v.jsx($J,{}):v.jsx(CJ,{});return v.jsxs(yJ,{open:n,modal:!1,children:[v.jsx(wJ,{tabIndex:-1,className:"z-10 outline-none absolute top-[68px] right-6 rounded-lg border bg-background",hidden:n,children:v.jsx(wn,{variant:"ghost",size:"icon",asChild:!0,className:"p-1.5",onClick:r,children:v.jsx(GU,{strokeWidth:1})})}),v.jsxs(wA,{side:"right",className:"w-[300px] mt-[60px] outline-none pl-4 pr-1",onOpenAutoFocus:i=>i.preventDefault(),onPointerDownOutside:i=>i.preventDefault(),children:[v.jsxs(xA,{children:[v.jsxs(Ut,{children:[v.jsx("div",{className:"overflow-hidden mr-8",children:e.model.name.split("/")[e.model.name.split("/").length-1]}),v.jsx(wn,{variant:"ghost",size:"icon",className:"border h-6 w-6",onClick:r,children:v.jsx(YU,{strokeWidth:1})})]}),v.jsx(gn,{})]}),v.jsx(lg,{style:{height:t.height-160},className:"pr-3",children:o()})]})]})},Jo=Object.create(null);Jo.open="0";Jo.close="1";Jo.ping="2";Jo.pong="3";Jo.message="4";Jo.upgrade="5";Jo.noop="6";const op=Object.create(null);Object.keys(Jo).forEach(e=>{op[Jo[e]]=e});const G1={type:"error",data:"parser error"},bA=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",SA=typeof ArrayBuffer=="function",_A=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,ab=({type:e,data:t},n,r)=>bA&&t instanceof Blob?n?r(t):q2(t,r):SA&&(t instanceof ArrayBuffer||_A(t))?n?r(t):q2(new Blob([t]),r):r(Jo[e]+(t||"")),q2=(e,t)=>{const n=new FileReader;return n.onload=function(){const r=n.result.split(",")[1];t("b"+(r||""))},n.readAsDataURL(e)};function Q2(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let B0;function kJ(e,t){if(bA&&e.data instanceof Blob)return e.data.arrayBuffer().then(Q2).then(t);if(SA&&(e.data instanceof ArrayBuffer||_A(e.data)))return t(Q2(e.data));ab(e,!1,n=>{B0||(B0=new TextEncoder),t(B0.encode(n))})}const J2="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",_u=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let e=0;e{let t=e.length*.75,n=e.length,r,o=0,i,s,l,u;e[e.length-1]==="="&&(t--,e[e.length-2]==="="&&t--);const f=new ArrayBuffer(t),p=new Uint8Array(f);for(r=0;r>4,p[o++]=(s&15)<<4|l>>2,p[o++]=(l&3)<<6|u&63;return f},PJ=typeof ArrayBuffer=="function",lb=(e,t)=>{if(typeof e!="string")return{type:"message",data:EA(e,t)};const n=e.charAt(0);return n==="b"?{type:"message",data:AJ(e.substring(1),t)}:op[n]?e.length>1?{type:op[n],data:e.substring(1)}:{type:op[n]}:G1},AJ=(e,t)=>{if(PJ){const n=TJ(e);return EA(n,t)}else return{base64:!0,data:e}},EA=(e,t)=>{switch(t){case"blob":return e instanceof Blob?e:new Blob([e]);case"arraybuffer":default:return e instanceof ArrayBuffer?e:e.buffer}},CA="",MJ=(e,t)=>{const n=e.length,r=new Array(n);let o=0;e.forEach((i,s)=>{ab(i,!1,l=>{r[s]=l,++o===n&&t(r.join(CA))})})},OJ=(e,t)=>{const n=e.split(CA),r=[];for(let o=0;o{const r=n.length;let o;if(r<126)o=new Uint8Array(1),new DataView(o.buffer).setUint8(0,r);else if(r<65536){o=new Uint8Array(3);const i=new DataView(o.buffer);i.setUint8(0,126),i.setUint16(1,r)}else{o=new Uint8Array(9);const i=new DataView(o.buffer);i.setUint8(0,127),i.setBigUint64(1,BigInt(r))}e.data&&typeof e.data!="string"&&(o[0]|=128),t.enqueue(o),t.enqueue(n)})}})}let U0;function Eh(e){return e.reduce((t,n)=>t+n.length,0)}function Ch(e,t){if(e[0].length===t)return e.shift();const n=new Uint8Array(t);let r=0;for(let o=0;oMath.pow(2,21)-1){l.enqueue(G1);break}o=p*Math.pow(2,32)+f.getUint32(4),r=3}else{if(Eh(n)e){l.enqueue(G1);break}}}})}const $A=4;function qt(e){if(e)return IJ(e)}function IJ(e){for(var t in qt.prototype)e[t]=qt.prototype[t];return e}qt.prototype.on=qt.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this};qt.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this};qt.prototype.off=qt.prototype.removeListener=qt.prototype.removeAllListeners=qt.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,o=0;o(e.hasOwnProperty(r)&&(n[r]=e[r]),n),{})}const LJ=Br.setTimeout,FJ=Br.clearTimeout;function yg(e,t){t.useNativeTimers?(e.setTimeoutFn=LJ.bind(Br),e.clearTimeoutFn=FJ.bind(Br)):(e.setTimeoutFn=Br.setTimeout.bind(Br),e.clearTimeoutFn=Br.clearTimeout.bind(Br))}const jJ=1.33;function zJ(e){return typeof e=="string"?BJ(e):Math.ceil((e.byteLength||e.size)*jJ)}function BJ(e){let t=0,n=0;for(let r=0,o=e.length;r=57344?n+=3:(r++,n+=4);return n}function UJ(e){let t="";for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+="&"),t+=encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t}function VJ(e){let t={},n=e.split("&");for(let r=0,o=n.length;r0);return t}function TA(){const e=n$(+new Date);return e!==t$?(e$=0,t$=e):e+"."+n$(e$++)}for(;$h{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)};OJ(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,MJ(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]=TA()),!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 Xo(this.uri(),t)}doWrite(t,n){const r=this.request({method:"POST",data:t});r.on("success",n),r.on("error",(o,i)=>{this.onError("xhr post error",o,i)})}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}}class Xo extends qt{constructor(t,n){super(),yg(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=RA(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");n.xdomain=!!this.opts.xd;const r=this.xhr=new AA(n);try{r.open(this.method,this.uri,!0);try{if(this.opts.extraHeaders){r.setDisableHeaderCheck&&r.setDisableHeaderCheck(!0);for(let o in this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(o)&&r.setRequestHeader(o,this.opts.extraHeaders[o])}}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 o;r.readyState===3&&((o=this.opts.cookieJar)===null||o===void 0||o.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(o){this.setTimeoutFn(()=>{this.onError(o)},0);return}typeof document<"u"&&(this.index=Xo.requestsCount++,Xo.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=GJ,t)try{this.xhr.abort()}catch{}typeof document<"u"&&delete Xo.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()}}Xo.requestsCount=0;Xo.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",r$);else if(typeof addEventListener=="function"){const e="onpagehide"in Br?"pagehide":"unload";addEventListener(e,r$,!1)}}function r$(){for(let e in Xo.requests)Xo.requests.hasOwnProperty(e)&&Xo.requests[e].abort()}const ub=typeof Promise=="function"&&typeof Promise.resolve=="function"?t=>Promise.resolve().then(t):(t,n)=>n(t,0),Rh=Br.WebSocket||Br.MozWebSocket,o$=!0,ZJ="arraybuffer",i$=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class qJ extends cb{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=i$?{}:RA(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=o$&&!i$?n?new Rh(t,n):new Rh(t):new Rh(t,n,r)}catch(o){return this.emitReserved("error",o)}this.ws.binaryType=this.socket.binaryType,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{o$&&this.ws.send(i)}catch{}o&&ub(()=>{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]=TA()),this.supportsBinary||(n.b64=1),this.createUri(t,n)}check(){return!!Rh}}class QJ extends cb{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=DJ(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=t.readable.pipeThrough(n).getReader(),o=NJ();o.readable.pipeTo(t.writable),this.writer=o.writable.getWriter();const i=()=>{r.read().then(({done:l,value:u})=>{l||(this.onPacket(u),i())}).catch(l=>{})};i();const s={type:"open"};this.query.sid&&(s.data=`{"sid":"${this.query.sid}"}`),this.writer.write(s).then(()=>this.onOpen())})}))}write(t){this.writable=!1;for(let n=0;n{o&&ub(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;(t=this.transport)===null||t===void 0||t.close()}}const JJ={websocket:qJ,webtransport:QJ,polling:XJ},eee=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,tee=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function X1(e){if(e.length>2e3)throw"URI too long";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 o=eee.exec(e||""),i={},s=14;for(;s--;)i[tee[s]]=o[s]||"";return n!=-1&&r!=-1&&(i.source=t,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=nee(i,i.path),i.queryKey=ree(i,i.query),i}function nee(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 ree(e,t){const n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(r,o,i){o&&(n[o]=i)}),n}let MA=class hl extends qt{constructor(t,n={}){super(),this.binaryType=ZJ,this.writeBuffer=[],t&&typeof t=="object"&&(n=t,t=null),t?(t=X1(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=X1(n.host).host),yg(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=VJ(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=$A,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 JJ[t](r)}open(){let t;if(this.opts.rememberUpgrade&&hl.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;hl.priorWebsocketSuccess=!1;const o=()=>{r||(n.send([{type:"ping",data:"probe"}]),n.once("packet",m=>{if(!r)if(m.type==="pong"&&m.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",n),!n)return;hl.priorWebsocketSuccess=n.name==="websocket",this.transport.pause(()=>{r||this.readyState!=="closed"&&(p(),this.setTransport(n),n.send([{type:"upgrade"}]),this.emitReserved("upgrade",n),n=null,this.upgrading=!1,this.flush())})}else{const g=new Error("probe error");g.transport=n.name,this.emitReserved("upgradeError",g)}}))};function i(){r||(r=!0,p(),n.close(),n=null)}const s=m=>{const g=new Error("probe error: "+m);g.transport=n.name,i(),this.emitReserved("upgradeError",g)};function l(){s("transport closed")}function u(){s("socket closed")}function f(m){n&&m.name!==n.name&&i()}const p=()=>{n.removeListener("open",o),n.removeListener("error",s),n.removeListener("close",l),this.off("close",u),this.off("upgrading",f)};n.once("open",o),n.once("error",s),n.once("close",l),this.once("close",u),this.once("upgrading",f),this.upgrades.indexOf("webtransport")!==-1&&t!=="webtransport"?this.setTimeoutFn(()=>{r||n.open()},200):n.open()}onOpen(){if(this.readyState="open",hl.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,o){if(typeof n=="function"&&(o=n,n=void 0),typeof r=="function"&&(o=r,r=null),this.readyState==="closing"||this.readyState==="closed")return;r=r||{},r.compress=r.compress!==!1;const i={type:t,data:n,options:r};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),o&&this.once("flush",o),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){hl.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 o=t.length;for(;rtypeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,OA=Object.prototype.toString,aee=typeof Blob=="function"||typeof Blob<"u"&&OA.call(Blob)==="[object BlobConstructor]",lee=typeof File=="function"||typeof File<"u"&&OA.call(File)==="[object FileConstructor]";function db(e){return iee&&(e instanceof ArrayBuffer||see(e))||aee&&e instanceof Blob||lee&&e instanceof File}function ip(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(i),n.apply(this,[null,...s])}}emitWithAck(t,...n){const r=this.flags.timeout!==void 0||this._opts.ackTimeout!==void 0;return new Promise((o,i)=>{n.push((s,l)=>r?s?i(s):o(l):o(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((o,...i)=>r!==this._queue[0]?void 0:(o!==null?r.tryCount>this._opts.retries&&(this._queue.shift(),n&&n(o)):(this._queue.shift(),n&&n(null,...i)),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:lt.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 lt.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 lt.EVENT:case lt.BINARY_EVENT:this.onevent(t);break;case lt.ACK:case lt.BINARY_ACK:this.onack(t);break;case lt.DISCONNECT:this.ondisconnect();break;case lt.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(...o){r||(r=!0,n.packet({type:lt.ACK,id:t,data:o}))}}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:lt.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}Ac.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};Ac.prototype.reset=function(){this.attempts=0};Ac.prototype.setMin=function(e){this.ms=e};Ac.prototype.setMax=function(e){this.max=e};Ac.prototype.setJitter=function(e){this.jitter=e};class Q1 extends qt{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,yg(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 Ac({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(n.timeout==null?2e4:n.timeout),this._readyState="closed",this.uri=t;const o=n.parser||mee;this.encoder=new o.Encoder,this.decoder=new o.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 MA(this.uri,this.opts);const n=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;const o=fo(n,"open",function(){r.onopen(),t&&t()}),i=l=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",l),t?t(l):this.maybeReconnectOnOpen()},s=fo(n,"error",i);if(this._timeout!==!1){const l=this._timeout,u=this.setTimeoutFn(()=>{o(),i(new Error("timeout")),n.close()},l);this.opts.autoUnref&&u.unref(),this.subs.push(()=>{this.clearTimeoutFn(u)})}return this.subs.push(o),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(fo(t,"ping",this.onping.bind(this)),fo(t,"data",this.ondata.bind(this)),fo(t,"error",this.onerror.bind(this)),fo(t,"close",this.onclose.bind(this)),fo(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){ub(()=>{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 NA(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(o=>{o?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",o)):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 gu={};function sp(e,t){typeof e=="object"&&(t=e,e=void 0),t=t||{};const n=oee(e,t.path||"/socket.io"),r=n.source,o=n.id,i=n.path,s=gu[o]&&i in gu[o].nsps,l=t.forceNew||t["force new connection"]||t.multiplex===!1||s;let u;return l?u=new Q1(r,t):(gu[o]||(gu[o]=new Q1(r,t)),u=gu[o]),n.query&&!t.query&&(t.query=n.queryKey),u.socket(n.path,t)}Object.assign(sp,{Manager:Q1,Socket:NA,io:sp,connect:sp});const DA="Progress",wg=100,[vee,kte]=Mn(DA),[yee,wee]=vee(DA),IA=d.forwardRef((e,t)=>{const{__scopeProgress:n,value:r,max:o,getValueLabel:i=See,...s}=e,l=J1(o)?o:wg,u=FA(r,l)?r:null,f=lm(u)?i(u,l):void 0;return d.createElement(yee,{scope:n,value:u,max:l},d.createElement(Ae.div,Y({"aria-valuemax":l,"aria-valuemin":0,"aria-valuenow":lm(u)?u:void 0,"aria-valuetext":f,role:"progressbar","data-state":LA(u,l),"data-value":u??void 0,"data-max":l},s,{ref:t})))});IA.propTypes={max(e,t,n){const r=e[t],o=String(r);return r&&!J1(r)?new Error(_ee(o,n)):null},value(e,t,n){const r=e[t],o=String(r),i=J1(e.max)?e.max:wg;return r!=null&&!FA(r,i)?new Error(Eee(o,n)):null}};const xee="ProgressIndicator",bee=d.forwardRef((e,t)=>{var n;const{__scopeProgress:r,...o}=e,i=wee(xee,r);return d.createElement(Ae.div,Y({"data-state":LA(i.value,i.max),"data-value":(n=i.value)!==null&&n!==void 0?n:void 0,"data-max":i.max},o,{ref:t}))});function See(e,t){return`${Math.round(e/t*100)}%`}function LA(e,t){return e==null?"indeterminate":e===t?"complete":"loading"}function lm(e){return typeof e=="number"}function J1(e){return lm(e)&&!isNaN(e)&&e>0}function FA(e,t){return lm(e)&&!isNaN(e)&&e<=t&&e>=0}function _ee(e,t){return`Invalid prop \`max\` of value \`${e}\` supplied to \`${t}\`. Only numbers greater than 0 are valid max values. Defaulting to \`${wg}\`.`}function Eee(e,t){return`Invalid prop \`value\` of value \`${e}\` supplied to \`${t}\`. The \`value\` prop must be: + - a positive number + - less than the value passed to \`max\` (or ${wg} if no \`max\` prop is set) + - \`null\` if the progress is indeterminate. + +Defaulting to \`null\`.`}const jA=IA,Cee=bee,zA=d.forwardRef(({className:e,value:t,...n},r)=>v.jsx(jA,{ref:r,className:_e("relative h-2 w-full overflow-hidden rounded-full bg-primary/20",e),...n,children:v.jsx(Cee,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(t||0)}%)`}})}));zA.displayName=jA.displayName;const $ee="",Zi=sp($ee),Ree=()=>{const[e,t,n]=xt(u=>[u.settings,u.isInpainting,u.isSD()]),[r,o]=d.useState(!1),[i,s]=d.useState(0),l=Math.min(Math.round(i/e.sdSteps*100),100);return d.useEffect(()=>(Zi.on("connect",()=>{o(!0)}),Zi.on("disconnect",()=>{o(!1)}),Zi.on("diffusion_progress",u=>{u&&s(u.step+1)}),Zi.on("diffusion_finish",()=>{s(0)}),()=>{Zi.off("connect"),Zi.off("disconnect"),Zi.off("diffusion_progress"),Zi.off("diffusion_finish")}),[]),v.jsxs("div",{className:"z-10 fixed bg-background w-[220px] left-1/2 -translate-x-1/2 top-[68px] h-[32px] flex justify-center items-center gap-[18px] border-[1px] border-[solid] rounded-[14px] pl-[8px] pr-[8px]",style:{visibility:r&&t&&n?"visible":"hidden"},children:[v.jsx(zA,{value:l}),v.jsxs("div",{className:"w-[45px] flex justify-center font-nums",children:[l,"%"]})]})},kee=()=>{const[e,t]=xt(n=>[n.file,n.updateSettings]);return d.useEffect(()=>{(async()=>{const r=await Uj();t({model:r})})()},[]),v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"flex gap-3 absolute top-[68px] left-[24px] items-center",children:[v.jsx(vJ,{}),v.jsx(qq,{})]}),v.jsx(Wq,{}),v.jsx(Ree,{}),v.jsx(RJ,{}),e?v.jsx(Zq,{file:e}):v.jsx(v.Fragment,{})]})},Tee=()=>{const[e,t]=d.useState(window.innerWidth),n=d.useCallback(()=>{t(window.innerWidth)},[]);if(d.useEffect(()=>(window.addEventListener("resize",n),()=>{window.removeEventListener("resize",n)})),e<768)return"mobile";if(e>=768&&e<1224)return"tablet";if(e>=1224)return"desktop"};function Pee(e){const{onSelection:t}=e,[n]=d.useState(`file-upload-${Math.random().toString()}`),r=Tee();function o(i){if(!(!i||!i.type.match("image.*")))try{if(i.size>20*1024*1024)throw new Error("file too large");t(i)}catch(l){alert(`error: ${l.message}`)}}return v.jsx("div",{className:"absolute flex w-screen h-screen justify-center items-center pointer-events-none",children:v.jsx("label",{htmlFor:n,className:"grid bg-background border-[2px] border-[dashed] rounded-lg min-w-[600px] hover:bg-primary hover:text-primary-foreground pointer-events-auto",children:v.jsxs("div",{className:"grid p-16 w-full h-full",onDragOver:i=>{i.stopPropagation(),i.preventDefault()},children:[v.jsx("input",{className:"hidden",id:n,name:n,type:"file",onChange:i=>{var l;const s=(l=i.currentTarget.files)==null?void 0:l[0];s&&o(s)},accept:"image/png, image/jpeg"}),v.jsx("p",{className:"text-center",children:r==="desktop"?"Click here or drag an image file":"Tap here to load your picture"})]})})})}const BA="ToastProvider",[hb,Aee,Mee]=Kd("Toast"),[UA,Tte]=Mn("Toast",[Mee]),[Oee,xg]=UA(BA),VA=e=>{const{__scopeToast:t,label:n="Notification",duration:r=5e3,swipeDirection:o="right",swipeThreshold:i=50,children:s}=e,[l,u]=d.useState(null),[f,p]=d.useState(0),m=d.useRef(!1),g=d.useRef(!1);return d.createElement(hb.Provider,{scope:t},d.createElement(Oee,{scope:t,label:n,duration:r,swipeDirection:o,swipeThreshold:i,toastCount:f,viewport:l,onViewportChange:u,onToastAdd:d.useCallback(()=>p(y=>y+1),[]),onToastRemove:d.useCallback(()=>p(y=>y-1),[]),isFocusedToastEscapeKeyDownRef:m,isClosePausedRef:g},s))};VA.propTypes={label(e){if(e.label&&typeof e.label=="string"&&!e.label.trim()){const t=`Invalid prop \`label\` supplied to \`${BA}\`. Expected non-empty \`string\`.`;return new Error(t)}return null}};const Nee="ToastViewport",Dee=["F8"],ew="toast.viewportPause",tw="toast.viewportResume",Iee=d.forwardRef((e,t)=>{const{__scopeToast:n,hotkey:r=Dee,label:o="Notifications ({hotkey})",...i}=e,s=xg(Nee,n),l=Aee(n),u=d.useRef(null),f=d.useRef(null),p=d.useRef(null),m=d.useRef(null),g=Ue(t,m,s.onViewportChange),y=r.join("+").replace(/Key/g,"").replace(/Digit/g,""),x=s.toastCount>0;d.useEffect(()=>{const E=_=>{var b;r.every(R=>_[R]||_.code===R)&&((b=m.current)===null||b===void 0||b.focus())};return document.addEventListener("keydown",E),()=>document.removeEventListener("keydown",E)},[r]),d.useEffect(()=>{const E=u.current,_=m.current;if(x&&E&&_){const b=()=>{if(!s.isClosePausedRef.current){const O=new CustomEvent(ew);_.dispatchEvent(O),s.isClosePausedRef.current=!0}},C=()=>{if(s.isClosePausedRef.current){const O=new CustomEvent(tw);_.dispatchEvent(O),s.isClosePausedRef.current=!1}},R=O=>{!E.contains(O.relatedTarget)&&C()},P=()=>{E.contains(document.activeElement)||C()};return E.addEventListener("focusin",b),E.addEventListener("focusout",R),E.addEventListener("pointermove",b),E.addEventListener("pointerleave",P),window.addEventListener("blur",b),window.addEventListener("focus",C),()=>{E.removeEventListener("focusin",b),E.removeEventListener("focusout",R),E.removeEventListener("pointermove",b),E.removeEventListener("pointerleave",P),window.removeEventListener("blur",b),window.removeEventListener("focus",C)}}},[x,s.isClosePausedRef]);const S=d.useCallback(({tabbingDirection:E})=>{const b=l().map(C=>{const R=C.ref.current,P=[R,...Qee(R)];return E==="forwards"?P:P.reverse()});return(E==="forwards"?b.reverse():b).flat()},[l]);return d.useEffect(()=>{const E=m.current;if(E){const _=b=>{const C=b.altKey||b.ctrlKey||b.metaKey;if(b.key==="Tab"&&!C){const D=document.activeElement,B=b.shiftKey;if(b.target===E&&B){var P;(P=f.current)===null||P===void 0||P.focus();return}const G=S({tabbingDirection:B?"backwards":"forwards"}),se=G.findIndex(U=>U===D);if(V0(G.slice(se+1)))b.preventDefault();else{var O,A;B?(O=f.current)===null||O===void 0||O.focus():(A=p.current)===null||A===void 0||A.focus()}}};return E.addEventListener("keydown",_),()=>E.removeEventListener("keydown",_)}},[l,S]),d.createElement(EB,{ref:u,role:"region","aria-label":o.replace("{hotkey}",y),tabIndex:-1,style:{pointerEvents:x?void 0:"none"}},x&&d.createElement(a$,{ref:f,onFocusFromOutsideViewport:()=>{const E=S({tabbingDirection:"forwards"});V0(E)}}),d.createElement(hb.Slot,{scope:n},d.createElement(Ae.ol,Y({tabIndex:-1},i,{ref:g}))),x&&d.createElement(a$,{ref:p,onFocusFromOutsideViewport:()=>{const E=S({tabbingDirection:"backwards"});V0(E)}}))}),Lee="ToastFocusProxy",a$=d.forwardRef((e,t)=>{const{__scopeToast:n,onFocusFromOutsideViewport:r,...o}=e,i=xg(Lee,n);return d.createElement(Km,Y({"aria-hidden":!0,tabIndex:0},o,{ref:t,style:{position:"fixed"},onFocus:s=>{var l;const u=s.relatedTarget;!((l=i.viewport)!==null&&l!==void 0&&l.contains(u))&&r()}}))}),bg="Toast",Fee="toast.swipeStart",jee="toast.swipeMove",zee="toast.swipeCancel",Bee="toast.swipeEnd",Uee=d.forwardRef((e,t)=>{const{forceMount:n,open:r,defaultOpen:o,onOpenChange:i,...s}=e,[l=!0,u]=Zr({prop:r,defaultProp:o,onChange:i});return d.createElement(Sn,{present:n||l},d.createElement(WA,Y({open:l},s,{ref:t,onClose:()=>u(!1),onPause:Ft(e.onPause),onResume:Ft(e.onResume),onSwipeStart:ue(e.onSwipeStart,f=>{f.currentTarget.setAttribute("data-swipe","start")}),onSwipeMove:ue(e.onSwipeMove,f=>{const{x:p,y:m}=f.detail.delta;f.currentTarget.setAttribute("data-swipe","move"),f.currentTarget.style.setProperty("--radix-toast-swipe-move-x",`${p}px`),f.currentTarget.style.setProperty("--radix-toast-swipe-move-y",`${m}px`)}),onSwipeCancel:ue(e.onSwipeCancel,f=>{f.currentTarget.setAttribute("data-swipe","cancel"),f.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),f.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),f.currentTarget.style.removeProperty("--radix-toast-swipe-end-x"),f.currentTarget.style.removeProperty("--radix-toast-swipe-end-y")}),onSwipeEnd:ue(e.onSwipeEnd,f=>{const{x:p,y:m}=f.detail.delta;f.currentTarget.setAttribute("data-swipe","end"),f.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),f.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),f.currentTarget.style.setProperty("--radix-toast-swipe-end-x",`${p}px`),f.currentTarget.style.setProperty("--radix-toast-swipe-end-y",`${m}px`),u(!1)})})))}),[Vee,Wee]=UA(bg,{onClose(){}}),WA=d.forwardRef((e,t)=>{const{__scopeToast:n,type:r="foreground",duration:o,open:i,onClose:s,onEscapeKeyDown:l,onPause:u,onResume:f,onSwipeStart:p,onSwipeMove:m,onSwipeCancel:g,onSwipeEnd:y,...x}=e,S=xg(bg,n),[E,_]=d.useState(null),b=Ue(t,U=>_(U)),C=d.useRef(null),R=d.useRef(null),P=o||S.duration,O=d.useRef(0),A=d.useRef(P),D=d.useRef(0),{onToastAdd:B,onToastRemove:V}=S,J=Ft(()=>{var U;(E==null?void 0:E.contains(document.activeElement))&&((U=S.viewport)===null||U===void 0||U.focus()),s()}),G=d.useCallback(U=>{!U||U===1/0||(window.clearTimeout(D.current),O.current=new Date().getTime(),D.current=window.setTimeout(J,U))},[J]);d.useEffect(()=>{const U=S.viewport;if(U){const ne=()=>{G(A.current),f==null||f()},M=()=>{const ee=new Date().getTime()-O.current;A.current=A.current-ee,window.clearTimeout(D.current),u==null||u()};return U.addEventListener(ew,M),U.addEventListener(tw,ne),()=>{U.removeEventListener(ew,M),U.removeEventListener(tw,ne)}}},[S.viewport,P,u,f,G]),d.useEffect(()=>{i&&!S.isClosePausedRef.current&&G(P)},[i,P,S.isClosePausedRef,G]),d.useEffect(()=>(B(),()=>V()),[B,V]);const se=d.useMemo(()=>E?YA(E):null,[E]);return S.viewport?d.createElement(d.Fragment,null,se&&d.createElement(Hee,{__scopeToast:n,role:"status","aria-live":r==="foreground"?"assertive":"polite","aria-atomic":!0},se),d.createElement(Vee,{scope:n,onClose:J},Is.createPortal(d.createElement(hb.ItemSlot,{scope:n},d.createElement(_B,{asChild:!0,onEscapeKeyDown:ue(l,()=>{S.isFocusedToastEscapeKeyDownRef.current||J(),S.isFocusedToastEscapeKeyDownRef.current=!1})},d.createElement(Ae.li,Y({role:"status","aria-live":"off","aria-atomic":!0,tabIndex:0,"data-state":i?"open":"closed","data-swipe-direction":S.swipeDirection},x,{ref:b,style:{userSelect:"none",touchAction:"none",...e.style},onKeyDown:ue(e.onKeyDown,U=>{U.key==="Escape"&&(l==null||l(U.nativeEvent),U.nativeEvent.defaultPrevented||(S.isFocusedToastEscapeKeyDownRef.current=!0,J()))}),onPointerDown:ue(e.onPointerDown,U=>{U.button===0&&(C.current={x:U.clientX,y:U.clientY})}),onPointerMove:ue(e.onPointerMove,U=>{if(!C.current)return;const ne=U.clientX-C.current.x,M=U.clientY-C.current.y,ee=!!R.current,H=["left","right"].includes(S.swipeDirection),X=["left","up"].includes(S.swipeDirection)?Math.min:Math.max,W=H?X(0,ne):0,le=H?0:X(0,M),pe=U.pointerType==="touch"?10:2,$e={x:W,y:le},Ve={originalEvent:U,delta:$e};ee?(R.current=$e,kh(jee,m,Ve,{discrete:!1})):l$($e,S.swipeDirection,pe)?(R.current=$e,kh(Fee,p,Ve,{discrete:!1}),U.target.setPointerCapture(U.pointerId)):(Math.abs(ne)>pe||Math.abs(M)>pe)&&(C.current=null)}),onPointerUp:ue(e.onPointerUp,U=>{const ne=R.current,M=U.target;if(M.hasPointerCapture(U.pointerId)&&M.releasePointerCapture(U.pointerId),R.current=null,C.current=null,ne){const ee=U.currentTarget,H={originalEvent:U,delta:ne};l$(ne,S.swipeDirection,S.swipeThreshold)?kh(Bee,y,H,{discrete:!0}):kh(zee,g,H,{discrete:!0}),ee.addEventListener("click",X=>X.preventDefault(),{once:!0})}})})))),S.viewport))):null});WA.propTypes={type(e){if(e.type&&!["foreground","background"].includes(e.type)){const t=`Invalid prop \`type\` supplied to \`${bg}\`. Expected \`foreground | background\`.`;return new Error(t)}return null}};const Hee=e=>{const{__scopeToast:t,children:n,...r}=e,o=xg(bg,t),[i,s]=d.useState(!1),[l,u]=d.useState(!1);return Zee(()=>s(!0)),d.useEffect(()=>{const f=window.setTimeout(()=>u(!0),1e3);return()=>window.clearTimeout(f)},[]),l?null:d.createElement(jd,{asChild:!0},d.createElement(Km,r,i&&d.createElement(d.Fragment,null,o.label," ",n)))},Kee=d.forwardRef((e,t)=>{const{__scopeToast:n,...r}=e;return d.createElement(Ae.div,Y({},r,{ref:t}))}),Gee=d.forwardRef((e,t)=>{const{__scopeToast:n,...r}=e;return d.createElement(Ae.div,Y({},r,{ref:t}))}),Yee="ToastAction",HA=d.forwardRef((e,t)=>{const{altText:n,...r}=e;return n?d.createElement(GA,{altText:n,asChild:!0},d.createElement(KA,Y({},r,{ref:t}))):null});HA.propTypes={altText(e){return e.altText?null:new Error(`Missing prop \`altText\` expected on \`${Yee}\``)}};const Xee="ToastClose",KA=d.forwardRef((e,t)=>{const{__scopeToast:n,...r}=e,o=Wee(Xee,n);return d.createElement(GA,{asChild:!0},d.createElement(Ae.button,Y({type:"button"},r,{ref:t,onClick:ue(e.onClick,o.onClose)})))}),GA=d.forwardRef((e,t)=>{const{__scopeToast:n,altText:r,...o}=e;return d.createElement(Ae.div,Y({"data-radix-toast-announce-exclude":"","data-radix-toast-announce-alt":r||void 0},o,{ref:t}))});function YA(e){const t=[];return Array.from(e.childNodes).forEach(r=>{if(r.nodeType===r.TEXT_NODE&&r.textContent&&t.push(r.textContent),qee(r)){const o=r.ariaHidden||r.hidden||r.style.display==="none",i=r.dataset.radixToastAnnounceExclude==="";if(!o)if(i){const s=r.dataset.radixToastAnnounceAlt;s&&t.push(s)}else t.push(...YA(r))}}),t}function kh(e,t,n,{discrete:r}){const o=n.originalEvent.currentTarget,i=new CustomEvent(e,{bubbles:!0,cancelable:!0,detail:n});t&&o.addEventListener(e,t,{once:!0}),r?dx(o,i):o.dispatchEvent(i)}const l$=(e,t,n=0)=>{const r=Math.abs(e.x),o=Math.abs(e.y),i=r>o;return t==="left"||t==="right"?i&&r>n:!i&&o>n};function Zee(e=()=>{}){const t=Ft(e);An(()=>{let n=0,r=0;return n=window.requestAnimationFrame(()=>r=window.requestAnimationFrame(t)),()=>{window.cancelAnimationFrame(n),window.cancelAnimationFrame(r)}},[t])}function qee(e){return e.nodeType===e.ELEMENT_NODE}function Qee(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const o=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||o?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function V0(e){const t=document.activeElement;return e.some(n=>n===t?!0:(n.focus(),document.activeElement!==t))}const Jee=VA,XA=Iee,ZA=Uee,qA=Kee,QA=Gee,JA=HA,e6=KA,ete=Jee,t6=d.forwardRef(({className:e,...t},n)=>v.jsx(XA,{ref:n,className:_e("fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]",e),tabIndex:-1,...t}));t6.displayName=XA.displayName;const tte=Dm("group pointer-events-auto relative flex w-full items-center justify-between space-x-2 overflow-hidden rounded-md border p-4 pr-6 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full",{variants:{variant:{default:"border bg-background text-foreground",destructive:"destructive group border-destructive bg-destructive text-destructive-foreground"}},defaultVariants:{variant:"default"}}),n6=d.forwardRef(({className:e,variant:t,...n},r)=>v.jsx(ZA,{ref:r,className:_e(tte({variant:t}),e),tabIndex:-1,...n}));n6.displayName=ZA.displayName;const nte=d.forwardRef(({className:e,...t},n)=>v.jsx(JA,{ref:n,className:_e("inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium transition-colors hover:bg-secondary focus:outline-none focus:ring-1 focus:ring-ring disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive",e),tabIndex:-1,...t}));nte.displayName=JA.displayName;const r6=d.forwardRef(({className:e,...t},n)=>v.jsx(e6,{ref:n,className:_e("absolute right-1 top-1 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-1 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600",e),"toast-close":"",tabIndex:-1,...t,children:v.jsx(bk,{className:"h-4 w-4"})}));r6.displayName=e6.displayName;const o6=d.forwardRef(({className:e,...t},n)=>v.jsx(qA,{ref:n,className:_e("text-sm font-semibold [&+div]:text-xs",e),tabIndex:-1,...t}));o6.displayName=qA.displayName;const i6=d.forwardRef(({className:e,...t},n)=>v.jsx(QA,{ref:n,className:_e("text-sm opacity-90",e),...t,tabIndex:-1}));i6.displayName=QA.displayName;function rte(){const{toasts:e}=Id();return v.jsxs(ete,{children:[e.map(function({id:t,title:n,description:r,action:o,...i}){return v.jsxs(n6,{...i,children:[v.jsxs("div",{className:"grid gap-1",children:[n&&v.jsx(o6,{children:n}),r&&v.jsx(i6,{children:r})]}),o,v.jsx(r6,{})]},t)}),v.jsx(t6,{})]})}const ote=["image/jpeg","image/png","image/webp","image/bmp","image/tiff"];function ite(){const[e,t,n,r]=xt(g=>[g.file,g.updateAppState,g.setServerConfig,g.setFile]),o=Yj(),i=vH();d.useEffect(()=>{o&&r(o)},[o,r]),d.useEffect(()=>{t({windowSize:i})},[i]),d.useEffect(()=>{(async()=>{const y=await yk();n(y),y.isDesktop&&pF()})()},[]);const s=d.useRef(0),l=d.useCallback(g=>{g.preventDefault(),g.stopPropagation()},[]),u=d.useCallback(g=>{g.preventDefault(),g.stopPropagation(),s.current+=1},[]),f=d.useCallback(g=>{g.preventDefault(),g.stopPropagation(),s.current-=1,s.current>0},[]),p=d.useCallback(g=>{if(g.preventDefault(),g.stopPropagation(),g.dataTransfer.files&&g.dataTransfer.files.length>0){if(!(g.dataTransfer.files.length>1)){const y=g.dataTransfer.files[0],x=y.type;ote.includes(x)&&r(y)}g.dataTransfer.clearData()}},[]),m=d.useCallback(g=>{if(!g.clipboardData)return;const y=g.clipboardData.items,x=[].slice.call(y).filter(_=>_.type.indexOf("image")!==-1);if(x.length===0)return;g.preventDefault(),g.stopPropagation();const E=x[0].getAsFile();E&&r(E)},[]);return d.useEffect(()=>(window.addEventListener("dragenter",u),window.addEventListener("dragleave",f),window.addEventListener("dragover",l),window.addEventListener("drop",p),window.addEventListener("paste",m),function(){window.removeEventListener("dragenter",u),window.removeEventListener("dragleave",f),window.removeEventListener("dragover",l),window.removeEventListener("drop",p),window.removeEventListener("paste",m)})),v.jsxs("main",{className:"flex min-h-screen flex-col items-center justify-between w-full bg-[radial-gradient(circle_at_1px_1px,_#8e8e8e8e_1px,_transparent_0)] [background-size:20px_20px] bg-repeat",children:[v.jsx(rte,{}),v.jsx(nZ,{}),v.jsx(kee,{}),e?v.jsx(v.Fragment,{}):v.jsx(Pee,{onSelection:async g=>{r(g)}})]})}const cm=["light","dark"],pb="(prefers-color-scheme: dark)",ste=typeof window>"u",s6=d.createContext(void 0),ate=e=>d.useContext(s6)?je.createElement(d.Fragment,null,e.children):je.createElement(cte,e),lte=["light","dark"],cte=({forcedTheme:e,disableTransitionOnChange:t=!1,enableSystem:n=!0,enableColorScheme:r=!0,storageKey:o="theme",themes:i=lte,defaultTheme:s=n?"system":"light",attribute:l="data-theme",value:u,children:f,nonce:p})=>{const[m,g]=d.useState(()=>c$(o,s)),[y,x]=d.useState(()=>c$(o)),S=u?Object.values(u):i,E=d.useCallback(R=>{let P=R;if(!P)return;R==="system"&&n&&(P=u$());const O=u?u[P]:P,A=t?dte():null,D=document.documentElement;if(l==="class"?(D.classList.remove(...S),O&&D.classList.add(O)):O?D.setAttribute(l,O):D.removeAttribute(l),r){const B=cm.includes(s)?s:null,V=cm.includes(P)?P:B;D.style.colorScheme=V}A==null||A()},[]),_=d.useCallback(R=>{g(R);try{localStorage.setItem(o,R)}catch{}},[e]),b=d.useCallback(R=>{const P=u$(R);x(P),m==="system"&&n&&!e&&E("system")},[m,e]);d.useEffect(()=>{const R=window.matchMedia(pb);return R.addListener(b),b(R),()=>R.removeListener(b)},[b]),d.useEffect(()=>{const R=P=>{P.key===o&&_(P.newValue||s)};return window.addEventListener("storage",R),()=>window.removeEventListener("storage",R)},[_]),d.useEffect(()=>{E(e??m)},[e,m]);const C=d.useMemo(()=>({theme:m,setTheme:_,forcedTheme:e,resolvedTheme:m==="system"?y:m,themes:n?[...i,"system"]:i,systemTheme:n?y:void 0}),[m,_,e,y,n,i]);return je.createElement(s6.Provider,{value:C},je.createElement(ute,{forcedTheme:e,disableTransitionOnChange:t,enableSystem:n,enableColorScheme:r,storageKey:o,themes:i,defaultTheme:s,attribute:l,value:u,children:f,attrs:S,nonce:p}),f)},ute=d.memo(({forcedTheme:e,storageKey:t,attribute:n,enableSystem:r,enableColorScheme:o,defaultTheme:i,value:s,attrs:l,nonce:u})=>{const f=i==="system",p=n==="class"?`var d=document.documentElement,c=d.classList;c.remove(${l.map(x=>`'${x}'`).join(",")});`:`var d=document.documentElement,n='${n}',s='setAttribute';`,m=o?cm.includes(i)&&i?`if(e==='light'||e==='dark'||!e)d.style.colorScheme=e||'${i}'`:"if(e==='light'||e==='dark')d.style.colorScheme=e":"",g=(x,S=!1,E=!0)=>{const _=s?s[x]:x,b=S?x+"|| ''":`'${_}'`;let C="";return o&&E&&!S&&cm.includes(x)&&(C+=`d.style.colorScheme = '${x}';`),n==="class"?C+=S||_?`c.add(${b})`:"null":_&&(C+=`d[s](n,${b})`),C},y=e?`!function(){${p}${g(e)}}()`:r?`!function(){try{${p}var e=localStorage.getItem('${t}');if('system'===e||(!e&&${f})){var t='${pb}',m=window.matchMedia(t);if(m.media!==t||m.matches){${g("dark")}}else{${g("light")}}}else if(e){${s?`var x=${JSON.stringify(s)};`:""}${g(s?"x[e]":"e",!0)}}${f?"":"else{"+g(i,!1,!1)+"}"}${m}}catch(e){}}()`:`!function(){try{${p}var e=localStorage.getItem('${t}');if(e){${s?`var x=${JSON.stringify(s)};`:""}${g(s?"x[e]":"e",!0)}}else{${g(i,!1,!1)};}${m}}catch(t){}}();`;return je.createElement("script",{nonce:u,dangerouslySetInnerHTML:{__html:y}})},()=>!0),c$=(e,t)=>{if(ste)return;let n;try{n=localStorage.getItem(e)||void 0}catch{}return n||t},dte=()=>{const e=document.createElement("style");return e.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(e),()=>{window.getComputedStyle(document.body),setTimeout(()=>{document.head.removeChild(e)},1)}},u$=e=>(e||(e=window.matchMedia(pb)),e.matches?"dark":"light"),fte=new pL;W0.createRoot(document.getElementById("root")).render(v.jsx(je.StrictMode,{children:v.jsx(wL,{client:fte,children:v.jsx(ate,{defaultTheme:"dark",disableTransitionOnChange:!0,children:v.jsx(VU,{children:v.jsx(ite,{})})})})})); diff --git a/py/iopaint/web_app/assets/index-TI-UMrGI.js b/py/iopaint/web_app/assets/index-TI-UMrGI.js new file mode 100644 index 0000000..14a546a --- /dev/null +++ b/py/iopaint/web_app/assets/index-TI-UMrGI.js @@ -0,0 +1,165 @@ +var Fv=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)};var j=(e,t,n)=>(Fv(e,t,"read from private field"),n?n.call(e):t.get(e)),Pe=(e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)},ye=(e,t,n,r)=>(Fv(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n);var Wf=(e,t,n,r)=>({set _(o){ye(e,t,o,n)},get _(){return j(e,t,r)}}),tt=(e,t,n)=>(Fv(e,t,"access private method"),n);function $9(e,t){for(var n=0;nr[o]})}}}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 o of document.querySelectorAll('link[rel="modulepreload"]'))r(o);new MutationObserver(o=>{for(const i of o)if(i.type==="childList")for(const s of i.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&r(s)}).observe(document,{childList:!0,subtree:!0});function n(o){const i={};return o.integrity&&(i.integrity=o.integrity),o.referrerPolicy&&(i.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?i.credentials="include":o.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(o){if(o.ep)return;o.ep=!0;const i=n(o);fetch(o.href,i)}})();var Jc=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function dm(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var x$={exports:{}},fm={},b$={exports:{}},it={};/** + * @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 kd=Symbol.for("react.element"),R9=Symbol.for("react.portal"),k9=Symbol.for("react.fragment"),T9=Symbol.for("react.strict_mode"),P9=Symbol.for("react.profiler"),A9=Symbol.for("react.provider"),M9=Symbol.for("react.context"),O9=Symbol.for("react.forward_ref"),N9=Symbol.for("react.suspense"),D9=Symbol.for("react.memo"),I9=Symbol.for("react.lazy"),B_=Symbol.iterator;function L9(e){return e===null||typeof e!="object"?null:(e=B_&&e[B_]||e["@@iterator"],typeof e=="function"?e:null)}var S$={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},_$=Object.assign,E$={};function yc(e,t,n){this.props=e,this.context=t,this.refs=E$,this.updater=n||S$}yc.prototype.isReactComponent={};yc.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")};yc.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function C$(){}C$.prototype=yc.prototype;function nw(e,t,n){this.props=e,this.context=t,this.refs=E$,this.updater=n||S$}var rw=nw.prototype=new C$;rw.constructor=nw;_$(rw,yc.prototype);rw.isPureReactComponent=!0;var U_=Array.isArray,$$=Object.prototype.hasOwnProperty,ow={current:null},R$={key:!0,ref:!0,__self:!0,__source:!0};function k$(e,t,n){var r,o={},i=null,s=null;if(t!=null)for(r in t.ref!==void 0&&(s=t.ref),t.key!==void 0&&(i=""+t.key),t)$$.call(t,r)&&!R$.hasOwnProperty(r)&&(o[r]=t[r]);var l=arguments.length-2;if(l===1)o.children=n;else if(1>>1,pe=H[le];if(0>>1;le<$e;){var Ve=2*(le+1)-1,We=H[Ve],Ne=Ve+1,fe=H[Ne];if(0>o(We,W))Neo(fe,We)?(H[le]=fe,H[Ne]=W,le=Ne):(H[le]=We,H[Ve]=W,le=Ve);else if(Neo(fe,W))H[le]=fe,H[Ne]=W,le=Ne;else break e}}return X}function o(H,X){var W=H.sortIndex-X.sortIndex;return W!==0?W:H.id-X.id}if(typeof performance=="object"&&typeof performance.now=="function"){var i=performance;e.unstable_now=function(){return i.now()}}else{var s=Date,l=s.now();e.unstable_now=function(){return s.now()-l}}var u=[],f=[],p=1,m=null,g=3,y=!1,x=!1,S=!1,E=typeof setTimeout=="function"?setTimeout:null,_=typeof clearTimeout=="function"?clearTimeout:null,b=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function C(H){for(var X=n(f);X!==null;){if(X.callback===null)r(f);else if(X.startTime<=H)r(f),X.sortIndex=X.expirationTime,t(u,X);else break;X=n(f)}}function R(H){if(S=!1,C(H),!x)if(n(u)!==null)x=!0,M(P);else{var X=n(f);X!==null&&ee(R,X.startTime-H)}}function P(H,X){x=!1,S&&(S=!1,_(D),D=-1),y=!0;var W=g;try{for(C(X),m=n(u);m!==null&&(!(m.expirationTime>X)||H&&!J());){var le=m.callback;if(typeof le=="function"){m.callback=null,g=m.priorityLevel;var pe=le(m.expirationTime<=X);X=e.unstable_now(),typeof pe=="function"?m.callback=pe:m===n(u)&&r(u),C(X)}else r(u);m=n(u)}if(m!==null)var $e=!0;else{var Ve=n(f);Ve!==null&&ee(R,Ve.startTime-X),$e=!1}return $e}finally{m=null,g=W,y=!1}}var O=!1,A=null,D=-1,B=5,V=-1;function J(){return!(e.unstable_now()-VH||125le?(H.sortIndex=W,t(f,H),n(u)===null&&H===n(f)&&(S?(_(D),D=-1):S=!0,ee(R,W-le))):(H.sortIndex=pe,t(u,H),x||y||(x=!0,M(P))),H},e.unstable_shouldYield=J,e.unstable_wrapCallback=function(H){var X=g;return function(){var W=g;g=X;try{return H.apply(this,arguments)}finally{g=W}}}})(M$);A$.exports=M$;var X9=A$.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 O$=d,yr=X9;function ce(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"),H0=Object.prototype.hasOwnProperty,Z9=/^[: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]*$/,W_={},H_={};function q9(e){return H0.call(H_,e)?!0:H0.call(W_,e)?!1:Z9.test(e)?H_[e]=!0:(W_[e]=!0,!1)}function Q9(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 J9(e,t,n,r){if(t===null||typeof t>"u"||Q9(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 Un(e,t,n,r,o,i,s){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=o,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=i,this.removeEmptyString=s}var bn={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){bn[e]=new Un(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];bn[t]=new Un(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){bn[e]=new Un(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){bn[e]=new Un(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){bn[e]=new Un(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){bn[e]=new Un(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){bn[e]=new Un(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){bn[e]=new Un(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){bn[e]=new Un(e,5,!1,e.toLowerCase(),null,!1,!1)});var sw=/[\-:]([a-z])/g;function aw(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(sw,aw);bn[t]=new Un(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(sw,aw);bn[t]=new Un(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(sw,aw);bn[t]=new Un(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){bn[e]=new Un(e,1,!1,e.toLowerCase(),null,!1,!1)});bn.xlinkHref=new Un("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){bn[e]=new Un(e,1,!1,e.toLowerCase(),null,!0,!0)});function lw(e,t,n,r){var o=bn.hasOwnProperty(t)?bn[t]:null;(o!==null?o.type!==0:r||!(2l||o[s]!==i[l]){var u=` +`+o[s].replace(" at new "," at ");return e.displayName&&u.includes("")&&(u=u.replace("",e.displayName)),u}while(1<=s&&0<=l);break}}}finally{Bv=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?vu(e):""}function eD(e){switch(e.tag){case 5:return vu(e.type);case 16:return vu("Lazy");case 13:return vu("Suspense");case 19:return vu("SuspenseList");case 0:case 2:case 15:return e=Uv(e.type,!1),e;case 11:return e=Uv(e.type.render,!1),e;case 1:return e=Uv(e.type,!0),e;default:return""}}function X0(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 ml:return"Fragment";case pl:return"Portal";case K0:return"Profiler";case cw:return"StrictMode";case G0:return"Suspense";case Y0:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case I$:return(e.displayName||"Context")+".Consumer";case D$:return(e._context.displayName||"Context")+".Provider";case uw:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case dw:return t=e.displayName||null,t!==null?t:X0(e.type)||"Memo";case Ji:t=e._payload,e=e._init;try{return X0(e(t))}catch{}}return null}function tD(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 X0(t);case 8:return t===cw?"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 Rs(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function F$(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function nD(e){var t=F$(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 o=n.get,i=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return o.call(this)},set:function(s){r=""+s,i.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 Gf(e){e._valueTracker||(e._valueTracker=nD(e))}function j$(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=F$(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function ap(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 Z0(e,t){var n=t.checked;return zt({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function G_(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=Rs(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 z$(e,t){t=t.checked,t!=null&&lw(e,"checked",t,!1)}function q0(e,t){z$(e,t);var n=Rs(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")?Q0(e,t.type,n):t.hasOwnProperty("defaultValue")&&Q0(e,t.type,Rs(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function Y_(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 Q0(e,t,n){(t!=="number"||ap(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var yu=Array.isArray;function Rl(e,t,n,r){if(e=e.options,t){t={};for(var o=0;o"+t.valueOf().toString()+"",t=Yf.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function ju(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var Eu={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},rD=["Webkit","ms","Moz","O"];Object.keys(Eu).forEach(function(e){rD.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),Eu[t]=Eu[e]})});function W$(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||Eu.hasOwnProperty(e)&&Eu[e]?(""+t).trim():t+"px"}function H$(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,o=W$(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,o):e[n]=o}}var oD=zt({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 ty(e,t){if(t){if(oD[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(ce(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(ce(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(ce(61))}if(t.style!=null&&typeof t.style!="object")throw Error(ce(62))}}function ny(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 ry=null;function fw(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var oy=null,kl=null,Tl=null;function q_(e){if(e=Ad(e)){if(typeof oy!="function")throw Error(ce(280));var t=e.stateNode;t&&(t=vm(t),oy(e.stateNode,e.type,t))}}function K$(e){kl?Tl?Tl.push(e):Tl=[e]:kl=e}function G$(){if(kl){var e=kl,t=Tl;if(Tl=kl=null,q_(e),t)for(e=0;e>>=0,e===0?32:31-(mD(e)/gD|0)|0}var Xf=64,Zf=4194304;function wu(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 dp(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,o=e.suspendedLanes,i=e.pingedLanes,s=n&268435455;if(s!==0){var l=s&~o;l!==0?r=wu(l):(i&=s,i!==0&&(r=wu(i)))}else s=n&~o,s!==0?r=wu(s):i!==0&&(r=wu(i));if(r===0)return 0;if(t!==0&&t!==r&&!(t&o)&&(o=r&-r,i=t&-t,o>=i||o===16&&(i&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 Td(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-wo(t),e[t]=n}function xD(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=$u),sE=" ",aE=!1;function h5(e,t){switch(e){case"keyup":return YD.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function p5(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var gl=!1;function ZD(e,t){switch(e){case"compositionend":return p5(t);case"keypress":return t.which!==32?null:(aE=!0,sE);case"textInput":return e=t.data,e===sE&&aE?null:e;default:return null}}function qD(e,t){if(gl)return e==="compositionend"||!xw&&h5(e,t)?(e=d5(),Mh=vw=us=null,gl=!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=dE(n)}}function y5(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?y5(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function w5(){for(var e=window,t=ap();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=ap(e.document)}return t}function bw(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 sI(e){var t=w5(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&y5(n.ownerDocument.documentElement,n)){if(r!==null&&bw(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 o=n.textContent.length,i=Math.min(r.start,o);r=r.end===void 0?i:Math.min(r.end,o),!e.extend&&i>r&&(o=r,r=i,i=o),o=fE(n,i);var s=fE(n,r);o&&s&&(e.rangeCount!==1||e.anchorNode!==o.node||e.anchorOffset!==o.offset||e.focusNode!==s.node||e.focusOffset!==s.offset)&&(t=t.createRange(),t.setStart(o.node,o.offset),e.removeAllRanges(),i>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,vl=null,uy=null,ku=null,dy=!1;function hE(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;dy||vl==null||vl!==ap(r)||(r=vl,"selectionStart"in r&&bw(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}),ku&&Hu(ku,r)||(ku=r,r=pp(uy,"onSelect"),0xl||(e.current=vy[xl],vy[xl]=null,xl--)}function $t(e,t){xl++,vy[xl]=e.current,e.current=t}var ks={},Pn=Ns(ks),Jn=Ns(!1),Ra=ks;function Ql(e,t){var n=e.type.contextTypes;if(!n)return ks;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var o={},i;for(i in n)o[i]=t[i];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=o),o}function er(e){return e=e.childContextTypes,e!=null}function gp(){At(Jn),At(Pn)}function xE(e,t,n){if(Pn.current!==ks)throw Error(ce(168));$t(Pn,t),$t(Jn,n)}function k5(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var o in r)if(!(o in t))throw Error(ce(108,tD(e)||"Unknown",o));return zt({},n,r)}function vp(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||ks,Ra=Pn.current,$t(Pn,e),$t(Jn,Jn.current),!0}function bE(e,t,n){var r=e.stateNode;if(!r)throw Error(ce(169));n?(e=k5(e,t,Ra),r.__reactInternalMemoizedMergedChildContext=e,At(Jn),At(Pn),$t(Pn,e)):At(Jn),$t(Jn,n)}var pi=null,ym=!1,n0=!1;function T5(e){pi===null?pi=[e]:pi.push(e)}function yI(e){ym=!0,T5(e)}function Ds(){if(!n0&&pi!==null){n0=!0;var e=0,t=xt;try{var n=pi;for(xt=1;e>=s,o-=s,mi=1<<32-wo(t)+o|n<D?(B=A,A=null):B=A.sibling;var V=g(_,A,C[D],R);if(V===null){A===null&&(A=B);break}e&&A&&V.alternate===null&&t(_,A),b=i(V,b,D),O===null?P=V:O.sibling=V,O=V,A=B}if(D===C.length)return n(_,A),Dt&&ta(_,D),P;if(A===null){for(;DD?(B=A,A=null):B=A.sibling;var J=g(_,A,V.value,R);if(J===null){A===null&&(A=B);break}e&&A&&J.alternate===null&&t(_,A),b=i(J,b,D),O===null?P=J:O.sibling=J,O=J,A=B}if(V.done)return n(_,A),Dt&&ta(_,D),P;if(A===null){for(;!V.done;D++,V=C.next())V=m(_,V.value,R),V!==null&&(b=i(V,b,D),O===null?P=V:O.sibling=V,O=V);return Dt&&ta(_,D),P}for(A=r(_,A);!V.done;D++,V=C.next())V=y(A,_,D,V.value,R),V!==null&&(e&&V.alternate!==null&&A.delete(V.key===null?D:V.key),b=i(V,b,D),O===null?P=V:O.sibling=V,O=V);return e&&A.forEach(function(G){return t(_,G)}),Dt&&ta(_,D),P}function E(_,b,C,R){if(typeof C=="object"&&C!==null&&C.type===ml&&C.key===null&&(C=C.props.children),typeof C=="object"&&C!==null){switch(C.$$typeof){case Kf:e:{for(var P=C.key,O=b;O!==null;){if(O.key===P){if(P=C.type,P===ml){if(O.tag===7){n(_,O.sibling),b=o(O,C.props.children),b.return=_,_=b;break e}}else if(O.elementType===P||typeof P=="object"&&P!==null&&P.$$typeof===Ji&&kE(P)===O.type){n(_,O.sibling),b=o(O,C.props),b.ref=iu(_,O,C),b.return=_,_=b;break e}n(_,O);break}else t(_,O);O=O.sibling}C.type===ml?(b=$a(C.props.children,_.mode,R,C.key),b.return=_,_=b):(R=zh(C.type,C.key,C.props,null,_.mode,R),R.ref=iu(_,b,C),R.return=_,_=R)}return s(_);case pl:e:{for(O=C.key;b!==null;){if(b.key===O)if(b.tag===4&&b.stateNode.containerInfo===C.containerInfo&&b.stateNode.implementation===C.implementation){n(_,b.sibling),b=o(b,C.children||[]),b.return=_,_=b;break e}else{n(_,b);break}else t(_,b);b=b.sibling}b=u0(C,_.mode,R),b.return=_,_=b}return s(_);case Ji:return O=C._init,E(_,b,O(C._payload),R)}if(yu(C))return x(_,b,C,R);if(eu(C))return S(_,b,C,R);rh(_,C)}return typeof C=="string"&&C!==""||typeof C=="number"?(C=""+C,b!==null&&b.tag===6?(n(_,b.sibling),b=o(b,C),b.return=_,_=b):(n(_,b),b=c0(C,_.mode,R),b.return=_,_=b),s(_)):n(_,b)}return E}var ec=L5(!0),F5=L5(!1),Md={},Ko=Ns(Md),Xu=Ns(Md),Zu=Ns(Md);function fa(e){if(e===Md)throw Error(ce(174));return e}function Pw(e,t){switch($t(Zu,t),$t(Xu,e),$t(Ko,Md),e=t.nodeType,e){case 9:case 11:t=(t=t.documentElement)?t.namespaceURI:ey(null,"");break;default:e=e===8?t.parentNode:t,t=e.namespaceURI||null,e=e.tagName,t=ey(t,e)}At(Ko),$t(Ko,t)}function tc(){At(Ko),At(Xu),At(Zu)}function j5(e){fa(Zu.current);var t=fa(Ko.current),n=ey(t,e.type);t!==n&&($t(Xu,e),$t(Ko,n))}function Aw(e){Xu.current===e&&(At(Ko),At(Xu))}var Lt=Ns(0);function _p(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 r0=[];function Mw(){for(var e=0;en?n:4,e(!0);var r=o0.transition;o0.transition={};try{e(!1),t()}finally{xt=n,o0.transition=r}}function tR(){return Yr().memoizedState}function SI(e,t,n){var r=Ss(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},nR(e))rR(t,n);else if(n=O5(e,t,n,r),n!==null){var o=jn();xo(n,e,r,o),oR(n,t,r)}}function _I(e,t,n){var r=Ss(e),o={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(nR(e))rR(t,o);else{var i=e.alternate;if(e.lanes===0&&(i===null||i.lanes===0)&&(i=t.lastRenderedReducer,i!==null))try{var s=t.lastRenderedState,l=i(s,n);if(o.hasEagerState=!0,o.eagerState=l,So(l,s)){var u=t.interleaved;u===null?(o.next=o,kw(t)):(o.next=u.next,u.next=o),t.interleaved=o;return}}catch{}finally{}n=O5(e,t,o,r),n!==null&&(o=jn(),xo(n,e,r,o),oR(n,t,r))}}function nR(e){var t=e.alternate;return e===jt||t!==null&&t===jt}function rR(e,t){Tu=Ep=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function oR(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,pw(e,n)}}var Cp={readContext:Gr,useCallback:$n,useContext:$n,useEffect:$n,useImperativeHandle:$n,useInsertionEffect:$n,useLayoutEffect:$n,useMemo:$n,useReducer:$n,useRef:$n,useState:$n,useDebugValue:$n,useDeferredValue:$n,useTransition:$n,useMutableSource:$n,useSyncExternalStore:$n,useId:$n,unstable_isNewReconciler:!1},EI={readContext:Gr,useCallback:function(e,t){return Po().memoizedState=[e,t===void 0?null:t],e},useContext:Gr,useEffect:PE,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,Ih(4194308,4,Z5.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Ih(4194308,4,e,t)},useInsertionEffect:function(e,t){return Ih(4,2,e,t)},useMemo:function(e,t){var n=Po();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=Po();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=SI.bind(null,jt,e),[r.memoizedState,e]},useRef:function(e){var t=Po();return e={current:e},t.memoizedState=e},useState:TE,useDebugValue:Lw,useDeferredValue:function(e){return Po().memoizedState=e},useTransition:function(){var e=TE(!1),t=e[0];return e=bI.bind(null,e[1]),Po().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=jt,o=Po();if(Dt){if(n===void 0)throw Error(ce(407));n=n()}else{if(n=t(),dn===null)throw Error(ce(349));Ta&30||U5(r,t,n)}o.memoizedState=n;var i={value:n,getSnapshot:t};return o.queue=i,PE(W5.bind(null,r,i,e),[e]),r.flags|=2048,Ju(9,V5.bind(null,r,i,n,t),void 0,null),n},useId:function(){var e=Po(),t=dn.identifierPrefix;if(Dt){var n=gi,r=mi;n=(r&~(1<<32-wo(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=qu++,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[Io]=t,e[Yu]=r,hR(e,t,!1,!1),t.stateNode=e;e:{switch(s=ny(n,r),n){case"dialog":Tt("cancel",e),Tt("close",e),o=r;break;case"iframe":case"object":case"embed":Tt("load",e),o=r;break;case"video":case"audio":for(o=0;orc&&(t.flags|=128,r=!0,su(i,!1),t.lanes=4194304)}else{if(!r)if(e=_p(s),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),su(i,!0),i.tail===null&&i.tailMode==="hidden"&&!s.alternate&&!Dt)return Rn(t),null}else 2*Xt()-i.renderingStartTime>rc&&n!==1073741824&&(t.flags|=128,r=!0,su(i,!1),t.lanes=4194304);i.isBackwards?(s.sibling=t.child,t.child=s):(n=i.last,n!==null?n.sibling=s:t.child=s,i.last=s)}return i.tail!==null?(t=i.tail,i.rendering=t,i.tail=t.sibling,i.renderingStartTime=Xt(),t.sibling=null,n=Lt.current,$t(Lt,r?n&1|2:n&1),t):(Rn(t),null);case 22:case 23:return Vw(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?fr&1073741824&&(Rn(t),t.subtreeFlags&6&&(t.flags|=8192)):Rn(t),null;case 24:return null;case 25:return null}throw Error(ce(156,t.tag))}function MI(e,t){switch(_w(t),t.tag){case 1:return er(t.type)&&gp(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return tc(),At(Jn),At(Pn),Mw(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return Aw(t),null;case 13:if(At(Lt),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(ce(340));Jl()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return At(Lt),null;case 4:return tc(),null;case 10:return Rw(t.type._context),null;case 22:case 23:return Vw(),null;case 24:return null;default:return null}}var ih=!1,Tn=!1,OI=typeof WeakSet=="function"?WeakSet:Set,Ee=null;function El(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){Wt(e,t,r)}else n.current=null}function Ty(e,t,n){try{n()}catch(r){Wt(e,t,r)}}var jE=!1;function NI(e,t){if(fy=fp,e=w5(),bw(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 o=r.anchorOffset,i=r.focusNode;r=r.focusOffset;try{n.nodeType,i.nodeType}catch{n=null;break e}var s=0,l=-1,u=-1,f=0,p=0,m=e,g=null;t:for(;;){for(var y;m!==n||o!==0&&m.nodeType!==3||(l=s+o),m!==i||r!==0&&m.nodeType!==3||(u=s+r),m.nodeType===3&&(s+=m.nodeValue.length),(y=m.firstChild)!==null;)g=m,m=y;for(;;){if(m===e)break t;if(g===n&&++f===o&&(l=s),g===i&&++p===r&&(u=s),(y=m.nextSibling)!==null)break;m=g,g=m.parentNode}m=y}n=l===-1||u===-1?null:{start:l,end:u}}else n=null}n=n||{start:0,end:0}}else n=null;for(hy={focusedElem:e,selectionRange:n},fp=!1,Ee=t;Ee!==null;)if(t=Ee,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,Ee=e;else for(;Ee!==null;){t=Ee;try{var x=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(x!==null){var S=x.memoizedProps,E=x.memoizedState,_=t.stateNode,b=_.getSnapshotBeforeUpdate(t.elementType===t.type?S:io(t.type,S),E);_.__reactInternalSnapshotBeforeUpdate=b}break;case 3:var C=t.stateNode.containerInfo;C.nodeType===1?C.textContent="":C.nodeType===9&&C.documentElement&&C.removeChild(C.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(ce(163))}}catch(R){Wt(t,t.return,R)}if(e=t.sibling,e!==null){e.return=t.return,Ee=e;break}Ee=t.return}return x=jE,jE=!1,x}function Pu(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var o=r=r.next;do{if((o.tag&e)===e){var i=o.destroy;o.destroy=void 0,i!==void 0&&Ty(t,n,i)}o=o.next}while(o!==r)}}function bm(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 Py(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 gR(e){var t=e.alternate;t!==null&&(e.alternate=null,gR(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Io],delete t[Yu],delete t[gy],delete t[gI],delete t[vI])),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 vR(e){return e.tag===5||e.tag===3||e.tag===4}function zE(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||vR(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 Ay(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=mp));else if(r!==4&&(e=e.child,e!==null))for(Ay(e,t,n),e=e.sibling;e!==null;)Ay(e,t,n),e=e.sibling}function My(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(My(e,t,n),e=e.sibling;e!==null;)My(e,t,n),e=e.sibling}var mn=null,lo=!1;function Ki(e,t,n){for(n=n.child;n!==null;)yR(e,t,n),n=n.sibling}function yR(e,t,n){if(Ho&&typeof Ho.onCommitFiberUnmount=="function")try{Ho.onCommitFiberUnmount(hm,n)}catch{}switch(n.tag){case 5:Tn||El(n,t);case 6:var r=mn,o=lo;mn=null,Ki(e,t,n),mn=r,lo=o,mn!==null&&(lo?(e=mn,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):mn.removeChild(n.stateNode));break;case 18:mn!==null&&(lo?(e=mn,n=n.stateNode,e.nodeType===8?t0(e.parentNode,n):e.nodeType===1&&t0(e,n),Vu(e)):t0(mn,n.stateNode));break;case 4:r=mn,o=lo,mn=n.stateNode.containerInfo,lo=!0,Ki(e,t,n),mn=r,lo=o;break;case 0:case 11:case 14:case 15:if(!Tn&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){o=r=r.next;do{var i=o,s=i.destroy;i=i.tag,s!==void 0&&(i&2||i&4)&&Ty(n,t,s),o=o.next}while(o!==r)}Ki(e,t,n);break;case 1:if(!Tn&&(El(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(l){Wt(n,t,l)}Ki(e,t,n);break;case 21:Ki(e,t,n);break;case 22:n.mode&1?(Tn=(r=Tn)||n.memoizedState!==null,Ki(e,t,n),Tn=r):Ki(e,t,n);break;default:Ki(e,t,n)}}function BE(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new OI),t.forEach(function(r){var o=VI.bind(null,e,r);n.has(r)||(n.add(r),r.then(o,o))})}}function ro(e,t){var n=t.deletions;if(n!==null)for(var r=0;ro&&(o=s),r&=~i}if(r=o,r=Xt()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*II(r/1960))-r,10e?16:e,ds===null)var r=!1;else{if(e=ds,ds=null,kp=0,dt&6)throw Error(ce(331));var o=dt;for(dt|=4,Ee=e.current;Ee!==null;){var i=Ee,s=i.child;if(Ee.flags&16){var l=i.deletions;if(l!==null){for(var u=0;uXt()-Bw?Ca(e,0):zw|=n),tr(e,t)}function $R(e,t){t===0&&(e.mode&1?(t=Zf,Zf<<=1,!(Zf&130023424)&&(Zf=4194304)):t=1);var n=jn();e=_i(e,t),e!==null&&(Td(e,t,n),tr(e,n))}function UI(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),$R(e,n)}function VI(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,o=e.memoizedState;o!==null&&(n=o.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(ce(314))}r!==null&&r.delete(t),$R(e,n)}var RR;RR=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||Jn.current)Qn=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return Qn=!1,PI(e,t,n);Qn=!!(e.flags&131072)}else Qn=!1,Dt&&t.flags&1048576&&P5(t,wp,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;Lh(e,t),e=t.pendingProps;var o=Ql(t,Pn.current);Al(t,n),o=Nw(null,t,r,e,o,n);var i=Dw();return t.flags|=1,typeof o=="object"&&o!==null&&typeof o.render=="function"&&o.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,er(r)?(i=!0,vp(t)):i=!1,t.memoizedState=o.state!==null&&o.state!==void 0?o.state:null,Tw(t),o.updater=wm,t.stateNode=o,o._reactInternals=t,Sy(t,r,e,n),t=Cy(null,t,r,!0,i,n)):(t.tag=0,Dt&&i&&Sw(t),In(null,t,o,n),t=t.child),t;case 16:r=t.elementType;e:{switch(Lh(e,t),e=t.pendingProps,o=r._init,r=o(r._payload),t.type=r,o=t.tag=HI(r),e=io(r,e),o){case 0:t=Ey(null,t,r,e,n);break e;case 1:t=IE(null,t,r,e,n);break e;case 11:t=NE(null,t,r,e,n);break e;case 14:t=DE(null,t,r,io(r.type,e),n);break e}throw Error(ce(306,r,""))}return t;case 0:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),Ey(e,t,r,o,n);case 1:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),IE(e,t,r,o,n);case 3:e:{if(uR(t),e===null)throw Error(ce(387));r=t.pendingProps,i=t.memoizedState,o=i.element,N5(e,t),Sp(t,r,null,n);var s=t.memoizedState;if(r=s.element,i.isDehydrated)if(i={element:r,isDehydrated:!1,cache:s.cache,pendingSuspenseBoundaries:s.pendingSuspenseBoundaries,transitions:s.transitions},t.updateQueue.baseState=i,t.memoizedState=i,t.flags&256){o=nc(Error(ce(423)),t),t=LE(e,t,r,n,o);break e}else if(r!==o){o=nc(Error(ce(424)),t),t=LE(e,t,r,n,o);break e}else for(mr=ws(t.stateNode.containerInfo.firstChild),gr=t,Dt=!0,ho=null,n=F5(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(Jl(),r===o){t=Ei(e,t,n);break e}In(e,t,r,n)}t=t.child}return t;case 5:return j5(t),e===null&&wy(t),r=t.type,o=t.pendingProps,i=e!==null?e.memoizedProps:null,s=o.children,py(r,o)?s=null:i!==null&&py(r,i)&&(t.flags|=32),cR(e,t),In(e,t,s,n),t.child;case 6:return e===null&&wy(t),null;case 13:return dR(e,t,n);case 4:return Pw(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=ec(t,null,r,n):In(e,t,r,n),t.child;case 11:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),NE(e,t,r,o,n);case 7:return In(e,t,t.pendingProps,n),t.child;case 8:return In(e,t,t.pendingProps.children,n),t.child;case 12:return In(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,o=t.pendingProps,i=t.memoizedProps,s=o.value,$t(xp,r._currentValue),r._currentValue=s,i!==null)if(So(i.value,s)){if(i.children===o.children&&!Jn.current){t=Ei(e,t,n);break e}}else for(i=t.child,i!==null&&(i.return=t);i!==null;){var l=i.dependencies;if(l!==null){s=i.child;for(var u=l.firstContext;u!==null;){if(u.context===r){if(i.tag===1){u=wi(-1,n&-n),u.tag=2;var f=i.updateQueue;if(f!==null){f=f.shared;var p=f.pending;p===null?u.next=u:(u.next=p.next,p.next=u),f.pending=u}}i.lanes|=n,u=i.alternate,u!==null&&(u.lanes|=n),xy(i.return,n,t),l.lanes|=n;break}u=u.next}}else if(i.tag===10)s=i.type===t.type?null:i.child;else if(i.tag===18){if(s=i.return,s===null)throw Error(ce(341));s.lanes|=n,l=s.alternate,l!==null&&(l.lanes|=n),xy(s,n,t),s=i.sibling}else s=i.child;if(s!==null)s.return=i;else for(s=i;s!==null;){if(s===t){s=null;break}if(i=s.sibling,i!==null){i.return=s.return,s=i;break}s=s.return}i=s}In(e,t,o.children,n),t=t.child}return t;case 9:return o=t.type,r=t.pendingProps.children,Al(t,n),o=Gr(o),r=r(o),t.flags|=1,In(e,t,r,n),t.child;case 14:return r=t.type,o=io(r,t.pendingProps),o=io(r.type,o),DE(e,t,r,o,n);case 15:return aR(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),Lh(e,t),t.tag=1,er(r)?(e=!0,vp(t)):e=!1,Al(t,n),I5(t,r,o),Sy(t,r,o,n),Cy(null,t,r,!0,e,n);case 19:return fR(e,t,n);case 22:return lR(e,t,n)}throw Error(ce(156,t.tag))};function kR(e,t){return e5(e,t)}function WI(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 Ur(e,t,n,r){return new WI(e,t,n,r)}function Hw(e){return e=e.prototype,!(!e||!e.isReactComponent)}function HI(e){if(typeof e=="function")return Hw(e)?1:0;if(e!=null){if(e=e.$$typeof,e===uw)return 11;if(e===dw)return 14}return 2}function _s(e,t){var n=e.alternate;return n===null?(n=Ur(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 zh(e,t,n,r,o,i){var s=2;if(r=e,typeof e=="function")Hw(e)&&(s=1);else if(typeof e=="string")s=5;else e:switch(e){case ml:return $a(n.children,o,i,t);case cw:s=8,o|=8;break;case K0:return e=Ur(12,n,t,o|2),e.elementType=K0,e.lanes=i,e;case G0:return e=Ur(13,n,t,o),e.elementType=G0,e.lanes=i,e;case Y0:return e=Ur(19,n,t,o),e.elementType=Y0,e.lanes=i,e;case L$:return _m(n,o,i,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case D$:s=10;break e;case I$:s=9;break e;case uw:s=11;break e;case dw:s=14;break e;case Ji:s=16,r=null;break e}throw Error(ce(130,e==null?e:typeof e,""))}return t=Ur(s,n,t,o),t.elementType=e,t.type=r,t.lanes=i,t}function $a(e,t,n,r){return e=Ur(7,e,r,t),e.lanes=n,e}function _m(e,t,n,r){return e=Ur(22,e,r,t),e.elementType=L$,e.lanes=n,e.stateNode={isHidden:!1},e}function c0(e,t,n){return e=Ur(6,e,null,t),e.lanes=n,e}function u0(e,t,n){return t=Ur(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function KI(e,t,n,r,o){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=Wv(0),this.expirationTimes=Wv(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Wv(0),this.identifierPrefix=r,this.onRecoverableError=o,this.mutableSourceEagerHydrationData=null}function Kw(e,t,n,r,o,i,s,l,u){return e=new KI(e,t,n,l,u),t===1?(t=1,i===!0&&(t|=8)):t=0,i=Ur(3,null,null,t),e.current=i,i.stateNode=e,i.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},Tw(i),e}function GI(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(MR)}catch(e){console.error(e)}}MR(),P$.exports=br;var Is=P$.exports;const QI=dm(Is);var XE=Is;W0.createRoot=XE.createRoot,W0.hydrateRoot=XE.hydrateRoot;var Od=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},oc=typeof window>"u"||"Deno"in window;function Lr(){}function JI(e,t){return typeof e=="function"?e(t):e}function Ly(e){return typeof e=="number"&&e>=0&&e!==1/0}function OR(e,t){return Math.max(e+(t||0)-Date.now(),0)}function ZE(e,t){const{type:n="all",exact:r,fetchStatus:o,predicate:i,queryKey:s,stale:l}=e;if(s){if(r){if(t.queryHash!==Zw(s,t.options))return!1}else if(!nd(t.queryKey,s))return!1}if(n!=="all"){const u=t.isActive();if(n==="active"&&!u||n==="inactive"&&u)return!1}return!(typeof l=="boolean"&&t.isStale()!==l||typeof o<"u"&&o!==t.state.fetchStatus||i&&!i(t))}function qE(e,t){const{exact:n,status:r,predicate:o,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(td(t.options.mutationKey)!==td(i))return!1}else if(!nd(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||o&&!o(t))}function Zw(e,t){return((t==null?void 0:t.queryKeyHashFn)||td)(e)}function td(e){return JSON.stringify(e,(t,n)=>jy(n)?Object.keys(n).sort().reduce((r,o)=>(r[o]=n[o],r),{}):n)}function nd(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?!Object.keys(t).some(n=>!nd(e[n],t[n])):!1}function NR(e,t){if(e===t)return e;const n=QE(e)&&QE(t);if(n||jy(e)&&jy(t)){const r=n?e.length:Object.keys(e).length,o=n?t:Object.keys(t),i=o.length,s=n?[]:{};let l=0;for(let u=0;u"u")return!0;const n=t.prototype;return!(!JE(n)||!n.hasOwnProperty("isPrototypeOf"))}function JE(e){return Object.prototype.toString.call(e)==="[object Object]"}function DR(e){return new Promise(t=>{setTimeout(t,e)})}function eC(e){DR(0).then(e)}function zy(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?NR(e,t):t}function eL(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function tL(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var ga,rs,Il,d$,nL=(d$=class extends Od{constructor(){super();Pe(this,ga,void 0);Pe(this,rs,void 0);Pe(this,Il,void 0);ye(this,Il,t=>{if(!oc&&window.addEventListener){const n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){j(this,rs)||this.setEventListener(j(this,Il))}onUnsubscribe(){var t;this.hasListeners()||((t=j(this,rs))==null||t.call(this),ye(this,rs,void 0))}setEventListener(t){var n;ye(this,Il,t),(n=j(this,rs))==null||n.call(this),ye(this,rs,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){j(this,ga)!==t&&(ye(this,ga,t),this.onFocus())}onFocus(){this.listeners.forEach(t=>{t()})}isFocused(){var t;return typeof j(this,ga)=="boolean"?j(this,ga):((t=globalThis.document)==null?void 0:t.visibilityState)!=="hidden"}},ga=new WeakMap,rs=new WeakMap,Il=new WeakMap,d$),Ap=new nL,Ll,os,Fl,f$,rL=(f$=class extends Od{constructor(){super();Pe(this,Ll,!0);Pe(this,os,void 0);Pe(this,Fl,void 0);ye(this,Fl,t=>{if(!oc&&window.addEventListener){const n=()=>t(!0),r=()=>t(!1);return window.addEventListener("online",n,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",r)}}})}onSubscribe(){j(this,os)||this.setEventListener(j(this,Fl))}onUnsubscribe(){var t;this.hasListeners()||((t=j(this,os))==null||t.call(this),ye(this,os,void 0))}setEventListener(t){var n;ye(this,Fl,t),(n=j(this,os))==null||n.call(this),ye(this,os,t(this.setOnline.bind(this)))}setOnline(t){j(this,Ll)!==t&&(ye(this,Ll,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return j(this,Ll)}},Ll=new WeakMap,os=new WeakMap,Fl=new WeakMap,f$),Mp=new rL;function oL(e){return Math.min(1e3*2**e,3e4)}function km(e){return(e??"online")==="online"?Mp.isOnline():!0}var IR=class{constructor(e){this.revert=e==null?void 0:e.revert,this.silent=e==null?void 0:e.silent}};function d0(e){return e instanceof IR}function LR(e){let t=!1,n=0,r=!1,o,i,s;const l=new Promise((E,_)=>{i=E,s=_}),u=E=>{var _;r||(y(new IR(E)),(_=e.abort)==null||_.call(e))},f=()=>{t=!0},p=()=>{t=!1},m=()=>!Ap.isFocused()||e.networkMode!=="always"&&!Mp.isOnline(),g=E=>{var _;r||(r=!0,(_=e.onSuccess)==null||_.call(e,E),o==null||o(),i(E))},y=E=>{var _;r||(r=!0,(_=e.onError)==null||_.call(e,E),o==null||o(),s(E))},x=()=>new Promise(E=>{var _;o=b=>{const C=r||!m();return C&&E(b),C},(_=e.onPause)==null||_.call(e)}).then(()=>{var E;o=void 0,r||(E=e.onContinue)==null||E.call(e)}),S=()=>{if(r)return;let E;try{E=e.fn()}catch(_){E=Promise.reject(_)}Promise.resolve(E).then(g).catch(_=>{var O;if(r)return;const b=e.retry??(oc?0:3),C=e.retryDelay??oL,R=typeof C=="function"?C(n,_):C,P=b===!0||typeof b=="number"&&n{if(m())return x()}).then(()=>{t?y(_):S()})})};return km(e.networkMode)?S():x().then(S),{promise:l,cancel:u,continue:()=>(o==null?void 0:o())?l:Promise.resolve(),cancelRetry:f,continueRetry:p}}function iL(){let e=[],t=0,n=p=>{p()},r=p=>{p()};const o=p=>{let m;t++;try{m=p()}finally{t--,t||l()}return m},i=p=>{t?e.push(p):eC(()=>{n(p)})},s=p=>(...m)=>{i(()=>{p(...m)})},l=()=>{const p=e;e=[],p.length&&eC(()=>{r(()=>{p.forEach(m=>{n(m)})})})};return{batch:o,batchCalls:s,schedule:i,setNotifyFunction:p=>{n=p},setBatchNotifyFunction:p=>{r=p}}}var vn=iL(),va,h$,FR=(h$=class{constructor(){Pe(this,va,void 0)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Ly(this.gcTime)&&ye(this,va,setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(oc?1/0:5*60*1e3))}clearGcTimeout(){j(this,va)&&(clearTimeout(j(this,va)),ye(this,va,void 0))}},va=new WeakMap,h$),jl,zl,Nr,is,Dr,cn,vd,ya,Bl,Bh,ao,di,p$,sL=(p$=class extends FR{constructor(t){super();Pe(this,Bl);Pe(this,ao);Pe(this,jl,void 0);Pe(this,zl,void 0);Pe(this,Nr,void 0);Pe(this,is,void 0);Pe(this,Dr,void 0);Pe(this,cn,void 0);Pe(this,vd,void 0);Pe(this,ya,void 0);ye(this,ya,!1),ye(this,vd,t.defaultOptions),tt(this,Bl,Bh).call(this,t.options),ye(this,cn,[]),ye(this,Nr,t.cache),this.queryKey=t.queryKey,this.queryHash=t.queryHash,ye(this,jl,t.state||aL(this.options)),this.state=j(this,jl),this.scheduleGc()}get meta(){return this.options.meta}optionalRemove(){!j(this,cn).length&&this.state.fetchStatus==="idle"&&j(this,Nr).remove(this)}setData(t,n){const r=zy(this.state.data,t,this.options);return tt(this,ao,di).call(this,{data:r,type:"success",dataUpdatedAt:n==null?void 0:n.updatedAt,manual:n==null?void 0:n.manual}),r}setState(t,n){tt(this,ao,di).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){var r;const n=j(this,is);return(r=j(this,Dr))==null||r.cancel(t),n?n.then(Lr).catch(Lr):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(j(this,jl))}isActive(){return j(this,cn).some(t=>t.options.enabled!==!1)}isDisabled(){return this.getObserversCount()>0&&!this.isActive()}isStale(){return this.state.isInvalidated||!this.state.dataUpdatedAt||j(this,cn).some(t=>t.getCurrentResult().isStale)}isStaleByTime(t=0){return this.state.isInvalidated||!this.state.dataUpdatedAt||!OR(this.state.dataUpdatedAt,t)}onFocus(){var n;const t=j(this,cn).find(r=>r.shouldFetchOnWindowFocus());t==null||t.refetch({cancelRefetch:!1}),(n=j(this,Dr))==null||n.continue()}onOnline(){var n;const t=j(this,cn).find(r=>r.shouldFetchOnReconnect());t==null||t.refetch({cancelRefetch:!1}),(n=j(this,Dr))==null||n.continue()}addObserver(t){j(this,cn).includes(t)||(j(this,cn).push(t),this.clearGcTimeout(),j(this,Nr).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){j(this,cn).includes(t)&&(ye(this,cn,j(this,cn).filter(n=>n!==t)),j(this,cn).length||(j(this,Dr)&&(j(this,ya)?j(this,Dr).cancel({revert:!0}):j(this,Dr).cancelRetry()),this.scheduleGc()),j(this,Nr).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return j(this,cn).length}invalidate(){this.state.isInvalidated||tt(this,ao,di).call(this,{type:"invalidate"})}fetch(t,n){var f,p,m,g;if(this.state.fetchStatus!=="idle"){if(this.state.dataUpdatedAt&&(n!=null&&n.cancelRefetch))this.cancel({silent:!0});else if(j(this,is))return(f=j(this,Dr))==null||f.continueRetry(),j(this,is)}if(t&&tt(this,Bl,Bh).call(this,t),!this.options.queryFn){const y=j(this,cn).find(x=>x.options.queryFn);y&&tt(this,Bl,Bh).call(this,y.options)}const r=new AbortController,o={queryKey:this.queryKey,meta:this.meta},i=y=>{Object.defineProperty(y,"signal",{enumerable:!0,get:()=>(ye(this,ya,!0),r.signal)})};i(o);const s=()=>this.options.queryFn?(ye(this,ya,!1),this.options.persister?this.options.persister(this.options.queryFn,o,this):this.options.queryFn(o)):Promise.reject(new Error(`Missing queryFn: '${this.options.queryHash}'`)),l={fetchOptions:n,options:this.options,queryKey:this.queryKey,state:this.state,fetchFn:s};i(l),(p=this.options.behavior)==null||p.onFetch(l,this),ye(this,zl,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((m=l.fetchOptions)==null?void 0:m.meta))&&tt(this,ao,di).call(this,{type:"fetch",meta:(g=l.fetchOptions)==null?void 0:g.meta});const u=y=>{var x,S,E,_;d0(y)&&y.silent||tt(this,ao,di).call(this,{type:"error",error:y}),d0(y)||((S=(x=j(this,Nr).config).onError)==null||S.call(x,y,this),(_=(E=j(this,Nr).config).onSettled)==null||_.call(E,this.state.data,y,this)),this.isFetchingOptimistic||this.scheduleGc(),this.isFetchingOptimistic=!1};return ye(this,Dr,LR({fn:l.fetchFn,abort:r.abort.bind(r),onSuccess:y=>{var x,S,E,_;if(typeof y>"u"){u(new Error(`${this.queryHash} data is undefined`));return}this.setData(y),(S=(x=j(this,Nr).config).onSuccess)==null||S.call(x,y,this),(_=(E=j(this,Nr).config).onSettled)==null||_.call(E,y,this.state.error,this),this.isFetchingOptimistic||this.scheduleGc(),this.isFetchingOptimistic=!1},onError:u,onFail:(y,x)=>{tt(this,ao,di).call(this,{type:"failed",failureCount:y,error:x})},onPause:()=>{tt(this,ao,di).call(this,{type:"pause"})},onContinue:()=>{tt(this,ao,di).call(this,{type:"continue"})},retry:l.options.retry,retryDelay:l.options.retryDelay,networkMode:l.options.networkMode})),ye(this,is,j(this,Dr).promise),j(this,is)}},jl=new WeakMap,zl=new WeakMap,Nr=new WeakMap,is=new WeakMap,Dr=new WeakMap,cn=new WeakMap,vd=new WeakMap,ya=new WeakMap,Bl=new WeakSet,Bh=function(t){this.options={...j(this,vd),...t},this.updateGcTime(this.options.gcTime)},ao=new WeakSet,di=function(t){const n=r=>{switch(t.type){case"failed":return{...r,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...r,fetchStatus:"paused"};case"continue":return{...r,fetchStatus:"fetching"};case"fetch":return{...r,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:t.meta??null,fetchStatus:km(this.options.networkMode)?"fetching":"paused",...!r.dataUpdatedAt&&{error:null,status:"pending"}};case"success":return{...r,data:t.data,dataUpdateCount:r.dataUpdateCount+1,dataUpdatedAt:t.dataUpdatedAt??Date.now(),error:null,isInvalidated:!1,status:"success",...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};case"error":const o=t.error;return d0(o)&&o.revert&&j(this,zl)?{...j(this,zl),fetchStatus:"idle"}:{...r,error:o,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:o,fetchStatus:"idle",status:"error"};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...t.state}}};this.state=n(this.state),vn.batch(()=>{j(this,cn).forEach(r=>{r.onQueryUpdate()}),j(this,Nr).notify({query:this,type:"updated",action:t})})},p$);function aL(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=typeof t<"u",r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var Mo,m$,lL=(m$=class extends Od{constructor(t={}){super();Pe(this,Mo,void 0);this.config=t,ye(this,Mo,new Map)}build(t,n,r){const o=n.queryKey,i=n.queryHash??Zw(o,n);let s=this.get(i);return s||(s=new sL({cache:this,queryKey:o,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(o)}),this.add(s)),s}add(t){j(this,Mo).has(t.queryHash)||(j(this,Mo).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){const n=j(this,Mo).get(t.queryHash);n&&(t.destroy(),n===t&&j(this,Mo).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){vn.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return j(this,Mo).get(t)}getAll(){return[...j(this,Mo).values()]}find(t){const n={exact:!0,...t};return this.getAll().find(r=>ZE(n,r))}findAll(t={}){const n=this.getAll();return Object.keys(t).length>0?n.filter(r=>ZE(t,r)):n}notify(t){vn.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){vn.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){vn.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},Mo=new WeakMap,m$),Oo,yd,dr,Ul,No,qi,g$,cL=(g$=class extends FR{constructor(t){super();Pe(this,No);Pe(this,Oo,void 0);Pe(this,yd,void 0);Pe(this,dr,void 0);Pe(this,Ul,void 0);this.mutationId=t.mutationId,ye(this,yd,t.defaultOptions),ye(this,dr,t.mutationCache),ye(this,Oo,[]),this.state=t.state||uL(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options={...j(this,yd),...t},this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){j(this,Oo).includes(t)||(j(this,Oo).push(t),this.clearGcTimeout(),j(this,dr).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){ye(this,Oo,j(this,Oo).filter(n=>n!==t)),this.scheduleGc(),j(this,dr).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){j(this,Oo).length||(this.state.status==="pending"?this.scheduleGc():j(this,dr).remove(this))}continue(){var t;return((t=j(this,Ul))==null?void 0:t.continue())??this.execute(this.state.variables)}async execute(t){var o,i,s,l,u,f,p,m,g,y,x,S,E,_,b,C,R,P,O,A;const n=()=>(ye(this,Ul,LR({fn:()=>this.options.mutationFn?this.options.mutationFn(t):Promise.reject(new Error("No mutationFn found")),onFail:(D,B)=>{tt(this,No,qi).call(this,{type:"failed",failureCount:D,error:B})},onPause:()=>{tt(this,No,qi).call(this,{type:"pause"})},onContinue:()=>{tt(this,No,qi).call(this,{type:"continue"})},retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode})),j(this,Ul).promise),r=this.state.status==="pending";try{if(!r){tt(this,No,qi).call(this,{type:"pending",variables:t}),await((i=(o=j(this,dr).config).onMutate)==null?void 0:i.call(o,t,this));const B=await((l=(s=this.options).onMutate)==null?void 0:l.call(s,t));B!==this.state.context&&tt(this,No,qi).call(this,{type:"pending",context:B,variables:t})}const D=await n();return await((f=(u=j(this,dr).config).onSuccess)==null?void 0:f.call(u,D,t,this.state.context,this)),await((m=(p=this.options).onSuccess)==null?void 0:m.call(p,D,t,this.state.context)),await((y=(g=j(this,dr).config).onSettled)==null?void 0:y.call(g,D,null,this.state.variables,this.state.context,this)),await((S=(x=this.options).onSettled)==null?void 0:S.call(x,D,null,t,this.state.context)),tt(this,No,qi).call(this,{type:"success",data:D}),D}catch(D){try{throw await((_=(E=j(this,dr).config).onError)==null?void 0:_.call(E,D,t,this.state.context,this)),await((C=(b=this.options).onError)==null?void 0:C.call(b,D,t,this.state.context)),await((P=(R=j(this,dr).config).onSettled)==null?void 0:P.call(R,void 0,D,this.state.variables,this.state.context,this)),await((A=(O=this.options).onSettled)==null?void 0:A.call(O,void 0,D,t,this.state.context)),D}finally{tt(this,No,qi).call(this,{type:"error",error:D})}}}},Oo=new WeakMap,yd=new WeakMap,dr=new WeakMap,Ul=new WeakMap,No=new WeakSet,qi=function(t){const n=r=>{switch(t.type){case"failed":return{...r,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};case"pending":return{...r,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:!km(this.options.networkMode),status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...r,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:t.error,failureCount:r.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}};this.state=n(this.state),vn.batch(()=>{j(this,Oo).forEach(r=>{r.onMutationUpdate(t)}),j(this,dr).notify({mutation:this,type:"updated",action:t})})},g$);function uL(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Ir,wd,wa,v$,dL=(v$=class extends Od{constructor(t={}){super();Pe(this,Ir,void 0);Pe(this,wd,void 0);Pe(this,wa,void 0);this.config=t,ye(this,Ir,[]),ye(this,wd,0)}build(t,n,r){const o=new cL({mutationCache:this,mutationId:++Wf(this,wd)._,options:t.defaultMutationOptions(n),state:r});return this.add(o),o}add(t){j(this,Ir).push(t),this.notify({type:"added",mutation:t})}remove(t){ye(this,Ir,j(this,Ir).filter(n=>n!==t)),this.notify({type:"removed",mutation:t})}clear(){vn.batch(()=>{j(this,Ir).forEach(t=>{this.remove(t)})})}getAll(){return j(this,Ir)}find(t){const n={exact:!0,...t};return j(this,Ir).find(r=>qE(n,r))}findAll(t={}){return j(this,Ir).filter(n=>qE(t,n))}notify(t){vn.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){return ye(this,wa,(j(this,wa)??Promise.resolve()).then(()=>{const t=j(this,Ir).filter(n=>n.state.isPaused);return vn.batch(()=>t.reduce((n,r)=>n.then(()=>r.continue().catch(Lr)),Promise.resolve()))}).then(()=>{ye(this,wa,void 0)})),j(this,wa)}},Ir=new WeakMap,wd=new WeakMap,wa=new WeakMap,v$);function fL(e){return{onFetch:(t,n)=>{const r=async()=>{var x,S,E,_,b;const o=t.options,i=(E=(S=(x=t.fetchOptions)==null?void 0:x.meta)==null?void 0:S.fetchMore)==null?void 0:E.direction,s=((_=t.state.data)==null?void 0:_.pages)||[],l=((b=t.state.data)==null?void 0:b.pageParams)||[],u={pages:[],pageParams:[]};let f=!1;const p=C=>{Object.defineProperty(C,"signal",{enumerable:!0,get:()=>(t.signal.aborted?f=!0:t.signal.addEventListener("abort",()=>{f=!0}),t.signal)})},m=t.options.queryFn||(()=>Promise.reject(new Error(`Missing queryFn: '${t.options.queryHash}'`))),g=async(C,R,P)=>{if(f)return Promise.reject();if(R==null&&C.pages.length)return Promise.resolve(C);const O={queryKey:t.queryKey,pageParam:R,direction:P?"backward":"forward",meta:t.options.meta};p(O);const A=await m(O),{maxPages:D}=t.options,B=P?tL:eL;return{pages:B(C.pages,A,D),pageParams:B(C.pageParams,R,D)}};let y;if(i&&s.length){const C=i==="backward",R=C?hL:tC,P={pages:s,pageParams:l},O=R(o,P);y=await g(P,O,C)}else{y=await g(u,l[0]??o.initialPageParam);const C=e??s.length;for(let R=1;R{var o,i;return(i=(o=t.options).persister)==null?void 0:i.call(o,r,{queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n)}:t.fetchFn=r}}}function tC(e,{pages:t,pageParams:n}){const r=t.length-1;return e.getNextPageParam(t[r],t,n[r],n)}function hL(e,{pages:t,pageParams:n}){var r;return(r=e.getPreviousPageParam)==null?void 0:r.call(e,t[0],t,n[0],n)}var nn,ss,as,Vl,Wl,ls,Hl,Kl,y$,pL=(y$=class{constructor(e={}){Pe(this,nn,void 0);Pe(this,ss,void 0);Pe(this,as,void 0);Pe(this,Vl,void 0);Pe(this,Wl,void 0);Pe(this,ls,void 0);Pe(this,Hl,void 0);Pe(this,Kl,void 0);ye(this,nn,e.queryCache||new lL),ye(this,ss,e.mutationCache||new dL),ye(this,as,e.defaultOptions||{}),ye(this,Vl,new Map),ye(this,Wl,new Map),ye(this,ls,0)}mount(){Wf(this,ls)._++,j(this,ls)===1&&(ye(this,Hl,Ap.subscribe(()=>{Ap.isFocused()&&(this.resumePausedMutations(),j(this,nn).onFocus())})),ye(this,Kl,Mp.subscribe(()=>{Mp.isOnline()&&(this.resumePausedMutations(),j(this,nn).onOnline())})))}unmount(){var e,t;Wf(this,ls)._--,j(this,ls)===0&&((e=j(this,Hl))==null||e.call(this),ye(this,Hl,void 0),(t=j(this,Kl))==null||t.call(this),ye(this,Kl,void 0))}isFetching(e){return j(this,nn).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return j(this,ss).findAll({...e,status:"pending"}).length}getQueryData(e){var t;return(t=j(this,nn).find({queryKey:e}))==null?void 0:t.state.data}ensureQueryData(e){const t=this.getQueryData(e.queryKey);return t!==void 0?Promise.resolve(t):this.fetchQuery(e)}getQueriesData(e){return this.getQueryCache().findAll(e).map(({queryKey:t,state:n})=>{const r=n.data;return[t,r]})}setQueryData(e,t,n){const r=j(this,nn).find({queryKey:e}),o=r==null?void 0:r.state.data,i=JI(t,o);if(typeof i>"u")return;const s=this.defaultQueryOptions({queryKey:e});return j(this,nn).build(this,s).setData(i,{...n,manual:!0})}setQueriesData(e,t,n){return vn.batch(()=>this.getQueryCache().findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){var t;return(t=j(this,nn).find({queryKey:e}))==null?void 0:t.state}removeQueries(e){const t=j(this,nn);vn.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=j(this,nn),r={type:"active",...e};return vn.batch(()=>(n.findAll(e).forEach(o=>{o.reset()}),this.refetchQueries(r,t)))}cancelQueries(e={},t={}){const n={revert:!0,...t},r=vn.batch(()=>j(this,nn).findAll(e).map(o=>o.cancel(n)));return Promise.all(r).then(Lr).catch(Lr)}invalidateQueries(e={},t={}){return vn.batch(()=>{if(j(this,nn).findAll(e).forEach(r=>{r.invalidate()}),e.refetchType==="none")return Promise.resolve();const n={...e,type:e.refetchType??e.type??"active"};return this.refetchQueries(n,t)})}refetchQueries(e={},t){const n={...t,cancelRefetch:(t==null?void 0:t.cancelRefetch)??!0},r=vn.batch(()=>j(this,nn).findAll(e).filter(o=>!o.isDisabled()).map(o=>{let i=o.fetch(void 0,n);return n.throwOnError||(i=i.catch(Lr)),o.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(Lr)}fetchQuery(e){const t=this.defaultQueryOptions(e);typeof t.retry>"u"&&(t.retry=!1);const n=j(this,nn).build(this,t);return n.isStaleByTime(t.staleTime)?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Lr).catch(Lr)}fetchInfiniteQuery(e){return e.behavior=fL(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Lr).catch(Lr)}resumePausedMutations(){return j(this,ss).resumePausedMutations()}getQueryCache(){return j(this,nn)}getMutationCache(){return j(this,ss)}getDefaultOptions(){return j(this,as)}setDefaultOptions(e){ye(this,as,e)}setQueryDefaults(e,t){j(this,Vl).set(td(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...j(this,Vl).values()];let n={};return t.forEach(r=>{nd(e,r.queryKey)&&(n={...n,...r.defaultOptions})}),n}setMutationDefaults(e,t){j(this,Wl).set(td(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...j(this,Wl).values()];let n={};return t.forEach(r=>{nd(e,r.mutationKey)&&(n={...n,...r.defaultOptions})}),n}defaultQueryOptions(e){if(e!=null&&e._defaulted)return e;const t={...j(this,as).queries,...(e==null?void 0:e.queryKey)&&this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Zw(t.queryKey,t)),typeof t.refetchOnReconnect>"u"&&(t.refetchOnReconnect=t.networkMode!=="always"),typeof t.throwOnError>"u"&&(t.throwOnError=!!t.suspense),typeof t.networkMode>"u"&&t.persister&&(t.networkMode="offlineFirst"),t}defaultMutationOptions(e){return e!=null&&e._defaulted?e:{...j(this,as).mutations,...(e==null?void 0:e.mutationKey)&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){j(this,nn).clear(),j(this,ss).clear()}},nn=new WeakMap,ss=new WeakMap,as=new WeakMap,Vl=new WeakMap,Wl=new WeakMap,ls=new WeakMap,Hl=new WeakMap,Kl=new WeakMap,y$),Xn,Ct,Gl,kn,xa,Yl,Do,xd,Xl,Zl,ba,Sa,cs,_a,Ea,bu,bd,By,Sd,Uy,_d,Vy,Ed,Wy,Cd,Hy,$d,Ky,Rd,Gy,um,jR,w$,mL=(w$=class extends Od{constructor(t,n){super();Pe(this,Ea);Pe(this,bd);Pe(this,Sd);Pe(this,_d);Pe(this,Ed);Pe(this,Cd);Pe(this,$d);Pe(this,Rd);Pe(this,um);Pe(this,Xn,void 0);Pe(this,Ct,void 0);Pe(this,Gl,void 0);Pe(this,kn,void 0);Pe(this,xa,void 0);Pe(this,Yl,void 0);Pe(this,Do,void 0);Pe(this,xd,void 0);Pe(this,Xl,void 0);Pe(this,Zl,void 0);Pe(this,ba,void 0);Pe(this,Sa,void 0);Pe(this,cs,void 0);Pe(this,_a,void 0);ye(this,Ct,void 0),ye(this,Gl,void 0),ye(this,kn,void 0),ye(this,_a,new Set),ye(this,Xn,t),this.options=n,ye(this,Do,null),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(j(this,Ct).addObserver(this),nC(j(this,Ct),this.options)?tt(this,Ea,bu).call(this):this.updateResult(),tt(this,Ed,Wy).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Yy(j(this,Ct),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Yy(j(this,Ct),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,tt(this,Cd,Hy).call(this),tt(this,$d,Ky).call(this),j(this,Ct).removeObserver(this)}setOptions(t,n){const r=this.options,o=j(this,Ct);if(this.options=j(this,Xn).defaultQueryOptions(t),Fy(r,this.options)||j(this,Xn).getQueryCache().notify({type:"observerOptionsUpdated",query:j(this,Ct),observer:this}),typeof this.options.enabled<"u"&&typeof this.options.enabled!="boolean")throw new Error("Expected enabled to be a boolean");this.options.queryKey||(this.options.queryKey=r.queryKey),tt(this,Rd,Gy).call(this);const i=this.hasListeners();i&&rC(j(this,Ct),o,this.options,r)&&tt(this,Ea,bu).call(this),this.updateResult(n),i&&(j(this,Ct)!==o||this.options.enabled!==r.enabled||this.options.staleTime!==r.staleTime)&&tt(this,bd,By).call(this);const s=tt(this,Sd,Uy).call(this);i&&(j(this,Ct)!==o||this.options.enabled!==r.enabled||s!==j(this,cs))&&tt(this,_d,Vy).call(this,s)}getOptimisticResult(t){const n=j(this,Xn).getQueryCache().build(j(this,Xn),t),r=this.createResult(n,t);return vL(this,r)&&(ye(this,kn,r),ye(this,Yl,this.options),ye(this,xa,j(this,Ct).state)),r}getCurrentResult(){return j(this,kn)}trackResult(t){const n={};return Object.keys(t).forEach(r=>{Object.defineProperty(n,r,{configurable:!1,enumerable:!0,get:()=>(j(this,_a).add(r),t[r])})}),n}getCurrentQuery(){return j(this,Ct)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){const n=j(this,Xn).defaultQueryOptions(t),r=j(this,Xn).getQueryCache().build(j(this,Xn),n);return r.isFetchingOptimistic=!0,r.fetch().then(()=>this.createResult(r,n))}fetch(t){return tt(this,Ea,bu).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),j(this,kn)))}createResult(t,n){var O;const r=j(this,Ct),o=this.options,i=j(this,kn),s=j(this,xa),l=j(this,Yl),f=t!==r?t.state:j(this,Gl),{state:p}=t;let{error:m,errorUpdatedAt:g,fetchStatus:y,status:x}=p,S=!1,E;if(n._optimisticResults){const A=this.hasListeners(),D=!A&&nC(t,n),B=A&&rC(t,r,n,o);(D||B)&&(y=km(t.options.networkMode)?"fetching":"paused",p.dataUpdatedAt||(x="pending")),n._optimisticResults==="isRestoring"&&(y="idle")}if(n.select&&typeof p.data<"u")if(i&&p.data===(s==null?void 0:s.data)&&n.select===j(this,xd))E=j(this,Xl);else try{ye(this,xd,n.select),E=n.select(p.data),E=zy(i==null?void 0:i.data,E,n),ye(this,Xl,E),ye(this,Do,null)}catch(A){ye(this,Do,A)}else E=p.data;if(typeof n.placeholderData<"u"&&typeof E>"u"&&x==="pending"){let A;if(i!=null&&i.isPlaceholderData&&n.placeholderData===(l==null?void 0:l.placeholderData))A=i.data;else if(A=typeof n.placeholderData=="function"?n.placeholderData((O=j(this,Zl))==null?void 0:O.state.data,j(this,Zl)):n.placeholderData,n.select&&typeof A<"u")try{A=n.select(A),ye(this,Do,null)}catch(D){ye(this,Do,D)}typeof A<"u"&&(x="success",E=zy(i==null?void 0:i.data,A,n),S=!0)}j(this,Do)&&(m=j(this,Do),E=j(this,Xl),g=Date.now(),x="error");const _=y==="fetching",b=x==="pending",C=x==="error",R=b&&_;return{status:x,fetchStatus:y,isPending:b,isSuccess:x==="success",isError:C,isInitialLoading:R,isLoading:R,data:E,dataUpdatedAt:p.dataUpdatedAt,error:m,errorUpdatedAt:g,failureCount:p.fetchFailureCount,failureReason:p.fetchFailureReason,errorUpdateCount:p.errorUpdateCount,isFetched:p.dataUpdateCount>0||p.errorUpdateCount>0,isFetchedAfterMount:p.dataUpdateCount>f.dataUpdateCount||p.errorUpdateCount>f.errorUpdateCount,isFetching:_,isRefetching:_&&!b,isLoadingError:C&&p.dataUpdatedAt===0,isPaused:y==="paused",isPlaceholderData:S,isRefetchError:C&&p.dataUpdatedAt!==0,isStale:qw(t,n),refetch:this.refetch}}updateResult(t){const n=j(this,kn),r=this.createResult(j(this,Ct),this.options);if(ye(this,xa,j(this,Ct).state),ye(this,Yl,this.options),j(this,xa).data!==void 0&&ye(this,Zl,j(this,Ct)),Fy(r,n))return;ye(this,kn,r);const o={},i=()=>{if(!n)return!0;const{notifyOnChangeProps:s}=this.options,l=typeof s=="function"?s():s;if(l==="all"||!l&&!j(this,_a).size)return!0;const u=new Set(l??j(this,_a));return this.options.throwOnError&&u.add("error"),Object.keys(j(this,kn)).some(f=>{const p=f;return j(this,kn)[p]!==n[p]&&u.has(p)})};(t==null?void 0:t.listeners)!==!1&&i()&&(o.listeners=!0),tt(this,um,jR).call(this,{...o,...t})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&tt(this,Ed,Wy).call(this)}},Xn=new WeakMap,Ct=new WeakMap,Gl=new WeakMap,kn=new WeakMap,xa=new WeakMap,Yl=new WeakMap,Do=new WeakMap,xd=new WeakMap,Xl=new WeakMap,Zl=new WeakMap,ba=new WeakMap,Sa=new WeakMap,cs=new WeakMap,_a=new WeakMap,Ea=new WeakSet,bu=function(t){tt(this,Rd,Gy).call(this);let n=j(this,Ct).fetch(this.options,t);return t!=null&&t.throwOnError||(n=n.catch(Lr)),n},bd=new WeakSet,By=function(){if(tt(this,Cd,Hy).call(this),oc||j(this,kn).isStale||!Ly(this.options.staleTime))return;const n=OR(j(this,kn).dataUpdatedAt,this.options.staleTime)+1;ye(this,ba,setTimeout(()=>{j(this,kn).isStale||this.updateResult()},n))},Sd=new WeakSet,Uy=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(j(this,Ct)):this.options.refetchInterval)??!1},_d=new WeakSet,Vy=function(t){tt(this,$d,Ky).call(this),ye(this,cs,t),!(oc||this.options.enabled===!1||!Ly(j(this,cs))||j(this,cs)===0)&&ye(this,Sa,setInterval(()=>{(this.options.refetchIntervalInBackground||Ap.isFocused())&&tt(this,Ea,bu).call(this)},j(this,cs)))},Ed=new WeakSet,Wy=function(){tt(this,bd,By).call(this),tt(this,_d,Vy).call(this,tt(this,Sd,Uy).call(this))},Cd=new WeakSet,Hy=function(){j(this,ba)&&(clearTimeout(j(this,ba)),ye(this,ba,void 0))},$d=new WeakSet,Ky=function(){j(this,Sa)&&(clearInterval(j(this,Sa)),ye(this,Sa,void 0))},Rd=new WeakSet,Gy=function(){const t=j(this,Xn).getQueryCache().build(j(this,Xn),this.options);if(t===j(this,Ct))return;const n=j(this,Ct);ye(this,Ct,t),ye(this,Gl,t.state),this.hasListeners()&&(n==null||n.removeObserver(this),t.addObserver(this))},um=new WeakSet,jR=function(t){vn.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(j(this,kn))}),j(this,Xn).getQueryCache().notify({query:j(this,Ct),type:"observerResultsUpdated"})})},w$);function gL(e,t){return t.enabled!==!1&&!e.state.dataUpdatedAt&&!(e.state.status==="error"&&t.retryOnMount===!1)}function nC(e,t){return gL(e,t)||e.state.dataUpdatedAt>0&&Yy(e,t,t.refetchOnMount)}function Yy(e,t,n){if(t.enabled!==!1){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&qw(e,t)}return!1}function rC(e,t,n,r){return n.enabled!==!1&&(e!==t||r.enabled===!1)&&(!n.suspense||e.state.status!=="error")&&qw(e,n)}function qw(e,t){return e.isStaleByTime(t.staleTime)}function vL(e,t){return!Fy(e.getCurrentResult(),t)}var zR=d.createContext(void 0),yL=e=>{const t=d.useContext(zR);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},wL=({client:e,children:t})=>(d.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),d.createElement(zR.Provider,{value:e},t)),BR=d.createContext(!1),xL=()=>d.useContext(BR);BR.Provider;function bL(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var SL=d.createContext(bL()),_L=()=>d.useContext(SL);function EL(e,t){return typeof e=="function"?e(...t):!!e}var CL=(e,t)=>{(e.suspense||e.throwOnError)&&(t.isReset()||(e.retryOnMount=!1))},$L=e=>{d.useEffect(()=>{e.clearReset()},[e])},RL=({result:e,errorResetBoundary:t,throwOnError:n,query:r})=>e.isError&&!t.isReset()&&!e.isFetching&&EL(n,[e.error,r]),kL=e=>{e.suspense&&typeof e.staleTime!="number"&&(e.staleTime=1e3)},TL=(e,t)=>(e==null?void 0:e.suspense)&&t.isPending,PL=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function AL(e,t,n){const r=yL(n),o=xL(),i=_L(),s=r.defaultQueryOptions(e);s._optimisticResults=o?"isRestoring":"optimistic",kL(s),CL(s,i),$L(i);const[l]=d.useState(()=>new t(r,s)),u=l.getOptimisticResult(s);if(d.useSyncExternalStore(d.useCallback(f=>{const p=o?()=>{}:l.subscribe(vn.batchCalls(f));return l.updateResult(),p},[l,o]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),d.useEffect(()=>{l.setOptions(s,{listeners:!1})},[s,l]),TL(s,u))throw l.setOptions(s,{listeners:!1}),PL(s,l,i);if(RL({result:u,errorResetBoundary:i,throwOnError:s.throwOnError,query:l.getCurrentQuery()}))throw u.error;return s.notifyOnChangeProps?u:l.trackResult(u)}function ML(e,t){return AL(e,mL,t)}var Ao=(e=>(e.RemoveBG="RemoveBG",e.AnimeSeg="AnimeSeg",e.RealESRGAN="RealESRGAN",e.GFPGAN="GFPGAN",e.RestoreFormer="RestoreFormer",e.InteractiveSeg="InteractiveSeg",e))(Ao||{}),Es=(e=>(e.NAME="name",e.CTIME="ctime",e.MTIME="mtime",e))(Es||{}),Ou=(e=>(e.DESCENDING="desc",e.ASCENDING="asc",e))(Ou||{}),Qw=(e=>(e.ddim="ddim",e.plms="plms",e))(Qw||{}),Jw=(e=>(e.INPAINT_NS="INPAINT_NS",e.INPAINT_TELEA="INPAINT_TELEA",e))(Jw||{}),Ln=(e=>(e.x="x",e.y="y",e.xy="xy",e))(Ln||{}),Ol=(e=>(e.text_guided="text-guided",e.shape_guided="shape-guided",e.object_remove="object-remove",e.outpainting="outpainting",e))(Ol||{});function UR(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;tl(i)))==null?void 0:s.classGroupId}const oC=/^\[(.+)\]$/;function NL(e){if(oC.test(e)){const t=oC.exec(e)[1],n=t==null?void 0:t.substring(0,t.indexOf(":"));if(n)return"arbitrary.."+n}}function DL(e){const{theme:t,prefix:n}=e,r={nextPart:new Map,validators:[]};return LL(Object.entries(e.classGroups),n).forEach(([i,s])=>{Xy(s,r,i,t)}),r}function Xy(e,t,n,r){e.forEach(o=>{if(typeof o=="string"){const i=o===""?t:iC(t,o);i.classGroupId=n;return}if(typeof o=="function"){if(IL(o)){Xy(o(r),t,n,r);return}t.validators.push({validator:o,classGroupId:n});return}Object.entries(o).forEach(([i,s])=>{Xy(s,iC(t,i),n,r)})})}function iC(e,t){let n=e;return t.split(ex).forEach(r=>{n.nextPart.has(r)||n.nextPart.set(r,{nextPart:new Map,validators:[]}),n=n.nextPart.get(r)}),n}function IL(e){return e.isThemeGetter}function LL(e,t){return t?e.map(([n,r])=>{const o=r.map(i=>typeof i=="string"?t+i:typeof i=="object"?Object.fromEntries(Object.entries(i).map(([s,l])=>[t+s,l])):i);return[n,o]}):e}function FL(e){if(e<1)return{get:()=>{},set:()=>{}};let t=0,n=new Map,r=new Map;function o(i,s){n.set(i,s),t++,t>e&&(t=0,r=n,n=new Map)}return{get(i){let s=n.get(i);if(s!==void 0)return s;if((s=r.get(i))!==void 0)return o(i,s),s},set(i,s){n.has(i)?n.set(i,s):o(i,s)}}}const HR="!";function jL(e){const t=e.separator,n=t.length===1,r=t[0],o=t.length;return function(s){const l=[];let u=0,f=0,p;for(let S=0;Sf?p-f:void 0;return{modifiers:l,hasImportantModifier:g,baseClassName:y,maybePostfixModifierPosition:x}}}function zL(e){if(e.length<=1)return e;const t=[];let n=[];return e.forEach(r=>{r[0]==="["?(t.push(...n.sort(),r),n=[]):n.push(r)}),t.push(...n.sort()),t}function BL(e){return{cache:FL(e.cacheSize),splitModifiers:jL(e),...OL(e)}}const UL=/\s+/;function VL(e,t){const{splitModifiers:n,getClassGroupId:r,getConflictingClassGroupIds:o}=t,i=new Set;return e.trim().split(UL).map(s=>{const{modifiers:l,hasImportantModifier:u,baseClassName:f,maybePostfixModifierPosition:p}=n(s);let m=r(p?f.substring(0,p):f),g=!!p;if(!m){if(!p)return{isTailwindClass:!1,originalClassName:s};if(m=r(f),!m)return{isTailwindClass:!1,originalClassName:s};g=!1}const y=zL(l).join(":");return{isTailwindClass:!0,modifierId:u?y+HR:y,classGroupId:m,originalClassName:s,hasPostfixModifier:g}}).reverse().filter(s=>{if(!s.isTailwindClass)return!0;const{modifierId:l,classGroupId:u,hasPostfixModifier:f}=s,p=l+u;return i.has(p)?!1:(i.add(p),o(u,f).forEach(m=>i.add(l+m)),!0)}).reverse().map(s=>s.originalClassName).join(" ")}function WL(){let e=0,t,n,r="";for(;em(p),e());return n=BL(f),r=n.cache.get,o=n.cache.set,i=l,l(u)}function l(u){const f=r(u);if(f)return f;const p=VL(u,n);return o(u,p),p}return function(){return i(WL.apply(null,arguments))}}function kt(e){const t=n=>n[e]||[];return t.isThemeGetter=!0,t}const GR=/^\[(?:([a-z-]+):)?(.+)\]$/i,KL=/^\d+\/\d+$/,GL=new Set(["px","full","screen"]),YL=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,XL=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,ZL=/^-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,qL=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/;function oo(e){return ha(e)||GL.has(e)||KL.test(e)}function Gi(e){return bc(e,"length",iF)}function ha(e){return!!e&&!Number.isNaN(Number(e))}function lh(e){return bc(e,"number",ha)}function lu(e){return!!e&&Number.isInteger(Number(e))}function QL(e){return e.endsWith("%")&&ha(e.slice(0,-1))}function Je(e){return GR.test(e)}function Yi(e){return YL.test(e)}const JL=new Set(["length","size","percentage"]);function eF(e){return bc(e,JL,YR)}function tF(e){return bc(e,"position",YR)}const nF=new Set(["image","url"]);function rF(e){return bc(e,nF,aF)}function oF(e){return bc(e,"",sF)}function cu(){return!0}function bc(e,t,n){const r=GR.exec(e);return r?r[1]?typeof t=="string"?r[1]===t:t.has(r[1]):n(r[2]):!1}function iF(e){return XL.test(e)}function YR(){return!1}function sF(e){return ZL.test(e)}function aF(e){return qL.test(e)}function lF(){const e=kt("colors"),t=kt("spacing"),n=kt("blur"),r=kt("brightness"),o=kt("borderColor"),i=kt("borderRadius"),s=kt("borderSpacing"),l=kt("borderWidth"),u=kt("contrast"),f=kt("grayscale"),p=kt("hueRotate"),m=kt("invert"),g=kt("gap"),y=kt("gradientColorStops"),x=kt("gradientColorStopPositions"),S=kt("inset"),E=kt("margin"),_=kt("opacity"),b=kt("padding"),C=kt("saturate"),R=kt("scale"),P=kt("sepia"),O=kt("skew"),A=kt("space"),D=kt("translate"),B=()=>["auto","contain","none"],V=()=>["auto","hidden","clip","visible","scroll"],J=()=>["auto",Je,t],G=()=>[Je,t],se=()=>["",oo,Gi],U=()=>["auto",ha,Je],ne=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],M=()=>["solid","dashed","dotted","double","none"],ee=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity","plus-lighter"],H=()=>["start","end","center","between","around","evenly","stretch"],X=()=>["","0",Je],W=()=>["auto","avoid","all","avoid-page","page","left","right","column"],le=()=>[ha,lh],pe=()=>[ha,Je];return{cacheSize:500,separator:":",theme:{colors:[cu],spacing:[oo,Gi],blur:["none","",Yi,Je],brightness:le(),borderColor:[e],borderRadius:["none","","full",Yi,Je],borderSpacing:G(),borderWidth:se(),contrast:le(),grayscale:X(),hueRotate:pe(),invert:X(),gap:G(),gradientColorStops:[e],gradientColorStopPositions:[QL,Gi],inset:J(),margin:J(),opacity:le(),padding:G(),saturate:le(),scale:le(),sepia:X(),skew:pe(),space:G(),translate:G()},classGroups:{aspect:[{aspect:["auto","square","video",Je]}],container:["container"],columns:[{columns:[Yi]}],"break-after":[{"break-after":W()}],"break-before":[{"break-before":W()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],float:[{float:["right","left","none"]}],clear:[{clear:["left","right","both","none"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:[...ne(),Je]}],overflow:[{overflow:V()}],"overflow-x":[{"overflow-x":V()}],"overflow-y":[{"overflow-y":V()}],overscroll:[{overscroll:B()}],"overscroll-x":[{"overscroll-x":B()}],"overscroll-y":[{"overscroll-y":B()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[S]}],"inset-x":[{"inset-x":[S]}],"inset-y":[{"inset-y":[S]}],start:[{start:[S]}],end:[{end:[S]}],top:[{top:[S]}],right:[{right:[S]}],bottom:[{bottom:[S]}],left:[{left:[S]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",lu,Je]}],basis:[{basis:J()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",Je]}],grow:[{grow:X()}],shrink:[{shrink:X()}],order:[{order:["first","last","none",lu,Je]}],"grid-cols":[{"grid-cols":[cu]}],"col-start-end":[{col:["auto",{span:["full",lu,Je]},Je]}],"col-start":[{"col-start":U()}],"col-end":[{"col-end":U()}],"grid-rows":[{"grid-rows":[cu]}],"row-start-end":[{row:["auto",{span:[lu,Je]},Je]}],"row-start":[{"row-start":U()}],"row-end":[{"row-end":U()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",Je]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",Je]}],gap:[{gap:[g]}],"gap-x":[{"gap-x":[g]}],"gap-y":[{"gap-y":[g]}],"justify-content":[{justify:["normal",...H()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...H(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...H(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[b]}],px:[{px:[b]}],py:[{py:[b]}],ps:[{ps:[b]}],pe:[{pe:[b]}],pt:[{pt:[b]}],pr:[{pr:[b]}],pb:[{pb:[b]}],pl:[{pl:[b]}],m:[{m:[E]}],mx:[{mx:[E]}],my:[{my:[E]}],ms:[{ms:[E]}],me:[{me:[E]}],mt:[{mt:[E]}],mr:[{mr:[E]}],mb:[{mb:[E]}],ml:[{ml:[E]}],"space-x":[{"space-x":[A]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[A]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit",Je,t]}],"min-w":[{"min-w":["min","max","fit",Je,oo]}],"max-w":[{"max-w":["0","none","full","min","max","fit","prose",{screen:[Yi]},Yi,Je]}],h:[{h:[Je,t,"auto","min","max","fit"]}],"min-h":[{"min-h":["min","max","fit",oo,Je]}],"max-h":[{"max-h":[Je,t,"min","max","fit"]}],"font-size":[{text:["base",Yi,Gi]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",lh]}],"font-family":[{font:[cu]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractons"],tracking:[{tracking:["tighter","tight","normal","wide","wider","widest",Je]}],"line-clamp":[{"line-clamp":["none",ha,lh]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",oo,Je]}],"list-image":[{"list-image":["none",Je]}],"list-style-type":[{list:["none","disc","decimal",Je]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[e]}],"placeholder-opacity":[{"placeholder-opacity":[_]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[e]}],"text-opacity":[{"text-opacity":[_]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...M(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",oo,Gi]}],"underline-offset":[{"underline-offset":["auto",oo,Je]}],"text-decoration-color":[{decoration:[e]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],indent:[{indent:G()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Je]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",Je]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[_]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...ne(),tF]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",eF]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},rF]}],"bg-color":[{bg:[e]}],"gradient-from-pos":[{from:[x]}],"gradient-via-pos":[{via:[x]}],"gradient-to-pos":[{to:[x]}],"gradient-from":[{from:[y]}],"gradient-via":[{via:[y]}],"gradient-to":[{to:[y]}],rounded:[{rounded:[i]}],"rounded-s":[{"rounded-s":[i]}],"rounded-e":[{"rounded-e":[i]}],"rounded-t":[{"rounded-t":[i]}],"rounded-r":[{"rounded-r":[i]}],"rounded-b":[{"rounded-b":[i]}],"rounded-l":[{"rounded-l":[i]}],"rounded-ss":[{"rounded-ss":[i]}],"rounded-se":[{"rounded-se":[i]}],"rounded-ee":[{"rounded-ee":[i]}],"rounded-es":[{"rounded-es":[i]}],"rounded-tl":[{"rounded-tl":[i]}],"rounded-tr":[{"rounded-tr":[i]}],"rounded-br":[{"rounded-br":[i]}],"rounded-bl":[{"rounded-bl":[i]}],"border-w":[{border:[l]}],"border-w-x":[{"border-x":[l]}],"border-w-y":[{"border-y":[l]}],"border-w-s":[{"border-s":[l]}],"border-w-e":[{"border-e":[l]}],"border-w-t":[{"border-t":[l]}],"border-w-r":[{"border-r":[l]}],"border-w-b":[{"border-b":[l]}],"border-w-l":[{"border-l":[l]}],"border-opacity":[{"border-opacity":[_]}],"border-style":[{border:[...M(),"hidden"]}],"divide-x":[{"divide-x":[l]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[l]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[_]}],"divide-style":[{divide:M()}],"border-color":[{border:[o]}],"border-color-x":[{"border-x":[o]}],"border-color-y":[{"border-y":[o]}],"border-color-t":[{"border-t":[o]}],"border-color-r":[{"border-r":[o]}],"border-color-b":[{"border-b":[o]}],"border-color-l":[{"border-l":[o]}],"divide-color":[{divide:[o]}],"outline-style":[{outline:["",...M()]}],"outline-offset":[{"outline-offset":[oo,Je]}],"outline-w":[{outline:[oo,Gi]}],"outline-color":[{outline:[e]}],"ring-w":[{ring:se()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[e]}],"ring-opacity":[{"ring-opacity":[_]}],"ring-offset-w":[{"ring-offset":[oo,Gi]}],"ring-offset-color":[{"ring-offset":[e]}],shadow:[{shadow:["","inner","none",Yi,oF]}],"shadow-color":[{shadow:[cu]}],opacity:[{opacity:[_]}],"mix-blend":[{"mix-blend":ee()}],"bg-blend":[{"bg-blend":ee()}],filter:[{filter:["","none"]}],blur:[{blur:[n]}],brightness:[{brightness:[r]}],contrast:[{contrast:[u]}],"drop-shadow":[{"drop-shadow":["","none",Yi,Je]}],grayscale:[{grayscale:[f]}],"hue-rotate":[{"hue-rotate":[p]}],invert:[{invert:[m]}],saturate:[{saturate:[C]}],sepia:[{sepia:[P]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[n]}],"backdrop-brightness":[{"backdrop-brightness":[r]}],"backdrop-contrast":[{"backdrop-contrast":[u]}],"backdrop-grayscale":[{"backdrop-grayscale":[f]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[p]}],"backdrop-invert":[{"backdrop-invert":[m]}],"backdrop-opacity":[{"backdrop-opacity":[_]}],"backdrop-saturate":[{"backdrop-saturate":[C]}],"backdrop-sepia":[{"backdrop-sepia":[P]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":[s]}],"border-spacing-x":[{"border-spacing-x":[s]}],"border-spacing-y":[{"border-spacing-y":[s]}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["none","all","","colors","opacity","shadow","transform",Je]}],duration:[{duration:pe()}],ease:[{ease:["linear","in","out","in-out",Je]}],delay:[{delay:pe()}],animate:[{animate:["none","spin","ping","pulse","bounce",Je]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[R]}],"scale-x":[{"scale-x":[R]}],"scale-y":[{"scale-y":[R]}],rotate:[{rotate:[lu,Je]}],"translate-x":[{"translate-x":[D]}],"translate-y":[{"translate-y":[D]}],"skew-x":[{"skew-x":[O]}],"skew-y":[{"skew-y":[O]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",Je]}],accent:[{accent:["auto",e]}],appearance:["appearance-none"],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",Je]}],"caret-color":[{caret:[e]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":G()}],"scroll-mx":[{"scroll-mx":G()}],"scroll-my":[{"scroll-my":G()}],"scroll-ms":[{"scroll-ms":G()}],"scroll-me":[{"scroll-me":G()}],"scroll-mt":[{"scroll-mt":G()}],"scroll-mr":[{"scroll-mr":G()}],"scroll-mb":[{"scroll-mb":G()}],"scroll-ml":[{"scroll-ml":G()}],"scroll-p":[{"scroll-p":G()}],"scroll-px":[{"scroll-px":G()}],"scroll-py":[{"scroll-py":G()}],"scroll-ps":[{"scroll-ps":G()}],"scroll-pe":[{"scroll-pe":G()}],"scroll-pt":[{"scroll-pt":G()}],"scroll-pr":[{"scroll-pr":G()}],"scroll-pb":[{"scroll-pb":G()}],"scroll-pl":[{"scroll-pl":G()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",Je]}],fill:[{fill:[e,"none"]}],"stroke-w":[{stroke:[oo,Gi,lh]}],stroke:[{stroke:[e,"none"]}],sr:["sr-only","not-sr-only"]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]}}}const tx=HL(lF),cF=40,fs="inpaint",ch="diffusers_sd",sC="diffusers_sdxl",uh="diffusers_sd_inpaint",aC="diffusers_sdxl_inpaint",f0="diffusers_other",Uh="#ffcc00bb",lC="ldm",cC="cv2",XR="Fantasy-Studio/Paint-by-Example",uF="timbrooks/instruct-pix2pix",dF="Sanster/PowerPaint-V1-stable-diffusion-inpainting",fF="Sanster/AnyText",hF="out of frame, lowres, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, disfigured, gross proportions, malformed limbs, watermark, signature";function _e(...e){return tx(VR(e))}function pF(){async function e(r=""){return(await fetch(r,{method:"GET",cache:"no-cache"})).json()}const t=()=>{const r=document.location;e(r+"/flaskwebgui-keep-server-alive").then(i=>i)},n=3*1e3;t(),setInterval(t,n)}function uC(e){const t=e.split(",")[0].split(":")[1].split(";")[0],n=atob(e.split(",")[1]),r=[];for(let o=0;o{const o=e.src,i=e;i.onload=n,i.onerror=s=>{i.src=o,r(s)},i.src=t})}async function mF(e){const t=URL.createObjectURL(e),n=new Image;return await Vh(n,t),n}function dC(e){return new Promise((t,n)=>{const r=new Image;r.addEventListener("load",()=>{t(r)}),r.addEventListener("error",o=>{n(o)}),r.src=e.toDataURL()})}function gF(e){return new Promise((t,n)=>{const r=new FileReader;r.onload=()=>{const o=new Image;o.onload=()=>{t(o)},o.onerror=()=>{n("无法加载图像。")},o.src=r.result},r.onerror=()=>{n("无法读取文件。")},r.readAsDataURL(e)})}function Nu(e,t,n){return fetch(e).then(function(r){return r.arrayBuffer()}).then(function(r){return new File([r],t,{type:n})})}async function vF(){try{const{state:e}=await navigator.permissions.query({name:"clipboard-write"});return e==="granted"}catch{return!1}}function yF(e,t){return new Promise((n,r)=>e.toBlob(async o=>{o?n(o):r(new Error("Expected toBlob() to be defined"))},t))}const wF=async e=>{const t=[new ClipboardItem({[e.type]:e})];await navigator.clipboard.write(t)};function fC(e){return e.nativeEvent.button===2}function hC(e){return e.nativeEvent.button===1}async function xF(e){const t=await yF(e,"image/png");try{await wF(t)}catch{console.log("Copy image failed!")}}function bF(e,t){const n=document.createElement("a");n.href=e,n.download=t,n.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0,view:window})),setTimeout(()=>{n.remove()},100)}function h0(e){const t=e.nativeEvent;return{x:t.offsetX,y:t.offsetY}}function ZR(e,t,n=Uh){e.strokeStyle=n,e.lineCap="round",e.lineJoin="round",t.forEach(r=>{!(r!=null&&r.pts.length)||!r.size||(e.lineWidth=r.size,e.beginPath(),e.moveTo(r.pts[0].x,r.pts[0].y),r.pts.forEach(o=>e.lineTo(o.x,o.y)),e.stroke())})}const Wh=(e,t,n,r=[],o="white")=>{const i=document.createElement("canvas");i.width=e,i.height=t;const s=i.getContext("2d");if(!s)throw new Error("could not retrieve mask canvas");return r.forEach(l=>{s.drawImage(l,0,0,e,t)}),n.forEach(l=>{ZR(s,l,o)}),i},Du=e=>new Promise((t,n)=>{const r=new FileReader;r.onload=o=>{var s;const i=(s=o.target)==null?void 0:s.result;t(i)},r.onerror=o=>{n(o)},r.readAsDataURL(e)});function qR(e,t){return function(){return e.apply(t,arguments)}}const{toString:SF}=Object.prototype,{getPrototypeOf:nx}=Object,Tm=(e=>t=>{const n=SF.call(t);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),ei=e=>(e=e.toLowerCase(),t=>Tm(t)===e),Pm=e=>t=>typeof t===e,{isArray:Sc}=Array,rd=Pm("undefined");function _F(e){return e!==null&&!rd(e)&&e.constructor!==null&&!rd(e.constructor)&&Kr(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const QR=ei("ArrayBuffer");function EF(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&QR(e.buffer),t}const CF=Pm("string"),Kr=Pm("function"),JR=Pm("number"),Am=e=>e!==null&&typeof e=="object",$F=e=>e===!0||e===!1,Hh=e=>{if(Tm(e)!=="object")return!1;const t=nx(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},RF=ei("Date"),kF=ei("File"),TF=ei("Blob"),PF=ei("FileList"),AF=e=>Am(e)&&Kr(e.pipe),MF=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||Kr(e.append)&&((t=Tm(e))==="formdata"||t==="object"&&Kr(e.toString)&&e.toString()==="[object FormData]"))},OF=ei("URLSearchParams"),NF=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function Nd(e,t,{allOwnKeys:n=!1}={}){if(e===null||typeof e>"u")return;let r,o;if(typeof e!="object"&&(e=[e]),Sc(e))for(r=0,o=e.length;r0;)if(o=n[r],t===o.toLowerCase())return o;return null}const tk=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,nk=e=>!rd(e)&&e!==tk;function Zy(){const{caseless:e}=nk(this)&&this||{},t={},n=(r,o)=>{const i=e&&ek(t,o)||o;Hh(t[i])&&Hh(r)?t[i]=Zy(t[i],r):Hh(r)?t[i]=Zy({},r):Sc(r)?t[i]=r.slice():t[i]=r};for(let r=0,o=arguments.length;r(Nd(t,(o,i)=>{n&&Kr(o)?e[i]=qR(o,n):e[i]=o},{allOwnKeys:r}),e),IF=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),LF=(e,t,n,r)=>{e.prototype=Object.create(t.prototype,r),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),n&&Object.assign(e.prototype,n)},FF=(e,t,n,r)=>{let o,i,s;const l={};if(t=t||{},e==null)return t;do{for(o=Object.getOwnPropertyNames(e),i=o.length;i-- >0;)s=o[i],(!r||r(s,e,t))&&!l[s]&&(t[s]=e[s],l[s]=!0);e=n!==!1&&nx(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},jF=(e,t,n)=>{e=String(e),(n===void 0||n>e.length)&&(n=e.length),n-=t.length;const r=e.indexOf(t,n);return r!==-1&&r===n},zF=e=>{if(!e)return null;if(Sc(e))return e;let t=e.length;if(!JR(t))return null;const n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},BF=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&nx(Uint8Array)),UF=(e,t)=>{const r=(e&&e[Symbol.iterator]).call(e);let o;for(;(o=r.next())&&!o.done;){const i=o.value;t.call(e,i[0],i[1])}},VF=(e,t)=>{let n;const r=[];for(;(n=e.exec(t))!==null;)r.push(n);return r},WF=ei("HTMLFormElement"),HF=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,r,o){return r.toUpperCase()+o}),pC=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),KF=ei("RegExp"),rk=(e,t)=>{const n=Object.getOwnPropertyDescriptors(e),r={};Nd(n,(o,i)=>{let s;(s=t(o,i,e))!==!1&&(r[i]=s||o)}),Object.defineProperties(e,r)},GF=e=>{rk(e,(t,n)=>{if(Kr(e)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;const r=e[n];if(Kr(r)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},YF=(e,t)=>{const n={},r=o=>{o.forEach(i=>{n[i]=!0})};return Sc(e)?r(e):r(String(e).split(t)),n},XF=()=>{},ZF=(e,t)=>(e=+e,Number.isFinite(e)?e:t),p0="abcdefghijklmnopqrstuvwxyz",mC="0123456789",ok={DIGIT:mC,ALPHA:p0,ALPHA_DIGIT:p0+p0.toUpperCase()+mC},qF=(e=16,t=ok.ALPHA_DIGIT)=>{let n="";const{length:r}=t;for(;e--;)n+=t[Math.random()*r|0];return n};function QF(e){return!!(e&&Kr(e.append)&&e[Symbol.toStringTag]==="FormData"&&e[Symbol.iterator])}const JF=e=>{const t=new Array(10),n=(r,o)=>{if(Am(r)){if(t.indexOf(r)>=0)return;if(!("toJSON"in r)){t[o]=r;const i=Sc(r)?[]:{};return Nd(r,(s,l)=>{const u=n(s,o+1);!rd(u)&&(i[l]=u)}),t[o]=void 0,i}}return r};return n(e,0)},ej=ei("AsyncFunction"),tj=e=>e&&(Am(e)||Kr(e))&&Kr(e.then)&&Kr(e.catch),ie={isArray:Sc,isArrayBuffer:QR,isBuffer:_F,isFormData:MF,isArrayBufferView:EF,isString:CF,isNumber:JR,isBoolean:$F,isObject:Am,isPlainObject:Hh,isUndefined:rd,isDate:RF,isFile:kF,isBlob:TF,isRegExp:KF,isFunction:Kr,isStream:AF,isURLSearchParams:OF,isTypedArray:BF,isFileList:PF,forEach:Nd,merge:Zy,extend:DF,trim:NF,stripBOM:IF,inherits:LF,toFlatObject:FF,kindOf:Tm,kindOfTest:ei,endsWith:jF,toArray:zF,forEachEntry:UF,matchAll:VF,isHTMLForm:WF,hasOwnProperty:pC,hasOwnProp:pC,reduceDescriptors:rk,freezeMethods:GF,toObjectSet:YF,toCamelCase:HF,noop:XF,toFiniteNumber:ZF,findKey:ek,global:tk,isContextDefined:nk,ALPHABET:ok,generateString:qF,isSpecCompliantForm:QF,toJSONObject:JF,isAsyncFn:ej,isThenable:tj};function ut(e,t,n,r,o){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),n&&(this.config=n),r&&(this.request=r),o&&(this.response=o)}ie.inherits(ut,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:ie.toJSONObject(this.config),code:this.code,status:this.response&&this.response.status?this.response.status:null}}});const ik=ut.prototype,sk={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{sk[e]={value:e}});Object.defineProperties(ut,sk);Object.defineProperty(ik,"isAxiosError",{value:!0});ut.from=(e,t,n,r,o,i)=>{const s=Object.create(ik);return ie.toFlatObject(e,s,function(u){return u!==Error.prototype},l=>l!=="isAxiosError"),ut.call(s,e.message,t,n,r,o),s.cause=e,s.name=e.name,i&&Object.assign(s,i),s};const nj=null;function qy(e){return ie.isPlainObject(e)||ie.isArray(e)}function ak(e){return ie.endsWith(e,"[]")?e.slice(0,-2):e}function gC(e,t,n){return e?e.concat(t).map(function(o,i){return o=ak(o),!n&&i?"["+o+"]":o}).join(n?".":""):t}function rj(e){return ie.isArray(e)&&!e.some(qy)}const oj=ie.toFlatObject(ie,{},null,function(t){return/^is[A-Z]/.test(t)});function Mm(e,t,n){if(!ie.isObject(e))throw new TypeError("target must be an object");t=t||new FormData,n=ie.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(S,E){return!ie.isUndefined(E[S])});const r=n.metaTokens,o=n.visitor||p,i=n.dots,s=n.indexes,u=(n.Blob||typeof Blob<"u"&&Blob)&&ie.isSpecCompliantForm(t);if(!ie.isFunction(o))throw new TypeError("visitor must be a function");function f(x){if(x===null)return"";if(ie.isDate(x))return x.toISOString();if(!u&&ie.isBlob(x))throw new ut("Blob is not supported. Use a Buffer instead.");return ie.isArrayBuffer(x)||ie.isTypedArray(x)?u&&typeof Blob=="function"?new Blob([x]):Buffer.from(x):x}function p(x,S,E){let _=x;if(x&&!E&&typeof x=="object"){if(ie.endsWith(S,"{}"))S=r?S:S.slice(0,-2),x=JSON.stringify(x);else if(ie.isArray(x)&&rj(x)||(ie.isFileList(x)||ie.endsWith(S,"[]"))&&(_=ie.toArray(x)))return S=ak(S),_.forEach(function(C,R){!(ie.isUndefined(C)||C===null)&&t.append(s===!0?gC([S],R,i):s===null?S:S+"[]",f(C))}),!1}return qy(x)?!0:(t.append(gC(E,S,i),f(x)),!1)}const m=[],g=Object.assign(oj,{defaultVisitor:p,convertValue:f,isVisitable:qy});function y(x,S){if(!ie.isUndefined(x)){if(m.indexOf(x)!==-1)throw Error("Circular reference detected in "+S.join("."));m.push(x),ie.forEach(x,function(_,b){(!(ie.isUndefined(_)||_===null)&&o.call(t,_,ie.isString(b)?b.trim():b,S,g))===!0&&y(_,S?S.concat(b):[b])}),m.pop()}}if(!ie.isObject(e))throw new TypeError("data must be an object");return y(e),t}function vC(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(r){return t[r]})}function rx(e,t){this._pairs=[],e&&Mm(e,this,t)}const lk=rx.prototype;lk.append=function(t,n){this._pairs.push([t,n])};lk.toString=function(t){const n=t?function(r){return t.call(this,r,vC)}:vC;return this._pairs.map(function(o){return n(o[0])+"="+n(o[1])},"").join("&")};function ij(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function ck(e,t,n){if(!t)return e;const r=n&&n.encode||ij,o=n&&n.serialize;let i;if(o?i=o(t,n):i=ie.isURLSearchParams(t)?t.toString():new rx(t,n).toString(r),i){const s=e.indexOf("#");s!==-1&&(e=e.slice(0,s)),e+=(e.indexOf("?")===-1?"?":"&")+i}return e}class sj{constructor(){this.handlers=[]}use(t,n,r){return this.handlers.push({fulfilled:t,rejected:n,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){ie.forEach(this.handlers,function(r){r!==null&&t(r)})}}const yC=sj,uk={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},aj=typeof URLSearchParams<"u"?URLSearchParams:rx,lj=typeof FormData<"u"?FormData:null,cj=typeof Blob<"u"?Blob:null,uj={isBrowser:!0,classes:{URLSearchParams:aj,FormData:lj,Blob:cj},protocols:["http","https","file","blob","url","data"]},dk=typeof window<"u"&&typeof document<"u",dj=(e=>dk&&["ReactNative","NativeScript","NS"].indexOf(e)<0)(typeof navigator<"u"&&navigator.product),fj=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",hj=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:dk,hasStandardBrowserEnv:dj,hasStandardBrowserWebWorkerEnv:fj},Symbol.toStringTag,{value:"Module"})),zo={...hj,...uj};function pj(e,t){return Mm(e,new zo.classes.URLSearchParams,Object.assign({visitor:function(n,r,o,i){return zo.isNode&&ie.isBuffer(n)?(this.append(r,n.toString("base64")),!1):i.defaultVisitor.apply(this,arguments)}},t))}function mj(e){return ie.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function gj(e){const t={},n=Object.keys(e);let r;const o=n.length;let i;for(r=0;r=n.length;return s=!s&&ie.isArray(o)?o.length:s,u?(ie.hasOwnProp(o,s)?o[s]=[o[s],r]:o[s]=r,!l):((!o[s]||!ie.isObject(o[s]))&&(o[s]=[]),t(n,r,o[s],i)&&ie.isArray(o[s])&&(o[s]=gj(o[s])),!l)}if(ie.isFormData(e)&&ie.isFunction(e.entries)){const n={};return ie.forEachEntry(e,(r,o)=>{t(mj(r),o,n,0)}),n}return null}function vj(e,t,n){if(ie.isString(e))try{return(t||JSON.parse)(e),ie.trim(e)}catch(r){if(r.name!=="SyntaxError")throw r}return(n||JSON.stringify)(e)}const ox={transitional:uk,adapter:["xhr","http"],transformRequest:[function(t,n){const r=n.getContentType()||"",o=r.indexOf("application/json")>-1,i=ie.isObject(t);if(i&&ie.isHTMLForm(t)&&(t=new FormData(t)),ie.isFormData(t))return o&&o?JSON.stringify(fk(t)):t;if(ie.isArrayBuffer(t)||ie.isBuffer(t)||ie.isStream(t)||ie.isFile(t)||ie.isBlob(t))return t;if(ie.isArrayBufferView(t))return t.buffer;if(ie.isURLSearchParams(t))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let l;if(i){if(r.indexOf("application/x-www-form-urlencoded")>-1)return pj(t,this.formSerializer).toString();if((l=ie.isFileList(t))||r.indexOf("multipart/form-data")>-1){const u=this.env&&this.env.FormData;return Mm(l?{"files[]":t}:t,u&&new u,this.formSerializer)}}return i||o?(n.setContentType("application/json",!1),vj(t)):t}],transformResponse:[function(t){const n=this.transitional||ox.transitional,r=n&&n.forcedJSONParsing,o=this.responseType==="json";if(t&&ie.isString(t)&&(r&&!this.responseType||o)){const s=!(n&&n.silentJSONParsing)&&o;try{return JSON.parse(t)}catch(l){if(s)throw l.name==="SyntaxError"?ut.from(l,ut.ERR_BAD_RESPONSE,this,null,this.response):l}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:zo.classes.FormData,Blob:zo.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};ie.forEach(["delete","get","head","post","put","patch"],e=>{ox.headers[e]={}});const ix=ox,yj=ie.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),wj=e=>{const t={};let n,r,o;return e&&e.split(` +`).forEach(function(s){o=s.indexOf(":"),n=s.substring(0,o).trim().toLowerCase(),r=s.substring(o+1).trim(),!(!n||t[n]&&yj[n])&&(n==="set-cookie"?t[n]?t[n].push(r):t[n]=[r]:t[n]=t[n]?t[n]+", "+r:r)}),t},wC=Symbol("internals");function uu(e){return e&&String(e).trim().toLowerCase()}function Kh(e){return e===!1||e==null?e:ie.isArray(e)?e.map(Kh):String(e)}function xj(e){const t=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=n.exec(e);)t[r[1]]=r[2];return t}const bj=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function m0(e,t,n,r,o){if(ie.isFunction(r))return r.call(this,t,n);if(o&&(t=n),!!ie.isString(t)){if(ie.isString(r))return t.indexOf(r)!==-1;if(ie.isRegExp(r))return r.test(t)}}function Sj(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,n,r)=>n.toUpperCase()+r)}function _j(e,t){const n=ie.toCamelCase(" "+t);["get","set","has"].forEach(r=>{Object.defineProperty(e,r+n,{value:function(o,i,s){return this[r].call(this,t,o,i,s)},configurable:!0})})}class Om{constructor(t){t&&this.set(t)}set(t,n,r){const o=this;function i(l,u,f){const p=uu(u);if(!p)throw new Error("header name must be a non-empty string");const m=ie.findKey(o,p);(!m||o[m]===void 0||f===!0||f===void 0&&o[m]!==!1)&&(o[m||u]=Kh(l))}const s=(l,u)=>ie.forEach(l,(f,p)=>i(f,p,u));return ie.isPlainObject(t)||t instanceof this.constructor?s(t,n):ie.isString(t)&&(t=t.trim())&&!bj(t)?s(wj(t),n):t!=null&&i(n,t,r),this}get(t,n){if(t=uu(t),t){const r=ie.findKey(this,t);if(r){const o=this[r];if(!n)return o;if(n===!0)return xj(o);if(ie.isFunction(n))return n.call(this,o,r);if(ie.isRegExp(n))return n.exec(o);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,n){if(t=uu(t),t){const r=ie.findKey(this,t);return!!(r&&this[r]!==void 0&&(!n||m0(this,this[r],r,n)))}return!1}delete(t,n){const r=this;let o=!1;function i(s){if(s=uu(s),s){const l=ie.findKey(r,s);l&&(!n||m0(r,r[l],l,n))&&(delete r[l],o=!0)}}return ie.isArray(t)?t.forEach(i):i(t),o}clear(t){const n=Object.keys(this);let r=n.length,o=!1;for(;r--;){const i=n[r];(!t||m0(this,this[i],i,t,!0))&&(delete this[i],o=!0)}return o}normalize(t){const n=this,r={};return ie.forEach(this,(o,i)=>{const s=ie.findKey(r,i);if(s){n[s]=Kh(o),delete n[i];return}const l=t?Sj(i):String(i).trim();l!==i&&delete n[i],n[l]=Kh(o),r[l]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){const n=Object.create(null);return ie.forEach(this,(r,o)=>{r!=null&&r!==!1&&(n[o]=t&&ie.isArray(r)?r.join(", "):r)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,n])=>t+": "+n).join(` +`)}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...n){const r=new this(t);return n.forEach(o=>r.set(o)),r}static accessor(t){const r=(this[wC]=this[wC]={accessors:{}}).accessors,o=this.prototype;function i(s){const l=uu(s);r[l]||(_j(o,s),r[l]=!0)}return ie.isArray(t)?t.forEach(i):i(t),this}}Om.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);ie.reduceDescriptors(Om.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(r){this[n]=r}}});ie.freezeMethods(Om);const xi=Om;function g0(e,t){const n=this||ix,r=t||n,o=xi.from(r.headers);let i=r.data;return ie.forEach(e,function(l){i=l.call(n,i,o.normalize(),t?t.status:void 0)}),o.normalize(),i}function hk(e){return!!(e&&e.__CANCEL__)}function Dd(e,t,n){ut.call(this,e??"canceled",ut.ERR_CANCELED,t,n),this.name="CanceledError"}ie.inherits(Dd,ut,{__CANCEL__:!0});function Ej(e,t,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?e(n):t(new ut("Request failed with status code "+n.status,[ut.ERR_BAD_REQUEST,ut.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}const Cj=zo.hasStandardBrowserEnv?{write(e,t,n,r,o,i){const s=[e+"="+encodeURIComponent(t)];ie.isNumber(n)&&s.push("expires="+new Date(n).toGMTString()),ie.isString(r)&&s.push("path="+r),ie.isString(o)&&s.push("domain="+o),i===!0&&s.push("secure"),document.cookie=s.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function $j(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function Rj(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e}function pk(e,t){return e&&!$j(t)?Rj(e,t):t}const kj=zo.hasStandardBrowserEnv?function(){const t=/(msie|trident)/i.test(navigator.userAgent),n=document.createElement("a");let r;function o(i){let s=i;return t&&(n.setAttribute("href",s),s=n.href),n.setAttribute("href",s),{href:n.href,protocol:n.protocol?n.protocol.replace(/:$/,""):"",host:n.host,search:n.search?n.search.replace(/^\?/,""):"",hash:n.hash?n.hash.replace(/^#/,""):"",hostname:n.hostname,port:n.port,pathname:n.pathname.charAt(0)==="/"?n.pathname:"/"+n.pathname}}return r=o(window.location.href),function(s){const l=ie.isString(s)?o(s):s;return l.protocol===r.protocol&&l.host===r.host}}():function(){return function(){return!0}}();function Tj(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function Pj(e,t){e=e||10;const n=new Array(e),r=new Array(e);let o=0,i=0,s;return t=t!==void 0?t:1e3,function(u){const f=Date.now(),p=r[i];s||(s=f),n[o]=u,r[o]=f;let m=i,g=0;for(;m!==o;)g+=n[m++],m=m%e;if(o=(o+1)%e,o===i&&(i=(i+1)%e),f-s{const i=o.loaded,s=o.lengthComputable?o.total:void 0,l=i-n,u=r(l),f=i<=s;n=i;const p={loaded:i,total:s,progress:s?i/s:void 0,bytes:l,rate:u||void 0,estimated:u&&s&&f?(s-i)/u:void 0,event:o};p[t?"download":"upload"]=!0,e(p)}}const Aj=typeof XMLHttpRequest<"u",Mj=Aj&&function(e){return new Promise(function(n,r){let o=e.data;const i=xi.from(e.headers).normalize();let{responseType:s,withXSRFToken:l}=e,u;function f(){e.cancelToken&&e.cancelToken.unsubscribe(u),e.signal&&e.signal.removeEventListener("abort",u)}let p;if(ie.isFormData(o)){if(zo.hasStandardBrowserEnv||zo.hasStandardBrowserWebWorkerEnv)i.setContentType(!1);else if((p=i.getContentType())!==!1){const[S,...E]=p?p.split(";").map(_=>_.trim()).filter(Boolean):[];i.setContentType([S||"multipart/form-data",...E].join("; "))}}let m=new XMLHttpRequest;if(e.auth){const S=e.auth.username||"",E=e.auth.password?unescape(encodeURIComponent(e.auth.password)):"";i.set("Authorization","Basic "+btoa(S+":"+E))}const g=pk(e.baseURL,e.url);m.open(e.method.toUpperCase(),ck(g,e.params,e.paramsSerializer),!0),m.timeout=e.timeout;function y(){if(!m)return;const S=xi.from("getAllResponseHeaders"in m&&m.getAllResponseHeaders()),_={data:!s||s==="text"||s==="json"?m.responseText:m.response,status:m.status,statusText:m.statusText,headers:S,config:e,request:m};Ej(function(C){n(C),f()},function(C){r(C),f()},_),m=null}if("onloadend"in m?m.onloadend=y:m.onreadystatechange=function(){!m||m.readyState!==4||m.status===0&&!(m.responseURL&&m.responseURL.indexOf("file:")===0)||setTimeout(y)},m.onabort=function(){m&&(r(new ut("Request aborted",ut.ECONNABORTED,e,m)),m=null)},m.onerror=function(){r(new ut("Network Error",ut.ERR_NETWORK,e,m)),m=null},m.ontimeout=function(){let E=e.timeout?"timeout of "+e.timeout+"ms exceeded":"timeout exceeded";const _=e.transitional||uk;e.timeoutErrorMessage&&(E=e.timeoutErrorMessage),r(new ut(E,_.clarifyTimeoutError?ut.ETIMEDOUT:ut.ECONNABORTED,e,m)),m=null},zo.hasStandardBrowserEnv&&(l&&ie.isFunction(l)&&(l=l(e)),l||l!==!1&&kj(g))){const S=e.xsrfHeaderName&&e.xsrfCookieName&&Cj.read(e.xsrfCookieName);S&&i.set(e.xsrfHeaderName,S)}o===void 0&&i.setContentType(null),"setRequestHeader"in m&&ie.forEach(i.toJSON(),function(E,_){m.setRequestHeader(_,E)}),ie.isUndefined(e.withCredentials)||(m.withCredentials=!!e.withCredentials),s&&s!=="json"&&(m.responseType=e.responseType),typeof e.onDownloadProgress=="function"&&m.addEventListener("progress",xC(e.onDownloadProgress,!0)),typeof e.onUploadProgress=="function"&&m.upload&&m.upload.addEventListener("progress",xC(e.onUploadProgress)),(e.cancelToken||e.signal)&&(u=S=>{m&&(r(!S||S.type?new Dd(null,e,m):S),m.abort(),m=null)},e.cancelToken&&e.cancelToken.subscribe(u),e.signal&&(e.signal.aborted?u():e.signal.addEventListener("abort",u)));const x=Tj(g);if(x&&zo.protocols.indexOf(x)===-1){r(new ut("Unsupported protocol "+x+":",ut.ERR_BAD_REQUEST,e));return}m.send(o||null)})},Qy={http:nj,xhr:Mj};ie.forEach(Qy,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});const bC=e=>`- ${e}`,Oj=e=>ie.isFunction(e)||e===null||e===!1,mk={getAdapter:e=>{e=ie.isArray(e)?e:[e];const{length:t}=e;let n,r;const o={};for(let i=0;i`adapter ${l} `+(u===!1?"is not supported by the environment":"is not available in the build"));let s=t?i.length>1?`since : +`+i.map(bC).join(` +`):" "+bC(i[0]):"as no adapter specified";throw new ut("There is no suitable adapter to dispatch the request "+s,"ERR_NOT_SUPPORT")}return r},adapters:Qy};function v0(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Dd(null,e)}function SC(e){return v0(e),e.headers=xi.from(e.headers),e.data=g0.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),mk.getAdapter(e.adapter||ix.adapter)(e).then(function(r){return v0(e),r.data=g0.call(e,e.transformResponse,r),r.headers=xi.from(r.headers),r},function(r){return hk(r)||(v0(e),r&&r.response&&(r.response.data=g0.call(e,e.transformResponse,r.response),r.response.headers=xi.from(r.response.headers))),Promise.reject(r)})}const _C=e=>e instanceof xi?e.toJSON():e;function ic(e,t){t=t||{};const n={};function r(f,p,m){return ie.isPlainObject(f)&&ie.isPlainObject(p)?ie.merge.call({caseless:m},f,p):ie.isPlainObject(p)?ie.merge({},p):ie.isArray(p)?p.slice():p}function o(f,p,m){if(ie.isUndefined(p)){if(!ie.isUndefined(f))return r(void 0,f,m)}else return r(f,p,m)}function i(f,p){if(!ie.isUndefined(p))return r(void 0,p)}function s(f,p){if(ie.isUndefined(p)){if(!ie.isUndefined(f))return r(void 0,f)}else return r(void 0,p)}function l(f,p,m){if(m in t)return r(f,p);if(m in e)return r(void 0,f)}const u={url:i,method:i,data:i,baseURL:s,transformRequest:s,transformResponse:s,paramsSerializer:s,timeout:s,timeoutMessage:s,withCredentials:s,withXSRFToken:s,adapter:s,responseType:s,xsrfCookieName:s,xsrfHeaderName:s,onUploadProgress:s,onDownloadProgress:s,decompress:s,maxContentLength:s,maxBodyLength:s,beforeRedirect:s,transport:s,httpAgent:s,httpsAgent:s,cancelToken:s,socketPath:s,responseEncoding:s,validateStatus:l,headers:(f,p)=>o(_C(f),_C(p),!0)};return ie.forEach(Object.keys(Object.assign({},e,t)),function(p){const m=u[p]||o,g=m(e[p],t[p],p);ie.isUndefined(g)&&m!==l||(n[p]=g)}),n}const gk="1.6.2",sx={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{sx[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const EC={};sx.transitional=function(t,n,r){function o(i,s){return"[Axios v"+gk+"] Transitional option '"+i+"'"+s+(r?". "+r:"")}return(i,s,l)=>{if(t===!1)throw new ut(o(s," has been removed"+(n?" in "+n:"")),ut.ERR_DEPRECATED);return n&&!EC[s]&&(EC[s]=!0,console.warn(o(s," has been deprecated since v"+n+" and will be removed in the near future"))),t?t(i,s,l):!0}};function Nj(e,t,n){if(typeof e!="object")throw new ut("options must be an object",ut.ERR_BAD_OPTION_VALUE);const r=Object.keys(e);let o=r.length;for(;o-- >0;){const i=r[o],s=t[i];if(s){const l=e[i],u=l===void 0||s(l,i,e);if(u!==!0)throw new ut("option "+i+" must be "+u,ut.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new ut("Unknown option "+i,ut.ERR_BAD_OPTION)}}const Jy={assertOptions:Nj,validators:sx},Xi=Jy.validators;class Op{constructor(t){this.defaults=t,this.interceptors={request:new yC,response:new yC}}request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=ic(this.defaults,n);const{transitional:r,paramsSerializer:o,headers:i}=n;r!==void 0&&Jy.assertOptions(r,{silentJSONParsing:Xi.transitional(Xi.boolean),forcedJSONParsing:Xi.transitional(Xi.boolean),clarifyTimeoutError:Xi.transitional(Xi.boolean)},!1),o!=null&&(ie.isFunction(o)?n.paramsSerializer={serialize:o}:Jy.assertOptions(o,{encode:Xi.function,serialize:Xi.function},!0)),n.method=(n.method||this.defaults.method||"get").toLowerCase();let s=i&&ie.merge(i.common,i[n.method]);i&&ie.forEach(["delete","get","head","post","put","patch","common"],x=>{delete i[x]}),n.headers=xi.concat(s,i);const l=[];let u=!0;this.interceptors.request.forEach(function(S){typeof S.runWhen=="function"&&S.runWhen(n)===!1||(u=u&&S.synchronous,l.unshift(S.fulfilled,S.rejected))});const f=[];this.interceptors.response.forEach(function(S){f.push(S.fulfilled,S.rejected)});let p,m=0,g;if(!u){const x=[SC.bind(this),void 0];for(x.unshift.apply(x,l),x.push.apply(x,f),g=x.length,p=Promise.resolve(n);m{if(!r._listeners)return;let i=r._listeners.length;for(;i-- >0;)r._listeners[i](o);r._listeners=null}),this.promise.then=o=>{let i;const s=new Promise(l=>{r.subscribe(l),i=l}).then(o);return s.cancel=function(){r.unsubscribe(i)},s},t(function(i,s,l){r.reason||(r.reason=new Dd(i,s,l),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}static source(){let t;return{token:new ax(function(o){t=o}),cancel:t}}}const Dj=ax;function Ij(e){return function(n){return e.apply(null,n)}}function Lj(e){return ie.isObject(e)&&e.isAxiosError===!0}const e1={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(e1).forEach(([e,t])=>{e1[t]=e});const Fj=e1;function vk(e){const t=new Gh(e),n=qR(Gh.prototype.request,t);return ie.extend(n,Gh.prototype,t,{allOwnKeys:!0}),ie.extend(n,t,null,{allOwnKeys:!0}),n.create=function(o){return vk(ic(e,o))},n}const Qt=vk(ix);Qt.Axios=Gh;Qt.CanceledError=Dd;Qt.CancelToken=Dj;Qt.isCancel=hk;Qt.VERSION=gk;Qt.toFormData=Mm;Qt.AxiosError=ut;Qt.Cancel=Qt.CanceledError;Qt.all=function(t){return Promise.all(t)};Qt.spread=Ij;Qt.isAxiosError=Lj;Qt.mergeConfig=ic;Qt.AxiosHeaders=xi;Qt.formToJSON=e=>fk(ie.isHTMLForm(e)?new FormData(e):e);Qt.getAdapter=mk.getAdapter;Qt.HttpStatusCode=Fj;Qt.default=Qt;const jj=Qt,Ls="/api/v1",_c=jj.create({baseURL:Ls});async function zj(e,t,n,r,o,i=null){const s=await Du(e),l=await Du(o),u=i?await Du(i):null,f=await fetch(`${Ls}/inpaint`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({image:s,mask:l,ldm_steps:t.ldmSteps,ldm_sampler:t.ldmSampler,zits_wireframe:t.zitsWireframe,cv2_flag:t.cv2Flag,cv2_radius:t.cv2Radius,hd_strategy:"Crop",hd_strategy_crop_triger_size:640,hd_strategy_crop_margin:128,hd_trategy_resize_imit:2048,prompt:t.prompt,negative_prompt:t.negativePrompt,use_croper:t.showCropper,croper_x:n.x,croper_y:n.y,croper_height:n.height,croper_width:n.width,use_extender:t.showExtender,extender_x:r.x,extender_y:r.y,extender_height:r.height,extender_width:r.width,sd_mask_blur:t.sdMaskBlur,sd_strength:t.sdStrength,sd_steps:t.sdSteps,sd_guidance_scale:t.sdGuidanceScale,sd_sampler:t.sdSampler,sd_seed:t.seedFixed?t.seed:-1,sd_match_histograms:t.sdMatchHistograms,sd_freeu:t.enableFreeu,sd_freeu_config:t.freeuConfig,sd_lcm_lora:t.enableLCMLora,paint_by_example_example_image:u,p2p_image_guidance_scale:t.p2pImageGuidanceScale,enable_controlnet:t.enableControlnet,controlnet_conditioning_scale:t.controlnetConditioningScale,controlnet_method:t.controlnetMethod?t.controlnetMethod:"",powerpaint_task:t.showExtender?Ol.outpainting:t.powerpaintTask})});if(f.ok){const m=await f.blob();return{blob:URL.createObjectURL(m),seed:f.headers.get("X-Seed")}}const p=await f.json();throw new Error(`Something went wrong: ${p.errors}`)}async function yk(){return(await _c.get("/server-config")).data}async function Bj(e){return(await _c.post("/model",{name:e})).data}async function y0(e,t){return _c.post("/switch_plugin_model",{plugin_name:e,model_name:t})}async function Uj(){return(await _c.get("/model")).data}async function wk(e,t,n,r,o){const i=await Du(n),l=await fetch(`${Ls}/${e?"run_plugin_gen_mask":"run_plugin_gen_image"}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t,image:i,upscale:r,clicks:o})});if(l.ok){const f=await l.blob();return{blob:URL.createObjectURL(f)}}const u=await l.json();throw new Error(u)}async function Vj(e,t){const n=await fetch(`${Ls}/media_file?tab=${e}&filename=${encodeURIComponent(t)}`,{method:"GET"});if(n.ok){const o=await n.blob();return new File([o],t,{type:n.headers.get("Content-Type")??"image/png"})}const r=await n.json();throw new Error(r.errors)}async function Wj(e){return(await _c.get("medias",{params:{tab:e}})).data}async function Hj(e,t,n){const r=await Nu(e.src,t,n),o=new FormData;o.append("file",r);try{const i=await fetch(`${Ls}/save_image`,{method:"POST",body:o});if(!i.ok){const s=await i.text();throw new Error(s)}}catch(i){throw new Error(`Something went wrong: ${i}`)}}async function Kj(e){const t=new FormData;return t.append("file",e),(await _c.post("/gen-info",t)).data}async function Gj(e,t,n){const r=await Du(e),o=await fetch(`${Ls}/adjust_mask`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mask:r,operate:t,kernel_size:n})});if(o.ok)return await o.blob();const i=await o.json();throw new Error(i)}function Yj(){const[e,t]=d.useState(null),n=d.useCallback(()=>{const r=new Headers;r.append("pragma","no-cache"),r.append("cache-control","no-cache"),fetch(`${Ls}/inputimage`,{headers:r}).then(async o=>{var l;if(!o.ok)return;const i=(l=o.headers.get("content-disposition"))==null?void 0:l.split("filename=")[1].split(";")[0],s=await o.blob();if(s&&s.type.startsWith("image")){const u=new File([s],i!==void 0?i:"inputImage");t(u)}}).catch(o=>{console.log(o)})},[t]);return d.useEffect(()=>{n()},[n]),e}function _o(e,t){if(e==null)return{};var n={},r=Object.keys(e),o,i;for(i=0;i=0)&&(n[o]=e[o]);return n}var Xj=["color"],Zj=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,Xj);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.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:r,fillRule:"evenodd",clipRule:"evenodd"}))}),qj=["color"],xk=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,qj);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M11.4669 3.72684C11.7558 3.91574 11.8369 4.30308 11.648 4.59198L7.39799 11.092C7.29783 11.2452 7.13556 11.3467 6.95402 11.3699C6.77247 11.3931 6.58989 11.3355 6.45446 11.2124L3.70446 8.71241C3.44905 8.48022 3.43023 8.08494 3.66242 7.82953C3.89461 7.57412 4.28989 7.55529 4.5453 7.78749L6.75292 9.79441L10.6018 3.90792C10.7907 3.61902 11.178 3.53795 11.4669 3.72684Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),Qj=["color"],Jj=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,Qj);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M3.13523 6.15803C3.3241 5.95657 3.64052 5.94637 3.84197 6.13523L7.5 9.56464L11.158 6.13523C11.3595 5.94637 11.6759 5.95657 11.8648 6.15803C12.0536 6.35949 12.0434 6.67591 11.842 6.86477L7.84197 10.6148C7.64964 10.7951 7.35036 10.7951 7.15803 10.6148L3.15803 6.86477C2.95657 6.67591 2.94637 6.35949 3.13523 6.15803Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),ez=["color"],tz=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,ez);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M6.1584 3.13508C6.35985 2.94621 6.67627 2.95642 6.86514 3.15788L10.6151 7.15788C10.7954 7.3502 10.7954 7.64949 10.6151 7.84182L6.86514 11.8418C6.67627 12.0433 6.35985 12.0535 6.1584 11.8646C5.95694 11.6757 5.94673 11.3593 6.1356 11.1579L9.565 7.49985L6.1356 3.84182C5.94673 3.64036 5.95694 3.32394 6.1584 3.13508Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),nz=["color"],rz=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,nz);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M3.13523 8.84197C3.3241 9.04343 3.64052 9.05363 3.84197 8.86477L7.5 5.43536L11.158 8.86477C11.3595 9.05363 11.6759 9.04343 11.8648 8.84197C12.0536 8.64051 12.0434 8.32409 11.842 8.13523L7.84197 4.38523C7.64964 4.20492 7.35036 4.20492 7.15803 4.38523L3.15803 8.13523C2.95657 8.32409 2.94637 8.64051 3.13523 8.84197Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),oz=["color"],bk=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,oz);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.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:r,fillRule:"evenodd",clipRule:"evenodd"}))}),iz=["color"],sz=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,iz);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M9.875 7.5C9.875 8.81168 8.81168 9.875 7.5 9.875C6.18832 9.875 5.125 8.81168 5.125 7.5C5.125 6.18832 6.18832 5.125 7.5 5.125C8.81168 5.125 9.875 6.18832 9.875 7.5Z",fill:r}))}),az=["color"],lz=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,az);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M10 6.5C10 8.433 8.433 10 6.5 10C4.567 10 3 8.433 3 6.5C3 4.567 4.567 3 6.5 3C8.433 3 10 4.567 10 6.5ZM9.30884 10.0159C8.53901 10.6318 7.56251 11 6.5 11C4.01472 11 2 8.98528 2 6.5C2 4.01472 4.01472 2 6.5 2C8.98528 2 11 4.01472 11 6.5C11 7.56251 10.6318 8.53901 10.0159 9.30884L12.8536 12.1464C13.0488 12.3417 13.0488 12.6583 12.8536 12.8536C12.6583 13.0488 12.3417 13.0488 12.1464 12.8536L9.30884 10.0159Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),cz=["color"],uz=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,cz);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M3.24182 2.32181C3.3919 2.23132 3.5784 2.22601 3.73338 2.30781L12.7334 7.05781C12.8974 7.14436 13 7.31457 13 7.5C13 7.68543 12.8974 7.85564 12.7334 7.94219L3.73338 12.6922C3.5784 12.774 3.3919 12.7687 3.24182 12.6782C3.09175 12.5877 3 12.4252 3 12.25V2.75C3 2.57476 3.09175 2.4123 3.24182 2.32181ZM4 3.57925V11.4207L11.4288 7.5L4 3.57925Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),dz=["color"],fz=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,dz);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M7 2H1.5C1.22386 2 1 2.22386 1 2.5V7H7V2ZM8 2V7H14V2.5C14 2.22386 13.7761 2 13.5 2H8ZM7 8H1V12.5C1 12.7761 1.22386 13 1.5 13H7V8ZM8 13V8H14V12.5C14 12.7761 13.7761 13 13.5 13H8ZM1.5 1C0.671573 1 0 1.67157 0 2.5V12.5C0 13.3284 0.671573 14 1.5 14H13.5C14.3284 14 15 13.3284 15 12.5V2.5C15 1.67157 14.3284 1 13.5 1H1.5Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),hz=["color"],pz=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,hz);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M1.5 2H13.5C13.7761 2 14 2.22386 14 2.5V7H1V2.5C1 2.22386 1.22386 2 1.5 2ZM1 8V12.5C1 12.7761 1.22386 13 1.5 13H13.5C13.7761 13 14 12.7761 14 12.5V8H1ZM0 2.5C0 1.67157 0.671573 1 1.5 1H13.5C14.3284 1 15 1.67157 15 2.5V12.5C15 13.3284 14.3284 14 13.5 14H1.5C0.671573 14 0 13.3284 0 12.5V2.5Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))});function Y(){return Y=Object.assign?Object.assign.bind():function(e){for(var t=1;te.forEach(n=>mz(n,t))}function Ue(...e){return d.useCallback(Nm(...e),e)}const Zo=d.forwardRef((e,t)=>{const{children:n,...r}=e,o=d.Children.toArray(n),i=o.find(gz);if(i){const s=i.props.children,l=o.map(u=>u===i?d.Children.count(s)>1?d.Children.only(null):d.isValidElement(s)?s.props.children:null:u);return d.createElement(t1,Y({},r,{ref:t}),d.isValidElement(s)?d.cloneElement(s,void 0,l):null)}return d.createElement(t1,Y({},r,{ref:t}),n)});Zo.displayName="Slot";const t1=d.forwardRef((e,t)=>{const{children:n,...r}=e;return d.isValidElement(n)?d.cloneElement(n,{...vz(r,n.props),ref:t?Nm(t,n.ref):n.ref}):d.Children.count(n)>1?d.Children.only(null):null});t1.displayName="SlotClone";const lx=({children:e})=>d.createElement(d.Fragment,null,e);function gz(e){return d.isValidElement(e)&&e.type===lx}function vz(e,t){const n={...t};for(const r in t){const o=e[r],i=t[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...l)=>{i(...l),o(...l)}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...e,...n}}const CC=e=>typeof e=="boolean"?"".concat(e):e===0?"0":e,$C=VR,Dm=(e,t)=>n=>{var r;if((t==null?void 0:t.variants)==null)return $C(e,n==null?void 0:n.class,n==null?void 0:n.className);const{variants:o,defaultVariants:i}=t,s=Object.keys(o).map(f=>{const p=n==null?void 0:n[f],m=i==null?void 0:i[f];if(p===null)return null;const g=CC(p)||CC(m);return o[f][g]}),l=n&&Object.entries(n).reduce((f,p)=>{let[m,g]=p;return g===void 0||(f[m]=g),f},{}),u=t==null||(r=t.compoundVariants)===null||r===void 0?void 0:r.reduce((f,p)=>{let{class:m,className:g,...y}=p;return Object.entries(y).every(x=>{let[S,E]=x;return Array.isArray(E)?E.includes({...i,...l}[S]):{...i,...l}[S]===E})?[...f,m,g]:f},[]);return $C(e,s,u,n==null?void 0:n.class,n==null?void 0:n.className)};var yz={VITE_BACKEND:"http://127.0.0.1:8080",BASE_URL:"/",MODE:"production",DEV:!1,PROD:!0,SSR:!1};function wz(e,t){let n;try{n=e()}catch{return}return{getItem:o=>{var i;const s=u=>u===null?null:JSON.parse(u,t==null?void 0:t.reviver),l=(i=n.getItem(o))!=null?i:null;return l instanceof Promise?l.then(s):s(l)},setItem:(o,i)=>n.setItem(o,JSON.stringify(i,t==null?void 0:t.replacer)),removeItem:o=>n.removeItem(o)}}const od=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then(r){return od(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return od(r)(n)}}}},xz=(e,t)=>(n,r,o)=>{let i={getStorage:()=>localStorage,serialize:JSON.stringify,deserialize:JSON.parse,partialize:E=>E,version:0,merge:(E,_)=>({..._,...E}),...t},s=!1;const l=new Set,u=new Set;let f;try{f=i.getStorage()}catch{}if(!f)return e((...E)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),n(...E)},r,o);const p=od(i.serialize),m=()=>{const E=i.partialize({...r()});let _;const b=p({state:E,version:i.version}).then(C=>f.setItem(i.name,C)).catch(C=>{_=C});if(_)throw _;return b},g=o.setState;o.setState=(E,_)=>{g(E,_),m()};const y=e((...E)=>{n(...E),m()},r,o);let x;const S=()=>{var E;if(!f)return;s=!1,l.forEach(b=>b(r()));const _=((E=i.onRehydrateStorage)==null?void 0:E.call(i,r()))||void 0;return od(f.getItem.bind(f))(i.name).then(b=>{if(b)return i.deserialize(b)}).then(b=>{if(b)if(typeof b.version=="number"&&b.version!==i.version){if(i.migrate)return i.migrate(b.state,b.version);console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return b.state}).then(b=>{var C;return x=i.merge(b,(C=r())!=null?C:y),n(x,!0),m()}).then(()=>{_==null||_(x,void 0),s=!0,u.forEach(b=>b(x))}).catch(b=>{_==null||_(void 0,b)})};return o.persist={setOptions:E=>{i={...i,...E},E.getStorage&&(f=E.getStorage())},clearStorage:()=>{f==null||f.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>S(),hasHydrated:()=>s,onHydrate:E=>(l.add(E),()=>{l.delete(E)}),onFinishHydration:E=>(u.add(E),()=>{u.delete(E)})},S(),x||y},bz=(e,t)=>(n,r,o)=>{let i={storage:wz(()=>localStorage),partialize:S=>S,version:0,merge:(S,E)=>({...E,...S}),...t},s=!1;const l=new Set,u=new Set;let f=i.storage;if(!f)return e((...S)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),n(...S)},r,o);const p=()=>{const S=i.partialize({...r()});return f.setItem(i.name,{state:S,version:i.version})},m=o.setState;o.setState=(S,E)=>{m(S,E),p()};const g=e((...S)=>{n(...S),p()},r,o);let y;const x=()=>{var S,E;if(!f)return;s=!1,l.forEach(b=>{var C;return b((C=r())!=null?C:g)});const _=((E=i.onRehydrateStorage)==null?void 0:E.call(i,(S=r())!=null?S:g))||void 0;return od(f.getItem.bind(f))(i.name).then(b=>{if(b)if(typeof b.version=="number"&&b.version!==i.version){if(i.migrate)return i.migrate(b.state,b.version);console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return b.state}).then(b=>{var C;return y=i.merge(b,(C=r())!=null?C:g),n(y,!0),p()}).then(()=>{_==null||_(y,void 0),y=r(),s=!0,u.forEach(b=>b(y))}).catch(b=>{_==null||_(void 0,b)})};return o.persist={setOptions:S=>{i={...i,...S},S.storage&&(f=S.storage)},clearStorage:()=>{f==null||f.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>x(),hasHydrated:()=>s,onHydrate:S=>(l.add(S),()=>{l.delete(S)}),onFinishHydration:S=>(u.add(S),()=>{u.delete(S)})},i.skipHydration||x(),y||g},Sz=(e,t)=>"getStorage"in t||"serialize"in t||"deserialize"in t?((yz?"production":void 0)!=="production"&&console.warn("[DEPRECATED] `getStorage`, `serialize` and `deserialize` options are deprecated. Use `storage` option instead."),xz(e,t)):bz(e,t),_z=Sz;function Ez(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,o]of e)if(!Object.is(o,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{t(n,r,e)}):e.forEach((n,r)=>t(r,n,e))}function Im(e){const t=e[wr];return t?t.type_:Array.isArray(e)?1:Lm(e)?2:Fm(e)?3:0}function n1(e,t){return Im(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function Ek(e,t,n){const r=Im(e);r===2?e.set(t,n):r===3?e.add(n):e[t]=n}function $z(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function Lm(e){return e instanceof Map}function Fm(e){return e instanceof Set}function ra(e){return e.copy_||e.base_}function r1(e,t){if(Lm(e))return new Map(e);if(Fm(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);if(!t&&_k(e))return sc(e)?{...e}:Object.assign(Object.create(null),e);const n=Object.getOwnPropertyDescriptors(e);delete n[wr];let r=Reflect.ownKeys(n);for(let o=0;o1&&(e.set=e.add=e.clear=e.delete=Rz),Object.freeze(e),t&&id(e,(n,r)=>cx(r,!0))),e}function Rz(){po(2)}function jm(e){return Object.isFrozen(e)}var kz={};function Oa(e){const t=kz[e];return t||po(0,e),t}var sd;function Ck(){return sd}function Tz(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function kC(e,t){t&&(Oa("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function o1(e){i1(e),e.drafts_.forEach(Pz),e.drafts_=null}function i1(e){e===sd&&(sd=e.parent_)}function TC(e){return sd=Tz(sd,e)}function Pz(e){const t=e[wr];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function PC(e,t){t.unfinalizedDrafts_=t.drafts_.length;const n=t.drafts_[0];return e!==void 0&&e!==n?(n[wr].modified_&&(o1(t),po(4)),Ma(e)&&(e=Np(t,e),t.parent_||Dp(t,e)),t.patches_&&Oa("Patches").generateReplacementPatches_(n[wr].base_,e,t.patches_,t.inversePatches_)):e=Np(t,n,[]),o1(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==Sk?e:void 0}function Np(e,t,n){if(jm(t))return t;const r=t[wr];if(!r)return id(t,(o,i)=>AC(e,r,t,o,i,n)),t;if(r.scope_!==e)return t;if(!r.modified_)return Dp(e,r.base_,!0),r.base_;if(!r.finalized_){r.finalized_=!0,r.scope_.unfinalizedDrafts_--;const o=r.copy_;let i=o,s=!1;r.type_===3&&(i=new Set(o),o.clear(),s=!0),id(i,(l,u)=>AC(e,r,o,l,u,n,s)),Dp(e,o,!1),n&&e.patches_&&Oa("Patches").generatePatches_(r,n,e.patches_,e.inversePatches_)}return r.copy_}function AC(e,t,n,r,o,i,s){if(ac(o)){const l=i&&t&&t.type_!==3&&!n1(t.assigned_,r)?i.concat(r):void 0,u=Np(e,o,l);if(Ek(n,r,u),ac(u))e.canAutoFreeze_=!1;else return}else s&&n.add(o);if(Ma(o)&&!jm(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;Np(e,o),(!t||!t.scope_.parent_)&&Dp(e,o)}}function Dp(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&cx(t,n)}function Az(e,t){const n=Array.isArray(e),r={type_:n?1:0,scope_:t?t.scope_:Ck(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1};let o=r,i=ux;n&&(o=[r],i=ad);const{revoke:s,proxy:l}=Proxy.revocable(o,i);return r.draft_=l,r.revoke_=s,l}var ux={get(e,t){if(t===wr)return e;const n=ra(e);if(!n1(n,t))return Mz(e,n,t);const r=n[t];return e.finalized_||!Ma(r)?r:r===w0(e.base_,t)?(x0(e),e.copy_[t]=a1(r,e)):r},has(e,t){return t in ra(e)},ownKeys(e){return Reflect.ownKeys(ra(e))},set(e,t,n){const r=$k(ra(e),t);if(r!=null&&r.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){const o=w0(ra(e),t),i=o==null?void 0:o[wr];if(i&&i.base_===n)return e.copy_[t]=n,e.assigned_[t]=!1,!0;if($z(n,o)&&(n!==void 0||n1(e.base_,t)))return!0;x0(e),s1(e)}return e.copy_[t]===n&&(n!==void 0||t in e.copy_)||Number.isNaN(n)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=n,e.assigned_[t]=!0),!0},deleteProperty(e,t){return w0(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,x0(e),s1(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){const n=ra(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:r.enumerable,value:n[t]}},defineProperty(){po(11)},getPrototypeOf(e){return sc(e.base_)},setPrototypeOf(){po(12)}},ad={};id(ux,(e,t)=>{ad[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});ad.deleteProperty=function(e,t){return ad.set.call(this,e,t,void 0)};ad.set=function(e,t,n){return ux.set.call(this,e[0],t,n,e[0])};function w0(e,t){const n=e[wr];return(n?ra(n):e)[t]}function Mz(e,t,n){var o;const r=$k(t,n);return r?"value"in r?r.value:(o=r.get)==null?void 0:o.call(e.draft_):void 0}function $k(e,t){if(!(t in e))return;let n=sc(e);for(;n;){const r=Object.getOwnPropertyDescriptor(n,t);if(r)return r;n=sc(n)}}function s1(e){e.modified_||(e.modified_=!0,e.parent_&&s1(e.parent_))}function x0(e){e.copy_||(e.copy_=r1(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var Oz=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(t,n,r)=>{if(typeof t=="function"&&typeof n!="function"){const i=n;n=t;const s=this;return function(u=i,...f){return s.produce(u,p=>n.call(this,p,...f))}}typeof n!="function"&&po(6),r!==void 0&&typeof r!="function"&&po(7);let o;if(Ma(t)){const i=TC(this),s=a1(t,void 0);let l=!0;try{o=n(s),l=!1}finally{l?o1(i):i1(i)}return kC(i,r),PC(o,i)}else if(!t||typeof t!="object"){if(o=n(t),o===void 0&&(o=t),o===Sk&&(o=void 0),this.autoFreeze_&&cx(o,!0),r){const i=[],s=[];Oa("Patches").generateReplacementPatches_(t,o,i,s),r(i,s)}return o}else po(1,t)},this.produceWithPatches=(t,n)=>{if(typeof t=="function")return(s,...l)=>this.produceWithPatches(s,u=>t(u,...l));let r,o;return[this.produce(t,n,(s,l)=>{r=s,o=l}),r,o]},typeof(e==null?void 0:e.autoFreeze)=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof(e==null?void 0:e.useStrictShallowCopy)=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){Ma(e)||po(8),ac(e)&&(e=Nz(e));const t=TC(this),n=a1(e,void 0);return n[wr].isManual_=!0,i1(t),n}finishDraft(e,t){const n=e&&e[wr];(!n||!n.isManual_)&&po(9);const{scope_:r}=n;return kC(r,t),PC(void 0,r)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let n;for(n=t.length-1;n>=0;n--){const o=t[n];if(o.path.length===0&&o.op==="replace"){e=o.value;break}}n>-1&&(t=t.slice(n+1));const r=Oa("Patches").applyPatches_;return ac(e)?r(e,t):this.produce(e,o=>r(o,t))}};function a1(e,t){const n=Lm(e)?Oa("MapSet").proxyMap_(e,t):Fm(e)?Oa("MapSet").proxySet_(e,t):Az(e,t);return(t?t.scope_:Ck()).drafts_.push(n),n}function Nz(e){return ac(e)||po(10,e),Rk(e)}function Rk(e){if(!Ma(e)||jm(e))return e;const t=e[wr];let n;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=r1(e,t.scope_.immer_.useStrictShallowCopy_)}else n=r1(e,!0);return id(n,(r,o)=>{Ek(n,r,Rk(o))}),t&&(t.finalized_=!1),n}var xr=new Oz,Dz=xr.produce;xr.produceWithPatches.bind(xr);xr.setAutoFreeze.bind(xr);xr.setUseStrictShallowCopy.bind(xr);xr.applyPatches.bind(xr);xr.createDraft.bind(xr);xr.finishDraft.bind(xr);const Iz=e=>(t,n,r)=>(r.setState=(o,i,...s)=>{const l=typeof o=="function"?Dz(o):o;return t(l,i,...s)},e(r.setState,n,r)),Lz=Iz;var kk={exports:{}},Tk={},Pk={exports:{}},Ak={};/** + * @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 lc=d;function Fz(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var jz=typeof Object.is=="function"?Object.is:Fz,zz=lc.useState,Bz=lc.useEffect,Uz=lc.useLayoutEffect,Vz=lc.useDebugValue;function Wz(e,t){var n=t(),r=zz({inst:{value:n,getSnapshot:t}}),o=r[0].inst,i=r[1];return Uz(function(){o.value=n,o.getSnapshot=t,b0(o)&&i({inst:o})},[e,n,t]),Bz(function(){return b0(o)&&i({inst:o}),e(function(){b0(o)&&i({inst:o})})},[e]),Vz(n),n}function b0(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!jz(e,n)}catch{return!0}}function Hz(e,t){return t()}var Kz=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?Hz:Wz;Ak.useSyncExternalStore=lc.useSyncExternalStore!==void 0?lc.useSyncExternalStore:Kz;Pk.exports=Ak;var Gz=Pk.exports;/** + * @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 zm=d,Yz=Gz;function Xz(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var Zz=typeof Object.is=="function"?Object.is:Xz,qz=Yz.useSyncExternalStore,Qz=zm.useRef,Jz=zm.useEffect,eB=zm.useMemo,tB=zm.useDebugValue;Tk.useSyncExternalStoreWithSelector=function(e,t,n,r,o){var i=Qz(null);if(i.current===null){var s={hasValue:!1,value:null};i.current=s}else s=i.current;i=eB(function(){function u(y){if(!f){if(f=!0,p=y,y=r(y),o!==void 0&&s.hasValue){var x=s.value;if(o(x,y))return m=x}return m=y}if(x=m,Zz(p,y))return x;var S=r(y);return o!==void 0&&o(x,S)?x:(p=y,m=S)}var f=!1,p,m,g=n===void 0?null:n;return[function(){return u(t())},g===null?void 0:function(){return u(g())}]},[t,n,r,o]);var l=qz(e,i[0],i[1]);return Jz(function(){s.hasValue=!0,s.value=l},[l]),tB(l),l};kk.exports=Tk;var nB=kk.exports;const rB=dm(nB);var oB={VITE_BACKEND:"http://127.0.0.1:8080",BASE_URL:"/",MODE:"production",DEV:!1,PROD:!0,SSR:!1};const MC=e=>{let t;const n=new Set,r=(u,f)=>{const p=typeof u=="function"?u(t):u;if(!Object.is(p,t)){const m=t;t=f??typeof p!="object"?p:Object.assign({},t,p),n.forEach(g=>g(t,m))}},o=()=>t,l={setState:r,getState:o,subscribe:u=>(n.add(u),()=>n.delete(u)),destroy:()=>{(oB?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),n.clear()}};return t=e(r,o,l),l},iB=e=>e?MC(e):MC,{useDebugValue:sB}=je,{useSyncExternalStoreWithSelector:aB}=rB;function lB(e,t=e.getState,n){const r=aB(e.subscribe,e.getState,e.getServerState||e.getState,t,n);return sB(r),r}const OC=(e,t)=>{const n=iB(e),r=(o,i=t)=>lB(n,o,i);return Object.assign(r,n),r},cB=(e,t)=>e?OC(e,t):OC,uB=1,dB=1e6;let S0=0;function fB(){return S0=(S0+1)%Number.MAX_VALUE,S0.toString()}const _0=new Map,NC=e=>{if(_0.has(e))return;const t=setTimeout(()=>{_0.delete(e),Iu({type:"REMOVE_TOAST",toastId:e})},dB);_0.set(e,t)},hB=(e,t)=>{switch(t.type){case"ADD_TOAST":return{...e,toasts:[t.toast,...e.toasts].slice(0,uB)};case"UPDATE_TOAST":return{...e,toasts:e.toasts.map(n=>n.id===t.toast.id?{...n,...t.toast}:n)};case"DISMISS_TOAST":{const{toastId:n}=t;return n?NC(n):e.toasts.forEach(r=>{NC(r.id)}),{...e,toasts:e.toasts.map(r=>r.id===n||n===void 0?{...r,open:!1}:r)}}case"REMOVE_TOAST":return t.toastId===void 0?{...e,toasts:[]}:{...e,toasts:e.toasts.filter(n=>n.id!==t.toastId)}}},Yh=[];let Xh={toasts:[]};function Iu(e){Xh=hB(Xh,e),Yh.forEach(t=>{t(Xh)})}function ul({...e}){const t=fB(),n=o=>Iu({type:"UPDATE_TOAST",toast:{...o,id:t}}),r=()=>Iu({type:"DISMISS_TOAST",toastId:t});return Iu({type:"ADD_TOAST",toast:{...e,id:t,open:!0,onOpenChange:o=>{o||r()}}}),{id:t,dismiss:r,update:n}}function Id(){const[e,t]=d.useState(Xh);return d.useEffect(()=>(Yh.push(t),()=>{const n=Yh.indexOf(t);n>-1&&Yh.splice(n,1)}),[e]),{...e,toast:ul,dismiss:n=>Iu({type:"DISMISS_TOAST",toastId:n})}}const ea={file:null,paintByExampleFile:null,customMask:null,imageHeight:0,imageWidth:0,isInpainting:!1,isPluginRunning:!1,isAdjustingMask:!1,disableShortCuts:!1,windowSize:{height:600,width:800},editorState:{baseBrushSize:cF,brushSizeScale:1,renders:[],extraMasks:[],prevExtraMasks:[],temporaryMasks:[],lineGroups:[],lastLineGroup:[],curLineGroup:[],redoRenders:[],redoCurLines:[],redoLineGroups:[]},interactiveSegState:{isInteractiveSeg:!1,tmpInteractiveSegMask:null,clicks:[]},cropperState:{x:0,y:0,width:512,height:512},extenderState:{x:0,y:0,width:512,height:512},isCropperExtenderResizing:!1,fileManagerState:{sortBy:Es.CTIME,sortOrder:Ou.DESCENDING,layout:"masonry",searchText:"",inputDirectory:"",outputDirectory:""},serverConfig:{plugins:[],modelInfos:[],removeBGModel:"briaai/RMBG-1.4",removeBGModels:[],realesrganModel:"realesr-general-x4v3",realesrganModels:[],interactiveSegModel:"vit_b",interactiveSegModels:[],enableFileManager:!1,enableAutoSaving:!1,enableControlnet:!1,controlnetMethod:"lllyasviel/control_v11p_sd15_canny",disableModelSwitch:!1,isDesktop:!1,samplers:["DPM++ 2M SDE Karras"]},settings:{model:{name:"lama",path:"lama",model_type:"inpaint",support_controlnet:!1,support_strength:!1,support_outpainting:!1,controlnets:[],support_freeu:!1,support_lcm_lora:!1,is_single_file_diffusers:!1,need_prompt:!1},enableControlnet:!1,showCropper:!1,showExtender:!1,extenderDirection:Ln.xy,enableDownloadMask:!1,enableManualInpainting:!1,enableUploadMask:!1,enableAutoExtractPrompt:!0,ldmSteps:30,ldmSampler:Qw.ddim,zitsWireframe:!0,cv2Radius:5,cv2Flag:Jw.INPAINT_NS,prompt:"",negativePrompt:hF,seed:42,seedFixed:!1,sdMaskBlur:12,sdStrength:1,sdSteps:50,sdGuidanceScale:7.5,sdSampler:"DPM++ 2M",sdMatchHistograms:!1,sdScale:1,p2pImageGuidanceScale:1.5,controlnetConditioningScale:.4,controlnetMethod:"lllyasviel/control_v11p_sd15_canny",enableLCMLora:!1,enableFreeu:!1,freeuConfig:{s1:.9,s2:.2,b1:1.2,b2:1.4},powerpaintTask:Ol.text_guided,adjustMaskKernelSize:12}},bt=cB()(_z(Lz((e,t)=>({...ea,showPrevMask:async()=>{if(t().settings.showExtender)return;const{lastLineGroup:n,curLineGroup:r,prevExtraMasks:o,extraMasks:i}=t().editorState;if(r.length!==0||i.length!==0)return;const{imageWidth:s,imageHeight:l}=t(),u=Wh(s,l,[n],o,Uh);try{const f=await dC(u);e(p=>{p.editorState.temporaryMasks.push(f)})}catch(f){console.error(f);return}},hidePrevMask:()=>{e(n=>{n.editorState.temporaryMasks=[]})},getCurrentTargetFile:async()=>{const n=t().file,r=t().editorState.renders;let o=n;if(r.length>0){const i=r[r.length-1];o=await Nu(i.currentSrc,n.name,n.type)}return o},runInpainting:async()=>{const{isInpainting:n,file:r,paintByExampleFile:o,imageWidth:i,imageHeight:s,settings:l,cropperState:u,extenderState:f}=t();if(n||r===null||t().settings.model.support_outpainting&&l.showExtender&&f.height===s&&f.width===i)return;const{lastLineGroup:p,curLineGroup:m,lineGroups:g,renders:y,prevExtraMasks:x,extraMasks:S}=t().editorState,E=m.length===0&&S.length===0&&!l.showExtender;let _=[],b=[];if(E===!0?(b=p,_=x):(b=m,_=S),b.length===0&&_===null&&!l.showExtender){ul({variant:"destructive",description:"Please draw mask on picture"});return}const C=[...g,b];e(O=>{O.isInpainting=!0});let R=r;if(E===!0){if(y.length>1){const O=y[y.length-2];R=await Nu(O.currentSrc,r.name,r.type)}}else if(y.length>0){const O=y[y.length-1];R=await Nu(O.currentSrc,r.name,r.type)}const P=Wh(i,s,[b],_,Uh);if(E){const O=await dC(P);e(A=>{A.editorState.temporaryMasks=[O]})}try{const O=await zj(R,l,u,f,uC(P.toDataURL()),o),{blob:A,seed:D}=O;D&&t().setSeed(parseInt(D,10));const B=new Image;await Vh(B,A);const V=[...y,B];t().setImageSize(B.width,B.height),t().updateEditorState({renders:V,lineGroups:C,lastLineGroup:b,curLineGroup:[],extraMasks:[],prevExtraMasks:_})}catch(O){ul({variant:"destructive",description:O.message?O.message:O.toString()})}t().resetRedoState(),e(O=>{O.isInpainting=!1,O.editorState.temporaryMasks=[]})},runRenderablePlugin:async(n,r,o={upscale:1})=>{const{renders:i,lineGroups:s}=t().editorState;e(l=>{l.isPluginRunning=!0});try{const l=new Date,u=await t().getCurrentTargetFile(),f=await wk(n,r,u,o.upscale),{blob:p}=f;if(n){const y=new Image;await Vh(y,p),e(x=>{x.editorState.extraMasks.push(y)})}else{const y=new Image;await Vh(y,p),t().setImageSize(y.width,y.height);const x=[...i,y],S=[...s,[]];t().updateEditorState({renders:x,lineGroups:S})}const g=new Date().getTime()-l.getTime();ul({description:`Run ${r} successfully in ${g/1e3}s`})}catch(l){ul({variant:"destructive",description:l.message?l.message:l.toString()})}e(l=>{l.isPluginRunning=!1})},updateEditorState:n=>{e(r=>{r.editorState={...r.editorState,...n}})},cleanCurLineGroup:()=>{t().updateEditorState({curLineGroup:[]})},handleCanvasMouseDown:n=>{let r=[];const o=t();o.runMannually()&&(r=[...o.editorState.curLineGroup]),r.push({size:o.getBrushSize(),pts:[n]}),e(i=>{i.editorState.curLineGroup=r})},handleCanvasMouseMove:n=>{e(r=>{const o=r.editorState.curLineGroup;o.length&&o[o.length-1].pts.push(n)})},runMannually:()=>{const n=t();return n.settings.enableManualInpainting||n.settings.model.model_type!==fs},getIsProcessing:()=>t().isInpainting||t().isPluginRunning||t().isAdjustingMask,isSD:()=>t().settings.model.model_type!==fs,undoDisabled:()=>{const n=t().editorState;if(n.renders.length>0)return!1;if(t().runMannually()){if(n.curLineGroup.length===0)return!0}else if(n.renders.length===0)return!0;return!1},undo:()=>{t().runMannually()&&t().editorState.curLineGroup.length!==0?e(n=>{const r=n.editorState;if(r.curLineGroup.length===0)return;r.lastLineGroup=[];const o=r.curLineGroup.pop();r.redoCurLines.push(o)}):e(n=>{const r=n.editorState;if(r.renders.length===0||r.lineGroups.length===0)return;const o=r.lineGroups.pop();r.redoLineGroups.push(o),r.redoCurLines=[],r.curLineGroup=[];const i=r.renders.pop();r.redoRenders.push(i)})},redoDisabled:()=>{const n=t().editorState;if(n.redoRenders.length>0)return!1;if(t().runMannually()){if(n.redoCurLines.length===0)return!0}else if(n.redoRenders.length===0)return!0;return!1},redo:()=>{t().runMannually()&&t().editorState.redoCurLines.length!==0?e(n=>{const r=n.editorState;if(r.redoCurLines.length===0)return;const o=r.redoCurLines.pop();r.curLineGroup.push(o)}):e(n=>{const r=n.editorState;if(r.redoRenders.length===0||r.redoLineGroups.length===0)return;const o=r.redoLineGroups.pop();r.lineGroups.push(o),r.curLineGroup=[];const i=r.redoRenders.pop();r.renders.push(i)})},resetRedoState:()=>{e(n=>{n.editorState.redoCurLines=[],n.editorState.redoLineGroups=[],n.editorState.redoRenders=[]})},updateAppState:n=>{e(()=>n)},getBrushSize:()=>t().editorState.baseBrushSize*t().editorState.brushSizeScale,showPromptInput:()=>{const n=t().settings.model;return n.model_type!==fs&&n.name!==XR},setServerConfig:n=>{e(r=>{r.serverConfig=n,r.settings.enableControlnet=n.enableControlnet,r.settings.controlnetMethod=n.controlnetMethod})},updateSettings:n=>{e(r=>{r.settings={...r.settings,...n}})},setModel:n=>{e(r=>{r.settings.model=n,n.support_controlnet&&!n.controlnets.includes(r.settings.controlnetMethod)&&(r.settings.controlnetMethod=n.controlnets[0])})},updateFileManagerState:n=>{e(r=>{r.fileManagerState={...r.fileManagerState,...n}})},updateInteractiveSegState:n=>{e(r=>({...r,interactiveSegState:{...r.interactiveSegState,...n}}))},resetInteractiveSegState:()=>{t().updateInteractiveSegState(ea.interactiveSegState)},handleInteractiveSegAccept:()=>{e(n=>{n.interactiveSegState.tmpInteractiveSegMask&&n.editorState.extraMasks.push(n.interactiveSegState.tmpInteractiveSegMask),n.interactiveSegState={...ea.interactiveSegState}})},setIsInpainting:n=>e(r=>{r.isInpainting=n}),setFile:async n=>{if(t().settings.enableAutoExtractPrompt)try{const r=await Kj(n);r.prompt&&e(o=>{o.settings.prompt=r.prompt}),r.negative_prompt&&e(o=>{o.settings.negativePrompt=r.negative_prompt})}catch(r){ul({variant:"destructive",description:r.message?r.message:r.toString()})}e(r=>{r.file=n,r.interactiveSegState=ea.interactiveSegState,r.editorState=ea.editorState,r.cropperState=ea.cropperState})},setCustomFile:n=>e(r=>{r.customMask=n}),setBaseBrushSize:n=>e(r=>{r.editorState.baseBrushSize=n}),setImageSize:(n,r)=>{e(o=>{o.imageWidth=n,o.imageHeight=r,o.editorState.brushSizeScale=Math.max(Math.min(n,r),512)/512}),t().resetExtender(n,r)},setCropperX:n=>e(r=>{r.cropperState.x=n}),setCropperY:n=>e(r=>{r.cropperState.y=n}),setCropperWidth:n=>e(r=>{r.cropperState.width=n}),setCropperHeight:n=>e(r=>{r.cropperState.height=n}),setExtenderX:n=>e(r=>{r.extenderState.x=n}),setExtenderY:n=>e(r=>{r.extenderState.y=n}),setExtenderWidth:n=>e(r=>{r.extenderState.width=n}),setExtenderHeight:n=>e(r=>{r.extenderState.height=n}),setIsCropperExtenderResizing:n=>e(r=>{r.isCropperExtenderResizing=n}),updateExtenderDirection:n=>{console.log(`updateExtenderDirection: ${JSON.stringify(t().extenderState)}`),e(r=>{r.settings.extenderDirection=n,r.extenderState.x=0,r.extenderState.y=0,r.extenderState.width=r.imageWidth,r.extenderState.height=r.imageHeight}),t().updateExtenderByBuiltIn(n,1.5)},updateExtenderByBuiltIn:(n,r)=>{const o={...ea.extenderState};let{x:i,y:s,width:l,height:u}=o;const{imageWidth:f,imageHeight:p}=t();switch(l=f,u=p,n){case Ln.x:i=-Math.ceil(f*(r-1)/2),l=Math.ceil(f*r);break;case Ln.y:s=-Math.ceil(p*(r-1)/2),u=Math.ceil(p*r);break;case Ln.xy:i=-Math.ceil(f*(r-1)/2),s=-Math.ceil(p*(r-1)/2),l=Math.ceil(f*r),u=Math.ceil(p*r);break}e(m=>{m.extenderState.x=i,m.extenderState.y=s,m.extenderState.width=l,m.extenderState.height=u})},resetExtender:(n,r)=>{e(o=>{o.extenderState.x=0,o.extenderState.y=0,o.extenderState.width=n,o.extenderState.height=r})},setSeed:n=>e(r=>{r.settings.seed=n}),adjustMask:async n=>{const{imageWidth:r,imageHeight:o}=t(),{curLineGroup:i,extraMasks:s}=t().editorState,{adjustMaskKernelSize:l}=t().settings;if(i.length===0&&s.length===0)return;e(g=>{g.isAdjustingMask=!0});const u=Wh(r,o,[i],s,Uh),f=uC(u.toDataURL()),p=await Gj(f,n,l),m=await mF(p);e(g=>{g.editorState.extraMasks=[m],g.editorState.curLineGroup=[]}),e(g=>{g.isAdjustingMask=!1})},clearMask:()=>{e(n=>{n.editorState.extraMasks=[],n.editorState.curLineGroup=[]})}})),{name:"ZUSTAND_STATE",version:1,partialize:e=>Object.fromEntries(Object.entries(e).filter(([t])=>["fileManagerState","settings"].includes(t)))}),Ez),Bm=d.forwardRef(({className:e,type:t,...n},r)=>{const o=bt(l=>l.updateAppState),i=()=>{o({disableShortCuts:!0})},s=()=>{o({disableShortCuts:!1})};return v.jsx("input",{type:t,className:_e("flex h-8 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",e),ref:r,autoComplete:"off",tabIndex:-1,onFocus:i,onBlur:s,...n})});Bm.displayName="Input";const Yn=d.forwardRef(({numberValue:e,allowFloat:t,onNumberValueChange:n,...r},o)=>{const[i,s]=d.useState(e.toString());d.useEffect(()=>{i!==e.toString()+"."&&s(e.toString())},[e]);const l=u=>{let p=u.target.value;if(t){if(p=p.replace(/[^0-9.]/g,"").replace(/(\..*?)\..*/g,"$1"),p.length===0){n(0);return}n(parseFloat(p))}else{if(p=p.replace(/\D/g,""),p.length===0){n(0);return}n(parseInt(p,10))}s(p)};return v.jsx(Bm,{ref:o,value:i,onInput:l,...r})});function ue(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 pB(e,t){const n=d.createContext(t);function r(i){const{children:s,...l}=i,u=d.useMemo(()=>l,Object.values(l));return d.createElement(n.Provider,{value:u},s)}function o(i){const s=d.useContext(n);if(s)return s;if(t!==void 0)return t;throw new Error(`\`${i}\` must be used within \`${e}\``)}return r.displayName=e+"Provider",[r,o]}function Mn(e,t=[]){let n=[];function r(i,s){const l=d.createContext(s),u=n.length;n=[...n,s];function f(m){const{scope:g,children:y,...x}=m,S=(g==null?void 0:g[e][u])||l,E=d.useMemo(()=>x,Object.values(x));return d.createElement(S.Provider,{value:E},y)}function p(m,g){const y=(g==null?void 0:g[e][u])||l,x=d.useContext(y);if(x)return x;if(s!==void 0)return s;throw new Error(`\`${m}\` must be used within \`${i}\``)}return f.displayName=i+"Provider",[f,p]}const o=()=>{const i=n.map(s=>d.createContext(s));return function(l){const u=(l==null?void 0:l[e])||i;return d.useMemo(()=>({[`__scope${e}`]:{...l,[e]:u}}),[l,u])}};return o.scopeName=e,[r,mB(o,...t)]}function mB(...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(i){const s=r.reduce((l,{useScope:u,scopeName:f})=>{const m=u(i)[`__scope${f}`];return{...l,...m}},{});return d.useMemo(()=>({[`__scope${t.scopeName}`]:s}),[s])}};return n.scopeName=t.scopeName,n}const gB=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","span","svg","ul"],Ae=gB.reduce((e,t)=>{const n=d.forwardRef((r,o)=>{const{asChild:i,...s}=r,l=i?Zo:t;return d.useEffect(()=>{window[Symbol.for("radix-ui")]=!0},[]),d.createElement(l,Y({},s,{ref:o}))});return n.displayName=`Primitive.${t}`,{...e,[t]:n}},{});function dx(e,t){e&&Is.flushSync(()=>e.dispatchEvent(t))}function Ft(e){const t=d.useRef(e);return d.useEffect(()=>{t.current=e}),d.useMemo(()=>(...n)=>{var r;return(r=t.current)===null||r===void 0?void 0:r.call(t,...n)},[])}function vB(e,t=globalThis==null?void 0:globalThis.document){const n=Ft(e);d.useEffect(()=>{const r=o=>{o.key==="Escape"&&n(o)};return t.addEventListener("keydown",r),()=>t.removeEventListener("keydown",r)},[n,t])}const l1="dismissableLayer.update",yB="dismissableLayer.pointerDownOutside",wB="dismissableLayer.focusOutside";let DC;const Mk=d.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),Ec=d.forwardRef((e,t)=>{var n;const{disableOutsidePointerEvents:r=!1,onEscapeKeyDown:o,onPointerDownOutside:i,onFocusOutside:s,onInteractOutside:l,onDismiss:u,...f}=e,p=d.useContext(Mk),[m,g]=d.useState(null),y=(n=m==null?void 0:m.ownerDocument)!==null&&n!==void 0?n:globalThis==null?void 0:globalThis.document,[,x]=d.useState({}),S=Ue(t,D=>g(D)),E=Array.from(p.layers),[_]=[...p.layersWithOutsidePointerEventsDisabled].slice(-1),b=E.indexOf(_),C=m?E.indexOf(m):-1,R=p.layersWithOutsidePointerEventsDisabled.size>0,P=C>=b,O=bB(D=>{const B=D.target,V=[...p.branches].some(J=>J.contains(B));!P||V||(i==null||i(D),l==null||l(D),D.defaultPrevented||u==null||u())},y),A=SB(D=>{const B=D.target;[...p.branches].some(J=>J.contains(B))||(s==null||s(D),l==null||l(D),D.defaultPrevented||u==null||u())},y);return vB(D=>{C===p.layers.size-1&&(o==null||o(D),!D.defaultPrevented&&u&&(D.preventDefault(),u()))},y),d.useEffect(()=>{if(m)return r&&(p.layersWithOutsidePointerEventsDisabled.size===0&&(DC=y.body.style.pointerEvents,y.body.style.pointerEvents="none"),p.layersWithOutsidePointerEventsDisabled.add(m)),p.layers.add(m),IC(),()=>{r&&p.layersWithOutsidePointerEventsDisabled.size===1&&(y.body.style.pointerEvents=DC)}},[m,y,r,p]),d.useEffect(()=>()=>{m&&(p.layers.delete(m),p.layersWithOutsidePointerEventsDisabled.delete(m),IC())},[m,p]),d.useEffect(()=>{const D=()=>x({});return document.addEventListener(l1,D),()=>document.removeEventListener(l1,D)},[]),d.createElement(Ae.div,Y({},f,{ref:S,style:{pointerEvents:R?P?"auto":"none":void 0,...e.style},onFocusCapture:ue(e.onFocusCapture,A.onFocusCapture),onBlurCapture:ue(e.onBlurCapture,A.onBlurCapture),onPointerDownCapture:ue(e.onPointerDownCapture,O.onPointerDownCapture)}))}),xB=d.forwardRef((e,t)=>{const n=d.useContext(Mk),r=d.useRef(null),o=Ue(t,r);return d.useEffect(()=>{const i=r.current;if(i)return n.branches.add(i),()=>{n.branches.delete(i)}},[n.branches]),d.createElement(Ae.div,Y({},e,{ref:o}))});function bB(e,t=globalThis==null?void 0:globalThis.document){const n=Ft(e),r=d.useRef(!1),o=d.useRef(()=>{});return d.useEffect(()=>{const i=l=>{if(l.target&&!r.current){let p=function(){Ok(yB,n,f,{discrete:!0})};var u=p;const f={originalEvent:l};l.pointerType==="touch"?(t.removeEventListener("click",o.current),o.current=p,t.addEventListener("click",o.current,{once:!0})):p()}else t.removeEventListener("click",o.current);r.current=!1},s=window.setTimeout(()=>{t.addEventListener("pointerdown",i)},0);return()=>{window.clearTimeout(s),t.removeEventListener("pointerdown",i),t.removeEventListener("click",o.current)}},[t,n]),{onPointerDownCapture:()=>r.current=!0}}function SB(e,t=globalThis==null?void 0:globalThis.document){const n=Ft(e),r=d.useRef(!1);return d.useEffect(()=>{const o=i=>{i.target&&!r.current&&Ok(wB,n,{originalEvent:i},{discrete:!1})};return t.addEventListener("focusin",o),()=>t.removeEventListener("focusin",o)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function IC(){const e=new CustomEvent(l1);document.dispatchEvent(e)}function Ok(e,t,n,{discrete:r}){const o=n.originalEvent.target,i=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&o.addEventListener(e,t,{once:!0}),r?dx(o,i):o.dispatchEvent(i)}const _B=Ec,EB=xB,An=globalThis!=null&&globalThis.document?d.useLayoutEffect:()=>{},CB=U9.useId||(()=>{});let $B=0;function nr(e){const[t,n]=d.useState(CB());return An(()=>{e||n(r=>r??String($B++))},[e]),e||(t?`radix-${t}`:"")}const RB=["top","right","bottom","left"],Ts=Math.min,hr=Math.max,Ip=Math.round,dh=Math.floor,Ps=e=>({x:e,y:e}),kB={left:"right",right:"left",bottom:"top",top:"bottom"},TB={start:"end",end:"start"};function c1(e,t,n){return hr(e,Ts(t,n))}function Ci(e,t){return typeof e=="function"?e(t):e}function $i(e){return e.split("-")[0]}function Cc(e){return e.split("-")[1]}function fx(e){return e==="x"?"y":"x"}function hx(e){return e==="y"?"height":"width"}function $c(e){return["top","bottom"].includes($i(e))?"y":"x"}function px(e){return fx($c(e))}function PB(e,t,n){n===void 0&&(n=!1);const r=Cc(e),o=px(e),i=hx(o);let s=o==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[i]>t.floating[i]&&(s=Lp(s)),[s,Lp(s)]}function AB(e){const t=Lp(e);return[u1(e),t,u1(t)]}function u1(e){return e.replace(/start|end/g,t=>TB[t])}function MB(e,t,n){const r=["left","right"],o=["right","left"],i=["top","bottom"],s=["bottom","top"];switch(e){case"top":case"bottom":return n?t?o:r:t?r:o;case"left":case"right":return t?i:s;default:return[]}}function OB(e,t,n,r){const o=Cc(e);let i=MB($i(e),n==="start",r);return o&&(i=i.map(s=>s+"-"+o),t&&(i=i.concat(i.map(u1)))),i}function Lp(e){return e.replace(/left|right|bottom|top/g,t=>kB[t])}function NB(e){return{top:0,right:0,bottom:0,left:0,...e}}function Nk(e){return typeof e!="number"?NB(e):{top:e,right:e,bottom:e,left:e}}function Fp(e){return{...e,top:e.y,left:e.x,right:e.x+e.width,bottom:e.y+e.height}}function LC(e,t,n){let{reference:r,floating:o}=e;const i=$c(t),s=px(t),l=hx(s),u=$i(t),f=i==="y",p=r.x+r.width/2-o.width/2,m=r.y+r.height/2-o.height/2,g=r[l]/2-o[l]/2;let y;switch(u){case"top":y={x:p,y:r.y-o.height};break;case"bottom":y={x:p,y:r.y+r.height};break;case"right":y={x:r.x+r.width,y:m};break;case"left":y={x:r.x-o.width,y:m};break;default:y={x:r.x,y:r.y}}switch(Cc(t)){case"start":y[s]-=g*(n&&f?-1:1);break;case"end":y[s]+=g*(n&&f?-1:1);break}return y}const DB=async(e,t,n)=>{const{placement:r="bottom",strategy:o="absolute",middleware:i=[],platform:s}=n,l=i.filter(Boolean),u=await(s.isRTL==null?void 0:s.isRTL(t));let f=await s.getElementRects({reference:e,floating:t,strategy:o}),{x:p,y:m}=LC(f,r,u),g=r,y={},x=0;for(let S=0;S({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:o,rects:i,platform:s,elements:l,middlewareData:u}=t,{element:f,padding:p=0}=Ci(e,t)||{};if(f==null)return{};const m=Nk(p),g={x:n,y:r},y=px(o),x=hx(y),S=await s.getDimensions(f),E=y==="y",_=E?"top":"left",b=E?"bottom":"right",C=E?"clientHeight":"clientWidth",R=i.reference[x]+i.reference[y]-g[y]-i.floating[x],P=g[y]-i.reference[y],O=await(s.getOffsetParent==null?void 0:s.getOffsetParent(f));let A=O?O[C]:0;(!A||!await(s.isElement==null?void 0:s.isElement(O)))&&(A=l.floating[C]||i.floating[x]);const D=R/2-P/2,B=A/2-S[x]/2-1,V=Ts(m[_],B),J=Ts(m[b],B),G=V,se=A-S[x]-J,U=A/2-S[x]/2+D,ne=c1(G,U,se),M=!u.arrow&&Cc(o)!=null&&U!=ne&&i.reference[x]/2-(UG<=0)){var B,V;const G=(((B=i.flip)==null?void 0:B.index)||0)+1,se=P[G];if(se)return{data:{index:G,overflows:D},reset:{placement:se}};let U=(V=D.filter(ne=>ne.overflows[0]<=0).sort((ne,M)=>ne.overflows[1]-M.overflows[1])[0])==null?void 0:V.placement;if(!U)switch(y){case"bestFit":{var J;const ne=(J=D.map(M=>[M.placement,M.overflows.filter(ee=>ee>0).reduce((ee,H)=>ee+H,0)]).sort((M,ee)=>M[1]-ee[1])[0])==null?void 0:J[0];ne&&(U=ne);break}case"initialPlacement":U=l;break}if(o!==U)return{reset:{placement:U}}}return{}}}};function jC(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function zC(e){return RB.some(t=>e[t]>=0)}const LB=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n}=t,{strategy:r="referenceHidden",...o}=Ci(e,t);switch(r){case"referenceHidden":{const i=await ld(t,{...o,elementContext:"reference"}),s=jC(i,n.reference);return{data:{referenceHiddenOffsets:s,referenceHidden:zC(s)}}}case"escaped":{const i=await ld(t,{...o,altBoundary:!0}),s=jC(i,n.floating);return{data:{escapedOffsets:s,escaped:zC(s)}}}default:return{}}}}};async function FB(e,t){const{placement:n,platform:r,elements:o}=e,i=await(r.isRTL==null?void 0:r.isRTL(o.floating)),s=$i(n),l=Cc(n),u=$c(n)==="y",f=["left","top"].includes(s)?-1:1,p=i&&u?-1:1,m=Ci(t,e);let{mainAxis:g,crossAxis:y,alignmentAxis:x}=typeof m=="number"?{mainAxis:m,crossAxis:0,alignmentAxis:null}:{mainAxis:0,crossAxis:0,alignmentAxis:null,...m};return l&&typeof x=="number"&&(y=l==="end"?x*-1:x),u?{x:y*p,y:g*f}:{x:g*f,y:y*p}}const jB=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){const{x:n,y:r}=t,o=await FB(t,e);return{x:n+o.x,y:r+o.y,data:o}}}},zB=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:o}=t,{mainAxis:i=!0,crossAxis:s=!1,limiter:l={fn:E=>{let{x:_,y:b}=E;return{x:_,y:b}}},...u}=Ci(e,t),f={x:n,y:r},p=await ld(t,u),m=$c($i(o)),g=fx(m);let y=f[g],x=f[m];if(i){const E=g==="y"?"top":"left",_=g==="y"?"bottom":"right",b=y+p[E],C=y-p[_];y=c1(b,y,C)}if(s){const E=m==="y"?"top":"left",_=m==="y"?"bottom":"right",b=x+p[E],C=x-p[_];x=c1(b,x,C)}const S=l.fn({...t,[g]:y,[m]:x});return{...S,data:{x:S.x-n,y:S.y-r}}}}},BB=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:r,placement:o,rects:i,middlewareData:s}=t,{offset:l=0,mainAxis:u=!0,crossAxis:f=!0}=Ci(e,t),p={x:n,y:r},m=$c(o),g=fx(m);let y=p[g],x=p[m];const S=Ci(l,t),E=typeof S=="number"?{mainAxis:S,crossAxis:0}:{mainAxis:0,crossAxis:0,...S};if(u){const C=g==="y"?"height":"width",R=i.reference[g]-i.floating[C]+E.mainAxis,P=i.reference[g]+i.reference[C]-E.mainAxis;yP&&(y=P)}if(f){var _,b;const C=g==="y"?"width":"height",R=["top","left"].includes($i(o)),P=i.reference[m]-i.floating[C]+(R&&((_=s.offset)==null?void 0:_[m])||0)+(R?0:E.crossAxis),O=i.reference[m]+i.reference[C]+(R?0:((b=s.offset)==null?void 0:b[m])||0)-(R?E.crossAxis:0);xO&&(x=O)}return{[g]:y,[m]:x}}}},UB=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){const{placement:n,rects:r,platform:o,elements:i}=t,{apply:s=()=>{},...l}=Ci(e,t),u=await ld(t,l),f=$i(n),p=Cc(n),m=$c(n)==="y",{width:g,height:y}=r.floating;let x,S;f==="top"||f==="bottom"?(x=f,S=p===(await(o.isRTL==null?void 0:o.isRTL(i.floating))?"start":"end")?"left":"right"):(S=f,x=p==="end"?"top":"bottom");const E=y-u[x],_=g-u[S],b=!t.middlewareData.shift;let C=E,R=_;if(m){const O=g-u.left-u.right;R=p||b?Ts(_,O):O}else{const O=y-u.top-u.bottom;C=p||b?Ts(E,O):O}if(b&&!p){const O=hr(u.left,0),A=hr(u.right,0),D=hr(u.top,0),B=hr(u.bottom,0);m?R=g-2*(O!==0||A!==0?O+A:hr(u.left,u.right)):C=y-2*(D!==0||B!==0?D+B:hr(u.top,u.bottom))}await s({...t,availableWidth:R,availableHeight:C});const P=await o.getDimensions(i.floating);return g!==P.width||y!==P.height?{reset:{rects:!0}}:{}}}};function As(e){return Dk(e)?(e.nodeName||"").toLowerCase():"#document"}function vr(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Mi(e){var t;return(t=(Dk(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function Dk(e){return e instanceof Node||e instanceof vr(e).Node}function Ri(e){return e instanceof Element||e instanceof vr(e).Element}function qo(e){return e instanceof HTMLElement||e instanceof vr(e).HTMLElement}function BC(e){return typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof vr(e).ShadowRoot}function Ld(e){const{overflow:t,overflowX:n,overflowY:r,display:o}=Xr(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&!["inline","contents"].includes(o)}function VB(e){return["table","td","th"].includes(As(e))}function mx(e){const t=gx(),n=Xr(e);return n.transform!=="none"||n.perspective!=="none"||(n.containerType?n.containerType!=="normal":!1)||!t&&(n.backdropFilter?n.backdropFilter!=="none":!1)||!t&&(n.filter?n.filter!=="none":!1)||["transform","perspective","filter"].some(r=>(n.willChange||"").includes(r))||["paint","layout","strict","content"].some(r=>(n.contain||"").includes(r))}function WB(e){let t=cc(e);for(;qo(t)&&!Um(t);){if(mx(t))return t;t=cc(t)}return null}function gx(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}function Um(e){return["html","body","#document"].includes(As(e))}function Xr(e){return vr(e).getComputedStyle(e)}function Vm(e){return Ri(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.pageXOffset,scrollTop:e.pageYOffset}}function cc(e){if(As(e)==="html")return e;const t=e.assignedSlot||e.parentNode||BC(e)&&e.host||Mi(e);return BC(t)?t.host:t}function Ik(e){const t=cc(e);return Um(t)?e.ownerDocument?e.ownerDocument.body:e.body:qo(t)&&Ld(t)?t:Ik(t)}function cd(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const o=Ik(e),i=o===((r=e.ownerDocument)==null?void 0:r.body),s=vr(o);return i?t.concat(s,s.visualViewport||[],Ld(o)?o:[],s.frameElement&&n?cd(s.frameElement):[]):t.concat(o,cd(o,[],n))}function Lk(e){const t=Xr(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const o=qo(e),i=o?e.offsetWidth:n,s=o?e.offsetHeight:r,l=Ip(n)!==i||Ip(r)!==s;return l&&(n=i,r=s),{width:n,height:r,$:l}}function vx(e){return Ri(e)?e:e.contextElement}function Nl(e){const t=vx(e);if(!qo(t))return Ps(1);const n=t.getBoundingClientRect(),{width:r,height:o,$:i}=Lk(t);let s=(i?Ip(n.width):n.width)/r,l=(i?Ip(n.height):n.height)/o;return(!s||!Number.isFinite(s))&&(s=1),(!l||!Number.isFinite(l))&&(l=1),{x:s,y:l}}const HB=Ps(0);function Fk(e){const t=vr(e);return!gx()||!t.visualViewport?HB:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function KB(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==vr(e)?!1:t}function Na(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const o=e.getBoundingClientRect(),i=vx(e);let s=Ps(1);t&&(r?Ri(r)&&(s=Nl(r)):s=Nl(e));const l=KB(i,n,r)?Fk(i):Ps(0);let u=(o.left+l.x)/s.x,f=(o.top+l.y)/s.y,p=o.width/s.x,m=o.height/s.y;if(i){const g=vr(i),y=r&&Ri(r)?vr(r):r;let x=g.frameElement;for(;x&&r&&y!==g;){const S=Nl(x),E=x.getBoundingClientRect(),_=Xr(x),b=E.left+(x.clientLeft+parseFloat(_.paddingLeft))*S.x,C=E.top+(x.clientTop+parseFloat(_.paddingTop))*S.y;u*=S.x,f*=S.y,p*=S.x,m*=S.y,u+=b,f+=C,x=vr(x).frameElement}}return Fp({width:p,height:m,x:u,y:f})}function GB(e){let{rect:t,offsetParent:n,strategy:r}=e;const o=qo(n),i=Mi(n);if(n===i)return t;let s={scrollLeft:0,scrollTop:0},l=Ps(1);const u=Ps(0);if((o||!o&&r!=="fixed")&&((As(n)!=="body"||Ld(i))&&(s=Vm(n)),qo(n))){const f=Na(n);l=Nl(n),u.x=f.x+n.clientLeft,u.y=f.y+n.clientTop}return{width:t.width*l.x,height:t.height*l.y,x:t.x*l.x-s.scrollLeft*l.x+u.x,y:t.y*l.y-s.scrollTop*l.y+u.y}}function YB(e){return Array.from(e.getClientRects())}function jk(e){return Na(Mi(e)).left+Vm(e).scrollLeft}function XB(e){const t=Mi(e),n=Vm(e),r=e.ownerDocument.body,o=hr(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),i=hr(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let s=-n.scrollLeft+jk(e);const l=-n.scrollTop;return Xr(r).direction==="rtl"&&(s+=hr(t.clientWidth,r.clientWidth)-o),{width:o,height:i,x:s,y:l}}function ZB(e,t){const n=vr(e),r=Mi(e),o=n.visualViewport;let i=r.clientWidth,s=r.clientHeight,l=0,u=0;if(o){i=o.width,s=o.height;const f=gx();(!f||f&&t==="fixed")&&(l=o.offsetLeft,u=o.offsetTop)}return{width:i,height:s,x:l,y:u}}function qB(e,t){const n=Na(e,!0,t==="fixed"),r=n.top+e.clientTop,o=n.left+e.clientLeft,i=qo(e)?Nl(e):Ps(1),s=e.clientWidth*i.x,l=e.clientHeight*i.y,u=o*i.x,f=r*i.y;return{width:s,height:l,x:u,y:f}}function UC(e,t,n){let r;if(t==="viewport")r=ZB(e,n);else if(t==="document")r=XB(Mi(e));else if(Ri(t))r=qB(t,n);else{const o=Fk(e);r={...t,x:t.x-o.x,y:t.y-o.y}}return Fp(r)}function zk(e,t){const n=cc(e);return n===t||!Ri(n)||Um(n)?!1:Xr(n).position==="fixed"||zk(n,t)}function QB(e,t){const n=t.get(e);if(n)return n;let r=cd(e,[],!1).filter(l=>Ri(l)&&As(l)!=="body"),o=null;const i=Xr(e).position==="fixed";let s=i?cc(e):e;for(;Ri(s)&&!Um(s);){const l=Xr(s),u=mx(s);!u&&l.position==="fixed"&&(o=null),(i?!u&&!o:!u&&l.position==="static"&&!!o&&["absolute","fixed"].includes(o.position)||Ld(s)&&!u&&zk(e,s))?r=r.filter(p=>p!==s):o=l,s=cc(s)}return t.set(e,r),r}function JB(e){let{element:t,boundary:n,rootBoundary:r,strategy:o}=e;const s=[...n==="clippingAncestors"?QB(t,this._c):[].concat(n),r],l=s[0],u=s.reduce((f,p)=>{const m=UC(t,p,o);return f.top=hr(m.top,f.top),f.right=Ts(m.right,f.right),f.bottom=Ts(m.bottom,f.bottom),f.left=hr(m.left,f.left),f},UC(t,l,o));return{width:u.right-u.left,height:u.bottom-u.top,x:u.left,y:u.top}}function eU(e){return Lk(e)}function tU(e,t,n){const r=qo(t),o=Mi(t),i=n==="fixed",s=Na(e,!0,i,t);let l={scrollLeft:0,scrollTop:0};const u=Ps(0);if(r||!r&&!i)if((As(t)!=="body"||Ld(o))&&(l=Vm(t)),r){const f=Na(t,!0,i,t);u.x=f.x+t.clientLeft,u.y=f.y+t.clientTop}else o&&(u.x=jk(o));return{x:s.left+l.scrollLeft-u.x,y:s.top+l.scrollTop-u.y,width:s.width,height:s.height}}function VC(e,t){return!qo(e)||Xr(e).position==="fixed"?null:t?t(e):e.offsetParent}function Bk(e,t){const n=vr(e);if(!qo(e))return n;let r=VC(e,t);for(;r&&VB(r)&&Xr(r).position==="static";)r=VC(r,t);return r&&(As(r)==="html"||As(r)==="body"&&Xr(r).position==="static"&&!mx(r))?n:r||WB(e)||n}const nU=async function(e){let{reference:t,floating:n,strategy:r}=e;const o=this.getOffsetParent||Bk,i=this.getDimensions;return{reference:tU(t,await o(n),r),floating:{x:0,y:0,...await i(n)}}};function rU(e){return Xr(e).direction==="rtl"}const oU={convertOffsetParentRelativeRectToViewportRelativeRect:GB,getDocumentElement:Mi,getClippingRect:JB,getOffsetParent:Bk,getElementRects:nU,getClientRects:YB,getDimensions:eU,getScale:Nl,isElement:Ri,isRTL:rU};function iU(e,t){let n=null,r;const o=Mi(e);function i(){clearTimeout(r),n&&n.disconnect(),n=null}function s(l,u){l===void 0&&(l=!1),u===void 0&&(u=1),i();const{left:f,top:p,width:m,height:g}=e.getBoundingClientRect();if(l||t(),!m||!g)return;const y=dh(p),x=dh(o.clientWidth-(f+m)),S=dh(o.clientHeight-(p+g)),E=dh(f),b={rootMargin:-y+"px "+-x+"px "+-S+"px "+-E+"px",threshold:hr(0,Ts(1,u))||1};let C=!0;function R(P){const O=P[0].intersectionRatio;if(O!==u){if(!C)return s();O?s(!1,O):r=setTimeout(()=>{s(!1,1e-7)},100)}C=!1}try{n=new IntersectionObserver(R,{...b,root:o.ownerDocument})}catch{n=new IntersectionObserver(R,b)}n.observe(e)}return s(!0),i}function sU(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:o=!0,ancestorResize:i=!0,elementResize:s=typeof ResizeObserver=="function",layoutShift:l=typeof IntersectionObserver=="function",animationFrame:u=!1}=r,f=vx(e),p=o||i?[...f?cd(f):[],...cd(t)]:[];p.forEach(_=>{o&&_.addEventListener("scroll",n,{passive:!0}),i&&_.addEventListener("resize",n)});const m=f&&l?iU(f,n):null;let g=-1,y=null;s&&(y=new ResizeObserver(_=>{let[b]=_;b&&b.target===f&&y&&(y.unobserve(t),cancelAnimationFrame(g),g=requestAnimationFrame(()=>{y&&y.observe(t)})),n()}),f&&!u&&y.observe(f),y.observe(t));let x,S=u?Na(e):null;u&&E();function E(){const _=Na(e);S&&(_.x!==S.x||_.y!==S.y||_.width!==S.width||_.height!==S.height)&&n(),S=_,x=requestAnimationFrame(E)}return n(),()=>{p.forEach(_=>{o&&_.removeEventListener("scroll",n),i&&_.removeEventListener("resize",n)}),m&&m(),y&&y.disconnect(),y=null,u&&cancelAnimationFrame(x)}}const aU=(e,t,n)=>{const r=new Map,o={platform:oU,...n},i={...o.platform,_c:r};return DB(e,t,{...o,platform:i})},lU=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:o}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?FC({element:r.current,padding:o}).fn(n):{}:r?FC({element:r,padding:o}).fn(n):{}}}};var Zh=typeof document<"u"?d.useLayoutEffect:d.useEffect;function jp(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(!jp(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(!{}.hasOwnProperty.call(t,o[r]))return!1;for(r=n;r--!==0;){const i=o[r];if(!(i==="_owner"&&e.$$typeof)&&!jp(e[i],t[i]))return!1}return!0}return e!==e&&t!==t}function Uk(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function WC(e,t){const n=Uk(e);return Math.round(t*n)/n}function HC(e){const t=d.useRef(e);return Zh(()=>{t.current=e}),t}function cU(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:o,elements:{reference:i,floating:s}={},transform:l=!0,whileElementsMounted:u,open:f}=e,[p,m]=d.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[g,y]=d.useState(r);jp(g,r)||y(r);const[x,S]=d.useState(null),[E,_]=d.useState(null),b=d.useCallback(M=>{M!=O.current&&(O.current=M,S(M))},[S]),C=d.useCallback(M=>{M!==A.current&&(A.current=M,_(M))},[_]),R=i||x,P=s||E,O=d.useRef(null),A=d.useRef(null),D=d.useRef(p),B=HC(u),V=HC(o),J=d.useCallback(()=>{if(!O.current||!A.current)return;const M={placement:t,strategy:n,middleware:g};V.current&&(M.platform=V.current),aU(O.current,A.current,M).then(ee=>{const H={...ee,isPositioned:!0};G.current&&!jp(D.current,H)&&(D.current=H,Is.flushSync(()=>{m(H)}))})},[g,t,n,V]);Zh(()=>{f===!1&&D.current.isPositioned&&(D.current.isPositioned=!1,m(M=>({...M,isPositioned:!1})))},[f]);const G=d.useRef(!1);Zh(()=>(G.current=!0,()=>{G.current=!1}),[]),Zh(()=>{if(R&&(O.current=R),P&&(A.current=P),R&&P){if(B.current)return B.current(R,P,J);J()}},[R,P,J,B]);const se=d.useMemo(()=>({reference:O,floating:A,setReference:b,setFloating:C}),[b,C]),U=d.useMemo(()=>({reference:R,floating:P}),[R,P]),ne=d.useMemo(()=>{const M={position:n,left:0,top:0};if(!U.floating)return M;const ee=WC(U.floating,p.x),H=WC(U.floating,p.y);return l?{...M,transform:"translate("+ee+"px, "+H+"px)",...Uk(U.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:ee,top:H}},[n,l,U.floating,p.x,p.y]);return d.useMemo(()=>({...p,update:J,refs:se,elements:U,floatingStyles:ne}),[p,J,se,U,ne])}function yx(e){const[t,n]=d.useState(void 0);return An(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(o=>{if(!Array.isArray(o)||!o.length)return;const i=o[0];let s,l;if("borderBoxSize"in i){const u=i.borderBoxSize,f=Array.isArray(u)?u[0]:u;s=f.inlineSize,l=f.blockSize}else s=e.offsetWidth,l=e.offsetHeight;n({width:s,height:l})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}const Vk="Popper",[Wk,Fs]=Mn(Vk),[uU,Hk]=Wk(Vk),dU=e=>{const{__scopePopper:t,children:n}=e,[r,o]=d.useState(null);return d.createElement(uU,{scope:t,anchor:r,onAnchorChange:o},n)},fU="PopperAnchor",hU=d.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...o}=e,i=Hk(fU,n),s=d.useRef(null),l=Ue(t,s);return d.useEffect(()=>{i.onAnchorChange((r==null?void 0:r.current)||s.current)}),r?null:d.createElement(Ae.div,Y({},o,{ref:l}))}),Kk="PopperContent",[pU,pte]=Wk(Kk),mU=d.forwardRef((e,t)=>{var n,r,o,i,s,l,u,f;const{__scopePopper:p,side:m="bottom",sideOffset:g=0,align:y="center",alignOffset:x=0,arrowPadding:S=0,avoidCollisions:E=!0,collisionBoundary:_=[],collisionPadding:b=0,sticky:C="partial",hideWhenDetached:R=!1,updatePositionStrategy:P="optimized",onPlaced:O,...A}=e,D=Hk(Kk,p),[B,V]=d.useState(null),J=Ue(t,Kt=>V(Kt)),[G,se]=d.useState(null),U=yx(G),ne=(n=U==null?void 0:U.width)!==null&&n!==void 0?n:0,M=(r=U==null?void 0:U.height)!==null&&r!==void 0?r:0,ee=m+(y!=="center"?"-"+y:""),H=typeof b=="number"?b:{top:0,right:0,bottom:0,left:0,...b},X=Array.isArray(_)?_:[_],W=X.length>0,le={padding:H,boundary:X.filter(gU),altBoundary:W},{refs:pe,floatingStyles:$e,placement:Ve,isPositioned:We,middlewareData:Ne}=cU({strategy:"fixed",placement:ee,whileElementsMounted:(...Kt)=>sU(...Kt,{animationFrame:P==="always"}),elements:{reference:D.anchor},middleware:[jB({mainAxis:g+M,alignmentAxis:x}),E&&zB({mainAxis:!0,crossAxis:!1,limiter:C==="partial"?BB():void 0,...le}),E&&IB({...le}),UB({...le,apply:({elements:Kt,rects:Er,availableWidth:gt,availableHeight:Vs})=>{const{width:L,height:Z}=Er.reference,q=Kt.floating.style;q.setProperty("--radix-popper-available-width",`${gt}px`),q.setProperty("--radix-popper-available-height",`${Vs}px`),q.setProperty("--radix-popper-anchor-width",`${L}px`),q.setProperty("--radix-popper-anchor-height",`${Z}px`)}}),G&&lU({element:G,padding:S}),vU({arrowWidth:ne,arrowHeight:M}),R&&LB({strategy:"referenceHidden",...le})]}),[fe,xe]=Gk(Ve),Re=Ft(O);An(()=>{We&&(Re==null||Re())},[We,Re]);const Me=(o=Ne.arrow)===null||o===void 0?void 0:o.x,Oe=(i=Ne.arrow)===null||i===void 0?void 0:i.y,ze=((s=Ne.arrow)===null||s===void 0?void 0:s.centerOffset)!==0,[Mt,ct]=d.useState();return An(()=>{B&&ct(window.getComputedStyle(B).zIndex)},[B]),d.createElement("div",{ref:pe.setFloating,"data-radix-popper-content-wrapper":"",style:{...$e,transform:We?$e.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:Mt,"--radix-popper-transform-origin":[(l=Ne.transformOrigin)===null||l===void 0?void 0:l.x,(u=Ne.transformOrigin)===null||u===void 0?void 0:u.y].join(" ")},dir:e.dir},d.createElement(pU,{scope:p,placedSide:fe,onArrowChange:se,arrowX:Me,arrowY:Oe,shouldHideArrow:ze},d.createElement(Ae.div,Y({"data-side":fe,"data-align":xe},A,{ref:J,style:{...A.style,animation:We?void 0:"none",opacity:(f=Ne.hide)!==null&&f!==void 0&&f.referenceHidden?0:void 0}}))))});function gU(e){return e!==null}const vU=e=>({name:"transformOrigin",options:e,fn(t){var n,r,o,i,s;const{placement:l,rects:u,middlewareData:f}=t,m=((n=f.arrow)===null||n===void 0?void 0:n.centerOffset)!==0,g=m?0:e.arrowWidth,y=m?0:e.arrowHeight,[x,S]=Gk(l),E={start:"0%",center:"50%",end:"100%"}[S],_=((r=(o=f.arrow)===null||o===void 0?void 0:o.x)!==null&&r!==void 0?r:0)+g/2,b=((i=(s=f.arrow)===null||s===void 0?void 0:s.y)!==null&&i!==void 0?i:0)+y/2;let C="",R="";return x==="bottom"?(C=m?E:`${_}px`,R=`${-y}px`):x==="top"?(C=m?E:`${_}px`,R=`${u.floating.height+y}px`):x==="right"?(C=`${-y}px`,R=m?E:`${b}px`):x==="left"&&(C=`${u.floating.width+y}px`,R=m?E:`${b}px`),{data:{x:C,y:R}}}});function Gk(e){const[t,n="center"]=e.split("-");return[t,n]}const Fd=dU,Wm=hU,Hm=mU,jd=d.forwardRef((e,t)=>{var n;const{container:r=globalThis==null||(n=globalThis.document)===null||n===void 0?void 0:n.body,...o}=e;return r?QI.createPortal(d.createElement(Ae.div,Y({},o,{ref:t})),r):null});function yU(e,t){return d.useReducer((n,r)=>{const o=t[n][r];return o??n},e)}const Sn=e=>{const{present:t,children:n}=e,r=wU(t),o=typeof n=="function"?n({present:r.isPresent}):d.Children.only(n),i=Ue(r.ref,o.ref);return typeof n=="function"||r.isPresent?d.cloneElement(o,{ref:i}):null};Sn.displayName="Presence";function wU(e){const[t,n]=d.useState(),r=d.useRef({}),o=d.useRef(e),i=d.useRef("none"),s=e?"mounted":"unmounted",[l,u]=yU(s,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return d.useEffect(()=>{const f=fh(r.current);i.current=l==="mounted"?f:"none"},[l]),An(()=>{const f=r.current,p=o.current;if(p!==e){const g=i.current,y=fh(f);e?u("MOUNT"):y==="none"||(f==null?void 0:f.display)==="none"?u("UNMOUNT"):u(p&&g!==y?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,u]),An(()=>{if(t){const f=m=>{const y=fh(r.current).includes(m.animationName);m.target===t&&y&&Is.flushSync(()=>u("ANIMATION_END"))},p=m=>{m.target===t&&(i.current=fh(r.current))};return t.addEventListener("animationstart",p),t.addEventListener("animationcancel",f),t.addEventListener("animationend",f),()=>{t.removeEventListener("animationstart",p),t.removeEventListener("animationcancel",f),t.removeEventListener("animationend",f)}}else u("ANIMATION_END")},[t,u]),{isPresent:["mounted","unmountSuspended"].includes(l),ref:d.useCallback(f=>{f&&(r.current=getComputedStyle(f)),n(f)},[])}}function fh(e){return(e==null?void 0:e.animationName)||"none"}function Zr({prop:e,defaultProp:t,onChange:n=()=>{}}){const[r,o]=xU({defaultProp:t,onChange:n}),i=e!==void 0,s=i?e:r,l=Ft(n),u=d.useCallback(f=>{if(i){const m=typeof f=="function"?f(e):f;m!==e&&l(m)}else o(f)},[i,e,o,l]);return[s,u]}function xU({defaultProp:e,onChange:t}){const n=d.useState(e),[r]=n,o=d.useRef(r),i=Ft(t);return d.useEffect(()=>{o.current!==r&&(i(r),o.current=r)},[r,o,i]),n}const Km=d.forwardRef((e,t)=>d.createElement(Ae.span,Y({},e,{ref:t,style:{position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal",...e.style}}))),bU=Km,[Gm,mte]=Mn("Tooltip",[Fs]),wx=Fs(),SU="TooltipProvider",_U=700,d1="tooltip.open",[EU,xx]=Gm(SU),CU=e=>{const{__scopeTooltip:t,delayDuration:n=_U,skipDelayDuration:r=300,disableHoverableContent:o=!1,children:i}=e,[s,l]=d.useState(!0),u=d.useRef(!1),f=d.useRef(0);return d.useEffect(()=>{const p=f.current;return()=>window.clearTimeout(p)},[]),d.createElement(EU,{scope:t,isOpenDelayed:s,delayDuration:n,onOpen:d.useCallback(()=>{window.clearTimeout(f.current),l(!1)},[]),onClose:d.useCallback(()=>{window.clearTimeout(f.current),f.current=window.setTimeout(()=>l(!0),r)},[r]),isPointerInTransitRef:u,onPointerInTransitChange:d.useCallback(p=>{u.current=p},[]),disableHoverableContent:o},i)},bx="Tooltip",[$U,Ym]=Gm(bx),RU=e=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:o=!1,onOpenChange:i,disableHoverableContent:s,delayDuration:l}=e,u=xx(bx,e.__scopeTooltip),f=wx(t),[p,m]=d.useState(null),g=nr(),y=d.useRef(0),x=s??u.disableHoverableContent,S=l??u.delayDuration,E=d.useRef(!1),[_=!1,b]=Zr({prop:r,defaultProp:o,onChange:A=>{A?(u.onOpen(),document.dispatchEvent(new CustomEvent(d1))):u.onClose(),i==null||i(A)}}),C=d.useMemo(()=>_?E.current?"delayed-open":"instant-open":"closed",[_]),R=d.useCallback(()=>{window.clearTimeout(y.current),E.current=!1,b(!0)},[b]),P=d.useCallback(()=>{window.clearTimeout(y.current),b(!1)},[b]),O=d.useCallback(()=>{window.clearTimeout(y.current),y.current=window.setTimeout(()=>{E.current=!0,b(!0)},S)},[S,b]);return d.useEffect(()=>()=>window.clearTimeout(y.current),[]),d.createElement(Fd,f,d.createElement($U,{scope:t,contentId:g,open:_,stateAttribute:C,trigger:p,onTriggerChange:m,onTriggerEnter:d.useCallback(()=>{u.isOpenDelayed?O():R()},[u.isOpenDelayed,O,R]),onTriggerLeave:d.useCallback(()=>{x?P():window.clearTimeout(y.current)},[P,x]),onOpen:R,onClose:P,disableHoverableContent:x},n))},KC="TooltipTrigger",kU=d.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,o=Ym(KC,n),i=xx(KC,n),s=wx(n),l=d.useRef(null),u=Ue(t,l,o.onTriggerChange),f=d.useRef(!1),p=d.useRef(!1),m=d.useCallback(()=>f.current=!1,[]);return d.useEffect(()=>()=>document.removeEventListener("pointerup",m),[m]),d.createElement(Wm,Y({asChild:!0},s),d.createElement(Ae.button,Y({"aria-describedby":o.open?o.contentId:void 0,"data-state":o.stateAttribute},r,{ref:u,onPointerMove:ue(e.onPointerMove,g=>{g.pointerType!=="touch"&&!p.current&&!i.isPointerInTransitRef.current&&(o.onTriggerEnter(),p.current=!0)}),onPointerLeave:ue(e.onPointerLeave,()=>{o.onTriggerLeave(),p.current=!1}),onPointerDown:ue(e.onPointerDown,()=>{f.current=!0,document.addEventListener("pointerup",m,{once:!0})}),onFocus:ue(e.onFocus,()=>{f.current||o.onOpen()}),onBlur:ue(e.onBlur,o.onClose),onClick:ue(e.onClick,o.onClose)})))}),TU="TooltipPortal",[gte,PU]=Gm(TU,{forceMount:void 0}),ud="TooltipContent",AU=d.forwardRef((e,t)=>{const n=PU(ud,e.__scopeTooltip),{forceMount:r=n.forceMount,side:o="top",...i}=e,s=Ym(ud,e.__scopeTooltip);return d.createElement(Sn,{present:r||s.open},s.disableHoverableContent?d.createElement(Yk,Y({side:o},i,{ref:t})):d.createElement(MU,Y({side:o},i,{ref:t})))}),MU=d.forwardRef((e,t)=>{const n=Ym(ud,e.__scopeTooltip),r=xx(ud,e.__scopeTooltip),o=d.useRef(null),i=Ue(t,o),[s,l]=d.useState(null),{trigger:u,onClose:f}=n,p=o.current,{onPointerInTransitChange:m}=r,g=d.useCallback(()=>{l(null),m(!1)},[m]),y=d.useCallback((x,S)=>{const E=x.currentTarget,_={x:x.clientX,y:x.clientY},b=NU(_,E.getBoundingClientRect()),C=DU(_,b),R=IU(S.getBoundingClientRect()),P=FU([...C,...R]);l(P),m(!0)},[m]);return d.useEffect(()=>()=>g(),[g]),d.useEffect(()=>{if(u&&p){const x=E=>y(E,p),S=E=>y(E,u);return u.addEventListener("pointerleave",x),p.addEventListener("pointerleave",S),()=>{u.removeEventListener("pointerleave",x),p.removeEventListener("pointerleave",S)}}},[u,p,y,g]),d.useEffect(()=>{if(s){const x=S=>{const E=S.target,_={x:S.clientX,y:S.clientY},b=(u==null?void 0:u.contains(E))||(p==null?void 0:p.contains(E)),C=!LU(_,s);b?g():C&&(g(),f())};return document.addEventListener("pointermove",x),()=>document.removeEventListener("pointermove",x)}},[u,p,s,f,g]),d.createElement(Yk,Y({},e,{ref:i}))}),[OU,vte]=Gm(bx,{isInside:!1}),Yk=d.forwardRef((e,t)=>{const{__scopeTooltip:n,children:r,"aria-label":o,onEscapeKeyDown:i,onPointerDownOutside:s,...l}=e,u=Ym(ud,n),f=wx(n),{onClose:p}=u;return d.useEffect(()=>(document.addEventListener(d1,p),()=>document.removeEventListener(d1,p)),[p]),d.useEffect(()=>{if(u.trigger){const m=g=>{const y=g.target;y!=null&&y.contains(u.trigger)&&p()};return window.addEventListener("scroll",m,{capture:!0}),()=>window.removeEventListener("scroll",m,{capture:!0})}},[u.trigger,p]),d.createElement(Ec,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:i,onPointerDownOutside:s,onFocusOutside:m=>m.preventDefault(),onDismiss:p},d.createElement(Hm,Y({"data-state":u.stateAttribute},f,l,{ref:t,style:{...l.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"}}),d.createElement(lx,null,r),d.createElement(OU,{scope:n,isInside:!0},d.createElement(bU,{id:u.contentId,role:"tooltip"},o||r))))});function NU(e,t){const n=Math.abs(t.top-e.y),r=Math.abs(t.bottom-e.y),o=Math.abs(t.right-e.x),i=Math.abs(t.left-e.x);switch(Math.min(n,r,o,i)){case i:return"left";case o:return"right";case n:return"top";case r:return"bottom";default:throw new Error("unreachable")}}function DU(e,t,n=5){const r=[];switch(t){case"top":r.push({x:e.x-n,y:e.y+n},{x:e.x+n,y:e.y+n});break;case"bottom":r.push({x:e.x-n,y:e.y-n},{x:e.x+n,y:e.y-n});break;case"left":r.push({x:e.x+n,y:e.y-n},{x:e.x+n,y:e.y+n});break;case"right":r.push({x:e.x-n,y:e.y-n},{x:e.x-n,y:e.y+n});break}return r}function IU(e){const{top:t,right:n,bottom:r,left:o}=e;return[{x:o,y:t},{x:n,y:t},{x:n,y:r},{x:o,y:r}]}function LU(e,t){const{x:n,y:r}=e;let o=!1;for(let i=0,s=t.length-1;ir!=p>r&&n<(f-l)*(r-u)/(p-u)+l&&(o=!o)}return o}function FU(e){const t=e.slice();return t.sort((n,r)=>n.xr.x?1:n.yr.y?1:0),jU(t)}function jU(e){if(e.length<=1)return e.slice();const t=[];for(let r=0;r=2;){const i=t[t.length-1],s=t[t.length-2];if((i.x-s.x)*(o.y-s.y)>=(i.y-s.y)*(o.x-s.x))t.pop();else break}t.push(o)}t.pop();const n=[];for(let r=e.length-1;r>=0;r--){const o=e[r];for(;n.length>=2;){const i=n[n.length-1],s=n[n.length-2];if((i.x-s.x)*(o.y-s.y)>=(i.y-s.y)*(o.x-s.x))n.pop();else break}n.push(o)}return n.pop(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}const zU=CU,BU=RU,UU=kU,Xk=AU,VU=zU,Zk=BU,qk=UU,Sx=d.forwardRef(({className:e,sideOffset:t=4,...n},r)=>v.jsx(Xk,{ref:r,sideOffset:t,className:_e("z-50 border overflow-hidden rounded-md bg-background text-foreground px-3 py-1.5 text-xs animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...n}));Sx.displayName=Xk.displayName;const _x=Dm("inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50",{variants:{variant:{default:"bg-primary text-primary-foreground shadow hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",outline:"border border-input bg-transparent shadow-sm hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2",sm:"h-8 rounded-md px-3 text-xs",lg:"h-10 rounded-md px-8",icon:"h-9 w-9"}},defaultVariants:{variant:"default",size:"default"}}),wn=d.forwardRef(({className:e,variant:t,size:n,asChild:r=!1,...o},i)=>{const s=r?Zo:"button";return v.jsx(s,{className:_e(_x({variant:t,size:n,className:e}),"outline-none cursor-default select-none"),ref:i,tabIndex:-1,...o})});wn.displayName="Button";const yn=d.forwardRef(({tooltip:e,children:t,...n},r)=>v.jsxs(Zk,{children:[v.jsx(qk,{asChild:!0,children:v.jsx(wn,{variant:"ghost",size:"icon",...n,ref:r,tabIndex:-1,className:"cursor-default bg-background",children:v.jsx("div",{className:"icon-button-icon-wrapper",children:t})})}),v.jsx(Sx,{children:v.jsx("p",{children:e})})]})),f1=e=>{const{onFileUpload:t,children:n,...r}=e,[o]=d.useState(`file-upload-${Math.random().toString()}`),i=s=>{var u;const l=(u=s.currentTarget.files)==null?void 0:u[0];l&&t(l)};return v.jsxs(v.Fragment,{children:[v.jsx("label",{htmlFor:o,children:v.jsx(yn,{...r,asChild:!0,children:n})}),v.jsx(Bm,{style:{display:"none"},id:o,name:o,type:"file",onChange:i,accept:"image/png, image/jpeg"})]})};var WU={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const HU=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Jt=(e,t)=>{const n=d.forwardRef(({color:r="currentColor",size:o=24,strokeWidth:i=2,absoluteStrokeWidth:s,children:l,...u},f)=>d.createElement("svg",{ref:f,...WU,width:o,height:o,stroke:r,strokeWidth:s?Number(i)*24/Number(o):i,className:`lucide lucide-${HU(e)}`,...u},[...t.map(([p,m])=>d.createElement(p,m)),...(Array.isArray(l)?l:[l])||[]]));return n.displayName=`${e}`,n},KU=Jt("Blocks",[["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["path",{d:"M10 21V8a1 1 0 0 0-1-1H4a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-5a1 1 0 0 0-1-1H3",key:"1fpvtg"}]]),GU=Jt("ChevronLeft",[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]]),YU=Jt("ChevronRight",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]),XU=Jt("Coffee",[["path",{d:"M17 8h1a4 4 0 1 1 0 8h-1",key:"jx4kbh"}],["path",{d:"M3 8h14v9a4 4 0 0 1-4 4H7a4 4 0 0 1-4-4Z",key:"1bxrl0"}],["line",{x1:"6",x2:"6",y1:"2",y2:"4",key:"1cr9l3"}],["line",{x1:"10",x2:"10",y1:"2",y2:"4",key:"170wym"}],["line",{x1:"14",x2:"14",y1:"2",y2:"4",key:"1c5f70"}]]),ZU=Jt("Download",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"7 10 12 15 17 10",key:"2ggqvy"}],["line",{x1:"12",x2:"12",y1:"15",y2:"3",key:"1vk2je"}]]),qU=Jt("Eraser",[["path",{d:"m7 21-4.3-4.3c-1-1-1-2.5 0-3.4l9.6-9.6c1-1 2.5-1 3.4 0l5.6 5.6c1 1 1 2.5 0 3.4L13 21",key:"182aya"}],["path",{d:"M22 21H7",key:"t4ddhn"}],["path",{d:"m5 11 9 9",key:"1mo9qw"}]]),QU=Jt("Expand",[["path",{d:"m21 21-6-6m6 6v-4.8m0 4.8h-4.8",key:"1c15vz"}],["path",{d:"M3 16.2V21m0 0h4.8M3 21l6-6",key:"1fsnz2"}],["path",{d:"M21 7.8V3m0 0h-4.8M21 3l-6 6",key:"hawz9i"}],["path",{d:"M3 7.8V3m0 0h4.8M3 3l6 6",key:"u9ee12"}]]),JU=Jt("Eye",[["path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z",key:"rwhkz3"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]),eV=Jt("FolderClosed",[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}],["path",{d:"M2 10h20",key:"1ir3d8"}]]),Qk=Jt("Fullscreen",[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}],["rect",{width:"10",height:"8",x:"7",y:"8",rx:"1",key:"vys8me"}]]),tV=Jt("Image",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]]),nV=Jt("Keyboard",[["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",ry:"2",key:"15u882"}],["path",{d:"M6 8h.001",key:"1ej0i3"}],["path",{d:"M10 8h.001",key:"1x2st2"}],["path",{d:"M14 8h.001",key:"1vkmyp"}],["path",{d:"M18 8h.001",key:"kfsenl"}],["path",{d:"M8 12h.001",key:"1sjpby"}],["path",{d:"M12 12h.001",key:"al75ts"}],["path",{d:"M16 12h.001",key:"931bgk"}],["path",{d:"M7 16h10",key:"wp8him"}]]),rV=Jt("MousePointerClick",[["path",{d:"m9 9 5 12 1.8-5.2L21 14Z",key:"1b76lo"}],["path",{d:"M7.2 2.2 8 5.1",key:"1cfko1"}],["path",{d:"m5.1 8-2.9-.8",key:"1go3kf"}],["path",{d:"M14 4.1 12 6",key:"ita8i4"}],["path",{d:"m6 12-1.9 2",key:"mnht97"}]]),oV=Jt("Redo",[["path",{d:"M21 7v6h-6",key:"3ptur4"}],["path",{d:"M3 17a9 9 0 0 1 9-9 9 9 0 0 1 6 2.3l3 2.7",key:"1kgawr"}]]),iV=Jt("RotateCw",[["path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8",key:"1p45f6"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}]]),sV=Jt("Settings",[["path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z",key:"1qme2f"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]),GC=Jt("Slice",[["path",{d:"m8 14-6 6h9v-3",key:"zo3j9a"}],["path",{d:"M18.37 3.63 8 14l3 3L21.37 6.63a2.12 2.12 0 1 0-3-3Z",key:"1dzx0j"}]]),YC=Jt("Smile",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 14s1.5 2 4 2 4-2 4-2",key:"1y1vjs"}],["line",{x1:"9",x2:"9.01",y1:"9",y2:"9",key:"yxxnd0"}],["line",{x1:"15",x2:"15.01",y1:"9",y2:"9",key:"1p4y9e"}]]),aV=Jt("Undo",[["path",{d:"M3 7v6h6",key:"1v2h90"}],["path",{d:"M21 17a9 9 0 0 0-9-9 9 9 0 0 0-6 2.3L3 13",key:"1r6uu6"}]]),Jk=Jt("Upload",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"17 8 12 3 7 8",key:"t8dd8p"}],["line",{x1:"12",x2:"12",y1:"3",y2:"15",key:"widbto"}]]);function lV(e,t){const[n,r]=d.useState(e);return d.useEffect(()=>{const o=setTimeout(()=>{r(e)},t);return()=>{clearTimeout(o)}},[e,t]),n}function eT(e){const[t,n]=d.useState(()=>typeof e=="boolean"?e:!!e),r=d.useCallback(o=>n(typeof o=="boolean"?o:i=>!i),[]);return[t,r]}const E0="focusScope.autoFocusOnMount",C0="focusScope.autoFocusOnUnmount",XC={bubbles:!1,cancelable:!0},Xm=d.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:o,onUnmountAutoFocus:i,...s}=e,[l,u]=d.useState(null),f=Ft(o),p=Ft(i),m=d.useRef(null),g=Ue(t,S=>u(S)),y=d.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;d.useEffect(()=>{if(r){let b=function(O){if(y.paused||!l)return;const A=O.target;l.contains(A)?m.current=A:Qi(m.current,{select:!0})},C=function(O){if(y.paused||!l)return;const A=O.relatedTarget;A!==null&&(l.contains(A)||Qi(m.current,{select:!0}))},R=function(O){if(document.activeElement===document.body)for(const D of O)D.removedNodes.length>0&&Qi(l)};var S=b,E=C,_=R;document.addEventListener("focusin",b),document.addEventListener("focusout",C);const P=new MutationObserver(R);return l&&P.observe(l,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",b),document.removeEventListener("focusout",C),P.disconnect()}}},[r,l,y.paused]),d.useEffect(()=>{if(l){qC.add(y);const S=document.activeElement;if(!l.contains(S)){const _=new CustomEvent(E0,XC);l.addEventListener(E0,f),l.dispatchEvent(_),_.defaultPrevented||(cV(pV(tT(l)),{select:!0}),document.activeElement===S&&Qi(l))}return()=>{l.removeEventListener(E0,f),setTimeout(()=>{const _=new CustomEvent(C0,XC);l.addEventListener(C0,p),l.dispatchEvent(_),_.defaultPrevented||Qi(S??document.body,{select:!0}),l.removeEventListener(C0,p),qC.remove(y)},0)}}},[l,f,p,y]);const x=d.useCallback(S=>{if(!n&&!r||y.paused)return;const E=S.key==="Tab"&&!S.altKey&&!S.ctrlKey&&!S.metaKey,_=document.activeElement;if(E&&_){const b=S.currentTarget,[C,R]=uV(b);C&&R?!S.shiftKey&&_===R?(S.preventDefault(),n&&Qi(C,{select:!0})):S.shiftKey&&_===C&&(S.preventDefault(),n&&Qi(R,{select:!0})):_===b&&S.preventDefault()}},[n,r,y.paused]);return d.createElement(Ae.div,Y({tabIndex:-1},s,{ref:g,onKeyDown:x}))});function cV(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(Qi(r,{select:t}),document.activeElement!==n)return}function uV(e){const t=tT(e),n=ZC(t,e),r=ZC(t.reverse(),e);return[n,r]}function tT(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const o=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||o?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function ZC(e,t){for(const n of e)if(!dV(n,{upTo:t}))return n}function dV(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function fV(e){return e instanceof HTMLInputElement&&"select"in e}function Qi(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&fV(e)&&t&&e.select()}}const qC=hV();function hV(){let e=[];return{add(t){const n=e[0];t!==n&&(n==null||n.pause()),e=QC(e,t),e.unshift(t)},remove(t){var n;e=QC(e,t),(n=e[0])===null||n===void 0||n.resume()}}}function QC(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function pV(e){return e.filter(t=>t.tagName!=="A")}let $0=0;function Zm(){d.useEffect(()=>{var e,t;const n=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",(e=n[0])!==null&&e!==void 0?e:JC()),document.body.insertAdjacentElement("beforeend",(t=n[1])!==null&&t!==void 0?t:JC()),$0++,()=>{$0===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(r=>r.remove()),$0--}},[])}function JC(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.cssText="outline: none; opacity: 0; position: fixed; pointer-events: none",e}var Lo=function(){return Lo=Object.assign||function(t){for(var n,r=1,o=arguments.length;r"u")return AV;var t=MV(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])}},NV=iT(),DV=function(e,t,n,r){var o=e.left,i=e.top,s=e.right,l=e.gap;return n===void 0&&(n="margin"),` + .`.concat(gV,` { + overflow: hidden `).concat(r,`; + padding-right: `).concat(l,"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(i,`px; + padding-right: `).concat(s,`px; + margin-left:0; + margin-top:0; + margin-right: `).concat(l,"px ").concat(r,`; + `),n==="padding"&&"padding-right: ".concat(l,"px ").concat(r,";")].filter(Boolean).join(""),` + } + + .`).concat(qh,` { + right: `).concat(l,"px ").concat(r,`; + } + + .`).concat(Qh,` { + margin-right: `).concat(l,"px ").concat(r,`; + } + + .`).concat(qh," .").concat(qh,` { + right: 0 `).concat(r,`; + } + + .`).concat(Qh," .").concat(Qh,` { + margin-right: 0 `).concat(r,`; + } + + body { + `).concat(vV,": ").concat(l,`px; + } +`)},IV=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,o=r===void 0?"margin":r,i=d.useMemo(function(){return OV(o)},[o]);return d.createElement(NV,{styles:DV(i,!t,o,n?"":"!important")})},h1=!1;if(typeof window<"u")try{var hh=Object.defineProperty({},"passive",{get:function(){return h1=!0,!0}});window.addEventListener("test",hh,hh),window.removeEventListener("test",hh,hh)}catch{h1=!1}var rl=h1?{passive:!1}:!1,LV=function(e){return e.tagName==="TEXTAREA"},sT=function(e,t){var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!LV(e)&&n[t]==="visible")},FV=function(e){return sT(e,"overflowY")},jV=function(e){return sT(e,"overflowX")},t2=function(e,t){var n=t;do{typeof ShadowRoot<"u"&&n instanceof ShadowRoot&&(n=n.host);var r=aT(e,n);if(r){var o=lT(e,n),i=o[1],s=o[2];if(i>s)return!0}n=n.parentNode}while(n&&n!==document.body);return!1},zV=function(e){var t=e.scrollTop,n=e.scrollHeight,r=e.clientHeight;return[t,n,r]},BV=function(e){var t=e.scrollLeft,n=e.scrollWidth,r=e.clientWidth;return[t,n,r]},aT=function(e,t){return e==="v"?FV(t):jV(t)},lT=function(e,t){return e==="v"?zV(t):BV(t)},UV=function(e,t){return e==="h"&&t==="rtl"?-1:1},VV=function(e,t,n,r,o){var i=UV(e,window.getComputedStyle(t).direction),s=i*r,l=n.target,u=t.contains(l),f=!1,p=s>0,m=0,g=0;do{var y=lT(e,l),x=y[0],S=y[1],E=y[2],_=S-E-i*x;(x||_)&&aT(e,l)&&(m+=_,g+=x),l=l.parentNode}while(!u&&l!==document.body||u&&(t.contains(l)||t===l));return(p&&(o&&m===0||!o&&s>m)||!p&&(o&&g===0||!o&&-s>g))&&(f=!0),f},ph=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},n2=function(e){return[e.deltaX,e.deltaY]},r2=function(e){return e&&"current"in e?e.current:e},WV=function(e,t){return e[0]===t[0]&&e[1]===t[1]},HV=function(e){return` + .block-interactivity-`.concat(e,` {pointer-events: none;} + .allow-interactivity-`).concat(e,` {pointer-events: all;} +`)},KV=0,ol=[];function GV(e){var t=d.useRef([]),n=d.useRef([0,0]),r=d.useRef(),o=d.useState(KV++)[0],i=d.useState(function(){return iT()})[0],s=d.useRef(e);d.useEffect(function(){s.current=e},[e]),d.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(o));var S=mV([e.lockRef.current],(e.shards||[]).map(r2),!0).filter(Boolean);return S.forEach(function(E){return E.classList.add("allow-interactivity-".concat(o))}),function(){document.body.classList.remove("block-interactivity-".concat(o)),S.forEach(function(E){return E.classList.remove("allow-interactivity-".concat(o))})}}},[e.inert,e.lockRef.current,e.shards]);var l=d.useCallback(function(S,E){if("touches"in S&&S.touches.length===2)return!s.current.allowPinchZoom;var _=ph(S),b=n.current,C="deltaX"in S?S.deltaX:b[0]-_[0],R="deltaY"in S?S.deltaY:b[1]-_[1],P,O=S.target,A=Math.abs(C)>Math.abs(R)?"h":"v";if("touches"in S&&A==="h"&&O.type==="range")return!1;var D=t2(A,O);if(!D)return!0;if(D?P=A:(P=A==="v"?"h":"v",D=t2(A,O)),!D)return!1;if(!r.current&&"changedTouches"in S&&(C||R)&&(r.current=P),!P)return!0;var B=r.current||P;return VV(B,E,S,B==="h"?C:R,!0)},[]),u=d.useCallback(function(S){var E=S;if(!(!ol.length||ol[ol.length-1]!==i)){var _="deltaY"in E?n2(E):ph(E),b=t.current.filter(function(P){return P.name===E.type&&P.target===E.target&&WV(P.delta,_)})[0];if(b&&b.should){E.cancelable&&E.preventDefault();return}if(!b){var C=(s.current.shards||[]).map(r2).filter(Boolean).filter(function(P){return P.contains(E.target)}),R=C.length>0?l(E,C[0]):!s.current.noIsolation;R&&E.cancelable&&E.preventDefault()}}},[]),f=d.useCallback(function(S,E,_,b){var C={name:S,delta:E,target:_,should:b};t.current.push(C),setTimeout(function(){t.current=t.current.filter(function(R){return R!==C})},1)},[]),p=d.useCallback(function(S){n.current=ph(S),r.current=void 0},[]),m=d.useCallback(function(S){f(S.type,n2(S),S.target,l(S,e.lockRef.current))},[]),g=d.useCallback(function(S){f(S.type,ph(S),S.target,l(S,e.lockRef.current))},[]);d.useEffect(function(){return ol.push(i),e.setCallbacks({onScrollCapture:m,onWheelCapture:m,onTouchMoveCapture:g}),document.addEventListener("wheel",u,rl),document.addEventListener("touchmove",u,rl),document.addEventListener("touchstart",p,rl),function(){ol=ol.filter(function(S){return S!==i}),document.removeEventListener("wheel",u,rl),document.removeEventListener("touchmove",u,rl),document.removeEventListener("touchstart",p,rl)}},[]);var y=e.removeScrollBar,x=e.inert;return d.createElement(d.Fragment,null,x?d.createElement(i,{styles:HV(o)}):null,y?d.createElement(IV,{gapMode:"margin"}):null)}const YV=EV(oT,GV);var cT=d.forwardRef(function(e,t){return d.createElement(qm,Lo({},e,{ref:t,sideCar:YV}))});cT.classNames=qm.classNames;const Qm=cT;var XV=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},il=new WeakMap,mh=new WeakMap,gh={},T0=0,uT=function(e){return e&&(e.host||uT(e.parentNode))},ZV=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=uT(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})},qV=function(e,t,n,r){var o=ZV(t,Array.isArray(e)?e:[e]);gh[n]||(gh[n]=new WeakMap);var i=gh[n],s=[],l=new Set,u=new Set(o),f=function(m){!m||l.has(m)||(l.add(m),f(m.parentNode))};o.forEach(f);var p=function(m){!m||u.has(m)||Array.prototype.forEach.call(m.children,function(g){if(l.has(g))p(g);else{var y=g.getAttribute(r),x=y!==null&&y!=="false",S=(il.get(g)||0)+1,E=(i.get(g)||0)+1;il.set(g,S),i.set(g,E),s.push(g),S===1&&x&&mh.set(g,!0),E===1&&g.setAttribute(n,"true"),x||g.setAttribute(r,"true")}})};return p(t),l.clear(),T0++,function(){s.forEach(function(m){var g=il.get(m)-1,y=i.get(m)-1;il.set(m,g),i.set(m,y),g||(mh.has(m)||m.removeAttribute(r),mh.delete(m)),y||m.removeAttribute(n)}),T0--,T0||(il=new WeakMap,il=new WeakMap,mh=new WeakMap,gh={})}},Jm=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),o=t||XV(e);return o?(r.push.apply(r,Array.from(o.querySelectorAll("[aria-live]"))),qV(r,o,n,"aria-hidden")):function(){return null}};const dT="Dialog",[fT,hT]=Mn(dT),[QV,Eo]=fT(dT),JV=e=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:o,onOpenChange:i,modal:s=!0}=e,l=d.useRef(null),u=d.useRef(null),[f=!1,p]=Zr({prop:r,defaultProp:o,onChange:i});return d.createElement(QV,{scope:t,triggerRef:l,contentRef:u,contentId:nr(),titleId:nr(),descriptionId:nr(),open:f,onOpenChange:p,onOpenToggle:d.useCallback(()=>p(m=>!m),[p]),modal:s},n)},eW="DialogTrigger",pT=d.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=Eo(eW,n),i=Ue(t,o.triggerRef);return d.createElement(Ae.button,Y({type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":Ex(o.open)},r,{ref:i,onClick:ue(e.onClick,o.onOpenToggle)}))}),mT="DialogPortal",[tW,gT]=fT(mT,{forceMount:void 0}),nW=e=>{const{__scopeDialog:t,forceMount:n,children:r,container:o}=e,i=Eo(mT,t);return d.createElement(tW,{scope:t,forceMount:n},d.Children.map(r,s=>d.createElement(Sn,{present:n||i.open},d.createElement(jd,{asChild:!0,container:o},s))))},p1="DialogOverlay",rW=d.forwardRef((e,t)=>{const n=gT(p1,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,i=Eo(p1,e.__scopeDialog);return i.modal?d.createElement(Sn,{present:r||i.open},d.createElement(oW,Y({},o,{ref:t}))):null}),oW=d.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=Eo(p1,n);return d.createElement(Qm,{as:Zo,allowPinchZoom:!0,shards:[o.contentRef]},d.createElement(Ae.div,Y({"data-state":Ex(o.open)},r,{ref:t,style:{pointerEvents:"auto",...r.style}})))}),uc="DialogContent",iW=d.forwardRef((e,t)=>{const n=gT(uc,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,i=Eo(uc,e.__scopeDialog);return d.createElement(Sn,{present:r||i.open},i.modal?d.createElement(sW,Y({},o,{ref:t})):d.createElement(aW,Y({},o,{ref:t})))}),sW=d.forwardRef((e,t)=>{const n=Eo(uc,e.__scopeDialog),r=d.useRef(null),o=Ue(t,n.contentRef,r);return d.useEffect(()=>{const i=r.current;if(i)return Jm(i)},[]),d.createElement(vT,Y({},e,{ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:ue(e.onCloseAutoFocus,i=>{var s;i.preventDefault(),(s=n.triggerRef.current)===null||s===void 0||s.focus()}),onPointerDownOutside:ue(e.onPointerDownOutside,i=>{const s=i.detail.originalEvent,l=s.button===0&&s.ctrlKey===!0;(s.button===2||l)&&i.preventDefault()}),onFocusOutside:ue(e.onFocusOutside,i=>i.preventDefault())}))}),aW=d.forwardRef((e,t)=>{const n=Eo(uc,e.__scopeDialog),r=d.useRef(!1),o=d.useRef(!1);return d.createElement(vT,Y({},e,{ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var s;if((s=e.onCloseAutoFocus)===null||s===void 0||s.call(e,i),!i.defaultPrevented){var l;r.current||(l=n.triggerRef.current)===null||l===void 0||l.focus(),i.preventDefault()}r.current=!1,o.current=!1},onInteractOutside:i=>{var s,l;(s=e.onInteractOutside)===null||s===void 0||s.call(e,i),i.defaultPrevented||(r.current=!0,i.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const u=i.target;((l=n.triggerRef.current)===null||l===void 0?void 0:l.contains(u))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&o.current&&i.preventDefault()}}))}),vT=d.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:i,...s}=e,l=Eo(uc,n),u=d.useRef(null),f=Ue(t,u);return Zm(),d.createElement(d.Fragment,null,d.createElement(Xm,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:i},d.createElement(Ec,Y({role:"dialog",id:l.contentId,"aria-describedby":l.descriptionId,"aria-labelledby":l.titleId,"data-state":Ex(l.open)},s,{ref:f,onDismiss:()=>l.onOpenChange(!1)}))),!1)}),yT="DialogTitle",lW=d.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=Eo(yT,n);return d.createElement(Ae.h2,Y({id:o.titleId},r,{ref:t}))}),cW="DialogDescription",wT=d.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=Eo(cW,n);return d.createElement(Ae.p,Y({id:o.descriptionId},r,{ref:t}))}),uW="DialogClose",dW=d.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=Eo(uW,n);return d.createElement(Ae.button,Y({type:"button"},r,{ref:t,onClick:ue(e.onClick,()=>o.onOpenChange(!1))}))});function Ex(e){return e?"open":"closed"}const fW="DialogTitleWarning",[hW,yte]=pB(fW,{contentName:uc,titleName:yT,docsSlug:"dialog"}),Cx=JV,xT=pT,$x=nW,zd=rW,Bd=iW,Ud=lW,Vd=wT,Rx=dW,eg=Cx,kx=xT,pW=$x,bT=d.forwardRef(({className:e,...t},n)=>v.jsx(zd,{ref:n,className:_e("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t}));bT.displayName=zd.displayName;const Wd=d.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(pW,{children:[v.jsx(bT,{}),v.jsxs(Bd,{ref:r,className:_e("fixed left-[50%] top-[50%] z-50 flex flex-col w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",e,"outline-none"),onCloseAutoFocus:o=>o.preventDefault(),...n,children:[t,v.jsxs(Rx,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[v.jsx(bk,{className:"h-4 w-4"}),v.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Wd.displayName=Bd.displayName;const ST=({className:e,...t})=>v.jsx("div",{className:_e("flex flex-col space-y-1.5 text-center sm:text-left",e),...t});ST.displayName="DialogHeader";const Hd=d.forwardRef(({className:e,...t},n)=>v.jsx(Ud,{ref:n,className:_e("text-2xl font-semibold leading-none tracking-tight",e),...t}));Hd.displayName=Ud.displayName;const mW=d.forwardRef(({className:e,...t},n)=>v.jsx(Vd,{ref:n,className:_e("text-sm text-muted-foreground",e),...t}));mW.displayName=Vd.displayName;function m1(){return m1=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 _W=function(t,n,r){r===void 0&&(r=!1);var o=n.alt,i=n.meta,s=n.mod,l=n.shift,u=n.ctrl,f=n.keys,p=t.key,m=t.code,g=t.ctrlKey,y=t.metaKey,x=t.shiftKey,S=t.altKey,E=hs(m),_=p.toLowerCase();if(!r){if(o===!S&&_!=="alt"||l===!x&&_!=="shift")return!1;if(s){if(!y&&!g)return!1}else if(i===!y&&_!=="meta"&&_!=="os"||u===!g&&_!=="ctrl"&&_!=="control")return!1}return f&&f.length===1&&(f.includes(_)||f.includes(E))?!0:f?yW(f):!f},EW=d.createContext(void 0),CW=function(){return d.useContext(EW)};function RT(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&&RT(e[r],t[r])},!0):e===t}var $W=d.createContext({hotkeys:[],enabledScopes:[],toggleScope:function(){},enableScope:function(){},disableScope:function(){}}),RW=function(){return d.useContext($W)};function kW(e){var t=d.useRef(void 0);return RT(t.current,e)||(t.current=e),t.current}var o2=function(t){t.stopPropagation(),t.preventDefault(),t.stopImmediatePropagation()},TW=typeof window<"u"?d.useLayoutEffect:d.useEffect;function PW(e,t,n,r){var o=d.useRef(null),i=d.useRef(!1),s=n instanceof Array?r instanceof Array?void 0:r:n,l=Tx(e)?e.join(s==null?void 0:s.splitKey):e,u=n instanceof Array?n:r instanceof Array?r:void 0,f=d.useCallback(t,u??[]),p=d.useRef(f);u?p.current=f:p.current=t;var m=kW(s),g=RW(),y=g.enabledScopes,x=CW();return TW(function(){if(!((m==null?void 0:m.enabled)===!1||!SW(y,m==null?void 0:m.scopes))){var S=function(R,P){var O;if(P===void 0&&(P=!1),!(bW(R)&&!$T(R,m==null?void 0:m.enableOnFormTags))&&!(m!=null&&m.ignoreEventWhen!=null&&m.ignoreEventWhen(R))){if(o.current!==null&&document.activeElement!==o.current&&!o.current.contains(document.activeElement)){o2(R);return}(O=R.target)!=null&&O.isContentEditable&&!(m!=null&&m.enableOnContentEditable)||P0(l,m==null?void 0:m.splitKey).forEach(function(A){var D,B=A0(A,m==null?void 0:m.combinationKey);if(_W(R,B,m==null?void 0:m.ignoreModifiers)||(D=B.keys)!=null&&D.includes("*")){if(P&&i.current)return;if(wW(R,B,m==null?void 0:m.preventDefault),!xW(R,B,m==null?void 0:m.enabled)){o2(R);return}p.current(R,B),P||(i.current=!0)}})}},E=function(R){R.key!==void 0&&(ET(hs(R.code)),((m==null?void 0:m.keydown)===void 0&&(m==null?void 0:m.keyup)!==!0||m!=null&&m.keydown)&&S(R))},_=function(R){R.key!==void 0&&(CT(hs(R.code)),i.current=!1,m!=null&&m.keyup&&S(R,!0))},b=o.current||(s==null?void 0:s.document)||document;return b.addEventListener("keyup",_),b.addEventListener("keydown",E),x&&P0(l,m==null?void 0:m.splitKey).forEach(function(C){return x.addHotkey(A0(C,m==null?void 0:m.combinationKey,m==null?void 0:m.description))}),function(){b.removeEventListener("keyup",_),b.removeEventListener("keydown",E),x&&P0(l,m==null?void 0:m.splitKey).forEach(function(C){return x.removeHotkey(A0(C,m==null?void 0:m.combinationKey,m==null?void 0:m.description))})}}},[l,m,y]),o}const Zn=(e,t,n)=>{const r=bt(i=>i.disableShortCuts);return PW(e,t,{enabled:!r},n)};function ur(e){const{content:t,keys:n}=e;return v.jsxs("div",{className:"flex justify-between",children:[v.jsx("div",{children:t}),v.jsx("div",{className:"flex gap-[8px]",children:n.map(r=>v.jsx("div",{className:"border px-2 py-1 rounded-lg",children:r},r))})]})}const AW=function(){return/macintosh|mac os x/i.test(navigator.userAgent)},vh=()=>AW()?"Cmd":"Ctrl";function MW(){const[e,t]=eT(!1);return Zn("h",()=>{t()}),v.jsxs(eg,{open:e,onOpenChange:t,children:[v.jsx(kx,{asChild:!0,children:v.jsx(yn,{tooltip:"Hotkeys",children:v.jsx(nV,{})})}),v.jsx(Wd,{children:v.jsxs(ST,{children:[v.jsx(Hd,{children:"Hotkeys"}),v.jsxs("div",{className:"flex gap-2 flex-col pt-4",children:[v.jsx(ur,{content:"Pan",keys:["Space + Drag"]}),v.jsx(ur,{content:"Reset Zoom/Pan",keys:["Esc"]}),v.jsx(ur,{content:"Decrease Brush Size",keys:["["]}),v.jsx(ur,{content:"Increase Brush Size",keys:["]"]}),v.jsx(ur,{content:"View Original Image",keys:["Hold Tab"]}),v.jsx(ur,{content:"Undo",keys:[vh(),"Z"]}),v.jsx(ur,{content:"Redo",keys:[vh(),"Shift","Z"]}),v.jsx(ur,{content:"Copy Result",keys:[vh(),"C"]}),v.jsx(ur,{content:"Paste Image",keys:[vh(),"V"]}),v.jsx(ur,{content:"Trigger Manually Inpainting",keys:["Shift","R"]}),v.jsx(ur,{content:"Toggle Hotkeys Dialog",keys:["H"]}),v.jsx(ur,{content:"Toggle Settings Dialog",keys:["S"]}),v.jsx(ur,{content:"Toggle File Manager",keys:["F"]})]})]})})]})}function Px(e){const[t]=d.useState(new Image),[n,r]=d.useState(!1);return d.useEffect(()=>{if(e)return t.onload=()=>{r(!0)},r(!1),t.src=URL.createObjectURL(e),()=>{t.onload=null}},[e,t]),[t,n]}const kT="Popover",[TT,wte]=Mn(kT,[Fs]),Ax=Fs(),[OW,Rc]=TT(kT),NW=e=>{const{__scopePopover:t,children:n,open:r,defaultOpen:o,onOpenChange:i,modal:s=!1}=e,l=Ax(t),u=d.useRef(null),[f,p]=d.useState(!1),[m=!1,g]=Zr({prop:r,defaultProp:o,onChange:i});return d.createElement(Fd,l,d.createElement(OW,{scope:t,contentId:nr(),triggerRef:u,open:m,onOpenChange:g,onOpenToggle:d.useCallback(()=>g(y=>!y),[g]),hasCustomAnchor:f,onCustomAnchorAdd:d.useCallback(()=>p(!0),[]),onCustomAnchorRemove:d.useCallback(()=>p(!1),[]),modal:s},n))},DW="PopoverTrigger",IW=d.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,o=Rc(DW,n),i=Ax(n),s=Ue(t,o.triggerRef),l=d.createElement(Ae.button,Y({type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":MT(o.open)},r,{ref:s,onClick:ue(e.onClick,o.onOpenToggle)}));return o.hasCustomAnchor?l:d.createElement(Wm,Y({asChild:!0},i),l)}),PT="PopoverPortal",[LW,FW]=TT(PT,{forceMount:void 0}),jW=e=>{const{__scopePopover:t,forceMount:n,children:r,container:o}=e,i=Rc(PT,t);return d.createElement(LW,{scope:t,forceMount:n},d.createElement(Sn,{present:n||i.open},d.createElement(jd,{asChild:!0,container:o},r)))},dd="PopoverContent",zW=d.forwardRef((e,t)=>{const n=FW(dd,e.__scopePopover),{forceMount:r=n.forceMount,...o}=e,i=Rc(dd,e.__scopePopover);return d.createElement(Sn,{present:r||i.open},i.modal?d.createElement(BW,Y({},o,{ref:t})):d.createElement(UW,Y({},o,{ref:t})))}),BW=d.forwardRef((e,t)=>{const n=Rc(dd,e.__scopePopover),r=d.useRef(null),o=Ue(t,r),i=d.useRef(!1);return d.useEffect(()=>{const s=r.current;if(s)return Jm(s)},[]),d.createElement(Qm,{as:Zo,allowPinchZoom:!0},d.createElement(AT,Y({},e,{ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:ue(e.onCloseAutoFocus,s=>{var l;s.preventDefault(),i.current||(l=n.triggerRef.current)===null||l===void 0||l.focus()}),onPointerDownOutside:ue(e.onPointerDownOutside,s=>{const l=s.detail.originalEvent,u=l.button===0&&l.ctrlKey===!0,f=l.button===2||u;i.current=f},{checkForDefaultPrevented:!1}),onFocusOutside:ue(e.onFocusOutside,s=>s.preventDefault(),{checkForDefaultPrevented:!1})})))}),UW=d.forwardRef((e,t)=>{const n=Rc(dd,e.__scopePopover),r=d.useRef(!1),o=d.useRef(!1);return d.createElement(AT,Y({},e,{ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var s;if((s=e.onCloseAutoFocus)===null||s===void 0||s.call(e,i),!i.defaultPrevented){var l;r.current||(l=n.triggerRef.current)===null||l===void 0||l.focus(),i.preventDefault()}r.current=!1,o.current=!1},onInteractOutside:i=>{var s,l;(s=e.onInteractOutside)===null||s===void 0||s.call(e,i),i.defaultPrevented||(r.current=!0,i.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const u=i.target;((l=n.triggerRef.current)===null||l===void 0?void 0:l.contains(u))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&o.current&&i.preventDefault()}}))}),AT=d.forwardRef((e,t)=>{const{__scopePopover:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:i,disableOutsidePointerEvents:s,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:f,onInteractOutside:p,...m}=e,g=Rc(dd,n),y=Ax(n);return Zm(),d.createElement(Xm,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:i},d.createElement(Ec,{asChild:!0,disableOutsidePointerEvents:s,onInteractOutside:p,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:f,onDismiss:()=>g.onOpenChange(!1)},d.createElement(Hm,Y({"data-state":MT(g.open),role:"dialog",id:g.contentId},y,m,{ref:t,style:{...m.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}}))))});function MT(e){return e?"open":"closed"}const VW=NW,WW=IW,HW=jW,OT=zW,KW=VW,GW=WW,NT=d.forwardRef(({className:e,align:t="center",sideOffset:n=4,...r},o)=>v.jsx(HW,{children:v.jsx(OT,{ref:o,align:t,tabIndex:-1,sideOffset:n,className:_e("z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...r})}));NT.displayName=OT.displayName;function YW(){var e=d.useRef(!0);return e.current?(e.current=!1,!0):e.current}var XW=function(e,t){var n=YW();d.useEffect(function(){if(!n)return e()},t)};const ZW=XW;var qW=function(){};function Mx(e){for(var t=[],n=1;nv.jsx("textarea",{className:_e("flex min-h-[60px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50","overflow-auto",e),tabIndex:-1,ref:n,...t}));Dx.displayName="Textarea";const yH=()=>{const[e,t,n,r,o,i]=bt(x=>[x.getIsProcessing(),x.settings.prompt,x.updateSettings,x.runInpainting,x.showPrevMask,x.hidePrevMask]),[s,l]=Nx(!1),u=d.useRef(null);DT(u,()=>{u!=null&&u.current&&u.current.blur()});const f=x=>{x.preventDefault(),x.stopPropagation();const S=x.target;n({prompt:S.value})},p=()=>{e||r()},m=x=>{x.key==="Enter"&&x.ctrlKey&&t.length!==0&&p()},g=()=>{o()},y=()=>{i()};return v.jsx("div",{className:"flex gap-4 relative w-full justify-center h-full",children:v.jsxs("div",{className:"absolute flex gap-4",children:[v.jsx(Dx,{ref:u,placeholder:"I want to repaint of...",className:_e(s?"focus:overflow-y-auto":"overflow-y-hidden","min-h-[32px] h-[32px] overflow-x-hidden focus:h-[120px] overflow-y-hidden transition-[height] w-[500px] py-1 px-3 bg-background resize-none"),style:{scrollbarGutter:"stable"},value:t,onInput:f,onKeyUp:m,onTransitionEnd:l}),v.jsx(wn,{size:"sm",onClick:p,disabled:e,onMouseEnter:g,onMouseLeave:y,children:"Paint"})]})})};var zp={exports:{}};/** + * @license + * Lodash + * Copyright OpenJS Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */zp.exports;(function(e,t){(function(){var n,r="4.17.21",o=200,i="Unsupported core-js use. Try https://npms.io/search?q=ponyfill.",s="Expected a function",l="Invalid `variable` option passed into `_.template`",u="__lodash_hash_undefined__",f=500,p="__lodash_placeholder__",m=1,g=2,y=4,x=1,S=2,E=1,_=2,b=4,C=8,R=16,P=32,O=64,A=128,D=256,B=512,V=30,J="...",G=800,se=16,U=1,ne=2,M=3,ee=1/0,H=9007199254740991,X=17976931348623157e292,W=NaN,le=4294967295,pe=le-1,$e=le>>>1,Ve=[["ary",A],["bind",E],["bindKey",_],["curry",C],["curryRight",R],["flip",B],["partial",P],["partialRight",O],["rearg",D]],We="[object Arguments]",Ne="[object Array]",fe="[object AsyncFunction]",xe="[object Boolean]",Re="[object Date]",Me="[object DOMException]",Oe="[object Error]",ze="[object Function]",Mt="[object GeneratorFunction]",ct="[object Map]",Kt="[object Number]",Er="[object Null]",gt="[object Object]",Vs="[object Promise]",L="[object Proxy]",Z="[object RegExp]",q="[object Set]",we="[object String]",me="[object Symbol]",de="[object Undefined]",ke="[object WeakMap]",ft="[object WeakSet]",ht="[object ArrayBuffer]",_n="[object DataView]",Cr="[object Float32Array]",Ni="[object Float64Array]",Co="[object Int8Array]",Vn="[object Int16Array]",Ba="[object Int32Array]",Di="[object Uint8Array]",Ws="[object Uint8ClampedArray]",Ii="[object Uint16Array]",Mc="[object Uint32Array]",Sg=/\b__p \+= '';/g,_g=/\b(__p \+=) '' \+/g,Qd=/(__e\(.*?\)|\b__t\)) \+\n'';/g,Oc=/&(?:amp|lt|gt|quot|#39);/g,Nc=/[&<>"']/g,Dc=RegExp(Oc.source),Eg=RegExp(Nc.source),Ic=/<%-([\s\S]+?)%>/g,Jd=/<%([\s\S]+?)%>/g,Lc=/<%=([\s\S]+?)%>/g,Cg=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,$g=/^\w*$/,Rg=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,K=/[\\^$.*+?()[\]{}|]/g,Ye=RegExp(K.source),st=/^\s+/,Qr=/\s/,an=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,ef=/\{\n\/\* \[wrapped with (.+)\] \*/,a6=/,? & /,l6=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,c6=/[()=,{}\[\]\/\s]/,u6=/\\(\\)?/g,d6=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,mb=/\w*$/,f6=/^[-+]0x[0-9a-f]+$/i,h6=/^0b[01]+$/i,p6=/^\[object .+?Constructor\]$/,m6=/^0o[0-7]+$/i,g6=/^(?:0|[1-9]\d*)$/,v6=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,tf=/($^)/,y6=/['\n\r\u2028\u2029\\]/g,nf="\\ud800-\\udfff",w6="\\u0300-\\u036f",x6="\\ufe20-\\ufe2f",b6="\\u20d0-\\u20ff",gb=w6+x6+b6,vb="\\u2700-\\u27bf",yb="a-z\\xdf-\\xf6\\xf8-\\xff",S6="\\xac\\xb1\\xd7\\xf7",_6="\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf",E6="\\u2000-\\u206f",C6=" \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",wb="A-Z\\xc0-\\xd6\\xd8-\\xde",xb="\\ufe0e\\ufe0f",bb=S6+_6+E6+C6,kg="['’]",$6="["+nf+"]",Sb="["+bb+"]",rf="["+gb+"]",_b="\\d+",R6="["+vb+"]",Eb="["+yb+"]",Cb="[^"+nf+bb+_b+vb+yb+wb+"]",Tg="\\ud83c[\\udffb-\\udfff]",k6="(?:"+rf+"|"+Tg+")",$b="[^"+nf+"]",Pg="(?:\\ud83c[\\udde6-\\uddff]){2}",Ag="[\\ud800-\\udbff][\\udc00-\\udfff]",Ua="["+wb+"]",Rb="\\u200d",kb="(?:"+Eb+"|"+Cb+")",T6="(?:"+Ua+"|"+Cb+")",Tb="(?:"+kg+"(?:d|ll|m|re|s|t|ve))?",Pb="(?:"+kg+"(?:D|LL|M|RE|S|T|VE))?",Ab=k6+"?",Mb="["+xb+"]?",P6="(?:"+Rb+"(?:"+[$b,Pg,Ag].join("|")+")"+Mb+Ab+")*",A6="\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",M6="\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])",Ob=Mb+Ab+P6,O6="(?:"+[R6,Pg,Ag].join("|")+")"+Ob,N6="(?:"+[$b+rf+"?",rf,Pg,Ag,$6].join("|")+")",D6=RegExp(kg,"g"),I6=RegExp(rf,"g"),Mg=RegExp(Tg+"(?="+Tg+")|"+N6+Ob,"g"),L6=RegExp([Ua+"?"+Eb+"+"+Tb+"(?="+[Sb,Ua,"$"].join("|")+")",T6+"+"+Pb+"(?="+[Sb,Ua+kb,"$"].join("|")+")",Ua+"?"+kb+"+"+Tb,Ua+"+"+Pb,M6,A6,_b,O6].join("|"),"g"),F6=RegExp("["+Rb+nf+gb+xb+"]"),j6=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,z6=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],B6=-1,Rt={};Rt[Cr]=Rt[Ni]=Rt[Co]=Rt[Vn]=Rt[Ba]=Rt[Di]=Rt[Ws]=Rt[Ii]=Rt[Mc]=!0,Rt[We]=Rt[Ne]=Rt[ht]=Rt[xe]=Rt[_n]=Rt[Re]=Rt[Oe]=Rt[ze]=Rt[ct]=Rt[Kt]=Rt[gt]=Rt[Z]=Rt[q]=Rt[we]=Rt[ke]=!1;var Et={};Et[We]=Et[Ne]=Et[ht]=Et[_n]=Et[xe]=Et[Re]=Et[Cr]=Et[Ni]=Et[Co]=Et[Vn]=Et[Ba]=Et[ct]=Et[Kt]=Et[gt]=Et[Z]=Et[q]=Et[we]=Et[me]=Et[Di]=Et[Ws]=Et[Ii]=Et[Mc]=!0,Et[Oe]=Et[ze]=Et[ke]=!1;var U6={À:"A",Á:"A",Â:"A",Ã:"A",Ä:"A",Å:"A",à:"a",á:"a",â:"a",ã:"a",ä:"a",å:"a",Ç:"C",ç:"c",Ð:"D",ð:"d",È:"E",É:"E",Ê:"E",Ë:"E",è:"e",é:"e",ê:"e",ë:"e",Ì:"I",Í:"I",Î:"I",Ï:"I",ì:"i",í:"i",î:"i",ï:"i",Ñ:"N",ñ:"n",Ò:"O",Ó:"O",Ô:"O",Õ:"O",Ö:"O",Ø:"O",ò:"o",ó:"o",ô:"o",õ:"o",ö:"o",ø:"o",Ù:"U",Ú:"U",Û:"U",Ü:"U",ù:"u",ú:"u",û:"u",ü:"u",Ý:"Y",ý:"y",ÿ:"y",Æ:"Ae",æ:"ae",Þ:"Th",þ:"th",ß:"ss",Ā:"A",Ă:"A",Ą:"A",ā:"a",ă:"a",ą:"a",Ć:"C",Ĉ:"C",Ċ:"C",Č:"C",ć:"c",ĉ:"c",ċ:"c",č:"c",Ď:"D",Đ:"D",ď:"d",đ:"d",Ē:"E",Ĕ:"E",Ė:"E",Ę:"E",Ě:"E",ē:"e",ĕ:"e",ė:"e",ę:"e",ě:"e",Ĝ:"G",Ğ:"G",Ġ:"G",Ģ:"G",ĝ:"g",ğ:"g",ġ:"g",ģ:"g",Ĥ:"H",Ħ:"H",ĥ:"h",ħ:"h",Ĩ:"I",Ī:"I",Ĭ:"I",Į:"I",İ:"I",ĩ:"i",ī:"i",ĭ:"i",į:"i",ı:"i",Ĵ:"J",ĵ:"j",Ķ:"K",ķ:"k",ĸ:"k",Ĺ:"L",Ļ:"L",Ľ:"L",Ŀ:"L",Ł:"L",ĺ:"l",ļ:"l",ľ:"l",ŀ:"l",ł:"l",Ń:"N",Ņ:"N",Ň:"N",Ŋ:"N",ń:"n",ņ:"n",ň:"n",ŋ:"n",Ō:"O",Ŏ:"O",Ő:"O",ō:"o",ŏ:"o",ő:"o",Ŕ:"R",Ŗ:"R",Ř:"R",ŕ:"r",ŗ:"r",ř:"r",Ś:"S",Ŝ:"S",Ş:"S",Š:"S",ś:"s",ŝ:"s",ş:"s",š:"s",Ţ:"T",Ť:"T",Ŧ:"T",ţ:"t",ť:"t",ŧ:"t",Ũ:"U",Ū:"U",Ŭ:"U",Ů:"U",Ű:"U",Ų:"U",ũ:"u",ū:"u",ŭ:"u",ů:"u",ű:"u",ų:"u",Ŵ:"W",ŵ:"w",Ŷ:"Y",ŷ:"y",Ÿ:"Y",Ź:"Z",Ż:"Z",Ž:"Z",ź:"z",ż:"z",ž:"z",IJ:"IJ",ij:"ij",Œ:"Oe",œ:"oe",ʼn:"'n",ſ:"s"},V6={"&":"&","<":"<",">":">",'"':""","'":"'"},W6={"&":"&","<":"<",">":">",""":'"',"'":"'"},H6={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},K6=parseFloat,G6=parseInt,Nb=typeof Jc=="object"&&Jc&&Jc.Object===Object&&Jc,Y6=typeof self=="object"&&self&&self.Object===Object&&self,fn=Nb||Y6||Function("return this")(),Og=t&&!t.nodeType&&t,Hs=Og&&!0&&e&&!e.nodeType&&e,Db=Hs&&Hs.exports===Og,Ng=Db&&Nb.process,$r=function(){try{var F=Hs&&Hs.require&&Hs.require("util").types;return F||Ng&&Ng.binding&&Ng.binding("util")}catch{}}(),Ib=$r&&$r.isArrayBuffer,Lb=$r&&$r.isDate,Fb=$r&&$r.isMap,jb=$r&&$r.isRegExp,zb=$r&&$r.isSet,Bb=$r&&$r.isTypedArray;function or(F,te,Q){switch(Q.length){case 0:return F.call(te);case 1:return F.call(te,Q[0]);case 2:return F.call(te,Q[0],Q[1]);case 3:return F.call(te,Q[0],Q[1],Q[2])}return F.apply(te,Q)}function X6(F,te,Q,Se){for(var Ke=-1,pt=F==null?0:F.length;++Ke-1}function Dg(F,te,Q){for(var Se=-1,Ke=F==null?0:F.length;++Se-1;);return Q}function Xb(F,te){for(var Q=F.length;Q--&&Va(te,F[Q],0)>-1;);return Q}function oM(F,te){for(var Q=F.length,Se=0;Q--;)F[Q]===te&&++Se;return Se}var iM=jg(U6),sM=jg(V6);function aM(F){return"\\"+H6[F]}function lM(F,te){return F==null?n:F[te]}function Wa(F){return F6.test(F)}function cM(F){return j6.test(F)}function uM(F){for(var te,Q=[];!(te=F.next()).done;)Q.push(te.value);return Q}function Vg(F){var te=-1,Q=Array(F.size);return F.forEach(function(Se,Ke){Q[++te]=[Ke,Se]}),Q}function Zb(F,te){return function(Q){return F(te(Q))}}function ji(F,te){for(var Q=-1,Se=F.length,Ke=0,pt=[];++Q-1}function qM(a,c){var h=this.__data__,w=Sf(h,a);return w<0?(++this.size,h.push([a,c])):h[w][1]=c,this}ti.prototype.clear=GM,ti.prototype.delete=YM,ti.prototype.get=XM,ti.prototype.has=ZM,ti.prototype.set=qM;function ni(a){var c=-1,h=a==null?0:a.length;for(this.clear();++c=c?a:c)),a}function Pr(a,c,h,w,$,T){var N,I=c&m,z=c&g,re=c&y;if(h&&(N=$?h(a,w,$,T):h(a)),N!==n)return N;if(!It(a))return a;var oe=Ge(a);if(oe){if(N=tO(a),!I)return Wn(a,N)}else{var ae=Cn(a),ge=ae==ze||ae==Mt;if(Hi(a))return MS(a,I);if(ae==gt||ae==We||ge&&!$){if(N=z||ge?{}:qS(a),!I)return z?W7(a,h7(N,a)):V7(a,lS(N,a))}else{if(!Et[ae])return $?a:{};N=nO(a,ae,I)}}T||(T=new eo);var Te=T.get(a);if(Te)return Te;T.set(a,N),$_(a)?a.forEach(function(Fe){N.add(Pr(Fe,c,h,Fe,a,T))}):E_(a)&&a.forEach(function(Fe,nt){N.set(nt,Pr(Fe,c,h,nt,a,T))});var Le=re?z?mv:pv:z?Kn:ln,Qe=oe?n:Le(a);return Rr(Qe||a,function(Fe,nt){Qe&&(nt=Fe,Fe=a[nt]),Wc(N,nt,Pr(Fe,c,h,nt,a,T))}),N}function p7(a){var c=ln(a);return function(h){return cS(h,a,c)}}function cS(a,c,h){var w=h.length;if(a==null)return!w;for(a=St(a);w--;){var $=h[w],T=c[$],N=a[$];if(N===n&&!($ in a)||!T(N))return!1}return!0}function uS(a,c,h){if(typeof a!="function")throw new kr(s);return qc(function(){a.apply(n,h)},c)}function Hc(a,c,h,w){var $=-1,T=of,N=!0,I=a.length,z=[],re=c.length;if(!I)return z;h&&(c=Ot(c,ir(h))),w?(T=Dg,N=!1):c.length>=o&&(T=Fc,N=!1,c=new Ys(c));e:for(;++$$?0:$+h),w=w===n||w>$?$:qe(w),w<0&&(w+=$),w=h>w?0:k_(w);h0&&h(I)?c>1?hn(I,c-1,h,w,$):Fi($,I):w||($[$.length]=I)}return $}var Zg=FS(),hS=FS(!0);function $o(a,c){return a&&Zg(a,c,ln)}function qg(a,c){return a&&hS(a,c,ln)}function Ef(a,c){return Li(c,function(h){return ai(a[h])})}function Zs(a,c){c=Vi(c,a);for(var h=0,w=c.length;a!=null&&hc}function v7(a,c){return a!=null&&yt.call(a,c)}function y7(a,c){return a!=null&&c in St(a)}function w7(a,c,h){return a>=En(c,h)&&a=120&&oe.length>=120)?new Ys(N&&oe):n}oe=a[0];var ae=-1,ge=I[0];e:for(;++ae<$&&re.length-1;)I!==a&&mf.call(I,z,1),mf.call(a,z,1);return a}function ES(a,c){for(var h=a?c.length:0,w=h-1;h--;){var $=c[h];if(h==w||$!==T){var T=$;si($)?mf.call(a,$,1):av(a,$)}}return a}function ov(a,c){return a+yf(oS()*(c-a+1))}function M7(a,c,h,w){for(var $=-1,T=tn(vf((c-a)/(h||1)),0),N=Q(T);T--;)N[w?T:++$]=a,a+=h;return N}function iv(a,c){var h="";if(!a||c<1||c>H)return h;do c%2&&(h+=a),c=yf(c/2),c&&(a+=a);while(c);return h}function et(a,c){return Sv(e_(a,c,Gn),a+"")}function O7(a){return aS(tl(a))}function N7(a,c){var h=tl(a);return Df(h,Xs(c,0,h.length))}function Yc(a,c,h,w){if(!It(a))return a;c=Vi(c,a);for(var $=-1,T=c.length,N=T-1,I=a;I!=null&&++$$?0:$+c),h=h>$?$:h,h<0&&(h+=$),$=c>h?0:h-c>>>0,c>>>=0;for(var T=Q($);++w<$;)T[w]=a[w+c];return T}function L7(a,c){var h;return Bi(a,function(w,$,T){return h=c(w,$,T),!h}),!!h}function $f(a,c,h){var w=0,$=a==null?w:a.length;if(typeof c=="number"&&c===c&&$<=$e){for(;w<$;){var T=w+$>>>1,N=a[T];N!==null&&!ar(N)&&(h?N<=c:N=o){var re=c?null:Y7(a);if(re)return af(re);N=!1,$=Fc,z=new Ys}else z=c?[]:I;e:for(;++w=w?a:Ar(a,c,h)}var AS=CM||function(a){return fn.clearTimeout(a)};function MS(a,c){if(c)return a.slice();var h=a.length,w=Jb?Jb(h):new a.constructor(h);return a.copy(w),w}function dv(a){var c=new a.constructor(a.byteLength);return new hf(c).set(new hf(a)),c}function j7(a,c){var h=c?dv(a.buffer):a.buffer;return new a.constructor(h,a.byteOffset,a.byteLength)}function z7(a){var c=new a.constructor(a.source,mb.exec(a));return c.lastIndex=a.lastIndex,c}function B7(a){return Vc?St(Vc.call(a)):{}}function OS(a,c){var h=c?dv(a.buffer):a.buffer;return new a.constructor(h,a.byteOffset,a.length)}function NS(a,c){if(a!==c){var h=a!==n,w=a===null,$=a===a,T=ar(a),N=c!==n,I=c===null,z=c===c,re=ar(c);if(!I&&!re&&!T&&a>c||T&&N&&z&&!I&&!re||w&&N&&z||!h&&z||!$)return 1;if(!w&&!T&&!re&&a=I)return z;var re=h[w];return z*(re=="desc"?-1:1)}}return a.index-c.index}function DS(a,c,h,w){for(var $=-1,T=a.length,N=h.length,I=-1,z=c.length,re=tn(T-N,0),oe=Q(z+re),ae=!w;++I1?h[$-1]:n,N=$>2?h[2]:n;for(T=a.length>3&&typeof T=="function"?($--,T):n,N&&Nn(h[0],h[1],N)&&(T=$<3?n:T,$=1),c=St(c);++w<$;){var I=h[w];I&&a(c,I,w,T)}return c})}function LS(a,c){return function(h,w){if(h==null)return h;if(!Hn(h))return a(h,w);for(var $=h.length,T=c?$:-1,N=St(h);(c?T--:++T<$)&&w(N[T],T,N)!==!1;);return h}}function FS(a){return function(c,h,w){for(var $=-1,T=St(c),N=w(c),I=N.length;I--;){var z=N[a?I:++$];if(h(T[z],z,T)===!1)break}return c}}function H7(a,c,h){var w=c&E,$=Xc(a);function T(){var N=this&&this!==fn&&this instanceof T?$:a;return N.apply(w?h:this,arguments)}return T}function jS(a){return function(c){c=vt(c);var h=Wa(c)?Jr(c):n,w=h?h[0]:c.charAt(0),$=h?Wi(h,1).join(""):c.slice(1);return w[a]()+$}}function Qa(a){return function(c){return Ig(L_(I_(c).replace(D6,"")),a,"")}}function Xc(a){return function(){var c=arguments;switch(c.length){case 0:return new a;case 1:return new a(c[0]);case 2:return new a(c[0],c[1]);case 3:return new a(c[0],c[1],c[2]);case 4:return new a(c[0],c[1],c[2],c[3]);case 5:return new a(c[0],c[1],c[2],c[3],c[4]);case 6:return new a(c[0],c[1],c[2],c[3],c[4],c[5]);case 7:return new a(c[0],c[1],c[2],c[3],c[4],c[5],c[6])}var h=Za(a.prototype),w=a.apply(h,c);return It(w)?w:h}}function K7(a,c,h){var w=Xc(a);function $(){for(var T=arguments.length,N=Q(T),I=T,z=Ja($);I--;)N[I]=arguments[I];var re=T<3&&N[0]!==z&&N[T-1]!==z?[]:ji(N,z);if(T-=re.length,T-1?$[T?c[N]:N]:n}}function BS(a){return ii(function(c){var h=c.length,w=h,$=Tr.prototype.thru;for(a&&c.reverse();w--;){var T=c[w];if(typeof T!="function")throw new kr(s);if($&&!N&&Of(T)=="wrapper")var N=new Tr([],!0)}for(w=N?w:h;++w1&&at.reverse(),oe&&zI))return!1;var re=T.get(a),oe=T.get(c);if(re&&oe)return re==c&&oe==a;var ae=-1,ge=!0,Te=h&S?new Ys:n;for(T.set(a,c),T.set(c,a);++ae1?"& ":"")+c[w],c=c.join(h>2?", ":" "),a.replace(an,`{ +/* [wrapped with `+c+`] */ +`)}function oO(a){return Ge(a)||Js(a)||!!(nS&&a&&a[nS])}function si(a,c){var h=typeof a;return c=c??H,!!c&&(h=="number"||h!="symbol"&&g6.test(a))&&a>-1&&a%1==0&&a0){if(++c>=G)return arguments[0]}else c=0;return a.apply(n,arguments)}}function Df(a,c){var h=-1,w=a.length,$=w-1;for(c=c===n?w:c;++h1?a[c-1]:n;return h=typeof h=="function"?(a.pop(),h):n,f_(a,h)});function h_(a){var c=k(a);return c.__chain__=!0,c}function m4(a,c){return c(a),a}function If(a,c){return c(a)}var g4=ii(function(a){var c=a.length,h=c?a[0]:0,w=this.__wrapped__,$=function(T){return Xg(T,a)};return c>1||this.__actions__.length||!(w instanceof ot)||!si(h)?this.thru($):(w=w.slice(h,+h+(c?1:0)),w.__actions__.push({func:If,args:[$],thisArg:n}),new Tr(w,this.__chain__).thru(function(T){return c&&!T.length&&T.push(n),T}))});function v4(){return h_(this)}function y4(){return new Tr(this.value(),this.__chain__)}function w4(){this.__values__===n&&(this.__values__=R_(this.value()));var a=this.__index__>=this.__values__.length,c=a?n:this.__values__[this.__index__++];return{done:a,value:c}}function x4(){return this}function b4(a){for(var c,h=this;h instanceof bf;){var w=s_(h);w.__index__=0,w.__values__=n,c?$.__wrapped__=w:c=w;var $=w;h=h.__wrapped__}return $.__wrapped__=a,c}function S4(){var a=this.__wrapped__;if(a instanceof ot){var c=a;return this.__actions__.length&&(c=new ot(this)),c=c.reverse(),c.__actions__.push({func:If,args:[_v],thisArg:n}),new Tr(c,this.__chain__)}return this.thru(_v)}function _4(){return TS(this.__wrapped__,this.__actions__)}var E4=kf(function(a,c,h){yt.call(a,h)?++a[h]:ri(a,h,1)});function C4(a,c,h){var w=Ge(a)?Ub:m7;return h&&Nn(a,c,h)&&(c=n),w(a,Ie(c,3))}function $4(a,c){var h=Ge(a)?Li:fS;return h(a,Ie(c,3))}var R4=zS(a_),k4=zS(l_);function T4(a,c){return hn(Lf(a,c),1)}function P4(a,c){return hn(Lf(a,c),ee)}function A4(a,c,h){return h=h===n?1:qe(h),hn(Lf(a,c),h)}function p_(a,c){var h=Ge(a)?Rr:Bi;return h(a,Ie(c,3))}function m_(a,c){var h=Ge(a)?Z6:dS;return h(a,Ie(c,3))}var M4=kf(function(a,c,h){yt.call(a,h)?a[h].push(c):ri(a,h,[c])});function O4(a,c,h,w){a=Hn(a)?a:tl(a),h=h&&!w?qe(h):0;var $=a.length;return h<0&&(h=tn($+h,0)),Uf(a)?h<=$&&a.indexOf(c,h)>-1:!!$&&Va(a,c,h)>-1}var N4=et(function(a,c,h){var w=-1,$=typeof c=="function",T=Hn(a)?Q(a.length):[];return Bi(a,function(N){T[++w]=$?or(c,N,h):Kc(N,c,h)}),T}),D4=kf(function(a,c,h){ri(a,h,c)});function Lf(a,c){var h=Ge(a)?Ot:yS;return h(a,Ie(c,3))}function I4(a,c,h,w){return a==null?[]:(Ge(c)||(c=c==null?[]:[c]),h=w?n:h,Ge(h)||(h=h==null?[]:[h]),SS(a,c,h))}var L4=kf(function(a,c,h){a[h?0:1].push(c)},function(){return[[],[]]});function F4(a,c,h){var w=Ge(a)?Ig:Kb,$=arguments.length<3;return w(a,Ie(c,4),h,$,Bi)}function j4(a,c,h){var w=Ge(a)?q6:Kb,$=arguments.length<3;return w(a,Ie(c,4),h,$,dS)}function z4(a,c){var h=Ge(a)?Li:fS;return h(a,zf(Ie(c,3)))}function B4(a){var c=Ge(a)?aS:O7;return c(a)}function U4(a,c,h){(h?Nn(a,c,h):c===n)?c=1:c=qe(c);var w=Ge(a)?u7:N7;return w(a,c)}function V4(a){var c=Ge(a)?d7:I7;return c(a)}function W4(a){if(a==null)return 0;if(Hn(a))return Uf(a)?Ha(a):a.length;var c=Cn(a);return c==ct||c==q?a.size:tv(a).length}function H4(a,c,h){var w=Ge(a)?Lg:L7;return h&&Nn(a,c,h)&&(c=n),w(a,Ie(c,3))}var K4=et(function(a,c){if(a==null)return[];var h=c.length;return h>1&&Nn(a,c[0],c[1])?c=[]:h>2&&Nn(c[0],c[1],c[2])&&(c=[c[0]]),SS(a,hn(c,1),[])}),Ff=$M||function(){return fn.Date.now()};function G4(a,c){if(typeof c!="function")throw new kr(s);return a=qe(a),function(){if(--a<1)return c.apply(this,arguments)}}function g_(a,c,h){return c=h?n:c,c=a&&c==null?a.length:c,oi(a,A,n,n,n,n,c)}function v_(a,c){var h;if(typeof c!="function")throw new kr(s);return a=qe(a),function(){return--a>0&&(h=c.apply(this,arguments)),a<=1&&(c=n),h}}var Cv=et(function(a,c,h){var w=E;if(h.length){var $=ji(h,Ja(Cv));w|=P}return oi(a,w,c,h,$)}),y_=et(function(a,c,h){var w=E|_;if(h.length){var $=ji(h,Ja(y_));w|=P}return oi(c,w,a,h,$)});function w_(a,c,h){c=h?n:c;var w=oi(a,C,n,n,n,n,n,c);return w.placeholder=w_.placeholder,w}function x_(a,c,h){c=h?n:c;var w=oi(a,R,n,n,n,n,n,c);return w.placeholder=x_.placeholder,w}function b_(a,c,h){var w,$,T,N,I,z,re=0,oe=!1,ae=!1,ge=!0;if(typeof a!="function")throw new kr(s);c=Or(c)||0,It(h)&&(oe=!!h.leading,ae="maxWait"in h,T=ae?tn(Or(h.maxWait)||0,c):T,ge="trailing"in h?!!h.trailing:ge);function Te(Yt){var no=w,ci=$;return w=$=n,re=Yt,N=a.apply(ci,no),N}function Le(Yt){return re=Yt,I=qc(nt,c),oe?Te(Yt):N}function Qe(Yt){var no=Yt-z,ci=Yt-re,z_=c-no;return ae?En(z_,T-ci):z_}function Fe(Yt){var no=Yt-z,ci=Yt-re;return z===n||no>=c||no<0||ae&&ci>=T}function nt(){var Yt=Ff();if(Fe(Yt))return at(Yt);I=qc(nt,Qe(Yt))}function at(Yt){return I=n,ge&&w?Te(Yt):(w=$=n,N)}function lr(){I!==n&&AS(I),re=0,w=z=$=I=n}function Dn(){return I===n?N:at(Ff())}function cr(){var Yt=Ff(),no=Fe(Yt);if(w=arguments,$=this,z=Yt,no){if(I===n)return Le(z);if(ae)return AS(I),I=qc(nt,c),Te(z)}return I===n&&(I=qc(nt,c)),N}return cr.cancel=lr,cr.flush=Dn,cr}var Y4=et(function(a,c){return uS(a,1,c)}),X4=et(function(a,c,h){return uS(a,Or(c)||0,h)});function Z4(a){return oi(a,B)}function jf(a,c){if(typeof a!="function"||c!=null&&typeof c!="function")throw new kr(s);var h=function(){var w=arguments,$=c?c.apply(this,w):w[0],T=h.cache;if(T.has($))return T.get($);var N=a.apply(this,w);return h.cache=T.set($,N)||T,N};return h.cache=new(jf.Cache||ni),h}jf.Cache=ni;function zf(a){if(typeof a!="function")throw new kr(s);return function(){var c=arguments;switch(c.length){case 0:return!a.call(this);case 1:return!a.call(this,c[0]);case 2:return!a.call(this,c[0],c[1]);case 3:return!a.call(this,c[0],c[1],c[2])}return!a.apply(this,c)}}function q4(a){return v_(2,a)}var Q4=F7(function(a,c){c=c.length==1&&Ge(c[0])?Ot(c[0],ir(Ie())):Ot(hn(c,1),ir(Ie()));var h=c.length;return et(function(w){for(var $=-1,T=En(w.length,h);++$=c}),Js=mS(function(){return arguments}())?mS:function(a){return Bt(a)&&yt.call(a,"callee")&&!tS.call(a,"callee")},Ge=Q.isArray,hN=Ib?ir(Ib):b7;function Hn(a){return a!=null&&Bf(a.length)&&!ai(a)}function Gt(a){return Bt(a)&&Hn(a)}function pN(a){return a===!0||a===!1||Bt(a)&&On(a)==xe}var Hi=kM||Lv,mN=Lb?ir(Lb):S7;function gN(a){return Bt(a)&&a.nodeType===1&&!Qc(a)}function vN(a){if(a==null)return!0;if(Hn(a)&&(Ge(a)||typeof a=="string"||typeof a.splice=="function"||Hi(a)||el(a)||Js(a)))return!a.length;var c=Cn(a);if(c==ct||c==q)return!a.size;if(Zc(a))return!tv(a).length;for(var h in a)if(yt.call(a,h))return!1;return!0}function yN(a,c){return Gc(a,c)}function wN(a,c,h){h=typeof h=="function"?h:n;var w=h?h(a,c):n;return w===n?Gc(a,c,n,h):!!w}function Rv(a){if(!Bt(a))return!1;var c=On(a);return c==Oe||c==Me||typeof a.message=="string"&&typeof a.name=="string"&&!Qc(a)}function xN(a){return typeof a=="number"&&rS(a)}function ai(a){if(!It(a))return!1;var c=On(a);return c==ze||c==Mt||c==fe||c==L}function __(a){return typeof a=="number"&&a==qe(a)}function Bf(a){return typeof a=="number"&&a>-1&&a%1==0&&a<=H}function It(a){var c=typeof a;return a!=null&&(c=="object"||c=="function")}function Bt(a){return a!=null&&typeof a=="object"}var E_=Fb?ir(Fb):E7;function bN(a,c){return a===c||ev(a,c,vv(c))}function SN(a,c,h){return h=typeof h=="function"?h:n,ev(a,c,vv(c),h)}function _N(a){return C_(a)&&a!=+a}function EN(a){if(aO(a))throw new Ke(i);return gS(a)}function CN(a){return a===null}function $N(a){return a==null}function C_(a){return typeof a=="number"||Bt(a)&&On(a)==Kt}function Qc(a){if(!Bt(a)||On(a)!=gt)return!1;var c=pf(a);if(c===null)return!0;var h=yt.call(c,"constructor")&&c.constructor;return typeof h=="function"&&h instanceof h&&uf.call(h)==SM}var kv=jb?ir(jb):C7;function RN(a){return __(a)&&a>=-H&&a<=H}var $_=zb?ir(zb):$7;function Uf(a){return typeof a=="string"||!Ge(a)&&Bt(a)&&On(a)==we}function ar(a){return typeof a=="symbol"||Bt(a)&&On(a)==me}var el=Bb?ir(Bb):R7;function kN(a){return a===n}function TN(a){return Bt(a)&&Cn(a)==ke}function PN(a){return Bt(a)&&On(a)==ft}var AN=Mf(nv),MN=Mf(function(a,c){return a<=c});function R_(a){if(!a)return[];if(Hn(a))return Uf(a)?Jr(a):Wn(a);if(jc&&a[jc])return uM(a[jc]());var c=Cn(a),h=c==ct?Vg:c==q?af:tl;return h(a)}function li(a){if(!a)return a===0?a:0;if(a=Or(a),a===ee||a===-ee){var c=a<0?-1:1;return c*X}return a===a?a:0}function qe(a){var c=li(a),h=c%1;return c===c?h?c-h:c:0}function k_(a){return a?Xs(qe(a),0,le):0}function Or(a){if(typeof a=="number")return a;if(ar(a))return W;if(It(a)){var c=typeof a.valueOf=="function"?a.valueOf():a;a=It(c)?c+"":c}if(typeof a!="string")return a===0?a:+a;a=Gb(a);var h=h6.test(a);return h||m6.test(a)?G6(a.slice(2),h?2:8):f6.test(a)?W:+a}function T_(a){return Ro(a,Kn(a))}function ON(a){return a?Xs(qe(a),-H,H):a===0?a:0}function vt(a){return a==null?"":sr(a)}var NN=qa(function(a,c){if(Zc(c)||Hn(c)){Ro(c,ln(c),a);return}for(var h in c)yt.call(c,h)&&Wc(a,h,c[h])}),P_=qa(function(a,c){Ro(c,Kn(c),a)}),Vf=qa(function(a,c,h,w){Ro(c,Kn(c),a,w)}),DN=qa(function(a,c,h,w){Ro(c,ln(c),a,w)}),IN=ii(Xg);function LN(a,c){var h=Za(a);return c==null?h:lS(h,c)}var FN=et(function(a,c){a=St(a);var h=-1,w=c.length,$=w>2?c[2]:n;for($&&Nn(c[0],c[1],$)&&(w=1);++h1),T}),Ro(a,mv(a),h),w&&(h=Pr(h,m|g|y,X7));for(var $=c.length;$--;)av(h,c[$]);return h});function n8(a,c){return M_(a,zf(Ie(c)))}var r8=ii(function(a,c){return a==null?{}:P7(a,c)});function M_(a,c){if(a==null)return{};var h=Ot(mv(a),function(w){return[w]});return c=Ie(c),_S(a,h,function(w,$){return c(w,$[0])})}function o8(a,c,h){c=Vi(c,a);var w=-1,$=c.length;for($||($=1,a=n);++w<$;){var T=a==null?n:a[ko(c[w])];T===n&&(w=$,T=h),a=ai(T)?T.call(a):T}return a}function i8(a,c,h){return a==null?a:Yc(a,c,h)}function s8(a,c,h,w){return w=typeof w=="function"?w:n,a==null?a:Yc(a,c,h,w)}var O_=HS(ln),N_=HS(Kn);function a8(a,c,h){var w=Ge(a),$=w||Hi(a)||el(a);if(c=Ie(c,4),h==null){var T=a&&a.constructor;$?h=w?new T:[]:It(a)?h=ai(T)?Za(pf(a)):{}:h={}}return($?Rr:$o)(a,function(N,I,z){return c(h,N,I,z)}),h}function l8(a,c){return a==null?!0:av(a,c)}function c8(a,c,h){return a==null?a:kS(a,c,uv(h))}function u8(a,c,h,w){return w=typeof w=="function"?w:n,a==null?a:kS(a,c,uv(h),w)}function tl(a){return a==null?[]:Ug(a,ln(a))}function d8(a){return a==null?[]:Ug(a,Kn(a))}function f8(a,c,h){return h===n&&(h=c,c=n),h!==n&&(h=Or(h),h=h===h?h:0),c!==n&&(c=Or(c),c=c===c?c:0),Xs(Or(a),c,h)}function h8(a,c,h){return c=li(c),h===n?(h=c,c=0):h=li(h),a=Or(a),w7(a,c,h)}function p8(a,c,h){if(h&&typeof h!="boolean"&&Nn(a,c,h)&&(c=h=n),h===n&&(typeof c=="boolean"?(h=c,c=n):typeof a=="boolean"&&(h=a,a=n)),a===n&&c===n?(a=0,c=1):(a=li(a),c===n?(c=a,a=0):c=li(c)),a>c){var w=a;a=c,c=w}if(h||a%1||c%1){var $=oS();return En(a+$*(c-a+K6("1e-"+(($+"").length-1))),c)}return ov(a,c)}var m8=Qa(function(a,c,h){return c=c.toLowerCase(),a+(h?D_(c):c)});function D_(a){return Av(vt(a).toLowerCase())}function I_(a){return a=vt(a),a&&a.replace(v6,iM).replace(I6,"")}function g8(a,c,h){a=vt(a),c=sr(c);var w=a.length;h=h===n?w:Xs(qe(h),0,w);var $=h;return h-=c.length,h>=0&&a.slice(h,$)==c}function v8(a){return a=vt(a),a&&Eg.test(a)?a.replace(Nc,sM):a}function y8(a){return a=vt(a),a&&Ye.test(a)?a.replace(K,"\\$&"):a}var w8=Qa(function(a,c,h){return a+(h?"-":"")+c.toLowerCase()}),x8=Qa(function(a,c,h){return a+(h?" ":"")+c.toLowerCase()}),b8=jS("toLowerCase");function S8(a,c,h){a=vt(a),c=qe(c);var w=c?Ha(a):0;if(!c||w>=c)return a;var $=(c-w)/2;return Af(yf($),h)+a+Af(vf($),h)}function _8(a,c,h){a=vt(a),c=qe(c);var w=c?Ha(a):0;return c&&w>>0,h?(a=vt(a),a&&(typeof c=="string"||c!=null&&!kv(c))&&(c=sr(c),!c&&Wa(a))?Wi(Jr(a),0,h):a.split(c,h)):[]}var P8=Qa(function(a,c,h){return a+(h?" ":"")+Av(c)});function A8(a,c,h){return a=vt(a),h=h==null?0:Xs(qe(h),0,a.length),c=sr(c),a.slice(h,h+c.length)==c}function M8(a,c,h){var w=k.templateSettings;h&&Nn(a,c,h)&&(c=n),a=vt(a),c=Vf({},c,w,KS);var $=Vf({},c.imports,w.imports,KS),T=ln($),N=Ug($,T),I,z,re=0,oe=c.interpolate||tf,ae="__p += '",ge=Wg((c.escape||tf).source+"|"+oe.source+"|"+(oe===Lc?d6:tf).source+"|"+(c.evaluate||tf).source+"|$","g"),Te="//# sourceURL="+(yt.call(c,"sourceURL")?(c.sourceURL+"").replace(/\s/g," "):"lodash.templateSources["+ ++B6+"]")+` +`;a.replace(ge,function(Fe,nt,at,lr,Dn,cr){return at||(at=lr),ae+=a.slice(re,cr).replace(y6,aM),nt&&(I=!0,ae+=`' + +__e(`+nt+`) + +'`),Dn&&(z=!0,ae+=`'; +`+Dn+`; +__p += '`),at&&(ae+=`' + +((__t = (`+at+`)) == null ? '' : __t) + +'`),re=cr+Fe.length,Fe}),ae+=`'; +`;var Le=yt.call(c,"variable")&&c.variable;if(!Le)ae=`with (obj) { +`+ae+` +} +`;else if(c6.test(Le))throw new Ke(l);ae=(z?ae.replace(Sg,""):ae).replace(_g,"$1").replace(Qd,"$1;"),ae="function("+(Le||"obj")+`) { +`+(Le?"":`obj || (obj = {}); +`)+"var __t, __p = ''"+(I?", __e = _.escape":"")+(z?`, __j = Array.prototype.join; +function print() { __p += __j.call(arguments, '') } +`:`; +`)+ae+`return __p +}`;var Qe=F_(function(){return pt(T,Te+"return "+ae).apply(n,N)});if(Qe.source=ae,Rv(Qe))throw Qe;return Qe}function O8(a){return vt(a).toLowerCase()}function N8(a){return vt(a).toUpperCase()}function D8(a,c,h){if(a=vt(a),a&&(h||c===n))return Gb(a);if(!a||!(c=sr(c)))return a;var w=Jr(a),$=Jr(c),T=Yb(w,$),N=Xb(w,$)+1;return Wi(w,T,N).join("")}function I8(a,c,h){if(a=vt(a),a&&(h||c===n))return a.slice(0,qb(a)+1);if(!a||!(c=sr(c)))return a;var w=Jr(a),$=Xb(w,Jr(c))+1;return Wi(w,0,$).join("")}function L8(a,c,h){if(a=vt(a),a&&(h||c===n))return a.replace(st,"");if(!a||!(c=sr(c)))return a;var w=Jr(a),$=Yb(w,Jr(c));return Wi(w,$).join("")}function F8(a,c){var h=V,w=J;if(It(c)){var $="separator"in c?c.separator:$;h="length"in c?qe(c.length):h,w="omission"in c?sr(c.omission):w}a=vt(a);var T=a.length;if(Wa(a)){var N=Jr(a);T=N.length}if(h>=T)return a;var I=h-Ha(w);if(I<1)return w;var z=N?Wi(N,0,I).join(""):a.slice(0,I);if($===n)return z+w;if(N&&(I+=z.length-I),kv($)){if(a.slice(I).search($)){var re,oe=z;for($.global||($=Wg($.source,vt(mb.exec($))+"g")),$.lastIndex=0;re=$.exec(oe);)var ae=re.index;z=z.slice(0,ae===n?I:ae)}}else if(a.indexOf(sr($),I)!=I){var ge=z.lastIndexOf($);ge>-1&&(z=z.slice(0,ge))}return z+w}function j8(a){return a=vt(a),a&&Dc.test(a)?a.replace(Oc,pM):a}var z8=Qa(function(a,c,h){return a+(h?" ":"")+c.toUpperCase()}),Av=jS("toUpperCase");function L_(a,c,h){return a=vt(a),c=h?n:c,c===n?cM(a)?vM(a):eM(a):a.match(c)||[]}var F_=et(function(a,c){try{return or(a,n,c)}catch(h){return Rv(h)?h:new Ke(h)}}),B8=ii(function(a,c){return Rr(c,function(h){h=ko(h),ri(a,h,Cv(a[h],a))}),a});function U8(a){var c=a==null?0:a.length,h=Ie();return a=c?Ot(a,function(w){if(typeof w[1]!="function")throw new kr(s);return[h(w[0]),w[1]]}):[],et(function(w){for(var $=-1;++$H)return[];var h=le,w=En(a,le);c=Ie(c),a-=le;for(var $=Bg(w,c);++h0||c<0)?new ot(h):(a<0?h=h.takeRight(-a):a&&(h=h.drop(a)),c!==n&&(c=qe(c),h=c<0?h.dropRight(-c):h.take(c-a)),h)},ot.prototype.takeRightWhile=function(a){return this.reverse().takeWhile(a).reverse()},ot.prototype.toArray=function(){return this.take(le)},$o(ot.prototype,function(a,c){var h=/^(?:filter|find|map|reject)|While$/.test(c),w=/^(?:head|last)$/.test(c),$=k[w?"take"+(c=="last"?"Right":""):c],T=w||/^find/.test(c);$&&(k.prototype[c]=function(){var N=this.__wrapped__,I=w?[1]:arguments,z=N instanceof ot,re=I[0],oe=z||Ge(N),ae=function(nt){var at=$.apply(k,Fi([nt],I));return w&&ge?at[0]:at};oe&&h&&typeof re=="function"&&re.length!=1&&(z=oe=!1);var ge=this.__chain__,Te=!!this.__actions__.length,Le=T&&!ge,Qe=z&&!Te;if(!T&&oe){N=Qe?N:new ot(this);var Fe=a.apply(N,I);return Fe.__actions__.push({func:If,args:[ae],thisArg:n}),new Tr(Fe,ge)}return Le&&Qe?a.apply(this,I):(Fe=this.thru(ae),Le?w?Fe.value()[0]:Fe.value():Fe)})}),Rr(["pop","push","shift","sort","splice","unshift"],function(a){var c=lf[a],h=/^(?:push|sort|unshift)$/.test(a)?"tap":"thru",w=/^(?:pop|shift)$/.test(a);k.prototype[a]=function(){var $=arguments;if(w&&!this.__chain__){var T=this.value();return c.apply(Ge(T)?T:[],$)}return this[h](function(N){return c.apply(Ge(N)?N:[],$)})}}),$o(ot.prototype,function(a,c){var h=k[c];if(h){var w=h.name+"";yt.call(Xa,w)||(Xa[w]=[]),Xa[w].push({name:c,func:h})}}),Xa[Tf(n,_).name]=[{name:"wrapper",func:n}],ot.prototype.clone=jM,ot.prototype.reverse=zM,ot.prototype.value=BM,k.prototype.at=g4,k.prototype.chain=v4,k.prototype.commit=y4,k.prototype.next=w4,k.prototype.plant=b4,k.prototype.reverse=S4,k.prototype.toJSON=k.prototype.valueOf=k.prototype.value=_4,k.prototype.first=k.prototype.head,jc&&(k.prototype[jc]=x4),k},Ka=yM();Hs?((Hs.exports=Ka)._=Ka,Og._=Ka):fn._=Ka}).call(Jc)})(zp,zp.exports);var wH=zp.exports;const xH=dm(wH);function Vr({width:e,height:t}){return e/t}function Bp(e,t=0){const n=10**t;return Math.round((e+Number.EPSILON)*n)/n}function bH(e){return(t,n)=>e(n)-e(t)}class SH{constructor(t){this.comparator=t,this.heap=[],this.n=0}greater(t,n){return this.comparator(this.heap[t],this.heap[n])<0}swap(t,n){const r=this.heap[t];this.heap[t]=this.heap[n],this.heap[n]=r}swim(t){let n=t,r=Math.floor(n/2);for(;n>1&&this.greater(r,n);)this.swap(r,n),n=r,r=Math.floor(n/2)}sink(t){let n=t,r=n*2;for(;r<=this.n&&(rl.weight));for(s.push({id:t,weight:0});s.size()>0;){const{id:l,weight:u}=s.pop();if(!o.has(l)){const f=e(l);o.add(l),f.forEach((p,m)=>{const g=u+p,y=r.get(m),x=i.get(m);(x===void 0||x>g&&(x/g>1.005||y!==void 0&&yMath.min(Vr(i),o),Number.MAX_VALUE);return Bp(n/t/r)+2}function IT(e,t,n,r){const o=t-(e.length-1)*n-2*r*e.length,i=e.reduce((s,l)=>s+Vr(l),0);return o/i}function RH(e,t,n,r,o,i,s){const l=e.slice(t,n),u=IT(l,r,i,s);return u>0?(u-o)**2*l.length:void 0}function kH({photos:e,layoutOptions:t,targetRowHeight:n,limitNodeSearch:r,rowConstraints:o}){return i=>{var s,l;const{containerWidth:u,spacing:f,padding:p}=t,m=new Map;m.set(i,0);const g=(s=o==null?void 0:o.minPhotos)!=null?s:1,y=Math.min(r,(l=o==null?void 0:o.maxPhotos)!=null?l:1/0);for(let x=i+g;xy);x+=1){const S=RH(e,i,x,u,n,f,p);if(S===void 0)break;m.set(x,S)}return m}}function TH({photos:e,layoutOptions:t}){const{spacing:n,padding:r,containerWidth:o,targetRowHeight:i,rowConstraints:s}=t,l=$H({photos:e,containerWidth:o,targetRowHeight:i}),u=kH({photos:e,layoutOptions:t,targetRowHeight:i,limitNodeSearch:l,rowConstraints:s}),f=CH(u,0,e.length);if(f===void 0)return;const p=[];for(let m=1;m({photo:x,index:S})).slice(f[m-1],f[m]),y=IT(g.map(({photo:x})=>x),o,n,r);p.push(g.map(({photo:x,index:S},E)=>({photo:x,layout:{height:y,width:y*Vr(x),index:S,photoIndex:E,photosCount:g.length}})))}return p}function tg(...e){return[...e].filter(t=>!!t).join(" ")}function LT(e,{width:t,photosCount:n},{spacing:r,padding:o,containerWidth:i}){const s=r*(n-1)+2*o*n;return`calc((${e} - ${s}px) / ${Bp((i-s)/t,5)})`}function PH(e,t){return t.layout!=="rows"?`calc(100% - ${2*t.padding}px)`:LT("100%",e,t)}function c2(e,t,n){var r,o;return LT((o=(r=e.match(/calc\((.*)\)/))==null?void 0:r[1])!=null?o:e,t,n)}function AH(e,t,n){let r,o;const i=e.srcSet||e.images;return i&&i.length>0&&(r=i.concat(i.find(({width:s})=>s===e.width)?[]:[{src:e.src,width:e.width,height:e.height}]).sort((s,l)=>s.width-l.width).map(s=>`${s.src} ${s.width}w`).join(", ")),n.sizes?o=(n.sizes.sizes||[]).map(({viewport:s,size:l})=>`${s} ${c2(l,t,n)}`).concat(c2(n.sizes.size,t,n)).join(", "):r&&(o=`${Math.ceil(t.width/n.containerWidth*100)}vw`),{srcSet:r,sizes:o}}function Ix(e){var t,n;const{photo:r,layout:o,layoutOptions:i,imageProps:{style:s,className:l,...u}={},renderPhoto:f}=e,{onClick:p}=i,m={display:"block",boxSizing:"content-box",width:PH(o,i),height:"auto",aspectRatio:`${r.width} / ${r.height}`,...i.padding?{padding:`${i.padding}px`}:null,...(i.layout==="columns"||i.layout==="masonry")&&o.photoIndex{p({event:E,photo:r,index:o.index})}:void 0,y={src:r.src,alt:(t=r.alt)!=null?t:"",title:r.title,onClick:g,style:m,className:tg("react-photo-album--photo",l),loading:"lazy",decoding:"async",...AH(r,o,i),...u},x=E=>{const{src:_,alt:b,srcSet:C,sizes:R,style:P,...O}=y;return d.createElement("img",{alt:b,...C?{srcSet:C,sizes:R}:null,src:_,style:E!=null&&E.wrapped?{display:"block",width:"100%",height:"100%"}:P,...O})},S=(({display:E,boxSizing:_,width:b,aspectRatio:C,padding:R,marginBottom:P,cursor:O})=>({display:E,boxSizing:_,width:b,aspectRatio:C,padding:R,marginBottom:P,cursor:O}))(m);return d.createElement(d.Fragment,null,(n=f==null?void 0:f({photo:r,layout:o,layoutOptions:i,imageProps:y,renderDefaultPhoto:x,wrapperStyle:S}))!=null?n:x())}function MH({rowContainerProps:e,children:t}){return d.createElement("div",{...e},t)}function OH(e){const{layoutOptions:t,rowIndex:n,rowsCount:r,renderRowContainer:o,rowContainerProps:{style:i,className:s,...l}={},children:u}=e,f={className:tg("react-photo-album--row",s),style:{display:"flex",flexDirection:"row",flexWrap:"nowrap",alignItems:"flex-start",justifyContent:"space-between",...nd.createElement(OH,{key:`row-${f}`,layoutOptions:n,rowIndex:f,rowsCount:l.length,renderRowContainer:o,rowContainerProps:s},u.map(({photo:p,layout:m})=>d.createElement(Ix,{key:p.key||p.src,photo:p,layout:m,layoutOptions:n,renderPhoto:r,imageProps:i}))))):null}function DH(e,t,n,r){const o=new Map,i=new Set;i.add(n);for(let s=0;s{const f=s>0?o.get(u)[s].weight:0;e(u).forEach(({neighbor:p,weight:m})=>{let g=o.get(p);g||(g=[],o.set(p,g));const y=f+m,x=g[s+1];(!x||x.weight>y&&(x.weight/y>1.0001||u0;i-=1)o=e.get(o)[i].node,r.push(o);return r.reverse()}function LH(e,t,n,r){return IH(DH(e,t,n,r),t,r)}function FH({photos:e,spacing:t,padding:n,targetColumnWidth:r,targetColumnHeight:o}){return i=>{const s=[],l=o*1.5;let u=r/Vr(e[i])+2*n;for(let f=i+1;fl||f===e.length));f+=1)u+=r/Vr(e[f])+t+2*n;return s}}function u2({path:e,photos:t,containerWidth:n,columnsGaps:r,columnsRatios:o,spacing:i,padding:s}){const l=[],u=o.reduce((f,p)=>f+p,0);for(let f=0;f({photo:y,index:x})).slice(e[f],e[f+1]),m=o.reduce((y,x,S)=>y+(r[f]-r[S])*x,0),g=(n-(e.length-2)*i-2*(e.length-1)*s-m)*o[f]/u;l.push(p.map(({photo:y,index:x},S)=>({photo:y,layout:{width:g,height:g/Vr(y),index:x,photoIndex:S,photosCount:p.length}})))}return l}function jH({photos:e,layoutOptions:t,targetColumnWidth:n}){const{columns:r,spacing:o,padding:i,containerWidth:s}=t,l=[],u=[];if(e.length<=r){const y=e.length>0?e.reduce((S,E)=>S+Vr(E),0)/e.length:1;for(let S=0;SMath.min(E,e.length)),photos:e,columnsRatios:u,columnsGaps:l,containerWidth:s,spacing:o,padding:i});return{columnsGaps:l,columnsRatios:u,columnsModel:x}}const f=(e.reduce((y,x)=>y+n/Vr(x),0)+o*(e.length-r)+2*i*e.length)/r,p=FH({photos:e,targetColumnWidth:n,targetColumnHeight:f,spacing:o,padding:i}),m=LH(p,r,0,e.length);for(let y=0;yS+1/Vr(E),0)}const g=u2({path:m,photos:e,columnsRatios:u,columnsGaps:l,containerWidth:s,spacing:o,padding:i});return{columnsGaps:l,columnsRatios:u,columnsModel:g}}function FT(e){const{photos:t,layoutOptions:n}=e,{columns:r,spacing:o,padding:i,containerWidth:s}=n,l=(s-o*(r-1)-2*i*r)/r,{columnsGaps:u,columnsRatios:f,columnsModel:p}=jH({photos:t,layoutOptions:n,targetColumnWidth:l});return p.findIndex(m=>m.findIndex(({layout:{width:g,height:y}})=>g<0||y<0)>=0)>=0?r>1?FT({photos:t,layoutOptions:{...n,columns:r-1}}):void 0:{columnsModel:p,columnsGaps:u,columnsRatios:f}}function zH({photos:e,layoutOptions:t}){return FT({photos:e,layoutOptions:t})}function BH({columnContainerProps:e,children:t}){return d.createElement("div",{...e},t)}function UH(e){const{layoutOptions:t,columnIndex:n,columnsCount:r,columnsGaps:o,columnsRatios:i}=e,{layout:s,spacing:l,padding:u}=t;if(s==="masonry"||!o||!i)return`calc((100% - ${l*(r-1)}px) / ${r})`;const f=i.reduce((m,g)=>m+g,0),p=i.reduce((m,g,y)=>m+(o[n]-o[y])*g,0);return`calc((100% - ${Bp((r-1)*l+2*r*u+p,3)}px) * ${Bp(i[n]/f,5)} + ${2*u}px)`}function jT(e){const{layoutOptions:t,renderColumnContainer:n,children:r,columnContainerProps:{style:o,className:i,...s}={},...l}=e,u={className:tg("react-photo-album--column",i),style:{display:"flex",flexDirection:"column",flexWrap:"nowrap",alignItems:"flex-start",width:UH(e),justifyContent:t.layout==="columns"?"space-between":"flex-start",...o},...s};return d.createElement(d.Fragment,null,(n??BH)({layoutOptions:t,columnContainerProps:u,children:r,...l}))}function VH(e){const{photos:t,layoutOptions:n,renderPhoto:r,renderColumnContainer:o,componentsProps:{imageProps:i,columnContainerProps:s}}=e,l=zH({photos:t,layoutOptions:n});if(!l)return null;const{columnsModel:u,columnsRatios:f,columnsGaps:p}=l;return d.createElement(d.Fragment,null,u.map((m,g)=>d.createElement(jT,{key:`column-${g}`,layoutOptions:n,columnIndex:g,columnsCount:u.length,columnsGaps:p,columnsRatios:f,renderColumnContainer:o,columnContainerProps:s},m.map(({photo:y,layout:x})=>d.createElement(Ix,{key:y.key||y.src,photo:y,layout:x,layoutOptions:n,renderPhoto:r,imageProps:i})))))}function zT(e){const{photos:t,layoutOptions:n}=e,{columns:r,spacing:o,padding:i,containerWidth:s}=n,l=(s-o*(r-1)-2*i*r)/r;if(l<=0)return r>1?zT({...e,layoutOptions:{...n,columns:r-1}}):void 0;const u=[];for(let p=0;p{const y=u.reduce((x,S,E)=>S[])).map(p=>p.map(({photo:m,index:g},y)=>({photo:m,layout:{width:l,height:l/Vr(m),index:g,photoIndex:y,photosCount:p.length}})))}function WH(e){const{photos:t,layoutOptions:n,renderPhoto:r,renderColumnContainer:o,componentsProps:{imageProps:i,columnContainerProps:s}}=e,l=zT({photos:t,layoutOptions:n});return l?d.createElement(d.Fragment,null,l.map((u,f)=>d.createElement(jT,{key:`masonry-column-${f}`,layoutOptions:n,columnsCount:l.length,columnIndex:f,renderColumnContainer:o,columnContainerProps:s},u.map(({photo:p,layout:m})=>d.createElement(Ix,{key:p.key||p.src,photo:p,layout:m,layoutOptions:n,renderPhoto:r,imageProps:i}))))):null}function HH({containerProps:e,children:t,containerRef:n}){return d.createElement("div",{ref:n,...e},t)}function KH(e){const{layout:t,renderContainer:n,children:r,containerRef:o,containerProps:{style:i,className:s,...l}={}}=e,u={className:tg("react-photo-album",`react-photo-album--${t}`,s),style:{display:"flex",flexWrap:"nowrap",justifyContent:"space-between",flexDirection:t==="rows"?"column":"row",...i},...l};return d.createElement(d.Fragment,null,(n??HH)({containerProps:u,containerRef:o,layout:t,children:r}))}function GH(e){const t=d.useRef(e);return(!e||!t.current||e.join()!==t.current.join())&&(t.current=e),t.current}function YH(e,{newContainerWidth:t,newScrollbarWidth:n}){const{containerWidth:r,scrollbarWidth:o}=e;return r!==void 0&&o!==void 0&&t!==void 0&&n!==void 0&&t>r&&t-r<=20&&n0){const r=[...t.filter(i=>i>0)].sort((i,s)=>s-i);r.push(Math.floor(r[r.length-1]/2));const o=n;n=r.find((i,s)=>i<=o||s===r.length-1)}return n}function ZH(e,t){const[{containerWidth:n},r]=d.useReducer(YH,{containerWidth:t}),o=d.useRef(null),i=d.useRef();return{containerRef:d.useCallback(l=>{var u;(u=i.current)==null||u.disconnect(),i.current=void 0,o.current=l;const f=()=>r({newContainerWidth:XH(o.current,e),newScrollbarWidth:window.innerWidth-document.documentElement.clientWidth});f(),l&&typeof ResizeObserver<"u"&&(i.current=new ResizeObserver(f),i.current.observe(l))},[e]),containerWidth:n}}const qH=Object.freeze([1200,600,300,0]);function Lx(e,t){return typeof e=="function"?e(t):e}function BT(e,t){return typeof e<"u"?Lx(e,t):void 0}function QH(e,t){const n=qH.findIndex(r=>r<=t);return Lx(e[n>=0?n:0],t)}function yh(e,t,n,r=0){const o=BT(e,t);return Math.round(Math.max(o===void 0?QH(n,t):o,r))}function JH({layout:e,onClick:t,containerWidth:n,targetRowHeight:r,rowConstraints:o,columns:i,spacing:s,padding:l,sizes:u}){return{layout:e,onClick:t,containerWidth:n,columns:yh(i,n,[5,4,3,2],1),spacing:yh(s,n,[20,15,10,5]),padding:yh(l,n,[0,0,0,0,0]),targetRowHeight:yh(r,n,[f=>f/5,f=>f/4,f=>f/3,f=>f/2]),rowConstraints:BT(o,n),sizes:u}}function eK(e,t,n){const{photos:r,componentsProps:o}=e,i=Lx(o,t)||{};if(n){const{layout:s,spacing:l,padding:u,rowConstraints:f}=n;if(s==="rows"){const{singleRowMaxHeight:p}=f||{};if(p){const m=Math.floor(r.reduce((g,{width:y,height:x})=>g+y/x*p-2*u,u*r.length*2+l*(r.length-1)));m>0&&(i.containerProps=i.containerProps||{},i.containerProps.style={maxWidth:m,...i.containerProps.style})}}}return i}function tK(e,t,n){const{photos:r,layout:o,renderPhoto:i,renderRowContainer:s,renderColumnContainer:l}=e,u={photos:r,renderPhoto:i,componentsProps:t};return o==="rows"?d.createElement(NH,{layoutOptions:n,renderRowContainer:s,...u}):o==="columns"?d.createElement(VH,{layoutOptions:n,renderColumnContainer:l,...u}):d.createElement(WH,{layoutOptions:n,renderColumnContainer:l,...u})}function nK(e){const{photos:t,layout:n,renderContainer:r,defaultContainerWidth:o,breakpoints:i}=e,{containerRef:s,containerWidth:l}=ZH(GH(i),o);if(!n||!["rows","columns","masonry"].includes(n)||!Array.isArray(t))return null;const u=l?JH({containerWidth:l,...e}):void 0,f=eK(e,l,u);return d.createElement(KH,{layout:n,containerRef:s,renderContainer:r,containerProps:f.containerProps},u&&tK(e,f,u))}function rK({title:e,titleId:t,...n},r){return d.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true",ref:r,"aria-labelledby":t},n),e?d.createElement("title",{id:t},e):null,d.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3 4.5h14.25M3 9h9.75M3 13.5h9.75m4.5-4.5v12m0 0l-3.75-3.75M17.25 21L21 17.25"}))}const oK=d.forwardRef(rK),iK=oK;function sK({title:e,titleId:t,...n},r){return d.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true",ref:r,"aria-labelledby":t},n),e?d.createElement("title",{id:t},e):null,d.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3 4.5h14.25M3 9h9.75M3 13.5h5.25m5.25-.75L17.25 9m0 0L21 12.75M17.25 9v12"}))}const aK=d.forwardRef(sK),lK=aK;function cK({title:e,titleId:t,...n},r){return d.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true",ref:r,"aria-labelledby":t},n),e?d.createElement("title",{id:t},e):null,d.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15.042 21.672L13.684 16.6m0 0l-2.51 2.225.569-9.47 5.227 7.917-3.286-.672zM12 2.25V4.5m5.834.166l-1.591 1.591M20.25 10.5H18M7.757 14.743l-1.59 1.59M6 10.5H3.75m4.007-4.243l-1.59-1.59"}))}const uK=d.forwardRef(cK),dK=uK;function ki(e){return Array.isArray?Array.isArray(e):WT(e)==="[object Array]"}const fK=1/0;function hK(e){if(typeof e=="string")return e;let t=e+"";return t=="0"&&1/e==-fK?"-0":t}function pK(e){return e==null?"":hK(e)}function Bo(e){return typeof e=="string"}function UT(e){return typeof e=="number"}function mK(e){return e===!0||e===!1||gK(e)&&WT(e)=="[object Boolean]"}function VT(e){return typeof e=="object"}function gK(e){return VT(e)&&e!==null}function pr(e){return e!=null}function M0(e){return!e.trim().length}function WT(e){return e==null?e===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}const vK="Incorrect 'index' type",yK=e=>`Invalid value for key ${e}`,wK=e=>`Pattern length exceeds max of ${e}.`,xK=e=>`Missing ${e} property in key`,bK=e=>`Property 'weight' in key '${e}' must be a positive integer`,d2=Object.prototype.hasOwnProperty;class SK{constructor(t){this._keys=[],this._keyMap={};let n=0;t.forEach(r=>{let o=HT(r);this._keys.push(o),this._keyMap[o.id]=o,n+=o.weight}),this._keys.forEach(r=>{r.weight/=n})}get(t){return this._keyMap[t]}keys(){return this._keys}toJSON(){return JSON.stringify(this._keys)}}function HT(e){let t=null,n=null,r=null,o=1,i=null;if(Bo(e)||ki(e))r=e,t=f2(e),n=g1(e);else{if(!d2.call(e,"name"))throw new Error(xK("name"));const s=e.name;if(r=s,d2.call(e,"weight")&&(o=e.weight,o<=0))throw new Error(bK(s));t=f2(s),n=g1(s),i=e.getFn}return{path:t,id:n,weight:o,src:r,getFn:i}}function f2(e){return ki(e)?e:e.split(".")}function g1(e){return ki(e)?e.join("."):e}function _K(e,t){let n=[],r=!1;const o=(i,s,l)=>{if(pr(i))if(!s[l])n.push(i);else{let u=s[l];const f=i[u];if(!pr(f))return;if(l===s.length-1&&(Bo(f)||UT(f)||mK(f)))n.push(pK(f));else if(ki(f)){r=!0;for(let p=0,m=f.length;pe.score===t.score?e.idx{this._keysMap[n.id]=r})}create(){this.isCreated||!this.docs.length||(this.isCreated=!0,Bo(this.docs[0])?this.docs.forEach((t,n)=>{this._addString(t,n)}):this.docs.forEach((t,n)=>{this._addObject(t,n)}),this.norm.clear())}add(t){const n=this.size();Bo(t)?this._addString(t,n):this._addObject(t,n)}removeAt(t){this.records.splice(t,1);for(let n=t,r=this.size();n{let s=o.getFn?o.getFn(t):this.getFn(t,o.path);if(pr(s)){if(ki(s)){let l=[];const u=[{nestedArrIndex:-1,value:s}];for(;u.length;){const{nestedArrIndex:f,value:p}=u.pop();if(pr(p))if(Bo(p)&&!M0(p)){let m={v:p,i:f,n:this.norm.get(p)};l.push(m)}else ki(p)&&p.forEach((m,g)=>{u.push({nestedArrIndex:g,value:m})})}r.$[i]=l}else if(Bo(s)&&!M0(s)){let l={v:s,n:this.norm.get(s)};r.$[i]=l}}}),this.records.push(r)}toJSON(){return{keys:this.keys,records:this.records}}}function KT(e,t,{getFn:n=He.getFn,fieldNormWeight:r=He.fieldNormWeight}={}){const o=new Fx({getFn:n,fieldNormWeight:r});return o.setKeys(e.map(HT)),o.setSources(t),o.create(),o}function PK(e,{getFn:t=He.getFn,fieldNormWeight:n=He.fieldNormWeight}={}){const{keys:r,records:o}=e,i=new Fx({getFn:t,fieldNormWeight:n});return i.setKeys(r),i.setIndexRecords(o),i}function wh(e,{errors:t=0,currentLocation:n=0,expectedLocation:r=0,distance:o=He.distance,ignoreLocation:i=He.ignoreLocation}={}){const s=t/e.length;if(i)return s;const l=Math.abs(r-n);return o?s+l/o:l?1:s}function AK(e=[],t=He.minMatchCharLength){let n=[],r=-1,o=-1,i=0;for(let s=e.length;i=t&&n.push([r,o]),r=-1)}return e[i-1]&&i-r>=t&&n.push([r,i-1]),n}const la=32;function MK(e,t,n,{location:r=He.location,distance:o=He.distance,threshold:i=He.threshold,findAllMatches:s=He.findAllMatches,minMatchCharLength:l=He.minMatchCharLength,includeMatches:u=He.includeMatches,ignoreLocation:f=He.ignoreLocation}={}){if(t.length>la)throw new Error(wK(la));const p=t.length,m=e.length,g=Math.max(0,Math.min(r,m));let y=i,x=g;const S=l>1||u,E=S?Array(m):[];let _;for(;(_=e.indexOf(t,x))>-1;){let A=wh(t,{currentLocation:_,expectedLocation:g,distance:o,ignoreLocation:f});if(y=Math.min(A,y),x=_+p,S){let D=0;for(;D=V;U-=1){let ne=U-1,M=n[e.charAt(ne)];if(S&&(E[ne]=+!!M),G[U]=(G[U+1]<<1|1)&M,A&&(G[U]|=(b[U+1]|b[U])<<1|1|b[U+1]),G[U]&P&&(C=wh(t,{errors:A,currentLocation:ne,expectedLocation:g,distance:o,ignoreLocation:f}),C<=y)){if(y=C,x=ne,x<=g)break;V=Math.max(1,2*g-x)}}if(wh(t,{errors:A+1,currentLocation:g,expectedLocation:g,distance:o,ignoreLocation:f})>y)break;b=G}const O={isMatch:x>=0,score:Math.max(.001,C)};if(S){const A=AK(E,l);A.length?u&&(O.indices=A):O.isMatch=!1}return O}function OK(e){let t={};for(let n=0,r=e.length;n{this.chunks.push({pattern:g,alphabet:OK(g),startIndex:y})},m=this.pattern.length;if(m>la){let g=0;const y=m%la,x=m-y;for(;g{const{isMatch:_,score:b,indices:C}=MK(t,x,S,{location:o+E,distance:i,threshold:s,findAllMatches:l,minMatchCharLength:u,includeMatches:r,ignoreLocation:f});_&&(g=!0),m+=b,_&&C&&(p=[...p,...C])});let y={isMatch:g,score:g?m/this.chunks.length:1};return g&&r&&(y.indices=p),y}}class js{constructor(t){this.pattern=t}static isMultiMatch(t){return h2(t,this.multiRegex)}static isSingleMatch(t){return h2(t,this.singleRegex)}search(){}}function h2(e,t){const n=e.match(t);return n?n[1]:null}class NK extends js{constructor(t){super(t)}static get type(){return"exact"}static get multiRegex(){return/^="(.*)"$/}static get singleRegex(){return/^=(.*)$/}search(t){const n=t===this.pattern;return{isMatch:n,score:n?0:1,indices:[0,this.pattern.length-1]}}}class DK extends js{constructor(t){super(t)}static get type(){return"inverse-exact"}static get multiRegex(){return/^!"(.*)"$/}static get singleRegex(){return/^!(.*)$/}search(t){const r=t.indexOf(this.pattern)===-1;return{isMatch:r,score:r?0:1,indices:[0,t.length-1]}}}class IK extends js{constructor(t){super(t)}static get type(){return"prefix-exact"}static get multiRegex(){return/^\^"(.*)"$/}static get singleRegex(){return/^\^(.*)$/}search(t){const n=t.startsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[0,this.pattern.length-1]}}}class LK extends js{constructor(t){super(t)}static get type(){return"inverse-prefix-exact"}static get multiRegex(){return/^!\^"(.*)"$/}static get singleRegex(){return/^!\^(.*)$/}search(t){const n=!t.startsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[0,t.length-1]}}}class FK extends js{constructor(t){super(t)}static get type(){return"suffix-exact"}static get multiRegex(){return/^"(.*)"\$$/}static get singleRegex(){return/^(.*)\$$/}search(t){const n=t.endsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[t.length-this.pattern.length,t.length-1]}}}class jK extends js{constructor(t){super(t)}static get type(){return"inverse-suffix-exact"}static get multiRegex(){return/^!"(.*)"\$$/}static get singleRegex(){return/^!(.*)\$$/}search(t){const n=!t.endsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[0,t.length-1]}}}class YT extends js{constructor(t,{location:n=He.location,threshold:r=He.threshold,distance:o=He.distance,includeMatches:i=He.includeMatches,findAllMatches:s=He.findAllMatches,minMatchCharLength:l=He.minMatchCharLength,isCaseSensitive:u=He.isCaseSensitive,ignoreLocation:f=He.ignoreLocation}={}){super(t),this._bitapSearch=new GT(t,{location:n,threshold:r,distance:o,includeMatches:i,findAllMatches:s,minMatchCharLength:l,isCaseSensitive:u,ignoreLocation:f})}static get type(){return"fuzzy"}static get multiRegex(){return/^"(.*)"$/}static get singleRegex(){return/^(.*)$/}search(t){return this._bitapSearch.searchIn(t)}}class XT extends js{constructor(t){super(t)}static get type(){return"include"}static get multiRegex(){return/^'"(.*)"$/}static get singleRegex(){return/^'(.*)$/}search(t){let n=0,r;const o=[],i=this.pattern.length;for(;(r=t.indexOf(this.pattern,n))>-1;)n=r+i,o.push([r,n-1]);const s=!!o.length;return{isMatch:s,score:s?0:1,indices:o}}}const v1=[NK,XT,IK,LK,jK,FK,DK,YT],p2=v1.length,zK=/ +(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/,BK="|";function UK(e,t={}){return e.split(BK).map(n=>{let r=n.trim().split(zK).filter(i=>i&&!!i.trim()),o=[];for(let i=0,s=r.length;i!!(e[Up.AND]||e[Up.OR]),KK=e=>!!e[x1.PATH],GK=e=>!ki(e)&&VT(e)&&!b1(e),m2=e=>({[Up.AND]:Object.keys(e).map(t=>({[t]:e[t]}))});function ZT(e,t,{auto:n=!0}={}){const r=o=>{let i=Object.keys(o);const s=KK(o);if(!s&&i.length>1&&!b1(o))return r(m2(o));if(GK(o)){const u=s?o[x1.PATH]:i[0],f=s?o[x1.PATTERN]:o[u];if(!Bo(f))throw new Error(yK(u));const p={keyId:g1(u),pattern:f};return n&&(p.searcher=w1(f,t)),p}let l={children:[],operator:i[0]};return i.forEach(u=>{const f=o[u];ki(f)&&f.forEach(p=>{l.children.push(r(p))})}),l};return b1(e)||(e=m2(e)),r(e)}function YK(e,{ignoreFieldNorm:t=He.ignoreFieldNorm}){e.forEach(n=>{let r=1;n.matches.forEach(({key:o,norm:i,score:s})=>{const l=o?o.weight:null;r*=Math.pow(s===0&&l?Number.EPSILON:s,(l||1)*(t?1:i))}),n.score=r})}function XK(e,t){const n=e.matches;t.matches=[],pr(n)&&n.forEach(r=>{if(!pr(r.indices)||!r.indices.length)return;const{indices:o,value:i}=r;let s={indices:o,value:i};r.key&&(s.key=r.key.src),r.idx>-1&&(s.refIndex=r.idx),t.matches.push(s)})}function ZK(e,t){t.score=e.score}function qK(e,t,{includeMatches:n=He.includeMatches,includeScore:r=He.includeScore}={}){const o=[];return n&&o.push(XK),r&&o.push(ZK),e.map(i=>{const{idx:s}=i,l={item:t[s],refIndex:s};return o.length&&o.forEach(u=>{u(i,l)}),l})}class kc{constructor(t,n={},r){this.options={...He,...n},this.options.useExtendedSearch,this._keyStore=new SK(this.options.keys),this.setCollection(t,r)}setCollection(t,n){if(this._docs=t,n&&!(n instanceof Fx))throw new Error(vK);this._myIndex=n||KT(this.options.keys,this._docs,{getFn:this.options.getFn,fieldNormWeight:this.options.fieldNormWeight})}add(t){pr(t)&&(this._docs.push(t),this._myIndex.add(t))}remove(t=()=>!1){const n=[];for(let r=0,o=this._docs.length;r-1&&(u=u.slice(0,n)),qK(u,this._docs,{includeMatches:r,includeScore:o})}_searchStringList(t){const n=w1(t,this.options),{records:r}=this._myIndex,o=[];return r.forEach(({v:i,i:s,n:l})=>{if(!pr(i))return;const{isMatch:u,score:f,indices:p}=n.searchIn(i);u&&o.push({item:i,idx:s,matches:[{score:f,value:i,norm:l,indices:p}]})}),o}_searchLogical(t){const n=ZT(t,this.options),r=(l,u,f)=>{if(!l.children){const{keyId:m,searcher:g}=l,y=this._findMatches({key:this._keyStore.get(m),value:this._myIndex.getValueForItemAtKeyId(u,m),searcher:g});return y&&y.length?[{idx:f,item:u,matches:y}]:[]}const p=[];for(let m=0,g=l.children.length;m{if(pr(l)){let f=r(n,l,u);f.length&&(i[u]||(i[u]={idx:u,item:l,matches:[]},s.push(i[u])),f.forEach(({matches:p})=>{i[u].matches.push(...p)}))}}),s}_searchObjectList(t){const n=w1(t,this.options),{keys:r,records:o}=this._myIndex,i=[];return o.forEach(({$:s,i:l})=>{if(!pr(s))return;let u=[];r.forEach((f,p)=>{u.push(...this._findMatches({key:f,value:s[p],searcher:n}))}),u.length&&i.push({idx:l,item:s,matches:u})}),i}_findMatches({key:t,value:n,searcher:r}){if(!pr(n))return[];let o=[];if(ki(n))n.forEach(({v:i,i:s,n:l})=>{if(!pr(i))return;const{isMatch:u,score:f,indices:p}=r.searchIn(i);u&&o.push({score:f,key:t,value:i,idx:s,norm:l,indices:p})});else{const{v:i,n:s}=n,{isMatch:l,score:u,indices:f}=r.searchIn(i);l&&o.push({score:u,key:t,value:i,norm:s,indices:f})}return o}}kc.version="7.0.0";kc.createIndex=KT;kc.parseIndex=PK;kc.config=He;kc.parseQuery=ZT;HK(WK);function Kd(e){const t=e+"CollectionProvider",[n,r]=Mn(t),[o,i]=n(t,{collectionRef:{current:null},itemMap:new Map}),s=y=>{const{scope:x,children:S}=y,E=je.useRef(null),_=je.useRef(new Map).current;return je.createElement(o,{scope:x,itemMap:_,collectionRef:E},S)},l=e+"CollectionSlot",u=je.forwardRef((y,x)=>{const{scope:S,children:E}=y,_=i(l,S),b=Ue(x,_.collectionRef);return je.createElement(Zo,{ref:b},E)}),f=e+"CollectionItemSlot",p="data-radix-collection-item",m=je.forwardRef((y,x)=>{const{scope:S,children:E,..._}=y,b=je.useRef(null),C=Ue(x,b),R=i(f,S);return je.useEffect(()=>(R.itemMap.set(b,{ref:b,..._}),()=>void R.itemMap.delete(b))),je.createElement(Zo,{[p]:"",ref:C},E)});function g(y){const x=i(e+"CollectionConsumer",y);return je.useCallback(()=>{const E=x.collectionRef.current;if(!E)return[];const _=Array.from(E.querySelectorAll(`[${p}]`));return Array.from(x.itemMap.values()).sort((R,P)=>_.indexOf(R.ref.current)-_.indexOf(P.ref.current))},[x.collectionRef,x.itemMap])}return[{Provider:s,Slot:u,ItemSlot:m},g,r]}const QK=d.createContext(void 0);function Tc(e){const t=d.useContext(QK);return e||t||"ltr"}const O0="rovingFocusGroup.onEntryFocus",JK={bubbles:!1,cancelable:!0},jx="RovingFocusGroup",[S1,qT,eG]=Kd(jx),[tG,ng]=Mn(jx,[eG]),[nG,rG]=tG(jx),oG=d.forwardRef((e,t)=>d.createElement(S1.Provider,{scope:e.__scopeRovingFocusGroup},d.createElement(S1.Slot,{scope:e.__scopeRovingFocusGroup},d.createElement(iG,Y({},e,{ref:t}))))),iG=d.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:o=!1,dir:i,currentTabStopId:s,defaultCurrentTabStopId:l,onCurrentTabStopIdChange:u,onEntryFocus:f,...p}=e,m=d.useRef(null),g=Ue(t,m),y=Tc(i),[x=null,S]=Zr({prop:s,defaultProp:l,onChange:u}),[E,_]=d.useState(!1),b=Ft(f),C=qT(n),R=d.useRef(!1),[P,O]=d.useState(0);return d.useEffect(()=>{const A=m.current;if(A)return A.addEventListener(O0,b),()=>A.removeEventListener(O0,b)},[b]),d.createElement(nG,{scope:n,orientation:r,dir:y,loop:o,currentTabStopId:x,onItemFocus:d.useCallback(A=>S(A),[S]),onItemShiftTab:d.useCallback(()=>_(!0),[]),onFocusableItemAdd:d.useCallback(()=>O(A=>A+1),[]),onFocusableItemRemove:d.useCallback(()=>O(A=>A-1),[])},d.createElement(Ae.div,Y({tabIndex:E||P===0?-1:0,"data-orientation":r},p,{ref:g,style:{outline:"none",...e.style},onMouseDown:ue(e.onMouseDown,()=>{R.current=!0}),onFocus:ue(e.onFocus,A=>{const D=!R.current;if(A.target===A.currentTarget&&D&&!E){const B=new CustomEvent(O0,JK);if(A.currentTarget.dispatchEvent(B),!B.defaultPrevented){const V=C().filter(ne=>ne.focusable),J=V.find(ne=>ne.active),G=V.find(ne=>ne.id===x),U=[J,G,...V].filter(Boolean).map(ne=>ne.ref.current);QT(U)}}R.current=!1}),onBlur:ue(e.onBlur,()=>_(!1))})))}),sG="RovingFocusGroupItem",aG=d.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:o=!1,tabStopId:i,...s}=e,l=nr(),u=i||l,f=rG(sG,n),p=f.currentTabStopId===u,m=qT(n),{onFocusableItemAdd:g,onFocusableItemRemove:y}=f;return d.useEffect(()=>{if(r)return g(),()=>y()},[r,g,y]),d.createElement(S1.ItemSlot,{scope:n,id:u,focusable:r,active:o},d.createElement(Ae.span,Y({tabIndex:p?0:-1,"data-orientation":f.orientation},s,{ref:t,onMouseDown:ue(e.onMouseDown,x=>{r?f.onItemFocus(u):x.preventDefault()}),onFocus:ue(e.onFocus,()=>f.onItemFocus(u)),onKeyDown:ue(e.onKeyDown,x=>{if(x.key==="Tab"&&x.shiftKey){f.onItemShiftTab();return}if(x.target!==x.currentTarget)return;const S=uG(x,f.orientation,f.dir);if(S!==void 0){x.preventDefault();let _=m().filter(b=>b.focusable).map(b=>b.ref.current);if(S==="last")_.reverse();else if(S==="prev"||S==="next"){S==="prev"&&_.reverse();const b=_.indexOf(x.currentTarget);_=f.loop?dG(_,b+1):_.slice(b+1)}setTimeout(()=>QT(_))}})})))}),lG={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function cG(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function uG(e,t,n){const r=cG(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return lG[r]}function QT(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function dG(e,t){return e.map((n,r)=>e[(t+r)%e.length])}const JT=oG,e3=aG,t3="Tabs",[fG,xte]=Mn(t3,[ng]),n3=ng(),[hG,zx]=fG(t3),pG=d.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,onValueChange:o,defaultValue:i,orientation:s="horizontal",dir:l,activationMode:u="automatic",...f}=e,p=Tc(l),[m,g]=Zr({prop:r,onChange:o,defaultProp:i});return d.createElement(hG,{scope:n,baseId:nr(),value:m,onValueChange:g,orientation:s,dir:p,activationMode:u},d.createElement(Ae.div,Y({dir:p,"data-orientation":s},f,{ref:t})))}),mG="TabsList",gG=d.forwardRef((e,t)=>{const{__scopeTabs:n,loop:r=!0,...o}=e,i=zx(mG,n),s=n3(n);return d.createElement(JT,Y({asChild:!0},s,{orientation:i.orientation,dir:i.dir,loop:r}),d.createElement(Ae.div,Y({role:"tablist","aria-orientation":i.orientation},o,{ref:t})))}),vG="TabsTrigger",yG=d.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,disabled:o=!1,...i}=e,s=zx(vG,n),l=n3(n),u=r3(s.baseId,r),f=o3(s.baseId,r),p=r===s.value;return d.createElement(e3,Y({asChild:!0},l,{focusable:!o,active:p}),d.createElement(Ae.button,Y({type:"button",role:"tab","aria-selected":p,"aria-controls":f,"data-state":p?"active":"inactive","data-disabled":o?"":void 0,disabled:o,id:u},i,{ref:t,onMouseDown:ue(e.onMouseDown,m=>{!o&&m.button===0&&m.ctrlKey===!1?s.onValueChange(r):m.preventDefault()}),onKeyDown:ue(e.onKeyDown,m=>{[" ","Enter"].includes(m.key)&&s.onValueChange(r)}),onFocus:ue(e.onFocus,()=>{const m=s.activationMode!=="manual";!p&&!o&&m&&s.onValueChange(r)})})))}),wG="TabsContent",xG=d.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,forceMount:o,children:i,...s}=e,l=zx(wG,n),u=r3(l.baseId,r),f=o3(l.baseId,r),p=r===l.value,m=d.useRef(p);return d.useEffect(()=>{const g=requestAnimationFrame(()=>m.current=!1);return()=>cancelAnimationFrame(g)},[]),d.createElement(Sn,{present:o||p},({present:g})=>d.createElement(Ae.div,Y({"data-state":p?"active":"inactive","data-orientation":l.orientation,role:"tabpanel","aria-labelledby":u,hidden:!g,id:f,tabIndex:0},s,{ref:t,style:{...e.style,animationDuration:m.current?"0s":void 0}}),g&&i))});function r3(e,t){return`${e}-trigger-${t}`}function o3(e,t){return`${e}-content-${t}`}const bG=pG,i3=gG,s3=yG,a3=xG,l3=bG,Bx=d.forwardRef(({className:e,...t},n)=>v.jsx(i3,{ref:n,className:_e("inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground",e),tabIndex:-1,...t}));Bx.displayName=i3.displayName;const pa=d.forwardRef(({className:e,...t},n)=>v.jsx(s3,{ref:n,className:_e("inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow",e),tabIndex:-1,...t}));pa.displayName=s3.displayName;const Su=d.forwardRef(({className:e,...t},n)=>v.jsx(a3,{ref:n,className:_e("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",e),tabIndex:-1,...t}));Su.displayName=a3.displayName;function fd(e,[t,n]){return Math.min(n,Math.max(t,e))}function Ux(e){const t=d.useRef({value:e,previous:e});return d.useMemo(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}const SG=[" ","Enter","ArrowUp","ArrowDown"],_G=[" ","Enter"],rg="Select",[og,ig,EG]=Kd(rg),[Pc,bte]=Mn(rg,[EG,Fs]),Vx=Fs(),[CG,Fa]=Pc(rg),[$G,RG]=Pc(rg),kG=e=>{const{__scopeSelect:t,children:n,open:r,defaultOpen:o,onOpenChange:i,value:s,defaultValue:l,onValueChange:u,dir:f,name:p,autoComplete:m,disabled:g,required:y}=e,x=Vx(t),[S,E]=d.useState(null),[_,b]=d.useState(null),[C,R]=d.useState(!1),P=Tc(f),[O=!1,A]=Zr({prop:r,defaultProp:o,onChange:i}),[D,B]=Zr({prop:s,defaultProp:l,onChange:u}),V=d.useRef(null),J=S?!!S.closest("form"):!0,[G,se]=d.useState(new Set),U=Array.from(G).map(ne=>ne.props.value).join(";");return d.createElement(Fd,x,d.createElement(CG,{required:y,scope:t,trigger:S,onTriggerChange:E,valueNode:_,onValueNodeChange:b,valueNodeHasChildren:C,onValueNodeHasChildrenChange:R,contentId:nr(),value:D,onValueChange:B,open:O,onOpenChange:A,dir:P,triggerPointerDownPosRef:V,disabled:g},d.createElement(og.Provider,{scope:t},d.createElement($G,{scope:e.__scopeSelect,onNativeOptionAdd:d.useCallback(ne=>{se(M=>new Set(M).add(ne))},[]),onNativeOptionRemove:d.useCallback(ne=>{se(M=>{const ee=new Set(M);return ee.delete(ne),ee})},[])},n)),J?d.createElement(h3,{key:U,"aria-hidden":!0,required:y,tabIndex:-1,name:p,autoComplete:m,value:D,onChange:ne=>B(ne.target.value),disabled:g},D===void 0?d.createElement("option",{value:""}):null,Array.from(G)):null))},TG="SelectTrigger",PG=d.forwardRef((e,t)=>{const{__scopeSelect:n,disabled:r=!1,...o}=e,i=Vx(n),s=Fa(TG,n),l=s.disabled||r,u=Ue(t,s.onTriggerChange),f=ig(n),[p,m,g]=p3(x=>{const S=f().filter(b=>!b.disabled),E=S.find(b=>b.value===s.value),_=m3(S,x,E);_!==void 0&&s.onValueChange(_.value)}),y=()=>{l||(s.onOpenChange(!0),g())};return d.createElement(Wm,Y({asChild:!0},i),d.createElement(Ae.button,Y({type:"button",role:"combobox","aria-controls":s.contentId,"aria-expanded":s.open,"aria-required":s.required,"aria-autocomplete":"none",dir:s.dir,"data-state":s.open?"open":"closed",disabled:l,"data-disabled":l?"":void 0,"data-placeholder":f3(s.value)?"":void 0},o,{ref:u,onClick:ue(o.onClick,x=>{x.currentTarget.focus()}),onPointerDown:ue(o.onPointerDown,x=>{const S=x.target;S.hasPointerCapture(x.pointerId)&&S.releasePointerCapture(x.pointerId),x.button===0&&x.ctrlKey===!1&&(y(),s.triggerPointerDownPosRef.current={x:Math.round(x.pageX),y:Math.round(x.pageY)},x.preventDefault())}),onKeyDown:ue(o.onKeyDown,x=>{const S=p.current!=="";!(x.ctrlKey||x.altKey||x.metaKey)&&x.key.length===1&&m(x.key),!(S&&x.key===" ")&&SG.includes(x.key)&&(y(),x.preventDefault())})})))}),AG="SelectValue",MG=d.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,children:i,placeholder:s="",...l}=e,u=Fa(AG,n),{onValueNodeHasChildrenChange:f}=u,p=i!==void 0,m=Ue(t,u.onValueNodeChange);return An(()=>{f(p)},[f,p]),d.createElement(Ae.span,Y({},l,{ref:m,style:{pointerEvents:"none"}}),f3(u.value)?d.createElement(d.Fragment,null,s):i)}),OG=d.forwardRef((e,t)=>{const{__scopeSelect:n,children:r,...o}=e;return d.createElement(Ae.span,Y({"aria-hidden":!0},o,{ref:t}),r||"▼")}),NG=e=>d.createElement(jd,Y({asChild:!0},e)),dc="SelectContent",DG=d.forwardRef((e,t)=>{const n=Fa(dc,e.__scopeSelect),[r,o]=d.useState();if(An(()=>{o(new DocumentFragment)},[]),!n.open){const i=r;return i?Is.createPortal(d.createElement(c3,{scope:e.__scopeSelect},d.createElement(og.Slot,{scope:e.__scopeSelect},d.createElement("div",null,e.children))),i):null}return d.createElement(IG,Y({},e,{ref:t}))}),hi=10,[c3,ja]=Pc(dc),IG=d.forwardRef((e,t)=>{const{__scopeSelect:n,position:r="item-aligned",onCloseAutoFocus:o,onEscapeKeyDown:i,onPointerDownOutside:s,side:l,sideOffset:u,align:f,alignOffset:p,arrowPadding:m,collisionBoundary:g,collisionPadding:y,sticky:x,hideWhenDetached:S,avoidCollisions:E,..._}=e,b=Fa(dc,n),[C,R]=d.useState(null),[P,O]=d.useState(null),A=Ue(t,fe=>R(fe)),[D,B]=d.useState(null),[V,J]=d.useState(null),G=ig(n),[se,U]=d.useState(!1),ne=d.useRef(!1);d.useEffect(()=>{if(C)return Jm(C)},[C]),Zm();const M=d.useCallback(fe=>{const[xe,...Re]=G().map(ze=>ze.ref.current),[Me]=Re.slice(-1),Oe=document.activeElement;for(const ze of fe)if(ze===Oe||(ze==null||ze.scrollIntoView({block:"nearest"}),ze===xe&&P&&(P.scrollTop=0),ze===Me&&P&&(P.scrollTop=P.scrollHeight),ze==null||ze.focus(),document.activeElement!==Oe))return},[G,P]),ee=d.useCallback(()=>M([D,C]),[M,D,C]);d.useEffect(()=>{se&&ee()},[se,ee]);const{onOpenChange:H,triggerPointerDownPosRef:X}=b;d.useEffect(()=>{if(C){let fe={x:0,y:0};const xe=Me=>{var Oe,ze,Mt,ct;fe={x:Math.abs(Math.round(Me.pageX)-((Oe=(ze=X.current)===null||ze===void 0?void 0:ze.x)!==null&&Oe!==void 0?Oe:0)),y:Math.abs(Math.round(Me.pageY)-((Mt=(ct=X.current)===null||ct===void 0?void 0:ct.y)!==null&&Mt!==void 0?Mt:0))}},Re=Me=>{fe.x<=10&&fe.y<=10?Me.preventDefault():C.contains(Me.target)||H(!1),document.removeEventListener("pointermove",xe),X.current=null};return X.current!==null&&(document.addEventListener("pointermove",xe),document.addEventListener("pointerup",Re,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",xe),document.removeEventListener("pointerup",Re,{capture:!0})}}},[C,H,X]),d.useEffect(()=>{const fe=()=>H(!1);return window.addEventListener("blur",fe),window.addEventListener("resize",fe),()=>{window.removeEventListener("blur",fe),window.removeEventListener("resize",fe)}},[H]);const[W,le]=p3(fe=>{const xe=G().filter(Oe=>!Oe.disabled),Re=xe.find(Oe=>Oe.ref.current===document.activeElement),Me=m3(xe,fe,Re);Me&&setTimeout(()=>Me.ref.current.focus())}),pe=d.useCallback((fe,xe,Re)=>{const Me=!ne.current&&!Re;(b.value!==void 0&&b.value===xe||Me)&&(B(fe),Me&&(ne.current=!0))},[b.value]),$e=d.useCallback(()=>C==null?void 0:C.focus(),[C]),Ve=d.useCallback((fe,xe,Re)=>{const Me=!ne.current&&!Re;(b.value!==void 0&&b.value===xe||Me)&&J(fe)},[b.value]),We=r==="popper"?g2:LG,Ne=We===g2?{side:l,sideOffset:u,align:f,alignOffset:p,arrowPadding:m,collisionBoundary:g,collisionPadding:y,sticky:x,hideWhenDetached:S,avoidCollisions:E}:{};return d.createElement(c3,{scope:n,content:C,viewport:P,onViewportChange:O,itemRefCallback:pe,selectedItem:D,onItemLeave:$e,itemTextRefCallback:Ve,focusSelectedItem:ee,selectedItemText:V,position:r,isPositioned:se,searchRef:W},d.createElement(Qm,{as:Zo,allowPinchZoom:!0},d.createElement(Xm,{asChild:!0,trapped:b.open,onMountAutoFocus:fe=>{fe.preventDefault()},onUnmountAutoFocus:ue(o,fe=>{var xe;(xe=b.trigger)===null||xe===void 0||xe.focus({preventScroll:!0}),fe.preventDefault()})},d.createElement(Ec,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:i,onPointerDownOutside:s,onFocusOutside:fe=>fe.preventDefault(),onDismiss:()=>b.onOpenChange(!1)},d.createElement(We,Y({role:"listbox",id:b.contentId,"data-state":b.open?"open":"closed",dir:b.dir,onContextMenu:fe=>fe.preventDefault()},_,Ne,{onPlaced:()=>U(!0),ref:A,style:{display:"flex",flexDirection:"column",outline:"none",..._.style},onKeyDown:ue(_.onKeyDown,fe=>{const xe=fe.ctrlKey||fe.altKey||fe.metaKey;if(fe.key==="Tab"&&fe.preventDefault(),!xe&&fe.key.length===1&&le(fe.key),["ArrowUp","ArrowDown","Home","End"].includes(fe.key)){let Me=G().filter(Oe=>!Oe.disabled).map(Oe=>Oe.ref.current);if(["ArrowUp","End"].includes(fe.key)&&(Me=Me.slice().reverse()),["ArrowUp","ArrowDown"].includes(fe.key)){const Oe=fe.target,ze=Me.indexOf(Oe);Me=Me.slice(ze+1)}setTimeout(()=>M(Me)),fe.preventDefault()}})}))))))}),LG=d.forwardRef((e,t)=>{const{__scopeSelect:n,onPlaced:r,...o}=e,i=Fa(dc,n),s=ja(dc,n),[l,u]=d.useState(null),[f,p]=d.useState(null),m=Ue(t,A=>p(A)),g=ig(n),y=d.useRef(!1),x=d.useRef(!0),{viewport:S,selectedItem:E,selectedItemText:_,focusSelectedItem:b}=s,C=d.useCallback(()=>{if(i.trigger&&i.valueNode&&l&&f&&S&&E&&_){const A=i.trigger.getBoundingClientRect(),D=f.getBoundingClientRect(),B=i.valueNode.getBoundingClientRect(),V=_.getBoundingClientRect();if(i.dir!=="rtl"){const Oe=V.left-D.left,ze=B.left-Oe,Mt=A.left-ze,ct=A.width+Mt,Kt=Math.max(ct,D.width),Er=window.innerWidth-hi,gt=fd(ze,[hi,Er-Kt]);l.style.minWidth=ct+"px",l.style.left=gt+"px"}else{const Oe=D.right-V.right,ze=window.innerWidth-B.right-Oe,Mt=window.innerWidth-A.right-ze,ct=A.width+Mt,Kt=Math.max(ct,D.width),Er=window.innerWidth-hi,gt=fd(ze,[hi,Er-Kt]);l.style.minWidth=ct+"px",l.style.right=gt+"px"}const J=g(),G=window.innerHeight-hi*2,se=S.scrollHeight,U=window.getComputedStyle(f),ne=parseInt(U.borderTopWidth,10),M=parseInt(U.paddingTop,10),ee=parseInt(U.borderBottomWidth,10),H=parseInt(U.paddingBottom,10),X=ne+M+se+H+ee,W=Math.min(E.offsetHeight*5,X),le=window.getComputedStyle(S),pe=parseInt(le.paddingTop,10),$e=parseInt(le.paddingBottom,10),Ve=A.top+A.height/2-hi,We=G-Ve,Ne=E.offsetHeight/2,fe=E.offsetTop+Ne,xe=ne+M+fe,Re=X-xe;if(xe<=Ve){const Oe=E===J[J.length-1].ref.current;l.style.bottom="0px";const ze=f.clientHeight-S.offsetTop-S.offsetHeight,Mt=Math.max(We,Ne+(Oe?$e:0)+ze+ee),ct=xe+Mt;l.style.height=ct+"px"}else{const Oe=E===J[0].ref.current;l.style.top="0px";const Mt=Math.max(Ve,ne+S.offsetTop+(Oe?pe:0)+Ne)+Re;l.style.height=Mt+"px",S.scrollTop=xe-Ve+S.offsetTop}l.style.margin=`${hi}px 0`,l.style.minHeight=W+"px",l.style.maxHeight=G+"px",r==null||r(),requestAnimationFrame(()=>y.current=!0)}},[g,i.trigger,i.valueNode,l,f,S,E,_,i.dir,r]);An(()=>C(),[C]);const[R,P]=d.useState();An(()=>{f&&P(window.getComputedStyle(f).zIndex)},[f]);const O=d.useCallback(A=>{A&&x.current===!0&&(C(),b==null||b(),x.current=!1)},[C,b]);return d.createElement(FG,{scope:n,contentWrapper:l,shouldExpandOnScrollRef:y,onScrollButtonChange:O},d.createElement("div",{ref:u,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:R}},d.createElement(Ae.div,Y({},o,{ref:m,style:{boxSizing:"border-box",maxHeight:"100%",...o.style}}))))}),g2=d.forwardRef((e,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:o=hi,...i}=e,s=Vx(n);return d.createElement(Hm,Y({},s,i,{ref:t,align:r,collisionPadding:o,style:{boxSizing:"border-box",...i.style,"--radix-select-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-select-content-available-width":"var(--radix-popper-available-width)","--radix-select-content-available-height":"var(--radix-popper-available-height)","--radix-select-trigger-width":"var(--radix-popper-anchor-width)","--radix-select-trigger-height":"var(--radix-popper-anchor-height)"}}))}),[FG,Wx]=Pc(dc,{}),v2="SelectViewport",jG=d.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=ja(v2,n),i=Wx(v2,n),s=Ue(t,o.onViewportChange),l=d.useRef(0);return d.createElement(d.Fragment,null,d.createElement("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"}}),d.createElement(og.Slot,{scope:n},d.createElement(Ae.div,Y({"data-radix-select-viewport":"",role:"presentation"},r,{ref:s,style:{position:"relative",flex:1,overflow:"auto",...r.style},onScroll:ue(r.onScroll,u=>{const f=u.currentTarget,{contentWrapper:p,shouldExpandOnScrollRef:m}=i;if(m!=null&&m.current&&p){const g=Math.abs(l.current-f.scrollTop);if(g>0){const y=window.innerHeight-hi*2,x=parseFloat(p.style.minHeight),S=parseFloat(p.style.height),E=Math.max(x,S);if(E0?C:0,p.style.justifyContent="flex-end")}}}l.current=f.scrollTop})}))))}),zG="SelectGroup",[BG,UG]=Pc(zG),VG=d.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=nr();return d.createElement(BG,{scope:n,id:o},d.createElement(Ae.div,Y({role:"group","aria-labelledby":o},r,{ref:t})))}),WG="SelectLabel",HG=d.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=UG(WG,n);return d.createElement(Ae.div,Y({id:o.id},r,{ref:t}))}),_1="SelectItem",[KG,u3]=Pc(_1),GG=d.forwardRef((e,t)=>{const{__scopeSelect:n,value:r,disabled:o=!1,textValue:i,...s}=e,l=Fa(_1,n),u=ja(_1,n),f=l.value===r,[p,m]=d.useState(i??""),[g,y]=d.useState(!1),x=Ue(t,_=>{var b;return(b=u.itemRefCallback)===null||b===void 0?void 0:b.call(u,_,r,o)}),S=nr(),E=()=>{o||(l.onValueChange(r),l.onOpenChange(!1))};if(r==="")throw new Error("A must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.");return d.createElement(KG,{scope:n,value:r,disabled:o,textId:S,isSelected:f,onItemTextChange:d.useCallback(_=>{m(b=>{var C;return b||((C=_==null?void 0:_.textContent)!==null&&C!==void 0?C:"").trim()})},[])},d.createElement(og.ItemSlot,{scope:n,value:r,disabled:o,textValue:p},d.createElement(Ae.div,Y({role:"option","aria-labelledby":S,"data-highlighted":g?"":void 0,"aria-selected":f&&g,"data-state":f?"checked":"unchecked","aria-disabled":o||void 0,"data-disabled":o?"":void 0,tabIndex:o?void 0:-1},s,{ref:x,onFocus:ue(s.onFocus,()=>y(!0)),onBlur:ue(s.onBlur,()=>y(!1)),onPointerUp:ue(s.onPointerUp,E),onPointerMove:ue(s.onPointerMove,_=>{if(o){var b;(b=u.onItemLeave)===null||b===void 0||b.call(u)}else _.currentTarget.focus({preventScroll:!0})}),onPointerLeave:ue(s.onPointerLeave,_=>{if(_.currentTarget===document.activeElement){var b;(b=u.onItemLeave)===null||b===void 0||b.call(u)}}),onKeyDown:ue(s.onKeyDown,_=>{var b;((b=u.searchRef)===null||b===void 0?void 0:b.current)!==""&&_.key===" "||(_G.includes(_.key)&&E(),_.key===" "&&_.preventDefault())})}))))}),xh="SelectItemText",YG=d.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,...i}=e,s=Fa(xh,n),l=ja(xh,n),u=u3(xh,n),f=RG(xh,n),[p,m]=d.useState(null),g=Ue(t,_=>m(_),u.onItemTextChange,_=>{var b;return(b=l.itemTextRefCallback)===null||b===void 0?void 0:b.call(l,_,u.value,u.disabled)}),y=p==null?void 0:p.textContent,x=d.useMemo(()=>d.createElement("option",{key:u.value,value:u.value,disabled:u.disabled},y),[u.disabled,u.value,y]),{onNativeOptionAdd:S,onNativeOptionRemove:E}=f;return An(()=>(S(x),()=>E(x)),[S,E,x]),d.createElement(d.Fragment,null,d.createElement(Ae.span,Y({id:u.textId},i,{ref:g})),u.isSelected&&s.valueNode&&!s.valueNodeHasChildren?Is.createPortal(i.children,s.valueNode):null)}),XG="SelectItemIndicator",ZG=d.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return u3(XG,n).isSelected?d.createElement(Ae.span,Y({"aria-hidden":!0},r,{ref:t})):null}),y2="SelectScrollUpButton",qG=d.forwardRef((e,t)=>{const n=ja(y2,e.__scopeSelect),r=Wx(y2,e.__scopeSelect),[o,i]=d.useState(!1),s=Ue(t,r.onScrollButtonChange);return An(()=>{if(n.viewport&&n.isPositioned){let f=function(){const p=u.scrollTop>0;i(p)};var l=f;const u=n.viewport;return f(),u.addEventListener("scroll",f),()=>u.removeEventListener("scroll",f)}},[n.viewport,n.isPositioned]),o?d.createElement(d3,Y({},e,{ref:s,onAutoScroll:()=>{const{viewport:l,selectedItem:u}=n;l&&u&&(l.scrollTop=l.scrollTop-u.offsetHeight)}})):null}),w2="SelectScrollDownButton",QG=d.forwardRef((e,t)=>{const n=ja(w2,e.__scopeSelect),r=Wx(w2,e.__scopeSelect),[o,i]=d.useState(!1),s=Ue(t,r.onScrollButtonChange);return An(()=>{if(n.viewport&&n.isPositioned){let f=function(){const p=u.scrollHeight-u.clientHeight,m=Math.ceil(u.scrollTop)u.removeEventListener("scroll",f)}},[n.viewport,n.isPositioned]),o?d.createElement(d3,Y({},e,{ref:s,onAutoScroll:()=>{const{viewport:l,selectedItem:u}=n;l&&u&&(l.scrollTop=l.scrollTop+u.offsetHeight)}})):null}),d3=d.forwardRef((e,t)=>{const{__scopeSelect:n,onAutoScroll:r,...o}=e,i=ja("SelectScrollButton",n),s=d.useRef(null),l=ig(n),u=d.useCallback(()=>{s.current!==null&&(window.clearInterval(s.current),s.current=null)},[]);return d.useEffect(()=>()=>u(),[u]),An(()=>{var f;const p=l().find(m=>m.ref.current===document.activeElement);p==null||(f=p.ref.current)===null||f===void 0||f.scrollIntoView({block:"nearest"})},[l]),d.createElement(Ae.div,Y({"aria-hidden":!0},o,{ref:t,style:{flexShrink:0,...o.style},onPointerDown:ue(o.onPointerDown,()=>{s.current===null&&(s.current=window.setInterval(r,50))}),onPointerMove:ue(o.onPointerMove,()=>{var f;(f=i.onItemLeave)===null||f===void 0||f.call(i),s.current===null&&(s.current=window.setInterval(r,50))}),onPointerLeave:ue(o.onPointerLeave,()=>{u()})}))}),JG=d.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return d.createElement(Ae.div,Y({"aria-hidden":!0},r,{ref:t}))});function f3(e){return e===""||e===void 0}const h3=d.forwardRef((e,t)=>{const{value:n,...r}=e,o=d.useRef(null),i=Ue(t,o),s=Ux(n);return d.useEffect(()=>{const l=o.current,u=window.HTMLSelectElement.prototype,p=Object.getOwnPropertyDescriptor(u,"value").set;if(s!==n&&p){const m=new Event("change",{bubbles:!0});p.call(l,n),l.dispatchEvent(m)}},[s,n]),d.createElement(Km,{asChild:!0},d.createElement("select",Y({},r,{ref:i,defaultValue:n})))});h3.displayName="BubbleSelect";function p3(e){const t=Ft(e),n=d.useRef(""),r=d.useRef(0),o=d.useCallback(s=>{const l=n.current+s;t(l),function u(f){n.current=f,window.clearTimeout(r.current),f!==""&&(r.current=window.setTimeout(()=>u(""),1e3))}(l)},[t]),i=d.useCallback(()=>{n.current="",window.clearTimeout(r.current)},[]);return d.useEffect(()=>()=>window.clearTimeout(r.current),[]),[n,o,i]}function m3(e,t,n){const o=t.length>1&&Array.from(t).every(f=>f===t[0])?t[0]:t,i=n?e.indexOf(n):-1;let s=eY(e,Math.max(i,0));o.length===1&&(s=s.filter(f=>f!==n));const u=s.find(f=>f.textValue.toLowerCase().startsWith(o.toLowerCase()));return u!==n?u:void 0}function eY(e,t){return e.map((n,r)=>e[(t+r)%e.length])}const tY=kG,g3=PG,nY=MG,rY=OG,oY=NG,v3=DG,iY=jG,sY=VG,y3=HG,w3=GG,aY=YG,lY=ZG,x3=qG,b3=QG,S3=JG,Uo=tY,vi=sY,Vo=nY,go=d.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(g3,{ref:r,className:_e("flex h-9 w-full items-center justify-between whitespace-nowrap rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",e),tabIndex:-1,...n,children:[t,v.jsx(rY,{asChild:!0,children:v.jsx(Zj,{className:"h-4 w-4 opacity-50"})})]}));go.displayName=g3.displayName;const _3=d.forwardRef(({className:e,...t},n)=>v.jsx(x3,{ref:n,className:_e("flex cursor-default items-center justify-center py-1",e),...t,children:v.jsx(rz,{})}));_3.displayName=x3.displayName;const E3=d.forwardRef(({className:e,...t},n)=>v.jsx(b3,{ref:n,className:_e("flex cursor-default items-center justify-center py-1",e),...t,children:v.jsx(Jj,{})}));E3.displayName=b3.displayName;const vo=d.forwardRef(({className:e,children:t,position:n="popper",...r},o)=>v.jsx(oY,{children:v.jsxs(v3,{ref:o,className:_e("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",n==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:n,onCloseAutoFocus:i=>i.preventDefault(),...r,children:[v.jsx(_3,{}),v.jsx(iY,{className:_e("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),v.jsx(E3,{})]})}));vo.displayName=v3.displayName;const cY=d.forwardRef(({className:e,...t},n)=>v.jsx(y3,{ref:n,className:_e("px-2 py-1.5 text-sm font-semibold",e),...t}));cY.displayName=y3.displayName;const yo=d.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(w3,{ref:r,className:_e("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-2 pr-8 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[v.jsx("span",{className:"absolute right-2 flex h-3.5 w-3.5 items-center justify-center",children:v.jsx(lY,{children:v.jsx(xk,{className:"h-4 w-4"})})}),v.jsx(aY,{children:t})]}));yo.displayName=w3.displayName;const uY=d.forwardRef(({className:e,...t},n)=>v.jsx(S3,{ref:n,className:_e("-mx-1 my-1 h-px bg-muted",e),...t}));uY.displayName=S3.displayName;function dY(e,t){return d.useReducer((n,r)=>{const o=t[n][r];return o??n},e)}const C3="ScrollArea",[$3,Ste]=Mn(C3),[fY,qr]=$3(C3),hY=d.forwardRef((e,t)=>{const{__scopeScrollArea:n,type:r="hover",dir:o,scrollHideDelay:i=600,...s}=e,[l,u]=d.useState(null),[f,p]=d.useState(null),[m,g]=d.useState(null),[y,x]=d.useState(null),[S,E]=d.useState(null),[_,b]=d.useState(0),[C,R]=d.useState(0),[P,O]=d.useState(!1),[A,D]=d.useState(!1),B=Ue(t,J=>u(J)),V=Tc(o);return d.createElement(fY,{scope:n,type:r,dir:V,scrollHideDelay:i,scrollArea:l,viewport:f,onViewportChange:p,content:m,onContentChange:g,scrollbarX:y,onScrollbarXChange:x,scrollbarXEnabled:P,onScrollbarXEnabledChange:O,scrollbarY:S,onScrollbarYChange:E,scrollbarYEnabled:A,onScrollbarYEnabledChange:D,onCornerWidthChange:b,onCornerHeightChange:R},d.createElement(Ae.div,Y({dir:V},s,{ref:B,style:{position:"relative","--radix-scroll-area-corner-width":_+"px","--radix-scroll-area-corner-height":C+"px",...e.style}})))}),pY="ScrollAreaViewport",mY=d.forwardRef((e,t)=>{const{__scopeScrollArea:n,children:r,...o}=e,i=qr(pY,n),s=d.useRef(null),l=Ue(t,s,i.onViewportChange);return d.createElement(d.Fragment,null,d.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}"}}),d.createElement(Ae.div,Y({"data-radix-scroll-area-viewport":""},o,{ref:l,style:{overflowX:i.scrollbarXEnabled?"scroll":"hidden",overflowY:i.scrollbarYEnabled?"scroll":"hidden",...e.style}}),d.createElement("div",{ref:i.onContentChange,style:{minWidth:"100%",display:"table"}},r)))}),Oi="ScrollAreaScrollbar",R3=d.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=qr(Oi,e.__scopeScrollArea),{onScrollbarXEnabledChange:i,onScrollbarYEnabledChange:s}=o,l=e.orientation==="horizontal";return d.useEffect(()=>(l?i(!0):s(!0),()=>{l?i(!1):s(!1)}),[l,i,s]),o.type==="hover"?d.createElement(gY,Y({},r,{ref:t,forceMount:n})):o.type==="scroll"?d.createElement(vY,Y({},r,{ref:t,forceMount:n})):o.type==="auto"?d.createElement(k3,Y({},r,{ref:t,forceMount:n})):o.type==="always"?d.createElement(Hx,Y({},r,{ref:t})):null}),gY=d.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=qr(Oi,e.__scopeScrollArea),[i,s]=d.useState(!1);return d.useEffect(()=>{const l=o.scrollArea;let u=0;if(l){const f=()=>{window.clearTimeout(u),s(!0)},p=()=>{u=window.setTimeout(()=>s(!1),o.scrollHideDelay)};return l.addEventListener("pointerenter",f),l.addEventListener("pointerleave",p),()=>{window.clearTimeout(u),l.removeEventListener("pointerenter",f),l.removeEventListener("pointerleave",p)}}},[o.scrollArea,o.scrollHideDelay]),d.createElement(Sn,{present:n||i},d.createElement(k3,Y({"data-state":i?"visible":"hidden"},r,{ref:t})))}),vY=d.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=qr(Oi,e.__scopeScrollArea),i=e.orientation==="horizontal",s=ag(()=>u("SCROLL_END"),100),[l,u]=dY("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 d.useEffect(()=>{if(l==="idle"){const f=window.setTimeout(()=>u("HIDE"),o.scrollHideDelay);return()=>window.clearTimeout(f)}},[l,o.scrollHideDelay,u]),d.useEffect(()=>{const f=o.viewport,p=i?"scrollLeft":"scrollTop";if(f){let m=f[p];const g=()=>{const y=f[p];m!==y&&(u("SCROLL"),s()),m=y};return f.addEventListener("scroll",g),()=>f.removeEventListener("scroll",g)}},[o.viewport,i,u,s]),d.createElement(Sn,{present:n||l!=="hidden"},d.createElement(Hx,Y({"data-state":l==="hidden"?"hidden":"visible"},r,{ref:t,onPointerEnter:ue(e.onPointerEnter,()=>u("POINTER_ENTER")),onPointerLeave:ue(e.onPointerLeave,()=>u("POINTER_LEAVE"))})))}),k3=d.forwardRef((e,t)=>{const n=qr(Oi,e.__scopeScrollArea),{forceMount:r,...o}=e,[i,s]=d.useState(!1),l=e.orientation==="horizontal",u=ag(()=>{if(n.viewport){const f=n.viewport.offsetWidth{const{orientation:n="vertical",...r}=e,o=qr(Oi,e.__scopeScrollArea),i=d.useRef(null),s=d.useRef(0),[l,u]=d.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),f=M3(l.viewport,l.content),p={...r,sizes:l,onSizesChange:u,hasThumb:f>0&&f<1,onThumbChange:g=>i.current=g,onThumbPointerUp:()=>s.current=0,onThumbPointerDown:g=>s.current=g};function m(g,y){return CY(g,s.current,l,y)}return n==="horizontal"?d.createElement(yY,Y({},p,{ref:t,onThumbPositionChange:()=>{if(o.viewport&&i.current){const g=o.viewport.scrollLeft,y=x2(g,l,o.dir);i.current.style.transform=`translate3d(${y}px, 0, 0)`}},onWheelScroll:g=>{o.viewport&&(o.viewport.scrollLeft=g)},onDragScroll:g=>{o.viewport&&(o.viewport.scrollLeft=m(g,o.dir))}})):n==="vertical"?d.createElement(wY,Y({},p,{ref:t,onThumbPositionChange:()=>{if(o.viewport&&i.current){const g=o.viewport.scrollTop,y=x2(g,l);i.current.style.transform=`translate3d(0, ${y}px, 0)`}},onWheelScroll:g=>{o.viewport&&(o.viewport.scrollTop=g)},onDragScroll:g=>{o.viewport&&(o.viewport.scrollTop=m(g))}})):null}),yY=d.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,i=qr(Oi,e.__scopeScrollArea),[s,l]=d.useState(),u=d.useRef(null),f=Ue(t,u,i.onScrollbarXChange);return d.useEffect(()=>{u.current&&l(getComputedStyle(u.current))},[u]),d.createElement(P3,Y({"data-orientation":"horizontal"},o,{ref:f,sizes:n,style:{bottom:0,left:i.dir==="rtl"?"var(--radix-scroll-area-corner-width)":0,right:i.dir==="ltr"?"var(--radix-scroll-area-corner-width)":0,"--radix-scroll-area-thumb-width":sg(n)+"px",...e.style},onThumbPointerDown:p=>e.onThumbPointerDown(p.x),onDragScroll:p=>e.onDragScroll(p.x),onWheelScroll:(p,m)=>{if(i.viewport){const g=i.viewport.scrollLeft+p.deltaX;e.onWheelScroll(g),N3(g,m)&&p.preventDefault()}},onResize:()=>{u.current&&i.viewport&&s&&r({content:i.viewport.scrollWidth,viewport:i.viewport.offsetWidth,scrollbar:{size:u.current.clientWidth,paddingStart:Vp(s.paddingLeft),paddingEnd:Vp(s.paddingRight)}})}}))}),wY=d.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,i=qr(Oi,e.__scopeScrollArea),[s,l]=d.useState(),u=d.useRef(null),f=Ue(t,u,i.onScrollbarYChange);return d.useEffect(()=>{u.current&&l(getComputedStyle(u.current))},[u]),d.createElement(P3,Y({"data-orientation":"vertical"},o,{ref:f,sizes:n,style:{top:0,right:i.dir==="ltr"?0:void 0,left:i.dir==="rtl"?0:void 0,bottom:"var(--radix-scroll-area-corner-height)","--radix-scroll-area-thumb-height":sg(n)+"px",...e.style},onThumbPointerDown:p=>e.onThumbPointerDown(p.y),onDragScroll:p=>e.onDragScroll(p.y),onWheelScroll:(p,m)=>{if(i.viewport){const g=i.viewport.scrollTop+p.deltaY;e.onWheelScroll(g),N3(g,m)&&p.preventDefault()}},onResize:()=>{u.current&&i.viewport&&s&&r({content:i.viewport.scrollHeight,viewport:i.viewport.offsetHeight,scrollbar:{size:u.current.clientHeight,paddingStart:Vp(s.paddingTop),paddingEnd:Vp(s.paddingBottom)}})}}))}),[xY,T3]=$3(Oi),P3=d.forwardRef((e,t)=>{const{__scopeScrollArea:n,sizes:r,hasThumb:o,onThumbChange:i,onThumbPointerUp:s,onThumbPointerDown:l,onThumbPositionChange:u,onDragScroll:f,onWheelScroll:p,onResize:m,...g}=e,y=qr(Oi,n),[x,S]=d.useState(null),E=Ue(t,B=>S(B)),_=d.useRef(null),b=d.useRef(""),C=y.viewport,R=r.content-r.viewport,P=Ft(p),O=Ft(u),A=ag(m,10);function D(B){if(_.current){const V=B.clientX-_.current.left,J=B.clientY-_.current.top;f({x:V,y:J})}}return d.useEffect(()=>{const B=V=>{const J=V.target;(x==null?void 0:x.contains(J))&&P(V,R)};return document.addEventListener("wheel",B,{passive:!1}),()=>document.removeEventListener("wheel",B,{passive:!1})},[C,x,R,P]),d.useEffect(O,[r,O]),fc(x,A),fc(y.content,A),d.createElement(xY,{scope:n,scrollbar:x,hasThumb:o,onThumbChange:Ft(i),onThumbPointerUp:Ft(s),onThumbPositionChange:O,onThumbPointerDown:Ft(l)},d.createElement(Ae.div,Y({},g,{ref:E,style:{position:"absolute",...g.style},onPointerDown:ue(e.onPointerDown,B=>{B.button===0&&(B.target.setPointerCapture(B.pointerId),_.current=x.getBoundingClientRect(),b.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",y.viewport&&(y.viewport.style.scrollBehavior="auto"),D(B))}),onPointerMove:ue(e.onPointerMove,D),onPointerUp:ue(e.onPointerUp,B=>{const V=B.target;V.hasPointerCapture(B.pointerId)&&V.releasePointerCapture(B.pointerId),document.body.style.webkitUserSelect=b.current,y.viewport&&(y.viewport.style.scrollBehavior=""),_.current=null})})))}),E1="ScrollAreaThumb",bY=d.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=T3(E1,e.__scopeScrollArea);return d.createElement(Sn,{present:n||o.hasThumb},d.createElement(SY,Y({ref:t},r)))}),SY=d.forwardRef((e,t)=>{const{__scopeScrollArea:n,style:r,...o}=e,i=qr(E1,n),s=T3(E1,n),{onThumbPositionChange:l}=s,u=Ue(t,m=>s.onThumbChange(m)),f=d.useRef(),p=ag(()=>{f.current&&(f.current(),f.current=void 0)},100);return d.useEffect(()=>{const m=i.viewport;if(m){const g=()=>{if(p(),!f.current){const y=$Y(m,l);f.current=y,l()}};return l(),m.addEventListener("scroll",g),()=>m.removeEventListener("scroll",g)}},[i.viewport,p,l]),d.createElement(Ae.div,Y({"data-state":s.hasThumb?"visible":"hidden"},o,{ref:u,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...r},onPointerDownCapture:ue(e.onPointerDownCapture,m=>{const y=m.target.getBoundingClientRect(),x=m.clientX-y.left,S=m.clientY-y.top;s.onThumbPointerDown({x,y:S})}),onPointerUp:ue(e.onPointerUp,s.onThumbPointerUp)}))}),A3="ScrollAreaCorner",_Y=d.forwardRef((e,t)=>{const n=qr(A3,e.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?d.createElement(EY,Y({},e,{ref:t})):null}),EY=d.forwardRef((e,t)=>{const{__scopeScrollArea:n,...r}=e,o=qr(A3,n),[i,s]=d.useState(0),[l,u]=d.useState(0),f=!!(i&&l);return fc(o.scrollbarX,()=>{var p;const m=((p=o.scrollbarX)===null||p===void 0?void 0:p.offsetHeight)||0;o.onCornerHeightChange(m),u(m)}),fc(o.scrollbarY,()=>{var p;const m=((p=o.scrollbarY)===null||p===void 0?void 0:p.offsetWidth)||0;o.onCornerWidthChange(m),s(m)}),f?d.createElement(Ae.div,Y({},r,{ref:t,style:{width:i,height:l,position:"absolute",right:o.dir==="ltr"?0:void 0,left:o.dir==="rtl"?0:void 0,bottom:0,...e.style}})):null});function Vp(e){return e?parseInt(e,10):0}function M3(e,t){const n=e/t;return isNaN(n)?0:n}function sg(e){const t=M3(e.viewport,e.content),n=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,r=(e.scrollbar.size-n)*t;return Math.max(r,18)}function CY(e,t,n,r="ltr"){const o=sg(n),i=o/2,s=t||i,l=o-s,u=n.scrollbar.paddingStart+s,f=n.scrollbar.size-n.scrollbar.paddingEnd-l,p=n.content-n.viewport,m=r==="ltr"?[0,p]:[p*-1,0];return O3([u,f],m)(e)}function x2(e,t,n="ltr"){const r=sg(t),o=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,i=t.scrollbar.size-o,s=t.content-t.viewport,l=i-r,u=n==="ltr"?[0,s]:[s*-1,0],f=fd(e,u);return O3([0,s],[0,l])(f)}function O3(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 N3(e,t){return e>0&&e{})=>{let n={left:e.scrollLeft,top:e.scrollTop},r=0;return function o(){const i={left:e.scrollLeft,top:e.scrollTop},s=n.left!==i.left,l=n.top!==i.top;(s||l)&&t(),n=i,r=window.requestAnimationFrame(o)}(),()=>window.cancelAnimationFrame(r)};function ag(e,t){const n=Ft(e),r=d.useRef(0);return d.useEffect(()=>()=>window.clearTimeout(r.current),[]),d.useCallback(()=>{window.clearTimeout(r.current),r.current=window.setTimeout(n,t)},[n,t])}function fc(e,t){const n=Ft(t);An(()=>{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 D3=hY,RY=mY,kY=_Y,lg=d.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(D3,{ref:r,className:_e("relative overflow-hidden",e),scrollHideDelay:400,...n,children:[v.jsx(RY,{className:"h-full w-full rounded-[inherit]",children:t}),v.jsx(I3,{}),v.jsx(kY,{})]}));lg.displayName=D3.displayName;const I3=d.forwardRef(({className:e,orientation:t="vertical",...n},r)=>v.jsx(R3,{ref:r,orientation:t,className:_e("flex touch-none select-none transition-colors",t==="vertical"&&"h-full w-2.5 border-l border-l-transparent p-[1px]",t==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",e),...n,children:v.jsx(bY,{className:"relative flex-1 rounded-full bg-border"})}));I3.displayName=R3.displayName;const L3="Name",F3="Created time",j3="Modified time",b2="input",TY="output",S2={[Es.NAME]:L3,[Es.CTIME]:F3,[Es.MTIME]:j3};function PY(e){const{onPhotoClick:t,photoWidth:n}=e,[r,o]=Nx(!1),[i,s]=bt(V=>[V.fileManagerState,V.updateFileManagerState]),{toast:l}=Id(),[u,f]=d.useState(0),[p,m]=d.useState(0),g=d.useRef(null),y=lV(i.searchText,300),[x,S]=d.useState(b2),[E,_]=d.useState([]),[b,C]=d.useState([]),[R,P]=d.useState(0);Zn("f",()=>{o()}),Zn("left",()=>{let V=R;R>0&&(V=R-1),P(V),t(x,b[V].name)},[R,b]),Zn("right",()=>{let V=R;R{r||m(u)},[r,u]);const O=d.useCallback(V=>{V!==null&&r&&setTimeout(()=>{V.scrollTo({top:p,left:0})},100)},[r,p]);d.useEffect(()=>{(async()=>{try{const J=await Wj(x);_(J)}catch(J){l({variant:"destructive",title:"Uh oh! Something went wrong.",description:J.message?J.message:J.toString()})}})()},[x]),d.useEffect(()=>{if(!r)return;(async()=>{try{let J=E;y&&(J=new kc(J,{keys:["name"]}).search(y).map(ne=>J[ne.refIndex])),J=xH.orderBy(J,i.sortBy,i.sortOrder);const G=J.map(se=>{const U=n,ne=se.height*(U/se.width);return{src:`${Ls}/media_thumbnail_file?tab=${x}&filename=${encodeURIComponent(se.name)}&width=${Math.ceil(U)}&height=${Math.ceil(ne)}`,height:ne,width:U,name:se.name}});C(G)}catch(J){l({variant:"destructive",title:"Uh oh! Something went wrong.",description:J.message?J.message:J.toString()})}})()},[E,y,i,n,r]);const A=V=>{f(V.currentTarget.scrollTop)},D=({index:V})=>{o(),P(V),t(x,b[V].name)},B=()=>v.jsxs("div",{className:"flex justify-start items-center gap-[12px]",children:[v.jsx("div",{children:`Images (${b.length})`}),v.jsxs("div",{className:"flex",children:[v.jsx(yn,{tooltip:"Rows layout",onClick:()=>{s({layout:"rows"})},children:v.jsx(pz,{className:i.layout!=="rows"?"opacity-50":""})}),v.jsx(yn,{tooltip:"Grid layout",onClick:()=>{s({layout:"masonry"})},children:v.jsx(fz,{className:i.layout!=="masonry"?"opacity-50":""})})]})]});return v.jsxs(eg,{open:r,onOpenChange:o,children:[v.jsx(pT,{asChild:!0,children:v.jsx(yn,{tooltip:"File Manager",children:v.jsx(eV,{})})}),v.jsxs(Wd,{className:"h-4/5 max-w-6xl",children:[v.jsx(Hd,{children:B()}),v.jsxs("div",{className:"flex justify-between gap-8 items-center",children:[v.jsxs("div",{className:"flex relative justify-start items-center",children:[v.jsx(lz,{className:"absolute left-[8px]"}),v.jsx(Bm,{ref:g,value:i.searchText,className:"w-[250px] pl-[30px]",tabIndex:-1,onInput:V=>{V.preventDefault(),V.stopPropagation();const J=V.target;s({searchText:J.value})},placeholder:"Search by file name"})]}),v.jsx(l3,{defaultValue:x,onValueChange:V=>S(V),children:v.jsxs(Bx,{"aria-label":"Manage your account",children:[v.jsx(pa,{value:b2,children:"Image Directory"}),v.jsx(pa,{value:TY,children:"Output Directory"})]})}),v.jsx("div",{className:"flex gap-2",children:v.jsxs("div",{className:"flex gap-1",children:[v.jsxs(Uo,{value:S2[i.sortBy],onValueChange:V=>{switch(V){case L3:s({sortBy:Es.NAME});break;case F3:s({sortBy:Es.CTIME});break;case j3:s({sortBy:Es.MTIME});break}},children:[v.jsx(go,{className:"w-[140px]",children:v.jsx(Vo,{})}),v.jsx(vo,{children:Object.values(S2).map(V=>v.jsx(yo,{value:V,children:V},V))})]}),i.sortOrder===Ou.DESCENDING?v.jsx(yn,{tooltip:"Descending Order",onClick:()=>{s({sortOrder:Ou.ASCENDING})},children:v.jsx(iK,{})}):v.jsx(yn,{tooltip:"Ascending Order",onClick:()=>{s({sortOrder:Ou.DESCENDING})},children:v.jsx(lK,{})})]})})]}),v.jsx(lg,{className:"w-full h-full rounded-md",onScroll:A,ref:O,children:v.jsx(nK,{layout:i.layout,photos:b,spacing:12,padding:0,onClick:D})})]})]})}var Gd=e=>e.type==="checkbox",$l=e=>e instanceof Date,Fn=e=>e==null;const z3=e=>typeof e=="object";var sn=e=>!Fn(e)&&!Array.isArray(e)&&z3(e)&&!$l(e),B3=e=>sn(e)&&e.target?Gd(e.target)?e.target.checked:e.target.value:e,AY=e=>e.substring(0,e.search(/\.\d+(\.|$)/))||e,U3=(e,t)=>e.has(AY(t)),MY=e=>{const t=e.constructor&&e.constructor.prototype;return sn(t)&&t.hasOwnProperty("isPrototypeOf")},Kx=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function so(e){let t;const n=Array.isArray(e);if(e instanceof Date)t=new Date(e);else if(e instanceof Set)t=new Set(e);else if(!(Kx&&(e instanceof Blob||e instanceof FileList))&&(n||sn(e)))if(t=n?[]:{},!n&&!MY(e))t=e;else for(const r in e)e.hasOwnProperty(r)&&(t[r]=so(e[r]));else return e;return t}var Yd=e=>Array.isArray(e)?e.filter(Boolean):[],Ht=e=>e===void 0,ve=(e,t,n)=>{if(!t||!sn(e))return n;const r=Yd(t.split(/[,[\].]+?/)).reduce((o,i)=>Fn(o)?o:o[i],e);return Ht(r)||r===e?Ht(e[t])?n:e[t]:r},Fo=e=>typeof e=="boolean";const Wp={BLUR:"blur",FOCUS_OUT:"focusout",CHANGE:"change"},mo={onBlur:"onBlur",onChange:"onChange",onSubmit:"onSubmit",onTouched:"onTouched",all:"all"},ui={max:"max",min:"min",maxLength:"maxLength",minLength:"minLength",pattern:"pattern",required:"required",validate:"validate"},V3=je.createContext(null),cg=()=>je.useContext(V3),OY=e=>{const{children:t,...n}=e;return je.createElement(V3.Provider,{value:n},t)};var W3=(e,t,n,r=!0)=>{const o={defaultValues:t._defaultValues};for(const i in e)Object.defineProperty(o,i,{get:()=>{const s=i;return t._proxyFormState[s]!==mo.all&&(t._proxyFormState[s]=!r||mo.all),n&&(n[s]=!0),e[s]}});return o},Fr=e=>sn(e)&&!Object.keys(e).length,H3=(e,t,n,r)=>{n(e);const{name:o,...i}=e;return Fr(i)||Object.keys(i).length>=Object.keys(t).length||Object.keys(i).find(s=>t[s]===(!r||mo.all))},ep=e=>Array.isArray(e)?e:[e],K3=(e,t,n)=>!e||!t||e===t||ep(e).some(r=>r&&(n?r===t:r.startsWith(t)||t.startsWith(r)));function Gx(e){const t=je.useRef(e);t.current=e,je.useEffect(()=>{const n=!e.disabled&&t.current.subject&&t.current.subject.subscribe({next:t.current.next});return()=>{n&&n.unsubscribe()}},[e.disabled])}function NY(e){const t=cg(),{control:n=t.control,disabled:r,name:o,exact:i}=e||{},[s,l]=je.useState(n._formState),u=je.useRef(!0),f=je.useRef({isDirty:!1,isLoading:!1,dirtyFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1}),p=je.useRef(o);return p.current=o,Gx({disabled:r,next:m=>u.current&&K3(p.current,m.name,i)&&H3(m,f.current,n._updateFormState)&&l({...n._formState,...m}),subject:n._subjects.state}),je.useEffect(()=>(u.current=!0,f.current.isValid&&n._updateValid(!0),()=>{u.current=!1}),[n]),W3(s,n,f.current,!1)}var Wo=e=>typeof e=="string",G3=(e,t,n,r,o)=>Wo(e)?(r&&t.watch.add(e),ve(n,e,o)):Array.isArray(e)?e.map(i=>(r&&t.watch.add(i),ve(n,i))):(r&&(t.watchAll=!0),n);function DY(e){const t=cg(),{control:n=t.control,name:r,defaultValue:o,disabled:i,exact:s}=e||{},l=je.useRef(r);l.current=r,Gx({disabled:i,subject:n._subjects.values,next:p=>{K3(l.current,p.name,s)&&f(so(G3(l.current,n._names,p.values||n._formValues,!1,o)))}});const[u,f]=je.useState(n._getWatch(r,o));return je.useEffect(()=>n._removeUnmounted()),u}var Yx=e=>/^\w*$/.test(e),Y3=e=>Yd(e.replace(/["|']|\]/g,"").split(/\.|\[/));function wt(e,t,n){let r=-1;const o=Yx(t)?[t]:Y3(t),i=o.length,s=i-1;for(;++r{const p=o._options.shouldUnregister||i,m=(g,y)=>{const x=ve(o._fields,g);x&&(x._f.mount=y)};if(m(n,!0),p){const g=so(ve(o._options.defaultValues,n));wt(o._defaultValues,n,g),Ht(ve(o._formValues,n))&&wt(o._formValues,n,g)}return()=>{(s?p&&!o._state.action:p)?o.unregister(n):m(n,!1)}},[n,o,s,i]),je.useEffect(()=>{ve(o._fields,n)&&o._updateDisabledField({disabled:r,fields:o._fields,name:n,value:ve(o._fields,n)._f.value})},[r,n,o]),{field:{name:n,value:l,...Fo(r)||Fo(u.disabled)?{disabled:u.disabled||r}:{},onChange:je.useCallback(p=>f.current.onChange({target:{value:B3(p),name:n},type:Wp.CHANGE}),[n]),onBlur:je.useCallback(()=>f.current.onBlur({target:{value:ve(o._formValues,n),name:n},type:Wp.BLUR}),[n,o]),ref:p=>{const m=ve(o._fields,n);m&&p&&(m._f.ref={focus:()=>p.focus(),select:()=>p.select(),setCustomValidity:g=>p.setCustomValidity(g),reportValidity:()=>p.reportValidity()})}},formState:u,fieldState:Object.defineProperties({},{invalid:{enumerable:!0,get:()=>!!ve(u.errors,n)},isDirty:{enumerable:!0,get:()=>!!ve(u.dirtyFields,n)},isTouched:{enumerable:!0,get:()=>!!ve(u.touchedFields,n)},error:{enumerable:!0,get:()=>ve(u.errors,n)}})}}const LY=e=>e.render(IY(e));var X3=(e,t,n,r,o)=>t?{...n[e],types:{...n[e]&&n[e].types?n[e].types:{},[r]:o||!0}}:{},_2=e=>({isOnSubmit:!e||e===mo.onSubmit,isOnBlur:e===mo.onBlur,isOnChange:e===mo.onChange,isOnAll:e===mo.all,isOnTouch:e===mo.onTouched}),E2=(e,t,n)=>!n&&(t.watchAll||t.watch.has(e)||[...t.watch].some(r=>e.startsWith(r)&&/^\.\w+/.test(e.slice(r.length))));const tp=(e,t,n,r)=>{for(const o of n||Object.keys(e)){const i=ve(e,o);if(i){const{_f:s,...l}=i;if(s){if(s.refs&&s.refs[0]&&t(s.refs[0],o)&&!r)break;if(s.ref&&t(s.ref,s.name)&&!r)break}else sn(l)&&tp(l,t)}}};var FY=(e,t,n)=>{const r=Yd(ve(e,n));return wt(r,"root",t[n]),wt(e,n,r),e},Xx=e=>e.type==="file",ms=e=>typeof e=="function",Hp=e=>{if(!Kx)return!1;const t=e?e.ownerDocument:0;return e instanceof(t&&t.defaultView?t.defaultView.HTMLElement:HTMLElement)},np=e=>Wo(e),Zx=e=>e.type==="radio",Kp=e=>e instanceof RegExp;const C2={value:!1,isValid:!1},$2={value:!0,isValid:!0};var Z3=e=>{if(Array.isArray(e)){if(e.length>1){const t=e.filter(n=>n&&n.checked&&!n.disabled).map(n=>n.value);return{value:t,isValid:!!t.length}}return e[0].checked&&!e[0].disabled?e[0].attributes&&!Ht(e[0].attributes.value)?Ht(e[0].value)||e[0].value===""?$2:{value:e[0].value,isValid:!0}:$2:C2}return C2};const R2={isValid:!1,value:null};var q3=e=>Array.isArray(e)?e.reduce((t,n)=>n&&n.checked&&!n.disabled?{isValid:!0,value:n.value}:t,R2):R2;function k2(e,t,n="validate"){if(np(e)||Array.isArray(e)&&e.every(np)||Fo(e)&&!e)return{type:n,message:np(e)?e:"",ref:t}}var sl=e=>sn(e)&&!Kp(e)?e:{value:e,message:""},T2=async(e,t,n,r,o)=>{const{ref:i,refs:s,required:l,maxLength:u,minLength:f,min:p,max:m,pattern:g,validate:y,name:x,valueAsNumber:S,mount:E,disabled:_}=e._f,b=ve(t,x);if(!E||_)return{};const C=s?s[0]:i,R=G=>{r&&C.reportValidity&&(C.setCustomValidity(Fo(G)?"":G||""),C.reportValidity())},P={},O=Zx(i),A=Gd(i),D=O||A,B=(S||Xx(i))&&Ht(i.value)&&Ht(b)||Hp(i)&&i.value===""||b===""||Array.isArray(b)&&!b.length,V=X3.bind(null,x,n,P),J=(G,se,U,ne=ui.maxLength,M=ui.minLength)=>{const ee=G?se:U;P[x]={type:G?ne:M,message:ee,ref:i,...V(G?ne:M,ee)}};if(o?!Array.isArray(b)||!b.length:l&&(!D&&(B||Fn(b))||Fo(b)&&!b||A&&!Z3(s).isValid||O&&!q3(s).isValid)){const{value:G,message:se}=np(l)?{value:!!l,message:l}:sl(l);if(G&&(P[x]={type:ui.required,message:se,ref:C,...V(ui.required,se)},!n))return R(se),P}if(!B&&(!Fn(p)||!Fn(m))){let G,se;const U=sl(m),ne=sl(p);if(!Fn(b)&&!isNaN(b)){const M=i.valueAsNumber||b&&+b;Fn(U.value)||(G=M>U.value),Fn(ne.value)||(se=Mnew Date(new Date().toDateString()+" "+W),H=i.type=="time",X=i.type=="week";Wo(U.value)&&b&&(G=H?ee(b)>ee(U.value):X?b>U.value:M>new Date(U.value)),Wo(ne.value)&&b&&(se=H?ee(b)+G.value,ne=!Fn(se.value)&&b.length<+se.value;if((U||ne)&&(J(U,G.message,se.message),!n))return R(P[x].message),P}if(g&&!B&&Wo(b)){const{value:G,message:se}=sl(g);if(Kp(G)&&!b.match(G)&&(P[x]={type:ui.pattern,message:se,ref:i,...V(ui.pattern,se)},!n))return R(se),P}if(y){if(ms(y)){const G=await y(b,t),se=k2(G,C);if(se&&(P[x]={...se,...V(ui.validate,se.message)},!n))return R(se.message),P}else if(sn(y)){let G={};for(const se in y){if(!Fr(G)&&!n)break;const U=k2(await y[se](b,t),C,se);U&&(G={...U,...V(se,U.message)},R(U.message),n&&(P[x]=G))}if(!Fr(G)&&(P[x]={ref:C,...G},!n))return P}}return R(!0),P};function jY(e,t){const n=t.slice(0,-1).length;let r=0;for(;r{for(const i of e)i.next&&i.next(o)},subscribe:o=>(e.push(o),{unsubscribe:()=>{e=e.filter(i=>i!==o)}}),unsubscribe:()=>{e=[]}}}var Gp=e=>Fn(e)||!z3(e);function ma(e,t){if(Gp(e)||Gp(t))return e===t;if($l(e)&&$l(t))return e.getTime()===t.getTime();const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(const o of n){const i=e[o];if(!r.includes(o))return!1;if(o!=="ref"){const s=t[o];if($l(i)&&$l(s)||sn(i)&&sn(s)||Array.isArray(i)&&Array.isArray(s)?!ma(i,s):i!==s)return!1}}return!0}var Q3=e=>e.type==="select-multiple",BY=e=>Zx(e)||Gd(e),D0=e=>Hp(e)&&e.isConnected,J3=e=>{for(const t in e)if(ms(e[t]))return!0;return!1};function Yp(e,t={}){const n=Array.isArray(e);if(sn(e)||n)for(const r in e)Array.isArray(e[r])||sn(e[r])&&!J3(e[r])?(t[r]=Array.isArray(e[r])?[]:{},Yp(e[r],t[r])):Fn(e[r])||(t[r]=!0);return t}function eP(e,t,n){const r=Array.isArray(e);if(sn(e)||r)for(const o in e)Array.isArray(e[o])||sn(e[o])&&!J3(e[o])?Ht(t)||Gp(n[o])?n[o]=Array.isArray(e[o])?Yp(e[o],[]):{...Yp(e[o])}:eP(e[o],Fn(t)?{}:t[o],n[o]):n[o]=!ma(e[o],t[o]);return n}var I0=(e,t)=>eP(e,t,Yp(t)),tP=(e,{valueAsNumber:t,valueAsDate:n,setValueAs:r})=>Ht(e)?e:t?e===""?NaN:e&&+e:n&&Wo(e)?new Date(e):r?r(e):e;function L0(e){const t=e.ref;if(!(e.refs?e.refs.every(n=>n.disabled):t.disabled))return Xx(t)?t.files:Zx(t)?q3(e.refs).value:Q3(t)?[...t.selectedOptions].map(({value:n})=>n):Gd(t)?Z3(e.refs).value:tP(Ht(t.value)?e.ref.value:t.value,e)}var UY=(e,t,n,r)=>{const o={};for(const i of e){const s=ve(t,i);s&&wt(o,i,s._f)}return{criteriaMode:n,names:[...e],fields:o,shouldUseNativeValidation:r}},du=e=>Ht(e)?e:Kp(e)?e.source:sn(e)?Kp(e.value)?e.value.source:e.value:e,VY=e=>e.mount&&(e.required||e.min||e.max||e.maxLength||e.minLength||e.pattern||e.validate);function P2(e,t,n){const r=ve(e,n);if(r||Yx(n))return{error:r,name:n};const o=n.split(".");for(;o.length;){const i=o.join("."),s=ve(t,i),l=ve(e,i);if(s&&!Array.isArray(s)&&n!==i)return{name:n};if(l&&l.type)return{name:i,error:l};o.pop()}return{name:n}}var WY=(e,t,n,r,o)=>o.isOnAll?!1:!n&&o.isOnTouch?!(t||e):(n?r.isOnBlur:o.isOnBlur)?!e:(n?r.isOnChange:o.isOnChange)?e:!0,HY=(e,t)=>!Yd(ve(e,t)).length&&pn(e,t);const KY={mode:mo.onSubmit,reValidateMode:mo.onChange,shouldFocusError:!0};function GY(e={},t){let n={...KY,...e},r={submitCount:0,isDirty:!1,isLoading:ms(n.defaultValues),isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},errors:{},disabled:!1},o={},i=sn(n.defaultValues)||sn(n.values)?so(n.defaultValues||n.values)||{}:{},s=n.shouldUnregister?{}:so(i),l={action:!1,mount:!1,watch:!1},u={mount:new Set,unMount:new Set,array:new Set,watch:new Set},f,p=0;const m={isDirty:!1,dirtyFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1},g={values:N0(),array:N0(),state:N0()},y=e.resetOptions&&e.resetOptions.keepDirtyValues,x=_2(n.mode),S=_2(n.reValidateMode),E=n.criteriaMode===mo.all,_=L=>Z=>{clearTimeout(p),p=setTimeout(L,Z)},b=async L=>{if(m.isValid||L){const Z=n.resolver?Fr((await B()).errors):await J(o,!0);Z!==r.isValid&&g.state.next({isValid:Z})}},C=L=>m.isValidating&&g.state.next({isValidating:L}),R=(L,Z=[],q,we,me=!0,de=!0)=>{if(we&&q){if(l.action=!0,de&&Array.isArray(ve(o,L))){const ke=q(ve(o,L),we.argA,we.argB);me&&wt(o,L,ke)}if(de&&Array.isArray(ve(r.errors,L))){const ke=q(ve(r.errors,L),we.argA,we.argB);me&&wt(r.errors,L,ke),HY(r.errors,L)}if(m.touchedFields&&de&&Array.isArray(ve(r.touchedFields,L))){const ke=q(ve(r.touchedFields,L),we.argA,we.argB);me&&wt(r.touchedFields,L,ke)}m.dirtyFields&&(r.dirtyFields=I0(i,s)),g.state.next({name:L,isDirty:se(L,Z),dirtyFields:r.dirtyFields,errors:r.errors,isValid:r.isValid})}else wt(s,L,Z)},P=(L,Z)=>{wt(r.errors,L,Z),g.state.next({errors:r.errors})},O=(L,Z,q,we)=>{const me=ve(o,L);if(me){const de=ve(s,L,Ht(q)?ve(i,L):q);Ht(de)||we&&we.defaultChecked||Z?wt(s,L,Z?de:L0(me._f)):M(L,de),l.mount&&b()}},A=(L,Z,q,we,me)=>{let de=!1,ke=!1;const ft={name:L};if(!q||we){m.isDirty&&(ke=r.isDirty,r.isDirty=ft.isDirty=se(),de=ke!==ft.isDirty);const ht=ma(ve(i,L),Z);ke=ve(r.dirtyFields,L),ht?pn(r.dirtyFields,L):wt(r.dirtyFields,L,!0),ft.dirtyFields=r.dirtyFields,de=de||m.dirtyFields&&ke!==!ht}if(q){const ht=ve(r.touchedFields,L);ht||(wt(r.touchedFields,L,q),ft.touchedFields=r.touchedFields,de=de||m.touchedFields&&ht!==q)}return de&&me&&g.state.next(ft),de?ft:{}},D=(L,Z,q,we)=>{const me=ve(r.errors,L),de=m.isValid&&Fo(Z)&&r.isValid!==Z;if(e.delayError&&q?(f=_(()=>P(L,q)),f(e.delayError)):(clearTimeout(p),f=null,q?wt(r.errors,L,q):pn(r.errors,L)),(q?!ma(me,q):me)||!Fr(we)||de){const ke={...we,...de&&Fo(Z)?{isValid:Z}:{},errors:r.errors,name:L};r={...r,...ke},g.state.next(ke)}C(!1)},B=async L=>n.resolver(s,n.context,UY(L||u.mount,o,n.criteriaMode,n.shouldUseNativeValidation)),V=async L=>{const{errors:Z}=await B(L);if(L)for(const q of L){const we=ve(Z,q);we?wt(r.errors,q,we):pn(r.errors,q)}else r.errors=Z;return Z},J=async(L,Z,q={valid:!0})=>{for(const we in L){const me=L[we];if(me){const{_f:de,...ke}=me;if(de){const ft=u.array.has(de.name),ht=await T2(me,s,E,n.shouldUseNativeValidation&&!Z,ft);if(ht[de.name]&&(q.valid=!1,Z))break;!Z&&(ve(ht,de.name)?ft?FY(r.errors,ht,de.name):wt(r.errors,de.name,ht[de.name]):pn(r.errors,de.name))}ke&&await J(ke,Z,q)}}return q.valid},G=()=>{for(const L of u.unMount){const Z=ve(o,L);Z&&(Z._f.refs?Z._f.refs.every(q=>!D0(q)):!D0(Z._f.ref))&&fe(L)}u.unMount=new Set},se=(L,Z)=>(L&&Z&&wt(s,L,Z),!ma(pe(),i)),U=(L,Z,q)=>G3(L,u,{...l.mount?s:Ht(Z)?i:Wo(L)?{[L]:Z}:Z},q,Z),ne=L=>Yd(ve(l.mount?s:i,L,e.shouldUnregister?ve(i,L,[]):[])),M=(L,Z,q={})=>{const we=ve(o,L);let me=Z;if(we){const de=we._f;de&&(!de.disabled&&wt(s,L,tP(Z,de)),me=Hp(de.ref)&&Fn(Z)?"":Z,Q3(de.ref)?[...de.ref.options].forEach(ke=>ke.selected=me.includes(ke.value)):de.refs?Gd(de.ref)?de.refs.length>1?de.refs.forEach(ke=>(!ke.defaultChecked||!ke.disabled)&&(ke.checked=Array.isArray(me)?!!me.find(ft=>ft===ke.value):me===ke.value)):de.refs[0]&&(de.refs[0].checked=!!me):de.refs.forEach(ke=>ke.checked=ke.value===me):Xx(de.ref)?de.ref.value="":(de.ref.value=me,de.ref.type||g.values.next({name:L,values:{...s}})))}(q.shouldDirty||q.shouldTouch)&&A(L,me,q.shouldTouch,q.shouldDirty,!0),q.shouldValidate&&le(L)},ee=(L,Z,q)=>{for(const we in Z){const me=Z[we],de=`${L}.${we}`,ke=ve(o,de);(u.array.has(L)||!Gp(me)||ke&&!ke._f)&&!$l(me)?ee(de,me,q):M(de,me,q)}},H=(L,Z,q={})=>{const we=ve(o,L),me=u.array.has(L),de=so(Z);wt(s,L,de),me?(g.array.next({name:L,values:{...s}}),(m.isDirty||m.dirtyFields)&&q.shouldDirty&&g.state.next({name:L,dirtyFields:I0(i,s),isDirty:se(L,de)})):we&&!we._f&&!Fn(de)?ee(L,de,q):M(L,de,q),E2(L,u)&&g.state.next({...r}),g.values.next({name:L,values:{...s}}),!l.mount&&t()},X=async L=>{const Z=L.target;let q=Z.name,we=!0;const me=ve(o,q),de=()=>Z.type?L0(me._f):B3(L),ke=ft=>{we=Number.isNaN(ft)||ft===ve(s,q,ft)};if(me){let ft,ht;const _n=de(),Cr=L.type===Wp.BLUR||L.type===Wp.FOCUS_OUT,Ni=!VY(me._f)&&!n.resolver&&!ve(r.errors,q)&&!me._f.deps||WY(Cr,ve(r.touchedFields,q),r.isSubmitted,S,x),Co=E2(q,u,Cr);wt(s,q,_n),Cr?(me._f.onBlur&&me._f.onBlur(L),f&&f(0)):me._f.onChange&&me._f.onChange(L);const Vn=A(q,_n,Cr,!1),Ba=!Fr(Vn)||Co;if(!Cr&&g.values.next({name:q,type:L.type,values:{...s}}),Ni)return m.isValid&&b(),Ba&&g.state.next({name:q,...Co?{}:Vn});if(!Cr&&Co&&g.state.next({...r}),C(!0),n.resolver){const{errors:Di}=await B([q]);if(ke(_n),we){const Ws=P2(r.errors,o,q),Ii=P2(Di,o,Ws.name||q);ft=Ii.error,q=Ii.name,ht=Fr(Di)}}else ft=(await T2(me,s,E,n.shouldUseNativeValidation))[q],ke(_n),we&&(ft?ht=!1:m.isValid&&(ht=await J(o,!0)));we&&(me._f.deps&&le(me._f.deps),D(q,ht,ft,Vn))}},W=(L,Z)=>{if(ve(r.errors,Z)&&L.focus)return L.focus(),1},le=async(L,Z={})=>{let q,we;const me=ep(L);if(C(!0),n.resolver){const de=await V(Ht(L)?L:me);q=Fr(de),we=L?!me.some(ke=>ve(de,ke)):q}else L?(we=(await Promise.all(me.map(async de=>{const ke=ve(o,de);return await J(ke&&ke._f?{[de]:ke}:ke)}))).every(Boolean),!(!we&&!r.isValid)&&b()):we=q=await J(o);return g.state.next({...!Wo(L)||m.isValid&&q!==r.isValid?{}:{name:L},...n.resolver||!L?{isValid:q}:{},errors:r.errors,isValidating:!1}),Z.shouldFocus&&!we&&tp(o,W,L?me:u.mount),we},pe=L=>{const Z={...i,...l.mount?s:{}};return Ht(L)?Z:Wo(L)?ve(Z,L):L.map(q=>ve(Z,q))},$e=(L,Z)=>({invalid:!!ve((Z||r).errors,L),isDirty:!!ve((Z||r).dirtyFields,L),isTouched:!!ve((Z||r).touchedFields,L),error:ve((Z||r).errors,L)}),Ve=L=>{L&&ep(L).forEach(Z=>pn(r.errors,Z)),g.state.next({errors:L?r.errors:{}})},We=(L,Z,q)=>{const we=(ve(o,L,{_f:{}})._f||{}).ref;wt(r.errors,L,{...Z,ref:we}),g.state.next({name:L,errors:r.errors,isValid:!1}),q&&q.shouldFocus&&we&&we.focus&&we.focus()},Ne=(L,Z)=>ms(L)?g.values.subscribe({next:q=>L(U(void 0,Z),q)}):U(L,Z,!0),fe=(L,Z={})=>{for(const q of L?ep(L):u.mount)u.mount.delete(q),u.array.delete(q),Z.keepValue||(pn(o,q),pn(s,q)),!Z.keepError&&pn(r.errors,q),!Z.keepDirty&&pn(r.dirtyFields,q),!Z.keepTouched&&pn(r.touchedFields,q),!n.shouldUnregister&&!Z.keepDefaultValue&&pn(i,q);g.values.next({values:{...s}}),g.state.next({...r,...Z.keepDirty?{isDirty:se()}:{}}),!Z.keepIsValid&&b()},xe=({disabled:L,name:Z,field:q,fields:we,value:me})=>{if(Fo(L)){const de=L?void 0:Ht(me)?L0(q?q._f:ve(we,Z)._f):me;wt(s,Z,de),A(Z,de,!1,!1,!0)}},Re=(L,Z={})=>{let q=ve(o,L);const we=Fo(Z.disabled);return wt(o,L,{...q||{},_f:{...q&&q._f?q._f:{ref:{name:L}},name:L,mount:!0,...Z}}),u.mount.add(L),q?xe({field:q,disabled:Z.disabled,name:L}):O(L,!0,Z.value),{...we?{disabled:Z.disabled}:{},...n.progressive?{required:!!Z.required,min:du(Z.min),max:du(Z.max),minLength:du(Z.minLength),maxLength:du(Z.maxLength),pattern:du(Z.pattern)}:{},name:L,onChange:X,onBlur:X,ref:me=>{if(me){Re(L,Z),q=ve(o,L);const de=Ht(me.value)&&me.querySelectorAll&&me.querySelectorAll("input,select,textarea")[0]||me,ke=BY(de),ft=q._f.refs||[];if(ke?ft.find(ht=>ht===de):de===q._f.ref)return;wt(o,L,{_f:{...q._f,...ke?{refs:[...ft.filter(D0),de,...Array.isArray(ve(i,L))?[{}]:[]],ref:{type:de.type,name:L}}:{ref:de}}}),O(L,!1,void 0,de)}else q=ve(o,L,{}),q._f&&(q._f.mount=!1),(n.shouldUnregister||Z.shouldUnregister)&&!(U3(u.array,L)&&l.action)&&u.unMount.add(L)}}},Me=()=>n.shouldFocusError&&tp(o,W,u.mount),Oe=L=>{Fo(L)&&(g.state.next({disabled:L}),tp(o,Z=>{Z.disabled=L},0,!1))},ze=(L,Z)=>async q=>{q&&(q.preventDefault&&q.preventDefault(),q.persist&&q.persist());let we=so(s);if(g.state.next({isSubmitting:!0}),n.resolver){const{errors:me,values:de}=await B();r.errors=me,we=de}else await J(o);pn(r.errors,"root"),Fr(r.errors)?(g.state.next({errors:{}}),await L(we,q)):(Z&&await Z({...r.errors},q),Me(),setTimeout(Me)),g.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:Fr(r.errors),submitCount:r.submitCount+1,errors:r.errors})},Mt=(L,Z={})=>{ve(o,L)&&(Ht(Z.defaultValue)?H(L,ve(i,L)):(H(L,Z.defaultValue),wt(i,L,Z.defaultValue)),Z.keepTouched||pn(r.touchedFields,L),Z.keepDirty||(pn(r.dirtyFields,L),r.isDirty=Z.defaultValue?se(L,ve(i,L)):se()),Z.keepError||(pn(r.errors,L),m.isValid&&b()),g.state.next({...r}))},ct=(L,Z={})=>{const q=L?so(L):i,we=so(q),me=L&&!Fr(L)?we:i;if(Z.keepDefaultValues||(i=q),!Z.keepValues){if(Z.keepDirtyValues||y)for(const de of u.mount)ve(r.dirtyFields,de)?wt(me,de,ve(s,de)):H(de,ve(me,de));else{if(Kx&&Ht(L))for(const de of u.mount){const ke=ve(o,de);if(ke&&ke._f){const ft=Array.isArray(ke._f.refs)?ke._f.refs[0]:ke._f.ref;if(Hp(ft)){const ht=ft.closest("form");if(ht){ht.reset();break}}}}o={}}s=e.shouldUnregister?Z.keepDefaultValues?so(i):{}:so(me),g.array.next({values:{...me}}),g.values.next({values:{...me}})}u={mount:new Set,unMount:new Set,array:new Set,watch:new Set,watchAll:!1,focus:""},!l.mount&&t(),l.mount=!m.isValid||!!Z.keepIsValid,l.watch=!!e.shouldUnregister,g.state.next({submitCount:Z.keepSubmitCount?r.submitCount:0,isDirty:Z.keepDirty?r.isDirty:!!(Z.keepDefaultValues&&!ma(L,i)),isSubmitted:Z.keepIsSubmitted?r.isSubmitted:!1,dirtyFields:Z.keepDirtyValues?r.dirtyFields:Z.keepDefaultValues&&L?I0(i,L):{},touchedFields:Z.keepTouched?r.touchedFields:{},errors:Z.keepErrors?r.errors:{},isSubmitSuccessful:Z.keepIsSubmitSuccessful?r.isSubmitSuccessful:!1,isSubmitting:!1})},Kt=(L,Z)=>ct(ms(L)?L(s):L,Z);return{control:{register:Re,unregister:fe,getFieldState:$e,handleSubmit:ze,setError:We,_executeSchema:B,_getWatch:U,_getDirty:se,_updateValid:b,_removeUnmounted:G,_updateFieldArray:R,_updateDisabledField:xe,_getFieldArray:ne,_reset:ct,_resetDefaultValues:()=>ms(n.defaultValues)&&n.defaultValues().then(L=>{Kt(L,n.resetOptions),g.state.next({isLoading:!1})}),_updateFormState:L=>{r={...r,...L}},_disableForm:Oe,_subjects:g,_proxyFormState:m,get _fields(){return o},get _formValues(){return s},get _state(){return l},set _state(L){l=L},get _defaultValues(){return i},get _names(){return u},set _names(L){u=L},get _formState(){return r},set _formState(L){r=L},get _options(){return n},set _options(L){n={...n,...L}}},trigger:le,register:Re,handleSubmit:ze,watch:Ne,setValue:H,getValues:pe,reset:Kt,resetField:Mt,clearErrors:Ve,unregister:fe,setError:We,setFocus:(L,Z={})=>{const q=ve(o,L),we=q&&q._f;if(we){const me=we.refs?we.refs[0]:we.ref;me.focus&&(me.focus(),Z.shouldSelect&&me.select())}},getFieldState:$e}}function YY(e={}){const t=je.useRef(),n=je.useRef(),[r,o]=je.useState({isDirty:!1,isValidating:!1,isLoading:ms(e.defaultValues),isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,submitCount:0,dirtyFields:{},touchedFields:{},errors:{},disabled:!1,defaultValues:ms(e.defaultValues)?void 0:e.defaultValues});t.current||(t.current={...GY(e,()=>o(s=>({...s}))),formState:r});const i=t.current.control;return i._options=e,Gx({subject:i._subjects.state,next:s=>{H3(s,i._proxyFormState,i._updateFormState,!0)&&o({...i._formState})}}),je.useEffect(()=>i._disableForm(e.disabled),[i,e.disabled]),je.useEffect(()=>{if(i._proxyFormState.isDirty){const s=i._getDirty();s!==r.isDirty&&i._subjects.state.next({isDirty:s})}},[i,r.isDirty]),je.useEffect(()=>{e.values&&!ma(e.values,n.current)?(i._reset(e.values,i._options.resetOptions),n.current=e.values):i._resetDefaultValues()},[e.values,i]),je.useEffect(()=>{i._state.mount||(i._updateValid(),i._state.mount=!0),i._state.watch&&(i._state.watch=!1,i._subjects.state.next({...i._formState})),i._removeUnmounted()}),t.current.formState=W3(r,i),t.current}var A2=function(e,t,n){if(e&&"reportValidity"in e){var r=ve(n,t);e.setCustomValidity(r&&r.message||""),e.reportValidity()}},nP=function(e,t){var n=function(o){var i=t.fields[o];i&&i.ref&&"reportValidity"in i.ref?A2(i.ref,o,e):i.refs&&i.refs.forEach(function(s){return A2(s,o,e)})};for(var r in t.fields)n(r)},XY=function(e,t){t.shouldUseNativeValidation&&nP(e,t);var n={};for(var r in e){var o=ve(t.fields,r),i=Object.assign(e[r]||{},{ref:o&&o.ref});if(qY(t.names||Object.keys(e),r)){var s=Object.assign({},ZY(ve(n,r)));wt(s,"root",i),wt(n,r,s)}else wt(n,r,i)}return n},ZY=function(e){return Array.isArray(e)?e.filter(Boolean):[]},qY=function(e,t){return e.some(function(n){return n.startsWith(t+".")})},QY=function(e,t){for(var n={};e.length;){var r=e[0],o=r.code,i=r.message,s=r.path.join(".");if(!n[s])if("unionErrors"in r){var l=r.unionErrors[0].errors[0];n[s]={message:l.message,type:l.code}}else n[s]={message:i,type:o};if("unionErrors"in r&&r.unionErrors.forEach(function(p){return p.errors.forEach(function(m){return e.push(m)})}),t){var u=n[s].types,f=u&&u[r.code];n[s]=X3(s,t,n,o,f?[].concat(f,r.message):r.message)}e.shift()}return n},JY=function(e,t,n){return n===void 0&&(n={}),function(r,o,i){try{return Promise.resolve(function(s,l){try{var u=Promise.resolve(e[n.mode==="sync"?"parse":"parseAsync"](r,t)).then(function(f){return i.shouldUseNativeValidation&&nP({},i),{errors:{},values:n.raw?r:f}})}catch(f){return l(f)}return u&&u.then?u.then(void 0,l):u}(0,function(s){if(function(l){return l.errors!=null}(s))return{values:{},errors:XY(QY(s.errors,!i.shouldUseNativeValidation&&i.criteriaMode==="all"),i)};throw s}))}catch(s){return Promise.reject(s)}}},mt;(function(e){e.assertEqual=o=>o;function t(o){}e.assertIs=t;function n(o){throw new Error}e.assertNever=n,e.arrayToEnum=o=>{const i={};for(const s of o)i[s]=s;return i},e.getValidEnumValues=o=>{const i=e.objectKeys(o).filter(l=>typeof o[o[l]]!="number"),s={};for(const l of i)s[l]=o[l];return e.objectValues(s)},e.objectValues=o=>e.objectKeys(o).map(function(i){return o[i]}),e.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{const i=[];for(const s in o)Object.prototype.hasOwnProperty.call(o,s)&&i.push(s);return i},e.find=(o,i)=>{for(const s of o)if(i(s))return s},e.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&isFinite(o)&&Math.floor(o)===o;function r(o,i=" | "){return o.map(s=>typeof s=="string"?`'${s}'`:s).join(i)}e.joinValues=r,e.jsonStringifyReplacer=(o,i)=>typeof i=="bigint"?i.toString():i})(mt||(mt={}));var M2;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(M2||(M2={}));const be=mt.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ca=e=>{switch(typeof e){case"undefined":return be.undefined;case"string":return be.string;case"number":return isNaN(e)?be.nan:be.number;case"boolean":return be.boolean;case"function":return be.function;case"bigint":return be.bigint;case"symbol":return be.symbol;case"object":return Array.isArray(e)?be.array:e===null?be.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?be.promise:typeof Map<"u"&&e instanceof Map?be.map:typeof Set<"u"&&e instanceof Set?be.set:typeof Date<"u"&&e instanceof Date?be.date:be.object;default:return be.unknown}},he=mt.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"]);class Go 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(i){return i.message},r={_errors:[]},o=i=>{for(const s of i.issues)if(s.code==="invalid_union")s.unionErrors.map(o);else if(s.code==="invalid_return_type")o(s.returnTypeError);else if(s.code==="invalid_arguments")o(s.argumentsError);else if(s.path.length===0)r._errors.push(n(s));else{let l=r,u=0;for(;un.message){const n={},r=[];for(const o of this.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(t(o))):r.push(t(o));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}}Go.create=e=>new Go(e);const Xp=(e,t)=>{let n;switch(e.code){case he.invalid_type:e.received===be.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case he.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,mt.jsonStringifyReplacer)}`;break;case he.unrecognized_keys:n=`Unrecognized key(s) in object: ${mt.joinValues(e.keys,", ")}`;break;case he.invalid_union:n="Invalid input";break;case he.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${mt.joinValues(e.options)}`;break;case he.invalid_enum_value:n=`Invalid enum value. Expected ${mt.joinValues(e.options)}, received '${e.received}'`;break;case he.invalid_arguments:n="Invalid function arguments";break;case he.invalid_return_type:n="Invalid function return type";break;case he.invalid_date:n="Invalid date";break;case he.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}"`:mt.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case he.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 he.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 he.custom:n="Invalid input";break;case he.invalid_intersection_types:n="Intersection results could not be merged";break;case he.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case he.not_finite:n="Number must be finite";break;default:n=t.defaultError,mt.assertNever(e)}return{message:n}};let eX=Xp;function C1(){return eX}const $1=e=>{const{data:t,path:n,errorMaps:r,issueData:o}=e,i=[...n,...o.path||[]],s={...o,path:i};let l="";const u=r.filter(f=>!!f).slice().reverse();for(const f of u)l=f(s,{data:t,defaultError:l}).message;return{...o,path:i,message:o.message||l}};function Ce(e,t){const n=$1({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,C1(),Xp].filter(r=>!!r)});e.common.issues.push(n)}class zn{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 o of n){if(o.status==="aborted")return Ze;o.status==="dirty"&&t.dirty(),r.push(o.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){const r=[];for(const o of n)r.push({key:await o.key,value:await o.value});return zn.mergeObjectSync(t,r)}static mergeObjectSync(t,n){const r={};for(const o of n){const{key:i,value:s}=o;if(i.status==="aborted"||s.status==="aborted")return Ze;i.status==="dirty"&&t.dirty(),s.status==="dirty"&&t.dirty(),i.value!=="__proto__"&&(typeof s.value<"u"||o.alwaysSet)&&(r[i.value]=s.value)}return{status:t.value,value:r}}}const Ze=Object.freeze({status:"aborted"}),tX=e=>({status:"dirty",value:e}),rr=e=>({status:"valid",value:e}),O2=e=>e.status==="aborted",N2=e=>e.status==="dirty",Zp=e=>e.status==="valid",R1=e=>typeof Promise<"u"&&e instanceof Promise;var De;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t==null?void 0:t.message})(De||(De={}));class Qo{constructor(t,n,r,o){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=o}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 D2=(e,t)=>{if(Zp(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 Go(e.common.issues);return this._error=n,this._error}}};function Xe(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:r,description:o}=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:o}:{errorMap:(s,l)=>s.code!=="invalid_type"?{message:l.defaultError}:typeof l.data>"u"?{message:r??l.defaultError}:{message:n??l.defaultError},description:o}}class rt{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.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this)}get description(){return this._def.description}_getType(t){return ca(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:ca(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new zn,ctx:{common:t.parent.common,data:t.data,parsedType:ca(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const n=this._parse(t);if(R1(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 o={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:ca(t)},i=this._parseSync({data:t,path:o.path,parent:o});return D2(o,i)}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:ca(t)},o=this._parse({data:t,path:r.path,parent:r}),i=await(R1(o)?o:Promise.resolve(o));return D2(r,i)}refine(t,n){const r=o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n;return this._refinement((o,i)=>{const s=t(o),l=()=>i.addIssue({code:he.custom,...r(o)});return typeof Promise<"u"&&s instanceof Promise?s.then(u=>u?!0:(l(),!1)):s?!0:(l(),!1)})}refinement(t,n){return this._refinement((r,o)=>t(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(t){return new Pi({schema:this,typeName:Be.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}optional(){return Cs.create(this,this._def)}nullable(){return gc.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Yo.create(this,this._def)}promise(){return pd.create(this,this._def)}or(t){return Jp.create([this,t],this._def)}and(t){return em.create(this,t,this._def)}transform(t){return new Pi({...Xe(this._def),schema:this,typeName:Be.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const n=typeof t=="function"?t:()=>t;return new im({...Xe(this._def),innerType:this,defaultValue:n,typeName:Be.ZodDefault})}brand(){return new hX({typeName:Be.ZodBranded,type:this,...Xe(this._def)})}catch(t){const n=typeof t=="function"?t:()=>t;return new N1({...Xe(this._def),innerType:this,catchValue:n,typeName:Be.ZodCatch})}describe(t){const n=this.constructor;return new n({...this._def,description:t})}pipe(t){return ug.create(this,t)}readonly(){return I1.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const nX=/^c[^\s-]{8,}$/i,rX=/^[a-z][a-z0-9]*$/,oX=/^[0-9A-HJKMNP-TV-Z]{26}$/,iX=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,sX=/^(?!\.)(?!.*\.\.)([A-Z0-9_+-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,aX="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let F0;const lX=/^(((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}))$/,cX=/^(([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})))$/,uX=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 dX(e,t){return!!((t==="v4"||!t)&&lX.test(e)||(t==="v6"||!t)&&cX.test(e))}class yi extends rt{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==be.string){const i=this._getOrReturnCtx(t);return Ce(i,{code:he.invalid_type,expected:be.string,received:i.parsedType}),Ze}const r=new zn;let o;for(const i of this._def.checks)if(i.kind==="min")t.data.lengthi.value&&(o=this._getOrReturnCtx(t,o),Ce(o,{code:he.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){const s=t.data.length>i.value,l=t.data.lengtht.test(o),{validation:n,code:he.invalid_string,...De.errToObj(r)})}_addCheck(t){return new yi({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...De.errToObj(t)})}url(t){return this._addCheck({kind:"url",...De.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...De.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...De.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...De.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...De.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...De.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...De.errToObj(t)})}datetime(t){var n;return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof(t==null?void 0:t.precision)>"u"?null:t==null?void 0:t.precision,offset:(n=t==null?void 0:t.offset)!==null&&n!==void 0?n:!1,...De.errToObj(t==null?void 0:t.message)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...De.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n==null?void 0:n.position,...De.errToObj(n==null?void 0:n.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...De.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...De.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...De.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...De.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...De.errToObj(n)})}nonempty(t){return this.min(1,De.errToObj(t))}trim(){return new yi({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new yi({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new yi({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}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 yi({checks:[],typeName:Be.ZodString,coerce:(t=e==null?void 0:e.coerce)!==null&&t!==void 0?t:!1,...Xe(e)})};function fX(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,o=n>r?n:r,i=parseInt(e.toFixed(o).replace(".","")),s=parseInt(t.toFixed(o).replace(".",""));return i%s/Math.pow(10,o)}class hc extends rt{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)!==be.number){const i=this._getOrReturnCtx(t);return Ce(i,{code:he.invalid_type,expected:be.number,received:i.parsedType}),Ze}let r;const o=new zn;for(const i of this._def.checks)i.kind==="int"?mt.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),Ce(r,{code:he.invalid_type,expected:"integer",received:"float",message:i.message}),o.dirty()):i.kind==="min"?(i.inclusive?t.datai.value:t.data>=i.value)&&(r=this._getOrReturnCtx(t,r),Ce(r,{code:he.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),o.dirty()):i.kind==="multipleOf"?fX(t.data,i.value)!==0&&(r=this._getOrReturnCtx(t,r),Ce(r,{code:he.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):i.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),Ce(r,{code:he.not_finite,message:i.message}),o.dirty()):mt.assertNever(i);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,De.toString(n))}gt(t,n){return this.setLimit("min",t,!1,De.toString(n))}lte(t,n){return this.setLimit("max",t,!0,De.toString(n))}lt(t,n){return this.setLimit("max",t,!1,De.toString(n))}setLimit(t,n,r,o){return new hc({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:De.toString(o)}]})}_addCheck(t){return new hc({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:De.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:De.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:De.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:De.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:De.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:De.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:De.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:De.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:De.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"&&mt.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 hc({checks:[],typeName:Be.ZodNumber,coerce:(e==null?void 0:e.coerce)||!1,...Xe(e)});class pc extends rt{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)!==be.bigint){const i=this._getOrReturnCtx(t);return Ce(i,{code:he.invalid_type,expected:be.bigint,received:i.parsedType}),Ze}let r;const o=new zn;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?t.datai.value:t.data>=i.value)&&(r=this._getOrReturnCtx(t,r),Ce(r,{code:he.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),o.dirty()):i.kind==="multipleOf"?t.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),Ce(r,{code:he.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):mt.assertNever(i);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,De.toString(n))}gt(t,n){return this.setLimit("min",t,!1,De.toString(n))}lte(t,n){return this.setLimit("max",t,!0,De.toString(n))}lt(t,n){return this.setLimit("max",t,!1,De.toString(n))}setLimit(t,n,r,o){return new pc({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:De.toString(o)}]})}_addCheck(t){return new pc({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:De.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:De.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:De.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:De.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:De.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 pc({checks:[],typeName:Be.ZodBigInt,coerce:(t=e==null?void 0:e.coerce)!==null&&t!==void 0?t:!1,...Xe(e)})};class k1 extends rt{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==be.boolean){const r=this._getOrReturnCtx(t);return Ce(r,{code:he.invalid_type,expected:be.boolean,received:r.parsedType}),Ze}return rr(t.data)}}k1.create=e=>new k1({typeName:Be.ZodBoolean,coerce:(e==null?void 0:e.coerce)||!1,...Xe(e)});class hd extends rt{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==be.date){const i=this._getOrReturnCtx(t);return Ce(i,{code:he.invalid_type,expected:be.date,received:i.parsedType}),Ze}if(isNaN(t.data.getTime())){const i=this._getOrReturnCtx(t);return Ce(i,{code:he.invalid_date}),Ze}const r=new zn;let o;for(const i of this._def.checks)i.kind==="min"?t.data.getTime()i.value&&(o=this._getOrReturnCtx(t,o),Ce(o,{code:he.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):mt.assertNever(i);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new hd({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:De.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:De.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 hd({checks:[],coerce:(e==null?void 0:e.coerce)||!1,typeName:Be.ZodDate,...Xe(e)});class T1 extends rt{_parse(t){if(this._getType(t)!==be.symbol){const r=this._getOrReturnCtx(t);return Ce(r,{code:he.invalid_type,expected:be.symbol,received:r.parsedType}),Ze}return rr(t.data)}}T1.create=e=>new T1({typeName:Be.ZodSymbol,...Xe(e)});class qp extends rt{_parse(t){if(this._getType(t)!==be.undefined){const r=this._getOrReturnCtx(t);return Ce(r,{code:he.invalid_type,expected:be.undefined,received:r.parsedType}),Ze}return rr(t.data)}}qp.create=e=>new qp({typeName:Be.ZodUndefined,...Xe(e)});class Qp extends rt{_parse(t){if(this._getType(t)!==be.null){const r=this._getOrReturnCtx(t);return Ce(r,{code:he.invalid_type,expected:be.null,received:r.parsedType}),Ze}return rr(t.data)}}Qp.create=e=>new Qp({typeName:Be.ZodNull,...Xe(e)});class P1 extends rt{constructor(){super(...arguments),this._any=!0}_parse(t){return rr(t.data)}}P1.create=e=>new P1({typeName:Be.ZodAny,...Xe(e)});class Dl extends rt{constructor(){super(...arguments),this._unknown=!0}_parse(t){return rr(t.data)}}Dl.create=e=>new Dl({typeName:Be.ZodUnknown,...Xe(e)});class Ms extends rt{_parse(t){const n=this._getOrReturnCtx(t);return Ce(n,{code:he.invalid_type,expected:be.never,received:n.parsedType}),Ze}}Ms.create=e=>new Ms({typeName:Be.ZodNever,...Xe(e)});class A1 extends rt{_parse(t){if(this._getType(t)!==be.undefined){const r=this._getOrReturnCtx(t);return Ce(r,{code:he.invalid_type,expected:be.void,received:r.parsedType}),Ze}return rr(t.data)}}A1.create=e=>new A1({typeName:Be.ZodVoid,...Xe(e)});class Yo extends rt{_parse(t){const{ctx:n,status:r}=this._processInputParams(t),o=this._def;if(n.parsedType!==be.array)return Ce(n,{code:he.invalid_type,expected:be.array,received:n.parsedType}),Ze;if(o.exactLength!==null){const s=n.data.length>o.exactLength.value,l=n.data.lengtho.maxLength.value&&(Ce(n,{code:he.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((s,l)=>o.type._parseAsync(new Qo(n,s,n.path,l)))).then(s=>zn.mergeArray(r,s));const i=[...n.data].map((s,l)=>o.type._parseSync(new Qo(n,s,n.path,l)));return zn.mergeArray(r,i)}get element(){return this._def.type}min(t,n){return new Yo({...this._def,minLength:{value:t,message:De.toString(n)}})}max(t,n){return new Yo({...this._def,maxLength:{value:t,message:De.toString(n)}})}length(t,n){return new Yo({...this._def,exactLength:{value:t,message:De.toString(n)}})}nonempty(t){return this.min(1,t)}}Yo.create=(e,t)=>new Yo({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Be.ZodArray,...Xe(t)});function dl(e){if(e instanceof Vt){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=Cs.create(dl(r))}return new Vt({...e._def,shape:()=>t})}else return e instanceof Yo?new Yo({...e._def,type:dl(e.element)}):e instanceof Cs?Cs.create(dl(e.unwrap())):e instanceof gc?gc.create(dl(e.unwrap())):e instanceof Ti?Ti.create(e.items.map(t=>dl(t))):e}class Vt extends rt{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=mt.objectKeys(t);return this._cached={shape:t,keys:n}}_parse(t){if(this._getType(t)!==be.object){const f=this._getOrReturnCtx(t);return Ce(f,{code:he.invalid_type,expected:be.object,received:f.parsedType}),Ze}const{status:r,ctx:o}=this._processInputParams(t),{shape:i,keys:s}=this._getCached(),l=[];if(!(this._def.catchall instanceof Ms&&this._def.unknownKeys==="strip"))for(const f in o.data)s.includes(f)||l.push(f);const u=[];for(const f of s){const p=i[f],m=o.data[f];u.push({key:{status:"valid",value:f},value:p._parse(new Qo(o,m,o.path,f)),alwaysSet:f in o.data})}if(this._def.catchall instanceof Ms){const f=this._def.unknownKeys;if(f==="passthrough")for(const p of l)u.push({key:{status:"valid",value:p},value:{status:"valid",value:o.data[p]}});else if(f==="strict")l.length>0&&(Ce(o,{code:he.unrecognized_keys,keys:l}),r.dirty());else if(f!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const f=this._def.catchall;for(const p of l){const m=o.data[p];u.push({key:{status:"valid",value:p},value:f._parse(new Qo(o,m,o.path,p)),alwaysSet:p in o.data})}}return o.common.async?Promise.resolve().then(async()=>{const f=[];for(const p of u){const m=await p.key;f.push({key:m,value:await p.value,alwaysSet:p.alwaysSet})}return f}).then(f=>zn.mergeObjectSync(r,f)):zn.mergeObjectSync(r,u)}get shape(){return this._def.shape()}strict(t){return De.errToObj,new Vt({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{var o,i,s,l;const u=(s=(i=(o=this._def).errorMap)===null||i===void 0?void 0:i.call(o,n,r).message)!==null&&s!==void 0?s:r.defaultError;return n.code==="unrecognized_keys"?{message:(l=De.errToObj(t).message)!==null&&l!==void 0?l:u}:{message:u}}}:{}})}strip(){return new Vt({...this._def,unknownKeys:"strip"})}passthrough(){return new Vt({...this._def,unknownKeys:"passthrough"})}extend(t){return new Vt({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new Vt({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:Be.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new Vt({...this._def,catchall:t})}pick(t){const n={};return mt.objectKeys(t).forEach(r=>{t[r]&&this.shape[r]&&(n[r]=this.shape[r])}),new Vt({...this._def,shape:()=>n})}omit(t){const n={};return mt.objectKeys(this.shape).forEach(r=>{t[r]||(n[r]=this.shape[r])}),new Vt({...this._def,shape:()=>n})}deepPartial(){return dl(this)}partial(t){const n={};return mt.objectKeys(this.shape).forEach(r=>{const o=this.shape[r];t&&!t[r]?n[r]=o:n[r]=o.optional()}),new Vt({...this._def,shape:()=>n})}required(t){const n={};return mt.objectKeys(this.shape).forEach(r=>{if(t&&!t[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof Cs;)i=i._def.innerType;n[r]=i}}),new Vt({...this._def,shape:()=>n})}keyof(){return rP(mt.objectKeys(this.shape))}}Vt.create=(e,t)=>new Vt({shape:()=>e,unknownKeys:"strip",catchall:Ms.create(),typeName:Be.ZodObject,...Xe(t)});Vt.strictCreate=(e,t)=>new Vt({shape:()=>e,unknownKeys:"strict",catchall:Ms.create(),typeName:Be.ZodObject,...Xe(t)});Vt.lazycreate=(e,t)=>new Vt({shape:e,unknownKeys:"strip",catchall:Ms.create(),typeName:Be.ZodObject,...Xe(t)});class Jp extends rt{_parse(t){const{ctx:n}=this._processInputParams(t),r=this._def.options;function o(i){for(const l of i)if(l.result.status==="valid")return l.result;for(const l of i)if(l.result.status==="dirty")return n.common.issues.push(...l.ctx.common.issues),l.result;const s=i.map(l=>new Go(l.ctx.common.issues));return Ce(n,{code:he.invalid_union,unionErrors:s}),Ze}if(n.common.async)return Promise.all(r.map(async i=>{const s={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:s}),ctx:s}})).then(o);{let i;const s=[];for(const u of r){const f={...n,common:{...n.common,issues:[]},parent:null},p=u._parseSync({data:n.data,path:n.path,parent:f});if(p.status==="valid")return p;p.status==="dirty"&&!i&&(i={result:p,ctx:f}),f.common.issues.length&&s.push(f.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;const l=s.map(u=>new Go(u));return Ce(n,{code:he.invalid_union,unionErrors:l}),Ze}}get options(){return this._def.options}}Jp.create=(e,t)=>new Jp({options:e,typeName:Be.ZodUnion,...Xe(t)});const rp=e=>e instanceof nm?rp(e.schema):e instanceof Pi?rp(e.innerType()):e instanceof rm?[e.value]:e instanceof Da?e.options:e instanceof om?Object.keys(e.enum):e instanceof im?rp(e._def.innerType):e instanceof qp?[void 0]:e instanceof Qp?[null]:null;class qx extends rt{_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.object)return Ce(n,{code:he.invalid_type,expected:be.object,received:n.parsedType}),Ze;const r=this.discriminator,o=n.data[r],i=this.optionsMap.get(o);return i?n.common.async?i._parseAsync({data:n.data,path:n.path,parent:n}):i._parseSync({data:n.data,path:n.path,parent:n}):(Ce(n,{code:he.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),Ze)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){const o=new Map;for(const i of n){const s=rp(i.shape[t]);if(!s)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const l of s){if(o.has(l))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(l)}`);o.set(l,i)}}return new qx({typeName:Be.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:o,...Xe(r)})}}function M1(e,t){const n=ca(e),r=ca(t);if(e===t)return{valid:!0,data:e};if(n===be.object&&r===be.object){const o=mt.objectKeys(t),i=mt.objectKeys(e).filter(l=>o.indexOf(l)!==-1),s={...e,...t};for(const l of i){const u=M1(e[l],t[l]);if(!u.valid)return{valid:!1};s[l]=u.data}return{valid:!0,data:s}}else if(n===be.array&&r===be.array){if(e.length!==t.length)return{valid:!1};const o=[];for(let i=0;i{if(O2(i)||O2(s))return Ze;const l=M1(i.value,s.value);return l.valid?((N2(i)||N2(s))&&n.dirty(),{status:n.value,value:l.data}):(Ce(r,{code:he.invalid_intersection_types}),Ze)};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(([i,s])=>o(i,s)):o(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}em.create=(e,t,n)=>new em({left:e,right:t,typeName:Be.ZodIntersection,...Xe(n)});class Ti extends rt{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.array)return Ce(r,{code:he.invalid_type,expected:be.array,received:r.parsedType}),Ze;if(r.data.lengththis._def.items.length&&(Ce(r,{code:he.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const i=[...r.data].map((s,l)=>{const u=this._def.items[l]||this._def.rest;return u?u._parse(new Qo(r,s,r.path,l)):null}).filter(s=>!!s);return r.common.async?Promise.all(i).then(s=>zn.mergeArray(n,s)):zn.mergeArray(n,i)}get items(){return this._def.items}rest(t){return new Ti({...this._def,rest:t})}}Ti.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ti({items:e,typeName:Be.ZodTuple,rest:null,...Xe(t)})};class tm extends rt{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!==be.object)return Ce(r,{code:he.invalid_type,expected:be.object,received:r.parsedType}),Ze;const o=[],i=this._def.keyType,s=this._def.valueType;for(const l in r.data)o.push({key:i._parse(new Qo(r,l,r.path,l)),value:s._parse(new Qo(r,r.data[l],r.path,l))});return r.common.async?zn.mergeObjectAsync(n,o):zn.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof rt?new tm({keyType:t,valueType:n,typeName:Be.ZodRecord,...Xe(r)}):new tm({keyType:yi.create(),valueType:t,typeName:Be.ZodRecord,...Xe(n)})}}class O1 extends rt{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!==be.map)return Ce(r,{code:he.invalid_type,expected:be.map,received:r.parsedType}),Ze;const o=this._def.keyType,i=this._def.valueType,s=[...r.data.entries()].map(([l,u],f)=>({key:o._parse(new Qo(r,l,r.path,[f,"key"])),value:i._parse(new Qo(r,u,r.path,[f,"value"]))}));if(r.common.async){const l=new Map;return Promise.resolve().then(async()=>{for(const u of s){const f=await u.key,p=await u.value;if(f.status==="aborted"||p.status==="aborted")return Ze;(f.status==="dirty"||p.status==="dirty")&&n.dirty(),l.set(f.value,p.value)}return{status:n.value,value:l}})}else{const l=new Map;for(const u of s){const f=u.key,p=u.value;if(f.status==="aborted"||p.status==="aborted")return Ze;(f.status==="dirty"||p.status==="dirty")&&n.dirty(),l.set(f.value,p.value)}return{status:n.value,value:l}}}}O1.create=(e,t,n)=>new O1({valueType:t,keyType:e,typeName:Be.ZodMap,...Xe(n)});class mc extends rt{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.set)return Ce(r,{code:he.invalid_type,expected:be.set,received:r.parsedType}),Ze;const o=this._def;o.minSize!==null&&r.data.sizeo.maxSize.value&&(Ce(r,{code:he.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());const i=this._def.valueType;function s(u){const f=new Set;for(const p of u){if(p.status==="aborted")return Ze;p.status==="dirty"&&n.dirty(),f.add(p.value)}return{status:n.value,value:f}}const l=[...r.data.values()].map((u,f)=>i._parse(new Qo(r,u,r.path,f)));return r.common.async?Promise.all(l).then(u=>s(u)):s(l)}min(t,n){return new mc({...this._def,minSize:{value:t,message:De.toString(n)}})}max(t,n){return new mc({...this._def,maxSize:{value:t,message:De.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}}mc.create=(e,t)=>new mc({valueType:e,minSize:null,maxSize:null,typeName:Be.ZodSet,...Xe(t)});class Lu extends rt{constructor(){super(...arguments),this.validate=this.implement}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.function)return Ce(n,{code:he.invalid_type,expected:be.function,received:n.parsedType}),Ze;function r(l,u){return $1({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,C1(),Xp].filter(f=>!!f),issueData:{code:he.invalid_arguments,argumentsError:u}})}function o(l,u){return $1({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,C1(),Xp].filter(f=>!!f),issueData:{code:he.invalid_return_type,returnTypeError:u}})}const i={errorMap:n.common.contextualErrorMap},s=n.data;if(this._def.returns instanceof pd){const l=this;return rr(async function(...u){const f=new Go([]),p=await l._def.args.parseAsync(u,i).catch(y=>{throw f.addIssue(r(u,y)),f}),m=await Reflect.apply(s,this,p);return await l._def.returns._def.type.parseAsync(m,i).catch(y=>{throw f.addIssue(o(m,y)),f})})}else{const l=this;return rr(function(...u){const f=l._def.args.safeParse(u,i);if(!f.success)throw new Go([r(u,f.error)]);const p=Reflect.apply(s,this,f.data),m=l._def.returns.safeParse(p,i);if(!m.success)throw new Go([o(p,m.error)]);return m.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new Lu({...this._def,args:Ti.create(t).rest(Dl.create())})}returns(t){return new Lu({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new Lu({args:t||Ti.create([]).rest(Dl.create()),returns:n||Dl.create(),typeName:Be.ZodFunction,...Xe(r)})}}class nm extends rt{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})}}nm.create=(e,t)=>new nm({getter:e,typeName:Be.ZodLazy,...Xe(t)});class rm extends rt{_parse(t){if(t.data!==this._def.value){const n=this._getOrReturnCtx(t);return Ce(n,{received:n.data,code:he.invalid_literal,expected:this._def.value}),Ze}return{status:"valid",value:t.data}}get value(){return this._def.value}}rm.create=(e,t)=>new rm({value:e,typeName:Be.ZodLiteral,...Xe(t)});function rP(e,t){return new Da({values:e,typeName:Be.ZodEnum,...Xe(t)})}class Da extends rt{_parse(t){if(typeof t.data!="string"){const n=this._getOrReturnCtx(t),r=this._def.values;return Ce(n,{expected:mt.joinValues(r),received:n.parsedType,code:he.invalid_type}),Ze}if(this._def.values.indexOf(t.data)===-1){const n=this._getOrReturnCtx(t),r=this._def.values;return Ce(n,{received:n.data,code:he.invalid_enum_value,options:r}),Ze}return rr(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 Da.create(t)}exclude(t){return Da.create(this.options.filter(n=>!t.includes(n)))}}Da.create=rP;class om extends rt{_parse(t){const n=mt.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==be.string&&r.parsedType!==be.number){const o=mt.objectValues(n);return Ce(r,{expected:mt.joinValues(o),received:r.parsedType,code:he.invalid_type}),Ze}if(n.indexOf(t.data)===-1){const o=mt.objectValues(n);return Ce(r,{received:r.data,code:he.invalid_enum_value,options:o}),Ze}return rr(t.data)}get enum(){return this._def.values}}om.create=(e,t)=>new om({values:e,typeName:Be.ZodNativeEnum,...Xe(t)});class pd extends rt{unwrap(){return this._def.type}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.promise&&n.common.async===!1)return Ce(n,{code:he.invalid_type,expected:be.promise,received:n.parsedType}),Ze;const r=n.parsedType===be.promise?n.data:Promise.resolve(n.data);return rr(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}}pd.create=(e,t)=>new pd({type:e,typeName:Be.ZodPromise,...Xe(t)});class Pi extends rt{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Be.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:n,ctx:r}=this._processInputParams(t),o=this._def.effect||null,i={addIssue:s=>{Ce(r,s),s.fatal?n.abort():n.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),o.type==="preprocess"){const s=o.transform(r.data,i);return r.common.issues.length?{status:"dirty",value:r.data}:r.common.async?Promise.resolve(s).then(l=>this._def.schema._parseAsync({data:l,path:r.path,parent:r})):this._def.schema._parseSync({data:s,path:r.path,parent:r})}if(o.type==="refinement"){const s=l=>{const u=o.refinement(l,i);if(r.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return l};if(r.common.async===!1){const l=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return l.status==="aborted"?Ze:(l.status==="dirty"&&n.dirty(),s(l.value),{status:n.value,value:l.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(l=>l.status==="aborted"?Ze:(l.status==="dirty"&&n.dirty(),s(l.value).then(()=>({status:n.value,value:l.value}))))}if(o.type==="transform")if(r.common.async===!1){const s=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Zp(s))return s;const l=o.transform(s.value,i);if(l instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:l}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(s=>Zp(s)?Promise.resolve(o.transform(s.value,i)).then(l=>({status:n.value,value:l})):s);mt.assertNever(o)}}Pi.create=(e,t,n)=>new Pi({schema:e,typeName:Be.ZodEffects,effect:t,...Xe(n)});Pi.createWithPreprocess=(e,t,n)=>new Pi({schema:t,effect:{type:"preprocess",transform:e},typeName:Be.ZodEffects,...Xe(n)});class Cs extends rt{_parse(t){return this._getType(t)===be.undefined?rr(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Cs.create=(e,t)=>new Cs({innerType:e,typeName:Be.ZodOptional,...Xe(t)});class gc extends rt{_parse(t){return this._getType(t)===be.null?rr(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}gc.create=(e,t)=>new gc({innerType:e,typeName:Be.ZodNullable,...Xe(t)});class im extends rt{_parse(t){const{ctx:n}=this._processInputParams(t);let r=n.data;return n.parsedType===be.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}im.create=(e,t)=>new im({innerType:e,typeName:Be.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Xe(t)});class N1 extends rt{_parse(t){const{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return R1(o)?o.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Go(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Go(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}N1.create=(e,t)=>new N1({innerType:e,typeName:Be.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Xe(t)});class D1 extends rt{_parse(t){if(this._getType(t)!==be.nan){const r=this._getOrReturnCtx(t);return Ce(r,{code:he.invalid_type,expected:be.nan,received:r.parsedType}),Ze}return{status:"valid",value:t.data}}}D1.create=e=>new D1({typeName:Be.ZodNaN,...Xe(e)});class hX extends rt{_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 ug extends rt{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?Ze:i.status==="dirty"?(n.dirty(),tX(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{const o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?Ze:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(t,n){return new ug({in:t,out:n,typeName:Be.ZodPipeline})}}class I1 extends rt{_parse(t){const n=this._def.innerType._parse(t);return Zp(n)&&(n.value=Object.freeze(n.value)),n}}I1.create=(e,t)=>new I1({innerType:e,typeName:Be.ZodReadonly,...Xe(t)});Vt.lazycreate;var Be;(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",e.ZodReadonly="ZodReadonly"})(Be||(Be={}));const fu=yi.create;hc.create;D1.create;pc.create;const hu=k1.create;hd.create;T1.create;qp.create;Qp.create;P1.create;Dl.create;Ms.create;A1.create;Yo.create;const pX=Vt.create;Vt.strictCreate;Jp.create;qx.create;em.create;Ti.create;tm.create;O1.create;mc.create;Lu.create;nm.create;rm.create;Da.create;om.create;pd.create;Pi.create;Cs.create;gc.create;Pi.createWithPreprocess;ug.create;const L1="horizontal",mX=["horizontal","vertical"],oP=d.forwardRef((e,t)=>{const{decorative:n,orientation:r=L1,...o}=e,i=iP(r)?r:L1,l=n?{role:"none"}:{"aria-orientation":i==="vertical"?i:void 0,role:"separator"};return d.createElement(Ae.div,Y({"data-orientation":i},l,o,{ref:t}))});oP.propTypes={orientation(e,t,n){const r=e[t],o=String(r);return r&&!iP(r)?new Error(gX(o,n)):null}};function gX(e,t){return`Invalid prop \`orientation\` of value \`${e}\` supplied to \`${t}\`, expected one of: + - horizontal + - vertical + +Defaulting to \`${L1}\`.`}function iP(e){return mX.includes(e)}const sP=oP,gn=d.forwardRef(({className:e,orientation:t="horizontal",decorative:n=!0,...r},o)=>v.jsx(sP,{ref:o,decorative:n,orientation:t,className:_e("shrink-0 bg-border",t==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",e),...r}));gn.displayName=sP.displayName;const vX=d.forwardRef((e,t)=>d.createElement(Ae.label,Y({},e,{ref:t,onMouseDown:n=>{var r;(r=e.onMouseDown)===null||r===void 0||r.call(e,n),!n.defaultPrevented&&n.detail>1&&n.preventDefault()}}))),aP=vX,yX=Dm("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),Qx=d.forwardRef(({className:e,disabled:t,...n},r)=>v.jsx(aP,{ref:r,className:_e(yX(),e,t?"opacity-50":"","select-none"),...n}));Qx.displayName=aP.displayName;const wX=OY,lP=d.createContext({}),al=({...e})=>v.jsx(lP.Provider,{value:{name:e.name},children:v.jsx(LY,{...e})}),dg=()=>{const e=d.useContext(lP),t=d.useContext(cP),{getFieldState:n,formState:r}=cg(),o=n(e.name,r);if(!e)throw new Error("useFormField should be used within ");const{id:i}=t;return{id:i,name:e.name,formItemId:`${i}-form-item`,formDescriptionId:`${i}-form-item-description`,formMessageId:`${i}-form-item-message`,...o}},cP=d.createContext({}),oa=d.forwardRef(({className:e,...t},n)=>{const r=d.useId();return v.jsx(cP.Provider,{value:{id:r},children:v.jsx("div",{ref:n,className:_e("space-y-2",e),...t})})});oa.displayName="FormItem";const ia=d.forwardRef(({className:e,...t},n)=>{const{error:r,formItemId:o}=dg();return v.jsx(Qx,{ref:n,className:_e(r&&"text-destructive","text-sm",e),htmlFor:o,...t})});ia.displayName="FormLabel";const sa=d.forwardRef(({...e},t)=>{const{error:n,formItemId:r,formDescriptionId:o,formMessageId:i}=dg();return v.jsx(Zo,{ref:t,id:r,"aria-describedby":n?`${o} ${i}`:`${o}`,"aria-invalid":!!n,...e})});sa.displayName="FormControl";const aa=d.forwardRef(({className:e,...t},n)=>{const{formDescriptionId:r}=dg();return v.jsx("p",{ref:n,id:r,className:_e("text-[0.8rem] text-muted-foreground",e),...t})});aa.displayName="FormDescription";const xX=d.forwardRef(({className:e,children:t,...n},r)=>{const{error:o,formMessageId:i}=dg(),s=o?String(o==null?void 0:o.message):t;return s?v.jsx("p",{ref:r,id:i,className:_e("text-[0.8rem] font-medium text-destructive",e),...n,children:s}):null});xX.displayName="FormMessage";const uP="Switch",[bX,_te]=Mn(uP),[SX,_X]=bX(uP),EX=d.forwardRef((e,t)=>{const{__scopeSwitch:n,name:r,checked:o,defaultChecked:i,required:s,disabled:l,value:u="on",onCheckedChange:f,...p}=e,[m,g]=d.useState(null),y=Ue(t,b=>g(b)),x=d.useRef(!1),S=m?!!m.closest("form"):!0,[E=!1,_]=Zr({prop:o,defaultProp:i,onChange:f});return d.createElement(SX,{scope:n,checked:E,disabled:l},d.createElement(Ae.button,Y({type:"button",role:"switch","aria-checked":E,"aria-required":s,"data-state":dP(E),"data-disabled":l?"":void 0,disabled:l,value:u},p,{ref:y,onClick:ue(e.onClick,b=>{_(C=>!C),S&&(x.current=b.isPropagationStopped(),x.current||b.stopPropagation())})})),S&&d.createElement(RX,{control:m,bubbles:!x.current,name:r,value:u,checked:E,required:s,disabled:l,style:{transform:"translateX(-100%)"}}))}),CX="SwitchThumb",$X=d.forwardRef((e,t)=>{const{__scopeSwitch:n,...r}=e,o=_X(CX,n);return d.createElement(Ae.span,Y({"data-state":dP(o.checked),"data-disabled":o.disabled?"":void 0},r,{ref:t}))}),RX=e=>{const{control:t,checked:n,bubbles:r=!0,...o}=e,i=d.useRef(null),s=Ux(n),l=yx(t);return d.useEffect(()=>{const u=i.current,f=window.HTMLInputElement.prototype,m=Object.getOwnPropertyDescriptor(f,"checked").set;if(s!==n&&m){const g=new Event("click",{bubbles:r});m.call(u,n),u.dispatchEvent(g)}},[s,n,r]),d.createElement("input",Y({type:"checkbox","aria-hidden":!0,defaultChecked:n},o,{tabIndex:-1,ref:i,style:{...e.style,...l,position:"absolute",pointerEvents:"none",opacity:0,margin:0}}))};function dP(e){return e?"checked":"unchecked"}const fP=EX,kX=$X,co=d.forwardRef(({className:e,...t},n)=>v.jsx(fP,{className:_e("peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",e),tabIndex:-1,...t,ref:n,children:v.jsx(kX,{className:_e("pointer-events-none block h-4 w-4 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0")})}));co.displayName=fP.displayName;const TX="AlertDialog",[PX,Ete]=Mn(TX,[hT]),zs=hT(),AX=e=>{const{__scopeAlertDialog:t,...n}=e,r=zs(t);return d.createElement(Cx,Y({},r,n,{modal:!0}))},MX=e=>{const{__scopeAlertDialog:t,...n}=e,r=zs(t);return d.createElement($x,Y({},r,n))},OX=d.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=zs(n);return d.createElement(zd,Y({},o,r,{ref:t}))}),hP="AlertDialogContent",[NX,DX]=PX(hP),IX=d.forwardRef((e,t)=>{const{__scopeAlertDialog:n,children:r,...o}=e,i=zs(n),s=d.useRef(null),l=Ue(t,s),u=d.useRef(null);return d.createElement(hW,{contentName:hP,titleName:LX,docsSlug:"alert-dialog"},d.createElement(NX,{scope:n,cancelRef:u},d.createElement(Bd,Y({role:"alertdialog"},i,o,{ref:l,onOpenAutoFocus:ue(o.onOpenAutoFocus,f=>{var p;f.preventDefault(),(p=u.current)===null||p===void 0||p.focus({preventScroll:!0})}),onPointerDownOutside:f=>f.preventDefault(),onInteractOutside:f=>f.preventDefault()}),d.createElement(lx,null,r),!1)))}),LX="AlertDialogTitle",FX=d.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=zs(n);return d.createElement(Ud,Y({},o,r,{ref:t}))}),jX=d.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=zs(n);return d.createElement(Vd,Y({},o,r,{ref:t}))}),zX=d.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=zs(n);return d.createElement(Rx,Y({},o,r,{ref:t}))}),BX="AlertDialogCancel",UX=d.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,{cancelRef:o}=DX(BX,n),i=zs(n),s=Ue(t,o);return d.createElement(Rx,Y({},i,r,{ref:s}))}),VX=AX,WX=MX,pP=OX,mP=IX,gP=zX,vP=UX,yP=FX,wP=jX,HX=VX,KX=WX,xP=d.forwardRef(({className:e,...t},n)=>v.jsx(pP,{className:_e("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t,ref:n}));xP.displayName=pP.displayName;const bP=d.forwardRef(({className:e,...t},n)=>v.jsxs(KX,{children:[v.jsx(xP,{}),v.jsx(mP,{ref:n,className:_e("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",e),...t})]}));bP.displayName=mP.displayName;const SP=({className:e,...t})=>v.jsx("div",{className:_e("flex flex-col space-y-2 text-center sm:text-left",e),...t});SP.displayName="AlertDialogHeader";const GX=d.forwardRef(({className:e,...t},n)=>v.jsx(yP,{ref:n,className:_e("text-lg font-semibold",e),...t}));GX.displayName=yP.displayName;const YX=d.forwardRef(({className:e,...t},n)=>v.jsx(wP,{ref:n,className:_e("text-sm text-muted-foreground",e),...t}));YX.displayName=wP.displayName;const XX=d.forwardRef(({className:e,...t},n)=>v.jsx(gP,{ref:n,className:_e(_x(),e),...t}));XX.displayName=gP.displayName;const ZX=d.forwardRef(({className:e,...t},n)=>v.jsx(vP,{ref:n,className:_e(_x({variant:"outline"}),"mt-2 sm:mt-0",e),...t}));ZX.displayName=vP.displayName;const qX=pX({enableFileManager:hu(),inputDirectory:fu(),outputDirectory:fu(),enableDownloadMask:hu(),enableManualInpainting:hu(),enableUploadMask:hu(),enableAutoExtractPrompt:hu(),removeBGModel:fu(),realesrganModel:fu(),interactiveSegModel:fu()}),_P="General",F1="Model",EP="Plugins",QX=[F1,_P,EP];function JX(){const[e,t]=eT(!1),[n,r]=d.useState(F1),[o,i,s,l,u,f]=bt(M=>[M.updateAppState,M.settings,M.updateSettings,M.fileManagerState,M.setModel,M.setServerConfig]),{toast:p}=Id(),[m,g]=d.useState(i.model),[y,x]=d.useState([]),S=y.length>0;d.useEffect(()=>{g(i.model)},[i.model]);const{data:E,status:_,refetch:b}=ML({queryKey:["serverConfig"],queryFn:yk}),C=YY({resolver:JY(qX),defaultValues:{enableDownloadMask:i.enableDownloadMask,enableManualInpainting:i.enableManualInpainting,enableUploadMask:i.enableUploadMask,enableAutoExtractPrompt:i.enableAutoExtractPrompt,inputDirectory:l.inputDirectory,outputDirectory:l.outputDirectory,removeBGModel:E==null?void 0:E.removeBGModel,realesrganModel:E==null?void 0:E.realesrganModel,interactiveSegModel:E==null?void 0:E.interactiveSegModel}});d.useEffect(()=>{E&&(f(E),C.setValue("removeBGModel",E.removeBGModel),C.setValue("realesrganModel",E.realesrganModel),C.setValue("interactiveSegModel",E.interactiveSegModel))},[C,E]);async function R(M){s({enableDownloadMask:M.enableDownloadMask,enableManualInpainting:M.enableManualInpainting,enableUploadMask:M.enableUploadMask,enableAutoExtractPrompt:M.enableAutoExtractPrompt});const ee=m.name!==i.model.name,H=(E==null?void 0:E.removeBGModel)!==M.removeBGModel&&A,X=(E==null?void 0:E.realesrganModel)!==M.realesrganModel&&D,W=(E==null?void 0:E.interactiveSegModel)!==M.interactiveSegModel&&B;if(ee||H||X||W){const pe=[];if(ee&&pe.push(`Switching model from ${i.model.name} to ${m.name}`),H&&pe.push(`Switching RemoveBG model from ${E==null?void 0:E.removeBGModel} to ${M.removeBGModel}`),X&&pe.push(`Switching RealESRGAN model from ${E==null?void 0:E.realesrganModel} to ${M.realesrganModel}`),W&&pe.push(`Switching ${Ao.InteractiveSeg} model from ${E==null?void 0:E.interactiveSegModel} to ${M.interactiveSegModel}`),x(pe),o({disableShortCuts:!0}),ee)try{const $e=await Bj(m.name);p({title:`Switch to ${$e.name} success`}),u(m)}catch($e){p({variant:"destructive",title:`Switch to ${m.name} failed: ${$e}`}),g(i.model)}if(H)try{const $e=await y0(Ao.RemoveBG,M.removeBGModel);if($e.status!==200)throw new Error($e.statusText)}catch($e){p({variant:"destructive",title:`Switch RemoveBG model to ${M.removeBGModel} failed: ${$e}`})}if(X)try{const $e=await y0(Ao.RealESRGAN,M.realesrganModel);if($e.status!==200)throw new Error($e.statusText)}catch($e){p({variant:"destructive",title:`Switch RealESRGAN model to ${M.realesrganModel} failed: ${$e}`})}if(W)try{const $e=await y0(Ao.InteractiveSeg,M.interactiveSegModel);if($e.status!==200)throw new Error($e.statusText)}catch($e){p({variant:"destructive",title:`Switch ${Ao.InteractiveSeg} model to ${M.interactiveSegModel} failed: ${$e}`})}x([]),o({disableShortCuts:!1}),b()}}if(Zn("s",()=>{t(),e&&R(C.getValues())},[e,C,m,E]),_!=="success")return v.jsx(v.Fragment,{});const P=E.modelInfos,O=E.plugins,A=O.some(M=>M.name===Ao.RemoveBG),D=O.some(M=>M.name===Ao.RealESRGAN),B=O.some(M=>M.name===Ao.InteractiveSeg);function V(M){t(),M||R(C.getValues())}function J(M){g(M)}function G(M){return P?P.filter(ee=>M.includes(ee.model_type)).map(ee=>v.jsxs("div",{onClick:()=>J(ee),className:"px-2",children:[v.jsx("div",{className:_e([ee.name===m.name?"bg-muted":"hover:bg-muted","rounded-md px-2 py-2","cursor-default"]),children:v.jsx("div",{className:"text-base",children:ee.name})}),v.jsx(gn,{className:"my-1"})]},ee.name)):v.jsx("div",{children:"Please download model first"})}function se(){let M=fs;for(let ee of P)if(m.name===ee.name){M=ee.model_type,M===sC&&(M=ch),M===aC&&(M=uh);break}return v.jsxs("div",{className:"flex flex-col gap-4 w-[510px]",children:[v.jsxs("div",{className:"flex flex-col gap-4 rounded-md",children:[v.jsx("div",{className:"font-medium",children:"Current Model"}),v.jsx("div",{children:m.name})]}),v.jsx(gn,{}),v.jsxs("div",{className:"space-y-4 rounded-md",children:[v.jsx("div",{className:"flex gap-1 items-center justify-start",children:v.jsx("div",{className:"font-medium",children:"Available models"})}),v.jsxs(l3,{defaultValue:M,children:[v.jsxs(Bx,{children:[v.jsx(pa,{value:fs,children:"Inpaint"}),v.jsx(pa,{value:ch,children:"Stable Diffusion"}),v.jsx(pa,{value:uh,children:"Stable Diffusion Inpaint"}),v.jsx(pa,{value:f0,children:"Other Diffusion"})]}),v.jsxs(lg,{className:"h-[240px] w-full mt-2 outline-none border rounded-lg",children:[v.jsx(Su,{value:fs,children:G([fs])}),v.jsx(Su,{value:ch,children:G([ch,sC])}),v.jsx(Su,{value:uh,children:G([uh,aC])}),v.jsx(Su,{value:f0,children:G([f0])})]})]})]})]})}function U(){return v.jsxs("div",{className:"space-y-4 w-[510px]",children:[v.jsx(al,{control:C.control,name:"enableManualInpainting",render:({field:M})=>v.jsxs(oa,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(ia,{children:"Enable manual inpainting"}),v.jsx(aa,{children:"For erase model, click a button to trigger inpainting after draw mask."})]}),v.jsx(sa,{children:v.jsx(co,{checked:M.value,onCheckedChange:M.onChange})})]})}),v.jsx(gn,{}),v.jsx(al,{control:C.control,name:"enableDownloadMask",render:({field:M})=>v.jsxs(oa,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(ia,{children:"Enable download mask"}),v.jsx(aa,{children:"Also download the mask after save the inpainting result."})]}),v.jsx(sa,{children:v.jsx(co,{checked:M.value,onCheckedChange:M.onChange})})]})}),v.jsx(gn,{}),v.jsx(al,{control:C.control,name:"enableAutoExtractPrompt",render:({field:M})=>v.jsxs(oa,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(ia,{children:"Enable auto extract prompt"}),v.jsx(aa,{children:"Automatically extract prompt/negativate prompt from the image meta."})]}),v.jsx(sa,{children:v.jsx(co,{checked:M.value,onCheckedChange:M.onChange})})]})})]})}function ne(){return v.jsxs("div",{className:"space-y-4 w-[510px]",children:[v.jsx(al,{control:C.control,name:"removeBGModel",render:({field:M})=>v.jsxs(oa,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(ia,{children:"Remove Background"}),v.jsx(aa,{children:"Remove background model"})]}),v.jsxs(Uo,{onValueChange:M.onChange,defaultValue:M.value,disabled:!A,children:[v.jsx(sa,{children:v.jsx(go,{className:"w-auto",children:v.jsx(Vo,{placeholder:"Select removebg model"})})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:E==null?void 0:E.removeBGModels.map(ee=>v.jsx(yo,{value:ee,children:ee},ee))})})]})]})}),v.jsx(gn,{}),v.jsx(al,{control:C.control,name:"realesrganModel",render:({field:M})=>v.jsxs(oa,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(ia,{children:"RealESRGAN"}),v.jsx(aa,{children:"RealESRGAN Model"})]}),v.jsxs(Uo,{onValueChange:M.onChange,defaultValue:M.value,disabled:!D,children:[v.jsx(sa,{children:v.jsx(go,{className:"w-auto",children:v.jsx(Vo,{placeholder:"Select RealESRGAN model"})})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:E==null?void 0:E.realesrganModels.map(ee=>v.jsx(yo,{value:ee,children:ee},ee))})})]})]})}),v.jsx(gn,{}),v.jsx(al,{control:C.control,name:"interactiveSegModel",render:({field:M})=>v.jsxs(oa,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(ia,{children:"Interactive Segmentation"}),v.jsx(aa,{children:"Interactive Segmentation Model"})]}),v.jsxs(Uo,{onValueChange:M.onChange,defaultValue:M.value,disabled:!B,children:[v.jsx(sa,{children:v.jsx(go,{className:"w-auto",children:v.jsx(Vo,{placeholder:"Select interactive segmentation model"})})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:E==null?void 0:E.interactiveSegModels.map(ee=>v.jsx(yo,{value:ee,children:ee},ee))})})]})]})})]})}return v.jsxs(v.Fragment,{children:[v.jsx(HX,{open:S,children:v.jsx(bP,{children:v.jsx(SP,{children:v.jsxs("div",{className:"flex flex-col justify-center items-center gap-4",children:[v.jsxs("div",{role:"status",children:[v.jsxs("svg",{"aria-hidden":"true",className:"w-8 h-8 text-gray-200 animate-spin dark:text-gray-600 fill-primary",viewBox:"0 0 100 101",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[v.jsx("path",{d:"M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z",fill:"currentColor"}),v.jsx("path",{d:"M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z",fill:"currentFill"})]}),v.jsx("span",{className:"sr-only",children:"Loading..."})]}),y?v.jsx("div",{className:"flex flex-col",children:y.map((M,ee)=>v.jsx("div",{children:M},ee))}):v.jsx(v.Fragment,{})]})})})}),v.jsxs(eg,{open:e,onOpenChange:V,children:[v.jsx(kx,{asChild:!0,children:v.jsx(yn,{tooltip:"Settings",children:v.jsx(sV,{})})}),v.jsxs(Wd,{className:"max-w-3xl h-[600px]",onOpenAutoFocus:M=>M.preventDefault(),children:[v.jsx(Hd,{children:"Settings"}),v.jsx(gn,{}),v.jsxs("div",{className:"flex flex-row space-x-8 h-full",children:[v.jsx("div",{className:"flex flex-col space-y-1",children:QX.map(M=>v.jsx(wn,{variant:"ghost",onClick:()=>r(M),className:_e(n===M?"bg-muted ":"hover:bg-muted","justify-start"),children:M},M))}),v.jsx(gn,{orientation:"vertical"}),v.jsx(wX,{...C,children:v.jsx("div",{className:"flex w-full justify-center",children:v.jsxs("form",{onSubmit:C.handleSubmit(R),children:[n===F1?se():v.jsx(v.Fragment,{}),n===_P?U():v.jsx(v.Fragment,{}),n===EP?ne():v.jsx(v.Fragment,{}),v.jsx("div",{className:"absolute right-10 bottom-6",children:v.jsx(wn,{onClick:()=>V(!1),children:"Ok"})})]})})})]})]})]})]})}const eZ="/assets/kofi_button_black-XI_Dr2zg.png";function tZ(){return v.jsxs(eg,{children:[v.jsx(kx,{asChild:!0,children:v.jsx(yn,{tooltip:"Buy me a coffee",children:v.jsx(XU,{})})}),v.jsxs(Wd,{children:[v.jsx(Hd,{children:"Buy me a coffee"}),v.jsx(wT,{className:"mb-8",children:"Hi, if you found my project is useful, please conside buy me a coffee to support my work. Thanks!"}),v.jsx("div",{className:"w-full flex items-center justify-center",children:v.jsx("a",{href:"https://ko-fi.com/Z8Z1CZJGY",target:"_blank",rel:"noreferrer",children:v.jsx("img",{src:eZ,className:"h-[32px]"})})})]})]})}const nZ=()=>{const[e,t,n,r,o,i,s,l,u,f,p,m,g,y]=bt(O=>[O.file,O.customMask,O.isInpainting,O.serverConfig,O.runMannually(),O.settings.enableUploadMask,O.settings.model,O.setFile,O.setCustomFile,O.runInpainting,O.showPrevMask,O.hidePrevMask,O.imageHeight,O.imageWidth]),{toast:x}=Id(),[S,E]=Px(t),[_,b]=d.useState(!1),C=()=>{f()},R=()=>{p()},P=()=>{m()};return v.jsxs("header",{className:"h-[60px] px-6 py-4 absolute top-[0] flex justify-between items-center w-full z-20 border-b backdrop-filter backdrop-blur-md bg-background/70",children:[v.jsxs("div",{className:"flex items-center gap-1",children:[r.enableFileManager?v.jsx(PY,{photoWidth:512,onPhotoClick:async(O,A)=>{try{const D=await Vj(O,A);l(D)}catch(D){x({variant:"destructive",description:D.message?D.message:D.toString()});return}}}):v.jsx(v.Fragment,{}),v.jsx(f1,{disabled:n,tooltip:"Upload image",onFileUpload:O=>{l(O)},children:v.jsx(tV,{})}),v.jsxs("div",{className:_e(["flex items-center gap-1",e&&i?"visible":"hidden"]),children:[v.jsx(f1,{disabled:n,tooltip:"Upload custom mask",onFileUpload:async O=>{let A=null;try{A=await gF(O)}catch(D){x({variant:"destructive",description:D.message?D.message:D.toString()});return}if(A.naturalHeight!==g||A.naturalWidth!==y){x({variant:"destructive",description:`The size of the mask must same as image: ${y}x${g}`});return}u(O),o||f()},children:v.jsx(Jk,{})}),t?v.jsxs(KW,{open:_,children:[v.jsx(GW,{className:"btn-primary side-panel-trigger",onMouseEnter:()=>b(!0),onMouseLeave:()=>b(!1),style:{visibility:t?"visible":"hidden",outline:"none"},onClick:()=>{},children:v.jsx(yn,{tooltip:"Run custom mask",children:v.jsx(uz,{})})}),v.jsx(NT,{children:E?v.jsx("img",{src:S.src,alt:"Custom mask"}):v.jsx(v.Fragment,{})})]}):v.jsx(v.Fragment,{})]}),e&&!s.need_prompt?v.jsx(yn,{disabled:n,tooltip:"Rerun previous mask",onClick:C,onMouseEnter:R,onMouseLeave:P,children:v.jsx(iV,{})}):v.jsx(v.Fragment,{})]}),s.need_prompt?v.jsx(yH,{}):v.jsx(v.Fragment,{}),v.jsxs("div",{className:"flex gap-1",children:[v.jsx(tZ,{}),v.jsx(MW,{}),r.disableModelSwitch?v.jsx(v.Fragment,{}):v.jsx(JX,{})]})]})};var Wr=function(e,t){return Number(e.toFixed(t))},rZ=function(e,t){return typeof e=="number"?e:t},Nt=function(e,t,n){n&&typeof n=="function"&&n(e,t)},oZ=function(e){return-Math.cos(e*Math.PI)/2+.5},iZ=function(e){return e},sZ=function(e){return e*e},aZ=function(e){return e*(2-e)},lZ=function(e){return e<.5?2*e*e:-1+(4-2*e)*e},cZ=function(e){return e*e*e},uZ=function(e){return--e*e*e+1},dZ=function(e){return e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1},fZ=function(e){return e*e*e*e},hZ=function(e){return 1- --e*e*e*e},pZ=function(e){return e<.5?8*e*e*e*e:1-8*--e*e*e*e},mZ=function(e){return e*e*e*e*e},gZ=function(e){return 1+--e*e*e*e*e},vZ=function(e){return e<.5?16*e*e*e*e*e:1+16*--e*e*e*e*e},CP={easeOut:oZ,linear:iZ,easeInQuad:sZ,easeOutQuad:aZ,easeInOutQuad:lZ,easeInCubic:cZ,easeOutCubic:uZ,easeInOutCubic:dZ,easeInQuart:fZ,easeOutQuart:hZ,easeInOutQuart:pZ,easeInQuint:mZ,easeOutQuint:gZ,easeInOutQuint:vZ},$P=function(e){typeof e=="number"&&cancelAnimationFrame(e)},jo=function(e){e.mounted&&($P(e.animation),e.animate=!1,e.animation=null,e.velocity=null)};function RP(e,t,n,r){if(e.mounted){var o=new Date().getTime(),i=1;jo(e),e.animation=function(){if(!e.mounted)return $P(e.animation);var s=new Date().getTime()-o,l=s/n,u=CP[t],f=u(l);s>=n?(r(i),e.animation=null):e.animation&&(r(f),requestAnimationFrame(e.animation))},requestAnimationFrame(e.animation)}}function yZ(e){var t=e.scale,n=e.positionX,r=e.positionY;return!(Number.isNaN(t)||Number.isNaN(n)||Number.isNaN(r))}function Bs(e,t,n,r){var o=yZ(t);if(!(!e.mounted||!o)){var i=e.setTransformState,s=e.transformState,l=s.scale,u=s.positionX,f=s.positionY,p=t.scale-l,m=t.positionX-u,g=t.positionY-f;n===0?i(t.scale,t.positionX,t.positionY):RP(e,r,n,function(y){var x=l+p*y,S=u+m*y,E=f+g*y;i(x,S,E)})}}function wZ(e,t,n){var r=e.offsetWidth,o=e.offsetHeight,i=t.offsetWidth,s=t.offsetHeight,l=i*n,u=s*n,f=r-l,p=o-u;return{wrapperWidth:r,wrapperHeight:o,newContentWidth:l,newDiffWidth:f,newContentHeight:u,newDiffHeight:p}}var xZ=function(e,t,n,r,o,i,s){var l=e>t?n*(s?1:.5):0,u=r>o?i*(s?1:.5):0,f=e-t-l,p=l,m=r-o-u,g=u;return{minPositionX:f,maxPositionX:p,minPositionY:m,maxPositionY:g}},Jx=function(e,t){var n=e.wrapperComponent,r=e.contentComponent,o=e.setup.centerZoomedOut;if(!n||!r)throw new Error("Components are not mounted");var i=wZ(n,r,t),s=i.wrapperWidth,l=i.wrapperHeight,u=i.newContentWidth,f=i.newDiffWidth,p=i.newContentHeight,m=i.newDiffHeight,g=xZ(s,u,f,l,p,m,!!o);return g},j1=function(e,t,n,r){return r?en?Wr(n,2):Wr(e,2):Wr(e,2)},vc=function(e,t){var n=Jx(e,t);return e.bounds=n,n};function fg(e,t,n,r,o,i,s){var l=n.minPositionX,u=n.minPositionY,f=n.maxPositionX,p=n.maxPositionY,m=0,g=0;s&&(m=o,g=i);var y=j1(e,l-m,f+m,r),x=j1(t,u-g,p+g,r);return{x:y,y:x}}function hg(e,t,n,r,o,i){var s=e.transformState,l=s.scale,u=s.positionX,f=s.positionY,p=r-l;if(typeof t!="number"||typeof n!="number")return console.error("Mouse X and Y position were not provided!"),{x:u,y:f};var m=u-t*p,g=f-n*p,y=fg(m,g,o,i,0,0,null);return y}function Xd(e,t,n,r,o){var i=o?r:0,s=t-i;return!Number.isNaN(n)&&e>=n?n:!Number.isNaN(t)&&e<=s?s:e}var I2=function(e,t){var n=e.setup.panning.excluded,r=e.isInitialized,o=e.wrapperComponent,i=t.target,s=o==null?void 0:o.contains(i),l=r&&i&&s;if(!l)return!1;var u=pg(i,n);return!u},L2=function(e){var t=e.isInitialized,n=e.isPanning,r=e.setup,o=r.panning.disabled,i=t&&n&&!o;return!!i},bZ=function(e,t){var n=e.transformState,r=n.positionX,o=n.positionY;e.isPanning=!0;var i=t.clientX,s=t.clientY;e.startCoords={x:i-r,y:s-o}},SZ=function(e,t){var n=t.touches,r=e.transformState,o=r.positionX,i=r.positionY;e.isPanning=!0;var s=n.length===1;if(s){var l=n[0].clientX,u=n[0].clientY;e.startCoords={x:l-o,y:u-i}}};function _Z(e){var t=e.transformState,n=t.positionX,r=t.positionY,o=t.scale,i=e.setup,s=i.disabled,l=i.limitToBounds,u=i.centerZoomedOut,f=e.wrapperComponent;if(!(s||!f||!e.bounds)){var p=e.bounds,m=p.maxPositionX,g=p.minPositionX,y=p.maxPositionY,x=p.minPositionY,S=n>m||ny||rm?f.offsetWidth:e.setup.minPositionX||0,b=r>y?f.offsetHeight:e.setup.minPositionY||0,C=hg(e,_,b,o,e.bounds,l||u),R=C.x,P=C.y;return{scale:o,positionX:S?R:n,positionY:E?P:r}}}function EZ(e,t,n,r,o){var i=e.setup.limitToBounds,s=e.wrapperComponent,l=e.bounds,u=e.transformState,f=u.scale,p=u.positionX,m=u.positionY;if(!(s===null||l===null||t===p&&n===m)){var g=fg(t,n,l,i,r,o,s),y=g.x,x=g.y;e.setTransformState(f,y,x)}}var CZ=function(e,t,n){var r=e.startCoords,o=e.transformState,i=e.setup.panning,s=i.lockAxisX,l=i.lockAxisY,u=o.positionX,f=o.positionY;if(!r)return{x:u,y:f};var p=t-r.x,m=n-r.y,g=s?u:p,y=l?f:m;return{x:g,y}},sm=function(e,t){var n=e.setup,r=e.transformState,o=r.scale,i=n.minScale,s=n.disablePadding;return t>0&&o>=i&&!s?t:0},$Z=function(e){var t=e.mounted,n=e.setup,r=n.disabled,o=n.velocityAnimation,i=e.transformState.scale,s=o.disabled,l=!s||i>1||!r||t;return!!l},RZ=function(e){var t=e.mounted,n=e.velocity,r=e.bounds,o=e.setup,i=o.disabled,s=o.velocityAnimation,l=e.transformState.scale,u=s.disabled,f=!u||l>1||!i||t;return!(!f||!n||!r)};function kZ(e,t){var n=e.setup.velocityAnimation,r=n.equalToMove,o=n.animationTime,i=n.sensitivity;return r?o*t*i:o}function F2(e,t,n,r,o,i,s,l,u,f){if(o){if(t>s&&n>s){var p=s+(e-s)*f;return p>u?u:pi?i:p}}return r?t:j1(e,i,s,o)}function TZ(e,t){var n=1;return t?Math.min(n,e.offsetWidth/window.innerWidth):n}function PZ(e,t){var n=$Z(e);if(n){var r=e.lastMousePosition,o=e.velocityTime,i=e.setup,s=e.wrapperComponent,l=i.velocityAnimation.equalToMove,u=Date.now();if(r&&o&&s){var f=TZ(s,l),p=t.x-r.x,m=t.y-r.y,g=p/f,y=m/f,x=u-o,S=p*p+m*m,E=Math.sqrt(S)/x;e.velocity={velocityX:g,velocityY:y,total:E}}e.lastMousePosition=t,e.velocityTime=u}}function AZ(e){var t=e.velocity,n=e.bounds,r=e.setup,o=e.wrapperComponent,i=RZ(e);if(!(!i||!t||!n||!o)){var s=t.velocityX,l=t.velocityY,u=t.total,f=n.maxPositionX,p=n.minPositionX,m=n.maxPositionY,g=n.minPositionY,y=r.limitToBounds,x=r.alignmentAnimation,S=r.zoomAnimation,E=r.panning,_=E.lockAxisY,b=E.lockAxisX,C=S.animationType,R=x.sizeX,P=x.sizeY,O=x.velocityAlignmentTime,A=O,D=kZ(e,u),B=Math.max(D,A),V=sm(e,R),J=sm(e,P),G=V*o.offsetWidth/100,se=J*o.offsetHeight/100,U=f+G,ne=p-G,M=m+se,ee=g-se,H=e.transformState,X=new Date().getTime();RP(e,C,B,function(W){var le=e.transformState,pe=le.scale,$e=le.positionX,Ve=le.positionY,We=new Date().getTime()-X,Ne=We/A,fe=CP[x.animationType],xe=1-fe(Math.min(1,Ne)),Re=1-W,Me=$e+s*Re,Oe=Ve+l*Re,ze=F2(Me,H.positionX,$e,b,y,p,f,ne,U,xe),Mt=F2(Oe,H.positionY,Ve,_,y,g,m,ee,M,xe);($e!==Me||Ve!==Oe)&&e.setTransformState(pe,ze,Mt)})}}function j2(e,t){var n=e.transformState.scale;jo(e),vc(e,n),window.TouchEvent!==void 0&&t instanceof TouchEvent?SZ(e,t):bZ(e,t)}function kP(e){var t=e.transformState.scale,n=e.setup,r=n.minScale,o=n.alignmentAnimation,i=o.disabled,s=o.sizeX,l=o.sizeY,u=o.animationTime,f=o.animationType,p=i||t.1&&m;g?AZ(e):kP(e)}}function eb(e,t,n,r){var o=e.setup,i=o.minScale,s=o.maxScale,l=o.limitToBounds,u=Xd(Wr(t,2),i,s,0,!1),f=vc(e,u),p=hg(e,n,r,u,f,l),m=p.x,g=p.y;return{scale:u,positionX:m,positionY:g}}function TP(e,t,n){var r=e.transformState.scale,o=e.wrapperComponent,i=e.setup,s=i.minScale,l=i.limitToBounds,u=i.zoomAnimation,f=u.disabled,p=u.animationTime,m=u.animationType,g=f||r>=s;if((r>=1||l)&&kP(e),!(g||!o||!e.mounted)){var y=t||o.offsetWidth/2,x=n||o.offsetHeight/2,S=eb(e,s,y,x);S&&Bs(e,S,p,m)}}var $s=function(){return $s=Object.assign||function(t){for(var n,r=1,o=arguments.length;rs||Math.sign(n.deltaY)!==Math.sign(t.deltaY)||n.deltaY>0&&n.deltaYt.deltaY||Math.sign(n.deltaY)!==Math.sign(t.deltaY):!1},XZ=function(e,t){var n=e.setup.pinch,r=n.disabled,o=n.excluded,i=e.isInitialized,s=t.target,l=i&&!r&&s;if(!l)return!1;var u=pg(s,o);return!u},ZZ=function(e){var t=e.setup.pinch.disabled,n=e.isInitialized,r=e.pinchStartDistance,o=n&&!t&&r;return!!o},qZ=function(e,t,n){var r=n.getBoundingClientRect(),o=e.touches,i=Wr(o[0].clientX-r.left,5),s=Wr(o[0].clientY-r.top,5),l=Wr(o[1].clientX-r.left,5),u=Wr(o[1].clientY-r.top,5);return{x:(i+l)/2/t,y:(s+u)/2/t}},IP=function(e){return Math.sqrt(Math.pow(e.touches[0].pageX-e.touches[1].pageX,2)+Math.pow(e.touches[0].pageY-e.touches[1].pageY,2))},QZ=function(e,t){var n=e.pinchStartScale,r=e.pinchStartDistance,o=e.setup,i=o.maxScale,s=o.minScale,l=o.zoomAnimation,u=o.disablePadding,f=l.size,p=l.disabled;if(!n||r===null||!t)throw new Error("Pinch touches distance was not provided");if(t<0)return e.transformState.scale;var m=t/r,g=m*n;return Xd(Wr(g,2),s,i,f,!p&&!u)},JZ=160,eq=100,tq=function(e,t){var n=e.props,r=n.onWheelStart,o=n.onZoomStart;e.wheelStopEventTimer||(jo(e),Nt(_t(e),t,r),Nt(_t(e),t,o))},nq=function(e,t){var n=e.props,r=n.onWheel,o=n.onZoom,i=e.contentComponent,s=e.setup,l=e.transformState,u=l.scale,f=s.limitToBounds,p=s.centerZoomedOut,m=s.zoomAnimation,g=s.wheel,y=s.disablePadding,x=s.smooth,S=m.size,E=m.disabled,_=g.step,b=g.smoothStep;if(!i)throw new Error("Component not mounted");t.preventDefault(),t.stopPropagation();var C=KZ(t,null),R=x?b*Math.abs(t.deltaY):_,P=GZ(e,C,R,!t.ctrlKey);if(u!==P){var O=vc(e,P),A=DP(t,i,u),D=E||S===0||p||y,B=f&&D,V=hg(e,A.x,A.y,P,O,B),J=V.x,G=V.y;e.previousWheelEvent=t,e.setTransformState(P,J,G),Nt(_t(e),t,r),Nt(_t(e),t,o)}},rq=function(e,t){var n=e.props,r=n.onWheelStop,o=n.onZoomStop;B1(e.wheelAnimationTimer),e.wheelAnimationTimer=setTimeout(function(){e.mounted&&(TP(e,t.x,t.y),e.wheelAnimationTimer=null)},eq);var i=YZ(e,t);i&&(B1(e.wheelStopEventTimer),e.wheelStopEventTimer=setTimeout(function(){e.mounted&&(e.wheelStopEventTimer=null,Nt(_t(e),t,r),Nt(_t(e),t,o))},JZ))},oq=function(e,t){var n=IP(t);e.pinchStartDistance=n,e.lastDistance=n,e.pinchStartScale=e.transformState.scale,e.isPanning=!1,jo(e)},iq=function(e,t){var n=e.contentComponent,r=e.pinchStartDistance,o=e.transformState.scale,i=e.setup,s=i.limitToBounds,l=i.centerZoomedOut,u=i.zoomAnimation,f=u.disabled,p=u.size;if(!(r===null||!n)){var m=qZ(t,o,n);if(!(!Number.isFinite(m.x)||!Number.isFinite(m.y))){var g=IP(t),y=QZ(e,g);if(y!==o){var x=vc(e,y),S=f||p===0||l,E=s&&S,_=hg(e,m.x,m.y,y,x,E),b=_.x,C=_.y;e.pinchMidpoint=m,e.lastDistance=g,e.setTransformState(y,b,C)}}}},sq=function(e){var t=e.pinchMidpoint;e.velocity=null,e.lastDistance=null,e.pinchMidpoint=null,e.pinchStartScale=null,e.pinchStartDistance=null,TP(e,t==null?void 0:t.x,t==null?void 0:t.y)},LP=function(e,t){var n=e.props.onZoomStop,r=e.setup.doubleClick.animationTime;B1(e.doubleClickStopEventTimer),e.doubleClickStopEventTimer=setTimeout(function(){e.doubleClickStopEventTimer=null,Nt(_t(e),t,n)},r)},aq=function(e,t){var n=e.props,r=n.onZoomStart,o=n.onZoom,i=e.setup.doubleClick,s=i.animationTime,l=i.animationType;Nt(_t(e),t,r),OP(e,s,l,function(){return Nt(_t(e),t,o)}),LP(e,t)};function lq(e,t){var n=e.setup,r=e.doubleClickStopEventTimer,o=e.transformState,i=e.contentComponent,s=o.scale,l=e.props,u=l.onZoomStart,f=l.onZoom,p=n.doubleClick,m=p.disabled,g=p.mode,y=p.step,x=p.animationTime,S=p.animationType;if(!m&&!r){if(g==="reset")return aq(e,t);if(!i)return console.error("No ContentComponent found");var E=g==="zoomOut"?-1:1,_=AP(e,E,y);if(s!==_){Nt(_t(e),t,u);var b=DP(t,i,s),C=eb(e,_,b.x,b.y);if(!C)return console.error("Error during zoom event. New transformation state was not calculated.");Nt(_t(e),t,f),Bs(e,C,x,S),LP(e,t)}}}var cq=function(e,t){var n=e.isInitialized,r=e.setup,o=e.wrapperComponent,i=r.doubleClick,s=i.disabled,l=i.excluded,u=t.target,f=o==null?void 0:o.contains(u),p=n&&u&&f&&!s;if(!p)return!1;var m=pg(u,l);return!m},uq=function(){function e(t){var n=this;this.mounted=!0,this.onChangeCallbacks=new Set,this.onInitCallbacks=new Set,this.wrapperComponent=null,this.contentComponent=null,this.isInitialized=!1,this.bounds=null,this.previousWheelEvent=null,this.wheelStopEventTimer=null,this.wheelAnimationTimer=null,this.isPanning=!1,this.startCoords=null,this.lastTouch=null,this.distance=null,this.lastDistance=null,this.pinchStartDistance=null,this.pinchStartScale=null,this.pinchMidpoint=null,this.doubleClickStopEventTimer=null,this.velocity=null,this.velocityTime=null,this.lastMousePosition=null,this.animate=!1,this.animation=null,this.maxBounds=null,this.pressedKeys={},this.mount=function(){n.initializeWindowEvents()},this.unmount=function(){n.cleanupWindowEvents()},this.update=function(r){vc(n,n.transformState.scale),n.setup=U2(r)},this.initializeWindowEvents=function(){var r,o=z0(),i=(r=n.wrapperComponent)===null||r===void 0?void 0:r.ownerDocument,s=i==null?void 0:i.defaultView;s==null||s.addEventListener("mousedown",n.onPanningStart,o),s==null||s.addEventListener("mousemove",n.onPanning,o),s==null||s.addEventListener("mouseup",n.onPanningStop,o),i==null||i.addEventListener("mouseleave",n.clearPanning,o),s==null||s.addEventListener("keyup",n.setKeyUnPressed,o),s==null||s.addEventListener("keydown",n.setKeyPressed,o)},this.cleanupWindowEvents=function(){var r,o,i=z0(),s=(r=n.wrapperComponent)===null||r===void 0?void 0:r.ownerDocument,l=s==null?void 0:s.defaultView;l==null||l.removeEventListener("mousedown",n.onPanningStart,i),l==null||l.removeEventListener("mousemove",n.onPanning,i),l==null||l.removeEventListener("mouseup",n.onPanningStop,i),s==null||s.removeEventListener("mouseleave",n.clearPanning,i),l==null||l.removeEventListener("keyup",n.setKeyUnPressed,i),l==null||l.removeEventListener("keydown",n.setKeyPressed,i),document.removeEventListener("mouseleave",n.clearPanning,i),jo(n),(o=n.observer)===null||o===void 0||o.disconnect()},this.handleInitializeWrapperEvents=function(r){var o=z0();r.addEventListener("wheel",n.onWheelZoom,o),r.addEventListener("dblclick",n.onDoubleClick,o),r.addEventListener("touchstart",n.onTouchPanningStart,o),r.addEventListener("touchmove",n.onTouchPanning,o),r.addEventListener("touchend",n.onTouchPanningStop,o)},this.handleInitialize=function(r){var o=n.setup.centerOnInit;n.applyTransformation(),n.onInitCallbacks.forEach(function(i){return i(_t(n))}),o&&(n.setCenter(),n.observer=new ResizeObserver(function(){var i;n.onInitCallbacks.forEach(function(s){return s(_t(n))}),n.setCenter(),(i=n.observer)===null||i===void 0||i.disconnect()}),n.observer.observe(r))},this.onWheelZoom=function(r){var o=n.setup.disabled;if(!o){var i=WZ(n,r);if(i){var s=n.isPressingKeys(n.setup.wheel.activationKeys);s&&(tq(n,r),nq(n,r),rq(n,r))}}},this.onPanningStart=function(r){var o=n.setup.disabled,i=n.props.onPanningStart;if(!o){var s=I2(n,r);if(s){var l=n.isPressingKeys(n.setup.panning.activationKeys);l&&(r.button===0&&!n.setup.panning.allowLeftClickPan||r.button===1&&!n.setup.panning.allowMiddleClickPan||r.button===2&&!n.setup.panning.allowRightClickPan||(r.preventDefault(),r.stopPropagation(),jo(n),j2(n,r),Nt(_t(n),r,i)))}}},this.onPanning=function(r){var o=n.setup.disabled,i=n.props.onPanning;if(!o){var s=L2(n);if(s){var l=n.isPressingKeys(n.setup.panning.activationKeys);l&&(r.preventDefault(),r.stopPropagation(),z2(n,r.clientX,r.clientY),Nt(_t(n),r,i))}}},this.onPanningStop=function(r){var o=n.props.onPanningStop;n.isPanning&&(MZ(n),Nt(_t(n),r,o))},this.onPinchStart=function(r){var o=n.setup.disabled,i=n.props,s=i.onPinchingStart,l=i.onZoomStart;if(!o){var u=XZ(n,r);u&&(oq(n,r),jo(n),Nt(_t(n),r,s),Nt(_t(n),r,l))}},this.onPinch=function(r){var o=n.setup.disabled,i=n.props,s=i.onPinching,l=i.onZoom;if(!o){var u=ZZ(n);u&&(r.preventDefault(),r.stopPropagation(),iq(n,r),Nt(_t(n),r,s),Nt(_t(n),r,l))}},this.onPinchStop=function(r){var o=n.props,i=o.onPinchingStop,s=o.onZoomStop;n.pinchStartScale&&(sq(n),Nt(_t(n),r,i),Nt(_t(n),r,s))},this.onTouchPanningStart=function(r){var o=n.setup.disabled,i=n.props.onPanningStart;if(!o){var s=I2(n,r);if(s){var l=n.lastTouch&&+new Date-n.lastTouch<200;if(l&&r.touches.length===1)n.onDoubleClick(r);else{n.lastTouch=+new Date,jo(n);var u=r.touches,f=u.length===1,p=u.length===2;f&&(jo(n),j2(n,r),Nt(_t(n),r,i)),p&&n.onPinchStart(r)}}}},this.onTouchPanning=function(r){var o=n.setup.disabled,i=n.props.onPanning;if(n.isPanning&&r.touches.length===1){if(o)return;var s=L2(n);if(!s)return;r.preventDefault(),r.stopPropagation();var l=r.touches[0];z2(n,l.clientX,l.clientY),Nt(_t(n),r,i)}else r.touches.length>1&&n.onPinch(r)},this.onTouchPanningStop=function(r){n.onPanningStop(r),n.onPinchStop(r)},this.onDoubleClick=function(r){var o=n.setup.disabled;if(!o){var i=cq(n,r);i&&lq(n,r)}},this.clearPanning=function(r){n.isPanning&&n.onPanningStop(r)},this.setKeyPressed=function(r){n.pressedKeys[r.key]=!0},this.setKeyUnPressed=function(r){n.pressedKeys[r.key]=!1},this.isPressingKeys=function(r){return r.length?!!r.find(function(o){return n.pressedKeys[o]}):!0},this.setTransformState=function(r,o,i){var s=n.props.onTransformed;if(!Number.isNaN(r)&&!Number.isNaN(o)&&!Number.isNaN(i)){r!==n.transformState.scale&&(n.transformState.previousScale=n.transformState.scale,n.transformState.scale=r),n.transformState.positionX=o,n.transformState.positionY=i,n.applyTransformation();var l=_t(n);n.onChangeCallbacks.forEach(function(u){return u(l)}),Nt(l,{scale:r,positionX:o,positionY:i},s)}else console.error("Detected NaN set state values")},this.setCenter=function(){if(n.wrapperComponent&&n.contentComponent){var r=NP(n.transformState.scale,n.wrapperComponent,n.contentComponent);n.setTransformState(r.scale,r.positionX,r.positionY)}},this.handleTransformStyles=function(r,o,i){return n.props.customTransform?n.props.customTransform(r,o,i):UZ(r,o,i)},this.applyTransformation=function(){if(!(!n.mounted||!n.contentComponent)){var r=n.transformState,o=r.scale,i=r.positionX,s=r.positionY,l=n.handleTransformStyles(i,s,o);n.contentComponent.style.transform=l}},this.getContext=function(){return _t(n)},this.onChange=function(r){return n.onChangeCallbacks.has(r)||n.onChangeCallbacks.add(r),function(){n.onChangeCallbacks.delete(r)}},this.onInit=function(r){return n.onInitCallbacks.has(r)||n.onInitCallbacks.add(r),function(){n.onInitCallbacks.delete(r)}},this.init=function(r,o){n.cleanupWindowEvents(),n.wrapperComponent=r,n.contentComponent=o,vc(n,n.transformState.scale),n.handleInitializeWrapperEvents(r),n.handleInitialize(o),n.initializeWindowEvents(),n.isInitialized=!0;var i=_t(n);Nt(i,void 0,n.props.onInit)},this.props=t,this.setup=U2(this.props),this.transformState=PP(this.props)}return e}(),tb=je.createContext(null),dq=function(e,t){return typeof e=="function"?e(t):e},fq=je.forwardRef(function(e,t){var n=d.useRef(new uq(e)).current,r=dq(e.children,z1(n));return d.useImperativeHandle(t,function(){return z1(n)},[n]),d.useEffect(function(){n.update(e)},[n,e]),je.createElement(tb.Provider,{value:n},r)});je.forwardRef(function(e,t){var n=d.useRef(null),r=d.useContext(tb);return d.useEffect(function(){return r.onChange(function(o){if(n.current){var i=0,s=0;n.current.style.transform=r.handleTransformStyles(i,s,1/o.instance.transformState.scale)}})},[r]),je.createElement("div",$s({},e,{ref:VZ([n,t])}))});function hq(e,t){t===void 0&&(t={});var n=t.insertAt;if(!(!e||typeof document>"u")){var r=document.head||document.getElementsByTagName("head")[0],o=document.createElement("style");o.type="text/css",n==="top"&&r.firstChild?r.insertBefore(o,r.firstChild):r.appendChild(o),o.styleSheet?o.styleSheet.cssText=e:o.appendChild(document.createTextNode(e))}}var pq=`.transform-component-module_wrapper__SPB86 { + position: relative; + width: -moz-fit-content; + width: fit-content; + height: -moz-fit-content; + height: fit-content; + overflow: hidden; + -webkit-touch-callout: none; /* iOS Safari */ + -webkit-user-select: none; /* Safari */ + -khtml-user-select: none; /* Konqueror HTML */ + -moz-user-select: none; /* Firefox */ + -ms-user-select: none; /* Internet Explorer/Edge */ + user-select: none; + margin: 0; + padding: 0; +} +.transform-component-module_content__FBWxo { + display: flex; + flex-wrap: wrap; + width: -moz-fit-content; + width: fit-content; + height: -moz-fit-content; + height: fit-content; + margin: 0; + padding: 0; + transform-origin: 0% 0%; +} +.transform-component-module_content__FBWxo img { + pointer-events: none; +} +`,V2={wrapper:"transform-component-module_wrapper__SPB86",content:"transform-component-module_content__FBWxo"};hq(pq);var mq=function(e){var t=e.children,n=e.wrapperClass,r=n===void 0?"":n,o=e.contentClass,i=o===void 0?"":o,s=e.wrapperStyle,l=e.contentStyle,u=e.wrapperProps,f=u===void 0?{}:u,p=e.contentProps,m=p===void 0?{}:p,g=d.useContext(tb),y=g.init,x=g.cleanupWindowEvents,S=d.useRef(null),E=d.useRef(null);return d.useEffect(function(){var _=S.current,b=E.current;return _!==null&&b!==null&&y&&(y==null||y(_,b)),function(){x==null||x()}},[]),je.createElement("div",$s({},f,{ref:S,className:"react-transform-wrapper ".concat(V2.wrapper," ").concat(r),style:s}),je.createElement("div",$s({},m,{ref:E,className:"react-transform-component ".concat(V2.content," ").concat(i),style:l}),t))};const FP=["PageUp","PageDown"],jP=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],zP={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},Zd="Slider",[U1,gq,vq]=Kd(Zd),[BP,Cte]=Mn(Zd,[vq]),[yq,mg]=BP(Zd),wq=d.forwardRef((e,t)=>{const{name:n,min:r=0,max:o=100,step:i=1,orientation:s="horizontal",disabled:l=!1,minStepsBetweenThumbs:u=0,defaultValue:f=[r],value:p,onValueChange:m=()=>{},onValueCommit:g=()=>{},inverted:y=!1,...x}=e,[S,E]=d.useState(null),_=Ue(t,U=>E(U)),b=d.useRef(new Set),C=d.useRef(0),R=s==="horizontal",P=S?!!S.closest("form"):!0,O=R?xq:bq,[A=[],D]=Zr({prop:p,defaultProp:f,onChange:U=>{var ne;(ne=[...b.current][C.current])===null||ne===void 0||ne.focus(),m(U)}}),B=d.useRef(A);function V(U){const ne=Pq(A,U);se(U,ne)}function J(U){se(U,C.current)}function G(){const U=B.current[C.current];A[C.current]!==U&&g(A)}function se(U,ne,{commit:M}={commit:!1}){const ee=Nq(i),H=Dq(Math.round((U-r)/i)*i+r,ee),X=fd(H,[r,o]);D((W=[])=>{const le=kq(W,X,ne);if(Oq(le,u*i)){C.current=le.indexOf(X);const pe=String(le)!==String(W);return pe&&M&&g(le),pe?le:W}else return W})}return d.createElement(yq,{scope:e.__scopeSlider,disabled:l,min:r,max:o,valueIndexToChangeRef:C,thumbs:b.current,values:A,orientation:s},d.createElement(U1.Provider,{scope:e.__scopeSlider},d.createElement(U1.Slot,{scope:e.__scopeSlider},d.createElement(O,Y({"aria-disabled":l,"data-disabled":l?"":void 0},x,{ref:_,onPointerDown:ue(x.onPointerDown,()=>{l||(B.current=A)}),min:r,max:o,inverted:y,onSlideStart:l?void 0:V,onSlideMove:l?void 0:J,onSlideEnd:l?void 0:G,onHomeKeyDown:()=>!l&&se(r,0,{commit:!0}),onEndKeyDown:()=>!l&&se(o,A.length-1,{commit:!0}),onStepKeyDown:({event:U,direction:ne})=>{if(!l){const H=FP.includes(U.key)||U.shiftKey&&jP.includes(U.key)?10:1,X=C.current,W=A[X],le=i*H*ne;se(W+le,X,{commit:!0})}}})))),P&&A.map((U,ne)=>d.createElement(Rq,{key:ne,name:n?n+(A.length>1?"[]":""):void 0,value:U})))}),[UP,VP]=BP(Zd,{startEdge:"left",endEdge:"right",size:"width",direction:1}),xq=d.forwardRef((e,t)=>{const{min:n,max:r,dir:o,inverted:i,onSlideStart:s,onSlideMove:l,onSlideEnd:u,onStepKeyDown:f,...p}=e,[m,g]=d.useState(null),y=Ue(t,C=>g(C)),x=d.useRef(),S=Tc(o),E=S==="ltr",_=E&&!i||!E&&i;function b(C){const R=x.current||m.getBoundingClientRect(),P=[0,R.width],A=nb(P,_?[n,r]:[r,n]);return x.current=R,A(C-R.left)}return d.createElement(UP,{scope:e.__scopeSlider,startEdge:_?"left":"right",endEdge:_?"right":"left",direction:_?1:-1,size:"width"},d.createElement(WP,Y({dir:S,"data-orientation":"horizontal"},p,{ref:y,style:{...p.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:C=>{const R=b(C.clientX);s==null||s(R)},onSlideMove:C=>{const R=b(C.clientX);l==null||l(R)},onSlideEnd:()=>{x.current=void 0,u==null||u()},onStepKeyDown:C=>{const P=zP[_?"from-left":"from-right"].includes(C.key);f==null||f({event:C,direction:P?-1:1})}})))}),bq=d.forwardRef((e,t)=>{const{min:n,max:r,inverted:o,onSlideStart:i,onSlideMove:s,onSlideEnd:l,onStepKeyDown:u,...f}=e,p=d.useRef(null),m=Ue(t,p),g=d.useRef(),y=!o;function x(S){const E=g.current||p.current.getBoundingClientRect(),_=[0,E.height],C=nb(_,y?[r,n]:[n,r]);return g.current=E,C(S-E.top)}return d.createElement(UP,{scope:e.__scopeSlider,startEdge:y?"bottom":"top",endEdge:y?"top":"bottom",size:"height",direction:y?1:-1},d.createElement(WP,Y({"data-orientation":"vertical"},f,{ref:m,style:{...f.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:S=>{const E=x(S.clientY);i==null||i(E)},onSlideMove:S=>{const E=x(S.clientY);s==null||s(E)},onSlideEnd:()=>{g.current=void 0,l==null||l()},onStepKeyDown:S=>{const _=zP[y?"from-bottom":"from-top"].includes(S.key);u==null||u({event:S,direction:_?-1:1})}})))}),WP=d.forwardRef((e,t)=>{const{__scopeSlider:n,onSlideStart:r,onSlideMove:o,onSlideEnd:i,onHomeKeyDown:s,onEndKeyDown:l,onStepKeyDown:u,...f}=e,p=mg(Zd,n);return d.createElement(Ae.span,Y({},f,{ref:t,onKeyDown:ue(e.onKeyDown,m=>{m.key==="Home"?(s(m),m.preventDefault()):m.key==="End"?(l(m),m.preventDefault()):FP.concat(jP).includes(m.key)&&(u(m),m.preventDefault())}),onPointerDown:ue(e.onPointerDown,m=>{const g=m.target;g.setPointerCapture(m.pointerId),m.preventDefault(),p.thumbs.has(g)?g.focus():r(m)}),onPointerMove:ue(e.onPointerMove,m=>{m.target.hasPointerCapture(m.pointerId)&&o(m)}),onPointerUp:ue(e.onPointerUp,m=>{const g=m.target;g.hasPointerCapture(m.pointerId)&&(g.releasePointerCapture(m.pointerId),i(m))})}))}),Sq="SliderTrack",_q=d.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,o=mg(Sq,n);return d.createElement(Ae.span,Y({"data-disabled":o.disabled?"":void 0,"data-orientation":o.orientation},r,{ref:t}))}),W2="SliderRange",Eq=d.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,o=mg(W2,n),i=VP(W2,n),s=d.useRef(null),l=Ue(t,s),u=o.values.length,f=o.values.map(g=>HP(g,o.min,o.max)),p=u>1?Math.min(...f):0,m=100-Math.max(...f);return d.createElement(Ae.span,Y({"data-orientation":o.orientation,"data-disabled":o.disabled?"":void 0},r,{ref:l,style:{...e.style,[i.startEdge]:p+"%",[i.endEdge]:m+"%"}}))}),H2="SliderThumb",Cq=d.forwardRef((e,t)=>{const n=gq(e.__scopeSlider),[r,o]=d.useState(null),i=Ue(t,l=>o(l)),s=d.useMemo(()=>r?n().findIndex(l=>l.ref.current===r):-1,[n,r]);return d.createElement($q,Y({},e,{ref:i,index:s}))}),$q=d.forwardRef((e,t)=>{const{__scopeSlider:n,index:r,...o}=e,i=mg(H2,n),s=VP(H2,n),[l,u]=d.useState(null),f=Ue(t,E=>u(E)),p=yx(l),m=i.values[r],g=m===void 0?0:HP(m,i.min,i.max),y=Tq(r,i.values.length),x=p==null?void 0:p[s.size],S=x?Aq(x,g,s.direction):0;return d.useEffect(()=>{if(l)return i.thumbs.add(l),()=>{i.thumbs.delete(l)}},[l,i.thumbs]),d.createElement("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[s.startEdge]:`calc(${g}% + ${S}px)`}},d.createElement(U1.ItemSlot,{scope:e.__scopeSlider},d.createElement(Ae.span,Y({role:"slider","aria-label":e["aria-label"]||y,"aria-valuemin":i.min,"aria-valuenow":m,"aria-valuemax":i.max,"aria-orientation":i.orientation,"data-orientation":i.orientation,"data-disabled":i.disabled?"":void 0,tabIndex:i.disabled?void 0:0},o,{ref:f,style:m===void 0?{display:"none"}:e.style,onFocus:ue(e.onFocus,()=>{i.valueIndexToChangeRef.current=r})}))))}),Rq=e=>{const{value:t,...n}=e,r=d.useRef(null),o=Ux(t);return d.useEffect(()=>{const i=r.current,s=window.HTMLInputElement.prototype,u=Object.getOwnPropertyDescriptor(s,"value").set;if(o!==t&&u){const f=new Event("input",{bubbles:!0});u.call(i,t),i.dispatchEvent(f)}},[o,t]),d.createElement("input",Y({style:{display:"none"}},n,{ref:r,defaultValue:t}))};function kq(e=[],t,n){const r=[...e];return r[n]=t,r.sort((o,i)=>o-i)}function HP(e,t,n){const i=100/(n-t)*(e-t);return fd(i,[0,100])}function Tq(e,t){return t>2?`Value ${e+1} of ${t}`:t===2?["Minimum","Maximum"][e]:void 0}function Pq(e,t){if(e.length===1)return 0;const n=e.map(o=>Math.abs(o-t)),r=Math.min(...n);return n.indexOf(r)}function Aq(e,t,n){const r=e/2,i=nb([0,50],[0,r]);return(r-i(t)*n)*n}function Mq(e){return e.slice(0,-1).map((t,n)=>e[n+1]-t)}function Oq(e,t){if(t>0){const n=Mq(e);return Math.min(...n)>=t}return!0}function nb(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 Nq(e){return(String(e).split(".")[1]||"").length}function Dq(e,t){const n=Math.pow(10,t);return Math.round(e*n)/n}const KP=wq,Iq=_q,Lq=Eq,Fq=Cq,uo=d.forwardRef(({className:e,...t},n)=>v.jsxs(KP,{ref:n,className:_e("relative flex w-full touch-none select-none items-center",e),tabIndex:-1,...t,children:[v.jsx(Iq,{className:"relative h-1.5 w-full grow overflow-hidden rounded-full bg-primary/20 data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50",children:v.jsx(Lq,{className:"absolute h-full bg-primary data-[disabled]:cursor-not-allowed "})}),v.jsx(Fq,{tabIndex:-1,className:"block h-4 w-4 rounded-full border border-primary/60 bg-background shadow transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring data-[disabled]:cursor-not-allowed"})]}));uo.displayName=KP.displayName;const ll={capture:!0,passive:!1},jq=2,K2=(e,t,n,r,o,i)=>{if(e!==n&&t===r){if(e<0)return[0,r];if(e+t>i)return[i-r,r]}else{if(ti)return[e,i-e]}return[e,t]},zq=e=>{const{minHeight:t,minWidth:n,maxHeight:r,maxWidth:o,scale:i,show:s}=e,[l,u,f,p,{x:m,y:g,width:y,height:x},S,E,_,b,C,R]=bt(W=>[W.imageWidth,W.imageHeight,W.isInpainting,W.isSD(),W.cropperState,W.setCropperX,W.setCropperY,W.setCropperWidth,W.setCropperHeight,W.isCropperExtenderResizing,W.setIsCropperExtenderResizing]),[P,O]=d.useState(!1);d.useEffect(()=>{S(Math.round((o-512)/2)),E(Math.round((r-512)/2))},[r,o,l,u]);const[A,D]=d.useState({initX:0,initY:0,initHeight:0,initWidth:0,startResizeX:0,startResizeY:0,ord:"top"}),B=()=>{},V=(W,le)=>K2(W,le,m,y,n,o),J=(W,le)=>K2(W,le,g,x,t,r),G=W=>{if(f)return;const le=W.clientX,pe=W.clientY,$e=Math.round((pe-A.startResizeY)/i),Ve=Math.round((le-A.startResizeX)/i),We=()=>{const Re=A.initHeight-$e,Me=A.initY+$e,[Oe,ze]=J(Me,Re);b(ze),E(Oe)},Ne=()=>{const Re=A.initHeight+$e,[Me,Oe]=J(A.initY,Re);b(Oe),E(Me)},fe=()=>{const Re=A.initWidth-Ve,Me=A.initX+Ve,[Oe,ze]=V(Me,Re);_(ze),S(Oe)},xe=()=>{const Re=A.initWidth+Ve,[Me,Oe]=V(A.initX,Re);_(Oe),S(Me)};if(C)switch(A.ord){case"topleft":{We(),fe();break}case"topright":{We(),xe();break}case"bottomleft":{Ne(),fe();break}case"bottomright":{Ne(),xe();break}case"top":{We();break}case"right":{xe();break}case"bottom":{Ne();break}case"left":{fe();break}}if(P){const Re=A.initX+Ve,Me=A.initY+$e,[Oe,ze]=V(Re,A.initWidth),[Mt,ct]=J(Me,A.initHeight);_(ze),b(ct),S(Oe),E(Mt)}},se=()=>{C&&R(!1),P&&O(!1)};d.useEffect(()=>{if(C||P)return document.addEventListener("pointermove",G,ll),document.addEventListener("pointerup",se,ll),document.addEventListener("pointercancel",se,ll),()=>{document.removeEventListener("pointermove",G,ll),document.removeEventListener("pointerup",se,ll),document.removeEventListener("pointercancel",se,ll)}},[C,P,y,x,A]);const U=W=>{const{ord:le}=W.target.dataset;le&&(R(!0),D({initX:m,initY:g,initHeight:x,initWidth:y,startResizeX:W.clientX,startResizeY:W.clientY,ord:le}))},ne=(W,le,pe)=>{const We="w-[12px] h-[12px] z-[4] absolute content-[''] block border-2 border-primary borde pointer-events-auto hover:bg-primary";let Ne="0",fe="0",xe=pe,Re="-6px";return pe===""&&(Re="50%",le==="left"||le==="right"?(xe="top",fe="-50%"):(xe="left",Ne="-50%")),v.jsx("div",{className:_e(We,W),style:{[le]:-6,[xe]:Re,transform:`translate(${Ne}, ${fe}) scale(${1/i})`},"data-ord":le+pe,"aria-label":le+pe,tabIndex:-1,role:"button"})},M=()=>v.jsxs("div",{onFocus:B,onPointerDown:U,className:"absolute top-0 h-full w-full",children:[v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 w-full cursor-ns-resize h-[12px] mt-[-6px]","data-ord":"top"}),v.jsx("div",{className:"absolute pointer-events-auto top-0 right-0 h-full cursor-ew-resize w-[12px] mr-[-6px]","data-ord":"right"}),v.jsx("div",{className:"absolute pointer-events-auto bottom-0 left-0 w-full cursor-ns-resize h-[12px] mb-[-6px]","data-ord":"bottom"}),v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 h-full cursor-ew-resize w-[12px] ml-[-6px]","data-ord":"left"}),ne("cursor-nw-resize","top","left"),ne("cursor-ne-resize","top","right"),ne("cursor-sw-resize","bottom","left"),ne("cursor-se-resize","bottom","right"),ne("cursor-ns-resize","top",""),ne("cursor-ns-resize","bottom",""),ne("cursor-ew-resize","left",""),ne("cursor-ew-resize","right","")]}),ee=W=>{O(!0),D({initX:m,initY:g,initHeight:x,initWidth:y,startResizeX:W.clientX,startResizeY:W.clientY,ord:""})},H=()=>v.jsxs("div",{className:tx("border absolute pointer-events-auto px-2 py-1 rounded-full hover:cursor-move bg-background","origin-top-left top-0 left-0"),style:{transform:`scale(${1/i*.8})`},onPointerDown:ee,children:[y," x ",x]}),X=()=>v.jsx("div",{className:"outline-dashed outline-primary",style:{height:x,width:y,outlineWidth:`${jq/i*1.3}px`}});return s===!1||!p?null:v.jsx("div",{className:"absolute h-full w-full overflow-hidden pointer-events-none z-[2]",children:v.jsxs("div",{className:"relative pointer-events-none z-[2] [box-shadow:0_0_0_9999px_rgba(0,_0,_0,_0.5)]",style:{height:x,width:y,left:m,top:g},children:[X(),H(),M()]})})},Bq=()=>{const[e,t,n]=bt(r=>[r.interactiveSegState,r.resetInteractiveSegState,r.handleInteractiveSegAccept]);return e.isInteractiveSeg?v.jsxs("div",{className:"z-10 absolute top-[68px] rounded-xl border-solid border p-[8px] left-1/2 translate-x-[-50%] flex justify-center items-center gap-[8px] bg-background",children:[v.jsx(wn,{onClick:()=>{t()},size:"sm",variant:"secondary",children:"Cancel"}),v.jsx(wn,{size:"sm",onClick:()=>{n()},children:"Accept"})]}):null},Uq=e=>{const{x:t,y:n,positive:r}=e,o=r?"bg-[rgba(21,_215,_121,_0.936)] outline-[rgba(98,255,179,0.31)]":"bg-[rgba(237,_49,_55,_0.942)] outline-[rgba(255,89,95,0.31)]";return v.jsx("div",{className:`absolute h-[10px] w-[10px] rounded-[50%] ${o} outline-8 outline`,style:{left:t,top:n,transform:"translate(-50%, -50%)"}})},Vq=()=>{const e=bt(t=>t.interactiveSegState.clicks);return v.jsx("div",{className:"absolute h-full w-full overflow-hidden pointer-events-none",children:e.map(t=>v.jsx(Uq,{x:t[0],y:t[1],positive:t[2]===1},t[3]))})},Wq=()=>v.jsx("div",{children:v.jsx(Bq,{})}),cl={capture:!0,passive:!1},Hq=2,G2=(e,t,n,r)=>t{const{minHeight:t,minWidth:n,scale:r,show:o}=e,[i,s,l,u,{x:f,y:p,width:m,height:g},y,x,S,E,_,b,C]=bt(ee=>[ee.isInpainting,ee.imageHeight,ee.imageWidth,ee.isSD(),ee.extenderState,ee.setExtenderX,ee.setExtenderY,ee.setExtenderWidth,ee.setExtenderHeight,ee.settings.extenderDirection,ee.isCropperExtenderResizing,ee.setIsCropperExtenderResizing]),[R,P]=d.useState({initX:0,initY:0,initHeight:0,initWidth:0,startResizeX:0,startResizeY:0,ord:"top"}),O=()=>{},A=(ee,H)=>G2(ee,H,f,n),D=(ee,H)=>G2(ee,H,p,t),B=ee=>{if(i)return;const H=ee.clientX,X=ee.clientY,W=Math.round((X-R.startResizeY)/r),le=Math.round((H-R.startResizeX)/r),pe=()=>{const Ne=R.initHeight-W,fe=R.initY+W;let xe=fe,Re=Ne;if(_===Ln.xy)xe>0&&(xe=0,Re=R.initHeight-Math.abs(R.initY));else{const Me=D(fe,Ne);xe=Me[0],Re=Me[1]}E(Re),x(xe)},$e=()=>{const Ne=R.initHeight+W;let[fe,xe]=D(R.initY,Ne);_===Ln.xy&&xe{const Ne=R.initWidth-le,fe=R.initX+le;let xe=fe,Re=Ne;if(_===Ln.xy)xe>0&&(xe=0,Re=R.initWidth-Math.abs(R.initX));else{const Me=A(fe,Ne);xe=Me[0],Re=Me[1]}S(Re),y(xe)},We=()=>{const Ne=R.initWidth+le;let[fe,xe]=A(R.initX,Ne);_===Ln.xy&&xe{b&&C(!1)};d.useEffect(()=>{if(b)return document.addEventListener("pointermove",B,cl),document.addEventListener("pointerup",V,cl),document.addEventListener("pointercancel",V,cl),()=>{document.removeEventListener("pointermove",B,cl),document.removeEventListener("pointerup",V,cl),document.removeEventListener("pointercancel",V,cl)}},[b,m,g,R]);const J=ee=>{const{ord:H}=ee.target.dataset;H&&(C(!0),P({initX:f,initY:p,initHeight:g,initWidth:m,startResizeX:ee.clientX,startResizeY:ee.clientY,ord:H}))},G=(ee,H,X)=>{const pe="w-[12px] h-[12px] z-[4] absolute content-[''] block border-2 border-primary borde pointer-events-auto hover:bg-primary";let $e="0",Ve="0",We=X,Ne="-6px";return X===""&&(Ne="50%",H==="left"||H==="right"?(We="top",Ve="-50%"):(We="left",$e="-50%")),v.jsx("div",{className:_e(pe,ee),style:{[H]:-6,[We]:Ne,transform:`translate(${$e}, ${Ve}) scale(${1/r})`},"data-ord":H+X,"aria-label":H+X,tabIndex:-1,role:"button"})},se=()=>v.jsxs("div",{onFocus:O,onPointerDown:J,className:"absolute top-0 h-full w-full",children:[[Ln.y,Ln.xy].includes(_)?v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 w-full cursor-ns-resize h-[12px] mt-[-6px]","data-ord":"top"}),v.jsx("div",{className:"absolute pointer-events-auto bottom-0 left-0 w-full cursor-ns-resize h-[12px] mb-[-6px]","data-ord":"bottom"}),G("cursor-ns-resize","top",""),G("cursor-ns-resize","bottom","")]}):v.jsx(v.Fragment,{}),[Ln.x,Ln.xy].includes(_)?v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"absolute pointer-events-auto top-0 right-0 h-full cursor-ew-resize w-[12px] mr-[-6px]","data-ord":"right"}),v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 h-full cursor-ew-resize w-[12px] ml-[-6px]","data-ord":"left"}),G("cursor-ew-resize","left",""),G("cursor-ew-resize","right","")]}):v.jsx(v.Fragment,{}),_===Ln.xy?v.jsxs(v.Fragment,{children:[G("cursor-nw-resize","top","left"),G("cursor-ne-resize","top","right"),G("cursor-sw-resize","bottom","left"),G("cursor-se-resize","bottom","right")]}):v.jsx(v.Fragment,{})]}),U=ee=>{P({initX:f,initY:p,initHeight:g,initWidth:m,startResizeX:ee.clientX,startResizeY:ee.clientY,ord:""})},ne=()=>v.jsxs("div",{className:tx("border absolute pointer-events-auto px-2 py-1 rounded-full bg-background","origin-top-left top-0 left-0"),style:{transform:`scale(${1/r*.8})`},onPointerDown:U,children:[m," x ",g]}),M=()=>v.jsx("div",{className:_e("outline-dashed outline-primary"),style:{height:g,width:m,outlineWidth:`${Hq/r*1.3}px`}});return o===!1||!u?null:v.jsx("div",{className:"absolute h-full w-full pointer-events-none z-[2]",children:v.jsxs("div",{className:"relative pointer-events-none z-[2] [box-shadow:0_0_0_9999px_rgba(0,_0,_0,_0.5)]",style:{height:g,width:m,left:f,top:p},children:[M(),ne(),se()]})})},Gq=200,Yq=3,Xq=200,mu=300;function Zq(e){const{file:t}=e,{toast:n}=Id(),[r,o,i,s,l,u,f,p,m,g,y,x,S,E,_,b,C,R,P,O,A,D]=bt(K=>[K.disableShortCuts,K.windowSize,K.isInpainting,K.imageWidth,K.imageHeight,K.settings,K.serverConfig.enableAutoSaving,K.setImageSize,K.setBaseBrushSize,K.interactiveSegState,K.updateInteractiveSegState,K.handleCanvasMouseDown,K.handleCanvasMouseMove,K.undo,K.redo,K.undoDisabled(),K.redoDisabled(),K.getIsProcessing(),K.updateAppState,K.runMannually(),K.runInpainting,K.isCropperExtenderResizing]),B=bt(K=>K.editorState.baseBrushSize),V=bt(K=>K.getBrushSize()),J=bt(K=>K.editorState.renders),G=bt(K=>K.editorState.extraMasks),se=bt(K=>K.editorState.temporaryMasks),U=bt(K=>K.editorState.lineGroups),ne=bt(K=>K.editorState.curLineGroup),[M,ee]=d.useState(!1),[H,X]=Px(t),[W,le]=d.useState(),[pe,$e]=d.useState(),[{x:Ve,y:We},Ne]=d.useState({x:-1,y:-1}),[fe,xe]=d.useState(!1),[Re,Me]=d.useState(!1),[Oe,ze]=d.useState(!1),[Mt,ct]=d.useState(1),[Kt,Er]=d.useState(!1),[gt,Vs]=d.useState(1),L=o.width/2,Z=o.height/2,q=d.useRef(null),[we,me]=d.useState(!1),[de,ke]=d.useState(!1),[ft,ht]=d.useState(0),_n=d.useCallback(()=>ne.length!==0,[ne]);d.useEffect(()=>{if(!pe||!X||s===0||l===0)return;const K=J.length===0?H:J[J.length-1];pe.canvas.width=s,pe.canvas.height=l,pe.clearRect(0,0,pe.canvas.width,pe.canvas.height),pe.drawImage(K,0,0,s,l)},[J,H,X,pe,l,s]),d.useEffect(()=>{!W||!X||s===0||l===0||(W.canvas.width=s,W.canvas.height=l,W.clearRect(0,0,W.canvas.width,W.canvas.height),se.forEach(K=>{W.drawImage(K,0,0,s,l)}),G.forEach(K=>{W.drawImage(K,0,0,s,l)}),g.isInteractiveSeg&&g.tmpInteractiveSegMask&&W.drawImage(g.tmpInteractiveSegMask,0,0,s,l),ZR(W,ne))},[se,G,X,g,W,ne,l,s]);const Cr=d.useCallback(async()=>{let K=t;if(J.length>0){const Ye=J[J.length-1];K=await Nu(Ye.currentSrc,t.name,t.type)}return K},[t,J]),Ni=()=>J.length!==0,Co=d.useCallback(()=>{let K=512,Ye=512;return X?(J.length===0?(K=H.naturalWidth,Ye=H.naturalHeight):J.length!==0&&(K=J[J.length-1].width,Ye=J[J.length-1].height),[K,Ye]):[K,Ye]},[H,X,J]);d.useEffect(()=>{var ef;if(!X)return;const[K,Ye]=Co();(K!==s||Ye!==l)&&p(K,Ye);const st=o.width/K,Qr=(o.height-Gq)/Ye;let an=1;(st<1||Qr<1)&&(an=Math.min(st,Qr)),Vs(an),ct(an),console.log(`[on file load] image size: ${K}x${Ye}, scale: ${an}, initialCentered: ${we}`),W!=null&&W.canvas&&(console.log("[on file load] set canvas size"),K!=W.canvas.width&&(W.canvas.width=K),Ye!=W.canvas.height&&(W.canvas.height=Ye)),we||((ef=q.current)==null||ef.centerView(an,1),console.log("[on file load] centerView"),me(!0))},[q,l,s,H,X,o,we,Co]),d.useEffect(()=>{var K;console.log("[useEffect] centerView"),(K=q==null?void 0:q.current)==null||K.centerView(gt,1)},[l,s,q,gt]);const Vn=d.useCallback(()=>{if(!gt||!o)return;const K=q.current;if(!K)return;const Ye=(o.width-s*gt)/2,st=(o.height-l*gt)/2;K.setTransform(Ye,st,gt,200,"easeOutQuad"),K.instance.transformState.scale&&(K.instance.transformState.scale=gt),ct(gt),Er(!1)},[q,o,l,s,o.height,gt]);d.useEffect(()=>(window.addEventListener("resize",()=>{Vn()}),()=>{window.removeEventListener("resize",()=>{Vn()})}),[o,Vn]),Zn("Escape",()=>{R||(de?ke(!1):Vn())},[de,i,Vn]);const Di=K=>{const Ye=K.nativeEvent;Ne({x:Ye.pageX,y:Ye.pageY})},Ws=K=>{R||g.isInteractiveSeg||Oe||de&&ne.length!==0&&S(h0(K))},Ii=async K=>{P({isPluginRunning:!0});const Ye=await Cr();try{const st=await wk(!0,Ao.InteractiveSeg,Ye,void 0,K),{blob:Qr}=st,an=new Image;an.onload=()=>{y({tmpInteractiveSegMask:an})},an.src=Qr}catch(st){n({variant:"destructive",description:st.message?st.message:st.toString()})}P({isPluginRunning:!1})},Mc=K=>{if(hC(K)){ze(!1);return}!_n()||g.isInteractiveSeg||Oe||!H.src||!(W!=null&&W.canvas)||i||de&&(O?ke(!1):A())},Sg=K=>{if(g.isInteractiveSeg){const Ye=h0(K),st=[...g.clicks];fC(K)?st.push([Ye.x,Ye.y,0,st.length]):st.push([Ye.x,Ye.y,1,st.length]),Ii(st),y({clicks:st})}},_g=K=>{if(!(R||g.isInteractiveSeg||Oe||!X||!(W!=null&&W.canvas))&&!fC(K)){if(hC(K)){ze(!0);return}ke(!0),x(h0(K))}},Qd=K=>{K.preventDefault(),E()};Zn("meta+z,ctrl+z",Qd);const Oc=K=>{K.preventDefault(),_()};Zn("shift+ctrl+z,shift+meta+z",Oc),l2("Tab",K=>{K==null||K.preventDefault(),K==null||K.stopPropagation(),Ni()&&ee(()=>(window.setTimeout(()=>{ht(100)},10),!0))},K=>{K==null||K.preventDefault(),K==null||K.stopPropagation(),Ni()&&(window.setTimeout(()=>{ht(0)},10),window.setTimeout(()=>{ee(!1)},mu))});const Nc=d.useCallback(async()=>{if(t===void 0)return;if(f&&J.length>0){try{await Hj(J[J.length-1],t.name,t.type),n({description:"Save image success"})}catch(st){n({variant:"destructive",title:"Uh oh! Something went wrong.",description:st.message?st.message:st.toString()})}return}const K=t.name.replace(/(\.[\w\d_-]+)$/i,"_cleanup$1"),Ye=J[J.length-1];if(bF(Ye.currentSrc,K),u.enableDownloadMask){let st=t.name.replace(/(\.[\w\d_-]+)$/i,"_mask$1");st=st.replace(/\.[^/.]+$/,".jpg");const Qr=Wh(s,l,U),an=document.createElement("a");an.download=st,an.href=Qr.toDataURL("image/jpeg"),an.click()}},[t,f,J,u,l,s,U]);Zn("meta+s,ctrl+s",Nc);const Dc=K=>{K!==fe&&!Oe&&!D&&xe(K)},Eg=d.useCallback(()=>{if(R)return"default";if(Oe)return"grab";if(fe)return"none"},[fe,Oe,R]);Zn("[",()=>{let K=B;B>10&&(K=B-10),B<=10&&B>0&&(K=B-3),m(K)},[B]),Zn("]",()=>{m(B+10)},[B]),Zn("shift+r",()=>{O&&_n()&&A()},[O,A,_n]),Zn("ctrl+c,meta+c",async()=>{await vF()&&J.length>0&&W!=null&&W.canvas&&(await xF(W==null?void 0:W.canvas),n({title:"Copy inpainting result to clipboard"}))},[J,W]),l2(" ",K=>{r||(K==null||K.preventDefault(),K==null||K.stopPropagation(),xe(!1),ze(!0))},K=>{r||(K==null||K.preventDefault(),K==null||K.stopPropagation(),xe(!0),ze(!1))});const Ic=()=>{var Ye,st,Qr,an;let K=gt;return((st=(Ye=q.current)==null?void 0:Ye.instance)==null?void 0:st.transformState.scale)!==void 0&&(K=(an=(Qr=q.current)==null?void 0:Qr.instance)==null?void 0:an.transformState.scale),K},Jd=(K,Ye)=>{const st=Ic();return{width:`${V*st}px`,height:`${V*st}px`,left:`${K}px`,top:`${Ye}px`,transform:"translate(-50%, -50%)"}},Lc=K=>v.jsx("div",{className:"absolute rounded-[50%] border-[1px] border-[solid] border-[#ffcc00] pointer-events-none bg-[#ffcc00bb]",style:K}),Cg=K=>{m(K),Re||(Me(!0),window.setTimeout(()=>{Me(!1)},1e4))},$g=()=>v.jsx("div",{className:"absolute h-[20px] w-[20px] pointer-events-none rounded-[50%] bg-[rgba(21,_215,_121,_0.936)] [box-shadow:0_0_0_0_rgba(21,_215,_121,_0.936)] animate-pulse",style:{left:`${Ve}px`,top:`${We}px`,transform:"translate(-50%, -50%)"},children:v.jsx(dK,{})}),Rg=()=>v.jsx(fq,{ref:K=>{K&&(q.current=K)},panning:{disabled:!Oe,velocityDisabled:!0},wheel:{step:.05},centerZoomedOut:!0,alignmentAnimation:{disabled:!0},centerOnInit:!0,limitToBounds:!1,doubleClick:{disabled:!0},initialScale:gt,minScale:gt*.3,onPanning:()=>{Kt||Er(!0)},onZoom:K=>{ct(K.state.scale)},children:v.jsxs(mq,{contentStyle:{visibility:we?"visible":"hidden"},children:[v.jsxs("div",{className:"grid [grid-template-areas:'editor-content'] gap-y-4",children:[v.jsx("canvas",{className:"[grid-area:editor-content]",style:{clipPath:`inset(0 ${ft}% 0 0)`,transition:`clip-path ${mu}ms`},ref:K=>{if(K&&!pe){const Ye=K.getContext("2d");Ye&&$e(Ye)}}}),v.jsx("canvas",{className:_e("[grid-area:editor-content]",R?"pointer-events-none animate-pulse duration-600":""),style:{cursor:Eg(),clipPath:`inset(0 ${ft}% 0 0)`,transition:`clip-path ${mu}ms`},onContextMenu:K=>{K.preventDefault()},onMouseOver:()=>{Dc(!0),Me(!1)},onFocus:()=>Dc(!0),onMouseLeave:()=>Dc(!1),onMouseDown:_g,onMouseUp:Sg,onMouseMove:Ws,ref:K=>{if(K&&!W){const Ye=K.getContext("2d");Ye&&le(Ye)}}}),v.jsx("div",{className:"[grid-area:editor-content] pointer-events-none grid [grid-template-areas:'original-image-content']",style:{width:`${s}px`,height:`${l}px`},children:M&&v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"[grid-area:original-image-content] z-10 bg-primary h-full w-[6px] justify-self-end",style:{marginRight:`${ft}%`,transition:`margin-right ${mu}ms`}}),v.jsx("img",{className:"[grid-area:original-image-content]",src:H.src,alt:"original",style:{width:`${s}px`,height:`${l}px`}})]})})]}),v.jsx(zq,{maxHeight:l,maxWidth:s,minHeight:Math.min(512,l),minWidth:Math.min(512,s),scale:Ic(),show:u.showCropper}),v.jsx(Kq,{minHeight:Math.min(512,l),minWidth:Math.min(512,s),scale:Ic(),show:u.showExtender}),g.isInteractiveSeg?v.jsx(Vq,{}):v.jsx(v.Fragment,{})]})});return v.jsxs("div",{className:"flex w-screen h-screen justify-center items-center","aria-hidden":"true",onMouseMove:Di,onMouseUp:Mc,children:[Rg(),fe&&!i&&!Oe&&(g.isInteractiveSeg?$g():Lc(Jd(Ve,We))),Re&&Lc(Jd(L,Z)),v.jsxs("div",{className:" overflow-hidden fixed flex bottom-5 border px-4 py-2 rounded-[3rem] gap-8 items-center justify-center backdrop-filter backdrop-blur-md bg-background/70",children:[v.jsx(uo,{className:"w-48",defaultValue:[50],min:Yq,max:Xq,step:1,tabIndex:-1,value:[B],onValueChange:K=>Cg(K[0]),onClick:()=>Me(!1)}),v.jsxs("div",{className:"flex gap-2",children:[v.jsx(yn,{tooltip:"Reset zoom & pan",disabled:Mt===gt&&Kt===!1,onClick:Vn,children:v.jsx(QU,{})}),v.jsx(yn,{tooltip:"Undo",onClick:Qd,disabled:b,children:v.jsx(aV,{})}),v.jsx(yn,{tooltip:"Redo",onClick:Oc,disabled:C,children:v.jsx(oV,{})}),v.jsx(yn,{tooltip:"Show original image",onPointerDown:K=>{K.preventDefault(),ee(()=>(window.setTimeout(()=>{ht(100)},10),!0))},onPointerUp:()=>{window.setTimeout(()=>{ht(0)},10),window.setTimeout(()=>{ee(!1)},mu)},disabled:J.length===0,children:v.jsx(JU,{})}),v.jsx(yn,{tooltip:"Save Image",disabled:!J.length,onClick:Nc,children:v.jsx(ZU,{})}),u.enableManualInpainting&&u.model.model_type==="inpaint"?v.jsx(yn,{tooltip:"Run Inpainting",disabled:R||!_n()&&G.length===0,onClick:()=>{A()},children:v.jsx(qU,{})}):v.jsx(v.Fragment,{})]})]})]})}const qq=()=>{const[e,t]=bt(n=>[n.imageWidth,n.imageHeight]);return!e||!t?null:v.jsxs("div",{className:"border rounded-lg px-2 py-[6px] z-10 bg-background",children:[e,"x",t]})},V1=["Enter"," "],Qq=["ArrowDown","PageUp","Home"],GP=["ArrowUp","PageDown","End"],Jq=[...Qq,...GP],eQ={ltr:[...V1,"ArrowRight"],rtl:[...V1,"ArrowLeft"]},tQ={ltr:["ArrowLeft"],rtl:["ArrowRight"]},gg="Menu",[md,nQ,rQ]=Kd(gg),[za,YP]=Mn(gg,[rQ,Fs,ng]),vg=Fs(),XP=ng(),[ZP,Us]=za(gg),[oQ,qd]=za(gg),iQ=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:o,onOpenChange:i,modal:s=!0}=e,l=vg(t),[u,f]=d.useState(null),p=d.useRef(!1),m=Ft(i),g=Tc(o);return d.useEffect(()=>{const y=()=>{p.current=!0,document.addEventListener("pointerdown",x,{capture:!0,once:!0}),document.addEventListener("pointermove",x,{capture:!0,once:!0})},x=()=>p.current=!1;return document.addEventListener("keydown",y,{capture:!0}),()=>{document.removeEventListener("keydown",y,{capture:!0}),document.removeEventListener("pointerdown",x,{capture:!0}),document.removeEventListener("pointermove",x,{capture:!0})}},[]),d.createElement(Fd,l,d.createElement(ZP,{scope:t,open:n,onOpenChange:m,content:u,onContentChange:f},d.createElement(oQ,{scope:t,onClose:d.useCallback(()=>m(!1),[m]),isUsingKeyboardRef:p,dir:g,modal:s},r)))},qP=d.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,o=vg(n);return d.createElement(Wm,Y({},o,r,{ref:t}))}),QP="MenuPortal",[sQ,JP]=za(QP,{forceMount:void 0}),aQ=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:o}=e,i=Us(QP,t);return d.createElement(sQ,{scope:t,forceMount:n},d.createElement(Sn,{present:n||i.open},d.createElement(jd,{asChild:!0,container:o},r)))},bo="MenuContent",[lQ,rb]=za(bo),cQ=d.forwardRef((e,t)=>{const n=JP(bo,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,i=Us(bo,e.__scopeMenu),s=qd(bo,e.__scopeMenu);return d.createElement(md.Provider,{scope:e.__scopeMenu},d.createElement(Sn,{present:r||i.open},d.createElement(md.Slot,{scope:e.__scopeMenu},s.modal?d.createElement(uQ,Y({},o,{ref:t})):d.createElement(dQ,Y({},o,{ref:t})))))}),uQ=d.forwardRef((e,t)=>{const n=Us(bo,e.__scopeMenu),r=d.useRef(null),o=Ue(t,r);return d.useEffect(()=>{const i=r.current;if(i)return Jm(i)},[]),d.createElement(ob,Y({},e,{ref:o,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:ue(e.onFocusOutside,i=>i.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)}))}),dQ=d.forwardRef((e,t)=>{const n=Us(bo,e.__scopeMenu);return d.createElement(ob,Y({},e,{ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)}))}),ob=d.forwardRef((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:o,onOpenAutoFocus:i,onCloseAutoFocus:s,disableOutsidePointerEvents:l,onEntryFocus:u,onEscapeKeyDown:f,onPointerDownOutside:p,onFocusOutside:m,onInteractOutside:g,onDismiss:y,disableOutsideScroll:x,...S}=e,E=Us(bo,n),_=qd(bo,n),b=vg(n),C=XP(n),R=nQ(n),[P,O]=d.useState(null),A=d.useRef(null),D=Ue(t,A,E.onContentChange),B=d.useRef(0),V=d.useRef(""),J=d.useRef(0),G=d.useRef(null),se=d.useRef("right"),U=d.useRef(0),ne=x?Qm:d.Fragment,M=x?{as:Zo,allowPinchZoom:!0}:void 0,ee=X=>{var W,le;const pe=V.current+X,$e=R().filter(Re=>!Re.disabled),Ve=document.activeElement,We=(W=$e.find(Re=>Re.ref.current===Ve))===null||W===void 0?void 0:W.textValue,Ne=$e.map(Re=>Re.textValue),fe=kQ(Ne,pe,We),xe=(le=$e.find(Re=>Re.textValue===fe))===null||le===void 0?void 0:le.ref.current;(function Re(Me){V.current=Me,window.clearTimeout(B.current),Me!==""&&(B.current=window.setTimeout(()=>Re(""),1e3))})(pe),xe&&setTimeout(()=>xe.focus())};d.useEffect(()=>()=>window.clearTimeout(B.current),[]),Zm();const H=d.useCallback(X=>{var W,le;return se.current===((W=G.current)===null||W===void 0?void 0:W.side)&&PQ(X,(le=G.current)===null||le===void 0?void 0:le.area)},[]);return d.createElement(lQ,{scope:n,searchRef:V,onItemEnter:d.useCallback(X=>{H(X)&&X.preventDefault()},[H]),onItemLeave:d.useCallback(X=>{var W;H(X)||((W=A.current)===null||W===void 0||W.focus(),O(null))},[H]),onTriggerLeave:d.useCallback(X=>{H(X)&&X.preventDefault()},[H]),pointerGraceTimerRef:J,onPointerGraceIntentChange:d.useCallback(X=>{G.current=X},[])},d.createElement(ne,M,d.createElement(Xm,{asChild:!0,trapped:o,onMountAutoFocus:ue(i,X=>{var W;X.preventDefault(),(W=A.current)===null||W===void 0||W.focus()}),onUnmountAutoFocus:s},d.createElement(Ec,{asChild:!0,disableOutsidePointerEvents:l,onEscapeKeyDown:f,onPointerDownOutside:p,onFocusOutside:m,onInteractOutside:g,onDismiss:y},d.createElement(JT,Y({asChild:!0},C,{dir:_.dir,orientation:"vertical",loop:r,currentTabStopId:P,onCurrentTabStopIdChange:O,onEntryFocus:ue(u,X=>{_.isUsingKeyboardRef.current||X.preventDefault()})}),d.createElement(Hm,Y({role:"menu","aria-orientation":"vertical","data-state":iA(E.open),"data-radix-menu-content":"",dir:_.dir},b,S,{ref:D,style:{outline:"none",...S.style},onKeyDown:ue(S.onKeyDown,X=>{const le=X.target.closest("[data-radix-menu-content]")===X.currentTarget,pe=X.ctrlKey||X.altKey||X.metaKey,$e=X.key.length===1;le&&(X.key==="Tab"&&X.preventDefault(),!pe&&$e&&ee(X.key));const Ve=A.current;if(X.target!==Ve||!Jq.includes(X.key))return;X.preventDefault();const Ne=R().filter(fe=>!fe.disabled).map(fe=>fe.ref.current);GP.includes(X.key)&&Ne.reverse(),$Q(Ne)}),onBlur:ue(e.onBlur,X=>{X.currentTarget.contains(X.target)||(window.clearTimeout(B.current),V.current="")}),onPointerMove:ue(e.onPointerMove,gd(X=>{const W=X.target,le=U.current!==X.clientX;if(X.currentTarget.contains(W)&&le){const pe=X.clientX>U.current?"right":"left";se.current=pe,U.current=X.clientX}}))})))))))}),fQ=d.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return d.createElement(Ae.div,Y({},r,{ref:t}))}),W1="MenuItem",Y2="menu.itemSelect",ib=d.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...o}=e,i=d.useRef(null),s=qd(W1,e.__scopeMenu),l=rb(W1,e.__scopeMenu),u=Ue(t,i),f=d.useRef(!1),p=()=>{const m=i.current;if(!n&&m){const g=new CustomEvent(Y2,{bubbles:!0,cancelable:!0});m.addEventListener(Y2,y=>r==null?void 0:r(y),{once:!0}),dx(m,g),g.defaultPrevented?f.current=!1:s.onClose()}};return d.createElement(eA,Y({},o,{ref:u,disabled:n,onClick:ue(e.onClick,p),onPointerDown:m=>{var g;(g=e.onPointerDown)===null||g===void 0||g.call(e,m),f.current=!0},onPointerUp:ue(e.onPointerUp,m=>{var g;f.current||(g=m.currentTarget)===null||g===void 0||g.click()}),onKeyDown:ue(e.onKeyDown,m=>{const g=l.searchRef.current!=="";n||g&&m.key===" "||V1.includes(m.key)&&(m.currentTarget.click(),m.preventDefault())})}))}),eA=d.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:o,...i}=e,s=rb(W1,n),l=XP(n),u=d.useRef(null),f=Ue(t,u),[p,m]=d.useState(!1),[g,y]=d.useState("");return d.useEffect(()=>{const x=u.current;if(x){var S;y(((S=x.textContent)!==null&&S!==void 0?S:"").trim())}},[i.children]),d.createElement(md.ItemSlot,{scope:n,disabled:r,textValue:o??g},d.createElement(e3,Y({asChild:!0},l,{focusable:!r}),d.createElement(Ae.div,Y({role:"menuitem","data-highlighted":p?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0},i,{ref:f,onPointerMove:ue(e.onPointerMove,gd(x=>{r?s.onItemLeave(x):(s.onItemEnter(x),x.defaultPrevented||x.currentTarget.focus())})),onPointerLeave:ue(e.onPointerLeave,gd(x=>s.onItemLeave(x))),onFocus:ue(e.onFocus,()=>m(!0)),onBlur:ue(e.onBlur,()=>m(!1))}))))}),hQ=d.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...o}=e;return d.createElement(nA,{scope:e.__scopeMenu,checked:n},d.createElement(ib,Y({role:"menuitemcheckbox","aria-checked":am(n)?"mixed":n},o,{ref:t,"data-state":sb(n),onSelect:ue(o.onSelect,()=>r==null?void 0:r(am(n)?!0:!n),{checkForDefaultPrevented:!1})})))}),pQ="MenuRadioGroup",[$te,mQ]=za(pQ,{value:void 0,onValueChange:()=>{}}),gQ="MenuRadioItem",vQ=d.forwardRef((e,t)=>{const{value:n,...r}=e,o=mQ(gQ,e.__scopeMenu),i=n===o.value;return d.createElement(nA,{scope:e.__scopeMenu,checked:i},d.createElement(ib,Y({role:"menuitemradio","aria-checked":i},r,{ref:t,"data-state":sb(i),onSelect:ue(r.onSelect,()=>{var s;return(s=o.onValueChange)===null||s===void 0?void 0:s.call(o,n)},{checkForDefaultPrevented:!1})})))}),tA="MenuItemIndicator",[nA,yQ]=za(tA,{checked:!1}),wQ=d.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...o}=e,i=yQ(tA,n);return d.createElement(Sn,{present:r||am(i.checked)||i.checked===!0},d.createElement(Ae.span,Y({},o,{ref:t,"data-state":sb(i.checked)})))}),xQ=d.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return d.createElement(Ae.div,Y({role:"separator","aria-orientation":"horizontal"},r,{ref:t}))}),rA="MenuSub",[bQ,oA]=za(rA),SQ=e=>{const{__scopeMenu:t,children:n,open:r=!1,onOpenChange:o}=e,i=Us(rA,t),s=vg(t),[l,u]=d.useState(null),[f,p]=d.useState(null),m=Ft(o);return d.useEffect(()=>(i.open===!1&&m(!1),()=>m(!1)),[i.open,m]),d.createElement(Fd,s,d.createElement(ZP,{scope:t,open:r,onOpenChange:m,content:f,onContentChange:p},d.createElement(bQ,{scope:t,contentId:nr(),triggerId:nr(),trigger:l,onTriggerChange:u},n)))},Sh="MenuSubTrigger",_Q=d.forwardRef((e,t)=>{const n=Us(Sh,e.__scopeMenu),r=qd(Sh,e.__scopeMenu),o=oA(Sh,e.__scopeMenu),i=rb(Sh,e.__scopeMenu),s=d.useRef(null),{pointerGraceTimerRef:l,onPointerGraceIntentChange:u}=i,f={__scopeMenu:e.__scopeMenu},p=d.useCallback(()=>{s.current&&window.clearTimeout(s.current),s.current=null},[]);return d.useEffect(()=>p,[p]),d.useEffect(()=>{const m=l.current;return()=>{window.clearTimeout(m),u(null)}},[l,u]),d.createElement(qP,Y({asChild:!0},f),d.createElement(eA,Y({id:o.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":o.contentId,"data-state":iA(n.open)},e,{ref:Nm(t,o.onTriggerChange),onClick:m=>{var g;(g=e.onClick)===null||g===void 0||g.call(e,m),!(e.disabled||m.defaultPrevented)&&(m.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:ue(e.onPointerMove,gd(m=>{i.onItemEnter(m),!m.defaultPrevented&&!e.disabled&&!n.open&&!s.current&&(i.onPointerGraceIntentChange(null),s.current=window.setTimeout(()=>{n.onOpenChange(!0),p()},100))})),onPointerLeave:ue(e.onPointerLeave,gd(m=>{var g;p();const y=(g=n.content)===null||g===void 0?void 0:g.getBoundingClientRect();if(y){var x;const S=(x=n.content)===null||x===void 0?void 0:x.dataset.side,E=S==="right",_=E?-5:5,b=y[E?"left":"right"],C=y[E?"right":"left"];i.onPointerGraceIntentChange({area:[{x:m.clientX+_,y:m.clientY},{x:b,y:y.top},{x:C,y:y.top},{x:C,y:y.bottom},{x:b,y:y.bottom}],side:S}),window.clearTimeout(l.current),l.current=window.setTimeout(()=>i.onPointerGraceIntentChange(null),300)}else{if(i.onTriggerLeave(m),m.defaultPrevented)return;i.onPointerGraceIntentChange(null)}})),onKeyDown:ue(e.onKeyDown,m=>{const g=i.searchRef.current!=="";if(!(e.disabled||g&&m.key===" ")&&eQ[r.dir].includes(m.key)){var y;n.onOpenChange(!0),(y=n.content)===null||y===void 0||y.focus(),m.preventDefault()}})})))}),EQ="MenuSubContent",CQ=d.forwardRef((e,t)=>{const n=JP(bo,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,i=Us(bo,e.__scopeMenu),s=qd(bo,e.__scopeMenu),l=oA(EQ,e.__scopeMenu),u=d.useRef(null),f=Ue(t,u);return d.createElement(md.Provider,{scope:e.__scopeMenu},d.createElement(Sn,{present:r||i.open},d.createElement(md.Slot,{scope:e.__scopeMenu},d.createElement(ob,Y({id:l.contentId,"aria-labelledby":l.triggerId},o,{ref:f,align:"start",side:s.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:p=>{var m;s.isUsingKeyboardRef.current&&((m=u.current)===null||m===void 0||m.focus()),p.preventDefault()},onCloseAutoFocus:p=>p.preventDefault(),onFocusOutside:ue(e.onFocusOutside,p=>{p.target!==l.trigger&&i.onOpenChange(!1)}),onEscapeKeyDown:ue(e.onEscapeKeyDown,p=>{s.onClose(),p.preventDefault()}),onKeyDown:ue(e.onKeyDown,p=>{const m=p.currentTarget.contains(p.target),g=tQ[s.dir].includes(p.key);if(m&&g){var y;i.onOpenChange(!1),(y=l.trigger)===null||y===void 0||y.focus(),p.preventDefault()}})})))))});function iA(e){return e?"open":"closed"}function am(e){return e==="indeterminate"}function sb(e){return am(e)?"indeterminate":e?"checked":"unchecked"}function $Q(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function RQ(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function kQ(e,t,n){const o=t.length>1&&Array.from(t).every(f=>f===t[0])?t[0]:t,i=n?e.indexOf(n):-1;let s=RQ(e,Math.max(i,0));o.length===1&&(s=s.filter(f=>f!==n));const u=s.find(f=>f.toLowerCase().startsWith(o.toLowerCase()));return u!==n?u:void 0}function TQ(e,t){const{x:n,y:r}=e;let o=!1;for(let i=0,s=t.length-1;ir!=p>r&&n<(f-l)*(r-u)/(p-u)+l&&(o=!o)}return o}function PQ(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return TQ(n,t)}function gd(e){return t=>t.pointerType==="mouse"?e(t):void 0}const AQ=iQ,MQ=qP,OQ=aQ,NQ=cQ,DQ=fQ,IQ=ib,LQ=hQ,FQ=vQ,jQ=wQ,zQ=xQ,BQ=SQ,UQ=_Q,VQ=CQ,sA="DropdownMenu",[WQ,Rte]=Mn(sA,[YP]),_r=YP(),[HQ,aA]=WQ(sA),KQ=e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:o,defaultOpen:i,onOpenChange:s,modal:l=!0}=e,u=_r(t),f=d.useRef(null),[p=!1,m]=Zr({prop:o,defaultProp:i,onChange:s});return d.createElement(HQ,{scope:t,triggerId:nr(),triggerRef:f,contentId:nr(),open:p,onOpenChange:m,onOpenToggle:d.useCallback(()=>m(g=>!g),[m]),modal:l},d.createElement(AQ,Y({},u,{open:p,onOpenChange:m,dir:r,modal:l}),n))},GQ="DropdownMenuTrigger",YQ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...o}=e,i=aA(GQ,n),s=_r(n);return d.createElement(MQ,Y({asChild:!0},s),d.createElement(Ae.button,Y({type:"button",id:i.triggerId,"aria-haspopup":"menu","aria-expanded":i.open,"aria-controls":i.open?i.contentId:void 0,"data-state":i.open?"open":"closed","data-disabled":r?"":void 0,disabled:r},o,{ref:Nm(t,i.triggerRef),onPointerDown:ue(e.onPointerDown,l=>{!r&&l.button===0&&l.ctrlKey===!1&&(i.onOpenToggle(),i.open||l.preventDefault())}),onKeyDown:ue(e.onKeyDown,l=>{r||(["Enter"," "].includes(l.key)&&i.onOpenToggle(),l.key==="ArrowDown"&&i.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(l.key)&&l.preventDefault())})})))}),XQ=e=>{const{__scopeDropdownMenu:t,...n}=e,r=_r(t);return d.createElement(OQ,Y({},r,n))},ZQ="DropdownMenuContent",qQ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=aA(ZQ,n),i=_r(n),s=d.useRef(!1);return d.createElement(NQ,Y({id:o.contentId,"aria-labelledby":o.triggerId},i,r,{ref:t,onCloseAutoFocus:ue(e.onCloseAutoFocus,l=>{var u;s.current||(u=o.triggerRef.current)===null||u===void 0||u.focus(),s.current=!1,l.preventDefault()}),onInteractOutside:ue(e.onInteractOutside,l=>{const u=l.detail.originalEvent,f=u.button===0&&u.ctrlKey===!0,p=u.button===2||f;(!o.modal||p)&&(s.current=!0)}),style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}}))}),QQ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(DQ,Y({},o,r,{ref:t}))}),JQ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(IQ,Y({},o,r,{ref:t}))}),eJ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(LQ,Y({},o,r,{ref:t}))}),tJ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(FQ,Y({},o,r,{ref:t}))}),nJ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(jQ,Y({},o,r,{ref:t}))}),rJ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(zQ,Y({},o,r,{ref:t}))}),oJ=e=>{const{__scopeDropdownMenu:t,children:n,open:r,onOpenChange:o,defaultOpen:i}=e,s=_r(t),[l=!1,u]=Zr({prop:r,defaultProp:i,onChange:o});return d.createElement(BQ,Y({},s,{open:l,onOpenChange:u}),n)},iJ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(UQ,Y({},o,r,{ref:t}))}),sJ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(VQ,Y({},o,r,{ref:t,style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}}))}),aJ=KQ,lJ=YQ,cJ=XQ,lA=qQ,cA=QQ,uA=JQ,dA=eJ,fA=tJ,hA=nJ,pA=rJ,uJ=oJ,mA=iJ,gA=sJ,dJ=aJ,fJ=lJ,X2=uJ,H1=d.forwardRef(({className:e,inset:t,children:n,...r},o)=>v.jsxs(mA,{ref:o,className:_e("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",e),...r,children:[n,v.jsx(tz,{className:"ml-auto h-4 w-4"})]}));H1.displayName=mA.displayName;const K1=d.forwardRef(({className:e,...t},n)=>v.jsx(gA,{ref:n,className:_e("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...t}));K1.displayName=gA.displayName;const vA=d.forwardRef(({className:e,sideOffset:t=4,...n},r)=>v.jsx(cJ,{children:v.jsx(lA,{ref:r,sideOffset:t,className:_e("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md","data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),onCloseAutoFocus:o=>o.preventDefault(),...n})}));vA.displayName=lA.displayName;const fl=d.forwardRef(({className:e,inset:t,...n},r)=>v.jsx(uA,{ref:r,className:_e("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",e),...n}));fl.displayName=uA.displayName;const hJ=d.forwardRef(({className:e,children:t,checked:n,...r},o)=>v.jsxs(dA,{ref:o,className:_e("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),checked:n,...r,children:[v.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:v.jsx(hA,{children:v.jsx(xk,{className:"h-4 w-4"})})}),t]}));hJ.displayName=dA.displayName;const pJ=d.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(fA,{ref:r,className:_e("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[v.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:v.jsx(hA,{children:v.jsx(sz,{className:"h-4 w-4 fill-current"})})}),t]}));pJ.displayName=fA.displayName;const mJ=d.forwardRef(({className:e,inset:t,...n},r)=>v.jsx(cA,{ref:r,className:_e("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",e),...n}));mJ.displayName=cA.displayName;const gJ=d.forwardRef(({className:e,...t},n)=>v.jsx(pA,{ref:n,className:_e("-mx-1 my-1 h-px bg-muted",e),...t}));gJ.displayName=pA.displayName;const Z2={RemoveBG:{IconClass:GC,showName:"RemoveBG"},AnimeSeg:{IconClass:GC,showName:"Anime Segmentation"},RealESRGAN:{IconClass:Qk,showName:"RealESRGAN"},GFPGAN:{IconClass:YC,showName:"GFPGAN"},RestoreFormer:{IconClass:YC,showName:"RestoreFormer"},InteractiveSeg:{IconClass:rV,showName:"Interactive Segmentation"}},vJ=()=>{const[e,t,n,r,o]=bt(p=>[p.file,p.serverConfig.plugins,p.isPluginRunning,p.updateInteractiveSegState,p.runRenderablePlugin]),i=!e;if(t.length===0)return null;const s=(p,m)=>{m==="InteractiveSeg"?r({isInteractiveSeg:!0}):o(p,m)},l=()=>v.jsxs(X2,{children:[v.jsx(H1,{disabled:i,children:v.jsxs("div",{className:"flex gap-2 items-center",children:[v.jsx(Qk,{}),"RealESRGAN"]})}),v.jsxs(K1,{children:[v.jsx(fl,{onClick:()=>o(!1,"RealESRGAN",{upscale:2}),children:"upscale 2x"}),v.jsx(fl,{onClick:()=>o(!1,"RealESRGAN",{upscale:4}),children:"upscale 4x"})]})]},"RealESRGAN"),u=p=>{const{IconClass:m,showName:g}=Z2[p.name];return v.jsxs(X2,{children:[v.jsx(H1,{disabled:i,children:v.jsxs("div",{className:"flex gap-2 items-center",children:[v.jsx(m,{className:"p-1"}),g]})}),v.jsxs(K1,{children:[v.jsx(fl,{onClick:()=>s(!1,p.name),children:"Remove Background"}),v.jsx(fl,{onClick:()=>s(!0,p.name),children:"Generate Mask"})]})]},p.name)},f=()=>t.map(p=>{const{IconClass:m,showName:g}=Z2[p.name];return p.name==="RealESRGAN"?l():p.name==="RemoveBG"||p.name==="AnimeSeg"?u(p):v.jsx(fl,{onClick:()=>s(!1,p.name),disabled:i,children:v.jsxs("div",{className:"flex gap-2 items-center",children:[v.jsx(m,{className:"p-1"}),g]})},p.name)});return v.jsxs(dJ,{modal:!1,children:[v.jsx(fJ,{className:"border rounded-lg z-10 bg-background outline-none",tabIndex:-1,children:v.jsx(wn,{variant:"ghost",size:"icon",asChild:!0,className:"p-1.5",children:n?v.jsx("div",{role:"status",children:v.jsxs("svg",{"aria-hidden":"true",className:"w-5 h-5 animate-spin fill-primary",viewBox:"0 0 100 101",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[v.jsx("path",{d:"M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z",fill:"currentColor"}),v.jsx("path",{d:"M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z",fill:"currentFill"})]})}):v.jsx(KU,{strokeWidth:1})})}),v.jsx(vA,{side:"bottom",align:"start",children:f()})]})},yJ=Cx,wJ=xT,xJ=$x,yA=d.forwardRef(({className:e,...t},n)=>v.jsx(zd,{className:_e("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t,ref:n}));yA.displayName=zd.displayName;const bJ=Dm("fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=closed]:duration-200 data-[state=open]:duration-300",{variants:{side:{top:"inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",bottom:"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",left:"inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",right:"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm"}},defaultVariants:{side:"right"}}),wA=d.forwardRef(({side:e="right",className:t,children:n,...r},o)=>v.jsxs(xJ,{children:[v.jsx(yA,{}),v.jsx(Bd,{ref:o,className:_e(bJ({side:e}),t),...r,children:n})]}));wA.displayName=Bd.displayName;const xA=({className:e,...t})=>v.jsx("div",{className:_e("flex flex-col space-y-2 text-center sm:text-left",e),...t});xA.displayName="SheetHeader";const SJ=d.forwardRef(({className:e,...t},n)=>v.jsx(Ud,{ref:n,className:_e("text-lg font-semibold text-foreground",e),...t}));SJ.displayName=Ud.displayName;const _J=d.forwardRef(({className:e,...t},n)=>v.jsx(Vd,{ref:n,className:_e("text-sm text-muted-foreground",e),...t}));_J.displayName=Vd.displayName;const Ut=({children:e})=>v.jsx("div",{className:"flex justify-between items-center pr-2",children:e}),Pt=({text:e,toolTip:t="",url:n,htmlFor:r,disabled:o=!1})=>v.jsxs(Zk,{children:[v.jsx(qk,{asChild:!0,children:v.jsx(Qx,{htmlFor:r||e.toLowerCase().replace(" ","-"),className:"font-medium",disabled:o,children:e})}),t||n?v.jsxs(Sx,{className:"flex flex-col max-w-xs text-sm",side:"left",children:[v.jsx("p",{children:t}),n?v.jsx(wn,{variant:"link",className:"justify-end",children:v.jsx("a",{href:n,target:"_blank",children:"More info"})}):v.jsx(v.Fragment,{})]}):v.jsx(v.Fragment,{})]}),EJ=()=>{const[e,t]=bt(n=>[n.settings,n.updateSettings]);return v.jsxs("div",{className:"flex flex-col gap-4 mt-4",children:[v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{htmlFor:"steps",text:"Steps",toolTip:"The number of denoising steps. More denoising steps usually lead to a higher quality image at the expense of slower inference."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[30],min:1,max:100,step:1,value:[Math.floor(e.ldmSteps)],onValueChange:n=>t({ldmSteps:n[0]})}),v.jsx(Yn,{id:"steps",className:"w-[60px] rounded-full",numberValue:e.ldmSteps,allowFloat:!1,onNumberValueChange:n=>{t({ldmSteps:n})}})]})]}),v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Sampler"}),v.jsxs(Uo,{value:e.ldmSampler,onValueChange:n=>{t({ldmSampler:n})},children:[v.jsx(go,{className:"w-[100px]",children:v.jsx(Vo,{placeholder:"Select sampler"})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:Object.values(Qw).map(n=>v.jsx(yo,{value:n,children:n},n))})})]})]})]})},_h=({text:e,onClick:t})=>{const[n]=bt(r=>[r.settings.showExtender]);return v.jsx(wn,{variant:"outline",className:"p-1 h-8",disabled:!n,onClick:t,children:v.jsx("div",{className:"flex items-center gap-1",children:e})})},CJ=()=>{const[e,t,n,r,o,i,s,l,u,f,p]=bt(M=>[M.serverConfig.samplers,M.settings,M.paintByExampleFile,M.getIsProcessing(),M.updateSettings,M.runInpainting,M.updateAppState,M.updateExtenderByBuiltIn,M.updateExtenderDirection,M.adjustMask,M.clearMask]),[m,g]=Px(n),y=d.useRef(null);DT(y,()=>{y!=null&&y.current&&y.current.blur()});const x=M=>{M.key==="Enter"&&M.ctrlKey&&t.prompt.length!==0&&i()},S=()=>v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Cropper",toolTip:"Inpainting on part of image, improve inference speed and reduce memory usage."}),v.jsx(co,{id:"cropper",checked:t.showCropper,onCheckedChange:M=>{o({showCropper:M}),M&&o({showExtender:!1})}})]}),E=()=>t.model.support_controlnet?v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex justify-between items-center pr-2",children:[v.jsx(Pt,{text:"ControlNet",toolTip:"Using an additional conditioning image to control how an image is generated",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#controlnet"}),v.jsx(co,{id:"controlnet",checked:t.enableControlnet,onCheckedChange:M=>{o({enableControlnet:M})}})]}),v.jsx("div",{className:"flex flex-col gap-1",children:v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[100],min:1,max:100,step:1,disabled:!t.enableControlnet,value:[Math.floor(t.controlnetConditioningScale*100)],onValueChange:M=>o({controlnetConditioningScale:M[0]/100})}),v.jsx(Yn,{id:"controlnet-weight",className:"w-[60px] rounded-full",disabled:!t.enableControlnet,numberValue:t.controlnetConditioningScale,allowFloat:!1,onNumberValueChange:M=>{o({controlnetConditioningScale:M})}})]})}),v.jsx("div",{className:"pr-2",children:v.jsxs(Uo,{defaultValue:t.controlnetMethod,value:t.controlnetMethod,onValueChange:M=>{o({controlnetMethod:M})},disabled:!t.enableControlnet,children:[v.jsx(go,{children:v.jsx(Vo,{placeholder:"Select control method"})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:Object.values(t.model.controlnets).map(M=>v.jsx(yo,{value:M,children:M.split("/")[1]},M))})})]})})]}),v.jsx(gn,{})]}):null,_=()=>t.model.support_lcm_lora?v.jsxs(v.Fragment,{children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"LCM LoRA",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inference_with_lcm_lora",toolTip:"Enable quality image generation in typically 2-4 steps. Suggest disabling guidance_scale by setting it to 0. You can also try values between 1.0 and 2.0. When LCM Lora is enabled, LCMSampler will be used automatically."}),v.jsx(co,{id:"lcm-lora",checked:t.enableLCMLora,onCheckedChange:M=>{o({enableLCMLora:M})}})]}),v.jsx(gn,{})]}):null,b=()=>t.model.support_freeu?v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex justify-between items-center pr-2",children:[v.jsx(Pt,{text:"FreeU",toolTip:"FreeU is a technique for improving image quality. Different models may require different FreeU-specific hyperparameters, which can be viewed in the more info section.",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/freeu"}),v.jsx(co,{id:"freeu",checked:t.enableFreeu,onCheckedChange:M=>{o({enableFreeu:M})}})]}),v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex justify-center gap-6",children:[v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-s1",text:"s1",disabled:!t.enableFreeu}),v.jsx(Yn,{id:"freeu-s1",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.s1,allowFloat:!0,onNumberValueChange:M=>{o({freeuConfig:{...t.freeuConfig,s1:M}})}})]}),v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-s2",text:"s2",disabled:!t.enableFreeu}),v.jsx(Yn,{id:"freeu-s2",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.s2,allowFloat:!0,onNumberValueChange:M=>{o({freeuConfig:{...t.freeuConfig,s2:M}})}})]})]}),v.jsxs("div",{className:"flex justify-center gap-6",children:[v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-b1",text:"b1",disabled:!t.enableFreeu}),v.jsx(Yn,{id:"freeu-b1",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.b1,allowFloat:!0,onNumberValueChange:M=>{o({freeuConfig:{...t.freeuConfig,b1:M}})}})]}),v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-b2",text:"b2",disabled:!t.enableFreeu}),v.jsx(Yn,{id:"freeu-b2",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.b2,allowFloat:!0,onNumberValueChange:M=>{o({freeuConfig:{...t.freeuConfig,b2:M}})}})]})]})]}),v.jsx(gn,{})]}):null,C=()=>t.model.need_prompt?v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsx(Pt,{text:"Negative prompt",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#negative-prompt",toolTip:"Negative prompt guides the model away from generating certain things in an image"}),v.jsx("div",{className:"pl-2 pr-4",children:v.jsx(Dx,{ref:y,rows:4,onKeyUp:x,className:"max-h-[8rem] overflow-y-auto mb-2",placeholder:"",id:"negative-prompt",value:t.negativePrompt,onInput:M=>{M.preventDefault(),M.stopPropagation();const ee=M.target;o({negativePrompt:ee.value})}})})]}):null,R=()=>t.model.name!==XR?null:v.jsxs("div",{children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Example Image",toolTip:"An example image to guide image generation."}),v.jsx(f1,{tooltip:"Upload example image",onFileUpload:M=>{s({paintByExampleFile:M})},children:v.jsx(Jk,{})})]}),g?v.jsx("div",{className:"flex justify-center items-center",children:v.jsx("img",{src:m.src,alt:"example",className:"max-w-[200px] max-h-[200px] m-3"})}):v.jsx(v.Fragment,{}),v.jsx(wn,{variant:"default",className:"w-full",disabled:r||!g,onClick:()=>{i()},children:"Paint"})]}),P=()=>t.model.name!==uF?null:v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Image guidance scale",toolTip:"Push the generated image towards the inital image. Higher image guidance scale encourages generated images that are closely linked to the source image, usually at the expense of lower image quality.",url:"https://huggingface.co/docs/diffusers/main/en/api/pipelines/pix2pix"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[150],min:100,max:1e3,step:1,value:[Math.floor(t.p2pImageGuidanceScale*100)],onValueChange:M=>o({p2pImageGuidanceScale:M[0]/100})}),v.jsx(Yn,{id:"image-guidance-scale",className:"w-[60px] rounded-full",numberValue:t.p2pImageGuidanceScale,allowFloat:!0,onNumberValueChange:M=>{o({p2pImageGuidanceScale:M})}})]})]}),O=()=>t.model.support_strength?v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Strength",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#strength",toolTip:"Strength is a measure of how much noise is added to the base image, which influences how similar the output is to the base image. Higher value means more noise and more different from the base image"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[100],min:10,max:100,step:1,value:[Math.floor(t.sdStrength*100)],onValueChange:M=>o({sdStrength:M[0]/100})}),v.jsx(Yn,{id:"strength",className:"w-[60px] rounded-full",numberValue:t.sdStrength,allowFloat:!0,onNumberValueChange:M=>{o({sdStrength:M})}})]})]}):null,A=()=>t.model.support_outpainting?v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Extender",toolTip:"Perform outpainting on images to expand it's content."}),v.jsx(co,{id:"extender",checked:t.showExtender,onCheckedChange:M=>{o({showExtender:M}),M&&o({showCropper:!1})}})]}),v.jsxs(Ut,{children:[v.jsxs(Uo,{defaultValue:t.extenderDirection,value:t.extenderDirection,onValueChange:M=>{u(M)},children:[v.jsx(go,{className:"w-[65px] h-7",disabled:!t.showExtender,children:v.jsx(Vo,{placeholder:"Select axis"})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:Object.values(Ln).map(M=>v.jsx(yo,{value:M,children:M},M))})})]}),v.jsxs("div",{className:"flex gap-1 justify-center mt-0",children:[v.jsx(_h,{text:"1.25x",onClick:()=>l(t.extenderDirection,1.25)}),v.jsx(_h,{text:"1.5x",onClick:()=>l(t.extenderDirection,1.5)}),v.jsx(_h,{text:"1.75x",onClick:()=>l(t.extenderDirection,1.75)}),v.jsx(_h,{text:"2.0x",onClick:()=>l(t.extenderDirection,2)})]})]})]}),v.jsx(gn,{})]}):null,D=()=>t.model.name!==dF?null:v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Task",toolTip:"PowerPaint task. When using extender, image-outpainting task will be auto used. For object-removal and image-outpainting, it is recommended to set the guidance_scale at 10 or above."}),v.jsxs(Uo,{defaultValue:t.powerpaintTask,value:t.powerpaintTask,onValueChange:M=>{o({powerpaintTask:M})},disabled:t.showExtender,children:[v.jsx(go,{className:"w-[140px]",children:v.jsx(Vo,{placeholder:"Select task"})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:[Ol.text_guided,Ol.object_remove,Ol.shape_guided].map(M=>v.jsx(yo,{value:M,children:M},M))})})]})]}),B=()=>v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{htmlFor:"steps",text:"Steps",toolTip:"The number of denoising steps. More denoising steps usually lead to a higher quality image at the expense of slower inference."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[30],min:1,max:100,step:1,value:[Math.floor(t.sdSteps)],onValueChange:M=>o({sdSteps:M[0]})}),v.jsx(Yn,{id:"steps",className:"w-[60px] rounded-full",numberValue:t.sdSteps,allowFloat:!1,onNumberValueChange:M=>{o({sdSteps:M})}})]})]}),V=()=>v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Guidance scale",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#guidance-scale",toolTip:"Guidance scale affects how aligned the text prompt and generated image are. Higher value means the prompt and generated image are closely aligned, so the output is a stricter interpretation of the prompt"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[750],min:0,max:1500,step:1,value:[Math.floor(t.sdGuidanceScale*100)],onValueChange:M=>o({sdGuidanceScale:M[0]/100})}),v.jsx(Yn,{id:"guidance-scale",className:"w-[60px] rounded-full",numberValue:t.sdGuidanceScale,allowFloat:!0,onNumberValueChange:M=>{o({sdGuidanceScale:M})}})]})]}),J=()=>t.model.name===fF?null:v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Sampler"}),v.jsxs(Uo,{defaultValue:t.sdSampler,value:t.sdSampler,onValueChange:M=>{o({sdSampler:M})},children:[v.jsx(go,{className:"w-[175px] text-xs",children:v.jsx(Vo,{placeholder:"Select sampler"})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:e.map(M=>v.jsx(yo,{value:M,className:"text-xs",children:M},M))})})]})]}),G=()=>v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Seed",toolTip:"Using same parameters and a fixed seed can generate same result image."}),v.jsxs("div",{className:"flex gap-2 justify-center items-center",children:[v.jsx(co,{id:"seed",checked:t.seedFixed,onCheckedChange:M=>{o({seedFixed:M})}}),v.jsx(Yn,{id:"seed",className:"w-[100px]",disabled:!t.seedFixed,numberValue:t.seed,allowFloat:!1,onNumberValueChange:M=>{o({seed:M})}})]})]}),se=()=>v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Mask blur",toolTip:"How much to blur the mask before processing, in pixels. Make the generated inpainting boundaries appear more natural."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[t.sdMaskBlur],min:0,max:96,step:1,value:[Math.floor(t.sdMaskBlur)],onValueChange:M=>o({sdMaskBlur:M[0]})}),v.jsx(Yn,{id:"mask-blur",className:"w-[60px] rounded-full",numberValue:t.sdMaskBlur,allowFloat:!1,onNumberValueChange:M=>{o({sdMaskBlur:M})}})]})]}),U=()=>v.jsxs(v.Fragment,{children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Match histograms",toolTip:"Match the inpainting result histogram to the source image histogram",url:"https://github.com/Sanster/lama-cleaner/pull/143#issuecomment-1325859307"}),v.jsx(co,{id:"match-histograms",checked:t.sdMatchHistograms,onCheckedChange:M=>{o({sdMatchHistograms:M})}})]}),v.jsx(gn,{})]}),ne=()=>v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{htmlFor:"adjustMaskKernelSize",text:"Adjust Mask",toolTip:"Expand or shrink mask. Using the slider to adjust the kernel size for dilation or erosion."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[12],min:1,max:100,step:1,value:[Math.floor(t.adjustMaskKernelSize)],onValueChange:M=>o({adjustMaskKernelSize:M[0]})}),v.jsx(Yn,{id:"adjustMaskKernelSize",className:"w-[60px] rounded-full",numberValue:t.adjustMaskKernelSize,allowFloat:!1,onNumberValueChange:M=>{o({adjustMaskKernelSize:M})}})]}),v.jsxs(Ut,{children:[v.jsxs("div",{className:"flex gap-1 justify-start",children:[v.jsx(wn,{variant:"outline",className:"p-1 h-8",onClick:()=>f("expand"),disabled:r,children:v.jsx("div",{className:"flex items-center gap-1 select-none",children:"Expand"})}),v.jsx(wn,{variant:"outline",className:"p-1 h-8",onClick:()=>f("shrink"),disabled:r,children:v.jsx("div",{className:"flex items-center gap-1 select-none",children:"Shrink"})}),v.jsx(wn,{variant:"outline",className:"p-1 h-8",onClick:()=>f("reverse"),disabled:r,children:v.jsx("div",{className:"flex items-center gap-1 select-none",children:"Reverse"})})]}),v.jsx(wn,{variant:"outline",className:"p-1 h-8 justify-self-end",onClick:p,disabled:r,children:v.jsx("div",{className:"flex items-center gap-1 select-none",children:"Clear"})})]})]}),v.jsx(gn,{})]});return v.jsxs("div",{className:"flex flex-col gap-4 mt-4",children:[S(),A(),ne(),D(),B(),V(),P(),O(),J(),G(),C(),v.jsx(gn,{}),E(),_(),se(),U(),b(),R()]})},$J=()=>{const[e,t]=bt(n=>[n.settings,n.updateSettings]);return v.jsxs("div",{className:"flex flex-col gap-4 mt-4",children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"CV2 Flag",url:"https://docs.opencv.org/4.8.0/d7/d8b/group__photo__inpaint.html#gga8002a65f5a3328fbf15df81b842d3c3ca892824c38e258feb5e72f308a358d52e"}),v.jsxs(Uo,{value:e.cv2Flag,onValueChange:n=>{t({cv2Flag:n})},children:[v.jsx(go,{className:"w-[160px]",children:v.jsx(Vo,{placeholder:"Select flag"})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:Object.values(Jw).map(n=>v.jsx(yo,{value:n,children:n},n))})})]})]}),v.jsx(Pt,{text:"CV2 Radius",url:"https://docs.opencv.org/4.8.0/d7/d8b/group__photo__inpaint.html#gga8002a65f5a3328fbf15df81b842d3c3ca892824c38e258feb5e72f308a358d52e"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[5],min:1,max:100,step:1,value:[Math.floor(e.cv2Radius)],onValueChange:n=>t({cv2Radius:n[0]})}),v.jsx(Yn,{id:"cv2-radius",className:"w-[60px] rounded-full",numberValue:e.cv2Radius,allowFloat:!1,onNumberValueChange:n=>{t({cv2Radius:n})}})]})]})},RJ=()=>{const[e,t]=bt(i=>[i.settings,i.windowSize]),[n,r]=Nx(!0);if(Zn("c",()=>{r()}),e.model.name!==lC&&e.model.name!==cC&&e.model.model_type===fs)return null;const o=()=>e.model.name===lC?v.jsx(EJ,{}):e.model.name===cC?v.jsx($J,{}):v.jsx(CJ,{});return v.jsxs(yJ,{open:n,modal:!1,children:[v.jsx(wJ,{tabIndex:-1,className:"z-10 outline-none absolute top-[68px] right-6 rounded-lg border bg-background",children:v.jsx(wn,{variant:"ghost",size:"icon",asChild:!0,className:"p-1.5",onClick:r,children:v.jsx(GU,{strokeWidth:1})})}),v.jsxs(wA,{side:"right",className:"w-[300px] mt-[60px] outline-none pl-4 pr-1",onOpenAutoFocus:i=>i.preventDefault(),onPointerDownOutside:i=>i.preventDefault(),children:[v.jsxs(xA,{children:[v.jsxs(Ut,{children:[v.jsx("div",{className:"overflow-hidden mr-8",children:e.model.name.split("/")[e.model.name.split("/").length-1]}),v.jsx(wn,{variant:"ghost",size:"icon",className:"border h-6 w-6",onClick:r,children:v.jsx(YU,{strokeWidth:1})})]}),v.jsx(gn,{})]}),v.jsx(lg,{style:{height:t.height-160},className:"pr-3",children:o()})]})]})},Jo=Object.create(null);Jo.open="0";Jo.close="1";Jo.ping="2";Jo.pong="3";Jo.message="4";Jo.upgrade="5";Jo.noop="6";const op=Object.create(null);Object.keys(Jo).forEach(e=>{op[Jo[e]]=e});const G1={type:"error",data:"parser error"},bA=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",SA=typeof ArrayBuffer=="function",_A=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,ab=({type:e,data:t},n,r)=>bA&&t instanceof Blob?n?r(t):q2(t,r):SA&&(t instanceof ArrayBuffer||_A(t))?n?r(t):q2(new Blob([t]),r):r(Jo[e]+(t||"")),q2=(e,t)=>{const n=new FileReader;return n.onload=function(){const r=n.result.split(",")[1];t("b"+(r||""))},n.readAsDataURL(e)};function Q2(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let B0;function kJ(e,t){if(bA&&e.data instanceof Blob)return e.data.arrayBuffer().then(Q2).then(t);if(SA&&(e.data instanceof ArrayBuffer||_A(e.data)))return t(Q2(e.data));ab(e,!1,n=>{B0||(B0=new TextEncoder),t(B0.encode(n))})}const J2="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",_u=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let e=0;e{let t=e.length*.75,n=e.length,r,o=0,i,s,l,u;e[e.length-1]==="="&&(t--,e[e.length-2]==="="&&t--);const f=new ArrayBuffer(t),p=new Uint8Array(f);for(r=0;r>4,p[o++]=(s&15)<<4|l>>2,p[o++]=(l&3)<<6|u&63;return f},PJ=typeof ArrayBuffer=="function",lb=(e,t)=>{if(typeof e!="string")return{type:"message",data:EA(e,t)};const n=e.charAt(0);return n==="b"?{type:"message",data:AJ(e.substring(1),t)}:op[n]?e.length>1?{type:op[n],data:e.substring(1)}:{type:op[n]}:G1},AJ=(e,t)=>{if(PJ){const n=TJ(e);return EA(n,t)}else return{base64:!0,data:e}},EA=(e,t)=>{switch(t){case"blob":return e instanceof Blob?e:new Blob([e]);case"arraybuffer":default:return e instanceof ArrayBuffer?e:e.buffer}},CA="",MJ=(e,t)=>{const n=e.length,r=new Array(n);let o=0;e.forEach((i,s)=>{ab(i,!1,l=>{r[s]=l,++o===n&&t(r.join(CA))})})},OJ=(e,t)=>{const n=e.split(CA),r=[];for(let o=0;o{const r=n.length;let o;if(r<126)o=new Uint8Array(1),new DataView(o.buffer).setUint8(0,r);else if(r<65536){o=new Uint8Array(3);const i=new DataView(o.buffer);i.setUint8(0,126),i.setUint16(1,r)}else{o=new Uint8Array(9);const i=new DataView(o.buffer);i.setUint8(0,127),i.setBigUint64(1,BigInt(r))}e.data&&typeof e.data!="string"&&(o[0]|=128),t.enqueue(o),t.enqueue(n)})}})}let U0;function Eh(e){return e.reduce((t,n)=>t+n.length,0)}function Ch(e,t){if(e[0].length===t)return e.shift();const n=new Uint8Array(t);let r=0;for(let o=0;oMath.pow(2,21)-1){l.enqueue(G1);break}o=p*Math.pow(2,32)+f.getUint32(4),r=3}else{if(Eh(n)e){l.enqueue(G1);break}}}})}const $A=4;function qt(e){if(e)return IJ(e)}function IJ(e){for(var t in qt.prototype)e[t]=qt.prototype[t];return e}qt.prototype.on=qt.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this};qt.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this};qt.prototype.off=qt.prototype.removeListener=qt.prototype.removeAllListeners=qt.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,o=0;o(e.hasOwnProperty(r)&&(n[r]=e[r]),n),{})}const LJ=Br.setTimeout,FJ=Br.clearTimeout;function yg(e,t){t.useNativeTimers?(e.setTimeoutFn=LJ.bind(Br),e.clearTimeoutFn=FJ.bind(Br)):(e.setTimeoutFn=Br.setTimeout.bind(Br),e.clearTimeoutFn=Br.clearTimeout.bind(Br))}const jJ=1.33;function zJ(e){return typeof e=="string"?BJ(e):Math.ceil((e.byteLength||e.size)*jJ)}function BJ(e){let t=0,n=0;for(let r=0,o=e.length;r=57344?n+=3:(r++,n+=4);return n}function UJ(e){let t="";for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+="&"),t+=encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t}function VJ(e){let t={},n=e.split("&");for(let r=0,o=n.length;r0);return t}function TA(){const e=n$(+new Date);return e!==t$?(e$=0,t$=e):e+"."+n$(e$++)}for(;$h{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)};OJ(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,MJ(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]=TA()),!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 Xo(this.uri(),t)}doWrite(t,n){const r=this.request({method:"POST",data:t});r.on("success",n),r.on("error",(o,i)=>{this.onError("xhr post error",o,i)})}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}}class Xo extends qt{constructor(t,n){super(),yg(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=RA(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");n.xdomain=!!this.opts.xd;const r=this.xhr=new AA(n);try{r.open(this.method,this.uri,!0);try{if(this.opts.extraHeaders){r.setDisableHeaderCheck&&r.setDisableHeaderCheck(!0);for(let o in this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(o)&&r.setRequestHeader(o,this.opts.extraHeaders[o])}}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 o;r.readyState===3&&((o=this.opts.cookieJar)===null||o===void 0||o.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(o){this.setTimeoutFn(()=>{this.onError(o)},0);return}typeof document<"u"&&(this.index=Xo.requestsCount++,Xo.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=GJ,t)try{this.xhr.abort()}catch{}typeof document<"u"&&delete Xo.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()}}Xo.requestsCount=0;Xo.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",r$);else if(typeof addEventListener=="function"){const e="onpagehide"in Br?"pagehide":"unload";addEventListener(e,r$,!1)}}function r$(){for(let e in Xo.requests)Xo.requests.hasOwnProperty(e)&&Xo.requests[e].abort()}const ub=typeof Promise=="function"&&typeof Promise.resolve=="function"?t=>Promise.resolve().then(t):(t,n)=>n(t,0),Rh=Br.WebSocket||Br.MozWebSocket,o$=!0,ZJ="arraybuffer",i$=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class qJ extends cb{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=i$?{}:RA(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=o$&&!i$?n?new Rh(t,n):new Rh(t):new Rh(t,n,r)}catch(o){return this.emitReserved("error",o)}this.ws.binaryType=this.socket.binaryType,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{o$&&this.ws.send(i)}catch{}o&&ub(()=>{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]=TA()),this.supportsBinary||(n.b64=1),this.createUri(t,n)}check(){return!!Rh}}class QJ extends cb{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=DJ(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=t.readable.pipeThrough(n).getReader(),o=NJ();o.readable.pipeTo(t.writable),this.writer=o.writable.getWriter();const i=()=>{r.read().then(({done:l,value:u})=>{l||(this.onPacket(u),i())}).catch(l=>{})};i();const s={type:"open"};this.query.sid&&(s.data=`{"sid":"${this.query.sid}"}`),this.writer.write(s).then(()=>this.onOpen())})}))}write(t){this.writable=!1;for(let n=0;n{o&&ub(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;(t=this.transport)===null||t===void 0||t.close()}}const JJ={websocket:qJ,webtransport:QJ,polling:XJ},eee=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,tee=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function X1(e){if(e.length>2e3)throw"URI too long";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 o=eee.exec(e||""),i={},s=14;for(;s--;)i[tee[s]]=o[s]||"";return n!=-1&&r!=-1&&(i.source=t,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=nee(i,i.path),i.queryKey=ree(i,i.query),i}function nee(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 ree(e,t){const n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(r,o,i){o&&(n[o]=i)}),n}let MA=class hl extends qt{constructor(t,n={}){super(),this.binaryType=ZJ,this.writeBuffer=[],t&&typeof t=="object"&&(n=t,t=null),t?(t=X1(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=X1(n.host).host),yg(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=VJ(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=$A,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 JJ[t](r)}open(){let t;if(this.opts.rememberUpgrade&&hl.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;hl.priorWebsocketSuccess=!1;const o=()=>{r||(n.send([{type:"ping",data:"probe"}]),n.once("packet",m=>{if(!r)if(m.type==="pong"&&m.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",n),!n)return;hl.priorWebsocketSuccess=n.name==="websocket",this.transport.pause(()=>{r||this.readyState!=="closed"&&(p(),this.setTransport(n),n.send([{type:"upgrade"}]),this.emitReserved("upgrade",n),n=null,this.upgrading=!1,this.flush())})}else{const g=new Error("probe error");g.transport=n.name,this.emitReserved("upgradeError",g)}}))};function i(){r||(r=!0,p(),n.close(),n=null)}const s=m=>{const g=new Error("probe error: "+m);g.transport=n.name,i(),this.emitReserved("upgradeError",g)};function l(){s("transport closed")}function u(){s("socket closed")}function f(m){n&&m.name!==n.name&&i()}const p=()=>{n.removeListener("open",o),n.removeListener("error",s),n.removeListener("close",l),this.off("close",u),this.off("upgrading",f)};n.once("open",o),n.once("error",s),n.once("close",l),this.once("close",u),this.once("upgrading",f),this.upgrades.indexOf("webtransport")!==-1&&t!=="webtransport"?this.setTimeoutFn(()=>{r||n.open()},200):n.open()}onOpen(){if(this.readyState="open",hl.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,o){if(typeof n=="function"&&(o=n,n=void 0),typeof r=="function"&&(o=r,r=null),this.readyState==="closing"||this.readyState==="closed")return;r=r||{},r.compress=r.compress!==!1;const i={type:t,data:n,options:r};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),o&&this.once("flush",o),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){hl.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 o=t.length;for(;rtypeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,OA=Object.prototype.toString,aee=typeof Blob=="function"||typeof Blob<"u"&&OA.call(Blob)==="[object BlobConstructor]",lee=typeof File=="function"||typeof File<"u"&&OA.call(File)==="[object FileConstructor]";function db(e){return iee&&(e instanceof ArrayBuffer||see(e))||aee&&e instanceof Blob||lee&&e instanceof File}function ip(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(i),n.apply(this,[null,...s])}}emitWithAck(t,...n){const r=this.flags.timeout!==void 0||this._opts.ackTimeout!==void 0;return new Promise((o,i)=>{n.push((s,l)=>r?s?i(s):o(l):o(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((o,...i)=>r!==this._queue[0]?void 0:(o!==null?r.tryCount>this._opts.retries&&(this._queue.shift(),n&&n(o)):(this._queue.shift(),n&&n(null,...i)),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:lt.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 lt.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 lt.EVENT:case lt.BINARY_EVENT:this.onevent(t);break;case lt.ACK:case lt.BINARY_ACK:this.onack(t);break;case lt.DISCONNECT:this.ondisconnect();break;case lt.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(...o){r||(r=!0,n.packet({type:lt.ACK,id:t,data:o}))}}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:lt.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}Ac.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};Ac.prototype.reset=function(){this.attempts=0};Ac.prototype.setMin=function(e){this.ms=e};Ac.prototype.setMax=function(e){this.max=e};Ac.prototype.setJitter=function(e){this.jitter=e};class Q1 extends qt{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,yg(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 Ac({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(n.timeout==null?2e4:n.timeout),this._readyState="closed",this.uri=t;const o=n.parser||mee;this.encoder=new o.Encoder,this.decoder=new o.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 MA(this.uri,this.opts);const n=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;const o=fo(n,"open",function(){r.onopen(),t&&t()}),i=l=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",l),t?t(l):this.maybeReconnectOnOpen()},s=fo(n,"error",i);if(this._timeout!==!1){const l=this._timeout,u=this.setTimeoutFn(()=>{o(),i(new Error("timeout")),n.close()},l);this.opts.autoUnref&&u.unref(),this.subs.push(()=>{this.clearTimeoutFn(u)})}return this.subs.push(o),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(fo(t,"ping",this.onping.bind(this)),fo(t,"data",this.ondata.bind(this)),fo(t,"error",this.onerror.bind(this)),fo(t,"close",this.onclose.bind(this)),fo(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){ub(()=>{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 NA(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(o=>{o?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",o)):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 gu={};function sp(e,t){typeof e=="object"&&(t=e,e=void 0),t=t||{};const n=oee(e,t.path||"/socket.io"),r=n.source,o=n.id,i=n.path,s=gu[o]&&i in gu[o].nsps,l=t.forceNew||t["force new connection"]||t.multiplex===!1||s;let u;return l?u=new Q1(r,t):(gu[o]||(gu[o]=new Q1(r,t)),u=gu[o]),n.query&&!t.query&&(t.query=n.queryKey),u.socket(n.path,t)}Object.assign(sp,{Manager:Q1,Socket:NA,io:sp,connect:sp});const DA="Progress",wg=100,[vee,kte]=Mn(DA),[yee,wee]=vee(DA),IA=d.forwardRef((e,t)=>{const{__scopeProgress:n,value:r,max:o,getValueLabel:i=See,...s}=e,l=J1(o)?o:wg,u=FA(r,l)?r:null,f=lm(u)?i(u,l):void 0;return d.createElement(yee,{scope:n,value:u,max:l},d.createElement(Ae.div,Y({"aria-valuemax":l,"aria-valuemin":0,"aria-valuenow":lm(u)?u:void 0,"aria-valuetext":f,role:"progressbar","data-state":LA(u,l),"data-value":u??void 0,"data-max":l},s,{ref:t})))});IA.propTypes={max(e,t,n){const r=e[t],o=String(r);return r&&!J1(r)?new Error(_ee(o,n)):null},value(e,t,n){const r=e[t],o=String(r),i=J1(e.max)?e.max:wg;return r!=null&&!FA(r,i)?new Error(Eee(o,n)):null}};const xee="ProgressIndicator",bee=d.forwardRef((e,t)=>{var n;const{__scopeProgress:r,...o}=e,i=wee(xee,r);return d.createElement(Ae.div,Y({"data-state":LA(i.value,i.max),"data-value":(n=i.value)!==null&&n!==void 0?n:void 0,"data-max":i.max},o,{ref:t}))});function See(e,t){return`${Math.round(e/t*100)}%`}function LA(e,t){return e==null?"indeterminate":e===t?"complete":"loading"}function lm(e){return typeof e=="number"}function J1(e){return lm(e)&&!isNaN(e)&&e>0}function FA(e,t){return lm(e)&&!isNaN(e)&&e<=t&&e>=0}function _ee(e,t){return`Invalid prop \`max\` of value \`${e}\` supplied to \`${t}\`. Only numbers greater than 0 are valid max values. Defaulting to \`${wg}\`.`}function Eee(e,t){return`Invalid prop \`value\` of value \`${e}\` supplied to \`${t}\`. The \`value\` prop must be: + - a positive number + - less than the value passed to \`max\` (or ${wg} if no \`max\` prop is set) + - \`null\` if the progress is indeterminate. + +Defaulting to \`null\`.`}const jA=IA,Cee=bee,zA=d.forwardRef(({className:e,value:t,...n},r)=>v.jsx(jA,{ref:r,className:_e("relative h-2 w-full overflow-hidden rounded-full bg-primary/20",e),...n,children:v.jsx(Cee,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(t||0)}%)`}})}));zA.displayName=jA.displayName;const $ee="",Zi=sp($ee),Ree=()=>{const[e,t,n]=bt(u=>[u.settings,u.isInpainting,u.isSD()]),[r,o]=d.useState(!1),[i,s]=d.useState(0),l=Math.min(Math.round(i/e.sdSteps*100),100);return d.useEffect(()=>(Zi.on("connect",()=>{o(!0)}),Zi.on("disconnect",()=>{o(!1)}),Zi.on("diffusion_progress",u=>{u&&s(u.step+1)}),Zi.on("diffusion_finish",()=>{s(0)}),()=>{Zi.off("connect"),Zi.off("disconnect"),Zi.off("diffusion_progress"),Zi.off("diffusion_finish")}),[]),v.jsxs("div",{className:"z-10 fixed bg-background w-[220px] left-1/2 -translate-x-1/2 top-[68px] h-[32px] flex justify-center items-center gap-[18px] border-[1px] border-[solid] rounded-[14px] pl-[8px] pr-[8px]",style:{visibility:r&&t&&n?"visible":"hidden"},children:[v.jsx(zA,{value:l}),v.jsxs("div",{className:"w-[45px] flex justify-center font-nums",children:[l,"%"]})]})},kee=()=>{const[e,t]=bt(n=>[n.file,n.updateSettings]);return d.useEffect(()=>{(async()=>{const r=await Uj();t({model:r})})()},[]),v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"flex gap-3 absolute top-[68px] left-[24px] items-center",children:[v.jsx(vJ,{}),v.jsx(qq,{})]}),v.jsx(Wq,{}),v.jsx(Ree,{}),v.jsx(RJ,{}),e?v.jsx(Zq,{file:e}):v.jsx(v.Fragment,{})]})},Tee=()=>{const[e,t]=d.useState(window.innerWidth),n=d.useCallback(()=>{t(window.innerWidth)},[]);if(d.useEffect(()=>(window.addEventListener("resize",n),()=>{window.removeEventListener("resize",n)})),e<768)return"mobile";if(e>=768&&e<1224)return"tablet";if(e>=1224)return"desktop"};function Pee(e){const{onSelection:t}=e,[n]=d.useState(`file-upload-${Math.random().toString()}`),r=Tee();function o(i){if(!(!i||!i.type.match("image.*")))try{if(i.size>20*1024*1024)throw new Error("file too large");t(i)}catch(l){alert(`error: ${l.message}`)}}return v.jsx("div",{className:"absolute flex w-screen h-screen justify-center items-center pointer-events-none",children:v.jsx("label",{htmlFor:n,className:"grid bg-background border-[2px] border-[dashed] rounded-lg min-w-[600px] hover:bg-primary hover:text-primary-foreground pointer-events-auto",children:v.jsxs("div",{className:"grid p-16 w-full h-full",onDragOver:i=>{i.stopPropagation(),i.preventDefault()},children:[v.jsx("input",{className:"hidden",id:n,name:n,type:"file",onChange:i=>{var l;const s=(l=i.currentTarget.files)==null?void 0:l[0];s&&o(s)},accept:"image/png, image/jpeg"}),v.jsx("p",{className:"text-center",children:r==="desktop"?"Click here or drag an image file":"Tap here to load your picture"})]})})})}const BA="ToastProvider",[hb,Aee,Mee]=Kd("Toast"),[UA,Tte]=Mn("Toast",[Mee]),[Oee,xg]=UA(BA),VA=e=>{const{__scopeToast:t,label:n="Notification",duration:r=5e3,swipeDirection:o="right",swipeThreshold:i=50,children:s}=e,[l,u]=d.useState(null),[f,p]=d.useState(0),m=d.useRef(!1),g=d.useRef(!1);return d.createElement(hb.Provider,{scope:t},d.createElement(Oee,{scope:t,label:n,duration:r,swipeDirection:o,swipeThreshold:i,toastCount:f,viewport:l,onViewportChange:u,onToastAdd:d.useCallback(()=>p(y=>y+1),[]),onToastRemove:d.useCallback(()=>p(y=>y-1),[]),isFocusedToastEscapeKeyDownRef:m,isClosePausedRef:g},s))};VA.propTypes={label(e){if(e.label&&typeof e.label=="string"&&!e.label.trim()){const t=`Invalid prop \`label\` supplied to \`${BA}\`. Expected non-empty \`string\`.`;return new Error(t)}return null}};const Nee="ToastViewport",Dee=["F8"],ew="toast.viewportPause",tw="toast.viewportResume",Iee=d.forwardRef((e,t)=>{const{__scopeToast:n,hotkey:r=Dee,label:o="Notifications ({hotkey})",...i}=e,s=xg(Nee,n),l=Aee(n),u=d.useRef(null),f=d.useRef(null),p=d.useRef(null),m=d.useRef(null),g=Ue(t,m,s.onViewportChange),y=r.join("+").replace(/Key/g,"").replace(/Digit/g,""),x=s.toastCount>0;d.useEffect(()=>{const E=_=>{var b;r.every(R=>_[R]||_.code===R)&&((b=m.current)===null||b===void 0||b.focus())};return document.addEventListener("keydown",E),()=>document.removeEventListener("keydown",E)},[r]),d.useEffect(()=>{const E=u.current,_=m.current;if(x&&E&&_){const b=()=>{if(!s.isClosePausedRef.current){const O=new CustomEvent(ew);_.dispatchEvent(O),s.isClosePausedRef.current=!0}},C=()=>{if(s.isClosePausedRef.current){const O=new CustomEvent(tw);_.dispatchEvent(O),s.isClosePausedRef.current=!1}},R=O=>{!E.contains(O.relatedTarget)&&C()},P=()=>{E.contains(document.activeElement)||C()};return E.addEventListener("focusin",b),E.addEventListener("focusout",R),E.addEventListener("pointermove",b),E.addEventListener("pointerleave",P),window.addEventListener("blur",b),window.addEventListener("focus",C),()=>{E.removeEventListener("focusin",b),E.removeEventListener("focusout",R),E.removeEventListener("pointermove",b),E.removeEventListener("pointerleave",P),window.removeEventListener("blur",b),window.removeEventListener("focus",C)}}},[x,s.isClosePausedRef]);const S=d.useCallback(({tabbingDirection:E})=>{const b=l().map(C=>{const R=C.ref.current,P=[R,...Qee(R)];return E==="forwards"?P:P.reverse()});return(E==="forwards"?b.reverse():b).flat()},[l]);return d.useEffect(()=>{const E=m.current;if(E){const _=b=>{const C=b.altKey||b.ctrlKey||b.metaKey;if(b.key==="Tab"&&!C){const D=document.activeElement,B=b.shiftKey;if(b.target===E&&B){var P;(P=f.current)===null||P===void 0||P.focus();return}const G=S({tabbingDirection:B?"backwards":"forwards"}),se=G.findIndex(U=>U===D);if(V0(G.slice(se+1)))b.preventDefault();else{var O,A;B?(O=f.current)===null||O===void 0||O.focus():(A=p.current)===null||A===void 0||A.focus()}}};return E.addEventListener("keydown",_),()=>E.removeEventListener("keydown",_)}},[l,S]),d.createElement(EB,{ref:u,role:"region","aria-label":o.replace("{hotkey}",y),tabIndex:-1,style:{pointerEvents:x?void 0:"none"}},x&&d.createElement(a$,{ref:f,onFocusFromOutsideViewport:()=>{const E=S({tabbingDirection:"forwards"});V0(E)}}),d.createElement(hb.Slot,{scope:n},d.createElement(Ae.ol,Y({tabIndex:-1},i,{ref:g}))),x&&d.createElement(a$,{ref:p,onFocusFromOutsideViewport:()=>{const E=S({tabbingDirection:"backwards"});V0(E)}}))}),Lee="ToastFocusProxy",a$=d.forwardRef((e,t)=>{const{__scopeToast:n,onFocusFromOutsideViewport:r,...o}=e,i=xg(Lee,n);return d.createElement(Km,Y({"aria-hidden":!0,tabIndex:0},o,{ref:t,style:{position:"fixed"},onFocus:s=>{var l;const u=s.relatedTarget;!((l=i.viewport)!==null&&l!==void 0&&l.contains(u))&&r()}}))}),bg="Toast",Fee="toast.swipeStart",jee="toast.swipeMove",zee="toast.swipeCancel",Bee="toast.swipeEnd",Uee=d.forwardRef((e,t)=>{const{forceMount:n,open:r,defaultOpen:o,onOpenChange:i,...s}=e,[l=!0,u]=Zr({prop:r,defaultProp:o,onChange:i});return d.createElement(Sn,{present:n||l},d.createElement(WA,Y({open:l},s,{ref:t,onClose:()=>u(!1),onPause:Ft(e.onPause),onResume:Ft(e.onResume),onSwipeStart:ue(e.onSwipeStart,f=>{f.currentTarget.setAttribute("data-swipe","start")}),onSwipeMove:ue(e.onSwipeMove,f=>{const{x:p,y:m}=f.detail.delta;f.currentTarget.setAttribute("data-swipe","move"),f.currentTarget.style.setProperty("--radix-toast-swipe-move-x",`${p}px`),f.currentTarget.style.setProperty("--radix-toast-swipe-move-y",`${m}px`)}),onSwipeCancel:ue(e.onSwipeCancel,f=>{f.currentTarget.setAttribute("data-swipe","cancel"),f.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),f.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),f.currentTarget.style.removeProperty("--radix-toast-swipe-end-x"),f.currentTarget.style.removeProperty("--radix-toast-swipe-end-y")}),onSwipeEnd:ue(e.onSwipeEnd,f=>{const{x:p,y:m}=f.detail.delta;f.currentTarget.setAttribute("data-swipe","end"),f.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),f.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),f.currentTarget.style.setProperty("--radix-toast-swipe-end-x",`${p}px`),f.currentTarget.style.setProperty("--radix-toast-swipe-end-y",`${m}px`),u(!1)})})))}),[Vee,Wee]=UA(bg,{onClose(){}}),WA=d.forwardRef((e,t)=>{const{__scopeToast:n,type:r="foreground",duration:o,open:i,onClose:s,onEscapeKeyDown:l,onPause:u,onResume:f,onSwipeStart:p,onSwipeMove:m,onSwipeCancel:g,onSwipeEnd:y,...x}=e,S=xg(bg,n),[E,_]=d.useState(null),b=Ue(t,U=>_(U)),C=d.useRef(null),R=d.useRef(null),P=o||S.duration,O=d.useRef(0),A=d.useRef(P),D=d.useRef(0),{onToastAdd:B,onToastRemove:V}=S,J=Ft(()=>{var U;(E==null?void 0:E.contains(document.activeElement))&&((U=S.viewport)===null||U===void 0||U.focus()),s()}),G=d.useCallback(U=>{!U||U===1/0||(window.clearTimeout(D.current),O.current=new Date().getTime(),D.current=window.setTimeout(J,U))},[J]);d.useEffect(()=>{const U=S.viewport;if(U){const ne=()=>{G(A.current),f==null||f()},M=()=>{const ee=new Date().getTime()-O.current;A.current=A.current-ee,window.clearTimeout(D.current),u==null||u()};return U.addEventListener(ew,M),U.addEventListener(tw,ne),()=>{U.removeEventListener(ew,M),U.removeEventListener(tw,ne)}}},[S.viewport,P,u,f,G]),d.useEffect(()=>{i&&!S.isClosePausedRef.current&&G(P)},[i,P,S.isClosePausedRef,G]),d.useEffect(()=>(B(),()=>V()),[B,V]);const se=d.useMemo(()=>E?YA(E):null,[E]);return S.viewport?d.createElement(d.Fragment,null,se&&d.createElement(Hee,{__scopeToast:n,role:"status","aria-live":r==="foreground"?"assertive":"polite","aria-atomic":!0},se),d.createElement(Vee,{scope:n,onClose:J},Is.createPortal(d.createElement(hb.ItemSlot,{scope:n},d.createElement(_B,{asChild:!0,onEscapeKeyDown:ue(l,()=>{S.isFocusedToastEscapeKeyDownRef.current||J(),S.isFocusedToastEscapeKeyDownRef.current=!1})},d.createElement(Ae.li,Y({role:"status","aria-live":"off","aria-atomic":!0,tabIndex:0,"data-state":i?"open":"closed","data-swipe-direction":S.swipeDirection},x,{ref:b,style:{userSelect:"none",touchAction:"none",...e.style},onKeyDown:ue(e.onKeyDown,U=>{U.key==="Escape"&&(l==null||l(U.nativeEvent),U.nativeEvent.defaultPrevented||(S.isFocusedToastEscapeKeyDownRef.current=!0,J()))}),onPointerDown:ue(e.onPointerDown,U=>{U.button===0&&(C.current={x:U.clientX,y:U.clientY})}),onPointerMove:ue(e.onPointerMove,U=>{if(!C.current)return;const ne=U.clientX-C.current.x,M=U.clientY-C.current.y,ee=!!R.current,H=["left","right"].includes(S.swipeDirection),X=["left","up"].includes(S.swipeDirection)?Math.min:Math.max,W=H?X(0,ne):0,le=H?0:X(0,M),pe=U.pointerType==="touch"?10:2,$e={x:W,y:le},Ve={originalEvent:U,delta:$e};ee?(R.current=$e,kh(jee,m,Ve,{discrete:!1})):l$($e,S.swipeDirection,pe)?(R.current=$e,kh(Fee,p,Ve,{discrete:!1}),U.target.setPointerCapture(U.pointerId)):(Math.abs(ne)>pe||Math.abs(M)>pe)&&(C.current=null)}),onPointerUp:ue(e.onPointerUp,U=>{const ne=R.current,M=U.target;if(M.hasPointerCapture(U.pointerId)&&M.releasePointerCapture(U.pointerId),R.current=null,C.current=null,ne){const ee=U.currentTarget,H={originalEvent:U,delta:ne};l$(ne,S.swipeDirection,S.swipeThreshold)?kh(Bee,y,H,{discrete:!0}):kh(zee,g,H,{discrete:!0}),ee.addEventListener("click",X=>X.preventDefault(),{once:!0})}})})))),S.viewport))):null});WA.propTypes={type(e){if(e.type&&!["foreground","background"].includes(e.type)){const t=`Invalid prop \`type\` supplied to \`${bg}\`. Expected \`foreground | background\`.`;return new Error(t)}return null}};const Hee=e=>{const{__scopeToast:t,children:n,...r}=e,o=xg(bg,t),[i,s]=d.useState(!1),[l,u]=d.useState(!1);return Zee(()=>s(!0)),d.useEffect(()=>{const f=window.setTimeout(()=>u(!0),1e3);return()=>window.clearTimeout(f)},[]),l?null:d.createElement(jd,{asChild:!0},d.createElement(Km,r,i&&d.createElement(d.Fragment,null,o.label," ",n)))},Kee=d.forwardRef((e,t)=>{const{__scopeToast:n,...r}=e;return d.createElement(Ae.div,Y({},r,{ref:t}))}),Gee=d.forwardRef((e,t)=>{const{__scopeToast:n,...r}=e;return d.createElement(Ae.div,Y({},r,{ref:t}))}),Yee="ToastAction",HA=d.forwardRef((e,t)=>{const{altText:n,...r}=e;return n?d.createElement(GA,{altText:n,asChild:!0},d.createElement(KA,Y({},r,{ref:t}))):null});HA.propTypes={altText(e){return e.altText?null:new Error(`Missing prop \`altText\` expected on \`${Yee}\``)}};const Xee="ToastClose",KA=d.forwardRef((e,t)=>{const{__scopeToast:n,...r}=e,o=Wee(Xee,n);return d.createElement(GA,{asChild:!0},d.createElement(Ae.button,Y({type:"button"},r,{ref:t,onClick:ue(e.onClick,o.onClose)})))}),GA=d.forwardRef((e,t)=>{const{__scopeToast:n,altText:r,...o}=e;return d.createElement(Ae.div,Y({"data-radix-toast-announce-exclude":"","data-radix-toast-announce-alt":r||void 0},o,{ref:t}))});function YA(e){const t=[];return Array.from(e.childNodes).forEach(r=>{if(r.nodeType===r.TEXT_NODE&&r.textContent&&t.push(r.textContent),qee(r)){const o=r.ariaHidden||r.hidden||r.style.display==="none",i=r.dataset.radixToastAnnounceExclude==="";if(!o)if(i){const s=r.dataset.radixToastAnnounceAlt;s&&t.push(s)}else t.push(...YA(r))}}),t}function kh(e,t,n,{discrete:r}){const o=n.originalEvent.currentTarget,i=new CustomEvent(e,{bubbles:!0,cancelable:!0,detail:n});t&&o.addEventListener(e,t,{once:!0}),r?dx(o,i):o.dispatchEvent(i)}const l$=(e,t,n=0)=>{const r=Math.abs(e.x),o=Math.abs(e.y),i=r>o;return t==="left"||t==="right"?i&&r>n:!i&&o>n};function Zee(e=()=>{}){const t=Ft(e);An(()=>{let n=0,r=0;return n=window.requestAnimationFrame(()=>r=window.requestAnimationFrame(t)),()=>{window.cancelAnimationFrame(n),window.cancelAnimationFrame(r)}},[t])}function qee(e){return e.nodeType===e.ELEMENT_NODE}function Qee(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const o=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||o?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function V0(e){const t=document.activeElement;return e.some(n=>n===t?!0:(n.focus(),document.activeElement!==t))}const Jee=VA,XA=Iee,ZA=Uee,qA=Kee,QA=Gee,JA=HA,e6=KA,ete=Jee,t6=d.forwardRef(({className:e,...t},n)=>v.jsx(XA,{ref:n,className:_e("fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]",e),tabIndex:-1,...t}));t6.displayName=XA.displayName;const tte=Dm("group pointer-events-auto relative flex w-full items-center justify-between space-x-2 overflow-hidden rounded-md border p-4 pr-6 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full",{variants:{variant:{default:"border bg-background text-foreground",destructive:"destructive group border-destructive bg-destructive text-destructive-foreground"}},defaultVariants:{variant:"default"}}),n6=d.forwardRef(({className:e,variant:t,...n},r)=>v.jsx(ZA,{ref:r,className:_e(tte({variant:t}),e),tabIndex:-1,...n}));n6.displayName=ZA.displayName;const nte=d.forwardRef(({className:e,...t},n)=>v.jsx(JA,{ref:n,className:_e("inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium transition-colors hover:bg-secondary focus:outline-none focus:ring-1 focus:ring-ring disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive",e),tabIndex:-1,...t}));nte.displayName=JA.displayName;const r6=d.forwardRef(({className:e,...t},n)=>v.jsx(e6,{ref:n,className:_e("absolute right-1 top-1 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-1 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600",e),"toast-close":"",tabIndex:-1,...t,children:v.jsx(bk,{className:"h-4 w-4"})}));r6.displayName=e6.displayName;const o6=d.forwardRef(({className:e,...t},n)=>v.jsx(qA,{ref:n,className:_e("text-sm font-semibold [&+div]:text-xs",e),tabIndex:-1,...t}));o6.displayName=qA.displayName;const i6=d.forwardRef(({className:e,...t},n)=>v.jsx(QA,{ref:n,className:_e("text-sm opacity-90",e),...t,tabIndex:-1}));i6.displayName=QA.displayName;function rte(){const{toasts:e}=Id();return v.jsxs(ete,{children:[e.map(function({id:t,title:n,description:r,action:o,...i}){return v.jsxs(n6,{...i,children:[v.jsxs("div",{className:"grid gap-1",children:[n&&v.jsx(o6,{children:n}),r&&v.jsx(i6,{children:r})]}),o,v.jsx(r6,{})]},t)}),v.jsx(t6,{})]})}const ote=["image/jpeg","image/png","image/webp","image/bmp","image/tiff"];function ite(){const[e,t,n,r]=bt(g=>[g.file,g.updateAppState,g.setServerConfig,g.setFile]),o=Yj(),i=vH();d.useEffect(()=>{o&&r(o)},[o,r]),d.useEffect(()=>{t({windowSize:i})},[i]),d.useEffect(()=>{(async()=>{const y=await yk();n(y),y.isDesktop&&pF()})()},[]);const s=d.useRef(0),l=d.useCallback(g=>{g.preventDefault(),g.stopPropagation()},[]),u=d.useCallback(g=>{g.preventDefault(),g.stopPropagation(),s.current+=1},[]),f=d.useCallback(g=>{g.preventDefault(),g.stopPropagation(),s.current-=1,s.current>0},[]),p=d.useCallback(g=>{if(g.preventDefault(),g.stopPropagation(),g.dataTransfer.files&&g.dataTransfer.files.length>0){if(!(g.dataTransfer.files.length>1)){const y=g.dataTransfer.files[0],x=y.type;ote.includes(x)&&r(y)}g.dataTransfer.clearData()}},[]),m=d.useCallback(g=>{if(!g.clipboardData)return;const y=g.clipboardData.items,x=[].slice.call(y).filter(_=>_.type.indexOf("image")!==-1);if(x.length===0)return;g.preventDefault(),g.stopPropagation();const E=x[0].getAsFile();E&&r(E)},[]);return d.useEffect(()=>(window.addEventListener("dragenter",u),window.addEventListener("dragleave",f),window.addEventListener("dragover",l),window.addEventListener("drop",p),window.addEventListener("paste",m),function(){window.removeEventListener("dragenter",u),window.removeEventListener("dragleave",f),window.removeEventListener("dragover",l),window.removeEventListener("drop",p),window.removeEventListener("paste",m)})),v.jsxs("main",{className:"flex min-h-screen flex-col items-center justify-between w-full bg-[radial-gradient(circle_at_1px_1px,_#8e8e8e8e_1px,_transparent_0)] [background-size:20px_20px] bg-repeat",children:[v.jsx(rte,{}),v.jsx(nZ,{}),v.jsx(kee,{}),e?v.jsx(v.Fragment,{}):v.jsx(Pee,{onSelection:async g=>{r(g)}})]})}const cm=["light","dark"],pb="(prefers-color-scheme: dark)",ste=typeof window>"u",s6=d.createContext(void 0),ate=e=>d.useContext(s6)?je.createElement(d.Fragment,null,e.children):je.createElement(cte,e),lte=["light","dark"],cte=({forcedTheme:e,disableTransitionOnChange:t=!1,enableSystem:n=!0,enableColorScheme:r=!0,storageKey:o="theme",themes:i=lte,defaultTheme:s=n?"system":"light",attribute:l="data-theme",value:u,children:f,nonce:p})=>{const[m,g]=d.useState(()=>c$(o,s)),[y,x]=d.useState(()=>c$(o)),S=u?Object.values(u):i,E=d.useCallback(R=>{let P=R;if(!P)return;R==="system"&&n&&(P=u$());const O=u?u[P]:P,A=t?dte():null,D=document.documentElement;if(l==="class"?(D.classList.remove(...S),O&&D.classList.add(O)):O?D.setAttribute(l,O):D.removeAttribute(l),r){const B=cm.includes(s)?s:null,V=cm.includes(P)?P:B;D.style.colorScheme=V}A==null||A()},[]),_=d.useCallback(R=>{g(R);try{localStorage.setItem(o,R)}catch{}},[e]),b=d.useCallback(R=>{const P=u$(R);x(P),m==="system"&&n&&!e&&E("system")},[m,e]);d.useEffect(()=>{const R=window.matchMedia(pb);return R.addListener(b),b(R),()=>R.removeListener(b)},[b]),d.useEffect(()=>{const R=P=>{P.key===o&&_(P.newValue||s)};return window.addEventListener("storage",R),()=>window.removeEventListener("storage",R)},[_]),d.useEffect(()=>{E(e??m)},[e,m]);const C=d.useMemo(()=>({theme:m,setTheme:_,forcedTheme:e,resolvedTheme:m==="system"?y:m,themes:n?[...i,"system"]:i,systemTheme:n?y:void 0}),[m,_,e,y,n,i]);return je.createElement(s6.Provider,{value:C},je.createElement(ute,{forcedTheme:e,disableTransitionOnChange:t,enableSystem:n,enableColorScheme:r,storageKey:o,themes:i,defaultTheme:s,attribute:l,value:u,children:f,attrs:S,nonce:p}),f)},ute=d.memo(({forcedTheme:e,storageKey:t,attribute:n,enableSystem:r,enableColorScheme:o,defaultTheme:i,value:s,attrs:l,nonce:u})=>{const f=i==="system",p=n==="class"?`var d=document.documentElement,c=d.classList;c.remove(${l.map(x=>`'${x}'`).join(",")});`:`var d=document.documentElement,n='${n}',s='setAttribute';`,m=o?cm.includes(i)&&i?`if(e==='light'||e==='dark'||!e)d.style.colorScheme=e||'${i}'`:"if(e==='light'||e==='dark')d.style.colorScheme=e":"",g=(x,S=!1,E=!0)=>{const _=s?s[x]:x,b=S?x+"|| ''":`'${_}'`;let C="";return o&&E&&!S&&cm.includes(x)&&(C+=`d.style.colorScheme = '${x}';`),n==="class"?C+=S||_?`c.add(${b})`:"null":_&&(C+=`d[s](n,${b})`),C},y=e?`!function(){${p}${g(e)}}()`:r?`!function(){try{${p}var e=localStorage.getItem('${t}');if('system'===e||(!e&&${f})){var t='${pb}',m=window.matchMedia(t);if(m.media!==t||m.matches){${g("dark")}}else{${g("light")}}}else if(e){${s?`var x=${JSON.stringify(s)};`:""}${g(s?"x[e]":"e",!0)}}${f?"":"else{"+g(i,!1,!1)+"}"}${m}}catch(e){}}()`:`!function(){try{${p}var e=localStorage.getItem('${t}');if(e){${s?`var x=${JSON.stringify(s)};`:""}${g(s?"x[e]":"e",!0)}}else{${g(i,!1,!1)};}${m}}catch(t){}}();`;return je.createElement("script",{nonce:u,dangerouslySetInnerHTML:{__html:y}})},()=>!0),c$=(e,t)=>{if(ste)return;let n;try{n=localStorage.getItem(e)||void 0}catch{}return n||t},dte=()=>{const e=document.createElement("style");return e.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(e),()=>{window.getComputedStyle(document.body),setTimeout(()=>{document.head.removeChild(e)},1)}},u$=e=>(e||(e=window.matchMedia(pb)),e.matches?"dark":"light"),fte=new pL;W0.createRoot(document.getElementById("root")).render(v.jsx(je.StrictMode,{children:v.jsx(wL,{client:fte,children:v.jsx(ate,{defaultTheme:"dark",disableTransitionOnChange:!0,children:v.jsx(VU,{children:v.jsx(ite,{})})})})})); diff --git a/py/iopaint/web_app/assets/index-Tqq3L7kY.js b/py/iopaint/web_app/assets/index-Tqq3L7kY.js new file mode 100644 index 0000000..dd1d5aa --- /dev/null +++ b/py/iopaint/web_app/assets/index-Tqq3L7kY.js @@ -0,0 +1,165 @@ +var Nv=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)};var z=(e,t,n)=>(Nv(e,t,"read from private field"),n?n.call(e):t.get(e)),Te=(e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)},ye=(e,t,n,r)=>(Nv(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n);var Ff=(e,t,n,r)=>({set _(o){ye(e,t,o,n)},get _(){return z(e,t,r)}}),tt=(e,t,n)=>(Nv(e,t,"access private method"),n);function SD(e,t){for(var n=0;nr[o]})}}}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 o of document.querySelectorAll('link[rel="modulepreload"]'))r(o);new MutationObserver(o=>{for(const i of o)if(i.type==="childList")for(const s of i.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&r(s)}).observe(document,{childList:!0,subtree:!0});function n(o){const i={};return o.integrity&&(i.integrity=o.integrity),o.referrerPolicy&&(i.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?i.credentials="include":o.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(o){if(o.ep)return;o.ep=!0;const i=n(o);fetch(o.href,i)}})();var Yc=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function lm(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var v$={exports:{}},cm={},y$={exports:{}},it={};/** + * @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 bd=Symbol.for("react.element"),ED=Symbol.for("react.portal"),CD=Symbol.for("react.fragment"),$D=Symbol.for("react.strict_mode"),kD=Symbol.for("react.profiler"),RD=Symbol.for("react.provider"),TD=Symbol.for("react.context"),PD=Symbol.for("react.forward_ref"),AD=Symbol.for("react.suspense"),OD=Symbol.for("react.memo"),MD=Symbol.for("react.lazy"),LS=Symbol.iterator;function ND(e){return e===null||typeof e!="object"?null:(e=LS&&e[LS]||e["@@iterator"],typeof e=="function"?e:null)}var w$={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},x$=Object.assign,b$={};function fc(e,t,n){this.props=e,this.context=t,this.refs=b$,this.updater=n||w$}fc.prototype.isReactComponent={};fc.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")};fc.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function _$(){}_$.prototype=fc.prototype;function ew(e,t,n){this.props=e,this.context=t,this.refs=b$,this.updater=n||w$}var tw=ew.prototype=new _$;tw.constructor=ew;x$(tw,fc.prototype);tw.isPureReactComponent=!0;var FS=Array.isArray,S$=Object.prototype.hasOwnProperty,nw={current:null},E$={key:!0,ref:!0,__self:!0,__source:!0};function C$(e,t,n){var r,o={},i=null,s=null;if(t!=null)for(r in t.ref!==void 0&&(s=t.ref),t.key!==void 0&&(i=""+t.key),t)S$.call(t,r)&&!E$.hasOwnProperty(r)&&(o[r]=t[r]);var l=arguments.length-2;if(l===1)o.children=n;else if(1>>1,ge=K[le];if(0>>1;leo(We,W))Meo(fe,We)?(K[le]=fe,K[Me]=W,le=Me):(K[le]=We,K[Ue]=W,le=Ue);else if(Meo(fe,W))K[le]=fe,K[Me]=W,le=Me;else break e}}return Q}function o(K,Q){var W=K.sortIndex-Q.sortIndex;return W!==0?W:K.id-Q.id}if(typeof performance=="object"&&typeof performance.now=="function"){var i=performance;e.unstable_now=function(){return i.now()}}else{var s=Date,l=s.now();e.unstable_now=function(){return s.now()-l}}var u=[],d=[],h=1,m=null,g=3,y=!1,x=!1,_=!1,C=typeof setTimeout=="function"?setTimeout:null,S=typeof clearTimeout=="function"?clearTimeout:null,b=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function E(K){for(var Q=n(d);Q!==null;){if(Q.callback===null)r(d);else if(Q.startTime<=K)r(d),Q.sortIndex=Q.expirationTime,t(u,Q);else break;Q=n(d)}}function k(K){if(_=!1,E(K),!x)if(n(u)!==null)x=!0,L(P);else{var Q=n(d);Q!==null&&ie(k,Q.startTime-K)}}function P(K,Q){x=!1,_&&(_=!1,S(O),O=-1),y=!0;var W=g;try{for(E(Q),m=n(u);m!==null&&(!(m.expirationTime>Q)||K&&!J());){var le=m.callback;if(typeof le=="function"){m.callback=null,g=m.priorityLevel;var ge=le(m.expirationTime<=Q);Q=e.unstable_now(),typeof ge=="function"?m.callback=ge:m===n(u)&&r(u),E(Q)}else r(u);m=n(u)}if(m!==null)var Ve=!0;else{var Ue=n(d);Ue!==null&&ie(k,Ue.startTime-Q),Ve=!1}return Ve}finally{m=null,g=W,y=!1}}var M=!1,A=null,O=-1,F=5,V=-1;function J(){return!(e.unstable_now()-VK||125le?(K.sortIndex=W,t(d,K),n(u)===null&&K===n(d)&&(_?(S(O),O=-1):_=!0,ie(k,W-le))):(K.sortIndex=ge,t(u,K),x||y||(x=!0,L(P))),K},e.unstable_shouldYield=J,e.unstable_wrapCallback=function(K){var Q=g;return function(){var W=g;g=Q;try{return K.apply(this,arguments)}finally{g=W}}}})(T$);R$.exports=T$;var KD=R$.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 P$=f,yr=KD;function ce(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"),B0=Object.prototype.hasOwnProperty,YD=/^[: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]*$/,zS={},BS={};function GD(e){return B0.call(BS,e)?!0:B0.call(zS,e)?!1:YD.test(e)?BS[e]=!0:(zS[e]=!0,!1)}function XD(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 ZD(e,t,n,r){if(t===null||typeof t>"u"||XD(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 Un(e,t,n,r,o,i,s){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=o,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=i,this.removeEmptyString=s}var wn={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){wn[e]=new Un(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];wn[t]=new Un(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){wn[e]=new Un(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){wn[e]=new Un(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){wn[e]=new Un(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){wn[e]=new Un(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){wn[e]=new Un(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){wn[e]=new Un(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){wn[e]=new Un(e,5,!1,e.toLowerCase(),null,!1,!1)});var ow=/[\-:]([a-z])/g;function iw(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(ow,iw);wn[t]=new Un(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(ow,iw);wn[t]=new Un(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(ow,iw);wn[t]=new Un(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){wn[e]=new Un(e,1,!1,e.toLowerCase(),null,!1,!1)});wn.xlinkHref=new Un("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){wn[e]=new Un(e,1,!1,e.toLowerCase(),null,!0,!0)});function sw(e,t,n,r){var o=wn.hasOwnProperty(t)?wn[t]:null;(o!==null?o.type!==0:r||!(2l||o[s]!==i[l]){var u=` +`+o[s].replace(" at new "," at ");return e.displayName&&u.includes("")&&(u=u.replace("",e.displayName)),u}while(1<=s&&0<=l);break}}}finally{Lv=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?uu(e):""}function qD(e){switch(e.tag){case 5:return uu(e.type);case 16:return uu("Lazy");case 13:return uu("Suspense");case 19:return uu("SuspenseList");case 0:case 2:case 15:return e=Fv(e.type,!1),e;case 11:return e=Fv(e.type.render,!1),e;case 1:return e=Fv(e.type,!0),e;default:return""}}function H0(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 ll:return"Fragment";case al:return"Portal";case U0:return"Profiler";case aw:return"StrictMode";case V0:return"Suspense";case W0:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case M$:return(e.displayName||"Context")+".Consumer";case O$:return(e._context.displayName||"Context")+".Provider";case lw:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case cw:return t=e.displayName||null,t!==null?t:H0(e.type)||"Memo";case Ki:t=e._payload,e=e._init;try{return H0(e(t))}catch{}}return null}function QD(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 H0(t);case 8:return t===aw?"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 Ss(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function D$(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function JD(e){var t=D$(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 o=n.get,i=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return o.call(this)},set:function(s){r=""+s,i.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 Bf(e){e._valueTracker||(e._valueTracker=JD(e))}function I$(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=D$(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function oh(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 K0(e,t){var n=t.checked;return zt({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function VS(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=Ss(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 L$(e,t){t=t.checked,t!=null&&sw(e,"checked",t,!1)}function Y0(e,t){L$(e,t);var n=Ss(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")?G0(e,t.type,n):t.hasOwnProperty("defaultValue")&&G0(e,t.type,Ss(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function WS(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 G0(e,t,n){(t!=="number"||oh(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var du=Array.isArray;function bl(e,t,n,r){if(e=e.options,t){t={};for(var o=0;o"+t.valueOf().toString()+"",t=Uf.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function Ou(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var vu={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},e9=["Webkit","ms","Moz","O"];Object.keys(vu).forEach(function(e){e9.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),vu[t]=vu[e]})});function B$(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||vu.hasOwnProperty(e)&&vu[e]?(""+t).trim():t+"px"}function U$(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,o=B$(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,o):e[n]=o}}var t9=zt({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 q0(e,t){if(t){if(t9[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(ce(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(ce(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(ce(61))}if(t.style!=null&&typeof t.style!="object")throw Error(ce(62))}}function Q0(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 J0=null;function uw(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var ey=null,_l=null,Sl=null;function YS(e){if(e=Ed(e)){if(typeof ey!="function")throw Error(ce(280));var t=e.stateNode;t&&(t=hm(t),ey(e.stateNode,e.type,t))}}function V$(e){_l?Sl?Sl.push(e):Sl=[e]:_l=e}function W$(){if(_l){var e=_l,t=Sl;if(Sl=_l=null,YS(e),t)for(e=0;e>>=0,e===0?32:31-(f9(e)/p9|0)|0}var Vf=64,Wf=4194304;function fu(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 lh(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,o=e.suspendedLanes,i=e.pingedLanes,s=n&268435455;if(s!==0){var l=s&~o;l!==0?r=fu(l):(i&=s,i!==0&&(r=fu(i)))}else s=n&~o,s!==0?r=fu(s):i!==0&&(r=fu(i));if(r===0)return 0;if(t!==0&&t!==r&&!(t&o)&&(o=r&-r,i=t&-t,o>=i||o===16&&(i&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 _d(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-go(t),e[t]=n}function v9(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=wu),nE=" ",rE=!1;function uk(e,t){switch(e){case"keyup":return H9.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function dk(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var cl=!1;function Y9(e,t){switch(e){case"compositionend":return dk(t);case"keypress":return t.which!==32?null:(rE=!0,nE);case"textInput":return e=t.data,e===nE&&rE?null:e;default:return null}}function G9(e,t){if(cl)return e==="compositionend"||!yw&&uk(e,t)?(e=lk(),$p=mw=rs=null,cl=!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=aE(n)}}function mk(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?mk(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function gk(){for(var e=window,t=oh();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=oh(e.document)}return t}function ww(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 rI(e){var t=gk(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&mk(n.ownerDocument.documentElement,n)){if(r!==null&&ww(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 o=n.textContent.length,i=Math.min(r.start,o);r=r.end===void 0?i:Math.min(r.end,o),!e.extend&&i>r&&(o=r,r=i,i=o),o=lE(n,i);var s=lE(n,r);o&&s&&(e.rangeCount!==1||e.anchorNode!==o.node||e.anchorOffset!==o.offset||e.focusNode!==s.node||e.focusOffset!==s.offset)&&(t=t.createRange(),t.setStart(o.node,o.offset),e.removeAllRanges(),i>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,ul=null,sy=null,bu=null,ay=!1;function cE(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;ay||ul==null||ul!==oh(r)||(r=ul,"selectionStart"in r&&ww(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}),bu&&Fu(bu,r)||(bu=r,r=dh(sy,"onSelect"),0pl||(e.current=py[pl],py[pl]=null,pl--)}function $t(e,t){pl++,py[pl]=e.current,e.current=t}var Es={},Tn=Ps(Es),Jn=Ps(!1),ba=Es;function Kl(e,t){var n=e.type.contextTypes;if(!n)return Es;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var o={},i;for(i in n)o[i]=t[i];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=o),o}function er(e){return e=e.childContextTypes,e!=null}function ph(){At(Jn),At(Tn)}function gE(e,t,n){if(Tn.current!==Es)throw Error(ce(168));$t(Tn,t),$t(Jn,n)}function Ck(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var o in r)if(!(o in t))throw Error(ce(108,QD(e)||"Unknown",o));return zt({},n,r)}function hh(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||Es,ba=Tn.current,$t(Tn,e),$t(Jn,Jn.current),!0}function vE(e,t,n){var r=e.stateNode;if(!r)throw Error(ce(169));n?(e=Ck(e,t,ba),r.__reactInternalMemoizedMergedChildContext=e,At(Jn),At(Tn),$t(Tn,e)):At(Jn),$t(Jn,n)}var li=null,mm=!1,Qv=!1;function $k(e){li===null?li=[e]:li.push(e)}function mI(e){mm=!0,$k(e)}function As(){if(!Qv&&li!==null){Qv=!0;var e=0,t=xt;try{var n=li;for(xt=1;e>=s,o-=s,ci=1<<32-go(t)+o|n<O?(F=A,A=null):F=A.sibling;var V=g(S,A,E[O],k);if(V===null){A===null&&(A=F);break}e&&A&&V.alternate===null&&t(S,A),b=i(V,b,O),M===null?P=V:M.sibling=V,M=V,A=F}if(O===E.length)return n(S,A),Dt&&qs(S,O),P;if(A===null){for(;OO?(F=A,A=null):F=A.sibling;var J=g(S,A,V.value,k);if(J===null){A===null&&(A=F);break}e&&A&&J.alternate===null&&t(S,A),b=i(J,b,O),M===null?P=J:M.sibling=J,M=J,A=F}if(V.done)return n(S,A),Dt&&qs(S,O),P;if(A===null){for(;!V.done;O++,V=E.next())V=m(S,V.value,k),V!==null&&(b=i(V,b,O),M===null?P=V:M.sibling=V,M=V);return Dt&&qs(S,O),P}for(A=r(S,A);!V.done;O++,V=E.next())V=y(A,S,O,V.value,k),V!==null&&(e&&V.alternate!==null&&A.delete(V.key===null?O:V.key),b=i(V,b,O),M===null?P=V:M.sibling=V,M=V);return e&&A.forEach(function(G){return t(S,G)}),Dt&&qs(S,O),P}function C(S,b,E,k){if(typeof E=="object"&&E!==null&&E.type===ll&&E.key===null&&(E=E.props.children),typeof E=="object"&&E!==null){switch(E.$$typeof){case zf:e:{for(var P=E.key,M=b;M!==null;){if(M.key===P){if(P=E.type,P===ll){if(M.tag===7){n(S,M.sibling),b=o(M,E.props.children),b.return=S,S=b;break e}}else if(M.elementType===P||typeof P=="object"&&P!==null&&P.$$typeof===Ki&&EE(P)===M.type){n(S,M.sibling),b=o(M,E.props),b.ref=Jc(S,M,E),b.return=S,S=b;break e}n(S,M);break}else t(S,M);M=M.sibling}E.type===ll?(b=xa(E.props.children,S.mode,k,E.key),b.return=S,S=b):(k=Np(E.type,E.key,E.props,null,S.mode,k),k.ref=Jc(S,b,E),k.return=S,S=k)}return s(S);case al:e:{for(M=E.key;b!==null;){if(b.key===M)if(b.tag===4&&b.stateNode.containerInfo===E.containerInfo&&b.stateNode.implementation===E.implementation){n(S,b.sibling),b=o(b,E.children||[]),b.return=S,S=b;break e}else{n(S,b);break}else t(S,b);b=b.sibling}b=s0(E,S.mode,k),b.return=S,S=b}return s(S);case Ki:return M=E._init,C(S,b,M(E._payload),k)}if(du(E))return x(S,b,E,k);if(Gc(E))return _(S,b,E,k);qf(S,E)}return typeof E=="string"&&E!==""||typeof E=="number"?(E=""+E,b!==null&&b.tag===6?(n(S,b.sibling),b=o(b,E),b.return=S,S=b):(n(S,b),b=i0(E,S.mode,k),b.return=S,S=b),s(S)):n(S,b)}return C}var Gl=Nk(!0),Dk=Nk(!1),Cd={},zo=Ps(Cd),Uu=Ps(Cd),Vu=Ps(Cd);function oa(e){if(e===Cd)throw Error(ce(174));return e}function Rw(e,t){switch($t(Vu,t),$t(Uu,e),$t(zo,Cd),e=t.nodeType,e){case 9:case 11:t=(t=t.documentElement)?t.namespaceURI:Z0(null,"");break;default:e=e===8?t.parentNode:t,t=e.namespaceURI||null,e=e.tagName,t=Z0(t,e)}At(zo),$t(zo,t)}function Xl(){At(zo),At(Uu),At(Vu)}function Ik(e){oa(Vu.current);var t=oa(zo.current),n=Z0(t,e.type);t!==n&&($t(Uu,e),$t(zo,n))}function Tw(e){Uu.current===e&&(At(zo),At(Uu))}var Lt=Ps(0);function xh(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 Jv=[];function Pw(){for(var e=0;en?n:4,e(!0);var r=e0.transition;e0.transition={};try{e(!1),t()}finally{xt=n,e0.transition=r}}function Qk(){return Gr().memoizedState}function wI(e,t,n){var r=ys(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},Jk(e))eR(t,n);else if(n=Pk(e,t,n,r),n!==null){var o=jn();vo(n,e,r,o),tR(n,t,r)}}function xI(e,t,n){var r=ys(e),o={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(Jk(e))eR(t,o);else{var i=e.alternate;if(e.lanes===0&&(i===null||i.lanes===0)&&(i=t.lastRenderedReducer,i!==null))try{var s=t.lastRenderedState,l=i(s,n);if(o.hasEagerState=!0,o.eagerState=l,wo(l,s)){var u=t.interleaved;u===null?(o.next=o,$w(t)):(o.next=u.next,u.next=o),t.interleaved=o;return}}catch{}finally{}n=Pk(e,t,o,r),n!==null&&(o=jn(),vo(n,e,r,o),tR(n,t,r))}}function Jk(e){var t=e.alternate;return e===jt||t!==null&&t===jt}function eR(e,t){_u=bh=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function tR(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,fw(e,n)}}var _h={readContext:Yr,useCallback:En,useContext:En,useEffect:En,useImperativeHandle:En,useInsertionEffect:En,useLayoutEffect:En,useMemo:En,useReducer:En,useRef:En,useState:En,useDebugValue:En,useDeferredValue:En,useTransition:En,useMutableSource:En,useSyncExternalStore:En,useId:En,unstable_isNewReconciler:!1},bI={readContext:Yr,useCallback:function(e,t){return ko().memoizedState=[e,t===void 0?null:t],e},useContext:Yr,useEffect:$E,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,Pp(4194308,4,Yk.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Pp(4194308,4,e,t)},useInsertionEffect:function(e,t){return Pp(4,2,e,t)},useMemo:function(e,t){var n=ko();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=ko();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=wI.bind(null,jt,e),[r.memoizedState,e]},useRef:function(e){var t=ko();return e={current:e},t.memoizedState=e},useState:CE,useDebugValue:Dw,useDeferredValue:function(e){return ko().memoizedState=e},useTransition:function(){var e=CE(!1),t=e[0];return e=yI.bind(null,e[1]),ko().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=jt,o=ko();if(Dt){if(n===void 0)throw Error(ce(407));n=n()}else{if(n=t(),dn===null)throw Error(ce(349));Sa&30||jk(r,t,n)}o.memoizedState=n;var i={value:n,getSnapshot:t};return o.queue=i,$E(Bk.bind(null,r,i,e),[e]),r.flags|=2048,Ku(9,zk.bind(null,r,i,n,t),void 0,null),n},useId:function(){var e=ko(),t=dn.identifierPrefix;if(Dt){var n=ui,r=ci;n=(r&~(1<<32-go(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=Wu++,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[Oo]=t,e[Bu]=r,uR(e,t,!1,!1),t.stateNode=e;e:{switch(s=Q0(n,r),n){case"dialog":Tt("cancel",e),Tt("close",e),o=r;break;case"iframe":case"object":case"embed":Tt("load",e),o=r;break;case"video":case"audio":for(o=0;oql&&(t.flags|=128,r=!0,eu(i,!1),t.lanes=4194304)}else{if(!r)if(e=xh(s),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),eu(i,!0),i.tail===null&&i.tailMode==="hidden"&&!s.alternate&&!Dt)return Cn(t),null}else 2*Zt()-i.renderingStartTime>ql&&n!==1073741824&&(t.flags|=128,r=!0,eu(i,!1),t.lanes=4194304);i.isBackwards?(s.sibling=t.child,t.child=s):(n=i.last,n!==null?n.sibling=s:t.child=s,i.last=s)}return i.tail!==null?(t=i.tail,i.rendering=t,i.tail=t.sibling,i.renderingStartTime=Zt(),t.sibling=null,n=Lt.current,$t(Lt,r?n&1|2:n&1),t):(Cn(t),null);case 22:case 23:return Bw(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?fr&1073741824&&(Cn(t),t.subtreeFlags&6&&(t.flags|=8192)):Cn(t),null;case 24:return null;case 25:return null}throw Error(ce(156,t.tag))}function TI(e,t){switch(bw(t),t.tag){case 1:return er(t.type)&&ph(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Xl(),At(Jn),At(Tn),Pw(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return Tw(t),null;case 13:if(At(Lt),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(ce(340));Yl()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return At(Lt),null;case 4:return Xl(),null;case 10:return Cw(t.type._context),null;case 22:case 23:return Bw(),null;case 24:return null;default:return null}}var Jf=!1,kn=!1,PI=typeof WeakSet=="function"?WeakSet:Set,Se=null;function vl(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){Wt(e,t,r)}else n.current=null}function Cy(e,t,n){try{n()}catch(r){Wt(e,t,r)}}var DE=!1;function AI(e,t){if(ly=ch,e=gk(),ww(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 o=r.anchorOffset,i=r.focusNode;r=r.focusOffset;try{n.nodeType,i.nodeType}catch{n=null;break e}var s=0,l=-1,u=-1,d=0,h=0,m=e,g=null;t:for(;;){for(var y;m!==n||o!==0&&m.nodeType!==3||(l=s+o),m!==i||r!==0&&m.nodeType!==3||(u=s+r),m.nodeType===3&&(s+=m.nodeValue.length),(y=m.firstChild)!==null;)g=m,m=y;for(;;){if(m===e)break t;if(g===n&&++d===o&&(l=s),g===i&&++h===r&&(u=s),(y=m.nextSibling)!==null)break;m=g,g=m.parentNode}m=y}n=l===-1||u===-1?null:{start:l,end:u}}else n=null}n=n||{start:0,end:0}}else n=null;for(cy={focusedElem:e,selectionRange:n},ch=!1,Se=t;Se!==null;)if(t=Se,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,Se=e;else for(;Se!==null;){t=Se;try{var x=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(x!==null){var _=x.memoizedProps,C=x.memoizedState,S=t.stateNode,b=S.getSnapshotBeforeUpdate(t.elementType===t.type?_:io(t.type,_),C);S.__reactInternalSnapshotBeforeUpdate=b}break;case 3:var E=t.stateNode.containerInfo;E.nodeType===1?E.textContent="":E.nodeType===9&&E.documentElement&&E.removeChild(E.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(ce(163))}}catch(k){Wt(t,t.return,k)}if(e=t.sibling,e!==null){e.return=t.return,Se=e;break}Se=t.return}return x=DE,DE=!1,x}function Su(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var o=r=r.next;do{if((o.tag&e)===e){var i=o.destroy;o.destroy=void 0,i!==void 0&&Cy(t,n,i)}o=o.next}while(o!==r)}}function ym(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 $y(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 pR(e){var t=e.alternate;t!==null&&(e.alternate=null,pR(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Oo],delete t[Bu],delete t[fy],delete t[pI],delete t[hI])),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 hR(e){return e.tag===5||e.tag===3||e.tag===4}function IE(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||hR(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 ky(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=fh));else if(r!==4&&(e=e.child,e!==null))for(ky(e,t,n),e=e.sibling;e!==null;)ky(e,t,n),e=e.sibling}function Ry(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(Ry(e,t,n),e=e.sibling;e!==null;)Ry(e,t,n),e=e.sibling}var mn=null,lo=!1;function ji(e,t,n){for(n=n.child;n!==null;)mR(e,t,n),n=n.sibling}function mR(e,t,n){if(jo&&typeof jo.onCommitFiberUnmount=="function")try{jo.onCommitFiberUnmount(um,n)}catch{}switch(n.tag){case 5:kn||vl(n,t);case 6:var r=mn,o=lo;mn=null,ji(e,t,n),mn=r,lo=o,mn!==null&&(lo?(e=mn,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):mn.removeChild(n.stateNode));break;case 18:mn!==null&&(lo?(e=mn,n=n.stateNode,e.nodeType===8?qv(e.parentNode,n):e.nodeType===1&&qv(e,n),Iu(e)):qv(mn,n.stateNode));break;case 4:r=mn,o=lo,mn=n.stateNode.containerInfo,lo=!0,ji(e,t,n),mn=r,lo=o;break;case 0:case 11:case 14:case 15:if(!kn&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){o=r=r.next;do{var i=o,s=i.destroy;i=i.tag,s!==void 0&&(i&2||i&4)&&Cy(n,t,s),o=o.next}while(o!==r)}ji(e,t,n);break;case 1:if(!kn&&(vl(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(l){Wt(n,t,l)}ji(e,t,n);break;case 21:ji(e,t,n);break;case 22:n.mode&1?(kn=(r=kn)||n.memoizedState!==null,ji(e,t,n),kn=r):ji(e,t,n);break;default:ji(e,t,n)}}function LE(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new PI),t.forEach(function(r){var o=zI.bind(null,e,r);n.has(r)||(n.add(r),r.then(o,o))})}}function ro(e,t){var n=t.deletions;if(n!==null)for(var r=0;ro&&(o=s),r&=~i}if(r=o,r=Zt()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*MI(r/1960))-r,10e?16:e,os===null)var r=!1;else{if(e=os,os=null,Ch=0,dt&6)throw Error(ce(331));var o=dt;for(dt|=4,Se=e.current;Se!==null;){var i=Se,s=i.child;if(Se.flags&16){var l=i.deletions;if(l!==null){for(var u=0;uZt()-jw?wa(e,0):Fw|=n),tr(e,t)}function SR(e,t){t===0&&(e.mode&1?(t=Wf,Wf<<=1,!(Wf&130023424)&&(Wf=4194304)):t=1);var n=jn();e=gi(e,t),e!==null&&(_d(e,t,n),tr(e,n))}function jI(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),SR(e,n)}function zI(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,o=e.memoizedState;o!==null&&(n=o.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(ce(314))}r!==null&&r.delete(t),SR(e,n)}var ER;ER=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||Jn.current)Qn=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return Qn=!1,kI(e,t,n);Qn=!!(e.flags&131072)}else Qn=!1,Dt&&t.flags&1048576&&kk(t,gh,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;Ap(e,t),e=t.pendingProps;var o=Kl(t,Tn.current);Cl(t,n),o=Ow(null,t,r,e,o,n);var i=Mw();return t.flags|=1,typeof o=="object"&&o!==null&&typeof o.render=="function"&&o.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,er(r)?(i=!0,hh(t)):i=!1,t.memoizedState=o.state!==null&&o.state!==void 0?o.state:null,kw(t),o.updater=gm,t.stateNode=o,o._reactInternals=t,yy(t,r,e,n),t=by(null,t,r,!0,i,n)):(t.tag=0,Dt&&i&&xw(t),Dn(null,t,o,n),t=t.child),t;case 16:r=t.elementType;e:{switch(Ap(e,t),e=t.pendingProps,o=r._init,r=o(r._payload),t.type=r,o=t.tag=UI(r),e=io(r,e),o){case 0:t=xy(null,t,r,e,n);break e;case 1:t=OE(null,t,r,e,n);break e;case 11:t=PE(null,t,r,e,n);break e;case 14:t=AE(null,t,r,io(r.type,e),n);break e}throw Error(ce(306,r,""))}return t;case 0:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),xy(e,t,r,o,n);case 1:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),OE(e,t,r,o,n);case 3:e:{if(aR(t),e===null)throw Error(ce(387));r=t.pendingProps,i=t.memoizedState,o=i.element,Ak(e,t),wh(t,r,null,n);var s=t.memoizedState;if(r=s.element,i.isDehydrated)if(i={element:r,isDehydrated:!1,cache:s.cache,pendingSuspenseBoundaries:s.pendingSuspenseBoundaries,transitions:s.transitions},t.updateQueue.baseState=i,t.memoizedState=i,t.flags&256){o=Zl(Error(ce(423)),t),t=ME(e,t,r,n,o);break e}else if(r!==o){o=Zl(Error(ce(424)),t),t=ME(e,t,r,n,o);break e}else for(mr=ms(t.stateNode.containerInfo.firstChild),gr=t,Dt=!0,po=null,n=Dk(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(Yl(),r===o){t=vi(e,t,n);break e}Dn(e,t,r,n)}t=t.child}return t;case 5:return Ik(t),e===null&&my(t),r=t.type,o=t.pendingProps,i=e!==null?e.memoizedProps:null,s=o.children,uy(r,o)?s=null:i!==null&&uy(r,i)&&(t.flags|=32),sR(e,t),Dn(e,t,s,n),t.child;case 6:return e===null&&my(t),null;case 13:return lR(e,t,n);case 4:return Rw(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=Gl(t,null,r,n):Dn(e,t,r,n),t.child;case 11:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),PE(e,t,r,o,n);case 7:return Dn(e,t,t.pendingProps,n),t.child;case 8:return Dn(e,t,t.pendingProps.children,n),t.child;case 12:return Dn(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,o=t.pendingProps,i=t.memoizedProps,s=o.value,$t(vh,r._currentValue),r._currentValue=s,i!==null)if(wo(i.value,s)){if(i.children===o.children&&!Jn.current){t=vi(e,t,n);break e}}else for(i=t.child,i!==null&&(i.return=t);i!==null;){var l=i.dependencies;if(l!==null){s=i.child;for(var u=l.firstContext;u!==null;){if(u.context===r){if(i.tag===1){u=fi(-1,n&-n),u.tag=2;var d=i.updateQueue;if(d!==null){d=d.shared;var h=d.pending;h===null?u.next=u:(u.next=h.next,h.next=u),d.pending=u}}i.lanes|=n,u=i.alternate,u!==null&&(u.lanes|=n),gy(i.return,n,t),l.lanes|=n;break}u=u.next}}else if(i.tag===10)s=i.type===t.type?null:i.child;else if(i.tag===18){if(s=i.return,s===null)throw Error(ce(341));s.lanes|=n,l=s.alternate,l!==null&&(l.lanes|=n),gy(s,n,t),s=i.sibling}else s=i.child;if(s!==null)s.return=i;else for(s=i;s!==null;){if(s===t){s=null;break}if(i=s.sibling,i!==null){i.return=s.return,s=i;break}s=s.return}i=s}Dn(e,t,o.children,n),t=t.child}return t;case 9:return o=t.type,r=t.pendingProps.children,Cl(t,n),o=Yr(o),r=r(o),t.flags|=1,Dn(e,t,r,n),t.child;case 14:return r=t.type,o=io(r,t.pendingProps),o=io(r.type,o),AE(e,t,r,o,n);case 15:return oR(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),Ap(e,t),t.tag=1,er(r)?(e=!0,hh(t)):e=!1,Cl(t,n),Mk(t,r,o),yy(t,r,o,n),by(null,t,r,!0,e,n);case 19:return cR(e,t,n);case 22:return iR(e,t,n)}throw Error(ce(156,t.tag))};function CR(e,t){return q$(e,t)}function BI(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 Ur(e,t,n,r){return new BI(e,t,n,r)}function Vw(e){return e=e.prototype,!(!e||!e.isReactComponent)}function UI(e){if(typeof e=="function")return Vw(e)?1:0;if(e!=null){if(e=e.$$typeof,e===lw)return 11;if(e===cw)return 14}return 2}function ws(e,t){var n=e.alternate;return n===null?(n=Ur(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 Np(e,t,n,r,o,i){var s=2;if(r=e,typeof e=="function")Vw(e)&&(s=1);else if(typeof e=="string")s=5;else e:switch(e){case ll:return xa(n.children,o,i,t);case aw:s=8,o|=8;break;case U0:return e=Ur(12,n,t,o|2),e.elementType=U0,e.lanes=i,e;case V0:return e=Ur(13,n,t,o),e.elementType=V0,e.lanes=i,e;case W0:return e=Ur(19,n,t,o),e.elementType=W0,e.lanes=i,e;case N$:return xm(n,o,i,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case O$:s=10;break e;case M$:s=9;break e;case lw:s=11;break e;case cw:s=14;break e;case Ki:s=16,r=null;break e}throw Error(ce(130,e==null?e:typeof e,""))}return t=Ur(s,n,t,o),t.elementType=e,t.type=r,t.lanes=i,t}function xa(e,t,n,r){return e=Ur(7,e,r,t),e.lanes=n,e}function xm(e,t,n,r){return e=Ur(22,e,r,t),e.elementType=N$,e.lanes=n,e.stateNode={isHidden:!1},e}function i0(e,t,n){return e=Ur(6,e,null,t),e.lanes=n,e}function s0(e,t,n){return t=Ur(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function VI(e,t,n,r,o){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=zv(0),this.expirationTimes=zv(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=zv(0),this.identifierPrefix=r,this.onRecoverableError=o,this.mutableSourceEagerHydrationData=null}function Ww(e,t,n,r,o,i,s,l,u){return e=new VI(e,t,n,l,u),t===1?(t=1,i===!0&&(t|=8)):t=0,i=Ur(3,null,null,t),e.current=i,i.stateNode=e,i.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},kw(i),e}function WI(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(TR)}catch(e){console.error(e)}}TR(),k$.exports=br;var Os=k$.exports;const XI=lm(Os);var HE=Os;z0.createRoot=HE.createRoot,z0.hydrateRoot=HE.hydrateRoot;var $d=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},Ql=typeof window>"u"||"Deno"in window;function Lr(){}function ZI(e,t){return typeof e=="function"?e(t):e}function My(e){return typeof e=="number"&&e>=0&&e!==1/0}function PR(e,t){return Math.max(e+(t||0)-Date.now(),0)}function KE(e,t){const{type:n="all",exact:r,fetchStatus:o,predicate:i,queryKey:s,stale:l}=e;if(s){if(r){if(t.queryHash!==Gw(s,t.options))return!1}else if(!Xu(t.queryKey,s))return!1}if(n!=="all"){const u=t.isActive();if(n==="active"&&!u||n==="inactive"&&u)return!1}return!(typeof l=="boolean"&&t.isStale()!==l||typeof o<"u"&&o!==t.state.fetchStatus||i&&!i(t))}function YE(e,t){const{exact:n,status:r,predicate:o,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(Gu(t.options.mutationKey)!==Gu(i))return!1}else if(!Xu(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||o&&!o(t))}function Gw(e,t){return((t==null?void 0:t.queryKeyHashFn)||Gu)(e)}function Gu(e){return JSON.stringify(e,(t,n)=>Dy(n)?Object.keys(n).sort().reduce((r,o)=>(r[o]=n[o],r),{}):n)}function Xu(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?!Object.keys(t).some(n=>!Xu(e[n],t[n])):!1}function AR(e,t){if(e===t)return e;const n=GE(e)&&GE(t);if(n||Dy(e)&&Dy(t)){const r=n?e.length:Object.keys(e).length,o=n?t:Object.keys(t),i=o.length,s=n?[]:{};let l=0;for(let u=0;u"u")return!0;const n=t.prototype;return!(!XE(n)||!n.hasOwnProperty("isPrototypeOf"))}function XE(e){return Object.prototype.toString.call(e)==="[object Object]"}function OR(e){return new Promise(t=>{setTimeout(t,e)})}function ZE(e){OR(0).then(e)}function Iy(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?AR(e,t):t}function qI(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function QI(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var ua,Zi,Pl,l$,JI=(l$=class extends $d{constructor(){super();Te(this,ua,void 0);Te(this,Zi,void 0);Te(this,Pl,void 0);ye(this,Pl,t=>{if(!Ql&&window.addEventListener){const n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){z(this,Zi)||this.setEventListener(z(this,Pl))}onUnsubscribe(){var t;this.hasListeners()||((t=z(this,Zi))==null||t.call(this),ye(this,Zi,void 0))}setEventListener(t){var n;ye(this,Pl,t),(n=z(this,Zi))==null||n.call(this),ye(this,Zi,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){z(this,ua)!==t&&(ye(this,ua,t),this.onFocus())}onFocus(){this.listeners.forEach(t=>{t()})}isFocused(){var t;return typeof z(this,ua)=="boolean"?z(this,ua):((t=globalThis.document)==null?void 0:t.visibilityState)!=="hidden"}},ua=new WeakMap,Zi=new WeakMap,Pl=new WeakMap,l$),Rh=new JI,Al,qi,Ol,c$,eL=(c$=class extends $d{constructor(){super();Te(this,Al,!0);Te(this,qi,void 0);Te(this,Ol,void 0);ye(this,Ol,t=>{if(!Ql&&window.addEventListener){const n=()=>t(!0),r=()=>t(!1);return window.addEventListener("online",n,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",r)}}})}onSubscribe(){z(this,qi)||this.setEventListener(z(this,Ol))}onUnsubscribe(){var t;this.hasListeners()||((t=z(this,qi))==null||t.call(this),ye(this,qi,void 0))}setEventListener(t){var n;ye(this,Ol,t),(n=z(this,qi))==null||n.call(this),ye(this,qi,t(this.setOnline.bind(this)))}setOnline(t){z(this,Al)!==t&&(ye(this,Al,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return z(this,Al)}},Al=new WeakMap,qi=new WeakMap,Ol=new WeakMap,c$),Th=new eL;function tL(e){return Math.min(1e3*2**e,3e4)}function Cm(e){return(e??"online")==="online"?Th.isOnline():!0}var MR=class{constructor(e){this.revert=e==null?void 0:e.revert,this.silent=e==null?void 0:e.silent}};function a0(e){return e instanceof MR}function NR(e){let t=!1,n=0,r=!1,o,i,s;const l=new Promise((C,S)=>{i=C,s=S}),u=C=>{var S;r||(y(new MR(C)),(S=e.abort)==null||S.call(e))},d=()=>{t=!0},h=()=>{t=!1},m=()=>!Rh.isFocused()||e.networkMode!=="always"&&!Th.isOnline(),g=C=>{var S;r||(r=!0,(S=e.onSuccess)==null||S.call(e,C),o==null||o(),i(C))},y=C=>{var S;r||(r=!0,(S=e.onError)==null||S.call(e,C),o==null||o(),s(C))},x=()=>new Promise(C=>{var S;o=b=>{const E=r||!m();return E&&C(b),E},(S=e.onPause)==null||S.call(e)}).then(()=>{var C;o=void 0,r||(C=e.onContinue)==null||C.call(e)}),_=()=>{if(r)return;let C;try{C=e.fn()}catch(S){C=Promise.reject(S)}Promise.resolve(C).then(g).catch(S=>{var M;if(r)return;const b=e.retry??(Ql?0:3),E=e.retryDelay??tL,k=typeof E=="function"?E(n,S):E,P=b===!0||typeof b=="number"&&n{if(m())return x()}).then(()=>{t?y(S):_()})})};return Cm(e.networkMode)?_():x().then(_),{promise:l,cancel:u,continue:()=>(o==null?void 0:o())?l:Promise.resolve(),cancelRetry:d,continueRetry:h}}function nL(){let e=[],t=0,n=h=>{h()},r=h=>{h()};const o=h=>{let m;t++;try{m=h()}finally{t--,t||l()}return m},i=h=>{t?e.push(h):ZE(()=>{n(h)})},s=h=>(...m)=>{i(()=>{h(...m)})},l=()=>{const h=e;e=[],h.length&&ZE(()=>{r(()=>{h.forEach(m=>{n(m)})})})};return{batch:o,batchCalls:s,schedule:i,setNotifyFunction:h=>{n=h},setBatchNotifyFunction:h=>{r=h}}}var gn=nL(),da,u$,DR=(u$=class{constructor(){Te(this,da,void 0)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),My(this.gcTime)&&ye(this,da,setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Ql?1/0:5*60*1e3))}clearGcTimeout(){z(this,da)&&(clearTimeout(z(this,da)),ye(this,da,void 0))}},da=new WeakMap,u$),Ml,Nl,Nr,Qi,Dr,cn,ud,fa,Dl,Dp,ao,ii,d$,rL=(d$=class extends DR{constructor(t){super();Te(this,Dl);Te(this,ao);Te(this,Ml,void 0);Te(this,Nl,void 0);Te(this,Nr,void 0);Te(this,Qi,void 0);Te(this,Dr,void 0);Te(this,cn,void 0);Te(this,ud,void 0);Te(this,fa,void 0);ye(this,fa,!1),ye(this,ud,t.defaultOptions),tt(this,Dl,Dp).call(this,t.options),ye(this,cn,[]),ye(this,Nr,t.cache),this.queryKey=t.queryKey,this.queryHash=t.queryHash,ye(this,Ml,t.state||oL(this.options)),this.state=z(this,Ml),this.scheduleGc()}get meta(){return this.options.meta}optionalRemove(){!z(this,cn).length&&this.state.fetchStatus==="idle"&&z(this,Nr).remove(this)}setData(t,n){const r=Iy(this.state.data,t,this.options);return tt(this,ao,ii).call(this,{data:r,type:"success",dataUpdatedAt:n==null?void 0:n.updatedAt,manual:n==null?void 0:n.manual}),r}setState(t,n){tt(this,ao,ii).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){var r;const n=z(this,Qi);return(r=z(this,Dr))==null||r.cancel(t),n?n.then(Lr).catch(Lr):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(z(this,Ml))}isActive(){return z(this,cn).some(t=>t.options.enabled!==!1)}isDisabled(){return this.getObserversCount()>0&&!this.isActive()}isStale(){return this.state.isInvalidated||!this.state.dataUpdatedAt||z(this,cn).some(t=>t.getCurrentResult().isStale)}isStaleByTime(t=0){return this.state.isInvalidated||!this.state.dataUpdatedAt||!PR(this.state.dataUpdatedAt,t)}onFocus(){var n;const t=z(this,cn).find(r=>r.shouldFetchOnWindowFocus());t==null||t.refetch({cancelRefetch:!1}),(n=z(this,Dr))==null||n.continue()}onOnline(){var n;const t=z(this,cn).find(r=>r.shouldFetchOnReconnect());t==null||t.refetch({cancelRefetch:!1}),(n=z(this,Dr))==null||n.continue()}addObserver(t){z(this,cn).includes(t)||(z(this,cn).push(t),this.clearGcTimeout(),z(this,Nr).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){z(this,cn).includes(t)&&(ye(this,cn,z(this,cn).filter(n=>n!==t)),z(this,cn).length||(z(this,Dr)&&(z(this,fa)?z(this,Dr).cancel({revert:!0}):z(this,Dr).cancelRetry()),this.scheduleGc()),z(this,Nr).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return z(this,cn).length}invalidate(){this.state.isInvalidated||tt(this,ao,ii).call(this,{type:"invalidate"})}fetch(t,n){var d,h,m,g;if(this.state.fetchStatus!=="idle"){if(this.state.dataUpdatedAt&&(n!=null&&n.cancelRefetch))this.cancel({silent:!0});else if(z(this,Qi))return(d=z(this,Dr))==null||d.continueRetry(),z(this,Qi)}if(t&&tt(this,Dl,Dp).call(this,t),!this.options.queryFn){const y=z(this,cn).find(x=>x.options.queryFn);y&&tt(this,Dl,Dp).call(this,y.options)}const r=new AbortController,o={queryKey:this.queryKey,meta:this.meta},i=y=>{Object.defineProperty(y,"signal",{enumerable:!0,get:()=>(ye(this,fa,!0),r.signal)})};i(o);const s=()=>this.options.queryFn?(ye(this,fa,!1),this.options.persister?this.options.persister(this.options.queryFn,o,this):this.options.queryFn(o)):Promise.reject(new Error(`Missing queryFn: '${this.options.queryHash}'`)),l={fetchOptions:n,options:this.options,queryKey:this.queryKey,state:this.state,fetchFn:s};i(l),(h=this.options.behavior)==null||h.onFetch(l,this),ye(this,Nl,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((m=l.fetchOptions)==null?void 0:m.meta))&&tt(this,ao,ii).call(this,{type:"fetch",meta:(g=l.fetchOptions)==null?void 0:g.meta});const u=y=>{var x,_,C,S;a0(y)&&y.silent||tt(this,ao,ii).call(this,{type:"error",error:y}),a0(y)||((_=(x=z(this,Nr).config).onError)==null||_.call(x,y,this),(S=(C=z(this,Nr).config).onSettled)==null||S.call(C,this.state.data,y,this)),this.isFetchingOptimistic||this.scheduleGc(),this.isFetchingOptimistic=!1};return ye(this,Dr,NR({fn:l.fetchFn,abort:r.abort.bind(r),onSuccess:y=>{var x,_,C,S;if(typeof y>"u"){u(new Error(`${this.queryHash} data is undefined`));return}this.setData(y),(_=(x=z(this,Nr).config).onSuccess)==null||_.call(x,y,this),(S=(C=z(this,Nr).config).onSettled)==null||S.call(C,y,this.state.error,this),this.isFetchingOptimistic||this.scheduleGc(),this.isFetchingOptimistic=!1},onError:u,onFail:(y,x)=>{tt(this,ao,ii).call(this,{type:"failed",failureCount:y,error:x})},onPause:()=>{tt(this,ao,ii).call(this,{type:"pause"})},onContinue:()=>{tt(this,ao,ii).call(this,{type:"continue"})},retry:l.options.retry,retryDelay:l.options.retryDelay,networkMode:l.options.networkMode})),ye(this,Qi,z(this,Dr).promise),z(this,Qi)}},Ml=new WeakMap,Nl=new WeakMap,Nr=new WeakMap,Qi=new WeakMap,Dr=new WeakMap,cn=new WeakMap,ud=new WeakMap,fa=new WeakMap,Dl=new WeakSet,Dp=function(t){this.options={...z(this,ud),...t},this.updateGcTime(this.options.gcTime)},ao=new WeakSet,ii=function(t){const n=r=>{switch(t.type){case"failed":return{...r,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...r,fetchStatus:"paused"};case"continue":return{...r,fetchStatus:"fetching"};case"fetch":return{...r,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:t.meta??null,fetchStatus:Cm(this.options.networkMode)?"fetching":"paused",...!r.dataUpdatedAt&&{error:null,status:"pending"}};case"success":return{...r,data:t.data,dataUpdateCount:r.dataUpdateCount+1,dataUpdatedAt:t.dataUpdatedAt??Date.now(),error:null,isInvalidated:!1,status:"success",...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};case"error":const o=t.error;return a0(o)&&o.revert&&z(this,Nl)?{...z(this,Nl),fetchStatus:"idle"}:{...r,error:o,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:o,fetchStatus:"idle",status:"error"};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...t.state}}};this.state=n(this.state),gn.batch(()=>{z(this,cn).forEach(r=>{r.onQueryUpdate()}),z(this,Nr).notify({query:this,type:"updated",action:t})})},d$);function oL(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=typeof t<"u",r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var Ro,f$,iL=(f$=class extends $d{constructor(t={}){super();Te(this,Ro,void 0);this.config=t,ye(this,Ro,new Map)}build(t,n,r){const o=n.queryKey,i=n.queryHash??Gw(o,n);let s=this.get(i);return s||(s=new rL({cache:this,queryKey:o,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(o)}),this.add(s)),s}add(t){z(this,Ro).has(t.queryHash)||(z(this,Ro).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){const n=z(this,Ro).get(t.queryHash);n&&(t.destroy(),n===t&&z(this,Ro).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){gn.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return z(this,Ro).get(t)}getAll(){return[...z(this,Ro).values()]}find(t){const n={exact:!0,...t};return this.getAll().find(r=>KE(n,r))}findAll(t={}){const n=this.getAll();return Object.keys(t).length>0?n.filter(r=>KE(t,r)):n}notify(t){gn.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){gn.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){gn.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},Ro=new WeakMap,f$),To,dd,dr,Il,Po,Wi,p$,sL=(p$=class extends DR{constructor(t){super();Te(this,Po);Te(this,To,void 0);Te(this,dd,void 0);Te(this,dr,void 0);Te(this,Il,void 0);this.mutationId=t.mutationId,ye(this,dd,t.defaultOptions),ye(this,dr,t.mutationCache),ye(this,To,[]),this.state=t.state||aL(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options={...z(this,dd),...t},this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){z(this,To).includes(t)||(z(this,To).push(t),this.clearGcTimeout(),z(this,dr).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){ye(this,To,z(this,To).filter(n=>n!==t)),this.scheduleGc(),z(this,dr).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){z(this,To).length||(this.state.status==="pending"?this.scheduleGc():z(this,dr).remove(this))}continue(){var t;return((t=z(this,Il))==null?void 0:t.continue())??this.execute(this.state.variables)}async execute(t){var o,i,s,l,u,d,h,m,g,y,x,_,C,S,b,E,k,P,M,A;const n=()=>(ye(this,Il,NR({fn:()=>this.options.mutationFn?this.options.mutationFn(t):Promise.reject(new Error("No mutationFn found")),onFail:(O,F)=>{tt(this,Po,Wi).call(this,{type:"failed",failureCount:O,error:F})},onPause:()=>{tt(this,Po,Wi).call(this,{type:"pause"})},onContinue:()=>{tt(this,Po,Wi).call(this,{type:"continue"})},retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode})),z(this,Il).promise),r=this.state.status==="pending";try{if(!r){tt(this,Po,Wi).call(this,{type:"pending",variables:t}),await((i=(o=z(this,dr).config).onMutate)==null?void 0:i.call(o,t,this));const F=await((l=(s=this.options).onMutate)==null?void 0:l.call(s,t));F!==this.state.context&&tt(this,Po,Wi).call(this,{type:"pending",context:F,variables:t})}const O=await n();return await((d=(u=z(this,dr).config).onSuccess)==null?void 0:d.call(u,O,t,this.state.context,this)),await((m=(h=this.options).onSuccess)==null?void 0:m.call(h,O,t,this.state.context)),await((y=(g=z(this,dr).config).onSettled)==null?void 0:y.call(g,O,null,this.state.variables,this.state.context,this)),await((_=(x=this.options).onSettled)==null?void 0:_.call(x,O,null,t,this.state.context)),tt(this,Po,Wi).call(this,{type:"success",data:O}),O}catch(O){try{throw await((S=(C=z(this,dr).config).onError)==null?void 0:S.call(C,O,t,this.state.context,this)),await((E=(b=this.options).onError)==null?void 0:E.call(b,O,t,this.state.context)),await((P=(k=z(this,dr).config).onSettled)==null?void 0:P.call(k,void 0,O,this.state.variables,this.state.context,this)),await((A=(M=this.options).onSettled)==null?void 0:A.call(M,void 0,O,t,this.state.context)),O}finally{tt(this,Po,Wi).call(this,{type:"error",error:O})}}}},To=new WeakMap,dd=new WeakMap,dr=new WeakMap,Il=new WeakMap,Po=new WeakSet,Wi=function(t){const n=r=>{switch(t.type){case"failed":return{...r,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};case"pending":return{...r,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:!Cm(this.options.networkMode),status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...r,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:t.error,failureCount:r.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}};this.state=n(this.state),gn.batch(()=>{z(this,To).forEach(r=>{r.onMutationUpdate(t)}),z(this,dr).notify({mutation:this,type:"updated",action:t})})},p$);function aL(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Ir,fd,pa,h$,lL=(h$=class extends $d{constructor(t={}){super();Te(this,Ir,void 0);Te(this,fd,void 0);Te(this,pa,void 0);this.config=t,ye(this,Ir,[]),ye(this,fd,0)}build(t,n,r){const o=new sL({mutationCache:this,mutationId:++Ff(this,fd)._,options:t.defaultMutationOptions(n),state:r});return this.add(o),o}add(t){z(this,Ir).push(t),this.notify({type:"added",mutation:t})}remove(t){ye(this,Ir,z(this,Ir).filter(n=>n!==t)),this.notify({type:"removed",mutation:t})}clear(){gn.batch(()=>{z(this,Ir).forEach(t=>{this.remove(t)})})}getAll(){return z(this,Ir)}find(t){const n={exact:!0,...t};return z(this,Ir).find(r=>YE(n,r))}findAll(t={}){return z(this,Ir).filter(n=>YE(t,n))}notify(t){gn.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){return ye(this,pa,(z(this,pa)??Promise.resolve()).then(()=>{const t=z(this,Ir).filter(n=>n.state.isPaused);return gn.batch(()=>t.reduce((n,r)=>n.then(()=>r.continue().catch(Lr)),Promise.resolve()))}).then(()=>{ye(this,pa,void 0)})),z(this,pa)}},Ir=new WeakMap,fd=new WeakMap,pa=new WeakMap,h$);function cL(e){return{onFetch:(t,n)=>{const r=async()=>{var x,_,C,S,b;const o=t.options,i=(C=(_=(x=t.fetchOptions)==null?void 0:x.meta)==null?void 0:_.fetchMore)==null?void 0:C.direction,s=((S=t.state.data)==null?void 0:S.pages)||[],l=((b=t.state.data)==null?void 0:b.pageParams)||[],u={pages:[],pageParams:[]};let d=!1;const h=E=>{Object.defineProperty(E,"signal",{enumerable:!0,get:()=>(t.signal.aborted?d=!0:t.signal.addEventListener("abort",()=>{d=!0}),t.signal)})},m=t.options.queryFn||(()=>Promise.reject(new Error(`Missing queryFn: '${t.options.queryHash}'`))),g=async(E,k,P)=>{if(d)return Promise.reject();if(k==null&&E.pages.length)return Promise.resolve(E);const M={queryKey:t.queryKey,pageParam:k,direction:P?"backward":"forward",meta:t.options.meta};h(M);const A=await m(M),{maxPages:O}=t.options,F=P?QI:qI;return{pages:F(E.pages,A,O),pageParams:F(E.pageParams,k,O)}};let y;if(i&&s.length){const E=i==="backward",k=E?uL:qE,P={pages:s,pageParams:l},M=k(o,P);y=await g(P,M,E)}else{y=await g(u,l[0]??o.initialPageParam);const E=e??s.length;for(let k=1;k{var o,i;return(i=(o=t.options).persister)==null?void 0:i.call(o,r,{queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n)}:t.fetchFn=r}}}function qE(e,{pages:t,pageParams:n}){const r=t.length-1;return e.getNextPageParam(t[r],t,n[r],n)}function uL(e,{pages:t,pageParams:n}){var r;return(r=e.getPreviousPageParam)==null?void 0:r.call(e,t[0],t,n[0],n)}var nn,Ji,es,Ll,Fl,ts,jl,zl,m$,dL=(m$=class{constructor(e={}){Te(this,nn,void 0);Te(this,Ji,void 0);Te(this,es,void 0);Te(this,Ll,void 0);Te(this,Fl,void 0);Te(this,ts,void 0);Te(this,jl,void 0);Te(this,zl,void 0);ye(this,nn,e.queryCache||new iL),ye(this,Ji,e.mutationCache||new lL),ye(this,es,e.defaultOptions||{}),ye(this,Ll,new Map),ye(this,Fl,new Map),ye(this,ts,0)}mount(){Ff(this,ts)._++,z(this,ts)===1&&(ye(this,jl,Rh.subscribe(()=>{Rh.isFocused()&&(this.resumePausedMutations(),z(this,nn).onFocus())})),ye(this,zl,Th.subscribe(()=>{Th.isOnline()&&(this.resumePausedMutations(),z(this,nn).onOnline())})))}unmount(){var e,t;Ff(this,ts)._--,z(this,ts)===0&&((e=z(this,jl))==null||e.call(this),ye(this,jl,void 0),(t=z(this,zl))==null||t.call(this),ye(this,zl,void 0))}isFetching(e){return z(this,nn).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return z(this,Ji).findAll({...e,status:"pending"}).length}getQueryData(e){var t;return(t=z(this,nn).find({queryKey:e}))==null?void 0:t.state.data}ensureQueryData(e){const t=this.getQueryData(e.queryKey);return t!==void 0?Promise.resolve(t):this.fetchQuery(e)}getQueriesData(e){return this.getQueryCache().findAll(e).map(({queryKey:t,state:n})=>{const r=n.data;return[t,r]})}setQueryData(e,t,n){const r=z(this,nn).find({queryKey:e}),o=r==null?void 0:r.state.data,i=ZI(t,o);if(typeof i>"u")return;const s=this.defaultQueryOptions({queryKey:e});return z(this,nn).build(this,s).setData(i,{...n,manual:!0})}setQueriesData(e,t,n){return gn.batch(()=>this.getQueryCache().findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){var t;return(t=z(this,nn).find({queryKey:e}))==null?void 0:t.state}removeQueries(e){const t=z(this,nn);gn.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=z(this,nn),r={type:"active",...e};return gn.batch(()=>(n.findAll(e).forEach(o=>{o.reset()}),this.refetchQueries(r,t)))}cancelQueries(e={},t={}){const n={revert:!0,...t},r=gn.batch(()=>z(this,nn).findAll(e).map(o=>o.cancel(n)));return Promise.all(r).then(Lr).catch(Lr)}invalidateQueries(e={},t={}){return gn.batch(()=>{if(z(this,nn).findAll(e).forEach(r=>{r.invalidate()}),e.refetchType==="none")return Promise.resolve();const n={...e,type:e.refetchType??e.type??"active"};return this.refetchQueries(n,t)})}refetchQueries(e={},t){const n={...t,cancelRefetch:(t==null?void 0:t.cancelRefetch)??!0},r=gn.batch(()=>z(this,nn).findAll(e).filter(o=>!o.isDisabled()).map(o=>{let i=o.fetch(void 0,n);return n.throwOnError||(i=i.catch(Lr)),o.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(Lr)}fetchQuery(e){const t=this.defaultQueryOptions(e);typeof t.retry>"u"&&(t.retry=!1);const n=z(this,nn).build(this,t);return n.isStaleByTime(t.staleTime)?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Lr).catch(Lr)}fetchInfiniteQuery(e){return e.behavior=cL(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Lr).catch(Lr)}resumePausedMutations(){return z(this,Ji).resumePausedMutations()}getQueryCache(){return z(this,nn)}getMutationCache(){return z(this,Ji)}getDefaultOptions(){return z(this,es)}setDefaultOptions(e){ye(this,es,e)}setQueryDefaults(e,t){z(this,Ll).set(Gu(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...z(this,Ll).values()];let n={};return t.forEach(r=>{Xu(e,r.queryKey)&&(n={...n,...r.defaultOptions})}),n}setMutationDefaults(e,t){z(this,Fl).set(Gu(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...z(this,Fl).values()];let n={};return t.forEach(r=>{Xu(e,r.mutationKey)&&(n={...n,...r.defaultOptions})}),n}defaultQueryOptions(e){if(e!=null&&e._defaulted)return e;const t={...z(this,es).queries,...(e==null?void 0:e.queryKey)&&this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Gw(t.queryKey,t)),typeof t.refetchOnReconnect>"u"&&(t.refetchOnReconnect=t.networkMode!=="always"),typeof t.throwOnError>"u"&&(t.throwOnError=!!t.suspense),typeof t.networkMode>"u"&&t.persister&&(t.networkMode="offlineFirst"),t}defaultMutationOptions(e){return e!=null&&e._defaulted?e:{...z(this,es).mutations,...(e==null?void 0:e.mutationKey)&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){z(this,nn).clear(),z(this,Ji).clear()}},nn=new WeakMap,Ji=new WeakMap,es=new WeakMap,Ll=new WeakMap,Fl=new WeakMap,ts=new WeakMap,jl=new WeakMap,zl=new WeakMap,m$),Xn,Ct,Bl,$n,ha,Ul,Ao,pd,Vl,Wl,ma,ga,ns,va,ya,hu,hd,Ly,md,Fy,gd,jy,vd,zy,yd,By,wd,Uy,xd,Vy,am,IR,g$,fL=(g$=class extends $d{constructor(t,n){super();Te(this,ya);Te(this,hd);Te(this,md);Te(this,gd);Te(this,vd);Te(this,yd);Te(this,wd);Te(this,xd);Te(this,am);Te(this,Xn,void 0);Te(this,Ct,void 0);Te(this,Bl,void 0);Te(this,$n,void 0);Te(this,ha,void 0);Te(this,Ul,void 0);Te(this,Ao,void 0);Te(this,pd,void 0);Te(this,Vl,void 0);Te(this,Wl,void 0);Te(this,ma,void 0);Te(this,ga,void 0);Te(this,ns,void 0);Te(this,va,void 0);ye(this,Ct,void 0),ye(this,Bl,void 0),ye(this,$n,void 0),ye(this,va,new Set),ye(this,Xn,t),this.options=n,ye(this,Ao,null),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(z(this,Ct).addObserver(this),QE(z(this,Ct),this.options)?tt(this,ya,hu).call(this):this.updateResult(),tt(this,vd,zy).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Wy(z(this,Ct),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Wy(z(this,Ct),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,tt(this,yd,By).call(this),tt(this,wd,Uy).call(this),z(this,Ct).removeObserver(this)}setOptions(t,n){const r=this.options,o=z(this,Ct);if(this.options=z(this,Xn).defaultQueryOptions(t),Ny(r,this.options)||z(this,Xn).getQueryCache().notify({type:"observerOptionsUpdated",query:z(this,Ct),observer:this}),typeof this.options.enabled<"u"&&typeof this.options.enabled!="boolean")throw new Error("Expected enabled to be a boolean");this.options.queryKey||(this.options.queryKey=r.queryKey),tt(this,xd,Vy).call(this);const i=this.hasListeners();i&&JE(z(this,Ct),o,this.options,r)&&tt(this,ya,hu).call(this),this.updateResult(n),i&&(z(this,Ct)!==o||this.options.enabled!==r.enabled||this.options.staleTime!==r.staleTime)&&tt(this,hd,Ly).call(this);const s=tt(this,md,Fy).call(this);i&&(z(this,Ct)!==o||this.options.enabled!==r.enabled||s!==z(this,ns))&&tt(this,gd,jy).call(this,s)}getOptimisticResult(t){const n=z(this,Xn).getQueryCache().build(z(this,Xn),t),r=this.createResult(n,t);return hL(this,r)&&(ye(this,$n,r),ye(this,Ul,this.options),ye(this,ha,z(this,Ct).state)),r}getCurrentResult(){return z(this,$n)}trackResult(t){const n={};return Object.keys(t).forEach(r=>{Object.defineProperty(n,r,{configurable:!1,enumerable:!0,get:()=>(z(this,va).add(r),t[r])})}),n}getCurrentQuery(){return z(this,Ct)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){const n=z(this,Xn).defaultQueryOptions(t),r=z(this,Xn).getQueryCache().build(z(this,Xn),n);return r.isFetchingOptimistic=!0,r.fetch().then(()=>this.createResult(r,n))}fetch(t){return tt(this,ya,hu).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),z(this,$n)))}createResult(t,n){var M;const r=z(this,Ct),o=this.options,i=z(this,$n),s=z(this,ha),l=z(this,Ul),d=t!==r?t.state:z(this,Bl),{state:h}=t;let{error:m,errorUpdatedAt:g,fetchStatus:y,status:x}=h,_=!1,C;if(n._optimisticResults){const A=this.hasListeners(),O=!A&&QE(t,n),F=A&&JE(t,r,n,o);(O||F)&&(y=Cm(t.options.networkMode)?"fetching":"paused",h.dataUpdatedAt||(x="pending")),n._optimisticResults==="isRestoring"&&(y="idle")}if(n.select&&typeof h.data<"u")if(i&&h.data===(s==null?void 0:s.data)&&n.select===z(this,pd))C=z(this,Vl);else try{ye(this,pd,n.select),C=n.select(h.data),C=Iy(i==null?void 0:i.data,C,n),ye(this,Vl,C),ye(this,Ao,null)}catch(A){ye(this,Ao,A)}else C=h.data;if(typeof n.placeholderData<"u"&&typeof C>"u"&&x==="pending"){let A;if(i!=null&&i.isPlaceholderData&&n.placeholderData===(l==null?void 0:l.placeholderData))A=i.data;else if(A=typeof n.placeholderData=="function"?n.placeholderData((M=z(this,Wl))==null?void 0:M.state.data,z(this,Wl)):n.placeholderData,n.select&&typeof A<"u")try{A=n.select(A),ye(this,Ao,null)}catch(O){ye(this,Ao,O)}typeof A<"u"&&(x="success",C=Iy(i==null?void 0:i.data,A,n),_=!0)}z(this,Ao)&&(m=z(this,Ao),C=z(this,Vl),g=Date.now(),x="error");const S=y==="fetching",b=x==="pending",E=x==="error",k=b&&S;return{status:x,fetchStatus:y,isPending:b,isSuccess:x==="success",isError:E,isInitialLoading:k,isLoading:k,data:C,dataUpdatedAt:h.dataUpdatedAt,error:m,errorUpdatedAt:g,failureCount:h.fetchFailureCount,failureReason:h.fetchFailureReason,errorUpdateCount:h.errorUpdateCount,isFetched:h.dataUpdateCount>0||h.errorUpdateCount>0,isFetchedAfterMount:h.dataUpdateCount>d.dataUpdateCount||h.errorUpdateCount>d.errorUpdateCount,isFetching:S,isRefetching:S&&!b,isLoadingError:E&&h.dataUpdatedAt===0,isPaused:y==="paused",isPlaceholderData:_,isRefetchError:E&&h.dataUpdatedAt!==0,isStale:Xw(t,n),refetch:this.refetch}}updateResult(t){const n=z(this,$n),r=this.createResult(z(this,Ct),this.options);if(ye(this,ha,z(this,Ct).state),ye(this,Ul,this.options),z(this,ha).data!==void 0&&ye(this,Wl,z(this,Ct)),Ny(r,n))return;ye(this,$n,r);const o={},i=()=>{if(!n)return!0;const{notifyOnChangeProps:s}=this.options,l=typeof s=="function"?s():s;if(l==="all"||!l&&!z(this,va).size)return!0;const u=new Set(l??z(this,va));return this.options.throwOnError&&u.add("error"),Object.keys(z(this,$n)).some(d=>{const h=d;return z(this,$n)[h]!==n[h]&&u.has(h)})};(t==null?void 0:t.listeners)!==!1&&i()&&(o.listeners=!0),tt(this,am,IR).call(this,{...o,...t})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&tt(this,vd,zy).call(this)}},Xn=new WeakMap,Ct=new WeakMap,Bl=new WeakMap,$n=new WeakMap,ha=new WeakMap,Ul=new WeakMap,Ao=new WeakMap,pd=new WeakMap,Vl=new WeakMap,Wl=new WeakMap,ma=new WeakMap,ga=new WeakMap,ns=new WeakMap,va=new WeakMap,ya=new WeakSet,hu=function(t){tt(this,xd,Vy).call(this);let n=z(this,Ct).fetch(this.options,t);return t!=null&&t.throwOnError||(n=n.catch(Lr)),n},hd=new WeakSet,Ly=function(){if(tt(this,yd,By).call(this),Ql||z(this,$n).isStale||!My(this.options.staleTime))return;const n=PR(z(this,$n).dataUpdatedAt,this.options.staleTime)+1;ye(this,ma,setTimeout(()=>{z(this,$n).isStale||this.updateResult()},n))},md=new WeakSet,Fy=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(z(this,Ct)):this.options.refetchInterval)??!1},gd=new WeakSet,jy=function(t){tt(this,wd,Uy).call(this),ye(this,ns,t),!(Ql||this.options.enabled===!1||!My(z(this,ns))||z(this,ns)===0)&&ye(this,ga,setInterval(()=>{(this.options.refetchIntervalInBackground||Rh.isFocused())&&tt(this,ya,hu).call(this)},z(this,ns)))},vd=new WeakSet,zy=function(){tt(this,hd,Ly).call(this),tt(this,gd,jy).call(this,tt(this,md,Fy).call(this))},yd=new WeakSet,By=function(){z(this,ma)&&(clearTimeout(z(this,ma)),ye(this,ma,void 0))},wd=new WeakSet,Uy=function(){z(this,ga)&&(clearInterval(z(this,ga)),ye(this,ga,void 0))},xd=new WeakSet,Vy=function(){const t=z(this,Xn).getQueryCache().build(z(this,Xn),this.options);if(t===z(this,Ct))return;const n=z(this,Ct);ye(this,Ct,t),ye(this,Bl,t.state),this.hasListeners()&&(n==null||n.removeObserver(this),t.addObserver(this))},am=new WeakSet,IR=function(t){gn.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(z(this,$n))}),z(this,Xn).getQueryCache().notify({query:z(this,Ct),type:"observerResultsUpdated"})})},g$);function pL(e,t){return t.enabled!==!1&&!e.state.dataUpdatedAt&&!(e.state.status==="error"&&t.retryOnMount===!1)}function QE(e,t){return pL(e,t)||e.state.dataUpdatedAt>0&&Wy(e,t,t.refetchOnMount)}function Wy(e,t,n){if(t.enabled!==!1){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&Xw(e,t)}return!1}function JE(e,t,n,r){return n.enabled!==!1&&(e!==t||r.enabled===!1)&&(!n.suspense||e.state.status!=="error")&&Xw(e,n)}function Xw(e,t){return e.isStaleByTime(t.staleTime)}function hL(e,t){return!Ny(e.getCurrentResult(),t)}var LR=f.createContext(void 0),mL=e=>{const t=f.useContext(LR);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},gL=({client:e,children:t})=>(f.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),f.createElement(LR.Provider,{value:e},t)),FR=f.createContext(!1),vL=()=>f.useContext(FR);FR.Provider;function yL(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var wL=f.createContext(yL()),xL=()=>f.useContext(wL);function bL(e,t){return typeof e=="function"?e(...t):!!e}var _L=(e,t)=>{(e.suspense||e.throwOnError)&&(t.isReset()||(e.retryOnMount=!1))},SL=e=>{f.useEffect(()=>{e.clearReset()},[e])},EL=({result:e,errorResetBoundary:t,throwOnError:n,query:r})=>e.isError&&!t.isReset()&&!e.isFetching&&bL(n,[e.error,r]),CL=e=>{e.suspense&&typeof e.staleTime!="number"&&(e.staleTime=1e3)},$L=(e,t)=>(e==null?void 0:e.suspense)&&t.isPending,kL=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function RL(e,t,n){const r=mL(n),o=vL(),i=xL(),s=r.defaultQueryOptions(e);s._optimisticResults=o?"isRestoring":"optimistic",CL(s),_L(s,i),SL(i);const[l]=f.useState(()=>new t(r,s)),u=l.getOptimisticResult(s);if(f.useSyncExternalStore(f.useCallback(d=>{const h=o?()=>{}:l.subscribe(gn.batchCalls(d));return l.updateResult(),h},[l,o]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),f.useEffect(()=>{l.setOptions(s,{listeners:!1})},[s,l]),$L(s,u))throw l.setOptions(s,{listeners:!1}),kL(s,l,i);if(EL({result:u,errorResetBoundary:i,throwOnError:s.throwOnError,query:l.getCurrentQuery()}))throw u.error;return s.notifyOnChangeProps?u:l.trackResult(u)}function TL(e,t){return RL(e,fL,t)}var jR=(e=>(e.RemoveBG="RemoveBG",e.AnimeSeg="AnimeSeg",e.RealESRGAN="RealESRGAN",e.GFPGAN="GFPGAN",e.RestoreFormer="RestoreFormer",e.InteractiveSeg="InteractiveSeg",e))(jR||{}),xs=(e=>(e.NAME="name",e.CTIME="ctime",e.MTIME="mtime",e))(xs||{}),$u=(e=>(e.DESCENDING="desc",e.ASCENDING="asc",e))($u||{}),Zw=(e=>(e.ddim="ddim",e.plms="plms",e))(Zw||{}),qw=(e=>(e.INPAINT_NS="INPAINT_NS",e.INPAINT_TELEA="INPAINT_TELEA",e))(qw||{}),In=(e=>(e.x="x",e.y="y",e.xy="xy",e))(In||{}),kl=(e=>(e.text_guided="text-guided",e.shape_guided="shape-guided",e.object_remove="object-remove",e.outpainting="outpainting",e))(kl||{});function zR(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;tl(i)))==null?void 0:s.classGroupId}const eC=/^\[(.+)\]$/;function AL(e){if(eC.test(e)){const t=eC.exec(e)[1],n=t==null?void 0:t.substring(0,t.indexOf(":"));if(n)return"arbitrary.."+n}}function OL(e){const{theme:t,prefix:n}=e,r={nextPart:new Map,validators:[]};return NL(Object.entries(e.classGroups),n).forEach(([i,s])=>{Hy(s,r,i,t)}),r}function Hy(e,t,n,r){e.forEach(o=>{if(typeof o=="string"){const i=o===""?t:tC(t,o);i.classGroupId=n;return}if(typeof o=="function"){if(ML(o)){Hy(o(r),t,n,r);return}t.validators.push({validator:o,classGroupId:n});return}Object.entries(o).forEach(([i,s])=>{Hy(s,tC(t,i),n,r)})})}function tC(e,t){let n=e;return t.split(Qw).forEach(r=>{n.nextPart.has(r)||n.nextPart.set(r,{nextPart:new Map,validators:[]}),n=n.nextPart.get(r)}),n}function ML(e){return e.isThemeGetter}function NL(e,t){return t?e.map(([n,r])=>{const o=r.map(i=>typeof i=="string"?t+i:typeof i=="object"?Object.fromEntries(Object.entries(i).map(([s,l])=>[t+s,l])):i);return[n,o]}):e}function DL(e){if(e<1)return{get:()=>{},set:()=>{}};let t=0,n=new Map,r=new Map;function o(i,s){n.set(i,s),t++,t>e&&(t=0,r=n,n=new Map)}return{get(i){let s=n.get(i);if(s!==void 0)return s;if((s=r.get(i))!==void 0)return o(i,s),s},set(i,s){n.has(i)?n.set(i,s):o(i,s)}}}const VR="!";function IL(e){const t=e.separator,n=t.length===1,r=t[0],o=t.length;return function(s){const l=[];let u=0,d=0,h;for(let _=0;_d?h-d:void 0;return{modifiers:l,hasImportantModifier:g,baseClassName:y,maybePostfixModifierPosition:x}}}function LL(e){if(e.length<=1)return e;const t=[];let n=[];return e.forEach(r=>{r[0]==="["?(t.push(...n.sort(),r),n=[]):n.push(r)}),t.push(...n.sort()),t}function FL(e){return{cache:DL(e.cacheSize),splitModifiers:IL(e),...PL(e)}}const jL=/\s+/;function zL(e,t){const{splitModifiers:n,getClassGroupId:r,getConflictingClassGroupIds:o}=t,i=new Set;return e.trim().split(jL).map(s=>{const{modifiers:l,hasImportantModifier:u,baseClassName:d,maybePostfixModifierPosition:h}=n(s);let m=r(h?d.substring(0,h):d),g=!!h;if(!m){if(!h)return{isTailwindClass:!1,originalClassName:s};if(m=r(d),!m)return{isTailwindClass:!1,originalClassName:s};g=!1}const y=LL(l).join(":");return{isTailwindClass:!0,modifierId:u?y+VR:y,classGroupId:m,originalClassName:s,hasPostfixModifier:g}}).reverse().filter(s=>{if(!s.isTailwindClass)return!0;const{modifierId:l,classGroupId:u,hasPostfixModifier:d}=s,h=l+u;return i.has(h)?!1:(i.add(h),o(u,d).forEach(m=>i.add(l+m)),!0)}).reverse().map(s=>s.originalClassName).join(" ")}function BL(){let e=0,t,n,r="";for(;em(h),e());return n=FL(d),r=n.cache.get,o=n.cache.set,i=l,l(u)}function l(u){const d=r(u);if(d)return d;const h=zL(u,n);return o(u,h),h}return function(){return i(BL.apply(null,arguments))}}function Rt(e){const t=n=>n[e]||[];return t.isThemeGetter=!0,t}const HR=/^\[(?:([a-z-]+):)?(.+)\]$/i,VL=/^\d+\/\d+$/,WL=new Set(["px","full","screen"]),HL=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,KL=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,YL=/^-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,GL=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/;function oo(e){return ia(e)||WL.has(e)||VL.test(e)}function zi(e){return mc(e,"length",nF)}function ia(e){return!!e&&!Number.isNaN(Number(e))}function np(e){return mc(e,"number",ia)}function nu(e){return!!e&&Number.isInteger(Number(e))}function XL(e){return e.endsWith("%")&&ia(e.slice(0,-1))}function Je(e){return HR.test(e)}function Bi(e){return HL.test(e)}const ZL=new Set(["length","size","percentage"]);function qL(e){return mc(e,ZL,KR)}function QL(e){return mc(e,"position",KR)}const JL=new Set(["image","url"]);function eF(e){return mc(e,JL,oF)}function tF(e){return mc(e,"",rF)}function ru(){return!0}function mc(e,t,n){const r=HR.exec(e);return r?r[1]?typeof t=="string"?r[1]===t:t.has(r[1]):n(r[2]):!1}function nF(e){return KL.test(e)}function KR(){return!1}function rF(e){return YL.test(e)}function oF(e){return GL.test(e)}function iF(){const e=Rt("colors"),t=Rt("spacing"),n=Rt("blur"),r=Rt("brightness"),o=Rt("borderColor"),i=Rt("borderRadius"),s=Rt("borderSpacing"),l=Rt("borderWidth"),u=Rt("contrast"),d=Rt("grayscale"),h=Rt("hueRotate"),m=Rt("invert"),g=Rt("gap"),y=Rt("gradientColorStops"),x=Rt("gradientColorStopPositions"),_=Rt("inset"),C=Rt("margin"),S=Rt("opacity"),b=Rt("padding"),E=Rt("saturate"),k=Rt("scale"),P=Rt("sepia"),M=Rt("skew"),A=Rt("space"),O=Rt("translate"),F=()=>["auto","contain","none"],V=()=>["auto","hidden","clip","visible","scroll"],J=()=>["auto",Je,t],G=()=>[Je,t],ae=()=>["",oo,zi],U=()=>["auto",ia,Je],te=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],L=()=>["solid","dashed","dotted","double","none"],ie=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity","plus-lighter"],K=()=>["start","end","center","between","around","evenly","stretch"],Q=()=>["","0",Je],W=()=>["auto","avoid","all","avoid-page","page","left","right","column"],le=()=>[ia,np],ge=()=>[ia,Je];return{cacheSize:500,separator:":",theme:{colors:[ru],spacing:[oo,zi],blur:["none","",Bi,Je],brightness:le(),borderColor:[e],borderRadius:["none","","full",Bi,Je],borderSpacing:G(),borderWidth:ae(),contrast:le(),grayscale:Q(),hueRotate:ge(),invert:Q(),gap:G(),gradientColorStops:[e],gradientColorStopPositions:[XL,zi],inset:J(),margin:J(),opacity:le(),padding:G(),saturate:le(),scale:le(),sepia:Q(),skew:ge(),space:G(),translate:G()},classGroups:{aspect:[{aspect:["auto","square","video",Je]}],container:["container"],columns:[{columns:[Bi]}],"break-after":[{"break-after":W()}],"break-before":[{"break-before":W()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],float:[{float:["right","left","none"]}],clear:[{clear:["left","right","both","none"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:[...te(),Je]}],overflow:[{overflow:V()}],"overflow-x":[{"overflow-x":V()}],"overflow-y":[{"overflow-y":V()}],overscroll:[{overscroll:F()}],"overscroll-x":[{"overscroll-x":F()}],"overscroll-y":[{"overscroll-y":F()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[_]}],"inset-x":[{"inset-x":[_]}],"inset-y":[{"inset-y":[_]}],start:[{start:[_]}],end:[{end:[_]}],top:[{top:[_]}],right:[{right:[_]}],bottom:[{bottom:[_]}],left:[{left:[_]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",nu,Je]}],basis:[{basis:J()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",Je]}],grow:[{grow:Q()}],shrink:[{shrink:Q()}],order:[{order:["first","last","none",nu,Je]}],"grid-cols":[{"grid-cols":[ru]}],"col-start-end":[{col:["auto",{span:["full",nu,Je]},Je]}],"col-start":[{"col-start":U()}],"col-end":[{"col-end":U()}],"grid-rows":[{"grid-rows":[ru]}],"row-start-end":[{row:["auto",{span:[nu,Je]},Je]}],"row-start":[{"row-start":U()}],"row-end":[{"row-end":U()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",Je]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",Je]}],gap:[{gap:[g]}],"gap-x":[{"gap-x":[g]}],"gap-y":[{"gap-y":[g]}],"justify-content":[{justify:["normal",...K()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...K(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...K(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[b]}],px:[{px:[b]}],py:[{py:[b]}],ps:[{ps:[b]}],pe:[{pe:[b]}],pt:[{pt:[b]}],pr:[{pr:[b]}],pb:[{pb:[b]}],pl:[{pl:[b]}],m:[{m:[C]}],mx:[{mx:[C]}],my:[{my:[C]}],ms:[{ms:[C]}],me:[{me:[C]}],mt:[{mt:[C]}],mr:[{mr:[C]}],mb:[{mb:[C]}],ml:[{ml:[C]}],"space-x":[{"space-x":[A]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[A]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit",Je,t]}],"min-w":[{"min-w":["min","max","fit",Je,oo]}],"max-w":[{"max-w":["0","none","full","min","max","fit","prose",{screen:[Bi]},Bi,Je]}],h:[{h:[Je,t,"auto","min","max","fit"]}],"min-h":[{"min-h":["min","max","fit",oo,Je]}],"max-h":[{"max-h":[Je,t,"min","max","fit"]}],"font-size":[{text:["base",Bi,zi]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",np]}],"font-family":[{font:[ru]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractons"],tracking:[{tracking:["tighter","tight","normal","wide","wider","widest",Je]}],"line-clamp":[{"line-clamp":["none",ia,np]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",oo,Je]}],"list-image":[{"list-image":["none",Je]}],"list-style-type":[{list:["none","disc","decimal",Je]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[e]}],"placeholder-opacity":[{"placeholder-opacity":[S]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[e]}],"text-opacity":[{"text-opacity":[S]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...L(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",oo,zi]}],"underline-offset":[{"underline-offset":["auto",oo,Je]}],"text-decoration-color":[{decoration:[e]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],indent:[{indent:G()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Je]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",Je]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[S]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...te(),QL]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",qL]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},eF]}],"bg-color":[{bg:[e]}],"gradient-from-pos":[{from:[x]}],"gradient-via-pos":[{via:[x]}],"gradient-to-pos":[{to:[x]}],"gradient-from":[{from:[y]}],"gradient-via":[{via:[y]}],"gradient-to":[{to:[y]}],rounded:[{rounded:[i]}],"rounded-s":[{"rounded-s":[i]}],"rounded-e":[{"rounded-e":[i]}],"rounded-t":[{"rounded-t":[i]}],"rounded-r":[{"rounded-r":[i]}],"rounded-b":[{"rounded-b":[i]}],"rounded-l":[{"rounded-l":[i]}],"rounded-ss":[{"rounded-ss":[i]}],"rounded-se":[{"rounded-se":[i]}],"rounded-ee":[{"rounded-ee":[i]}],"rounded-es":[{"rounded-es":[i]}],"rounded-tl":[{"rounded-tl":[i]}],"rounded-tr":[{"rounded-tr":[i]}],"rounded-br":[{"rounded-br":[i]}],"rounded-bl":[{"rounded-bl":[i]}],"border-w":[{border:[l]}],"border-w-x":[{"border-x":[l]}],"border-w-y":[{"border-y":[l]}],"border-w-s":[{"border-s":[l]}],"border-w-e":[{"border-e":[l]}],"border-w-t":[{"border-t":[l]}],"border-w-r":[{"border-r":[l]}],"border-w-b":[{"border-b":[l]}],"border-w-l":[{"border-l":[l]}],"border-opacity":[{"border-opacity":[S]}],"border-style":[{border:[...L(),"hidden"]}],"divide-x":[{"divide-x":[l]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[l]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[S]}],"divide-style":[{divide:L()}],"border-color":[{border:[o]}],"border-color-x":[{"border-x":[o]}],"border-color-y":[{"border-y":[o]}],"border-color-t":[{"border-t":[o]}],"border-color-r":[{"border-r":[o]}],"border-color-b":[{"border-b":[o]}],"border-color-l":[{"border-l":[o]}],"divide-color":[{divide:[o]}],"outline-style":[{outline:["",...L()]}],"outline-offset":[{"outline-offset":[oo,Je]}],"outline-w":[{outline:[oo,zi]}],"outline-color":[{outline:[e]}],"ring-w":[{ring:ae()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[e]}],"ring-opacity":[{"ring-opacity":[S]}],"ring-offset-w":[{"ring-offset":[oo,zi]}],"ring-offset-color":[{"ring-offset":[e]}],shadow:[{shadow:["","inner","none",Bi,tF]}],"shadow-color":[{shadow:[ru]}],opacity:[{opacity:[S]}],"mix-blend":[{"mix-blend":ie()}],"bg-blend":[{"bg-blend":ie()}],filter:[{filter:["","none"]}],blur:[{blur:[n]}],brightness:[{brightness:[r]}],contrast:[{contrast:[u]}],"drop-shadow":[{"drop-shadow":["","none",Bi,Je]}],grayscale:[{grayscale:[d]}],"hue-rotate":[{"hue-rotate":[h]}],invert:[{invert:[m]}],saturate:[{saturate:[E]}],sepia:[{sepia:[P]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[n]}],"backdrop-brightness":[{"backdrop-brightness":[r]}],"backdrop-contrast":[{"backdrop-contrast":[u]}],"backdrop-grayscale":[{"backdrop-grayscale":[d]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[h]}],"backdrop-invert":[{"backdrop-invert":[m]}],"backdrop-opacity":[{"backdrop-opacity":[S]}],"backdrop-saturate":[{"backdrop-saturate":[E]}],"backdrop-sepia":[{"backdrop-sepia":[P]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":[s]}],"border-spacing-x":[{"border-spacing-x":[s]}],"border-spacing-y":[{"border-spacing-y":[s]}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["none","all","","colors","opacity","shadow","transform",Je]}],duration:[{duration:ge()}],ease:[{ease:["linear","in","out","in-out",Je]}],delay:[{delay:ge()}],animate:[{animate:["none","spin","ping","pulse","bounce",Je]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[k]}],"scale-x":[{"scale-x":[k]}],"scale-y":[{"scale-y":[k]}],rotate:[{rotate:[nu,Je]}],"translate-x":[{"translate-x":[O]}],"translate-y":[{"translate-y":[O]}],"skew-x":[{"skew-x":[M]}],"skew-y":[{"skew-y":[M]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",Je]}],accent:[{accent:["auto",e]}],appearance:["appearance-none"],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",Je]}],"caret-color":[{caret:[e]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":G()}],"scroll-mx":[{"scroll-mx":G()}],"scroll-my":[{"scroll-my":G()}],"scroll-ms":[{"scroll-ms":G()}],"scroll-me":[{"scroll-me":G()}],"scroll-mt":[{"scroll-mt":G()}],"scroll-mr":[{"scroll-mr":G()}],"scroll-mb":[{"scroll-mb":G()}],"scroll-ml":[{"scroll-ml":G()}],"scroll-p":[{"scroll-p":G()}],"scroll-px":[{"scroll-px":G()}],"scroll-py":[{"scroll-py":G()}],"scroll-ps":[{"scroll-ps":G()}],"scroll-pe":[{"scroll-pe":G()}],"scroll-pt":[{"scroll-pt":G()}],"scroll-pr":[{"scroll-pr":G()}],"scroll-pb":[{"scroll-pb":G()}],"scroll-pl":[{"scroll-pl":G()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",Je]}],fill:[{fill:[e,"none"]}],"stroke-w":[{stroke:[oo,zi,np]}],stroke:[{stroke:[e,"none"]}],sr:["sr-only","not-sr-only"]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]}}}const Jw=UL(iF),sF=40,is="inpaint",rp="diffusers_sd",nC="diffusers_sdxl",op="diffusers_sd_inpaint",rC="diffusers_sdxl_inpaint",l0="diffusers_other",Ky="#ffcc00bb",oC="ldm",iC="cv2",YR="Fantasy-Studio/Paint-by-Example",aF="timbrooks/instruct-pix2pix",lF="Sanster/PowerPaint-V1-stable-diffusion-inpainting",cF="out of frame, lowres, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, disfigured, gross proportions, malformed limbs, watermark, signature";function Ce(...e){return Jw(BR(e))}function uF(){async function e(r=""){return(await fetch(r,{method:"GET",cache:"no-cache"})).json()}const t=()=>{const r=document.location;e(r+"/flaskwebgui-keep-server-alive").then(i=>i)},n=3*1e3;t(),setInterval(t,n)}function sC(e){const t=e.split(",")[0].split(":")[1].split(";")[0],n=atob(e.split(",")[1]),r=[];for(let o=0;o{const o=e.src,i=e;i.onload=n,i.onerror=s=>{i.src=o,r(s)},i.src=t})}async function dF(e){const t=URL.createObjectURL(e),n=new Image;return await Ip(n,t),n}function aC(e){return new Promise((t,n)=>{const r=new Image;r.addEventListener("load",()=>{t(r)}),r.addEventListener("error",o=>{n(o)}),r.src=e.toDataURL()})}function fF(e){return new Promise((t,n)=>{const r=new FileReader;r.onload=()=>{const o=new Image;o.onload=()=>{t(o)},o.onerror=()=>{n("无法加载图像。")},o.src=r.result},r.onerror=()=>{n("无法读取文件。")},r.readAsDataURL(e)})}function ku(e,t,n){return fetch(e).then(function(r){return r.arrayBuffer()}).then(function(r){return new File([r],t,{type:n})})}async function pF(){try{const{state:e}=await navigator.permissions.query({name:"clipboard-write"});return e==="granted"}catch{return!1}}function hF(e,t){return new Promise((n,r)=>e.toBlob(async o=>{o?n(o):r(new Error("Expected toBlob() to be defined"))},t))}const mF=async e=>{const t=[new ClipboardItem({[e.type]:e})];await navigator.clipboard.write(t)};function lC(e){return e.nativeEvent.button===2}function cC(e){return e.nativeEvent.button===1}async function gF(e){const t=await hF(e,"image/png");try{await mF(t)}catch{console.log("Copy image failed!")}}function vF(e,t){const n=document.createElement("a");n.href=e,n.download=t,n.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0,view:window})),setTimeout(()=>{n.remove()},100)}function c0(e){const t=e.nativeEvent;return{x:t.offsetX,y:t.offsetY}}function GR(e,t,n=Ky){e.strokeStyle=n,e.lineCap="round",e.lineJoin="round",t.forEach(r=>{!(r!=null&&r.pts.length)||!r.size||(e.lineWidth=r.size,e.beginPath(),e.moveTo(r.pts[0].x,r.pts[0].y),r.pts.forEach(o=>e.lineTo(o.x,o.y)),e.stroke())})}const Lp=(e,t,n,r=[],o="white")=>{const i=document.createElement("canvas");i.width=e,i.height=t;const s=i.getContext("2d");if(!s)throw new Error("could not retrieve mask canvas");return r.forEach(l=>{s.drawImage(l,0,0,e,t)}),n.forEach(l=>{GR(s,l,o)}),i},Ru=e=>new Promise((t,n)=>{const r=new FileReader;r.onload=o=>{var s;const i=(s=o.target)==null?void 0:s.result;t(i)},r.onerror=o=>{n(o)},r.readAsDataURL(e)});function XR(e,t){return function(){return e.apply(t,arguments)}}const{toString:yF}=Object.prototype,{getPrototypeOf:ex}=Object,$m=(e=>t=>{const n=yF.call(t);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),Go=e=>(e=e.toLowerCase(),t=>$m(t)===e),km=e=>t=>typeof t===e,{isArray:gc}=Array,Zu=km("undefined");function wF(e){return e!==null&&!Zu(e)&&e.constructor!==null&&!Zu(e.constructor)&&Kr(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const ZR=Go("ArrayBuffer");function xF(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&ZR(e.buffer),t}const bF=km("string"),Kr=km("function"),qR=km("number"),Rm=e=>e!==null&&typeof e=="object",_F=e=>e===!0||e===!1,Fp=e=>{if($m(e)!=="object")return!1;const t=ex(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},SF=Go("Date"),EF=Go("File"),CF=Go("Blob"),$F=Go("FileList"),kF=e=>Rm(e)&&Kr(e.pipe),RF=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||Kr(e.append)&&((t=$m(e))==="formdata"||t==="object"&&Kr(e.toString)&&e.toString()==="[object FormData]"))},TF=Go("URLSearchParams"),PF=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function kd(e,t,{allOwnKeys:n=!1}={}){if(e===null||typeof e>"u")return;let r,o;if(typeof e!="object"&&(e=[e]),gc(e))for(r=0,o=e.length;r0;)if(o=n[r],t===o.toLowerCase())return o;return null}const JR=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,eT=e=>!Zu(e)&&e!==JR;function Yy(){const{caseless:e}=eT(this)&&this||{},t={},n=(r,o)=>{const i=e&&QR(t,o)||o;Fp(t[i])&&Fp(r)?t[i]=Yy(t[i],r):Fp(r)?t[i]=Yy({},r):gc(r)?t[i]=r.slice():t[i]=r};for(let r=0,o=arguments.length;r(kd(t,(o,i)=>{n&&Kr(o)?e[i]=XR(o,n):e[i]=o},{allOwnKeys:r}),e),OF=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),MF=(e,t,n,r)=>{e.prototype=Object.create(t.prototype,r),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),n&&Object.assign(e.prototype,n)},NF=(e,t,n,r)=>{let o,i,s;const l={};if(t=t||{},e==null)return t;do{for(o=Object.getOwnPropertyNames(e),i=o.length;i-- >0;)s=o[i],(!r||r(s,e,t))&&!l[s]&&(t[s]=e[s],l[s]=!0);e=n!==!1&&ex(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},DF=(e,t,n)=>{e=String(e),(n===void 0||n>e.length)&&(n=e.length),n-=t.length;const r=e.indexOf(t,n);return r!==-1&&r===n},IF=e=>{if(!e)return null;if(gc(e))return e;let t=e.length;if(!qR(t))return null;const n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},LF=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&ex(Uint8Array)),FF=(e,t)=>{const r=(e&&e[Symbol.iterator]).call(e);let o;for(;(o=r.next())&&!o.done;){const i=o.value;t.call(e,i[0],i[1])}},jF=(e,t)=>{let n;const r=[];for(;(n=e.exec(t))!==null;)r.push(n);return r},zF=Go("HTMLFormElement"),BF=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,r,o){return r.toUpperCase()+o}),uC=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),UF=Go("RegExp"),tT=(e,t)=>{const n=Object.getOwnPropertyDescriptors(e),r={};kd(n,(o,i)=>{let s;(s=t(o,i,e))!==!1&&(r[i]=s||o)}),Object.defineProperties(e,r)},VF=e=>{tT(e,(t,n)=>{if(Kr(e)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;const r=e[n];if(Kr(r)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},WF=(e,t)=>{const n={},r=o=>{o.forEach(i=>{n[i]=!0})};return gc(e)?r(e):r(String(e).split(t)),n},HF=()=>{},KF=(e,t)=>(e=+e,Number.isFinite(e)?e:t),u0="abcdefghijklmnopqrstuvwxyz",dC="0123456789",nT={DIGIT:dC,ALPHA:u0,ALPHA_DIGIT:u0+u0.toUpperCase()+dC},YF=(e=16,t=nT.ALPHA_DIGIT)=>{let n="";const{length:r}=t;for(;e--;)n+=t[Math.random()*r|0];return n};function GF(e){return!!(e&&Kr(e.append)&&e[Symbol.toStringTag]==="FormData"&&e[Symbol.iterator])}const XF=e=>{const t=new Array(10),n=(r,o)=>{if(Rm(r)){if(t.indexOf(r)>=0)return;if(!("toJSON"in r)){t[o]=r;const i=gc(r)?[]:{};return kd(r,(s,l)=>{const u=n(s,o+1);!Zu(u)&&(i[l]=u)}),t[o]=void 0,i}}return r};return n(e,0)},ZF=Go("AsyncFunction"),qF=e=>e&&(Rm(e)||Kr(e))&&Kr(e.then)&&Kr(e.catch),oe={isArray:gc,isArrayBuffer:ZR,isBuffer:wF,isFormData:RF,isArrayBufferView:xF,isString:bF,isNumber:qR,isBoolean:_F,isObject:Rm,isPlainObject:Fp,isUndefined:Zu,isDate:SF,isFile:EF,isBlob:CF,isRegExp:UF,isFunction:Kr,isStream:kF,isURLSearchParams:TF,isTypedArray:LF,isFileList:$F,forEach:kd,merge:Yy,extend:AF,trim:PF,stripBOM:OF,inherits:MF,toFlatObject:NF,kindOf:$m,kindOfTest:Go,endsWith:DF,toArray:IF,forEachEntry:FF,matchAll:jF,isHTMLForm:zF,hasOwnProperty:uC,hasOwnProp:uC,reduceDescriptors:tT,freezeMethods:VF,toObjectSet:WF,toCamelCase:BF,noop:HF,toFiniteNumber:KF,findKey:QR,global:JR,isContextDefined:eT,ALPHABET:nT,generateString:YF,isSpecCompliantForm:GF,toJSONObject:XF,isAsyncFn:ZF,isThenable:qF};function ut(e,t,n,r,o){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),n&&(this.config=n),r&&(this.request=r),o&&(this.response=o)}oe.inherits(ut,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:oe.toJSONObject(this.config),code:this.code,status:this.response&&this.response.status?this.response.status:null}}});const rT=ut.prototype,oT={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{oT[e]={value:e}});Object.defineProperties(ut,oT);Object.defineProperty(rT,"isAxiosError",{value:!0});ut.from=(e,t,n,r,o,i)=>{const s=Object.create(rT);return oe.toFlatObject(e,s,function(u){return u!==Error.prototype},l=>l!=="isAxiosError"),ut.call(s,e.message,t,n,r,o),s.cause=e,s.name=e.name,i&&Object.assign(s,i),s};const QF=null;function Gy(e){return oe.isPlainObject(e)||oe.isArray(e)}function iT(e){return oe.endsWith(e,"[]")?e.slice(0,-2):e}function fC(e,t,n){return e?e.concat(t).map(function(o,i){return o=iT(o),!n&&i?"["+o+"]":o}).join(n?".":""):t}function JF(e){return oe.isArray(e)&&!e.some(Gy)}const ej=oe.toFlatObject(oe,{},null,function(t){return/^is[A-Z]/.test(t)});function Tm(e,t,n){if(!oe.isObject(e))throw new TypeError("target must be an object");t=t||new FormData,n=oe.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(_,C){return!oe.isUndefined(C[_])});const r=n.metaTokens,o=n.visitor||h,i=n.dots,s=n.indexes,u=(n.Blob||typeof Blob<"u"&&Blob)&&oe.isSpecCompliantForm(t);if(!oe.isFunction(o))throw new TypeError("visitor must be a function");function d(x){if(x===null)return"";if(oe.isDate(x))return x.toISOString();if(!u&&oe.isBlob(x))throw new ut("Blob is not supported. Use a Buffer instead.");return oe.isArrayBuffer(x)||oe.isTypedArray(x)?u&&typeof Blob=="function"?new Blob([x]):Buffer.from(x):x}function h(x,_,C){let S=x;if(x&&!C&&typeof x=="object"){if(oe.endsWith(_,"{}"))_=r?_:_.slice(0,-2),x=JSON.stringify(x);else if(oe.isArray(x)&&JF(x)||(oe.isFileList(x)||oe.endsWith(_,"[]"))&&(S=oe.toArray(x)))return _=iT(_),S.forEach(function(E,k){!(oe.isUndefined(E)||E===null)&&t.append(s===!0?fC([_],k,i):s===null?_:_+"[]",d(E))}),!1}return Gy(x)?!0:(t.append(fC(C,_,i),d(x)),!1)}const m=[],g=Object.assign(ej,{defaultVisitor:h,convertValue:d,isVisitable:Gy});function y(x,_){if(!oe.isUndefined(x)){if(m.indexOf(x)!==-1)throw Error("Circular reference detected in "+_.join("."));m.push(x),oe.forEach(x,function(S,b){(!(oe.isUndefined(S)||S===null)&&o.call(t,S,oe.isString(b)?b.trim():b,_,g))===!0&&y(S,_?_.concat(b):[b])}),m.pop()}}if(!oe.isObject(e))throw new TypeError("data must be an object");return y(e),t}function pC(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(r){return t[r]})}function tx(e,t){this._pairs=[],e&&Tm(e,this,t)}const sT=tx.prototype;sT.append=function(t,n){this._pairs.push([t,n])};sT.toString=function(t){const n=t?function(r){return t.call(this,r,pC)}:pC;return this._pairs.map(function(o){return n(o[0])+"="+n(o[1])},"").join("&")};function tj(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function aT(e,t,n){if(!t)return e;const r=n&&n.encode||tj,o=n&&n.serialize;let i;if(o?i=o(t,n):i=oe.isURLSearchParams(t)?t.toString():new tx(t,n).toString(r),i){const s=e.indexOf("#");s!==-1&&(e=e.slice(0,s)),e+=(e.indexOf("?")===-1?"?":"&")+i}return e}class nj{constructor(){this.handlers=[]}use(t,n,r){return this.handlers.push({fulfilled:t,rejected:n,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){oe.forEach(this.handlers,function(r){r!==null&&t(r)})}}const hC=nj,lT={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},rj=typeof URLSearchParams<"u"?URLSearchParams:tx,oj=typeof FormData<"u"?FormData:null,ij=typeof Blob<"u"?Blob:null,sj={isBrowser:!0,classes:{URLSearchParams:rj,FormData:oj,Blob:ij},protocols:["http","https","file","blob","url","data"]},cT=typeof window<"u"&&typeof document<"u",aj=(e=>cT&&["ReactNative","NativeScript","NS"].indexOf(e)<0)(typeof navigator<"u"&&navigator.product),lj=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",cj=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:cT,hasStandardBrowserEnv:aj,hasStandardBrowserWebWorkerEnv:lj},Symbol.toStringTag,{value:"Module"})),Io={...cj,...sj};function uj(e,t){return Tm(e,new Io.classes.URLSearchParams,Object.assign({visitor:function(n,r,o,i){return Io.isNode&&oe.isBuffer(n)?(this.append(r,n.toString("base64")),!1):i.defaultVisitor.apply(this,arguments)}},t))}function dj(e){return oe.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function fj(e){const t={},n=Object.keys(e);let r;const o=n.length;let i;for(r=0;r=n.length;return s=!s&&oe.isArray(o)?o.length:s,u?(oe.hasOwnProp(o,s)?o[s]=[o[s],r]:o[s]=r,!l):((!o[s]||!oe.isObject(o[s]))&&(o[s]=[]),t(n,r,o[s],i)&&oe.isArray(o[s])&&(o[s]=fj(o[s])),!l)}if(oe.isFormData(e)&&oe.isFunction(e.entries)){const n={};return oe.forEachEntry(e,(r,o)=>{t(dj(r),o,n,0)}),n}return null}function pj(e,t,n){if(oe.isString(e))try{return(t||JSON.parse)(e),oe.trim(e)}catch(r){if(r.name!=="SyntaxError")throw r}return(n||JSON.stringify)(e)}const nx={transitional:lT,adapter:["xhr","http"],transformRequest:[function(t,n){const r=n.getContentType()||"",o=r.indexOf("application/json")>-1,i=oe.isObject(t);if(i&&oe.isHTMLForm(t)&&(t=new FormData(t)),oe.isFormData(t))return o&&o?JSON.stringify(uT(t)):t;if(oe.isArrayBuffer(t)||oe.isBuffer(t)||oe.isStream(t)||oe.isFile(t)||oe.isBlob(t))return t;if(oe.isArrayBufferView(t))return t.buffer;if(oe.isURLSearchParams(t))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let l;if(i){if(r.indexOf("application/x-www-form-urlencoded")>-1)return uj(t,this.formSerializer).toString();if((l=oe.isFileList(t))||r.indexOf("multipart/form-data")>-1){const u=this.env&&this.env.FormData;return Tm(l?{"files[]":t}:t,u&&new u,this.formSerializer)}}return i||o?(n.setContentType("application/json",!1),pj(t)):t}],transformResponse:[function(t){const n=this.transitional||nx.transitional,r=n&&n.forcedJSONParsing,o=this.responseType==="json";if(t&&oe.isString(t)&&(r&&!this.responseType||o)){const s=!(n&&n.silentJSONParsing)&&o;try{return JSON.parse(t)}catch(l){if(s)throw l.name==="SyntaxError"?ut.from(l,ut.ERR_BAD_RESPONSE,this,null,this.response):l}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:Io.classes.FormData,Blob:Io.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};oe.forEach(["delete","get","head","post","put","patch"],e=>{nx.headers[e]={}});const rx=nx,hj=oe.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),mj=e=>{const t={};let n,r,o;return e&&e.split(` +`).forEach(function(s){o=s.indexOf(":"),n=s.substring(0,o).trim().toLowerCase(),r=s.substring(o+1).trim(),!(!n||t[n]&&hj[n])&&(n==="set-cookie"?t[n]?t[n].push(r):t[n]=[r]:t[n]=t[n]?t[n]+", "+r:r)}),t},mC=Symbol("internals");function ou(e){return e&&String(e).trim().toLowerCase()}function jp(e){return e===!1||e==null?e:oe.isArray(e)?e.map(jp):String(e)}function gj(e){const t=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=n.exec(e);)t[r[1]]=r[2];return t}const vj=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function d0(e,t,n,r,o){if(oe.isFunction(r))return r.call(this,t,n);if(o&&(t=n),!!oe.isString(t)){if(oe.isString(r))return t.indexOf(r)!==-1;if(oe.isRegExp(r))return r.test(t)}}function yj(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,n,r)=>n.toUpperCase()+r)}function wj(e,t){const n=oe.toCamelCase(" "+t);["get","set","has"].forEach(r=>{Object.defineProperty(e,r+n,{value:function(o,i,s){return this[r].call(this,t,o,i,s)},configurable:!0})})}class Pm{constructor(t){t&&this.set(t)}set(t,n,r){const o=this;function i(l,u,d){const h=ou(u);if(!h)throw new Error("header name must be a non-empty string");const m=oe.findKey(o,h);(!m||o[m]===void 0||d===!0||d===void 0&&o[m]!==!1)&&(o[m||u]=jp(l))}const s=(l,u)=>oe.forEach(l,(d,h)=>i(d,h,u));return oe.isPlainObject(t)||t instanceof this.constructor?s(t,n):oe.isString(t)&&(t=t.trim())&&!vj(t)?s(mj(t),n):t!=null&&i(n,t,r),this}get(t,n){if(t=ou(t),t){const r=oe.findKey(this,t);if(r){const o=this[r];if(!n)return o;if(n===!0)return gj(o);if(oe.isFunction(n))return n.call(this,o,r);if(oe.isRegExp(n))return n.exec(o);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,n){if(t=ou(t),t){const r=oe.findKey(this,t);return!!(r&&this[r]!==void 0&&(!n||d0(this,this[r],r,n)))}return!1}delete(t,n){const r=this;let o=!1;function i(s){if(s=ou(s),s){const l=oe.findKey(r,s);l&&(!n||d0(r,r[l],l,n))&&(delete r[l],o=!0)}}return oe.isArray(t)?t.forEach(i):i(t),o}clear(t){const n=Object.keys(this);let r=n.length,o=!1;for(;r--;){const i=n[r];(!t||d0(this,this[i],i,t,!0))&&(delete this[i],o=!0)}return o}normalize(t){const n=this,r={};return oe.forEach(this,(o,i)=>{const s=oe.findKey(r,i);if(s){n[s]=jp(o),delete n[i];return}const l=t?yj(i):String(i).trim();l!==i&&delete n[i],n[l]=jp(o),r[l]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){const n=Object.create(null);return oe.forEach(this,(r,o)=>{r!=null&&r!==!1&&(n[o]=t&&oe.isArray(r)?r.join(", "):r)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,n])=>t+": "+n).join(` +`)}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...n){const r=new this(t);return n.forEach(o=>r.set(o)),r}static accessor(t){const r=(this[mC]=this[mC]={accessors:{}}).accessors,o=this.prototype;function i(s){const l=ou(s);r[l]||(wj(o,s),r[l]=!0)}return oe.isArray(t)?t.forEach(i):i(t),this}}Pm.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);oe.reduceDescriptors(Pm.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(r){this[n]=r}}});oe.freezeMethods(Pm);const pi=Pm;function f0(e,t){const n=this||rx,r=t||n,o=pi.from(r.headers);let i=r.data;return oe.forEach(e,function(l){i=l.call(n,i,o.normalize(),t?t.status:void 0)}),o.normalize(),i}function dT(e){return!!(e&&e.__CANCEL__)}function Rd(e,t,n){ut.call(this,e??"canceled",ut.ERR_CANCELED,t,n),this.name="CanceledError"}oe.inherits(Rd,ut,{__CANCEL__:!0});function xj(e,t,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?e(n):t(new ut("Request failed with status code "+n.status,[ut.ERR_BAD_REQUEST,ut.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}const bj=Io.hasStandardBrowserEnv?{write(e,t,n,r,o,i){const s=[e+"="+encodeURIComponent(t)];oe.isNumber(n)&&s.push("expires="+new Date(n).toGMTString()),oe.isString(r)&&s.push("path="+r),oe.isString(o)&&s.push("domain="+o),i===!0&&s.push("secure"),document.cookie=s.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function _j(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function Sj(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e}function fT(e,t){return e&&!_j(t)?Sj(e,t):t}const Ej=Io.hasStandardBrowserEnv?function(){const t=/(msie|trident)/i.test(navigator.userAgent),n=document.createElement("a");let r;function o(i){let s=i;return t&&(n.setAttribute("href",s),s=n.href),n.setAttribute("href",s),{href:n.href,protocol:n.protocol?n.protocol.replace(/:$/,""):"",host:n.host,search:n.search?n.search.replace(/^\?/,""):"",hash:n.hash?n.hash.replace(/^#/,""):"",hostname:n.hostname,port:n.port,pathname:n.pathname.charAt(0)==="/"?n.pathname:"/"+n.pathname}}return r=o(window.location.href),function(s){const l=oe.isString(s)?o(s):s;return l.protocol===r.protocol&&l.host===r.host}}():function(){return function(){return!0}}();function Cj(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function $j(e,t){e=e||10;const n=new Array(e),r=new Array(e);let o=0,i=0,s;return t=t!==void 0?t:1e3,function(u){const d=Date.now(),h=r[i];s||(s=d),n[o]=u,r[o]=d;let m=i,g=0;for(;m!==o;)g+=n[m++],m=m%e;if(o=(o+1)%e,o===i&&(i=(i+1)%e),d-s{const i=o.loaded,s=o.lengthComputable?o.total:void 0,l=i-n,u=r(l),d=i<=s;n=i;const h={loaded:i,total:s,progress:s?i/s:void 0,bytes:l,rate:u||void 0,estimated:u&&s&&d?(s-i)/u:void 0,event:o};h[t?"download":"upload"]=!0,e(h)}}const kj=typeof XMLHttpRequest<"u",Rj=kj&&function(e){return new Promise(function(n,r){let o=e.data;const i=pi.from(e.headers).normalize();let{responseType:s,withXSRFToken:l}=e,u;function d(){e.cancelToken&&e.cancelToken.unsubscribe(u),e.signal&&e.signal.removeEventListener("abort",u)}let h;if(oe.isFormData(o)){if(Io.hasStandardBrowserEnv||Io.hasStandardBrowserWebWorkerEnv)i.setContentType(!1);else if((h=i.getContentType())!==!1){const[_,...C]=h?h.split(";").map(S=>S.trim()).filter(Boolean):[];i.setContentType([_||"multipart/form-data",...C].join("; "))}}let m=new XMLHttpRequest;if(e.auth){const _=e.auth.username||"",C=e.auth.password?unescape(encodeURIComponent(e.auth.password)):"";i.set("Authorization","Basic "+btoa(_+":"+C))}const g=fT(e.baseURL,e.url);m.open(e.method.toUpperCase(),aT(g,e.params,e.paramsSerializer),!0),m.timeout=e.timeout;function y(){if(!m)return;const _=pi.from("getAllResponseHeaders"in m&&m.getAllResponseHeaders()),S={data:!s||s==="text"||s==="json"?m.responseText:m.response,status:m.status,statusText:m.statusText,headers:_,config:e,request:m};xj(function(E){n(E),d()},function(E){r(E),d()},S),m=null}if("onloadend"in m?m.onloadend=y:m.onreadystatechange=function(){!m||m.readyState!==4||m.status===0&&!(m.responseURL&&m.responseURL.indexOf("file:")===0)||setTimeout(y)},m.onabort=function(){m&&(r(new ut("Request aborted",ut.ECONNABORTED,e,m)),m=null)},m.onerror=function(){r(new ut("Network Error",ut.ERR_NETWORK,e,m)),m=null},m.ontimeout=function(){let C=e.timeout?"timeout of "+e.timeout+"ms exceeded":"timeout exceeded";const S=e.transitional||lT;e.timeoutErrorMessage&&(C=e.timeoutErrorMessage),r(new ut(C,S.clarifyTimeoutError?ut.ETIMEDOUT:ut.ECONNABORTED,e,m)),m=null},Io.hasStandardBrowserEnv&&(l&&oe.isFunction(l)&&(l=l(e)),l||l!==!1&&Ej(g))){const _=e.xsrfHeaderName&&e.xsrfCookieName&&bj.read(e.xsrfCookieName);_&&i.set(e.xsrfHeaderName,_)}o===void 0&&i.setContentType(null),"setRequestHeader"in m&&oe.forEach(i.toJSON(),function(C,S){m.setRequestHeader(S,C)}),oe.isUndefined(e.withCredentials)||(m.withCredentials=!!e.withCredentials),s&&s!=="json"&&(m.responseType=e.responseType),typeof e.onDownloadProgress=="function"&&m.addEventListener("progress",gC(e.onDownloadProgress,!0)),typeof e.onUploadProgress=="function"&&m.upload&&m.upload.addEventListener("progress",gC(e.onUploadProgress)),(e.cancelToken||e.signal)&&(u=_=>{m&&(r(!_||_.type?new Rd(null,e,m):_),m.abort(),m=null)},e.cancelToken&&e.cancelToken.subscribe(u),e.signal&&(e.signal.aborted?u():e.signal.addEventListener("abort",u)));const x=Cj(g);if(x&&Io.protocols.indexOf(x)===-1){r(new ut("Unsupported protocol "+x+":",ut.ERR_BAD_REQUEST,e));return}m.send(o||null)})},Xy={http:QF,xhr:Rj};oe.forEach(Xy,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});const vC=e=>`- ${e}`,Tj=e=>oe.isFunction(e)||e===null||e===!1,pT={getAdapter:e=>{e=oe.isArray(e)?e:[e];const{length:t}=e;let n,r;const o={};for(let i=0;i`adapter ${l} `+(u===!1?"is not supported by the environment":"is not available in the build"));let s=t?i.length>1?`since : +`+i.map(vC).join(` +`):" "+vC(i[0]):"as no adapter specified";throw new ut("There is no suitable adapter to dispatch the request "+s,"ERR_NOT_SUPPORT")}return r},adapters:Xy};function p0(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Rd(null,e)}function yC(e){return p0(e),e.headers=pi.from(e.headers),e.data=f0.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),pT.getAdapter(e.adapter||rx.adapter)(e).then(function(r){return p0(e),r.data=f0.call(e,e.transformResponse,r),r.headers=pi.from(r.headers),r},function(r){return dT(r)||(p0(e),r&&r.response&&(r.response.data=f0.call(e,e.transformResponse,r.response),r.response.headers=pi.from(r.response.headers))),Promise.reject(r)})}const wC=e=>e instanceof pi?e.toJSON():e;function Jl(e,t){t=t||{};const n={};function r(d,h,m){return oe.isPlainObject(d)&&oe.isPlainObject(h)?oe.merge.call({caseless:m},d,h):oe.isPlainObject(h)?oe.merge({},h):oe.isArray(h)?h.slice():h}function o(d,h,m){if(oe.isUndefined(h)){if(!oe.isUndefined(d))return r(void 0,d,m)}else return r(d,h,m)}function i(d,h){if(!oe.isUndefined(h))return r(void 0,h)}function s(d,h){if(oe.isUndefined(h)){if(!oe.isUndefined(d))return r(void 0,d)}else return r(void 0,h)}function l(d,h,m){if(m in t)return r(d,h);if(m in e)return r(void 0,d)}const u={url:i,method:i,data:i,baseURL:s,transformRequest:s,transformResponse:s,paramsSerializer:s,timeout:s,timeoutMessage:s,withCredentials:s,withXSRFToken:s,adapter:s,responseType:s,xsrfCookieName:s,xsrfHeaderName:s,onUploadProgress:s,onDownloadProgress:s,decompress:s,maxContentLength:s,maxBodyLength:s,beforeRedirect:s,transport:s,httpAgent:s,httpsAgent:s,cancelToken:s,socketPath:s,responseEncoding:s,validateStatus:l,headers:(d,h)=>o(wC(d),wC(h),!0)};return oe.forEach(Object.keys(Object.assign({},e,t)),function(h){const m=u[h]||o,g=m(e[h],t[h],h);oe.isUndefined(g)&&m!==l||(n[h]=g)}),n}const hT="1.6.2",ox={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{ox[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const xC={};ox.transitional=function(t,n,r){function o(i,s){return"[Axios v"+hT+"] Transitional option '"+i+"'"+s+(r?". "+r:"")}return(i,s,l)=>{if(t===!1)throw new ut(o(s," has been removed"+(n?" in "+n:"")),ut.ERR_DEPRECATED);return n&&!xC[s]&&(xC[s]=!0,console.warn(o(s," has been deprecated since v"+n+" and will be removed in the near future"))),t?t(i,s,l):!0}};function Pj(e,t,n){if(typeof e!="object")throw new ut("options must be an object",ut.ERR_BAD_OPTION_VALUE);const r=Object.keys(e);let o=r.length;for(;o-- >0;){const i=r[o],s=t[i];if(s){const l=e[i],u=l===void 0||s(l,i,e);if(u!==!0)throw new ut("option "+i+" must be "+u,ut.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new ut("Unknown option "+i,ut.ERR_BAD_OPTION)}}const Zy={assertOptions:Pj,validators:ox},Ui=Zy.validators;class Ph{constructor(t){this.defaults=t,this.interceptors={request:new hC,response:new hC}}request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=Jl(this.defaults,n);const{transitional:r,paramsSerializer:o,headers:i}=n;r!==void 0&&Zy.assertOptions(r,{silentJSONParsing:Ui.transitional(Ui.boolean),forcedJSONParsing:Ui.transitional(Ui.boolean),clarifyTimeoutError:Ui.transitional(Ui.boolean)},!1),o!=null&&(oe.isFunction(o)?n.paramsSerializer={serialize:o}:Zy.assertOptions(o,{encode:Ui.function,serialize:Ui.function},!0)),n.method=(n.method||this.defaults.method||"get").toLowerCase();let s=i&&oe.merge(i.common,i[n.method]);i&&oe.forEach(["delete","get","head","post","put","patch","common"],x=>{delete i[x]}),n.headers=pi.concat(s,i);const l=[];let u=!0;this.interceptors.request.forEach(function(_){typeof _.runWhen=="function"&&_.runWhen(n)===!1||(u=u&&_.synchronous,l.unshift(_.fulfilled,_.rejected))});const d=[];this.interceptors.response.forEach(function(_){d.push(_.fulfilled,_.rejected)});let h,m=0,g;if(!u){const x=[yC.bind(this),void 0];for(x.unshift.apply(x,l),x.push.apply(x,d),g=x.length,h=Promise.resolve(n);m{if(!r._listeners)return;let i=r._listeners.length;for(;i-- >0;)r._listeners[i](o);r._listeners=null}),this.promise.then=o=>{let i;const s=new Promise(l=>{r.subscribe(l),i=l}).then(o);return s.cancel=function(){r.unsubscribe(i)},s},t(function(i,s,l){r.reason||(r.reason=new Rd(i,s,l),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}static source(){let t;return{token:new ix(function(o){t=o}),cancel:t}}}const Aj=ix;function Oj(e){return function(n){return e.apply(null,n)}}function Mj(e){return oe.isObject(e)&&e.isAxiosError===!0}const qy={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(qy).forEach(([e,t])=>{qy[t]=e});const Nj=qy;function mT(e){const t=new zp(e),n=XR(zp.prototype.request,t);return oe.extend(n,zp.prototype,t,{allOwnKeys:!0}),oe.extend(n,t,null,{allOwnKeys:!0}),n.create=function(o){return mT(Jl(e,o))},n}const Jt=mT(rx);Jt.Axios=zp;Jt.CanceledError=Rd;Jt.CancelToken=Aj;Jt.isCancel=dT;Jt.VERSION=hT;Jt.toFormData=Tm;Jt.AxiosError=ut;Jt.Cancel=Jt.CanceledError;Jt.all=function(t){return Promise.all(t)};Jt.spread=Oj;Jt.isAxiosError=Mj;Jt.mergeConfig=Jl;Jt.AxiosHeaders=pi;Jt.formToJSON=e=>uT(oe.isHTMLForm(e)?new FormData(e):e);Jt.getAdapter=pT.getAdapter;Jt.HttpStatusCode=Nj;Jt.default=Jt;const Dj=Jt,Ms="/api/v1",vc=Dj.create({baseURL:Ms});async function Ij(e,t,n,r,o,i=null){const s=await Ru(e),l=await Ru(o),u=i?await Ru(i):null,d=await fetch(`${Ms}/inpaint`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({image:s,mask:l,ldm_steps:t.ldmSteps,ldm_sampler:t.ldmSampler,zits_wireframe:t.zitsWireframe,cv2_flag:t.cv2Flag,cv2_radius:t.cv2Radius,hd_strategy:"Crop",hd_strategy_crop_triger_size:640,hd_strategy_crop_margin:128,hd_trategy_resize_imit:2048,prompt:t.prompt,negative_prompt:t.negativePrompt,use_croper:t.showCropper,croper_x:n.x,croper_y:n.y,croper_height:n.height,croper_width:n.width,use_extender:t.showExtender,extender_x:r.x,extender_y:r.y,extender_height:r.height,extender_width:r.width,sd_mask_blur:t.sdMaskBlur,sd_strength:t.sdStrength,sd_steps:t.sdSteps,sd_guidance_scale:t.sdGuidanceScale,sd_sampler:t.sdSampler,sd_seed:t.seedFixed?t.seed:-1,sd_match_histograms:t.sdMatchHistograms,sd_freeu:t.enableFreeu,sd_freeu_config:t.freeuConfig,sd_lcm_lora:t.enableLCMLora,paint_by_example_example_image:u,p2p_image_guidance_scale:t.p2pImageGuidanceScale,enable_controlnet:t.enableControlnet,controlnet_conditioning_scale:t.controlnetConditioningScale,controlnet_method:t.controlnetMethod?t.controlnetMethod:"",powerpaint_task:t.showExtender?kl.outpainting:t.powerpaintTask})});if(d.ok){const m=await d.blob();return{blob:URL.createObjectURL(m),seed:d.headers.get("X-Seed")}}const h=await d.json();throw new Error(`Something went wrong: ${h.errors}`)}async function Lj(){return(await vc.get("/server-config")).data}async function Fj(e){return(await vc.post("/model",{name:e})).data}async function jj(){return(await vc.get("/model")).data}function zj(){return vc.get("/models").then(e=>e.data)}async function gT(e,t,n,r,o){const i=await Ru(n),l=await fetch(`${Ms}/${e?"run_plugin_gen_mask":"run_plugin_gen_image"}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t,image:i,upscale:r,clicks:o})});if(l.ok){const d=await l.blob();return{blob:URL.createObjectURL(d)}}const u=await l.json();throw new Error(u)}async function Bj(e,t){const n=await fetch(`${Ms}/media_file?tab=${e}&filename=${encodeURIComponent(t)}`,{method:"GET"});if(n.ok){const o=await n.blob();return new File([o],t,{type:n.headers.get("Content-Type")??"image/png"})}const r=await n.json();throw new Error(r.errors)}async function Uj(e){return(await vc.get("medias",{params:{tab:e}})).data}async function Vj(e,t,n){const r=await ku(e.src,t,n),o=new FormData;o.append("file",r);try{const i=await fetch(`${Ms}/save_image`,{method:"POST",body:o});if(!i.ok){const s=await i.text();throw new Error(s)}}catch(i){throw new Error(`Something went wrong: ${i}`)}}async function Wj(e){const t=new FormData;return t.append("file",e),(await vc.post("/gen-info",t)).data}async function Hj(e,t,n){const r=await Ru(e),o=await fetch(`${Ms}/adjust_mask`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mask:r,operate:t,kernel_size:n})});if(o.ok)return await o.blob();const i=await o.json();throw new Error(i)}function Kj(){const[e,t]=f.useState(null),n=f.useCallback(()=>{const r=new Headers;r.append("pragma","no-cache"),r.append("cache-control","no-cache"),fetch(`${Ms}/inputimage`,{headers:r}).then(async o=>{var l;if(!o.ok)throw new Error("No input image found");const i=(l=o.headers.get("content-disposition"))==null?void 0:l.split("filename=")[1].split(";")[0],s=await o.blob();if(s&&s.type.startsWith("image")){const u=new File([s],i!==void 0?i:"inputImage");t(u)}}).catch(o=>{console.log(o)})},[t]);return f.useEffect(()=>{n()},[n]),e}function xo(e,t){if(e==null)return{};var n={},r=Object.keys(e),o,i;for(i=0;i=0)&&(n[o]=e[o]);return n}var Yj=["color"],Gj=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,Yj);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),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:r,fillRule:"evenodd",clipRule:"evenodd"}))}),Xj=["color"],vT=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,Xj);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M11.4669 3.72684C11.7558 3.91574 11.8369 4.30308 11.648 4.59198L7.39799 11.092C7.29783 11.2452 7.13556 11.3467 6.95402 11.3699C6.77247 11.3931 6.58989 11.3355 6.45446 11.2124L3.70446 8.71241C3.44905 8.48022 3.43023 8.08494 3.66242 7.82953C3.89461 7.57412 4.28989 7.55529 4.5453 7.78749L6.75292 9.79441L10.6018 3.90792C10.7907 3.61902 11.178 3.53795 11.4669 3.72684Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),Zj=["color"],qj=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,Zj);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M3.13523 6.15803C3.3241 5.95657 3.64052 5.94637 3.84197 6.13523L7.5 9.56464L11.158 6.13523C11.3595 5.94637 11.6759 5.95657 11.8648 6.15803C12.0536 6.35949 12.0434 6.67591 11.842 6.86477L7.84197 10.6148C7.64964 10.7951 7.35036 10.7951 7.15803 10.6148L3.15803 6.86477C2.95657 6.67591 2.94637 6.35949 3.13523 6.15803Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),Qj=["color"],Jj=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,Qj);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M6.1584 3.13508C6.35985 2.94621 6.67627 2.95642 6.86514 3.15788L10.6151 7.15788C10.7954 7.3502 10.7954 7.64949 10.6151 7.84182L6.86514 11.8418C6.67627 12.0433 6.35985 12.0535 6.1584 11.8646C5.95694 11.6757 5.94673 11.3593 6.1356 11.1579L9.565 7.49985L6.1356 3.84182C5.94673 3.64036 5.95694 3.32394 6.1584 3.13508Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),ez=["color"],tz=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,ez);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M3.13523 8.84197C3.3241 9.04343 3.64052 9.05363 3.84197 8.86477L7.5 5.43536L11.158 8.86477C11.3595 9.05363 11.6759 9.04343 11.8648 8.84197C12.0536 8.64051 12.0434 8.32409 11.842 8.13523L7.84197 4.38523C7.64964 4.20492 7.35036 4.20492 7.15803 4.38523L3.15803 8.13523C2.95657 8.32409 2.94637 8.64051 3.13523 8.84197Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),nz=["color"],yT=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,nz);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),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:r,fillRule:"evenodd",clipRule:"evenodd"}))}),rz=["color"],oz=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,rz);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M9.875 7.5C9.875 8.81168 8.81168 9.875 7.5 9.875C6.18832 9.875 5.125 8.81168 5.125 7.5C5.125 6.18832 6.18832 5.125 7.5 5.125C8.81168 5.125 9.875 6.18832 9.875 7.5Z",fill:r}))}),iz=["color"],sz=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,iz);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M10 6.5C10 8.433 8.433 10 6.5 10C4.567 10 3 8.433 3 6.5C3 4.567 4.567 3 6.5 3C8.433 3 10 4.567 10 6.5ZM9.30884 10.0159C8.53901 10.6318 7.56251 11 6.5 11C4.01472 11 2 8.98528 2 6.5C2 4.01472 4.01472 2 6.5 2C8.98528 2 11 4.01472 11 6.5C11 7.56251 10.6318 8.53901 10.0159 9.30884L12.8536 12.1464C13.0488 12.3417 13.0488 12.6583 12.8536 12.8536C12.6583 13.0488 12.3417 13.0488 12.1464 12.8536L9.30884 10.0159Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),az=["color"],lz=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,az);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M3.24182 2.32181C3.3919 2.23132 3.5784 2.22601 3.73338 2.30781L12.7334 7.05781C12.8974 7.14436 13 7.31457 13 7.5C13 7.68543 12.8974 7.85564 12.7334 7.94219L3.73338 12.6922C3.5784 12.774 3.3919 12.7687 3.24182 12.6782C3.09175 12.5877 3 12.4252 3 12.25V2.75C3 2.57476 3.09175 2.4123 3.24182 2.32181ZM4 3.57925V11.4207L11.4288 7.5L4 3.57925Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),cz=["color"],uz=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,cz);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M7 2H1.5C1.22386 2 1 2.22386 1 2.5V7H7V2ZM8 2V7H14V2.5C14 2.22386 13.7761 2 13.5 2H8ZM7 8H1V12.5C1 12.7761 1.22386 13 1.5 13H7V8ZM8 13V8H14V12.5C14 12.7761 13.7761 13 13.5 13H8ZM1.5 1C0.671573 1 0 1.67157 0 2.5V12.5C0 13.3284 0.671573 14 1.5 14H13.5C14.3284 14 15 13.3284 15 12.5V2.5C15 1.67157 14.3284 1 13.5 1H1.5Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),dz=["color"],fz=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,dz);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M1.5 2H13.5C13.7761 2 14 2.22386 14 2.5V7H1V2.5C1 2.22386 1.22386 2 1.5 2ZM1 8V12.5C1 12.7761 1.22386 13 1.5 13H13.5C13.7761 13 14 12.7761 14 12.5V8H1ZM0 2.5C0 1.67157 0.671573 1 1.5 1H13.5C14.3284 1 15 1.67157 15 2.5V12.5C15 13.3284 14.3284 14 13.5 14H1.5C0.671573 14 0 13.3284 0 12.5V2.5Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))});function Y(){return Y=Object.assign?Object.assign.bind():function(e){for(var t=1;te.forEach(n=>pz(n,t))}function Be(...e){return f.useCallback(Am(...e),e)}const Wo=f.forwardRef((e,t)=>{const{children:n,...r}=e,o=f.Children.toArray(n),i=o.find(hz);if(i){const s=i.props.children,l=o.map(u=>u===i?f.Children.count(s)>1?f.Children.only(null):f.isValidElement(s)?s.props.children:null:u);return f.createElement(Qy,Y({},r,{ref:t}),f.isValidElement(s)?f.cloneElement(s,void 0,l):null)}return f.createElement(Qy,Y({},r,{ref:t}),n)});Wo.displayName="Slot";const Qy=f.forwardRef((e,t)=>{const{children:n,...r}=e;return f.isValidElement(n)?f.cloneElement(n,{...mz(r,n.props),ref:t?Am(t,n.ref):n.ref}):f.Children.count(n)>1?f.Children.only(null):null});Qy.displayName="SlotClone";const sx=({children:e})=>f.createElement(f.Fragment,null,e);function hz(e){return f.isValidElement(e)&&e.type===sx}function mz(e,t){const n={...t};for(const r in t){const o=e[r],i=t[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...l)=>{i(...l),o(...l)}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...e,...n}}const bC=e=>typeof e=="boolean"?"".concat(e):e===0?"0":e,_C=BR,Om=(e,t)=>n=>{var r;if((t==null?void 0:t.variants)==null)return _C(e,n==null?void 0:n.class,n==null?void 0:n.className);const{variants:o,defaultVariants:i}=t,s=Object.keys(o).map(d=>{const h=n==null?void 0:n[d],m=i==null?void 0:i[d];if(h===null)return null;const g=bC(h)||bC(m);return o[d][g]}),l=n&&Object.entries(n).reduce((d,h)=>{let[m,g]=h;return g===void 0||(d[m]=g),d},{}),u=t==null||(r=t.compoundVariants)===null||r===void 0?void 0:r.reduce((d,h)=>{let{class:m,className:g,...y}=h;return Object.entries(y).every(x=>{let[_,C]=x;return Array.isArray(C)?C.includes({...i,...l}[_]):{...i,...l}[_]===C})?[...d,m,g]:d},[]);return _C(e,s,u,n==null?void 0:n.class,n==null?void 0:n.className)};var gz={VITE_BACKEND:"http://127.0.0.1:8080",BASE_URL:"/",MODE:"production",DEV:!1,PROD:!0,SSR:!1};function vz(e,t){let n;try{n=e()}catch{return}return{getItem:o=>{var i;const s=u=>u===null?null:JSON.parse(u,t==null?void 0:t.reviver),l=(i=n.getItem(o))!=null?i:null;return l instanceof Promise?l.then(s):s(l)},setItem:(o,i)=>n.setItem(o,JSON.stringify(i,t==null?void 0:t.replacer)),removeItem:o=>n.removeItem(o)}}const qu=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then(r){return qu(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return qu(r)(n)}}}},yz=(e,t)=>(n,r,o)=>{let i={getStorage:()=>localStorage,serialize:JSON.stringify,deserialize:JSON.parse,partialize:C=>C,version:0,merge:(C,S)=>({...S,...C}),...t},s=!1;const l=new Set,u=new Set;let d;try{d=i.getStorage()}catch{}if(!d)return e((...C)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),n(...C)},r,o);const h=qu(i.serialize),m=()=>{const C=i.partialize({...r()});let S;const b=h({state:C,version:i.version}).then(E=>d.setItem(i.name,E)).catch(E=>{S=E});if(S)throw S;return b},g=o.setState;o.setState=(C,S)=>{g(C,S),m()};const y=e((...C)=>{n(...C),m()},r,o);let x;const _=()=>{var C;if(!d)return;s=!1,l.forEach(b=>b(r()));const S=((C=i.onRehydrateStorage)==null?void 0:C.call(i,r()))||void 0;return qu(d.getItem.bind(d))(i.name).then(b=>{if(b)return i.deserialize(b)}).then(b=>{if(b)if(typeof b.version=="number"&&b.version!==i.version){if(i.migrate)return i.migrate(b.state,b.version);console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return b.state}).then(b=>{var E;return x=i.merge(b,(E=r())!=null?E:y),n(x,!0),m()}).then(()=>{S==null||S(x,void 0),s=!0,u.forEach(b=>b(x))}).catch(b=>{S==null||S(void 0,b)})};return o.persist={setOptions:C=>{i={...i,...C},C.getStorage&&(d=C.getStorage())},clearStorage:()=>{d==null||d.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>_(),hasHydrated:()=>s,onHydrate:C=>(l.add(C),()=>{l.delete(C)}),onFinishHydration:C=>(u.add(C),()=>{u.delete(C)})},_(),x||y},wz=(e,t)=>(n,r,o)=>{let i={storage:vz(()=>localStorage),partialize:_=>_,version:0,merge:(_,C)=>({...C,..._}),...t},s=!1;const l=new Set,u=new Set;let d=i.storage;if(!d)return e((..._)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),n(..._)},r,o);const h=()=>{const _=i.partialize({...r()});return d.setItem(i.name,{state:_,version:i.version})},m=o.setState;o.setState=(_,C)=>{m(_,C),h()};const g=e((..._)=>{n(..._),h()},r,o);let y;const x=()=>{var _,C;if(!d)return;s=!1,l.forEach(b=>{var E;return b((E=r())!=null?E:g)});const S=((C=i.onRehydrateStorage)==null?void 0:C.call(i,(_=r())!=null?_:g))||void 0;return qu(d.getItem.bind(d))(i.name).then(b=>{if(b)if(typeof b.version=="number"&&b.version!==i.version){if(i.migrate)return i.migrate(b.state,b.version);console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return b.state}).then(b=>{var E;return y=i.merge(b,(E=r())!=null?E:g),n(y,!0),h()}).then(()=>{S==null||S(y,void 0),y=r(),s=!0,u.forEach(b=>b(y))}).catch(b=>{S==null||S(void 0,b)})};return o.persist={setOptions:_=>{i={...i,..._},_.storage&&(d=_.storage)},clearStorage:()=>{d==null||d.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>x(),hasHydrated:()=>s,onHydrate:_=>(l.add(_),()=>{l.delete(_)}),onFinishHydration:_=>(u.add(_),()=>{u.delete(_)})},i.skipHydration||x(),y||g},xz=(e,t)=>"getStorage"in t||"serialize"in t||"deserialize"in t?((gz?"production":void 0)!=="production"&&console.warn("[DEPRECATED] `getStorage`, `serialize` and `deserialize` options are deprecated. Use `storage` option instead."),yz(e,t)):wz(e,t),bz=xz;function _z(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,o]of e)if(!Object.is(o,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{t(n,r,e)}):e.forEach((n,r)=>t(r,n,e))}function Mm(e){const t=e[wr];return t?t.type_:Array.isArray(e)?1:Nm(e)?2:Dm(e)?3:0}function Jy(e,t){return Mm(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function bT(e,t,n){const r=Mm(e);r===2?e.set(t,n):r===3?e.add(n):e[t]=n}function Ez(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function Nm(e){return e instanceof Map}function Dm(e){return e instanceof Set}function Js(e){return e.copy_||e.base_}function e1(e,t){if(Nm(e))return new Map(e);if(Dm(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);if(!t&&xT(e))return ec(e)?{...e}:Object.assign(Object.create(null),e);const n=Object.getOwnPropertyDescriptors(e);delete n[wr];let r=Reflect.ownKeys(n);for(let o=0;o1&&(e.set=e.add=e.clear=e.delete=Cz),Object.freeze(e),t&&Qu(e,(n,r)=>ax(r,!0))),e}function Cz(){ho(2)}function Im(e){return Object.isFrozen(e)}var $z={};function ka(e){const t=$z[e];return t||ho(0,e),t}var Ju;function _T(){return Ju}function kz(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function EC(e,t){t&&(ka("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function t1(e){n1(e),e.drafts_.forEach(Rz),e.drafts_=null}function n1(e){e===Ju&&(Ju=e.parent_)}function CC(e){return Ju=kz(Ju,e)}function Rz(e){const t=e[wr];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function $C(e,t){t.unfinalizedDrafts_=t.drafts_.length;const n=t.drafts_[0];return e!==void 0&&e!==n?(n[wr].modified_&&(t1(t),ho(4)),$a(e)&&(e=Ah(t,e),t.parent_||Oh(t,e)),t.patches_&&ka("Patches").generateReplacementPatches_(n[wr].base_,e,t.patches_,t.inversePatches_)):e=Ah(t,n,[]),t1(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==wT?e:void 0}function Ah(e,t,n){if(Im(t))return t;const r=t[wr];if(!r)return Qu(t,(o,i)=>kC(e,r,t,o,i,n)),t;if(r.scope_!==e)return t;if(!r.modified_)return Oh(e,r.base_,!0),r.base_;if(!r.finalized_){r.finalized_=!0,r.scope_.unfinalizedDrafts_--;const o=r.copy_;let i=o,s=!1;r.type_===3&&(i=new Set(o),o.clear(),s=!0),Qu(i,(l,u)=>kC(e,r,o,l,u,n,s)),Oh(e,o,!1),n&&e.patches_&&ka("Patches").generatePatches_(r,n,e.patches_,e.inversePatches_)}return r.copy_}function kC(e,t,n,r,o,i,s){if(tc(o)){const l=i&&t&&t.type_!==3&&!Jy(t.assigned_,r)?i.concat(r):void 0,u=Ah(e,o,l);if(bT(n,r,u),tc(u))e.canAutoFreeze_=!1;else return}else s&&n.add(o);if($a(o)&&!Im(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;Ah(e,o),(!t||!t.scope_.parent_)&&Oh(e,o)}}function Oh(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&ax(t,n)}function Tz(e,t){const n=Array.isArray(e),r={type_:n?1:0,scope_:t?t.scope_:_T(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1};let o=r,i=lx;n&&(o=[r],i=ed);const{revoke:s,proxy:l}=Proxy.revocable(o,i);return r.draft_=l,r.revoke_=s,l}var lx={get(e,t){if(t===wr)return e;const n=Js(e);if(!Jy(n,t))return Pz(e,n,t);const r=n[t];return e.finalized_||!$a(r)?r:r===h0(e.base_,t)?(m0(e),e.copy_[t]=o1(r,e)):r},has(e,t){return t in Js(e)},ownKeys(e){return Reflect.ownKeys(Js(e))},set(e,t,n){const r=ST(Js(e),t);if(r!=null&&r.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){const o=h0(Js(e),t),i=o==null?void 0:o[wr];if(i&&i.base_===n)return e.copy_[t]=n,e.assigned_[t]=!1,!0;if(Ez(n,o)&&(n!==void 0||Jy(e.base_,t)))return!0;m0(e),r1(e)}return e.copy_[t]===n&&(n!==void 0||t in e.copy_)||Number.isNaN(n)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=n,e.assigned_[t]=!0),!0},deleteProperty(e,t){return h0(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,m0(e),r1(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){const n=Js(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:r.enumerable,value:n[t]}},defineProperty(){ho(11)},getPrototypeOf(e){return ec(e.base_)},setPrototypeOf(){ho(12)}},ed={};Qu(lx,(e,t)=>{ed[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});ed.deleteProperty=function(e,t){return ed.set.call(this,e,t,void 0)};ed.set=function(e,t,n){return lx.set.call(this,e[0],t,n,e[0])};function h0(e,t){const n=e[wr];return(n?Js(n):e)[t]}function Pz(e,t,n){var o;const r=ST(t,n);return r?"value"in r?r.value:(o=r.get)==null?void 0:o.call(e.draft_):void 0}function ST(e,t){if(!(t in e))return;let n=ec(e);for(;n;){const r=Object.getOwnPropertyDescriptor(n,t);if(r)return r;n=ec(n)}}function r1(e){e.modified_||(e.modified_=!0,e.parent_&&r1(e.parent_))}function m0(e){e.copy_||(e.copy_=e1(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var Az=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(t,n,r)=>{if(typeof t=="function"&&typeof n!="function"){const i=n;n=t;const s=this;return function(u=i,...d){return s.produce(u,h=>n.call(this,h,...d))}}typeof n!="function"&&ho(6),r!==void 0&&typeof r!="function"&&ho(7);let o;if($a(t)){const i=CC(this),s=o1(t,void 0);let l=!0;try{o=n(s),l=!1}finally{l?t1(i):n1(i)}return EC(i,r),$C(o,i)}else if(!t||typeof t!="object"){if(o=n(t),o===void 0&&(o=t),o===wT&&(o=void 0),this.autoFreeze_&&ax(o,!0),r){const i=[],s=[];ka("Patches").generateReplacementPatches_(t,o,i,s),r(i,s)}return o}else ho(1,t)},this.produceWithPatches=(t,n)=>{if(typeof t=="function")return(s,...l)=>this.produceWithPatches(s,u=>t(u,...l));let r,o;return[this.produce(t,n,(s,l)=>{r=s,o=l}),r,o]},typeof(e==null?void 0:e.autoFreeze)=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof(e==null?void 0:e.useStrictShallowCopy)=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){$a(e)||ho(8),tc(e)&&(e=Oz(e));const t=CC(this),n=o1(e,void 0);return n[wr].isManual_=!0,n1(t),n}finishDraft(e,t){const n=e&&e[wr];(!n||!n.isManual_)&&ho(9);const{scope_:r}=n;return EC(r,t),$C(void 0,r)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let n;for(n=t.length-1;n>=0;n--){const o=t[n];if(o.path.length===0&&o.op==="replace"){e=o.value;break}}n>-1&&(t=t.slice(n+1));const r=ka("Patches").applyPatches_;return tc(e)?r(e,t):this.produce(e,o=>r(o,t))}};function o1(e,t){const n=Nm(e)?ka("MapSet").proxyMap_(e,t):Dm(e)?ka("MapSet").proxySet_(e,t):Tz(e,t);return(t?t.scope_:_T()).drafts_.push(n),n}function Oz(e){return tc(e)||ho(10,e),ET(e)}function ET(e){if(!$a(e)||Im(e))return e;const t=e[wr];let n;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=e1(e,t.scope_.immer_.useStrictShallowCopy_)}else n=e1(e,!0);return Qu(n,(r,o)=>{bT(n,r,ET(o))}),t&&(t.finalized_=!1),n}var xr=new Az,Mz=xr.produce;xr.produceWithPatches.bind(xr);xr.setAutoFreeze.bind(xr);xr.setUseStrictShallowCopy.bind(xr);xr.applyPatches.bind(xr);xr.createDraft.bind(xr);xr.finishDraft.bind(xr);const Nz=e=>(t,n,r)=>(r.setState=(o,i,...s)=>{const l=typeof o=="function"?Mz(o):o;return t(l,i,...s)},e(r.setState,n,r)),Dz=Nz;var CT={exports:{}},$T={},kT={exports:{}},RT={};/** + * @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 nc=f;function Iz(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var Lz=typeof Object.is=="function"?Object.is:Iz,Fz=nc.useState,jz=nc.useEffect,zz=nc.useLayoutEffect,Bz=nc.useDebugValue;function Uz(e,t){var n=t(),r=Fz({inst:{value:n,getSnapshot:t}}),o=r[0].inst,i=r[1];return zz(function(){o.value=n,o.getSnapshot=t,g0(o)&&i({inst:o})},[e,n,t]),jz(function(){return g0(o)&&i({inst:o}),e(function(){g0(o)&&i({inst:o})})},[e]),Bz(n),n}function g0(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!Lz(e,n)}catch{return!0}}function Vz(e,t){return t()}var Wz=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?Vz:Uz;RT.useSyncExternalStore=nc.useSyncExternalStore!==void 0?nc.useSyncExternalStore:Wz;kT.exports=RT;var Hz=kT.exports;/** + * @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 Lm=f,Kz=Hz;function Yz(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var Gz=typeof Object.is=="function"?Object.is:Yz,Xz=Kz.useSyncExternalStore,Zz=Lm.useRef,qz=Lm.useEffect,Qz=Lm.useMemo,Jz=Lm.useDebugValue;$T.useSyncExternalStoreWithSelector=function(e,t,n,r,o){var i=Zz(null);if(i.current===null){var s={hasValue:!1,value:null};i.current=s}else s=i.current;i=Qz(function(){function u(y){if(!d){if(d=!0,h=y,y=r(y),o!==void 0&&s.hasValue){var x=s.value;if(o(x,y))return m=x}return m=y}if(x=m,Gz(h,y))return x;var _=r(y);return o!==void 0&&o(x,_)?x:(h=y,m=_)}var d=!1,h,m,g=n===void 0?null:n;return[function(){return u(t())},g===null?void 0:function(){return u(g())}]},[t,n,r,o]);var l=Xz(e,i[0],i[1]);return qz(function(){s.hasValue=!0,s.value=l},[l]),Jz(l),l};CT.exports=$T;var eB=CT.exports;const tB=lm(eB);var nB={VITE_BACKEND:"http://127.0.0.1:8080",BASE_URL:"/",MODE:"production",DEV:!1,PROD:!0,SSR:!1};const RC=e=>{let t;const n=new Set,r=(u,d)=>{const h=typeof u=="function"?u(t):u;if(!Object.is(h,t)){const m=t;t=d??typeof h!="object"?h:Object.assign({},t,h),n.forEach(g=>g(t,m))}},o=()=>t,l={setState:r,getState:o,subscribe:u=>(n.add(u),()=>n.delete(u)),destroy:()=>{(nB?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),n.clear()}};return t=e(r,o,l),l},rB=e=>e?RC(e):RC,{useDebugValue:oB}=Fe,{useSyncExternalStoreWithSelector:iB}=tB;function sB(e,t=e.getState,n){const r=iB(e.subscribe,e.getState,e.getServerState||e.getState,t,n);return oB(r),r}const TC=(e,t)=>{const n=rB(e),r=(o,i=t)=>sB(n,o,i);return Object.assign(r,n),r},aB=(e,t)=>e?TC(e,t):TC,lB=1,cB=1e6;let v0=0;function uB(){return v0=(v0+1)%Number.MAX_VALUE,v0.toString()}const y0=new Map,PC=e=>{if(y0.has(e))return;const t=setTimeout(()=>{y0.delete(e),Tu({type:"REMOVE_TOAST",toastId:e})},cB);y0.set(e,t)},dB=(e,t)=>{switch(t.type){case"ADD_TOAST":return{...e,toasts:[t.toast,...e.toasts].slice(0,lB)};case"UPDATE_TOAST":return{...e,toasts:e.toasts.map(n=>n.id===t.toast.id?{...n,...t.toast}:n)};case"DISMISS_TOAST":{const{toastId:n}=t;return n?PC(n):e.toasts.forEach(r=>{PC(r.id)}),{...e,toasts:e.toasts.map(r=>r.id===n||n===void 0?{...r,open:!1}:r)}}case"REMOVE_TOAST":return t.toastId===void 0?{...e,toasts:[]}:{...e,toasts:e.toasts.filter(n=>n.id!==t.toastId)}}},Bp=[];let Up={toasts:[]};function Tu(e){Up=dB(Up,e),Bp.forEach(t=>{t(Up)})}function rl({...e}){const t=uB(),n=o=>Tu({type:"UPDATE_TOAST",toast:{...o,id:t}}),r=()=>Tu({type:"DISMISS_TOAST",toastId:t});return Tu({type:"ADD_TOAST",toast:{...e,id:t,open:!0,onOpenChange:o=>{o||r()}}}),{id:t,dismiss:r,update:n}}function Td(){const[e,t]=f.useState(Up);return f.useEffect(()=>(Bp.push(t),()=>{const n=Bp.indexOf(t);n>-1&&Bp.splice(n,1)}),[e]),{...e,toast:rl,dismiss:n=>Tu({type:"DISMISS_TOAST",toastId:n})}}const Zs={file:null,paintByExampleFile:null,customMask:null,imageHeight:0,imageWidth:0,isInpainting:!1,isPluginRunning:!1,isAdjustingMask:!1,disableShortCuts:!1,windowSize:{height:600,width:800},editorState:{baseBrushSize:sF,brushSizeScale:1,renders:[],extraMasks:[],prevExtraMasks:[],temporaryMasks:[],lineGroups:[],lastLineGroup:[],curLineGroup:[],redoRenders:[],redoCurLines:[],redoLineGroups:[]},interactiveSegState:{isInteractiveSeg:!1,tmpInteractiveSegMask:null,clicks:[]},cropperState:{x:0,y:0,width:512,height:512},extenderState:{x:0,y:0,width:512,height:512},isCropperExtenderResizing:!1,fileManagerState:{sortBy:xs.CTIME,sortOrder:$u.DESCENDING,layout:"masonry",searchText:"",inputDirectory:"",outputDirectory:""},serverConfig:{plugins:[],enableFileManager:!1,enableAutoSaving:!1,enableControlnet:!1,controlnetMethod:"lllyasviel/control_v11p_sd15_canny",disableModelSwitch:!1,isDesktop:!1,samplers:["DPM++ 2M"]},settings:{model:{name:"lama",path:"lama",model_type:"inpaint",support_controlnet:!1,support_strength:!1,support_outpainting:!1,controlnets:[],support_freeu:!1,support_lcm_lora:!1,is_single_file_diffusers:!1,need_prompt:!1},enableControlnet:!1,showCropper:!1,showExtender:!1,extenderDirection:In.xy,enableDownloadMask:!1,enableManualInpainting:!1,enableUploadMask:!1,enableAutoExtractPrompt:!0,ldmSteps:30,ldmSampler:Zw.ddim,zitsWireframe:!0,cv2Radius:5,cv2Flag:qw.INPAINT_NS,prompt:"",negativePrompt:cF,seed:42,seedFixed:!1,sdMaskBlur:35,sdStrength:1,sdSteps:50,sdGuidanceScale:7.5,sdSampler:"DPM++ 2M",sdMatchHistograms:!1,sdScale:1,p2pImageGuidanceScale:1.5,controlnetConditioningScale:.4,controlnetMethod:"lllyasviel/control_v11p_sd15_canny",enableLCMLora:!1,enableFreeu:!1,freeuConfig:{s1:.9,s2:.2,b1:1.2,b2:1.4},powerpaintTask:kl.text_guided,adjustMaskKernelSize:12}},bt=aB()(bz(Dz((e,t)=>({...Zs,showPrevMask:async()=>{if(t().settings.showExtender)return;const{lastLineGroup:n,curLineGroup:r,prevExtraMasks:o,extraMasks:i}=t().editorState;if(r.length!==0||i.length!==0)return;const{imageWidth:s,imageHeight:l}=t(),u=Lp(s,l,[n],o,Ky);try{const d=await aC(u);e(h=>{h.editorState.temporaryMasks.push(d)})}catch(d){console.error(d);return}},hidePrevMask:()=>{e(n=>{n.editorState.temporaryMasks=[]})},getCurrentTargetFile:async()=>{const n=t().file,r=t().editorState.renders;let o=n;if(r.length>0){const i=r[r.length-1];o=await ku(i.currentSrc,n.name,n.type)}return o},runInpainting:async()=>{const{isInpainting:n,file:r,paintByExampleFile:o,imageWidth:i,imageHeight:s,settings:l,cropperState:u,extenderState:d}=t();if(n||r===null||t().settings.model.support_outpainting&&l.showExtender&&d.height===s&&d.width===i)return;const{lastLineGroup:h,curLineGroup:m,lineGroups:g,renders:y,prevExtraMasks:x,extraMasks:_}=t().editorState,C=m.length===0&&_.length===0&&!l.showExtender;let S=[],b=[];if(C===!0?(b=h,S=x):(b=m,S=_),b.length===0&&S===null&&!l.showExtender){rl({variant:"destructive",description:"Please draw mask on picture"});return}const E=[...g,b];e(M=>{M.isInpainting=!0});let k=r;if(C===!0){if(y.length>1){const M=y[y.length-2];k=await ku(M.currentSrc,r.name,r.type)}}else if(y.length>0){const M=y[y.length-1];k=await ku(M.currentSrc,r.name,r.type)}const P=Lp(i,s,[b],S);if(C){const M=await aC(P);e(A=>{A.editorState.temporaryMasks=[M]})}try{const M=await Ij(k,l,u,d,sC(P.toDataURL()),o),{blob:A,seed:O}=M;O&&t().setSeed(parseInt(O,10));const F=new Image;await Ip(F,A);const V=[...y,F];t().setImageSize(F.width,F.height),t().updateEditorState({renders:V,lineGroups:E,lastLineGroup:b,curLineGroup:[],extraMasks:[],prevExtraMasks:S})}catch(M){rl({variant:"destructive",description:M.message?M.message:M.toString()})}t().resetRedoState(),e(M=>{M.isInpainting=!1,M.editorState.temporaryMasks=[]})},runRenderablePlugin:async(n,r,o={upscale:1})=>{const{renders:i,lineGroups:s}=t().editorState;e(l=>{l.isPluginRunning=!0});try{const l=new Date,u=await t().getCurrentTargetFile(),d=await gT(n,r,u,o.upscale),{blob:h}=d;if(n){const y=new Image;await Ip(y,h),e(x=>{x.editorState.extraMasks.push(y)})}else{const y=new Image;await Ip(y,h),t().setImageSize(y.width,y.height);const x=[...i,y],_=[...s,[]];t().updateEditorState({renders:x,lineGroups:_})}const g=new Date().getTime()-l.getTime();rl({description:`Run ${r} successfully in ${g/1e3}s`})}catch(l){rl({variant:"destructive",description:l.message?l.message:l.toString()})}e(l=>{l.isPluginRunning=!1})},updateEditorState:n=>{e(r=>{r.editorState={...r.editorState,...n}})},cleanCurLineGroup:()=>{t().updateEditorState({curLineGroup:[]})},handleCanvasMouseDown:n=>{let r=[];const o=t();o.runMannually()&&(r=[...o.editorState.curLineGroup]),r.push({size:o.getBrushSize(),pts:[n]}),e(i=>{i.editorState.curLineGroup=r})},handleCanvasMouseMove:n=>{e(r=>{const o=r.editorState.curLineGroup;o.length&&o[o.length-1].pts.push(n)})},runMannually:()=>{const n=t();return n.settings.enableManualInpainting||n.settings.model.model_type!==is},getIsProcessing:()=>t().isInpainting||t().isPluginRunning||t().isAdjustingMask,isSD:()=>t().settings.model.model_type!==is,undoDisabled:()=>{const n=t().editorState;if(n.renders.length>0)return!1;if(t().runMannually()){if(n.curLineGroup.length===0)return!0}else if(n.renders.length===0)return!0;return!1},undo:()=>{t().runMannually()&&t().editorState.curLineGroup.length!==0?e(n=>{const r=n.editorState;if(r.curLineGroup.length===0)return;r.lastLineGroup=[];const o=r.curLineGroup.pop();r.redoCurLines.push(o)}):e(n=>{const r=n.editorState;if(r.renders.length===0||r.lineGroups.length===0)return;const o=r.lineGroups.pop();r.redoLineGroups.push(o),r.redoCurLines=[],r.curLineGroup=[];const i=r.renders.pop();r.redoRenders.push(i)})},redoDisabled:()=>{const n=t().editorState;if(n.redoRenders.length>0)return!1;if(t().runMannually()){if(n.redoCurLines.length===0)return!0}else if(n.redoRenders.length===0)return!0;return!1},redo:()=>{t().runMannually()&&t().editorState.redoCurLines.length!==0?e(n=>{const r=n.editorState;if(r.redoCurLines.length===0)return;const o=r.redoCurLines.pop();r.curLineGroup.push(o)}):e(n=>{const r=n.editorState;if(r.redoRenders.length===0||r.redoLineGroups.length===0)return;const o=r.redoLineGroups.pop();r.lineGroups.push(o),r.curLineGroup=[];const i=r.redoRenders.pop();r.renders.push(i)})},resetRedoState:()=>{e(n=>{n.editorState.redoCurLines=[],n.editorState.redoLineGroups=[],n.editorState.redoRenders=[]})},updateAppState:n=>{e(()=>n)},getBrushSize:()=>t().editorState.baseBrushSize*t().editorState.brushSizeScale,showPromptInput:()=>{const n=t().settings.model;return n.model_type!==is&&n.name!==YR},setServerConfig:n=>{e(r=>{r.serverConfig=n,r.settings.enableControlnet=n.enableControlnet,r.settings.controlnetMethod=n.controlnetMethod})},updateSettings:n=>{e(r=>{r.settings={...r.settings,...n}})},setModel:n=>{e(r=>{r.settings.model=n,n.support_controlnet&&!n.controlnets.includes(r.settings.controlnetMethod)&&(r.settings.controlnetMethod=n.controlnets[0])})},updateFileManagerState:n=>{e(r=>{r.fileManagerState={...r.fileManagerState,...n}})},updateInteractiveSegState:n=>{e(r=>({...r,interactiveSegState:{...r.interactiveSegState,...n}}))},resetInteractiveSegState:()=>{t().updateInteractiveSegState(Zs.interactiveSegState)},handleInteractiveSegAccept:()=>{e(n=>{n.interactiveSegState.tmpInteractiveSegMask&&n.editorState.extraMasks.push(n.interactiveSegState.tmpInteractiveSegMask),n.interactiveSegState={...Zs.interactiveSegState}})},setIsInpainting:n=>e(r=>{r.isInpainting=n}),setFile:async n=>{if(t().settings.enableAutoExtractPrompt)try{const r=await Wj(n);r.prompt&&e(o=>{o.settings.prompt=r.prompt}),r.negative_prompt&&e(o=>{o.settings.negativePrompt=r.negative_prompt})}catch(r){rl({variant:"destructive",description:r.message?r.message:r.toString()})}e(r=>{r.file=n,r.interactiveSegState=Zs.interactiveSegState,r.editorState=Zs.editorState,r.cropperState=Zs.cropperState})},setCustomFile:n=>e(r=>{r.customMask=n}),setBaseBrushSize:n=>e(r=>{r.editorState.baseBrushSize=n}),setImageSize:(n,r)=>{e(o=>{o.imageWidth=n,o.imageHeight=r,o.editorState.brushSizeScale=Math.max(Math.min(n,r),512)/512}),t().resetExtender(n,r)},setCropperX:n=>e(r=>{r.cropperState.x=n}),setCropperY:n=>e(r=>{r.cropperState.y=n}),setCropperWidth:n=>e(r=>{r.cropperState.width=n}),setCropperHeight:n=>e(r=>{r.cropperState.height=n}),setExtenderX:n=>e(r=>{r.extenderState.x=n}),setExtenderY:n=>e(r=>{r.extenderState.y=n}),setExtenderWidth:n=>e(r=>{r.extenderState.width=n}),setExtenderHeight:n=>e(r=>{r.extenderState.height=n}),setIsCropperExtenderResizing:n=>e(r=>{r.isCropperExtenderResizing=n}),updateExtenderDirection:n=>{console.log(`updateExtenderDirection: ${JSON.stringify(t().extenderState)}`),e(r=>{r.settings.extenderDirection=n,r.extenderState.x=0,r.extenderState.y=0,r.extenderState.width=r.imageWidth,r.extenderState.height=r.imageHeight}),t().updateExtenderByBuiltIn(n,1.5)},updateExtenderByBuiltIn:(n,r)=>{const o={...Zs.extenderState};let{x:i,y:s,width:l,height:u}=o;const{imageWidth:d,imageHeight:h}=t();switch(l=d,u=h,n){case In.x:i=-Math.ceil(d*(r-1)/2),l=Math.ceil(d*r);break;case In.y:s=-Math.ceil(h*(r-1)/2),u=Math.ceil(h*r);break;case In.xy:i=-Math.ceil(d*(r-1)/2),s=-Math.ceil(h*(r-1)/2),l=Math.ceil(d*r),u=Math.ceil(h*r);break}e(m=>{m.extenderState.x=i,m.extenderState.y=s,m.extenderState.width=l,m.extenderState.height=u})},resetExtender:(n,r)=>{e(o=>{o.extenderState.x=0,o.extenderState.y=0,o.extenderState.width=n,o.extenderState.height=r})},setSeed:n=>e(r=>{r.settings.seed=n}),adjustMask:async n=>{const{imageWidth:r,imageHeight:o}=t(),{curLineGroup:i,extraMasks:s}=t().editorState,{adjustMaskKernelSize:l}=t().settings;if(i.length===0&&s.length===0)return;e(g=>{g.isAdjustingMask=!0});const u=Lp(r,o,[i],s,Ky),d=sC(u.toDataURL()),h=await Hj(d,n,l),m=await dF(h);e(g=>{g.editorState.extraMasks=[m],g.editorState.curLineGroup=[]}),e(g=>{g.isAdjustingMask=!1})},clearMask:()=>{e(n=>{n.editorState.extraMasks=[],n.editorState.curLineGroup=[]})}})),{name:"ZUSTAND_STATE",version:1,partialize:e=>Object.fromEntries(Object.entries(e).filter(([t])=>["fileManagerState","settings"].includes(t)))}),_z),Pd=f.forwardRef(({className:e,type:t,...n},r)=>{const o=bt(l=>l.updateAppState),i=()=>{o({disableShortCuts:!0})},s=()=>{o({disableShortCuts:!1})};return v.jsx("input",{type:t,className:Ce("flex h-8 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",e),ref:r,autoComplete:"off",tabIndex:-1,onFocus:i,onBlur:s,...n})});Pd.displayName="Input";const Gn=f.forwardRef(({numberValue:e,allowFloat:t,onNumberValueChange:n,...r},o)=>{const[i,s]=f.useState(e.toString());f.useEffect(()=>{i!==e.toString()+"."&&s(e.toString())},[e]);const l=u=>{let h=u.target.value;if(t){if(h=h.replace(/[^0-9.]/g,"").replace(/(\..*?)\..*/g,"$1"),h.length===0){n(0);return}n(parseFloat(h))}else{if(h=h.replace(/\D/g,""),h.length===0){n(0);return}n(parseInt(h,10))}s(h)};return v.jsx(Pd,{ref:o,value:i,onInput:l,...r})});function ue(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 fB(e,t){const n=f.createContext(t);function r(i){const{children:s,...l}=i,u=f.useMemo(()=>l,Object.values(l));return f.createElement(n.Provider,{value:u},s)}function o(i){const s=f.useContext(n);if(s)return s;if(t!==void 0)return t;throw new Error(`\`${i}\` must be used within \`${e}\``)}return r.displayName=e+"Provider",[r,o]}function An(e,t=[]){let n=[];function r(i,s){const l=f.createContext(s),u=n.length;n=[...n,s];function d(m){const{scope:g,children:y,...x}=m,_=(g==null?void 0:g[e][u])||l,C=f.useMemo(()=>x,Object.values(x));return f.createElement(_.Provider,{value:C},y)}function h(m,g){const y=(g==null?void 0:g[e][u])||l,x=f.useContext(y);if(x)return x;if(s!==void 0)return s;throw new Error(`\`${m}\` must be used within \`${i}\``)}return d.displayName=i+"Provider",[d,h]}const o=()=>{const i=n.map(s=>f.createContext(s));return function(l){const u=(l==null?void 0:l[e])||i;return f.useMemo(()=>({[`__scope${e}`]:{...l,[e]:u}}),[l,u])}};return o.scopeName=e,[r,pB(o,...t)]}function pB(...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(i){const s=r.reduce((l,{useScope:u,scopeName:d})=>{const m=u(i)[`__scope${d}`];return{...l,...m}},{});return f.useMemo(()=>({[`__scope${t.scopeName}`]:s}),[s])}};return n.scopeName=t.scopeName,n}const hB=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","span","svg","ul"],Pe=hB.reduce((e,t)=>{const n=f.forwardRef((r,o)=>{const{asChild:i,...s}=r,l=i?Wo:t;return f.useEffect(()=>{window[Symbol.for("radix-ui")]=!0},[]),f.createElement(l,Y({},s,{ref:o}))});return n.displayName=`Primitive.${t}`,{...e,[t]:n}},{});function cx(e,t){e&&Os.flushSync(()=>e.dispatchEvent(t))}function Ft(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)},[])}function mB(e,t=globalThis==null?void 0:globalThis.document){const n=Ft(e);f.useEffect(()=>{const r=o=>{o.key==="Escape"&&n(o)};return t.addEventListener("keydown",r),()=>t.removeEventListener("keydown",r)},[n,t])}const i1="dismissableLayer.update",gB="dismissableLayer.pointerDownOutside",vB="dismissableLayer.focusOutside";let AC;const TT=f.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),yc=f.forwardRef((e,t)=>{var n;const{disableOutsidePointerEvents:r=!1,onEscapeKeyDown:o,onPointerDownOutside:i,onFocusOutside:s,onInteractOutside:l,onDismiss:u,...d}=e,h=f.useContext(TT),[m,g]=f.useState(null),y=(n=m==null?void 0:m.ownerDocument)!==null&&n!==void 0?n:globalThis==null?void 0:globalThis.document,[,x]=f.useState({}),_=Be(t,O=>g(O)),C=Array.from(h.layers),[S]=[...h.layersWithOutsidePointerEventsDisabled].slice(-1),b=C.indexOf(S),E=m?C.indexOf(m):-1,k=h.layersWithOutsidePointerEventsDisabled.size>0,P=E>=b,M=wB(O=>{const F=O.target,V=[...h.branches].some(J=>J.contains(F));!P||V||(i==null||i(O),l==null||l(O),O.defaultPrevented||u==null||u())},y),A=xB(O=>{const F=O.target;[...h.branches].some(J=>J.contains(F))||(s==null||s(O),l==null||l(O),O.defaultPrevented||u==null||u())},y);return mB(O=>{E===h.layers.size-1&&(o==null||o(O),!O.defaultPrevented&&u&&(O.preventDefault(),u()))},y),f.useEffect(()=>{if(m)return r&&(h.layersWithOutsidePointerEventsDisabled.size===0&&(AC=y.body.style.pointerEvents,y.body.style.pointerEvents="none"),h.layersWithOutsidePointerEventsDisabled.add(m)),h.layers.add(m),OC(),()=>{r&&h.layersWithOutsidePointerEventsDisabled.size===1&&(y.body.style.pointerEvents=AC)}},[m,y,r,h]),f.useEffect(()=>()=>{m&&(h.layers.delete(m),h.layersWithOutsidePointerEventsDisabled.delete(m),OC())},[m,h]),f.useEffect(()=>{const O=()=>x({});return document.addEventListener(i1,O),()=>document.removeEventListener(i1,O)},[]),f.createElement(Pe.div,Y({},d,{ref:_,style:{pointerEvents:k?P?"auto":"none":void 0,...e.style},onFocusCapture:ue(e.onFocusCapture,A.onFocusCapture),onBlurCapture:ue(e.onBlurCapture,A.onBlurCapture),onPointerDownCapture:ue(e.onPointerDownCapture,M.onPointerDownCapture)}))}),yB=f.forwardRef((e,t)=>{const n=f.useContext(TT),r=f.useRef(null),o=Be(t,r);return f.useEffect(()=>{const i=r.current;if(i)return n.branches.add(i),()=>{n.branches.delete(i)}},[n.branches]),f.createElement(Pe.div,Y({},e,{ref:o}))});function wB(e,t=globalThis==null?void 0:globalThis.document){const n=Ft(e),r=f.useRef(!1),o=f.useRef(()=>{});return f.useEffect(()=>{const i=l=>{if(l.target&&!r.current){let h=function(){PT(gB,n,d,{discrete:!0})};var u=h;const d={originalEvent:l};l.pointerType==="touch"?(t.removeEventListener("click",o.current),o.current=h,t.addEventListener("click",o.current,{once:!0})):h()}else t.removeEventListener("click",o.current);r.current=!1},s=window.setTimeout(()=>{t.addEventListener("pointerdown",i)},0);return()=>{window.clearTimeout(s),t.removeEventListener("pointerdown",i),t.removeEventListener("click",o.current)}},[t,n]),{onPointerDownCapture:()=>r.current=!0}}function xB(e,t=globalThis==null?void 0:globalThis.document){const n=Ft(e),r=f.useRef(!1);return f.useEffect(()=>{const o=i=>{i.target&&!r.current&&PT(vB,n,{originalEvent:i},{discrete:!1})};return t.addEventListener("focusin",o),()=>t.removeEventListener("focusin",o)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function OC(){const e=new CustomEvent(i1);document.dispatchEvent(e)}function PT(e,t,n,{discrete:r}){const o=n.originalEvent.target,i=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&o.addEventListener(e,t,{once:!0}),r?cx(o,i):o.dispatchEvent(i)}const bB=yc,_B=yB,Pn=globalThis!=null&&globalThis.document?f.useLayoutEffect:()=>{},SB=jD.useId||(()=>{});let EB=0;function nr(e){const[t,n]=f.useState(SB());return Pn(()=>{e||n(r=>r??String(EB++))},[e]),e||(t?`radix-${t}`:"")}const CB=["top","right","bottom","left"],Cs=Math.min,pr=Math.max,Mh=Math.round,ip=Math.floor,$s=e=>({x:e,y:e}),$B={left:"right",right:"left",bottom:"top",top:"bottom"},kB={start:"end",end:"start"};function s1(e,t,n){return pr(e,Cs(t,n))}function yi(e,t){return typeof e=="function"?e(t):e}function wi(e){return e.split("-")[0]}function wc(e){return e.split("-")[1]}function ux(e){return e==="x"?"y":"x"}function dx(e){return e==="y"?"height":"width"}function xc(e){return["top","bottom"].includes(wi(e))?"y":"x"}function fx(e){return ux(xc(e))}function RB(e,t,n){n===void 0&&(n=!1);const r=wc(e),o=fx(e),i=dx(o);let s=o==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[i]>t.floating[i]&&(s=Nh(s)),[s,Nh(s)]}function TB(e){const t=Nh(e);return[a1(e),t,a1(t)]}function a1(e){return e.replace(/start|end/g,t=>kB[t])}function PB(e,t,n){const r=["left","right"],o=["right","left"],i=["top","bottom"],s=["bottom","top"];switch(e){case"top":case"bottom":return n?t?o:r:t?r:o;case"left":case"right":return t?i:s;default:return[]}}function AB(e,t,n,r){const o=wc(e);let i=PB(wi(e),n==="start",r);return o&&(i=i.map(s=>s+"-"+o),t&&(i=i.concat(i.map(a1)))),i}function Nh(e){return e.replace(/left|right|bottom|top/g,t=>$B[t])}function OB(e){return{top:0,right:0,bottom:0,left:0,...e}}function AT(e){return typeof e!="number"?OB(e):{top:e,right:e,bottom:e,left:e}}function Dh(e){return{...e,top:e.y,left:e.x,right:e.x+e.width,bottom:e.y+e.height}}function MC(e,t,n){let{reference:r,floating:o}=e;const i=xc(t),s=fx(t),l=dx(s),u=wi(t),d=i==="y",h=r.x+r.width/2-o.width/2,m=r.y+r.height/2-o.height/2,g=r[l]/2-o[l]/2;let y;switch(u){case"top":y={x:h,y:r.y-o.height};break;case"bottom":y={x:h,y:r.y+r.height};break;case"right":y={x:r.x+r.width,y:m};break;case"left":y={x:r.x-o.width,y:m};break;default:y={x:r.x,y:r.y}}switch(wc(t)){case"start":y[s]-=g*(n&&d?-1:1);break;case"end":y[s]+=g*(n&&d?-1:1);break}return y}const MB=async(e,t,n)=>{const{placement:r="bottom",strategy:o="absolute",middleware:i=[],platform:s}=n,l=i.filter(Boolean),u=await(s.isRTL==null?void 0:s.isRTL(t));let d=await s.getElementRects({reference:e,floating:t,strategy:o}),{x:h,y:m}=MC(d,r,u),g=r,y={},x=0;for(let _=0;_({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:o,rects:i,platform:s,elements:l,middlewareData:u}=t,{element:d,padding:h=0}=yi(e,t)||{};if(d==null)return{};const m=AT(h),g={x:n,y:r},y=fx(o),x=dx(y),_=await s.getDimensions(d),C=y==="y",S=C?"top":"left",b=C?"bottom":"right",E=C?"clientHeight":"clientWidth",k=i.reference[x]+i.reference[y]-g[y]-i.floating[x],P=g[y]-i.reference[y],M=await(s.getOffsetParent==null?void 0:s.getOffsetParent(d));let A=M?M[E]:0;(!A||!await(s.isElement==null?void 0:s.isElement(M)))&&(A=l.floating[E]||i.floating[x]);const O=k/2-P/2,F=A/2-_[x]/2-1,V=Cs(m[S],F),J=Cs(m[b],F),G=V,ae=A-_[x]-J,U=A/2-_[x]/2+O,te=s1(G,U,ae),L=!u.arrow&&wc(o)!=null&&U!=te&&i.reference[x]/2-(UG<=0)){var F,V;const G=(((F=i.flip)==null?void 0:F.index)||0)+1,ae=P[G];if(ae)return{data:{index:G,overflows:O},reset:{placement:ae}};let U=(V=O.filter(te=>te.overflows[0]<=0).sort((te,L)=>te.overflows[1]-L.overflows[1])[0])==null?void 0:V.placement;if(!U)switch(y){case"bestFit":{var J;const te=(J=O.map(L=>[L.placement,L.overflows.filter(ie=>ie>0).reduce((ie,K)=>ie+K,0)]).sort((L,ie)=>L[1]-ie[1])[0])==null?void 0:J[0];te&&(U=te);break}case"initialPlacement":U=l;break}if(o!==U)return{reset:{placement:U}}}return{}}}};function DC(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function IC(e){return CB.some(t=>e[t]>=0)}const DB=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n}=t,{strategy:r="referenceHidden",...o}=yi(e,t);switch(r){case"referenceHidden":{const i=await td(t,{...o,elementContext:"reference"}),s=DC(i,n.reference);return{data:{referenceHiddenOffsets:s,referenceHidden:IC(s)}}}case"escaped":{const i=await td(t,{...o,altBoundary:!0}),s=DC(i,n.floating);return{data:{escapedOffsets:s,escaped:IC(s)}}}default:return{}}}}};async function IB(e,t){const{placement:n,platform:r,elements:o}=e,i=await(r.isRTL==null?void 0:r.isRTL(o.floating)),s=wi(n),l=wc(n),u=xc(n)==="y",d=["left","top"].includes(s)?-1:1,h=i&&u?-1:1,m=yi(t,e);let{mainAxis:g,crossAxis:y,alignmentAxis:x}=typeof m=="number"?{mainAxis:m,crossAxis:0,alignmentAxis:null}:{mainAxis:0,crossAxis:0,alignmentAxis:null,...m};return l&&typeof x=="number"&&(y=l==="end"?x*-1:x),u?{x:y*h,y:g*d}:{x:g*d,y:y*h}}const LB=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){const{x:n,y:r}=t,o=await IB(t,e);return{x:n+o.x,y:r+o.y,data:o}}}},FB=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:o}=t,{mainAxis:i=!0,crossAxis:s=!1,limiter:l={fn:C=>{let{x:S,y:b}=C;return{x:S,y:b}}},...u}=yi(e,t),d={x:n,y:r},h=await td(t,u),m=xc(wi(o)),g=ux(m);let y=d[g],x=d[m];if(i){const C=g==="y"?"top":"left",S=g==="y"?"bottom":"right",b=y+h[C],E=y-h[S];y=s1(b,y,E)}if(s){const C=m==="y"?"top":"left",S=m==="y"?"bottom":"right",b=x+h[C],E=x-h[S];x=s1(b,x,E)}const _=l.fn({...t,[g]:y,[m]:x});return{..._,data:{x:_.x-n,y:_.y-r}}}}},jB=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:r,placement:o,rects:i,middlewareData:s}=t,{offset:l=0,mainAxis:u=!0,crossAxis:d=!0}=yi(e,t),h={x:n,y:r},m=xc(o),g=ux(m);let y=h[g],x=h[m];const _=yi(l,t),C=typeof _=="number"?{mainAxis:_,crossAxis:0}:{mainAxis:0,crossAxis:0,..._};if(u){const E=g==="y"?"height":"width",k=i.reference[g]-i.floating[E]+C.mainAxis,P=i.reference[g]+i.reference[E]-C.mainAxis;yP&&(y=P)}if(d){var S,b;const E=g==="y"?"width":"height",k=["top","left"].includes(wi(o)),P=i.reference[m]-i.floating[E]+(k&&((S=s.offset)==null?void 0:S[m])||0)+(k?0:C.crossAxis),M=i.reference[m]+i.reference[E]+(k?0:((b=s.offset)==null?void 0:b[m])||0)-(k?C.crossAxis:0);xM&&(x=M)}return{[g]:y,[m]:x}}}},zB=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){const{placement:n,rects:r,platform:o,elements:i}=t,{apply:s=()=>{},...l}=yi(e,t),u=await td(t,l),d=wi(n),h=wc(n),m=xc(n)==="y",{width:g,height:y}=r.floating;let x,_;d==="top"||d==="bottom"?(x=d,_=h===(await(o.isRTL==null?void 0:o.isRTL(i.floating))?"start":"end")?"left":"right"):(_=d,x=h==="end"?"top":"bottom");const C=y-u[x],S=g-u[_],b=!t.middlewareData.shift;let E=C,k=S;if(m){const M=g-u.left-u.right;k=h||b?Cs(S,M):M}else{const M=y-u.top-u.bottom;E=h||b?Cs(C,M):M}if(b&&!h){const M=pr(u.left,0),A=pr(u.right,0),O=pr(u.top,0),F=pr(u.bottom,0);m?k=g-2*(M!==0||A!==0?M+A:pr(u.left,u.right)):E=y-2*(O!==0||F!==0?O+F:pr(u.top,u.bottom))}await s({...t,availableWidth:k,availableHeight:E});const P=await o.getDimensions(i.floating);return g!==P.width||y!==P.height?{reset:{rects:!0}}:{}}}};function ks(e){return OT(e)?(e.nodeName||"").toLowerCase():"#document"}function vr(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Ci(e){var t;return(t=(OT(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function OT(e){return e instanceof Node||e instanceof vr(e).Node}function xi(e){return e instanceof Element||e instanceof vr(e).Element}function Ho(e){return e instanceof HTMLElement||e instanceof vr(e).HTMLElement}function LC(e){return typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof vr(e).ShadowRoot}function Ad(e){const{overflow:t,overflowX:n,overflowY:r,display:o}=Xr(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&!["inline","contents"].includes(o)}function BB(e){return["table","td","th"].includes(ks(e))}function px(e){const t=hx(),n=Xr(e);return n.transform!=="none"||n.perspective!=="none"||(n.containerType?n.containerType!=="normal":!1)||!t&&(n.backdropFilter?n.backdropFilter!=="none":!1)||!t&&(n.filter?n.filter!=="none":!1)||["transform","perspective","filter"].some(r=>(n.willChange||"").includes(r))||["paint","layout","strict","content"].some(r=>(n.contain||"").includes(r))}function UB(e){let t=rc(e);for(;Ho(t)&&!Fm(t);){if(px(t))return t;t=rc(t)}return null}function hx(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}function Fm(e){return["html","body","#document"].includes(ks(e))}function Xr(e){return vr(e).getComputedStyle(e)}function jm(e){return xi(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.pageXOffset,scrollTop:e.pageYOffset}}function rc(e){if(ks(e)==="html")return e;const t=e.assignedSlot||e.parentNode||LC(e)&&e.host||Ci(e);return LC(t)?t.host:t}function MT(e){const t=rc(e);return Fm(t)?e.ownerDocument?e.ownerDocument.body:e.body:Ho(t)&&Ad(t)?t:MT(t)}function nd(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const o=MT(e),i=o===((r=e.ownerDocument)==null?void 0:r.body),s=vr(o);return i?t.concat(s,s.visualViewport||[],Ad(o)?o:[],s.frameElement&&n?nd(s.frameElement):[]):t.concat(o,nd(o,[],n))}function NT(e){const t=Xr(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const o=Ho(e),i=o?e.offsetWidth:n,s=o?e.offsetHeight:r,l=Mh(n)!==i||Mh(r)!==s;return l&&(n=i,r=s),{width:n,height:r,$:l}}function mx(e){return xi(e)?e:e.contextElement}function Rl(e){const t=mx(e);if(!Ho(t))return $s(1);const n=t.getBoundingClientRect(),{width:r,height:o,$:i}=NT(t);let s=(i?Mh(n.width):n.width)/r,l=(i?Mh(n.height):n.height)/o;return(!s||!Number.isFinite(s))&&(s=1),(!l||!Number.isFinite(l))&&(l=1),{x:s,y:l}}const VB=$s(0);function DT(e){const t=vr(e);return!hx()||!t.visualViewport?VB:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function WB(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==vr(e)?!1:t}function Ra(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const o=e.getBoundingClientRect(),i=mx(e);let s=$s(1);t&&(r?xi(r)&&(s=Rl(r)):s=Rl(e));const l=WB(i,n,r)?DT(i):$s(0);let u=(o.left+l.x)/s.x,d=(o.top+l.y)/s.y,h=o.width/s.x,m=o.height/s.y;if(i){const g=vr(i),y=r&&xi(r)?vr(r):r;let x=g.frameElement;for(;x&&r&&y!==g;){const _=Rl(x),C=x.getBoundingClientRect(),S=Xr(x),b=C.left+(x.clientLeft+parseFloat(S.paddingLeft))*_.x,E=C.top+(x.clientTop+parseFloat(S.paddingTop))*_.y;u*=_.x,d*=_.y,h*=_.x,m*=_.y,u+=b,d+=E,x=vr(x).frameElement}}return Dh({width:h,height:m,x:u,y:d})}function HB(e){let{rect:t,offsetParent:n,strategy:r}=e;const o=Ho(n),i=Ci(n);if(n===i)return t;let s={scrollLeft:0,scrollTop:0},l=$s(1);const u=$s(0);if((o||!o&&r!=="fixed")&&((ks(n)!=="body"||Ad(i))&&(s=jm(n)),Ho(n))){const d=Ra(n);l=Rl(n),u.x=d.x+n.clientLeft,u.y=d.y+n.clientTop}return{width:t.width*l.x,height:t.height*l.y,x:t.x*l.x-s.scrollLeft*l.x+u.x,y:t.y*l.y-s.scrollTop*l.y+u.y}}function KB(e){return Array.from(e.getClientRects())}function IT(e){return Ra(Ci(e)).left+jm(e).scrollLeft}function YB(e){const t=Ci(e),n=jm(e),r=e.ownerDocument.body,o=pr(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),i=pr(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let s=-n.scrollLeft+IT(e);const l=-n.scrollTop;return Xr(r).direction==="rtl"&&(s+=pr(t.clientWidth,r.clientWidth)-o),{width:o,height:i,x:s,y:l}}function GB(e,t){const n=vr(e),r=Ci(e),o=n.visualViewport;let i=r.clientWidth,s=r.clientHeight,l=0,u=0;if(o){i=o.width,s=o.height;const d=hx();(!d||d&&t==="fixed")&&(l=o.offsetLeft,u=o.offsetTop)}return{width:i,height:s,x:l,y:u}}function XB(e,t){const n=Ra(e,!0,t==="fixed"),r=n.top+e.clientTop,o=n.left+e.clientLeft,i=Ho(e)?Rl(e):$s(1),s=e.clientWidth*i.x,l=e.clientHeight*i.y,u=o*i.x,d=r*i.y;return{width:s,height:l,x:u,y:d}}function FC(e,t,n){let r;if(t==="viewport")r=GB(e,n);else if(t==="document")r=YB(Ci(e));else if(xi(t))r=XB(t,n);else{const o=DT(e);r={...t,x:t.x-o.x,y:t.y-o.y}}return Dh(r)}function LT(e,t){const n=rc(e);return n===t||!xi(n)||Fm(n)?!1:Xr(n).position==="fixed"||LT(n,t)}function ZB(e,t){const n=t.get(e);if(n)return n;let r=nd(e,[],!1).filter(l=>xi(l)&&ks(l)!=="body"),o=null;const i=Xr(e).position==="fixed";let s=i?rc(e):e;for(;xi(s)&&!Fm(s);){const l=Xr(s),u=px(s);!u&&l.position==="fixed"&&(o=null),(i?!u&&!o:!u&&l.position==="static"&&!!o&&["absolute","fixed"].includes(o.position)||Ad(s)&&!u&<(e,s))?r=r.filter(h=>h!==s):o=l,s=rc(s)}return t.set(e,r),r}function qB(e){let{element:t,boundary:n,rootBoundary:r,strategy:o}=e;const s=[...n==="clippingAncestors"?ZB(t,this._c):[].concat(n),r],l=s[0],u=s.reduce((d,h)=>{const m=FC(t,h,o);return d.top=pr(m.top,d.top),d.right=Cs(m.right,d.right),d.bottom=Cs(m.bottom,d.bottom),d.left=pr(m.left,d.left),d},FC(t,l,o));return{width:u.right-u.left,height:u.bottom-u.top,x:u.left,y:u.top}}function QB(e){return NT(e)}function JB(e,t,n){const r=Ho(t),o=Ci(t),i=n==="fixed",s=Ra(e,!0,i,t);let l={scrollLeft:0,scrollTop:0};const u=$s(0);if(r||!r&&!i)if((ks(t)!=="body"||Ad(o))&&(l=jm(t)),r){const d=Ra(t,!0,i,t);u.x=d.x+t.clientLeft,u.y=d.y+t.clientTop}else o&&(u.x=IT(o));return{x:s.left+l.scrollLeft-u.x,y:s.top+l.scrollTop-u.y,width:s.width,height:s.height}}function jC(e,t){return!Ho(e)||Xr(e).position==="fixed"?null:t?t(e):e.offsetParent}function FT(e,t){const n=vr(e);if(!Ho(e))return n;let r=jC(e,t);for(;r&&BB(r)&&Xr(r).position==="static";)r=jC(r,t);return r&&(ks(r)==="html"||ks(r)==="body"&&Xr(r).position==="static"&&!px(r))?n:r||UB(e)||n}const eU=async function(e){let{reference:t,floating:n,strategy:r}=e;const o=this.getOffsetParent||FT,i=this.getDimensions;return{reference:JB(t,await o(n),r),floating:{x:0,y:0,...await i(n)}}};function tU(e){return Xr(e).direction==="rtl"}const nU={convertOffsetParentRelativeRectToViewportRelativeRect:HB,getDocumentElement:Ci,getClippingRect:qB,getOffsetParent:FT,getElementRects:eU,getClientRects:KB,getDimensions:QB,getScale:Rl,isElement:xi,isRTL:tU};function rU(e,t){let n=null,r;const o=Ci(e);function i(){clearTimeout(r),n&&n.disconnect(),n=null}function s(l,u){l===void 0&&(l=!1),u===void 0&&(u=1),i();const{left:d,top:h,width:m,height:g}=e.getBoundingClientRect();if(l||t(),!m||!g)return;const y=ip(h),x=ip(o.clientWidth-(d+m)),_=ip(o.clientHeight-(h+g)),C=ip(d),b={rootMargin:-y+"px "+-x+"px "+-_+"px "+-C+"px",threshold:pr(0,Cs(1,u))||1};let E=!0;function k(P){const M=P[0].intersectionRatio;if(M!==u){if(!E)return s();M?s(!1,M):r=setTimeout(()=>{s(!1,1e-7)},100)}E=!1}try{n=new IntersectionObserver(k,{...b,root:o.ownerDocument})}catch{n=new IntersectionObserver(k,b)}n.observe(e)}return s(!0),i}function oU(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:o=!0,ancestorResize:i=!0,elementResize:s=typeof ResizeObserver=="function",layoutShift:l=typeof IntersectionObserver=="function",animationFrame:u=!1}=r,d=mx(e),h=o||i?[...d?nd(d):[],...nd(t)]:[];h.forEach(S=>{o&&S.addEventListener("scroll",n,{passive:!0}),i&&S.addEventListener("resize",n)});const m=d&&l?rU(d,n):null;let g=-1,y=null;s&&(y=new ResizeObserver(S=>{let[b]=S;b&&b.target===d&&y&&(y.unobserve(t),cancelAnimationFrame(g),g=requestAnimationFrame(()=>{y&&y.observe(t)})),n()}),d&&!u&&y.observe(d),y.observe(t));let x,_=u?Ra(e):null;u&&C();function C(){const S=Ra(e);_&&(S.x!==_.x||S.y!==_.y||S.width!==_.width||S.height!==_.height)&&n(),_=S,x=requestAnimationFrame(C)}return n(),()=>{h.forEach(S=>{o&&S.removeEventListener("scroll",n),i&&S.removeEventListener("resize",n)}),m&&m(),y&&y.disconnect(),y=null,u&&cancelAnimationFrame(x)}}const iU=(e,t,n)=>{const r=new Map,o={platform:nU,...n},i={...o.platform,_c:r};return MB(e,t,{...o,platform:i})},sU=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:o}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?NC({element:r.current,padding:o}).fn(n):{}:r?NC({element:r,padding:o}).fn(n):{}}}};var Vp=typeof document<"u"?f.useLayoutEffect:f.useEffect;function Ih(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(!Ih(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(!{}.hasOwnProperty.call(t,o[r]))return!1;for(r=n;r--!==0;){const i=o[r];if(!(i==="_owner"&&e.$$typeof)&&!Ih(e[i],t[i]))return!1}return!0}return e!==e&&t!==t}function jT(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function zC(e,t){const n=jT(e);return Math.round(t*n)/n}function BC(e){const t=f.useRef(e);return Vp(()=>{t.current=e}),t}function aU(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:o,elements:{reference:i,floating:s}={},transform:l=!0,whileElementsMounted:u,open:d}=e,[h,m]=f.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[g,y]=f.useState(r);Ih(g,r)||y(r);const[x,_]=f.useState(null),[C,S]=f.useState(null),b=f.useCallback(L=>{L!=M.current&&(M.current=L,_(L))},[_]),E=f.useCallback(L=>{L!==A.current&&(A.current=L,S(L))},[S]),k=i||x,P=s||C,M=f.useRef(null),A=f.useRef(null),O=f.useRef(h),F=BC(u),V=BC(o),J=f.useCallback(()=>{if(!M.current||!A.current)return;const L={placement:t,strategy:n,middleware:g};V.current&&(L.platform=V.current),iU(M.current,A.current,L).then(ie=>{const K={...ie,isPositioned:!0};G.current&&!Ih(O.current,K)&&(O.current=K,Os.flushSync(()=>{m(K)}))})},[g,t,n,V]);Vp(()=>{d===!1&&O.current.isPositioned&&(O.current.isPositioned=!1,m(L=>({...L,isPositioned:!1})))},[d]);const G=f.useRef(!1);Vp(()=>(G.current=!0,()=>{G.current=!1}),[]),Vp(()=>{if(k&&(M.current=k),P&&(A.current=P),k&&P){if(F.current)return F.current(k,P,J);J()}},[k,P,J,F]);const ae=f.useMemo(()=>({reference:M,floating:A,setReference:b,setFloating:E}),[b,E]),U=f.useMemo(()=>({reference:k,floating:P}),[k,P]),te=f.useMemo(()=>{const L={position:n,left:0,top:0};if(!U.floating)return L;const ie=zC(U.floating,h.x),K=zC(U.floating,h.y);return l?{...L,transform:"translate("+ie+"px, "+K+"px)",...jT(U.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:ie,top:K}},[n,l,U.floating,h.x,h.y]);return f.useMemo(()=>({...h,update:J,refs:ae,elements:U,floatingStyles:te}),[h,J,ae,U,te])}function gx(e){const[t,n]=f.useState(void 0);return Pn(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(o=>{if(!Array.isArray(o)||!o.length)return;const i=o[0];let s,l;if("borderBoxSize"in i){const u=i.borderBoxSize,d=Array.isArray(u)?u[0]:u;s=d.inlineSize,l=d.blockSize}else s=e.offsetWidth,l=e.offsetHeight;n({width:s,height:l})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}const zT="Popper",[BT,Ns]=An(zT),[lU,UT]=BT(zT),cU=e=>{const{__scopePopper:t,children:n}=e,[r,o]=f.useState(null);return f.createElement(lU,{scope:t,anchor:r,onAnchorChange:o},n)},uU="PopperAnchor",dU=f.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...o}=e,i=UT(uU,n),s=f.useRef(null),l=Be(t,s);return f.useEffect(()=>{i.onAnchorChange((r==null?void 0:r.current)||s.current)}),r?null:f.createElement(Pe.div,Y({},o,{ref:l}))}),VT="PopperContent",[fU,hte]=BT(VT),pU=f.forwardRef((e,t)=>{var n,r,o,i,s,l,u,d;const{__scopePopper:h,side:m="bottom",sideOffset:g=0,align:y="center",alignOffset:x=0,arrowPadding:_=0,avoidCollisions:C=!0,collisionBoundary:S=[],collisionPadding:b=0,sticky:E="partial",hideWhenDetached:k=!1,updatePositionStrategy:P="optimized",onPlaced:M,...A}=e,O=UT(VT,h),[F,V]=f.useState(null),J=Be(t,Yt=>V(Yt)),[G,ae]=f.useState(null),U=gx(G),te=(n=U==null?void 0:U.width)!==null&&n!==void 0?n:0,L=(r=U==null?void 0:U.height)!==null&&r!==void 0?r:0,ie=m+(y!=="center"?"-"+y:""),K=typeof b=="number"?b:{top:0,right:0,bottom:0,left:0,...b},Q=Array.isArray(S)?S:[S],W=Q.length>0,le={padding:K,boundary:Q.filter(hU),altBoundary:W},{refs:ge,floatingStyles:Ve,placement:Ue,isPositioned:We,middlewareData:Me}=aU({strategy:"fixed",placement:ie,whileElementsMounted:(...Yt)=>oU(...Yt,{animationFrame:P==="always"}),elements:{reference:O.anchor},middleware:[LB({mainAxis:g+L,alignmentAxis:x}),C&&FB({mainAxis:!0,crossAxis:!1,limiter:E==="partial"?jB():void 0,...le}),C&&NB({...le}),zB({...le,apply:({elements:Yt,rects:Er,availableWidth:gt,availableHeight:js})=>{const{width:I,height:X}=Er.reference,Z=Yt.floating.style;Z.setProperty("--radix-popper-available-width",`${gt}px`),Z.setProperty("--radix-popper-available-height",`${js}px`),Z.setProperty("--radix-popper-anchor-width",`${I}px`),Z.setProperty("--radix-popper-anchor-height",`${X}px`)}}),G&&sU({element:G,padding:_}),mU({arrowWidth:te,arrowHeight:L}),k&&DB({strategy:"referenceHidden",...le})]}),[fe,xe]=WT(Ue),$e=Ft(M);Pn(()=>{We&&($e==null||$e())},[We,$e]);const Ae=(o=Me.arrow)===null||o===void 0?void 0:o.x,Oe=(i=Me.arrow)===null||i===void 0?void 0:i.y,je=((s=Me.arrow)===null||s===void 0?void 0:s.centerOffset)!==0,[Ot,ct]=f.useState();return Pn(()=>{F&&ct(window.getComputedStyle(F).zIndex)},[F]),f.createElement("div",{ref:ge.setFloating,"data-radix-popper-content-wrapper":"",style:{...Ve,transform:We?Ve.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:Ot,"--radix-popper-transform-origin":[(l=Me.transformOrigin)===null||l===void 0?void 0:l.x,(u=Me.transformOrigin)===null||u===void 0?void 0:u.y].join(" ")},dir:e.dir},f.createElement(fU,{scope:h,placedSide:fe,onArrowChange:ae,arrowX:Ae,arrowY:Oe,shouldHideArrow:je},f.createElement(Pe.div,Y({"data-side":fe,"data-align":xe},A,{ref:J,style:{...A.style,animation:We?void 0:"none",opacity:(d=Me.hide)!==null&&d!==void 0&&d.referenceHidden?0:void 0}}))))});function hU(e){return e!==null}const mU=e=>({name:"transformOrigin",options:e,fn(t){var n,r,o,i,s;const{placement:l,rects:u,middlewareData:d}=t,m=((n=d.arrow)===null||n===void 0?void 0:n.centerOffset)!==0,g=m?0:e.arrowWidth,y=m?0:e.arrowHeight,[x,_]=WT(l),C={start:"0%",center:"50%",end:"100%"}[_],S=((r=(o=d.arrow)===null||o===void 0?void 0:o.x)!==null&&r!==void 0?r:0)+g/2,b=((i=(s=d.arrow)===null||s===void 0?void 0:s.y)!==null&&i!==void 0?i:0)+y/2;let E="",k="";return x==="bottom"?(E=m?C:`${S}px`,k=`${-y}px`):x==="top"?(E=m?C:`${S}px`,k=`${u.floating.height+y}px`):x==="right"?(E=`${-y}px`,k=m?C:`${b}px`):x==="left"&&(E=`${u.floating.width+y}px`,k=m?C:`${b}px`),{data:{x:E,y:k}}}});function WT(e){const[t,n="center"]=e.split("-");return[t,n]}const Od=cU,zm=dU,Bm=pU,Md=f.forwardRef((e,t)=>{var n;const{container:r=globalThis==null||(n=globalThis.document)===null||n===void 0?void 0:n.body,...o}=e;return r?XI.createPortal(f.createElement(Pe.div,Y({},o,{ref:t})),r):null});function gU(e,t){return f.useReducer((n,r)=>{const o=t[n][r];return o??n},e)}const xn=e=>{const{present:t,children:n}=e,r=vU(t),o=typeof n=="function"?n({present:r.isPresent}):f.Children.only(n),i=Be(r.ref,o.ref);return typeof n=="function"||r.isPresent?f.cloneElement(o,{ref:i}):null};xn.displayName="Presence";function vU(e){const[t,n]=f.useState(),r=f.useRef({}),o=f.useRef(e),i=f.useRef("none"),s=e?"mounted":"unmounted",[l,u]=gU(s,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return f.useEffect(()=>{const d=sp(r.current);i.current=l==="mounted"?d:"none"},[l]),Pn(()=>{const d=r.current,h=o.current;if(h!==e){const g=i.current,y=sp(d);e?u("MOUNT"):y==="none"||(d==null?void 0:d.display)==="none"?u("UNMOUNT"):u(h&&g!==y?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,u]),Pn(()=>{if(t){const d=m=>{const y=sp(r.current).includes(m.animationName);m.target===t&&y&&Os.flushSync(()=>u("ANIMATION_END"))},h=m=>{m.target===t&&(i.current=sp(r.current))};return t.addEventListener("animationstart",h),t.addEventListener("animationcancel",d),t.addEventListener("animationend",d),()=>{t.removeEventListener("animationstart",h),t.removeEventListener("animationcancel",d),t.removeEventListener("animationend",d)}}else u("ANIMATION_END")},[t,u]),{isPresent:["mounted","unmountSuspended"].includes(l),ref:f.useCallback(d=>{d&&(r.current=getComputedStyle(d)),n(d)},[])}}function sp(e){return(e==null?void 0:e.animationName)||"none"}function Zr({prop:e,defaultProp:t,onChange:n=()=>{}}){const[r,o]=yU({defaultProp:t,onChange:n}),i=e!==void 0,s=i?e:r,l=Ft(n),u=f.useCallback(d=>{if(i){const m=typeof d=="function"?d(e):d;m!==e&&l(m)}else o(d)},[i,e,o,l]);return[s,u]}function yU({defaultProp:e,onChange:t}){const n=f.useState(e),[r]=n,o=f.useRef(r),i=Ft(t);return f.useEffect(()=>{o.current!==r&&(i(r),o.current=r)},[r,o,i]),n}const Um=f.forwardRef((e,t)=>f.createElement(Pe.span,Y({},e,{ref:t,style:{position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal",...e.style}}))),wU=Um,[Vm,mte]=An("Tooltip",[Ns]),vx=Ns(),xU="TooltipProvider",bU=700,l1="tooltip.open",[_U,yx]=Vm(xU),SU=e=>{const{__scopeTooltip:t,delayDuration:n=bU,skipDelayDuration:r=300,disableHoverableContent:o=!1,children:i}=e,[s,l]=f.useState(!0),u=f.useRef(!1),d=f.useRef(0);return f.useEffect(()=>{const h=d.current;return()=>window.clearTimeout(h)},[]),f.createElement(_U,{scope:t,isOpenDelayed:s,delayDuration:n,onOpen:f.useCallback(()=>{window.clearTimeout(d.current),l(!1)},[]),onClose:f.useCallback(()=>{window.clearTimeout(d.current),d.current=window.setTimeout(()=>l(!0),r)},[r]),isPointerInTransitRef:u,onPointerInTransitChange:f.useCallback(h=>{u.current=h},[]),disableHoverableContent:o},i)},wx="Tooltip",[EU,Wm]=Vm(wx),CU=e=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:o=!1,onOpenChange:i,disableHoverableContent:s,delayDuration:l}=e,u=yx(wx,e.__scopeTooltip),d=vx(t),[h,m]=f.useState(null),g=nr(),y=f.useRef(0),x=s??u.disableHoverableContent,_=l??u.delayDuration,C=f.useRef(!1),[S=!1,b]=Zr({prop:r,defaultProp:o,onChange:A=>{A?(u.onOpen(),document.dispatchEvent(new CustomEvent(l1))):u.onClose(),i==null||i(A)}}),E=f.useMemo(()=>S?C.current?"delayed-open":"instant-open":"closed",[S]),k=f.useCallback(()=>{window.clearTimeout(y.current),C.current=!1,b(!0)},[b]),P=f.useCallback(()=>{window.clearTimeout(y.current),b(!1)},[b]),M=f.useCallback(()=>{window.clearTimeout(y.current),y.current=window.setTimeout(()=>{C.current=!0,b(!0)},_)},[_,b]);return f.useEffect(()=>()=>window.clearTimeout(y.current),[]),f.createElement(Od,d,f.createElement(EU,{scope:t,contentId:g,open:S,stateAttribute:E,trigger:h,onTriggerChange:m,onTriggerEnter:f.useCallback(()=>{u.isOpenDelayed?M():k()},[u.isOpenDelayed,M,k]),onTriggerLeave:f.useCallback(()=>{x?P():window.clearTimeout(y.current)},[P,x]),onOpen:k,onClose:P,disableHoverableContent:x},n))},UC="TooltipTrigger",$U=f.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,o=Wm(UC,n),i=yx(UC,n),s=vx(n),l=f.useRef(null),u=Be(t,l,o.onTriggerChange),d=f.useRef(!1),h=f.useRef(!1),m=f.useCallback(()=>d.current=!1,[]);return f.useEffect(()=>()=>document.removeEventListener("pointerup",m),[m]),f.createElement(zm,Y({asChild:!0},s),f.createElement(Pe.button,Y({"aria-describedby":o.open?o.contentId:void 0,"data-state":o.stateAttribute},r,{ref:u,onPointerMove:ue(e.onPointerMove,g=>{g.pointerType!=="touch"&&!h.current&&!i.isPointerInTransitRef.current&&(o.onTriggerEnter(),h.current=!0)}),onPointerLeave:ue(e.onPointerLeave,()=>{o.onTriggerLeave(),h.current=!1}),onPointerDown:ue(e.onPointerDown,()=>{d.current=!0,document.addEventListener("pointerup",m,{once:!0})}),onFocus:ue(e.onFocus,()=>{d.current||o.onOpen()}),onBlur:ue(e.onBlur,o.onClose),onClick:ue(e.onClick,o.onClose)})))}),kU="TooltipPortal",[gte,RU]=Vm(kU,{forceMount:void 0}),rd="TooltipContent",TU=f.forwardRef((e,t)=>{const n=RU(rd,e.__scopeTooltip),{forceMount:r=n.forceMount,side:o="top",...i}=e,s=Wm(rd,e.__scopeTooltip);return f.createElement(xn,{present:r||s.open},s.disableHoverableContent?f.createElement(HT,Y({side:o},i,{ref:t})):f.createElement(PU,Y({side:o},i,{ref:t})))}),PU=f.forwardRef((e,t)=>{const n=Wm(rd,e.__scopeTooltip),r=yx(rd,e.__scopeTooltip),o=f.useRef(null),i=Be(t,o),[s,l]=f.useState(null),{trigger:u,onClose:d}=n,h=o.current,{onPointerInTransitChange:m}=r,g=f.useCallback(()=>{l(null),m(!1)},[m]),y=f.useCallback((x,_)=>{const C=x.currentTarget,S={x:x.clientX,y:x.clientY},b=OU(S,C.getBoundingClientRect()),E=MU(S,b),k=NU(_.getBoundingClientRect()),P=IU([...E,...k]);l(P),m(!0)},[m]);return f.useEffect(()=>()=>g(),[g]),f.useEffect(()=>{if(u&&h){const x=C=>y(C,h),_=C=>y(C,u);return u.addEventListener("pointerleave",x),h.addEventListener("pointerleave",_),()=>{u.removeEventListener("pointerleave",x),h.removeEventListener("pointerleave",_)}}},[u,h,y,g]),f.useEffect(()=>{if(s){const x=_=>{const C=_.target,S={x:_.clientX,y:_.clientY},b=(u==null?void 0:u.contains(C))||(h==null?void 0:h.contains(C)),E=!DU(S,s);b?g():E&&(g(),d())};return document.addEventListener("pointermove",x),()=>document.removeEventListener("pointermove",x)}},[u,h,s,d,g]),f.createElement(HT,Y({},e,{ref:i}))}),[AU,vte]=Vm(wx,{isInside:!1}),HT=f.forwardRef((e,t)=>{const{__scopeTooltip:n,children:r,"aria-label":o,onEscapeKeyDown:i,onPointerDownOutside:s,...l}=e,u=Wm(rd,n),d=vx(n),{onClose:h}=u;return f.useEffect(()=>(document.addEventListener(l1,h),()=>document.removeEventListener(l1,h)),[h]),f.useEffect(()=>{if(u.trigger){const m=g=>{const y=g.target;y!=null&&y.contains(u.trigger)&&h()};return window.addEventListener("scroll",m,{capture:!0}),()=>window.removeEventListener("scroll",m,{capture:!0})}},[u.trigger,h]),f.createElement(yc,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:i,onPointerDownOutside:s,onFocusOutside:m=>m.preventDefault(),onDismiss:h},f.createElement(Bm,Y({"data-state":u.stateAttribute},d,l,{ref:t,style:{...l.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"}}),f.createElement(sx,null,r),f.createElement(AU,{scope:n,isInside:!0},f.createElement(wU,{id:u.contentId,role:"tooltip"},o||r))))});function OU(e,t){const n=Math.abs(t.top-e.y),r=Math.abs(t.bottom-e.y),o=Math.abs(t.right-e.x),i=Math.abs(t.left-e.x);switch(Math.min(n,r,o,i)){case i:return"left";case o:return"right";case n:return"top";case r:return"bottom";default:throw new Error("unreachable")}}function MU(e,t,n=5){const r=[];switch(t){case"top":r.push({x:e.x-n,y:e.y+n},{x:e.x+n,y:e.y+n});break;case"bottom":r.push({x:e.x-n,y:e.y-n},{x:e.x+n,y:e.y-n});break;case"left":r.push({x:e.x+n,y:e.y-n},{x:e.x+n,y:e.y+n});break;case"right":r.push({x:e.x-n,y:e.y-n},{x:e.x-n,y:e.y+n});break}return r}function NU(e){const{top:t,right:n,bottom:r,left:o}=e;return[{x:o,y:t},{x:n,y:t},{x:n,y:r},{x:o,y:r}]}function DU(e,t){const{x:n,y:r}=e;let o=!1;for(let i=0,s=t.length-1;ir!=h>r&&n<(d-l)*(r-u)/(h-u)+l&&(o=!o)}return o}function IU(e){const t=e.slice();return t.sort((n,r)=>n.xr.x?1:n.yr.y?1:0),LU(t)}function LU(e){if(e.length<=1)return e.slice();const t=[];for(let r=0;r=2;){const i=t[t.length-1],s=t[t.length-2];if((i.x-s.x)*(o.y-s.y)>=(i.y-s.y)*(o.x-s.x))t.pop();else break}t.push(o)}t.pop();const n=[];for(let r=e.length-1;r>=0;r--){const o=e[r];for(;n.length>=2;){const i=n[n.length-1],s=n[n.length-2];if((i.x-s.x)*(o.y-s.y)>=(i.y-s.y)*(o.x-s.x))n.pop();else break}n.push(o)}return n.pop(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}const FU=SU,jU=CU,zU=$U,KT=TU,BU=FU,YT=jU,GT=zU,xx=f.forwardRef(({className:e,sideOffset:t=4,...n},r)=>v.jsx(KT,{ref:r,sideOffset:t,className:Ce("z-50 border overflow-hidden rounded-md bg-background text-foreground px-3 py-1.5 text-xs animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...n}));xx.displayName=KT.displayName;const bx=Om("inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50",{variants:{variant:{default:"bg-primary text-primary-foreground shadow hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",outline:"border border-input bg-transparent shadow-sm hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2",sm:"h-8 rounded-md px-3 text-xs",lg:"h-10 rounded-md px-8",icon:"h-9 w-9"}},defaultVariants:{variant:"default",size:"default"}}),Rn=f.forwardRef(({className:e,variant:t,size:n,asChild:r=!1,...o},i)=>{const s=r?Wo:"button";return v.jsx(s,{className:Ce(bx({variant:t,size:n,className:e}),"outline-none cursor-default"),ref:i,tabIndex:-1,...o})});Rn.displayName="Button";const vn=f.forwardRef(({tooltip:e,children:t,...n},r)=>v.jsxs(YT,{children:[v.jsx(GT,{asChild:!0,children:v.jsx(Rn,{variant:"ghost",size:"icon",...n,ref:r,tabIndex:-1,className:"cursor-default bg-background",children:v.jsx("div",{className:"icon-button-icon-wrapper",children:t})})}),v.jsx(xx,{children:v.jsx("p",{children:e})})]})),c1=e=>{const{onFileUpload:t,children:n,...r}=e,[o]=f.useState(`file-upload-${Math.random().toString()}`),i=s=>{var u;const l=(u=s.currentTarget.files)==null?void 0:u[0];l&&t(l)};return v.jsxs(v.Fragment,{children:[v.jsx("label",{htmlFor:o,children:v.jsx(vn,{...r,asChild:!0,children:n})}),v.jsx(Pd,{style:{display:"none"},id:o,name:o,type:"file",onChange:i,accept:"image/png, image/jpeg"})]})};var UU={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const VU=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Kt=(e,t)=>{const n=f.forwardRef(({color:r="currentColor",size:o=24,strokeWidth:i=2,absoluteStrokeWidth:s,children:l,...u},d)=>f.createElement("svg",{ref:d,...UU,width:o,height:o,stroke:r,strokeWidth:s?Number(i)*24/Number(o):i,className:`lucide lucide-${VU(e)}`,...u},[...t.map(([h,m])=>f.createElement(h,m)),...(Array.isArray(l)?l:[l])||[]]));return n.displayName=`${e}`,n},WU=Kt("Blocks",[["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["path",{d:"M10 21V8a1 1 0 0 0-1-1H4a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-5a1 1 0 0 0-1-1H3",key:"1fpvtg"}]]),HU=Kt("ChevronLeft",[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]]),KU=Kt("ChevronRight",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]),YU=Kt("Coffee",[["path",{d:"M17 8h1a4 4 0 1 1 0 8h-1",key:"jx4kbh"}],["path",{d:"M3 8h14v9a4 4 0 0 1-4 4H7a4 4 0 0 1-4-4Z",key:"1bxrl0"}],["line",{x1:"6",x2:"6",y1:"2",y2:"4",key:"1cr9l3"}],["line",{x1:"10",x2:"10",y1:"2",y2:"4",key:"170wym"}],["line",{x1:"14",x2:"14",y1:"2",y2:"4",key:"1c5f70"}]]),GU=Kt("Download",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"7 10 12 15 17 10",key:"2ggqvy"}],["line",{x1:"12",x2:"12",y1:"15",y2:"3",key:"1vk2je"}]]),XU=Kt("Eraser",[["path",{d:"m7 21-4.3-4.3c-1-1-1-2.5 0-3.4l9.6-9.6c1-1 2.5-1 3.4 0l5.6 5.6c1 1 1 2.5 0 3.4L13 21",key:"182aya"}],["path",{d:"M22 21H7",key:"t4ddhn"}],["path",{d:"m5 11 9 9",key:"1mo9qw"}]]),ZU=Kt("Expand",[["path",{d:"m21 21-6-6m6 6v-4.8m0 4.8h-4.8",key:"1c15vz"}],["path",{d:"M3 16.2V21m0 0h4.8M3 21l6-6",key:"1fsnz2"}],["path",{d:"M21 7.8V3m0 0h-4.8M21 3l-6 6",key:"hawz9i"}],["path",{d:"M3 7.8V3m0 0h4.8M3 3l6 6",key:"u9ee12"}]]),qU=Kt("Eye",[["path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z",key:"rwhkz3"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]),QU=Kt("FolderClosed",[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}],["path",{d:"M2 10h20",key:"1ir3d8"}]]),XT=Kt("Fullscreen",[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}],["rect",{width:"10",height:"8",x:"7",y:"8",rx:"1",key:"vys8me"}]]),JU=Kt("Image",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]]),eV=Kt("Keyboard",[["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",ry:"2",key:"15u882"}],["path",{d:"M6 8h.001",key:"1ej0i3"}],["path",{d:"M10 8h.001",key:"1x2st2"}],["path",{d:"M14 8h.001",key:"1vkmyp"}],["path",{d:"M18 8h.001",key:"kfsenl"}],["path",{d:"M8 12h.001",key:"1sjpby"}],["path",{d:"M12 12h.001",key:"al75ts"}],["path",{d:"M16 12h.001",key:"931bgk"}],["path",{d:"M7 16h10",key:"wp8him"}]]),tV=Kt("Minus",[["path",{d:"M5 12h14",key:"1ays0h"}]]),nV=Kt("MousePointerClick",[["path",{d:"m9 9 5 12 1.8-5.2L21 14Z",key:"1b76lo"}],["path",{d:"M7.2 2.2 8 5.1",key:"1cfko1"}],["path",{d:"m5.1 8-2.9-.8",key:"1go3kf"}],["path",{d:"M14 4.1 12 6",key:"ita8i4"}],["path",{d:"m6 12-1.9 2",key:"mnht97"}]]),rV=Kt("Plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]),oV=Kt("Redo",[["path",{d:"M21 7v6h-6",key:"3ptur4"}],["path",{d:"M3 17a9 9 0 0 1 9-9 9 9 0 0 1 6 2.3l3 2.7",key:"1kgawr"}]]),iV=Kt("RotateCw",[["path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8",key:"1p45f6"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}]]),sV=Kt("Settings",[["path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z",key:"1qme2f"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]),VC=Kt("Slice",[["path",{d:"m8 14-6 6h9v-3",key:"zo3j9a"}],["path",{d:"M18.37 3.63 8 14l3 3L21.37 6.63a2.12 2.12 0 1 0-3-3Z",key:"1dzx0j"}]]),WC=Kt("Smile",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 14s1.5 2 4 2 4-2 4-2",key:"1y1vjs"}],["line",{x1:"9",x2:"9.01",y1:"9",y2:"9",key:"yxxnd0"}],["line",{x1:"15",x2:"15.01",y1:"9",y2:"9",key:"1p4y9e"}]]),aV=Kt("Undo",[["path",{d:"M3 7v6h6",key:"1v2h90"}],["path",{d:"M21 17a9 9 0 0 0-9-9 9 9 0 0 0-6 2.3L3 13",key:"1r6uu6"}]]),ZT=Kt("Upload",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"17 8 12 3 7 8",key:"t8dd8p"}],["line",{x1:"12",x2:"12",y1:"3",y2:"15",key:"widbto"}]]);function lV(e,t){const[n,r]=f.useState(e);return f.useEffect(()=>{const o=setTimeout(()=>{r(e)},t);return()=>{clearTimeout(o)}},[e,t]),n}function u1(e){const[t,n]=f.useState(()=>typeof e=="boolean"?e:!!e),r=f.useCallback(o=>n(typeof o=="boolean"?o:i=>!i),[]);return[t,r]}const w0="focusScope.autoFocusOnMount",x0="focusScope.autoFocusOnUnmount",HC={bubbles:!1,cancelable:!0},Hm=f.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:o,onUnmountAutoFocus:i,...s}=e,[l,u]=f.useState(null),d=Ft(o),h=Ft(i),m=f.useRef(null),g=Be(t,_=>u(_)),y=f.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;f.useEffect(()=>{if(r){let b=function(M){if(y.paused||!l)return;const A=M.target;l.contains(A)?m.current=A:Hi(m.current,{select:!0})},E=function(M){if(y.paused||!l)return;const A=M.relatedTarget;A!==null&&(l.contains(A)||Hi(m.current,{select:!0}))},k=function(M){if(document.activeElement===document.body)for(const O of M)O.removedNodes.length>0&&Hi(l)};var _=b,C=E,S=k;document.addEventListener("focusin",b),document.addEventListener("focusout",E);const P=new MutationObserver(k);return l&&P.observe(l,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",b),document.removeEventListener("focusout",E),P.disconnect()}}},[r,l,y.paused]),f.useEffect(()=>{if(l){YC.add(y);const _=document.activeElement;if(!l.contains(_)){const S=new CustomEvent(w0,HC);l.addEventListener(w0,d),l.dispatchEvent(S),S.defaultPrevented||(cV(hV(qT(l)),{select:!0}),document.activeElement===_&&Hi(l))}return()=>{l.removeEventListener(w0,d),setTimeout(()=>{const S=new CustomEvent(x0,HC);l.addEventListener(x0,h),l.dispatchEvent(S),S.defaultPrevented||Hi(_??document.body,{select:!0}),l.removeEventListener(x0,h),YC.remove(y)},0)}}},[l,d,h,y]);const x=f.useCallback(_=>{if(!n&&!r||y.paused)return;const C=_.key==="Tab"&&!_.altKey&&!_.ctrlKey&&!_.metaKey,S=document.activeElement;if(C&&S){const b=_.currentTarget,[E,k]=uV(b);E&&k?!_.shiftKey&&S===k?(_.preventDefault(),n&&Hi(E,{select:!0})):_.shiftKey&&S===E&&(_.preventDefault(),n&&Hi(k,{select:!0})):S===b&&_.preventDefault()}},[n,r,y.paused]);return f.createElement(Pe.div,Y({tabIndex:-1},s,{ref:g,onKeyDown:x}))});function cV(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(Hi(r,{select:t}),document.activeElement!==n)return}function uV(e){const t=qT(e),n=KC(t,e),r=KC(t.reverse(),e);return[n,r]}function qT(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const o=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||o?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function KC(e,t){for(const n of e)if(!dV(n,{upTo:t}))return n}function dV(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function fV(e){return e instanceof HTMLInputElement&&"select"in e}function Hi(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&fV(e)&&t&&e.select()}}const YC=pV();function pV(){let e=[];return{add(t){const n=e[0];t!==n&&(n==null||n.pause()),e=GC(e,t),e.unshift(t)},remove(t){var n;e=GC(e,t),(n=e[0])===null||n===void 0||n.resume()}}}function GC(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function hV(e){return e.filter(t=>t.tagName!=="A")}let b0=0;function Km(){f.useEffect(()=>{var e,t;const n=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",(e=n[0])!==null&&e!==void 0?e:XC()),document.body.insertAdjacentElement("beforeend",(t=n[1])!==null&&t!==void 0?t:XC()),b0++,()=>{b0===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(r=>r.remove()),b0--}},[])}function XC(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.cssText="outline: none; opacity: 0; position: fixed; pointer-events: none",e}var Mo=function(){return Mo=Object.assign||function(t){for(var n,r=1,o=arguments.length;r"u")return AV;var t=OV(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])}},NV=tP(),DV=function(e,t,n,r){var o=e.left,i=e.top,s=e.right,l=e.gap;return n===void 0&&(n="margin"),` + .`.concat(gV,` { + overflow: hidden `).concat(r,`; + padding-right: `).concat(l,"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(i,`px; + padding-right: `).concat(s,`px; + margin-left:0; + margin-top:0; + margin-right: `).concat(l,"px ").concat(r,`; + `),n==="padding"&&"padding-right: ".concat(l,"px ").concat(r,";")].filter(Boolean).join(""),` + } + + .`).concat(Wp,` { + right: `).concat(l,"px ").concat(r,`; + } + + .`).concat(Hp,` { + margin-right: `).concat(l,"px ").concat(r,`; + } + + .`).concat(Wp," .").concat(Wp,` { + right: 0 `).concat(r,`; + } + + .`).concat(Hp," .").concat(Hp,` { + margin-right: 0 `).concat(r,`; + } + + body { + `).concat(vV,": ").concat(l,`px; + } +`)},IV=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,o=r===void 0?"margin":r,i=f.useMemo(function(){return MV(o)},[o]);return f.createElement(NV,{styles:DV(i,!t,o,n?"":"!important")})},d1=!1;if(typeof window<"u")try{var ap=Object.defineProperty({},"passive",{get:function(){return d1=!0,!0}});window.addEventListener("test",ap,ap),window.removeEventListener("test",ap,ap)}catch{d1=!1}var qa=d1?{passive:!1}:!1,LV=function(e){return e.tagName==="TEXTAREA"},nP=function(e,t){var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!LV(e)&&n[t]==="visible")},FV=function(e){return nP(e,"overflowY")},jV=function(e){return nP(e,"overflowX")},qC=function(e,t){var n=t;do{typeof ShadowRoot<"u"&&n instanceof ShadowRoot&&(n=n.host);var r=rP(e,n);if(r){var o=oP(e,n),i=o[1],s=o[2];if(i>s)return!0}n=n.parentNode}while(n&&n!==document.body);return!1},zV=function(e){var t=e.scrollTop,n=e.scrollHeight,r=e.clientHeight;return[t,n,r]},BV=function(e){var t=e.scrollLeft,n=e.scrollWidth,r=e.clientWidth;return[t,n,r]},rP=function(e,t){return e==="v"?FV(t):jV(t)},oP=function(e,t){return e==="v"?zV(t):BV(t)},UV=function(e,t){return e==="h"&&t==="rtl"?-1:1},VV=function(e,t,n,r,o){var i=UV(e,window.getComputedStyle(t).direction),s=i*r,l=n.target,u=t.contains(l),d=!1,h=s>0,m=0,g=0;do{var y=oP(e,l),x=y[0],_=y[1],C=y[2],S=_-C-i*x;(x||S)&&rP(e,l)&&(m+=S,g+=x),l=l.parentNode}while(!u&&l!==document.body||u&&(t.contains(l)||t===l));return(h&&(o&&m===0||!o&&s>m)||!h&&(o&&g===0||!o&&-s>g))&&(d=!0),d},lp=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},QC=function(e){return[e.deltaX,e.deltaY]},JC=function(e){return e&&"current"in e?e.current:e},WV=function(e,t){return e[0]===t[0]&&e[1]===t[1]},HV=function(e){return` + .block-interactivity-`.concat(e,` {pointer-events: none;} + .allow-interactivity-`).concat(e,` {pointer-events: all;} +`)},KV=0,Qa=[];function YV(e){var t=f.useRef([]),n=f.useRef([0,0]),r=f.useRef(),o=f.useState(KV++)[0],i=f.useState(function(){return tP()})[0],s=f.useRef(e);f.useEffect(function(){s.current=e},[e]),f.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(o));var _=mV([e.lockRef.current],(e.shards||[]).map(JC),!0).filter(Boolean);return _.forEach(function(C){return C.classList.add("allow-interactivity-".concat(o))}),function(){document.body.classList.remove("block-interactivity-".concat(o)),_.forEach(function(C){return C.classList.remove("allow-interactivity-".concat(o))})}}},[e.inert,e.lockRef.current,e.shards]);var l=f.useCallback(function(_,C){if("touches"in _&&_.touches.length===2)return!s.current.allowPinchZoom;var S=lp(_),b=n.current,E="deltaX"in _?_.deltaX:b[0]-S[0],k="deltaY"in _?_.deltaY:b[1]-S[1],P,M=_.target,A=Math.abs(E)>Math.abs(k)?"h":"v";if("touches"in _&&A==="h"&&M.type==="range")return!1;var O=qC(A,M);if(!O)return!0;if(O?P=A:(P=A==="v"?"h":"v",O=qC(A,M)),!O)return!1;if(!r.current&&"changedTouches"in _&&(E||k)&&(r.current=P),!P)return!0;var F=r.current||P;return VV(F,C,_,F==="h"?E:k,!0)},[]),u=f.useCallback(function(_){var C=_;if(!(!Qa.length||Qa[Qa.length-1]!==i)){var S="deltaY"in C?QC(C):lp(C),b=t.current.filter(function(P){return P.name===C.type&&P.target===C.target&&WV(P.delta,S)})[0];if(b&&b.should){C.cancelable&&C.preventDefault();return}if(!b){var E=(s.current.shards||[]).map(JC).filter(Boolean).filter(function(P){return P.contains(C.target)}),k=E.length>0?l(C,E[0]):!s.current.noIsolation;k&&C.cancelable&&C.preventDefault()}}},[]),d=f.useCallback(function(_,C,S,b){var E={name:_,delta:C,target:S,should:b};t.current.push(E),setTimeout(function(){t.current=t.current.filter(function(k){return k!==E})},1)},[]),h=f.useCallback(function(_){n.current=lp(_),r.current=void 0},[]),m=f.useCallback(function(_){d(_.type,QC(_),_.target,l(_,e.lockRef.current))},[]),g=f.useCallback(function(_){d(_.type,lp(_),_.target,l(_,e.lockRef.current))},[]);f.useEffect(function(){return Qa.push(i),e.setCallbacks({onScrollCapture:m,onWheelCapture:m,onTouchMoveCapture:g}),document.addEventListener("wheel",u,qa),document.addEventListener("touchmove",u,qa),document.addEventListener("touchstart",h,qa),function(){Qa=Qa.filter(function(_){return _!==i}),document.removeEventListener("wheel",u,qa),document.removeEventListener("touchmove",u,qa),document.removeEventListener("touchstart",h,qa)}},[]);var y=e.removeScrollBar,x=e.inert;return f.createElement(f.Fragment,null,x?f.createElement(i,{styles:HV(o)}):null,y?f.createElement(IV,{gapMode:"margin"}):null)}const GV=EV(eP,YV);var iP=f.forwardRef(function(e,t){return f.createElement(Ym,Mo({},e,{ref:t,sideCar:GV}))});iP.classNames=Ym.classNames;const Gm=iP;var XV=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},Ja=new WeakMap,cp=new WeakMap,up={},E0=0,sP=function(e){return e&&(e.host||sP(e.parentNode))},ZV=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=sP(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})},qV=function(e,t,n,r){var o=ZV(t,Array.isArray(e)?e:[e]);up[n]||(up[n]=new WeakMap);var i=up[n],s=[],l=new Set,u=new Set(o),d=function(m){!m||l.has(m)||(l.add(m),d(m.parentNode))};o.forEach(d);var h=function(m){!m||u.has(m)||Array.prototype.forEach.call(m.children,function(g){if(l.has(g))h(g);else{var y=g.getAttribute(r),x=y!==null&&y!=="false",_=(Ja.get(g)||0)+1,C=(i.get(g)||0)+1;Ja.set(g,_),i.set(g,C),s.push(g),_===1&&x&&cp.set(g,!0),C===1&&g.setAttribute(n,"true"),x||g.setAttribute(r,"true")}})};return h(t),l.clear(),E0++,function(){s.forEach(function(m){var g=Ja.get(m)-1,y=i.get(m)-1;Ja.set(m,g),i.set(m,y),g||(cp.has(m)||m.removeAttribute(r),cp.delete(m)),y||m.removeAttribute(n)}),E0--,E0||(Ja=new WeakMap,Ja=new WeakMap,cp=new WeakMap,up={})}},Xm=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),o=t||XV(e);return o?(r.push.apply(r,Array.from(o.querySelectorAll("[aria-live]"))),qV(r,o,n,"aria-hidden")):function(){return null}};const aP="Dialog",[lP,cP]=An(aP),[QV,bo]=lP(aP),JV=e=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:o,onOpenChange:i,modal:s=!0}=e,l=f.useRef(null),u=f.useRef(null),[d=!1,h]=Zr({prop:r,defaultProp:o,onChange:i});return f.createElement(QV,{scope:t,triggerRef:l,contentRef:u,contentId:nr(),titleId:nr(),descriptionId:nr(),open:d,onOpenChange:h,onOpenToggle:f.useCallback(()=>h(m=>!m),[h]),modal:s},n)},eW="DialogTrigger",uP=f.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=bo(eW,n),i=Be(t,o.triggerRef);return f.createElement(Pe.button,Y({type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":_x(o.open)},r,{ref:i,onClick:ue(e.onClick,o.onOpenToggle)}))}),dP="DialogPortal",[tW,fP]=lP(dP,{forceMount:void 0}),nW=e=>{const{__scopeDialog:t,forceMount:n,children:r,container:o}=e,i=bo(dP,t);return f.createElement(tW,{scope:t,forceMount:n},f.Children.map(r,s=>f.createElement(xn,{present:n||i.open},f.createElement(Md,{asChild:!0,container:o},s))))},f1="DialogOverlay",rW=f.forwardRef((e,t)=>{const n=fP(f1,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,i=bo(f1,e.__scopeDialog);return i.modal?f.createElement(xn,{present:r||i.open},f.createElement(oW,Y({},o,{ref:t}))):null}),oW=f.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=bo(f1,n);return f.createElement(Gm,{as:Wo,allowPinchZoom:!0,shards:[o.contentRef]},f.createElement(Pe.div,Y({"data-state":_x(o.open)},r,{ref:t,style:{pointerEvents:"auto",...r.style}})))}),oc="DialogContent",iW=f.forwardRef((e,t)=>{const n=fP(oc,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,i=bo(oc,e.__scopeDialog);return f.createElement(xn,{present:r||i.open},i.modal?f.createElement(sW,Y({},o,{ref:t})):f.createElement(aW,Y({},o,{ref:t})))}),sW=f.forwardRef((e,t)=>{const n=bo(oc,e.__scopeDialog),r=f.useRef(null),o=Be(t,n.contentRef,r);return f.useEffect(()=>{const i=r.current;if(i)return Xm(i)},[]),f.createElement(pP,Y({},e,{ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:ue(e.onCloseAutoFocus,i=>{var s;i.preventDefault(),(s=n.triggerRef.current)===null||s===void 0||s.focus()}),onPointerDownOutside:ue(e.onPointerDownOutside,i=>{const s=i.detail.originalEvent,l=s.button===0&&s.ctrlKey===!0;(s.button===2||l)&&i.preventDefault()}),onFocusOutside:ue(e.onFocusOutside,i=>i.preventDefault())}))}),aW=f.forwardRef((e,t)=>{const n=bo(oc,e.__scopeDialog),r=f.useRef(!1),o=f.useRef(!1);return f.createElement(pP,Y({},e,{ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var s;if((s=e.onCloseAutoFocus)===null||s===void 0||s.call(e,i),!i.defaultPrevented){var l;r.current||(l=n.triggerRef.current)===null||l===void 0||l.focus(),i.preventDefault()}r.current=!1,o.current=!1},onInteractOutside:i=>{var s,l;(s=e.onInteractOutside)===null||s===void 0||s.call(e,i),i.defaultPrevented||(r.current=!0,i.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const u=i.target;((l=n.triggerRef.current)===null||l===void 0?void 0:l.contains(u))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&o.current&&i.preventDefault()}}))}),pP=f.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:i,...s}=e,l=bo(oc,n),u=f.useRef(null),d=Be(t,u);return Km(),f.createElement(f.Fragment,null,f.createElement(Hm,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:i},f.createElement(yc,Y({role:"dialog",id:l.contentId,"aria-describedby":l.descriptionId,"aria-labelledby":l.titleId,"data-state":_x(l.open)},s,{ref:d,onDismiss:()=>l.onOpenChange(!1)}))),!1)}),hP="DialogTitle",lW=f.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=bo(hP,n);return f.createElement(Pe.h2,Y({id:o.titleId},r,{ref:t}))}),cW="DialogDescription",mP=f.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=bo(cW,n);return f.createElement(Pe.p,Y({id:o.descriptionId},r,{ref:t}))}),uW="DialogClose",dW=f.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=bo(uW,n);return f.createElement(Pe.button,Y({type:"button"},r,{ref:t,onClick:ue(e.onClick,()=>o.onOpenChange(!1))}))});function _x(e){return e?"open":"closed"}const fW="DialogTitleWarning",[pW,yte]=fB(fW,{contentName:oc,titleName:hP,docsSlug:"dialog"}),Sx=JV,gP=uP,Ex=nW,Nd=rW,Dd=iW,Id=lW,Ld=mP,Cx=dW,Zm=Sx,$x=gP,hW=Ex,vP=f.forwardRef(({className:e,...t},n)=>v.jsx(Nd,{ref:n,className:Ce("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t}));vP.displayName=Nd.displayName;const Fd=f.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(hW,{children:[v.jsx(vP,{}),v.jsxs(Dd,{ref:r,className:Ce("fixed left-[50%] top-[50%] z-50 flex flex-col w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",e,"outline-none"),onCloseAutoFocus:o=>o.preventDefault(),...n,children:[t,v.jsxs(Cx,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[v.jsx(yT,{className:"h-4 w-4"}),v.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Fd.displayName=Dd.displayName;const yP=({className:e,...t})=>v.jsx("div",{className:Ce("flex flex-col space-y-1.5 text-center sm:text-left",e),...t});yP.displayName="DialogHeader";const jd=f.forwardRef(({className:e,...t},n)=>v.jsx(Id,{ref:n,className:Ce("text-2xl font-semibold leading-none tracking-tight",e),...t}));jd.displayName=Id.displayName;const mW=f.forwardRef(({className:e,...t},n)=>v.jsx(Ld,{ref:n,className:Ce("text-sm text-muted-foreground",e),...t}));mW.displayName=Ld.displayName;function p1(){return p1=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 SW=function(t,n,r){r===void 0&&(r=!1);var o=n.alt,i=n.meta,s=n.mod,l=n.shift,u=n.ctrl,d=n.keys,h=t.key,m=t.code,g=t.ctrlKey,y=t.metaKey,x=t.shiftKey,_=t.altKey,C=ss(m),S=h.toLowerCase();if(!r){if(o===!_&&S!=="alt"||l===!x&&S!=="shift")return!1;if(s){if(!y&&!g)return!1}else if(i===!y&&S!=="meta"&&S!=="os"||u===!g&&S!=="ctrl"&&S!=="control")return!1}return d&&d.length===1&&(d.includes(S)||d.includes(C))?!0:d?yW(d):!d},EW=f.createContext(void 0),CW=function(){return f.useContext(EW)};function SP(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&&SP(e[r],t[r])},!0):e===t}var $W=f.createContext({hotkeys:[],enabledScopes:[],toggleScope:function(){},enableScope:function(){},disableScope:function(){}}),kW=function(){return f.useContext($W)};function RW(e){var t=f.useRef(void 0);return SP(t.current,e)||(t.current=e),t.current}var e2=function(t){t.stopPropagation(),t.preventDefault(),t.stopImmediatePropagation()},TW=typeof window<"u"?f.useLayoutEffect:f.useEffect;function PW(e,t,n,r){var o=f.useRef(null),i=f.useRef(!1),s=n instanceof Array?r instanceof Array?void 0:r:n,l=kx(e)?e.join(s==null?void 0:s.splitKey):e,u=n instanceof Array?n:r instanceof Array?r:void 0,d=f.useCallback(t,u??[]),h=f.useRef(d);u?h.current=d:h.current=t;var m=RW(s),g=kW(),y=g.enabledScopes,x=CW();return TW(function(){if(!((m==null?void 0:m.enabled)===!1||!_W(y,m==null?void 0:m.scopes))){var _=function(k,P){var M;if(P===void 0&&(P=!1),!(bW(k)&&!_P(k,m==null?void 0:m.enableOnFormTags))&&!(m!=null&&m.ignoreEventWhen!=null&&m.ignoreEventWhen(k))){if(o.current!==null&&document.activeElement!==o.current&&!o.current.contains(document.activeElement)){e2(k);return}(M=k.target)!=null&&M.isContentEditable&&!(m!=null&&m.enableOnContentEditable)||C0(l,m==null?void 0:m.splitKey).forEach(function(A){var O,F=$0(A,m==null?void 0:m.combinationKey);if(SW(k,F,m==null?void 0:m.ignoreModifiers)||(O=F.keys)!=null&&O.includes("*")){if(P&&i.current)return;if(wW(k,F,m==null?void 0:m.preventDefault),!xW(k,F,m==null?void 0:m.enabled)){e2(k);return}h.current(k,F),P||(i.current=!0)}})}},C=function(k){k.key!==void 0&&(xP(ss(k.code)),((m==null?void 0:m.keydown)===void 0&&(m==null?void 0:m.keyup)!==!0||m!=null&&m.keydown)&&_(k))},S=function(k){k.key!==void 0&&(bP(ss(k.code)),i.current=!1,m!=null&&m.keyup&&_(k,!0))},b=o.current||(s==null?void 0:s.document)||document;return b.addEventListener("keyup",S),b.addEventListener("keydown",C),x&&C0(l,m==null?void 0:m.splitKey).forEach(function(E){return x.addHotkey($0(E,m==null?void 0:m.combinationKey,m==null?void 0:m.description))}),function(){b.removeEventListener("keyup",S),b.removeEventListener("keydown",C),x&&C0(l,m==null?void 0:m.splitKey).forEach(function(E){return x.removeHotkey($0(E,m==null?void 0:m.combinationKey,m==null?void 0:m.description))})}}},[l,m,y]),o}const Zn=(e,t,n)=>{const r=bt(i=>i.disableShortCuts);return PW(e,t,{enabled:!r},n)};function ur(e){const{content:t,keys:n}=e;return v.jsxs("div",{className:"flex justify-between",children:[v.jsx("div",{children:t}),v.jsx("div",{className:"flex gap-[8px]",children:n.map(r=>v.jsx("div",{className:"border px-2 py-1 rounded-lg",children:r},r))})]})}const AW=function(){return/macintosh|mac os x/i.test(navigator.userAgent)},dp=()=>AW()?"Cmd":"Ctrl";function OW(){const[e,t]=u1(!1);return Zn("h",()=>{t()}),v.jsxs(Zm,{open:e,onOpenChange:t,children:[v.jsx($x,{asChild:!0,children:v.jsx(vn,{tooltip:"Hotkeys",children:v.jsx(eV,{})})}),v.jsx(Fd,{children:v.jsxs(yP,{children:[v.jsx(jd,{children:"Hotkeys"}),v.jsxs("div",{className:"flex gap-2 flex-col pt-4",children:[v.jsx(ur,{content:"Pan",keys:["Space + Drag"]}),v.jsx(ur,{content:"Reset Zoom/Pan",keys:["Esc"]}),v.jsx(ur,{content:"Decrease Brush Size",keys:["["]}),v.jsx(ur,{content:"Increase Brush Size",keys:["]"]}),v.jsx(ur,{content:"View Original Image",keys:["Hold Tab"]}),v.jsx(ur,{content:"Undo",keys:[dp(),"Z"]}),v.jsx(ur,{content:"Redo",keys:[dp(),"Shift","Z"]}),v.jsx(ur,{content:"Copy Result",keys:[dp(),"C"]}),v.jsx(ur,{content:"Paste Image",keys:[dp(),"V"]}),v.jsx(ur,{content:"Trigger Manually Inpainting",keys:["Shift","R"]}),v.jsx(ur,{content:"Toggle Hotkeys Dialog",keys:["H"]}),v.jsx(ur,{content:"Toggle Settings Dialog",keys:["S"]}),v.jsx(ur,{content:"Toggle File Manager",keys:["F"]})]})]})})]})}function Rx(e){const[t]=f.useState(new Image),[n,r]=f.useState(!1);return f.useEffect(()=>{if(e)return t.onload=()=>{r(!0)},r(!1),t.src=URL.createObjectURL(e),()=>{t.onload=null}},[e,t]),[t,n]}const EP="Popover",[CP,wte]=An(EP,[Ns]),Tx=Ns(),[MW,bc]=CP(EP),NW=e=>{const{__scopePopover:t,children:n,open:r,defaultOpen:o,onOpenChange:i,modal:s=!1}=e,l=Tx(t),u=f.useRef(null),[d,h]=f.useState(!1),[m=!1,g]=Zr({prop:r,defaultProp:o,onChange:i});return f.createElement(Od,l,f.createElement(MW,{scope:t,contentId:nr(),triggerRef:u,open:m,onOpenChange:g,onOpenToggle:f.useCallback(()=>g(y=>!y),[g]),hasCustomAnchor:d,onCustomAnchorAdd:f.useCallback(()=>h(!0),[]),onCustomAnchorRemove:f.useCallback(()=>h(!1),[]),modal:s},n))},DW="PopoverTrigger",IW=f.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,o=bc(DW,n),i=Tx(n),s=Be(t,o.triggerRef),l=f.createElement(Pe.button,Y({type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":RP(o.open)},r,{ref:s,onClick:ue(e.onClick,o.onOpenToggle)}));return o.hasCustomAnchor?l:f.createElement(zm,Y({asChild:!0},i),l)}),$P="PopoverPortal",[LW,FW]=CP($P,{forceMount:void 0}),jW=e=>{const{__scopePopover:t,forceMount:n,children:r,container:o}=e,i=bc($P,t);return f.createElement(LW,{scope:t,forceMount:n},f.createElement(xn,{present:n||i.open},f.createElement(Md,{asChild:!0,container:o},r)))},od="PopoverContent",zW=f.forwardRef((e,t)=>{const n=FW(od,e.__scopePopover),{forceMount:r=n.forceMount,...o}=e,i=bc(od,e.__scopePopover);return f.createElement(xn,{present:r||i.open},i.modal?f.createElement(BW,Y({},o,{ref:t})):f.createElement(UW,Y({},o,{ref:t})))}),BW=f.forwardRef((e,t)=>{const n=bc(od,e.__scopePopover),r=f.useRef(null),o=Be(t,r),i=f.useRef(!1);return f.useEffect(()=>{const s=r.current;if(s)return Xm(s)},[]),f.createElement(Gm,{as:Wo,allowPinchZoom:!0},f.createElement(kP,Y({},e,{ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:ue(e.onCloseAutoFocus,s=>{var l;s.preventDefault(),i.current||(l=n.triggerRef.current)===null||l===void 0||l.focus()}),onPointerDownOutside:ue(e.onPointerDownOutside,s=>{const l=s.detail.originalEvent,u=l.button===0&&l.ctrlKey===!0,d=l.button===2||u;i.current=d},{checkForDefaultPrevented:!1}),onFocusOutside:ue(e.onFocusOutside,s=>s.preventDefault(),{checkForDefaultPrevented:!1})})))}),UW=f.forwardRef((e,t)=>{const n=bc(od,e.__scopePopover),r=f.useRef(!1),o=f.useRef(!1);return f.createElement(kP,Y({},e,{ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var s;if((s=e.onCloseAutoFocus)===null||s===void 0||s.call(e,i),!i.defaultPrevented){var l;r.current||(l=n.triggerRef.current)===null||l===void 0||l.focus(),i.preventDefault()}r.current=!1,o.current=!1},onInteractOutside:i=>{var s,l;(s=e.onInteractOutside)===null||s===void 0||s.call(e,i),i.defaultPrevented||(r.current=!0,i.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const u=i.target;((l=n.triggerRef.current)===null||l===void 0?void 0:l.contains(u))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&o.current&&i.preventDefault()}}))}),kP=f.forwardRef((e,t)=>{const{__scopePopover:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:i,disableOutsidePointerEvents:s,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:d,onInteractOutside:h,...m}=e,g=bc(od,n),y=Tx(n);return Km(),f.createElement(Hm,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:i},f.createElement(yc,{asChild:!0,disableOutsidePointerEvents:s,onInteractOutside:h,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:d,onDismiss:()=>g.onOpenChange(!1)},f.createElement(Bm,Y({"data-state":RP(g.open),role:"dialog",id:g.contentId},y,m,{ref:t,style:{...m.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}}))))});function RP(e){return e?"open":"closed"}const VW=NW,WW=IW,HW=jW,TP=zW,KW=VW,YW=WW,PP=f.forwardRef(({className:e,align:t="center",sideOffset:n=4,...r},o)=>v.jsx(HW,{children:v.jsx(TP,{ref:o,align:t,tabIndex:-1,sideOffset:n,className:Ce("z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...r})}));PP.displayName=TP.displayName;function GW(){var e=f.useRef(!0);return e.current?(e.current=!1,!0):e.current}var XW=function(e,t){var n=GW();f.useEffect(function(){if(!n)return e()},t)};const ZW=XW;var qW=function(){};function Px(e){for(var t=[],n=1;n{const[e,t,n,r,o,i]=bt(g=>[g.getIsProcessing(),g.settings.prompt,g.updateSettings,g.runInpainting,g.showPrevMask,g.hidePrevMask]),s=f.useRef(null);OP(s,()=>{s!=null&&s.current&&s.current.blur()});const l=g=>{g.preventDefault(),g.stopPropagation();const y=g.target;n({prompt:y.value})},u=()=>{e||r()},d=g=>{g.key==="Enter"&&!e&&u()},h=()=>{o()},m=()=>{i()};return v.jsxs("div",{className:"flex gap-4 items-center",children:[v.jsx(Pd,{ref:s,className:"min-w-[500px]",value:t,onInput:l,onKeyUp:d,placeholder:"I want to repaint of..."}),v.jsx(Rn,{size:"sm",onClick:u,disabled:e,onMouseEnter:h,onMouseLeave:m,children:"Dream"})]})};var Lh={exports:{}};/** + * @license + * Lodash + * Copyright OpenJS Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */Lh.exports;(function(e,t){(function(){var n,r="4.17.21",o=200,i="Unsupported core-js use. Try https://npms.io/search?q=ponyfill.",s="Expected a function",l="Invalid `variable` option passed into `_.template`",u="__lodash_hash_undefined__",d=500,h="__lodash_placeholder__",m=1,g=2,y=4,x=1,_=2,C=1,S=2,b=4,E=8,k=16,P=32,M=64,A=128,O=256,F=512,V=30,J="...",G=800,ae=16,U=1,te=2,L=3,ie=1/0,K=9007199254740991,Q=17976931348623157e292,W=NaN,le=4294967295,ge=le-1,Ve=le>>>1,Ue=[["ary",A],["bind",C],["bindKey",S],["curry",E],["curryRight",k],["flip",F],["partial",P],["partialRight",M],["rearg",O]],We="[object Arguments]",Me="[object Array]",fe="[object AsyncFunction]",xe="[object Boolean]",$e="[object Date]",Ae="[object DOMException]",Oe="[object Error]",je="[object Function]",Ot="[object GeneratorFunction]",ct="[object Map]",Yt="[object Number]",Er="[object Null]",gt="[object Object]",js="[object Promise]",I="[object Proxy]",X="[object RegExp]",Z="[object Set]",we="[object String]",he="[object Symbol]",de="[object Undefined]",ke="[object WeakMap]",ft="[object WeakSet]",pt="[object ArrayBuffer]",bn="[object DataView]",Cr="[object Float32Array]",ki="[object Float64Array]",_o="[object Int8Array]",Vn="[object Int16Array]",Da="[object Int32Array]",Ri="[object Uint8Array]",zs="[object Uint8ClampedArray]",Ti="[object Uint16Array]",$c="[object Uint32Array]",yg=/\b__p \+= '';/g,wg=/\b(__p \+=) '' \+/g,Kd=/(__e\(.*?\)|\b__t\)) \+\n'';/g,kc=/&(?:amp|lt|gt|quot|#39);/g,Rc=/[&<>"']/g,Tc=RegExp(kc.source),xg=RegExp(Rc.source),Pc=/<%-([\s\S]+?)%>/g,Yd=/<%([\s\S]+?)%>/g,Ac=/<%=([\s\S]+?)%>/g,bg=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,_g=/^\w*$/,Sg=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,H=/[\\^$.*+?()[\]{}|]/g,Ge=RegExp(H.source),st=/^\s+/,Qr=/\s/,an=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,Gd=/\{\n\/\* \[wrapped with (.+)\] \*/,oO=/,? & /,iO=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,sO=/[()=,{}\[\]\/\s]/,aO=/\\(\\)?/g,lO=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,db=/\w*$/,cO=/^[-+]0x[0-9a-f]+$/i,uO=/^0b[01]+$/i,dO=/^\[object .+?Constructor\]$/,fO=/^0o[0-7]+$/i,pO=/^(?:0|[1-9]\d*)$/,hO=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,Xd=/($^)/,mO=/['\n\r\u2028\u2029\\]/g,Zd="\\ud800-\\udfff",gO="\\u0300-\\u036f",vO="\\ufe20-\\ufe2f",yO="\\u20d0-\\u20ff",fb=gO+vO+yO,pb="\\u2700-\\u27bf",hb="a-z\\xdf-\\xf6\\xf8-\\xff",wO="\\xac\\xb1\\xd7\\xf7",xO="\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf",bO="\\u2000-\\u206f",_O=" \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",mb="A-Z\\xc0-\\xd6\\xd8-\\xde",gb="\\ufe0e\\ufe0f",vb=wO+xO+bO+_O,Eg="['’]",SO="["+Zd+"]",yb="["+vb+"]",qd="["+fb+"]",wb="\\d+",EO="["+pb+"]",xb="["+hb+"]",bb="[^"+Zd+vb+wb+pb+hb+mb+"]",Cg="\\ud83c[\\udffb-\\udfff]",CO="(?:"+qd+"|"+Cg+")",_b="[^"+Zd+"]",$g="(?:\\ud83c[\\udde6-\\uddff]){2}",kg="[\\ud800-\\udbff][\\udc00-\\udfff]",Ia="["+mb+"]",Sb="\\u200d",Eb="(?:"+xb+"|"+bb+")",$O="(?:"+Ia+"|"+bb+")",Cb="(?:"+Eg+"(?:d|ll|m|re|s|t|ve))?",$b="(?:"+Eg+"(?:D|LL|M|RE|S|T|VE))?",kb=CO+"?",Rb="["+gb+"]?",kO="(?:"+Sb+"(?:"+[_b,$g,kg].join("|")+")"+Rb+kb+")*",RO="\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",TO="\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])",Tb=Rb+kb+kO,PO="(?:"+[EO,$g,kg].join("|")+")"+Tb,AO="(?:"+[_b+qd+"?",qd,$g,kg,SO].join("|")+")",OO=RegExp(Eg,"g"),MO=RegExp(qd,"g"),Rg=RegExp(Cg+"(?="+Cg+")|"+AO+Tb,"g"),NO=RegExp([Ia+"?"+xb+"+"+Cb+"(?="+[yb,Ia,"$"].join("|")+")",$O+"+"+$b+"(?="+[yb,Ia+Eb,"$"].join("|")+")",Ia+"?"+Eb+"+"+Cb,Ia+"+"+$b,TO,RO,wb,PO].join("|"),"g"),DO=RegExp("["+Sb+Zd+fb+gb+"]"),IO=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,LO=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],FO=-1,kt={};kt[Cr]=kt[ki]=kt[_o]=kt[Vn]=kt[Da]=kt[Ri]=kt[zs]=kt[Ti]=kt[$c]=!0,kt[We]=kt[Me]=kt[pt]=kt[xe]=kt[bn]=kt[$e]=kt[Oe]=kt[je]=kt[ct]=kt[Yt]=kt[gt]=kt[X]=kt[Z]=kt[we]=kt[ke]=!1;var Et={};Et[We]=Et[Me]=Et[pt]=Et[bn]=Et[xe]=Et[$e]=Et[Cr]=Et[ki]=Et[_o]=Et[Vn]=Et[Da]=Et[ct]=Et[Yt]=Et[gt]=Et[X]=Et[Z]=Et[we]=Et[he]=Et[Ri]=Et[zs]=Et[Ti]=Et[$c]=!0,Et[Oe]=Et[je]=Et[ke]=!1;var jO={À:"A",Á:"A",Â:"A",Ã:"A",Ä:"A",Å:"A",à:"a",á:"a",â:"a",ã:"a",ä:"a",å:"a",Ç:"C",ç:"c",Ð:"D",ð:"d",È:"E",É:"E",Ê:"E",Ë:"E",è:"e",é:"e",ê:"e",ë:"e",Ì:"I",Í:"I",Î:"I",Ï:"I",ì:"i",í:"i",î:"i",ï:"i",Ñ:"N",ñ:"n",Ò:"O",Ó:"O",Ô:"O",Õ:"O",Ö:"O",Ø:"O",ò:"o",ó:"o",ô:"o",õ:"o",ö:"o",ø:"o",Ù:"U",Ú:"U",Û:"U",Ü:"U",ù:"u",ú:"u",û:"u",ü:"u",Ý:"Y",ý:"y",ÿ:"y",Æ:"Ae",æ:"ae",Þ:"Th",þ:"th",ß:"ss",Ā:"A",Ă:"A",Ą:"A",ā:"a",ă:"a",ą:"a",Ć:"C",Ĉ:"C",Ċ:"C",Č:"C",ć:"c",ĉ:"c",ċ:"c",č:"c",Ď:"D",Đ:"D",ď:"d",đ:"d",Ē:"E",Ĕ:"E",Ė:"E",Ę:"E",Ě:"E",ē:"e",ĕ:"e",ė:"e",ę:"e",ě:"e",Ĝ:"G",Ğ:"G",Ġ:"G",Ģ:"G",ĝ:"g",ğ:"g",ġ:"g",ģ:"g",Ĥ:"H",Ħ:"H",ĥ:"h",ħ:"h",Ĩ:"I",Ī:"I",Ĭ:"I",Į:"I",İ:"I",ĩ:"i",ī:"i",ĭ:"i",į:"i",ı:"i",Ĵ:"J",ĵ:"j",Ķ:"K",ķ:"k",ĸ:"k",Ĺ:"L",Ļ:"L",Ľ:"L",Ŀ:"L",Ł:"L",ĺ:"l",ļ:"l",ľ:"l",ŀ:"l",ł:"l",Ń:"N",Ņ:"N",Ň:"N",Ŋ:"N",ń:"n",ņ:"n",ň:"n",ŋ:"n",Ō:"O",Ŏ:"O",Ő:"O",ō:"o",ŏ:"o",ő:"o",Ŕ:"R",Ŗ:"R",Ř:"R",ŕ:"r",ŗ:"r",ř:"r",Ś:"S",Ŝ:"S",Ş:"S",Š:"S",ś:"s",ŝ:"s",ş:"s",š:"s",Ţ:"T",Ť:"T",Ŧ:"T",ţ:"t",ť:"t",ŧ:"t",Ũ:"U",Ū:"U",Ŭ:"U",Ů:"U",Ű:"U",Ų:"U",ũ:"u",ū:"u",ŭ:"u",ů:"u",ű:"u",ų:"u",Ŵ:"W",ŵ:"w",Ŷ:"Y",ŷ:"y",Ÿ:"Y",Ź:"Z",Ż:"Z",Ž:"Z",ź:"z",ż:"z",ž:"z",IJ:"IJ",ij:"ij",Œ:"Oe",œ:"oe",ʼn:"'n",ſ:"s"},zO={"&":"&","<":"<",">":">",'"':""","'":"'"},BO={"&":"&","<":"<",">":">",""":'"',"'":"'"},UO={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},VO=parseFloat,WO=parseInt,Pb=typeof Yc=="object"&&Yc&&Yc.Object===Object&&Yc,HO=typeof self=="object"&&self&&self.Object===Object&&self,fn=Pb||HO||Function("return this")(),Tg=t&&!t.nodeType&&t,Bs=Tg&&!0&&e&&!e.nodeType&&e,Ab=Bs&&Bs.exports===Tg,Pg=Ab&&Pb.process,$r=function(){try{var j=Bs&&Bs.require&&Bs.require("util").types;return j||Pg&&Pg.binding&&Pg.binding("util")}catch{}}(),Ob=$r&&$r.isArrayBuffer,Mb=$r&&$r.isDate,Nb=$r&&$r.isMap,Db=$r&&$r.isRegExp,Ib=$r&&$r.isSet,Lb=$r&&$r.isTypedArray;function or(j,ee,q){switch(q.length){case 0:return j.call(ee);case 1:return j.call(ee,q[0]);case 2:return j.call(ee,q[0],q[1]);case 3:return j.call(ee,q[0],q[1],q[2])}return j.apply(ee,q)}function KO(j,ee,q,_e){for(var Ke=-1,ht=j==null?0:j.length;++Ke-1}function Ag(j,ee,q){for(var _e=-1,Ke=j==null?0:j.length;++_e-1;);return q}function Hb(j,ee){for(var q=j.length;q--&&La(ee,j[q],0)>-1;);return q}function t6(j,ee){for(var q=j.length,_e=0;q--;)j[q]===ee&&++_e;return _e}var n6=Dg(jO),r6=Dg(zO);function o6(j){return"\\"+UO[j]}function i6(j,ee){return j==null?n:j[ee]}function Fa(j){return DO.test(j)}function s6(j){return IO.test(j)}function a6(j){for(var ee,q=[];!(ee=j.next()).done;)q.push(ee.value);return q}function jg(j){var ee=-1,q=Array(j.size);return j.forEach(function(_e,Ke){q[++ee]=[Ke,_e]}),q}function Kb(j,ee){return function(q){return j(ee(q))}}function Oi(j,ee){for(var q=-1,_e=j.length,Ke=0,ht=[];++q<_e;){var en=j[q];(en===ee||en===h)&&(j[q]=h,ht[Ke++]=q)}return ht}function ef(j){var ee=-1,q=Array(j.size);return j.forEach(function(_e){q[++ee]=_e}),q}function l6(j){var ee=-1,q=Array(j.size);return j.forEach(function(_e){q[++ee]=[_e,_e]}),q}function c6(j,ee,q){for(var _e=q-1,Ke=j.length;++_e-1}function G6(a,c){var p=this.__data__,w=gf(p,a);return w<0?(++this.size,p.push([a,c])):p[w][1]=c,this}Xo.prototype.clear=W6,Xo.prototype.delete=H6,Xo.prototype.get=K6,Xo.prototype.has=Y6,Xo.prototype.set=G6;function Zo(a){var c=-1,p=a==null?0:a.length;for(this.clear();++c=c?a:c)),a}function Pr(a,c,p,w,$,T){var N,D=c&m,B=c&g,ne=c&y;if(p&&(N=$?p(a,w,$,T):p(a)),N!==n)return N;if(!It(a))return a;var re=Ye(a);if(re){if(N=QM(a),!D)return Wn(a,N)}else{var se=Sn(a),me=se==je||se==Ot;if(Fi(a))return R_(a,D);if(se==gt||se==We||me&&!$){if(N=B||me?{}:Y_(a),!D)return B?BM(a,uM(N,a)):zM(a,o_(N,a))}else{if(!Et[se])return $?a:{};N=JM(a,se,D)}}T||(T=new eo);var Re=T.get(a);if(Re)return Re;T.set(a,N),_S(a)?a.forEach(function(Le){N.add(Pr(Le,c,p,Le,a,T))}):xS(a)&&a.forEach(function(Le,nt){N.set(nt,Pr(Le,c,p,nt,a,T))});var Ie=ne?B?dv:uv:B?Kn:ln,Qe=re?n:Ie(a);return kr(Qe||a,function(Le,nt){Qe&&(nt=Le,Le=a[nt]),Fc(N,nt,Pr(Le,c,p,nt,a,T))}),N}function dM(a){var c=ln(a);return function(p){return i_(p,a,c)}}function i_(a,c,p){var w=p.length;if(a==null)return!w;for(a=_t(a);w--;){var $=p[w],T=c[$],N=a[$];if(N===n&&!($ in a)||!T(N))return!1}return!0}function s_(a,c,p){if(typeof a!="function")throw new Rr(s);return Hc(function(){a.apply(n,p)},c)}function jc(a,c,p,w){var $=-1,T=Qd,N=!0,D=a.length,B=[],ne=c.length;if(!D)return B;p&&(c=Mt(c,ir(p))),w?(T=Ag,N=!1):c.length>=o&&(T=Oc,N=!1,c=new Ws(c));e:for(;++$$?0:$+p),w=w===n||w>$?$:qe(w),w<0&&(w+=$),w=p>w?0:ES(w);p0&&p(D)?c>1?pn(D,c-1,p,w,$):Ai($,D):w||($[$.length]=D)}return $}var Kg=N_(),c_=N_(!0);function So(a,c){return a&&Kg(a,c,ln)}function Yg(a,c){return a&&c_(a,c,ln)}function yf(a,c){return Pi(c,function(p){return ti(a[p])})}function Ks(a,c){c=Ii(c,a);for(var p=0,w=c.length;a!=null&&pc}function hM(a,c){return a!=null&&yt.call(a,c)}function mM(a,c){return a!=null&&c in _t(a)}function gM(a,c,p){return a>=_n(c,p)&&a=120&&re.length>=120)?new Ws(N&&re):n}re=a[0];var se=-1,me=D[0];e:for(;++se<$&&ne.length-1;)D!==a&&cf.call(D,B,1),cf.call(a,B,1);return a}function x_(a,c){for(var p=a?c.length:0,w=p-1;p--;){var $=c[p];if(p==w||$!==T){var T=$;ei($)?cf.call(a,$,1):rv(a,$)}}return a}function ev(a,c){return a+ff(e_()*(c-a+1))}function TM(a,c,p,w){for(var $=-1,T=tn(df((c-a)/(p||1)),0),N=q(T);T--;)N[w?T:++$]=a,a+=p;return N}function tv(a,c){var p="";if(!a||c<1||c>K)return p;do c%2&&(p+=a),c=ff(c/2),c&&(a+=a);while(c);return p}function et(a,c){return yv(Z_(a,c,Yn),a+"")}function PM(a){return r_(Xa(a))}function AM(a,c){var p=Xa(a);return Tf(p,Hs(c,0,p.length))}function Uc(a,c,p,w){if(!It(a))return a;c=Ii(c,a);for(var $=-1,T=c.length,N=T-1,D=a;D!=null&&++$$?0:$+c),p=p>$?$:p,p<0&&(p+=$),$=c>p?0:p-c>>>0,c>>>=0;for(var T=q($);++w<$;)T[w]=a[w+c];return T}function NM(a,c){var p;return Ni(a,function(w,$,T){return p=c(w,$,T),!p}),!!p}function xf(a,c,p){var w=0,$=a==null?w:a.length;if(typeof c=="number"&&c===c&&$<=Ve){for(;w<$;){var T=w+$>>>1,N=a[T];N!==null&&!ar(N)&&(p?N<=c:N=o){var ne=c?null:HM(a);if(ne)return ef(ne);N=!1,$=Oc,B=new Ws}else B=c?[]:D;e:for(;++w=w?a:Ar(a,c,p)}var k_=_6||function(a){return fn.clearTimeout(a)};function R_(a,c){if(c)return a.slice();var p=a.length,w=Xb?Xb(p):new a.constructor(p);return a.copy(w),w}function av(a){var c=new a.constructor(a.byteLength);return new af(c).set(new af(a)),c}function IM(a,c){var p=c?av(a.buffer):a.buffer;return new a.constructor(p,a.byteOffset,a.byteLength)}function LM(a){var c=new a.constructor(a.source,db.exec(a));return c.lastIndex=a.lastIndex,c}function FM(a){return Lc?_t(Lc.call(a)):{}}function T_(a,c){var p=c?av(a.buffer):a.buffer;return new a.constructor(p,a.byteOffset,a.length)}function P_(a,c){if(a!==c){var p=a!==n,w=a===null,$=a===a,T=ar(a),N=c!==n,D=c===null,B=c===c,ne=ar(c);if(!D&&!ne&&!T&&a>c||T&&N&&B&&!D&&!ne||w&&N&&B||!p&&B||!$)return 1;if(!w&&!T&&!ne&&a=D)return B;var ne=p[w];return B*(ne=="desc"?-1:1)}}return a.index-c.index}function A_(a,c,p,w){for(var $=-1,T=a.length,N=p.length,D=-1,B=c.length,ne=tn(T-N,0),re=q(B+ne),se=!w;++D1?p[$-1]:n,N=$>2?p[2]:n;for(T=a.length>3&&typeof T=="function"?($--,T):n,N&&Mn(p[0],p[1],N)&&(T=$<3?n:T,$=1),c=_t(c);++w<$;){var D=p[w];D&&a(c,D,w,T)}return c})}function M_(a,c){return function(p,w){if(p==null)return p;if(!Hn(p))return a(p,w);for(var $=p.length,T=c?$:-1,N=_t(p);(c?T--:++T<$)&&w(N[T],T,N)!==!1;);return p}}function N_(a){return function(c,p,w){for(var $=-1,T=_t(c),N=w(c),D=N.length;D--;){var B=N[a?D:++$];if(p(T[B],B,T)===!1)break}return c}}function UM(a,c,p){var w=c&C,$=Vc(a);function T(){var N=this&&this!==fn&&this instanceof T?$:a;return N.apply(w?p:this,arguments)}return T}function D_(a){return function(c){c=vt(c);var p=Fa(c)?Jr(c):n,w=p?p[0]:c.charAt(0),$=p?Li(p,1).join(""):c.slice(1);return w[a]()+$}}function Ka(a){return function(c){return Og(MS(OS(c).replace(OO,"")),a,"")}}function Vc(a){return function(){var c=arguments;switch(c.length){case 0:return new a;case 1:return new a(c[0]);case 2:return new a(c[0],c[1]);case 3:return new a(c[0],c[1],c[2]);case 4:return new a(c[0],c[1],c[2],c[3]);case 5:return new a(c[0],c[1],c[2],c[3],c[4]);case 6:return new a(c[0],c[1],c[2],c[3],c[4],c[5]);case 7:return new a(c[0],c[1],c[2],c[3],c[4],c[5],c[6])}var p=Wa(a.prototype),w=a.apply(p,c);return It(w)?w:p}}function VM(a,c,p){var w=Vc(a);function $(){for(var T=arguments.length,N=q(T),D=T,B=Ya($);D--;)N[D]=arguments[D];var ne=T<3&&N[0]!==B&&N[T-1]!==B?[]:Oi(N,B);if(T-=ne.length,T-1?$[T?c[N]:N]:n}}function L_(a){return Jo(function(c){var p=c.length,w=p,$=Tr.prototype.thru;for(a&&c.reverse();w--;){var T=c[w];if(typeof T!="function")throw new Rr(s);if($&&!N&&kf(T)=="wrapper")var N=new Tr([],!0)}for(w=N?w:p;++w1&&at.reverse(),re&&BD))return!1;var ne=T.get(a),re=T.get(c);if(ne&&re)return ne==c&&re==a;var se=-1,me=!0,Re=p&_?new Ws:n;for(T.set(a,c),T.set(c,a);++se1?"& ":"")+c[w],c=c.join(p>2?", ":" "),a.replace(an,`{ +/* [wrapped with `+c+`] */ +`)}function tN(a){return Ye(a)||Xs(a)||!!(Qb&&a&&a[Qb])}function ei(a,c){var p=typeof a;return c=c??K,!!c&&(p=="number"||p!="symbol"&&pO.test(a))&&a>-1&&a%1==0&&a0){if(++c>=G)return arguments[0]}else c=0;return a.apply(n,arguments)}}function Tf(a,c){var p=-1,w=a.length,$=w-1;for(c=c===n?w:c;++p1?a[c-1]:n;return p=typeof p=="function"?(a.pop(),p):n,lS(a,p)});function cS(a){var c=R(a);return c.__chain__=!0,c}function f7(a,c){return c(a),a}function Pf(a,c){return c(a)}var p7=Jo(function(a){var c=a.length,p=c?a[0]:0,w=this.__wrapped__,$=function(T){return Hg(T,a)};return c>1||this.__actions__.length||!(w instanceof ot)||!ei(p)?this.thru($):(w=w.slice(p,+p+(c?1:0)),w.__actions__.push({func:Pf,args:[$],thisArg:n}),new Tr(w,this.__chain__).thru(function(T){return c&&!T.length&&T.push(n),T}))});function h7(){return cS(this)}function m7(){return new Tr(this.value(),this.__chain__)}function g7(){this.__values__===n&&(this.__values__=SS(this.value()));var a=this.__index__>=this.__values__.length,c=a?n:this.__values__[this.__index__++];return{done:a,value:c}}function v7(){return this}function y7(a){for(var c,p=this;p instanceof mf;){var w=nS(p);w.__index__=0,w.__values__=n,c?$.__wrapped__=w:c=w;var $=w;p=p.__wrapped__}return $.__wrapped__=a,c}function w7(){var a=this.__wrapped__;if(a instanceof ot){var c=a;return this.__actions__.length&&(c=new ot(this)),c=c.reverse(),c.__actions__.push({func:Pf,args:[wv],thisArg:n}),new Tr(c,this.__chain__)}return this.thru(wv)}function x7(){return C_(this.__wrapped__,this.__actions__)}var b7=_f(function(a,c,p){yt.call(a,p)?++a[p]:qo(a,p,1)});function _7(a,c,p){var w=Ye(a)?Fb:fM;return p&&Mn(a,c,p)&&(c=n),w(a,De(c,3))}function S7(a,c){var p=Ye(a)?Pi:l_;return p(a,De(c,3))}var E7=I_(rS),C7=I_(oS);function $7(a,c){return pn(Af(a,c),1)}function k7(a,c){return pn(Af(a,c),ie)}function R7(a,c,p){return p=p===n?1:qe(p),pn(Af(a,c),p)}function uS(a,c){var p=Ye(a)?kr:Ni;return p(a,De(c,3))}function dS(a,c){var p=Ye(a)?YO:a_;return p(a,De(c,3))}var T7=_f(function(a,c,p){yt.call(a,p)?a[p].push(c):qo(a,p,[c])});function P7(a,c,p,w){a=Hn(a)?a:Xa(a),p=p&&!w?qe(p):0;var $=a.length;return p<0&&(p=tn($+p,0)),If(a)?p<=$&&a.indexOf(c,p)>-1:!!$&&La(a,c,p)>-1}var A7=et(function(a,c,p){var w=-1,$=typeof c=="function",T=Hn(a)?q(a.length):[];return Ni(a,function(N){T[++w]=$?or(c,N,p):zc(N,c,p)}),T}),O7=_f(function(a,c,p){qo(a,p,c)});function Af(a,c){var p=Ye(a)?Mt:h_;return p(a,De(c,3))}function M7(a,c,p,w){return a==null?[]:(Ye(c)||(c=c==null?[]:[c]),p=w?n:p,Ye(p)||(p=p==null?[]:[p]),y_(a,c,p))}var N7=_f(function(a,c,p){a[p?0:1].push(c)},function(){return[[],[]]});function D7(a,c,p){var w=Ye(a)?Og:Ub,$=arguments.length<3;return w(a,De(c,4),p,$,Ni)}function I7(a,c,p){var w=Ye(a)?GO:Ub,$=arguments.length<3;return w(a,De(c,4),p,$,a_)}function L7(a,c){var p=Ye(a)?Pi:l_;return p(a,Nf(De(c,3)))}function F7(a){var c=Ye(a)?r_:PM;return c(a)}function j7(a,c,p){(p?Mn(a,c,p):c===n)?c=1:c=qe(c);var w=Ye(a)?aM:AM;return w(a,c)}function z7(a){var c=Ye(a)?lM:MM;return c(a)}function B7(a){if(a==null)return 0;if(Hn(a))return If(a)?ja(a):a.length;var c=Sn(a);return c==ct||c==Z?a.size:qg(a).length}function U7(a,c,p){var w=Ye(a)?Mg:NM;return p&&Mn(a,c,p)&&(c=n),w(a,De(c,3))}var V7=et(function(a,c){if(a==null)return[];var p=c.length;return p>1&&Mn(a,c[0],c[1])?c=[]:p>2&&Mn(c[0],c[1],c[2])&&(c=[c[0]]),y_(a,pn(c,1),[])}),Of=S6||function(){return fn.Date.now()};function W7(a,c){if(typeof c!="function")throw new Rr(s);return a=qe(a),function(){if(--a<1)return c.apply(this,arguments)}}function fS(a,c,p){return c=p?n:c,c=a&&c==null?a.length:c,Qo(a,A,n,n,n,n,c)}function pS(a,c){var p;if(typeof c!="function")throw new Rr(s);return a=qe(a),function(){return--a>0&&(p=c.apply(this,arguments)),a<=1&&(c=n),p}}var bv=et(function(a,c,p){var w=C;if(p.length){var $=Oi(p,Ya(bv));w|=P}return Qo(a,w,c,p,$)}),hS=et(function(a,c,p){var w=C|S;if(p.length){var $=Oi(p,Ya(hS));w|=P}return Qo(c,w,a,p,$)});function mS(a,c,p){c=p?n:c;var w=Qo(a,E,n,n,n,n,n,c);return w.placeholder=mS.placeholder,w}function gS(a,c,p){c=p?n:c;var w=Qo(a,k,n,n,n,n,n,c);return w.placeholder=gS.placeholder,w}function vS(a,c,p){var w,$,T,N,D,B,ne=0,re=!1,se=!1,me=!0;if(typeof a!="function")throw new Rr(s);c=Mr(c)||0,It(p)&&(re=!!p.leading,se="maxWait"in p,T=se?tn(Mr(p.maxWait)||0,c):T,me="trailing"in p?!!p.trailing:me);function Re(Xt){var no=w,ri=$;return w=$=n,ne=Xt,N=a.apply(ri,no),N}function Ie(Xt){return ne=Xt,D=Hc(nt,c),re?Re(Xt):N}function Qe(Xt){var no=Xt-B,ri=Xt-ne,IS=c-no;return se?_n(IS,T-ri):IS}function Le(Xt){var no=Xt-B,ri=Xt-ne;return B===n||no>=c||no<0||se&&ri>=T}function nt(){var Xt=Of();if(Le(Xt))return at(Xt);D=Hc(nt,Qe(Xt))}function at(Xt){return D=n,me&&w?Re(Xt):(w=$=n,N)}function lr(){D!==n&&k_(D),ne=0,w=B=$=D=n}function Nn(){return D===n?N:at(Of())}function cr(){var Xt=Of(),no=Le(Xt);if(w=arguments,$=this,B=Xt,no){if(D===n)return Ie(B);if(se)return k_(D),D=Hc(nt,c),Re(B)}return D===n&&(D=Hc(nt,c)),N}return cr.cancel=lr,cr.flush=Nn,cr}var H7=et(function(a,c){return s_(a,1,c)}),K7=et(function(a,c,p){return s_(a,Mr(c)||0,p)});function Y7(a){return Qo(a,F)}function Mf(a,c){if(typeof a!="function"||c!=null&&typeof c!="function")throw new Rr(s);var p=function(){var w=arguments,$=c?c.apply(this,w):w[0],T=p.cache;if(T.has($))return T.get($);var N=a.apply(this,w);return p.cache=T.set($,N)||T,N};return p.cache=new(Mf.Cache||Zo),p}Mf.Cache=Zo;function Nf(a){if(typeof a!="function")throw new Rr(s);return function(){var c=arguments;switch(c.length){case 0:return!a.call(this);case 1:return!a.call(this,c[0]);case 2:return!a.call(this,c[0],c[1]);case 3:return!a.call(this,c[0],c[1],c[2])}return!a.apply(this,c)}}function G7(a){return pS(2,a)}var X7=DM(function(a,c){c=c.length==1&&Ye(c[0])?Mt(c[0],ir(De())):Mt(pn(c,1),ir(De()));var p=c.length;return et(function(w){for(var $=-1,T=_n(w.length,p);++$=c}),Xs=d_(function(){return arguments}())?d_:function(a){return Bt(a)&&yt.call(a,"callee")&&!qb.call(a,"callee")},Ye=q.isArray,u4=Ob?ir(Ob):yM;function Hn(a){return a!=null&&Df(a.length)&&!ti(a)}function Gt(a){return Bt(a)&&Hn(a)}function d4(a){return a===!0||a===!1||Bt(a)&&On(a)==xe}var Fi=C6||Mv,f4=Mb?ir(Mb):wM;function p4(a){return Bt(a)&&a.nodeType===1&&!Kc(a)}function h4(a){if(a==null)return!0;if(Hn(a)&&(Ye(a)||typeof a=="string"||typeof a.splice=="function"||Fi(a)||Ga(a)||Xs(a)))return!a.length;var c=Sn(a);if(c==ct||c==Z)return!a.size;if(Wc(a))return!qg(a).length;for(var p in a)if(yt.call(a,p))return!1;return!0}function m4(a,c){return Bc(a,c)}function g4(a,c,p){p=typeof p=="function"?p:n;var w=p?p(a,c):n;return w===n?Bc(a,c,n,p):!!w}function Sv(a){if(!Bt(a))return!1;var c=On(a);return c==Oe||c==Ae||typeof a.message=="string"&&typeof a.name=="string"&&!Kc(a)}function v4(a){return typeof a=="number"&&Jb(a)}function ti(a){if(!It(a))return!1;var c=On(a);return c==je||c==Ot||c==fe||c==I}function wS(a){return typeof a=="number"&&a==qe(a)}function Df(a){return typeof a=="number"&&a>-1&&a%1==0&&a<=K}function It(a){var c=typeof a;return a!=null&&(c=="object"||c=="function")}function Bt(a){return a!=null&&typeof a=="object"}var xS=Nb?ir(Nb):bM;function y4(a,c){return a===c||Zg(a,c,pv(c))}function w4(a,c,p){return p=typeof p=="function"?p:n,Zg(a,c,pv(c),p)}function x4(a){return bS(a)&&a!=+a}function b4(a){if(oN(a))throw new Ke(i);return f_(a)}function _4(a){return a===null}function S4(a){return a==null}function bS(a){return typeof a=="number"||Bt(a)&&On(a)==Yt}function Kc(a){if(!Bt(a)||On(a)!=gt)return!1;var c=lf(a);if(c===null)return!0;var p=yt.call(c,"constructor")&&c.constructor;return typeof p=="function"&&p instanceof p&&rf.call(p)==w6}var Ev=Db?ir(Db):_M;function E4(a){return wS(a)&&a>=-K&&a<=K}var _S=Ib?ir(Ib):SM;function If(a){return typeof a=="string"||!Ye(a)&&Bt(a)&&On(a)==we}function ar(a){return typeof a=="symbol"||Bt(a)&&On(a)==he}var Ga=Lb?ir(Lb):EM;function C4(a){return a===n}function $4(a){return Bt(a)&&Sn(a)==ke}function k4(a){return Bt(a)&&On(a)==ft}var R4=$f(Qg),T4=$f(function(a,c){return a<=c});function SS(a){if(!a)return[];if(Hn(a))return If(a)?Jr(a):Wn(a);if(Mc&&a[Mc])return a6(a[Mc]());var c=Sn(a),p=c==ct?jg:c==Z?ef:Xa;return p(a)}function ni(a){if(!a)return a===0?a:0;if(a=Mr(a),a===ie||a===-ie){var c=a<0?-1:1;return c*Q}return a===a?a:0}function qe(a){var c=ni(a),p=c%1;return c===c?p?c-p:c:0}function ES(a){return a?Hs(qe(a),0,le):0}function Mr(a){if(typeof a=="number")return a;if(ar(a))return W;if(It(a)){var c=typeof a.valueOf=="function"?a.valueOf():a;a=It(c)?c+"":c}if(typeof a!="string")return a===0?a:+a;a=Vb(a);var p=uO.test(a);return p||fO.test(a)?WO(a.slice(2),p?2:8):cO.test(a)?W:+a}function CS(a){return Eo(a,Kn(a))}function P4(a){return a?Hs(qe(a),-K,K):a===0?a:0}function vt(a){return a==null?"":sr(a)}var A4=Ha(function(a,c){if(Wc(c)||Hn(c)){Eo(c,ln(c),a);return}for(var p in c)yt.call(c,p)&&Fc(a,p,c[p])}),$S=Ha(function(a,c){Eo(c,Kn(c),a)}),Lf=Ha(function(a,c,p,w){Eo(c,Kn(c),a,w)}),O4=Ha(function(a,c,p,w){Eo(c,ln(c),a,w)}),M4=Jo(Hg);function N4(a,c){var p=Wa(a);return c==null?p:o_(p,c)}var D4=et(function(a,c){a=_t(a);var p=-1,w=c.length,$=w>2?c[2]:n;for($&&Mn(c[0],c[1],$)&&(w=1);++p1),T}),Eo(a,dv(a),p),w&&(p=Pr(p,m|g|y,KM));for(var $=c.length;$--;)rv(p,c[$]);return p});function J4(a,c){return RS(a,Nf(De(c)))}var e8=Jo(function(a,c){return a==null?{}:kM(a,c)});function RS(a,c){if(a==null)return{};var p=Mt(dv(a),function(w){return[w]});return c=De(c),w_(a,p,function(w,$){return c(w,$[0])})}function t8(a,c,p){c=Ii(c,a);var w=-1,$=c.length;for($||($=1,a=n);++w<$;){var T=a==null?n:a[Co(c[w])];T===n&&(w=$,T=p),a=ti(T)?T.call(a):T}return a}function n8(a,c,p){return a==null?a:Uc(a,c,p)}function r8(a,c,p,w){return w=typeof w=="function"?w:n,a==null?a:Uc(a,c,p,w)}var TS=B_(ln),PS=B_(Kn);function o8(a,c,p){var w=Ye(a),$=w||Fi(a)||Ga(a);if(c=De(c,4),p==null){var T=a&&a.constructor;$?p=w?new T:[]:It(a)?p=ti(T)?Wa(lf(a)):{}:p={}}return($?kr:So)(a,function(N,D,B){return c(p,N,D,B)}),p}function i8(a,c){return a==null?!0:rv(a,c)}function s8(a,c,p){return a==null?a:E_(a,c,sv(p))}function a8(a,c,p,w){return w=typeof w=="function"?w:n,a==null?a:E_(a,c,sv(p),w)}function Xa(a){return a==null?[]:Fg(a,ln(a))}function l8(a){return a==null?[]:Fg(a,Kn(a))}function c8(a,c,p){return p===n&&(p=c,c=n),p!==n&&(p=Mr(p),p=p===p?p:0),c!==n&&(c=Mr(c),c=c===c?c:0),Hs(Mr(a),c,p)}function u8(a,c,p){return c=ni(c),p===n?(p=c,c=0):p=ni(p),a=Mr(a),gM(a,c,p)}function d8(a,c,p){if(p&&typeof p!="boolean"&&Mn(a,c,p)&&(c=p=n),p===n&&(typeof c=="boolean"?(p=c,c=n):typeof a=="boolean"&&(p=a,a=n)),a===n&&c===n?(a=0,c=1):(a=ni(a),c===n?(c=a,a=0):c=ni(c)),a>c){var w=a;a=c,c=w}if(p||a%1||c%1){var $=e_();return _n(a+$*(c-a+VO("1e-"+(($+"").length-1))),c)}return ev(a,c)}var f8=Ka(function(a,c,p){return c=c.toLowerCase(),a+(p?AS(c):c)});function AS(a){return kv(vt(a).toLowerCase())}function OS(a){return a=vt(a),a&&a.replace(hO,n6).replace(MO,"")}function p8(a,c,p){a=vt(a),c=sr(c);var w=a.length;p=p===n?w:Hs(qe(p),0,w);var $=p;return p-=c.length,p>=0&&a.slice(p,$)==c}function h8(a){return a=vt(a),a&&xg.test(a)?a.replace(Rc,r6):a}function m8(a){return a=vt(a),a&&Ge.test(a)?a.replace(H,"\\$&"):a}var g8=Ka(function(a,c,p){return a+(p?"-":"")+c.toLowerCase()}),v8=Ka(function(a,c,p){return a+(p?" ":"")+c.toLowerCase()}),y8=D_("toLowerCase");function w8(a,c,p){a=vt(a),c=qe(c);var w=c?ja(a):0;if(!c||w>=c)return a;var $=(c-w)/2;return Cf(ff($),p)+a+Cf(df($),p)}function x8(a,c,p){a=vt(a),c=qe(c);var w=c?ja(a):0;return c&&w>>0,p?(a=vt(a),a&&(typeof c=="string"||c!=null&&!Ev(c))&&(c=sr(c),!c&&Fa(a))?Li(Jr(a),0,p):a.split(c,p)):[]}var k8=Ka(function(a,c,p){return a+(p?" ":"")+kv(c)});function R8(a,c,p){return a=vt(a),p=p==null?0:Hs(qe(p),0,a.length),c=sr(c),a.slice(p,p+c.length)==c}function T8(a,c,p){var w=R.templateSettings;p&&Mn(a,c,p)&&(c=n),a=vt(a),c=Lf({},c,w,U_);var $=Lf({},c.imports,w.imports,U_),T=ln($),N=Fg($,T),D,B,ne=0,re=c.interpolate||Xd,se="__p += '",me=zg((c.escape||Xd).source+"|"+re.source+"|"+(re===Ac?lO:Xd).source+"|"+(c.evaluate||Xd).source+"|$","g"),Re="//# sourceURL="+(yt.call(c,"sourceURL")?(c.sourceURL+"").replace(/\s/g," "):"lodash.templateSources["+ ++FO+"]")+` +`;a.replace(me,function(Le,nt,at,lr,Nn,cr){return at||(at=lr),se+=a.slice(ne,cr).replace(mO,o6),nt&&(D=!0,se+=`' + +__e(`+nt+`) + +'`),Nn&&(B=!0,se+=`'; +`+Nn+`; +__p += '`),at&&(se+=`' + +((__t = (`+at+`)) == null ? '' : __t) + +'`),ne=cr+Le.length,Le}),se+=`'; +`;var Ie=yt.call(c,"variable")&&c.variable;if(!Ie)se=`with (obj) { +`+se+` +} +`;else if(sO.test(Ie))throw new Ke(l);se=(B?se.replace(yg,""):se).replace(wg,"$1").replace(Kd,"$1;"),se="function("+(Ie||"obj")+`) { +`+(Ie?"":`obj || (obj = {}); +`)+"var __t, __p = ''"+(D?", __e = _.escape":"")+(B?`, __j = Array.prototype.join; +function print() { __p += __j.call(arguments, '') } +`:`; +`)+se+`return __p +}`;var Qe=NS(function(){return ht(T,Re+"return "+se).apply(n,N)});if(Qe.source=se,Sv(Qe))throw Qe;return Qe}function P8(a){return vt(a).toLowerCase()}function A8(a){return vt(a).toUpperCase()}function O8(a,c,p){if(a=vt(a),a&&(p||c===n))return Vb(a);if(!a||!(c=sr(c)))return a;var w=Jr(a),$=Jr(c),T=Wb(w,$),N=Hb(w,$)+1;return Li(w,T,N).join("")}function M8(a,c,p){if(a=vt(a),a&&(p||c===n))return a.slice(0,Yb(a)+1);if(!a||!(c=sr(c)))return a;var w=Jr(a),$=Hb(w,Jr(c))+1;return Li(w,0,$).join("")}function N8(a,c,p){if(a=vt(a),a&&(p||c===n))return a.replace(st,"");if(!a||!(c=sr(c)))return a;var w=Jr(a),$=Wb(w,Jr(c));return Li(w,$).join("")}function D8(a,c){var p=V,w=J;if(It(c)){var $="separator"in c?c.separator:$;p="length"in c?qe(c.length):p,w="omission"in c?sr(c.omission):w}a=vt(a);var T=a.length;if(Fa(a)){var N=Jr(a);T=N.length}if(p>=T)return a;var D=p-ja(w);if(D<1)return w;var B=N?Li(N,0,D).join(""):a.slice(0,D);if($===n)return B+w;if(N&&(D+=B.length-D),Ev($)){if(a.slice(D).search($)){var ne,re=B;for($.global||($=zg($.source,vt(db.exec($))+"g")),$.lastIndex=0;ne=$.exec(re);)var se=ne.index;B=B.slice(0,se===n?D:se)}}else if(a.indexOf(sr($),D)!=D){var me=B.lastIndexOf($);me>-1&&(B=B.slice(0,me))}return B+w}function I8(a){return a=vt(a),a&&Tc.test(a)?a.replace(kc,d6):a}var L8=Ka(function(a,c,p){return a+(p?" ":"")+c.toUpperCase()}),kv=D_("toUpperCase");function MS(a,c,p){return a=vt(a),c=p?n:c,c===n?s6(a)?h6(a):qO(a):a.match(c)||[]}var NS=et(function(a,c){try{return or(a,n,c)}catch(p){return Sv(p)?p:new Ke(p)}}),F8=Jo(function(a,c){return kr(c,function(p){p=Co(p),qo(a,p,bv(a[p],a))}),a});function j8(a){var c=a==null?0:a.length,p=De();return a=c?Mt(a,function(w){if(typeof w[1]!="function")throw new Rr(s);return[p(w[0]),w[1]]}):[],et(function(w){for(var $=-1;++$K)return[];var p=le,w=_n(a,le);c=De(c),a-=le;for(var $=Lg(w,c);++p0||c<0)?new ot(p):(a<0?p=p.takeRight(-a):a&&(p=p.drop(a)),c!==n&&(c=qe(c),p=c<0?p.dropRight(-c):p.take(c-a)),p)},ot.prototype.takeRightWhile=function(a){return this.reverse().takeWhile(a).reverse()},ot.prototype.toArray=function(){return this.take(le)},So(ot.prototype,function(a,c){var p=/^(?:filter|find|map|reject)|While$/.test(c),w=/^(?:head|last)$/.test(c),$=R[w?"take"+(c=="last"?"Right":""):c],T=w||/^find/.test(c);$&&(R.prototype[c]=function(){var N=this.__wrapped__,D=w?[1]:arguments,B=N instanceof ot,ne=D[0],re=B||Ye(N),se=function(nt){var at=$.apply(R,Ai([nt],D));return w&&me?at[0]:at};re&&p&&typeof ne=="function"&&ne.length!=1&&(B=re=!1);var me=this.__chain__,Re=!!this.__actions__.length,Ie=T&&!me,Qe=B&&!Re;if(!T&&re){N=Qe?N:new ot(this);var Le=a.apply(N,D);return Le.__actions__.push({func:Pf,args:[se],thisArg:n}),new Tr(Le,me)}return Ie&&Qe?a.apply(this,D):(Le=this.thru(se),Ie?w?Le.value()[0]:Le.value():Le)})}),kr(["pop","push","shift","sort","splice","unshift"],function(a){var c=tf[a],p=/^(?:push|sort|unshift)$/.test(a)?"tap":"thru",w=/^(?:pop|shift)$/.test(a);R.prototype[a]=function(){var $=arguments;if(w&&!this.__chain__){var T=this.value();return c.apply(Ye(T)?T:[],$)}return this[p](function(N){return c.apply(Ye(N)?N:[],$)})}}),So(ot.prototype,function(a,c){var p=R[c];if(p){var w=p.name+"";yt.call(Va,w)||(Va[w]=[]),Va[w].push({name:c,func:p})}}),Va[Sf(n,S).name]=[{name:"wrapper",func:n}],ot.prototype.clone=I6,ot.prototype.reverse=L6,ot.prototype.value=F6,R.prototype.at=p7,R.prototype.chain=h7,R.prototype.commit=m7,R.prototype.next=g7,R.prototype.plant=y7,R.prototype.reverse=w7,R.prototype.toJSON=R.prototype.valueOf=R.prototype.value=x7,R.prototype.first=R.prototype.head,Mc&&(R.prototype[Mc]=v7),R},za=m6();Bs?((Bs.exports=za)._=za,Tg._=za):fn._=za}).call(Yc)})(Lh,Lh.exports);var wH=Lh.exports;const xH=lm(wH);function Vr({width:e,height:t}){return e/t}function Fh(e,t=0){const n=10**t;return Math.round((e+Number.EPSILON)*n)/n}function bH(e){return(t,n)=>e(n)-e(t)}class _H{constructor(t){this.comparator=t,this.heap=[],this.n=0}greater(t,n){return this.comparator(this.heap[t],this.heap[n])<0}swap(t,n){const r=this.heap[t];this.heap[t]=this.heap[n],this.heap[n]=r}swim(t){let n=t,r=Math.floor(n/2);for(;n>1&&this.greater(r,n);)this.swap(r,n),n=r,r=Math.floor(n/2)}sink(t){let n=t,r=n*2;for(;r<=this.n&&(rl.weight));for(s.push({id:t,weight:0});s.size()>0;){const{id:l,weight:u}=s.pop();if(!o.has(l)){const d=e(l);o.add(l),d.forEach((h,m)=>{const g=u+h,y=r.get(m),x=i.get(m);(x===void 0||x>g&&(x/g>1.005||y!==void 0&&yMath.min(Vr(i),o),Number.MAX_VALUE);return Fh(n/t/r)+2}function MP(e,t,n,r){const o=t-(e.length-1)*n-2*r*e.length,i=e.reduce((s,l)=>s+Vr(l),0);return o/i}function kH(e,t,n,r,o,i,s){const l=e.slice(t,n),u=MP(l,r,i,s);return u>0?(u-o)**2*l.length:void 0}function RH({photos:e,layoutOptions:t,targetRowHeight:n,limitNodeSearch:r,rowConstraints:o}){return i=>{var s,l;const{containerWidth:u,spacing:d,padding:h}=t,m=new Map;m.set(i,0);const g=(s=o==null?void 0:o.minPhotos)!=null?s:1,y=Math.min(r,(l=o==null?void 0:o.maxPhotos)!=null?l:1/0);for(let x=i+g;xy);x+=1){const _=kH(e,i,x,u,n,d,h);if(_===void 0)break;m.set(x,_)}return m}}function TH({photos:e,layoutOptions:t}){const{spacing:n,padding:r,containerWidth:o,targetRowHeight:i,rowConstraints:s}=t,l=$H({photos:e,containerWidth:o,targetRowHeight:i}),u=RH({photos:e,layoutOptions:t,targetRowHeight:i,limitNodeSearch:l,rowConstraints:s}),d=CH(u,0,e.length);if(d===void 0)return;const h=[];for(let m=1;m({photo:x,index:_})).slice(d[m-1],d[m]),y=MP(g.map(({photo:x})=>x),o,n,r);h.push(g.map(({photo:x,index:_},C)=>({photo:x,layout:{height:y,width:y*Vr(x),index:_,photoIndex:C,photosCount:g.length}})))}return h}function qm(...e){return[...e].filter(t=>!!t).join(" ")}function NP(e,{width:t,photosCount:n},{spacing:r,padding:o,containerWidth:i}){const s=r*(n-1)+2*o*n;return`calc((${e} - ${s}px) / ${Fh((i-s)/t,5)})`}function PH(e,t){return t.layout!=="rows"?`calc(100% - ${2*t.padding}px)`:NP("100%",e,t)}function i2(e,t,n){var r,o;return NP((o=(r=e.match(/calc\((.*)\)/))==null?void 0:r[1])!=null?o:e,t,n)}function AH(e,t,n){let r,o;const i=e.srcSet||e.images;return i&&i.length>0&&(r=i.concat(i.find(({width:s})=>s===e.width)?[]:[{src:e.src,width:e.width,height:e.height}]).sort((s,l)=>s.width-l.width).map(s=>`${s.src} ${s.width}w`).join(", ")),n.sizes?o=(n.sizes.sizes||[]).map(({viewport:s,size:l})=>`${s} ${i2(l,t,n)}`).concat(i2(n.sizes.size,t,n)).join(", "):r&&(o=`${Math.ceil(t.width/n.containerWidth*100)}vw`),{srcSet:r,sizes:o}}function Ox(e){var t,n;const{photo:r,layout:o,layoutOptions:i,imageProps:{style:s,className:l,...u}={},renderPhoto:d}=e,{onClick:h}=i,m={display:"block",boxSizing:"content-box",width:PH(o,i),height:"auto",aspectRatio:`${r.width} / ${r.height}`,...i.padding?{padding:`${i.padding}px`}:null,...(i.layout==="columns"||i.layout==="masonry")&&o.photoIndex{h({event:C,photo:r,index:o.index})}:void 0,y={src:r.src,alt:(t=r.alt)!=null?t:"",title:r.title,onClick:g,style:m,className:qm("react-photo-album--photo",l),loading:"lazy",decoding:"async",...AH(r,o,i),...u},x=C=>{const{src:S,alt:b,srcSet:E,sizes:k,style:P,...M}=y;return f.createElement("img",{alt:b,...E?{srcSet:E,sizes:k}:null,src:S,style:C!=null&&C.wrapped?{display:"block",width:"100%",height:"100%"}:P,...M})},_=(({display:C,boxSizing:S,width:b,aspectRatio:E,padding:k,marginBottom:P,cursor:M})=>({display:C,boxSizing:S,width:b,aspectRatio:E,padding:k,marginBottom:P,cursor:M}))(m);return f.createElement(f.Fragment,null,(n=d==null?void 0:d({photo:r,layout:o,layoutOptions:i,imageProps:y,renderDefaultPhoto:x,wrapperStyle:_}))!=null?n:x())}function OH({rowContainerProps:e,children:t}){return f.createElement("div",{...e},t)}function MH(e){const{layoutOptions:t,rowIndex:n,rowsCount:r,renderRowContainer:o,rowContainerProps:{style:i,className:s,...l}={},children:u}=e,d={className:qm("react-photo-album--row",s),style:{display:"flex",flexDirection:"row",flexWrap:"nowrap",alignItems:"flex-start",justifyContent:"space-between",...nf.createElement(MH,{key:`row-${d}`,layoutOptions:n,rowIndex:d,rowsCount:l.length,renderRowContainer:o,rowContainerProps:s},u.map(({photo:h,layout:m})=>f.createElement(Ox,{key:h.key||h.src,photo:h,layout:m,layoutOptions:n,renderPhoto:r,imageProps:i}))))):null}function DH(e,t,n,r){const o=new Map,i=new Set;i.add(n);for(let s=0;s{const d=s>0?o.get(u)[s].weight:0;e(u).forEach(({neighbor:h,weight:m})=>{let g=o.get(h);g||(g=[],o.set(h,g));const y=d+m,x=g[s+1];(!x||x.weight>y&&(x.weight/y>1.0001||u0;i-=1)o=e.get(o)[i].node,r.push(o);return r.reverse()}function LH(e,t,n,r){return IH(DH(e,t,n,r),t,r)}function FH({photos:e,spacing:t,padding:n,targetColumnWidth:r,targetColumnHeight:o}){return i=>{const s=[],l=o*1.5;let u=r/Vr(e[i])+2*n;for(let d=i+1;dl||d===e.length));d+=1)u+=r/Vr(e[d])+t+2*n;return s}}function s2({path:e,photos:t,containerWidth:n,columnsGaps:r,columnsRatios:o,spacing:i,padding:s}){const l=[],u=o.reduce((d,h)=>d+h,0);for(let d=0;d({photo:y,index:x})).slice(e[d],e[d+1]),m=o.reduce((y,x,_)=>y+(r[d]-r[_])*x,0),g=(n-(e.length-2)*i-2*(e.length-1)*s-m)*o[d]/u;l.push(h.map(({photo:y,index:x},_)=>({photo:y,layout:{width:g,height:g/Vr(y),index:x,photoIndex:_,photosCount:h.length}})))}return l}function jH({photos:e,layoutOptions:t,targetColumnWidth:n}){const{columns:r,spacing:o,padding:i,containerWidth:s}=t,l=[],u=[];if(e.length<=r){const y=e.length>0?e.reduce((_,C)=>_+Vr(C),0)/e.length:1;for(let _=0;_Math.min(C,e.length)),photos:e,columnsRatios:u,columnsGaps:l,containerWidth:s,spacing:o,padding:i});return{columnsGaps:l,columnsRatios:u,columnsModel:x}}const d=(e.reduce((y,x)=>y+n/Vr(x),0)+o*(e.length-r)+2*i*e.length)/r,h=FH({photos:e,targetColumnWidth:n,targetColumnHeight:d,spacing:o,padding:i}),m=LH(h,r,0,e.length);for(let y=0;y_+1/Vr(C),0)}const g=s2({path:m,photos:e,columnsRatios:u,columnsGaps:l,containerWidth:s,spacing:o,padding:i});return{columnsGaps:l,columnsRatios:u,columnsModel:g}}function DP(e){const{photos:t,layoutOptions:n}=e,{columns:r,spacing:o,padding:i,containerWidth:s}=n,l=(s-o*(r-1)-2*i*r)/r,{columnsGaps:u,columnsRatios:d,columnsModel:h}=jH({photos:t,layoutOptions:n,targetColumnWidth:l});return h.findIndex(m=>m.findIndex(({layout:{width:g,height:y}})=>g<0||y<0)>=0)>=0?r>1?DP({photos:t,layoutOptions:{...n,columns:r-1}}):void 0:{columnsModel:h,columnsGaps:u,columnsRatios:d}}function zH({photos:e,layoutOptions:t}){return DP({photos:e,layoutOptions:t})}function BH({columnContainerProps:e,children:t}){return f.createElement("div",{...e},t)}function UH(e){const{layoutOptions:t,columnIndex:n,columnsCount:r,columnsGaps:o,columnsRatios:i}=e,{layout:s,spacing:l,padding:u}=t;if(s==="masonry"||!o||!i)return`calc((100% - ${l*(r-1)}px) / ${r})`;const d=i.reduce((m,g)=>m+g,0),h=i.reduce((m,g,y)=>m+(o[n]-o[y])*g,0);return`calc((100% - ${Fh((r-1)*l+2*r*u+h,3)}px) * ${Fh(i[n]/d,5)} + ${2*u}px)`}function IP(e){const{layoutOptions:t,renderColumnContainer:n,children:r,columnContainerProps:{style:o,className:i,...s}={},...l}=e,u={className:qm("react-photo-album--column",i),style:{display:"flex",flexDirection:"column",flexWrap:"nowrap",alignItems:"flex-start",width:UH(e),justifyContent:t.layout==="columns"?"space-between":"flex-start",...o},...s};return f.createElement(f.Fragment,null,(n??BH)({layoutOptions:t,columnContainerProps:u,children:r,...l}))}function VH(e){const{photos:t,layoutOptions:n,renderPhoto:r,renderColumnContainer:o,componentsProps:{imageProps:i,columnContainerProps:s}}=e,l=zH({photos:t,layoutOptions:n});if(!l)return null;const{columnsModel:u,columnsRatios:d,columnsGaps:h}=l;return f.createElement(f.Fragment,null,u.map((m,g)=>f.createElement(IP,{key:`column-${g}`,layoutOptions:n,columnIndex:g,columnsCount:u.length,columnsGaps:h,columnsRatios:d,renderColumnContainer:o,columnContainerProps:s},m.map(({photo:y,layout:x})=>f.createElement(Ox,{key:y.key||y.src,photo:y,layout:x,layoutOptions:n,renderPhoto:r,imageProps:i})))))}function LP(e){const{photos:t,layoutOptions:n}=e,{columns:r,spacing:o,padding:i,containerWidth:s}=n,l=(s-o*(r-1)-2*i*r)/r;if(l<=0)return r>1?LP({...e,layoutOptions:{...n,columns:r-1}}):void 0;const u=[];for(let h=0;h{const y=u.reduce((x,_,C)=>_[])).map(h=>h.map(({photo:m,index:g},y)=>({photo:m,layout:{width:l,height:l/Vr(m),index:g,photoIndex:y,photosCount:h.length}})))}function WH(e){const{photos:t,layoutOptions:n,renderPhoto:r,renderColumnContainer:o,componentsProps:{imageProps:i,columnContainerProps:s}}=e,l=LP({photos:t,layoutOptions:n});return l?f.createElement(f.Fragment,null,l.map((u,d)=>f.createElement(IP,{key:`masonry-column-${d}`,layoutOptions:n,columnsCount:l.length,columnIndex:d,renderColumnContainer:o,columnContainerProps:s},u.map(({photo:h,layout:m})=>f.createElement(Ox,{key:h.key||h.src,photo:h,layout:m,layoutOptions:n,renderPhoto:r,imageProps:i}))))):null}function HH({containerProps:e,children:t,containerRef:n}){return f.createElement("div",{ref:n,...e},t)}function KH(e){const{layout:t,renderContainer:n,children:r,containerRef:o,containerProps:{style:i,className:s,...l}={}}=e,u={className:qm("react-photo-album",`react-photo-album--${t}`,s),style:{display:"flex",flexWrap:"nowrap",justifyContent:"space-between",flexDirection:t==="rows"?"column":"row",...i},...l};return f.createElement(f.Fragment,null,(n??HH)({containerProps:u,containerRef:o,layout:t,children:r}))}function YH(e){const t=f.useRef(e);return(!e||!t.current||e.join()!==t.current.join())&&(t.current=e),t.current}function GH(e,{newContainerWidth:t,newScrollbarWidth:n}){const{containerWidth:r,scrollbarWidth:o}=e;return r!==void 0&&o!==void 0&&t!==void 0&&n!==void 0&&t>r&&t-r<=20&&n0){const r=[...t.filter(i=>i>0)].sort((i,s)=>s-i);r.push(Math.floor(r[r.length-1]/2));const o=n;n=r.find((i,s)=>i<=o||s===r.length-1)}return n}function ZH(e,t){const[{containerWidth:n},r]=f.useReducer(GH,{containerWidth:t}),o=f.useRef(null),i=f.useRef();return{containerRef:f.useCallback(l=>{var u;(u=i.current)==null||u.disconnect(),i.current=void 0,o.current=l;const d=()=>r({newContainerWidth:XH(o.current,e),newScrollbarWidth:window.innerWidth-document.documentElement.clientWidth});d(),l&&typeof ResizeObserver<"u"&&(i.current=new ResizeObserver(d),i.current.observe(l))},[e]),containerWidth:n}}const qH=Object.freeze([1200,600,300,0]);function Mx(e,t){return typeof e=="function"?e(t):e}function FP(e,t){return typeof e<"u"?Mx(e,t):void 0}function QH(e,t){const n=qH.findIndex(r=>r<=t);return Mx(e[n>=0?n:0],t)}function fp(e,t,n,r=0){const o=FP(e,t);return Math.round(Math.max(o===void 0?QH(n,t):o,r))}function JH({layout:e,onClick:t,containerWidth:n,targetRowHeight:r,rowConstraints:o,columns:i,spacing:s,padding:l,sizes:u}){return{layout:e,onClick:t,containerWidth:n,columns:fp(i,n,[5,4,3,2],1),spacing:fp(s,n,[20,15,10,5]),padding:fp(l,n,[0,0,0,0,0]),targetRowHeight:fp(r,n,[d=>d/5,d=>d/4,d=>d/3,d=>d/2]),rowConstraints:FP(o,n),sizes:u}}function eK(e,t,n){const{photos:r,componentsProps:o}=e,i=Mx(o,t)||{};if(n){const{layout:s,spacing:l,padding:u,rowConstraints:d}=n;if(s==="rows"){const{singleRowMaxHeight:h}=d||{};if(h){const m=Math.floor(r.reduce((g,{width:y,height:x})=>g+y/x*h-2*u,u*r.length*2+l*(r.length-1)));m>0&&(i.containerProps=i.containerProps||{},i.containerProps.style={maxWidth:m,...i.containerProps.style})}}}return i}function tK(e,t,n){const{photos:r,layout:o,renderPhoto:i,renderRowContainer:s,renderColumnContainer:l}=e,u={photos:r,renderPhoto:i,componentsProps:t};return o==="rows"?f.createElement(NH,{layoutOptions:n,renderRowContainer:s,...u}):o==="columns"?f.createElement(VH,{layoutOptions:n,renderColumnContainer:l,...u}):f.createElement(WH,{layoutOptions:n,renderColumnContainer:l,...u})}function nK(e){const{photos:t,layout:n,renderContainer:r,defaultContainerWidth:o,breakpoints:i}=e,{containerRef:s,containerWidth:l}=ZH(YH(i),o);if(!n||!["rows","columns","masonry"].includes(n)||!Array.isArray(t))return null;const u=l?JH({containerWidth:l,...e}):void 0,d=eK(e,l,u);return f.createElement(KH,{layout:n,containerRef:s,renderContainer:r,containerProps:d.containerProps},u&&tK(e,d,u))}function rK({title:e,titleId:t,...n},r){return f.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true",ref:r,"aria-labelledby":t},n),e?f.createElement("title",{id:t},e):null,f.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3 4.5h14.25M3 9h9.75M3 13.5h9.75m4.5-4.5v12m0 0l-3.75-3.75M17.25 21L21 17.25"}))}const oK=f.forwardRef(rK),iK=oK;function sK({title:e,titleId:t,...n},r){return f.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true",ref:r,"aria-labelledby":t},n),e?f.createElement("title",{id:t},e):null,f.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3 4.5h14.25M3 9h9.75M3 13.5h5.25m5.25-.75L17.25 9m0 0L21 12.75M17.25 9v12"}))}const aK=f.forwardRef(sK),lK=aK;function cK({title:e,titleId:t,...n},r){return f.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true",ref:r,"aria-labelledby":t},n),e?f.createElement("title",{id:t},e):null,f.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15.042 21.672L13.684 16.6m0 0l-2.51 2.225.569-9.47 5.227 7.917-3.286-.672zM12 2.25V4.5m5.834.166l-1.591 1.591M20.25 10.5H18M7.757 14.743l-1.59 1.59M6 10.5H3.75m4.007-4.243l-1.59-1.59"}))}const uK=f.forwardRef(cK),dK=uK;function bi(e){return Array.isArray?Array.isArray(e):BP(e)==="[object Array]"}const fK=1/0;function pK(e){if(typeof e=="string")return e;let t=e+"";return t=="0"&&1/e==-fK?"-0":t}function hK(e){return e==null?"":pK(e)}function Lo(e){return typeof e=="string"}function jP(e){return typeof e=="number"}function mK(e){return e===!0||e===!1||gK(e)&&BP(e)=="[object Boolean]"}function zP(e){return typeof e=="object"}function gK(e){return zP(e)&&e!==null}function hr(e){return e!=null}function k0(e){return!e.trim().length}function BP(e){return e==null?e===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}const vK="Incorrect 'index' type",yK=e=>`Invalid value for key ${e}`,wK=e=>`Pattern length exceeds max of ${e}.`,xK=e=>`Missing ${e} property in key`,bK=e=>`Property 'weight' in key '${e}' must be a positive integer`,a2=Object.prototype.hasOwnProperty;class _K{constructor(t){this._keys=[],this._keyMap={};let n=0;t.forEach(r=>{let o=UP(r);this._keys.push(o),this._keyMap[o.id]=o,n+=o.weight}),this._keys.forEach(r=>{r.weight/=n})}get(t){return this._keyMap[t]}keys(){return this._keys}toJSON(){return JSON.stringify(this._keys)}}function UP(e){let t=null,n=null,r=null,o=1,i=null;if(Lo(e)||bi(e))r=e,t=l2(e),n=h1(e);else{if(!a2.call(e,"name"))throw new Error(xK("name"));const s=e.name;if(r=s,a2.call(e,"weight")&&(o=e.weight,o<=0))throw new Error(bK(s));t=l2(s),n=h1(s),i=e.getFn}return{path:t,id:n,weight:o,src:r,getFn:i}}function l2(e){return bi(e)?e:e.split(".")}function h1(e){return bi(e)?e.join("."):e}function SK(e,t){let n=[],r=!1;const o=(i,s,l)=>{if(hr(i))if(!s[l])n.push(i);else{let u=s[l];const d=i[u];if(!hr(d))return;if(l===s.length-1&&(Lo(d)||jP(d)||mK(d)))n.push(hK(d));else if(bi(d)){r=!0;for(let h=0,m=d.length;he.score===t.score?e.idx{this._keysMap[n.id]=r})}create(){this.isCreated||!this.docs.length||(this.isCreated=!0,Lo(this.docs[0])?this.docs.forEach((t,n)=>{this._addString(t,n)}):this.docs.forEach((t,n)=>{this._addObject(t,n)}),this.norm.clear())}add(t){const n=this.size();Lo(t)?this._addString(t,n):this._addObject(t,n)}removeAt(t){this.records.splice(t,1);for(let n=t,r=this.size();n{let s=o.getFn?o.getFn(t):this.getFn(t,o.path);if(hr(s)){if(bi(s)){let l=[];const u=[{nestedArrIndex:-1,value:s}];for(;u.length;){const{nestedArrIndex:d,value:h}=u.pop();if(hr(h))if(Lo(h)&&!k0(h)){let m={v:h,i:d,n:this.norm.get(h)};l.push(m)}else bi(h)&&h.forEach((m,g)=>{u.push({nestedArrIndex:g,value:m})})}r.$[i]=l}else if(Lo(s)&&!k0(s)){let l={v:s,n:this.norm.get(s)};r.$[i]=l}}}),this.records.push(r)}toJSON(){return{keys:this.keys,records:this.records}}}function VP(e,t,{getFn:n=He.getFn,fieldNormWeight:r=He.fieldNormWeight}={}){const o=new Nx({getFn:n,fieldNormWeight:r});return o.setKeys(e.map(UP)),o.setSources(t),o.create(),o}function PK(e,{getFn:t=He.getFn,fieldNormWeight:n=He.fieldNormWeight}={}){const{keys:r,records:o}=e,i=new Nx({getFn:t,fieldNormWeight:n});return i.setKeys(r),i.setIndexRecords(o),i}function pp(e,{errors:t=0,currentLocation:n=0,expectedLocation:r=0,distance:o=He.distance,ignoreLocation:i=He.ignoreLocation}={}){const s=t/e.length;if(i)return s;const l=Math.abs(r-n);return o?s+l/o:l?1:s}function AK(e=[],t=He.minMatchCharLength){let n=[],r=-1,o=-1,i=0;for(let s=e.length;i=t&&n.push([r,o]),r=-1)}return e[i-1]&&i-r>=t&&n.push([r,i-1]),n}const ea=32;function OK(e,t,n,{location:r=He.location,distance:o=He.distance,threshold:i=He.threshold,findAllMatches:s=He.findAllMatches,minMatchCharLength:l=He.minMatchCharLength,includeMatches:u=He.includeMatches,ignoreLocation:d=He.ignoreLocation}={}){if(t.length>ea)throw new Error(wK(ea));const h=t.length,m=e.length,g=Math.max(0,Math.min(r,m));let y=i,x=g;const _=l>1||u,C=_?Array(m):[];let S;for(;(S=e.indexOf(t,x))>-1;){let A=pp(t,{currentLocation:S,expectedLocation:g,distance:o,ignoreLocation:d});if(y=Math.min(A,y),x=S+h,_){let O=0;for(;O=V;U-=1){let te=U-1,L=n[e.charAt(te)];if(_&&(C[te]=+!!L),G[U]=(G[U+1]<<1|1)&L,A&&(G[U]|=(b[U+1]|b[U])<<1|1|b[U+1]),G[U]&P&&(E=pp(t,{errors:A,currentLocation:te,expectedLocation:g,distance:o,ignoreLocation:d}),E<=y)){if(y=E,x=te,x<=g)break;V=Math.max(1,2*g-x)}}if(pp(t,{errors:A+1,currentLocation:g,expectedLocation:g,distance:o,ignoreLocation:d})>y)break;b=G}const M={isMatch:x>=0,score:Math.max(.001,E)};if(_){const A=AK(C,l);A.length?u&&(M.indices=A):M.isMatch=!1}return M}function MK(e){let t={};for(let n=0,r=e.length;n{this.chunks.push({pattern:g,alphabet:MK(g),startIndex:y})},m=this.pattern.length;if(m>ea){let g=0;const y=m%ea,x=m-y;for(;g{const{isMatch:S,score:b,indices:E}=OK(t,x,_,{location:o+C,distance:i,threshold:s,findAllMatches:l,minMatchCharLength:u,includeMatches:r,ignoreLocation:d});S&&(g=!0),m+=b,S&&E&&(h=[...h,...E])});let y={isMatch:g,score:g?m/this.chunks.length:1};return g&&r&&(y.indices=h),y}}class Ds{constructor(t){this.pattern=t}static isMultiMatch(t){return c2(t,this.multiRegex)}static isSingleMatch(t){return c2(t,this.singleRegex)}search(){}}function c2(e,t){const n=e.match(t);return n?n[1]:null}class NK extends Ds{constructor(t){super(t)}static get type(){return"exact"}static get multiRegex(){return/^="(.*)"$/}static get singleRegex(){return/^=(.*)$/}search(t){const n=t===this.pattern;return{isMatch:n,score:n?0:1,indices:[0,this.pattern.length-1]}}}class DK extends Ds{constructor(t){super(t)}static get type(){return"inverse-exact"}static get multiRegex(){return/^!"(.*)"$/}static get singleRegex(){return/^!(.*)$/}search(t){const r=t.indexOf(this.pattern)===-1;return{isMatch:r,score:r?0:1,indices:[0,t.length-1]}}}class IK extends Ds{constructor(t){super(t)}static get type(){return"prefix-exact"}static get multiRegex(){return/^\^"(.*)"$/}static get singleRegex(){return/^\^(.*)$/}search(t){const n=t.startsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[0,this.pattern.length-1]}}}class LK extends Ds{constructor(t){super(t)}static get type(){return"inverse-prefix-exact"}static get multiRegex(){return/^!\^"(.*)"$/}static get singleRegex(){return/^!\^(.*)$/}search(t){const n=!t.startsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[0,t.length-1]}}}class FK extends Ds{constructor(t){super(t)}static get type(){return"suffix-exact"}static get multiRegex(){return/^"(.*)"\$$/}static get singleRegex(){return/^(.*)\$$/}search(t){const n=t.endsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[t.length-this.pattern.length,t.length-1]}}}class jK extends Ds{constructor(t){super(t)}static get type(){return"inverse-suffix-exact"}static get multiRegex(){return/^!"(.*)"\$$/}static get singleRegex(){return/^!(.*)\$$/}search(t){const n=!t.endsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[0,t.length-1]}}}class HP extends Ds{constructor(t,{location:n=He.location,threshold:r=He.threshold,distance:o=He.distance,includeMatches:i=He.includeMatches,findAllMatches:s=He.findAllMatches,minMatchCharLength:l=He.minMatchCharLength,isCaseSensitive:u=He.isCaseSensitive,ignoreLocation:d=He.ignoreLocation}={}){super(t),this._bitapSearch=new WP(t,{location:n,threshold:r,distance:o,includeMatches:i,findAllMatches:s,minMatchCharLength:l,isCaseSensitive:u,ignoreLocation:d})}static get type(){return"fuzzy"}static get multiRegex(){return/^"(.*)"$/}static get singleRegex(){return/^(.*)$/}search(t){return this._bitapSearch.searchIn(t)}}class KP extends Ds{constructor(t){super(t)}static get type(){return"include"}static get multiRegex(){return/^'"(.*)"$/}static get singleRegex(){return/^'(.*)$/}search(t){let n=0,r;const o=[],i=this.pattern.length;for(;(r=t.indexOf(this.pattern,n))>-1;)n=r+i,o.push([r,n-1]);const s=!!o.length;return{isMatch:s,score:s?0:1,indices:o}}}const m1=[NK,KP,IK,LK,jK,FK,DK,HP],u2=m1.length,zK=/ +(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/,BK="|";function UK(e,t={}){return e.split(BK).map(n=>{let r=n.trim().split(zK).filter(i=>i&&!!i.trim()),o=[];for(let i=0,s=r.length;i!!(e[jh.AND]||e[jh.OR]),KK=e=>!!e[y1.PATH],YK=e=>!bi(e)&&zP(e)&&!w1(e),d2=e=>({[jh.AND]:Object.keys(e).map(t=>({[t]:e[t]}))});function YP(e,t,{auto:n=!0}={}){const r=o=>{let i=Object.keys(o);const s=KK(o);if(!s&&i.length>1&&!w1(o))return r(d2(o));if(YK(o)){const u=s?o[y1.PATH]:i[0],d=s?o[y1.PATTERN]:o[u];if(!Lo(d))throw new Error(yK(u));const h={keyId:h1(u),pattern:d};return n&&(h.searcher=v1(d,t)),h}let l={children:[],operator:i[0]};return i.forEach(u=>{const d=o[u];bi(d)&&d.forEach(h=>{l.children.push(r(h))})}),l};return w1(e)||(e=d2(e)),r(e)}function GK(e,{ignoreFieldNorm:t=He.ignoreFieldNorm}){e.forEach(n=>{let r=1;n.matches.forEach(({key:o,norm:i,score:s})=>{const l=o?o.weight:null;r*=Math.pow(s===0&&l?Number.EPSILON:s,(l||1)*(t?1:i))}),n.score=r})}function XK(e,t){const n=e.matches;t.matches=[],hr(n)&&n.forEach(r=>{if(!hr(r.indices)||!r.indices.length)return;const{indices:o,value:i}=r;let s={indices:o,value:i};r.key&&(s.key=r.key.src),r.idx>-1&&(s.refIndex=r.idx),t.matches.push(s)})}function ZK(e,t){t.score=e.score}function qK(e,t,{includeMatches:n=He.includeMatches,includeScore:r=He.includeScore}={}){const o=[];return n&&o.push(XK),r&&o.push(ZK),e.map(i=>{const{idx:s}=i,l={item:t[s],refIndex:s};return o.length&&o.forEach(u=>{u(i,l)}),l})}class _c{constructor(t,n={},r){this.options={...He,...n},this.options.useExtendedSearch,this._keyStore=new _K(this.options.keys),this.setCollection(t,r)}setCollection(t,n){if(this._docs=t,n&&!(n instanceof Nx))throw new Error(vK);this._myIndex=n||VP(this.options.keys,this._docs,{getFn:this.options.getFn,fieldNormWeight:this.options.fieldNormWeight})}add(t){hr(t)&&(this._docs.push(t),this._myIndex.add(t))}remove(t=()=>!1){const n=[];for(let r=0,o=this._docs.length;r-1&&(u=u.slice(0,n)),qK(u,this._docs,{includeMatches:r,includeScore:o})}_searchStringList(t){const n=v1(t,this.options),{records:r}=this._myIndex,o=[];return r.forEach(({v:i,i:s,n:l})=>{if(!hr(i))return;const{isMatch:u,score:d,indices:h}=n.searchIn(i);u&&o.push({item:i,idx:s,matches:[{score:d,value:i,norm:l,indices:h}]})}),o}_searchLogical(t){const n=YP(t,this.options),r=(l,u,d)=>{if(!l.children){const{keyId:m,searcher:g}=l,y=this._findMatches({key:this._keyStore.get(m),value:this._myIndex.getValueForItemAtKeyId(u,m),searcher:g});return y&&y.length?[{idx:d,item:u,matches:y}]:[]}const h=[];for(let m=0,g=l.children.length;m{if(hr(l)){let d=r(n,l,u);d.length&&(i[u]||(i[u]={idx:u,item:l,matches:[]},s.push(i[u])),d.forEach(({matches:h})=>{i[u].matches.push(...h)}))}}),s}_searchObjectList(t){const n=v1(t,this.options),{keys:r,records:o}=this._myIndex,i=[];return o.forEach(({$:s,i:l})=>{if(!hr(s))return;let u=[];r.forEach((d,h)=>{u.push(...this._findMatches({key:d,value:s[h],searcher:n}))}),u.length&&i.push({idx:l,item:s,matches:u})}),i}_findMatches({key:t,value:n,searcher:r}){if(!hr(n))return[];let o=[];if(bi(n))n.forEach(({v:i,i:s,n:l})=>{if(!hr(i))return;const{isMatch:u,score:d,indices:h}=r.searchIn(i);u&&o.push({score:d,key:t,value:i,idx:s,norm:l,indices:h})});else{const{v:i,n:s}=n,{isMatch:l,score:u,indices:d}=r.searchIn(i);l&&o.push({score:u,key:t,value:i,norm:s,indices:d})}return o}}_c.version="7.0.0";_c.createIndex=VP;_c.parseIndex=PK;_c.config=He;_c.parseQuery=YP;HK(WK);function zd(e){const t=e+"CollectionProvider",[n,r]=An(t),[o,i]=n(t,{collectionRef:{current:null},itemMap:new Map}),s=y=>{const{scope:x,children:_}=y,C=Fe.useRef(null),S=Fe.useRef(new Map).current;return Fe.createElement(o,{scope:x,itemMap:S,collectionRef:C},_)},l=e+"CollectionSlot",u=Fe.forwardRef((y,x)=>{const{scope:_,children:C}=y,S=i(l,_),b=Be(x,S.collectionRef);return Fe.createElement(Wo,{ref:b},C)}),d=e+"CollectionItemSlot",h="data-radix-collection-item",m=Fe.forwardRef((y,x)=>{const{scope:_,children:C,...S}=y,b=Fe.useRef(null),E=Be(x,b),k=i(d,_);return Fe.useEffect(()=>(k.itemMap.set(b,{ref:b,...S}),()=>void k.itemMap.delete(b))),Fe.createElement(Wo,{[h]:"",ref:E},C)});function g(y){const x=i(e+"CollectionConsumer",y);return Fe.useCallback(()=>{const C=x.collectionRef.current;if(!C)return[];const S=Array.from(C.querySelectorAll(`[${h}]`));return Array.from(x.itemMap.values()).sort((k,P)=>S.indexOf(k.ref.current)-S.indexOf(P.ref.current))},[x.collectionRef,x.itemMap])}return[{Provider:s,Slot:u,ItemSlot:m},g,r]}const QK=f.createContext(void 0);function Sc(e){const t=f.useContext(QK);return e||t||"ltr"}const R0="rovingFocusGroup.onEntryFocus",JK={bubbles:!1,cancelable:!0},Dx="RovingFocusGroup",[x1,GP,eY]=zd(Dx),[tY,Qm]=An(Dx,[eY]),[nY,rY]=tY(Dx),oY=f.forwardRef((e,t)=>f.createElement(x1.Provider,{scope:e.__scopeRovingFocusGroup},f.createElement(x1.Slot,{scope:e.__scopeRovingFocusGroup},f.createElement(iY,Y({},e,{ref:t}))))),iY=f.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:o=!1,dir:i,currentTabStopId:s,defaultCurrentTabStopId:l,onCurrentTabStopIdChange:u,onEntryFocus:d,...h}=e,m=f.useRef(null),g=Be(t,m),y=Sc(i),[x=null,_]=Zr({prop:s,defaultProp:l,onChange:u}),[C,S]=f.useState(!1),b=Ft(d),E=GP(n),k=f.useRef(!1),[P,M]=f.useState(0);return f.useEffect(()=>{const A=m.current;if(A)return A.addEventListener(R0,b),()=>A.removeEventListener(R0,b)},[b]),f.createElement(nY,{scope:n,orientation:r,dir:y,loop:o,currentTabStopId:x,onItemFocus:f.useCallback(A=>_(A),[_]),onItemShiftTab:f.useCallback(()=>S(!0),[]),onFocusableItemAdd:f.useCallback(()=>M(A=>A+1),[]),onFocusableItemRemove:f.useCallback(()=>M(A=>A-1),[])},f.createElement(Pe.div,Y({tabIndex:C||P===0?-1:0,"data-orientation":r},h,{ref:g,style:{outline:"none",...e.style},onMouseDown:ue(e.onMouseDown,()=>{k.current=!0}),onFocus:ue(e.onFocus,A=>{const O=!k.current;if(A.target===A.currentTarget&&O&&!C){const F=new CustomEvent(R0,JK);if(A.currentTarget.dispatchEvent(F),!F.defaultPrevented){const V=E().filter(te=>te.focusable),J=V.find(te=>te.active),G=V.find(te=>te.id===x),U=[J,G,...V].filter(Boolean).map(te=>te.ref.current);XP(U)}}k.current=!1}),onBlur:ue(e.onBlur,()=>S(!1))})))}),sY="RovingFocusGroupItem",aY=f.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:o=!1,tabStopId:i,...s}=e,l=nr(),u=i||l,d=rY(sY,n),h=d.currentTabStopId===u,m=GP(n),{onFocusableItemAdd:g,onFocusableItemRemove:y}=d;return f.useEffect(()=>{if(r)return g(),()=>y()},[r,g,y]),f.createElement(x1.ItemSlot,{scope:n,id:u,focusable:r,active:o},f.createElement(Pe.span,Y({tabIndex:h?0:-1,"data-orientation":d.orientation},s,{ref:t,onMouseDown:ue(e.onMouseDown,x=>{r?d.onItemFocus(u):x.preventDefault()}),onFocus:ue(e.onFocus,()=>d.onItemFocus(u)),onKeyDown:ue(e.onKeyDown,x=>{if(x.key==="Tab"&&x.shiftKey){d.onItemShiftTab();return}if(x.target!==x.currentTarget)return;const _=uY(x,d.orientation,d.dir);if(_!==void 0){x.preventDefault();let S=m().filter(b=>b.focusable).map(b=>b.ref.current);if(_==="last")S.reverse();else if(_==="prev"||_==="next"){_==="prev"&&S.reverse();const b=S.indexOf(x.currentTarget);S=d.loop?dY(S,b+1):S.slice(b+1)}setTimeout(()=>XP(S))}})})))}),lY={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function cY(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function uY(e,t,n){const r=cY(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return lY[r]}function XP(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function dY(e,t){return e.map((n,r)=>e[(t+r)%e.length])}const ZP=oY,qP=aY,QP="Tabs",[fY,xte]=An(QP,[Qm]),JP=Qm(),[pY,Ix]=fY(QP),hY=f.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,onValueChange:o,defaultValue:i,orientation:s="horizontal",dir:l,activationMode:u="automatic",...d}=e,h=Sc(l),[m,g]=Zr({prop:r,onChange:o,defaultProp:i});return f.createElement(pY,{scope:n,baseId:nr(),value:m,onValueChange:g,orientation:s,dir:h,activationMode:u},f.createElement(Pe.div,Y({dir:h,"data-orientation":s},d,{ref:t})))}),mY="TabsList",gY=f.forwardRef((e,t)=>{const{__scopeTabs:n,loop:r=!0,...o}=e,i=Ix(mY,n),s=JP(n);return f.createElement(ZP,Y({asChild:!0},s,{orientation:i.orientation,dir:i.dir,loop:r}),f.createElement(Pe.div,Y({role:"tablist","aria-orientation":i.orientation},o,{ref:t})))}),vY="TabsTrigger",yY=f.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,disabled:o=!1,...i}=e,s=Ix(vY,n),l=JP(n),u=e5(s.baseId,r),d=t5(s.baseId,r),h=r===s.value;return f.createElement(qP,Y({asChild:!0},l,{focusable:!o,active:h}),f.createElement(Pe.button,Y({type:"button",role:"tab","aria-selected":h,"aria-controls":d,"data-state":h?"active":"inactive","data-disabled":o?"":void 0,disabled:o,id:u},i,{ref:t,onMouseDown:ue(e.onMouseDown,m=>{!o&&m.button===0&&m.ctrlKey===!1?s.onValueChange(r):m.preventDefault()}),onKeyDown:ue(e.onKeyDown,m=>{[" ","Enter"].includes(m.key)&&s.onValueChange(r)}),onFocus:ue(e.onFocus,()=>{const m=s.activationMode!=="manual";!h&&!o&&m&&s.onValueChange(r)})})))}),wY="TabsContent",xY=f.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,forceMount:o,children:i,...s}=e,l=Ix(wY,n),u=e5(l.baseId,r),d=t5(l.baseId,r),h=r===l.value,m=f.useRef(h);return f.useEffect(()=>{const g=requestAnimationFrame(()=>m.current=!1);return()=>cancelAnimationFrame(g)},[]),f.createElement(xn,{present:o||h},({present:g})=>f.createElement(Pe.div,Y({"data-state":h?"active":"inactive","data-orientation":l.orientation,role:"tabpanel","aria-labelledby":u,hidden:!g,id:d,tabIndex:0},s,{ref:t,style:{...e.style,animationDuration:m.current?"0s":void 0}}),g&&i))});function e5(e,t){return`${e}-trigger-${t}`}function t5(e,t){return`${e}-content-${t}`}const bY=hY,n5=gY,r5=yY,o5=xY,i5=bY,Lx=f.forwardRef(({className:e,...t},n)=>v.jsx(n5,{ref:n,className:Ce("inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground",e),tabIndex:-1,...t}));Lx.displayName=n5.displayName;const sa=f.forwardRef(({className:e,...t},n)=>v.jsx(r5,{ref:n,className:Ce("inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow",e),tabIndex:-1,...t}));sa.displayName=r5.displayName;const mu=f.forwardRef(({className:e,...t},n)=>v.jsx(o5,{ref:n,className:Ce("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",e),tabIndex:-1,...t}));mu.displayName=o5.displayName;function id(e,[t,n]){return Math.min(n,Math.max(t,e))}function Fx(e){const t=f.useRef({value:e,previous:e});return f.useMemo(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}const _Y=[" ","Enter","ArrowUp","ArrowDown"],SY=[" ","Enter"],Jm="Select",[eg,tg,EY]=zd(Jm),[Ec,bte]=An(Jm,[EY,Ns]),jx=Ns(),[CY,Oa]=Ec(Jm),[$Y,kY]=Ec(Jm),RY=e=>{const{__scopeSelect:t,children:n,open:r,defaultOpen:o,onOpenChange:i,value:s,defaultValue:l,onValueChange:u,dir:d,name:h,autoComplete:m,disabled:g,required:y}=e,x=jx(t),[_,C]=f.useState(null),[S,b]=f.useState(null),[E,k]=f.useState(!1),P=Sc(d),[M=!1,A]=Zr({prop:r,defaultProp:o,onChange:i}),[O,F]=Zr({prop:s,defaultProp:l,onChange:u}),V=f.useRef(null),J=_?!!_.closest("form"):!0,[G,ae]=f.useState(new Set),U=Array.from(G).map(te=>te.props.value).join(";");return f.createElement(Od,x,f.createElement(CY,{required:y,scope:t,trigger:_,onTriggerChange:C,valueNode:S,onValueNodeChange:b,valueNodeHasChildren:E,onValueNodeHasChildrenChange:k,contentId:nr(),value:O,onValueChange:F,open:M,onOpenChange:A,dir:P,triggerPointerDownPosRef:V,disabled:g},f.createElement(eg.Provider,{scope:t},f.createElement($Y,{scope:e.__scopeSelect,onNativeOptionAdd:f.useCallback(te=>{ae(L=>new Set(L).add(te))},[]),onNativeOptionRemove:f.useCallback(te=>{ae(L=>{const ie=new Set(L);return ie.delete(te),ie})},[])},n)),J?f.createElement(u5,{key:U,"aria-hidden":!0,required:y,tabIndex:-1,name:h,autoComplete:m,value:O,onChange:te=>F(te.target.value),disabled:g},O===void 0?f.createElement("option",{value:""}):null,Array.from(G)):null))},TY="SelectTrigger",PY=f.forwardRef((e,t)=>{const{__scopeSelect:n,disabled:r=!1,...o}=e,i=jx(n),s=Oa(TY,n),l=s.disabled||r,u=Be(t,s.onTriggerChange),d=tg(n),[h,m,g]=d5(x=>{const _=d().filter(b=>!b.disabled),C=_.find(b=>b.value===s.value),S=f5(_,x,C);S!==void 0&&s.onValueChange(S.value)}),y=()=>{l||(s.onOpenChange(!0),g())};return f.createElement(zm,Y({asChild:!0},i),f.createElement(Pe.button,Y({type:"button",role:"combobox","aria-controls":s.contentId,"aria-expanded":s.open,"aria-required":s.required,"aria-autocomplete":"none",dir:s.dir,"data-state":s.open?"open":"closed",disabled:l,"data-disabled":l?"":void 0,"data-placeholder":c5(s.value)?"":void 0},o,{ref:u,onClick:ue(o.onClick,x=>{x.currentTarget.focus()}),onPointerDown:ue(o.onPointerDown,x=>{const _=x.target;_.hasPointerCapture(x.pointerId)&&_.releasePointerCapture(x.pointerId),x.button===0&&x.ctrlKey===!1&&(y(),s.triggerPointerDownPosRef.current={x:Math.round(x.pageX),y:Math.round(x.pageY)},x.preventDefault())}),onKeyDown:ue(o.onKeyDown,x=>{const _=h.current!=="";!(x.ctrlKey||x.altKey||x.metaKey)&&x.key.length===1&&m(x.key),!(_&&x.key===" ")&&_Y.includes(x.key)&&(y(),x.preventDefault())})})))}),AY="SelectValue",OY=f.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,children:i,placeholder:s="",...l}=e,u=Oa(AY,n),{onValueNodeHasChildrenChange:d}=u,h=i!==void 0,m=Be(t,u.onValueNodeChange);return Pn(()=>{d(h)},[d,h]),f.createElement(Pe.span,Y({},l,{ref:m,style:{pointerEvents:"none"}}),c5(u.value)?f.createElement(f.Fragment,null,s):i)}),MY=f.forwardRef((e,t)=>{const{__scopeSelect:n,children:r,...o}=e;return f.createElement(Pe.span,Y({"aria-hidden":!0},o,{ref:t}),r||"▼")}),NY=e=>f.createElement(Md,Y({asChild:!0},e)),ic="SelectContent",DY=f.forwardRef((e,t)=>{const n=Oa(ic,e.__scopeSelect),[r,o]=f.useState();if(Pn(()=>{o(new DocumentFragment)},[]),!n.open){const i=r;return i?Os.createPortal(f.createElement(s5,{scope:e.__scopeSelect},f.createElement(eg.Slot,{scope:e.__scopeSelect},f.createElement("div",null,e.children))),i):null}return f.createElement(IY,Y({},e,{ref:t}))}),ai=10,[s5,Ma]=Ec(ic),IY=f.forwardRef((e,t)=>{const{__scopeSelect:n,position:r="item-aligned",onCloseAutoFocus:o,onEscapeKeyDown:i,onPointerDownOutside:s,side:l,sideOffset:u,align:d,alignOffset:h,arrowPadding:m,collisionBoundary:g,collisionPadding:y,sticky:x,hideWhenDetached:_,avoidCollisions:C,...S}=e,b=Oa(ic,n),[E,k]=f.useState(null),[P,M]=f.useState(null),A=Be(t,fe=>k(fe)),[O,F]=f.useState(null),[V,J]=f.useState(null),G=tg(n),[ae,U]=f.useState(!1),te=f.useRef(!1);f.useEffect(()=>{if(E)return Xm(E)},[E]),Km();const L=f.useCallback(fe=>{const[xe,...$e]=G().map(je=>je.ref.current),[Ae]=$e.slice(-1),Oe=document.activeElement;for(const je of fe)if(je===Oe||(je==null||je.scrollIntoView({block:"nearest"}),je===xe&&P&&(P.scrollTop=0),je===Ae&&P&&(P.scrollTop=P.scrollHeight),je==null||je.focus(),document.activeElement!==Oe))return},[G,P]),ie=f.useCallback(()=>L([O,E]),[L,O,E]);f.useEffect(()=>{ae&&ie()},[ae,ie]);const{onOpenChange:K,triggerPointerDownPosRef:Q}=b;f.useEffect(()=>{if(E){let fe={x:0,y:0};const xe=Ae=>{var Oe,je,Ot,ct;fe={x:Math.abs(Math.round(Ae.pageX)-((Oe=(je=Q.current)===null||je===void 0?void 0:je.x)!==null&&Oe!==void 0?Oe:0)),y:Math.abs(Math.round(Ae.pageY)-((Ot=(ct=Q.current)===null||ct===void 0?void 0:ct.y)!==null&&Ot!==void 0?Ot:0))}},$e=Ae=>{fe.x<=10&&fe.y<=10?Ae.preventDefault():E.contains(Ae.target)||K(!1),document.removeEventListener("pointermove",xe),Q.current=null};return Q.current!==null&&(document.addEventListener("pointermove",xe),document.addEventListener("pointerup",$e,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",xe),document.removeEventListener("pointerup",$e,{capture:!0})}}},[E,K,Q]),f.useEffect(()=>{const fe=()=>K(!1);return window.addEventListener("blur",fe),window.addEventListener("resize",fe),()=>{window.removeEventListener("blur",fe),window.removeEventListener("resize",fe)}},[K]);const[W,le]=d5(fe=>{const xe=G().filter(Oe=>!Oe.disabled),$e=xe.find(Oe=>Oe.ref.current===document.activeElement),Ae=f5(xe,fe,$e);Ae&&setTimeout(()=>Ae.ref.current.focus())}),ge=f.useCallback((fe,xe,$e)=>{const Ae=!te.current&&!$e;(b.value!==void 0&&b.value===xe||Ae)&&(F(fe),Ae&&(te.current=!0))},[b.value]),Ve=f.useCallback(()=>E==null?void 0:E.focus(),[E]),Ue=f.useCallback((fe,xe,$e)=>{const Ae=!te.current&&!$e;(b.value!==void 0&&b.value===xe||Ae)&&J(fe)},[b.value]),We=r==="popper"?f2:LY,Me=We===f2?{side:l,sideOffset:u,align:d,alignOffset:h,arrowPadding:m,collisionBoundary:g,collisionPadding:y,sticky:x,hideWhenDetached:_,avoidCollisions:C}:{};return f.createElement(s5,{scope:n,content:E,viewport:P,onViewportChange:M,itemRefCallback:ge,selectedItem:O,onItemLeave:Ve,itemTextRefCallback:Ue,focusSelectedItem:ie,selectedItemText:V,position:r,isPositioned:ae,searchRef:W},f.createElement(Gm,{as:Wo,allowPinchZoom:!0},f.createElement(Hm,{asChild:!0,trapped:b.open,onMountAutoFocus:fe=>{fe.preventDefault()},onUnmountAutoFocus:ue(o,fe=>{var xe;(xe=b.trigger)===null||xe===void 0||xe.focus({preventScroll:!0}),fe.preventDefault()})},f.createElement(yc,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:i,onPointerDownOutside:s,onFocusOutside:fe=>fe.preventDefault(),onDismiss:()=>b.onOpenChange(!1)},f.createElement(We,Y({role:"listbox",id:b.contentId,"data-state":b.open?"open":"closed",dir:b.dir,onContextMenu:fe=>fe.preventDefault()},S,Me,{onPlaced:()=>U(!0),ref:A,style:{display:"flex",flexDirection:"column",outline:"none",...S.style},onKeyDown:ue(S.onKeyDown,fe=>{const xe=fe.ctrlKey||fe.altKey||fe.metaKey;if(fe.key==="Tab"&&fe.preventDefault(),!xe&&fe.key.length===1&&le(fe.key),["ArrowUp","ArrowDown","Home","End"].includes(fe.key)){let Ae=G().filter(Oe=>!Oe.disabled).map(Oe=>Oe.ref.current);if(["ArrowUp","End"].includes(fe.key)&&(Ae=Ae.slice().reverse()),["ArrowUp","ArrowDown"].includes(fe.key)){const Oe=fe.target,je=Ae.indexOf(Oe);Ae=Ae.slice(je+1)}setTimeout(()=>L(Ae)),fe.preventDefault()}})}))))))}),LY=f.forwardRef((e,t)=>{const{__scopeSelect:n,onPlaced:r,...o}=e,i=Oa(ic,n),s=Ma(ic,n),[l,u]=f.useState(null),[d,h]=f.useState(null),m=Be(t,A=>h(A)),g=tg(n),y=f.useRef(!1),x=f.useRef(!0),{viewport:_,selectedItem:C,selectedItemText:S,focusSelectedItem:b}=s,E=f.useCallback(()=>{if(i.trigger&&i.valueNode&&l&&d&&_&&C&&S){const A=i.trigger.getBoundingClientRect(),O=d.getBoundingClientRect(),F=i.valueNode.getBoundingClientRect(),V=S.getBoundingClientRect();if(i.dir!=="rtl"){const Oe=V.left-O.left,je=F.left-Oe,Ot=A.left-je,ct=A.width+Ot,Yt=Math.max(ct,O.width),Er=window.innerWidth-ai,gt=id(je,[ai,Er-Yt]);l.style.minWidth=ct+"px",l.style.left=gt+"px"}else{const Oe=O.right-V.right,je=window.innerWidth-F.right-Oe,Ot=window.innerWidth-A.right-je,ct=A.width+Ot,Yt=Math.max(ct,O.width),Er=window.innerWidth-ai,gt=id(je,[ai,Er-Yt]);l.style.minWidth=ct+"px",l.style.right=gt+"px"}const J=g(),G=window.innerHeight-ai*2,ae=_.scrollHeight,U=window.getComputedStyle(d),te=parseInt(U.borderTopWidth,10),L=parseInt(U.paddingTop,10),ie=parseInt(U.borderBottomWidth,10),K=parseInt(U.paddingBottom,10),Q=te+L+ae+K+ie,W=Math.min(C.offsetHeight*5,Q),le=window.getComputedStyle(_),ge=parseInt(le.paddingTop,10),Ve=parseInt(le.paddingBottom,10),Ue=A.top+A.height/2-ai,We=G-Ue,Me=C.offsetHeight/2,fe=C.offsetTop+Me,xe=te+L+fe,$e=Q-xe;if(xe<=Ue){const Oe=C===J[J.length-1].ref.current;l.style.bottom="0px";const je=d.clientHeight-_.offsetTop-_.offsetHeight,Ot=Math.max(We,Me+(Oe?Ve:0)+je+ie),ct=xe+Ot;l.style.height=ct+"px"}else{const Oe=C===J[0].ref.current;l.style.top="0px";const Ot=Math.max(Ue,te+_.offsetTop+(Oe?ge:0)+Me)+$e;l.style.height=Ot+"px",_.scrollTop=xe-Ue+_.offsetTop}l.style.margin=`${ai}px 0`,l.style.minHeight=W+"px",l.style.maxHeight=G+"px",r==null||r(),requestAnimationFrame(()=>y.current=!0)}},[g,i.trigger,i.valueNode,l,d,_,C,S,i.dir,r]);Pn(()=>E(),[E]);const[k,P]=f.useState();Pn(()=>{d&&P(window.getComputedStyle(d).zIndex)},[d]);const M=f.useCallback(A=>{A&&x.current===!0&&(E(),b==null||b(),x.current=!1)},[E,b]);return f.createElement(FY,{scope:n,contentWrapper:l,shouldExpandOnScrollRef:y,onScrollButtonChange:M},f.createElement("div",{ref:u,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:k}},f.createElement(Pe.div,Y({},o,{ref:m,style:{boxSizing:"border-box",maxHeight:"100%",...o.style}}))))}),f2=f.forwardRef((e,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:o=ai,...i}=e,s=jx(n);return f.createElement(Bm,Y({},s,i,{ref:t,align:r,collisionPadding:o,style:{boxSizing:"border-box",...i.style,"--radix-select-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-select-content-available-width":"var(--radix-popper-available-width)","--radix-select-content-available-height":"var(--radix-popper-available-height)","--radix-select-trigger-width":"var(--radix-popper-anchor-width)","--radix-select-trigger-height":"var(--radix-popper-anchor-height)"}}))}),[FY,zx]=Ec(ic,{}),p2="SelectViewport",jY=f.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=Ma(p2,n),i=zx(p2,n),s=Be(t,o.onViewportChange),l=f.useRef(0);return f.createElement(f.Fragment,null,f.createElement("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"}}),f.createElement(eg.Slot,{scope:n},f.createElement(Pe.div,Y({"data-radix-select-viewport":"",role:"presentation"},r,{ref:s,style:{position:"relative",flex:1,overflow:"auto",...r.style},onScroll:ue(r.onScroll,u=>{const d=u.currentTarget,{contentWrapper:h,shouldExpandOnScrollRef:m}=i;if(m!=null&&m.current&&h){const g=Math.abs(l.current-d.scrollTop);if(g>0){const y=window.innerHeight-ai*2,x=parseFloat(h.style.minHeight),_=parseFloat(h.style.height),C=Math.max(x,_);if(C0?E:0,h.style.justifyContent="flex-end")}}}l.current=d.scrollTop})}))))}),zY="SelectGroup",[BY,UY]=Ec(zY),VY=f.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=nr();return f.createElement(BY,{scope:n,id:o},f.createElement(Pe.div,Y({role:"group","aria-labelledby":o},r,{ref:t})))}),WY="SelectLabel",HY=f.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=UY(WY,n);return f.createElement(Pe.div,Y({id:o.id},r,{ref:t}))}),b1="SelectItem",[KY,a5]=Ec(b1),YY=f.forwardRef((e,t)=>{const{__scopeSelect:n,value:r,disabled:o=!1,textValue:i,...s}=e,l=Oa(b1,n),u=Ma(b1,n),d=l.value===r,[h,m]=f.useState(i??""),[g,y]=f.useState(!1),x=Be(t,S=>{var b;return(b=u.itemRefCallback)===null||b===void 0?void 0:b.call(u,S,r,o)}),_=nr(),C=()=>{o||(l.onValueChange(r),l.onOpenChange(!1))};if(r==="")throw new Error("A must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.");return f.createElement(KY,{scope:n,value:r,disabled:o,textId:_,isSelected:d,onItemTextChange:f.useCallback(S=>{m(b=>{var E;return b||((E=S==null?void 0:S.textContent)!==null&&E!==void 0?E:"").trim()})},[])},f.createElement(eg.ItemSlot,{scope:n,value:r,disabled:o,textValue:h},f.createElement(Pe.div,Y({role:"option","aria-labelledby":_,"data-highlighted":g?"":void 0,"aria-selected":d&&g,"data-state":d?"checked":"unchecked","aria-disabled":o||void 0,"data-disabled":o?"":void 0,tabIndex:o?void 0:-1},s,{ref:x,onFocus:ue(s.onFocus,()=>y(!0)),onBlur:ue(s.onBlur,()=>y(!1)),onPointerUp:ue(s.onPointerUp,C),onPointerMove:ue(s.onPointerMove,S=>{if(o){var b;(b=u.onItemLeave)===null||b===void 0||b.call(u)}else S.currentTarget.focus({preventScroll:!0})}),onPointerLeave:ue(s.onPointerLeave,S=>{if(S.currentTarget===document.activeElement){var b;(b=u.onItemLeave)===null||b===void 0||b.call(u)}}),onKeyDown:ue(s.onKeyDown,S=>{var b;((b=u.searchRef)===null||b===void 0?void 0:b.current)!==""&&S.key===" "||(SY.includes(S.key)&&C(),S.key===" "&&S.preventDefault())})}))))}),hp="SelectItemText",GY=f.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,...i}=e,s=Oa(hp,n),l=Ma(hp,n),u=a5(hp,n),d=kY(hp,n),[h,m]=f.useState(null),g=Be(t,S=>m(S),u.onItemTextChange,S=>{var b;return(b=l.itemTextRefCallback)===null||b===void 0?void 0:b.call(l,S,u.value,u.disabled)}),y=h==null?void 0:h.textContent,x=f.useMemo(()=>f.createElement("option",{key:u.value,value:u.value,disabled:u.disabled},y),[u.disabled,u.value,y]),{onNativeOptionAdd:_,onNativeOptionRemove:C}=d;return Pn(()=>(_(x),()=>C(x)),[_,C,x]),f.createElement(f.Fragment,null,f.createElement(Pe.span,Y({id:u.textId},i,{ref:g})),u.isSelected&&s.valueNode&&!s.valueNodeHasChildren?Os.createPortal(i.children,s.valueNode):null)}),XY="SelectItemIndicator",ZY=f.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return a5(XY,n).isSelected?f.createElement(Pe.span,Y({"aria-hidden":!0},r,{ref:t})):null}),h2="SelectScrollUpButton",qY=f.forwardRef((e,t)=>{const n=Ma(h2,e.__scopeSelect),r=zx(h2,e.__scopeSelect),[o,i]=f.useState(!1),s=Be(t,r.onScrollButtonChange);return Pn(()=>{if(n.viewport&&n.isPositioned){let d=function(){const h=u.scrollTop>0;i(h)};var l=d;const u=n.viewport;return d(),u.addEventListener("scroll",d),()=>u.removeEventListener("scroll",d)}},[n.viewport,n.isPositioned]),o?f.createElement(l5,Y({},e,{ref:s,onAutoScroll:()=>{const{viewport:l,selectedItem:u}=n;l&&u&&(l.scrollTop=l.scrollTop-u.offsetHeight)}})):null}),m2="SelectScrollDownButton",QY=f.forwardRef((e,t)=>{const n=Ma(m2,e.__scopeSelect),r=zx(m2,e.__scopeSelect),[o,i]=f.useState(!1),s=Be(t,r.onScrollButtonChange);return Pn(()=>{if(n.viewport&&n.isPositioned){let d=function(){const h=u.scrollHeight-u.clientHeight,m=Math.ceil(u.scrollTop)u.removeEventListener("scroll",d)}},[n.viewport,n.isPositioned]),o?f.createElement(l5,Y({},e,{ref:s,onAutoScroll:()=>{const{viewport:l,selectedItem:u}=n;l&&u&&(l.scrollTop=l.scrollTop+u.offsetHeight)}})):null}),l5=f.forwardRef((e,t)=>{const{__scopeSelect:n,onAutoScroll:r,...o}=e,i=Ma("SelectScrollButton",n),s=f.useRef(null),l=tg(n),u=f.useCallback(()=>{s.current!==null&&(window.clearInterval(s.current),s.current=null)},[]);return f.useEffect(()=>()=>u(),[u]),Pn(()=>{var d;const h=l().find(m=>m.ref.current===document.activeElement);h==null||(d=h.ref.current)===null||d===void 0||d.scrollIntoView({block:"nearest"})},[l]),f.createElement(Pe.div,Y({"aria-hidden":!0},o,{ref:t,style:{flexShrink:0,...o.style},onPointerDown:ue(o.onPointerDown,()=>{s.current===null&&(s.current=window.setInterval(r,50))}),onPointerMove:ue(o.onPointerMove,()=>{var d;(d=i.onItemLeave)===null||d===void 0||d.call(i),s.current===null&&(s.current=window.setInterval(r,50))}),onPointerLeave:ue(o.onPointerLeave,()=>{u()})}))}),JY=f.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return f.createElement(Pe.div,Y({"aria-hidden":!0},r,{ref:t}))});function c5(e){return e===""||e===void 0}const u5=f.forwardRef((e,t)=>{const{value:n,...r}=e,o=f.useRef(null),i=Be(t,o),s=Fx(n);return f.useEffect(()=>{const l=o.current,u=window.HTMLSelectElement.prototype,h=Object.getOwnPropertyDescriptor(u,"value").set;if(s!==n&&h){const m=new Event("change",{bubbles:!0});h.call(l,n),l.dispatchEvent(m)}},[s,n]),f.createElement(Um,{asChild:!0},f.createElement("select",Y({},r,{ref:i,defaultValue:n})))});u5.displayName="BubbleSelect";function d5(e){const t=Ft(e),n=f.useRef(""),r=f.useRef(0),o=f.useCallback(s=>{const l=n.current+s;t(l),function u(d){n.current=d,window.clearTimeout(r.current),d!==""&&(r.current=window.setTimeout(()=>u(""),1e3))}(l)},[t]),i=f.useCallback(()=>{n.current="",window.clearTimeout(r.current)},[]);return f.useEffect(()=>()=>window.clearTimeout(r.current),[]),[n,o,i]}function f5(e,t,n){const o=t.length>1&&Array.from(t).every(d=>d===t[0])?t[0]:t,i=n?e.indexOf(n):-1;let s=eG(e,Math.max(i,0));o.length===1&&(s=s.filter(d=>d!==n));const u=s.find(d=>d.textValue.toLowerCase().startsWith(o.toLowerCase()));return u!==n?u:void 0}function eG(e,t){return e.map((n,r)=>e[(t+r)%e.length])}const tG=RY,p5=PY,nG=OY,rG=MY,oG=NY,h5=DY,iG=jY,sG=VY,m5=HY,g5=YY,aG=GY,lG=ZY,v5=qY,y5=QY,w5=JY,aa=tG,wl=sG,la=nG,ls=f.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(p5,{ref:r,className:Ce("flex h-9 w-full items-center justify-between whitespace-nowrap rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",e),tabIndex:-1,...n,children:[t,v.jsx(rG,{asChild:!0,children:v.jsx(Gj,{className:"h-4 w-4 opacity-50"})})]}));ls.displayName=p5.displayName;const x5=f.forwardRef(({className:e,...t},n)=>v.jsx(v5,{ref:n,className:Ce("flex cursor-default items-center justify-center py-1",e),...t,children:v.jsx(tz,{})}));x5.displayName=v5.displayName;const b5=f.forwardRef(({className:e,...t},n)=>v.jsx(y5,{ref:n,className:Ce("flex cursor-default items-center justify-center py-1",e),...t,children:v.jsx(qj,{})}));b5.displayName=y5.displayName;const cs=f.forwardRef(({className:e,children:t,position:n="popper",...r},o)=>v.jsx(oG,{children:v.jsxs(h5,{ref:o,className:Ce("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",n==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:n,onCloseAutoFocus:i=>i.preventDefault(),...r,children:[v.jsx(x5,{}),v.jsx(iG,{className:Ce("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),v.jsx(b5,{})]})}));cs.displayName=h5.displayName;const cG=f.forwardRef(({className:e,...t},n)=>v.jsx(m5,{ref:n,className:Ce("px-2 py-1.5 text-sm font-semibold",e),...t}));cG.displayName=m5.displayName;const us=f.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(g5,{ref:r,className:Ce("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-2 pr-8 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[v.jsx("span",{className:"absolute right-2 flex h-3.5 w-3.5 items-center justify-center",children:v.jsx(lG,{children:v.jsx(vT,{className:"h-4 w-4"})})}),v.jsx(aG,{children:t})]}));us.displayName=g5.displayName;const uG=f.forwardRef(({className:e,...t},n)=>v.jsx(w5,{ref:n,className:Ce("-mx-1 my-1 h-px bg-muted",e),...t}));uG.displayName=w5.displayName;function dG(e,t){return f.useReducer((n,r)=>{const o=t[n][r];return o??n},e)}const _5="ScrollArea",[S5,_te]=An(_5),[fG,qr]=S5(_5),pG=f.forwardRef((e,t)=>{const{__scopeScrollArea:n,type:r="hover",dir:o,scrollHideDelay:i=600,...s}=e,[l,u]=f.useState(null),[d,h]=f.useState(null),[m,g]=f.useState(null),[y,x]=f.useState(null),[_,C]=f.useState(null),[S,b]=f.useState(0),[E,k]=f.useState(0),[P,M]=f.useState(!1),[A,O]=f.useState(!1),F=Be(t,J=>u(J)),V=Sc(o);return f.createElement(fG,{scope:n,type:r,dir:V,scrollHideDelay:i,scrollArea:l,viewport:d,onViewportChange:h,content:m,onContentChange:g,scrollbarX:y,onScrollbarXChange:x,scrollbarXEnabled:P,onScrollbarXEnabledChange:M,scrollbarY:_,onScrollbarYChange:C,scrollbarYEnabled:A,onScrollbarYEnabledChange:O,onCornerWidthChange:b,onCornerHeightChange:k},f.createElement(Pe.div,Y({dir:V},s,{ref:F,style:{position:"relative","--radix-scroll-area-corner-width":S+"px","--radix-scroll-area-corner-height":E+"px",...e.style}})))}),hG="ScrollAreaViewport",mG=f.forwardRef((e,t)=>{const{__scopeScrollArea:n,children:r,...o}=e,i=qr(hG,n),s=f.useRef(null),l=Be(t,s,i.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(Pe.div,Y({"data-radix-scroll-area-viewport":""},o,{ref:l,style:{overflowX:i.scrollbarXEnabled?"scroll":"hidden",overflowY:i.scrollbarYEnabled?"scroll":"hidden",...e.style}}),f.createElement("div",{ref:i.onContentChange,style:{minWidth:"100%",display:"table"}},r)))}),$i="ScrollAreaScrollbar",E5=f.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=qr($i,e.__scopeScrollArea),{onScrollbarXEnabledChange:i,onScrollbarYEnabledChange:s}=o,l=e.orientation==="horizontal";return f.useEffect(()=>(l?i(!0):s(!0),()=>{l?i(!1):s(!1)}),[l,i,s]),o.type==="hover"?f.createElement(gG,Y({},r,{ref:t,forceMount:n})):o.type==="scroll"?f.createElement(vG,Y({},r,{ref:t,forceMount:n})):o.type==="auto"?f.createElement(C5,Y({},r,{ref:t,forceMount:n})):o.type==="always"?f.createElement(Bx,Y({},r,{ref:t})):null}),gG=f.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=qr($i,e.__scopeScrollArea),[i,s]=f.useState(!1);return f.useEffect(()=>{const l=o.scrollArea;let u=0;if(l){const d=()=>{window.clearTimeout(u),s(!0)},h=()=>{u=window.setTimeout(()=>s(!1),o.scrollHideDelay)};return l.addEventListener("pointerenter",d),l.addEventListener("pointerleave",h),()=>{window.clearTimeout(u),l.removeEventListener("pointerenter",d),l.removeEventListener("pointerleave",h)}}},[o.scrollArea,o.scrollHideDelay]),f.createElement(xn,{present:n||i},f.createElement(C5,Y({"data-state":i?"visible":"hidden"},r,{ref:t})))}),vG=f.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=qr($i,e.__scopeScrollArea),i=e.orientation==="horizontal",s=rg(()=>u("SCROLL_END"),100),[l,u]=dG("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(l==="idle"){const d=window.setTimeout(()=>u("HIDE"),o.scrollHideDelay);return()=>window.clearTimeout(d)}},[l,o.scrollHideDelay,u]),f.useEffect(()=>{const d=o.viewport,h=i?"scrollLeft":"scrollTop";if(d){let m=d[h];const g=()=>{const y=d[h];m!==y&&(u("SCROLL"),s()),m=y};return d.addEventListener("scroll",g),()=>d.removeEventListener("scroll",g)}},[o.viewport,i,u,s]),f.createElement(xn,{present:n||l!=="hidden"},f.createElement(Bx,Y({"data-state":l==="hidden"?"hidden":"visible"},r,{ref:t,onPointerEnter:ue(e.onPointerEnter,()=>u("POINTER_ENTER")),onPointerLeave:ue(e.onPointerLeave,()=>u("POINTER_LEAVE"))})))}),C5=f.forwardRef((e,t)=>{const n=qr($i,e.__scopeScrollArea),{forceMount:r,...o}=e,[i,s]=f.useState(!1),l=e.orientation==="horizontal",u=rg(()=>{if(n.viewport){const d=n.viewport.offsetWidth{const{orientation:n="vertical",...r}=e,o=qr($i,e.__scopeScrollArea),i=f.useRef(null),s=f.useRef(0),[l,u]=f.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),d=T5(l.viewport,l.content),h={...r,sizes:l,onSizesChange:u,hasThumb:d>0&&d<1,onThumbChange:g=>i.current=g,onThumbPointerUp:()=>s.current=0,onThumbPointerDown:g=>s.current=g};function m(g,y){return CG(g,s.current,l,y)}return n==="horizontal"?f.createElement(yG,Y({},h,{ref:t,onThumbPositionChange:()=>{if(o.viewport&&i.current){const g=o.viewport.scrollLeft,y=g2(g,l,o.dir);i.current.style.transform=`translate3d(${y}px, 0, 0)`}},onWheelScroll:g=>{o.viewport&&(o.viewport.scrollLeft=g)},onDragScroll:g=>{o.viewport&&(o.viewport.scrollLeft=m(g,o.dir))}})):n==="vertical"?f.createElement(wG,Y({},h,{ref:t,onThumbPositionChange:()=>{if(o.viewport&&i.current){const g=o.viewport.scrollTop,y=g2(g,l);i.current.style.transform=`translate3d(0, ${y}px, 0)`}},onWheelScroll:g=>{o.viewport&&(o.viewport.scrollTop=g)},onDragScroll:g=>{o.viewport&&(o.viewport.scrollTop=m(g))}})):null}),yG=f.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,i=qr($i,e.__scopeScrollArea),[s,l]=f.useState(),u=f.useRef(null),d=Be(t,u,i.onScrollbarXChange);return f.useEffect(()=>{u.current&&l(getComputedStyle(u.current))},[u]),f.createElement(k5,Y({"data-orientation":"horizontal"},o,{ref:d,sizes:n,style:{bottom:0,left:i.dir==="rtl"?"var(--radix-scroll-area-corner-width)":0,right:i.dir==="ltr"?"var(--radix-scroll-area-corner-width)":0,"--radix-scroll-area-thumb-width":ng(n)+"px",...e.style},onThumbPointerDown:h=>e.onThumbPointerDown(h.x),onDragScroll:h=>e.onDragScroll(h.x),onWheelScroll:(h,m)=>{if(i.viewport){const g=i.viewport.scrollLeft+h.deltaX;e.onWheelScroll(g),A5(g,m)&&h.preventDefault()}},onResize:()=>{u.current&&i.viewport&&s&&r({content:i.viewport.scrollWidth,viewport:i.viewport.offsetWidth,scrollbar:{size:u.current.clientWidth,paddingStart:zh(s.paddingLeft),paddingEnd:zh(s.paddingRight)}})}}))}),wG=f.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,i=qr($i,e.__scopeScrollArea),[s,l]=f.useState(),u=f.useRef(null),d=Be(t,u,i.onScrollbarYChange);return f.useEffect(()=>{u.current&&l(getComputedStyle(u.current))},[u]),f.createElement(k5,Y({"data-orientation":"vertical"},o,{ref:d,sizes:n,style:{top:0,right:i.dir==="ltr"?0:void 0,left:i.dir==="rtl"?0:void 0,bottom:"var(--radix-scroll-area-corner-height)","--radix-scroll-area-thumb-height":ng(n)+"px",...e.style},onThumbPointerDown:h=>e.onThumbPointerDown(h.y),onDragScroll:h=>e.onDragScroll(h.y),onWheelScroll:(h,m)=>{if(i.viewport){const g=i.viewport.scrollTop+h.deltaY;e.onWheelScroll(g),A5(g,m)&&h.preventDefault()}},onResize:()=>{u.current&&i.viewport&&s&&r({content:i.viewport.scrollHeight,viewport:i.viewport.offsetHeight,scrollbar:{size:u.current.clientHeight,paddingStart:zh(s.paddingTop),paddingEnd:zh(s.paddingBottom)}})}}))}),[xG,$5]=S5($i),k5=f.forwardRef((e,t)=>{const{__scopeScrollArea:n,sizes:r,hasThumb:o,onThumbChange:i,onThumbPointerUp:s,onThumbPointerDown:l,onThumbPositionChange:u,onDragScroll:d,onWheelScroll:h,onResize:m,...g}=e,y=qr($i,n),[x,_]=f.useState(null),C=Be(t,F=>_(F)),S=f.useRef(null),b=f.useRef(""),E=y.viewport,k=r.content-r.viewport,P=Ft(h),M=Ft(u),A=rg(m,10);function O(F){if(S.current){const V=F.clientX-S.current.left,J=F.clientY-S.current.top;d({x:V,y:J})}}return f.useEffect(()=>{const F=V=>{const J=V.target;(x==null?void 0:x.contains(J))&&P(V,k)};return document.addEventListener("wheel",F,{passive:!1}),()=>document.removeEventListener("wheel",F,{passive:!1})},[E,x,k,P]),f.useEffect(M,[r,M]),sc(x,A),sc(y.content,A),f.createElement(xG,{scope:n,scrollbar:x,hasThumb:o,onThumbChange:Ft(i),onThumbPointerUp:Ft(s),onThumbPositionChange:M,onThumbPointerDown:Ft(l)},f.createElement(Pe.div,Y({},g,{ref:C,style:{position:"absolute",...g.style},onPointerDown:ue(e.onPointerDown,F=>{F.button===0&&(F.target.setPointerCapture(F.pointerId),S.current=x.getBoundingClientRect(),b.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",y.viewport&&(y.viewport.style.scrollBehavior="auto"),O(F))}),onPointerMove:ue(e.onPointerMove,O),onPointerUp:ue(e.onPointerUp,F=>{const V=F.target;V.hasPointerCapture(F.pointerId)&&V.releasePointerCapture(F.pointerId),document.body.style.webkitUserSelect=b.current,y.viewport&&(y.viewport.style.scrollBehavior=""),S.current=null})})))}),_1="ScrollAreaThumb",bG=f.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=$5(_1,e.__scopeScrollArea);return f.createElement(xn,{present:n||o.hasThumb},f.createElement(_G,Y({ref:t},r)))}),_G=f.forwardRef((e,t)=>{const{__scopeScrollArea:n,style:r,...o}=e,i=qr(_1,n),s=$5(_1,n),{onThumbPositionChange:l}=s,u=Be(t,m=>s.onThumbChange(m)),d=f.useRef(),h=rg(()=>{d.current&&(d.current(),d.current=void 0)},100);return f.useEffect(()=>{const m=i.viewport;if(m){const g=()=>{if(h(),!d.current){const y=$G(m,l);d.current=y,l()}};return l(),m.addEventListener("scroll",g),()=>m.removeEventListener("scroll",g)}},[i.viewport,h,l]),f.createElement(Pe.div,Y({"data-state":s.hasThumb?"visible":"hidden"},o,{ref:u,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...r},onPointerDownCapture:ue(e.onPointerDownCapture,m=>{const y=m.target.getBoundingClientRect(),x=m.clientX-y.left,_=m.clientY-y.top;s.onThumbPointerDown({x,y:_})}),onPointerUp:ue(e.onPointerUp,s.onThumbPointerUp)}))}),R5="ScrollAreaCorner",SG=f.forwardRef((e,t)=>{const n=qr(R5,e.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?f.createElement(EG,Y({},e,{ref:t})):null}),EG=f.forwardRef((e,t)=>{const{__scopeScrollArea:n,...r}=e,o=qr(R5,n),[i,s]=f.useState(0),[l,u]=f.useState(0),d=!!(i&&l);return sc(o.scrollbarX,()=>{var h;const m=((h=o.scrollbarX)===null||h===void 0?void 0:h.offsetHeight)||0;o.onCornerHeightChange(m),u(m)}),sc(o.scrollbarY,()=>{var h;const m=((h=o.scrollbarY)===null||h===void 0?void 0:h.offsetWidth)||0;o.onCornerWidthChange(m),s(m)}),d?f.createElement(Pe.div,Y({},r,{ref:t,style:{width:i,height:l,position:"absolute",right:o.dir==="ltr"?0:void 0,left:o.dir==="rtl"?0:void 0,bottom:0,...e.style}})):null});function zh(e){return e?parseInt(e,10):0}function T5(e,t){const n=e/t;return isNaN(n)?0:n}function ng(e){const t=T5(e.viewport,e.content),n=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,r=(e.scrollbar.size-n)*t;return Math.max(r,18)}function CG(e,t,n,r="ltr"){const o=ng(n),i=o/2,s=t||i,l=o-s,u=n.scrollbar.paddingStart+s,d=n.scrollbar.size-n.scrollbar.paddingEnd-l,h=n.content-n.viewport,m=r==="ltr"?[0,h]:[h*-1,0];return P5([u,d],m)(e)}function g2(e,t,n="ltr"){const r=ng(t),o=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,i=t.scrollbar.size-o,s=t.content-t.viewport,l=i-r,u=n==="ltr"?[0,s]:[s*-1,0],d=id(e,u);return P5([0,s],[0,l])(d)}function P5(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 A5(e,t){return e>0&&e{})=>{let n={left:e.scrollLeft,top:e.scrollTop},r=0;return function o(){const i={left:e.scrollLeft,top:e.scrollTop},s=n.left!==i.left,l=n.top!==i.top;(s||l)&&t(),n=i,r=window.requestAnimationFrame(o)}(),()=>window.cancelAnimationFrame(r)};function rg(e,t){const n=Ft(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 sc(e,t){const n=Ft(t);Pn(()=>{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 O5=pG,kG=mG,RG=SG,og=f.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(O5,{ref:r,className:Ce("relative overflow-hidden",e),scrollHideDelay:400,...n,children:[v.jsx(kG,{className:"h-full w-full rounded-[inherit]",children:t}),v.jsx(M5,{}),v.jsx(RG,{})]}));og.displayName=O5.displayName;const M5=f.forwardRef(({className:e,orientation:t="vertical",...n},r)=>v.jsx(E5,{ref:r,orientation:t,className:Ce("flex touch-none select-none transition-colors",t==="vertical"&&"h-full w-2.5 border-l border-l-transparent p-[1px]",t==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",e),...n,children:v.jsx(bG,{className:"relative flex-1 rounded-full bg-border"})}));M5.displayName=E5.displayName;const N5="Name",D5="Created time",I5="Modified time",v2="input",TG="output",y2={[xs.NAME]:N5,[xs.CTIME]:D5,[xs.MTIME]:I5};function PG(e){const{onPhotoClick:t,photoWidth:n}=e,[r,o]=AP(!1),[i,s]=bt(V=>[V.fileManagerState,V.updateFileManagerState]),{toast:l}=Td(),[u,d]=f.useState(0),[h,m]=f.useState(0),g=f.useRef(null),y=lV(i.searchText,300),[x,_]=f.useState(v2),[C,S]=f.useState([]),[b,E]=f.useState([]),[k,P]=f.useState(0);Zn("f",()=>{o()}),Zn("left",()=>{let V=k;k>0&&(V=k-1),P(V),t(x,b[V].name)},[k,b]),Zn("right",()=>{let V=k;k{r||m(u)},[r,u]);const M=f.useCallback(V=>{V!==null&&r&&setTimeout(()=>{V.scrollTo({top:h,left:0})},100)},[r,h]);f.useEffect(()=>{(async()=>{try{const J=await Uj(x);S(J)}catch(J){l({variant:"destructive",title:"Uh oh! Something went wrong.",description:J.message?J.message:J.toString()})}})()},[x]),f.useEffect(()=>{if(!r)return;(async()=>{try{let J=C;y&&(J=new _c(J,{keys:["name"]}).search(y).map(te=>J[te.refIndex])),J=xH.orderBy(J,i.sortBy,i.sortOrder);const G=J.map(ae=>{const U=n,te=ae.height*(U/ae.width);return{src:`${Ms}/media_thumbnail_file?tab=${x}&filename=${encodeURIComponent(ae.name)}&width=${Math.ceil(U)}&height=${Math.ceil(te)}`,height:te,width:U,name:ae.name}});E(G)}catch(J){l({variant:"destructive",title:"Uh oh! Something went wrong.",description:J.message?J.message:J.toString()})}})()},[C,y,i,n,r]);const A=V=>{d(V.currentTarget.scrollTop)},O=({index:V})=>{o(),P(V),t(x,b[V].name)},F=()=>v.jsxs("div",{className:"flex justify-start items-center gap-[12px]",children:[v.jsx("div",{children:`Images (${b.length})`}),v.jsxs("div",{className:"flex",children:[v.jsx(vn,{tooltip:"Rows layout",onClick:()=>{s({layout:"rows"})},children:v.jsx(fz,{className:i.layout!=="rows"?"opacity-50":""})}),v.jsx(vn,{tooltip:"Grid layout",onClick:()=>{s({layout:"masonry"})},children:v.jsx(uz,{className:i.layout!=="masonry"?"opacity-50":""})})]})]});return v.jsxs(Zm,{open:r,onOpenChange:o,children:[v.jsx(uP,{asChild:!0,children:v.jsx(vn,{tooltip:"File Manager",children:v.jsx(QU,{})})}),v.jsxs(Fd,{className:"h-4/5 max-w-6xl",children:[v.jsx(jd,{children:F()}),v.jsxs("div",{className:"flex justify-between gap-8 items-center",children:[v.jsxs("div",{className:"flex relative justify-start items-center",children:[v.jsx(sz,{className:"absolute left-[8px]"}),v.jsx(Pd,{ref:g,value:i.searchText,className:"w-[250px] pl-[30px]",tabIndex:-1,onInput:V=>{V.preventDefault(),V.stopPropagation();const J=V.target;s({searchText:J.value})},placeholder:"Search by file name"})]}),v.jsx(i5,{defaultValue:x,onValueChange:V=>_(V),children:v.jsxs(Lx,{"aria-label":"Manage your account",children:[v.jsx(sa,{value:v2,children:"Image Directory"}),v.jsx(sa,{value:TG,children:"Output Directory"})]})}),v.jsx("div",{className:"flex gap-2",children:v.jsxs("div",{className:"flex gap-1",children:[v.jsxs(aa,{value:y2[i.sortBy],onValueChange:V=>{switch(V){case N5:s({sortBy:xs.NAME});break;case D5:s({sortBy:xs.CTIME});break;case I5:s({sortBy:xs.MTIME});break}},children:[v.jsx(ls,{className:"w-[140px]",children:v.jsx(la,{})}),v.jsx(cs,{children:Object.values(y2).map(V=>v.jsx(us,{value:V,children:V},V))})]}),i.sortOrder===$u.DESCENDING?v.jsx(vn,{tooltip:"Descending Order",onClick:()=>{s({sortOrder:$u.ASCENDING})},children:v.jsx(iK,{})}):v.jsx(vn,{tooltip:"Ascending Order",onClick:()=>{s({sortOrder:$u.DESCENDING})},children:v.jsx(lK,{})})]})})]}),v.jsx(og,{className:"w-full h-full rounded-md",onScroll:A,ref:M,children:v.jsx(nK,{layout:i.layout,photos:b,spacing:12,padding:0,onClick:O})})]})]})}var Bd=e=>e.type==="checkbox",xl=e=>e instanceof Date,Ln=e=>e==null;const L5=e=>typeof e=="object";var sn=e=>!Ln(e)&&!Array.isArray(e)&&L5(e)&&!xl(e),F5=e=>sn(e)&&e.target?Bd(e.target)?e.target.checked:e.target.value:e,AG=e=>e.substring(0,e.search(/\.\d+(\.|$)/))||e,j5=(e,t)=>e.has(AG(t)),OG=e=>{const t=e.constructor&&e.constructor.prototype;return sn(t)&&t.hasOwnProperty("isPrototypeOf")},Ux=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function so(e){let t;const n=Array.isArray(e);if(e instanceof Date)t=new Date(e);else if(e instanceof Set)t=new Set(e);else if(!(Ux&&(e instanceof Blob||e instanceof FileList))&&(n||sn(e)))if(t=n?[]:{},!n&&!OG(e))t=e;else for(const r in e)e.hasOwnProperty(r)&&(t[r]=so(e[r]));else return e;return t}var Ud=e=>Array.isArray(e)?e.filter(Boolean):[],Ht=e=>e===void 0,ve=(e,t,n)=>{if(!t||!sn(e))return n;const r=Ud(t.split(/[,[\].]+?/)).reduce((o,i)=>Ln(o)?o:o[i],e);return Ht(r)||r===e?Ht(e[t])?n:e[t]:r},No=e=>typeof e=="boolean";const Bh={BLUR:"blur",FOCUS_OUT:"focusout",CHANGE:"change"},mo={onBlur:"onBlur",onChange:"onChange",onSubmit:"onSubmit",onTouched:"onTouched",all:"all"},oi={max:"max",min:"min",maxLength:"maxLength",minLength:"minLength",pattern:"pattern",required:"required",validate:"validate"},z5=Fe.createContext(null),ig=()=>Fe.useContext(z5),MG=e=>{const{children:t,...n}=e;return Fe.createElement(z5.Provider,{value:n},t)};var B5=(e,t,n,r=!0)=>{const o={defaultValues:t._defaultValues};for(const i in e)Object.defineProperty(o,i,{get:()=>{const s=i;return t._proxyFormState[s]!==mo.all&&(t._proxyFormState[s]=!r||mo.all),n&&(n[s]=!0),e[s]}});return o},Fr=e=>sn(e)&&!Object.keys(e).length,U5=(e,t,n,r)=>{n(e);const{name:o,...i}=e;return Fr(i)||Object.keys(i).length>=Object.keys(t).length||Object.keys(i).find(s=>t[s]===(!r||mo.all))},Yp=e=>Array.isArray(e)?e:[e],V5=(e,t,n)=>!e||!t||e===t||Yp(e).some(r=>r&&(n?r===t:r.startsWith(t)||t.startsWith(r)));function Vx(e){const t=Fe.useRef(e);t.current=e,Fe.useEffect(()=>{const n=!e.disabled&&t.current.subject&&t.current.subject.subscribe({next:t.current.next});return()=>{n&&n.unsubscribe()}},[e.disabled])}function NG(e){const t=ig(),{control:n=t.control,disabled:r,name:o,exact:i}=e||{},[s,l]=Fe.useState(n._formState),u=Fe.useRef(!0),d=Fe.useRef({isDirty:!1,isLoading:!1,dirtyFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1}),h=Fe.useRef(o);return h.current=o,Vx({disabled:r,next:m=>u.current&&V5(h.current,m.name,i)&&U5(m,d.current,n._updateFormState)&&l({...n._formState,...m}),subject:n._subjects.state}),Fe.useEffect(()=>(u.current=!0,d.current.isValid&&n._updateValid(!0),()=>{u.current=!1}),[n]),B5(s,n,d.current,!1)}var Fo=e=>typeof e=="string",W5=(e,t,n,r,o)=>Fo(e)?(r&&t.watch.add(e),ve(n,e,o)):Array.isArray(e)?e.map(i=>(r&&t.watch.add(i),ve(n,i))):(r&&(t.watchAll=!0),n);function DG(e){const t=ig(),{control:n=t.control,name:r,defaultValue:o,disabled:i,exact:s}=e||{},l=Fe.useRef(r);l.current=r,Vx({disabled:i,subject:n._subjects.values,next:h=>{V5(l.current,h.name,s)&&d(so(W5(l.current,n._names,h.values||n._formValues,!1,o)))}});const[u,d]=Fe.useState(n._getWatch(r,o));return Fe.useEffect(()=>n._removeUnmounted()),u}var Wx=e=>/^\w*$/.test(e),H5=e=>Ud(e.replace(/["|']|\]/g,"").split(/\.|\[/));function wt(e,t,n){let r=-1;const o=Wx(t)?[t]:H5(t),i=o.length,s=i-1;for(;++r{const h=o._options.shouldUnregister||i,m=(g,y)=>{const x=ve(o._fields,g);x&&(x._f.mount=y)};if(m(n,!0),h){const g=so(ve(o._options.defaultValues,n));wt(o._defaultValues,n,g),Ht(ve(o._formValues,n))&&wt(o._formValues,n,g)}return()=>{(s?h&&!o._state.action:h)?o.unregister(n):m(n,!1)}},[n,o,s,i]),Fe.useEffect(()=>{ve(o._fields,n)&&o._updateDisabledField({disabled:r,fields:o._fields,name:n,value:ve(o._fields,n)._f.value})},[r,n,o]),{field:{name:n,value:l,...No(r)||No(u.disabled)?{disabled:u.disabled||r}:{},onChange:Fe.useCallback(h=>d.current.onChange({target:{value:F5(h),name:n},type:Bh.CHANGE}),[n]),onBlur:Fe.useCallback(()=>d.current.onBlur({target:{value:ve(o._formValues,n),name:n},type:Bh.BLUR}),[n,o]),ref:h=>{const m=ve(o._fields,n);m&&h&&(m._f.ref={focus:()=>h.focus(),select:()=>h.select(),setCustomValidity:g=>h.setCustomValidity(g),reportValidity:()=>h.reportValidity()})}},formState:u,fieldState:Object.defineProperties({},{invalid:{enumerable:!0,get:()=>!!ve(u.errors,n)},isDirty:{enumerable:!0,get:()=>!!ve(u.dirtyFields,n)},isTouched:{enumerable:!0,get:()=>!!ve(u.touchedFields,n)},error:{enumerable:!0,get:()=>ve(u.errors,n)}})}}const LG=e=>e.render(IG(e));var K5=(e,t,n,r,o)=>t?{...n[e],types:{...n[e]&&n[e].types?n[e].types:{},[r]:o||!0}}:{},w2=e=>({isOnSubmit:!e||e===mo.onSubmit,isOnBlur:e===mo.onBlur,isOnChange:e===mo.onChange,isOnAll:e===mo.all,isOnTouch:e===mo.onTouched}),x2=(e,t,n)=>!n&&(t.watchAll||t.watch.has(e)||[...t.watch].some(r=>e.startsWith(r)&&/^\.\w+/.test(e.slice(r.length))));const Gp=(e,t,n,r)=>{for(const o of n||Object.keys(e)){const i=ve(e,o);if(i){const{_f:s,...l}=i;if(s){if(s.refs&&s.refs[0]&&t(s.refs[0],o)&&!r)break;if(s.ref&&t(s.ref,s.name)&&!r)break}else sn(l)&&Gp(l,t)}}};var FG=(e,t,n)=>{const r=Ud(ve(e,n));return wt(r,"root",t[n]),wt(e,n,r),e},Hx=e=>e.type==="file",ds=e=>typeof e=="function",Uh=e=>{if(!Ux)return!1;const t=e?e.ownerDocument:0;return e instanceof(t&&t.defaultView?t.defaultView.HTMLElement:HTMLElement)},Xp=e=>Fo(e),Kx=e=>e.type==="radio",Vh=e=>e instanceof RegExp;const b2={value:!1,isValid:!1},_2={value:!0,isValid:!0};var Y5=e=>{if(Array.isArray(e)){if(e.length>1){const t=e.filter(n=>n&&n.checked&&!n.disabled).map(n=>n.value);return{value:t,isValid:!!t.length}}return e[0].checked&&!e[0].disabled?e[0].attributes&&!Ht(e[0].attributes.value)?Ht(e[0].value)||e[0].value===""?_2:{value:e[0].value,isValid:!0}:_2:b2}return b2};const S2={isValid:!1,value:null};var G5=e=>Array.isArray(e)?e.reduce((t,n)=>n&&n.checked&&!n.disabled?{isValid:!0,value:n.value}:t,S2):S2;function E2(e,t,n="validate"){if(Xp(e)||Array.isArray(e)&&e.every(Xp)||No(e)&&!e)return{type:n,message:Xp(e)?e:"",ref:t}}var el=e=>sn(e)&&!Vh(e)?e:{value:e,message:""},C2=async(e,t,n,r,o)=>{const{ref:i,refs:s,required:l,maxLength:u,minLength:d,min:h,max:m,pattern:g,validate:y,name:x,valueAsNumber:_,mount:C,disabled:S}=e._f,b=ve(t,x);if(!C||S)return{};const E=s?s[0]:i,k=G=>{r&&E.reportValidity&&(E.setCustomValidity(No(G)?"":G||""),E.reportValidity())},P={},M=Kx(i),A=Bd(i),O=M||A,F=(_||Hx(i))&&Ht(i.value)&&Ht(b)||Uh(i)&&i.value===""||b===""||Array.isArray(b)&&!b.length,V=K5.bind(null,x,n,P),J=(G,ae,U,te=oi.maxLength,L=oi.minLength)=>{const ie=G?ae:U;P[x]={type:G?te:L,message:ie,ref:i,...V(G?te:L,ie)}};if(o?!Array.isArray(b)||!b.length:l&&(!O&&(F||Ln(b))||No(b)&&!b||A&&!Y5(s).isValid||M&&!G5(s).isValid)){const{value:G,message:ae}=Xp(l)?{value:!!l,message:l}:el(l);if(G&&(P[x]={type:oi.required,message:ae,ref:E,...V(oi.required,ae)},!n))return k(ae),P}if(!F&&(!Ln(h)||!Ln(m))){let G,ae;const U=el(m),te=el(h);if(!Ln(b)&&!isNaN(b)){const L=i.valueAsNumber||b&&+b;Ln(U.value)||(G=L>U.value),Ln(te.value)||(ae=Lnew Date(new Date().toDateString()+" "+W),K=i.type=="time",Q=i.type=="week";Fo(U.value)&&b&&(G=K?ie(b)>ie(U.value):Q?b>U.value:L>new Date(U.value)),Fo(te.value)&&b&&(ae=K?ie(b)+G.value,te=!Ln(ae.value)&&b.length<+ae.value;if((U||te)&&(J(U,G.message,ae.message),!n))return k(P[x].message),P}if(g&&!F&&Fo(b)){const{value:G,message:ae}=el(g);if(Vh(G)&&!b.match(G)&&(P[x]={type:oi.pattern,message:ae,ref:i,...V(oi.pattern,ae)},!n))return k(ae),P}if(y){if(ds(y)){const G=await y(b,t),ae=E2(G,E);if(ae&&(P[x]={...ae,...V(oi.validate,ae.message)},!n))return k(ae.message),P}else if(sn(y)){let G={};for(const ae in y){if(!Fr(G)&&!n)break;const U=E2(await y[ae](b,t),E,ae);U&&(G={...U,...V(ae,U.message)},k(U.message),n&&(P[x]=G))}if(!Fr(G)&&(P[x]={ref:E,...G},!n))return P}}return k(!0),P};function jG(e,t){const n=t.slice(0,-1).length;let r=0;for(;r{for(const i of e)i.next&&i.next(o)},subscribe:o=>(e.push(o),{unsubscribe:()=>{e=e.filter(i=>i!==o)}}),unsubscribe:()=>{e=[]}}}var Wh=e=>Ln(e)||!L5(e);function ca(e,t){if(Wh(e)||Wh(t))return e===t;if(xl(e)&&xl(t))return e.getTime()===t.getTime();const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(const o of n){const i=e[o];if(!r.includes(o))return!1;if(o!=="ref"){const s=t[o];if(xl(i)&&xl(s)||sn(i)&&sn(s)||Array.isArray(i)&&Array.isArray(s)?!ca(i,s):i!==s)return!1}}return!0}var X5=e=>e.type==="select-multiple",BG=e=>Kx(e)||Bd(e),P0=e=>Uh(e)&&e.isConnected,Z5=e=>{for(const t in e)if(ds(e[t]))return!0;return!1};function Hh(e,t={}){const n=Array.isArray(e);if(sn(e)||n)for(const r in e)Array.isArray(e[r])||sn(e[r])&&!Z5(e[r])?(t[r]=Array.isArray(e[r])?[]:{},Hh(e[r],t[r])):Ln(e[r])||(t[r]=!0);return t}function q5(e,t,n){const r=Array.isArray(e);if(sn(e)||r)for(const o in e)Array.isArray(e[o])||sn(e[o])&&!Z5(e[o])?Ht(t)||Wh(n[o])?n[o]=Array.isArray(e[o])?Hh(e[o],[]):{...Hh(e[o])}:q5(e[o],Ln(t)?{}:t[o],n[o]):n[o]=!ca(e[o],t[o]);return n}var A0=(e,t)=>q5(e,t,Hh(t)),Q5=(e,{valueAsNumber:t,valueAsDate:n,setValueAs:r})=>Ht(e)?e:t?e===""?NaN:e&&+e:n&&Fo(e)?new Date(e):r?r(e):e;function O0(e){const t=e.ref;if(!(e.refs?e.refs.every(n=>n.disabled):t.disabled))return Hx(t)?t.files:Kx(t)?G5(e.refs).value:X5(t)?[...t.selectedOptions].map(({value:n})=>n):Bd(t)?Y5(e.refs).value:Q5(Ht(t.value)?e.ref.value:t.value,e)}var UG=(e,t,n,r)=>{const o={};for(const i of e){const s=ve(t,i);s&&wt(o,i,s._f)}return{criteriaMode:n,names:[...e],fields:o,shouldUseNativeValidation:r}},iu=e=>Ht(e)?e:Vh(e)?e.source:sn(e)?Vh(e.value)?e.value.source:e.value:e,VG=e=>e.mount&&(e.required||e.min||e.max||e.maxLength||e.minLength||e.pattern||e.validate);function $2(e,t,n){const r=ve(e,n);if(r||Wx(n))return{error:r,name:n};const o=n.split(".");for(;o.length;){const i=o.join("."),s=ve(t,i),l=ve(e,i);if(s&&!Array.isArray(s)&&n!==i)return{name:n};if(l&&l.type)return{name:i,error:l};o.pop()}return{name:n}}var WG=(e,t,n,r,o)=>o.isOnAll?!1:!n&&o.isOnTouch?!(t||e):(n?r.isOnBlur:o.isOnBlur)?!e:(n?r.isOnChange:o.isOnChange)?e:!0,HG=(e,t)=>!Ud(ve(e,t)).length&&hn(e,t);const KG={mode:mo.onSubmit,reValidateMode:mo.onChange,shouldFocusError:!0};function YG(e={},t){let n={...KG,...e},r={submitCount:0,isDirty:!1,isLoading:ds(n.defaultValues),isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},errors:{},disabled:!1},o={},i=sn(n.defaultValues)||sn(n.values)?so(n.defaultValues||n.values)||{}:{},s=n.shouldUnregister?{}:so(i),l={action:!1,mount:!1,watch:!1},u={mount:new Set,unMount:new Set,array:new Set,watch:new Set},d,h=0;const m={isDirty:!1,dirtyFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1},g={values:T0(),array:T0(),state:T0()},y=e.resetOptions&&e.resetOptions.keepDirtyValues,x=w2(n.mode),_=w2(n.reValidateMode),C=n.criteriaMode===mo.all,S=I=>X=>{clearTimeout(h),h=setTimeout(I,X)},b=async I=>{if(m.isValid||I){const X=n.resolver?Fr((await F()).errors):await J(o,!0);X!==r.isValid&&g.state.next({isValid:X})}},E=I=>m.isValidating&&g.state.next({isValidating:I}),k=(I,X=[],Z,we,he=!0,de=!0)=>{if(we&&Z){if(l.action=!0,de&&Array.isArray(ve(o,I))){const ke=Z(ve(o,I),we.argA,we.argB);he&&wt(o,I,ke)}if(de&&Array.isArray(ve(r.errors,I))){const ke=Z(ve(r.errors,I),we.argA,we.argB);he&&wt(r.errors,I,ke),HG(r.errors,I)}if(m.touchedFields&&de&&Array.isArray(ve(r.touchedFields,I))){const ke=Z(ve(r.touchedFields,I),we.argA,we.argB);he&&wt(r.touchedFields,I,ke)}m.dirtyFields&&(r.dirtyFields=A0(i,s)),g.state.next({name:I,isDirty:ae(I,X),dirtyFields:r.dirtyFields,errors:r.errors,isValid:r.isValid})}else wt(s,I,X)},P=(I,X)=>{wt(r.errors,I,X),g.state.next({errors:r.errors})},M=(I,X,Z,we)=>{const he=ve(o,I);if(he){const de=ve(s,I,Ht(Z)?ve(i,I):Z);Ht(de)||we&&we.defaultChecked||X?wt(s,I,X?de:O0(he._f)):L(I,de),l.mount&&b()}},A=(I,X,Z,we,he)=>{let de=!1,ke=!1;const ft={name:I};if(!Z||we){m.isDirty&&(ke=r.isDirty,r.isDirty=ft.isDirty=ae(),de=ke!==ft.isDirty);const pt=ca(ve(i,I),X);ke=ve(r.dirtyFields,I),pt?hn(r.dirtyFields,I):wt(r.dirtyFields,I,!0),ft.dirtyFields=r.dirtyFields,de=de||m.dirtyFields&&ke!==!pt}if(Z){const pt=ve(r.touchedFields,I);pt||(wt(r.touchedFields,I,Z),ft.touchedFields=r.touchedFields,de=de||m.touchedFields&&pt!==Z)}return de&&he&&g.state.next(ft),de?ft:{}},O=(I,X,Z,we)=>{const he=ve(r.errors,I),de=m.isValid&&No(X)&&r.isValid!==X;if(e.delayError&&Z?(d=S(()=>P(I,Z)),d(e.delayError)):(clearTimeout(h),d=null,Z?wt(r.errors,I,Z):hn(r.errors,I)),(Z?!ca(he,Z):he)||!Fr(we)||de){const ke={...we,...de&&No(X)?{isValid:X}:{},errors:r.errors,name:I};r={...r,...ke},g.state.next(ke)}E(!1)},F=async I=>n.resolver(s,n.context,UG(I||u.mount,o,n.criteriaMode,n.shouldUseNativeValidation)),V=async I=>{const{errors:X}=await F(I);if(I)for(const Z of I){const we=ve(X,Z);we?wt(r.errors,Z,we):hn(r.errors,Z)}else r.errors=X;return X},J=async(I,X,Z={valid:!0})=>{for(const we in I){const he=I[we];if(he){const{_f:de,...ke}=he;if(de){const ft=u.array.has(de.name),pt=await C2(he,s,C,n.shouldUseNativeValidation&&!X,ft);if(pt[de.name]&&(Z.valid=!1,X))break;!X&&(ve(pt,de.name)?ft?FG(r.errors,pt,de.name):wt(r.errors,de.name,pt[de.name]):hn(r.errors,de.name))}ke&&await J(ke,X,Z)}}return Z.valid},G=()=>{for(const I of u.unMount){const X=ve(o,I);X&&(X._f.refs?X._f.refs.every(Z=>!P0(Z)):!P0(X._f.ref))&&fe(I)}u.unMount=new Set},ae=(I,X)=>(I&&X&&wt(s,I,X),!ca(ge(),i)),U=(I,X,Z)=>W5(I,u,{...l.mount?s:Ht(X)?i:Fo(I)?{[I]:X}:X},Z,X),te=I=>Ud(ve(l.mount?s:i,I,e.shouldUnregister?ve(i,I,[]):[])),L=(I,X,Z={})=>{const we=ve(o,I);let he=X;if(we){const de=we._f;de&&(!de.disabled&&wt(s,I,Q5(X,de)),he=Uh(de.ref)&&Ln(X)?"":X,X5(de.ref)?[...de.ref.options].forEach(ke=>ke.selected=he.includes(ke.value)):de.refs?Bd(de.ref)?de.refs.length>1?de.refs.forEach(ke=>(!ke.defaultChecked||!ke.disabled)&&(ke.checked=Array.isArray(he)?!!he.find(ft=>ft===ke.value):he===ke.value)):de.refs[0]&&(de.refs[0].checked=!!he):de.refs.forEach(ke=>ke.checked=ke.value===he):Hx(de.ref)?de.ref.value="":(de.ref.value=he,de.ref.type||g.values.next({name:I,values:{...s}})))}(Z.shouldDirty||Z.shouldTouch)&&A(I,he,Z.shouldTouch,Z.shouldDirty,!0),Z.shouldValidate&&le(I)},ie=(I,X,Z)=>{for(const we in X){const he=X[we],de=`${I}.${we}`,ke=ve(o,de);(u.array.has(I)||!Wh(he)||ke&&!ke._f)&&!xl(he)?ie(de,he,Z):L(de,he,Z)}},K=(I,X,Z={})=>{const we=ve(o,I),he=u.array.has(I),de=so(X);wt(s,I,de),he?(g.array.next({name:I,values:{...s}}),(m.isDirty||m.dirtyFields)&&Z.shouldDirty&&g.state.next({name:I,dirtyFields:A0(i,s),isDirty:ae(I,de)})):we&&!we._f&&!Ln(de)?ie(I,de,Z):L(I,de,Z),x2(I,u)&&g.state.next({...r}),g.values.next({name:I,values:{...s}}),!l.mount&&t()},Q=async I=>{const X=I.target;let Z=X.name,we=!0;const he=ve(o,Z),de=()=>X.type?O0(he._f):F5(I),ke=ft=>{we=Number.isNaN(ft)||ft===ve(s,Z,ft)};if(he){let ft,pt;const bn=de(),Cr=I.type===Bh.BLUR||I.type===Bh.FOCUS_OUT,ki=!VG(he._f)&&!n.resolver&&!ve(r.errors,Z)&&!he._f.deps||WG(Cr,ve(r.touchedFields,Z),r.isSubmitted,_,x),_o=x2(Z,u,Cr);wt(s,Z,bn),Cr?(he._f.onBlur&&he._f.onBlur(I),d&&d(0)):he._f.onChange&&he._f.onChange(I);const Vn=A(Z,bn,Cr,!1),Da=!Fr(Vn)||_o;if(!Cr&&g.values.next({name:Z,type:I.type,values:{...s}}),ki)return m.isValid&&b(),Da&&g.state.next({name:Z,..._o?{}:Vn});if(!Cr&&_o&&g.state.next({...r}),E(!0),n.resolver){const{errors:Ri}=await F([Z]);if(ke(bn),we){const zs=$2(r.errors,o,Z),Ti=$2(Ri,o,zs.name||Z);ft=Ti.error,Z=Ti.name,pt=Fr(Ri)}}else ft=(await C2(he,s,C,n.shouldUseNativeValidation))[Z],ke(bn),we&&(ft?pt=!1:m.isValid&&(pt=await J(o,!0)));we&&(he._f.deps&&le(he._f.deps),O(Z,pt,ft,Vn))}},W=(I,X)=>{if(ve(r.errors,X)&&I.focus)return I.focus(),1},le=async(I,X={})=>{let Z,we;const he=Yp(I);if(E(!0),n.resolver){const de=await V(Ht(I)?I:he);Z=Fr(de),we=I?!he.some(ke=>ve(de,ke)):Z}else I?(we=(await Promise.all(he.map(async de=>{const ke=ve(o,de);return await J(ke&&ke._f?{[de]:ke}:ke)}))).every(Boolean),!(!we&&!r.isValid)&&b()):we=Z=await J(o);return g.state.next({...!Fo(I)||m.isValid&&Z!==r.isValid?{}:{name:I},...n.resolver||!I?{isValid:Z}:{},errors:r.errors,isValidating:!1}),X.shouldFocus&&!we&&Gp(o,W,I?he:u.mount),we},ge=I=>{const X={...i,...l.mount?s:{}};return Ht(I)?X:Fo(I)?ve(X,I):I.map(Z=>ve(X,Z))},Ve=(I,X)=>({invalid:!!ve((X||r).errors,I),isDirty:!!ve((X||r).dirtyFields,I),isTouched:!!ve((X||r).touchedFields,I),error:ve((X||r).errors,I)}),Ue=I=>{I&&Yp(I).forEach(X=>hn(r.errors,X)),g.state.next({errors:I?r.errors:{}})},We=(I,X,Z)=>{const we=(ve(o,I,{_f:{}})._f||{}).ref;wt(r.errors,I,{...X,ref:we}),g.state.next({name:I,errors:r.errors,isValid:!1}),Z&&Z.shouldFocus&&we&&we.focus&&we.focus()},Me=(I,X)=>ds(I)?g.values.subscribe({next:Z=>I(U(void 0,X),Z)}):U(I,X,!0),fe=(I,X={})=>{for(const Z of I?Yp(I):u.mount)u.mount.delete(Z),u.array.delete(Z),X.keepValue||(hn(o,Z),hn(s,Z)),!X.keepError&&hn(r.errors,Z),!X.keepDirty&&hn(r.dirtyFields,Z),!X.keepTouched&&hn(r.touchedFields,Z),!n.shouldUnregister&&!X.keepDefaultValue&&hn(i,Z);g.values.next({values:{...s}}),g.state.next({...r,...X.keepDirty?{isDirty:ae()}:{}}),!X.keepIsValid&&b()},xe=({disabled:I,name:X,field:Z,fields:we,value:he})=>{if(No(I)){const de=I?void 0:Ht(he)?O0(Z?Z._f:ve(we,X)._f):he;wt(s,X,de),A(X,de,!1,!1,!0)}},$e=(I,X={})=>{let Z=ve(o,I);const we=No(X.disabled);return wt(o,I,{...Z||{},_f:{...Z&&Z._f?Z._f:{ref:{name:I}},name:I,mount:!0,...X}}),u.mount.add(I),Z?xe({field:Z,disabled:X.disabled,name:I}):M(I,!0,X.value),{...we?{disabled:X.disabled}:{},...n.progressive?{required:!!X.required,min:iu(X.min),max:iu(X.max),minLength:iu(X.minLength),maxLength:iu(X.maxLength),pattern:iu(X.pattern)}:{},name:I,onChange:Q,onBlur:Q,ref:he=>{if(he){$e(I,X),Z=ve(o,I);const de=Ht(he.value)&&he.querySelectorAll&&he.querySelectorAll("input,select,textarea")[0]||he,ke=BG(de),ft=Z._f.refs||[];if(ke?ft.find(pt=>pt===de):de===Z._f.ref)return;wt(o,I,{_f:{...Z._f,...ke?{refs:[...ft.filter(P0),de,...Array.isArray(ve(i,I))?[{}]:[]],ref:{type:de.type,name:I}}:{ref:de}}}),M(I,!1,void 0,de)}else Z=ve(o,I,{}),Z._f&&(Z._f.mount=!1),(n.shouldUnregister||X.shouldUnregister)&&!(j5(u.array,I)&&l.action)&&u.unMount.add(I)}}},Ae=()=>n.shouldFocusError&&Gp(o,W,u.mount),Oe=I=>{No(I)&&(g.state.next({disabled:I}),Gp(o,X=>{X.disabled=I},0,!1))},je=(I,X)=>async Z=>{Z&&(Z.preventDefault&&Z.preventDefault(),Z.persist&&Z.persist());let we=so(s);if(g.state.next({isSubmitting:!0}),n.resolver){const{errors:he,values:de}=await F();r.errors=he,we=de}else await J(o);hn(r.errors,"root"),Fr(r.errors)?(g.state.next({errors:{}}),await I(we,Z)):(X&&await X({...r.errors},Z),Ae(),setTimeout(Ae)),g.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:Fr(r.errors),submitCount:r.submitCount+1,errors:r.errors})},Ot=(I,X={})=>{ve(o,I)&&(Ht(X.defaultValue)?K(I,ve(i,I)):(K(I,X.defaultValue),wt(i,I,X.defaultValue)),X.keepTouched||hn(r.touchedFields,I),X.keepDirty||(hn(r.dirtyFields,I),r.isDirty=X.defaultValue?ae(I,ve(i,I)):ae()),X.keepError||(hn(r.errors,I),m.isValid&&b()),g.state.next({...r}))},ct=(I,X={})=>{const Z=I?so(I):i,we=so(Z),he=I&&!Fr(I)?we:i;if(X.keepDefaultValues||(i=Z),!X.keepValues){if(X.keepDirtyValues||y)for(const de of u.mount)ve(r.dirtyFields,de)?wt(he,de,ve(s,de)):K(de,ve(he,de));else{if(Ux&&Ht(I))for(const de of u.mount){const ke=ve(o,de);if(ke&&ke._f){const ft=Array.isArray(ke._f.refs)?ke._f.refs[0]:ke._f.ref;if(Uh(ft)){const pt=ft.closest("form");if(pt){pt.reset();break}}}}o={}}s=e.shouldUnregister?X.keepDefaultValues?so(i):{}:so(he),g.array.next({values:{...he}}),g.values.next({values:{...he}})}u={mount:new Set,unMount:new Set,array:new Set,watch:new Set,watchAll:!1,focus:""},!l.mount&&t(),l.mount=!m.isValid||!!X.keepIsValid,l.watch=!!e.shouldUnregister,g.state.next({submitCount:X.keepSubmitCount?r.submitCount:0,isDirty:X.keepDirty?r.isDirty:!!(X.keepDefaultValues&&!ca(I,i)),isSubmitted:X.keepIsSubmitted?r.isSubmitted:!1,dirtyFields:X.keepDirtyValues?r.dirtyFields:X.keepDefaultValues&&I?A0(i,I):{},touchedFields:X.keepTouched?r.touchedFields:{},errors:X.keepErrors?r.errors:{},isSubmitSuccessful:X.keepIsSubmitSuccessful?r.isSubmitSuccessful:!1,isSubmitting:!1})},Yt=(I,X)=>ct(ds(I)?I(s):I,X);return{control:{register:$e,unregister:fe,getFieldState:Ve,handleSubmit:je,setError:We,_executeSchema:F,_getWatch:U,_getDirty:ae,_updateValid:b,_removeUnmounted:G,_updateFieldArray:k,_updateDisabledField:xe,_getFieldArray:te,_reset:ct,_resetDefaultValues:()=>ds(n.defaultValues)&&n.defaultValues().then(I=>{Yt(I,n.resetOptions),g.state.next({isLoading:!1})}),_updateFormState:I=>{r={...r,...I}},_disableForm:Oe,_subjects:g,_proxyFormState:m,get _fields(){return o},get _formValues(){return s},get _state(){return l},set _state(I){l=I},get _defaultValues(){return i},get _names(){return u},set _names(I){u=I},get _formState(){return r},set _formState(I){r=I},get _options(){return n},set _options(I){n={...n,...I}}},trigger:le,register:$e,handleSubmit:je,watch:Me,setValue:K,getValues:ge,reset:Yt,resetField:Ot,clearErrors:Ue,unregister:fe,setError:We,setFocus:(I,X={})=>{const Z=ve(o,I),we=Z&&Z._f;if(we){const he=we.refs?we.refs[0]:we.ref;he.focus&&(he.focus(),X.shouldSelect&&he.select())}},getFieldState:Ve}}function GG(e={}){const t=Fe.useRef(),n=Fe.useRef(),[r,o]=Fe.useState({isDirty:!1,isValidating:!1,isLoading:ds(e.defaultValues),isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,submitCount:0,dirtyFields:{},touchedFields:{},errors:{},disabled:!1,defaultValues:ds(e.defaultValues)?void 0:e.defaultValues});t.current||(t.current={...YG(e,()=>o(s=>({...s}))),formState:r});const i=t.current.control;return i._options=e,Vx({subject:i._subjects.state,next:s=>{U5(s,i._proxyFormState,i._updateFormState,!0)&&o({...i._formState})}}),Fe.useEffect(()=>i._disableForm(e.disabled),[i,e.disabled]),Fe.useEffect(()=>{if(i._proxyFormState.isDirty){const s=i._getDirty();s!==r.isDirty&&i._subjects.state.next({isDirty:s})}},[i,r.isDirty]),Fe.useEffect(()=>{e.values&&!ca(e.values,n.current)?(i._reset(e.values,i._options.resetOptions),n.current=e.values):i._resetDefaultValues()},[e.values,i]),Fe.useEffect(()=>{i._state.mount||(i._updateValid(),i._state.mount=!0),i._state.watch&&(i._state.watch=!1,i._subjects.state.next({...i._formState})),i._removeUnmounted()}),t.current.formState=B5(r,i),t.current}var k2=function(e,t,n){if(e&&"reportValidity"in e){var r=ve(n,t);e.setCustomValidity(r&&r.message||""),e.reportValidity()}},J5=function(e,t){var n=function(o){var i=t.fields[o];i&&i.ref&&"reportValidity"in i.ref?k2(i.ref,o,e):i.refs&&i.refs.forEach(function(s){return k2(s,o,e)})};for(var r in t.fields)n(r)},XG=function(e,t){t.shouldUseNativeValidation&&J5(e,t);var n={};for(var r in e){var o=ve(t.fields,r),i=Object.assign(e[r]||{},{ref:o&&o.ref});if(qG(t.names||Object.keys(e),r)){var s=Object.assign({},ZG(ve(n,r)));wt(s,"root",i),wt(n,r,s)}else wt(n,r,i)}return n},ZG=function(e){return Array.isArray(e)?e.filter(Boolean):[]},qG=function(e,t){return e.some(function(n){return n.startsWith(t+".")})},QG=function(e,t){for(var n={};e.length;){var r=e[0],o=r.code,i=r.message,s=r.path.join(".");if(!n[s])if("unionErrors"in r){var l=r.unionErrors[0].errors[0];n[s]={message:l.message,type:l.code}}else n[s]={message:i,type:o};if("unionErrors"in r&&r.unionErrors.forEach(function(h){return h.errors.forEach(function(m){return e.push(m)})}),t){var u=n[s].types,d=u&&u[r.code];n[s]=K5(s,t,n,o,d?[].concat(d,r.message):r.message)}e.shift()}return n},JG=function(e,t,n){return n===void 0&&(n={}),function(r,o,i){try{return Promise.resolve(function(s,l){try{var u=Promise.resolve(e[n.mode==="sync"?"parse":"parseAsync"](r,t)).then(function(d){return i.shouldUseNativeValidation&&J5({},i),{errors:{},values:n.raw?r:d}})}catch(d){return l(d)}return u&&u.then?u.then(void 0,l):u}(0,function(s){if(function(l){return l.errors!=null}(s))return{values:{},errors:XG(QG(s.errors,!i.shouldUseNativeValidation&&i.criteriaMode==="all"),i)};throw s}))}catch(s){return Promise.reject(s)}}},mt;(function(e){e.assertEqual=o=>o;function t(o){}e.assertIs=t;function n(o){throw new Error}e.assertNever=n,e.arrayToEnum=o=>{const i={};for(const s of o)i[s]=s;return i},e.getValidEnumValues=o=>{const i=e.objectKeys(o).filter(l=>typeof o[o[l]]!="number"),s={};for(const l of i)s[l]=o[l];return e.objectValues(s)},e.objectValues=o=>e.objectKeys(o).map(function(i){return o[i]}),e.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{const i=[];for(const s in o)Object.prototype.hasOwnProperty.call(o,s)&&i.push(s);return i},e.find=(o,i)=>{for(const s of o)if(i(s))return s},e.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&isFinite(o)&&Math.floor(o)===o;function r(o,i=" | "){return o.map(s=>typeof s=="string"?`'${s}'`:s).join(i)}e.joinValues=r,e.jsonStringifyReplacer=(o,i)=>typeof i=="bigint"?i.toString():i})(mt||(mt={}));var R2;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(R2||(R2={}));const be=mt.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ta=e=>{switch(typeof e){case"undefined":return be.undefined;case"string":return be.string;case"number":return isNaN(e)?be.nan:be.number;case"boolean":return be.boolean;case"function":return be.function;case"bigint":return be.bigint;case"symbol":return be.symbol;case"object":return Array.isArray(e)?be.array:e===null?be.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?be.promise:typeof Map<"u"&&e instanceof Map?be.map:typeof Set<"u"&&e instanceof Set?be.set:typeof Date<"u"&&e instanceof Date?be.date:be.object;default:return be.unknown}},pe=mt.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"]);class Bo 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(i){return i.message},r={_errors:[]},o=i=>{for(const s of i.issues)if(s.code==="invalid_union")s.unionErrors.map(o);else if(s.code==="invalid_return_type")o(s.returnTypeError);else if(s.code==="invalid_arguments")o(s.argumentsError);else if(s.path.length===0)r._errors.push(n(s));else{let l=r,u=0;for(;un.message){const n={},r=[];for(const o of this.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(t(o))):r.push(t(o));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}}Bo.create=e=>new Bo(e);const Kh=(e,t)=>{let n;switch(e.code){case pe.invalid_type:e.received===be.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case pe.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,mt.jsonStringifyReplacer)}`;break;case pe.unrecognized_keys:n=`Unrecognized key(s) in object: ${mt.joinValues(e.keys,", ")}`;break;case pe.invalid_union:n="Invalid input";break;case pe.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${mt.joinValues(e.options)}`;break;case pe.invalid_enum_value:n=`Invalid enum value. Expected ${mt.joinValues(e.options)}, received '${e.received}'`;break;case pe.invalid_arguments:n="Invalid function arguments";break;case pe.invalid_return_type:n="Invalid function return type";break;case pe.invalid_date:n="Invalid date";break;case pe.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}"`:mt.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case pe.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 pe.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 pe.custom:n="Invalid input";break;case pe.invalid_intersection_types:n="Intersection results could not be merged";break;case pe.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case pe.not_finite:n="Number must be finite";break;default:n=t.defaultError,mt.assertNever(e)}return{message:n}};let eX=Kh;function S1(){return eX}const E1=e=>{const{data:t,path:n,errorMaps:r,issueData:o}=e,i=[...n,...o.path||[]],s={...o,path:i};let l="";const u=r.filter(d=>!!d).slice().reverse();for(const d of u)l=d(s,{data:t,defaultError:l}).message;return{...o,path:i,message:o.message||l}};function Ee(e,t){const n=E1({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,S1(),Kh].filter(r=>!!r)});e.common.issues.push(n)}class zn{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 o of n){if(o.status==="aborted")return Ze;o.status==="dirty"&&t.dirty(),r.push(o.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){const r=[];for(const o of n)r.push({key:await o.key,value:await o.value});return zn.mergeObjectSync(t,r)}static mergeObjectSync(t,n){const r={};for(const o of n){const{key:i,value:s}=o;if(i.status==="aborted"||s.status==="aborted")return Ze;i.status==="dirty"&&t.dirty(),s.status==="dirty"&&t.dirty(),i.value!=="__proto__"&&(typeof s.value<"u"||o.alwaysSet)&&(r[i.value]=s.value)}return{status:t.value,value:r}}}const Ze=Object.freeze({status:"aborted"}),tX=e=>({status:"dirty",value:e}),rr=e=>({status:"valid",value:e}),T2=e=>e.status==="aborted",P2=e=>e.status==="dirty",Yh=e=>e.status==="valid",C1=e=>typeof Promise<"u"&&e instanceof Promise;var Ne;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t==null?void 0:t.message})(Ne||(Ne={}));class Ko{constructor(t,n,r,o){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=o}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 A2=(e,t)=>{if(Yh(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 Bo(e.common.issues);return this._error=n,this._error}}};function Xe(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:r,description:o}=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:o}:{errorMap:(s,l)=>s.code!=="invalid_type"?{message:l.defaultError}:typeof l.data>"u"?{message:r??l.defaultError}:{message:n??l.defaultError},description:o}}class rt{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.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this)}get description(){return this._def.description}_getType(t){return ta(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:ta(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new zn,ctx:{common:t.parent.common,data:t.data,parsedType:ta(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const n=this._parse(t);if(C1(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 o={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:ta(t)},i=this._parseSync({data:t,path:o.path,parent:o});return A2(o,i)}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:ta(t)},o=this._parse({data:t,path:r.path,parent:r}),i=await(C1(o)?o:Promise.resolve(o));return A2(r,i)}refine(t,n){const r=o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n;return this._refinement((o,i)=>{const s=t(o),l=()=>i.addIssue({code:pe.custom,...r(o)});return typeof Promise<"u"&&s instanceof Promise?s.then(u=>u?!0:(l(),!1)):s?!0:(l(),!1)})}refinement(t,n){return this._refinement((r,o)=>t(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(t){return new Si({schema:this,typeName:ze.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}optional(){return bs.create(this,this._def)}nullable(){return uc.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Uo.create(this,this._def)}promise(){return ad.create(this,this._def)}or(t){return Zh.create([this,t],this._def)}and(t){return qh.create(this,t,this._def)}transform(t){return new Si({...Xe(this._def),schema:this,typeName:ze.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const n=typeof t=="function"?t:()=>t;return new nm({...Xe(this._def),innerType:this,defaultValue:n,typeName:ze.ZodDefault})}brand(){return new pX({typeName:ze.ZodBranded,type:this,...Xe(this._def)})}catch(t){const n=typeof t=="function"?t:()=>t;return new O1({...Xe(this._def),innerType:this,catchValue:n,typeName:ze.ZodCatch})}describe(t){const n=this.constructor;return new n({...this._def,description:t})}pipe(t){return sg.create(this,t)}readonly(){return N1.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const nX=/^c[^\s-]{8,}$/i,rX=/^[a-z][a-z0-9]*$/,oX=/^[0-9A-HJKMNP-TV-Z]{26}$/,iX=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,sX=/^(?!\.)(?!.*\.\.)([A-Z0-9_+-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,aX="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let M0;const lX=/^(((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}))$/,cX=/^(([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})))$/,uX=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 dX(e,t){return!!((t==="v4"||!t)&&lX.test(e)||(t==="v6"||!t)&&cX.test(e))}class di extends rt{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==be.string){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_type,expected:be.string,received:i.parsedType}),Ze}const r=new zn;let o;for(const i of this._def.checks)if(i.kind==="min")t.data.lengthi.value&&(o=this._getOrReturnCtx(t,o),Ee(o,{code:pe.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){const s=t.data.length>i.value,l=t.data.lengtht.test(o),{validation:n,code:pe.invalid_string,...Ne.errToObj(r)})}_addCheck(t){return new di({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...Ne.errToObj(t)})}url(t){return this._addCheck({kind:"url",...Ne.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...Ne.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...Ne.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...Ne.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...Ne.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...Ne.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...Ne.errToObj(t)})}datetime(t){var n;return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof(t==null?void 0:t.precision)>"u"?null:t==null?void 0:t.precision,offset:(n=t==null?void 0:t.offset)!==null&&n!==void 0?n:!1,...Ne.errToObj(t==null?void 0:t.message)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...Ne.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n==null?void 0:n.position,...Ne.errToObj(n==null?void 0:n.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...Ne.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...Ne.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...Ne.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...Ne.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...Ne.errToObj(n)})}nonempty(t){return this.min(1,Ne.errToObj(t))}trim(){return new di({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new di({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new di({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}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 di({checks:[],typeName:ze.ZodString,coerce:(t=e==null?void 0:e.coerce)!==null&&t!==void 0?t:!1,...Xe(e)})};function fX(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,o=n>r?n:r,i=parseInt(e.toFixed(o).replace(".","")),s=parseInt(t.toFixed(o).replace(".",""));return i%s/Math.pow(10,o)}class ac extends rt{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)!==be.number){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_type,expected:be.number,received:i.parsedType}),Ze}let r;const o=new zn;for(const i of this._def.checks)i.kind==="int"?mt.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.invalid_type,expected:"integer",received:"float",message:i.message}),o.dirty()):i.kind==="min"?(i.inclusive?t.datai.value:t.data>=i.value)&&(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),o.dirty()):i.kind==="multipleOf"?fX(t.data,i.value)!==0&&(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):i.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.not_finite,message:i.message}),o.dirty()):mt.assertNever(i);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,Ne.toString(n))}gt(t,n){return this.setLimit("min",t,!1,Ne.toString(n))}lte(t,n){return this.setLimit("max",t,!0,Ne.toString(n))}lt(t,n){return this.setLimit("max",t,!1,Ne.toString(n))}setLimit(t,n,r,o){return new ac({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:Ne.toString(o)}]})}_addCheck(t){return new ac({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:Ne.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Ne.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Ne.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Ne.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Ne.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:Ne.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:Ne.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Ne.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Ne.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"&&mt.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 ac({checks:[],typeName:ze.ZodNumber,coerce:(e==null?void 0:e.coerce)||!1,...Xe(e)});class lc extends rt{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)!==be.bigint){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_type,expected:be.bigint,received:i.parsedType}),Ze}let r;const o=new zn;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?t.datai.value:t.data>=i.value)&&(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),o.dirty()):i.kind==="multipleOf"?t.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):mt.assertNever(i);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,Ne.toString(n))}gt(t,n){return this.setLimit("min",t,!1,Ne.toString(n))}lte(t,n){return this.setLimit("max",t,!0,Ne.toString(n))}lt(t,n){return this.setLimit("max",t,!1,Ne.toString(n))}setLimit(t,n,r,o){return new lc({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:Ne.toString(o)}]})}_addCheck(t){return new lc({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Ne.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Ne.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Ne.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Ne.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:Ne.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 lc({checks:[],typeName:ze.ZodBigInt,coerce:(t=e==null?void 0:e.coerce)!==null&&t!==void 0?t:!1,...Xe(e)})};class $1 extends rt{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==be.boolean){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.boolean,received:r.parsedType}),Ze}return rr(t.data)}}$1.create=e=>new $1({typeName:ze.ZodBoolean,coerce:(e==null?void 0:e.coerce)||!1,...Xe(e)});class sd extends rt{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==be.date){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_type,expected:be.date,received:i.parsedType}),Ze}if(isNaN(t.data.getTime())){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_date}),Ze}const r=new zn;let o;for(const i of this._def.checks)i.kind==="min"?t.data.getTime()i.value&&(o=this._getOrReturnCtx(t,o),Ee(o,{code:pe.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):mt.assertNever(i);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new sd({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:Ne.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:Ne.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 sd({checks:[],coerce:(e==null?void 0:e.coerce)||!1,typeName:ze.ZodDate,...Xe(e)});class k1 extends rt{_parse(t){if(this._getType(t)!==be.symbol){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.symbol,received:r.parsedType}),Ze}return rr(t.data)}}k1.create=e=>new k1({typeName:ze.ZodSymbol,...Xe(e)});class Gh extends rt{_parse(t){if(this._getType(t)!==be.undefined){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.undefined,received:r.parsedType}),Ze}return rr(t.data)}}Gh.create=e=>new Gh({typeName:ze.ZodUndefined,...Xe(e)});class Xh extends rt{_parse(t){if(this._getType(t)!==be.null){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.null,received:r.parsedType}),Ze}return rr(t.data)}}Xh.create=e=>new Xh({typeName:ze.ZodNull,...Xe(e)});class R1 extends rt{constructor(){super(...arguments),this._any=!0}_parse(t){return rr(t.data)}}R1.create=e=>new R1({typeName:ze.ZodAny,...Xe(e)});class Tl extends rt{constructor(){super(...arguments),this._unknown=!0}_parse(t){return rr(t.data)}}Tl.create=e=>new Tl({typeName:ze.ZodUnknown,...Xe(e)});class Rs extends rt{_parse(t){const n=this._getOrReturnCtx(t);return Ee(n,{code:pe.invalid_type,expected:be.never,received:n.parsedType}),Ze}}Rs.create=e=>new Rs({typeName:ze.ZodNever,...Xe(e)});class T1 extends rt{_parse(t){if(this._getType(t)!==be.undefined){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.void,received:r.parsedType}),Ze}return rr(t.data)}}T1.create=e=>new T1({typeName:ze.ZodVoid,...Xe(e)});class Uo extends rt{_parse(t){const{ctx:n,status:r}=this._processInputParams(t),o=this._def;if(n.parsedType!==be.array)return Ee(n,{code:pe.invalid_type,expected:be.array,received:n.parsedType}),Ze;if(o.exactLength!==null){const s=n.data.length>o.exactLength.value,l=n.data.lengtho.maxLength.value&&(Ee(n,{code:pe.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((s,l)=>o.type._parseAsync(new Ko(n,s,n.path,l)))).then(s=>zn.mergeArray(r,s));const i=[...n.data].map((s,l)=>o.type._parseSync(new Ko(n,s,n.path,l)));return zn.mergeArray(r,i)}get element(){return this._def.type}min(t,n){return new Uo({...this._def,minLength:{value:t,message:Ne.toString(n)}})}max(t,n){return new Uo({...this._def,maxLength:{value:t,message:Ne.toString(n)}})}length(t,n){return new Uo({...this._def,exactLength:{value:t,message:Ne.toString(n)}})}nonempty(t){return this.min(1,t)}}Uo.create=(e,t)=>new Uo({type:e,minLength:null,maxLength:null,exactLength:null,typeName:ze.ZodArray,...Xe(t)});function ol(e){if(e instanceof Vt){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=bs.create(ol(r))}return new Vt({...e._def,shape:()=>t})}else return e instanceof Uo?new Uo({...e._def,type:ol(e.element)}):e instanceof bs?bs.create(ol(e.unwrap())):e instanceof uc?uc.create(ol(e.unwrap())):e instanceof _i?_i.create(e.items.map(t=>ol(t))):e}class Vt extends rt{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=mt.objectKeys(t);return this._cached={shape:t,keys:n}}_parse(t){if(this._getType(t)!==be.object){const d=this._getOrReturnCtx(t);return Ee(d,{code:pe.invalid_type,expected:be.object,received:d.parsedType}),Ze}const{status:r,ctx:o}=this._processInputParams(t),{shape:i,keys:s}=this._getCached(),l=[];if(!(this._def.catchall instanceof Rs&&this._def.unknownKeys==="strip"))for(const d in o.data)s.includes(d)||l.push(d);const u=[];for(const d of s){const h=i[d],m=o.data[d];u.push({key:{status:"valid",value:d},value:h._parse(new Ko(o,m,o.path,d)),alwaysSet:d in o.data})}if(this._def.catchall instanceof Rs){const d=this._def.unknownKeys;if(d==="passthrough")for(const h of l)u.push({key:{status:"valid",value:h},value:{status:"valid",value:o.data[h]}});else if(d==="strict")l.length>0&&(Ee(o,{code:pe.unrecognized_keys,keys:l}),r.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const d=this._def.catchall;for(const h of l){const m=o.data[h];u.push({key:{status:"valid",value:h},value:d._parse(new Ko(o,m,o.path,h)),alwaysSet:h in o.data})}}return o.common.async?Promise.resolve().then(async()=>{const d=[];for(const h of u){const m=await h.key;d.push({key:m,value:await h.value,alwaysSet:h.alwaysSet})}return d}).then(d=>zn.mergeObjectSync(r,d)):zn.mergeObjectSync(r,u)}get shape(){return this._def.shape()}strict(t){return Ne.errToObj,new Vt({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{var o,i,s,l;const u=(s=(i=(o=this._def).errorMap)===null||i===void 0?void 0:i.call(o,n,r).message)!==null&&s!==void 0?s:r.defaultError;return n.code==="unrecognized_keys"?{message:(l=Ne.errToObj(t).message)!==null&&l!==void 0?l:u}:{message:u}}}:{}})}strip(){return new Vt({...this._def,unknownKeys:"strip"})}passthrough(){return new Vt({...this._def,unknownKeys:"passthrough"})}extend(t){return new Vt({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new Vt({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:ze.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new Vt({...this._def,catchall:t})}pick(t){const n={};return mt.objectKeys(t).forEach(r=>{t[r]&&this.shape[r]&&(n[r]=this.shape[r])}),new Vt({...this._def,shape:()=>n})}omit(t){const n={};return mt.objectKeys(this.shape).forEach(r=>{t[r]||(n[r]=this.shape[r])}),new Vt({...this._def,shape:()=>n})}deepPartial(){return ol(this)}partial(t){const n={};return mt.objectKeys(this.shape).forEach(r=>{const o=this.shape[r];t&&!t[r]?n[r]=o:n[r]=o.optional()}),new Vt({...this._def,shape:()=>n})}required(t){const n={};return mt.objectKeys(this.shape).forEach(r=>{if(t&&!t[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof bs;)i=i._def.innerType;n[r]=i}}),new Vt({...this._def,shape:()=>n})}keyof(){return e3(mt.objectKeys(this.shape))}}Vt.create=(e,t)=>new Vt({shape:()=>e,unknownKeys:"strip",catchall:Rs.create(),typeName:ze.ZodObject,...Xe(t)});Vt.strictCreate=(e,t)=>new Vt({shape:()=>e,unknownKeys:"strict",catchall:Rs.create(),typeName:ze.ZodObject,...Xe(t)});Vt.lazycreate=(e,t)=>new Vt({shape:e,unknownKeys:"strip",catchall:Rs.create(),typeName:ze.ZodObject,...Xe(t)});class Zh extends rt{_parse(t){const{ctx:n}=this._processInputParams(t),r=this._def.options;function o(i){for(const l of i)if(l.result.status==="valid")return l.result;for(const l of i)if(l.result.status==="dirty")return n.common.issues.push(...l.ctx.common.issues),l.result;const s=i.map(l=>new Bo(l.ctx.common.issues));return Ee(n,{code:pe.invalid_union,unionErrors:s}),Ze}if(n.common.async)return Promise.all(r.map(async i=>{const s={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:s}),ctx:s}})).then(o);{let i;const s=[];for(const u of r){const d={...n,common:{...n.common,issues:[]},parent:null},h=u._parseSync({data:n.data,path:n.path,parent:d});if(h.status==="valid")return h;h.status==="dirty"&&!i&&(i={result:h,ctx:d}),d.common.issues.length&&s.push(d.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;const l=s.map(u=>new Bo(u));return Ee(n,{code:pe.invalid_union,unionErrors:l}),Ze}}get options(){return this._def.options}}Zh.create=(e,t)=>new Zh({options:e,typeName:ze.ZodUnion,...Xe(t)});const Zp=e=>e instanceof Jh?Zp(e.schema):e instanceof Si?Zp(e.innerType()):e instanceof em?[e.value]:e instanceof Ta?e.options:e instanceof tm?Object.keys(e.enum):e instanceof nm?Zp(e._def.innerType):e instanceof Gh?[void 0]:e instanceof Xh?[null]:null;class Yx extends rt{_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.object)return Ee(n,{code:pe.invalid_type,expected:be.object,received:n.parsedType}),Ze;const r=this.discriminator,o=n.data[r],i=this.optionsMap.get(o);return i?n.common.async?i._parseAsync({data:n.data,path:n.path,parent:n}):i._parseSync({data:n.data,path:n.path,parent:n}):(Ee(n,{code:pe.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),Ze)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){const o=new Map;for(const i of n){const s=Zp(i.shape[t]);if(!s)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const l of s){if(o.has(l))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(l)}`);o.set(l,i)}}return new Yx({typeName:ze.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:o,...Xe(r)})}}function P1(e,t){const n=ta(e),r=ta(t);if(e===t)return{valid:!0,data:e};if(n===be.object&&r===be.object){const o=mt.objectKeys(t),i=mt.objectKeys(e).filter(l=>o.indexOf(l)!==-1),s={...e,...t};for(const l of i){const u=P1(e[l],t[l]);if(!u.valid)return{valid:!1};s[l]=u.data}return{valid:!0,data:s}}else if(n===be.array&&r===be.array){if(e.length!==t.length)return{valid:!1};const o=[];for(let i=0;i{if(T2(i)||T2(s))return Ze;const l=P1(i.value,s.value);return l.valid?((P2(i)||P2(s))&&n.dirty(),{status:n.value,value:l.data}):(Ee(r,{code:pe.invalid_intersection_types}),Ze)};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(([i,s])=>o(i,s)):o(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}qh.create=(e,t,n)=>new qh({left:e,right:t,typeName:ze.ZodIntersection,...Xe(n)});class _i extends rt{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.array)return Ee(r,{code:pe.invalid_type,expected:be.array,received:r.parsedType}),Ze;if(r.data.lengththis._def.items.length&&(Ee(r,{code:pe.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const i=[...r.data].map((s,l)=>{const u=this._def.items[l]||this._def.rest;return u?u._parse(new Ko(r,s,r.path,l)):null}).filter(s=>!!s);return r.common.async?Promise.all(i).then(s=>zn.mergeArray(n,s)):zn.mergeArray(n,i)}get items(){return this._def.items}rest(t){return new _i({...this._def,rest:t})}}_i.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new _i({items:e,typeName:ze.ZodTuple,rest:null,...Xe(t)})};class Qh extends rt{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!==be.object)return Ee(r,{code:pe.invalid_type,expected:be.object,received:r.parsedType}),Ze;const o=[],i=this._def.keyType,s=this._def.valueType;for(const l in r.data)o.push({key:i._parse(new Ko(r,l,r.path,l)),value:s._parse(new Ko(r,r.data[l],r.path,l))});return r.common.async?zn.mergeObjectAsync(n,o):zn.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof rt?new Qh({keyType:t,valueType:n,typeName:ze.ZodRecord,...Xe(r)}):new Qh({keyType:di.create(),valueType:t,typeName:ze.ZodRecord,...Xe(n)})}}class A1 extends rt{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!==be.map)return Ee(r,{code:pe.invalid_type,expected:be.map,received:r.parsedType}),Ze;const o=this._def.keyType,i=this._def.valueType,s=[...r.data.entries()].map(([l,u],d)=>({key:o._parse(new Ko(r,l,r.path,[d,"key"])),value:i._parse(new Ko(r,u,r.path,[d,"value"]))}));if(r.common.async){const l=new Map;return Promise.resolve().then(async()=>{for(const u of s){const d=await u.key,h=await u.value;if(d.status==="aborted"||h.status==="aborted")return Ze;(d.status==="dirty"||h.status==="dirty")&&n.dirty(),l.set(d.value,h.value)}return{status:n.value,value:l}})}else{const l=new Map;for(const u of s){const d=u.key,h=u.value;if(d.status==="aborted"||h.status==="aborted")return Ze;(d.status==="dirty"||h.status==="dirty")&&n.dirty(),l.set(d.value,h.value)}return{status:n.value,value:l}}}}A1.create=(e,t,n)=>new A1({valueType:t,keyType:e,typeName:ze.ZodMap,...Xe(n)});class cc extends rt{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.set)return Ee(r,{code:pe.invalid_type,expected:be.set,received:r.parsedType}),Ze;const o=this._def;o.minSize!==null&&r.data.sizeo.maxSize.value&&(Ee(r,{code:pe.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());const i=this._def.valueType;function s(u){const d=new Set;for(const h of u){if(h.status==="aborted")return Ze;h.status==="dirty"&&n.dirty(),d.add(h.value)}return{status:n.value,value:d}}const l=[...r.data.values()].map((u,d)=>i._parse(new Ko(r,u,r.path,d)));return r.common.async?Promise.all(l).then(u=>s(u)):s(l)}min(t,n){return new cc({...this._def,minSize:{value:t,message:Ne.toString(n)}})}max(t,n){return new cc({...this._def,maxSize:{value:t,message:Ne.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}}cc.create=(e,t)=>new cc({valueType:e,minSize:null,maxSize:null,typeName:ze.ZodSet,...Xe(t)});class Pu extends rt{constructor(){super(...arguments),this.validate=this.implement}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.function)return Ee(n,{code:pe.invalid_type,expected:be.function,received:n.parsedType}),Ze;function r(l,u){return E1({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,S1(),Kh].filter(d=>!!d),issueData:{code:pe.invalid_arguments,argumentsError:u}})}function o(l,u){return E1({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,S1(),Kh].filter(d=>!!d),issueData:{code:pe.invalid_return_type,returnTypeError:u}})}const i={errorMap:n.common.contextualErrorMap},s=n.data;if(this._def.returns instanceof ad){const l=this;return rr(async function(...u){const d=new Bo([]),h=await l._def.args.parseAsync(u,i).catch(y=>{throw d.addIssue(r(u,y)),d}),m=await Reflect.apply(s,this,h);return await l._def.returns._def.type.parseAsync(m,i).catch(y=>{throw d.addIssue(o(m,y)),d})})}else{const l=this;return rr(function(...u){const d=l._def.args.safeParse(u,i);if(!d.success)throw new Bo([r(u,d.error)]);const h=Reflect.apply(s,this,d.data),m=l._def.returns.safeParse(h,i);if(!m.success)throw new Bo([o(h,m.error)]);return m.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new Pu({...this._def,args:_i.create(t).rest(Tl.create())})}returns(t){return new Pu({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new Pu({args:t||_i.create([]).rest(Tl.create()),returns:n||Tl.create(),typeName:ze.ZodFunction,...Xe(r)})}}class Jh extends rt{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})}}Jh.create=(e,t)=>new Jh({getter:e,typeName:ze.ZodLazy,...Xe(t)});class em extends rt{_parse(t){if(t.data!==this._def.value){const n=this._getOrReturnCtx(t);return Ee(n,{received:n.data,code:pe.invalid_literal,expected:this._def.value}),Ze}return{status:"valid",value:t.data}}get value(){return this._def.value}}em.create=(e,t)=>new em({value:e,typeName:ze.ZodLiteral,...Xe(t)});function e3(e,t){return new Ta({values:e,typeName:ze.ZodEnum,...Xe(t)})}class Ta extends rt{_parse(t){if(typeof t.data!="string"){const n=this._getOrReturnCtx(t),r=this._def.values;return Ee(n,{expected:mt.joinValues(r),received:n.parsedType,code:pe.invalid_type}),Ze}if(this._def.values.indexOf(t.data)===-1){const n=this._getOrReturnCtx(t),r=this._def.values;return Ee(n,{received:n.data,code:pe.invalid_enum_value,options:r}),Ze}return rr(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 Ta.create(t)}exclude(t){return Ta.create(this.options.filter(n=>!t.includes(n)))}}Ta.create=e3;class tm extends rt{_parse(t){const n=mt.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==be.string&&r.parsedType!==be.number){const o=mt.objectValues(n);return Ee(r,{expected:mt.joinValues(o),received:r.parsedType,code:pe.invalid_type}),Ze}if(n.indexOf(t.data)===-1){const o=mt.objectValues(n);return Ee(r,{received:r.data,code:pe.invalid_enum_value,options:o}),Ze}return rr(t.data)}get enum(){return this._def.values}}tm.create=(e,t)=>new tm({values:e,typeName:ze.ZodNativeEnum,...Xe(t)});class ad extends rt{unwrap(){return this._def.type}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.promise&&n.common.async===!1)return Ee(n,{code:pe.invalid_type,expected:be.promise,received:n.parsedType}),Ze;const r=n.parsedType===be.promise?n.data:Promise.resolve(n.data);return rr(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}}ad.create=(e,t)=>new ad({type:e,typeName:ze.ZodPromise,...Xe(t)});class Si extends rt{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ze.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:n,ctx:r}=this._processInputParams(t),o=this._def.effect||null,i={addIssue:s=>{Ee(r,s),s.fatal?n.abort():n.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),o.type==="preprocess"){const s=o.transform(r.data,i);return r.common.issues.length?{status:"dirty",value:r.data}:r.common.async?Promise.resolve(s).then(l=>this._def.schema._parseAsync({data:l,path:r.path,parent:r})):this._def.schema._parseSync({data:s,path:r.path,parent:r})}if(o.type==="refinement"){const s=l=>{const u=o.refinement(l,i);if(r.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return l};if(r.common.async===!1){const l=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return l.status==="aborted"?Ze:(l.status==="dirty"&&n.dirty(),s(l.value),{status:n.value,value:l.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(l=>l.status==="aborted"?Ze:(l.status==="dirty"&&n.dirty(),s(l.value).then(()=>({status:n.value,value:l.value}))))}if(o.type==="transform")if(r.common.async===!1){const s=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Yh(s))return s;const l=o.transform(s.value,i);if(l instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:l}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(s=>Yh(s)?Promise.resolve(o.transform(s.value,i)).then(l=>({status:n.value,value:l})):s);mt.assertNever(o)}}Si.create=(e,t,n)=>new Si({schema:e,typeName:ze.ZodEffects,effect:t,...Xe(n)});Si.createWithPreprocess=(e,t,n)=>new Si({schema:t,effect:{type:"preprocess",transform:e},typeName:ze.ZodEffects,...Xe(n)});class bs extends rt{_parse(t){return this._getType(t)===be.undefined?rr(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}bs.create=(e,t)=>new bs({innerType:e,typeName:ze.ZodOptional,...Xe(t)});class uc extends rt{_parse(t){return this._getType(t)===be.null?rr(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}uc.create=(e,t)=>new uc({innerType:e,typeName:ze.ZodNullable,...Xe(t)});class nm extends rt{_parse(t){const{ctx:n}=this._processInputParams(t);let r=n.data;return n.parsedType===be.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}nm.create=(e,t)=>new nm({innerType:e,typeName:ze.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Xe(t)});class O1 extends rt{_parse(t){const{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return C1(o)?o.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Bo(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Bo(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}O1.create=(e,t)=>new O1({innerType:e,typeName:ze.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Xe(t)});class M1 extends rt{_parse(t){if(this._getType(t)!==be.nan){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.nan,received:r.parsedType}),Ze}return{status:"valid",value:t.data}}}M1.create=e=>new M1({typeName:ze.ZodNaN,...Xe(e)});class pX extends rt{_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 sg extends rt{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?Ze:i.status==="dirty"?(n.dirty(),tX(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{const o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?Ze:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(t,n){return new sg({in:t,out:n,typeName:ze.ZodPipeline})}}class N1 extends rt{_parse(t){const n=this._def.innerType._parse(t);return Yh(n)&&(n.value=Object.freeze(n.value)),n}}N1.create=(e,t)=>new N1({innerType:e,typeName:ze.ZodReadonly,...Xe(t)});Vt.lazycreate;var ze;(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",e.ZodReadonly="ZodReadonly"})(ze||(ze={}));const O2=di.create;ac.create;M1.create;lc.create;const su=$1.create;sd.create;k1.create;Gh.create;Xh.create;R1.create;Tl.create;Rs.create;T1.create;Uo.create;const hX=Vt.create;Vt.strictCreate;Zh.create;Yx.create;qh.create;_i.create;Qh.create;A1.create;cc.create;Pu.create;Jh.create;em.create;Ta.create;tm.create;ad.create;Si.create;bs.create;uc.create;Si.createWithPreprocess;sg.create;const D1="horizontal",mX=["horizontal","vertical"],t3=f.forwardRef((e,t)=>{const{decorative:n,orientation:r=D1,...o}=e,i=n3(r)?r:D1,l=n?{role:"none"}:{"aria-orientation":i==="vertical"?i:void 0,role:"separator"};return f.createElement(Pe.div,Y({"data-orientation":i},l,o,{ref:t}))});t3.propTypes={orientation(e,t,n){const r=e[t],o=String(r);return r&&!n3(r)?new Error(gX(o,n)):null}};function gX(e,t){return`Invalid prop \`orientation\` of value \`${e}\` supplied to \`${t}\`, expected one of: + - horizontal + - vertical + +Defaulting to \`${D1}\`.`}function n3(e){return mX.includes(e)}const r3=t3,Fn=f.forwardRef(({className:e,orientation:t="horizontal",decorative:n=!0,...r},o)=>v.jsx(r3,{ref:o,decorative:n,orientation:t,className:Ce("shrink-0 bg-border",t==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",e),...r}));Fn.displayName=r3.displayName;const vX=f.forwardRef((e,t)=>f.createElement(Pe.label,Y({},e,{ref:t,onMouseDown:n=>{var r;(r=e.onMouseDown)===null||r===void 0||r.call(e,n),!n.defaultPrevented&&n.detail>1&&n.preventDefault()}}))),o3=vX,yX=Om("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),Gx=f.forwardRef(({className:e,disabled:t,...n},r)=>v.jsx(o3,{ref:r,className:Ce(yX(),e,t?"opacity-50":"","select-none"),...n}));Gx.displayName=o3.displayName;const wX=MG,i3=f.createContext({}),N0=({...e})=>v.jsx(i3.Provider,{value:{name:e.name},children:v.jsx(LG,{...e})}),ag=()=>{const e=f.useContext(i3),t=f.useContext(s3),{getFieldState:n,formState:r}=ig(),o=n(e.name,r);if(!e)throw new Error("useFormField should be used within ");const{id:i}=t;return{id:i,name:e.name,formItemId:`${i}-form-item`,formDescriptionId:`${i}-form-item-description`,formMessageId:`${i}-form-item-message`,...o}},s3=f.createContext({}),qp=f.forwardRef(({className:e,...t},n)=>{const r=f.useId();return v.jsx(s3.Provider,{value:{id:r},children:v.jsx("div",{ref:n,className:Ce("space-y-2",e),...t})})});qp.displayName="FormItem";const Qp=f.forwardRef(({className:e,...t},n)=>{const{error:r,formItemId:o}=ag();return v.jsx(Gx,{ref:n,className:Ce(r&&"text-destructive","text-sm",e),htmlFor:o,...t})});Qp.displayName="FormLabel";const Jp=f.forwardRef(({...e},t)=>{const{error:n,formItemId:r,formDescriptionId:o,formMessageId:i}=ag();return v.jsx(Wo,{ref:t,id:r,"aria-describedby":n?`${o} ${i}`:`${o}`,"aria-invalid":!!n,...e})});Jp.displayName="FormControl";const eh=f.forwardRef(({className:e,...t},n)=>{const{formDescriptionId:r}=ag();return v.jsx("p",{ref:n,id:r,className:Ce("text-[0.8rem] text-muted-foreground",e),...t})});eh.displayName="FormDescription";const xX=f.forwardRef(({className:e,children:t,...n},r)=>{const{error:o,formMessageId:i}=ag(),s=o?String(o==null?void 0:o.message):t;return s?v.jsx("p",{ref:r,id:i,className:Ce("text-[0.8rem] font-medium text-destructive",e),...n,children:s}):null});xX.displayName="FormMessage";const a3="Switch",[bX,Ste]=An(a3),[_X,SX]=bX(a3),EX=f.forwardRef((e,t)=>{const{__scopeSwitch:n,name:r,checked:o,defaultChecked:i,required:s,disabled:l,value:u="on",onCheckedChange:d,...h}=e,[m,g]=f.useState(null),y=Be(t,b=>g(b)),x=f.useRef(!1),_=m?!!m.closest("form"):!0,[C=!1,S]=Zr({prop:o,defaultProp:i,onChange:d});return f.createElement(_X,{scope:n,checked:C,disabled:l},f.createElement(Pe.button,Y({type:"button",role:"switch","aria-checked":C,"aria-required":s,"data-state":l3(C),"data-disabled":l?"":void 0,disabled:l,value:u},h,{ref:y,onClick:ue(e.onClick,b=>{S(E=>!E),_&&(x.current=b.isPropagationStopped(),x.current||b.stopPropagation())})})),_&&f.createElement(kX,{control:m,bubbles:!x.current,name:r,value:u,checked:C,required:s,disabled:l,style:{transform:"translateX(-100%)"}}))}),CX="SwitchThumb",$X=f.forwardRef((e,t)=>{const{__scopeSwitch:n,...r}=e,o=SX(CX,n);return f.createElement(Pe.span,Y({"data-state":l3(o.checked),"data-disabled":o.disabled?"":void 0},r,{ref:t}))}),kX=e=>{const{control:t,checked:n,bubbles:r=!0,...o}=e,i=f.useRef(null),s=Fx(n),l=gx(t);return f.useEffect(()=>{const u=i.current,d=window.HTMLInputElement.prototype,m=Object.getOwnPropertyDescriptor(d,"checked").set;if(s!==n&&m){const g=new Event("click",{bubbles:r});m.call(u,n),u.dispatchEvent(g)}},[s,n,r]),f.createElement("input",Y({type:"checkbox","aria-hidden":!0,defaultChecked:n},o,{tabIndex:-1,ref:i,style:{...e.style,...l,position:"absolute",pointerEvents:"none",opacity:0,margin:0}}))};function l3(e){return e?"checked":"unchecked"}const c3=EX,RX=$X,co=f.forwardRef(({className:e,...t},n)=>v.jsx(c3,{className:Ce("peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",e),tabIndex:-1,...t,ref:n,children:v.jsx(RX,{className:Ce("pointer-events-none block h-4 w-4 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0")})}));co.displayName=c3.displayName;const TX="AlertDialog",[PX,Ete]=An(TX,[cP]),Is=cP(),AX=e=>{const{__scopeAlertDialog:t,...n}=e,r=Is(t);return f.createElement(Sx,Y({},r,n,{modal:!0}))},OX=e=>{const{__scopeAlertDialog:t,...n}=e,r=Is(t);return f.createElement(Ex,Y({},r,n))},MX=f.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=Is(n);return f.createElement(Nd,Y({},o,r,{ref:t}))}),u3="AlertDialogContent",[NX,DX]=PX(u3),IX=f.forwardRef((e,t)=>{const{__scopeAlertDialog:n,children:r,...o}=e,i=Is(n),s=f.useRef(null),l=Be(t,s),u=f.useRef(null);return f.createElement(pW,{contentName:u3,titleName:LX,docsSlug:"alert-dialog"},f.createElement(NX,{scope:n,cancelRef:u},f.createElement(Dd,Y({role:"alertdialog"},i,o,{ref:l,onOpenAutoFocus:ue(o.onOpenAutoFocus,d=>{var h;d.preventDefault(),(h=u.current)===null||h===void 0||h.focus({preventScroll:!0})}),onPointerDownOutside:d=>d.preventDefault(),onInteractOutside:d=>d.preventDefault()}),f.createElement(sx,null,r),!1)))}),LX="AlertDialogTitle",FX=f.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=Is(n);return f.createElement(Id,Y({},o,r,{ref:t}))}),jX=f.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=Is(n);return f.createElement(Ld,Y({},o,r,{ref:t}))}),zX=f.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=Is(n);return f.createElement(Cx,Y({},o,r,{ref:t}))}),BX="AlertDialogCancel",UX=f.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,{cancelRef:o}=DX(BX,n),i=Is(n),s=Be(t,o);return f.createElement(Cx,Y({},i,r,{ref:s}))}),VX=AX,WX=OX,d3=MX,f3=IX,p3=zX,h3=UX,m3=FX,g3=jX,HX=VX,KX=WX,v3=f.forwardRef(({className:e,...t},n)=>v.jsx(d3,{className:Ce("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t,ref:n}));v3.displayName=d3.displayName;const y3=f.forwardRef(({className:e,...t},n)=>v.jsxs(KX,{children:[v.jsx(v3,{}),v.jsx(f3,{ref:n,className:Ce("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",e),...t})]}));y3.displayName=f3.displayName;const w3=({className:e,...t})=>v.jsx("div",{className:Ce("flex flex-col space-y-2 text-center sm:text-left",e),...t});w3.displayName="AlertDialogHeader";const YX=f.forwardRef(({className:e,...t},n)=>v.jsx(m3,{ref:n,className:Ce("text-lg font-semibold",e),...t}));YX.displayName=m3.displayName;const GX=f.forwardRef(({className:e,...t},n)=>v.jsx(g3,{ref:n,className:Ce("text-sm text-muted-foreground",e),...t}));GX.displayName=g3.displayName;const XX=f.forwardRef(({className:e,...t},n)=>v.jsx(p3,{ref:n,className:Ce(bx(),e),...t}));XX.displayName=p3.displayName;const ZX=f.forwardRef(({className:e,...t},n)=>v.jsx(h3,{ref:n,className:Ce(bx({variant:"outline"}),"mt-2 sm:mt-0",e),...t}));ZX.displayName=h3.displayName;const qX=hX({enableFileManager:su(),inputDirectory:O2(),outputDirectory:O2(),enableDownloadMask:su(),enableManualInpainting:su(),enableUploadMask:su(),enableAutoExtractPrompt:su()}),x3="General",I1="Model",QX=[I1,x3];function JX(){const[e,t]=u1(!1),[n,r]=u1(!1),[o,i]=f.useState(I1),[s,l,u,d,h,m]=bt(O=>[O.updateAppState,O.settings,O.updateSettings,O.fileManagerState,O.updateFileManagerState,O.setModel]),{toast:g}=Td(),[y,x]=f.useState(l.model);f.useEffect(()=>{x(l.model)},[l.model]);const{data:_,status:C}=TL({queryKey:["modelInfos"],queryFn:zj}),S=GG({resolver:JG(qX),defaultValues:{enableDownloadMask:l.enableDownloadMask,enableManualInpainting:l.enableManualInpainting,enableUploadMask:l.enableUploadMask,enableAutoExtractPrompt:l.enableAutoExtractPrompt,inputDirectory:d.inputDirectory,outputDirectory:d.outputDirectory}});async function b(O){if(u({enableDownloadMask:O.enableDownloadMask,enableManualInpainting:O.enableManualInpainting,enableUploadMask:O.enableUploadMask,enableAutoExtractPrompt:O.enableAutoExtractPrompt}),h({inputDirectory:O.inputDirectory,outputDirectory:O.outputDirectory}),y.name!==l.model.name){r(),s({disableShortCuts:!0});try{const F=await Fj(y.name);g({title:`Switch to ${F.name} success`}),m(y)}catch(F){g({variant:"destructive",title:`Switch to ${y.name} failed: ${F}`}),x(l.model)}finally{r(),s({disableShortCuts:!1})}}}Zn("s",()=>{t(),e&&b(S.getValues())},[e,S,y]);function E(O){t(),O||b(S.getValues())}function k(O){x(O)}function P(O){return _?_.filter(F=>O.includes(F.model_type)).map(F=>v.jsxs("div",{onClick:()=>k(F),className:"px-2",children:[v.jsx("div",{className:Ce([F.name===y.name?"bg-muted":"hover:bg-muted","rounded-md px-2 py-2","cursor-default"]),children:v.jsx("div",{className:"text-base",children:F.name})}),v.jsx(Fn,{className:"my-1"})]},F.name)):v.jsx("div",{children:"Please download model first"})}function M(){if(C!=="success")return v.jsx(v.Fragment,{});let O=is;for(let F of _)if(y.name===F.name){O=F.model_type,O===nC&&(O=rp),O===rC&&(O=op);break}return v.jsxs("div",{className:"flex flex-col gap-4 w-[510px]",children:[v.jsxs("div",{className:"flex flex-col gap-4 rounded-md",children:[v.jsx("div",{className:"font-medium",children:"Current Model"}),v.jsx("div",{children:y.name})]}),v.jsx(Fn,{}),v.jsxs("div",{className:"space-y-4 rounded-md",children:[v.jsx("div",{className:"flex gap-1 items-center justify-start",children:v.jsx("div",{className:"font-medium",children:"Available models"})}),v.jsxs(i5,{defaultValue:O,children:[v.jsxs(Lx,{children:[v.jsx(sa,{value:is,children:"Inpaint"}),v.jsx(sa,{value:rp,children:"Stable Diffusion"}),v.jsx(sa,{value:op,children:"Stable Diffusion Inpaint"}),v.jsx(sa,{value:l0,children:"Other Diffusion"})]}),v.jsxs(og,{className:"h-[240px] w-full mt-2 outline-none border rounded-lg",children:[v.jsx(mu,{value:is,children:P([is])}),v.jsx(mu,{value:rp,children:P([rp,nC])}),v.jsx(mu,{value:op,children:P([op,rC])}),v.jsx(mu,{value:l0,children:P([l0])})]})]})]})]})}function A(){return v.jsxs("div",{className:"space-y-4 w-[510px]",children:[v.jsx(N0,{control:S.control,name:"enableManualInpainting",render:({field:O})=>v.jsxs(qp,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(Qp,{children:"Enable manual inpainting"}),v.jsx(eh,{children:"For erase model, click a button to trigger inpainting after draw mask."})]}),v.jsx(Jp,{children:v.jsx(co,{checked:O.value,onCheckedChange:O.onChange})})]})}),v.jsx(Fn,{}),v.jsx(N0,{control:S.control,name:"enableDownloadMask",render:({field:O})=>v.jsxs(qp,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(Qp,{children:"Enable download mask"}),v.jsx(eh,{children:"Also download the mask after save the inpainting result."})]}),v.jsx(Jp,{children:v.jsx(co,{checked:O.value,onCheckedChange:O.onChange})})]})}),v.jsx(Fn,{}),v.jsx(N0,{control:S.control,name:"enableAutoExtractPrompt",render:({field:O})=>v.jsxs(qp,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(Qp,{children:"Enable auto extract prompt"}),v.jsx(eh,{children:"Automatically extract prompt/negativate prompt from the image meta."})]}),v.jsx(Jp,{children:v.jsx(co,{checked:O.value,onCheckedChange:O.onChange})})]})})]})}return v.jsxs(v.Fragment,{children:[v.jsx(HX,{open:n,children:v.jsx(y3,{children:v.jsx(w3,{children:v.jsxs("div",{className:"flex flex-col justify-center items-center gap-4",children:[v.jsxs("div",{role:"status",children:[v.jsxs("svg",{"aria-hidden":"true",className:"w-8 h-8 text-gray-200 animate-spin dark:text-gray-600 fill-primary",viewBox:"0 0 100 101",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[v.jsx("path",{d:"M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z",fill:"currentColor"}),v.jsx("path",{d:"M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z",fill:"currentFill"})]}),v.jsx("span",{className:"sr-only",children:"Loading..."})]}),v.jsxs("div",{children:["Switching to ",y.name]})]})})})}),v.jsxs(Zm,{open:e,onOpenChange:E,children:[v.jsx($x,{asChild:!0,children:v.jsx(vn,{tooltip:"Settings",children:v.jsx(sV,{})})}),v.jsxs(Fd,{className:"max-w-3xl h-[600px]",onOpenAutoFocus:O=>O.preventDefault(),children:[v.jsx(jd,{children:"Settings"}),v.jsx(Fn,{}),v.jsxs("div",{className:"flex flex-row space-x-8 h-full",children:[v.jsx("div",{className:"flex flex-col space-y-1",children:QX.map(O=>v.jsx(Rn,{variant:"ghost",onClick:()=>i(O),className:Ce(o===O?"bg-muted ":"hover:bg-muted","justify-start"),children:O},O))}),v.jsx(Fn,{orientation:"vertical"}),v.jsx(wX,{...S,children:v.jsx("div",{className:"flex w-full justify-center",children:v.jsxs("form",{onSubmit:S.handleSubmit(b),children:[o===I1?M():v.jsx(v.Fragment,{}),o===x3?A():v.jsx(v.Fragment,{}),v.jsx("div",{className:"absolute right-10 bottom-6",children:v.jsx(Rn,{onClick:()=>E(!1),children:"Ok"})})]})})})]})]})]})]})}const eZ="/assets/kofi_button_black-XI_Dr2zg.png";function tZ(){return v.jsxs(Zm,{children:[v.jsx($x,{asChild:!0,children:v.jsx(vn,{tooltip:"Buy me a coffee",children:v.jsx(YU,{})})}),v.jsxs(Fd,{children:[v.jsx(jd,{children:"Buy me a coffee"}),v.jsx(mP,{className:"mb-8",children:"Hi, if you found my project is useful, please conside buy me a coffee to support my work. Thanks!"}),v.jsx("div",{className:"w-full flex items-center justify-center",children:v.jsx("a",{href:"https://ko-fi.com/Z8Z1CZJGY",target:"_blank",rel:"noreferrer",children:v.jsx("img",{src:eZ,className:"h-[32px]"})})})]})]})}const nZ=()=>{const[e,t,n,r,o,i,s,l,u,d,h,m,g,y]=bt(M=>[M.file,M.customMask,M.isInpainting,M.serverConfig,M.runMannually(),M.settings.enableUploadMask,M.settings.model,M.setFile,M.setCustomFile,M.runInpainting,M.showPrevMask,M.hidePrevMask,M.imageHeight,M.imageWidth]),{toast:x}=Td(),[_,C]=Rx(t),[S,b]=f.useState(!1),E=()=>{d()},k=()=>{h()},P=()=>{m()};return v.jsxs("header",{className:"h-[60px] px-6 py-4 absolute top-[0] flex justify-between items-center w-full z-20 border-b backdrop-filter backdrop-blur-md bg-background/70",children:[v.jsxs("div",{className:"flex items-center gap-1",children:[r.enableFileManager?v.jsx(PG,{photoWidth:512,onPhotoClick:async(M,A)=>{try{const O=await Bj(M,A);l(O)}catch(O){x({variant:"destructive",description:O.message?O.message:O.toString()});return}}}):v.jsx(v.Fragment,{}),v.jsx(c1,{disabled:n,tooltip:"Upload image",onFileUpload:M=>{l(M)},children:v.jsx(JU,{})}),v.jsxs("div",{className:Ce(["flex items-center gap-1",e&&i?"visible":"hidden"]),children:[v.jsx(c1,{disabled:n,tooltip:"Upload custom mask",onFileUpload:async M=>{let A=null;try{A=await fF(M)}catch(O){x({variant:"destructive",description:O.message?O.message:O.toString()});return}if(A.naturalHeight!==g||A.naturalWidth!==y){x({variant:"destructive",description:`The size of the mask must same as image: ${y}x${g}`});return}u(M),o||d()},children:v.jsx(ZT,{})}),t?v.jsxs(KW,{open:S,children:[v.jsx(YW,{className:"btn-primary side-panel-trigger",onMouseEnter:()=>b(!0),onMouseLeave:()=>b(!1),style:{visibility:t?"visible":"hidden",outline:"none"},onClick:()=>{},children:v.jsx(vn,{tooltip:"Run custom mask",children:v.jsx(lz,{})})}),v.jsx(PP,{children:C?v.jsx("img",{src:_.src,alt:"Custom mask"}):v.jsx(v.Fragment,{})})]}):v.jsx(v.Fragment,{})]}),e&&!s.need_prompt?v.jsx(vn,{disabled:n,tooltip:"Rerun previous mask",onClick:E,onMouseEnter:k,onMouseLeave:P,children:v.jsx(iV,{})}):v.jsx(v.Fragment,{})]}),s.need_prompt?v.jsx(yH,{}):v.jsx(v.Fragment,{}),v.jsxs("div",{className:"flex gap-1",children:[v.jsx(tZ,{}),v.jsx(OW,{}),r.disableModelSwitch?v.jsx(v.Fragment,{}):v.jsx(JX,{})]})]})};var Wr=function(e,t){return Number(e.toFixed(t))},rZ=function(e,t){return typeof e=="number"?e:t},Nt=function(e,t,n){n&&typeof n=="function"&&n(e,t)},oZ=function(e){return-Math.cos(e*Math.PI)/2+.5},iZ=function(e){return e},sZ=function(e){return e*e},aZ=function(e){return e*(2-e)},lZ=function(e){return e<.5?2*e*e:-1+(4-2*e)*e},cZ=function(e){return e*e*e},uZ=function(e){return--e*e*e+1},dZ=function(e){return e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1},fZ=function(e){return e*e*e*e},pZ=function(e){return 1- --e*e*e*e},hZ=function(e){return e<.5?8*e*e*e*e:1-8*--e*e*e*e},mZ=function(e){return e*e*e*e*e},gZ=function(e){return 1+--e*e*e*e*e},vZ=function(e){return e<.5?16*e*e*e*e*e:1+16*--e*e*e*e*e},b3={easeOut:oZ,linear:iZ,easeInQuad:sZ,easeOutQuad:aZ,easeInOutQuad:lZ,easeInCubic:cZ,easeOutCubic:uZ,easeInOutCubic:dZ,easeInQuart:fZ,easeOutQuart:pZ,easeInOutQuart:hZ,easeInQuint:mZ,easeOutQuint:gZ,easeInOutQuint:vZ},_3=function(e){typeof e=="number"&&cancelAnimationFrame(e)},Do=function(e){e.mounted&&(_3(e.animation),e.animate=!1,e.animation=null,e.velocity=null)};function S3(e,t,n,r){if(e.mounted){var o=new Date().getTime(),i=1;Do(e),e.animation=function(){if(!e.mounted)return _3(e.animation);var s=new Date().getTime()-o,l=s/n,u=b3[t],d=u(l);s>=n?(r(i),e.animation=null):e.animation&&(r(d),requestAnimationFrame(e.animation))},requestAnimationFrame(e.animation)}}function yZ(e){var t=e.scale,n=e.positionX,r=e.positionY;return!(Number.isNaN(t)||Number.isNaN(n)||Number.isNaN(r))}function Ls(e,t,n,r){var o=yZ(t);if(!(!e.mounted||!o)){var i=e.setTransformState,s=e.transformState,l=s.scale,u=s.positionX,d=s.positionY,h=t.scale-l,m=t.positionX-u,g=t.positionY-d;n===0?i(t.scale,t.positionX,t.positionY):S3(e,r,n,function(y){var x=l+h*y,_=u+m*y,C=d+g*y;i(x,_,C)})}}function wZ(e,t,n){var r=e.offsetWidth,o=e.offsetHeight,i=t.offsetWidth,s=t.offsetHeight,l=i*n,u=s*n,d=r-l,h=o-u;return{wrapperWidth:r,wrapperHeight:o,newContentWidth:l,newDiffWidth:d,newContentHeight:u,newDiffHeight:h}}var xZ=function(e,t,n,r,o,i,s){var l=e>t?n*(s?1:.5):0,u=r>o?i*(s?1:.5):0,d=e-t-l,h=l,m=r-o-u,g=u;return{minPositionX:d,maxPositionX:h,minPositionY:m,maxPositionY:g}},Xx=function(e,t){var n=e.wrapperComponent,r=e.contentComponent,o=e.setup.centerZoomedOut;if(!n||!r)throw new Error("Components are not mounted");var i=wZ(n,r,t),s=i.wrapperWidth,l=i.wrapperHeight,u=i.newContentWidth,d=i.newDiffWidth,h=i.newContentHeight,m=i.newDiffHeight,g=xZ(s,u,d,l,h,m,!!o);return g},L1=function(e,t,n,r){return r?en?Wr(n,2):Wr(e,2):Wr(e,2)},dc=function(e,t){var n=Xx(e,t);return e.bounds=n,n};function lg(e,t,n,r,o,i,s){var l=n.minPositionX,u=n.minPositionY,d=n.maxPositionX,h=n.maxPositionY,m=0,g=0;s&&(m=o,g=i);var y=L1(e,l-m,d+m,r),x=L1(t,u-g,h+g,r);return{x:y,y:x}}function cg(e,t,n,r,o,i){var s=e.transformState,l=s.scale,u=s.positionX,d=s.positionY,h=r-l;if(typeof t!="number"||typeof n!="number")return console.error("Mouse X and Y position were not provided!"),{x:u,y:d};var m=u-t*h,g=d-n*h,y=lg(m,g,o,i,0,0,null);return y}function Vd(e,t,n,r,o){var i=o?r:0,s=t-i;return!Number.isNaN(n)&&e>=n?n:!Number.isNaN(t)&&e<=s?s:e}var M2=function(e,t){var n=e.setup.panning.excluded,r=e.isInitialized,o=e.wrapperComponent,i=t.target,s=o==null?void 0:o.contains(i),l=r&&i&&s;if(!l)return!1;var u=ug(i,n);return!u},N2=function(e){var t=e.isInitialized,n=e.isPanning,r=e.setup,o=r.panning.disabled,i=t&&n&&!o;return!!i},bZ=function(e,t){var n=e.transformState,r=n.positionX,o=n.positionY;e.isPanning=!0;var i=t.clientX,s=t.clientY;e.startCoords={x:i-r,y:s-o}},_Z=function(e,t){var n=t.touches,r=e.transformState,o=r.positionX,i=r.positionY;e.isPanning=!0;var s=n.length===1;if(s){var l=n[0].clientX,u=n[0].clientY;e.startCoords={x:l-o,y:u-i}}};function SZ(e){var t=e.transformState,n=t.positionX,r=t.positionY,o=t.scale,i=e.setup,s=i.disabled,l=i.limitToBounds,u=i.centerZoomedOut,d=e.wrapperComponent;if(!(s||!d||!e.bounds)){var h=e.bounds,m=h.maxPositionX,g=h.minPositionX,y=h.maxPositionY,x=h.minPositionY,_=n>m||ny||rm?d.offsetWidth:e.setup.minPositionX||0,b=r>y?d.offsetHeight:e.setup.minPositionY||0,E=cg(e,S,b,o,e.bounds,l||u),k=E.x,P=E.y;return{scale:o,positionX:_?k:n,positionY:C?P:r}}}function EZ(e,t,n,r,o){var i=e.setup.limitToBounds,s=e.wrapperComponent,l=e.bounds,u=e.transformState,d=u.scale,h=u.positionX,m=u.positionY;if(!(s===null||l===null||t===h&&n===m)){var g=lg(t,n,l,i,r,o,s),y=g.x,x=g.y;e.setTransformState(d,y,x)}}var CZ=function(e,t,n){var r=e.startCoords,o=e.transformState,i=e.setup.panning,s=i.lockAxisX,l=i.lockAxisY,u=o.positionX,d=o.positionY;if(!r)return{x:u,y:d};var h=t-r.x,m=n-r.y,g=s?u:h,y=l?d:m;return{x:g,y}},rm=function(e,t){var n=e.setup,r=e.transformState,o=r.scale,i=n.minScale,s=n.disablePadding;return t>0&&o>=i&&!s?t:0},$Z=function(e){var t=e.mounted,n=e.setup,r=n.disabled,o=n.velocityAnimation,i=e.transformState.scale,s=o.disabled,l=!s||i>1||!r||t;return!!l},kZ=function(e){var t=e.mounted,n=e.velocity,r=e.bounds,o=e.setup,i=o.disabled,s=o.velocityAnimation,l=e.transformState.scale,u=s.disabled,d=!u||l>1||!i||t;return!(!d||!n||!r)};function RZ(e,t){var n=e.setup.velocityAnimation,r=n.equalToMove,o=n.animationTime,i=n.sensitivity;return r?o*t*i:o}function D2(e,t,n,r,o,i,s,l,u,d){if(o){if(t>s&&n>s){var h=s+(e-s)*d;return h>u?u:hi?i:h}}return r?t:L1(e,i,s,o)}function TZ(e,t){var n=1;return t?Math.min(n,e.offsetWidth/window.innerWidth):n}function PZ(e,t){var n=$Z(e);if(n){var r=e.lastMousePosition,o=e.velocityTime,i=e.setup,s=e.wrapperComponent,l=i.velocityAnimation.equalToMove,u=Date.now();if(r&&o&&s){var d=TZ(s,l),h=t.x-r.x,m=t.y-r.y,g=h/d,y=m/d,x=u-o,_=h*h+m*m,C=Math.sqrt(_)/x;e.velocity={velocityX:g,velocityY:y,total:C}}e.lastMousePosition=t,e.velocityTime=u}}function AZ(e){var t=e.velocity,n=e.bounds,r=e.setup,o=e.wrapperComponent,i=kZ(e);if(!(!i||!t||!n||!o)){var s=t.velocityX,l=t.velocityY,u=t.total,d=n.maxPositionX,h=n.minPositionX,m=n.maxPositionY,g=n.minPositionY,y=r.limitToBounds,x=r.alignmentAnimation,_=r.zoomAnimation,C=r.panning,S=C.lockAxisY,b=C.lockAxisX,E=_.animationType,k=x.sizeX,P=x.sizeY,M=x.velocityAlignmentTime,A=M,O=RZ(e,u),F=Math.max(O,A),V=rm(e,k),J=rm(e,P),G=V*o.offsetWidth/100,ae=J*o.offsetHeight/100,U=d+G,te=h-G,L=m+ae,ie=g-ae,K=e.transformState,Q=new Date().getTime();S3(e,E,F,function(W){var le=e.transformState,ge=le.scale,Ve=le.positionX,Ue=le.positionY,We=new Date().getTime()-Q,Me=We/A,fe=b3[x.animationType],xe=1-fe(Math.min(1,Me)),$e=1-W,Ae=Ve+s*$e,Oe=Ue+l*$e,je=D2(Ae,K.positionX,Ve,b,y,h,d,te,U,xe),Ot=D2(Oe,K.positionY,Ue,S,y,g,m,ie,L,xe);(Ve!==Ae||Ue!==Oe)&&e.setTransformState(ge,je,Ot)})}}function I2(e,t){var n=e.transformState.scale;Do(e),dc(e,n),window.TouchEvent!==void 0&&t instanceof TouchEvent?_Z(e,t):bZ(e,t)}function E3(e){var t=e.transformState.scale,n=e.setup,r=n.minScale,o=n.alignmentAnimation,i=o.disabled,s=o.sizeX,l=o.sizeY,u=o.animationTime,d=o.animationType,h=i||t.1&&m;g?AZ(e):E3(e)}}function Zx(e,t,n,r){var o=e.setup,i=o.minScale,s=o.maxScale,l=o.limitToBounds,u=Vd(Wr(t,2),i,s,0,!1),d=dc(e,u),h=cg(e,n,r,u,d,l),m=h.x,g=h.y;return{scale:u,positionX:m,positionY:g}}function C3(e,t,n){var r=e.transformState.scale,o=e.wrapperComponent,i=e.setup,s=i.minScale,l=i.limitToBounds,u=i.zoomAnimation,d=u.disabled,h=u.animationTime,m=u.animationType,g=d||r>=s;if((r>=1||l)&&E3(e),!(g||!o||!e.mounted)){var y=t||o.offsetWidth/2,x=n||o.offsetHeight/2,_=Zx(e,s,y,x);_&&Ls(e,_,h,m)}}var _s=function(){return _s=Object.assign||function(t){for(var n,r=1,o=arguments.length;rs||Math.sign(n.deltaY)!==Math.sign(t.deltaY)||n.deltaY>0&&n.deltaYt.deltaY||Math.sign(n.deltaY)!==Math.sign(t.deltaY):!1},XZ=function(e,t){var n=e.setup.pinch,r=n.disabled,o=n.excluded,i=e.isInitialized,s=t.target,l=i&&!r&&s;if(!l)return!1;var u=ug(s,o);return!u},ZZ=function(e){var t=e.setup.pinch.disabled,n=e.isInitialized,r=e.pinchStartDistance,o=n&&!t&&r;return!!o},qZ=function(e,t,n){var r=n.getBoundingClientRect(),o=e.touches,i=Wr(o[0].clientX-r.left,5),s=Wr(o[0].clientY-r.top,5),l=Wr(o[1].clientX-r.left,5),u=Wr(o[1].clientY-r.top,5);return{x:(i+l)/2/t,y:(s+u)/2/t}},O3=function(e){return Math.sqrt(Math.pow(e.touches[0].pageX-e.touches[1].pageX,2)+Math.pow(e.touches[0].pageY-e.touches[1].pageY,2))},QZ=function(e,t){var n=e.pinchStartScale,r=e.pinchStartDistance,o=e.setup,i=o.maxScale,s=o.minScale,l=o.zoomAnimation,u=o.disablePadding,d=l.size,h=l.disabled;if(!n||r===null||!t)throw new Error("Pinch touches distance was not provided");if(t<0)return e.transformState.scale;var m=t/r,g=m*n;return Vd(Wr(g,2),s,i,d,!h&&!u)},JZ=160,eq=100,tq=function(e,t){var n=e.props,r=n.onWheelStart,o=n.onZoomStart;e.wheelStopEventTimer||(Do(e),Nt(St(e),t,r),Nt(St(e),t,o))},nq=function(e,t){var n=e.props,r=n.onWheel,o=n.onZoom,i=e.contentComponent,s=e.setup,l=e.transformState,u=l.scale,d=s.limitToBounds,h=s.centerZoomedOut,m=s.zoomAnimation,g=s.wheel,y=s.disablePadding,x=s.smooth,_=m.size,C=m.disabled,S=g.step,b=g.smoothStep;if(!i)throw new Error("Component not mounted");t.preventDefault(),t.stopPropagation();var E=KZ(t,null),k=x?b*Math.abs(t.deltaY):S,P=YZ(e,E,k,!t.ctrlKey);if(u!==P){var M=dc(e,P),A=A3(t,i,u),O=C||_===0||h||y,F=d&&O,V=cg(e,A.x,A.y,P,M,F),J=V.x,G=V.y;e.previousWheelEvent=t,e.setTransformState(P,J,G),Nt(St(e),t,r),Nt(St(e),t,o)}},rq=function(e,t){var n=e.props,r=n.onWheelStop,o=n.onZoomStop;j1(e.wheelAnimationTimer),e.wheelAnimationTimer=setTimeout(function(){e.mounted&&(C3(e,t.x,t.y),e.wheelAnimationTimer=null)},eq);var i=GZ(e,t);i&&(j1(e.wheelStopEventTimer),e.wheelStopEventTimer=setTimeout(function(){e.mounted&&(e.wheelStopEventTimer=null,Nt(St(e),t,r),Nt(St(e),t,o))},JZ))},oq=function(e,t){var n=O3(t);e.pinchStartDistance=n,e.lastDistance=n,e.pinchStartScale=e.transformState.scale,e.isPanning=!1,Do(e)},iq=function(e,t){var n=e.contentComponent,r=e.pinchStartDistance,o=e.transformState.scale,i=e.setup,s=i.limitToBounds,l=i.centerZoomedOut,u=i.zoomAnimation,d=u.disabled,h=u.size;if(!(r===null||!n)){var m=qZ(t,o,n);if(!(!Number.isFinite(m.x)||!Number.isFinite(m.y))){var g=O3(t),y=QZ(e,g);if(y!==o){var x=dc(e,y),_=d||h===0||l,C=s&&_,S=cg(e,m.x,m.y,y,x,C),b=S.x,E=S.y;e.pinchMidpoint=m,e.lastDistance=g,e.setTransformState(y,b,E)}}}},sq=function(e){var t=e.pinchMidpoint;e.velocity=null,e.lastDistance=null,e.pinchMidpoint=null,e.pinchStartScale=null,e.pinchStartDistance=null,C3(e,t==null?void 0:t.x,t==null?void 0:t.y)},M3=function(e,t){var n=e.props.onZoomStop,r=e.setup.doubleClick.animationTime;j1(e.doubleClickStopEventTimer),e.doubleClickStopEventTimer=setTimeout(function(){e.doubleClickStopEventTimer=null,Nt(St(e),t,n)},r)},aq=function(e,t){var n=e.props,r=n.onZoomStart,o=n.onZoom,i=e.setup.doubleClick,s=i.animationTime,l=i.animationType;Nt(St(e),t,r),T3(e,s,l,function(){return Nt(St(e),t,o)}),M3(e,t)};function lq(e,t){var n=e.setup,r=e.doubleClickStopEventTimer,o=e.transformState,i=e.contentComponent,s=o.scale,l=e.props,u=l.onZoomStart,d=l.onZoom,h=n.doubleClick,m=h.disabled,g=h.mode,y=h.step,x=h.animationTime,_=h.animationType;if(!m&&!r){if(g==="reset")return aq(e,t);if(!i)return console.error("No ContentComponent found");var C=g==="zoomOut"?-1:1,S=k3(e,C,y);if(s!==S){Nt(St(e),t,u);var b=A3(t,i,s),E=Zx(e,S,b.x,b.y);if(!E)return console.error("Error during zoom event. New transformation state was not calculated.");Nt(St(e),t,d),Ls(e,E,x,_),M3(e,t)}}}var cq=function(e,t){var n=e.isInitialized,r=e.setup,o=e.wrapperComponent,i=r.doubleClick,s=i.disabled,l=i.excluded,u=t.target,d=o==null?void 0:o.contains(u),h=n&&u&&d&&!s;if(!h)return!1;var m=ug(u,l);return!m},uq=function(){function e(t){var n=this;this.mounted=!0,this.onChangeCallbacks=new Set,this.onInitCallbacks=new Set,this.wrapperComponent=null,this.contentComponent=null,this.isInitialized=!1,this.bounds=null,this.previousWheelEvent=null,this.wheelStopEventTimer=null,this.wheelAnimationTimer=null,this.isPanning=!1,this.startCoords=null,this.lastTouch=null,this.distance=null,this.lastDistance=null,this.pinchStartDistance=null,this.pinchStartScale=null,this.pinchMidpoint=null,this.doubleClickStopEventTimer=null,this.velocity=null,this.velocityTime=null,this.lastMousePosition=null,this.animate=!1,this.animation=null,this.maxBounds=null,this.pressedKeys={},this.mount=function(){n.initializeWindowEvents()},this.unmount=function(){n.cleanupWindowEvents()},this.update=function(r){dc(n,n.transformState.scale),n.setup=j2(r)},this.initializeWindowEvents=function(){var r,o=I0(),i=(r=n.wrapperComponent)===null||r===void 0?void 0:r.ownerDocument,s=i==null?void 0:i.defaultView;s==null||s.addEventListener("mousedown",n.onPanningStart,o),s==null||s.addEventListener("mousemove",n.onPanning,o),s==null||s.addEventListener("mouseup",n.onPanningStop,o),i==null||i.addEventListener("mouseleave",n.clearPanning,o),s==null||s.addEventListener("keyup",n.setKeyUnPressed,o),s==null||s.addEventListener("keydown",n.setKeyPressed,o)},this.cleanupWindowEvents=function(){var r,o,i=I0(),s=(r=n.wrapperComponent)===null||r===void 0?void 0:r.ownerDocument,l=s==null?void 0:s.defaultView;l==null||l.removeEventListener("mousedown",n.onPanningStart,i),l==null||l.removeEventListener("mousemove",n.onPanning,i),l==null||l.removeEventListener("mouseup",n.onPanningStop,i),s==null||s.removeEventListener("mouseleave",n.clearPanning,i),l==null||l.removeEventListener("keyup",n.setKeyUnPressed,i),l==null||l.removeEventListener("keydown",n.setKeyPressed,i),document.removeEventListener("mouseleave",n.clearPanning,i),Do(n),(o=n.observer)===null||o===void 0||o.disconnect()},this.handleInitializeWrapperEvents=function(r){var o=I0();r.addEventListener("wheel",n.onWheelZoom,o),r.addEventListener("dblclick",n.onDoubleClick,o),r.addEventListener("touchstart",n.onTouchPanningStart,o),r.addEventListener("touchmove",n.onTouchPanning,o),r.addEventListener("touchend",n.onTouchPanningStop,o)},this.handleInitialize=function(r){var o=n.setup.centerOnInit;n.applyTransformation(),n.onInitCallbacks.forEach(function(i){return i(St(n))}),o&&(n.setCenter(),n.observer=new ResizeObserver(function(){var i;n.onInitCallbacks.forEach(function(s){return s(St(n))}),n.setCenter(),(i=n.observer)===null||i===void 0||i.disconnect()}),n.observer.observe(r))},this.onWheelZoom=function(r){var o=n.setup.disabled;if(!o){var i=WZ(n,r);if(i){var s=n.isPressingKeys(n.setup.wheel.activationKeys);s&&(tq(n,r),nq(n,r),rq(n,r))}}},this.onPanningStart=function(r){var o=n.setup.disabled,i=n.props.onPanningStart;if(!o){var s=M2(n,r);if(s){var l=n.isPressingKeys(n.setup.panning.activationKeys);l&&(r.button===0&&!n.setup.panning.allowLeftClickPan||r.button===1&&!n.setup.panning.allowMiddleClickPan||r.button===2&&!n.setup.panning.allowRightClickPan||(r.preventDefault(),r.stopPropagation(),Do(n),I2(n,r),Nt(St(n),r,i)))}}},this.onPanning=function(r){var o=n.setup.disabled,i=n.props.onPanning;if(!o){var s=N2(n);if(s){var l=n.isPressingKeys(n.setup.panning.activationKeys);l&&(r.preventDefault(),r.stopPropagation(),L2(n,r.clientX,r.clientY),Nt(St(n),r,i))}}},this.onPanningStop=function(r){var o=n.props.onPanningStop;n.isPanning&&(OZ(n),Nt(St(n),r,o))},this.onPinchStart=function(r){var o=n.setup.disabled,i=n.props,s=i.onPinchingStart,l=i.onZoomStart;if(!o){var u=XZ(n,r);u&&(oq(n,r),Do(n),Nt(St(n),r,s),Nt(St(n),r,l))}},this.onPinch=function(r){var o=n.setup.disabled,i=n.props,s=i.onPinching,l=i.onZoom;if(!o){var u=ZZ(n);u&&(r.preventDefault(),r.stopPropagation(),iq(n,r),Nt(St(n),r,s),Nt(St(n),r,l))}},this.onPinchStop=function(r){var o=n.props,i=o.onPinchingStop,s=o.onZoomStop;n.pinchStartScale&&(sq(n),Nt(St(n),r,i),Nt(St(n),r,s))},this.onTouchPanningStart=function(r){var o=n.setup.disabled,i=n.props.onPanningStart;if(!o){var s=M2(n,r);if(s){var l=n.lastTouch&&+new Date-n.lastTouch<200;if(l&&r.touches.length===1)n.onDoubleClick(r);else{n.lastTouch=+new Date,Do(n);var u=r.touches,d=u.length===1,h=u.length===2;d&&(Do(n),I2(n,r),Nt(St(n),r,i)),h&&n.onPinchStart(r)}}}},this.onTouchPanning=function(r){var o=n.setup.disabled,i=n.props.onPanning;if(n.isPanning&&r.touches.length===1){if(o)return;var s=N2(n);if(!s)return;r.preventDefault(),r.stopPropagation();var l=r.touches[0];L2(n,l.clientX,l.clientY),Nt(St(n),r,i)}else r.touches.length>1&&n.onPinch(r)},this.onTouchPanningStop=function(r){n.onPanningStop(r),n.onPinchStop(r)},this.onDoubleClick=function(r){var o=n.setup.disabled;if(!o){var i=cq(n,r);i&&lq(n,r)}},this.clearPanning=function(r){n.isPanning&&n.onPanningStop(r)},this.setKeyPressed=function(r){n.pressedKeys[r.key]=!0},this.setKeyUnPressed=function(r){n.pressedKeys[r.key]=!1},this.isPressingKeys=function(r){return r.length?!!r.find(function(o){return n.pressedKeys[o]}):!0},this.setTransformState=function(r,o,i){var s=n.props.onTransformed;if(!Number.isNaN(r)&&!Number.isNaN(o)&&!Number.isNaN(i)){r!==n.transformState.scale&&(n.transformState.previousScale=n.transformState.scale,n.transformState.scale=r),n.transformState.positionX=o,n.transformState.positionY=i,n.applyTransformation();var l=St(n);n.onChangeCallbacks.forEach(function(u){return u(l)}),Nt(l,{scale:r,positionX:o,positionY:i},s)}else console.error("Detected NaN set state values")},this.setCenter=function(){if(n.wrapperComponent&&n.contentComponent){var r=P3(n.transformState.scale,n.wrapperComponent,n.contentComponent);n.setTransformState(r.scale,r.positionX,r.positionY)}},this.handleTransformStyles=function(r,o,i){return n.props.customTransform?n.props.customTransform(r,o,i):UZ(r,o,i)},this.applyTransformation=function(){if(!(!n.mounted||!n.contentComponent)){var r=n.transformState,o=r.scale,i=r.positionX,s=r.positionY,l=n.handleTransformStyles(i,s,o);n.contentComponent.style.transform=l}},this.getContext=function(){return St(n)},this.onChange=function(r){return n.onChangeCallbacks.has(r)||n.onChangeCallbacks.add(r),function(){n.onChangeCallbacks.delete(r)}},this.onInit=function(r){return n.onInitCallbacks.has(r)||n.onInitCallbacks.add(r),function(){n.onInitCallbacks.delete(r)}},this.init=function(r,o){n.cleanupWindowEvents(),n.wrapperComponent=r,n.contentComponent=o,dc(n,n.transformState.scale),n.handleInitializeWrapperEvents(r),n.handleInitialize(o),n.initializeWindowEvents(),n.isInitialized=!0;var i=St(n);Nt(i,void 0,n.props.onInit)},this.props=t,this.setup=j2(this.props),this.transformState=$3(this.props)}return e}(),qx=Fe.createContext(null),dq=function(e,t){return typeof e=="function"?e(t):e},fq=Fe.forwardRef(function(e,t){var n=f.useRef(new uq(e)).current,r=dq(e.children,F1(n));return f.useImperativeHandle(t,function(){return F1(n)},[n]),f.useEffect(function(){n.update(e)},[n,e]),Fe.createElement(qx.Provider,{value:n},r)});Fe.forwardRef(function(e,t){var n=f.useRef(null),r=f.useContext(qx);return f.useEffect(function(){return r.onChange(function(o){if(n.current){var i=0,s=0;n.current.style.transform=r.handleTransformStyles(i,s,1/o.instance.transformState.scale)}})},[r]),Fe.createElement("div",_s({},e,{ref:VZ([n,t])}))});function pq(e,t){t===void 0&&(t={});var n=t.insertAt;if(!(!e||typeof document>"u")){var r=document.head||document.getElementsByTagName("head")[0],o=document.createElement("style");o.type="text/css",n==="top"&&r.firstChild?r.insertBefore(o,r.firstChild):r.appendChild(o),o.styleSheet?o.styleSheet.cssText=e:o.appendChild(document.createTextNode(e))}}var hq=`.transform-component-module_wrapper__SPB86 { + position: relative; + width: -moz-fit-content; + width: fit-content; + height: -moz-fit-content; + height: fit-content; + overflow: hidden; + -webkit-touch-callout: none; /* iOS Safari */ + -webkit-user-select: none; /* Safari */ + -khtml-user-select: none; /* Konqueror HTML */ + -moz-user-select: none; /* Firefox */ + -ms-user-select: none; /* Internet Explorer/Edge */ + user-select: none; + margin: 0; + padding: 0; +} +.transform-component-module_content__FBWxo { + display: flex; + flex-wrap: wrap; + width: -moz-fit-content; + width: fit-content; + height: -moz-fit-content; + height: fit-content; + margin: 0; + padding: 0; + transform-origin: 0% 0%; +} +.transform-component-module_content__FBWxo img { + pointer-events: none; +} +`,z2={wrapper:"transform-component-module_wrapper__SPB86",content:"transform-component-module_content__FBWxo"};pq(hq);var mq=function(e){var t=e.children,n=e.wrapperClass,r=n===void 0?"":n,o=e.contentClass,i=o===void 0?"":o,s=e.wrapperStyle,l=e.contentStyle,u=e.wrapperProps,d=u===void 0?{}:u,h=e.contentProps,m=h===void 0?{}:h,g=f.useContext(qx),y=g.init,x=g.cleanupWindowEvents,_=f.useRef(null),C=f.useRef(null);return f.useEffect(function(){var S=_.current,b=C.current;return S!==null&&b!==null&&y&&(y==null||y(S,b)),function(){x==null||x()}},[]),Fe.createElement("div",_s({},d,{ref:_,className:"react-transform-wrapper ".concat(z2.wrapper," ").concat(r),style:s}),Fe.createElement("div",_s({},m,{ref:C,className:"react-transform-component ".concat(z2.content," ").concat(i),style:l}),t))};const N3=["PageUp","PageDown"],D3=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],I3={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},Wd="Slider",[z1,gq,vq]=zd(Wd),[L3,Cte]=An(Wd,[vq]),[yq,dg]=L3(Wd),wq=f.forwardRef((e,t)=>{const{name:n,min:r=0,max:o=100,step:i=1,orientation:s="horizontal",disabled:l=!1,minStepsBetweenThumbs:u=0,defaultValue:d=[r],value:h,onValueChange:m=()=>{},onValueCommit:g=()=>{},inverted:y=!1,...x}=e,[_,C]=f.useState(null),S=Be(t,U=>C(U)),b=f.useRef(new Set),E=f.useRef(0),k=s==="horizontal",P=_?!!_.closest("form"):!0,M=k?xq:bq,[A=[],O]=Zr({prop:h,defaultProp:d,onChange:U=>{var te;(te=[...b.current][E.current])===null||te===void 0||te.focus(),m(U)}}),F=f.useRef(A);function V(U){const te=Pq(A,U);ae(U,te)}function J(U){ae(U,E.current)}function G(){const U=F.current[E.current];A[E.current]!==U&&g(A)}function ae(U,te,{commit:L}={commit:!1}){const ie=Nq(i),K=Dq(Math.round((U-r)/i)*i+r,ie),Q=id(K,[r,o]);O((W=[])=>{const le=Rq(W,Q,te);if(Mq(le,u*i)){E.current=le.indexOf(Q);const ge=String(le)!==String(W);return ge&&L&&g(le),ge?le:W}else return W})}return f.createElement(yq,{scope:e.__scopeSlider,disabled:l,min:r,max:o,valueIndexToChangeRef:E,thumbs:b.current,values:A,orientation:s},f.createElement(z1.Provider,{scope:e.__scopeSlider},f.createElement(z1.Slot,{scope:e.__scopeSlider},f.createElement(M,Y({"aria-disabled":l,"data-disabled":l?"":void 0},x,{ref:S,onPointerDown:ue(x.onPointerDown,()=>{l||(F.current=A)}),min:r,max:o,inverted:y,onSlideStart:l?void 0:V,onSlideMove:l?void 0:J,onSlideEnd:l?void 0:G,onHomeKeyDown:()=>!l&&ae(r,0,{commit:!0}),onEndKeyDown:()=>!l&&ae(o,A.length-1,{commit:!0}),onStepKeyDown:({event:U,direction:te})=>{if(!l){const K=N3.includes(U.key)||U.shiftKey&&D3.includes(U.key)?10:1,Q=E.current,W=A[Q],le=i*K*te;ae(W+le,Q,{commit:!0})}}})))),P&&A.map((U,te)=>f.createElement(kq,{key:te,name:n?n+(A.length>1?"[]":""):void 0,value:U})))}),[F3,j3]=L3(Wd,{startEdge:"left",endEdge:"right",size:"width",direction:1}),xq=f.forwardRef((e,t)=>{const{min:n,max:r,dir:o,inverted:i,onSlideStart:s,onSlideMove:l,onSlideEnd:u,onStepKeyDown:d,...h}=e,[m,g]=f.useState(null),y=Be(t,E=>g(E)),x=f.useRef(),_=Sc(o),C=_==="ltr",S=C&&!i||!C&&i;function b(E){const k=x.current||m.getBoundingClientRect(),P=[0,k.width],A=Qx(P,S?[n,r]:[r,n]);return x.current=k,A(E-k.left)}return f.createElement(F3,{scope:e.__scopeSlider,startEdge:S?"left":"right",endEdge:S?"right":"left",direction:S?1:-1,size:"width"},f.createElement(z3,Y({dir:_,"data-orientation":"horizontal"},h,{ref:y,style:{...h.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:E=>{const k=b(E.clientX);s==null||s(k)},onSlideMove:E=>{const k=b(E.clientX);l==null||l(k)},onSlideEnd:()=>{x.current=void 0,u==null||u()},onStepKeyDown:E=>{const P=I3[S?"from-left":"from-right"].includes(E.key);d==null||d({event:E,direction:P?-1:1})}})))}),bq=f.forwardRef((e,t)=>{const{min:n,max:r,inverted:o,onSlideStart:i,onSlideMove:s,onSlideEnd:l,onStepKeyDown:u,...d}=e,h=f.useRef(null),m=Be(t,h),g=f.useRef(),y=!o;function x(_){const C=g.current||h.current.getBoundingClientRect(),S=[0,C.height],E=Qx(S,y?[r,n]:[n,r]);return g.current=C,E(_-C.top)}return f.createElement(F3,{scope:e.__scopeSlider,startEdge:y?"bottom":"top",endEdge:y?"top":"bottom",size:"height",direction:y?1:-1},f.createElement(z3,Y({"data-orientation":"vertical"},d,{ref:m,style:{...d.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:_=>{const C=x(_.clientY);i==null||i(C)},onSlideMove:_=>{const C=x(_.clientY);s==null||s(C)},onSlideEnd:()=>{g.current=void 0,l==null||l()},onStepKeyDown:_=>{const S=I3[y?"from-bottom":"from-top"].includes(_.key);u==null||u({event:_,direction:S?-1:1})}})))}),z3=f.forwardRef((e,t)=>{const{__scopeSlider:n,onSlideStart:r,onSlideMove:o,onSlideEnd:i,onHomeKeyDown:s,onEndKeyDown:l,onStepKeyDown:u,...d}=e,h=dg(Wd,n);return f.createElement(Pe.span,Y({},d,{ref:t,onKeyDown:ue(e.onKeyDown,m=>{m.key==="Home"?(s(m),m.preventDefault()):m.key==="End"?(l(m),m.preventDefault()):N3.concat(D3).includes(m.key)&&(u(m),m.preventDefault())}),onPointerDown:ue(e.onPointerDown,m=>{const g=m.target;g.setPointerCapture(m.pointerId),m.preventDefault(),h.thumbs.has(g)?g.focus():r(m)}),onPointerMove:ue(e.onPointerMove,m=>{m.target.hasPointerCapture(m.pointerId)&&o(m)}),onPointerUp:ue(e.onPointerUp,m=>{const g=m.target;g.hasPointerCapture(m.pointerId)&&(g.releasePointerCapture(m.pointerId),i(m))})}))}),_q="SliderTrack",Sq=f.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,o=dg(_q,n);return f.createElement(Pe.span,Y({"data-disabled":o.disabled?"":void 0,"data-orientation":o.orientation},r,{ref:t}))}),B2="SliderRange",Eq=f.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,o=dg(B2,n),i=j3(B2,n),s=f.useRef(null),l=Be(t,s),u=o.values.length,d=o.values.map(g=>B3(g,o.min,o.max)),h=u>1?Math.min(...d):0,m=100-Math.max(...d);return f.createElement(Pe.span,Y({"data-orientation":o.orientation,"data-disabled":o.disabled?"":void 0},r,{ref:l,style:{...e.style,[i.startEdge]:h+"%",[i.endEdge]:m+"%"}}))}),U2="SliderThumb",Cq=f.forwardRef((e,t)=>{const n=gq(e.__scopeSlider),[r,o]=f.useState(null),i=Be(t,l=>o(l)),s=f.useMemo(()=>r?n().findIndex(l=>l.ref.current===r):-1,[n,r]);return f.createElement($q,Y({},e,{ref:i,index:s}))}),$q=f.forwardRef((e,t)=>{const{__scopeSlider:n,index:r,...o}=e,i=dg(U2,n),s=j3(U2,n),[l,u]=f.useState(null),d=Be(t,C=>u(C)),h=gx(l),m=i.values[r],g=m===void 0?0:B3(m,i.min,i.max),y=Tq(r,i.values.length),x=h==null?void 0:h[s.size],_=x?Aq(x,g,s.direction):0;return f.useEffect(()=>{if(l)return i.thumbs.add(l),()=>{i.thumbs.delete(l)}},[l,i.thumbs]),f.createElement("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[s.startEdge]:`calc(${g}% + ${_}px)`}},f.createElement(z1.ItemSlot,{scope:e.__scopeSlider},f.createElement(Pe.span,Y({role:"slider","aria-label":e["aria-label"]||y,"aria-valuemin":i.min,"aria-valuenow":m,"aria-valuemax":i.max,"aria-orientation":i.orientation,"data-orientation":i.orientation,"data-disabled":i.disabled?"":void 0,tabIndex:i.disabled?void 0:0},o,{ref:d,style:m===void 0?{display:"none"}:e.style,onFocus:ue(e.onFocus,()=>{i.valueIndexToChangeRef.current=r})}))))}),kq=e=>{const{value:t,...n}=e,r=f.useRef(null),o=Fx(t);return f.useEffect(()=>{const i=r.current,s=window.HTMLInputElement.prototype,u=Object.getOwnPropertyDescriptor(s,"value").set;if(o!==t&&u){const d=new Event("input",{bubbles:!0});u.call(i,t),i.dispatchEvent(d)}},[o,t]),f.createElement("input",Y({style:{display:"none"}},n,{ref:r,defaultValue:t}))};function Rq(e=[],t,n){const r=[...e];return r[n]=t,r.sort((o,i)=>o-i)}function B3(e,t,n){const i=100/(n-t)*(e-t);return id(i,[0,100])}function Tq(e,t){return t>2?`Value ${e+1} of ${t}`:t===2?["Minimum","Maximum"][e]:void 0}function Pq(e,t){if(e.length===1)return 0;const n=e.map(o=>Math.abs(o-t)),r=Math.min(...n);return n.indexOf(r)}function Aq(e,t,n){const r=e/2,i=Qx([0,50],[0,r]);return(r-i(t)*n)*n}function Oq(e){return e.slice(0,-1).map((t,n)=>e[n+1]-t)}function Mq(e,t){if(t>0){const n=Oq(e);return Math.min(...n)>=t}return!0}function Qx(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 Nq(e){return(String(e).split(".")[1]||"").length}function Dq(e,t){const n=Math.pow(10,t);return Math.round(e*n)/n}const U3=wq,Iq=Sq,Lq=Eq,Fq=Cq,uo=f.forwardRef(({className:e,...t},n)=>v.jsxs(U3,{ref:n,className:Ce("relative flex w-full touch-none select-none items-center",e),tabIndex:-1,...t,children:[v.jsx(Iq,{className:"relative h-1.5 w-full grow overflow-hidden rounded-full bg-primary/20 data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50",children:v.jsx(Lq,{className:"absolute h-full bg-primary data-[disabled]:cursor-not-allowed "})}),v.jsx(Fq,{tabIndex:-1,className:"block h-4 w-4 rounded-full border border-primary/60 bg-background shadow transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring data-[disabled]:cursor-not-allowed"})]}));uo.displayName=U3.displayName;const tl={capture:!0,passive:!1},jq=2,V2=(e,t,n,r,o,i)=>{if(e!==n&&t===r){if(e<0)return[0,r];if(e+t>i)return[i-r,r]}else{if(ti)return[e,i-e]}return[e,t]},zq=e=>{const{minHeight:t,minWidth:n,maxHeight:r,maxWidth:o,scale:i,show:s}=e,[l,u,d,h,{x:m,y:g,width:y,height:x},_,C,S,b,E,k]=bt(W=>[W.imageWidth,W.imageHeight,W.isInpainting,W.isSD(),W.cropperState,W.setCropperX,W.setCropperY,W.setCropperWidth,W.setCropperHeight,W.isCropperExtenderResizing,W.setIsCropperExtenderResizing]),[P,M]=f.useState(!1);f.useEffect(()=>{_(Math.round((o-512)/2)),C(Math.round((r-512)/2))},[r,o,l,u]);const[A,O]=f.useState({initX:0,initY:0,initHeight:0,initWidth:0,startResizeX:0,startResizeY:0,ord:"top"}),F=()=>{},V=(W,le)=>V2(W,le,m,y,n,o),J=(W,le)=>V2(W,le,g,x,t,r),G=W=>{if(d)return;const le=W.clientX,ge=W.clientY,Ve=Math.round((ge-A.startResizeY)/i),Ue=Math.round((le-A.startResizeX)/i),We=()=>{const $e=A.initHeight-Ve,Ae=A.initY+Ve,[Oe,je]=J(Ae,$e);b(je),C(Oe)},Me=()=>{const $e=A.initHeight+Ve,[Ae,Oe]=J(A.initY,$e);b(Oe),C(Ae)},fe=()=>{const $e=A.initWidth-Ue,Ae=A.initX+Ue,[Oe,je]=V(Ae,$e);S(je),_(Oe)},xe=()=>{const $e=A.initWidth+Ue,[Ae,Oe]=V(A.initX,$e);S(Oe),_(Ae)};if(E)switch(A.ord){case"topleft":{We(),fe();break}case"topright":{We(),xe();break}case"bottomleft":{Me(),fe();break}case"bottomright":{Me(),xe();break}case"top":{We();break}case"right":{xe();break}case"bottom":{Me();break}case"left":{fe();break}}if(P){const $e=A.initX+Ue,Ae=A.initY+Ve,[Oe,je]=V($e,A.initWidth),[Ot,ct]=J(Ae,A.initHeight);S(je),b(ct),_(Oe),C(Ot)}},ae=()=>{E&&k(!1),P&&M(!1)};f.useEffect(()=>{if(E||P)return document.addEventListener("pointermove",G,tl),document.addEventListener("pointerup",ae,tl),document.addEventListener("pointercancel",ae,tl),()=>{document.removeEventListener("pointermove",G,tl),document.removeEventListener("pointerup",ae,tl),document.removeEventListener("pointercancel",ae,tl)}},[E,P,y,x,A]);const U=W=>{const{ord:le}=W.target.dataset;le&&(k(!0),O({initX:m,initY:g,initHeight:x,initWidth:y,startResizeX:W.clientX,startResizeY:W.clientY,ord:le}))},te=(W,le,ge)=>{const We="w-[12px] h-[12px] z-[4] absolute content-[''] block border-2 border-primary borde pointer-events-auto hover:bg-primary";let Me="0",fe="0",xe=ge,$e="-6px";return ge===""&&($e="50%",le==="left"||le==="right"?(xe="top",fe="-50%"):(xe="left",Me="-50%")),v.jsx("div",{className:Ce(We,W),style:{[le]:-6,[xe]:$e,transform:`translate(${Me}, ${fe}) scale(${1/i})`},"data-ord":le+ge,"aria-label":le+ge,tabIndex:-1,role:"button"})},L=()=>v.jsxs("div",{onFocus:F,onPointerDown:U,className:"absolute top-0 h-full w-full",children:[v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 w-full cursor-ns-resize h-[12px] mt-[-6px]","data-ord":"top"}),v.jsx("div",{className:"absolute pointer-events-auto top-0 right-0 h-full cursor-ew-resize w-[12px] mr-[-6px]","data-ord":"right"}),v.jsx("div",{className:"absolute pointer-events-auto bottom-0 left-0 w-full cursor-ns-resize h-[12px] mb-[-6px]","data-ord":"bottom"}),v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 h-full cursor-ew-resize w-[12px] ml-[-6px]","data-ord":"left"}),te("cursor-nw-resize","top","left"),te("cursor-ne-resize","top","right"),te("cursor-sw-resize","bottom","left"),te("cursor-se-resize","bottom","right"),te("cursor-ns-resize","top",""),te("cursor-ns-resize","bottom",""),te("cursor-ew-resize","left",""),te("cursor-ew-resize","right","")]}),ie=W=>{M(!0),O({initX:m,initY:g,initHeight:x,initWidth:y,startResizeX:W.clientX,startResizeY:W.clientY,ord:""})},K=()=>v.jsxs("div",{className:Jw("border absolute pointer-events-auto px-2 py-1 rounded-full hover:cursor-move bg-background","origin-top-left top-0 left-0"),style:{transform:`scale(${1/i*.8})`},onPointerDown:ie,children:[y," x ",x]}),Q=()=>v.jsx("div",{className:"outline-dashed outline-primary",style:{height:x,width:y,outlineWidth:`${jq/i*1.3}px`}});return s===!1||!h?null:v.jsx("div",{className:"absolute h-full w-full overflow-hidden pointer-events-none z-[2]",children:v.jsxs("div",{className:"relative pointer-events-none z-[2] [box-shadow:0_0_0_9999px_rgba(0,_0,_0,_0.5)]",style:{height:x,width:y,left:m,top:g},children:[Q(),K(),L()]})})},Bq=()=>{const[e,t,n]=bt(r=>[r.interactiveSegState,r.resetInteractiveSegState,r.handleInteractiveSegAccept]);return e.isInteractiveSeg?v.jsxs("div",{className:"z-10 absolute top-[68px] rounded-xl border-solid border p-[8px] left-1/2 translate-x-[-50%] flex justify-center items-center gap-[8px] bg-background",children:[v.jsx(Rn,{onClick:()=>{t()},size:"sm",variant:"secondary",children:"Cancel"}),v.jsx(Rn,{size:"sm",onClick:()=>{n()},children:"Accept"})]}):null},Uq=e=>{const{x:t,y:n,positive:r}=e,o=r?"bg-[rgba(21,_215,_121,_0.936)] outline-[rgba(98,255,179,0.31)]":"bg-[rgba(237,_49,_55,_0.942)] outline-[rgba(255,89,95,0.31)]";return v.jsx("div",{className:`absolute h-[10px] w-[10px] rounded-[50%] ${o} outline-8 outline`,style:{left:t,top:n,transform:"translate(-50%, -50%)"}})},Vq=()=>{const e=bt(t=>t.interactiveSegState.clicks);return v.jsx("div",{className:"absolute h-full w-full overflow-hidden pointer-events-none",children:e.map(t=>v.jsx(Uq,{x:t[0],y:t[1],positive:t[2]===1},t[3]))})},Wq=()=>v.jsx("div",{children:v.jsx(Bq,{})}),nl={capture:!0,passive:!1},Hq=2,W2=(e,t,n,r)=>t{const{minHeight:t,minWidth:n,scale:r,show:o}=e,[i,s,l,u,{x:d,y:h,width:m,height:g},y,x,_,C,S,b,E]=bt(ie=>[ie.isInpainting,ie.imageHeight,ie.imageWidth,ie.isSD(),ie.extenderState,ie.setExtenderX,ie.setExtenderY,ie.setExtenderWidth,ie.setExtenderHeight,ie.settings.extenderDirection,ie.isCropperExtenderResizing,ie.setIsCropperExtenderResizing]),[k,P]=f.useState({initX:0,initY:0,initHeight:0,initWidth:0,startResizeX:0,startResizeY:0,ord:"top"}),M=()=>{},A=(ie,K)=>W2(ie,K,d,n),O=(ie,K)=>W2(ie,K,h,t),F=ie=>{if(i)return;const K=ie.clientX,Q=ie.clientY,W=Math.round((Q-k.startResizeY)/r),le=Math.round((K-k.startResizeX)/r),ge=()=>{const Me=k.initHeight-W,fe=k.initY+W;let xe=fe,$e=Me;if(S===In.xy)xe>0&&(xe=0,$e=k.initHeight-Math.abs(k.initY));else{const Ae=O(fe,Me);xe=Ae[0],$e=Ae[1]}C($e),x(xe)},Ve=()=>{const Me=k.initHeight+W;let[fe,xe]=O(k.initY,Me);S===In.xy&&xe{const Me=k.initWidth-le,fe=k.initX+le;let xe=fe,$e=Me;if(S===In.xy)xe>0&&(xe=0,$e=k.initWidth-Math.abs(k.initX));else{const Ae=A(fe,Me);xe=Ae[0],$e=Ae[1]}_($e),y(xe)},We=()=>{const Me=k.initWidth+le;let[fe,xe]=A(k.initX,Me);S===In.xy&&xe{b&&E(!1)};f.useEffect(()=>{if(b)return document.addEventListener("pointermove",F,nl),document.addEventListener("pointerup",V,nl),document.addEventListener("pointercancel",V,nl),()=>{document.removeEventListener("pointermove",F,nl),document.removeEventListener("pointerup",V,nl),document.removeEventListener("pointercancel",V,nl)}},[b,m,g,k]);const J=ie=>{const{ord:K}=ie.target.dataset;K&&(E(!0),P({initX:d,initY:h,initHeight:g,initWidth:m,startResizeX:ie.clientX,startResizeY:ie.clientY,ord:K}))},G=(ie,K,Q)=>{const ge="w-[12px] h-[12px] z-[4] absolute content-[''] block border-2 border-primary borde pointer-events-auto hover:bg-primary";let Ve="0",Ue="0",We=Q,Me="-6px";return Q===""&&(Me="50%",K==="left"||K==="right"?(We="top",Ue="-50%"):(We="left",Ve="-50%")),v.jsx("div",{className:Ce(ge,ie),style:{[K]:-6,[We]:Me,transform:`translate(${Ve}, ${Ue}) scale(${1/r})`},"data-ord":K+Q,"aria-label":K+Q,tabIndex:-1,role:"button"})},ae=()=>v.jsxs("div",{onFocus:M,onPointerDown:J,className:"absolute top-0 h-full w-full",children:[[In.y,In.xy].includes(S)?v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 w-full cursor-ns-resize h-[12px] mt-[-6px]","data-ord":"top"}),v.jsx("div",{className:"absolute pointer-events-auto bottom-0 left-0 w-full cursor-ns-resize h-[12px] mb-[-6px]","data-ord":"bottom"}),G("cursor-ns-resize","top",""),G("cursor-ns-resize","bottom","")]}):v.jsx(v.Fragment,{}),[In.x,In.xy].includes(S)?v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"absolute pointer-events-auto top-0 right-0 h-full cursor-ew-resize w-[12px] mr-[-6px]","data-ord":"right"}),v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 h-full cursor-ew-resize w-[12px] ml-[-6px]","data-ord":"left"}),G("cursor-ew-resize","left",""),G("cursor-ew-resize","right","")]}):v.jsx(v.Fragment,{}),S===In.xy?v.jsxs(v.Fragment,{children:[G("cursor-nw-resize","top","left"),G("cursor-ne-resize","top","right"),G("cursor-sw-resize","bottom","left"),G("cursor-se-resize","bottom","right")]}):v.jsx(v.Fragment,{})]}),U=ie=>{P({initX:d,initY:h,initHeight:g,initWidth:m,startResizeX:ie.clientX,startResizeY:ie.clientY,ord:""})},te=()=>v.jsxs("div",{className:Jw("border absolute pointer-events-auto px-2 py-1 rounded-full bg-background","origin-top-left top-0 left-0"),style:{transform:`scale(${1/r*.8})`},onPointerDown:U,children:[m," x ",g]}),L=()=>v.jsx("div",{className:Ce("outline-dashed outline-primary"),style:{height:g,width:m,outlineWidth:`${Hq/r*1.3}px`}});return o===!1||!u?null:v.jsx("div",{className:"absolute h-full w-full pointer-events-none z-[2]",children:v.jsxs("div",{className:"relative pointer-events-none z-[2] [box-shadow:0_0_0_9999px_rgba(0,_0,_0,_0.5)]",style:{height:g,width:m,left:d,top:h},children:[L(),te(),ae()]})})},Yq=200,Gq=10,Xq=200,lu=300;function Zq(e){const{file:t}=e,{toast:n}=Td(),[r,o,i,s,l,u,d,h,m,g,y,x,_,C,S,b,E,k,P,M,A,O]=bt(H=>[H.disableShortCuts,H.windowSize,H.isInpainting,H.imageWidth,H.imageHeight,H.settings,H.serverConfig.enableAutoSaving,H.setImageSize,H.setBaseBrushSize,H.interactiveSegState,H.updateInteractiveSegState,H.handleCanvasMouseDown,H.handleCanvasMouseMove,H.undo,H.redo,H.undoDisabled(),H.redoDisabled(),H.getIsProcessing(),H.updateAppState,H.runMannually(),H.runInpainting,H.isCropperExtenderResizing]),F=bt(H=>H.editorState.baseBrushSize),V=bt(H=>H.getBrushSize()),J=bt(H=>H.editorState.renders),G=bt(H=>H.editorState.extraMasks),ae=bt(H=>H.editorState.temporaryMasks),U=bt(H=>H.editorState.lineGroups),te=bt(H=>H.editorState.curLineGroup),[L,ie]=f.useState(!1),[K,Q]=Rx(t),[W,le]=f.useState(),[ge,Ve]=f.useState(),[{x:Ue,y:We},Me]=f.useState({x:-1,y:-1}),[fe,xe]=f.useState(!1),[$e,Ae]=f.useState(!1),[Oe,je]=f.useState(!1),[Ot,ct]=f.useState(1),[Yt,Er]=f.useState(!1),[gt,js]=f.useState(1),I=o.width/2,X=o.height/2,Z=f.useRef(null),[we,he]=f.useState(!1),[de,ke]=f.useState(!1),[ft,pt]=f.useState(0),bn=f.useCallback(()=>te.length!==0,[te]);f.useEffect(()=>{if(!ge||!Q||s===0||l===0)return;const H=J.length===0?K:J[J.length-1];ge.canvas.width=s,ge.canvas.height=l,ge.clearRect(0,0,ge.canvas.width,ge.canvas.height),ge.drawImage(H,0,0,s,l)},[J,K,Q,ge,l,s]),f.useEffect(()=>{!W||!Q||s===0||l===0||(W.canvas.width=s,W.canvas.height=l,W.clearRect(0,0,W.canvas.width,W.canvas.height),ae.forEach(H=>{W.drawImage(H,0,0,s,l)}),G.forEach(H=>{W.drawImage(H,0,0,s,l)}),g.isInteractiveSeg&&g.tmpInteractiveSegMask&&W.drawImage(g.tmpInteractiveSegMask,0,0,s,l),GR(W,te))},[ae,G,Q,g,W,te,l,s]);const Cr=f.useCallback(async()=>{let H=t;if(J.length>0){const Ge=J[J.length-1];H=await ku(Ge.currentSrc,t.name,t.type)}return H},[t,J]),ki=()=>J.length!==0,_o=f.useCallback(()=>{let H=512,Ge=512;return Q?(J.length===0?(H=K.naturalWidth,Ge=K.naturalHeight):J.length!==0&&(H=J[J.length-1].width,Ge=J[J.length-1].height),[H,Ge]):[H,Ge]},[K,Q,J]);f.useEffect(()=>{var Gd;if(!Q)return;const[H,Ge]=_o();(H!==s||Ge!==l)&&h(H,Ge);const st=o.width/H,Qr=(o.height-Yq)/Ge;let an=1;(st<1||Qr<1)&&(an=Math.min(st,Qr)),js(an),ct(an),console.log(`[on file load] image size: ${H}x${Ge}, scale: ${an}, initialCentered: ${we}`),W!=null&&W.canvas&&(console.log("[on file load] set canvas size"),H!=W.canvas.width&&(W.canvas.width=H),Ge!=W.canvas.height&&(W.canvas.height=Ge)),we||((Gd=Z.current)==null||Gd.centerView(an,1),console.log("[on file load] centerView"),he(!0))},[Z,l,s,K,Q,o,we,_o]),f.useEffect(()=>{var H;console.log("[useEffect] centerView"),(H=Z==null?void 0:Z.current)==null||H.centerView(gt,1)},[l,s,Z,gt]);const Vn=f.useCallback(()=>{if(!gt||!o)return;const H=Z.current;if(!H)return;const Ge=(o.width-s*gt)/2,st=(o.height-l*gt)/2;H.setTransform(Ge,st,gt,200,"easeOutQuad"),H.instance.transformState.scale&&(H.instance.transformState.scale=gt),ct(gt),Er(!1)},[Z,o,l,s,o.height,gt]);f.useEffect(()=>(window.addEventListener("resize",()=>{Vn()}),()=>{window.removeEventListener("resize",()=>{Vn()})}),[o,Vn]),Zn("Escape",()=>{k||(de?ke(!1):Vn())},[de,i,Vn]);const Ri=H=>{const Ge=H.nativeEvent;Me({x:Ge.pageX,y:Ge.pageY})},zs=H=>{k||g.isInteractiveSeg||Oe||de&&te.length!==0&&_(c0(H))},Ti=async H=>{P({isPluginRunning:!0});const Ge=await Cr();try{const st=await gT(!0,jR.InteractiveSeg,Ge,void 0,H),{blob:Qr}=st,an=new Image;an.onload=()=>{y({tmpInteractiveSegMask:an})},an.src=Qr}catch(st){n({variant:"destructive",description:st.message?st.message:st.toString()})}P({isPluginRunning:!1})},$c=H=>{if(!bn())return;if(cC(H)){je(!1);return}g.isInteractiveSeg||Oe||!K.src||!(W!=null&&W.canvas)||i||de&&(M?ke(!1):A())},yg=H=>{if(g.isInteractiveSeg){const Ge=c0(H),st=[...g.clicks];lC(H)?st.push([Ge.x,Ge.y,0,st.length]):st.push([Ge.x,Ge.y,1,st.length]),Ti(st),y({clicks:st})}},wg=H=>{if(!(k||g.isInteractiveSeg||Oe||!Q||!(W!=null&&W.canvas))&&!lC(H)){if(cC(H)){je(!0);return}ke(!0),x(c0(H))}},Kd=H=>{H.preventDefault(),C()};Zn("meta+z,ctrl+z",Kd);const kc=H=>{H.preventDefault(),S()};Zn("shift+ctrl+z,shift+meta+z",kc),o2("Tab",H=>{H==null||H.preventDefault(),H==null||H.stopPropagation(),ki()&&ie(()=>(window.setTimeout(()=>{pt(100)},10),!0))},H=>{H==null||H.preventDefault(),H==null||H.stopPropagation(),ki()&&(window.setTimeout(()=>{pt(0)},10),window.setTimeout(()=>{ie(!1)},lu))});const Rc=f.useCallback(async()=>{if(t===void 0)return;if(d&&J.length>0){try{await Vj(J[J.length-1],t.name,t.type),n({description:"Save image success"})}catch(st){n({variant:"destructive",title:"Uh oh! Something went wrong.",description:st.message?st.message:st.toString()})}return}const H=t.name.replace(/(\.[\w\d_-]+)$/i,"_cleanup$1"),Ge=J[J.length-1];if(vF(Ge.currentSrc,H),u.enableDownloadMask){let st=t.name.replace(/(\.[\w\d_-]+)$/i,"_mask$1");st=st.replace(/\.[^/.]+$/,".jpg");const Qr=Lp(s,l,U),an=document.createElement("a");an.download=st,an.href=Qr.toDataURL("image/jpeg"),an.click()}},[t,d,J,u,l,s,U]);Zn("meta+s,ctrl+s",Rc);const Tc=H=>{H!==fe&&!Oe&&!O&&xe(H)},xg=f.useCallback(()=>{if(k)return"default";if(Oe)return"grab";if(fe)return"none"},[fe,Oe,k]);Zn("[",()=>{let H=F;F>10&&(H=F-10),F<=10&&F>0&&(H=F-5),m(H)},[F]),Zn("]",()=>{m(F+10)},[F]),Zn("shift+r",()=>{M&&bn()&&A()},[M,A,bn]),Zn("ctrl+c,meta+c",async()=>{await pF()&&J.length>0&&W!=null&&W.canvas&&(await gF(W==null?void 0:W.canvas),n({title:"Copy inpainting result to clipboard"}))},[J,W]),o2(" ",H=>{r||(H==null||H.preventDefault(),H==null||H.stopPropagation(),xe(!1),je(!0))},H=>{r||(H==null||H.preventDefault(),H==null||H.stopPropagation(),xe(!0),je(!1))});const Pc=()=>{var Ge,st,Qr,an;let H=gt;return((st=(Ge=Z.current)==null?void 0:Ge.instance)==null?void 0:st.transformState.scale)!==void 0&&(H=(an=(Qr=Z.current)==null?void 0:Qr.instance)==null?void 0:an.transformState.scale),H},Yd=(H,Ge)=>{const st=Pc();return{width:`${V*st}px`,height:`${V*st}px`,left:`${H}px`,top:`${Ge}px`,transform:"translate(-50%, -50%)"}},Ac=H=>v.jsx("div",{className:"absolute rounded-[50%] border-[1px] border-[solid] border-[#ffcc00] pointer-events-none bg-[#ffcc00bb]",style:H}),bg=H=>{m(H),$e||(Ae(!0),window.setTimeout(()=>{Ae(!1)},1e4))},_g=()=>v.jsx("div",{className:"absolute h-[20px] w-[20px] pointer-events-none rounded-[50%] bg-[rgba(21,_215,_121,_0.936)] [box-shadow:0_0_0_0_rgba(21,_215,_121,_0.936)] animate-pulse",style:{left:`${Ue}px`,top:`${We}px`,transform:"translate(-50%, -50%)"},children:v.jsx(dK,{})}),Sg=()=>v.jsx(fq,{ref:H=>{H&&(Z.current=H)},panning:{disabled:!Oe,velocityDisabled:!0},wheel:{step:.05},centerZoomedOut:!0,alignmentAnimation:{disabled:!0},centerOnInit:!0,limitToBounds:!1,doubleClick:{disabled:!0},initialScale:gt,minScale:gt*.3,onPanning:()=>{Yt||Er(!0)},onZoom:H=>{ct(H.state.scale)},children:v.jsxs(mq,{contentStyle:{visibility:we?"visible":"hidden"},children:[v.jsxs("div",{className:"grid [grid-template-areas:'editor-content'] gap-y-4",children:[v.jsx("canvas",{className:"[grid-area:editor-content]",style:{clipPath:`inset(0 ${ft}% 0 0)`,transition:`clip-path ${lu}ms`},ref:H=>{if(H&&!ge){const Ge=H.getContext("2d");Ge&&Ve(Ge)}}}),v.jsx("canvas",{className:Ce("[grid-area:editor-content]",k?"pointer-events-none animate-pulse duration-600":""),style:{cursor:xg(),clipPath:`inset(0 ${ft}% 0 0)`,transition:`clip-path ${lu}ms`},onContextMenu:H=>{H.preventDefault()},onMouseOver:()=>{Tc(!0),Ae(!1)},onFocus:()=>Tc(!0),onMouseLeave:()=>Tc(!1),onMouseDown:wg,onMouseUp:yg,onMouseMove:zs,ref:H=>{if(H&&!W){const Ge=H.getContext("2d");Ge&&le(Ge)}}}),v.jsx("div",{className:"[grid-area:editor-content] pointer-events-none grid [grid-template-areas:'original-image-content']",style:{width:`${s}px`,height:`${l}px`},children:L&&v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"[grid-area:original-image-content] z-10 bg-primary h-full w-[6px] justify-self-end",style:{marginRight:`${ft}%`,transition:`margin-right ${lu}ms`}}),v.jsx("img",{className:"[grid-area:original-image-content]",src:K.src,alt:"original",style:{width:`${s}px`,height:`${l}px`}})]})})]}),v.jsx(zq,{maxHeight:l,maxWidth:s,minHeight:Math.min(512,l),minWidth:Math.min(512,s),scale:Pc(),show:u.showCropper}),v.jsx(Kq,{minHeight:Math.min(512,l),minWidth:Math.min(512,s),scale:Pc(),show:u.showExtender}),g.isInteractiveSeg?v.jsx(Vq,{}):v.jsx(v.Fragment,{})]})});return v.jsxs("div",{className:"flex w-screen h-screen justify-center items-center","aria-hidden":"true",onMouseMove:Ri,onMouseUp:$c,children:[Sg(),fe&&!i&&!Oe&&(g.isInteractiveSeg?_g():Ac(Yd(Ue,We))),$e&&Ac(Yd(I,X)),v.jsxs("div",{className:" overflow-hidden fixed flex bottom-5 border px-4 py-2 rounded-[3rem] gap-8 items-center justify-center backdrop-filter backdrop-blur-md bg-background/70",children:[v.jsx(uo,{className:"w-48",defaultValue:[50],min:Gq,max:Xq,step:1,tabIndex:-1,value:[F],onValueChange:H=>bg(H[0]),onClick:()=>Ae(!1)}),v.jsxs("div",{className:"flex gap-2",children:[v.jsx(vn,{tooltip:"Reset zoom & pan",disabled:Ot===gt&&Yt===!1,onClick:Vn,children:v.jsx(ZU,{})}),v.jsx(vn,{tooltip:"Undo",onClick:Kd,disabled:b,children:v.jsx(aV,{})}),v.jsx(vn,{tooltip:"Redo",onClick:kc,disabled:E,children:v.jsx(oV,{})}),v.jsx(vn,{tooltip:"Show original image",onPointerDown:H=>{H.preventDefault(),ie(()=>(window.setTimeout(()=>{pt(100)},10),!0))},onPointerUp:()=>{window.setTimeout(()=>{pt(0)},10),window.setTimeout(()=>{ie(!1)},lu)},disabled:J.length===0,children:v.jsx(qU,{})}),v.jsx(vn,{tooltip:"Save Image",disabled:!J.length,onClick:Rc,children:v.jsx(GU,{})}),u.enableManualInpainting&&u.model.model_type==="inpaint"?v.jsx(vn,{tooltip:"Run Inpainting",disabled:k||!bn()&&G.length===0,onClick:()=>{A()},children:v.jsx(XU,{})}):v.jsx(v.Fragment,{})]})]})]})}const qq=()=>{const[e,t]=bt(n=>[n.imageWidth,n.imageHeight]);return!e||!t?null:v.jsxs("div",{className:"border rounded-lg px-2 py-[6px] z-10 bg-background",children:[e,"x",t]})},B1=["Enter"," "],Qq=["ArrowDown","PageUp","Home"],V3=["ArrowUp","PageDown","End"],Jq=[...Qq,...V3],eQ={ltr:[...B1,"ArrowRight"],rtl:[...B1,"ArrowLeft"]},tQ={ltr:["ArrowLeft"],rtl:["ArrowRight"]},fg="Menu",[ld,nQ,rQ]=zd(fg),[Na,W3]=An(fg,[rQ,Ns,Qm]),pg=Ns(),H3=Qm(),[K3,Fs]=Na(fg),[oQ,Hd]=Na(fg),iQ=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:o,onOpenChange:i,modal:s=!0}=e,l=pg(t),[u,d]=f.useState(null),h=f.useRef(!1),m=Ft(i),g=Sc(o);return f.useEffect(()=>{const y=()=>{h.current=!0,document.addEventListener("pointerdown",x,{capture:!0,once:!0}),document.addEventListener("pointermove",x,{capture:!0,once:!0})},x=()=>h.current=!1;return document.addEventListener("keydown",y,{capture:!0}),()=>{document.removeEventListener("keydown",y,{capture:!0}),document.removeEventListener("pointerdown",x,{capture:!0}),document.removeEventListener("pointermove",x,{capture:!0})}},[]),f.createElement(Od,l,f.createElement(K3,{scope:t,open:n,onOpenChange:m,content:u,onContentChange:d},f.createElement(oQ,{scope:t,onClose:f.useCallback(()=>m(!1),[m]),isUsingKeyboardRef:h,dir:g,modal:s},r)))},Y3=f.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,o=pg(n);return f.createElement(zm,Y({},o,r,{ref:t}))}),G3="MenuPortal",[sQ,X3]=Na(G3,{forceMount:void 0}),aQ=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:o}=e,i=Fs(G3,t);return f.createElement(sQ,{scope:t,forceMount:n},f.createElement(xn,{present:n||i.open},f.createElement(Md,{asChild:!0,container:o},r)))},yo="MenuContent",[lQ,Jx]=Na(yo),cQ=f.forwardRef((e,t)=>{const n=X3(yo,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,i=Fs(yo,e.__scopeMenu),s=Hd(yo,e.__scopeMenu);return f.createElement(ld.Provider,{scope:e.__scopeMenu},f.createElement(xn,{present:r||i.open},f.createElement(ld.Slot,{scope:e.__scopeMenu},s.modal?f.createElement(uQ,Y({},o,{ref:t})):f.createElement(dQ,Y({},o,{ref:t})))))}),uQ=f.forwardRef((e,t)=>{const n=Fs(yo,e.__scopeMenu),r=f.useRef(null),o=Be(t,r);return f.useEffect(()=>{const i=r.current;if(i)return Xm(i)},[]),f.createElement(eb,Y({},e,{ref:o,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:ue(e.onFocusOutside,i=>i.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)}))}),dQ=f.forwardRef((e,t)=>{const n=Fs(yo,e.__scopeMenu);return f.createElement(eb,Y({},e,{ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)}))}),eb=f.forwardRef((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:o,onOpenAutoFocus:i,onCloseAutoFocus:s,disableOutsidePointerEvents:l,onEntryFocus:u,onEscapeKeyDown:d,onPointerDownOutside:h,onFocusOutside:m,onInteractOutside:g,onDismiss:y,disableOutsideScroll:x,..._}=e,C=Fs(yo,n),S=Hd(yo,n),b=pg(n),E=H3(n),k=nQ(n),[P,M]=f.useState(null),A=f.useRef(null),O=Be(t,A,C.onContentChange),F=f.useRef(0),V=f.useRef(""),J=f.useRef(0),G=f.useRef(null),ae=f.useRef("right"),U=f.useRef(0),te=x?Gm:f.Fragment,L=x?{as:Wo,allowPinchZoom:!0}:void 0,ie=Q=>{var W,le;const ge=V.current+Q,Ve=k().filter($e=>!$e.disabled),Ue=document.activeElement,We=(W=Ve.find($e=>$e.ref.current===Ue))===null||W===void 0?void 0:W.textValue,Me=Ve.map($e=>$e.textValue),fe=RQ(Me,ge,We),xe=(le=Ve.find($e=>$e.textValue===fe))===null||le===void 0?void 0:le.ref.current;(function $e(Ae){V.current=Ae,window.clearTimeout(F.current),Ae!==""&&(F.current=window.setTimeout(()=>$e(""),1e3))})(ge),xe&&setTimeout(()=>xe.focus())};f.useEffect(()=>()=>window.clearTimeout(F.current),[]),Km();const K=f.useCallback(Q=>{var W,le;return ae.current===((W=G.current)===null||W===void 0?void 0:W.side)&&PQ(Q,(le=G.current)===null||le===void 0?void 0:le.area)},[]);return f.createElement(lQ,{scope:n,searchRef:V,onItemEnter:f.useCallback(Q=>{K(Q)&&Q.preventDefault()},[K]),onItemLeave:f.useCallback(Q=>{var W;K(Q)||((W=A.current)===null||W===void 0||W.focus(),M(null))},[K]),onTriggerLeave:f.useCallback(Q=>{K(Q)&&Q.preventDefault()},[K]),pointerGraceTimerRef:J,onPointerGraceIntentChange:f.useCallback(Q=>{G.current=Q},[])},f.createElement(te,L,f.createElement(Hm,{asChild:!0,trapped:o,onMountAutoFocus:ue(i,Q=>{var W;Q.preventDefault(),(W=A.current)===null||W===void 0||W.focus()}),onUnmountAutoFocus:s},f.createElement(yc,{asChild:!0,disableOutsidePointerEvents:l,onEscapeKeyDown:d,onPointerDownOutside:h,onFocusOutside:m,onInteractOutside:g,onDismiss:y},f.createElement(ZP,Y({asChild:!0},E,{dir:S.dir,orientation:"vertical",loop:r,currentTabStopId:P,onCurrentTabStopIdChange:M,onEntryFocus:ue(u,Q=>{S.isUsingKeyboardRef.current||Q.preventDefault()})}),f.createElement(Bm,Y({role:"menu","aria-orientation":"vertical","data-state":tA(C.open),"data-radix-menu-content":"",dir:S.dir},b,_,{ref:O,style:{outline:"none",..._.style},onKeyDown:ue(_.onKeyDown,Q=>{const le=Q.target.closest("[data-radix-menu-content]")===Q.currentTarget,ge=Q.ctrlKey||Q.altKey||Q.metaKey,Ve=Q.key.length===1;le&&(Q.key==="Tab"&&Q.preventDefault(),!ge&&Ve&&ie(Q.key));const Ue=A.current;if(Q.target!==Ue||!Jq.includes(Q.key))return;Q.preventDefault();const Me=k().filter(fe=>!fe.disabled).map(fe=>fe.ref.current);V3.includes(Q.key)&&Me.reverse(),$Q(Me)}),onBlur:ue(e.onBlur,Q=>{Q.currentTarget.contains(Q.target)||(window.clearTimeout(F.current),V.current="")}),onPointerMove:ue(e.onPointerMove,cd(Q=>{const W=Q.target,le=U.current!==Q.clientX;if(Q.currentTarget.contains(W)&&le){const ge=Q.clientX>U.current?"right":"left";ae.current=ge,U.current=Q.clientX}}))})))))))}),fQ=f.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return f.createElement(Pe.div,Y({},r,{ref:t}))}),U1="MenuItem",H2="menu.itemSelect",tb=f.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...o}=e,i=f.useRef(null),s=Hd(U1,e.__scopeMenu),l=Jx(U1,e.__scopeMenu),u=Be(t,i),d=f.useRef(!1),h=()=>{const m=i.current;if(!n&&m){const g=new CustomEvent(H2,{bubbles:!0,cancelable:!0});m.addEventListener(H2,y=>r==null?void 0:r(y),{once:!0}),cx(m,g),g.defaultPrevented?d.current=!1:s.onClose()}};return f.createElement(Z3,Y({},o,{ref:u,disabled:n,onClick:ue(e.onClick,h),onPointerDown:m=>{var g;(g=e.onPointerDown)===null||g===void 0||g.call(e,m),d.current=!0},onPointerUp:ue(e.onPointerUp,m=>{var g;d.current||(g=m.currentTarget)===null||g===void 0||g.click()}),onKeyDown:ue(e.onKeyDown,m=>{const g=l.searchRef.current!=="";n||g&&m.key===" "||B1.includes(m.key)&&(m.currentTarget.click(),m.preventDefault())})}))}),Z3=f.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:o,...i}=e,s=Jx(U1,n),l=H3(n),u=f.useRef(null),d=Be(t,u),[h,m]=f.useState(!1),[g,y]=f.useState("");return f.useEffect(()=>{const x=u.current;if(x){var _;y(((_=x.textContent)!==null&&_!==void 0?_:"").trim())}},[i.children]),f.createElement(ld.ItemSlot,{scope:n,disabled:r,textValue:o??g},f.createElement(qP,Y({asChild:!0},l,{focusable:!r}),f.createElement(Pe.div,Y({role:"menuitem","data-highlighted":h?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0},i,{ref:d,onPointerMove:ue(e.onPointerMove,cd(x=>{r?s.onItemLeave(x):(s.onItemEnter(x),x.defaultPrevented||x.currentTarget.focus())})),onPointerLeave:ue(e.onPointerLeave,cd(x=>s.onItemLeave(x))),onFocus:ue(e.onFocus,()=>m(!0)),onBlur:ue(e.onBlur,()=>m(!1))}))))}),pQ=f.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...o}=e;return f.createElement(Q3,{scope:e.__scopeMenu,checked:n},f.createElement(tb,Y({role:"menuitemcheckbox","aria-checked":om(n)?"mixed":n},o,{ref:t,"data-state":nb(n),onSelect:ue(o.onSelect,()=>r==null?void 0:r(om(n)?!0:!n),{checkForDefaultPrevented:!1})})))}),hQ="MenuRadioGroup",[$te,mQ]=Na(hQ,{value:void 0,onValueChange:()=>{}}),gQ="MenuRadioItem",vQ=f.forwardRef((e,t)=>{const{value:n,...r}=e,o=mQ(gQ,e.__scopeMenu),i=n===o.value;return f.createElement(Q3,{scope:e.__scopeMenu,checked:i},f.createElement(tb,Y({role:"menuitemradio","aria-checked":i},r,{ref:t,"data-state":nb(i),onSelect:ue(r.onSelect,()=>{var s;return(s=o.onValueChange)===null||s===void 0?void 0:s.call(o,n)},{checkForDefaultPrevented:!1})})))}),q3="MenuItemIndicator",[Q3,yQ]=Na(q3,{checked:!1}),wQ=f.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...o}=e,i=yQ(q3,n);return f.createElement(xn,{present:r||om(i.checked)||i.checked===!0},f.createElement(Pe.span,Y({},o,{ref:t,"data-state":nb(i.checked)})))}),xQ=f.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return f.createElement(Pe.div,Y({role:"separator","aria-orientation":"horizontal"},r,{ref:t}))}),J3="MenuSub",[bQ,eA]=Na(J3),_Q=e=>{const{__scopeMenu:t,children:n,open:r=!1,onOpenChange:o}=e,i=Fs(J3,t),s=pg(t),[l,u]=f.useState(null),[d,h]=f.useState(null),m=Ft(o);return f.useEffect(()=>(i.open===!1&&m(!1),()=>m(!1)),[i.open,m]),f.createElement(Od,s,f.createElement(K3,{scope:t,open:r,onOpenChange:m,content:d,onContentChange:h},f.createElement(bQ,{scope:t,contentId:nr(),triggerId:nr(),trigger:l,onTriggerChange:u},n)))},gp="MenuSubTrigger",SQ=f.forwardRef((e,t)=>{const n=Fs(gp,e.__scopeMenu),r=Hd(gp,e.__scopeMenu),o=eA(gp,e.__scopeMenu),i=Jx(gp,e.__scopeMenu),s=f.useRef(null),{pointerGraceTimerRef:l,onPointerGraceIntentChange:u}=i,d={__scopeMenu:e.__scopeMenu},h=f.useCallback(()=>{s.current&&window.clearTimeout(s.current),s.current=null},[]);return f.useEffect(()=>h,[h]),f.useEffect(()=>{const m=l.current;return()=>{window.clearTimeout(m),u(null)}},[l,u]),f.createElement(Y3,Y({asChild:!0},d),f.createElement(Z3,Y({id:o.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":o.contentId,"data-state":tA(n.open)},e,{ref:Am(t,o.onTriggerChange),onClick:m=>{var g;(g=e.onClick)===null||g===void 0||g.call(e,m),!(e.disabled||m.defaultPrevented)&&(m.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:ue(e.onPointerMove,cd(m=>{i.onItemEnter(m),!m.defaultPrevented&&!e.disabled&&!n.open&&!s.current&&(i.onPointerGraceIntentChange(null),s.current=window.setTimeout(()=>{n.onOpenChange(!0),h()},100))})),onPointerLeave:ue(e.onPointerLeave,cd(m=>{var g;h();const y=(g=n.content)===null||g===void 0?void 0:g.getBoundingClientRect();if(y){var x;const _=(x=n.content)===null||x===void 0?void 0:x.dataset.side,C=_==="right",S=C?-5:5,b=y[C?"left":"right"],E=y[C?"right":"left"];i.onPointerGraceIntentChange({area:[{x:m.clientX+S,y:m.clientY},{x:b,y:y.top},{x:E,y:y.top},{x:E,y:y.bottom},{x:b,y:y.bottom}],side:_}),window.clearTimeout(l.current),l.current=window.setTimeout(()=>i.onPointerGraceIntentChange(null),300)}else{if(i.onTriggerLeave(m),m.defaultPrevented)return;i.onPointerGraceIntentChange(null)}})),onKeyDown:ue(e.onKeyDown,m=>{const g=i.searchRef.current!=="";if(!(e.disabled||g&&m.key===" ")&&eQ[r.dir].includes(m.key)){var y;n.onOpenChange(!0),(y=n.content)===null||y===void 0||y.focus(),m.preventDefault()}})})))}),EQ="MenuSubContent",CQ=f.forwardRef((e,t)=>{const n=X3(yo,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,i=Fs(yo,e.__scopeMenu),s=Hd(yo,e.__scopeMenu),l=eA(EQ,e.__scopeMenu),u=f.useRef(null),d=Be(t,u);return f.createElement(ld.Provider,{scope:e.__scopeMenu},f.createElement(xn,{present:r||i.open},f.createElement(ld.Slot,{scope:e.__scopeMenu},f.createElement(eb,Y({id:l.contentId,"aria-labelledby":l.triggerId},o,{ref:d,align:"start",side:s.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:h=>{var m;s.isUsingKeyboardRef.current&&((m=u.current)===null||m===void 0||m.focus()),h.preventDefault()},onCloseAutoFocus:h=>h.preventDefault(),onFocusOutside:ue(e.onFocusOutside,h=>{h.target!==l.trigger&&i.onOpenChange(!1)}),onEscapeKeyDown:ue(e.onEscapeKeyDown,h=>{s.onClose(),h.preventDefault()}),onKeyDown:ue(e.onKeyDown,h=>{const m=h.currentTarget.contains(h.target),g=tQ[s.dir].includes(h.key);if(m&&g){var y;i.onOpenChange(!1),(y=l.trigger)===null||y===void 0||y.focus(),h.preventDefault()}})})))))});function tA(e){return e?"open":"closed"}function om(e){return e==="indeterminate"}function nb(e){return om(e)?"indeterminate":e?"checked":"unchecked"}function $Q(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function kQ(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function RQ(e,t,n){const o=t.length>1&&Array.from(t).every(d=>d===t[0])?t[0]:t,i=n?e.indexOf(n):-1;let s=kQ(e,Math.max(i,0));o.length===1&&(s=s.filter(d=>d!==n));const u=s.find(d=>d.toLowerCase().startsWith(o.toLowerCase()));return u!==n?u:void 0}function TQ(e,t){const{x:n,y:r}=e;let o=!1;for(let i=0,s=t.length-1;ir!=h>r&&n<(d-l)*(r-u)/(h-u)+l&&(o=!o)}return o}function PQ(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return TQ(n,t)}function cd(e){return t=>t.pointerType==="mouse"?e(t):void 0}const AQ=iQ,OQ=Y3,MQ=aQ,NQ=cQ,DQ=fQ,IQ=tb,LQ=pQ,FQ=vQ,jQ=wQ,zQ=xQ,BQ=_Q,UQ=SQ,VQ=CQ,nA="DropdownMenu",[WQ,kte]=An(nA,[W3]),Sr=W3(),[HQ,rA]=WQ(nA),KQ=e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:o,defaultOpen:i,onOpenChange:s,modal:l=!0}=e,u=Sr(t),d=f.useRef(null),[h=!1,m]=Zr({prop:o,defaultProp:i,onChange:s});return f.createElement(HQ,{scope:t,triggerId:nr(),triggerRef:d,contentId:nr(),open:h,onOpenChange:m,onOpenToggle:f.useCallback(()=>m(g=>!g),[m]),modal:l},f.createElement(AQ,Y({},u,{open:h,onOpenChange:m,dir:r,modal:l}),n))},YQ="DropdownMenuTrigger",GQ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...o}=e,i=rA(YQ,n),s=Sr(n);return f.createElement(OQ,Y({asChild:!0},s),f.createElement(Pe.button,Y({type:"button",id:i.triggerId,"aria-haspopup":"menu","aria-expanded":i.open,"aria-controls":i.open?i.contentId:void 0,"data-state":i.open?"open":"closed","data-disabled":r?"":void 0,disabled:r},o,{ref:Am(t,i.triggerRef),onPointerDown:ue(e.onPointerDown,l=>{!r&&l.button===0&&l.ctrlKey===!1&&(i.onOpenToggle(),i.open||l.preventDefault())}),onKeyDown:ue(e.onKeyDown,l=>{r||(["Enter"," "].includes(l.key)&&i.onOpenToggle(),l.key==="ArrowDown"&&i.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(l.key)&&l.preventDefault())})})))}),XQ=e=>{const{__scopeDropdownMenu:t,...n}=e,r=Sr(t);return f.createElement(MQ,Y({},r,n))},ZQ="DropdownMenuContent",qQ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=rA(ZQ,n),i=Sr(n),s=f.useRef(!1);return f.createElement(NQ,Y({id:o.contentId,"aria-labelledby":o.triggerId},i,r,{ref:t,onCloseAutoFocus:ue(e.onCloseAutoFocus,l=>{var u;s.current||(u=o.triggerRef.current)===null||u===void 0||u.focus(),s.current=!1,l.preventDefault()}),onInteractOutside:ue(e.onInteractOutside,l=>{const u=l.detail.originalEvent,d=u.button===0&&u.ctrlKey===!0,h=u.button===2||d;(!o.modal||h)&&(s.current=!0)}),style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}}))}),QQ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(DQ,Y({},o,r,{ref:t}))}),JQ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(IQ,Y({},o,r,{ref:t}))}),eJ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(LQ,Y({},o,r,{ref:t}))}),tJ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(FQ,Y({},o,r,{ref:t}))}),nJ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(jQ,Y({},o,r,{ref:t}))}),rJ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(zQ,Y({},o,r,{ref:t}))}),oJ=e=>{const{__scopeDropdownMenu:t,children:n,open:r,onOpenChange:o,defaultOpen:i}=e,s=Sr(t),[l=!1,u]=Zr({prop:r,defaultProp:i,onChange:o});return f.createElement(BQ,Y({},s,{open:l,onOpenChange:u}),n)},iJ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(UQ,Y({},o,r,{ref:t}))}),sJ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(VQ,Y({},o,r,{ref:t,style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}}))}),aJ=KQ,lJ=GQ,cJ=XQ,oA=qQ,iA=QQ,sA=JQ,aA=eJ,lA=tJ,cA=nJ,uA=rJ,uJ=oJ,dA=iJ,fA=sJ,dJ=aJ,fJ=lJ,K2=uJ,V1=f.forwardRef(({className:e,inset:t,children:n,...r},o)=>v.jsxs(dA,{ref:o,className:Ce("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",e),...r,children:[n,v.jsx(Jj,{className:"ml-auto h-4 w-4"})]}));V1.displayName=dA.displayName;const W1=f.forwardRef(({className:e,...t},n)=>v.jsx(fA,{ref:n,className:Ce("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...t}));W1.displayName=fA.displayName;const pA=f.forwardRef(({className:e,sideOffset:t=4,...n},r)=>v.jsx(cJ,{children:v.jsx(oA,{ref:r,sideOffset:t,className:Ce("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md","data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),onCloseAutoFocus:o=>o.preventDefault(),...n})}));pA.displayName=oA.displayName;const il=f.forwardRef(({className:e,inset:t,...n},r)=>v.jsx(sA,{ref:r,className:Ce("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",e),...n}));il.displayName=sA.displayName;const pJ=f.forwardRef(({className:e,children:t,checked:n,...r},o)=>v.jsxs(aA,{ref:o,className:Ce("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),checked:n,...r,children:[v.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:v.jsx(cA,{children:v.jsx(vT,{className:"h-4 w-4"})})}),t]}));pJ.displayName=aA.displayName;const hJ=f.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(lA,{ref:r,className:Ce("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[v.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:v.jsx(cA,{children:v.jsx(oz,{className:"h-4 w-4 fill-current"})})}),t]}));hJ.displayName=lA.displayName;const mJ=f.forwardRef(({className:e,inset:t,...n},r)=>v.jsx(iA,{ref:r,className:Ce("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",e),...n}));mJ.displayName=iA.displayName;const gJ=f.forwardRef(({className:e,...t},n)=>v.jsx(uA,{ref:n,className:Ce("-mx-1 my-1 h-px bg-muted",e),...t}));gJ.displayName=uA.displayName;const Y2={RemoveBG:{IconClass:VC,showName:"RemoveBG"},AnimeSeg:{IconClass:VC,showName:"Anime Segmentation"},RealESRGAN:{IconClass:XT,showName:"RealESRGAN"},GFPGAN:{IconClass:WC,showName:"GFPGAN"},RestoreFormer:{IconClass:WC,showName:"RestoreFormer"},InteractiveSeg:{IconClass:nV,showName:"Interactive Segmentation"}},vJ=()=>{const[e,t,n,r]=bt(d=>[d.file,d.serverConfig.plugins,d.updateInteractiveSegState,d.runRenderablePlugin]),o=!e;if(t.length===0)return null;const i=(d,h)=>{h==="InteractiveSeg"?n({isInteractiveSeg:!0}):r(d,h)},s=()=>v.jsxs(K2,{children:[v.jsx(V1,{disabled:o,children:v.jsxs("div",{className:"flex gap-2 items-center",children:[v.jsx(XT,{}),"RealESRGAN"]})}),v.jsxs(W1,{children:[v.jsx(il,{onClick:()=>r(!1,"RealESRGAN",{upscale:2}),children:"upscale 2x"}),v.jsx(il,{onClick:()=>r(!1,"RealESRGAN",{upscale:4}),children:"upscale 4x"})]})]},"RealESRGAN"),l=d=>{const{IconClass:h,showName:m}=Y2[d.name];return v.jsxs(K2,{children:[v.jsx(V1,{disabled:o,children:v.jsxs("div",{className:"flex gap-2 items-center",children:[v.jsx(h,{className:"p-1"}),m]})}),v.jsxs(W1,{children:[v.jsx(il,{onClick:()=>i(!1,d.name),children:"Remove Background"}),v.jsx(il,{onClick:()=>i(!0,d.name),children:"Generate Mask"})]})]},d.name)},u=()=>t.map(d=>{const{IconClass:h,showName:m}=Y2[d.name];return d.name==="RealESRGAN"?s():d.name==="RemoveBG"||d.name==="AnimeSeg"?l(d):v.jsx(il,{onClick:()=>i(!1,d.name),disabled:o,children:v.jsxs("div",{className:"flex gap-2 items-center",children:[v.jsx(h,{className:"p-1"}),m]})},d.name)});return v.jsxs(dJ,{modal:!1,children:[v.jsx(fJ,{className:"border rounded-lg z-10 bg-background outline-none",tabIndex:-1,children:v.jsx(Rn,{variant:"ghost",size:"icon",asChild:!0,className:"p-1.5",children:v.jsx(WU,{strokeWidth:1})})}),v.jsx(pA,{side:"bottom",align:"start",children:u()})]})},yJ=Sx,wJ=gP,xJ=Ex,hA=f.forwardRef(({className:e,...t},n)=>v.jsx(Nd,{className:Ce("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t,ref:n}));hA.displayName=Nd.displayName;const bJ=Om("fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=closed]:duration-200 data-[state=open]:duration-300",{variants:{side:{top:"inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",bottom:"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",left:"inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",right:"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm"}},defaultVariants:{side:"right"}}),mA=f.forwardRef(({side:e="right",className:t,children:n,...r},o)=>v.jsxs(xJ,{children:[v.jsx(hA,{}),v.jsx(Dd,{ref:o,className:Ce(bJ({side:e}),t),...r,children:n})]}));mA.displayName=Dd.displayName;const gA=({className:e,...t})=>v.jsx("div",{className:Ce("flex flex-col space-y-2 text-center sm:text-left",e),...t});gA.displayName="SheetHeader";const _J=f.forwardRef(({className:e,...t},n)=>v.jsx(Id,{ref:n,className:Ce("text-lg font-semibold text-foreground",e),...t}));_J.displayName=Id.displayName;const SJ=f.forwardRef(({className:e,...t},n)=>v.jsx(Ld,{ref:n,className:Ce("text-sm text-muted-foreground",e),...t}));SJ.displayName=Ld.displayName;const Ut=({children:e})=>v.jsx("div",{className:"flex justify-between items-center pr-2",children:e}),Pt=({text:e,toolTip:t="",url:n,htmlFor:r,disabled:o=!1})=>v.jsxs(YT,{children:[v.jsx(GT,{asChild:!0,children:v.jsx(Gx,{htmlFor:r||e.toLowerCase().replace(" ","-"),className:"font-medium",disabled:o,children:e})}),t||n?v.jsxs(xx,{className:"flex flex-col max-w-xs text-sm",side:"left",children:[v.jsx("p",{children:t}),n?v.jsx(Rn,{variant:"link",className:"justify-end",children:v.jsx("a",{href:n,target:"_blank",children:"More info"})}):v.jsx(v.Fragment,{})]}):v.jsx(v.Fragment,{})]}),EJ=()=>{const[e,t]=bt(n=>[n.settings,n.updateSettings]);return v.jsxs("div",{className:"flex flex-col gap-4 mt-4",children:[v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{htmlFor:"steps",text:"Steps",toolTip:"The number of denoising steps. More denoising steps usually lead to a higher quality image at the expense of slower inference."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[30],min:1,max:100,step:1,value:[Math.floor(e.ldmSteps)],onValueChange:n=>t({ldmSteps:n[0]})}),v.jsx(Gn,{id:"steps",className:"w-[60px] rounded-full",numberValue:e.ldmSteps,allowFloat:!1,onNumberValueChange:n=>{t({ldmSteps:n})}})]})]}),v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Sampler"}),v.jsxs(aa,{value:e.ldmSampler,onValueChange:n=>{t({ldmSampler:n})},children:[v.jsx(ls,{className:"w-[100px]",children:v.jsx(la,{placeholder:"Select sampler"})}),v.jsx(cs,{align:"end",children:v.jsx(wl,{children:Object.values(Zw).map(n=>v.jsx(us,{value:n,children:n},n))})})]})]})]})},vA=f.forwardRef(({className:e,...t},n)=>v.jsx("textarea",{className:Ce("flex min-h-[60px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",e,"overflow-auto"),tabIndex:-1,ref:n,...t}));vA.displayName="Textarea";const vp=({text:e,onClick:t})=>{const[n]=bt(r=>[r.settings.showExtender]);return v.jsx(Rn,{variant:"outline",className:"p-1 h-8",disabled:!n,onClick:t,children:v.jsx("div",{className:"flex items-center gap-1",children:e})})},CJ=()=>{const[e,t,n,r,o,i,s,l,u,d,h]=bt(L=>[L.serverConfig.samplers,L.settings,L.paintByExampleFile,L.getIsProcessing(),L.updateSettings,L.runInpainting,L.updateAppState,L.updateExtenderByBuiltIn,L.updateExtenderDirection,L.adjustMask,L.clearMask]),[m,g]=Rx(n),y=f.useRef(null);OP(y,()=>{y!=null&&y.current&&y.current.blur()});const x=L=>{L.key==="Enter"&&L.ctrlKey&&t.prompt.length!==0&&i()},_=()=>v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Cropper",toolTip:"Inpainting on part of image, improve inference speed and reduce memory usage."}),v.jsx(co,{id:"cropper",checked:t.showCropper,onCheckedChange:L=>{o({showCropper:L}),L&&o({showExtender:!1})}})]}),C=()=>t.model.support_controlnet?v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex justify-between items-center pr-2",children:[v.jsx(Pt,{text:"ControlNet",toolTip:"Using an additional conditioning image to control how an image is generated",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#controlnet"}),v.jsx(co,{id:"controlnet",checked:t.enableControlnet,onCheckedChange:L=>{o({enableControlnet:L})}})]}),v.jsx("div",{className:"flex flex-col gap-1",children:v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[100],min:1,max:100,step:1,disabled:!t.enableControlnet,value:[Math.floor(t.controlnetConditioningScale*100)],onValueChange:L=>o({controlnetConditioningScale:L[0]/100})}),v.jsx(Gn,{id:"controlnet-weight",className:"w-[60px] rounded-full",disabled:!t.enableControlnet,numberValue:t.controlnetConditioningScale,allowFloat:!1,onNumberValueChange:L=>{o({controlnetConditioningScale:L})}})]})}),v.jsx("div",{className:"pr-2",children:v.jsxs(aa,{defaultValue:t.controlnetMethod,value:t.controlnetMethod,onValueChange:L=>{o({controlnetMethod:L})},disabled:!t.enableControlnet,children:[v.jsx(ls,{children:v.jsx(la,{placeholder:"Select control method"})}),v.jsx(cs,{align:"end",children:v.jsx(wl,{children:Object.values(t.model.controlnets).map(L=>v.jsx(us,{value:L,children:L.split("/")[1]},L))})})]})})]}),v.jsx(Fn,{})]}):null,S=()=>t.model.support_lcm_lora?v.jsxs(v.Fragment,{children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"LCM Lora",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inference_with_lcm_lora",toolTip:"Enable quality image generation in typically 2-4 steps. Suggest disabling guidance_scale by setting it to 0. You can also try values between 1.0 and 2.0. When LCM Lora is enabled, LCMSampler will be used automatically."}),v.jsx(co,{id:"lcm-lora",checked:t.enableLCMLora,onCheckedChange:L=>{o({enableLCMLora:L})}})]}),v.jsx(Fn,{})]}):null,b=()=>t.model.support_freeu?v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex justify-between items-center pr-2",children:[v.jsx(Pt,{text:"FreeU",toolTip:"FreeU is a technique for improving image quality. Different models may require different FreeU-specific hyperparameters, which can be viewed in the more info section.",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/freeu"}),v.jsx(co,{id:"freeu",checked:t.enableFreeu,onCheckedChange:L=>{o({enableFreeu:L})}})]}),v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex justify-center gap-6",children:[v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-s1",text:"s1",disabled:!t.enableFreeu}),v.jsx(Gn,{id:"freeu-s1",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.s1,allowFloat:!0,onNumberValueChange:L=>{o({freeuConfig:{...t.freeuConfig,s1:L}})}})]}),v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-s2",text:"s2",disabled:!t.enableFreeu}),v.jsx(Gn,{id:"freeu-s2",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.s2,allowFloat:!0,onNumberValueChange:L=>{o({freeuConfig:{...t.freeuConfig,s2:L}})}})]})]}),v.jsxs("div",{className:"flex justify-center gap-6",children:[v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-b1",text:"b1",disabled:!t.enableFreeu}),v.jsx(Gn,{id:"freeu-b1",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.b1,allowFloat:!0,onNumberValueChange:L=>{o({freeuConfig:{...t.freeuConfig,b1:L}})}})]}),v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-b2",text:"b2",disabled:!t.enableFreeu}),v.jsx(Gn,{id:"freeu-b2",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.b2,allowFloat:!0,onNumberValueChange:L=>{o({freeuConfig:{...t.freeuConfig,b2:L}})}})]})]})]}),v.jsx(Fn,{})]}):null,E=()=>t.model.need_prompt?v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsx(Pt,{text:"Negative prompt",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#negative-prompt",toolTip:"Negative prompt guides the model away from generating certain things in an image"}),v.jsx("div",{className:"pl-2 pr-4",children:v.jsx(vA,{ref:y,rows:4,onKeyUp:x,className:"max-h-[8rem] overflow-y-auto mb-2",placeholder:"",id:"negative-prompt",value:t.negativePrompt,onInput:L=>{L.preventDefault(),L.stopPropagation();const ie=L.target;o({negativePrompt:ie.value})}})})]}):null,k=()=>t.model.name!==YR?null:v.jsxs("div",{children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Example Image",toolTip:"An example image to guide image generation."}),v.jsx(c1,{tooltip:"Upload example image",onFileUpload:L=>{s({paintByExampleFile:L})},children:v.jsx(ZT,{})})]}),g?v.jsx("div",{className:"flex justify-center items-center",children:v.jsx("img",{src:m.src,alt:"example",className:"max-w-[200px] max-h-[200px] m-3"})}):v.jsx(v.Fragment,{}),v.jsx(Rn,{variant:"default",className:"w-full",disabled:r||!g,onClick:()=>{i()},children:"Paint"})]}),P=()=>t.model.name!==aF?null:v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Image guidance scale",toolTip:"Push the generated image towards the inital image. Higher image guidance scale encourages generated images that are closely linked to the source image, usually at the expense of lower image quality.",url:"https://huggingface.co/docs/diffusers/main/en/api/pipelines/pix2pix"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[150],min:100,max:1e3,step:1,value:[Math.floor(t.p2pImageGuidanceScale*100)],onValueChange:L=>o({p2pImageGuidanceScale:L[0]/100})}),v.jsx(Gn,{id:"image-guidance-scale",className:"w-[60px] rounded-full",numberValue:t.p2pImageGuidanceScale,allowFloat:!0,onNumberValueChange:L=>{o({p2pImageGuidanceScale:L})}})]})]}),M=()=>t.model.support_strength?v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Strength",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#strength",toolTip:"Strength is a measure of how much noise is added to the base image, which influences how similar the output is to the base image. Higher value means more noise and more different from the base image"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[100],min:10,max:100,step:1,value:[Math.floor(t.sdStrength*100)],onValueChange:L=>o({sdStrength:L[0]/100})}),v.jsx(Gn,{id:"strength",className:"w-[60px] rounded-full",numberValue:t.sdStrength,allowFloat:!0,onNumberValueChange:L=>{o({sdStrength:L})}})]})]}):null,A=()=>t.model.support_outpainting?v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Extender",toolTip:"Perform outpainting on images to expand it's content."}),v.jsx(co,{id:"extender",checked:t.showExtender,onCheckedChange:L=>{o({showExtender:L}),L&&o({showCropper:!1})}})]}),v.jsxs(Ut,{children:[v.jsxs(aa,{defaultValue:t.extenderDirection,value:t.extenderDirection,onValueChange:L=>{u(L)},children:[v.jsx(ls,{className:"w-[65px] h-7",disabled:!t.showExtender,children:v.jsx(la,{placeholder:"Select axis"})}),v.jsx(cs,{align:"end",children:v.jsx(wl,{children:Object.values(In).map(L=>v.jsx(us,{value:L,children:L},L))})})]}),v.jsxs("div",{className:"flex gap-1 justify-center mt-0",children:[v.jsx(vp,{text:"1.25x",onClick:()=>l(t.extenderDirection,1.25)}),v.jsx(vp,{text:"1.5x",onClick:()=>l(t.extenderDirection,1.5)}),v.jsx(vp,{text:"1.75x",onClick:()=>l(t.extenderDirection,1.75)}),v.jsx(vp,{text:"2.0x",onClick:()=>l(t.extenderDirection,2)})]})]})]}),v.jsx(Fn,{})]}):null,O=()=>t.model.name!==lF?null:v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Task",toolTip:"PowerPaint task. When using extender, image-outpainting task will be auto used. For object-removal and image-outpainting, it is recommended to set the guidance_scale at 10 or above."}),v.jsxs(aa,{defaultValue:t.powerpaintTask,value:t.powerpaintTask,onValueChange:L=>{o({powerpaintTask:L})},disabled:t.showExtender,children:[v.jsx(ls,{className:"w-[140px]",children:v.jsx(la,{placeholder:"Select task"})}),v.jsx(cs,{align:"end",children:v.jsx(wl,{children:[kl.text_guided,kl.object_remove,kl.shape_guided].map(L=>v.jsx(us,{value:L,children:L},L))})})]})]}),F=()=>v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{htmlFor:"steps",text:"Steps",toolTip:"The number of denoising steps. More denoising steps usually lead to a higher quality image at the expense of slower inference."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[30],min:1,max:100,step:1,value:[Math.floor(t.sdSteps)],onValueChange:L=>o({sdSteps:L[0]})}),v.jsx(Gn,{id:"steps",className:"w-[60px] rounded-full",numberValue:t.sdSteps,allowFloat:!1,onNumberValueChange:L=>{o({sdSteps:L})}})]})]}),V=()=>v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Guidance scale",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#guidance-scale",toolTip:"Guidance scale affects how aligned the text prompt and generated image are. Higher value means the prompt and generated image are closely aligned, so the output is a stricter interpretation of the prompt"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[750],min:0,max:1500,step:1,value:[Math.floor(t.sdGuidanceScale*100)],onValueChange:L=>o({sdGuidanceScale:L[0]/100})}),v.jsx(Gn,{id:"guidance-scale",className:"w-[60px] rounded-full",numberValue:t.sdGuidanceScale,allowFloat:!0,onNumberValueChange:L=>{o({sdGuidanceScale:L})}})]})]}),J=()=>v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Sampler"}),v.jsxs(aa,{defaultValue:t.sdSampler,value:t.sdSampler,onValueChange:L=>{o({sdSampler:L})},children:[v.jsx(ls,{className:"w-[175px] text-xs",children:v.jsx(la,{placeholder:"Select sampler"})}),v.jsx(cs,{align:"end",children:v.jsx(wl,{children:e.map(L=>v.jsx(us,{value:L,className:"text-xs",children:L},L))})})]})]}),G=()=>v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Seed",toolTip:"Using same parameters and a fixed seed can generate same result image."}),v.jsxs("div",{className:"flex gap-2 justify-center items-center",children:[v.jsx(co,{id:"seed",checked:t.seedFixed,onCheckedChange:L=>{o({seedFixed:L})}}),v.jsx(Gn,{id:"seed",className:"w-[100px]",disabled:!t.seedFixed,numberValue:t.seed,allowFloat:!1,onNumberValueChange:L=>{o({seed:L})}})]})]}),ae=()=>v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Mask blur",toolTip:"How much to blur the mask before processing, in pixels."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[t.sdMaskBlur],min:0,max:96,step:1,value:[Math.floor(t.sdMaskBlur)],onValueChange:L=>o({sdMaskBlur:L[0]})}),v.jsx(Gn,{id:"mask-blur",className:"w-[60px] rounded-full",numberValue:t.sdMaskBlur,allowFloat:!1,onNumberValueChange:L=>{o({sdMaskBlur:L})}})]})]}),U=()=>v.jsxs(v.Fragment,{children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Match histograms",toolTip:"Match the inpainting result histogram to the source image histogram",url:"https://github.com/Sanster/lama-cleaner/pull/143#issuecomment-1325859307"}),v.jsx(co,{id:"match-histograms",checked:t.sdMatchHistograms,onCheckedChange:L=>{o({sdMatchHistograms:L})}})]}),v.jsx(Fn,{})]}),te=()=>v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{htmlFor:"adjustMaskKernelSize",text:"Adjust Mask",toolTip:"Expand or shrink mask. Using the slider to adjust the kernel size for dilation or erosion."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[12],min:1,max:100,step:1,value:[Math.floor(t.adjustMaskKernelSize)],onValueChange:L=>o({adjustMaskKernelSize:L[0]})}),v.jsx(Gn,{id:"adjustMaskKernelSize",className:"w-[60px] rounded-full",numberValue:t.adjustMaskKernelSize,allowFloat:!1,onNumberValueChange:L=>{o({adjustMaskKernelSize:L})}})]}),v.jsxs(Ut,{children:[v.jsxs("div",{className:"flex gap-1 justify-start",children:[v.jsx(Rn,{variant:"outline",className:"p-1 h-8",onClick:()=>d("expand"),disabled:r,children:v.jsxs("div",{className:"flex items-center gap-1 select-none",children:[v.jsx(rV,{size:16}),"expand"]})}),v.jsx(Rn,{variant:"outline",className:"p-1 h-8",onClick:()=>d("shrink"),disabled:r,children:v.jsxs("div",{className:"flex items-center gap-1 select-none",children:[v.jsx(tV,{size:16}),"Shrink"]})})]}),v.jsx(Rn,{variant:"outline",className:"p-1 h-8 justify-self-end",onClick:h,disabled:r,children:v.jsx("div",{className:"flex items-center gap-1 select-none",children:"Clear"})})]})]}),v.jsx(Fn,{})]});return v.jsxs("div",{className:"flex flex-col gap-4 mt-4",children:[_(),A(),te(),O(),F(),V(),P(),M(),J(),G(),E(),v.jsx(Fn,{}),C(),S(),ae(),U(),b(),k()]})},$J=()=>{const[e,t]=bt(n=>[n.settings,n.updateSettings]);return v.jsxs("div",{className:"flex flex-col gap-4 mt-4",children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"CV2 Flag",url:"https://docs.opencv.org/4.8.0/d7/d8b/group__photo__inpaint.html#gga8002a65f5a3328fbf15df81b842d3c3ca892824c38e258feb5e72f308a358d52e"}),v.jsxs(aa,{value:e.cv2Flag,onValueChange:n=>{t({cv2Flag:n})},children:[v.jsx(ls,{className:"w-[160px]",children:v.jsx(la,{placeholder:"Select flag"})}),v.jsx(cs,{align:"end",children:v.jsx(wl,{children:Object.values(qw).map(n=>v.jsx(us,{value:n,children:n},n))})})]})]}),v.jsx(Pt,{text:"CV2 Radius",url:"https://docs.opencv.org/4.8.0/d7/d8b/group__photo__inpaint.html#gga8002a65f5a3328fbf15df81b842d3c3ca892824c38e258feb5e72f308a358d52e"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[5],min:1,max:100,step:1,value:[Math.floor(e.cv2Radius)],onValueChange:n=>t({cv2Radius:n[0]})}),v.jsx(Gn,{id:"cv2-radius",className:"w-[60px] rounded-full",numberValue:e.cv2Radius,allowFloat:!1,onNumberValueChange:n=>{t({cv2Radius:n})}})]})]})},kJ=()=>{const[e,t]=bt(i=>[i.settings,i.windowSize]),[n,r]=AP(!0);if(Zn("c",()=>{r()}),e.model.name!==oC&&e.model.name!==iC&&e.model.model_type===is)return null;const o=()=>e.model.name===oC?v.jsx(EJ,{}):e.model.name===iC?v.jsx($J,{}):v.jsx(CJ,{});return v.jsxs(yJ,{open:n,modal:!1,children:[v.jsx(wJ,{tabIndex:-1,className:"z-10 outline-none absolute top-[68px] right-6 rounded-lg border bg-background",children:v.jsx(Rn,{variant:"ghost",size:"icon",asChild:!0,className:"p-1.5",onClick:r,children:v.jsx(HU,{strokeWidth:1})})}),v.jsxs(mA,{side:"right",className:"w-[300px] mt-[60px] outline-none pl-4 pr-1",onOpenAutoFocus:i=>i.preventDefault(),onPointerDownOutside:i=>i.preventDefault(),children:[v.jsxs(gA,{children:[v.jsxs(Ut,{children:[v.jsx("div",{className:"overflow-hidden mr-8",children:e.model.name.split("/")[e.model.name.split("/").length-1]}),v.jsx(Rn,{variant:"ghost",size:"icon",className:"border h-6 w-6",onClick:r,children:v.jsx(KU,{strokeWidth:1})})]}),v.jsx(Fn,{})]}),v.jsx(og,{style:{height:t.height-160},className:"pr-3",children:o()})]})]})},Yo=Object.create(null);Yo.open="0";Yo.close="1";Yo.ping="2";Yo.pong="3";Yo.message="4";Yo.upgrade="5";Yo.noop="6";const th=Object.create(null);Object.keys(Yo).forEach(e=>{th[Yo[e]]=e});const H1={type:"error",data:"parser error"},yA=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",wA=typeof ArrayBuffer=="function",xA=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,rb=({type:e,data:t},n,r)=>yA&&t instanceof Blob?n?r(t):G2(t,r):wA&&(t instanceof ArrayBuffer||xA(t))?n?r(t):G2(new Blob([t]),r):r(Yo[e]+(t||"")),G2=(e,t)=>{const n=new FileReader;return n.onload=function(){const r=n.result.split(",")[1];t("b"+(r||""))},n.readAsDataURL(e)};function X2(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let L0;function RJ(e,t){if(yA&&e.data instanceof Blob)return e.data.arrayBuffer().then(X2).then(t);if(wA&&(e.data instanceof ArrayBuffer||xA(e.data)))return t(X2(e.data));rb(e,!1,n=>{L0||(L0=new TextEncoder),t(L0.encode(n))})}const Z2="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",gu=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let e=0;e{let t=e.length*.75,n=e.length,r,o=0,i,s,l,u;e[e.length-1]==="="&&(t--,e[e.length-2]==="="&&t--);const d=new ArrayBuffer(t),h=new Uint8Array(d);for(r=0;r>4,h[o++]=(s&15)<<4|l>>2,h[o++]=(l&3)<<6|u&63;return d},PJ=typeof ArrayBuffer=="function",ob=(e,t)=>{if(typeof e!="string")return{type:"message",data:bA(e,t)};const n=e.charAt(0);return n==="b"?{type:"message",data:AJ(e.substring(1),t)}:th[n]?e.length>1?{type:th[n],data:e.substring(1)}:{type:th[n]}:H1},AJ=(e,t)=>{if(PJ){const n=TJ(e);return bA(n,t)}else return{base64:!0,data:e}},bA=(e,t)=>{switch(t){case"blob":return e instanceof Blob?e:new Blob([e]);case"arraybuffer":default:return e instanceof ArrayBuffer?e:e.buffer}},_A="",OJ=(e,t)=>{const n=e.length,r=new Array(n);let o=0;e.forEach((i,s)=>{rb(i,!1,l=>{r[s]=l,++o===n&&t(r.join(_A))})})},MJ=(e,t)=>{const n=e.split(_A),r=[];for(let o=0;o{const r=n.length;let o;if(r<126)o=new Uint8Array(1),new DataView(o.buffer).setUint8(0,r);else if(r<65536){o=new Uint8Array(3);const i=new DataView(o.buffer);i.setUint8(0,126),i.setUint16(1,r)}else{o=new Uint8Array(9);const i=new DataView(o.buffer);i.setUint8(0,127),i.setBigUint64(1,BigInt(r))}e.data&&typeof e.data!="string"&&(o[0]|=128),t.enqueue(o),t.enqueue(n)})}})}let F0;function yp(e){return e.reduce((t,n)=>t+n.length,0)}function wp(e,t){if(e[0].length===t)return e.shift();const n=new Uint8Array(t);let r=0;for(let o=0;oMath.pow(2,21)-1){l.enqueue(H1);break}o=h*Math.pow(2,32)+d.getUint32(4),r=3}else{if(yp(n)e){l.enqueue(H1);break}}}})}const SA=4;function Qt(e){if(e)return IJ(e)}function IJ(e){for(var t in Qt.prototype)e[t]=Qt.prototype[t];return e}Qt.prototype.on=Qt.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this};Qt.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this};Qt.prototype.off=Qt.prototype.removeListener=Qt.prototype.removeAllListeners=Qt.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,o=0;o(e.hasOwnProperty(r)&&(n[r]=e[r]),n),{})}const LJ=Br.setTimeout,FJ=Br.clearTimeout;function hg(e,t){t.useNativeTimers?(e.setTimeoutFn=LJ.bind(Br),e.clearTimeoutFn=FJ.bind(Br)):(e.setTimeoutFn=Br.setTimeout.bind(Br),e.clearTimeoutFn=Br.clearTimeout.bind(Br))}const jJ=1.33;function zJ(e){return typeof e=="string"?BJ(e):Math.ceil((e.byteLength||e.size)*jJ)}function BJ(e){let t=0,n=0;for(let r=0,o=e.length;r=57344?n+=3:(r++,n+=4);return n}function UJ(e){let t="";for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+="&"),t+=encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t}function VJ(e){let t={},n=e.split("&");for(let r=0,o=n.length;r0);return t}function $A(){const e=J2(+new Date);return e!==Q2?(q2=0,Q2=e):e+"."+J2(q2++)}for(;xp{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)};MJ(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,OJ(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]=$A()),!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 Vo(this.uri(),t)}doWrite(t,n){const r=this.request({method:"POST",data:t});r.on("success",n),r.on("error",(o,i)=>{this.onError("xhr post error",o,i)})}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}}class Vo extends Qt{constructor(t,n){super(),hg(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=EA(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");n.xdomain=!!this.opts.xd;const r=this.xhr=new RA(n);try{r.open(this.method,this.uri,!0);try{if(this.opts.extraHeaders){r.setDisableHeaderCheck&&r.setDisableHeaderCheck(!0);for(let o in this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(o)&&r.setRequestHeader(o,this.opts.extraHeaders[o])}}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 o;r.readyState===3&&((o=this.opts.cookieJar)===null||o===void 0||o.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(o){this.setTimeoutFn(()=>{this.onError(o)},0);return}typeof document<"u"&&(this.index=Vo.requestsCount++,Vo.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=YJ,t)try{this.xhr.abort()}catch{}typeof document<"u"&&delete Vo.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()}}Vo.requestsCount=0;Vo.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",e$);else if(typeof addEventListener=="function"){const e="onpagehide"in Br?"pagehide":"unload";addEventListener(e,e$,!1)}}function e$(){for(let e in Vo.requests)Vo.requests.hasOwnProperty(e)&&Vo.requests[e].abort()}const sb=typeof Promise=="function"&&typeof Promise.resolve=="function"?t=>Promise.resolve().then(t):(t,n)=>n(t,0),bp=Br.WebSocket||Br.MozWebSocket,t$=!0,ZJ="arraybuffer",n$=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class qJ extends ib{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=n$?{}:EA(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=t$&&!n$?n?new bp(t,n):new bp(t):new bp(t,n,r)}catch(o){return this.emitReserved("error",o)}this.ws.binaryType=this.socket.binaryType,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{t$&&this.ws.send(i)}catch{}o&&sb(()=>{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]=$A()),this.supportsBinary||(n.b64=1),this.createUri(t,n)}check(){return!!bp}}class QJ extends ib{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=DJ(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=t.readable.pipeThrough(n).getReader(),o=NJ();o.readable.pipeTo(t.writable),this.writer=o.writable.getWriter();const i=()=>{r.read().then(({done:l,value:u})=>{l||(this.onPacket(u),i())}).catch(l=>{})};i();const s={type:"open"};this.query.sid&&(s.data=`{"sid":"${this.query.sid}"}`),this.writer.write(s).then(()=>this.onOpen())})}))}write(t){this.writable=!1;for(let n=0;n{o&&sb(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;(t=this.transport)===null||t===void 0||t.close()}}const JJ={websocket:qJ,webtransport:QJ,polling:XJ},eee=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,tee=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Y1(e){if(e.length>2e3)throw"URI too long";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 o=eee.exec(e||""),i={},s=14;for(;s--;)i[tee[s]]=o[s]||"";return n!=-1&&r!=-1&&(i.source=t,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=nee(i,i.path),i.queryKey=ree(i,i.query),i}function nee(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 ree(e,t){const n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(r,o,i){o&&(n[o]=i)}),n}let TA=class sl extends Qt{constructor(t,n={}){super(),this.binaryType=ZJ,this.writeBuffer=[],t&&typeof t=="object"&&(n=t,t=null),t?(t=Y1(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=Y1(n.host).host),hg(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=VJ(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=SA,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 JJ[t](r)}open(){let t;if(this.opts.rememberUpgrade&&sl.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;sl.priorWebsocketSuccess=!1;const o=()=>{r||(n.send([{type:"ping",data:"probe"}]),n.once("packet",m=>{if(!r)if(m.type==="pong"&&m.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",n),!n)return;sl.priorWebsocketSuccess=n.name==="websocket",this.transport.pause(()=>{r||this.readyState!=="closed"&&(h(),this.setTransport(n),n.send([{type:"upgrade"}]),this.emitReserved("upgrade",n),n=null,this.upgrading=!1,this.flush())})}else{const g=new Error("probe error");g.transport=n.name,this.emitReserved("upgradeError",g)}}))};function i(){r||(r=!0,h(),n.close(),n=null)}const s=m=>{const g=new Error("probe error: "+m);g.transport=n.name,i(),this.emitReserved("upgradeError",g)};function l(){s("transport closed")}function u(){s("socket closed")}function d(m){n&&m.name!==n.name&&i()}const h=()=>{n.removeListener("open",o),n.removeListener("error",s),n.removeListener("close",l),this.off("close",u),this.off("upgrading",d)};n.once("open",o),n.once("error",s),n.once("close",l),this.once("close",u),this.once("upgrading",d),this.upgrades.indexOf("webtransport")!==-1&&t!=="webtransport"?this.setTimeoutFn(()=>{r||n.open()},200):n.open()}onOpen(){if(this.readyState="open",sl.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,o){if(typeof n=="function"&&(o=n,n=void 0),typeof r=="function"&&(o=r,r=null),this.readyState==="closing"||this.readyState==="closed")return;r=r||{},r.compress=r.compress!==!1;const i={type:t,data:n,options:r};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),o&&this.once("flush",o),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){sl.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 o=t.length;for(;rtypeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,PA=Object.prototype.toString,aee=typeof Blob=="function"||typeof Blob<"u"&&PA.call(Blob)==="[object BlobConstructor]",lee=typeof File=="function"||typeof File<"u"&&PA.call(File)==="[object FileConstructor]";function ab(e){return iee&&(e instanceof ArrayBuffer||see(e))||aee&&e instanceof Blob||lee&&e instanceof File}function nh(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(i),n.apply(this,[null,...s])}}emitWithAck(t,...n){const r=this.flags.timeout!==void 0||this._opts.ackTimeout!==void 0;return new Promise((o,i)=>{n.push((s,l)=>r?s?i(s):o(l):o(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((o,...i)=>r!==this._queue[0]?void 0:(o!==null?r.tryCount>this._opts.retries&&(this._queue.shift(),n&&n(o)):(this._queue.shift(),n&&n(null,...i)),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:lt.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 lt.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 lt.EVENT:case lt.BINARY_EVENT:this.onevent(t);break;case lt.ACK:case lt.BINARY_ACK:this.onack(t);break;case lt.DISCONNECT:this.ondisconnect();break;case lt.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(...o){r||(r=!0,n.packet({type:lt.ACK,id:t,data:o}))}}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:lt.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}Cc.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};Cc.prototype.reset=function(){this.attempts=0};Cc.prototype.setMin=function(e){this.ms=e};Cc.prototype.setMax=function(e){this.max=e};Cc.prototype.setJitter=function(e){this.jitter=e};class Z1 extends Qt{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,hg(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 Cc({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(n.timeout==null?2e4:n.timeout),this._readyState="closed",this.uri=t;const o=n.parser||mee;this.encoder=new o.Encoder,this.decoder=new o.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 TA(this.uri,this.opts);const n=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;const o=fo(n,"open",function(){r.onopen(),t&&t()}),i=l=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",l),t?t(l):this.maybeReconnectOnOpen()},s=fo(n,"error",i);if(this._timeout!==!1){const l=this._timeout,u=this.setTimeoutFn(()=>{o(),i(new Error("timeout")),n.close()},l);this.opts.autoUnref&&u.unref(),this.subs.push(()=>{this.clearTimeoutFn(u)})}return this.subs.push(o),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(fo(t,"ping",this.onping.bind(this)),fo(t,"data",this.ondata.bind(this)),fo(t,"error",this.onerror.bind(this)),fo(t,"close",this.onclose.bind(this)),fo(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){sb(()=>{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 AA(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(o=>{o?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",o)):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 cu={};function rh(e,t){typeof e=="object"&&(t=e,e=void 0),t=t||{};const n=oee(e,t.path||"/socket.io"),r=n.source,o=n.id,i=n.path,s=cu[o]&&i in cu[o].nsps,l=t.forceNew||t["force new connection"]||t.multiplex===!1||s;let u;return l?u=new Z1(r,t):(cu[o]||(cu[o]=new Z1(r,t)),u=cu[o]),n.query&&!t.query&&(t.query=n.queryKey),u.socket(n.path,t)}Object.assign(rh,{Manager:Z1,Socket:AA,io:rh,connect:rh});const OA="Progress",mg=100,[vee,Rte]=An(OA),[yee,wee]=vee(OA),MA=f.forwardRef((e,t)=>{const{__scopeProgress:n,value:r,max:o,getValueLabel:i=_ee,...s}=e,l=q1(o)?o:mg,u=DA(r,l)?r:null,d=im(u)?i(u,l):void 0;return f.createElement(yee,{scope:n,value:u,max:l},f.createElement(Pe.div,Y({"aria-valuemax":l,"aria-valuemin":0,"aria-valuenow":im(u)?u:void 0,"aria-valuetext":d,role:"progressbar","data-state":NA(u,l),"data-value":u??void 0,"data-max":l},s,{ref:t})))});MA.propTypes={max(e,t,n){const r=e[t],o=String(r);return r&&!q1(r)?new Error(See(o,n)):null},value(e,t,n){const r=e[t],o=String(r),i=q1(e.max)?e.max:mg;return r!=null&&!DA(r,i)?new Error(Eee(o,n)):null}};const xee="ProgressIndicator",bee=f.forwardRef((e,t)=>{var n;const{__scopeProgress:r,...o}=e,i=wee(xee,r);return f.createElement(Pe.div,Y({"data-state":NA(i.value,i.max),"data-value":(n=i.value)!==null&&n!==void 0?n:void 0,"data-max":i.max},o,{ref:t}))});function _ee(e,t){return`${Math.round(e/t*100)}%`}function NA(e,t){return e==null?"indeterminate":e===t?"complete":"loading"}function im(e){return typeof e=="number"}function q1(e){return im(e)&&!isNaN(e)&&e>0}function DA(e,t){return im(e)&&!isNaN(e)&&e<=t&&e>=0}function See(e,t){return`Invalid prop \`max\` of value \`${e}\` supplied to \`${t}\`. Only numbers greater than 0 are valid max values. Defaulting to \`${mg}\`.`}function Eee(e,t){return`Invalid prop \`value\` of value \`${e}\` supplied to \`${t}\`. The \`value\` prop must be: + - a positive number + - less than the value passed to \`max\` (or ${mg} if no \`max\` prop is set) + - \`null\` if the progress is indeterminate. + +Defaulting to \`null\`.`}const IA=MA,Cee=bee,LA=f.forwardRef(({className:e,value:t,...n},r)=>v.jsx(IA,{ref:r,className:Ce("relative h-2 w-full overflow-hidden rounded-full bg-primary/20",e),...n,children:v.jsx(Cee,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(t||0)}%)`}})}));LA.displayName=IA.displayName;const $ee="",Vi=rh($ee),kee=()=>{const[e,t,n]=bt(u=>[u.settings,u.isInpainting,u.isSD()]),[r,o]=f.useState(!1),[i,s]=f.useState(0),l=Math.min(Math.round(i/e.sdSteps*100),100);return f.useEffect(()=>(Vi.on("connect",()=>{o(!0)}),Vi.on("disconnect",()=>{o(!1)}),Vi.on("diffusion_progress",u=>{u&&s(u.step+1)}),Vi.on("diffusion_finish",()=>{s(0)}),()=>{Vi.off("connect"),Vi.off("disconnect"),Vi.off("diffusion_progress"),Vi.off("diffusion_finish")}),[]),v.jsxs("div",{className:"z-10 fixed bg-background w-[220px] left-1/2 -translate-x-1/2 top-[68px] h-[32px] flex justify-center items-center gap-[18px] border-[1px] border-[solid] rounded-[14px] pl-[8px] pr-[8px]",style:{visibility:r&&t&&n?"visible":"hidden"},children:[v.jsx(LA,{value:l}),v.jsxs("div",{className:"w-[45px] flex justify-center font-nums",children:[l,"%"]})]})},Ree=()=>{const[e,t]=bt(n=>[n.file,n.updateSettings]);return f.useEffect(()=>{(async()=>{const r=await jj();t({model:r})})()},[]),v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"flex gap-3 absolute top-[68px] left-[24px] items-center",children:[v.jsx(vJ,{}),v.jsx(qq,{})]}),v.jsx(Wq,{}),v.jsx(kee,{}),v.jsx(kJ,{}),e?v.jsx(Zq,{file:e}):v.jsx(v.Fragment,{})]})},Tee=()=>{const[e,t]=f.useState(window.innerWidth),n=f.useCallback(()=>{t(window.innerWidth)},[]);if(f.useEffect(()=>(window.addEventListener("resize",n),()=>{window.removeEventListener("resize",n)})),e<768)return"mobile";if(e>=768&&e<1224)return"tablet";if(e>=1224)return"desktop"};function Pee(e){const{onSelection:t}=e,[n]=f.useState(`file-upload-${Math.random().toString()}`),r=Tee();function o(i){if(!(!i||!i.type.match("image.*")))try{if(i.size>20*1024*1024)throw new Error("file too large");t(i)}catch(l){alert(`error: ${l.message}`)}}return v.jsx("div",{className:"absolute flex w-screen h-screen justify-center items-center pointer-events-none",children:v.jsx("label",{htmlFor:n,className:"grid bg-background border-[2px] border-[dashed] rounded-lg min-w-[600px] hover:bg-primary hover:text-primary-foreground pointer-events-auto",children:v.jsxs("div",{className:"grid p-16 w-full h-full",onDragOver:i=>{i.stopPropagation(),i.preventDefault()},children:[v.jsx("input",{className:"hidden",id:n,name:n,type:"file",onChange:i=>{var l;const s=(l=i.currentTarget.files)==null?void 0:l[0];s&&o(s)},accept:"image/png, image/jpeg"}),v.jsx("p",{className:"text-center",children:r==="desktop"?"Click here or drag an image file":"Tap here to load your picture"})]})})})}const FA="ToastProvider",[cb,Aee,Oee]=zd("Toast"),[jA,Tte]=An("Toast",[Oee]),[Mee,gg]=jA(FA),zA=e=>{const{__scopeToast:t,label:n="Notification",duration:r=5e3,swipeDirection:o="right",swipeThreshold:i=50,children:s}=e,[l,u]=f.useState(null),[d,h]=f.useState(0),m=f.useRef(!1),g=f.useRef(!1);return f.createElement(cb.Provider,{scope:t},f.createElement(Mee,{scope:t,label:n,duration:r,swipeDirection:o,swipeThreshold:i,toastCount:d,viewport:l,onViewportChange:u,onToastAdd:f.useCallback(()=>h(y=>y+1),[]),onToastRemove:f.useCallback(()=>h(y=>y-1),[]),isFocusedToastEscapeKeyDownRef:m,isClosePausedRef:g},s))};zA.propTypes={label(e){if(e.label&&typeof e.label=="string"&&!e.label.trim()){const t=`Invalid prop \`label\` supplied to \`${FA}\`. Expected non-empty \`string\`.`;return new Error(t)}return null}};const Nee="ToastViewport",Dee=["F8"],Q1="toast.viewportPause",J1="toast.viewportResume",Iee=f.forwardRef((e,t)=>{const{__scopeToast:n,hotkey:r=Dee,label:o="Notifications ({hotkey})",...i}=e,s=gg(Nee,n),l=Aee(n),u=f.useRef(null),d=f.useRef(null),h=f.useRef(null),m=f.useRef(null),g=Be(t,m,s.onViewportChange),y=r.join("+").replace(/Key/g,"").replace(/Digit/g,""),x=s.toastCount>0;f.useEffect(()=>{const C=S=>{var b;r.every(k=>S[k]||S.code===k)&&((b=m.current)===null||b===void 0||b.focus())};return document.addEventListener("keydown",C),()=>document.removeEventListener("keydown",C)},[r]),f.useEffect(()=>{const C=u.current,S=m.current;if(x&&C&&S){const b=()=>{if(!s.isClosePausedRef.current){const M=new CustomEvent(Q1);S.dispatchEvent(M),s.isClosePausedRef.current=!0}},E=()=>{if(s.isClosePausedRef.current){const M=new CustomEvent(J1);S.dispatchEvent(M),s.isClosePausedRef.current=!1}},k=M=>{!C.contains(M.relatedTarget)&&E()},P=()=>{C.contains(document.activeElement)||E()};return C.addEventListener("focusin",b),C.addEventListener("focusout",k),C.addEventListener("pointermove",b),C.addEventListener("pointerleave",P),window.addEventListener("blur",b),window.addEventListener("focus",E),()=>{C.removeEventListener("focusin",b),C.removeEventListener("focusout",k),C.removeEventListener("pointermove",b),C.removeEventListener("pointerleave",P),window.removeEventListener("blur",b),window.removeEventListener("focus",E)}}},[x,s.isClosePausedRef]);const _=f.useCallback(({tabbingDirection:C})=>{const b=l().map(E=>{const k=E.ref.current,P=[k,...Qee(k)];return C==="forwards"?P:P.reverse()});return(C==="forwards"?b.reverse():b).flat()},[l]);return f.useEffect(()=>{const C=m.current;if(C){const S=b=>{const E=b.altKey||b.ctrlKey||b.metaKey;if(b.key==="Tab"&&!E){const O=document.activeElement,F=b.shiftKey;if(b.target===C&&F){var P;(P=d.current)===null||P===void 0||P.focus();return}const G=_({tabbingDirection:F?"backwards":"forwards"}),ae=G.findIndex(U=>U===O);if(j0(G.slice(ae+1)))b.preventDefault();else{var M,A;F?(M=d.current)===null||M===void 0||M.focus():(A=h.current)===null||A===void 0||A.focus()}}};return C.addEventListener("keydown",S),()=>C.removeEventListener("keydown",S)}},[l,_]),f.createElement(_B,{ref:u,role:"region","aria-label":o.replace("{hotkey}",y),tabIndex:-1,style:{pointerEvents:x?void 0:"none"}},x&&f.createElement(o$,{ref:d,onFocusFromOutsideViewport:()=>{const C=_({tabbingDirection:"forwards"});j0(C)}}),f.createElement(cb.Slot,{scope:n},f.createElement(Pe.ol,Y({tabIndex:-1},i,{ref:g}))),x&&f.createElement(o$,{ref:h,onFocusFromOutsideViewport:()=>{const C=_({tabbingDirection:"backwards"});j0(C)}}))}),Lee="ToastFocusProxy",o$=f.forwardRef((e,t)=>{const{__scopeToast:n,onFocusFromOutsideViewport:r,...o}=e,i=gg(Lee,n);return f.createElement(Um,Y({"aria-hidden":!0,tabIndex:0},o,{ref:t,style:{position:"fixed"},onFocus:s=>{var l;const u=s.relatedTarget;!((l=i.viewport)!==null&&l!==void 0&&l.contains(u))&&r()}}))}),vg="Toast",Fee="toast.swipeStart",jee="toast.swipeMove",zee="toast.swipeCancel",Bee="toast.swipeEnd",Uee=f.forwardRef((e,t)=>{const{forceMount:n,open:r,defaultOpen:o,onOpenChange:i,...s}=e,[l=!0,u]=Zr({prop:r,defaultProp:o,onChange:i});return f.createElement(xn,{present:n||l},f.createElement(BA,Y({open:l},s,{ref:t,onClose:()=>u(!1),onPause:Ft(e.onPause),onResume:Ft(e.onResume),onSwipeStart:ue(e.onSwipeStart,d=>{d.currentTarget.setAttribute("data-swipe","start")}),onSwipeMove:ue(e.onSwipeMove,d=>{const{x:h,y:m}=d.detail.delta;d.currentTarget.setAttribute("data-swipe","move"),d.currentTarget.style.setProperty("--radix-toast-swipe-move-x",`${h}px`),d.currentTarget.style.setProperty("--radix-toast-swipe-move-y",`${m}px`)}),onSwipeCancel:ue(e.onSwipeCancel,d=>{d.currentTarget.setAttribute("data-swipe","cancel"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),d.currentTarget.style.removeProperty("--radix-toast-swipe-end-x"),d.currentTarget.style.removeProperty("--radix-toast-swipe-end-y")}),onSwipeEnd:ue(e.onSwipeEnd,d=>{const{x:h,y:m}=d.detail.delta;d.currentTarget.setAttribute("data-swipe","end"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),d.currentTarget.style.setProperty("--radix-toast-swipe-end-x",`${h}px`),d.currentTarget.style.setProperty("--radix-toast-swipe-end-y",`${m}px`),u(!1)})})))}),[Vee,Wee]=jA(vg,{onClose(){}}),BA=f.forwardRef((e,t)=>{const{__scopeToast:n,type:r="foreground",duration:o,open:i,onClose:s,onEscapeKeyDown:l,onPause:u,onResume:d,onSwipeStart:h,onSwipeMove:m,onSwipeCancel:g,onSwipeEnd:y,...x}=e,_=gg(vg,n),[C,S]=f.useState(null),b=Be(t,U=>S(U)),E=f.useRef(null),k=f.useRef(null),P=o||_.duration,M=f.useRef(0),A=f.useRef(P),O=f.useRef(0),{onToastAdd:F,onToastRemove:V}=_,J=Ft(()=>{var U;(C==null?void 0:C.contains(document.activeElement))&&((U=_.viewport)===null||U===void 0||U.focus()),s()}),G=f.useCallback(U=>{!U||U===1/0||(window.clearTimeout(O.current),M.current=new Date().getTime(),O.current=window.setTimeout(J,U))},[J]);f.useEffect(()=>{const U=_.viewport;if(U){const te=()=>{G(A.current),d==null||d()},L=()=>{const ie=new Date().getTime()-M.current;A.current=A.current-ie,window.clearTimeout(O.current),u==null||u()};return U.addEventListener(Q1,L),U.addEventListener(J1,te),()=>{U.removeEventListener(Q1,L),U.removeEventListener(J1,te)}}},[_.viewport,P,u,d,G]),f.useEffect(()=>{i&&!_.isClosePausedRef.current&&G(P)},[i,P,_.isClosePausedRef,G]),f.useEffect(()=>(F(),()=>V()),[F,V]);const ae=f.useMemo(()=>C?HA(C):null,[C]);return _.viewport?f.createElement(f.Fragment,null,ae&&f.createElement(Hee,{__scopeToast:n,role:"status","aria-live":r==="foreground"?"assertive":"polite","aria-atomic":!0},ae),f.createElement(Vee,{scope:n,onClose:J},Os.createPortal(f.createElement(cb.ItemSlot,{scope:n},f.createElement(bB,{asChild:!0,onEscapeKeyDown:ue(l,()=>{_.isFocusedToastEscapeKeyDownRef.current||J(),_.isFocusedToastEscapeKeyDownRef.current=!1})},f.createElement(Pe.li,Y({role:"status","aria-live":"off","aria-atomic":!0,tabIndex:0,"data-state":i?"open":"closed","data-swipe-direction":_.swipeDirection},x,{ref:b,style:{userSelect:"none",touchAction:"none",...e.style},onKeyDown:ue(e.onKeyDown,U=>{U.key==="Escape"&&(l==null||l(U.nativeEvent),U.nativeEvent.defaultPrevented||(_.isFocusedToastEscapeKeyDownRef.current=!0,J()))}),onPointerDown:ue(e.onPointerDown,U=>{U.button===0&&(E.current={x:U.clientX,y:U.clientY})}),onPointerMove:ue(e.onPointerMove,U=>{if(!E.current)return;const te=U.clientX-E.current.x,L=U.clientY-E.current.y,ie=!!k.current,K=["left","right"].includes(_.swipeDirection),Q=["left","up"].includes(_.swipeDirection)?Math.min:Math.max,W=K?Q(0,te):0,le=K?0:Q(0,L),ge=U.pointerType==="touch"?10:2,Ve={x:W,y:le},Ue={originalEvent:U,delta:Ve};ie?(k.current=Ve,_p(jee,m,Ue,{discrete:!1})):i$(Ve,_.swipeDirection,ge)?(k.current=Ve,_p(Fee,h,Ue,{discrete:!1}),U.target.setPointerCapture(U.pointerId)):(Math.abs(te)>ge||Math.abs(L)>ge)&&(E.current=null)}),onPointerUp:ue(e.onPointerUp,U=>{const te=k.current,L=U.target;if(L.hasPointerCapture(U.pointerId)&&L.releasePointerCapture(U.pointerId),k.current=null,E.current=null,te){const ie=U.currentTarget,K={originalEvent:U,delta:te};i$(te,_.swipeDirection,_.swipeThreshold)?_p(Bee,y,K,{discrete:!0}):_p(zee,g,K,{discrete:!0}),ie.addEventListener("click",Q=>Q.preventDefault(),{once:!0})}})})))),_.viewport))):null});BA.propTypes={type(e){if(e.type&&!["foreground","background"].includes(e.type)){const t=`Invalid prop \`type\` supplied to \`${vg}\`. Expected \`foreground | background\`.`;return new Error(t)}return null}};const Hee=e=>{const{__scopeToast:t,children:n,...r}=e,o=gg(vg,t),[i,s]=f.useState(!1),[l,u]=f.useState(!1);return Zee(()=>s(!0)),f.useEffect(()=>{const d=window.setTimeout(()=>u(!0),1e3);return()=>window.clearTimeout(d)},[]),l?null:f.createElement(Md,{asChild:!0},f.createElement(Um,r,i&&f.createElement(f.Fragment,null,o.label," ",n)))},Kee=f.forwardRef((e,t)=>{const{__scopeToast:n,...r}=e;return f.createElement(Pe.div,Y({},r,{ref:t}))}),Yee=f.forwardRef((e,t)=>{const{__scopeToast:n,...r}=e;return f.createElement(Pe.div,Y({},r,{ref:t}))}),Gee="ToastAction",UA=f.forwardRef((e,t)=>{const{altText:n,...r}=e;return n?f.createElement(WA,{altText:n,asChild:!0},f.createElement(VA,Y({},r,{ref:t}))):null});UA.propTypes={altText(e){return e.altText?null:new Error(`Missing prop \`altText\` expected on \`${Gee}\``)}};const Xee="ToastClose",VA=f.forwardRef((e,t)=>{const{__scopeToast:n,...r}=e,o=Wee(Xee,n);return f.createElement(WA,{asChild:!0},f.createElement(Pe.button,Y({type:"button"},r,{ref:t,onClick:ue(e.onClick,o.onClose)})))}),WA=f.forwardRef((e,t)=>{const{__scopeToast:n,altText:r,...o}=e;return f.createElement(Pe.div,Y({"data-radix-toast-announce-exclude":"","data-radix-toast-announce-alt":r||void 0},o,{ref:t}))});function HA(e){const t=[];return Array.from(e.childNodes).forEach(r=>{if(r.nodeType===r.TEXT_NODE&&r.textContent&&t.push(r.textContent),qee(r)){const o=r.ariaHidden||r.hidden||r.style.display==="none",i=r.dataset.radixToastAnnounceExclude==="";if(!o)if(i){const s=r.dataset.radixToastAnnounceAlt;s&&t.push(s)}else t.push(...HA(r))}}),t}function _p(e,t,n,{discrete:r}){const o=n.originalEvent.currentTarget,i=new CustomEvent(e,{bubbles:!0,cancelable:!0,detail:n});t&&o.addEventListener(e,t,{once:!0}),r?cx(o,i):o.dispatchEvent(i)}const i$=(e,t,n=0)=>{const r=Math.abs(e.x),o=Math.abs(e.y),i=r>o;return t==="left"||t==="right"?i&&r>n:!i&&o>n};function Zee(e=()=>{}){const t=Ft(e);Pn(()=>{let n=0,r=0;return n=window.requestAnimationFrame(()=>r=window.requestAnimationFrame(t)),()=>{window.cancelAnimationFrame(n),window.cancelAnimationFrame(r)}},[t])}function qee(e){return e.nodeType===e.ELEMENT_NODE}function Qee(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const o=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||o?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function j0(e){const t=document.activeElement;return e.some(n=>n===t?!0:(n.focus(),document.activeElement!==t))}const Jee=zA,KA=Iee,YA=Uee,GA=Kee,XA=Yee,ZA=UA,qA=VA,ete=Jee,QA=f.forwardRef(({className:e,...t},n)=>v.jsx(KA,{ref:n,className:Ce("fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]",e),tabIndex:-1,...t}));QA.displayName=KA.displayName;const tte=Om("group pointer-events-auto relative flex w-full items-center justify-between space-x-2 overflow-hidden rounded-md border p-4 pr-6 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full",{variants:{variant:{default:"border bg-background text-foreground",destructive:"destructive group border-destructive bg-destructive text-destructive-foreground"}},defaultVariants:{variant:"default"}}),JA=f.forwardRef(({className:e,variant:t,...n},r)=>v.jsx(YA,{ref:r,className:Ce(tte({variant:t}),e),tabIndex:-1,...n}));JA.displayName=YA.displayName;const nte=f.forwardRef(({className:e,...t},n)=>v.jsx(ZA,{ref:n,className:Ce("inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium transition-colors hover:bg-secondary focus:outline-none focus:ring-1 focus:ring-ring disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive",e),tabIndex:-1,...t}));nte.displayName=ZA.displayName;const eO=f.forwardRef(({className:e,...t},n)=>v.jsx(qA,{ref:n,className:Ce("absolute right-1 top-1 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-1 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600",e),"toast-close":"",tabIndex:-1,...t,children:v.jsx(yT,{className:"h-4 w-4"})}));eO.displayName=qA.displayName;const tO=f.forwardRef(({className:e,...t},n)=>v.jsx(GA,{ref:n,className:Ce("text-sm font-semibold [&+div]:text-xs",e),tabIndex:-1,...t}));tO.displayName=GA.displayName;const nO=f.forwardRef(({className:e,...t},n)=>v.jsx(XA,{ref:n,className:Ce("text-sm opacity-90",e),...t,tabIndex:-1}));nO.displayName=XA.displayName;function rte(){const{toasts:e}=Td();return v.jsxs(ete,{children:[e.map(function({id:t,title:n,description:r,action:o,...i}){return v.jsxs(JA,{...i,children:[v.jsxs("div",{className:"grid gap-1",children:[n&&v.jsx(tO,{children:n}),r&&v.jsx(nO,{children:r})]}),o,v.jsx(eO,{})]},t)}),v.jsx(QA,{})]})}const ote=["image/jpeg","image/png","image/webp","image/bmp","image/tiff"];function ite(){const[e,t,n,r]=bt(g=>[g.file,g.updateAppState,g.setServerConfig,g.setFile]),o=Kj(),i=vH();f.useEffect(()=>{o&&r(o)},[o,r]),f.useEffect(()=>{t({windowSize:i})},[i]),f.useEffect(()=>{(async()=>{const y=await Lj();n(y),y.isDesktop&&uF()})()},[]);const s=f.useRef(0),l=f.useCallback(g=>{g.preventDefault(),g.stopPropagation()},[]),u=f.useCallback(g=>{g.preventDefault(),g.stopPropagation(),s.current+=1},[]),d=f.useCallback(g=>{g.preventDefault(),g.stopPropagation(),s.current-=1,s.current>0},[]),h=f.useCallback(g=>{if(g.preventDefault(),g.stopPropagation(),g.dataTransfer.files&&g.dataTransfer.files.length>0){if(!(g.dataTransfer.files.length>1)){const y=g.dataTransfer.files[0],x=y.type;ote.includes(x)&&r(y)}g.dataTransfer.clearData()}},[]),m=f.useCallback(g=>{if(!g.clipboardData)return;const y=g.clipboardData.items,x=[].slice.call(y).filter(S=>S.type.indexOf("image")!==-1);if(x.length===0)return;g.preventDefault(),g.stopPropagation();const C=x[0].getAsFile();C&&r(C)},[]);return f.useEffect(()=>(window.addEventListener("dragenter",u),window.addEventListener("dragleave",d),window.addEventListener("dragover",l),window.addEventListener("drop",h),window.addEventListener("paste",m),function(){window.removeEventListener("dragenter",u),window.removeEventListener("dragleave",d),window.removeEventListener("dragover",l),window.removeEventListener("drop",h),window.removeEventListener("paste",m)})),v.jsxs("main",{className:"flex min-h-screen flex-col items-center justify-between w-full bg-[radial-gradient(circle_at_1px_1px,_#8e8e8e8e_1px,_transparent_0)] [background-size:20px_20px] bg-repeat",children:[v.jsx(rte,{}),v.jsx(nZ,{}),v.jsx(Ree,{}),e?v.jsx(v.Fragment,{}):v.jsx(Pee,{onSelection:async g=>{r(g)}})]})}const sm=["light","dark"],ub="(prefers-color-scheme: dark)",ste=typeof window>"u",rO=f.createContext(void 0),ate=e=>f.useContext(rO)?Fe.createElement(f.Fragment,null,e.children):Fe.createElement(cte,e),lte=["light","dark"],cte=({forcedTheme:e,disableTransitionOnChange:t=!1,enableSystem:n=!0,enableColorScheme:r=!0,storageKey:o="theme",themes:i=lte,defaultTheme:s=n?"system":"light",attribute:l="data-theme",value:u,children:d,nonce:h})=>{const[m,g]=f.useState(()=>s$(o,s)),[y,x]=f.useState(()=>s$(o)),_=u?Object.values(u):i,C=f.useCallback(k=>{let P=k;if(!P)return;k==="system"&&n&&(P=a$());const M=u?u[P]:P,A=t?dte():null,O=document.documentElement;if(l==="class"?(O.classList.remove(..._),M&&O.classList.add(M)):M?O.setAttribute(l,M):O.removeAttribute(l),r){const F=sm.includes(s)?s:null,V=sm.includes(P)?P:F;O.style.colorScheme=V}A==null||A()},[]),S=f.useCallback(k=>{g(k);try{localStorage.setItem(o,k)}catch{}},[e]),b=f.useCallback(k=>{const P=a$(k);x(P),m==="system"&&n&&!e&&C("system")},[m,e]);f.useEffect(()=>{const k=window.matchMedia(ub);return k.addListener(b),b(k),()=>k.removeListener(b)},[b]),f.useEffect(()=>{const k=P=>{P.key===o&&S(P.newValue||s)};return window.addEventListener("storage",k),()=>window.removeEventListener("storage",k)},[S]),f.useEffect(()=>{C(e??m)},[e,m]);const E=f.useMemo(()=>({theme:m,setTheme:S,forcedTheme:e,resolvedTheme:m==="system"?y:m,themes:n?[...i,"system"]:i,systemTheme:n?y:void 0}),[m,S,e,y,n,i]);return Fe.createElement(rO.Provider,{value:E},Fe.createElement(ute,{forcedTheme:e,disableTransitionOnChange:t,enableSystem:n,enableColorScheme:r,storageKey:o,themes:i,defaultTheme:s,attribute:l,value:u,children:d,attrs:_,nonce:h}),d)},ute=f.memo(({forcedTheme:e,storageKey:t,attribute:n,enableSystem:r,enableColorScheme:o,defaultTheme:i,value:s,attrs:l,nonce:u})=>{const d=i==="system",h=n==="class"?`var d=document.documentElement,c=d.classList;c.remove(${l.map(x=>`'${x}'`).join(",")});`:`var d=document.documentElement,n='${n}',s='setAttribute';`,m=o?sm.includes(i)&&i?`if(e==='light'||e==='dark'||!e)d.style.colorScheme=e||'${i}'`:"if(e==='light'||e==='dark')d.style.colorScheme=e":"",g=(x,_=!1,C=!0)=>{const S=s?s[x]:x,b=_?x+"|| ''":`'${S}'`;let E="";return o&&C&&!_&&sm.includes(x)&&(E+=`d.style.colorScheme = '${x}';`),n==="class"?E+=_||S?`c.add(${b})`:"null":S&&(E+=`d[s](n,${b})`),E},y=e?`!function(){${h}${g(e)}}()`:r?`!function(){try{${h}var e=localStorage.getItem('${t}');if('system'===e||(!e&&${d})){var t='${ub}',m=window.matchMedia(t);if(m.media!==t||m.matches){${g("dark")}}else{${g("light")}}}else if(e){${s?`var x=${JSON.stringify(s)};`:""}${g(s?"x[e]":"e",!0)}}${d?"":"else{"+g(i,!1,!1)+"}"}${m}}catch(e){}}()`:`!function(){try{${h}var e=localStorage.getItem('${t}');if(e){${s?`var x=${JSON.stringify(s)};`:""}${g(s?"x[e]":"e",!0)}}else{${g(i,!1,!1)};}${m}}catch(t){}}();`;return Fe.createElement("script",{nonce:u,dangerouslySetInnerHTML:{__html:y}})},()=>!0),s$=(e,t)=>{if(ste)return;let n;try{n=localStorage.getItem(e)||void 0}catch{}return n||t},dte=()=>{const e=document.createElement("style");return e.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(e),()=>{window.getComputedStyle(document.body),setTimeout(()=>{document.head.removeChild(e)},1)}},a$=e=>(e||(e=window.matchMedia(ub)),e.matches?"dark":"light"),fte=new dL;z0.createRoot(document.getElementById("root")).render(v.jsx(Fe.StrictMode,{children:v.jsx(gL,{client:fte,children:v.jsx(ate,{defaultTheme:"dark",disableTransitionOnChange:!0,children:v.jsx(BU,{children:v.jsx(ite,{})})})})})); diff --git a/py/iopaint/web_app/assets/index-UXaKiZjP.css b/py/iopaint/web_app/assets/index-UXaKiZjP.css new file mode 100644 index 0000000..9d489eb --- /dev/null +++ b/py/iopaint/web_app/assets/index-UXaKiZjP.css @@ -0,0 +1 @@ +@font-face{font-family:Inter;font-style:normal;font-weight:100;font-display:swap;src:url(/assets/Inter-Thin-eKObIkJC.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:italic;font-weight:100;font-display:swap;src:url(/assets/Inter-ThinItalic-L6uBn3RP.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:normal;font-weight:200;font-display:swap;src:url(/assets/Inter-ExtraLight-w5HAp5iF.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:italic;font-weight:200;font-display:swap;src:url(/assets/Inter-ExtraLightItalic-ZptecSuc.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:normal;font-weight:300;font-display:swap;src:url(/assets/Inter-Light-DFhX0qo-.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:italic;font-weight:300;font-display:swap;src:url(/assets/Inter-LightItalic-fu56_DRc.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:normal;font-weight:400;font-display:swap;src:url(/assets/Inter-Regular-dEFHw1tF.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:italic;font-weight:400;font-display:swap;src:url(/assets/Inter-Italic-f6M78thn.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:normal;font-weight:500;font-display:swap;src:url(/assets/Inter-Medium-dDRaJ8tM.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:italic;font-weight:500;font-display:swap;src:url(/assets/Inter-MediumItalic-zr3roggP.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:normal;font-weight:600;font-display:swap;src:url(/assets/Inter-SemiBold-PyS8DO2L.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:italic;font-weight:600;font-display:swap;src:url(/assets/Inter-SemiBoldItalic-uIDb7hsH.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:normal;font-weight:700;font-display:swap;src:url(/assets/Inter-Bold-srYz_-1B.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:italic;font-weight:700;font-display:swap;src:url(/assets/Inter-BoldItalic-dE_gZyur.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:normal;font-weight:800;font-display:swap;src:url(/assets/Inter-ExtraBold-TduDdwUu.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:italic;font-weight:800;font-display:swap;src:url(/assets/Inter-ExtraBoldItalic-BJafRE5I.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:normal;font-weight:900;font-display:swap;src:url(/assets/Inter-Black-jiII8dog.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:italic;font-weight:900;font-display:swap;src:url(/assets/Inter-BlackItalic-1413vuen.woff2?v=4.0) format("woff2")}*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:before,:after{--tw-content: ""}html{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,"Apple Color Emoji","Segoe UI Emoji",Segoe UI Symbol,"Noto Color Emoji";font-feature-settings:normal;font-variation-settings:normal}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,[type=button],[type=reset],[type=submit]{-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]{display:none}:root{--background: 0 0% 100%;--foreground: 224 71.4% 4.1%;--card: 0 0% 100%;--card-foreground: 224 71.4% 4.1%;--popover: 0 0% 100%;--popover-foreground: 224 71.4% 4.1%;--primary: 48 100% 50%;--primary-foreground: 210 20% 98%;--secondary: 220 14.3% 95.9%;--secondary-foreground: 220.9 39.3% 11%;--muted: 220 14.3% 95.9%;--muted-foreground: 220 8.9% 46.1%;--accent: 220 14.3% 95.9%;--accent-foreground: 220.9 39.3% 11%;--destructive: 0 84.2% 60.2%;--destructive-foreground: 210 20% 98%;--border: 220 13% 91%;--input: 220 13% 91%;--ring: 224 71.4% 4.1%;--radius: .5rem}[data-theme=dark]{--background: 240 10% 3.9%;--foreground: 0 0% 98%;--card: 224 71.4% 4.1%;--card-foreground: 210 20% 98%;--popover: 240 10% 3.9%;--popover-foreground: 0 0% 98%;--primary: 48 100% 50%;--primary-foreground: 220.9 39.3% 11%;--secondary: 240 3.7% 15.9%;--secondary-foreground: 0 0% 98%;--muted: 240 3.7% 15.9%;--muted-foreground: 240 5% 64.9%;--accent: 240 3.7% 15.9%;--accent-foreground: 0 0% 98%;--destructive: 0 62.8% 30.6%;--destructive-foreground: 0 85.7% 97.3%;--border: 240 3.7% 15.9%;--input: 240 3.7% 15.9%;--ring: 240 4.9% 83.9%}*{border-color:hsl(var(--border))}body{background-color:hsl(var(--background));color:hsl(var(--foreground))}*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: }.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border-width:0}.pointer-events-none{pointer-events:none}.pointer-events-auto{pointer-events:auto}.visible{visibility:visible}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.inset-0{top:0;right:0;bottom:0;left:0}.inset-x-0{left:0;right:0}.inset-y-0{top:0;bottom:0}.bottom-0{bottom:0}.bottom-5{bottom:1.25rem}.bottom-6{bottom:1.5rem}.left-0{left:0}.left-1\/2{left:50%}.left-2{left:.5rem}.left-\[24px\]{left:24px}.left-\[50\%\]{left:50%}.left-\[8px\]{left:8px}.right-0{right:0}.right-1{right:.25rem}.right-10{right:2.5rem}.right-2{right:.5rem}.right-4{right:1rem}.right-6{right:1.5rem}.top-0{top:0}.top-1{top:.25rem}.top-4{top:1rem}.top-\[0\]{top:0}.top-\[50\%\]{top:50%}.top-\[68px\]{top:68px}.z-10{z-index:10}.z-20{z-index:20}.z-50{z-index:50}.z-\[100\]{z-index:100}.z-\[2\]{z-index:2}.z-\[4\]{z-index:4}.m-3{margin:.75rem}.-mx-1{margin-left:-.25rem;margin-right:-.25rem}.my-1{margin-top:.25rem;margin-bottom:.25rem}.mb-2{margin-bottom:.5rem}.mb-8{margin-bottom:2rem}.mb-\[-6px\]{margin-bottom:-6px}.ml-\[-6px\]{margin-left:-6px}.ml-auto{margin-left:auto}.mr-8{margin-right:2rem}.mr-\[-6px\]{margin-right:-6px}.mt-0{margin-top:0}.mt-2{margin-top:.5rem}.mt-4{margin-top:1rem}.mt-\[-6px\]{margin-top:-6px}.mt-\[60px\]{margin-top:60px}.block{display:block}.flex{display:flex}.inline-flex{display:inline-flex}.grid{display:grid}.hidden{display:none}.aspect-square{aspect-ratio:1 / 1}.h-1{height:.25rem}.h-1\.5{height:.375rem}.h-10{height:2.5rem}.h-2{height:.5rem}.h-2\.5{height:.625rem}.h-3{height:.75rem}.h-3\.5{height:.875rem}.h-4{height:1rem}.h-4\/5{height:80%}.h-5{height:1.25rem}.h-6{height:1.5rem}.h-7{height:1.75rem}.h-8{height:2rem}.h-9{height:2.25rem}.h-\[10px\]{height:10px}.h-\[12px\]{height:12px}.h-\[1px\]{height:1px}.h-\[20px\]{height:20px}.h-\[240px\]{height:240px}.h-\[32px\]{height:32px}.h-\[600px\]{height:600px}.h-\[60px\]{height:60px}.h-\[var\(--radix-select-trigger-height\)\]{height:var(--radix-select-trigger-height)}.h-full{height:100%}.h-px{height:1px}.h-screen{height:100vh}.max-h-96{max-height:24rem}.max-h-\[200px\]{max-height:200px}.max-h-\[8rem\]{max-height:8rem}.max-h-screen{max-height:100vh}.min-h-\[60px\]{min-height:60px}.min-h-screen{min-height:100vh}.w-14{width:3.5rem}.w-2{width:.5rem}.w-2\.5{width:.625rem}.w-3{width:.75rem}.w-3\.5{width:.875rem}.w-3\/4{width:75%}.w-4{width:1rem}.w-48{width:12rem}.w-6{width:1.5rem}.w-72{width:18rem}.w-8{width:2rem}.w-9{width:2.25rem}.w-\[100px\]{width:100px}.w-\[10px\]{width:10px}.w-\[12px\]{width:12px}.w-\[140px\]{width:140px}.w-\[160px\]{width:160px}.w-\[175px\]{width:175px}.w-\[180px\]{width:180px}.w-\[1px\]{width:1px}.w-\[20px\]{width:20px}.w-\[220px\]{width:220px}.w-\[250px\]{width:250px}.w-\[300px\]{width:300px}.w-\[400px\]{width:400px}.w-\[45px\]{width:45px}.w-\[510px\]{width:510px}.w-\[60px\]{width:60px}.w-\[65px\]{width:65px}.w-\[6px\]{width:6px}.w-auto{width:auto}.w-full{width:100%}.w-screen{width:100vw}.min-w-\[500px\]{min-width:500px}.min-w-\[600px\]{min-width:600px}.min-w-\[8rem\]{min-width:8rem}.min-w-\[var\(--radix-select-trigger-width\)\]{min-width:var(--radix-select-trigger-width)}.max-w-3xl{max-width:48rem}.max-w-6xl{max-width:72rem}.max-w-\[200px\]{max-width:200px}.max-w-lg{max-width:32rem}.max-w-sm{max-width:24rem}.max-w-xs{max-width:20rem}.flex-1{flex:1 1 0%}.shrink{flex-shrink:1}.shrink-0{flex-shrink:0}.grow{flex-grow:1}.origin-top-left{transform-origin:top left}.-translate-x-1\/2,.translate-x-\[-50\%\]{--tw-translate-x: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-y-\[-50\%\]{--tw-translate-y: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.transform{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}@keyframes pulse{50%{opacity:.5}}.animate-pulse{animation:pulse 2s cubic-bezier(.4,0,.6,1) infinite}@keyframes spin{to{transform:rotate(360deg)}}.animate-spin{animation:spin 1s linear infinite}.cursor-default{cursor:default}.cursor-ew-resize{cursor:ew-resize}.cursor-ne-resize{cursor:ne-resize}.cursor-ns-resize{cursor:ns-resize}.cursor-nw-resize{cursor:nw-resize}.cursor-pointer{cursor:pointer}.cursor-se-resize{cursor:se-resize}.cursor-sw-resize{cursor:sw-resize}.touch-none{touch-action:none}.select-none{-webkit-user-select:none;-moz-user-select:none;user-select:none}.resize{resize:both}.flex-row{flex-direction:row}.flex-col{flex-direction:column}.flex-col-reverse{flex-direction:column-reverse}.items-center{align-items:center}.justify-start{justify-content:flex-start}.justify-end{justify-content:flex-end}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.gap-1{gap:.25rem}.gap-2{gap:.5rem}.gap-3{gap:.75rem}.gap-4{gap:1rem}.gap-6{gap:1.5rem}.gap-8{gap:2rem}.gap-\[12px\]{gap:12px}.gap-\[18px\]{gap:18px}.gap-\[8px\]{gap:8px}.gap-y-4{row-gap:1rem}.space-x-2>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.5rem * var(--tw-space-x-reverse));margin-left:calc(.5rem * calc(1 - var(--tw-space-x-reverse)))}.space-x-8>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(2rem * var(--tw-space-x-reverse));margin-left:calc(2rem * calc(1 - var(--tw-space-x-reverse)))}.space-y-0>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(0px * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(0px * var(--tw-space-y-reverse))}.space-y-0\.5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.125rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.125rem * var(--tw-space-y-reverse))}.space-y-1>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.25rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.25rem * var(--tw-space-y-reverse))}.space-y-1\.5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.375rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.375rem * var(--tw-space-y-reverse))}.space-y-2>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.5rem * var(--tw-space-y-reverse))}.space-y-4>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1rem * var(--tw-space-y-reverse))}.justify-self-end{justify-self:end}.overflow-auto{overflow:auto}.overflow-hidden{overflow:hidden}.overflow-y-auto{overflow-y:auto}.whitespace-nowrap{white-space:nowrap}.rounded-\[14px\]{border-radius:14px}.rounded-\[3rem\]{border-radius:3rem}.rounded-\[50\%\]{border-radius:50%}.rounded-\[inherit\]{border-radius:inherit}.rounded-full{border-radius:9999px}.rounded-lg{border-radius:var(--radius)}.rounded-md{border-radius:calc(var(--radius) - 2px)}.rounded-sm{border-radius:calc(var(--radius) - 4px)}.rounded-xl{border-radius:.75rem}.border{border-width:1px}.border-2{border-width:2px}.border-\[1px\]{border-width:1px}.border-\[2px\]{border-width:2px}.border-b{border-bottom-width:1px}.border-l{border-left-width:1px}.border-r{border-right-width:1px}.border-t{border-top-width:1px}.border-solid{border-style:solid}.border-\[\#ffcc00\]{--tw-border-opacity: 1;border-color:rgb(255 204 0 / var(--tw-border-opacity))}.border-\[dashed\]{border-color:dashed}.border-\[solid\]{border-color:solid}.border-destructive{border-color:hsl(var(--destructive))}.border-input{border-color:hsl(var(--input))}.border-primary{border-color:hsl(var(--primary))}.border-primary\/60{border-color:hsl(var(--primary) / .6)}.border-transparent{border-color:transparent}.border-l-transparent{border-left-color:transparent}.border-t-transparent{border-top-color:transparent}.bg-\[\#ffcc00bb\]{background-color:#fc0b}.bg-\[rgba\(21\,_215\,_121\,_0\.936\)\]{background-color:#15d779ef}.bg-\[rgba\(237\,_49\,_55\,_0\.942\)\]{background-color:#ed3137f0}.bg-background{background-color:hsl(var(--background))}.bg-background\/70{background-color:hsl(var(--background) / .7)}.bg-background\/80{background-color:hsl(var(--background) / .8)}.bg-border{background-color:hsl(var(--border))}.bg-destructive{background-color:hsl(var(--destructive))}.bg-muted{background-color:hsl(var(--muted))}.bg-popover{background-color:hsl(var(--popover))}.bg-primary{background-color:hsl(var(--primary))}.bg-primary\/20{background-color:hsl(var(--primary) / .2)}.bg-secondary{background-color:hsl(var(--secondary))}.bg-transparent{background-color:transparent}.bg-\[radial-gradient\(circle_at_1px_1px\,_\#8e8e8e8e_1px\,_transparent_0\)\]{background-image:radial-gradient(circle at 1px 1px,#8e8e8e8e 1px,transparent 0)}.bg-repeat{background-repeat:repeat}.fill-current{fill:currentColor}.fill-primary{fill:hsl(var(--primary))}.p-1{padding:.25rem}.p-1\.5{padding:.375rem}.p-16{padding:4rem}.p-4{padding:1rem}.p-6{padding:1.5rem}.p-\[1px\]{padding:1px}.p-\[8px\]{padding:8px}.px-2{padding-left:.5rem;padding-right:.5rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-4{padding-left:1rem;padding-right:1rem}.px-6{padding-left:1.5rem;padding-right:1.5rem}.px-8{padding-left:2rem;padding-right:2rem}.py-1{padding-top:.25rem;padding-bottom:.25rem}.py-1\.5{padding-top:.375rem;padding-bottom:.375rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.py-3{padding-top:.75rem;padding-bottom:.75rem}.py-4{padding-top:1rem;padding-bottom:1rem}.py-\[6px\]{padding-top:6px;padding-bottom:6px}.pb-4{padding-bottom:1rem}.pl-2{padding-left:.5rem}.pl-4{padding-left:1rem}.pl-8{padding-left:2rem}.pl-\[30px\]{padding-left:30px}.pl-\[8px\]{padding-left:8px}.pr-1{padding-right:.25rem}.pr-2{padding-right:.5rem}.pr-3{padding-right:.75rem}.pr-4{padding-right:1rem}.pr-6{padding-right:1.5rem}.pr-8{padding-right:2rem}.pr-\[8px\]{padding-right:8px}.pt-0{padding-top:0}.pt-4{padding-top:1rem}.text-center{text-align:center}.text-2xl{font-size:1.5rem;line-height:2rem}.text-\[0\.8rem\]{font-size:.8rem}.text-base{font-size:1rem;line-height:1.5rem}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xs{font-size:.75rem;line-height:1rem}.font-medium{font-weight:500}.font-semibold{font-weight:600}.leading-none{line-height:1}.tracking-tight{letter-spacing:-.025em}.tracking-widest{letter-spacing:.1em}.text-destructive{color:hsl(var(--destructive))}.text-destructive-foreground{color:hsl(var(--destructive-foreground))}.text-foreground{color:hsl(var(--foreground))}.text-foreground\/50{color:hsl(var(--foreground) / .5)}.text-gray-200{--tw-text-opacity: 1;color:rgb(229 231 235 / var(--tw-text-opacity))}.text-muted-foreground{color:hsl(var(--muted-foreground))}.text-popover-foreground{color:hsl(var(--popover-foreground))}.text-primary{color:hsl(var(--primary))}.text-primary-foreground{color:hsl(var(--primary-foreground))}.text-secondary-foreground{color:hsl(var(--secondary-foreground))}.underline-offset-4{text-underline-offset:4px}.opacity-0{opacity:0}.opacity-50{opacity:.5}.opacity-60{opacity:.6}.opacity-70{opacity:.7}.opacity-90{opacity:.9}.shadow{--tw-shadow: 0 1px 3px 0 rgb(0 0 0 / .1), 0 1px 2px -1px rgb(0 0 0 / .1);--tw-shadow-colored: 0 1px 3px 0 var(--tw-shadow-color), 0 1px 2px -1px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-lg{--tw-shadow: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1);--tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-md{--tw-shadow: 0 4px 6px -1px rgb(0 0 0 / .1), 0 2px 4px -2px rgb(0 0 0 / .1);--tw-shadow-colored: 0 4px 6px -1px var(--tw-shadow-color), 0 2px 4px -2px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-sm{--tw-shadow: 0 1px 2px 0 rgb(0 0 0 / .05);--tw-shadow-colored: 0 1px 2px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.outline-none{outline:2px solid transparent;outline-offset:2px}.outline{outline-style:solid}.outline-dashed{outline-style:dashed}.outline-8{outline-width:8px}.outline-\[rgba\(255\,89\,95\,0\.31\)\]{outline-color:#ff595f4f}.outline-\[rgba\(98\,255\,179\,0\.31\)\]{outline-color:#62ffb34f}.outline-primary{outline-color:hsl(var(--primary))}.ring-0{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(0px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.ring-offset-background{--tw-ring-offset-color: hsl(var(--background))}.blur{--tw-blur: blur(8px);filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.backdrop-blur-md{--tw-backdrop-blur: blur(12px);-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.backdrop-blur-sm{--tw-backdrop-blur: blur(4px);-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.backdrop-filter{-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.transition{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,-webkit-backdrop-filter;transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter;transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter,-webkit-backdrop-filter;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-all{transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-colors{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-opacity{transition-property:opacity;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-transform{transition-property:transform;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.duration-200{transition-duration:.2s}.ease-in-out{transition-timing-function:cubic-bezier(.4,0,.2,1)}.content-\[\'\'\]{--tw-content: "";content:var(--tw-content)}@keyframes enter{0%{opacity:var(--tw-enter-opacity, 1);transform:translate3d(var(--tw-enter-translate-x, 0),var(--tw-enter-translate-y, 0),0) scale3d(var(--tw-enter-scale, 1),var(--tw-enter-scale, 1),var(--tw-enter-scale, 1)) rotate(var(--tw-enter-rotate, 0))}}@keyframes exit{to{opacity:var(--tw-exit-opacity, 1);transform:translate3d(var(--tw-exit-translate-x, 0),var(--tw-exit-translate-y, 0),0) scale3d(var(--tw-exit-scale, 1),var(--tw-exit-scale, 1),var(--tw-exit-scale, 1)) rotate(var(--tw-exit-rotate, 0))}}.animate-in{animation-name:enter;animation-duration:.15s;--tw-enter-opacity: initial;--tw-enter-scale: initial;--tw-enter-rotate: initial;--tw-enter-translate-x: initial;--tw-enter-translate-y: initial}.fade-in-0{--tw-enter-opacity: 0}.zoom-in-95{--tw-enter-scale: .95}.duration-200{animation-duration:.2s}.ease-in-out{animation-timing-function:cubic-bezier(.4,0,.2,1)}.\[background-size\:20px_20px\]{background-size:20px 20px}.\[box-shadow\:0_0_0_0_rgba\(21\,_215\,_121\,_0\.936\)\]{box-shadow:0 0 #15d779ef}.\[box-shadow\:0_0_0_9999px_rgba\(0\,_0\,_0\,_0\.5\)\]{box-shadow:0 0 0 9999px #00000080}.\[grid-area\:editor-content\]{grid-area:editor-content}.\[grid-area\:original-image-content\]{grid-area:original-image-content}.\[grid-template-areas\:\'editor-content\'\]{grid-template-areas:"editor-content"}.\[grid-template-areas\:\'original-image-content\'\]{grid-template-areas:"original-image-content"}html{font-family:Inter,"system-ui";overflow:hidden}@supports (font-variation-settings: normal){html{font-family:Inter var,"system-ui"}}.react-transform-wrapper{display:grid!important;width:100%!important;height:100%!important}.react-photo-album{padding:8px}.react-photo-album--photo{-moz-user-select:none;-webkit-user-select:none;user-select:none;border-radius:8px;transition:transform .25s,visibility .25s ease-in}.react-photo-album--photo:hover{border:1px solid var(--border);transform:scale(1.03)}.icon-button-icon-wrapper svg{stroke-width:1px}.file\:border-0::file-selector-button{border-width:0px}.file\:bg-transparent::file-selector-button{background-color:transparent}.file\:text-sm::file-selector-button{font-size:.875rem;line-height:1.25rem}.file\:font-medium::file-selector-button{font-weight:500}.placeholder\:text-muted-foreground::-moz-placeholder{color:hsl(var(--muted-foreground))}.placeholder\:text-muted-foreground::placeholder{color:hsl(var(--muted-foreground))}.hover\:cursor-move:hover{cursor:move}.hover\:bg-accent:hover{background-color:hsl(var(--accent))}.hover\:bg-destructive\/90:hover{background-color:hsl(var(--destructive) / .9)}.hover\:bg-muted:hover{background-color:hsl(var(--muted))}.hover\:bg-primary:hover{background-color:hsl(var(--primary))}.hover\:bg-primary\/90:hover{background-color:hsl(var(--primary) / .9)}.hover\:bg-secondary:hover{background-color:hsl(var(--secondary))}.hover\:bg-secondary\/80:hover{background-color:hsl(var(--secondary) / .8)}.hover\:text-accent-foreground:hover{color:hsl(var(--accent-foreground))}.hover\:text-foreground:hover{color:hsl(var(--foreground))}.hover\:text-muted-foreground:hover{color:hsl(var(--muted-foreground))}.hover\:text-primary-foreground:hover{color:hsl(var(--primary-foreground))}.hover\:underline:hover{text-decoration-line:underline}.hover\:opacity-100:hover{opacity:1}.focus\:bg-accent:focus{background-color:hsl(var(--accent))}.focus\:text-accent-foreground:focus{color:hsl(var(--accent-foreground))}.focus\:opacity-100:focus{opacity:1}.focus\:outline-none:focus{outline:2px solid transparent;outline-offset:2px}.focus\:ring-1:focus{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus\:ring-2:focus{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus\:ring-ring:focus{--tw-ring-color: hsl(var(--ring))}.focus\:ring-offset-2:focus{--tw-ring-offset-width: 2px}.focus-visible\:outline-none:focus-visible{outline:2px solid transparent;outline-offset:2px}.focus-visible\:ring-1:focus-visible{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus-visible\:ring-2:focus-visible{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus-visible\:ring-ring:focus-visible{--tw-ring-color: hsl(var(--ring))}.focus-visible\:ring-offset-2:focus-visible{--tw-ring-offset-width: 2px}.focus-visible\:ring-offset-background:focus-visible{--tw-ring-offset-color: hsl(var(--background))}.disabled\:pointer-events-none:disabled{pointer-events:none}.disabled\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\:opacity-50:disabled{opacity:.5}.group:hover .group-hover\:opacity-100{opacity:1}.group.destructive .group-\[\.destructive\]\:border-muted\/40{border-color:hsl(var(--muted) / .4)}.group.destructive .group-\[\.destructive\]\:text-red-300{--tw-text-opacity: 1;color:rgb(252 165 165 / var(--tw-text-opacity))}.group.destructive .group-\[\.destructive\]\:hover\:border-destructive\/30:hover{border-color:hsl(var(--destructive) / .3)}.group.destructive .group-\[\.destructive\]\:hover\:bg-destructive:hover{background-color:hsl(var(--destructive))}.group.destructive .group-\[\.destructive\]\:hover\:text-destructive-foreground:hover{color:hsl(var(--destructive-foreground))}.group.destructive .group-\[\.destructive\]\:hover\:text-red-50:hover{--tw-text-opacity: 1;color:rgb(254 242 242 / var(--tw-text-opacity))}.group.destructive .group-\[\.destructive\]\:focus\:ring-destructive:focus{--tw-ring-color: hsl(var(--destructive))}.group.destructive .group-\[\.destructive\]\:focus\:ring-red-400:focus{--tw-ring-opacity: 1;--tw-ring-color: rgb(248 113 113 / var(--tw-ring-opacity))}.group.destructive .group-\[\.destructive\]\:focus\:ring-offset-red-600:focus{--tw-ring-offset-color: #dc2626}.peer:disabled~.peer-disabled\:cursor-not-allowed{cursor:not-allowed}.peer:disabled~.peer-disabled\:opacity-70{opacity:.7}.data-\[disabled\]\:pointer-events-none[data-disabled]{pointer-events:none}.data-\[side\=bottom\]\:translate-y-1[data-side=bottom]{--tw-translate-y: .25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[side\=left\]\:-translate-x-1[data-side=left]{--tw-translate-x: -.25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[side\=right\]\:translate-x-1[data-side=right]{--tw-translate-x: .25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[side\=top\]\:-translate-y-1[data-side=top]{--tw-translate-y: -.25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[state\=checked\]\:translate-x-4[data-state=checked]{--tw-translate-x: 1rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[state\=unchecked\]\:translate-x-0[data-state=unchecked],.data-\[swipe\=cancel\]\:translate-x-0[data-swipe=cancel]{--tw-translate-x: 0px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[swipe\=end\]\:translate-x-\[var\(--radix-toast-swipe-end-x\)\][data-swipe=end]{--tw-translate-x: var(--radix-toast-swipe-end-x);transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[swipe\=move\]\:translate-x-\[var\(--radix-toast-swipe-move-x\)\][data-swipe=move]{--tw-translate-x: var(--radix-toast-swipe-move-x);transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}@keyframes accordion-up{0%{height:var(--radix-accordion-content-height)}to{height:0}}.data-\[state\=closed\]\:animate-accordion-up[data-state=closed]{animation:accordion-up .2s ease-out}@keyframes accordion-down{0%{height:0}to{height:var(--radix-accordion-content-height)}}.data-\[state\=open\]\:animate-accordion-down[data-state=open]{animation:accordion-down .2s ease-out}.data-\[disabled\]\:cursor-not-allowed[data-disabled]{cursor:not-allowed}.data-\[state\=active\]\:bg-background[data-state=active]{background-color:hsl(var(--background))}.data-\[state\=checked\]\:bg-primary[data-state=checked]{background-color:hsl(var(--primary))}.data-\[state\=on\]\:bg-accent[data-state=on],.data-\[state\=open\]\:bg-accent[data-state=open]{background-color:hsl(var(--accent))}.data-\[state\=unchecked\]\:bg-input[data-state=unchecked]{background-color:hsl(var(--input))}.data-\[state\=active\]\:text-foreground[data-state=active]{color:hsl(var(--foreground))}.data-\[state\=on\]\:text-accent-foreground[data-state=on],.data-\[state\=open\]\:text-accent-foreground[data-state=open]{color:hsl(var(--accent-foreground))}.data-\[state\=open\]\:text-muted-foreground[data-state=open]{color:hsl(var(--muted-foreground))}.data-\[disabled\]\:opacity-50[data-disabled]{opacity:.5}.data-\[state\=active\]\:shadow[data-state=active]{--tw-shadow: 0 1px 3px 0 rgb(0 0 0 / .1), 0 1px 2px -1px rgb(0 0 0 / .1);--tw-shadow-colored: 0 1px 3px 0 var(--tw-shadow-color), 0 1px 2px -1px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.data-\[swipe\=move\]\:transition-none[data-swipe=move]{transition-property:none}.data-\[state\=closed\]\:duration-200[data-state=closed]{transition-duration:.2s}.data-\[state\=open\]\:duration-300[data-state=open]{transition-duration:.3s}.data-\[state\=open\]\:animate-in[data-state=open]{animation-name:enter;animation-duration:.15s;--tw-enter-opacity: initial;--tw-enter-scale: initial;--tw-enter-rotate: initial;--tw-enter-translate-x: initial;--tw-enter-translate-y: initial}.data-\[state\=closed\]\:animate-out[data-state=closed],.data-\[swipe\=end\]\:animate-out[data-swipe=end]{animation-name:exit;animation-duration:.15s;--tw-exit-opacity: initial;--tw-exit-scale: initial;--tw-exit-rotate: initial;--tw-exit-translate-x: initial;--tw-exit-translate-y: initial}.data-\[state\=closed\]\:fade-out-0[data-state=closed]{--tw-exit-opacity: 0}.data-\[state\=closed\]\:fade-out-80[data-state=closed]{--tw-exit-opacity: .8}.data-\[state\=open\]\:fade-in-0[data-state=open]{--tw-enter-opacity: 0}.data-\[state\=closed\]\:zoom-out-95[data-state=closed]{--tw-exit-scale: .95}.data-\[state\=open\]\:zoom-in-95[data-state=open]{--tw-enter-scale: .95}.data-\[side\=bottom\]\:slide-in-from-top-2[data-side=bottom]{--tw-enter-translate-y: -.5rem}.data-\[side\=left\]\:slide-in-from-right-2[data-side=left]{--tw-enter-translate-x: .5rem}.data-\[side\=right\]\:slide-in-from-left-2[data-side=right]{--tw-enter-translate-x: -.5rem}.data-\[side\=top\]\:slide-in-from-bottom-2[data-side=top]{--tw-enter-translate-y: .5rem}.data-\[state\=closed\]\:slide-out-to-bottom[data-state=closed]{--tw-exit-translate-y: 100%}.data-\[state\=closed\]\:slide-out-to-left[data-state=closed]{--tw-exit-translate-x: -100%}.data-\[state\=closed\]\:slide-out-to-left-1\/2[data-state=closed]{--tw-exit-translate-x: -50%}.data-\[state\=closed\]\:slide-out-to-right[data-state=closed],.data-\[state\=closed\]\:slide-out-to-right-full[data-state=closed]{--tw-exit-translate-x: 100%}.data-\[state\=closed\]\:slide-out-to-top[data-state=closed]{--tw-exit-translate-y: -100%}.data-\[state\=closed\]\:slide-out-to-top-\[48\%\][data-state=closed]{--tw-exit-translate-y: -48%}.data-\[state\=open\]\:slide-in-from-bottom[data-state=open]{--tw-enter-translate-y: 100%}.data-\[state\=open\]\:slide-in-from-left[data-state=open]{--tw-enter-translate-x: -100%}.data-\[state\=open\]\:slide-in-from-left-1\/2[data-state=open]{--tw-enter-translate-x: -50%}.data-\[state\=open\]\:slide-in-from-right[data-state=open]{--tw-enter-translate-x: 100%}.data-\[state\=open\]\:slide-in-from-top[data-state=open]{--tw-enter-translate-y: -100%}.data-\[state\=open\]\:slide-in-from-top-\[48\%\][data-state=open]{--tw-enter-translate-y: -48%}.data-\[state\=open\]\:slide-in-from-top-full[data-state=open]{--tw-enter-translate-y: -100%}.data-\[state\=closed\]\:duration-200[data-state=closed]{animation-duration:.2s}.data-\[state\=open\]\:duration-300[data-state=open]{animation-duration:.3s}:is(.dark .dark\:text-gray-600){--tw-text-opacity: 1;color:rgb(75 85 99 / var(--tw-text-opacity))}@media (min-width: 640px){.sm\:bottom-0{bottom:0}.sm\:right-0{right:0}.sm\:top-auto{top:auto}.sm\:mt-0{margin-top:0}.sm\:max-w-sm{max-width:24rem}.sm\:flex-row{flex-direction:row}.sm\:flex-col{flex-direction:column}.sm\:justify-end{justify-content:flex-end}.sm\:space-x-2>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.5rem * var(--tw-space-x-reverse));margin-left:calc(.5rem * calc(1 - var(--tw-space-x-reverse)))}.sm\:rounded-lg{border-radius:var(--radius)}.sm\:text-left{text-align:left}.data-\[state\=open\]\:sm\:slide-in-from-bottom-full[data-state=open]{--tw-enter-translate-y: 100%}}@media (min-width: 768px){.md\:max-w-\[420px\]{max-width:420px}}.\[\&\+div\]\:text-xs+div{font-size:.75rem;line-height:1rem}.\[\&\>span\]\:line-clamp-1>span{overflow:hidden;display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:1}.\[\&\[data-state\=open\]\>svg\]\:rotate-180[data-state=open]>svg{--tw-rotate: 180deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))} diff --git a/py/iopaint/web_app/assets/index-_6nUWG_P.js b/py/iopaint/web_app/assets/index-_6nUWG_P.js new file mode 100644 index 0000000..6a08871 --- /dev/null +++ b/py/iopaint/web_app/assets/index-_6nUWG_P.js @@ -0,0 +1,165 @@ +var Lv=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)};var j=(e,t,n)=>(Lv(e,t,"read from private field"),n?n.call(e):t.get(e)),Pe=(e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)},ye=(e,t,n,r)=>(Lv(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n);var Hf=(e,t,n,r)=>({set _(o){ye(e,t,o,n)},get _(){return j(e,t,r)}}),tt=(e,t,n)=>(Lv(e,t,"access private method"),n);function $D(e,t){for(var n=0;nr[o]})}}}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 o of document.querySelectorAll('link[rel="modulepreload"]'))r(o);new MutationObserver(o=>{for(const i of o)if(i.type==="childList")for(const s of i.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&r(s)}).observe(document,{childList:!0,subtree:!0});function n(o){const i={};return o.integrity&&(i.integrity=o.integrity),o.referrerPolicy&&(i.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?i.credentials="include":o.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(o){if(o.ep)return;o.ep=!0;const i=n(o);fetch(o.href,i)}})();var Jc=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function dm(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var y$={exports:{}},fm={},w$={exports:{}},it={};/** + * @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 kd=Symbol.for("react.element"),RD=Symbol.for("react.portal"),kD=Symbol.for("react.fragment"),TD=Symbol.for("react.strict_mode"),PD=Symbol.for("react.profiler"),AD=Symbol.for("react.provider"),MD=Symbol.for("react.context"),OD=Symbol.for("react.forward_ref"),ND=Symbol.for("react.suspense"),DD=Symbol.for("react.memo"),ID=Symbol.for("react.lazy"),j_=Symbol.iterator;function LD(e){return e===null||typeof e!="object"?null:(e=j_&&e[j_]||e["@@iterator"],typeof e=="function"?e:null)}var x$={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},b$=Object.assign,S$={};function yc(e,t,n){this.props=e,this.context=t,this.refs=S$,this.updater=n||x$}yc.prototype.isReactComponent={};yc.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")};yc.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function _$(){}_$.prototype=yc.prototype;function nw(e,t,n){this.props=e,this.context=t,this.refs=S$,this.updater=n||x$}var rw=nw.prototype=new _$;rw.constructor=nw;b$(rw,yc.prototype);rw.isPureReactComponent=!0;var z_=Array.isArray,E$=Object.prototype.hasOwnProperty,ow={current:null},C$={key:!0,ref:!0,__self:!0,__source:!0};function $$(e,t,n){var r,o={},i=null,s=null;if(t!=null)for(r in t.ref!==void 0&&(s=t.ref),t.key!==void 0&&(i=""+t.key),t)E$.call(t,r)&&!C$.hasOwnProperty(r)&&(o[r]=t[r]);var l=arguments.length-2;if(l===1)o.children=n;else if(1>>1,pe=H[le];if(0>>1;le<$e;){var Ve=2*(le+1)-1,We=H[Ve],Ne=Ve+1,fe=H[Ne];if(0>o(We,W))Neo(fe,We)?(H[le]=fe,H[Ne]=W,le=Ne):(H[le]=We,H[Ve]=W,le=Ve);else if(Neo(fe,W))H[le]=fe,H[Ne]=W,le=Ne;else break e}}return X}function o(H,X){var W=H.sortIndex-X.sortIndex;return W!==0?W:H.id-X.id}if(typeof performance=="object"&&typeof performance.now=="function"){var i=performance;e.unstable_now=function(){return i.now()}}else{var s=Date,l=s.now();e.unstable_now=function(){return s.now()-l}}var u=[],f=[],m=1,p=null,g=3,y=!1,x=!1,S=!1,E=typeof setTimeout=="function"?setTimeout:null,_=typeof clearTimeout=="function"?clearTimeout:null,b=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function C(H){for(var X=n(f);X!==null;){if(X.callback===null)r(f);else if(X.startTime<=H)r(f),X.sortIndex=X.expirationTime,t(u,X);else break;X=n(f)}}function R(H){if(S=!1,C(H),!x)if(n(u)!==null)x=!0,M(P);else{var X=n(f);X!==null&&ee(R,X.startTime-H)}}function P(H,X){x=!1,S&&(S=!1,_(D),D=-1),y=!0;var W=g;try{for(C(X),p=n(u);p!==null&&(!(p.expirationTime>X)||H&&!J());){var le=p.callback;if(typeof le=="function"){p.callback=null,g=p.priorityLevel;var pe=le(p.expirationTime<=X);X=e.unstable_now(),typeof pe=="function"?p.callback=pe:p===n(u)&&r(u),C(X)}else r(u);p=n(u)}if(p!==null)var $e=!0;else{var Ve=n(f);Ve!==null&&ee(R,Ve.startTime-X),$e=!1}return $e}finally{p=null,g=W,y=!1}}var O=!1,A=null,D=-1,B=5,V=-1;function J(){return!(e.unstable_now()-VH||125le?(H.sortIndex=W,t(f,H),n(u)===null&&H===n(f)&&(S?(_(D),D=-1):S=!0,ee(R,W-le))):(H.sortIndex=pe,t(u,H),x||y||(x=!0,M(P))),H},e.unstable_shouldYield=J,e.unstable_wrapCallback=function(H){var X=g;return function(){var W=g;g=X;try{return H.apply(this,arguments)}finally{g=W}}}})(P$);T$.exports=P$;var XD=T$.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 A$=d,yr=XD;function ce(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"),W0=Object.prototype.hasOwnProperty,ZD=/^[: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]*$/,U_={},V_={};function qD(e){return W0.call(V_,e)?!0:W0.call(U_,e)?!1:ZD.test(e)?V_[e]=!0:(U_[e]=!0,!1)}function QD(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 JD(e,t,n,r){if(t===null||typeof t>"u"||QD(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 Un(e,t,n,r,o,i,s){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=o,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=i,this.removeEmptyString=s}var bn={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){bn[e]=new Un(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];bn[t]=new Un(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){bn[e]=new Un(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){bn[e]=new Un(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){bn[e]=new Un(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){bn[e]=new Un(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){bn[e]=new Un(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){bn[e]=new Un(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){bn[e]=new Un(e,5,!1,e.toLowerCase(),null,!1,!1)});var sw=/[\-:]([a-z])/g;function aw(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(sw,aw);bn[t]=new Un(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(sw,aw);bn[t]=new Un(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(sw,aw);bn[t]=new Un(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){bn[e]=new Un(e,1,!1,e.toLowerCase(),null,!1,!1)});bn.xlinkHref=new Un("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){bn[e]=new Un(e,1,!1,e.toLowerCase(),null,!0,!0)});function lw(e,t,n,r){var o=bn.hasOwnProperty(t)?bn[t]:null;(o!==null?o.type!==0:r||!(2l||o[s]!==i[l]){var u=` +`+o[s].replace(" at new "," at ");return e.displayName&&u.includes("")&&(u=u.replace("",e.displayName)),u}while(1<=s&&0<=l);break}}}finally{zv=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?vu(e):""}function e9(e){switch(e.tag){case 5:return vu(e.type);case 16:return vu("Lazy");case 13:return vu("Suspense");case 19:return vu("SuspenseList");case 0:case 2:case 15:return e=Bv(e.type,!1),e;case 11:return e=Bv(e.type.render,!1),e;case 1:return e=Bv(e.type,!0),e;default:return""}}function Y0(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 ml:return"Fragment";case pl:return"Portal";case H0:return"Profiler";case cw:return"StrictMode";case K0:return"Suspense";case G0:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case N$:return(e.displayName||"Context")+".Consumer";case O$:return(e._context.displayName||"Context")+".Provider";case uw:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case dw:return t=e.displayName||null,t!==null?t:Y0(e.type)||"Memo";case Ji:t=e._payload,e=e._init;try{return Y0(e(t))}catch{}}return null}function t9(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 Y0(t);case 8:return t===cw?"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 Rs(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function I$(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function n9(e){var t=I$(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 o=n.get,i=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return o.call(this)},set:function(s){r=""+s,i.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 Yf(e){e._valueTracker||(e._valueTracker=n9(e))}function L$(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=I$(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function ap(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 X0(e,t){var n=t.checked;return zt({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function H_(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=Rs(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 F$(e,t){t=t.checked,t!=null&&lw(e,"checked",t,!1)}function Z0(e,t){F$(e,t);var n=Rs(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")?q0(e,t.type,n):t.hasOwnProperty("defaultValue")&&q0(e,t.type,Rs(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function K_(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 q0(e,t,n){(t!=="number"||ap(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var yu=Array.isArray;function Rl(e,t,n,r){if(e=e.options,t){t={};for(var o=0;o"+t.valueOf().toString()+"",t=Xf.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function ju(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var Eu={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},r9=["Webkit","ms","Moz","O"];Object.keys(Eu).forEach(function(e){r9.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),Eu[t]=Eu[e]})});function U$(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||Eu.hasOwnProperty(e)&&Eu[e]?(""+t).trim():t+"px"}function V$(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,o=U$(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,o):e[n]=o}}var o9=zt({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 ey(e,t){if(t){if(o9[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(ce(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(ce(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(ce(61))}if(t.style!=null&&typeof t.style!="object")throw Error(ce(62))}}function ty(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 ny=null;function fw(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var ry=null,kl=null,Tl=null;function X_(e){if(e=Ad(e)){if(typeof ry!="function")throw Error(ce(280));var t=e.stateNode;t&&(t=vm(t),ry(e.stateNode,e.type,t))}}function W$(e){kl?Tl?Tl.push(e):Tl=[e]:kl=e}function H$(){if(kl){var e=kl,t=Tl;if(Tl=kl=null,X_(e),t)for(e=0;e>>=0,e===0?32:31-(m9(e)/g9|0)|0}var Zf=64,qf=4194304;function wu(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 dp(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,o=e.suspendedLanes,i=e.pingedLanes,s=n&268435455;if(s!==0){var l=s&~o;l!==0?r=wu(l):(i&=s,i!==0&&(r=wu(i)))}else s=n&~o,s!==0?r=wu(s):i!==0&&(r=wu(i));if(r===0)return 0;if(t!==0&&t!==r&&!(t&o)&&(o=r&-r,i=t&-t,o>=i||o===16&&(i&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 Td(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-wo(t),e[t]=n}function x9(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=$u),oE=" ",iE=!1;function dR(e,t){switch(e){case"keyup":return Y9.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function fR(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var gl=!1;function Z9(e,t){switch(e){case"compositionend":return fR(t);case"keypress":return t.which!==32?null:(iE=!0,oE);case"textInput":return e=t.data,e===oE&&iE?null:e;default:return null}}function q9(e,t){if(gl)return e==="compositionend"||!xw&&dR(e,t)?(e=cR(),Oh=vw=us=null,gl=!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=cE(n)}}function gR(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?gR(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function vR(){for(var e=window,t=ap();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=ap(e.document)}return t}function bw(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 sI(e){var t=vR(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&gR(n.ownerDocument.documentElement,n)){if(r!==null&&bw(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 o=n.textContent.length,i=Math.min(r.start,o);r=r.end===void 0?i:Math.min(r.end,o),!e.extend&&i>r&&(o=r,r=i,i=o),o=uE(n,i);var s=uE(n,r);o&&s&&(e.rangeCount!==1||e.anchorNode!==o.node||e.anchorOffset!==o.offset||e.focusNode!==s.node||e.focusOffset!==s.offset)&&(t=t.createRange(),t.setStart(o.node,o.offset),e.removeAllRanges(),i>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,vl=null,cy=null,ku=null,uy=!1;function dE(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;uy||vl==null||vl!==ap(r)||(r=vl,"selectionStart"in r&&bw(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}),ku&&Hu(ku,r)||(ku=r,r=pp(cy,"onSelect"),0xl||(e.current=gy[xl],gy[xl]=null,xl--)}function $t(e,t){xl++,gy[xl]=e.current,e.current=t}var ks={},Pn=Ns(ks),Jn=Ns(!1),Ra=ks;function Ql(e,t){var n=e.type.contextTypes;if(!n)return ks;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var o={},i;for(i in n)o[i]=t[i];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=o),o}function er(e){return e=e.childContextTypes,e!=null}function gp(){At(Jn),At(Pn)}function yE(e,t,n){if(Pn.current!==ks)throw Error(ce(168));$t(Pn,t),$t(Jn,n)}function $R(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var o in r)if(!(o in t))throw Error(ce(108,t9(e)||"Unknown",o));return zt({},n,r)}function vp(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||ks,Ra=Pn.current,$t(Pn,e),$t(Jn,Jn.current),!0}function wE(e,t,n){var r=e.stateNode;if(!r)throw Error(ce(169));n?(e=$R(e,t,Ra),r.__reactInternalMemoizedMergedChildContext=e,At(Jn),At(Pn),$t(Pn,e)):At(Jn),$t(Jn,n)}var pi=null,ym=!1,t0=!1;function RR(e){pi===null?pi=[e]:pi.push(e)}function yI(e){ym=!0,RR(e)}function Ds(){if(!t0&&pi!==null){t0=!0;var e=0,t=xt;try{var n=pi;for(xt=1;e>=s,o-=s,mi=1<<32-wo(t)+o|n<D?(B=A,A=null):B=A.sibling;var V=g(_,A,C[D],R);if(V===null){A===null&&(A=B);break}e&&A&&V.alternate===null&&t(_,A),b=i(V,b,D),O===null?P=V:O.sibling=V,O=V,A=B}if(D===C.length)return n(_,A),Dt&&ta(_,D),P;if(A===null){for(;DD?(B=A,A=null):B=A.sibling;var J=g(_,A,V.value,R);if(J===null){A===null&&(A=B);break}e&&A&&J.alternate===null&&t(_,A),b=i(J,b,D),O===null?P=J:O.sibling=J,O=J,A=B}if(V.done)return n(_,A),Dt&&ta(_,D),P;if(A===null){for(;!V.done;D++,V=C.next())V=p(_,V.value,R),V!==null&&(b=i(V,b,D),O===null?P=V:O.sibling=V,O=V);return Dt&&ta(_,D),P}for(A=r(_,A);!V.done;D++,V=C.next())V=y(A,_,D,V.value,R),V!==null&&(e&&V.alternate!==null&&A.delete(V.key===null?D:V.key),b=i(V,b,D),O===null?P=V:O.sibling=V,O=V);return e&&A.forEach(function(G){return t(_,G)}),Dt&&ta(_,D),P}function E(_,b,C,R){if(typeof C=="object"&&C!==null&&C.type===ml&&C.key===null&&(C=C.props.children),typeof C=="object"&&C!==null){switch(C.$$typeof){case Gf:e:{for(var P=C.key,O=b;O!==null;){if(O.key===P){if(P=C.type,P===ml){if(O.tag===7){n(_,O.sibling),b=o(O,C.props.children),b.return=_,_=b;break e}}else if(O.elementType===P||typeof P=="object"&&P!==null&&P.$$typeof===Ji&&$E(P)===O.type){n(_,O.sibling),b=o(O,C.props),b.ref=iu(_,O,C),b.return=_,_=b;break e}n(_,O);break}else t(_,O);O=O.sibling}C.type===ml?(b=$a(C.props.children,_.mode,R,C.key),b.return=_,_=b):(R=Bh(C.type,C.key,C.props,null,_.mode,R),R.ref=iu(_,b,C),R.return=_,_=R)}return s(_);case pl:e:{for(O=C.key;b!==null;){if(b.key===O)if(b.tag===4&&b.stateNode.containerInfo===C.containerInfo&&b.stateNode.implementation===C.implementation){n(_,b.sibling),b=o(b,C.children||[]),b.return=_,_=b;break e}else{n(_,b);break}else t(_,b);b=b.sibling}b=c0(C,_.mode,R),b.return=_,_=b}return s(_);case Ji:return O=C._init,E(_,b,O(C._payload),R)}if(yu(C))return x(_,b,C,R);if(eu(C))return S(_,b,C,R);oh(_,C)}return typeof C=="string"&&C!==""||typeof C=="number"?(C=""+C,b!==null&&b.tag===6?(n(_,b.sibling),b=o(b,C),b.return=_,_=b):(n(_,b),b=l0(C,_.mode,R),b.return=_,_=b),s(_)):n(_,b)}return E}var ec=DR(!0),IR=DR(!1),Md={},Ko=Ns(Md),Xu=Ns(Md),Zu=Ns(Md);function fa(e){if(e===Md)throw Error(ce(174));return e}function Pw(e,t){switch($t(Zu,t),$t(Xu,e),$t(Ko,Md),e=t.nodeType,e){case 9:case 11:t=(t=t.documentElement)?t.namespaceURI:J0(null,"");break;default:e=e===8?t.parentNode:t,t=e.namespaceURI||null,e=e.tagName,t=J0(t,e)}At(Ko),$t(Ko,t)}function tc(){At(Ko),At(Xu),At(Zu)}function LR(e){fa(Zu.current);var t=fa(Ko.current),n=J0(t,e.type);t!==n&&($t(Xu,e),$t(Ko,n))}function Aw(e){Xu.current===e&&(At(Ko),At(Xu))}var Lt=Ns(0);function _p(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 n0=[];function Mw(){for(var e=0;en?n:4,e(!0);var r=r0.transition;r0.transition={};try{e(!1),t()}finally{xt=n,r0.transition=r}}function JR(){return Yr().memoizedState}function SI(e,t,n){var r=Ss(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},ek(e))tk(t,n);else if(n=AR(e,t,n,r),n!==null){var o=jn();xo(n,e,r,o),nk(n,t,r)}}function _I(e,t,n){var r=Ss(e),o={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(ek(e))tk(t,o);else{var i=e.alternate;if(e.lanes===0&&(i===null||i.lanes===0)&&(i=t.lastRenderedReducer,i!==null))try{var s=t.lastRenderedState,l=i(s,n);if(o.hasEagerState=!0,o.eagerState=l,So(l,s)){var u=t.interleaved;u===null?(o.next=o,kw(t)):(o.next=u.next,u.next=o),t.interleaved=o;return}}catch{}finally{}n=AR(e,t,o,r),n!==null&&(o=jn(),xo(n,e,r,o),nk(n,t,r))}}function ek(e){var t=e.alternate;return e===jt||t!==null&&t===jt}function tk(e,t){Tu=Ep=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function nk(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,pw(e,n)}}var Cp={readContext:Gr,useCallback:$n,useContext:$n,useEffect:$n,useImperativeHandle:$n,useInsertionEffect:$n,useLayoutEffect:$n,useMemo:$n,useReducer:$n,useRef:$n,useState:$n,useDebugValue:$n,useDeferredValue:$n,useTransition:$n,useMutableSource:$n,useSyncExternalStore:$n,useId:$n,unstable_isNewReconciler:!1},EI={readContext:Gr,useCallback:function(e,t){return Po().memoizedState=[e,t===void 0?null:t],e},useContext:Gr,useEffect:kE,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,Lh(4194308,4,YR.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Lh(4194308,4,e,t)},useInsertionEffect:function(e,t){return Lh(4,2,e,t)},useMemo:function(e,t){var n=Po();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=Po();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=SI.bind(null,jt,e),[r.memoizedState,e]},useRef:function(e){var t=Po();return e={current:e},t.memoizedState=e},useState:RE,useDebugValue:Lw,useDeferredValue:function(e){return Po().memoizedState=e},useTransition:function(){var e=RE(!1),t=e[0];return e=bI.bind(null,e[1]),Po().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=jt,o=Po();if(Dt){if(n===void 0)throw Error(ce(407));n=n()}else{if(n=t(),dn===null)throw Error(ce(349));Ta&30||zR(r,t,n)}o.memoizedState=n;var i={value:n,getSnapshot:t};return o.queue=i,kE(UR.bind(null,r,i,e),[e]),r.flags|=2048,Ju(9,BR.bind(null,r,i,n,t),void 0,null),n},useId:function(){var e=Po(),t=dn.identifierPrefix;if(Dt){var n=gi,r=mi;n=(r&~(1<<32-wo(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=qu++,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[Io]=t,e[Yu]=r,dk(e,t,!1,!1),t.stateNode=e;e:{switch(s=ty(n,r),n){case"dialog":Tt("cancel",e),Tt("close",e),o=r;break;case"iframe":case"object":case"embed":Tt("load",e),o=r;break;case"video":case"audio":for(o=0;orc&&(t.flags|=128,r=!0,su(i,!1),t.lanes=4194304)}else{if(!r)if(e=_p(s),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),su(i,!0),i.tail===null&&i.tailMode==="hidden"&&!s.alternate&&!Dt)return Rn(t),null}else 2*Xt()-i.renderingStartTime>rc&&n!==1073741824&&(t.flags|=128,r=!0,su(i,!1),t.lanes=4194304);i.isBackwards?(s.sibling=t.child,t.child=s):(n=i.last,n!==null?n.sibling=s:t.child=s,i.last=s)}return i.tail!==null?(t=i.tail,i.rendering=t,i.tail=t.sibling,i.renderingStartTime=Xt(),t.sibling=null,n=Lt.current,$t(Lt,r?n&1|2:n&1),t):(Rn(t),null);case 22:case 23:return Vw(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?fr&1073741824&&(Rn(t),t.subtreeFlags&6&&(t.flags|=8192)):Rn(t),null;case 24:return null;case 25:return null}throw Error(ce(156,t.tag))}function MI(e,t){switch(_w(t),t.tag){case 1:return er(t.type)&&gp(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return tc(),At(Jn),At(Pn),Mw(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return Aw(t),null;case 13:if(At(Lt),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(ce(340));Jl()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return At(Lt),null;case 4:return tc(),null;case 10:return Rw(t.type._context),null;case 22:case 23:return Vw(),null;case 24:return null;default:return null}}var sh=!1,Tn=!1,OI=typeof WeakSet=="function"?WeakSet:Set,_e=null;function El(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){Wt(e,t,r)}else n.current=null}function ky(e,t,n){try{n()}catch(r){Wt(e,t,r)}}var LE=!1;function NI(e,t){if(dy=fp,e=vR(),bw(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 o=r.anchorOffset,i=r.focusNode;r=r.focusOffset;try{n.nodeType,i.nodeType}catch{n=null;break e}var s=0,l=-1,u=-1,f=0,m=0,p=e,g=null;t:for(;;){for(var y;p!==n||o!==0&&p.nodeType!==3||(l=s+o),p!==i||r!==0&&p.nodeType!==3||(u=s+r),p.nodeType===3&&(s+=p.nodeValue.length),(y=p.firstChild)!==null;)g=p,p=y;for(;;){if(p===e)break t;if(g===n&&++f===o&&(l=s),g===i&&++m===r&&(u=s),(y=p.nextSibling)!==null)break;p=g,g=p.parentNode}p=y}n=l===-1||u===-1?null:{start:l,end:u}}else n=null}n=n||{start:0,end:0}}else n=null;for(fy={focusedElem:e,selectionRange:n},fp=!1,_e=t;_e!==null;)if(t=_e,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,_e=e;else for(;_e!==null;){t=_e;try{var x=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(x!==null){var S=x.memoizedProps,E=x.memoizedState,_=t.stateNode,b=_.getSnapshotBeforeUpdate(t.elementType===t.type?S:io(t.type,S),E);_.__reactInternalSnapshotBeforeUpdate=b}break;case 3:var C=t.stateNode.containerInfo;C.nodeType===1?C.textContent="":C.nodeType===9&&C.documentElement&&C.removeChild(C.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(ce(163))}}catch(R){Wt(t,t.return,R)}if(e=t.sibling,e!==null){e.return=t.return,_e=e;break}_e=t.return}return x=LE,LE=!1,x}function Pu(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var o=r=r.next;do{if((o.tag&e)===e){var i=o.destroy;o.destroy=void 0,i!==void 0&&ky(t,n,i)}o=o.next}while(o!==r)}}function bm(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 Ty(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 pk(e){var t=e.alternate;t!==null&&(e.alternate=null,pk(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Io],delete t[Yu],delete t[my],delete t[gI],delete t[vI])),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 mk(e){return e.tag===5||e.tag===3||e.tag===4}function FE(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||mk(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 Py(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=mp));else if(r!==4&&(e=e.child,e!==null))for(Py(e,t,n),e=e.sibling;e!==null;)Py(e,t,n),e=e.sibling}function Ay(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(Ay(e,t,n),e=e.sibling;e!==null;)Ay(e,t,n),e=e.sibling}var mn=null,lo=!1;function Ki(e,t,n){for(n=n.child;n!==null;)gk(e,t,n),n=n.sibling}function gk(e,t,n){if(Ho&&typeof Ho.onCommitFiberUnmount=="function")try{Ho.onCommitFiberUnmount(hm,n)}catch{}switch(n.tag){case 5:Tn||El(n,t);case 6:var r=mn,o=lo;mn=null,Ki(e,t,n),mn=r,lo=o,mn!==null&&(lo?(e=mn,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):mn.removeChild(n.stateNode));break;case 18:mn!==null&&(lo?(e=mn,n=n.stateNode,e.nodeType===8?e0(e.parentNode,n):e.nodeType===1&&e0(e,n),Vu(e)):e0(mn,n.stateNode));break;case 4:r=mn,o=lo,mn=n.stateNode.containerInfo,lo=!0,Ki(e,t,n),mn=r,lo=o;break;case 0:case 11:case 14:case 15:if(!Tn&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){o=r=r.next;do{var i=o,s=i.destroy;i=i.tag,s!==void 0&&(i&2||i&4)&&ky(n,t,s),o=o.next}while(o!==r)}Ki(e,t,n);break;case 1:if(!Tn&&(El(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(l){Wt(n,t,l)}Ki(e,t,n);break;case 21:Ki(e,t,n);break;case 22:n.mode&1?(Tn=(r=Tn)||n.memoizedState!==null,Ki(e,t,n),Tn=r):Ki(e,t,n);break;default:Ki(e,t,n)}}function jE(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new OI),t.forEach(function(r){var o=VI.bind(null,e,r);n.has(r)||(n.add(r),r.then(o,o))})}}function ro(e,t){var n=t.deletions;if(n!==null)for(var r=0;ro&&(o=s),r&=~i}if(r=o,r=Xt()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*II(r/1960))-r,10e?16:e,ds===null)var r=!1;else{if(e=ds,ds=null,kp=0,dt&6)throw Error(ce(331));var o=dt;for(dt|=4,_e=e.current;_e!==null;){var i=_e,s=i.child;if(_e.flags&16){var l=i.deletions;if(l!==null){for(var u=0;uXt()-Bw?Ca(e,0):zw|=n),tr(e,t)}function Ek(e,t){t===0&&(e.mode&1?(t=qf,qf<<=1,!(qf&130023424)&&(qf=4194304)):t=1);var n=jn();e=_i(e,t),e!==null&&(Td(e,t,n),tr(e,n))}function UI(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),Ek(e,n)}function VI(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,o=e.memoizedState;o!==null&&(n=o.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(ce(314))}r!==null&&r.delete(t),Ek(e,n)}var Ck;Ck=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||Jn.current)Qn=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return Qn=!1,PI(e,t,n);Qn=!!(e.flags&131072)}else Qn=!1,Dt&&t.flags&1048576&&kR(t,wp,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;Fh(e,t),e=t.pendingProps;var o=Ql(t,Pn.current);Al(t,n),o=Nw(null,t,r,e,o,n);var i=Dw();return t.flags|=1,typeof o=="object"&&o!==null&&typeof o.render=="function"&&o.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,er(r)?(i=!0,vp(t)):i=!1,t.memoizedState=o.state!==null&&o.state!==void 0?o.state:null,Tw(t),o.updater=wm,t.stateNode=o,o._reactInternals=t,by(t,r,e,n),t=Ey(null,t,r,!0,i,n)):(t.tag=0,Dt&&i&&Sw(t),In(null,t,o,n),t=t.child),t;case 16:r=t.elementType;e:{switch(Fh(e,t),e=t.pendingProps,o=r._init,r=o(r._payload),t.type=r,o=t.tag=HI(r),e=io(r,e),o){case 0:t=_y(null,t,r,e,n);break e;case 1:t=NE(null,t,r,e,n);break e;case 11:t=ME(null,t,r,e,n);break e;case 14:t=OE(null,t,r,io(r.type,e),n);break e}throw Error(ce(306,r,""))}return t;case 0:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),_y(e,t,r,o,n);case 1:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),NE(e,t,r,o,n);case 3:e:{if(lk(t),e===null)throw Error(ce(387));r=t.pendingProps,i=t.memoizedState,o=i.element,MR(e,t),Sp(t,r,null,n);var s=t.memoizedState;if(r=s.element,i.isDehydrated)if(i={element:r,isDehydrated:!1,cache:s.cache,pendingSuspenseBoundaries:s.pendingSuspenseBoundaries,transitions:s.transitions},t.updateQueue.baseState=i,t.memoizedState=i,t.flags&256){o=nc(Error(ce(423)),t),t=DE(e,t,r,n,o);break e}else if(r!==o){o=nc(Error(ce(424)),t),t=DE(e,t,r,n,o);break e}else for(mr=ws(t.stateNode.containerInfo.firstChild),gr=t,Dt=!0,ho=null,n=IR(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(Jl(),r===o){t=Ei(e,t,n);break e}In(e,t,r,n)}t=t.child}return t;case 5:return LR(t),e===null&&yy(t),r=t.type,o=t.pendingProps,i=e!==null?e.memoizedProps:null,s=o.children,hy(r,o)?s=null:i!==null&&hy(r,i)&&(t.flags|=32),ak(e,t),In(e,t,s,n),t.child;case 6:return e===null&&yy(t),null;case 13:return ck(e,t,n);case 4:return Pw(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=ec(t,null,r,n):In(e,t,r,n),t.child;case 11:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),ME(e,t,r,o,n);case 7:return In(e,t,t.pendingProps,n),t.child;case 8:return In(e,t,t.pendingProps.children,n),t.child;case 12:return In(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,o=t.pendingProps,i=t.memoizedProps,s=o.value,$t(xp,r._currentValue),r._currentValue=s,i!==null)if(So(i.value,s)){if(i.children===o.children&&!Jn.current){t=Ei(e,t,n);break e}}else for(i=t.child,i!==null&&(i.return=t);i!==null;){var l=i.dependencies;if(l!==null){s=i.child;for(var u=l.firstContext;u!==null;){if(u.context===r){if(i.tag===1){u=wi(-1,n&-n),u.tag=2;var f=i.updateQueue;if(f!==null){f=f.shared;var m=f.pending;m===null?u.next=u:(u.next=m.next,m.next=u),f.pending=u}}i.lanes|=n,u=i.alternate,u!==null&&(u.lanes|=n),wy(i.return,n,t),l.lanes|=n;break}u=u.next}}else if(i.tag===10)s=i.type===t.type?null:i.child;else if(i.tag===18){if(s=i.return,s===null)throw Error(ce(341));s.lanes|=n,l=s.alternate,l!==null&&(l.lanes|=n),wy(s,n,t),s=i.sibling}else s=i.child;if(s!==null)s.return=i;else for(s=i;s!==null;){if(s===t){s=null;break}if(i=s.sibling,i!==null){i.return=s.return,s=i;break}s=s.return}i=s}In(e,t,o.children,n),t=t.child}return t;case 9:return o=t.type,r=t.pendingProps.children,Al(t,n),o=Gr(o),r=r(o),t.flags|=1,In(e,t,r,n),t.child;case 14:return r=t.type,o=io(r,t.pendingProps),o=io(r.type,o),OE(e,t,r,o,n);case 15:return ik(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),Fh(e,t),t.tag=1,er(r)?(e=!0,vp(t)):e=!1,Al(t,n),NR(t,r,o),by(t,r,o,n),Ey(null,t,r,!0,e,n);case 19:return uk(e,t,n);case 22:return sk(e,t,n)}throw Error(ce(156,t.tag))};function $k(e,t){return Q$(e,t)}function WI(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 Ur(e,t,n,r){return new WI(e,t,n,r)}function Hw(e){return e=e.prototype,!(!e||!e.isReactComponent)}function HI(e){if(typeof e=="function")return Hw(e)?1:0;if(e!=null){if(e=e.$$typeof,e===uw)return 11;if(e===dw)return 14}return 2}function _s(e,t){var n=e.alternate;return n===null?(n=Ur(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 Bh(e,t,n,r,o,i){var s=2;if(r=e,typeof e=="function")Hw(e)&&(s=1);else if(typeof e=="string")s=5;else e:switch(e){case ml:return $a(n.children,o,i,t);case cw:s=8,o|=8;break;case H0:return e=Ur(12,n,t,o|2),e.elementType=H0,e.lanes=i,e;case K0:return e=Ur(13,n,t,o),e.elementType=K0,e.lanes=i,e;case G0:return e=Ur(19,n,t,o),e.elementType=G0,e.lanes=i,e;case D$:return _m(n,o,i,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case O$:s=10;break e;case N$:s=9;break e;case uw:s=11;break e;case dw:s=14;break e;case Ji:s=16,r=null;break e}throw Error(ce(130,e==null?e:typeof e,""))}return t=Ur(s,n,t,o),t.elementType=e,t.type=r,t.lanes=i,t}function $a(e,t,n,r){return e=Ur(7,e,r,t),e.lanes=n,e}function _m(e,t,n,r){return e=Ur(22,e,r,t),e.elementType=D$,e.lanes=n,e.stateNode={isHidden:!1},e}function l0(e,t,n){return e=Ur(6,e,null,t),e.lanes=n,e}function c0(e,t,n){return t=Ur(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function KI(e,t,n,r,o){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=Vv(0),this.expirationTimes=Vv(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Vv(0),this.identifierPrefix=r,this.onRecoverableError=o,this.mutableSourceEagerHydrationData=null}function Kw(e,t,n,r,o,i,s,l,u){return e=new KI(e,t,n,l,u),t===1?(t=1,i===!0&&(t|=8)):t=0,i=Ur(3,null,null,t),e.current=i,i.stateNode=e,i.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},Tw(i),e}function GI(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(Pk)}catch(e){console.error(e)}}Pk(),k$.exports=br;var Is=k$.exports;const QI=dm(Is);var GE=Is;V0.createRoot=GE.createRoot,V0.hydrateRoot=GE.hydrateRoot;var Od=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},oc=typeof window>"u"||"Deno"in window;function Lr(){}function JI(e,t){return typeof e=="function"?e(t):e}function Iy(e){return typeof e=="number"&&e>=0&&e!==1/0}function Ak(e,t){return Math.max(e+(t||0)-Date.now(),0)}function YE(e,t){const{type:n="all",exact:r,fetchStatus:o,predicate:i,queryKey:s,stale:l}=e;if(s){if(r){if(t.queryHash!==Zw(s,t.options))return!1}else if(!nd(t.queryKey,s))return!1}if(n!=="all"){const u=t.isActive();if(n==="active"&&!u||n==="inactive"&&u)return!1}return!(typeof l=="boolean"&&t.isStale()!==l||typeof o<"u"&&o!==t.state.fetchStatus||i&&!i(t))}function XE(e,t){const{exact:n,status:r,predicate:o,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(td(t.options.mutationKey)!==td(i))return!1}else if(!nd(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||o&&!o(t))}function Zw(e,t){return((t==null?void 0:t.queryKeyHashFn)||td)(e)}function td(e){return JSON.stringify(e,(t,n)=>Fy(n)?Object.keys(n).sort().reduce((r,o)=>(r[o]=n[o],r),{}):n)}function nd(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?!Object.keys(t).some(n=>!nd(e[n],t[n])):!1}function Mk(e,t){if(e===t)return e;const n=ZE(e)&&ZE(t);if(n||Fy(e)&&Fy(t)){const r=n?e.length:Object.keys(e).length,o=n?t:Object.keys(t),i=o.length,s=n?[]:{};let l=0;for(let u=0;u"u")return!0;const n=t.prototype;return!(!qE(n)||!n.hasOwnProperty("isPrototypeOf"))}function qE(e){return Object.prototype.toString.call(e)==="[object Object]"}function Ok(e){return new Promise(t=>{setTimeout(t,e)})}function QE(e){Ok(0).then(e)}function jy(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?Mk(e,t):t}function eL(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function tL(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var ga,rs,Il,c$,nL=(c$=class extends Od{constructor(){super();Pe(this,ga,void 0);Pe(this,rs,void 0);Pe(this,Il,void 0);ye(this,Il,t=>{if(!oc&&window.addEventListener){const n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){j(this,rs)||this.setEventListener(j(this,Il))}onUnsubscribe(){var t;this.hasListeners()||((t=j(this,rs))==null||t.call(this),ye(this,rs,void 0))}setEventListener(t){var n;ye(this,Il,t),(n=j(this,rs))==null||n.call(this),ye(this,rs,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){j(this,ga)!==t&&(ye(this,ga,t),this.onFocus())}onFocus(){this.listeners.forEach(t=>{t()})}isFocused(){var t;return typeof j(this,ga)=="boolean"?j(this,ga):((t=globalThis.document)==null?void 0:t.visibilityState)!=="hidden"}},ga=new WeakMap,rs=new WeakMap,Il=new WeakMap,c$),Ap=new nL,Ll,os,Fl,u$,rL=(u$=class extends Od{constructor(){super();Pe(this,Ll,!0);Pe(this,os,void 0);Pe(this,Fl,void 0);ye(this,Fl,t=>{if(!oc&&window.addEventListener){const n=()=>t(!0),r=()=>t(!1);return window.addEventListener("online",n,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",r)}}})}onSubscribe(){j(this,os)||this.setEventListener(j(this,Fl))}onUnsubscribe(){var t;this.hasListeners()||((t=j(this,os))==null||t.call(this),ye(this,os,void 0))}setEventListener(t){var n;ye(this,Fl,t),(n=j(this,os))==null||n.call(this),ye(this,os,t(this.setOnline.bind(this)))}setOnline(t){j(this,Ll)!==t&&(ye(this,Ll,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return j(this,Ll)}},Ll=new WeakMap,os=new WeakMap,Fl=new WeakMap,u$),Mp=new rL;function oL(e){return Math.min(1e3*2**e,3e4)}function km(e){return(e??"online")==="online"?Mp.isOnline():!0}var Nk=class{constructor(e){this.revert=e==null?void 0:e.revert,this.silent=e==null?void 0:e.silent}};function u0(e){return e instanceof Nk}function Dk(e){let t=!1,n=0,r=!1,o,i,s;const l=new Promise((E,_)=>{i=E,s=_}),u=E=>{var _;r||(y(new Nk(E)),(_=e.abort)==null||_.call(e))},f=()=>{t=!0},m=()=>{t=!1},p=()=>!Ap.isFocused()||e.networkMode!=="always"&&!Mp.isOnline(),g=E=>{var _;r||(r=!0,(_=e.onSuccess)==null||_.call(e,E),o==null||o(),i(E))},y=E=>{var _;r||(r=!0,(_=e.onError)==null||_.call(e,E),o==null||o(),s(E))},x=()=>new Promise(E=>{var _;o=b=>{const C=r||!p();return C&&E(b),C},(_=e.onPause)==null||_.call(e)}).then(()=>{var E;o=void 0,r||(E=e.onContinue)==null||E.call(e)}),S=()=>{if(r)return;let E;try{E=e.fn()}catch(_){E=Promise.reject(_)}Promise.resolve(E).then(g).catch(_=>{var O;if(r)return;const b=e.retry??(oc?0:3),C=e.retryDelay??oL,R=typeof C=="function"?C(n,_):C,P=b===!0||typeof b=="number"&&n{if(p())return x()}).then(()=>{t?y(_):S()})})};return km(e.networkMode)?S():x().then(S),{promise:l,cancel:u,continue:()=>(o==null?void 0:o())?l:Promise.resolve(),cancelRetry:f,continueRetry:m}}function iL(){let e=[],t=0,n=m=>{m()},r=m=>{m()};const o=m=>{let p;t++;try{p=m()}finally{t--,t||l()}return p},i=m=>{t?e.push(m):QE(()=>{n(m)})},s=m=>(...p)=>{i(()=>{m(...p)})},l=()=>{const m=e;e=[],m.length&&QE(()=>{r(()=>{m.forEach(p=>{n(p)})})})};return{batch:o,batchCalls:s,schedule:i,setNotifyFunction:m=>{n=m},setBatchNotifyFunction:m=>{r=m}}}var vn=iL(),va,d$,Ik=(d$=class{constructor(){Pe(this,va,void 0)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Iy(this.gcTime)&&ye(this,va,setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(oc?1/0:5*60*1e3))}clearGcTimeout(){j(this,va)&&(clearTimeout(j(this,va)),ye(this,va,void 0))}},va=new WeakMap,d$),jl,zl,Nr,is,Dr,cn,vd,ya,Bl,Uh,ao,di,f$,sL=(f$=class extends Ik{constructor(t){super();Pe(this,Bl);Pe(this,ao);Pe(this,jl,void 0);Pe(this,zl,void 0);Pe(this,Nr,void 0);Pe(this,is,void 0);Pe(this,Dr,void 0);Pe(this,cn,void 0);Pe(this,vd,void 0);Pe(this,ya,void 0);ye(this,ya,!1),ye(this,vd,t.defaultOptions),tt(this,Bl,Uh).call(this,t.options),ye(this,cn,[]),ye(this,Nr,t.cache),this.queryKey=t.queryKey,this.queryHash=t.queryHash,ye(this,jl,t.state||aL(this.options)),this.state=j(this,jl),this.scheduleGc()}get meta(){return this.options.meta}optionalRemove(){!j(this,cn).length&&this.state.fetchStatus==="idle"&&j(this,Nr).remove(this)}setData(t,n){const r=jy(this.state.data,t,this.options);return tt(this,ao,di).call(this,{data:r,type:"success",dataUpdatedAt:n==null?void 0:n.updatedAt,manual:n==null?void 0:n.manual}),r}setState(t,n){tt(this,ao,di).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){var r;const n=j(this,is);return(r=j(this,Dr))==null||r.cancel(t),n?n.then(Lr).catch(Lr):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(j(this,jl))}isActive(){return j(this,cn).some(t=>t.options.enabled!==!1)}isDisabled(){return this.getObserversCount()>0&&!this.isActive()}isStale(){return this.state.isInvalidated||!this.state.dataUpdatedAt||j(this,cn).some(t=>t.getCurrentResult().isStale)}isStaleByTime(t=0){return this.state.isInvalidated||!this.state.dataUpdatedAt||!Ak(this.state.dataUpdatedAt,t)}onFocus(){var n;const t=j(this,cn).find(r=>r.shouldFetchOnWindowFocus());t==null||t.refetch({cancelRefetch:!1}),(n=j(this,Dr))==null||n.continue()}onOnline(){var n;const t=j(this,cn).find(r=>r.shouldFetchOnReconnect());t==null||t.refetch({cancelRefetch:!1}),(n=j(this,Dr))==null||n.continue()}addObserver(t){j(this,cn).includes(t)||(j(this,cn).push(t),this.clearGcTimeout(),j(this,Nr).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){j(this,cn).includes(t)&&(ye(this,cn,j(this,cn).filter(n=>n!==t)),j(this,cn).length||(j(this,Dr)&&(j(this,ya)?j(this,Dr).cancel({revert:!0}):j(this,Dr).cancelRetry()),this.scheduleGc()),j(this,Nr).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return j(this,cn).length}invalidate(){this.state.isInvalidated||tt(this,ao,di).call(this,{type:"invalidate"})}fetch(t,n){var f,m,p,g;if(this.state.fetchStatus!=="idle"){if(this.state.dataUpdatedAt&&(n!=null&&n.cancelRefetch))this.cancel({silent:!0});else if(j(this,is))return(f=j(this,Dr))==null||f.continueRetry(),j(this,is)}if(t&&tt(this,Bl,Uh).call(this,t),!this.options.queryFn){const y=j(this,cn).find(x=>x.options.queryFn);y&&tt(this,Bl,Uh).call(this,y.options)}const r=new AbortController,o={queryKey:this.queryKey,meta:this.meta},i=y=>{Object.defineProperty(y,"signal",{enumerable:!0,get:()=>(ye(this,ya,!0),r.signal)})};i(o);const s=()=>this.options.queryFn?(ye(this,ya,!1),this.options.persister?this.options.persister(this.options.queryFn,o,this):this.options.queryFn(o)):Promise.reject(new Error(`Missing queryFn: '${this.options.queryHash}'`)),l={fetchOptions:n,options:this.options,queryKey:this.queryKey,state:this.state,fetchFn:s};i(l),(m=this.options.behavior)==null||m.onFetch(l,this),ye(this,zl,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((p=l.fetchOptions)==null?void 0:p.meta))&&tt(this,ao,di).call(this,{type:"fetch",meta:(g=l.fetchOptions)==null?void 0:g.meta});const u=y=>{var x,S,E,_;u0(y)&&y.silent||tt(this,ao,di).call(this,{type:"error",error:y}),u0(y)||((S=(x=j(this,Nr).config).onError)==null||S.call(x,y,this),(_=(E=j(this,Nr).config).onSettled)==null||_.call(E,this.state.data,y,this)),this.isFetchingOptimistic||this.scheduleGc(),this.isFetchingOptimistic=!1};return ye(this,Dr,Dk({fn:l.fetchFn,abort:r.abort.bind(r),onSuccess:y=>{var x,S,E,_;if(typeof y>"u"){u(new Error(`${this.queryHash} data is undefined`));return}this.setData(y),(S=(x=j(this,Nr).config).onSuccess)==null||S.call(x,y,this),(_=(E=j(this,Nr).config).onSettled)==null||_.call(E,y,this.state.error,this),this.isFetchingOptimistic||this.scheduleGc(),this.isFetchingOptimistic=!1},onError:u,onFail:(y,x)=>{tt(this,ao,di).call(this,{type:"failed",failureCount:y,error:x})},onPause:()=>{tt(this,ao,di).call(this,{type:"pause"})},onContinue:()=>{tt(this,ao,di).call(this,{type:"continue"})},retry:l.options.retry,retryDelay:l.options.retryDelay,networkMode:l.options.networkMode})),ye(this,is,j(this,Dr).promise),j(this,is)}},jl=new WeakMap,zl=new WeakMap,Nr=new WeakMap,is=new WeakMap,Dr=new WeakMap,cn=new WeakMap,vd=new WeakMap,ya=new WeakMap,Bl=new WeakSet,Uh=function(t){this.options={...j(this,vd),...t},this.updateGcTime(this.options.gcTime)},ao=new WeakSet,di=function(t){const n=r=>{switch(t.type){case"failed":return{...r,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...r,fetchStatus:"paused"};case"continue":return{...r,fetchStatus:"fetching"};case"fetch":return{...r,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:t.meta??null,fetchStatus:km(this.options.networkMode)?"fetching":"paused",...!r.dataUpdatedAt&&{error:null,status:"pending"}};case"success":return{...r,data:t.data,dataUpdateCount:r.dataUpdateCount+1,dataUpdatedAt:t.dataUpdatedAt??Date.now(),error:null,isInvalidated:!1,status:"success",...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};case"error":const o=t.error;return u0(o)&&o.revert&&j(this,zl)?{...j(this,zl),fetchStatus:"idle"}:{...r,error:o,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:o,fetchStatus:"idle",status:"error"};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...t.state}}};this.state=n(this.state),vn.batch(()=>{j(this,cn).forEach(r=>{r.onQueryUpdate()}),j(this,Nr).notify({query:this,type:"updated",action:t})})},f$);function aL(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=typeof t<"u",r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var Mo,h$,lL=(h$=class extends Od{constructor(t={}){super();Pe(this,Mo,void 0);this.config=t,ye(this,Mo,new Map)}build(t,n,r){const o=n.queryKey,i=n.queryHash??Zw(o,n);let s=this.get(i);return s||(s=new sL({cache:this,queryKey:o,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(o)}),this.add(s)),s}add(t){j(this,Mo).has(t.queryHash)||(j(this,Mo).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){const n=j(this,Mo).get(t.queryHash);n&&(t.destroy(),n===t&&j(this,Mo).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){vn.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return j(this,Mo).get(t)}getAll(){return[...j(this,Mo).values()]}find(t){const n={exact:!0,...t};return this.getAll().find(r=>YE(n,r))}findAll(t={}){const n=this.getAll();return Object.keys(t).length>0?n.filter(r=>YE(t,r)):n}notify(t){vn.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){vn.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){vn.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},Mo=new WeakMap,h$),Oo,yd,dr,Ul,No,qi,p$,cL=(p$=class extends Ik{constructor(t){super();Pe(this,No);Pe(this,Oo,void 0);Pe(this,yd,void 0);Pe(this,dr,void 0);Pe(this,Ul,void 0);this.mutationId=t.mutationId,ye(this,yd,t.defaultOptions),ye(this,dr,t.mutationCache),ye(this,Oo,[]),this.state=t.state||uL(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options={...j(this,yd),...t},this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){j(this,Oo).includes(t)||(j(this,Oo).push(t),this.clearGcTimeout(),j(this,dr).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){ye(this,Oo,j(this,Oo).filter(n=>n!==t)),this.scheduleGc(),j(this,dr).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){j(this,Oo).length||(this.state.status==="pending"?this.scheduleGc():j(this,dr).remove(this))}continue(){var t;return((t=j(this,Ul))==null?void 0:t.continue())??this.execute(this.state.variables)}async execute(t){var o,i,s,l,u,f,m,p,g,y,x,S,E,_,b,C,R,P,O,A;const n=()=>(ye(this,Ul,Dk({fn:()=>this.options.mutationFn?this.options.mutationFn(t):Promise.reject(new Error("No mutationFn found")),onFail:(D,B)=>{tt(this,No,qi).call(this,{type:"failed",failureCount:D,error:B})},onPause:()=>{tt(this,No,qi).call(this,{type:"pause"})},onContinue:()=>{tt(this,No,qi).call(this,{type:"continue"})},retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode})),j(this,Ul).promise),r=this.state.status==="pending";try{if(!r){tt(this,No,qi).call(this,{type:"pending",variables:t}),await((i=(o=j(this,dr).config).onMutate)==null?void 0:i.call(o,t,this));const B=await((l=(s=this.options).onMutate)==null?void 0:l.call(s,t));B!==this.state.context&&tt(this,No,qi).call(this,{type:"pending",context:B,variables:t})}const D=await n();return await((f=(u=j(this,dr).config).onSuccess)==null?void 0:f.call(u,D,t,this.state.context,this)),await((p=(m=this.options).onSuccess)==null?void 0:p.call(m,D,t,this.state.context)),await((y=(g=j(this,dr).config).onSettled)==null?void 0:y.call(g,D,null,this.state.variables,this.state.context,this)),await((S=(x=this.options).onSettled)==null?void 0:S.call(x,D,null,t,this.state.context)),tt(this,No,qi).call(this,{type:"success",data:D}),D}catch(D){try{throw await((_=(E=j(this,dr).config).onError)==null?void 0:_.call(E,D,t,this.state.context,this)),await((C=(b=this.options).onError)==null?void 0:C.call(b,D,t,this.state.context)),await((P=(R=j(this,dr).config).onSettled)==null?void 0:P.call(R,void 0,D,this.state.variables,this.state.context,this)),await((A=(O=this.options).onSettled)==null?void 0:A.call(O,void 0,D,t,this.state.context)),D}finally{tt(this,No,qi).call(this,{type:"error",error:D})}}}},Oo=new WeakMap,yd=new WeakMap,dr=new WeakMap,Ul=new WeakMap,No=new WeakSet,qi=function(t){const n=r=>{switch(t.type){case"failed":return{...r,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};case"pending":return{...r,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:!km(this.options.networkMode),status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...r,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:t.error,failureCount:r.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}};this.state=n(this.state),vn.batch(()=>{j(this,Oo).forEach(r=>{r.onMutationUpdate(t)}),j(this,dr).notify({mutation:this,type:"updated",action:t})})},p$);function uL(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Ir,wd,wa,m$,dL=(m$=class extends Od{constructor(t={}){super();Pe(this,Ir,void 0);Pe(this,wd,void 0);Pe(this,wa,void 0);this.config=t,ye(this,Ir,[]),ye(this,wd,0)}build(t,n,r){const o=new cL({mutationCache:this,mutationId:++Hf(this,wd)._,options:t.defaultMutationOptions(n),state:r});return this.add(o),o}add(t){j(this,Ir).push(t),this.notify({type:"added",mutation:t})}remove(t){ye(this,Ir,j(this,Ir).filter(n=>n!==t)),this.notify({type:"removed",mutation:t})}clear(){vn.batch(()=>{j(this,Ir).forEach(t=>{this.remove(t)})})}getAll(){return j(this,Ir)}find(t){const n={exact:!0,...t};return j(this,Ir).find(r=>XE(n,r))}findAll(t={}){return j(this,Ir).filter(n=>XE(t,n))}notify(t){vn.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){return ye(this,wa,(j(this,wa)??Promise.resolve()).then(()=>{const t=j(this,Ir).filter(n=>n.state.isPaused);return vn.batch(()=>t.reduce((n,r)=>n.then(()=>r.continue().catch(Lr)),Promise.resolve()))}).then(()=>{ye(this,wa,void 0)})),j(this,wa)}},Ir=new WeakMap,wd=new WeakMap,wa=new WeakMap,m$);function fL(e){return{onFetch:(t,n)=>{const r=async()=>{var x,S,E,_,b;const o=t.options,i=(E=(S=(x=t.fetchOptions)==null?void 0:x.meta)==null?void 0:S.fetchMore)==null?void 0:E.direction,s=((_=t.state.data)==null?void 0:_.pages)||[],l=((b=t.state.data)==null?void 0:b.pageParams)||[],u={pages:[],pageParams:[]};let f=!1;const m=C=>{Object.defineProperty(C,"signal",{enumerable:!0,get:()=>(t.signal.aborted?f=!0:t.signal.addEventListener("abort",()=>{f=!0}),t.signal)})},p=t.options.queryFn||(()=>Promise.reject(new Error(`Missing queryFn: '${t.options.queryHash}'`))),g=async(C,R,P)=>{if(f)return Promise.reject();if(R==null&&C.pages.length)return Promise.resolve(C);const O={queryKey:t.queryKey,pageParam:R,direction:P?"backward":"forward",meta:t.options.meta};m(O);const A=await p(O),{maxPages:D}=t.options,B=P?tL:eL;return{pages:B(C.pages,A,D),pageParams:B(C.pageParams,R,D)}};let y;if(i&&s.length){const C=i==="backward",R=C?hL:JE,P={pages:s,pageParams:l},O=R(o,P);y=await g(P,O,C)}else{y=await g(u,l[0]??o.initialPageParam);const C=e??s.length;for(let R=1;R{var o,i;return(i=(o=t.options).persister)==null?void 0:i.call(o,r,{queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n)}:t.fetchFn=r}}}function JE(e,{pages:t,pageParams:n}){const r=t.length-1;return e.getNextPageParam(t[r],t,n[r],n)}function hL(e,{pages:t,pageParams:n}){var r;return(r=e.getPreviousPageParam)==null?void 0:r.call(e,t[0],t,n[0],n)}var nn,ss,as,Vl,Wl,ls,Hl,Kl,g$,pL=(g$=class{constructor(e={}){Pe(this,nn,void 0);Pe(this,ss,void 0);Pe(this,as,void 0);Pe(this,Vl,void 0);Pe(this,Wl,void 0);Pe(this,ls,void 0);Pe(this,Hl,void 0);Pe(this,Kl,void 0);ye(this,nn,e.queryCache||new lL),ye(this,ss,e.mutationCache||new dL),ye(this,as,e.defaultOptions||{}),ye(this,Vl,new Map),ye(this,Wl,new Map),ye(this,ls,0)}mount(){Hf(this,ls)._++,j(this,ls)===1&&(ye(this,Hl,Ap.subscribe(()=>{Ap.isFocused()&&(this.resumePausedMutations(),j(this,nn).onFocus())})),ye(this,Kl,Mp.subscribe(()=>{Mp.isOnline()&&(this.resumePausedMutations(),j(this,nn).onOnline())})))}unmount(){var e,t;Hf(this,ls)._--,j(this,ls)===0&&((e=j(this,Hl))==null||e.call(this),ye(this,Hl,void 0),(t=j(this,Kl))==null||t.call(this),ye(this,Kl,void 0))}isFetching(e){return j(this,nn).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return j(this,ss).findAll({...e,status:"pending"}).length}getQueryData(e){var t;return(t=j(this,nn).find({queryKey:e}))==null?void 0:t.state.data}ensureQueryData(e){const t=this.getQueryData(e.queryKey);return t!==void 0?Promise.resolve(t):this.fetchQuery(e)}getQueriesData(e){return this.getQueryCache().findAll(e).map(({queryKey:t,state:n})=>{const r=n.data;return[t,r]})}setQueryData(e,t,n){const r=j(this,nn).find({queryKey:e}),o=r==null?void 0:r.state.data,i=JI(t,o);if(typeof i>"u")return;const s=this.defaultQueryOptions({queryKey:e});return j(this,nn).build(this,s).setData(i,{...n,manual:!0})}setQueriesData(e,t,n){return vn.batch(()=>this.getQueryCache().findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){var t;return(t=j(this,nn).find({queryKey:e}))==null?void 0:t.state}removeQueries(e){const t=j(this,nn);vn.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=j(this,nn),r={type:"active",...e};return vn.batch(()=>(n.findAll(e).forEach(o=>{o.reset()}),this.refetchQueries(r,t)))}cancelQueries(e={},t={}){const n={revert:!0,...t},r=vn.batch(()=>j(this,nn).findAll(e).map(o=>o.cancel(n)));return Promise.all(r).then(Lr).catch(Lr)}invalidateQueries(e={},t={}){return vn.batch(()=>{if(j(this,nn).findAll(e).forEach(r=>{r.invalidate()}),e.refetchType==="none")return Promise.resolve();const n={...e,type:e.refetchType??e.type??"active"};return this.refetchQueries(n,t)})}refetchQueries(e={},t){const n={...t,cancelRefetch:(t==null?void 0:t.cancelRefetch)??!0},r=vn.batch(()=>j(this,nn).findAll(e).filter(o=>!o.isDisabled()).map(o=>{let i=o.fetch(void 0,n);return n.throwOnError||(i=i.catch(Lr)),o.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(Lr)}fetchQuery(e){const t=this.defaultQueryOptions(e);typeof t.retry>"u"&&(t.retry=!1);const n=j(this,nn).build(this,t);return n.isStaleByTime(t.staleTime)?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Lr).catch(Lr)}fetchInfiniteQuery(e){return e.behavior=fL(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Lr).catch(Lr)}resumePausedMutations(){return j(this,ss).resumePausedMutations()}getQueryCache(){return j(this,nn)}getMutationCache(){return j(this,ss)}getDefaultOptions(){return j(this,as)}setDefaultOptions(e){ye(this,as,e)}setQueryDefaults(e,t){j(this,Vl).set(td(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...j(this,Vl).values()];let n={};return t.forEach(r=>{nd(e,r.queryKey)&&(n={...n,...r.defaultOptions})}),n}setMutationDefaults(e,t){j(this,Wl).set(td(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...j(this,Wl).values()];let n={};return t.forEach(r=>{nd(e,r.mutationKey)&&(n={...n,...r.defaultOptions})}),n}defaultQueryOptions(e){if(e!=null&&e._defaulted)return e;const t={...j(this,as).queries,...(e==null?void 0:e.queryKey)&&this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Zw(t.queryKey,t)),typeof t.refetchOnReconnect>"u"&&(t.refetchOnReconnect=t.networkMode!=="always"),typeof t.throwOnError>"u"&&(t.throwOnError=!!t.suspense),typeof t.networkMode>"u"&&t.persister&&(t.networkMode="offlineFirst"),t}defaultMutationOptions(e){return e!=null&&e._defaulted?e:{...j(this,as).mutations,...(e==null?void 0:e.mutationKey)&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){j(this,nn).clear(),j(this,ss).clear()}},nn=new WeakMap,ss=new WeakMap,as=new WeakMap,Vl=new WeakMap,Wl=new WeakMap,ls=new WeakMap,Hl=new WeakMap,Kl=new WeakMap,g$),Xn,Ct,Gl,kn,xa,Yl,Do,xd,Xl,Zl,ba,Sa,cs,_a,Ea,bu,bd,zy,Sd,By,_d,Uy,Ed,Vy,Cd,Wy,$d,Hy,Rd,Ky,um,Lk,v$,mL=(v$=class extends Od{constructor(t,n){super();Pe(this,Ea);Pe(this,bd);Pe(this,Sd);Pe(this,_d);Pe(this,Ed);Pe(this,Cd);Pe(this,$d);Pe(this,Rd);Pe(this,um);Pe(this,Xn,void 0);Pe(this,Ct,void 0);Pe(this,Gl,void 0);Pe(this,kn,void 0);Pe(this,xa,void 0);Pe(this,Yl,void 0);Pe(this,Do,void 0);Pe(this,xd,void 0);Pe(this,Xl,void 0);Pe(this,Zl,void 0);Pe(this,ba,void 0);Pe(this,Sa,void 0);Pe(this,cs,void 0);Pe(this,_a,void 0);ye(this,Ct,void 0),ye(this,Gl,void 0),ye(this,kn,void 0),ye(this,_a,new Set),ye(this,Xn,t),this.options=n,ye(this,Do,null),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(j(this,Ct).addObserver(this),eC(j(this,Ct),this.options)?tt(this,Ea,bu).call(this):this.updateResult(),tt(this,Ed,Vy).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Gy(j(this,Ct),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Gy(j(this,Ct),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,tt(this,Cd,Wy).call(this),tt(this,$d,Hy).call(this),j(this,Ct).removeObserver(this)}setOptions(t,n){const r=this.options,o=j(this,Ct);if(this.options=j(this,Xn).defaultQueryOptions(t),Ly(r,this.options)||j(this,Xn).getQueryCache().notify({type:"observerOptionsUpdated",query:j(this,Ct),observer:this}),typeof this.options.enabled<"u"&&typeof this.options.enabled!="boolean")throw new Error("Expected enabled to be a boolean");this.options.queryKey||(this.options.queryKey=r.queryKey),tt(this,Rd,Ky).call(this);const i=this.hasListeners();i&&tC(j(this,Ct),o,this.options,r)&&tt(this,Ea,bu).call(this),this.updateResult(n),i&&(j(this,Ct)!==o||this.options.enabled!==r.enabled||this.options.staleTime!==r.staleTime)&&tt(this,bd,zy).call(this);const s=tt(this,Sd,By).call(this);i&&(j(this,Ct)!==o||this.options.enabled!==r.enabled||s!==j(this,cs))&&tt(this,_d,Uy).call(this,s)}getOptimisticResult(t){const n=j(this,Xn).getQueryCache().build(j(this,Xn),t),r=this.createResult(n,t);return vL(this,r)&&(ye(this,kn,r),ye(this,Yl,this.options),ye(this,xa,j(this,Ct).state)),r}getCurrentResult(){return j(this,kn)}trackResult(t){const n={};return Object.keys(t).forEach(r=>{Object.defineProperty(n,r,{configurable:!1,enumerable:!0,get:()=>(j(this,_a).add(r),t[r])})}),n}getCurrentQuery(){return j(this,Ct)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){const n=j(this,Xn).defaultQueryOptions(t),r=j(this,Xn).getQueryCache().build(j(this,Xn),n);return r.isFetchingOptimistic=!0,r.fetch().then(()=>this.createResult(r,n))}fetch(t){return tt(this,Ea,bu).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),j(this,kn)))}createResult(t,n){var O;const r=j(this,Ct),o=this.options,i=j(this,kn),s=j(this,xa),l=j(this,Yl),f=t!==r?t.state:j(this,Gl),{state:m}=t;let{error:p,errorUpdatedAt:g,fetchStatus:y,status:x}=m,S=!1,E;if(n._optimisticResults){const A=this.hasListeners(),D=!A&&eC(t,n),B=A&&tC(t,r,n,o);(D||B)&&(y=km(t.options.networkMode)?"fetching":"paused",m.dataUpdatedAt||(x="pending")),n._optimisticResults==="isRestoring"&&(y="idle")}if(n.select&&typeof m.data<"u")if(i&&m.data===(s==null?void 0:s.data)&&n.select===j(this,xd))E=j(this,Xl);else try{ye(this,xd,n.select),E=n.select(m.data),E=jy(i==null?void 0:i.data,E,n),ye(this,Xl,E),ye(this,Do,null)}catch(A){ye(this,Do,A)}else E=m.data;if(typeof n.placeholderData<"u"&&typeof E>"u"&&x==="pending"){let A;if(i!=null&&i.isPlaceholderData&&n.placeholderData===(l==null?void 0:l.placeholderData))A=i.data;else if(A=typeof n.placeholderData=="function"?n.placeholderData((O=j(this,Zl))==null?void 0:O.state.data,j(this,Zl)):n.placeholderData,n.select&&typeof A<"u")try{A=n.select(A),ye(this,Do,null)}catch(D){ye(this,Do,D)}typeof A<"u"&&(x="success",E=jy(i==null?void 0:i.data,A,n),S=!0)}j(this,Do)&&(p=j(this,Do),E=j(this,Xl),g=Date.now(),x="error");const _=y==="fetching",b=x==="pending",C=x==="error",R=b&&_;return{status:x,fetchStatus:y,isPending:b,isSuccess:x==="success",isError:C,isInitialLoading:R,isLoading:R,data:E,dataUpdatedAt:m.dataUpdatedAt,error:p,errorUpdatedAt:g,failureCount:m.fetchFailureCount,failureReason:m.fetchFailureReason,errorUpdateCount:m.errorUpdateCount,isFetched:m.dataUpdateCount>0||m.errorUpdateCount>0,isFetchedAfterMount:m.dataUpdateCount>f.dataUpdateCount||m.errorUpdateCount>f.errorUpdateCount,isFetching:_,isRefetching:_&&!b,isLoadingError:C&&m.dataUpdatedAt===0,isPaused:y==="paused",isPlaceholderData:S,isRefetchError:C&&m.dataUpdatedAt!==0,isStale:qw(t,n),refetch:this.refetch}}updateResult(t){const n=j(this,kn),r=this.createResult(j(this,Ct),this.options);if(ye(this,xa,j(this,Ct).state),ye(this,Yl,this.options),j(this,xa).data!==void 0&&ye(this,Zl,j(this,Ct)),Ly(r,n))return;ye(this,kn,r);const o={},i=()=>{if(!n)return!0;const{notifyOnChangeProps:s}=this.options,l=typeof s=="function"?s():s;if(l==="all"||!l&&!j(this,_a).size)return!0;const u=new Set(l??j(this,_a));return this.options.throwOnError&&u.add("error"),Object.keys(j(this,kn)).some(f=>{const m=f;return j(this,kn)[m]!==n[m]&&u.has(m)})};(t==null?void 0:t.listeners)!==!1&&i()&&(o.listeners=!0),tt(this,um,Lk).call(this,{...o,...t})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&tt(this,Ed,Vy).call(this)}},Xn=new WeakMap,Ct=new WeakMap,Gl=new WeakMap,kn=new WeakMap,xa=new WeakMap,Yl=new WeakMap,Do=new WeakMap,xd=new WeakMap,Xl=new WeakMap,Zl=new WeakMap,ba=new WeakMap,Sa=new WeakMap,cs=new WeakMap,_a=new WeakMap,Ea=new WeakSet,bu=function(t){tt(this,Rd,Ky).call(this);let n=j(this,Ct).fetch(this.options,t);return t!=null&&t.throwOnError||(n=n.catch(Lr)),n},bd=new WeakSet,zy=function(){if(tt(this,Cd,Wy).call(this),oc||j(this,kn).isStale||!Iy(this.options.staleTime))return;const n=Ak(j(this,kn).dataUpdatedAt,this.options.staleTime)+1;ye(this,ba,setTimeout(()=>{j(this,kn).isStale||this.updateResult()},n))},Sd=new WeakSet,By=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(j(this,Ct)):this.options.refetchInterval)??!1},_d=new WeakSet,Uy=function(t){tt(this,$d,Hy).call(this),ye(this,cs,t),!(oc||this.options.enabled===!1||!Iy(j(this,cs))||j(this,cs)===0)&&ye(this,Sa,setInterval(()=>{(this.options.refetchIntervalInBackground||Ap.isFocused())&&tt(this,Ea,bu).call(this)},j(this,cs)))},Ed=new WeakSet,Vy=function(){tt(this,bd,zy).call(this),tt(this,_d,Uy).call(this,tt(this,Sd,By).call(this))},Cd=new WeakSet,Wy=function(){j(this,ba)&&(clearTimeout(j(this,ba)),ye(this,ba,void 0))},$d=new WeakSet,Hy=function(){j(this,Sa)&&(clearInterval(j(this,Sa)),ye(this,Sa,void 0))},Rd=new WeakSet,Ky=function(){const t=j(this,Xn).getQueryCache().build(j(this,Xn),this.options);if(t===j(this,Ct))return;const n=j(this,Ct);ye(this,Ct,t),ye(this,Gl,t.state),this.hasListeners()&&(n==null||n.removeObserver(this),t.addObserver(this))},um=new WeakSet,Lk=function(t){vn.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(j(this,kn))}),j(this,Xn).getQueryCache().notify({query:j(this,Ct),type:"observerResultsUpdated"})})},v$);function gL(e,t){return t.enabled!==!1&&!e.state.dataUpdatedAt&&!(e.state.status==="error"&&t.retryOnMount===!1)}function eC(e,t){return gL(e,t)||e.state.dataUpdatedAt>0&&Gy(e,t,t.refetchOnMount)}function Gy(e,t,n){if(t.enabled!==!1){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&qw(e,t)}return!1}function tC(e,t,n,r){return n.enabled!==!1&&(e!==t||r.enabled===!1)&&(!n.suspense||e.state.status!=="error")&&qw(e,n)}function qw(e,t){return e.isStaleByTime(t.staleTime)}function vL(e,t){return!Ly(e.getCurrentResult(),t)}var Fk=d.createContext(void 0),yL=e=>{const t=d.useContext(Fk);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},wL=({client:e,children:t})=>(d.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),d.createElement(Fk.Provider,{value:e},t)),jk=d.createContext(!1),xL=()=>d.useContext(jk);jk.Provider;function bL(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var SL=d.createContext(bL()),_L=()=>d.useContext(SL);function EL(e,t){return typeof e=="function"?e(...t):!!e}var CL=(e,t)=>{(e.suspense||e.throwOnError)&&(t.isReset()||(e.retryOnMount=!1))},$L=e=>{d.useEffect(()=>{e.clearReset()},[e])},RL=({result:e,errorResetBoundary:t,throwOnError:n,query:r})=>e.isError&&!t.isReset()&&!e.isFetching&&EL(n,[e.error,r]),kL=e=>{e.suspense&&typeof e.staleTime!="number"&&(e.staleTime=1e3)},TL=(e,t)=>(e==null?void 0:e.suspense)&&t.isPending,PL=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function AL(e,t,n){const r=yL(n),o=xL(),i=_L(),s=r.defaultQueryOptions(e);s._optimisticResults=o?"isRestoring":"optimistic",kL(s),CL(s,i),$L(i);const[l]=d.useState(()=>new t(r,s)),u=l.getOptimisticResult(s);if(d.useSyncExternalStore(d.useCallback(f=>{const m=o?()=>{}:l.subscribe(vn.batchCalls(f));return l.updateResult(),m},[l,o]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),d.useEffect(()=>{l.setOptions(s,{listeners:!1})},[s,l]),TL(s,u))throw l.setOptions(s,{listeners:!1}),PL(s,l,i);if(RL({result:u,errorResetBoundary:i,throwOnError:s.throwOnError,query:l.getCurrentQuery()}))throw u.error;return s.notifyOnChangeProps?u:l.trackResult(u)}function ML(e,t){return AL(e,mL,t)}var Ao=(e=>(e.RemoveBG="RemoveBG",e.AnimeSeg="AnimeSeg",e.RealESRGAN="RealESRGAN",e.GFPGAN="GFPGAN",e.RestoreFormer="RestoreFormer",e.InteractiveSeg="InteractiveSeg",e))(Ao||{}),Es=(e=>(e.NAME="name",e.CTIME="ctime",e.MTIME="mtime",e))(Es||{}),Ou=(e=>(e.DESCENDING="desc",e.ASCENDING="asc",e))(Ou||{}),Qw=(e=>(e.ddim="ddim",e.plms="plms",e))(Qw||{}),Jw=(e=>(e.INPAINT_NS="INPAINT_NS",e.INPAINT_TELEA="INPAINT_TELEA",e))(Jw||{}),Ln=(e=>(e.x="x",e.y="y",e.xy="xy",e))(Ln||{}),Ol=(e=>(e.text_guided="text-guided",e.shape_guided="shape-guided",e.object_remove="object-remove",e.outpainting="outpainting",e))(Ol||{});function zk(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;tl(i)))==null?void 0:s.classGroupId}const nC=/^\[(.+)\]$/;function NL(e){if(nC.test(e)){const t=nC.exec(e)[1],n=t==null?void 0:t.substring(0,t.indexOf(":"));if(n)return"arbitrary.."+n}}function DL(e){const{theme:t,prefix:n}=e,r={nextPart:new Map,validators:[]};return LL(Object.entries(e.classGroups),n).forEach(([i,s])=>{Yy(s,r,i,t)}),r}function Yy(e,t,n,r){e.forEach(o=>{if(typeof o=="string"){const i=o===""?t:rC(t,o);i.classGroupId=n;return}if(typeof o=="function"){if(IL(o)){Yy(o(r),t,n,r);return}t.validators.push({validator:o,classGroupId:n});return}Object.entries(o).forEach(([i,s])=>{Yy(s,rC(t,i),n,r)})})}function rC(e,t){let n=e;return t.split(ex).forEach(r=>{n.nextPart.has(r)||n.nextPart.set(r,{nextPart:new Map,validators:[]}),n=n.nextPart.get(r)}),n}function IL(e){return e.isThemeGetter}function LL(e,t){return t?e.map(([n,r])=>{const o=r.map(i=>typeof i=="string"?t+i:typeof i=="object"?Object.fromEntries(Object.entries(i).map(([s,l])=>[t+s,l])):i);return[n,o]}):e}function FL(e){if(e<1)return{get:()=>{},set:()=>{}};let t=0,n=new Map,r=new Map;function o(i,s){n.set(i,s),t++,t>e&&(t=0,r=n,n=new Map)}return{get(i){let s=n.get(i);if(s!==void 0)return s;if((s=r.get(i))!==void 0)return o(i,s),s},set(i,s){n.has(i)?n.set(i,s):o(i,s)}}}const Vk="!";function jL(e){const t=e.separator,n=t.length===1,r=t[0],o=t.length;return function(s){const l=[];let u=0,f=0,m;for(let S=0;Sf?m-f:void 0;return{modifiers:l,hasImportantModifier:g,baseClassName:y,maybePostfixModifierPosition:x}}}function zL(e){if(e.length<=1)return e;const t=[];let n=[];return e.forEach(r=>{r[0]==="["?(t.push(...n.sort(),r),n=[]):n.push(r)}),t.push(...n.sort()),t}function BL(e){return{cache:FL(e.cacheSize),splitModifiers:jL(e),...OL(e)}}const UL=/\s+/;function VL(e,t){const{splitModifiers:n,getClassGroupId:r,getConflictingClassGroupIds:o}=t,i=new Set;return e.trim().split(UL).map(s=>{const{modifiers:l,hasImportantModifier:u,baseClassName:f,maybePostfixModifierPosition:m}=n(s);let p=r(m?f.substring(0,m):f),g=!!m;if(!p){if(!m)return{isTailwindClass:!1,originalClassName:s};if(p=r(f),!p)return{isTailwindClass:!1,originalClassName:s};g=!1}const y=zL(l).join(":");return{isTailwindClass:!0,modifierId:u?y+Vk:y,classGroupId:p,originalClassName:s,hasPostfixModifier:g}}).reverse().filter(s=>{if(!s.isTailwindClass)return!0;const{modifierId:l,classGroupId:u,hasPostfixModifier:f}=s,m=l+u;return i.has(m)?!1:(i.add(m),o(u,f).forEach(p=>i.add(l+p)),!0)}).reverse().map(s=>s.originalClassName).join(" ")}function WL(){let e=0,t,n,r="";for(;ep(m),e());return n=BL(f),r=n.cache.get,o=n.cache.set,i=l,l(u)}function l(u){const f=r(u);if(f)return f;const m=VL(u,n);return o(u,m),m}return function(){return i(WL.apply(null,arguments))}}function kt(e){const t=n=>n[e]||[];return t.isThemeGetter=!0,t}const Hk=/^\[(?:([a-z-]+):)?(.+)\]$/i,KL=/^\d+\/\d+$/,GL=new Set(["px","full","screen"]),YL=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,XL=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,ZL=/^-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,qL=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/;function oo(e){return ha(e)||GL.has(e)||KL.test(e)}function Gi(e){return bc(e,"length",iF)}function ha(e){return!!e&&!Number.isNaN(Number(e))}function ch(e){return bc(e,"number",ha)}function lu(e){return!!e&&Number.isInteger(Number(e))}function QL(e){return e.endsWith("%")&&ha(e.slice(0,-1))}function Je(e){return Hk.test(e)}function Yi(e){return YL.test(e)}const JL=new Set(["length","size","percentage"]);function eF(e){return bc(e,JL,Kk)}function tF(e){return bc(e,"position",Kk)}const nF=new Set(["image","url"]);function rF(e){return bc(e,nF,aF)}function oF(e){return bc(e,"",sF)}function cu(){return!0}function bc(e,t,n){const r=Hk.exec(e);return r?r[1]?typeof t=="string"?r[1]===t:t.has(r[1]):n(r[2]):!1}function iF(e){return XL.test(e)}function Kk(){return!1}function sF(e){return ZL.test(e)}function aF(e){return qL.test(e)}function lF(){const e=kt("colors"),t=kt("spacing"),n=kt("blur"),r=kt("brightness"),o=kt("borderColor"),i=kt("borderRadius"),s=kt("borderSpacing"),l=kt("borderWidth"),u=kt("contrast"),f=kt("grayscale"),m=kt("hueRotate"),p=kt("invert"),g=kt("gap"),y=kt("gradientColorStops"),x=kt("gradientColorStopPositions"),S=kt("inset"),E=kt("margin"),_=kt("opacity"),b=kt("padding"),C=kt("saturate"),R=kt("scale"),P=kt("sepia"),O=kt("skew"),A=kt("space"),D=kt("translate"),B=()=>["auto","contain","none"],V=()=>["auto","hidden","clip","visible","scroll"],J=()=>["auto",Je,t],G=()=>[Je,t],se=()=>["",oo,Gi],U=()=>["auto",ha,Je],ne=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],M=()=>["solid","dashed","dotted","double","none"],ee=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity","plus-lighter"],H=()=>["start","end","center","between","around","evenly","stretch"],X=()=>["","0",Je],W=()=>["auto","avoid","all","avoid-page","page","left","right","column"],le=()=>[ha,ch],pe=()=>[ha,Je];return{cacheSize:500,separator:":",theme:{colors:[cu],spacing:[oo,Gi],blur:["none","",Yi,Je],brightness:le(),borderColor:[e],borderRadius:["none","","full",Yi,Je],borderSpacing:G(),borderWidth:se(),contrast:le(),grayscale:X(),hueRotate:pe(),invert:X(),gap:G(),gradientColorStops:[e],gradientColorStopPositions:[QL,Gi],inset:J(),margin:J(),opacity:le(),padding:G(),saturate:le(),scale:le(),sepia:X(),skew:pe(),space:G(),translate:G()},classGroups:{aspect:[{aspect:["auto","square","video",Je]}],container:["container"],columns:[{columns:[Yi]}],"break-after":[{"break-after":W()}],"break-before":[{"break-before":W()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],float:[{float:["right","left","none"]}],clear:[{clear:["left","right","both","none"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:[...ne(),Je]}],overflow:[{overflow:V()}],"overflow-x":[{"overflow-x":V()}],"overflow-y":[{"overflow-y":V()}],overscroll:[{overscroll:B()}],"overscroll-x":[{"overscroll-x":B()}],"overscroll-y":[{"overscroll-y":B()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[S]}],"inset-x":[{"inset-x":[S]}],"inset-y":[{"inset-y":[S]}],start:[{start:[S]}],end:[{end:[S]}],top:[{top:[S]}],right:[{right:[S]}],bottom:[{bottom:[S]}],left:[{left:[S]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",lu,Je]}],basis:[{basis:J()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",Je]}],grow:[{grow:X()}],shrink:[{shrink:X()}],order:[{order:["first","last","none",lu,Je]}],"grid-cols":[{"grid-cols":[cu]}],"col-start-end":[{col:["auto",{span:["full",lu,Je]},Je]}],"col-start":[{"col-start":U()}],"col-end":[{"col-end":U()}],"grid-rows":[{"grid-rows":[cu]}],"row-start-end":[{row:["auto",{span:[lu,Je]},Je]}],"row-start":[{"row-start":U()}],"row-end":[{"row-end":U()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",Je]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",Je]}],gap:[{gap:[g]}],"gap-x":[{"gap-x":[g]}],"gap-y":[{"gap-y":[g]}],"justify-content":[{justify:["normal",...H()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...H(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...H(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[b]}],px:[{px:[b]}],py:[{py:[b]}],ps:[{ps:[b]}],pe:[{pe:[b]}],pt:[{pt:[b]}],pr:[{pr:[b]}],pb:[{pb:[b]}],pl:[{pl:[b]}],m:[{m:[E]}],mx:[{mx:[E]}],my:[{my:[E]}],ms:[{ms:[E]}],me:[{me:[E]}],mt:[{mt:[E]}],mr:[{mr:[E]}],mb:[{mb:[E]}],ml:[{ml:[E]}],"space-x":[{"space-x":[A]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[A]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit",Je,t]}],"min-w":[{"min-w":["min","max","fit",Je,oo]}],"max-w":[{"max-w":["0","none","full","min","max","fit","prose",{screen:[Yi]},Yi,Je]}],h:[{h:[Je,t,"auto","min","max","fit"]}],"min-h":[{"min-h":["min","max","fit",oo,Je]}],"max-h":[{"max-h":[Je,t,"min","max","fit"]}],"font-size":[{text:["base",Yi,Gi]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",ch]}],"font-family":[{font:[cu]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractons"],tracking:[{tracking:["tighter","tight","normal","wide","wider","widest",Je]}],"line-clamp":[{"line-clamp":["none",ha,ch]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",oo,Je]}],"list-image":[{"list-image":["none",Je]}],"list-style-type":[{list:["none","disc","decimal",Je]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[e]}],"placeholder-opacity":[{"placeholder-opacity":[_]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[e]}],"text-opacity":[{"text-opacity":[_]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...M(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",oo,Gi]}],"underline-offset":[{"underline-offset":["auto",oo,Je]}],"text-decoration-color":[{decoration:[e]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],indent:[{indent:G()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Je]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",Je]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[_]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...ne(),tF]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",eF]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},rF]}],"bg-color":[{bg:[e]}],"gradient-from-pos":[{from:[x]}],"gradient-via-pos":[{via:[x]}],"gradient-to-pos":[{to:[x]}],"gradient-from":[{from:[y]}],"gradient-via":[{via:[y]}],"gradient-to":[{to:[y]}],rounded:[{rounded:[i]}],"rounded-s":[{"rounded-s":[i]}],"rounded-e":[{"rounded-e":[i]}],"rounded-t":[{"rounded-t":[i]}],"rounded-r":[{"rounded-r":[i]}],"rounded-b":[{"rounded-b":[i]}],"rounded-l":[{"rounded-l":[i]}],"rounded-ss":[{"rounded-ss":[i]}],"rounded-se":[{"rounded-se":[i]}],"rounded-ee":[{"rounded-ee":[i]}],"rounded-es":[{"rounded-es":[i]}],"rounded-tl":[{"rounded-tl":[i]}],"rounded-tr":[{"rounded-tr":[i]}],"rounded-br":[{"rounded-br":[i]}],"rounded-bl":[{"rounded-bl":[i]}],"border-w":[{border:[l]}],"border-w-x":[{"border-x":[l]}],"border-w-y":[{"border-y":[l]}],"border-w-s":[{"border-s":[l]}],"border-w-e":[{"border-e":[l]}],"border-w-t":[{"border-t":[l]}],"border-w-r":[{"border-r":[l]}],"border-w-b":[{"border-b":[l]}],"border-w-l":[{"border-l":[l]}],"border-opacity":[{"border-opacity":[_]}],"border-style":[{border:[...M(),"hidden"]}],"divide-x":[{"divide-x":[l]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[l]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[_]}],"divide-style":[{divide:M()}],"border-color":[{border:[o]}],"border-color-x":[{"border-x":[o]}],"border-color-y":[{"border-y":[o]}],"border-color-t":[{"border-t":[o]}],"border-color-r":[{"border-r":[o]}],"border-color-b":[{"border-b":[o]}],"border-color-l":[{"border-l":[o]}],"divide-color":[{divide:[o]}],"outline-style":[{outline:["",...M()]}],"outline-offset":[{"outline-offset":[oo,Je]}],"outline-w":[{outline:[oo,Gi]}],"outline-color":[{outline:[e]}],"ring-w":[{ring:se()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[e]}],"ring-opacity":[{"ring-opacity":[_]}],"ring-offset-w":[{"ring-offset":[oo,Gi]}],"ring-offset-color":[{"ring-offset":[e]}],shadow:[{shadow:["","inner","none",Yi,oF]}],"shadow-color":[{shadow:[cu]}],opacity:[{opacity:[_]}],"mix-blend":[{"mix-blend":ee()}],"bg-blend":[{"bg-blend":ee()}],filter:[{filter:["","none"]}],blur:[{blur:[n]}],brightness:[{brightness:[r]}],contrast:[{contrast:[u]}],"drop-shadow":[{"drop-shadow":["","none",Yi,Je]}],grayscale:[{grayscale:[f]}],"hue-rotate":[{"hue-rotate":[m]}],invert:[{invert:[p]}],saturate:[{saturate:[C]}],sepia:[{sepia:[P]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[n]}],"backdrop-brightness":[{"backdrop-brightness":[r]}],"backdrop-contrast":[{"backdrop-contrast":[u]}],"backdrop-grayscale":[{"backdrop-grayscale":[f]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[m]}],"backdrop-invert":[{"backdrop-invert":[p]}],"backdrop-opacity":[{"backdrop-opacity":[_]}],"backdrop-saturate":[{"backdrop-saturate":[C]}],"backdrop-sepia":[{"backdrop-sepia":[P]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":[s]}],"border-spacing-x":[{"border-spacing-x":[s]}],"border-spacing-y":[{"border-spacing-y":[s]}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["none","all","","colors","opacity","shadow","transform",Je]}],duration:[{duration:pe()}],ease:[{ease:["linear","in","out","in-out",Je]}],delay:[{delay:pe()}],animate:[{animate:["none","spin","ping","pulse","bounce",Je]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[R]}],"scale-x":[{"scale-x":[R]}],"scale-y":[{"scale-y":[R]}],rotate:[{rotate:[lu,Je]}],"translate-x":[{"translate-x":[D]}],"translate-y":[{"translate-y":[D]}],"skew-x":[{"skew-x":[O]}],"skew-y":[{"skew-y":[O]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",Je]}],accent:[{accent:["auto",e]}],appearance:["appearance-none"],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",Je]}],"caret-color":[{caret:[e]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":G()}],"scroll-mx":[{"scroll-mx":G()}],"scroll-my":[{"scroll-my":G()}],"scroll-ms":[{"scroll-ms":G()}],"scroll-me":[{"scroll-me":G()}],"scroll-mt":[{"scroll-mt":G()}],"scroll-mr":[{"scroll-mr":G()}],"scroll-mb":[{"scroll-mb":G()}],"scroll-ml":[{"scroll-ml":G()}],"scroll-p":[{"scroll-p":G()}],"scroll-px":[{"scroll-px":G()}],"scroll-py":[{"scroll-py":G()}],"scroll-ps":[{"scroll-ps":G()}],"scroll-pe":[{"scroll-pe":G()}],"scroll-pt":[{"scroll-pt":G()}],"scroll-pr":[{"scroll-pr":G()}],"scroll-pb":[{"scroll-pb":G()}],"scroll-pl":[{"scroll-pl":G()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",Je]}],fill:[{fill:[e,"none"]}],"stroke-w":[{stroke:[oo,Gi,ch]}],stroke:[{stroke:[e,"none"]}],sr:["sr-only","not-sr-only"]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]}}}const tx=HL(lF),cF=40,fs="inpaint",uh="diffusers_sd",oC="diffusers_sdxl",dh="diffusers_sd_inpaint",iC="diffusers_sdxl_inpaint",d0="diffusers_other",Xy="#ffcc00bb",sC="ldm",aC="cv2",Gk="Fantasy-Studio/Paint-by-Example",uF="timbrooks/instruct-pix2pix",dF="Sanster/PowerPaint-V1-stable-diffusion-inpainting",fF="Sanster/AnyText",hF="out of frame, lowres, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, disfigured, gross proportions, malformed limbs, watermark, signature";function Ce(...e){return tx(Bk(e))}function pF(){async function e(r=""){return(await fetch(r,{method:"GET",cache:"no-cache"})).json()}const t=()=>{const r=document.location;e(r+"/flaskwebgui-keep-server-alive").then(i=>i)},n=3*1e3;t(),setInterval(t,n)}function lC(e){const t=e.split(",")[0].split(":")[1].split(";")[0],n=atob(e.split(",")[1]),r=[];for(let o=0;o{const o=e.src,i=e;i.onload=n,i.onerror=s=>{i.src=o,r(s)},i.src=t})}async function mF(e){const t=URL.createObjectURL(e),n=new Image;return await Vh(n,t),n}function cC(e){return new Promise((t,n)=>{const r=new Image;r.addEventListener("load",()=>{t(r)}),r.addEventListener("error",o=>{n(o)}),r.src=e.toDataURL()})}function gF(e){return new Promise((t,n)=>{const r=new FileReader;r.onload=()=>{const o=new Image;o.onload=()=>{t(o)},o.onerror=()=>{n("无法加载图像。")},o.src=r.result},r.onerror=()=>{n("无法读取文件。")},r.readAsDataURL(e)})}function Nu(e,t,n){return fetch(e).then(function(r){return r.arrayBuffer()}).then(function(r){return new File([r],t,{type:n})})}async function vF(){try{const{state:e}=await navigator.permissions.query({name:"clipboard-write"});return e==="granted"}catch{return!1}}function yF(e,t){return new Promise((n,r)=>e.toBlob(async o=>{o?n(o):r(new Error("Expected toBlob() to be defined"))},t))}const wF=async e=>{const t=[new ClipboardItem({[e.type]:e})];await navigator.clipboard.write(t)};function uC(e){return e.nativeEvent.button===2}function dC(e){return e.nativeEvent.button===1}async function xF(e){const t=await yF(e,"image/png");try{await wF(t)}catch{console.log("Copy image failed!")}}function bF(e,t){const n=document.createElement("a");n.href=e,n.download=t,n.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0,view:window})),setTimeout(()=>{n.remove()},100)}function f0(e){const t=e.nativeEvent;return{x:t.offsetX,y:t.offsetY}}function Yk(e,t,n=Xy){e.strokeStyle=n,e.lineCap="round",e.lineJoin="round",t.forEach(r=>{!(r!=null&&r.pts.length)||!r.size||(e.lineWidth=r.size,e.beginPath(),e.moveTo(r.pts[0].x,r.pts[0].y),r.pts.forEach(o=>e.lineTo(o.x,o.y)),e.stroke())})}const Wh=(e,t,n,r=[],o="white")=>{const i=document.createElement("canvas");i.width=e,i.height=t;const s=i.getContext("2d");if(!s)throw new Error("could not retrieve mask canvas");return r.forEach(l=>{s.drawImage(l,0,0,e,t)}),n.forEach(l=>{Yk(s,l,o)}),i},Du=e=>new Promise((t,n)=>{const r=new FileReader;r.onload=o=>{var s;const i=(s=o.target)==null?void 0:s.result;t(i)},r.onerror=o=>{n(o)},r.readAsDataURL(e)});function Xk(e,t){return function(){return e.apply(t,arguments)}}const{toString:SF}=Object.prototype,{getPrototypeOf:nx}=Object,Tm=(e=>t=>{const n=SF.call(t);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),ei=e=>(e=e.toLowerCase(),t=>Tm(t)===e),Pm=e=>t=>typeof t===e,{isArray:Sc}=Array,rd=Pm("undefined");function _F(e){return e!==null&&!rd(e)&&e.constructor!==null&&!rd(e.constructor)&&Kr(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const Zk=ei("ArrayBuffer");function EF(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&Zk(e.buffer),t}const CF=Pm("string"),Kr=Pm("function"),qk=Pm("number"),Am=e=>e!==null&&typeof e=="object",$F=e=>e===!0||e===!1,Hh=e=>{if(Tm(e)!=="object")return!1;const t=nx(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},RF=ei("Date"),kF=ei("File"),TF=ei("Blob"),PF=ei("FileList"),AF=e=>Am(e)&&Kr(e.pipe),MF=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||Kr(e.append)&&((t=Tm(e))==="formdata"||t==="object"&&Kr(e.toString)&&e.toString()==="[object FormData]"))},OF=ei("URLSearchParams"),NF=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function Nd(e,t,{allOwnKeys:n=!1}={}){if(e===null||typeof e>"u")return;let r,o;if(typeof e!="object"&&(e=[e]),Sc(e))for(r=0,o=e.length;r0;)if(o=n[r],t===o.toLowerCase())return o;return null}const Jk=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,eT=e=>!rd(e)&&e!==Jk;function Zy(){const{caseless:e}=eT(this)&&this||{},t={},n=(r,o)=>{const i=e&&Qk(t,o)||o;Hh(t[i])&&Hh(r)?t[i]=Zy(t[i],r):Hh(r)?t[i]=Zy({},r):Sc(r)?t[i]=r.slice():t[i]=r};for(let r=0,o=arguments.length;r(Nd(t,(o,i)=>{n&&Kr(o)?e[i]=Xk(o,n):e[i]=o},{allOwnKeys:r}),e),IF=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),LF=(e,t,n,r)=>{e.prototype=Object.create(t.prototype,r),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),n&&Object.assign(e.prototype,n)},FF=(e,t,n,r)=>{let o,i,s;const l={};if(t=t||{},e==null)return t;do{for(o=Object.getOwnPropertyNames(e),i=o.length;i-- >0;)s=o[i],(!r||r(s,e,t))&&!l[s]&&(t[s]=e[s],l[s]=!0);e=n!==!1&&nx(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},jF=(e,t,n)=>{e=String(e),(n===void 0||n>e.length)&&(n=e.length),n-=t.length;const r=e.indexOf(t,n);return r!==-1&&r===n},zF=e=>{if(!e)return null;if(Sc(e))return e;let t=e.length;if(!qk(t))return null;const n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},BF=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&nx(Uint8Array)),UF=(e,t)=>{const r=(e&&e[Symbol.iterator]).call(e);let o;for(;(o=r.next())&&!o.done;){const i=o.value;t.call(e,i[0],i[1])}},VF=(e,t)=>{let n;const r=[];for(;(n=e.exec(t))!==null;)r.push(n);return r},WF=ei("HTMLFormElement"),HF=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,r,o){return r.toUpperCase()+o}),fC=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),KF=ei("RegExp"),tT=(e,t)=>{const n=Object.getOwnPropertyDescriptors(e),r={};Nd(n,(o,i)=>{let s;(s=t(o,i,e))!==!1&&(r[i]=s||o)}),Object.defineProperties(e,r)},GF=e=>{tT(e,(t,n)=>{if(Kr(e)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;const r=e[n];if(Kr(r)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},YF=(e,t)=>{const n={},r=o=>{o.forEach(i=>{n[i]=!0})};return Sc(e)?r(e):r(String(e).split(t)),n},XF=()=>{},ZF=(e,t)=>(e=+e,Number.isFinite(e)?e:t),h0="abcdefghijklmnopqrstuvwxyz",hC="0123456789",nT={DIGIT:hC,ALPHA:h0,ALPHA_DIGIT:h0+h0.toUpperCase()+hC},qF=(e=16,t=nT.ALPHA_DIGIT)=>{let n="";const{length:r}=t;for(;e--;)n+=t[Math.random()*r|0];return n};function QF(e){return!!(e&&Kr(e.append)&&e[Symbol.toStringTag]==="FormData"&&e[Symbol.iterator])}const JF=e=>{const t=new Array(10),n=(r,o)=>{if(Am(r)){if(t.indexOf(r)>=0)return;if(!("toJSON"in r)){t[o]=r;const i=Sc(r)?[]:{};return Nd(r,(s,l)=>{const u=n(s,o+1);!rd(u)&&(i[l]=u)}),t[o]=void 0,i}}return r};return n(e,0)},ej=ei("AsyncFunction"),tj=e=>e&&(Am(e)||Kr(e))&&Kr(e.then)&&Kr(e.catch),ie={isArray:Sc,isArrayBuffer:Zk,isBuffer:_F,isFormData:MF,isArrayBufferView:EF,isString:CF,isNumber:qk,isBoolean:$F,isObject:Am,isPlainObject:Hh,isUndefined:rd,isDate:RF,isFile:kF,isBlob:TF,isRegExp:KF,isFunction:Kr,isStream:AF,isURLSearchParams:OF,isTypedArray:BF,isFileList:PF,forEach:Nd,merge:Zy,extend:DF,trim:NF,stripBOM:IF,inherits:LF,toFlatObject:FF,kindOf:Tm,kindOfTest:ei,endsWith:jF,toArray:zF,forEachEntry:UF,matchAll:VF,isHTMLForm:WF,hasOwnProperty:fC,hasOwnProp:fC,reduceDescriptors:tT,freezeMethods:GF,toObjectSet:YF,toCamelCase:HF,noop:XF,toFiniteNumber:ZF,findKey:Qk,global:Jk,isContextDefined:eT,ALPHABET:nT,generateString:qF,isSpecCompliantForm:QF,toJSONObject:JF,isAsyncFn:ej,isThenable:tj};function ut(e,t,n,r,o){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),n&&(this.config=n),r&&(this.request=r),o&&(this.response=o)}ie.inherits(ut,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:ie.toJSONObject(this.config),code:this.code,status:this.response&&this.response.status?this.response.status:null}}});const rT=ut.prototype,oT={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{oT[e]={value:e}});Object.defineProperties(ut,oT);Object.defineProperty(rT,"isAxiosError",{value:!0});ut.from=(e,t,n,r,o,i)=>{const s=Object.create(rT);return ie.toFlatObject(e,s,function(u){return u!==Error.prototype},l=>l!=="isAxiosError"),ut.call(s,e.message,t,n,r,o),s.cause=e,s.name=e.name,i&&Object.assign(s,i),s};const nj=null;function qy(e){return ie.isPlainObject(e)||ie.isArray(e)}function iT(e){return ie.endsWith(e,"[]")?e.slice(0,-2):e}function pC(e,t,n){return e?e.concat(t).map(function(o,i){return o=iT(o),!n&&i?"["+o+"]":o}).join(n?".":""):t}function rj(e){return ie.isArray(e)&&!e.some(qy)}const oj=ie.toFlatObject(ie,{},null,function(t){return/^is[A-Z]/.test(t)});function Mm(e,t,n){if(!ie.isObject(e))throw new TypeError("target must be an object");t=t||new FormData,n=ie.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(S,E){return!ie.isUndefined(E[S])});const r=n.metaTokens,o=n.visitor||m,i=n.dots,s=n.indexes,u=(n.Blob||typeof Blob<"u"&&Blob)&&ie.isSpecCompliantForm(t);if(!ie.isFunction(o))throw new TypeError("visitor must be a function");function f(x){if(x===null)return"";if(ie.isDate(x))return x.toISOString();if(!u&&ie.isBlob(x))throw new ut("Blob is not supported. Use a Buffer instead.");return ie.isArrayBuffer(x)||ie.isTypedArray(x)?u&&typeof Blob=="function"?new Blob([x]):Buffer.from(x):x}function m(x,S,E){let _=x;if(x&&!E&&typeof x=="object"){if(ie.endsWith(S,"{}"))S=r?S:S.slice(0,-2),x=JSON.stringify(x);else if(ie.isArray(x)&&rj(x)||(ie.isFileList(x)||ie.endsWith(S,"[]"))&&(_=ie.toArray(x)))return S=iT(S),_.forEach(function(C,R){!(ie.isUndefined(C)||C===null)&&t.append(s===!0?pC([S],R,i):s===null?S:S+"[]",f(C))}),!1}return qy(x)?!0:(t.append(pC(E,S,i),f(x)),!1)}const p=[],g=Object.assign(oj,{defaultVisitor:m,convertValue:f,isVisitable:qy});function y(x,S){if(!ie.isUndefined(x)){if(p.indexOf(x)!==-1)throw Error("Circular reference detected in "+S.join("."));p.push(x),ie.forEach(x,function(_,b){(!(ie.isUndefined(_)||_===null)&&o.call(t,_,ie.isString(b)?b.trim():b,S,g))===!0&&y(_,S?S.concat(b):[b])}),p.pop()}}if(!ie.isObject(e))throw new TypeError("data must be an object");return y(e),t}function mC(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(r){return t[r]})}function rx(e,t){this._pairs=[],e&&Mm(e,this,t)}const sT=rx.prototype;sT.append=function(t,n){this._pairs.push([t,n])};sT.toString=function(t){const n=t?function(r){return t.call(this,r,mC)}:mC;return this._pairs.map(function(o){return n(o[0])+"="+n(o[1])},"").join("&")};function ij(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function aT(e,t,n){if(!t)return e;const r=n&&n.encode||ij,o=n&&n.serialize;let i;if(o?i=o(t,n):i=ie.isURLSearchParams(t)?t.toString():new rx(t,n).toString(r),i){const s=e.indexOf("#");s!==-1&&(e=e.slice(0,s)),e+=(e.indexOf("?")===-1?"?":"&")+i}return e}class sj{constructor(){this.handlers=[]}use(t,n,r){return this.handlers.push({fulfilled:t,rejected:n,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){ie.forEach(this.handlers,function(r){r!==null&&t(r)})}}const gC=sj,lT={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},aj=typeof URLSearchParams<"u"?URLSearchParams:rx,lj=typeof FormData<"u"?FormData:null,cj=typeof Blob<"u"?Blob:null,uj={isBrowser:!0,classes:{URLSearchParams:aj,FormData:lj,Blob:cj},protocols:["http","https","file","blob","url","data"]},cT=typeof window<"u"&&typeof document<"u",dj=(e=>cT&&["ReactNative","NativeScript","NS"].indexOf(e)<0)(typeof navigator<"u"&&navigator.product),fj=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",hj=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:cT,hasStandardBrowserEnv:dj,hasStandardBrowserWebWorkerEnv:fj},Symbol.toStringTag,{value:"Module"})),zo={...hj,...uj};function pj(e,t){return Mm(e,new zo.classes.URLSearchParams,Object.assign({visitor:function(n,r,o,i){return zo.isNode&&ie.isBuffer(n)?(this.append(r,n.toString("base64")),!1):i.defaultVisitor.apply(this,arguments)}},t))}function mj(e){return ie.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function gj(e){const t={},n=Object.keys(e);let r;const o=n.length;let i;for(r=0;r=n.length;return s=!s&&ie.isArray(o)?o.length:s,u?(ie.hasOwnProp(o,s)?o[s]=[o[s],r]:o[s]=r,!l):((!o[s]||!ie.isObject(o[s]))&&(o[s]=[]),t(n,r,o[s],i)&&ie.isArray(o[s])&&(o[s]=gj(o[s])),!l)}if(ie.isFormData(e)&&ie.isFunction(e.entries)){const n={};return ie.forEachEntry(e,(r,o)=>{t(mj(r),o,n,0)}),n}return null}function vj(e,t,n){if(ie.isString(e))try{return(t||JSON.parse)(e),ie.trim(e)}catch(r){if(r.name!=="SyntaxError")throw r}return(n||JSON.stringify)(e)}const ox={transitional:lT,adapter:["xhr","http"],transformRequest:[function(t,n){const r=n.getContentType()||"",o=r.indexOf("application/json")>-1,i=ie.isObject(t);if(i&&ie.isHTMLForm(t)&&(t=new FormData(t)),ie.isFormData(t))return o&&o?JSON.stringify(uT(t)):t;if(ie.isArrayBuffer(t)||ie.isBuffer(t)||ie.isStream(t)||ie.isFile(t)||ie.isBlob(t))return t;if(ie.isArrayBufferView(t))return t.buffer;if(ie.isURLSearchParams(t))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let l;if(i){if(r.indexOf("application/x-www-form-urlencoded")>-1)return pj(t,this.formSerializer).toString();if((l=ie.isFileList(t))||r.indexOf("multipart/form-data")>-1){const u=this.env&&this.env.FormData;return Mm(l?{"files[]":t}:t,u&&new u,this.formSerializer)}}return i||o?(n.setContentType("application/json",!1),vj(t)):t}],transformResponse:[function(t){const n=this.transitional||ox.transitional,r=n&&n.forcedJSONParsing,o=this.responseType==="json";if(t&&ie.isString(t)&&(r&&!this.responseType||o)){const s=!(n&&n.silentJSONParsing)&&o;try{return JSON.parse(t)}catch(l){if(s)throw l.name==="SyntaxError"?ut.from(l,ut.ERR_BAD_RESPONSE,this,null,this.response):l}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:zo.classes.FormData,Blob:zo.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};ie.forEach(["delete","get","head","post","put","patch"],e=>{ox.headers[e]={}});const ix=ox,yj=ie.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),wj=e=>{const t={};let n,r,o;return e&&e.split(` +`).forEach(function(s){o=s.indexOf(":"),n=s.substring(0,o).trim().toLowerCase(),r=s.substring(o+1).trim(),!(!n||t[n]&&yj[n])&&(n==="set-cookie"?t[n]?t[n].push(r):t[n]=[r]:t[n]=t[n]?t[n]+", "+r:r)}),t},vC=Symbol("internals");function uu(e){return e&&String(e).trim().toLowerCase()}function Kh(e){return e===!1||e==null?e:ie.isArray(e)?e.map(Kh):String(e)}function xj(e){const t=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=n.exec(e);)t[r[1]]=r[2];return t}const bj=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function p0(e,t,n,r,o){if(ie.isFunction(r))return r.call(this,t,n);if(o&&(t=n),!!ie.isString(t)){if(ie.isString(r))return t.indexOf(r)!==-1;if(ie.isRegExp(r))return r.test(t)}}function Sj(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,n,r)=>n.toUpperCase()+r)}function _j(e,t){const n=ie.toCamelCase(" "+t);["get","set","has"].forEach(r=>{Object.defineProperty(e,r+n,{value:function(o,i,s){return this[r].call(this,t,o,i,s)},configurable:!0})})}class Om{constructor(t){t&&this.set(t)}set(t,n,r){const o=this;function i(l,u,f){const m=uu(u);if(!m)throw new Error("header name must be a non-empty string");const p=ie.findKey(o,m);(!p||o[p]===void 0||f===!0||f===void 0&&o[p]!==!1)&&(o[p||u]=Kh(l))}const s=(l,u)=>ie.forEach(l,(f,m)=>i(f,m,u));return ie.isPlainObject(t)||t instanceof this.constructor?s(t,n):ie.isString(t)&&(t=t.trim())&&!bj(t)?s(wj(t),n):t!=null&&i(n,t,r),this}get(t,n){if(t=uu(t),t){const r=ie.findKey(this,t);if(r){const o=this[r];if(!n)return o;if(n===!0)return xj(o);if(ie.isFunction(n))return n.call(this,o,r);if(ie.isRegExp(n))return n.exec(o);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,n){if(t=uu(t),t){const r=ie.findKey(this,t);return!!(r&&this[r]!==void 0&&(!n||p0(this,this[r],r,n)))}return!1}delete(t,n){const r=this;let o=!1;function i(s){if(s=uu(s),s){const l=ie.findKey(r,s);l&&(!n||p0(r,r[l],l,n))&&(delete r[l],o=!0)}}return ie.isArray(t)?t.forEach(i):i(t),o}clear(t){const n=Object.keys(this);let r=n.length,o=!1;for(;r--;){const i=n[r];(!t||p0(this,this[i],i,t,!0))&&(delete this[i],o=!0)}return o}normalize(t){const n=this,r={};return ie.forEach(this,(o,i)=>{const s=ie.findKey(r,i);if(s){n[s]=Kh(o),delete n[i];return}const l=t?Sj(i):String(i).trim();l!==i&&delete n[i],n[l]=Kh(o),r[l]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){const n=Object.create(null);return ie.forEach(this,(r,o)=>{r!=null&&r!==!1&&(n[o]=t&&ie.isArray(r)?r.join(", "):r)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,n])=>t+": "+n).join(` +`)}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...n){const r=new this(t);return n.forEach(o=>r.set(o)),r}static accessor(t){const r=(this[vC]=this[vC]={accessors:{}}).accessors,o=this.prototype;function i(s){const l=uu(s);r[l]||(_j(o,s),r[l]=!0)}return ie.isArray(t)?t.forEach(i):i(t),this}}Om.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);ie.reduceDescriptors(Om.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(r){this[n]=r}}});ie.freezeMethods(Om);const xi=Om;function m0(e,t){const n=this||ix,r=t||n,o=xi.from(r.headers);let i=r.data;return ie.forEach(e,function(l){i=l.call(n,i,o.normalize(),t?t.status:void 0)}),o.normalize(),i}function dT(e){return!!(e&&e.__CANCEL__)}function Dd(e,t,n){ut.call(this,e??"canceled",ut.ERR_CANCELED,t,n),this.name="CanceledError"}ie.inherits(Dd,ut,{__CANCEL__:!0});function Ej(e,t,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?e(n):t(new ut("Request failed with status code "+n.status,[ut.ERR_BAD_REQUEST,ut.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}const Cj=zo.hasStandardBrowserEnv?{write(e,t,n,r,o,i){const s=[e+"="+encodeURIComponent(t)];ie.isNumber(n)&&s.push("expires="+new Date(n).toGMTString()),ie.isString(r)&&s.push("path="+r),ie.isString(o)&&s.push("domain="+o),i===!0&&s.push("secure"),document.cookie=s.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function $j(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function Rj(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e}function fT(e,t){return e&&!$j(t)?Rj(e,t):t}const kj=zo.hasStandardBrowserEnv?function(){const t=/(msie|trident)/i.test(navigator.userAgent),n=document.createElement("a");let r;function o(i){let s=i;return t&&(n.setAttribute("href",s),s=n.href),n.setAttribute("href",s),{href:n.href,protocol:n.protocol?n.protocol.replace(/:$/,""):"",host:n.host,search:n.search?n.search.replace(/^\?/,""):"",hash:n.hash?n.hash.replace(/^#/,""):"",hostname:n.hostname,port:n.port,pathname:n.pathname.charAt(0)==="/"?n.pathname:"/"+n.pathname}}return r=o(window.location.href),function(s){const l=ie.isString(s)?o(s):s;return l.protocol===r.protocol&&l.host===r.host}}():function(){return function(){return!0}}();function Tj(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function Pj(e,t){e=e||10;const n=new Array(e),r=new Array(e);let o=0,i=0,s;return t=t!==void 0?t:1e3,function(u){const f=Date.now(),m=r[i];s||(s=f),n[o]=u,r[o]=f;let p=i,g=0;for(;p!==o;)g+=n[p++],p=p%e;if(o=(o+1)%e,o===i&&(i=(i+1)%e),f-s{const i=o.loaded,s=o.lengthComputable?o.total:void 0,l=i-n,u=r(l),f=i<=s;n=i;const m={loaded:i,total:s,progress:s?i/s:void 0,bytes:l,rate:u||void 0,estimated:u&&s&&f?(s-i)/u:void 0,event:o};m[t?"download":"upload"]=!0,e(m)}}const Aj=typeof XMLHttpRequest<"u",Mj=Aj&&function(e){return new Promise(function(n,r){let o=e.data;const i=xi.from(e.headers).normalize();let{responseType:s,withXSRFToken:l}=e,u;function f(){e.cancelToken&&e.cancelToken.unsubscribe(u),e.signal&&e.signal.removeEventListener("abort",u)}let m;if(ie.isFormData(o)){if(zo.hasStandardBrowserEnv||zo.hasStandardBrowserWebWorkerEnv)i.setContentType(!1);else if((m=i.getContentType())!==!1){const[S,...E]=m?m.split(";").map(_=>_.trim()).filter(Boolean):[];i.setContentType([S||"multipart/form-data",...E].join("; "))}}let p=new XMLHttpRequest;if(e.auth){const S=e.auth.username||"",E=e.auth.password?unescape(encodeURIComponent(e.auth.password)):"";i.set("Authorization","Basic "+btoa(S+":"+E))}const g=fT(e.baseURL,e.url);p.open(e.method.toUpperCase(),aT(g,e.params,e.paramsSerializer),!0),p.timeout=e.timeout;function y(){if(!p)return;const S=xi.from("getAllResponseHeaders"in p&&p.getAllResponseHeaders()),_={data:!s||s==="text"||s==="json"?p.responseText:p.response,status:p.status,statusText:p.statusText,headers:S,config:e,request:p};Ej(function(C){n(C),f()},function(C){r(C),f()},_),p=null}if("onloadend"in p?p.onloadend=y:p.onreadystatechange=function(){!p||p.readyState!==4||p.status===0&&!(p.responseURL&&p.responseURL.indexOf("file:")===0)||setTimeout(y)},p.onabort=function(){p&&(r(new ut("Request aborted",ut.ECONNABORTED,e,p)),p=null)},p.onerror=function(){r(new ut("Network Error",ut.ERR_NETWORK,e,p)),p=null},p.ontimeout=function(){let E=e.timeout?"timeout of "+e.timeout+"ms exceeded":"timeout exceeded";const _=e.transitional||lT;e.timeoutErrorMessage&&(E=e.timeoutErrorMessage),r(new ut(E,_.clarifyTimeoutError?ut.ETIMEDOUT:ut.ECONNABORTED,e,p)),p=null},zo.hasStandardBrowserEnv&&(l&&ie.isFunction(l)&&(l=l(e)),l||l!==!1&&kj(g))){const S=e.xsrfHeaderName&&e.xsrfCookieName&&Cj.read(e.xsrfCookieName);S&&i.set(e.xsrfHeaderName,S)}o===void 0&&i.setContentType(null),"setRequestHeader"in p&&ie.forEach(i.toJSON(),function(E,_){p.setRequestHeader(_,E)}),ie.isUndefined(e.withCredentials)||(p.withCredentials=!!e.withCredentials),s&&s!=="json"&&(p.responseType=e.responseType),typeof e.onDownloadProgress=="function"&&p.addEventListener("progress",yC(e.onDownloadProgress,!0)),typeof e.onUploadProgress=="function"&&p.upload&&p.upload.addEventListener("progress",yC(e.onUploadProgress)),(e.cancelToken||e.signal)&&(u=S=>{p&&(r(!S||S.type?new Dd(null,e,p):S),p.abort(),p=null)},e.cancelToken&&e.cancelToken.subscribe(u),e.signal&&(e.signal.aborted?u():e.signal.addEventListener("abort",u)));const x=Tj(g);if(x&&zo.protocols.indexOf(x)===-1){r(new ut("Unsupported protocol "+x+":",ut.ERR_BAD_REQUEST,e));return}p.send(o||null)})},Qy={http:nj,xhr:Mj};ie.forEach(Qy,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});const wC=e=>`- ${e}`,Oj=e=>ie.isFunction(e)||e===null||e===!1,hT={getAdapter:e=>{e=ie.isArray(e)?e:[e];const{length:t}=e;let n,r;const o={};for(let i=0;i`adapter ${l} `+(u===!1?"is not supported by the environment":"is not available in the build"));let s=t?i.length>1?`since : +`+i.map(wC).join(` +`):" "+wC(i[0]):"as no adapter specified";throw new ut("There is no suitable adapter to dispatch the request "+s,"ERR_NOT_SUPPORT")}return r},adapters:Qy};function g0(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Dd(null,e)}function xC(e){return g0(e),e.headers=xi.from(e.headers),e.data=m0.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),hT.getAdapter(e.adapter||ix.adapter)(e).then(function(r){return g0(e),r.data=m0.call(e,e.transformResponse,r),r.headers=xi.from(r.headers),r},function(r){return dT(r)||(g0(e),r&&r.response&&(r.response.data=m0.call(e,e.transformResponse,r.response),r.response.headers=xi.from(r.response.headers))),Promise.reject(r)})}const bC=e=>e instanceof xi?e.toJSON():e;function ic(e,t){t=t||{};const n={};function r(f,m,p){return ie.isPlainObject(f)&&ie.isPlainObject(m)?ie.merge.call({caseless:p},f,m):ie.isPlainObject(m)?ie.merge({},m):ie.isArray(m)?m.slice():m}function o(f,m,p){if(ie.isUndefined(m)){if(!ie.isUndefined(f))return r(void 0,f,p)}else return r(f,m,p)}function i(f,m){if(!ie.isUndefined(m))return r(void 0,m)}function s(f,m){if(ie.isUndefined(m)){if(!ie.isUndefined(f))return r(void 0,f)}else return r(void 0,m)}function l(f,m,p){if(p in t)return r(f,m);if(p in e)return r(void 0,f)}const u={url:i,method:i,data:i,baseURL:s,transformRequest:s,transformResponse:s,paramsSerializer:s,timeout:s,timeoutMessage:s,withCredentials:s,withXSRFToken:s,adapter:s,responseType:s,xsrfCookieName:s,xsrfHeaderName:s,onUploadProgress:s,onDownloadProgress:s,decompress:s,maxContentLength:s,maxBodyLength:s,beforeRedirect:s,transport:s,httpAgent:s,httpsAgent:s,cancelToken:s,socketPath:s,responseEncoding:s,validateStatus:l,headers:(f,m)=>o(bC(f),bC(m),!0)};return ie.forEach(Object.keys(Object.assign({},e,t)),function(m){const p=u[m]||o,g=p(e[m],t[m],m);ie.isUndefined(g)&&p!==l||(n[m]=g)}),n}const pT="1.6.2",sx={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{sx[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const SC={};sx.transitional=function(t,n,r){function o(i,s){return"[Axios v"+pT+"] Transitional option '"+i+"'"+s+(r?". "+r:"")}return(i,s,l)=>{if(t===!1)throw new ut(o(s," has been removed"+(n?" in "+n:"")),ut.ERR_DEPRECATED);return n&&!SC[s]&&(SC[s]=!0,console.warn(o(s," has been deprecated since v"+n+" and will be removed in the near future"))),t?t(i,s,l):!0}};function Nj(e,t,n){if(typeof e!="object")throw new ut("options must be an object",ut.ERR_BAD_OPTION_VALUE);const r=Object.keys(e);let o=r.length;for(;o-- >0;){const i=r[o],s=t[i];if(s){const l=e[i],u=l===void 0||s(l,i,e);if(u!==!0)throw new ut("option "+i+" must be "+u,ut.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new ut("Unknown option "+i,ut.ERR_BAD_OPTION)}}const Jy={assertOptions:Nj,validators:sx},Xi=Jy.validators;class Op{constructor(t){this.defaults=t,this.interceptors={request:new gC,response:new gC}}request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=ic(this.defaults,n);const{transitional:r,paramsSerializer:o,headers:i}=n;r!==void 0&&Jy.assertOptions(r,{silentJSONParsing:Xi.transitional(Xi.boolean),forcedJSONParsing:Xi.transitional(Xi.boolean),clarifyTimeoutError:Xi.transitional(Xi.boolean)},!1),o!=null&&(ie.isFunction(o)?n.paramsSerializer={serialize:o}:Jy.assertOptions(o,{encode:Xi.function,serialize:Xi.function},!0)),n.method=(n.method||this.defaults.method||"get").toLowerCase();let s=i&&ie.merge(i.common,i[n.method]);i&&ie.forEach(["delete","get","head","post","put","patch","common"],x=>{delete i[x]}),n.headers=xi.concat(s,i);const l=[];let u=!0;this.interceptors.request.forEach(function(S){typeof S.runWhen=="function"&&S.runWhen(n)===!1||(u=u&&S.synchronous,l.unshift(S.fulfilled,S.rejected))});const f=[];this.interceptors.response.forEach(function(S){f.push(S.fulfilled,S.rejected)});let m,p=0,g;if(!u){const x=[xC.bind(this),void 0];for(x.unshift.apply(x,l),x.push.apply(x,f),g=x.length,m=Promise.resolve(n);p{if(!r._listeners)return;let i=r._listeners.length;for(;i-- >0;)r._listeners[i](o);r._listeners=null}),this.promise.then=o=>{let i;const s=new Promise(l=>{r.subscribe(l),i=l}).then(o);return s.cancel=function(){r.unsubscribe(i)},s},t(function(i,s,l){r.reason||(r.reason=new Dd(i,s,l),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}static source(){let t;return{token:new ax(function(o){t=o}),cancel:t}}}const Dj=ax;function Ij(e){return function(n){return e.apply(null,n)}}function Lj(e){return ie.isObject(e)&&e.isAxiosError===!0}const e1={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(e1).forEach(([e,t])=>{e1[t]=e});const Fj=e1;function mT(e){const t=new Gh(e),n=Xk(Gh.prototype.request,t);return ie.extend(n,Gh.prototype,t,{allOwnKeys:!0}),ie.extend(n,t,null,{allOwnKeys:!0}),n.create=function(o){return mT(ic(e,o))},n}const Qt=mT(ix);Qt.Axios=Gh;Qt.CanceledError=Dd;Qt.CancelToken=Dj;Qt.isCancel=dT;Qt.VERSION=pT;Qt.toFormData=Mm;Qt.AxiosError=ut;Qt.Cancel=Qt.CanceledError;Qt.all=function(t){return Promise.all(t)};Qt.spread=Ij;Qt.isAxiosError=Lj;Qt.mergeConfig=ic;Qt.AxiosHeaders=xi;Qt.formToJSON=e=>uT(ie.isHTMLForm(e)?new FormData(e):e);Qt.getAdapter=hT.getAdapter;Qt.HttpStatusCode=Fj;Qt.default=Qt;const jj=Qt,Ls="/api/v1",_c=jj.create({baseURL:Ls});async function zj(e,t,n,r,o,i=null){const s=await Du(e),l=await Du(o),u=i?await Du(i):null,f=await fetch(`${Ls}/inpaint`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({image:s,mask:l,ldm_steps:t.ldmSteps,ldm_sampler:t.ldmSampler,zits_wireframe:t.zitsWireframe,cv2_flag:t.cv2Flag,cv2_radius:t.cv2Radius,hd_strategy:"Crop",hd_strategy_crop_triger_size:640,hd_strategy_crop_margin:128,hd_trategy_resize_imit:2048,prompt:t.prompt,negative_prompt:t.negativePrompt,use_croper:t.showCropper,croper_x:n.x,croper_y:n.y,croper_height:n.height,croper_width:n.width,use_extender:t.showExtender,extender_x:r.x,extender_y:r.y,extender_height:r.height,extender_width:r.width,sd_mask_blur:t.sdMaskBlur,sd_strength:t.sdStrength,sd_steps:t.sdSteps,sd_guidance_scale:t.sdGuidanceScale,sd_sampler:t.sdSampler,sd_seed:t.seedFixed?t.seed:-1,sd_match_histograms:t.sdMatchHistograms,sd_freeu:t.enableFreeu,sd_freeu_config:t.freeuConfig,sd_lcm_lora:t.enableLCMLora,paint_by_example_example_image:u,p2p_image_guidance_scale:t.p2pImageGuidanceScale,enable_controlnet:t.enableControlnet,controlnet_conditioning_scale:t.controlnetConditioningScale,controlnet_method:t.controlnetMethod?t.controlnetMethod:"",powerpaint_task:t.showExtender?Ol.outpainting:t.powerpaintTask})});if(f.ok){const p=await f.blob();return{blob:URL.createObjectURL(p),seed:f.headers.get("X-Seed")}}const m=await f.json();throw new Error(`Something went wrong: ${m.errors}`)}async function gT(){return(await _c.get("/server-config")).data}async function Bj(e){return(await _c.post("/model",{name:e})).data}async function v0(e,t){return _c.post("/switch_plugin_model",{plugin_name:e,model_name:t})}async function Uj(){return(await _c.get("/model")).data}async function vT(e,t,n,r,o){const i=await Du(n),l=await fetch(`${Ls}/${e?"run_plugin_gen_mask":"run_plugin_gen_image"}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t,image:i,upscale:r,clicks:o})});if(l.ok){const f=await l.blob();return{blob:URL.createObjectURL(f)}}const u=await l.json();throw new Error(u)}async function Vj(e,t){const n=await fetch(`${Ls}/media_file?tab=${e}&filename=${encodeURIComponent(t)}`,{method:"GET"});if(n.ok){const o=await n.blob();return new File([o],t,{type:n.headers.get("Content-Type")??"image/png"})}const r=await n.json();throw new Error(r.errors)}async function Wj(e){return(await _c.get("medias",{params:{tab:e}})).data}async function Hj(e,t,n){const r=await Nu(e.src,t,n),o=new FormData;o.append("file",r);try{const i=await fetch(`${Ls}/save_image`,{method:"POST",body:o});if(!i.ok){const s=await i.text();throw new Error(s)}}catch(i){throw new Error(`Something went wrong: ${i}`)}}async function Kj(e){const t=new FormData;return t.append("file",e),(await _c.post("/gen-info",t)).data}async function Gj(e,t,n){const r=await Du(e),o=await fetch(`${Ls}/adjust_mask`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mask:r,operate:t,kernel_size:n})});if(o.ok)return await o.blob();const i=await o.json();throw new Error(i)}function Yj(){const[e,t]=d.useState(null),n=d.useCallback(()=>{const r=new Headers;r.append("pragma","no-cache"),r.append("cache-control","no-cache"),fetch(`${Ls}/inputimage`,{headers:r}).then(async o=>{var l;if(!o.ok)return;const i=(l=o.headers.get("content-disposition"))==null?void 0:l.split("filename=")[1].split(";")[0],s=await o.blob();if(s&&s.type.startsWith("image")){const u=new File([s],i!==void 0?i:"inputImage");t(u)}}).catch(o=>{console.log(o)})},[t]);return d.useEffect(()=>{n()},[n]),e}function _o(e,t){if(e==null)return{};var n={},r=Object.keys(e),o,i;for(i=0;i=0)&&(n[o]=e[o]);return n}var Xj=["color"],Zj=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,Xj);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.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:r,fillRule:"evenodd",clipRule:"evenodd"}))}),qj=["color"],yT=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,qj);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M11.4669 3.72684C11.7558 3.91574 11.8369 4.30308 11.648 4.59198L7.39799 11.092C7.29783 11.2452 7.13556 11.3467 6.95402 11.3699C6.77247 11.3931 6.58989 11.3355 6.45446 11.2124L3.70446 8.71241C3.44905 8.48022 3.43023 8.08494 3.66242 7.82953C3.89461 7.57412 4.28989 7.55529 4.5453 7.78749L6.75292 9.79441L10.6018 3.90792C10.7907 3.61902 11.178 3.53795 11.4669 3.72684Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),Qj=["color"],Jj=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,Qj);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M3.13523 6.15803C3.3241 5.95657 3.64052 5.94637 3.84197 6.13523L7.5 9.56464L11.158 6.13523C11.3595 5.94637 11.6759 5.95657 11.8648 6.15803C12.0536 6.35949 12.0434 6.67591 11.842 6.86477L7.84197 10.6148C7.64964 10.7951 7.35036 10.7951 7.15803 10.6148L3.15803 6.86477C2.95657 6.67591 2.94637 6.35949 3.13523 6.15803Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),ez=["color"],tz=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,ez);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M6.1584 3.13508C6.35985 2.94621 6.67627 2.95642 6.86514 3.15788L10.6151 7.15788C10.7954 7.3502 10.7954 7.64949 10.6151 7.84182L6.86514 11.8418C6.67627 12.0433 6.35985 12.0535 6.1584 11.8646C5.95694 11.6757 5.94673 11.3593 6.1356 11.1579L9.565 7.49985L6.1356 3.84182C5.94673 3.64036 5.95694 3.32394 6.1584 3.13508Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),nz=["color"],rz=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,nz);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M3.13523 8.84197C3.3241 9.04343 3.64052 9.05363 3.84197 8.86477L7.5 5.43536L11.158 8.86477C11.3595 9.05363 11.6759 9.04343 11.8648 8.84197C12.0536 8.64051 12.0434 8.32409 11.842 8.13523L7.84197 4.38523C7.64964 4.20492 7.35036 4.20492 7.15803 4.38523L3.15803 8.13523C2.95657 8.32409 2.94637 8.64051 3.13523 8.84197Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),oz=["color"],wT=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,oz);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.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:r,fillRule:"evenodd",clipRule:"evenodd"}))}),iz=["color"],sz=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,iz);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M9.875 7.5C9.875 8.81168 8.81168 9.875 7.5 9.875C6.18832 9.875 5.125 8.81168 5.125 7.5C5.125 6.18832 6.18832 5.125 7.5 5.125C8.81168 5.125 9.875 6.18832 9.875 7.5Z",fill:r}))}),az=["color"],lz=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,az);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M10 6.5C10 8.433 8.433 10 6.5 10C4.567 10 3 8.433 3 6.5C3 4.567 4.567 3 6.5 3C8.433 3 10 4.567 10 6.5ZM9.30884 10.0159C8.53901 10.6318 7.56251 11 6.5 11C4.01472 11 2 8.98528 2 6.5C2 4.01472 4.01472 2 6.5 2C8.98528 2 11 4.01472 11 6.5C11 7.56251 10.6318 8.53901 10.0159 9.30884L12.8536 12.1464C13.0488 12.3417 13.0488 12.6583 12.8536 12.8536C12.6583 13.0488 12.3417 13.0488 12.1464 12.8536L9.30884 10.0159Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),cz=["color"],uz=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,cz);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M3.24182 2.32181C3.3919 2.23132 3.5784 2.22601 3.73338 2.30781L12.7334 7.05781C12.8974 7.14436 13 7.31457 13 7.5C13 7.68543 12.8974 7.85564 12.7334 7.94219L3.73338 12.6922C3.5784 12.774 3.3919 12.7687 3.24182 12.6782C3.09175 12.5877 3 12.4252 3 12.25V2.75C3 2.57476 3.09175 2.4123 3.24182 2.32181ZM4 3.57925V11.4207L11.4288 7.5L4 3.57925Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),dz=["color"],fz=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,dz);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M7 2H1.5C1.22386 2 1 2.22386 1 2.5V7H7V2ZM8 2V7H14V2.5C14 2.22386 13.7761 2 13.5 2H8ZM7 8H1V12.5C1 12.7761 1.22386 13 1.5 13H7V8ZM8 13V8H14V12.5C14 12.7761 13.7761 13 13.5 13H8ZM1.5 1C0.671573 1 0 1.67157 0 2.5V12.5C0 13.3284 0.671573 14 1.5 14H13.5C14.3284 14 15 13.3284 15 12.5V2.5C15 1.67157 14.3284 1 13.5 1H1.5Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),hz=["color"],pz=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,hz);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M1.5 2H13.5C13.7761 2 14 2.22386 14 2.5V7H1V2.5C1 2.22386 1.22386 2 1.5 2ZM1 8V12.5C1 12.7761 1.22386 13 1.5 13H13.5C13.7761 13 14 12.7761 14 12.5V8H1ZM0 2.5C0 1.67157 0.671573 1 1.5 1H13.5C14.3284 1 15 1.67157 15 2.5V12.5C15 13.3284 14.3284 14 13.5 14H1.5C0.671573 14 0 13.3284 0 12.5V2.5Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))});function Y(){return Y=Object.assign?Object.assign.bind():function(e){for(var t=1;te.forEach(n=>mz(n,t))}function Ue(...e){return d.useCallback(Nm(...e),e)}const Zo=d.forwardRef((e,t)=>{const{children:n,...r}=e,o=d.Children.toArray(n),i=o.find(gz);if(i){const s=i.props.children,l=o.map(u=>u===i?d.Children.count(s)>1?d.Children.only(null):d.isValidElement(s)?s.props.children:null:u);return d.createElement(t1,Y({},r,{ref:t}),d.isValidElement(s)?d.cloneElement(s,void 0,l):null)}return d.createElement(t1,Y({},r,{ref:t}),n)});Zo.displayName="Slot";const t1=d.forwardRef((e,t)=>{const{children:n,...r}=e;return d.isValidElement(n)?d.cloneElement(n,{...vz(r,n.props),ref:t?Nm(t,n.ref):n.ref}):d.Children.count(n)>1?d.Children.only(null):null});t1.displayName="SlotClone";const lx=({children:e})=>d.createElement(d.Fragment,null,e);function gz(e){return d.isValidElement(e)&&e.type===lx}function vz(e,t){const n={...t};for(const r in t){const o=e[r],i=t[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...l)=>{i(...l),o(...l)}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...e,...n}}const _C=e=>typeof e=="boolean"?"".concat(e):e===0?"0":e,EC=Bk,Dm=(e,t)=>n=>{var r;if((t==null?void 0:t.variants)==null)return EC(e,n==null?void 0:n.class,n==null?void 0:n.className);const{variants:o,defaultVariants:i}=t,s=Object.keys(o).map(f=>{const m=n==null?void 0:n[f],p=i==null?void 0:i[f];if(m===null)return null;const g=_C(m)||_C(p);return o[f][g]}),l=n&&Object.entries(n).reduce((f,m)=>{let[p,g]=m;return g===void 0||(f[p]=g),f},{}),u=t==null||(r=t.compoundVariants)===null||r===void 0?void 0:r.reduce((f,m)=>{let{class:p,className:g,...y}=m;return Object.entries(y).every(x=>{let[S,E]=x;return Array.isArray(E)?E.includes({...i,...l}[S]):{...i,...l}[S]===E})?[...f,p,g]:f},[]);return EC(e,s,u,n==null?void 0:n.class,n==null?void 0:n.className)};var yz={VITE_BACKEND:"http://127.0.0.1:8080",BASE_URL:"/",MODE:"production",DEV:!1,PROD:!0,SSR:!1};function wz(e,t){let n;try{n=e()}catch{return}return{getItem:o=>{var i;const s=u=>u===null?null:JSON.parse(u,t==null?void 0:t.reviver),l=(i=n.getItem(o))!=null?i:null;return l instanceof Promise?l.then(s):s(l)},setItem:(o,i)=>n.setItem(o,JSON.stringify(i,t==null?void 0:t.replacer)),removeItem:o=>n.removeItem(o)}}const od=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then(r){return od(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return od(r)(n)}}}},xz=(e,t)=>(n,r,o)=>{let i={getStorage:()=>localStorage,serialize:JSON.stringify,deserialize:JSON.parse,partialize:E=>E,version:0,merge:(E,_)=>({..._,...E}),...t},s=!1;const l=new Set,u=new Set;let f;try{f=i.getStorage()}catch{}if(!f)return e((...E)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),n(...E)},r,o);const m=od(i.serialize),p=()=>{const E=i.partialize({...r()});let _;const b=m({state:E,version:i.version}).then(C=>f.setItem(i.name,C)).catch(C=>{_=C});if(_)throw _;return b},g=o.setState;o.setState=(E,_)=>{g(E,_),p()};const y=e((...E)=>{n(...E),p()},r,o);let x;const S=()=>{var E;if(!f)return;s=!1,l.forEach(b=>b(r()));const _=((E=i.onRehydrateStorage)==null?void 0:E.call(i,r()))||void 0;return od(f.getItem.bind(f))(i.name).then(b=>{if(b)return i.deserialize(b)}).then(b=>{if(b)if(typeof b.version=="number"&&b.version!==i.version){if(i.migrate)return i.migrate(b.state,b.version);console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return b.state}).then(b=>{var C;return x=i.merge(b,(C=r())!=null?C:y),n(x,!0),p()}).then(()=>{_==null||_(x,void 0),s=!0,u.forEach(b=>b(x))}).catch(b=>{_==null||_(void 0,b)})};return o.persist={setOptions:E=>{i={...i,...E},E.getStorage&&(f=E.getStorage())},clearStorage:()=>{f==null||f.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>S(),hasHydrated:()=>s,onHydrate:E=>(l.add(E),()=>{l.delete(E)}),onFinishHydration:E=>(u.add(E),()=>{u.delete(E)})},S(),x||y},bz=(e,t)=>(n,r,o)=>{let i={storage:wz(()=>localStorage),partialize:S=>S,version:0,merge:(S,E)=>({...E,...S}),...t},s=!1;const l=new Set,u=new Set;let f=i.storage;if(!f)return e((...S)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),n(...S)},r,o);const m=()=>{const S=i.partialize({...r()});return f.setItem(i.name,{state:S,version:i.version})},p=o.setState;o.setState=(S,E)=>{p(S,E),m()};const g=e((...S)=>{n(...S),m()},r,o);let y;const x=()=>{var S,E;if(!f)return;s=!1,l.forEach(b=>{var C;return b((C=r())!=null?C:g)});const _=((E=i.onRehydrateStorage)==null?void 0:E.call(i,(S=r())!=null?S:g))||void 0;return od(f.getItem.bind(f))(i.name).then(b=>{if(b)if(typeof b.version=="number"&&b.version!==i.version){if(i.migrate)return i.migrate(b.state,b.version);console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return b.state}).then(b=>{var C;return y=i.merge(b,(C=r())!=null?C:g),n(y,!0),m()}).then(()=>{_==null||_(y,void 0),y=r(),s=!0,u.forEach(b=>b(y))}).catch(b=>{_==null||_(void 0,b)})};return o.persist={setOptions:S=>{i={...i,...S},S.storage&&(f=S.storage)},clearStorage:()=>{f==null||f.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>x(),hasHydrated:()=>s,onHydrate:S=>(l.add(S),()=>{l.delete(S)}),onFinishHydration:S=>(u.add(S),()=>{u.delete(S)})},i.skipHydration||x(),y||g},Sz=(e,t)=>"getStorage"in t||"serialize"in t||"deserialize"in t?((yz?"production":void 0)!=="production"&&console.warn("[DEPRECATED] `getStorage`, `serialize` and `deserialize` options are deprecated. Use `storage` option instead."),xz(e,t)):bz(e,t),_z=Sz;function Ez(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,o]of e)if(!Object.is(o,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{t(n,r,e)}):e.forEach((n,r)=>t(r,n,e))}function Im(e){const t=e[wr];return t?t.type_:Array.isArray(e)?1:Lm(e)?2:Fm(e)?3:0}function n1(e,t){return Im(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function ST(e,t,n){const r=Im(e);r===2?e.set(t,n):r===3?e.add(n):e[t]=n}function $z(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function Lm(e){return e instanceof Map}function Fm(e){return e instanceof Set}function ra(e){return e.copy_||e.base_}function r1(e,t){if(Lm(e))return new Map(e);if(Fm(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);if(!t&&bT(e))return sc(e)?{...e}:Object.assign(Object.create(null),e);const n=Object.getOwnPropertyDescriptors(e);delete n[wr];let r=Reflect.ownKeys(n);for(let o=0;o1&&(e.set=e.add=e.clear=e.delete=Rz),Object.freeze(e),t&&id(e,(n,r)=>cx(r,!0))),e}function Rz(){po(2)}function jm(e){return Object.isFrozen(e)}var kz={};function Oa(e){const t=kz[e];return t||po(0,e),t}var sd;function _T(){return sd}function Tz(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function $C(e,t){t&&(Oa("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function o1(e){i1(e),e.drafts_.forEach(Pz),e.drafts_=null}function i1(e){e===sd&&(sd=e.parent_)}function RC(e){return sd=Tz(sd,e)}function Pz(e){const t=e[wr];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function kC(e,t){t.unfinalizedDrafts_=t.drafts_.length;const n=t.drafts_[0];return e!==void 0&&e!==n?(n[wr].modified_&&(o1(t),po(4)),Ma(e)&&(e=Np(t,e),t.parent_||Dp(t,e)),t.patches_&&Oa("Patches").generateReplacementPatches_(n[wr].base_,e,t.patches_,t.inversePatches_)):e=Np(t,n,[]),o1(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==xT?e:void 0}function Np(e,t,n){if(jm(t))return t;const r=t[wr];if(!r)return id(t,(o,i)=>TC(e,r,t,o,i,n)),t;if(r.scope_!==e)return t;if(!r.modified_)return Dp(e,r.base_,!0),r.base_;if(!r.finalized_){r.finalized_=!0,r.scope_.unfinalizedDrafts_--;const o=r.copy_;let i=o,s=!1;r.type_===3&&(i=new Set(o),o.clear(),s=!0),id(i,(l,u)=>TC(e,r,o,l,u,n,s)),Dp(e,o,!1),n&&e.patches_&&Oa("Patches").generatePatches_(r,n,e.patches_,e.inversePatches_)}return r.copy_}function TC(e,t,n,r,o,i,s){if(ac(o)){const l=i&&t&&t.type_!==3&&!n1(t.assigned_,r)?i.concat(r):void 0,u=Np(e,o,l);if(ST(n,r,u),ac(u))e.canAutoFreeze_=!1;else return}else s&&n.add(o);if(Ma(o)&&!jm(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;Np(e,o),(!t||!t.scope_.parent_)&&Dp(e,o)}}function Dp(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&cx(t,n)}function Az(e,t){const n=Array.isArray(e),r={type_:n?1:0,scope_:t?t.scope_:_T(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1};let o=r,i=ux;n&&(o=[r],i=ad);const{revoke:s,proxy:l}=Proxy.revocable(o,i);return r.draft_=l,r.revoke_=s,l}var ux={get(e,t){if(t===wr)return e;const n=ra(e);if(!n1(n,t))return Mz(e,n,t);const r=n[t];return e.finalized_||!Ma(r)?r:r===y0(e.base_,t)?(w0(e),e.copy_[t]=a1(r,e)):r},has(e,t){return t in ra(e)},ownKeys(e){return Reflect.ownKeys(ra(e))},set(e,t,n){const r=ET(ra(e),t);if(r!=null&&r.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){const o=y0(ra(e),t),i=o==null?void 0:o[wr];if(i&&i.base_===n)return e.copy_[t]=n,e.assigned_[t]=!1,!0;if($z(n,o)&&(n!==void 0||n1(e.base_,t)))return!0;w0(e),s1(e)}return e.copy_[t]===n&&(n!==void 0||t in e.copy_)||Number.isNaN(n)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=n,e.assigned_[t]=!0),!0},deleteProperty(e,t){return y0(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,w0(e),s1(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){const n=ra(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:r.enumerable,value:n[t]}},defineProperty(){po(11)},getPrototypeOf(e){return sc(e.base_)},setPrototypeOf(){po(12)}},ad={};id(ux,(e,t)=>{ad[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});ad.deleteProperty=function(e,t){return ad.set.call(this,e,t,void 0)};ad.set=function(e,t,n){return ux.set.call(this,e[0],t,n,e[0])};function y0(e,t){const n=e[wr];return(n?ra(n):e)[t]}function Mz(e,t,n){var o;const r=ET(t,n);return r?"value"in r?r.value:(o=r.get)==null?void 0:o.call(e.draft_):void 0}function ET(e,t){if(!(t in e))return;let n=sc(e);for(;n;){const r=Object.getOwnPropertyDescriptor(n,t);if(r)return r;n=sc(n)}}function s1(e){e.modified_||(e.modified_=!0,e.parent_&&s1(e.parent_))}function w0(e){e.copy_||(e.copy_=r1(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var Oz=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(t,n,r)=>{if(typeof t=="function"&&typeof n!="function"){const i=n;n=t;const s=this;return function(u=i,...f){return s.produce(u,m=>n.call(this,m,...f))}}typeof n!="function"&&po(6),r!==void 0&&typeof r!="function"&&po(7);let o;if(Ma(t)){const i=RC(this),s=a1(t,void 0);let l=!0;try{o=n(s),l=!1}finally{l?o1(i):i1(i)}return $C(i,r),kC(o,i)}else if(!t||typeof t!="object"){if(o=n(t),o===void 0&&(o=t),o===xT&&(o=void 0),this.autoFreeze_&&cx(o,!0),r){const i=[],s=[];Oa("Patches").generateReplacementPatches_(t,o,i,s),r(i,s)}return o}else po(1,t)},this.produceWithPatches=(t,n)=>{if(typeof t=="function")return(s,...l)=>this.produceWithPatches(s,u=>t(u,...l));let r,o;return[this.produce(t,n,(s,l)=>{r=s,o=l}),r,o]},typeof(e==null?void 0:e.autoFreeze)=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof(e==null?void 0:e.useStrictShallowCopy)=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){Ma(e)||po(8),ac(e)&&(e=Nz(e));const t=RC(this),n=a1(e,void 0);return n[wr].isManual_=!0,i1(t),n}finishDraft(e,t){const n=e&&e[wr];(!n||!n.isManual_)&&po(9);const{scope_:r}=n;return $C(r,t),kC(void 0,r)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let n;for(n=t.length-1;n>=0;n--){const o=t[n];if(o.path.length===0&&o.op==="replace"){e=o.value;break}}n>-1&&(t=t.slice(n+1));const r=Oa("Patches").applyPatches_;return ac(e)?r(e,t):this.produce(e,o=>r(o,t))}};function a1(e,t){const n=Lm(e)?Oa("MapSet").proxyMap_(e,t):Fm(e)?Oa("MapSet").proxySet_(e,t):Az(e,t);return(t?t.scope_:_T()).drafts_.push(n),n}function Nz(e){return ac(e)||po(10,e),CT(e)}function CT(e){if(!Ma(e)||jm(e))return e;const t=e[wr];let n;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=r1(e,t.scope_.immer_.useStrictShallowCopy_)}else n=r1(e,!0);return id(n,(r,o)=>{ST(n,r,CT(o))}),t&&(t.finalized_=!1),n}var xr=new Oz,Dz=xr.produce;xr.produceWithPatches.bind(xr);xr.setAutoFreeze.bind(xr);xr.setUseStrictShallowCopy.bind(xr);xr.applyPatches.bind(xr);xr.createDraft.bind(xr);xr.finishDraft.bind(xr);const Iz=e=>(t,n,r)=>(r.setState=(o,i,...s)=>{const l=typeof o=="function"?Dz(o):o;return t(l,i,...s)},e(r.setState,n,r)),Lz=Iz;var $T={exports:{}},RT={},kT={exports:{}},TT={};/** + * @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 lc=d;function Fz(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var jz=typeof Object.is=="function"?Object.is:Fz,zz=lc.useState,Bz=lc.useEffect,Uz=lc.useLayoutEffect,Vz=lc.useDebugValue;function Wz(e,t){var n=t(),r=zz({inst:{value:n,getSnapshot:t}}),o=r[0].inst,i=r[1];return Uz(function(){o.value=n,o.getSnapshot=t,x0(o)&&i({inst:o})},[e,n,t]),Bz(function(){return x0(o)&&i({inst:o}),e(function(){x0(o)&&i({inst:o})})},[e]),Vz(n),n}function x0(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!jz(e,n)}catch{return!0}}function Hz(e,t){return t()}var Kz=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?Hz:Wz;TT.useSyncExternalStore=lc.useSyncExternalStore!==void 0?lc.useSyncExternalStore:Kz;kT.exports=TT;var Gz=kT.exports;/** + * @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 zm=d,Yz=Gz;function Xz(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var Zz=typeof Object.is=="function"?Object.is:Xz,qz=Yz.useSyncExternalStore,Qz=zm.useRef,Jz=zm.useEffect,eB=zm.useMemo,tB=zm.useDebugValue;RT.useSyncExternalStoreWithSelector=function(e,t,n,r,o){var i=Qz(null);if(i.current===null){var s={hasValue:!1,value:null};i.current=s}else s=i.current;i=eB(function(){function u(y){if(!f){if(f=!0,m=y,y=r(y),o!==void 0&&s.hasValue){var x=s.value;if(o(x,y))return p=x}return p=y}if(x=p,Zz(m,y))return x;var S=r(y);return o!==void 0&&o(x,S)?x:(m=y,p=S)}var f=!1,m,p,g=n===void 0?null:n;return[function(){return u(t())},g===null?void 0:function(){return u(g())}]},[t,n,r,o]);var l=qz(e,i[0],i[1]);return Jz(function(){s.hasValue=!0,s.value=l},[l]),tB(l),l};$T.exports=RT;var nB=$T.exports;const rB=dm(nB);var oB={VITE_BACKEND:"http://127.0.0.1:8080",BASE_URL:"/",MODE:"production",DEV:!1,PROD:!0,SSR:!1};const PC=e=>{let t;const n=new Set,r=(u,f)=>{const m=typeof u=="function"?u(t):u;if(!Object.is(m,t)){const p=t;t=f??typeof m!="object"?m:Object.assign({},t,m),n.forEach(g=>g(t,p))}},o=()=>t,l={setState:r,getState:o,subscribe:u=>(n.add(u),()=>n.delete(u)),destroy:()=>{(oB?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),n.clear()}};return t=e(r,o,l),l},iB=e=>e?PC(e):PC,{useDebugValue:sB}=je,{useSyncExternalStoreWithSelector:aB}=rB;function lB(e,t=e.getState,n){const r=aB(e.subscribe,e.getState,e.getServerState||e.getState,t,n);return sB(r),r}const AC=(e,t)=>{const n=iB(e),r=(o,i=t)=>lB(n,o,i);return Object.assign(r,n),r},cB=(e,t)=>e?AC(e,t):AC,uB=1,dB=1e6;let b0=0;function fB(){return b0=(b0+1)%Number.MAX_VALUE,b0.toString()}const S0=new Map,MC=e=>{if(S0.has(e))return;const t=setTimeout(()=>{S0.delete(e),Iu({type:"REMOVE_TOAST",toastId:e})},dB);S0.set(e,t)},hB=(e,t)=>{switch(t.type){case"ADD_TOAST":return{...e,toasts:[t.toast,...e.toasts].slice(0,uB)};case"UPDATE_TOAST":return{...e,toasts:e.toasts.map(n=>n.id===t.toast.id?{...n,...t.toast}:n)};case"DISMISS_TOAST":{const{toastId:n}=t;return n?MC(n):e.toasts.forEach(r=>{MC(r.id)}),{...e,toasts:e.toasts.map(r=>r.id===n||n===void 0?{...r,open:!1}:r)}}case"REMOVE_TOAST":return t.toastId===void 0?{...e,toasts:[]}:{...e,toasts:e.toasts.filter(n=>n.id!==t.toastId)}}},Yh=[];let Xh={toasts:[]};function Iu(e){Xh=hB(Xh,e),Yh.forEach(t=>{t(Xh)})}function ul({...e}){const t=fB(),n=o=>Iu({type:"UPDATE_TOAST",toast:{...o,id:t}}),r=()=>Iu({type:"DISMISS_TOAST",toastId:t});return Iu({type:"ADD_TOAST",toast:{...e,id:t,open:!0,onOpenChange:o=>{o||r()}}}),{id:t,dismiss:r,update:n}}function Id(){const[e,t]=d.useState(Xh);return d.useEffect(()=>(Yh.push(t),()=>{const n=Yh.indexOf(t);n>-1&&Yh.splice(n,1)}),[e]),{...e,toast:ul,dismiss:n=>Iu({type:"DISMISS_TOAST",toastId:n})}}const ea={file:null,paintByExampleFile:null,customMask:null,imageHeight:0,imageWidth:0,isInpainting:!1,isPluginRunning:!1,isAdjustingMask:!1,disableShortCuts:!1,windowSize:{height:600,width:800},editorState:{baseBrushSize:cF,brushSizeScale:1,renders:[],extraMasks:[],prevExtraMasks:[],temporaryMasks:[],lineGroups:[],lastLineGroup:[],curLineGroup:[],redoRenders:[],redoCurLines:[],redoLineGroups:[]},interactiveSegState:{isInteractiveSeg:!1,tmpInteractiveSegMask:null,clicks:[]},cropperState:{x:0,y:0,width:512,height:512},extenderState:{x:0,y:0,width:512,height:512},isCropperExtenderResizing:!1,fileManagerState:{sortBy:Es.CTIME,sortOrder:Ou.DESCENDING,layout:"masonry",searchText:"",inputDirectory:"",outputDirectory:""},serverConfig:{plugins:[],modelInfos:[],removeBGModel:"briaai/RMBG-1.4",removeBGModels:[],realesrganModel:"realesr-general-x4v3",realesrganModels:[],interactiveSegModel:"vit_b",interactiveSegModels:[],enableFileManager:!1,enableAutoSaving:!1,enableControlnet:!1,controlnetMethod:"lllyasviel/control_v11p_sd15_canny",disableModelSwitch:!1,isDesktop:!1,samplers:["DPM++ 2M"]},settings:{model:{name:"lama",path:"lama",model_type:"inpaint",support_controlnet:!1,support_strength:!1,support_outpainting:!1,controlnets:[],support_freeu:!1,support_lcm_lora:!1,is_single_file_diffusers:!1,need_prompt:!1},enableControlnet:!1,showCropper:!1,showExtender:!1,extenderDirection:Ln.xy,enableDownloadMask:!1,enableManualInpainting:!1,enableUploadMask:!1,enableAutoExtractPrompt:!0,ldmSteps:30,ldmSampler:Qw.ddim,zitsWireframe:!0,cv2Radius:5,cv2Flag:Jw.INPAINT_NS,prompt:"",negativePrompt:hF,seed:42,seedFixed:!1,sdMaskBlur:12,sdStrength:1,sdSteps:50,sdGuidanceScale:7.5,sdSampler:"DPM++ 2M",sdMatchHistograms:!1,sdScale:1,p2pImageGuidanceScale:1.5,controlnetConditioningScale:.4,controlnetMethod:"lllyasviel/control_v11p_sd15_canny",enableLCMLora:!1,enableFreeu:!1,freeuConfig:{s1:.9,s2:.2,b1:1.2,b2:1.4},powerpaintTask:Ol.text_guided,adjustMaskKernelSize:12}},bt=cB()(_z(Lz((e,t)=>({...ea,showPrevMask:async()=>{if(t().settings.showExtender)return;const{lastLineGroup:n,curLineGroup:r,prevExtraMasks:o,extraMasks:i}=t().editorState;if(r.length!==0||i.length!==0)return;const{imageWidth:s,imageHeight:l}=t(),u=Wh(s,l,[n],o,Xy);try{const f=await cC(u);e(m=>{m.editorState.temporaryMasks.push(f)})}catch(f){console.error(f);return}},hidePrevMask:()=>{e(n=>{n.editorState.temporaryMasks=[]})},getCurrentTargetFile:async()=>{const n=t().file,r=t().editorState.renders;let o=n;if(r.length>0){const i=r[r.length-1];o=await Nu(i.currentSrc,n.name,n.type)}return o},runInpainting:async()=>{const{isInpainting:n,file:r,paintByExampleFile:o,imageWidth:i,imageHeight:s,settings:l,cropperState:u,extenderState:f}=t();if(n||r===null||t().settings.model.support_outpainting&&l.showExtender&&f.height===s&&f.width===i)return;const{lastLineGroup:m,curLineGroup:p,lineGroups:g,renders:y,prevExtraMasks:x,extraMasks:S}=t().editorState,E=p.length===0&&S.length===0&&!l.showExtender;let _=[],b=[];if(E===!0?(b=m,_=x):(b=p,_=S),b.length===0&&_===null&&!l.showExtender){ul({variant:"destructive",description:"Please draw mask on picture"});return}const C=[...g,b];e(O=>{O.isInpainting=!0});let R=r;if(E===!0){if(y.length>1){const O=y[y.length-2];R=await Nu(O.currentSrc,r.name,r.type)}}else if(y.length>0){const O=y[y.length-1];R=await Nu(O.currentSrc,r.name,r.type)}const P=Wh(i,s,[b],_);if(E){const O=await cC(P);e(A=>{A.editorState.temporaryMasks=[O]})}try{const O=await zj(R,l,u,f,lC(P.toDataURL()),o),{blob:A,seed:D}=O;D&&t().setSeed(parseInt(D,10));const B=new Image;await Vh(B,A);const V=[...y,B];t().setImageSize(B.width,B.height),t().updateEditorState({renders:V,lineGroups:C,lastLineGroup:b,curLineGroup:[],extraMasks:[],prevExtraMasks:_})}catch(O){ul({variant:"destructive",description:O.message?O.message:O.toString()})}t().resetRedoState(),e(O=>{O.isInpainting=!1,O.editorState.temporaryMasks=[]})},runRenderablePlugin:async(n,r,o={upscale:1})=>{const{renders:i,lineGroups:s}=t().editorState;e(l=>{l.isPluginRunning=!0});try{const l=new Date,u=await t().getCurrentTargetFile(),f=await vT(n,r,u,o.upscale),{blob:m}=f;if(n){const y=new Image;await Vh(y,m),e(x=>{x.editorState.extraMasks.push(y)})}else{const y=new Image;await Vh(y,m),t().setImageSize(y.width,y.height);const x=[...i,y],S=[...s,[]];t().updateEditorState({renders:x,lineGroups:S})}const g=new Date().getTime()-l.getTime();ul({description:`Run ${r} successfully in ${g/1e3}s`})}catch(l){ul({variant:"destructive",description:l.message?l.message:l.toString()})}e(l=>{l.isPluginRunning=!1})},updateEditorState:n=>{e(r=>{r.editorState={...r.editorState,...n}})},cleanCurLineGroup:()=>{t().updateEditorState({curLineGroup:[]})},handleCanvasMouseDown:n=>{let r=[];const o=t();o.runMannually()&&(r=[...o.editorState.curLineGroup]),r.push({size:o.getBrushSize(),pts:[n]}),e(i=>{i.editorState.curLineGroup=r})},handleCanvasMouseMove:n=>{e(r=>{const o=r.editorState.curLineGroup;o.length&&o[o.length-1].pts.push(n)})},runMannually:()=>{const n=t();return n.settings.enableManualInpainting||n.settings.model.model_type!==fs},getIsProcessing:()=>t().isInpainting||t().isPluginRunning||t().isAdjustingMask,isSD:()=>t().settings.model.model_type!==fs,undoDisabled:()=>{const n=t().editorState;if(n.renders.length>0)return!1;if(t().runMannually()){if(n.curLineGroup.length===0)return!0}else if(n.renders.length===0)return!0;return!1},undo:()=>{t().runMannually()&&t().editorState.curLineGroup.length!==0?e(n=>{const r=n.editorState;if(r.curLineGroup.length===0)return;r.lastLineGroup=[];const o=r.curLineGroup.pop();r.redoCurLines.push(o)}):e(n=>{const r=n.editorState;if(r.renders.length===0||r.lineGroups.length===0)return;const o=r.lineGroups.pop();r.redoLineGroups.push(o),r.redoCurLines=[],r.curLineGroup=[];const i=r.renders.pop();r.redoRenders.push(i)})},redoDisabled:()=>{const n=t().editorState;if(n.redoRenders.length>0)return!1;if(t().runMannually()){if(n.redoCurLines.length===0)return!0}else if(n.redoRenders.length===0)return!0;return!1},redo:()=>{t().runMannually()&&t().editorState.redoCurLines.length!==0?e(n=>{const r=n.editorState;if(r.redoCurLines.length===0)return;const o=r.redoCurLines.pop();r.curLineGroup.push(o)}):e(n=>{const r=n.editorState;if(r.redoRenders.length===0||r.redoLineGroups.length===0)return;const o=r.redoLineGroups.pop();r.lineGroups.push(o),r.curLineGroup=[];const i=r.redoRenders.pop();r.renders.push(i)})},resetRedoState:()=>{e(n=>{n.editorState.redoCurLines=[],n.editorState.redoLineGroups=[],n.editorState.redoRenders=[]})},updateAppState:n=>{e(()=>n)},getBrushSize:()=>t().editorState.baseBrushSize*t().editorState.brushSizeScale,showPromptInput:()=>{const n=t().settings.model;return n.model_type!==fs&&n.name!==Gk},setServerConfig:n=>{e(r=>{r.serverConfig=n,r.settings.enableControlnet=n.enableControlnet,r.settings.controlnetMethod=n.controlnetMethod})},updateSettings:n=>{e(r=>{r.settings={...r.settings,...n}})},setModel:n=>{e(r=>{r.settings.model=n,n.support_controlnet&&!n.controlnets.includes(r.settings.controlnetMethod)&&(r.settings.controlnetMethod=n.controlnets[0])})},updateFileManagerState:n=>{e(r=>{r.fileManagerState={...r.fileManagerState,...n}})},updateInteractiveSegState:n=>{e(r=>({...r,interactiveSegState:{...r.interactiveSegState,...n}}))},resetInteractiveSegState:()=>{t().updateInteractiveSegState(ea.interactiveSegState)},handleInteractiveSegAccept:()=>{e(n=>{n.interactiveSegState.tmpInteractiveSegMask&&n.editorState.extraMasks.push(n.interactiveSegState.tmpInteractiveSegMask),n.interactiveSegState={...ea.interactiveSegState}})},setIsInpainting:n=>e(r=>{r.isInpainting=n}),setFile:async n=>{if(t().settings.enableAutoExtractPrompt)try{const r=await Kj(n);r.prompt&&e(o=>{o.settings.prompt=r.prompt}),r.negative_prompt&&e(o=>{o.settings.negativePrompt=r.negative_prompt})}catch(r){ul({variant:"destructive",description:r.message?r.message:r.toString()})}e(r=>{r.file=n,r.interactiveSegState=ea.interactiveSegState,r.editorState=ea.editorState,r.cropperState=ea.cropperState})},setCustomFile:n=>e(r=>{r.customMask=n}),setBaseBrushSize:n=>e(r=>{r.editorState.baseBrushSize=n}),setImageSize:(n,r)=>{e(o=>{o.imageWidth=n,o.imageHeight=r,o.editorState.brushSizeScale=Math.max(Math.min(n,r),512)/512}),t().resetExtender(n,r)},setCropperX:n=>e(r=>{r.cropperState.x=n}),setCropperY:n=>e(r=>{r.cropperState.y=n}),setCropperWidth:n=>e(r=>{r.cropperState.width=n}),setCropperHeight:n=>e(r=>{r.cropperState.height=n}),setExtenderX:n=>e(r=>{r.extenderState.x=n}),setExtenderY:n=>e(r=>{r.extenderState.y=n}),setExtenderWidth:n=>e(r=>{r.extenderState.width=n}),setExtenderHeight:n=>e(r=>{r.extenderState.height=n}),setIsCropperExtenderResizing:n=>e(r=>{r.isCropperExtenderResizing=n}),updateExtenderDirection:n=>{console.log(`updateExtenderDirection: ${JSON.stringify(t().extenderState)}`),e(r=>{r.settings.extenderDirection=n,r.extenderState.x=0,r.extenderState.y=0,r.extenderState.width=r.imageWidth,r.extenderState.height=r.imageHeight}),t().updateExtenderByBuiltIn(n,1.5)},updateExtenderByBuiltIn:(n,r)=>{const o={...ea.extenderState};let{x:i,y:s,width:l,height:u}=o;const{imageWidth:f,imageHeight:m}=t();switch(l=f,u=m,n){case Ln.x:i=-Math.ceil(f*(r-1)/2),l=Math.ceil(f*r);break;case Ln.y:s=-Math.ceil(m*(r-1)/2),u=Math.ceil(m*r);break;case Ln.xy:i=-Math.ceil(f*(r-1)/2),s=-Math.ceil(m*(r-1)/2),l=Math.ceil(f*r),u=Math.ceil(m*r);break}e(p=>{p.extenderState.x=i,p.extenderState.y=s,p.extenderState.width=l,p.extenderState.height=u})},resetExtender:(n,r)=>{e(o=>{o.extenderState.x=0,o.extenderState.y=0,o.extenderState.width=n,o.extenderState.height=r})},setSeed:n=>e(r=>{r.settings.seed=n}),adjustMask:async n=>{const{imageWidth:r,imageHeight:o}=t(),{curLineGroup:i,extraMasks:s}=t().editorState,{adjustMaskKernelSize:l}=t().settings;if(i.length===0&&s.length===0)return;e(g=>{g.isAdjustingMask=!0});const u=Wh(r,o,[i],s,Xy),f=lC(u.toDataURL()),m=await Gj(f,n,l),p=await mF(m);e(g=>{g.editorState.extraMasks=[p],g.editorState.curLineGroup=[]}),e(g=>{g.isAdjustingMask=!1})},clearMask:()=>{e(n=>{n.editorState.extraMasks=[],n.editorState.curLineGroup=[]})}})),{name:"ZUSTAND_STATE",version:1,partialize:e=>Object.fromEntries(Object.entries(e).filter(([t])=>["fileManagerState","settings"].includes(t)))}),Ez),Ld=d.forwardRef(({className:e,type:t,...n},r)=>{const o=bt(l=>l.updateAppState),i=()=>{o({disableShortCuts:!0})},s=()=>{o({disableShortCuts:!1})};return v.jsx("input",{type:t,className:Ce("flex h-8 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",e),ref:r,autoComplete:"off",tabIndex:-1,onFocus:i,onBlur:s,...n})});Ld.displayName="Input";const Yn=d.forwardRef(({numberValue:e,allowFloat:t,onNumberValueChange:n,...r},o)=>{const[i,s]=d.useState(e.toString());d.useEffect(()=>{i!==e.toString()+"."&&s(e.toString())},[e]);const l=u=>{let m=u.target.value;if(t){if(m=m.replace(/[^0-9.]/g,"").replace(/(\..*?)\..*/g,"$1"),m.length===0){n(0);return}n(parseFloat(m))}else{if(m=m.replace(/\D/g,""),m.length===0){n(0);return}n(parseInt(m,10))}s(m)};return v.jsx(Ld,{ref:o,value:i,onInput:l,...r})});function ue(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 pB(e,t){const n=d.createContext(t);function r(i){const{children:s,...l}=i,u=d.useMemo(()=>l,Object.values(l));return d.createElement(n.Provider,{value:u},s)}function o(i){const s=d.useContext(n);if(s)return s;if(t!==void 0)return t;throw new Error(`\`${i}\` must be used within \`${e}\``)}return r.displayName=e+"Provider",[r,o]}function Mn(e,t=[]){let n=[];function r(i,s){const l=d.createContext(s),u=n.length;n=[...n,s];function f(p){const{scope:g,children:y,...x}=p,S=(g==null?void 0:g[e][u])||l,E=d.useMemo(()=>x,Object.values(x));return d.createElement(S.Provider,{value:E},y)}function m(p,g){const y=(g==null?void 0:g[e][u])||l,x=d.useContext(y);if(x)return x;if(s!==void 0)return s;throw new Error(`\`${p}\` must be used within \`${i}\``)}return f.displayName=i+"Provider",[f,m]}const o=()=>{const i=n.map(s=>d.createContext(s));return function(l){const u=(l==null?void 0:l[e])||i;return d.useMemo(()=>({[`__scope${e}`]:{...l,[e]:u}}),[l,u])}};return o.scopeName=e,[r,mB(o,...t)]}function mB(...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(i){const s=r.reduce((l,{useScope:u,scopeName:f})=>{const p=u(i)[`__scope${f}`];return{...l,...p}},{});return d.useMemo(()=>({[`__scope${t.scopeName}`]:s}),[s])}};return n.scopeName=t.scopeName,n}const gB=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","span","svg","ul"],Ae=gB.reduce((e,t)=>{const n=d.forwardRef((r,o)=>{const{asChild:i,...s}=r,l=i?Zo:t;return d.useEffect(()=>{window[Symbol.for("radix-ui")]=!0},[]),d.createElement(l,Y({},s,{ref:o}))});return n.displayName=`Primitive.${t}`,{...e,[t]:n}},{});function dx(e,t){e&&Is.flushSync(()=>e.dispatchEvent(t))}function Ft(e){const t=d.useRef(e);return d.useEffect(()=>{t.current=e}),d.useMemo(()=>(...n)=>{var r;return(r=t.current)===null||r===void 0?void 0:r.call(t,...n)},[])}function vB(e,t=globalThis==null?void 0:globalThis.document){const n=Ft(e);d.useEffect(()=>{const r=o=>{o.key==="Escape"&&n(o)};return t.addEventListener("keydown",r),()=>t.removeEventListener("keydown",r)},[n,t])}const l1="dismissableLayer.update",yB="dismissableLayer.pointerDownOutside",wB="dismissableLayer.focusOutside";let OC;const PT=d.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),Ec=d.forwardRef((e,t)=>{var n;const{disableOutsidePointerEvents:r=!1,onEscapeKeyDown:o,onPointerDownOutside:i,onFocusOutside:s,onInteractOutside:l,onDismiss:u,...f}=e,m=d.useContext(PT),[p,g]=d.useState(null),y=(n=p==null?void 0:p.ownerDocument)!==null&&n!==void 0?n:globalThis==null?void 0:globalThis.document,[,x]=d.useState({}),S=Ue(t,D=>g(D)),E=Array.from(m.layers),[_]=[...m.layersWithOutsidePointerEventsDisabled].slice(-1),b=E.indexOf(_),C=p?E.indexOf(p):-1,R=m.layersWithOutsidePointerEventsDisabled.size>0,P=C>=b,O=bB(D=>{const B=D.target,V=[...m.branches].some(J=>J.contains(B));!P||V||(i==null||i(D),l==null||l(D),D.defaultPrevented||u==null||u())},y),A=SB(D=>{const B=D.target;[...m.branches].some(J=>J.contains(B))||(s==null||s(D),l==null||l(D),D.defaultPrevented||u==null||u())},y);return vB(D=>{C===m.layers.size-1&&(o==null||o(D),!D.defaultPrevented&&u&&(D.preventDefault(),u()))},y),d.useEffect(()=>{if(p)return r&&(m.layersWithOutsidePointerEventsDisabled.size===0&&(OC=y.body.style.pointerEvents,y.body.style.pointerEvents="none"),m.layersWithOutsidePointerEventsDisabled.add(p)),m.layers.add(p),NC(),()=>{r&&m.layersWithOutsidePointerEventsDisabled.size===1&&(y.body.style.pointerEvents=OC)}},[p,y,r,m]),d.useEffect(()=>()=>{p&&(m.layers.delete(p),m.layersWithOutsidePointerEventsDisabled.delete(p),NC())},[p,m]),d.useEffect(()=>{const D=()=>x({});return document.addEventListener(l1,D),()=>document.removeEventListener(l1,D)},[]),d.createElement(Ae.div,Y({},f,{ref:S,style:{pointerEvents:R?P?"auto":"none":void 0,...e.style},onFocusCapture:ue(e.onFocusCapture,A.onFocusCapture),onBlurCapture:ue(e.onBlurCapture,A.onBlurCapture),onPointerDownCapture:ue(e.onPointerDownCapture,O.onPointerDownCapture)}))}),xB=d.forwardRef((e,t)=>{const n=d.useContext(PT),r=d.useRef(null),o=Ue(t,r);return d.useEffect(()=>{const i=r.current;if(i)return n.branches.add(i),()=>{n.branches.delete(i)}},[n.branches]),d.createElement(Ae.div,Y({},e,{ref:o}))});function bB(e,t=globalThis==null?void 0:globalThis.document){const n=Ft(e),r=d.useRef(!1),o=d.useRef(()=>{});return d.useEffect(()=>{const i=l=>{if(l.target&&!r.current){let m=function(){AT(yB,n,f,{discrete:!0})};var u=m;const f={originalEvent:l};l.pointerType==="touch"?(t.removeEventListener("click",o.current),o.current=m,t.addEventListener("click",o.current,{once:!0})):m()}else t.removeEventListener("click",o.current);r.current=!1},s=window.setTimeout(()=>{t.addEventListener("pointerdown",i)},0);return()=>{window.clearTimeout(s),t.removeEventListener("pointerdown",i),t.removeEventListener("click",o.current)}},[t,n]),{onPointerDownCapture:()=>r.current=!0}}function SB(e,t=globalThis==null?void 0:globalThis.document){const n=Ft(e),r=d.useRef(!1);return d.useEffect(()=>{const o=i=>{i.target&&!r.current&&AT(wB,n,{originalEvent:i},{discrete:!1})};return t.addEventListener("focusin",o),()=>t.removeEventListener("focusin",o)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function NC(){const e=new CustomEvent(l1);document.dispatchEvent(e)}function AT(e,t,n,{discrete:r}){const o=n.originalEvent.target,i=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&o.addEventListener(e,t,{once:!0}),r?dx(o,i):o.dispatchEvent(i)}const _B=Ec,EB=xB,An=globalThis!=null&&globalThis.document?d.useLayoutEffect:()=>{},CB=UD.useId||(()=>{});let $B=0;function nr(e){const[t,n]=d.useState(CB());return An(()=>{e||n(r=>r??String($B++))},[e]),e||(t?`radix-${t}`:"")}const RB=["top","right","bottom","left"],Ts=Math.min,hr=Math.max,Ip=Math.round,fh=Math.floor,Ps=e=>({x:e,y:e}),kB={left:"right",right:"left",bottom:"top",top:"bottom"},TB={start:"end",end:"start"};function c1(e,t,n){return hr(e,Ts(t,n))}function Ci(e,t){return typeof e=="function"?e(t):e}function $i(e){return e.split("-")[0]}function Cc(e){return e.split("-")[1]}function fx(e){return e==="x"?"y":"x"}function hx(e){return e==="y"?"height":"width"}function $c(e){return["top","bottom"].includes($i(e))?"y":"x"}function px(e){return fx($c(e))}function PB(e,t,n){n===void 0&&(n=!1);const r=Cc(e),o=px(e),i=hx(o);let s=o==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[i]>t.floating[i]&&(s=Lp(s)),[s,Lp(s)]}function AB(e){const t=Lp(e);return[u1(e),t,u1(t)]}function u1(e){return e.replace(/start|end/g,t=>TB[t])}function MB(e,t,n){const r=["left","right"],o=["right","left"],i=["top","bottom"],s=["bottom","top"];switch(e){case"top":case"bottom":return n?t?o:r:t?r:o;case"left":case"right":return t?i:s;default:return[]}}function OB(e,t,n,r){const o=Cc(e);let i=MB($i(e),n==="start",r);return o&&(i=i.map(s=>s+"-"+o),t&&(i=i.concat(i.map(u1)))),i}function Lp(e){return e.replace(/left|right|bottom|top/g,t=>kB[t])}function NB(e){return{top:0,right:0,bottom:0,left:0,...e}}function MT(e){return typeof e!="number"?NB(e):{top:e,right:e,bottom:e,left:e}}function Fp(e){return{...e,top:e.y,left:e.x,right:e.x+e.width,bottom:e.y+e.height}}function DC(e,t,n){let{reference:r,floating:o}=e;const i=$c(t),s=px(t),l=hx(s),u=$i(t),f=i==="y",m=r.x+r.width/2-o.width/2,p=r.y+r.height/2-o.height/2,g=r[l]/2-o[l]/2;let y;switch(u){case"top":y={x:m,y:r.y-o.height};break;case"bottom":y={x:m,y:r.y+r.height};break;case"right":y={x:r.x+r.width,y:p};break;case"left":y={x:r.x-o.width,y:p};break;default:y={x:r.x,y:r.y}}switch(Cc(t)){case"start":y[s]-=g*(n&&f?-1:1);break;case"end":y[s]+=g*(n&&f?-1:1);break}return y}const DB=async(e,t,n)=>{const{placement:r="bottom",strategy:o="absolute",middleware:i=[],platform:s}=n,l=i.filter(Boolean),u=await(s.isRTL==null?void 0:s.isRTL(t));let f=await s.getElementRects({reference:e,floating:t,strategy:o}),{x:m,y:p}=DC(f,r,u),g=r,y={},x=0;for(let S=0;S({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:o,rects:i,platform:s,elements:l,middlewareData:u}=t,{element:f,padding:m=0}=Ci(e,t)||{};if(f==null)return{};const p=MT(m),g={x:n,y:r},y=px(o),x=hx(y),S=await s.getDimensions(f),E=y==="y",_=E?"top":"left",b=E?"bottom":"right",C=E?"clientHeight":"clientWidth",R=i.reference[x]+i.reference[y]-g[y]-i.floating[x],P=g[y]-i.reference[y],O=await(s.getOffsetParent==null?void 0:s.getOffsetParent(f));let A=O?O[C]:0;(!A||!await(s.isElement==null?void 0:s.isElement(O)))&&(A=l.floating[C]||i.floating[x]);const D=R/2-P/2,B=A/2-S[x]/2-1,V=Ts(p[_],B),J=Ts(p[b],B),G=V,se=A-S[x]-J,U=A/2-S[x]/2+D,ne=c1(G,U,se),M=!u.arrow&&Cc(o)!=null&&U!=ne&&i.reference[x]/2-(UG<=0)){var B,V;const G=(((B=i.flip)==null?void 0:B.index)||0)+1,se=P[G];if(se)return{data:{index:G,overflows:D},reset:{placement:se}};let U=(V=D.filter(ne=>ne.overflows[0]<=0).sort((ne,M)=>ne.overflows[1]-M.overflows[1])[0])==null?void 0:V.placement;if(!U)switch(y){case"bestFit":{var J;const ne=(J=D.map(M=>[M.placement,M.overflows.filter(ee=>ee>0).reduce((ee,H)=>ee+H,0)]).sort((M,ee)=>M[1]-ee[1])[0])==null?void 0:J[0];ne&&(U=ne);break}case"initialPlacement":U=l;break}if(o!==U)return{reset:{placement:U}}}return{}}}};function LC(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function FC(e){return RB.some(t=>e[t]>=0)}const LB=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n}=t,{strategy:r="referenceHidden",...o}=Ci(e,t);switch(r){case"referenceHidden":{const i=await ld(t,{...o,elementContext:"reference"}),s=LC(i,n.reference);return{data:{referenceHiddenOffsets:s,referenceHidden:FC(s)}}}case"escaped":{const i=await ld(t,{...o,altBoundary:!0}),s=LC(i,n.floating);return{data:{escapedOffsets:s,escaped:FC(s)}}}default:return{}}}}};async function FB(e,t){const{placement:n,platform:r,elements:o}=e,i=await(r.isRTL==null?void 0:r.isRTL(o.floating)),s=$i(n),l=Cc(n),u=$c(n)==="y",f=["left","top"].includes(s)?-1:1,m=i&&u?-1:1,p=Ci(t,e);let{mainAxis:g,crossAxis:y,alignmentAxis:x}=typeof p=="number"?{mainAxis:p,crossAxis:0,alignmentAxis:null}:{mainAxis:0,crossAxis:0,alignmentAxis:null,...p};return l&&typeof x=="number"&&(y=l==="end"?x*-1:x),u?{x:y*m,y:g*f}:{x:g*f,y:y*m}}const jB=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){const{x:n,y:r}=t,o=await FB(t,e);return{x:n+o.x,y:r+o.y,data:o}}}},zB=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:o}=t,{mainAxis:i=!0,crossAxis:s=!1,limiter:l={fn:E=>{let{x:_,y:b}=E;return{x:_,y:b}}},...u}=Ci(e,t),f={x:n,y:r},m=await ld(t,u),p=$c($i(o)),g=fx(p);let y=f[g],x=f[p];if(i){const E=g==="y"?"top":"left",_=g==="y"?"bottom":"right",b=y+m[E],C=y-m[_];y=c1(b,y,C)}if(s){const E=p==="y"?"top":"left",_=p==="y"?"bottom":"right",b=x+m[E],C=x-m[_];x=c1(b,x,C)}const S=l.fn({...t,[g]:y,[p]:x});return{...S,data:{x:S.x-n,y:S.y-r}}}}},BB=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:r,placement:o,rects:i,middlewareData:s}=t,{offset:l=0,mainAxis:u=!0,crossAxis:f=!0}=Ci(e,t),m={x:n,y:r},p=$c(o),g=fx(p);let y=m[g],x=m[p];const S=Ci(l,t),E=typeof S=="number"?{mainAxis:S,crossAxis:0}:{mainAxis:0,crossAxis:0,...S};if(u){const C=g==="y"?"height":"width",R=i.reference[g]-i.floating[C]+E.mainAxis,P=i.reference[g]+i.reference[C]-E.mainAxis;yP&&(y=P)}if(f){var _,b;const C=g==="y"?"width":"height",R=["top","left"].includes($i(o)),P=i.reference[p]-i.floating[C]+(R&&((_=s.offset)==null?void 0:_[p])||0)+(R?0:E.crossAxis),O=i.reference[p]+i.reference[C]+(R?0:((b=s.offset)==null?void 0:b[p])||0)-(R?E.crossAxis:0);xO&&(x=O)}return{[g]:y,[p]:x}}}},UB=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){const{placement:n,rects:r,platform:o,elements:i}=t,{apply:s=()=>{},...l}=Ci(e,t),u=await ld(t,l),f=$i(n),m=Cc(n),p=$c(n)==="y",{width:g,height:y}=r.floating;let x,S;f==="top"||f==="bottom"?(x=f,S=m===(await(o.isRTL==null?void 0:o.isRTL(i.floating))?"start":"end")?"left":"right"):(S=f,x=m==="end"?"top":"bottom");const E=y-u[x],_=g-u[S],b=!t.middlewareData.shift;let C=E,R=_;if(p){const O=g-u.left-u.right;R=m||b?Ts(_,O):O}else{const O=y-u.top-u.bottom;C=m||b?Ts(E,O):O}if(b&&!m){const O=hr(u.left,0),A=hr(u.right,0),D=hr(u.top,0),B=hr(u.bottom,0);p?R=g-2*(O!==0||A!==0?O+A:hr(u.left,u.right)):C=y-2*(D!==0||B!==0?D+B:hr(u.top,u.bottom))}await s({...t,availableWidth:R,availableHeight:C});const P=await o.getDimensions(i.floating);return g!==P.width||y!==P.height?{reset:{rects:!0}}:{}}}};function As(e){return OT(e)?(e.nodeName||"").toLowerCase():"#document"}function vr(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Mi(e){var t;return(t=(OT(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function OT(e){return e instanceof Node||e instanceof vr(e).Node}function Ri(e){return e instanceof Element||e instanceof vr(e).Element}function qo(e){return e instanceof HTMLElement||e instanceof vr(e).HTMLElement}function jC(e){return typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof vr(e).ShadowRoot}function Fd(e){const{overflow:t,overflowX:n,overflowY:r,display:o}=Xr(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&!["inline","contents"].includes(o)}function VB(e){return["table","td","th"].includes(As(e))}function mx(e){const t=gx(),n=Xr(e);return n.transform!=="none"||n.perspective!=="none"||(n.containerType?n.containerType!=="normal":!1)||!t&&(n.backdropFilter?n.backdropFilter!=="none":!1)||!t&&(n.filter?n.filter!=="none":!1)||["transform","perspective","filter"].some(r=>(n.willChange||"").includes(r))||["paint","layout","strict","content"].some(r=>(n.contain||"").includes(r))}function WB(e){let t=cc(e);for(;qo(t)&&!Bm(t);){if(mx(t))return t;t=cc(t)}return null}function gx(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}function Bm(e){return["html","body","#document"].includes(As(e))}function Xr(e){return vr(e).getComputedStyle(e)}function Um(e){return Ri(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.pageXOffset,scrollTop:e.pageYOffset}}function cc(e){if(As(e)==="html")return e;const t=e.assignedSlot||e.parentNode||jC(e)&&e.host||Mi(e);return jC(t)?t.host:t}function NT(e){const t=cc(e);return Bm(t)?e.ownerDocument?e.ownerDocument.body:e.body:qo(t)&&Fd(t)?t:NT(t)}function cd(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const o=NT(e),i=o===((r=e.ownerDocument)==null?void 0:r.body),s=vr(o);return i?t.concat(s,s.visualViewport||[],Fd(o)?o:[],s.frameElement&&n?cd(s.frameElement):[]):t.concat(o,cd(o,[],n))}function DT(e){const t=Xr(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const o=qo(e),i=o?e.offsetWidth:n,s=o?e.offsetHeight:r,l=Ip(n)!==i||Ip(r)!==s;return l&&(n=i,r=s),{width:n,height:r,$:l}}function vx(e){return Ri(e)?e:e.contextElement}function Nl(e){const t=vx(e);if(!qo(t))return Ps(1);const n=t.getBoundingClientRect(),{width:r,height:o,$:i}=DT(t);let s=(i?Ip(n.width):n.width)/r,l=(i?Ip(n.height):n.height)/o;return(!s||!Number.isFinite(s))&&(s=1),(!l||!Number.isFinite(l))&&(l=1),{x:s,y:l}}const HB=Ps(0);function IT(e){const t=vr(e);return!gx()||!t.visualViewport?HB:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function KB(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==vr(e)?!1:t}function Na(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const o=e.getBoundingClientRect(),i=vx(e);let s=Ps(1);t&&(r?Ri(r)&&(s=Nl(r)):s=Nl(e));const l=KB(i,n,r)?IT(i):Ps(0);let u=(o.left+l.x)/s.x,f=(o.top+l.y)/s.y,m=o.width/s.x,p=o.height/s.y;if(i){const g=vr(i),y=r&&Ri(r)?vr(r):r;let x=g.frameElement;for(;x&&r&&y!==g;){const S=Nl(x),E=x.getBoundingClientRect(),_=Xr(x),b=E.left+(x.clientLeft+parseFloat(_.paddingLeft))*S.x,C=E.top+(x.clientTop+parseFloat(_.paddingTop))*S.y;u*=S.x,f*=S.y,m*=S.x,p*=S.y,u+=b,f+=C,x=vr(x).frameElement}}return Fp({width:m,height:p,x:u,y:f})}function GB(e){let{rect:t,offsetParent:n,strategy:r}=e;const o=qo(n),i=Mi(n);if(n===i)return t;let s={scrollLeft:0,scrollTop:0},l=Ps(1);const u=Ps(0);if((o||!o&&r!=="fixed")&&((As(n)!=="body"||Fd(i))&&(s=Um(n)),qo(n))){const f=Na(n);l=Nl(n),u.x=f.x+n.clientLeft,u.y=f.y+n.clientTop}return{width:t.width*l.x,height:t.height*l.y,x:t.x*l.x-s.scrollLeft*l.x+u.x,y:t.y*l.y-s.scrollTop*l.y+u.y}}function YB(e){return Array.from(e.getClientRects())}function LT(e){return Na(Mi(e)).left+Um(e).scrollLeft}function XB(e){const t=Mi(e),n=Um(e),r=e.ownerDocument.body,o=hr(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),i=hr(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let s=-n.scrollLeft+LT(e);const l=-n.scrollTop;return Xr(r).direction==="rtl"&&(s+=hr(t.clientWidth,r.clientWidth)-o),{width:o,height:i,x:s,y:l}}function ZB(e,t){const n=vr(e),r=Mi(e),o=n.visualViewport;let i=r.clientWidth,s=r.clientHeight,l=0,u=0;if(o){i=o.width,s=o.height;const f=gx();(!f||f&&t==="fixed")&&(l=o.offsetLeft,u=o.offsetTop)}return{width:i,height:s,x:l,y:u}}function qB(e,t){const n=Na(e,!0,t==="fixed"),r=n.top+e.clientTop,o=n.left+e.clientLeft,i=qo(e)?Nl(e):Ps(1),s=e.clientWidth*i.x,l=e.clientHeight*i.y,u=o*i.x,f=r*i.y;return{width:s,height:l,x:u,y:f}}function zC(e,t,n){let r;if(t==="viewport")r=ZB(e,n);else if(t==="document")r=XB(Mi(e));else if(Ri(t))r=qB(t,n);else{const o=IT(e);r={...t,x:t.x-o.x,y:t.y-o.y}}return Fp(r)}function FT(e,t){const n=cc(e);return n===t||!Ri(n)||Bm(n)?!1:Xr(n).position==="fixed"||FT(n,t)}function QB(e,t){const n=t.get(e);if(n)return n;let r=cd(e,[],!1).filter(l=>Ri(l)&&As(l)!=="body"),o=null;const i=Xr(e).position==="fixed";let s=i?cc(e):e;for(;Ri(s)&&!Bm(s);){const l=Xr(s),u=mx(s);!u&&l.position==="fixed"&&(o=null),(i?!u&&!o:!u&&l.position==="static"&&!!o&&["absolute","fixed"].includes(o.position)||Fd(s)&&!u&&FT(e,s))?r=r.filter(m=>m!==s):o=l,s=cc(s)}return t.set(e,r),r}function JB(e){let{element:t,boundary:n,rootBoundary:r,strategy:o}=e;const s=[...n==="clippingAncestors"?QB(t,this._c):[].concat(n),r],l=s[0],u=s.reduce((f,m)=>{const p=zC(t,m,o);return f.top=hr(p.top,f.top),f.right=Ts(p.right,f.right),f.bottom=Ts(p.bottom,f.bottom),f.left=hr(p.left,f.left),f},zC(t,l,o));return{width:u.right-u.left,height:u.bottom-u.top,x:u.left,y:u.top}}function eU(e){return DT(e)}function tU(e,t,n){const r=qo(t),o=Mi(t),i=n==="fixed",s=Na(e,!0,i,t);let l={scrollLeft:0,scrollTop:0};const u=Ps(0);if(r||!r&&!i)if((As(t)!=="body"||Fd(o))&&(l=Um(t)),r){const f=Na(t,!0,i,t);u.x=f.x+t.clientLeft,u.y=f.y+t.clientTop}else o&&(u.x=LT(o));return{x:s.left+l.scrollLeft-u.x,y:s.top+l.scrollTop-u.y,width:s.width,height:s.height}}function BC(e,t){return!qo(e)||Xr(e).position==="fixed"?null:t?t(e):e.offsetParent}function jT(e,t){const n=vr(e);if(!qo(e))return n;let r=BC(e,t);for(;r&&VB(r)&&Xr(r).position==="static";)r=BC(r,t);return r&&(As(r)==="html"||As(r)==="body"&&Xr(r).position==="static"&&!mx(r))?n:r||WB(e)||n}const nU=async function(e){let{reference:t,floating:n,strategy:r}=e;const o=this.getOffsetParent||jT,i=this.getDimensions;return{reference:tU(t,await o(n),r),floating:{x:0,y:0,...await i(n)}}};function rU(e){return Xr(e).direction==="rtl"}const oU={convertOffsetParentRelativeRectToViewportRelativeRect:GB,getDocumentElement:Mi,getClippingRect:JB,getOffsetParent:jT,getElementRects:nU,getClientRects:YB,getDimensions:eU,getScale:Nl,isElement:Ri,isRTL:rU};function iU(e,t){let n=null,r;const o=Mi(e);function i(){clearTimeout(r),n&&n.disconnect(),n=null}function s(l,u){l===void 0&&(l=!1),u===void 0&&(u=1),i();const{left:f,top:m,width:p,height:g}=e.getBoundingClientRect();if(l||t(),!p||!g)return;const y=fh(m),x=fh(o.clientWidth-(f+p)),S=fh(o.clientHeight-(m+g)),E=fh(f),b={rootMargin:-y+"px "+-x+"px "+-S+"px "+-E+"px",threshold:hr(0,Ts(1,u))||1};let C=!0;function R(P){const O=P[0].intersectionRatio;if(O!==u){if(!C)return s();O?s(!1,O):r=setTimeout(()=>{s(!1,1e-7)},100)}C=!1}try{n=new IntersectionObserver(R,{...b,root:o.ownerDocument})}catch{n=new IntersectionObserver(R,b)}n.observe(e)}return s(!0),i}function sU(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:o=!0,ancestorResize:i=!0,elementResize:s=typeof ResizeObserver=="function",layoutShift:l=typeof IntersectionObserver=="function",animationFrame:u=!1}=r,f=vx(e),m=o||i?[...f?cd(f):[],...cd(t)]:[];m.forEach(_=>{o&&_.addEventListener("scroll",n,{passive:!0}),i&&_.addEventListener("resize",n)});const p=f&&l?iU(f,n):null;let g=-1,y=null;s&&(y=new ResizeObserver(_=>{let[b]=_;b&&b.target===f&&y&&(y.unobserve(t),cancelAnimationFrame(g),g=requestAnimationFrame(()=>{y&&y.observe(t)})),n()}),f&&!u&&y.observe(f),y.observe(t));let x,S=u?Na(e):null;u&&E();function E(){const _=Na(e);S&&(_.x!==S.x||_.y!==S.y||_.width!==S.width||_.height!==S.height)&&n(),S=_,x=requestAnimationFrame(E)}return n(),()=>{m.forEach(_=>{o&&_.removeEventListener("scroll",n),i&&_.removeEventListener("resize",n)}),p&&p(),y&&y.disconnect(),y=null,u&&cancelAnimationFrame(x)}}const aU=(e,t,n)=>{const r=new Map,o={platform:oU,...n},i={...o.platform,_c:r};return DB(e,t,{...o,platform:i})},lU=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:o}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?IC({element:r.current,padding:o}).fn(n):{}:r?IC({element:r,padding:o}).fn(n):{}}}};var Zh=typeof document<"u"?d.useLayoutEffect:d.useEffect;function jp(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(!jp(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(!{}.hasOwnProperty.call(t,o[r]))return!1;for(r=n;r--!==0;){const i=o[r];if(!(i==="_owner"&&e.$$typeof)&&!jp(e[i],t[i]))return!1}return!0}return e!==e&&t!==t}function zT(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function UC(e,t){const n=zT(e);return Math.round(t*n)/n}function VC(e){const t=d.useRef(e);return Zh(()=>{t.current=e}),t}function cU(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:o,elements:{reference:i,floating:s}={},transform:l=!0,whileElementsMounted:u,open:f}=e,[m,p]=d.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[g,y]=d.useState(r);jp(g,r)||y(r);const[x,S]=d.useState(null),[E,_]=d.useState(null),b=d.useCallback(M=>{M!=O.current&&(O.current=M,S(M))},[S]),C=d.useCallback(M=>{M!==A.current&&(A.current=M,_(M))},[_]),R=i||x,P=s||E,O=d.useRef(null),A=d.useRef(null),D=d.useRef(m),B=VC(u),V=VC(o),J=d.useCallback(()=>{if(!O.current||!A.current)return;const M={placement:t,strategy:n,middleware:g};V.current&&(M.platform=V.current),aU(O.current,A.current,M).then(ee=>{const H={...ee,isPositioned:!0};G.current&&!jp(D.current,H)&&(D.current=H,Is.flushSync(()=>{p(H)}))})},[g,t,n,V]);Zh(()=>{f===!1&&D.current.isPositioned&&(D.current.isPositioned=!1,p(M=>({...M,isPositioned:!1})))},[f]);const G=d.useRef(!1);Zh(()=>(G.current=!0,()=>{G.current=!1}),[]),Zh(()=>{if(R&&(O.current=R),P&&(A.current=P),R&&P){if(B.current)return B.current(R,P,J);J()}},[R,P,J,B]);const se=d.useMemo(()=>({reference:O,floating:A,setReference:b,setFloating:C}),[b,C]),U=d.useMemo(()=>({reference:R,floating:P}),[R,P]),ne=d.useMemo(()=>{const M={position:n,left:0,top:0};if(!U.floating)return M;const ee=UC(U.floating,m.x),H=UC(U.floating,m.y);return l?{...M,transform:"translate("+ee+"px, "+H+"px)",...zT(U.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:ee,top:H}},[n,l,U.floating,m.x,m.y]);return d.useMemo(()=>({...m,update:J,refs:se,elements:U,floatingStyles:ne}),[m,J,se,U,ne])}function yx(e){const[t,n]=d.useState(void 0);return An(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(o=>{if(!Array.isArray(o)||!o.length)return;const i=o[0];let s,l;if("borderBoxSize"in i){const u=i.borderBoxSize,f=Array.isArray(u)?u[0]:u;s=f.inlineSize,l=f.blockSize}else s=e.offsetWidth,l=e.offsetHeight;n({width:s,height:l})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}const BT="Popper",[UT,Fs]=Mn(BT),[uU,VT]=UT(BT),dU=e=>{const{__scopePopper:t,children:n}=e,[r,o]=d.useState(null);return d.createElement(uU,{scope:t,anchor:r,onAnchorChange:o},n)},fU="PopperAnchor",hU=d.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...o}=e,i=VT(fU,n),s=d.useRef(null),l=Ue(t,s);return d.useEffect(()=>{i.onAnchorChange((r==null?void 0:r.current)||s.current)}),r?null:d.createElement(Ae.div,Y({},o,{ref:l}))}),WT="PopperContent",[pU,pte]=UT(WT),mU=d.forwardRef((e,t)=>{var n,r,o,i,s,l,u,f;const{__scopePopper:m,side:p="bottom",sideOffset:g=0,align:y="center",alignOffset:x=0,arrowPadding:S=0,avoidCollisions:E=!0,collisionBoundary:_=[],collisionPadding:b=0,sticky:C="partial",hideWhenDetached:R=!1,updatePositionStrategy:P="optimized",onPlaced:O,...A}=e,D=VT(WT,m),[B,V]=d.useState(null),J=Ue(t,Kt=>V(Kt)),[G,se]=d.useState(null),U=yx(G),ne=(n=U==null?void 0:U.width)!==null&&n!==void 0?n:0,M=(r=U==null?void 0:U.height)!==null&&r!==void 0?r:0,ee=p+(y!=="center"?"-"+y:""),H=typeof b=="number"?b:{top:0,right:0,bottom:0,left:0,...b},X=Array.isArray(_)?_:[_],W=X.length>0,le={padding:H,boundary:X.filter(gU),altBoundary:W},{refs:pe,floatingStyles:$e,placement:Ve,isPositioned:We,middlewareData:Ne}=cU({strategy:"fixed",placement:ee,whileElementsMounted:(...Kt)=>sU(...Kt,{animationFrame:P==="always"}),elements:{reference:D.anchor},middleware:[jB({mainAxis:g+M,alignmentAxis:x}),E&&zB({mainAxis:!0,crossAxis:!1,limiter:C==="partial"?BB():void 0,...le}),E&&IB({...le}),UB({...le,apply:({elements:Kt,rects:Er,availableWidth:gt,availableHeight:Vs})=>{const{width:L,height:Z}=Er.reference,q=Kt.floating.style;q.setProperty("--radix-popper-available-width",`${gt}px`),q.setProperty("--radix-popper-available-height",`${Vs}px`),q.setProperty("--radix-popper-anchor-width",`${L}px`),q.setProperty("--radix-popper-anchor-height",`${Z}px`)}}),G&&lU({element:G,padding:S}),vU({arrowWidth:ne,arrowHeight:M}),R&&LB({strategy:"referenceHidden",...le})]}),[fe,xe]=HT(Ve),Re=Ft(O);An(()=>{We&&(Re==null||Re())},[We,Re]);const Me=(o=Ne.arrow)===null||o===void 0?void 0:o.x,Oe=(i=Ne.arrow)===null||i===void 0?void 0:i.y,ze=((s=Ne.arrow)===null||s===void 0?void 0:s.centerOffset)!==0,[Mt,ct]=d.useState();return An(()=>{B&&ct(window.getComputedStyle(B).zIndex)},[B]),d.createElement("div",{ref:pe.setFloating,"data-radix-popper-content-wrapper":"",style:{...$e,transform:We?$e.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:Mt,"--radix-popper-transform-origin":[(l=Ne.transformOrigin)===null||l===void 0?void 0:l.x,(u=Ne.transformOrigin)===null||u===void 0?void 0:u.y].join(" ")},dir:e.dir},d.createElement(pU,{scope:m,placedSide:fe,onArrowChange:se,arrowX:Me,arrowY:Oe,shouldHideArrow:ze},d.createElement(Ae.div,Y({"data-side":fe,"data-align":xe},A,{ref:J,style:{...A.style,animation:We?void 0:"none",opacity:(f=Ne.hide)!==null&&f!==void 0&&f.referenceHidden?0:void 0}}))))});function gU(e){return e!==null}const vU=e=>({name:"transformOrigin",options:e,fn(t){var n,r,o,i,s;const{placement:l,rects:u,middlewareData:f}=t,p=((n=f.arrow)===null||n===void 0?void 0:n.centerOffset)!==0,g=p?0:e.arrowWidth,y=p?0:e.arrowHeight,[x,S]=HT(l),E={start:"0%",center:"50%",end:"100%"}[S],_=((r=(o=f.arrow)===null||o===void 0?void 0:o.x)!==null&&r!==void 0?r:0)+g/2,b=((i=(s=f.arrow)===null||s===void 0?void 0:s.y)!==null&&i!==void 0?i:0)+y/2;let C="",R="";return x==="bottom"?(C=p?E:`${_}px`,R=`${-y}px`):x==="top"?(C=p?E:`${_}px`,R=`${u.floating.height+y}px`):x==="right"?(C=`${-y}px`,R=p?E:`${b}px`):x==="left"&&(C=`${u.floating.width+y}px`,R=p?E:`${b}px`),{data:{x:C,y:R}}}});function HT(e){const[t,n="center"]=e.split("-");return[t,n]}const jd=dU,Vm=hU,Wm=mU,zd=d.forwardRef((e,t)=>{var n;const{container:r=globalThis==null||(n=globalThis.document)===null||n===void 0?void 0:n.body,...o}=e;return r?QI.createPortal(d.createElement(Ae.div,Y({},o,{ref:t})),r):null});function yU(e,t){return d.useReducer((n,r)=>{const o=t[n][r];return o??n},e)}const Sn=e=>{const{present:t,children:n}=e,r=wU(t),o=typeof n=="function"?n({present:r.isPresent}):d.Children.only(n),i=Ue(r.ref,o.ref);return typeof n=="function"||r.isPresent?d.cloneElement(o,{ref:i}):null};Sn.displayName="Presence";function wU(e){const[t,n]=d.useState(),r=d.useRef({}),o=d.useRef(e),i=d.useRef("none"),s=e?"mounted":"unmounted",[l,u]=yU(s,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return d.useEffect(()=>{const f=hh(r.current);i.current=l==="mounted"?f:"none"},[l]),An(()=>{const f=r.current,m=o.current;if(m!==e){const g=i.current,y=hh(f);e?u("MOUNT"):y==="none"||(f==null?void 0:f.display)==="none"?u("UNMOUNT"):u(m&&g!==y?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,u]),An(()=>{if(t){const f=p=>{const y=hh(r.current).includes(p.animationName);p.target===t&&y&&Is.flushSync(()=>u("ANIMATION_END"))},m=p=>{p.target===t&&(i.current=hh(r.current))};return t.addEventListener("animationstart",m),t.addEventListener("animationcancel",f),t.addEventListener("animationend",f),()=>{t.removeEventListener("animationstart",m),t.removeEventListener("animationcancel",f),t.removeEventListener("animationend",f)}}else u("ANIMATION_END")},[t,u]),{isPresent:["mounted","unmountSuspended"].includes(l),ref:d.useCallback(f=>{f&&(r.current=getComputedStyle(f)),n(f)},[])}}function hh(e){return(e==null?void 0:e.animationName)||"none"}function Zr({prop:e,defaultProp:t,onChange:n=()=>{}}){const[r,o]=xU({defaultProp:t,onChange:n}),i=e!==void 0,s=i?e:r,l=Ft(n),u=d.useCallback(f=>{if(i){const p=typeof f=="function"?f(e):f;p!==e&&l(p)}else o(f)},[i,e,o,l]);return[s,u]}function xU({defaultProp:e,onChange:t}){const n=d.useState(e),[r]=n,o=d.useRef(r),i=Ft(t);return d.useEffect(()=>{o.current!==r&&(i(r),o.current=r)},[r,o,i]),n}const Hm=d.forwardRef((e,t)=>d.createElement(Ae.span,Y({},e,{ref:t,style:{position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal",...e.style}}))),bU=Hm,[Km,mte]=Mn("Tooltip",[Fs]),wx=Fs(),SU="TooltipProvider",_U=700,d1="tooltip.open",[EU,xx]=Km(SU),CU=e=>{const{__scopeTooltip:t,delayDuration:n=_U,skipDelayDuration:r=300,disableHoverableContent:o=!1,children:i}=e,[s,l]=d.useState(!0),u=d.useRef(!1),f=d.useRef(0);return d.useEffect(()=>{const m=f.current;return()=>window.clearTimeout(m)},[]),d.createElement(EU,{scope:t,isOpenDelayed:s,delayDuration:n,onOpen:d.useCallback(()=>{window.clearTimeout(f.current),l(!1)},[]),onClose:d.useCallback(()=>{window.clearTimeout(f.current),f.current=window.setTimeout(()=>l(!0),r)},[r]),isPointerInTransitRef:u,onPointerInTransitChange:d.useCallback(m=>{u.current=m},[]),disableHoverableContent:o},i)},bx="Tooltip",[$U,Gm]=Km(bx),RU=e=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:o=!1,onOpenChange:i,disableHoverableContent:s,delayDuration:l}=e,u=xx(bx,e.__scopeTooltip),f=wx(t),[m,p]=d.useState(null),g=nr(),y=d.useRef(0),x=s??u.disableHoverableContent,S=l??u.delayDuration,E=d.useRef(!1),[_=!1,b]=Zr({prop:r,defaultProp:o,onChange:A=>{A?(u.onOpen(),document.dispatchEvent(new CustomEvent(d1))):u.onClose(),i==null||i(A)}}),C=d.useMemo(()=>_?E.current?"delayed-open":"instant-open":"closed",[_]),R=d.useCallback(()=>{window.clearTimeout(y.current),E.current=!1,b(!0)},[b]),P=d.useCallback(()=>{window.clearTimeout(y.current),b(!1)},[b]),O=d.useCallback(()=>{window.clearTimeout(y.current),y.current=window.setTimeout(()=>{E.current=!0,b(!0)},S)},[S,b]);return d.useEffect(()=>()=>window.clearTimeout(y.current),[]),d.createElement(jd,f,d.createElement($U,{scope:t,contentId:g,open:_,stateAttribute:C,trigger:m,onTriggerChange:p,onTriggerEnter:d.useCallback(()=>{u.isOpenDelayed?O():R()},[u.isOpenDelayed,O,R]),onTriggerLeave:d.useCallback(()=>{x?P():window.clearTimeout(y.current)},[P,x]),onOpen:R,onClose:P,disableHoverableContent:x},n))},WC="TooltipTrigger",kU=d.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,o=Gm(WC,n),i=xx(WC,n),s=wx(n),l=d.useRef(null),u=Ue(t,l,o.onTriggerChange),f=d.useRef(!1),m=d.useRef(!1),p=d.useCallback(()=>f.current=!1,[]);return d.useEffect(()=>()=>document.removeEventListener("pointerup",p),[p]),d.createElement(Vm,Y({asChild:!0},s),d.createElement(Ae.button,Y({"aria-describedby":o.open?o.contentId:void 0,"data-state":o.stateAttribute},r,{ref:u,onPointerMove:ue(e.onPointerMove,g=>{g.pointerType!=="touch"&&!m.current&&!i.isPointerInTransitRef.current&&(o.onTriggerEnter(),m.current=!0)}),onPointerLeave:ue(e.onPointerLeave,()=>{o.onTriggerLeave(),m.current=!1}),onPointerDown:ue(e.onPointerDown,()=>{f.current=!0,document.addEventListener("pointerup",p,{once:!0})}),onFocus:ue(e.onFocus,()=>{f.current||o.onOpen()}),onBlur:ue(e.onBlur,o.onClose),onClick:ue(e.onClick,o.onClose)})))}),TU="TooltipPortal",[gte,PU]=Km(TU,{forceMount:void 0}),ud="TooltipContent",AU=d.forwardRef((e,t)=>{const n=PU(ud,e.__scopeTooltip),{forceMount:r=n.forceMount,side:o="top",...i}=e,s=Gm(ud,e.__scopeTooltip);return d.createElement(Sn,{present:r||s.open},s.disableHoverableContent?d.createElement(KT,Y({side:o},i,{ref:t})):d.createElement(MU,Y({side:o},i,{ref:t})))}),MU=d.forwardRef((e,t)=>{const n=Gm(ud,e.__scopeTooltip),r=xx(ud,e.__scopeTooltip),o=d.useRef(null),i=Ue(t,o),[s,l]=d.useState(null),{trigger:u,onClose:f}=n,m=o.current,{onPointerInTransitChange:p}=r,g=d.useCallback(()=>{l(null),p(!1)},[p]),y=d.useCallback((x,S)=>{const E=x.currentTarget,_={x:x.clientX,y:x.clientY},b=NU(_,E.getBoundingClientRect()),C=DU(_,b),R=IU(S.getBoundingClientRect()),P=FU([...C,...R]);l(P),p(!0)},[p]);return d.useEffect(()=>()=>g(),[g]),d.useEffect(()=>{if(u&&m){const x=E=>y(E,m),S=E=>y(E,u);return u.addEventListener("pointerleave",x),m.addEventListener("pointerleave",S),()=>{u.removeEventListener("pointerleave",x),m.removeEventListener("pointerleave",S)}}},[u,m,y,g]),d.useEffect(()=>{if(s){const x=S=>{const E=S.target,_={x:S.clientX,y:S.clientY},b=(u==null?void 0:u.contains(E))||(m==null?void 0:m.contains(E)),C=!LU(_,s);b?g():C&&(g(),f())};return document.addEventListener("pointermove",x),()=>document.removeEventListener("pointermove",x)}},[u,m,s,f,g]),d.createElement(KT,Y({},e,{ref:i}))}),[OU,vte]=Km(bx,{isInside:!1}),KT=d.forwardRef((e,t)=>{const{__scopeTooltip:n,children:r,"aria-label":o,onEscapeKeyDown:i,onPointerDownOutside:s,...l}=e,u=Gm(ud,n),f=wx(n),{onClose:m}=u;return d.useEffect(()=>(document.addEventListener(d1,m),()=>document.removeEventListener(d1,m)),[m]),d.useEffect(()=>{if(u.trigger){const p=g=>{const y=g.target;y!=null&&y.contains(u.trigger)&&m()};return window.addEventListener("scroll",p,{capture:!0}),()=>window.removeEventListener("scroll",p,{capture:!0})}},[u.trigger,m]),d.createElement(Ec,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:i,onPointerDownOutside:s,onFocusOutside:p=>p.preventDefault(),onDismiss:m},d.createElement(Wm,Y({"data-state":u.stateAttribute},f,l,{ref:t,style:{...l.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"}}),d.createElement(lx,null,r),d.createElement(OU,{scope:n,isInside:!0},d.createElement(bU,{id:u.contentId,role:"tooltip"},o||r))))});function NU(e,t){const n=Math.abs(t.top-e.y),r=Math.abs(t.bottom-e.y),o=Math.abs(t.right-e.x),i=Math.abs(t.left-e.x);switch(Math.min(n,r,o,i)){case i:return"left";case o:return"right";case n:return"top";case r:return"bottom";default:throw new Error("unreachable")}}function DU(e,t,n=5){const r=[];switch(t){case"top":r.push({x:e.x-n,y:e.y+n},{x:e.x+n,y:e.y+n});break;case"bottom":r.push({x:e.x-n,y:e.y-n},{x:e.x+n,y:e.y-n});break;case"left":r.push({x:e.x+n,y:e.y-n},{x:e.x+n,y:e.y+n});break;case"right":r.push({x:e.x-n,y:e.y-n},{x:e.x-n,y:e.y+n});break}return r}function IU(e){const{top:t,right:n,bottom:r,left:o}=e;return[{x:o,y:t},{x:n,y:t},{x:n,y:r},{x:o,y:r}]}function LU(e,t){const{x:n,y:r}=e;let o=!1;for(let i=0,s=t.length-1;ir!=m>r&&n<(f-l)*(r-u)/(m-u)+l&&(o=!o)}return o}function FU(e){const t=e.slice();return t.sort((n,r)=>n.xr.x?1:n.yr.y?1:0),jU(t)}function jU(e){if(e.length<=1)return e.slice();const t=[];for(let r=0;r=2;){const i=t[t.length-1],s=t[t.length-2];if((i.x-s.x)*(o.y-s.y)>=(i.y-s.y)*(o.x-s.x))t.pop();else break}t.push(o)}t.pop();const n=[];for(let r=e.length-1;r>=0;r--){const o=e[r];for(;n.length>=2;){const i=n[n.length-1],s=n[n.length-2];if((i.x-s.x)*(o.y-s.y)>=(i.y-s.y)*(o.x-s.x))n.pop();else break}n.push(o)}return n.pop(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}const zU=CU,BU=RU,UU=kU,GT=AU,VU=zU,YT=BU,XT=UU,Sx=d.forwardRef(({className:e,sideOffset:t=4,...n},r)=>v.jsx(GT,{ref:r,sideOffset:t,className:Ce("z-50 border overflow-hidden rounded-md bg-background text-foreground px-3 py-1.5 text-xs animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...n}));Sx.displayName=GT.displayName;const _x=Dm("inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50",{variants:{variant:{default:"bg-primary text-primary-foreground shadow hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",outline:"border border-input bg-transparent shadow-sm hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2",sm:"h-8 rounded-md px-3 text-xs",lg:"h-10 rounded-md px-8",icon:"h-9 w-9"}},defaultVariants:{variant:"default",size:"default"}}),wn=d.forwardRef(({className:e,variant:t,size:n,asChild:r=!1,...o},i)=>{const s=r?Zo:"button";return v.jsx(s,{className:Ce(_x({variant:t,size:n,className:e}),"outline-none cursor-default"),ref:i,tabIndex:-1,...o})});wn.displayName="Button";const yn=d.forwardRef(({tooltip:e,children:t,...n},r)=>v.jsxs(YT,{children:[v.jsx(XT,{asChild:!0,children:v.jsx(wn,{variant:"ghost",size:"icon",...n,ref:r,tabIndex:-1,className:"cursor-default bg-background",children:v.jsx("div",{className:"icon-button-icon-wrapper",children:t})})}),v.jsx(Sx,{children:v.jsx("p",{children:e})})]})),f1=e=>{const{onFileUpload:t,children:n,...r}=e,[o]=d.useState(`file-upload-${Math.random().toString()}`),i=s=>{var u;const l=(u=s.currentTarget.files)==null?void 0:u[0];l&&t(l)};return v.jsxs(v.Fragment,{children:[v.jsx("label",{htmlFor:o,children:v.jsx(yn,{...r,asChild:!0,children:n})}),v.jsx(Ld,{style:{display:"none"},id:o,name:o,type:"file",onChange:i,accept:"image/png, image/jpeg"})]})};var WU={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const HU=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Jt=(e,t)=>{const n=d.forwardRef(({color:r="currentColor",size:o=24,strokeWidth:i=2,absoluteStrokeWidth:s,children:l,...u},f)=>d.createElement("svg",{ref:f,...WU,width:o,height:o,stroke:r,strokeWidth:s?Number(i)*24/Number(o):i,className:`lucide lucide-${HU(e)}`,...u},[...t.map(([m,p])=>d.createElement(m,p)),...(Array.isArray(l)?l:[l])||[]]));return n.displayName=`${e}`,n},KU=Jt("Blocks",[["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["path",{d:"M10 21V8a1 1 0 0 0-1-1H4a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-5a1 1 0 0 0-1-1H3",key:"1fpvtg"}]]),GU=Jt("ChevronLeft",[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]]),YU=Jt("ChevronRight",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]),XU=Jt("Coffee",[["path",{d:"M17 8h1a4 4 0 1 1 0 8h-1",key:"jx4kbh"}],["path",{d:"M3 8h14v9a4 4 0 0 1-4 4H7a4 4 0 0 1-4-4Z",key:"1bxrl0"}],["line",{x1:"6",x2:"6",y1:"2",y2:"4",key:"1cr9l3"}],["line",{x1:"10",x2:"10",y1:"2",y2:"4",key:"170wym"}],["line",{x1:"14",x2:"14",y1:"2",y2:"4",key:"1c5f70"}]]),ZU=Jt("Download",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"7 10 12 15 17 10",key:"2ggqvy"}],["line",{x1:"12",x2:"12",y1:"15",y2:"3",key:"1vk2je"}]]),qU=Jt("Eraser",[["path",{d:"m7 21-4.3-4.3c-1-1-1-2.5 0-3.4l9.6-9.6c1-1 2.5-1 3.4 0l5.6 5.6c1 1 1 2.5 0 3.4L13 21",key:"182aya"}],["path",{d:"M22 21H7",key:"t4ddhn"}],["path",{d:"m5 11 9 9",key:"1mo9qw"}]]),QU=Jt("Expand",[["path",{d:"m21 21-6-6m6 6v-4.8m0 4.8h-4.8",key:"1c15vz"}],["path",{d:"M3 16.2V21m0 0h4.8M3 21l6-6",key:"1fsnz2"}],["path",{d:"M21 7.8V3m0 0h-4.8M21 3l-6 6",key:"hawz9i"}],["path",{d:"M3 7.8V3m0 0h4.8M3 3l6 6",key:"u9ee12"}]]),JU=Jt("Eye",[["path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z",key:"rwhkz3"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]),eV=Jt("FolderClosed",[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}],["path",{d:"M2 10h20",key:"1ir3d8"}]]),ZT=Jt("Fullscreen",[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}],["rect",{width:"10",height:"8",x:"7",y:"8",rx:"1",key:"vys8me"}]]),tV=Jt("Image",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]]),nV=Jt("Keyboard",[["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",ry:"2",key:"15u882"}],["path",{d:"M6 8h.001",key:"1ej0i3"}],["path",{d:"M10 8h.001",key:"1x2st2"}],["path",{d:"M14 8h.001",key:"1vkmyp"}],["path",{d:"M18 8h.001",key:"kfsenl"}],["path",{d:"M8 12h.001",key:"1sjpby"}],["path",{d:"M12 12h.001",key:"al75ts"}],["path",{d:"M16 12h.001",key:"931bgk"}],["path",{d:"M7 16h10",key:"wp8him"}]]),rV=Jt("MousePointerClick",[["path",{d:"m9 9 5 12 1.8-5.2L21 14Z",key:"1b76lo"}],["path",{d:"M7.2 2.2 8 5.1",key:"1cfko1"}],["path",{d:"m5.1 8-2.9-.8",key:"1go3kf"}],["path",{d:"M14 4.1 12 6",key:"ita8i4"}],["path",{d:"m6 12-1.9 2",key:"mnht97"}]]),oV=Jt("Redo",[["path",{d:"M21 7v6h-6",key:"3ptur4"}],["path",{d:"M3 17a9 9 0 0 1 9-9 9 9 0 0 1 6 2.3l3 2.7",key:"1kgawr"}]]),iV=Jt("RotateCw",[["path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8",key:"1p45f6"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}]]),sV=Jt("Settings",[["path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z",key:"1qme2f"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]),HC=Jt("Slice",[["path",{d:"m8 14-6 6h9v-3",key:"zo3j9a"}],["path",{d:"M18.37 3.63 8 14l3 3L21.37 6.63a2.12 2.12 0 1 0-3-3Z",key:"1dzx0j"}]]),KC=Jt("Smile",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 14s1.5 2 4 2 4-2 4-2",key:"1y1vjs"}],["line",{x1:"9",x2:"9.01",y1:"9",y2:"9",key:"yxxnd0"}],["line",{x1:"15",x2:"15.01",y1:"9",y2:"9",key:"1p4y9e"}]]),aV=Jt("Undo",[["path",{d:"M3 7v6h6",key:"1v2h90"}],["path",{d:"M21 17a9 9 0 0 0-9-9 9 9 0 0 0-6 2.3L3 13",key:"1r6uu6"}]]),qT=Jt("Upload",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"17 8 12 3 7 8",key:"t8dd8p"}],["line",{x1:"12",x2:"12",y1:"3",y2:"15",key:"widbto"}]]);function lV(e,t){const[n,r]=d.useState(e);return d.useEffect(()=>{const o=setTimeout(()=>{r(e)},t);return()=>{clearTimeout(o)}},[e,t]),n}function QT(e){const[t,n]=d.useState(()=>typeof e=="boolean"?e:!!e),r=d.useCallback(o=>n(typeof o=="boolean"?o:i=>!i),[]);return[t,r]}const _0="focusScope.autoFocusOnMount",E0="focusScope.autoFocusOnUnmount",GC={bubbles:!1,cancelable:!0},Ym=d.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:o,onUnmountAutoFocus:i,...s}=e,[l,u]=d.useState(null),f=Ft(o),m=Ft(i),p=d.useRef(null),g=Ue(t,S=>u(S)),y=d.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;d.useEffect(()=>{if(r){let b=function(O){if(y.paused||!l)return;const A=O.target;l.contains(A)?p.current=A:Qi(p.current,{select:!0})},C=function(O){if(y.paused||!l)return;const A=O.relatedTarget;A!==null&&(l.contains(A)||Qi(p.current,{select:!0}))},R=function(O){if(document.activeElement===document.body)for(const D of O)D.removedNodes.length>0&&Qi(l)};var S=b,E=C,_=R;document.addEventListener("focusin",b),document.addEventListener("focusout",C);const P=new MutationObserver(R);return l&&P.observe(l,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",b),document.removeEventListener("focusout",C),P.disconnect()}}},[r,l,y.paused]),d.useEffect(()=>{if(l){XC.add(y);const S=document.activeElement;if(!l.contains(S)){const _=new CustomEvent(_0,GC);l.addEventListener(_0,f),l.dispatchEvent(_),_.defaultPrevented||(cV(pV(JT(l)),{select:!0}),document.activeElement===S&&Qi(l))}return()=>{l.removeEventListener(_0,f),setTimeout(()=>{const _=new CustomEvent(E0,GC);l.addEventListener(E0,m),l.dispatchEvent(_),_.defaultPrevented||Qi(S??document.body,{select:!0}),l.removeEventListener(E0,m),XC.remove(y)},0)}}},[l,f,m,y]);const x=d.useCallback(S=>{if(!n&&!r||y.paused)return;const E=S.key==="Tab"&&!S.altKey&&!S.ctrlKey&&!S.metaKey,_=document.activeElement;if(E&&_){const b=S.currentTarget,[C,R]=uV(b);C&&R?!S.shiftKey&&_===R?(S.preventDefault(),n&&Qi(C,{select:!0})):S.shiftKey&&_===C&&(S.preventDefault(),n&&Qi(R,{select:!0})):_===b&&S.preventDefault()}},[n,r,y.paused]);return d.createElement(Ae.div,Y({tabIndex:-1},s,{ref:g,onKeyDown:x}))});function cV(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(Qi(r,{select:t}),document.activeElement!==n)return}function uV(e){const t=JT(e),n=YC(t,e),r=YC(t.reverse(),e);return[n,r]}function JT(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const o=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||o?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function YC(e,t){for(const n of e)if(!dV(n,{upTo:t}))return n}function dV(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function fV(e){return e instanceof HTMLInputElement&&"select"in e}function Qi(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&fV(e)&&t&&e.select()}}const XC=hV();function hV(){let e=[];return{add(t){const n=e[0];t!==n&&(n==null||n.pause()),e=ZC(e,t),e.unshift(t)},remove(t){var n;e=ZC(e,t),(n=e[0])===null||n===void 0||n.resume()}}}function ZC(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function pV(e){return e.filter(t=>t.tagName!=="A")}let C0=0;function Xm(){d.useEffect(()=>{var e,t;const n=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",(e=n[0])!==null&&e!==void 0?e:qC()),document.body.insertAdjacentElement("beforeend",(t=n[1])!==null&&t!==void 0?t:qC()),C0++,()=>{C0===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(r=>r.remove()),C0--}},[])}function qC(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.cssText="outline: none; opacity: 0; position: fixed; pointer-events: none",e}var Lo=function(){return Lo=Object.assign||function(t){for(var n,r=1,o=arguments.length;r"u")return AV;var t=MV(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])}},NV=rP(),DV=function(e,t,n,r){var o=e.left,i=e.top,s=e.right,l=e.gap;return n===void 0&&(n="margin"),` + .`.concat(gV,` { + overflow: hidden `).concat(r,`; + padding-right: `).concat(l,"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(i,`px; + padding-right: `).concat(s,`px; + margin-left:0; + margin-top:0; + margin-right: `).concat(l,"px ").concat(r,`; + `),n==="padding"&&"padding-right: ".concat(l,"px ").concat(r,";")].filter(Boolean).join(""),` + } + + .`).concat(qh,` { + right: `).concat(l,"px ").concat(r,`; + } + + .`).concat(Qh,` { + margin-right: `).concat(l,"px ").concat(r,`; + } + + .`).concat(qh," .").concat(qh,` { + right: 0 `).concat(r,`; + } + + .`).concat(Qh," .").concat(Qh,` { + margin-right: 0 `).concat(r,`; + } + + body { + `).concat(vV,": ").concat(l,`px; + } +`)},IV=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,o=r===void 0?"margin":r,i=d.useMemo(function(){return OV(o)},[o]);return d.createElement(NV,{styles:DV(i,!t,o,n?"":"!important")})},h1=!1;if(typeof window<"u")try{var ph=Object.defineProperty({},"passive",{get:function(){return h1=!0,!0}});window.addEventListener("test",ph,ph),window.removeEventListener("test",ph,ph)}catch{h1=!1}var rl=h1?{passive:!1}:!1,LV=function(e){return e.tagName==="TEXTAREA"},oP=function(e,t){var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!LV(e)&&n[t]==="visible")},FV=function(e){return oP(e,"overflowY")},jV=function(e){return oP(e,"overflowX")},JC=function(e,t){var n=t;do{typeof ShadowRoot<"u"&&n instanceof ShadowRoot&&(n=n.host);var r=iP(e,n);if(r){var o=sP(e,n),i=o[1],s=o[2];if(i>s)return!0}n=n.parentNode}while(n&&n!==document.body);return!1},zV=function(e){var t=e.scrollTop,n=e.scrollHeight,r=e.clientHeight;return[t,n,r]},BV=function(e){var t=e.scrollLeft,n=e.scrollWidth,r=e.clientWidth;return[t,n,r]},iP=function(e,t){return e==="v"?FV(t):jV(t)},sP=function(e,t){return e==="v"?zV(t):BV(t)},UV=function(e,t){return e==="h"&&t==="rtl"?-1:1},VV=function(e,t,n,r,o){var i=UV(e,window.getComputedStyle(t).direction),s=i*r,l=n.target,u=t.contains(l),f=!1,m=s>0,p=0,g=0;do{var y=sP(e,l),x=y[0],S=y[1],E=y[2],_=S-E-i*x;(x||_)&&iP(e,l)&&(p+=_,g+=x),l=l.parentNode}while(!u&&l!==document.body||u&&(t.contains(l)||t===l));return(m&&(o&&p===0||!o&&s>p)||!m&&(o&&g===0||!o&&-s>g))&&(f=!0),f},mh=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},e2=function(e){return[e.deltaX,e.deltaY]},t2=function(e){return e&&"current"in e?e.current:e},WV=function(e,t){return e[0]===t[0]&&e[1]===t[1]},HV=function(e){return` + .block-interactivity-`.concat(e,` {pointer-events: none;} + .allow-interactivity-`).concat(e,` {pointer-events: all;} +`)},KV=0,ol=[];function GV(e){var t=d.useRef([]),n=d.useRef([0,0]),r=d.useRef(),o=d.useState(KV++)[0],i=d.useState(function(){return rP()})[0],s=d.useRef(e);d.useEffect(function(){s.current=e},[e]),d.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(o));var S=mV([e.lockRef.current],(e.shards||[]).map(t2),!0).filter(Boolean);return S.forEach(function(E){return E.classList.add("allow-interactivity-".concat(o))}),function(){document.body.classList.remove("block-interactivity-".concat(o)),S.forEach(function(E){return E.classList.remove("allow-interactivity-".concat(o))})}}},[e.inert,e.lockRef.current,e.shards]);var l=d.useCallback(function(S,E){if("touches"in S&&S.touches.length===2)return!s.current.allowPinchZoom;var _=mh(S),b=n.current,C="deltaX"in S?S.deltaX:b[0]-_[0],R="deltaY"in S?S.deltaY:b[1]-_[1],P,O=S.target,A=Math.abs(C)>Math.abs(R)?"h":"v";if("touches"in S&&A==="h"&&O.type==="range")return!1;var D=JC(A,O);if(!D)return!0;if(D?P=A:(P=A==="v"?"h":"v",D=JC(A,O)),!D)return!1;if(!r.current&&"changedTouches"in S&&(C||R)&&(r.current=P),!P)return!0;var B=r.current||P;return VV(B,E,S,B==="h"?C:R,!0)},[]),u=d.useCallback(function(S){var E=S;if(!(!ol.length||ol[ol.length-1]!==i)){var _="deltaY"in E?e2(E):mh(E),b=t.current.filter(function(P){return P.name===E.type&&P.target===E.target&&WV(P.delta,_)})[0];if(b&&b.should){E.cancelable&&E.preventDefault();return}if(!b){var C=(s.current.shards||[]).map(t2).filter(Boolean).filter(function(P){return P.contains(E.target)}),R=C.length>0?l(E,C[0]):!s.current.noIsolation;R&&E.cancelable&&E.preventDefault()}}},[]),f=d.useCallback(function(S,E,_,b){var C={name:S,delta:E,target:_,should:b};t.current.push(C),setTimeout(function(){t.current=t.current.filter(function(R){return R!==C})},1)},[]),m=d.useCallback(function(S){n.current=mh(S),r.current=void 0},[]),p=d.useCallback(function(S){f(S.type,e2(S),S.target,l(S,e.lockRef.current))},[]),g=d.useCallback(function(S){f(S.type,mh(S),S.target,l(S,e.lockRef.current))},[]);d.useEffect(function(){return ol.push(i),e.setCallbacks({onScrollCapture:p,onWheelCapture:p,onTouchMoveCapture:g}),document.addEventListener("wheel",u,rl),document.addEventListener("touchmove",u,rl),document.addEventListener("touchstart",m,rl),function(){ol=ol.filter(function(S){return S!==i}),document.removeEventListener("wheel",u,rl),document.removeEventListener("touchmove",u,rl),document.removeEventListener("touchstart",m,rl)}},[]);var y=e.removeScrollBar,x=e.inert;return d.createElement(d.Fragment,null,x?d.createElement(i,{styles:HV(o)}):null,y?d.createElement(IV,{gapMode:"margin"}):null)}const YV=EV(nP,GV);var aP=d.forwardRef(function(e,t){return d.createElement(Zm,Lo({},e,{ref:t,sideCar:YV}))});aP.classNames=Zm.classNames;const qm=aP;var XV=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},il=new WeakMap,gh=new WeakMap,vh={},k0=0,lP=function(e){return e&&(e.host||lP(e.parentNode))},ZV=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=lP(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})},qV=function(e,t,n,r){var o=ZV(t,Array.isArray(e)?e:[e]);vh[n]||(vh[n]=new WeakMap);var i=vh[n],s=[],l=new Set,u=new Set(o),f=function(p){!p||l.has(p)||(l.add(p),f(p.parentNode))};o.forEach(f);var m=function(p){!p||u.has(p)||Array.prototype.forEach.call(p.children,function(g){if(l.has(g))m(g);else{var y=g.getAttribute(r),x=y!==null&&y!=="false",S=(il.get(g)||0)+1,E=(i.get(g)||0)+1;il.set(g,S),i.set(g,E),s.push(g),S===1&&x&&gh.set(g,!0),E===1&&g.setAttribute(n,"true"),x||g.setAttribute(r,"true")}})};return m(t),l.clear(),k0++,function(){s.forEach(function(p){var g=il.get(p)-1,y=i.get(p)-1;il.set(p,g),i.set(p,y),g||(gh.has(p)||p.removeAttribute(r),gh.delete(p)),y||p.removeAttribute(n)}),k0--,k0||(il=new WeakMap,il=new WeakMap,gh=new WeakMap,vh={})}},Qm=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),o=t||XV(e);return o?(r.push.apply(r,Array.from(o.querySelectorAll("[aria-live]"))),qV(r,o,n,"aria-hidden")):function(){return null}};const cP="Dialog",[uP,dP]=Mn(cP),[QV,Eo]=uP(cP),JV=e=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:o,onOpenChange:i,modal:s=!0}=e,l=d.useRef(null),u=d.useRef(null),[f=!1,m]=Zr({prop:r,defaultProp:o,onChange:i});return d.createElement(QV,{scope:t,triggerRef:l,contentRef:u,contentId:nr(),titleId:nr(),descriptionId:nr(),open:f,onOpenChange:m,onOpenToggle:d.useCallback(()=>m(p=>!p),[m]),modal:s},n)},eW="DialogTrigger",fP=d.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=Eo(eW,n),i=Ue(t,o.triggerRef);return d.createElement(Ae.button,Y({type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":Ex(o.open)},r,{ref:i,onClick:ue(e.onClick,o.onOpenToggle)}))}),hP="DialogPortal",[tW,pP]=uP(hP,{forceMount:void 0}),nW=e=>{const{__scopeDialog:t,forceMount:n,children:r,container:o}=e,i=Eo(hP,t);return d.createElement(tW,{scope:t,forceMount:n},d.Children.map(r,s=>d.createElement(Sn,{present:n||i.open},d.createElement(zd,{asChild:!0,container:o},s))))},p1="DialogOverlay",rW=d.forwardRef((e,t)=>{const n=pP(p1,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,i=Eo(p1,e.__scopeDialog);return i.modal?d.createElement(Sn,{present:r||i.open},d.createElement(oW,Y({},o,{ref:t}))):null}),oW=d.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=Eo(p1,n);return d.createElement(qm,{as:Zo,allowPinchZoom:!0,shards:[o.contentRef]},d.createElement(Ae.div,Y({"data-state":Ex(o.open)},r,{ref:t,style:{pointerEvents:"auto",...r.style}})))}),uc="DialogContent",iW=d.forwardRef((e,t)=>{const n=pP(uc,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,i=Eo(uc,e.__scopeDialog);return d.createElement(Sn,{present:r||i.open},i.modal?d.createElement(sW,Y({},o,{ref:t})):d.createElement(aW,Y({},o,{ref:t})))}),sW=d.forwardRef((e,t)=>{const n=Eo(uc,e.__scopeDialog),r=d.useRef(null),o=Ue(t,n.contentRef,r);return d.useEffect(()=>{const i=r.current;if(i)return Qm(i)},[]),d.createElement(mP,Y({},e,{ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:ue(e.onCloseAutoFocus,i=>{var s;i.preventDefault(),(s=n.triggerRef.current)===null||s===void 0||s.focus()}),onPointerDownOutside:ue(e.onPointerDownOutside,i=>{const s=i.detail.originalEvent,l=s.button===0&&s.ctrlKey===!0;(s.button===2||l)&&i.preventDefault()}),onFocusOutside:ue(e.onFocusOutside,i=>i.preventDefault())}))}),aW=d.forwardRef((e,t)=>{const n=Eo(uc,e.__scopeDialog),r=d.useRef(!1),o=d.useRef(!1);return d.createElement(mP,Y({},e,{ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var s;if((s=e.onCloseAutoFocus)===null||s===void 0||s.call(e,i),!i.defaultPrevented){var l;r.current||(l=n.triggerRef.current)===null||l===void 0||l.focus(),i.preventDefault()}r.current=!1,o.current=!1},onInteractOutside:i=>{var s,l;(s=e.onInteractOutside)===null||s===void 0||s.call(e,i),i.defaultPrevented||(r.current=!0,i.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const u=i.target;((l=n.triggerRef.current)===null||l===void 0?void 0:l.contains(u))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&o.current&&i.preventDefault()}}))}),mP=d.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:i,...s}=e,l=Eo(uc,n),u=d.useRef(null),f=Ue(t,u);return Xm(),d.createElement(d.Fragment,null,d.createElement(Ym,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:i},d.createElement(Ec,Y({role:"dialog",id:l.contentId,"aria-describedby":l.descriptionId,"aria-labelledby":l.titleId,"data-state":Ex(l.open)},s,{ref:f,onDismiss:()=>l.onOpenChange(!1)}))),!1)}),gP="DialogTitle",lW=d.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=Eo(gP,n);return d.createElement(Ae.h2,Y({id:o.titleId},r,{ref:t}))}),cW="DialogDescription",vP=d.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=Eo(cW,n);return d.createElement(Ae.p,Y({id:o.descriptionId},r,{ref:t}))}),uW="DialogClose",dW=d.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=Eo(uW,n);return d.createElement(Ae.button,Y({type:"button"},r,{ref:t,onClick:ue(e.onClick,()=>o.onOpenChange(!1))}))});function Ex(e){return e?"open":"closed"}const fW="DialogTitleWarning",[hW,yte]=pB(fW,{contentName:uc,titleName:gP,docsSlug:"dialog"}),Cx=JV,yP=fP,$x=nW,Bd=rW,Ud=iW,Vd=lW,Wd=vP,Rx=dW,Jm=Cx,kx=yP,pW=$x,wP=d.forwardRef(({className:e,...t},n)=>v.jsx(Bd,{ref:n,className:Ce("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t}));wP.displayName=Bd.displayName;const Hd=d.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(pW,{children:[v.jsx(wP,{}),v.jsxs(Ud,{ref:r,className:Ce("fixed left-[50%] top-[50%] z-50 flex flex-col w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",e,"outline-none"),onCloseAutoFocus:o=>o.preventDefault(),...n,children:[t,v.jsxs(Rx,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[v.jsx(wT,{className:"h-4 w-4"}),v.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Hd.displayName=Ud.displayName;const xP=({className:e,...t})=>v.jsx("div",{className:Ce("flex flex-col space-y-1.5 text-center sm:text-left",e),...t});xP.displayName="DialogHeader";const Kd=d.forwardRef(({className:e,...t},n)=>v.jsx(Vd,{ref:n,className:Ce("text-2xl font-semibold leading-none tracking-tight",e),...t}));Kd.displayName=Vd.displayName;const mW=d.forwardRef(({className:e,...t},n)=>v.jsx(Wd,{ref:n,className:Ce("text-sm text-muted-foreground",e),...t}));mW.displayName=Wd.displayName;function m1(){return m1=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 _W=function(t,n,r){r===void 0&&(r=!1);var o=n.alt,i=n.meta,s=n.mod,l=n.shift,u=n.ctrl,f=n.keys,m=t.key,p=t.code,g=t.ctrlKey,y=t.metaKey,x=t.shiftKey,S=t.altKey,E=hs(p),_=m.toLowerCase();if(!r){if(o===!S&&_!=="alt"||l===!x&&_!=="shift")return!1;if(s){if(!y&&!g)return!1}else if(i===!y&&_!=="meta"&&_!=="os"||u===!g&&_!=="ctrl"&&_!=="control")return!1}return f&&f.length===1&&(f.includes(_)||f.includes(E))?!0:f?yW(f):!f},EW=d.createContext(void 0),CW=function(){return d.useContext(EW)};function CP(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&&CP(e[r],t[r])},!0):e===t}var $W=d.createContext({hotkeys:[],enabledScopes:[],toggleScope:function(){},enableScope:function(){},disableScope:function(){}}),RW=function(){return d.useContext($W)};function kW(e){var t=d.useRef(void 0);return CP(t.current,e)||(t.current=e),t.current}var n2=function(t){t.stopPropagation(),t.preventDefault(),t.stopImmediatePropagation()},TW=typeof window<"u"?d.useLayoutEffect:d.useEffect;function PW(e,t,n,r){var o=d.useRef(null),i=d.useRef(!1),s=n instanceof Array?r instanceof Array?void 0:r:n,l=Tx(e)?e.join(s==null?void 0:s.splitKey):e,u=n instanceof Array?n:r instanceof Array?r:void 0,f=d.useCallback(t,u??[]),m=d.useRef(f);u?m.current=f:m.current=t;var p=kW(s),g=RW(),y=g.enabledScopes,x=CW();return TW(function(){if(!((p==null?void 0:p.enabled)===!1||!SW(y,p==null?void 0:p.scopes))){var S=function(R,P){var O;if(P===void 0&&(P=!1),!(bW(R)&&!EP(R,p==null?void 0:p.enableOnFormTags))&&!(p!=null&&p.ignoreEventWhen!=null&&p.ignoreEventWhen(R))){if(o.current!==null&&document.activeElement!==o.current&&!o.current.contains(document.activeElement)){n2(R);return}(O=R.target)!=null&&O.isContentEditable&&!(p!=null&&p.enableOnContentEditable)||T0(l,p==null?void 0:p.splitKey).forEach(function(A){var D,B=P0(A,p==null?void 0:p.combinationKey);if(_W(R,B,p==null?void 0:p.ignoreModifiers)||(D=B.keys)!=null&&D.includes("*")){if(P&&i.current)return;if(wW(R,B,p==null?void 0:p.preventDefault),!xW(R,B,p==null?void 0:p.enabled)){n2(R);return}m.current(R,B),P||(i.current=!0)}})}},E=function(R){R.key!==void 0&&(SP(hs(R.code)),((p==null?void 0:p.keydown)===void 0&&(p==null?void 0:p.keyup)!==!0||p!=null&&p.keydown)&&S(R))},_=function(R){R.key!==void 0&&(_P(hs(R.code)),i.current=!1,p!=null&&p.keyup&&S(R,!0))},b=o.current||(s==null?void 0:s.document)||document;return b.addEventListener("keyup",_),b.addEventListener("keydown",E),x&&T0(l,p==null?void 0:p.splitKey).forEach(function(C){return x.addHotkey(P0(C,p==null?void 0:p.combinationKey,p==null?void 0:p.description))}),function(){b.removeEventListener("keyup",_),b.removeEventListener("keydown",E),x&&T0(l,p==null?void 0:p.splitKey).forEach(function(C){return x.removeHotkey(P0(C,p==null?void 0:p.combinationKey,p==null?void 0:p.description))})}}},[l,p,y]),o}const Zn=(e,t,n)=>{const r=bt(i=>i.disableShortCuts);return PW(e,t,{enabled:!r},n)};function ur(e){const{content:t,keys:n}=e;return v.jsxs("div",{className:"flex justify-between",children:[v.jsx("div",{children:t}),v.jsx("div",{className:"flex gap-[8px]",children:n.map(r=>v.jsx("div",{className:"border px-2 py-1 rounded-lg",children:r},r))})]})}const AW=function(){return/macintosh|mac os x/i.test(navigator.userAgent)},yh=()=>AW()?"Cmd":"Ctrl";function MW(){const[e,t]=QT(!1);return Zn("h",()=>{t()}),v.jsxs(Jm,{open:e,onOpenChange:t,children:[v.jsx(kx,{asChild:!0,children:v.jsx(yn,{tooltip:"Hotkeys",children:v.jsx(nV,{})})}),v.jsx(Hd,{children:v.jsxs(xP,{children:[v.jsx(Kd,{children:"Hotkeys"}),v.jsxs("div",{className:"flex gap-2 flex-col pt-4",children:[v.jsx(ur,{content:"Pan",keys:["Space + Drag"]}),v.jsx(ur,{content:"Reset Zoom/Pan",keys:["Esc"]}),v.jsx(ur,{content:"Decrease Brush Size",keys:["["]}),v.jsx(ur,{content:"Increase Brush Size",keys:["]"]}),v.jsx(ur,{content:"View Original Image",keys:["Hold Tab"]}),v.jsx(ur,{content:"Undo",keys:[yh(),"Z"]}),v.jsx(ur,{content:"Redo",keys:[yh(),"Shift","Z"]}),v.jsx(ur,{content:"Copy Result",keys:[yh(),"C"]}),v.jsx(ur,{content:"Paste Image",keys:[yh(),"V"]}),v.jsx(ur,{content:"Trigger Manually Inpainting",keys:["Shift","R"]}),v.jsx(ur,{content:"Toggle Hotkeys Dialog",keys:["H"]}),v.jsx(ur,{content:"Toggle Settings Dialog",keys:["S"]}),v.jsx(ur,{content:"Toggle File Manager",keys:["F"]})]})]})})]})}function Px(e){const[t]=d.useState(new Image),[n,r]=d.useState(!1);return d.useEffect(()=>{if(e)return t.onload=()=>{r(!0)},r(!1),t.src=URL.createObjectURL(e),()=>{t.onload=null}},[e,t]),[t,n]}const $P="Popover",[RP,wte]=Mn($P,[Fs]),Ax=Fs(),[OW,Rc]=RP($P),NW=e=>{const{__scopePopover:t,children:n,open:r,defaultOpen:o,onOpenChange:i,modal:s=!1}=e,l=Ax(t),u=d.useRef(null),[f,m]=d.useState(!1),[p=!1,g]=Zr({prop:r,defaultProp:o,onChange:i});return d.createElement(jd,l,d.createElement(OW,{scope:t,contentId:nr(),triggerRef:u,open:p,onOpenChange:g,onOpenToggle:d.useCallback(()=>g(y=>!y),[g]),hasCustomAnchor:f,onCustomAnchorAdd:d.useCallback(()=>m(!0),[]),onCustomAnchorRemove:d.useCallback(()=>m(!1),[]),modal:s},n))},DW="PopoverTrigger",IW=d.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,o=Rc(DW,n),i=Ax(n),s=Ue(t,o.triggerRef),l=d.createElement(Ae.button,Y({type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":PP(o.open)},r,{ref:s,onClick:ue(e.onClick,o.onOpenToggle)}));return o.hasCustomAnchor?l:d.createElement(Vm,Y({asChild:!0},i),l)}),kP="PopoverPortal",[LW,FW]=RP(kP,{forceMount:void 0}),jW=e=>{const{__scopePopover:t,forceMount:n,children:r,container:o}=e,i=Rc(kP,t);return d.createElement(LW,{scope:t,forceMount:n},d.createElement(Sn,{present:n||i.open},d.createElement(zd,{asChild:!0,container:o},r)))},dd="PopoverContent",zW=d.forwardRef((e,t)=>{const n=FW(dd,e.__scopePopover),{forceMount:r=n.forceMount,...o}=e,i=Rc(dd,e.__scopePopover);return d.createElement(Sn,{present:r||i.open},i.modal?d.createElement(BW,Y({},o,{ref:t})):d.createElement(UW,Y({},o,{ref:t})))}),BW=d.forwardRef((e,t)=>{const n=Rc(dd,e.__scopePopover),r=d.useRef(null),o=Ue(t,r),i=d.useRef(!1);return d.useEffect(()=>{const s=r.current;if(s)return Qm(s)},[]),d.createElement(qm,{as:Zo,allowPinchZoom:!0},d.createElement(TP,Y({},e,{ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:ue(e.onCloseAutoFocus,s=>{var l;s.preventDefault(),i.current||(l=n.triggerRef.current)===null||l===void 0||l.focus()}),onPointerDownOutside:ue(e.onPointerDownOutside,s=>{const l=s.detail.originalEvent,u=l.button===0&&l.ctrlKey===!0,f=l.button===2||u;i.current=f},{checkForDefaultPrevented:!1}),onFocusOutside:ue(e.onFocusOutside,s=>s.preventDefault(),{checkForDefaultPrevented:!1})})))}),UW=d.forwardRef((e,t)=>{const n=Rc(dd,e.__scopePopover),r=d.useRef(!1),o=d.useRef(!1);return d.createElement(TP,Y({},e,{ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var s;if((s=e.onCloseAutoFocus)===null||s===void 0||s.call(e,i),!i.defaultPrevented){var l;r.current||(l=n.triggerRef.current)===null||l===void 0||l.focus(),i.preventDefault()}r.current=!1,o.current=!1},onInteractOutside:i=>{var s,l;(s=e.onInteractOutside)===null||s===void 0||s.call(e,i),i.defaultPrevented||(r.current=!0,i.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const u=i.target;((l=n.triggerRef.current)===null||l===void 0?void 0:l.contains(u))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&o.current&&i.preventDefault()}}))}),TP=d.forwardRef((e,t)=>{const{__scopePopover:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:i,disableOutsidePointerEvents:s,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:f,onInteractOutside:m,...p}=e,g=Rc(dd,n),y=Ax(n);return Xm(),d.createElement(Ym,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:i},d.createElement(Ec,{asChild:!0,disableOutsidePointerEvents:s,onInteractOutside:m,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:f,onDismiss:()=>g.onOpenChange(!1)},d.createElement(Wm,Y({"data-state":PP(g.open),role:"dialog",id:g.contentId},y,p,{ref:t,style:{...p.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}}))))});function PP(e){return e?"open":"closed"}const VW=NW,WW=IW,HW=jW,AP=zW,KW=VW,GW=WW,MP=d.forwardRef(({className:e,align:t="center",sideOffset:n=4,...r},o)=>v.jsx(HW,{children:v.jsx(AP,{ref:o,align:t,tabIndex:-1,sideOffset:n,className:Ce("z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...r})}));MP.displayName=AP.displayName;function YW(){var e=d.useRef(!0);return e.current?(e.current=!1,!0):e.current}var XW=function(e,t){var n=YW();d.useEffect(function(){if(!n)return e()},t)};const ZW=XW;var qW=function(){};function Mx(e){for(var t=[],n=1;n{const[e,t,n,r,o,i]=bt(g=>[g.getIsProcessing(),g.settings.prompt,g.updateSettings,g.runInpainting,g.showPrevMask,g.hidePrevMask]),s=d.useRef(null);NP(s,()=>{s!=null&&s.current&&s.current.blur()});const l=g=>{g.preventDefault(),g.stopPropagation();const y=g.target;n({prompt:y.value})},u=()=>{e||r()},f=g=>{g.key==="Enter"&&!e&&u()},m=()=>{o()},p=()=>{i()};return v.jsxs("div",{className:"flex gap-4 items-center",children:[v.jsx(Ld,{ref:s,className:"min-w-[500px]",value:t,onInput:l,onKeyUp:f,placeholder:"I want to repaint of..."}),v.jsx(wn,{size:"sm",onClick:u,disabled:e,onMouseEnter:m,onMouseLeave:p,children:"Paint"})]})};var zp={exports:{}};/** + * @license + * Lodash + * Copyright OpenJS Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */zp.exports;(function(e,t){(function(){var n,r="4.17.21",o=200,i="Unsupported core-js use. Try https://npms.io/search?q=ponyfill.",s="Expected a function",l="Invalid `variable` option passed into `_.template`",u="__lodash_hash_undefined__",f=500,m="__lodash_placeholder__",p=1,g=2,y=4,x=1,S=2,E=1,_=2,b=4,C=8,R=16,P=32,O=64,A=128,D=256,B=512,V=30,J="...",G=800,se=16,U=1,ne=2,M=3,ee=1/0,H=9007199254740991,X=17976931348623157e292,W=NaN,le=4294967295,pe=le-1,$e=le>>>1,Ve=[["ary",A],["bind",E],["bindKey",_],["curry",C],["curryRight",R],["flip",B],["partial",P],["partialRight",O],["rearg",D]],We="[object Arguments]",Ne="[object Array]",fe="[object AsyncFunction]",xe="[object Boolean]",Re="[object Date]",Me="[object DOMException]",Oe="[object Error]",ze="[object Function]",Mt="[object GeneratorFunction]",ct="[object Map]",Kt="[object Number]",Er="[object Null]",gt="[object Object]",Vs="[object Promise]",L="[object Proxy]",Z="[object RegExp]",q="[object Set]",we="[object String]",me="[object Symbol]",de="[object Undefined]",ke="[object WeakMap]",ft="[object WeakSet]",ht="[object ArrayBuffer]",_n="[object DataView]",Cr="[object Float32Array]",Ni="[object Float64Array]",Co="[object Int8Array]",Vn="[object Int16Array]",Ba="[object Int32Array]",Di="[object Uint8Array]",Ws="[object Uint8ClampedArray]",Ii="[object Uint16Array]",Mc="[object Uint32Array]",bg=/\b__p \+= '';/g,Sg=/\b(__p \+=) '' \+/g,Jd=/(__e\(.*?\)|\b__t\)) \+\n'';/g,Oc=/&(?:amp|lt|gt|quot|#39);/g,Nc=/[&<>"']/g,Dc=RegExp(Oc.source),_g=RegExp(Nc.source),Ic=/<%-([\s\S]+?)%>/g,ef=/<%([\s\S]+?)%>/g,Lc=/<%=([\s\S]+?)%>/g,Eg=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Cg=/^\w*$/,$g=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,K=/[\\^$.*+?()[\]{}|]/g,Ye=RegExp(K.source),st=/^\s+/,Qr=/\s/,an=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,tf=/\{\n\/\* \[wrapped with (.+)\] \*/,aM=/,? & /,lM=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,cM=/[()=,{}\[\]\/\s]/,uM=/\\(\\)?/g,dM=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,hb=/\w*$/,fM=/^[-+]0x[0-9a-f]+$/i,hM=/^0b[01]+$/i,pM=/^\[object .+?Constructor\]$/,mM=/^0o[0-7]+$/i,gM=/^(?:0|[1-9]\d*)$/,vM=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,nf=/($^)/,yM=/['\n\r\u2028\u2029\\]/g,rf="\\ud800-\\udfff",wM="\\u0300-\\u036f",xM="\\ufe20-\\ufe2f",bM="\\u20d0-\\u20ff",pb=wM+xM+bM,mb="\\u2700-\\u27bf",gb="a-z\\xdf-\\xf6\\xf8-\\xff",SM="\\xac\\xb1\\xd7\\xf7",_M="\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf",EM="\\u2000-\\u206f",CM=" \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",vb="A-Z\\xc0-\\xd6\\xd8-\\xde",yb="\\ufe0e\\ufe0f",wb=SM+_M+EM+CM,Rg="['’]",$M="["+rf+"]",xb="["+wb+"]",of="["+pb+"]",bb="\\d+",RM="["+mb+"]",Sb="["+gb+"]",_b="[^"+rf+wb+bb+mb+gb+vb+"]",kg="\\ud83c[\\udffb-\\udfff]",kM="(?:"+of+"|"+kg+")",Eb="[^"+rf+"]",Tg="(?:\\ud83c[\\udde6-\\uddff]){2}",Pg="[\\ud800-\\udbff][\\udc00-\\udfff]",Ua="["+vb+"]",Cb="\\u200d",$b="(?:"+Sb+"|"+_b+")",TM="(?:"+Ua+"|"+_b+")",Rb="(?:"+Rg+"(?:d|ll|m|re|s|t|ve))?",kb="(?:"+Rg+"(?:D|LL|M|RE|S|T|VE))?",Tb=kM+"?",Pb="["+yb+"]?",PM="(?:"+Cb+"(?:"+[Eb,Tg,Pg].join("|")+")"+Pb+Tb+")*",AM="\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",MM="\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])",Ab=Pb+Tb+PM,OM="(?:"+[RM,Tg,Pg].join("|")+")"+Ab,NM="(?:"+[Eb+of+"?",of,Tg,Pg,$M].join("|")+")",DM=RegExp(Rg,"g"),IM=RegExp(of,"g"),Ag=RegExp(kg+"(?="+kg+")|"+NM+Ab,"g"),LM=RegExp([Ua+"?"+Sb+"+"+Rb+"(?="+[xb,Ua,"$"].join("|")+")",TM+"+"+kb+"(?="+[xb,Ua+$b,"$"].join("|")+")",Ua+"?"+$b+"+"+Rb,Ua+"+"+kb,MM,AM,bb,OM].join("|"),"g"),FM=RegExp("["+Cb+rf+pb+yb+"]"),jM=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,zM=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],BM=-1,Rt={};Rt[Cr]=Rt[Ni]=Rt[Co]=Rt[Vn]=Rt[Ba]=Rt[Di]=Rt[Ws]=Rt[Ii]=Rt[Mc]=!0,Rt[We]=Rt[Ne]=Rt[ht]=Rt[xe]=Rt[_n]=Rt[Re]=Rt[Oe]=Rt[ze]=Rt[ct]=Rt[Kt]=Rt[gt]=Rt[Z]=Rt[q]=Rt[we]=Rt[ke]=!1;var Et={};Et[We]=Et[Ne]=Et[ht]=Et[_n]=Et[xe]=Et[Re]=Et[Cr]=Et[Ni]=Et[Co]=Et[Vn]=Et[Ba]=Et[ct]=Et[Kt]=Et[gt]=Et[Z]=Et[q]=Et[we]=Et[me]=Et[Di]=Et[Ws]=Et[Ii]=Et[Mc]=!0,Et[Oe]=Et[ze]=Et[ke]=!1;var UM={À:"A",Á:"A",Â:"A",Ã:"A",Ä:"A",Å:"A",à:"a",á:"a",â:"a",ã:"a",ä:"a",å:"a",Ç:"C",ç:"c",Ð:"D",ð:"d",È:"E",É:"E",Ê:"E",Ë:"E",è:"e",é:"e",ê:"e",ë:"e",Ì:"I",Í:"I",Î:"I",Ï:"I",ì:"i",í:"i",î:"i",ï:"i",Ñ:"N",ñ:"n",Ò:"O",Ó:"O",Ô:"O",Õ:"O",Ö:"O",Ø:"O",ò:"o",ó:"o",ô:"o",õ:"o",ö:"o",ø:"o",Ù:"U",Ú:"U",Û:"U",Ü:"U",ù:"u",ú:"u",û:"u",ü:"u",Ý:"Y",ý:"y",ÿ:"y",Æ:"Ae",æ:"ae",Þ:"Th",þ:"th",ß:"ss",Ā:"A",Ă:"A",Ą:"A",ā:"a",ă:"a",ą:"a",Ć:"C",Ĉ:"C",Ċ:"C",Č:"C",ć:"c",ĉ:"c",ċ:"c",č:"c",Ď:"D",Đ:"D",ď:"d",đ:"d",Ē:"E",Ĕ:"E",Ė:"E",Ę:"E",Ě:"E",ē:"e",ĕ:"e",ė:"e",ę:"e",ě:"e",Ĝ:"G",Ğ:"G",Ġ:"G",Ģ:"G",ĝ:"g",ğ:"g",ġ:"g",ģ:"g",Ĥ:"H",Ħ:"H",ĥ:"h",ħ:"h",Ĩ:"I",Ī:"I",Ĭ:"I",Į:"I",İ:"I",ĩ:"i",ī:"i",ĭ:"i",į:"i",ı:"i",Ĵ:"J",ĵ:"j",Ķ:"K",ķ:"k",ĸ:"k",Ĺ:"L",Ļ:"L",Ľ:"L",Ŀ:"L",Ł:"L",ĺ:"l",ļ:"l",ľ:"l",ŀ:"l",ł:"l",Ń:"N",Ņ:"N",Ň:"N",Ŋ:"N",ń:"n",ņ:"n",ň:"n",ŋ:"n",Ō:"O",Ŏ:"O",Ő:"O",ō:"o",ŏ:"o",ő:"o",Ŕ:"R",Ŗ:"R",Ř:"R",ŕ:"r",ŗ:"r",ř:"r",Ś:"S",Ŝ:"S",Ş:"S",Š:"S",ś:"s",ŝ:"s",ş:"s",š:"s",Ţ:"T",Ť:"T",Ŧ:"T",ţ:"t",ť:"t",ŧ:"t",Ũ:"U",Ū:"U",Ŭ:"U",Ů:"U",Ű:"U",Ų:"U",ũ:"u",ū:"u",ŭ:"u",ů:"u",ű:"u",ų:"u",Ŵ:"W",ŵ:"w",Ŷ:"Y",ŷ:"y",Ÿ:"Y",Ź:"Z",Ż:"Z",Ž:"Z",ź:"z",ż:"z",ž:"z",IJ:"IJ",ij:"ij",Œ:"Oe",œ:"oe",ʼn:"'n",ſ:"s"},VM={"&":"&","<":"<",">":">",'"':""","'":"'"},WM={"&":"&","<":"<",">":">",""":'"',"'":"'"},HM={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},KM=parseFloat,GM=parseInt,Mb=typeof Jc=="object"&&Jc&&Jc.Object===Object&&Jc,YM=typeof self=="object"&&self&&self.Object===Object&&self,fn=Mb||YM||Function("return this")(),Mg=t&&!t.nodeType&&t,Hs=Mg&&!0&&e&&!e.nodeType&&e,Ob=Hs&&Hs.exports===Mg,Og=Ob&&Mb.process,$r=function(){try{var F=Hs&&Hs.require&&Hs.require("util").types;return F||Og&&Og.binding&&Og.binding("util")}catch{}}(),Nb=$r&&$r.isArrayBuffer,Db=$r&&$r.isDate,Ib=$r&&$r.isMap,Lb=$r&&$r.isRegExp,Fb=$r&&$r.isSet,jb=$r&&$r.isTypedArray;function or(F,te,Q){switch(Q.length){case 0:return F.call(te);case 1:return F.call(te,Q[0]);case 2:return F.call(te,Q[0],Q[1]);case 3:return F.call(te,Q[0],Q[1],Q[2])}return F.apply(te,Q)}function XM(F,te,Q,Se){for(var Ke=-1,pt=F==null?0:F.length;++Ke-1}function Ng(F,te,Q){for(var Se=-1,Ke=F==null?0:F.length;++Se-1;);return Q}function Gb(F,te){for(var Q=F.length;Q--&&Va(te,F[Q],0)>-1;);return Q}function oO(F,te){for(var Q=F.length,Se=0;Q--;)F[Q]===te&&++Se;return Se}var iO=Fg(UM),sO=Fg(VM);function aO(F){return"\\"+HM[F]}function lO(F,te){return F==null?n:F[te]}function Wa(F){return FM.test(F)}function cO(F){return jM.test(F)}function uO(F){for(var te,Q=[];!(te=F.next()).done;)Q.push(te.value);return Q}function Ug(F){var te=-1,Q=Array(F.size);return F.forEach(function(Se,Ke){Q[++te]=[Ke,Se]}),Q}function Yb(F,te){return function(Q){return F(te(Q))}}function ji(F,te){for(var Q=-1,Se=F.length,Ke=0,pt=[];++Q-1}function qO(a,c){var h=this.__data__,w=_f(h,a);return w<0?(++this.size,h.push([a,c])):h[w][1]=c,this}ti.prototype.clear=GO,ti.prototype.delete=YO,ti.prototype.get=XO,ti.prototype.has=ZO,ti.prototype.set=qO;function ni(a){var c=-1,h=a==null?0:a.length;for(this.clear();++c=c?a:c)),a}function Pr(a,c,h,w,$,T){var N,I=c&p,z=c&g,re=c&y;if(h&&(N=$?h(a,w,$,T):h(a)),N!==n)return N;if(!It(a))return a;var oe=Ge(a);if(oe){if(N=tN(a),!I)return Wn(a,N)}else{var ae=Cn(a),ge=ae==ze||ae==Mt;if(Hi(a))return PS(a,I);if(ae==gt||ae==We||ge&&!$){if(N=z||ge?{}:XS(a),!I)return z?W6(a,h6(N,a)):V6(a,sS(N,a))}else{if(!Et[ae])return $?a:{};N=nN(a,ae,I)}}T||(T=new eo);var Te=T.get(a);if(Te)return Te;T.set(a,N),E_(a)?a.forEach(function(Fe){N.add(Pr(Fe,c,h,Fe,a,T))}):S_(a)&&a.forEach(function(Fe,nt){N.set(nt,Pr(Fe,c,h,nt,a,T))});var Le=re?z?pv:hv:z?Kn:ln,Qe=oe?n:Le(a);return Rr(Qe||a,function(Fe,nt){Qe&&(nt=Fe,Fe=a[nt]),Wc(N,nt,Pr(Fe,c,h,nt,a,T))}),N}function p6(a){var c=ln(a);return function(h){return aS(h,a,c)}}function aS(a,c,h){var w=h.length;if(a==null)return!w;for(a=St(a);w--;){var $=h[w],T=c[$],N=a[$];if(N===n&&!($ in a)||!T(N))return!1}return!0}function lS(a,c,h){if(typeof a!="function")throw new kr(s);return qc(function(){a.apply(n,h)},c)}function Hc(a,c,h,w){var $=-1,T=sf,N=!0,I=a.length,z=[],re=c.length;if(!I)return z;h&&(c=Ot(c,ir(h))),w?(T=Ng,N=!1):c.length>=o&&(T=Fc,N=!1,c=new Ys(c));e:for(;++$$?0:$+h),w=w===n||w>$?$:qe(w),w<0&&(w+=$),w=h>w?0:$_(w);h0&&h(I)?c>1?hn(I,c-1,h,w,$):Fi($,I):w||($[$.length]=I)}return $}var Xg=IS(),dS=IS(!0);function $o(a,c){return a&&Xg(a,c,ln)}function Zg(a,c){return a&&dS(a,c,ln)}function Cf(a,c){return Li(c,function(h){return ai(a[h])})}function Zs(a,c){c=Vi(c,a);for(var h=0,w=c.length;a!=null&&hc}function v6(a,c){return a!=null&&yt.call(a,c)}function y6(a,c){return a!=null&&c in St(a)}function w6(a,c,h){return a>=En(c,h)&&a=120&&oe.length>=120)?new Ys(N&&oe):n}oe=a[0];var ae=-1,ge=I[0];e:for(;++ae<$&&re.length-1;)I!==a&&gf.call(I,z,1),gf.call(a,z,1);return a}function SS(a,c){for(var h=a?c.length:0,w=h-1;h--;){var $=c[h];if(h==w||$!==T){var T=$;si($)?gf.call(a,$,1):sv(a,$)}}return a}function rv(a,c){return a+wf(nS()*(c-a+1))}function M6(a,c,h,w){for(var $=-1,T=tn(yf((c-a)/(h||1)),0),N=Q(T);T--;)N[w?T:++$]=a,a+=h;return N}function ov(a,c){var h="";if(!a||c<1||c>H)return h;do c%2&&(h+=a),c=wf(c/2),c&&(a+=a);while(c);return h}function et(a,c){return bv(QS(a,c,Gn),a+"")}function O6(a){return iS(tl(a))}function N6(a,c){var h=tl(a);return If(h,Xs(c,0,h.length))}function Yc(a,c,h,w){if(!It(a))return a;c=Vi(c,a);for(var $=-1,T=c.length,N=T-1,I=a;I!=null&&++$$?0:$+c),h=h>$?$:h,h<0&&(h+=$),$=c>h?0:h-c>>>0,c>>>=0;for(var T=Q($);++w<$;)T[w]=a[w+c];return T}function L6(a,c){var h;return Bi(a,function(w,$,T){return h=c(w,$,T),!h}),!!h}function Rf(a,c,h){var w=0,$=a==null?w:a.length;if(typeof c=="number"&&c===c&&$<=$e){for(;w<$;){var T=w+$>>>1,N=a[T];N!==null&&!ar(N)&&(h?N<=c:N=o){var re=c?null:Y6(a);if(re)return lf(re);N=!1,$=Fc,z=new Ys}else z=c?[]:I;e:for(;++w=w?a:Ar(a,c,h)}var TS=CO||function(a){return fn.clearTimeout(a)};function PS(a,c){if(c)return a.slice();var h=a.length,w=qb?qb(h):new a.constructor(h);return a.copy(w),w}function uv(a){var c=new a.constructor(a.byteLength);return new pf(c).set(new pf(a)),c}function j6(a,c){var h=c?uv(a.buffer):a.buffer;return new a.constructor(h,a.byteOffset,a.byteLength)}function z6(a){var c=new a.constructor(a.source,hb.exec(a));return c.lastIndex=a.lastIndex,c}function B6(a){return Vc?St(Vc.call(a)):{}}function AS(a,c){var h=c?uv(a.buffer):a.buffer;return new a.constructor(h,a.byteOffset,a.length)}function MS(a,c){if(a!==c){var h=a!==n,w=a===null,$=a===a,T=ar(a),N=c!==n,I=c===null,z=c===c,re=ar(c);if(!I&&!re&&!T&&a>c||T&&N&&z&&!I&&!re||w&&N&&z||!h&&z||!$)return 1;if(!w&&!T&&!re&&a=I)return z;var re=h[w];return z*(re=="desc"?-1:1)}}return a.index-c.index}function OS(a,c,h,w){for(var $=-1,T=a.length,N=h.length,I=-1,z=c.length,re=tn(T-N,0),oe=Q(z+re),ae=!w;++I1?h[$-1]:n,N=$>2?h[2]:n;for(T=a.length>3&&typeof T=="function"?($--,T):n,N&&Nn(h[0],h[1],N)&&(T=$<3?n:T,$=1),c=St(c);++w<$;){var I=h[w];I&&a(c,I,w,T)}return c})}function DS(a,c){return function(h,w){if(h==null)return h;if(!Hn(h))return a(h,w);for(var $=h.length,T=c?$:-1,N=St(h);(c?T--:++T<$)&&w(N[T],T,N)!==!1;);return h}}function IS(a){return function(c,h,w){for(var $=-1,T=St(c),N=w(c),I=N.length;I--;){var z=N[a?I:++$];if(h(T[z],z,T)===!1)break}return c}}function H6(a,c,h){var w=c&E,$=Xc(a);function T(){var N=this&&this!==fn&&this instanceof T?$:a;return N.apply(w?h:this,arguments)}return T}function LS(a){return function(c){c=vt(c);var h=Wa(c)?Jr(c):n,w=h?h[0]:c.charAt(0),$=h?Wi(h,1).join(""):c.slice(1);return w[a]()+$}}function Qa(a){return function(c){return Dg(D_(N_(c).replace(DM,"")),a,"")}}function Xc(a){return function(){var c=arguments;switch(c.length){case 0:return new a;case 1:return new a(c[0]);case 2:return new a(c[0],c[1]);case 3:return new a(c[0],c[1],c[2]);case 4:return new a(c[0],c[1],c[2],c[3]);case 5:return new a(c[0],c[1],c[2],c[3],c[4]);case 6:return new a(c[0],c[1],c[2],c[3],c[4],c[5]);case 7:return new a(c[0],c[1],c[2],c[3],c[4],c[5],c[6])}var h=Za(a.prototype),w=a.apply(h,c);return It(w)?w:h}}function K6(a,c,h){var w=Xc(a);function $(){for(var T=arguments.length,N=Q(T),I=T,z=Ja($);I--;)N[I]=arguments[I];var re=T<3&&N[0]!==z&&N[T-1]!==z?[]:ji(N,z);if(T-=re.length,T-1?$[T?c[N]:N]:n}}function jS(a){return ii(function(c){var h=c.length,w=h,$=Tr.prototype.thru;for(a&&c.reverse();w--;){var T=c[w];if(typeof T!="function")throw new kr(s);if($&&!N&&Nf(T)=="wrapper")var N=new Tr([],!0)}for(w=N?w:h;++w1&&at.reverse(),oe&&zI))return!1;var re=T.get(a),oe=T.get(c);if(re&&oe)return re==c&&oe==a;var ae=-1,ge=!0,Te=h&S?new Ys:n;for(T.set(a,c),T.set(c,a);++ae1?"& ":"")+c[w],c=c.join(h>2?", ":" "),a.replace(an,`{ +/* [wrapped with `+c+`] */ +`)}function oN(a){return Ge(a)||Js(a)||!!(eS&&a&&a[eS])}function si(a,c){var h=typeof a;return c=c??H,!!c&&(h=="number"||h!="symbol"&&gM.test(a))&&a>-1&&a%1==0&&a0){if(++c>=G)return arguments[0]}else c=0;return a.apply(n,arguments)}}function If(a,c){var h=-1,w=a.length,$=w-1;for(c=c===n?w:c;++h1?a[c-1]:n;return h=typeof h=="function"?(a.pop(),h):n,u_(a,h)});function d_(a){var c=k(a);return c.__chain__=!0,c}function m7(a,c){return c(a),a}function Lf(a,c){return c(a)}var g7=ii(function(a){var c=a.length,h=c?a[0]:0,w=this.__wrapped__,$=function(T){return Yg(T,a)};return c>1||this.__actions__.length||!(w instanceof ot)||!si(h)?this.thru($):(w=w.slice(h,+h+(c?1:0)),w.__actions__.push({func:Lf,args:[$],thisArg:n}),new Tr(w,this.__chain__).thru(function(T){return c&&!T.length&&T.push(n),T}))});function v7(){return d_(this)}function y7(){return new Tr(this.value(),this.__chain__)}function w7(){this.__values__===n&&(this.__values__=C_(this.value()));var a=this.__index__>=this.__values__.length,c=a?n:this.__values__[this.__index__++];return{done:a,value:c}}function x7(){return this}function b7(a){for(var c,h=this;h instanceof Sf;){var w=o_(h);w.__index__=0,w.__values__=n,c?$.__wrapped__=w:c=w;var $=w;h=h.__wrapped__}return $.__wrapped__=a,c}function S7(){var a=this.__wrapped__;if(a instanceof ot){var c=a;return this.__actions__.length&&(c=new ot(this)),c=c.reverse(),c.__actions__.push({func:Lf,args:[Sv],thisArg:n}),new Tr(c,this.__chain__)}return this.thru(Sv)}function _7(){return RS(this.__wrapped__,this.__actions__)}var E7=Tf(function(a,c,h){yt.call(a,h)?++a[h]:ri(a,h,1)});function C7(a,c,h){var w=Ge(a)?zb:m6;return h&&Nn(a,c,h)&&(c=n),w(a,Ie(c,3))}function $7(a,c){var h=Ge(a)?Li:uS;return h(a,Ie(c,3))}var R7=FS(i_),k7=FS(s_);function T7(a,c){return hn(Ff(a,c),1)}function P7(a,c){return hn(Ff(a,c),ee)}function A7(a,c,h){return h=h===n?1:qe(h),hn(Ff(a,c),h)}function f_(a,c){var h=Ge(a)?Rr:Bi;return h(a,Ie(c,3))}function h_(a,c){var h=Ge(a)?ZM:cS;return h(a,Ie(c,3))}var M7=Tf(function(a,c,h){yt.call(a,h)?a[h].push(c):ri(a,h,[c])});function O7(a,c,h,w){a=Hn(a)?a:tl(a),h=h&&!w?qe(h):0;var $=a.length;return h<0&&(h=tn($+h,0)),Vf(a)?h<=$&&a.indexOf(c,h)>-1:!!$&&Va(a,c,h)>-1}var N7=et(function(a,c,h){var w=-1,$=typeof c=="function",T=Hn(a)?Q(a.length):[];return Bi(a,function(N){T[++w]=$?or(c,N,h):Kc(N,c,h)}),T}),D7=Tf(function(a,c,h){ri(a,h,c)});function Ff(a,c){var h=Ge(a)?Ot:gS;return h(a,Ie(c,3))}function I7(a,c,h,w){return a==null?[]:(Ge(c)||(c=c==null?[]:[c]),h=w?n:h,Ge(h)||(h=h==null?[]:[h]),xS(a,c,h))}var L7=Tf(function(a,c,h){a[h?0:1].push(c)},function(){return[[],[]]});function F7(a,c,h){var w=Ge(a)?Dg:Wb,$=arguments.length<3;return w(a,Ie(c,4),h,$,Bi)}function j7(a,c,h){var w=Ge(a)?qM:Wb,$=arguments.length<3;return w(a,Ie(c,4),h,$,cS)}function z7(a,c){var h=Ge(a)?Li:uS;return h(a,Bf(Ie(c,3)))}function B7(a){var c=Ge(a)?iS:O6;return c(a)}function U7(a,c,h){(h?Nn(a,c,h):c===n)?c=1:c=qe(c);var w=Ge(a)?u6:N6;return w(a,c)}function V7(a){var c=Ge(a)?d6:I6;return c(a)}function W7(a){if(a==null)return 0;if(Hn(a))return Vf(a)?Ha(a):a.length;var c=Cn(a);return c==ct||c==q?a.size:ev(a).length}function H7(a,c,h){var w=Ge(a)?Ig:L6;return h&&Nn(a,c,h)&&(c=n),w(a,Ie(c,3))}var K7=et(function(a,c){if(a==null)return[];var h=c.length;return h>1&&Nn(a,c[0],c[1])?c=[]:h>2&&Nn(c[0],c[1],c[2])&&(c=[c[0]]),xS(a,hn(c,1),[])}),jf=$O||function(){return fn.Date.now()};function G7(a,c){if(typeof c!="function")throw new kr(s);return a=qe(a),function(){if(--a<1)return c.apply(this,arguments)}}function p_(a,c,h){return c=h?n:c,c=a&&c==null?a.length:c,oi(a,A,n,n,n,n,c)}function m_(a,c){var h;if(typeof c!="function")throw new kr(s);return a=qe(a),function(){return--a>0&&(h=c.apply(this,arguments)),a<=1&&(c=n),h}}var Ev=et(function(a,c,h){var w=E;if(h.length){var $=ji(h,Ja(Ev));w|=P}return oi(a,w,c,h,$)}),g_=et(function(a,c,h){var w=E|_;if(h.length){var $=ji(h,Ja(g_));w|=P}return oi(c,w,a,h,$)});function v_(a,c,h){c=h?n:c;var w=oi(a,C,n,n,n,n,n,c);return w.placeholder=v_.placeholder,w}function y_(a,c,h){c=h?n:c;var w=oi(a,R,n,n,n,n,n,c);return w.placeholder=y_.placeholder,w}function w_(a,c,h){var w,$,T,N,I,z,re=0,oe=!1,ae=!1,ge=!0;if(typeof a!="function")throw new kr(s);c=Or(c)||0,It(h)&&(oe=!!h.leading,ae="maxWait"in h,T=ae?tn(Or(h.maxWait)||0,c):T,ge="trailing"in h?!!h.trailing:ge);function Te(Yt){var no=w,ci=$;return w=$=n,re=Yt,N=a.apply(ci,no),N}function Le(Yt){return re=Yt,I=qc(nt,c),oe?Te(Yt):N}function Qe(Yt){var no=Yt-z,ci=Yt-re,F_=c-no;return ae?En(F_,T-ci):F_}function Fe(Yt){var no=Yt-z,ci=Yt-re;return z===n||no>=c||no<0||ae&&ci>=T}function nt(){var Yt=jf();if(Fe(Yt))return at(Yt);I=qc(nt,Qe(Yt))}function at(Yt){return I=n,ge&&w?Te(Yt):(w=$=n,N)}function lr(){I!==n&&TS(I),re=0,w=z=$=I=n}function Dn(){return I===n?N:at(jf())}function cr(){var Yt=jf(),no=Fe(Yt);if(w=arguments,$=this,z=Yt,no){if(I===n)return Le(z);if(ae)return TS(I),I=qc(nt,c),Te(z)}return I===n&&(I=qc(nt,c)),N}return cr.cancel=lr,cr.flush=Dn,cr}var Y7=et(function(a,c){return lS(a,1,c)}),X7=et(function(a,c,h){return lS(a,Or(c)||0,h)});function Z7(a){return oi(a,B)}function zf(a,c){if(typeof a!="function"||c!=null&&typeof c!="function")throw new kr(s);var h=function(){var w=arguments,$=c?c.apply(this,w):w[0],T=h.cache;if(T.has($))return T.get($);var N=a.apply(this,w);return h.cache=T.set($,N)||T,N};return h.cache=new(zf.Cache||ni),h}zf.Cache=ni;function Bf(a){if(typeof a!="function")throw new kr(s);return function(){var c=arguments;switch(c.length){case 0:return!a.call(this);case 1:return!a.call(this,c[0]);case 2:return!a.call(this,c[0],c[1]);case 3:return!a.call(this,c[0],c[1],c[2])}return!a.apply(this,c)}}function q7(a){return m_(2,a)}var Q7=F6(function(a,c){c=c.length==1&&Ge(c[0])?Ot(c[0],ir(Ie())):Ot(hn(c,1),ir(Ie()));var h=c.length;return et(function(w){for(var $=-1,T=En(w.length,h);++$=c}),Js=hS(function(){return arguments}())?hS:function(a){return Bt(a)&&yt.call(a,"callee")&&!Jb.call(a,"callee")},Ge=Q.isArray,h4=Nb?ir(Nb):b6;function Hn(a){return a!=null&&Uf(a.length)&&!ai(a)}function Gt(a){return Bt(a)&&Hn(a)}function p4(a){return a===!0||a===!1||Bt(a)&&On(a)==xe}var Hi=kO||Iv,m4=Db?ir(Db):S6;function g4(a){return Bt(a)&&a.nodeType===1&&!Qc(a)}function v4(a){if(a==null)return!0;if(Hn(a)&&(Ge(a)||typeof a=="string"||typeof a.splice=="function"||Hi(a)||el(a)||Js(a)))return!a.length;var c=Cn(a);if(c==ct||c==q)return!a.size;if(Zc(a))return!ev(a).length;for(var h in a)if(yt.call(a,h))return!1;return!0}function y4(a,c){return Gc(a,c)}function w4(a,c,h){h=typeof h=="function"?h:n;var w=h?h(a,c):n;return w===n?Gc(a,c,n,h):!!w}function $v(a){if(!Bt(a))return!1;var c=On(a);return c==Oe||c==Me||typeof a.message=="string"&&typeof a.name=="string"&&!Qc(a)}function x4(a){return typeof a=="number"&&tS(a)}function ai(a){if(!It(a))return!1;var c=On(a);return c==ze||c==Mt||c==fe||c==L}function b_(a){return typeof a=="number"&&a==qe(a)}function Uf(a){return typeof a=="number"&&a>-1&&a%1==0&&a<=H}function It(a){var c=typeof a;return a!=null&&(c=="object"||c=="function")}function Bt(a){return a!=null&&typeof a=="object"}var S_=Ib?ir(Ib):E6;function b4(a,c){return a===c||Jg(a,c,gv(c))}function S4(a,c,h){return h=typeof h=="function"?h:n,Jg(a,c,gv(c),h)}function _4(a){return __(a)&&a!=+a}function E4(a){if(aN(a))throw new Ke(i);return pS(a)}function C4(a){return a===null}function $4(a){return a==null}function __(a){return typeof a=="number"||Bt(a)&&On(a)==Kt}function Qc(a){if(!Bt(a)||On(a)!=gt)return!1;var c=mf(a);if(c===null)return!0;var h=yt.call(c,"constructor")&&c.constructor;return typeof h=="function"&&h instanceof h&&df.call(h)==SO}var Rv=Lb?ir(Lb):C6;function R4(a){return b_(a)&&a>=-H&&a<=H}var E_=Fb?ir(Fb):$6;function Vf(a){return typeof a=="string"||!Ge(a)&&Bt(a)&&On(a)==we}function ar(a){return typeof a=="symbol"||Bt(a)&&On(a)==me}var el=jb?ir(jb):R6;function k4(a){return a===n}function T4(a){return Bt(a)&&Cn(a)==ke}function P4(a){return Bt(a)&&On(a)==ft}var A4=Of(tv),M4=Of(function(a,c){return a<=c});function C_(a){if(!a)return[];if(Hn(a))return Vf(a)?Jr(a):Wn(a);if(jc&&a[jc])return uO(a[jc]());var c=Cn(a),h=c==ct?Ug:c==q?lf:tl;return h(a)}function li(a){if(!a)return a===0?a:0;if(a=Or(a),a===ee||a===-ee){var c=a<0?-1:1;return c*X}return a===a?a:0}function qe(a){var c=li(a),h=c%1;return c===c?h?c-h:c:0}function $_(a){return a?Xs(qe(a),0,le):0}function Or(a){if(typeof a=="number")return a;if(ar(a))return W;if(It(a)){var c=typeof a.valueOf=="function"?a.valueOf():a;a=It(c)?c+"":c}if(typeof a!="string")return a===0?a:+a;a=Hb(a);var h=hM.test(a);return h||mM.test(a)?GM(a.slice(2),h?2:8):fM.test(a)?W:+a}function R_(a){return Ro(a,Kn(a))}function O4(a){return a?Xs(qe(a),-H,H):a===0?a:0}function vt(a){return a==null?"":sr(a)}var N4=qa(function(a,c){if(Zc(c)||Hn(c)){Ro(c,ln(c),a);return}for(var h in c)yt.call(c,h)&&Wc(a,h,c[h])}),k_=qa(function(a,c){Ro(c,Kn(c),a)}),Wf=qa(function(a,c,h,w){Ro(c,Kn(c),a,w)}),D4=qa(function(a,c,h,w){Ro(c,ln(c),a,w)}),I4=ii(Yg);function L4(a,c){var h=Za(a);return c==null?h:sS(h,c)}var F4=et(function(a,c){a=St(a);var h=-1,w=c.length,$=w>2?c[2]:n;for($&&Nn(c[0],c[1],$)&&(w=1);++h1),T}),Ro(a,pv(a),h),w&&(h=Pr(h,p|g|y,X6));for(var $=c.length;$--;)sv(h,c[$]);return h});function n8(a,c){return P_(a,Bf(Ie(c)))}var r8=ii(function(a,c){return a==null?{}:P6(a,c)});function P_(a,c){if(a==null)return{};var h=Ot(pv(a),function(w){return[w]});return c=Ie(c),bS(a,h,function(w,$){return c(w,$[0])})}function o8(a,c,h){c=Vi(c,a);var w=-1,$=c.length;for($||($=1,a=n);++w<$;){var T=a==null?n:a[ko(c[w])];T===n&&(w=$,T=h),a=ai(T)?T.call(a):T}return a}function i8(a,c,h){return a==null?a:Yc(a,c,h)}function s8(a,c,h,w){return w=typeof w=="function"?w:n,a==null?a:Yc(a,c,h,w)}var A_=VS(ln),M_=VS(Kn);function a8(a,c,h){var w=Ge(a),$=w||Hi(a)||el(a);if(c=Ie(c,4),h==null){var T=a&&a.constructor;$?h=w?new T:[]:It(a)?h=ai(T)?Za(mf(a)):{}:h={}}return($?Rr:$o)(a,function(N,I,z){return c(h,N,I,z)}),h}function l8(a,c){return a==null?!0:sv(a,c)}function c8(a,c,h){return a==null?a:$S(a,c,cv(h))}function u8(a,c,h,w){return w=typeof w=="function"?w:n,a==null?a:$S(a,c,cv(h),w)}function tl(a){return a==null?[]:Bg(a,ln(a))}function d8(a){return a==null?[]:Bg(a,Kn(a))}function f8(a,c,h){return h===n&&(h=c,c=n),h!==n&&(h=Or(h),h=h===h?h:0),c!==n&&(c=Or(c),c=c===c?c:0),Xs(Or(a),c,h)}function h8(a,c,h){return c=li(c),h===n?(h=c,c=0):h=li(h),a=Or(a),w6(a,c,h)}function p8(a,c,h){if(h&&typeof h!="boolean"&&Nn(a,c,h)&&(c=h=n),h===n&&(typeof c=="boolean"?(h=c,c=n):typeof a=="boolean"&&(h=a,a=n)),a===n&&c===n?(a=0,c=1):(a=li(a),c===n?(c=a,a=0):c=li(c)),a>c){var w=a;a=c,c=w}if(h||a%1||c%1){var $=nS();return En(a+$*(c-a+KM("1e-"+(($+"").length-1))),c)}return rv(a,c)}var m8=Qa(function(a,c,h){return c=c.toLowerCase(),a+(h?O_(c):c)});function O_(a){return Pv(vt(a).toLowerCase())}function N_(a){return a=vt(a),a&&a.replace(vM,iO).replace(IM,"")}function g8(a,c,h){a=vt(a),c=sr(c);var w=a.length;h=h===n?w:Xs(qe(h),0,w);var $=h;return h-=c.length,h>=0&&a.slice(h,$)==c}function v8(a){return a=vt(a),a&&_g.test(a)?a.replace(Nc,sO):a}function y8(a){return a=vt(a),a&&Ye.test(a)?a.replace(K,"\\$&"):a}var w8=Qa(function(a,c,h){return a+(h?"-":"")+c.toLowerCase()}),x8=Qa(function(a,c,h){return a+(h?" ":"")+c.toLowerCase()}),b8=LS("toLowerCase");function S8(a,c,h){a=vt(a),c=qe(c);var w=c?Ha(a):0;if(!c||w>=c)return a;var $=(c-w)/2;return Mf(wf($),h)+a+Mf(yf($),h)}function _8(a,c,h){a=vt(a),c=qe(c);var w=c?Ha(a):0;return c&&w>>0,h?(a=vt(a),a&&(typeof c=="string"||c!=null&&!Rv(c))&&(c=sr(c),!c&&Wa(a))?Wi(Jr(a),0,h):a.split(c,h)):[]}var P8=Qa(function(a,c,h){return a+(h?" ":"")+Pv(c)});function A8(a,c,h){return a=vt(a),h=h==null?0:Xs(qe(h),0,a.length),c=sr(c),a.slice(h,h+c.length)==c}function M8(a,c,h){var w=k.templateSettings;h&&Nn(a,c,h)&&(c=n),a=vt(a),c=Wf({},c,w,WS);var $=Wf({},c.imports,w.imports,WS),T=ln($),N=Bg($,T),I,z,re=0,oe=c.interpolate||nf,ae="__p += '",ge=Vg((c.escape||nf).source+"|"+oe.source+"|"+(oe===Lc?dM:nf).source+"|"+(c.evaluate||nf).source+"|$","g"),Te="//# sourceURL="+(yt.call(c,"sourceURL")?(c.sourceURL+"").replace(/\s/g," "):"lodash.templateSources["+ ++BM+"]")+` +`;a.replace(ge,function(Fe,nt,at,lr,Dn,cr){return at||(at=lr),ae+=a.slice(re,cr).replace(yM,aO),nt&&(I=!0,ae+=`' + +__e(`+nt+`) + +'`),Dn&&(z=!0,ae+=`'; +`+Dn+`; +__p += '`),at&&(ae+=`' + +((__t = (`+at+`)) == null ? '' : __t) + +'`),re=cr+Fe.length,Fe}),ae+=`'; +`;var Le=yt.call(c,"variable")&&c.variable;if(!Le)ae=`with (obj) { +`+ae+` +} +`;else if(cM.test(Le))throw new Ke(l);ae=(z?ae.replace(bg,""):ae).replace(Sg,"$1").replace(Jd,"$1;"),ae="function("+(Le||"obj")+`) { +`+(Le?"":`obj || (obj = {}); +`)+"var __t, __p = ''"+(I?", __e = _.escape":"")+(z?`, __j = Array.prototype.join; +function print() { __p += __j.call(arguments, '') } +`:`; +`)+ae+`return __p +}`;var Qe=I_(function(){return pt(T,Te+"return "+ae).apply(n,N)});if(Qe.source=ae,$v(Qe))throw Qe;return Qe}function O8(a){return vt(a).toLowerCase()}function N8(a){return vt(a).toUpperCase()}function D8(a,c,h){if(a=vt(a),a&&(h||c===n))return Hb(a);if(!a||!(c=sr(c)))return a;var w=Jr(a),$=Jr(c),T=Kb(w,$),N=Gb(w,$)+1;return Wi(w,T,N).join("")}function I8(a,c,h){if(a=vt(a),a&&(h||c===n))return a.slice(0,Xb(a)+1);if(!a||!(c=sr(c)))return a;var w=Jr(a),$=Gb(w,Jr(c))+1;return Wi(w,0,$).join("")}function L8(a,c,h){if(a=vt(a),a&&(h||c===n))return a.replace(st,"");if(!a||!(c=sr(c)))return a;var w=Jr(a),$=Kb(w,Jr(c));return Wi(w,$).join("")}function F8(a,c){var h=V,w=J;if(It(c)){var $="separator"in c?c.separator:$;h="length"in c?qe(c.length):h,w="omission"in c?sr(c.omission):w}a=vt(a);var T=a.length;if(Wa(a)){var N=Jr(a);T=N.length}if(h>=T)return a;var I=h-Ha(w);if(I<1)return w;var z=N?Wi(N,0,I).join(""):a.slice(0,I);if($===n)return z+w;if(N&&(I+=z.length-I),Rv($)){if(a.slice(I).search($)){var re,oe=z;for($.global||($=Vg($.source,vt(hb.exec($))+"g")),$.lastIndex=0;re=$.exec(oe);)var ae=re.index;z=z.slice(0,ae===n?I:ae)}}else if(a.indexOf(sr($),I)!=I){var ge=z.lastIndexOf($);ge>-1&&(z=z.slice(0,ge))}return z+w}function j8(a){return a=vt(a),a&&Dc.test(a)?a.replace(Oc,pO):a}var z8=Qa(function(a,c,h){return a+(h?" ":"")+c.toUpperCase()}),Pv=LS("toUpperCase");function D_(a,c,h){return a=vt(a),c=h?n:c,c===n?cO(a)?vO(a):eO(a):a.match(c)||[]}var I_=et(function(a,c){try{return or(a,n,c)}catch(h){return $v(h)?h:new Ke(h)}}),B8=ii(function(a,c){return Rr(c,function(h){h=ko(h),ri(a,h,Ev(a[h],a))}),a});function U8(a){var c=a==null?0:a.length,h=Ie();return a=c?Ot(a,function(w){if(typeof w[1]!="function")throw new kr(s);return[h(w[0]),w[1]]}):[],et(function(w){for(var $=-1;++$H)return[];var h=le,w=En(a,le);c=Ie(c),a-=le;for(var $=zg(w,c);++h0||c<0)?new ot(h):(a<0?h=h.takeRight(-a):a&&(h=h.drop(a)),c!==n&&(c=qe(c),h=c<0?h.dropRight(-c):h.take(c-a)),h)},ot.prototype.takeRightWhile=function(a){return this.reverse().takeWhile(a).reverse()},ot.prototype.toArray=function(){return this.take(le)},$o(ot.prototype,function(a,c){var h=/^(?:filter|find|map|reject)|While$/.test(c),w=/^(?:head|last)$/.test(c),$=k[w?"take"+(c=="last"?"Right":""):c],T=w||/^find/.test(c);$&&(k.prototype[c]=function(){var N=this.__wrapped__,I=w?[1]:arguments,z=N instanceof ot,re=I[0],oe=z||Ge(N),ae=function(nt){var at=$.apply(k,Fi([nt],I));return w&&ge?at[0]:at};oe&&h&&typeof re=="function"&&re.length!=1&&(z=oe=!1);var ge=this.__chain__,Te=!!this.__actions__.length,Le=T&&!ge,Qe=z&&!Te;if(!T&&oe){N=Qe?N:new ot(this);var Fe=a.apply(N,I);return Fe.__actions__.push({func:Lf,args:[ae],thisArg:n}),new Tr(Fe,ge)}return Le&&Qe?a.apply(this,I):(Fe=this.thru(ae),Le?w?Fe.value()[0]:Fe.value():Fe)})}),Rr(["pop","push","shift","sort","splice","unshift"],function(a){var c=cf[a],h=/^(?:push|sort|unshift)$/.test(a)?"tap":"thru",w=/^(?:pop|shift)$/.test(a);k.prototype[a]=function(){var $=arguments;if(w&&!this.__chain__){var T=this.value();return c.apply(Ge(T)?T:[],$)}return this[h](function(N){return c.apply(Ge(N)?N:[],$)})}}),$o(ot.prototype,function(a,c){var h=k[c];if(h){var w=h.name+"";yt.call(Xa,w)||(Xa[w]=[]),Xa[w].push({name:c,func:h})}}),Xa[Pf(n,_).name]=[{name:"wrapper",func:n}],ot.prototype.clone=jO,ot.prototype.reverse=zO,ot.prototype.value=BO,k.prototype.at=g7,k.prototype.chain=v7,k.prototype.commit=y7,k.prototype.next=w7,k.prototype.plant=b7,k.prototype.reverse=S7,k.prototype.toJSON=k.prototype.valueOf=k.prototype.value=_7,k.prototype.first=k.prototype.head,jc&&(k.prototype[jc]=x7),k},Ka=yO();Hs?((Hs.exports=Ka)._=Ka,Mg._=Ka):fn._=Ka}).call(Jc)})(zp,zp.exports);var wH=zp.exports;const xH=dm(wH);function Vr({width:e,height:t}){return e/t}function Bp(e,t=0){const n=10**t;return Math.round((e+Number.EPSILON)*n)/n}function bH(e){return(t,n)=>e(n)-e(t)}class SH{constructor(t){this.comparator=t,this.heap=[],this.n=0}greater(t,n){return this.comparator(this.heap[t],this.heap[n])<0}swap(t,n){const r=this.heap[t];this.heap[t]=this.heap[n],this.heap[n]=r}swim(t){let n=t,r=Math.floor(n/2);for(;n>1&&this.greater(r,n);)this.swap(r,n),n=r,r=Math.floor(n/2)}sink(t){let n=t,r=n*2;for(;r<=this.n&&(rl.weight));for(s.push({id:t,weight:0});s.size()>0;){const{id:l,weight:u}=s.pop();if(!o.has(l)){const f=e(l);o.add(l),f.forEach((m,p)=>{const g=u+m,y=r.get(p),x=i.get(p);(x===void 0||x>g&&(x/g>1.005||y!==void 0&&yMath.min(Vr(i),o),Number.MAX_VALUE);return Bp(n/t/r)+2}function DP(e,t,n,r){const o=t-(e.length-1)*n-2*r*e.length,i=e.reduce((s,l)=>s+Vr(l),0);return o/i}function RH(e,t,n,r,o,i,s){const l=e.slice(t,n),u=DP(l,r,i,s);return u>0?(u-o)**2*l.length:void 0}function kH({photos:e,layoutOptions:t,targetRowHeight:n,limitNodeSearch:r,rowConstraints:o}){return i=>{var s,l;const{containerWidth:u,spacing:f,padding:m}=t,p=new Map;p.set(i,0);const g=(s=o==null?void 0:o.minPhotos)!=null?s:1,y=Math.min(r,(l=o==null?void 0:o.maxPhotos)!=null?l:1/0);for(let x=i+g;xy);x+=1){const S=RH(e,i,x,u,n,f,m);if(S===void 0)break;p.set(x,S)}return p}}function TH({photos:e,layoutOptions:t}){const{spacing:n,padding:r,containerWidth:o,targetRowHeight:i,rowConstraints:s}=t,l=$H({photos:e,containerWidth:o,targetRowHeight:i}),u=kH({photos:e,layoutOptions:t,targetRowHeight:i,limitNodeSearch:l,rowConstraints:s}),f=CH(u,0,e.length);if(f===void 0)return;const m=[];for(let p=1;p({photo:x,index:S})).slice(f[p-1],f[p]),y=DP(g.map(({photo:x})=>x),o,n,r);m.push(g.map(({photo:x,index:S},E)=>({photo:x,layout:{height:y,width:y*Vr(x),index:S,photoIndex:E,photosCount:g.length}})))}return m}function eg(...e){return[...e].filter(t=>!!t).join(" ")}function IP(e,{width:t,photosCount:n},{spacing:r,padding:o,containerWidth:i}){const s=r*(n-1)+2*o*n;return`calc((${e} - ${s}px) / ${Bp((i-s)/t,5)})`}function PH(e,t){return t.layout!=="rows"?`calc(100% - ${2*t.padding}px)`:IP("100%",e,t)}function a2(e,t,n){var r,o;return IP((o=(r=e.match(/calc\((.*)\)/))==null?void 0:r[1])!=null?o:e,t,n)}function AH(e,t,n){let r,o;const i=e.srcSet||e.images;return i&&i.length>0&&(r=i.concat(i.find(({width:s})=>s===e.width)?[]:[{src:e.src,width:e.width,height:e.height}]).sort((s,l)=>s.width-l.width).map(s=>`${s.src} ${s.width}w`).join(", ")),n.sizes?o=(n.sizes.sizes||[]).map(({viewport:s,size:l})=>`${s} ${a2(l,t,n)}`).concat(a2(n.sizes.size,t,n)).join(", "):r&&(o=`${Math.ceil(t.width/n.containerWidth*100)}vw`),{srcSet:r,sizes:o}}function Nx(e){var t,n;const{photo:r,layout:o,layoutOptions:i,imageProps:{style:s,className:l,...u}={},renderPhoto:f}=e,{onClick:m}=i,p={display:"block",boxSizing:"content-box",width:PH(o,i),height:"auto",aspectRatio:`${r.width} / ${r.height}`,...i.padding?{padding:`${i.padding}px`}:null,...(i.layout==="columns"||i.layout==="masonry")&&o.photoIndex{m({event:E,photo:r,index:o.index})}:void 0,y={src:r.src,alt:(t=r.alt)!=null?t:"",title:r.title,onClick:g,style:p,className:eg("react-photo-album--photo",l),loading:"lazy",decoding:"async",...AH(r,o,i),...u},x=E=>{const{src:_,alt:b,srcSet:C,sizes:R,style:P,...O}=y;return d.createElement("img",{alt:b,...C?{srcSet:C,sizes:R}:null,src:_,style:E!=null&&E.wrapped?{display:"block",width:"100%",height:"100%"}:P,...O})},S=(({display:E,boxSizing:_,width:b,aspectRatio:C,padding:R,marginBottom:P,cursor:O})=>({display:E,boxSizing:_,width:b,aspectRatio:C,padding:R,marginBottom:P,cursor:O}))(p);return d.createElement(d.Fragment,null,(n=f==null?void 0:f({photo:r,layout:o,layoutOptions:i,imageProps:y,renderDefaultPhoto:x,wrapperStyle:S}))!=null?n:x())}function MH({rowContainerProps:e,children:t}){return d.createElement("div",{...e},t)}function OH(e){const{layoutOptions:t,rowIndex:n,rowsCount:r,renderRowContainer:o,rowContainerProps:{style:i,className:s,...l}={},children:u}=e,f={className:eg("react-photo-album--row",s),style:{display:"flex",flexDirection:"row",flexWrap:"nowrap",alignItems:"flex-start",justifyContent:"space-between",...nd.createElement(OH,{key:`row-${f}`,layoutOptions:n,rowIndex:f,rowsCount:l.length,renderRowContainer:o,rowContainerProps:s},u.map(({photo:m,layout:p})=>d.createElement(Nx,{key:m.key||m.src,photo:m,layout:p,layoutOptions:n,renderPhoto:r,imageProps:i}))))):null}function DH(e,t,n,r){const o=new Map,i=new Set;i.add(n);for(let s=0;s{const f=s>0?o.get(u)[s].weight:0;e(u).forEach(({neighbor:m,weight:p})=>{let g=o.get(m);g||(g=[],o.set(m,g));const y=f+p,x=g[s+1];(!x||x.weight>y&&(x.weight/y>1.0001||u0;i-=1)o=e.get(o)[i].node,r.push(o);return r.reverse()}function LH(e,t,n,r){return IH(DH(e,t,n,r),t,r)}function FH({photos:e,spacing:t,padding:n,targetColumnWidth:r,targetColumnHeight:o}){return i=>{const s=[],l=o*1.5;let u=r/Vr(e[i])+2*n;for(let f=i+1;fl||f===e.length));f+=1)u+=r/Vr(e[f])+t+2*n;return s}}function l2({path:e,photos:t,containerWidth:n,columnsGaps:r,columnsRatios:o,spacing:i,padding:s}){const l=[],u=o.reduce((f,m)=>f+m,0);for(let f=0;f({photo:y,index:x})).slice(e[f],e[f+1]),p=o.reduce((y,x,S)=>y+(r[f]-r[S])*x,0),g=(n-(e.length-2)*i-2*(e.length-1)*s-p)*o[f]/u;l.push(m.map(({photo:y,index:x},S)=>({photo:y,layout:{width:g,height:g/Vr(y),index:x,photoIndex:S,photosCount:m.length}})))}return l}function jH({photos:e,layoutOptions:t,targetColumnWidth:n}){const{columns:r,spacing:o,padding:i,containerWidth:s}=t,l=[],u=[];if(e.length<=r){const y=e.length>0?e.reduce((S,E)=>S+Vr(E),0)/e.length:1;for(let S=0;SMath.min(E,e.length)),photos:e,columnsRatios:u,columnsGaps:l,containerWidth:s,spacing:o,padding:i});return{columnsGaps:l,columnsRatios:u,columnsModel:x}}const f=(e.reduce((y,x)=>y+n/Vr(x),0)+o*(e.length-r)+2*i*e.length)/r,m=FH({photos:e,targetColumnWidth:n,targetColumnHeight:f,spacing:o,padding:i}),p=LH(m,r,0,e.length);for(let y=0;yS+1/Vr(E),0)}const g=l2({path:p,photos:e,columnsRatios:u,columnsGaps:l,containerWidth:s,spacing:o,padding:i});return{columnsGaps:l,columnsRatios:u,columnsModel:g}}function LP(e){const{photos:t,layoutOptions:n}=e,{columns:r,spacing:o,padding:i,containerWidth:s}=n,l=(s-o*(r-1)-2*i*r)/r,{columnsGaps:u,columnsRatios:f,columnsModel:m}=jH({photos:t,layoutOptions:n,targetColumnWidth:l});return m.findIndex(p=>p.findIndex(({layout:{width:g,height:y}})=>g<0||y<0)>=0)>=0?r>1?LP({photos:t,layoutOptions:{...n,columns:r-1}}):void 0:{columnsModel:m,columnsGaps:u,columnsRatios:f}}function zH({photos:e,layoutOptions:t}){return LP({photos:e,layoutOptions:t})}function BH({columnContainerProps:e,children:t}){return d.createElement("div",{...e},t)}function UH(e){const{layoutOptions:t,columnIndex:n,columnsCount:r,columnsGaps:o,columnsRatios:i}=e,{layout:s,spacing:l,padding:u}=t;if(s==="masonry"||!o||!i)return`calc((100% - ${l*(r-1)}px) / ${r})`;const f=i.reduce((p,g)=>p+g,0),m=i.reduce((p,g,y)=>p+(o[n]-o[y])*g,0);return`calc((100% - ${Bp((r-1)*l+2*r*u+m,3)}px) * ${Bp(i[n]/f,5)} + ${2*u}px)`}function FP(e){const{layoutOptions:t,renderColumnContainer:n,children:r,columnContainerProps:{style:o,className:i,...s}={},...l}=e,u={className:eg("react-photo-album--column",i),style:{display:"flex",flexDirection:"column",flexWrap:"nowrap",alignItems:"flex-start",width:UH(e),justifyContent:t.layout==="columns"?"space-between":"flex-start",...o},...s};return d.createElement(d.Fragment,null,(n??BH)({layoutOptions:t,columnContainerProps:u,children:r,...l}))}function VH(e){const{photos:t,layoutOptions:n,renderPhoto:r,renderColumnContainer:o,componentsProps:{imageProps:i,columnContainerProps:s}}=e,l=zH({photos:t,layoutOptions:n});if(!l)return null;const{columnsModel:u,columnsRatios:f,columnsGaps:m}=l;return d.createElement(d.Fragment,null,u.map((p,g)=>d.createElement(FP,{key:`column-${g}`,layoutOptions:n,columnIndex:g,columnsCount:u.length,columnsGaps:m,columnsRatios:f,renderColumnContainer:o,columnContainerProps:s},p.map(({photo:y,layout:x})=>d.createElement(Nx,{key:y.key||y.src,photo:y,layout:x,layoutOptions:n,renderPhoto:r,imageProps:i})))))}function jP(e){const{photos:t,layoutOptions:n}=e,{columns:r,spacing:o,padding:i,containerWidth:s}=n,l=(s-o*(r-1)-2*i*r)/r;if(l<=0)return r>1?jP({...e,layoutOptions:{...n,columns:r-1}}):void 0;const u=[];for(let m=0;m{const y=u.reduce((x,S,E)=>S[])).map(m=>m.map(({photo:p,index:g},y)=>({photo:p,layout:{width:l,height:l/Vr(p),index:g,photoIndex:y,photosCount:m.length}})))}function WH(e){const{photos:t,layoutOptions:n,renderPhoto:r,renderColumnContainer:o,componentsProps:{imageProps:i,columnContainerProps:s}}=e,l=jP({photos:t,layoutOptions:n});return l?d.createElement(d.Fragment,null,l.map((u,f)=>d.createElement(FP,{key:`masonry-column-${f}`,layoutOptions:n,columnsCount:l.length,columnIndex:f,renderColumnContainer:o,columnContainerProps:s},u.map(({photo:m,layout:p})=>d.createElement(Nx,{key:m.key||m.src,photo:m,layout:p,layoutOptions:n,renderPhoto:r,imageProps:i}))))):null}function HH({containerProps:e,children:t,containerRef:n}){return d.createElement("div",{ref:n,...e},t)}function KH(e){const{layout:t,renderContainer:n,children:r,containerRef:o,containerProps:{style:i,className:s,...l}={}}=e,u={className:eg("react-photo-album",`react-photo-album--${t}`,s),style:{display:"flex",flexWrap:"nowrap",justifyContent:"space-between",flexDirection:t==="rows"?"column":"row",...i},...l};return d.createElement(d.Fragment,null,(n??HH)({containerProps:u,containerRef:o,layout:t,children:r}))}function GH(e){const t=d.useRef(e);return(!e||!t.current||e.join()!==t.current.join())&&(t.current=e),t.current}function YH(e,{newContainerWidth:t,newScrollbarWidth:n}){const{containerWidth:r,scrollbarWidth:o}=e;return r!==void 0&&o!==void 0&&t!==void 0&&n!==void 0&&t>r&&t-r<=20&&n0){const r=[...t.filter(i=>i>0)].sort((i,s)=>s-i);r.push(Math.floor(r[r.length-1]/2));const o=n;n=r.find((i,s)=>i<=o||s===r.length-1)}return n}function ZH(e,t){const[{containerWidth:n},r]=d.useReducer(YH,{containerWidth:t}),o=d.useRef(null),i=d.useRef();return{containerRef:d.useCallback(l=>{var u;(u=i.current)==null||u.disconnect(),i.current=void 0,o.current=l;const f=()=>r({newContainerWidth:XH(o.current,e),newScrollbarWidth:window.innerWidth-document.documentElement.clientWidth});f(),l&&typeof ResizeObserver<"u"&&(i.current=new ResizeObserver(f),i.current.observe(l))},[e]),containerWidth:n}}const qH=Object.freeze([1200,600,300,0]);function Dx(e,t){return typeof e=="function"?e(t):e}function zP(e,t){return typeof e<"u"?Dx(e,t):void 0}function QH(e,t){const n=qH.findIndex(r=>r<=t);return Dx(e[n>=0?n:0],t)}function wh(e,t,n,r=0){const o=zP(e,t);return Math.round(Math.max(o===void 0?QH(n,t):o,r))}function JH({layout:e,onClick:t,containerWidth:n,targetRowHeight:r,rowConstraints:o,columns:i,spacing:s,padding:l,sizes:u}){return{layout:e,onClick:t,containerWidth:n,columns:wh(i,n,[5,4,3,2],1),spacing:wh(s,n,[20,15,10,5]),padding:wh(l,n,[0,0,0,0,0]),targetRowHeight:wh(r,n,[f=>f/5,f=>f/4,f=>f/3,f=>f/2]),rowConstraints:zP(o,n),sizes:u}}function eK(e,t,n){const{photos:r,componentsProps:o}=e,i=Dx(o,t)||{};if(n){const{layout:s,spacing:l,padding:u,rowConstraints:f}=n;if(s==="rows"){const{singleRowMaxHeight:m}=f||{};if(m){const p=Math.floor(r.reduce((g,{width:y,height:x})=>g+y/x*m-2*u,u*r.length*2+l*(r.length-1)));p>0&&(i.containerProps=i.containerProps||{},i.containerProps.style={maxWidth:p,...i.containerProps.style})}}}return i}function tK(e,t,n){const{photos:r,layout:o,renderPhoto:i,renderRowContainer:s,renderColumnContainer:l}=e,u={photos:r,renderPhoto:i,componentsProps:t};return o==="rows"?d.createElement(NH,{layoutOptions:n,renderRowContainer:s,...u}):o==="columns"?d.createElement(VH,{layoutOptions:n,renderColumnContainer:l,...u}):d.createElement(WH,{layoutOptions:n,renderColumnContainer:l,...u})}function nK(e){const{photos:t,layout:n,renderContainer:r,defaultContainerWidth:o,breakpoints:i}=e,{containerRef:s,containerWidth:l}=ZH(GH(i),o);if(!n||!["rows","columns","masonry"].includes(n)||!Array.isArray(t))return null;const u=l?JH({containerWidth:l,...e}):void 0,f=eK(e,l,u);return d.createElement(KH,{layout:n,containerRef:s,renderContainer:r,containerProps:f.containerProps},u&&tK(e,f,u))}function rK({title:e,titleId:t,...n},r){return d.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true",ref:r,"aria-labelledby":t},n),e?d.createElement("title",{id:t},e):null,d.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3 4.5h14.25M3 9h9.75M3 13.5h9.75m4.5-4.5v12m0 0l-3.75-3.75M17.25 21L21 17.25"}))}const oK=d.forwardRef(rK),iK=oK;function sK({title:e,titleId:t,...n},r){return d.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true",ref:r,"aria-labelledby":t},n),e?d.createElement("title",{id:t},e):null,d.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3 4.5h14.25M3 9h9.75M3 13.5h5.25m5.25-.75L17.25 9m0 0L21 12.75M17.25 9v12"}))}const aK=d.forwardRef(sK),lK=aK;function cK({title:e,titleId:t,...n},r){return d.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true",ref:r,"aria-labelledby":t},n),e?d.createElement("title",{id:t},e):null,d.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15.042 21.672L13.684 16.6m0 0l-2.51 2.225.569-9.47 5.227 7.917-3.286-.672zM12 2.25V4.5m5.834.166l-1.591 1.591M20.25 10.5H18M7.757 14.743l-1.59 1.59M6 10.5H3.75m4.007-4.243l-1.59-1.59"}))}const uK=d.forwardRef(cK),dK=uK;function ki(e){return Array.isArray?Array.isArray(e):VP(e)==="[object Array]"}const fK=1/0;function hK(e){if(typeof e=="string")return e;let t=e+"";return t=="0"&&1/e==-fK?"-0":t}function pK(e){return e==null?"":hK(e)}function Bo(e){return typeof e=="string"}function BP(e){return typeof e=="number"}function mK(e){return e===!0||e===!1||gK(e)&&VP(e)=="[object Boolean]"}function UP(e){return typeof e=="object"}function gK(e){return UP(e)&&e!==null}function pr(e){return e!=null}function A0(e){return!e.trim().length}function VP(e){return e==null?e===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}const vK="Incorrect 'index' type",yK=e=>`Invalid value for key ${e}`,wK=e=>`Pattern length exceeds max of ${e}.`,xK=e=>`Missing ${e} property in key`,bK=e=>`Property 'weight' in key '${e}' must be a positive integer`,c2=Object.prototype.hasOwnProperty;class SK{constructor(t){this._keys=[],this._keyMap={};let n=0;t.forEach(r=>{let o=WP(r);this._keys.push(o),this._keyMap[o.id]=o,n+=o.weight}),this._keys.forEach(r=>{r.weight/=n})}get(t){return this._keyMap[t]}keys(){return this._keys}toJSON(){return JSON.stringify(this._keys)}}function WP(e){let t=null,n=null,r=null,o=1,i=null;if(Bo(e)||ki(e))r=e,t=u2(e),n=g1(e);else{if(!c2.call(e,"name"))throw new Error(xK("name"));const s=e.name;if(r=s,c2.call(e,"weight")&&(o=e.weight,o<=0))throw new Error(bK(s));t=u2(s),n=g1(s),i=e.getFn}return{path:t,id:n,weight:o,src:r,getFn:i}}function u2(e){return ki(e)?e:e.split(".")}function g1(e){return ki(e)?e.join("."):e}function _K(e,t){let n=[],r=!1;const o=(i,s,l)=>{if(pr(i))if(!s[l])n.push(i);else{let u=s[l];const f=i[u];if(!pr(f))return;if(l===s.length-1&&(Bo(f)||BP(f)||mK(f)))n.push(pK(f));else if(ki(f)){r=!0;for(let m=0,p=f.length;me.score===t.score?e.idx{this._keysMap[n.id]=r})}create(){this.isCreated||!this.docs.length||(this.isCreated=!0,Bo(this.docs[0])?this.docs.forEach((t,n)=>{this._addString(t,n)}):this.docs.forEach((t,n)=>{this._addObject(t,n)}),this.norm.clear())}add(t){const n=this.size();Bo(t)?this._addString(t,n):this._addObject(t,n)}removeAt(t){this.records.splice(t,1);for(let n=t,r=this.size();n{let s=o.getFn?o.getFn(t):this.getFn(t,o.path);if(pr(s)){if(ki(s)){let l=[];const u=[{nestedArrIndex:-1,value:s}];for(;u.length;){const{nestedArrIndex:f,value:m}=u.pop();if(pr(m))if(Bo(m)&&!A0(m)){let p={v:m,i:f,n:this.norm.get(m)};l.push(p)}else ki(m)&&m.forEach((p,g)=>{u.push({nestedArrIndex:g,value:p})})}r.$[i]=l}else if(Bo(s)&&!A0(s)){let l={v:s,n:this.norm.get(s)};r.$[i]=l}}}),this.records.push(r)}toJSON(){return{keys:this.keys,records:this.records}}}function HP(e,t,{getFn:n=He.getFn,fieldNormWeight:r=He.fieldNormWeight}={}){const o=new Ix({getFn:n,fieldNormWeight:r});return o.setKeys(e.map(WP)),o.setSources(t),o.create(),o}function PK(e,{getFn:t=He.getFn,fieldNormWeight:n=He.fieldNormWeight}={}){const{keys:r,records:o}=e,i=new Ix({getFn:t,fieldNormWeight:n});return i.setKeys(r),i.setIndexRecords(o),i}function xh(e,{errors:t=0,currentLocation:n=0,expectedLocation:r=0,distance:o=He.distance,ignoreLocation:i=He.ignoreLocation}={}){const s=t/e.length;if(i)return s;const l=Math.abs(r-n);return o?s+l/o:l?1:s}function AK(e=[],t=He.minMatchCharLength){let n=[],r=-1,o=-1,i=0;for(let s=e.length;i=t&&n.push([r,o]),r=-1)}return e[i-1]&&i-r>=t&&n.push([r,i-1]),n}const la=32;function MK(e,t,n,{location:r=He.location,distance:o=He.distance,threshold:i=He.threshold,findAllMatches:s=He.findAllMatches,minMatchCharLength:l=He.minMatchCharLength,includeMatches:u=He.includeMatches,ignoreLocation:f=He.ignoreLocation}={}){if(t.length>la)throw new Error(wK(la));const m=t.length,p=e.length,g=Math.max(0,Math.min(r,p));let y=i,x=g;const S=l>1||u,E=S?Array(p):[];let _;for(;(_=e.indexOf(t,x))>-1;){let A=xh(t,{currentLocation:_,expectedLocation:g,distance:o,ignoreLocation:f});if(y=Math.min(A,y),x=_+m,S){let D=0;for(;D=V;U-=1){let ne=U-1,M=n[e.charAt(ne)];if(S&&(E[ne]=+!!M),G[U]=(G[U+1]<<1|1)&M,A&&(G[U]|=(b[U+1]|b[U])<<1|1|b[U+1]),G[U]&P&&(C=xh(t,{errors:A,currentLocation:ne,expectedLocation:g,distance:o,ignoreLocation:f}),C<=y)){if(y=C,x=ne,x<=g)break;V=Math.max(1,2*g-x)}}if(xh(t,{errors:A+1,currentLocation:g,expectedLocation:g,distance:o,ignoreLocation:f})>y)break;b=G}const O={isMatch:x>=0,score:Math.max(.001,C)};if(S){const A=AK(E,l);A.length?u&&(O.indices=A):O.isMatch=!1}return O}function OK(e){let t={};for(let n=0,r=e.length;n{this.chunks.push({pattern:g,alphabet:OK(g),startIndex:y})},p=this.pattern.length;if(p>la){let g=0;const y=p%la,x=p-y;for(;g{const{isMatch:_,score:b,indices:C}=MK(t,x,S,{location:o+E,distance:i,threshold:s,findAllMatches:l,minMatchCharLength:u,includeMatches:r,ignoreLocation:f});_&&(g=!0),p+=b,_&&C&&(m=[...m,...C])});let y={isMatch:g,score:g?p/this.chunks.length:1};return g&&r&&(y.indices=m),y}}class js{constructor(t){this.pattern=t}static isMultiMatch(t){return d2(t,this.multiRegex)}static isSingleMatch(t){return d2(t,this.singleRegex)}search(){}}function d2(e,t){const n=e.match(t);return n?n[1]:null}class NK extends js{constructor(t){super(t)}static get type(){return"exact"}static get multiRegex(){return/^="(.*)"$/}static get singleRegex(){return/^=(.*)$/}search(t){const n=t===this.pattern;return{isMatch:n,score:n?0:1,indices:[0,this.pattern.length-1]}}}class DK extends js{constructor(t){super(t)}static get type(){return"inverse-exact"}static get multiRegex(){return/^!"(.*)"$/}static get singleRegex(){return/^!(.*)$/}search(t){const r=t.indexOf(this.pattern)===-1;return{isMatch:r,score:r?0:1,indices:[0,t.length-1]}}}class IK extends js{constructor(t){super(t)}static get type(){return"prefix-exact"}static get multiRegex(){return/^\^"(.*)"$/}static get singleRegex(){return/^\^(.*)$/}search(t){const n=t.startsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[0,this.pattern.length-1]}}}class LK extends js{constructor(t){super(t)}static get type(){return"inverse-prefix-exact"}static get multiRegex(){return/^!\^"(.*)"$/}static get singleRegex(){return/^!\^(.*)$/}search(t){const n=!t.startsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[0,t.length-1]}}}class FK extends js{constructor(t){super(t)}static get type(){return"suffix-exact"}static get multiRegex(){return/^"(.*)"\$$/}static get singleRegex(){return/^(.*)\$$/}search(t){const n=t.endsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[t.length-this.pattern.length,t.length-1]}}}class jK extends js{constructor(t){super(t)}static get type(){return"inverse-suffix-exact"}static get multiRegex(){return/^!"(.*)"\$$/}static get singleRegex(){return/^!(.*)\$$/}search(t){const n=!t.endsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[0,t.length-1]}}}class GP extends js{constructor(t,{location:n=He.location,threshold:r=He.threshold,distance:o=He.distance,includeMatches:i=He.includeMatches,findAllMatches:s=He.findAllMatches,minMatchCharLength:l=He.minMatchCharLength,isCaseSensitive:u=He.isCaseSensitive,ignoreLocation:f=He.ignoreLocation}={}){super(t),this._bitapSearch=new KP(t,{location:n,threshold:r,distance:o,includeMatches:i,findAllMatches:s,minMatchCharLength:l,isCaseSensitive:u,ignoreLocation:f})}static get type(){return"fuzzy"}static get multiRegex(){return/^"(.*)"$/}static get singleRegex(){return/^(.*)$/}search(t){return this._bitapSearch.searchIn(t)}}class YP extends js{constructor(t){super(t)}static get type(){return"include"}static get multiRegex(){return/^'"(.*)"$/}static get singleRegex(){return/^'(.*)$/}search(t){let n=0,r;const o=[],i=this.pattern.length;for(;(r=t.indexOf(this.pattern,n))>-1;)n=r+i,o.push([r,n-1]);const s=!!o.length;return{isMatch:s,score:s?0:1,indices:o}}}const v1=[NK,YP,IK,LK,jK,FK,DK,GP],f2=v1.length,zK=/ +(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/,BK="|";function UK(e,t={}){return e.split(BK).map(n=>{let r=n.trim().split(zK).filter(i=>i&&!!i.trim()),o=[];for(let i=0,s=r.length;i!!(e[Up.AND]||e[Up.OR]),KK=e=>!!e[x1.PATH],GK=e=>!ki(e)&&UP(e)&&!b1(e),h2=e=>({[Up.AND]:Object.keys(e).map(t=>({[t]:e[t]}))});function XP(e,t,{auto:n=!0}={}){const r=o=>{let i=Object.keys(o);const s=KK(o);if(!s&&i.length>1&&!b1(o))return r(h2(o));if(GK(o)){const u=s?o[x1.PATH]:i[0],f=s?o[x1.PATTERN]:o[u];if(!Bo(f))throw new Error(yK(u));const m={keyId:g1(u),pattern:f};return n&&(m.searcher=w1(f,t)),m}let l={children:[],operator:i[0]};return i.forEach(u=>{const f=o[u];ki(f)&&f.forEach(m=>{l.children.push(r(m))})}),l};return b1(e)||(e=h2(e)),r(e)}function YK(e,{ignoreFieldNorm:t=He.ignoreFieldNorm}){e.forEach(n=>{let r=1;n.matches.forEach(({key:o,norm:i,score:s})=>{const l=o?o.weight:null;r*=Math.pow(s===0&&l?Number.EPSILON:s,(l||1)*(t?1:i))}),n.score=r})}function XK(e,t){const n=e.matches;t.matches=[],pr(n)&&n.forEach(r=>{if(!pr(r.indices)||!r.indices.length)return;const{indices:o,value:i}=r;let s={indices:o,value:i};r.key&&(s.key=r.key.src),r.idx>-1&&(s.refIndex=r.idx),t.matches.push(s)})}function ZK(e,t){t.score=e.score}function qK(e,t,{includeMatches:n=He.includeMatches,includeScore:r=He.includeScore}={}){const o=[];return n&&o.push(XK),r&&o.push(ZK),e.map(i=>{const{idx:s}=i,l={item:t[s],refIndex:s};return o.length&&o.forEach(u=>{u(i,l)}),l})}class kc{constructor(t,n={},r){this.options={...He,...n},this.options.useExtendedSearch,this._keyStore=new SK(this.options.keys),this.setCollection(t,r)}setCollection(t,n){if(this._docs=t,n&&!(n instanceof Ix))throw new Error(vK);this._myIndex=n||HP(this.options.keys,this._docs,{getFn:this.options.getFn,fieldNormWeight:this.options.fieldNormWeight})}add(t){pr(t)&&(this._docs.push(t),this._myIndex.add(t))}remove(t=()=>!1){const n=[];for(let r=0,o=this._docs.length;r-1&&(u=u.slice(0,n)),qK(u,this._docs,{includeMatches:r,includeScore:o})}_searchStringList(t){const n=w1(t,this.options),{records:r}=this._myIndex,o=[];return r.forEach(({v:i,i:s,n:l})=>{if(!pr(i))return;const{isMatch:u,score:f,indices:m}=n.searchIn(i);u&&o.push({item:i,idx:s,matches:[{score:f,value:i,norm:l,indices:m}]})}),o}_searchLogical(t){const n=XP(t,this.options),r=(l,u,f)=>{if(!l.children){const{keyId:p,searcher:g}=l,y=this._findMatches({key:this._keyStore.get(p),value:this._myIndex.getValueForItemAtKeyId(u,p),searcher:g});return y&&y.length?[{idx:f,item:u,matches:y}]:[]}const m=[];for(let p=0,g=l.children.length;p{if(pr(l)){let f=r(n,l,u);f.length&&(i[u]||(i[u]={idx:u,item:l,matches:[]},s.push(i[u])),f.forEach(({matches:m})=>{i[u].matches.push(...m)}))}}),s}_searchObjectList(t){const n=w1(t,this.options),{keys:r,records:o}=this._myIndex,i=[];return o.forEach(({$:s,i:l})=>{if(!pr(s))return;let u=[];r.forEach((f,m)=>{u.push(...this._findMatches({key:f,value:s[m],searcher:n}))}),u.length&&i.push({idx:l,item:s,matches:u})}),i}_findMatches({key:t,value:n,searcher:r}){if(!pr(n))return[];let o=[];if(ki(n))n.forEach(({v:i,i:s,n:l})=>{if(!pr(i))return;const{isMatch:u,score:f,indices:m}=r.searchIn(i);u&&o.push({score:f,key:t,value:i,idx:s,norm:l,indices:m})});else{const{v:i,n:s}=n,{isMatch:l,score:u,indices:f}=r.searchIn(i);l&&o.push({score:u,key:t,value:i,norm:s,indices:f})}return o}}kc.version="7.0.0";kc.createIndex=HP;kc.parseIndex=PK;kc.config=He;kc.parseQuery=XP;HK(WK);function Gd(e){const t=e+"CollectionProvider",[n,r]=Mn(t),[o,i]=n(t,{collectionRef:{current:null},itemMap:new Map}),s=y=>{const{scope:x,children:S}=y,E=je.useRef(null),_=je.useRef(new Map).current;return je.createElement(o,{scope:x,itemMap:_,collectionRef:E},S)},l=e+"CollectionSlot",u=je.forwardRef((y,x)=>{const{scope:S,children:E}=y,_=i(l,S),b=Ue(x,_.collectionRef);return je.createElement(Zo,{ref:b},E)}),f=e+"CollectionItemSlot",m="data-radix-collection-item",p=je.forwardRef((y,x)=>{const{scope:S,children:E,..._}=y,b=je.useRef(null),C=Ue(x,b),R=i(f,S);return je.useEffect(()=>(R.itemMap.set(b,{ref:b,..._}),()=>void R.itemMap.delete(b))),je.createElement(Zo,{[m]:"",ref:C},E)});function g(y){const x=i(e+"CollectionConsumer",y);return je.useCallback(()=>{const E=x.collectionRef.current;if(!E)return[];const _=Array.from(E.querySelectorAll(`[${m}]`));return Array.from(x.itemMap.values()).sort((R,P)=>_.indexOf(R.ref.current)-_.indexOf(P.ref.current))},[x.collectionRef,x.itemMap])}return[{Provider:s,Slot:u,ItemSlot:p},g,r]}const QK=d.createContext(void 0);function Tc(e){const t=d.useContext(QK);return e||t||"ltr"}const M0="rovingFocusGroup.onEntryFocus",JK={bubbles:!1,cancelable:!0},Lx="RovingFocusGroup",[S1,ZP,eG]=Gd(Lx),[tG,tg]=Mn(Lx,[eG]),[nG,rG]=tG(Lx),oG=d.forwardRef((e,t)=>d.createElement(S1.Provider,{scope:e.__scopeRovingFocusGroup},d.createElement(S1.Slot,{scope:e.__scopeRovingFocusGroup},d.createElement(iG,Y({},e,{ref:t}))))),iG=d.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:o=!1,dir:i,currentTabStopId:s,defaultCurrentTabStopId:l,onCurrentTabStopIdChange:u,onEntryFocus:f,...m}=e,p=d.useRef(null),g=Ue(t,p),y=Tc(i),[x=null,S]=Zr({prop:s,defaultProp:l,onChange:u}),[E,_]=d.useState(!1),b=Ft(f),C=ZP(n),R=d.useRef(!1),[P,O]=d.useState(0);return d.useEffect(()=>{const A=p.current;if(A)return A.addEventListener(M0,b),()=>A.removeEventListener(M0,b)},[b]),d.createElement(nG,{scope:n,orientation:r,dir:y,loop:o,currentTabStopId:x,onItemFocus:d.useCallback(A=>S(A),[S]),onItemShiftTab:d.useCallback(()=>_(!0),[]),onFocusableItemAdd:d.useCallback(()=>O(A=>A+1),[]),onFocusableItemRemove:d.useCallback(()=>O(A=>A-1),[])},d.createElement(Ae.div,Y({tabIndex:E||P===0?-1:0,"data-orientation":r},m,{ref:g,style:{outline:"none",...e.style},onMouseDown:ue(e.onMouseDown,()=>{R.current=!0}),onFocus:ue(e.onFocus,A=>{const D=!R.current;if(A.target===A.currentTarget&&D&&!E){const B=new CustomEvent(M0,JK);if(A.currentTarget.dispatchEvent(B),!B.defaultPrevented){const V=C().filter(ne=>ne.focusable),J=V.find(ne=>ne.active),G=V.find(ne=>ne.id===x),U=[J,G,...V].filter(Boolean).map(ne=>ne.ref.current);qP(U)}}R.current=!1}),onBlur:ue(e.onBlur,()=>_(!1))})))}),sG="RovingFocusGroupItem",aG=d.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:o=!1,tabStopId:i,...s}=e,l=nr(),u=i||l,f=rG(sG,n),m=f.currentTabStopId===u,p=ZP(n),{onFocusableItemAdd:g,onFocusableItemRemove:y}=f;return d.useEffect(()=>{if(r)return g(),()=>y()},[r,g,y]),d.createElement(S1.ItemSlot,{scope:n,id:u,focusable:r,active:o},d.createElement(Ae.span,Y({tabIndex:m?0:-1,"data-orientation":f.orientation},s,{ref:t,onMouseDown:ue(e.onMouseDown,x=>{r?f.onItemFocus(u):x.preventDefault()}),onFocus:ue(e.onFocus,()=>f.onItemFocus(u)),onKeyDown:ue(e.onKeyDown,x=>{if(x.key==="Tab"&&x.shiftKey){f.onItemShiftTab();return}if(x.target!==x.currentTarget)return;const S=uG(x,f.orientation,f.dir);if(S!==void 0){x.preventDefault();let _=p().filter(b=>b.focusable).map(b=>b.ref.current);if(S==="last")_.reverse();else if(S==="prev"||S==="next"){S==="prev"&&_.reverse();const b=_.indexOf(x.currentTarget);_=f.loop?dG(_,b+1):_.slice(b+1)}setTimeout(()=>qP(_))}})})))}),lG={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function cG(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function uG(e,t,n){const r=cG(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return lG[r]}function qP(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function dG(e,t){return e.map((n,r)=>e[(t+r)%e.length])}const QP=oG,JP=aG,e5="Tabs",[fG,xte]=Mn(e5,[tg]),t5=tg(),[hG,Fx]=fG(e5),pG=d.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,onValueChange:o,defaultValue:i,orientation:s="horizontal",dir:l,activationMode:u="automatic",...f}=e,m=Tc(l),[p,g]=Zr({prop:r,onChange:o,defaultProp:i});return d.createElement(hG,{scope:n,baseId:nr(),value:p,onValueChange:g,orientation:s,dir:m,activationMode:u},d.createElement(Ae.div,Y({dir:m,"data-orientation":s},f,{ref:t})))}),mG="TabsList",gG=d.forwardRef((e,t)=>{const{__scopeTabs:n,loop:r=!0,...o}=e,i=Fx(mG,n),s=t5(n);return d.createElement(QP,Y({asChild:!0},s,{orientation:i.orientation,dir:i.dir,loop:r}),d.createElement(Ae.div,Y({role:"tablist","aria-orientation":i.orientation},o,{ref:t})))}),vG="TabsTrigger",yG=d.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,disabled:o=!1,...i}=e,s=Fx(vG,n),l=t5(n),u=n5(s.baseId,r),f=r5(s.baseId,r),m=r===s.value;return d.createElement(JP,Y({asChild:!0},l,{focusable:!o,active:m}),d.createElement(Ae.button,Y({type:"button",role:"tab","aria-selected":m,"aria-controls":f,"data-state":m?"active":"inactive","data-disabled":o?"":void 0,disabled:o,id:u},i,{ref:t,onMouseDown:ue(e.onMouseDown,p=>{!o&&p.button===0&&p.ctrlKey===!1?s.onValueChange(r):p.preventDefault()}),onKeyDown:ue(e.onKeyDown,p=>{[" ","Enter"].includes(p.key)&&s.onValueChange(r)}),onFocus:ue(e.onFocus,()=>{const p=s.activationMode!=="manual";!m&&!o&&p&&s.onValueChange(r)})})))}),wG="TabsContent",xG=d.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,forceMount:o,children:i,...s}=e,l=Fx(wG,n),u=n5(l.baseId,r),f=r5(l.baseId,r),m=r===l.value,p=d.useRef(m);return d.useEffect(()=>{const g=requestAnimationFrame(()=>p.current=!1);return()=>cancelAnimationFrame(g)},[]),d.createElement(Sn,{present:o||m},({present:g})=>d.createElement(Ae.div,Y({"data-state":m?"active":"inactive","data-orientation":l.orientation,role:"tabpanel","aria-labelledby":u,hidden:!g,id:f,tabIndex:0},s,{ref:t,style:{...e.style,animationDuration:p.current?"0s":void 0}}),g&&i))});function n5(e,t){return`${e}-trigger-${t}`}function r5(e,t){return`${e}-content-${t}`}const bG=pG,o5=gG,i5=yG,s5=xG,a5=bG,jx=d.forwardRef(({className:e,...t},n)=>v.jsx(o5,{ref:n,className:Ce("inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground",e),tabIndex:-1,...t}));jx.displayName=o5.displayName;const pa=d.forwardRef(({className:e,...t},n)=>v.jsx(i5,{ref:n,className:Ce("inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow",e),tabIndex:-1,...t}));pa.displayName=i5.displayName;const Su=d.forwardRef(({className:e,...t},n)=>v.jsx(s5,{ref:n,className:Ce("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",e),tabIndex:-1,...t}));Su.displayName=s5.displayName;function fd(e,[t,n]){return Math.min(n,Math.max(t,e))}function zx(e){const t=d.useRef({value:e,previous:e});return d.useMemo(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}const SG=[" ","Enter","ArrowUp","ArrowDown"],_G=[" ","Enter"],ng="Select",[rg,og,EG]=Gd(ng),[Pc,bte]=Mn(ng,[EG,Fs]),Bx=Fs(),[CG,Fa]=Pc(ng),[$G,RG]=Pc(ng),kG=e=>{const{__scopeSelect:t,children:n,open:r,defaultOpen:o,onOpenChange:i,value:s,defaultValue:l,onValueChange:u,dir:f,name:m,autoComplete:p,disabled:g,required:y}=e,x=Bx(t),[S,E]=d.useState(null),[_,b]=d.useState(null),[C,R]=d.useState(!1),P=Tc(f),[O=!1,A]=Zr({prop:r,defaultProp:o,onChange:i}),[D,B]=Zr({prop:s,defaultProp:l,onChange:u}),V=d.useRef(null),J=S?!!S.closest("form"):!0,[G,se]=d.useState(new Set),U=Array.from(G).map(ne=>ne.props.value).join(";");return d.createElement(jd,x,d.createElement(CG,{required:y,scope:t,trigger:S,onTriggerChange:E,valueNode:_,onValueNodeChange:b,valueNodeHasChildren:C,onValueNodeHasChildrenChange:R,contentId:nr(),value:D,onValueChange:B,open:O,onOpenChange:A,dir:P,triggerPointerDownPosRef:V,disabled:g},d.createElement(rg.Provider,{scope:t},d.createElement($G,{scope:e.__scopeSelect,onNativeOptionAdd:d.useCallback(ne=>{se(M=>new Set(M).add(ne))},[]),onNativeOptionRemove:d.useCallback(ne=>{se(M=>{const ee=new Set(M);return ee.delete(ne),ee})},[])},n)),J?d.createElement(f5,{key:U,"aria-hidden":!0,required:y,tabIndex:-1,name:m,autoComplete:p,value:D,onChange:ne=>B(ne.target.value),disabled:g},D===void 0?d.createElement("option",{value:""}):null,Array.from(G)):null))},TG="SelectTrigger",PG=d.forwardRef((e,t)=>{const{__scopeSelect:n,disabled:r=!1,...o}=e,i=Bx(n),s=Fa(TG,n),l=s.disabled||r,u=Ue(t,s.onTriggerChange),f=og(n),[m,p,g]=h5(x=>{const S=f().filter(b=>!b.disabled),E=S.find(b=>b.value===s.value),_=p5(S,x,E);_!==void 0&&s.onValueChange(_.value)}),y=()=>{l||(s.onOpenChange(!0),g())};return d.createElement(Vm,Y({asChild:!0},i),d.createElement(Ae.button,Y({type:"button",role:"combobox","aria-controls":s.contentId,"aria-expanded":s.open,"aria-required":s.required,"aria-autocomplete":"none",dir:s.dir,"data-state":s.open?"open":"closed",disabled:l,"data-disabled":l?"":void 0,"data-placeholder":d5(s.value)?"":void 0},o,{ref:u,onClick:ue(o.onClick,x=>{x.currentTarget.focus()}),onPointerDown:ue(o.onPointerDown,x=>{const S=x.target;S.hasPointerCapture(x.pointerId)&&S.releasePointerCapture(x.pointerId),x.button===0&&x.ctrlKey===!1&&(y(),s.triggerPointerDownPosRef.current={x:Math.round(x.pageX),y:Math.round(x.pageY)},x.preventDefault())}),onKeyDown:ue(o.onKeyDown,x=>{const S=m.current!=="";!(x.ctrlKey||x.altKey||x.metaKey)&&x.key.length===1&&p(x.key),!(S&&x.key===" ")&&SG.includes(x.key)&&(y(),x.preventDefault())})})))}),AG="SelectValue",MG=d.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,children:i,placeholder:s="",...l}=e,u=Fa(AG,n),{onValueNodeHasChildrenChange:f}=u,m=i!==void 0,p=Ue(t,u.onValueNodeChange);return An(()=>{f(m)},[f,m]),d.createElement(Ae.span,Y({},l,{ref:p,style:{pointerEvents:"none"}}),d5(u.value)?d.createElement(d.Fragment,null,s):i)}),OG=d.forwardRef((e,t)=>{const{__scopeSelect:n,children:r,...o}=e;return d.createElement(Ae.span,Y({"aria-hidden":!0},o,{ref:t}),r||"▼")}),NG=e=>d.createElement(zd,Y({asChild:!0},e)),dc="SelectContent",DG=d.forwardRef((e,t)=>{const n=Fa(dc,e.__scopeSelect),[r,o]=d.useState();if(An(()=>{o(new DocumentFragment)},[]),!n.open){const i=r;return i?Is.createPortal(d.createElement(l5,{scope:e.__scopeSelect},d.createElement(rg.Slot,{scope:e.__scopeSelect},d.createElement("div",null,e.children))),i):null}return d.createElement(IG,Y({},e,{ref:t}))}),hi=10,[l5,ja]=Pc(dc),IG=d.forwardRef((e,t)=>{const{__scopeSelect:n,position:r="item-aligned",onCloseAutoFocus:o,onEscapeKeyDown:i,onPointerDownOutside:s,side:l,sideOffset:u,align:f,alignOffset:m,arrowPadding:p,collisionBoundary:g,collisionPadding:y,sticky:x,hideWhenDetached:S,avoidCollisions:E,..._}=e,b=Fa(dc,n),[C,R]=d.useState(null),[P,O]=d.useState(null),A=Ue(t,fe=>R(fe)),[D,B]=d.useState(null),[V,J]=d.useState(null),G=og(n),[se,U]=d.useState(!1),ne=d.useRef(!1);d.useEffect(()=>{if(C)return Qm(C)},[C]),Xm();const M=d.useCallback(fe=>{const[xe,...Re]=G().map(ze=>ze.ref.current),[Me]=Re.slice(-1),Oe=document.activeElement;for(const ze of fe)if(ze===Oe||(ze==null||ze.scrollIntoView({block:"nearest"}),ze===xe&&P&&(P.scrollTop=0),ze===Me&&P&&(P.scrollTop=P.scrollHeight),ze==null||ze.focus(),document.activeElement!==Oe))return},[G,P]),ee=d.useCallback(()=>M([D,C]),[M,D,C]);d.useEffect(()=>{se&&ee()},[se,ee]);const{onOpenChange:H,triggerPointerDownPosRef:X}=b;d.useEffect(()=>{if(C){let fe={x:0,y:0};const xe=Me=>{var Oe,ze,Mt,ct;fe={x:Math.abs(Math.round(Me.pageX)-((Oe=(ze=X.current)===null||ze===void 0?void 0:ze.x)!==null&&Oe!==void 0?Oe:0)),y:Math.abs(Math.round(Me.pageY)-((Mt=(ct=X.current)===null||ct===void 0?void 0:ct.y)!==null&&Mt!==void 0?Mt:0))}},Re=Me=>{fe.x<=10&&fe.y<=10?Me.preventDefault():C.contains(Me.target)||H(!1),document.removeEventListener("pointermove",xe),X.current=null};return X.current!==null&&(document.addEventListener("pointermove",xe),document.addEventListener("pointerup",Re,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",xe),document.removeEventListener("pointerup",Re,{capture:!0})}}},[C,H,X]),d.useEffect(()=>{const fe=()=>H(!1);return window.addEventListener("blur",fe),window.addEventListener("resize",fe),()=>{window.removeEventListener("blur",fe),window.removeEventListener("resize",fe)}},[H]);const[W,le]=h5(fe=>{const xe=G().filter(Oe=>!Oe.disabled),Re=xe.find(Oe=>Oe.ref.current===document.activeElement),Me=p5(xe,fe,Re);Me&&setTimeout(()=>Me.ref.current.focus())}),pe=d.useCallback((fe,xe,Re)=>{const Me=!ne.current&&!Re;(b.value!==void 0&&b.value===xe||Me)&&(B(fe),Me&&(ne.current=!0))},[b.value]),$e=d.useCallback(()=>C==null?void 0:C.focus(),[C]),Ve=d.useCallback((fe,xe,Re)=>{const Me=!ne.current&&!Re;(b.value!==void 0&&b.value===xe||Me)&&J(fe)},[b.value]),We=r==="popper"?p2:LG,Ne=We===p2?{side:l,sideOffset:u,align:f,alignOffset:m,arrowPadding:p,collisionBoundary:g,collisionPadding:y,sticky:x,hideWhenDetached:S,avoidCollisions:E}:{};return d.createElement(l5,{scope:n,content:C,viewport:P,onViewportChange:O,itemRefCallback:pe,selectedItem:D,onItemLeave:$e,itemTextRefCallback:Ve,focusSelectedItem:ee,selectedItemText:V,position:r,isPositioned:se,searchRef:W},d.createElement(qm,{as:Zo,allowPinchZoom:!0},d.createElement(Ym,{asChild:!0,trapped:b.open,onMountAutoFocus:fe=>{fe.preventDefault()},onUnmountAutoFocus:ue(o,fe=>{var xe;(xe=b.trigger)===null||xe===void 0||xe.focus({preventScroll:!0}),fe.preventDefault()})},d.createElement(Ec,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:i,onPointerDownOutside:s,onFocusOutside:fe=>fe.preventDefault(),onDismiss:()=>b.onOpenChange(!1)},d.createElement(We,Y({role:"listbox",id:b.contentId,"data-state":b.open?"open":"closed",dir:b.dir,onContextMenu:fe=>fe.preventDefault()},_,Ne,{onPlaced:()=>U(!0),ref:A,style:{display:"flex",flexDirection:"column",outline:"none",..._.style},onKeyDown:ue(_.onKeyDown,fe=>{const xe=fe.ctrlKey||fe.altKey||fe.metaKey;if(fe.key==="Tab"&&fe.preventDefault(),!xe&&fe.key.length===1&&le(fe.key),["ArrowUp","ArrowDown","Home","End"].includes(fe.key)){let Me=G().filter(Oe=>!Oe.disabled).map(Oe=>Oe.ref.current);if(["ArrowUp","End"].includes(fe.key)&&(Me=Me.slice().reverse()),["ArrowUp","ArrowDown"].includes(fe.key)){const Oe=fe.target,ze=Me.indexOf(Oe);Me=Me.slice(ze+1)}setTimeout(()=>M(Me)),fe.preventDefault()}})}))))))}),LG=d.forwardRef((e,t)=>{const{__scopeSelect:n,onPlaced:r,...o}=e,i=Fa(dc,n),s=ja(dc,n),[l,u]=d.useState(null),[f,m]=d.useState(null),p=Ue(t,A=>m(A)),g=og(n),y=d.useRef(!1),x=d.useRef(!0),{viewport:S,selectedItem:E,selectedItemText:_,focusSelectedItem:b}=s,C=d.useCallback(()=>{if(i.trigger&&i.valueNode&&l&&f&&S&&E&&_){const A=i.trigger.getBoundingClientRect(),D=f.getBoundingClientRect(),B=i.valueNode.getBoundingClientRect(),V=_.getBoundingClientRect();if(i.dir!=="rtl"){const Oe=V.left-D.left,ze=B.left-Oe,Mt=A.left-ze,ct=A.width+Mt,Kt=Math.max(ct,D.width),Er=window.innerWidth-hi,gt=fd(ze,[hi,Er-Kt]);l.style.minWidth=ct+"px",l.style.left=gt+"px"}else{const Oe=D.right-V.right,ze=window.innerWidth-B.right-Oe,Mt=window.innerWidth-A.right-ze,ct=A.width+Mt,Kt=Math.max(ct,D.width),Er=window.innerWidth-hi,gt=fd(ze,[hi,Er-Kt]);l.style.minWidth=ct+"px",l.style.right=gt+"px"}const J=g(),G=window.innerHeight-hi*2,se=S.scrollHeight,U=window.getComputedStyle(f),ne=parseInt(U.borderTopWidth,10),M=parseInt(U.paddingTop,10),ee=parseInt(U.borderBottomWidth,10),H=parseInt(U.paddingBottom,10),X=ne+M+se+H+ee,W=Math.min(E.offsetHeight*5,X),le=window.getComputedStyle(S),pe=parseInt(le.paddingTop,10),$e=parseInt(le.paddingBottom,10),Ve=A.top+A.height/2-hi,We=G-Ve,Ne=E.offsetHeight/2,fe=E.offsetTop+Ne,xe=ne+M+fe,Re=X-xe;if(xe<=Ve){const Oe=E===J[J.length-1].ref.current;l.style.bottom="0px";const ze=f.clientHeight-S.offsetTop-S.offsetHeight,Mt=Math.max(We,Ne+(Oe?$e:0)+ze+ee),ct=xe+Mt;l.style.height=ct+"px"}else{const Oe=E===J[0].ref.current;l.style.top="0px";const Mt=Math.max(Ve,ne+S.offsetTop+(Oe?pe:0)+Ne)+Re;l.style.height=Mt+"px",S.scrollTop=xe-Ve+S.offsetTop}l.style.margin=`${hi}px 0`,l.style.minHeight=W+"px",l.style.maxHeight=G+"px",r==null||r(),requestAnimationFrame(()=>y.current=!0)}},[g,i.trigger,i.valueNode,l,f,S,E,_,i.dir,r]);An(()=>C(),[C]);const[R,P]=d.useState();An(()=>{f&&P(window.getComputedStyle(f).zIndex)},[f]);const O=d.useCallback(A=>{A&&x.current===!0&&(C(),b==null||b(),x.current=!1)},[C,b]);return d.createElement(FG,{scope:n,contentWrapper:l,shouldExpandOnScrollRef:y,onScrollButtonChange:O},d.createElement("div",{ref:u,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:R}},d.createElement(Ae.div,Y({},o,{ref:p,style:{boxSizing:"border-box",maxHeight:"100%",...o.style}}))))}),p2=d.forwardRef((e,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:o=hi,...i}=e,s=Bx(n);return d.createElement(Wm,Y({},s,i,{ref:t,align:r,collisionPadding:o,style:{boxSizing:"border-box",...i.style,"--radix-select-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-select-content-available-width":"var(--radix-popper-available-width)","--radix-select-content-available-height":"var(--radix-popper-available-height)","--radix-select-trigger-width":"var(--radix-popper-anchor-width)","--radix-select-trigger-height":"var(--radix-popper-anchor-height)"}}))}),[FG,Ux]=Pc(dc,{}),m2="SelectViewport",jG=d.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=ja(m2,n),i=Ux(m2,n),s=Ue(t,o.onViewportChange),l=d.useRef(0);return d.createElement(d.Fragment,null,d.createElement("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"}}),d.createElement(rg.Slot,{scope:n},d.createElement(Ae.div,Y({"data-radix-select-viewport":"",role:"presentation"},r,{ref:s,style:{position:"relative",flex:1,overflow:"auto",...r.style},onScroll:ue(r.onScroll,u=>{const f=u.currentTarget,{contentWrapper:m,shouldExpandOnScrollRef:p}=i;if(p!=null&&p.current&&m){const g=Math.abs(l.current-f.scrollTop);if(g>0){const y=window.innerHeight-hi*2,x=parseFloat(m.style.minHeight),S=parseFloat(m.style.height),E=Math.max(x,S);if(E0?C:0,m.style.justifyContent="flex-end")}}}l.current=f.scrollTop})}))))}),zG="SelectGroup",[BG,UG]=Pc(zG),VG=d.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=nr();return d.createElement(BG,{scope:n,id:o},d.createElement(Ae.div,Y({role:"group","aria-labelledby":o},r,{ref:t})))}),WG="SelectLabel",HG=d.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=UG(WG,n);return d.createElement(Ae.div,Y({id:o.id},r,{ref:t}))}),_1="SelectItem",[KG,c5]=Pc(_1),GG=d.forwardRef((e,t)=>{const{__scopeSelect:n,value:r,disabled:o=!1,textValue:i,...s}=e,l=Fa(_1,n),u=ja(_1,n),f=l.value===r,[m,p]=d.useState(i??""),[g,y]=d.useState(!1),x=Ue(t,_=>{var b;return(b=u.itemRefCallback)===null||b===void 0?void 0:b.call(u,_,r,o)}),S=nr(),E=()=>{o||(l.onValueChange(r),l.onOpenChange(!1))};if(r==="")throw new Error("A must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.");return d.createElement(KG,{scope:n,value:r,disabled:o,textId:S,isSelected:f,onItemTextChange:d.useCallback(_=>{p(b=>{var C;return b||((C=_==null?void 0:_.textContent)!==null&&C!==void 0?C:"").trim()})},[])},d.createElement(rg.ItemSlot,{scope:n,value:r,disabled:o,textValue:m},d.createElement(Ae.div,Y({role:"option","aria-labelledby":S,"data-highlighted":g?"":void 0,"aria-selected":f&&g,"data-state":f?"checked":"unchecked","aria-disabled":o||void 0,"data-disabled":o?"":void 0,tabIndex:o?void 0:-1},s,{ref:x,onFocus:ue(s.onFocus,()=>y(!0)),onBlur:ue(s.onBlur,()=>y(!1)),onPointerUp:ue(s.onPointerUp,E),onPointerMove:ue(s.onPointerMove,_=>{if(o){var b;(b=u.onItemLeave)===null||b===void 0||b.call(u)}else _.currentTarget.focus({preventScroll:!0})}),onPointerLeave:ue(s.onPointerLeave,_=>{if(_.currentTarget===document.activeElement){var b;(b=u.onItemLeave)===null||b===void 0||b.call(u)}}),onKeyDown:ue(s.onKeyDown,_=>{var b;((b=u.searchRef)===null||b===void 0?void 0:b.current)!==""&&_.key===" "||(_G.includes(_.key)&&E(),_.key===" "&&_.preventDefault())})}))))}),bh="SelectItemText",YG=d.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,...i}=e,s=Fa(bh,n),l=ja(bh,n),u=c5(bh,n),f=RG(bh,n),[m,p]=d.useState(null),g=Ue(t,_=>p(_),u.onItemTextChange,_=>{var b;return(b=l.itemTextRefCallback)===null||b===void 0?void 0:b.call(l,_,u.value,u.disabled)}),y=m==null?void 0:m.textContent,x=d.useMemo(()=>d.createElement("option",{key:u.value,value:u.value,disabled:u.disabled},y),[u.disabled,u.value,y]),{onNativeOptionAdd:S,onNativeOptionRemove:E}=f;return An(()=>(S(x),()=>E(x)),[S,E,x]),d.createElement(d.Fragment,null,d.createElement(Ae.span,Y({id:u.textId},i,{ref:g})),u.isSelected&&s.valueNode&&!s.valueNodeHasChildren?Is.createPortal(i.children,s.valueNode):null)}),XG="SelectItemIndicator",ZG=d.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return c5(XG,n).isSelected?d.createElement(Ae.span,Y({"aria-hidden":!0},r,{ref:t})):null}),g2="SelectScrollUpButton",qG=d.forwardRef((e,t)=>{const n=ja(g2,e.__scopeSelect),r=Ux(g2,e.__scopeSelect),[o,i]=d.useState(!1),s=Ue(t,r.onScrollButtonChange);return An(()=>{if(n.viewport&&n.isPositioned){let f=function(){const m=u.scrollTop>0;i(m)};var l=f;const u=n.viewport;return f(),u.addEventListener("scroll",f),()=>u.removeEventListener("scroll",f)}},[n.viewport,n.isPositioned]),o?d.createElement(u5,Y({},e,{ref:s,onAutoScroll:()=>{const{viewport:l,selectedItem:u}=n;l&&u&&(l.scrollTop=l.scrollTop-u.offsetHeight)}})):null}),v2="SelectScrollDownButton",QG=d.forwardRef((e,t)=>{const n=ja(v2,e.__scopeSelect),r=Ux(v2,e.__scopeSelect),[o,i]=d.useState(!1),s=Ue(t,r.onScrollButtonChange);return An(()=>{if(n.viewport&&n.isPositioned){let f=function(){const m=u.scrollHeight-u.clientHeight,p=Math.ceil(u.scrollTop)u.removeEventListener("scroll",f)}},[n.viewport,n.isPositioned]),o?d.createElement(u5,Y({},e,{ref:s,onAutoScroll:()=>{const{viewport:l,selectedItem:u}=n;l&&u&&(l.scrollTop=l.scrollTop+u.offsetHeight)}})):null}),u5=d.forwardRef((e,t)=>{const{__scopeSelect:n,onAutoScroll:r,...o}=e,i=ja("SelectScrollButton",n),s=d.useRef(null),l=og(n),u=d.useCallback(()=>{s.current!==null&&(window.clearInterval(s.current),s.current=null)},[]);return d.useEffect(()=>()=>u(),[u]),An(()=>{var f;const m=l().find(p=>p.ref.current===document.activeElement);m==null||(f=m.ref.current)===null||f===void 0||f.scrollIntoView({block:"nearest"})},[l]),d.createElement(Ae.div,Y({"aria-hidden":!0},o,{ref:t,style:{flexShrink:0,...o.style},onPointerDown:ue(o.onPointerDown,()=>{s.current===null&&(s.current=window.setInterval(r,50))}),onPointerMove:ue(o.onPointerMove,()=>{var f;(f=i.onItemLeave)===null||f===void 0||f.call(i),s.current===null&&(s.current=window.setInterval(r,50))}),onPointerLeave:ue(o.onPointerLeave,()=>{u()})}))}),JG=d.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return d.createElement(Ae.div,Y({"aria-hidden":!0},r,{ref:t}))});function d5(e){return e===""||e===void 0}const f5=d.forwardRef((e,t)=>{const{value:n,...r}=e,o=d.useRef(null),i=Ue(t,o),s=zx(n);return d.useEffect(()=>{const l=o.current,u=window.HTMLSelectElement.prototype,m=Object.getOwnPropertyDescriptor(u,"value").set;if(s!==n&&m){const p=new Event("change",{bubbles:!0});m.call(l,n),l.dispatchEvent(p)}},[s,n]),d.createElement(Hm,{asChild:!0},d.createElement("select",Y({},r,{ref:i,defaultValue:n})))});f5.displayName="BubbleSelect";function h5(e){const t=Ft(e),n=d.useRef(""),r=d.useRef(0),o=d.useCallback(s=>{const l=n.current+s;t(l),function u(f){n.current=f,window.clearTimeout(r.current),f!==""&&(r.current=window.setTimeout(()=>u(""),1e3))}(l)},[t]),i=d.useCallback(()=>{n.current="",window.clearTimeout(r.current)},[]);return d.useEffect(()=>()=>window.clearTimeout(r.current),[]),[n,o,i]}function p5(e,t,n){const o=t.length>1&&Array.from(t).every(f=>f===t[0])?t[0]:t,i=n?e.indexOf(n):-1;let s=eY(e,Math.max(i,0));o.length===1&&(s=s.filter(f=>f!==n));const u=s.find(f=>f.textValue.toLowerCase().startsWith(o.toLowerCase()));return u!==n?u:void 0}function eY(e,t){return e.map((n,r)=>e[(t+r)%e.length])}const tY=kG,m5=PG,nY=MG,rY=OG,oY=NG,g5=DG,iY=jG,sY=VG,v5=HG,y5=GG,aY=YG,lY=ZG,w5=qG,x5=QG,b5=JG,Uo=tY,vi=sY,Vo=nY,go=d.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(m5,{ref:r,className:Ce("flex h-9 w-full items-center justify-between whitespace-nowrap rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",e),tabIndex:-1,...n,children:[t,v.jsx(rY,{asChild:!0,children:v.jsx(Zj,{className:"h-4 w-4 opacity-50"})})]}));go.displayName=m5.displayName;const S5=d.forwardRef(({className:e,...t},n)=>v.jsx(w5,{ref:n,className:Ce("flex cursor-default items-center justify-center py-1",e),...t,children:v.jsx(rz,{})}));S5.displayName=w5.displayName;const _5=d.forwardRef(({className:e,...t},n)=>v.jsx(x5,{ref:n,className:Ce("flex cursor-default items-center justify-center py-1",e),...t,children:v.jsx(Jj,{})}));_5.displayName=x5.displayName;const vo=d.forwardRef(({className:e,children:t,position:n="popper",...r},o)=>v.jsx(oY,{children:v.jsxs(g5,{ref:o,className:Ce("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",n==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:n,onCloseAutoFocus:i=>i.preventDefault(),...r,children:[v.jsx(S5,{}),v.jsx(iY,{className:Ce("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),v.jsx(_5,{})]})}));vo.displayName=g5.displayName;const cY=d.forwardRef(({className:e,...t},n)=>v.jsx(v5,{ref:n,className:Ce("px-2 py-1.5 text-sm font-semibold",e),...t}));cY.displayName=v5.displayName;const yo=d.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(y5,{ref:r,className:Ce("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-2 pr-8 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[v.jsx("span",{className:"absolute right-2 flex h-3.5 w-3.5 items-center justify-center",children:v.jsx(lY,{children:v.jsx(yT,{className:"h-4 w-4"})})}),v.jsx(aY,{children:t})]}));yo.displayName=y5.displayName;const uY=d.forwardRef(({className:e,...t},n)=>v.jsx(b5,{ref:n,className:Ce("-mx-1 my-1 h-px bg-muted",e),...t}));uY.displayName=b5.displayName;function dY(e,t){return d.useReducer((n,r)=>{const o=t[n][r];return o??n},e)}const E5="ScrollArea",[C5,Ste]=Mn(E5),[fY,qr]=C5(E5),hY=d.forwardRef((e,t)=>{const{__scopeScrollArea:n,type:r="hover",dir:o,scrollHideDelay:i=600,...s}=e,[l,u]=d.useState(null),[f,m]=d.useState(null),[p,g]=d.useState(null),[y,x]=d.useState(null),[S,E]=d.useState(null),[_,b]=d.useState(0),[C,R]=d.useState(0),[P,O]=d.useState(!1),[A,D]=d.useState(!1),B=Ue(t,J=>u(J)),V=Tc(o);return d.createElement(fY,{scope:n,type:r,dir:V,scrollHideDelay:i,scrollArea:l,viewport:f,onViewportChange:m,content:p,onContentChange:g,scrollbarX:y,onScrollbarXChange:x,scrollbarXEnabled:P,onScrollbarXEnabledChange:O,scrollbarY:S,onScrollbarYChange:E,scrollbarYEnabled:A,onScrollbarYEnabledChange:D,onCornerWidthChange:b,onCornerHeightChange:R},d.createElement(Ae.div,Y({dir:V},s,{ref:B,style:{position:"relative","--radix-scroll-area-corner-width":_+"px","--radix-scroll-area-corner-height":C+"px",...e.style}})))}),pY="ScrollAreaViewport",mY=d.forwardRef((e,t)=>{const{__scopeScrollArea:n,children:r,...o}=e,i=qr(pY,n),s=d.useRef(null),l=Ue(t,s,i.onViewportChange);return d.createElement(d.Fragment,null,d.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}"}}),d.createElement(Ae.div,Y({"data-radix-scroll-area-viewport":""},o,{ref:l,style:{overflowX:i.scrollbarXEnabled?"scroll":"hidden",overflowY:i.scrollbarYEnabled?"scroll":"hidden",...e.style}}),d.createElement("div",{ref:i.onContentChange,style:{minWidth:"100%",display:"table"}},r)))}),Oi="ScrollAreaScrollbar",$5=d.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=qr(Oi,e.__scopeScrollArea),{onScrollbarXEnabledChange:i,onScrollbarYEnabledChange:s}=o,l=e.orientation==="horizontal";return d.useEffect(()=>(l?i(!0):s(!0),()=>{l?i(!1):s(!1)}),[l,i,s]),o.type==="hover"?d.createElement(gY,Y({},r,{ref:t,forceMount:n})):o.type==="scroll"?d.createElement(vY,Y({},r,{ref:t,forceMount:n})):o.type==="auto"?d.createElement(R5,Y({},r,{ref:t,forceMount:n})):o.type==="always"?d.createElement(Vx,Y({},r,{ref:t})):null}),gY=d.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=qr(Oi,e.__scopeScrollArea),[i,s]=d.useState(!1);return d.useEffect(()=>{const l=o.scrollArea;let u=0;if(l){const f=()=>{window.clearTimeout(u),s(!0)},m=()=>{u=window.setTimeout(()=>s(!1),o.scrollHideDelay)};return l.addEventListener("pointerenter",f),l.addEventListener("pointerleave",m),()=>{window.clearTimeout(u),l.removeEventListener("pointerenter",f),l.removeEventListener("pointerleave",m)}}},[o.scrollArea,o.scrollHideDelay]),d.createElement(Sn,{present:n||i},d.createElement(R5,Y({"data-state":i?"visible":"hidden"},r,{ref:t})))}),vY=d.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=qr(Oi,e.__scopeScrollArea),i=e.orientation==="horizontal",s=sg(()=>u("SCROLL_END"),100),[l,u]=dY("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 d.useEffect(()=>{if(l==="idle"){const f=window.setTimeout(()=>u("HIDE"),o.scrollHideDelay);return()=>window.clearTimeout(f)}},[l,o.scrollHideDelay,u]),d.useEffect(()=>{const f=o.viewport,m=i?"scrollLeft":"scrollTop";if(f){let p=f[m];const g=()=>{const y=f[m];p!==y&&(u("SCROLL"),s()),p=y};return f.addEventListener("scroll",g),()=>f.removeEventListener("scroll",g)}},[o.viewport,i,u,s]),d.createElement(Sn,{present:n||l!=="hidden"},d.createElement(Vx,Y({"data-state":l==="hidden"?"hidden":"visible"},r,{ref:t,onPointerEnter:ue(e.onPointerEnter,()=>u("POINTER_ENTER")),onPointerLeave:ue(e.onPointerLeave,()=>u("POINTER_LEAVE"))})))}),R5=d.forwardRef((e,t)=>{const n=qr(Oi,e.__scopeScrollArea),{forceMount:r,...o}=e,[i,s]=d.useState(!1),l=e.orientation==="horizontal",u=sg(()=>{if(n.viewport){const f=n.viewport.offsetWidth{const{orientation:n="vertical",...r}=e,o=qr(Oi,e.__scopeScrollArea),i=d.useRef(null),s=d.useRef(0),[l,u]=d.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),f=A5(l.viewport,l.content),m={...r,sizes:l,onSizesChange:u,hasThumb:f>0&&f<1,onThumbChange:g=>i.current=g,onThumbPointerUp:()=>s.current=0,onThumbPointerDown:g=>s.current=g};function p(g,y){return CY(g,s.current,l,y)}return n==="horizontal"?d.createElement(yY,Y({},m,{ref:t,onThumbPositionChange:()=>{if(o.viewport&&i.current){const g=o.viewport.scrollLeft,y=y2(g,l,o.dir);i.current.style.transform=`translate3d(${y}px, 0, 0)`}},onWheelScroll:g=>{o.viewport&&(o.viewport.scrollLeft=g)},onDragScroll:g=>{o.viewport&&(o.viewport.scrollLeft=p(g,o.dir))}})):n==="vertical"?d.createElement(wY,Y({},m,{ref:t,onThumbPositionChange:()=>{if(o.viewport&&i.current){const g=o.viewport.scrollTop,y=y2(g,l);i.current.style.transform=`translate3d(0, ${y}px, 0)`}},onWheelScroll:g=>{o.viewport&&(o.viewport.scrollTop=g)},onDragScroll:g=>{o.viewport&&(o.viewport.scrollTop=p(g))}})):null}),yY=d.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,i=qr(Oi,e.__scopeScrollArea),[s,l]=d.useState(),u=d.useRef(null),f=Ue(t,u,i.onScrollbarXChange);return d.useEffect(()=>{u.current&&l(getComputedStyle(u.current))},[u]),d.createElement(T5,Y({"data-orientation":"horizontal"},o,{ref:f,sizes:n,style:{bottom:0,left:i.dir==="rtl"?"var(--radix-scroll-area-corner-width)":0,right:i.dir==="ltr"?"var(--radix-scroll-area-corner-width)":0,"--radix-scroll-area-thumb-width":ig(n)+"px",...e.style},onThumbPointerDown:m=>e.onThumbPointerDown(m.x),onDragScroll:m=>e.onDragScroll(m.x),onWheelScroll:(m,p)=>{if(i.viewport){const g=i.viewport.scrollLeft+m.deltaX;e.onWheelScroll(g),O5(g,p)&&m.preventDefault()}},onResize:()=>{u.current&&i.viewport&&s&&r({content:i.viewport.scrollWidth,viewport:i.viewport.offsetWidth,scrollbar:{size:u.current.clientWidth,paddingStart:Vp(s.paddingLeft),paddingEnd:Vp(s.paddingRight)}})}}))}),wY=d.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,i=qr(Oi,e.__scopeScrollArea),[s,l]=d.useState(),u=d.useRef(null),f=Ue(t,u,i.onScrollbarYChange);return d.useEffect(()=>{u.current&&l(getComputedStyle(u.current))},[u]),d.createElement(T5,Y({"data-orientation":"vertical"},o,{ref:f,sizes:n,style:{top:0,right:i.dir==="ltr"?0:void 0,left:i.dir==="rtl"?0:void 0,bottom:"var(--radix-scroll-area-corner-height)","--radix-scroll-area-thumb-height":ig(n)+"px",...e.style},onThumbPointerDown:m=>e.onThumbPointerDown(m.y),onDragScroll:m=>e.onDragScroll(m.y),onWheelScroll:(m,p)=>{if(i.viewport){const g=i.viewport.scrollTop+m.deltaY;e.onWheelScroll(g),O5(g,p)&&m.preventDefault()}},onResize:()=>{u.current&&i.viewport&&s&&r({content:i.viewport.scrollHeight,viewport:i.viewport.offsetHeight,scrollbar:{size:u.current.clientHeight,paddingStart:Vp(s.paddingTop),paddingEnd:Vp(s.paddingBottom)}})}}))}),[xY,k5]=C5(Oi),T5=d.forwardRef((e,t)=>{const{__scopeScrollArea:n,sizes:r,hasThumb:o,onThumbChange:i,onThumbPointerUp:s,onThumbPointerDown:l,onThumbPositionChange:u,onDragScroll:f,onWheelScroll:m,onResize:p,...g}=e,y=qr(Oi,n),[x,S]=d.useState(null),E=Ue(t,B=>S(B)),_=d.useRef(null),b=d.useRef(""),C=y.viewport,R=r.content-r.viewport,P=Ft(m),O=Ft(u),A=sg(p,10);function D(B){if(_.current){const V=B.clientX-_.current.left,J=B.clientY-_.current.top;f({x:V,y:J})}}return d.useEffect(()=>{const B=V=>{const J=V.target;(x==null?void 0:x.contains(J))&&P(V,R)};return document.addEventListener("wheel",B,{passive:!1}),()=>document.removeEventListener("wheel",B,{passive:!1})},[C,x,R,P]),d.useEffect(O,[r,O]),fc(x,A),fc(y.content,A),d.createElement(xY,{scope:n,scrollbar:x,hasThumb:o,onThumbChange:Ft(i),onThumbPointerUp:Ft(s),onThumbPositionChange:O,onThumbPointerDown:Ft(l)},d.createElement(Ae.div,Y({},g,{ref:E,style:{position:"absolute",...g.style},onPointerDown:ue(e.onPointerDown,B=>{B.button===0&&(B.target.setPointerCapture(B.pointerId),_.current=x.getBoundingClientRect(),b.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",y.viewport&&(y.viewport.style.scrollBehavior="auto"),D(B))}),onPointerMove:ue(e.onPointerMove,D),onPointerUp:ue(e.onPointerUp,B=>{const V=B.target;V.hasPointerCapture(B.pointerId)&&V.releasePointerCapture(B.pointerId),document.body.style.webkitUserSelect=b.current,y.viewport&&(y.viewport.style.scrollBehavior=""),_.current=null})})))}),E1="ScrollAreaThumb",bY=d.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=k5(E1,e.__scopeScrollArea);return d.createElement(Sn,{present:n||o.hasThumb},d.createElement(SY,Y({ref:t},r)))}),SY=d.forwardRef((e,t)=>{const{__scopeScrollArea:n,style:r,...o}=e,i=qr(E1,n),s=k5(E1,n),{onThumbPositionChange:l}=s,u=Ue(t,p=>s.onThumbChange(p)),f=d.useRef(),m=sg(()=>{f.current&&(f.current(),f.current=void 0)},100);return d.useEffect(()=>{const p=i.viewport;if(p){const g=()=>{if(m(),!f.current){const y=$Y(p,l);f.current=y,l()}};return l(),p.addEventListener("scroll",g),()=>p.removeEventListener("scroll",g)}},[i.viewport,m,l]),d.createElement(Ae.div,Y({"data-state":s.hasThumb?"visible":"hidden"},o,{ref:u,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...r},onPointerDownCapture:ue(e.onPointerDownCapture,p=>{const y=p.target.getBoundingClientRect(),x=p.clientX-y.left,S=p.clientY-y.top;s.onThumbPointerDown({x,y:S})}),onPointerUp:ue(e.onPointerUp,s.onThumbPointerUp)}))}),P5="ScrollAreaCorner",_Y=d.forwardRef((e,t)=>{const n=qr(P5,e.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?d.createElement(EY,Y({},e,{ref:t})):null}),EY=d.forwardRef((e,t)=>{const{__scopeScrollArea:n,...r}=e,o=qr(P5,n),[i,s]=d.useState(0),[l,u]=d.useState(0),f=!!(i&&l);return fc(o.scrollbarX,()=>{var m;const p=((m=o.scrollbarX)===null||m===void 0?void 0:m.offsetHeight)||0;o.onCornerHeightChange(p),u(p)}),fc(o.scrollbarY,()=>{var m;const p=((m=o.scrollbarY)===null||m===void 0?void 0:m.offsetWidth)||0;o.onCornerWidthChange(p),s(p)}),f?d.createElement(Ae.div,Y({},r,{ref:t,style:{width:i,height:l,position:"absolute",right:o.dir==="ltr"?0:void 0,left:o.dir==="rtl"?0:void 0,bottom:0,...e.style}})):null});function Vp(e){return e?parseInt(e,10):0}function A5(e,t){const n=e/t;return isNaN(n)?0:n}function ig(e){const t=A5(e.viewport,e.content),n=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,r=(e.scrollbar.size-n)*t;return Math.max(r,18)}function CY(e,t,n,r="ltr"){const o=ig(n),i=o/2,s=t||i,l=o-s,u=n.scrollbar.paddingStart+s,f=n.scrollbar.size-n.scrollbar.paddingEnd-l,m=n.content-n.viewport,p=r==="ltr"?[0,m]:[m*-1,0];return M5([u,f],p)(e)}function y2(e,t,n="ltr"){const r=ig(t),o=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,i=t.scrollbar.size-o,s=t.content-t.viewport,l=i-r,u=n==="ltr"?[0,s]:[s*-1,0],f=fd(e,u);return M5([0,s],[0,l])(f)}function M5(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 O5(e,t){return e>0&&e{})=>{let n={left:e.scrollLeft,top:e.scrollTop},r=0;return function o(){const i={left:e.scrollLeft,top:e.scrollTop},s=n.left!==i.left,l=n.top!==i.top;(s||l)&&t(),n=i,r=window.requestAnimationFrame(o)}(),()=>window.cancelAnimationFrame(r)};function sg(e,t){const n=Ft(e),r=d.useRef(0);return d.useEffect(()=>()=>window.clearTimeout(r.current),[]),d.useCallback(()=>{window.clearTimeout(r.current),r.current=window.setTimeout(n,t)},[n,t])}function fc(e,t){const n=Ft(t);An(()=>{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 N5=hY,RY=mY,kY=_Y,ag=d.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(N5,{ref:r,className:Ce("relative overflow-hidden",e),scrollHideDelay:400,...n,children:[v.jsx(RY,{className:"h-full w-full rounded-[inherit]",children:t}),v.jsx(D5,{}),v.jsx(kY,{})]}));ag.displayName=N5.displayName;const D5=d.forwardRef(({className:e,orientation:t="vertical",...n},r)=>v.jsx($5,{ref:r,orientation:t,className:Ce("flex touch-none select-none transition-colors",t==="vertical"&&"h-full w-2.5 border-l border-l-transparent p-[1px]",t==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",e),...n,children:v.jsx(bY,{className:"relative flex-1 rounded-full bg-border"})}));D5.displayName=$5.displayName;const I5="Name",L5="Created time",F5="Modified time",w2="input",TY="output",x2={[Es.NAME]:I5,[Es.CTIME]:L5,[Es.MTIME]:F5};function PY(e){const{onPhotoClick:t,photoWidth:n}=e,[r,o]=OP(!1),[i,s]=bt(V=>[V.fileManagerState,V.updateFileManagerState]),{toast:l}=Id(),[u,f]=d.useState(0),[m,p]=d.useState(0),g=d.useRef(null),y=lV(i.searchText,300),[x,S]=d.useState(w2),[E,_]=d.useState([]),[b,C]=d.useState([]),[R,P]=d.useState(0);Zn("f",()=>{o()}),Zn("left",()=>{let V=R;R>0&&(V=R-1),P(V),t(x,b[V].name)},[R,b]),Zn("right",()=>{let V=R;R{r||p(u)},[r,u]);const O=d.useCallback(V=>{V!==null&&r&&setTimeout(()=>{V.scrollTo({top:m,left:0})},100)},[r,m]);d.useEffect(()=>{(async()=>{try{const J=await Wj(x);_(J)}catch(J){l({variant:"destructive",title:"Uh oh! Something went wrong.",description:J.message?J.message:J.toString()})}})()},[x]),d.useEffect(()=>{if(!r)return;(async()=>{try{let J=E;y&&(J=new kc(J,{keys:["name"]}).search(y).map(ne=>J[ne.refIndex])),J=xH.orderBy(J,i.sortBy,i.sortOrder);const G=J.map(se=>{const U=n,ne=se.height*(U/se.width);return{src:`${Ls}/media_thumbnail_file?tab=${x}&filename=${encodeURIComponent(se.name)}&width=${Math.ceil(U)}&height=${Math.ceil(ne)}`,height:ne,width:U,name:se.name}});C(G)}catch(J){l({variant:"destructive",title:"Uh oh! Something went wrong.",description:J.message?J.message:J.toString()})}})()},[E,y,i,n,r]);const A=V=>{f(V.currentTarget.scrollTop)},D=({index:V})=>{o(),P(V),t(x,b[V].name)},B=()=>v.jsxs("div",{className:"flex justify-start items-center gap-[12px]",children:[v.jsx("div",{children:`Images (${b.length})`}),v.jsxs("div",{className:"flex",children:[v.jsx(yn,{tooltip:"Rows layout",onClick:()=>{s({layout:"rows"})},children:v.jsx(pz,{className:i.layout!=="rows"?"opacity-50":""})}),v.jsx(yn,{tooltip:"Grid layout",onClick:()=>{s({layout:"masonry"})},children:v.jsx(fz,{className:i.layout!=="masonry"?"opacity-50":""})})]})]});return v.jsxs(Jm,{open:r,onOpenChange:o,children:[v.jsx(fP,{asChild:!0,children:v.jsx(yn,{tooltip:"File Manager",children:v.jsx(eV,{})})}),v.jsxs(Hd,{className:"h-4/5 max-w-6xl",children:[v.jsx(Kd,{children:B()}),v.jsxs("div",{className:"flex justify-between gap-8 items-center",children:[v.jsxs("div",{className:"flex relative justify-start items-center",children:[v.jsx(lz,{className:"absolute left-[8px]"}),v.jsx(Ld,{ref:g,value:i.searchText,className:"w-[250px] pl-[30px]",tabIndex:-1,onInput:V=>{V.preventDefault(),V.stopPropagation();const J=V.target;s({searchText:J.value})},placeholder:"Search by file name"})]}),v.jsx(a5,{defaultValue:x,onValueChange:V=>S(V),children:v.jsxs(jx,{"aria-label":"Manage your account",children:[v.jsx(pa,{value:w2,children:"Image Directory"}),v.jsx(pa,{value:TY,children:"Output Directory"})]})}),v.jsx("div",{className:"flex gap-2",children:v.jsxs("div",{className:"flex gap-1",children:[v.jsxs(Uo,{value:x2[i.sortBy],onValueChange:V=>{switch(V){case I5:s({sortBy:Es.NAME});break;case L5:s({sortBy:Es.CTIME});break;case F5:s({sortBy:Es.MTIME});break}},children:[v.jsx(go,{className:"w-[140px]",children:v.jsx(Vo,{})}),v.jsx(vo,{children:Object.values(x2).map(V=>v.jsx(yo,{value:V,children:V},V))})]}),i.sortOrder===Ou.DESCENDING?v.jsx(yn,{tooltip:"Descending Order",onClick:()=>{s({sortOrder:Ou.ASCENDING})},children:v.jsx(iK,{})}):v.jsx(yn,{tooltip:"Ascending Order",onClick:()=>{s({sortOrder:Ou.DESCENDING})},children:v.jsx(lK,{})})]})})]}),v.jsx(ag,{className:"w-full h-full rounded-md",onScroll:A,ref:O,children:v.jsx(nK,{layout:i.layout,photos:b,spacing:12,padding:0,onClick:D})})]})]})}var Yd=e=>e.type==="checkbox",$l=e=>e instanceof Date,Fn=e=>e==null;const j5=e=>typeof e=="object";var sn=e=>!Fn(e)&&!Array.isArray(e)&&j5(e)&&!$l(e),z5=e=>sn(e)&&e.target?Yd(e.target)?e.target.checked:e.target.value:e,AY=e=>e.substring(0,e.search(/\.\d+(\.|$)/))||e,B5=(e,t)=>e.has(AY(t)),MY=e=>{const t=e.constructor&&e.constructor.prototype;return sn(t)&&t.hasOwnProperty("isPrototypeOf")},Wx=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function so(e){let t;const n=Array.isArray(e);if(e instanceof Date)t=new Date(e);else if(e instanceof Set)t=new Set(e);else if(!(Wx&&(e instanceof Blob||e instanceof FileList))&&(n||sn(e)))if(t=n?[]:{},!n&&!MY(e))t=e;else for(const r in e)e.hasOwnProperty(r)&&(t[r]=so(e[r]));else return e;return t}var Xd=e=>Array.isArray(e)?e.filter(Boolean):[],Ht=e=>e===void 0,ve=(e,t,n)=>{if(!t||!sn(e))return n;const r=Xd(t.split(/[,[\].]+?/)).reduce((o,i)=>Fn(o)?o:o[i],e);return Ht(r)||r===e?Ht(e[t])?n:e[t]:r},Fo=e=>typeof e=="boolean";const Wp={BLUR:"blur",FOCUS_OUT:"focusout",CHANGE:"change"},mo={onBlur:"onBlur",onChange:"onChange",onSubmit:"onSubmit",onTouched:"onTouched",all:"all"},ui={max:"max",min:"min",maxLength:"maxLength",minLength:"minLength",pattern:"pattern",required:"required",validate:"validate"},U5=je.createContext(null),lg=()=>je.useContext(U5),OY=e=>{const{children:t,...n}=e;return je.createElement(U5.Provider,{value:n},t)};var V5=(e,t,n,r=!0)=>{const o={defaultValues:t._defaultValues};for(const i in e)Object.defineProperty(o,i,{get:()=>{const s=i;return t._proxyFormState[s]!==mo.all&&(t._proxyFormState[s]=!r||mo.all),n&&(n[s]=!0),e[s]}});return o},Fr=e=>sn(e)&&!Object.keys(e).length,W5=(e,t,n,r)=>{n(e);const{name:o,...i}=e;return Fr(i)||Object.keys(i).length>=Object.keys(t).length||Object.keys(i).find(s=>t[s]===(!r||mo.all))},ep=e=>Array.isArray(e)?e:[e],H5=(e,t,n)=>!e||!t||e===t||ep(e).some(r=>r&&(n?r===t:r.startsWith(t)||t.startsWith(r)));function Hx(e){const t=je.useRef(e);t.current=e,je.useEffect(()=>{const n=!e.disabled&&t.current.subject&&t.current.subject.subscribe({next:t.current.next});return()=>{n&&n.unsubscribe()}},[e.disabled])}function NY(e){const t=lg(),{control:n=t.control,disabled:r,name:o,exact:i}=e||{},[s,l]=je.useState(n._formState),u=je.useRef(!0),f=je.useRef({isDirty:!1,isLoading:!1,dirtyFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1}),m=je.useRef(o);return m.current=o,Hx({disabled:r,next:p=>u.current&&H5(m.current,p.name,i)&&W5(p,f.current,n._updateFormState)&&l({...n._formState,...p}),subject:n._subjects.state}),je.useEffect(()=>(u.current=!0,f.current.isValid&&n._updateValid(!0),()=>{u.current=!1}),[n]),V5(s,n,f.current,!1)}var Wo=e=>typeof e=="string",K5=(e,t,n,r,o)=>Wo(e)?(r&&t.watch.add(e),ve(n,e,o)):Array.isArray(e)?e.map(i=>(r&&t.watch.add(i),ve(n,i))):(r&&(t.watchAll=!0),n);function DY(e){const t=lg(),{control:n=t.control,name:r,defaultValue:o,disabled:i,exact:s}=e||{},l=je.useRef(r);l.current=r,Hx({disabled:i,subject:n._subjects.values,next:m=>{H5(l.current,m.name,s)&&f(so(K5(l.current,n._names,m.values||n._formValues,!1,o)))}});const[u,f]=je.useState(n._getWatch(r,o));return je.useEffect(()=>n._removeUnmounted()),u}var Kx=e=>/^\w*$/.test(e),G5=e=>Xd(e.replace(/["|']|\]/g,"").split(/\.|\[/));function wt(e,t,n){let r=-1;const o=Kx(t)?[t]:G5(t),i=o.length,s=i-1;for(;++r{const m=o._options.shouldUnregister||i,p=(g,y)=>{const x=ve(o._fields,g);x&&(x._f.mount=y)};if(p(n,!0),m){const g=so(ve(o._options.defaultValues,n));wt(o._defaultValues,n,g),Ht(ve(o._formValues,n))&&wt(o._formValues,n,g)}return()=>{(s?m&&!o._state.action:m)?o.unregister(n):p(n,!1)}},[n,o,s,i]),je.useEffect(()=>{ve(o._fields,n)&&o._updateDisabledField({disabled:r,fields:o._fields,name:n,value:ve(o._fields,n)._f.value})},[r,n,o]),{field:{name:n,value:l,...Fo(r)||Fo(u.disabled)?{disabled:u.disabled||r}:{},onChange:je.useCallback(m=>f.current.onChange({target:{value:z5(m),name:n},type:Wp.CHANGE}),[n]),onBlur:je.useCallback(()=>f.current.onBlur({target:{value:ve(o._formValues,n),name:n},type:Wp.BLUR}),[n,o]),ref:m=>{const p=ve(o._fields,n);p&&m&&(p._f.ref={focus:()=>m.focus(),select:()=>m.select(),setCustomValidity:g=>m.setCustomValidity(g),reportValidity:()=>m.reportValidity()})}},formState:u,fieldState:Object.defineProperties({},{invalid:{enumerable:!0,get:()=>!!ve(u.errors,n)},isDirty:{enumerable:!0,get:()=>!!ve(u.dirtyFields,n)},isTouched:{enumerable:!0,get:()=>!!ve(u.touchedFields,n)},error:{enumerable:!0,get:()=>ve(u.errors,n)}})}}const LY=e=>e.render(IY(e));var Y5=(e,t,n,r,o)=>t?{...n[e],types:{...n[e]&&n[e].types?n[e].types:{},[r]:o||!0}}:{},b2=e=>({isOnSubmit:!e||e===mo.onSubmit,isOnBlur:e===mo.onBlur,isOnChange:e===mo.onChange,isOnAll:e===mo.all,isOnTouch:e===mo.onTouched}),S2=(e,t,n)=>!n&&(t.watchAll||t.watch.has(e)||[...t.watch].some(r=>e.startsWith(r)&&/^\.\w+/.test(e.slice(r.length))));const tp=(e,t,n,r)=>{for(const o of n||Object.keys(e)){const i=ve(e,o);if(i){const{_f:s,...l}=i;if(s){if(s.refs&&s.refs[0]&&t(s.refs[0],o)&&!r)break;if(s.ref&&t(s.ref,s.name)&&!r)break}else sn(l)&&tp(l,t)}}};var FY=(e,t,n)=>{const r=Xd(ve(e,n));return wt(r,"root",t[n]),wt(e,n,r),e},Gx=e=>e.type==="file",ms=e=>typeof e=="function",Hp=e=>{if(!Wx)return!1;const t=e?e.ownerDocument:0;return e instanceof(t&&t.defaultView?t.defaultView.HTMLElement:HTMLElement)},np=e=>Wo(e),Yx=e=>e.type==="radio",Kp=e=>e instanceof RegExp;const _2={value:!1,isValid:!1},E2={value:!0,isValid:!0};var X5=e=>{if(Array.isArray(e)){if(e.length>1){const t=e.filter(n=>n&&n.checked&&!n.disabled).map(n=>n.value);return{value:t,isValid:!!t.length}}return e[0].checked&&!e[0].disabled?e[0].attributes&&!Ht(e[0].attributes.value)?Ht(e[0].value)||e[0].value===""?E2:{value:e[0].value,isValid:!0}:E2:_2}return _2};const C2={isValid:!1,value:null};var Z5=e=>Array.isArray(e)?e.reduce((t,n)=>n&&n.checked&&!n.disabled?{isValid:!0,value:n.value}:t,C2):C2;function $2(e,t,n="validate"){if(np(e)||Array.isArray(e)&&e.every(np)||Fo(e)&&!e)return{type:n,message:np(e)?e:"",ref:t}}var sl=e=>sn(e)&&!Kp(e)?e:{value:e,message:""},R2=async(e,t,n,r,o)=>{const{ref:i,refs:s,required:l,maxLength:u,minLength:f,min:m,max:p,pattern:g,validate:y,name:x,valueAsNumber:S,mount:E,disabled:_}=e._f,b=ve(t,x);if(!E||_)return{};const C=s?s[0]:i,R=G=>{r&&C.reportValidity&&(C.setCustomValidity(Fo(G)?"":G||""),C.reportValidity())},P={},O=Yx(i),A=Yd(i),D=O||A,B=(S||Gx(i))&&Ht(i.value)&&Ht(b)||Hp(i)&&i.value===""||b===""||Array.isArray(b)&&!b.length,V=Y5.bind(null,x,n,P),J=(G,se,U,ne=ui.maxLength,M=ui.minLength)=>{const ee=G?se:U;P[x]={type:G?ne:M,message:ee,ref:i,...V(G?ne:M,ee)}};if(o?!Array.isArray(b)||!b.length:l&&(!D&&(B||Fn(b))||Fo(b)&&!b||A&&!X5(s).isValid||O&&!Z5(s).isValid)){const{value:G,message:se}=np(l)?{value:!!l,message:l}:sl(l);if(G&&(P[x]={type:ui.required,message:se,ref:C,...V(ui.required,se)},!n))return R(se),P}if(!B&&(!Fn(m)||!Fn(p))){let G,se;const U=sl(p),ne=sl(m);if(!Fn(b)&&!isNaN(b)){const M=i.valueAsNumber||b&&+b;Fn(U.value)||(G=M>U.value),Fn(ne.value)||(se=Mnew Date(new Date().toDateString()+" "+W),H=i.type=="time",X=i.type=="week";Wo(U.value)&&b&&(G=H?ee(b)>ee(U.value):X?b>U.value:M>new Date(U.value)),Wo(ne.value)&&b&&(se=H?ee(b)+G.value,ne=!Fn(se.value)&&b.length<+se.value;if((U||ne)&&(J(U,G.message,se.message),!n))return R(P[x].message),P}if(g&&!B&&Wo(b)){const{value:G,message:se}=sl(g);if(Kp(G)&&!b.match(G)&&(P[x]={type:ui.pattern,message:se,ref:i,...V(ui.pattern,se)},!n))return R(se),P}if(y){if(ms(y)){const G=await y(b,t),se=$2(G,C);if(se&&(P[x]={...se,...V(ui.validate,se.message)},!n))return R(se.message),P}else if(sn(y)){let G={};for(const se in y){if(!Fr(G)&&!n)break;const U=$2(await y[se](b,t),C,se);U&&(G={...U,...V(se,U.message)},R(U.message),n&&(P[x]=G))}if(!Fr(G)&&(P[x]={ref:C,...G},!n))return P}}return R(!0),P};function jY(e,t){const n=t.slice(0,-1).length;let r=0;for(;r{for(const i of e)i.next&&i.next(o)},subscribe:o=>(e.push(o),{unsubscribe:()=>{e=e.filter(i=>i!==o)}}),unsubscribe:()=>{e=[]}}}var Gp=e=>Fn(e)||!j5(e);function ma(e,t){if(Gp(e)||Gp(t))return e===t;if($l(e)&&$l(t))return e.getTime()===t.getTime();const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(const o of n){const i=e[o];if(!r.includes(o))return!1;if(o!=="ref"){const s=t[o];if($l(i)&&$l(s)||sn(i)&&sn(s)||Array.isArray(i)&&Array.isArray(s)?!ma(i,s):i!==s)return!1}}return!0}var q5=e=>e.type==="select-multiple",BY=e=>Yx(e)||Yd(e),N0=e=>Hp(e)&&e.isConnected,Q5=e=>{for(const t in e)if(ms(e[t]))return!0;return!1};function Yp(e,t={}){const n=Array.isArray(e);if(sn(e)||n)for(const r in e)Array.isArray(e[r])||sn(e[r])&&!Q5(e[r])?(t[r]=Array.isArray(e[r])?[]:{},Yp(e[r],t[r])):Fn(e[r])||(t[r]=!0);return t}function J5(e,t,n){const r=Array.isArray(e);if(sn(e)||r)for(const o in e)Array.isArray(e[o])||sn(e[o])&&!Q5(e[o])?Ht(t)||Gp(n[o])?n[o]=Array.isArray(e[o])?Yp(e[o],[]):{...Yp(e[o])}:J5(e[o],Fn(t)?{}:t[o],n[o]):n[o]=!ma(e[o],t[o]);return n}var D0=(e,t)=>J5(e,t,Yp(t)),e3=(e,{valueAsNumber:t,valueAsDate:n,setValueAs:r})=>Ht(e)?e:t?e===""?NaN:e&&+e:n&&Wo(e)?new Date(e):r?r(e):e;function I0(e){const t=e.ref;if(!(e.refs?e.refs.every(n=>n.disabled):t.disabled))return Gx(t)?t.files:Yx(t)?Z5(e.refs).value:q5(t)?[...t.selectedOptions].map(({value:n})=>n):Yd(t)?X5(e.refs).value:e3(Ht(t.value)?e.ref.value:t.value,e)}var UY=(e,t,n,r)=>{const o={};for(const i of e){const s=ve(t,i);s&&wt(o,i,s._f)}return{criteriaMode:n,names:[...e],fields:o,shouldUseNativeValidation:r}},du=e=>Ht(e)?e:Kp(e)?e.source:sn(e)?Kp(e.value)?e.value.source:e.value:e,VY=e=>e.mount&&(e.required||e.min||e.max||e.maxLength||e.minLength||e.pattern||e.validate);function k2(e,t,n){const r=ve(e,n);if(r||Kx(n))return{error:r,name:n};const o=n.split(".");for(;o.length;){const i=o.join("."),s=ve(t,i),l=ve(e,i);if(s&&!Array.isArray(s)&&n!==i)return{name:n};if(l&&l.type)return{name:i,error:l};o.pop()}return{name:n}}var WY=(e,t,n,r,o)=>o.isOnAll?!1:!n&&o.isOnTouch?!(t||e):(n?r.isOnBlur:o.isOnBlur)?!e:(n?r.isOnChange:o.isOnChange)?e:!0,HY=(e,t)=>!Xd(ve(e,t)).length&&pn(e,t);const KY={mode:mo.onSubmit,reValidateMode:mo.onChange,shouldFocusError:!0};function GY(e={},t){let n={...KY,...e},r={submitCount:0,isDirty:!1,isLoading:ms(n.defaultValues),isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},errors:{},disabled:!1},o={},i=sn(n.defaultValues)||sn(n.values)?so(n.defaultValues||n.values)||{}:{},s=n.shouldUnregister?{}:so(i),l={action:!1,mount:!1,watch:!1},u={mount:new Set,unMount:new Set,array:new Set,watch:new Set},f,m=0;const p={isDirty:!1,dirtyFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1},g={values:O0(),array:O0(),state:O0()},y=e.resetOptions&&e.resetOptions.keepDirtyValues,x=b2(n.mode),S=b2(n.reValidateMode),E=n.criteriaMode===mo.all,_=L=>Z=>{clearTimeout(m),m=setTimeout(L,Z)},b=async L=>{if(p.isValid||L){const Z=n.resolver?Fr((await B()).errors):await J(o,!0);Z!==r.isValid&&g.state.next({isValid:Z})}},C=L=>p.isValidating&&g.state.next({isValidating:L}),R=(L,Z=[],q,we,me=!0,de=!0)=>{if(we&&q){if(l.action=!0,de&&Array.isArray(ve(o,L))){const ke=q(ve(o,L),we.argA,we.argB);me&&wt(o,L,ke)}if(de&&Array.isArray(ve(r.errors,L))){const ke=q(ve(r.errors,L),we.argA,we.argB);me&&wt(r.errors,L,ke),HY(r.errors,L)}if(p.touchedFields&&de&&Array.isArray(ve(r.touchedFields,L))){const ke=q(ve(r.touchedFields,L),we.argA,we.argB);me&&wt(r.touchedFields,L,ke)}p.dirtyFields&&(r.dirtyFields=D0(i,s)),g.state.next({name:L,isDirty:se(L,Z),dirtyFields:r.dirtyFields,errors:r.errors,isValid:r.isValid})}else wt(s,L,Z)},P=(L,Z)=>{wt(r.errors,L,Z),g.state.next({errors:r.errors})},O=(L,Z,q,we)=>{const me=ve(o,L);if(me){const de=ve(s,L,Ht(q)?ve(i,L):q);Ht(de)||we&&we.defaultChecked||Z?wt(s,L,Z?de:I0(me._f)):M(L,de),l.mount&&b()}},A=(L,Z,q,we,me)=>{let de=!1,ke=!1;const ft={name:L};if(!q||we){p.isDirty&&(ke=r.isDirty,r.isDirty=ft.isDirty=se(),de=ke!==ft.isDirty);const ht=ma(ve(i,L),Z);ke=ve(r.dirtyFields,L),ht?pn(r.dirtyFields,L):wt(r.dirtyFields,L,!0),ft.dirtyFields=r.dirtyFields,de=de||p.dirtyFields&&ke!==!ht}if(q){const ht=ve(r.touchedFields,L);ht||(wt(r.touchedFields,L,q),ft.touchedFields=r.touchedFields,de=de||p.touchedFields&&ht!==q)}return de&&me&&g.state.next(ft),de?ft:{}},D=(L,Z,q,we)=>{const me=ve(r.errors,L),de=p.isValid&&Fo(Z)&&r.isValid!==Z;if(e.delayError&&q?(f=_(()=>P(L,q)),f(e.delayError)):(clearTimeout(m),f=null,q?wt(r.errors,L,q):pn(r.errors,L)),(q?!ma(me,q):me)||!Fr(we)||de){const ke={...we,...de&&Fo(Z)?{isValid:Z}:{},errors:r.errors,name:L};r={...r,...ke},g.state.next(ke)}C(!1)},B=async L=>n.resolver(s,n.context,UY(L||u.mount,o,n.criteriaMode,n.shouldUseNativeValidation)),V=async L=>{const{errors:Z}=await B(L);if(L)for(const q of L){const we=ve(Z,q);we?wt(r.errors,q,we):pn(r.errors,q)}else r.errors=Z;return Z},J=async(L,Z,q={valid:!0})=>{for(const we in L){const me=L[we];if(me){const{_f:de,...ke}=me;if(de){const ft=u.array.has(de.name),ht=await R2(me,s,E,n.shouldUseNativeValidation&&!Z,ft);if(ht[de.name]&&(q.valid=!1,Z))break;!Z&&(ve(ht,de.name)?ft?FY(r.errors,ht,de.name):wt(r.errors,de.name,ht[de.name]):pn(r.errors,de.name))}ke&&await J(ke,Z,q)}}return q.valid},G=()=>{for(const L of u.unMount){const Z=ve(o,L);Z&&(Z._f.refs?Z._f.refs.every(q=>!N0(q)):!N0(Z._f.ref))&&fe(L)}u.unMount=new Set},se=(L,Z)=>(L&&Z&&wt(s,L,Z),!ma(pe(),i)),U=(L,Z,q)=>K5(L,u,{...l.mount?s:Ht(Z)?i:Wo(L)?{[L]:Z}:Z},q,Z),ne=L=>Xd(ve(l.mount?s:i,L,e.shouldUnregister?ve(i,L,[]):[])),M=(L,Z,q={})=>{const we=ve(o,L);let me=Z;if(we){const de=we._f;de&&(!de.disabled&&wt(s,L,e3(Z,de)),me=Hp(de.ref)&&Fn(Z)?"":Z,q5(de.ref)?[...de.ref.options].forEach(ke=>ke.selected=me.includes(ke.value)):de.refs?Yd(de.ref)?de.refs.length>1?de.refs.forEach(ke=>(!ke.defaultChecked||!ke.disabled)&&(ke.checked=Array.isArray(me)?!!me.find(ft=>ft===ke.value):me===ke.value)):de.refs[0]&&(de.refs[0].checked=!!me):de.refs.forEach(ke=>ke.checked=ke.value===me):Gx(de.ref)?de.ref.value="":(de.ref.value=me,de.ref.type||g.values.next({name:L,values:{...s}})))}(q.shouldDirty||q.shouldTouch)&&A(L,me,q.shouldTouch,q.shouldDirty,!0),q.shouldValidate&&le(L)},ee=(L,Z,q)=>{for(const we in Z){const me=Z[we],de=`${L}.${we}`,ke=ve(o,de);(u.array.has(L)||!Gp(me)||ke&&!ke._f)&&!$l(me)?ee(de,me,q):M(de,me,q)}},H=(L,Z,q={})=>{const we=ve(o,L),me=u.array.has(L),de=so(Z);wt(s,L,de),me?(g.array.next({name:L,values:{...s}}),(p.isDirty||p.dirtyFields)&&q.shouldDirty&&g.state.next({name:L,dirtyFields:D0(i,s),isDirty:se(L,de)})):we&&!we._f&&!Fn(de)?ee(L,de,q):M(L,de,q),S2(L,u)&&g.state.next({...r}),g.values.next({name:L,values:{...s}}),!l.mount&&t()},X=async L=>{const Z=L.target;let q=Z.name,we=!0;const me=ve(o,q),de=()=>Z.type?I0(me._f):z5(L),ke=ft=>{we=Number.isNaN(ft)||ft===ve(s,q,ft)};if(me){let ft,ht;const _n=de(),Cr=L.type===Wp.BLUR||L.type===Wp.FOCUS_OUT,Ni=!VY(me._f)&&!n.resolver&&!ve(r.errors,q)&&!me._f.deps||WY(Cr,ve(r.touchedFields,q),r.isSubmitted,S,x),Co=S2(q,u,Cr);wt(s,q,_n),Cr?(me._f.onBlur&&me._f.onBlur(L),f&&f(0)):me._f.onChange&&me._f.onChange(L);const Vn=A(q,_n,Cr,!1),Ba=!Fr(Vn)||Co;if(!Cr&&g.values.next({name:q,type:L.type,values:{...s}}),Ni)return p.isValid&&b(),Ba&&g.state.next({name:q,...Co?{}:Vn});if(!Cr&&Co&&g.state.next({...r}),C(!0),n.resolver){const{errors:Di}=await B([q]);if(ke(_n),we){const Ws=k2(r.errors,o,q),Ii=k2(Di,o,Ws.name||q);ft=Ii.error,q=Ii.name,ht=Fr(Di)}}else ft=(await R2(me,s,E,n.shouldUseNativeValidation))[q],ke(_n),we&&(ft?ht=!1:p.isValid&&(ht=await J(o,!0)));we&&(me._f.deps&&le(me._f.deps),D(q,ht,ft,Vn))}},W=(L,Z)=>{if(ve(r.errors,Z)&&L.focus)return L.focus(),1},le=async(L,Z={})=>{let q,we;const me=ep(L);if(C(!0),n.resolver){const de=await V(Ht(L)?L:me);q=Fr(de),we=L?!me.some(ke=>ve(de,ke)):q}else L?(we=(await Promise.all(me.map(async de=>{const ke=ve(o,de);return await J(ke&&ke._f?{[de]:ke}:ke)}))).every(Boolean),!(!we&&!r.isValid)&&b()):we=q=await J(o);return g.state.next({...!Wo(L)||p.isValid&&q!==r.isValid?{}:{name:L},...n.resolver||!L?{isValid:q}:{},errors:r.errors,isValidating:!1}),Z.shouldFocus&&!we&&tp(o,W,L?me:u.mount),we},pe=L=>{const Z={...i,...l.mount?s:{}};return Ht(L)?Z:Wo(L)?ve(Z,L):L.map(q=>ve(Z,q))},$e=(L,Z)=>({invalid:!!ve((Z||r).errors,L),isDirty:!!ve((Z||r).dirtyFields,L),isTouched:!!ve((Z||r).touchedFields,L),error:ve((Z||r).errors,L)}),Ve=L=>{L&&ep(L).forEach(Z=>pn(r.errors,Z)),g.state.next({errors:L?r.errors:{}})},We=(L,Z,q)=>{const we=(ve(o,L,{_f:{}})._f||{}).ref;wt(r.errors,L,{...Z,ref:we}),g.state.next({name:L,errors:r.errors,isValid:!1}),q&&q.shouldFocus&&we&&we.focus&&we.focus()},Ne=(L,Z)=>ms(L)?g.values.subscribe({next:q=>L(U(void 0,Z),q)}):U(L,Z,!0),fe=(L,Z={})=>{for(const q of L?ep(L):u.mount)u.mount.delete(q),u.array.delete(q),Z.keepValue||(pn(o,q),pn(s,q)),!Z.keepError&&pn(r.errors,q),!Z.keepDirty&&pn(r.dirtyFields,q),!Z.keepTouched&&pn(r.touchedFields,q),!n.shouldUnregister&&!Z.keepDefaultValue&&pn(i,q);g.values.next({values:{...s}}),g.state.next({...r,...Z.keepDirty?{isDirty:se()}:{}}),!Z.keepIsValid&&b()},xe=({disabled:L,name:Z,field:q,fields:we,value:me})=>{if(Fo(L)){const de=L?void 0:Ht(me)?I0(q?q._f:ve(we,Z)._f):me;wt(s,Z,de),A(Z,de,!1,!1,!0)}},Re=(L,Z={})=>{let q=ve(o,L);const we=Fo(Z.disabled);return wt(o,L,{...q||{},_f:{...q&&q._f?q._f:{ref:{name:L}},name:L,mount:!0,...Z}}),u.mount.add(L),q?xe({field:q,disabled:Z.disabled,name:L}):O(L,!0,Z.value),{...we?{disabled:Z.disabled}:{},...n.progressive?{required:!!Z.required,min:du(Z.min),max:du(Z.max),minLength:du(Z.minLength),maxLength:du(Z.maxLength),pattern:du(Z.pattern)}:{},name:L,onChange:X,onBlur:X,ref:me=>{if(me){Re(L,Z),q=ve(o,L);const de=Ht(me.value)&&me.querySelectorAll&&me.querySelectorAll("input,select,textarea")[0]||me,ke=BY(de),ft=q._f.refs||[];if(ke?ft.find(ht=>ht===de):de===q._f.ref)return;wt(o,L,{_f:{...q._f,...ke?{refs:[...ft.filter(N0),de,...Array.isArray(ve(i,L))?[{}]:[]],ref:{type:de.type,name:L}}:{ref:de}}}),O(L,!1,void 0,de)}else q=ve(o,L,{}),q._f&&(q._f.mount=!1),(n.shouldUnregister||Z.shouldUnregister)&&!(B5(u.array,L)&&l.action)&&u.unMount.add(L)}}},Me=()=>n.shouldFocusError&&tp(o,W,u.mount),Oe=L=>{Fo(L)&&(g.state.next({disabled:L}),tp(o,Z=>{Z.disabled=L},0,!1))},ze=(L,Z)=>async q=>{q&&(q.preventDefault&&q.preventDefault(),q.persist&&q.persist());let we=so(s);if(g.state.next({isSubmitting:!0}),n.resolver){const{errors:me,values:de}=await B();r.errors=me,we=de}else await J(o);pn(r.errors,"root"),Fr(r.errors)?(g.state.next({errors:{}}),await L(we,q)):(Z&&await Z({...r.errors},q),Me(),setTimeout(Me)),g.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:Fr(r.errors),submitCount:r.submitCount+1,errors:r.errors})},Mt=(L,Z={})=>{ve(o,L)&&(Ht(Z.defaultValue)?H(L,ve(i,L)):(H(L,Z.defaultValue),wt(i,L,Z.defaultValue)),Z.keepTouched||pn(r.touchedFields,L),Z.keepDirty||(pn(r.dirtyFields,L),r.isDirty=Z.defaultValue?se(L,ve(i,L)):se()),Z.keepError||(pn(r.errors,L),p.isValid&&b()),g.state.next({...r}))},ct=(L,Z={})=>{const q=L?so(L):i,we=so(q),me=L&&!Fr(L)?we:i;if(Z.keepDefaultValues||(i=q),!Z.keepValues){if(Z.keepDirtyValues||y)for(const de of u.mount)ve(r.dirtyFields,de)?wt(me,de,ve(s,de)):H(de,ve(me,de));else{if(Wx&&Ht(L))for(const de of u.mount){const ke=ve(o,de);if(ke&&ke._f){const ft=Array.isArray(ke._f.refs)?ke._f.refs[0]:ke._f.ref;if(Hp(ft)){const ht=ft.closest("form");if(ht){ht.reset();break}}}}o={}}s=e.shouldUnregister?Z.keepDefaultValues?so(i):{}:so(me),g.array.next({values:{...me}}),g.values.next({values:{...me}})}u={mount:new Set,unMount:new Set,array:new Set,watch:new Set,watchAll:!1,focus:""},!l.mount&&t(),l.mount=!p.isValid||!!Z.keepIsValid,l.watch=!!e.shouldUnregister,g.state.next({submitCount:Z.keepSubmitCount?r.submitCount:0,isDirty:Z.keepDirty?r.isDirty:!!(Z.keepDefaultValues&&!ma(L,i)),isSubmitted:Z.keepIsSubmitted?r.isSubmitted:!1,dirtyFields:Z.keepDirtyValues?r.dirtyFields:Z.keepDefaultValues&&L?D0(i,L):{},touchedFields:Z.keepTouched?r.touchedFields:{},errors:Z.keepErrors?r.errors:{},isSubmitSuccessful:Z.keepIsSubmitSuccessful?r.isSubmitSuccessful:!1,isSubmitting:!1})},Kt=(L,Z)=>ct(ms(L)?L(s):L,Z);return{control:{register:Re,unregister:fe,getFieldState:$e,handleSubmit:ze,setError:We,_executeSchema:B,_getWatch:U,_getDirty:se,_updateValid:b,_removeUnmounted:G,_updateFieldArray:R,_updateDisabledField:xe,_getFieldArray:ne,_reset:ct,_resetDefaultValues:()=>ms(n.defaultValues)&&n.defaultValues().then(L=>{Kt(L,n.resetOptions),g.state.next({isLoading:!1})}),_updateFormState:L=>{r={...r,...L}},_disableForm:Oe,_subjects:g,_proxyFormState:p,get _fields(){return o},get _formValues(){return s},get _state(){return l},set _state(L){l=L},get _defaultValues(){return i},get _names(){return u},set _names(L){u=L},get _formState(){return r},set _formState(L){r=L},get _options(){return n},set _options(L){n={...n,...L}}},trigger:le,register:Re,handleSubmit:ze,watch:Ne,setValue:H,getValues:pe,reset:Kt,resetField:Mt,clearErrors:Ve,unregister:fe,setError:We,setFocus:(L,Z={})=>{const q=ve(o,L),we=q&&q._f;if(we){const me=we.refs?we.refs[0]:we.ref;me.focus&&(me.focus(),Z.shouldSelect&&me.select())}},getFieldState:$e}}function YY(e={}){const t=je.useRef(),n=je.useRef(),[r,o]=je.useState({isDirty:!1,isValidating:!1,isLoading:ms(e.defaultValues),isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,submitCount:0,dirtyFields:{},touchedFields:{},errors:{},disabled:!1,defaultValues:ms(e.defaultValues)?void 0:e.defaultValues});t.current||(t.current={...GY(e,()=>o(s=>({...s}))),formState:r});const i=t.current.control;return i._options=e,Hx({subject:i._subjects.state,next:s=>{W5(s,i._proxyFormState,i._updateFormState,!0)&&o({...i._formState})}}),je.useEffect(()=>i._disableForm(e.disabled),[i,e.disabled]),je.useEffect(()=>{if(i._proxyFormState.isDirty){const s=i._getDirty();s!==r.isDirty&&i._subjects.state.next({isDirty:s})}},[i,r.isDirty]),je.useEffect(()=>{e.values&&!ma(e.values,n.current)?(i._reset(e.values,i._options.resetOptions),n.current=e.values):i._resetDefaultValues()},[e.values,i]),je.useEffect(()=>{i._state.mount||(i._updateValid(),i._state.mount=!0),i._state.watch&&(i._state.watch=!1,i._subjects.state.next({...i._formState})),i._removeUnmounted()}),t.current.formState=V5(r,i),t.current}var T2=function(e,t,n){if(e&&"reportValidity"in e){var r=ve(n,t);e.setCustomValidity(r&&r.message||""),e.reportValidity()}},t3=function(e,t){var n=function(o){var i=t.fields[o];i&&i.ref&&"reportValidity"in i.ref?T2(i.ref,o,e):i.refs&&i.refs.forEach(function(s){return T2(s,o,e)})};for(var r in t.fields)n(r)},XY=function(e,t){t.shouldUseNativeValidation&&t3(e,t);var n={};for(var r in e){var o=ve(t.fields,r),i=Object.assign(e[r]||{},{ref:o&&o.ref});if(qY(t.names||Object.keys(e),r)){var s=Object.assign({},ZY(ve(n,r)));wt(s,"root",i),wt(n,r,s)}else wt(n,r,i)}return n},ZY=function(e){return Array.isArray(e)?e.filter(Boolean):[]},qY=function(e,t){return e.some(function(n){return n.startsWith(t+".")})},QY=function(e,t){for(var n={};e.length;){var r=e[0],o=r.code,i=r.message,s=r.path.join(".");if(!n[s])if("unionErrors"in r){var l=r.unionErrors[0].errors[0];n[s]={message:l.message,type:l.code}}else n[s]={message:i,type:o};if("unionErrors"in r&&r.unionErrors.forEach(function(m){return m.errors.forEach(function(p){return e.push(p)})}),t){var u=n[s].types,f=u&&u[r.code];n[s]=Y5(s,t,n,o,f?[].concat(f,r.message):r.message)}e.shift()}return n},JY=function(e,t,n){return n===void 0&&(n={}),function(r,o,i){try{return Promise.resolve(function(s,l){try{var u=Promise.resolve(e[n.mode==="sync"?"parse":"parseAsync"](r,t)).then(function(f){return i.shouldUseNativeValidation&&t3({},i),{errors:{},values:n.raw?r:f}})}catch(f){return l(f)}return u&&u.then?u.then(void 0,l):u}(0,function(s){if(function(l){return l.errors!=null}(s))return{values:{},errors:XY(QY(s.errors,!i.shouldUseNativeValidation&&i.criteriaMode==="all"),i)};throw s}))}catch(s){return Promise.reject(s)}}},mt;(function(e){e.assertEqual=o=>o;function t(o){}e.assertIs=t;function n(o){throw new Error}e.assertNever=n,e.arrayToEnum=o=>{const i={};for(const s of o)i[s]=s;return i},e.getValidEnumValues=o=>{const i=e.objectKeys(o).filter(l=>typeof o[o[l]]!="number"),s={};for(const l of i)s[l]=o[l];return e.objectValues(s)},e.objectValues=o=>e.objectKeys(o).map(function(i){return o[i]}),e.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{const i=[];for(const s in o)Object.prototype.hasOwnProperty.call(o,s)&&i.push(s);return i},e.find=(o,i)=>{for(const s of o)if(i(s))return s},e.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&isFinite(o)&&Math.floor(o)===o;function r(o,i=" | "){return o.map(s=>typeof s=="string"?`'${s}'`:s).join(i)}e.joinValues=r,e.jsonStringifyReplacer=(o,i)=>typeof i=="bigint"?i.toString():i})(mt||(mt={}));var P2;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(P2||(P2={}));const be=mt.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ca=e=>{switch(typeof e){case"undefined":return be.undefined;case"string":return be.string;case"number":return isNaN(e)?be.nan:be.number;case"boolean":return be.boolean;case"function":return be.function;case"bigint":return be.bigint;case"symbol":return be.symbol;case"object":return Array.isArray(e)?be.array:e===null?be.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?be.promise:typeof Map<"u"&&e instanceof Map?be.map:typeof Set<"u"&&e instanceof Set?be.set:typeof Date<"u"&&e instanceof Date?be.date:be.object;default:return be.unknown}},he=mt.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"]);class Go 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(i){return i.message},r={_errors:[]},o=i=>{for(const s of i.issues)if(s.code==="invalid_union")s.unionErrors.map(o);else if(s.code==="invalid_return_type")o(s.returnTypeError);else if(s.code==="invalid_arguments")o(s.argumentsError);else if(s.path.length===0)r._errors.push(n(s));else{let l=r,u=0;for(;un.message){const n={},r=[];for(const o of this.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(t(o))):r.push(t(o));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}}Go.create=e=>new Go(e);const Xp=(e,t)=>{let n;switch(e.code){case he.invalid_type:e.received===be.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case he.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,mt.jsonStringifyReplacer)}`;break;case he.unrecognized_keys:n=`Unrecognized key(s) in object: ${mt.joinValues(e.keys,", ")}`;break;case he.invalid_union:n="Invalid input";break;case he.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${mt.joinValues(e.options)}`;break;case he.invalid_enum_value:n=`Invalid enum value. Expected ${mt.joinValues(e.options)}, received '${e.received}'`;break;case he.invalid_arguments:n="Invalid function arguments";break;case he.invalid_return_type:n="Invalid function return type";break;case he.invalid_date:n="Invalid date";break;case he.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}"`:mt.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case he.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 he.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 he.custom:n="Invalid input";break;case he.invalid_intersection_types:n="Intersection results could not be merged";break;case he.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case he.not_finite:n="Number must be finite";break;default:n=t.defaultError,mt.assertNever(e)}return{message:n}};let eX=Xp;function C1(){return eX}const $1=e=>{const{data:t,path:n,errorMaps:r,issueData:o}=e,i=[...n,...o.path||[]],s={...o,path:i};let l="";const u=r.filter(f=>!!f).slice().reverse();for(const f of u)l=f(s,{data:t,defaultError:l}).message;return{...o,path:i,message:o.message||l}};function Ee(e,t){const n=$1({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,C1(),Xp].filter(r=>!!r)});e.common.issues.push(n)}class zn{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 o of n){if(o.status==="aborted")return Ze;o.status==="dirty"&&t.dirty(),r.push(o.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){const r=[];for(const o of n)r.push({key:await o.key,value:await o.value});return zn.mergeObjectSync(t,r)}static mergeObjectSync(t,n){const r={};for(const o of n){const{key:i,value:s}=o;if(i.status==="aborted"||s.status==="aborted")return Ze;i.status==="dirty"&&t.dirty(),s.status==="dirty"&&t.dirty(),i.value!=="__proto__"&&(typeof s.value<"u"||o.alwaysSet)&&(r[i.value]=s.value)}return{status:t.value,value:r}}}const Ze=Object.freeze({status:"aborted"}),tX=e=>({status:"dirty",value:e}),rr=e=>({status:"valid",value:e}),A2=e=>e.status==="aborted",M2=e=>e.status==="dirty",Zp=e=>e.status==="valid",R1=e=>typeof Promise<"u"&&e instanceof Promise;var De;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t==null?void 0:t.message})(De||(De={}));class Qo{constructor(t,n,r,o){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=o}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 O2=(e,t)=>{if(Zp(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 Go(e.common.issues);return this._error=n,this._error}}};function Xe(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:r,description:o}=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:o}:{errorMap:(s,l)=>s.code!=="invalid_type"?{message:l.defaultError}:typeof l.data>"u"?{message:r??l.defaultError}:{message:n??l.defaultError},description:o}}class rt{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.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this)}get description(){return this._def.description}_getType(t){return ca(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:ca(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new zn,ctx:{common:t.parent.common,data:t.data,parsedType:ca(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const n=this._parse(t);if(R1(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 o={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:ca(t)},i=this._parseSync({data:t,path:o.path,parent:o});return O2(o,i)}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:ca(t)},o=this._parse({data:t,path:r.path,parent:r}),i=await(R1(o)?o:Promise.resolve(o));return O2(r,i)}refine(t,n){const r=o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n;return this._refinement((o,i)=>{const s=t(o),l=()=>i.addIssue({code:he.custom,...r(o)});return typeof Promise<"u"&&s instanceof Promise?s.then(u=>u?!0:(l(),!1)):s?!0:(l(),!1)})}refinement(t,n){return this._refinement((r,o)=>t(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(t){return new Pi({schema:this,typeName:Be.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}optional(){return Cs.create(this,this._def)}nullable(){return gc.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Yo.create(this,this._def)}promise(){return pd.create(this,this._def)}or(t){return Jp.create([this,t],this._def)}and(t){return em.create(this,t,this._def)}transform(t){return new Pi({...Xe(this._def),schema:this,typeName:Be.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const n=typeof t=="function"?t:()=>t;return new im({...Xe(this._def),innerType:this,defaultValue:n,typeName:Be.ZodDefault})}brand(){return new hX({typeName:Be.ZodBranded,type:this,...Xe(this._def)})}catch(t){const n=typeof t=="function"?t:()=>t;return new N1({...Xe(this._def),innerType:this,catchValue:n,typeName:Be.ZodCatch})}describe(t){const n=this.constructor;return new n({...this._def,description:t})}pipe(t){return cg.create(this,t)}readonly(){return I1.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const nX=/^c[^\s-]{8,}$/i,rX=/^[a-z][a-z0-9]*$/,oX=/^[0-9A-HJKMNP-TV-Z]{26}$/,iX=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,sX=/^(?!\.)(?!.*\.\.)([A-Z0-9_+-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,aX="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let L0;const lX=/^(((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}))$/,cX=/^(([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})))$/,uX=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 dX(e,t){return!!((t==="v4"||!t)&&lX.test(e)||(t==="v6"||!t)&&cX.test(e))}class yi extends rt{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==be.string){const i=this._getOrReturnCtx(t);return Ee(i,{code:he.invalid_type,expected:be.string,received:i.parsedType}),Ze}const r=new zn;let o;for(const i of this._def.checks)if(i.kind==="min")t.data.lengthi.value&&(o=this._getOrReturnCtx(t,o),Ee(o,{code:he.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){const s=t.data.length>i.value,l=t.data.lengtht.test(o),{validation:n,code:he.invalid_string,...De.errToObj(r)})}_addCheck(t){return new yi({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...De.errToObj(t)})}url(t){return this._addCheck({kind:"url",...De.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...De.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...De.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...De.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...De.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...De.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...De.errToObj(t)})}datetime(t){var n;return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof(t==null?void 0:t.precision)>"u"?null:t==null?void 0:t.precision,offset:(n=t==null?void 0:t.offset)!==null&&n!==void 0?n:!1,...De.errToObj(t==null?void 0:t.message)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...De.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n==null?void 0:n.position,...De.errToObj(n==null?void 0:n.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...De.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...De.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...De.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...De.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...De.errToObj(n)})}nonempty(t){return this.min(1,De.errToObj(t))}trim(){return new yi({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new yi({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new yi({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}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 yi({checks:[],typeName:Be.ZodString,coerce:(t=e==null?void 0:e.coerce)!==null&&t!==void 0?t:!1,...Xe(e)})};function fX(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,o=n>r?n:r,i=parseInt(e.toFixed(o).replace(".","")),s=parseInt(t.toFixed(o).replace(".",""));return i%s/Math.pow(10,o)}class hc extends rt{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)!==be.number){const i=this._getOrReturnCtx(t);return Ee(i,{code:he.invalid_type,expected:be.number,received:i.parsedType}),Ze}let r;const o=new zn;for(const i of this._def.checks)i.kind==="int"?mt.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),Ee(r,{code:he.invalid_type,expected:"integer",received:"float",message:i.message}),o.dirty()):i.kind==="min"?(i.inclusive?t.datai.value:t.data>=i.value)&&(r=this._getOrReturnCtx(t,r),Ee(r,{code:he.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),o.dirty()):i.kind==="multipleOf"?fX(t.data,i.value)!==0&&(r=this._getOrReturnCtx(t,r),Ee(r,{code:he.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):i.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),Ee(r,{code:he.not_finite,message:i.message}),o.dirty()):mt.assertNever(i);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,De.toString(n))}gt(t,n){return this.setLimit("min",t,!1,De.toString(n))}lte(t,n){return this.setLimit("max",t,!0,De.toString(n))}lt(t,n){return this.setLimit("max",t,!1,De.toString(n))}setLimit(t,n,r,o){return new hc({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:De.toString(o)}]})}_addCheck(t){return new hc({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:De.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:De.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:De.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:De.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:De.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:De.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:De.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:De.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:De.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"&&mt.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 hc({checks:[],typeName:Be.ZodNumber,coerce:(e==null?void 0:e.coerce)||!1,...Xe(e)});class pc extends rt{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)!==be.bigint){const i=this._getOrReturnCtx(t);return Ee(i,{code:he.invalid_type,expected:be.bigint,received:i.parsedType}),Ze}let r;const o=new zn;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?t.datai.value:t.data>=i.value)&&(r=this._getOrReturnCtx(t,r),Ee(r,{code:he.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),o.dirty()):i.kind==="multipleOf"?t.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),Ee(r,{code:he.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):mt.assertNever(i);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,De.toString(n))}gt(t,n){return this.setLimit("min",t,!1,De.toString(n))}lte(t,n){return this.setLimit("max",t,!0,De.toString(n))}lt(t,n){return this.setLimit("max",t,!1,De.toString(n))}setLimit(t,n,r,o){return new pc({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:De.toString(o)}]})}_addCheck(t){return new pc({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:De.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:De.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:De.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:De.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:De.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 pc({checks:[],typeName:Be.ZodBigInt,coerce:(t=e==null?void 0:e.coerce)!==null&&t!==void 0?t:!1,...Xe(e)})};class k1 extends rt{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==be.boolean){const r=this._getOrReturnCtx(t);return Ee(r,{code:he.invalid_type,expected:be.boolean,received:r.parsedType}),Ze}return rr(t.data)}}k1.create=e=>new k1({typeName:Be.ZodBoolean,coerce:(e==null?void 0:e.coerce)||!1,...Xe(e)});class hd extends rt{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==be.date){const i=this._getOrReturnCtx(t);return Ee(i,{code:he.invalid_type,expected:be.date,received:i.parsedType}),Ze}if(isNaN(t.data.getTime())){const i=this._getOrReturnCtx(t);return Ee(i,{code:he.invalid_date}),Ze}const r=new zn;let o;for(const i of this._def.checks)i.kind==="min"?t.data.getTime()i.value&&(o=this._getOrReturnCtx(t,o),Ee(o,{code:he.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):mt.assertNever(i);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new hd({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:De.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:De.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 hd({checks:[],coerce:(e==null?void 0:e.coerce)||!1,typeName:Be.ZodDate,...Xe(e)});class T1 extends rt{_parse(t){if(this._getType(t)!==be.symbol){const r=this._getOrReturnCtx(t);return Ee(r,{code:he.invalid_type,expected:be.symbol,received:r.parsedType}),Ze}return rr(t.data)}}T1.create=e=>new T1({typeName:Be.ZodSymbol,...Xe(e)});class qp extends rt{_parse(t){if(this._getType(t)!==be.undefined){const r=this._getOrReturnCtx(t);return Ee(r,{code:he.invalid_type,expected:be.undefined,received:r.parsedType}),Ze}return rr(t.data)}}qp.create=e=>new qp({typeName:Be.ZodUndefined,...Xe(e)});class Qp extends rt{_parse(t){if(this._getType(t)!==be.null){const r=this._getOrReturnCtx(t);return Ee(r,{code:he.invalid_type,expected:be.null,received:r.parsedType}),Ze}return rr(t.data)}}Qp.create=e=>new Qp({typeName:Be.ZodNull,...Xe(e)});class P1 extends rt{constructor(){super(...arguments),this._any=!0}_parse(t){return rr(t.data)}}P1.create=e=>new P1({typeName:Be.ZodAny,...Xe(e)});class Dl extends rt{constructor(){super(...arguments),this._unknown=!0}_parse(t){return rr(t.data)}}Dl.create=e=>new Dl({typeName:Be.ZodUnknown,...Xe(e)});class Ms extends rt{_parse(t){const n=this._getOrReturnCtx(t);return Ee(n,{code:he.invalid_type,expected:be.never,received:n.parsedType}),Ze}}Ms.create=e=>new Ms({typeName:Be.ZodNever,...Xe(e)});class A1 extends rt{_parse(t){if(this._getType(t)!==be.undefined){const r=this._getOrReturnCtx(t);return Ee(r,{code:he.invalid_type,expected:be.void,received:r.parsedType}),Ze}return rr(t.data)}}A1.create=e=>new A1({typeName:Be.ZodVoid,...Xe(e)});class Yo extends rt{_parse(t){const{ctx:n,status:r}=this._processInputParams(t),o=this._def;if(n.parsedType!==be.array)return Ee(n,{code:he.invalid_type,expected:be.array,received:n.parsedType}),Ze;if(o.exactLength!==null){const s=n.data.length>o.exactLength.value,l=n.data.lengtho.maxLength.value&&(Ee(n,{code:he.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((s,l)=>o.type._parseAsync(new Qo(n,s,n.path,l)))).then(s=>zn.mergeArray(r,s));const i=[...n.data].map((s,l)=>o.type._parseSync(new Qo(n,s,n.path,l)));return zn.mergeArray(r,i)}get element(){return this._def.type}min(t,n){return new Yo({...this._def,minLength:{value:t,message:De.toString(n)}})}max(t,n){return new Yo({...this._def,maxLength:{value:t,message:De.toString(n)}})}length(t,n){return new Yo({...this._def,exactLength:{value:t,message:De.toString(n)}})}nonempty(t){return this.min(1,t)}}Yo.create=(e,t)=>new Yo({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Be.ZodArray,...Xe(t)});function dl(e){if(e instanceof Vt){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=Cs.create(dl(r))}return new Vt({...e._def,shape:()=>t})}else return e instanceof Yo?new Yo({...e._def,type:dl(e.element)}):e instanceof Cs?Cs.create(dl(e.unwrap())):e instanceof gc?gc.create(dl(e.unwrap())):e instanceof Ti?Ti.create(e.items.map(t=>dl(t))):e}class Vt extends rt{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=mt.objectKeys(t);return this._cached={shape:t,keys:n}}_parse(t){if(this._getType(t)!==be.object){const f=this._getOrReturnCtx(t);return Ee(f,{code:he.invalid_type,expected:be.object,received:f.parsedType}),Ze}const{status:r,ctx:o}=this._processInputParams(t),{shape:i,keys:s}=this._getCached(),l=[];if(!(this._def.catchall instanceof Ms&&this._def.unknownKeys==="strip"))for(const f in o.data)s.includes(f)||l.push(f);const u=[];for(const f of s){const m=i[f],p=o.data[f];u.push({key:{status:"valid",value:f},value:m._parse(new Qo(o,p,o.path,f)),alwaysSet:f in o.data})}if(this._def.catchall instanceof Ms){const f=this._def.unknownKeys;if(f==="passthrough")for(const m of l)u.push({key:{status:"valid",value:m},value:{status:"valid",value:o.data[m]}});else if(f==="strict")l.length>0&&(Ee(o,{code:he.unrecognized_keys,keys:l}),r.dirty());else if(f!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const f=this._def.catchall;for(const m of l){const p=o.data[m];u.push({key:{status:"valid",value:m},value:f._parse(new Qo(o,p,o.path,m)),alwaysSet:m in o.data})}}return o.common.async?Promise.resolve().then(async()=>{const f=[];for(const m of u){const p=await m.key;f.push({key:p,value:await m.value,alwaysSet:m.alwaysSet})}return f}).then(f=>zn.mergeObjectSync(r,f)):zn.mergeObjectSync(r,u)}get shape(){return this._def.shape()}strict(t){return De.errToObj,new Vt({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{var o,i,s,l;const u=(s=(i=(o=this._def).errorMap)===null||i===void 0?void 0:i.call(o,n,r).message)!==null&&s!==void 0?s:r.defaultError;return n.code==="unrecognized_keys"?{message:(l=De.errToObj(t).message)!==null&&l!==void 0?l:u}:{message:u}}}:{}})}strip(){return new Vt({...this._def,unknownKeys:"strip"})}passthrough(){return new Vt({...this._def,unknownKeys:"passthrough"})}extend(t){return new Vt({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new Vt({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:Be.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new Vt({...this._def,catchall:t})}pick(t){const n={};return mt.objectKeys(t).forEach(r=>{t[r]&&this.shape[r]&&(n[r]=this.shape[r])}),new Vt({...this._def,shape:()=>n})}omit(t){const n={};return mt.objectKeys(this.shape).forEach(r=>{t[r]||(n[r]=this.shape[r])}),new Vt({...this._def,shape:()=>n})}deepPartial(){return dl(this)}partial(t){const n={};return mt.objectKeys(this.shape).forEach(r=>{const o=this.shape[r];t&&!t[r]?n[r]=o:n[r]=o.optional()}),new Vt({...this._def,shape:()=>n})}required(t){const n={};return mt.objectKeys(this.shape).forEach(r=>{if(t&&!t[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof Cs;)i=i._def.innerType;n[r]=i}}),new Vt({...this._def,shape:()=>n})}keyof(){return n3(mt.objectKeys(this.shape))}}Vt.create=(e,t)=>new Vt({shape:()=>e,unknownKeys:"strip",catchall:Ms.create(),typeName:Be.ZodObject,...Xe(t)});Vt.strictCreate=(e,t)=>new Vt({shape:()=>e,unknownKeys:"strict",catchall:Ms.create(),typeName:Be.ZodObject,...Xe(t)});Vt.lazycreate=(e,t)=>new Vt({shape:e,unknownKeys:"strip",catchall:Ms.create(),typeName:Be.ZodObject,...Xe(t)});class Jp extends rt{_parse(t){const{ctx:n}=this._processInputParams(t),r=this._def.options;function o(i){for(const l of i)if(l.result.status==="valid")return l.result;for(const l of i)if(l.result.status==="dirty")return n.common.issues.push(...l.ctx.common.issues),l.result;const s=i.map(l=>new Go(l.ctx.common.issues));return Ee(n,{code:he.invalid_union,unionErrors:s}),Ze}if(n.common.async)return Promise.all(r.map(async i=>{const s={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:s}),ctx:s}})).then(o);{let i;const s=[];for(const u of r){const f={...n,common:{...n.common,issues:[]},parent:null},m=u._parseSync({data:n.data,path:n.path,parent:f});if(m.status==="valid")return m;m.status==="dirty"&&!i&&(i={result:m,ctx:f}),f.common.issues.length&&s.push(f.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;const l=s.map(u=>new Go(u));return Ee(n,{code:he.invalid_union,unionErrors:l}),Ze}}get options(){return this._def.options}}Jp.create=(e,t)=>new Jp({options:e,typeName:Be.ZodUnion,...Xe(t)});const rp=e=>e instanceof nm?rp(e.schema):e instanceof Pi?rp(e.innerType()):e instanceof rm?[e.value]:e instanceof Da?e.options:e instanceof om?Object.keys(e.enum):e instanceof im?rp(e._def.innerType):e instanceof qp?[void 0]:e instanceof Qp?[null]:null;class Xx extends rt{_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.object)return Ee(n,{code:he.invalid_type,expected:be.object,received:n.parsedType}),Ze;const r=this.discriminator,o=n.data[r],i=this.optionsMap.get(o);return i?n.common.async?i._parseAsync({data:n.data,path:n.path,parent:n}):i._parseSync({data:n.data,path:n.path,parent:n}):(Ee(n,{code:he.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),Ze)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){const o=new Map;for(const i of n){const s=rp(i.shape[t]);if(!s)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const l of s){if(o.has(l))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(l)}`);o.set(l,i)}}return new Xx({typeName:Be.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:o,...Xe(r)})}}function M1(e,t){const n=ca(e),r=ca(t);if(e===t)return{valid:!0,data:e};if(n===be.object&&r===be.object){const o=mt.objectKeys(t),i=mt.objectKeys(e).filter(l=>o.indexOf(l)!==-1),s={...e,...t};for(const l of i){const u=M1(e[l],t[l]);if(!u.valid)return{valid:!1};s[l]=u.data}return{valid:!0,data:s}}else if(n===be.array&&r===be.array){if(e.length!==t.length)return{valid:!1};const o=[];for(let i=0;i{if(A2(i)||A2(s))return Ze;const l=M1(i.value,s.value);return l.valid?((M2(i)||M2(s))&&n.dirty(),{status:n.value,value:l.data}):(Ee(r,{code:he.invalid_intersection_types}),Ze)};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(([i,s])=>o(i,s)):o(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}em.create=(e,t,n)=>new em({left:e,right:t,typeName:Be.ZodIntersection,...Xe(n)});class Ti extends rt{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.array)return Ee(r,{code:he.invalid_type,expected:be.array,received:r.parsedType}),Ze;if(r.data.lengththis._def.items.length&&(Ee(r,{code:he.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const i=[...r.data].map((s,l)=>{const u=this._def.items[l]||this._def.rest;return u?u._parse(new Qo(r,s,r.path,l)):null}).filter(s=>!!s);return r.common.async?Promise.all(i).then(s=>zn.mergeArray(n,s)):zn.mergeArray(n,i)}get items(){return this._def.items}rest(t){return new Ti({...this._def,rest:t})}}Ti.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ti({items:e,typeName:Be.ZodTuple,rest:null,...Xe(t)})};class tm extends rt{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!==be.object)return Ee(r,{code:he.invalid_type,expected:be.object,received:r.parsedType}),Ze;const o=[],i=this._def.keyType,s=this._def.valueType;for(const l in r.data)o.push({key:i._parse(new Qo(r,l,r.path,l)),value:s._parse(new Qo(r,r.data[l],r.path,l))});return r.common.async?zn.mergeObjectAsync(n,o):zn.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof rt?new tm({keyType:t,valueType:n,typeName:Be.ZodRecord,...Xe(r)}):new tm({keyType:yi.create(),valueType:t,typeName:Be.ZodRecord,...Xe(n)})}}class O1 extends rt{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!==be.map)return Ee(r,{code:he.invalid_type,expected:be.map,received:r.parsedType}),Ze;const o=this._def.keyType,i=this._def.valueType,s=[...r.data.entries()].map(([l,u],f)=>({key:o._parse(new Qo(r,l,r.path,[f,"key"])),value:i._parse(new Qo(r,u,r.path,[f,"value"]))}));if(r.common.async){const l=new Map;return Promise.resolve().then(async()=>{for(const u of s){const f=await u.key,m=await u.value;if(f.status==="aborted"||m.status==="aborted")return Ze;(f.status==="dirty"||m.status==="dirty")&&n.dirty(),l.set(f.value,m.value)}return{status:n.value,value:l}})}else{const l=new Map;for(const u of s){const f=u.key,m=u.value;if(f.status==="aborted"||m.status==="aborted")return Ze;(f.status==="dirty"||m.status==="dirty")&&n.dirty(),l.set(f.value,m.value)}return{status:n.value,value:l}}}}O1.create=(e,t,n)=>new O1({valueType:t,keyType:e,typeName:Be.ZodMap,...Xe(n)});class mc extends rt{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.set)return Ee(r,{code:he.invalid_type,expected:be.set,received:r.parsedType}),Ze;const o=this._def;o.minSize!==null&&r.data.sizeo.maxSize.value&&(Ee(r,{code:he.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());const i=this._def.valueType;function s(u){const f=new Set;for(const m of u){if(m.status==="aborted")return Ze;m.status==="dirty"&&n.dirty(),f.add(m.value)}return{status:n.value,value:f}}const l=[...r.data.values()].map((u,f)=>i._parse(new Qo(r,u,r.path,f)));return r.common.async?Promise.all(l).then(u=>s(u)):s(l)}min(t,n){return new mc({...this._def,minSize:{value:t,message:De.toString(n)}})}max(t,n){return new mc({...this._def,maxSize:{value:t,message:De.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}}mc.create=(e,t)=>new mc({valueType:e,minSize:null,maxSize:null,typeName:Be.ZodSet,...Xe(t)});class Lu extends rt{constructor(){super(...arguments),this.validate=this.implement}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.function)return Ee(n,{code:he.invalid_type,expected:be.function,received:n.parsedType}),Ze;function r(l,u){return $1({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,C1(),Xp].filter(f=>!!f),issueData:{code:he.invalid_arguments,argumentsError:u}})}function o(l,u){return $1({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,C1(),Xp].filter(f=>!!f),issueData:{code:he.invalid_return_type,returnTypeError:u}})}const i={errorMap:n.common.contextualErrorMap},s=n.data;if(this._def.returns instanceof pd){const l=this;return rr(async function(...u){const f=new Go([]),m=await l._def.args.parseAsync(u,i).catch(y=>{throw f.addIssue(r(u,y)),f}),p=await Reflect.apply(s,this,m);return await l._def.returns._def.type.parseAsync(p,i).catch(y=>{throw f.addIssue(o(p,y)),f})})}else{const l=this;return rr(function(...u){const f=l._def.args.safeParse(u,i);if(!f.success)throw new Go([r(u,f.error)]);const m=Reflect.apply(s,this,f.data),p=l._def.returns.safeParse(m,i);if(!p.success)throw new Go([o(m,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new Lu({...this._def,args:Ti.create(t).rest(Dl.create())})}returns(t){return new Lu({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new Lu({args:t||Ti.create([]).rest(Dl.create()),returns:n||Dl.create(),typeName:Be.ZodFunction,...Xe(r)})}}class nm extends rt{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})}}nm.create=(e,t)=>new nm({getter:e,typeName:Be.ZodLazy,...Xe(t)});class rm extends rt{_parse(t){if(t.data!==this._def.value){const n=this._getOrReturnCtx(t);return Ee(n,{received:n.data,code:he.invalid_literal,expected:this._def.value}),Ze}return{status:"valid",value:t.data}}get value(){return this._def.value}}rm.create=(e,t)=>new rm({value:e,typeName:Be.ZodLiteral,...Xe(t)});function n3(e,t){return new Da({values:e,typeName:Be.ZodEnum,...Xe(t)})}class Da extends rt{_parse(t){if(typeof t.data!="string"){const n=this._getOrReturnCtx(t),r=this._def.values;return Ee(n,{expected:mt.joinValues(r),received:n.parsedType,code:he.invalid_type}),Ze}if(this._def.values.indexOf(t.data)===-1){const n=this._getOrReturnCtx(t),r=this._def.values;return Ee(n,{received:n.data,code:he.invalid_enum_value,options:r}),Ze}return rr(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 Da.create(t)}exclude(t){return Da.create(this.options.filter(n=>!t.includes(n)))}}Da.create=n3;class om extends rt{_parse(t){const n=mt.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==be.string&&r.parsedType!==be.number){const o=mt.objectValues(n);return Ee(r,{expected:mt.joinValues(o),received:r.parsedType,code:he.invalid_type}),Ze}if(n.indexOf(t.data)===-1){const o=mt.objectValues(n);return Ee(r,{received:r.data,code:he.invalid_enum_value,options:o}),Ze}return rr(t.data)}get enum(){return this._def.values}}om.create=(e,t)=>new om({values:e,typeName:Be.ZodNativeEnum,...Xe(t)});class pd extends rt{unwrap(){return this._def.type}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.promise&&n.common.async===!1)return Ee(n,{code:he.invalid_type,expected:be.promise,received:n.parsedType}),Ze;const r=n.parsedType===be.promise?n.data:Promise.resolve(n.data);return rr(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}}pd.create=(e,t)=>new pd({type:e,typeName:Be.ZodPromise,...Xe(t)});class Pi extends rt{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Be.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:n,ctx:r}=this._processInputParams(t),o=this._def.effect||null,i={addIssue:s=>{Ee(r,s),s.fatal?n.abort():n.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),o.type==="preprocess"){const s=o.transform(r.data,i);return r.common.issues.length?{status:"dirty",value:r.data}:r.common.async?Promise.resolve(s).then(l=>this._def.schema._parseAsync({data:l,path:r.path,parent:r})):this._def.schema._parseSync({data:s,path:r.path,parent:r})}if(o.type==="refinement"){const s=l=>{const u=o.refinement(l,i);if(r.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return l};if(r.common.async===!1){const l=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return l.status==="aborted"?Ze:(l.status==="dirty"&&n.dirty(),s(l.value),{status:n.value,value:l.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(l=>l.status==="aborted"?Ze:(l.status==="dirty"&&n.dirty(),s(l.value).then(()=>({status:n.value,value:l.value}))))}if(o.type==="transform")if(r.common.async===!1){const s=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Zp(s))return s;const l=o.transform(s.value,i);if(l instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:l}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(s=>Zp(s)?Promise.resolve(o.transform(s.value,i)).then(l=>({status:n.value,value:l})):s);mt.assertNever(o)}}Pi.create=(e,t,n)=>new Pi({schema:e,typeName:Be.ZodEffects,effect:t,...Xe(n)});Pi.createWithPreprocess=(e,t,n)=>new Pi({schema:t,effect:{type:"preprocess",transform:e},typeName:Be.ZodEffects,...Xe(n)});class Cs extends rt{_parse(t){return this._getType(t)===be.undefined?rr(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Cs.create=(e,t)=>new Cs({innerType:e,typeName:Be.ZodOptional,...Xe(t)});class gc extends rt{_parse(t){return this._getType(t)===be.null?rr(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}gc.create=(e,t)=>new gc({innerType:e,typeName:Be.ZodNullable,...Xe(t)});class im extends rt{_parse(t){const{ctx:n}=this._processInputParams(t);let r=n.data;return n.parsedType===be.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}im.create=(e,t)=>new im({innerType:e,typeName:Be.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Xe(t)});class N1 extends rt{_parse(t){const{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return R1(o)?o.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Go(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Go(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}N1.create=(e,t)=>new N1({innerType:e,typeName:Be.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Xe(t)});class D1 extends rt{_parse(t){if(this._getType(t)!==be.nan){const r=this._getOrReturnCtx(t);return Ee(r,{code:he.invalid_type,expected:be.nan,received:r.parsedType}),Ze}return{status:"valid",value:t.data}}}D1.create=e=>new D1({typeName:Be.ZodNaN,...Xe(e)});class hX extends rt{_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 cg extends rt{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?Ze:i.status==="dirty"?(n.dirty(),tX(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{const o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?Ze:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(t,n){return new cg({in:t,out:n,typeName:Be.ZodPipeline})}}class I1 extends rt{_parse(t){const n=this._def.innerType._parse(t);return Zp(n)&&(n.value=Object.freeze(n.value)),n}}I1.create=(e,t)=>new I1({innerType:e,typeName:Be.ZodReadonly,...Xe(t)});Vt.lazycreate;var Be;(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",e.ZodReadonly="ZodReadonly"})(Be||(Be={}));const fu=yi.create;hc.create;D1.create;pc.create;const hu=k1.create;hd.create;T1.create;qp.create;Qp.create;P1.create;Dl.create;Ms.create;A1.create;Yo.create;const pX=Vt.create;Vt.strictCreate;Jp.create;Xx.create;em.create;Ti.create;tm.create;O1.create;mc.create;Lu.create;nm.create;rm.create;Da.create;om.create;pd.create;Pi.create;Cs.create;gc.create;Pi.createWithPreprocess;cg.create;const L1="horizontal",mX=["horizontal","vertical"],r3=d.forwardRef((e,t)=>{const{decorative:n,orientation:r=L1,...o}=e,i=o3(r)?r:L1,l=n?{role:"none"}:{"aria-orientation":i==="vertical"?i:void 0,role:"separator"};return d.createElement(Ae.div,Y({"data-orientation":i},l,o,{ref:t}))});r3.propTypes={orientation(e,t,n){const r=e[t],o=String(r);return r&&!o3(r)?new Error(gX(o,n)):null}};function gX(e,t){return`Invalid prop \`orientation\` of value \`${e}\` supplied to \`${t}\`, expected one of: + - horizontal + - vertical + +Defaulting to \`${L1}\`.`}function o3(e){return mX.includes(e)}const i3=r3,gn=d.forwardRef(({className:e,orientation:t="horizontal",decorative:n=!0,...r},o)=>v.jsx(i3,{ref:o,decorative:n,orientation:t,className:Ce("shrink-0 bg-border",t==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",e),...r}));gn.displayName=i3.displayName;const vX=d.forwardRef((e,t)=>d.createElement(Ae.label,Y({},e,{ref:t,onMouseDown:n=>{var r;(r=e.onMouseDown)===null||r===void 0||r.call(e,n),!n.defaultPrevented&&n.detail>1&&n.preventDefault()}}))),s3=vX,yX=Dm("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),Zx=d.forwardRef(({className:e,disabled:t,...n},r)=>v.jsx(s3,{ref:r,className:Ce(yX(),e,t?"opacity-50":"","select-none"),...n}));Zx.displayName=s3.displayName;const wX=OY,a3=d.createContext({}),al=({...e})=>v.jsx(a3.Provider,{value:{name:e.name},children:v.jsx(LY,{...e})}),ug=()=>{const e=d.useContext(a3),t=d.useContext(l3),{getFieldState:n,formState:r}=lg(),o=n(e.name,r);if(!e)throw new Error("useFormField should be used within ");const{id:i}=t;return{id:i,name:e.name,formItemId:`${i}-form-item`,formDescriptionId:`${i}-form-item-description`,formMessageId:`${i}-form-item-message`,...o}},l3=d.createContext({}),oa=d.forwardRef(({className:e,...t},n)=>{const r=d.useId();return v.jsx(l3.Provider,{value:{id:r},children:v.jsx("div",{ref:n,className:Ce("space-y-2",e),...t})})});oa.displayName="FormItem";const ia=d.forwardRef(({className:e,...t},n)=>{const{error:r,formItemId:o}=ug();return v.jsx(Zx,{ref:n,className:Ce(r&&"text-destructive","text-sm",e),htmlFor:o,...t})});ia.displayName="FormLabel";const sa=d.forwardRef(({...e},t)=>{const{error:n,formItemId:r,formDescriptionId:o,formMessageId:i}=ug();return v.jsx(Zo,{ref:t,id:r,"aria-describedby":n?`${o} ${i}`:`${o}`,"aria-invalid":!!n,...e})});sa.displayName="FormControl";const aa=d.forwardRef(({className:e,...t},n)=>{const{formDescriptionId:r}=ug();return v.jsx("p",{ref:n,id:r,className:Ce("text-[0.8rem] text-muted-foreground",e),...t})});aa.displayName="FormDescription";const xX=d.forwardRef(({className:e,children:t,...n},r)=>{const{error:o,formMessageId:i}=ug(),s=o?String(o==null?void 0:o.message):t;return s?v.jsx("p",{ref:r,id:i,className:Ce("text-[0.8rem] font-medium text-destructive",e),...n,children:s}):null});xX.displayName="FormMessage";const c3="Switch",[bX,_te]=Mn(c3),[SX,_X]=bX(c3),EX=d.forwardRef((e,t)=>{const{__scopeSwitch:n,name:r,checked:o,defaultChecked:i,required:s,disabled:l,value:u="on",onCheckedChange:f,...m}=e,[p,g]=d.useState(null),y=Ue(t,b=>g(b)),x=d.useRef(!1),S=p?!!p.closest("form"):!0,[E=!1,_]=Zr({prop:o,defaultProp:i,onChange:f});return d.createElement(SX,{scope:n,checked:E,disabled:l},d.createElement(Ae.button,Y({type:"button",role:"switch","aria-checked":E,"aria-required":s,"data-state":u3(E),"data-disabled":l?"":void 0,disabled:l,value:u},m,{ref:y,onClick:ue(e.onClick,b=>{_(C=>!C),S&&(x.current=b.isPropagationStopped(),x.current||b.stopPropagation())})})),S&&d.createElement(RX,{control:p,bubbles:!x.current,name:r,value:u,checked:E,required:s,disabled:l,style:{transform:"translateX(-100%)"}}))}),CX="SwitchThumb",$X=d.forwardRef((e,t)=>{const{__scopeSwitch:n,...r}=e,o=_X(CX,n);return d.createElement(Ae.span,Y({"data-state":u3(o.checked),"data-disabled":o.disabled?"":void 0},r,{ref:t}))}),RX=e=>{const{control:t,checked:n,bubbles:r=!0,...o}=e,i=d.useRef(null),s=zx(n),l=yx(t);return d.useEffect(()=>{const u=i.current,f=window.HTMLInputElement.prototype,p=Object.getOwnPropertyDescriptor(f,"checked").set;if(s!==n&&p){const g=new Event("click",{bubbles:r});p.call(u,n),u.dispatchEvent(g)}},[s,n,r]),d.createElement("input",Y({type:"checkbox","aria-hidden":!0,defaultChecked:n},o,{tabIndex:-1,ref:i,style:{...e.style,...l,position:"absolute",pointerEvents:"none",opacity:0,margin:0}}))};function u3(e){return e?"checked":"unchecked"}const d3=EX,kX=$X,co=d.forwardRef(({className:e,...t},n)=>v.jsx(d3,{className:Ce("peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",e),tabIndex:-1,...t,ref:n,children:v.jsx(kX,{className:Ce("pointer-events-none block h-4 w-4 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0")})}));co.displayName=d3.displayName;const TX="AlertDialog",[PX,Ete]=Mn(TX,[dP]),zs=dP(),AX=e=>{const{__scopeAlertDialog:t,...n}=e,r=zs(t);return d.createElement(Cx,Y({},r,n,{modal:!0}))},MX=e=>{const{__scopeAlertDialog:t,...n}=e,r=zs(t);return d.createElement($x,Y({},r,n))},OX=d.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=zs(n);return d.createElement(Bd,Y({},o,r,{ref:t}))}),f3="AlertDialogContent",[NX,DX]=PX(f3),IX=d.forwardRef((e,t)=>{const{__scopeAlertDialog:n,children:r,...o}=e,i=zs(n),s=d.useRef(null),l=Ue(t,s),u=d.useRef(null);return d.createElement(hW,{contentName:f3,titleName:LX,docsSlug:"alert-dialog"},d.createElement(NX,{scope:n,cancelRef:u},d.createElement(Ud,Y({role:"alertdialog"},i,o,{ref:l,onOpenAutoFocus:ue(o.onOpenAutoFocus,f=>{var m;f.preventDefault(),(m=u.current)===null||m===void 0||m.focus({preventScroll:!0})}),onPointerDownOutside:f=>f.preventDefault(),onInteractOutside:f=>f.preventDefault()}),d.createElement(lx,null,r),!1)))}),LX="AlertDialogTitle",FX=d.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=zs(n);return d.createElement(Vd,Y({},o,r,{ref:t}))}),jX=d.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=zs(n);return d.createElement(Wd,Y({},o,r,{ref:t}))}),zX=d.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=zs(n);return d.createElement(Rx,Y({},o,r,{ref:t}))}),BX="AlertDialogCancel",UX=d.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,{cancelRef:o}=DX(BX,n),i=zs(n),s=Ue(t,o);return d.createElement(Rx,Y({},i,r,{ref:s}))}),VX=AX,WX=MX,h3=OX,p3=IX,m3=zX,g3=UX,v3=FX,y3=jX,HX=VX,KX=WX,w3=d.forwardRef(({className:e,...t},n)=>v.jsx(h3,{className:Ce("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t,ref:n}));w3.displayName=h3.displayName;const x3=d.forwardRef(({className:e,...t},n)=>v.jsxs(KX,{children:[v.jsx(w3,{}),v.jsx(p3,{ref:n,className:Ce("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",e),...t})]}));x3.displayName=p3.displayName;const b3=({className:e,...t})=>v.jsx("div",{className:Ce("flex flex-col space-y-2 text-center sm:text-left",e),...t});b3.displayName="AlertDialogHeader";const GX=d.forwardRef(({className:e,...t},n)=>v.jsx(v3,{ref:n,className:Ce("text-lg font-semibold",e),...t}));GX.displayName=v3.displayName;const YX=d.forwardRef(({className:e,...t},n)=>v.jsx(y3,{ref:n,className:Ce("text-sm text-muted-foreground",e),...t}));YX.displayName=y3.displayName;const XX=d.forwardRef(({className:e,...t},n)=>v.jsx(m3,{ref:n,className:Ce(_x(),e),...t}));XX.displayName=m3.displayName;const ZX=d.forwardRef(({className:e,...t},n)=>v.jsx(g3,{ref:n,className:Ce(_x({variant:"outline"}),"mt-2 sm:mt-0",e),...t}));ZX.displayName=g3.displayName;const qX=pX({enableFileManager:hu(),inputDirectory:fu(),outputDirectory:fu(),enableDownloadMask:hu(),enableManualInpainting:hu(),enableUploadMask:hu(),enableAutoExtractPrompt:hu(),removeBGModel:fu(),realesrganModel:fu(),interactiveSegModel:fu()}),S3="General",F1="Model",_3="Plugins",QX=[F1,S3,_3];function JX(){const[e,t]=QT(!1),[n,r]=d.useState(F1),[o,i,s,l,u,f]=bt(M=>[M.updateAppState,M.settings,M.updateSettings,M.fileManagerState,M.setModel,M.setServerConfig]),{toast:m}=Id(),[p,g]=d.useState(i.model),[y,x]=d.useState([]),S=y.length>0;d.useEffect(()=>{g(i.model)},[i.model]);const{data:E,status:_,refetch:b}=ML({queryKey:["serverConfig"],queryFn:gT}),C=YY({resolver:JY(qX),defaultValues:{enableDownloadMask:i.enableDownloadMask,enableManualInpainting:i.enableManualInpainting,enableUploadMask:i.enableUploadMask,enableAutoExtractPrompt:i.enableAutoExtractPrompt,inputDirectory:l.inputDirectory,outputDirectory:l.outputDirectory,removeBGModel:E==null?void 0:E.removeBGModel,realesrganModel:E==null?void 0:E.realesrganModel,interactiveSegModel:E==null?void 0:E.interactiveSegModel}});d.useEffect(()=>{E&&(f(E),C.setValue("removeBGModel",E.removeBGModel),C.setValue("realesrganModel",E.realesrganModel),C.setValue("interactiveSegModel",E.interactiveSegModel))},[C,E]);async function R(M){s({enableDownloadMask:M.enableDownloadMask,enableManualInpainting:M.enableManualInpainting,enableUploadMask:M.enableUploadMask,enableAutoExtractPrompt:M.enableAutoExtractPrompt});const ee=p.name!==i.model.name,H=(E==null?void 0:E.removeBGModel)!==M.removeBGModel&&A,X=(E==null?void 0:E.realesrganModel)!==M.realesrganModel&&D,W=(E==null?void 0:E.interactiveSegModel)!==M.interactiveSegModel&&B;if(ee||H||X||W){const pe=[];if(ee&&pe.push(`Switching model from ${i.model.name} to ${p.name}`),H&&pe.push(`Switching RemoveBG model from ${E==null?void 0:E.removeBGModel} to ${M.removeBGModel}`),X&&pe.push(`Switching RealESRGAN model from ${E==null?void 0:E.realesrganModel} to ${M.realesrganModel}`),W&&pe.push(`Switching ${Ao.InteractiveSeg} model from ${E==null?void 0:E.interactiveSegModel} to ${M.interactiveSegModel}`),x(pe),o({disableShortCuts:!0}),ee)try{const $e=await Bj(p.name);m({title:`Switch to ${$e.name} success`}),u(p)}catch($e){m({variant:"destructive",title:`Switch to ${p.name} failed: ${$e}`}),g(i.model)}if(H)try{const $e=await v0(Ao.RemoveBG,M.removeBGModel);if($e.status!==200)throw new Error($e.statusText)}catch($e){m({variant:"destructive",title:`Switch RemoveBG model to ${M.removeBGModel} failed: ${$e}`})}if(X)try{const $e=await v0(Ao.RealESRGAN,M.realesrganModel);if($e.status!==200)throw new Error($e.statusText)}catch($e){m({variant:"destructive",title:`Switch RealESRGAN model to ${M.realesrganModel} failed: ${$e}`})}if(W)try{const $e=await v0(Ao.InteractiveSeg,M.interactiveSegModel);if($e.status!==200)throw new Error($e.statusText)}catch($e){m({variant:"destructive",title:`Switch ${Ao.InteractiveSeg} model to ${M.interactiveSegModel} failed: ${$e}`})}x([]),o({disableShortCuts:!1}),b()}}if(Zn("s",()=>{t(),e&&R(C.getValues())},[e,C,p,E]),_!=="success")return v.jsx(v.Fragment,{});const P=E.modelInfos,O=E.plugins,A=O.some(M=>M.name===Ao.RemoveBG),D=O.some(M=>M.name===Ao.RealESRGAN),B=O.some(M=>M.name===Ao.InteractiveSeg);function V(M){t(),M||R(C.getValues())}function J(M){g(M)}function G(M){return P?P.filter(ee=>M.includes(ee.model_type)).map(ee=>v.jsxs("div",{onClick:()=>J(ee),className:"px-2",children:[v.jsx("div",{className:Ce([ee.name===p.name?"bg-muted":"hover:bg-muted","rounded-md px-2 py-2","cursor-default"]),children:v.jsx("div",{className:"text-base",children:ee.name})}),v.jsx(gn,{className:"my-1"})]},ee.name)):v.jsx("div",{children:"Please download model first"})}function se(){let M=fs;for(let ee of P)if(p.name===ee.name){M=ee.model_type,M===oC&&(M=uh),M===iC&&(M=dh);break}return v.jsxs("div",{className:"flex flex-col gap-4 w-[510px]",children:[v.jsxs("div",{className:"flex flex-col gap-4 rounded-md",children:[v.jsx("div",{className:"font-medium",children:"Current Model"}),v.jsx("div",{children:p.name})]}),v.jsx(gn,{}),v.jsxs("div",{className:"space-y-4 rounded-md",children:[v.jsx("div",{className:"flex gap-1 items-center justify-start",children:v.jsx("div",{className:"font-medium",children:"Available models"})}),v.jsxs(a5,{defaultValue:M,children:[v.jsxs(jx,{children:[v.jsx(pa,{value:fs,children:"Inpaint"}),v.jsx(pa,{value:uh,children:"Stable Diffusion"}),v.jsx(pa,{value:dh,children:"Stable Diffusion Inpaint"}),v.jsx(pa,{value:d0,children:"Other Diffusion"})]}),v.jsxs(ag,{className:"h-[240px] w-full mt-2 outline-none border rounded-lg",children:[v.jsx(Su,{value:fs,children:G([fs])}),v.jsx(Su,{value:uh,children:G([uh,oC])}),v.jsx(Su,{value:dh,children:G([dh,iC])}),v.jsx(Su,{value:d0,children:G([d0])})]})]})]})]})}function U(){return v.jsxs("div",{className:"space-y-4 w-[510px]",children:[v.jsx(al,{control:C.control,name:"enableManualInpainting",render:({field:M})=>v.jsxs(oa,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(ia,{children:"Enable manual inpainting"}),v.jsx(aa,{children:"For erase model, click a button to trigger inpainting after draw mask."})]}),v.jsx(sa,{children:v.jsx(co,{checked:M.value,onCheckedChange:M.onChange})})]})}),v.jsx(gn,{}),v.jsx(al,{control:C.control,name:"enableDownloadMask",render:({field:M})=>v.jsxs(oa,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(ia,{children:"Enable download mask"}),v.jsx(aa,{children:"Also download the mask after save the inpainting result."})]}),v.jsx(sa,{children:v.jsx(co,{checked:M.value,onCheckedChange:M.onChange})})]})}),v.jsx(gn,{}),v.jsx(al,{control:C.control,name:"enableAutoExtractPrompt",render:({field:M})=>v.jsxs(oa,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(ia,{children:"Enable auto extract prompt"}),v.jsx(aa,{children:"Automatically extract prompt/negativate prompt from the image meta."})]}),v.jsx(sa,{children:v.jsx(co,{checked:M.value,onCheckedChange:M.onChange})})]})})]})}function ne(){return v.jsxs("div",{className:"space-y-4 w-[510px]",children:[v.jsx(al,{control:C.control,name:"removeBGModel",render:({field:M})=>v.jsxs(oa,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(ia,{children:"Remove Background"}),v.jsx(aa,{children:"Remove background model"})]}),v.jsxs(Uo,{onValueChange:M.onChange,defaultValue:M.value,disabled:!A,children:[v.jsx(sa,{children:v.jsx(go,{className:"w-auto",children:v.jsx(Vo,{placeholder:"Select removebg model"})})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:E==null?void 0:E.removeBGModels.map(ee=>v.jsx(yo,{value:ee,children:ee},ee))})})]})]})}),v.jsx(gn,{}),v.jsx(al,{control:C.control,name:"realesrganModel",render:({field:M})=>v.jsxs(oa,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(ia,{children:"RealESRGAN"}),v.jsx(aa,{children:"RealESRGAN Model"})]}),v.jsxs(Uo,{onValueChange:M.onChange,defaultValue:M.value,disabled:!D,children:[v.jsx(sa,{children:v.jsx(go,{className:"w-auto",children:v.jsx(Vo,{placeholder:"Select RealESRGAN model"})})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:E==null?void 0:E.realesrganModels.map(ee=>v.jsx(yo,{value:ee,children:ee},ee))})})]})]})}),v.jsx(gn,{}),v.jsx(al,{control:C.control,name:"interactiveSegModel",render:({field:M})=>v.jsxs(oa,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(ia,{children:"Interactive Segmentation"}),v.jsx(aa,{children:"Interactive Segmentation Model"})]}),v.jsxs(Uo,{onValueChange:M.onChange,defaultValue:M.value,disabled:!B,children:[v.jsx(sa,{children:v.jsx(go,{className:"w-auto",children:v.jsx(Vo,{placeholder:"Select interactive segmentation model"})})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:E==null?void 0:E.interactiveSegModels.map(ee=>v.jsx(yo,{value:ee,children:ee},ee))})})]})]})})]})}return v.jsxs(v.Fragment,{children:[v.jsx(HX,{open:S,children:v.jsx(x3,{children:v.jsx(b3,{children:v.jsxs("div",{className:"flex flex-col justify-center items-center gap-4",children:[v.jsxs("div",{role:"status",children:[v.jsxs("svg",{"aria-hidden":"true",className:"w-8 h-8 text-gray-200 animate-spin dark:text-gray-600 fill-primary",viewBox:"0 0 100 101",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[v.jsx("path",{d:"M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z",fill:"currentColor"}),v.jsx("path",{d:"M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z",fill:"currentFill"})]}),v.jsx("span",{className:"sr-only",children:"Loading..."})]}),y?v.jsx("div",{className:"flex flex-col",children:y.map((M,ee)=>v.jsx("div",{children:M},ee))}):v.jsx(v.Fragment,{})]})})})}),v.jsxs(Jm,{open:e,onOpenChange:V,children:[v.jsx(kx,{asChild:!0,children:v.jsx(yn,{tooltip:"Settings",children:v.jsx(sV,{})})}),v.jsxs(Hd,{className:"max-w-3xl h-[600px]",onOpenAutoFocus:M=>M.preventDefault(),children:[v.jsx(Kd,{children:"Settings"}),v.jsx(gn,{}),v.jsxs("div",{className:"flex flex-row space-x-8 h-full",children:[v.jsx("div",{className:"flex flex-col space-y-1",children:QX.map(M=>v.jsx(wn,{variant:"ghost",onClick:()=>r(M),className:Ce(n===M?"bg-muted ":"hover:bg-muted","justify-start"),children:M},M))}),v.jsx(gn,{orientation:"vertical"}),v.jsx(wX,{...C,children:v.jsx("div",{className:"flex w-full justify-center",children:v.jsxs("form",{onSubmit:C.handleSubmit(R),children:[n===F1?se():v.jsx(v.Fragment,{}),n===S3?U():v.jsx(v.Fragment,{}),n===_3?ne():v.jsx(v.Fragment,{}),v.jsx("div",{className:"absolute right-10 bottom-6",children:v.jsx(wn,{onClick:()=>V(!1),children:"Ok"})})]})})})]})]})]})]})}const eZ="/assets/kofi_button_black-XI_Dr2zg.png";function tZ(){return v.jsxs(Jm,{children:[v.jsx(kx,{asChild:!0,children:v.jsx(yn,{tooltip:"Buy me a coffee",children:v.jsx(XU,{})})}),v.jsxs(Hd,{children:[v.jsx(Kd,{children:"Buy me a coffee"}),v.jsx(vP,{className:"mb-8",children:"Hi, if you found my project is useful, please conside buy me a coffee to support my work. Thanks!"}),v.jsx("div",{className:"w-full flex items-center justify-center",children:v.jsx("a",{href:"https://ko-fi.com/Z8Z1CZJGY",target:"_blank",rel:"noreferrer",children:v.jsx("img",{src:eZ,className:"h-[32px]"})})})]})]})}const nZ=()=>{const[e,t,n,r,o,i,s,l,u,f,m,p,g,y]=bt(O=>[O.file,O.customMask,O.isInpainting,O.serverConfig,O.runMannually(),O.settings.enableUploadMask,O.settings.model,O.setFile,O.setCustomFile,O.runInpainting,O.showPrevMask,O.hidePrevMask,O.imageHeight,O.imageWidth]),{toast:x}=Id(),[S,E]=Px(t),[_,b]=d.useState(!1),C=()=>{f()},R=()=>{m()},P=()=>{p()};return v.jsxs("header",{className:"h-[60px] px-6 py-4 absolute top-[0] flex justify-between items-center w-full z-20 border-b backdrop-filter backdrop-blur-md bg-background/70",children:[v.jsxs("div",{className:"flex items-center gap-1",children:[r.enableFileManager?v.jsx(PY,{photoWidth:512,onPhotoClick:async(O,A)=>{try{const D=await Vj(O,A);l(D)}catch(D){x({variant:"destructive",description:D.message?D.message:D.toString()});return}}}):v.jsx(v.Fragment,{}),v.jsx(f1,{disabled:n,tooltip:"Upload image",onFileUpload:O=>{l(O)},children:v.jsx(tV,{})}),v.jsxs("div",{className:Ce(["flex items-center gap-1",e&&i?"visible":"hidden"]),children:[v.jsx(f1,{disabled:n,tooltip:"Upload custom mask",onFileUpload:async O=>{let A=null;try{A=await gF(O)}catch(D){x({variant:"destructive",description:D.message?D.message:D.toString()});return}if(A.naturalHeight!==g||A.naturalWidth!==y){x({variant:"destructive",description:`The size of the mask must same as image: ${y}x${g}`});return}u(O),o||f()},children:v.jsx(qT,{})}),t?v.jsxs(KW,{open:_,children:[v.jsx(GW,{className:"btn-primary side-panel-trigger",onMouseEnter:()=>b(!0),onMouseLeave:()=>b(!1),style:{visibility:t?"visible":"hidden",outline:"none"},onClick:()=>{},children:v.jsx(yn,{tooltip:"Run custom mask",children:v.jsx(uz,{})})}),v.jsx(MP,{children:E?v.jsx("img",{src:S.src,alt:"Custom mask"}):v.jsx(v.Fragment,{})})]}):v.jsx(v.Fragment,{})]}),e&&!s.need_prompt?v.jsx(yn,{disabled:n,tooltip:"Rerun previous mask",onClick:C,onMouseEnter:R,onMouseLeave:P,children:v.jsx(iV,{})}):v.jsx(v.Fragment,{})]}),s.need_prompt?v.jsx(yH,{}):v.jsx(v.Fragment,{}),v.jsxs("div",{className:"flex gap-1",children:[v.jsx(tZ,{}),v.jsx(MW,{}),r.disableModelSwitch?v.jsx(v.Fragment,{}):v.jsx(JX,{})]})]})};var Wr=function(e,t){return Number(e.toFixed(t))},rZ=function(e,t){return typeof e=="number"?e:t},Nt=function(e,t,n){n&&typeof n=="function"&&n(e,t)},oZ=function(e){return-Math.cos(e*Math.PI)/2+.5},iZ=function(e){return e},sZ=function(e){return e*e},aZ=function(e){return e*(2-e)},lZ=function(e){return e<.5?2*e*e:-1+(4-2*e)*e},cZ=function(e){return e*e*e},uZ=function(e){return--e*e*e+1},dZ=function(e){return e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1},fZ=function(e){return e*e*e*e},hZ=function(e){return 1- --e*e*e*e},pZ=function(e){return e<.5?8*e*e*e*e:1-8*--e*e*e*e},mZ=function(e){return e*e*e*e*e},gZ=function(e){return 1+--e*e*e*e*e},vZ=function(e){return e<.5?16*e*e*e*e*e:1+16*--e*e*e*e*e},E3={easeOut:oZ,linear:iZ,easeInQuad:sZ,easeOutQuad:aZ,easeInOutQuad:lZ,easeInCubic:cZ,easeOutCubic:uZ,easeInOutCubic:dZ,easeInQuart:fZ,easeOutQuart:hZ,easeInOutQuart:pZ,easeInQuint:mZ,easeOutQuint:gZ,easeInOutQuint:vZ},C3=function(e){typeof e=="number"&&cancelAnimationFrame(e)},jo=function(e){e.mounted&&(C3(e.animation),e.animate=!1,e.animation=null,e.velocity=null)};function $3(e,t,n,r){if(e.mounted){var o=new Date().getTime(),i=1;jo(e),e.animation=function(){if(!e.mounted)return C3(e.animation);var s=new Date().getTime()-o,l=s/n,u=E3[t],f=u(l);s>=n?(r(i),e.animation=null):e.animation&&(r(f),requestAnimationFrame(e.animation))},requestAnimationFrame(e.animation)}}function yZ(e){var t=e.scale,n=e.positionX,r=e.positionY;return!(Number.isNaN(t)||Number.isNaN(n)||Number.isNaN(r))}function Bs(e,t,n,r){var o=yZ(t);if(!(!e.mounted||!o)){var i=e.setTransformState,s=e.transformState,l=s.scale,u=s.positionX,f=s.positionY,m=t.scale-l,p=t.positionX-u,g=t.positionY-f;n===0?i(t.scale,t.positionX,t.positionY):$3(e,r,n,function(y){var x=l+m*y,S=u+p*y,E=f+g*y;i(x,S,E)})}}function wZ(e,t,n){var r=e.offsetWidth,o=e.offsetHeight,i=t.offsetWidth,s=t.offsetHeight,l=i*n,u=s*n,f=r-l,m=o-u;return{wrapperWidth:r,wrapperHeight:o,newContentWidth:l,newDiffWidth:f,newContentHeight:u,newDiffHeight:m}}var xZ=function(e,t,n,r,o,i,s){var l=e>t?n*(s?1:.5):0,u=r>o?i*(s?1:.5):0,f=e-t-l,m=l,p=r-o-u,g=u;return{minPositionX:f,maxPositionX:m,minPositionY:p,maxPositionY:g}},qx=function(e,t){var n=e.wrapperComponent,r=e.contentComponent,o=e.setup.centerZoomedOut;if(!n||!r)throw new Error("Components are not mounted");var i=wZ(n,r,t),s=i.wrapperWidth,l=i.wrapperHeight,u=i.newContentWidth,f=i.newDiffWidth,m=i.newContentHeight,p=i.newDiffHeight,g=xZ(s,u,f,l,m,p,!!o);return g},j1=function(e,t,n,r){return r?en?Wr(n,2):Wr(e,2):Wr(e,2)},vc=function(e,t){var n=qx(e,t);return e.bounds=n,n};function dg(e,t,n,r,o,i,s){var l=n.minPositionX,u=n.minPositionY,f=n.maxPositionX,m=n.maxPositionY,p=0,g=0;s&&(p=o,g=i);var y=j1(e,l-p,f+p,r),x=j1(t,u-g,m+g,r);return{x:y,y:x}}function fg(e,t,n,r,o,i){var s=e.transformState,l=s.scale,u=s.positionX,f=s.positionY,m=r-l;if(typeof t!="number"||typeof n!="number")return console.error("Mouse X and Y position were not provided!"),{x:u,y:f};var p=u-t*m,g=f-n*m,y=dg(p,g,o,i,0,0,null);return y}function Zd(e,t,n,r,o){var i=o?r:0,s=t-i;return!Number.isNaN(n)&&e>=n?n:!Number.isNaN(t)&&e<=s?s:e}var N2=function(e,t){var n=e.setup.panning.excluded,r=e.isInitialized,o=e.wrapperComponent,i=t.target,s=o==null?void 0:o.contains(i),l=r&&i&&s;if(!l)return!1;var u=hg(i,n);return!u},D2=function(e){var t=e.isInitialized,n=e.isPanning,r=e.setup,o=r.panning.disabled,i=t&&n&&!o;return!!i},bZ=function(e,t){var n=e.transformState,r=n.positionX,o=n.positionY;e.isPanning=!0;var i=t.clientX,s=t.clientY;e.startCoords={x:i-r,y:s-o}},SZ=function(e,t){var n=t.touches,r=e.transformState,o=r.positionX,i=r.positionY;e.isPanning=!0;var s=n.length===1;if(s){var l=n[0].clientX,u=n[0].clientY;e.startCoords={x:l-o,y:u-i}}};function _Z(e){var t=e.transformState,n=t.positionX,r=t.positionY,o=t.scale,i=e.setup,s=i.disabled,l=i.limitToBounds,u=i.centerZoomedOut,f=e.wrapperComponent;if(!(s||!f||!e.bounds)){var m=e.bounds,p=m.maxPositionX,g=m.minPositionX,y=m.maxPositionY,x=m.minPositionY,S=n>p||ny||rp?f.offsetWidth:e.setup.minPositionX||0,b=r>y?f.offsetHeight:e.setup.minPositionY||0,C=fg(e,_,b,o,e.bounds,l||u),R=C.x,P=C.y;return{scale:o,positionX:S?R:n,positionY:E?P:r}}}function EZ(e,t,n,r,o){var i=e.setup.limitToBounds,s=e.wrapperComponent,l=e.bounds,u=e.transformState,f=u.scale,m=u.positionX,p=u.positionY;if(!(s===null||l===null||t===m&&n===p)){var g=dg(t,n,l,i,r,o,s),y=g.x,x=g.y;e.setTransformState(f,y,x)}}var CZ=function(e,t,n){var r=e.startCoords,o=e.transformState,i=e.setup.panning,s=i.lockAxisX,l=i.lockAxisY,u=o.positionX,f=o.positionY;if(!r)return{x:u,y:f};var m=t-r.x,p=n-r.y,g=s?u:m,y=l?f:p;return{x:g,y}},sm=function(e,t){var n=e.setup,r=e.transformState,o=r.scale,i=n.minScale,s=n.disablePadding;return t>0&&o>=i&&!s?t:0},$Z=function(e){var t=e.mounted,n=e.setup,r=n.disabled,o=n.velocityAnimation,i=e.transformState.scale,s=o.disabled,l=!s||i>1||!r||t;return!!l},RZ=function(e){var t=e.mounted,n=e.velocity,r=e.bounds,o=e.setup,i=o.disabled,s=o.velocityAnimation,l=e.transformState.scale,u=s.disabled,f=!u||l>1||!i||t;return!(!f||!n||!r)};function kZ(e,t){var n=e.setup.velocityAnimation,r=n.equalToMove,o=n.animationTime,i=n.sensitivity;return r?o*t*i:o}function I2(e,t,n,r,o,i,s,l,u,f){if(o){if(t>s&&n>s){var m=s+(e-s)*f;return m>u?u:mi?i:m}}return r?t:j1(e,i,s,o)}function TZ(e,t){var n=1;return t?Math.min(n,e.offsetWidth/window.innerWidth):n}function PZ(e,t){var n=$Z(e);if(n){var r=e.lastMousePosition,o=e.velocityTime,i=e.setup,s=e.wrapperComponent,l=i.velocityAnimation.equalToMove,u=Date.now();if(r&&o&&s){var f=TZ(s,l),m=t.x-r.x,p=t.y-r.y,g=m/f,y=p/f,x=u-o,S=m*m+p*p,E=Math.sqrt(S)/x;e.velocity={velocityX:g,velocityY:y,total:E}}e.lastMousePosition=t,e.velocityTime=u}}function AZ(e){var t=e.velocity,n=e.bounds,r=e.setup,o=e.wrapperComponent,i=RZ(e);if(!(!i||!t||!n||!o)){var s=t.velocityX,l=t.velocityY,u=t.total,f=n.maxPositionX,m=n.minPositionX,p=n.maxPositionY,g=n.minPositionY,y=r.limitToBounds,x=r.alignmentAnimation,S=r.zoomAnimation,E=r.panning,_=E.lockAxisY,b=E.lockAxisX,C=S.animationType,R=x.sizeX,P=x.sizeY,O=x.velocityAlignmentTime,A=O,D=kZ(e,u),B=Math.max(D,A),V=sm(e,R),J=sm(e,P),G=V*o.offsetWidth/100,se=J*o.offsetHeight/100,U=f+G,ne=m-G,M=p+se,ee=g-se,H=e.transformState,X=new Date().getTime();$3(e,C,B,function(W){var le=e.transformState,pe=le.scale,$e=le.positionX,Ve=le.positionY,We=new Date().getTime()-X,Ne=We/A,fe=E3[x.animationType],xe=1-fe(Math.min(1,Ne)),Re=1-W,Me=$e+s*Re,Oe=Ve+l*Re,ze=I2(Me,H.positionX,$e,b,y,m,f,ne,U,xe),Mt=I2(Oe,H.positionY,Ve,_,y,g,p,ee,M,xe);($e!==Me||Ve!==Oe)&&e.setTransformState(pe,ze,Mt)})}}function L2(e,t){var n=e.transformState.scale;jo(e),vc(e,n),window.TouchEvent!==void 0&&t instanceof TouchEvent?SZ(e,t):bZ(e,t)}function R3(e){var t=e.transformState.scale,n=e.setup,r=n.minScale,o=n.alignmentAnimation,i=o.disabled,s=o.sizeX,l=o.sizeY,u=o.animationTime,f=o.animationType,m=i||t.1&&p;g?AZ(e):R3(e)}}function Qx(e,t,n,r){var o=e.setup,i=o.minScale,s=o.maxScale,l=o.limitToBounds,u=Zd(Wr(t,2),i,s,0,!1),f=vc(e,u),m=fg(e,n,r,u,f,l),p=m.x,g=m.y;return{scale:u,positionX:p,positionY:g}}function k3(e,t,n){var r=e.transformState.scale,o=e.wrapperComponent,i=e.setup,s=i.minScale,l=i.limitToBounds,u=i.zoomAnimation,f=u.disabled,m=u.animationTime,p=u.animationType,g=f||r>=s;if((r>=1||l)&&R3(e),!(g||!o||!e.mounted)){var y=t||o.offsetWidth/2,x=n||o.offsetHeight/2,S=Qx(e,s,y,x);S&&Bs(e,S,m,p)}}var $s=function(){return $s=Object.assign||function(t){for(var n,r=1,o=arguments.length;rs||Math.sign(n.deltaY)!==Math.sign(t.deltaY)||n.deltaY>0&&n.deltaYt.deltaY||Math.sign(n.deltaY)!==Math.sign(t.deltaY):!1},XZ=function(e,t){var n=e.setup.pinch,r=n.disabled,o=n.excluded,i=e.isInitialized,s=t.target,l=i&&!r&&s;if(!l)return!1;var u=hg(s,o);return!u},ZZ=function(e){var t=e.setup.pinch.disabled,n=e.isInitialized,r=e.pinchStartDistance,o=n&&!t&&r;return!!o},qZ=function(e,t,n){var r=n.getBoundingClientRect(),o=e.touches,i=Wr(o[0].clientX-r.left,5),s=Wr(o[0].clientY-r.top,5),l=Wr(o[1].clientX-r.left,5),u=Wr(o[1].clientY-r.top,5);return{x:(i+l)/2/t,y:(s+u)/2/t}},D3=function(e){return Math.sqrt(Math.pow(e.touches[0].pageX-e.touches[1].pageX,2)+Math.pow(e.touches[0].pageY-e.touches[1].pageY,2))},QZ=function(e,t){var n=e.pinchStartScale,r=e.pinchStartDistance,o=e.setup,i=o.maxScale,s=o.minScale,l=o.zoomAnimation,u=o.disablePadding,f=l.size,m=l.disabled;if(!n||r===null||!t)throw new Error("Pinch touches distance was not provided");if(t<0)return e.transformState.scale;var p=t/r,g=p*n;return Zd(Wr(g,2),s,i,f,!m&&!u)},JZ=160,eq=100,tq=function(e,t){var n=e.props,r=n.onWheelStart,o=n.onZoomStart;e.wheelStopEventTimer||(jo(e),Nt(_t(e),t,r),Nt(_t(e),t,o))},nq=function(e,t){var n=e.props,r=n.onWheel,o=n.onZoom,i=e.contentComponent,s=e.setup,l=e.transformState,u=l.scale,f=s.limitToBounds,m=s.centerZoomedOut,p=s.zoomAnimation,g=s.wheel,y=s.disablePadding,x=s.smooth,S=p.size,E=p.disabled,_=g.step,b=g.smoothStep;if(!i)throw new Error("Component not mounted");t.preventDefault(),t.stopPropagation();var C=KZ(t,null),R=x?b*Math.abs(t.deltaY):_,P=GZ(e,C,R,!t.ctrlKey);if(u!==P){var O=vc(e,P),A=N3(t,i,u),D=E||S===0||m||y,B=f&&D,V=fg(e,A.x,A.y,P,O,B),J=V.x,G=V.y;e.previousWheelEvent=t,e.setTransformState(P,J,G),Nt(_t(e),t,r),Nt(_t(e),t,o)}},rq=function(e,t){var n=e.props,r=n.onWheelStop,o=n.onZoomStop;B1(e.wheelAnimationTimer),e.wheelAnimationTimer=setTimeout(function(){e.mounted&&(k3(e,t.x,t.y),e.wheelAnimationTimer=null)},eq);var i=YZ(e,t);i&&(B1(e.wheelStopEventTimer),e.wheelStopEventTimer=setTimeout(function(){e.mounted&&(e.wheelStopEventTimer=null,Nt(_t(e),t,r),Nt(_t(e),t,o))},JZ))},oq=function(e,t){var n=D3(t);e.pinchStartDistance=n,e.lastDistance=n,e.pinchStartScale=e.transformState.scale,e.isPanning=!1,jo(e)},iq=function(e,t){var n=e.contentComponent,r=e.pinchStartDistance,o=e.transformState.scale,i=e.setup,s=i.limitToBounds,l=i.centerZoomedOut,u=i.zoomAnimation,f=u.disabled,m=u.size;if(!(r===null||!n)){var p=qZ(t,o,n);if(!(!Number.isFinite(p.x)||!Number.isFinite(p.y))){var g=D3(t),y=QZ(e,g);if(y!==o){var x=vc(e,y),S=f||m===0||l,E=s&&S,_=fg(e,p.x,p.y,y,x,E),b=_.x,C=_.y;e.pinchMidpoint=p,e.lastDistance=g,e.setTransformState(y,b,C)}}}},sq=function(e){var t=e.pinchMidpoint;e.velocity=null,e.lastDistance=null,e.pinchMidpoint=null,e.pinchStartScale=null,e.pinchStartDistance=null,k3(e,t==null?void 0:t.x,t==null?void 0:t.y)},I3=function(e,t){var n=e.props.onZoomStop,r=e.setup.doubleClick.animationTime;B1(e.doubleClickStopEventTimer),e.doubleClickStopEventTimer=setTimeout(function(){e.doubleClickStopEventTimer=null,Nt(_t(e),t,n)},r)},aq=function(e,t){var n=e.props,r=n.onZoomStart,o=n.onZoom,i=e.setup.doubleClick,s=i.animationTime,l=i.animationType;Nt(_t(e),t,r),M3(e,s,l,function(){return Nt(_t(e),t,o)}),I3(e,t)};function lq(e,t){var n=e.setup,r=e.doubleClickStopEventTimer,o=e.transformState,i=e.contentComponent,s=o.scale,l=e.props,u=l.onZoomStart,f=l.onZoom,m=n.doubleClick,p=m.disabled,g=m.mode,y=m.step,x=m.animationTime,S=m.animationType;if(!p&&!r){if(g==="reset")return aq(e,t);if(!i)return console.error("No ContentComponent found");var E=g==="zoomOut"?-1:1,_=P3(e,E,y);if(s!==_){Nt(_t(e),t,u);var b=N3(t,i,s),C=Qx(e,_,b.x,b.y);if(!C)return console.error("Error during zoom event. New transformation state was not calculated.");Nt(_t(e),t,f),Bs(e,C,x,S),I3(e,t)}}}var cq=function(e,t){var n=e.isInitialized,r=e.setup,o=e.wrapperComponent,i=r.doubleClick,s=i.disabled,l=i.excluded,u=t.target,f=o==null?void 0:o.contains(u),m=n&&u&&f&&!s;if(!m)return!1;var p=hg(u,l);return!p},uq=function(){function e(t){var n=this;this.mounted=!0,this.onChangeCallbacks=new Set,this.onInitCallbacks=new Set,this.wrapperComponent=null,this.contentComponent=null,this.isInitialized=!1,this.bounds=null,this.previousWheelEvent=null,this.wheelStopEventTimer=null,this.wheelAnimationTimer=null,this.isPanning=!1,this.startCoords=null,this.lastTouch=null,this.distance=null,this.lastDistance=null,this.pinchStartDistance=null,this.pinchStartScale=null,this.pinchMidpoint=null,this.doubleClickStopEventTimer=null,this.velocity=null,this.velocityTime=null,this.lastMousePosition=null,this.animate=!1,this.animation=null,this.maxBounds=null,this.pressedKeys={},this.mount=function(){n.initializeWindowEvents()},this.unmount=function(){n.cleanupWindowEvents()},this.update=function(r){vc(n,n.transformState.scale),n.setup=z2(r)},this.initializeWindowEvents=function(){var r,o=j0(),i=(r=n.wrapperComponent)===null||r===void 0?void 0:r.ownerDocument,s=i==null?void 0:i.defaultView;s==null||s.addEventListener("mousedown",n.onPanningStart,o),s==null||s.addEventListener("mousemove",n.onPanning,o),s==null||s.addEventListener("mouseup",n.onPanningStop,o),i==null||i.addEventListener("mouseleave",n.clearPanning,o),s==null||s.addEventListener("keyup",n.setKeyUnPressed,o),s==null||s.addEventListener("keydown",n.setKeyPressed,o)},this.cleanupWindowEvents=function(){var r,o,i=j0(),s=(r=n.wrapperComponent)===null||r===void 0?void 0:r.ownerDocument,l=s==null?void 0:s.defaultView;l==null||l.removeEventListener("mousedown",n.onPanningStart,i),l==null||l.removeEventListener("mousemove",n.onPanning,i),l==null||l.removeEventListener("mouseup",n.onPanningStop,i),s==null||s.removeEventListener("mouseleave",n.clearPanning,i),l==null||l.removeEventListener("keyup",n.setKeyUnPressed,i),l==null||l.removeEventListener("keydown",n.setKeyPressed,i),document.removeEventListener("mouseleave",n.clearPanning,i),jo(n),(o=n.observer)===null||o===void 0||o.disconnect()},this.handleInitializeWrapperEvents=function(r){var o=j0();r.addEventListener("wheel",n.onWheelZoom,o),r.addEventListener("dblclick",n.onDoubleClick,o),r.addEventListener("touchstart",n.onTouchPanningStart,o),r.addEventListener("touchmove",n.onTouchPanning,o),r.addEventListener("touchend",n.onTouchPanningStop,o)},this.handleInitialize=function(r){var o=n.setup.centerOnInit;n.applyTransformation(),n.onInitCallbacks.forEach(function(i){return i(_t(n))}),o&&(n.setCenter(),n.observer=new ResizeObserver(function(){var i;n.onInitCallbacks.forEach(function(s){return s(_t(n))}),n.setCenter(),(i=n.observer)===null||i===void 0||i.disconnect()}),n.observer.observe(r))},this.onWheelZoom=function(r){var o=n.setup.disabled;if(!o){var i=WZ(n,r);if(i){var s=n.isPressingKeys(n.setup.wheel.activationKeys);s&&(tq(n,r),nq(n,r),rq(n,r))}}},this.onPanningStart=function(r){var o=n.setup.disabled,i=n.props.onPanningStart;if(!o){var s=N2(n,r);if(s){var l=n.isPressingKeys(n.setup.panning.activationKeys);l&&(r.button===0&&!n.setup.panning.allowLeftClickPan||r.button===1&&!n.setup.panning.allowMiddleClickPan||r.button===2&&!n.setup.panning.allowRightClickPan||(r.preventDefault(),r.stopPropagation(),jo(n),L2(n,r),Nt(_t(n),r,i)))}}},this.onPanning=function(r){var o=n.setup.disabled,i=n.props.onPanning;if(!o){var s=D2(n);if(s){var l=n.isPressingKeys(n.setup.panning.activationKeys);l&&(r.preventDefault(),r.stopPropagation(),F2(n,r.clientX,r.clientY),Nt(_t(n),r,i))}}},this.onPanningStop=function(r){var o=n.props.onPanningStop;n.isPanning&&(MZ(n),Nt(_t(n),r,o))},this.onPinchStart=function(r){var o=n.setup.disabled,i=n.props,s=i.onPinchingStart,l=i.onZoomStart;if(!o){var u=XZ(n,r);u&&(oq(n,r),jo(n),Nt(_t(n),r,s),Nt(_t(n),r,l))}},this.onPinch=function(r){var o=n.setup.disabled,i=n.props,s=i.onPinching,l=i.onZoom;if(!o){var u=ZZ(n);u&&(r.preventDefault(),r.stopPropagation(),iq(n,r),Nt(_t(n),r,s),Nt(_t(n),r,l))}},this.onPinchStop=function(r){var o=n.props,i=o.onPinchingStop,s=o.onZoomStop;n.pinchStartScale&&(sq(n),Nt(_t(n),r,i),Nt(_t(n),r,s))},this.onTouchPanningStart=function(r){var o=n.setup.disabled,i=n.props.onPanningStart;if(!o){var s=N2(n,r);if(s){var l=n.lastTouch&&+new Date-n.lastTouch<200;if(l&&r.touches.length===1)n.onDoubleClick(r);else{n.lastTouch=+new Date,jo(n);var u=r.touches,f=u.length===1,m=u.length===2;f&&(jo(n),L2(n,r),Nt(_t(n),r,i)),m&&n.onPinchStart(r)}}}},this.onTouchPanning=function(r){var o=n.setup.disabled,i=n.props.onPanning;if(n.isPanning&&r.touches.length===1){if(o)return;var s=D2(n);if(!s)return;r.preventDefault(),r.stopPropagation();var l=r.touches[0];F2(n,l.clientX,l.clientY),Nt(_t(n),r,i)}else r.touches.length>1&&n.onPinch(r)},this.onTouchPanningStop=function(r){n.onPanningStop(r),n.onPinchStop(r)},this.onDoubleClick=function(r){var o=n.setup.disabled;if(!o){var i=cq(n,r);i&&lq(n,r)}},this.clearPanning=function(r){n.isPanning&&n.onPanningStop(r)},this.setKeyPressed=function(r){n.pressedKeys[r.key]=!0},this.setKeyUnPressed=function(r){n.pressedKeys[r.key]=!1},this.isPressingKeys=function(r){return r.length?!!r.find(function(o){return n.pressedKeys[o]}):!0},this.setTransformState=function(r,o,i){var s=n.props.onTransformed;if(!Number.isNaN(r)&&!Number.isNaN(o)&&!Number.isNaN(i)){r!==n.transformState.scale&&(n.transformState.previousScale=n.transformState.scale,n.transformState.scale=r),n.transformState.positionX=o,n.transformState.positionY=i,n.applyTransformation();var l=_t(n);n.onChangeCallbacks.forEach(function(u){return u(l)}),Nt(l,{scale:r,positionX:o,positionY:i},s)}else console.error("Detected NaN set state values")},this.setCenter=function(){if(n.wrapperComponent&&n.contentComponent){var r=O3(n.transformState.scale,n.wrapperComponent,n.contentComponent);n.setTransformState(r.scale,r.positionX,r.positionY)}},this.handleTransformStyles=function(r,o,i){return n.props.customTransform?n.props.customTransform(r,o,i):UZ(r,o,i)},this.applyTransformation=function(){if(!(!n.mounted||!n.contentComponent)){var r=n.transformState,o=r.scale,i=r.positionX,s=r.positionY,l=n.handleTransformStyles(i,s,o);n.contentComponent.style.transform=l}},this.getContext=function(){return _t(n)},this.onChange=function(r){return n.onChangeCallbacks.has(r)||n.onChangeCallbacks.add(r),function(){n.onChangeCallbacks.delete(r)}},this.onInit=function(r){return n.onInitCallbacks.has(r)||n.onInitCallbacks.add(r),function(){n.onInitCallbacks.delete(r)}},this.init=function(r,o){n.cleanupWindowEvents(),n.wrapperComponent=r,n.contentComponent=o,vc(n,n.transformState.scale),n.handleInitializeWrapperEvents(r),n.handleInitialize(o),n.initializeWindowEvents(),n.isInitialized=!0;var i=_t(n);Nt(i,void 0,n.props.onInit)},this.props=t,this.setup=z2(this.props),this.transformState=T3(this.props)}return e}(),Jx=je.createContext(null),dq=function(e,t){return typeof e=="function"?e(t):e},fq=je.forwardRef(function(e,t){var n=d.useRef(new uq(e)).current,r=dq(e.children,z1(n));return d.useImperativeHandle(t,function(){return z1(n)},[n]),d.useEffect(function(){n.update(e)},[n,e]),je.createElement(Jx.Provider,{value:n},r)});je.forwardRef(function(e,t){var n=d.useRef(null),r=d.useContext(Jx);return d.useEffect(function(){return r.onChange(function(o){if(n.current){var i=0,s=0;n.current.style.transform=r.handleTransformStyles(i,s,1/o.instance.transformState.scale)}})},[r]),je.createElement("div",$s({},e,{ref:VZ([n,t])}))});function hq(e,t){t===void 0&&(t={});var n=t.insertAt;if(!(!e||typeof document>"u")){var r=document.head||document.getElementsByTagName("head")[0],o=document.createElement("style");o.type="text/css",n==="top"&&r.firstChild?r.insertBefore(o,r.firstChild):r.appendChild(o),o.styleSheet?o.styleSheet.cssText=e:o.appendChild(document.createTextNode(e))}}var pq=`.transform-component-module_wrapper__SPB86 { + position: relative; + width: -moz-fit-content; + width: fit-content; + height: -moz-fit-content; + height: fit-content; + overflow: hidden; + -webkit-touch-callout: none; /* iOS Safari */ + -webkit-user-select: none; /* Safari */ + -khtml-user-select: none; /* Konqueror HTML */ + -moz-user-select: none; /* Firefox */ + -ms-user-select: none; /* Internet Explorer/Edge */ + user-select: none; + margin: 0; + padding: 0; +} +.transform-component-module_content__FBWxo { + display: flex; + flex-wrap: wrap; + width: -moz-fit-content; + width: fit-content; + height: -moz-fit-content; + height: fit-content; + margin: 0; + padding: 0; + transform-origin: 0% 0%; +} +.transform-component-module_content__FBWxo img { + pointer-events: none; +} +`,B2={wrapper:"transform-component-module_wrapper__SPB86",content:"transform-component-module_content__FBWxo"};hq(pq);var mq=function(e){var t=e.children,n=e.wrapperClass,r=n===void 0?"":n,o=e.contentClass,i=o===void 0?"":o,s=e.wrapperStyle,l=e.contentStyle,u=e.wrapperProps,f=u===void 0?{}:u,m=e.contentProps,p=m===void 0?{}:m,g=d.useContext(Jx),y=g.init,x=g.cleanupWindowEvents,S=d.useRef(null),E=d.useRef(null);return d.useEffect(function(){var _=S.current,b=E.current;return _!==null&&b!==null&&y&&(y==null||y(_,b)),function(){x==null||x()}},[]),je.createElement("div",$s({},f,{ref:S,className:"react-transform-wrapper ".concat(B2.wrapper," ").concat(r),style:s}),je.createElement("div",$s({},p,{ref:E,className:"react-transform-component ".concat(B2.content," ").concat(i),style:l}),t))};const L3=["PageUp","PageDown"],F3=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],j3={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},qd="Slider",[U1,gq,vq]=Gd(qd),[z3,Cte]=Mn(qd,[vq]),[yq,pg]=z3(qd),wq=d.forwardRef((e,t)=>{const{name:n,min:r=0,max:o=100,step:i=1,orientation:s="horizontal",disabled:l=!1,minStepsBetweenThumbs:u=0,defaultValue:f=[r],value:m,onValueChange:p=()=>{},onValueCommit:g=()=>{},inverted:y=!1,...x}=e,[S,E]=d.useState(null),_=Ue(t,U=>E(U)),b=d.useRef(new Set),C=d.useRef(0),R=s==="horizontal",P=S?!!S.closest("form"):!0,O=R?xq:bq,[A=[],D]=Zr({prop:m,defaultProp:f,onChange:U=>{var ne;(ne=[...b.current][C.current])===null||ne===void 0||ne.focus(),p(U)}}),B=d.useRef(A);function V(U){const ne=Pq(A,U);se(U,ne)}function J(U){se(U,C.current)}function G(){const U=B.current[C.current];A[C.current]!==U&&g(A)}function se(U,ne,{commit:M}={commit:!1}){const ee=Nq(i),H=Dq(Math.round((U-r)/i)*i+r,ee),X=fd(H,[r,o]);D((W=[])=>{const le=kq(W,X,ne);if(Oq(le,u*i)){C.current=le.indexOf(X);const pe=String(le)!==String(W);return pe&&M&&g(le),pe?le:W}else return W})}return d.createElement(yq,{scope:e.__scopeSlider,disabled:l,min:r,max:o,valueIndexToChangeRef:C,thumbs:b.current,values:A,orientation:s},d.createElement(U1.Provider,{scope:e.__scopeSlider},d.createElement(U1.Slot,{scope:e.__scopeSlider},d.createElement(O,Y({"aria-disabled":l,"data-disabled":l?"":void 0},x,{ref:_,onPointerDown:ue(x.onPointerDown,()=>{l||(B.current=A)}),min:r,max:o,inverted:y,onSlideStart:l?void 0:V,onSlideMove:l?void 0:J,onSlideEnd:l?void 0:G,onHomeKeyDown:()=>!l&&se(r,0,{commit:!0}),onEndKeyDown:()=>!l&&se(o,A.length-1,{commit:!0}),onStepKeyDown:({event:U,direction:ne})=>{if(!l){const H=L3.includes(U.key)||U.shiftKey&&F3.includes(U.key)?10:1,X=C.current,W=A[X],le=i*H*ne;se(W+le,X,{commit:!0})}}})))),P&&A.map((U,ne)=>d.createElement(Rq,{key:ne,name:n?n+(A.length>1?"[]":""):void 0,value:U})))}),[B3,U3]=z3(qd,{startEdge:"left",endEdge:"right",size:"width",direction:1}),xq=d.forwardRef((e,t)=>{const{min:n,max:r,dir:o,inverted:i,onSlideStart:s,onSlideMove:l,onSlideEnd:u,onStepKeyDown:f,...m}=e,[p,g]=d.useState(null),y=Ue(t,C=>g(C)),x=d.useRef(),S=Tc(o),E=S==="ltr",_=E&&!i||!E&&i;function b(C){const R=x.current||p.getBoundingClientRect(),P=[0,R.width],A=eb(P,_?[n,r]:[r,n]);return x.current=R,A(C-R.left)}return d.createElement(B3,{scope:e.__scopeSlider,startEdge:_?"left":"right",endEdge:_?"right":"left",direction:_?1:-1,size:"width"},d.createElement(V3,Y({dir:S,"data-orientation":"horizontal"},m,{ref:y,style:{...m.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:C=>{const R=b(C.clientX);s==null||s(R)},onSlideMove:C=>{const R=b(C.clientX);l==null||l(R)},onSlideEnd:()=>{x.current=void 0,u==null||u()},onStepKeyDown:C=>{const P=j3[_?"from-left":"from-right"].includes(C.key);f==null||f({event:C,direction:P?-1:1})}})))}),bq=d.forwardRef((e,t)=>{const{min:n,max:r,inverted:o,onSlideStart:i,onSlideMove:s,onSlideEnd:l,onStepKeyDown:u,...f}=e,m=d.useRef(null),p=Ue(t,m),g=d.useRef(),y=!o;function x(S){const E=g.current||m.current.getBoundingClientRect(),_=[0,E.height],C=eb(_,y?[r,n]:[n,r]);return g.current=E,C(S-E.top)}return d.createElement(B3,{scope:e.__scopeSlider,startEdge:y?"bottom":"top",endEdge:y?"top":"bottom",size:"height",direction:y?1:-1},d.createElement(V3,Y({"data-orientation":"vertical"},f,{ref:p,style:{...f.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:S=>{const E=x(S.clientY);i==null||i(E)},onSlideMove:S=>{const E=x(S.clientY);s==null||s(E)},onSlideEnd:()=>{g.current=void 0,l==null||l()},onStepKeyDown:S=>{const _=j3[y?"from-bottom":"from-top"].includes(S.key);u==null||u({event:S,direction:_?-1:1})}})))}),V3=d.forwardRef((e,t)=>{const{__scopeSlider:n,onSlideStart:r,onSlideMove:o,onSlideEnd:i,onHomeKeyDown:s,onEndKeyDown:l,onStepKeyDown:u,...f}=e,m=pg(qd,n);return d.createElement(Ae.span,Y({},f,{ref:t,onKeyDown:ue(e.onKeyDown,p=>{p.key==="Home"?(s(p),p.preventDefault()):p.key==="End"?(l(p),p.preventDefault()):L3.concat(F3).includes(p.key)&&(u(p),p.preventDefault())}),onPointerDown:ue(e.onPointerDown,p=>{const g=p.target;g.setPointerCapture(p.pointerId),p.preventDefault(),m.thumbs.has(g)?g.focus():r(p)}),onPointerMove:ue(e.onPointerMove,p=>{p.target.hasPointerCapture(p.pointerId)&&o(p)}),onPointerUp:ue(e.onPointerUp,p=>{const g=p.target;g.hasPointerCapture(p.pointerId)&&(g.releasePointerCapture(p.pointerId),i(p))})}))}),Sq="SliderTrack",_q=d.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,o=pg(Sq,n);return d.createElement(Ae.span,Y({"data-disabled":o.disabled?"":void 0,"data-orientation":o.orientation},r,{ref:t}))}),U2="SliderRange",Eq=d.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,o=pg(U2,n),i=U3(U2,n),s=d.useRef(null),l=Ue(t,s),u=o.values.length,f=o.values.map(g=>W3(g,o.min,o.max)),m=u>1?Math.min(...f):0,p=100-Math.max(...f);return d.createElement(Ae.span,Y({"data-orientation":o.orientation,"data-disabled":o.disabled?"":void 0},r,{ref:l,style:{...e.style,[i.startEdge]:m+"%",[i.endEdge]:p+"%"}}))}),V2="SliderThumb",Cq=d.forwardRef((e,t)=>{const n=gq(e.__scopeSlider),[r,o]=d.useState(null),i=Ue(t,l=>o(l)),s=d.useMemo(()=>r?n().findIndex(l=>l.ref.current===r):-1,[n,r]);return d.createElement($q,Y({},e,{ref:i,index:s}))}),$q=d.forwardRef((e,t)=>{const{__scopeSlider:n,index:r,...o}=e,i=pg(V2,n),s=U3(V2,n),[l,u]=d.useState(null),f=Ue(t,E=>u(E)),m=yx(l),p=i.values[r],g=p===void 0?0:W3(p,i.min,i.max),y=Tq(r,i.values.length),x=m==null?void 0:m[s.size],S=x?Aq(x,g,s.direction):0;return d.useEffect(()=>{if(l)return i.thumbs.add(l),()=>{i.thumbs.delete(l)}},[l,i.thumbs]),d.createElement("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[s.startEdge]:`calc(${g}% + ${S}px)`}},d.createElement(U1.ItemSlot,{scope:e.__scopeSlider},d.createElement(Ae.span,Y({role:"slider","aria-label":e["aria-label"]||y,"aria-valuemin":i.min,"aria-valuenow":p,"aria-valuemax":i.max,"aria-orientation":i.orientation,"data-orientation":i.orientation,"data-disabled":i.disabled?"":void 0,tabIndex:i.disabled?void 0:0},o,{ref:f,style:p===void 0?{display:"none"}:e.style,onFocus:ue(e.onFocus,()=>{i.valueIndexToChangeRef.current=r})}))))}),Rq=e=>{const{value:t,...n}=e,r=d.useRef(null),o=zx(t);return d.useEffect(()=>{const i=r.current,s=window.HTMLInputElement.prototype,u=Object.getOwnPropertyDescriptor(s,"value").set;if(o!==t&&u){const f=new Event("input",{bubbles:!0});u.call(i,t),i.dispatchEvent(f)}},[o,t]),d.createElement("input",Y({style:{display:"none"}},n,{ref:r,defaultValue:t}))};function kq(e=[],t,n){const r=[...e];return r[n]=t,r.sort((o,i)=>o-i)}function W3(e,t,n){const i=100/(n-t)*(e-t);return fd(i,[0,100])}function Tq(e,t){return t>2?`Value ${e+1} of ${t}`:t===2?["Minimum","Maximum"][e]:void 0}function Pq(e,t){if(e.length===1)return 0;const n=e.map(o=>Math.abs(o-t)),r=Math.min(...n);return n.indexOf(r)}function Aq(e,t,n){const r=e/2,i=eb([0,50],[0,r]);return(r-i(t)*n)*n}function Mq(e){return e.slice(0,-1).map((t,n)=>e[n+1]-t)}function Oq(e,t){if(t>0){const n=Mq(e);return Math.min(...n)>=t}return!0}function eb(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 Nq(e){return(String(e).split(".")[1]||"").length}function Dq(e,t){const n=Math.pow(10,t);return Math.round(e*n)/n}const H3=wq,Iq=_q,Lq=Eq,Fq=Cq,uo=d.forwardRef(({className:e,...t},n)=>v.jsxs(H3,{ref:n,className:Ce("relative flex w-full touch-none select-none items-center",e),tabIndex:-1,...t,children:[v.jsx(Iq,{className:"relative h-1.5 w-full grow overflow-hidden rounded-full bg-primary/20 data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50",children:v.jsx(Lq,{className:"absolute h-full bg-primary data-[disabled]:cursor-not-allowed "})}),v.jsx(Fq,{tabIndex:-1,className:"block h-4 w-4 rounded-full border border-primary/60 bg-background shadow transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring data-[disabled]:cursor-not-allowed"})]}));uo.displayName=H3.displayName;const ll={capture:!0,passive:!1},jq=2,W2=(e,t,n,r,o,i)=>{if(e!==n&&t===r){if(e<0)return[0,r];if(e+t>i)return[i-r,r]}else{if(ti)return[e,i-e]}return[e,t]},zq=e=>{const{minHeight:t,minWidth:n,maxHeight:r,maxWidth:o,scale:i,show:s}=e,[l,u,f,m,{x:p,y:g,width:y,height:x},S,E,_,b,C,R]=bt(W=>[W.imageWidth,W.imageHeight,W.isInpainting,W.isSD(),W.cropperState,W.setCropperX,W.setCropperY,W.setCropperWidth,W.setCropperHeight,W.isCropperExtenderResizing,W.setIsCropperExtenderResizing]),[P,O]=d.useState(!1);d.useEffect(()=>{S(Math.round((o-512)/2)),E(Math.round((r-512)/2))},[r,o,l,u]);const[A,D]=d.useState({initX:0,initY:0,initHeight:0,initWidth:0,startResizeX:0,startResizeY:0,ord:"top"}),B=()=>{},V=(W,le)=>W2(W,le,p,y,n,o),J=(W,le)=>W2(W,le,g,x,t,r),G=W=>{if(f)return;const le=W.clientX,pe=W.clientY,$e=Math.round((pe-A.startResizeY)/i),Ve=Math.round((le-A.startResizeX)/i),We=()=>{const Re=A.initHeight-$e,Me=A.initY+$e,[Oe,ze]=J(Me,Re);b(ze),E(Oe)},Ne=()=>{const Re=A.initHeight+$e,[Me,Oe]=J(A.initY,Re);b(Oe),E(Me)},fe=()=>{const Re=A.initWidth-Ve,Me=A.initX+Ve,[Oe,ze]=V(Me,Re);_(ze),S(Oe)},xe=()=>{const Re=A.initWidth+Ve,[Me,Oe]=V(A.initX,Re);_(Oe),S(Me)};if(C)switch(A.ord){case"topleft":{We(),fe();break}case"topright":{We(),xe();break}case"bottomleft":{Ne(),fe();break}case"bottomright":{Ne(),xe();break}case"top":{We();break}case"right":{xe();break}case"bottom":{Ne();break}case"left":{fe();break}}if(P){const Re=A.initX+Ve,Me=A.initY+$e,[Oe,ze]=V(Re,A.initWidth),[Mt,ct]=J(Me,A.initHeight);_(ze),b(ct),S(Oe),E(Mt)}},se=()=>{C&&R(!1),P&&O(!1)};d.useEffect(()=>{if(C||P)return document.addEventListener("pointermove",G,ll),document.addEventListener("pointerup",se,ll),document.addEventListener("pointercancel",se,ll),()=>{document.removeEventListener("pointermove",G,ll),document.removeEventListener("pointerup",se,ll),document.removeEventListener("pointercancel",se,ll)}},[C,P,y,x,A]);const U=W=>{const{ord:le}=W.target.dataset;le&&(R(!0),D({initX:p,initY:g,initHeight:x,initWidth:y,startResizeX:W.clientX,startResizeY:W.clientY,ord:le}))},ne=(W,le,pe)=>{const We="w-[12px] h-[12px] z-[4] absolute content-[''] block border-2 border-primary borde pointer-events-auto hover:bg-primary";let Ne="0",fe="0",xe=pe,Re="-6px";return pe===""&&(Re="50%",le==="left"||le==="right"?(xe="top",fe="-50%"):(xe="left",Ne="-50%")),v.jsx("div",{className:Ce(We,W),style:{[le]:-6,[xe]:Re,transform:`translate(${Ne}, ${fe}) scale(${1/i})`},"data-ord":le+pe,"aria-label":le+pe,tabIndex:-1,role:"button"})},M=()=>v.jsxs("div",{onFocus:B,onPointerDown:U,className:"absolute top-0 h-full w-full",children:[v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 w-full cursor-ns-resize h-[12px] mt-[-6px]","data-ord":"top"}),v.jsx("div",{className:"absolute pointer-events-auto top-0 right-0 h-full cursor-ew-resize w-[12px] mr-[-6px]","data-ord":"right"}),v.jsx("div",{className:"absolute pointer-events-auto bottom-0 left-0 w-full cursor-ns-resize h-[12px] mb-[-6px]","data-ord":"bottom"}),v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 h-full cursor-ew-resize w-[12px] ml-[-6px]","data-ord":"left"}),ne("cursor-nw-resize","top","left"),ne("cursor-ne-resize","top","right"),ne("cursor-sw-resize","bottom","left"),ne("cursor-se-resize","bottom","right"),ne("cursor-ns-resize","top",""),ne("cursor-ns-resize","bottom",""),ne("cursor-ew-resize","left",""),ne("cursor-ew-resize","right","")]}),ee=W=>{O(!0),D({initX:p,initY:g,initHeight:x,initWidth:y,startResizeX:W.clientX,startResizeY:W.clientY,ord:""})},H=()=>v.jsxs("div",{className:tx("border absolute pointer-events-auto px-2 py-1 rounded-full hover:cursor-move bg-background","origin-top-left top-0 left-0"),style:{transform:`scale(${1/i*.8})`},onPointerDown:ee,children:[y," x ",x]}),X=()=>v.jsx("div",{className:"outline-dashed outline-primary",style:{height:x,width:y,outlineWidth:`${jq/i*1.3}px`}});return s===!1||!m?null:v.jsx("div",{className:"absolute h-full w-full overflow-hidden pointer-events-none z-[2]",children:v.jsxs("div",{className:"relative pointer-events-none z-[2] [box-shadow:0_0_0_9999px_rgba(0,_0,_0,_0.5)]",style:{height:x,width:y,left:p,top:g},children:[X(),H(),M()]})})},Bq=()=>{const[e,t,n]=bt(r=>[r.interactiveSegState,r.resetInteractiveSegState,r.handleInteractiveSegAccept]);return e.isInteractiveSeg?v.jsxs("div",{className:"z-10 absolute top-[68px] rounded-xl border-solid border p-[8px] left-1/2 translate-x-[-50%] flex justify-center items-center gap-[8px] bg-background",children:[v.jsx(wn,{onClick:()=>{t()},size:"sm",variant:"secondary",children:"Cancel"}),v.jsx(wn,{size:"sm",onClick:()=>{n()},children:"Accept"})]}):null},Uq=e=>{const{x:t,y:n,positive:r}=e,o=r?"bg-[rgba(21,_215,_121,_0.936)] outline-[rgba(98,255,179,0.31)]":"bg-[rgba(237,_49,_55,_0.942)] outline-[rgba(255,89,95,0.31)]";return v.jsx("div",{className:`absolute h-[10px] w-[10px] rounded-[50%] ${o} outline-8 outline`,style:{left:t,top:n,transform:"translate(-50%, -50%)"}})},Vq=()=>{const e=bt(t=>t.interactiveSegState.clicks);return v.jsx("div",{className:"absolute h-full w-full overflow-hidden pointer-events-none",children:e.map(t=>v.jsx(Uq,{x:t[0],y:t[1],positive:t[2]===1},t[3]))})},Wq=()=>v.jsx("div",{children:v.jsx(Bq,{})}),cl={capture:!0,passive:!1},Hq=2,H2=(e,t,n,r)=>t{const{minHeight:t,minWidth:n,scale:r,show:o}=e,[i,s,l,u,{x:f,y:m,width:p,height:g},y,x,S,E,_,b,C]=bt(ee=>[ee.isInpainting,ee.imageHeight,ee.imageWidth,ee.isSD(),ee.extenderState,ee.setExtenderX,ee.setExtenderY,ee.setExtenderWidth,ee.setExtenderHeight,ee.settings.extenderDirection,ee.isCropperExtenderResizing,ee.setIsCropperExtenderResizing]),[R,P]=d.useState({initX:0,initY:0,initHeight:0,initWidth:0,startResizeX:0,startResizeY:0,ord:"top"}),O=()=>{},A=(ee,H)=>H2(ee,H,f,n),D=(ee,H)=>H2(ee,H,m,t),B=ee=>{if(i)return;const H=ee.clientX,X=ee.clientY,W=Math.round((X-R.startResizeY)/r),le=Math.round((H-R.startResizeX)/r),pe=()=>{const Ne=R.initHeight-W,fe=R.initY+W;let xe=fe,Re=Ne;if(_===Ln.xy)xe>0&&(xe=0,Re=R.initHeight-Math.abs(R.initY));else{const Me=D(fe,Ne);xe=Me[0],Re=Me[1]}E(Re),x(xe)},$e=()=>{const Ne=R.initHeight+W;let[fe,xe]=D(R.initY,Ne);_===Ln.xy&&xe{const Ne=R.initWidth-le,fe=R.initX+le;let xe=fe,Re=Ne;if(_===Ln.xy)xe>0&&(xe=0,Re=R.initWidth-Math.abs(R.initX));else{const Me=A(fe,Ne);xe=Me[0],Re=Me[1]}S(Re),y(xe)},We=()=>{const Ne=R.initWidth+le;let[fe,xe]=A(R.initX,Ne);_===Ln.xy&&xe{b&&C(!1)};d.useEffect(()=>{if(b)return document.addEventListener("pointermove",B,cl),document.addEventListener("pointerup",V,cl),document.addEventListener("pointercancel",V,cl),()=>{document.removeEventListener("pointermove",B,cl),document.removeEventListener("pointerup",V,cl),document.removeEventListener("pointercancel",V,cl)}},[b,p,g,R]);const J=ee=>{const{ord:H}=ee.target.dataset;H&&(C(!0),P({initX:f,initY:m,initHeight:g,initWidth:p,startResizeX:ee.clientX,startResizeY:ee.clientY,ord:H}))},G=(ee,H,X)=>{const pe="w-[12px] h-[12px] z-[4] absolute content-[''] block border-2 border-primary borde pointer-events-auto hover:bg-primary";let $e="0",Ve="0",We=X,Ne="-6px";return X===""&&(Ne="50%",H==="left"||H==="right"?(We="top",Ve="-50%"):(We="left",$e="-50%")),v.jsx("div",{className:Ce(pe,ee),style:{[H]:-6,[We]:Ne,transform:`translate(${$e}, ${Ve}) scale(${1/r})`},"data-ord":H+X,"aria-label":H+X,tabIndex:-1,role:"button"})},se=()=>v.jsxs("div",{onFocus:O,onPointerDown:J,className:"absolute top-0 h-full w-full",children:[[Ln.y,Ln.xy].includes(_)?v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 w-full cursor-ns-resize h-[12px] mt-[-6px]","data-ord":"top"}),v.jsx("div",{className:"absolute pointer-events-auto bottom-0 left-0 w-full cursor-ns-resize h-[12px] mb-[-6px]","data-ord":"bottom"}),G("cursor-ns-resize","top",""),G("cursor-ns-resize","bottom","")]}):v.jsx(v.Fragment,{}),[Ln.x,Ln.xy].includes(_)?v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"absolute pointer-events-auto top-0 right-0 h-full cursor-ew-resize w-[12px] mr-[-6px]","data-ord":"right"}),v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 h-full cursor-ew-resize w-[12px] ml-[-6px]","data-ord":"left"}),G("cursor-ew-resize","left",""),G("cursor-ew-resize","right","")]}):v.jsx(v.Fragment,{}),_===Ln.xy?v.jsxs(v.Fragment,{children:[G("cursor-nw-resize","top","left"),G("cursor-ne-resize","top","right"),G("cursor-sw-resize","bottom","left"),G("cursor-se-resize","bottom","right")]}):v.jsx(v.Fragment,{})]}),U=ee=>{P({initX:f,initY:m,initHeight:g,initWidth:p,startResizeX:ee.clientX,startResizeY:ee.clientY,ord:""})},ne=()=>v.jsxs("div",{className:tx("border absolute pointer-events-auto px-2 py-1 rounded-full bg-background","origin-top-left top-0 left-0"),style:{transform:`scale(${1/r*.8})`},onPointerDown:U,children:[p," x ",g]}),M=()=>v.jsx("div",{className:Ce("outline-dashed outline-primary"),style:{height:g,width:p,outlineWidth:`${Hq/r*1.3}px`}});return o===!1||!u?null:v.jsx("div",{className:"absolute h-full w-full pointer-events-none z-[2]",children:v.jsxs("div",{className:"relative pointer-events-none z-[2] [box-shadow:0_0_0_9999px_rgba(0,_0,_0,_0.5)]",style:{height:g,width:p,left:f,top:m},children:[M(),ne(),se()]})})},Gq=200,Yq=10,Xq=200,mu=300;function Zq(e){const{file:t}=e,{toast:n}=Id(),[r,o,i,s,l,u,f,m,p,g,y,x,S,E,_,b,C,R,P,O,A,D]=bt(K=>[K.disableShortCuts,K.windowSize,K.isInpainting,K.imageWidth,K.imageHeight,K.settings,K.serverConfig.enableAutoSaving,K.setImageSize,K.setBaseBrushSize,K.interactiveSegState,K.updateInteractiveSegState,K.handleCanvasMouseDown,K.handleCanvasMouseMove,K.undo,K.redo,K.undoDisabled(),K.redoDisabled(),K.getIsProcessing(),K.updateAppState,K.runMannually(),K.runInpainting,K.isCropperExtenderResizing]),B=bt(K=>K.editorState.baseBrushSize),V=bt(K=>K.getBrushSize()),J=bt(K=>K.editorState.renders),G=bt(K=>K.editorState.extraMasks),se=bt(K=>K.editorState.temporaryMasks),U=bt(K=>K.editorState.lineGroups),ne=bt(K=>K.editorState.curLineGroup),[M,ee]=d.useState(!1),[H,X]=Px(t),[W,le]=d.useState(),[pe,$e]=d.useState(),[{x:Ve,y:We},Ne]=d.useState({x:-1,y:-1}),[fe,xe]=d.useState(!1),[Re,Me]=d.useState(!1),[Oe,ze]=d.useState(!1),[Mt,ct]=d.useState(1),[Kt,Er]=d.useState(!1),[gt,Vs]=d.useState(1),L=o.width/2,Z=o.height/2,q=d.useRef(null),[we,me]=d.useState(!1),[de,ke]=d.useState(!1),[ft,ht]=d.useState(0),_n=d.useCallback(()=>ne.length!==0,[ne]);d.useEffect(()=>{if(!pe||!X||s===0||l===0)return;const K=J.length===0?H:J[J.length-1];pe.canvas.width=s,pe.canvas.height=l,pe.clearRect(0,0,pe.canvas.width,pe.canvas.height),pe.drawImage(K,0,0,s,l)},[J,H,X,pe,l,s]),d.useEffect(()=>{!W||!X||s===0||l===0||(W.canvas.width=s,W.canvas.height=l,W.clearRect(0,0,W.canvas.width,W.canvas.height),se.forEach(K=>{W.drawImage(K,0,0,s,l)}),G.forEach(K=>{W.drawImage(K,0,0,s,l)}),g.isInteractiveSeg&&g.tmpInteractiveSegMask&&W.drawImage(g.tmpInteractiveSegMask,0,0,s,l),Yk(W,ne))},[se,G,X,g,W,ne,l,s]);const Cr=d.useCallback(async()=>{let K=t;if(J.length>0){const Ye=J[J.length-1];K=await Nu(Ye.currentSrc,t.name,t.type)}return K},[t,J]),Ni=()=>J.length!==0,Co=d.useCallback(()=>{let K=512,Ye=512;return X?(J.length===0?(K=H.naturalWidth,Ye=H.naturalHeight):J.length!==0&&(K=J[J.length-1].width,Ye=J[J.length-1].height),[K,Ye]):[K,Ye]},[H,X,J]);d.useEffect(()=>{var tf;if(!X)return;const[K,Ye]=Co();(K!==s||Ye!==l)&&m(K,Ye);const st=o.width/K,Qr=(o.height-Gq)/Ye;let an=1;(st<1||Qr<1)&&(an=Math.min(st,Qr)),Vs(an),ct(an),console.log(`[on file load] image size: ${K}x${Ye}, scale: ${an}, initialCentered: ${we}`),W!=null&&W.canvas&&(console.log("[on file load] set canvas size"),K!=W.canvas.width&&(W.canvas.width=K),Ye!=W.canvas.height&&(W.canvas.height=Ye)),we||((tf=q.current)==null||tf.centerView(an,1),console.log("[on file load] centerView"),me(!0))},[q,l,s,H,X,o,we,Co]),d.useEffect(()=>{var K;console.log("[useEffect] centerView"),(K=q==null?void 0:q.current)==null||K.centerView(gt,1)},[l,s,q,gt]);const Vn=d.useCallback(()=>{if(!gt||!o)return;const K=q.current;if(!K)return;const Ye=(o.width-s*gt)/2,st=(o.height-l*gt)/2;K.setTransform(Ye,st,gt,200,"easeOutQuad"),K.instance.transformState.scale&&(K.instance.transformState.scale=gt),ct(gt),Er(!1)},[q,o,l,s,o.height,gt]);d.useEffect(()=>(window.addEventListener("resize",()=>{Vn()}),()=>{window.removeEventListener("resize",()=>{Vn()})}),[o,Vn]),Zn("Escape",()=>{R||(de?ke(!1):Vn())},[de,i,Vn]);const Di=K=>{const Ye=K.nativeEvent;Ne({x:Ye.pageX,y:Ye.pageY})},Ws=K=>{R||g.isInteractiveSeg||Oe||de&&ne.length!==0&&S(f0(K))},Ii=async K=>{P({isPluginRunning:!0});const Ye=await Cr();try{const st=await vT(!0,Ao.InteractiveSeg,Ye,void 0,K),{blob:Qr}=st,an=new Image;an.onload=()=>{y({tmpInteractiveSegMask:an})},an.src=Qr}catch(st){n({variant:"destructive",description:st.message?st.message:st.toString()})}P({isPluginRunning:!1})},Mc=K=>{if(dC(K)){ze(!1);return}!_n()||g.isInteractiveSeg||Oe||!H.src||!(W!=null&&W.canvas)||i||de&&(O?ke(!1):A())},bg=K=>{if(g.isInteractiveSeg){const Ye=f0(K),st=[...g.clicks];uC(K)?st.push([Ye.x,Ye.y,0,st.length]):st.push([Ye.x,Ye.y,1,st.length]),Ii(st),y({clicks:st})}},Sg=K=>{if(!(R||g.isInteractiveSeg||Oe||!X||!(W!=null&&W.canvas))&&!uC(K)){if(dC(K)){ze(!0);return}ke(!0),x(f0(K))}},Jd=K=>{K.preventDefault(),E()};Zn("meta+z,ctrl+z",Jd);const Oc=K=>{K.preventDefault(),_()};Zn("shift+ctrl+z,shift+meta+z",Oc),s2("Tab",K=>{K==null||K.preventDefault(),K==null||K.stopPropagation(),Ni()&&ee(()=>(window.setTimeout(()=>{ht(100)},10),!0))},K=>{K==null||K.preventDefault(),K==null||K.stopPropagation(),Ni()&&(window.setTimeout(()=>{ht(0)},10),window.setTimeout(()=>{ee(!1)},mu))});const Nc=d.useCallback(async()=>{if(t===void 0)return;if(f&&J.length>0){try{await Hj(J[J.length-1],t.name,t.type),n({description:"Save image success"})}catch(st){n({variant:"destructive",title:"Uh oh! Something went wrong.",description:st.message?st.message:st.toString()})}return}const K=t.name.replace(/(\.[\w\d_-]+)$/i,"_cleanup$1"),Ye=J[J.length-1];if(bF(Ye.currentSrc,K),u.enableDownloadMask){let st=t.name.replace(/(\.[\w\d_-]+)$/i,"_mask$1");st=st.replace(/\.[^/.]+$/,".jpg");const Qr=Wh(s,l,U),an=document.createElement("a");an.download=st,an.href=Qr.toDataURL("image/jpeg"),an.click()}},[t,f,J,u,l,s,U]);Zn("meta+s,ctrl+s",Nc);const Dc=K=>{K!==fe&&!Oe&&!D&&xe(K)},_g=d.useCallback(()=>{if(R)return"default";if(Oe)return"grab";if(fe)return"none"},[fe,Oe,R]);Zn("[",()=>{let K=B;B>10&&(K=B-10),B<=10&&B>0&&(K=B-5),p(K)},[B]),Zn("]",()=>{p(B+10)},[B]),Zn("shift+r",()=>{O&&_n()&&A()},[O,A,_n]),Zn("ctrl+c,meta+c",async()=>{await vF()&&J.length>0&&W!=null&&W.canvas&&(await xF(W==null?void 0:W.canvas),n({title:"Copy inpainting result to clipboard"}))},[J,W]),s2(" ",K=>{r||(K==null||K.preventDefault(),K==null||K.stopPropagation(),xe(!1),ze(!0))},K=>{r||(K==null||K.preventDefault(),K==null||K.stopPropagation(),xe(!0),ze(!1))});const Ic=()=>{var Ye,st,Qr,an;let K=gt;return((st=(Ye=q.current)==null?void 0:Ye.instance)==null?void 0:st.transformState.scale)!==void 0&&(K=(an=(Qr=q.current)==null?void 0:Qr.instance)==null?void 0:an.transformState.scale),K},ef=(K,Ye)=>{const st=Ic();return{width:`${V*st}px`,height:`${V*st}px`,left:`${K}px`,top:`${Ye}px`,transform:"translate(-50%, -50%)"}},Lc=K=>v.jsx("div",{className:"absolute rounded-[50%] border-[1px] border-[solid] border-[#ffcc00] pointer-events-none bg-[#ffcc00bb]",style:K}),Eg=K=>{p(K),Re||(Me(!0),window.setTimeout(()=>{Me(!1)},1e4))},Cg=()=>v.jsx("div",{className:"absolute h-[20px] w-[20px] pointer-events-none rounded-[50%] bg-[rgba(21,_215,_121,_0.936)] [box-shadow:0_0_0_0_rgba(21,_215,_121,_0.936)] animate-pulse",style:{left:`${Ve}px`,top:`${We}px`,transform:"translate(-50%, -50%)"},children:v.jsx(dK,{})}),$g=()=>v.jsx(fq,{ref:K=>{K&&(q.current=K)},panning:{disabled:!Oe,velocityDisabled:!0},wheel:{step:.05},centerZoomedOut:!0,alignmentAnimation:{disabled:!0},centerOnInit:!0,limitToBounds:!1,doubleClick:{disabled:!0},initialScale:gt,minScale:gt*.3,onPanning:()=>{Kt||Er(!0)},onZoom:K=>{ct(K.state.scale)},children:v.jsxs(mq,{contentStyle:{visibility:we?"visible":"hidden"},children:[v.jsxs("div",{className:"grid [grid-template-areas:'editor-content'] gap-y-4",children:[v.jsx("canvas",{className:"[grid-area:editor-content]",style:{clipPath:`inset(0 ${ft}% 0 0)`,transition:`clip-path ${mu}ms`},ref:K=>{if(K&&!pe){const Ye=K.getContext("2d");Ye&&$e(Ye)}}}),v.jsx("canvas",{className:Ce("[grid-area:editor-content]",R?"pointer-events-none animate-pulse duration-600":""),style:{cursor:_g(),clipPath:`inset(0 ${ft}% 0 0)`,transition:`clip-path ${mu}ms`},onContextMenu:K=>{K.preventDefault()},onMouseOver:()=>{Dc(!0),Me(!1)},onFocus:()=>Dc(!0),onMouseLeave:()=>Dc(!1),onMouseDown:Sg,onMouseUp:bg,onMouseMove:Ws,ref:K=>{if(K&&!W){const Ye=K.getContext("2d");Ye&&le(Ye)}}}),v.jsx("div",{className:"[grid-area:editor-content] pointer-events-none grid [grid-template-areas:'original-image-content']",style:{width:`${s}px`,height:`${l}px`},children:M&&v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"[grid-area:original-image-content] z-10 bg-primary h-full w-[6px] justify-self-end",style:{marginRight:`${ft}%`,transition:`margin-right ${mu}ms`}}),v.jsx("img",{className:"[grid-area:original-image-content]",src:H.src,alt:"original",style:{width:`${s}px`,height:`${l}px`}})]})})]}),v.jsx(zq,{maxHeight:l,maxWidth:s,minHeight:Math.min(512,l),minWidth:Math.min(512,s),scale:Ic(),show:u.showCropper}),v.jsx(Kq,{minHeight:Math.min(512,l),minWidth:Math.min(512,s),scale:Ic(),show:u.showExtender}),g.isInteractiveSeg?v.jsx(Vq,{}):v.jsx(v.Fragment,{})]})});return v.jsxs("div",{className:"flex w-screen h-screen justify-center items-center","aria-hidden":"true",onMouseMove:Di,onMouseUp:Mc,children:[$g(),fe&&!i&&!Oe&&(g.isInteractiveSeg?Cg():Lc(ef(Ve,We))),Re&&Lc(ef(L,Z)),v.jsxs("div",{className:" overflow-hidden fixed flex bottom-5 border px-4 py-2 rounded-[3rem] gap-8 items-center justify-center backdrop-filter backdrop-blur-md bg-background/70",children:[v.jsx(uo,{className:"w-48",defaultValue:[50],min:Yq,max:Xq,step:1,tabIndex:-1,value:[B],onValueChange:K=>Eg(K[0]),onClick:()=>Me(!1)}),v.jsxs("div",{className:"flex gap-2",children:[v.jsx(yn,{tooltip:"Reset zoom & pan",disabled:Mt===gt&&Kt===!1,onClick:Vn,children:v.jsx(QU,{})}),v.jsx(yn,{tooltip:"Undo",onClick:Jd,disabled:b,children:v.jsx(aV,{})}),v.jsx(yn,{tooltip:"Redo",onClick:Oc,disabled:C,children:v.jsx(oV,{})}),v.jsx(yn,{tooltip:"Show original image",onPointerDown:K=>{K.preventDefault(),ee(()=>(window.setTimeout(()=>{ht(100)},10),!0))},onPointerUp:()=>{window.setTimeout(()=>{ht(0)},10),window.setTimeout(()=>{ee(!1)},mu)},disabled:J.length===0,children:v.jsx(JU,{})}),v.jsx(yn,{tooltip:"Save Image",disabled:!J.length,onClick:Nc,children:v.jsx(ZU,{})}),u.enableManualInpainting&&u.model.model_type==="inpaint"?v.jsx(yn,{tooltip:"Run Inpainting",disabled:R||!_n()&&G.length===0,onClick:()=>{A()},children:v.jsx(qU,{})}):v.jsx(v.Fragment,{})]})]})]})}const qq=()=>{const[e,t]=bt(n=>[n.imageWidth,n.imageHeight]);return!e||!t?null:v.jsxs("div",{className:"border rounded-lg px-2 py-[6px] z-10 bg-background",children:[e,"x",t]})},V1=["Enter"," "],Qq=["ArrowDown","PageUp","Home"],K3=["ArrowUp","PageDown","End"],Jq=[...Qq,...K3],eQ={ltr:[...V1,"ArrowRight"],rtl:[...V1,"ArrowLeft"]},tQ={ltr:["ArrowLeft"],rtl:["ArrowRight"]},mg="Menu",[md,nQ,rQ]=Gd(mg),[za,G3]=Mn(mg,[rQ,Fs,tg]),gg=Fs(),Y3=tg(),[X3,Us]=za(mg),[oQ,Qd]=za(mg),iQ=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:o,onOpenChange:i,modal:s=!0}=e,l=gg(t),[u,f]=d.useState(null),m=d.useRef(!1),p=Ft(i),g=Tc(o);return d.useEffect(()=>{const y=()=>{m.current=!0,document.addEventListener("pointerdown",x,{capture:!0,once:!0}),document.addEventListener("pointermove",x,{capture:!0,once:!0})},x=()=>m.current=!1;return document.addEventListener("keydown",y,{capture:!0}),()=>{document.removeEventListener("keydown",y,{capture:!0}),document.removeEventListener("pointerdown",x,{capture:!0}),document.removeEventListener("pointermove",x,{capture:!0})}},[]),d.createElement(jd,l,d.createElement(X3,{scope:t,open:n,onOpenChange:p,content:u,onContentChange:f},d.createElement(oQ,{scope:t,onClose:d.useCallback(()=>p(!1),[p]),isUsingKeyboardRef:m,dir:g,modal:s},r)))},Z3=d.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,o=gg(n);return d.createElement(Vm,Y({},o,r,{ref:t}))}),q3="MenuPortal",[sQ,Q3]=za(q3,{forceMount:void 0}),aQ=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:o}=e,i=Us(q3,t);return d.createElement(sQ,{scope:t,forceMount:n},d.createElement(Sn,{present:n||i.open},d.createElement(zd,{asChild:!0,container:o},r)))},bo="MenuContent",[lQ,tb]=za(bo),cQ=d.forwardRef((e,t)=>{const n=Q3(bo,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,i=Us(bo,e.__scopeMenu),s=Qd(bo,e.__scopeMenu);return d.createElement(md.Provider,{scope:e.__scopeMenu},d.createElement(Sn,{present:r||i.open},d.createElement(md.Slot,{scope:e.__scopeMenu},s.modal?d.createElement(uQ,Y({},o,{ref:t})):d.createElement(dQ,Y({},o,{ref:t})))))}),uQ=d.forwardRef((e,t)=>{const n=Us(bo,e.__scopeMenu),r=d.useRef(null),o=Ue(t,r);return d.useEffect(()=>{const i=r.current;if(i)return Qm(i)},[]),d.createElement(nb,Y({},e,{ref:o,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:ue(e.onFocusOutside,i=>i.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)}))}),dQ=d.forwardRef((e,t)=>{const n=Us(bo,e.__scopeMenu);return d.createElement(nb,Y({},e,{ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)}))}),nb=d.forwardRef((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:o,onOpenAutoFocus:i,onCloseAutoFocus:s,disableOutsidePointerEvents:l,onEntryFocus:u,onEscapeKeyDown:f,onPointerDownOutside:m,onFocusOutside:p,onInteractOutside:g,onDismiss:y,disableOutsideScroll:x,...S}=e,E=Us(bo,n),_=Qd(bo,n),b=gg(n),C=Y3(n),R=nQ(n),[P,O]=d.useState(null),A=d.useRef(null),D=Ue(t,A,E.onContentChange),B=d.useRef(0),V=d.useRef(""),J=d.useRef(0),G=d.useRef(null),se=d.useRef("right"),U=d.useRef(0),ne=x?qm:d.Fragment,M=x?{as:Zo,allowPinchZoom:!0}:void 0,ee=X=>{var W,le;const pe=V.current+X,$e=R().filter(Re=>!Re.disabled),Ve=document.activeElement,We=(W=$e.find(Re=>Re.ref.current===Ve))===null||W===void 0?void 0:W.textValue,Ne=$e.map(Re=>Re.textValue),fe=kQ(Ne,pe,We),xe=(le=$e.find(Re=>Re.textValue===fe))===null||le===void 0?void 0:le.ref.current;(function Re(Me){V.current=Me,window.clearTimeout(B.current),Me!==""&&(B.current=window.setTimeout(()=>Re(""),1e3))})(pe),xe&&setTimeout(()=>xe.focus())};d.useEffect(()=>()=>window.clearTimeout(B.current),[]),Xm();const H=d.useCallback(X=>{var W,le;return se.current===((W=G.current)===null||W===void 0?void 0:W.side)&&PQ(X,(le=G.current)===null||le===void 0?void 0:le.area)},[]);return d.createElement(lQ,{scope:n,searchRef:V,onItemEnter:d.useCallback(X=>{H(X)&&X.preventDefault()},[H]),onItemLeave:d.useCallback(X=>{var W;H(X)||((W=A.current)===null||W===void 0||W.focus(),O(null))},[H]),onTriggerLeave:d.useCallback(X=>{H(X)&&X.preventDefault()},[H]),pointerGraceTimerRef:J,onPointerGraceIntentChange:d.useCallback(X=>{G.current=X},[])},d.createElement(ne,M,d.createElement(Ym,{asChild:!0,trapped:o,onMountAutoFocus:ue(i,X=>{var W;X.preventDefault(),(W=A.current)===null||W===void 0||W.focus()}),onUnmountAutoFocus:s},d.createElement(Ec,{asChild:!0,disableOutsidePointerEvents:l,onEscapeKeyDown:f,onPointerDownOutside:m,onFocusOutside:p,onInteractOutside:g,onDismiss:y},d.createElement(QP,Y({asChild:!0},C,{dir:_.dir,orientation:"vertical",loop:r,currentTabStopId:P,onCurrentTabStopIdChange:O,onEntryFocus:ue(u,X=>{_.isUsingKeyboardRef.current||X.preventDefault()})}),d.createElement(Wm,Y({role:"menu","aria-orientation":"vertical","data-state":oA(E.open),"data-radix-menu-content":"",dir:_.dir},b,S,{ref:D,style:{outline:"none",...S.style},onKeyDown:ue(S.onKeyDown,X=>{const le=X.target.closest("[data-radix-menu-content]")===X.currentTarget,pe=X.ctrlKey||X.altKey||X.metaKey,$e=X.key.length===1;le&&(X.key==="Tab"&&X.preventDefault(),!pe&&$e&&ee(X.key));const Ve=A.current;if(X.target!==Ve||!Jq.includes(X.key))return;X.preventDefault();const Ne=R().filter(fe=>!fe.disabled).map(fe=>fe.ref.current);K3.includes(X.key)&&Ne.reverse(),$Q(Ne)}),onBlur:ue(e.onBlur,X=>{X.currentTarget.contains(X.target)||(window.clearTimeout(B.current),V.current="")}),onPointerMove:ue(e.onPointerMove,gd(X=>{const W=X.target,le=U.current!==X.clientX;if(X.currentTarget.contains(W)&&le){const pe=X.clientX>U.current?"right":"left";se.current=pe,U.current=X.clientX}}))})))))))}),fQ=d.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return d.createElement(Ae.div,Y({},r,{ref:t}))}),W1="MenuItem",K2="menu.itemSelect",rb=d.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...o}=e,i=d.useRef(null),s=Qd(W1,e.__scopeMenu),l=tb(W1,e.__scopeMenu),u=Ue(t,i),f=d.useRef(!1),m=()=>{const p=i.current;if(!n&&p){const g=new CustomEvent(K2,{bubbles:!0,cancelable:!0});p.addEventListener(K2,y=>r==null?void 0:r(y),{once:!0}),dx(p,g),g.defaultPrevented?f.current=!1:s.onClose()}};return d.createElement(J3,Y({},o,{ref:u,disabled:n,onClick:ue(e.onClick,m),onPointerDown:p=>{var g;(g=e.onPointerDown)===null||g===void 0||g.call(e,p),f.current=!0},onPointerUp:ue(e.onPointerUp,p=>{var g;f.current||(g=p.currentTarget)===null||g===void 0||g.click()}),onKeyDown:ue(e.onKeyDown,p=>{const g=l.searchRef.current!=="";n||g&&p.key===" "||V1.includes(p.key)&&(p.currentTarget.click(),p.preventDefault())})}))}),J3=d.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:o,...i}=e,s=tb(W1,n),l=Y3(n),u=d.useRef(null),f=Ue(t,u),[m,p]=d.useState(!1),[g,y]=d.useState("");return d.useEffect(()=>{const x=u.current;if(x){var S;y(((S=x.textContent)!==null&&S!==void 0?S:"").trim())}},[i.children]),d.createElement(md.ItemSlot,{scope:n,disabled:r,textValue:o??g},d.createElement(JP,Y({asChild:!0},l,{focusable:!r}),d.createElement(Ae.div,Y({role:"menuitem","data-highlighted":m?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0},i,{ref:f,onPointerMove:ue(e.onPointerMove,gd(x=>{r?s.onItemLeave(x):(s.onItemEnter(x),x.defaultPrevented||x.currentTarget.focus())})),onPointerLeave:ue(e.onPointerLeave,gd(x=>s.onItemLeave(x))),onFocus:ue(e.onFocus,()=>p(!0)),onBlur:ue(e.onBlur,()=>p(!1))}))))}),hQ=d.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...o}=e;return d.createElement(tA,{scope:e.__scopeMenu,checked:n},d.createElement(rb,Y({role:"menuitemcheckbox","aria-checked":am(n)?"mixed":n},o,{ref:t,"data-state":ob(n),onSelect:ue(o.onSelect,()=>r==null?void 0:r(am(n)?!0:!n),{checkForDefaultPrevented:!1})})))}),pQ="MenuRadioGroup",[$te,mQ]=za(pQ,{value:void 0,onValueChange:()=>{}}),gQ="MenuRadioItem",vQ=d.forwardRef((e,t)=>{const{value:n,...r}=e,o=mQ(gQ,e.__scopeMenu),i=n===o.value;return d.createElement(tA,{scope:e.__scopeMenu,checked:i},d.createElement(rb,Y({role:"menuitemradio","aria-checked":i},r,{ref:t,"data-state":ob(i),onSelect:ue(r.onSelect,()=>{var s;return(s=o.onValueChange)===null||s===void 0?void 0:s.call(o,n)},{checkForDefaultPrevented:!1})})))}),eA="MenuItemIndicator",[tA,yQ]=za(eA,{checked:!1}),wQ=d.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...o}=e,i=yQ(eA,n);return d.createElement(Sn,{present:r||am(i.checked)||i.checked===!0},d.createElement(Ae.span,Y({},o,{ref:t,"data-state":ob(i.checked)})))}),xQ=d.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return d.createElement(Ae.div,Y({role:"separator","aria-orientation":"horizontal"},r,{ref:t}))}),nA="MenuSub",[bQ,rA]=za(nA),SQ=e=>{const{__scopeMenu:t,children:n,open:r=!1,onOpenChange:o}=e,i=Us(nA,t),s=gg(t),[l,u]=d.useState(null),[f,m]=d.useState(null),p=Ft(o);return d.useEffect(()=>(i.open===!1&&p(!1),()=>p(!1)),[i.open,p]),d.createElement(jd,s,d.createElement(X3,{scope:t,open:r,onOpenChange:p,content:f,onContentChange:m},d.createElement(bQ,{scope:t,contentId:nr(),triggerId:nr(),trigger:l,onTriggerChange:u},n)))},_h="MenuSubTrigger",_Q=d.forwardRef((e,t)=>{const n=Us(_h,e.__scopeMenu),r=Qd(_h,e.__scopeMenu),o=rA(_h,e.__scopeMenu),i=tb(_h,e.__scopeMenu),s=d.useRef(null),{pointerGraceTimerRef:l,onPointerGraceIntentChange:u}=i,f={__scopeMenu:e.__scopeMenu},m=d.useCallback(()=>{s.current&&window.clearTimeout(s.current),s.current=null},[]);return d.useEffect(()=>m,[m]),d.useEffect(()=>{const p=l.current;return()=>{window.clearTimeout(p),u(null)}},[l,u]),d.createElement(Z3,Y({asChild:!0},f),d.createElement(J3,Y({id:o.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":o.contentId,"data-state":oA(n.open)},e,{ref:Nm(t,o.onTriggerChange),onClick:p=>{var g;(g=e.onClick)===null||g===void 0||g.call(e,p),!(e.disabled||p.defaultPrevented)&&(p.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:ue(e.onPointerMove,gd(p=>{i.onItemEnter(p),!p.defaultPrevented&&!e.disabled&&!n.open&&!s.current&&(i.onPointerGraceIntentChange(null),s.current=window.setTimeout(()=>{n.onOpenChange(!0),m()},100))})),onPointerLeave:ue(e.onPointerLeave,gd(p=>{var g;m();const y=(g=n.content)===null||g===void 0?void 0:g.getBoundingClientRect();if(y){var x;const S=(x=n.content)===null||x===void 0?void 0:x.dataset.side,E=S==="right",_=E?-5:5,b=y[E?"left":"right"],C=y[E?"right":"left"];i.onPointerGraceIntentChange({area:[{x:p.clientX+_,y:p.clientY},{x:b,y:y.top},{x:C,y:y.top},{x:C,y:y.bottom},{x:b,y:y.bottom}],side:S}),window.clearTimeout(l.current),l.current=window.setTimeout(()=>i.onPointerGraceIntentChange(null),300)}else{if(i.onTriggerLeave(p),p.defaultPrevented)return;i.onPointerGraceIntentChange(null)}})),onKeyDown:ue(e.onKeyDown,p=>{const g=i.searchRef.current!=="";if(!(e.disabled||g&&p.key===" ")&&eQ[r.dir].includes(p.key)){var y;n.onOpenChange(!0),(y=n.content)===null||y===void 0||y.focus(),p.preventDefault()}})})))}),EQ="MenuSubContent",CQ=d.forwardRef((e,t)=>{const n=Q3(bo,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,i=Us(bo,e.__scopeMenu),s=Qd(bo,e.__scopeMenu),l=rA(EQ,e.__scopeMenu),u=d.useRef(null),f=Ue(t,u);return d.createElement(md.Provider,{scope:e.__scopeMenu},d.createElement(Sn,{present:r||i.open},d.createElement(md.Slot,{scope:e.__scopeMenu},d.createElement(nb,Y({id:l.contentId,"aria-labelledby":l.triggerId},o,{ref:f,align:"start",side:s.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:m=>{var p;s.isUsingKeyboardRef.current&&((p=u.current)===null||p===void 0||p.focus()),m.preventDefault()},onCloseAutoFocus:m=>m.preventDefault(),onFocusOutside:ue(e.onFocusOutside,m=>{m.target!==l.trigger&&i.onOpenChange(!1)}),onEscapeKeyDown:ue(e.onEscapeKeyDown,m=>{s.onClose(),m.preventDefault()}),onKeyDown:ue(e.onKeyDown,m=>{const p=m.currentTarget.contains(m.target),g=tQ[s.dir].includes(m.key);if(p&&g){var y;i.onOpenChange(!1),(y=l.trigger)===null||y===void 0||y.focus(),m.preventDefault()}})})))))});function oA(e){return e?"open":"closed"}function am(e){return e==="indeterminate"}function ob(e){return am(e)?"indeterminate":e?"checked":"unchecked"}function $Q(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function RQ(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function kQ(e,t,n){const o=t.length>1&&Array.from(t).every(f=>f===t[0])?t[0]:t,i=n?e.indexOf(n):-1;let s=RQ(e,Math.max(i,0));o.length===1&&(s=s.filter(f=>f!==n));const u=s.find(f=>f.toLowerCase().startsWith(o.toLowerCase()));return u!==n?u:void 0}function TQ(e,t){const{x:n,y:r}=e;let o=!1;for(let i=0,s=t.length-1;ir!=m>r&&n<(f-l)*(r-u)/(m-u)+l&&(o=!o)}return o}function PQ(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return TQ(n,t)}function gd(e){return t=>t.pointerType==="mouse"?e(t):void 0}const AQ=iQ,MQ=Z3,OQ=aQ,NQ=cQ,DQ=fQ,IQ=rb,LQ=hQ,FQ=vQ,jQ=wQ,zQ=xQ,BQ=SQ,UQ=_Q,VQ=CQ,iA="DropdownMenu",[WQ,Rte]=Mn(iA,[G3]),_r=G3(),[HQ,sA]=WQ(iA),KQ=e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:o,defaultOpen:i,onOpenChange:s,modal:l=!0}=e,u=_r(t),f=d.useRef(null),[m=!1,p]=Zr({prop:o,defaultProp:i,onChange:s});return d.createElement(HQ,{scope:t,triggerId:nr(),triggerRef:f,contentId:nr(),open:m,onOpenChange:p,onOpenToggle:d.useCallback(()=>p(g=>!g),[p]),modal:l},d.createElement(AQ,Y({},u,{open:m,onOpenChange:p,dir:r,modal:l}),n))},GQ="DropdownMenuTrigger",YQ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...o}=e,i=sA(GQ,n),s=_r(n);return d.createElement(MQ,Y({asChild:!0},s),d.createElement(Ae.button,Y({type:"button",id:i.triggerId,"aria-haspopup":"menu","aria-expanded":i.open,"aria-controls":i.open?i.contentId:void 0,"data-state":i.open?"open":"closed","data-disabled":r?"":void 0,disabled:r},o,{ref:Nm(t,i.triggerRef),onPointerDown:ue(e.onPointerDown,l=>{!r&&l.button===0&&l.ctrlKey===!1&&(i.onOpenToggle(),i.open||l.preventDefault())}),onKeyDown:ue(e.onKeyDown,l=>{r||(["Enter"," "].includes(l.key)&&i.onOpenToggle(),l.key==="ArrowDown"&&i.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(l.key)&&l.preventDefault())})})))}),XQ=e=>{const{__scopeDropdownMenu:t,...n}=e,r=_r(t);return d.createElement(OQ,Y({},r,n))},ZQ="DropdownMenuContent",qQ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=sA(ZQ,n),i=_r(n),s=d.useRef(!1);return d.createElement(NQ,Y({id:o.contentId,"aria-labelledby":o.triggerId},i,r,{ref:t,onCloseAutoFocus:ue(e.onCloseAutoFocus,l=>{var u;s.current||(u=o.triggerRef.current)===null||u===void 0||u.focus(),s.current=!1,l.preventDefault()}),onInteractOutside:ue(e.onInteractOutside,l=>{const u=l.detail.originalEvent,f=u.button===0&&u.ctrlKey===!0,m=u.button===2||f;(!o.modal||m)&&(s.current=!0)}),style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}}))}),QQ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(DQ,Y({},o,r,{ref:t}))}),JQ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(IQ,Y({},o,r,{ref:t}))}),eJ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(LQ,Y({},o,r,{ref:t}))}),tJ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(FQ,Y({},o,r,{ref:t}))}),nJ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(jQ,Y({},o,r,{ref:t}))}),rJ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(zQ,Y({},o,r,{ref:t}))}),oJ=e=>{const{__scopeDropdownMenu:t,children:n,open:r,onOpenChange:o,defaultOpen:i}=e,s=_r(t),[l=!1,u]=Zr({prop:r,defaultProp:i,onChange:o});return d.createElement(BQ,Y({},s,{open:l,onOpenChange:u}),n)},iJ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(UQ,Y({},o,r,{ref:t}))}),sJ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(VQ,Y({},o,r,{ref:t,style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}}))}),aJ=KQ,lJ=YQ,cJ=XQ,aA=qQ,lA=QQ,cA=JQ,uA=eJ,dA=tJ,fA=nJ,hA=rJ,uJ=oJ,pA=iJ,mA=sJ,dJ=aJ,fJ=lJ,G2=uJ,H1=d.forwardRef(({className:e,inset:t,children:n,...r},o)=>v.jsxs(pA,{ref:o,className:Ce("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",e),...r,children:[n,v.jsx(tz,{className:"ml-auto h-4 w-4"})]}));H1.displayName=pA.displayName;const K1=d.forwardRef(({className:e,...t},n)=>v.jsx(mA,{ref:n,className:Ce("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...t}));K1.displayName=mA.displayName;const gA=d.forwardRef(({className:e,sideOffset:t=4,...n},r)=>v.jsx(cJ,{children:v.jsx(aA,{ref:r,sideOffset:t,className:Ce("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md","data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),onCloseAutoFocus:o=>o.preventDefault(),...n})}));gA.displayName=aA.displayName;const fl=d.forwardRef(({className:e,inset:t,...n},r)=>v.jsx(cA,{ref:r,className:Ce("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",e),...n}));fl.displayName=cA.displayName;const hJ=d.forwardRef(({className:e,children:t,checked:n,...r},o)=>v.jsxs(uA,{ref:o,className:Ce("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),checked:n,...r,children:[v.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:v.jsx(fA,{children:v.jsx(yT,{className:"h-4 w-4"})})}),t]}));hJ.displayName=uA.displayName;const pJ=d.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(dA,{ref:r,className:Ce("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[v.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:v.jsx(fA,{children:v.jsx(sz,{className:"h-4 w-4 fill-current"})})}),t]}));pJ.displayName=dA.displayName;const mJ=d.forwardRef(({className:e,inset:t,...n},r)=>v.jsx(lA,{ref:r,className:Ce("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",e),...n}));mJ.displayName=lA.displayName;const gJ=d.forwardRef(({className:e,...t},n)=>v.jsx(hA,{ref:n,className:Ce("-mx-1 my-1 h-px bg-muted",e),...t}));gJ.displayName=hA.displayName;const Y2={RemoveBG:{IconClass:HC,showName:"RemoveBG"},AnimeSeg:{IconClass:HC,showName:"Anime Segmentation"},RealESRGAN:{IconClass:ZT,showName:"RealESRGAN"},GFPGAN:{IconClass:KC,showName:"GFPGAN"},RestoreFormer:{IconClass:KC,showName:"RestoreFormer"},InteractiveSeg:{IconClass:rV,showName:"Interactive Segmentation"}},vJ=()=>{const[e,t,n,r]=bt(f=>[f.file,f.serverConfig.plugins,f.updateInteractiveSegState,f.runRenderablePlugin]),o=!e;if(t.length===0)return null;const i=(f,m)=>{m==="InteractiveSeg"?n({isInteractiveSeg:!0}):r(f,m)},s=()=>v.jsxs(G2,{children:[v.jsx(H1,{disabled:o,children:v.jsxs("div",{className:"flex gap-2 items-center",children:[v.jsx(ZT,{}),"RealESRGAN"]})}),v.jsxs(K1,{children:[v.jsx(fl,{onClick:()=>r(!1,"RealESRGAN",{upscale:2}),children:"upscale 2x"}),v.jsx(fl,{onClick:()=>r(!1,"RealESRGAN",{upscale:4}),children:"upscale 4x"})]})]},"RealESRGAN"),l=f=>{const{IconClass:m,showName:p}=Y2[f.name];return v.jsxs(G2,{children:[v.jsx(H1,{disabled:o,children:v.jsxs("div",{className:"flex gap-2 items-center",children:[v.jsx(m,{className:"p-1"}),p]})}),v.jsxs(K1,{children:[v.jsx(fl,{onClick:()=>i(!1,f.name),children:"Remove Background"}),v.jsx(fl,{onClick:()=>i(!0,f.name),children:"Generate Mask"})]})]},f.name)},u=()=>t.map(f=>{const{IconClass:m,showName:p}=Y2[f.name];return f.name==="RealESRGAN"?s():f.name==="RemoveBG"||f.name==="AnimeSeg"?l(f):v.jsx(fl,{onClick:()=>i(!1,f.name),disabled:o,children:v.jsxs("div",{className:"flex gap-2 items-center",children:[v.jsx(m,{className:"p-1"}),p]})},f.name)});return v.jsxs(dJ,{modal:!1,children:[v.jsx(fJ,{className:"border rounded-lg z-10 bg-background outline-none",tabIndex:-1,children:v.jsx(wn,{variant:"ghost",size:"icon",asChild:!0,className:"p-1.5",children:v.jsx(KU,{strokeWidth:1})})}),v.jsx(gA,{side:"bottom",align:"start",children:u()})]})},yJ=Cx,wJ=yP,xJ=$x,vA=d.forwardRef(({className:e,...t},n)=>v.jsx(Bd,{className:Ce("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t,ref:n}));vA.displayName=Bd.displayName;const bJ=Dm("fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=closed]:duration-200 data-[state=open]:duration-300",{variants:{side:{top:"inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",bottom:"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",left:"inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",right:"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm"}},defaultVariants:{side:"right"}}),yA=d.forwardRef(({side:e="right",className:t,children:n,...r},o)=>v.jsxs(xJ,{children:[v.jsx(vA,{}),v.jsx(Ud,{ref:o,className:Ce(bJ({side:e}),t),...r,children:n})]}));yA.displayName=Ud.displayName;const wA=({className:e,...t})=>v.jsx("div",{className:Ce("flex flex-col space-y-2 text-center sm:text-left",e),...t});wA.displayName="SheetHeader";const SJ=d.forwardRef(({className:e,...t},n)=>v.jsx(Vd,{ref:n,className:Ce("text-lg font-semibold text-foreground",e),...t}));SJ.displayName=Vd.displayName;const _J=d.forwardRef(({className:e,...t},n)=>v.jsx(Wd,{ref:n,className:Ce("text-sm text-muted-foreground",e),...t}));_J.displayName=Wd.displayName;const Ut=({children:e})=>v.jsx("div",{className:"flex justify-between items-center pr-2",children:e}),Pt=({text:e,toolTip:t="",url:n,htmlFor:r,disabled:o=!1})=>v.jsxs(YT,{children:[v.jsx(XT,{asChild:!0,children:v.jsx(Zx,{htmlFor:r||e.toLowerCase().replace(" ","-"),className:"font-medium",disabled:o,children:e})}),t||n?v.jsxs(Sx,{className:"flex flex-col max-w-xs text-sm",side:"left",children:[v.jsx("p",{children:t}),n?v.jsx(wn,{variant:"link",className:"justify-end",children:v.jsx("a",{href:n,target:"_blank",children:"More info"})}):v.jsx(v.Fragment,{})]}):v.jsx(v.Fragment,{})]}),EJ=()=>{const[e,t]=bt(n=>[n.settings,n.updateSettings]);return v.jsxs("div",{className:"flex flex-col gap-4 mt-4",children:[v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{htmlFor:"steps",text:"Steps",toolTip:"The number of denoising steps. More denoising steps usually lead to a higher quality image at the expense of slower inference."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[30],min:1,max:100,step:1,value:[Math.floor(e.ldmSteps)],onValueChange:n=>t({ldmSteps:n[0]})}),v.jsx(Yn,{id:"steps",className:"w-[60px] rounded-full",numberValue:e.ldmSteps,allowFloat:!1,onNumberValueChange:n=>{t({ldmSteps:n})}})]})]}),v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Sampler"}),v.jsxs(Uo,{value:e.ldmSampler,onValueChange:n=>{t({ldmSampler:n})},children:[v.jsx(go,{className:"w-[100px]",children:v.jsx(Vo,{placeholder:"Select sampler"})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:Object.values(Qw).map(n=>v.jsx(yo,{value:n,children:n},n))})})]})]})]})},xA=d.forwardRef(({className:e,...t},n)=>v.jsx("textarea",{className:Ce("flex min-h-[60px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",e,"overflow-auto"),tabIndex:-1,ref:n,...t}));xA.displayName="Textarea";const Eh=({text:e,onClick:t})=>{const[n]=bt(r=>[r.settings.showExtender]);return v.jsx(wn,{variant:"outline",className:"p-1 h-8",disabled:!n,onClick:t,children:v.jsx("div",{className:"flex items-center gap-1",children:e})})},CJ=()=>{const[e,t,n,r,o,i,s,l,u,f,m]=bt(M=>[M.serverConfig.samplers,M.settings,M.paintByExampleFile,M.getIsProcessing(),M.updateSettings,M.runInpainting,M.updateAppState,M.updateExtenderByBuiltIn,M.updateExtenderDirection,M.adjustMask,M.clearMask]),[p,g]=Px(n),y=d.useRef(null);NP(y,()=>{y!=null&&y.current&&y.current.blur()});const x=M=>{M.key==="Enter"&&M.ctrlKey&&t.prompt.length!==0&&i()},S=()=>v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Cropper",toolTip:"Inpainting on part of image, improve inference speed and reduce memory usage."}),v.jsx(co,{id:"cropper",checked:t.showCropper,onCheckedChange:M=>{o({showCropper:M}),M&&o({showExtender:!1})}})]}),E=()=>t.model.support_controlnet?v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex justify-between items-center pr-2",children:[v.jsx(Pt,{text:"ControlNet",toolTip:"Using an additional conditioning image to control how an image is generated",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#controlnet"}),v.jsx(co,{id:"controlnet",checked:t.enableControlnet,onCheckedChange:M=>{o({enableControlnet:M})}})]}),v.jsx("div",{className:"flex flex-col gap-1",children:v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[100],min:1,max:100,step:1,disabled:!t.enableControlnet,value:[Math.floor(t.controlnetConditioningScale*100)],onValueChange:M=>o({controlnetConditioningScale:M[0]/100})}),v.jsx(Yn,{id:"controlnet-weight",className:"w-[60px] rounded-full",disabled:!t.enableControlnet,numberValue:t.controlnetConditioningScale,allowFloat:!1,onNumberValueChange:M=>{o({controlnetConditioningScale:M})}})]})}),v.jsx("div",{className:"pr-2",children:v.jsxs(Uo,{defaultValue:t.controlnetMethod,value:t.controlnetMethod,onValueChange:M=>{o({controlnetMethod:M})},disabled:!t.enableControlnet,children:[v.jsx(go,{children:v.jsx(Vo,{placeholder:"Select control method"})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:Object.values(t.model.controlnets).map(M=>v.jsx(yo,{value:M,children:M.split("/")[1]},M))})})]})})]}),v.jsx(gn,{})]}):null,_=()=>t.model.support_lcm_lora?v.jsxs(v.Fragment,{children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"LCM LoRA",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inference_with_lcm_lora",toolTip:"Enable quality image generation in typically 2-4 steps. Suggest disabling guidance_scale by setting it to 0. You can also try values between 1.0 and 2.0. When LCM Lora is enabled, LCMSampler will be used automatically."}),v.jsx(co,{id:"lcm-lora",checked:t.enableLCMLora,onCheckedChange:M=>{o({enableLCMLora:M})}})]}),v.jsx(gn,{})]}):null,b=()=>t.model.support_freeu?v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex justify-between items-center pr-2",children:[v.jsx(Pt,{text:"FreeU",toolTip:"FreeU is a technique for improving image quality. Different models may require different FreeU-specific hyperparameters, which can be viewed in the more info section.",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/freeu"}),v.jsx(co,{id:"freeu",checked:t.enableFreeu,onCheckedChange:M=>{o({enableFreeu:M})}})]}),v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex justify-center gap-6",children:[v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-s1",text:"s1",disabled:!t.enableFreeu}),v.jsx(Yn,{id:"freeu-s1",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.s1,allowFloat:!0,onNumberValueChange:M=>{o({freeuConfig:{...t.freeuConfig,s1:M}})}})]}),v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-s2",text:"s2",disabled:!t.enableFreeu}),v.jsx(Yn,{id:"freeu-s2",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.s2,allowFloat:!0,onNumberValueChange:M=>{o({freeuConfig:{...t.freeuConfig,s2:M}})}})]})]}),v.jsxs("div",{className:"flex justify-center gap-6",children:[v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-b1",text:"b1",disabled:!t.enableFreeu}),v.jsx(Yn,{id:"freeu-b1",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.b1,allowFloat:!0,onNumberValueChange:M=>{o({freeuConfig:{...t.freeuConfig,b1:M}})}})]}),v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-b2",text:"b2",disabled:!t.enableFreeu}),v.jsx(Yn,{id:"freeu-b2",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.b2,allowFloat:!0,onNumberValueChange:M=>{o({freeuConfig:{...t.freeuConfig,b2:M}})}})]})]})]}),v.jsx(gn,{})]}):null,C=()=>t.model.need_prompt?v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsx(Pt,{text:"Negative prompt",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#negative-prompt",toolTip:"Negative prompt guides the model away from generating certain things in an image"}),v.jsx("div",{className:"pl-2 pr-4",children:v.jsx(xA,{ref:y,rows:4,onKeyUp:x,className:"max-h-[8rem] overflow-y-auto mb-2",placeholder:"",id:"negative-prompt",value:t.negativePrompt,onInput:M=>{M.preventDefault(),M.stopPropagation();const ee=M.target;o({negativePrompt:ee.value})}})})]}):null,R=()=>t.model.name!==Gk?null:v.jsxs("div",{children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Example Image",toolTip:"An example image to guide image generation."}),v.jsx(f1,{tooltip:"Upload example image",onFileUpload:M=>{s({paintByExampleFile:M})},children:v.jsx(qT,{})})]}),g?v.jsx("div",{className:"flex justify-center items-center",children:v.jsx("img",{src:p.src,alt:"example",className:"max-w-[200px] max-h-[200px] m-3"})}):v.jsx(v.Fragment,{}),v.jsx(wn,{variant:"default",className:"w-full",disabled:r||!g,onClick:()=>{i()},children:"Paint"})]}),P=()=>t.model.name!==uF?null:v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Image guidance scale",toolTip:"Push the generated image towards the inital image. Higher image guidance scale encourages generated images that are closely linked to the source image, usually at the expense of lower image quality.",url:"https://huggingface.co/docs/diffusers/main/en/api/pipelines/pix2pix"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[150],min:100,max:1e3,step:1,value:[Math.floor(t.p2pImageGuidanceScale*100)],onValueChange:M=>o({p2pImageGuidanceScale:M[0]/100})}),v.jsx(Yn,{id:"image-guidance-scale",className:"w-[60px] rounded-full",numberValue:t.p2pImageGuidanceScale,allowFloat:!0,onNumberValueChange:M=>{o({p2pImageGuidanceScale:M})}})]})]}),O=()=>t.model.support_strength?v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Strength",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#strength",toolTip:"Strength is a measure of how much noise is added to the base image, which influences how similar the output is to the base image. Higher value means more noise and more different from the base image"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[100],min:10,max:100,step:1,value:[Math.floor(t.sdStrength*100)],onValueChange:M=>o({sdStrength:M[0]/100})}),v.jsx(Yn,{id:"strength",className:"w-[60px] rounded-full",numberValue:t.sdStrength,allowFloat:!0,onNumberValueChange:M=>{o({sdStrength:M})}})]})]}):null,A=()=>t.model.support_outpainting?v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Extender",toolTip:"Perform outpainting on images to expand it's content."}),v.jsx(co,{id:"extender",checked:t.showExtender,onCheckedChange:M=>{o({showExtender:M}),M&&o({showCropper:!1})}})]}),v.jsxs(Ut,{children:[v.jsxs(Uo,{defaultValue:t.extenderDirection,value:t.extenderDirection,onValueChange:M=>{u(M)},children:[v.jsx(go,{className:"w-[65px] h-7",disabled:!t.showExtender,children:v.jsx(Vo,{placeholder:"Select axis"})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:Object.values(Ln).map(M=>v.jsx(yo,{value:M,children:M},M))})})]}),v.jsxs("div",{className:"flex gap-1 justify-center mt-0",children:[v.jsx(Eh,{text:"1.25x",onClick:()=>l(t.extenderDirection,1.25)}),v.jsx(Eh,{text:"1.5x",onClick:()=>l(t.extenderDirection,1.5)}),v.jsx(Eh,{text:"1.75x",onClick:()=>l(t.extenderDirection,1.75)}),v.jsx(Eh,{text:"2.0x",onClick:()=>l(t.extenderDirection,2)})]})]})]}),v.jsx(gn,{})]}):null,D=()=>t.model.name!==dF?null:v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Task",toolTip:"PowerPaint task. When using extender, image-outpainting task will be auto used. For object-removal and image-outpainting, it is recommended to set the guidance_scale at 10 or above."}),v.jsxs(Uo,{defaultValue:t.powerpaintTask,value:t.powerpaintTask,onValueChange:M=>{o({powerpaintTask:M})},disabled:t.showExtender,children:[v.jsx(go,{className:"w-[140px]",children:v.jsx(Vo,{placeholder:"Select task"})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:[Ol.text_guided,Ol.object_remove,Ol.shape_guided].map(M=>v.jsx(yo,{value:M,children:M},M))})})]})]}),B=()=>v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{htmlFor:"steps",text:"Steps",toolTip:"The number of denoising steps. More denoising steps usually lead to a higher quality image at the expense of slower inference."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[30],min:1,max:100,step:1,value:[Math.floor(t.sdSteps)],onValueChange:M=>o({sdSteps:M[0]})}),v.jsx(Yn,{id:"steps",className:"w-[60px] rounded-full",numberValue:t.sdSteps,allowFloat:!1,onNumberValueChange:M=>{o({sdSteps:M})}})]})]}),V=()=>v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Guidance scale",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#guidance-scale",toolTip:"Guidance scale affects how aligned the text prompt and generated image are. Higher value means the prompt and generated image are closely aligned, so the output is a stricter interpretation of the prompt"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[750],min:0,max:1500,step:1,value:[Math.floor(t.sdGuidanceScale*100)],onValueChange:M=>o({sdGuidanceScale:M[0]/100})}),v.jsx(Yn,{id:"guidance-scale",className:"w-[60px] rounded-full",numberValue:t.sdGuidanceScale,allowFloat:!0,onNumberValueChange:M=>{o({sdGuidanceScale:M})}})]})]}),J=()=>t.model.name===fF?null:v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Sampler"}),v.jsxs(Uo,{defaultValue:t.sdSampler,value:t.sdSampler,onValueChange:M=>{o({sdSampler:M})},children:[v.jsx(go,{className:"w-[175px] text-xs",children:v.jsx(Vo,{placeholder:"Select sampler"})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:e.map(M=>v.jsx(yo,{value:M,className:"text-xs",children:M},M))})})]})]}),G=()=>v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Seed",toolTip:"Using same parameters and a fixed seed can generate same result image."}),v.jsxs("div",{className:"flex gap-2 justify-center items-center",children:[v.jsx(co,{id:"seed",checked:t.seedFixed,onCheckedChange:M=>{o({seedFixed:M})}}),v.jsx(Yn,{id:"seed",className:"w-[100px]",disabled:!t.seedFixed,numberValue:t.seed,allowFloat:!1,onNumberValueChange:M=>{o({seed:M})}})]})]}),se=()=>v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Mask blur",toolTip:"How much to blur the mask before processing, in pixels. Make the generated inpainting boundaries appear more natural."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[t.sdMaskBlur],min:0,max:96,step:1,value:[Math.floor(t.sdMaskBlur)],onValueChange:M=>o({sdMaskBlur:M[0]})}),v.jsx(Yn,{id:"mask-blur",className:"w-[60px] rounded-full",numberValue:t.sdMaskBlur,allowFloat:!1,onNumberValueChange:M=>{o({sdMaskBlur:M})}})]})]}),U=()=>v.jsxs(v.Fragment,{children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Match histograms",toolTip:"Match the inpainting result histogram to the source image histogram",url:"https://github.com/Sanster/lama-cleaner/pull/143#issuecomment-1325859307"}),v.jsx(co,{id:"match-histograms",checked:t.sdMatchHistograms,onCheckedChange:M=>{o({sdMatchHistograms:M})}})]}),v.jsx(gn,{})]}),ne=()=>v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{htmlFor:"adjustMaskKernelSize",text:"Adjust Mask",toolTip:"Expand or shrink mask. Using the slider to adjust the kernel size for dilation or erosion."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[12],min:1,max:100,step:1,value:[Math.floor(t.adjustMaskKernelSize)],onValueChange:M=>o({adjustMaskKernelSize:M[0]})}),v.jsx(Yn,{id:"adjustMaskKernelSize",className:"w-[60px] rounded-full",numberValue:t.adjustMaskKernelSize,allowFloat:!1,onNumberValueChange:M=>{o({adjustMaskKernelSize:M})}})]}),v.jsxs(Ut,{children:[v.jsxs("div",{className:"flex gap-1 justify-start",children:[v.jsx(wn,{variant:"outline",className:"p-1 h-8",onClick:()=>f("expand"),disabled:r,children:v.jsx("div",{className:"flex items-center gap-1 select-none",children:"expand"})}),v.jsx(wn,{variant:"outline",className:"p-1 h-8",onClick:()=>f("shrink"),disabled:r,children:v.jsx("div",{className:"flex items-center gap-1 select-none",children:"Shrink"})}),v.jsx(wn,{variant:"outline",className:"p-1 h-8",onClick:()=>f("reverse"),disabled:r,children:v.jsx("div",{className:"flex items-center gap-1 select-none",children:"Reverse"})})]}),v.jsx(wn,{variant:"outline",className:"p-1 h-8 justify-self-end",onClick:m,disabled:r,children:v.jsx("div",{className:"flex items-center gap-1 select-none",children:"Clear"})})]})]}),v.jsx(gn,{})]});return v.jsxs("div",{className:"flex flex-col gap-4 mt-4",children:[S(),A(),ne(),D(),B(),V(),P(),O(),J(),G(),C(),v.jsx(gn,{}),E(),_(),se(),U(),b(),R()]})},$J=()=>{const[e,t]=bt(n=>[n.settings,n.updateSettings]);return v.jsxs("div",{className:"flex flex-col gap-4 mt-4",children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"CV2 Flag",url:"https://docs.opencv.org/4.8.0/d7/d8b/group__photo__inpaint.html#gga8002a65f5a3328fbf15df81b842d3c3ca892824c38e258feb5e72f308a358d52e"}),v.jsxs(Uo,{value:e.cv2Flag,onValueChange:n=>{t({cv2Flag:n})},children:[v.jsx(go,{className:"w-[160px]",children:v.jsx(Vo,{placeholder:"Select flag"})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:Object.values(Jw).map(n=>v.jsx(yo,{value:n,children:n},n))})})]})]}),v.jsx(Pt,{text:"CV2 Radius",url:"https://docs.opencv.org/4.8.0/d7/d8b/group__photo__inpaint.html#gga8002a65f5a3328fbf15df81b842d3c3ca892824c38e258feb5e72f308a358d52e"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[5],min:1,max:100,step:1,value:[Math.floor(e.cv2Radius)],onValueChange:n=>t({cv2Radius:n[0]})}),v.jsx(Yn,{id:"cv2-radius",className:"w-[60px] rounded-full",numberValue:e.cv2Radius,allowFloat:!1,onNumberValueChange:n=>{t({cv2Radius:n})}})]})]})},RJ=()=>{const[e,t]=bt(i=>[i.settings,i.windowSize]),[n,r]=OP(!0);if(Zn("c",()=>{r()}),e.model.name!==sC&&e.model.name!==aC&&e.model.model_type===fs)return null;const o=()=>e.model.name===sC?v.jsx(EJ,{}):e.model.name===aC?v.jsx($J,{}):v.jsx(CJ,{});return v.jsxs(yJ,{open:n,modal:!1,children:[v.jsx(wJ,{tabIndex:-1,className:"z-10 outline-none absolute top-[68px] right-6 rounded-lg border bg-background",children:v.jsx(wn,{variant:"ghost",size:"icon",asChild:!0,className:"p-1.5",onClick:r,children:v.jsx(GU,{strokeWidth:1})})}),v.jsxs(yA,{side:"right",className:"w-[300px] mt-[60px] outline-none pl-4 pr-1",onOpenAutoFocus:i=>i.preventDefault(),onPointerDownOutside:i=>i.preventDefault(),children:[v.jsxs(wA,{children:[v.jsxs(Ut,{children:[v.jsx("div",{className:"overflow-hidden mr-8",children:e.model.name.split("/")[e.model.name.split("/").length-1]}),v.jsx(wn,{variant:"ghost",size:"icon",className:"border h-6 w-6",onClick:r,children:v.jsx(YU,{strokeWidth:1})})]}),v.jsx(gn,{})]}),v.jsx(ag,{style:{height:t.height-160},className:"pr-3",children:o()})]})]})},Jo=Object.create(null);Jo.open="0";Jo.close="1";Jo.ping="2";Jo.pong="3";Jo.message="4";Jo.upgrade="5";Jo.noop="6";const op=Object.create(null);Object.keys(Jo).forEach(e=>{op[Jo[e]]=e});const G1={type:"error",data:"parser error"},bA=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",SA=typeof ArrayBuffer=="function",_A=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,ib=({type:e,data:t},n,r)=>bA&&t instanceof Blob?n?r(t):X2(t,r):SA&&(t instanceof ArrayBuffer||_A(t))?n?r(t):X2(new Blob([t]),r):r(Jo[e]+(t||"")),X2=(e,t)=>{const n=new FileReader;return n.onload=function(){const r=n.result.split(",")[1];t("b"+(r||""))},n.readAsDataURL(e)};function Z2(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let z0;function kJ(e,t){if(bA&&e.data instanceof Blob)return e.data.arrayBuffer().then(Z2).then(t);if(SA&&(e.data instanceof ArrayBuffer||_A(e.data)))return t(Z2(e.data));ib(e,!1,n=>{z0||(z0=new TextEncoder),t(z0.encode(n))})}const q2="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",_u=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let e=0;e{let t=e.length*.75,n=e.length,r,o=0,i,s,l,u;e[e.length-1]==="="&&(t--,e[e.length-2]==="="&&t--);const f=new ArrayBuffer(t),m=new Uint8Array(f);for(r=0;r>4,m[o++]=(s&15)<<4|l>>2,m[o++]=(l&3)<<6|u&63;return f},PJ=typeof ArrayBuffer=="function",sb=(e,t)=>{if(typeof e!="string")return{type:"message",data:EA(e,t)};const n=e.charAt(0);return n==="b"?{type:"message",data:AJ(e.substring(1),t)}:op[n]?e.length>1?{type:op[n],data:e.substring(1)}:{type:op[n]}:G1},AJ=(e,t)=>{if(PJ){const n=TJ(e);return EA(n,t)}else return{base64:!0,data:e}},EA=(e,t)=>{switch(t){case"blob":return e instanceof Blob?e:new Blob([e]);case"arraybuffer":default:return e instanceof ArrayBuffer?e:e.buffer}},CA="",MJ=(e,t)=>{const n=e.length,r=new Array(n);let o=0;e.forEach((i,s)=>{ib(i,!1,l=>{r[s]=l,++o===n&&t(r.join(CA))})})},OJ=(e,t)=>{const n=e.split(CA),r=[];for(let o=0;o{const r=n.length;let o;if(r<126)o=new Uint8Array(1),new DataView(o.buffer).setUint8(0,r);else if(r<65536){o=new Uint8Array(3);const i=new DataView(o.buffer);i.setUint8(0,126),i.setUint16(1,r)}else{o=new Uint8Array(9);const i=new DataView(o.buffer);i.setUint8(0,127),i.setBigUint64(1,BigInt(r))}e.data&&typeof e.data!="string"&&(o[0]|=128),t.enqueue(o),t.enqueue(n)})}})}let B0;function Ch(e){return e.reduce((t,n)=>t+n.length,0)}function $h(e,t){if(e[0].length===t)return e.shift();const n=new Uint8Array(t);let r=0;for(let o=0;oMath.pow(2,21)-1){l.enqueue(G1);break}o=m*Math.pow(2,32)+f.getUint32(4),r=3}else{if(Ch(n)e){l.enqueue(G1);break}}}})}const $A=4;function qt(e){if(e)return IJ(e)}function IJ(e){for(var t in qt.prototype)e[t]=qt.prototype[t];return e}qt.prototype.on=qt.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this};qt.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this};qt.prototype.off=qt.prototype.removeListener=qt.prototype.removeAllListeners=qt.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,o=0;o(e.hasOwnProperty(r)&&(n[r]=e[r]),n),{})}const LJ=Br.setTimeout,FJ=Br.clearTimeout;function vg(e,t){t.useNativeTimers?(e.setTimeoutFn=LJ.bind(Br),e.clearTimeoutFn=FJ.bind(Br)):(e.setTimeoutFn=Br.setTimeout.bind(Br),e.clearTimeoutFn=Br.clearTimeout.bind(Br))}const jJ=1.33;function zJ(e){return typeof e=="string"?BJ(e):Math.ceil((e.byteLength||e.size)*jJ)}function BJ(e){let t=0,n=0;for(let r=0,o=e.length;r=57344?n+=3:(r++,n+=4);return n}function UJ(e){let t="";for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+="&"),t+=encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t}function VJ(e){let t={},n=e.split("&");for(let r=0,o=n.length;r0);return t}function TA(){const e=e$(+new Date);return e!==J2?(Q2=0,J2=e):e+"."+e$(Q2++)}for(;Rh{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)};OJ(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,MJ(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]=TA()),!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 Xo(this.uri(),t)}doWrite(t,n){const r=this.request({method:"POST",data:t});r.on("success",n),r.on("error",(o,i)=>{this.onError("xhr post error",o,i)})}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}}class Xo extends qt{constructor(t,n){super(),vg(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=RA(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");n.xdomain=!!this.opts.xd;const r=this.xhr=new AA(n);try{r.open(this.method,this.uri,!0);try{if(this.opts.extraHeaders){r.setDisableHeaderCheck&&r.setDisableHeaderCheck(!0);for(let o in this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(o)&&r.setRequestHeader(o,this.opts.extraHeaders[o])}}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 o;r.readyState===3&&((o=this.opts.cookieJar)===null||o===void 0||o.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(o){this.setTimeoutFn(()=>{this.onError(o)},0);return}typeof document<"u"&&(this.index=Xo.requestsCount++,Xo.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=GJ,t)try{this.xhr.abort()}catch{}typeof document<"u"&&delete Xo.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()}}Xo.requestsCount=0;Xo.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",t$);else if(typeof addEventListener=="function"){const e="onpagehide"in Br?"pagehide":"unload";addEventListener(e,t$,!1)}}function t$(){for(let e in Xo.requests)Xo.requests.hasOwnProperty(e)&&Xo.requests[e].abort()}const lb=typeof Promise=="function"&&typeof Promise.resolve=="function"?t=>Promise.resolve().then(t):(t,n)=>n(t,0),kh=Br.WebSocket||Br.MozWebSocket,n$=!0,ZJ="arraybuffer",r$=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class qJ extends ab{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=r$?{}:RA(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=n$&&!r$?n?new kh(t,n):new kh(t):new kh(t,n,r)}catch(o){return this.emitReserved("error",o)}this.ws.binaryType=this.socket.binaryType,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{n$&&this.ws.send(i)}catch{}o&&lb(()=>{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]=TA()),this.supportsBinary||(n.b64=1),this.createUri(t,n)}check(){return!!kh}}class QJ extends ab{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=DJ(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=t.readable.pipeThrough(n).getReader(),o=NJ();o.readable.pipeTo(t.writable),this.writer=o.writable.getWriter();const i=()=>{r.read().then(({done:l,value:u})=>{l||(this.onPacket(u),i())}).catch(l=>{})};i();const s={type:"open"};this.query.sid&&(s.data=`{"sid":"${this.query.sid}"}`),this.writer.write(s).then(()=>this.onOpen())})}))}write(t){this.writable=!1;for(let n=0;n{o&&lb(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;(t=this.transport)===null||t===void 0||t.close()}}const JJ={websocket:qJ,webtransport:QJ,polling:XJ},eee=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,tee=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function X1(e){if(e.length>2e3)throw"URI too long";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 o=eee.exec(e||""),i={},s=14;for(;s--;)i[tee[s]]=o[s]||"";return n!=-1&&r!=-1&&(i.source=t,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=nee(i,i.path),i.queryKey=ree(i,i.query),i}function nee(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 ree(e,t){const n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(r,o,i){o&&(n[o]=i)}),n}let MA=class hl extends qt{constructor(t,n={}){super(),this.binaryType=ZJ,this.writeBuffer=[],t&&typeof t=="object"&&(n=t,t=null),t?(t=X1(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=X1(n.host).host),vg(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=VJ(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=$A,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 JJ[t](r)}open(){let t;if(this.opts.rememberUpgrade&&hl.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;hl.priorWebsocketSuccess=!1;const o=()=>{r||(n.send([{type:"ping",data:"probe"}]),n.once("packet",p=>{if(!r)if(p.type==="pong"&&p.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",n),!n)return;hl.priorWebsocketSuccess=n.name==="websocket",this.transport.pause(()=>{r||this.readyState!=="closed"&&(m(),this.setTransport(n),n.send([{type:"upgrade"}]),this.emitReserved("upgrade",n),n=null,this.upgrading=!1,this.flush())})}else{const g=new Error("probe error");g.transport=n.name,this.emitReserved("upgradeError",g)}}))};function i(){r||(r=!0,m(),n.close(),n=null)}const s=p=>{const g=new Error("probe error: "+p);g.transport=n.name,i(),this.emitReserved("upgradeError",g)};function l(){s("transport closed")}function u(){s("socket closed")}function f(p){n&&p.name!==n.name&&i()}const m=()=>{n.removeListener("open",o),n.removeListener("error",s),n.removeListener("close",l),this.off("close",u),this.off("upgrading",f)};n.once("open",o),n.once("error",s),n.once("close",l),this.once("close",u),this.once("upgrading",f),this.upgrades.indexOf("webtransport")!==-1&&t!=="webtransport"?this.setTimeoutFn(()=>{r||n.open()},200):n.open()}onOpen(){if(this.readyState="open",hl.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,o){if(typeof n=="function"&&(o=n,n=void 0),typeof r=="function"&&(o=r,r=null),this.readyState==="closing"||this.readyState==="closed")return;r=r||{},r.compress=r.compress!==!1;const i={type:t,data:n,options:r};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),o&&this.once("flush",o),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){hl.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 o=t.length;for(;rtypeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,OA=Object.prototype.toString,aee=typeof Blob=="function"||typeof Blob<"u"&&OA.call(Blob)==="[object BlobConstructor]",lee=typeof File=="function"||typeof File<"u"&&OA.call(File)==="[object FileConstructor]";function cb(e){return iee&&(e instanceof ArrayBuffer||see(e))||aee&&e instanceof Blob||lee&&e instanceof File}function ip(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(i),n.apply(this,[null,...s])}}emitWithAck(t,...n){const r=this.flags.timeout!==void 0||this._opts.ackTimeout!==void 0;return new Promise((o,i)=>{n.push((s,l)=>r?s?i(s):o(l):o(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((o,...i)=>r!==this._queue[0]?void 0:(o!==null?r.tryCount>this._opts.retries&&(this._queue.shift(),n&&n(o)):(this._queue.shift(),n&&n(null,...i)),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:lt.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 lt.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 lt.EVENT:case lt.BINARY_EVENT:this.onevent(t);break;case lt.ACK:case lt.BINARY_ACK:this.onack(t);break;case lt.DISCONNECT:this.ondisconnect();break;case lt.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(...o){r||(r=!0,n.packet({type:lt.ACK,id:t,data:o}))}}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:lt.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}Ac.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};Ac.prototype.reset=function(){this.attempts=0};Ac.prototype.setMin=function(e){this.ms=e};Ac.prototype.setMax=function(e){this.max=e};Ac.prototype.setJitter=function(e){this.jitter=e};class Q1 extends qt{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,vg(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 Ac({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(n.timeout==null?2e4:n.timeout),this._readyState="closed",this.uri=t;const o=n.parser||mee;this.encoder=new o.Encoder,this.decoder=new o.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 MA(this.uri,this.opts);const n=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;const o=fo(n,"open",function(){r.onopen(),t&&t()}),i=l=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",l),t?t(l):this.maybeReconnectOnOpen()},s=fo(n,"error",i);if(this._timeout!==!1){const l=this._timeout,u=this.setTimeoutFn(()=>{o(),i(new Error("timeout")),n.close()},l);this.opts.autoUnref&&u.unref(),this.subs.push(()=>{this.clearTimeoutFn(u)})}return this.subs.push(o),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(fo(t,"ping",this.onping.bind(this)),fo(t,"data",this.ondata.bind(this)),fo(t,"error",this.onerror.bind(this)),fo(t,"close",this.onclose.bind(this)),fo(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){lb(()=>{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 NA(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(o=>{o?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",o)):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 gu={};function sp(e,t){typeof e=="object"&&(t=e,e=void 0),t=t||{};const n=oee(e,t.path||"/socket.io"),r=n.source,o=n.id,i=n.path,s=gu[o]&&i in gu[o].nsps,l=t.forceNew||t["force new connection"]||t.multiplex===!1||s;let u;return l?u=new Q1(r,t):(gu[o]||(gu[o]=new Q1(r,t)),u=gu[o]),n.query&&!t.query&&(t.query=n.queryKey),u.socket(n.path,t)}Object.assign(sp,{Manager:Q1,Socket:NA,io:sp,connect:sp});const DA="Progress",yg=100,[vee,kte]=Mn(DA),[yee,wee]=vee(DA),IA=d.forwardRef((e,t)=>{const{__scopeProgress:n,value:r,max:o,getValueLabel:i=See,...s}=e,l=J1(o)?o:yg,u=FA(r,l)?r:null,f=lm(u)?i(u,l):void 0;return d.createElement(yee,{scope:n,value:u,max:l},d.createElement(Ae.div,Y({"aria-valuemax":l,"aria-valuemin":0,"aria-valuenow":lm(u)?u:void 0,"aria-valuetext":f,role:"progressbar","data-state":LA(u,l),"data-value":u??void 0,"data-max":l},s,{ref:t})))});IA.propTypes={max(e,t,n){const r=e[t],o=String(r);return r&&!J1(r)?new Error(_ee(o,n)):null},value(e,t,n){const r=e[t],o=String(r),i=J1(e.max)?e.max:yg;return r!=null&&!FA(r,i)?new Error(Eee(o,n)):null}};const xee="ProgressIndicator",bee=d.forwardRef((e,t)=>{var n;const{__scopeProgress:r,...o}=e,i=wee(xee,r);return d.createElement(Ae.div,Y({"data-state":LA(i.value,i.max),"data-value":(n=i.value)!==null&&n!==void 0?n:void 0,"data-max":i.max},o,{ref:t}))});function See(e,t){return`${Math.round(e/t*100)}%`}function LA(e,t){return e==null?"indeterminate":e===t?"complete":"loading"}function lm(e){return typeof e=="number"}function J1(e){return lm(e)&&!isNaN(e)&&e>0}function FA(e,t){return lm(e)&&!isNaN(e)&&e<=t&&e>=0}function _ee(e,t){return`Invalid prop \`max\` of value \`${e}\` supplied to \`${t}\`. Only numbers greater than 0 are valid max values. Defaulting to \`${yg}\`.`}function Eee(e,t){return`Invalid prop \`value\` of value \`${e}\` supplied to \`${t}\`. The \`value\` prop must be: + - a positive number + - less than the value passed to \`max\` (or ${yg} if no \`max\` prop is set) + - \`null\` if the progress is indeterminate. + +Defaulting to \`null\`.`}const jA=IA,Cee=bee,zA=d.forwardRef(({className:e,value:t,...n},r)=>v.jsx(jA,{ref:r,className:Ce("relative h-2 w-full overflow-hidden rounded-full bg-primary/20",e),...n,children:v.jsx(Cee,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(t||0)}%)`}})}));zA.displayName=jA.displayName;const $ee="",Zi=sp($ee),Ree=()=>{const[e,t,n]=bt(u=>[u.settings,u.isInpainting,u.isSD()]),[r,o]=d.useState(!1),[i,s]=d.useState(0),l=Math.min(Math.round(i/e.sdSteps*100),100);return d.useEffect(()=>(Zi.on("connect",()=>{o(!0)}),Zi.on("disconnect",()=>{o(!1)}),Zi.on("diffusion_progress",u=>{u&&s(u.step+1)}),Zi.on("diffusion_finish",()=>{s(0)}),()=>{Zi.off("connect"),Zi.off("disconnect"),Zi.off("diffusion_progress"),Zi.off("diffusion_finish")}),[]),v.jsxs("div",{className:"z-10 fixed bg-background w-[220px] left-1/2 -translate-x-1/2 top-[68px] h-[32px] flex justify-center items-center gap-[18px] border-[1px] border-[solid] rounded-[14px] pl-[8px] pr-[8px]",style:{visibility:r&&t&&n?"visible":"hidden"},children:[v.jsx(zA,{value:l}),v.jsxs("div",{className:"w-[45px] flex justify-center font-nums",children:[l,"%"]})]})},kee=()=>{const[e,t]=bt(n=>[n.file,n.updateSettings]);return d.useEffect(()=>{(async()=>{const r=await Uj();t({model:r})})()},[]),v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"flex gap-3 absolute top-[68px] left-[24px] items-center",children:[v.jsx(vJ,{}),v.jsx(qq,{})]}),v.jsx(Wq,{}),v.jsx(Ree,{}),v.jsx(RJ,{}),e?v.jsx(Zq,{file:e}):v.jsx(v.Fragment,{})]})},Tee=()=>{const[e,t]=d.useState(window.innerWidth),n=d.useCallback(()=>{t(window.innerWidth)},[]);if(d.useEffect(()=>(window.addEventListener("resize",n),()=>{window.removeEventListener("resize",n)})),e<768)return"mobile";if(e>=768&&e<1224)return"tablet";if(e>=1224)return"desktop"};function Pee(e){const{onSelection:t}=e,[n]=d.useState(`file-upload-${Math.random().toString()}`),r=Tee();function o(i){if(!(!i||!i.type.match("image.*")))try{if(i.size>20*1024*1024)throw new Error("file too large");t(i)}catch(l){alert(`error: ${l.message}`)}}return v.jsx("div",{className:"absolute flex w-screen h-screen justify-center items-center pointer-events-none",children:v.jsx("label",{htmlFor:n,className:"grid bg-background border-[2px] border-[dashed] rounded-lg min-w-[600px] hover:bg-primary hover:text-primary-foreground pointer-events-auto",children:v.jsxs("div",{className:"grid p-16 w-full h-full",onDragOver:i=>{i.stopPropagation(),i.preventDefault()},children:[v.jsx("input",{className:"hidden",id:n,name:n,type:"file",onChange:i=>{var l;const s=(l=i.currentTarget.files)==null?void 0:l[0];s&&o(s)},accept:"image/png, image/jpeg"}),v.jsx("p",{className:"text-center",children:r==="desktop"?"Click here or drag an image file":"Tap here to load your picture"})]})})})}const BA="ToastProvider",[db,Aee,Mee]=Gd("Toast"),[UA,Tte]=Mn("Toast",[Mee]),[Oee,wg]=UA(BA),VA=e=>{const{__scopeToast:t,label:n="Notification",duration:r=5e3,swipeDirection:o="right",swipeThreshold:i=50,children:s}=e,[l,u]=d.useState(null),[f,m]=d.useState(0),p=d.useRef(!1),g=d.useRef(!1);return d.createElement(db.Provider,{scope:t},d.createElement(Oee,{scope:t,label:n,duration:r,swipeDirection:o,swipeThreshold:i,toastCount:f,viewport:l,onViewportChange:u,onToastAdd:d.useCallback(()=>m(y=>y+1),[]),onToastRemove:d.useCallback(()=>m(y=>y-1),[]),isFocusedToastEscapeKeyDownRef:p,isClosePausedRef:g},s))};VA.propTypes={label(e){if(e.label&&typeof e.label=="string"&&!e.label.trim()){const t=`Invalid prop \`label\` supplied to \`${BA}\`. Expected non-empty \`string\`.`;return new Error(t)}return null}};const Nee="ToastViewport",Dee=["F8"],ew="toast.viewportPause",tw="toast.viewportResume",Iee=d.forwardRef((e,t)=>{const{__scopeToast:n,hotkey:r=Dee,label:o="Notifications ({hotkey})",...i}=e,s=wg(Nee,n),l=Aee(n),u=d.useRef(null),f=d.useRef(null),m=d.useRef(null),p=d.useRef(null),g=Ue(t,p,s.onViewportChange),y=r.join("+").replace(/Key/g,"").replace(/Digit/g,""),x=s.toastCount>0;d.useEffect(()=>{const E=_=>{var b;r.every(R=>_[R]||_.code===R)&&((b=p.current)===null||b===void 0||b.focus())};return document.addEventListener("keydown",E),()=>document.removeEventListener("keydown",E)},[r]),d.useEffect(()=>{const E=u.current,_=p.current;if(x&&E&&_){const b=()=>{if(!s.isClosePausedRef.current){const O=new CustomEvent(ew);_.dispatchEvent(O),s.isClosePausedRef.current=!0}},C=()=>{if(s.isClosePausedRef.current){const O=new CustomEvent(tw);_.dispatchEvent(O),s.isClosePausedRef.current=!1}},R=O=>{!E.contains(O.relatedTarget)&&C()},P=()=>{E.contains(document.activeElement)||C()};return E.addEventListener("focusin",b),E.addEventListener("focusout",R),E.addEventListener("pointermove",b),E.addEventListener("pointerleave",P),window.addEventListener("blur",b),window.addEventListener("focus",C),()=>{E.removeEventListener("focusin",b),E.removeEventListener("focusout",R),E.removeEventListener("pointermove",b),E.removeEventListener("pointerleave",P),window.removeEventListener("blur",b),window.removeEventListener("focus",C)}}},[x,s.isClosePausedRef]);const S=d.useCallback(({tabbingDirection:E})=>{const b=l().map(C=>{const R=C.ref.current,P=[R,...Qee(R)];return E==="forwards"?P:P.reverse()});return(E==="forwards"?b.reverse():b).flat()},[l]);return d.useEffect(()=>{const E=p.current;if(E){const _=b=>{const C=b.altKey||b.ctrlKey||b.metaKey;if(b.key==="Tab"&&!C){const D=document.activeElement,B=b.shiftKey;if(b.target===E&&B){var P;(P=f.current)===null||P===void 0||P.focus();return}const G=S({tabbingDirection:B?"backwards":"forwards"}),se=G.findIndex(U=>U===D);if(U0(G.slice(se+1)))b.preventDefault();else{var O,A;B?(O=f.current)===null||O===void 0||O.focus():(A=m.current)===null||A===void 0||A.focus()}}};return E.addEventListener("keydown",_),()=>E.removeEventListener("keydown",_)}},[l,S]),d.createElement(EB,{ref:u,role:"region","aria-label":o.replace("{hotkey}",y),tabIndex:-1,style:{pointerEvents:x?void 0:"none"}},x&&d.createElement(i$,{ref:f,onFocusFromOutsideViewport:()=>{const E=S({tabbingDirection:"forwards"});U0(E)}}),d.createElement(db.Slot,{scope:n},d.createElement(Ae.ol,Y({tabIndex:-1},i,{ref:g}))),x&&d.createElement(i$,{ref:m,onFocusFromOutsideViewport:()=>{const E=S({tabbingDirection:"backwards"});U0(E)}}))}),Lee="ToastFocusProxy",i$=d.forwardRef((e,t)=>{const{__scopeToast:n,onFocusFromOutsideViewport:r,...o}=e,i=wg(Lee,n);return d.createElement(Hm,Y({"aria-hidden":!0,tabIndex:0},o,{ref:t,style:{position:"fixed"},onFocus:s=>{var l;const u=s.relatedTarget;!((l=i.viewport)!==null&&l!==void 0&&l.contains(u))&&r()}}))}),xg="Toast",Fee="toast.swipeStart",jee="toast.swipeMove",zee="toast.swipeCancel",Bee="toast.swipeEnd",Uee=d.forwardRef((e,t)=>{const{forceMount:n,open:r,defaultOpen:o,onOpenChange:i,...s}=e,[l=!0,u]=Zr({prop:r,defaultProp:o,onChange:i});return d.createElement(Sn,{present:n||l},d.createElement(WA,Y({open:l},s,{ref:t,onClose:()=>u(!1),onPause:Ft(e.onPause),onResume:Ft(e.onResume),onSwipeStart:ue(e.onSwipeStart,f=>{f.currentTarget.setAttribute("data-swipe","start")}),onSwipeMove:ue(e.onSwipeMove,f=>{const{x:m,y:p}=f.detail.delta;f.currentTarget.setAttribute("data-swipe","move"),f.currentTarget.style.setProperty("--radix-toast-swipe-move-x",`${m}px`),f.currentTarget.style.setProperty("--radix-toast-swipe-move-y",`${p}px`)}),onSwipeCancel:ue(e.onSwipeCancel,f=>{f.currentTarget.setAttribute("data-swipe","cancel"),f.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),f.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),f.currentTarget.style.removeProperty("--radix-toast-swipe-end-x"),f.currentTarget.style.removeProperty("--radix-toast-swipe-end-y")}),onSwipeEnd:ue(e.onSwipeEnd,f=>{const{x:m,y:p}=f.detail.delta;f.currentTarget.setAttribute("data-swipe","end"),f.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),f.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),f.currentTarget.style.setProperty("--radix-toast-swipe-end-x",`${m}px`),f.currentTarget.style.setProperty("--radix-toast-swipe-end-y",`${p}px`),u(!1)})})))}),[Vee,Wee]=UA(xg,{onClose(){}}),WA=d.forwardRef((e,t)=>{const{__scopeToast:n,type:r="foreground",duration:o,open:i,onClose:s,onEscapeKeyDown:l,onPause:u,onResume:f,onSwipeStart:m,onSwipeMove:p,onSwipeCancel:g,onSwipeEnd:y,...x}=e,S=wg(xg,n),[E,_]=d.useState(null),b=Ue(t,U=>_(U)),C=d.useRef(null),R=d.useRef(null),P=o||S.duration,O=d.useRef(0),A=d.useRef(P),D=d.useRef(0),{onToastAdd:B,onToastRemove:V}=S,J=Ft(()=>{var U;(E==null?void 0:E.contains(document.activeElement))&&((U=S.viewport)===null||U===void 0||U.focus()),s()}),G=d.useCallback(U=>{!U||U===1/0||(window.clearTimeout(D.current),O.current=new Date().getTime(),D.current=window.setTimeout(J,U))},[J]);d.useEffect(()=>{const U=S.viewport;if(U){const ne=()=>{G(A.current),f==null||f()},M=()=>{const ee=new Date().getTime()-O.current;A.current=A.current-ee,window.clearTimeout(D.current),u==null||u()};return U.addEventListener(ew,M),U.addEventListener(tw,ne),()=>{U.removeEventListener(ew,M),U.removeEventListener(tw,ne)}}},[S.viewport,P,u,f,G]),d.useEffect(()=>{i&&!S.isClosePausedRef.current&&G(P)},[i,P,S.isClosePausedRef,G]),d.useEffect(()=>(B(),()=>V()),[B,V]);const se=d.useMemo(()=>E?YA(E):null,[E]);return S.viewport?d.createElement(d.Fragment,null,se&&d.createElement(Hee,{__scopeToast:n,role:"status","aria-live":r==="foreground"?"assertive":"polite","aria-atomic":!0},se),d.createElement(Vee,{scope:n,onClose:J},Is.createPortal(d.createElement(db.ItemSlot,{scope:n},d.createElement(_B,{asChild:!0,onEscapeKeyDown:ue(l,()=>{S.isFocusedToastEscapeKeyDownRef.current||J(),S.isFocusedToastEscapeKeyDownRef.current=!1})},d.createElement(Ae.li,Y({role:"status","aria-live":"off","aria-atomic":!0,tabIndex:0,"data-state":i?"open":"closed","data-swipe-direction":S.swipeDirection},x,{ref:b,style:{userSelect:"none",touchAction:"none",...e.style},onKeyDown:ue(e.onKeyDown,U=>{U.key==="Escape"&&(l==null||l(U.nativeEvent),U.nativeEvent.defaultPrevented||(S.isFocusedToastEscapeKeyDownRef.current=!0,J()))}),onPointerDown:ue(e.onPointerDown,U=>{U.button===0&&(C.current={x:U.clientX,y:U.clientY})}),onPointerMove:ue(e.onPointerMove,U=>{if(!C.current)return;const ne=U.clientX-C.current.x,M=U.clientY-C.current.y,ee=!!R.current,H=["left","right"].includes(S.swipeDirection),X=["left","up"].includes(S.swipeDirection)?Math.min:Math.max,W=H?X(0,ne):0,le=H?0:X(0,M),pe=U.pointerType==="touch"?10:2,$e={x:W,y:le},Ve={originalEvent:U,delta:$e};ee?(R.current=$e,Th(jee,p,Ve,{discrete:!1})):s$($e,S.swipeDirection,pe)?(R.current=$e,Th(Fee,m,Ve,{discrete:!1}),U.target.setPointerCapture(U.pointerId)):(Math.abs(ne)>pe||Math.abs(M)>pe)&&(C.current=null)}),onPointerUp:ue(e.onPointerUp,U=>{const ne=R.current,M=U.target;if(M.hasPointerCapture(U.pointerId)&&M.releasePointerCapture(U.pointerId),R.current=null,C.current=null,ne){const ee=U.currentTarget,H={originalEvent:U,delta:ne};s$(ne,S.swipeDirection,S.swipeThreshold)?Th(Bee,y,H,{discrete:!0}):Th(zee,g,H,{discrete:!0}),ee.addEventListener("click",X=>X.preventDefault(),{once:!0})}})})))),S.viewport))):null});WA.propTypes={type(e){if(e.type&&!["foreground","background"].includes(e.type)){const t=`Invalid prop \`type\` supplied to \`${xg}\`. Expected \`foreground | background\`.`;return new Error(t)}return null}};const Hee=e=>{const{__scopeToast:t,children:n,...r}=e,o=wg(xg,t),[i,s]=d.useState(!1),[l,u]=d.useState(!1);return Zee(()=>s(!0)),d.useEffect(()=>{const f=window.setTimeout(()=>u(!0),1e3);return()=>window.clearTimeout(f)},[]),l?null:d.createElement(zd,{asChild:!0},d.createElement(Hm,r,i&&d.createElement(d.Fragment,null,o.label," ",n)))},Kee=d.forwardRef((e,t)=>{const{__scopeToast:n,...r}=e;return d.createElement(Ae.div,Y({},r,{ref:t}))}),Gee=d.forwardRef((e,t)=>{const{__scopeToast:n,...r}=e;return d.createElement(Ae.div,Y({},r,{ref:t}))}),Yee="ToastAction",HA=d.forwardRef((e,t)=>{const{altText:n,...r}=e;return n?d.createElement(GA,{altText:n,asChild:!0},d.createElement(KA,Y({},r,{ref:t}))):null});HA.propTypes={altText(e){return e.altText?null:new Error(`Missing prop \`altText\` expected on \`${Yee}\``)}};const Xee="ToastClose",KA=d.forwardRef((e,t)=>{const{__scopeToast:n,...r}=e,o=Wee(Xee,n);return d.createElement(GA,{asChild:!0},d.createElement(Ae.button,Y({type:"button"},r,{ref:t,onClick:ue(e.onClick,o.onClose)})))}),GA=d.forwardRef((e,t)=>{const{__scopeToast:n,altText:r,...o}=e;return d.createElement(Ae.div,Y({"data-radix-toast-announce-exclude":"","data-radix-toast-announce-alt":r||void 0},o,{ref:t}))});function YA(e){const t=[];return Array.from(e.childNodes).forEach(r=>{if(r.nodeType===r.TEXT_NODE&&r.textContent&&t.push(r.textContent),qee(r)){const o=r.ariaHidden||r.hidden||r.style.display==="none",i=r.dataset.radixToastAnnounceExclude==="";if(!o)if(i){const s=r.dataset.radixToastAnnounceAlt;s&&t.push(s)}else t.push(...YA(r))}}),t}function Th(e,t,n,{discrete:r}){const o=n.originalEvent.currentTarget,i=new CustomEvent(e,{bubbles:!0,cancelable:!0,detail:n});t&&o.addEventListener(e,t,{once:!0}),r?dx(o,i):o.dispatchEvent(i)}const s$=(e,t,n=0)=>{const r=Math.abs(e.x),o=Math.abs(e.y),i=r>o;return t==="left"||t==="right"?i&&r>n:!i&&o>n};function Zee(e=()=>{}){const t=Ft(e);An(()=>{let n=0,r=0;return n=window.requestAnimationFrame(()=>r=window.requestAnimationFrame(t)),()=>{window.cancelAnimationFrame(n),window.cancelAnimationFrame(r)}},[t])}function qee(e){return e.nodeType===e.ELEMENT_NODE}function Qee(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const o=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||o?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function U0(e){const t=document.activeElement;return e.some(n=>n===t?!0:(n.focus(),document.activeElement!==t))}const Jee=VA,XA=Iee,ZA=Uee,qA=Kee,QA=Gee,JA=HA,eM=KA,ete=Jee,tM=d.forwardRef(({className:e,...t},n)=>v.jsx(XA,{ref:n,className:Ce("fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]",e),tabIndex:-1,...t}));tM.displayName=XA.displayName;const tte=Dm("group pointer-events-auto relative flex w-full items-center justify-between space-x-2 overflow-hidden rounded-md border p-4 pr-6 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full",{variants:{variant:{default:"border bg-background text-foreground",destructive:"destructive group border-destructive bg-destructive text-destructive-foreground"}},defaultVariants:{variant:"default"}}),nM=d.forwardRef(({className:e,variant:t,...n},r)=>v.jsx(ZA,{ref:r,className:Ce(tte({variant:t}),e),tabIndex:-1,...n}));nM.displayName=ZA.displayName;const nte=d.forwardRef(({className:e,...t},n)=>v.jsx(JA,{ref:n,className:Ce("inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium transition-colors hover:bg-secondary focus:outline-none focus:ring-1 focus:ring-ring disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive",e),tabIndex:-1,...t}));nte.displayName=JA.displayName;const rM=d.forwardRef(({className:e,...t},n)=>v.jsx(eM,{ref:n,className:Ce("absolute right-1 top-1 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-1 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600",e),"toast-close":"",tabIndex:-1,...t,children:v.jsx(wT,{className:"h-4 w-4"})}));rM.displayName=eM.displayName;const oM=d.forwardRef(({className:e,...t},n)=>v.jsx(qA,{ref:n,className:Ce("text-sm font-semibold [&+div]:text-xs",e),tabIndex:-1,...t}));oM.displayName=qA.displayName;const iM=d.forwardRef(({className:e,...t},n)=>v.jsx(QA,{ref:n,className:Ce("text-sm opacity-90",e),...t,tabIndex:-1}));iM.displayName=QA.displayName;function rte(){const{toasts:e}=Id();return v.jsxs(ete,{children:[e.map(function({id:t,title:n,description:r,action:o,...i}){return v.jsxs(nM,{...i,children:[v.jsxs("div",{className:"grid gap-1",children:[n&&v.jsx(oM,{children:n}),r&&v.jsx(iM,{children:r})]}),o,v.jsx(rM,{})]},t)}),v.jsx(tM,{})]})}const ote=["image/jpeg","image/png","image/webp","image/bmp","image/tiff"];function ite(){const[e,t,n,r]=bt(g=>[g.file,g.updateAppState,g.setServerConfig,g.setFile]),o=Yj(),i=vH();d.useEffect(()=>{o&&r(o)},[o,r]),d.useEffect(()=>{t({windowSize:i})},[i]),d.useEffect(()=>{(async()=>{const y=await gT();n(y),y.isDesktop&&pF()})()},[]);const s=d.useRef(0),l=d.useCallback(g=>{g.preventDefault(),g.stopPropagation()},[]),u=d.useCallback(g=>{g.preventDefault(),g.stopPropagation(),s.current+=1},[]),f=d.useCallback(g=>{g.preventDefault(),g.stopPropagation(),s.current-=1,s.current>0},[]),m=d.useCallback(g=>{if(g.preventDefault(),g.stopPropagation(),g.dataTransfer.files&&g.dataTransfer.files.length>0){if(!(g.dataTransfer.files.length>1)){const y=g.dataTransfer.files[0],x=y.type;ote.includes(x)&&r(y)}g.dataTransfer.clearData()}},[]),p=d.useCallback(g=>{if(!g.clipboardData)return;const y=g.clipboardData.items,x=[].slice.call(y).filter(_=>_.type.indexOf("image")!==-1);if(x.length===0)return;g.preventDefault(),g.stopPropagation();const E=x[0].getAsFile();E&&r(E)},[]);return d.useEffect(()=>(window.addEventListener("dragenter",u),window.addEventListener("dragleave",f),window.addEventListener("dragover",l),window.addEventListener("drop",m),window.addEventListener("paste",p),function(){window.removeEventListener("dragenter",u),window.removeEventListener("dragleave",f),window.removeEventListener("dragover",l),window.removeEventListener("drop",m),window.removeEventListener("paste",p)})),v.jsxs("main",{className:"flex min-h-screen flex-col items-center justify-between w-full bg-[radial-gradient(circle_at_1px_1px,_#8e8e8e8e_1px,_transparent_0)] [background-size:20px_20px] bg-repeat",children:[v.jsx(rte,{}),v.jsx(nZ,{}),v.jsx(kee,{}),e?v.jsx(v.Fragment,{}):v.jsx(Pee,{onSelection:async g=>{r(g)}})]})}const cm=["light","dark"],fb="(prefers-color-scheme: dark)",ste=typeof window>"u",sM=d.createContext(void 0),ate=e=>d.useContext(sM)?je.createElement(d.Fragment,null,e.children):je.createElement(cte,e),lte=["light","dark"],cte=({forcedTheme:e,disableTransitionOnChange:t=!1,enableSystem:n=!0,enableColorScheme:r=!0,storageKey:o="theme",themes:i=lte,defaultTheme:s=n?"system":"light",attribute:l="data-theme",value:u,children:f,nonce:m})=>{const[p,g]=d.useState(()=>a$(o,s)),[y,x]=d.useState(()=>a$(o)),S=u?Object.values(u):i,E=d.useCallback(R=>{let P=R;if(!P)return;R==="system"&&n&&(P=l$());const O=u?u[P]:P,A=t?dte():null,D=document.documentElement;if(l==="class"?(D.classList.remove(...S),O&&D.classList.add(O)):O?D.setAttribute(l,O):D.removeAttribute(l),r){const B=cm.includes(s)?s:null,V=cm.includes(P)?P:B;D.style.colorScheme=V}A==null||A()},[]),_=d.useCallback(R=>{g(R);try{localStorage.setItem(o,R)}catch{}},[e]),b=d.useCallback(R=>{const P=l$(R);x(P),p==="system"&&n&&!e&&E("system")},[p,e]);d.useEffect(()=>{const R=window.matchMedia(fb);return R.addListener(b),b(R),()=>R.removeListener(b)},[b]),d.useEffect(()=>{const R=P=>{P.key===o&&_(P.newValue||s)};return window.addEventListener("storage",R),()=>window.removeEventListener("storage",R)},[_]),d.useEffect(()=>{E(e??p)},[e,p]);const C=d.useMemo(()=>({theme:p,setTheme:_,forcedTheme:e,resolvedTheme:p==="system"?y:p,themes:n?[...i,"system"]:i,systemTheme:n?y:void 0}),[p,_,e,y,n,i]);return je.createElement(sM.Provider,{value:C},je.createElement(ute,{forcedTheme:e,disableTransitionOnChange:t,enableSystem:n,enableColorScheme:r,storageKey:o,themes:i,defaultTheme:s,attribute:l,value:u,children:f,attrs:S,nonce:m}),f)},ute=d.memo(({forcedTheme:e,storageKey:t,attribute:n,enableSystem:r,enableColorScheme:o,defaultTheme:i,value:s,attrs:l,nonce:u})=>{const f=i==="system",m=n==="class"?`var d=document.documentElement,c=d.classList;c.remove(${l.map(x=>`'${x}'`).join(",")});`:`var d=document.documentElement,n='${n}',s='setAttribute';`,p=o?cm.includes(i)&&i?`if(e==='light'||e==='dark'||!e)d.style.colorScheme=e||'${i}'`:"if(e==='light'||e==='dark')d.style.colorScheme=e":"",g=(x,S=!1,E=!0)=>{const _=s?s[x]:x,b=S?x+"|| ''":`'${_}'`;let C="";return o&&E&&!S&&cm.includes(x)&&(C+=`d.style.colorScheme = '${x}';`),n==="class"?C+=S||_?`c.add(${b})`:"null":_&&(C+=`d[s](n,${b})`),C},y=e?`!function(){${m}${g(e)}}()`:r?`!function(){try{${m}var e=localStorage.getItem('${t}');if('system'===e||(!e&&${f})){var t='${fb}',m=window.matchMedia(t);if(m.media!==t||m.matches){${g("dark")}}else{${g("light")}}}else if(e){${s?`var x=${JSON.stringify(s)};`:""}${g(s?"x[e]":"e",!0)}}${f?"":"else{"+g(i,!1,!1)+"}"}${p}}catch(e){}}()`:`!function(){try{${m}var e=localStorage.getItem('${t}');if(e){${s?`var x=${JSON.stringify(s)};`:""}${g(s?"x[e]":"e",!0)}}else{${g(i,!1,!1)};}${p}}catch(t){}}();`;return je.createElement("script",{nonce:u,dangerouslySetInnerHTML:{__html:y}})},()=>!0),a$=(e,t)=>{if(ste)return;let n;try{n=localStorage.getItem(e)||void 0}catch{}return n||t},dte=()=>{const e=document.createElement("style");return e.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(e),()=>{window.getComputedStyle(document.body),setTimeout(()=>{document.head.removeChild(e)},1)}},l$=e=>(e||(e=window.matchMedia(fb)),e.matches?"dark":"light"),fte=new pL;V0.createRoot(document.getElementById("root")).render(v.jsx(je.StrictMode,{children:v.jsx(wL,{client:fte,children:v.jsx(ate,{defaultTheme:"dark",disableTransitionOnChange:!0,children:v.jsx(VU,{children:v.jsx(ite,{})})})})})); diff --git a/py/iopaint/web_app/assets/index-c6LmMFap.js b/py/iopaint/web_app/assets/index-c6LmMFap.js new file mode 100644 index 0000000..991a916 --- /dev/null +++ b/py/iopaint/web_app/assets/index-c6LmMFap.js @@ -0,0 +1,165 @@ +var Lv=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)};var z=(e,t,n)=>(Lv(e,t,"read from private field"),n?n.call(e):t.get(e)),Te=(e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)},ye=(e,t,n,r)=>(Lv(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n);var Hf=(e,t,n,r)=>({set _(o){ye(e,t,o,n)},get _(){return z(e,t,r)}}),tt=(e,t,n)=>(Lv(e,t,"access private method"),n);function $D(e,t){for(var n=0;nr[o]})}}}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 o of document.querySelectorAll('link[rel="modulepreload"]'))r(o);new MutationObserver(o=>{for(const i of o)if(i.type==="childList")for(const s of i.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&r(s)}).observe(document,{childList:!0,subtree:!0});function n(o){const i={};return o.integrity&&(i.integrity=o.integrity),o.referrerPolicy&&(i.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?i.credentials="include":o.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(o){if(o.ep)return;o.ep=!0;const i=n(o);fetch(o.href,i)}})();var Jc=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function dm(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var y$={exports:{}},fm={},w$={exports:{}},it={};/** + * @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 kd=Symbol.for("react.element"),RD=Symbol.for("react.portal"),kD=Symbol.for("react.fragment"),TD=Symbol.for("react.strict_mode"),PD=Symbol.for("react.profiler"),AD=Symbol.for("react.provider"),MD=Symbol.for("react.context"),OD=Symbol.for("react.forward_ref"),ND=Symbol.for("react.suspense"),DD=Symbol.for("react.memo"),ID=Symbol.for("react.lazy"),j_=Symbol.iterator;function LD(e){return e===null||typeof e!="object"?null:(e=j_&&e[j_]||e["@@iterator"],typeof e=="function"?e:null)}var x$={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},b$=Object.assign,S$={};function yc(e,t,n){this.props=e,this.context=t,this.refs=S$,this.updater=n||x$}yc.prototype.isReactComponent={};yc.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")};yc.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function _$(){}_$.prototype=yc.prototype;function nw(e,t,n){this.props=e,this.context=t,this.refs=S$,this.updater=n||x$}var rw=nw.prototype=new _$;rw.constructor=nw;b$(rw,yc.prototype);rw.isPureReactComponent=!0;var z_=Array.isArray,E$=Object.prototype.hasOwnProperty,ow={current:null},C$={key:!0,ref:!0,__self:!0,__source:!0};function $$(e,t,n){var r,o={},i=null,s=null;if(t!=null)for(r in t.ref!==void 0&&(s=t.ref),t.key!==void 0&&(i=""+t.key),t)E$.call(t,r)&&!C$.hasOwnProperty(r)&&(o[r]=t[r]);var l=arguments.length-2;if(l===1)o.children=n;else if(1>>1,ce=K[se];if(0>>1;seo(We,H))Oeo(he,We)?(K[se]=he,K[Oe]=H,se=Oe):(K[se]=We,K[Ue]=H,se=Ue);else if(Oeo(he,H))K[se]=he,K[Oe]=H,se=Oe;else break e}}return Z}function o(K,Z){var H=K.sortIndex-Z.sortIndex;return H!==0?H:K.id-Z.id}if(typeof performance=="object"&&typeof performance.now=="function"){var i=performance;e.unstable_now=function(){return i.now()}}else{var s=Date,l=s.now();e.unstable_now=function(){return s.now()-l}}var u=[],f=[],m=1,p=null,g=3,y=!1,b=!1,S=!1,E=typeof setTimeout=="function"?setTimeout:null,_=typeof clearTimeout=="function"?clearTimeout:null,x=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function C(K){for(var Z=n(f);Z!==null;){if(Z.callback===null)r(f);else if(Z.startTime<=K)r(f),Z.sortIndex=Z.expirationTime,t(u,Z);else break;Z=n(f)}}function R(K){if(S=!1,C(K),!b)if(n(u)!==null)b=!0,N(P);else{var Z=n(f);Z!==null&&ie(R,Z.startTime-K)}}function P(K,Z){b=!1,S&&(S=!1,_(D),D=-1),y=!0;var H=g;try{for(C(Z),p=n(u);p!==null&&(!(p.expirationTime>Z)||K&&!q());){var se=p.callback;if(typeof se=="function"){p.callback=null,g=p.priorityLevel;var ce=se(p.expirationTime<=Z);Z=e.unstable_now(),typeof ce=="function"?p.callback=ce:p===n(u)&&r(u),C(Z)}else r(u);p=n(u)}if(p!==null)var Ve=!0;else{var Ue=n(f);Ue!==null&&ie(R,Ue.startTime-Z),Ve=!1}return Ve}finally{p=null,g=H,y=!1}}var M=!1,A=null,D=-1,U=5,W=-1;function q(){return!(e.unstable_now()-WK||125se?(K.sortIndex=H,t(f,K),n(u)===null&&K===n(f)&&(S?(_(D),D=-1):S=!0,ie(R,H-se))):(K.sortIndex=ce,t(u,K),b||y||(b=!0,N(P))),K},e.unstable_shouldYield=q,e.unstable_wrapCallback=function(K){var Z=g;return function(){var H=g;g=Z;try{return K.apply(this,arguments)}finally{g=H}}}})(P$);T$.exports=P$;var XD=T$.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 A$=d,yr=XD;function ue(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"),W0=Object.prototype.hasOwnProperty,ZD=/^[: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]*$/,U_={},V_={};function qD(e){return W0.call(V_,e)?!0:W0.call(U_,e)?!1:ZD.test(e)?V_[e]=!0:(U_[e]=!0,!1)}function QD(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 JD(e,t,n,r){if(t===null||typeof t>"u"||QD(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 Un(e,t,n,r,o,i,s){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=o,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=i,this.removeEmptyString=s}var bn={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){bn[e]=new Un(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];bn[t]=new Un(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){bn[e]=new Un(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){bn[e]=new Un(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){bn[e]=new Un(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){bn[e]=new Un(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){bn[e]=new Un(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){bn[e]=new Un(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){bn[e]=new Un(e,5,!1,e.toLowerCase(),null,!1,!1)});var sw=/[\-:]([a-z])/g;function aw(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(sw,aw);bn[t]=new Un(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(sw,aw);bn[t]=new Un(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(sw,aw);bn[t]=new Un(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){bn[e]=new Un(e,1,!1,e.toLowerCase(),null,!1,!1)});bn.xlinkHref=new Un("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){bn[e]=new Un(e,1,!1,e.toLowerCase(),null,!0,!0)});function lw(e,t,n,r){var o=bn.hasOwnProperty(t)?bn[t]:null;(o!==null?o.type!==0:r||!(2l||o[s]!==i[l]){var u=` +`+o[s].replace(" at new "," at ");return e.displayName&&u.includes("")&&(u=u.replace("",e.displayName)),u}while(1<=s&&0<=l);break}}}finally{zv=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?vu(e):""}function e9(e){switch(e.tag){case 5:return vu(e.type);case 16:return vu("Lazy");case 13:return vu("Suspense");case 19:return vu("SuspenseList");case 0:case 2:case 15:return e=Bv(e.type,!1),e;case 11:return e=Bv(e.type.render,!1),e;case 1:return e=Bv(e.type,!0),e;default:return""}}function Y0(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 ml:return"Fragment";case pl:return"Portal";case H0:return"Profiler";case cw:return"StrictMode";case K0:return"Suspense";case G0:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case N$:return(e.displayName||"Context")+".Consumer";case O$:return(e._context.displayName||"Context")+".Provider";case uw:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case dw:return t=e.displayName||null,t!==null?t:Y0(e.type)||"Memo";case Ji:t=e._payload,e=e._init;try{return Y0(e(t))}catch{}}return null}function t9(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 Y0(t);case 8:return t===cw?"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 Rs(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function I$(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function n9(e){var t=I$(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 o=n.get,i=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return o.call(this)},set:function(s){r=""+s,i.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 Yf(e){e._valueTracker||(e._valueTracker=n9(e))}function L$(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=I$(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function ap(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 X0(e,t){var n=t.checked;return zt({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function H_(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=Rs(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 F$(e,t){t=t.checked,t!=null&&lw(e,"checked",t,!1)}function Z0(e,t){F$(e,t);var n=Rs(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")?q0(e,t.type,n):t.hasOwnProperty("defaultValue")&&q0(e,t.type,Rs(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function K_(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 q0(e,t,n){(t!=="number"||ap(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var yu=Array.isArray;function Rl(e,t,n,r){if(e=e.options,t){t={};for(var o=0;o"+t.valueOf().toString()+"",t=Xf.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function ju(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var Eu={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},r9=["Webkit","ms","Moz","O"];Object.keys(Eu).forEach(function(e){r9.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),Eu[t]=Eu[e]})});function U$(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||Eu.hasOwnProperty(e)&&Eu[e]?(""+t).trim():t+"px"}function V$(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,o=U$(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,o):e[n]=o}}var o9=zt({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 ey(e,t){if(t){if(o9[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(ue(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(ue(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(ue(61))}if(t.style!=null&&typeof t.style!="object")throw Error(ue(62))}}function ty(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 ny=null;function fw(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var ry=null,kl=null,Tl=null;function X_(e){if(e=Ad(e)){if(typeof ry!="function")throw Error(ue(280));var t=e.stateNode;t&&(t=vm(t),ry(e.stateNode,e.type,t))}}function W$(e){kl?Tl?Tl.push(e):Tl=[e]:kl=e}function H$(){if(kl){var e=kl,t=Tl;if(Tl=kl=null,X_(e),t)for(e=0;e>>=0,e===0?32:31-(m9(e)/g9|0)|0}var Zf=64,qf=4194304;function wu(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 dp(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,o=e.suspendedLanes,i=e.pingedLanes,s=n&268435455;if(s!==0){var l=s&~o;l!==0?r=wu(l):(i&=s,i!==0&&(r=wu(i)))}else s=n&~o,s!==0?r=wu(s):i!==0&&(r=wu(i));if(r===0)return 0;if(t!==0&&t!==r&&!(t&o)&&(o=r&-r,i=t&-t,o>=i||o===16&&(i&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 Td(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-wo(t),e[t]=n}function x9(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=$u),oE=" ",iE=!1;function dR(e,t){switch(e){case"keyup":return Y9.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function fR(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var gl=!1;function Z9(e,t){switch(e){case"compositionend":return fR(t);case"keypress":return t.which!==32?null:(iE=!0,oE);case"textInput":return e=t.data,e===oE&&iE?null:e;default:return null}}function q9(e,t){if(gl)return e==="compositionend"||!xw&&dR(e,t)?(e=cR(),Oh=vw=us=null,gl=!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=cE(n)}}function gR(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?gR(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function vR(){for(var e=window,t=ap();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=ap(e.document)}return t}function bw(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 sI(e){var t=vR(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&gR(n.ownerDocument.documentElement,n)){if(r!==null&&bw(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 o=n.textContent.length,i=Math.min(r.start,o);r=r.end===void 0?i:Math.min(r.end,o),!e.extend&&i>r&&(o=r,r=i,i=o),o=uE(n,i);var s=uE(n,r);o&&s&&(e.rangeCount!==1||e.anchorNode!==o.node||e.anchorOffset!==o.offset||e.focusNode!==s.node||e.focusOffset!==s.offset)&&(t=t.createRange(),t.setStart(o.node,o.offset),e.removeAllRanges(),i>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,vl=null,cy=null,ku=null,uy=!1;function dE(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;uy||vl==null||vl!==ap(r)||(r=vl,"selectionStart"in r&&bw(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}),ku&&Hu(ku,r)||(ku=r,r=pp(cy,"onSelect"),0xl||(e.current=gy[xl],gy[xl]=null,xl--)}function $t(e,t){xl++,gy[xl]=e.current,e.current=t}var ks={},Pn=Ns(ks),Jn=Ns(!1),Ra=ks;function Ql(e,t){var n=e.type.contextTypes;if(!n)return ks;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var o={},i;for(i in n)o[i]=t[i];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=o),o}function er(e){return e=e.childContextTypes,e!=null}function gp(){At(Jn),At(Pn)}function yE(e,t,n){if(Pn.current!==ks)throw Error(ue(168));$t(Pn,t),$t(Jn,n)}function $R(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var o in r)if(!(o in t))throw Error(ue(108,t9(e)||"Unknown",o));return zt({},n,r)}function vp(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||ks,Ra=Pn.current,$t(Pn,e),$t(Jn,Jn.current),!0}function wE(e,t,n){var r=e.stateNode;if(!r)throw Error(ue(169));n?(e=$R(e,t,Ra),r.__reactInternalMemoizedMergedChildContext=e,At(Jn),At(Pn),$t(Pn,e)):At(Jn),$t(Jn,n)}var pi=null,ym=!1,t0=!1;function RR(e){pi===null?pi=[e]:pi.push(e)}function yI(e){ym=!0,RR(e)}function Ds(){if(!t0&&pi!==null){t0=!0;var e=0,t=xt;try{var n=pi;for(xt=1;e>=s,o-=s,mi=1<<32-wo(t)+o|n<D?(U=A,A=null):U=A.sibling;var W=g(_,A,C[D],R);if(W===null){A===null&&(A=U);break}e&&A&&W.alternate===null&&t(_,A),x=i(W,x,D),M===null?P=W:M.sibling=W,M=W,A=U}if(D===C.length)return n(_,A),Dt&&ta(_,D),P;if(A===null){for(;DD?(U=A,A=null):U=A.sibling;var q=g(_,A,W.value,R);if(q===null){A===null&&(A=U);break}e&&A&&q.alternate===null&&t(_,A),x=i(q,x,D),M===null?P=q:M.sibling=q,M=q,A=U}if(W.done)return n(_,A),Dt&&ta(_,D),P;if(A===null){for(;!W.done;D++,W=C.next())W=p(_,W.value,R),W!==null&&(x=i(W,x,D),M===null?P=W:M.sibling=W,M=W);return Dt&&ta(_,D),P}for(A=r(_,A);!W.done;D++,W=C.next())W=y(A,_,D,W.value,R),W!==null&&(e&&W.alternate!==null&&A.delete(W.key===null?D:W.key),x=i(W,x,D),M===null?P=W:M.sibling=W,M=W);return e&&A.forEach(function(X){return t(_,X)}),Dt&&ta(_,D),P}function E(_,x,C,R){if(typeof C=="object"&&C!==null&&C.type===ml&&C.key===null&&(C=C.props.children),typeof C=="object"&&C!==null){switch(C.$$typeof){case Gf:e:{for(var P=C.key,M=x;M!==null;){if(M.key===P){if(P=C.type,P===ml){if(M.tag===7){n(_,M.sibling),x=o(M,C.props.children),x.return=_,_=x;break e}}else if(M.elementType===P||typeof P=="object"&&P!==null&&P.$$typeof===Ji&&$E(P)===M.type){n(_,M.sibling),x=o(M,C.props),x.ref=iu(_,M,C),x.return=_,_=x;break e}n(_,M);break}else t(_,M);M=M.sibling}C.type===ml?(x=$a(C.props.children,_.mode,R,C.key),x.return=_,_=x):(R=Bh(C.type,C.key,C.props,null,_.mode,R),R.ref=iu(_,x,C),R.return=_,_=R)}return s(_);case pl:e:{for(M=C.key;x!==null;){if(x.key===M)if(x.tag===4&&x.stateNode.containerInfo===C.containerInfo&&x.stateNode.implementation===C.implementation){n(_,x.sibling),x=o(x,C.children||[]),x.return=_,_=x;break e}else{n(_,x);break}else t(_,x);x=x.sibling}x=c0(C,_.mode,R),x.return=_,_=x}return s(_);case Ji:return M=C._init,E(_,x,M(C._payload),R)}if(yu(C))return b(_,x,C,R);if(eu(C))return S(_,x,C,R);oh(_,C)}return typeof C=="string"&&C!==""||typeof C=="number"?(C=""+C,x!==null&&x.tag===6?(n(_,x.sibling),x=o(x,C),x.return=_,_=x):(n(_,x),x=l0(C,_.mode,R),x.return=_,_=x),s(_)):n(_,x)}return E}var ec=DR(!0),IR=DR(!1),Md={},Ko=Ns(Md),Xu=Ns(Md),Zu=Ns(Md);function fa(e){if(e===Md)throw Error(ue(174));return e}function Pw(e,t){switch($t(Zu,t),$t(Xu,e),$t(Ko,Md),e=t.nodeType,e){case 9:case 11:t=(t=t.documentElement)?t.namespaceURI:J0(null,"");break;default:e=e===8?t.parentNode:t,t=e.namespaceURI||null,e=e.tagName,t=J0(t,e)}At(Ko),$t(Ko,t)}function tc(){At(Ko),At(Xu),At(Zu)}function LR(e){fa(Zu.current);var t=fa(Ko.current),n=J0(t,e.type);t!==n&&($t(Xu,e),$t(Ko,n))}function Aw(e){Xu.current===e&&(At(Ko),At(Xu))}var Lt=Ns(0);function _p(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 n0=[];function Mw(){for(var e=0;en?n:4,e(!0);var r=r0.transition;r0.transition={};try{e(!1),t()}finally{xt=n,r0.transition=r}}function JR(){return Yr().memoizedState}function SI(e,t,n){var r=Ss(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},ek(e))tk(t,n);else if(n=AR(e,t,n,r),n!==null){var o=jn();xo(n,e,r,o),nk(n,t,r)}}function _I(e,t,n){var r=Ss(e),o={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(ek(e))tk(t,o);else{var i=e.alternate;if(e.lanes===0&&(i===null||i.lanes===0)&&(i=t.lastRenderedReducer,i!==null))try{var s=t.lastRenderedState,l=i(s,n);if(o.hasEagerState=!0,o.eagerState=l,So(l,s)){var u=t.interleaved;u===null?(o.next=o,kw(t)):(o.next=u.next,u.next=o),t.interleaved=o;return}}catch{}finally{}n=AR(e,t,o,r),n!==null&&(o=jn(),xo(n,e,r,o),nk(n,t,r))}}function ek(e){var t=e.alternate;return e===jt||t!==null&&t===jt}function tk(e,t){Tu=Ep=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function nk(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,pw(e,n)}}var Cp={readContext:Gr,useCallback:$n,useContext:$n,useEffect:$n,useImperativeHandle:$n,useInsertionEffect:$n,useLayoutEffect:$n,useMemo:$n,useReducer:$n,useRef:$n,useState:$n,useDebugValue:$n,useDeferredValue:$n,useTransition:$n,useMutableSource:$n,useSyncExternalStore:$n,useId:$n,unstable_isNewReconciler:!1},EI={readContext:Gr,useCallback:function(e,t){return Po().memoizedState=[e,t===void 0?null:t],e},useContext:Gr,useEffect:kE,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,Lh(4194308,4,YR.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Lh(4194308,4,e,t)},useInsertionEffect:function(e,t){return Lh(4,2,e,t)},useMemo:function(e,t){var n=Po();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=Po();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=SI.bind(null,jt,e),[r.memoizedState,e]},useRef:function(e){var t=Po();return e={current:e},t.memoizedState=e},useState:RE,useDebugValue:Lw,useDeferredValue:function(e){return Po().memoizedState=e},useTransition:function(){var e=RE(!1),t=e[0];return e=bI.bind(null,e[1]),Po().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=jt,o=Po();if(Dt){if(n===void 0)throw Error(ue(407));n=n()}else{if(n=t(),dn===null)throw Error(ue(349));Ta&30||zR(r,t,n)}o.memoizedState=n;var i={value:n,getSnapshot:t};return o.queue=i,kE(UR.bind(null,r,i,e),[e]),r.flags|=2048,Ju(9,BR.bind(null,r,i,n,t),void 0,null),n},useId:function(){var e=Po(),t=dn.identifierPrefix;if(Dt){var n=gi,r=mi;n=(r&~(1<<32-wo(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=qu++,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[Io]=t,e[Yu]=r,dk(e,t,!1,!1),t.stateNode=e;e:{switch(s=ty(n,r),n){case"dialog":Tt("cancel",e),Tt("close",e),o=r;break;case"iframe":case"object":case"embed":Tt("load",e),o=r;break;case"video":case"audio":for(o=0;orc&&(t.flags|=128,r=!0,su(i,!1),t.lanes=4194304)}else{if(!r)if(e=_p(s),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),su(i,!0),i.tail===null&&i.tailMode==="hidden"&&!s.alternate&&!Dt)return Rn(t),null}else 2*Xt()-i.renderingStartTime>rc&&n!==1073741824&&(t.flags|=128,r=!0,su(i,!1),t.lanes=4194304);i.isBackwards?(s.sibling=t.child,t.child=s):(n=i.last,n!==null?n.sibling=s:t.child=s,i.last=s)}return i.tail!==null?(t=i.tail,i.rendering=t,i.tail=t.sibling,i.renderingStartTime=Xt(),t.sibling=null,n=Lt.current,$t(Lt,r?n&1|2:n&1),t):(Rn(t),null);case 22:case 23:return Vw(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?fr&1073741824&&(Rn(t),t.subtreeFlags&6&&(t.flags|=8192)):Rn(t),null;case 24:return null;case 25:return null}throw Error(ue(156,t.tag))}function MI(e,t){switch(_w(t),t.tag){case 1:return er(t.type)&&gp(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return tc(),At(Jn),At(Pn),Mw(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return Aw(t),null;case 13:if(At(Lt),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(ue(340));Jl()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return At(Lt),null;case 4:return tc(),null;case 10:return Rw(t.type._context),null;case 22:case 23:return Vw(),null;case 24:return null;default:return null}}var sh=!1,Tn=!1,OI=typeof WeakSet=="function"?WeakSet:Set,_e=null;function El(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){Wt(e,t,r)}else n.current=null}function ky(e,t,n){try{n()}catch(r){Wt(e,t,r)}}var LE=!1;function NI(e,t){if(dy=fp,e=vR(),bw(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 o=r.anchorOffset,i=r.focusNode;r=r.focusOffset;try{n.nodeType,i.nodeType}catch{n=null;break e}var s=0,l=-1,u=-1,f=0,m=0,p=e,g=null;t:for(;;){for(var y;p!==n||o!==0&&p.nodeType!==3||(l=s+o),p!==i||r!==0&&p.nodeType!==3||(u=s+r),p.nodeType===3&&(s+=p.nodeValue.length),(y=p.firstChild)!==null;)g=p,p=y;for(;;){if(p===e)break t;if(g===n&&++f===o&&(l=s),g===i&&++m===r&&(u=s),(y=p.nextSibling)!==null)break;p=g,g=p.parentNode}p=y}n=l===-1||u===-1?null:{start:l,end:u}}else n=null}n=n||{start:0,end:0}}else n=null;for(fy={focusedElem:e,selectionRange:n},fp=!1,_e=t;_e!==null;)if(t=_e,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,_e=e;else for(;_e!==null;){t=_e;try{var b=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(b!==null){var S=b.memoizedProps,E=b.memoizedState,_=t.stateNode,x=_.getSnapshotBeforeUpdate(t.elementType===t.type?S:io(t.type,S),E);_.__reactInternalSnapshotBeforeUpdate=x}break;case 3:var C=t.stateNode.containerInfo;C.nodeType===1?C.textContent="":C.nodeType===9&&C.documentElement&&C.removeChild(C.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(ue(163))}}catch(R){Wt(t,t.return,R)}if(e=t.sibling,e!==null){e.return=t.return,_e=e;break}_e=t.return}return b=LE,LE=!1,b}function Pu(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var o=r=r.next;do{if((o.tag&e)===e){var i=o.destroy;o.destroy=void 0,i!==void 0&&ky(t,n,i)}o=o.next}while(o!==r)}}function bm(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 Ty(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 pk(e){var t=e.alternate;t!==null&&(e.alternate=null,pk(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Io],delete t[Yu],delete t[my],delete t[gI],delete t[vI])),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 mk(e){return e.tag===5||e.tag===3||e.tag===4}function FE(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||mk(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 Py(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=mp));else if(r!==4&&(e=e.child,e!==null))for(Py(e,t,n),e=e.sibling;e!==null;)Py(e,t,n),e=e.sibling}function Ay(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(Ay(e,t,n),e=e.sibling;e!==null;)Ay(e,t,n),e=e.sibling}var mn=null,lo=!1;function Ki(e,t,n){for(n=n.child;n!==null;)gk(e,t,n),n=n.sibling}function gk(e,t,n){if(Ho&&typeof Ho.onCommitFiberUnmount=="function")try{Ho.onCommitFiberUnmount(hm,n)}catch{}switch(n.tag){case 5:Tn||El(n,t);case 6:var r=mn,o=lo;mn=null,Ki(e,t,n),mn=r,lo=o,mn!==null&&(lo?(e=mn,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):mn.removeChild(n.stateNode));break;case 18:mn!==null&&(lo?(e=mn,n=n.stateNode,e.nodeType===8?e0(e.parentNode,n):e.nodeType===1&&e0(e,n),Vu(e)):e0(mn,n.stateNode));break;case 4:r=mn,o=lo,mn=n.stateNode.containerInfo,lo=!0,Ki(e,t,n),mn=r,lo=o;break;case 0:case 11:case 14:case 15:if(!Tn&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){o=r=r.next;do{var i=o,s=i.destroy;i=i.tag,s!==void 0&&(i&2||i&4)&&ky(n,t,s),o=o.next}while(o!==r)}Ki(e,t,n);break;case 1:if(!Tn&&(El(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(l){Wt(n,t,l)}Ki(e,t,n);break;case 21:Ki(e,t,n);break;case 22:n.mode&1?(Tn=(r=Tn)||n.memoizedState!==null,Ki(e,t,n),Tn=r):Ki(e,t,n);break;default:Ki(e,t,n)}}function jE(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new OI),t.forEach(function(r){var o=VI.bind(null,e,r);n.has(r)||(n.add(r),r.then(o,o))})}}function ro(e,t){var n=t.deletions;if(n!==null)for(var r=0;ro&&(o=s),r&=~i}if(r=o,r=Xt()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*II(r/1960))-r,10e?16:e,ds===null)var r=!1;else{if(e=ds,ds=null,kp=0,dt&6)throw Error(ue(331));var o=dt;for(dt|=4,_e=e.current;_e!==null;){var i=_e,s=i.child;if(_e.flags&16){var l=i.deletions;if(l!==null){for(var u=0;uXt()-Bw?Ca(e,0):zw|=n),tr(e,t)}function Ek(e,t){t===0&&(e.mode&1?(t=qf,qf<<=1,!(qf&130023424)&&(qf=4194304)):t=1);var n=jn();e=_i(e,t),e!==null&&(Td(e,t,n),tr(e,n))}function UI(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),Ek(e,n)}function VI(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,o=e.memoizedState;o!==null&&(n=o.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(ue(314))}r!==null&&r.delete(t),Ek(e,n)}var Ck;Ck=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||Jn.current)Qn=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return Qn=!1,PI(e,t,n);Qn=!!(e.flags&131072)}else Qn=!1,Dt&&t.flags&1048576&&kR(t,wp,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;Fh(e,t),e=t.pendingProps;var o=Ql(t,Pn.current);Al(t,n),o=Nw(null,t,r,e,o,n);var i=Dw();return t.flags|=1,typeof o=="object"&&o!==null&&typeof o.render=="function"&&o.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,er(r)?(i=!0,vp(t)):i=!1,t.memoizedState=o.state!==null&&o.state!==void 0?o.state:null,Tw(t),o.updater=wm,t.stateNode=o,o._reactInternals=t,by(t,r,e,n),t=Ey(null,t,r,!0,i,n)):(t.tag=0,Dt&&i&&Sw(t),In(null,t,o,n),t=t.child),t;case 16:r=t.elementType;e:{switch(Fh(e,t),e=t.pendingProps,o=r._init,r=o(r._payload),t.type=r,o=t.tag=HI(r),e=io(r,e),o){case 0:t=_y(null,t,r,e,n);break e;case 1:t=NE(null,t,r,e,n);break e;case 11:t=ME(null,t,r,e,n);break e;case 14:t=OE(null,t,r,io(r.type,e),n);break e}throw Error(ue(306,r,""))}return t;case 0:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),_y(e,t,r,o,n);case 1:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),NE(e,t,r,o,n);case 3:e:{if(lk(t),e===null)throw Error(ue(387));r=t.pendingProps,i=t.memoizedState,o=i.element,MR(e,t),Sp(t,r,null,n);var s=t.memoizedState;if(r=s.element,i.isDehydrated)if(i={element:r,isDehydrated:!1,cache:s.cache,pendingSuspenseBoundaries:s.pendingSuspenseBoundaries,transitions:s.transitions},t.updateQueue.baseState=i,t.memoizedState=i,t.flags&256){o=nc(Error(ue(423)),t),t=DE(e,t,r,n,o);break e}else if(r!==o){o=nc(Error(ue(424)),t),t=DE(e,t,r,n,o);break e}else for(mr=ws(t.stateNode.containerInfo.firstChild),gr=t,Dt=!0,ho=null,n=IR(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(Jl(),r===o){t=Ei(e,t,n);break e}In(e,t,r,n)}t=t.child}return t;case 5:return LR(t),e===null&&yy(t),r=t.type,o=t.pendingProps,i=e!==null?e.memoizedProps:null,s=o.children,hy(r,o)?s=null:i!==null&&hy(r,i)&&(t.flags|=32),ak(e,t),In(e,t,s,n),t.child;case 6:return e===null&&yy(t),null;case 13:return ck(e,t,n);case 4:return Pw(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=ec(t,null,r,n):In(e,t,r,n),t.child;case 11:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),ME(e,t,r,o,n);case 7:return In(e,t,t.pendingProps,n),t.child;case 8:return In(e,t,t.pendingProps.children,n),t.child;case 12:return In(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,o=t.pendingProps,i=t.memoizedProps,s=o.value,$t(xp,r._currentValue),r._currentValue=s,i!==null)if(So(i.value,s)){if(i.children===o.children&&!Jn.current){t=Ei(e,t,n);break e}}else for(i=t.child,i!==null&&(i.return=t);i!==null;){var l=i.dependencies;if(l!==null){s=i.child;for(var u=l.firstContext;u!==null;){if(u.context===r){if(i.tag===1){u=wi(-1,n&-n),u.tag=2;var f=i.updateQueue;if(f!==null){f=f.shared;var m=f.pending;m===null?u.next=u:(u.next=m.next,m.next=u),f.pending=u}}i.lanes|=n,u=i.alternate,u!==null&&(u.lanes|=n),wy(i.return,n,t),l.lanes|=n;break}u=u.next}}else if(i.tag===10)s=i.type===t.type?null:i.child;else if(i.tag===18){if(s=i.return,s===null)throw Error(ue(341));s.lanes|=n,l=s.alternate,l!==null&&(l.lanes|=n),wy(s,n,t),s=i.sibling}else s=i.child;if(s!==null)s.return=i;else for(s=i;s!==null;){if(s===t){s=null;break}if(i=s.sibling,i!==null){i.return=s.return,s=i;break}s=s.return}i=s}In(e,t,o.children,n),t=t.child}return t;case 9:return o=t.type,r=t.pendingProps.children,Al(t,n),o=Gr(o),r=r(o),t.flags|=1,In(e,t,r,n),t.child;case 14:return r=t.type,o=io(r,t.pendingProps),o=io(r.type,o),OE(e,t,r,o,n);case 15:return ik(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),Fh(e,t),t.tag=1,er(r)?(e=!0,vp(t)):e=!1,Al(t,n),NR(t,r,o),by(t,r,o,n),Ey(null,t,r,!0,e,n);case 19:return uk(e,t,n);case 22:return sk(e,t,n)}throw Error(ue(156,t.tag))};function $k(e,t){return Q$(e,t)}function WI(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 Ur(e,t,n,r){return new WI(e,t,n,r)}function Hw(e){return e=e.prototype,!(!e||!e.isReactComponent)}function HI(e){if(typeof e=="function")return Hw(e)?1:0;if(e!=null){if(e=e.$$typeof,e===uw)return 11;if(e===dw)return 14}return 2}function _s(e,t){var n=e.alternate;return n===null?(n=Ur(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 Bh(e,t,n,r,o,i){var s=2;if(r=e,typeof e=="function")Hw(e)&&(s=1);else if(typeof e=="string")s=5;else e:switch(e){case ml:return $a(n.children,o,i,t);case cw:s=8,o|=8;break;case H0:return e=Ur(12,n,t,o|2),e.elementType=H0,e.lanes=i,e;case K0:return e=Ur(13,n,t,o),e.elementType=K0,e.lanes=i,e;case G0:return e=Ur(19,n,t,o),e.elementType=G0,e.lanes=i,e;case D$:return _m(n,o,i,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case O$:s=10;break e;case N$:s=9;break e;case uw:s=11;break e;case dw:s=14;break e;case Ji:s=16,r=null;break e}throw Error(ue(130,e==null?e:typeof e,""))}return t=Ur(s,n,t,o),t.elementType=e,t.type=r,t.lanes=i,t}function $a(e,t,n,r){return e=Ur(7,e,r,t),e.lanes=n,e}function _m(e,t,n,r){return e=Ur(22,e,r,t),e.elementType=D$,e.lanes=n,e.stateNode={isHidden:!1},e}function l0(e,t,n){return e=Ur(6,e,null,t),e.lanes=n,e}function c0(e,t,n){return t=Ur(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function KI(e,t,n,r,o){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=Vv(0),this.expirationTimes=Vv(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Vv(0),this.identifierPrefix=r,this.onRecoverableError=o,this.mutableSourceEagerHydrationData=null}function Kw(e,t,n,r,o,i,s,l,u){return e=new KI(e,t,n,l,u),t===1?(t=1,i===!0&&(t|=8)):t=0,i=Ur(3,null,null,t),e.current=i,i.stateNode=e,i.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},Tw(i),e}function GI(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(Pk)}catch(e){console.error(e)}}Pk(),k$.exports=br;var Is=k$.exports;const QI=dm(Is);var GE=Is;V0.createRoot=GE.createRoot,V0.hydrateRoot=GE.hydrateRoot;var Od=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},oc=typeof window>"u"||"Deno"in window;function Lr(){}function JI(e,t){return typeof e=="function"?e(t):e}function Iy(e){return typeof e=="number"&&e>=0&&e!==1/0}function Ak(e,t){return Math.max(e+(t||0)-Date.now(),0)}function YE(e,t){const{type:n="all",exact:r,fetchStatus:o,predicate:i,queryKey:s,stale:l}=e;if(s){if(r){if(t.queryHash!==Zw(s,t.options))return!1}else if(!nd(t.queryKey,s))return!1}if(n!=="all"){const u=t.isActive();if(n==="active"&&!u||n==="inactive"&&u)return!1}return!(typeof l=="boolean"&&t.isStale()!==l||typeof o<"u"&&o!==t.state.fetchStatus||i&&!i(t))}function XE(e,t){const{exact:n,status:r,predicate:o,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(td(t.options.mutationKey)!==td(i))return!1}else if(!nd(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||o&&!o(t))}function Zw(e,t){return((t==null?void 0:t.queryKeyHashFn)||td)(e)}function td(e){return JSON.stringify(e,(t,n)=>Fy(n)?Object.keys(n).sort().reduce((r,o)=>(r[o]=n[o],r),{}):n)}function nd(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?!Object.keys(t).some(n=>!nd(e[n],t[n])):!1}function Mk(e,t){if(e===t)return e;const n=ZE(e)&&ZE(t);if(n||Fy(e)&&Fy(t)){const r=n?e.length:Object.keys(e).length,o=n?t:Object.keys(t),i=o.length,s=n?[]:{};let l=0;for(let u=0;u"u")return!0;const n=t.prototype;return!(!qE(n)||!n.hasOwnProperty("isPrototypeOf"))}function qE(e){return Object.prototype.toString.call(e)==="[object Object]"}function Ok(e){return new Promise(t=>{setTimeout(t,e)})}function QE(e){Ok(0).then(e)}function jy(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?Mk(e,t):t}function eL(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function tL(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var ga,rs,Il,c$,nL=(c$=class extends Od{constructor(){super();Te(this,ga,void 0);Te(this,rs,void 0);Te(this,Il,void 0);ye(this,Il,t=>{if(!oc&&window.addEventListener){const n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){z(this,rs)||this.setEventListener(z(this,Il))}onUnsubscribe(){var t;this.hasListeners()||((t=z(this,rs))==null||t.call(this),ye(this,rs,void 0))}setEventListener(t){var n;ye(this,Il,t),(n=z(this,rs))==null||n.call(this),ye(this,rs,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){z(this,ga)!==t&&(ye(this,ga,t),this.onFocus())}onFocus(){this.listeners.forEach(t=>{t()})}isFocused(){var t;return typeof z(this,ga)=="boolean"?z(this,ga):((t=globalThis.document)==null?void 0:t.visibilityState)!=="hidden"}},ga=new WeakMap,rs=new WeakMap,Il=new WeakMap,c$),Ap=new nL,Ll,os,Fl,u$,rL=(u$=class extends Od{constructor(){super();Te(this,Ll,!0);Te(this,os,void 0);Te(this,Fl,void 0);ye(this,Fl,t=>{if(!oc&&window.addEventListener){const n=()=>t(!0),r=()=>t(!1);return window.addEventListener("online",n,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",r)}}})}onSubscribe(){z(this,os)||this.setEventListener(z(this,Fl))}onUnsubscribe(){var t;this.hasListeners()||((t=z(this,os))==null||t.call(this),ye(this,os,void 0))}setEventListener(t){var n;ye(this,Fl,t),(n=z(this,os))==null||n.call(this),ye(this,os,t(this.setOnline.bind(this)))}setOnline(t){z(this,Ll)!==t&&(ye(this,Ll,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return z(this,Ll)}},Ll=new WeakMap,os=new WeakMap,Fl=new WeakMap,u$),Mp=new rL;function oL(e){return Math.min(1e3*2**e,3e4)}function km(e){return(e??"online")==="online"?Mp.isOnline():!0}var Nk=class{constructor(e){this.revert=e==null?void 0:e.revert,this.silent=e==null?void 0:e.silent}};function u0(e){return e instanceof Nk}function Dk(e){let t=!1,n=0,r=!1,o,i,s;const l=new Promise((E,_)=>{i=E,s=_}),u=E=>{var _;r||(y(new Nk(E)),(_=e.abort)==null||_.call(e))},f=()=>{t=!0},m=()=>{t=!1},p=()=>!Ap.isFocused()||e.networkMode!=="always"&&!Mp.isOnline(),g=E=>{var _;r||(r=!0,(_=e.onSuccess)==null||_.call(e,E),o==null||o(),i(E))},y=E=>{var _;r||(r=!0,(_=e.onError)==null||_.call(e,E),o==null||o(),s(E))},b=()=>new Promise(E=>{var _;o=x=>{const C=r||!p();return C&&E(x),C},(_=e.onPause)==null||_.call(e)}).then(()=>{var E;o=void 0,r||(E=e.onContinue)==null||E.call(e)}),S=()=>{if(r)return;let E;try{E=e.fn()}catch(_){E=Promise.reject(_)}Promise.resolve(E).then(g).catch(_=>{var M;if(r)return;const x=e.retry??(oc?0:3),C=e.retryDelay??oL,R=typeof C=="function"?C(n,_):C,P=x===!0||typeof x=="number"&&n{if(p())return b()}).then(()=>{t?y(_):S()})})};return km(e.networkMode)?S():b().then(S),{promise:l,cancel:u,continue:()=>(o==null?void 0:o())?l:Promise.resolve(),cancelRetry:f,continueRetry:m}}function iL(){let e=[],t=0,n=m=>{m()},r=m=>{m()};const o=m=>{let p;t++;try{p=m()}finally{t--,t||l()}return p},i=m=>{t?e.push(m):QE(()=>{n(m)})},s=m=>(...p)=>{i(()=>{m(...p)})},l=()=>{const m=e;e=[],m.length&&QE(()=>{r(()=>{m.forEach(p=>{n(p)})})})};return{batch:o,batchCalls:s,schedule:i,setNotifyFunction:m=>{n=m},setBatchNotifyFunction:m=>{r=m}}}var vn=iL(),va,d$,Ik=(d$=class{constructor(){Te(this,va,void 0)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Iy(this.gcTime)&&ye(this,va,setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(oc?1/0:5*60*1e3))}clearGcTimeout(){z(this,va)&&(clearTimeout(z(this,va)),ye(this,va,void 0))}},va=new WeakMap,d$),jl,zl,Nr,is,Dr,cn,vd,ya,Bl,Uh,ao,di,f$,sL=(f$=class extends Ik{constructor(t){super();Te(this,Bl);Te(this,ao);Te(this,jl,void 0);Te(this,zl,void 0);Te(this,Nr,void 0);Te(this,is,void 0);Te(this,Dr,void 0);Te(this,cn,void 0);Te(this,vd,void 0);Te(this,ya,void 0);ye(this,ya,!1),ye(this,vd,t.defaultOptions),tt(this,Bl,Uh).call(this,t.options),ye(this,cn,[]),ye(this,Nr,t.cache),this.queryKey=t.queryKey,this.queryHash=t.queryHash,ye(this,jl,t.state||aL(this.options)),this.state=z(this,jl),this.scheduleGc()}get meta(){return this.options.meta}optionalRemove(){!z(this,cn).length&&this.state.fetchStatus==="idle"&&z(this,Nr).remove(this)}setData(t,n){const r=jy(this.state.data,t,this.options);return tt(this,ao,di).call(this,{data:r,type:"success",dataUpdatedAt:n==null?void 0:n.updatedAt,manual:n==null?void 0:n.manual}),r}setState(t,n){tt(this,ao,di).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){var r;const n=z(this,is);return(r=z(this,Dr))==null||r.cancel(t),n?n.then(Lr).catch(Lr):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(z(this,jl))}isActive(){return z(this,cn).some(t=>t.options.enabled!==!1)}isDisabled(){return this.getObserversCount()>0&&!this.isActive()}isStale(){return this.state.isInvalidated||!this.state.dataUpdatedAt||z(this,cn).some(t=>t.getCurrentResult().isStale)}isStaleByTime(t=0){return this.state.isInvalidated||!this.state.dataUpdatedAt||!Ak(this.state.dataUpdatedAt,t)}onFocus(){var n;const t=z(this,cn).find(r=>r.shouldFetchOnWindowFocus());t==null||t.refetch({cancelRefetch:!1}),(n=z(this,Dr))==null||n.continue()}onOnline(){var n;const t=z(this,cn).find(r=>r.shouldFetchOnReconnect());t==null||t.refetch({cancelRefetch:!1}),(n=z(this,Dr))==null||n.continue()}addObserver(t){z(this,cn).includes(t)||(z(this,cn).push(t),this.clearGcTimeout(),z(this,Nr).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){z(this,cn).includes(t)&&(ye(this,cn,z(this,cn).filter(n=>n!==t)),z(this,cn).length||(z(this,Dr)&&(z(this,ya)?z(this,Dr).cancel({revert:!0}):z(this,Dr).cancelRetry()),this.scheduleGc()),z(this,Nr).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return z(this,cn).length}invalidate(){this.state.isInvalidated||tt(this,ao,di).call(this,{type:"invalidate"})}fetch(t,n){var f,m,p,g;if(this.state.fetchStatus!=="idle"){if(this.state.dataUpdatedAt&&(n!=null&&n.cancelRefetch))this.cancel({silent:!0});else if(z(this,is))return(f=z(this,Dr))==null||f.continueRetry(),z(this,is)}if(t&&tt(this,Bl,Uh).call(this,t),!this.options.queryFn){const y=z(this,cn).find(b=>b.options.queryFn);y&&tt(this,Bl,Uh).call(this,y.options)}const r=new AbortController,o={queryKey:this.queryKey,meta:this.meta},i=y=>{Object.defineProperty(y,"signal",{enumerable:!0,get:()=>(ye(this,ya,!0),r.signal)})};i(o);const s=()=>this.options.queryFn?(ye(this,ya,!1),this.options.persister?this.options.persister(this.options.queryFn,o,this):this.options.queryFn(o)):Promise.reject(new Error(`Missing queryFn: '${this.options.queryHash}'`)),l={fetchOptions:n,options:this.options,queryKey:this.queryKey,state:this.state,fetchFn:s};i(l),(m=this.options.behavior)==null||m.onFetch(l,this),ye(this,zl,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((p=l.fetchOptions)==null?void 0:p.meta))&&tt(this,ao,di).call(this,{type:"fetch",meta:(g=l.fetchOptions)==null?void 0:g.meta});const u=y=>{var b,S,E,_;u0(y)&&y.silent||tt(this,ao,di).call(this,{type:"error",error:y}),u0(y)||((S=(b=z(this,Nr).config).onError)==null||S.call(b,y,this),(_=(E=z(this,Nr).config).onSettled)==null||_.call(E,this.state.data,y,this)),this.isFetchingOptimistic||this.scheduleGc(),this.isFetchingOptimistic=!1};return ye(this,Dr,Dk({fn:l.fetchFn,abort:r.abort.bind(r),onSuccess:y=>{var b,S,E,_;if(typeof y>"u"){u(new Error(`${this.queryHash} data is undefined`));return}this.setData(y),(S=(b=z(this,Nr).config).onSuccess)==null||S.call(b,y,this),(_=(E=z(this,Nr).config).onSettled)==null||_.call(E,y,this.state.error,this),this.isFetchingOptimistic||this.scheduleGc(),this.isFetchingOptimistic=!1},onError:u,onFail:(y,b)=>{tt(this,ao,di).call(this,{type:"failed",failureCount:y,error:b})},onPause:()=>{tt(this,ao,di).call(this,{type:"pause"})},onContinue:()=>{tt(this,ao,di).call(this,{type:"continue"})},retry:l.options.retry,retryDelay:l.options.retryDelay,networkMode:l.options.networkMode})),ye(this,is,z(this,Dr).promise),z(this,is)}},jl=new WeakMap,zl=new WeakMap,Nr=new WeakMap,is=new WeakMap,Dr=new WeakMap,cn=new WeakMap,vd=new WeakMap,ya=new WeakMap,Bl=new WeakSet,Uh=function(t){this.options={...z(this,vd),...t},this.updateGcTime(this.options.gcTime)},ao=new WeakSet,di=function(t){const n=r=>{switch(t.type){case"failed":return{...r,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...r,fetchStatus:"paused"};case"continue":return{...r,fetchStatus:"fetching"};case"fetch":return{...r,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:t.meta??null,fetchStatus:km(this.options.networkMode)?"fetching":"paused",...!r.dataUpdatedAt&&{error:null,status:"pending"}};case"success":return{...r,data:t.data,dataUpdateCount:r.dataUpdateCount+1,dataUpdatedAt:t.dataUpdatedAt??Date.now(),error:null,isInvalidated:!1,status:"success",...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};case"error":const o=t.error;return u0(o)&&o.revert&&z(this,zl)?{...z(this,zl),fetchStatus:"idle"}:{...r,error:o,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:o,fetchStatus:"idle",status:"error"};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...t.state}}};this.state=n(this.state),vn.batch(()=>{z(this,cn).forEach(r=>{r.onQueryUpdate()}),z(this,Nr).notify({query:this,type:"updated",action:t})})},f$);function aL(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=typeof t<"u",r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var Mo,h$,lL=(h$=class extends Od{constructor(t={}){super();Te(this,Mo,void 0);this.config=t,ye(this,Mo,new Map)}build(t,n,r){const o=n.queryKey,i=n.queryHash??Zw(o,n);let s=this.get(i);return s||(s=new sL({cache:this,queryKey:o,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(o)}),this.add(s)),s}add(t){z(this,Mo).has(t.queryHash)||(z(this,Mo).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){const n=z(this,Mo).get(t.queryHash);n&&(t.destroy(),n===t&&z(this,Mo).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){vn.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return z(this,Mo).get(t)}getAll(){return[...z(this,Mo).values()]}find(t){const n={exact:!0,...t};return this.getAll().find(r=>YE(n,r))}findAll(t={}){const n=this.getAll();return Object.keys(t).length>0?n.filter(r=>YE(t,r)):n}notify(t){vn.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){vn.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){vn.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},Mo=new WeakMap,h$),Oo,yd,dr,Ul,No,qi,p$,cL=(p$=class extends Ik{constructor(t){super();Te(this,No);Te(this,Oo,void 0);Te(this,yd,void 0);Te(this,dr,void 0);Te(this,Ul,void 0);this.mutationId=t.mutationId,ye(this,yd,t.defaultOptions),ye(this,dr,t.mutationCache),ye(this,Oo,[]),this.state=t.state||uL(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options={...z(this,yd),...t},this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){z(this,Oo).includes(t)||(z(this,Oo).push(t),this.clearGcTimeout(),z(this,dr).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){ye(this,Oo,z(this,Oo).filter(n=>n!==t)),this.scheduleGc(),z(this,dr).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){z(this,Oo).length||(this.state.status==="pending"?this.scheduleGc():z(this,dr).remove(this))}continue(){var t;return((t=z(this,Ul))==null?void 0:t.continue())??this.execute(this.state.variables)}async execute(t){var o,i,s,l,u,f,m,p,g,y,b,S,E,_,x,C,R,P,M,A;const n=()=>(ye(this,Ul,Dk({fn:()=>this.options.mutationFn?this.options.mutationFn(t):Promise.reject(new Error("No mutationFn found")),onFail:(D,U)=>{tt(this,No,qi).call(this,{type:"failed",failureCount:D,error:U})},onPause:()=>{tt(this,No,qi).call(this,{type:"pause"})},onContinue:()=>{tt(this,No,qi).call(this,{type:"continue"})},retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode})),z(this,Ul).promise),r=this.state.status==="pending";try{if(!r){tt(this,No,qi).call(this,{type:"pending",variables:t}),await((i=(o=z(this,dr).config).onMutate)==null?void 0:i.call(o,t,this));const U=await((l=(s=this.options).onMutate)==null?void 0:l.call(s,t));U!==this.state.context&&tt(this,No,qi).call(this,{type:"pending",context:U,variables:t})}const D=await n();return await((f=(u=z(this,dr).config).onSuccess)==null?void 0:f.call(u,D,t,this.state.context,this)),await((p=(m=this.options).onSuccess)==null?void 0:p.call(m,D,t,this.state.context)),await((y=(g=z(this,dr).config).onSettled)==null?void 0:y.call(g,D,null,this.state.variables,this.state.context,this)),await((S=(b=this.options).onSettled)==null?void 0:S.call(b,D,null,t,this.state.context)),tt(this,No,qi).call(this,{type:"success",data:D}),D}catch(D){try{throw await((_=(E=z(this,dr).config).onError)==null?void 0:_.call(E,D,t,this.state.context,this)),await((C=(x=this.options).onError)==null?void 0:C.call(x,D,t,this.state.context)),await((P=(R=z(this,dr).config).onSettled)==null?void 0:P.call(R,void 0,D,this.state.variables,this.state.context,this)),await((A=(M=this.options).onSettled)==null?void 0:A.call(M,void 0,D,t,this.state.context)),D}finally{tt(this,No,qi).call(this,{type:"error",error:D})}}}},Oo=new WeakMap,yd=new WeakMap,dr=new WeakMap,Ul=new WeakMap,No=new WeakSet,qi=function(t){const n=r=>{switch(t.type){case"failed":return{...r,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};case"pending":return{...r,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:!km(this.options.networkMode),status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...r,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:t.error,failureCount:r.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}};this.state=n(this.state),vn.batch(()=>{z(this,Oo).forEach(r=>{r.onMutationUpdate(t)}),z(this,dr).notify({mutation:this,type:"updated",action:t})})},p$);function uL(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Ir,wd,wa,m$,dL=(m$=class extends Od{constructor(t={}){super();Te(this,Ir,void 0);Te(this,wd,void 0);Te(this,wa,void 0);this.config=t,ye(this,Ir,[]),ye(this,wd,0)}build(t,n,r){const o=new cL({mutationCache:this,mutationId:++Hf(this,wd)._,options:t.defaultMutationOptions(n),state:r});return this.add(o),o}add(t){z(this,Ir).push(t),this.notify({type:"added",mutation:t})}remove(t){ye(this,Ir,z(this,Ir).filter(n=>n!==t)),this.notify({type:"removed",mutation:t})}clear(){vn.batch(()=>{z(this,Ir).forEach(t=>{this.remove(t)})})}getAll(){return z(this,Ir)}find(t){const n={exact:!0,...t};return z(this,Ir).find(r=>XE(n,r))}findAll(t={}){return z(this,Ir).filter(n=>XE(t,n))}notify(t){vn.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){return ye(this,wa,(z(this,wa)??Promise.resolve()).then(()=>{const t=z(this,Ir).filter(n=>n.state.isPaused);return vn.batch(()=>t.reduce((n,r)=>n.then(()=>r.continue().catch(Lr)),Promise.resolve()))}).then(()=>{ye(this,wa,void 0)})),z(this,wa)}},Ir=new WeakMap,wd=new WeakMap,wa=new WeakMap,m$);function fL(e){return{onFetch:(t,n)=>{const r=async()=>{var b,S,E,_,x;const o=t.options,i=(E=(S=(b=t.fetchOptions)==null?void 0:b.meta)==null?void 0:S.fetchMore)==null?void 0:E.direction,s=((_=t.state.data)==null?void 0:_.pages)||[],l=((x=t.state.data)==null?void 0:x.pageParams)||[],u={pages:[],pageParams:[]};let f=!1;const m=C=>{Object.defineProperty(C,"signal",{enumerable:!0,get:()=>(t.signal.aborted?f=!0:t.signal.addEventListener("abort",()=>{f=!0}),t.signal)})},p=t.options.queryFn||(()=>Promise.reject(new Error(`Missing queryFn: '${t.options.queryHash}'`))),g=async(C,R,P)=>{if(f)return Promise.reject();if(R==null&&C.pages.length)return Promise.resolve(C);const M={queryKey:t.queryKey,pageParam:R,direction:P?"backward":"forward",meta:t.options.meta};m(M);const A=await p(M),{maxPages:D}=t.options,U=P?tL:eL;return{pages:U(C.pages,A,D),pageParams:U(C.pageParams,R,D)}};let y;if(i&&s.length){const C=i==="backward",R=C?hL:JE,P={pages:s,pageParams:l},M=R(o,P);y=await g(P,M,C)}else{y=await g(u,l[0]??o.initialPageParam);const C=e??s.length;for(let R=1;R{var o,i;return(i=(o=t.options).persister)==null?void 0:i.call(o,r,{queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n)}:t.fetchFn=r}}}function JE(e,{pages:t,pageParams:n}){const r=t.length-1;return e.getNextPageParam(t[r],t,n[r],n)}function hL(e,{pages:t,pageParams:n}){var r;return(r=e.getPreviousPageParam)==null?void 0:r.call(e,t[0],t,n[0],n)}var nn,ss,as,Vl,Wl,ls,Hl,Kl,g$,pL=(g$=class{constructor(e={}){Te(this,nn,void 0);Te(this,ss,void 0);Te(this,as,void 0);Te(this,Vl,void 0);Te(this,Wl,void 0);Te(this,ls,void 0);Te(this,Hl,void 0);Te(this,Kl,void 0);ye(this,nn,e.queryCache||new lL),ye(this,ss,e.mutationCache||new dL),ye(this,as,e.defaultOptions||{}),ye(this,Vl,new Map),ye(this,Wl,new Map),ye(this,ls,0)}mount(){Hf(this,ls)._++,z(this,ls)===1&&(ye(this,Hl,Ap.subscribe(()=>{Ap.isFocused()&&(this.resumePausedMutations(),z(this,nn).onFocus())})),ye(this,Kl,Mp.subscribe(()=>{Mp.isOnline()&&(this.resumePausedMutations(),z(this,nn).onOnline())})))}unmount(){var e,t;Hf(this,ls)._--,z(this,ls)===0&&((e=z(this,Hl))==null||e.call(this),ye(this,Hl,void 0),(t=z(this,Kl))==null||t.call(this),ye(this,Kl,void 0))}isFetching(e){return z(this,nn).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return z(this,ss).findAll({...e,status:"pending"}).length}getQueryData(e){var t;return(t=z(this,nn).find({queryKey:e}))==null?void 0:t.state.data}ensureQueryData(e){const t=this.getQueryData(e.queryKey);return t!==void 0?Promise.resolve(t):this.fetchQuery(e)}getQueriesData(e){return this.getQueryCache().findAll(e).map(({queryKey:t,state:n})=>{const r=n.data;return[t,r]})}setQueryData(e,t,n){const r=z(this,nn).find({queryKey:e}),o=r==null?void 0:r.state.data,i=JI(t,o);if(typeof i>"u")return;const s=this.defaultQueryOptions({queryKey:e});return z(this,nn).build(this,s).setData(i,{...n,manual:!0})}setQueriesData(e,t,n){return vn.batch(()=>this.getQueryCache().findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){var t;return(t=z(this,nn).find({queryKey:e}))==null?void 0:t.state}removeQueries(e){const t=z(this,nn);vn.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=z(this,nn),r={type:"active",...e};return vn.batch(()=>(n.findAll(e).forEach(o=>{o.reset()}),this.refetchQueries(r,t)))}cancelQueries(e={},t={}){const n={revert:!0,...t},r=vn.batch(()=>z(this,nn).findAll(e).map(o=>o.cancel(n)));return Promise.all(r).then(Lr).catch(Lr)}invalidateQueries(e={},t={}){return vn.batch(()=>{if(z(this,nn).findAll(e).forEach(r=>{r.invalidate()}),e.refetchType==="none")return Promise.resolve();const n={...e,type:e.refetchType??e.type??"active"};return this.refetchQueries(n,t)})}refetchQueries(e={},t){const n={...t,cancelRefetch:(t==null?void 0:t.cancelRefetch)??!0},r=vn.batch(()=>z(this,nn).findAll(e).filter(o=>!o.isDisabled()).map(o=>{let i=o.fetch(void 0,n);return n.throwOnError||(i=i.catch(Lr)),o.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(Lr)}fetchQuery(e){const t=this.defaultQueryOptions(e);typeof t.retry>"u"&&(t.retry=!1);const n=z(this,nn).build(this,t);return n.isStaleByTime(t.staleTime)?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Lr).catch(Lr)}fetchInfiniteQuery(e){return e.behavior=fL(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Lr).catch(Lr)}resumePausedMutations(){return z(this,ss).resumePausedMutations()}getQueryCache(){return z(this,nn)}getMutationCache(){return z(this,ss)}getDefaultOptions(){return z(this,as)}setDefaultOptions(e){ye(this,as,e)}setQueryDefaults(e,t){z(this,Vl).set(td(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...z(this,Vl).values()];let n={};return t.forEach(r=>{nd(e,r.queryKey)&&(n={...n,...r.defaultOptions})}),n}setMutationDefaults(e,t){z(this,Wl).set(td(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...z(this,Wl).values()];let n={};return t.forEach(r=>{nd(e,r.mutationKey)&&(n={...n,...r.defaultOptions})}),n}defaultQueryOptions(e){if(e!=null&&e._defaulted)return e;const t={...z(this,as).queries,...(e==null?void 0:e.queryKey)&&this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Zw(t.queryKey,t)),typeof t.refetchOnReconnect>"u"&&(t.refetchOnReconnect=t.networkMode!=="always"),typeof t.throwOnError>"u"&&(t.throwOnError=!!t.suspense),typeof t.networkMode>"u"&&t.persister&&(t.networkMode="offlineFirst"),t}defaultMutationOptions(e){return e!=null&&e._defaulted?e:{...z(this,as).mutations,...(e==null?void 0:e.mutationKey)&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){z(this,nn).clear(),z(this,ss).clear()}},nn=new WeakMap,ss=new WeakMap,as=new WeakMap,Vl=new WeakMap,Wl=new WeakMap,ls=new WeakMap,Hl=new WeakMap,Kl=new WeakMap,g$),Xn,Ct,Gl,kn,xa,Yl,Do,xd,Xl,Zl,ba,Sa,cs,_a,Ea,bu,bd,zy,Sd,By,_d,Uy,Ed,Vy,Cd,Wy,$d,Hy,Rd,Ky,um,Lk,v$,mL=(v$=class extends Od{constructor(t,n){super();Te(this,Ea);Te(this,bd);Te(this,Sd);Te(this,_d);Te(this,Ed);Te(this,Cd);Te(this,$d);Te(this,Rd);Te(this,um);Te(this,Xn,void 0);Te(this,Ct,void 0);Te(this,Gl,void 0);Te(this,kn,void 0);Te(this,xa,void 0);Te(this,Yl,void 0);Te(this,Do,void 0);Te(this,xd,void 0);Te(this,Xl,void 0);Te(this,Zl,void 0);Te(this,ba,void 0);Te(this,Sa,void 0);Te(this,cs,void 0);Te(this,_a,void 0);ye(this,Ct,void 0),ye(this,Gl,void 0),ye(this,kn,void 0),ye(this,_a,new Set),ye(this,Xn,t),this.options=n,ye(this,Do,null),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(z(this,Ct).addObserver(this),eC(z(this,Ct),this.options)?tt(this,Ea,bu).call(this):this.updateResult(),tt(this,Ed,Vy).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Gy(z(this,Ct),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Gy(z(this,Ct),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,tt(this,Cd,Wy).call(this),tt(this,$d,Hy).call(this),z(this,Ct).removeObserver(this)}setOptions(t,n){const r=this.options,o=z(this,Ct);if(this.options=z(this,Xn).defaultQueryOptions(t),Ly(r,this.options)||z(this,Xn).getQueryCache().notify({type:"observerOptionsUpdated",query:z(this,Ct),observer:this}),typeof this.options.enabled<"u"&&typeof this.options.enabled!="boolean")throw new Error("Expected enabled to be a boolean");this.options.queryKey||(this.options.queryKey=r.queryKey),tt(this,Rd,Ky).call(this);const i=this.hasListeners();i&&tC(z(this,Ct),o,this.options,r)&&tt(this,Ea,bu).call(this),this.updateResult(n),i&&(z(this,Ct)!==o||this.options.enabled!==r.enabled||this.options.staleTime!==r.staleTime)&&tt(this,bd,zy).call(this);const s=tt(this,Sd,By).call(this);i&&(z(this,Ct)!==o||this.options.enabled!==r.enabled||s!==z(this,cs))&&tt(this,_d,Uy).call(this,s)}getOptimisticResult(t){const n=z(this,Xn).getQueryCache().build(z(this,Xn),t),r=this.createResult(n,t);return vL(this,r)&&(ye(this,kn,r),ye(this,Yl,this.options),ye(this,xa,z(this,Ct).state)),r}getCurrentResult(){return z(this,kn)}trackResult(t){const n={};return Object.keys(t).forEach(r=>{Object.defineProperty(n,r,{configurable:!1,enumerable:!0,get:()=>(z(this,_a).add(r),t[r])})}),n}getCurrentQuery(){return z(this,Ct)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){const n=z(this,Xn).defaultQueryOptions(t),r=z(this,Xn).getQueryCache().build(z(this,Xn),n);return r.isFetchingOptimistic=!0,r.fetch().then(()=>this.createResult(r,n))}fetch(t){return tt(this,Ea,bu).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),z(this,kn)))}createResult(t,n){var M;const r=z(this,Ct),o=this.options,i=z(this,kn),s=z(this,xa),l=z(this,Yl),f=t!==r?t.state:z(this,Gl),{state:m}=t;let{error:p,errorUpdatedAt:g,fetchStatus:y,status:b}=m,S=!1,E;if(n._optimisticResults){const A=this.hasListeners(),D=!A&&eC(t,n),U=A&&tC(t,r,n,o);(D||U)&&(y=km(t.options.networkMode)?"fetching":"paused",m.dataUpdatedAt||(b="pending")),n._optimisticResults==="isRestoring"&&(y="idle")}if(n.select&&typeof m.data<"u")if(i&&m.data===(s==null?void 0:s.data)&&n.select===z(this,xd))E=z(this,Xl);else try{ye(this,xd,n.select),E=n.select(m.data),E=jy(i==null?void 0:i.data,E,n),ye(this,Xl,E),ye(this,Do,null)}catch(A){ye(this,Do,A)}else E=m.data;if(typeof n.placeholderData<"u"&&typeof E>"u"&&b==="pending"){let A;if(i!=null&&i.isPlaceholderData&&n.placeholderData===(l==null?void 0:l.placeholderData))A=i.data;else if(A=typeof n.placeholderData=="function"?n.placeholderData((M=z(this,Zl))==null?void 0:M.state.data,z(this,Zl)):n.placeholderData,n.select&&typeof A<"u")try{A=n.select(A),ye(this,Do,null)}catch(D){ye(this,Do,D)}typeof A<"u"&&(b="success",E=jy(i==null?void 0:i.data,A,n),S=!0)}z(this,Do)&&(p=z(this,Do),E=z(this,Xl),g=Date.now(),b="error");const _=y==="fetching",x=b==="pending",C=b==="error",R=x&&_;return{status:b,fetchStatus:y,isPending:x,isSuccess:b==="success",isError:C,isInitialLoading:R,isLoading:R,data:E,dataUpdatedAt:m.dataUpdatedAt,error:p,errorUpdatedAt:g,failureCount:m.fetchFailureCount,failureReason:m.fetchFailureReason,errorUpdateCount:m.errorUpdateCount,isFetched:m.dataUpdateCount>0||m.errorUpdateCount>0,isFetchedAfterMount:m.dataUpdateCount>f.dataUpdateCount||m.errorUpdateCount>f.errorUpdateCount,isFetching:_,isRefetching:_&&!x,isLoadingError:C&&m.dataUpdatedAt===0,isPaused:y==="paused",isPlaceholderData:S,isRefetchError:C&&m.dataUpdatedAt!==0,isStale:qw(t,n),refetch:this.refetch}}updateResult(t){const n=z(this,kn),r=this.createResult(z(this,Ct),this.options);if(ye(this,xa,z(this,Ct).state),ye(this,Yl,this.options),z(this,xa).data!==void 0&&ye(this,Zl,z(this,Ct)),Ly(r,n))return;ye(this,kn,r);const o={},i=()=>{if(!n)return!0;const{notifyOnChangeProps:s}=this.options,l=typeof s=="function"?s():s;if(l==="all"||!l&&!z(this,_a).size)return!0;const u=new Set(l??z(this,_a));return this.options.throwOnError&&u.add("error"),Object.keys(z(this,kn)).some(f=>{const m=f;return z(this,kn)[m]!==n[m]&&u.has(m)})};(t==null?void 0:t.listeners)!==!1&&i()&&(o.listeners=!0),tt(this,um,Lk).call(this,{...o,...t})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&tt(this,Ed,Vy).call(this)}},Xn=new WeakMap,Ct=new WeakMap,Gl=new WeakMap,kn=new WeakMap,xa=new WeakMap,Yl=new WeakMap,Do=new WeakMap,xd=new WeakMap,Xl=new WeakMap,Zl=new WeakMap,ba=new WeakMap,Sa=new WeakMap,cs=new WeakMap,_a=new WeakMap,Ea=new WeakSet,bu=function(t){tt(this,Rd,Ky).call(this);let n=z(this,Ct).fetch(this.options,t);return t!=null&&t.throwOnError||(n=n.catch(Lr)),n},bd=new WeakSet,zy=function(){if(tt(this,Cd,Wy).call(this),oc||z(this,kn).isStale||!Iy(this.options.staleTime))return;const n=Ak(z(this,kn).dataUpdatedAt,this.options.staleTime)+1;ye(this,ba,setTimeout(()=>{z(this,kn).isStale||this.updateResult()},n))},Sd=new WeakSet,By=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(z(this,Ct)):this.options.refetchInterval)??!1},_d=new WeakSet,Uy=function(t){tt(this,$d,Hy).call(this),ye(this,cs,t),!(oc||this.options.enabled===!1||!Iy(z(this,cs))||z(this,cs)===0)&&ye(this,Sa,setInterval(()=>{(this.options.refetchIntervalInBackground||Ap.isFocused())&&tt(this,Ea,bu).call(this)},z(this,cs)))},Ed=new WeakSet,Vy=function(){tt(this,bd,zy).call(this),tt(this,_d,Uy).call(this,tt(this,Sd,By).call(this))},Cd=new WeakSet,Wy=function(){z(this,ba)&&(clearTimeout(z(this,ba)),ye(this,ba,void 0))},$d=new WeakSet,Hy=function(){z(this,Sa)&&(clearInterval(z(this,Sa)),ye(this,Sa,void 0))},Rd=new WeakSet,Ky=function(){const t=z(this,Xn).getQueryCache().build(z(this,Xn),this.options);if(t===z(this,Ct))return;const n=z(this,Ct);ye(this,Ct,t),ye(this,Gl,t.state),this.hasListeners()&&(n==null||n.removeObserver(this),t.addObserver(this))},um=new WeakSet,Lk=function(t){vn.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(z(this,kn))}),z(this,Xn).getQueryCache().notify({query:z(this,Ct),type:"observerResultsUpdated"})})},v$);function gL(e,t){return t.enabled!==!1&&!e.state.dataUpdatedAt&&!(e.state.status==="error"&&t.retryOnMount===!1)}function eC(e,t){return gL(e,t)||e.state.dataUpdatedAt>0&&Gy(e,t,t.refetchOnMount)}function Gy(e,t,n){if(t.enabled!==!1){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&qw(e,t)}return!1}function tC(e,t,n,r){return n.enabled!==!1&&(e!==t||r.enabled===!1)&&(!n.suspense||e.state.status!=="error")&&qw(e,n)}function qw(e,t){return e.isStaleByTime(t.staleTime)}function vL(e,t){return!Ly(e.getCurrentResult(),t)}var Fk=d.createContext(void 0),yL=e=>{const t=d.useContext(Fk);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},wL=({client:e,children:t})=>(d.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),d.createElement(Fk.Provider,{value:e},t)),jk=d.createContext(!1),xL=()=>d.useContext(jk);jk.Provider;function bL(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var SL=d.createContext(bL()),_L=()=>d.useContext(SL);function EL(e,t){return typeof e=="function"?e(...t):!!e}var CL=(e,t)=>{(e.suspense||e.throwOnError)&&(t.isReset()||(e.retryOnMount=!1))},$L=e=>{d.useEffect(()=>{e.clearReset()},[e])},RL=({result:e,errorResetBoundary:t,throwOnError:n,query:r})=>e.isError&&!t.isReset()&&!e.isFetching&&EL(n,[e.error,r]),kL=e=>{e.suspense&&typeof e.staleTime!="number"&&(e.staleTime=1e3)},TL=(e,t)=>(e==null?void 0:e.suspense)&&t.isPending,PL=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function AL(e,t,n){const r=yL(n),o=xL(),i=_L(),s=r.defaultQueryOptions(e);s._optimisticResults=o?"isRestoring":"optimistic",kL(s),CL(s,i),$L(i);const[l]=d.useState(()=>new t(r,s)),u=l.getOptimisticResult(s);if(d.useSyncExternalStore(d.useCallback(f=>{const m=o?()=>{}:l.subscribe(vn.batchCalls(f));return l.updateResult(),m},[l,o]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),d.useEffect(()=>{l.setOptions(s,{listeners:!1})},[s,l]),TL(s,u))throw l.setOptions(s,{listeners:!1}),PL(s,l,i);if(RL({result:u,errorResetBoundary:i,throwOnError:s.throwOnError,query:l.getCurrentQuery()}))throw u.error;return s.notifyOnChangeProps?u:l.trackResult(u)}function ML(e,t){return AL(e,mL,t)}var Ao=(e=>(e.RemoveBG="RemoveBG",e.AnimeSeg="AnimeSeg",e.RealESRGAN="RealESRGAN",e.GFPGAN="GFPGAN",e.RestoreFormer="RestoreFormer",e.InteractiveSeg="InteractiveSeg",e))(Ao||{}),Es=(e=>(e.NAME="name",e.CTIME="ctime",e.MTIME="mtime",e))(Es||{}),Ou=(e=>(e.DESCENDING="desc",e.ASCENDING="asc",e))(Ou||{}),Qw=(e=>(e.ddim="ddim",e.plms="plms",e))(Qw||{}),Jw=(e=>(e.INPAINT_NS="INPAINT_NS",e.INPAINT_TELEA="INPAINT_TELEA",e))(Jw||{}),Ln=(e=>(e.x="x",e.y="y",e.xy="xy",e))(Ln||{}),Ol=(e=>(e.text_guided="text-guided",e.shape_guided="shape-guided",e.object_remove="object-remove",e.outpainting="outpainting",e))(Ol||{});function zk(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;tl(i)))==null?void 0:s.classGroupId}const nC=/^\[(.+)\]$/;function NL(e){if(nC.test(e)){const t=nC.exec(e)[1],n=t==null?void 0:t.substring(0,t.indexOf(":"));if(n)return"arbitrary.."+n}}function DL(e){const{theme:t,prefix:n}=e,r={nextPart:new Map,validators:[]};return LL(Object.entries(e.classGroups),n).forEach(([i,s])=>{Yy(s,r,i,t)}),r}function Yy(e,t,n,r){e.forEach(o=>{if(typeof o=="string"){const i=o===""?t:rC(t,o);i.classGroupId=n;return}if(typeof o=="function"){if(IL(o)){Yy(o(r),t,n,r);return}t.validators.push({validator:o,classGroupId:n});return}Object.entries(o).forEach(([i,s])=>{Yy(s,rC(t,i),n,r)})})}function rC(e,t){let n=e;return t.split(ex).forEach(r=>{n.nextPart.has(r)||n.nextPart.set(r,{nextPart:new Map,validators:[]}),n=n.nextPart.get(r)}),n}function IL(e){return e.isThemeGetter}function LL(e,t){return t?e.map(([n,r])=>{const o=r.map(i=>typeof i=="string"?t+i:typeof i=="object"?Object.fromEntries(Object.entries(i).map(([s,l])=>[t+s,l])):i);return[n,o]}):e}function FL(e){if(e<1)return{get:()=>{},set:()=>{}};let t=0,n=new Map,r=new Map;function o(i,s){n.set(i,s),t++,t>e&&(t=0,r=n,n=new Map)}return{get(i){let s=n.get(i);if(s!==void 0)return s;if((s=r.get(i))!==void 0)return o(i,s),s},set(i,s){n.has(i)?n.set(i,s):o(i,s)}}}const Vk="!";function jL(e){const t=e.separator,n=t.length===1,r=t[0],o=t.length;return function(s){const l=[];let u=0,f=0,m;for(let S=0;Sf?m-f:void 0;return{modifiers:l,hasImportantModifier:g,baseClassName:y,maybePostfixModifierPosition:b}}}function zL(e){if(e.length<=1)return e;const t=[];let n=[];return e.forEach(r=>{r[0]==="["?(t.push(...n.sort(),r),n=[]):n.push(r)}),t.push(...n.sort()),t}function BL(e){return{cache:FL(e.cacheSize),splitModifiers:jL(e),...OL(e)}}const UL=/\s+/;function VL(e,t){const{splitModifiers:n,getClassGroupId:r,getConflictingClassGroupIds:o}=t,i=new Set;return e.trim().split(UL).map(s=>{const{modifiers:l,hasImportantModifier:u,baseClassName:f,maybePostfixModifierPosition:m}=n(s);let p=r(m?f.substring(0,m):f),g=!!m;if(!p){if(!m)return{isTailwindClass:!1,originalClassName:s};if(p=r(f),!p)return{isTailwindClass:!1,originalClassName:s};g=!1}const y=zL(l).join(":");return{isTailwindClass:!0,modifierId:u?y+Vk:y,classGroupId:p,originalClassName:s,hasPostfixModifier:g}}).reverse().filter(s=>{if(!s.isTailwindClass)return!0;const{modifierId:l,classGroupId:u,hasPostfixModifier:f}=s,m=l+u;return i.has(m)?!1:(i.add(m),o(u,f).forEach(p=>i.add(l+p)),!0)}).reverse().map(s=>s.originalClassName).join(" ")}function WL(){let e=0,t,n,r="";for(;ep(m),e());return n=BL(f),r=n.cache.get,o=n.cache.set,i=l,l(u)}function l(u){const f=r(u);if(f)return f;const m=VL(u,n);return o(u,m),m}return function(){return i(WL.apply(null,arguments))}}function kt(e){const t=n=>n[e]||[];return t.isThemeGetter=!0,t}const Hk=/^\[(?:([a-z-]+):)?(.+)\]$/i,KL=/^\d+\/\d+$/,GL=new Set(["px","full","screen"]),YL=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,XL=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,ZL=/^-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,qL=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/;function oo(e){return ha(e)||GL.has(e)||KL.test(e)}function Gi(e){return bc(e,"length",iF)}function ha(e){return!!e&&!Number.isNaN(Number(e))}function ch(e){return bc(e,"number",ha)}function lu(e){return!!e&&Number.isInteger(Number(e))}function QL(e){return e.endsWith("%")&&ha(e.slice(0,-1))}function Je(e){return Hk.test(e)}function Yi(e){return YL.test(e)}const JL=new Set(["length","size","percentage"]);function eF(e){return bc(e,JL,Kk)}function tF(e){return bc(e,"position",Kk)}const nF=new Set(["image","url"]);function rF(e){return bc(e,nF,aF)}function oF(e){return bc(e,"",sF)}function cu(){return!0}function bc(e,t,n){const r=Hk.exec(e);return r?r[1]?typeof t=="string"?r[1]===t:t.has(r[1]):n(r[2]):!1}function iF(e){return XL.test(e)}function Kk(){return!1}function sF(e){return ZL.test(e)}function aF(e){return qL.test(e)}function lF(){const e=kt("colors"),t=kt("spacing"),n=kt("blur"),r=kt("brightness"),o=kt("borderColor"),i=kt("borderRadius"),s=kt("borderSpacing"),l=kt("borderWidth"),u=kt("contrast"),f=kt("grayscale"),m=kt("hueRotate"),p=kt("invert"),g=kt("gap"),y=kt("gradientColorStops"),b=kt("gradientColorStopPositions"),S=kt("inset"),E=kt("margin"),_=kt("opacity"),x=kt("padding"),C=kt("saturate"),R=kt("scale"),P=kt("sepia"),M=kt("skew"),A=kt("space"),D=kt("translate"),U=()=>["auto","contain","none"],W=()=>["auto","hidden","clip","visible","scroll"],q=()=>["auto",Je,t],X=()=>[Je,t],ae=()=>["",oo,Gi],V=()=>["auto",ha,Je],F=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],N=()=>["solid","dashed","dotted","double","none"],ie=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity","plus-lighter"],K=()=>["start","end","center","between","around","evenly","stretch"],Z=()=>["","0",Je],H=()=>["auto","avoid","all","avoid-page","page","left","right","column"],se=()=>[ha,ch],ce=()=>[ha,Je];return{cacheSize:500,separator:":",theme:{colors:[cu],spacing:[oo,Gi],blur:["none","",Yi,Je],brightness:se(),borderColor:[e],borderRadius:["none","","full",Yi,Je],borderSpacing:X(),borderWidth:ae(),contrast:se(),grayscale:Z(),hueRotate:ce(),invert:Z(),gap:X(),gradientColorStops:[e],gradientColorStopPositions:[QL,Gi],inset:q(),margin:q(),opacity:se(),padding:X(),saturate:se(),scale:se(),sepia:Z(),skew:ce(),space:X(),translate:X()},classGroups:{aspect:[{aspect:["auto","square","video",Je]}],container:["container"],columns:[{columns:[Yi]}],"break-after":[{"break-after":H()}],"break-before":[{"break-before":H()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],float:[{float:["right","left","none"]}],clear:[{clear:["left","right","both","none"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:[...F(),Je]}],overflow:[{overflow:W()}],"overflow-x":[{"overflow-x":W()}],"overflow-y":[{"overflow-y":W()}],overscroll:[{overscroll:U()}],"overscroll-x":[{"overscroll-x":U()}],"overscroll-y":[{"overscroll-y":U()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[S]}],"inset-x":[{"inset-x":[S]}],"inset-y":[{"inset-y":[S]}],start:[{start:[S]}],end:[{end:[S]}],top:[{top:[S]}],right:[{right:[S]}],bottom:[{bottom:[S]}],left:[{left:[S]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",lu,Je]}],basis:[{basis:q()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",Je]}],grow:[{grow:Z()}],shrink:[{shrink:Z()}],order:[{order:["first","last","none",lu,Je]}],"grid-cols":[{"grid-cols":[cu]}],"col-start-end":[{col:["auto",{span:["full",lu,Je]},Je]}],"col-start":[{"col-start":V()}],"col-end":[{"col-end":V()}],"grid-rows":[{"grid-rows":[cu]}],"row-start-end":[{row:["auto",{span:[lu,Je]},Je]}],"row-start":[{"row-start":V()}],"row-end":[{"row-end":V()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",Je]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",Je]}],gap:[{gap:[g]}],"gap-x":[{"gap-x":[g]}],"gap-y":[{"gap-y":[g]}],"justify-content":[{justify:["normal",...K()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...K(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...K(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[x]}],px:[{px:[x]}],py:[{py:[x]}],ps:[{ps:[x]}],pe:[{pe:[x]}],pt:[{pt:[x]}],pr:[{pr:[x]}],pb:[{pb:[x]}],pl:[{pl:[x]}],m:[{m:[E]}],mx:[{mx:[E]}],my:[{my:[E]}],ms:[{ms:[E]}],me:[{me:[E]}],mt:[{mt:[E]}],mr:[{mr:[E]}],mb:[{mb:[E]}],ml:[{ml:[E]}],"space-x":[{"space-x":[A]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[A]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit",Je,t]}],"min-w":[{"min-w":["min","max","fit",Je,oo]}],"max-w":[{"max-w":["0","none","full","min","max","fit","prose",{screen:[Yi]},Yi,Je]}],h:[{h:[Je,t,"auto","min","max","fit"]}],"min-h":[{"min-h":["min","max","fit",oo,Je]}],"max-h":[{"max-h":[Je,t,"min","max","fit"]}],"font-size":[{text:["base",Yi,Gi]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",ch]}],"font-family":[{font:[cu]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractons"],tracking:[{tracking:["tighter","tight","normal","wide","wider","widest",Je]}],"line-clamp":[{"line-clamp":["none",ha,ch]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",oo,Je]}],"list-image":[{"list-image":["none",Je]}],"list-style-type":[{list:["none","disc","decimal",Je]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[e]}],"placeholder-opacity":[{"placeholder-opacity":[_]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[e]}],"text-opacity":[{"text-opacity":[_]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...N(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",oo,Gi]}],"underline-offset":[{"underline-offset":["auto",oo,Je]}],"text-decoration-color":[{decoration:[e]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],indent:[{indent:X()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Je]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",Je]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[_]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...F(),tF]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",eF]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},rF]}],"bg-color":[{bg:[e]}],"gradient-from-pos":[{from:[b]}],"gradient-via-pos":[{via:[b]}],"gradient-to-pos":[{to:[b]}],"gradient-from":[{from:[y]}],"gradient-via":[{via:[y]}],"gradient-to":[{to:[y]}],rounded:[{rounded:[i]}],"rounded-s":[{"rounded-s":[i]}],"rounded-e":[{"rounded-e":[i]}],"rounded-t":[{"rounded-t":[i]}],"rounded-r":[{"rounded-r":[i]}],"rounded-b":[{"rounded-b":[i]}],"rounded-l":[{"rounded-l":[i]}],"rounded-ss":[{"rounded-ss":[i]}],"rounded-se":[{"rounded-se":[i]}],"rounded-ee":[{"rounded-ee":[i]}],"rounded-es":[{"rounded-es":[i]}],"rounded-tl":[{"rounded-tl":[i]}],"rounded-tr":[{"rounded-tr":[i]}],"rounded-br":[{"rounded-br":[i]}],"rounded-bl":[{"rounded-bl":[i]}],"border-w":[{border:[l]}],"border-w-x":[{"border-x":[l]}],"border-w-y":[{"border-y":[l]}],"border-w-s":[{"border-s":[l]}],"border-w-e":[{"border-e":[l]}],"border-w-t":[{"border-t":[l]}],"border-w-r":[{"border-r":[l]}],"border-w-b":[{"border-b":[l]}],"border-w-l":[{"border-l":[l]}],"border-opacity":[{"border-opacity":[_]}],"border-style":[{border:[...N(),"hidden"]}],"divide-x":[{"divide-x":[l]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[l]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[_]}],"divide-style":[{divide:N()}],"border-color":[{border:[o]}],"border-color-x":[{"border-x":[o]}],"border-color-y":[{"border-y":[o]}],"border-color-t":[{"border-t":[o]}],"border-color-r":[{"border-r":[o]}],"border-color-b":[{"border-b":[o]}],"border-color-l":[{"border-l":[o]}],"divide-color":[{divide:[o]}],"outline-style":[{outline:["",...N()]}],"outline-offset":[{"outline-offset":[oo,Je]}],"outline-w":[{outline:[oo,Gi]}],"outline-color":[{outline:[e]}],"ring-w":[{ring:ae()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[e]}],"ring-opacity":[{"ring-opacity":[_]}],"ring-offset-w":[{"ring-offset":[oo,Gi]}],"ring-offset-color":[{"ring-offset":[e]}],shadow:[{shadow:["","inner","none",Yi,oF]}],"shadow-color":[{shadow:[cu]}],opacity:[{opacity:[_]}],"mix-blend":[{"mix-blend":ie()}],"bg-blend":[{"bg-blend":ie()}],filter:[{filter:["","none"]}],blur:[{blur:[n]}],brightness:[{brightness:[r]}],contrast:[{contrast:[u]}],"drop-shadow":[{"drop-shadow":["","none",Yi,Je]}],grayscale:[{grayscale:[f]}],"hue-rotate":[{"hue-rotate":[m]}],invert:[{invert:[p]}],saturate:[{saturate:[C]}],sepia:[{sepia:[P]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[n]}],"backdrop-brightness":[{"backdrop-brightness":[r]}],"backdrop-contrast":[{"backdrop-contrast":[u]}],"backdrop-grayscale":[{"backdrop-grayscale":[f]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[m]}],"backdrop-invert":[{"backdrop-invert":[p]}],"backdrop-opacity":[{"backdrop-opacity":[_]}],"backdrop-saturate":[{"backdrop-saturate":[C]}],"backdrop-sepia":[{"backdrop-sepia":[P]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":[s]}],"border-spacing-x":[{"border-spacing-x":[s]}],"border-spacing-y":[{"border-spacing-y":[s]}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["none","all","","colors","opacity","shadow","transform",Je]}],duration:[{duration:ce()}],ease:[{ease:["linear","in","out","in-out",Je]}],delay:[{delay:ce()}],animate:[{animate:["none","spin","ping","pulse","bounce",Je]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[R]}],"scale-x":[{"scale-x":[R]}],"scale-y":[{"scale-y":[R]}],rotate:[{rotate:[lu,Je]}],"translate-x":[{"translate-x":[D]}],"translate-y":[{"translate-y":[D]}],"skew-x":[{"skew-x":[M]}],"skew-y":[{"skew-y":[M]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",Je]}],accent:[{accent:["auto",e]}],appearance:["appearance-none"],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",Je]}],"caret-color":[{caret:[e]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":X()}],"scroll-mx":[{"scroll-mx":X()}],"scroll-my":[{"scroll-my":X()}],"scroll-ms":[{"scroll-ms":X()}],"scroll-me":[{"scroll-me":X()}],"scroll-mt":[{"scroll-mt":X()}],"scroll-mr":[{"scroll-mr":X()}],"scroll-mb":[{"scroll-mb":X()}],"scroll-ml":[{"scroll-ml":X()}],"scroll-p":[{"scroll-p":X()}],"scroll-px":[{"scroll-px":X()}],"scroll-py":[{"scroll-py":X()}],"scroll-ps":[{"scroll-ps":X()}],"scroll-pe":[{"scroll-pe":X()}],"scroll-pt":[{"scroll-pt":X()}],"scroll-pr":[{"scroll-pr":X()}],"scroll-pb":[{"scroll-pb":X()}],"scroll-pl":[{"scroll-pl":X()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",Je]}],fill:[{fill:[e,"none"]}],"stroke-w":[{stroke:[oo,Gi,ch]}],stroke:[{stroke:[e,"none"]}],sr:["sr-only","not-sr-only"]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]}}}const tx=HL(lF),cF=40,fs="inpaint",uh="diffusers_sd",oC="diffusers_sdxl",dh="diffusers_sd_inpaint",iC="diffusers_sdxl_inpaint",d0="diffusers_other",Xy="#ffcc00bb",sC="ldm",aC="cv2",Gk="Fantasy-Studio/Paint-by-Example",uF="timbrooks/instruct-pix2pix",dF="Sanster/PowerPaint-V1-stable-diffusion-inpainting",fF="Sanster/AnyText",hF="out of frame, lowres, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, disfigured, gross proportions, malformed limbs, watermark, signature";function Ce(...e){return tx(Bk(e))}function pF(){async function e(r=""){return(await fetch(r,{method:"GET",cache:"no-cache"})).json()}const t=()=>{const r=document.location;e(r+"/flaskwebgui-keep-server-alive").then(i=>i)},n=3*1e3;t(),setInterval(t,n)}function lC(e){const t=e.split(",")[0].split(":")[1].split(";")[0],n=atob(e.split(",")[1]),r=[];for(let o=0;o{const o=e.src,i=e;i.onload=n,i.onerror=s=>{i.src=o,r(s)},i.src=t})}async function mF(e){const t=URL.createObjectURL(e),n=new Image;return await Vh(n,t),n}function cC(e){return new Promise((t,n)=>{const r=new Image;r.addEventListener("load",()=>{t(r)}),r.addEventListener("error",o=>{n(o)}),r.src=e.toDataURL()})}function gF(e){return new Promise((t,n)=>{const r=new FileReader;r.onload=()=>{const o=new Image;o.onload=()=>{t(o)},o.onerror=()=>{n("无法加载图像。")},o.src=r.result},r.onerror=()=>{n("无法读取文件。")},r.readAsDataURL(e)})}function Nu(e,t,n){return fetch(e).then(function(r){return r.arrayBuffer()}).then(function(r){return new File([r],t,{type:n})})}async function vF(){try{const{state:e}=await navigator.permissions.query({name:"clipboard-write"});return e==="granted"}catch{return!1}}function yF(e,t){return new Promise((n,r)=>e.toBlob(async o=>{o?n(o):r(new Error("Expected toBlob() to be defined"))},t))}const wF=async e=>{const t=[new ClipboardItem({[e.type]:e})];await navigator.clipboard.write(t)};function uC(e){return e.nativeEvent.button===2}function dC(e){return e.nativeEvent.button===1}async function xF(e){const t=await yF(e,"image/png");try{await wF(t)}catch{console.log("Copy image failed!")}}function bF(e,t){const n=document.createElement("a");n.href=e,n.download=t,n.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0,view:window})),setTimeout(()=>{n.remove()},100)}function f0(e){const t=e.nativeEvent;return{x:t.offsetX,y:t.offsetY}}function Yk(e,t,n=Xy){e.strokeStyle=n,e.lineCap="round",e.lineJoin="round",t.forEach(r=>{!(r!=null&&r.pts.length)||!r.size||(e.lineWidth=r.size,e.beginPath(),e.moveTo(r.pts[0].x,r.pts[0].y),r.pts.forEach(o=>e.lineTo(o.x,o.y)),e.stroke())})}const Wh=(e,t,n,r=[],o="white")=>{const i=document.createElement("canvas");i.width=e,i.height=t;const s=i.getContext("2d");if(!s)throw new Error("could not retrieve mask canvas");return r.forEach(l=>{s.drawImage(l,0,0,e,t)}),n.forEach(l=>{Yk(s,l,o)}),i},Du=e=>new Promise((t,n)=>{const r=new FileReader;r.onload=o=>{var s;const i=(s=o.target)==null?void 0:s.result;t(i)},r.onerror=o=>{n(o)},r.readAsDataURL(e)});function Xk(e,t){return function(){return e.apply(t,arguments)}}const{toString:SF}=Object.prototype,{getPrototypeOf:nx}=Object,Tm=(e=>t=>{const n=SF.call(t);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),ei=e=>(e=e.toLowerCase(),t=>Tm(t)===e),Pm=e=>t=>typeof t===e,{isArray:Sc}=Array,rd=Pm("undefined");function _F(e){return e!==null&&!rd(e)&&e.constructor!==null&&!rd(e.constructor)&&Kr(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const Zk=ei("ArrayBuffer");function EF(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&Zk(e.buffer),t}const CF=Pm("string"),Kr=Pm("function"),qk=Pm("number"),Am=e=>e!==null&&typeof e=="object",$F=e=>e===!0||e===!1,Hh=e=>{if(Tm(e)!=="object")return!1;const t=nx(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},RF=ei("Date"),kF=ei("File"),TF=ei("Blob"),PF=ei("FileList"),AF=e=>Am(e)&&Kr(e.pipe),MF=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||Kr(e.append)&&((t=Tm(e))==="formdata"||t==="object"&&Kr(e.toString)&&e.toString()==="[object FormData]"))},OF=ei("URLSearchParams"),NF=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function Nd(e,t,{allOwnKeys:n=!1}={}){if(e===null||typeof e>"u")return;let r,o;if(typeof e!="object"&&(e=[e]),Sc(e))for(r=0,o=e.length;r0;)if(o=n[r],t===o.toLowerCase())return o;return null}const Jk=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,eT=e=>!rd(e)&&e!==Jk;function Zy(){const{caseless:e}=eT(this)&&this||{},t={},n=(r,o)=>{const i=e&&Qk(t,o)||o;Hh(t[i])&&Hh(r)?t[i]=Zy(t[i],r):Hh(r)?t[i]=Zy({},r):Sc(r)?t[i]=r.slice():t[i]=r};for(let r=0,o=arguments.length;r(Nd(t,(o,i)=>{n&&Kr(o)?e[i]=Xk(o,n):e[i]=o},{allOwnKeys:r}),e),IF=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),LF=(e,t,n,r)=>{e.prototype=Object.create(t.prototype,r),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),n&&Object.assign(e.prototype,n)},FF=(e,t,n,r)=>{let o,i,s;const l={};if(t=t||{},e==null)return t;do{for(o=Object.getOwnPropertyNames(e),i=o.length;i-- >0;)s=o[i],(!r||r(s,e,t))&&!l[s]&&(t[s]=e[s],l[s]=!0);e=n!==!1&&nx(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},jF=(e,t,n)=>{e=String(e),(n===void 0||n>e.length)&&(n=e.length),n-=t.length;const r=e.indexOf(t,n);return r!==-1&&r===n},zF=e=>{if(!e)return null;if(Sc(e))return e;let t=e.length;if(!qk(t))return null;const n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},BF=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&nx(Uint8Array)),UF=(e,t)=>{const r=(e&&e[Symbol.iterator]).call(e);let o;for(;(o=r.next())&&!o.done;){const i=o.value;t.call(e,i[0],i[1])}},VF=(e,t)=>{let n;const r=[];for(;(n=e.exec(t))!==null;)r.push(n);return r},WF=ei("HTMLFormElement"),HF=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,r,o){return r.toUpperCase()+o}),fC=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),KF=ei("RegExp"),tT=(e,t)=>{const n=Object.getOwnPropertyDescriptors(e),r={};Nd(n,(o,i)=>{let s;(s=t(o,i,e))!==!1&&(r[i]=s||o)}),Object.defineProperties(e,r)},GF=e=>{tT(e,(t,n)=>{if(Kr(e)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;const r=e[n];if(Kr(r)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},YF=(e,t)=>{const n={},r=o=>{o.forEach(i=>{n[i]=!0})};return Sc(e)?r(e):r(String(e).split(t)),n},XF=()=>{},ZF=(e,t)=>(e=+e,Number.isFinite(e)?e:t),h0="abcdefghijklmnopqrstuvwxyz",hC="0123456789",nT={DIGIT:hC,ALPHA:h0,ALPHA_DIGIT:h0+h0.toUpperCase()+hC},qF=(e=16,t=nT.ALPHA_DIGIT)=>{let n="";const{length:r}=t;for(;e--;)n+=t[Math.random()*r|0];return n};function QF(e){return!!(e&&Kr(e.append)&&e[Symbol.toStringTag]==="FormData"&&e[Symbol.iterator])}const JF=e=>{const t=new Array(10),n=(r,o)=>{if(Am(r)){if(t.indexOf(r)>=0)return;if(!("toJSON"in r)){t[o]=r;const i=Sc(r)?[]:{};return Nd(r,(s,l)=>{const u=n(s,o+1);!rd(u)&&(i[l]=u)}),t[o]=void 0,i}}return r};return n(e,0)},ej=ei("AsyncFunction"),tj=e=>e&&(Am(e)||Kr(e))&&Kr(e.then)&&Kr(e.catch),oe={isArray:Sc,isArrayBuffer:Zk,isBuffer:_F,isFormData:MF,isArrayBufferView:EF,isString:CF,isNumber:qk,isBoolean:$F,isObject:Am,isPlainObject:Hh,isUndefined:rd,isDate:RF,isFile:kF,isBlob:TF,isRegExp:KF,isFunction:Kr,isStream:AF,isURLSearchParams:OF,isTypedArray:BF,isFileList:PF,forEach:Nd,merge:Zy,extend:DF,trim:NF,stripBOM:IF,inherits:LF,toFlatObject:FF,kindOf:Tm,kindOfTest:ei,endsWith:jF,toArray:zF,forEachEntry:UF,matchAll:VF,isHTMLForm:WF,hasOwnProperty:fC,hasOwnProp:fC,reduceDescriptors:tT,freezeMethods:GF,toObjectSet:YF,toCamelCase:HF,noop:XF,toFiniteNumber:ZF,findKey:Qk,global:Jk,isContextDefined:eT,ALPHABET:nT,generateString:qF,isSpecCompliantForm:QF,toJSONObject:JF,isAsyncFn:ej,isThenable:tj};function ut(e,t,n,r,o){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),n&&(this.config=n),r&&(this.request=r),o&&(this.response=o)}oe.inherits(ut,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:oe.toJSONObject(this.config),code:this.code,status:this.response&&this.response.status?this.response.status:null}}});const rT=ut.prototype,oT={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{oT[e]={value:e}});Object.defineProperties(ut,oT);Object.defineProperty(rT,"isAxiosError",{value:!0});ut.from=(e,t,n,r,o,i)=>{const s=Object.create(rT);return oe.toFlatObject(e,s,function(u){return u!==Error.prototype},l=>l!=="isAxiosError"),ut.call(s,e.message,t,n,r,o),s.cause=e,s.name=e.name,i&&Object.assign(s,i),s};const nj=null;function qy(e){return oe.isPlainObject(e)||oe.isArray(e)}function iT(e){return oe.endsWith(e,"[]")?e.slice(0,-2):e}function pC(e,t,n){return e?e.concat(t).map(function(o,i){return o=iT(o),!n&&i?"["+o+"]":o}).join(n?".":""):t}function rj(e){return oe.isArray(e)&&!e.some(qy)}const oj=oe.toFlatObject(oe,{},null,function(t){return/^is[A-Z]/.test(t)});function Mm(e,t,n){if(!oe.isObject(e))throw new TypeError("target must be an object");t=t||new FormData,n=oe.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(S,E){return!oe.isUndefined(E[S])});const r=n.metaTokens,o=n.visitor||m,i=n.dots,s=n.indexes,u=(n.Blob||typeof Blob<"u"&&Blob)&&oe.isSpecCompliantForm(t);if(!oe.isFunction(o))throw new TypeError("visitor must be a function");function f(b){if(b===null)return"";if(oe.isDate(b))return b.toISOString();if(!u&&oe.isBlob(b))throw new ut("Blob is not supported. Use a Buffer instead.");return oe.isArrayBuffer(b)||oe.isTypedArray(b)?u&&typeof Blob=="function"?new Blob([b]):Buffer.from(b):b}function m(b,S,E){let _=b;if(b&&!E&&typeof b=="object"){if(oe.endsWith(S,"{}"))S=r?S:S.slice(0,-2),b=JSON.stringify(b);else if(oe.isArray(b)&&rj(b)||(oe.isFileList(b)||oe.endsWith(S,"[]"))&&(_=oe.toArray(b)))return S=iT(S),_.forEach(function(C,R){!(oe.isUndefined(C)||C===null)&&t.append(s===!0?pC([S],R,i):s===null?S:S+"[]",f(C))}),!1}return qy(b)?!0:(t.append(pC(E,S,i),f(b)),!1)}const p=[],g=Object.assign(oj,{defaultVisitor:m,convertValue:f,isVisitable:qy});function y(b,S){if(!oe.isUndefined(b)){if(p.indexOf(b)!==-1)throw Error("Circular reference detected in "+S.join("."));p.push(b),oe.forEach(b,function(_,x){(!(oe.isUndefined(_)||_===null)&&o.call(t,_,oe.isString(x)?x.trim():x,S,g))===!0&&y(_,S?S.concat(x):[x])}),p.pop()}}if(!oe.isObject(e))throw new TypeError("data must be an object");return y(e),t}function mC(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(r){return t[r]})}function rx(e,t){this._pairs=[],e&&Mm(e,this,t)}const sT=rx.prototype;sT.append=function(t,n){this._pairs.push([t,n])};sT.toString=function(t){const n=t?function(r){return t.call(this,r,mC)}:mC;return this._pairs.map(function(o){return n(o[0])+"="+n(o[1])},"").join("&")};function ij(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function aT(e,t,n){if(!t)return e;const r=n&&n.encode||ij,o=n&&n.serialize;let i;if(o?i=o(t,n):i=oe.isURLSearchParams(t)?t.toString():new rx(t,n).toString(r),i){const s=e.indexOf("#");s!==-1&&(e=e.slice(0,s)),e+=(e.indexOf("?")===-1?"?":"&")+i}return e}class sj{constructor(){this.handlers=[]}use(t,n,r){return this.handlers.push({fulfilled:t,rejected:n,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){oe.forEach(this.handlers,function(r){r!==null&&t(r)})}}const gC=sj,lT={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},aj=typeof URLSearchParams<"u"?URLSearchParams:rx,lj=typeof FormData<"u"?FormData:null,cj=typeof Blob<"u"?Blob:null,uj={isBrowser:!0,classes:{URLSearchParams:aj,FormData:lj,Blob:cj},protocols:["http","https","file","blob","url","data"]},cT=typeof window<"u"&&typeof document<"u",dj=(e=>cT&&["ReactNative","NativeScript","NS"].indexOf(e)<0)(typeof navigator<"u"&&navigator.product),fj=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",hj=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:cT,hasStandardBrowserEnv:dj,hasStandardBrowserWebWorkerEnv:fj},Symbol.toStringTag,{value:"Module"})),zo={...hj,...uj};function pj(e,t){return Mm(e,new zo.classes.URLSearchParams,Object.assign({visitor:function(n,r,o,i){return zo.isNode&&oe.isBuffer(n)?(this.append(r,n.toString("base64")),!1):i.defaultVisitor.apply(this,arguments)}},t))}function mj(e){return oe.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function gj(e){const t={},n=Object.keys(e);let r;const o=n.length;let i;for(r=0;r=n.length;return s=!s&&oe.isArray(o)?o.length:s,u?(oe.hasOwnProp(o,s)?o[s]=[o[s],r]:o[s]=r,!l):((!o[s]||!oe.isObject(o[s]))&&(o[s]=[]),t(n,r,o[s],i)&&oe.isArray(o[s])&&(o[s]=gj(o[s])),!l)}if(oe.isFormData(e)&&oe.isFunction(e.entries)){const n={};return oe.forEachEntry(e,(r,o)=>{t(mj(r),o,n,0)}),n}return null}function vj(e,t,n){if(oe.isString(e))try{return(t||JSON.parse)(e),oe.trim(e)}catch(r){if(r.name!=="SyntaxError")throw r}return(n||JSON.stringify)(e)}const ox={transitional:lT,adapter:["xhr","http"],transformRequest:[function(t,n){const r=n.getContentType()||"",o=r.indexOf("application/json")>-1,i=oe.isObject(t);if(i&&oe.isHTMLForm(t)&&(t=new FormData(t)),oe.isFormData(t))return o&&o?JSON.stringify(uT(t)):t;if(oe.isArrayBuffer(t)||oe.isBuffer(t)||oe.isStream(t)||oe.isFile(t)||oe.isBlob(t))return t;if(oe.isArrayBufferView(t))return t.buffer;if(oe.isURLSearchParams(t))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let l;if(i){if(r.indexOf("application/x-www-form-urlencoded")>-1)return pj(t,this.formSerializer).toString();if((l=oe.isFileList(t))||r.indexOf("multipart/form-data")>-1){const u=this.env&&this.env.FormData;return Mm(l?{"files[]":t}:t,u&&new u,this.formSerializer)}}return i||o?(n.setContentType("application/json",!1),vj(t)):t}],transformResponse:[function(t){const n=this.transitional||ox.transitional,r=n&&n.forcedJSONParsing,o=this.responseType==="json";if(t&&oe.isString(t)&&(r&&!this.responseType||o)){const s=!(n&&n.silentJSONParsing)&&o;try{return JSON.parse(t)}catch(l){if(s)throw l.name==="SyntaxError"?ut.from(l,ut.ERR_BAD_RESPONSE,this,null,this.response):l}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:zo.classes.FormData,Blob:zo.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};oe.forEach(["delete","get","head","post","put","patch"],e=>{ox.headers[e]={}});const ix=ox,yj=oe.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),wj=e=>{const t={};let n,r,o;return e&&e.split(` +`).forEach(function(s){o=s.indexOf(":"),n=s.substring(0,o).trim().toLowerCase(),r=s.substring(o+1).trim(),!(!n||t[n]&&yj[n])&&(n==="set-cookie"?t[n]?t[n].push(r):t[n]=[r]:t[n]=t[n]?t[n]+", "+r:r)}),t},vC=Symbol("internals");function uu(e){return e&&String(e).trim().toLowerCase()}function Kh(e){return e===!1||e==null?e:oe.isArray(e)?e.map(Kh):String(e)}function xj(e){const t=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=n.exec(e);)t[r[1]]=r[2];return t}const bj=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function p0(e,t,n,r,o){if(oe.isFunction(r))return r.call(this,t,n);if(o&&(t=n),!!oe.isString(t)){if(oe.isString(r))return t.indexOf(r)!==-1;if(oe.isRegExp(r))return r.test(t)}}function Sj(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,n,r)=>n.toUpperCase()+r)}function _j(e,t){const n=oe.toCamelCase(" "+t);["get","set","has"].forEach(r=>{Object.defineProperty(e,r+n,{value:function(o,i,s){return this[r].call(this,t,o,i,s)},configurable:!0})})}class Om{constructor(t){t&&this.set(t)}set(t,n,r){const o=this;function i(l,u,f){const m=uu(u);if(!m)throw new Error("header name must be a non-empty string");const p=oe.findKey(o,m);(!p||o[p]===void 0||f===!0||f===void 0&&o[p]!==!1)&&(o[p||u]=Kh(l))}const s=(l,u)=>oe.forEach(l,(f,m)=>i(f,m,u));return oe.isPlainObject(t)||t instanceof this.constructor?s(t,n):oe.isString(t)&&(t=t.trim())&&!bj(t)?s(wj(t),n):t!=null&&i(n,t,r),this}get(t,n){if(t=uu(t),t){const r=oe.findKey(this,t);if(r){const o=this[r];if(!n)return o;if(n===!0)return xj(o);if(oe.isFunction(n))return n.call(this,o,r);if(oe.isRegExp(n))return n.exec(o);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,n){if(t=uu(t),t){const r=oe.findKey(this,t);return!!(r&&this[r]!==void 0&&(!n||p0(this,this[r],r,n)))}return!1}delete(t,n){const r=this;let o=!1;function i(s){if(s=uu(s),s){const l=oe.findKey(r,s);l&&(!n||p0(r,r[l],l,n))&&(delete r[l],o=!0)}}return oe.isArray(t)?t.forEach(i):i(t),o}clear(t){const n=Object.keys(this);let r=n.length,o=!1;for(;r--;){const i=n[r];(!t||p0(this,this[i],i,t,!0))&&(delete this[i],o=!0)}return o}normalize(t){const n=this,r={};return oe.forEach(this,(o,i)=>{const s=oe.findKey(r,i);if(s){n[s]=Kh(o),delete n[i];return}const l=t?Sj(i):String(i).trim();l!==i&&delete n[i],n[l]=Kh(o),r[l]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){const n=Object.create(null);return oe.forEach(this,(r,o)=>{r!=null&&r!==!1&&(n[o]=t&&oe.isArray(r)?r.join(", "):r)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,n])=>t+": "+n).join(` +`)}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...n){const r=new this(t);return n.forEach(o=>r.set(o)),r}static accessor(t){const r=(this[vC]=this[vC]={accessors:{}}).accessors,o=this.prototype;function i(s){const l=uu(s);r[l]||(_j(o,s),r[l]=!0)}return oe.isArray(t)?t.forEach(i):i(t),this}}Om.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);oe.reduceDescriptors(Om.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(r){this[n]=r}}});oe.freezeMethods(Om);const xi=Om;function m0(e,t){const n=this||ix,r=t||n,o=xi.from(r.headers);let i=r.data;return oe.forEach(e,function(l){i=l.call(n,i,o.normalize(),t?t.status:void 0)}),o.normalize(),i}function dT(e){return!!(e&&e.__CANCEL__)}function Dd(e,t,n){ut.call(this,e??"canceled",ut.ERR_CANCELED,t,n),this.name="CanceledError"}oe.inherits(Dd,ut,{__CANCEL__:!0});function Ej(e,t,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?e(n):t(new ut("Request failed with status code "+n.status,[ut.ERR_BAD_REQUEST,ut.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}const Cj=zo.hasStandardBrowserEnv?{write(e,t,n,r,o,i){const s=[e+"="+encodeURIComponent(t)];oe.isNumber(n)&&s.push("expires="+new Date(n).toGMTString()),oe.isString(r)&&s.push("path="+r),oe.isString(o)&&s.push("domain="+o),i===!0&&s.push("secure"),document.cookie=s.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function $j(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function Rj(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e}function fT(e,t){return e&&!$j(t)?Rj(e,t):t}const kj=zo.hasStandardBrowserEnv?function(){const t=/(msie|trident)/i.test(navigator.userAgent),n=document.createElement("a");let r;function o(i){let s=i;return t&&(n.setAttribute("href",s),s=n.href),n.setAttribute("href",s),{href:n.href,protocol:n.protocol?n.protocol.replace(/:$/,""):"",host:n.host,search:n.search?n.search.replace(/^\?/,""):"",hash:n.hash?n.hash.replace(/^#/,""):"",hostname:n.hostname,port:n.port,pathname:n.pathname.charAt(0)==="/"?n.pathname:"/"+n.pathname}}return r=o(window.location.href),function(s){const l=oe.isString(s)?o(s):s;return l.protocol===r.protocol&&l.host===r.host}}():function(){return function(){return!0}}();function Tj(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function Pj(e,t){e=e||10;const n=new Array(e),r=new Array(e);let o=0,i=0,s;return t=t!==void 0?t:1e3,function(u){const f=Date.now(),m=r[i];s||(s=f),n[o]=u,r[o]=f;let p=i,g=0;for(;p!==o;)g+=n[p++],p=p%e;if(o=(o+1)%e,o===i&&(i=(i+1)%e),f-s{const i=o.loaded,s=o.lengthComputable?o.total:void 0,l=i-n,u=r(l),f=i<=s;n=i;const m={loaded:i,total:s,progress:s?i/s:void 0,bytes:l,rate:u||void 0,estimated:u&&s&&f?(s-i)/u:void 0,event:o};m[t?"download":"upload"]=!0,e(m)}}const Aj=typeof XMLHttpRequest<"u",Mj=Aj&&function(e){return new Promise(function(n,r){let o=e.data;const i=xi.from(e.headers).normalize();let{responseType:s,withXSRFToken:l}=e,u;function f(){e.cancelToken&&e.cancelToken.unsubscribe(u),e.signal&&e.signal.removeEventListener("abort",u)}let m;if(oe.isFormData(o)){if(zo.hasStandardBrowserEnv||zo.hasStandardBrowserWebWorkerEnv)i.setContentType(!1);else if((m=i.getContentType())!==!1){const[S,...E]=m?m.split(";").map(_=>_.trim()).filter(Boolean):[];i.setContentType([S||"multipart/form-data",...E].join("; "))}}let p=new XMLHttpRequest;if(e.auth){const S=e.auth.username||"",E=e.auth.password?unescape(encodeURIComponent(e.auth.password)):"";i.set("Authorization","Basic "+btoa(S+":"+E))}const g=fT(e.baseURL,e.url);p.open(e.method.toUpperCase(),aT(g,e.params,e.paramsSerializer),!0),p.timeout=e.timeout;function y(){if(!p)return;const S=xi.from("getAllResponseHeaders"in p&&p.getAllResponseHeaders()),_={data:!s||s==="text"||s==="json"?p.responseText:p.response,status:p.status,statusText:p.statusText,headers:S,config:e,request:p};Ej(function(C){n(C),f()},function(C){r(C),f()},_),p=null}if("onloadend"in p?p.onloadend=y:p.onreadystatechange=function(){!p||p.readyState!==4||p.status===0&&!(p.responseURL&&p.responseURL.indexOf("file:")===0)||setTimeout(y)},p.onabort=function(){p&&(r(new ut("Request aborted",ut.ECONNABORTED,e,p)),p=null)},p.onerror=function(){r(new ut("Network Error",ut.ERR_NETWORK,e,p)),p=null},p.ontimeout=function(){let E=e.timeout?"timeout of "+e.timeout+"ms exceeded":"timeout exceeded";const _=e.transitional||lT;e.timeoutErrorMessage&&(E=e.timeoutErrorMessage),r(new ut(E,_.clarifyTimeoutError?ut.ETIMEDOUT:ut.ECONNABORTED,e,p)),p=null},zo.hasStandardBrowserEnv&&(l&&oe.isFunction(l)&&(l=l(e)),l||l!==!1&&kj(g))){const S=e.xsrfHeaderName&&e.xsrfCookieName&&Cj.read(e.xsrfCookieName);S&&i.set(e.xsrfHeaderName,S)}o===void 0&&i.setContentType(null),"setRequestHeader"in p&&oe.forEach(i.toJSON(),function(E,_){p.setRequestHeader(_,E)}),oe.isUndefined(e.withCredentials)||(p.withCredentials=!!e.withCredentials),s&&s!=="json"&&(p.responseType=e.responseType),typeof e.onDownloadProgress=="function"&&p.addEventListener("progress",yC(e.onDownloadProgress,!0)),typeof e.onUploadProgress=="function"&&p.upload&&p.upload.addEventListener("progress",yC(e.onUploadProgress)),(e.cancelToken||e.signal)&&(u=S=>{p&&(r(!S||S.type?new Dd(null,e,p):S),p.abort(),p=null)},e.cancelToken&&e.cancelToken.subscribe(u),e.signal&&(e.signal.aborted?u():e.signal.addEventListener("abort",u)));const b=Tj(g);if(b&&zo.protocols.indexOf(b)===-1){r(new ut("Unsupported protocol "+b+":",ut.ERR_BAD_REQUEST,e));return}p.send(o||null)})},Qy={http:nj,xhr:Mj};oe.forEach(Qy,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});const wC=e=>`- ${e}`,Oj=e=>oe.isFunction(e)||e===null||e===!1,hT={getAdapter:e=>{e=oe.isArray(e)?e:[e];const{length:t}=e;let n,r;const o={};for(let i=0;i`adapter ${l} `+(u===!1?"is not supported by the environment":"is not available in the build"));let s=t?i.length>1?`since : +`+i.map(wC).join(` +`):" "+wC(i[0]):"as no adapter specified";throw new ut("There is no suitable adapter to dispatch the request "+s,"ERR_NOT_SUPPORT")}return r},adapters:Qy};function g0(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Dd(null,e)}function xC(e){return g0(e),e.headers=xi.from(e.headers),e.data=m0.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),hT.getAdapter(e.adapter||ix.adapter)(e).then(function(r){return g0(e),r.data=m0.call(e,e.transformResponse,r),r.headers=xi.from(r.headers),r},function(r){return dT(r)||(g0(e),r&&r.response&&(r.response.data=m0.call(e,e.transformResponse,r.response),r.response.headers=xi.from(r.response.headers))),Promise.reject(r)})}const bC=e=>e instanceof xi?e.toJSON():e;function ic(e,t){t=t||{};const n={};function r(f,m,p){return oe.isPlainObject(f)&&oe.isPlainObject(m)?oe.merge.call({caseless:p},f,m):oe.isPlainObject(m)?oe.merge({},m):oe.isArray(m)?m.slice():m}function o(f,m,p){if(oe.isUndefined(m)){if(!oe.isUndefined(f))return r(void 0,f,p)}else return r(f,m,p)}function i(f,m){if(!oe.isUndefined(m))return r(void 0,m)}function s(f,m){if(oe.isUndefined(m)){if(!oe.isUndefined(f))return r(void 0,f)}else return r(void 0,m)}function l(f,m,p){if(p in t)return r(f,m);if(p in e)return r(void 0,f)}const u={url:i,method:i,data:i,baseURL:s,transformRequest:s,transformResponse:s,paramsSerializer:s,timeout:s,timeoutMessage:s,withCredentials:s,withXSRFToken:s,adapter:s,responseType:s,xsrfCookieName:s,xsrfHeaderName:s,onUploadProgress:s,onDownloadProgress:s,decompress:s,maxContentLength:s,maxBodyLength:s,beforeRedirect:s,transport:s,httpAgent:s,httpsAgent:s,cancelToken:s,socketPath:s,responseEncoding:s,validateStatus:l,headers:(f,m)=>o(bC(f),bC(m),!0)};return oe.forEach(Object.keys(Object.assign({},e,t)),function(m){const p=u[m]||o,g=p(e[m],t[m],m);oe.isUndefined(g)&&p!==l||(n[m]=g)}),n}const pT="1.6.2",sx={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{sx[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const SC={};sx.transitional=function(t,n,r){function o(i,s){return"[Axios v"+pT+"] Transitional option '"+i+"'"+s+(r?". "+r:"")}return(i,s,l)=>{if(t===!1)throw new ut(o(s," has been removed"+(n?" in "+n:"")),ut.ERR_DEPRECATED);return n&&!SC[s]&&(SC[s]=!0,console.warn(o(s," has been deprecated since v"+n+" and will be removed in the near future"))),t?t(i,s,l):!0}};function Nj(e,t,n){if(typeof e!="object")throw new ut("options must be an object",ut.ERR_BAD_OPTION_VALUE);const r=Object.keys(e);let o=r.length;for(;o-- >0;){const i=r[o],s=t[i];if(s){const l=e[i],u=l===void 0||s(l,i,e);if(u!==!0)throw new ut("option "+i+" must be "+u,ut.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new ut("Unknown option "+i,ut.ERR_BAD_OPTION)}}const Jy={assertOptions:Nj,validators:sx},Xi=Jy.validators;class Op{constructor(t){this.defaults=t,this.interceptors={request:new gC,response:new gC}}request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=ic(this.defaults,n);const{transitional:r,paramsSerializer:o,headers:i}=n;r!==void 0&&Jy.assertOptions(r,{silentJSONParsing:Xi.transitional(Xi.boolean),forcedJSONParsing:Xi.transitional(Xi.boolean),clarifyTimeoutError:Xi.transitional(Xi.boolean)},!1),o!=null&&(oe.isFunction(o)?n.paramsSerializer={serialize:o}:Jy.assertOptions(o,{encode:Xi.function,serialize:Xi.function},!0)),n.method=(n.method||this.defaults.method||"get").toLowerCase();let s=i&&oe.merge(i.common,i[n.method]);i&&oe.forEach(["delete","get","head","post","put","patch","common"],b=>{delete i[b]}),n.headers=xi.concat(s,i);const l=[];let u=!0;this.interceptors.request.forEach(function(S){typeof S.runWhen=="function"&&S.runWhen(n)===!1||(u=u&&S.synchronous,l.unshift(S.fulfilled,S.rejected))});const f=[];this.interceptors.response.forEach(function(S){f.push(S.fulfilled,S.rejected)});let m,p=0,g;if(!u){const b=[xC.bind(this),void 0];for(b.unshift.apply(b,l),b.push.apply(b,f),g=b.length,m=Promise.resolve(n);p{if(!r._listeners)return;let i=r._listeners.length;for(;i-- >0;)r._listeners[i](o);r._listeners=null}),this.promise.then=o=>{let i;const s=new Promise(l=>{r.subscribe(l),i=l}).then(o);return s.cancel=function(){r.unsubscribe(i)},s},t(function(i,s,l){r.reason||(r.reason=new Dd(i,s,l),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}static source(){let t;return{token:new ax(function(o){t=o}),cancel:t}}}const Dj=ax;function Ij(e){return function(n){return e.apply(null,n)}}function Lj(e){return oe.isObject(e)&&e.isAxiosError===!0}const e1={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(e1).forEach(([e,t])=>{e1[t]=e});const Fj=e1;function mT(e){const t=new Gh(e),n=Xk(Gh.prototype.request,t);return oe.extend(n,Gh.prototype,t,{allOwnKeys:!0}),oe.extend(n,t,null,{allOwnKeys:!0}),n.create=function(o){return mT(ic(e,o))},n}const Qt=mT(ix);Qt.Axios=Gh;Qt.CanceledError=Dd;Qt.CancelToken=Dj;Qt.isCancel=dT;Qt.VERSION=pT;Qt.toFormData=Mm;Qt.AxiosError=ut;Qt.Cancel=Qt.CanceledError;Qt.all=function(t){return Promise.all(t)};Qt.spread=Ij;Qt.isAxiosError=Lj;Qt.mergeConfig=ic;Qt.AxiosHeaders=xi;Qt.formToJSON=e=>uT(oe.isHTMLForm(e)?new FormData(e):e);Qt.getAdapter=hT.getAdapter;Qt.HttpStatusCode=Fj;Qt.default=Qt;const jj=Qt,Ls="/api/v1",_c=jj.create({baseURL:Ls});async function zj(e,t,n,r,o,i=null){const s=await Du(e),l=await Du(o),u=i?await Du(i):null,f=await fetch(`${Ls}/inpaint`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({image:s,mask:l,ldm_steps:t.ldmSteps,ldm_sampler:t.ldmSampler,zits_wireframe:t.zitsWireframe,cv2_flag:t.cv2Flag,cv2_radius:t.cv2Radius,hd_strategy:"Crop",hd_strategy_crop_triger_size:640,hd_strategy_crop_margin:128,hd_trategy_resize_imit:2048,prompt:t.prompt,negative_prompt:t.negativePrompt,use_croper:t.showCropper,croper_x:n.x,croper_y:n.y,croper_height:n.height,croper_width:n.width,use_extender:t.showExtender,extender_x:r.x,extender_y:r.y,extender_height:r.height,extender_width:r.width,sd_mask_blur:t.sdMaskBlur,sd_strength:t.sdStrength,sd_steps:t.sdSteps,sd_guidance_scale:t.sdGuidanceScale,sd_sampler:t.sdSampler,sd_seed:t.seedFixed?t.seed:-1,sd_match_histograms:t.sdMatchHistograms,sd_freeu:t.enableFreeu,sd_freeu_config:t.freeuConfig,sd_lcm_lora:t.enableLCMLora,paint_by_example_example_image:u,p2p_image_guidance_scale:t.p2pImageGuidanceScale,enable_controlnet:t.enableControlnet,controlnet_conditioning_scale:t.controlnetConditioningScale,controlnet_method:t.controlnetMethod?t.controlnetMethod:"",powerpaint_task:t.showExtender?Ol.outpainting:t.powerpaintTask})});if(f.ok){const p=await f.blob();return{blob:URL.createObjectURL(p),seed:f.headers.get("X-Seed")}}const m=await f.json();throw new Error(`Something went wrong: ${m.errors}`)}async function gT(){return(await _c.get("/server-config")).data}async function Bj(e){return(await _c.post("/model",{name:e})).data}async function v0(e,t){return _c.post("/switch_plugin_model",{plugin_name:e,model_name:t})}async function Uj(){return(await _c.get("/model")).data}async function vT(e,t,n,r,o){const i=await Du(n),l=await fetch(`${Ls}/${e?"run_plugin_gen_mask":"run_plugin_gen_image"}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t,image:i,upscale:r,clicks:o})});if(l.ok){const f=await l.blob();return{blob:URL.createObjectURL(f)}}const u=await l.json();throw new Error(u)}async function Vj(e,t){const n=await fetch(`${Ls}/media_file?tab=${e}&filename=${encodeURIComponent(t)}`,{method:"GET"});if(n.ok){const o=await n.blob();return new File([o],t,{type:n.headers.get("Content-Type")??"image/png"})}const r=await n.json();throw new Error(r.errors)}async function Wj(e){return(await _c.get("medias",{params:{tab:e}})).data}async function Hj(e,t,n){const r=await Nu(e.src,t,n),o=new FormData;o.append("file",r);try{const i=await fetch(`${Ls}/save_image`,{method:"POST",body:o});if(!i.ok){const s=await i.text();throw new Error(s)}}catch(i){throw new Error(`Something went wrong: ${i}`)}}async function Kj(e){const t=new FormData;return t.append("file",e),(await _c.post("/gen-info",t)).data}async function Gj(e,t,n){const r=await Du(e),o=await fetch(`${Ls}/adjust_mask`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mask:r,operate:t,kernel_size:n})});if(o.ok)return await o.blob();const i=await o.json();throw new Error(i)}function Yj(){const[e,t]=d.useState(null),n=d.useCallback(()=>{const r=new Headers;r.append("pragma","no-cache"),r.append("cache-control","no-cache"),fetch(`${Ls}/inputimage`,{headers:r}).then(async o=>{var l;if(!o.ok)return;const i=(l=o.headers.get("content-disposition"))==null?void 0:l.split("filename=")[1].split(";")[0],s=await o.blob();if(s&&s.type.startsWith("image")){const u=new File([s],i!==void 0?i:"inputImage");t(u)}}).catch(o=>{console.log(o)})},[t]);return d.useEffect(()=>{n()},[n]),e}function _o(e,t){if(e==null)return{};var n={},r=Object.keys(e),o,i;for(i=0;i=0)&&(n[o]=e[o]);return n}var Xj=["color"],Zj=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,Xj);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.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:r,fillRule:"evenodd",clipRule:"evenodd"}))}),qj=["color"],yT=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,qj);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M11.4669 3.72684C11.7558 3.91574 11.8369 4.30308 11.648 4.59198L7.39799 11.092C7.29783 11.2452 7.13556 11.3467 6.95402 11.3699C6.77247 11.3931 6.58989 11.3355 6.45446 11.2124L3.70446 8.71241C3.44905 8.48022 3.43023 8.08494 3.66242 7.82953C3.89461 7.57412 4.28989 7.55529 4.5453 7.78749L6.75292 9.79441L10.6018 3.90792C10.7907 3.61902 11.178 3.53795 11.4669 3.72684Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),Qj=["color"],Jj=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,Qj);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M3.13523 6.15803C3.3241 5.95657 3.64052 5.94637 3.84197 6.13523L7.5 9.56464L11.158 6.13523C11.3595 5.94637 11.6759 5.95657 11.8648 6.15803C12.0536 6.35949 12.0434 6.67591 11.842 6.86477L7.84197 10.6148C7.64964 10.7951 7.35036 10.7951 7.15803 10.6148L3.15803 6.86477C2.95657 6.67591 2.94637 6.35949 3.13523 6.15803Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),ez=["color"],tz=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,ez);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M6.1584 3.13508C6.35985 2.94621 6.67627 2.95642 6.86514 3.15788L10.6151 7.15788C10.7954 7.3502 10.7954 7.64949 10.6151 7.84182L6.86514 11.8418C6.67627 12.0433 6.35985 12.0535 6.1584 11.8646C5.95694 11.6757 5.94673 11.3593 6.1356 11.1579L9.565 7.49985L6.1356 3.84182C5.94673 3.64036 5.95694 3.32394 6.1584 3.13508Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),nz=["color"],rz=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,nz);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M3.13523 8.84197C3.3241 9.04343 3.64052 9.05363 3.84197 8.86477L7.5 5.43536L11.158 8.86477C11.3595 9.05363 11.6759 9.04343 11.8648 8.84197C12.0536 8.64051 12.0434 8.32409 11.842 8.13523L7.84197 4.38523C7.64964 4.20492 7.35036 4.20492 7.15803 4.38523L3.15803 8.13523C2.95657 8.32409 2.94637 8.64051 3.13523 8.84197Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),oz=["color"],wT=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,oz);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.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:r,fillRule:"evenodd",clipRule:"evenodd"}))}),iz=["color"],sz=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,iz);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M9.875 7.5C9.875 8.81168 8.81168 9.875 7.5 9.875C6.18832 9.875 5.125 8.81168 5.125 7.5C5.125 6.18832 6.18832 5.125 7.5 5.125C8.81168 5.125 9.875 6.18832 9.875 7.5Z",fill:r}))}),az=["color"],lz=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,az);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M10 6.5C10 8.433 8.433 10 6.5 10C4.567 10 3 8.433 3 6.5C3 4.567 4.567 3 6.5 3C8.433 3 10 4.567 10 6.5ZM9.30884 10.0159C8.53901 10.6318 7.56251 11 6.5 11C4.01472 11 2 8.98528 2 6.5C2 4.01472 4.01472 2 6.5 2C8.98528 2 11 4.01472 11 6.5C11 7.56251 10.6318 8.53901 10.0159 9.30884L12.8536 12.1464C13.0488 12.3417 13.0488 12.6583 12.8536 12.8536C12.6583 13.0488 12.3417 13.0488 12.1464 12.8536L9.30884 10.0159Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),cz=["color"],uz=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,cz);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M3.24182 2.32181C3.3919 2.23132 3.5784 2.22601 3.73338 2.30781L12.7334 7.05781C12.8974 7.14436 13 7.31457 13 7.5C13 7.68543 12.8974 7.85564 12.7334 7.94219L3.73338 12.6922C3.5784 12.774 3.3919 12.7687 3.24182 12.6782C3.09175 12.5877 3 12.4252 3 12.25V2.75C3 2.57476 3.09175 2.4123 3.24182 2.32181ZM4 3.57925V11.4207L11.4288 7.5L4 3.57925Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),dz=["color"],fz=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,dz);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M7 2H1.5C1.22386 2 1 2.22386 1 2.5V7H7V2ZM8 2V7H14V2.5C14 2.22386 13.7761 2 13.5 2H8ZM7 8H1V12.5C1 12.7761 1.22386 13 1.5 13H7V8ZM8 13V8H14V12.5C14 12.7761 13.7761 13 13.5 13H8ZM1.5 1C0.671573 1 0 1.67157 0 2.5V12.5C0 13.3284 0.671573 14 1.5 14H13.5C14.3284 14 15 13.3284 15 12.5V2.5C15 1.67157 14.3284 1 13.5 1H1.5Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),hz=["color"],pz=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,hz);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M1.5 2H13.5C13.7761 2 14 2.22386 14 2.5V7H1V2.5C1 2.22386 1.22386 2 1.5 2ZM1 8V12.5C1 12.7761 1.22386 13 1.5 13H13.5C13.7761 13 14 12.7761 14 12.5V8H1ZM0 2.5C0 1.67157 0.671573 1 1.5 1H13.5C14.3284 1 15 1.67157 15 2.5V12.5C15 13.3284 14.3284 14 13.5 14H1.5C0.671573 14 0 13.3284 0 12.5V2.5Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))});function Y(){return Y=Object.assign?Object.assign.bind():function(e){for(var t=1;te.forEach(n=>mz(n,t))}function Be(...e){return d.useCallback(Nm(...e),e)}const Zo=d.forwardRef((e,t)=>{const{children:n,...r}=e,o=d.Children.toArray(n),i=o.find(gz);if(i){const s=i.props.children,l=o.map(u=>u===i?d.Children.count(s)>1?d.Children.only(null):d.isValidElement(s)?s.props.children:null:u);return d.createElement(t1,Y({},r,{ref:t}),d.isValidElement(s)?d.cloneElement(s,void 0,l):null)}return d.createElement(t1,Y({},r,{ref:t}),n)});Zo.displayName="Slot";const t1=d.forwardRef((e,t)=>{const{children:n,...r}=e;return d.isValidElement(n)?d.cloneElement(n,{...vz(r,n.props),ref:t?Nm(t,n.ref):n.ref}):d.Children.count(n)>1?d.Children.only(null):null});t1.displayName="SlotClone";const lx=({children:e})=>d.createElement(d.Fragment,null,e);function gz(e){return d.isValidElement(e)&&e.type===lx}function vz(e,t){const n={...t};for(const r in t){const o=e[r],i=t[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...l)=>{i(...l),o(...l)}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...e,...n}}const _C=e=>typeof e=="boolean"?"".concat(e):e===0?"0":e,EC=Bk,Dm=(e,t)=>n=>{var r;if((t==null?void 0:t.variants)==null)return EC(e,n==null?void 0:n.class,n==null?void 0:n.className);const{variants:o,defaultVariants:i}=t,s=Object.keys(o).map(f=>{const m=n==null?void 0:n[f],p=i==null?void 0:i[f];if(m===null)return null;const g=_C(m)||_C(p);return o[f][g]}),l=n&&Object.entries(n).reduce((f,m)=>{let[p,g]=m;return g===void 0||(f[p]=g),f},{}),u=t==null||(r=t.compoundVariants)===null||r===void 0?void 0:r.reduce((f,m)=>{let{class:p,className:g,...y}=m;return Object.entries(y).every(b=>{let[S,E]=b;return Array.isArray(E)?E.includes({...i,...l}[S]):{...i,...l}[S]===E})?[...f,p,g]:f},[]);return EC(e,s,u,n==null?void 0:n.class,n==null?void 0:n.className)};var yz={VITE_BACKEND:"http://127.0.0.1:8080",BASE_URL:"/",MODE:"production",DEV:!1,PROD:!0,SSR:!1};function wz(e,t){let n;try{n=e()}catch{return}return{getItem:o=>{var i;const s=u=>u===null?null:JSON.parse(u,t==null?void 0:t.reviver),l=(i=n.getItem(o))!=null?i:null;return l instanceof Promise?l.then(s):s(l)},setItem:(o,i)=>n.setItem(o,JSON.stringify(i,t==null?void 0:t.replacer)),removeItem:o=>n.removeItem(o)}}const od=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then(r){return od(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return od(r)(n)}}}},xz=(e,t)=>(n,r,o)=>{let i={getStorage:()=>localStorage,serialize:JSON.stringify,deserialize:JSON.parse,partialize:E=>E,version:0,merge:(E,_)=>({..._,...E}),...t},s=!1;const l=new Set,u=new Set;let f;try{f=i.getStorage()}catch{}if(!f)return e((...E)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),n(...E)},r,o);const m=od(i.serialize),p=()=>{const E=i.partialize({...r()});let _;const x=m({state:E,version:i.version}).then(C=>f.setItem(i.name,C)).catch(C=>{_=C});if(_)throw _;return x},g=o.setState;o.setState=(E,_)=>{g(E,_),p()};const y=e((...E)=>{n(...E),p()},r,o);let b;const S=()=>{var E;if(!f)return;s=!1,l.forEach(x=>x(r()));const _=((E=i.onRehydrateStorage)==null?void 0:E.call(i,r()))||void 0;return od(f.getItem.bind(f))(i.name).then(x=>{if(x)return i.deserialize(x)}).then(x=>{if(x)if(typeof x.version=="number"&&x.version!==i.version){if(i.migrate)return i.migrate(x.state,x.version);console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return x.state}).then(x=>{var C;return b=i.merge(x,(C=r())!=null?C:y),n(b,!0),p()}).then(()=>{_==null||_(b,void 0),s=!0,u.forEach(x=>x(b))}).catch(x=>{_==null||_(void 0,x)})};return o.persist={setOptions:E=>{i={...i,...E},E.getStorage&&(f=E.getStorage())},clearStorage:()=>{f==null||f.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>S(),hasHydrated:()=>s,onHydrate:E=>(l.add(E),()=>{l.delete(E)}),onFinishHydration:E=>(u.add(E),()=>{u.delete(E)})},S(),b||y},bz=(e,t)=>(n,r,o)=>{let i={storage:wz(()=>localStorage),partialize:S=>S,version:0,merge:(S,E)=>({...E,...S}),...t},s=!1;const l=new Set,u=new Set;let f=i.storage;if(!f)return e((...S)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),n(...S)},r,o);const m=()=>{const S=i.partialize({...r()});return f.setItem(i.name,{state:S,version:i.version})},p=o.setState;o.setState=(S,E)=>{p(S,E),m()};const g=e((...S)=>{n(...S),m()},r,o);let y;const b=()=>{var S,E;if(!f)return;s=!1,l.forEach(x=>{var C;return x((C=r())!=null?C:g)});const _=((E=i.onRehydrateStorage)==null?void 0:E.call(i,(S=r())!=null?S:g))||void 0;return od(f.getItem.bind(f))(i.name).then(x=>{if(x)if(typeof x.version=="number"&&x.version!==i.version){if(i.migrate)return i.migrate(x.state,x.version);console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return x.state}).then(x=>{var C;return y=i.merge(x,(C=r())!=null?C:g),n(y,!0),m()}).then(()=>{_==null||_(y,void 0),y=r(),s=!0,u.forEach(x=>x(y))}).catch(x=>{_==null||_(void 0,x)})};return o.persist={setOptions:S=>{i={...i,...S},S.storage&&(f=S.storage)},clearStorage:()=>{f==null||f.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>b(),hasHydrated:()=>s,onHydrate:S=>(l.add(S),()=>{l.delete(S)}),onFinishHydration:S=>(u.add(S),()=>{u.delete(S)})},i.skipHydration||b(),y||g},Sz=(e,t)=>"getStorage"in t||"serialize"in t||"deserialize"in t?((yz?"production":void 0)!=="production"&&console.warn("[DEPRECATED] `getStorage`, `serialize` and `deserialize` options are deprecated. Use `storage` option instead."),xz(e,t)):bz(e,t),_z=Sz;function Ez(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,o]of e)if(!Object.is(o,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{t(n,r,e)}):e.forEach((n,r)=>t(r,n,e))}function Im(e){const t=e[wr];return t?t.type_:Array.isArray(e)?1:Lm(e)?2:Fm(e)?3:0}function n1(e,t){return Im(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function ST(e,t,n){const r=Im(e);r===2?e.set(t,n):r===3?e.add(n):e[t]=n}function $z(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function Lm(e){return e instanceof Map}function Fm(e){return e instanceof Set}function ra(e){return e.copy_||e.base_}function r1(e,t){if(Lm(e))return new Map(e);if(Fm(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);if(!t&&bT(e))return sc(e)?{...e}:Object.assign(Object.create(null),e);const n=Object.getOwnPropertyDescriptors(e);delete n[wr];let r=Reflect.ownKeys(n);for(let o=0;o1&&(e.set=e.add=e.clear=e.delete=Rz),Object.freeze(e),t&&id(e,(n,r)=>cx(r,!0))),e}function Rz(){po(2)}function jm(e){return Object.isFrozen(e)}var kz={};function Oa(e){const t=kz[e];return t||po(0,e),t}var sd;function _T(){return sd}function Tz(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function $C(e,t){t&&(Oa("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function o1(e){i1(e),e.drafts_.forEach(Pz),e.drafts_=null}function i1(e){e===sd&&(sd=e.parent_)}function RC(e){return sd=Tz(sd,e)}function Pz(e){const t=e[wr];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function kC(e,t){t.unfinalizedDrafts_=t.drafts_.length;const n=t.drafts_[0];return e!==void 0&&e!==n?(n[wr].modified_&&(o1(t),po(4)),Ma(e)&&(e=Np(t,e),t.parent_||Dp(t,e)),t.patches_&&Oa("Patches").generateReplacementPatches_(n[wr].base_,e,t.patches_,t.inversePatches_)):e=Np(t,n,[]),o1(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==xT?e:void 0}function Np(e,t,n){if(jm(t))return t;const r=t[wr];if(!r)return id(t,(o,i)=>TC(e,r,t,o,i,n)),t;if(r.scope_!==e)return t;if(!r.modified_)return Dp(e,r.base_,!0),r.base_;if(!r.finalized_){r.finalized_=!0,r.scope_.unfinalizedDrafts_--;const o=r.copy_;let i=o,s=!1;r.type_===3&&(i=new Set(o),o.clear(),s=!0),id(i,(l,u)=>TC(e,r,o,l,u,n,s)),Dp(e,o,!1),n&&e.patches_&&Oa("Patches").generatePatches_(r,n,e.patches_,e.inversePatches_)}return r.copy_}function TC(e,t,n,r,o,i,s){if(ac(o)){const l=i&&t&&t.type_!==3&&!n1(t.assigned_,r)?i.concat(r):void 0,u=Np(e,o,l);if(ST(n,r,u),ac(u))e.canAutoFreeze_=!1;else return}else s&&n.add(o);if(Ma(o)&&!jm(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;Np(e,o),(!t||!t.scope_.parent_)&&Dp(e,o)}}function Dp(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&cx(t,n)}function Az(e,t){const n=Array.isArray(e),r={type_:n?1:0,scope_:t?t.scope_:_T(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1};let o=r,i=ux;n&&(o=[r],i=ad);const{revoke:s,proxy:l}=Proxy.revocable(o,i);return r.draft_=l,r.revoke_=s,l}var ux={get(e,t){if(t===wr)return e;const n=ra(e);if(!n1(n,t))return Mz(e,n,t);const r=n[t];return e.finalized_||!Ma(r)?r:r===y0(e.base_,t)?(w0(e),e.copy_[t]=a1(r,e)):r},has(e,t){return t in ra(e)},ownKeys(e){return Reflect.ownKeys(ra(e))},set(e,t,n){const r=ET(ra(e),t);if(r!=null&&r.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){const o=y0(ra(e),t),i=o==null?void 0:o[wr];if(i&&i.base_===n)return e.copy_[t]=n,e.assigned_[t]=!1,!0;if($z(n,o)&&(n!==void 0||n1(e.base_,t)))return!0;w0(e),s1(e)}return e.copy_[t]===n&&(n!==void 0||t in e.copy_)||Number.isNaN(n)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=n,e.assigned_[t]=!0),!0},deleteProperty(e,t){return y0(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,w0(e),s1(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){const n=ra(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:r.enumerable,value:n[t]}},defineProperty(){po(11)},getPrototypeOf(e){return sc(e.base_)},setPrototypeOf(){po(12)}},ad={};id(ux,(e,t)=>{ad[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});ad.deleteProperty=function(e,t){return ad.set.call(this,e,t,void 0)};ad.set=function(e,t,n){return ux.set.call(this,e[0],t,n,e[0])};function y0(e,t){const n=e[wr];return(n?ra(n):e)[t]}function Mz(e,t,n){var o;const r=ET(t,n);return r?"value"in r?r.value:(o=r.get)==null?void 0:o.call(e.draft_):void 0}function ET(e,t){if(!(t in e))return;let n=sc(e);for(;n;){const r=Object.getOwnPropertyDescriptor(n,t);if(r)return r;n=sc(n)}}function s1(e){e.modified_||(e.modified_=!0,e.parent_&&s1(e.parent_))}function w0(e){e.copy_||(e.copy_=r1(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var Oz=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(t,n,r)=>{if(typeof t=="function"&&typeof n!="function"){const i=n;n=t;const s=this;return function(u=i,...f){return s.produce(u,m=>n.call(this,m,...f))}}typeof n!="function"&&po(6),r!==void 0&&typeof r!="function"&&po(7);let o;if(Ma(t)){const i=RC(this),s=a1(t,void 0);let l=!0;try{o=n(s),l=!1}finally{l?o1(i):i1(i)}return $C(i,r),kC(o,i)}else if(!t||typeof t!="object"){if(o=n(t),o===void 0&&(o=t),o===xT&&(o=void 0),this.autoFreeze_&&cx(o,!0),r){const i=[],s=[];Oa("Patches").generateReplacementPatches_(t,o,i,s),r(i,s)}return o}else po(1,t)},this.produceWithPatches=(t,n)=>{if(typeof t=="function")return(s,...l)=>this.produceWithPatches(s,u=>t(u,...l));let r,o;return[this.produce(t,n,(s,l)=>{r=s,o=l}),r,o]},typeof(e==null?void 0:e.autoFreeze)=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof(e==null?void 0:e.useStrictShallowCopy)=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){Ma(e)||po(8),ac(e)&&(e=Nz(e));const t=RC(this),n=a1(e,void 0);return n[wr].isManual_=!0,i1(t),n}finishDraft(e,t){const n=e&&e[wr];(!n||!n.isManual_)&&po(9);const{scope_:r}=n;return $C(r,t),kC(void 0,r)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let n;for(n=t.length-1;n>=0;n--){const o=t[n];if(o.path.length===0&&o.op==="replace"){e=o.value;break}}n>-1&&(t=t.slice(n+1));const r=Oa("Patches").applyPatches_;return ac(e)?r(e,t):this.produce(e,o=>r(o,t))}};function a1(e,t){const n=Lm(e)?Oa("MapSet").proxyMap_(e,t):Fm(e)?Oa("MapSet").proxySet_(e,t):Az(e,t);return(t?t.scope_:_T()).drafts_.push(n),n}function Nz(e){return ac(e)||po(10,e),CT(e)}function CT(e){if(!Ma(e)||jm(e))return e;const t=e[wr];let n;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=r1(e,t.scope_.immer_.useStrictShallowCopy_)}else n=r1(e,!0);return id(n,(r,o)=>{ST(n,r,CT(o))}),t&&(t.finalized_=!1),n}var xr=new Oz,Dz=xr.produce;xr.produceWithPatches.bind(xr);xr.setAutoFreeze.bind(xr);xr.setUseStrictShallowCopy.bind(xr);xr.applyPatches.bind(xr);xr.createDraft.bind(xr);xr.finishDraft.bind(xr);const Iz=e=>(t,n,r)=>(r.setState=(o,i,...s)=>{const l=typeof o=="function"?Dz(o):o;return t(l,i,...s)},e(r.setState,n,r)),Lz=Iz;var $T={exports:{}},RT={},kT={exports:{}},TT={};/** + * @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 lc=d;function Fz(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var jz=typeof Object.is=="function"?Object.is:Fz,zz=lc.useState,Bz=lc.useEffect,Uz=lc.useLayoutEffect,Vz=lc.useDebugValue;function Wz(e,t){var n=t(),r=zz({inst:{value:n,getSnapshot:t}}),o=r[0].inst,i=r[1];return Uz(function(){o.value=n,o.getSnapshot=t,x0(o)&&i({inst:o})},[e,n,t]),Bz(function(){return x0(o)&&i({inst:o}),e(function(){x0(o)&&i({inst:o})})},[e]),Vz(n),n}function x0(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!jz(e,n)}catch{return!0}}function Hz(e,t){return t()}var Kz=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?Hz:Wz;TT.useSyncExternalStore=lc.useSyncExternalStore!==void 0?lc.useSyncExternalStore:Kz;kT.exports=TT;var Gz=kT.exports;/** + * @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 zm=d,Yz=Gz;function Xz(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var Zz=typeof Object.is=="function"?Object.is:Xz,qz=Yz.useSyncExternalStore,Qz=zm.useRef,Jz=zm.useEffect,eB=zm.useMemo,tB=zm.useDebugValue;RT.useSyncExternalStoreWithSelector=function(e,t,n,r,o){var i=Qz(null);if(i.current===null){var s={hasValue:!1,value:null};i.current=s}else s=i.current;i=eB(function(){function u(y){if(!f){if(f=!0,m=y,y=r(y),o!==void 0&&s.hasValue){var b=s.value;if(o(b,y))return p=b}return p=y}if(b=p,Zz(m,y))return b;var S=r(y);return o!==void 0&&o(b,S)?b:(m=y,p=S)}var f=!1,m,p,g=n===void 0?null:n;return[function(){return u(t())},g===null?void 0:function(){return u(g())}]},[t,n,r,o]);var l=qz(e,i[0],i[1]);return Jz(function(){s.hasValue=!0,s.value=l},[l]),tB(l),l};$T.exports=RT;var nB=$T.exports;const rB=dm(nB);var oB={VITE_BACKEND:"http://127.0.0.1:8080",BASE_URL:"/",MODE:"production",DEV:!1,PROD:!0,SSR:!1};const PC=e=>{let t;const n=new Set,r=(u,f)=>{const m=typeof u=="function"?u(t):u;if(!Object.is(m,t)){const p=t;t=f??typeof m!="object"?m:Object.assign({},t,m),n.forEach(g=>g(t,p))}},o=()=>t,l={setState:r,getState:o,subscribe:u=>(n.add(u),()=>n.delete(u)),destroy:()=>{(oB?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),n.clear()}};return t=e(r,o,l),l},iB=e=>e?PC(e):PC,{useDebugValue:sB}=Fe,{useSyncExternalStoreWithSelector:aB}=rB;function lB(e,t=e.getState,n){const r=aB(e.subscribe,e.getState,e.getServerState||e.getState,t,n);return sB(r),r}const AC=(e,t)=>{const n=iB(e),r=(o,i=t)=>lB(n,o,i);return Object.assign(r,n),r},cB=(e,t)=>e?AC(e,t):AC,uB=1,dB=1e6;let b0=0;function fB(){return b0=(b0+1)%Number.MAX_VALUE,b0.toString()}const S0=new Map,MC=e=>{if(S0.has(e))return;const t=setTimeout(()=>{S0.delete(e),Iu({type:"REMOVE_TOAST",toastId:e})},dB);S0.set(e,t)},hB=(e,t)=>{switch(t.type){case"ADD_TOAST":return{...e,toasts:[t.toast,...e.toasts].slice(0,uB)};case"UPDATE_TOAST":return{...e,toasts:e.toasts.map(n=>n.id===t.toast.id?{...n,...t.toast}:n)};case"DISMISS_TOAST":{const{toastId:n}=t;return n?MC(n):e.toasts.forEach(r=>{MC(r.id)}),{...e,toasts:e.toasts.map(r=>r.id===n||n===void 0?{...r,open:!1}:r)}}case"REMOVE_TOAST":return t.toastId===void 0?{...e,toasts:[]}:{...e,toasts:e.toasts.filter(n=>n.id!==t.toastId)}}},Yh=[];let Xh={toasts:[]};function Iu(e){Xh=hB(Xh,e),Yh.forEach(t=>{t(Xh)})}function ul({...e}){const t=fB(),n=o=>Iu({type:"UPDATE_TOAST",toast:{...o,id:t}}),r=()=>Iu({type:"DISMISS_TOAST",toastId:t});return Iu({type:"ADD_TOAST",toast:{...e,id:t,open:!0,onOpenChange:o=>{o||r()}}}),{id:t,dismiss:r,update:n}}function Id(){const[e,t]=d.useState(Xh);return d.useEffect(()=>(Yh.push(t),()=>{const n=Yh.indexOf(t);n>-1&&Yh.splice(n,1)}),[e]),{...e,toast:ul,dismiss:n=>Iu({type:"DISMISS_TOAST",toastId:n})}}const ea={file:null,paintByExampleFile:null,customMask:null,imageHeight:0,imageWidth:0,isInpainting:!1,isPluginRunning:!1,isAdjustingMask:!1,disableShortCuts:!1,windowSize:{height:600,width:800},editorState:{baseBrushSize:cF,brushSizeScale:1,renders:[],extraMasks:[],prevExtraMasks:[],temporaryMasks:[],lineGroups:[],lastLineGroup:[],curLineGroup:[],redoRenders:[],redoCurLines:[],redoLineGroups:[]},interactiveSegState:{isInteractiveSeg:!1,tmpInteractiveSegMask:null,clicks:[]},cropperState:{x:0,y:0,width:512,height:512},extenderState:{x:0,y:0,width:512,height:512},isCropperExtenderResizing:!1,fileManagerState:{sortBy:Es.CTIME,sortOrder:Ou.DESCENDING,layout:"masonry",searchText:"",inputDirectory:"",outputDirectory:""},serverConfig:{plugins:[],modelInfos:[],removeBGModel:"briaai/RMBG-1.4",removeBGModels:[],realesrganModel:"realesr-general-x4v3",realesrganModels:[],interactiveSegModel:"vit_b",interactiveSegModels:[],enableFileManager:!1,enableAutoSaving:!1,enableControlnet:!1,controlnetMethod:"lllyasviel/control_v11p_sd15_canny",disableModelSwitch:!1,isDesktop:!1,samplers:["DPM++ 2M"]},settings:{model:{name:"lama",path:"lama",model_type:"inpaint",support_controlnet:!1,support_strength:!1,support_outpainting:!1,controlnets:[],support_freeu:!1,support_lcm_lora:!1,is_single_file_diffusers:!1,need_prompt:!1},enableControlnet:!1,showCropper:!1,showExtender:!1,extenderDirection:Ln.xy,enableDownloadMask:!1,enableManualInpainting:!1,enableUploadMask:!1,enableAutoExtractPrompt:!0,ldmSteps:30,ldmSampler:Qw.ddim,zitsWireframe:!0,cv2Radius:5,cv2Flag:Jw.INPAINT_NS,prompt:"",negativePrompt:hF,seed:42,seedFixed:!1,sdMaskBlur:12,sdStrength:1,sdSteps:50,sdGuidanceScale:7.5,sdSampler:"DPM++ 2M",sdMatchHistograms:!1,sdScale:1,p2pImageGuidanceScale:1.5,controlnetConditioningScale:.4,controlnetMethod:"lllyasviel/control_v11p_sd15_canny",enableLCMLora:!1,enableFreeu:!1,freeuConfig:{s1:.9,s2:.2,b1:1.2,b2:1.4},powerpaintTask:Ol.text_guided,adjustMaskKernelSize:12}},bt=cB()(_z(Lz((e,t)=>({...ea,showPrevMask:async()=>{if(t().settings.showExtender)return;const{lastLineGroup:n,curLineGroup:r,prevExtraMasks:o,extraMasks:i}=t().editorState;if(r.length!==0||i.length!==0)return;const{imageWidth:s,imageHeight:l}=t(),u=Wh(s,l,[n],o,Xy);try{const f=await cC(u);e(m=>{m.editorState.temporaryMasks.push(f)})}catch(f){console.error(f);return}},hidePrevMask:()=>{e(n=>{n.editorState.temporaryMasks=[]})},getCurrentTargetFile:async()=>{const n=t().file,r=t().editorState.renders;let o=n;if(r.length>0){const i=r[r.length-1];o=await Nu(i.currentSrc,n.name,n.type)}return o},runInpainting:async()=>{const{isInpainting:n,file:r,paintByExampleFile:o,imageWidth:i,imageHeight:s,settings:l,cropperState:u,extenderState:f}=t();if(n||r===null||t().settings.model.support_outpainting&&l.showExtender&&f.height===s&&f.width===i)return;const{lastLineGroup:m,curLineGroup:p,lineGroups:g,renders:y,prevExtraMasks:b,extraMasks:S}=t().editorState,E=p.length===0&&S.length===0&&!l.showExtender;let _=[],x=[];if(E===!0?(x=m,_=b):(x=p,_=S),x.length===0&&_===null&&!l.showExtender){ul({variant:"destructive",description:"Please draw mask on picture"});return}const C=[...g,x];e(M=>{M.isInpainting=!0});let R=r;if(E===!0){if(y.length>1){const M=y[y.length-2];R=await Nu(M.currentSrc,r.name,r.type)}}else if(y.length>0){const M=y[y.length-1];R=await Nu(M.currentSrc,r.name,r.type)}const P=Wh(i,s,[x],_);if(E){const M=await cC(P);e(A=>{A.editorState.temporaryMasks=[M]})}try{const M=await zj(R,l,u,f,lC(P.toDataURL()),o),{blob:A,seed:D}=M;D&&t().setSeed(parseInt(D,10));const U=new Image;await Vh(U,A);const W=[...y,U];t().setImageSize(U.width,U.height),t().updateEditorState({renders:W,lineGroups:C,lastLineGroup:x,curLineGroup:[],extraMasks:[],prevExtraMasks:_})}catch(M){ul({variant:"destructive",description:M.message?M.message:M.toString()})}t().resetRedoState(),e(M=>{M.isInpainting=!1,M.editorState.temporaryMasks=[]})},runRenderablePlugin:async(n,r,o={upscale:1})=>{const{renders:i,lineGroups:s}=t().editorState;e(l=>{l.isPluginRunning=!0});try{const l=new Date,u=await t().getCurrentTargetFile(),f=await vT(n,r,u,o.upscale),{blob:m}=f;if(n){const y=new Image;await Vh(y,m),e(b=>{b.editorState.extraMasks.push(y)})}else{const y=new Image;await Vh(y,m),t().setImageSize(y.width,y.height);const b=[...i,y],S=[...s,[]];t().updateEditorState({renders:b,lineGroups:S})}const g=new Date().getTime()-l.getTime();ul({description:`Run ${r} successfully in ${g/1e3}s`})}catch(l){ul({variant:"destructive",description:l.message?l.message:l.toString()})}e(l=>{l.isPluginRunning=!1})},updateEditorState:n=>{e(r=>{r.editorState={...r.editorState,...n}})},cleanCurLineGroup:()=>{t().updateEditorState({curLineGroup:[]})},handleCanvasMouseDown:n=>{let r=[];const o=t();o.runMannually()&&(r=[...o.editorState.curLineGroup]),r.push({size:o.getBrushSize(),pts:[n]}),e(i=>{i.editorState.curLineGroup=r})},handleCanvasMouseMove:n=>{e(r=>{const o=r.editorState.curLineGroup;o.length&&o[o.length-1].pts.push(n)})},runMannually:()=>{const n=t();return n.settings.enableManualInpainting||n.settings.model.model_type!==fs},getIsProcessing:()=>t().isInpainting||t().isPluginRunning||t().isAdjustingMask,isSD:()=>t().settings.model.model_type!==fs,undoDisabled:()=>{const n=t().editorState;if(n.renders.length>0)return!1;if(t().runMannually()){if(n.curLineGroup.length===0)return!0}else if(n.renders.length===0)return!0;return!1},undo:()=>{t().runMannually()&&t().editorState.curLineGroup.length!==0?e(n=>{const r=n.editorState;if(r.curLineGroup.length===0)return;r.lastLineGroup=[];const o=r.curLineGroup.pop();r.redoCurLines.push(o)}):e(n=>{const r=n.editorState;if(r.renders.length===0||r.lineGroups.length===0)return;const o=r.lineGroups.pop();r.redoLineGroups.push(o),r.redoCurLines=[],r.curLineGroup=[];const i=r.renders.pop();r.redoRenders.push(i)})},redoDisabled:()=>{const n=t().editorState;if(n.redoRenders.length>0)return!1;if(t().runMannually()){if(n.redoCurLines.length===0)return!0}else if(n.redoRenders.length===0)return!0;return!1},redo:()=>{t().runMannually()&&t().editorState.redoCurLines.length!==0?e(n=>{const r=n.editorState;if(r.redoCurLines.length===0)return;const o=r.redoCurLines.pop();r.curLineGroup.push(o)}):e(n=>{const r=n.editorState;if(r.redoRenders.length===0||r.redoLineGroups.length===0)return;const o=r.redoLineGroups.pop();r.lineGroups.push(o),r.curLineGroup=[];const i=r.redoRenders.pop();r.renders.push(i)})},resetRedoState:()=>{e(n=>{n.editorState.redoCurLines=[],n.editorState.redoLineGroups=[],n.editorState.redoRenders=[]})},updateAppState:n=>{e(()=>n)},getBrushSize:()=>t().editorState.baseBrushSize*t().editorState.brushSizeScale,showPromptInput:()=>{const n=t().settings.model;return n.model_type!==fs&&n.name!==Gk},setServerConfig:n=>{e(r=>{r.serverConfig=n,r.settings.enableControlnet=n.enableControlnet,r.settings.controlnetMethod=n.controlnetMethod})},updateSettings:n=>{e(r=>{r.settings={...r.settings,...n}})},setModel:n=>{e(r=>{r.settings.model=n,n.support_controlnet&&!n.controlnets.includes(r.settings.controlnetMethod)&&(r.settings.controlnetMethod=n.controlnets[0])})},updateFileManagerState:n=>{e(r=>{r.fileManagerState={...r.fileManagerState,...n}})},updateInteractiveSegState:n=>{e(r=>({...r,interactiveSegState:{...r.interactiveSegState,...n}}))},resetInteractiveSegState:()=>{t().updateInteractiveSegState(ea.interactiveSegState)},handleInteractiveSegAccept:()=>{e(n=>{n.interactiveSegState.tmpInteractiveSegMask&&n.editorState.extraMasks.push(n.interactiveSegState.tmpInteractiveSegMask),n.interactiveSegState={...ea.interactiveSegState}})},setIsInpainting:n=>e(r=>{r.isInpainting=n}),setFile:async n=>{if(t().settings.enableAutoExtractPrompt)try{const r=await Kj(n);r.prompt&&e(o=>{o.settings.prompt=r.prompt}),r.negative_prompt&&e(o=>{o.settings.negativePrompt=r.negative_prompt})}catch(r){ul({variant:"destructive",description:r.message?r.message:r.toString()})}e(r=>{r.file=n,r.interactiveSegState=ea.interactiveSegState,r.editorState=ea.editorState,r.cropperState=ea.cropperState})},setCustomFile:n=>e(r=>{r.customMask=n}),setBaseBrushSize:n=>e(r=>{r.editorState.baseBrushSize=n}),setImageSize:(n,r)=>{e(o=>{o.imageWidth=n,o.imageHeight=r,o.editorState.brushSizeScale=Math.max(Math.min(n,r),512)/512}),t().resetExtender(n,r)},setCropperX:n=>e(r=>{r.cropperState.x=n}),setCropperY:n=>e(r=>{r.cropperState.y=n}),setCropperWidth:n=>e(r=>{r.cropperState.width=n}),setCropperHeight:n=>e(r=>{r.cropperState.height=n}),setExtenderX:n=>e(r=>{r.extenderState.x=n}),setExtenderY:n=>e(r=>{r.extenderState.y=n}),setExtenderWidth:n=>e(r=>{r.extenderState.width=n}),setExtenderHeight:n=>e(r=>{r.extenderState.height=n}),setIsCropperExtenderResizing:n=>e(r=>{r.isCropperExtenderResizing=n}),updateExtenderDirection:n=>{console.log(`updateExtenderDirection: ${JSON.stringify(t().extenderState)}`),e(r=>{r.settings.extenderDirection=n,r.extenderState.x=0,r.extenderState.y=0,r.extenderState.width=r.imageWidth,r.extenderState.height=r.imageHeight}),t().updateExtenderByBuiltIn(n,1.5)},updateExtenderByBuiltIn:(n,r)=>{const o={...ea.extenderState};let{x:i,y:s,width:l,height:u}=o;const{imageWidth:f,imageHeight:m}=t();switch(l=f,u=m,n){case Ln.x:i=-Math.ceil(f*(r-1)/2),l=Math.ceil(f*r);break;case Ln.y:s=-Math.ceil(m*(r-1)/2),u=Math.ceil(m*r);break;case Ln.xy:i=-Math.ceil(f*(r-1)/2),s=-Math.ceil(m*(r-1)/2),l=Math.ceil(f*r),u=Math.ceil(m*r);break}e(p=>{p.extenderState.x=i,p.extenderState.y=s,p.extenderState.width=l,p.extenderState.height=u})},resetExtender:(n,r)=>{e(o=>{o.extenderState.x=0,o.extenderState.y=0,o.extenderState.width=n,o.extenderState.height=r})},setSeed:n=>e(r=>{r.settings.seed=n}),adjustMask:async n=>{const{imageWidth:r,imageHeight:o}=t(),{curLineGroup:i,extraMasks:s}=t().editorState,{adjustMaskKernelSize:l}=t().settings;if(i.length===0&&s.length===0)return;e(g=>{g.isAdjustingMask=!0});const u=Wh(r,o,[i],s,Xy),f=lC(u.toDataURL()),m=await Gj(f,n,l),p=await mF(m);e(g=>{g.editorState.extraMasks=[p],g.editorState.curLineGroup=[]}),e(g=>{g.isAdjustingMask=!1})},clearMask:()=>{e(n=>{n.editorState.extraMasks=[],n.editorState.curLineGroup=[]})}})),{name:"ZUSTAND_STATE",version:1,partialize:e=>Object.fromEntries(Object.entries(e).filter(([t])=>["fileManagerState","settings"].includes(t)))}),Ez),Ld=d.forwardRef(({className:e,type:t,...n},r)=>{const o=bt(l=>l.updateAppState),i=()=>{o({disableShortCuts:!0})},s=()=>{o({disableShortCuts:!1})};return v.jsx("input",{type:t,className:Ce("flex h-8 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",e),ref:r,autoComplete:"off",tabIndex:-1,onFocus:i,onBlur:s,...n})});Ld.displayName="Input";const Yn=d.forwardRef(({numberValue:e,allowFloat:t,onNumberValueChange:n,...r},o)=>{const[i,s]=d.useState(e.toString());d.useEffect(()=>{i!==e.toString()+"."&&s(e.toString())},[e]);const l=u=>{let m=u.target.value;if(t){if(m=m.replace(/[^0-9.]/g,"").replace(/(\..*?)\..*/g,"$1"),m.length===0){n(0);return}n(parseFloat(m))}else{if(m=m.replace(/\D/g,""),m.length===0){n(0);return}n(parseInt(m,10))}s(m)};return v.jsx(Ld,{ref:o,value:i,onInput:l,...r})});function de(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 pB(e,t){const n=d.createContext(t);function r(i){const{children:s,...l}=i,u=d.useMemo(()=>l,Object.values(l));return d.createElement(n.Provider,{value:u},s)}function o(i){const s=d.useContext(n);if(s)return s;if(t!==void 0)return t;throw new Error(`\`${i}\` must be used within \`${e}\``)}return r.displayName=e+"Provider",[r,o]}function Mn(e,t=[]){let n=[];function r(i,s){const l=d.createContext(s),u=n.length;n=[...n,s];function f(p){const{scope:g,children:y,...b}=p,S=(g==null?void 0:g[e][u])||l,E=d.useMemo(()=>b,Object.values(b));return d.createElement(S.Provider,{value:E},y)}function m(p,g){const y=(g==null?void 0:g[e][u])||l,b=d.useContext(y);if(b)return b;if(s!==void 0)return s;throw new Error(`\`${p}\` must be used within \`${i}\``)}return f.displayName=i+"Provider",[f,m]}const o=()=>{const i=n.map(s=>d.createContext(s));return function(l){const u=(l==null?void 0:l[e])||i;return d.useMemo(()=>({[`__scope${e}`]:{...l,[e]:u}}),[l,u])}};return o.scopeName=e,[r,mB(o,...t)]}function mB(...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(i){const s=r.reduce((l,{useScope:u,scopeName:f})=>{const p=u(i)[`__scope${f}`];return{...l,...p}},{});return d.useMemo(()=>({[`__scope${t.scopeName}`]:s}),[s])}};return n.scopeName=t.scopeName,n}const gB=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","span","svg","ul"],Pe=gB.reduce((e,t)=>{const n=d.forwardRef((r,o)=>{const{asChild:i,...s}=r,l=i?Zo:t;return d.useEffect(()=>{window[Symbol.for("radix-ui")]=!0},[]),d.createElement(l,Y({},s,{ref:o}))});return n.displayName=`Primitive.${t}`,{...e,[t]:n}},{});function dx(e,t){e&&Is.flushSync(()=>e.dispatchEvent(t))}function Ft(e){const t=d.useRef(e);return d.useEffect(()=>{t.current=e}),d.useMemo(()=>(...n)=>{var r;return(r=t.current)===null||r===void 0?void 0:r.call(t,...n)},[])}function vB(e,t=globalThis==null?void 0:globalThis.document){const n=Ft(e);d.useEffect(()=>{const r=o=>{o.key==="Escape"&&n(o)};return t.addEventListener("keydown",r),()=>t.removeEventListener("keydown",r)},[n,t])}const l1="dismissableLayer.update",yB="dismissableLayer.pointerDownOutside",wB="dismissableLayer.focusOutside";let OC;const PT=d.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),Ec=d.forwardRef((e,t)=>{var n;const{disableOutsidePointerEvents:r=!1,onEscapeKeyDown:o,onPointerDownOutside:i,onFocusOutside:s,onInteractOutside:l,onDismiss:u,...f}=e,m=d.useContext(PT),[p,g]=d.useState(null),y=(n=p==null?void 0:p.ownerDocument)!==null&&n!==void 0?n:globalThis==null?void 0:globalThis.document,[,b]=d.useState({}),S=Be(t,D=>g(D)),E=Array.from(m.layers),[_]=[...m.layersWithOutsidePointerEventsDisabled].slice(-1),x=E.indexOf(_),C=p?E.indexOf(p):-1,R=m.layersWithOutsidePointerEventsDisabled.size>0,P=C>=x,M=bB(D=>{const U=D.target,W=[...m.branches].some(q=>q.contains(U));!P||W||(i==null||i(D),l==null||l(D),D.defaultPrevented||u==null||u())},y),A=SB(D=>{const U=D.target;[...m.branches].some(q=>q.contains(U))||(s==null||s(D),l==null||l(D),D.defaultPrevented||u==null||u())},y);return vB(D=>{C===m.layers.size-1&&(o==null||o(D),!D.defaultPrevented&&u&&(D.preventDefault(),u()))},y),d.useEffect(()=>{if(p)return r&&(m.layersWithOutsidePointerEventsDisabled.size===0&&(OC=y.body.style.pointerEvents,y.body.style.pointerEvents="none"),m.layersWithOutsidePointerEventsDisabled.add(p)),m.layers.add(p),NC(),()=>{r&&m.layersWithOutsidePointerEventsDisabled.size===1&&(y.body.style.pointerEvents=OC)}},[p,y,r,m]),d.useEffect(()=>()=>{p&&(m.layers.delete(p),m.layersWithOutsidePointerEventsDisabled.delete(p),NC())},[p,m]),d.useEffect(()=>{const D=()=>b({});return document.addEventListener(l1,D),()=>document.removeEventListener(l1,D)},[]),d.createElement(Pe.div,Y({},f,{ref:S,style:{pointerEvents:R?P?"auto":"none":void 0,...e.style},onFocusCapture:de(e.onFocusCapture,A.onFocusCapture),onBlurCapture:de(e.onBlurCapture,A.onBlurCapture),onPointerDownCapture:de(e.onPointerDownCapture,M.onPointerDownCapture)}))}),xB=d.forwardRef((e,t)=>{const n=d.useContext(PT),r=d.useRef(null),o=Be(t,r);return d.useEffect(()=>{const i=r.current;if(i)return n.branches.add(i),()=>{n.branches.delete(i)}},[n.branches]),d.createElement(Pe.div,Y({},e,{ref:o}))});function bB(e,t=globalThis==null?void 0:globalThis.document){const n=Ft(e),r=d.useRef(!1),o=d.useRef(()=>{});return d.useEffect(()=>{const i=l=>{if(l.target&&!r.current){let m=function(){AT(yB,n,f,{discrete:!0})};var u=m;const f={originalEvent:l};l.pointerType==="touch"?(t.removeEventListener("click",o.current),o.current=m,t.addEventListener("click",o.current,{once:!0})):m()}else t.removeEventListener("click",o.current);r.current=!1},s=window.setTimeout(()=>{t.addEventListener("pointerdown",i)},0);return()=>{window.clearTimeout(s),t.removeEventListener("pointerdown",i),t.removeEventListener("click",o.current)}},[t,n]),{onPointerDownCapture:()=>r.current=!0}}function SB(e,t=globalThis==null?void 0:globalThis.document){const n=Ft(e),r=d.useRef(!1);return d.useEffect(()=>{const o=i=>{i.target&&!r.current&&AT(wB,n,{originalEvent:i},{discrete:!1})};return t.addEventListener("focusin",o),()=>t.removeEventListener("focusin",o)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function NC(){const e=new CustomEvent(l1);document.dispatchEvent(e)}function AT(e,t,n,{discrete:r}){const o=n.originalEvent.target,i=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&o.addEventListener(e,t,{once:!0}),r?dx(o,i):o.dispatchEvent(i)}const _B=Ec,EB=xB,An=globalThis!=null&&globalThis.document?d.useLayoutEffect:()=>{},CB=UD.useId||(()=>{});let $B=0;function nr(e){const[t,n]=d.useState(CB());return An(()=>{e||n(r=>r??String($B++))},[e]),e||(t?`radix-${t}`:"")}const RB=["top","right","bottom","left"],Ts=Math.min,hr=Math.max,Ip=Math.round,fh=Math.floor,Ps=e=>({x:e,y:e}),kB={left:"right",right:"left",bottom:"top",top:"bottom"},TB={start:"end",end:"start"};function c1(e,t,n){return hr(e,Ts(t,n))}function Ci(e,t){return typeof e=="function"?e(t):e}function $i(e){return e.split("-")[0]}function Cc(e){return e.split("-")[1]}function fx(e){return e==="x"?"y":"x"}function hx(e){return e==="y"?"height":"width"}function $c(e){return["top","bottom"].includes($i(e))?"y":"x"}function px(e){return fx($c(e))}function PB(e,t,n){n===void 0&&(n=!1);const r=Cc(e),o=px(e),i=hx(o);let s=o==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[i]>t.floating[i]&&(s=Lp(s)),[s,Lp(s)]}function AB(e){const t=Lp(e);return[u1(e),t,u1(t)]}function u1(e){return e.replace(/start|end/g,t=>TB[t])}function MB(e,t,n){const r=["left","right"],o=["right","left"],i=["top","bottom"],s=["bottom","top"];switch(e){case"top":case"bottom":return n?t?o:r:t?r:o;case"left":case"right":return t?i:s;default:return[]}}function OB(e,t,n,r){const o=Cc(e);let i=MB($i(e),n==="start",r);return o&&(i=i.map(s=>s+"-"+o),t&&(i=i.concat(i.map(u1)))),i}function Lp(e){return e.replace(/left|right|bottom|top/g,t=>kB[t])}function NB(e){return{top:0,right:0,bottom:0,left:0,...e}}function MT(e){return typeof e!="number"?NB(e):{top:e,right:e,bottom:e,left:e}}function Fp(e){return{...e,top:e.y,left:e.x,right:e.x+e.width,bottom:e.y+e.height}}function DC(e,t,n){let{reference:r,floating:o}=e;const i=$c(t),s=px(t),l=hx(s),u=$i(t),f=i==="y",m=r.x+r.width/2-o.width/2,p=r.y+r.height/2-o.height/2,g=r[l]/2-o[l]/2;let y;switch(u){case"top":y={x:m,y:r.y-o.height};break;case"bottom":y={x:m,y:r.y+r.height};break;case"right":y={x:r.x+r.width,y:p};break;case"left":y={x:r.x-o.width,y:p};break;default:y={x:r.x,y:r.y}}switch(Cc(t)){case"start":y[s]-=g*(n&&f?-1:1);break;case"end":y[s]+=g*(n&&f?-1:1);break}return y}const DB=async(e,t,n)=>{const{placement:r="bottom",strategy:o="absolute",middleware:i=[],platform:s}=n,l=i.filter(Boolean),u=await(s.isRTL==null?void 0:s.isRTL(t));let f=await s.getElementRects({reference:e,floating:t,strategy:o}),{x:m,y:p}=DC(f,r,u),g=r,y={},b=0;for(let S=0;S({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:o,rects:i,platform:s,elements:l,middlewareData:u}=t,{element:f,padding:m=0}=Ci(e,t)||{};if(f==null)return{};const p=MT(m),g={x:n,y:r},y=px(o),b=hx(y),S=await s.getDimensions(f),E=y==="y",_=E?"top":"left",x=E?"bottom":"right",C=E?"clientHeight":"clientWidth",R=i.reference[b]+i.reference[y]-g[y]-i.floating[b],P=g[y]-i.reference[y],M=await(s.getOffsetParent==null?void 0:s.getOffsetParent(f));let A=M?M[C]:0;(!A||!await(s.isElement==null?void 0:s.isElement(M)))&&(A=l.floating[C]||i.floating[b]);const D=R/2-P/2,U=A/2-S[b]/2-1,W=Ts(p[_],U),q=Ts(p[x],U),X=W,ae=A-S[b]-q,V=A/2-S[b]/2+D,F=c1(X,V,ae),N=!u.arrow&&Cc(o)!=null&&V!=F&&i.reference[b]/2-(VX<=0)){var U,W;const X=(((U=i.flip)==null?void 0:U.index)||0)+1,ae=P[X];if(ae)return{data:{index:X,overflows:D},reset:{placement:ae}};let V=(W=D.filter(F=>F.overflows[0]<=0).sort((F,N)=>F.overflows[1]-N.overflows[1])[0])==null?void 0:W.placement;if(!V)switch(y){case"bestFit":{var q;const F=(q=D.map(N=>[N.placement,N.overflows.filter(ie=>ie>0).reduce((ie,K)=>ie+K,0)]).sort((N,ie)=>N[1]-ie[1])[0])==null?void 0:q[0];F&&(V=F);break}case"initialPlacement":V=l;break}if(o!==V)return{reset:{placement:V}}}return{}}}};function LC(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function FC(e){return RB.some(t=>e[t]>=0)}const LB=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n}=t,{strategy:r="referenceHidden",...o}=Ci(e,t);switch(r){case"referenceHidden":{const i=await ld(t,{...o,elementContext:"reference"}),s=LC(i,n.reference);return{data:{referenceHiddenOffsets:s,referenceHidden:FC(s)}}}case"escaped":{const i=await ld(t,{...o,altBoundary:!0}),s=LC(i,n.floating);return{data:{escapedOffsets:s,escaped:FC(s)}}}default:return{}}}}};async function FB(e,t){const{placement:n,platform:r,elements:o}=e,i=await(r.isRTL==null?void 0:r.isRTL(o.floating)),s=$i(n),l=Cc(n),u=$c(n)==="y",f=["left","top"].includes(s)?-1:1,m=i&&u?-1:1,p=Ci(t,e);let{mainAxis:g,crossAxis:y,alignmentAxis:b}=typeof p=="number"?{mainAxis:p,crossAxis:0,alignmentAxis:null}:{mainAxis:0,crossAxis:0,alignmentAxis:null,...p};return l&&typeof b=="number"&&(y=l==="end"?b*-1:b),u?{x:y*m,y:g*f}:{x:g*f,y:y*m}}const jB=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){const{x:n,y:r}=t,o=await FB(t,e);return{x:n+o.x,y:r+o.y,data:o}}}},zB=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:o}=t,{mainAxis:i=!0,crossAxis:s=!1,limiter:l={fn:E=>{let{x:_,y:x}=E;return{x:_,y:x}}},...u}=Ci(e,t),f={x:n,y:r},m=await ld(t,u),p=$c($i(o)),g=fx(p);let y=f[g],b=f[p];if(i){const E=g==="y"?"top":"left",_=g==="y"?"bottom":"right",x=y+m[E],C=y-m[_];y=c1(x,y,C)}if(s){const E=p==="y"?"top":"left",_=p==="y"?"bottom":"right",x=b+m[E],C=b-m[_];b=c1(x,b,C)}const S=l.fn({...t,[g]:y,[p]:b});return{...S,data:{x:S.x-n,y:S.y-r}}}}},BB=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:r,placement:o,rects:i,middlewareData:s}=t,{offset:l=0,mainAxis:u=!0,crossAxis:f=!0}=Ci(e,t),m={x:n,y:r},p=$c(o),g=fx(p);let y=m[g],b=m[p];const S=Ci(l,t),E=typeof S=="number"?{mainAxis:S,crossAxis:0}:{mainAxis:0,crossAxis:0,...S};if(u){const C=g==="y"?"height":"width",R=i.reference[g]-i.floating[C]+E.mainAxis,P=i.reference[g]+i.reference[C]-E.mainAxis;yP&&(y=P)}if(f){var _,x;const C=g==="y"?"width":"height",R=["top","left"].includes($i(o)),P=i.reference[p]-i.floating[C]+(R&&((_=s.offset)==null?void 0:_[p])||0)+(R?0:E.crossAxis),M=i.reference[p]+i.reference[C]+(R?0:((x=s.offset)==null?void 0:x[p])||0)-(R?E.crossAxis:0);bM&&(b=M)}return{[g]:y,[p]:b}}}},UB=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){const{placement:n,rects:r,platform:o,elements:i}=t,{apply:s=()=>{},...l}=Ci(e,t),u=await ld(t,l),f=$i(n),m=Cc(n),p=$c(n)==="y",{width:g,height:y}=r.floating;let b,S;f==="top"||f==="bottom"?(b=f,S=m===(await(o.isRTL==null?void 0:o.isRTL(i.floating))?"start":"end")?"left":"right"):(S=f,b=m==="end"?"top":"bottom");const E=y-u[b],_=g-u[S],x=!t.middlewareData.shift;let C=E,R=_;if(p){const M=g-u.left-u.right;R=m||x?Ts(_,M):M}else{const M=y-u.top-u.bottom;C=m||x?Ts(E,M):M}if(x&&!m){const M=hr(u.left,0),A=hr(u.right,0),D=hr(u.top,0),U=hr(u.bottom,0);p?R=g-2*(M!==0||A!==0?M+A:hr(u.left,u.right)):C=y-2*(D!==0||U!==0?D+U:hr(u.top,u.bottom))}await s({...t,availableWidth:R,availableHeight:C});const P=await o.getDimensions(i.floating);return g!==P.width||y!==P.height?{reset:{rects:!0}}:{}}}};function As(e){return OT(e)?(e.nodeName||"").toLowerCase():"#document"}function vr(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Mi(e){var t;return(t=(OT(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function OT(e){return e instanceof Node||e instanceof vr(e).Node}function Ri(e){return e instanceof Element||e instanceof vr(e).Element}function qo(e){return e instanceof HTMLElement||e instanceof vr(e).HTMLElement}function jC(e){return typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof vr(e).ShadowRoot}function Fd(e){const{overflow:t,overflowX:n,overflowY:r,display:o}=Xr(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&!["inline","contents"].includes(o)}function VB(e){return["table","td","th"].includes(As(e))}function mx(e){const t=gx(),n=Xr(e);return n.transform!=="none"||n.perspective!=="none"||(n.containerType?n.containerType!=="normal":!1)||!t&&(n.backdropFilter?n.backdropFilter!=="none":!1)||!t&&(n.filter?n.filter!=="none":!1)||["transform","perspective","filter"].some(r=>(n.willChange||"").includes(r))||["paint","layout","strict","content"].some(r=>(n.contain||"").includes(r))}function WB(e){let t=cc(e);for(;qo(t)&&!Bm(t);){if(mx(t))return t;t=cc(t)}return null}function gx(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}function Bm(e){return["html","body","#document"].includes(As(e))}function Xr(e){return vr(e).getComputedStyle(e)}function Um(e){return Ri(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.pageXOffset,scrollTop:e.pageYOffset}}function cc(e){if(As(e)==="html")return e;const t=e.assignedSlot||e.parentNode||jC(e)&&e.host||Mi(e);return jC(t)?t.host:t}function NT(e){const t=cc(e);return Bm(t)?e.ownerDocument?e.ownerDocument.body:e.body:qo(t)&&Fd(t)?t:NT(t)}function cd(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const o=NT(e),i=o===((r=e.ownerDocument)==null?void 0:r.body),s=vr(o);return i?t.concat(s,s.visualViewport||[],Fd(o)?o:[],s.frameElement&&n?cd(s.frameElement):[]):t.concat(o,cd(o,[],n))}function DT(e){const t=Xr(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const o=qo(e),i=o?e.offsetWidth:n,s=o?e.offsetHeight:r,l=Ip(n)!==i||Ip(r)!==s;return l&&(n=i,r=s),{width:n,height:r,$:l}}function vx(e){return Ri(e)?e:e.contextElement}function Nl(e){const t=vx(e);if(!qo(t))return Ps(1);const n=t.getBoundingClientRect(),{width:r,height:o,$:i}=DT(t);let s=(i?Ip(n.width):n.width)/r,l=(i?Ip(n.height):n.height)/o;return(!s||!Number.isFinite(s))&&(s=1),(!l||!Number.isFinite(l))&&(l=1),{x:s,y:l}}const HB=Ps(0);function IT(e){const t=vr(e);return!gx()||!t.visualViewport?HB:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function KB(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==vr(e)?!1:t}function Na(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const o=e.getBoundingClientRect(),i=vx(e);let s=Ps(1);t&&(r?Ri(r)&&(s=Nl(r)):s=Nl(e));const l=KB(i,n,r)?IT(i):Ps(0);let u=(o.left+l.x)/s.x,f=(o.top+l.y)/s.y,m=o.width/s.x,p=o.height/s.y;if(i){const g=vr(i),y=r&&Ri(r)?vr(r):r;let b=g.frameElement;for(;b&&r&&y!==g;){const S=Nl(b),E=b.getBoundingClientRect(),_=Xr(b),x=E.left+(b.clientLeft+parseFloat(_.paddingLeft))*S.x,C=E.top+(b.clientTop+parseFloat(_.paddingTop))*S.y;u*=S.x,f*=S.y,m*=S.x,p*=S.y,u+=x,f+=C,b=vr(b).frameElement}}return Fp({width:m,height:p,x:u,y:f})}function GB(e){let{rect:t,offsetParent:n,strategy:r}=e;const o=qo(n),i=Mi(n);if(n===i)return t;let s={scrollLeft:0,scrollTop:0},l=Ps(1);const u=Ps(0);if((o||!o&&r!=="fixed")&&((As(n)!=="body"||Fd(i))&&(s=Um(n)),qo(n))){const f=Na(n);l=Nl(n),u.x=f.x+n.clientLeft,u.y=f.y+n.clientTop}return{width:t.width*l.x,height:t.height*l.y,x:t.x*l.x-s.scrollLeft*l.x+u.x,y:t.y*l.y-s.scrollTop*l.y+u.y}}function YB(e){return Array.from(e.getClientRects())}function LT(e){return Na(Mi(e)).left+Um(e).scrollLeft}function XB(e){const t=Mi(e),n=Um(e),r=e.ownerDocument.body,o=hr(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),i=hr(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let s=-n.scrollLeft+LT(e);const l=-n.scrollTop;return Xr(r).direction==="rtl"&&(s+=hr(t.clientWidth,r.clientWidth)-o),{width:o,height:i,x:s,y:l}}function ZB(e,t){const n=vr(e),r=Mi(e),o=n.visualViewport;let i=r.clientWidth,s=r.clientHeight,l=0,u=0;if(o){i=o.width,s=o.height;const f=gx();(!f||f&&t==="fixed")&&(l=o.offsetLeft,u=o.offsetTop)}return{width:i,height:s,x:l,y:u}}function qB(e,t){const n=Na(e,!0,t==="fixed"),r=n.top+e.clientTop,o=n.left+e.clientLeft,i=qo(e)?Nl(e):Ps(1),s=e.clientWidth*i.x,l=e.clientHeight*i.y,u=o*i.x,f=r*i.y;return{width:s,height:l,x:u,y:f}}function zC(e,t,n){let r;if(t==="viewport")r=ZB(e,n);else if(t==="document")r=XB(Mi(e));else if(Ri(t))r=qB(t,n);else{const o=IT(e);r={...t,x:t.x-o.x,y:t.y-o.y}}return Fp(r)}function FT(e,t){const n=cc(e);return n===t||!Ri(n)||Bm(n)?!1:Xr(n).position==="fixed"||FT(n,t)}function QB(e,t){const n=t.get(e);if(n)return n;let r=cd(e,[],!1).filter(l=>Ri(l)&&As(l)!=="body"),o=null;const i=Xr(e).position==="fixed";let s=i?cc(e):e;for(;Ri(s)&&!Bm(s);){const l=Xr(s),u=mx(s);!u&&l.position==="fixed"&&(o=null),(i?!u&&!o:!u&&l.position==="static"&&!!o&&["absolute","fixed"].includes(o.position)||Fd(s)&&!u&&FT(e,s))?r=r.filter(m=>m!==s):o=l,s=cc(s)}return t.set(e,r),r}function JB(e){let{element:t,boundary:n,rootBoundary:r,strategy:o}=e;const s=[...n==="clippingAncestors"?QB(t,this._c):[].concat(n),r],l=s[0],u=s.reduce((f,m)=>{const p=zC(t,m,o);return f.top=hr(p.top,f.top),f.right=Ts(p.right,f.right),f.bottom=Ts(p.bottom,f.bottom),f.left=hr(p.left,f.left),f},zC(t,l,o));return{width:u.right-u.left,height:u.bottom-u.top,x:u.left,y:u.top}}function eU(e){return DT(e)}function tU(e,t,n){const r=qo(t),o=Mi(t),i=n==="fixed",s=Na(e,!0,i,t);let l={scrollLeft:0,scrollTop:0};const u=Ps(0);if(r||!r&&!i)if((As(t)!=="body"||Fd(o))&&(l=Um(t)),r){const f=Na(t,!0,i,t);u.x=f.x+t.clientLeft,u.y=f.y+t.clientTop}else o&&(u.x=LT(o));return{x:s.left+l.scrollLeft-u.x,y:s.top+l.scrollTop-u.y,width:s.width,height:s.height}}function BC(e,t){return!qo(e)||Xr(e).position==="fixed"?null:t?t(e):e.offsetParent}function jT(e,t){const n=vr(e);if(!qo(e))return n;let r=BC(e,t);for(;r&&VB(r)&&Xr(r).position==="static";)r=BC(r,t);return r&&(As(r)==="html"||As(r)==="body"&&Xr(r).position==="static"&&!mx(r))?n:r||WB(e)||n}const nU=async function(e){let{reference:t,floating:n,strategy:r}=e;const o=this.getOffsetParent||jT,i=this.getDimensions;return{reference:tU(t,await o(n),r),floating:{x:0,y:0,...await i(n)}}};function rU(e){return Xr(e).direction==="rtl"}const oU={convertOffsetParentRelativeRectToViewportRelativeRect:GB,getDocumentElement:Mi,getClippingRect:JB,getOffsetParent:jT,getElementRects:nU,getClientRects:YB,getDimensions:eU,getScale:Nl,isElement:Ri,isRTL:rU};function iU(e,t){let n=null,r;const o=Mi(e);function i(){clearTimeout(r),n&&n.disconnect(),n=null}function s(l,u){l===void 0&&(l=!1),u===void 0&&(u=1),i();const{left:f,top:m,width:p,height:g}=e.getBoundingClientRect();if(l||t(),!p||!g)return;const y=fh(m),b=fh(o.clientWidth-(f+p)),S=fh(o.clientHeight-(m+g)),E=fh(f),x={rootMargin:-y+"px "+-b+"px "+-S+"px "+-E+"px",threshold:hr(0,Ts(1,u))||1};let C=!0;function R(P){const M=P[0].intersectionRatio;if(M!==u){if(!C)return s();M?s(!1,M):r=setTimeout(()=>{s(!1,1e-7)},100)}C=!1}try{n=new IntersectionObserver(R,{...x,root:o.ownerDocument})}catch{n=new IntersectionObserver(R,x)}n.observe(e)}return s(!0),i}function sU(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:o=!0,ancestorResize:i=!0,elementResize:s=typeof ResizeObserver=="function",layoutShift:l=typeof IntersectionObserver=="function",animationFrame:u=!1}=r,f=vx(e),m=o||i?[...f?cd(f):[],...cd(t)]:[];m.forEach(_=>{o&&_.addEventListener("scroll",n,{passive:!0}),i&&_.addEventListener("resize",n)});const p=f&&l?iU(f,n):null;let g=-1,y=null;s&&(y=new ResizeObserver(_=>{let[x]=_;x&&x.target===f&&y&&(y.unobserve(t),cancelAnimationFrame(g),g=requestAnimationFrame(()=>{y&&y.observe(t)})),n()}),f&&!u&&y.observe(f),y.observe(t));let b,S=u?Na(e):null;u&&E();function E(){const _=Na(e);S&&(_.x!==S.x||_.y!==S.y||_.width!==S.width||_.height!==S.height)&&n(),S=_,b=requestAnimationFrame(E)}return n(),()=>{m.forEach(_=>{o&&_.removeEventListener("scroll",n),i&&_.removeEventListener("resize",n)}),p&&p(),y&&y.disconnect(),y=null,u&&cancelAnimationFrame(b)}}const aU=(e,t,n)=>{const r=new Map,o={platform:oU,...n},i={...o.platform,_c:r};return DB(e,t,{...o,platform:i})},lU=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:o}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?IC({element:r.current,padding:o}).fn(n):{}:r?IC({element:r,padding:o}).fn(n):{}}}};var Zh=typeof document<"u"?d.useLayoutEffect:d.useEffect;function jp(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(!jp(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(!{}.hasOwnProperty.call(t,o[r]))return!1;for(r=n;r--!==0;){const i=o[r];if(!(i==="_owner"&&e.$$typeof)&&!jp(e[i],t[i]))return!1}return!0}return e!==e&&t!==t}function zT(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function UC(e,t){const n=zT(e);return Math.round(t*n)/n}function VC(e){const t=d.useRef(e);return Zh(()=>{t.current=e}),t}function cU(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:o,elements:{reference:i,floating:s}={},transform:l=!0,whileElementsMounted:u,open:f}=e,[m,p]=d.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[g,y]=d.useState(r);jp(g,r)||y(r);const[b,S]=d.useState(null),[E,_]=d.useState(null),x=d.useCallback(N=>{N!=M.current&&(M.current=N,S(N))},[S]),C=d.useCallback(N=>{N!==A.current&&(A.current=N,_(N))},[_]),R=i||b,P=s||E,M=d.useRef(null),A=d.useRef(null),D=d.useRef(m),U=VC(u),W=VC(o),q=d.useCallback(()=>{if(!M.current||!A.current)return;const N={placement:t,strategy:n,middleware:g};W.current&&(N.platform=W.current),aU(M.current,A.current,N).then(ie=>{const K={...ie,isPositioned:!0};X.current&&!jp(D.current,K)&&(D.current=K,Is.flushSync(()=>{p(K)}))})},[g,t,n,W]);Zh(()=>{f===!1&&D.current.isPositioned&&(D.current.isPositioned=!1,p(N=>({...N,isPositioned:!1})))},[f]);const X=d.useRef(!1);Zh(()=>(X.current=!0,()=>{X.current=!1}),[]),Zh(()=>{if(R&&(M.current=R),P&&(A.current=P),R&&P){if(U.current)return U.current(R,P,q);q()}},[R,P,q,U]);const ae=d.useMemo(()=>({reference:M,floating:A,setReference:x,setFloating:C}),[x,C]),V=d.useMemo(()=>({reference:R,floating:P}),[R,P]),F=d.useMemo(()=>{const N={position:n,left:0,top:0};if(!V.floating)return N;const ie=UC(V.floating,m.x),K=UC(V.floating,m.y);return l?{...N,transform:"translate("+ie+"px, "+K+"px)",...zT(V.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:ie,top:K}},[n,l,V.floating,m.x,m.y]);return d.useMemo(()=>({...m,update:q,refs:ae,elements:V,floatingStyles:F}),[m,q,ae,V,F])}function yx(e){const[t,n]=d.useState(void 0);return An(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(o=>{if(!Array.isArray(o)||!o.length)return;const i=o[0];let s,l;if("borderBoxSize"in i){const u=i.borderBoxSize,f=Array.isArray(u)?u[0]:u;s=f.inlineSize,l=f.blockSize}else s=e.offsetWidth,l=e.offsetHeight;n({width:s,height:l})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}const BT="Popper",[UT,Fs]=Mn(BT),[uU,VT]=UT(BT),dU=e=>{const{__scopePopper:t,children:n}=e,[r,o]=d.useState(null);return d.createElement(uU,{scope:t,anchor:r,onAnchorChange:o},n)},fU="PopperAnchor",hU=d.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...o}=e,i=VT(fU,n),s=d.useRef(null),l=Be(t,s);return d.useEffect(()=>{i.onAnchorChange((r==null?void 0:r.current)||s.current)}),r?null:d.createElement(Pe.div,Y({},o,{ref:l}))}),WT="PopperContent",[pU,pte]=UT(WT),mU=d.forwardRef((e,t)=>{var n,r,o,i,s,l,u,f;const{__scopePopper:m,side:p="bottom",sideOffset:g=0,align:y="center",alignOffset:b=0,arrowPadding:S=0,avoidCollisions:E=!0,collisionBoundary:_=[],collisionPadding:x=0,sticky:C="partial",hideWhenDetached:R=!1,updatePositionStrategy:P="optimized",onPlaced:M,...A}=e,D=VT(WT,m),[U,W]=d.useState(null),q=Be(t,Kt=>W(Kt)),[X,ae]=d.useState(null),V=yx(X),F=(n=V==null?void 0:V.width)!==null&&n!==void 0?n:0,N=(r=V==null?void 0:V.height)!==null&&r!==void 0?r:0,ie=p+(y!=="center"?"-"+y:""),K=typeof x=="number"?x:{top:0,right:0,bottom:0,left:0,...x},Z=Array.isArray(_)?_:[_],H=Z.length>0,se={padding:K,boundary:Z.filter(gU),altBoundary:H},{refs:ce,floatingStyles:Ve,placement:Ue,isPositioned:We,middlewareData:Oe}=cU({strategy:"fixed",placement:ie,whileElementsMounted:(...Kt)=>sU(...Kt,{animationFrame:P==="always"}),elements:{reference:D.anchor},middleware:[jB({mainAxis:g+N,alignmentAxis:b}),E&&zB({mainAxis:!0,crossAxis:!1,limiter:C==="partial"?BB():void 0,...se}),E&&IB({...se}),UB({...se,apply:({elements:Kt,rects:Er,availableWidth:gt,availableHeight:Vs})=>{const{width:L,height:Q}=Er.reference,J=Kt.floating.style;J.setProperty("--radix-popper-available-width",`${gt}px`),J.setProperty("--radix-popper-available-height",`${Vs}px`),J.setProperty("--radix-popper-anchor-width",`${L}px`),J.setProperty("--radix-popper-anchor-height",`${Q}px`)}}),X&&lU({element:X,padding:S}),vU({arrowWidth:F,arrowHeight:N}),R&&LB({strategy:"referenceHidden",...se})]}),[he,xe]=HT(Ue),$e=Ft(M);An(()=>{We&&($e==null||$e())},[We,$e]);const Ae=(o=Oe.arrow)===null||o===void 0?void 0:o.x,Me=(i=Oe.arrow)===null||i===void 0?void 0:i.y,je=((s=Oe.arrow)===null||s===void 0?void 0:s.centerOffset)!==0,[Mt,ct]=d.useState();return An(()=>{U&&ct(window.getComputedStyle(U).zIndex)},[U]),d.createElement("div",{ref:ce.setFloating,"data-radix-popper-content-wrapper":"",style:{...Ve,transform:We?Ve.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:Mt,"--radix-popper-transform-origin":[(l=Oe.transformOrigin)===null||l===void 0?void 0:l.x,(u=Oe.transformOrigin)===null||u===void 0?void 0:u.y].join(" ")},dir:e.dir},d.createElement(pU,{scope:m,placedSide:he,onArrowChange:ae,arrowX:Ae,arrowY:Me,shouldHideArrow:je},d.createElement(Pe.div,Y({"data-side":he,"data-align":xe},A,{ref:q,style:{...A.style,animation:We?void 0:"none",opacity:(f=Oe.hide)!==null&&f!==void 0&&f.referenceHidden?0:void 0}}))))});function gU(e){return e!==null}const vU=e=>({name:"transformOrigin",options:e,fn(t){var n,r,o,i,s;const{placement:l,rects:u,middlewareData:f}=t,p=((n=f.arrow)===null||n===void 0?void 0:n.centerOffset)!==0,g=p?0:e.arrowWidth,y=p?0:e.arrowHeight,[b,S]=HT(l),E={start:"0%",center:"50%",end:"100%"}[S],_=((r=(o=f.arrow)===null||o===void 0?void 0:o.x)!==null&&r!==void 0?r:0)+g/2,x=((i=(s=f.arrow)===null||s===void 0?void 0:s.y)!==null&&i!==void 0?i:0)+y/2;let C="",R="";return b==="bottom"?(C=p?E:`${_}px`,R=`${-y}px`):b==="top"?(C=p?E:`${_}px`,R=`${u.floating.height+y}px`):b==="right"?(C=`${-y}px`,R=p?E:`${x}px`):b==="left"&&(C=`${u.floating.width+y}px`,R=p?E:`${x}px`),{data:{x:C,y:R}}}});function HT(e){const[t,n="center"]=e.split("-");return[t,n]}const jd=dU,Vm=hU,Wm=mU,zd=d.forwardRef((e,t)=>{var n;const{container:r=globalThis==null||(n=globalThis.document)===null||n===void 0?void 0:n.body,...o}=e;return r?QI.createPortal(d.createElement(Pe.div,Y({},o,{ref:t})),r):null});function yU(e,t){return d.useReducer((n,r)=>{const o=t[n][r];return o??n},e)}const Sn=e=>{const{present:t,children:n}=e,r=wU(t),o=typeof n=="function"?n({present:r.isPresent}):d.Children.only(n),i=Be(r.ref,o.ref);return typeof n=="function"||r.isPresent?d.cloneElement(o,{ref:i}):null};Sn.displayName="Presence";function wU(e){const[t,n]=d.useState(),r=d.useRef({}),o=d.useRef(e),i=d.useRef("none"),s=e?"mounted":"unmounted",[l,u]=yU(s,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return d.useEffect(()=>{const f=hh(r.current);i.current=l==="mounted"?f:"none"},[l]),An(()=>{const f=r.current,m=o.current;if(m!==e){const g=i.current,y=hh(f);e?u("MOUNT"):y==="none"||(f==null?void 0:f.display)==="none"?u("UNMOUNT"):u(m&&g!==y?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,u]),An(()=>{if(t){const f=p=>{const y=hh(r.current).includes(p.animationName);p.target===t&&y&&Is.flushSync(()=>u("ANIMATION_END"))},m=p=>{p.target===t&&(i.current=hh(r.current))};return t.addEventListener("animationstart",m),t.addEventListener("animationcancel",f),t.addEventListener("animationend",f),()=>{t.removeEventListener("animationstart",m),t.removeEventListener("animationcancel",f),t.removeEventListener("animationend",f)}}else u("ANIMATION_END")},[t,u]),{isPresent:["mounted","unmountSuspended"].includes(l),ref:d.useCallback(f=>{f&&(r.current=getComputedStyle(f)),n(f)},[])}}function hh(e){return(e==null?void 0:e.animationName)||"none"}function Zr({prop:e,defaultProp:t,onChange:n=()=>{}}){const[r,o]=xU({defaultProp:t,onChange:n}),i=e!==void 0,s=i?e:r,l=Ft(n),u=d.useCallback(f=>{if(i){const p=typeof f=="function"?f(e):f;p!==e&&l(p)}else o(f)},[i,e,o,l]);return[s,u]}function xU({defaultProp:e,onChange:t}){const n=d.useState(e),[r]=n,o=d.useRef(r),i=Ft(t);return d.useEffect(()=>{o.current!==r&&(i(r),o.current=r)},[r,o,i]),n}const Hm=d.forwardRef((e,t)=>d.createElement(Pe.span,Y({},e,{ref:t,style:{position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal",...e.style}}))),bU=Hm,[Km,mte]=Mn("Tooltip",[Fs]),wx=Fs(),SU="TooltipProvider",_U=700,d1="tooltip.open",[EU,xx]=Km(SU),CU=e=>{const{__scopeTooltip:t,delayDuration:n=_U,skipDelayDuration:r=300,disableHoverableContent:o=!1,children:i}=e,[s,l]=d.useState(!0),u=d.useRef(!1),f=d.useRef(0);return d.useEffect(()=>{const m=f.current;return()=>window.clearTimeout(m)},[]),d.createElement(EU,{scope:t,isOpenDelayed:s,delayDuration:n,onOpen:d.useCallback(()=>{window.clearTimeout(f.current),l(!1)},[]),onClose:d.useCallback(()=>{window.clearTimeout(f.current),f.current=window.setTimeout(()=>l(!0),r)},[r]),isPointerInTransitRef:u,onPointerInTransitChange:d.useCallback(m=>{u.current=m},[]),disableHoverableContent:o},i)},bx="Tooltip",[$U,Gm]=Km(bx),RU=e=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:o=!1,onOpenChange:i,disableHoverableContent:s,delayDuration:l}=e,u=xx(bx,e.__scopeTooltip),f=wx(t),[m,p]=d.useState(null),g=nr(),y=d.useRef(0),b=s??u.disableHoverableContent,S=l??u.delayDuration,E=d.useRef(!1),[_=!1,x]=Zr({prop:r,defaultProp:o,onChange:A=>{A?(u.onOpen(),document.dispatchEvent(new CustomEvent(d1))):u.onClose(),i==null||i(A)}}),C=d.useMemo(()=>_?E.current?"delayed-open":"instant-open":"closed",[_]),R=d.useCallback(()=>{window.clearTimeout(y.current),E.current=!1,x(!0)},[x]),P=d.useCallback(()=>{window.clearTimeout(y.current),x(!1)},[x]),M=d.useCallback(()=>{window.clearTimeout(y.current),y.current=window.setTimeout(()=>{E.current=!0,x(!0)},S)},[S,x]);return d.useEffect(()=>()=>window.clearTimeout(y.current),[]),d.createElement(jd,f,d.createElement($U,{scope:t,contentId:g,open:_,stateAttribute:C,trigger:m,onTriggerChange:p,onTriggerEnter:d.useCallback(()=>{u.isOpenDelayed?M():R()},[u.isOpenDelayed,M,R]),onTriggerLeave:d.useCallback(()=>{b?P():window.clearTimeout(y.current)},[P,b]),onOpen:R,onClose:P,disableHoverableContent:b},n))},WC="TooltipTrigger",kU=d.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,o=Gm(WC,n),i=xx(WC,n),s=wx(n),l=d.useRef(null),u=Be(t,l,o.onTriggerChange),f=d.useRef(!1),m=d.useRef(!1),p=d.useCallback(()=>f.current=!1,[]);return d.useEffect(()=>()=>document.removeEventListener("pointerup",p),[p]),d.createElement(Vm,Y({asChild:!0},s),d.createElement(Pe.button,Y({"aria-describedby":o.open?o.contentId:void 0,"data-state":o.stateAttribute},r,{ref:u,onPointerMove:de(e.onPointerMove,g=>{g.pointerType!=="touch"&&!m.current&&!i.isPointerInTransitRef.current&&(o.onTriggerEnter(),m.current=!0)}),onPointerLeave:de(e.onPointerLeave,()=>{o.onTriggerLeave(),m.current=!1}),onPointerDown:de(e.onPointerDown,()=>{f.current=!0,document.addEventListener("pointerup",p,{once:!0})}),onFocus:de(e.onFocus,()=>{f.current||o.onOpen()}),onBlur:de(e.onBlur,o.onClose),onClick:de(e.onClick,o.onClose)})))}),TU="TooltipPortal",[gte,PU]=Km(TU,{forceMount:void 0}),ud="TooltipContent",AU=d.forwardRef((e,t)=>{const n=PU(ud,e.__scopeTooltip),{forceMount:r=n.forceMount,side:o="top",...i}=e,s=Gm(ud,e.__scopeTooltip);return d.createElement(Sn,{present:r||s.open},s.disableHoverableContent?d.createElement(KT,Y({side:o},i,{ref:t})):d.createElement(MU,Y({side:o},i,{ref:t})))}),MU=d.forwardRef((e,t)=>{const n=Gm(ud,e.__scopeTooltip),r=xx(ud,e.__scopeTooltip),o=d.useRef(null),i=Be(t,o),[s,l]=d.useState(null),{trigger:u,onClose:f}=n,m=o.current,{onPointerInTransitChange:p}=r,g=d.useCallback(()=>{l(null),p(!1)},[p]),y=d.useCallback((b,S)=>{const E=b.currentTarget,_={x:b.clientX,y:b.clientY},x=NU(_,E.getBoundingClientRect()),C=DU(_,x),R=IU(S.getBoundingClientRect()),P=FU([...C,...R]);l(P),p(!0)},[p]);return d.useEffect(()=>()=>g(),[g]),d.useEffect(()=>{if(u&&m){const b=E=>y(E,m),S=E=>y(E,u);return u.addEventListener("pointerleave",b),m.addEventListener("pointerleave",S),()=>{u.removeEventListener("pointerleave",b),m.removeEventListener("pointerleave",S)}}},[u,m,y,g]),d.useEffect(()=>{if(s){const b=S=>{const E=S.target,_={x:S.clientX,y:S.clientY},x=(u==null?void 0:u.contains(E))||(m==null?void 0:m.contains(E)),C=!LU(_,s);x?g():C&&(g(),f())};return document.addEventListener("pointermove",b),()=>document.removeEventListener("pointermove",b)}},[u,m,s,f,g]),d.createElement(KT,Y({},e,{ref:i}))}),[OU,vte]=Km(bx,{isInside:!1}),KT=d.forwardRef((e,t)=>{const{__scopeTooltip:n,children:r,"aria-label":o,onEscapeKeyDown:i,onPointerDownOutside:s,...l}=e,u=Gm(ud,n),f=wx(n),{onClose:m}=u;return d.useEffect(()=>(document.addEventListener(d1,m),()=>document.removeEventListener(d1,m)),[m]),d.useEffect(()=>{if(u.trigger){const p=g=>{const y=g.target;y!=null&&y.contains(u.trigger)&&m()};return window.addEventListener("scroll",p,{capture:!0}),()=>window.removeEventListener("scroll",p,{capture:!0})}},[u.trigger,m]),d.createElement(Ec,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:i,onPointerDownOutside:s,onFocusOutside:p=>p.preventDefault(),onDismiss:m},d.createElement(Wm,Y({"data-state":u.stateAttribute},f,l,{ref:t,style:{...l.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"}}),d.createElement(lx,null,r),d.createElement(OU,{scope:n,isInside:!0},d.createElement(bU,{id:u.contentId,role:"tooltip"},o||r))))});function NU(e,t){const n=Math.abs(t.top-e.y),r=Math.abs(t.bottom-e.y),o=Math.abs(t.right-e.x),i=Math.abs(t.left-e.x);switch(Math.min(n,r,o,i)){case i:return"left";case o:return"right";case n:return"top";case r:return"bottom";default:throw new Error("unreachable")}}function DU(e,t,n=5){const r=[];switch(t){case"top":r.push({x:e.x-n,y:e.y+n},{x:e.x+n,y:e.y+n});break;case"bottom":r.push({x:e.x-n,y:e.y-n},{x:e.x+n,y:e.y-n});break;case"left":r.push({x:e.x+n,y:e.y-n},{x:e.x+n,y:e.y+n});break;case"right":r.push({x:e.x-n,y:e.y-n},{x:e.x-n,y:e.y+n});break}return r}function IU(e){const{top:t,right:n,bottom:r,left:o}=e;return[{x:o,y:t},{x:n,y:t},{x:n,y:r},{x:o,y:r}]}function LU(e,t){const{x:n,y:r}=e;let o=!1;for(let i=0,s=t.length-1;ir!=m>r&&n<(f-l)*(r-u)/(m-u)+l&&(o=!o)}return o}function FU(e){const t=e.slice();return t.sort((n,r)=>n.xr.x?1:n.yr.y?1:0),jU(t)}function jU(e){if(e.length<=1)return e.slice();const t=[];for(let r=0;r=2;){const i=t[t.length-1],s=t[t.length-2];if((i.x-s.x)*(o.y-s.y)>=(i.y-s.y)*(o.x-s.x))t.pop();else break}t.push(o)}t.pop();const n=[];for(let r=e.length-1;r>=0;r--){const o=e[r];for(;n.length>=2;){const i=n[n.length-1],s=n[n.length-2];if((i.x-s.x)*(o.y-s.y)>=(i.y-s.y)*(o.x-s.x))n.pop();else break}n.push(o)}return n.pop(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}const zU=CU,BU=RU,UU=kU,GT=AU,VU=zU,YT=BU,XT=UU,Sx=d.forwardRef(({className:e,sideOffset:t=4,...n},r)=>v.jsx(GT,{ref:r,sideOffset:t,className:Ce("z-50 border overflow-hidden rounded-md bg-background text-foreground px-3 py-1.5 text-xs animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...n}));Sx.displayName=GT.displayName;const _x=Dm("inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50",{variants:{variant:{default:"bg-primary text-primary-foreground shadow hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",outline:"border border-input bg-transparent shadow-sm hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2",sm:"h-8 rounded-md px-3 text-xs",lg:"h-10 rounded-md px-8",icon:"h-9 w-9"}},defaultVariants:{variant:"default",size:"default"}}),wn=d.forwardRef(({className:e,variant:t,size:n,asChild:r=!1,...o},i)=>{const s=r?Zo:"button";return v.jsx(s,{className:Ce(_x({variant:t,size:n,className:e}),"outline-none cursor-default"),ref:i,tabIndex:-1,...o})});wn.displayName="Button";const yn=d.forwardRef(({tooltip:e,children:t,...n},r)=>v.jsxs(YT,{children:[v.jsx(XT,{asChild:!0,children:v.jsx(wn,{variant:"ghost",size:"icon",...n,ref:r,tabIndex:-1,className:"cursor-default bg-background",children:v.jsx("div",{className:"icon-button-icon-wrapper",children:t})})}),v.jsx(Sx,{children:v.jsx("p",{children:e})})]})),f1=e=>{const{onFileUpload:t,children:n,...r}=e,[o]=d.useState(`file-upload-${Math.random().toString()}`),i=s=>{var u;const l=(u=s.currentTarget.files)==null?void 0:u[0];l&&t(l)};return v.jsxs(v.Fragment,{children:[v.jsx("label",{htmlFor:o,children:v.jsx(yn,{...r,asChild:!0,children:n})}),v.jsx(Ld,{style:{display:"none"},id:o,name:o,type:"file",onChange:i,accept:"image/png, image/jpeg"})]})};var WU={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const HU=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Jt=(e,t)=>{const n=d.forwardRef(({color:r="currentColor",size:o=24,strokeWidth:i=2,absoluteStrokeWidth:s,children:l,...u},f)=>d.createElement("svg",{ref:f,...WU,width:o,height:o,stroke:r,strokeWidth:s?Number(i)*24/Number(o):i,className:`lucide lucide-${HU(e)}`,...u},[...t.map(([m,p])=>d.createElement(m,p)),...(Array.isArray(l)?l:[l])||[]]));return n.displayName=`${e}`,n},KU=Jt("Blocks",[["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["path",{d:"M10 21V8a1 1 0 0 0-1-1H4a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-5a1 1 0 0 0-1-1H3",key:"1fpvtg"}]]),GU=Jt("ChevronLeft",[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]]),YU=Jt("ChevronRight",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]),XU=Jt("Coffee",[["path",{d:"M17 8h1a4 4 0 1 1 0 8h-1",key:"jx4kbh"}],["path",{d:"M3 8h14v9a4 4 0 0 1-4 4H7a4 4 0 0 1-4-4Z",key:"1bxrl0"}],["line",{x1:"6",x2:"6",y1:"2",y2:"4",key:"1cr9l3"}],["line",{x1:"10",x2:"10",y1:"2",y2:"4",key:"170wym"}],["line",{x1:"14",x2:"14",y1:"2",y2:"4",key:"1c5f70"}]]),ZU=Jt("Download",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"7 10 12 15 17 10",key:"2ggqvy"}],["line",{x1:"12",x2:"12",y1:"15",y2:"3",key:"1vk2je"}]]),qU=Jt("Eraser",[["path",{d:"m7 21-4.3-4.3c-1-1-1-2.5 0-3.4l9.6-9.6c1-1 2.5-1 3.4 0l5.6 5.6c1 1 1 2.5 0 3.4L13 21",key:"182aya"}],["path",{d:"M22 21H7",key:"t4ddhn"}],["path",{d:"m5 11 9 9",key:"1mo9qw"}]]),QU=Jt("Expand",[["path",{d:"m21 21-6-6m6 6v-4.8m0 4.8h-4.8",key:"1c15vz"}],["path",{d:"M3 16.2V21m0 0h4.8M3 21l6-6",key:"1fsnz2"}],["path",{d:"M21 7.8V3m0 0h-4.8M21 3l-6 6",key:"hawz9i"}],["path",{d:"M3 7.8V3m0 0h4.8M3 3l6 6",key:"u9ee12"}]]),JU=Jt("Eye",[["path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z",key:"rwhkz3"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]),eV=Jt("FolderClosed",[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}],["path",{d:"M2 10h20",key:"1ir3d8"}]]),ZT=Jt("Fullscreen",[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}],["rect",{width:"10",height:"8",x:"7",y:"8",rx:"1",key:"vys8me"}]]),tV=Jt("Image",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]]),nV=Jt("Keyboard",[["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",ry:"2",key:"15u882"}],["path",{d:"M6 8h.001",key:"1ej0i3"}],["path",{d:"M10 8h.001",key:"1x2st2"}],["path",{d:"M14 8h.001",key:"1vkmyp"}],["path",{d:"M18 8h.001",key:"kfsenl"}],["path",{d:"M8 12h.001",key:"1sjpby"}],["path",{d:"M12 12h.001",key:"al75ts"}],["path",{d:"M16 12h.001",key:"931bgk"}],["path",{d:"M7 16h10",key:"wp8him"}]]),rV=Jt("MousePointerClick",[["path",{d:"m9 9 5 12 1.8-5.2L21 14Z",key:"1b76lo"}],["path",{d:"M7.2 2.2 8 5.1",key:"1cfko1"}],["path",{d:"m5.1 8-2.9-.8",key:"1go3kf"}],["path",{d:"M14 4.1 12 6",key:"ita8i4"}],["path",{d:"m6 12-1.9 2",key:"mnht97"}]]),oV=Jt("Redo",[["path",{d:"M21 7v6h-6",key:"3ptur4"}],["path",{d:"M3 17a9 9 0 0 1 9-9 9 9 0 0 1 6 2.3l3 2.7",key:"1kgawr"}]]),iV=Jt("RotateCw",[["path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8",key:"1p45f6"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}]]),sV=Jt("Settings",[["path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z",key:"1qme2f"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]),HC=Jt("Slice",[["path",{d:"m8 14-6 6h9v-3",key:"zo3j9a"}],["path",{d:"M18.37 3.63 8 14l3 3L21.37 6.63a2.12 2.12 0 1 0-3-3Z",key:"1dzx0j"}]]),KC=Jt("Smile",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 14s1.5 2 4 2 4-2 4-2",key:"1y1vjs"}],["line",{x1:"9",x2:"9.01",y1:"9",y2:"9",key:"yxxnd0"}],["line",{x1:"15",x2:"15.01",y1:"9",y2:"9",key:"1p4y9e"}]]),aV=Jt("Undo",[["path",{d:"M3 7v6h6",key:"1v2h90"}],["path",{d:"M21 17a9 9 0 0 0-9-9 9 9 0 0 0-6 2.3L3 13",key:"1r6uu6"}]]),qT=Jt("Upload",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"17 8 12 3 7 8",key:"t8dd8p"}],["line",{x1:"12",x2:"12",y1:"3",y2:"15",key:"widbto"}]]);function lV(e,t){const[n,r]=d.useState(e);return d.useEffect(()=>{const o=setTimeout(()=>{r(e)},t);return()=>{clearTimeout(o)}},[e,t]),n}function QT(e){const[t,n]=d.useState(()=>typeof e=="boolean"?e:!!e),r=d.useCallback(o=>n(typeof o=="boolean"?o:i=>!i),[]);return[t,r]}const _0="focusScope.autoFocusOnMount",E0="focusScope.autoFocusOnUnmount",GC={bubbles:!1,cancelable:!0},Ym=d.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:o,onUnmountAutoFocus:i,...s}=e,[l,u]=d.useState(null),f=Ft(o),m=Ft(i),p=d.useRef(null),g=Be(t,S=>u(S)),y=d.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;d.useEffect(()=>{if(r){let x=function(M){if(y.paused||!l)return;const A=M.target;l.contains(A)?p.current=A:Qi(p.current,{select:!0})},C=function(M){if(y.paused||!l)return;const A=M.relatedTarget;A!==null&&(l.contains(A)||Qi(p.current,{select:!0}))},R=function(M){if(document.activeElement===document.body)for(const D of M)D.removedNodes.length>0&&Qi(l)};var S=x,E=C,_=R;document.addEventListener("focusin",x),document.addEventListener("focusout",C);const P=new MutationObserver(R);return l&&P.observe(l,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",x),document.removeEventListener("focusout",C),P.disconnect()}}},[r,l,y.paused]),d.useEffect(()=>{if(l){XC.add(y);const S=document.activeElement;if(!l.contains(S)){const _=new CustomEvent(_0,GC);l.addEventListener(_0,f),l.dispatchEvent(_),_.defaultPrevented||(cV(pV(JT(l)),{select:!0}),document.activeElement===S&&Qi(l))}return()=>{l.removeEventListener(_0,f),setTimeout(()=>{const _=new CustomEvent(E0,GC);l.addEventListener(E0,m),l.dispatchEvent(_),_.defaultPrevented||Qi(S??document.body,{select:!0}),l.removeEventListener(E0,m),XC.remove(y)},0)}}},[l,f,m,y]);const b=d.useCallback(S=>{if(!n&&!r||y.paused)return;const E=S.key==="Tab"&&!S.altKey&&!S.ctrlKey&&!S.metaKey,_=document.activeElement;if(E&&_){const x=S.currentTarget,[C,R]=uV(x);C&&R?!S.shiftKey&&_===R?(S.preventDefault(),n&&Qi(C,{select:!0})):S.shiftKey&&_===C&&(S.preventDefault(),n&&Qi(R,{select:!0})):_===x&&S.preventDefault()}},[n,r,y.paused]);return d.createElement(Pe.div,Y({tabIndex:-1},s,{ref:g,onKeyDown:b}))});function cV(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(Qi(r,{select:t}),document.activeElement!==n)return}function uV(e){const t=JT(e),n=YC(t,e),r=YC(t.reverse(),e);return[n,r]}function JT(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const o=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||o?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function YC(e,t){for(const n of e)if(!dV(n,{upTo:t}))return n}function dV(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function fV(e){return e instanceof HTMLInputElement&&"select"in e}function Qi(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&fV(e)&&t&&e.select()}}const XC=hV();function hV(){let e=[];return{add(t){const n=e[0];t!==n&&(n==null||n.pause()),e=ZC(e,t),e.unshift(t)},remove(t){var n;e=ZC(e,t),(n=e[0])===null||n===void 0||n.resume()}}}function ZC(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function pV(e){return e.filter(t=>t.tagName!=="A")}let C0=0;function Xm(){d.useEffect(()=>{var e,t;const n=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",(e=n[0])!==null&&e!==void 0?e:qC()),document.body.insertAdjacentElement("beforeend",(t=n[1])!==null&&t!==void 0?t:qC()),C0++,()=>{C0===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(r=>r.remove()),C0--}},[])}function qC(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.cssText="outline: none; opacity: 0; position: fixed; pointer-events: none",e}var Lo=function(){return Lo=Object.assign||function(t){for(var n,r=1,o=arguments.length;r"u")return AV;var t=MV(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])}},NV=rP(),DV=function(e,t,n,r){var o=e.left,i=e.top,s=e.right,l=e.gap;return n===void 0&&(n="margin"),` + .`.concat(gV,` { + overflow: hidden `).concat(r,`; + padding-right: `).concat(l,"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(i,`px; + padding-right: `).concat(s,`px; + margin-left:0; + margin-top:0; + margin-right: `).concat(l,"px ").concat(r,`; + `),n==="padding"&&"padding-right: ".concat(l,"px ").concat(r,";")].filter(Boolean).join(""),` + } + + .`).concat(qh,` { + right: `).concat(l,"px ").concat(r,`; + } + + .`).concat(Qh,` { + margin-right: `).concat(l,"px ").concat(r,`; + } + + .`).concat(qh," .").concat(qh,` { + right: 0 `).concat(r,`; + } + + .`).concat(Qh," .").concat(Qh,` { + margin-right: 0 `).concat(r,`; + } + + body { + `).concat(vV,": ").concat(l,`px; + } +`)},IV=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,o=r===void 0?"margin":r,i=d.useMemo(function(){return OV(o)},[o]);return d.createElement(NV,{styles:DV(i,!t,o,n?"":"!important")})},h1=!1;if(typeof window<"u")try{var ph=Object.defineProperty({},"passive",{get:function(){return h1=!0,!0}});window.addEventListener("test",ph,ph),window.removeEventListener("test",ph,ph)}catch{h1=!1}var rl=h1?{passive:!1}:!1,LV=function(e){return e.tagName==="TEXTAREA"},oP=function(e,t){var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!LV(e)&&n[t]==="visible")},FV=function(e){return oP(e,"overflowY")},jV=function(e){return oP(e,"overflowX")},JC=function(e,t){var n=t;do{typeof ShadowRoot<"u"&&n instanceof ShadowRoot&&(n=n.host);var r=iP(e,n);if(r){var o=sP(e,n),i=o[1],s=o[2];if(i>s)return!0}n=n.parentNode}while(n&&n!==document.body);return!1},zV=function(e){var t=e.scrollTop,n=e.scrollHeight,r=e.clientHeight;return[t,n,r]},BV=function(e){var t=e.scrollLeft,n=e.scrollWidth,r=e.clientWidth;return[t,n,r]},iP=function(e,t){return e==="v"?FV(t):jV(t)},sP=function(e,t){return e==="v"?zV(t):BV(t)},UV=function(e,t){return e==="h"&&t==="rtl"?-1:1},VV=function(e,t,n,r,o){var i=UV(e,window.getComputedStyle(t).direction),s=i*r,l=n.target,u=t.contains(l),f=!1,m=s>0,p=0,g=0;do{var y=sP(e,l),b=y[0],S=y[1],E=y[2],_=S-E-i*b;(b||_)&&iP(e,l)&&(p+=_,g+=b),l=l.parentNode}while(!u&&l!==document.body||u&&(t.contains(l)||t===l));return(m&&(o&&p===0||!o&&s>p)||!m&&(o&&g===0||!o&&-s>g))&&(f=!0),f},mh=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},e2=function(e){return[e.deltaX,e.deltaY]},t2=function(e){return e&&"current"in e?e.current:e},WV=function(e,t){return e[0]===t[0]&&e[1]===t[1]},HV=function(e){return` + .block-interactivity-`.concat(e,` {pointer-events: none;} + .allow-interactivity-`).concat(e,` {pointer-events: all;} +`)},KV=0,ol=[];function GV(e){var t=d.useRef([]),n=d.useRef([0,0]),r=d.useRef(),o=d.useState(KV++)[0],i=d.useState(function(){return rP()})[0],s=d.useRef(e);d.useEffect(function(){s.current=e},[e]),d.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(o));var S=mV([e.lockRef.current],(e.shards||[]).map(t2),!0).filter(Boolean);return S.forEach(function(E){return E.classList.add("allow-interactivity-".concat(o))}),function(){document.body.classList.remove("block-interactivity-".concat(o)),S.forEach(function(E){return E.classList.remove("allow-interactivity-".concat(o))})}}},[e.inert,e.lockRef.current,e.shards]);var l=d.useCallback(function(S,E){if("touches"in S&&S.touches.length===2)return!s.current.allowPinchZoom;var _=mh(S),x=n.current,C="deltaX"in S?S.deltaX:x[0]-_[0],R="deltaY"in S?S.deltaY:x[1]-_[1],P,M=S.target,A=Math.abs(C)>Math.abs(R)?"h":"v";if("touches"in S&&A==="h"&&M.type==="range")return!1;var D=JC(A,M);if(!D)return!0;if(D?P=A:(P=A==="v"?"h":"v",D=JC(A,M)),!D)return!1;if(!r.current&&"changedTouches"in S&&(C||R)&&(r.current=P),!P)return!0;var U=r.current||P;return VV(U,E,S,U==="h"?C:R,!0)},[]),u=d.useCallback(function(S){var E=S;if(!(!ol.length||ol[ol.length-1]!==i)){var _="deltaY"in E?e2(E):mh(E),x=t.current.filter(function(P){return P.name===E.type&&P.target===E.target&&WV(P.delta,_)})[0];if(x&&x.should){E.cancelable&&E.preventDefault();return}if(!x){var C=(s.current.shards||[]).map(t2).filter(Boolean).filter(function(P){return P.contains(E.target)}),R=C.length>0?l(E,C[0]):!s.current.noIsolation;R&&E.cancelable&&E.preventDefault()}}},[]),f=d.useCallback(function(S,E,_,x){var C={name:S,delta:E,target:_,should:x};t.current.push(C),setTimeout(function(){t.current=t.current.filter(function(R){return R!==C})},1)},[]),m=d.useCallback(function(S){n.current=mh(S),r.current=void 0},[]),p=d.useCallback(function(S){f(S.type,e2(S),S.target,l(S,e.lockRef.current))},[]),g=d.useCallback(function(S){f(S.type,mh(S),S.target,l(S,e.lockRef.current))},[]);d.useEffect(function(){return ol.push(i),e.setCallbacks({onScrollCapture:p,onWheelCapture:p,onTouchMoveCapture:g}),document.addEventListener("wheel",u,rl),document.addEventListener("touchmove",u,rl),document.addEventListener("touchstart",m,rl),function(){ol=ol.filter(function(S){return S!==i}),document.removeEventListener("wheel",u,rl),document.removeEventListener("touchmove",u,rl),document.removeEventListener("touchstart",m,rl)}},[]);var y=e.removeScrollBar,b=e.inert;return d.createElement(d.Fragment,null,b?d.createElement(i,{styles:HV(o)}):null,y?d.createElement(IV,{gapMode:"margin"}):null)}const YV=EV(nP,GV);var aP=d.forwardRef(function(e,t){return d.createElement(Zm,Lo({},e,{ref:t,sideCar:YV}))});aP.classNames=Zm.classNames;const qm=aP;var XV=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},il=new WeakMap,gh=new WeakMap,vh={},k0=0,lP=function(e){return e&&(e.host||lP(e.parentNode))},ZV=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=lP(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})},qV=function(e,t,n,r){var o=ZV(t,Array.isArray(e)?e:[e]);vh[n]||(vh[n]=new WeakMap);var i=vh[n],s=[],l=new Set,u=new Set(o),f=function(p){!p||l.has(p)||(l.add(p),f(p.parentNode))};o.forEach(f);var m=function(p){!p||u.has(p)||Array.prototype.forEach.call(p.children,function(g){if(l.has(g))m(g);else{var y=g.getAttribute(r),b=y!==null&&y!=="false",S=(il.get(g)||0)+1,E=(i.get(g)||0)+1;il.set(g,S),i.set(g,E),s.push(g),S===1&&b&&gh.set(g,!0),E===1&&g.setAttribute(n,"true"),b||g.setAttribute(r,"true")}})};return m(t),l.clear(),k0++,function(){s.forEach(function(p){var g=il.get(p)-1,y=i.get(p)-1;il.set(p,g),i.set(p,y),g||(gh.has(p)||p.removeAttribute(r),gh.delete(p)),y||p.removeAttribute(n)}),k0--,k0||(il=new WeakMap,il=new WeakMap,gh=new WeakMap,vh={})}},Qm=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),o=t||XV(e);return o?(r.push.apply(r,Array.from(o.querySelectorAll("[aria-live]"))),qV(r,o,n,"aria-hidden")):function(){return null}};const cP="Dialog",[uP,dP]=Mn(cP),[QV,Eo]=uP(cP),JV=e=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:o,onOpenChange:i,modal:s=!0}=e,l=d.useRef(null),u=d.useRef(null),[f=!1,m]=Zr({prop:r,defaultProp:o,onChange:i});return d.createElement(QV,{scope:t,triggerRef:l,contentRef:u,contentId:nr(),titleId:nr(),descriptionId:nr(),open:f,onOpenChange:m,onOpenToggle:d.useCallback(()=>m(p=>!p),[m]),modal:s},n)},eW="DialogTrigger",fP=d.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=Eo(eW,n),i=Be(t,o.triggerRef);return d.createElement(Pe.button,Y({type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":Ex(o.open)},r,{ref:i,onClick:de(e.onClick,o.onOpenToggle)}))}),hP="DialogPortal",[tW,pP]=uP(hP,{forceMount:void 0}),nW=e=>{const{__scopeDialog:t,forceMount:n,children:r,container:o}=e,i=Eo(hP,t);return d.createElement(tW,{scope:t,forceMount:n},d.Children.map(r,s=>d.createElement(Sn,{present:n||i.open},d.createElement(zd,{asChild:!0,container:o},s))))},p1="DialogOverlay",rW=d.forwardRef((e,t)=>{const n=pP(p1,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,i=Eo(p1,e.__scopeDialog);return i.modal?d.createElement(Sn,{present:r||i.open},d.createElement(oW,Y({},o,{ref:t}))):null}),oW=d.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=Eo(p1,n);return d.createElement(qm,{as:Zo,allowPinchZoom:!0,shards:[o.contentRef]},d.createElement(Pe.div,Y({"data-state":Ex(o.open)},r,{ref:t,style:{pointerEvents:"auto",...r.style}})))}),uc="DialogContent",iW=d.forwardRef((e,t)=>{const n=pP(uc,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,i=Eo(uc,e.__scopeDialog);return d.createElement(Sn,{present:r||i.open},i.modal?d.createElement(sW,Y({},o,{ref:t})):d.createElement(aW,Y({},o,{ref:t})))}),sW=d.forwardRef((e,t)=>{const n=Eo(uc,e.__scopeDialog),r=d.useRef(null),o=Be(t,n.contentRef,r);return d.useEffect(()=>{const i=r.current;if(i)return Qm(i)},[]),d.createElement(mP,Y({},e,{ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:de(e.onCloseAutoFocus,i=>{var s;i.preventDefault(),(s=n.triggerRef.current)===null||s===void 0||s.focus()}),onPointerDownOutside:de(e.onPointerDownOutside,i=>{const s=i.detail.originalEvent,l=s.button===0&&s.ctrlKey===!0;(s.button===2||l)&&i.preventDefault()}),onFocusOutside:de(e.onFocusOutside,i=>i.preventDefault())}))}),aW=d.forwardRef((e,t)=>{const n=Eo(uc,e.__scopeDialog),r=d.useRef(!1),o=d.useRef(!1);return d.createElement(mP,Y({},e,{ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var s;if((s=e.onCloseAutoFocus)===null||s===void 0||s.call(e,i),!i.defaultPrevented){var l;r.current||(l=n.triggerRef.current)===null||l===void 0||l.focus(),i.preventDefault()}r.current=!1,o.current=!1},onInteractOutside:i=>{var s,l;(s=e.onInteractOutside)===null||s===void 0||s.call(e,i),i.defaultPrevented||(r.current=!0,i.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const u=i.target;((l=n.triggerRef.current)===null||l===void 0?void 0:l.contains(u))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&o.current&&i.preventDefault()}}))}),mP=d.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:i,...s}=e,l=Eo(uc,n),u=d.useRef(null),f=Be(t,u);return Xm(),d.createElement(d.Fragment,null,d.createElement(Ym,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:i},d.createElement(Ec,Y({role:"dialog",id:l.contentId,"aria-describedby":l.descriptionId,"aria-labelledby":l.titleId,"data-state":Ex(l.open)},s,{ref:f,onDismiss:()=>l.onOpenChange(!1)}))),!1)}),gP="DialogTitle",lW=d.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=Eo(gP,n);return d.createElement(Pe.h2,Y({id:o.titleId},r,{ref:t}))}),cW="DialogDescription",vP=d.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=Eo(cW,n);return d.createElement(Pe.p,Y({id:o.descriptionId},r,{ref:t}))}),uW="DialogClose",dW=d.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=Eo(uW,n);return d.createElement(Pe.button,Y({type:"button"},r,{ref:t,onClick:de(e.onClick,()=>o.onOpenChange(!1))}))});function Ex(e){return e?"open":"closed"}const fW="DialogTitleWarning",[hW,yte]=pB(fW,{contentName:uc,titleName:gP,docsSlug:"dialog"}),Cx=JV,yP=fP,$x=nW,Bd=rW,Ud=iW,Vd=lW,Wd=vP,Rx=dW,Jm=Cx,kx=yP,pW=$x,wP=d.forwardRef(({className:e,...t},n)=>v.jsx(Bd,{ref:n,className:Ce("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t}));wP.displayName=Bd.displayName;const Hd=d.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(pW,{children:[v.jsx(wP,{}),v.jsxs(Ud,{ref:r,className:Ce("fixed left-[50%] top-[50%] z-50 flex flex-col w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",e,"outline-none"),onCloseAutoFocus:o=>o.preventDefault(),...n,children:[t,v.jsxs(Rx,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[v.jsx(wT,{className:"h-4 w-4"}),v.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Hd.displayName=Ud.displayName;const xP=({className:e,...t})=>v.jsx("div",{className:Ce("flex flex-col space-y-1.5 text-center sm:text-left",e),...t});xP.displayName="DialogHeader";const Kd=d.forwardRef(({className:e,...t},n)=>v.jsx(Vd,{ref:n,className:Ce("text-2xl font-semibold leading-none tracking-tight",e),...t}));Kd.displayName=Vd.displayName;const mW=d.forwardRef(({className:e,...t},n)=>v.jsx(Wd,{ref:n,className:Ce("text-sm text-muted-foreground",e),...t}));mW.displayName=Wd.displayName;function m1(){return m1=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 _W=function(t,n,r){r===void 0&&(r=!1);var o=n.alt,i=n.meta,s=n.mod,l=n.shift,u=n.ctrl,f=n.keys,m=t.key,p=t.code,g=t.ctrlKey,y=t.metaKey,b=t.shiftKey,S=t.altKey,E=hs(p),_=m.toLowerCase();if(!r){if(o===!S&&_!=="alt"||l===!b&&_!=="shift")return!1;if(s){if(!y&&!g)return!1}else if(i===!y&&_!=="meta"&&_!=="os"||u===!g&&_!=="ctrl"&&_!=="control")return!1}return f&&f.length===1&&(f.includes(_)||f.includes(E))?!0:f?yW(f):!f},EW=d.createContext(void 0),CW=function(){return d.useContext(EW)};function CP(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&&CP(e[r],t[r])},!0):e===t}var $W=d.createContext({hotkeys:[],enabledScopes:[],toggleScope:function(){},enableScope:function(){},disableScope:function(){}}),RW=function(){return d.useContext($W)};function kW(e){var t=d.useRef(void 0);return CP(t.current,e)||(t.current=e),t.current}var n2=function(t){t.stopPropagation(),t.preventDefault(),t.stopImmediatePropagation()},TW=typeof window<"u"?d.useLayoutEffect:d.useEffect;function PW(e,t,n,r){var o=d.useRef(null),i=d.useRef(!1),s=n instanceof Array?r instanceof Array?void 0:r:n,l=Tx(e)?e.join(s==null?void 0:s.splitKey):e,u=n instanceof Array?n:r instanceof Array?r:void 0,f=d.useCallback(t,u??[]),m=d.useRef(f);u?m.current=f:m.current=t;var p=kW(s),g=RW(),y=g.enabledScopes,b=CW();return TW(function(){if(!((p==null?void 0:p.enabled)===!1||!SW(y,p==null?void 0:p.scopes))){var S=function(R,P){var M;if(P===void 0&&(P=!1),!(bW(R)&&!EP(R,p==null?void 0:p.enableOnFormTags))&&!(p!=null&&p.ignoreEventWhen!=null&&p.ignoreEventWhen(R))){if(o.current!==null&&document.activeElement!==o.current&&!o.current.contains(document.activeElement)){n2(R);return}(M=R.target)!=null&&M.isContentEditable&&!(p!=null&&p.enableOnContentEditable)||T0(l,p==null?void 0:p.splitKey).forEach(function(A){var D,U=P0(A,p==null?void 0:p.combinationKey);if(_W(R,U,p==null?void 0:p.ignoreModifiers)||(D=U.keys)!=null&&D.includes("*")){if(P&&i.current)return;if(wW(R,U,p==null?void 0:p.preventDefault),!xW(R,U,p==null?void 0:p.enabled)){n2(R);return}m.current(R,U),P||(i.current=!0)}})}},E=function(R){R.key!==void 0&&(SP(hs(R.code)),((p==null?void 0:p.keydown)===void 0&&(p==null?void 0:p.keyup)!==!0||p!=null&&p.keydown)&&S(R))},_=function(R){R.key!==void 0&&(_P(hs(R.code)),i.current=!1,p!=null&&p.keyup&&S(R,!0))},x=o.current||(s==null?void 0:s.document)||document;return x.addEventListener("keyup",_),x.addEventListener("keydown",E),b&&T0(l,p==null?void 0:p.splitKey).forEach(function(C){return b.addHotkey(P0(C,p==null?void 0:p.combinationKey,p==null?void 0:p.description))}),function(){x.removeEventListener("keyup",_),x.removeEventListener("keydown",E),b&&T0(l,p==null?void 0:p.splitKey).forEach(function(C){return b.removeHotkey(P0(C,p==null?void 0:p.combinationKey,p==null?void 0:p.description))})}}},[l,p,y]),o}const Zn=(e,t,n)=>{const r=bt(i=>i.disableShortCuts);return PW(e,t,{enabled:!r},n)};function ur(e){const{content:t,keys:n}=e;return v.jsxs("div",{className:"flex justify-between",children:[v.jsx("div",{children:t}),v.jsx("div",{className:"flex gap-[8px]",children:n.map(r=>v.jsx("div",{className:"border px-2 py-1 rounded-lg",children:r},r))})]})}const AW=function(){return/macintosh|mac os x/i.test(navigator.userAgent)},yh=()=>AW()?"Cmd":"Ctrl";function MW(){const[e,t]=QT(!1);return Zn("h",()=>{t()}),v.jsxs(Jm,{open:e,onOpenChange:t,children:[v.jsx(kx,{asChild:!0,children:v.jsx(yn,{tooltip:"Hotkeys",children:v.jsx(nV,{})})}),v.jsx(Hd,{children:v.jsxs(xP,{children:[v.jsx(Kd,{children:"Hotkeys"}),v.jsxs("div",{className:"flex gap-2 flex-col pt-4",children:[v.jsx(ur,{content:"Pan",keys:["Space + Drag"]}),v.jsx(ur,{content:"Reset Zoom/Pan",keys:["Esc"]}),v.jsx(ur,{content:"Decrease Brush Size",keys:["["]}),v.jsx(ur,{content:"Increase Brush Size",keys:["]"]}),v.jsx(ur,{content:"View Original Image",keys:["Hold Tab"]}),v.jsx(ur,{content:"Undo",keys:[yh(),"Z"]}),v.jsx(ur,{content:"Redo",keys:[yh(),"Shift","Z"]}),v.jsx(ur,{content:"Copy Result",keys:[yh(),"C"]}),v.jsx(ur,{content:"Paste Image",keys:[yh(),"V"]}),v.jsx(ur,{content:"Trigger Manually Inpainting",keys:["Shift","R"]}),v.jsx(ur,{content:"Toggle Hotkeys Dialog",keys:["H"]}),v.jsx(ur,{content:"Toggle Settings Dialog",keys:["S"]}),v.jsx(ur,{content:"Toggle File Manager",keys:["F"]})]})]})})]})}function Px(e){const[t]=d.useState(new Image),[n,r]=d.useState(!1);return d.useEffect(()=>{if(e)return t.onload=()=>{r(!0)},r(!1),t.src=URL.createObjectURL(e),()=>{t.onload=null}},[e,t]),[t,n]}const $P="Popover",[RP,wte]=Mn($P,[Fs]),Ax=Fs(),[OW,Rc]=RP($P),NW=e=>{const{__scopePopover:t,children:n,open:r,defaultOpen:o,onOpenChange:i,modal:s=!1}=e,l=Ax(t),u=d.useRef(null),[f,m]=d.useState(!1),[p=!1,g]=Zr({prop:r,defaultProp:o,onChange:i});return d.createElement(jd,l,d.createElement(OW,{scope:t,contentId:nr(),triggerRef:u,open:p,onOpenChange:g,onOpenToggle:d.useCallback(()=>g(y=>!y),[g]),hasCustomAnchor:f,onCustomAnchorAdd:d.useCallback(()=>m(!0),[]),onCustomAnchorRemove:d.useCallback(()=>m(!1),[]),modal:s},n))},DW="PopoverTrigger",IW=d.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,o=Rc(DW,n),i=Ax(n),s=Be(t,o.triggerRef),l=d.createElement(Pe.button,Y({type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":PP(o.open)},r,{ref:s,onClick:de(e.onClick,o.onOpenToggle)}));return o.hasCustomAnchor?l:d.createElement(Vm,Y({asChild:!0},i),l)}),kP="PopoverPortal",[LW,FW]=RP(kP,{forceMount:void 0}),jW=e=>{const{__scopePopover:t,forceMount:n,children:r,container:o}=e,i=Rc(kP,t);return d.createElement(LW,{scope:t,forceMount:n},d.createElement(Sn,{present:n||i.open},d.createElement(zd,{asChild:!0,container:o},r)))},dd="PopoverContent",zW=d.forwardRef((e,t)=>{const n=FW(dd,e.__scopePopover),{forceMount:r=n.forceMount,...o}=e,i=Rc(dd,e.__scopePopover);return d.createElement(Sn,{present:r||i.open},i.modal?d.createElement(BW,Y({},o,{ref:t})):d.createElement(UW,Y({},o,{ref:t})))}),BW=d.forwardRef((e,t)=>{const n=Rc(dd,e.__scopePopover),r=d.useRef(null),o=Be(t,r),i=d.useRef(!1);return d.useEffect(()=>{const s=r.current;if(s)return Qm(s)},[]),d.createElement(qm,{as:Zo,allowPinchZoom:!0},d.createElement(TP,Y({},e,{ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:de(e.onCloseAutoFocus,s=>{var l;s.preventDefault(),i.current||(l=n.triggerRef.current)===null||l===void 0||l.focus()}),onPointerDownOutside:de(e.onPointerDownOutside,s=>{const l=s.detail.originalEvent,u=l.button===0&&l.ctrlKey===!0,f=l.button===2||u;i.current=f},{checkForDefaultPrevented:!1}),onFocusOutside:de(e.onFocusOutside,s=>s.preventDefault(),{checkForDefaultPrevented:!1})})))}),UW=d.forwardRef((e,t)=>{const n=Rc(dd,e.__scopePopover),r=d.useRef(!1),o=d.useRef(!1);return d.createElement(TP,Y({},e,{ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var s;if((s=e.onCloseAutoFocus)===null||s===void 0||s.call(e,i),!i.defaultPrevented){var l;r.current||(l=n.triggerRef.current)===null||l===void 0||l.focus(),i.preventDefault()}r.current=!1,o.current=!1},onInteractOutside:i=>{var s,l;(s=e.onInteractOutside)===null||s===void 0||s.call(e,i),i.defaultPrevented||(r.current=!0,i.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const u=i.target;((l=n.triggerRef.current)===null||l===void 0?void 0:l.contains(u))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&o.current&&i.preventDefault()}}))}),TP=d.forwardRef((e,t)=>{const{__scopePopover:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:i,disableOutsidePointerEvents:s,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:f,onInteractOutside:m,...p}=e,g=Rc(dd,n),y=Ax(n);return Xm(),d.createElement(Ym,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:i},d.createElement(Ec,{asChild:!0,disableOutsidePointerEvents:s,onInteractOutside:m,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:f,onDismiss:()=>g.onOpenChange(!1)},d.createElement(Wm,Y({"data-state":PP(g.open),role:"dialog",id:g.contentId},y,p,{ref:t,style:{...p.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}}))))});function PP(e){return e?"open":"closed"}const VW=NW,WW=IW,HW=jW,AP=zW,KW=VW,GW=WW,MP=d.forwardRef(({className:e,align:t="center",sideOffset:n=4,...r},o)=>v.jsx(HW,{children:v.jsx(AP,{ref:o,align:t,tabIndex:-1,sideOffset:n,className:Ce("z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...r})}));MP.displayName=AP.displayName;function YW(){var e=d.useRef(!0);return e.current?(e.current=!1,!0):e.current}var XW=function(e,t){var n=YW();d.useEffect(function(){if(!n)return e()},t)};const ZW=XW;var qW=function(){};function Mx(e){for(var t=[],n=1;n{const[e,t,n,r,o,i]=bt(g=>[g.getIsProcessing(),g.settings.prompt,g.updateSettings,g.runInpainting,g.showPrevMask,g.hidePrevMask]),s=d.useRef(null);NP(s,()=>{s!=null&&s.current&&s.current.blur()});const l=g=>{g.preventDefault(),g.stopPropagation();const y=g.target;n({prompt:y.value})},u=()=>{e||r()},f=g=>{g.key==="Enter"&&!e&&u()},m=()=>{o()},p=()=>{i()};return v.jsxs("div",{className:"flex gap-4 items-center",children:[v.jsx(Ld,{ref:s,className:"min-w-[500px]",value:t,onInput:l,onKeyUp:f,placeholder:"I want to repaint of..."}),v.jsx(wn,{size:"sm",onClick:u,disabled:e,onMouseEnter:m,onMouseLeave:p,children:"Paint"})]})};var zp={exports:{}};/** + * @license + * Lodash + * Copyright OpenJS Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */zp.exports;(function(e,t){(function(){var n,r="4.17.21",o=200,i="Unsupported core-js use. Try https://npms.io/search?q=ponyfill.",s="Expected a function",l="Invalid `variable` option passed into `_.template`",u="__lodash_hash_undefined__",f=500,m="__lodash_placeholder__",p=1,g=2,y=4,b=1,S=2,E=1,_=2,x=4,C=8,R=16,P=32,M=64,A=128,D=256,U=512,W=30,q="...",X=800,ae=16,V=1,F=2,N=3,ie=1/0,K=9007199254740991,Z=17976931348623157e292,H=NaN,se=4294967295,ce=se-1,Ve=se>>>1,Ue=[["ary",A],["bind",E],["bindKey",_],["curry",C],["curryRight",R],["flip",U],["partial",P],["partialRight",M],["rearg",D]],We="[object Arguments]",Oe="[object Array]",he="[object AsyncFunction]",xe="[object Boolean]",$e="[object Date]",Ae="[object DOMException]",Me="[object Error]",je="[object Function]",Mt="[object GeneratorFunction]",ct="[object Map]",Kt="[object Number]",Er="[object Null]",gt="[object Object]",Vs="[object Promise]",L="[object Proxy]",Q="[object RegExp]",J="[object Set]",we="[object String]",me="[object Symbol]",fe="[object Undefined]",Re="[object WeakMap]",ft="[object WeakSet]",ht="[object ArrayBuffer]",_n="[object DataView]",Cr="[object Float32Array]",Ni="[object Float64Array]",Co="[object Int8Array]",Vn="[object Int16Array]",Ba="[object Int32Array]",Di="[object Uint8Array]",Ws="[object Uint8ClampedArray]",Ii="[object Uint16Array]",Mc="[object Uint32Array]",bg=/\b__p \+= '';/g,Sg=/\b(__p \+=) '' \+/g,Jd=/(__e\(.*?\)|\b__t\)) \+\n'';/g,Oc=/&(?:amp|lt|gt|quot|#39);/g,Nc=/[&<>"']/g,Dc=RegExp(Oc.source),_g=RegExp(Nc.source),Ic=/<%-([\s\S]+?)%>/g,ef=/<%([\s\S]+?)%>/g,Lc=/<%=([\s\S]+?)%>/g,Eg=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Cg=/^\w*$/,$g=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,G=/[\\^$.*+?()[\]{}|]/g,Ye=RegExp(G.source),st=/^\s+/,Qr=/\s/,an=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,tf=/\{\n\/\* \[wrapped with (.+)\] \*/,aM=/,? & /,lM=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,cM=/[()=,{}\[\]\/\s]/,uM=/\\(\\)?/g,dM=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,hb=/\w*$/,fM=/^[-+]0x[0-9a-f]+$/i,hM=/^0b[01]+$/i,pM=/^\[object .+?Constructor\]$/,mM=/^0o[0-7]+$/i,gM=/^(?:0|[1-9]\d*)$/,vM=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,nf=/($^)/,yM=/['\n\r\u2028\u2029\\]/g,rf="\\ud800-\\udfff",wM="\\u0300-\\u036f",xM="\\ufe20-\\ufe2f",bM="\\u20d0-\\u20ff",pb=wM+xM+bM,mb="\\u2700-\\u27bf",gb="a-z\\xdf-\\xf6\\xf8-\\xff",SM="\\xac\\xb1\\xd7\\xf7",_M="\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf",EM="\\u2000-\\u206f",CM=" \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",vb="A-Z\\xc0-\\xd6\\xd8-\\xde",yb="\\ufe0e\\ufe0f",wb=SM+_M+EM+CM,Rg="['’]",$M="["+rf+"]",xb="["+wb+"]",of="["+pb+"]",bb="\\d+",RM="["+mb+"]",Sb="["+gb+"]",_b="[^"+rf+wb+bb+mb+gb+vb+"]",kg="\\ud83c[\\udffb-\\udfff]",kM="(?:"+of+"|"+kg+")",Eb="[^"+rf+"]",Tg="(?:\\ud83c[\\udde6-\\uddff]){2}",Pg="[\\ud800-\\udbff][\\udc00-\\udfff]",Ua="["+vb+"]",Cb="\\u200d",$b="(?:"+Sb+"|"+_b+")",TM="(?:"+Ua+"|"+_b+")",Rb="(?:"+Rg+"(?:d|ll|m|re|s|t|ve))?",kb="(?:"+Rg+"(?:D|LL|M|RE|S|T|VE))?",Tb=kM+"?",Pb="["+yb+"]?",PM="(?:"+Cb+"(?:"+[Eb,Tg,Pg].join("|")+")"+Pb+Tb+")*",AM="\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",MM="\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])",Ab=Pb+Tb+PM,OM="(?:"+[RM,Tg,Pg].join("|")+")"+Ab,NM="(?:"+[Eb+of+"?",of,Tg,Pg,$M].join("|")+")",DM=RegExp(Rg,"g"),IM=RegExp(of,"g"),Ag=RegExp(kg+"(?="+kg+")|"+NM+Ab,"g"),LM=RegExp([Ua+"?"+Sb+"+"+Rb+"(?="+[xb,Ua,"$"].join("|")+")",TM+"+"+kb+"(?="+[xb,Ua+$b,"$"].join("|")+")",Ua+"?"+$b+"+"+Rb,Ua+"+"+kb,MM,AM,bb,OM].join("|"),"g"),FM=RegExp("["+Cb+rf+pb+yb+"]"),jM=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,zM=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],BM=-1,Rt={};Rt[Cr]=Rt[Ni]=Rt[Co]=Rt[Vn]=Rt[Ba]=Rt[Di]=Rt[Ws]=Rt[Ii]=Rt[Mc]=!0,Rt[We]=Rt[Oe]=Rt[ht]=Rt[xe]=Rt[_n]=Rt[$e]=Rt[Me]=Rt[je]=Rt[ct]=Rt[Kt]=Rt[gt]=Rt[Q]=Rt[J]=Rt[we]=Rt[Re]=!1;var Et={};Et[We]=Et[Oe]=Et[ht]=Et[_n]=Et[xe]=Et[$e]=Et[Cr]=Et[Ni]=Et[Co]=Et[Vn]=Et[Ba]=Et[ct]=Et[Kt]=Et[gt]=Et[Q]=Et[J]=Et[we]=Et[me]=Et[Di]=Et[Ws]=Et[Ii]=Et[Mc]=!0,Et[Me]=Et[je]=Et[Re]=!1;var UM={À:"A",Á:"A",Â:"A",Ã:"A",Ä:"A",Å:"A",à:"a",á:"a",â:"a",ã:"a",ä:"a",å:"a",Ç:"C",ç:"c",Ð:"D",ð:"d",È:"E",É:"E",Ê:"E",Ë:"E",è:"e",é:"e",ê:"e",ë:"e",Ì:"I",Í:"I",Î:"I",Ï:"I",ì:"i",í:"i",î:"i",ï:"i",Ñ:"N",ñ:"n",Ò:"O",Ó:"O",Ô:"O",Õ:"O",Ö:"O",Ø:"O",ò:"o",ó:"o",ô:"o",õ:"o",ö:"o",ø:"o",Ù:"U",Ú:"U",Û:"U",Ü:"U",ù:"u",ú:"u",û:"u",ü:"u",Ý:"Y",ý:"y",ÿ:"y",Æ:"Ae",æ:"ae",Þ:"Th",þ:"th",ß:"ss",Ā:"A",Ă:"A",Ą:"A",ā:"a",ă:"a",ą:"a",Ć:"C",Ĉ:"C",Ċ:"C",Č:"C",ć:"c",ĉ:"c",ċ:"c",č:"c",Ď:"D",Đ:"D",ď:"d",đ:"d",Ē:"E",Ĕ:"E",Ė:"E",Ę:"E",Ě:"E",ē:"e",ĕ:"e",ė:"e",ę:"e",ě:"e",Ĝ:"G",Ğ:"G",Ġ:"G",Ģ:"G",ĝ:"g",ğ:"g",ġ:"g",ģ:"g",Ĥ:"H",Ħ:"H",ĥ:"h",ħ:"h",Ĩ:"I",Ī:"I",Ĭ:"I",Į:"I",İ:"I",ĩ:"i",ī:"i",ĭ:"i",į:"i",ı:"i",Ĵ:"J",ĵ:"j",Ķ:"K",ķ:"k",ĸ:"k",Ĺ:"L",Ļ:"L",Ľ:"L",Ŀ:"L",Ł:"L",ĺ:"l",ļ:"l",ľ:"l",ŀ:"l",ł:"l",Ń:"N",Ņ:"N",Ň:"N",Ŋ:"N",ń:"n",ņ:"n",ň:"n",ŋ:"n",Ō:"O",Ŏ:"O",Ő:"O",ō:"o",ŏ:"o",ő:"o",Ŕ:"R",Ŗ:"R",Ř:"R",ŕ:"r",ŗ:"r",ř:"r",Ś:"S",Ŝ:"S",Ş:"S",Š:"S",ś:"s",ŝ:"s",ş:"s",š:"s",Ţ:"T",Ť:"T",Ŧ:"T",ţ:"t",ť:"t",ŧ:"t",Ũ:"U",Ū:"U",Ŭ:"U",Ů:"U",Ű:"U",Ų:"U",ũ:"u",ū:"u",ŭ:"u",ů:"u",ű:"u",ų:"u",Ŵ:"W",ŵ:"w",Ŷ:"Y",ŷ:"y",Ÿ:"Y",Ź:"Z",Ż:"Z",Ž:"Z",ź:"z",ż:"z",ž:"z",IJ:"IJ",ij:"ij",Œ:"Oe",œ:"oe",ʼn:"'n",ſ:"s"},VM={"&":"&","<":"<",">":">",'"':""","'":"'"},WM={"&":"&","<":"<",">":">",""":'"',"'":"'"},HM={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},KM=parseFloat,GM=parseInt,Mb=typeof Jc=="object"&&Jc&&Jc.Object===Object&&Jc,YM=typeof self=="object"&&self&&self.Object===Object&&self,fn=Mb||YM||Function("return this")(),Mg=t&&!t.nodeType&&t,Hs=Mg&&!0&&e&&!e.nodeType&&e,Ob=Hs&&Hs.exports===Mg,Og=Ob&&Mb.process,$r=function(){try{var j=Hs&&Hs.require&&Hs.require("util").types;return j||Og&&Og.binding&&Og.binding("util")}catch{}}(),Nb=$r&&$r.isArrayBuffer,Db=$r&&$r.isDate,Ib=$r&&$r.isMap,Lb=$r&&$r.isRegExp,Fb=$r&&$r.isSet,jb=$r&&$r.isTypedArray;function or(j,te,ee){switch(ee.length){case 0:return j.call(te);case 1:return j.call(te,ee[0]);case 2:return j.call(te,ee[0],ee[1]);case 3:return j.call(te,ee[0],ee[1],ee[2])}return j.apply(te,ee)}function XM(j,te,ee,Se){for(var Ke=-1,pt=j==null?0:j.length;++Ke-1}function Ng(j,te,ee){for(var Se=-1,Ke=j==null?0:j.length;++Se-1;);return ee}function Gb(j,te){for(var ee=j.length;ee--&&Va(te,j[ee],0)>-1;);return ee}function oO(j,te){for(var ee=j.length,Se=0;ee--;)j[ee]===te&&++Se;return Se}var iO=Fg(UM),sO=Fg(VM);function aO(j){return"\\"+HM[j]}function lO(j,te){return j==null?n:j[te]}function Wa(j){return FM.test(j)}function cO(j){return jM.test(j)}function uO(j){for(var te,ee=[];!(te=j.next()).done;)ee.push(te.value);return ee}function Ug(j){var te=-1,ee=Array(j.size);return j.forEach(function(Se,Ke){ee[++te]=[Ke,Se]}),ee}function Yb(j,te){return function(ee){return j(te(ee))}}function ji(j,te){for(var ee=-1,Se=j.length,Ke=0,pt=[];++ee-1}function qO(a,c){var h=this.__data__,w=_f(h,a);return w<0?(++this.size,h.push([a,c])):h[w][1]=c,this}ti.prototype.clear=GO,ti.prototype.delete=YO,ti.prototype.get=XO,ti.prototype.has=ZO,ti.prototype.set=qO;function ni(a){var c=-1,h=a==null?0:a.length;for(this.clear();++c=c?a:c)),a}function Pr(a,c,h,w,$,T){var O,I=c&p,B=c&g,ne=c&y;if(h&&(O=$?h(a,w,$,T):h(a)),O!==n)return O;if(!It(a))return a;var re=Ge(a);if(re){if(O=tN(a),!I)return Wn(a,O)}else{var le=Cn(a),ge=le==je||le==Mt;if(Hi(a))return PS(a,I);if(le==gt||le==We||ge&&!$){if(O=B||ge?{}:XS(a),!I)return B?W6(a,h6(O,a)):V6(a,sS(O,a))}else{if(!Et[le])return $?a:{};O=nN(a,le,I)}}T||(T=new eo);var ke=T.get(a);if(ke)return ke;T.set(a,O),E_(a)?a.forEach(function(Le){O.add(Pr(Le,c,h,Le,a,T))}):S_(a)&&a.forEach(function(Le,nt){O.set(nt,Pr(Le,c,h,nt,a,T))});var Ie=ne?B?pv:hv:B?Kn:ln,Qe=re?n:Ie(a);return Rr(Qe||a,function(Le,nt){Qe&&(nt=Le,Le=a[nt]),Wc(O,nt,Pr(Le,c,h,nt,a,T))}),O}function p6(a){var c=ln(a);return function(h){return aS(h,a,c)}}function aS(a,c,h){var w=h.length;if(a==null)return!w;for(a=St(a);w--;){var $=h[w],T=c[$],O=a[$];if(O===n&&!($ in a)||!T(O))return!1}return!0}function lS(a,c,h){if(typeof a!="function")throw new kr(s);return qc(function(){a.apply(n,h)},c)}function Hc(a,c,h,w){var $=-1,T=sf,O=!0,I=a.length,B=[],ne=c.length;if(!I)return B;h&&(c=Ot(c,ir(h))),w?(T=Ng,O=!1):c.length>=o&&(T=Fc,O=!1,c=new Ys(c));e:for(;++$$?0:$+h),w=w===n||w>$?$:qe(w),w<0&&(w+=$),w=h>w?0:$_(w);h0&&h(I)?c>1?hn(I,c-1,h,w,$):Fi($,I):w||($[$.length]=I)}return $}var Xg=IS(),dS=IS(!0);function $o(a,c){return a&&Xg(a,c,ln)}function Zg(a,c){return a&&dS(a,c,ln)}function Cf(a,c){return Li(c,function(h){return ai(a[h])})}function Zs(a,c){c=Vi(c,a);for(var h=0,w=c.length;a!=null&&hc}function v6(a,c){return a!=null&&yt.call(a,c)}function y6(a,c){return a!=null&&c in St(a)}function w6(a,c,h){return a>=En(c,h)&&a=120&&re.length>=120)?new Ys(O&&re):n}re=a[0];var le=-1,ge=I[0];e:for(;++le<$&&ne.length-1;)I!==a&&gf.call(I,B,1),gf.call(a,B,1);return a}function SS(a,c){for(var h=a?c.length:0,w=h-1;h--;){var $=c[h];if(h==w||$!==T){var T=$;si($)?gf.call(a,$,1):sv(a,$)}}return a}function rv(a,c){return a+wf(nS()*(c-a+1))}function M6(a,c,h,w){for(var $=-1,T=tn(yf((c-a)/(h||1)),0),O=ee(T);T--;)O[w?T:++$]=a,a+=h;return O}function ov(a,c){var h="";if(!a||c<1||c>K)return h;do c%2&&(h+=a),c=wf(c/2),c&&(a+=a);while(c);return h}function et(a,c){return bv(QS(a,c,Gn),a+"")}function O6(a){return iS(tl(a))}function N6(a,c){var h=tl(a);return If(h,Xs(c,0,h.length))}function Yc(a,c,h,w){if(!It(a))return a;c=Vi(c,a);for(var $=-1,T=c.length,O=T-1,I=a;I!=null&&++$$?0:$+c),h=h>$?$:h,h<0&&(h+=$),$=c>h?0:h-c>>>0,c>>>=0;for(var T=ee($);++w<$;)T[w]=a[w+c];return T}function L6(a,c){var h;return Bi(a,function(w,$,T){return h=c(w,$,T),!h}),!!h}function Rf(a,c,h){var w=0,$=a==null?w:a.length;if(typeof c=="number"&&c===c&&$<=Ve){for(;w<$;){var T=w+$>>>1,O=a[T];O!==null&&!ar(O)&&(h?O<=c:O=o){var ne=c?null:Y6(a);if(ne)return lf(ne);O=!1,$=Fc,B=new Ys}else B=c?[]:I;e:for(;++w=w?a:Ar(a,c,h)}var TS=CO||function(a){return fn.clearTimeout(a)};function PS(a,c){if(c)return a.slice();var h=a.length,w=qb?qb(h):new a.constructor(h);return a.copy(w),w}function uv(a){var c=new a.constructor(a.byteLength);return new pf(c).set(new pf(a)),c}function j6(a,c){var h=c?uv(a.buffer):a.buffer;return new a.constructor(h,a.byteOffset,a.byteLength)}function z6(a){var c=new a.constructor(a.source,hb.exec(a));return c.lastIndex=a.lastIndex,c}function B6(a){return Vc?St(Vc.call(a)):{}}function AS(a,c){var h=c?uv(a.buffer):a.buffer;return new a.constructor(h,a.byteOffset,a.length)}function MS(a,c){if(a!==c){var h=a!==n,w=a===null,$=a===a,T=ar(a),O=c!==n,I=c===null,B=c===c,ne=ar(c);if(!I&&!ne&&!T&&a>c||T&&O&&B&&!I&&!ne||w&&O&&B||!h&&B||!$)return 1;if(!w&&!T&&!ne&&a=I)return B;var ne=h[w];return B*(ne=="desc"?-1:1)}}return a.index-c.index}function OS(a,c,h,w){for(var $=-1,T=a.length,O=h.length,I=-1,B=c.length,ne=tn(T-O,0),re=ee(B+ne),le=!w;++I1?h[$-1]:n,O=$>2?h[2]:n;for(T=a.length>3&&typeof T=="function"?($--,T):n,O&&Nn(h[0],h[1],O)&&(T=$<3?n:T,$=1),c=St(c);++w<$;){var I=h[w];I&&a(c,I,w,T)}return c})}function DS(a,c){return function(h,w){if(h==null)return h;if(!Hn(h))return a(h,w);for(var $=h.length,T=c?$:-1,O=St(h);(c?T--:++T<$)&&w(O[T],T,O)!==!1;);return h}}function IS(a){return function(c,h,w){for(var $=-1,T=St(c),O=w(c),I=O.length;I--;){var B=O[a?I:++$];if(h(T[B],B,T)===!1)break}return c}}function H6(a,c,h){var w=c&E,$=Xc(a);function T(){var O=this&&this!==fn&&this instanceof T?$:a;return O.apply(w?h:this,arguments)}return T}function LS(a){return function(c){c=vt(c);var h=Wa(c)?Jr(c):n,w=h?h[0]:c.charAt(0),$=h?Wi(h,1).join(""):c.slice(1);return w[a]()+$}}function Qa(a){return function(c){return Dg(D_(N_(c).replace(DM,"")),a,"")}}function Xc(a){return function(){var c=arguments;switch(c.length){case 0:return new a;case 1:return new a(c[0]);case 2:return new a(c[0],c[1]);case 3:return new a(c[0],c[1],c[2]);case 4:return new a(c[0],c[1],c[2],c[3]);case 5:return new a(c[0],c[1],c[2],c[3],c[4]);case 6:return new a(c[0],c[1],c[2],c[3],c[4],c[5]);case 7:return new a(c[0],c[1],c[2],c[3],c[4],c[5],c[6])}var h=Za(a.prototype),w=a.apply(h,c);return It(w)?w:h}}function K6(a,c,h){var w=Xc(a);function $(){for(var T=arguments.length,O=ee(T),I=T,B=Ja($);I--;)O[I]=arguments[I];var ne=T<3&&O[0]!==B&&O[T-1]!==B?[]:ji(O,B);if(T-=ne.length,T-1?$[T?c[O]:O]:n}}function jS(a){return ii(function(c){var h=c.length,w=h,$=Tr.prototype.thru;for(a&&c.reverse();w--;){var T=c[w];if(typeof T!="function")throw new kr(s);if($&&!O&&Nf(T)=="wrapper")var O=new Tr([],!0)}for(w=O?w:h;++w1&&at.reverse(),re&&BI))return!1;var ne=T.get(a),re=T.get(c);if(ne&&re)return ne==c&&re==a;var le=-1,ge=!0,ke=h&S?new Ys:n;for(T.set(a,c),T.set(c,a);++le1?"& ":"")+c[w],c=c.join(h>2?", ":" "),a.replace(an,`{ +/* [wrapped with `+c+`] */ +`)}function oN(a){return Ge(a)||Js(a)||!!(eS&&a&&a[eS])}function si(a,c){var h=typeof a;return c=c??K,!!c&&(h=="number"||h!="symbol"&&gM.test(a))&&a>-1&&a%1==0&&a0){if(++c>=X)return arguments[0]}else c=0;return a.apply(n,arguments)}}function If(a,c){var h=-1,w=a.length,$=w-1;for(c=c===n?w:c;++h1?a[c-1]:n;return h=typeof h=="function"?(a.pop(),h):n,u_(a,h)});function d_(a){var c=k(a);return c.__chain__=!0,c}function m7(a,c){return c(a),a}function Lf(a,c){return c(a)}var g7=ii(function(a){var c=a.length,h=c?a[0]:0,w=this.__wrapped__,$=function(T){return Yg(T,a)};return c>1||this.__actions__.length||!(w instanceof ot)||!si(h)?this.thru($):(w=w.slice(h,+h+(c?1:0)),w.__actions__.push({func:Lf,args:[$],thisArg:n}),new Tr(w,this.__chain__).thru(function(T){return c&&!T.length&&T.push(n),T}))});function v7(){return d_(this)}function y7(){return new Tr(this.value(),this.__chain__)}function w7(){this.__values__===n&&(this.__values__=C_(this.value()));var a=this.__index__>=this.__values__.length,c=a?n:this.__values__[this.__index__++];return{done:a,value:c}}function x7(){return this}function b7(a){for(var c,h=this;h instanceof Sf;){var w=o_(h);w.__index__=0,w.__values__=n,c?$.__wrapped__=w:c=w;var $=w;h=h.__wrapped__}return $.__wrapped__=a,c}function S7(){var a=this.__wrapped__;if(a instanceof ot){var c=a;return this.__actions__.length&&(c=new ot(this)),c=c.reverse(),c.__actions__.push({func:Lf,args:[Sv],thisArg:n}),new Tr(c,this.__chain__)}return this.thru(Sv)}function _7(){return RS(this.__wrapped__,this.__actions__)}var E7=Tf(function(a,c,h){yt.call(a,h)?++a[h]:ri(a,h,1)});function C7(a,c,h){var w=Ge(a)?zb:m6;return h&&Nn(a,c,h)&&(c=n),w(a,De(c,3))}function $7(a,c){var h=Ge(a)?Li:uS;return h(a,De(c,3))}var R7=FS(i_),k7=FS(s_);function T7(a,c){return hn(Ff(a,c),1)}function P7(a,c){return hn(Ff(a,c),ie)}function A7(a,c,h){return h=h===n?1:qe(h),hn(Ff(a,c),h)}function f_(a,c){var h=Ge(a)?Rr:Bi;return h(a,De(c,3))}function h_(a,c){var h=Ge(a)?ZM:cS;return h(a,De(c,3))}var M7=Tf(function(a,c,h){yt.call(a,h)?a[h].push(c):ri(a,h,[c])});function O7(a,c,h,w){a=Hn(a)?a:tl(a),h=h&&!w?qe(h):0;var $=a.length;return h<0&&(h=tn($+h,0)),Vf(a)?h<=$&&a.indexOf(c,h)>-1:!!$&&Va(a,c,h)>-1}var N7=et(function(a,c,h){var w=-1,$=typeof c=="function",T=Hn(a)?ee(a.length):[];return Bi(a,function(O){T[++w]=$?or(c,O,h):Kc(O,c,h)}),T}),D7=Tf(function(a,c,h){ri(a,h,c)});function Ff(a,c){var h=Ge(a)?Ot:gS;return h(a,De(c,3))}function I7(a,c,h,w){return a==null?[]:(Ge(c)||(c=c==null?[]:[c]),h=w?n:h,Ge(h)||(h=h==null?[]:[h]),xS(a,c,h))}var L7=Tf(function(a,c,h){a[h?0:1].push(c)},function(){return[[],[]]});function F7(a,c,h){var w=Ge(a)?Dg:Wb,$=arguments.length<3;return w(a,De(c,4),h,$,Bi)}function j7(a,c,h){var w=Ge(a)?qM:Wb,$=arguments.length<3;return w(a,De(c,4),h,$,cS)}function z7(a,c){var h=Ge(a)?Li:uS;return h(a,Bf(De(c,3)))}function B7(a){var c=Ge(a)?iS:O6;return c(a)}function U7(a,c,h){(h?Nn(a,c,h):c===n)?c=1:c=qe(c);var w=Ge(a)?u6:N6;return w(a,c)}function V7(a){var c=Ge(a)?d6:I6;return c(a)}function W7(a){if(a==null)return 0;if(Hn(a))return Vf(a)?Ha(a):a.length;var c=Cn(a);return c==ct||c==J?a.size:ev(a).length}function H7(a,c,h){var w=Ge(a)?Ig:L6;return h&&Nn(a,c,h)&&(c=n),w(a,De(c,3))}var K7=et(function(a,c){if(a==null)return[];var h=c.length;return h>1&&Nn(a,c[0],c[1])?c=[]:h>2&&Nn(c[0],c[1],c[2])&&(c=[c[0]]),xS(a,hn(c,1),[])}),jf=$O||function(){return fn.Date.now()};function G7(a,c){if(typeof c!="function")throw new kr(s);return a=qe(a),function(){if(--a<1)return c.apply(this,arguments)}}function p_(a,c,h){return c=h?n:c,c=a&&c==null?a.length:c,oi(a,A,n,n,n,n,c)}function m_(a,c){var h;if(typeof c!="function")throw new kr(s);return a=qe(a),function(){return--a>0&&(h=c.apply(this,arguments)),a<=1&&(c=n),h}}var Ev=et(function(a,c,h){var w=E;if(h.length){var $=ji(h,Ja(Ev));w|=P}return oi(a,w,c,h,$)}),g_=et(function(a,c,h){var w=E|_;if(h.length){var $=ji(h,Ja(g_));w|=P}return oi(c,w,a,h,$)});function v_(a,c,h){c=h?n:c;var w=oi(a,C,n,n,n,n,n,c);return w.placeholder=v_.placeholder,w}function y_(a,c,h){c=h?n:c;var w=oi(a,R,n,n,n,n,n,c);return w.placeholder=y_.placeholder,w}function w_(a,c,h){var w,$,T,O,I,B,ne=0,re=!1,le=!1,ge=!0;if(typeof a!="function")throw new kr(s);c=Or(c)||0,It(h)&&(re=!!h.leading,le="maxWait"in h,T=le?tn(Or(h.maxWait)||0,c):T,ge="trailing"in h?!!h.trailing:ge);function ke(Yt){var no=w,ci=$;return w=$=n,ne=Yt,O=a.apply(ci,no),O}function Ie(Yt){return ne=Yt,I=qc(nt,c),re?ke(Yt):O}function Qe(Yt){var no=Yt-B,ci=Yt-ne,F_=c-no;return le?En(F_,T-ci):F_}function Le(Yt){var no=Yt-B,ci=Yt-ne;return B===n||no>=c||no<0||le&&ci>=T}function nt(){var Yt=jf();if(Le(Yt))return at(Yt);I=qc(nt,Qe(Yt))}function at(Yt){return I=n,ge&&w?ke(Yt):(w=$=n,O)}function lr(){I!==n&&TS(I),ne=0,w=B=$=I=n}function Dn(){return I===n?O:at(jf())}function cr(){var Yt=jf(),no=Le(Yt);if(w=arguments,$=this,B=Yt,no){if(I===n)return Ie(B);if(le)return TS(I),I=qc(nt,c),ke(B)}return I===n&&(I=qc(nt,c)),O}return cr.cancel=lr,cr.flush=Dn,cr}var Y7=et(function(a,c){return lS(a,1,c)}),X7=et(function(a,c,h){return lS(a,Or(c)||0,h)});function Z7(a){return oi(a,U)}function zf(a,c){if(typeof a!="function"||c!=null&&typeof c!="function")throw new kr(s);var h=function(){var w=arguments,$=c?c.apply(this,w):w[0],T=h.cache;if(T.has($))return T.get($);var O=a.apply(this,w);return h.cache=T.set($,O)||T,O};return h.cache=new(zf.Cache||ni),h}zf.Cache=ni;function Bf(a){if(typeof a!="function")throw new kr(s);return function(){var c=arguments;switch(c.length){case 0:return!a.call(this);case 1:return!a.call(this,c[0]);case 2:return!a.call(this,c[0],c[1]);case 3:return!a.call(this,c[0],c[1],c[2])}return!a.apply(this,c)}}function q7(a){return m_(2,a)}var Q7=F6(function(a,c){c=c.length==1&&Ge(c[0])?Ot(c[0],ir(De())):Ot(hn(c,1),ir(De()));var h=c.length;return et(function(w){for(var $=-1,T=En(w.length,h);++$=c}),Js=hS(function(){return arguments}())?hS:function(a){return Bt(a)&&yt.call(a,"callee")&&!Jb.call(a,"callee")},Ge=ee.isArray,h4=Nb?ir(Nb):b6;function Hn(a){return a!=null&&Uf(a.length)&&!ai(a)}function Gt(a){return Bt(a)&&Hn(a)}function p4(a){return a===!0||a===!1||Bt(a)&&On(a)==xe}var Hi=kO||Iv,m4=Db?ir(Db):S6;function g4(a){return Bt(a)&&a.nodeType===1&&!Qc(a)}function v4(a){if(a==null)return!0;if(Hn(a)&&(Ge(a)||typeof a=="string"||typeof a.splice=="function"||Hi(a)||el(a)||Js(a)))return!a.length;var c=Cn(a);if(c==ct||c==J)return!a.size;if(Zc(a))return!ev(a).length;for(var h in a)if(yt.call(a,h))return!1;return!0}function y4(a,c){return Gc(a,c)}function w4(a,c,h){h=typeof h=="function"?h:n;var w=h?h(a,c):n;return w===n?Gc(a,c,n,h):!!w}function $v(a){if(!Bt(a))return!1;var c=On(a);return c==Me||c==Ae||typeof a.message=="string"&&typeof a.name=="string"&&!Qc(a)}function x4(a){return typeof a=="number"&&tS(a)}function ai(a){if(!It(a))return!1;var c=On(a);return c==je||c==Mt||c==he||c==L}function b_(a){return typeof a=="number"&&a==qe(a)}function Uf(a){return typeof a=="number"&&a>-1&&a%1==0&&a<=K}function It(a){var c=typeof a;return a!=null&&(c=="object"||c=="function")}function Bt(a){return a!=null&&typeof a=="object"}var S_=Ib?ir(Ib):E6;function b4(a,c){return a===c||Jg(a,c,gv(c))}function S4(a,c,h){return h=typeof h=="function"?h:n,Jg(a,c,gv(c),h)}function _4(a){return __(a)&&a!=+a}function E4(a){if(aN(a))throw new Ke(i);return pS(a)}function C4(a){return a===null}function $4(a){return a==null}function __(a){return typeof a=="number"||Bt(a)&&On(a)==Kt}function Qc(a){if(!Bt(a)||On(a)!=gt)return!1;var c=mf(a);if(c===null)return!0;var h=yt.call(c,"constructor")&&c.constructor;return typeof h=="function"&&h instanceof h&&df.call(h)==SO}var Rv=Lb?ir(Lb):C6;function R4(a){return b_(a)&&a>=-K&&a<=K}var E_=Fb?ir(Fb):$6;function Vf(a){return typeof a=="string"||!Ge(a)&&Bt(a)&&On(a)==we}function ar(a){return typeof a=="symbol"||Bt(a)&&On(a)==me}var el=jb?ir(jb):R6;function k4(a){return a===n}function T4(a){return Bt(a)&&Cn(a)==Re}function P4(a){return Bt(a)&&On(a)==ft}var A4=Of(tv),M4=Of(function(a,c){return a<=c});function C_(a){if(!a)return[];if(Hn(a))return Vf(a)?Jr(a):Wn(a);if(jc&&a[jc])return uO(a[jc]());var c=Cn(a),h=c==ct?Ug:c==J?lf:tl;return h(a)}function li(a){if(!a)return a===0?a:0;if(a=Or(a),a===ie||a===-ie){var c=a<0?-1:1;return c*Z}return a===a?a:0}function qe(a){var c=li(a),h=c%1;return c===c?h?c-h:c:0}function $_(a){return a?Xs(qe(a),0,se):0}function Or(a){if(typeof a=="number")return a;if(ar(a))return H;if(It(a)){var c=typeof a.valueOf=="function"?a.valueOf():a;a=It(c)?c+"":c}if(typeof a!="string")return a===0?a:+a;a=Hb(a);var h=hM.test(a);return h||mM.test(a)?GM(a.slice(2),h?2:8):fM.test(a)?H:+a}function R_(a){return Ro(a,Kn(a))}function O4(a){return a?Xs(qe(a),-K,K):a===0?a:0}function vt(a){return a==null?"":sr(a)}var N4=qa(function(a,c){if(Zc(c)||Hn(c)){Ro(c,ln(c),a);return}for(var h in c)yt.call(c,h)&&Wc(a,h,c[h])}),k_=qa(function(a,c){Ro(c,Kn(c),a)}),Wf=qa(function(a,c,h,w){Ro(c,Kn(c),a,w)}),D4=qa(function(a,c,h,w){Ro(c,ln(c),a,w)}),I4=ii(Yg);function L4(a,c){var h=Za(a);return c==null?h:sS(h,c)}var F4=et(function(a,c){a=St(a);var h=-1,w=c.length,$=w>2?c[2]:n;for($&&Nn(c[0],c[1],$)&&(w=1);++h1),T}),Ro(a,pv(a),h),w&&(h=Pr(h,p|g|y,X6));for(var $=c.length;$--;)sv(h,c[$]);return h});function n8(a,c){return P_(a,Bf(De(c)))}var r8=ii(function(a,c){return a==null?{}:P6(a,c)});function P_(a,c){if(a==null)return{};var h=Ot(pv(a),function(w){return[w]});return c=De(c),bS(a,h,function(w,$){return c(w,$[0])})}function o8(a,c,h){c=Vi(c,a);var w=-1,$=c.length;for($||($=1,a=n);++w<$;){var T=a==null?n:a[ko(c[w])];T===n&&(w=$,T=h),a=ai(T)?T.call(a):T}return a}function i8(a,c,h){return a==null?a:Yc(a,c,h)}function s8(a,c,h,w){return w=typeof w=="function"?w:n,a==null?a:Yc(a,c,h,w)}var A_=VS(ln),M_=VS(Kn);function a8(a,c,h){var w=Ge(a),$=w||Hi(a)||el(a);if(c=De(c,4),h==null){var T=a&&a.constructor;$?h=w?new T:[]:It(a)?h=ai(T)?Za(mf(a)):{}:h={}}return($?Rr:$o)(a,function(O,I,B){return c(h,O,I,B)}),h}function l8(a,c){return a==null?!0:sv(a,c)}function c8(a,c,h){return a==null?a:$S(a,c,cv(h))}function u8(a,c,h,w){return w=typeof w=="function"?w:n,a==null?a:$S(a,c,cv(h),w)}function tl(a){return a==null?[]:Bg(a,ln(a))}function d8(a){return a==null?[]:Bg(a,Kn(a))}function f8(a,c,h){return h===n&&(h=c,c=n),h!==n&&(h=Or(h),h=h===h?h:0),c!==n&&(c=Or(c),c=c===c?c:0),Xs(Or(a),c,h)}function h8(a,c,h){return c=li(c),h===n?(h=c,c=0):h=li(h),a=Or(a),w6(a,c,h)}function p8(a,c,h){if(h&&typeof h!="boolean"&&Nn(a,c,h)&&(c=h=n),h===n&&(typeof c=="boolean"?(h=c,c=n):typeof a=="boolean"&&(h=a,a=n)),a===n&&c===n?(a=0,c=1):(a=li(a),c===n?(c=a,a=0):c=li(c)),a>c){var w=a;a=c,c=w}if(h||a%1||c%1){var $=nS();return En(a+$*(c-a+KM("1e-"+(($+"").length-1))),c)}return rv(a,c)}var m8=Qa(function(a,c,h){return c=c.toLowerCase(),a+(h?O_(c):c)});function O_(a){return Pv(vt(a).toLowerCase())}function N_(a){return a=vt(a),a&&a.replace(vM,iO).replace(IM,"")}function g8(a,c,h){a=vt(a),c=sr(c);var w=a.length;h=h===n?w:Xs(qe(h),0,w);var $=h;return h-=c.length,h>=0&&a.slice(h,$)==c}function v8(a){return a=vt(a),a&&_g.test(a)?a.replace(Nc,sO):a}function y8(a){return a=vt(a),a&&Ye.test(a)?a.replace(G,"\\$&"):a}var w8=Qa(function(a,c,h){return a+(h?"-":"")+c.toLowerCase()}),x8=Qa(function(a,c,h){return a+(h?" ":"")+c.toLowerCase()}),b8=LS("toLowerCase");function S8(a,c,h){a=vt(a),c=qe(c);var w=c?Ha(a):0;if(!c||w>=c)return a;var $=(c-w)/2;return Mf(wf($),h)+a+Mf(yf($),h)}function _8(a,c,h){a=vt(a),c=qe(c);var w=c?Ha(a):0;return c&&w>>0,h?(a=vt(a),a&&(typeof c=="string"||c!=null&&!Rv(c))&&(c=sr(c),!c&&Wa(a))?Wi(Jr(a),0,h):a.split(c,h)):[]}var P8=Qa(function(a,c,h){return a+(h?" ":"")+Pv(c)});function A8(a,c,h){return a=vt(a),h=h==null?0:Xs(qe(h),0,a.length),c=sr(c),a.slice(h,h+c.length)==c}function M8(a,c,h){var w=k.templateSettings;h&&Nn(a,c,h)&&(c=n),a=vt(a),c=Wf({},c,w,WS);var $=Wf({},c.imports,w.imports,WS),T=ln($),O=Bg($,T),I,B,ne=0,re=c.interpolate||nf,le="__p += '",ge=Vg((c.escape||nf).source+"|"+re.source+"|"+(re===Lc?dM:nf).source+"|"+(c.evaluate||nf).source+"|$","g"),ke="//# sourceURL="+(yt.call(c,"sourceURL")?(c.sourceURL+"").replace(/\s/g," "):"lodash.templateSources["+ ++BM+"]")+` +`;a.replace(ge,function(Le,nt,at,lr,Dn,cr){return at||(at=lr),le+=a.slice(ne,cr).replace(yM,aO),nt&&(I=!0,le+=`' + +__e(`+nt+`) + +'`),Dn&&(B=!0,le+=`'; +`+Dn+`; +__p += '`),at&&(le+=`' + +((__t = (`+at+`)) == null ? '' : __t) + +'`),ne=cr+Le.length,Le}),le+=`'; +`;var Ie=yt.call(c,"variable")&&c.variable;if(!Ie)le=`with (obj) { +`+le+` +} +`;else if(cM.test(Ie))throw new Ke(l);le=(B?le.replace(bg,""):le).replace(Sg,"$1").replace(Jd,"$1;"),le="function("+(Ie||"obj")+`) { +`+(Ie?"":`obj || (obj = {}); +`)+"var __t, __p = ''"+(I?", __e = _.escape":"")+(B?`, __j = Array.prototype.join; +function print() { __p += __j.call(arguments, '') } +`:`; +`)+le+`return __p +}`;var Qe=I_(function(){return pt(T,ke+"return "+le).apply(n,O)});if(Qe.source=le,$v(Qe))throw Qe;return Qe}function O8(a){return vt(a).toLowerCase()}function N8(a){return vt(a).toUpperCase()}function D8(a,c,h){if(a=vt(a),a&&(h||c===n))return Hb(a);if(!a||!(c=sr(c)))return a;var w=Jr(a),$=Jr(c),T=Kb(w,$),O=Gb(w,$)+1;return Wi(w,T,O).join("")}function I8(a,c,h){if(a=vt(a),a&&(h||c===n))return a.slice(0,Xb(a)+1);if(!a||!(c=sr(c)))return a;var w=Jr(a),$=Gb(w,Jr(c))+1;return Wi(w,0,$).join("")}function L8(a,c,h){if(a=vt(a),a&&(h||c===n))return a.replace(st,"");if(!a||!(c=sr(c)))return a;var w=Jr(a),$=Kb(w,Jr(c));return Wi(w,$).join("")}function F8(a,c){var h=W,w=q;if(It(c)){var $="separator"in c?c.separator:$;h="length"in c?qe(c.length):h,w="omission"in c?sr(c.omission):w}a=vt(a);var T=a.length;if(Wa(a)){var O=Jr(a);T=O.length}if(h>=T)return a;var I=h-Ha(w);if(I<1)return w;var B=O?Wi(O,0,I).join(""):a.slice(0,I);if($===n)return B+w;if(O&&(I+=B.length-I),Rv($)){if(a.slice(I).search($)){var ne,re=B;for($.global||($=Vg($.source,vt(hb.exec($))+"g")),$.lastIndex=0;ne=$.exec(re);)var le=ne.index;B=B.slice(0,le===n?I:le)}}else if(a.indexOf(sr($),I)!=I){var ge=B.lastIndexOf($);ge>-1&&(B=B.slice(0,ge))}return B+w}function j8(a){return a=vt(a),a&&Dc.test(a)?a.replace(Oc,pO):a}var z8=Qa(function(a,c,h){return a+(h?" ":"")+c.toUpperCase()}),Pv=LS("toUpperCase");function D_(a,c,h){return a=vt(a),c=h?n:c,c===n?cO(a)?vO(a):eO(a):a.match(c)||[]}var I_=et(function(a,c){try{return or(a,n,c)}catch(h){return $v(h)?h:new Ke(h)}}),B8=ii(function(a,c){return Rr(c,function(h){h=ko(h),ri(a,h,Ev(a[h],a))}),a});function U8(a){var c=a==null?0:a.length,h=De();return a=c?Ot(a,function(w){if(typeof w[1]!="function")throw new kr(s);return[h(w[0]),w[1]]}):[],et(function(w){for(var $=-1;++$K)return[];var h=se,w=En(a,se);c=De(c),a-=se;for(var $=zg(w,c);++h0||c<0)?new ot(h):(a<0?h=h.takeRight(-a):a&&(h=h.drop(a)),c!==n&&(c=qe(c),h=c<0?h.dropRight(-c):h.take(c-a)),h)},ot.prototype.takeRightWhile=function(a){return this.reverse().takeWhile(a).reverse()},ot.prototype.toArray=function(){return this.take(se)},$o(ot.prototype,function(a,c){var h=/^(?:filter|find|map|reject)|While$/.test(c),w=/^(?:head|last)$/.test(c),$=k[w?"take"+(c=="last"?"Right":""):c],T=w||/^find/.test(c);$&&(k.prototype[c]=function(){var O=this.__wrapped__,I=w?[1]:arguments,B=O instanceof ot,ne=I[0],re=B||Ge(O),le=function(nt){var at=$.apply(k,Fi([nt],I));return w&&ge?at[0]:at};re&&h&&typeof ne=="function"&&ne.length!=1&&(B=re=!1);var ge=this.__chain__,ke=!!this.__actions__.length,Ie=T&&!ge,Qe=B&&!ke;if(!T&&re){O=Qe?O:new ot(this);var Le=a.apply(O,I);return Le.__actions__.push({func:Lf,args:[le],thisArg:n}),new Tr(Le,ge)}return Ie&&Qe?a.apply(this,I):(Le=this.thru(le),Ie?w?Le.value()[0]:Le.value():Le)})}),Rr(["pop","push","shift","sort","splice","unshift"],function(a){var c=cf[a],h=/^(?:push|sort|unshift)$/.test(a)?"tap":"thru",w=/^(?:pop|shift)$/.test(a);k.prototype[a]=function(){var $=arguments;if(w&&!this.__chain__){var T=this.value();return c.apply(Ge(T)?T:[],$)}return this[h](function(O){return c.apply(Ge(O)?O:[],$)})}}),$o(ot.prototype,function(a,c){var h=k[c];if(h){var w=h.name+"";yt.call(Xa,w)||(Xa[w]=[]),Xa[w].push({name:c,func:h})}}),Xa[Pf(n,_).name]=[{name:"wrapper",func:n}],ot.prototype.clone=jO,ot.prototype.reverse=zO,ot.prototype.value=BO,k.prototype.at=g7,k.prototype.chain=v7,k.prototype.commit=y7,k.prototype.next=w7,k.prototype.plant=b7,k.prototype.reverse=S7,k.prototype.toJSON=k.prototype.valueOf=k.prototype.value=_7,k.prototype.first=k.prototype.head,jc&&(k.prototype[jc]=x7),k},Ka=yO();Hs?((Hs.exports=Ka)._=Ka,Mg._=Ka):fn._=Ka}).call(Jc)})(zp,zp.exports);var wH=zp.exports;const xH=dm(wH);function Vr({width:e,height:t}){return e/t}function Bp(e,t=0){const n=10**t;return Math.round((e+Number.EPSILON)*n)/n}function bH(e){return(t,n)=>e(n)-e(t)}class SH{constructor(t){this.comparator=t,this.heap=[],this.n=0}greater(t,n){return this.comparator(this.heap[t],this.heap[n])<0}swap(t,n){const r=this.heap[t];this.heap[t]=this.heap[n],this.heap[n]=r}swim(t){let n=t,r=Math.floor(n/2);for(;n>1&&this.greater(r,n);)this.swap(r,n),n=r,r=Math.floor(n/2)}sink(t){let n=t,r=n*2;for(;r<=this.n&&(rl.weight));for(s.push({id:t,weight:0});s.size()>0;){const{id:l,weight:u}=s.pop();if(!o.has(l)){const f=e(l);o.add(l),f.forEach((m,p)=>{const g=u+m,y=r.get(p),b=i.get(p);(b===void 0||b>g&&(b/g>1.005||y!==void 0&&yMath.min(Vr(i),o),Number.MAX_VALUE);return Bp(n/t/r)+2}function DP(e,t,n,r){const o=t-(e.length-1)*n-2*r*e.length,i=e.reduce((s,l)=>s+Vr(l),0);return o/i}function RH(e,t,n,r,o,i,s){const l=e.slice(t,n),u=DP(l,r,i,s);return u>0?(u-o)**2*l.length:void 0}function kH({photos:e,layoutOptions:t,targetRowHeight:n,limitNodeSearch:r,rowConstraints:o}){return i=>{var s,l;const{containerWidth:u,spacing:f,padding:m}=t,p=new Map;p.set(i,0);const g=(s=o==null?void 0:o.minPhotos)!=null?s:1,y=Math.min(r,(l=o==null?void 0:o.maxPhotos)!=null?l:1/0);for(let b=i+g;by);b+=1){const S=RH(e,i,b,u,n,f,m);if(S===void 0)break;p.set(b,S)}return p}}function TH({photos:e,layoutOptions:t}){const{spacing:n,padding:r,containerWidth:o,targetRowHeight:i,rowConstraints:s}=t,l=$H({photos:e,containerWidth:o,targetRowHeight:i}),u=kH({photos:e,layoutOptions:t,targetRowHeight:i,limitNodeSearch:l,rowConstraints:s}),f=CH(u,0,e.length);if(f===void 0)return;const m=[];for(let p=1;p({photo:b,index:S})).slice(f[p-1],f[p]),y=DP(g.map(({photo:b})=>b),o,n,r);m.push(g.map(({photo:b,index:S},E)=>({photo:b,layout:{height:y,width:y*Vr(b),index:S,photoIndex:E,photosCount:g.length}})))}return m}function eg(...e){return[...e].filter(t=>!!t).join(" ")}function IP(e,{width:t,photosCount:n},{spacing:r,padding:o,containerWidth:i}){const s=r*(n-1)+2*o*n;return`calc((${e} - ${s}px) / ${Bp((i-s)/t,5)})`}function PH(e,t){return t.layout!=="rows"?`calc(100% - ${2*t.padding}px)`:IP("100%",e,t)}function a2(e,t,n){var r,o;return IP((o=(r=e.match(/calc\((.*)\)/))==null?void 0:r[1])!=null?o:e,t,n)}function AH(e,t,n){let r,o;const i=e.srcSet||e.images;return i&&i.length>0&&(r=i.concat(i.find(({width:s})=>s===e.width)?[]:[{src:e.src,width:e.width,height:e.height}]).sort((s,l)=>s.width-l.width).map(s=>`${s.src} ${s.width}w`).join(", ")),n.sizes?o=(n.sizes.sizes||[]).map(({viewport:s,size:l})=>`${s} ${a2(l,t,n)}`).concat(a2(n.sizes.size,t,n)).join(", "):r&&(o=`${Math.ceil(t.width/n.containerWidth*100)}vw`),{srcSet:r,sizes:o}}function Nx(e){var t,n;const{photo:r,layout:o,layoutOptions:i,imageProps:{style:s,className:l,...u}={},renderPhoto:f}=e,{onClick:m}=i,p={display:"block",boxSizing:"content-box",width:PH(o,i),height:"auto",aspectRatio:`${r.width} / ${r.height}`,...i.padding?{padding:`${i.padding}px`}:null,...(i.layout==="columns"||i.layout==="masonry")&&o.photoIndex{m({event:E,photo:r,index:o.index})}:void 0,y={src:r.src,alt:(t=r.alt)!=null?t:"",title:r.title,onClick:g,style:p,className:eg("react-photo-album--photo",l),loading:"lazy",decoding:"async",...AH(r,o,i),...u},b=E=>{const{src:_,alt:x,srcSet:C,sizes:R,style:P,...M}=y;return d.createElement("img",{alt:x,...C?{srcSet:C,sizes:R}:null,src:_,style:E!=null&&E.wrapped?{display:"block",width:"100%",height:"100%"}:P,...M})},S=(({display:E,boxSizing:_,width:x,aspectRatio:C,padding:R,marginBottom:P,cursor:M})=>({display:E,boxSizing:_,width:x,aspectRatio:C,padding:R,marginBottom:P,cursor:M}))(p);return d.createElement(d.Fragment,null,(n=f==null?void 0:f({photo:r,layout:o,layoutOptions:i,imageProps:y,renderDefaultPhoto:b,wrapperStyle:S}))!=null?n:b())}function MH({rowContainerProps:e,children:t}){return d.createElement("div",{...e},t)}function OH(e){const{layoutOptions:t,rowIndex:n,rowsCount:r,renderRowContainer:o,rowContainerProps:{style:i,className:s,...l}={},children:u}=e,f={className:eg("react-photo-album--row",s),style:{display:"flex",flexDirection:"row",flexWrap:"nowrap",alignItems:"flex-start",justifyContent:"space-between",...nd.createElement(OH,{key:`row-${f}`,layoutOptions:n,rowIndex:f,rowsCount:l.length,renderRowContainer:o,rowContainerProps:s},u.map(({photo:m,layout:p})=>d.createElement(Nx,{key:m.key||m.src,photo:m,layout:p,layoutOptions:n,renderPhoto:r,imageProps:i}))))):null}function DH(e,t,n,r){const o=new Map,i=new Set;i.add(n);for(let s=0;s{const f=s>0?o.get(u)[s].weight:0;e(u).forEach(({neighbor:m,weight:p})=>{let g=o.get(m);g||(g=[],o.set(m,g));const y=f+p,b=g[s+1];(!b||b.weight>y&&(b.weight/y>1.0001||u0;i-=1)o=e.get(o)[i].node,r.push(o);return r.reverse()}function LH(e,t,n,r){return IH(DH(e,t,n,r),t,r)}function FH({photos:e,spacing:t,padding:n,targetColumnWidth:r,targetColumnHeight:o}){return i=>{const s=[],l=o*1.5;let u=r/Vr(e[i])+2*n;for(let f=i+1;fl||f===e.length));f+=1)u+=r/Vr(e[f])+t+2*n;return s}}function l2({path:e,photos:t,containerWidth:n,columnsGaps:r,columnsRatios:o,spacing:i,padding:s}){const l=[],u=o.reduce((f,m)=>f+m,0);for(let f=0;f({photo:y,index:b})).slice(e[f],e[f+1]),p=o.reduce((y,b,S)=>y+(r[f]-r[S])*b,0),g=(n-(e.length-2)*i-2*(e.length-1)*s-p)*o[f]/u;l.push(m.map(({photo:y,index:b},S)=>({photo:y,layout:{width:g,height:g/Vr(y),index:b,photoIndex:S,photosCount:m.length}})))}return l}function jH({photos:e,layoutOptions:t,targetColumnWidth:n}){const{columns:r,spacing:o,padding:i,containerWidth:s}=t,l=[],u=[];if(e.length<=r){const y=e.length>0?e.reduce((S,E)=>S+Vr(E),0)/e.length:1;for(let S=0;SMath.min(E,e.length)),photos:e,columnsRatios:u,columnsGaps:l,containerWidth:s,spacing:o,padding:i});return{columnsGaps:l,columnsRatios:u,columnsModel:b}}const f=(e.reduce((y,b)=>y+n/Vr(b),0)+o*(e.length-r)+2*i*e.length)/r,m=FH({photos:e,targetColumnWidth:n,targetColumnHeight:f,spacing:o,padding:i}),p=LH(m,r,0,e.length);for(let y=0;yS+1/Vr(E),0)}const g=l2({path:p,photos:e,columnsRatios:u,columnsGaps:l,containerWidth:s,spacing:o,padding:i});return{columnsGaps:l,columnsRatios:u,columnsModel:g}}function LP(e){const{photos:t,layoutOptions:n}=e,{columns:r,spacing:o,padding:i,containerWidth:s}=n,l=(s-o*(r-1)-2*i*r)/r,{columnsGaps:u,columnsRatios:f,columnsModel:m}=jH({photos:t,layoutOptions:n,targetColumnWidth:l});return m.findIndex(p=>p.findIndex(({layout:{width:g,height:y}})=>g<0||y<0)>=0)>=0?r>1?LP({photos:t,layoutOptions:{...n,columns:r-1}}):void 0:{columnsModel:m,columnsGaps:u,columnsRatios:f}}function zH({photos:e,layoutOptions:t}){return LP({photos:e,layoutOptions:t})}function BH({columnContainerProps:e,children:t}){return d.createElement("div",{...e},t)}function UH(e){const{layoutOptions:t,columnIndex:n,columnsCount:r,columnsGaps:o,columnsRatios:i}=e,{layout:s,spacing:l,padding:u}=t;if(s==="masonry"||!o||!i)return`calc((100% - ${l*(r-1)}px) / ${r})`;const f=i.reduce((p,g)=>p+g,0),m=i.reduce((p,g,y)=>p+(o[n]-o[y])*g,0);return`calc((100% - ${Bp((r-1)*l+2*r*u+m,3)}px) * ${Bp(i[n]/f,5)} + ${2*u}px)`}function FP(e){const{layoutOptions:t,renderColumnContainer:n,children:r,columnContainerProps:{style:o,className:i,...s}={},...l}=e,u={className:eg("react-photo-album--column",i),style:{display:"flex",flexDirection:"column",flexWrap:"nowrap",alignItems:"flex-start",width:UH(e),justifyContent:t.layout==="columns"?"space-between":"flex-start",...o},...s};return d.createElement(d.Fragment,null,(n??BH)({layoutOptions:t,columnContainerProps:u,children:r,...l}))}function VH(e){const{photos:t,layoutOptions:n,renderPhoto:r,renderColumnContainer:o,componentsProps:{imageProps:i,columnContainerProps:s}}=e,l=zH({photos:t,layoutOptions:n});if(!l)return null;const{columnsModel:u,columnsRatios:f,columnsGaps:m}=l;return d.createElement(d.Fragment,null,u.map((p,g)=>d.createElement(FP,{key:`column-${g}`,layoutOptions:n,columnIndex:g,columnsCount:u.length,columnsGaps:m,columnsRatios:f,renderColumnContainer:o,columnContainerProps:s},p.map(({photo:y,layout:b})=>d.createElement(Nx,{key:y.key||y.src,photo:y,layout:b,layoutOptions:n,renderPhoto:r,imageProps:i})))))}function jP(e){const{photos:t,layoutOptions:n}=e,{columns:r,spacing:o,padding:i,containerWidth:s}=n,l=(s-o*(r-1)-2*i*r)/r;if(l<=0)return r>1?jP({...e,layoutOptions:{...n,columns:r-1}}):void 0;const u=[];for(let m=0;m{const y=u.reduce((b,S,E)=>S[])).map(m=>m.map(({photo:p,index:g},y)=>({photo:p,layout:{width:l,height:l/Vr(p),index:g,photoIndex:y,photosCount:m.length}})))}function WH(e){const{photos:t,layoutOptions:n,renderPhoto:r,renderColumnContainer:o,componentsProps:{imageProps:i,columnContainerProps:s}}=e,l=jP({photos:t,layoutOptions:n});return l?d.createElement(d.Fragment,null,l.map((u,f)=>d.createElement(FP,{key:`masonry-column-${f}`,layoutOptions:n,columnsCount:l.length,columnIndex:f,renderColumnContainer:o,columnContainerProps:s},u.map(({photo:m,layout:p})=>d.createElement(Nx,{key:m.key||m.src,photo:m,layout:p,layoutOptions:n,renderPhoto:r,imageProps:i}))))):null}function HH({containerProps:e,children:t,containerRef:n}){return d.createElement("div",{ref:n,...e},t)}function KH(e){const{layout:t,renderContainer:n,children:r,containerRef:o,containerProps:{style:i,className:s,...l}={}}=e,u={className:eg("react-photo-album",`react-photo-album--${t}`,s),style:{display:"flex",flexWrap:"nowrap",justifyContent:"space-between",flexDirection:t==="rows"?"column":"row",...i},...l};return d.createElement(d.Fragment,null,(n??HH)({containerProps:u,containerRef:o,layout:t,children:r}))}function GH(e){const t=d.useRef(e);return(!e||!t.current||e.join()!==t.current.join())&&(t.current=e),t.current}function YH(e,{newContainerWidth:t,newScrollbarWidth:n}){const{containerWidth:r,scrollbarWidth:o}=e;return r!==void 0&&o!==void 0&&t!==void 0&&n!==void 0&&t>r&&t-r<=20&&n0){const r=[...t.filter(i=>i>0)].sort((i,s)=>s-i);r.push(Math.floor(r[r.length-1]/2));const o=n;n=r.find((i,s)=>i<=o||s===r.length-1)}return n}function ZH(e,t){const[{containerWidth:n},r]=d.useReducer(YH,{containerWidth:t}),o=d.useRef(null),i=d.useRef();return{containerRef:d.useCallback(l=>{var u;(u=i.current)==null||u.disconnect(),i.current=void 0,o.current=l;const f=()=>r({newContainerWidth:XH(o.current,e),newScrollbarWidth:window.innerWidth-document.documentElement.clientWidth});f(),l&&typeof ResizeObserver<"u"&&(i.current=new ResizeObserver(f),i.current.observe(l))},[e]),containerWidth:n}}const qH=Object.freeze([1200,600,300,0]);function Dx(e,t){return typeof e=="function"?e(t):e}function zP(e,t){return typeof e<"u"?Dx(e,t):void 0}function QH(e,t){const n=qH.findIndex(r=>r<=t);return Dx(e[n>=0?n:0],t)}function wh(e,t,n,r=0){const o=zP(e,t);return Math.round(Math.max(o===void 0?QH(n,t):o,r))}function JH({layout:e,onClick:t,containerWidth:n,targetRowHeight:r,rowConstraints:o,columns:i,spacing:s,padding:l,sizes:u}){return{layout:e,onClick:t,containerWidth:n,columns:wh(i,n,[5,4,3,2],1),spacing:wh(s,n,[20,15,10,5]),padding:wh(l,n,[0,0,0,0,0]),targetRowHeight:wh(r,n,[f=>f/5,f=>f/4,f=>f/3,f=>f/2]),rowConstraints:zP(o,n),sizes:u}}function eK(e,t,n){const{photos:r,componentsProps:o}=e,i=Dx(o,t)||{};if(n){const{layout:s,spacing:l,padding:u,rowConstraints:f}=n;if(s==="rows"){const{singleRowMaxHeight:m}=f||{};if(m){const p=Math.floor(r.reduce((g,{width:y,height:b})=>g+y/b*m-2*u,u*r.length*2+l*(r.length-1)));p>0&&(i.containerProps=i.containerProps||{},i.containerProps.style={maxWidth:p,...i.containerProps.style})}}}return i}function tK(e,t,n){const{photos:r,layout:o,renderPhoto:i,renderRowContainer:s,renderColumnContainer:l}=e,u={photos:r,renderPhoto:i,componentsProps:t};return o==="rows"?d.createElement(NH,{layoutOptions:n,renderRowContainer:s,...u}):o==="columns"?d.createElement(VH,{layoutOptions:n,renderColumnContainer:l,...u}):d.createElement(WH,{layoutOptions:n,renderColumnContainer:l,...u})}function nK(e){const{photos:t,layout:n,renderContainer:r,defaultContainerWidth:o,breakpoints:i}=e,{containerRef:s,containerWidth:l}=ZH(GH(i),o);if(!n||!["rows","columns","masonry"].includes(n)||!Array.isArray(t))return null;const u=l?JH({containerWidth:l,...e}):void 0,f=eK(e,l,u);return d.createElement(KH,{layout:n,containerRef:s,renderContainer:r,containerProps:f.containerProps},u&&tK(e,f,u))}function rK({title:e,titleId:t,...n},r){return d.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true",ref:r,"aria-labelledby":t},n),e?d.createElement("title",{id:t},e):null,d.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3 4.5h14.25M3 9h9.75M3 13.5h9.75m4.5-4.5v12m0 0l-3.75-3.75M17.25 21L21 17.25"}))}const oK=d.forwardRef(rK),iK=oK;function sK({title:e,titleId:t,...n},r){return d.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true",ref:r,"aria-labelledby":t},n),e?d.createElement("title",{id:t},e):null,d.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3 4.5h14.25M3 9h9.75M3 13.5h5.25m5.25-.75L17.25 9m0 0L21 12.75M17.25 9v12"}))}const aK=d.forwardRef(sK),lK=aK;function cK({title:e,titleId:t,...n},r){return d.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true",ref:r,"aria-labelledby":t},n),e?d.createElement("title",{id:t},e):null,d.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15.042 21.672L13.684 16.6m0 0l-2.51 2.225.569-9.47 5.227 7.917-3.286-.672zM12 2.25V4.5m5.834.166l-1.591 1.591M20.25 10.5H18M7.757 14.743l-1.59 1.59M6 10.5H3.75m4.007-4.243l-1.59-1.59"}))}const uK=d.forwardRef(cK),dK=uK;function ki(e){return Array.isArray?Array.isArray(e):VP(e)==="[object Array]"}const fK=1/0;function hK(e){if(typeof e=="string")return e;let t=e+"";return t=="0"&&1/e==-fK?"-0":t}function pK(e){return e==null?"":hK(e)}function Bo(e){return typeof e=="string"}function BP(e){return typeof e=="number"}function mK(e){return e===!0||e===!1||gK(e)&&VP(e)=="[object Boolean]"}function UP(e){return typeof e=="object"}function gK(e){return UP(e)&&e!==null}function pr(e){return e!=null}function A0(e){return!e.trim().length}function VP(e){return e==null?e===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}const vK="Incorrect 'index' type",yK=e=>`Invalid value for key ${e}`,wK=e=>`Pattern length exceeds max of ${e}.`,xK=e=>`Missing ${e} property in key`,bK=e=>`Property 'weight' in key '${e}' must be a positive integer`,c2=Object.prototype.hasOwnProperty;class SK{constructor(t){this._keys=[],this._keyMap={};let n=0;t.forEach(r=>{let o=WP(r);this._keys.push(o),this._keyMap[o.id]=o,n+=o.weight}),this._keys.forEach(r=>{r.weight/=n})}get(t){return this._keyMap[t]}keys(){return this._keys}toJSON(){return JSON.stringify(this._keys)}}function WP(e){let t=null,n=null,r=null,o=1,i=null;if(Bo(e)||ki(e))r=e,t=u2(e),n=g1(e);else{if(!c2.call(e,"name"))throw new Error(xK("name"));const s=e.name;if(r=s,c2.call(e,"weight")&&(o=e.weight,o<=0))throw new Error(bK(s));t=u2(s),n=g1(s),i=e.getFn}return{path:t,id:n,weight:o,src:r,getFn:i}}function u2(e){return ki(e)?e:e.split(".")}function g1(e){return ki(e)?e.join("."):e}function _K(e,t){let n=[],r=!1;const o=(i,s,l)=>{if(pr(i))if(!s[l])n.push(i);else{let u=s[l];const f=i[u];if(!pr(f))return;if(l===s.length-1&&(Bo(f)||BP(f)||mK(f)))n.push(pK(f));else if(ki(f)){r=!0;for(let m=0,p=f.length;me.score===t.score?e.idx{this._keysMap[n.id]=r})}create(){this.isCreated||!this.docs.length||(this.isCreated=!0,Bo(this.docs[0])?this.docs.forEach((t,n)=>{this._addString(t,n)}):this.docs.forEach((t,n)=>{this._addObject(t,n)}),this.norm.clear())}add(t){const n=this.size();Bo(t)?this._addString(t,n):this._addObject(t,n)}removeAt(t){this.records.splice(t,1);for(let n=t,r=this.size();n{let s=o.getFn?o.getFn(t):this.getFn(t,o.path);if(pr(s)){if(ki(s)){let l=[];const u=[{nestedArrIndex:-1,value:s}];for(;u.length;){const{nestedArrIndex:f,value:m}=u.pop();if(pr(m))if(Bo(m)&&!A0(m)){let p={v:m,i:f,n:this.norm.get(m)};l.push(p)}else ki(m)&&m.forEach((p,g)=>{u.push({nestedArrIndex:g,value:p})})}r.$[i]=l}else if(Bo(s)&&!A0(s)){let l={v:s,n:this.norm.get(s)};r.$[i]=l}}}),this.records.push(r)}toJSON(){return{keys:this.keys,records:this.records}}}function HP(e,t,{getFn:n=He.getFn,fieldNormWeight:r=He.fieldNormWeight}={}){const o=new Ix({getFn:n,fieldNormWeight:r});return o.setKeys(e.map(WP)),o.setSources(t),o.create(),o}function PK(e,{getFn:t=He.getFn,fieldNormWeight:n=He.fieldNormWeight}={}){const{keys:r,records:o}=e,i=new Ix({getFn:t,fieldNormWeight:n});return i.setKeys(r),i.setIndexRecords(o),i}function xh(e,{errors:t=0,currentLocation:n=0,expectedLocation:r=0,distance:o=He.distance,ignoreLocation:i=He.ignoreLocation}={}){const s=t/e.length;if(i)return s;const l=Math.abs(r-n);return o?s+l/o:l?1:s}function AK(e=[],t=He.minMatchCharLength){let n=[],r=-1,o=-1,i=0;for(let s=e.length;i=t&&n.push([r,o]),r=-1)}return e[i-1]&&i-r>=t&&n.push([r,i-1]),n}const la=32;function MK(e,t,n,{location:r=He.location,distance:o=He.distance,threshold:i=He.threshold,findAllMatches:s=He.findAllMatches,minMatchCharLength:l=He.minMatchCharLength,includeMatches:u=He.includeMatches,ignoreLocation:f=He.ignoreLocation}={}){if(t.length>la)throw new Error(wK(la));const m=t.length,p=e.length,g=Math.max(0,Math.min(r,p));let y=i,b=g;const S=l>1||u,E=S?Array(p):[];let _;for(;(_=e.indexOf(t,b))>-1;){let A=xh(t,{currentLocation:_,expectedLocation:g,distance:o,ignoreLocation:f});if(y=Math.min(A,y),b=_+m,S){let D=0;for(;D=W;V-=1){let F=V-1,N=n[e.charAt(F)];if(S&&(E[F]=+!!N),X[V]=(X[V+1]<<1|1)&N,A&&(X[V]|=(x[V+1]|x[V])<<1|1|x[V+1]),X[V]&P&&(C=xh(t,{errors:A,currentLocation:F,expectedLocation:g,distance:o,ignoreLocation:f}),C<=y)){if(y=C,b=F,b<=g)break;W=Math.max(1,2*g-b)}}if(xh(t,{errors:A+1,currentLocation:g,expectedLocation:g,distance:o,ignoreLocation:f})>y)break;x=X}const M={isMatch:b>=0,score:Math.max(.001,C)};if(S){const A=AK(E,l);A.length?u&&(M.indices=A):M.isMatch=!1}return M}function OK(e){let t={};for(let n=0,r=e.length;n{this.chunks.push({pattern:g,alphabet:OK(g),startIndex:y})},p=this.pattern.length;if(p>la){let g=0;const y=p%la,b=p-y;for(;g{const{isMatch:_,score:x,indices:C}=MK(t,b,S,{location:o+E,distance:i,threshold:s,findAllMatches:l,minMatchCharLength:u,includeMatches:r,ignoreLocation:f});_&&(g=!0),p+=x,_&&C&&(m=[...m,...C])});let y={isMatch:g,score:g?p/this.chunks.length:1};return g&&r&&(y.indices=m),y}}class js{constructor(t){this.pattern=t}static isMultiMatch(t){return d2(t,this.multiRegex)}static isSingleMatch(t){return d2(t,this.singleRegex)}search(){}}function d2(e,t){const n=e.match(t);return n?n[1]:null}class NK extends js{constructor(t){super(t)}static get type(){return"exact"}static get multiRegex(){return/^="(.*)"$/}static get singleRegex(){return/^=(.*)$/}search(t){const n=t===this.pattern;return{isMatch:n,score:n?0:1,indices:[0,this.pattern.length-1]}}}class DK extends js{constructor(t){super(t)}static get type(){return"inverse-exact"}static get multiRegex(){return/^!"(.*)"$/}static get singleRegex(){return/^!(.*)$/}search(t){const r=t.indexOf(this.pattern)===-1;return{isMatch:r,score:r?0:1,indices:[0,t.length-1]}}}class IK extends js{constructor(t){super(t)}static get type(){return"prefix-exact"}static get multiRegex(){return/^\^"(.*)"$/}static get singleRegex(){return/^\^(.*)$/}search(t){const n=t.startsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[0,this.pattern.length-1]}}}class LK extends js{constructor(t){super(t)}static get type(){return"inverse-prefix-exact"}static get multiRegex(){return/^!\^"(.*)"$/}static get singleRegex(){return/^!\^(.*)$/}search(t){const n=!t.startsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[0,t.length-1]}}}class FK extends js{constructor(t){super(t)}static get type(){return"suffix-exact"}static get multiRegex(){return/^"(.*)"\$$/}static get singleRegex(){return/^(.*)\$$/}search(t){const n=t.endsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[t.length-this.pattern.length,t.length-1]}}}class jK extends js{constructor(t){super(t)}static get type(){return"inverse-suffix-exact"}static get multiRegex(){return/^!"(.*)"\$$/}static get singleRegex(){return/^!(.*)\$$/}search(t){const n=!t.endsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[0,t.length-1]}}}class GP extends js{constructor(t,{location:n=He.location,threshold:r=He.threshold,distance:o=He.distance,includeMatches:i=He.includeMatches,findAllMatches:s=He.findAllMatches,minMatchCharLength:l=He.minMatchCharLength,isCaseSensitive:u=He.isCaseSensitive,ignoreLocation:f=He.ignoreLocation}={}){super(t),this._bitapSearch=new KP(t,{location:n,threshold:r,distance:o,includeMatches:i,findAllMatches:s,minMatchCharLength:l,isCaseSensitive:u,ignoreLocation:f})}static get type(){return"fuzzy"}static get multiRegex(){return/^"(.*)"$/}static get singleRegex(){return/^(.*)$/}search(t){return this._bitapSearch.searchIn(t)}}class YP extends js{constructor(t){super(t)}static get type(){return"include"}static get multiRegex(){return/^'"(.*)"$/}static get singleRegex(){return/^'(.*)$/}search(t){let n=0,r;const o=[],i=this.pattern.length;for(;(r=t.indexOf(this.pattern,n))>-1;)n=r+i,o.push([r,n-1]);const s=!!o.length;return{isMatch:s,score:s?0:1,indices:o}}}const v1=[NK,YP,IK,LK,jK,FK,DK,GP],f2=v1.length,zK=/ +(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/,BK="|";function UK(e,t={}){return e.split(BK).map(n=>{let r=n.trim().split(zK).filter(i=>i&&!!i.trim()),o=[];for(let i=0,s=r.length;i!!(e[Up.AND]||e[Up.OR]),KK=e=>!!e[x1.PATH],GK=e=>!ki(e)&&UP(e)&&!b1(e),h2=e=>({[Up.AND]:Object.keys(e).map(t=>({[t]:e[t]}))});function XP(e,t,{auto:n=!0}={}){const r=o=>{let i=Object.keys(o);const s=KK(o);if(!s&&i.length>1&&!b1(o))return r(h2(o));if(GK(o)){const u=s?o[x1.PATH]:i[0],f=s?o[x1.PATTERN]:o[u];if(!Bo(f))throw new Error(yK(u));const m={keyId:g1(u),pattern:f};return n&&(m.searcher=w1(f,t)),m}let l={children:[],operator:i[0]};return i.forEach(u=>{const f=o[u];ki(f)&&f.forEach(m=>{l.children.push(r(m))})}),l};return b1(e)||(e=h2(e)),r(e)}function YK(e,{ignoreFieldNorm:t=He.ignoreFieldNorm}){e.forEach(n=>{let r=1;n.matches.forEach(({key:o,norm:i,score:s})=>{const l=o?o.weight:null;r*=Math.pow(s===0&&l?Number.EPSILON:s,(l||1)*(t?1:i))}),n.score=r})}function XK(e,t){const n=e.matches;t.matches=[],pr(n)&&n.forEach(r=>{if(!pr(r.indices)||!r.indices.length)return;const{indices:o,value:i}=r;let s={indices:o,value:i};r.key&&(s.key=r.key.src),r.idx>-1&&(s.refIndex=r.idx),t.matches.push(s)})}function ZK(e,t){t.score=e.score}function qK(e,t,{includeMatches:n=He.includeMatches,includeScore:r=He.includeScore}={}){const o=[];return n&&o.push(XK),r&&o.push(ZK),e.map(i=>{const{idx:s}=i,l={item:t[s],refIndex:s};return o.length&&o.forEach(u=>{u(i,l)}),l})}class kc{constructor(t,n={},r){this.options={...He,...n},this.options.useExtendedSearch,this._keyStore=new SK(this.options.keys),this.setCollection(t,r)}setCollection(t,n){if(this._docs=t,n&&!(n instanceof Ix))throw new Error(vK);this._myIndex=n||HP(this.options.keys,this._docs,{getFn:this.options.getFn,fieldNormWeight:this.options.fieldNormWeight})}add(t){pr(t)&&(this._docs.push(t),this._myIndex.add(t))}remove(t=()=>!1){const n=[];for(let r=0,o=this._docs.length;r-1&&(u=u.slice(0,n)),qK(u,this._docs,{includeMatches:r,includeScore:o})}_searchStringList(t){const n=w1(t,this.options),{records:r}=this._myIndex,o=[];return r.forEach(({v:i,i:s,n:l})=>{if(!pr(i))return;const{isMatch:u,score:f,indices:m}=n.searchIn(i);u&&o.push({item:i,idx:s,matches:[{score:f,value:i,norm:l,indices:m}]})}),o}_searchLogical(t){const n=XP(t,this.options),r=(l,u,f)=>{if(!l.children){const{keyId:p,searcher:g}=l,y=this._findMatches({key:this._keyStore.get(p),value:this._myIndex.getValueForItemAtKeyId(u,p),searcher:g});return y&&y.length?[{idx:f,item:u,matches:y}]:[]}const m=[];for(let p=0,g=l.children.length;p{if(pr(l)){let f=r(n,l,u);f.length&&(i[u]||(i[u]={idx:u,item:l,matches:[]},s.push(i[u])),f.forEach(({matches:m})=>{i[u].matches.push(...m)}))}}),s}_searchObjectList(t){const n=w1(t,this.options),{keys:r,records:o}=this._myIndex,i=[];return o.forEach(({$:s,i:l})=>{if(!pr(s))return;let u=[];r.forEach((f,m)=>{u.push(...this._findMatches({key:f,value:s[m],searcher:n}))}),u.length&&i.push({idx:l,item:s,matches:u})}),i}_findMatches({key:t,value:n,searcher:r}){if(!pr(n))return[];let o=[];if(ki(n))n.forEach(({v:i,i:s,n:l})=>{if(!pr(i))return;const{isMatch:u,score:f,indices:m}=r.searchIn(i);u&&o.push({score:f,key:t,value:i,idx:s,norm:l,indices:m})});else{const{v:i,n:s}=n,{isMatch:l,score:u,indices:f}=r.searchIn(i);l&&o.push({score:u,key:t,value:i,norm:s,indices:f})}return o}}kc.version="7.0.0";kc.createIndex=HP;kc.parseIndex=PK;kc.config=He;kc.parseQuery=XP;HK(WK);function Gd(e){const t=e+"CollectionProvider",[n,r]=Mn(t),[o,i]=n(t,{collectionRef:{current:null},itemMap:new Map}),s=y=>{const{scope:b,children:S}=y,E=Fe.useRef(null),_=Fe.useRef(new Map).current;return Fe.createElement(o,{scope:b,itemMap:_,collectionRef:E},S)},l=e+"CollectionSlot",u=Fe.forwardRef((y,b)=>{const{scope:S,children:E}=y,_=i(l,S),x=Be(b,_.collectionRef);return Fe.createElement(Zo,{ref:x},E)}),f=e+"CollectionItemSlot",m="data-radix-collection-item",p=Fe.forwardRef((y,b)=>{const{scope:S,children:E,..._}=y,x=Fe.useRef(null),C=Be(b,x),R=i(f,S);return Fe.useEffect(()=>(R.itemMap.set(x,{ref:x,..._}),()=>void R.itemMap.delete(x))),Fe.createElement(Zo,{[m]:"",ref:C},E)});function g(y){const b=i(e+"CollectionConsumer",y);return Fe.useCallback(()=>{const E=b.collectionRef.current;if(!E)return[];const _=Array.from(E.querySelectorAll(`[${m}]`));return Array.from(b.itemMap.values()).sort((R,P)=>_.indexOf(R.ref.current)-_.indexOf(P.ref.current))},[b.collectionRef,b.itemMap])}return[{Provider:s,Slot:u,ItemSlot:p},g,r]}const QK=d.createContext(void 0);function Tc(e){const t=d.useContext(QK);return e||t||"ltr"}const M0="rovingFocusGroup.onEntryFocus",JK={bubbles:!1,cancelable:!0},Lx="RovingFocusGroup",[S1,ZP,eG]=Gd(Lx),[tG,tg]=Mn(Lx,[eG]),[nG,rG]=tG(Lx),oG=d.forwardRef((e,t)=>d.createElement(S1.Provider,{scope:e.__scopeRovingFocusGroup},d.createElement(S1.Slot,{scope:e.__scopeRovingFocusGroup},d.createElement(iG,Y({},e,{ref:t}))))),iG=d.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:o=!1,dir:i,currentTabStopId:s,defaultCurrentTabStopId:l,onCurrentTabStopIdChange:u,onEntryFocus:f,...m}=e,p=d.useRef(null),g=Be(t,p),y=Tc(i),[b=null,S]=Zr({prop:s,defaultProp:l,onChange:u}),[E,_]=d.useState(!1),x=Ft(f),C=ZP(n),R=d.useRef(!1),[P,M]=d.useState(0);return d.useEffect(()=>{const A=p.current;if(A)return A.addEventListener(M0,x),()=>A.removeEventListener(M0,x)},[x]),d.createElement(nG,{scope:n,orientation:r,dir:y,loop:o,currentTabStopId:b,onItemFocus:d.useCallback(A=>S(A),[S]),onItemShiftTab:d.useCallback(()=>_(!0),[]),onFocusableItemAdd:d.useCallback(()=>M(A=>A+1),[]),onFocusableItemRemove:d.useCallback(()=>M(A=>A-1),[])},d.createElement(Pe.div,Y({tabIndex:E||P===0?-1:0,"data-orientation":r},m,{ref:g,style:{outline:"none",...e.style},onMouseDown:de(e.onMouseDown,()=>{R.current=!0}),onFocus:de(e.onFocus,A=>{const D=!R.current;if(A.target===A.currentTarget&&D&&!E){const U=new CustomEvent(M0,JK);if(A.currentTarget.dispatchEvent(U),!U.defaultPrevented){const W=C().filter(F=>F.focusable),q=W.find(F=>F.active),X=W.find(F=>F.id===b),V=[q,X,...W].filter(Boolean).map(F=>F.ref.current);qP(V)}}R.current=!1}),onBlur:de(e.onBlur,()=>_(!1))})))}),sG="RovingFocusGroupItem",aG=d.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:o=!1,tabStopId:i,...s}=e,l=nr(),u=i||l,f=rG(sG,n),m=f.currentTabStopId===u,p=ZP(n),{onFocusableItemAdd:g,onFocusableItemRemove:y}=f;return d.useEffect(()=>{if(r)return g(),()=>y()},[r,g,y]),d.createElement(S1.ItemSlot,{scope:n,id:u,focusable:r,active:o},d.createElement(Pe.span,Y({tabIndex:m?0:-1,"data-orientation":f.orientation},s,{ref:t,onMouseDown:de(e.onMouseDown,b=>{r?f.onItemFocus(u):b.preventDefault()}),onFocus:de(e.onFocus,()=>f.onItemFocus(u)),onKeyDown:de(e.onKeyDown,b=>{if(b.key==="Tab"&&b.shiftKey){f.onItemShiftTab();return}if(b.target!==b.currentTarget)return;const S=uG(b,f.orientation,f.dir);if(S!==void 0){b.preventDefault();let _=p().filter(x=>x.focusable).map(x=>x.ref.current);if(S==="last")_.reverse();else if(S==="prev"||S==="next"){S==="prev"&&_.reverse();const x=_.indexOf(b.currentTarget);_=f.loop?dG(_,x+1):_.slice(x+1)}setTimeout(()=>qP(_))}})})))}),lG={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function cG(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function uG(e,t,n){const r=cG(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return lG[r]}function qP(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function dG(e,t){return e.map((n,r)=>e[(t+r)%e.length])}const QP=oG,JP=aG,e5="Tabs",[fG,xte]=Mn(e5,[tg]),t5=tg(),[hG,Fx]=fG(e5),pG=d.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,onValueChange:o,defaultValue:i,orientation:s="horizontal",dir:l,activationMode:u="automatic",...f}=e,m=Tc(l),[p,g]=Zr({prop:r,onChange:o,defaultProp:i});return d.createElement(hG,{scope:n,baseId:nr(),value:p,onValueChange:g,orientation:s,dir:m,activationMode:u},d.createElement(Pe.div,Y({dir:m,"data-orientation":s},f,{ref:t})))}),mG="TabsList",gG=d.forwardRef((e,t)=>{const{__scopeTabs:n,loop:r=!0,...o}=e,i=Fx(mG,n),s=t5(n);return d.createElement(QP,Y({asChild:!0},s,{orientation:i.orientation,dir:i.dir,loop:r}),d.createElement(Pe.div,Y({role:"tablist","aria-orientation":i.orientation},o,{ref:t})))}),vG="TabsTrigger",yG=d.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,disabled:o=!1,...i}=e,s=Fx(vG,n),l=t5(n),u=n5(s.baseId,r),f=r5(s.baseId,r),m=r===s.value;return d.createElement(JP,Y({asChild:!0},l,{focusable:!o,active:m}),d.createElement(Pe.button,Y({type:"button",role:"tab","aria-selected":m,"aria-controls":f,"data-state":m?"active":"inactive","data-disabled":o?"":void 0,disabled:o,id:u},i,{ref:t,onMouseDown:de(e.onMouseDown,p=>{!o&&p.button===0&&p.ctrlKey===!1?s.onValueChange(r):p.preventDefault()}),onKeyDown:de(e.onKeyDown,p=>{[" ","Enter"].includes(p.key)&&s.onValueChange(r)}),onFocus:de(e.onFocus,()=>{const p=s.activationMode!=="manual";!m&&!o&&p&&s.onValueChange(r)})})))}),wG="TabsContent",xG=d.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,forceMount:o,children:i,...s}=e,l=Fx(wG,n),u=n5(l.baseId,r),f=r5(l.baseId,r),m=r===l.value,p=d.useRef(m);return d.useEffect(()=>{const g=requestAnimationFrame(()=>p.current=!1);return()=>cancelAnimationFrame(g)},[]),d.createElement(Sn,{present:o||m},({present:g})=>d.createElement(Pe.div,Y({"data-state":m?"active":"inactive","data-orientation":l.orientation,role:"tabpanel","aria-labelledby":u,hidden:!g,id:f,tabIndex:0},s,{ref:t,style:{...e.style,animationDuration:p.current?"0s":void 0}}),g&&i))});function n5(e,t){return`${e}-trigger-${t}`}function r5(e,t){return`${e}-content-${t}`}const bG=pG,o5=gG,i5=yG,s5=xG,a5=bG,jx=d.forwardRef(({className:e,...t},n)=>v.jsx(o5,{ref:n,className:Ce("inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground",e),tabIndex:-1,...t}));jx.displayName=o5.displayName;const pa=d.forwardRef(({className:e,...t},n)=>v.jsx(i5,{ref:n,className:Ce("inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow",e),tabIndex:-1,...t}));pa.displayName=i5.displayName;const Su=d.forwardRef(({className:e,...t},n)=>v.jsx(s5,{ref:n,className:Ce("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",e),tabIndex:-1,...t}));Su.displayName=s5.displayName;function fd(e,[t,n]){return Math.min(n,Math.max(t,e))}function zx(e){const t=d.useRef({value:e,previous:e});return d.useMemo(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}const SG=[" ","Enter","ArrowUp","ArrowDown"],_G=[" ","Enter"],ng="Select",[rg,og,EG]=Gd(ng),[Pc,bte]=Mn(ng,[EG,Fs]),Bx=Fs(),[CG,Fa]=Pc(ng),[$G,RG]=Pc(ng),kG=e=>{const{__scopeSelect:t,children:n,open:r,defaultOpen:o,onOpenChange:i,value:s,defaultValue:l,onValueChange:u,dir:f,name:m,autoComplete:p,disabled:g,required:y}=e,b=Bx(t),[S,E]=d.useState(null),[_,x]=d.useState(null),[C,R]=d.useState(!1),P=Tc(f),[M=!1,A]=Zr({prop:r,defaultProp:o,onChange:i}),[D,U]=Zr({prop:s,defaultProp:l,onChange:u}),W=d.useRef(null),q=S?!!S.closest("form"):!0,[X,ae]=d.useState(new Set),V=Array.from(X).map(F=>F.props.value).join(";");return d.createElement(jd,b,d.createElement(CG,{required:y,scope:t,trigger:S,onTriggerChange:E,valueNode:_,onValueNodeChange:x,valueNodeHasChildren:C,onValueNodeHasChildrenChange:R,contentId:nr(),value:D,onValueChange:U,open:M,onOpenChange:A,dir:P,triggerPointerDownPosRef:W,disabled:g},d.createElement(rg.Provider,{scope:t},d.createElement($G,{scope:e.__scopeSelect,onNativeOptionAdd:d.useCallback(F=>{ae(N=>new Set(N).add(F))},[]),onNativeOptionRemove:d.useCallback(F=>{ae(N=>{const ie=new Set(N);return ie.delete(F),ie})},[])},n)),q?d.createElement(f5,{key:V,"aria-hidden":!0,required:y,tabIndex:-1,name:m,autoComplete:p,value:D,onChange:F=>U(F.target.value),disabled:g},D===void 0?d.createElement("option",{value:""}):null,Array.from(X)):null))},TG="SelectTrigger",PG=d.forwardRef((e,t)=>{const{__scopeSelect:n,disabled:r=!1,...o}=e,i=Bx(n),s=Fa(TG,n),l=s.disabled||r,u=Be(t,s.onTriggerChange),f=og(n),[m,p,g]=h5(b=>{const S=f().filter(x=>!x.disabled),E=S.find(x=>x.value===s.value),_=p5(S,b,E);_!==void 0&&s.onValueChange(_.value)}),y=()=>{l||(s.onOpenChange(!0),g())};return d.createElement(Vm,Y({asChild:!0},i),d.createElement(Pe.button,Y({type:"button",role:"combobox","aria-controls":s.contentId,"aria-expanded":s.open,"aria-required":s.required,"aria-autocomplete":"none",dir:s.dir,"data-state":s.open?"open":"closed",disabled:l,"data-disabled":l?"":void 0,"data-placeholder":d5(s.value)?"":void 0},o,{ref:u,onClick:de(o.onClick,b=>{b.currentTarget.focus()}),onPointerDown:de(o.onPointerDown,b=>{const S=b.target;S.hasPointerCapture(b.pointerId)&&S.releasePointerCapture(b.pointerId),b.button===0&&b.ctrlKey===!1&&(y(),s.triggerPointerDownPosRef.current={x:Math.round(b.pageX),y:Math.round(b.pageY)},b.preventDefault())}),onKeyDown:de(o.onKeyDown,b=>{const S=m.current!=="";!(b.ctrlKey||b.altKey||b.metaKey)&&b.key.length===1&&p(b.key),!(S&&b.key===" ")&&SG.includes(b.key)&&(y(),b.preventDefault())})})))}),AG="SelectValue",MG=d.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,children:i,placeholder:s="",...l}=e,u=Fa(AG,n),{onValueNodeHasChildrenChange:f}=u,m=i!==void 0,p=Be(t,u.onValueNodeChange);return An(()=>{f(m)},[f,m]),d.createElement(Pe.span,Y({},l,{ref:p,style:{pointerEvents:"none"}}),d5(u.value)?d.createElement(d.Fragment,null,s):i)}),OG=d.forwardRef((e,t)=>{const{__scopeSelect:n,children:r,...o}=e;return d.createElement(Pe.span,Y({"aria-hidden":!0},o,{ref:t}),r||"▼")}),NG=e=>d.createElement(zd,Y({asChild:!0},e)),dc="SelectContent",DG=d.forwardRef((e,t)=>{const n=Fa(dc,e.__scopeSelect),[r,o]=d.useState();if(An(()=>{o(new DocumentFragment)},[]),!n.open){const i=r;return i?Is.createPortal(d.createElement(l5,{scope:e.__scopeSelect},d.createElement(rg.Slot,{scope:e.__scopeSelect},d.createElement("div",null,e.children))),i):null}return d.createElement(IG,Y({},e,{ref:t}))}),hi=10,[l5,ja]=Pc(dc),IG=d.forwardRef((e,t)=>{const{__scopeSelect:n,position:r="item-aligned",onCloseAutoFocus:o,onEscapeKeyDown:i,onPointerDownOutside:s,side:l,sideOffset:u,align:f,alignOffset:m,arrowPadding:p,collisionBoundary:g,collisionPadding:y,sticky:b,hideWhenDetached:S,avoidCollisions:E,..._}=e,x=Fa(dc,n),[C,R]=d.useState(null),[P,M]=d.useState(null),A=Be(t,he=>R(he)),[D,U]=d.useState(null),[W,q]=d.useState(null),X=og(n),[ae,V]=d.useState(!1),F=d.useRef(!1);d.useEffect(()=>{if(C)return Qm(C)},[C]),Xm();const N=d.useCallback(he=>{const[xe,...$e]=X().map(je=>je.ref.current),[Ae]=$e.slice(-1),Me=document.activeElement;for(const je of he)if(je===Me||(je==null||je.scrollIntoView({block:"nearest"}),je===xe&&P&&(P.scrollTop=0),je===Ae&&P&&(P.scrollTop=P.scrollHeight),je==null||je.focus(),document.activeElement!==Me))return},[X,P]),ie=d.useCallback(()=>N([D,C]),[N,D,C]);d.useEffect(()=>{ae&&ie()},[ae,ie]);const{onOpenChange:K,triggerPointerDownPosRef:Z}=x;d.useEffect(()=>{if(C){let he={x:0,y:0};const xe=Ae=>{var Me,je,Mt,ct;he={x:Math.abs(Math.round(Ae.pageX)-((Me=(je=Z.current)===null||je===void 0?void 0:je.x)!==null&&Me!==void 0?Me:0)),y:Math.abs(Math.round(Ae.pageY)-((Mt=(ct=Z.current)===null||ct===void 0?void 0:ct.y)!==null&&Mt!==void 0?Mt:0))}},$e=Ae=>{he.x<=10&&he.y<=10?Ae.preventDefault():C.contains(Ae.target)||K(!1),document.removeEventListener("pointermove",xe),Z.current=null};return Z.current!==null&&(document.addEventListener("pointermove",xe),document.addEventListener("pointerup",$e,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",xe),document.removeEventListener("pointerup",$e,{capture:!0})}}},[C,K,Z]),d.useEffect(()=>{const he=()=>K(!1);return window.addEventListener("blur",he),window.addEventListener("resize",he),()=>{window.removeEventListener("blur",he),window.removeEventListener("resize",he)}},[K]);const[H,se]=h5(he=>{const xe=X().filter(Me=>!Me.disabled),$e=xe.find(Me=>Me.ref.current===document.activeElement),Ae=p5(xe,he,$e);Ae&&setTimeout(()=>Ae.ref.current.focus())}),ce=d.useCallback((he,xe,$e)=>{const Ae=!F.current&&!$e;(x.value!==void 0&&x.value===xe||Ae)&&(U(he),Ae&&(F.current=!0))},[x.value]),Ve=d.useCallback(()=>C==null?void 0:C.focus(),[C]),Ue=d.useCallback((he,xe,$e)=>{const Ae=!F.current&&!$e;(x.value!==void 0&&x.value===xe||Ae)&&q(he)},[x.value]),We=r==="popper"?p2:LG,Oe=We===p2?{side:l,sideOffset:u,align:f,alignOffset:m,arrowPadding:p,collisionBoundary:g,collisionPadding:y,sticky:b,hideWhenDetached:S,avoidCollisions:E}:{};return d.createElement(l5,{scope:n,content:C,viewport:P,onViewportChange:M,itemRefCallback:ce,selectedItem:D,onItemLeave:Ve,itemTextRefCallback:Ue,focusSelectedItem:ie,selectedItemText:W,position:r,isPositioned:ae,searchRef:H},d.createElement(qm,{as:Zo,allowPinchZoom:!0},d.createElement(Ym,{asChild:!0,trapped:x.open,onMountAutoFocus:he=>{he.preventDefault()},onUnmountAutoFocus:de(o,he=>{var xe;(xe=x.trigger)===null||xe===void 0||xe.focus({preventScroll:!0}),he.preventDefault()})},d.createElement(Ec,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:i,onPointerDownOutside:s,onFocusOutside:he=>he.preventDefault(),onDismiss:()=>x.onOpenChange(!1)},d.createElement(We,Y({role:"listbox",id:x.contentId,"data-state":x.open?"open":"closed",dir:x.dir,onContextMenu:he=>he.preventDefault()},_,Oe,{onPlaced:()=>V(!0),ref:A,style:{display:"flex",flexDirection:"column",outline:"none",..._.style},onKeyDown:de(_.onKeyDown,he=>{const xe=he.ctrlKey||he.altKey||he.metaKey;if(he.key==="Tab"&&he.preventDefault(),!xe&&he.key.length===1&&se(he.key),["ArrowUp","ArrowDown","Home","End"].includes(he.key)){let Ae=X().filter(Me=>!Me.disabled).map(Me=>Me.ref.current);if(["ArrowUp","End"].includes(he.key)&&(Ae=Ae.slice().reverse()),["ArrowUp","ArrowDown"].includes(he.key)){const Me=he.target,je=Ae.indexOf(Me);Ae=Ae.slice(je+1)}setTimeout(()=>N(Ae)),he.preventDefault()}})}))))))}),LG=d.forwardRef((e,t)=>{const{__scopeSelect:n,onPlaced:r,...o}=e,i=Fa(dc,n),s=ja(dc,n),[l,u]=d.useState(null),[f,m]=d.useState(null),p=Be(t,A=>m(A)),g=og(n),y=d.useRef(!1),b=d.useRef(!0),{viewport:S,selectedItem:E,selectedItemText:_,focusSelectedItem:x}=s,C=d.useCallback(()=>{if(i.trigger&&i.valueNode&&l&&f&&S&&E&&_){const A=i.trigger.getBoundingClientRect(),D=f.getBoundingClientRect(),U=i.valueNode.getBoundingClientRect(),W=_.getBoundingClientRect();if(i.dir!=="rtl"){const Me=W.left-D.left,je=U.left-Me,Mt=A.left-je,ct=A.width+Mt,Kt=Math.max(ct,D.width),Er=window.innerWidth-hi,gt=fd(je,[hi,Er-Kt]);l.style.minWidth=ct+"px",l.style.left=gt+"px"}else{const Me=D.right-W.right,je=window.innerWidth-U.right-Me,Mt=window.innerWidth-A.right-je,ct=A.width+Mt,Kt=Math.max(ct,D.width),Er=window.innerWidth-hi,gt=fd(je,[hi,Er-Kt]);l.style.minWidth=ct+"px",l.style.right=gt+"px"}const q=g(),X=window.innerHeight-hi*2,ae=S.scrollHeight,V=window.getComputedStyle(f),F=parseInt(V.borderTopWidth,10),N=parseInt(V.paddingTop,10),ie=parseInt(V.borderBottomWidth,10),K=parseInt(V.paddingBottom,10),Z=F+N+ae+K+ie,H=Math.min(E.offsetHeight*5,Z),se=window.getComputedStyle(S),ce=parseInt(se.paddingTop,10),Ve=parseInt(se.paddingBottom,10),Ue=A.top+A.height/2-hi,We=X-Ue,Oe=E.offsetHeight/2,he=E.offsetTop+Oe,xe=F+N+he,$e=Z-xe;if(xe<=Ue){const Me=E===q[q.length-1].ref.current;l.style.bottom="0px";const je=f.clientHeight-S.offsetTop-S.offsetHeight,Mt=Math.max(We,Oe+(Me?Ve:0)+je+ie),ct=xe+Mt;l.style.height=ct+"px"}else{const Me=E===q[0].ref.current;l.style.top="0px";const Mt=Math.max(Ue,F+S.offsetTop+(Me?ce:0)+Oe)+$e;l.style.height=Mt+"px",S.scrollTop=xe-Ue+S.offsetTop}l.style.margin=`${hi}px 0`,l.style.minHeight=H+"px",l.style.maxHeight=X+"px",r==null||r(),requestAnimationFrame(()=>y.current=!0)}},[g,i.trigger,i.valueNode,l,f,S,E,_,i.dir,r]);An(()=>C(),[C]);const[R,P]=d.useState();An(()=>{f&&P(window.getComputedStyle(f).zIndex)},[f]);const M=d.useCallback(A=>{A&&b.current===!0&&(C(),x==null||x(),b.current=!1)},[C,x]);return d.createElement(FG,{scope:n,contentWrapper:l,shouldExpandOnScrollRef:y,onScrollButtonChange:M},d.createElement("div",{ref:u,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:R}},d.createElement(Pe.div,Y({},o,{ref:p,style:{boxSizing:"border-box",maxHeight:"100%",...o.style}}))))}),p2=d.forwardRef((e,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:o=hi,...i}=e,s=Bx(n);return d.createElement(Wm,Y({},s,i,{ref:t,align:r,collisionPadding:o,style:{boxSizing:"border-box",...i.style,"--radix-select-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-select-content-available-width":"var(--radix-popper-available-width)","--radix-select-content-available-height":"var(--radix-popper-available-height)","--radix-select-trigger-width":"var(--radix-popper-anchor-width)","--radix-select-trigger-height":"var(--radix-popper-anchor-height)"}}))}),[FG,Ux]=Pc(dc,{}),m2="SelectViewport",jG=d.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=ja(m2,n),i=Ux(m2,n),s=Be(t,o.onViewportChange),l=d.useRef(0);return d.createElement(d.Fragment,null,d.createElement("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"}}),d.createElement(rg.Slot,{scope:n},d.createElement(Pe.div,Y({"data-radix-select-viewport":"",role:"presentation"},r,{ref:s,style:{position:"relative",flex:1,overflow:"auto",...r.style},onScroll:de(r.onScroll,u=>{const f=u.currentTarget,{contentWrapper:m,shouldExpandOnScrollRef:p}=i;if(p!=null&&p.current&&m){const g=Math.abs(l.current-f.scrollTop);if(g>0){const y=window.innerHeight-hi*2,b=parseFloat(m.style.minHeight),S=parseFloat(m.style.height),E=Math.max(b,S);if(E0?C:0,m.style.justifyContent="flex-end")}}}l.current=f.scrollTop})}))))}),zG="SelectGroup",[BG,UG]=Pc(zG),VG=d.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=nr();return d.createElement(BG,{scope:n,id:o},d.createElement(Pe.div,Y({role:"group","aria-labelledby":o},r,{ref:t})))}),WG="SelectLabel",HG=d.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=UG(WG,n);return d.createElement(Pe.div,Y({id:o.id},r,{ref:t}))}),_1="SelectItem",[KG,c5]=Pc(_1),GG=d.forwardRef((e,t)=>{const{__scopeSelect:n,value:r,disabled:o=!1,textValue:i,...s}=e,l=Fa(_1,n),u=ja(_1,n),f=l.value===r,[m,p]=d.useState(i??""),[g,y]=d.useState(!1),b=Be(t,_=>{var x;return(x=u.itemRefCallback)===null||x===void 0?void 0:x.call(u,_,r,o)}),S=nr(),E=()=>{o||(l.onValueChange(r),l.onOpenChange(!1))};if(r==="")throw new Error("A must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.");return d.createElement(KG,{scope:n,value:r,disabled:o,textId:S,isSelected:f,onItemTextChange:d.useCallback(_=>{p(x=>{var C;return x||((C=_==null?void 0:_.textContent)!==null&&C!==void 0?C:"").trim()})},[])},d.createElement(rg.ItemSlot,{scope:n,value:r,disabled:o,textValue:m},d.createElement(Pe.div,Y({role:"option","aria-labelledby":S,"data-highlighted":g?"":void 0,"aria-selected":f&&g,"data-state":f?"checked":"unchecked","aria-disabled":o||void 0,"data-disabled":o?"":void 0,tabIndex:o?void 0:-1},s,{ref:b,onFocus:de(s.onFocus,()=>y(!0)),onBlur:de(s.onBlur,()=>y(!1)),onPointerUp:de(s.onPointerUp,E),onPointerMove:de(s.onPointerMove,_=>{if(o){var x;(x=u.onItemLeave)===null||x===void 0||x.call(u)}else _.currentTarget.focus({preventScroll:!0})}),onPointerLeave:de(s.onPointerLeave,_=>{if(_.currentTarget===document.activeElement){var x;(x=u.onItemLeave)===null||x===void 0||x.call(u)}}),onKeyDown:de(s.onKeyDown,_=>{var x;((x=u.searchRef)===null||x===void 0?void 0:x.current)!==""&&_.key===" "||(_G.includes(_.key)&&E(),_.key===" "&&_.preventDefault())})}))))}),bh="SelectItemText",YG=d.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,...i}=e,s=Fa(bh,n),l=ja(bh,n),u=c5(bh,n),f=RG(bh,n),[m,p]=d.useState(null),g=Be(t,_=>p(_),u.onItemTextChange,_=>{var x;return(x=l.itemTextRefCallback)===null||x===void 0?void 0:x.call(l,_,u.value,u.disabled)}),y=m==null?void 0:m.textContent,b=d.useMemo(()=>d.createElement("option",{key:u.value,value:u.value,disabled:u.disabled},y),[u.disabled,u.value,y]),{onNativeOptionAdd:S,onNativeOptionRemove:E}=f;return An(()=>(S(b),()=>E(b)),[S,E,b]),d.createElement(d.Fragment,null,d.createElement(Pe.span,Y({id:u.textId},i,{ref:g})),u.isSelected&&s.valueNode&&!s.valueNodeHasChildren?Is.createPortal(i.children,s.valueNode):null)}),XG="SelectItemIndicator",ZG=d.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return c5(XG,n).isSelected?d.createElement(Pe.span,Y({"aria-hidden":!0},r,{ref:t})):null}),g2="SelectScrollUpButton",qG=d.forwardRef((e,t)=>{const n=ja(g2,e.__scopeSelect),r=Ux(g2,e.__scopeSelect),[o,i]=d.useState(!1),s=Be(t,r.onScrollButtonChange);return An(()=>{if(n.viewport&&n.isPositioned){let f=function(){const m=u.scrollTop>0;i(m)};var l=f;const u=n.viewport;return f(),u.addEventListener("scroll",f),()=>u.removeEventListener("scroll",f)}},[n.viewport,n.isPositioned]),o?d.createElement(u5,Y({},e,{ref:s,onAutoScroll:()=>{const{viewport:l,selectedItem:u}=n;l&&u&&(l.scrollTop=l.scrollTop-u.offsetHeight)}})):null}),v2="SelectScrollDownButton",QG=d.forwardRef((e,t)=>{const n=ja(v2,e.__scopeSelect),r=Ux(v2,e.__scopeSelect),[o,i]=d.useState(!1),s=Be(t,r.onScrollButtonChange);return An(()=>{if(n.viewport&&n.isPositioned){let f=function(){const m=u.scrollHeight-u.clientHeight,p=Math.ceil(u.scrollTop)u.removeEventListener("scroll",f)}},[n.viewport,n.isPositioned]),o?d.createElement(u5,Y({},e,{ref:s,onAutoScroll:()=>{const{viewport:l,selectedItem:u}=n;l&&u&&(l.scrollTop=l.scrollTop+u.offsetHeight)}})):null}),u5=d.forwardRef((e,t)=>{const{__scopeSelect:n,onAutoScroll:r,...o}=e,i=ja("SelectScrollButton",n),s=d.useRef(null),l=og(n),u=d.useCallback(()=>{s.current!==null&&(window.clearInterval(s.current),s.current=null)},[]);return d.useEffect(()=>()=>u(),[u]),An(()=>{var f;const m=l().find(p=>p.ref.current===document.activeElement);m==null||(f=m.ref.current)===null||f===void 0||f.scrollIntoView({block:"nearest"})},[l]),d.createElement(Pe.div,Y({"aria-hidden":!0},o,{ref:t,style:{flexShrink:0,...o.style},onPointerDown:de(o.onPointerDown,()=>{s.current===null&&(s.current=window.setInterval(r,50))}),onPointerMove:de(o.onPointerMove,()=>{var f;(f=i.onItemLeave)===null||f===void 0||f.call(i),s.current===null&&(s.current=window.setInterval(r,50))}),onPointerLeave:de(o.onPointerLeave,()=>{u()})}))}),JG=d.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return d.createElement(Pe.div,Y({"aria-hidden":!0},r,{ref:t}))});function d5(e){return e===""||e===void 0}const f5=d.forwardRef((e,t)=>{const{value:n,...r}=e,o=d.useRef(null),i=Be(t,o),s=zx(n);return d.useEffect(()=>{const l=o.current,u=window.HTMLSelectElement.prototype,m=Object.getOwnPropertyDescriptor(u,"value").set;if(s!==n&&m){const p=new Event("change",{bubbles:!0});m.call(l,n),l.dispatchEvent(p)}},[s,n]),d.createElement(Hm,{asChild:!0},d.createElement("select",Y({},r,{ref:i,defaultValue:n})))});f5.displayName="BubbleSelect";function h5(e){const t=Ft(e),n=d.useRef(""),r=d.useRef(0),o=d.useCallback(s=>{const l=n.current+s;t(l),function u(f){n.current=f,window.clearTimeout(r.current),f!==""&&(r.current=window.setTimeout(()=>u(""),1e3))}(l)},[t]),i=d.useCallback(()=>{n.current="",window.clearTimeout(r.current)},[]);return d.useEffect(()=>()=>window.clearTimeout(r.current),[]),[n,o,i]}function p5(e,t,n){const o=t.length>1&&Array.from(t).every(f=>f===t[0])?t[0]:t,i=n?e.indexOf(n):-1;let s=eY(e,Math.max(i,0));o.length===1&&(s=s.filter(f=>f!==n));const u=s.find(f=>f.textValue.toLowerCase().startsWith(o.toLowerCase()));return u!==n?u:void 0}function eY(e,t){return e.map((n,r)=>e[(t+r)%e.length])}const tY=kG,m5=PG,nY=MG,rY=OG,oY=NG,g5=DG,iY=jG,sY=VG,v5=HG,y5=GG,aY=YG,lY=ZG,w5=qG,x5=QG,b5=JG,Uo=tY,vi=sY,Vo=nY,go=d.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(m5,{ref:r,className:Ce("flex h-9 w-full items-center justify-between whitespace-nowrap rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",e),tabIndex:-1,...n,children:[t,v.jsx(rY,{asChild:!0,children:v.jsx(Zj,{className:"h-4 w-4 opacity-50"})})]}));go.displayName=m5.displayName;const S5=d.forwardRef(({className:e,...t},n)=>v.jsx(w5,{ref:n,className:Ce("flex cursor-default items-center justify-center py-1",e),...t,children:v.jsx(rz,{})}));S5.displayName=w5.displayName;const _5=d.forwardRef(({className:e,...t},n)=>v.jsx(x5,{ref:n,className:Ce("flex cursor-default items-center justify-center py-1",e),...t,children:v.jsx(Jj,{})}));_5.displayName=x5.displayName;const vo=d.forwardRef(({className:e,children:t,position:n="popper",...r},o)=>v.jsx(oY,{children:v.jsxs(g5,{ref:o,className:Ce("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",n==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:n,onCloseAutoFocus:i=>i.preventDefault(),...r,children:[v.jsx(S5,{}),v.jsx(iY,{className:Ce("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),v.jsx(_5,{})]})}));vo.displayName=g5.displayName;const cY=d.forwardRef(({className:e,...t},n)=>v.jsx(v5,{ref:n,className:Ce("px-2 py-1.5 text-sm font-semibold",e),...t}));cY.displayName=v5.displayName;const yo=d.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(y5,{ref:r,className:Ce("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-2 pr-8 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[v.jsx("span",{className:"absolute right-2 flex h-3.5 w-3.5 items-center justify-center",children:v.jsx(lY,{children:v.jsx(yT,{className:"h-4 w-4"})})}),v.jsx(aY,{children:t})]}));yo.displayName=y5.displayName;const uY=d.forwardRef(({className:e,...t},n)=>v.jsx(b5,{ref:n,className:Ce("-mx-1 my-1 h-px bg-muted",e),...t}));uY.displayName=b5.displayName;function dY(e,t){return d.useReducer((n,r)=>{const o=t[n][r];return o??n},e)}const E5="ScrollArea",[C5,Ste]=Mn(E5),[fY,qr]=C5(E5),hY=d.forwardRef((e,t)=>{const{__scopeScrollArea:n,type:r="hover",dir:o,scrollHideDelay:i=600,...s}=e,[l,u]=d.useState(null),[f,m]=d.useState(null),[p,g]=d.useState(null),[y,b]=d.useState(null),[S,E]=d.useState(null),[_,x]=d.useState(0),[C,R]=d.useState(0),[P,M]=d.useState(!1),[A,D]=d.useState(!1),U=Be(t,q=>u(q)),W=Tc(o);return d.createElement(fY,{scope:n,type:r,dir:W,scrollHideDelay:i,scrollArea:l,viewport:f,onViewportChange:m,content:p,onContentChange:g,scrollbarX:y,onScrollbarXChange:b,scrollbarXEnabled:P,onScrollbarXEnabledChange:M,scrollbarY:S,onScrollbarYChange:E,scrollbarYEnabled:A,onScrollbarYEnabledChange:D,onCornerWidthChange:x,onCornerHeightChange:R},d.createElement(Pe.div,Y({dir:W},s,{ref:U,style:{position:"relative","--radix-scroll-area-corner-width":_+"px","--radix-scroll-area-corner-height":C+"px",...e.style}})))}),pY="ScrollAreaViewport",mY=d.forwardRef((e,t)=>{const{__scopeScrollArea:n,children:r,...o}=e,i=qr(pY,n),s=d.useRef(null),l=Be(t,s,i.onViewportChange);return d.createElement(d.Fragment,null,d.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}"}}),d.createElement(Pe.div,Y({"data-radix-scroll-area-viewport":""},o,{ref:l,style:{overflowX:i.scrollbarXEnabled?"scroll":"hidden",overflowY:i.scrollbarYEnabled?"scroll":"hidden",...e.style}}),d.createElement("div",{ref:i.onContentChange,style:{minWidth:"100%",display:"table"}},r)))}),Oi="ScrollAreaScrollbar",$5=d.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=qr(Oi,e.__scopeScrollArea),{onScrollbarXEnabledChange:i,onScrollbarYEnabledChange:s}=o,l=e.orientation==="horizontal";return d.useEffect(()=>(l?i(!0):s(!0),()=>{l?i(!1):s(!1)}),[l,i,s]),o.type==="hover"?d.createElement(gY,Y({},r,{ref:t,forceMount:n})):o.type==="scroll"?d.createElement(vY,Y({},r,{ref:t,forceMount:n})):o.type==="auto"?d.createElement(R5,Y({},r,{ref:t,forceMount:n})):o.type==="always"?d.createElement(Vx,Y({},r,{ref:t})):null}),gY=d.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=qr(Oi,e.__scopeScrollArea),[i,s]=d.useState(!1);return d.useEffect(()=>{const l=o.scrollArea;let u=0;if(l){const f=()=>{window.clearTimeout(u),s(!0)},m=()=>{u=window.setTimeout(()=>s(!1),o.scrollHideDelay)};return l.addEventListener("pointerenter",f),l.addEventListener("pointerleave",m),()=>{window.clearTimeout(u),l.removeEventListener("pointerenter",f),l.removeEventListener("pointerleave",m)}}},[o.scrollArea,o.scrollHideDelay]),d.createElement(Sn,{present:n||i},d.createElement(R5,Y({"data-state":i?"visible":"hidden"},r,{ref:t})))}),vY=d.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=qr(Oi,e.__scopeScrollArea),i=e.orientation==="horizontal",s=sg(()=>u("SCROLL_END"),100),[l,u]=dY("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 d.useEffect(()=>{if(l==="idle"){const f=window.setTimeout(()=>u("HIDE"),o.scrollHideDelay);return()=>window.clearTimeout(f)}},[l,o.scrollHideDelay,u]),d.useEffect(()=>{const f=o.viewport,m=i?"scrollLeft":"scrollTop";if(f){let p=f[m];const g=()=>{const y=f[m];p!==y&&(u("SCROLL"),s()),p=y};return f.addEventListener("scroll",g),()=>f.removeEventListener("scroll",g)}},[o.viewport,i,u,s]),d.createElement(Sn,{present:n||l!=="hidden"},d.createElement(Vx,Y({"data-state":l==="hidden"?"hidden":"visible"},r,{ref:t,onPointerEnter:de(e.onPointerEnter,()=>u("POINTER_ENTER")),onPointerLeave:de(e.onPointerLeave,()=>u("POINTER_LEAVE"))})))}),R5=d.forwardRef((e,t)=>{const n=qr(Oi,e.__scopeScrollArea),{forceMount:r,...o}=e,[i,s]=d.useState(!1),l=e.orientation==="horizontal",u=sg(()=>{if(n.viewport){const f=n.viewport.offsetWidth{const{orientation:n="vertical",...r}=e,o=qr(Oi,e.__scopeScrollArea),i=d.useRef(null),s=d.useRef(0),[l,u]=d.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),f=A5(l.viewport,l.content),m={...r,sizes:l,onSizesChange:u,hasThumb:f>0&&f<1,onThumbChange:g=>i.current=g,onThumbPointerUp:()=>s.current=0,onThumbPointerDown:g=>s.current=g};function p(g,y){return CY(g,s.current,l,y)}return n==="horizontal"?d.createElement(yY,Y({},m,{ref:t,onThumbPositionChange:()=>{if(o.viewport&&i.current){const g=o.viewport.scrollLeft,y=y2(g,l,o.dir);i.current.style.transform=`translate3d(${y}px, 0, 0)`}},onWheelScroll:g=>{o.viewport&&(o.viewport.scrollLeft=g)},onDragScroll:g=>{o.viewport&&(o.viewport.scrollLeft=p(g,o.dir))}})):n==="vertical"?d.createElement(wY,Y({},m,{ref:t,onThumbPositionChange:()=>{if(o.viewport&&i.current){const g=o.viewport.scrollTop,y=y2(g,l);i.current.style.transform=`translate3d(0, ${y}px, 0)`}},onWheelScroll:g=>{o.viewport&&(o.viewport.scrollTop=g)},onDragScroll:g=>{o.viewport&&(o.viewport.scrollTop=p(g))}})):null}),yY=d.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,i=qr(Oi,e.__scopeScrollArea),[s,l]=d.useState(),u=d.useRef(null),f=Be(t,u,i.onScrollbarXChange);return d.useEffect(()=>{u.current&&l(getComputedStyle(u.current))},[u]),d.createElement(T5,Y({"data-orientation":"horizontal"},o,{ref:f,sizes:n,style:{bottom:0,left:i.dir==="rtl"?"var(--radix-scroll-area-corner-width)":0,right:i.dir==="ltr"?"var(--radix-scroll-area-corner-width)":0,"--radix-scroll-area-thumb-width":ig(n)+"px",...e.style},onThumbPointerDown:m=>e.onThumbPointerDown(m.x),onDragScroll:m=>e.onDragScroll(m.x),onWheelScroll:(m,p)=>{if(i.viewport){const g=i.viewport.scrollLeft+m.deltaX;e.onWheelScroll(g),O5(g,p)&&m.preventDefault()}},onResize:()=>{u.current&&i.viewport&&s&&r({content:i.viewport.scrollWidth,viewport:i.viewport.offsetWidth,scrollbar:{size:u.current.clientWidth,paddingStart:Vp(s.paddingLeft),paddingEnd:Vp(s.paddingRight)}})}}))}),wY=d.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,i=qr(Oi,e.__scopeScrollArea),[s,l]=d.useState(),u=d.useRef(null),f=Be(t,u,i.onScrollbarYChange);return d.useEffect(()=>{u.current&&l(getComputedStyle(u.current))},[u]),d.createElement(T5,Y({"data-orientation":"vertical"},o,{ref:f,sizes:n,style:{top:0,right:i.dir==="ltr"?0:void 0,left:i.dir==="rtl"?0:void 0,bottom:"var(--radix-scroll-area-corner-height)","--radix-scroll-area-thumb-height":ig(n)+"px",...e.style},onThumbPointerDown:m=>e.onThumbPointerDown(m.y),onDragScroll:m=>e.onDragScroll(m.y),onWheelScroll:(m,p)=>{if(i.viewport){const g=i.viewport.scrollTop+m.deltaY;e.onWheelScroll(g),O5(g,p)&&m.preventDefault()}},onResize:()=>{u.current&&i.viewport&&s&&r({content:i.viewport.scrollHeight,viewport:i.viewport.offsetHeight,scrollbar:{size:u.current.clientHeight,paddingStart:Vp(s.paddingTop),paddingEnd:Vp(s.paddingBottom)}})}}))}),[xY,k5]=C5(Oi),T5=d.forwardRef((e,t)=>{const{__scopeScrollArea:n,sizes:r,hasThumb:o,onThumbChange:i,onThumbPointerUp:s,onThumbPointerDown:l,onThumbPositionChange:u,onDragScroll:f,onWheelScroll:m,onResize:p,...g}=e,y=qr(Oi,n),[b,S]=d.useState(null),E=Be(t,U=>S(U)),_=d.useRef(null),x=d.useRef(""),C=y.viewport,R=r.content-r.viewport,P=Ft(m),M=Ft(u),A=sg(p,10);function D(U){if(_.current){const W=U.clientX-_.current.left,q=U.clientY-_.current.top;f({x:W,y:q})}}return d.useEffect(()=>{const U=W=>{const q=W.target;(b==null?void 0:b.contains(q))&&P(W,R)};return document.addEventListener("wheel",U,{passive:!1}),()=>document.removeEventListener("wheel",U,{passive:!1})},[C,b,R,P]),d.useEffect(M,[r,M]),fc(b,A),fc(y.content,A),d.createElement(xY,{scope:n,scrollbar:b,hasThumb:o,onThumbChange:Ft(i),onThumbPointerUp:Ft(s),onThumbPositionChange:M,onThumbPointerDown:Ft(l)},d.createElement(Pe.div,Y({},g,{ref:E,style:{position:"absolute",...g.style},onPointerDown:de(e.onPointerDown,U=>{U.button===0&&(U.target.setPointerCapture(U.pointerId),_.current=b.getBoundingClientRect(),x.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",y.viewport&&(y.viewport.style.scrollBehavior="auto"),D(U))}),onPointerMove:de(e.onPointerMove,D),onPointerUp:de(e.onPointerUp,U=>{const W=U.target;W.hasPointerCapture(U.pointerId)&&W.releasePointerCapture(U.pointerId),document.body.style.webkitUserSelect=x.current,y.viewport&&(y.viewport.style.scrollBehavior=""),_.current=null})})))}),E1="ScrollAreaThumb",bY=d.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=k5(E1,e.__scopeScrollArea);return d.createElement(Sn,{present:n||o.hasThumb},d.createElement(SY,Y({ref:t},r)))}),SY=d.forwardRef((e,t)=>{const{__scopeScrollArea:n,style:r,...o}=e,i=qr(E1,n),s=k5(E1,n),{onThumbPositionChange:l}=s,u=Be(t,p=>s.onThumbChange(p)),f=d.useRef(),m=sg(()=>{f.current&&(f.current(),f.current=void 0)},100);return d.useEffect(()=>{const p=i.viewport;if(p){const g=()=>{if(m(),!f.current){const y=$Y(p,l);f.current=y,l()}};return l(),p.addEventListener("scroll",g),()=>p.removeEventListener("scroll",g)}},[i.viewport,m,l]),d.createElement(Pe.div,Y({"data-state":s.hasThumb?"visible":"hidden"},o,{ref:u,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...r},onPointerDownCapture:de(e.onPointerDownCapture,p=>{const y=p.target.getBoundingClientRect(),b=p.clientX-y.left,S=p.clientY-y.top;s.onThumbPointerDown({x:b,y:S})}),onPointerUp:de(e.onPointerUp,s.onThumbPointerUp)}))}),P5="ScrollAreaCorner",_Y=d.forwardRef((e,t)=>{const n=qr(P5,e.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?d.createElement(EY,Y({},e,{ref:t})):null}),EY=d.forwardRef((e,t)=>{const{__scopeScrollArea:n,...r}=e,o=qr(P5,n),[i,s]=d.useState(0),[l,u]=d.useState(0),f=!!(i&&l);return fc(o.scrollbarX,()=>{var m;const p=((m=o.scrollbarX)===null||m===void 0?void 0:m.offsetHeight)||0;o.onCornerHeightChange(p),u(p)}),fc(o.scrollbarY,()=>{var m;const p=((m=o.scrollbarY)===null||m===void 0?void 0:m.offsetWidth)||0;o.onCornerWidthChange(p),s(p)}),f?d.createElement(Pe.div,Y({},r,{ref:t,style:{width:i,height:l,position:"absolute",right:o.dir==="ltr"?0:void 0,left:o.dir==="rtl"?0:void 0,bottom:0,...e.style}})):null});function Vp(e){return e?parseInt(e,10):0}function A5(e,t){const n=e/t;return isNaN(n)?0:n}function ig(e){const t=A5(e.viewport,e.content),n=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,r=(e.scrollbar.size-n)*t;return Math.max(r,18)}function CY(e,t,n,r="ltr"){const o=ig(n),i=o/2,s=t||i,l=o-s,u=n.scrollbar.paddingStart+s,f=n.scrollbar.size-n.scrollbar.paddingEnd-l,m=n.content-n.viewport,p=r==="ltr"?[0,m]:[m*-1,0];return M5([u,f],p)(e)}function y2(e,t,n="ltr"){const r=ig(t),o=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,i=t.scrollbar.size-o,s=t.content-t.viewport,l=i-r,u=n==="ltr"?[0,s]:[s*-1,0],f=fd(e,u);return M5([0,s],[0,l])(f)}function M5(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 O5(e,t){return e>0&&e{})=>{let n={left:e.scrollLeft,top:e.scrollTop},r=0;return function o(){const i={left:e.scrollLeft,top:e.scrollTop},s=n.left!==i.left,l=n.top!==i.top;(s||l)&&t(),n=i,r=window.requestAnimationFrame(o)}(),()=>window.cancelAnimationFrame(r)};function sg(e,t){const n=Ft(e),r=d.useRef(0);return d.useEffect(()=>()=>window.clearTimeout(r.current),[]),d.useCallback(()=>{window.clearTimeout(r.current),r.current=window.setTimeout(n,t)},[n,t])}function fc(e,t){const n=Ft(t);An(()=>{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 N5=hY,RY=mY,kY=_Y,ag=d.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(N5,{ref:r,className:Ce("relative overflow-hidden",e),scrollHideDelay:400,...n,children:[v.jsx(RY,{className:"h-full w-full rounded-[inherit]",children:t}),v.jsx(D5,{}),v.jsx(kY,{})]}));ag.displayName=N5.displayName;const D5=d.forwardRef(({className:e,orientation:t="vertical",...n},r)=>v.jsx($5,{ref:r,orientation:t,className:Ce("flex touch-none select-none transition-colors",t==="vertical"&&"h-full w-2.5 border-l border-l-transparent p-[1px]",t==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",e),...n,children:v.jsx(bY,{className:"relative flex-1 rounded-full bg-border"})}));D5.displayName=$5.displayName;const I5="Name",L5="Created time",F5="Modified time",w2="input",TY="output",x2={[Es.NAME]:I5,[Es.CTIME]:L5,[Es.MTIME]:F5};function PY(e){const{onPhotoClick:t,photoWidth:n}=e,[r,o]=OP(!1),[i,s]=bt(W=>[W.fileManagerState,W.updateFileManagerState]),{toast:l}=Id(),[u,f]=d.useState(0),[m,p]=d.useState(0),g=d.useRef(null),y=lV(i.searchText,300),[b,S]=d.useState(w2),[E,_]=d.useState([]),[x,C]=d.useState([]),[R,P]=d.useState(0);Zn("f",()=>{o()}),Zn("left",()=>{let W=R;R>0&&(W=R-1),P(W),t(b,x[W].name)},[R,x]),Zn("right",()=>{let W=R;R{r||p(u)},[r,u]);const M=d.useCallback(W=>{W!==null&&r&&setTimeout(()=>{W.scrollTo({top:m,left:0})},100)},[r,m]);d.useEffect(()=>{(async()=>{try{const q=await Wj(b);_(q)}catch(q){l({variant:"destructive",title:"Uh oh! Something went wrong.",description:q.message?q.message:q.toString()})}})()},[b]),d.useEffect(()=>{if(!r)return;(async()=>{try{let q=E;y&&(q=new kc(q,{keys:["name"]}).search(y).map(F=>q[F.refIndex])),q=xH.orderBy(q,i.sortBy,i.sortOrder);const X=q.map(ae=>{const V=n,F=ae.height*(V/ae.width);return{src:`${Ls}/media_thumbnail_file?tab=${b}&filename=${encodeURIComponent(ae.name)}&width=${Math.ceil(V)}&height=${Math.ceil(F)}`,height:F,width:V,name:ae.name}});C(X)}catch(q){l({variant:"destructive",title:"Uh oh! Something went wrong.",description:q.message?q.message:q.toString()})}})()},[E,y,i,n,r]);const A=W=>{f(W.currentTarget.scrollTop)},D=({index:W})=>{o(),P(W),t(b,x[W].name)},U=()=>v.jsxs("div",{className:"flex justify-start items-center gap-[12px]",children:[v.jsx("div",{children:`Images (${x.length})`}),v.jsxs("div",{className:"flex",children:[v.jsx(yn,{tooltip:"Rows layout",onClick:()=>{s({layout:"rows"})},children:v.jsx(pz,{className:i.layout!=="rows"?"opacity-50":""})}),v.jsx(yn,{tooltip:"Grid layout",onClick:()=>{s({layout:"masonry"})},children:v.jsx(fz,{className:i.layout!=="masonry"?"opacity-50":""})})]})]});return v.jsxs(Jm,{open:r,onOpenChange:o,children:[v.jsx(fP,{asChild:!0,children:v.jsx(yn,{tooltip:"File Manager",children:v.jsx(eV,{})})}),v.jsxs(Hd,{className:"h-4/5 max-w-6xl",children:[v.jsx(Kd,{children:U()}),v.jsxs("div",{className:"flex justify-between gap-8 items-center",children:[v.jsxs("div",{className:"flex relative justify-start items-center",children:[v.jsx(lz,{className:"absolute left-[8px]"}),v.jsx(Ld,{ref:g,value:i.searchText,className:"w-[250px] pl-[30px]",tabIndex:-1,onInput:W=>{W.preventDefault(),W.stopPropagation();const q=W.target;s({searchText:q.value})},placeholder:"Search by file name"})]}),v.jsx(a5,{defaultValue:b,onValueChange:W=>S(W),children:v.jsxs(jx,{"aria-label":"Manage your account",children:[v.jsx(pa,{value:w2,children:"Image Directory"}),v.jsx(pa,{value:TY,children:"Output Directory"})]})}),v.jsx("div",{className:"flex gap-2",children:v.jsxs("div",{className:"flex gap-1",children:[v.jsxs(Uo,{value:x2[i.sortBy],onValueChange:W=>{switch(W){case I5:s({sortBy:Es.NAME});break;case L5:s({sortBy:Es.CTIME});break;case F5:s({sortBy:Es.MTIME});break}},children:[v.jsx(go,{className:"w-[140px]",children:v.jsx(Vo,{})}),v.jsx(vo,{children:Object.values(x2).map(W=>v.jsx(yo,{value:W,children:W},W))})]}),i.sortOrder===Ou.DESCENDING?v.jsx(yn,{tooltip:"Descending Order",onClick:()=>{s({sortOrder:Ou.ASCENDING})},children:v.jsx(iK,{})}):v.jsx(yn,{tooltip:"Ascending Order",onClick:()=>{s({sortOrder:Ou.DESCENDING})},children:v.jsx(lK,{})})]})})]}),v.jsx(ag,{className:"w-full h-full rounded-md",onScroll:A,ref:M,children:v.jsx(nK,{layout:i.layout,photos:x,spacing:12,padding:0,onClick:D})})]})]})}var Yd=e=>e.type==="checkbox",$l=e=>e instanceof Date,Fn=e=>e==null;const j5=e=>typeof e=="object";var sn=e=>!Fn(e)&&!Array.isArray(e)&&j5(e)&&!$l(e),z5=e=>sn(e)&&e.target?Yd(e.target)?e.target.checked:e.target.value:e,AY=e=>e.substring(0,e.search(/\.\d+(\.|$)/))||e,B5=(e,t)=>e.has(AY(t)),MY=e=>{const t=e.constructor&&e.constructor.prototype;return sn(t)&&t.hasOwnProperty("isPrototypeOf")},Wx=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function so(e){let t;const n=Array.isArray(e);if(e instanceof Date)t=new Date(e);else if(e instanceof Set)t=new Set(e);else if(!(Wx&&(e instanceof Blob||e instanceof FileList))&&(n||sn(e)))if(t=n?[]:{},!n&&!MY(e))t=e;else for(const r in e)e.hasOwnProperty(r)&&(t[r]=so(e[r]));else return e;return t}var Xd=e=>Array.isArray(e)?e.filter(Boolean):[],Ht=e=>e===void 0,ve=(e,t,n)=>{if(!t||!sn(e))return n;const r=Xd(t.split(/[,[\].]+?/)).reduce((o,i)=>Fn(o)?o:o[i],e);return Ht(r)||r===e?Ht(e[t])?n:e[t]:r},Fo=e=>typeof e=="boolean";const Wp={BLUR:"blur",FOCUS_OUT:"focusout",CHANGE:"change"},mo={onBlur:"onBlur",onChange:"onChange",onSubmit:"onSubmit",onTouched:"onTouched",all:"all"},ui={max:"max",min:"min",maxLength:"maxLength",minLength:"minLength",pattern:"pattern",required:"required",validate:"validate"},U5=Fe.createContext(null),lg=()=>Fe.useContext(U5),OY=e=>{const{children:t,...n}=e;return Fe.createElement(U5.Provider,{value:n},t)};var V5=(e,t,n,r=!0)=>{const o={defaultValues:t._defaultValues};for(const i in e)Object.defineProperty(o,i,{get:()=>{const s=i;return t._proxyFormState[s]!==mo.all&&(t._proxyFormState[s]=!r||mo.all),n&&(n[s]=!0),e[s]}});return o},Fr=e=>sn(e)&&!Object.keys(e).length,W5=(e,t,n,r)=>{n(e);const{name:o,...i}=e;return Fr(i)||Object.keys(i).length>=Object.keys(t).length||Object.keys(i).find(s=>t[s]===(!r||mo.all))},ep=e=>Array.isArray(e)?e:[e],H5=(e,t,n)=>!e||!t||e===t||ep(e).some(r=>r&&(n?r===t:r.startsWith(t)||t.startsWith(r)));function Hx(e){const t=Fe.useRef(e);t.current=e,Fe.useEffect(()=>{const n=!e.disabled&&t.current.subject&&t.current.subject.subscribe({next:t.current.next});return()=>{n&&n.unsubscribe()}},[e.disabled])}function NY(e){const t=lg(),{control:n=t.control,disabled:r,name:o,exact:i}=e||{},[s,l]=Fe.useState(n._formState),u=Fe.useRef(!0),f=Fe.useRef({isDirty:!1,isLoading:!1,dirtyFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1}),m=Fe.useRef(o);return m.current=o,Hx({disabled:r,next:p=>u.current&&H5(m.current,p.name,i)&&W5(p,f.current,n._updateFormState)&&l({...n._formState,...p}),subject:n._subjects.state}),Fe.useEffect(()=>(u.current=!0,f.current.isValid&&n._updateValid(!0),()=>{u.current=!1}),[n]),V5(s,n,f.current,!1)}var Wo=e=>typeof e=="string",K5=(e,t,n,r,o)=>Wo(e)?(r&&t.watch.add(e),ve(n,e,o)):Array.isArray(e)?e.map(i=>(r&&t.watch.add(i),ve(n,i))):(r&&(t.watchAll=!0),n);function DY(e){const t=lg(),{control:n=t.control,name:r,defaultValue:o,disabled:i,exact:s}=e||{},l=Fe.useRef(r);l.current=r,Hx({disabled:i,subject:n._subjects.values,next:m=>{H5(l.current,m.name,s)&&f(so(K5(l.current,n._names,m.values||n._formValues,!1,o)))}});const[u,f]=Fe.useState(n._getWatch(r,o));return Fe.useEffect(()=>n._removeUnmounted()),u}var Kx=e=>/^\w*$/.test(e),G5=e=>Xd(e.replace(/["|']|\]/g,"").split(/\.|\[/));function wt(e,t,n){let r=-1;const o=Kx(t)?[t]:G5(t),i=o.length,s=i-1;for(;++r{const m=o._options.shouldUnregister||i,p=(g,y)=>{const b=ve(o._fields,g);b&&(b._f.mount=y)};if(p(n,!0),m){const g=so(ve(o._options.defaultValues,n));wt(o._defaultValues,n,g),Ht(ve(o._formValues,n))&&wt(o._formValues,n,g)}return()=>{(s?m&&!o._state.action:m)?o.unregister(n):p(n,!1)}},[n,o,s,i]),Fe.useEffect(()=>{ve(o._fields,n)&&o._updateDisabledField({disabled:r,fields:o._fields,name:n,value:ve(o._fields,n)._f.value})},[r,n,o]),{field:{name:n,value:l,...Fo(r)||Fo(u.disabled)?{disabled:u.disabled||r}:{},onChange:Fe.useCallback(m=>f.current.onChange({target:{value:z5(m),name:n},type:Wp.CHANGE}),[n]),onBlur:Fe.useCallback(()=>f.current.onBlur({target:{value:ve(o._formValues,n),name:n},type:Wp.BLUR}),[n,o]),ref:m=>{const p=ve(o._fields,n);p&&m&&(p._f.ref={focus:()=>m.focus(),select:()=>m.select(),setCustomValidity:g=>m.setCustomValidity(g),reportValidity:()=>m.reportValidity()})}},formState:u,fieldState:Object.defineProperties({},{invalid:{enumerable:!0,get:()=>!!ve(u.errors,n)},isDirty:{enumerable:!0,get:()=>!!ve(u.dirtyFields,n)},isTouched:{enumerable:!0,get:()=>!!ve(u.touchedFields,n)},error:{enumerable:!0,get:()=>ve(u.errors,n)}})}}const LY=e=>e.render(IY(e));var Y5=(e,t,n,r,o)=>t?{...n[e],types:{...n[e]&&n[e].types?n[e].types:{},[r]:o||!0}}:{},b2=e=>({isOnSubmit:!e||e===mo.onSubmit,isOnBlur:e===mo.onBlur,isOnChange:e===mo.onChange,isOnAll:e===mo.all,isOnTouch:e===mo.onTouched}),S2=(e,t,n)=>!n&&(t.watchAll||t.watch.has(e)||[...t.watch].some(r=>e.startsWith(r)&&/^\.\w+/.test(e.slice(r.length))));const tp=(e,t,n,r)=>{for(const o of n||Object.keys(e)){const i=ve(e,o);if(i){const{_f:s,...l}=i;if(s){if(s.refs&&s.refs[0]&&t(s.refs[0],o)&&!r)break;if(s.ref&&t(s.ref,s.name)&&!r)break}else sn(l)&&tp(l,t)}}};var FY=(e,t,n)=>{const r=Xd(ve(e,n));return wt(r,"root",t[n]),wt(e,n,r),e},Gx=e=>e.type==="file",ms=e=>typeof e=="function",Hp=e=>{if(!Wx)return!1;const t=e?e.ownerDocument:0;return e instanceof(t&&t.defaultView?t.defaultView.HTMLElement:HTMLElement)},np=e=>Wo(e),Yx=e=>e.type==="radio",Kp=e=>e instanceof RegExp;const _2={value:!1,isValid:!1},E2={value:!0,isValid:!0};var X5=e=>{if(Array.isArray(e)){if(e.length>1){const t=e.filter(n=>n&&n.checked&&!n.disabled).map(n=>n.value);return{value:t,isValid:!!t.length}}return e[0].checked&&!e[0].disabled?e[0].attributes&&!Ht(e[0].attributes.value)?Ht(e[0].value)||e[0].value===""?E2:{value:e[0].value,isValid:!0}:E2:_2}return _2};const C2={isValid:!1,value:null};var Z5=e=>Array.isArray(e)?e.reduce((t,n)=>n&&n.checked&&!n.disabled?{isValid:!0,value:n.value}:t,C2):C2;function $2(e,t,n="validate"){if(np(e)||Array.isArray(e)&&e.every(np)||Fo(e)&&!e)return{type:n,message:np(e)?e:"",ref:t}}var sl=e=>sn(e)&&!Kp(e)?e:{value:e,message:""},R2=async(e,t,n,r,o)=>{const{ref:i,refs:s,required:l,maxLength:u,minLength:f,min:m,max:p,pattern:g,validate:y,name:b,valueAsNumber:S,mount:E,disabled:_}=e._f,x=ve(t,b);if(!E||_)return{};const C=s?s[0]:i,R=X=>{r&&C.reportValidity&&(C.setCustomValidity(Fo(X)?"":X||""),C.reportValidity())},P={},M=Yx(i),A=Yd(i),D=M||A,U=(S||Gx(i))&&Ht(i.value)&&Ht(x)||Hp(i)&&i.value===""||x===""||Array.isArray(x)&&!x.length,W=Y5.bind(null,b,n,P),q=(X,ae,V,F=ui.maxLength,N=ui.minLength)=>{const ie=X?ae:V;P[b]={type:X?F:N,message:ie,ref:i,...W(X?F:N,ie)}};if(o?!Array.isArray(x)||!x.length:l&&(!D&&(U||Fn(x))||Fo(x)&&!x||A&&!X5(s).isValid||M&&!Z5(s).isValid)){const{value:X,message:ae}=np(l)?{value:!!l,message:l}:sl(l);if(X&&(P[b]={type:ui.required,message:ae,ref:C,...W(ui.required,ae)},!n))return R(ae),P}if(!U&&(!Fn(m)||!Fn(p))){let X,ae;const V=sl(p),F=sl(m);if(!Fn(x)&&!isNaN(x)){const N=i.valueAsNumber||x&&+x;Fn(V.value)||(X=N>V.value),Fn(F.value)||(ae=Nnew Date(new Date().toDateString()+" "+H),K=i.type=="time",Z=i.type=="week";Wo(V.value)&&x&&(X=K?ie(x)>ie(V.value):Z?x>V.value:N>new Date(V.value)),Wo(F.value)&&x&&(ae=K?ie(x)+X.value,F=!Fn(ae.value)&&x.length<+ae.value;if((V||F)&&(q(V,X.message,ae.message),!n))return R(P[b].message),P}if(g&&!U&&Wo(x)){const{value:X,message:ae}=sl(g);if(Kp(X)&&!x.match(X)&&(P[b]={type:ui.pattern,message:ae,ref:i,...W(ui.pattern,ae)},!n))return R(ae),P}if(y){if(ms(y)){const X=await y(x,t),ae=$2(X,C);if(ae&&(P[b]={...ae,...W(ui.validate,ae.message)},!n))return R(ae.message),P}else if(sn(y)){let X={};for(const ae in y){if(!Fr(X)&&!n)break;const V=$2(await y[ae](x,t),C,ae);V&&(X={...V,...W(ae,V.message)},R(V.message),n&&(P[b]=X))}if(!Fr(X)&&(P[b]={ref:C,...X},!n))return P}}return R(!0),P};function jY(e,t){const n=t.slice(0,-1).length;let r=0;for(;r{for(const i of e)i.next&&i.next(o)},subscribe:o=>(e.push(o),{unsubscribe:()=>{e=e.filter(i=>i!==o)}}),unsubscribe:()=>{e=[]}}}var Gp=e=>Fn(e)||!j5(e);function ma(e,t){if(Gp(e)||Gp(t))return e===t;if($l(e)&&$l(t))return e.getTime()===t.getTime();const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(const o of n){const i=e[o];if(!r.includes(o))return!1;if(o!=="ref"){const s=t[o];if($l(i)&&$l(s)||sn(i)&&sn(s)||Array.isArray(i)&&Array.isArray(s)?!ma(i,s):i!==s)return!1}}return!0}var q5=e=>e.type==="select-multiple",BY=e=>Yx(e)||Yd(e),N0=e=>Hp(e)&&e.isConnected,Q5=e=>{for(const t in e)if(ms(e[t]))return!0;return!1};function Yp(e,t={}){const n=Array.isArray(e);if(sn(e)||n)for(const r in e)Array.isArray(e[r])||sn(e[r])&&!Q5(e[r])?(t[r]=Array.isArray(e[r])?[]:{},Yp(e[r],t[r])):Fn(e[r])||(t[r]=!0);return t}function J5(e,t,n){const r=Array.isArray(e);if(sn(e)||r)for(const o in e)Array.isArray(e[o])||sn(e[o])&&!Q5(e[o])?Ht(t)||Gp(n[o])?n[o]=Array.isArray(e[o])?Yp(e[o],[]):{...Yp(e[o])}:J5(e[o],Fn(t)?{}:t[o],n[o]):n[o]=!ma(e[o],t[o]);return n}var D0=(e,t)=>J5(e,t,Yp(t)),e3=(e,{valueAsNumber:t,valueAsDate:n,setValueAs:r})=>Ht(e)?e:t?e===""?NaN:e&&+e:n&&Wo(e)?new Date(e):r?r(e):e;function I0(e){const t=e.ref;if(!(e.refs?e.refs.every(n=>n.disabled):t.disabled))return Gx(t)?t.files:Yx(t)?Z5(e.refs).value:q5(t)?[...t.selectedOptions].map(({value:n})=>n):Yd(t)?X5(e.refs).value:e3(Ht(t.value)?e.ref.value:t.value,e)}var UY=(e,t,n,r)=>{const o={};for(const i of e){const s=ve(t,i);s&&wt(o,i,s._f)}return{criteriaMode:n,names:[...e],fields:o,shouldUseNativeValidation:r}},du=e=>Ht(e)?e:Kp(e)?e.source:sn(e)?Kp(e.value)?e.value.source:e.value:e,VY=e=>e.mount&&(e.required||e.min||e.max||e.maxLength||e.minLength||e.pattern||e.validate);function k2(e,t,n){const r=ve(e,n);if(r||Kx(n))return{error:r,name:n};const o=n.split(".");for(;o.length;){const i=o.join("."),s=ve(t,i),l=ve(e,i);if(s&&!Array.isArray(s)&&n!==i)return{name:n};if(l&&l.type)return{name:i,error:l};o.pop()}return{name:n}}var WY=(e,t,n,r,o)=>o.isOnAll?!1:!n&&o.isOnTouch?!(t||e):(n?r.isOnBlur:o.isOnBlur)?!e:(n?r.isOnChange:o.isOnChange)?e:!0,HY=(e,t)=>!Xd(ve(e,t)).length&&pn(e,t);const KY={mode:mo.onSubmit,reValidateMode:mo.onChange,shouldFocusError:!0};function GY(e={},t){let n={...KY,...e},r={submitCount:0,isDirty:!1,isLoading:ms(n.defaultValues),isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},errors:{},disabled:!1},o={},i=sn(n.defaultValues)||sn(n.values)?so(n.defaultValues||n.values)||{}:{},s=n.shouldUnregister?{}:so(i),l={action:!1,mount:!1,watch:!1},u={mount:new Set,unMount:new Set,array:new Set,watch:new Set},f,m=0;const p={isDirty:!1,dirtyFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1},g={values:O0(),array:O0(),state:O0()},y=e.resetOptions&&e.resetOptions.keepDirtyValues,b=b2(n.mode),S=b2(n.reValidateMode),E=n.criteriaMode===mo.all,_=L=>Q=>{clearTimeout(m),m=setTimeout(L,Q)},x=async L=>{if(p.isValid||L){const Q=n.resolver?Fr((await U()).errors):await q(o,!0);Q!==r.isValid&&g.state.next({isValid:Q})}},C=L=>p.isValidating&&g.state.next({isValidating:L}),R=(L,Q=[],J,we,me=!0,fe=!0)=>{if(we&&J){if(l.action=!0,fe&&Array.isArray(ve(o,L))){const Re=J(ve(o,L),we.argA,we.argB);me&&wt(o,L,Re)}if(fe&&Array.isArray(ve(r.errors,L))){const Re=J(ve(r.errors,L),we.argA,we.argB);me&&wt(r.errors,L,Re),HY(r.errors,L)}if(p.touchedFields&&fe&&Array.isArray(ve(r.touchedFields,L))){const Re=J(ve(r.touchedFields,L),we.argA,we.argB);me&&wt(r.touchedFields,L,Re)}p.dirtyFields&&(r.dirtyFields=D0(i,s)),g.state.next({name:L,isDirty:ae(L,Q),dirtyFields:r.dirtyFields,errors:r.errors,isValid:r.isValid})}else wt(s,L,Q)},P=(L,Q)=>{wt(r.errors,L,Q),g.state.next({errors:r.errors})},M=(L,Q,J,we)=>{const me=ve(o,L);if(me){const fe=ve(s,L,Ht(J)?ve(i,L):J);Ht(fe)||we&&we.defaultChecked||Q?wt(s,L,Q?fe:I0(me._f)):N(L,fe),l.mount&&x()}},A=(L,Q,J,we,me)=>{let fe=!1,Re=!1;const ft={name:L};if(!J||we){p.isDirty&&(Re=r.isDirty,r.isDirty=ft.isDirty=ae(),fe=Re!==ft.isDirty);const ht=ma(ve(i,L),Q);Re=ve(r.dirtyFields,L),ht?pn(r.dirtyFields,L):wt(r.dirtyFields,L,!0),ft.dirtyFields=r.dirtyFields,fe=fe||p.dirtyFields&&Re!==!ht}if(J){const ht=ve(r.touchedFields,L);ht||(wt(r.touchedFields,L,J),ft.touchedFields=r.touchedFields,fe=fe||p.touchedFields&&ht!==J)}return fe&&me&&g.state.next(ft),fe?ft:{}},D=(L,Q,J,we)=>{const me=ve(r.errors,L),fe=p.isValid&&Fo(Q)&&r.isValid!==Q;if(e.delayError&&J?(f=_(()=>P(L,J)),f(e.delayError)):(clearTimeout(m),f=null,J?wt(r.errors,L,J):pn(r.errors,L)),(J?!ma(me,J):me)||!Fr(we)||fe){const Re={...we,...fe&&Fo(Q)?{isValid:Q}:{},errors:r.errors,name:L};r={...r,...Re},g.state.next(Re)}C(!1)},U=async L=>n.resolver(s,n.context,UY(L||u.mount,o,n.criteriaMode,n.shouldUseNativeValidation)),W=async L=>{const{errors:Q}=await U(L);if(L)for(const J of L){const we=ve(Q,J);we?wt(r.errors,J,we):pn(r.errors,J)}else r.errors=Q;return Q},q=async(L,Q,J={valid:!0})=>{for(const we in L){const me=L[we];if(me){const{_f:fe,...Re}=me;if(fe){const ft=u.array.has(fe.name),ht=await R2(me,s,E,n.shouldUseNativeValidation&&!Q,ft);if(ht[fe.name]&&(J.valid=!1,Q))break;!Q&&(ve(ht,fe.name)?ft?FY(r.errors,ht,fe.name):wt(r.errors,fe.name,ht[fe.name]):pn(r.errors,fe.name))}Re&&await q(Re,Q,J)}}return J.valid},X=()=>{for(const L of u.unMount){const Q=ve(o,L);Q&&(Q._f.refs?Q._f.refs.every(J=>!N0(J)):!N0(Q._f.ref))&&he(L)}u.unMount=new Set},ae=(L,Q)=>(L&&Q&&wt(s,L,Q),!ma(ce(),i)),V=(L,Q,J)=>K5(L,u,{...l.mount?s:Ht(Q)?i:Wo(L)?{[L]:Q}:Q},J,Q),F=L=>Xd(ve(l.mount?s:i,L,e.shouldUnregister?ve(i,L,[]):[])),N=(L,Q,J={})=>{const we=ve(o,L);let me=Q;if(we){const fe=we._f;fe&&(!fe.disabled&&wt(s,L,e3(Q,fe)),me=Hp(fe.ref)&&Fn(Q)?"":Q,q5(fe.ref)?[...fe.ref.options].forEach(Re=>Re.selected=me.includes(Re.value)):fe.refs?Yd(fe.ref)?fe.refs.length>1?fe.refs.forEach(Re=>(!Re.defaultChecked||!Re.disabled)&&(Re.checked=Array.isArray(me)?!!me.find(ft=>ft===Re.value):me===Re.value)):fe.refs[0]&&(fe.refs[0].checked=!!me):fe.refs.forEach(Re=>Re.checked=Re.value===me):Gx(fe.ref)?fe.ref.value="":(fe.ref.value=me,fe.ref.type||g.values.next({name:L,values:{...s}})))}(J.shouldDirty||J.shouldTouch)&&A(L,me,J.shouldTouch,J.shouldDirty,!0),J.shouldValidate&&se(L)},ie=(L,Q,J)=>{for(const we in Q){const me=Q[we],fe=`${L}.${we}`,Re=ve(o,fe);(u.array.has(L)||!Gp(me)||Re&&!Re._f)&&!$l(me)?ie(fe,me,J):N(fe,me,J)}},K=(L,Q,J={})=>{const we=ve(o,L),me=u.array.has(L),fe=so(Q);wt(s,L,fe),me?(g.array.next({name:L,values:{...s}}),(p.isDirty||p.dirtyFields)&&J.shouldDirty&&g.state.next({name:L,dirtyFields:D0(i,s),isDirty:ae(L,fe)})):we&&!we._f&&!Fn(fe)?ie(L,fe,J):N(L,fe,J),S2(L,u)&&g.state.next({...r}),g.values.next({name:L,values:{...s}}),!l.mount&&t()},Z=async L=>{const Q=L.target;let J=Q.name,we=!0;const me=ve(o,J),fe=()=>Q.type?I0(me._f):z5(L),Re=ft=>{we=Number.isNaN(ft)||ft===ve(s,J,ft)};if(me){let ft,ht;const _n=fe(),Cr=L.type===Wp.BLUR||L.type===Wp.FOCUS_OUT,Ni=!VY(me._f)&&!n.resolver&&!ve(r.errors,J)&&!me._f.deps||WY(Cr,ve(r.touchedFields,J),r.isSubmitted,S,b),Co=S2(J,u,Cr);wt(s,J,_n),Cr?(me._f.onBlur&&me._f.onBlur(L),f&&f(0)):me._f.onChange&&me._f.onChange(L);const Vn=A(J,_n,Cr,!1),Ba=!Fr(Vn)||Co;if(!Cr&&g.values.next({name:J,type:L.type,values:{...s}}),Ni)return p.isValid&&x(),Ba&&g.state.next({name:J,...Co?{}:Vn});if(!Cr&&Co&&g.state.next({...r}),C(!0),n.resolver){const{errors:Di}=await U([J]);if(Re(_n),we){const Ws=k2(r.errors,o,J),Ii=k2(Di,o,Ws.name||J);ft=Ii.error,J=Ii.name,ht=Fr(Di)}}else ft=(await R2(me,s,E,n.shouldUseNativeValidation))[J],Re(_n),we&&(ft?ht=!1:p.isValid&&(ht=await q(o,!0)));we&&(me._f.deps&&se(me._f.deps),D(J,ht,ft,Vn))}},H=(L,Q)=>{if(ve(r.errors,Q)&&L.focus)return L.focus(),1},se=async(L,Q={})=>{let J,we;const me=ep(L);if(C(!0),n.resolver){const fe=await W(Ht(L)?L:me);J=Fr(fe),we=L?!me.some(Re=>ve(fe,Re)):J}else L?(we=(await Promise.all(me.map(async fe=>{const Re=ve(o,fe);return await q(Re&&Re._f?{[fe]:Re}:Re)}))).every(Boolean),!(!we&&!r.isValid)&&x()):we=J=await q(o);return g.state.next({...!Wo(L)||p.isValid&&J!==r.isValid?{}:{name:L},...n.resolver||!L?{isValid:J}:{},errors:r.errors,isValidating:!1}),Q.shouldFocus&&!we&&tp(o,H,L?me:u.mount),we},ce=L=>{const Q={...i,...l.mount?s:{}};return Ht(L)?Q:Wo(L)?ve(Q,L):L.map(J=>ve(Q,J))},Ve=(L,Q)=>({invalid:!!ve((Q||r).errors,L),isDirty:!!ve((Q||r).dirtyFields,L),isTouched:!!ve((Q||r).touchedFields,L),error:ve((Q||r).errors,L)}),Ue=L=>{L&&ep(L).forEach(Q=>pn(r.errors,Q)),g.state.next({errors:L?r.errors:{}})},We=(L,Q,J)=>{const we=(ve(o,L,{_f:{}})._f||{}).ref;wt(r.errors,L,{...Q,ref:we}),g.state.next({name:L,errors:r.errors,isValid:!1}),J&&J.shouldFocus&&we&&we.focus&&we.focus()},Oe=(L,Q)=>ms(L)?g.values.subscribe({next:J=>L(V(void 0,Q),J)}):V(L,Q,!0),he=(L,Q={})=>{for(const J of L?ep(L):u.mount)u.mount.delete(J),u.array.delete(J),Q.keepValue||(pn(o,J),pn(s,J)),!Q.keepError&&pn(r.errors,J),!Q.keepDirty&&pn(r.dirtyFields,J),!Q.keepTouched&&pn(r.touchedFields,J),!n.shouldUnregister&&!Q.keepDefaultValue&&pn(i,J);g.values.next({values:{...s}}),g.state.next({...r,...Q.keepDirty?{isDirty:ae()}:{}}),!Q.keepIsValid&&x()},xe=({disabled:L,name:Q,field:J,fields:we,value:me})=>{if(Fo(L)){const fe=L?void 0:Ht(me)?I0(J?J._f:ve(we,Q)._f):me;wt(s,Q,fe),A(Q,fe,!1,!1,!0)}},$e=(L,Q={})=>{let J=ve(o,L);const we=Fo(Q.disabled);return wt(o,L,{...J||{},_f:{...J&&J._f?J._f:{ref:{name:L}},name:L,mount:!0,...Q}}),u.mount.add(L),J?xe({field:J,disabled:Q.disabled,name:L}):M(L,!0,Q.value),{...we?{disabled:Q.disabled}:{},...n.progressive?{required:!!Q.required,min:du(Q.min),max:du(Q.max),minLength:du(Q.minLength),maxLength:du(Q.maxLength),pattern:du(Q.pattern)}:{},name:L,onChange:Z,onBlur:Z,ref:me=>{if(me){$e(L,Q),J=ve(o,L);const fe=Ht(me.value)&&me.querySelectorAll&&me.querySelectorAll("input,select,textarea")[0]||me,Re=BY(fe),ft=J._f.refs||[];if(Re?ft.find(ht=>ht===fe):fe===J._f.ref)return;wt(o,L,{_f:{...J._f,...Re?{refs:[...ft.filter(N0),fe,...Array.isArray(ve(i,L))?[{}]:[]],ref:{type:fe.type,name:L}}:{ref:fe}}}),M(L,!1,void 0,fe)}else J=ve(o,L,{}),J._f&&(J._f.mount=!1),(n.shouldUnregister||Q.shouldUnregister)&&!(B5(u.array,L)&&l.action)&&u.unMount.add(L)}}},Ae=()=>n.shouldFocusError&&tp(o,H,u.mount),Me=L=>{Fo(L)&&(g.state.next({disabled:L}),tp(o,Q=>{Q.disabled=L},0,!1))},je=(L,Q)=>async J=>{J&&(J.preventDefault&&J.preventDefault(),J.persist&&J.persist());let we=so(s);if(g.state.next({isSubmitting:!0}),n.resolver){const{errors:me,values:fe}=await U();r.errors=me,we=fe}else await q(o);pn(r.errors,"root"),Fr(r.errors)?(g.state.next({errors:{}}),await L(we,J)):(Q&&await Q({...r.errors},J),Ae(),setTimeout(Ae)),g.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:Fr(r.errors),submitCount:r.submitCount+1,errors:r.errors})},Mt=(L,Q={})=>{ve(o,L)&&(Ht(Q.defaultValue)?K(L,ve(i,L)):(K(L,Q.defaultValue),wt(i,L,Q.defaultValue)),Q.keepTouched||pn(r.touchedFields,L),Q.keepDirty||(pn(r.dirtyFields,L),r.isDirty=Q.defaultValue?ae(L,ve(i,L)):ae()),Q.keepError||(pn(r.errors,L),p.isValid&&x()),g.state.next({...r}))},ct=(L,Q={})=>{const J=L?so(L):i,we=so(J),me=L&&!Fr(L)?we:i;if(Q.keepDefaultValues||(i=J),!Q.keepValues){if(Q.keepDirtyValues||y)for(const fe of u.mount)ve(r.dirtyFields,fe)?wt(me,fe,ve(s,fe)):K(fe,ve(me,fe));else{if(Wx&&Ht(L))for(const fe of u.mount){const Re=ve(o,fe);if(Re&&Re._f){const ft=Array.isArray(Re._f.refs)?Re._f.refs[0]:Re._f.ref;if(Hp(ft)){const ht=ft.closest("form");if(ht){ht.reset();break}}}}o={}}s=e.shouldUnregister?Q.keepDefaultValues?so(i):{}:so(me),g.array.next({values:{...me}}),g.values.next({values:{...me}})}u={mount:new Set,unMount:new Set,array:new Set,watch:new Set,watchAll:!1,focus:""},!l.mount&&t(),l.mount=!p.isValid||!!Q.keepIsValid,l.watch=!!e.shouldUnregister,g.state.next({submitCount:Q.keepSubmitCount?r.submitCount:0,isDirty:Q.keepDirty?r.isDirty:!!(Q.keepDefaultValues&&!ma(L,i)),isSubmitted:Q.keepIsSubmitted?r.isSubmitted:!1,dirtyFields:Q.keepDirtyValues?r.dirtyFields:Q.keepDefaultValues&&L?D0(i,L):{},touchedFields:Q.keepTouched?r.touchedFields:{},errors:Q.keepErrors?r.errors:{},isSubmitSuccessful:Q.keepIsSubmitSuccessful?r.isSubmitSuccessful:!1,isSubmitting:!1})},Kt=(L,Q)=>ct(ms(L)?L(s):L,Q);return{control:{register:$e,unregister:he,getFieldState:Ve,handleSubmit:je,setError:We,_executeSchema:U,_getWatch:V,_getDirty:ae,_updateValid:x,_removeUnmounted:X,_updateFieldArray:R,_updateDisabledField:xe,_getFieldArray:F,_reset:ct,_resetDefaultValues:()=>ms(n.defaultValues)&&n.defaultValues().then(L=>{Kt(L,n.resetOptions),g.state.next({isLoading:!1})}),_updateFormState:L=>{r={...r,...L}},_disableForm:Me,_subjects:g,_proxyFormState:p,get _fields(){return o},get _formValues(){return s},get _state(){return l},set _state(L){l=L},get _defaultValues(){return i},get _names(){return u},set _names(L){u=L},get _formState(){return r},set _formState(L){r=L},get _options(){return n},set _options(L){n={...n,...L}}},trigger:se,register:$e,handleSubmit:je,watch:Oe,setValue:K,getValues:ce,reset:Kt,resetField:Mt,clearErrors:Ue,unregister:he,setError:We,setFocus:(L,Q={})=>{const J=ve(o,L),we=J&&J._f;if(we){const me=we.refs?we.refs[0]:we.ref;me.focus&&(me.focus(),Q.shouldSelect&&me.select())}},getFieldState:Ve}}function YY(e={}){const t=Fe.useRef(),n=Fe.useRef(),[r,o]=Fe.useState({isDirty:!1,isValidating:!1,isLoading:ms(e.defaultValues),isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,submitCount:0,dirtyFields:{},touchedFields:{},errors:{},disabled:!1,defaultValues:ms(e.defaultValues)?void 0:e.defaultValues});t.current||(t.current={...GY(e,()=>o(s=>({...s}))),formState:r});const i=t.current.control;return i._options=e,Hx({subject:i._subjects.state,next:s=>{W5(s,i._proxyFormState,i._updateFormState,!0)&&o({...i._formState})}}),Fe.useEffect(()=>i._disableForm(e.disabled),[i,e.disabled]),Fe.useEffect(()=>{if(i._proxyFormState.isDirty){const s=i._getDirty();s!==r.isDirty&&i._subjects.state.next({isDirty:s})}},[i,r.isDirty]),Fe.useEffect(()=>{e.values&&!ma(e.values,n.current)?(i._reset(e.values,i._options.resetOptions),n.current=e.values):i._resetDefaultValues()},[e.values,i]),Fe.useEffect(()=>{i._state.mount||(i._updateValid(),i._state.mount=!0),i._state.watch&&(i._state.watch=!1,i._subjects.state.next({...i._formState})),i._removeUnmounted()}),t.current.formState=V5(r,i),t.current}var T2=function(e,t,n){if(e&&"reportValidity"in e){var r=ve(n,t);e.setCustomValidity(r&&r.message||""),e.reportValidity()}},t3=function(e,t){var n=function(o){var i=t.fields[o];i&&i.ref&&"reportValidity"in i.ref?T2(i.ref,o,e):i.refs&&i.refs.forEach(function(s){return T2(s,o,e)})};for(var r in t.fields)n(r)},XY=function(e,t){t.shouldUseNativeValidation&&t3(e,t);var n={};for(var r in e){var o=ve(t.fields,r),i=Object.assign(e[r]||{},{ref:o&&o.ref});if(qY(t.names||Object.keys(e),r)){var s=Object.assign({},ZY(ve(n,r)));wt(s,"root",i),wt(n,r,s)}else wt(n,r,i)}return n},ZY=function(e){return Array.isArray(e)?e.filter(Boolean):[]},qY=function(e,t){return e.some(function(n){return n.startsWith(t+".")})},QY=function(e,t){for(var n={};e.length;){var r=e[0],o=r.code,i=r.message,s=r.path.join(".");if(!n[s])if("unionErrors"in r){var l=r.unionErrors[0].errors[0];n[s]={message:l.message,type:l.code}}else n[s]={message:i,type:o};if("unionErrors"in r&&r.unionErrors.forEach(function(m){return m.errors.forEach(function(p){return e.push(p)})}),t){var u=n[s].types,f=u&&u[r.code];n[s]=Y5(s,t,n,o,f?[].concat(f,r.message):r.message)}e.shift()}return n},JY=function(e,t,n){return n===void 0&&(n={}),function(r,o,i){try{return Promise.resolve(function(s,l){try{var u=Promise.resolve(e[n.mode==="sync"?"parse":"parseAsync"](r,t)).then(function(f){return i.shouldUseNativeValidation&&t3({},i),{errors:{},values:n.raw?r:f}})}catch(f){return l(f)}return u&&u.then?u.then(void 0,l):u}(0,function(s){if(function(l){return l.errors!=null}(s))return{values:{},errors:XY(QY(s.errors,!i.shouldUseNativeValidation&&i.criteriaMode==="all"),i)};throw s}))}catch(s){return Promise.reject(s)}}},mt;(function(e){e.assertEqual=o=>o;function t(o){}e.assertIs=t;function n(o){throw new Error}e.assertNever=n,e.arrayToEnum=o=>{const i={};for(const s of o)i[s]=s;return i},e.getValidEnumValues=o=>{const i=e.objectKeys(o).filter(l=>typeof o[o[l]]!="number"),s={};for(const l of i)s[l]=o[l];return e.objectValues(s)},e.objectValues=o=>e.objectKeys(o).map(function(i){return o[i]}),e.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{const i=[];for(const s in o)Object.prototype.hasOwnProperty.call(o,s)&&i.push(s);return i},e.find=(o,i)=>{for(const s of o)if(i(s))return s},e.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&isFinite(o)&&Math.floor(o)===o;function r(o,i=" | "){return o.map(s=>typeof s=="string"?`'${s}'`:s).join(i)}e.joinValues=r,e.jsonStringifyReplacer=(o,i)=>typeof i=="bigint"?i.toString():i})(mt||(mt={}));var P2;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(P2||(P2={}));const be=mt.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ca=e=>{switch(typeof e){case"undefined":return be.undefined;case"string":return be.string;case"number":return isNaN(e)?be.nan:be.number;case"boolean":return be.boolean;case"function":return be.function;case"bigint":return be.bigint;case"symbol":return be.symbol;case"object":return Array.isArray(e)?be.array:e===null?be.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?be.promise:typeof Map<"u"&&e instanceof Map?be.map:typeof Set<"u"&&e instanceof Set?be.set:typeof Date<"u"&&e instanceof Date?be.date:be.object;default:return be.unknown}},pe=mt.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"]);class Go 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(i){return i.message},r={_errors:[]},o=i=>{for(const s of i.issues)if(s.code==="invalid_union")s.unionErrors.map(o);else if(s.code==="invalid_return_type")o(s.returnTypeError);else if(s.code==="invalid_arguments")o(s.argumentsError);else if(s.path.length===0)r._errors.push(n(s));else{let l=r,u=0;for(;un.message){const n={},r=[];for(const o of this.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(t(o))):r.push(t(o));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}}Go.create=e=>new Go(e);const Xp=(e,t)=>{let n;switch(e.code){case pe.invalid_type:e.received===be.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case pe.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,mt.jsonStringifyReplacer)}`;break;case pe.unrecognized_keys:n=`Unrecognized key(s) in object: ${mt.joinValues(e.keys,", ")}`;break;case pe.invalid_union:n="Invalid input";break;case pe.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${mt.joinValues(e.options)}`;break;case pe.invalid_enum_value:n=`Invalid enum value. Expected ${mt.joinValues(e.options)}, received '${e.received}'`;break;case pe.invalid_arguments:n="Invalid function arguments";break;case pe.invalid_return_type:n="Invalid function return type";break;case pe.invalid_date:n="Invalid date";break;case pe.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}"`:mt.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case pe.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 pe.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 pe.custom:n="Invalid input";break;case pe.invalid_intersection_types:n="Intersection results could not be merged";break;case pe.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case pe.not_finite:n="Number must be finite";break;default:n=t.defaultError,mt.assertNever(e)}return{message:n}};let eX=Xp;function C1(){return eX}const $1=e=>{const{data:t,path:n,errorMaps:r,issueData:o}=e,i=[...n,...o.path||[]],s={...o,path:i};let l="";const u=r.filter(f=>!!f).slice().reverse();for(const f of u)l=f(s,{data:t,defaultError:l}).message;return{...o,path:i,message:o.message||l}};function Ee(e,t){const n=$1({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,C1(),Xp].filter(r=>!!r)});e.common.issues.push(n)}class zn{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 o of n){if(o.status==="aborted")return Ze;o.status==="dirty"&&t.dirty(),r.push(o.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){const r=[];for(const o of n)r.push({key:await o.key,value:await o.value});return zn.mergeObjectSync(t,r)}static mergeObjectSync(t,n){const r={};for(const o of n){const{key:i,value:s}=o;if(i.status==="aborted"||s.status==="aborted")return Ze;i.status==="dirty"&&t.dirty(),s.status==="dirty"&&t.dirty(),i.value!=="__proto__"&&(typeof s.value<"u"||o.alwaysSet)&&(r[i.value]=s.value)}return{status:t.value,value:r}}}const Ze=Object.freeze({status:"aborted"}),tX=e=>({status:"dirty",value:e}),rr=e=>({status:"valid",value:e}),A2=e=>e.status==="aborted",M2=e=>e.status==="dirty",Zp=e=>e.status==="valid",R1=e=>typeof Promise<"u"&&e instanceof Promise;var Ne;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t==null?void 0:t.message})(Ne||(Ne={}));class Qo{constructor(t,n,r,o){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=o}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 O2=(e,t)=>{if(Zp(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 Go(e.common.issues);return this._error=n,this._error}}};function Xe(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:r,description:o}=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:o}:{errorMap:(s,l)=>s.code!=="invalid_type"?{message:l.defaultError}:typeof l.data>"u"?{message:r??l.defaultError}:{message:n??l.defaultError},description:o}}class rt{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.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this)}get description(){return this._def.description}_getType(t){return ca(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:ca(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new zn,ctx:{common:t.parent.common,data:t.data,parsedType:ca(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const n=this._parse(t);if(R1(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 o={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:ca(t)},i=this._parseSync({data:t,path:o.path,parent:o});return O2(o,i)}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:ca(t)},o=this._parse({data:t,path:r.path,parent:r}),i=await(R1(o)?o:Promise.resolve(o));return O2(r,i)}refine(t,n){const r=o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n;return this._refinement((o,i)=>{const s=t(o),l=()=>i.addIssue({code:pe.custom,...r(o)});return typeof Promise<"u"&&s instanceof Promise?s.then(u=>u?!0:(l(),!1)):s?!0:(l(),!1)})}refinement(t,n){return this._refinement((r,o)=>t(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(t){return new Pi({schema:this,typeName:ze.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}optional(){return Cs.create(this,this._def)}nullable(){return gc.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Yo.create(this,this._def)}promise(){return pd.create(this,this._def)}or(t){return Jp.create([this,t],this._def)}and(t){return em.create(this,t,this._def)}transform(t){return new Pi({...Xe(this._def),schema:this,typeName:ze.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const n=typeof t=="function"?t:()=>t;return new im({...Xe(this._def),innerType:this,defaultValue:n,typeName:ze.ZodDefault})}brand(){return new hX({typeName:ze.ZodBranded,type:this,...Xe(this._def)})}catch(t){const n=typeof t=="function"?t:()=>t;return new N1({...Xe(this._def),innerType:this,catchValue:n,typeName:ze.ZodCatch})}describe(t){const n=this.constructor;return new n({...this._def,description:t})}pipe(t){return cg.create(this,t)}readonly(){return I1.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const nX=/^c[^\s-]{8,}$/i,rX=/^[a-z][a-z0-9]*$/,oX=/^[0-9A-HJKMNP-TV-Z]{26}$/,iX=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,sX=/^(?!\.)(?!.*\.\.)([A-Z0-9_+-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,aX="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let L0;const lX=/^(((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}))$/,cX=/^(([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})))$/,uX=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 dX(e,t){return!!((t==="v4"||!t)&&lX.test(e)||(t==="v6"||!t)&&cX.test(e))}class yi extends rt{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==be.string){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_type,expected:be.string,received:i.parsedType}),Ze}const r=new zn;let o;for(const i of this._def.checks)if(i.kind==="min")t.data.lengthi.value&&(o=this._getOrReturnCtx(t,o),Ee(o,{code:pe.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){const s=t.data.length>i.value,l=t.data.lengtht.test(o),{validation:n,code:pe.invalid_string,...Ne.errToObj(r)})}_addCheck(t){return new yi({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...Ne.errToObj(t)})}url(t){return this._addCheck({kind:"url",...Ne.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...Ne.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...Ne.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...Ne.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...Ne.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...Ne.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...Ne.errToObj(t)})}datetime(t){var n;return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof(t==null?void 0:t.precision)>"u"?null:t==null?void 0:t.precision,offset:(n=t==null?void 0:t.offset)!==null&&n!==void 0?n:!1,...Ne.errToObj(t==null?void 0:t.message)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...Ne.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n==null?void 0:n.position,...Ne.errToObj(n==null?void 0:n.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...Ne.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...Ne.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...Ne.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...Ne.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...Ne.errToObj(n)})}nonempty(t){return this.min(1,Ne.errToObj(t))}trim(){return new yi({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new yi({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new yi({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}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 yi({checks:[],typeName:ze.ZodString,coerce:(t=e==null?void 0:e.coerce)!==null&&t!==void 0?t:!1,...Xe(e)})};function fX(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,o=n>r?n:r,i=parseInt(e.toFixed(o).replace(".","")),s=parseInt(t.toFixed(o).replace(".",""));return i%s/Math.pow(10,o)}class hc extends rt{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)!==be.number){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_type,expected:be.number,received:i.parsedType}),Ze}let r;const o=new zn;for(const i of this._def.checks)i.kind==="int"?mt.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.invalid_type,expected:"integer",received:"float",message:i.message}),o.dirty()):i.kind==="min"?(i.inclusive?t.datai.value:t.data>=i.value)&&(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),o.dirty()):i.kind==="multipleOf"?fX(t.data,i.value)!==0&&(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):i.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.not_finite,message:i.message}),o.dirty()):mt.assertNever(i);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,Ne.toString(n))}gt(t,n){return this.setLimit("min",t,!1,Ne.toString(n))}lte(t,n){return this.setLimit("max",t,!0,Ne.toString(n))}lt(t,n){return this.setLimit("max",t,!1,Ne.toString(n))}setLimit(t,n,r,o){return new hc({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:Ne.toString(o)}]})}_addCheck(t){return new hc({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:Ne.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Ne.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Ne.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Ne.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Ne.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:Ne.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:Ne.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Ne.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Ne.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"&&mt.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 hc({checks:[],typeName:ze.ZodNumber,coerce:(e==null?void 0:e.coerce)||!1,...Xe(e)});class pc extends rt{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)!==be.bigint){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_type,expected:be.bigint,received:i.parsedType}),Ze}let r;const o=new zn;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?t.datai.value:t.data>=i.value)&&(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),o.dirty()):i.kind==="multipleOf"?t.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):mt.assertNever(i);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,Ne.toString(n))}gt(t,n){return this.setLimit("min",t,!1,Ne.toString(n))}lte(t,n){return this.setLimit("max",t,!0,Ne.toString(n))}lt(t,n){return this.setLimit("max",t,!1,Ne.toString(n))}setLimit(t,n,r,o){return new pc({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:Ne.toString(o)}]})}_addCheck(t){return new pc({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Ne.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Ne.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Ne.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Ne.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:Ne.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 pc({checks:[],typeName:ze.ZodBigInt,coerce:(t=e==null?void 0:e.coerce)!==null&&t!==void 0?t:!1,...Xe(e)})};class k1 extends rt{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==be.boolean){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.boolean,received:r.parsedType}),Ze}return rr(t.data)}}k1.create=e=>new k1({typeName:ze.ZodBoolean,coerce:(e==null?void 0:e.coerce)||!1,...Xe(e)});class hd extends rt{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==be.date){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_type,expected:be.date,received:i.parsedType}),Ze}if(isNaN(t.data.getTime())){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_date}),Ze}const r=new zn;let o;for(const i of this._def.checks)i.kind==="min"?t.data.getTime()i.value&&(o=this._getOrReturnCtx(t,o),Ee(o,{code:pe.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):mt.assertNever(i);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new hd({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:Ne.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:Ne.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 hd({checks:[],coerce:(e==null?void 0:e.coerce)||!1,typeName:ze.ZodDate,...Xe(e)});class T1 extends rt{_parse(t){if(this._getType(t)!==be.symbol){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.symbol,received:r.parsedType}),Ze}return rr(t.data)}}T1.create=e=>new T1({typeName:ze.ZodSymbol,...Xe(e)});class qp extends rt{_parse(t){if(this._getType(t)!==be.undefined){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.undefined,received:r.parsedType}),Ze}return rr(t.data)}}qp.create=e=>new qp({typeName:ze.ZodUndefined,...Xe(e)});class Qp extends rt{_parse(t){if(this._getType(t)!==be.null){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.null,received:r.parsedType}),Ze}return rr(t.data)}}Qp.create=e=>new Qp({typeName:ze.ZodNull,...Xe(e)});class P1 extends rt{constructor(){super(...arguments),this._any=!0}_parse(t){return rr(t.data)}}P1.create=e=>new P1({typeName:ze.ZodAny,...Xe(e)});class Dl extends rt{constructor(){super(...arguments),this._unknown=!0}_parse(t){return rr(t.data)}}Dl.create=e=>new Dl({typeName:ze.ZodUnknown,...Xe(e)});class Ms extends rt{_parse(t){const n=this._getOrReturnCtx(t);return Ee(n,{code:pe.invalid_type,expected:be.never,received:n.parsedType}),Ze}}Ms.create=e=>new Ms({typeName:ze.ZodNever,...Xe(e)});class A1 extends rt{_parse(t){if(this._getType(t)!==be.undefined){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.void,received:r.parsedType}),Ze}return rr(t.data)}}A1.create=e=>new A1({typeName:ze.ZodVoid,...Xe(e)});class Yo extends rt{_parse(t){const{ctx:n,status:r}=this._processInputParams(t),o=this._def;if(n.parsedType!==be.array)return Ee(n,{code:pe.invalid_type,expected:be.array,received:n.parsedType}),Ze;if(o.exactLength!==null){const s=n.data.length>o.exactLength.value,l=n.data.lengtho.maxLength.value&&(Ee(n,{code:pe.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((s,l)=>o.type._parseAsync(new Qo(n,s,n.path,l)))).then(s=>zn.mergeArray(r,s));const i=[...n.data].map((s,l)=>o.type._parseSync(new Qo(n,s,n.path,l)));return zn.mergeArray(r,i)}get element(){return this._def.type}min(t,n){return new Yo({...this._def,minLength:{value:t,message:Ne.toString(n)}})}max(t,n){return new Yo({...this._def,maxLength:{value:t,message:Ne.toString(n)}})}length(t,n){return new Yo({...this._def,exactLength:{value:t,message:Ne.toString(n)}})}nonempty(t){return this.min(1,t)}}Yo.create=(e,t)=>new Yo({type:e,minLength:null,maxLength:null,exactLength:null,typeName:ze.ZodArray,...Xe(t)});function dl(e){if(e instanceof Vt){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=Cs.create(dl(r))}return new Vt({...e._def,shape:()=>t})}else return e instanceof Yo?new Yo({...e._def,type:dl(e.element)}):e instanceof Cs?Cs.create(dl(e.unwrap())):e instanceof gc?gc.create(dl(e.unwrap())):e instanceof Ti?Ti.create(e.items.map(t=>dl(t))):e}class Vt extends rt{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=mt.objectKeys(t);return this._cached={shape:t,keys:n}}_parse(t){if(this._getType(t)!==be.object){const f=this._getOrReturnCtx(t);return Ee(f,{code:pe.invalid_type,expected:be.object,received:f.parsedType}),Ze}const{status:r,ctx:o}=this._processInputParams(t),{shape:i,keys:s}=this._getCached(),l=[];if(!(this._def.catchall instanceof Ms&&this._def.unknownKeys==="strip"))for(const f in o.data)s.includes(f)||l.push(f);const u=[];for(const f of s){const m=i[f],p=o.data[f];u.push({key:{status:"valid",value:f},value:m._parse(new Qo(o,p,o.path,f)),alwaysSet:f in o.data})}if(this._def.catchall instanceof Ms){const f=this._def.unknownKeys;if(f==="passthrough")for(const m of l)u.push({key:{status:"valid",value:m},value:{status:"valid",value:o.data[m]}});else if(f==="strict")l.length>0&&(Ee(o,{code:pe.unrecognized_keys,keys:l}),r.dirty());else if(f!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const f=this._def.catchall;for(const m of l){const p=o.data[m];u.push({key:{status:"valid",value:m},value:f._parse(new Qo(o,p,o.path,m)),alwaysSet:m in o.data})}}return o.common.async?Promise.resolve().then(async()=>{const f=[];for(const m of u){const p=await m.key;f.push({key:p,value:await m.value,alwaysSet:m.alwaysSet})}return f}).then(f=>zn.mergeObjectSync(r,f)):zn.mergeObjectSync(r,u)}get shape(){return this._def.shape()}strict(t){return Ne.errToObj,new Vt({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{var o,i,s,l;const u=(s=(i=(o=this._def).errorMap)===null||i===void 0?void 0:i.call(o,n,r).message)!==null&&s!==void 0?s:r.defaultError;return n.code==="unrecognized_keys"?{message:(l=Ne.errToObj(t).message)!==null&&l!==void 0?l:u}:{message:u}}}:{}})}strip(){return new Vt({...this._def,unknownKeys:"strip"})}passthrough(){return new Vt({...this._def,unknownKeys:"passthrough"})}extend(t){return new Vt({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new Vt({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:ze.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new Vt({...this._def,catchall:t})}pick(t){const n={};return mt.objectKeys(t).forEach(r=>{t[r]&&this.shape[r]&&(n[r]=this.shape[r])}),new Vt({...this._def,shape:()=>n})}omit(t){const n={};return mt.objectKeys(this.shape).forEach(r=>{t[r]||(n[r]=this.shape[r])}),new Vt({...this._def,shape:()=>n})}deepPartial(){return dl(this)}partial(t){const n={};return mt.objectKeys(this.shape).forEach(r=>{const o=this.shape[r];t&&!t[r]?n[r]=o:n[r]=o.optional()}),new Vt({...this._def,shape:()=>n})}required(t){const n={};return mt.objectKeys(this.shape).forEach(r=>{if(t&&!t[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof Cs;)i=i._def.innerType;n[r]=i}}),new Vt({...this._def,shape:()=>n})}keyof(){return n3(mt.objectKeys(this.shape))}}Vt.create=(e,t)=>new Vt({shape:()=>e,unknownKeys:"strip",catchall:Ms.create(),typeName:ze.ZodObject,...Xe(t)});Vt.strictCreate=(e,t)=>new Vt({shape:()=>e,unknownKeys:"strict",catchall:Ms.create(),typeName:ze.ZodObject,...Xe(t)});Vt.lazycreate=(e,t)=>new Vt({shape:e,unknownKeys:"strip",catchall:Ms.create(),typeName:ze.ZodObject,...Xe(t)});class Jp extends rt{_parse(t){const{ctx:n}=this._processInputParams(t),r=this._def.options;function o(i){for(const l of i)if(l.result.status==="valid")return l.result;for(const l of i)if(l.result.status==="dirty")return n.common.issues.push(...l.ctx.common.issues),l.result;const s=i.map(l=>new Go(l.ctx.common.issues));return Ee(n,{code:pe.invalid_union,unionErrors:s}),Ze}if(n.common.async)return Promise.all(r.map(async i=>{const s={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:s}),ctx:s}})).then(o);{let i;const s=[];for(const u of r){const f={...n,common:{...n.common,issues:[]},parent:null},m=u._parseSync({data:n.data,path:n.path,parent:f});if(m.status==="valid")return m;m.status==="dirty"&&!i&&(i={result:m,ctx:f}),f.common.issues.length&&s.push(f.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;const l=s.map(u=>new Go(u));return Ee(n,{code:pe.invalid_union,unionErrors:l}),Ze}}get options(){return this._def.options}}Jp.create=(e,t)=>new Jp({options:e,typeName:ze.ZodUnion,...Xe(t)});const rp=e=>e instanceof nm?rp(e.schema):e instanceof Pi?rp(e.innerType()):e instanceof rm?[e.value]:e instanceof Da?e.options:e instanceof om?Object.keys(e.enum):e instanceof im?rp(e._def.innerType):e instanceof qp?[void 0]:e instanceof Qp?[null]:null;class Xx extends rt{_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.object)return Ee(n,{code:pe.invalid_type,expected:be.object,received:n.parsedType}),Ze;const r=this.discriminator,o=n.data[r],i=this.optionsMap.get(o);return i?n.common.async?i._parseAsync({data:n.data,path:n.path,parent:n}):i._parseSync({data:n.data,path:n.path,parent:n}):(Ee(n,{code:pe.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),Ze)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){const o=new Map;for(const i of n){const s=rp(i.shape[t]);if(!s)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const l of s){if(o.has(l))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(l)}`);o.set(l,i)}}return new Xx({typeName:ze.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:o,...Xe(r)})}}function M1(e,t){const n=ca(e),r=ca(t);if(e===t)return{valid:!0,data:e};if(n===be.object&&r===be.object){const o=mt.objectKeys(t),i=mt.objectKeys(e).filter(l=>o.indexOf(l)!==-1),s={...e,...t};for(const l of i){const u=M1(e[l],t[l]);if(!u.valid)return{valid:!1};s[l]=u.data}return{valid:!0,data:s}}else if(n===be.array&&r===be.array){if(e.length!==t.length)return{valid:!1};const o=[];for(let i=0;i{if(A2(i)||A2(s))return Ze;const l=M1(i.value,s.value);return l.valid?((M2(i)||M2(s))&&n.dirty(),{status:n.value,value:l.data}):(Ee(r,{code:pe.invalid_intersection_types}),Ze)};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(([i,s])=>o(i,s)):o(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}em.create=(e,t,n)=>new em({left:e,right:t,typeName:ze.ZodIntersection,...Xe(n)});class Ti extends rt{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.array)return Ee(r,{code:pe.invalid_type,expected:be.array,received:r.parsedType}),Ze;if(r.data.lengththis._def.items.length&&(Ee(r,{code:pe.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const i=[...r.data].map((s,l)=>{const u=this._def.items[l]||this._def.rest;return u?u._parse(new Qo(r,s,r.path,l)):null}).filter(s=>!!s);return r.common.async?Promise.all(i).then(s=>zn.mergeArray(n,s)):zn.mergeArray(n,i)}get items(){return this._def.items}rest(t){return new Ti({...this._def,rest:t})}}Ti.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ti({items:e,typeName:ze.ZodTuple,rest:null,...Xe(t)})};class tm extends rt{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!==be.object)return Ee(r,{code:pe.invalid_type,expected:be.object,received:r.parsedType}),Ze;const o=[],i=this._def.keyType,s=this._def.valueType;for(const l in r.data)o.push({key:i._parse(new Qo(r,l,r.path,l)),value:s._parse(new Qo(r,r.data[l],r.path,l))});return r.common.async?zn.mergeObjectAsync(n,o):zn.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof rt?new tm({keyType:t,valueType:n,typeName:ze.ZodRecord,...Xe(r)}):new tm({keyType:yi.create(),valueType:t,typeName:ze.ZodRecord,...Xe(n)})}}class O1 extends rt{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!==be.map)return Ee(r,{code:pe.invalid_type,expected:be.map,received:r.parsedType}),Ze;const o=this._def.keyType,i=this._def.valueType,s=[...r.data.entries()].map(([l,u],f)=>({key:o._parse(new Qo(r,l,r.path,[f,"key"])),value:i._parse(new Qo(r,u,r.path,[f,"value"]))}));if(r.common.async){const l=new Map;return Promise.resolve().then(async()=>{for(const u of s){const f=await u.key,m=await u.value;if(f.status==="aborted"||m.status==="aborted")return Ze;(f.status==="dirty"||m.status==="dirty")&&n.dirty(),l.set(f.value,m.value)}return{status:n.value,value:l}})}else{const l=new Map;for(const u of s){const f=u.key,m=u.value;if(f.status==="aborted"||m.status==="aborted")return Ze;(f.status==="dirty"||m.status==="dirty")&&n.dirty(),l.set(f.value,m.value)}return{status:n.value,value:l}}}}O1.create=(e,t,n)=>new O1({valueType:t,keyType:e,typeName:ze.ZodMap,...Xe(n)});class mc extends rt{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.set)return Ee(r,{code:pe.invalid_type,expected:be.set,received:r.parsedType}),Ze;const o=this._def;o.minSize!==null&&r.data.sizeo.maxSize.value&&(Ee(r,{code:pe.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());const i=this._def.valueType;function s(u){const f=new Set;for(const m of u){if(m.status==="aborted")return Ze;m.status==="dirty"&&n.dirty(),f.add(m.value)}return{status:n.value,value:f}}const l=[...r.data.values()].map((u,f)=>i._parse(new Qo(r,u,r.path,f)));return r.common.async?Promise.all(l).then(u=>s(u)):s(l)}min(t,n){return new mc({...this._def,minSize:{value:t,message:Ne.toString(n)}})}max(t,n){return new mc({...this._def,maxSize:{value:t,message:Ne.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}}mc.create=(e,t)=>new mc({valueType:e,minSize:null,maxSize:null,typeName:ze.ZodSet,...Xe(t)});class Lu extends rt{constructor(){super(...arguments),this.validate=this.implement}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.function)return Ee(n,{code:pe.invalid_type,expected:be.function,received:n.parsedType}),Ze;function r(l,u){return $1({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,C1(),Xp].filter(f=>!!f),issueData:{code:pe.invalid_arguments,argumentsError:u}})}function o(l,u){return $1({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,C1(),Xp].filter(f=>!!f),issueData:{code:pe.invalid_return_type,returnTypeError:u}})}const i={errorMap:n.common.contextualErrorMap},s=n.data;if(this._def.returns instanceof pd){const l=this;return rr(async function(...u){const f=new Go([]),m=await l._def.args.parseAsync(u,i).catch(y=>{throw f.addIssue(r(u,y)),f}),p=await Reflect.apply(s,this,m);return await l._def.returns._def.type.parseAsync(p,i).catch(y=>{throw f.addIssue(o(p,y)),f})})}else{const l=this;return rr(function(...u){const f=l._def.args.safeParse(u,i);if(!f.success)throw new Go([r(u,f.error)]);const m=Reflect.apply(s,this,f.data),p=l._def.returns.safeParse(m,i);if(!p.success)throw new Go([o(m,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new Lu({...this._def,args:Ti.create(t).rest(Dl.create())})}returns(t){return new Lu({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new Lu({args:t||Ti.create([]).rest(Dl.create()),returns:n||Dl.create(),typeName:ze.ZodFunction,...Xe(r)})}}class nm extends rt{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})}}nm.create=(e,t)=>new nm({getter:e,typeName:ze.ZodLazy,...Xe(t)});class rm extends rt{_parse(t){if(t.data!==this._def.value){const n=this._getOrReturnCtx(t);return Ee(n,{received:n.data,code:pe.invalid_literal,expected:this._def.value}),Ze}return{status:"valid",value:t.data}}get value(){return this._def.value}}rm.create=(e,t)=>new rm({value:e,typeName:ze.ZodLiteral,...Xe(t)});function n3(e,t){return new Da({values:e,typeName:ze.ZodEnum,...Xe(t)})}class Da extends rt{_parse(t){if(typeof t.data!="string"){const n=this._getOrReturnCtx(t),r=this._def.values;return Ee(n,{expected:mt.joinValues(r),received:n.parsedType,code:pe.invalid_type}),Ze}if(this._def.values.indexOf(t.data)===-1){const n=this._getOrReturnCtx(t),r=this._def.values;return Ee(n,{received:n.data,code:pe.invalid_enum_value,options:r}),Ze}return rr(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 Da.create(t)}exclude(t){return Da.create(this.options.filter(n=>!t.includes(n)))}}Da.create=n3;class om extends rt{_parse(t){const n=mt.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==be.string&&r.parsedType!==be.number){const o=mt.objectValues(n);return Ee(r,{expected:mt.joinValues(o),received:r.parsedType,code:pe.invalid_type}),Ze}if(n.indexOf(t.data)===-1){const o=mt.objectValues(n);return Ee(r,{received:r.data,code:pe.invalid_enum_value,options:o}),Ze}return rr(t.data)}get enum(){return this._def.values}}om.create=(e,t)=>new om({values:e,typeName:ze.ZodNativeEnum,...Xe(t)});class pd extends rt{unwrap(){return this._def.type}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.promise&&n.common.async===!1)return Ee(n,{code:pe.invalid_type,expected:be.promise,received:n.parsedType}),Ze;const r=n.parsedType===be.promise?n.data:Promise.resolve(n.data);return rr(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}}pd.create=(e,t)=>new pd({type:e,typeName:ze.ZodPromise,...Xe(t)});class Pi extends rt{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ze.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:n,ctx:r}=this._processInputParams(t),o=this._def.effect||null,i={addIssue:s=>{Ee(r,s),s.fatal?n.abort():n.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),o.type==="preprocess"){const s=o.transform(r.data,i);return r.common.issues.length?{status:"dirty",value:r.data}:r.common.async?Promise.resolve(s).then(l=>this._def.schema._parseAsync({data:l,path:r.path,parent:r})):this._def.schema._parseSync({data:s,path:r.path,parent:r})}if(o.type==="refinement"){const s=l=>{const u=o.refinement(l,i);if(r.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return l};if(r.common.async===!1){const l=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return l.status==="aborted"?Ze:(l.status==="dirty"&&n.dirty(),s(l.value),{status:n.value,value:l.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(l=>l.status==="aborted"?Ze:(l.status==="dirty"&&n.dirty(),s(l.value).then(()=>({status:n.value,value:l.value}))))}if(o.type==="transform")if(r.common.async===!1){const s=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Zp(s))return s;const l=o.transform(s.value,i);if(l instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:l}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(s=>Zp(s)?Promise.resolve(o.transform(s.value,i)).then(l=>({status:n.value,value:l})):s);mt.assertNever(o)}}Pi.create=(e,t,n)=>new Pi({schema:e,typeName:ze.ZodEffects,effect:t,...Xe(n)});Pi.createWithPreprocess=(e,t,n)=>new Pi({schema:t,effect:{type:"preprocess",transform:e},typeName:ze.ZodEffects,...Xe(n)});class Cs extends rt{_parse(t){return this._getType(t)===be.undefined?rr(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Cs.create=(e,t)=>new Cs({innerType:e,typeName:ze.ZodOptional,...Xe(t)});class gc extends rt{_parse(t){return this._getType(t)===be.null?rr(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}gc.create=(e,t)=>new gc({innerType:e,typeName:ze.ZodNullable,...Xe(t)});class im extends rt{_parse(t){const{ctx:n}=this._processInputParams(t);let r=n.data;return n.parsedType===be.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}im.create=(e,t)=>new im({innerType:e,typeName:ze.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Xe(t)});class N1 extends rt{_parse(t){const{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return R1(o)?o.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Go(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Go(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}N1.create=(e,t)=>new N1({innerType:e,typeName:ze.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Xe(t)});class D1 extends rt{_parse(t){if(this._getType(t)!==be.nan){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.nan,received:r.parsedType}),Ze}return{status:"valid",value:t.data}}}D1.create=e=>new D1({typeName:ze.ZodNaN,...Xe(e)});class hX extends rt{_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 cg extends rt{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?Ze:i.status==="dirty"?(n.dirty(),tX(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{const o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?Ze:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(t,n){return new cg({in:t,out:n,typeName:ze.ZodPipeline})}}class I1 extends rt{_parse(t){const n=this._def.innerType._parse(t);return Zp(n)&&(n.value=Object.freeze(n.value)),n}}I1.create=(e,t)=>new I1({innerType:e,typeName:ze.ZodReadonly,...Xe(t)});Vt.lazycreate;var ze;(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",e.ZodReadonly="ZodReadonly"})(ze||(ze={}));const fu=yi.create;hc.create;D1.create;pc.create;const hu=k1.create;hd.create;T1.create;qp.create;Qp.create;P1.create;Dl.create;Ms.create;A1.create;Yo.create;const pX=Vt.create;Vt.strictCreate;Jp.create;Xx.create;em.create;Ti.create;tm.create;O1.create;mc.create;Lu.create;nm.create;rm.create;Da.create;om.create;pd.create;Pi.create;Cs.create;gc.create;Pi.createWithPreprocess;cg.create;const L1="horizontal",mX=["horizontal","vertical"],r3=d.forwardRef((e,t)=>{const{decorative:n,orientation:r=L1,...o}=e,i=o3(r)?r:L1,l=n?{role:"none"}:{"aria-orientation":i==="vertical"?i:void 0,role:"separator"};return d.createElement(Pe.div,Y({"data-orientation":i},l,o,{ref:t}))});r3.propTypes={orientation(e,t,n){const r=e[t],o=String(r);return r&&!o3(r)?new Error(gX(o,n)):null}};function gX(e,t){return`Invalid prop \`orientation\` of value \`${e}\` supplied to \`${t}\`, expected one of: + - horizontal + - vertical + +Defaulting to \`${L1}\`.`}function o3(e){return mX.includes(e)}const i3=r3,gn=d.forwardRef(({className:e,orientation:t="horizontal",decorative:n=!0,...r},o)=>v.jsx(i3,{ref:o,decorative:n,orientation:t,className:Ce("shrink-0 bg-border",t==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",e),...r}));gn.displayName=i3.displayName;const vX=d.forwardRef((e,t)=>d.createElement(Pe.label,Y({},e,{ref:t,onMouseDown:n=>{var r;(r=e.onMouseDown)===null||r===void 0||r.call(e,n),!n.defaultPrevented&&n.detail>1&&n.preventDefault()}}))),s3=vX,yX=Dm("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),Zx=d.forwardRef(({className:e,disabled:t,...n},r)=>v.jsx(s3,{ref:r,className:Ce(yX(),e,t?"opacity-50":"","select-none"),...n}));Zx.displayName=s3.displayName;const wX=OY,a3=d.createContext({}),al=({...e})=>v.jsx(a3.Provider,{value:{name:e.name},children:v.jsx(LY,{...e})}),ug=()=>{const e=d.useContext(a3),t=d.useContext(l3),{getFieldState:n,formState:r}=lg(),o=n(e.name,r);if(!e)throw new Error("useFormField should be used within ");const{id:i}=t;return{id:i,name:e.name,formItemId:`${i}-form-item`,formDescriptionId:`${i}-form-item-description`,formMessageId:`${i}-form-item-message`,...o}},l3=d.createContext({}),oa=d.forwardRef(({className:e,...t},n)=>{const r=d.useId();return v.jsx(l3.Provider,{value:{id:r},children:v.jsx("div",{ref:n,className:Ce("space-y-2",e),...t})})});oa.displayName="FormItem";const ia=d.forwardRef(({className:e,...t},n)=>{const{error:r,formItemId:o}=ug();return v.jsx(Zx,{ref:n,className:Ce(r&&"text-destructive","text-sm",e),htmlFor:o,...t})});ia.displayName="FormLabel";const sa=d.forwardRef(({...e},t)=>{const{error:n,formItemId:r,formDescriptionId:o,formMessageId:i}=ug();return v.jsx(Zo,{ref:t,id:r,"aria-describedby":n?`${o} ${i}`:`${o}`,"aria-invalid":!!n,...e})});sa.displayName="FormControl";const aa=d.forwardRef(({className:e,...t},n)=>{const{formDescriptionId:r}=ug();return v.jsx("p",{ref:n,id:r,className:Ce("text-[0.8rem] text-muted-foreground",e),...t})});aa.displayName="FormDescription";const xX=d.forwardRef(({className:e,children:t,...n},r)=>{const{error:o,formMessageId:i}=ug(),s=o?String(o==null?void 0:o.message):t;return s?v.jsx("p",{ref:r,id:i,className:Ce("text-[0.8rem] font-medium text-destructive",e),...n,children:s}):null});xX.displayName="FormMessage";const c3="Switch",[bX,_te]=Mn(c3),[SX,_X]=bX(c3),EX=d.forwardRef((e,t)=>{const{__scopeSwitch:n,name:r,checked:o,defaultChecked:i,required:s,disabled:l,value:u="on",onCheckedChange:f,...m}=e,[p,g]=d.useState(null),y=Be(t,x=>g(x)),b=d.useRef(!1),S=p?!!p.closest("form"):!0,[E=!1,_]=Zr({prop:o,defaultProp:i,onChange:f});return d.createElement(SX,{scope:n,checked:E,disabled:l},d.createElement(Pe.button,Y({type:"button",role:"switch","aria-checked":E,"aria-required":s,"data-state":u3(E),"data-disabled":l?"":void 0,disabled:l,value:u},m,{ref:y,onClick:de(e.onClick,x=>{_(C=>!C),S&&(b.current=x.isPropagationStopped(),b.current||x.stopPropagation())})})),S&&d.createElement(RX,{control:p,bubbles:!b.current,name:r,value:u,checked:E,required:s,disabled:l,style:{transform:"translateX(-100%)"}}))}),CX="SwitchThumb",$X=d.forwardRef((e,t)=>{const{__scopeSwitch:n,...r}=e,o=_X(CX,n);return d.createElement(Pe.span,Y({"data-state":u3(o.checked),"data-disabled":o.disabled?"":void 0},r,{ref:t}))}),RX=e=>{const{control:t,checked:n,bubbles:r=!0,...o}=e,i=d.useRef(null),s=zx(n),l=yx(t);return d.useEffect(()=>{const u=i.current,f=window.HTMLInputElement.prototype,p=Object.getOwnPropertyDescriptor(f,"checked").set;if(s!==n&&p){const g=new Event("click",{bubbles:r});p.call(u,n),u.dispatchEvent(g)}},[s,n,r]),d.createElement("input",Y({type:"checkbox","aria-hidden":!0,defaultChecked:n},o,{tabIndex:-1,ref:i,style:{...e.style,...l,position:"absolute",pointerEvents:"none",opacity:0,margin:0}}))};function u3(e){return e?"checked":"unchecked"}const d3=EX,kX=$X,co=d.forwardRef(({className:e,...t},n)=>v.jsx(d3,{className:Ce("peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",e),tabIndex:-1,...t,ref:n,children:v.jsx(kX,{className:Ce("pointer-events-none block h-4 w-4 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0")})}));co.displayName=d3.displayName;const TX="AlertDialog",[PX,Ete]=Mn(TX,[dP]),zs=dP(),AX=e=>{const{__scopeAlertDialog:t,...n}=e,r=zs(t);return d.createElement(Cx,Y({},r,n,{modal:!0}))},MX=e=>{const{__scopeAlertDialog:t,...n}=e,r=zs(t);return d.createElement($x,Y({},r,n))},OX=d.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=zs(n);return d.createElement(Bd,Y({},o,r,{ref:t}))}),f3="AlertDialogContent",[NX,DX]=PX(f3),IX=d.forwardRef((e,t)=>{const{__scopeAlertDialog:n,children:r,...o}=e,i=zs(n),s=d.useRef(null),l=Be(t,s),u=d.useRef(null);return d.createElement(hW,{contentName:f3,titleName:LX,docsSlug:"alert-dialog"},d.createElement(NX,{scope:n,cancelRef:u},d.createElement(Ud,Y({role:"alertdialog"},i,o,{ref:l,onOpenAutoFocus:de(o.onOpenAutoFocus,f=>{var m;f.preventDefault(),(m=u.current)===null||m===void 0||m.focus({preventScroll:!0})}),onPointerDownOutside:f=>f.preventDefault(),onInteractOutside:f=>f.preventDefault()}),d.createElement(lx,null,r),!1)))}),LX="AlertDialogTitle",FX=d.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=zs(n);return d.createElement(Vd,Y({},o,r,{ref:t}))}),jX=d.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=zs(n);return d.createElement(Wd,Y({},o,r,{ref:t}))}),zX=d.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=zs(n);return d.createElement(Rx,Y({},o,r,{ref:t}))}),BX="AlertDialogCancel",UX=d.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,{cancelRef:o}=DX(BX,n),i=zs(n),s=Be(t,o);return d.createElement(Rx,Y({},i,r,{ref:s}))}),VX=AX,WX=MX,h3=OX,p3=IX,m3=zX,g3=UX,v3=FX,y3=jX,HX=VX,KX=WX,w3=d.forwardRef(({className:e,...t},n)=>v.jsx(h3,{className:Ce("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t,ref:n}));w3.displayName=h3.displayName;const x3=d.forwardRef(({className:e,...t},n)=>v.jsxs(KX,{children:[v.jsx(w3,{}),v.jsx(p3,{ref:n,className:Ce("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",e),...t})]}));x3.displayName=p3.displayName;const b3=({className:e,...t})=>v.jsx("div",{className:Ce("flex flex-col space-y-2 text-center sm:text-left",e),...t});b3.displayName="AlertDialogHeader";const GX=d.forwardRef(({className:e,...t},n)=>v.jsx(v3,{ref:n,className:Ce("text-lg font-semibold",e),...t}));GX.displayName=v3.displayName;const YX=d.forwardRef(({className:e,...t},n)=>v.jsx(y3,{ref:n,className:Ce("text-sm text-muted-foreground",e),...t}));YX.displayName=y3.displayName;const XX=d.forwardRef(({className:e,...t},n)=>v.jsx(m3,{ref:n,className:Ce(_x(),e),...t}));XX.displayName=m3.displayName;const ZX=d.forwardRef(({className:e,...t},n)=>v.jsx(g3,{ref:n,className:Ce(_x({variant:"outline"}),"mt-2 sm:mt-0",e),...t}));ZX.displayName=g3.displayName;const qX=pX({enableFileManager:hu(),inputDirectory:fu(),outputDirectory:fu(),enableDownloadMask:hu(),enableManualInpainting:hu(),enableUploadMask:hu(),enableAutoExtractPrompt:hu(),removeBGModel:fu(),realesrganModel:fu(),interactiveSegModel:fu()}),S3="General",F1="Model",_3="Plugins",QX=[F1,S3,_3];function JX(){const[e,t]=QT(!1),[n,r]=d.useState(F1),[o,i,s,l,u,f]=bt(F=>[F.updateAppState,F.settings,F.updateSettings,F.fileManagerState,F.setModel,F.setServerConfig]),{toast:m}=Id(),[p,g]=d.useState(i.model),[y,b]=d.useState([]),S=y.length>0;d.useEffect(()=>{g(i.model)},[i.model]);const{data:E,status:_}=ML({queryKey:["serverConfig"],queryFn:gT}),x=YY({resolver:JY(qX),defaultValues:{enableDownloadMask:i.enableDownloadMask,enableManualInpainting:i.enableManualInpainting,enableUploadMask:i.enableUploadMask,enableAutoExtractPrompt:i.enableAutoExtractPrompt,inputDirectory:l.inputDirectory,outputDirectory:l.outputDirectory,removeBGModel:E==null?void 0:E.removeBGModel,realesrganModel:E==null?void 0:E.realesrganModel,interactiveSegModel:E==null?void 0:E.interactiveSegModel}});d.useEffect(()=>{E&&(f(E),x.setValue("removeBGModel",E.removeBGModel),x.setValue("realesrganModel",E.realesrganModel),x.setValue("interactiveSegModel",E.interactiveSegModel))},[x,E]);async function C(F){s({enableDownloadMask:F.enableDownloadMask,enableManualInpainting:F.enableManualInpainting,enableUploadMask:F.enableUploadMask,enableAutoExtractPrompt:F.enableAutoExtractPrompt});const N=p.name!==i.model.name,ie=(E==null?void 0:E.removeBGModel)!==F.removeBGModel&&M,K=(E==null?void 0:E.realesrganModel)!==F.realesrganModel&&A,Z=(E==null?void 0:E.interactiveSegModel)!==F.interactiveSegModel&&D;if(N||ie||K||Z){const se=[];if(N&&se.push(`Switching model from ${i.model.name} to ${p.name}`),ie&&se.push(`Switching RemoveBG model from ${E==null?void 0:E.removeBGModel} to ${F.removeBGModel}`),K&&se.push(`Switching RealESRGAN model from ${E==null?void 0:E.realesrganModel} to ${F.realesrganModel}`),Z&&se.push(`Switching ${Ao.InteractiveSeg} model from ${E==null?void 0:E.interactiveSegModel} to ${F.interactiveSegModel}`),b(se),o({disableShortCuts:!0}),N)try{const ce=await Bj(p.name);m({title:`Switch to ${ce.name} success`}),u(p)}catch(ce){m({variant:"destructive",title:`Switch to ${p.name} failed: ${ce}`}),g(i.model)}if(ie)try{const ce=await v0(Ao.RemoveBG,F.removeBGModel);if(ce.status!==200)throw new Error(ce.statusText)}catch(ce){m({variant:"destructive",title:`Switch RemoveBG model to ${F.removeBGModel} failed: ${ce}`})}if(K)try{const ce=await v0(Ao.RealESRGAN,F.realesrganModel);if(ce.status!==200)throw new Error(ce.statusText)}catch(ce){m({variant:"destructive",title:`Switch RealESRGAN model to ${F.realesrganModel} failed: ${ce}`})}if(Z)try{const ce=await v0(Ao.InteractiveSeg,F.interactiveSegModel);if(ce.status!==200)throw new Error(ce.statusText)}catch(ce){m({variant:"destructive",title:`Switch ${Ao.InteractiveSeg} model to ${F.interactiveSegModel} failed: ${ce}`})}b([]),o({disableShortCuts:!1})}}if(Zn("s",()=>{t(),e&&C(x.getValues())},[e,x,p,E]),_!=="success")return v.jsx(v.Fragment,{});const R=E.modelInfos,P=E.plugins,M=P.some(F=>F.name===Ao.RemoveBG),A=P.some(F=>F.name===Ao.RealESRGAN),D=P.some(F=>F.name===Ao.InteractiveSeg);function U(F){t(),F||C(x.getValues())}function W(F){g(F)}function q(F){return R?R.filter(N=>F.includes(N.model_type)).map(N=>v.jsxs("div",{onClick:()=>W(N),className:"px-2",children:[v.jsx("div",{className:Ce([N.name===p.name?"bg-muted":"hover:bg-muted","rounded-md px-2 py-2","cursor-default"]),children:v.jsx("div",{className:"text-base",children:N.name})}),v.jsx(gn,{className:"my-1"})]},N.name)):v.jsx("div",{children:"Please download model first"})}function X(){let F=fs;for(let N of R)if(p.name===N.name){F=N.model_type,F===oC&&(F=uh),F===iC&&(F=dh);break}return v.jsxs("div",{className:"flex flex-col gap-4 w-[510px]",children:[v.jsxs("div",{className:"flex flex-col gap-4 rounded-md",children:[v.jsx("div",{className:"font-medium",children:"Current Model"}),v.jsx("div",{children:p.name})]}),v.jsx(gn,{}),v.jsxs("div",{className:"space-y-4 rounded-md",children:[v.jsx("div",{className:"flex gap-1 items-center justify-start",children:v.jsx("div",{className:"font-medium",children:"Available models"})}),v.jsxs(a5,{defaultValue:F,children:[v.jsxs(jx,{children:[v.jsx(pa,{value:fs,children:"Inpaint"}),v.jsx(pa,{value:uh,children:"Stable Diffusion"}),v.jsx(pa,{value:dh,children:"Stable Diffusion Inpaint"}),v.jsx(pa,{value:d0,children:"Other Diffusion"})]}),v.jsxs(ag,{className:"h-[240px] w-full mt-2 outline-none border rounded-lg",children:[v.jsx(Su,{value:fs,children:q([fs])}),v.jsx(Su,{value:uh,children:q([uh,oC])}),v.jsx(Su,{value:dh,children:q([dh,iC])}),v.jsx(Su,{value:d0,children:q([d0])})]})]})]})]})}function ae(){return v.jsxs("div",{className:"space-y-4 w-[510px]",children:[v.jsx(al,{control:x.control,name:"enableManualInpainting",render:({field:F})=>v.jsxs(oa,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(ia,{children:"Enable manual inpainting"}),v.jsx(aa,{children:"For erase model, click a button to trigger inpainting after draw mask."})]}),v.jsx(sa,{children:v.jsx(co,{checked:F.value,onCheckedChange:F.onChange})})]})}),v.jsx(gn,{}),v.jsx(al,{control:x.control,name:"enableDownloadMask",render:({field:F})=>v.jsxs(oa,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(ia,{children:"Enable download mask"}),v.jsx(aa,{children:"Also download the mask after save the inpainting result."})]}),v.jsx(sa,{children:v.jsx(co,{checked:F.value,onCheckedChange:F.onChange})})]})}),v.jsx(gn,{}),v.jsx(al,{control:x.control,name:"enableAutoExtractPrompt",render:({field:F})=>v.jsxs(oa,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(ia,{children:"Enable auto extract prompt"}),v.jsx(aa,{children:"Automatically extract prompt/negativate prompt from the image meta."})]}),v.jsx(sa,{children:v.jsx(co,{checked:F.value,onCheckedChange:F.onChange})})]})})]})}function V(){return v.jsxs("div",{className:"space-y-4 w-[510px]",children:[v.jsx(al,{control:x.control,name:"removeBGModel",render:({field:F})=>v.jsxs(oa,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(ia,{children:"Remove Background"}),v.jsx(aa,{children:"Remove background model"})]}),v.jsxs(Uo,{onValueChange:F.onChange,defaultValue:F.value,disabled:!M,children:[v.jsx(sa,{children:v.jsx(go,{className:"w-auto",children:v.jsx(Vo,{placeholder:"Select removebg model"})})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:E==null?void 0:E.removeBGModels.map(N=>v.jsx(yo,{value:N,children:N},N))})})]})]})}),v.jsx(gn,{}),v.jsx(al,{control:x.control,name:"realesrganModel",render:({field:F})=>v.jsxs(oa,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(ia,{children:"RealESRGAN"}),v.jsx(aa,{children:"RealESRGAN Model"})]}),v.jsxs(Uo,{onValueChange:F.onChange,defaultValue:F.value,disabled:!A,children:[v.jsx(sa,{children:v.jsx(go,{className:"w-auto",children:v.jsx(Vo,{placeholder:"Select RealESRGAN model"})})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:E==null?void 0:E.realesrganModels.map(N=>v.jsx(yo,{value:N,children:N},N))})})]})]})}),v.jsx(gn,{}),v.jsx(al,{control:x.control,name:"interactiveSegModel",render:({field:F})=>v.jsxs(oa,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(ia,{children:"Interactive Segmentation"}),v.jsx(aa,{children:"Interactive Segmentation Model"})]}),v.jsxs(Uo,{onValueChange:F.onChange,defaultValue:F.value,disabled:!D,children:[v.jsx(sa,{children:v.jsx(go,{className:"w-auto",children:v.jsx(Vo,{placeholder:"Select interactive segmentation model"})})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:E==null?void 0:E.interactiveSegModels.map(N=>v.jsx(yo,{value:N,children:N},N))})})]})]})})]})}return v.jsxs(v.Fragment,{children:[v.jsx(HX,{open:S,children:v.jsx(x3,{children:v.jsx(b3,{children:v.jsxs("div",{className:"flex flex-col justify-center items-center gap-4",children:[v.jsxs("div",{role:"status",children:[v.jsxs("svg",{"aria-hidden":"true",className:"w-8 h-8 text-gray-200 animate-spin dark:text-gray-600 fill-primary",viewBox:"0 0 100 101",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[v.jsx("path",{d:"M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z",fill:"currentColor"}),v.jsx("path",{d:"M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z",fill:"currentFill"})]}),v.jsx("span",{className:"sr-only",children:"Loading..."})]}),y.map((F,N)=>v.jsx("div",{children:F},N))]})})})}),v.jsxs(Jm,{open:e,onOpenChange:U,children:[v.jsx(kx,{asChild:!0,children:v.jsx(yn,{tooltip:"Settings",children:v.jsx(sV,{})})}),v.jsxs(Hd,{className:"max-w-3xl h-[600px]",onOpenAutoFocus:F=>F.preventDefault(),children:[v.jsx(Kd,{children:"Settings"}),v.jsx(gn,{}),v.jsxs("div",{className:"flex flex-row space-x-8 h-full",children:[v.jsx("div",{className:"flex flex-col space-y-1",children:QX.map(F=>v.jsx(wn,{variant:"ghost",onClick:()=>r(F),className:Ce(n===F?"bg-muted ":"hover:bg-muted","justify-start"),children:F},F))}),v.jsx(gn,{orientation:"vertical"}),v.jsx(wX,{...x,children:v.jsx("div",{className:"flex w-full justify-center",children:v.jsxs("form",{onSubmit:x.handleSubmit(C),children:[n===F1?X():v.jsx(v.Fragment,{}),n===S3?ae():v.jsx(v.Fragment,{}),n===_3?V():v.jsx(v.Fragment,{}),v.jsx("div",{className:"absolute right-10 bottom-6",children:v.jsx(wn,{onClick:()=>U(!1),children:"Ok"})})]})})})]})]})]})]})}const eZ="/assets/kofi_button_black-XI_Dr2zg.png";function tZ(){return v.jsxs(Jm,{children:[v.jsx(kx,{asChild:!0,children:v.jsx(yn,{tooltip:"Buy me a coffee",children:v.jsx(XU,{})})}),v.jsxs(Hd,{children:[v.jsx(Kd,{children:"Buy me a coffee"}),v.jsx(vP,{className:"mb-8",children:"Hi, if you found my project is useful, please conside buy me a coffee to support my work. Thanks!"}),v.jsx("div",{className:"w-full flex items-center justify-center",children:v.jsx("a",{href:"https://ko-fi.com/Z8Z1CZJGY",target:"_blank",rel:"noreferrer",children:v.jsx("img",{src:eZ,className:"h-[32px]"})})})]})]})}const nZ=()=>{const[e,t,n,r,o,i,s,l,u,f,m,p,g,y]=bt(M=>[M.file,M.customMask,M.isInpainting,M.serverConfig,M.runMannually(),M.settings.enableUploadMask,M.settings.model,M.setFile,M.setCustomFile,M.runInpainting,M.showPrevMask,M.hidePrevMask,M.imageHeight,M.imageWidth]),{toast:b}=Id(),[S,E]=Px(t),[_,x]=d.useState(!1),C=()=>{f()},R=()=>{m()},P=()=>{p()};return v.jsxs("header",{className:"h-[60px] px-6 py-4 absolute top-[0] flex justify-between items-center w-full z-20 border-b backdrop-filter backdrop-blur-md bg-background/70",children:[v.jsxs("div",{className:"flex items-center gap-1",children:[r.enableFileManager?v.jsx(PY,{photoWidth:512,onPhotoClick:async(M,A)=>{try{const D=await Vj(M,A);l(D)}catch(D){b({variant:"destructive",description:D.message?D.message:D.toString()});return}}}):v.jsx(v.Fragment,{}),v.jsx(f1,{disabled:n,tooltip:"Upload image",onFileUpload:M=>{l(M)},children:v.jsx(tV,{})}),v.jsxs("div",{className:Ce(["flex items-center gap-1",e&&i?"visible":"hidden"]),children:[v.jsx(f1,{disabled:n,tooltip:"Upload custom mask",onFileUpload:async M=>{let A=null;try{A=await gF(M)}catch(D){b({variant:"destructive",description:D.message?D.message:D.toString()});return}if(A.naturalHeight!==g||A.naturalWidth!==y){b({variant:"destructive",description:`The size of the mask must same as image: ${y}x${g}`});return}u(M),o||f()},children:v.jsx(qT,{})}),t?v.jsxs(KW,{open:_,children:[v.jsx(GW,{className:"btn-primary side-panel-trigger",onMouseEnter:()=>x(!0),onMouseLeave:()=>x(!1),style:{visibility:t?"visible":"hidden",outline:"none"},onClick:()=>{},children:v.jsx(yn,{tooltip:"Run custom mask",children:v.jsx(uz,{})})}),v.jsx(MP,{children:E?v.jsx("img",{src:S.src,alt:"Custom mask"}):v.jsx(v.Fragment,{})})]}):v.jsx(v.Fragment,{})]}),e&&!s.need_prompt?v.jsx(yn,{disabled:n,tooltip:"Rerun previous mask",onClick:C,onMouseEnter:R,onMouseLeave:P,children:v.jsx(iV,{})}):v.jsx(v.Fragment,{})]}),s.need_prompt?v.jsx(yH,{}):v.jsx(v.Fragment,{}),v.jsxs("div",{className:"flex gap-1",children:[v.jsx(tZ,{}),v.jsx(MW,{}),r.disableModelSwitch?v.jsx(v.Fragment,{}):v.jsx(JX,{})]})]})};var Wr=function(e,t){return Number(e.toFixed(t))},rZ=function(e,t){return typeof e=="number"?e:t},Nt=function(e,t,n){n&&typeof n=="function"&&n(e,t)},oZ=function(e){return-Math.cos(e*Math.PI)/2+.5},iZ=function(e){return e},sZ=function(e){return e*e},aZ=function(e){return e*(2-e)},lZ=function(e){return e<.5?2*e*e:-1+(4-2*e)*e},cZ=function(e){return e*e*e},uZ=function(e){return--e*e*e+1},dZ=function(e){return e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1},fZ=function(e){return e*e*e*e},hZ=function(e){return 1- --e*e*e*e},pZ=function(e){return e<.5?8*e*e*e*e:1-8*--e*e*e*e},mZ=function(e){return e*e*e*e*e},gZ=function(e){return 1+--e*e*e*e*e},vZ=function(e){return e<.5?16*e*e*e*e*e:1+16*--e*e*e*e*e},E3={easeOut:oZ,linear:iZ,easeInQuad:sZ,easeOutQuad:aZ,easeInOutQuad:lZ,easeInCubic:cZ,easeOutCubic:uZ,easeInOutCubic:dZ,easeInQuart:fZ,easeOutQuart:hZ,easeInOutQuart:pZ,easeInQuint:mZ,easeOutQuint:gZ,easeInOutQuint:vZ},C3=function(e){typeof e=="number"&&cancelAnimationFrame(e)},jo=function(e){e.mounted&&(C3(e.animation),e.animate=!1,e.animation=null,e.velocity=null)};function $3(e,t,n,r){if(e.mounted){var o=new Date().getTime(),i=1;jo(e),e.animation=function(){if(!e.mounted)return C3(e.animation);var s=new Date().getTime()-o,l=s/n,u=E3[t],f=u(l);s>=n?(r(i),e.animation=null):e.animation&&(r(f),requestAnimationFrame(e.animation))},requestAnimationFrame(e.animation)}}function yZ(e){var t=e.scale,n=e.positionX,r=e.positionY;return!(Number.isNaN(t)||Number.isNaN(n)||Number.isNaN(r))}function Bs(e,t,n,r){var o=yZ(t);if(!(!e.mounted||!o)){var i=e.setTransformState,s=e.transformState,l=s.scale,u=s.positionX,f=s.positionY,m=t.scale-l,p=t.positionX-u,g=t.positionY-f;n===0?i(t.scale,t.positionX,t.positionY):$3(e,r,n,function(y){var b=l+m*y,S=u+p*y,E=f+g*y;i(b,S,E)})}}function wZ(e,t,n){var r=e.offsetWidth,o=e.offsetHeight,i=t.offsetWidth,s=t.offsetHeight,l=i*n,u=s*n,f=r-l,m=o-u;return{wrapperWidth:r,wrapperHeight:o,newContentWidth:l,newDiffWidth:f,newContentHeight:u,newDiffHeight:m}}var xZ=function(e,t,n,r,o,i,s){var l=e>t?n*(s?1:.5):0,u=r>o?i*(s?1:.5):0,f=e-t-l,m=l,p=r-o-u,g=u;return{minPositionX:f,maxPositionX:m,minPositionY:p,maxPositionY:g}},qx=function(e,t){var n=e.wrapperComponent,r=e.contentComponent,o=e.setup.centerZoomedOut;if(!n||!r)throw new Error("Components are not mounted");var i=wZ(n,r,t),s=i.wrapperWidth,l=i.wrapperHeight,u=i.newContentWidth,f=i.newDiffWidth,m=i.newContentHeight,p=i.newDiffHeight,g=xZ(s,u,f,l,m,p,!!o);return g},j1=function(e,t,n,r){return r?en?Wr(n,2):Wr(e,2):Wr(e,2)},vc=function(e,t){var n=qx(e,t);return e.bounds=n,n};function dg(e,t,n,r,o,i,s){var l=n.minPositionX,u=n.minPositionY,f=n.maxPositionX,m=n.maxPositionY,p=0,g=0;s&&(p=o,g=i);var y=j1(e,l-p,f+p,r),b=j1(t,u-g,m+g,r);return{x:y,y:b}}function fg(e,t,n,r,o,i){var s=e.transformState,l=s.scale,u=s.positionX,f=s.positionY,m=r-l;if(typeof t!="number"||typeof n!="number")return console.error("Mouse X and Y position were not provided!"),{x:u,y:f};var p=u-t*m,g=f-n*m,y=dg(p,g,o,i,0,0,null);return y}function Zd(e,t,n,r,o){var i=o?r:0,s=t-i;return!Number.isNaN(n)&&e>=n?n:!Number.isNaN(t)&&e<=s?s:e}var N2=function(e,t){var n=e.setup.panning.excluded,r=e.isInitialized,o=e.wrapperComponent,i=t.target,s=o==null?void 0:o.contains(i),l=r&&i&&s;if(!l)return!1;var u=hg(i,n);return!u},D2=function(e){var t=e.isInitialized,n=e.isPanning,r=e.setup,o=r.panning.disabled,i=t&&n&&!o;return!!i},bZ=function(e,t){var n=e.transformState,r=n.positionX,o=n.positionY;e.isPanning=!0;var i=t.clientX,s=t.clientY;e.startCoords={x:i-r,y:s-o}},SZ=function(e,t){var n=t.touches,r=e.transformState,o=r.positionX,i=r.positionY;e.isPanning=!0;var s=n.length===1;if(s){var l=n[0].clientX,u=n[0].clientY;e.startCoords={x:l-o,y:u-i}}};function _Z(e){var t=e.transformState,n=t.positionX,r=t.positionY,o=t.scale,i=e.setup,s=i.disabled,l=i.limitToBounds,u=i.centerZoomedOut,f=e.wrapperComponent;if(!(s||!f||!e.bounds)){var m=e.bounds,p=m.maxPositionX,g=m.minPositionX,y=m.maxPositionY,b=m.minPositionY,S=n>p||ny||rp?f.offsetWidth:e.setup.minPositionX||0,x=r>y?f.offsetHeight:e.setup.minPositionY||0,C=fg(e,_,x,o,e.bounds,l||u),R=C.x,P=C.y;return{scale:o,positionX:S?R:n,positionY:E?P:r}}}function EZ(e,t,n,r,o){var i=e.setup.limitToBounds,s=e.wrapperComponent,l=e.bounds,u=e.transformState,f=u.scale,m=u.positionX,p=u.positionY;if(!(s===null||l===null||t===m&&n===p)){var g=dg(t,n,l,i,r,o,s),y=g.x,b=g.y;e.setTransformState(f,y,b)}}var CZ=function(e,t,n){var r=e.startCoords,o=e.transformState,i=e.setup.panning,s=i.lockAxisX,l=i.lockAxisY,u=o.positionX,f=o.positionY;if(!r)return{x:u,y:f};var m=t-r.x,p=n-r.y,g=s?u:m,y=l?f:p;return{x:g,y}},sm=function(e,t){var n=e.setup,r=e.transformState,o=r.scale,i=n.minScale,s=n.disablePadding;return t>0&&o>=i&&!s?t:0},$Z=function(e){var t=e.mounted,n=e.setup,r=n.disabled,o=n.velocityAnimation,i=e.transformState.scale,s=o.disabled,l=!s||i>1||!r||t;return!!l},RZ=function(e){var t=e.mounted,n=e.velocity,r=e.bounds,o=e.setup,i=o.disabled,s=o.velocityAnimation,l=e.transformState.scale,u=s.disabled,f=!u||l>1||!i||t;return!(!f||!n||!r)};function kZ(e,t){var n=e.setup.velocityAnimation,r=n.equalToMove,o=n.animationTime,i=n.sensitivity;return r?o*t*i:o}function I2(e,t,n,r,o,i,s,l,u,f){if(o){if(t>s&&n>s){var m=s+(e-s)*f;return m>u?u:mi?i:m}}return r?t:j1(e,i,s,o)}function TZ(e,t){var n=1;return t?Math.min(n,e.offsetWidth/window.innerWidth):n}function PZ(e,t){var n=$Z(e);if(n){var r=e.lastMousePosition,o=e.velocityTime,i=e.setup,s=e.wrapperComponent,l=i.velocityAnimation.equalToMove,u=Date.now();if(r&&o&&s){var f=TZ(s,l),m=t.x-r.x,p=t.y-r.y,g=m/f,y=p/f,b=u-o,S=m*m+p*p,E=Math.sqrt(S)/b;e.velocity={velocityX:g,velocityY:y,total:E}}e.lastMousePosition=t,e.velocityTime=u}}function AZ(e){var t=e.velocity,n=e.bounds,r=e.setup,o=e.wrapperComponent,i=RZ(e);if(!(!i||!t||!n||!o)){var s=t.velocityX,l=t.velocityY,u=t.total,f=n.maxPositionX,m=n.minPositionX,p=n.maxPositionY,g=n.minPositionY,y=r.limitToBounds,b=r.alignmentAnimation,S=r.zoomAnimation,E=r.panning,_=E.lockAxisY,x=E.lockAxisX,C=S.animationType,R=b.sizeX,P=b.sizeY,M=b.velocityAlignmentTime,A=M,D=kZ(e,u),U=Math.max(D,A),W=sm(e,R),q=sm(e,P),X=W*o.offsetWidth/100,ae=q*o.offsetHeight/100,V=f+X,F=m-X,N=p+ae,ie=g-ae,K=e.transformState,Z=new Date().getTime();$3(e,C,U,function(H){var se=e.transformState,ce=se.scale,Ve=se.positionX,Ue=se.positionY,We=new Date().getTime()-Z,Oe=We/A,he=E3[b.animationType],xe=1-he(Math.min(1,Oe)),$e=1-H,Ae=Ve+s*$e,Me=Ue+l*$e,je=I2(Ae,K.positionX,Ve,x,y,m,f,F,V,xe),Mt=I2(Me,K.positionY,Ue,_,y,g,p,ie,N,xe);(Ve!==Ae||Ue!==Me)&&e.setTransformState(ce,je,Mt)})}}function L2(e,t){var n=e.transformState.scale;jo(e),vc(e,n),window.TouchEvent!==void 0&&t instanceof TouchEvent?SZ(e,t):bZ(e,t)}function R3(e){var t=e.transformState.scale,n=e.setup,r=n.minScale,o=n.alignmentAnimation,i=o.disabled,s=o.sizeX,l=o.sizeY,u=o.animationTime,f=o.animationType,m=i||t.1&&p;g?AZ(e):R3(e)}}function Qx(e,t,n,r){var o=e.setup,i=o.minScale,s=o.maxScale,l=o.limitToBounds,u=Zd(Wr(t,2),i,s,0,!1),f=vc(e,u),m=fg(e,n,r,u,f,l),p=m.x,g=m.y;return{scale:u,positionX:p,positionY:g}}function k3(e,t,n){var r=e.transformState.scale,o=e.wrapperComponent,i=e.setup,s=i.minScale,l=i.limitToBounds,u=i.zoomAnimation,f=u.disabled,m=u.animationTime,p=u.animationType,g=f||r>=s;if((r>=1||l)&&R3(e),!(g||!o||!e.mounted)){var y=t||o.offsetWidth/2,b=n||o.offsetHeight/2,S=Qx(e,s,y,b);S&&Bs(e,S,m,p)}}var $s=function(){return $s=Object.assign||function(t){for(var n,r=1,o=arguments.length;rs||Math.sign(n.deltaY)!==Math.sign(t.deltaY)||n.deltaY>0&&n.deltaYt.deltaY||Math.sign(n.deltaY)!==Math.sign(t.deltaY):!1},XZ=function(e,t){var n=e.setup.pinch,r=n.disabled,o=n.excluded,i=e.isInitialized,s=t.target,l=i&&!r&&s;if(!l)return!1;var u=hg(s,o);return!u},ZZ=function(e){var t=e.setup.pinch.disabled,n=e.isInitialized,r=e.pinchStartDistance,o=n&&!t&&r;return!!o},qZ=function(e,t,n){var r=n.getBoundingClientRect(),o=e.touches,i=Wr(o[0].clientX-r.left,5),s=Wr(o[0].clientY-r.top,5),l=Wr(o[1].clientX-r.left,5),u=Wr(o[1].clientY-r.top,5);return{x:(i+l)/2/t,y:(s+u)/2/t}},D3=function(e){return Math.sqrt(Math.pow(e.touches[0].pageX-e.touches[1].pageX,2)+Math.pow(e.touches[0].pageY-e.touches[1].pageY,2))},QZ=function(e,t){var n=e.pinchStartScale,r=e.pinchStartDistance,o=e.setup,i=o.maxScale,s=o.minScale,l=o.zoomAnimation,u=o.disablePadding,f=l.size,m=l.disabled;if(!n||r===null||!t)throw new Error("Pinch touches distance was not provided");if(t<0)return e.transformState.scale;var p=t/r,g=p*n;return Zd(Wr(g,2),s,i,f,!m&&!u)},JZ=160,eq=100,tq=function(e,t){var n=e.props,r=n.onWheelStart,o=n.onZoomStart;e.wheelStopEventTimer||(jo(e),Nt(_t(e),t,r),Nt(_t(e),t,o))},nq=function(e,t){var n=e.props,r=n.onWheel,o=n.onZoom,i=e.contentComponent,s=e.setup,l=e.transformState,u=l.scale,f=s.limitToBounds,m=s.centerZoomedOut,p=s.zoomAnimation,g=s.wheel,y=s.disablePadding,b=s.smooth,S=p.size,E=p.disabled,_=g.step,x=g.smoothStep;if(!i)throw new Error("Component not mounted");t.preventDefault(),t.stopPropagation();var C=KZ(t,null),R=b?x*Math.abs(t.deltaY):_,P=GZ(e,C,R,!t.ctrlKey);if(u!==P){var M=vc(e,P),A=N3(t,i,u),D=E||S===0||m||y,U=f&&D,W=fg(e,A.x,A.y,P,M,U),q=W.x,X=W.y;e.previousWheelEvent=t,e.setTransformState(P,q,X),Nt(_t(e),t,r),Nt(_t(e),t,o)}},rq=function(e,t){var n=e.props,r=n.onWheelStop,o=n.onZoomStop;B1(e.wheelAnimationTimer),e.wheelAnimationTimer=setTimeout(function(){e.mounted&&(k3(e,t.x,t.y),e.wheelAnimationTimer=null)},eq);var i=YZ(e,t);i&&(B1(e.wheelStopEventTimer),e.wheelStopEventTimer=setTimeout(function(){e.mounted&&(e.wheelStopEventTimer=null,Nt(_t(e),t,r),Nt(_t(e),t,o))},JZ))},oq=function(e,t){var n=D3(t);e.pinchStartDistance=n,e.lastDistance=n,e.pinchStartScale=e.transformState.scale,e.isPanning=!1,jo(e)},iq=function(e,t){var n=e.contentComponent,r=e.pinchStartDistance,o=e.transformState.scale,i=e.setup,s=i.limitToBounds,l=i.centerZoomedOut,u=i.zoomAnimation,f=u.disabled,m=u.size;if(!(r===null||!n)){var p=qZ(t,o,n);if(!(!Number.isFinite(p.x)||!Number.isFinite(p.y))){var g=D3(t),y=QZ(e,g);if(y!==o){var b=vc(e,y),S=f||m===0||l,E=s&&S,_=fg(e,p.x,p.y,y,b,E),x=_.x,C=_.y;e.pinchMidpoint=p,e.lastDistance=g,e.setTransformState(y,x,C)}}}},sq=function(e){var t=e.pinchMidpoint;e.velocity=null,e.lastDistance=null,e.pinchMidpoint=null,e.pinchStartScale=null,e.pinchStartDistance=null,k3(e,t==null?void 0:t.x,t==null?void 0:t.y)},I3=function(e,t){var n=e.props.onZoomStop,r=e.setup.doubleClick.animationTime;B1(e.doubleClickStopEventTimer),e.doubleClickStopEventTimer=setTimeout(function(){e.doubleClickStopEventTimer=null,Nt(_t(e),t,n)},r)},aq=function(e,t){var n=e.props,r=n.onZoomStart,o=n.onZoom,i=e.setup.doubleClick,s=i.animationTime,l=i.animationType;Nt(_t(e),t,r),M3(e,s,l,function(){return Nt(_t(e),t,o)}),I3(e,t)};function lq(e,t){var n=e.setup,r=e.doubleClickStopEventTimer,o=e.transformState,i=e.contentComponent,s=o.scale,l=e.props,u=l.onZoomStart,f=l.onZoom,m=n.doubleClick,p=m.disabled,g=m.mode,y=m.step,b=m.animationTime,S=m.animationType;if(!p&&!r){if(g==="reset")return aq(e,t);if(!i)return console.error("No ContentComponent found");var E=g==="zoomOut"?-1:1,_=P3(e,E,y);if(s!==_){Nt(_t(e),t,u);var x=N3(t,i,s),C=Qx(e,_,x.x,x.y);if(!C)return console.error("Error during zoom event. New transformation state was not calculated.");Nt(_t(e),t,f),Bs(e,C,b,S),I3(e,t)}}}var cq=function(e,t){var n=e.isInitialized,r=e.setup,o=e.wrapperComponent,i=r.doubleClick,s=i.disabled,l=i.excluded,u=t.target,f=o==null?void 0:o.contains(u),m=n&&u&&f&&!s;if(!m)return!1;var p=hg(u,l);return!p},uq=function(){function e(t){var n=this;this.mounted=!0,this.onChangeCallbacks=new Set,this.onInitCallbacks=new Set,this.wrapperComponent=null,this.contentComponent=null,this.isInitialized=!1,this.bounds=null,this.previousWheelEvent=null,this.wheelStopEventTimer=null,this.wheelAnimationTimer=null,this.isPanning=!1,this.startCoords=null,this.lastTouch=null,this.distance=null,this.lastDistance=null,this.pinchStartDistance=null,this.pinchStartScale=null,this.pinchMidpoint=null,this.doubleClickStopEventTimer=null,this.velocity=null,this.velocityTime=null,this.lastMousePosition=null,this.animate=!1,this.animation=null,this.maxBounds=null,this.pressedKeys={},this.mount=function(){n.initializeWindowEvents()},this.unmount=function(){n.cleanupWindowEvents()},this.update=function(r){vc(n,n.transformState.scale),n.setup=z2(r)},this.initializeWindowEvents=function(){var r,o=j0(),i=(r=n.wrapperComponent)===null||r===void 0?void 0:r.ownerDocument,s=i==null?void 0:i.defaultView;s==null||s.addEventListener("mousedown",n.onPanningStart,o),s==null||s.addEventListener("mousemove",n.onPanning,o),s==null||s.addEventListener("mouseup",n.onPanningStop,o),i==null||i.addEventListener("mouseleave",n.clearPanning,o),s==null||s.addEventListener("keyup",n.setKeyUnPressed,o),s==null||s.addEventListener("keydown",n.setKeyPressed,o)},this.cleanupWindowEvents=function(){var r,o,i=j0(),s=(r=n.wrapperComponent)===null||r===void 0?void 0:r.ownerDocument,l=s==null?void 0:s.defaultView;l==null||l.removeEventListener("mousedown",n.onPanningStart,i),l==null||l.removeEventListener("mousemove",n.onPanning,i),l==null||l.removeEventListener("mouseup",n.onPanningStop,i),s==null||s.removeEventListener("mouseleave",n.clearPanning,i),l==null||l.removeEventListener("keyup",n.setKeyUnPressed,i),l==null||l.removeEventListener("keydown",n.setKeyPressed,i),document.removeEventListener("mouseleave",n.clearPanning,i),jo(n),(o=n.observer)===null||o===void 0||o.disconnect()},this.handleInitializeWrapperEvents=function(r){var o=j0();r.addEventListener("wheel",n.onWheelZoom,o),r.addEventListener("dblclick",n.onDoubleClick,o),r.addEventListener("touchstart",n.onTouchPanningStart,o),r.addEventListener("touchmove",n.onTouchPanning,o),r.addEventListener("touchend",n.onTouchPanningStop,o)},this.handleInitialize=function(r){var o=n.setup.centerOnInit;n.applyTransformation(),n.onInitCallbacks.forEach(function(i){return i(_t(n))}),o&&(n.setCenter(),n.observer=new ResizeObserver(function(){var i;n.onInitCallbacks.forEach(function(s){return s(_t(n))}),n.setCenter(),(i=n.observer)===null||i===void 0||i.disconnect()}),n.observer.observe(r))},this.onWheelZoom=function(r){var o=n.setup.disabled;if(!o){var i=WZ(n,r);if(i){var s=n.isPressingKeys(n.setup.wheel.activationKeys);s&&(tq(n,r),nq(n,r),rq(n,r))}}},this.onPanningStart=function(r){var o=n.setup.disabled,i=n.props.onPanningStart;if(!o){var s=N2(n,r);if(s){var l=n.isPressingKeys(n.setup.panning.activationKeys);l&&(r.button===0&&!n.setup.panning.allowLeftClickPan||r.button===1&&!n.setup.panning.allowMiddleClickPan||r.button===2&&!n.setup.panning.allowRightClickPan||(r.preventDefault(),r.stopPropagation(),jo(n),L2(n,r),Nt(_t(n),r,i)))}}},this.onPanning=function(r){var o=n.setup.disabled,i=n.props.onPanning;if(!o){var s=D2(n);if(s){var l=n.isPressingKeys(n.setup.panning.activationKeys);l&&(r.preventDefault(),r.stopPropagation(),F2(n,r.clientX,r.clientY),Nt(_t(n),r,i))}}},this.onPanningStop=function(r){var o=n.props.onPanningStop;n.isPanning&&(MZ(n),Nt(_t(n),r,o))},this.onPinchStart=function(r){var o=n.setup.disabled,i=n.props,s=i.onPinchingStart,l=i.onZoomStart;if(!o){var u=XZ(n,r);u&&(oq(n,r),jo(n),Nt(_t(n),r,s),Nt(_t(n),r,l))}},this.onPinch=function(r){var o=n.setup.disabled,i=n.props,s=i.onPinching,l=i.onZoom;if(!o){var u=ZZ(n);u&&(r.preventDefault(),r.stopPropagation(),iq(n,r),Nt(_t(n),r,s),Nt(_t(n),r,l))}},this.onPinchStop=function(r){var o=n.props,i=o.onPinchingStop,s=o.onZoomStop;n.pinchStartScale&&(sq(n),Nt(_t(n),r,i),Nt(_t(n),r,s))},this.onTouchPanningStart=function(r){var o=n.setup.disabled,i=n.props.onPanningStart;if(!o){var s=N2(n,r);if(s){var l=n.lastTouch&&+new Date-n.lastTouch<200;if(l&&r.touches.length===1)n.onDoubleClick(r);else{n.lastTouch=+new Date,jo(n);var u=r.touches,f=u.length===1,m=u.length===2;f&&(jo(n),L2(n,r),Nt(_t(n),r,i)),m&&n.onPinchStart(r)}}}},this.onTouchPanning=function(r){var o=n.setup.disabled,i=n.props.onPanning;if(n.isPanning&&r.touches.length===1){if(o)return;var s=D2(n);if(!s)return;r.preventDefault(),r.stopPropagation();var l=r.touches[0];F2(n,l.clientX,l.clientY),Nt(_t(n),r,i)}else r.touches.length>1&&n.onPinch(r)},this.onTouchPanningStop=function(r){n.onPanningStop(r),n.onPinchStop(r)},this.onDoubleClick=function(r){var o=n.setup.disabled;if(!o){var i=cq(n,r);i&&lq(n,r)}},this.clearPanning=function(r){n.isPanning&&n.onPanningStop(r)},this.setKeyPressed=function(r){n.pressedKeys[r.key]=!0},this.setKeyUnPressed=function(r){n.pressedKeys[r.key]=!1},this.isPressingKeys=function(r){return r.length?!!r.find(function(o){return n.pressedKeys[o]}):!0},this.setTransformState=function(r,o,i){var s=n.props.onTransformed;if(!Number.isNaN(r)&&!Number.isNaN(o)&&!Number.isNaN(i)){r!==n.transformState.scale&&(n.transformState.previousScale=n.transformState.scale,n.transformState.scale=r),n.transformState.positionX=o,n.transformState.positionY=i,n.applyTransformation();var l=_t(n);n.onChangeCallbacks.forEach(function(u){return u(l)}),Nt(l,{scale:r,positionX:o,positionY:i},s)}else console.error("Detected NaN set state values")},this.setCenter=function(){if(n.wrapperComponent&&n.contentComponent){var r=O3(n.transformState.scale,n.wrapperComponent,n.contentComponent);n.setTransformState(r.scale,r.positionX,r.positionY)}},this.handleTransformStyles=function(r,o,i){return n.props.customTransform?n.props.customTransform(r,o,i):UZ(r,o,i)},this.applyTransformation=function(){if(!(!n.mounted||!n.contentComponent)){var r=n.transformState,o=r.scale,i=r.positionX,s=r.positionY,l=n.handleTransformStyles(i,s,o);n.contentComponent.style.transform=l}},this.getContext=function(){return _t(n)},this.onChange=function(r){return n.onChangeCallbacks.has(r)||n.onChangeCallbacks.add(r),function(){n.onChangeCallbacks.delete(r)}},this.onInit=function(r){return n.onInitCallbacks.has(r)||n.onInitCallbacks.add(r),function(){n.onInitCallbacks.delete(r)}},this.init=function(r,o){n.cleanupWindowEvents(),n.wrapperComponent=r,n.contentComponent=o,vc(n,n.transformState.scale),n.handleInitializeWrapperEvents(r),n.handleInitialize(o),n.initializeWindowEvents(),n.isInitialized=!0;var i=_t(n);Nt(i,void 0,n.props.onInit)},this.props=t,this.setup=z2(this.props),this.transformState=T3(this.props)}return e}(),Jx=Fe.createContext(null),dq=function(e,t){return typeof e=="function"?e(t):e},fq=Fe.forwardRef(function(e,t){var n=d.useRef(new uq(e)).current,r=dq(e.children,z1(n));return d.useImperativeHandle(t,function(){return z1(n)},[n]),d.useEffect(function(){n.update(e)},[n,e]),Fe.createElement(Jx.Provider,{value:n},r)});Fe.forwardRef(function(e,t){var n=d.useRef(null),r=d.useContext(Jx);return d.useEffect(function(){return r.onChange(function(o){if(n.current){var i=0,s=0;n.current.style.transform=r.handleTransformStyles(i,s,1/o.instance.transformState.scale)}})},[r]),Fe.createElement("div",$s({},e,{ref:VZ([n,t])}))});function hq(e,t){t===void 0&&(t={});var n=t.insertAt;if(!(!e||typeof document>"u")){var r=document.head||document.getElementsByTagName("head")[0],o=document.createElement("style");o.type="text/css",n==="top"&&r.firstChild?r.insertBefore(o,r.firstChild):r.appendChild(o),o.styleSheet?o.styleSheet.cssText=e:o.appendChild(document.createTextNode(e))}}var pq=`.transform-component-module_wrapper__SPB86 { + position: relative; + width: -moz-fit-content; + width: fit-content; + height: -moz-fit-content; + height: fit-content; + overflow: hidden; + -webkit-touch-callout: none; /* iOS Safari */ + -webkit-user-select: none; /* Safari */ + -khtml-user-select: none; /* Konqueror HTML */ + -moz-user-select: none; /* Firefox */ + -ms-user-select: none; /* Internet Explorer/Edge */ + user-select: none; + margin: 0; + padding: 0; +} +.transform-component-module_content__FBWxo { + display: flex; + flex-wrap: wrap; + width: -moz-fit-content; + width: fit-content; + height: -moz-fit-content; + height: fit-content; + margin: 0; + padding: 0; + transform-origin: 0% 0%; +} +.transform-component-module_content__FBWxo img { + pointer-events: none; +} +`,B2={wrapper:"transform-component-module_wrapper__SPB86",content:"transform-component-module_content__FBWxo"};hq(pq);var mq=function(e){var t=e.children,n=e.wrapperClass,r=n===void 0?"":n,o=e.contentClass,i=o===void 0?"":o,s=e.wrapperStyle,l=e.contentStyle,u=e.wrapperProps,f=u===void 0?{}:u,m=e.contentProps,p=m===void 0?{}:m,g=d.useContext(Jx),y=g.init,b=g.cleanupWindowEvents,S=d.useRef(null),E=d.useRef(null);return d.useEffect(function(){var _=S.current,x=E.current;return _!==null&&x!==null&&y&&(y==null||y(_,x)),function(){b==null||b()}},[]),Fe.createElement("div",$s({},f,{ref:S,className:"react-transform-wrapper ".concat(B2.wrapper," ").concat(r),style:s}),Fe.createElement("div",$s({},p,{ref:E,className:"react-transform-component ".concat(B2.content," ").concat(i),style:l}),t))};const L3=["PageUp","PageDown"],F3=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],j3={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},qd="Slider",[U1,gq,vq]=Gd(qd),[z3,Cte]=Mn(qd,[vq]),[yq,pg]=z3(qd),wq=d.forwardRef((e,t)=>{const{name:n,min:r=0,max:o=100,step:i=1,orientation:s="horizontal",disabled:l=!1,minStepsBetweenThumbs:u=0,defaultValue:f=[r],value:m,onValueChange:p=()=>{},onValueCommit:g=()=>{},inverted:y=!1,...b}=e,[S,E]=d.useState(null),_=Be(t,V=>E(V)),x=d.useRef(new Set),C=d.useRef(0),R=s==="horizontal",P=S?!!S.closest("form"):!0,M=R?xq:bq,[A=[],D]=Zr({prop:m,defaultProp:f,onChange:V=>{var F;(F=[...x.current][C.current])===null||F===void 0||F.focus(),p(V)}}),U=d.useRef(A);function W(V){const F=Pq(A,V);ae(V,F)}function q(V){ae(V,C.current)}function X(){const V=U.current[C.current];A[C.current]!==V&&g(A)}function ae(V,F,{commit:N}={commit:!1}){const ie=Nq(i),K=Dq(Math.round((V-r)/i)*i+r,ie),Z=fd(K,[r,o]);D((H=[])=>{const se=kq(H,Z,F);if(Oq(se,u*i)){C.current=se.indexOf(Z);const ce=String(se)!==String(H);return ce&&N&&g(se),ce?se:H}else return H})}return d.createElement(yq,{scope:e.__scopeSlider,disabled:l,min:r,max:o,valueIndexToChangeRef:C,thumbs:x.current,values:A,orientation:s},d.createElement(U1.Provider,{scope:e.__scopeSlider},d.createElement(U1.Slot,{scope:e.__scopeSlider},d.createElement(M,Y({"aria-disabled":l,"data-disabled":l?"":void 0},b,{ref:_,onPointerDown:de(b.onPointerDown,()=>{l||(U.current=A)}),min:r,max:o,inverted:y,onSlideStart:l?void 0:W,onSlideMove:l?void 0:q,onSlideEnd:l?void 0:X,onHomeKeyDown:()=>!l&&ae(r,0,{commit:!0}),onEndKeyDown:()=>!l&&ae(o,A.length-1,{commit:!0}),onStepKeyDown:({event:V,direction:F})=>{if(!l){const K=L3.includes(V.key)||V.shiftKey&&F3.includes(V.key)?10:1,Z=C.current,H=A[Z],se=i*K*F;ae(H+se,Z,{commit:!0})}}})))),P&&A.map((V,F)=>d.createElement(Rq,{key:F,name:n?n+(A.length>1?"[]":""):void 0,value:V})))}),[B3,U3]=z3(qd,{startEdge:"left",endEdge:"right",size:"width",direction:1}),xq=d.forwardRef((e,t)=>{const{min:n,max:r,dir:o,inverted:i,onSlideStart:s,onSlideMove:l,onSlideEnd:u,onStepKeyDown:f,...m}=e,[p,g]=d.useState(null),y=Be(t,C=>g(C)),b=d.useRef(),S=Tc(o),E=S==="ltr",_=E&&!i||!E&&i;function x(C){const R=b.current||p.getBoundingClientRect(),P=[0,R.width],A=eb(P,_?[n,r]:[r,n]);return b.current=R,A(C-R.left)}return d.createElement(B3,{scope:e.__scopeSlider,startEdge:_?"left":"right",endEdge:_?"right":"left",direction:_?1:-1,size:"width"},d.createElement(V3,Y({dir:S,"data-orientation":"horizontal"},m,{ref:y,style:{...m.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:C=>{const R=x(C.clientX);s==null||s(R)},onSlideMove:C=>{const R=x(C.clientX);l==null||l(R)},onSlideEnd:()=>{b.current=void 0,u==null||u()},onStepKeyDown:C=>{const P=j3[_?"from-left":"from-right"].includes(C.key);f==null||f({event:C,direction:P?-1:1})}})))}),bq=d.forwardRef((e,t)=>{const{min:n,max:r,inverted:o,onSlideStart:i,onSlideMove:s,onSlideEnd:l,onStepKeyDown:u,...f}=e,m=d.useRef(null),p=Be(t,m),g=d.useRef(),y=!o;function b(S){const E=g.current||m.current.getBoundingClientRect(),_=[0,E.height],C=eb(_,y?[r,n]:[n,r]);return g.current=E,C(S-E.top)}return d.createElement(B3,{scope:e.__scopeSlider,startEdge:y?"bottom":"top",endEdge:y?"top":"bottom",size:"height",direction:y?1:-1},d.createElement(V3,Y({"data-orientation":"vertical"},f,{ref:p,style:{...f.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:S=>{const E=b(S.clientY);i==null||i(E)},onSlideMove:S=>{const E=b(S.clientY);s==null||s(E)},onSlideEnd:()=>{g.current=void 0,l==null||l()},onStepKeyDown:S=>{const _=j3[y?"from-bottom":"from-top"].includes(S.key);u==null||u({event:S,direction:_?-1:1})}})))}),V3=d.forwardRef((e,t)=>{const{__scopeSlider:n,onSlideStart:r,onSlideMove:o,onSlideEnd:i,onHomeKeyDown:s,onEndKeyDown:l,onStepKeyDown:u,...f}=e,m=pg(qd,n);return d.createElement(Pe.span,Y({},f,{ref:t,onKeyDown:de(e.onKeyDown,p=>{p.key==="Home"?(s(p),p.preventDefault()):p.key==="End"?(l(p),p.preventDefault()):L3.concat(F3).includes(p.key)&&(u(p),p.preventDefault())}),onPointerDown:de(e.onPointerDown,p=>{const g=p.target;g.setPointerCapture(p.pointerId),p.preventDefault(),m.thumbs.has(g)?g.focus():r(p)}),onPointerMove:de(e.onPointerMove,p=>{p.target.hasPointerCapture(p.pointerId)&&o(p)}),onPointerUp:de(e.onPointerUp,p=>{const g=p.target;g.hasPointerCapture(p.pointerId)&&(g.releasePointerCapture(p.pointerId),i(p))})}))}),Sq="SliderTrack",_q=d.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,o=pg(Sq,n);return d.createElement(Pe.span,Y({"data-disabled":o.disabled?"":void 0,"data-orientation":o.orientation},r,{ref:t}))}),U2="SliderRange",Eq=d.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,o=pg(U2,n),i=U3(U2,n),s=d.useRef(null),l=Be(t,s),u=o.values.length,f=o.values.map(g=>W3(g,o.min,o.max)),m=u>1?Math.min(...f):0,p=100-Math.max(...f);return d.createElement(Pe.span,Y({"data-orientation":o.orientation,"data-disabled":o.disabled?"":void 0},r,{ref:l,style:{...e.style,[i.startEdge]:m+"%",[i.endEdge]:p+"%"}}))}),V2="SliderThumb",Cq=d.forwardRef((e,t)=>{const n=gq(e.__scopeSlider),[r,o]=d.useState(null),i=Be(t,l=>o(l)),s=d.useMemo(()=>r?n().findIndex(l=>l.ref.current===r):-1,[n,r]);return d.createElement($q,Y({},e,{ref:i,index:s}))}),$q=d.forwardRef((e,t)=>{const{__scopeSlider:n,index:r,...o}=e,i=pg(V2,n),s=U3(V2,n),[l,u]=d.useState(null),f=Be(t,E=>u(E)),m=yx(l),p=i.values[r],g=p===void 0?0:W3(p,i.min,i.max),y=Tq(r,i.values.length),b=m==null?void 0:m[s.size],S=b?Aq(b,g,s.direction):0;return d.useEffect(()=>{if(l)return i.thumbs.add(l),()=>{i.thumbs.delete(l)}},[l,i.thumbs]),d.createElement("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[s.startEdge]:`calc(${g}% + ${S}px)`}},d.createElement(U1.ItemSlot,{scope:e.__scopeSlider},d.createElement(Pe.span,Y({role:"slider","aria-label":e["aria-label"]||y,"aria-valuemin":i.min,"aria-valuenow":p,"aria-valuemax":i.max,"aria-orientation":i.orientation,"data-orientation":i.orientation,"data-disabled":i.disabled?"":void 0,tabIndex:i.disabled?void 0:0},o,{ref:f,style:p===void 0?{display:"none"}:e.style,onFocus:de(e.onFocus,()=>{i.valueIndexToChangeRef.current=r})}))))}),Rq=e=>{const{value:t,...n}=e,r=d.useRef(null),o=zx(t);return d.useEffect(()=>{const i=r.current,s=window.HTMLInputElement.prototype,u=Object.getOwnPropertyDescriptor(s,"value").set;if(o!==t&&u){const f=new Event("input",{bubbles:!0});u.call(i,t),i.dispatchEvent(f)}},[o,t]),d.createElement("input",Y({style:{display:"none"}},n,{ref:r,defaultValue:t}))};function kq(e=[],t,n){const r=[...e];return r[n]=t,r.sort((o,i)=>o-i)}function W3(e,t,n){const i=100/(n-t)*(e-t);return fd(i,[0,100])}function Tq(e,t){return t>2?`Value ${e+1} of ${t}`:t===2?["Minimum","Maximum"][e]:void 0}function Pq(e,t){if(e.length===1)return 0;const n=e.map(o=>Math.abs(o-t)),r=Math.min(...n);return n.indexOf(r)}function Aq(e,t,n){const r=e/2,i=eb([0,50],[0,r]);return(r-i(t)*n)*n}function Mq(e){return e.slice(0,-1).map((t,n)=>e[n+1]-t)}function Oq(e,t){if(t>0){const n=Mq(e);return Math.min(...n)>=t}return!0}function eb(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 Nq(e){return(String(e).split(".")[1]||"").length}function Dq(e,t){const n=Math.pow(10,t);return Math.round(e*n)/n}const H3=wq,Iq=_q,Lq=Eq,Fq=Cq,uo=d.forwardRef(({className:e,...t},n)=>v.jsxs(H3,{ref:n,className:Ce("relative flex w-full touch-none select-none items-center",e),tabIndex:-1,...t,children:[v.jsx(Iq,{className:"relative h-1.5 w-full grow overflow-hidden rounded-full bg-primary/20 data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50",children:v.jsx(Lq,{className:"absolute h-full bg-primary data-[disabled]:cursor-not-allowed "})}),v.jsx(Fq,{tabIndex:-1,className:"block h-4 w-4 rounded-full border border-primary/60 bg-background shadow transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring data-[disabled]:cursor-not-allowed"})]}));uo.displayName=H3.displayName;const ll={capture:!0,passive:!1},jq=2,W2=(e,t,n,r,o,i)=>{if(e!==n&&t===r){if(e<0)return[0,r];if(e+t>i)return[i-r,r]}else{if(ti)return[e,i-e]}return[e,t]},zq=e=>{const{minHeight:t,minWidth:n,maxHeight:r,maxWidth:o,scale:i,show:s}=e,[l,u,f,m,{x:p,y:g,width:y,height:b},S,E,_,x,C,R]=bt(H=>[H.imageWidth,H.imageHeight,H.isInpainting,H.isSD(),H.cropperState,H.setCropperX,H.setCropperY,H.setCropperWidth,H.setCropperHeight,H.isCropperExtenderResizing,H.setIsCropperExtenderResizing]),[P,M]=d.useState(!1);d.useEffect(()=>{S(Math.round((o-512)/2)),E(Math.round((r-512)/2))},[r,o,l,u]);const[A,D]=d.useState({initX:0,initY:0,initHeight:0,initWidth:0,startResizeX:0,startResizeY:0,ord:"top"}),U=()=>{},W=(H,se)=>W2(H,se,p,y,n,o),q=(H,se)=>W2(H,se,g,b,t,r),X=H=>{if(f)return;const se=H.clientX,ce=H.clientY,Ve=Math.round((ce-A.startResizeY)/i),Ue=Math.round((se-A.startResizeX)/i),We=()=>{const $e=A.initHeight-Ve,Ae=A.initY+Ve,[Me,je]=q(Ae,$e);x(je),E(Me)},Oe=()=>{const $e=A.initHeight+Ve,[Ae,Me]=q(A.initY,$e);x(Me),E(Ae)},he=()=>{const $e=A.initWidth-Ue,Ae=A.initX+Ue,[Me,je]=W(Ae,$e);_(je),S(Me)},xe=()=>{const $e=A.initWidth+Ue,[Ae,Me]=W(A.initX,$e);_(Me),S(Ae)};if(C)switch(A.ord){case"topleft":{We(),he();break}case"topright":{We(),xe();break}case"bottomleft":{Oe(),he();break}case"bottomright":{Oe(),xe();break}case"top":{We();break}case"right":{xe();break}case"bottom":{Oe();break}case"left":{he();break}}if(P){const $e=A.initX+Ue,Ae=A.initY+Ve,[Me,je]=W($e,A.initWidth),[Mt,ct]=q(Ae,A.initHeight);_(je),x(ct),S(Me),E(Mt)}},ae=()=>{C&&R(!1),P&&M(!1)};d.useEffect(()=>{if(C||P)return document.addEventListener("pointermove",X,ll),document.addEventListener("pointerup",ae,ll),document.addEventListener("pointercancel",ae,ll),()=>{document.removeEventListener("pointermove",X,ll),document.removeEventListener("pointerup",ae,ll),document.removeEventListener("pointercancel",ae,ll)}},[C,P,y,b,A]);const V=H=>{const{ord:se}=H.target.dataset;se&&(R(!0),D({initX:p,initY:g,initHeight:b,initWidth:y,startResizeX:H.clientX,startResizeY:H.clientY,ord:se}))},F=(H,se,ce)=>{const We="w-[12px] h-[12px] z-[4] absolute content-[''] block border-2 border-primary borde pointer-events-auto hover:bg-primary";let Oe="0",he="0",xe=ce,$e="-6px";return ce===""&&($e="50%",se==="left"||se==="right"?(xe="top",he="-50%"):(xe="left",Oe="-50%")),v.jsx("div",{className:Ce(We,H),style:{[se]:-6,[xe]:$e,transform:`translate(${Oe}, ${he}) scale(${1/i})`},"data-ord":se+ce,"aria-label":se+ce,tabIndex:-1,role:"button"})},N=()=>v.jsxs("div",{onFocus:U,onPointerDown:V,className:"absolute top-0 h-full w-full",children:[v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 w-full cursor-ns-resize h-[12px] mt-[-6px]","data-ord":"top"}),v.jsx("div",{className:"absolute pointer-events-auto top-0 right-0 h-full cursor-ew-resize w-[12px] mr-[-6px]","data-ord":"right"}),v.jsx("div",{className:"absolute pointer-events-auto bottom-0 left-0 w-full cursor-ns-resize h-[12px] mb-[-6px]","data-ord":"bottom"}),v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 h-full cursor-ew-resize w-[12px] ml-[-6px]","data-ord":"left"}),F("cursor-nw-resize","top","left"),F("cursor-ne-resize","top","right"),F("cursor-sw-resize","bottom","left"),F("cursor-se-resize","bottom","right"),F("cursor-ns-resize","top",""),F("cursor-ns-resize","bottom",""),F("cursor-ew-resize","left",""),F("cursor-ew-resize","right","")]}),ie=H=>{M(!0),D({initX:p,initY:g,initHeight:b,initWidth:y,startResizeX:H.clientX,startResizeY:H.clientY,ord:""})},K=()=>v.jsxs("div",{className:tx("border absolute pointer-events-auto px-2 py-1 rounded-full hover:cursor-move bg-background","origin-top-left top-0 left-0"),style:{transform:`scale(${1/i*.8})`},onPointerDown:ie,children:[y," x ",b]}),Z=()=>v.jsx("div",{className:"outline-dashed outline-primary",style:{height:b,width:y,outlineWidth:`${jq/i*1.3}px`}});return s===!1||!m?null:v.jsx("div",{className:"absolute h-full w-full overflow-hidden pointer-events-none z-[2]",children:v.jsxs("div",{className:"relative pointer-events-none z-[2] [box-shadow:0_0_0_9999px_rgba(0,_0,_0,_0.5)]",style:{height:b,width:y,left:p,top:g},children:[Z(),K(),N()]})})},Bq=()=>{const[e,t,n]=bt(r=>[r.interactiveSegState,r.resetInteractiveSegState,r.handleInteractiveSegAccept]);return e.isInteractiveSeg?v.jsxs("div",{className:"z-10 absolute top-[68px] rounded-xl border-solid border p-[8px] left-1/2 translate-x-[-50%] flex justify-center items-center gap-[8px] bg-background",children:[v.jsx(wn,{onClick:()=>{t()},size:"sm",variant:"secondary",children:"Cancel"}),v.jsx(wn,{size:"sm",onClick:()=>{n()},children:"Accept"})]}):null},Uq=e=>{const{x:t,y:n,positive:r}=e,o=r?"bg-[rgba(21,_215,_121,_0.936)] outline-[rgba(98,255,179,0.31)]":"bg-[rgba(237,_49,_55,_0.942)] outline-[rgba(255,89,95,0.31)]";return v.jsx("div",{className:`absolute h-[10px] w-[10px] rounded-[50%] ${o} outline-8 outline`,style:{left:t,top:n,transform:"translate(-50%, -50%)"}})},Vq=()=>{const e=bt(t=>t.interactiveSegState.clicks);return v.jsx("div",{className:"absolute h-full w-full overflow-hidden pointer-events-none",children:e.map(t=>v.jsx(Uq,{x:t[0],y:t[1],positive:t[2]===1},t[3]))})},Wq=()=>v.jsx("div",{children:v.jsx(Bq,{})}),cl={capture:!0,passive:!1},Hq=2,H2=(e,t,n,r)=>t{const{minHeight:t,minWidth:n,scale:r,show:o}=e,[i,s,l,u,{x:f,y:m,width:p,height:g},y,b,S,E,_,x,C]=bt(ie=>[ie.isInpainting,ie.imageHeight,ie.imageWidth,ie.isSD(),ie.extenderState,ie.setExtenderX,ie.setExtenderY,ie.setExtenderWidth,ie.setExtenderHeight,ie.settings.extenderDirection,ie.isCropperExtenderResizing,ie.setIsCropperExtenderResizing]),[R,P]=d.useState({initX:0,initY:0,initHeight:0,initWidth:0,startResizeX:0,startResizeY:0,ord:"top"}),M=()=>{},A=(ie,K)=>H2(ie,K,f,n),D=(ie,K)=>H2(ie,K,m,t),U=ie=>{if(i)return;const K=ie.clientX,Z=ie.clientY,H=Math.round((Z-R.startResizeY)/r),se=Math.round((K-R.startResizeX)/r),ce=()=>{const Oe=R.initHeight-H,he=R.initY+H;let xe=he,$e=Oe;if(_===Ln.xy)xe>0&&(xe=0,$e=R.initHeight-Math.abs(R.initY));else{const Ae=D(he,Oe);xe=Ae[0],$e=Ae[1]}E($e),b(xe)},Ve=()=>{const Oe=R.initHeight+H;let[he,xe]=D(R.initY,Oe);_===Ln.xy&&xe{const Oe=R.initWidth-se,he=R.initX+se;let xe=he,$e=Oe;if(_===Ln.xy)xe>0&&(xe=0,$e=R.initWidth-Math.abs(R.initX));else{const Ae=A(he,Oe);xe=Ae[0],$e=Ae[1]}S($e),y(xe)},We=()=>{const Oe=R.initWidth+se;let[he,xe]=A(R.initX,Oe);_===Ln.xy&&xe{x&&C(!1)};d.useEffect(()=>{if(x)return document.addEventListener("pointermove",U,cl),document.addEventListener("pointerup",W,cl),document.addEventListener("pointercancel",W,cl),()=>{document.removeEventListener("pointermove",U,cl),document.removeEventListener("pointerup",W,cl),document.removeEventListener("pointercancel",W,cl)}},[x,p,g,R]);const q=ie=>{const{ord:K}=ie.target.dataset;K&&(C(!0),P({initX:f,initY:m,initHeight:g,initWidth:p,startResizeX:ie.clientX,startResizeY:ie.clientY,ord:K}))},X=(ie,K,Z)=>{const ce="w-[12px] h-[12px] z-[4] absolute content-[''] block border-2 border-primary borde pointer-events-auto hover:bg-primary";let Ve="0",Ue="0",We=Z,Oe="-6px";return Z===""&&(Oe="50%",K==="left"||K==="right"?(We="top",Ue="-50%"):(We="left",Ve="-50%")),v.jsx("div",{className:Ce(ce,ie),style:{[K]:-6,[We]:Oe,transform:`translate(${Ve}, ${Ue}) scale(${1/r})`},"data-ord":K+Z,"aria-label":K+Z,tabIndex:-1,role:"button"})},ae=()=>v.jsxs("div",{onFocus:M,onPointerDown:q,className:"absolute top-0 h-full w-full",children:[[Ln.y,Ln.xy].includes(_)?v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 w-full cursor-ns-resize h-[12px] mt-[-6px]","data-ord":"top"}),v.jsx("div",{className:"absolute pointer-events-auto bottom-0 left-0 w-full cursor-ns-resize h-[12px] mb-[-6px]","data-ord":"bottom"}),X("cursor-ns-resize","top",""),X("cursor-ns-resize","bottom","")]}):v.jsx(v.Fragment,{}),[Ln.x,Ln.xy].includes(_)?v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"absolute pointer-events-auto top-0 right-0 h-full cursor-ew-resize w-[12px] mr-[-6px]","data-ord":"right"}),v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 h-full cursor-ew-resize w-[12px] ml-[-6px]","data-ord":"left"}),X("cursor-ew-resize","left",""),X("cursor-ew-resize","right","")]}):v.jsx(v.Fragment,{}),_===Ln.xy?v.jsxs(v.Fragment,{children:[X("cursor-nw-resize","top","left"),X("cursor-ne-resize","top","right"),X("cursor-sw-resize","bottom","left"),X("cursor-se-resize","bottom","right")]}):v.jsx(v.Fragment,{})]}),V=ie=>{P({initX:f,initY:m,initHeight:g,initWidth:p,startResizeX:ie.clientX,startResizeY:ie.clientY,ord:""})},F=()=>v.jsxs("div",{className:tx("border absolute pointer-events-auto px-2 py-1 rounded-full bg-background","origin-top-left top-0 left-0"),style:{transform:`scale(${1/r*.8})`},onPointerDown:V,children:[p," x ",g]}),N=()=>v.jsx("div",{className:Ce("outline-dashed outline-primary"),style:{height:g,width:p,outlineWidth:`${Hq/r*1.3}px`}});return o===!1||!u?null:v.jsx("div",{className:"absolute h-full w-full pointer-events-none z-[2]",children:v.jsxs("div",{className:"relative pointer-events-none z-[2] [box-shadow:0_0_0_9999px_rgba(0,_0,_0,_0.5)]",style:{height:g,width:p,left:f,top:m},children:[N(),F(),ae()]})})},Gq=200,Yq=10,Xq=200,mu=300;function Zq(e){const{file:t}=e,{toast:n}=Id(),[r,o,i,s,l,u,f,m,p,g,y,b,S,E,_,x,C,R,P,M,A,D]=bt(G=>[G.disableShortCuts,G.windowSize,G.isInpainting,G.imageWidth,G.imageHeight,G.settings,G.serverConfig.enableAutoSaving,G.setImageSize,G.setBaseBrushSize,G.interactiveSegState,G.updateInteractiveSegState,G.handleCanvasMouseDown,G.handleCanvasMouseMove,G.undo,G.redo,G.undoDisabled(),G.redoDisabled(),G.getIsProcessing(),G.updateAppState,G.runMannually(),G.runInpainting,G.isCropperExtenderResizing]),U=bt(G=>G.editorState.baseBrushSize),W=bt(G=>G.getBrushSize()),q=bt(G=>G.editorState.renders),X=bt(G=>G.editorState.extraMasks),ae=bt(G=>G.editorState.temporaryMasks),V=bt(G=>G.editorState.lineGroups),F=bt(G=>G.editorState.curLineGroup),[N,ie]=d.useState(!1),[K,Z]=Px(t),[H,se]=d.useState(),[ce,Ve]=d.useState(),[{x:Ue,y:We},Oe]=d.useState({x:-1,y:-1}),[he,xe]=d.useState(!1),[$e,Ae]=d.useState(!1),[Me,je]=d.useState(!1),[Mt,ct]=d.useState(1),[Kt,Er]=d.useState(!1),[gt,Vs]=d.useState(1),L=o.width/2,Q=o.height/2,J=d.useRef(null),[we,me]=d.useState(!1),[fe,Re]=d.useState(!1),[ft,ht]=d.useState(0),_n=d.useCallback(()=>F.length!==0,[F]);d.useEffect(()=>{if(!ce||!Z||s===0||l===0)return;const G=q.length===0?K:q[q.length-1];ce.canvas.width=s,ce.canvas.height=l,ce.clearRect(0,0,ce.canvas.width,ce.canvas.height),ce.drawImage(G,0,0,s,l)},[q,K,Z,ce,l,s]),d.useEffect(()=>{!H||!Z||s===0||l===0||(H.canvas.width=s,H.canvas.height=l,H.clearRect(0,0,H.canvas.width,H.canvas.height),ae.forEach(G=>{H.drawImage(G,0,0,s,l)}),X.forEach(G=>{H.drawImage(G,0,0,s,l)}),g.isInteractiveSeg&&g.tmpInteractiveSegMask&&H.drawImage(g.tmpInteractiveSegMask,0,0,s,l),Yk(H,F))},[ae,X,Z,g,H,F,l,s]);const Cr=d.useCallback(async()=>{let G=t;if(q.length>0){const Ye=q[q.length-1];G=await Nu(Ye.currentSrc,t.name,t.type)}return G},[t,q]),Ni=()=>q.length!==0,Co=d.useCallback(()=>{let G=512,Ye=512;return Z?(q.length===0?(G=K.naturalWidth,Ye=K.naturalHeight):q.length!==0&&(G=q[q.length-1].width,Ye=q[q.length-1].height),[G,Ye]):[G,Ye]},[K,Z,q]);d.useEffect(()=>{var tf;if(!Z)return;const[G,Ye]=Co();(G!==s||Ye!==l)&&m(G,Ye);const st=o.width/G,Qr=(o.height-Gq)/Ye;let an=1;(st<1||Qr<1)&&(an=Math.min(st,Qr)),Vs(an),ct(an),console.log(`[on file load] image size: ${G}x${Ye}, scale: ${an}, initialCentered: ${we}`),H!=null&&H.canvas&&(console.log("[on file load] set canvas size"),G!=H.canvas.width&&(H.canvas.width=G),Ye!=H.canvas.height&&(H.canvas.height=Ye)),we||((tf=J.current)==null||tf.centerView(an,1),console.log("[on file load] centerView"),me(!0))},[J,l,s,K,Z,o,we,Co]),d.useEffect(()=>{var G;console.log("[useEffect] centerView"),(G=J==null?void 0:J.current)==null||G.centerView(gt,1)},[l,s,J,gt]);const Vn=d.useCallback(()=>{if(!gt||!o)return;const G=J.current;if(!G)return;const Ye=(o.width-s*gt)/2,st=(o.height-l*gt)/2;G.setTransform(Ye,st,gt,200,"easeOutQuad"),G.instance.transformState.scale&&(G.instance.transformState.scale=gt),ct(gt),Er(!1)},[J,o,l,s,o.height,gt]);d.useEffect(()=>(window.addEventListener("resize",()=>{Vn()}),()=>{window.removeEventListener("resize",()=>{Vn()})}),[o,Vn]),Zn("Escape",()=>{R||(fe?Re(!1):Vn())},[fe,i,Vn]);const Di=G=>{const Ye=G.nativeEvent;Oe({x:Ye.pageX,y:Ye.pageY})},Ws=G=>{R||g.isInteractiveSeg||Me||fe&&F.length!==0&&S(f0(G))},Ii=async G=>{P({isPluginRunning:!0});const Ye=await Cr();try{const st=await vT(!0,Ao.InteractiveSeg,Ye,void 0,G),{blob:Qr}=st,an=new Image;an.onload=()=>{y({tmpInteractiveSegMask:an})},an.src=Qr}catch(st){n({variant:"destructive",description:st.message?st.message:st.toString()})}P({isPluginRunning:!1})},Mc=G=>{if(dC(G)){je(!1);return}!_n()||g.isInteractiveSeg||Me||!K.src||!(H!=null&&H.canvas)||i||fe&&(M?Re(!1):A())},bg=G=>{if(g.isInteractiveSeg){const Ye=f0(G),st=[...g.clicks];uC(G)?st.push([Ye.x,Ye.y,0,st.length]):st.push([Ye.x,Ye.y,1,st.length]),Ii(st),y({clicks:st})}},Sg=G=>{if(!(R||g.isInteractiveSeg||Me||!Z||!(H!=null&&H.canvas))&&!uC(G)){if(dC(G)){je(!0);return}Re(!0),b(f0(G))}},Jd=G=>{G.preventDefault(),E()};Zn("meta+z,ctrl+z",Jd);const Oc=G=>{G.preventDefault(),_()};Zn("shift+ctrl+z,shift+meta+z",Oc),s2("Tab",G=>{G==null||G.preventDefault(),G==null||G.stopPropagation(),Ni()&&ie(()=>(window.setTimeout(()=>{ht(100)},10),!0))},G=>{G==null||G.preventDefault(),G==null||G.stopPropagation(),Ni()&&(window.setTimeout(()=>{ht(0)},10),window.setTimeout(()=>{ie(!1)},mu))});const Nc=d.useCallback(async()=>{if(t===void 0)return;if(f&&q.length>0){try{await Hj(q[q.length-1],t.name,t.type),n({description:"Save image success"})}catch(st){n({variant:"destructive",title:"Uh oh! Something went wrong.",description:st.message?st.message:st.toString()})}return}const G=t.name.replace(/(\.[\w\d_-]+)$/i,"_cleanup$1"),Ye=q[q.length-1];if(bF(Ye.currentSrc,G),u.enableDownloadMask){let st=t.name.replace(/(\.[\w\d_-]+)$/i,"_mask$1");st=st.replace(/\.[^/.]+$/,".jpg");const Qr=Wh(s,l,V),an=document.createElement("a");an.download=st,an.href=Qr.toDataURL("image/jpeg"),an.click()}},[t,f,q,u,l,s,V]);Zn("meta+s,ctrl+s",Nc);const Dc=G=>{G!==he&&!Me&&!D&&xe(G)},_g=d.useCallback(()=>{if(R)return"default";if(Me)return"grab";if(he)return"none"},[he,Me,R]);Zn("[",()=>{let G=U;U>10&&(G=U-10),U<=10&&U>0&&(G=U-5),p(G)},[U]),Zn("]",()=>{p(U+10)},[U]),Zn("shift+r",()=>{M&&_n()&&A()},[M,A,_n]),Zn("ctrl+c,meta+c",async()=>{await vF()&&q.length>0&&H!=null&&H.canvas&&(await xF(H==null?void 0:H.canvas),n({title:"Copy inpainting result to clipboard"}))},[q,H]),s2(" ",G=>{r||(G==null||G.preventDefault(),G==null||G.stopPropagation(),xe(!1),je(!0))},G=>{r||(G==null||G.preventDefault(),G==null||G.stopPropagation(),xe(!0),je(!1))});const Ic=()=>{var Ye,st,Qr,an;let G=gt;return((st=(Ye=J.current)==null?void 0:Ye.instance)==null?void 0:st.transformState.scale)!==void 0&&(G=(an=(Qr=J.current)==null?void 0:Qr.instance)==null?void 0:an.transformState.scale),G},ef=(G,Ye)=>{const st=Ic();return{width:`${W*st}px`,height:`${W*st}px`,left:`${G}px`,top:`${Ye}px`,transform:"translate(-50%, -50%)"}},Lc=G=>v.jsx("div",{className:"absolute rounded-[50%] border-[1px] border-[solid] border-[#ffcc00] pointer-events-none bg-[#ffcc00bb]",style:G}),Eg=G=>{p(G),$e||(Ae(!0),window.setTimeout(()=>{Ae(!1)},1e4))},Cg=()=>v.jsx("div",{className:"absolute h-[20px] w-[20px] pointer-events-none rounded-[50%] bg-[rgba(21,_215,_121,_0.936)] [box-shadow:0_0_0_0_rgba(21,_215,_121,_0.936)] animate-pulse",style:{left:`${Ue}px`,top:`${We}px`,transform:"translate(-50%, -50%)"},children:v.jsx(dK,{})}),$g=()=>v.jsx(fq,{ref:G=>{G&&(J.current=G)},panning:{disabled:!Me,velocityDisabled:!0},wheel:{step:.05},centerZoomedOut:!0,alignmentAnimation:{disabled:!0},centerOnInit:!0,limitToBounds:!1,doubleClick:{disabled:!0},initialScale:gt,minScale:gt*.3,onPanning:()=>{Kt||Er(!0)},onZoom:G=>{ct(G.state.scale)},children:v.jsxs(mq,{contentStyle:{visibility:we?"visible":"hidden"},children:[v.jsxs("div",{className:"grid [grid-template-areas:'editor-content'] gap-y-4",children:[v.jsx("canvas",{className:"[grid-area:editor-content]",style:{clipPath:`inset(0 ${ft}% 0 0)`,transition:`clip-path ${mu}ms`},ref:G=>{if(G&&!ce){const Ye=G.getContext("2d");Ye&&Ve(Ye)}}}),v.jsx("canvas",{className:Ce("[grid-area:editor-content]",R?"pointer-events-none animate-pulse duration-600":""),style:{cursor:_g(),clipPath:`inset(0 ${ft}% 0 0)`,transition:`clip-path ${mu}ms`},onContextMenu:G=>{G.preventDefault()},onMouseOver:()=>{Dc(!0),Ae(!1)},onFocus:()=>Dc(!0),onMouseLeave:()=>Dc(!1),onMouseDown:Sg,onMouseUp:bg,onMouseMove:Ws,ref:G=>{if(G&&!H){const Ye=G.getContext("2d");Ye&&se(Ye)}}}),v.jsx("div",{className:"[grid-area:editor-content] pointer-events-none grid [grid-template-areas:'original-image-content']",style:{width:`${s}px`,height:`${l}px`},children:N&&v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"[grid-area:original-image-content] z-10 bg-primary h-full w-[6px] justify-self-end",style:{marginRight:`${ft}%`,transition:`margin-right ${mu}ms`}}),v.jsx("img",{className:"[grid-area:original-image-content]",src:K.src,alt:"original",style:{width:`${s}px`,height:`${l}px`}})]})})]}),v.jsx(zq,{maxHeight:l,maxWidth:s,minHeight:Math.min(512,l),minWidth:Math.min(512,s),scale:Ic(),show:u.showCropper}),v.jsx(Kq,{minHeight:Math.min(512,l),minWidth:Math.min(512,s),scale:Ic(),show:u.showExtender}),g.isInteractiveSeg?v.jsx(Vq,{}):v.jsx(v.Fragment,{})]})});return v.jsxs("div",{className:"flex w-screen h-screen justify-center items-center","aria-hidden":"true",onMouseMove:Di,onMouseUp:Mc,children:[$g(),he&&!i&&!Me&&(g.isInteractiveSeg?Cg():Lc(ef(Ue,We))),$e&&Lc(ef(L,Q)),v.jsxs("div",{className:" overflow-hidden fixed flex bottom-5 border px-4 py-2 rounded-[3rem] gap-8 items-center justify-center backdrop-filter backdrop-blur-md bg-background/70",children:[v.jsx(uo,{className:"w-48",defaultValue:[50],min:Yq,max:Xq,step:1,tabIndex:-1,value:[U],onValueChange:G=>Eg(G[0]),onClick:()=>Ae(!1)}),v.jsxs("div",{className:"flex gap-2",children:[v.jsx(yn,{tooltip:"Reset zoom & pan",disabled:Mt===gt&&Kt===!1,onClick:Vn,children:v.jsx(QU,{})}),v.jsx(yn,{tooltip:"Undo",onClick:Jd,disabled:x,children:v.jsx(aV,{})}),v.jsx(yn,{tooltip:"Redo",onClick:Oc,disabled:C,children:v.jsx(oV,{})}),v.jsx(yn,{tooltip:"Show original image",onPointerDown:G=>{G.preventDefault(),ie(()=>(window.setTimeout(()=>{ht(100)},10),!0))},onPointerUp:()=>{window.setTimeout(()=>{ht(0)},10),window.setTimeout(()=>{ie(!1)},mu)},disabled:q.length===0,children:v.jsx(JU,{})}),v.jsx(yn,{tooltip:"Save Image",disabled:!q.length,onClick:Nc,children:v.jsx(ZU,{})}),u.enableManualInpainting&&u.model.model_type==="inpaint"?v.jsx(yn,{tooltip:"Run Inpainting",disabled:R||!_n()&&X.length===0,onClick:()=>{A()},children:v.jsx(qU,{})}):v.jsx(v.Fragment,{})]})]})]})}const qq=()=>{const[e,t]=bt(n=>[n.imageWidth,n.imageHeight]);return!e||!t?null:v.jsxs("div",{className:"border rounded-lg px-2 py-[6px] z-10 bg-background",children:[e,"x",t]})},V1=["Enter"," "],Qq=["ArrowDown","PageUp","Home"],K3=["ArrowUp","PageDown","End"],Jq=[...Qq,...K3],eQ={ltr:[...V1,"ArrowRight"],rtl:[...V1,"ArrowLeft"]},tQ={ltr:["ArrowLeft"],rtl:["ArrowRight"]},mg="Menu",[md,nQ,rQ]=Gd(mg),[za,G3]=Mn(mg,[rQ,Fs,tg]),gg=Fs(),Y3=tg(),[X3,Us]=za(mg),[oQ,Qd]=za(mg),iQ=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:o,onOpenChange:i,modal:s=!0}=e,l=gg(t),[u,f]=d.useState(null),m=d.useRef(!1),p=Ft(i),g=Tc(o);return d.useEffect(()=>{const y=()=>{m.current=!0,document.addEventListener("pointerdown",b,{capture:!0,once:!0}),document.addEventListener("pointermove",b,{capture:!0,once:!0})},b=()=>m.current=!1;return document.addEventListener("keydown",y,{capture:!0}),()=>{document.removeEventListener("keydown",y,{capture:!0}),document.removeEventListener("pointerdown",b,{capture:!0}),document.removeEventListener("pointermove",b,{capture:!0})}},[]),d.createElement(jd,l,d.createElement(X3,{scope:t,open:n,onOpenChange:p,content:u,onContentChange:f},d.createElement(oQ,{scope:t,onClose:d.useCallback(()=>p(!1),[p]),isUsingKeyboardRef:m,dir:g,modal:s},r)))},Z3=d.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,o=gg(n);return d.createElement(Vm,Y({},o,r,{ref:t}))}),q3="MenuPortal",[sQ,Q3]=za(q3,{forceMount:void 0}),aQ=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:o}=e,i=Us(q3,t);return d.createElement(sQ,{scope:t,forceMount:n},d.createElement(Sn,{present:n||i.open},d.createElement(zd,{asChild:!0,container:o},r)))},bo="MenuContent",[lQ,tb]=za(bo),cQ=d.forwardRef((e,t)=>{const n=Q3(bo,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,i=Us(bo,e.__scopeMenu),s=Qd(bo,e.__scopeMenu);return d.createElement(md.Provider,{scope:e.__scopeMenu},d.createElement(Sn,{present:r||i.open},d.createElement(md.Slot,{scope:e.__scopeMenu},s.modal?d.createElement(uQ,Y({},o,{ref:t})):d.createElement(dQ,Y({},o,{ref:t})))))}),uQ=d.forwardRef((e,t)=>{const n=Us(bo,e.__scopeMenu),r=d.useRef(null),o=Be(t,r);return d.useEffect(()=>{const i=r.current;if(i)return Qm(i)},[]),d.createElement(nb,Y({},e,{ref:o,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:de(e.onFocusOutside,i=>i.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)}))}),dQ=d.forwardRef((e,t)=>{const n=Us(bo,e.__scopeMenu);return d.createElement(nb,Y({},e,{ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)}))}),nb=d.forwardRef((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:o,onOpenAutoFocus:i,onCloseAutoFocus:s,disableOutsidePointerEvents:l,onEntryFocus:u,onEscapeKeyDown:f,onPointerDownOutside:m,onFocusOutside:p,onInteractOutside:g,onDismiss:y,disableOutsideScroll:b,...S}=e,E=Us(bo,n),_=Qd(bo,n),x=gg(n),C=Y3(n),R=nQ(n),[P,M]=d.useState(null),A=d.useRef(null),D=Be(t,A,E.onContentChange),U=d.useRef(0),W=d.useRef(""),q=d.useRef(0),X=d.useRef(null),ae=d.useRef("right"),V=d.useRef(0),F=b?qm:d.Fragment,N=b?{as:Zo,allowPinchZoom:!0}:void 0,ie=Z=>{var H,se;const ce=W.current+Z,Ve=R().filter($e=>!$e.disabled),Ue=document.activeElement,We=(H=Ve.find($e=>$e.ref.current===Ue))===null||H===void 0?void 0:H.textValue,Oe=Ve.map($e=>$e.textValue),he=kQ(Oe,ce,We),xe=(se=Ve.find($e=>$e.textValue===he))===null||se===void 0?void 0:se.ref.current;(function $e(Ae){W.current=Ae,window.clearTimeout(U.current),Ae!==""&&(U.current=window.setTimeout(()=>$e(""),1e3))})(ce),xe&&setTimeout(()=>xe.focus())};d.useEffect(()=>()=>window.clearTimeout(U.current),[]),Xm();const K=d.useCallback(Z=>{var H,se;return ae.current===((H=X.current)===null||H===void 0?void 0:H.side)&&PQ(Z,(se=X.current)===null||se===void 0?void 0:se.area)},[]);return d.createElement(lQ,{scope:n,searchRef:W,onItemEnter:d.useCallback(Z=>{K(Z)&&Z.preventDefault()},[K]),onItemLeave:d.useCallback(Z=>{var H;K(Z)||((H=A.current)===null||H===void 0||H.focus(),M(null))},[K]),onTriggerLeave:d.useCallback(Z=>{K(Z)&&Z.preventDefault()},[K]),pointerGraceTimerRef:q,onPointerGraceIntentChange:d.useCallback(Z=>{X.current=Z},[])},d.createElement(F,N,d.createElement(Ym,{asChild:!0,trapped:o,onMountAutoFocus:de(i,Z=>{var H;Z.preventDefault(),(H=A.current)===null||H===void 0||H.focus()}),onUnmountAutoFocus:s},d.createElement(Ec,{asChild:!0,disableOutsidePointerEvents:l,onEscapeKeyDown:f,onPointerDownOutside:m,onFocusOutside:p,onInteractOutside:g,onDismiss:y},d.createElement(QP,Y({asChild:!0},C,{dir:_.dir,orientation:"vertical",loop:r,currentTabStopId:P,onCurrentTabStopIdChange:M,onEntryFocus:de(u,Z=>{_.isUsingKeyboardRef.current||Z.preventDefault()})}),d.createElement(Wm,Y({role:"menu","aria-orientation":"vertical","data-state":oA(E.open),"data-radix-menu-content":"",dir:_.dir},x,S,{ref:D,style:{outline:"none",...S.style},onKeyDown:de(S.onKeyDown,Z=>{const se=Z.target.closest("[data-radix-menu-content]")===Z.currentTarget,ce=Z.ctrlKey||Z.altKey||Z.metaKey,Ve=Z.key.length===1;se&&(Z.key==="Tab"&&Z.preventDefault(),!ce&&Ve&&ie(Z.key));const Ue=A.current;if(Z.target!==Ue||!Jq.includes(Z.key))return;Z.preventDefault();const Oe=R().filter(he=>!he.disabled).map(he=>he.ref.current);K3.includes(Z.key)&&Oe.reverse(),$Q(Oe)}),onBlur:de(e.onBlur,Z=>{Z.currentTarget.contains(Z.target)||(window.clearTimeout(U.current),W.current="")}),onPointerMove:de(e.onPointerMove,gd(Z=>{const H=Z.target,se=V.current!==Z.clientX;if(Z.currentTarget.contains(H)&&se){const ce=Z.clientX>V.current?"right":"left";ae.current=ce,V.current=Z.clientX}}))})))))))}),fQ=d.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return d.createElement(Pe.div,Y({},r,{ref:t}))}),W1="MenuItem",K2="menu.itemSelect",rb=d.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...o}=e,i=d.useRef(null),s=Qd(W1,e.__scopeMenu),l=tb(W1,e.__scopeMenu),u=Be(t,i),f=d.useRef(!1),m=()=>{const p=i.current;if(!n&&p){const g=new CustomEvent(K2,{bubbles:!0,cancelable:!0});p.addEventListener(K2,y=>r==null?void 0:r(y),{once:!0}),dx(p,g),g.defaultPrevented?f.current=!1:s.onClose()}};return d.createElement(J3,Y({},o,{ref:u,disabled:n,onClick:de(e.onClick,m),onPointerDown:p=>{var g;(g=e.onPointerDown)===null||g===void 0||g.call(e,p),f.current=!0},onPointerUp:de(e.onPointerUp,p=>{var g;f.current||(g=p.currentTarget)===null||g===void 0||g.click()}),onKeyDown:de(e.onKeyDown,p=>{const g=l.searchRef.current!=="";n||g&&p.key===" "||V1.includes(p.key)&&(p.currentTarget.click(),p.preventDefault())})}))}),J3=d.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:o,...i}=e,s=tb(W1,n),l=Y3(n),u=d.useRef(null),f=Be(t,u),[m,p]=d.useState(!1),[g,y]=d.useState("");return d.useEffect(()=>{const b=u.current;if(b){var S;y(((S=b.textContent)!==null&&S!==void 0?S:"").trim())}},[i.children]),d.createElement(md.ItemSlot,{scope:n,disabled:r,textValue:o??g},d.createElement(JP,Y({asChild:!0},l,{focusable:!r}),d.createElement(Pe.div,Y({role:"menuitem","data-highlighted":m?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0},i,{ref:f,onPointerMove:de(e.onPointerMove,gd(b=>{r?s.onItemLeave(b):(s.onItemEnter(b),b.defaultPrevented||b.currentTarget.focus())})),onPointerLeave:de(e.onPointerLeave,gd(b=>s.onItemLeave(b))),onFocus:de(e.onFocus,()=>p(!0)),onBlur:de(e.onBlur,()=>p(!1))}))))}),hQ=d.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...o}=e;return d.createElement(tA,{scope:e.__scopeMenu,checked:n},d.createElement(rb,Y({role:"menuitemcheckbox","aria-checked":am(n)?"mixed":n},o,{ref:t,"data-state":ob(n),onSelect:de(o.onSelect,()=>r==null?void 0:r(am(n)?!0:!n),{checkForDefaultPrevented:!1})})))}),pQ="MenuRadioGroup",[$te,mQ]=za(pQ,{value:void 0,onValueChange:()=>{}}),gQ="MenuRadioItem",vQ=d.forwardRef((e,t)=>{const{value:n,...r}=e,o=mQ(gQ,e.__scopeMenu),i=n===o.value;return d.createElement(tA,{scope:e.__scopeMenu,checked:i},d.createElement(rb,Y({role:"menuitemradio","aria-checked":i},r,{ref:t,"data-state":ob(i),onSelect:de(r.onSelect,()=>{var s;return(s=o.onValueChange)===null||s===void 0?void 0:s.call(o,n)},{checkForDefaultPrevented:!1})})))}),eA="MenuItemIndicator",[tA,yQ]=za(eA,{checked:!1}),wQ=d.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...o}=e,i=yQ(eA,n);return d.createElement(Sn,{present:r||am(i.checked)||i.checked===!0},d.createElement(Pe.span,Y({},o,{ref:t,"data-state":ob(i.checked)})))}),xQ=d.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return d.createElement(Pe.div,Y({role:"separator","aria-orientation":"horizontal"},r,{ref:t}))}),nA="MenuSub",[bQ,rA]=za(nA),SQ=e=>{const{__scopeMenu:t,children:n,open:r=!1,onOpenChange:o}=e,i=Us(nA,t),s=gg(t),[l,u]=d.useState(null),[f,m]=d.useState(null),p=Ft(o);return d.useEffect(()=>(i.open===!1&&p(!1),()=>p(!1)),[i.open,p]),d.createElement(jd,s,d.createElement(X3,{scope:t,open:r,onOpenChange:p,content:f,onContentChange:m},d.createElement(bQ,{scope:t,contentId:nr(),triggerId:nr(),trigger:l,onTriggerChange:u},n)))},_h="MenuSubTrigger",_Q=d.forwardRef((e,t)=>{const n=Us(_h,e.__scopeMenu),r=Qd(_h,e.__scopeMenu),o=rA(_h,e.__scopeMenu),i=tb(_h,e.__scopeMenu),s=d.useRef(null),{pointerGraceTimerRef:l,onPointerGraceIntentChange:u}=i,f={__scopeMenu:e.__scopeMenu},m=d.useCallback(()=>{s.current&&window.clearTimeout(s.current),s.current=null},[]);return d.useEffect(()=>m,[m]),d.useEffect(()=>{const p=l.current;return()=>{window.clearTimeout(p),u(null)}},[l,u]),d.createElement(Z3,Y({asChild:!0},f),d.createElement(J3,Y({id:o.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":o.contentId,"data-state":oA(n.open)},e,{ref:Nm(t,o.onTriggerChange),onClick:p=>{var g;(g=e.onClick)===null||g===void 0||g.call(e,p),!(e.disabled||p.defaultPrevented)&&(p.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:de(e.onPointerMove,gd(p=>{i.onItemEnter(p),!p.defaultPrevented&&!e.disabled&&!n.open&&!s.current&&(i.onPointerGraceIntentChange(null),s.current=window.setTimeout(()=>{n.onOpenChange(!0),m()},100))})),onPointerLeave:de(e.onPointerLeave,gd(p=>{var g;m();const y=(g=n.content)===null||g===void 0?void 0:g.getBoundingClientRect();if(y){var b;const S=(b=n.content)===null||b===void 0?void 0:b.dataset.side,E=S==="right",_=E?-5:5,x=y[E?"left":"right"],C=y[E?"right":"left"];i.onPointerGraceIntentChange({area:[{x:p.clientX+_,y:p.clientY},{x,y:y.top},{x:C,y:y.top},{x:C,y:y.bottom},{x,y:y.bottom}],side:S}),window.clearTimeout(l.current),l.current=window.setTimeout(()=>i.onPointerGraceIntentChange(null),300)}else{if(i.onTriggerLeave(p),p.defaultPrevented)return;i.onPointerGraceIntentChange(null)}})),onKeyDown:de(e.onKeyDown,p=>{const g=i.searchRef.current!=="";if(!(e.disabled||g&&p.key===" ")&&eQ[r.dir].includes(p.key)){var y;n.onOpenChange(!0),(y=n.content)===null||y===void 0||y.focus(),p.preventDefault()}})})))}),EQ="MenuSubContent",CQ=d.forwardRef((e,t)=>{const n=Q3(bo,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,i=Us(bo,e.__scopeMenu),s=Qd(bo,e.__scopeMenu),l=rA(EQ,e.__scopeMenu),u=d.useRef(null),f=Be(t,u);return d.createElement(md.Provider,{scope:e.__scopeMenu},d.createElement(Sn,{present:r||i.open},d.createElement(md.Slot,{scope:e.__scopeMenu},d.createElement(nb,Y({id:l.contentId,"aria-labelledby":l.triggerId},o,{ref:f,align:"start",side:s.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:m=>{var p;s.isUsingKeyboardRef.current&&((p=u.current)===null||p===void 0||p.focus()),m.preventDefault()},onCloseAutoFocus:m=>m.preventDefault(),onFocusOutside:de(e.onFocusOutside,m=>{m.target!==l.trigger&&i.onOpenChange(!1)}),onEscapeKeyDown:de(e.onEscapeKeyDown,m=>{s.onClose(),m.preventDefault()}),onKeyDown:de(e.onKeyDown,m=>{const p=m.currentTarget.contains(m.target),g=tQ[s.dir].includes(m.key);if(p&&g){var y;i.onOpenChange(!1),(y=l.trigger)===null||y===void 0||y.focus(),m.preventDefault()}})})))))});function oA(e){return e?"open":"closed"}function am(e){return e==="indeterminate"}function ob(e){return am(e)?"indeterminate":e?"checked":"unchecked"}function $Q(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function RQ(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function kQ(e,t,n){const o=t.length>1&&Array.from(t).every(f=>f===t[0])?t[0]:t,i=n?e.indexOf(n):-1;let s=RQ(e,Math.max(i,0));o.length===1&&(s=s.filter(f=>f!==n));const u=s.find(f=>f.toLowerCase().startsWith(o.toLowerCase()));return u!==n?u:void 0}function TQ(e,t){const{x:n,y:r}=e;let o=!1;for(let i=0,s=t.length-1;ir!=m>r&&n<(f-l)*(r-u)/(m-u)+l&&(o=!o)}return o}function PQ(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return TQ(n,t)}function gd(e){return t=>t.pointerType==="mouse"?e(t):void 0}const AQ=iQ,MQ=Z3,OQ=aQ,NQ=cQ,DQ=fQ,IQ=rb,LQ=hQ,FQ=vQ,jQ=wQ,zQ=xQ,BQ=SQ,UQ=_Q,VQ=CQ,iA="DropdownMenu",[WQ,Rte]=Mn(iA,[G3]),_r=G3(),[HQ,sA]=WQ(iA),KQ=e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:o,defaultOpen:i,onOpenChange:s,modal:l=!0}=e,u=_r(t),f=d.useRef(null),[m=!1,p]=Zr({prop:o,defaultProp:i,onChange:s});return d.createElement(HQ,{scope:t,triggerId:nr(),triggerRef:f,contentId:nr(),open:m,onOpenChange:p,onOpenToggle:d.useCallback(()=>p(g=>!g),[p]),modal:l},d.createElement(AQ,Y({},u,{open:m,onOpenChange:p,dir:r,modal:l}),n))},GQ="DropdownMenuTrigger",YQ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...o}=e,i=sA(GQ,n),s=_r(n);return d.createElement(MQ,Y({asChild:!0},s),d.createElement(Pe.button,Y({type:"button",id:i.triggerId,"aria-haspopup":"menu","aria-expanded":i.open,"aria-controls":i.open?i.contentId:void 0,"data-state":i.open?"open":"closed","data-disabled":r?"":void 0,disabled:r},o,{ref:Nm(t,i.triggerRef),onPointerDown:de(e.onPointerDown,l=>{!r&&l.button===0&&l.ctrlKey===!1&&(i.onOpenToggle(),i.open||l.preventDefault())}),onKeyDown:de(e.onKeyDown,l=>{r||(["Enter"," "].includes(l.key)&&i.onOpenToggle(),l.key==="ArrowDown"&&i.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(l.key)&&l.preventDefault())})})))}),XQ=e=>{const{__scopeDropdownMenu:t,...n}=e,r=_r(t);return d.createElement(OQ,Y({},r,n))},ZQ="DropdownMenuContent",qQ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=sA(ZQ,n),i=_r(n),s=d.useRef(!1);return d.createElement(NQ,Y({id:o.contentId,"aria-labelledby":o.triggerId},i,r,{ref:t,onCloseAutoFocus:de(e.onCloseAutoFocus,l=>{var u;s.current||(u=o.triggerRef.current)===null||u===void 0||u.focus(),s.current=!1,l.preventDefault()}),onInteractOutside:de(e.onInteractOutside,l=>{const u=l.detail.originalEvent,f=u.button===0&&u.ctrlKey===!0,m=u.button===2||f;(!o.modal||m)&&(s.current=!0)}),style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}}))}),QQ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(DQ,Y({},o,r,{ref:t}))}),JQ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(IQ,Y({},o,r,{ref:t}))}),eJ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(LQ,Y({},o,r,{ref:t}))}),tJ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(FQ,Y({},o,r,{ref:t}))}),nJ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(jQ,Y({},o,r,{ref:t}))}),rJ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(zQ,Y({},o,r,{ref:t}))}),oJ=e=>{const{__scopeDropdownMenu:t,children:n,open:r,onOpenChange:o,defaultOpen:i}=e,s=_r(t),[l=!1,u]=Zr({prop:r,defaultProp:i,onChange:o});return d.createElement(BQ,Y({},s,{open:l,onOpenChange:u}),n)},iJ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(UQ,Y({},o,r,{ref:t}))}),sJ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(VQ,Y({},o,r,{ref:t,style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}}))}),aJ=KQ,lJ=YQ,cJ=XQ,aA=qQ,lA=QQ,cA=JQ,uA=eJ,dA=tJ,fA=nJ,hA=rJ,uJ=oJ,pA=iJ,mA=sJ,dJ=aJ,fJ=lJ,G2=uJ,H1=d.forwardRef(({className:e,inset:t,children:n,...r},o)=>v.jsxs(pA,{ref:o,className:Ce("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",e),...r,children:[n,v.jsx(tz,{className:"ml-auto h-4 w-4"})]}));H1.displayName=pA.displayName;const K1=d.forwardRef(({className:e,...t},n)=>v.jsx(mA,{ref:n,className:Ce("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...t}));K1.displayName=mA.displayName;const gA=d.forwardRef(({className:e,sideOffset:t=4,...n},r)=>v.jsx(cJ,{children:v.jsx(aA,{ref:r,sideOffset:t,className:Ce("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md","data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),onCloseAutoFocus:o=>o.preventDefault(),...n})}));gA.displayName=aA.displayName;const fl=d.forwardRef(({className:e,inset:t,...n},r)=>v.jsx(cA,{ref:r,className:Ce("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",e),...n}));fl.displayName=cA.displayName;const hJ=d.forwardRef(({className:e,children:t,checked:n,...r},o)=>v.jsxs(uA,{ref:o,className:Ce("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),checked:n,...r,children:[v.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:v.jsx(fA,{children:v.jsx(yT,{className:"h-4 w-4"})})}),t]}));hJ.displayName=uA.displayName;const pJ=d.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(dA,{ref:r,className:Ce("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[v.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:v.jsx(fA,{children:v.jsx(sz,{className:"h-4 w-4 fill-current"})})}),t]}));pJ.displayName=dA.displayName;const mJ=d.forwardRef(({className:e,inset:t,...n},r)=>v.jsx(lA,{ref:r,className:Ce("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",e),...n}));mJ.displayName=lA.displayName;const gJ=d.forwardRef(({className:e,...t},n)=>v.jsx(hA,{ref:n,className:Ce("-mx-1 my-1 h-px bg-muted",e),...t}));gJ.displayName=hA.displayName;const Y2={RemoveBG:{IconClass:HC,showName:"RemoveBG"},AnimeSeg:{IconClass:HC,showName:"Anime Segmentation"},RealESRGAN:{IconClass:ZT,showName:"RealESRGAN"},GFPGAN:{IconClass:KC,showName:"GFPGAN"},RestoreFormer:{IconClass:KC,showName:"RestoreFormer"},InteractiveSeg:{IconClass:rV,showName:"Interactive Segmentation"}},vJ=()=>{const[e,t,n,r]=bt(f=>[f.file,f.serverConfig.plugins,f.updateInteractiveSegState,f.runRenderablePlugin]),o=!e;if(t.length===0)return null;const i=(f,m)=>{m==="InteractiveSeg"?n({isInteractiveSeg:!0}):r(f,m)},s=()=>v.jsxs(G2,{children:[v.jsx(H1,{disabled:o,children:v.jsxs("div",{className:"flex gap-2 items-center",children:[v.jsx(ZT,{}),"RealESRGAN"]})}),v.jsxs(K1,{children:[v.jsx(fl,{onClick:()=>r(!1,"RealESRGAN",{upscale:2}),children:"upscale 2x"}),v.jsx(fl,{onClick:()=>r(!1,"RealESRGAN",{upscale:4}),children:"upscale 4x"})]})]},"RealESRGAN"),l=f=>{const{IconClass:m,showName:p}=Y2[f.name];return v.jsxs(G2,{children:[v.jsx(H1,{disabled:o,children:v.jsxs("div",{className:"flex gap-2 items-center",children:[v.jsx(m,{className:"p-1"}),p]})}),v.jsxs(K1,{children:[v.jsx(fl,{onClick:()=>i(!1,f.name),children:"Remove Background"}),v.jsx(fl,{onClick:()=>i(!0,f.name),children:"Generate Mask"})]})]},f.name)},u=()=>t.map(f=>{const{IconClass:m,showName:p}=Y2[f.name];return f.name==="RealESRGAN"?s():f.name==="RemoveBG"||f.name==="AnimeSeg"?l(f):v.jsx(fl,{onClick:()=>i(!1,f.name),disabled:o,children:v.jsxs("div",{className:"flex gap-2 items-center",children:[v.jsx(m,{className:"p-1"}),p]})},f.name)});return v.jsxs(dJ,{modal:!1,children:[v.jsx(fJ,{className:"border rounded-lg z-10 bg-background outline-none",tabIndex:-1,children:v.jsx(wn,{variant:"ghost",size:"icon",asChild:!0,className:"p-1.5",children:v.jsx(KU,{strokeWidth:1})})}),v.jsx(gA,{side:"bottom",align:"start",children:u()})]})},yJ=Cx,wJ=yP,xJ=$x,vA=d.forwardRef(({className:e,...t},n)=>v.jsx(Bd,{className:Ce("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t,ref:n}));vA.displayName=Bd.displayName;const bJ=Dm("fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=closed]:duration-200 data-[state=open]:duration-300",{variants:{side:{top:"inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",bottom:"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",left:"inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",right:"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm"}},defaultVariants:{side:"right"}}),yA=d.forwardRef(({side:e="right",className:t,children:n,...r},o)=>v.jsxs(xJ,{children:[v.jsx(vA,{}),v.jsx(Ud,{ref:o,className:Ce(bJ({side:e}),t),...r,children:n})]}));yA.displayName=Ud.displayName;const wA=({className:e,...t})=>v.jsx("div",{className:Ce("flex flex-col space-y-2 text-center sm:text-left",e),...t});wA.displayName="SheetHeader";const SJ=d.forwardRef(({className:e,...t},n)=>v.jsx(Vd,{ref:n,className:Ce("text-lg font-semibold text-foreground",e),...t}));SJ.displayName=Vd.displayName;const _J=d.forwardRef(({className:e,...t},n)=>v.jsx(Wd,{ref:n,className:Ce("text-sm text-muted-foreground",e),...t}));_J.displayName=Wd.displayName;const Ut=({children:e})=>v.jsx("div",{className:"flex justify-between items-center pr-2",children:e}),Pt=({text:e,toolTip:t="",url:n,htmlFor:r,disabled:o=!1})=>v.jsxs(YT,{children:[v.jsx(XT,{asChild:!0,children:v.jsx(Zx,{htmlFor:r||e.toLowerCase().replace(" ","-"),className:"font-medium",disabled:o,children:e})}),t||n?v.jsxs(Sx,{className:"flex flex-col max-w-xs text-sm",side:"left",children:[v.jsx("p",{children:t}),n?v.jsx(wn,{variant:"link",className:"justify-end",children:v.jsx("a",{href:n,target:"_blank",children:"More info"})}):v.jsx(v.Fragment,{})]}):v.jsx(v.Fragment,{})]}),EJ=()=>{const[e,t]=bt(n=>[n.settings,n.updateSettings]);return v.jsxs("div",{className:"flex flex-col gap-4 mt-4",children:[v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{htmlFor:"steps",text:"Steps",toolTip:"The number of denoising steps. More denoising steps usually lead to a higher quality image at the expense of slower inference."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[30],min:1,max:100,step:1,value:[Math.floor(e.ldmSteps)],onValueChange:n=>t({ldmSteps:n[0]})}),v.jsx(Yn,{id:"steps",className:"w-[60px] rounded-full",numberValue:e.ldmSteps,allowFloat:!1,onNumberValueChange:n=>{t({ldmSteps:n})}})]})]}),v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Sampler"}),v.jsxs(Uo,{value:e.ldmSampler,onValueChange:n=>{t({ldmSampler:n})},children:[v.jsx(go,{className:"w-[100px]",children:v.jsx(Vo,{placeholder:"Select sampler"})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:Object.values(Qw).map(n=>v.jsx(yo,{value:n,children:n},n))})})]})]})]})},xA=d.forwardRef(({className:e,...t},n)=>v.jsx("textarea",{className:Ce("flex min-h-[60px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",e,"overflow-auto"),tabIndex:-1,ref:n,...t}));xA.displayName="Textarea";const Eh=({text:e,onClick:t})=>{const[n]=bt(r=>[r.settings.showExtender]);return v.jsx(wn,{variant:"outline",className:"p-1 h-8",disabled:!n,onClick:t,children:v.jsx("div",{className:"flex items-center gap-1",children:e})})},CJ=()=>{const[e,t,n,r,o,i,s,l,u,f,m]=bt(N=>[N.serverConfig.samplers,N.settings,N.paintByExampleFile,N.getIsProcessing(),N.updateSettings,N.runInpainting,N.updateAppState,N.updateExtenderByBuiltIn,N.updateExtenderDirection,N.adjustMask,N.clearMask]),[p,g]=Px(n),y=d.useRef(null);NP(y,()=>{y!=null&&y.current&&y.current.blur()});const b=N=>{N.key==="Enter"&&N.ctrlKey&&t.prompt.length!==0&&i()},S=()=>v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Cropper",toolTip:"Inpainting on part of image, improve inference speed and reduce memory usage."}),v.jsx(co,{id:"cropper",checked:t.showCropper,onCheckedChange:N=>{o({showCropper:N}),N&&o({showExtender:!1})}})]}),E=()=>t.model.support_controlnet?v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex justify-between items-center pr-2",children:[v.jsx(Pt,{text:"ControlNet",toolTip:"Using an additional conditioning image to control how an image is generated",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#controlnet"}),v.jsx(co,{id:"controlnet",checked:t.enableControlnet,onCheckedChange:N=>{o({enableControlnet:N})}})]}),v.jsx("div",{className:"flex flex-col gap-1",children:v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[100],min:1,max:100,step:1,disabled:!t.enableControlnet,value:[Math.floor(t.controlnetConditioningScale*100)],onValueChange:N=>o({controlnetConditioningScale:N[0]/100})}),v.jsx(Yn,{id:"controlnet-weight",className:"w-[60px] rounded-full",disabled:!t.enableControlnet,numberValue:t.controlnetConditioningScale,allowFloat:!1,onNumberValueChange:N=>{o({controlnetConditioningScale:N})}})]})}),v.jsx("div",{className:"pr-2",children:v.jsxs(Uo,{defaultValue:t.controlnetMethod,value:t.controlnetMethod,onValueChange:N=>{o({controlnetMethod:N})},disabled:!t.enableControlnet,children:[v.jsx(go,{children:v.jsx(Vo,{placeholder:"Select control method"})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:Object.values(t.model.controlnets).map(N=>v.jsx(yo,{value:N,children:N.split("/")[1]},N))})})]})})]}),v.jsx(gn,{})]}):null,_=()=>t.model.support_lcm_lora?v.jsxs(v.Fragment,{children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"LCM LoRA",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inference_with_lcm_lora",toolTip:"Enable quality image generation in typically 2-4 steps. Suggest disabling guidance_scale by setting it to 0. You can also try values between 1.0 and 2.0. When LCM Lora is enabled, LCMSampler will be used automatically."}),v.jsx(co,{id:"lcm-lora",checked:t.enableLCMLora,onCheckedChange:N=>{o({enableLCMLora:N})}})]}),v.jsx(gn,{})]}):null,x=()=>t.model.support_freeu?v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex justify-between items-center pr-2",children:[v.jsx(Pt,{text:"FreeU",toolTip:"FreeU is a technique for improving image quality. Different models may require different FreeU-specific hyperparameters, which can be viewed in the more info section.",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/freeu"}),v.jsx(co,{id:"freeu",checked:t.enableFreeu,onCheckedChange:N=>{o({enableFreeu:N})}})]}),v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex justify-center gap-6",children:[v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-s1",text:"s1",disabled:!t.enableFreeu}),v.jsx(Yn,{id:"freeu-s1",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.s1,allowFloat:!0,onNumberValueChange:N=>{o({freeuConfig:{...t.freeuConfig,s1:N}})}})]}),v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-s2",text:"s2",disabled:!t.enableFreeu}),v.jsx(Yn,{id:"freeu-s2",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.s2,allowFloat:!0,onNumberValueChange:N=>{o({freeuConfig:{...t.freeuConfig,s2:N}})}})]})]}),v.jsxs("div",{className:"flex justify-center gap-6",children:[v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-b1",text:"b1",disabled:!t.enableFreeu}),v.jsx(Yn,{id:"freeu-b1",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.b1,allowFloat:!0,onNumberValueChange:N=>{o({freeuConfig:{...t.freeuConfig,b1:N}})}})]}),v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-b2",text:"b2",disabled:!t.enableFreeu}),v.jsx(Yn,{id:"freeu-b2",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.b2,allowFloat:!0,onNumberValueChange:N=>{o({freeuConfig:{...t.freeuConfig,b2:N}})}})]})]})]}),v.jsx(gn,{})]}):null,C=()=>t.model.need_prompt?v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsx(Pt,{text:"Negative prompt",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#negative-prompt",toolTip:"Negative prompt guides the model away from generating certain things in an image"}),v.jsx("div",{className:"pl-2 pr-4",children:v.jsx(xA,{ref:y,rows:4,onKeyUp:b,className:"max-h-[8rem] overflow-y-auto mb-2",placeholder:"",id:"negative-prompt",value:t.negativePrompt,onInput:N=>{N.preventDefault(),N.stopPropagation();const ie=N.target;o({negativePrompt:ie.value})}})})]}):null,R=()=>t.model.name!==Gk?null:v.jsxs("div",{children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Example Image",toolTip:"An example image to guide image generation."}),v.jsx(f1,{tooltip:"Upload example image",onFileUpload:N=>{s({paintByExampleFile:N})},children:v.jsx(qT,{})})]}),g?v.jsx("div",{className:"flex justify-center items-center",children:v.jsx("img",{src:p.src,alt:"example",className:"max-w-[200px] max-h-[200px] m-3"})}):v.jsx(v.Fragment,{}),v.jsx(wn,{variant:"default",className:"w-full",disabled:r||!g,onClick:()=>{i()},children:"Paint"})]}),P=()=>t.model.name!==uF?null:v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Image guidance scale",toolTip:"Push the generated image towards the inital image. Higher image guidance scale encourages generated images that are closely linked to the source image, usually at the expense of lower image quality.",url:"https://huggingface.co/docs/diffusers/main/en/api/pipelines/pix2pix"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[150],min:100,max:1e3,step:1,value:[Math.floor(t.p2pImageGuidanceScale*100)],onValueChange:N=>o({p2pImageGuidanceScale:N[0]/100})}),v.jsx(Yn,{id:"image-guidance-scale",className:"w-[60px] rounded-full",numberValue:t.p2pImageGuidanceScale,allowFloat:!0,onNumberValueChange:N=>{o({p2pImageGuidanceScale:N})}})]})]}),M=()=>t.model.support_strength?v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Strength",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#strength",toolTip:"Strength is a measure of how much noise is added to the base image, which influences how similar the output is to the base image. Higher value means more noise and more different from the base image"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[100],min:10,max:100,step:1,value:[Math.floor(t.sdStrength*100)],onValueChange:N=>o({sdStrength:N[0]/100})}),v.jsx(Yn,{id:"strength",className:"w-[60px] rounded-full",numberValue:t.sdStrength,allowFloat:!0,onNumberValueChange:N=>{o({sdStrength:N})}})]})]}):null,A=()=>t.model.support_outpainting?v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Extender",toolTip:"Perform outpainting on images to expand it's content."}),v.jsx(co,{id:"extender",checked:t.showExtender,onCheckedChange:N=>{o({showExtender:N}),N&&o({showCropper:!1})}})]}),v.jsxs(Ut,{children:[v.jsxs(Uo,{defaultValue:t.extenderDirection,value:t.extenderDirection,onValueChange:N=>{u(N)},children:[v.jsx(go,{className:"w-[65px] h-7",disabled:!t.showExtender,children:v.jsx(Vo,{placeholder:"Select axis"})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:Object.values(Ln).map(N=>v.jsx(yo,{value:N,children:N},N))})})]}),v.jsxs("div",{className:"flex gap-1 justify-center mt-0",children:[v.jsx(Eh,{text:"1.25x",onClick:()=>l(t.extenderDirection,1.25)}),v.jsx(Eh,{text:"1.5x",onClick:()=>l(t.extenderDirection,1.5)}),v.jsx(Eh,{text:"1.75x",onClick:()=>l(t.extenderDirection,1.75)}),v.jsx(Eh,{text:"2.0x",onClick:()=>l(t.extenderDirection,2)})]})]})]}),v.jsx(gn,{})]}):null,D=()=>t.model.name!==dF?null:v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Task",toolTip:"PowerPaint task. When using extender, image-outpainting task will be auto used. For object-removal and image-outpainting, it is recommended to set the guidance_scale at 10 or above."}),v.jsxs(Uo,{defaultValue:t.powerpaintTask,value:t.powerpaintTask,onValueChange:N=>{o({powerpaintTask:N})},disabled:t.showExtender,children:[v.jsx(go,{className:"w-[140px]",children:v.jsx(Vo,{placeholder:"Select task"})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:[Ol.text_guided,Ol.object_remove,Ol.shape_guided].map(N=>v.jsx(yo,{value:N,children:N},N))})})]})]}),U=()=>v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{htmlFor:"steps",text:"Steps",toolTip:"The number of denoising steps. More denoising steps usually lead to a higher quality image at the expense of slower inference."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[30],min:1,max:100,step:1,value:[Math.floor(t.sdSteps)],onValueChange:N=>o({sdSteps:N[0]})}),v.jsx(Yn,{id:"steps",className:"w-[60px] rounded-full",numberValue:t.sdSteps,allowFloat:!1,onNumberValueChange:N=>{o({sdSteps:N})}})]})]}),W=()=>v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Guidance scale",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#guidance-scale",toolTip:"Guidance scale affects how aligned the text prompt and generated image are. Higher value means the prompt and generated image are closely aligned, so the output is a stricter interpretation of the prompt"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[750],min:0,max:1500,step:1,value:[Math.floor(t.sdGuidanceScale*100)],onValueChange:N=>o({sdGuidanceScale:N[0]/100})}),v.jsx(Yn,{id:"guidance-scale",className:"w-[60px] rounded-full",numberValue:t.sdGuidanceScale,allowFloat:!0,onNumberValueChange:N=>{o({sdGuidanceScale:N})}})]})]}),q=()=>t.model.name===fF?null:v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Sampler"}),v.jsxs(Uo,{defaultValue:t.sdSampler,value:t.sdSampler,onValueChange:N=>{o({sdSampler:N})},children:[v.jsx(go,{className:"w-[175px] text-xs",children:v.jsx(Vo,{placeholder:"Select sampler"})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:e.map(N=>v.jsx(yo,{value:N,className:"text-xs",children:N},N))})})]})]}),X=()=>v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Seed",toolTip:"Using same parameters and a fixed seed can generate same result image."}),v.jsxs("div",{className:"flex gap-2 justify-center items-center",children:[v.jsx(co,{id:"seed",checked:t.seedFixed,onCheckedChange:N=>{o({seedFixed:N})}}),v.jsx(Yn,{id:"seed",className:"w-[100px]",disabled:!t.seedFixed,numberValue:t.seed,allowFloat:!1,onNumberValueChange:N=>{o({seed:N})}})]})]}),ae=()=>v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Mask blur",toolTip:"How much to blur the mask before processing, in pixels. Make the generated inpainting boundaries appear more natural."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[t.sdMaskBlur],min:0,max:96,step:1,value:[Math.floor(t.sdMaskBlur)],onValueChange:N=>o({sdMaskBlur:N[0]})}),v.jsx(Yn,{id:"mask-blur",className:"w-[60px] rounded-full",numberValue:t.sdMaskBlur,allowFloat:!1,onNumberValueChange:N=>{o({sdMaskBlur:N})}})]})]}),V=()=>v.jsxs(v.Fragment,{children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Match histograms",toolTip:"Match the inpainting result histogram to the source image histogram",url:"https://github.com/Sanster/lama-cleaner/pull/143#issuecomment-1325859307"}),v.jsx(co,{id:"match-histograms",checked:t.sdMatchHistograms,onCheckedChange:N=>{o({sdMatchHistograms:N})}})]}),v.jsx(gn,{})]}),F=()=>v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{htmlFor:"adjustMaskKernelSize",text:"Adjust Mask",toolTip:"Expand or shrink mask. Using the slider to adjust the kernel size for dilation or erosion."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[12],min:1,max:100,step:1,value:[Math.floor(t.adjustMaskKernelSize)],onValueChange:N=>o({adjustMaskKernelSize:N[0]})}),v.jsx(Yn,{id:"adjustMaskKernelSize",className:"w-[60px] rounded-full",numberValue:t.adjustMaskKernelSize,allowFloat:!1,onNumberValueChange:N=>{o({adjustMaskKernelSize:N})}})]}),v.jsxs(Ut,{children:[v.jsxs("div",{className:"flex gap-1 justify-start",children:[v.jsx(wn,{variant:"outline",className:"p-1 h-8",onClick:()=>f("expand"),disabled:r,children:v.jsx("div",{className:"flex items-center gap-1 select-none",children:"expand"})}),v.jsx(wn,{variant:"outline",className:"p-1 h-8",onClick:()=>f("shrink"),disabled:r,children:v.jsx("div",{className:"flex items-center gap-1 select-none",children:"Shrink"})}),v.jsx(wn,{variant:"outline",className:"p-1 h-8",onClick:()=>f("reverse"),disabled:r,children:v.jsx("div",{className:"flex items-center gap-1 select-none",children:"Reverse"})})]}),v.jsx(wn,{variant:"outline",className:"p-1 h-8 justify-self-end",onClick:m,disabled:r,children:v.jsx("div",{className:"flex items-center gap-1 select-none",children:"Clear"})})]})]}),v.jsx(gn,{})]});return v.jsxs("div",{className:"flex flex-col gap-4 mt-4",children:[S(),A(),F(),D(),U(),W(),P(),M(),q(),X(),C(),v.jsx(gn,{}),E(),_(),ae(),V(),x(),R()]})},$J=()=>{const[e,t]=bt(n=>[n.settings,n.updateSettings]);return v.jsxs("div",{className:"flex flex-col gap-4 mt-4",children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"CV2 Flag",url:"https://docs.opencv.org/4.8.0/d7/d8b/group__photo__inpaint.html#gga8002a65f5a3328fbf15df81b842d3c3ca892824c38e258feb5e72f308a358d52e"}),v.jsxs(Uo,{value:e.cv2Flag,onValueChange:n=>{t({cv2Flag:n})},children:[v.jsx(go,{className:"w-[160px]",children:v.jsx(Vo,{placeholder:"Select flag"})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:Object.values(Jw).map(n=>v.jsx(yo,{value:n,children:n},n))})})]})]}),v.jsx(Pt,{text:"CV2 Radius",url:"https://docs.opencv.org/4.8.0/d7/d8b/group__photo__inpaint.html#gga8002a65f5a3328fbf15df81b842d3c3ca892824c38e258feb5e72f308a358d52e"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[5],min:1,max:100,step:1,value:[Math.floor(e.cv2Radius)],onValueChange:n=>t({cv2Radius:n[0]})}),v.jsx(Yn,{id:"cv2-radius",className:"w-[60px] rounded-full",numberValue:e.cv2Radius,allowFloat:!1,onNumberValueChange:n=>{t({cv2Radius:n})}})]})]})},RJ=()=>{const[e,t]=bt(i=>[i.settings,i.windowSize]),[n,r]=OP(!0);if(Zn("c",()=>{r()}),e.model.name!==sC&&e.model.name!==aC&&e.model.model_type===fs)return null;const o=()=>e.model.name===sC?v.jsx(EJ,{}):e.model.name===aC?v.jsx($J,{}):v.jsx(CJ,{});return v.jsxs(yJ,{open:n,modal:!1,children:[v.jsx(wJ,{tabIndex:-1,className:"z-10 outline-none absolute top-[68px] right-6 rounded-lg border bg-background",children:v.jsx(wn,{variant:"ghost",size:"icon",asChild:!0,className:"p-1.5",onClick:r,children:v.jsx(GU,{strokeWidth:1})})}),v.jsxs(yA,{side:"right",className:"w-[300px] mt-[60px] outline-none pl-4 pr-1",onOpenAutoFocus:i=>i.preventDefault(),onPointerDownOutside:i=>i.preventDefault(),children:[v.jsxs(wA,{children:[v.jsxs(Ut,{children:[v.jsx("div",{className:"overflow-hidden mr-8",children:e.model.name.split("/")[e.model.name.split("/").length-1]}),v.jsx(wn,{variant:"ghost",size:"icon",className:"border h-6 w-6",onClick:r,children:v.jsx(YU,{strokeWidth:1})})]}),v.jsx(gn,{})]}),v.jsx(ag,{style:{height:t.height-160},className:"pr-3",children:o()})]})]})},Jo=Object.create(null);Jo.open="0";Jo.close="1";Jo.ping="2";Jo.pong="3";Jo.message="4";Jo.upgrade="5";Jo.noop="6";const op=Object.create(null);Object.keys(Jo).forEach(e=>{op[Jo[e]]=e});const G1={type:"error",data:"parser error"},bA=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",SA=typeof ArrayBuffer=="function",_A=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,ib=({type:e,data:t},n,r)=>bA&&t instanceof Blob?n?r(t):X2(t,r):SA&&(t instanceof ArrayBuffer||_A(t))?n?r(t):X2(new Blob([t]),r):r(Jo[e]+(t||"")),X2=(e,t)=>{const n=new FileReader;return n.onload=function(){const r=n.result.split(",")[1];t("b"+(r||""))},n.readAsDataURL(e)};function Z2(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let z0;function kJ(e,t){if(bA&&e.data instanceof Blob)return e.data.arrayBuffer().then(Z2).then(t);if(SA&&(e.data instanceof ArrayBuffer||_A(e.data)))return t(Z2(e.data));ib(e,!1,n=>{z0||(z0=new TextEncoder),t(z0.encode(n))})}const q2="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",_u=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let e=0;e{let t=e.length*.75,n=e.length,r,o=0,i,s,l,u;e[e.length-1]==="="&&(t--,e[e.length-2]==="="&&t--);const f=new ArrayBuffer(t),m=new Uint8Array(f);for(r=0;r>4,m[o++]=(s&15)<<4|l>>2,m[o++]=(l&3)<<6|u&63;return f},PJ=typeof ArrayBuffer=="function",sb=(e,t)=>{if(typeof e!="string")return{type:"message",data:EA(e,t)};const n=e.charAt(0);return n==="b"?{type:"message",data:AJ(e.substring(1),t)}:op[n]?e.length>1?{type:op[n],data:e.substring(1)}:{type:op[n]}:G1},AJ=(e,t)=>{if(PJ){const n=TJ(e);return EA(n,t)}else return{base64:!0,data:e}},EA=(e,t)=>{switch(t){case"blob":return e instanceof Blob?e:new Blob([e]);case"arraybuffer":default:return e instanceof ArrayBuffer?e:e.buffer}},CA="",MJ=(e,t)=>{const n=e.length,r=new Array(n);let o=0;e.forEach((i,s)=>{ib(i,!1,l=>{r[s]=l,++o===n&&t(r.join(CA))})})},OJ=(e,t)=>{const n=e.split(CA),r=[];for(let o=0;o{const r=n.length;let o;if(r<126)o=new Uint8Array(1),new DataView(o.buffer).setUint8(0,r);else if(r<65536){o=new Uint8Array(3);const i=new DataView(o.buffer);i.setUint8(0,126),i.setUint16(1,r)}else{o=new Uint8Array(9);const i=new DataView(o.buffer);i.setUint8(0,127),i.setBigUint64(1,BigInt(r))}e.data&&typeof e.data!="string"&&(o[0]|=128),t.enqueue(o),t.enqueue(n)})}})}let B0;function Ch(e){return e.reduce((t,n)=>t+n.length,0)}function $h(e,t){if(e[0].length===t)return e.shift();const n=new Uint8Array(t);let r=0;for(let o=0;oMath.pow(2,21)-1){l.enqueue(G1);break}o=m*Math.pow(2,32)+f.getUint32(4),r=3}else{if(Ch(n)e){l.enqueue(G1);break}}}})}const $A=4;function qt(e){if(e)return IJ(e)}function IJ(e){for(var t in qt.prototype)e[t]=qt.prototype[t];return e}qt.prototype.on=qt.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this};qt.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this};qt.prototype.off=qt.prototype.removeListener=qt.prototype.removeAllListeners=qt.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,o=0;o(e.hasOwnProperty(r)&&(n[r]=e[r]),n),{})}const LJ=Br.setTimeout,FJ=Br.clearTimeout;function vg(e,t){t.useNativeTimers?(e.setTimeoutFn=LJ.bind(Br),e.clearTimeoutFn=FJ.bind(Br)):(e.setTimeoutFn=Br.setTimeout.bind(Br),e.clearTimeoutFn=Br.clearTimeout.bind(Br))}const jJ=1.33;function zJ(e){return typeof e=="string"?BJ(e):Math.ceil((e.byteLength||e.size)*jJ)}function BJ(e){let t=0,n=0;for(let r=0,o=e.length;r=57344?n+=3:(r++,n+=4);return n}function UJ(e){let t="";for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+="&"),t+=encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t}function VJ(e){let t={},n=e.split("&");for(let r=0,o=n.length;r0);return t}function TA(){const e=e$(+new Date);return e!==J2?(Q2=0,J2=e):e+"."+e$(Q2++)}for(;Rh{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)};OJ(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,MJ(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]=TA()),!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 Xo(this.uri(),t)}doWrite(t,n){const r=this.request({method:"POST",data:t});r.on("success",n),r.on("error",(o,i)=>{this.onError("xhr post error",o,i)})}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}}class Xo extends qt{constructor(t,n){super(),vg(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=RA(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");n.xdomain=!!this.opts.xd;const r=this.xhr=new AA(n);try{r.open(this.method,this.uri,!0);try{if(this.opts.extraHeaders){r.setDisableHeaderCheck&&r.setDisableHeaderCheck(!0);for(let o in this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(o)&&r.setRequestHeader(o,this.opts.extraHeaders[o])}}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 o;r.readyState===3&&((o=this.opts.cookieJar)===null||o===void 0||o.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(o){this.setTimeoutFn(()=>{this.onError(o)},0);return}typeof document<"u"&&(this.index=Xo.requestsCount++,Xo.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=GJ,t)try{this.xhr.abort()}catch{}typeof document<"u"&&delete Xo.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()}}Xo.requestsCount=0;Xo.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",t$);else if(typeof addEventListener=="function"){const e="onpagehide"in Br?"pagehide":"unload";addEventListener(e,t$,!1)}}function t$(){for(let e in Xo.requests)Xo.requests.hasOwnProperty(e)&&Xo.requests[e].abort()}const lb=typeof Promise=="function"&&typeof Promise.resolve=="function"?t=>Promise.resolve().then(t):(t,n)=>n(t,0),kh=Br.WebSocket||Br.MozWebSocket,n$=!0,ZJ="arraybuffer",r$=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class qJ extends ab{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=r$?{}:RA(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=n$&&!r$?n?new kh(t,n):new kh(t):new kh(t,n,r)}catch(o){return this.emitReserved("error",o)}this.ws.binaryType=this.socket.binaryType,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{n$&&this.ws.send(i)}catch{}o&&lb(()=>{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]=TA()),this.supportsBinary||(n.b64=1),this.createUri(t,n)}check(){return!!kh}}class QJ extends ab{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=DJ(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=t.readable.pipeThrough(n).getReader(),o=NJ();o.readable.pipeTo(t.writable),this.writer=o.writable.getWriter();const i=()=>{r.read().then(({done:l,value:u})=>{l||(this.onPacket(u),i())}).catch(l=>{})};i();const s={type:"open"};this.query.sid&&(s.data=`{"sid":"${this.query.sid}"}`),this.writer.write(s).then(()=>this.onOpen())})}))}write(t){this.writable=!1;for(let n=0;n{o&&lb(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;(t=this.transport)===null||t===void 0||t.close()}}const JJ={websocket:qJ,webtransport:QJ,polling:XJ},eee=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,tee=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function X1(e){if(e.length>2e3)throw"URI too long";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 o=eee.exec(e||""),i={},s=14;for(;s--;)i[tee[s]]=o[s]||"";return n!=-1&&r!=-1&&(i.source=t,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=nee(i,i.path),i.queryKey=ree(i,i.query),i}function nee(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 ree(e,t){const n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(r,o,i){o&&(n[o]=i)}),n}let MA=class hl extends qt{constructor(t,n={}){super(),this.binaryType=ZJ,this.writeBuffer=[],t&&typeof t=="object"&&(n=t,t=null),t?(t=X1(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=X1(n.host).host),vg(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=VJ(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=$A,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 JJ[t](r)}open(){let t;if(this.opts.rememberUpgrade&&hl.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;hl.priorWebsocketSuccess=!1;const o=()=>{r||(n.send([{type:"ping",data:"probe"}]),n.once("packet",p=>{if(!r)if(p.type==="pong"&&p.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",n),!n)return;hl.priorWebsocketSuccess=n.name==="websocket",this.transport.pause(()=>{r||this.readyState!=="closed"&&(m(),this.setTransport(n),n.send([{type:"upgrade"}]),this.emitReserved("upgrade",n),n=null,this.upgrading=!1,this.flush())})}else{const g=new Error("probe error");g.transport=n.name,this.emitReserved("upgradeError",g)}}))};function i(){r||(r=!0,m(),n.close(),n=null)}const s=p=>{const g=new Error("probe error: "+p);g.transport=n.name,i(),this.emitReserved("upgradeError",g)};function l(){s("transport closed")}function u(){s("socket closed")}function f(p){n&&p.name!==n.name&&i()}const m=()=>{n.removeListener("open",o),n.removeListener("error",s),n.removeListener("close",l),this.off("close",u),this.off("upgrading",f)};n.once("open",o),n.once("error",s),n.once("close",l),this.once("close",u),this.once("upgrading",f),this.upgrades.indexOf("webtransport")!==-1&&t!=="webtransport"?this.setTimeoutFn(()=>{r||n.open()},200):n.open()}onOpen(){if(this.readyState="open",hl.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,o){if(typeof n=="function"&&(o=n,n=void 0),typeof r=="function"&&(o=r,r=null),this.readyState==="closing"||this.readyState==="closed")return;r=r||{},r.compress=r.compress!==!1;const i={type:t,data:n,options:r};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),o&&this.once("flush",o),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){hl.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 o=t.length;for(;rtypeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,OA=Object.prototype.toString,aee=typeof Blob=="function"||typeof Blob<"u"&&OA.call(Blob)==="[object BlobConstructor]",lee=typeof File=="function"||typeof File<"u"&&OA.call(File)==="[object FileConstructor]";function cb(e){return iee&&(e instanceof ArrayBuffer||see(e))||aee&&e instanceof Blob||lee&&e instanceof File}function ip(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(i),n.apply(this,[null,...s])}}emitWithAck(t,...n){const r=this.flags.timeout!==void 0||this._opts.ackTimeout!==void 0;return new Promise((o,i)=>{n.push((s,l)=>r?s?i(s):o(l):o(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((o,...i)=>r!==this._queue[0]?void 0:(o!==null?r.tryCount>this._opts.retries&&(this._queue.shift(),n&&n(o)):(this._queue.shift(),n&&n(null,...i)),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:lt.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 lt.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 lt.EVENT:case lt.BINARY_EVENT:this.onevent(t);break;case lt.ACK:case lt.BINARY_ACK:this.onack(t);break;case lt.DISCONNECT:this.ondisconnect();break;case lt.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(...o){r||(r=!0,n.packet({type:lt.ACK,id:t,data:o}))}}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:lt.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}Ac.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};Ac.prototype.reset=function(){this.attempts=0};Ac.prototype.setMin=function(e){this.ms=e};Ac.prototype.setMax=function(e){this.max=e};Ac.prototype.setJitter=function(e){this.jitter=e};class Q1 extends qt{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,vg(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 Ac({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(n.timeout==null?2e4:n.timeout),this._readyState="closed",this.uri=t;const o=n.parser||mee;this.encoder=new o.Encoder,this.decoder=new o.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 MA(this.uri,this.opts);const n=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;const o=fo(n,"open",function(){r.onopen(),t&&t()}),i=l=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",l),t?t(l):this.maybeReconnectOnOpen()},s=fo(n,"error",i);if(this._timeout!==!1){const l=this._timeout,u=this.setTimeoutFn(()=>{o(),i(new Error("timeout")),n.close()},l);this.opts.autoUnref&&u.unref(),this.subs.push(()=>{this.clearTimeoutFn(u)})}return this.subs.push(o),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(fo(t,"ping",this.onping.bind(this)),fo(t,"data",this.ondata.bind(this)),fo(t,"error",this.onerror.bind(this)),fo(t,"close",this.onclose.bind(this)),fo(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){lb(()=>{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 NA(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(o=>{o?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",o)):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 gu={};function sp(e,t){typeof e=="object"&&(t=e,e=void 0),t=t||{};const n=oee(e,t.path||"/socket.io"),r=n.source,o=n.id,i=n.path,s=gu[o]&&i in gu[o].nsps,l=t.forceNew||t["force new connection"]||t.multiplex===!1||s;let u;return l?u=new Q1(r,t):(gu[o]||(gu[o]=new Q1(r,t)),u=gu[o]),n.query&&!t.query&&(t.query=n.queryKey),u.socket(n.path,t)}Object.assign(sp,{Manager:Q1,Socket:NA,io:sp,connect:sp});const DA="Progress",yg=100,[vee,kte]=Mn(DA),[yee,wee]=vee(DA),IA=d.forwardRef((e,t)=>{const{__scopeProgress:n,value:r,max:o,getValueLabel:i=See,...s}=e,l=J1(o)?o:yg,u=FA(r,l)?r:null,f=lm(u)?i(u,l):void 0;return d.createElement(yee,{scope:n,value:u,max:l},d.createElement(Pe.div,Y({"aria-valuemax":l,"aria-valuemin":0,"aria-valuenow":lm(u)?u:void 0,"aria-valuetext":f,role:"progressbar","data-state":LA(u,l),"data-value":u??void 0,"data-max":l},s,{ref:t})))});IA.propTypes={max(e,t,n){const r=e[t],o=String(r);return r&&!J1(r)?new Error(_ee(o,n)):null},value(e,t,n){const r=e[t],o=String(r),i=J1(e.max)?e.max:yg;return r!=null&&!FA(r,i)?new Error(Eee(o,n)):null}};const xee="ProgressIndicator",bee=d.forwardRef((e,t)=>{var n;const{__scopeProgress:r,...o}=e,i=wee(xee,r);return d.createElement(Pe.div,Y({"data-state":LA(i.value,i.max),"data-value":(n=i.value)!==null&&n!==void 0?n:void 0,"data-max":i.max},o,{ref:t}))});function See(e,t){return`${Math.round(e/t*100)}%`}function LA(e,t){return e==null?"indeterminate":e===t?"complete":"loading"}function lm(e){return typeof e=="number"}function J1(e){return lm(e)&&!isNaN(e)&&e>0}function FA(e,t){return lm(e)&&!isNaN(e)&&e<=t&&e>=0}function _ee(e,t){return`Invalid prop \`max\` of value \`${e}\` supplied to \`${t}\`. Only numbers greater than 0 are valid max values. Defaulting to \`${yg}\`.`}function Eee(e,t){return`Invalid prop \`value\` of value \`${e}\` supplied to \`${t}\`. The \`value\` prop must be: + - a positive number + - less than the value passed to \`max\` (or ${yg} if no \`max\` prop is set) + - \`null\` if the progress is indeterminate. + +Defaulting to \`null\`.`}const jA=IA,Cee=bee,zA=d.forwardRef(({className:e,value:t,...n},r)=>v.jsx(jA,{ref:r,className:Ce("relative h-2 w-full overflow-hidden rounded-full bg-primary/20",e),...n,children:v.jsx(Cee,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(t||0)}%)`}})}));zA.displayName=jA.displayName;const $ee="",Zi=sp($ee),Ree=()=>{const[e,t,n]=bt(u=>[u.settings,u.isInpainting,u.isSD()]),[r,o]=d.useState(!1),[i,s]=d.useState(0),l=Math.min(Math.round(i/e.sdSteps*100),100);return d.useEffect(()=>(Zi.on("connect",()=>{o(!0)}),Zi.on("disconnect",()=>{o(!1)}),Zi.on("diffusion_progress",u=>{u&&s(u.step+1)}),Zi.on("diffusion_finish",()=>{s(0)}),()=>{Zi.off("connect"),Zi.off("disconnect"),Zi.off("diffusion_progress"),Zi.off("diffusion_finish")}),[]),v.jsxs("div",{className:"z-10 fixed bg-background w-[220px] left-1/2 -translate-x-1/2 top-[68px] h-[32px] flex justify-center items-center gap-[18px] border-[1px] border-[solid] rounded-[14px] pl-[8px] pr-[8px]",style:{visibility:r&&t&&n?"visible":"hidden"},children:[v.jsx(zA,{value:l}),v.jsxs("div",{className:"w-[45px] flex justify-center font-nums",children:[l,"%"]})]})},kee=()=>{const[e,t]=bt(n=>[n.file,n.updateSettings]);return d.useEffect(()=>{(async()=>{const r=await Uj();t({model:r})})()},[]),v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"flex gap-3 absolute top-[68px] left-[24px] items-center",children:[v.jsx(vJ,{}),v.jsx(qq,{})]}),v.jsx(Wq,{}),v.jsx(Ree,{}),v.jsx(RJ,{}),e?v.jsx(Zq,{file:e}):v.jsx(v.Fragment,{})]})},Tee=()=>{const[e,t]=d.useState(window.innerWidth),n=d.useCallback(()=>{t(window.innerWidth)},[]);if(d.useEffect(()=>(window.addEventListener("resize",n),()=>{window.removeEventListener("resize",n)})),e<768)return"mobile";if(e>=768&&e<1224)return"tablet";if(e>=1224)return"desktop"};function Pee(e){const{onSelection:t}=e,[n]=d.useState(`file-upload-${Math.random().toString()}`),r=Tee();function o(i){if(!(!i||!i.type.match("image.*")))try{if(i.size>20*1024*1024)throw new Error("file too large");t(i)}catch(l){alert(`error: ${l.message}`)}}return v.jsx("div",{className:"absolute flex w-screen h-screen justify-center items-center pointer-events-none",children:v.jsx("label",{htmlFor:n,className:"grid bg-background border-[2px] border-[dashed] rounded-lg min-w-[600px] hover:bg-primary hover:text-primary-foreground pointer-events-auto",children:v.jsxs("div",{className:"grid p-16 w-full h-full",onDragOver:i=>{i.stopPropagation(),i.preventDefault()},children:[v.jsx("input",{className:"hidden",id:n,name:n,type:"file",onChange:i=>{var l;const s=(l=i.currentTarget.files)==null?void 0:l[0];s&&o(s)},accept:"image/png, image/jpeg"}),v.jsx("p",{className:"text-center",children:r==="desktop"?"Click here or drag an image file":"Tap here to load your picture"})]})})})}const BA="ToastProvider",[db,Aee,Mee]=Gd("Toast"),[UA,Tte]=Mn("Toast",[Mee]),[Oee,wg]=UA(BA),VA=e=>{const{__scopeToast:t,label:n="Notification",duration:r=5e3,swipeDirection:o="right",swipeThreshold:i=50,children:s}=e,[l,u]=d.useState(null),[f,m]=d.useState(0),p=d.useRef(!1),g=d.useRef(!1);return d.createElement(db.Provider,{scope:t},d.createElement(Oee,{scope:t,label:n,duration:r,swipeDirection:o,swipeThreshold:i,toastCount:f,viewport:l,onViewportChange:u,onToastAdd:d.useCallback(()=>m(y=>y+1),[]),onToastRemove:d.useCallback(()=>m(y=>y-1),[]),isFocusedToastEscapeKeyDownRef:p,isClosePausedRef:g},s))};VA.propTypes={label(e){if(e.label&&typeof e.label=="string"&&!e.label.trim()){const t=`Invalid prop \`label\` supplied to \`${BA}\`. Expected non-empty \`string\`.`;return new Error(t)}return null}};const Nee="ToastViewport",Dee=["F8"],ew="toast.viewportPause",tw="toast.viewportResume",Iee=d.forwardRef((e,t)=>{const{__scopeToast:n,hotkey:r=Dee,label:o="Notifications ({hotkey})",...i}=e,s=wg(Nee,n),l=Aee(n),u=d.useRef(null),f=d.useRef(null),m=d.useRef(null),p=d.useRef(null),g=Be(t,p,s.onViewportChange),y=r.join("+").replace(/Key/g,"").replace(/Digit/g,""),b=s.toastCount>0;d.useEffect(()=>{const E=_=>{var x;r.every(R=>_[R]||_.code===R)&&((x=p.current)===null||x===void 0||x.focus())};return document.addEventListener("keydown",E),()=>document.removeEventListener("keydown",E)},[r]),d.useEffect(()=>{const E=u.current,_=p.current;if(b&&E&&_){const x=()=>{if(!s.isClosePausedRef.current){const M=new CustomEvent(ew);_.dispatchEvent(M),s.isClosePausedRef.current=!0}},C=()=>{if(s.isClosePausedRef.current){const M=new CustomEvent(tw);_.dispatchEvent(M),s.isClosePausedRef.current=!1}},R=M=>{!E.contains(M.relatedTarget)&&C()},P=()=>{E.contains(document.activeElement)||C()};return E.addEventListener("focusin",x),E.addEventListener("focusout",R),E.addEventListener("pointermove",x),E.addEventListener("pointerleave",P),window.addEventListener("blur",x),window.addEventListener("focus",C),()=>{E.removeEventListener("focusin",x),E.removeEventListener("focusout",R),E.removeEventListener("pointermove",x),E.removeEventListener("pointerleave",P),window.removeEventListener("blur",x),window.removeEventListener("focus",C)}}},[b,s.isClosePausedRef]);const S=d.useCallback(({tabbingDirection:E})=>{const x=l().map(C=>{const R=C.ref.current,P=[R,...Qee(R)];return E==="forwards"?P:P.reverse()});return(E==="forwards"?x.reverse():x).flat()},[l]);return d.useEffect(()=>{const E=p.current;if(E){const _=x=>{const C=x.altKey||x.ctrlKey||x.metaKey;if(x.key==="Tab"&&!C){const D=document.activeElement,U=x.shiftKey;if(x.target===E&&U){var P;(P=f.current)===null||P===void 0||P.focus();return}const X=S({tabbingDirection:U?"backwards":"forwards"}),ae=X.findIndex(V=>V===D);if(U0(X.slice(ae+1)))x.preventDefault();else{var M,A;U?(M=f.current)===null||M===void 0||M.focus():(A=m.current)===null||A===void 0||A.focus()}}};return E.addEventListener("keydown",_),()=>E.removeEventListener("keydown",_)}},[l,S]),d.createElement(EB,{ref:u,role:"region","aria-label":o.replace("{hotkey}",y),tabIndex:-1,style:{pointerEvents:b?void 0:"none"}},b&&d.createElement(i$,{ref:f,onFocusFromOutsideViewport:()=>{const E=S({tabbingDirection:"forwards"});U0(E)}}),d.createElement(db.Slot,{scope:n},d.createElement(Pe.ol,Y({tabIndex:-1},i,{ref:g}))),b&&d.createElement(i$,{ref:m,onFocusFromOutsideViewport:()=>{const E=S({tabbingDirection:"backwards"});U0(E)}}))}),Lee="ToastFocusProxy",i$=d.forwardRef((e,t)=>{const{__scopeToast:n,onFocusFromOutsideViewport:r,...o}=e,i=wg(Lee,n);return d.createElement(Hm,Y({"aria-hidden":!0,tabIndex:0},o,{ref:t,style:{position:"fixed"},onFocus:s=>{var l;const u=s.relatedTarget;!((l=i.viewport)!==null&&l!==void 0&&l.contains(u))&&r()}}))}),xg="Toast",Fee="toast.swipeStart",jee="toast.swipeMove",zee="toast.swipeCancel",Bee="toast.swipeEnd",Uee=d.forwardRef((e,t)=>{const{forceMount:n,open:r,defaultOpen:o,onOpenChange:i,...s}=e,[l=!0,u]=Zr({prop:r,defaultProp:o,onChange:i});return d.createElement(Sn,{present:n||l},d.createElement(WA,Y({open:l},s,{ref:t,onClose:()=>u(!1),onPause:Ft(e.onPause),onResume:Ft(e.onResume),onSwipeStart:de(e.onSwipeStart,f=>{f.currentTarget.setAttribute("data-swipe","start")}),onSwipeMove:de(e.onSwipeMove,f=>{const{x:m,y:p}=f.detail.delta;f.currentTarget.setAttribute("data-swipe","move"),f.currentTarget.style.setProperty("--radix-toast-swipe-move-x",`${m}px`),f.currentTarget.style.setProperty("--radix-toast-swipe-move-y",`${p}px`)}),onSwipeCancel:de(e.onSwipeCancel,f=>{f.currentTarget.setAttribute("data-swipe","cancel"),f.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),f.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),f.currentTarget.style.removeProperty("--radix-toast-swipe-end-x"),f.currentTarget.style.removeProperty("--radix-toast-swipe-end-y")}),onSwipeEnd:de(e.onSwipeEnd,f=>{const{x:m,y:p}=f.detail.delta;f.currentTarget.setAttribute("data-swipe","end"),f.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),f.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),f.currentTarget.style.setProperty("--radix-toast-swipe-end-x",`${m}px`),f.currentTarget.style.setProperty("--radix-toast-swipe-end-y",`${p}px`),u(!1)})})))}),[Vee,Wee]=UA(xg,{onClose(){}}),WA=d.forwardRef((e,t)=>{const{__scopeToast:n,type:r="foreground",duration:o,open:i,onClose:s,onEscapeKeyDown:l,onPause:u,onResume:f,onSwipeStart:m,onSwipeMove:p,onSwipeCancel:g,onSwipeEnd:y,...b}=e,S=wg(xg,n),[E,_]=d.useState(null),x=Be(t,V=>_(V)),C=d.useRef(null),R=d.useRef(null),P=o||S.duration,M=d.useRef(0),A=d.useRef(P),D=d.useRef(0),{onToastAdd:U,onToastRemove:W}=S,q=Ft(()=>{var V;(E==null?void 0:E.contains(document.activeElement))&&((V=S.viewport)===null||V===void 0||V.focus()),s()}),X=d.useCallback(V=>{!V||V===1/0||(window.clearTimeout(D.current),M.current=new Date().getTime(),D.current=window.setTimeout(q,V))},[q]);d.useEffect(()=>{const V=S.viewport;if(V){const F=()=>{X(A.current),f==null||f()},N=()=>{const ie=new Date().getTime()-M.current;A.current=A.current-ie,window.clearTimeout(D.current),u==null||u()};return V.addEventListener(ew,N),V.addEventListener(tw,F),()=>{V.removeEventListener(ew,N),V.removeEventListener(tw,F)}}},[S.viewport,P,u,f,X]),d.useEffect(()=>{i&&!S.isClosePausedRef.current&&X(P)},[i,P,S.isClosePausedRef,X]),d.useEffect(()=>(U(),()=>W()),[U,W]);const ae=d.useMemo(()=>E?YA(E):null,[E]);return S.viewport?d.createElement(d.Fragment,null,ae&&d.createElement(Hee,{__scopeToast:n,role:"status","aria-live":r==="foreground"?"assertive":"polite","aria-atomic":!0},ae),d.createElement(Vee,{scope:n,onClose:q},Is.createPortal(d.createElement(db.ItemSlot,{scope:n},d.createElement(_B,{asChild:!0,onEscapeKeyDown:de(l,()=>{S.isFocusedToastEscapeKeyDownRef.current||q(),S.isFocusedToastEscapeKeyDownRef.current=!1})},d.createElement(Pe.li,Y({role:"status","aria-live":"off","aria-atomic":!0,tabIndex:0,"data-state":i?"open":"closed","data-swipe-direction":S.swipeDirection},b,{ref:x,style:{userSelect:"none",touchAction:"none",...e.style},onKeyDown:de(e.onKeyDown,V=>{V.key==="Escape"&&(l==null||l(V.nativeEvent),V.nativeEvent.defaultPrevented||(S.isFocusedToastEscapeKeyDownRef.current=!0,q()))}),onPointerDown:de(e.onPointerDown,V=>{V.button===0&&(C.current={x:V.clientX,y:V.clientY})}),onPointerMove:de(e.onPointerMove,V=>{if(!C.current)return;const F=V.clientX-C.current.x,N=V.clientY-C.current.y,ie=!!R.current,K=["left","right"].includes(S.swipeDirection),Z=["left","up"].includes(S.swipeDirection)?Math.min:Math.max,H=K?Z(0,F):0,se=K?0:Z(0,N),ce=V.pointerType==="touch"?10:2,Ve={x:H,y:se},Ue={originalEvent:V,delta:Ve};ie?(R.current=Ve,Th(jee,p,Ue,{discrete:!1})):s$(Ve,S.swipeDirection,ce)?(R.current=Ve,Th(Fee,m,Ue,{discrete:!1}),V.target.setPointerCapture(V.pointerId)):(Math.abs(F)>ce||Math.abs(N)>ce)&&(C.current=null)}),onPointerUp:de(e.onPointerUp,V=>{const F=R.current,N=V.target;if(N.hasPointerCapture(V.pointerId)&&N.releasePointerCapture(V.pointerId),R.current=null,C.current=null,F){const ie=V.currentTarget,K={originalEvent:V,delta:F};s$(F,S.swipeDirection,S.swipeThreshold)?Th(Bee,y,K,{discrete:!0}):Th(zee,g,K,{discrete:!0}),ie.addEventListener("click",Z=>Z.preventDefault(),{once:!0})}})})))),S.viewport))):null});WA.propTypes={type(e){if(e.type&&!["foreground","background"].includes(e.type)){const t=`Invalid prop \`type\` supplied to \`${xg}\`. Expected \`foreground | background\`.`;return new Error(t)}return null}};const Hee=e=>{const{__scopeToast:t,children:n,...r}=e,o=wg(xg,t),[i,s]=d.useState(!1),[l,u]=d.useState(!1);return Zee(()=>s(!0)),d.useEffect(()=>{const f=window.setTimeout(()=>u(!0),1e3);return()=>window.clearTimeout(f)},[]),l?null:d.createElement(zd,{asChild:!0},d.createElement(Hm,r,i&&d.createElement(d.Fragment,null,o.label," ",n)))},Kee=d.forwardRef((e,t)=>{const{__scopeToast:n,...r}=e;return d.createElement(Pe.div,Y({},r,{ref:t}))}),Gee=d.forwardRef((e,t)=>{const{__scopeToast:n,...r}=e;return d.createElement(Pe.div,Y({},r,{ref:t}))}),Yee="ToastAction",HA=d.forwardRef((e,t)=>{const{altText:n,...r}=e;return n?d.createElement(GA,{altText:n,asChild:!0},d.createElement(KA,Y({},r,{ref:t}))):null});HA.propTypes={altText(e){return e.altText?null:new Error(`Missing prop \`altText\` expected on \`${Yee}\``)}};const Xee="ToastClose",KA=d.forwardRef((e,t)=>{const{__scopeToast:n,...r}=e,o=Wee(Xee,n);return d.createElement(GA,{asChild:!0},d.createElement(Pe.button,Y({type:"button"},r,{ref:t,onClick:de(e.onClick,o.onClose)})))}),GA=d.forwardRef((e,t)=>{const{__scopeToast:n,altText:r,...o}=e;return d.createElement(Pe.div,Y({"data-radix-toast-announce-exclude":"","data-radix-toast-announce-alt":r||void 0},o,{ref:t}))});function YA(e){const t=[];return Array.from(e.childNodes).forEach(r=>{if(r.nodeType===r.TEXT_NODE&&r.textContent&&t.push(r.textContent),qee(r)){const o=r.ariaHidden||r.hidden||r.style.display==="none",i=r.dataset.radixToastAnnounceExclude==="";if(!o)if(i){const s=r.dataset.radixToastAnnounceAlt;s&&t.push(s)}else t.push(...YA(r))}}),t}function Th(e,t,n,{discrete:r}){const o=n.originalEvent.currentTarget,i=new CustomEvent(e,{bubbles:!0,cancelable:!0,detail:n});t&&o.addEventListener(e,t,{once:!0}),r?dx(o,i):o.dispatchEvent(i)}const s$=(e,t,n=0)=>{const r=Math.abs(e.x),o=Math.abs(e.y),i=r>o;return t==="left"||t==="right"?i&&r>n:!i&&o>n};function Zee(e=()=>{}){const t=Ft(e);An(()=>{let n=0,r=0;return n=window.requestAnimationFrame(()=>r=window.requestAnimationFrame(t)),()=>{window.cancelAnimationFrame(n),window.cancelAnimationFrame(r)}},[t])}function qee(e){return e.nodeType===e.ELEMENT_NODE}function Qee(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const o=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||o?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function U0(e){const t=document.activeElement;return e.some(n=>n===t?!0:(n.focus(),document.activeElement!==t))}const Jee=VA,XA=Iee,ZA=Uee,qA=Kee,QA=Gee,JA=HA,eM=KA,ete=Jee,tM=d.forwardRef(({className:e,...t},n)=>v.jsx(XA,{ref:n,className:Ce("fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]",e),tabIndex:-1,...t}));tM.displayName=XA.displayName;const tte=Dm("group pointer-events-auto relative flex w-full items-center justify-between space-x-2 overflow-hidden rounded-md border p-4 pr-6 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full",{variants:{variant:{default:"border bg-background text-foreground",destructive:"destructive group border-destructive bg-destructive text-destructive-foreground"}},defaultVariants:{variant:"default"}}),nM=d.forwardRef(({className:e,variant:t,...n},r)=>v.jsx(ZA,{ref:r,className:Ce(tte({variant:t}),e),tabIndex:-1,...n}));nM.displayName=ZA.displayName;const nte=d.forwardRef(({className:e,...t},n)=>v.jsx(JA,{ref:n,className:Ce("inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium transition-colors hover:bg-secondary focus:outline-none focus:ring-1 focus:ring-ring disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive",e),tabIndex:-1,...t}));nte.displayName=JA.displayName;const rM=d.forwardRef(({className:e,...t},n)=>v.jsx(eM,{ref:n,className:Ce("absolute right-1 top-1 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-1 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600",e),"toast-close":"",tabIndex:-1,...t,children:v.jsx(wT,{className:"h-4 w-4"})}));rM.displayName=eM.displayName;const oM=d.forwardRef(({className:e,...t},n)=>v.jsx(qA,{ref:n,className:Ce("text-sm font-semibold [&+div]:text-xs",e),tabIndex:-1,...t}));oM.displayName=qA.displayName;const iM=d.forwardRef(({className:e,...t},n)=>v.jsx(QA,{ref:n,className:Ce("text-sm opacity-90",e),...t,tabIndex:-1}));iM.displayName=QA.displayName;function rte(){const{toasts:e}=Id();return v.jsxs(ete,{children:[e.map(function({id:t,title:n,description:r,action:o,...i}){return v.jsxs(nM,{...i,children:[v.jsxs("div",{className:"grid gap-1",children:[n&&v.jsx(oM,{children:n}),r&&v.jsx(iM,{children:r})]}),o,v.jsx(rM,{})]},t)}),v.jsx(tM,{})]})}const ote=["image/jpeg","image/png","image/webp","image/bmp","image/tiff"];function ite(){const[e,t,n,r]=bt(g=>[g.file,g.updateAppState,g.setServerConfig,g.setFile]),o=Yj(),i=vH();d.useEffect(()=>{o&&r(o)},[o,r]),d.useEffect(()=>{t({windowSize:i})},[i]),d.useEffect(()=>{(async()=>{const y=await gT();n(y),y.isDesktop&&pF()})()},[]);const s=d.useRef(0),l=d.useCallback(g=>{g.preventDefault(),g.stopPropagation()},[]),u=d.useCallback(g=>{g.preventDefault(),g.stopPropagation(),s.current+=1},[]),f=d.useCallback(g=>{g.preventDefault(),g.stopPropagation(),s.current-=1,s.current>0},[]),m=d.useCallback(g=>{if(g.preventDefault(),g.stopPropagation(),g.dataTransfer.files&&g.dataTransfer.files.length>0){if(!(g.dataTransfer.files.length>1)){const y=g.dataTransfer.files[0],b=y.type;ote.includes(b)&&r(y)}g.dataTransfer.clearData()}},[]),p=d.useCallback(g=>{if(!g.clipboardData)return;const y=g.clipboardData.items,b=[].slice.call(y).filter(_=>_.type.indexOf("image")!==-1);if(b.length===0)return;g.preventDefault(),g.stopPropagation();const E=b[0].getAsFile();E&&r(E)},[]);return d.useEffect(()=>(window.addEventListener("dragenter",u),window.addEventListener("dragleave",f),window.addEventListener("dragover",l),window.addEventListener("drop",m),window.addEventListener("paste",p),function(){window.removeEventListener("dragenter",u),window.removeEventListener("dragleave",f),window.removeEventListener("dragover",l),window.removeEventListener("drop",m),window.removeEventListener("paste",p)})),v.jsxs("main",{className:"flex min-h-screen flex-col items-center justify-between w-full bg-[radial-gradient(circle_at_1px_1px,_#8e8e8e8e_1px,_transparent_0)] [background-size:20px_20px] bg-repeat",children:[v.jsx(rte,{}),v.jsx(nZ,{}),v.jsx(kee,{}),e?v.jsx(v.Fragment,{}):v.jsx(Pee,{onSelection:async g=>{r(g)}})]})}const cm=["light","dark"],fb="(prefers-color-scheme: dark)",ste=typeof window>"u",sM=d.createContext(void 0),ate=e=>d.useContext(sM)?Fe.createElement(d.Fragment,null,e.children):Fe.createElement(cte,e),lte=["light","dark"],cte=({forcedTheme:e,disableTransitionOnChange:t=!1,enableSystem:n=!0,enableColorScheme:r=!0,storageKey:o="theme",themes:i=lte,defaultTheme:s=n?"system":"light",attribute:l="data-theme",value:u,children:f,nonce:m})=>{const[p,g]=d.useState(()=>a$(o,s)),[y,b]=d.useState(()=>a$(o)),S=u?Object.values(u):i,E=d.useCallback(R=>{let P=R;if(!P)return;R==="system"&&n&&(P=l$());const M=u?u[P]:P,A=t?dte():null,D=document.documentElement;if(l==="class"?(D.classList.remove(...S),M&&D.classList.add(M)):M?D.setAttribute(l,M):D.removeAttribute(l),r){const U=cm.includes(s)?s:null,W=cm.includes(P)?P:U;D.style.colorScheme=W}A==null||A()},[]),_=d.useCallback(R=>{g(R);try{localStorage.setItem(o,R)}catch{}},[e]),x=d.useCallback(R=>{const P=l$(R);b(P),p==="system"&&n&&!e&&E("system")},[p,e]);d.useEffect(()=>{const R=window.matchMedia(fb);return R.addListener(x),x(R),()=>R.removeListener(x)},[x]),d.useEffect(()=>{const R=P=>{P.key===o&&_(P.newValue||s)};return window.addEventListener("storage",R),()=>window.removeEventListener("storage",R)},[_]),d.useEffect(()=>{E(e??p)},[e,p]);const C=d.useMemo(()=>({theme:p,setTheme:_,forcedTheme:e,resolvedTheme:p==="system"?y:p,themes:n?[...i,"system"]:i,systemTheme:n?y:void 0}),[p,_,e,y,n,i]);return Fe.createElement(sM.Provider,{value:C},Fe.createElement(ute,{forcedTheme:e,disableTransitionOnChange:t,enableSystem:n,enableColorScheme:r,storageKey:o,themes:i,defaultTheme:s,attribute:l,value:u,children:f,attrs:S,nonce:m}),f)},ute=d.memo(({forcedTheme:e,storageKey:t,attribute:n,enableSystem:r,enableColorScheme:o,defaultTheme:i,value:s,attrs:l,nonce:u})=>{const f=i==="system",m=n==="class"?`var d=document.documentElement,c=d.classList;c.remove(${l.map(b=>`'${b}'`).join(",")});`:`var d=document.documentElement,n='${n}',s='setAttribute';`,p=o?cm.includes(i)&&i?`if(e==='light'||e==='dark'||!e)d.style.colorScheme=e||'${i}'`:"if(e==='light'||e==='dark')d.style.colorScheme=e":"",g=(b,S=!1,E=!0)=>{const _=s?s[b]:b,x=S?b+"|| ''":`'${_}'`;let C="";return o&&E&&!S&&cm.includes(b)&&(C+=`d.style.colorScheme = '${b}';`),n==="class"?C+=S||_?`c.add(${x})`:"null":_&&(C+=`d[s](n,${x})`),C},y=e?`!function(){${m}${g(e)}}()`:r?`!function(){try{${m}var e=localStorage.getItem('${t}');if('system'===e||(!e&&${f})){var t='${fb}',m=window.matchMedia(t);if(m.media!==t||m.matches){${g("dark")}}else{${g("light")}}}else if(e){${s?`var x=${JSON.stringify(s)};`:""}${g(s?"x[e]":"e",!0)}}${f?"":"else{"+g(i,!1,!1)+"}"}${p}}catch(e){}}()`:`!function(){try{${m}var e=localStorage.getItem('${t}');if(e){${s?`var x=${JSON.stringify(s)};`:""}${g(s?"x[e]":"e",!0)}}else{${g(i,!1,!1)};}${p}}catch(t){}}();`;return Fe.createElement("script",{nonce:u,dangerouslySetInnerHTML:{__html:y}})},()=>!0),a$=(e,t)=>{if(ste)return;let n;try{n=localStorage.getItem(e)||void 0}catch{}return n||t},dte=()=>{const e=document.createElement("style");return e.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(e),()=>{window.getComputedStyle(document.body),setTimeout(()=>{document.head.removeChild(e)},1)}},l$=e=>(e||(e=window.matchMedia(fb)),e.matches?"dark":"light"),fte=new pL;V0.createRoot(document.getElementById("root")).render(v.jsx(Fe.StrictMode,{children:v.jsx(wL,{client:fte,children:v.jsx(ate,{defaultTheme:"dark",disableTransitionOnChange:!0,children:v.jsx(VU,{children:v.jsx(ite,{})})})})})); diff --git a/py/iopaint/web_app/assets/index-hrusMZZs.js b/py/iopaint/web_app/assets/index-hrusMZZs.js new file mode 100644 index 0000000..7a05f8a --- /dev/null +++ b/py/iopaint/web_app/assets/index-hrusMZZs.js @@ -0,0 +1,165 @@ +var Nv=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)};var z=(e,t,n)=>(Nv(e,t,"read from private field"),n?n.call(e):t.get(e)),Te=(e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)},ye=(e,t,n,r)=>(Nv(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n);var Ff=(e,t,n,r)=>({set _(o){ye(e,t,o,n)},get _(){return z(e,t,r)}}),tt=(e,t,n)=>(Nv(e,t,"access private method"),n);function SD(e,t){for(var n=0;nr[o]})}}}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 o of document.querySelectorAll('link[rel="modulepreload"]'))r(o);new MutationObserver(o=>{for(const i of o)if(i.type==="childList")for(const s of i.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&r(s)}).observe(document,{childList:!0,subtree:!0});function n(o){const i={};return o.integrity&&(i.integrity=o.integrity),o.referrerPolicy&&(i.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?i.credentials="include":o.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(o){if(o.ep)return;o.ep=!0;const i=n(o);fetch(o.href,i)}})();var Yc=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function lm(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var v$={exports:{}},cm={},y$={exports:{}},it={};/** + * @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 bd=Symbol.for("react.element"),ED=Symbol.for("react.portal"),CD=Symbol.for("react.fragment"),$D=Symbol.for("react.strict_mode"),kD=Symbol.for("react.profiler"),RD=Symbol.for("react.provider"),TD=Symbol.for("react.context"),PD=Symbol.for("react.forward_ref"),AD=Symbol.for("react.suspense"),OD=Symbol.for("react.memo"),MD=Symbol.for("react.lazy"),LS=Symbol.iterator;function ND(e){return e===null||typeof e!="object"?null:(e=LS&&e[LS]||e["@@iterator"],typeof e=="function"?e:null)}var w$={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},x$=Object.assign,b$={};function fc(e,t,n){this.props=e,this.context=t,this.refs=b$,this.updater=n||w$}fc.prototype.isReactComponent={};fc.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")};fc.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function _$(){}_$.prototype=fc.prototype;function ew(e,t,n){this.props=e,this.context=t,this.refs=b$,this.updater=n||w$}var tw=ew.prototype=new _$;tw.constructor=ew;x$(tw,fc.prototype);tw.isPureReactComponent=!0;var FS=Array.isArray,S$=Object.prototype.hasOwnProperty,nw={current:null},E$={key:!0,ref:!0,__self:!0,__source:!0};function C$(e,t,n){var r,o={},i=null,s=null;if(t!=null)for(r in t.ref!==void 0&&(s=t.ref),t.key!==void 0&&(i=""+t.key),t)S$.call(t,r)&&!E$.hasOwnProperty(r)&&(o[r]=t[r]);var l=arguments.length-2;if(l===1)o.children=n;else if(1>>1,ge=K[le];if(0>>1;leo(We,W))Meo(fe,We)?(K[le]=fe,K[Me]=W,le=Me):(K[le]=We,K[Ue]=W,le=Ue);else if(Meo(fe,W))K[le]=fe,K[Me]=W,le=Me;else break e}}return Q}function o(K,Q){var W=K.sortIndex-Q.sortIndex;return W!==0?W:K.id-Q.id}if(typeof performance=="object"&&typeof performance.now=="function"){var i=performance;e.unstable_now=function(){return i.now()}}else{var s=Date,l=s.now();e.unstable_now=function(){return s.now()-l}}var u=[],d=[],h=1,m=null,g=3,y=!1,x=!1,_=!1,C=typeof setTimeout=="function"?setTimeout:null,S=typeof clearTimeout=="function"?clearTimeout:null,b=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function E(K){for(var Q=n(d);Q!==null;){if(Q.callback===null)r(d);else if(Q.startTime<=K)r(d),Q.sortIndex=Q.expirationTime,t(u,Q);else break;Q=n(d)}}function k(K){if(_=!1,E(K),!x)if(n(u)!==null)x=!0,L(P);else{var Q=n(d);Q!==null&&ie(k,Q.startTime-K)}}function P(K,Q){x=!1,_&&(_=!1,S(O),O=-1),y=!0;var W=g;try{for(E(Q),m=n(u);m!==null&&(!(m.expirationTime>Q)||K&&!J());){var le=m.callback;if(typeof le=="function"){m.callback=null,g=m.priorityLevel;var ge=le(m.expirationTime<=Q);Q=e.unstable_now(),typeof ge=="function"?m.callback=ge:m===n(u)&&r(u),E(Q)}else r(u);m=n(u)}if(m!==null)var Ve=!0;else{var Ue=n(d);Ue!==null&&ie(k,Ue.startTime-Q),Ve=!1}return Ve}finally{m=null,g=W,y=!1}}var M=!1,A=null,O=-1,F=5,V=-1;function J(){return!(e.unstable_now()-VK||125le?(K.sortIndex=W,t(d,K),n(u)===null&&K===n(d)&&(_?(S(O),O=-1):_=!0,ie(k,W-le))):(K.sortIndex=ge,t(u,K),x||y||(x=!0,L(P))),K},e.unstable_shouldYield=J,e.unstable_wrapCallback=function(K){var Q=g;return function(){var W=g;g=Q;try{return K.apply(this,arguments)}finally{g=W}}}})(T$);R$.exports=T$;var KD=R$.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 P$=f,yr=KD;function ce(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"),B0=Object.prototype.hasOwnProperty,YD=/^[: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]*$/,zS={},BS={};function GD(e){return B0.call(BS,e)?!0:B0.call(zS,e)?!1:YD.test(e)?BS[e]=!0:(zS[e]=!0,!1)}function XD(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 ZD(e,t,n,r){if(t===null||typeof t>"u"||XD(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 Un(e,t,n,r,o,i,s){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=o,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=i,this.removeEmptyString=s}var wn={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){wn[e]=new Un(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];wn[t]=new Un(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){wn[e]=new Un(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){wn[e]=new Un(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){wn[e]=new Un(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){wn[e]=new Un(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){wn[e]=new Un(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){wn[e]=new Un(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){wn[e]=new Un(e,5,!1,e.toLowerCase(),null,!1,!1)});var ow=/[\-:]([a-z])/g;function iw(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(ow,iw);wn[t]=new Un(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(ow,iw);wn[t]=new Un(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(ow,iw);wn[t]=new Un(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){wn[e]=new Un(e,1,!1,e.toLowerCase(),null,!1,!1)});wn.xlinkHref=new Un("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){wn[e]=new Un(e,1,!1,e.toLowerCase(),null,!0,!0)});function sw(e,t,n,r){var o=wn.hasOwnProperty(t)?wn[t]:null;(o!==null?o.type!==0:r||!(2l||o[s]!==i[l]){var u=` +`+o[s].replace(" at new "," at ");return e.displayName&&u.includes("")&&(u=u.replace("",e.displayName)),u}while(1<=s&&0<=l);break}}}finally{Lv=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?uu(e):""}function qD(e){switch(e.tag){case 5:return uu(e.type);case 16:return uu("Lazy");case 13:return uu("Suspense");case 19:return uu("SuspenseList");case 0:case 2:case 15:return e=Fv(e.type,!1),e;case 11:return e=Fv(e.type.render,!1),e;case 1:return e=Fv(e.type,!0),e;default:return""}}function H0(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 ll:return"Fragment";case al:return"Portal";case U0:return"Profiler";case aw:return"StrictMode";case V0:return"Suspense";case W0:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case M$:return(e.displayName||"Context")+".Consumer";case O$:return(e._context.displayName||"Context")+".Provider";case lw:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case cw:return t=e.displayName||null,t!==null?t:H0(e.type)||"Memo";case Ki:t=e._payload,e=e._init;try{return H0(e(t))}catch{}}return null}function QD(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 H0(t);case 8:return t===aw?"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 Ss(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function D$(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function JD(e){var t=D$(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 o=n.get,i=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return o.call(this)},set:function(s){r=""+s,i.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 Bf(e){e._valueTracker||(e._valueTracker=JD(e))}function I$(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=D$(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function oh(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 K0(e,t){var n=t.checked;return zt({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function VS(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=Ss(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 L$(e,t){t=t.checked,t!=null&&sw(e,"checked",t,!1)}function Y0(e,t){L$(e,t);var n=Ss(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")?G0(e,t.type,n):t.hasOwnProperty("defaultValue")&&G0(e,t.type,Ss(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function WS(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 G0(e,t,n){(t!=="number"||oh(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var du=Array.isArray;function bl(e,t,n,r){if(e=e.options,t){t={};for(var o=0;o"+t.valueOf().toString()+"",t=Uf.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function Ou(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var vu={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},e9=["Webkit","ms","Moz","O"];Object.keys(vu).forEach(function(e){e9.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),vu[t]=vu[e]})});function B$(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||vu.hasOwnProperty(e)&&vu[e]?(""+t).trim():t+"px"}function U$(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,o=B$(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,o):e[n]=o}}var t9=zt({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 q0(e,t){if(t){if(t9[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(ce(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(ce(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(ce(61))}if(t.style!=null&&typeof t.style!="object")throw Error(ce(62))}}function Q0(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 J0=null;function uw(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var ey=null,_l=null,Sl=null;function YS(e){if(e=Ed(e)){if(typeof ey!="function")throw Error(ce(280));var t=e.stateNode;t&&(t=hm(t),ey(e.stateNode,e.type,t))}}function V$(e){_l?Sl?Sl.push(e):Sl=[e]:_l=e}function W$(){if(_l){var e=_l,t=Sl;if(Sl=_l=null,YS(e),t)for(e=0;e>>=0,e===0?32:31-(f9(e)/p9|0)|0}var Vf=64,Wf=4194304;function fu(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 lh(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,o=e.suspendedLanes,i=e.pingedLanes,s=n&268435455;if(s!==0){var l=s&~o;l!==0?r=fu(l):(i&=s,i!==0&&(r=fu(i)))}else s=n&~o,s!==0?r=fu(s):i!==0&&(r=fu(i));if(r===0)return 0;if(t!==0&&t!==r&&!(t&o)&&(o=r&-r,i=t&-t,o>=i||o===16&&(i&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 _d(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-go(t),e[t]=n}function v9(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=wu),nE=" ",rE=!1;function uk(e,t){switch(e){case"keyup":return H9.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function dk(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var cl=!1;function Y9(e,t){switch(e){case"compositionend":return dk(t);case"keypress":return t.which!==32?null:(rE=!0,nE);case"textInput":return e=t.data,e===nE&&rE?null:e;default:return null}}function G9(e,t){if(cl)return e==="compositionend"||!yw&&uk(e,t)?(e=lk(),$p=mw=rs=null,cl=!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=aE(n)}}function mk(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?mk(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function gk(){for(var e=window,t=oh();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=oh(e.document)}return t}function ww(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 rI(e){var t=gk(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&mk(n.ownerDocument.documentElement,n)){if(r!==null&&ww(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 o=n.textContent.length,i=Math.min(r.start,o);r=r.end===void 0?i:Math.min(r.end,o),!e.extend&&i>r&&(o=r,r=i,i=o),o=lE(n,i);var s=lE(n,r);o&&s&&(e.rangeCount!==1||e.anchorNode!==o.node||e.anchorOffset!==o.offset||e.focusNode!==s.node||e.focusOffset!==s.offset)&&(t=t.createRange(),t.setStart(o.node,o.offset),e.removeAllRanges(),i>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,ul=null,sy=null,bu=null,ay=!1;function cE(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;ay||ul==null||ul!==oh(r)||(r=ul,"selectionStart"in r&&ww(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}),bu&&Fu(bu,r)||(bu=r,r=dh(sy,"onSelect"),0pl||(e.current=py[pl],py[pl]=null,pl--)}function $t(e,t){pl++,py[pl]=e.current,e.current=t}var Es={},Tn=Ps(Es),Jn=Ps(!1),ba=Es;function Kl(e,t){var n=e.type.contextTypes;if(!n)return Es;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var o={},i;for(i in n)o[i]=t[i];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=o),o}function er(e){return e=e.childContextTypes,e!=null}function ph(){At(Jn),At(Tn)}function gE(e,t,n){if(Tn.current!==Es)throw Error(ce(168));$t(Tn,t),$t(Jn,n)}function Ck(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var o in r)if(!(o in t))throw Error(ce(108,QD(e)||"Unknown",o));return zt({},n,r)}function hh(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||Es,ba=Tn.current,$t(Tn,e),$t(Jn,Jn.current),!0}function vE(e,t,n){var r=e.stateNode;if(!r)throw Error(ce(169));n?(e=Ck(e,t,ba),r.__reactInternalMemoizedMergedChildContext=e,At(Jn),At(Tn),$t(Tn,e)):At(Jn),$t(Jn,n)}var li=null,mm=!1,Qv=!1;function $k(e){li===null?li=[e]:li.push(e)}function mI(e){mm=!0,$k(e)}function As(){if(!Qv&&li!==null){Qv=!0;var e=0,t=xt;try{var n=li;for(xt=1;e>=s,o-=s,ci=1<<32-go(t)+o|n<O?(F=A,A=null):F=A.sibling;var V=g(S,A,E[O],k);if(V===null){A===null&&(A=F);break}e&&A&&V.alternate===null&&t(S,A),b=i(V,b,O),M===null?P=V:M.sibling=V,M=V,A=F}if(O===E.length)return n(S,A),Dt&&qs(S,O),P;if(A===null){for(;OO?(F=A,A=null):F=A.sibling;var J=g(S,A,V.value,k);if(J===null){A===null&&(A=F);break}e&&A&&J.alternate===null&&t(S,A),b=i(J,b,O),M===null?P=J:M.sibling=J,M=J,A=F}if(V.done)return n(S,A),Dt&&qs(S,O),P;if(A===null){for(;!V.done;O++,V=E.next())V=m(S,V.value,k),V!==null&&(b=i(V,b,O),M===null?P=V:M.sibling=V,M=V);return Dt&&qs(S,O),P}for(A=r(S,A);!V.done;O++,V=E.next())V=y(A,S,O,V.value,k),V!==null&&(e&&V.alternate!==null&&A.delete(V.key===null?O:V.key),b=i(V,b,O),M===null?P=V:M.sibling=V,M=V);return e&&A.forEach(function(G){return t(S,G)}),Dt&&qs(S,O),P}function C(S,b,E,k){if(typeof E=="object"&&E!==null&&E.type===ll&&E.key===null&&(E=E.props.children),typeof E=="object"&&E!==null){switch(E.$$typeof){case zf:e:{for(var P=E.key,M=b;M!==null;){if(M.key===P){if(P=E.type,P===ll){if(M.tag===7){n(S,M.sibling),b=o(M,E.props.children),b.return=S,S=b;break e}}else if(M.elementType===P||typeof P=="object"&&P!==null&&P.$$typeof===Ki&&EE(P)===M.type){n(S,M.sibling),b=o(M,E.props),b.ref=Jc(S,M,E),b.return=S,S=b;break e}n(S,M);break}else t(S,M);M=M.sibling}E.type===ll?(b=xa(E.props.children,S.mode,k,E.key),b.return=S,S=b):(k=Np(E.type,E.key,E.props,null,S.mode,k),k.ref=Jc(S,b,E),k.return=S,S=k)}return s(S);case al:e:{for(M=E.key;b!==null;){if(b.key===M)if(b.tag===4&&b.stateNode.containerInfo===E.containerInfo&&b.stateNode.implementation===E.implementation){n(S,b.sibling),b=o(b,E.children||[]),b.return=S,S=b;break e}else{n(S,b);break}else t(S,b);b=b.sibling}b=s0(E,S.mode,k),b.return=S,S=b}return s(S);case Ki:return M=E._init,C(S,b,M(E._payload),k)}if(du(E))return x(S,b,E,k);if(Gc(E))return _(S,b,E,k);qf(S,E)}return typeof E=="string"&&E!==""||typeof E=="number"?(E=""+E,b!==null&&b.tag===6?(n(S,b.sibling),b=o(b,E),b.return=S,S=b):(n(S,b),b=i0(E,S.mode,k),b.return=S,S=b),s(S)):n(S,b)}return C}var Gl=Nk(!0),Dk=Nk(!1),Cd={},zo=Ps(Cd),Uu=Ps(Cd),Vu=Ps(Cd);function oa(e){if(e===Cd)throw Error(ce(174));return e}function Rw(e,t){switch($t(Vu,t),$t(Uu,e),$t(zo,Cd),e=t.nodeType,e){case 9:case 11:t=(t=t.documentElement)?t.namespaceURI:Z0(null,"");break;default:e=e===8?t.parentNode:t,t=e.namespaceURI||null,e=e.tagName,t=Z0(t,e)}At(zo),$t(zo,t)}function Xl(){At(zo),At(Uu),At(Vu)}function Ik(e){oa(Vu.current);var t=oa(zo.current),n=Z0(t,e.type);t!==n&&($t(Uu,e),$t(zo,n))}function Tw(e){Uu.current===e&&(At(zo),At(Uu))}var Lt=Ps(0);function xh(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 Jv=[];function Pw(){for(var e=0;en?n:4,e(!0);var r=e0.transition;e0.transition={};try{e(!1),t()}finally{xt=n,e0.transition=r}}function Qk(){return Gr().memoizedState}function wI(e,t,n){var r=ys(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},Jk(e))eR(t,n);else if(n=Pk(e,t,n,r),n!==null){var o=jn();vo(n,e,r,o),tR(n,t,r)}}function xI(e,t,n){var r=ys(e),o={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(Jk(e))eR(t,o);else{var i=e.alternate;if(e.lanes===0&&(i===null||i.lanes===0)&&(i=t.lastRenderedReducer,i!==null))try{var s=t.lastRenderedState,l=i(s,n);if(o.hasEagerState=!0,o.eagerState=l,wo(l,s)){var u=t.interleaved;u===null?(o.next=o,$w(t)):(o.next=u.next,u.next=o),t.interleaved=o;return}}catch{}finally{}n=Pk(e,t,o,r),n!==null&&(o=jn(),vo(n,e,r,o),tR(n,t,r))}}function Jk(e){var t=e.alternate;return e===jt||t!==null&&t===jt}function eR(e,t){_u=bh=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function tR(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,fw(e,n)}}var _h={readContext:Yr,useCallback:En,useContext:En,useEffect:En,useImperativeHandle:En,useInsertionEffect:En,useLayoutEffect:En,useMemo:En,useReducer:En,useRef:En,useState:En,useDebugValue:En,useDeferredValue:En,useTransition:En,useMutableSource:En,useSyncExternalStore:En,useId:En,unstable_isNewReconciler:!1},bI={readContext:Yr,useCallback:function(e,t){return ko().memoizedState=[e,t===void 0?null:t],e},useContext:Yr,useEffect:$E,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,Pp(4194308,4,Yk.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Pp(4194308,4,e,t)},useInsertionEffect:function(e,t){return Pp(4,2,e,t)},useMemo:function(e,t){var n=ko();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=ko();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=wI.bind(null,jt,e),[r.memoizedState,e]},useRef:function(e){var t=ko();return e={current:e},t.memoizedState=e},useState:CE,useDebugValue:Dw,useDeferredValue:function(e){return ko().memoizedState=e},useTransition:function(){var e=CE(!1),t=e[0];return e=yI.bind(null,e[1]),ko().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=jt,o=ko();if(Dt){if(n===void 0)throw Error(ce(407));n=n()}else{if(n=t(),dn===null)throw Error(ce(349));Sa&30||jk(r,t,n)}o.memoizedState=n;var i={value:n,getSnapshot:t};return o.queue=i,$E(Bk.bind(null,r,i,e),[e]),r.flags|=2048,Ku(9,zk.bind(null,r,i,n,t),void 0,null),n},useId:function(){var e=ko(),t=dn.identifierPrefix;if(Dt){var n=ui,r=ci;n=(r&~(1<<32-go(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=Wu++,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[Oo]=t,e[Bu]=r,uR(e,t,!1,!1),t.stateNode=e;e:{switch(s=Q0(n,r),n){case"dialog":Tt("cancel",e),Tt("close",e),o=r;break;case"iframe":case"object":case"embed":Tt("load",e),o=r;break;case"video":case"audio":for(o=0;oql&&(t.flags|=128,r=!0,eu(i,!1),t.lanes=4194304)}else{if(!r)if(e=xh(s),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),eu(i,!0),i.tail===null&&i.tailMode==="hidden"&&!s.alternate&&!Dt)return Cn(t),null}else 2*Zt()-i.renderingStartTime>ql&&n!==1073741824&&(t.flags|=128,r=!0,eu(i,!1),t.lanes=4194304);i.isBackwards?(s.sibling=t.child,t.child=s):(n=i.last,n!==null?n.sibling=s:t.child=s,i.last=s)}return i.tail!==null?(t=i.tail,i.rendering=t,i.tail=t.sibling,i.renderingStartTime=Zt(),t.sibling=null,n=Lt.current,$t(Lt,r?n&1|2:n&1),t):(Cn(t),null);case 22:case 23:return Bw(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?fr&1073741824&&(Cn(t),t.subtreeFlags&6&&(t.flags|=8192)):Cn(t),null;case 24:return null;case 25:return null}throw Error(ce(156,t.tag))}function TI(e,t){switch(bw(t),t.tag){case 1:return er(t.type)&&ph(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Xl(),At(Jn),At(Tn),Pw(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return Tw(t),null;case 13:if(At(Lt),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(ce(340));Yl()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return At(Lt),null;case 4:return Xl(),null;case 10:return Cw(t.type._context),null;case 22:case 23:return Bw(),null;case 24:return null;default:return null}}var Jf=!1,kn=!1,PI=typeof WeakSet=="function"?WeakSet:Set,Se=null;function vl(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){Wt(e,t,r)}else n.current=null}function Cy(e,t,n){try{n()}catch(r){Wt(e,t,r)}}var DE=!1;function AI(e,t){if(ly=ch,e=gk(),ww(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 o=r.anchorOffset,i=r.focusNode;r=r.focusOffset;try{n.nodeType,i.nodeType}catch{n=null;break e}var s=0,l=-1,u=-1,d=0,h=0,m=e,g=null;t:for(;;){for(var y;m!==n||o!==0&&m.nodeType!==3||(l=s+o),m!==i||r!==0&&m.nodeType!==3||(u=s+r),m.nodeType===3&&(s+=m.nodeValue.length),(y=m.firstChild)!==null;)g=m,m=y;for(;;){if(m===e)break t;if(g===n&&++d===o&&(l=s),g===i&&++h===r&&(u=s),(y=m.nextSibling)!==null)break;m=g,g=m.parentNode}m=y}n=l===-1||u===-1?null:{start:l,end:u}}else n=null}n=n||{start:0,end:0}}else n=null;for(cy={focusedElem:e,selectionRange:n},ch=!1,Se=t;Se!==null;)if(t=Se,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,Se=e;else for(;Se!==null;){t=Se;try{var x=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(x!==null){var _=x.memoizedProps,C=x.memoizedState,S=t.stateNode,b=S.getSnapshotBeforeUpdate(t.elementType===t.type?_:io(t.type,_),C);S.__reactInternalSnapshotBeforeUpdate=b}break;case 3:var E=t.stateNode.containerInfo;E.nodeType===1?E.textContent="":E.nodeType===9&&E.documentElement&&E.removeChild(E.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(ce(163))}}catch(k){Wt(t,t.return,k)}if(e=t.sibling,e!==null){e.return=t.return,Se=e;break}Se=t.return}return x=DE,DE=!1,x}function Su(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var o=r=r.next;do{if((o.tag&e)===e){var i=o.destroy;o.destroy=void 0,i!==void 0&&Cy(t,n,i)}o=o.next}while(o!==r)}}function ym(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 $y(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 pR(e){var t=e.alternate;t!==null&&(e.alternate=null,pR(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Oo],delete t[Bu],delete t[fy],delete t[pI],delete t[hI])),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 hR(e){return e.tag===5||e.tag===3||e.tag===4}function IE(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||hR(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 ky(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=fh));else if(r!==4&&(e=e.child,e!==null))for(ky(e,t,n),e=e.sibling;e!==null;)ky(e,t,n),e=e.sibling}function Ry(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(Ry(e,t,n),e=e.sibling;e!==null;)Ry(e,t,n),e=e.sibling}var mn=null,lo=!1;function ji(e,t,n){for(n=n.child;n!==null;)mR(e,t,n),n=n.sibling}function mR(e,t,n){if(jo&&typeof jo.onCommitFiberUnmount=="function")try{jo.onCommitFiberUnmount(um,n)}catch{}switch(n.tag){case 5:kn||vl(n,t);case 6:var r=mn,o=lo;mn=null,ji(e,t,n),mn=r,lo=o,mn!==null&&(lo?(e=mn,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):mn.removeChild(n.stateNode));break;case 18:mn!==null&&(lo?(e=mn,n=n.stateNode,e.nodeType===8?qv(e.parentNode,n):e.nodeType===1&&qv(e,n),Iu(e)):qv(mn,n.stateNode));break;case 4:r=mn,o=lo,mn=n.stateNode.containerInfo,lo=!0,ji(e,t,n),mn=r,lo=o;break;case 0:case 11:case 14:case 15:if(!kn&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){o=r=r.next;do{var i=o,s=i.destroy;i=i.tag,s!==void 0&&(i&2||i&4)&&Cy(n,t,s),o=o.next}while(o!==r)}ji(e,t,n);break;case 1:if(!kn&&(vl(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(l){Wt(n,t,l)}ji(e,t,n);break;case 21:ji(e,t,n);break;case 22:n.mode&1?(kn=(r=kn)||n.memoizedState!==null,ji(e,t,n),kn=r):ji(e,t,n);break;default:ji(e,t,n)}}function LE(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new PI),t.forEach(function(r){var o=zI.bind(null,e,r);n.has(r)||(n.add(r),r.then(o,o))})}}function ro(e,t){var n=t.deletions;if(n!==null)for(var r=0;ro&&(o=s),r&=~i}if(r=o,r=Zt()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*MI(r/1960))-r,10e?16:e,os===null)var r=!1;else{if(e=os,os=null,Ch=0,dt&6)throw Error(ce(331));var o=dt;for(dt|=4,Se=e.current;Se!==null;){var i=Se,s=i.child;if(Se.flags&16){var l=i.deletions;if(l!==null){for(var u=0;uZt()-jw?wa(e,0):Fw|=n),tr(e,t)}function SR(e,t){t===0&&(e.mode&1?(t=Wf,Wf<<=1,!(Wf&130023424)&&(Wf=4194304)):t=1);var n=jn();e=gi(e,t),e!==null&&(_d(e,t,n),tr(e,n))}function jI(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),SR(e,n)}function zI(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,o=e.memoizedState;o!==null&&(n=o.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(ce(314))}r!==null&&r.delete(t),SR(e,n)}var ER;ER=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||Jn.current)Qn=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return Qn=!1,kI(e,t,n);Qn=!!(e.flags&131072)}else Qn=!1,Dt&&t.flags&1048576&&kk(t,gh,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;Ap(e,t),e=t.pendingProps;var o=Kl(t,Tn.current);Cl(t,n),o=Ow(null,t,r,e,o,n);var i=Mw();return t.flags|=1,typeof o=="object"&&o!==null&&typeof o.render=="function"&&o.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,er(r)?(i=!0,hh(t)):i=!1,t.memoizedState=o.state!==null&&o.state!==void 0?o.state:null,kw(t),o.updater=gm,t.stateNode=o,o._reactInternals=t,yy(t,r,e,n),t=by(null,t,r,!0,i,n)):(t.tag=0,Dt&&i&&xw(t),Dn(null,t,o,n),t=t.child),t;case 16:r=t.elementType;e:{switch(Ap(e,t),e=t.pendingProps,o=r._init,r=o(r._payload),t.type=r,o=t.tag=UI(r),e=io(r,e),o){case 0:t=xy(null,t,r,e,n);break e;case 1:t=OE(null,t,r,e,n);break e;case 11:t=PE(null,t,r,e,n);break e;case 14:t=AE(null,t,r,io(r.type,e),n);break e}throw Error(ce(306,r,""))}return t;case 0:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),xy(e,t,r,o,n);case 1:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),OE(e,t,r,o,n);case 3:e:{if(aR(t),e===null)throw Error(ce(387));r=t.pendingProps,i=t.memoizedState,o=i.element,Ak(e,t),wh(t,r,null,n);var s=t.memoizedState;if(r=s.element,i.isDehydrated)if(i={element:r,isDehydrated:!1,cache:s.cache,pendingSuspenseBoundaries:s.pendingSuspenseBoundaries,transitions:s.transitions},t.updateQueue.baseState=i,t.memoizedState=i,t.flags&256){o=Zl(Error(ce(423)),t),t=ME(e,t,r,n,o);break e}else if(r!==o){o=Zl(Error(ce(424)),t),t=ME(e,t,r,n,o);break e}else for(mr=ms(t.stateNode.containerInfo.firstChild),gr=t,Dt=!0,po=null,n=Dk(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(Yl(),r===o){t=vi(e,t,n);break e}Dn(e,t,r,n)}t=t.child}return t;case 5:return Ik(t),e===null&&my(t),r=t.type,o=t.pendingProps,i=e!==null?e.memoizedProps:null,s=o.children,uy(r,o)?s=null:i!==null&&uy(r,i)&&(t.flags|=32),sR(e,t),Dn(e,t,s,n),t.child;case 6:return e===null&&my(t),null;case 13:return lR(e,t,n);case 4:return Rw(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=Gl(t,null,r,n):Dn(e,t,r,n),t.child;case 11:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),PE(e,t,r,o,n);case 7:return Dn(e,t,t.pendingProps,n),t.child;case 8:return Dn(e,t,t.pendingProps.children,n),t.child;case 12:return Dn(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,o=t.pendingProps,i=t.memoizedProps,s=o.value,$t(vh,r._currentValue),r._currentValue=s,i!==null)if(wo(i.value,s)){if(i.children===o.children&&!Jn.current){t=vi(e,t,n);break e}}else for(i=t.child,i!==null&&(i.return=t);i!==null;){var l=i.dependencies;if(l!==null){s=i.child;for(var u=l.firstContext;u!==null;){if(u.context===r){if(i.tag===1){u=fi(-1,n&-n),u.tag=2;var d=i.updateQueue;if(d!==null){d=d.shared;var h=d.pending;h===null?u.next=u:(u.next=h.next,h.next=u),d.pending=u}}i.lanes|=n,u=i.alternate,u!==null&&(u.lanes|=n),gy(i.return,n,t),l.lanes|=n;break}u=u.next}}else if(i.tag===10)s=i.type===t.type?null:i.child;else if(i.tag===18){if(s=i.return,s===null)throw Error(ce(341));s.lanes|=n,l=s.alternate,l!==null&&(l.lanes|=n),gy(s,n,t),s=i.sibling}else s=i.child;if(s!==null)s.return=i;else for(s=i;s!==null;){if(s===t){s=null;break}if(i=s.sibling,i!==null){i.return=s.return,s=i;break}s=s.return}i=s}Dn(e,t,o.children,n),t=t.child}return t;case 9:return o=t.type,r=t.pendingProps.children,Cl(t,n),o=Yr(o),r=r(o),t.flags|=1,Dn(e,t,r,n),t.child;case 14:return r=t.type,o=io(r,t.pendingProps),o=io(r.type,o),AE(e,t,r,o,n);case 15:return oR(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),Ap(e,t),t.tag=1,er(r)?(e=!0,hh(t)):e=!1,Cl(t,n),Mk(t,r,o),yy(t,r,o,n),by(null,t,r,!0,e,n);case 19:return cR(e,t,n);case 22:return iR(e,t,n)}throw Error(ce(156,t.tag))};function CR(e,t){return q$(e,t)}function BI(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 Ur(e,t,n,r){return new BI(e,t,n,r)}function Vw(e){return e=e.prototype,!(!e||!e.isReactComponent)}function UI(e){if(typeof e=="function")return Vw(e)?1:0;if(e!=null){if(e=e.$$typeof,e===lw)return 11;if(e===cw)return 14}return 2}function ws(e,t){var n=e.alternate;return n===null?(n=Ur(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 Np(e,t,n,r,o,i){var s=2;if(r=e,typeof e=="function")Vw(e)&&(s=1);else if(typeof e=="string")s=5;else e:switch(e){case ll:return xa(n.children,o,i,t);case aw:s=8,o|=8;break;case U0:return e=Ur(12,n,t,o|2),e.elementType=U0,e.lanes=i,e;case V0:return e=Ur(13,n,t,o),e.elementType=V0,e.lanes=i,e;case W0:return e=Ur(19,n,t,o),e.elementType=W0,e.lanes=i,e;case N$:return xm(n,o,i,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case O$:s=10;break e;case M$:s=9;break e;case lw:s=11;break e;case cw:s=14;break e;case Ki:s=16,r=null;break e}throw Error(ce(130,e==null?e:typeof e,""))}return t=Ur(s,n,t,o),t.elementType=e,t.type=r,t.lanes=i,t}function xa(e,t,n,r){return e=Ur(7,e,r,t),e.lanes=n,e}function xm(e,t,n,r){return e=Ur(22,e,r,t),e.elementType=N$,e.lanes=n,e.stateNode={isHidden:!1},e}function i0(e,t,n){return e=Ur(6,e,null,t),e.lanes=n,e}function s0(e,t,n){return t=Ur(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function VI(e,t,n,r,o){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=zv(0),this.expirationTimes=zv(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=zv(0),this.identifierPrefix=r,this.onRecoverableError=o,this.mutableSourceEagerHydrationData=null}function Ww(e,t,n,r,o,i,s,l,u){return e=new VI(e,t,n,l,u),t===1?(t=1,i===!0&&(t|=8)):t=0,i=Ur(3,null,null,t),e.current=i,i.stateNode=e,i.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},kw(i),e}function WI(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(TR)}catch(e){console.error(e)}}TR(),k$.exports=br;var Os=k$.exports;const XI=lm(Os);var HE=Os;z0.createRoot=HE.createRoot,z0.hydrateRoot=HE.hydrateRoot;var $d=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},Ql=typeof window>"u"||"Deno"in window;function Lr(){}function ZI(e,t){return typeof e=="function"?e(t):e}function My(e){return typeof e=="number"&&e>=0&&e!==1/0}function PR(e,t){return Math.max(e+(t||0)-Date.now(),0)}function KE(e,t){const{type:n="all",exact:r,fetchStatus:o,predicate:i,queryKey:s,stale:l}=e;if(s){if(r){if(t.queryHash!==Gw(s,t.options))return!1}else if(!Xu(t.queryKey,s))return!1}if(n!=="all"){const u=t.isActive();if(n==="active"&&!u||n==="inactive"&&u)return!1}return!(typeof l=="boolean"&&t.isStale()!==l||typeof o<"u"&&o!==t.state.fetchStatus||i&&!i(t))}function YE(e,t){const{exact:n,status:r,predicate:o,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(Gu(t.options.mutationKey)!==Gu(i))return!1}else if(!Xu(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||o&&!o(t))}function Gw(e,t){return((t==null?void 0:t.queryKeyHashFn)||Gu)(e)}function Gu(e){return JSON.stringify(e,(t,n)=>Dy(n)?Object.keys(n).sort().reduce((r,o)=>(r[o]=n[o],r),{}):n)}function Xu(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?!Object.keys(t).some(n=>!Xu(e[n],t[n])):!1}function AR(e,t){if(e===t)return e;const n=GE(e)&&GE(t);if(n||Dy(e)&&Dy(t)){const r=n?e.length:Object.keys(e).length,o=n?t:Object.keys(t),i=o.length,s=n?[]:{};let l=0;for(let u=0;u"u")return!0;const n=t.prototype;return!(!XE(n)||!n.hasOwnProperty("isPrototypeOf"))}function XE(e){return Object.prototype.toString.call(e)==="[object Object]"}function OR(e){return new Promise(t=>{setTimeout(t,e)})}function ZE(e){OR(0).then(e)}function Iy(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?AR(e,t):t}function qI(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function QI(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var ua,Zi,Pl,l$,JI=(l$=class extends $d{constructor(){super();Te(this,ua,void 0);Te(this,Zi,void 0);Te(this,Pl,void 0);ye(this,Pl,t=>{if(!Ql&&window.addEventListener){const n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){z(this,Zi)||this.setEventListener(z(this,Pl))}onUnsubscribe(){var t;this.hasListeners()||((t=z(this,Zi))==null||t.call(this),ye(this,Zi,void 0))}setEventListener(t){var n;ye(this,Pl,t),(n=z(this,Zi))==null||n.call(this),ye(this,Zi,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){z(this,ua)!==t&&(ye(this,ua,t),this.onFocus())}onFocus(){this.listeners.forEach(t=>{t()})}isFocused(){var t;return typeof z(this,ua)=="boolean"?z(this,ua):((t=globalThis.document)==null?void 0:t.visibilityState)!=="hidden"}},ua=new WeakMap,Zi=new WeakMap,Pl=new WeakMap,l$),Rh=new JI,Al,qi,Ol,c$,eL=(c$=class extends $d{constructor(){super();Te(this,Al,!0);Te(this,qi,void 0);Te(this,Ol,void 0);ye(this,Ol,t=>{if(!Ql&&window.addEventListener){const n=()=>t(!0),r=()=>t(!1);return window.addEventListener("online",n,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",r)}}})}onSubscribe(){z(this,qi)||this.setEventListener(z(this,Ol))}onUnsubscribe(){var t;this.hasListeners()||((t=z(this,qi))==null||t.call(this),ye(this,qi,void 0))}setEventListener(t){var n;ye(this,Ol,t),(n=z(this,qi))==null||n.call(this),ye(this,qi,t(this.setOnline.bind(this)))}setOnline(t){z(this,Al)!==t&&(ye(this,Al,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return z(this,Al)}},Al=new WeakMap,qi=new WeakMap,Ol=new WeakMap,c$),Th=new eL;function tL(e){return Math.min(1e3*2**e,3e4)}function Cm(e){return(e??"online")==="online"?Th.isOnline():!0}var MR=class{constructor(e){this.revert=e==null?void 0:e.revert,this.silent=e==null?void 0:e.silent}};function a0(e){return e instanceof MR}function NR(e){let t=!1,n=0,r=!1,o,i,s;const l=new Promise((C,S)=>{i=C,s=S}),u=C=>{var S;r||(y(new MR(C)),(S=e.abort)==null||S.call(e))},d=()=>{t=!0},h=()=>{t=!1},m=()=>!Rh.isFocused()||e.networkMode!=="always"&&!Th.isOnline(),g=C=>{var S;r||(r=!0,(S=e.onSuccess)==null||S.call(e,C),o==null||o(),i(C))},y=C=>{var S;r||(r=!0,(S=e.onError)==null||S.call(e,C),o==null||o(),s(C))},x=()=>new Promise(C=>{var S;o=b=>{const E=r||!m();return E&&C(b),E},(S=e.onPause)==null||S.call(e)}).then(()=>{var C;o=void 0,r||(C=e.onContinue)==null||C.call(e)}),_=()=>{if(r)return;let C;try{C=e.fn()}catch(S){C=Promise.reject(S)}Promise.resolve(C).then(g).catch(S=>{var M;if(r)return;const b=e.retry??(Ql?0:3),E=e.retryDelay??tL,k=typeof E=="function"?E(n,S):E,P=b===!0||typeof b=="number"&&n{if(m())return x()}).then(()=>{t?y(S):_()})})};return Cm(e.networkMode)?_():x().then(_),{promise:l,cancel:u,continue:()=>(o==null?void 0:o())?l:Promise.resolve(),cancelRetry:d,continueRetry:h}}function nL(){let e=[],t=0,n=h=>{h()},r=h=>{h()};const o=h=>{let m;t++;try{m=h()}finally{t--,t||l()}return m},i=h=>{t?e.push(h):ZE(()=>{n(h)})},s=h=>(...m)=>{i(()=>{h(...m)})},l=()=>{const h=e;e=[],h.length&&ZE(()=>{r(()=>{h.forEach(m=>{n(m)})})})};return{batch:o,batchCalls:s,schedule:i,setNotifyFunction:h=>{n=h},setBatchNotifyFunction:h=>{r=h}}}var gn=nL(),da,u$,DR=(u$=class{constructor(){Te(this,da,void 0)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),My(this.gcTime)&&ye(this,da,setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Ql?1/0:5*60*1e3))}clearGcTimeout(){z(this,da)&&(clearTimeout(z(this,da)),ye(this,da,void 0))}},da=new WeakMap,u$),Ml,Nl,Nr,Qi,Dr,cn,ud,fa,Dl,Dp,ao,ii,d$,rL=(d$=class extends DR{constructor(t){super();Te(this,Dl);Te(this,ao);Te(this,Ml,void 0);Te(this,Nl,void 0);Te(this,Nr,void 0);Te(this,Qi,void 0);Te(this,Dr,void 0);Te(this,cn,void 0);Te(this,ud,void 0);Te(this,fa,void 0);ye(this,fa,!1),ye(this,ud,t.defaultOptions),tt(this,Dl,Dp).call(this,t.options),ye(this,cn,[]),ye(this,Nr,t.cache),this.queryKey=t.queryKey,this.queryHash=t.queryHash,ye(this,Ml,t.state||oL(this.options)),this.state=z(this,Ml),this.scheduleGc()}get meta(){return this.options.meta}optionalRemove(){!z(this,cn).length&&this.state.fetchStatus==="idle"&&z(this,Nr).remove(this)}setData(t,n){const r=Iy(this.state.data,t,this.options);return tt(this,ao,ii).call(this,{data:r,type:"success",dataUpdatedAt:n==null?void 0:n.updatedAt,manual:n==null?void 0:n.manual}),r}setState(t,n){tt(this,ao,ii).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){var r;const n=z(this,Qi);return(r=z(this,Dr))==null||r.cancel(t),n?n.then(Lr).catch(Lr):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(z(this,Ml))}isActive(){return z(this,cn).some(t=>t.options.enabled!==!1)}isDisabled(){return this.getObserversCount()>0&&!this.isActive()}isStale(){return this.state.isInvalidated||!this.state.dataUpdatedAt||z(this,cn).some(t=>t.getCurrentResult().isStale)}isStaleByTime(t=0){return this.state.isInvalidated||!this.state.dataUpdatedAt||!PR(this.state.dataUpdatedAt,t)}onFocus(){var n;const t=z(this,cn).find(r=>r.shouldFetchOnWindowFocus());t==null||t.refetch({cancelRefetch:!1}),(n=z(this,Dr))==null||n.continue()}onOnline(){var n;const t=z(this,cn).find(r=>r.shouldFetchOnReconnect());t==null||t.refetch({cancelRefetch:!1}),(n=z(this,Dr))==null||n.continue()}addObserver(t){z(this,cn).includes(t)||(z(this,cn).push(t),this.clearGcTimeout(),z(this,Nr).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){z(this,cn).includes(t)&&(ye(this,cn,z(this,cn).filter(n=>n!==t)),z(this,cn).length||(z(this,Dr)&&(z(this,fa)?z(this,Dr).cancel({revert:!0}):z(this,Dr).cancelRetry()),this.scheduleGc()),z(this,Nr).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return z(this,cn).length}invalidate(){this.state.isInvalidated||tt(this,ao,ii).call(this,{type:"invalidate"})}fetch(t,n){var d,h,m,g;if(this.state.fetchStatus!=="idle"){if(this.state.dataUpdatedAt&&(n!=null&&n.cancelRefetch))this.cancel({silent:!0});else if(z(this,Qi))return(d=z(this,Dr))==null||d.continueRetry(),z(this,Qi)}if(t&&tt(this,Dl,Dp).call(this,t),!this.options.queryFn){const y=z(this,cn).find(x=>x.options.queryFn);y&&tt(this,Dl,Dp).call(this,y.options)}const r=new AbortController,o={queryKey:this.queryKey,meta:this.meta},i=y=>{Object.defineProperty(y,"signal",{enumerable:!0,get:()=>(ye(this,fa,!0),r.signal)})};i(o);const s=()=>this.options.queryFn?(ye(this,fa,!1),this.options.persister?this.options.persister(this.options.queryFn,o,this):this.options.queryFn(o)):Promise.reject(new Error(`Missing queryFn: '${this.options.queryHash}'`)),l={fetchOptions:n,options:this.options,queryKey:this.queryKey,state:this.state,fetchFn:s};i(l),(h=this.options.behavior)==null||h.onFetch(l,this),ye(this,Nl,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((m=l.fetchOptions)==null?void 0:m.meta))&&tt(this,ao,ii).call(this,{type:"fetch",meta:(g=l.fetchOptions)==null?void 0:g.meta});const u=y=>{var x,_,C,S;a0(y)&&y.silent||tt(this,ao,ii).call(this,{type:"error",error:y}),a0(y)||((_=(x=z(this,Nr).config).onError)==null||_.call(x,y,this),(S=(C=z(this,Nr).config).onSettled)==null||S.call(C,this.state.data,y,this)),this.isFetchingOptimistic||this.scheduleGc(),this.isFetchingOptimistic=!1};return ye(this,Dr,NR({fn:l.fetchFn,abort:r.abort.bind(r),onSuccess:y=>{var x,_,C,S;if(typeof y>"u"){u(new Error(`${this.queryHash} data is undefined`));return}this.setData(y),(_=(x=z(this,Nr).config).onSuccess)==null||_.call(x,y,this),(S=(C=z(this,Nr).config).onSettled)==null||S.call(C,y,this.state.error,this),this.isFetchingOptimistic||this.scheduleGc(),this.isFetchingOptimistic=!1},onError:u,onFail:(y,x)=>{tt(this,ao,ii).call(this,{type:"failed",failureCount:y,error:x})},onPause:()=>{tt(this,ao,ii).call(this,{type:"pause"})},onContinue:()=>{tt(this,ao,ii).call(this,{type:"continue"})},retry:l.options.retry,retryDelay:l.options.retryDelay,networkMode:l.options.networkMode})),ye(this,Qi,z(this,Dr).promise),z(this,Qi)}},Ml=new WeakMap,Nl=new WeakMap,Nr=new WeakMap,Qi=new WeakMap,Dr=new WeakMap,cn=new WeakMap,ud=new WeakMap,fa=new WeakMap,Dl=new WeakSet,Dp=function(t){this.options={...z(this,ud),...t},this.updateGcTime(this.options.gcTime)},ao=new WeakSet,ii=function(t){const n=r=>{switch(t.type){case"failed":return{...r,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...r,fetchStatus:"paused"};case"continue":return{...r,fetchStatus:"fetching"};case"fetch":return{...r,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:t.meta??null,fetchStatus:Cm(this.options.networkMode)?"fetching":"paused",...!r.dataUpdatedAt&&{error:null,status:"pending"}};case"success":return{...r,data:t.data,dataUpdateCount:r.dataUpdateCount+1,dataUpdatedAt:t.dataUpdatedAt??Date.now(),error:null,isInvalidated:!1,status:"success",...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};case"error":const o=t.error;return a0(o)&&o.revert&&z(this,Nl)?{...z(this,Nl),fetchStatus:"idle"}:{...r,error:o,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:o,fetchStatus:"idle",status:"error"};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...t.state}}};this.state=n(this.state),gn.batch(()=>{z(this,cn).forEach(r=>{r.onQueryUpdate()}),z(this,Nr).notify({query:this,type:"updated",action:t})})},d$);function oL(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=typeof t<"u",r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var Ro,f$,iL=(f$=class extends $d{constructor(t={}){super();Te(this,Ro,void 0);this.config=t,ye(this,Ro,new Map)}build(t,n,r){const o=n.queryKey,i=n.queryHash??Gw(o,n);let s=this.get(i);return s||(s=new rL({cache:this,queryKey:o,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(o)}),this.add(s)),s}add(t){z(this,Ro).has(t.queryHash)||(z(this,Ro).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){const n=z(this,Ro).get(t.queryHash);n&&(t.destroy(),n===t&&z(this,Ro).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){gn.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return z(this,Ro).get(t)}getAll(){return[...z(this,Ro).values()]}find(t){const n={exact:!0,...t};return this.getAll().find(r=>KE(n,r))}findAll(t={}){const n=this.getAll();return Object.keys(t).length>0?n.filter(r=>KE(t,r)):n}notify(t){gn.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){gn.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){gn.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},Ro=new WeakMap,f$),To,dd,dr,Il,Po,Wi,p$,sL=(p$=class extends DR{constructor(t){super();Te(this,Po);Te(this,To,void 0);Te(this,dd,void 0);Te(this,dr,void 0);Te(this,Il,void 0);this.mutationId=t.mutationId,ye(this,dd,t.defaultOptions),ye(this,dr,t.mutationCache),ye(this,To,[]),this.state=t.state||aL(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options={...z(this,dd),...t},this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){z(this,To).includes(t)||(z(this,To).push(t),this.clearGcTimeout(),z(this,dr).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){ye(this,To,z(this,To).filter(n=>n!==t)),this.scheduleGc(),z(this,dr).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){z(this,To).length||(this.state.status==="pending"?this.scheduleGc():z(this,dr).remove(this))}continue(){var t;return((t=z(this,Il))==null?void 0:t.continue())??this.execute(this.state.variables)}async execute(t){var o,i,s,l,u,d,h,m,g,y,x,_,C,S,b,E,k,P,M,A;const n=()=>(ye(this,Il,NR({fn:()=>this.options.mutationFn?this.options.mutationFn(t):Promise.reject(new Error("No mutationFn found")),onFail:(O,F)=>{tt(this,Po,Wi).call(this,{type:"failed",failureCount:O,error:F})},onPause:()=>{tt(this,Po,Wi).call(this,{type:"pause"})},onContinue:()=>{tt(this,Po,Wi).call(this,{type:"continue"})},retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode})),z(this,Il).promise),r=this.state.status==="pending";try{if(!r){tt(this,Po,Wi).call(this,{type:"pending",variables:t}),await((i=(o=z(this,dr).config).onMutate)==null?void 0:i.call(o,t,this));const F=await((l=(s=this.options).onMutate)==null?void 0:l.call(s,t));F!==this.state.context&&tt(this,Po,Wi).call(this,{type:"pending",context:F,variables:t})}const O=await n();return await((d=(u=z(this,dr).config).onSuccess)==null?void 0:d.call(u,O,t,this.state.context,this)),await((m=(h=this.options).onSuccess)==null?void 0:m.call(h,O,t,this.state.context)),await((y=(g=z(this,dr).config).onSettled)==null?void 0:y.call(g,O,null,this.state.variables,this.state.context,this)),await((_=(x=this.options).onSettled)==null?void 0:_.call(x,O,null,t,this.state.context)),tt(this,Po,Wi).call(this,{type:"success",data:O}),O}catch(O){try{throw await((S=(C=z(this,dr).config).onError)==null?void 0:S.call(C,O,t,this.state.context,this)),await((E=(b=this.options).onError)==null?void 0:E.call(b,O,t,this.state.context)),await((P=(k=z(this,dr).config).onSettled)==null?void 0:P.call(k,void 0,O,this.state.variables,this.state.context,this)),await((A=(M=this.options).onSettled)==null?void 0:A.call(M,void 0,O,t,this.state.context)),O}finally{tt(this,Po,Wi).call(this,{type:"error",error:O})}}}},To=new WeakMap,dd=new WeakMap,dr=new WeakMap,Il=new WeakMap,Po=new WeakSet,Wi=function(t){const n=r=>{switch(t.type){case"failed":return{...r,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};case"pending":return{...r,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:!Cm(this.options.networkMode),status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...r,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:t.error,failureCount:r.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}};this.state=n(this.state),gn.batch(()=>{z(this,To).forEach(r=>{r.onMutationUpdate(t)}),z(this,dr).notify({mutation:this,type:"updated",action:t})})},p$);function aL(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Ir,fd,pa,h$,lL=(h$=class extends $d{constructor(t={}){super();Te(this,Ir,void 0);Te(this,fd,void 0);Te(this,pa,void 0);this.config=t,ye(this,Ir,[]),ye(this,fd,0)}build(t,n,r){const o=new sL({mutationCache:this,mutationId:++Ff(this,fd)._,options:t.defaultMutationOptions(n),state:r});return this.add(o),o}add(t){z(this,Ir).push(t),this.notify({type:"added",mutation:t})}remove(t){ye(this,Ir,z(this,Ir).filter(n=>n!==t)),this.notify({type:"removed",mutation:t})}clear(){gn.batch(()=>{z(this,Ir).forEach(t=>{this.remove(t)})})}getAll(){return z(this,Ir)}find(t){const n={exact:!0,...t};return z(this,Ir).find(r=>YE(n,r))}findAll(t={}){return z(this,Ir).filter(n=>YE(t,n))}notify(t){gn.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){return ye(this,pa,(z(this,pa)??Promise.resolve()).then(()=>{const t=z(this,Ir).filter(n=>n.state.isPaused);return gn.batch(()=>t.reduce((n,r)=>n.then(()=>r.continue().catch(Lr)),Promise.resolve()))}).then(()=>{ye(this,pa,void 0)})),z(this,pa)}},Ir=new WeakMap,fd=new WeakMap,pa=new WeakMap,h$);function cL(e){return{onFetch:(t,n)=>{const r=async()=>{var x,_,C,S,b;const o=t.options,i=(C=(_=(x=t.fetchOptions)==null?void 0:x.meta)==null?void 0:_.fetchMore)==null?void 0:C.direction,s=((S=t.state.data)==null?void 0:S.pages)||[],l=((b=t.state.data)==null?void 0:b.pageParams)||[],u={pages:[],pageParams:[]};let d=!1;const h=E=>{Object.defineProperty(E,"signal",{enumerable:!0,get:()=>(t.signal.aborted?d=!0:t.signal.addEventListener("abort",()=>{d=!0}),t.signal)})},m=t.options.queryFn||(()=>Promise.reject(new Error(`Missing queryFn: '${t.options.queryHash}'`))),g=async(E,k,P)=>{if(d)return Promise.reject();if(k==null&&E.pages.length)return Promise.resolve(E);const M={queryKey:t.queryKey,pageParam:k,direction:P?"backward":"forward",meta:t.options.meta};h(M);const A=await m(M),{maxPages:O}=t.options,F=P?QI:qI;return{pages:F(E.pages,A,O),pageParams:F(E.pageParams,k,O)}};let y;if(i&&s.length){const E=i==="backward",k=E?uL:qE,P={pages:s,pageParams:l},M=k(o,P);y=await g(P,M,E)}else{y=await g(u,l[0]??o.initialPageParam);const E=e??s.length;for(let k=1;k{var o,i;return(i=(o=t.options).persister)==null?void 0:i.call(o,r,{queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n)}:t.fetchFn=r}}}function qE(e,{pages:t,pageParams:n}){const r=t.length-1;return e.getNextPageParam(t[r],t,n[r],n)}function uL(e,{pages:t,pageParams:n}){var r;return(r=e.getPreviousPageParam)==null?void 0:r.call(e,t[0],t,n[0],n)}var nn,Ji,es,Ll,Fl,ts,jl,zl,m$,dL=(m$=class{constructor(e={}){Te(this,nn,void 0);Te(this,Ji,void 0);Te(this,es,void 0);Te(this,Ll,void 0);Te(this,Fl,void 0);Te(this,ts,void 0);Te(this,jl,void 0);Te(this,zl,void 0);ye(this,nn,e.queryCache||new iL),ye(this,Ji,e.mutationCache||new lL),ye(this,es,e.defaultOptions||{}),ye(this,Ll,new Map),ye(this,Fl,new Map),ye(this,ts,0)}mount(){Ff(this,ts)._++,z(this,ts)===1&&(ye(this,jl,Rh.subscribe(()=>{Rh.isFocused()&&(this.resumePausedMutations(),z(this,nn).onFocus())})),ye(this,zl,Th.subscribe(()=>{Th.isOnline()&&(this.resumePausedMutations(),z(this,nn).onOnline())})))}unmount(){var e,t;Ff(this,ts)._--,z(this,ts)===0&&((e=z(this,jl))==null||e.call(this),ye(this,jl,void 0),(t=z(this,zl))==null||t.call(this),ye(this,zl,void 0))}isFetching(e){return z(this,nn).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return z(this,Ji).findAll({...e,status:"pending"}).length}getQueryData(e){var t;return(t=z(this,nn).find({queryKey:e}))==null?void 0:t.state.data}ensureQueryData(e){const t=this.getQueryData(e.queryKey);return t!==void 0?Promise.resolve(t):this.fetchQuery(e)}getQueriesData(e){return this.getQueryCache().findAll(e).map(({queryKey:t,state:n})=>{const r=n.data;return[t,r]})}setQueryData(e,t,n){const r=z(this,nn).find({queryKey:e}),o=r==null?void 0:r.state.data,i=ZI(t,o);if(typeof i>"u")return;const s=this.defaultQueryOptions({queryKey:e});return z(this,nn).build(this,s).setData(i,{...n,manual:!0})}setQueriesData(e,t,n){return gn.batch(()=>this.getQueryCache().findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){var t;return(t=z(this,nn).find({queryKey:e}))==null?void 0:t.state}removeQueries(e){const t=z(this,nn);gn.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=z(this,nn),r={type:"active",...e};return gn.batch(()=>(n.findAll(e).forEach(o=>{o.reset()}),this.refetchQueries(r,t)))}cancelQueries(e={},t={}){const n={revert:!0,...t},r=gn.batch(()=>z(this,nn).findAll(e).map(o=>o.cancel(n)));return Promise.all(r).then(Lr).catch(Lr)}invalidateQueries(e={},t={}){return gn.batch(()=>{if(z(this,nn).findAll(e).forEach(r=>{r.invalidate()}),e.refetchType==="none")return Promise.resolve();const n={...e,type:e.refetchType??e.type??"active"};return this.refetchQueries(n,t)})}refetchQueries(e={},t){const n={...t,cancelRefetch:(t==null?void 0:t.cancelRefetch)??!0},r=gn.batch(()=>z(this,nn).findAll(e).filter(o=>!o.isDisabled()).map(o=>{let i=o.fetch(void 0,n);return n.throwOnError||(i=i.catch(Lr)),o.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(Lr)}fetchQuery(e){const t=this.defaultQueryOptions(e);typeof t.retry>"u"&&(t.retry=!1);const n=z(this,nn).build(this,t);return n.isStaleByTime(t.staleTime)?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Lr).catch(Lr)}fetchInfiniteQuery(e){return e.behavior=cL(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Lr).catch(Lr)}resumePausedMutations(){return z(this,Ji).resumePausedMutations()}getQueryCache(){return z(this,nn)}getMutationCache(){return z(this,Ji)}getDefaultOptions(){return z(this,es)}setDefaultOptions(e){ye(this,es,e)}setQueryDefaults(e,t){z(this,Ll).set(Gu(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...z(this,Ll).values()];let n={};return t.forEach(r=>{Xu(e,r.queryKey)&&(n={...n,...r.defaultOptions})}),n}setMutationDefaults(e,t){z(this,Fl).set(Gu(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...z(this,Fl).values()];let n={};return t.forEach(r=>{Xu(e,r.mutationKey)&&(n={...n,...r.defaultOptions})}),n}defaultQueryOptions(e){if(e!=null&&e._defaulted)return e;const t={...z(this,es).queries,...(e==null?void 0:e.queryKey)&&this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Gw(t.queryKey,t)),typeof t.refetchOnReconnect>"u"&&(t.refetchOnReconnect=t.networkMode!=="always"),typeof t.throwOnError>"u"&&(t.throwOnError=!!t.suspense),typeof t.networkMode>"u"&&t.persister&&(t.networkMode="offlineFirst"),t}defaultMutationOptions(e){return e!=null&&e._defaulted?e:{...z(this,es).mutations,...(e==null?void 0:e.mutationKey)&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){z(this,nn).clear(),z(this,Ji).clear()}},nn=new WeakMap,Ji=new WeakMap,es=new WeakMap,Ll=new WeakMap,Fl=new WeakMap,ts=new WeakMap,jl=new WeakMap,zl=new WeakMap,m$),Xn,Ct,Bl,$n,ha,Ul,Ao,pd,Vl,Wl,ma,ga,ns,va,ya,hu,hd,Ly,md,Fy,gd,jy,vd,zy,yd,By,wd,Uy,xd,Vy,am,IR,g$,fL=(g$=class extends $d{constructor(t,n){super();Te(this,ya);Te(this,hd);Te(this,md);Te(this,gd);Te(this,vd);Te(this,yd);Te(this,wd);Te(this,xd);Te(this,am);Te(this,Xn,void 0);Te(this,Ct,void 0);Te(this,Bl,void 0);Te(this,$n,void 0);Te(this,ha,void 0);Te(this,Ul,void 0);Te(this,Ao,void 0);Te(this,pd,void 0);Te(this,Vl,void 0);Te(this,Wl,void 0);Te(this,ma,void 0);Te(this,ga,void 0);Te(this,ns,void 0);Te(this,va,void 0);ye(this,Ct,void 0),ye(this,Bl,void 0),ye(this,$n,void 0),ye(this,va,new Set),ye(this,Xn,t),this.options=n,ye(this,Ao,null),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(z(this,Ct).addObserver(this),QE(z(this,Ct),this.options)?tt(this,ya,hu).call(this):this.updateResult(),tt(this,vd,zy).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Wy(z(this,Ct),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Wy(z(this,Ct),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,tt(this,yd,By).call(this),tt(this,wd,Uy).call(this),z(this,Ct).removeObserver(this)}setOptions(t,n){const r=this.options,o=z(this,Ct);if(this.options=z(this,Xn).defaultQueryOptions(t),Ny(r,this.options)||z(this,Xn).getQueryCache().notify({type:"observerOptionsUpdated",query:z(this,Ct),observer:this}),typeof this.options.enabled<"u"&&typeof this.options.enabled!="boolean")throw new Error("Expected enabled to be a boolean");this.options.queryKey||(this.options.queryKey=r.queryKey),tt(this,xd,Vy).call(this);const i=this.hasListeners();i&&JE(z(this,Ct),o,this.options,r)&&tt(this,ya,hu).call(this),this.updateResult(n),i&&(z(this,Ct)!==o||this.options.enabled!==r.enabled||this.options.staleTime!==r.staleTime)&&tt(this,hd,Ly).call(this);const s=tt(this,md,Fy).call(this);i&&(z(this,Ct)!==o||this.options.enabled!==r.enabled||s!==z(this,ns))&&tt(this,gd,jy).call(this,s)}getOptimisticResult(t){const n=z(this,Xn).getQueryCache().build(z(this,Xn),t),r=this.createResult(n,t);return hL(this,r)&&(ye(this,$n,r),ye(this,Ul,this.options),ye(this,ha,z(this,Ct).state)),r}getCurrentResult(){return z(this,$n)}trackResult(t){const n={};return Object.keys(t).forEach(r=>{Object.defineProperty(n,r,{configurable:!1,enumerable:!0,get:()=>(z(this,va).add(r),t[r])})}),n}getCurrentQuery(){return z(this,Ct)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){const n=z(this,Xn).defaultQueryOptions(t),r=z(this,Xn).getQueryCache().build(z(this,Xn),n);return r.isFetchingOptimistic=!0,r.fetch().then(()=>this.createResult(r,n))}fetch(t){return tt(this,ya,hu).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),z(this,$n)))}createResult(t,n){var M;const r=z(this,Ct),o=this.options,i=z(this,$n),s=z(this,ha),l=z(this,Ul),d=t!==r?t.state:z(this,Bl),{state:h}=t;let{error:m,errorUpdatedAt:g,fetchStatus:y,status:x}=h,_=!1,C;if(n._optimisticResults){const A=this.hasListeners(),O=!A&&QE(t,n),F=A&&JE(t,r,n,o);(O||F)&&(y=Cm(t.options.networkMode)?"fetching":"paused",h.dataUpdatedAt||(x="pending")),n._optimisticResults==="isRestoring"&&(y="idle")}if(n.select&&typeof h.data<"u")if(i&&h.data===(s==null?void 0:s.data)&&n.select===z(this,pd))C=z(this,Vl);else try{ye(this,pd,n.select),C=n.select(h.data),C=Iy(i==null?void 0:i.data,C,n),ye(this,Vl,C),ye(this,Ao,null)}catch(A){ye(this,Ao,A)}else C=h.data;if(typeof n.placeholderData<"u"&&typeof C>"u"&&x==="pending"){let A;if(i!=null&&i.isPlaceholderData&&n.placeholderData===(l==null?void 0:l.placeholderData))A=i.data;else if(A=typeof n.placeholderData=="function"?n.placeholderData((M=z(this,Wl))==null?void 0:M.state.data,z(this,Wl)):n.placeholderData,n.select&&typeof A<"u")try{A=n.select(A),ye(this,Ao,null)}catch(O){ye(this,Ao,O)}typeof A<"u"&&(x="success",C=Iy(i==null?void 0:i.data,A,n),_=!0)}z(this,Ao)&&(m=z(this,Ao),C=z(this,Vl),g=Date.now(),x="error");const S=y==="fetching",b=x==="pending",E=x==="error",k=b&&S;return{status:x,fetchStatus:y,isPending:b,isSuccess:x==="success",isError:E,isInitialLoading:k,isLoading:k,data:C,dataUpdatedAt:h.dataUpdatedAt,error:m,errorUpdatedAt:g,failureCount:h.fetchFailureCount,failureReason:h.fetchFailureReason,errorUpdateCount:h.errorUpdateCount,isFetched:h.dataUpdateCount>0||h.errorUpdateCount>0,isFetchedAfterMount:h.dataUpdateCount>d.dataUpdateCount||h.errorUpdateCount>d.errorUpdateCount,isFetching:S,isRefetching:S&&!b,isLoadingError:E&&h.dataUpdatedAt===0,isPaused:y==="paused",isPlaceholderData:_,isRefetchError:E&&h.dataUpdatedAt!==0,isStale:Xw(t,n),refetch:this.refetch}}updateResult(t){const n=z(this,$n),r=this.createResult(z(this,Ct),this.options);if(ye(this,ha,z(this,Ct).state),ye(this,Ul,this.options),z(this,ha).data!==void 0&&ye(this,Wl,z(this,Ct)),Ny(r,n))return;ye(this,$n,r);const o={},i=()=>{if(!n)return!0;const{notifyOnChangeProps:s}=this.options,l=typeof s=="function"?s():s;if(l==="all"||!l&&!z(this,va).size)return!0;const u=new Set(l??z(this,va));return this.options.throwOnError&&u.add("error"),Object.keys(z(this,$n)).some(d=>{const h=d;return z(this,$n)[h]!==n[h]&&u.has(h)})};(t==null?void 0:t.listeners)!==!1&&i()&&(o.listeners=!0),tt(this,am,IR).call(this,{...o,...t})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&tt(this,vd,zy).call(this)}},Xn=new WeakMap,Ct=new WeakMap,Bl=new WeakMap,$n=new WeakMap,ha=new WeakMap,Ul=new WeakMap,Ao=new WeakMap,pd=new WeakMap,Vl=new WeakMap,Wl=new WeakMap,ma=new WeakMap,ga=new WeakMap,ns=new WeakMap,va=new WeakMap,ya=new WeakSet,hu=function(t){tt(this,xd,Vy).call(this);let n=z(this,Ct).fetch(this.options,t);return t!=null&&t.throwOnError||(n=n.catch(Lr)),n},hd=new WeakSet,Ly=function(){if(tt(this,yd,By).call(this),Ql||z(this,$n).isStale||!My(this.options.staleTime))return;const n=PR(z(this,$n).dataUpdatedAt,this.options.staleTime)+1;ye(this,ma,setTimeout(()=>{z(this,$n).isStale||this.updateResult()},n))},md=new WeakSet,Fy=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(z(this,Ct)):this.options.refetchInterval)??!1},gd=new WeakSet,jy=function(t){tt(this,wd,Uy).call(this),ye(this,ns,t),!(Ql||this.options.enabled===!1||!My(z(this,ns))||z(this,ns)===0)&&ye(this,ga,setInterval(()=>{(this.options.refetchIntervalInBackground||Rh.isFocused())&&tt(this,ya,hu).call(this)},z(this,ns)))},vd=new WeakSet,zy=function(){tt(this,hd,Ly).call(this),tt(this,gd,jy).call(this,tt(this,md,Fy).call(this))},yd=new WeakSet,By=function(){z(this,ma)&&(clearTimeout(z(this,ma)),ye(this,ma,void 0))},wd=new WeakSet,Uy=function(){z(this,ga)&&(clearInterval(z(this,ga)),ye(this,ga,void 0))},xd=new WeakSet,Vy=function(){const t=z(this,Xn).getQueryCache().build(z(this,Xn),this.options);if(t===z(this,Ct))return;const n=z(this,Ct);ye(this,Ct,t),ye(this,Bl,t.state),this.hasListeners()&&(n==null||n.removeObserver(this),t.addObserver(this))},am=new WeakSet,IR=function(t){gn.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(z(this,$n))}),z(this,Xn).getQueryCache().notify({query:z(this,Ct),type:"observerResultsUpdated"})})},g$);function pL(e,t){return t.enabled!==!1&&!e.state.dataUpdatedAt&&!(e.state.status==="error"&&t.retryOnMount===!1)}function QE(e,t){return pL(e,t)||e.state.dataUpdatedAt>0&&Wy(e,t,t.refetchOnMount)}function Wy(e,t,n){if(t.enabled!==!1){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&Xw(e,t)}return!1}function JE(e,t,n,r){return n.enabled!==!1&&(e!==t||r.enabled===!1)&&(!n.suspense||e.state.status!=="error")&&Xw(e,n)}function Xw(e,t){return e.isStaleByTime(t.staleTime)}function hL(e,t){return!Ny(e.getCurrentResult(),t)}var LR=f.createContext(void 0),mL=e=>{const t=f.useContext(LR);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},gL=({client:e,children:t})=>(f.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),f.createElement(LR.Provider,{value:e},t)),FR=f.createContext(!1),vL=()=>f.useContext(FR);FR.Provider;function yL(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var wL=f.createContext(yL()),xL=()=>f.useContext(wL);function bL(e,t){return typeof e=="function"?e(...t):!!e}var _L=(e,t)=>{(e.suspense||e.throwOnError)&&(t.isReset()||(e.retryOnMount=!1))},SL=e=>{f.useEffect(()=>{e.clearReset()},[e])},EL=({result:e,errorResetBoundary:t,throwOnError:n,query:r})=>e.isError&&!t.isReset()&&!e.isFetching&&bL(n,[e.error,r]),CL=e=>{e.suspense&&typeof e.staleTime!="number"&&(e.staleTime=1e3)},$L=(e,t)=>(e==null?void 0:e.suspense)&&t.isPending,kL=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function RL(e,t,n){const r=mL(n),o=vL(),i=xL(),s=r.defaultQueryOptions(e);s._optimisticResults=o?"isRestoring":"optimistic",CL(s),_L(s,i),SL(i);const[l]=f.useState(()=>new t(r,s)),u=l.getOptimisticResult(s);if(f.useSyncExternalStore(f.useCallback(d=>{const h=o?()=>{}:l.subscribe(gn.batchCalls(d));return l.updateResult(),h},[l,o]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),f.useEffect(()=>{l.setOptions(s,{listeners:!1})},[s,l]),$L(s,u))throw l.setOptions(s,{listeners:!1}),kL(s,l,i);if(EL({result:u,errorResetBoundary:i,throwOnError:s.throwOnError,query:l.getCurrentQuery()}))throw u.error;return s.notifyOnChangeProps?u:l.trackResult(u)}function TL(e,t){return RL(e,fL,t)}var jR=(e=>(e.RemoveBG="RemoveBG",e.AnimeSeg="AnimeSeg",e.RealESRGAN="RealESRGAN",e.GFPGAN="GFPGAN",e.RestoreFormer="RestoreFormer",e.InteractiveSeg="InteractiveSeg",e))(jR||{}),xs=(e=>(e.NAME="name",e.CTIME="ctime",e.MTIME="mtime",e))(xs||{}),$u=(e=>(e.DESCENDING="desc",e.ASCENDING="asc",e))($u||{}),Zw=(e=>(e.ddim="ddim",e.plms="plms",e))(Zw||{}),qw=(e=>(e.INPAINT_NS="INPAINT_NS",e.INPAINT_TELEA="INPAINT_TELEA",e))(qw||{}),In=(e=>(e.x="x",e.y="y",e.xy="xy",e))(In||{}),kl=(e=>(e.text_guided="text-guided",e.shape_guided="shape-guided",e.object_remove="object-remove",e.outpainting="outpainting",e))(kl||{});function zR(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;tl(i)))==null?void 0:s.classGroupId}const eC=/^\[(.+)\]$/;function AL(e){if(eC.test(e)){const t=eC.exec(e)[1],n=t==null?void 0:t.substring(0,t.indexOf(":"));if(n)return"arbitrary.."+n}}function OL(e){const{theme:t,prefix:n}=e,r={nextPart:new Map,validators:[]};return NL(Object.entries(e.classGroups),n).forEach(([i,s])=>{Hy(s,r,i,t)}),r}function Hy(e,t,n,r){e.forEach(o=>{if(typeof o=="string"){const i=o===""?t:tC(t,o);i.classGroupId=n;return}if(typeof o=="function"){if(ML(o)){Hy(o(r),t,n,r);return}t.validators.push({validator:o,classGroupId:n});return}Object.entries(o).forEach(([i,s])=>{Hy(s,tC(t,i),n,r)})})}function tC(e,t){let n=e;return t.split(Qw).forEach(r=>{n.nextPart.has(r)||n.nextPart.set(r,{nextPart:new Map,validators:[]}),n=n.nextPart.get(r)}),n}function ML(e){return e.isThemeGetter}function NL(e,t){return t?e.map(([n,r])=>{const o=r.map(i=>typeof i=="string"?t+i:typeof i=="object"?Object.fromEntries(Object.entries(i).map(([s,l])=>[t+s,l])):i);return[n,o]}):e}function DL(e){if(e<1)return{get:()=>{},set:()=>{}};let t=0,n=new Map,r=new Map;function o(i,s){n.set(i,s),t++,t>e&&(t=0,r=n,n=new Map)}return{get(i){let s=n.get(i);if(s!==void 0)return s;if((s=r.get(i))!==void 0)return o(i,s),s},set(i,s){n.has(i)?n.set(i,s):o(i,s)}}}const VR="!";function IL(e){const t=e.separator,n=t.length===1,r=t[0],o=t.length;return function(s){const l=[];let u=0,d=0,h;for(let _=0;_d?h-d:void 0;return{modifiers:l,hasImportantModifier:g,baseClassName:y,maybePostfixModifierPosition:x}}}function LL(e){if(e.length<=1)return e;const t=[];let n=[];return e.forEach(r=>{r[0]==="["?(t.push(...n.sort(),r),n=[]):n.push(r)}),t.push(...n.sort()),t}function FL(e){return{cache:DL(e.cacheSize),splitModifiers:IL(e),...PL(e)}}const jL=/\s+/;function zL(e,t){const{splitModifiers:n,getClassGroupId:r,getConflictingClassGroupIds:o}=t,i=new Set;return e.trim().split(jL).map(s=>{const{modifiers:l,hasImportantModifier:u,baseClassName:d,maybePostfixModifierPosition:h}=n(s);let m=r(h?d.substring(0,h):d),g=!!h;if(!m){if(!h)return{isTailwindClass:!1,originalClassName:s};if(m=r(d),!m)return{isTailwindClass:!1,originalClassName:s};g=!1}const y=LL(l).join(":");return{isTailwindClass:!0,modifierId:u?y+VR:y,classGroupId:m,originalClassName:s,hasPostfixModifier:g}}).reverse().filter(s=>{if(!s.isTailwindClass)return!0;const{modifierId:l,classGroupId:u,hasPostfixModifier:d}=s,h=l+u;return i.has(h)?!1:(i.add(h),o(u,d).forEach(m=>i.add(l+m)),!0)}).reverse().map(s=>s.originalClassName).join(" ")}function BL(){let e=0,t,n,r="";for(;em(h),e());return n=FL(d),r=n.cache.get,o=n.cache.set,i=l,l(u)}function l(u){const d=r(u);if(d)return d;const h=zL(u,n);return o(u,h),h}return function(){return i(BL.apply(null,arguments))}}function Rt(e){const t=n=>n[e]||[];return t.isThemeGetter=!0,t}const HR=/^\[(?:([a-z-]+):)?(.+)\]$/i,VL=/^\d+\/\d+$/,WL=new Set(["px","full","screen"]),HL=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,KL=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,YL=/^-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,GL=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/;function oo(e){return ia(e)||WL.has(e)||VL.test(e)}function zi(e){return mc(e,"length",nF)}function ia(e){return!!e&&!Number.isNaN(Number(e))}function np(e){return mc(e,"number",ia)}function nu(e){return!!e&&Number.isInteger(Number(e))}function XL(e){return e.endsWith("%")&&ia(e.slice(0,-1))}function Je(e){return HR.test(e)}function Bi(e){return HL.test(e)}const ZL=new Set(["length","size","percentage"]);function qL(e){return mc(e,ZL,KR)}function QL(e){return mc(e,"position",KR)}const JL=new Set(["image","url"]);function eF(e){return mc(e,JL,oF)}function tF(e){return mc(e,"",rF)}function ru(){return!0}function mc(e,t,n){const r=HR.exec(e);return r?r[1]?typeof t=="string"?r[1]===t:t.has(r[1]):n(r[2]):!1}function nF(e){return KL.test(e)}function KR(){return!1}function rF(e){return YL.test(e)}function oF(e){return GL.test(e)}function iF(){const e=Rt("colors"),t=Rt("spacing"),n=Rt("blur"),r=Rt("brightness"),o=Rt("borderColor"),i=Rt("borderRadius"),s=Rt("borderSpacing"),l=Rt("borderWidth"),u=Rt("contrast"),d=Rt("grayscale"),h=Rt("hueRotate"),m=Rt("invert"),g=Rt("gap"),y=Rt("gradientColorStops"),x=Rt("gradientColorStopPositions"),_=Rt("inset"),C=Rt("margin"),S=Rt("opacity"),b=Rt("padding"),E=Rt("saturate"),k=Rt("scale"),P=Rt("sepia"),M=Rt("skew"),A=Rt("space"),O=Rt("translate"),F=()=>["auto","contain","none"],V=()=>["auto","hidden","clip","visible","scroll"],J=()=>["auto",Je,t],G=()=>[Je,t],ae=()=>["",oo,zi],U=()=>["auto",ia,Je],te=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],L=()=>["solid","dashed","dotted","double","none"],ie=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity","plus-lighter"],K=()=>["start","end","center","between","around","evenly","stretch"],Q=()=>["","0",Je],W=()=>["auto","avoid","all","avoid-page","page","left","right","column"],le=()=>[ia,np],ge=()=>[ia,Je];return{cacheSize:500,separator:":",theme:{colors:[ru],spacing:[oo,zi],blur:["none","",Bi,Je],brightness:le(),borderColor:[e],borderRadius:["none","","full",Bi,Je],borderSpacing:G(),borderWidth:ae(),contrast:le(),grayscale:Q(),hueRotate:ge(),invert:Q(),gap:G(),gradientColorStops:[e],gradientColorStopPositions:[XL,zi],inset:J(),margin:J(),opacity:le(),padding:G(),saturate:le(),scale:le(),sepia:Q(),skew:ge(),space:G(),translate:G()},classGroups:{aspect:[{aspect:["auto","square","video",Je]}],container:["container"],columns:[{columns:[Bi]}],"break-after":[{"break-after":W()}],"break-before":[{"break-before":W()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],float:[{float:["right","left","none"]}],clear:[{clear:["left","right","both","none"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:[...te(),Je]}],overflow:[{overflow:V()}],"overflow-x":[{"overflow-x":V()}],"overflow-y":[{"overflow-y":V()}],overscroll:[{overscroll:F()}],"overscroll-x":[{"overscroll-x":F()}],"overscroll-y":[{"overscroll-y":F()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[_]}],"inset-x":[{"inset-x":[_]}],"inset-y":[{"inset-y":[_]}],start:[{start:[_]}],end:[{end:[_]}],top:[{top:[_]}],right:[{right:[_]}],bottom:[{bottom:[_]}],left:[{left:[_]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",nu,Je]}],basis:[{basis:J()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",Je]}],grow:[{grow:Q()}],shrink:[{shrink:Q()}],order:[{order:["first","last","none",nu,Je]}],"grid-cols":[{"grid-cols":[ru]}],"col-start-end":[{col:["auto",{span:["full",nu,Je]},Je]}],"col-start":[{"col-start":U()}],"col-end":[{"col-end":U()}],"grid-rows":[{"grid-rows":[ru]}],"row-start-end":[{row:["auto",{span:[nu,Je]},Je]}],"row-start":[{"row-start":U()}],"row-end":[{"row-end":U()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",Je]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",Je]}],gap:[{gap:[g]}],"gap-x":[{"gap-x":[g]}],"gap-y":[{"gap-y":[g]}],"justify-content":[{justify:["normal",...K()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...K(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...K(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[b]}],px:[{px:[b]}],py:[{py:[b]}],ps:[{ps:[b]}],pe:[{pe:[b]}],pt:[{pt:[b]}],pr:[{pr:[b]}],pb:[{pb:[b]}],pl:[{pl:[b]}],m:[{m:[C]}],mx:[{mx:[C]}],my:[{my:[C]}],ms:[{ms:[C]}],me:[{me:[C]}],mt:[{mt:[C]}],mr:[{mr:[C]}],mb:[{mb:[C]}],ml:[{ml:[C]}],"space-x":[{"space-x":[A]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[A]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit",Je,t]}],"min-w":[{"min-w":["min","max","fit",Je,oo]}],"max-w":[{"max-w":["0","none","full","min","max","fit","prose",{screen:[Bi]},Bi,Je]}],h:[{h:[Je,t,"auto","min","max","fit"]}],"min-h":[{"min-h":["min","max","fit",oo,Je]}],"max-h":[{"max-h":[Je,t,"min","max","fit"]}],"font-size":[{text:["base",Bi,zi]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",np]}],"font-family":[{font:[ru]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractons"],tracking:[{tracking:["tighter","tight","normal","wide","wider","widest",Je]}],"line-clamp":[{"line-clamp":["none",ia,np]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",oo,Je]}],"list-image":[{"list-image":["none",Je]}],"list-style-type":[{list:["none","disc","decimal",Je]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[e]}],"placeholder-opacity":[{"placeholder-opacity":[S]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[e]}],"text-opacity":[{"text-opacity":[S]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...L(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",oo,zi]}],"underline-offset":[{"underline-offset":["auto",oo,Je]}],"text-decoration-color":[{decoration:[e]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],indent:[{indent:G()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Je]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",Je]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[S]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...te(),QL]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",qL]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},eF]}],"bg-color":[{bg:[e]}],"gradient-from-pos":[{from:[x]}],"gradient-via-pos":[{via:[x]}],"gradient-to-pos":[{to:[x]}],"gradient-from":[{from:[y]}],"gradient-via":[{via:[y]}],"gradient-to":[{to:[y]}],rounded:[{rounded:[i]}],"rounded-s":[{"rounded-s":[i]}],"rounded-e":[{"rounded-e":[i]}],"rounded-t":[{"rounded-t":[i]}],"rounded-r":[{"rounded-r":[i]}],"rounded-b":[{"rounded-b":[i]}],"rounded-l":[{"rounded-l":[i]}],"rounded-ss":[{"rounded-ss":[i]}],"rounded-se":[{"rounded-se":[i]}],"rounded-ee":[{"rounded-ee":[i]}],"rounded-es":[{"rounded-es":[i]}],"rounded-tl":[{"rounded-tl":[i]}],"rounded-tr":[{"rounded-tr":[i]}],"rounded-br":[{"rounded-br":[i]}],"rounded-bl":[{"rounded-bl":[i]}],"border-w":[{border:[l]}],"border-w-x":[{"border-x":[l]}],"border-w-y":[{"border-y":[l]}],"border-w-s":[{"border-s":[l]}],"border-w-e":[{"border-e":[l]}],"border-w-t":[{"border-t":[l]}],"border-w-r":[{"border-r":[l]}],"border-w-b":[{"border-b":[l]}],"border-w-l":[{"border-l":[l]}],"border-opacity":[{"border-opacity":[S]}],"border-style":[{border:[...L(),"hidden"]}],"divide-x":[{"divide-x":[l]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[l]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[S]}],"divide-style":[{divide:L()}],"border-color":[{border:[o]}],"border-color-x":[{"border-x":[o]}],"border-color-y":[{"border-y":[o]}],"border-color-t":[{"border-t":[o]}],"border-color-r":[{"border-r":[o]}],"border-color-b":[{"border-b":[o]}],"border-color-l":[{"border-l":[o]}],"divide-color":[{divide:[o]}],"outline-style":[{outline:["",...L()]}],"outline-offset":[{"outline-offset":[oo,Je]}],"outline-w":[{outline:[oo,zi]}],"outline-color":[{outline:[e]}],"ring-w":[{ring:ae()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[e]}],"ring-opacity":[{"ring-opacity":[S]}],"ring-offset-w":[{"ring-offset":[oo,zi]}],"ring-offset-color":[{"ring-offset":[e]}],shadow:[{shadow:["","inner","none",Bi,tF]}],"shadow-color":[{shadow:[ru]}],opacity:[{opacity:[S]}],"mix-blend":[{"mix-blend":ie()}],"bg-blend":[{"bg-blend":ie()}],filter:[{filter:["","none"]}],blur:[{blur:[n]}],brightness:[{brightness:[r]}],contrast:[{contrast:[u]}],"drop-shadow":[{"drop-shadow":["","none",Bi,Je]}],grayscale:[{grayscale:[d]}],"hue-rotate":[{"hue-rotate":[h]}],invert:[{invert:[m]}],saturate:[{saturate:[E]}],sepia:[{sepia:[P]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[n]}],"backdrop-brightness":[{"backdrop-brightness":[r]}],"backdrop-contrast":[{"backdrop-contrast":[u]}],"backdrop-grayscale":[{"backdrop-grayscale":[d]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[h]}],"backdrop-invert":[{"backdrop-invert":[m]}],"backdrop-opacity":[{"backdrop-opacity":[S]}],"backdrop-saturate":[{"backdrop-saturate":[E]}],"backdrop-sepia":[{"backdrop-sepia":[P]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":[s]}],"border-spacing-x":[{"border-spacing-x":[s]}],"border-spacing-y":[{"border-spacing-y":[s]}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["none","all","","colors","opacity","shadow","transform",Je]}],duration:[{duration:ge()}],ease:[{ease:["linear","in","out","in-out",Je]}],delay:[{delay:ge()}],animate:[{animate:["none","spin","ping","pulse","bounce",Je]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[k]}],"scale-x":[{"scale-x":[k]}],"scale-y":[{"scale-y":[k]}],rotate:[{rotate:[nu,Je]}],"translate-x":[{"translate-x":[O]}],"translate-y":[{"translate-y":[O]}],"skew-x":[{"skew-x":[M]}],"skew-y":[{"skew-y":[M]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",Je]}],accent:[{accent:["auto",e]}],appearance:["appearance-none"],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",Je]}],"caret-color":[{caret:[e]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":G()}],"scroll-mx":[{"scroll-mx":G()}],"scroll-my":[{"scroll-my":G()}],"scroll-ms":[{"scroll-ms":G()}],"scroll-me":[{"scroll-me":G()}],"scroll-mt":[{"scroll-mt":G()}],"scroll-mr":[{"scroll-mr":G()}],"scroll-mb":[{"scroll-mb":G()}],"scroll-ml":[{"scroll-ml":G()}],"scroll-p":[{"scroll-p":G()}],"scroll-px":[{"scroll-px":G()}],"scroll-py":[{"scroll-py":G()}],"scroll-ps":[{"scroll-ps":G()}],"scroll-pe":[{"scroll-pe":G()}],"scroll-pt":[{"scroll-pt":G()}],"scroll-pr":[{"scroll-pr":G()}],"scroll-pb":[{"scroll-pb":G()}],"scroll-pl":[{"scroll-pl":G()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",Je]}],fill:[{fill:[e,"none"]}],"stroke-w":[{stroke:[oo,zi,np]}],stroke:[{stroke:[e,"none"]}],sr:["sr-only","not-sr-only"]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]}}}const Jw=UL(iF),sF=40,is="inpaint",rp="diffusers_sd",nC="diffusers_sdxl",op="diffusers_sd_inpaint",rC="diffusers_sdxl_inpaint",l0="diffusers_other",Ky="#ffcc00bb",oC="ldm",iC="cv2",YR="Fantasy-Studio/Paint-by-Example",aF="timbrooks/instruct-pix2pix",lF="Sanster/PowerPaint-V1-stable-diffusion-inpainting",cF="out of frame, lowres, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, disfigured, gross proportions, malformed limbs, watermark, signature";function Ce(...e){return Jw(BR(e))}function uF(){async function e(r=""){return(await fetch(r,{method:"GET",cache:"no-cache"})).json()}const t=()=>{const r=document.location;e(r+"/flaskwebgui-keep-server-alive").then(i=>i)},n=3*1e3;t(),setInterval(t,n)}function sC(e){const t=e.split(",")[0].split(":")[1].split(";")[0],n=atob(e.split(",")[1]),r=[];for(let o=0;o{const o=e.src,i=e;i.onload=n,i.onerror=s=>{i.src=o,r(s)},i.src=t})}async function dF(e){const t=URL.createObjectURL(e),n=new Image;return await Ip(n,t),n}function aC(e){return new Promise((t,n)=>{const r=new Image;r.addEventListener("load",()=>{t(r)}),r.addEventListener("error",o=>{n(o)}),r.src=e.toDataURL()})}function fF(e){return new Promise((t,n)=>{const r=new FileReader;r.onload=()=>{const o=new Image;o.onload=()=>{t(o)},o.onerror=()=>{n("无法加载图像。")},o.src=r.result},r.onerror=()=>{n("无法读取文件。")},r.readAsDataURL(e)})}function ku(e,t,n){return fetch(e).then(function(r){return r.arrayBuffer()}).then(function(r){return new File([r],t,{type:n})})}async function pF(){try{const{state:e}=await navigator.permissions.query({name:"clipboard-write"});return e==="granted"}catch{return!1}}function hF(e,t){return new Promise((n,r)=>e.toBlob(async o=>{o?n(o):r(new Error("Expected toBlob() to be defined"))},t))}const mF=async e=>{const t=[new ClipboardItem({[e.type]:e})];await navigator.clipboard.write(t)};function lC(e){return e.nativeEvent.button===2}function cC(e){return e.nativeEvent.button===1}async function gF(e){const t=await hF(e,"image/png");try{await mF(t)}catch{console.log("Copy image failed!")}}function vF(e,t){const n=document.createElement("a");n.href=e,n.download=t,n.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0,view:window})),setTimeout(()=>{n.remove()},100)}function c0(e){const t=e.nativeEvent;return{x:t.offsetX,y:t.offsetY}}function GR(e,t,n=Ky){e.strokeStyle=n,e.lineCap="round",e.lineJoin="round",t.forEach(r=>{!(r!=null&&r.pts.length)||!r.size||(e.lineWidth=r.size,e.beginPath(),e.moveTo(r.pts[0].x,r.pts[0].y),r.pts.forEach(o=>e.lineTo(o.x,o.y)),e.stroke())})}const Lp=(e,t,n,r=[],o="white")=>{const i=document.createElement("canvas");i.width=e,i.height=t;const s=i.getContext("2d");if(!s)throw new Error("could not retrieve mask canvas");return r.forEach(l=>{s.drawImage(l,0,0,e,t)}),n.forEach(l=>{GR(s,l,o)}),i},Ru=e=>new Promise((t,n)=>{const r=new FileReader;r.onload=o=>{var s;const i=(s=o.target)==null?void 0:s.result;t(i)},r.onerror=o=>{n(o)},r.readAsDataURL(e)});function XR(e,t){return function(){return e.apply(t,arguments)}}const{toString:yF}=Object.prototype,{getPrototypeOf:ex}=Object,$m=(e=>t=>{const n=yF.call(t);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),Go=e=>(e=e.toLowerCase(),t=>$m(t)===e),km=e=>t=>typeof t===e,{isArray:gc}=Array,Zu=km("undefined");function wF(e){return e!==null&&!Zu(e)&&e.constructor!==null&&!Zu(e.constructor)&&Kr(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const ZR=Go("ArrayBuffer");function xF(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&ZR(e.buffer),t}const bF=km("string"),Kr=km("function"),qR=km("number"),Rm=e=>e!==null&&typeof e=="object",_F=e=>e===!0||e===!1,Fp=e=>{if($m(e)!=="object")return!1;const t=ex(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},SF=Go("Date"),EF=Go("File"),CF=Go("Blob"),$F=Go("FileList"),kF=e=>Rm(e)&&Kr(e.pipe),RF=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||Kr(e.append)&&((t=$m(e))==="formdata"||t==="object"&&Kr(e.toString)&&e.toString()==="[object FormData]"))},TF=Go("URLSearchParams"),PF=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function kd(e,t,{allOwnKeys:n=!1}={}){if(e===null||typeof e>"u")return;let r,o;if(typeof e!="object"&&(e=[e]),gc(e))for(r=0,o=e.length;r0;)if(o=n[r],t===o.toLowerCase())return o;return null}const JR=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,eT=e=>!Zu(e)&&e!==JR;function Yy(){const{caseless:e}=eT(this)&&this||{},t={},n=(r,o)=>{const i=e&&QR(t,o)||o;Fp(t[i])&&Fp(r)?t[i]=Yy(t[i],r):Fp(r)?t[i]=Yy({},r):gc(r)?t[i]=r.slice():t[i]=r};for(let r=0,o=arguments.length;r(kd(t,(o,i)=>{n&&Kr(o)?e[i]=XR(o,n):e[i]=o},{allOwnKeys:r}),e),OF=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),MF=(e,t,n,r)=>{e.prototype=Object.create(t.prototype,r),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),n&&Object.assign(e.prototype,n)},NF=(e,t,n,r)=>{let o,i,s;const l={};if(t=t||{},e==null)return t;do{for(o=Object.getOwnPropertyNames(e),i=o.length;i-- >0;)s=o[i],(!r||r(s,e,t))&&!l[s]&&(t[s]=e[s],l[s]=!0);e=n!==!1&&ex(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},DF=(e,t,n)=>{e=String(e),(n===void 0||n>e.length)&&(n=e.length),n-=t.length;const r=e.indexOf(t,n);return r!==-1&&r===n},IF=e=>{if(!e)return null;if(gc(e))return e;let t=e.length;if(!qR(t))return null;const n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},LF=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&ex(Uint8Array)),FF=(e,t)=>{const r=(e&&e[Symbol.iterator]).call(e);let o;for(;(o=r.next())&&!o.done;){const i=o.value;t.call(e,i[0],i[1])}},jF=(e,t)=>{let n;const r=[];for(;(n=e.exec(t))!==null;)r.push(n);return r},zF=Go("HTMLFormElement"),BF=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,r,o){return r.toUpperCase()+o}),uC=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),UF=Go("RegExp"),tT=(e,t)=>{const n=Object.getOwnPropertyDescriptors(e),r={};kd(n,(o,i)=>{let s;(s=t(o,i,e))!==!1&&(r[i]=s||o)}),Object.defineProperties(e,r)},VF=e=>{tT(e,(t,n)=>{if(Kr(e)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;const r=e[n];if(Kr(r)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},WF=(e,t)=>{const n={},r=o=>{o.forEach(i=>{n[i]=!0})};return gc(e)?r(e):r(String(e).split(t)),n},HF=()=>{},KF=(e,t)=>(e=+e,Number.isFinite(e)?e:t),u0="abcdefghijklmnopqrstuvwxyz",dC="0123456789",nT={DIGIT:dC,ALPHA:u0,ALPHA_DIGIT:u0+u0.toUpperCase()+dC},YF=(e=16,t=nT.ALPHA_DIGIT)=>{let n="";const{length:r}=t;for(;e--;)n+=t[Math.random()*r|0];return n};function GF(e){return!!(e&&Kr(e.append)&&e[Symbol.toStringTag]==="FormData"&&e[Symbol.iterator])}const XF=e=>{const t=new Array(10),n=(r,o)=>{if(Rm(r)){if(t.indexOf(r)>=0)return;if(!("toJSON"in r)){t[o]=r;const i=gc(r)?[]:{};return kd(r,(s,l)=>{const u=n(s,o+1);!Zu(u)&&(i[l]=u)}),t[o]=void 0,i}}return r};return n(e,0)},ZF=Go("AsyncFunction"),qF=e=>e&&(Rm(e)||Kr(e))&&Kr(e.then)&&Kr(e.catch),oe={isArray:gc,isArrayBuffer:ZR,isBuffer:wF,isFormData:RF,isArrayBufferView:xF,isString:bF,isNumber:qR,isBoolean:_F,isObject:Rm,isPlainObject:Fp,isUndefined:Zu,isDate:SF,isFile:EF,isBlob:CF,isRegExp:UF,isFunction:Kr,isStream:kF,isURLSearchParams:TF,isTypedArray:LF,isFileList:$F,forEach:kd,merge:Yy,extend:AF,trim:PF,stripBOM:OF,inherits:MF,toFlatObject:NF,kindOf:$m,kindOfTest:Go,endsWith:DF,toArray:IF,forEachEntry:FF,matchAll:jF,isHTMLForm:zF,hasOwnProperty:uC,hasOwnProp:uC,reduceDescriptors:tT,freezeMethods:VF,toObjectSet:WF,toCamelCase:BF,noop:HF,toFiniteNumber:KF,findKey:QR,global:JR,isContextDefined:eT,ALPHABET:nT,generateString:YF,isSpecCompliantForm:GF,toJSONObject:XF,isAsyncFn:ZF,isThenable:qF};function ut(e,t,n,r,o){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),n&&(this.config=n),r&&(this.request=r),o&&(this.response=o)}oe.inherits(ut,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:oe.toJSONObject(this.config),code:this.code,status:this.response&&this.response.status?this.response.status:null}}});const rT=ut.prototype,oT={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{oT[e]={value:e}});Object.defineProperties(ut,oT);Object.defineProperty(rT,"isAxiosError",{value:!0});ut.from=(e,t,n,r,o,i)=>{const s=Object.create(rT);return oe.toFlatObject(e,s,function(u){return u!==Error.prototype},l=>l!=="isAxiosError"),ut.call(s,e.message,t,n,r,o),s.cause=e,s.name=e.name,i&&Object.assign(s,i),s};const QF=null;function Gy(e){return oe.isPlainObject(e)||oe.isArray(e)}function iT(e){return oe.endsWith(e,"[]")?e.slice(0,-2):e}function fC(e,t,n){return e?e.concat(t).map(function(o,i){return o=iT(o),!n&&i?"["+o+"]":o}).join(n?".":""):t}function JF(e){return oe.isArray(e)&&!e.some(Gy)}const ej=oe.toFlatObject(oe,{},null,function(t){return/^is[A-Z]/.test(t)});function Tm(e,t,n){if(!oe.isObject(e))throw new TypeError("target must be an object");t=t||new FormData,n=oe.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(_,C){return!oe.isUndefined(C[_])});const r=n.metaTokens,o=n.visitor||h,i=n.dots,s=n.indexes,u=(n.Blob||typeof Blob<"u"&&Blob)&&oe.isSpecCompliantForm(t);if(!oe.isFunction(o))throw new TypeError("visitor must be a function");function d(x){if(x===null)return"";if(oe.isDate(x))return x.toISOString();if(!u&&oe.isBlob(x))throw new ut("Blob is not supported. Use a Buffer instead.");return oe.isArrayBuffer(x)||oe.isTypedArray(x)?u&&typeof Blob=="function"?new Blob([x]):Buffer.from(x):x}function h(x,_,C){let S=x;if(x&&!C&&typeof x=="object"){if(oe.endsWith(_,"{}"))_=r?_:_.slice(0,-2),x=JSON.stringify(x);else if(oe.isArray(x)&&JF(x)||(oe.isFileList(x)||oe.endsWith(_,"[]"))&&(S=oe.toArray(x)))return _=iT(_),S.forEach(function(E,k){!(oe.isUndefined(E)||E===null)&&t.append(s===!0?fC([_],k,i):s===null?_:_+"[]",d(E))}),!1}return Gy(x)?!0:(t.append(fC(C,_,i),d(x)),!1)}const m=[],g=Object.assign(ej,{defaultVisitor:h,convertValue:d,isVisitable:Gy});function y(x,_){if(!oe.isUndefined(x)){if(m.indexOf(x)!==-1)throw Error("Circular reference detected in "+_.join("."));m.push(x),oe.forEach(x,function(S,b){(!(oe.isUndefined(S)||S===null)&&o.call(t,S,oe.isString(b)?b.trim():b,_,g))===!0&&y(S,_?_.concat(b):[b])}),m.pop()}}if(!oe.isObject(e))throw new TypeError("data must be an object");return y(e),t}function pC(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(r){return t[r]})}function tx(e,t){this._pairs=[],e&&Tm(e,this,t)}const sT=tx.prototype;sT.append=function(t,n){this._pairs.push([t,n])};sT.toString=function(t){const n=t?function(r){return t.call(this,r,pC)}:pC;return this._pairs.map(function(o){return n(o[0])+"="+n(o[1])},"").join("&")};function tj(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function aT(e,t,n){if(!t)return e;const r=n&&n.encode||tj,o=n&&n.serialize;let i;if(o?i=o(t,n):i=oe.isURLSearchParams(t)?t.toString():new tx(t,n).toString(r),i){const s=e.indexOf("#");s!==-1&&(e=e.slice(0,s)),e+=(e.indexOf("?")===-1?"?":"&")+i}return e}class nj{constructor(){this.handlers=[]}use(t,n,r){return this.handlers.push({fulfilled:t,rejected:n,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){oe.forEach(this.handlers,function(r){r!==null&&t(r)})}}const hC=nj,lT={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},rj=typeof URLSearchParams<"u"?URLSearchParams:tx,oj=typeof FormData<"u"?FormData:null,ij=typeof Blob<"u"?Blob:null,sj={isBrowser:!0,classes:{URLSearchParams:rj,FormData:oj,Blob:ij},protocols:["http","https","file","blob","url","data"]},cT=typeof window<"u"&&typeof document<"u",aj=(e=>cT&&["ReactNative","NativeScript","NS"].indexOf(e)<0)(typeof navigator<"u"&&navigator.product),lj=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",cj=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:cT,hasStandardBrowserEnv:aj,hasStandardBrowserWebWorkerEnv:lj},Symbol.toStringTag,{value:"Module"})),Io={...cj,...sj};function uj(e,t){return Tm(e,new Io.classes.URLSearchParams,Object.assign({visitor:function(n,r,o,i){return Io.isNode&&oe.isBuffer(n)?(this.append(r,n.toString("base64")),!1):i.defaultVisitor.apply(this,arguments)}},t))}function dj(e){return oe.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function fj(e){const t={},n=Object.keys(e);let r;const o=n.length;let i;for(r=0;r=n.length;return s=!s&&oe.isArray(o)?o.length:s,u?(oe.hasOwnProp(o,s)?o[s]=[o[s],r]:o[s]=r,!l):((!o[s]||!oe.isObject(o[s]))&&(o[s]=[]),t(n,r,o[s],i)&&oe.isArray(o[s])&&(o[s]=fj(o[s])),!l)}if(oe.isFormData(e)&&oe.isFunction(e.entries)){const n={};return oe.forEachEntry(e,(r,o)=>{t(dj(r),o,n,0)}),n}return null}function pj(e,t,n){if(oe.isString(e))try{return(t||JSON.parse)(e),oe.trim(e)}catch(r){if(r.name!=="SyntaxError")throw r}return(n||JSON.stringify)(e)}const nx={transitional:lT,adapter:["xhr","http"],transformRequest:[function(t,n){const r=n.getContentType()||"",o=r.indexOf("application/json")>-1,i=oe.isObject(t);if(i&&oe.isHTMLForm(t)&&(t=new FormData(t)),oe.isFormData(t))return o&&o?JSON.stringify(uT(t)):t;if(oe.isArrayBuffer(t)||oe.isBuffer(t)||oe.isStream(t)||oe.isFile(t)||oe.isBlob(t))return t;if(oe.isArrayBufferView(t))return t.buffer;if(oe.isURLSearchParams(t))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let l;if(i){if(r.indexOf("application/x-www-form-urlencoded")>-1)return uj(t,this.formSerializer).toString();if((l=oe.isFileList(t))||r.indexOf("multipart/form-data")>-1){const u=this.env&&this.env.FormData;return Tm(l?{"files[]":t}:t,u&&new u,this.formSerializer)}}return i||o?(n.setContentType("application/json",!1),pj(t)):t}],transformResponse:[function(t){const n=this.transitional||nx.transitional,r=n&&n.forcedJSONParsing,o=this.responseType==="json";if(t&&oe.isString(t)&&(r&&!this.responseType||o)){const s=!(n&&n.silentJSONParsing)&&o;try{return JSON.parse(t)}catch(l){if(s)throw l.name==="SyntaxError"?ut.from(l,ut.ERR_BAD_RESPONSE,this,null,this.response):l}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:Io.classes.FormData,Blob:Io.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};oe.forEach(["delete","get","head","post","put","patch"],e=>{nx.headers[e]={}});const rx=nx,hj=oe.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),mj=e=>{const t={};let n,r,o;return e&&e.split(` +`).forEach(function(s){o=s.indexOf(":"),n=s.substring(0,o).trim().toLowerCase(),r=s.substring(o+1).trim(),!(!n||t[n]&&hj[n])&&(n==="set-cookie"?t[n]?t[n].push(r):t[n]=[r]:t[n]=t[n]?t[n]+", "+r:r)}),t},mC=Symbol("internals");function ou(e){return e&&String(e).trim().toLowerCase()}function jp(e){return e===!1||e==null?e:oe.isArray(e)?e.map(jp):String(e)}function gj(e){const t=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=n.exec(e);)t[r[1]]=r[2];return t}const vj=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function d0(e,t,n,r,o){if(oe.isFunction(r))return r.call(this,t,n);if(o&&(t=n),!!oe.isString(t)){if(oe.isString(r))return t.indexOf(r)!==-1;if(oe.isRegExp(r))return r.test(t)}}function yj(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,n,r)=>n.toUpperCase()+r)}function wj(e,t){const n=oe.toCamelCase(" "+t);["get","set","has"].forEach(r=>{Object.defineProperty(e,r+n,{value:function(o,i,s){return this[r].call(this,t,o,i,s)},configurable:!0})})}class Pm{constructor(t){t&&this.set(t)}set(t,n,r){const o=this;function i(l,u,d){const h=ou(u);if(!h)throw new Error("header name must be a non-empty string");const m=oe.findKey(o,h);(!m||o[m]===void 0||d===!0||d===void 0&&o[m]!==!1)&&(o[m||u]=jp(l))}const s=(l,u)=>oe.forEach(l,(d,h)=>i(d,h,u));return oe.isPlainObject(t)||t instanceof this.constructor?s(t,n):oe.isString(t)&&(t=t.trim())&&!vj(t)?s(mj(t),n):t!=null&&i(n,t,r),this}get(t,n){if(t=ou(t),t){const r=oe.findKey(this,t);if(r){const o=this[r];if(!n)return o;if(n===!0)return gj(o);if(oe.isFunction(n))return n.call(this,o,r);if(oe.isRegExp(n))return n.exec(o);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,n){if(t=ou(t),t){const r=oe.findKey(this,t);return!!(r&&this[r]!==void 0&&(!n||d0(this,this[r],r,n)))}return!1}delete(t,n){const r=this;let o=!1;function i(s){if(s=ou(s),s){const l=oe.findKey(r,s);l&&(!n||d0(r,r[l],l,n))&&(delete r[l],o=!0)}}return oe.isArray(t)?t.forEach(i):i(t),o}clear(t){const n=Object.keys(this);let r=n.length,o=!1;for(;r--;){const i=n[r];(!t||d0(this,this[i],i,t,!0))&&(delete this[i],o=!0)}return o}normalize(t){const n=this,r={};return oe.forEach(this,(o,i)=>{const s=oe.findKey(r,i);if(s){n[s]=jp(o),delete n[i];return}const l=t?yj(i):String(i).trim();l!==i&&delete n[i],n[l]=jp(o),r[l]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){const n=Object.create(null);return oe.forEach(this,(r,o)=>{r!=null&&r!==!1&&(n[o]=t&&oe.isArray(r)?r.join(", "):r)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,n])=>t+": "+n).join(` +`)}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...n){const r=new this(t);return n.forEach(o=>r.set(o)),r}static accessor(t){const r=(this[mC]=this[mC]={accessors:{}}).accessors,o=this.prototype;function i(s){const l=ou(s);r[l]||(wj(o,s),r[l]=!0)}return oe.isArray(t)?t.forEach(i):i(t),this}}Pm.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);oe.reduceDescriptors(Pm.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(r){this[n]=r}}});oe.freezeMethods(Pm);const pi=Pm;function f0(e,t){const n=this||rx,r=t||n,o=pi.from(r.headers);let i=r.data;return oe.forEach(e,function(l){i=l.call(n,i,o.normalize(),t?t.status:void 0)}),o.normalize(),i}function dT(e){return!!(e&&e.__CANCEL__)}function Rd(e,t,n){ut.call(this,e??"canceled",ut.ERR_CANCELED,t,n),this.name="CanceledError"}oe.inherits(Rd,ut,{__CANCEL__:!0});function xj(e,t,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?e(n):t(new ut("Request failed with status code "+n.status,[ut.ERR_BAD_REQUEST,ut.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}const bj=Io.hasStandardBrowserEnv?{write(e,t,n,r,o,i){const s=[e+"="+encodeURIComponent(t)];oe.isNumber(n)&&s.push("expires="+new Date(n).toGMTString()),oe.isString(r)&&s.push("path="+r),oe.isString(o)&&s.push("domain="+o),i===!0&&s.push("secure"),document.cookie=s.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function _j(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function Sj(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e}function fT(e,t){return e&&!_j(t)?Sj(e,t):t}const Ej=Io.hasStandardBrowserEnv?function(){const t=/(msie|trident)/i.test(navigator.userAgent),n=document.createElement("a");let r;function o(i){let s=i;return t&&(n.setAttribute("href",s),s=n.href),n.setAttribute("href",s),{href:n.href,protocol:n.protocol?n.protocol.replace(/:$/,""):"",host:n.host,search:n.search?n.search.replace(/^\?/,""):"",hash:n.hash?n.hash.replace(/^#/,""):"",hostname:n.hostname,port:n.port,pathname:n.pathname.charAt(0)==="/"?n.pathname:"/"+n.pathname}}return r=o(window.location.href),function(s){const l=oe.isString(s)?o(s):s;return l.protocol===r.protocol&&l.host===r.host}}():function(){return function(){return!0}}();function Cj(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function $j(e,t){e=e||10;const n=new Array(e),r=new Array(e);let o=0,i=0,s;return t=t!==void 0?t:1e3,function(u){const d=Date.now(),h=r[i];s||(s=d),n[o]=u,r[o]=d;let m=i,g=0;for(;m!==o;)g+=n[m++],m=m%e;if(o=(o+1)%e,o===i&&(i=(i+1)%e),d-s{const i=o.loaded,s=o.lengthComputable?o.total:void 0,l=i-n,u=r(l),d=i<=s;n=i;const h={loaded:i,total:s,progress:s?i/s:void 0,bytes:l,rate:u||void 0,estimated:u&&s&&d?(s-i)/u:void 0,event:o};h[t?"download":"upload"]=!0,e(h)}}const kj=typeof XMLHttpRequest<"u",Rj=kj&&function(e){return new Promise(function(n,r){let o=e.data;const i=pi.from(e.headers).normalize();let{responseType:s,withXSRFToken:l}=e,u;function d(){e.cancelToken&&e.cancelToken.unsubscribe(u),e.signal&&e.signal.removeEventListener("abort",u)}let h;if(oe.isFormData(o)){if(Io.hasStandardBrowserEnv||Io.hasStandardBrowserWebWorkerEnv)i.setContentType(!1);else if((h=i.getContentType())!==!1){const[_,...C]=h?h.split(";").map(S=>S.trim()).filter(Boolean):[];i.setContentType([_||"multipart/form-data",...C].join("; "))}}let m=new XMLHttpRequest;if(e.auth){const _=e.auth.username||"",C=e.auth.password?unescape(encodeURIComponent(e.auth.password)):"";i.set("Authorization","Basic "+btoa(_+":"+C))}const g=fT(e.baseURL,e.url);m.open(e.method.toUpperCase(),aT(g,e.params,e.paramsSerializer),!0),m.timeout=e.timeout;function y(){if(!m)return;const _=pi.from("getAllResponseHeaders"in m&&m.getAllResponseHeaders()),S={data:!s||s==="text"||s==="json"?m.responseText:m.response,status:m.status,statusText:m.statusText,headers:_,config:e,request:m};xj(function(E){n(E),d()},function(E){r(E),d()},S),m=null}if("onloadend"in m?m.onloadend=y:m.onreadystatechange=function(){!m||m.readyState!==4||m.status===0&&!(m.responseURL&&m.responseURL.indexOf("file:")===0)||setTimeout(y)},m.onabort=function(){m&&(r(new ut("Request aborted",ut.ECONNABORTED,e,m)),m=null)},m.onerror=function(){r(new ut("Network Error",ut.ERR_NETWORK,e,m)),m=null},m.ontimeout=function(){let C=e.timeout?"timeout of "+e.timeout+"ms exceeded":"timeout exceeded";const S=e.transitional||lT;e.timeoutErrorMessage&&(C=e.timeoutErrorMessage),r(new ut(C,S.clarifyTimeoutError?ut.ETIMEDOUT:ut.ECONNABORTED,e,m)),m=null},Io.hasStandardBrowserEnv&&(l&&oe.isFunction(l)&&(l=l(e)),l||l!==!1&&Ej(g))){const _=e.xsrfHeaderName&&e.xsrfCookieName&&bj.read(e.xsrfCookieName);_&&i.set(e.xsrfHeaderName,_)}o===void 0&&i.setContentType(null),"setRequestHeader"in m&&oe.forEach(i.toJSON(),function(C,S){m.setRequestHeader(S,C)}),oe.isUndefined(e.withCredentials)||(m.withCredentials=!!e.withCredentials),s&&s!=="json"&&(m.responseType=e.responseType),typeof e.onDownloadProgress=="function"&&m.addEventListener("progress",gC(e.onDownloadProgress,!0)),typeof e.onUploadProgress=="function"&&m.upload&&m.upload.addEventListener("progress",gC(e.onUploadProgress)),(e.cancelToken||e.signal)&&(u=_=>{m&&(r(!_||_.type?new Rd(null,e,m):_),m.abort(),m=null)},e.cancelToken&&e.cancelToken.subscribe(u),e.signal&&(e.signal.aborted?u():e.signal.addEventListener("abort",u)));const x=Cj(g);if(x&&Io.protocols.indexOf(x)===-1){r(new ut("Unsupported protocol "+x+":",ut.ERR_BAD_REQUEST,e));return}m.send(o||null)})},Xy={http:QF,xhr:Rj};oe.forEach(Xy,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});const vC=e=>`- ${e}`,Tj=e=>oe.isFunction(e)||e===null||e===!1,pT={getAdapter:e=>{e=oe.isArray(e)?e:[e];const{length:t}=e;let n,r;const o={};for(let i=0;i`adapter ${l} `+(u===!1?"is not supported by the environment":"is not available in the build"));let s=t?i.length>1?`since : +`+i.map(vC).join(` +`):" "+vC(i[0]):"as no adapter specified";throw new ut("There is no suitable adapter to dispatch the request "+s,"ERR_NOT_SUPPORT")}return r},adapters:Xy};function p0(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Rd(null,e)}function yC(e){return p0(e),e.headers=pi.from(e.headers),e.data=f0.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),pT.getAdapter(e.adapter||rx.adapter)(e).then(function(r){return p0(e),r.data=f0.call(e,e.transformResponse,r),r.headers=pi.from(r.headers),r},function(r){return dT(r)||(p0(e),r&&r.response&&(r.response.data=f0.call(e,e.transformResponse,r.response),r.response.headers=pi.from(r.response.headers))),Promise.reject(r)})}const wC=e=>e instanceof pi?e.toJSON():e;function Jl(e,t){t=t||{};const n={};function r(d,h,m){return oe.isPlainObject(d)&&oe.isPlainObject(h)?oe.merge.call({caseless:m},d,h):oe.isPlainObject(h)?oe.merge({},h):oe.isArray(h)?h.slice():h}function o(d,h,m){if(oe.isUndefined(h)){if(!oe.isUndefined(d))return r(void 0,d,m)}else return r(d,h,m)}function i(d,h){if(!oe.isUndefined(h))return r(void 0,h)}function s(d,h){if(oe.isUndefined(h)){if(!oe.isUndefined(d))return r(void 0,d)}else return r(void 0,h)}function l(d,h,m){if(m in t)return r(d,h);if(m in e)return r(void 0,d)}const u={url:i,method:i,data:i,baseURL:s,transformRequest:s,transformResponse:s,paramsSerializer:s,timeout:s,timeoutMessage:s,withCredentials:s,withXSRFToken:s,adapter:s,responseType:s,xsrfCookieName:s,xsrfHeaderName:s,onUploadProgress:s,onDownloadProgress:s,decompress:s,maxContentLength:s,maxBodyLength:s,beforeRedirect:s,transport:s,httpAgent:s,httpsAgent:s,cancelToken:s,socketPath:s,responseEncoding:s,validateStatus:l,headers:(d,h)=>o(wC(d),wC(h),!0)};return oe.forEach(Object.keys(Object.assign({},e,t)),function(h){const m=u[h]||o,g=m(e[h],t[h],h);oe.isUndefined(g)&&m!==l||(n[h]=g)}),n}const hT="1.6.2",ox={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{ox[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const xC={};ox.transitional=function(t,n,r){function o(i,s){return"[Axios v"+hT+"] Transitional option '"+i+"'"+s+(r?". "+r:"")}return(i,s,l)=>{if(t===!1)throw new ut(o(s," has been removed"+(n?" in "+n:"")),ut.ERR_DEPRECATED);return n&&!xC[s]&&(xC[s]=!0,console.warn(o(s," has been deprecated since v"+n+" and will be removed in the near future"))),t?t(i,s,l):!0}};function Pj(e,t,n){if(typeof e!="object")throw new ut("options must be an object",ut.ERR_BAD_OPTION_VALUE);const r=Object.keys(e);let o=r.length;for(;o-- >0;){const i=r[o],s=t[i];if(s){const l=e[i],u=l===void 0||s(l,i,e);if(u!==!0)throw new ut("option "+i+" must be "+u,ut.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new ut("Unknown option "+i,ut.ERR_BAD_OPTION)}}const Zy={assertOptions:Pj,validators:ox},Ui=Zy.validators;class Ph{constructor(t){this.defaults=t,this.interceptors={request:new hC,response:new hC}}request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=Jl(this.defaults,n);const{transitional:r,paramsSerializer:o,headers:i}=n;r!==void 0&&Zy.assertOptions(r,{silentJSONParsing:Ui.transitional(Ui.boolean),forcedJSONParsing:Ui.transitional(Ui.boolean),clarifyTimeoutError:Ui.transitional(Ui.boolean)},!1),o!=null&&(oe.isFunction(o)?n.paramsSerializer={serialize:o}:Zy.assertOptions(o,{encode:Ui.function,serialize:Ui.function},!0)),n.method=(n.method||this.defaults.method||"get").toLowerCase();let s=i&&oe.merge(i.common,i[n.method]);i&&oe.forEach(["delete","get","head","post","put","patch","common"],x=>{delete i[x]}),n.headers=pi.concat(s,i);const l=[];let u=!0;this.interceptors.request.forEach(function(_){typeof _.runWhen=="function"&&_.runWhen(n)===!1||(u=u&&_.synchronous,l.unshift(_.fulfilled,_.rejected))});const d=[];this.interceptors.response.forEach(function(_){d.push(_.fulfilled,_.rejected)});let h,m=0,g;if(!u){const x=[yC.bind(this),void 0];for(x.unshift.apply(x,l),x.push.apply(x,d),g=x.length,h=Promise.resolve(n);m{if(!r._listeners)return;let i=r._listeners.length;for(;i-- >0;)r._listeners[i](o);r._listeners=null}),this.promise.then=o=>{let i;const s=new Promise(l=>{r.subscribe(l),i=l}).then(o);return s.cancel=function(){r.unsubscribe(i)},s},t(function(i,s,l){r.reason||(r.reason=new Rd(i,s,l),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}static source(){let t;return{token:new ix(function(o){t=o}),cancel:t}}}const Aj=ix;function Oj(e){return function(n){return e.apply(null,n)}}function Mj(e){return oe.isObject(e)&&e.isAxiosError===!0}const qy={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(qy).forEach(([e,t])=>{qy[t]=e});const Nj=qy;function mT(e){const t=new zp(e),n=XR(zp.prototype.request,t);return oe.extend(n,zp.prototype,t,{allOwnKeys:!0}),oe.extend(n,t,null,{allOwnKeys:!0}),n.create=function(o){return mT(Jl(e,o))},n}const Jt=mT(rx);Jt.Axios=zp;Jt.CanceledError=Rd;Jt.CancelToken=Aj;Jt.isCancel=dT;Jt.VERSION=hT;Jt.toFormData=Tm;Jt.AxiosError=ut;Jt.Cancel=Jt.CanceledError;Jt.all=function(t){return Promise.all(t)};Jt.spread=Oj;Jt.isAxiosError=Mj;Jt.mergeConfig=Jl;Jt.AxiosHeaders=pi;Jt.formToJSON=e=>uT(oe.isHTMLForm(e)?new FormData(e):e);Jt.getAdapter=pT.getAdapter;Jt.HttpStatusCode=Nj;Jt.default=Jt;const Dj=Jt,Ms="http://127.0.0.1:8080/api/v1",vc=Dj.create({baseURL:Ms});async function Ij(e,t,n,r,o,i=null){const s=await Ru(e),l=await Ru(o),u=i?await Ru(i):null,d=await fetch(`${Ms}/inpaint`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({image:s,mask:l,ldm_steps:t.ldmSteps,ldm_sampler:t.ldmSampler,zits_wireframe:t.zitsWireframe,cv2_flag:t.cv2Flag,cv2_radius:t.cv2Radius,hd_strategy:"Crop",hd_strategy_crop_triger_size:640,hd_strategy_crop_margin:128,hd_trategy_resize_imit:2048,prompt:t.prompt,negative_prompt:t.negativePrompt,use_croper:t.showCropper,croper_x:n.x,croper_y:n.y,croper_height:n.height,croper_width:n.width,use_extender:t.showExtender,extender_x:r.x,extender_y:r.y,extender_height:r.height,extender_width:r.width,sd_mask_blur:t.sdMaskBlur,sd_strength:t.sdStrength,sd_steps:t.sdSteps,sd_guidance_scale:t.sdGuidanceScale,sd_sampler:t.sdSampler,sd_seed:t.seedFixed?t.seed:-1,sd_match_histograms:t.sdMatchHistograms,sd_freeu:t.enableFreeu,sd_freeu_config:t.freeuConfig,sd_lcm_lora:t.enableLCMLora,paint_by_example_example_image:u,p2p_image_guidance_scale:t.p2pImageGuidanceScale,enable_controlnet:t.enableControlnet,controlnet_conditioning_scale:t.controlnetConditioningScale,controlnet_method:t.controlnetMethod?t.controlnetMethod:"",powerpaint_task:t.showExtender?kl.outpainting:t.powerpaintTask})});if(d.ok){const m=await d.blob();return{blob:URL.createObjectURL(m),seed:d.headers.get("X-Seed")}}const h=await d.json();throw new Error(`Something went wrong: ${h.errors}`)}async function Lj(){return(await vc.get("/server-config")).data}async function Fj(e){return(await vc.post("/model",{name:e})).data}async function jj(){return(await vc.get("/model")).data}function zj(){return vc.get("/models").then(e=>e.data)}async function gT(e,t,n,r,o){const i=await Ru(n),l=await fetch(`${Ms}/${e?"run_plugin_gen_mask":"run_plugin_gen_image"}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t,image:i,upscale:r,clicks:o})});if(l.ok){const d=await l.blob();return{blob:URL.createObjectURL(d)}}const u=await l.json();throw new Error(u)}async function Bj(e,t){const n=await fetch(`${Ms}/media_file?tab=${e}&filename=${encodeURIComponent(t)}`,{method:"GET"});if(n.ok){const o=await n.blob();return new File([o],t,{type:n.headers.get("Content-Type")??"image/png"})}const r=await n.json();throw new Error(r.errors)}async function Uj(e){return(await vc.get("medias",{params:{tab:e}})).data}async function Vj(e,t,n){const r=await ku(e.src,t,n),o=new FormData;o.append("file",r);try{const i=await fetch(`${Ms}/save_image`,{method:"POST",body:o});if(!i.ok){const s=await i.text();throw new Error(s)}}catch(i){throw new Error(`Something went wrong: ${i}`)}}async function Wj(e){const t=new FormData;return t.append("file",e),(await vc.post("/gen-info",t)).data}async function Hj(e,t,n){const r=await Ru(e),o=await fetch(`${Ms}/adjust_mask`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mask:r,operate:t,kernel_size:n})});if(o.ok)return await o.blob();const i=await o.json();throw new Error(i)}function Kj(){const[e,t]=f.useState(null),n=f.useCallback(()=>{const r=new Headers;r.append("pragma","no-cache"),r.append("cache-control","no-cache"),fetch(`${Ms}/inputimage`,{headers:r}).then(async o=>{var l;if(!o.ok)throw new Error("No input image found");const i=(l=o.headers.get("content-disposition"))==null?void 0:l.split("filename=")[1].split(";")[0],s=await o.blob();if(s&&s.type.startsWith("image")){const u=new File([s],i!==void 0?i:"inputImage");t(u)}}).catch(o=>{console.log(o)})},[t]);return f.useEffect(()=>{n()},[n]),e}function xo(e,t){if(e==null)return{};var n={},r=Object.keys(e),o,i;for(i=0;i=0)&&(n[o]=e[o]);return n}var Yj=["color"],Gj=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,Yj);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),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:r,fillRule:"evenodd",clipRule:"evenodd"}))}),Xj=["color"],vT=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,Xj);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M11.4669 3.72684C11.7558 3.91574 11.8369 4.30308 11.648 4.59198L7.39799 11.092C7.29783 11.2452 7.13556 11.3467 6.95402 11.3699C6.77247 11.3931 6.58989 11.3355 6.45446 11.2124L3.70446 8.71241C3.44905 8.48022 3.43023 8.08494 3.66242 7.82953C3.89461 7.57412 4.28989 7.55529 4.5453 7.78749L6.75292 9.79441L10.6018 3.90792C10.7907 3.61902 11.178 3.53795 11.4669 3.72684Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),Zj=["color"],qj=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,Zj);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M3.13523 6.15803C3.3241 5.95657 3.64052 5.94637 3.84197 6.13523L7.5 9.56464L11.158 6.13523C11.3595 5.94637 11.6759 5.95657 11.8648 6.15803C12.0536 6.35949 12.0434 6.67591 11.842 6.86477L7.84197 10.6148C7.64964 10.7951 7.35036 10.7951 7.15803 10.6148L3.15803 6.86477C2.95657 6.67591 2.94637 6.35949 3.13523 6.15803Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),Qj=["color"],Jj=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,Qj);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M6.1584 3.13508C6.35985 2.94621 6.67627 2.95642 6.86514 3.15788L10.6151 7.15788C10.7954 7.3502 10.7954 7.64949 10.6151 7.84182L6.86514 11.8418C6.67627 12.0433 6.35985 12.0535 6.1584 11.8646C5.95694 11.6757 5.94673 11.3593 6.1356 11.1579L9.565 7.49985L6.1356 3.84182C5.94673 3.64036 5.95694 3.32394 6.1584 3.13508Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),ez=["color"],tz=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,ez);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M3.13523 8.84197C3.3241 9.04343 3.64052 9.05363 3.84197 8.86477L7.5 5.43536L11.158 8.86477C11.3595 9.05363 11.6759 9.04343 11.8648 8.84197C12.0536 8.64051 12.0434 8.32409 11.842 8.13523L7.84197 4.38523C7.64964 4.20492 7.35036 4.20492 7.15803 4.38523L3.15803 8.13523C2.95657 8.32409 2.94637 8.64051 3.13523 8.84197Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),nz=["color"],yT=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,nz);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),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:r,fillRule:"evenodd",clipRule:"evenodd"}))}),rz=["color"],oz=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,rz);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M9.875 7.5C9.875 8.81168 8.81168 9.875 7.5 9.875C6.18832 9.875 5.125 8.81168 5.125 7.5C5.125 6.18832 6.18832 5.125 7.5 5.125C8.81168 5.125 9.875 6.18832 9.875 7.5Z",fill:r}))}),iz=["color"],sz=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,iz);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M10 6.5C10 8.433 8.433 10 6.5 10C4.567 10 3 8.433 3 6.5C3 4.567 4.567 3 6.5 3C8.433 3 10 4.567 10 6.5ZM9.30884 10.0159C8.53901 10.6318 7.56251 11 6.5 11C4.01472 11 2 8.98528 2 6.5C2 4.01472 4.01472 2 6.5 2C8.98528 2 11 4.01472 11 6.5C11 7.56251 10.6318 8.53901 10.0159 9.30884L12.8536 12.1464C13.0488 12.3417 13.0488 12.6583 12.8536 12.8536C12.6583 13.0488 12.3417 13.0488 12.1464 12.8536L9.30884 10.0159Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),az=["color"],lz=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,az);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M3.24182 2.32181C3.3919 2.23132 3.5784 2.22601 3.73338 2.30781L12.7334 7.05781C12.8974 7.14436 13 7.31457 13 7.5C13 7.68543 12.8974 7.85564 12.7334 7.94219L3.73338 12.6922C3.5784 12.774 3.3919 12.7687 3.24182 12.6782C3.09175 12.5877 3 12.4252 3 12.25V2.75C3 2.57476 3.09175 2.4123 3.24182 2.32181ZM4 3.57925V11.4207L11.4288 7.5L4 3.57925Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),cz=["color"],uz=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,cz);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M7 2H1.5C1.22386 2 1 2.22386 1 2.5V7H7V2ZM8 2V7H14V2.5C14 2.22386 13.7761 2 13.5 2H8ZM7 8H1V12.5C1 12.7761 1.22386 13 1.5 13H7V8ZM8 13V8H14V12.5C14 12.7761 13.7761 13 13.5 13H8ZM1.5 1C0.671573 1 0 1.67157 0 2.5V12.5C0 13.3284 0.671573 14 1.5 14H13.5C14.3284 14 15 13.3284 15 12.5V2.5C15 1.67157 14.3284 1 13.5 1H1.5Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),dz=["color"],fz=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,dz);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M1.5 2H13.5C13.7761 2 14 2.22386 14 2.5V7H1V2.5C1 2.22386 1.22386 2 1.5 2ZM1 8V12.5C1 12.7761 1.22386 13 1.5 13H13.5C13.7761 13 14 12.7761 14 12.5V8H1ZM0 2.5C0 1.67157 0.671573 1 1.5 1H13.5C14.3284 1 15 1.67157 15 2.5V12.5C15 13.3284 14.3284 14 13.5 14H1.5C0.671573 14 0 13.3284 0 12.5V2.5Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))});function Y(){return Y=Object.assign?Object.assign.bind():function(e){for(var t=1;te.forEach(n=>pz(n,t))}function Be(...e){return f.useCallback(Am(...e),e)}const Wo=f.forwardRef((e,t)=>{const{children:n,...r}=e,o=f.Children.toArray(n),i=o.find(hz);if(i){const s=i.props.children,l=o.map(u=>u===i?f.Children.count(s)>1?f.Children.only(null):f.isValidElement(s)?s.props.children:null:u);return f.createElement(Qy,Y({},r,{ref:t}),f.isValidElement(s)?f.cloneElement(s,void 0,l):null)}return f.createElement(Qy,Y({},r,{ref:t}),n)});Wo.displayName="Slot";const Qy=f.forwardRef((e,t)=>{const{children:n,...r}=e;return f.isValidElement(n)?f.cloneElement(n,{...mz(r,n.props),ref:t?Am(t,n.ref):n.ref}):f.Children.count(n)>1?f.Children.only(null):null});Qy.displayName="SlotClone";const sx=({children:e})=>f.createElement(f.Fragment,null,e);function hz(e){return f.isValidElement(e)&&e.type===sx}function mz(e,t){const n={...t};for(const r in t){const o=e[r],i=t[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...l)=>{i(...l),o(...l)}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...e,...n}}const bC=e=>typeof e=="boolean"?"".concat(e):e===0?"0":e,_C=BR,Om=(e,t)=>n=>{var r;if((t==null?void 0:t.variants)==null)return _C(e,n==null?void 0:n.class,n==null?void 0:n.className);const{variants:o,defaultVariants:i}=t,s=Object.keys(o).map(d=>{const h=n==null?void 0:n[d],m=i==null?void 0:i[d];if(h===null)return null;const g=bC(h)||bC(m);return o[d][g]}),l=n&&Object.entries(n).reduce((d,h)=>{let[m,g]=h;return g===void 0||(d[m]=g),d},{}),u=t==null||(r=t.compoundVariants)===null||r===void 0?void 0:r.reduce((d,h)=>{let{class:m,className:g,...y}=h;return Object.entries(y).every(x=>{let[_,C]=x;return Array.isArray(C)?C.includes({...i,...l}[_]):{...i,...l}[_]===C})?[...d,m,g]:d},[]);return _C(e,s,u,n==null?void 0:n.class,n==null?void 0:n.className)};var gz={VITE_BACKEND:"http://127.0.0.1:8080",BASE_URL:"/",MODE:"production",DEV:!1,PROD:!0,SSR:!1};function vz(e,t){let n;try{n=e()}catch{return}return{getItem:o=>{var i;const s=u=>u===null?null:JSON.parse(u,t==null?void 0:t.reviver),l=(i=n.getItem(o))!=null?i:null;return l instanceof Promise?l.then(s):s(l)},setItem:(o,i)=>n.setItem(o,JSON.stringify(i,t==null?void 0:t.replacer)),removeItem:o=>n.removeItem(o)}}const qu=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then(r){return qu(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return qu(r)(n)}}}},yz=(e,t)=>(n,r,o)=>{let i={getStorage:()=>localStorage,serialize:JSON.stringify,deserialize:JSON.parse,partialize:C=>C,version:0,merge:(C,S)=>({...S,...C}),...t},s=!1;const l=new Set,u=new Set;let d;try{d=i.getStorage()}catch{}if(!d)return e((...C)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),n(...C)},r,o);const h=qu(i.serialize),m=()=>{const C=i.partialize({...r()});let S;const b=h({state:C,version:i.version}).then(E=>d.setItem(i.name,E)).catch(E=>{S=E});if(S)throw S;return b},g=o.setState;o.setState=(C,S)=>{g(C,S),m()};const y=e((...C)=>{n(...C),m()},r,o);let x;const _=()=>{var C;if(!d)return;s=!1,l.forEach(b=>b(r()));const S=((C=i.onRehydrateStorage)==null?void 0:C.call(i,r()))||void 0;return qu(d.getItem.bind(d))(i.name).then(b=>{if(b)return i.deserialize(b)}).then(b=>{if(b)if(typeof b.version=="number"&&b.version!==i.version){if(i.migrate)return i.migrate(b.state,b.version);console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return b.state}).then(b=>{var E;return x=i.merge(b,(E=r())!=null?E:y),n(x,!0),m()}).then(()=>{S==null||S(x,void 0),s=!0,u.forEach(b=>b(x))}).catch(b=>{S==null||S(void 0,b)})};return o.persist={setOptions:C=>{i={...i,...C},C.getStorage&&(d=C.getStorage())},clearStorage:()=>{d==null||d.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>_(),hasHydrated:()=>s,onHydrate:C=>(l.add(C),()=>{l.delete(C)}),onFinishHydration:C=>(u.add(C),()=>{u.delete(C)})},_(),x||y},wz=(e,t)=>(n,r,o)=>{let i={storage:vz(()=>localStorage),partialize:_=>_,version:0,merge:(_,C)=>({...C,..._}),...t},s=!1;const l=new Set,u=new Set;let d=i.storage;if(!d)return e((..._)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),n(..._)},r,o);const h=()=>{const _=i.partialize({...r()});return d.setItem(i.name,{state:_,version:i.version})},m=o.setState;o.setState=(_,C)=>{m(_,C),h()};const g=e((..._)=>{n(..._),h()},r,o);let y;const x=()=>{var _,C;if(!d)return;s=!1,l.forEach(b=>{var E;return b((E=r())!=null?E:g)});const S=((C=i.onRehydrateStorage)==null?void 0:C.call(i,(_=r())!=null?_:g))||void 0;return qu(d.getItem.bind(d))(i.name).then(b=>{if(b)if(typeof b.version=="number"&&b.version!==i.version){if(i.migrate)return i.migrate(b.state,b.version);console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return b.state}).then(b=>{var E;return y=i.merge(b,(E=r())!=null?E:g),n(y,!0),h()}).then(()=>{S==null||S(y,void 0),y=r(),s=!0,u.forEach(b=>b(y))}).catch(b=>{S==null||S(void 0,b)})};return o.persist={setOptions:_=>{i={...i,..._},_.storage&&(d=_.storage)},clearStorage:()=>{d==null||d.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>x(),hasHydrated:()=>s,onHydrate:_=>(l.add(_),()=>{l.delete(_)}),onFinishHydration:_=>(u.add(_),()=>{u.delete(_)})},i.skipHydration||x(),y||g},xz=(e,t)=>"getStorage"in t||"serialize"in t||"deserialize"in t?((gz?"production":void 0)!=="production"&&console.warn("[DEPRECATED] `getStorage`, `serialize` and `deserialize` options are deprecated. Use `storage` option instead."),yz(e,t)):wz(e,t),bz=xz;function _z(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,o]of e)if(!Object.is(o,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{t(n,r,e)}):e.forEach((n,r)=>t(r,n,e))}function Mm(e){const t=e[wr];return t?t.type_:Array.isArray(e)?1:Nm(e)?2:Dm(e)?3:0}function Jy(e,t){return Mm(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function bT(e,t,n){const r=Mm(e);r===2?e.set(t,n):r===3?e.add(n):e[t]=n}function Ez(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function Nm(e){return e instanceof Map}function Dm(e){return e instanceof Set}function Js(e){return e.copy_||e.base_}function e1(e,t){if(Nm(e))return new Map(e);if(Dm(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);if(!t&&xT(e))return ec(e)?{...e}:Object.assign(Object.create(null),e);const n=Object.getOwnPropertyDescriptors(e);delete n[wr];let r=Reflect.ownKeys(n);for(let o=0;o1&&(e.set=e.add=e.clear=e.delete=Cz),Object.freeze(e),t&&Qu(e,(n,r)=>ax(r,!0))),e}function Cz(){ho(2)}function Im(e){return Object.isFrozen(e)}var $z={};function ka(e){const t=$z[e];return t||ho(0,e),t}var Ju;function _T(){return Ju}function kz(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function EC(e,t){t&&(ka("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function t1(e){n1(e),e.drafts_.forEach(Rz),e.drafts_=null}function n1(e){e===Ju&&(Ju=e.parent_)}function CC(e){return Ju=kz(Ju,e)}function Rz(e){const t=e[wr];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function $C(e,t){t.unfinalizedDrafts_=t.drafts_.length;const n=t.drafts_[0];return e!==void 0&&e!==n?(n[wr].modified_&&(t1(t),ho(4)),$a(e)&&(e=Ah(t,e),t.parent_||Oh(t,e)),t.patches_&&ka("Patches").generateReplacementPatches_(n[wr].base_,e,t.patches_,t.inversePatches_)):e=Ah(t,n,[]),t1(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==wT?e:void 0}function Ah(e,t,n){if(Im(t))return t;const r=t[wr];if(!r)return Qu(t,(o,i)=>kC(e,r,t,o,i,n)),t;if(r.scope_!==e)return t;if(!r.modified_)return Oh(e,r.base_,!0),r.base_;if(!r.finalized_){r.finalized_=!0,r.scope_.unfinalizedDrafts_--;const o=r.copy_;let i=o,s=!1;r.type_===3&&(i=new Set(o),o.clear(),s=!0),Qu(i,(l,u)=>kC(e,r,o,l,u,n,s)),Oh(e,o,!1),n&&e.patches_&&ka("Patches").generatePatches_(r,n,e.patches_,e.inversePatches_)}return r.copy_}function kC(e,t,n,r,o,i,s){if(tc(o)){const l=i&&t&&t.type_!==3&&!Jy(t.assigned_,r)?i.concat(r):void 0,u=Ah(e,o,l);if(bT(n,r,u),tc(u))e.canAutoFreeze_=!1;else return}else s&&n.add(o);if($a(o)&&!Im(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;Ah(e,o),(!t||!t.scope_.parent_)&&Oh(e,o)}}function Oh(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&ax(t,n)}function Tz(e,t){const n=Array.isArray(e),r={type_:n?1:0,scope_:t?t.scope_:_T(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1};let o=r,i=lx;n&&(o=[r],i=ed);const{revoke:s,proxy:l}=Proxy.revocable(o,i);return r.draft_=l,r.revoke_=s,l}var lx={get(e,t){if(t===wr)return e;const n=Js(e);if(!Jy(n,t))return Pz(e,n,t);const r=n[t];return e.finalized_||!$a(r)?r:r===h0(e.base_,t)?(m0(e),e.copy_[t]=o1(r,e)):r},has(e,t){return t in Js(e)},ownKeys(e){return Reflect.ownKeys(Js(e))},set(e,t,n){const r=ST(Js(e),t);if(r!=null&&r.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){const o=h0(Js(e),t),i=o==null?void 0:o[wr];if(i&&i.base_===n)return e.copy_[t]=n,e.assigned_[t]=!1,!0;if(Ez(n,o)&&(n!==void 0||Jy(e.base_,t)))return!0;m0(e),r1(e)}return e.copy_[t]===n&&(n!==void 0||t in e.copy_)||Number.isNaN(n)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=n,e.assigned_[t]=!0),!0},deleteProperty(e,t){return h0(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,m0(e),r1(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){const n=Js(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:r.enumerable,value:n[t]}},defineProperty(){ho(11)},getPrototypeOf(e){return ec(e.base_)},setPrototypeOf(){ho(12)}},ed={};Qu(lx,(e,t)=>{ed[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});ed.deleteProperty=function(e,t){return ed.set.call(this,e,t,void 0)};ed.set=function(e,t,n){return lx.set.call(this,e[0],t,n,e[0])};function h0(e,t){const n=e[wr];return(n?Js(n):e)[t]}function Pz(e,t,n){var o;const r=ST(t,n);return r?"value"in r?r.value:(o=r.get)==null?void 0:o.call(e.draft_):void 0}function ST(e,t){if(!(t in e))return;let n=ec(e);for(;n;){const r=Object.getOwnPropertyDescriptor(n,t);if(r)return r;n=ec(n)}}function r1(e){e.modified_||(e.modified_=!0,e.parent_&&r1(e.parent_))}function m0(e){e.copy_||(e.copy_=e1(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var Az=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(t,n,r)=>{if(typeof t=="function"&&typeof n!="function"){const i=n;n=t;const s=this;return function(u=i,...d){return s.produce(u,h=>n.call(this,h,...d))}}typeof n!="function"&&ho(6),r!==void 0&&typeof r!="function"&&ho(7);let o;if($a(t)){const i=CC(this),s=o1(t,void 0);let l=!0;try{o=n(s),l=!1}finally{l?t1(i):n1(i)}return EC(i,r),$C(o,i)}else if(!t||typeof t!="object"){if(o=n(t),o===void 0&&(o=t),o===wT&&(o=void 0),this.autoFreeze_&&ax(o,!0),r){const i=[],s=[];ka("Patches").generateReplacementPatches_(t,o,i,s),r(i,s)}return o}else ho(1,t)},this.produceWithPatches=(t,n)=>{if(typeof t=="function")return(s,...l)=>this.produceWithPatches(s,u=>t(u,...l));let r,o;return[this.produce(t,n,(s,l)=>{r=s,o=l}),r,o]},typeof(e==null?void 0:e.autoFreeze)=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof(e==null?void 0:e.useStrictShallowCopy)=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){$a(e)||ho(8),tc(e)&&(e=Oz(e));const t=CC(this),n=o1(e,void 0);return n[wr].isManual_=!0,n1(t),n}finishDraft(e,t){const n=e&&e[wr];(!n||!n.isManual_)&&ho(9);const{scope_:r}=n;return EC(r,t),$C(void 0,r)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let n;for(n=t.length-1;n>=0;n--){const o=t[n];if(o.path.length===0&&o.op==="replace"){e=o.value;break}}n>-1&&(t=t.slice(n+1));const r=ka("Patches").applyPatches_;return tc(e)?r(e,t):this.produce(e,o=>r(o,t))}};function o1(e,t){const n=Nm(e)?ka("MapSet").proxyMap_(e,t):Dm(e)?ka("MapSet").proxySet_(e,t):Tz(e,t);return(t?t.scope_:_T()).drafts_.push(n),n}function Oz(e){return tc(e)||ho(10,e),ET(e)}function ET(e){if(!$a(e)||Im(e))return e;const t=e[wr];let n;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=e1(e,t.scope_.immer_.useStrictShallowCopy_)}else n=e1(e,!0);return Qu(n,(r,o)=>{bT(n,r,ET(o))}),t&&(t.finalized_=!1),n}var xr=new Az,Mz=xr.produce;xr.produceWithPatches.bind(xr);xr.setAutoFreeze.bind(xr);xr.setUseStrictShallowCopy.bind(xr);xr.applyPatches.bind(xr);xr.createDraft.bind(xr);xr.finishDraft.bind(xr);const Nz=e=>(t,n,r)=>(r.setState=(o,i,...s)=>{const l=typeof o=="function"?Mz(o):o;return t(l,i,...s)},e(r.setState,n,r)),Dz=Nz;var CT={exports:{}},$T={},kT={exports:{}},RT={};/** + * @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 nc=f;function Iz(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var Lz=typeof Object.is=="function"?Object.is:Iz,Fz=nc.useState,jz=nc.useEffect,zz=nc.useLayoutEffect,Bz=nc.useDebugValue;function Uz(e,t){var n=t(),r=Fz({inst:{value:n,getSnapshot:t}}),o=r[0].inst,i=r[1];return zz(function(){o.value=n,o.getSnapshot=t,g0(o)&&i({inst:o})},[e,n,t]),jz(function(){return g0(o)&&i({inst:o}),e(function(){g0(o)&&i({inst:o})})},[e]),Bz(n),n}function g0(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!Lz(e,n)}catch{return!0}}function Vz(e,t){return t()}var Wz=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?Vz:Uz;RT.useSyncExternalStore=nc.useSyncExternalStore!==void 0?nc.useSyncExternalStore:Wz;kT.exports=RT;var Hz=kT.exports;/** + * @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 Lm=f,Kz=Hz;function Yz(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var Gz=typeof Object.is=="function"?Object.is:Yz,Xz=Kz.useSyncExternalStore,Zz=Lm.useRef,qz=Lm.useEffect,Qz=Lm.useMemo,Jz=Lm.useDebugValue;$T.useSyncExternalStoreWithSelector=function(e,t,n,r,o){var i=Zz(null);if(i.current===null){var s={hasValue:!1,value:null};i.current=s}else s=i.current;i=Qz(function(){function u(y){if(!d){if(d=!0,h=y,y=r(y),o!==void 0&&s.hasValue){var x=s.value;if(o(x,y))return m=x}return m=y}if(x=m,Gz(h,y))return x;var _=r(y);return o!==void 0&&o(x,_)?x:(h=y,m=_)}var d=!1,h,m,g=n===void 0?null:n;return[function(){return u(t())},g===null?void 0:function(){return u(g())}]},[t,n,r,o]);var l=Xz(e,i[0],i[1]);return qz(function(){s.hasValue=!0,s.value=l},[l]),Jz(l),l};CT.exports=$T;var eB=CT.exports;const tB=lm(eB);var nB={VITE_BACKEND:"http://127.0.0.1:8080",BASE_URL:"/",MODE:"production",DEV:!1,PROD:!0,SSR:!1};const RC=e=>{let t;const n=new Set,r=(u,d)=>{const h=typeof u=="function"?u(t):u;if(!Object.is(h,t)){const m=t;t=d??typeof h!="object"?h:Object.assign({},t,h),n.forEach(g=>g(t,m))}},o=()=>t,l={setState:r,getState:o,subscribe:u=>(n.add(u),()=>n.delete(u)),destroy:()=>{(nB?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),n.clear()}};return t=e(r,o,l),l},rB=e=>e?RC(e):RC,{useDebugValue:oB}=Fe,{useSyncExternalStoreWithSelector:iB}=tB;function sB(e,t=e.getState,n){const r=iB(e.subscribe,e.getState,e.getServerState||e.getState,t,n);return oB(r),r}const TC=(e,t)=>{const n=rB(e),r=(o,i=t)=>sB(n,o,i);return Object.assign(r,n),r},aB=(e,t)=>e?TC(e,t):TC,lB=1,cB=1e6;let v0=0;function uB(){return v0=(v0+1)%Number.MAX_VALUE,v0.toString()}const y0=new Map,PC=e=>{if(y0.has(e))return;const t=setTimeout(()=>{y0.delete(e),Tu({type:"REMOVE_TOAST",toastId:e})},cB);y0.set(e,t)},dB=(e,t)=>{switch(t.type){case"ADD_TOAST":return{...e,toasts:[t.toast,...e.toasts].slice(0,lB)};case"UPDATE_TOAST":return{...e,toasts:e.toasts.map(n=>n.id===t.toast.id?{...n,...t.toast}:n)};case"DISMISS_TOAST":{const{toastId:n}=t;return n?PC(n):e.toasts.forEach(r=>{PC(r.id)}),{...e,toasts:e.toasts.map(r=>r.id===n||n===void 0?{...r,open:!1}:r)}}case"REMOVE_TOAST":return t.toastId===void 0?{...e,toasts:[]}:{...e,toasts:e.toasts.filter(n=>n.id!==t.toastId)}}},Bp=[];let Up={toasts:[]};function Tu(e){Up=dB(Up,e),Bp.forEach(t=>{t(Up)})}function rl({...e}){const t=uB(),n=o=>Tu({type:"UPDATE_TOAST",toast:{...o,id:t}}),r=()=>Tu({type:"DISMISS_TOAST",toastId:t});return Tu({type:"ADD_TOAST",toast:{...e,id:t,open:!0,onOpenChange:o=>{o||r()}}}),{id:t,dismiss:r,update:n}}function Td(){const[e,t]=f.useState(Up);return f.useEffect(()=>(Bp.push(t),()=>{const n=Bp.indexOf(t);n>-1&&Bp.splice(n,1)}),[e]),{...e,toast:rl,dismiss:n=>Tu({type:"DISMISS_TOAST",toastId:n})}}const Zs={file:null,paintByExampleFile:null,customMask:null,imageHeight:0,imageWidth:0,isInpainting:!1,isPluginRunning:!1,isAdjustingMask:!1,disableShortCuts:!1,windowSize:{height:600,width:800},editorState:{baseBrushSize:sF,brushSizeScale:1,renders:[],extraMasks:[],prevExtraMasks:[],temporaryMasks:[],lineGroups:[],lastLineGroup:[],curLineGroup:[],redoRenders:[],redoCurLines:[],redoLineGroups:[]},interactiveSegState:{isInteractiveSeg:!1,tmpInteractiveSegMask:null,clicks:[]},cropperState:{x:0,y:0,width:512,height:512},extenderState:{x:0,y:0,width:512,height:512},isCropperExtenderResizing:!1,fileManagerState:{sortBy:xs.CTIME,sortOrder:$u.DESCENDING,layout:"masonry",searchText:"",inputDirectory:"",outputDirectory:""},serverConfig:{plugins:[],enableFileManager:!1,enableAutoSaving:!1,enableControlnet:!1,controlnetMethod:"lllyasviel/control_v11p_sd15_canny",disableModelSwitch:!1,isDesktop:!1,samplers:["DPM++ 2M"]},settings:{model:{name:"lama",path:"lama",model_type:"inpaint",support_controlnet:!1,support_strength:!1,support_outpainting:!1,controlnets:[],support_freeu:!1,support_lcm_lora:!1,is_single_file_diffusers:!1,need_prompt:!1},enableControlnet:!1,showCropper:!1,showExtender:!1,extenderDirection:In.xy,enableDownloadMask:!1,enableManualInpainting:!1,enableUploadMask:!1,enableAutoExtractPrompt:!0,ldmSteps:30,ldmSampler:Zw.ddim,zitsWireframe:!0,cv2Radius:5,cv2Flag:qw.INPAINT_NS,prompt:"",negativePrompt:cF,seed:42,seedFixed:!1,sdMaskBlur:35,sdStrength:1,sdSteps:50,sdGuidanceScale:7.5,sdSampler:"DPM++ 2M",sdMatchHistograms:!1,sdScale:1,p2pImageGuidanceScale:1.5,controlnetConditioningScale:.4,controlnetMethod:"lllyasviel/control_v11p_sd15_canny",enableLCMLora:!1,enableFreeu:!1,freeuConfig:{s1:.9,s2:.2,b1:1.2,b2:1.4},powerpaintTask:kl.text_guided,adjustMaskKernelSize:12}},bt=aB()(bz(Dz((e,t)=>({...Zs,showPrevMask:async()=>{if(t().settings.showExtender)return;const{lastLineGroup:n,curLineGroup:r,prevExtraMasks:o,extraMasks:i}=t().editorState;if(r.length!==0||i.length!==0)return;const{imageWidth:s,imageHeight:l}=t(),u=Lp(s,l,[n],o,Ky);try{const d=await aC(u);e(h=>{h.editorState.temporaryMasks.push(d)})}catch(d){console.error(d);return}},hidePrevMask:()=>{e(n=>{n.editorState.temporaryMasks=[]})},getCurrentTargetFile:async()=>{const n=t().file,r=t().editorState.renders;let o=n;if(r.length>0){const i=r[r.length-1];o=await ku(i.currentSrc,n.name,n.type)}return o},runInpainting:async()=>{const{isInpainting:n,file:r,paintByExampleFile:o,imageWidth:i,imageHeight:s,settings:l,cropperState:u,extenderState:d}=t();if(n||r===null||t().settings.model.support_outpainting&&l.showExtender&&d.height===s&&d.width===i)return;const{lastLineGroup:h,curLineGroup:m,lineGroups:g,renders:y,prevExtraMasks:x,extraMasks:_}=t().editorState,C=m.length===0&&_.length===0&&!l.showExtender;let S=[],b=[];if(C===!0?(b=h,S=x):(b=m,S=_),b.length===0&&S===null&&!l.showExtender){rl({variant:"destructive",description:"Please draw mask on picture"});return}const E=[...g,b];e(M=>{M.isInpainting=!0});let k=r;if(C===!0){if(y.length>1){const M=y[y.length-2];k=await ku(M.currentSrc,r.name,r.type)}}else if(y.length>0){const M=y[y.length-1];k=await ku(M.currentSrc,r.name,r.type)}const P=Lp(i,s,[b],S);if(C){const M=await aC(P);e(A=>{A.editorState.temporaryMasks=[M]})}try{const M=await Ij(k,l,u,d,sC(P.toDataURL()),o),{blob:A,seed:O}=M;O&&t().setSeed(parseInt(O,10));const F=new Image;await Ip(F,A);const V=[...y,F];t().setImageSize(F.width,F.height),t().updateEditorState({renders:V,lineGroups:E,lastLineGroup:b,curLineGroup:[],extraMasks:[],prevExtraMasks:S})}catch(M){rl({variant:"destructive",description:M.message?M.message:M.toString()})}t().resetRedoState(),e(M=>{M.isInpainting=!1,M.editorState.temporaryMasks=[]})},runRenderablePlugin:async(n,r,o={upscale:1})=>{const{renders:i,lineGroups:s}=t().editorState;e(l=>{l.isPluginRunning=!0});try{const l=new Date,u=await t().getCurrentTargetFile(),d=await gT(n,r,u,o.upscale),{blob:h}=d;if(n){const y=new Image;await Ip(y,h),e(x=>{x.editorState.extraMasks.push(y)})}else{const y=new Image;await Ip(y,h),t().setImageSize(y.width,y.height);const x=[...i,y],_=[...s,[]];t().updateEditorState({renders:x,lineGroups:_})}const g=new Date().getTime()-l.getTime();rl({description:`Run ${r} successfully in ${g/1e3}s`})}catch(l){rl({variant:"destructive",description:l.message?l.message:l.toString()})}e(l=>{l.isPluginRunning=!1})},updateEditorState:n=>{e(r=>{r.editorState={...r.editorState,...n}})},cleanCurLineGroup:()=>{t().updateEditorState({curLineGroup:[]})},handleCanvasMouseDown:n=>{let r=[];const o=t();o.runMannually()&&(r=[...o.editorState.curLineGroup]),r.push({size:o.getBrushSize(),pts:[n]}),e(i=>{i.editorState.curLineGroup=r})},handleCanvasMouseMove:n=>{e(r=>{const o=r.editorState.curLineGroup;o.length&&o[o.length-1].pts.push(n)})},runMannually:()=>{const n=t();return n.settings.enableManualInpainting||n.settings.model.model_type!==is},getIsProcessing:()=>t().isInpainting||t().isPluginRunning||t().isAdjustingMask,isSD:()=>t().settings.model.model_type!==is,undoDisabled:()=>{const n=t().editorState;if(n.renders.length>0)return!1;if(t().runMannually()){if(n.curLineGroup.length===0)return!0}else if(n.renders.length===0)return!0;return!1},undo:()=>{t().runMannually()&&t().editorState.curLineGroup.length!==0?e(n=>{const r=n.editorState;if(r.curLineGroup.length===0)return;r.lastLineGroup=[];const o=r.curLineGroup.pop();r.redoCurLines.push(o)}):e(n=>{const r=n.editorState;if(r.renders.length===0||r.lineGroups.length===0)return;const o=r.lineGroups.pop();r.redoLineGroups.push(o),r.redoCurLines=[],r.curLineGroup=[];const i=r.renders.pop();r.redoRenders.push(i)})},redoDisabled:()=>{const n=t().editorState;if(n.redoRenders.length>0)return!1;if(t().runMannually()){if(n.redoCurLines.length===0)return!0}else if(n.redoRenders.length===0)return!0;return!1},redo:()=>{t().runMannually()&&t().editorState.redoCurLines.length!==0?e(n=>{const r=n.editorState;if(r.redoCurLines.length===0)return;const o=r.redoCurLines.pop();r.curLineGroup.push(o)}):e(n=>{const r=n.editorState;if(r.redoRenders.length===0||r.redoLineGroups.length===0)return;const o=r.redoLineGroups.pop();r.lineGroups.push(o),r.curLineGroup=[];const i=r.redoRenders.pop();r.renders.push(i)})},resetRedoState:()=>{e(n=>{n.editorState.redoCurLines=[],n.editorState.redoLineGroups=[],n.editorState.redoRenders=[]})},updateAppState:n=>{e(()=>n)},getBrushSize:()=>t().editorState.baseBrushSize*t().editorState.brushSizeScale,showPromptInput:()=>{const n=t().settings.model;return n.model_type!==is&&n.name!==YR},setServerConfig:n=>{e(r=>{r.serverConfig=n,r.settings.enableControlnet=n.enableControlnet,r.settings.controlnetMethod=n.controlnetMethod})},updateSettings:n=>{e(r=>{r.settings={...r.settings,...n}})},setModel:n=>{e(r=>{r.settings.model=n,n.support_controlnet&&!n.controlnets.includes(r.settings.controlnetMethod)&&(r.settings.controlnetMethod=n.controlnets[0])})},updateFileManagerState:n=>{e(r=>{r.fileManagerState={...r.fileManagerState,...n}})},updateInteractiveSegState:n=>{e(r=>({...r,interactiveSegState:{...r.interactiveSegState,...n}}))},resetInteractiveSegState:()=>{t().updateInteractiveSegState(Zs.interactiveSegState)},handleInteractiveSegAccept:()=>{e(n=>{n.interactiveSegState.tmpInteractiveSegMask&&n.editorState.extraMasks.push(n.interactiveSegState.tmpInteractiveSegMask),n.interactiveSegState={...Zs.interactiveSegState}})},setIsInpainting:n=>e(r=>{r.isInpainting=n}),setFile:async n=>{if(t().settings.enableAutoExtractPrompt)try{const r=await Wj(n);r.prompt&&e(o=>{o.settings.prompt=r.prompt}),r.negative_prompt&&e(o=>{o.settings.negativePrompt=r.negative_prompt})}catch(r){rl({variant:"destructive",description:r.message?r.message:r.toString()})}e(r=>{r.file=n,r.interactiveSegState=Zs.interactiveSegState,r.editorState=Zs.editorState,r.cropperState=Zs.cropperState})},setCustomFile:n=>e(r=>{r.customMask=n}),setBaseBrushSize:n=>e(r=>{r.editorState.baseBrushSize=n}),setImageSize:(n,r)=>{e(o=>{o.imageWidth=n,o.imageHeight=r,o.editorState.brushSizeScale=Math.max(Math.min(n,r),512)/512}),t().resetExtender(n,r)},setCropperX:n=>e(r=>{r.cropperState.x=n}),setCropperY:n=>e(r=>{r.cropperState.y=n}),setCropperWidth:n=>e(r=>{r.cropperState.width=n}),setCropperHeight:n=>e(r=>{r.cropperState.height=n}),setExtenderX:n=>e(r=>{r.extenderState.x=n}),setExtenderY:n=>e(r=>{r.extenderState.y=n}),setExtenderWidth:n=>e(r=>{r.extenderState.width=n}),setExtenderHeight:n=>e(r=>{r.extenderState.height=n}),setIsCropperExtenderResizing:n=>e(r=>{r.isCropperExtenderResizing=n}),updateExtenderDirection:n=>{console.log(`updateExtenderDirection: ${JSON.stringify(t().extenderState)}`),e(r=>{r.settings.extenderDirection=n,r.extenderState.x=0,r.extenderState.y=0,r.extenderState.width=r.imageWidth,r.extenderState.height=r.imageHeight}),t().updateExtenderByBuiltIn(n,1.5)},updateExtenderByBuiltIn:(n,r)=>{const o={...Zs.extenderState};let{x:i,y:s,width:l,height:u}=o;const{imageWidth:d,imageHeight:h}=t();switch(l=d,u=h,n){case In.x:i=-Math.ceil(d*(r-1)/2),l=Math.ceil(d*r);break;case In.y:s=-Math.ceil(h*(r-1)/2),u=Math.ceil(h*r);break;case In.xy:i=-Math.ceil(d*(r-1)/2),s=-Math.ceil(h*(r-1)/2),l=Math.ceil(d*r),u=Math.ceil(h*r);break}e(m=>{m.extenderState.x=i,m.extenderState.y=s,m.extenderState.width=l,m.extenderState.height=u})},resetExtender:(n,r)=>{e(o=>{o.extenderState.x=0,o.extenderState.y=0,o.extenderState.width=n,o.extenderState.height=r})},setSeed:n=>e(r=>{r.settings.seed=n}),adjustMask:async n=>{const{imageWidth:r,imageHeight:o}=t(),{curLineGroup:i,extraMasks:s}=t().editorState,{adjustMaskKernelSize:l}=t().settings;if(i.length===0&&s.length===0)return;e(g=>{g.isAdjustingMask=!0});const u=Lp(r,o,[i],s,Ky),d=sC(u.toDataURL()),h=await Hj(d,n,l),m=await dF(h);e(g=>{g.editorState.extraMasks=[m],g.editorState.curLineGroup=[]}),e(g=>{g.isAdjustingMask=!1})},clearMask:()=>{e(n=>{n.editorState.extraMasks=[],n.editorState.curLineGroup=[]})}})),{name:"ZUSTAND_STATE",version:1,partialize:e=>Object.fromEntries(Object.entries(e).filter(([t])=>["fileManagerState","settings"].includes(t)))}),_z),Pd=f.forwardRef(({className:e,type:t,...n},r)=>{const o=bt(l=>l.updateAppState),i=()=>{o({disableShortCuts:!0})},s=()=>{o({disableShortCuts:!1})};return v.jsx("input",{type:t,className:Ce("flex h-8 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",e),ref:r,autoComplete:"off",tabIndex:-1,onFocus:i,onBlur:s,...n})});Pd.displayName="Input";const Gn=f.forwardRef(({numberValue:e,allowFloat:t,onNumberValueChange:n,...r},o)=>{const[i,s]=f.useState(e.toString());f.useEffect(()=>{i!==e.toString()+"."&&s(e.toString())},[e]);const l=u=>{let h=u.target.value;if(t){if(h=h.replace(/[^0-9.]/g,"").replace(/(\..*?)\..*/g,"$1"),h.length===0){n(0);return}n(parseFloat(h))}else{if(h=h.replace(/\D/g,""),h.length===0){n(0);return}n(parseInt(h,10))}s(h)};return v.jsx(Pd,{ref:o,value:i,onInput:l,...r})});function ue(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 fB(e,t){const n=f.createContext(t);function r(i){const{children:s,...l}=i,u=f.useMemo(()=>l,Object.values(l));return f.createElement(n.Provider,{value:u},s)}function o(i){const s=f.useContext(n);if(s)return s;if(t!==void 0)return t;throw new Error(`\`${i}\` must be used within \`${e}\``)}return r.displayName=e+"Provider",[r,o]}function An(e,t=[]){let n=[];function r(i,s){const l=f.createContext(s),u=n.length;n=[...n,s];function d(m){const{scope:g,children:y,...x}=m,_=(g==null?void 0:g[e][u])||l,C=f.useMemo(()=>x,Object.values(x));return f.createElement(_.Provider,{value:C},y)}function h(m,g){const y=(g==null?void 0:g[e][u])||l,x=f.useContext(y);if(x)return x;if(s!==void 0)return s;throw new Error(`\`${m}\` must be used within \`${i}\``)}return d.displayName=i+"Provider",[d,h]}const o=()=>{const i=n.map(s=>f.createContext(s));return function(l){const u=(l==null?void 0:l[e])||i;return f.useMemo(()=>({[`__scope${e}`]:{...l,[e]:u}}),[l,u])}};return o.scopeName=e,[r,pB(o,...t)]}function pB(...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(i){const s=r.reduce((l,{useScope:u,scopeName:d})=>{const m=u(i)[`__scope${d}`];return{...l,...m}},{});return f.useMemo(()=>({[`__scope${t.scopeName}`]:s}),[s])}};return n.scopeName=t.scopeName,n}const hB=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","span","svg","ul"],Pe=hB.reduce((e,t)=>{const n=f.forwardRef((r,o)=>{const{asChild:i,...s}=r,l=i?Wo:t;return f.useEffect(()=>{window[Symbol.for("radix-ui")]=!0},[]),f.createElement(l,Y({},s,{ref:o}))});return n.displayName=`Primitive.${t}`,{...e,[t]:n}},{});function cx(e,t){e&&Os.flushSync(()=>e.dispatchEvent(t))}function Ft(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)},[])}function mB(e,t=globalThis==null?void 0:globalThis.document){const n=Ft(e);f.useEffect(()=>{const r=o=>{o.key==="Escape"&&n(o)};return t.addEventListener("keydown",r),()=>t.removeEventListener("keydown",r)},[n,t])}const i1="dismissableLayer.update",gB="dismissableLayer.pointerDownOutside",vB="dismissableLayer.focusOutside";let AC;const TT=f.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),yc=f.forwardRef((e,t)=>{var n;const{disableOutsidePointerEvents:r=!1,onEscapeKeyDown:o,onPointerDownOutside:i,onFocusOutside:s,onInteractOutside:l,onDismiss:u,...d}=e,h=f.useContext(TT),[m,g]=f.useState(null),y=(n=m==null?void 0:m.ownerDocument)!==null&&n!==void 0?n:globalThis==null?void 0:globalThis.document,[,x]=f.useState({}),_=Be(t,O=>g(O)),C=Array.from(h.layers),[S]=[...h.layersWithOutsidePointerEventsDisabled].slice(-1),b=C.indexOf(S),E=m?C.indexOf(m):-1,k=h.layersWithOutsidePointerEventsDisabled.size>0,P=E>=b,M=wB(O=>{const F=O.target,V=[...h.branches].some(J=>J.contains(F));!P||V||(i==null||i(O),l==null||l(O),O.defaultPrevented||u==null||u())},y),A=xB(O=>{const F=O.target;[...h.branches].some(J=>J.contains(F))||(s==null||s(O),l==null||l(O),O.defaultPrevented||u==null||u())},y);return mB(O=>{E===h.layers.size-1&&(o==null||o(O),!O.defaultPrevented&&u&&(O.preventDefault(),u()))},y),f.useEffect(()=>{if(m)return r&&(h.layersWithOutsidePointerEventsDisabled.size===0&&(AC=y.body.style.pointerEvents,y.body.style.pointerEvents="none"),h.layersWithOutsidePointerEventsDisabled.add(m)),h.layers.add(m),OC(),()=>{r&&h.layersWithOutsidePointerEventsDisabled.size===1&&(y.body.style.pointerEvents=AC)}},[m,y,r,h]),f.useEffect(()=>()=>{m&&(h.layers.delete(m),h.layersWithOutsidePointerEventsDisabled.delete(m),OC())},[m,h]),f.useEffect(()=>{const O=()=>x({});return document.addEventListener(i1,O),()=>document.removeEventListener(i1,O)},[]),f.createElement(Pe.div,Y({},d,{ref:_,style:{pointerEvents:k?P?"auto":"none":void 0,...e.style},onFocusCapture:ue(e.onFocusCapture,A.onFocusCapture),onBlurCapture:ue(e.onBlurCapture,A.onBlurCapture),onPointerDownCapture:ue(e.onPointerDownCapture,M.onPointerDownCapture)}))}),yB=f.forwardRef((e,t)=>{const n=f.useContext(TT),r=f.useRef(null),o=Be(t,r);return f.useEffect(()=>{const i=r.current;if(i)return n.branches.add(i),()=>{n.branches.delete(i)}},[n.branches]),f.createElement(Pe.div,Y({},e,{ref:o}))});function wB(e,t=globalThis==null?void 0:globalThis.document){const n=Ft(e),r=f.useRef(!1),o=f.useRef(()=>{});return f.useEffect(()=>{const i=l=>{if(l.target&&!r.current){let h=function(){PT(gB,n,d,{discrete:!0})};var u=h;const d={originalEvent:l};l.pointerType==="touch"?(t.removeEventListener("click",o.current),o.current=h,t.addEventListener("click",o.current,{once:!0})):h()}else t.removeEventListener("click",o.current);r.current=!1},s=window.setTimeout(()=>{t.addEventListener("pointerdown",i)},0);return()=>{window.clearTimeout(s),t.removeEventListener("pointerdown",i),t.removeEventListener("click",o.current)}},[t,n]),{onPointerDownCapture:()=>r.current=!0}}function xB(e,t=globalThis==null?void 0:globalThis.document){const n=Ft(e),r=f.useRef(!1);return f.useEffect(()=>{const o=i=>{i.target&&!r.current&&PT(vB,n,{originalEvent:i},{discrete:!1})};return t.addEventListener("focusin",o),()=>t.removeEventListener("focusin",o)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function OC(){const e=new CustomEvent(i1);document.dispatchEvent(e)}function PT(e,t,n,{discrete:r}){const o=n.originalEvent.target,i=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&o.addEventListener(e,t,{once:!0}),r?cx(o,i):o.dispatchEvent(i)}const bB=yc,_B=yB,Pn=globalThis!=null&&globalThis.document?f.useLayoutEffect:()=>{},SB=jD.useId||(()=>{});let EB=0;function nr(e){const[t,n]=f.useState(SB());return Pn(()=>{e||n(r=>r??String(EB++))},[e]),e||(t?`radix-${t}`:"")}const CB=["top","right","bottom","left"],Cs=Math.min,pr=Math.max,Mh=Math.round,ip=Math.floor,$s=e=>({x:e,y:e}),$B={left:"right",right:"left",bottom:"top",top:"bottom"},kB={start:"end",end:"start"};function s1(e,t,n){return pr(e,Cs(t,n))}function yi(e,t){return typeof e=="function"?e(t):e}function wi(e){return e.split("-")[0]}function wc(e){return e.split("-")[1]}function ux(e){return e==="x"?"y":"x"}function dx(e){return e==="y"?"height":"width"}function xc(e){return["top","bottom"].includes(wi(e))?"y":"x"}function fx(e){return ux(xc(e))}function RB(e,t,n){n===void 0&&(n=!1);const r=wc(e),o=fx(e),i=dx(o);let s=o==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[i]>t.floating[i]&&(s=Nh(s)),[s,Nh(s)]}function TB(e){const t=Nh(e);return[a1(e),t,a1(t)]}function a1(e){return e.replace(/start|end/g,t=>kB[t])}function PB(e,t,n){const r=["left","right"],o=["right","left"],i=["top","bottom"],s=["bottom","top"];switch(e){case"top":case"bottom":return n?t?o:r:t?r:o;case"left":case"right":return t?i:s;default:return[]}}function AB(e,t,n,r){const o=wc(e);let i=PB(wi(e),n==="start",r);return o&&(i=i.map(s=>s+"-"+o),t&&(i=i.concat(i.map(a1)))),i}function Nh(e){return e.replace(/left|right|bottom|top/g,t=>$B[t])}function OB(e){return{top:0,right:0,bottom:0,left:0,...e}}function AT(e){return typeof e!="number"?OB(e):{top:e,right:e,bottom:e,left:e}}function Dh(e){return{...e,top:e.y,left:e.x,right:e.x+e.width,bottom:e.y+e.height}}function MC(e,t,n){let{reference:r,floating:o}=e;const i=xc(t),s=fx(t),l=dx(s),u=wi(t),d=i==="y",h=r.x+r.width/2-o.width/2,m=r.y+r.height/2-o.height/2,g=r[l]/2-o[l]/2;let y;switch(u){case"top":y={x:h,y:r.y-o.height};break;case"bottom":y={x:h,y:r.y+r.height};break;case"right":y={x:r.x+r.width,y:m};break;case"left":y={x:r.x-o.width,y:m};break;default:y={x:r.x,y:r.y}}switch(wc(t)){case"start":y[s]-=g*(n&&d?-1:1);break;case"end":y[s]+=g*(n&&d?-1:1);break}return y}const MB=async(e,t,n)=>{const{placement:r="bottom",strategy:o="absolute",middleware:i=[],platform:s}=n,l=i.filter(Boolean),u=await(s.isRTL==null?void 0:s.isRTL(t));let d=await s.getElementRects({reference:e,floating:t,strategy:o}),{x:h,y:m}=MC(d,r,u),g=r,y={},x=0;for(let _=0;_({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:o,rects:i,platform:s,elements:l,middlewareData:u}=t,{element:d,padding:h=0}=yi(e,t)||{};if(d==null)return{};const m=AT(h),g={x:n,y:r},y=fx(o),x=dx(y),_=await s.getDimensions(d),C=y==="y",S=C?"top":"left",b=C?"bottom":"right",E=C?"clientHeight":"clientWidth",k=i.reference[x]+i.reference[y]-g[y]-i.floating[x],P=g[y]-i.reference[y],M=await(s.getOffsetParent==null?void 0:s.getOffsetParent(d));let A=M?M[E]:0;(!A||!await(s.isElement==null?void 0:s.isElement(M)))&&(A=l.floating[E]||i.floating[x]);const O=k/2-P/2,F=A/2-_[x]/2-1,V=Cs(m[S],F),J=Cs(m[b],F),G=V,ae=A-_[x]-J,U=A/2-_[x]/2+O,te=s1(G,U,ae),L=!u.arrow&&wc(o)!=null&&U!=te&&i.reference[x]/2-(UG<=0)){var F,V;const G=(((F=i.flip)==null?void 0:F.index)||0)+1,ae=P[G];if(ae)return{data:{index:G,overflows:O},reset:{placement:ae}};let U=(V=O.filter(te=>te.overflows[0]<=0).sort((te,L)=>te.overflows[1]-L.overflows[1])[0])==null?void 0:V.placement;if(!U)switch(y){case"bestFit":{var J;const te=(J=O.map(L=>[L.placement,L.overflows.filter(ie=>ie>0).reduce((ie,K)=>ie+K,0)]).sort((L,ie)=>L[1]-ie[1])[0])==null?void 0:J[0];te&&(U=te);break}case"initialPlacement":U=l;break}if(o!==U)return{reset:{placement:U}}}return{}}}};function DC(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function IC(e){return CB.some(t=>e[t]>=0)}const DB=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n}=t,{strategy:r="referenceHidden",...o}=yi(e,t);switch(r){case"referenceHidden":{const i=await td(t,{...o,elementContext:"reference"}),s=DC(i,n.reference);return{data:{referenceHiddenOffsets:s,referenceHidden:IC(s)}}}case"escaped":{const i=await td(t,{...o,altBoundary:!0}),s=DC(i,n.floating);return{data:{escapedOffsets:s,escaped:IC(s)}}}default:return{}}}}};async function IB(e,t){const{placement:n,platform:r,elements:o}=e,i=await(r.isRTL==null?void 0:r.isRTL(o.floating)),s=wi(n),l=wc(n),u=xc(n)==="y",d=["left","top"].includes(s)?-1:1,h=i&&u?-1:1,m=yi(t,e);let{mainAxis:g,crossAxis:y,alignmentAxis:x}=typeof m=="number"?{mainAxis:m,crossAxis:0,alignmentAxis:null}:{mainAxis:0,crossAxis:0,alignmentAxis:null,...m};return l&&typeof x=="number"&&(y=l==="end"?x*-1:x),u?{x:y*h,y:g*d}:{x:g*d,y:y*h}}const LB=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){const{x:n,y:r}=t,o=await IB(t,e);return{x:n+o.x,y:r+o.y,data:o}}}},FB=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:o}=t,{mainAxis:i=!0,crossAxis:s=!1,limiter:l={fn:C=>{let{x:S,y:b}=C;return{x:S,y:b}}},...u}=yi(e,t),d={x:n,y:r},h=await td(t,u),m=xc(wi(o)),g=ux(m);let y=d[g],x=d[m];if(i){const C=g==="y"?"top":"left",S=g==="y"?"bottom":"right",b=y+h[C],E=y-h[S];y=s1(b,y,E)}if(s){const C=m==="y"?"top":"left",S=m==="y"?"bottom":"right",b=x+h[C],E=x-h[S];x=s1(b,x,E)}const _=l.fn({...t,[g]:y,[m]:x});return{..._,data:{x:_.x-n,y:_.y-r}}}}},jB=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:r,placement:o,rects:i,middlewareData:s}=t,{offset:l=0,mainAxis:u=!0,crossAxis:d=!0}=yi(e,t),h={x:n,y:r},m=xc(o),g=ux(m);let y=h[g],x=h[m];const _=yi(l,t),C=typeof _=="number"?{mainAxis:_,crossAxis:0}:{mainAxis:0,crossAxis:0,..._};if(u){const E=g==="y"?"height":"width",k=i.reference[g]-i.floating[E]+C.mainAxis,P=i.reference[g]+i.reference[E]-C.mainAxis;yP&&(y=P)}if(d){var S,b;const E=g==="y"?"width":"height",k=["top","left"].includes(wi(o)),P=i.reference[m]-i.floating[E]+(k&&((S=s.offset)==null?void 0:S[m])||0)+(k?0:C.crossAxis),M=i.reference[m]+i.reference[E]+(k?0:((b=s.offset)==null?void 0:b[m])||0)-(k?C.crossAxis:0);xM&&(x=M)}return{[g]:y,[m]:x}}}},zB=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){const{placement:n,rects:r,platform:o,elements:i}=t,{apply:s=()=>{},...l}=yi(e,t),u=await td(t,l),d=wi(n),h=wc(n),m=xc(n)==="y",{width:g,height:y}=r.floating;let x,_;d==="top"||d==="bottom"?(x=d,_=h===(await(o.isRTL==null?void 0:o.isRTL(i.floating))?"start":"end")?"left":"right"):(_=d,x=h==="end"?"top":"bottom");const C=y-u[x],S=g-u[_],b=!t.middlewareData.shift;let E=C,k=S;if(m){const M=g-u.left-u.right;k=h||b?Cs(S,M):M}else{const M=y-u.top-u.bottom;E=h||b?Cs(C,M):M}if(b&&!h){const M=pr(u.left,0),A=pr(u.right,0),O=pr(u.top,0),F=pr(u.bottom,0);m?k=g-2*(M!==0||A!==0?M+A:pr(u.left,u.right)):E=y-2*(O!==0||F!==0?O+F:pr(u.top,u.bottom))}await s({...t,availableWidth:k,availableHeight:E});const P=await o.getDimensions(i.floating);return g!==P.width||y!==P.height?{reset:{rects:!0}}:{}}}};function ks(e){return OT(e)?(e.nodeName||"").toLowerCase():"#document"}function vr(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Ci(e){var t;return(t=(OT(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function OT(e){return e instanceof Node||e instanceof vr(e).Node}function xi(e){return e instanceof Element||e instanceof vr(e).Element}function Ho(e){return e instanceof HTMLElement||e instanceof vr(e).HTMLElement}function LC(e){return typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof vr(e).ShadowRoot}function Ad(e){const{overflow:t,overflowX:n,overflowY:r,display:o}=Xr(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&!["inline","contents"].includes(o)}function BB(e){return["table","td","th"].includes(ks(e))}function px(e){const t=hx(),n=Xr(e);return n.transform!=="none"||n.perspective!=="none"||(n.containerType?n.containerType!=="normal":!1)||!t&&(n.backdropFilter?n.backdropFilter!=="none":!1)||!t&&(n.filter?n.filter!=="none":!1)||["transform","perspective","filter"].some(r=>(n.willChange||"").includes(r))||["paint","layout","strict","content"].some(r=>(n.contain||"").includes(r))}function UB(e){let t=rc(e);for(;Ho(t)&&!Fm(t);){if(px(t))return t;t=rc(t)}return null}function hx(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}function Fm(e){return["html","body","#document"].includes(ks(e))}function Xr(e){return vr(e).getComputedStyle(e)}function jm(e){return xi(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.pageXOffset,scrollTop:e.pageYOffset}}function rc(e){if(ks(e)==="html")return e;const t=e.assignedSlot||e.parentNode||LC(e)&&e.host||Ci(e);return LC(t)?t.host:t}function MT(e){const t=rc(e);return Fm(t)?e.ownerDocument?e.ownerDocument.body:e.body:Ho(t)&&Ad(t)?t:MT(t)}function nd(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const o=MT(e),i=o===((r=e.ownerDocument)==null?void 0:r.body),s=vr(o);return i?t.concat(s,s.visualViewport||[],Ad(o)?o:[],s.frameElement&&n?nd(s.frameElement):[]):t.concat(o,nd(o,[],n))}function NT(e){const t=Xr(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const o=Ho(e),i=o?e.offsetWidth:n,s=o?e.offsetHeight:r,l=Mh(n)!==i||Mh(r)!==s;return l&&(n=i,r=s),{width:n,height:r,$:l}}function mx(e){return xi(e)?e:e.contextElement}function Rl(e){const t=mx(e);if(!Ho(t))return $s(1);const n=t.getBoundingClientRect(),{width:r,height:o,$:i}=NT(t);let s=(i?Mh(n.width):n.width)/r,l=(i?Mh(n.height):n.height)/o;return(!s||!Number.isFinite(s))&&(s=1),(!l||!Number.isFinite(l))&&(l=1),{x:s,y:l}}const VB=$s(0);function DT(e){const t=vr(e);return!hx()||!t.visualViewport?VB:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function WB(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==vr(e)?!1:t}function Ra(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const o=e.getBoundingClientRect(),i=mx(e);let s=$s(1);t&&(r?xi(r)&&(s=Rl(r)):s=Rl(e));const l=WB(i,n,r)?DT(i):$s(0);let u=(o.left+l.x)/s.x,d=(o.top+l.y)/s.y,h=o.width/s.x,m=o.height/s.y;if(i){const g=vr(i),y=r&&xi(r)?vr(r):r;let x=g.frameElement;for(;x&&r&&y!==g;){const _=Rl(x),C=x.getBoundingClientRect(),S=Xr(x),b=C.left+(x.clientLeft+parseFloat(S.paddingLeft))*_.x,E=C.top+(x.clientTop+parseFloat(S.paddingTop))*_.y;u*=_.x,d*=_.y,h*=_.x,m*=_.y,u+=b,d+=E,x=vr(x).frameElement}}return Dh({width:h,height:m,x:u,y:d})}function HB(e){let{rect:t,offsetParent:n,strategy:r}=e;const o=Ho(n),i=Ci(n);if(n===i)return t;let s={scrollLeft:0,scrollTop:0},l=$s(1);const u=$s(0);if((o||!o&&r!=="fixed")&&((ks(n)!=="body"||Ad(i))&&(s=jm(n)),Ho(n))){const d=Ra(n);l=Rl(n),u.x=d.x+n.clientLeft,u.y=d.y+n.clientTop}return{width:t.width*l.x,height:t.height*l.y,x:t.x*l.x-s.scrollLeft*l.x+u.x,y:t.y*l.y-s.scrollTop*l.y+u.y}}function KB(e){return Array.from(e.getClientRects())}function IT(e){return Ra(Ci(e)).left+jm(e).scrollLeft}function YB(e){const t=Ci(e),n=jm(e),r=e.ownerDocument.body,o=pr(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),i=pr(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let s=-n.scrollLeft+IT(e);const l=-n.scrollTop;return Xr(r).direction==="rtl"&&(s+=pr(t.clientWidth,r.clientWidth)-o),{width:o,height:i,x:s,y:l}}function GB(e,t){const n=vr(e),r=Ci(e),o=n.visualViewport;let i=r.clientWidth,s=r.clientHeight,l=0,u=0;if(o){i=o.width,s=o.height;const d=hx();(!d||d&&t==="fixed")&&(l=o.offsetLeft,u=o.offsetTop)}return{width:i,height:s,x:l,y:u}}function XB(e,t){const n=Ra(e,!0,t==="fixed"),r=n.top+e.clientTop,o=n.left+e.clientLeft,i=Ho(e)?Rl(e):$s(1),s=e.clientWidth*i.x,l=e.clientHeight*i.y,u=o*i.x,d=r*i.y;return{width:s,height:l,x:u,y:d}}function FC(e,t,n){let r;if(t==="viewport")r=GB(e,n);else if(t==="document")r=YB(Ci(e));else if(xi(t))r=XB(t,n);else{const o=DT(e);r={...t,x:t.x-o.x,y:t.y-o.y}}return Dh(r)}function LT(e,t){const n=rc(e);return n===t||!xi(n)||Fm(n)?!1:Xr(n).position==="fixed"||LT(n,t)}function ZB(e,t){const n=t.get(e);if(n)return n;let r=nd(e,[],!1).filter(l=>xi(l)&&ks(l)!=="body"),o=null;const i=Xr(e).position==="fixed";let s=i?rc(e):e;for(;xi(s)&&!Fm(s);){const l=Xr(s),u=px(s);!u&&l.position==="fixed"&&(o=null),(i?!u&&!o:!u&&l.position==="static"&&!!o&&["absolute","fixed"].includes(o.position)||Ad(s)&&!u&<(e,s))?r=r.filter(h=>h!==s):o=l,s=rc(s)}return t.set(e,r),r}function qB(e){let{element:t,boundary:n,rootBoundary:r,strategy:o}=e;const s=[...n==="clippingAncestors"?ZB(t,this._c):[].concat(n),r],l=s[0],u=s.reduce((d,h)=>{const m=FC(t,h,o);return d.top=pr(m.top,d.top),d.right=Cs(m.right,d.right),d.bottom=Cs(m.bottom,d.bottom),d.left=pr(m.left,d.left),d},FC(t,l,o));return{width:u.right-u.left,height:u.bottom-u.top,x:u.left,y:u.top}}function QB(e){return NT(e)}function JB(e,t,n){const r=Ho(t),o=Ci(t),i=n==="fixed",s=Ra(e,!0,i,t);let l={scrollLeft:0,scrollTop:0};const u=$s(0);if(r||!r&&!i)if((ks(t)!=="body"||Ad(o))&&(l=jm(t)),r){const d=Ra(t,!0,i,t);u.x=d.x+t.clientLeft,u.y=d.y+t.clientTop}else o&&(u.x=IT(o));return{x:s.left+l.scrollLeft-u.x,y:s.top+l.scrollTop-u.y,width:s.width,height:s.height}}function jC(e,t){return!Ho(e)||Xr(e).position==="fixed"?null:t?t(e):e.offsetParent}function FT(e,t){const n=vr(e);if(!Ho(e))return n;let r=jC(e,t);for(;r&&BB(r)&&Xr(r).position==="static";)r=jC(r,t);return r&&(ks(r)==="html"||ks(r)==="body"&&Xr(r).position==="static"&&!px(r))?n:r||UB(e)||n}const eU=async function(e){let{reference:t,floating:n,strategy:r}=e;const o=this.getOffsetParent||FT,i=this.getDimensions;return{reference:JB(t,await o(n),r),floating:{x:0,y:0,...await i(n)}}};function tU(e){return Xr(e).direction==="rtl"}const nU={convertOffsetParentRelativeRectToViewportRelativeRect:HB,getDocumentElement:Ci,getClippingRect:qB,getOffsetParent:FT,getElementRects:eU,getClientRects:KB,getDimensions:QB,getScale:Rl,isElement:xi,isRTL:tU};function rU(e,t){let n=null,r;const o=Ci(e);function i(){clearTimeout(r),n&&n.disconnect(),n=null}function s(l,u){l===void 0&&(l=!1),u===void 0&&(u=1),i();const{left:d,top:h,width:m,height:g}=e.getBoundingClientRect();if(l||t(),!m||!g)return;const y=ip(h),x=ip(o.clientWidth-(d+m)),_=ip(o.clientHeight-(h+g)),C=ip(d),b={rootMargin:-y+"px "+-x+"px "+-_+"px "+-C+"px",threshold:pr(0,Cs(1,u))||1};let E=!0;function k(P){const M=P[0].intersectionRatio;if(M!==u){if(!E)return s();M?s(!1,M):r=setTimeout(()=>{s(!1,1e-7)},100)}E=!1}try{n=new IntersectionObserver(k,{...b,root:o.ownerDocument})}catch{n=new IntersectionObserver(k,b)}n.observe(e)}return s(!0),i}function oU(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:o=!0,ancestorResize:i=!0,elementResize:s=typeof ResizeObserver=="function",layoutShift:l=typeof IntersectionObserver=="function",animationFrame:u=!1}=r,d=mx(e),h=o||i?[...d?nd(d):[],...nd(t)]:[];h.forEach(S=>{o&&S.addEventListener("scroll",n,{passive:!0}),i&&S.addEventListener("resize",n)});const m=d&&l?rU(d,n):null;let g=-1,y=null;s&&(y=new ResizeObserver(S=>{let[b]=S;b&&b.target===d&&y&&(y.unobserve(t),cancelAnimationFrame(g),g=requestAnimationFrame(()=>{y&&y.observe(t)})),n()}),d&&!u&&y.observe(d),y.observe(t));let x,_=u?Ra(e):null;u&&C();function C(){const S=Ra(e);_&&(S.x!==_.x||S.y!==_.y||S.width!==_.width||S.height!==_.height)&&n(),_=S,x=requestAnimationFrame(C)}return n(),()=>{h.forEach(S=>{o&&S.removeEventListener("scroll",n),i&&S.removeEventListener("resize",n)}),m&&m(),y&&y.disconnect(),y=null,u&&cancelAnimationFrame(x)}}const iU=(e,t,n)=>{const r=new Map,o={platform:nU,...n},i={...o.platform,_c:r};return MB(e,t,{...o,platform:i})},sU=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:o}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?NC({element:r.current,padding:o}).fn(n):{}:r?NC({element:r,padding:o}).fn(n):{}}}};var Vp=typeof document<"u"?f.useLayoutEffect:f.useEffect;function Ih(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(!Ih(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(!{}.hasOwnProperty.call(t,o[r]))return!1;for(r=n;r--!==0;){const i=o[r];if(!(i==="_owner"&&e.$$typeof)&&!Ih(e[i],t[i]))return!1}return!0}return e!==e&&t!==t}function jT(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function zC(e,t){const n=jT(e);return Math.round(t*n)/n}function BC(e){const t=f.useRef(e);return Vp(()=>{t.current=e}),t}function aU(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:o,elements:{reference:i,floating:s}={},transform:l=!0,whileElementsMounted:u,open:d}=e,[h,m]=f.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[g,y]=f.useState(r);Ih(g,r)||y(r);const[x,_]=f.useState(null),[C,S]=f.useState(null),b=f.useCallback(L=>{L!=M.current&&(M.current=L,_(L))},[_]),E=f.useCallback(L=>{L!==A.current&&(A.current=L,S(L))},[S]),k=i||x,P=s||C,M=f.useRef(null),A=f.useRef(null),O=f.useRef(h),F=BC(u),V=BC(o),J=f.useCallback(()=>{if(!M.current||!A.current)return;const L={placement:t,strategy:n,middleware:g};V.current&&(L.platform=V.current),iU(M.current,A.current,L).then(ie=>{const K={...ie,isPositioned:!0};G.current&&!Ih(O.current,K)&&(O.current=K,Os.flushSync(()=>{m(K)}))})},[g,t,n,V]);Vp(()=>{d===!1&&O.current.isPositioned&&(O.current.isPositioned=!1,m(L=>({...L,isPositioned:!1})))},[d]);const G=f.useRef(!1);Vp(()=>(G.current=!0,()=>{G.current=!1}),[]),Vp(()=>{if(k&&(M.current=k),P&&(A.current=P),k&&P){if(F.current)return F.current(k,P,J);J()}},[k,P,J,F]);const ae=f.useMemo(()=>({reference:M,floating:A,setReference:b,setFloating:E}),[b,E]),U=f.useMemo(()=>({reference:k,floating:P}),[k,P]),te=f.useMemo(()=>{const L={position:n,left:0,top:0};if(!U.floating)return L;const ie=zC(U.floating,h.x),K=zC(U.floating,h.y);return l?{...L,transform:"translate("+ie+"px, "+K+"px)",...jT(U.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:ie,top:K}},[n,l,U.floating,h.x,h.y]);return f.useMemo(()=>({...h,update:J,refs:ae,elements:U,floatingStyles:te}),[h,J,ae,U,te])}function gx(e){const[t,n]=f.useState(void 0);return Pn(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(o=>{if(!Array.isArray(o)||!o.length)return;const i=o[0];let s,l;if("borderBoxSize"in i){const u=i.borderBoxSize,d=Array.isArray(u)?u[0]:u;s=d.inlineSize,l=d.blockSize}else s=e.offsetWidth,l=e.offsetHeight;n({width:s,height:l})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}const zT="Popper",[BT,Ns]=An(zT),[lU,UT]=BT(zT),cU=e=>{const{__scopePopper:t,children:n}=e,[r,o]=f.useState(null);return f.createElement(lU,{scope:t,anchor:r,onAnchorChange:o},n)},uU="PopperAnchor",dU=f.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...o}=e,i=UT(uU,n),s=f.useRef(null),l=Be(t,s);return f.useEffect(()=>{i.onAnchorChange((r==null?void 0:r.current)||s.current)}),r?null:f.createElement(Pe.div,Y({},o,{ref:l}))}),VT="PopperContent",[fU,hte]=BT(VT),pU=f.forwardRef((e,t)=>{var n,r,o,i,s,l,u,d;const{__scopePopper:h,side:m="bottom",sideOffset:g=0,align:y="center",alignOffset:x=0,arrowPadding:_=0,avoidCollisions:C=!0,collisionBoundary:S=[],collisionPadding:b=0,sticky:E="partial",hideWhenDetached:k=!1,updatePositionStrategy:P="optimized",onPlaced:M,...A}=e,O=UT(VT,h),[F,V]=f.useState(null),J=Be(t,Yt=>V(Yt)),[G,ae]=f.useState(null),U=gx(G),te=(n=U==null?void 0:U.width)!==null&&n!==void 0?n:0,L=(r=U==null?void 0:U.height)!==null&&r!==void 0?r:0,ie=m+(y!=="center"?"-"+y:""),K=typeof b=="number"?b:{top:0,right:0,bottom:0,left:0,...b},Q=Array.isArray(S)?S:[S],W=Q.length>0,le={padding:K,boundary:Q.filter(hU),altBoundary:W},{refs:ge,floatingStyles:Ve,placement:Ue,isPositioned:We,middlewareData:Me}=aU({strategy:"fixed",placement:ie,whileElementsMounted:(...Yt)=>oU(...Yt,{animationFrame:P==="always"}),elements:{reference:O.anchor},middleware:[LB({mainAxis:g+L,alignmentAxis:x}),C&&FB({mainAxis:!0,crossAxis:!1,limiter:E==="partial"?jB():void 0,...le}),C&&NB({...le}),zB({...le,apply:({elements:Yt,rects:Er,availableWidth:gt,availableHeight:js})=>{const{width:I,height:X}=Er.reference,Z=Yt.floating.style;Z.setProperty("--radix-popper-available-width",`${gt}px`),Z.setProperty("--radix-popper-available-height",`${js}px`),Z.setProperty("--radix-popper-anchor-width",`${I}px`),Z.setProperty("--radix-popper-anchor-height",`${X}px`)}}),G&&sU({element:G,padding:_}),mU({arrowWidth:te,arrowHeight:L}),k&&DB({strategy:"referenceHidden",...le})]}),[fe,xe]=WT(Ue),$e=Ft(M);Pn(()=>{We&&($e==null||$e())},[We,$e]);const Ae=(o=Me.arrow)===null||o===void 0?void 0:o.x,Oe=(i=Me.arrow)===null||i===void 0?void 0:i.y,je=((s=Me.arrow)===null||s===void 0?void 0:s.centerOffset)!==0,[Ot,ct]=f.useState();return Pn(()=>{F&&ct(window.getComputedStyle(F).zIndex)},[F]),f.createElement("div",{ref:ge.setFloating,"data-radix-popper-content-wrapper":"",style:{...Ve,transform:We?Ve.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:Ot,"--radix-popper-transform-origin":[(l=Me.transformOrigin)===null||l===void 0?void 0:l.x,(u=Me.transformOrigin)===null||u===void 0?void 0:u.y].join(" ")},dir:e.dir},f.createElement(fU,{scope:h,placedSide:fe,onArrowChange:ae,arrowX:Ae,arrowY:Oe,shouldHideArrow:je},f.createElement(Pe.div,Y({"data-side":fe,"data-align":xe},A,{ref:J,style:{...A.style,animation:We?void 0:"none",opacity:(d=Me.hide)!==null&&d!==void 0&&d.referenceHidden?0:void 0}}))))});function hU(e){return e!==null}const mU=e=>({name:"transformOrigin",options:e,fn(t){var n,r,o,i,s;const{placement:l,rects:u,middlewareData:d}=t,m=((n=d.arrow)===null||n===void 0?void 0:n.centerOffset)!==0,g=m?0:e.arrowWidth,y=m?0:e.arrowHeight,[x,_]=WT(l),C={start:"0%",center:"50%",end:"100%"}[_],S=((r=(o=d.arrow)===null||o===void 0?void 0:o.x)!==null&&r!==void 0?r:0)+g/2,b=((i=(s=d.arrow)===null||s===void 0?void 0:s.y)!==null&&i!==void 0?i:0)+y/2;let E="",k="";return x==="bottom"?(E=m?C:`${S}px`,k=`${-y}px`):x==="top"?(E=m?C:`${S}px`,k=`${u.floating.height+y}px`):x==="right"?(E=`${-y}px`,k=m?C:`${b}px`):x==="left"&&(E=`${u.floating.width+y}px`,k=m?C:`${b}px`),{data:{x:E,y:k}}}});function WT(e){const[t,n="center"]=e.split("-");return[t,n]}const Od=cU,zm=dU,Bm=pU,Md=f.forwardRef((e,t)=>{var n;const{container:r=globalThis==null||(n=globalThis.document)===null||n===void 0?void 0:n.body,...o}=e;return r?XI.createPortal(f.createElement(Pe.div,Y({},o,{ref:t})),r):null});function gU(e,t){return f.useReducer((n,r)=>{const o=t[n][r];return o??n},e)}const xn=e=>{const{present:t,children:n}=e,r=vU(t),o=typeof n=="function"?n({present:r.isPresent}):f.Children.only(n),i=Be(r.ref,o.ref);return typeof n=="function"||r.isPresent?f.cloneElement(o,{ref:i}):null};xn.displayName="Presence";function vU(e){const[t,n]=f.useState(),r=f.useRef({}),o=f.useRef(e),i=f.useRef("none"),s=e?"mounted":"unmounted",[l,u]=gU(s,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return f.useEffect(()=>{const d=sp(r.current);i.current=l==="mounted"?d:"none"},[l]),Pn(()=>{const d=r.current,h=o.current;if(h!==e){const g=i.current,y=sp(d);e?u("MOUNT"):y==="none"||(d==null?void 0:d.display)==="none"?u("UNMOUNT"):u(h&&g!==y?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,u]),Pn(()=>{if(t){const d=m=>{const y=sp(r.current).includes(m.animationName);m.target===t&&y&&Os.flushSync(()=>u("ANIMATION_END"))},h=m=>{m.target===t&&(i.current=sp(r.current))};return t.addEventListener("animationstart",h),t.addEventListener("animationcancel",d),t.addEventListener("animationend",d),()=>{t.removeEventListener("animationstart",h),t.removeEventListener("animationcancel",d),t.removeEventListener("animationend",d)}}else u("ANIMATION_END")},[t,u]),{isPresent:["mounted","unmountSuspended"].includes(l),ref:f.useCallback(d=>{d&&(r.current=getComputedStyle(d)),n(d)},[])}}function sp(e){return(e==null?void 0:e.animationName)||"none"}function Zr({prop:e,defaultProp:t,onChange:n=()=>{}}){const[r,o]=yU({defaultProp:t,onChange:n}),i=e!==void 0,s=i?e:r,l=Ft(n),u=f.useCallback(d=>{if(i){const m=typeof d=="function"?d(e):d;m!==e&&l(m)}else o(d)},[i,e,o,l]);return[s,u]}function yU({defaultProp:e,onChange:t}){const n=f.useState(e),[r]=n,o=f.useRef(r),i=Ft(t);return f.useEffect(()=>{o.current!==r&&(i(r),o.current=r)},[r,o,i]),n}const Um=f.forwardRef((e,t)=>f.createElement(Pe.span,Y({},e,{ref:t,style:{position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal",...e.style}}))),wU=Um,[Vm,mte]=An("Tooltip",[Ns]),vx=Ns(),xU="TooltipProvider",bU=700,l1="tooltip.open",[_U,yx]=Vm(xU),SU=e=>{const{__scopeTooltip:t,delayDuration:n=bU,skipDelayDuration:r=300,disableHoverableContent:o=!1,children:i}=e,[s,l]=f.useState(!0),u=f.useRef(!1),d=f.useRef(0);return f.useEffect(()=>{const h=d.current;return()=>window.clearTimeout(h)},[]),f.createElement(_U,{scope:t,isOpenDelayed:s,delayDuration:n,onOpen:f.useCallback(()=>{window.clearTimeout(d.current),l(!1)},[]),onClose:f.useCallback(()=>{window.clearTimeout(d.current),d.current=window.setTimeout(()=>l(!0),r)},[r]),isPointerInTransitRef:u,onPointerInTransitChange:f.useCallback(h=>{u.current=h},[]),disableHoverableContent:o},i)},wx="Tooltip",[EU,Wm]=Vm(wx),CU=e=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:o=!1,onOpenChange:i,disableHoverableContent:s,delayDuration:l}=e,u=yx(wx,e.__scopeTooltip),d=vx(t),[h,m]=f.useState(null),g=nr(),y=f.useRef(0),x=s??u.disableHoverableContent,_=l??u.delayDuration,C=f.useRef(!1),[S=!1,b]=Zr({prop:r,defaultProp:o,onChange:A=>{A?(u.onOpen(),document.dispatchEvent(new CustomEvent(l1))):u.onClose(),i==null||i(A)}}),E=f.useMemo(()=>S?C.current?"delayed-open":"instant-open":"closed",[S]),k=f.useCallback(()=>{window.clearTimeout(y.current),C.current=!1,b(!0)},[b]),P=f.useCallback(()=>{window.clearTimeout(y.current),b(!1)},[b]),M=f.useCallback(()=>{window.clearTimeout(y.current),y.current=window.setTimeout(()=>{C.current=!0,b(!0)},_)},[_,b]);return f.useEffect(()=>()=>window.clearTimeout(y.current),[]),f.createElement(Od,d,f.createElement(EU,{scope:t,contentId:g,open:S,stateAttribute:E,trigger:h,onTriggerChange:m,onTriggerEnter:f.useCallback(()=>{u.isOpenDelayed?M():k()},[u.isOpenDelayed,M,k]),onTriggerLeave:f.useCallback(()=>{x?P():window.clearTimeout(y.current)},[P,x]),onOpen:k,onClose:P,disableHoverableContent:x},n))},UC="TooltipTrigger",$U=f.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,o=Wm(UC,n),i=yx(UC,n),s=vx(n),l=f.useRef(null),u=Be(t,l,o.onTriggerChange),d=f.useRef(!1),h=f.useRef(!1),m=f.useCallback(()=>d.current=!1,[]);return f.useEffect(()=>()=>document.removeEventListener("pointerup",m),[m]),f.createElement(zm,Y({asChild:!0},s),f.createElement(Pe.button,Y({"aria-describedby":o.open?o.contentId:void 0,"data-state":o.stateAttribute},r,{ref:u,onPointerMove:ue(e.onPointerMove,g=>{g.pointerType!=="touch"&&!h.current&&!i.isPointerInTransitRef.current&&(o.onTriggerEnter(),h.current=!0)}),onPointerLeave:ue(e.onPointerLeave,()=>{o.onTriggerLeave(),h.current=!1}),onPointerDown:ue(e.onPointerDown,()=>{d.current=!0,document.addEventListener("pointerup",m,{once:!0})}),onFocus:ue(e.onFocus,()=>{d.current||o.onOpen()}),onBlur:ue(e.onBlur,o.onClose),onClick:ue(e.onClick,o.onClose)})))}),kU="TooltipPortal",[gte,RU]=Vm(kU,{forceMount:void 0}),rd="TooltipContent",TU=f.forwardRef((e,t)=>{const n=RU(rd,e.__scopeTooltip),{forceMount:r=n.forceMount,side:o="top",...i}=e,s=Wm(rd,e.__scopeTooltip);return f.createElement(xn,{present:r||s.open},s.disableHoverableContent?f.createElement(HT,Y({side:o},i,{ref:t})):f.createElement(PU,Y({side:o},i,{ref:t})))}),PU=f.forwardRef((e,t)=>{const n=Wm(rd,e.__scopeTooltip),r=yx(rd,e.__scopeTooltip),o=f.useRef(null),i=Be(t,o),[s,l]=f.useState(null),{trigger:u,onClose:d}=n,h=o.current,{onPointerInTransitChange:m}=r,g=f.useCallback(()=>{l(null),m(!1)},[m]),y=f.useCallback((x,_)=>{const C=x.currentTarget,S={x:x.clientX,y:x.clientY},b=OU(S,C.getBoundingClientRect()),E=MU(S,b),k=NU(_.getBoundingClientRect()),P=IU([...E,...k]);l(P),m(!0)},[m]);return f.useEffect(()=>()=>g(),[g]),f.useEffect(()=>{if(u&&h){const x=C=>y(C,h),_=C=>y(C,u);return u.addEventListener("pointerleave",x),h.addEventListener("pointerleave",_),()=>{u.removeEventListener("pointerleave",x),h.removeEventListener("pointerleave",_)}}},[u,h,y,g]),f.useEffect(()=>{if(s){const x=_=>{const C=_.target,S={x:_.clientX,y:_.clientY},b=(u==null?void 0:u.contains(C))||(h==null?void 0:h.contains(C)),E=!DU(S,s);b?g():E&&(g(),d())};return document.addEventListener("pointermove",x),()=>document.removeEventListener("pointermove",x)}},[u,h,s,d,g]),f.createElement(HT,Y({},e,{ref:i}))}),[AU,vte]=Vm(wx,{isInside:!1}),HT=f.forwardRef((e,t)=>{const{__scopeTooltip:n,children:r,"aria-label":o,onEscapeKeyDown:i,onPointerDownOutside:s,...l}=e,u=Wm(rd,n),d=vx(n),{onClose:h}=u;return f.useEffect(()=>(document.addEventListener(l1,h),()=>document.removeEventListener(l1,h)),[h]),f.useEffect(()=>{if(u.trigger){const m=g=>{const y=g.target;y!=null&&y.contains(u.trigger)&&h()};return window.addEventListener("scroll",m,{capture:!0}),()=>window.removeEventListener("scroll",m,{capture:!0})}},[u.trigger,h]),f.createElement(yc,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:i,onPointerDownOutside:s,onFocusOutside:m=>m.preventDefault(),onDismiss:h},f.createElement(Bm,Y({"data-state":u.stateAttribute},d,l,{ref:t,style:{...l.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"}}),f.createElement(sx,null,r),f.createElement(AU,{scope:n,isInside:!0},f.createElement(wU,{id:u.contentId,role:"tooltip"},o||r))))});function OU(e,t){const n=Math.abs(t.top-e.y),r=Math.abs(t.bottom-e.y),o=Math.abs(t.right-e.x),i=Math.abs(t.left-e.x);switch(Math.min(n,r,o,i)){case i:return"left";case o:return"right";case n:return"top";case r:return"bottom";default:throw new Error("unreachable")}}function MU(e,t,n=5){const r=[];switch(t){case"top":r.push({x:e.x-n,y:e.y+n},{x:e.x+n,y:e.y+n});break;case"bottom":r.push({x:e.x-n,y:e.y-n},{x:e.x+n,y:e.y-n});break;case"left":r.push({x:e.x+n,y:e.y-n},{x:e.x+n,y:e.y+n});break;case"right":r.push({x:e.x-n,y:e.y-n},{x:e.x-n,y:e.y+n});break}return r}function NU(e){const{top:t,right:n,bottom:r,left:o}=e;return[{x:o,y:t},{x:n,y:t},{x:n,y:r},{x:o,y:r}]}function DU(e,t){const{x:n,y:r}=e;let o=!1;for(let i=0,s=t.length-1;ir!=h>r&&n<(d-l)*(r-u)/(h-u)+l&&(o=!o)}return o}function IU(e){const t=e.slice();return t.sort((n,r)=>n.xr.x?1:n.yr.y?1:0),LU(t)}function LU(e){if(e.length<=1)return e.slice();const t=[];for(let r=0;r=2;){const i=t[t.length-1],s=t[t.length-2];if((i.x-s.x)*(o.y-s.y)>=(i.y-s.y)*(o.x-s.x))t.pop();else break}t.push(o)}t.pop();const n=[];for(let r=e.length-1;r>=0;r--){const o=e[r];for(;n.length>=2;){const i=n[n.length-1],s=n[n.length-2];if((i.x-s.x)*(o.y-s.y)>=(i.y-s.y)*(o.x-s.x))n.pop();else break}n.push(o)}return n.pop(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}const FU=SU,jU=CU,zU=$U,KT=TU,BU=FU,YT=jU,GT=zU,xx=f.forwardRef(({className:e,sideOffset:t=4,...n},r)=>v.jsx(KT,{ref:r,sideOffset:t,className:Ce("z-50 border overflow-hidden rounded-md bg-background text-foreground px-3 py-1.5 text-xs animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...n}));xx.displayName=KT.displayName;const bx=Om("inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50",{variants:{variant:{default:"bg-primary text-primary-foreground shadow hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",outline:"border border-input bg-transparent shadow-sm hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2",sm:"h-8 rounded-md px-3 text-xs",lg:"h-10 rounded-md px-8",icon:"h-9 w-9"}},defaultVariants:{variant:"default",size:"default"}}),Rn=f.forwardRef(({className:e,variant:t,size:n,asChild:r=!1,...o},i)=>{const s=r?Wo:"button";return v.jsx(s,{className:Ce(bx({variant:t,size:n,className:e}),"outline-none cursor-default"),ref:i,tabIndex:-1,...o})});Rn.displayName="Button";const vn=f.forwardRef(({tooltip:e,children:t,...n},r)=>v.jsxs(YT,{children:[v.jsx(GT,{asChild:!0,children:v.jsx(Rn,{variant:"ghost",size:"icon",...n,ref:r,tabIndex:-1,className:"cursor-default bg-background",children:v.jsx("div",{className:"icon-button-icon-wrapper",children:t})})}),v.jsx(xx,{children:v.jsx("p",{children:e})})]})),c1=e=>{const{onFileUpload:t,children:n,...r}=e,[o]=f.useState(`file-upload-${Math.random().toString()}`),i=s=>{var u;const l=(u=s.currentTarget.files)==null?void 0:u[0];l&&t(l)};return v.jsxs(v.Fragment,{children:[v.jsx("label",{htmlFor:o,children:v.jsx(vn,{...r,asChild:!0,children:n})}),v.jsx(Pd,{style:{display:"none"},id:o,name:o,type:"file",onChange:i,accept:"image/png, image/jpeg"})]})};var UU={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const VU=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Kt=(e,t)=>{const n=f.forwardRef(({color:r="currentColor",size:o=24,strokeWidth:i=2,absoluteStrokeWidth:s,children:l,...u},d)=>f.createElement("svg",{ref:d,...UU,width:o,height:o,stroke:r,strokeWidth:s?Number(i)*24/Number(o):i,className:`lucide lucide-${VU(e)}`,...u},[...t.map(([h,m])=>f.createElement(h,m)),...(Array.isArray(l)?l:[l])||[]]));return n.displayName=`${e}`,n},WU=Kt("Blocks",[["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["path",{d:"M10 21V8a1 1 0 0 0-1-1H4a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-5a1 1 0 0 0-1-1H3",key:"1fpvtg"}]]),HU=Kt("ChevronLeft",[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]]),KU=Kt("ChevronRight",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]),YU=Kt("Coffee",[["path",{d:"M17 8h1a4 4 0 1 1 0 8h-1",key:"jx4kbh"}],["path",{d:"M3 8h14v9a4 4 0 0 1-4 4H7a4 4 0 0 1-4-4Z",key:"1bxrl0"}],["line",{x1:"6",x2:"6",y1:"2",y2:"4",key:"1cr9l3"}],["line",{x1:"10",x2:"10",y1:"2",y2:"4",key:"170wym"}],["line",{x1:"14",x2:"14",y1:"2",y2:"4",key:"1c5f70"}]]),GU=Kt("Download",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"7 10 12 15 17 10",key:"2ggqvy"}],["line",{x1:"12",x2:"12",y1:"15",y2:"3",key:"1vk2je"}]]),XU=Kt("Eraser",[["path",{d:"m7 21-4.3-4.3c-1-1-1-2.5 0-3.4l9.6-9.6c1-1 2.5-1 3.4 0l5.6 5.6c1 1 1 2.5 0 3.4L13 21",key:"182aya"}],["path",{d:"M22 21H7",key:"t4ddhn"}],["path",{d:"m5 11 9 9",key:"1mo9qw"}]]),ZU=Kt("Expand",[["path",{d:"m21 21-6-6m6 6v-4.8m0 4.8h-4.8",key:"1c15vz"}],["path",{d:"M3 16.2V21m0 0h4.8M3 21l6-6",key:"1fsnz2"}],["path",{d:"M21 7.8V3m0 0h-4.8M21 3l-6 6",key:"hawz9i"}],["path",{d:"M3 7.8V3m0 0h4.8M3 3l6 6",key:"u9ee12"}]]),qU=Kt("Eye",[["path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z",key:"rwhkz3"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]),QU=Kt("FolderClosed",[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}],["path",{d:"M2 10h20",key:"1ir3d8"}]]),XT=Kt("Fullscreen",[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}],["rect",{width:"10",height:"8",x:"7",y:"8",rx:"1",key:"vys8me"}]]),JU=Kt("Image",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]]),eV=Kt("Keyboard",[["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",ry:"2",key:"15u882"}],["path",{d:"M6 8h.001",key:"1ej0i3"}],["path",{d:"M10 8h.001",key:"1x2st2"}],["path",{d:"M14 8h.001",key:"1vkmyp"}],["path",{d:"M18 8h.001",key:"kfsenl"}],["path",{d:"M8 12h.001",key:"1sjpby"}],["path",{d:"M12 12h.001",key:"al75ts"}],["path",{d:"M16 12h.001",key:"931bgk"}],["path",{d:"M7 16h10",key:"wp8him"}]]),tV=Kt("Minus",[["path",{d:"M5 12h14",key:"1ays0h"}]]),nV=Kt("MousePointerClick",[["path",{d:"m9 9 5 12 1.8-5.2L21 14Z",key:"1b76lo"}],["path",{d:"M7.2 2.2 8 5.1",key:"1cfko1"}],["path",{d:"m5.1 8-2.9-.8",key:"1go3kf"}],["path",{d:"M14 4.1 12 6",key:"ita8i4"}],["path",{d:"m6 12-1.9 2",key:"mnht97"}]]),rV=Kt("Plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]),oV=Kt("Redo",[["path",{d:"M21 7v6h-6",key:"3ptur4"}],["path",{d:"M3 17a9 9 0 0 1 9-9 9 9 0 0 1 6 2.3l3 2.7",key:"1kgawr"}]]),iV=Kt("RotateCw",[["path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8",key:"1p45f6"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}]]),sV=Kt("Settings",[["path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z",key:"1qme2f"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]),VC=Kt("Slice",[["path",{d:"m8 14-6 6h9v-3",key:"zo3j9a"}],["path",{d:"M18.37 3.63 8 14l3 3L21.37 6.63a2.12 2.12 0 1 0-3-3Z",key:"1dzx0j"}]]),WC=Kt("Smile",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 14s1.5 2 4 2 4-2 4-2",key:"1y1vjs"}],["line",{x1:"9",x2:"9.01",y1:"9",y2:"9",key:"yxxnd0"}],["line",{x1:"15",x2:"15.01",y1:"9",y2:"9",key:"1p4y9e"}]]),aV=Kt("Undo",[["path",{d:"M3 7v6h6",key:"1v2h90"}],["path",{d:"M21 17a9 9 0 0 0-9-9 9 9 0 0 0-6 2.3L3 13",key:"1r6uu6"}]]),ZT=Kt("Upload",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"17 8 12 3 7 8",key:"t8dd8p"}],["line",{x1:"12",x2:"12",y1:"3",y2:"15",key:"widbto"}]]);function lV(e,t){const[n,r]=f.useState(e);return f.useEffect(()=>{const o=setTimeout(()=>{r(e)},t);return()=>{clearTimeout(o)}},[e,t]),n}function u1(e){const[t,n]=f.useState(()=>typeof e=="boolean"?e:!!e),r=f.useCallback(o=>n(typeof o=="boolean"?o:i=>!i),[]);return[t,r]}const w0="focusScope.autoFocusOnMount",x0="focusScope.autoFocusOnUnmount",HC={bubbles:!1,cancelable:!0},Hm=f.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:o,onUnmountAutoFocus:i,...s}=e,[l,u]=f.useState(null),d=Ft(o),h=Ft(i),m=f.useRef(null),g=Be(t,_=>u(_)),y=f.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;f.useEffect(()=>{if(r){let b=function(M){if(y.paused||!l)return;const A=M.target;l.contains(A)?m.current=A:Hi(m.current,{select:!0})},E=function(M){if(y.paused||!l)return;const A=M.relatedTarget;A!==null&&(l.contains(A)||Hi(m.current,{select:!0}))},k=function(M){if(document.activeElement===document.body)for(const O of M)O.removedNodes.length>0&&Hi(l)};var _=b,C=E,S=k;document.addEventListener("focusin",b),document.addEventListener("focusout",E);const P=new MutationObserver(k);return l&&P.observe(l,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",b),document.removeEventListener("focusout",E),P.disconnect()}}},[r,l,y.paused]),f.useEffect(()=>{if(l){YC.add(y);const _=document.activeElement;if(!l.contains(_)){const S=new CustomEvent(w0,HC);l.addEventListener(w0,d),l.dispatchEvent(S),S.defaultPrevented||(cV(hV(qT(l)),{select:!0}),document.activeElement===_&&Hi(l))}return()=>{l.removeEventListener(w0,d),setTimeout(()=>{const S=new CustomEvent(x0,HC);l.addEventListener(x0,h),l.dispatchEvent(S),S.defaultPrevented||Hi(_??document.body,{select:!0}),l.removeEventListener(x0,h),YC.remove(y)},0)}}},[l,d,h,y]);const x=f.useCallback(_=>{if(!n&&!r||y.paused)return;const C=_.key==="Tab"&&!_.altKey&&!_.ctrlKey&&!_.metaKey,S=document.activeElement;if(C&&S){const b=_.currentTarget,[E,k]=uV(b);E&&k?!_.shiftKey&&S===k?(_.preventDefault(),n&&Hi(E,{select:!0})):_.shiftKey&&S===E&&(_.preventDefault(),n&&Hi(k,{select:!0})):S===b&&_.preventDefault()}},[n,r,y.paused]);return f.createElement(Pe.div,Y({tabIndex:-1},s,{ref:g,onKeyDown:x}))});function cV(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(Hi(r,{select:t}),document.activeElement!==n)return}function uV(e){const t=qT(e),n=KC(t,e),r=KC(t.reverse(),e);return[n,r]}function qT(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const o=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||o?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function KC(e,t){for(const n of e)if(!dV(n,{upTo:t}))return n}function dV(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function fV(e){return e instanceof HTMLInputElement&&"select"in e}function Hi(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&fV(e)&&t&&e.select()}}const YC=pV();function pV(){let e=[];return{add(t){const n=e[0];t!==n&&(n==null||n.pause()),e=GC(e,t),e.unshift(t)},remove(t){var n;e=GC(e,t),(n=e[0])===null||n===void 0||n.resume()}}}function GC(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function hV(e){return e.filter(t=>t.tagName!=="A")}let b0=0;function Km(){f.useEffect(()=>{var e,t;const n=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",(e=n[0])!==null&&e!==void 0?e:XC()),document.body.insertAdjacentElement("beforeend",(t=n[1])!==null&&t!==void 0?t:XC()),b0++,()=>{b0===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(r=>r.remove()),b0--}},[])}function XC(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.cssText="outline: none; opacity: 0; position: fixed; pointer-events: none",e}var Mo=function(){return Mo=Object.assign||function(t){for(var n,r=1,o=arguments.length;r"u")return AV;var t=OV(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])}},NV=tP(),DV=function(e,t,n,r){var o=e.left,i=e.top,s=e.right,l=e.gap;return n===void 0&&(n="margin"),` + .`.concat(gV,` { + overflow: hidden `).concat(r,`; + padding-right: `).concat(l,"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(i,`px; + padding-right: `).concat(s,`px; + margin-left:0; + margin-top:0; + margin-right: `).concat(l,"px ").concat(r,`; + `),n==="padding"&&"padding-right: ".concat(l,"px ").concat(r,";")].filter(Boolean).join(""),` + } + + .`).concat(Wp,` { + right: `).concat(l,"px ").concat(r,`; + } + + .`).concat(Hp,` { + margin-right: `).concat(l,"px ").concat(r,`; + } + + .`).concat(Wp," .").concat(Wp,` { + right: 0 `).concat(r,`; + } + + .`).concat(Hp," .").concat(Hp,` { + margin-right: 0 `).concat(r,`; + } + + body { + `).concat(vV,": ").concat(l,`px; + } +`)},IV=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,o=r===void 0?"margin":r,i=f.useMemo(function(){return MV(o)},[o]);return f.createElement(NV,{styles:DV(i,!t,o,n?"":"!important")})},d1=!1;if(typeof window<"u")try{var ap=Object.defineProperty({},"passive",{get:function(){return d1=!0,!0}});window.addEventListener("test",ap,ap),window.removeEventListener("test",ap,ap)}catch{d1=!1}var qa=d1?{passive:!1}:!1,LV=function(e){return e.tagName==="TEXTAREA"},nP=function(e,t){var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!LV(e)&&n[t]==="visible")},FV=function(e){return nP(e,"overflowY")},jV=function(e){return nP(e,"overflowX")},qC=function(e,t){var n=t;do{typeof ShadowRoot<"u"&&n instanceof ShadowRoot&&(n=n.host);var r=rP(e,n);if(r){var o=oP(e,n),i=o[1],s=o[2];if(i>s)return!0}n=n.parentNode}while(n&&n!==document.body);return!1},zV=function(e){var t=e.scrollTop,n=e.scrollHeight,r=e.clientHeight;return[t,n,r]},BV=function(e){var t=e.scrollLeft,n=e.scrollWidth,r=e.clientWidth;return[t,n,r]},rP=function(e,t){return e==="v"?FV(t):jV(t)},oP=function(e,t){return e==="v"?zV(t):BV(t)},UV=function(e,t){return e==="h"&&t==="rtl"?-1:1},VV=function(e,t,n,r,o){var i=UV(e,window.getComputedStyle(t).direction),s=i*r,l=n.target,u=t.contains(l),d=!1,h=s>0,m=0,g=0;do{var y=oP(e,l),x=y[0],_=y[1],C=y[2],S=_-C-i*x;(x||S)&&rP(e,l)&&(m+=S,g+=x),l=l.parentNode}while(!u&&l!==document.body||u&&(t.contains(l)||t===l));return(h&&(o&&m===0||!o&&s>m)||!h&&(o&&g===0||!o&&-s>g))&&(d=!0),d},lp=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},QC=function(e){return[e.deltaX,e.deltaY]},JC=function(e){return e&&"current"in e?e.current:e},WV=function(e,t){return e[0]===t[0]&&e[1]===t[1]},HV=function(e){return` + .block-interactivity-`.concat(e,` {pointer-events: none;} + .allow-interactivity-`).concat(e,` {pointer-events: all;} +`)},KV=0,Qa=[];function YV(e){var t=f.useRef([]),n=f.useRef([0,0]),r=f.useRef(),o=f.useState(KV++)[0],i=f.useState(function(){return tP()})[0],s=f.useRef(e);f.useEffect(function(){s.current=e},[e]),f.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(o));var _=mV([e.lockRef.current],(e.shards||[]).map(JC),!0).filter(Boolean);return _.forEach(function(C){return C.classList.add("allow-interactivity-".concat(o))}),function(){document.body.classList.remove("block-interactivity-".concat(o)),_.forEach(function(C){return C.classList.remove("allow-interactivity-".concat(o))})}}},[e.inert,e.lockRef.current,e.shards]);var l=f.useCallback(function(_,C){if("touches"in _&&_.touches.length===2)return!s.current.allowPinchZoom;var S=lp(_),b=n.current,E="deltaX"in _?_.deltaX:b[0]-S[0],k="deltaY"in _?_.deltaY:b[1]-S[1],P,M=_.target,A=Math.abs(E)>Math.abs(k)?"h":"v";if("touches"in _&&A==="h"&&M.type==="range")return!1;var O=qC(A,M);if(!O)return!0;if(O?P=A:(P=A==="v"?"h":"v",O=qC(A,M)),!O)return!1;if(!r.current&&"changedTouches"in _&&(E||k)&&(r.current=P),!P)return!0;var F=r.current||P;return VV(F,C,_,F==="h"?E:k,!0)},[]),u=f.useCallback(function(_){var C=_;if(!(!Qa.length||Qa[Qa.length-1]!==i)){var S="deltaY"in C?QC(C):lp(C),b=t.current.filter(function(P){return P.name===C.type&&P.target===C.target&&WV(P.delta,S)})[0];if(b&&b.should){C.cancelable&&C.preventDefault();return}if(!b){var E=(s.current.shards||[]).map(JC).filter(Boolean).filter(function(P){return P.contains(C.target)}),k=E.length>0?l(C,E[0]):!s.current.noIsolation;k&&C.cancelable&&C.preventDefault()}}},[]),d=f.useCallback(function(_,C,S,b){var E={name:_,delta:C,target:S,should:b};t.current.push(E),setTimeout(function(){t.current=t.current.filter(function(k){return k!==E})},1)},[]),h=f.useCallback(function(_){n.current=lp(_),r.current=void 0},[]),m=f.useCallback(function(_){d(_.type,QC(_),_.target,l(_,e.lockRef.current))},[]),g=f.useCallback(function(_){d(_.type,lp(_),_.target,l(_,e.lockRef.current))},[]);f.useEffect(function(){return Qa.push(i),e.setCallbacks({onScrollCapture:m,onWheelCapture:m,onTouchMoveCapture:g}),document.addEventListener("wheel",u,qa),document.addEventListener("touchmove",u,qa),document.addEventListener("touchstart",h,qa),function(){Qa=Qa.filter(function(_){return _!==i}),document.removeEventListener("wheel",u,qa),document.removeEventListener("touchmove",u,qa),document.removeEventListener("touchstart",h,qa)}},[]);var y=e.removeScrollBar,x=e.inert;return f.createElement(f.Fragment,null,x?f.createElement(i,{styles:HV(o)}):null,y?f.createElement(IV,{gapMode:"margin"}):null)}const GV=EV(eP,YV);var iP=f.forwardRef(function(e,t){return f.createElement(Ym,Mo({},e,{ref:t,sideCar:GV}))});iP.classNames=Ym.classNames;const Gm=iP;var XV=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},Ja=new WeakMap,cp=new WeakMap,up={},E0=0,sP=function(e){return e&&(e.host||sP(e.parentNode))},ZV=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=sP(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})},qV=function(e,t,n,r){var o=ZV(t,Array.isArray(e)?e:[e]);up[n]||(up[n]=new WeakMap);var i=up[n],s=[],l=new Set,u=new Set(o),d=function(m){!m||l.has(m)||(l.add(m),d(m.parentNode))};o.forEach(d);var h=function(m){!m||u.has(m)||Array.prototype.forEach.call(m.children,function(g){if(l.has(g))h(g);else{var y=g.getAttribute(r),x=y!==null&&y!=="false",_=(Ja.get(g)||0)+1,C=(i.get(g)||0)+1;Ja.set(g,_),i.set(g,C),s.push(g),_===1&&x&&cp.set(g,!0),C===1&&g.setAttribute(n,"true"),x||g.setAttribute(r,"true")}})};return h(t),l.clear(),E0++,function(){s.forEach(function(m){var g=Ja.get(m)-1,y=i.get(m)-1;Ja.set(m,g),i.set(m,y),g||(cp.has(m)||m.removeAttribute(r),cp.delete(m)),y||m.removeAttribute(n)}),E0--,E0||(Ja=new WeakMap,Ja=new WeakMap,cp=new WeakMap,up={})}},Xm=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),o=t||XV(e);return o?(r.push.apply(r,Array.from(o.querySelectorAll("[aria-live]"))),qV(r,o,n,"aria-hidden")):function(){return null}};const aP="Dialog",[lP,cP]=An(aP),[QV,bo]=lP(aP),JV=e=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:o,onOpenChange:i,modal:s=!0}=e,l=f.useRef(null),u=f.useRef(null),[d=!1,h]=Zr({prop:r,defaultProp:o,onChange:i});return f.createElement(QV,{scope:t,triggerRef:l,contentRef:u,contentId:nr(),titleId:nr(),descriptionId:nr(),open:d,onOpenChange:h,onOpenToggle:f.useCallback(()=>h(m=>!m),[h]),modal:s},n)},eW="DialogTrigger",uP=f.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=bo(eW,n),i=Be(t,o.triggerRef);return f.createElement(Pe.button,Y({type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":_x(o.open)},r,{ref:i,onClick:ue(e.onClick,o.onOpenToggle)}))}),dP="DialogPortal",[tW,fP]=lP(dP,{forceMount:void 0}),nW=e=>{const{__scopeDialog:t,forceMount:n,children:r,container:o}=e,i=bo(dP,t);return f.createElement(tW,{scope:t,forceMount:n},f.Children.map(r,s=>f.createElement(xn,{present:n||i.open},f.createElement(Md,{asChild:!0,container:o},s))))},f1="DialogOverlay",rW=f.forwardRef((e,t)=>{const n=fP(f1,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,i=bo(f1,e.__scopeDialog);return i.modal?f.createElement(xn,{present:r||i.open},f.createElement(oW,Y({},o,{ref:t}))):null}),oW=f.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=bo(f1,n);return f.createElement(Gm,{as:Wo,allowPinchZoom:!0,shards:[o.contentRef]},f.createElement(Pe.div,Y({"data-state":_x(o.open)},r,{ref:t,style:{pointerEvents:"auto",...r.style}})))}),oc="DialogContent",iW=f.forwardRef((e,t)=>{const n=fP(oc,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,i=bo(oc,e.__scopeDialog);return f.createElement(xn,{present:r||i.open},i.modal?f.createElement(sW,Y({},o,{ref:t})):f.createElement(aW,Y({},o,{ref:t})))}),sW=f.forwardRef((e,t)=>{const n=bo(oc,e.__scopeDialog),r=f.useRef(null),o=Be(t,n.contentRef,r);return f.useEffect(()=>{const i=r.current;if(i)return Xm(i)},[]),f.createElement(pP,Y({},e,{ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:ue(e.onCloseAutoFocus,i=>{var s;i.preventDefault(),(s=n.triggerRef.current)===null||s===void 0||s.focus()}),onPointerDownOutside:ue(e.onPointerDownOutside,i=>{const s=i.detail.originalEvent,l=s.button===0&&s.ctrlKey===!0;(s.button===2||l)&&i.preventDefault()}),onFocusOutside:ue(e.onFocusOutside,i=>i.preventDefault())}))}),aW=f.forwardRef((e,t)=>{const n=bo(oc,e.__scopeDialog),r=f.useRef(!1),o=f.useRef(!1);return f.createElement(pP,Y({},e,{ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var s;if((s=e.onCloseAutoFocus)===null||s===void 0||s.call(e,i),!i.defaultPrevented){var l;r.current||(l=n.triggerRef.current)===null||l===void 0||l.focus(),i.preventDefault()}r.current=!1,o.current=!1},onInteractOutside:i=>{var s,l;(s=e.onInteractOutside)===null||s===void 0||s.call(e,i),i.defaultPrevented||(r.current=!0,i.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const u=i.target;((l=n.triggerRef.current)===null||l===void 0?void 0:l.contains(u))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&o.current&&i.preventDefault()}}))}),pP=f.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:i,...s}=e,l=bo(oc,n),u=f.useRef(null),d=Be(t,u);return Km(),f.createElement(f.Fragment,null,f.createElement(Hm,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:i},f.createElement(yc,Y({role:"dialog",id:l.contentId,"aria-describedby":l.descriptionId,"aria-labelledby":l.titleId,"data-state":_x(l.open)},s,{ref:d,onDismiss:()=>l.onOpenChange(!1)}))),!1)}),hP="DialogTitle",lW=f.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=bo(hP,n);return f.createElement(Pe.h2,Y({id:o.titleId},r,{ref:t}))}),cW="DialogDescription",mP=f.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=bo(cW,n);return f.createElement(Pe.p,Y({id:o.descriptionId},r,{ref:t}))}),uW="DialogClose",dW=f.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=bo(uW,n);return f.createElement(Pe.button,Y({type:"button"},r,{ref:t,onClick:ue(e.onClick,()=>o.onOpenChange(!1))}))});function _x(e){return e?"open":"closed"}const fW="DialogTitleWarning",[pW,yte]=fB(fW,{contentName:oc,titleName:hP,docsSlug:"dialog"}),Sx=JV,gP=uP,Ex=nW,Nd=rW,Dd=iW,Id=lW,Ld=mP,Cx=dW,Zm=Sx,$x=gP,hW=Ex,vP=f.forwardRef(({className:e,...t},n)=>v.jsx(Nd,{ref:n,className:Ce("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t}));vP.displayName=Nd.displayName;const Fd=f.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(hW,{children:[v.jsx(vP,{}),v.jsxs(Dd,{ref:r,className:Ce("fixed left-[50%] top-[50%] z-50 flex flex-col w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",e,"outline-none"),onCloseAutoFocus:o=>o.preventDefault(),...n,children:[t,v.jsxs(Cx,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[v.jsx(yT,{className:"h-4 w-4"}),v.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Fd.displayName=Dd.displayName;const yP=({className:e,...t})=>v.jsx("div",{className:Ce("flex flex-col space-y-1.5 text-center sm:text-left",e),...t});yP.displayName="DialogHeader";const jd=f.forwardRef(({className:e,...t},n)=>v.jsx(Id,{ref:n,className:Ce("text-2xl font-semibold leading-none tracking-tight",e),...t}));jd.displayName=Id.displayName;const mW=f.forwardRef(({className:e,...t},n)=>v.jsx(Ld,{ref:n,className:Ce("text-sm text-muted-foreground",e),...t}));mW.displayName=Ld.displayName;function p1(){return p1=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 SW=function(t,n,r){r===void 0&&(r=!1);var o=n.alt,i=n.meta,s=n.mod,l=n.shift,u=n.ctrl,d=n.keys,h=t.key,m=t.code,g=t.ctrlKey,y=t.metaKey,x=t.shiftKey,_=t.altKey,C=ss(m),S=h.toLowerCase();if(!r){if(o===!_&&S!=="alt"||l===!x&&S!=="shift")return!1;if(s){if(!y&&!g)return!1}else if(i===!y&&S!=="meta"&&S!=="os"||u===!g&&S!=="ctrl"&&S!=="control")return!1}return d&&d.length===1&&(d.includes(S)||d.includes(C))?!0:d?yW(d):!d},EW=f.createContext(void 0),CW=function(){return f.useContext(EW)};function SP(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&&SP(e[r],t[r])},!0):e===t}var $W=f.createContext({hotkeys:[],enabledScopes:[],toggleScope:function(){},enableScope:function(){},disableScope:function(){}}),kW=function(){return f.useContext($W)};function RW(e){var t=f.useRef(void 0);return SP(t.current,e)||(t.current=e),t.current}var e2=function(t){t.stopPropagation(),t.preventDefault(),t.stopImmediatePropagation()},TW=typeof window<"u"?f.useLayoutEffect:f.useEffect;function PW(e,t,n,r){var o=f.useRef(null),i=f.useRef(!1),s=n instanceof Array?r instanceof Array?void 0:r:n,l=kx(e)?e.join(s==null?void 0:s.splitKey):e,u=n instanceof Array?n:r instanceof Array?r:void 0,d=f.useCallback(t,u??[]),h=f.useRef(d);u?h.current=d:h.current=t;var m=RW(s),g=kW(),y=g.enabledScopes,x=CW();return TW(function(){if(!((m==null?void 0:m.enabled)===!1||!_W(y,m==null?void 0:m.scopes))){var _=function(k,P){var M;if(P===void 0&&(P=!1),!(bW(k)&&!_P(k,m==null?void 0:m.enableOnFormTags))&&!(m!=null&&m.ignoreEventWhen!=null&&m.ignoreEventWhen(k))){if(o.current!==null&&document.activeElement!==o.current&&!o.current.contains(document.activeElement)){e2(k);return}(M=k.target)!=null&&M.isContentEditable&&!(m!=null&&m.enableOnContentEditable)||C0(l,m==null?void 0:m.splitKey).forEach(function(A){var O,F=$0(A,m==null?void 0:m.combinationKey);if(SW(k,F,m==null?void 0:m.ignoreModifiers)||(O=F.keys)!=null&&O.includes("*")){if(P&&i.current)return;if(wW(k,F,m==null?void 0:m.preventDefault),!xW(k,F,m==null?void 0:m.enabled)){e2(k);return}h.current(k,F),P||(i.current=!0)}})}},C=function(k){k.key!==void 0&&(xP(ss(k.code)),((m==null?void 0:m.keydown)===void 0&&(m==null?void 0:m.keyup)!==!0||m!=null&&m.keydown)&&_(k))},S=function(k){k.key!==void 0&&(bP(ss(k.code)),i.current=!1,m!=null&&m.keyup&&_(k,!0))},b=o.current||(s==null?void 0:s.document)||document;return b.addEventListener("keyup",S),b.addEventListener("keydown",C),x&&C0(l,m==null?void 0:m.splitKey).forEach(function(E){return x.addHotkey($0(E,m==null?void 0:m.combinationKey,m==null?void 0:m.description))}),function(){b.removeEventListener("keyup",S),b.removeEventListener("keydown",C),x&&C0(l,m==null?void 0:m.splitKey).forEach(function(E){return x.removeHotkey($0(E,m==null?void 0:m.combinationKey,m==null?void 0:m.description))})}}},[l,m,y]),o}const Zn=(e,t,n)=>{const r=bt(i=>i.disableShortCuts);return PW(e,t,{enabled:!r},n)};function ur(e){const{content:t,keys:n}=e;return v.jsxs("div",{className:"flex justify-between",children:[v.jsx("div",{children:t}),v.jsx("div",{className:"flex gap-[8px]",children:n.map(r=>v.jsx("div",{className:"border px-2 py-1 rounded-lg",children:r},r))})]})}const AW=function(){return/macintosh|mac os x/i.test(navigator.userAgent)},dp=()=>AW()?"Cmd":"Ctrl";function OW(){const[e,t]=u1(!1);return Zn("h",()=>{t()}),v.jsxs(Zm,{open:e,onOpenChange:t,children:[v.jsx($x,{asChild:!0,children:v.jsx(vn,{tooltip:"Hotkeys",children:v.jsx(eV,{})})}),v.jsx(Fd,{children:v.jsxs(yP,{children:[v.jsx(jd,{children:"Hotkeys"}),v.jsxs("div",{className:"flex gap-2 flex-col pt-4",children:[v.jsx(ur,{content:"Pan",keys:["Space + Drag"]}),v.jsx(ur,{content:"Reset Zoom/Pan",keys:["Esc"]}),v.jsx(ur,{content:"Decrease Brush Size",keys:["["]}),v.jsx(ur,{content:"Increase Brush Size",keys:["]"]}),v.jsx(ur,{content:"View Original Image",keys:["Hold Tab"]}),v.jsx(ur,{content:"Undo",keys:[dp(),"Z"]}),v.jsx(ur,{content:"Redo",keys:[dp(),"Shift","Z"]}),v.jsx(ur,{content:"Copy Result",keys:[dp(),"C"]}),v.jsx(ur,{content:"Paste Image",keys:[dp(),"V"]}),v.jsx(ur,{content:"Trigger Manually Inpainting",keys:["Shift","R"]}),v.jsx(ur,{content:"Toggle Hotkeys Dialog",keys:["H"]}),v.jsx(ur,{content:"Toggle Settings Dialog",keys:["S"]}),v.jsx(ur,{content:"Toggle File Manager",keys:["F"]})]})]})})]})}function Rx(e){const[t]=f.useState(new Image),[n,r]=f.useState(!1);return f.useEffect(()=>{if(e)return t.onload=()=>{r(!0)},r(!1),t.src=URL.createObjectURL(e),()=>{t.onload=null}},[e,t]),[t,n]}const EP="Popover",[CP,wte]=An(EP,[Ns]),Tx=Ns(),[MW,bc]=CP(EP),NW=e=>{const{__scopePopover:t,children:n,open:r,defaultOpen:o,onOpenChange:i,modal:s=!1}=e,l=Tx(t),u=f.useRef(null),[d,h]=f.useState(!1),[m=!1,g]=Zr({prop:r,defaultProp:o,onChange:i});return f.createElement(Od,l,f.createElement(MW,{scope:t,contentId:nr(),triggerRef:u,open:m,onOpenChange:g,onOpenToggle:f.useCallback(()=>g(y=>!y),[g]),hasCustomAnchor:d,onCustomAnchorAdd:f.useCallback(()=>h(!0),[]),onCustomAnchorRemove:f.useCallback(()=>h(!1),[]),modal:s},n))},DW="PopoverTrigger",IW=f.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,o=bc(DW,n),i=Tx(n),s=Be(t,o.triggerRef),l=f.createElement(Pe.button,Y({type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":RP(o.open)},r,{ref:s,onClick:ue(e.onClick,o.onOpenToggle)}));return o.hasCustomAnchor?l:f.createElement(zm,Y({asChild:!0},i),l)}),$P="PopoverPortal",[LW,FW]=CP($P,{forceMount:void 0}),jW=e=>{const{__scopePopover:t,forceMount:n,children:r,container:o}=e,i=bc($P,t);return f.createElement(LW,{scope:t,forceMount:n},f.createElement(xn,{present:n||i.open},f.createElement(Md,{asChild:!0,container:o},r)))},od="PopoverContent",zW=f.forwardRef((e,t)=>{const n=FW(od,e.__scopePopover),{forceMount:r=n.forceMount,...o}=e,i=bc(od,e.__scopePopover);return f.createElement(xn,{present:r||i.open},i.modal?f.createElement(BW,Y({},o,{ref:t})):f.createElement(UW,Y({},o,{ref:t})))}),BW=f.forwardRef((e,t)=>{const n=bc(od,e.__scopePopover),r=f.useRef(null),o=Be(t,r),i=f.useRef(!1);return f.useEffect(()=>{const s=r.current;if(s)return Xm(s)},[]),f.createElement(Gm,{as:Wo,allowPinchZoom:!0},f.createElement(kP,Y({},e,{ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:ue(e.onCloseAutoFocus,s=>{var l;s.preventDefault(),i.current||(l=n.triggerRef.current)===null||l===void 0||l.focus()}),onPointerDownOutside:ue(e.onPointerDownOutside,s=>{const l=s.detail.originalEvent,u=l.button===0&&l.ctrlKey===!0,d=l.button===2||u;i.current=d},{checkForDefaultPrevented:!1}),onFocusOutside:ue(e.onFocusOutside,s=>s.preventDefault(),{checkForDefaultPrevented:!1})})))}),UW=f.forwardRef((e,t)=>{const n=bc(od,e.__scopePopover),r=f.useRef(!1),o=f.useRef(!1);return f.createElement(kP,Y({},e,{ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var s;if((s=e.onCloseAutoFocus)===null||s===void 0||s.call(e,i),!i.defaultPrevented){var l;r.current||(l=n.triggerRef.current)===null||l===void 0||l.focus(),i.preventDefault()}r.current=!1,o.current=!1},onInteractOutside:i=>{var s,l;(s=e.onInteractOutside)===null||s===void 0||s.call(e,i),i.defaultPrevented||(r.current=!0,i.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const u=i.target;((l=n.triggerRef.current)===null||l===void 0?void 0:l.contains(u))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&o.current&&i.preventDefault()}}))}),kP=f.forwardRef((e,t)=>{const{__scopePopover:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:i,disableOutsidePointerEvents:s,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:d,onInteractOutside:h,...m}=e,g=bc(od,n),y=Tx(n);return Km(),f.createElement(Hm,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:i},f.createElement(yc,{asChild:!0,disableOutsidePointerEvents:s,onInteractOutside:h,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:d,onDismiss:()=>g.onOpenChange(!1)},f.createElement(Bm,Y({"data-state":RP(g.open),role:"dialog",id:g.contentId},y,m,{ref:t,style:{...m.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}}))))});function RP(e){return e?"open":"closed"}const VW=NW,WW=IW,HW=jW,TP=zW,KW=VW,YW=WW,PP=f.forwardRef(({className:e,align:t="center",sideOffset:n=4,...r},o)=>v.jsx(HW,{children:v.jsx(TP,{ref:o,align:t,tabIndex:-1,sideOffset:n,className:Ce("z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...r})}));PP.displayName=TP.displayName;function GW(){var e=f.useRef(!0);return e.current?(e.current=!1,!0):e.current}var XW=function(e,t){var n=GW();f.useEffect(function(){if(!n)return e()},t)};const ZW=XW;var qW=function(){};function Px(e){for(var t=[],n=1;n{const[e,t,n,r,o,i]=bt(g=>[g.getIsProcessing(),g.settings.prompt,g.updateSettings,g.runInpainting,g.showPrevMask,g.hidePrevMask]),s=f.useRef(null);OP(s,()=>{s!=null&&s.current&&s.current.blur()});const l=g=>{g.preventDefault(),g.stopPropagation();const y=g.target;n({prompt:y.value})},u=()=>{e||r()},d=g=>{g.key==="Enter"&&!e&&u()},h=()=>{o()},m=()=>{i()};return v.jsxs("div",{className:"flex gap-4 items-center",children:[v.jsx(Pd,{ref:s,className:"min-w-[500px]",value:t,onInput:l,onKeyUp:d,placeholder:"I want to repaint of..."}),v.jsx(Rn,{size:"sm",onClick:u,disabled:e,onMouseEnter:h,onMouseLeave:m,children:"Dream"})]})};var Lh={exports:{}};/** + * @license + * Lodash + * Copyright OpenJS Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */Lh.exports;(function(e,t){(function(){var n,r="4.17.21",o=200,i="Unsupported core-js use. Try https://npms.io/search?q=ponyfill.",s="Expected a function",l="Invalid `variable` option passed into `_.template`",u="__lodash_hash_undefined__",d=500,h="__lodash_placeholder__",m=1,g=2,y=4,x=1,_=2,C=1,S=2,b=4,E=8,k=16,P=32,M=64,A=128,O=256,F=512,V=30,J="...",G=800,ae=16,U=1,te=2,L=3,ie=1/0,K=9007199254740991,Q=17976931348623157e292,W=NaN,le=4294967295,ge=le-1,Ve=le>>>1,Ue=[["ary",A],["bind",C],["bindKey",S],["curry",E],["curryRight",k],["flip",F],["partial",P],["partialRight",M],["rearg",O]],We="[object Arguments]",Me="[object Array]",fe="[object AsyncFunction]",xe="[object Boolean]",$e="[object Date]",Ae="[object DOMException]",Oe="[object Error]",je="[object Function]",Ot="[object GeneratorFunction]",ct="[object Map]",Yt="[object Number]",Er="[object Null]",gt="[object Object]",js="[object Promise]",I="[object Proxy]",X="[object RegExp]",Z="[object Set]",we="[object String]",he="[object Symbol]",de="[object Undefined]",ke="[object WeakMap]",ft="[object WeakSet]",pt="[object ArrayBuffer]",bn="[object DataView]",Cr="[object Float32Array]",ki="[object Float64Array]",_o="[object Int8Array]",Vn="[object Int16Array]",Da="[object Int32Array]",Ri="[object Uint8Array]",zs="[object Uint8ClampedArray]",Ti="[object Uint16Array]",$c="[object Uint32Array]",yg=/\b__p \+= '';/g,wg=/\b(__p \+=) '' \+/g,Kd=/(__e\(.*?\)|\b__t\)) \+\n'';/g,kc=/&(?:amp|lt|gt|quot|#39);/g,Rc=/[&<>"']/g,Tc=RegExp(kc.source),xg=RegExp(Rc.source),Pc=/<%-([\s\S]+?)%>/g,Yd=/<%([\s\S]+?)%>/g,Ac=/<%=([\s\S]+?)%>/g,bg=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,_g=/^\w*$/,Sg=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,H=/[\\^$.*+?()[\]{}|]/g,Ge=RegExp(H.source),st=/^\s+/,Qr=/\s/,an=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,Gd=/\{\n\/\* \[wrapped with (.+)\] \*/,oO=/,? & /,iO=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,sO=/[()=,{}\[\]\/\s]/,aO=/\\(\\)?/g,lO=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,db=/\w*$/,cO=/^[-+]0x[0-9a-f]+$/i,uO=/^0b[01]+$/i,dO=/^\[object .+?Constructor\]$/,fO=/^0o[0-7]+$/i,pO=/^(?:0|[1-9]\d*)$/,hO=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,Xd=/($^)/,mO=/['\n\r\u2028\u2029\\]/g,Zd="\\ud800-\\udfff",gO="\\u0300-\\u036f",vO="\\ufe20-\\ufe2f",yO="\\u20d0-\\u20ff",fb=gO+vO+yO,pb="\\u2700-\\u27bf",hb="a-z\\xdf-\\xf6\\xf8-\\xff",wO="\\xac\\xb1\\xd7\\xf7",xO="\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf",bO="\\u2000-\\u206f",_O=" \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",mb="A-Z\\xc0-\\xd6\\xd8-\\xde",gb="\\ufe0e\\ufe0f",vb=wO+xO+bO+_O,Eg="['’]",SO="["+Zd+"]",yb="["+vb+"]",qd="["+fb+"]",wb="\\d+",EO="["+pb+"]",xb="["+hb+"]",bb="[^"+Zd+vb+wb+pb+hb+mb+"]",Cg="\\ud83c[\\udffb-\\udfff]",CO="(?:"+qd+"|"+Cg+")",_b="[^"+Zd+"]",$g="(?:\\ud83c[\\udde6-\\uddff]){2}",kg="[\\ud800-\\udbff][\\udc00-\\udfff]",Ia="["+mb+"]",Sb="\\u200d",Eb="(?:"+xb+"|"+bb+")",$O="(?:"+Ia+"|"+bb+")",Cb="(?:"+Eg+"(?:d|ll|m|re|s|t|ve))?",$b="(?:"+Eg+"(?:D|LL|M|RE|S|T|VE))?",kb=CO+"?",Rb="["+gb+"]?",kO="(?:"+Sb+"(?:"+[_b,$g,kg].join("|")+")"+Rb+kb+")*",RO="\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",TO="\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])",Tb=Rb+kb+kO,PO="(?:"+[EO,$g,kg].join("|")+")"+Tb,AO="(?:"+[_b+qd+"?",qd,$g,kg,SO].join("|")+")",OO=RegExp(Eg,"g"),MO=RegExp(qd,"g"),Rg=RegExp(Cg+"(?="+Cg+")|"+AO+Tb,"g"),NO=RegExp([Ia+"?"+xb+"+"+Cb+"(?="+[yb,Ia,"$"].join("|")+")",$O+"+"+$b+"(?="+[yb,Ia+Eb,"$"].join("|")+")",Ia+"?"+Eb+"+"+Cb,Ia+"+"+$b,TO,RO,wb,PO].join("|"),"g"),DO=RegExp("["+Sb+Zd+fb+gb+"]"),IO=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,LO=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],FO=-1,kt={};kt[Cr]=kt[ki]=kt[_o]=kt[Vn]=kt[Da]=kt[Ri]=kt[zs]=kt[Ti]=kt[$c]=!0,kt[We]=kt[Me]=kt[pt]=kt[xe]=kt[bn]=kt[$e]=kt[Oe]=kt[je]=kt[ct]=kt[Yt]=kt[gt]=kt[X]=kt[Z]=kt[we]=kt[ke]=!1;var Et={};Et[We]=Et[Me]=Et[pt]=Et[bn]=Et[xe]=Et[$e]=Et[Cr]=Et[ki]=Et[_o]=Et[Vn]=Et[Da]=Et[ct]=Et[Yt]=Et[gt]=Et[X]=Et[Z]=Et[we]=Et[he]=Et[Ri]=Et[zs]=Et[Ti]=Et[$c]=!0,Et[Oe]=Et[je]=Et[ke]=!1;var jO={À:"A",Á:"A",Â:"A",Ã:"A",Ä:"A",Å:"A",à:"a",á:"a",â:"a",ã:"a",ä:"a",å:"a",Ç:"C",ç:"c",Ð:"D",ð:"d",È:"E",É:"E",Ê:"E",Ë:"E",è:"e",é:"e",ê:"e",ë:"e",Ì:"I",Í:"I",Î:"I",Ï:"I",ì:"i",í:"i",î:"i",ï:"i",Ñ:"N",ñ:"n",Ò:"O",Ó:"O",Ô:"O",Õ:"O",Ö:"O",Ø:"O",ò:"o",ó:"o",ô:"o",õ:"o",ö:"o",ø:"o",Ù:"U",Ú:"U",Û:"U",Ü:"U",ù:"u",ú:"u",û:"u",ü:"u",Ý:"Y",ý:"y",ÿ:"y",Æ:"Ae",æ:"ae",Þ:"Th",þ:"th",ß:"ss",Ā:"A",Ă:"A",Ą:"A",ā:"a",ă:"a",ą:"a",Ć:"C",Ĉ:"C",Ċ:"C",Č:"C",ć:"c",ĉ:"c",ċ:"c",č:"c",Ď:"D",Đ:"D",ď:"d",đ:"d",Ē:"E",Ĕ:"E",Ė:"E",Ę:"E",Ě:"E",ē:"e",ĕ:"e",ė:"e",ę:"e",ě:"e",Ĝ:"G",Ğ:"G",Ġ:"G",Ģ:"G",ĝ:"g",ğ:"g",ġ:"g",ģ:"g",Ĥ:"H",Ħ:"H",ĥ:"h",ħ:"h",Ĩ:"I",Ī:"I",Ĭ:"I",Į:"I",İ:"I",ĩ:"i",ī:"i",ĭ:"i",į:"i",ı:"i",Ĵ:"J",ĵ:"j",Ķ:"K",ķ:"k",ĸ:"k",Ĺ:"L",Ļ:"L",Ľ:"L",Ŀ:"L",Ł:"L",ĺ:"l",ļ:"l",ľ:"l",ŀ:"l",ł:"l",Ń:"N",Ņ:"N",Ň:"N",Ŋ:"N",ń:"n",ņ:"n",ň:"n",ŋ:"n",Ō:"O",Ŏ:"O",Ő:"O",ō:"o",ŏ:"o",ő:"o",Ŕ:"R",Ŗ:"R",Ř:"R",ŕ:"r",ŗ:"r",ř:"r",Ś:"S",Ŝ:"S",Ş:"S",Š:"S",ś:"s",ŝ:"s",ş:"s",š:"s",Ţ:"T",Ť:"T",Ŧ:"T",ţ:"t",ť:"t",ŧ:"t",Ũ:"U",Ū:"U",Ŭ:"U",Ů:"U",Ű:"U",Ų:"U",ũ:"u",ū:"u",ŭ:"u",ů:"u",ű:"u",ų:"u",Ŵ:"W",ŵ:"w",Ŷ:"Y",ŷ:"y",Ÿ:"Y",Ź:"Z",Ż:"Z",Ž:"Z",ź:"z",ż:"z",ž:"z",IJ:"IJ",ij:"ij",Œ:"Oe",œ:"oe",ʼn:"'n",ſ:"s"},zO={"&":"&","<":"<",">":">",'"':""","'":"'"},BO={"&":"&","<":"<",">":">",""":'"',"'":"'"},UO={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},VO=parseFloat,WO=parseInt,Pb=typeof Yc=="object"&&Yc&&Yc.Object===Object&&Yc,HO=typeof self=="object"&&self&&self.Object===Object&&self,fn=Pb||HO||Function("return this")(),Tg=t&&!t.nodeType&&t,Bs=Tg&&!0&&e&&!e.nodeType&&e,Ab=Bs&&Bs.exports===Tg,Pg=Ab&&Pb.process,$r=function(){try{var j=Bs&&Bs.require&&Bs.require("util").types;return j||Pg&&Pg.binding&&Pg.binding("util")}catch{}}(),Ob=$r&&$r.isArrayBuffer,Mb=$r&&$r.isDate,Nb=$r&&$r.isMap,Db=$r&&$r.isRegExp,Ib=$r&&$r.isSet,Lb=$r&&$r.isTypedArray;function or(j,ee,q){switch(q.length){case 0:return j.call(ee);case 1:return j.call(ee,q[0]);case 2:return j.call(ee,q[0],q[1]);case 3:return j.call(ee,q[0],q[1],q[2])}return j.apply(ee,q)}function KO(j,ee,q,_e){for(var Ke=-1,ht=j==null?0:j.length;++Ke-1}function Ag(j,ee,q){for(var _e=-1,Ke=j==null?0:j.length;++_e-1;);return q}function Hb(j,ee){for(var q=j.length;q--&&La(ee,j[q],0)>-1;);return q}function t6(j,ee){for(var q=j.length,_e=0;q--;)j[q]===ee&&++_e;return _e}var n6=Dg(jO),r6=Dg(zO);function o6(j){return"\\"+UO[j]}function i6(j,ee){return j==null?n:j[ee]}function Fa(j){return DO.test(j)}function s6(j){return IO.test(j)}function a6(j){for(var ee,q=[];!(ee=j.next()).done;)q.push(ee.value);return q}function jg(j){var ee=-1,q=Array(j.size);return j.forEach(function(_e,Ke){q[++ee]=[Ke,_e]}),q}function Kb(j,ee){return function(q){return j(ee(q))}}function Oi(j,ee){for(var q=-1,_e=j.length,Ke=0,ht=[];++q<_e;){var en=j[q];(en===ee||en===h)&&(j[q]=h,ht[Ke++]=q)}return ht}function ef(j){var ee=-1,q=Array(j.size);return j.forEach(function(_e){q[++ee]=_e}),q}function l6(j){var ee=-1,q=Array(j.size);return j.forEach(function(_e){q[++ee]=[_e,_e]}),q}function c6(j,ee,q){for(var _e=q-1,Ke=j.length;++_e-1}function G6(a,c){var p=this.__data__,w=gf(p,a);return w<0?(++this.size,p.push([a,c])):p[w][1]=c,this}Xo.prototype.clear=W6,Xo.prototype.delete=H6,Xo.prototype.get=K6,Xo.prototype.has=Y6,Xo.prototype.set=G6;function Zo(a){var c=-1,p=a==null?0:a.length;for(this.clear();++c=c?a:c)),a}function Pr(a,c,p,w,$,T){var N,D=c&m,B=c&g,ne=c&y;if(p&&(N=$?p(a,w,$,T):p(a)),N!==n)return N;if(!It(a))return a;var re=Ye(a);if(re){if(N=QM(a),!D)return Wn(a,N)}else{var se=Sn(a),me=se==je||se==Ot;if(Fi(a))return R_(a,D);if(se==gt||se==We||me&&!$){if(N=B||me?{}:Y_(a),!D)return B?BM(a,uM(N,a)):zM(a,o_(N,a))}else{if(!Et[se])return $?a:{};N=JM(a,se,D)}}T||(T=new eo);var Re=T.get(a);if(Re)return Re;T.set(a,N),_S(a)?a.forEach(function(Le){N.add(Pr(Le,c,p,Le,a,T))}):xS(a)&&a.forEach(function(Le,nt){N.set(nt,Pr(Le,c,p,nt,a,T))});var Ie=ne?B?dv:uv:B?Kn:ln,Qe=re?n:Ie(a);return kr(Qe||a,function(Le,nt){Qe&&(nt=Le,Le=a[nt]),Fc(N,nt,Pr(Le,c,p,nt,a,T))}),N}function dM(a){var c=ln(a);return function(p){return i_(p,a,c)}}function i_(a,c,p){var w=p.length;if(a==null)return!w;for(a=_t(a);w--;){var $=p[w],T=c[$],N=a[$];if(N===n&&!($ in a)||!T(N))return!1}return!0}function s_(a,c,p){if(typeof a!="function")throw new Rr(s);return Hc(function(){a.apply(n,p)},c)}function jc(a,c,p,w){var $=-1,T=Qd,N=!0,D=a.length,B=[],ne=c.length;if(!D)return B;p&&(c=Mt(c,ir(p))),w?(T=Ag,N=!1):c.length>=o&&(T=Oc,N=!1,c=new Ws(c));e:for(;++$$?0:$+p),w=w===n||w>$?$:qe(w),w<0&&(w+=$),w=p>w?0:ES(w);p0&&p(D)?c>1?pn(D,c-1,p,w,$):Ai($,D):w||($[$.length]=D)}return $}var Kg=N_(),c_=N_(!0);function So(a,c){return a&&Kg(a,c,ln)}function Yg(a,c){return a&&c_(a,c,ln)}function yf(a,c){return Pi(c,function(p){return ti(a[p])})}function Ks(a,c){c=Ii(c,a);for(var p=0,w=c.length;a!=null&&pc}function hM(a,c){return a!=null&&yt.call(a,c)}function mM(a,c){return a!=null&&c in _t(a)}function gM(a,c,p){return a>=_n(c,p)&&a=120&&re.length>=120)?new Ws(N&&re):n}re=a[0];var se=-1,me=D[0];e:for(;++se<$&&ne.length-1;)D!==a&&cf.call(D,B,1),cf.call(a,B,1);return a}function x_(a,c){for(var p=a?c.length:0,w=p-1;p--;){var $=c[p];if(p==w||$!==T){var T=$;ei($)?cf.call(a,$,1):rv(a,$)}}return a}function ev(a,c){return a+ff(e_()*(c-a+1))}function TM(a,c,p,w){for(var $=-1,T=tn(df((c-a)/(p||1)),0),N=q(T);T--;)N[w?T:++$]=a,a+=p;return N}function tv(a,c){var p="";if(!a||c<1||c>K)return p;do c%2&&(p+=a),c=ff(c/2),c&&(a+=a);while(c);return p}function et(a,c){return yv(Z_(a,c,Yn),a+"")}function PM(a){return r_(Xa(a))}function AM(a,c){var p=Xa(a);return Tf(p,Hs(c,0,p.length))}function Uc(a,c,p,w){if(!It(a))return a;c=Ii(c,a);for(var $=-1,T=c.length,N=T-1,D=a;D!=null&&++$$?0:$+c),p=p>$?$:p,p<0&&(p+=$),$=c>p?0:p-c>>>0,c>>>=0;for(var T=q($);++w<$;)T[w]=a[w+c];return T}function NM(a,c){var p;return Ni(a,function(w,$,T){return p=c(w,$,T),!p}),!!p}function xf(a,c,p){var w=0,$=a==null?w:a.length;if(typeof c=="number"&&c===c&&$<=Ve){for(;w<$;){var T=w+$>>>1,N=a[T];N!==null&&!ar(N)&&(p?N<=c:N=o){var ne=c?null:HM(a);if(ne)return ef(ne);N=!1,$=Oc,B=new Ws}else B=c?[]:D;e:for(;++w=w?a:Ar(a,c,p)}var k_=_6||function(a){return fn.clearTimeout(a)};function R_(a,c){if(c)return a.slice();var p=a.length,w=Xb?Xb(p):new a.constructor(p);return a.copy(w),w}function av(a){var c=new a.constructor(a.byteLength);return new af(c).set(new af(a)),c}function IM(a,c){var p=c?av(a.buffer):a.buffer;return new a.constructor(p,a.byteOffset,a.byteLength)}function LM(a){var c=new a.constructor(a.source,db.exec(a));return c.lastIndex=a.lastIndex,c}function FM(a){return Lc?_t(Lc.call(a)):{}}function T_(a,c){var p=c?av(a.buffer):a.buffer;return new a.constructor(p,a.byteOffset,a.length)}function P_(a,c){if(a!==c){var p=a!==n,w=a===null,$=a===a,T=ar(a),N=c!==n,D=c===null,B=c===c,ne=ar(c);if(!D&&!ne&&!T&&a>c||T&&N&&B&&!D&&!ne||w&&N&&B||!p&&B||!$)return 1;if(!w&&!T&&!ne&&a=D)return B;var ne=p[w];return B*(ne=="desc"?-1:1)}}return a.index-c.index}function A_(a,c,p,w){for(var $=-1,T=a.length,N=p.length,D=-1,B=c.length,ne=tn(T-N,0),re=q(B+ne),se=!w;++D1?p[$-1]:n,N=$>2?p[2]:n;for(T=a.length>3&&typeof T=="function"?($--,T):n,N&&Mn(p[0],p[1],N)&&(T=$<3?n:T,$=1),c=_t(c);++w<$;){var D=p[w];D&&a(c,D,w,T)}return c})}function M_(a,c){return function(p,w){if(p==null)return p;if(!Hn(p))return a(p,w);for(var $=p.length,T=c?$:-1,N=_t(p);(c?T--:++T<$)&&w(N[T],T,N)!==!1;);return p}}function N_(a){return function(c,p,w){for(var $=-1,T=_t(c),N=w(c),D=N.length;D--;){var B=N[a?D:++$];if(p(T[B],B,T)===!1)break}return c}}function UM(a,c,p){var w=c&C,$=Vc(a);function T(){var N=this&&this!==fn&&this instanceof T?$:a;return N.apply(w?p:this,arguments)}return T}function D_(a){return function(c){c=vt(c);var p=Fa(c)?Jr(c):n,w=p?p[0]:c.charAt(0),$=p?Li(p,1).join(""):c.slice(1);return w[a]()+$}}function Ka(a){return function(c){return Og(MS(OS(c).replace(OO,"")),a,"")}}function Vc(a){return function(){var c=arguments;switch(c.length){case 0:return new a;case 1:return new a(c[0]);case 2:return new a(c[0],c[1]);case 3:return new a(c[0],c[1],c[2]);case 4:return new a(c[0],c[1],c[2],c[3]);case 5:return new a(c[0],c[1],c[2],c[3],c[4]);case 6:return new a(c[0],c[1],c[2],c[3],c[4],c[5]);case 7:return new a(c[0],c[1],c[2],c[3],c[4],c[5],c[6])}var p=Wa(a.prototype),w=a.apply(p,c);return It(w)?w:p}}function VM(a,c,p){var w=Vc(a);function $(){for(var T=arguments.length,N=q(T),D=T,B=Ya($);D--;)N[D]=arguments[D];var ne=T<3&&N[0]!==B&&N[T-1]!==B?[]:Oi(N,B);if(T-=ne.length,T-1?$[T?c[N]:N]:n}}function L_(a){return Jo(function(c){var p=c.length,w=p,$=Tr.prototype.thru;for(a&&c.reverse();w--;){var T=c[w];if(typeof T!="function")throw new Rr(s);if($&&!N&&kf(T)=="wrapper")var N=new Tr([],!0)}for(w=N?w:p;++w1&&at.reverse(),re&&BD))return!1;var ne=T.get(a),re=T.get(c);if(ne&&re)return ne==c&&re==a;var se=-1,me=!0,Re=p&_?new Ws:n;for(T.set(a,c),T.set(c,a);++se1?"& ":"")+c[w],c=c.join(p>2?", ":" "),a.replace(an,`{ +/* [wrapped with `+c+`] */ +`)}function tN(a){return Ye(a)||Xs(a)||!!(Qb&&a&&a[Qb])}function ei(a,c){var p=typeof a;return c=c??K,!!c&&(p=="number"||p!="symbol"&&pO.test(a))&&a>-1&&a%1==0&&a0){if(++c>=G)return arguments[0]}else c=0;return a.apply(n,arguments)}}function Tf(a,c){var p=-1,w=a.length,$=w-1;for(c=c===n?w:c;++p1?a[c-1]:n;return p=typeof p=="function"?(a.pop(),p):n,lS(a,p)});function cS(a){var c=R(a);return c.__chain__=!0,c}function f7(a,c){return c(a),a}function Pf(a,c){return c(a)}var p7=Jo(function(a){var c=a.length,p=c?a[0]:0,w=this.__wrapped__,$=function(T){return Hg(T,a)};return c>1||this.__actions__.length||!(w instanceof ot)||!ei(p)?this.thru($):(w=w.slice(p,+p+(c?1:0)),w.__actions__.push({func:Pf,args:[$],thisArg:n}),new Tr(w,this.__chain__).thru(function(T){return c&&!T.length&&T.push(n),T}))});function h7(){return cS(this)}function m7(){return new Tr(this.value(),this.__chain__)}function g7(){this.__values__===n&&(this.__values__=SS(this.value()));var a=this.__index__>=this.__values__.length,c=a?n:this.__values__[this.__index__++];return{done:a,value:c}}function v7(){return this}function y7(a){for(var c,p=this;p instanceof mf;){var w=nS(p);w.__index__=0,w.__values__=n,c?$.__wrapped__=w:c=w;var $=w;p=p.__wrapped__}return $.__wrapped__=a,c}function w7(){var a=this.__wrapped__;if(a instanceof ot){var c=a;return this.__actions__.length&&(c=new ot(this)),c=c.reverse(),c.__actions__.push({func:Pf,args:[wv],thisArg:n}),new Tr(c,this.__chain__)}return this.thru(wv)}function x7(){return C_(this.__wrapped__,this.__actions__)}var b7=_f(function(a,c,p){yt.call(a,p)?++a[p]:qo(a,p,1)});function _7(a,c,p){var w=Ye(a)?Fb:fM;return p&&Mn(a,c,p)&&(c=n),w(a,De(c,3))}function S7(a,c){var p=Ye(a)?Pi:l_;return p(a,De(c,3))}var E7=I_(rS),C7=I_(oS);function $7(a,c){return pn(Af(a,c),1)}function k7(a,c){return pn(Af(a,c),ie)}function R7(a,c,p){return p=p===n?1:qe(p),pn(Af(a,c),p)}function uS(a,c){var p=Ye(a)?kr:Ni;return p(a,De(c,3))}function dS(a,c){var p=Ye(a)?YO:a_;return p(a,De(c,3))}var T7=_f(function(a,c,p){yt.call(a,p)?a[p].push(c):qo(a,p,[c])});function P7(a,c,p,w){a=Hn(a)?a:Xa(a),p=p&&!w?qe(p):0;var $=a.length;return p<0&&(p=tn($+p,0)),If(a)?p<=$&&a.indexOf(c,p)>-1:!!$&&La(a,c,p)>-1}var A7=et(function(a,c,p){var w=-1,$=typeof c=="function",T=Hn(a)?q(a.length):[];return Ni(a,function(N){T[++w]=$?or(c,N,p):zc(N,c,p)}),T}),O7=_f(function(a,c,p){qo(a,p,c)});function Af(a,c){var p=Ye(a)?Mt:h_;return p(a,De(c,3))}function M7(a,c,p,w){return a==null?[]:(Ye(c)||(c=c==null?[]:[c]),p=w?n:p,Ye(p)||(p=p==null?[]:[p]),y_(a,c,p))}var N7=_f(function(a,c,p){a[p?0:1].push(c)},function(){return[[],[]]});function D7(a,c,p){var w=Ye(a)?Og:Ub,$=arguments.length<3;return w(a,De(c,4),p,$,Ni)}function I7(a,c,p){var w=Ye(a)?GO:Ub,$=arguments.length<3;return w(a,De(c,4),p,$,a_)}function L7(a,c){var p=Ye(a)?Pi:l_;return p(a,Nf(De(c,3)))}function F7(a){var c=Ye(a)?r_:PM;return c(a)}function j7(a,c,p){(p?Mn(a,c,p):c===n)?c=1:c=qe(c);var w=Ye(a)?aM:AM;return w(a,c)}function z7(a){var c=Ye(a)?lM:MM;return c(a)}function B7(a){if(a==null)return 0;if(Hn(a))return If(a)?ja(a):a.length;var c=Sn(a);return c==ct||c==Z?a.size:qg(a).length}function U7(a,c,p){var w=Ye(a)?Mg:NM;return p&&Mn(a,c,p)&&(c=n),w(a,De(c,3))}var V7=et(function(a,c){if(a==null)return[];var p=c.length;return p>1&&Mn(a,c[0],c[1])?c=[]:p>2&&Mn(c[0],c[1],c[2])&&(c=[c[0]]),y_(a,pn(c,1),[])}),Of=S6||function(){return fn.Date.now()};function W7(a,c){if(typeof c!="function")throw new Rr(s);return a=qe(a),function(){if(--a<1)return c.apply(this,arguments)}}function fS(a,c,p){return c=p?n:c,c=a&&c==null?a.length:c,Qo(a,A,n,n,n,n,c)}function pS(a,c){var p;if(typeof c!="function")throw new Rr(s);return a=qe(a),function(){return--a>0&&(p=c.apply(this,arguments)),a<=1&&(c=n),p}}var bv=et(function(a,c,p){var w=C;if(p.length){var $=Oi(p,Ya(bv));w|=P}return Qo(a,w,c,p,$)}),hS=et(function(a,c,p){var w=C|S;if(p.length){var $=Oi(p,Ya(hS));w|=P}return Qo(c,w,a,p,$)});function mS(a,c,p){c=p?n:c;var w=Qo(a,E,n,n,n,n,n,c);return w.placeholder=mS.placeholder,w}function gS(a,c,p){c=p?n:c;var w=Qo(a,k,n,n,n,n,n,c);return w.placeholder=gS.placeholder,w}function vS(a,c,p){var w,$,T,N,D,B,ne=0,re=!1,se=!1,me=!0;if(typeof a!="function")throw new Rr(s);c=Mr(c)||0,It(p)&&(re=!!p.leading,se="maxWait"in p,T=se?tn(Mr(p.maxWait)||0,c):T,me="trailing"in p?!!p.trailing:me);function Re(Xt){var no=w,ri=$;return w=$=n,ne=Xt,N=a.apply(ri,no),N}function Ie(Xt){return ne=Xt,D=Hc(nt,c),re?Re(Xt):N}function Qe(Xt){var no=Xt-B,ri=Xt-ne,IS=c-no;return se?_n(IS,T-ri):IS}function Le(Xt){var no=Xt-B,ri=Xt-ne;return B===n||no>=c||no<0||se&&ri>=T}function nt(){var Xt=Of();if(Le(Xt))return at(Xt);D=Hc(nt,Qe(Xt))}function at(Xt){return D=n,me&&w?Re(Xt):(w=$=n,N)}function lr(){D!==n&&k_(D),ne=0,w=B=$=D=n}function Nn(){return D===n?N:at(Of())}function cr(){var Xt=Of(),no=Le(Xt);if(w=arguments,$=this,B=Xt,no){if(D===n)return Ie(B);if(se)return k_(D),D=Hc(nt,c),Re(B)}return D===n&&(D=Hc(nt,c)),N}return cr.cancel=lr,cr.flush=Nn,cr}var H7=et(function(a,c){return s_(a,1,c)}),K7=et(function(a,c,p){return s_(a,Mr(c)||0,p)});function Y7(a){return Qo(a,F)}function Mf(a,c){if(typeof a!="function"||c!=null&&typeof c!="function")throw new Rr(s);var p=function(){var w=arguments,$=c?c.apply(this,w):w[0],T=p.cache;if(T.has($))return T.get($);var N=a.apply(this,w);return p.cache=T.set($,N)||T,N};return p.cache=new(Mf.Cache||Zo),p}Mf.Cache=Zo;function Nf(a){if(typeof a!="function")throw new Rr(s);return function(){var c=arguments;switch(c.length){case 0:return!a.call(this);case 1:return!a.call(this,c[0]);case 2:return!a.call(this,c[0],c[1]);case 3:return!a.call(this,c[0],c[1],c[2])}return!a.apply(this,c)}}function G7(a){return pS(2,a)}var X7=DM(function(a,c){c=c.length==1&&Ye(c[0])?Mt(c[0],ir(De())):Mt(pn(c,1),ir(De()));var p=c.length;return et(function(w){for(var $=-1,T=_n(w.length,p);++$=c}),Xs=d_(function(){return arguments}())?d_:function(a){return Bt(a)&&yt.call(a,"callee")&&!qb.call(a,"callee")},Ye=q.isArray,u4=Ob?ir(Ob):yM;function Hn(a){return a!=null&&Df(a.length)&&!ti(a)}function Gt(a){return Bt(a)&&Hn(a)}function d4(a){return a===!0||a===!1||Bt(a)&&On(a)==xe}var Fi=C6||Mv,f4=Mb?ir(Mb):wM;function p4(a){return Bt(a)&&a.nodeType===1&&!Kc(a)}function h4(a){if(a==null)return!0;if(Hn(a)&&(Ye(a)||typeof a=="string"||typeof a.splice=="function"||Fi(a)||Ga(a)||Xs(a)))return!a.length;var c=Sn(a);if(c==ct||c==Z)return!a.size;if(Wc(a))return!qg(a).length;for(var p in a)if(yt.call(a,p))return!1;return!0}function m4(a,c){return Bc(a,c)}function g4(a,c,p){p=typeof p=="function"?p:n;var w=p?p(a,c):n;return w===n?Bc(a,c,n,p):!!w}function Sv(a){if(!Bt(a))return!1;var c=On(a);return c==Oe||c==Ae||typeof a.message=="string"&&typeof a.name=="string"&&!Kc(a)}function v4(a){return typeof a=="number"&&Jb(a)}function ti(a){if(!It(a))return!1;var c=On(a);return c==je||c==Ot||c==fe||c==I}function wS(a){return typeof a=="number"&&a==qe(a)}function Df(a){return typeof a=="number"&&a>-1&&a%1==0&&a<=K}function It(a){var c=typeof a;return a!=null&&(c=="object"||c=="function")}function Bt(a){return a!=null&&typeof a=="object"}var xS=Nb?ir(Nb):bM;function y4(a,c){return a===c||Zg(a,c,pv(c))}function w4(a,c,p){return p=typeof p=="function"?p:n,Zg(a,c,pv(c),p)}function x4(a){return bS(a)&&a!=+a}function b4(a){if(oN(a))throw new Ke(i);return f_(a)}function _4(a){return a===null}function S4(a){return a==null}function bS(a){return typeof a=="number"||Bt(a)&&On(a)==Yt}function Kc(a){if(!Bt(a)||On(a)!=gt)return!1;var c=lf(a);if(c===null)return!0;var p=yt.call(c,"constructor")&&c.constructor;return typeof p=="function"&&p instanceof p&&rf.call(p)==w6}var Ev=Db?ir(Db):_M;function E4(a){return wS(a)&&a>=-K&&a<=K}var _S=Ib?ir(Ib):SM;function If(a){return typeof a=="string"||!Ye(a)&&Bt(a)&&On(a)==we}function ar(a){return typeof a=="symbol"||Bt(a)&&On(a)==he}var Ga=Lb?ir(Lb):EM;function C4(a){return a===n}function $4(a){return Bt(a)&&Sn(a)==ke}function k4(a){return Bt(a)&&On(a)==ft}var R4=$f(Qg),T4=$f(function(a,c){return a<=c});function SS(a){if(!a)return[];if(Hn(a))return If(a)?Jr(a):Wn(a);if(Mc&&a[Mc])return a6(a[Mc]());var c=Sn(a),p=c==ct?jg:c==Z?ef:Xa;return p(a)}function ni(a){if(!a)return a===0?a:0;if(a=Mr(a),a===ie||a===-ie){var c=a<0?-1:1;return c*Q}return a===a?a:0}function qe(a){var c=ni(a),p=c%1;return c===c?p?c-p:c:0}function ES(a){return a?Hs(qe(a),0,le):0}function Mr(a){if(typeof a=="number")return a;if(ar(a))return W;if(It(a)){var c=typeof a.valueOf=="function"?a.valueOf():a;a=It(c)?c+"":c}if(typeof a!="string")return a===0?a:+a;a=Vb(a);var p=uO.test(a);return p||fO.test(a)?WO(a.slice(2),p?2:8):cO.test(a)?W:+a}function CS(a){return Eo(a,Kn(a))}function P4(a){return a?Hs(qe(a),-K,K):a===0?a:0}function vt(a){return a==null?"":sr(a)}var A4=Ha(function(a,c){if(Wc(c)||Hn(c)){Eo(c,ln(c),a);return}for(var p in c)yt.call(c,p)&&Fc(a,p,c[p])}),$S=Ha(function(a,c){Eo(c,Kn(c),a)}),Lf=Ha(function(a,c,p,w){Eo(c,Kn(c),a,w)}),O4=Ha(function(a,c,p,w){Eo(c,ln(c),a,w)}),M4=Jo(Hg);function N4(a,c){var p=Wa(a);return c==null?p:o_(p,c)}var D4=et(function(a,c){a=_t(a);var p=-1,w=c.length,$=w>2?c[2]:n;for($&&Mn(c[0],c[1],$)&&(w=1);++p1),T}),Eo(a,dv(a),p),w&&(p=Pr(p,m|g|y,KM));for(var $=c.length;$--;)rv(p,c[$]);return p});function J4(a,c){return RS(a,Nf(De(c)))}var e8=Jo(function(a,c){return a==null?{}:kM(a,c)});function RS(a,c){if(a==null)return{};var p=Mt(dv(a),function(w){return[w]});return c=De(c),w_(a,p,function(w,$){return c(w,$[0])})}function t8(a,c,p){c=Ii(c,a);var w=-1,$=c.length;for($||($=1,a=n);++w<$;){var T=a==null?n:a[Co(c[w])];T===n&&(w=$,T=p),a=ti(T)?T.call(a):T}return a}function n8(a,c,p){return a==null?a:Uc(a,c,p)}function r8(a,c,p,w){return w=typeof w=="function"?w:n,a==null?a:Uc(a,c,p,w)}var TS=B_(ln),PS=B_(Kn);function o8(a,c,p){var w=Ye(a),$=w||Fi(a)||Ga(a);if(c=De(c,4),p==null){var T=a&&a.constructor;$?p=w?new T:[]:It(a)?p=ti(T)?Wa(lf(a)):{}:p={}}return($?kr:So)(a,function(N,D,B){return c(p,N,D,B)}),p}function i8(a,c){return a==null?!0:rv(a,c)}function s8(a,c,p){return a==null?a:E_(a,c,sv(p))}function a8(a,c,p,w){return w=typeof w=="function"?w:n,a==null?a:E_(a,c,sv(p),w)}function Xa(a){return a==null?[]:Fg(a,ln(a))}function l8(a){return a==null?[]:Fg(a,Kn(a))}function c8(a,c,p){return p===n&&(p=c,c=n),p!==n&&(p=Mr(p),p=p===p?p:0),c!==n&&(c=Mr(c),c=c===c?c:0),Hs(Mr(a),c,p)}function u8(a,c,p){return c=ni(c),p===n?(p=c,c=0):p=ni(p),a=Mr(a),gM(a,c,p)}function d8(a,c,p){if(p&&typeof p!="boolean"&&Mn(a,c,p)&&(c=p=n),p===n&&(typeof c=="boolean"?(p=c,c=n):typeof a=="boolean"&&(p=a,a=n)),a===n&&c===n?(a=0,c=1):(a=ni(a),c===n?(c=a,a=0):c=ni(c)),a>c){var w=a;a=c,c=w}if(p||a%1||c%1){var $=e_();return _n(a+$*(c-a+VO("1e-"+(($+"").length-1))),c)}return ev(a,c)}var f8=Ka(function(a,c,p){return c=c.toLowerCase(),a+(p?AS(c):c)});function AS(a){return kv(vt(a).toLowerCase())}function OS(a){return a=vt(a),a&&a.replace(hO,n6).replace(MO,"")}function p8(a,c,p){a=vt(a),c=sr(c);var w=a.length;p=p===n?w:Hs(qe(p),0,w);var $=p;return p-=c.length,p>=0&&a.slice(p,$)==c}function h8(a){return a=vt(a),a&&xg.test(a)?a.replace(Rc,r6):a}function m8(a){return a=vt(a),a&&Ge.test(a)?a.replace(H,"\\$&"):a}var g8=Ka(function(a,c,p){return a+(p?"-":"")+c.toLowerCase()}),v8=Ka(function(a,c,p){return a+(p?" ":"")+c.toLowerCase()}),y8=D_("toLowerCase");function w8(a,c,p){a=vt(a),c=qe(c);var w=c?ja(a):0;if(!c||w>=c)return a;var $=(c-w)/2;return Cf(ff($),p)+a+Cf(df($),p)}function x8(a,c,p){a=vt(a),c=qe(c);var w=c?ja(a):0;return c&&w>>0,p?(a=vt(a),a&&(typeof c=="string"||c!=null&&!Ev(c))&&(c=sr(c),!c&&Fa(a))?Li(Jr(a),0,p):a.split(c,p)):[]}var k8=Ka(function(a,c,p){return a+(p?" ":"")+kv(c)});function R8(a,c,p){return a=vt(a),p=p==null?0:Hs(qe(p),0,a.length),c=sr(c),a.slice(p,p+c.length)==c}function T8(a,c,p){var w=R.templateSettings;p&&Mn(a,c,p)&&(c=n),a=vt(a),c=Lf({},c,w,U_);var $=Lf({},c.imports,w.imports,U_),T=ln($),N=Fg($,T),D,B,ne=0,re=c.interpolate||Xd,se="__p += '",me=zg((c.escape||Xd).source+"|"+re.source+"|"+(re===Ac?lO:Xd).source+"|"+(c.evaluate||Xd).source+"|$","g"),Re="//# sourceURL="+(yt.call(c,"sourceURL")?(c.sourceURL+"").replace(/\s/g," "):"lodash.templateSources["+ ++FO+"]")+` +`;a.replace(me,function(Le,nt,at,lr,Nn,cr){return at||(at=lr),se+=a.slice(ne,cr).replace(mO,o6),nt&&(D=!0,se+=`' + +__e(`+nt+`) + +'`),Nn&&(B=!0,se+=`'; +`+Nn+`; +__p += '`),at&&(se+=`' + +((__t = (`+at+`)) == null ? '' : __t) + +'`),ne=cr+Le.length,Le}),se+=`'; +`;var Ie=yt.call(c,"variable")&&c.variable;if(!Ie)se=`with (obj) { +`+se+` +} +`;else if(sO.test(Ie))throw new Ke(l);se=(B?se.replace(yg,""):se).replace(wg,"$1").replace(Kd,"$1;"),se="function("+(Ie||"obj")+`) { +`+(Ie?"":`obj || (obj = {}); +`)+"var __t, __p = ''"+(D?", __e = _.escape":"")+(B?`, __j = Array.prototype.join; +function print() { __p += __j.call(arguments, '') } +`:`; +`)+se+`return __p +}`;var Qe=NS(function(){return ht(T,Re+"return "+se).apply(n,N)});if(Qe.source=se,Sv(Qe))throw Qe;return Qe}function P8(a){return vt(a).toLowerCase()}function A8(a){return vt(a).toUpperCase()}function O8(a,c,p){if(a=vt(a),a&&(p||c===n))return Vb(a);if(!a||!(c=sr(c)))return a;var w=Jr(a),$=Jr(c),T=Wb(w,$),N=Hb(w,$)+1;return Li(w,T,N).join("")}function M8(a,c,p){if(a=vt(a),a&&(p||c===n))return a.slice(0,Yb(a)+1);if(!a||!(c=sr(c)))return a;var w=Jr(a),$=Hb(w,Jr(c))+1;return Li(w,0,$).join("")}function N8(a,c,p){if(a=vt(a),a&&(p||c===n))return a.replace(st,"");if(!a||!(c=sr(c)))return a;var w=Jr(a),$=Wb(w,Jr(c));return Li(w,$).join("")}function D8(a,c){var p=V,w=J;if(It(c)){var $="separator"in c?c.separator:$;p="length"in c?qe(c.length):p,w="omission"in c?sr(c.omission):w}a=vt(a);var T=a.length;if(Fa(a)){var N=Jr(a);T=N.length}if(p>=T)return a;var D=p-ja(w);if(D<1)return w;var B=N?Li(N,0,D).join(""):a.slice(0,D);if($===n)return B+w;if(N&&(D+=B.length-D),Ev($)){if(a.slice(D).search($)){var ne,re=B;for($.global||($=zg($.source,vt(db.exec($))+"g")),$.lastIndex=0;ne=$.exec(re);)var se=ne.index;B=B.slice(0,se===n?D:se)}}else if(a.indexOf(sr($),D)!=D){var me=B.lastIndexOf($);me>-1&&(B=B.slice(0,me))}return B+w}function I8(a){return a=vt(a),a&&Tc.test(a)?a.replace(kc,d6):a}var L8=Ka(function(a,c,p){return a+(p?" ":"")+c.toUpperCase()}),kv=D_("toUpperCase");function MS(a,c,p){return a=vt(a),c=p?n:c,c===n?s6(a)?h6(a):qO(a):a.match(c)||[]}var NS=et(function(a,c){try{return or(a,n,c)}catch(p){return Sv(p)?p:new Ke(p)}}),F8=Jo(function(a,c){return kr(c,function(p){p=Co(p),qo(a,p,bv(a[p],a))}),a});function j8(a){var c=a==null?0:a.length,p=De();return a=c?Mt(a,function(w){if(typeof w[1]!="function")throw new Rr(s);return[p(w[0]),w[1]]}):[],et(function(w){for(var $=-1;++$K)return[];var p=le,w=_n(a,le);c=De(c),a-=le;for(var $=Lg(w,c);++p0||c<0)?new ot(p):(a<0?p=p.takeRight(-a):a&&(p=p.drop(a)),c!==n&&(c=qe(c),p=c<0?p.dropRight(-c):p.take(c-a)),p)},ot.prototype.takeRightWhile=function(a){return this.reverse().takeWhile(a).reverse()},ot.prototype.toArray=function(){return this.take(le)},So(ot.prototype,function(a,c){var p=/^(?:filter|find|map|reject)|While$/.test(c),w=/^(?:head|last)$/.test(c),$=R[w?"take"+(c=="last"?"Right":""):c],T=w||/^find/.test(c);$&&(R.prototype[c]=function(){var N=this.__wrapped__,D=w?[1]:arguments,B=N instanceof ot,ne=D[0],re=B||Ye(N),se=function(nt){var at=$.apply(R,Ai([nt],D));return w&&me?at[0]:at};re&&p&&typeof ne=="function"&&ne.length!=1&&(B=re=!1);var me=this.__chain__,Re=!!this.__actions__.length,Ie=T&&!me,Qe=B&&!Re;if(!T&&re){N=Qe?N:new ot(this);var Le=a.apply(N,D);return Le.__actions__.push({func:Pf,args:[se],thisArg:n}),new Tr(Le,me)}return Ie&&Qe?a.apply(this,D):(Le=this.thru(se),Ie?w?Le.value()[0]:Le.value():Le)})}),kr(["pop","push","shift","sort","splice","unshift"],function(a){var c=tf[a],p=/^(?:push|sort|unshift)$/.test(a)?"tap":"thru",w=/^(?:pop|shift)$/.test(a);R.prototype[a]=function(){var $=arguments;if(w&&!this.__chain__){var T=this.value();return c.apply(Ye(T)?T:[],$)}return this[p](function(N){return c.apply(Ye(N)?N:[],$)})}}),So(ot.prototype,function(a,c){var p=R[c];if(p){var w=p.name+"";yt.call(Va,w)||(Va[w]=[]),Va[w].push({name:c,func:p})}}),Va[Sf(n,S).name]=[{name:"wrapper",func:n}],ot.prototype.clone=I6,ot.prototype.reverse=L6,ot.prototype.value=F6,R.prototype.at=p7,R.prototype.chain=h7,R.prototype.commit=m7,R.prototype.next=g7,R.prototype.plant=y7,R.prototype.reverse=w7,R.prototype.toJSON=R.prototype.valueOf=R.prototype.value=x7,R.prototype.first=R.prototype.head,Mc&&(R.prototype[Mc]=v7),R},za=m6();Bs?((Bs.exports=za)._=za,Tg._=za):fn._=za}).call(Yc)})(Lh,Lh.exports);var wH=Lh.exports;const xH=lm(wH);function Vr({width:e,height:t}){return e/t}function Fh(e,t=0){const n=10**t;return Math.round((e+Number.EPSILON)*n)/n}function bH(e){return(t,n)=>e(n)-e(t)}class _H{constructor(t){this.comparator=t,this.heap=[],this.n=0}greater(t,n){return this.comparator(this.heap[t],this.heap[n])<0}swap(t,n){const r=this.heap[t];this.heap[t]=this.heap[n],this.heap[n]=r}swim(t){let n=t,r=Math.floor(n/2);for(;n>1&&this.greater(r,n);)this.swap(r,n),n=r,r=Math.floor(n/2)}sink(t){let n=t,r=n*2;for(;r<=this.n&&(rl.weight));for(s.push({id:t,weight:0});s.size()>0;){const{id:l,weight:u}=s.pop();if(!o.has(l)){const d=e(l);o.add(l),d.forEach((h,m)=>{const g=u+h,y=r.get(m),x=i.get(m);(x===void 0||x>g&&(x/g>1.005||y!==void 0&&yMath.min(Vr(i),o),Number.MAX_VALUE);return Fh(n/t/r)+2}function MP(e,t,n,r){const o=t-(e.length-1)*n-2*r*e.length,i=e.reduce((s,l)=>s+Vr(l),0);return o/i}function kH(e,t,n,r,o,i,s){const l=e.slice(t,n),u=MP(l,r,i,s);return u>0?(u-o)**2*l.length:void 0}function RH({photos:e,layoutOptions:t,targetRowHeight:n,limitNodeSearch:r,rowConstraints:o}){return i=>{var s,l;const{containerWidth:u,spacing:d,padding:h}=t,m=new Map;m.set(i,0);const g=(s=o==null?void 0:o.minPhotos)!=null?s:1,y=Math.min(r,(l=o==null?void 0:o.maxPhotos)!=null?l:1/0);for(let x=i+g;xy);x+=1){const _=kH(e,i,x,u,n,d,h);if(_===void 0)break;m.set(x,_)}return m}}function TH({photos:e,layoutOptions:t}){const{spacing:n,padding:r,containerWidth:o,targetRowHeight:i,rowConstraints:s}=t,l=$H({photos:e,containerWidth:o,targetRowHeight:i}),u=RH({photos:e,layoutOptions:t,targetRowHeight:i,limitNodeSearch:l,rowConstraints:s}),d=CH(u,0,e.length);if(d===void 0)return;const h=[];for(let m=1;m({photo:x,index:_})).slice(d[m-1],d[m]),y=MP(g.map(({photo:x})=>x),o,n,r);h.push(g.map(({photo:x,index:_},C)=>({photo:x,layout:{height:y,width:y*Vr(x),index:_,photoIndex:C,photosCount:g.length}})))}return h}function qm(...e){return[...e].filter(t=>!!t).join(" ")}function NP(e,{width:t,photosCount:n},{spacing:r,padding:o,containerWidth:i}){const s=r*(n-1)+2*o*n;return`calc((${e} - ${s}px) / ${Fh((i-s)/t,5)})`}function PH(e,t){return t.layout!=="rows"?`calc(100% - ${2*t.padding}px)`:NP("100%",e,t)}function i2(e,t,n){var r,o;return NP((o=(r=e.match(/calc\((.*)\)/))==null?void 0:r[1])!=null?o:e,t,n)}function AH(e,t,n){let r,o;const i=e.srcSet||e.images;return i&&i.length>0&&(r=i.concat(i.find(({width:s})=>s===e.width)?[]:[{src:e.src,width:e.width,height:e.height}]).sort((s,l)=>s.width-l.width).map(s=>`${s.src} ${s.width}w`).join(", ")),n.sizes?o=(n.sizes.sizes||[]).map(({viewport:s,size:l})=>`${s} ${i2(l,t,n)}`).concat(i2(n.sizes.size,t,n)).join(", "):r&&(o=`${Math.ceil(t.width/n.containerWidth*100)}vw`),{srcSet:r,sizes:o}}function Ox(e){var t,n;const{photo:r,layout:o,layoutOptions:i,imageProps:{style:s,className:l,...u}={},renderPhoto:d}=e,{onClick:h}=i,m={display:"block",boxSizing:"content-box",width:PH(o,i),height:"auto",aspectRatio:`${r.width} / ${r.height}`,...i.padding?{padding:`${i.padding}px`}:null,...(i.layout==="columns"||i.layout==="masonry")&&o.photoIndex{h({event:C,photo:r,index:o.index})}:void 0,y={src:r.src,alt:(t=r.alt)!=null?t:"",title:r.title,onClick:g,style:m,className:qm("react-photo-album--photo",l),loading:"lazy",decoding:"async",...AH(r,o,i),...u},x=C=>{const{src:S,alt:b,srcSet:E,sizes:k,style:P,...M}=y;return f.createElement("img",{alt:b,...E?{srcSet:E,sizes:k}:null,src:S,style:C!=null&&C.wrapped?{display:"block",width:"100%",height:"100%"}:P,...M})},_=(({display:C,boxSizing:S,width:b,aspectRatio:E,padding:k,marginBottom:P,cursor:M})=>({display:C,boxSizing:S,width:b,aspectRatio:E,padding:k,marginBottom:P,cursor:M}))(m);return f.createElement(f.Fragment,null,(n=d==null?void 0:d({photo:r,layout:o,layoutOptions:i,imageProps:y,renderDefaultPhoto:x,wrapperStyle:_}))!=null?n:x())}function OH({rowContainerProps:e,children:t}){return f.createElement("div",{...e},t)}function MH(e){const{layoutOptions:t,rowIndex:n,rowsCount:r,renderRowContainer:o,rowContainerProps:{style:i,className:s,...l}={},children:u}=e,d={className:qm("react-photo-album--row",s),style:{display:"flex",flexDirection:"row",flexWrap:"nowrap",alignItems:"flex-start",justifyContent:"space-between",...nf.createElement(MH,{key:`row-${d}`,layoutOptions:n,rowIndex:d,rowsCount:l.length,renderRowContainer:o,rowContainerProps:s},u.map(({photo:h,layout:m})=>f.createElement(Ox,{key:h.key||h.src,photo:h,layout:m,layoutOptions:n,renderPhoto:r,imageProps:i}))))):null}function DH(e,t,n,r){const o=new Map,i=new Set;i.add(n);for(let s=0;s{const d=s>0?o.get(u)[s].weight:0;e(u).forEach(({neighbor:h,weight:m})=>{let g=o.get(h);g||(g=[],o.set(h,g));const y=d+m,x=g[s+1];(!x||x.weight>y&&(x.weight/y>1.0001||u0;i-=1)o=e.get(o)[i].node,r.push(o);return r.reverse()}function LH(e,t,n,r){return IH(DH(e,t,n,r),t,r)}function FH({photos:e,spacing:t,padding:n,targetColumnWidth:r,targetColumnHeight:o}){return i=>{const s=[],l=o*1.5;let u=r/Vr(e[i])+2*n;for(let d=i+1;dl||d===e.length));d+=1)u+=r/Vr(e[d])+t+2*n;return s}}function s2({path:e,photos:t,containerWidth:n,columnsGaps:r,columnsRatios:o,spacing:i,padding:s}){const l=[],u=o.reduce((d,h)=>d+h,0);for(let d=0;d({photo:y,index:x})).slice(e[d],e[d+1]),m=o.reduce((y,x,_)=>y+(r[d]-r[_])*x,0),g=(n-(e.length-2)*i-2*(e.length-1)*s-m)*o[d]/u;l.push(h.map(({photo:y,index:x},_)=>({photo:y,layout:{width:g,height:g/Vr(y),index:x,photoIndex:_,photosCount:h.length}})))}return l}function jH({photos:e,layoutOptions:t,targetColumnWidth:n}){const{columns:r,spacing:o,padding:i,containerWidth:s}=t,l=[],u=[];if(e.length<=r){const y=e.length>0?e.reduce((_,C)=>_+Vr(C),0)/e.length:1;for(let _=0;_Math.min(C,e.length)),photos:e,columnsRatios:u,columnsGaps:l,containerWidth:s,spacing:o,padding:i});return{columnsGaps:l,columnsRatios:u,columnsModel:x}}const d=(e.reduce((y,x)=>y+n/Vr(x),0)+o*(e.length-r)+2*i*e.length)/r,h=FH({photos:e,targetColumnWidth:n,targetColumnHeight:d,spacing:o,padding:i}),m=LH(h,r,0,e.length);for(let y=0;y_+1/Vr(C),0)}const g=s2({path:m,photos:e,columnsRatios:u,columnsGaps:l,containerWidth:s,spacing:o,padding:i});return{columnsGaps:l,columnsRatios:u,columnsModel:g}}function DP(e){const{photos:t,layoutOptions:n}=e,{columns:r,spacing:o,padding:i,containerWidth:s}=n,l=(s-o*(r-1)-2*i*r)/r,{columnsGaps:u,columnsRatios:d,columnsModel:h}=jH({photos:t,layoutOptions:n,targetColumnWidth:l});return h.findIndex(m=>m.findIndex(({layout:{width:g,height:y}})=>g<0||y<0)>=0)>=0?r>1?DP({photos:t,layoutOptions:{...n,columns:r-1}}):void 0:{columnsModel:h,columnsGaps:u,columnsRatios:d}}function zH({photos:e,layoutOptions:t}){return DP({photos:e,layoutOptions:t})}function BH({columnContainerProps:e,children:t}){return f.createElement("div",{...e},t)}function UH(e){const{layoutOptions:t,columnIndex:n,columnsCount:r,columnsGaps:o,columnsRatios:i}=e,{layout:s,spacing:l,padding:u}=t;if(s==="masonry"||!o||!i)return`calc((100% - ${l*(r-1)}px) / ${r})`;const d=i.reduce((m,g)=>m+g,0),h=i.reduce((m,g,y)=>m+(o[n]-o[y])*g,0);return`calc((100% - ${Fh((r-1)*l+2*r*u+h,3)}px) * ${Fh(i[n]/d,5)} + ${2*u}px)`}function IP(e){const{layoutOptions:t,renderColumnContainer:n,children:r,columnContainerProps:{style:o,className:i,...s}={},...l}=e,u={className:qm("react-photo-album--column",i),style:{display:"flex",flexDirection:"column",flexWrap:"nowrap",alignItems:"flex-start",width:UH(e),justifyContent:t.layout==="columns"?"space-between":"flex-start",...o},...s};return f.createElement(f.Fragment,null,(n??BH)({layoutOptions:t,columnContainerProps:u,children:r,...l}))}function VH(e){const{photos:t,layoutOptions:n,renderPhoto:r,renderColumnContainer:o,componentsProps:{imageProps:i,columnContainerProps:s}}=e,l=zH({photos:t,layoutOptions:n});if(!l)return null;const{columnsModel:u,columnsRatios:d,columnsGaps:h}=l;return f.createElement(f.Fragment,null,u.map((m,g)=>f.createElement(IP,{key:`column-${g}`,layoutOptions:n,columnIndex:g,columnsCount:u.length,columnsGaps:h,columnsRatios:d,renderColumnContainer:o,columnContainerProps:s},m.map(({photo:y,layout:x})=>f.createElement(Ox,{key:y.key||y.src,photo:y,layout:x,layoutOptions:n,renderPhoto:r,imageProps:i})))))}function LP(e){const{photos:t,layoutOptions:n}=e,{columns:r,spacing:o,padding:i,containerWidth:s}=n,l=(s-o*(r-1)-2*i*r)/r;if(l<=0)return r>1?LP({...e,layoutOptions:{...n,columns:r-1}}):void 0;const u=[];for(let h=0;h{const y=u.reduce((x,_,C)=>_[])).map(h=>h.map(({photo:m,index:g},y)=>({photo:m,layout:{width:l,height:l/Vr(m),index:g,photoIndex:y,photosCount:h.length}})))}function WH(e){const{photos:t,layoutOptions:n,renderPhoto:r,renderColumnContainer:o,componentsProps:{imageProps:i,columnContainerProps:s}}=e,l=LP({photos:t,layoutOptions:n});return l?f.createElement(f.Fragment,null,l.map((u,d)=>f.createElement(IP,{key:`masonry-column-${d}`,layoutOptions:n,columnsCount:l.length,columnIndex:d,renderColumnContainer:o,columnContainerProps:s},u.map(({photo:h,layout:m})=>f.createElement(Ox,{key:h.key||h.src,photo:h,layout:m,layoutOptions:n,renderPhoto:r,imageProps:i}))))):null}function HH({containerProps:e,children:t,containerRef:n}){return f.createElement("div",{ref:n,...e},t)}function KH(e){const{layout:t,renderContainer:n,children:r,containerRef:o,containerProps:{style:i,className:s,...l}={}}=e,u={className:qm("react-photo-album",`react-photo-album--${t}`,s),style:{display:"flex",flexWrap:"nowrap",justifyContent:"space-between",flexDirection:t==="rows"?"column":"row",...i},...l};return f.createElement(f.Fragment,null,(n??HH)({containerProps:u,containerRef:o,layout:t,children:r}))}function YH(e){const t=f.useRef(e);return(!e||!t.current||e.join()!==t.current.join())&&(t.current=e),t.current}function GH(e,{newContainerWidth:t,newScrollbarWidth:n}){const{containerWidth:r,scrollbarWidth:o}=e;return r!==void 0&&o!==void 0&&t!==void 0&&n!==void 0&&t>r&&t-r<=20&&n0){const r=[...t.filter(i=>i>0)].sort((i,s)=>s-i);r.push(Math.floor(r[r.length-1]/2));const o=n;n=r.find((i,s)=>i<=o||s===r.length-1)}return n}function ZH(e,t){const[{containerWidth:n},r]=f.useReducer(GH,{containerWidth:t}),o=f.useRef(null),i=f.useRef();return{containerRef:f.useCallback(l=>{var u;(u=i.current)==null||u.disconnect(),i.current=void 0,o.current=l;const d=()=>r({newContainerWidth:XH(o.current,e),newScrollbarWidth:window.innerWidth-document.documentElement.clientWidth});d(),l&&typeof ResizeObserver<"u"&&(i.current=new ResizeObserver(d),i.current.observe(l))},[e]),containerWidth:n}}const qH=Object.freeze([1200,600,300,0]);function Mx(e,t){return typeof e=="function"?e(t):e}function FP(e,t){return typeof e<"u"?Mx(e,t):void 0}function QH(e,t){const n=qH.findIndex(r=>r<=t);return Mx(e[n>=0?n:0],t)}function fp(e,t,n,r=0){const o=FP(e,t);return Math.round(Math.max(o===void 0?QH(n,t):o,r))}function JH({layout:e,onClick:t,containerWidth:n,targetRowHeight:r,rowConstraints:o,columns:i,spacing:s,padding:l,sizes:u}){return{layout:e,onClick:t,containerWidth:n,columns:fp(i,n,[5,4,3,2],1),spacing:fp(s,n,[20,15,10,5]),padding:fp(l,n,[0,0,0,0,0]),targetRowHeight:fp(r,n,[d=>d/5,d=>d/4,d=>d/3,d=>d/2]),rowConstraints:FP(o,n),sizes:u}}function eK(e,t,n){const{photos:r,componentsProps:o}=e,i=Mx(o,t)||{};if(n){const{layout:s,spacing:l,padding:u,rowConstraints:d}=n;if(s==="rows"){const{singleRowMaxHeight:h}=d||{};if(h){const m=Math.floor(r.reduce((g,{width:y,height:x})=>g+y/x*h-2*u,u*r.length*2+l*(r.length-1)));m>0&&(i.containerProps=i.containerProps||{},i.containerProps.style={maxWidth:m,...i.containerProps.style})}}}return i}function tK(e,t,n){const{photos:r,layout:o,renderPhoto:i,renderRowContainer:s,renderColumnContainer:l}=e,u={photos:r,renderPhoto:i,componentsProps:t};return o==="rows"?f.createElement(NH,{layoutOptions:n,renderRowContainer:s,...u}):o==="columns"?f.createElement(VH,{layoutOptions:n,renderColumnContainer:l,...u}):f.createElement(WH,{layoutOptions:n,renderColumnContainer:l,...u})}function nK(e){const{photos:t,layout:n,renderContainer:r,defaultContainerWidth:o,breakpoints:i}=e,{containerRef:s,containerWidth:l}=ZH(YH(i),o);if(!n||!["rows","columns","masonry"].includes(n)||!Array.isArray(t))return null;const u=l?JH({containerWidth:l,...e}):void 0,d=eK(e,l,u);return f.createElement(KH,{layout:n,containerRef:s,renderContainer:r,containerProps:d.containerProps},u&&tK(e,d,u))}function rK({title:e,titleId:t,...n},r){return f.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true",ref:r,"aria-labelledby":t},n),e?f.createElement("title",{id:t},e):null,f.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3 4.5h14.25M3 9h9.75M3 13.5h9.75m4.5-4.5v12m0 0l-3.75-3.75M17.25 21L21 17.25"}))}const oK=f.forwardRef(rK),iK=oK;function sK({title:e,titleId:t,...n},r){return f.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true",ref:r,"aria-labelledby":t},n),e?f.createElement("title",{id:t},e):null,f.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3 4.5h14.25M3 9h9.75M3 13.5h5.25m5.25-.75L17.25 9m0 0L21 12.75M17.25 9v12"}))}const aK=f.forwardRef(sK),lK=aK;function cK({title:e,titleId:t,...n},r){return f.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true",ref:r,"aria-labelledby":t},n),e?f.createElement("title",{id:t},e):null,f.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15.042 21.672L13.684 16.6m0 0l-2.51 2.225.569-9.47 5.227 7.917-3.286-.672zM12 2.25V4.5m5.834.166l-1.591 1.591M20.25 10.5H18M7.757 14.743l-1.59 1.59M6 10.5H3.75m4.007-4.243l-1.59-1.59"}))}const uK=f.forwardRef(cK),dK=uK;function bi(e){return Array.isArray?Array.isArray(e):BP(e)==="[object Array]"}const fK=1/0;function pK(e){if(typeof e=="string")return e;let t=e+"";return t=="0"&&1/e==-fK?"-0":t}function hK(e){return e==null?"":pK(e)}function Lo(e){return typeof e=="string"}function jP(e){return typeof e=="number"}function mK(e){return e===!0||e===!1||gK(e)&&BP(e)=="[object Boolean]"}function zP(e){return typeof e=="object"}function gK(e){return zP(e)&&e!==null}function hr(e){return e!=null}function k0(e){return!e.trim().length}function BP(e){return e==null?e===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}const vK="Incorrect 'index' type",yK=e=>`Invalid value for key ${e}`,wK=e=>`Pattern length exceeds max of ${e}.`,xK=e=>`Missing ${e} property in key`,bK=e=>`Property 'weight' in key '${e}' must be a positive integer`,a2=Object.prototype.hasOwnProperty;class _K{constructor(t){this._keys=[],this._keyMap={};let n=0;t.forEach(r=>{let o=UP(r);this._keys.push(o),this._keyMap[o.id]=o,n+=o.weight}),this._keys.forEach(r=>{r.weight/=n})}get(t){return this._keyMap[t]}keys(){return this._keys}toJSON(){return JSON.stringify(this._keys)}}function UP(e){let t=null,n=null,r=null,o=1,i=null;if(Lo(e)||bi(e))r=e,t=l2(e),n=h1(e);else{if(!a2.call(e,"name"))throw new Error(xK("name"));const s=e.name;if(r=s,a2.call(e,"weight")&&(o=e.weight,o<=0))throw new Error(bK(s));t=l2(s),n=h1(s),i=e.getFn}return{path:t,id:n,weight:o,src:r,getFn:i}}function l2(e){return bi(e)?e:e.split(".")}function h1(e){return bi(e)?e.join("."):e}function SK(e,t){let n=[],r=!1;const o=(i,s,l)=>{if(hr(i))if(!s[l])n.push(i);else{let u=s[l];const d=i[u];if(!hr(d))return;if(l===s.length-1&&(Lo(d)||jP(d)||mK(d)))n.push(hK(d));else if(bi(d)){r=!0;for(let h=0,m=d.length;he.score===t.score?e.idx{this._keysMap[n.id]=r})}create(){this.isCreated||!this.docs.length||(this.isCreated=!0,Lo(this.docs[0])?this.docs.forEach((t,n)=>{this._addString(t,n)}):this.docs.forEach((t,n)=>{this._addObject(t,n)}),this.norm.clear())}add(t){const n=this.size();Lo(t)?this._addString(t,n):this._addObject(t,n)}removeAt(t){this.records.splice(t,1);for(let n=t,r=this.size();n{let s=o.getFn?o.getFn(t):this.getFn(t,o.path);if(hr(s)){if(bi(s)){let l=[];const u=[{nestedArrIndex:-1,value:s}];for(;u.length;){const{nestedArrIndex:d,value:h}=u.pop();if(hr(h))if(Lo(h)&&!k0(h)){let m={v:h,i:d,n:this.norm.get(h)};l.push(m)}else bi(h)&&h.forEach((m,g)=>{u.push({nestedArrIndex:g,value:m})})}r.$[i]=l}else if(Lo(s)&&!k0(s)){let l={v:s,n:this.norm.get(s)};r.$[i]=l}}}),this.records.push(r)}toJSON(){return{keys:this.keys,records:this.records}}}function VP(e,t,{getFn:n=He.getFn,fieldNormWeight:r=He.fieldNormWeight}={}){const o=new Nx({getFn:n,fieldNormWeight:r});return o.setKeys(e.map(UP)),o.setSources(t),o.create(),o}function PK(e,{getFn:t=He.getFn,fieldNormWeight:n=He.fieldNormWeight}={}){const{keys:r,records:o}=e,i=new Nx({getFn:t,fieldNormWeight:n});return i.setKeys(r),i.setIndexRecords(o),i}function pp(e,{errors:t=0,currentLocation:n=0,expectedLocation:r=0,distance:o=He.distance,ignoreLocation:i=He.ignoreLocation}={}){const s=t/e.length;if(i)return s;const l=Math.abs(r-n);return o?s+l/o:l?1:s}function AK(e=[],t=He.minMatchCharLength){let n=[],r=-1,o=-1,i=0;for(let s=e.length;i=t&&n.push([r,o]),r=-1)}return e[i-1]&&i-r>=t&&n.push([r,i-1]),n}const ea=32;function OK(e,t,n,{location:r=He.location,distance:o=He.distance,threshold:i=He.threshold,findAllMatches:s=He.findAllMatches,minMatchCharLength:l=He.minMatchCharLength,includeMatches:u=He.includeMatches,ignoreLocation:d=He.ignoreLocation}={}){if(t.length>ea)throw new Error(wK(ea));const h=t.length,m=e.length,g=Math.max(0,Math.min(r,m));let y=i,x=g;const _=l>1||u,C=_?Array(m):[];let S;for(;(S=e.indexOf(t,x))>-1;){let A=pp(t,{currentLocation:S,expectedLocation:g,distance:o,ignoreLocation:d});if(y=Math.min(A,y),x=S+h,_){let O=0;for(;O=V;U-=1){let te=U-1,L=n[e.charAt(te)];if(_&&(C[te]=+!!L),G[U]=(G[U+1]<<1|1)&L,A&&(G[U]|=(b[U+1]|b[U])<<1|1|b[U+1]),G[U]&P&&(E=pp(t,{errors:A,currentLocation:te,expectedLocation:g,distance:o,ignoreLocation:d}),E<=y)){if(y=E,x=te,x<=g)break;V=Math.max(1,2*g-x)}}if(pp(t,{errors:A+1,currentLocation:g,expectedLocation:g,distance:o,ignoreLocation:d})>y)break;b=G}const M={isMatch:x>=0,score:Math.max(.001,E)};if(_){const A=AK(C,l);A.length?u&&(M.indices=A):M.isMatch=!1}return M}function MK(e){let t={};for(let n=0,r=e.length;n{this.chunks.push({pattern:g,alphabet:MK(g),startIndex:y})},m=this.pattern.length;if(m>ea){let g=0;const y=m%ea,x=m-y;for(;g{const{isMatch:S,score:b,indices:E}=OK(t,x,_,{location:o+C,distance:i,threshold:s,findAllMatches:l,minMatchCharLength:u,includeMatches:r,ignoreLocation:d});S&&(g=!0),m+=b,S&&E&&(h=[...h,...E])});let y={isMatch:g,score:g?m/this.chunks.length:1};return g&&r&&(y.indices=h),y}}class Ds{constructor(t){this.pattern=t}static isMultiMatch(t){return c2(t,this.multiRegex)}static isSingleMatch(t){return c2(t,this.singleRegex)}search(){}}function c2(e,t){const n=e.match(t);return n?n[1]:null}class NK extends Ds{constructor(t){super(t)}static get type(){return"exact"}static get multiRegex(){return/^="(.*)"$/}static get singleRegex(){return/^=(.*)$/}search(t){const n=t===this.pattern;return{isMatch:n,score:n?0:1,indices:[0,this.pattern.length-1]}}}class DK extends Ds{constructor(t){super(t)}static get type(){return"inverse-exact"}static get multiRegex(){return/^!"(.*)"$/}static get singleRegex(){return/^!(.*)$/}search(t){const r=t.indexOf(this.pattern)===-1;return{isMatch:r,score:r?0:1,indices:[0,t.length-1]}}}class IK extends Ds{constructor(t){super(t)}static get type(){return"prefix-exact"}static get multiRegex(){return/^\^"(.*)"$/}static get singleRegex(){return/^\^(.*)$/}search(t){const n=t.startsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[0,this.pattern.length-1]}}}class LK extends Ds{constructor(t){super(t)}static get type(){return"inverse-prefix-exact"}static get multiRegex(){return/^!\^"(.*)"$/}static get singleRegex(){return/^!\^(.*)$/}search(t){const n=!t.startsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[0,t.length-1]}}}class FK extends Ds{constructor(t){super(t)}static get type(){return"suffix-exact"}static get multiRegex(){return/^"(.*)"\$$/}static get singleRegex(){return/^(.*)\$$/}search(t){const n=t.endsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[t.length-this.pattern.length,t.length-1]}}}class jK extends Ds{constructor(t){super(t)}static get type(){return"inverse-suffix-exact"}static get multiRegex(){return/^!"(.*)"\$$/}static get singleRegex(){return/^!(.*)\$$/}search(t){const n=!t.endsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[0,t.length-1]}}}class HP extends Ds{constructor(t,{location:n=He.location,threshold:r=He.threshold,distance:o=He.distance,includeMatches:i=He.includeMatches,findAllMatches:s=He.findAllMatches,minMatchCharLength:l=He.minMatchCharLength,isCaseSensitive:u=He.isCaseSensitive,ignoreLocation:d=He.ignoreLocation}={}){super(t),this._bitapSearch=new WP(t,{location:n,threshold:r,distance:o,includeMatches:i,findAllMatches:s,minMatchCharLength:l,isCaseSensitive:u,ignoreLocation:d})}static get type(){return"fuzzy"}static get multiRegex(){return/^"(.*)"$/}static get singleRegex(){return/^(.*)$/}search(t){return this._bitapSearch.searchIn(t)}}class KP extends Ds{constructor(t){super(t)}static get type(){return"include"}static get multiRegex(){return/^'"(.*)"$/}static get singleRegex(){return/^'(.*)$/}search(t){let n=0,r;const o=[],i=this.pattern.length;for(;(r=t.indexOf(this.pattern,n))>-1;)n=r+i,o.push([r,n-1]);const s=!!o.length;return{isMatch:s,score:s?0:1,indices:o}}}const m1=[NK,KP,IK,LK,jK,FK,DK,HP],u2=m1.length,zK=/ +(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/,BK="|";function UK(e,t={}){return e.split(BK).map(n=>{let r=n.trim().split(zK).filter(i=>i&&!!i.trim()),o=[];for(let i=0,s=r.length;i!!(e[jh.AND]||e[jh.OR]),KK=e=>!!e[y1.PATH],YK=e=>!bi(e)&&zP(e)&&!w1(e),d2=e=>({[jh.AND]:Object.keys(e).map(t=>({[t]:e[t]}))});function YP(e,t,{auto:n=!0}={}){const r=o=>{let i=Object.keys(o);const s=KK(o);if(!s&&i.length>1&&!w1(o))return r(d2(o));if(YK(o)){const u=s?o[y1.PATH]:i[0],d=s?o[y1.PATTERN]:o[u];if(!Lo(d))throw new Error(yK(u));const h={keyId:h1(u),pattern:d};return n&&(h.searcher=v1(d,t)),h}let l={children:[],operator:i[0]};return i.forEach(u=>{const d=o[u];bi(d)&&d.forEach(h=>{l.children.push(r(h))})}),l};return w1(e)||(e=d2(e)),r(e)}function GK(e,{ignoreFieldNorm:t=He.ignoreFieldNorm}){e.forEach(n=>{let r=1;n.matches.forEach(({key:o,norm:i,score:s})=>{const l=o?o.weight:null;r*=Math.pow(s===0&&l?Number.EPSILON:s,(l||1)*(t?1:i))}),n.score=r})}function XK(e,t){const n=e.matches;t.matches=[],hr(n)&&n.forEach(r=>{if(!hr(r.indices)||!r.indices.length)return;const{indices:o,value:i}=r;let s={indices:o,value:i};r.key&&(s.key=r.key.src),r.idx>-1&&(s.refIndex=r.idx),t.matches.push(s)})}function ZK(e,t){t.score=e.score}function qK(e,t,{includeMatches:n=He.includeMatches,includeScore:r=He.includeScore}={}){const o=[];return n&&o.push(XK),r&&o.push(ZK),e.map(i=>{const{idx:s}=i,l={item:t[s],refIndex:s};return o.length&&o.forEach(u=>{u(i,l)}),l})}class _c{constructor(t,n={},r){this.options={...He,...n},this.options.useExtendedSearch,this._keyStore=new _K(this.options.keys),this.setCollection(t,r)}setCollection(t,n){if(this._docs=t,n&&!(n instanceof Nx))throw new Error(vK);this._myIndex=n||VP(this.options.keys,this._docs,{getFn:this.options.getFn,fieldNormWeight:this.options.fieldNormWeight})}add(t){hr(t)&&(this._docs.push(t),this._myIndex.add(t))}remove(t=()=>!1){const n=[];for(let r=0,o=this._docs.length;r-1&&(u=u.slice(0,n)),qK(u,this._docs,{includeMatches:r,includeScore:o})}_searchStringList(t){const n=v1(t,this.options),{records:r}=this._myIndex,o=[];return r.forEach(({v:i,i:s,n:l})=>{if(!hr(i))return;const{isMatch:u,score:d,indices:h}=n.searchIn(i);u&&o.push({item:i,idx:s,matches:[{score:d,value:i,norm:l,indices:h}]})}),o}_searchLogical(t){const n=YP(t,this.options),r=(l,u,d)=>{if(!l.children){const{keyId:m,searcher:g}=l,y=this._findMatches({key:this._keyStore.get(m),value:this._myIndex.getValueForItemAtKeyId(u,m),searcher:g});return y&&y.length?[{idx:d,item:u,matches:y}]:[]}const h=[];for(let m=0,g=l.children.length;m{if(hr(l)){let d=r(n,l,u);d.length&&(i[u]||(i[u]={idx:u,item:l,matches:[]},s.push(i[u])),d.forEach(({matches:h})=>{i[u].matches.push(...h)}))}}),s}_searchObjectList(t){const n=v1(t,this.options),{keys:r,records:o}=this._myIndex,i=[];return o.forEach(({$:s,i:l})=>{if(!hr(s))return;let u=[];r.forEach((d,h)=>{u.push(...this._findMatches({key:d,value:s[h],searcher:n}))}),u.length&&i.push({idx:l,item:s,matches:u})}),i}_findMatches({key:t,value:n,searcher:r}){if(!hr(n))return[];let o=[];if(bi(n))n.forEach(({v:i,i:s,n:l})=>{if(!hr(i))return;const{isMatch:u,score:d,indices:h}=r.searchIn(i);u&&o.push({score:d,key:t,value:i,idx:s,norm:l,indices:h})});else{const{v:i,n:s}=n,{isMatch:l,score:u,indices:d}=r.searchIn(i);l&&o.push({score:u,key:t,value:i,norm:s,indices:d})}return o}}_c.version="7.0.0";_c.createIndex=VP;_c.parseIndex=PK;_c.config=He;_c.parseQuery=YP;HK(WK);function zd(e){const t=e+"CollectionProvider",[n,r]=An(t),[o,i]=n(t,{collectionRef:{current:null},itemMap:new Map}),s=y=>{const{scope:x,children:_}=y,C=Fe.useRef(null),S=Fe.useRef(new Map).current;return Fe.createElement(o,{scope:x,itemMap:S,collectionRef:C},_)},l=e+"CollectionSlot",u=Fe.forwardRef((y,x)=>{const{scope:_,children:C}=y,S=i(l,_),b=Be(x,S.collectionRef);return Fe.createElement(Wo,{ref:b},C)}),d=e+"CollectionItemSlot",h="data-radix-collection-item",m=Fe.forwardRef((y,x)=>{const{scope:_,children:C,...S}=y,b=Fe.useRef(null),E=Be(x,b),k=i(d,_);return Fe.useEffect(()=>(k.itemMap.set(b,{ref:b,...S}),()=>void k.itemMap.delete(b))),Fe.createElement(Wo,{[h]:"",ref:E},C)});function g(y){const x=i(e+"CollectionConsumer",y);return Fe.useCallback(()=>{const C=x.collectionRef.current;if(!C)return[];const S=Array.from(C.querySelectorAll(`[${h}]`));return Array.from(x.itemMap.values()).sort((k,P)=>S.indexOf(k.ref.current)-S.indexOf(P.ref.current))},[x.collectionRef,x.itemMap])}return[{Provider:s,Slot:u,ItemSlot:m},g,r]}const QK=f.createContext(void 0);function Sc(e){const t=f.useContext(QK);return e||t||"ltr"}const R0="rovingFocusGroup.onEntryFocus",JK={bubbles:!1,cancelable:!0},Dx="RovingFocusGroup",[x1,GP,eY]=zd(Dx),[tY,Qm]=An(Dx,[eY]),[nY,rY]=tY(Dx),oY=f.forwardRef((e,t)=>f.createElement(x1.Provider,{scope:e.__scopeRovingFocusGroup},f.createElement(x1.Slot,{scope:e.__scopeRovingFocusGroup},f.createElement(iY,Y({},e,{ref:t}))))),iY=f.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:o=!1,dir:i,currentTabStopId:s,defaultCurrentTabStopId:l,onCurrentTabStopIdChange:u,onEntryFocus:d,...h}=e,m=f.useRef(null),g=Be(t,m),y=Sc(i),[x=null,_]=Zr({prop:s,defaultProp:l,onChange:u}),[C,S]=f.useState(!1),b=Ft(d),E=GP(n),k=f.useRef(!1),[P,M]=f.useState(0);return f.useEffect(()=>{const A=m.current;if(A)return A.addEventListener(R0,b),()=>A.removeEventListener(R0,b)},[b]),f.createElement(nY,{scope:n,orientation:r,dir:y,loop:o,currentTabStopId:x,onItemFocus:f.useCallback(A=>_(A),[_]),onItemShiftTab:f.useCallback(()=>S(!0),[]),onFocusableItemAdd:f.useCallback(()=>M(A=>A+1),[]),onFocusableItemRemove:f.useCallback(()=>M(A=>A-1),[])},f.createElement(Pe.div,Y({tabIndex:C||P===0?-1:0,"data-orientation":r},h,{ref:g,style:{outline:"none",...e.style},onMouseDown:ue(e.onMouseDown,()=>{k.current=!0}),onFocus:ue(e.onFocus,A=>{const O=!k.current;if(A.target===A.currentTarget&&O&&!C){const F=new CustomEvent(R0,JK);if(A.currentTarget.dispatchEvent(F),!F.defaultPrevented){const V=E().filter(te=>te.focusable),J=V.find(te=>te.active),G=V.find(te=>te.id===x),U=[J,G,...V].filter(Boolean).map(te=>te.ref.current);XP(U)}}k.current=!1}),onBlur:ue(e.onBlur,()=>S(!1))})))}),sY="RovingFocusGroupItem",aY=f.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:o=!1,tabStopId:i,...s}=e,l=nr(),u=i||l,d=rY(sY,n),h=d.currentTabStopId===u,m=GP(n),{onFocusableItemAdd:g,onFocusableItemRemove:y}=d;return f.useEffect(()=>{if(r)return g(),()=>y()},[r,g,y]),f.createElement(x1.ItemSlot,{scope:n,id:u,focusable:r,active:o},f.createElement(Pe.span,Y({tabIndex:h?0:-1,"data-orientation":d.orientation},s,{ref:t,onMouseDown:ue(e.onMouseDown,x=>{r?d.onItemFocus(u):x.preventDefault()}),onFocus:ue(e.onFocus,()=>d.onItemFocus(u)),onKeyDown:ue(e.onKeyDown,x=>{if(x.key==="Tab"&&x.shiftKey){d.onItemShiftTab();return}if(x.target!==x.currentTarget)return;const _=uY(x,d.orientation,d.dir);if(_!==void 0){x.preventDefault();let S=m().filter(b=>b.focusable).map(b=>b.ref.current);if(_==="last")S.reverse();else if(_==="prev"||_==="next"){_==="prev"&&S.reverse();const b=S.indexOf(x.currentTarget);S=d.loop?dY(S,b+1):S.slice(b+1)}setTimeout(()=>XP(S))}})})))}),lY={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function cY(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function uY(e,t,n){const r=cY(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return lY[r]}function XP(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function dY(e,t){return e.map((n,r)=>e[(t+r)%e.length])}const ZP=oY,qP=aY,QP="Tabs",[fY,xte]=An(QP,[Qm]),JP=Qm(),[pY,Ix]=fY(QP),hY=f.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,onValueChange:o,defaultValue:i,orientation:s="horizontal",dir:l,activationMode:u="automatic",...d}=e,h=Sc(l),[m,g]=Zr({prop:r,onChange:o,defaultProp:i});return f.createElement(pY,{scope:n,baseId:nr(),value:m,onValueChange:g,orientation:s,dir:h,activationMode:u},f.createElement(Pe.div,Y({dir:h,"data-orientation":s},d,{ref:t})))}),mY="TabsList",gY=f.forwardRef((e,t)=>{const{__scopeTabs:n,loop:r=!0,...o}=e,i=Ix(mY,n),s=JP(n);return f.createElement(ZP,Y({asChild:!0},s,{orientation:i.orientation,dir:i.dir,loop:r}),f.createElement(Pe.div,Y({role:"tablist","aria-orientation":i.orientation},o,{ref:t})))}),vY="TabsTrigger",yY=f.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,disabled:o=!1,...i}=e,s=Ix(vY,n),l=JP(n),u=e5(s.baseId,r),d=t5(s.baseId,r),h=r===s.value;return f.createElement(qP,Y({asChild:!0},l,{focusable:!o,active:h}),f.createElement(Pe.button,Y({type:"button",role:"tab","aria-selected":h,"aria-controls":d,"data-state":h?"active":"inactive","data-disabled":o?"":void 0,disabled:o,id:u},i,{ref:t,onMouseDown:ue(e.onMouseDown,m=>{!o&&m.button===0&&m.ctrlKey===!1?s.onValueChange(r):m.preventDefault()}),onKeyDown:ue(e.onKeyDown,m=>{[" ","Enter"].includes(m.key)&&s.onValueChange(r)}),onFocus:ue(e.onFocus,()=>{const m=s.activationMode!=="manual";!h&&!o&&m&&s.onValueChange(r)})})))}),wY="TabsContent",xY=f.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,forceMount:o,children:i,...s}=e,l=Ix(wY,n),u=e5(l.baseId,r),d=t5(l.baseId,r),h=r===l.value,m=f.useRef(h);return f.useEffect(()=>{const g=requestAnimationFrame(()=>m.current=!1);return()=>cancelAnimationFrame(g)},[]),f.createElement(xn,{present:o||h},({present:g})=>f.createElement(Pe.div,Y({"data-state":h?"active":"inactive","data-orientation":l.orientation,role:"tabpanel","aria-labelledby":u,hidden:!g,id:d,tabIndex:0},s,{ref:t,style:{...e.style,animationDuration:m.current?"0s":void 0}}),g&&i))});function e5(e,t){return`${e}-trigger-${t}`}function t5(e,t){return`${e}-content-${t}`}const bY=hY,n5=gY,r5=yY,o5=xY,i5=bY,Lx=f.forwardRef(({className:e,...t},n)=>v.jsx(n5,{ref:n,className:Ce("inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground",e),tabIndex:-1,...t}));Lx.displayName=n5.displayName;const sa=f.forwardRef(({className:e,...t},n)=>v.jsx(r5,{ref:n,className:Ce("inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow",e),tabIndex:-1,...t}));sa.displayName=r5.displayName;const mu=f.forwardRef(({className:e,...t},n)=>v.jsx(o5,{ref:n,className:Ce("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",e),tabIndex:-1,...t}));mu.displayName=o5.displayName;function id(e,[t,n]){return Math.min(n,Math.max(t,e))}function Fx(e){const t=f.useRef({value:e,previous:e});return f.useMemo(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}const _Y=[" ","Enter","ArrowUp","ArrowDown"],SY=[" ","Enter"],Jm="Select",[eg,tg,EY]=zd(Jm),[Ec,bte]=An(Jm,[EY,Ns]),jx=Ns(),[CY,Oa]=Ec(Jm),[$Y,kY]=Ec(Jm),RY=e=>{const{__scopeSelect:t,children:n,open:r,defaultOpen:o,onOpenChange:i,value:s,defaultValue:l,onValueChange:u,dir:d,name:h,autoComplete:m,disabled:g,required:y}=e,x=jx(t),[_,C]=f.useState(null),[S,b]=f.useState(null),[E,k]=f.useState(!1),P=Sc(d),[M=!1,A]=Zr({prop:r,defaultProp:o,onChange:i}),[O,F]=Zr({prop:s,defaultProp:l,onChange:u}),V=f.useRef(null),J=_?!!_.closest("form"):!0,[G,ae]=f.useState(new Set),U=Array.from(G).map(te=>te.props.value).join(";");return f.createElement(Od,x,f.createElement(CY,{required:y,scope:t,trigger:_,onTriggerChange:C,valueNode:S,onValueNodeChange:b,valueNodeHasChildren:E,onValueNodeHasChildrenChange:k,contentId:nr(),value:O,onValueChange:F,open:M,onOpenChange:A,dir:P,triggerPointerDownPosRef:V,disabled:g},f.createElement(eg.Provider,{scope:t},f.createElement($Y,{scope:e.__scopeSelect,onNativeOptionAdd:f.useCallback(te=>{ae(L=>new Set(L).add(te))},[]),onNativeOptionRemove:f.useCallback(te=>{ae(L=>{const ie=new Set(L);return ie.delete(te),ie})},[])},n)),J?f.createElement(u5,{key:U,"aria-hidden":!0,required:y,tabIndex:-1,name:h,autoComplete:m,value:O,onChange:te=>F(te.target.value),disabled:g},O===void 0?f.createElement("option",{value:""}):null,Array.from(G)):null))},TY="SelectTrigger",PY=f.forwardRef((e,t)=>{const{__scopeSelect:n,disabled:r=!1,...o}=e,i=jx(n),s=Oa(TY,n),l=s.disabled||r,u=Be(t,s.onTriggerChange),d=tg(n),[h,m,g]=d5(x=>{const _=d().filter(b=>!b.disabled),C=_.find(b=>b.value===s.value),S=f5(_,x,C);S!==void 0&&s.onValueChange(S.value)}),y=()=>{l||(s.onOpenChange(!0),g())};return f.createElement(zm,Y({asChild:!0},i),f.createElement(Pe.button,Y({type:"button",role:"combobox","aria-controls":s.contentId,"aria-expanded":s.open,"aria-required":s.required,"aria-autocomplete":"none",dir:s.dir,"data-state":s.open?"open":"closed",disabled:l,"data-disabled":l?"":void 0,"data-placeholder":c5(s.value)?"":void 0},o,{ref:u,onClick:ue(o.onClick,x=>{x.currentTarget.focus()}),onPointerDown:ue(o.onPointerDown,x=>{const _=x.target;_.hasPointerCapture(x.pointerId)&&_.releasePointerCapture(x.pointerId),x.button===0&&x.ctrlKey===!1&&(y(),s.triggerPointerDownPosRef.current={x:Math.round(x.pageX),y:Math.round(x.pageY)},x.preventDefault())}),onKeyDown:ue(o.onKeyDown,x=>{const _=h.current!=="";!(x.ctrlKey||x.altKey||x.metaKey)&&x.key.length===1&&m(x.key),!(_&&x.key===" ")&&_Y.includes(x.key)&&(y(),x.preventDefault())})})))}),AY="SelectValue",OY=f.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,children:i,placeholder:s="",...l}=e,u=Oa(AY,n),{onValueNodeHasChildrenChange:d}=u,h=i!==void 0,m=Be(t,u.onValueNodeChange);return Pn(()=>{d(h)},[d,h]),f.createElement(Pe.span,Y({},l,{ref:m,style:{pointerEvents:"none"}}),c5(u.value)?f.createElement(f.Fragment,null,s):i)}),MY=f.forwardRef((e,t)=>{const{__scopeSelect:n,children:r,...o}=e;return f.createElement(Pe.span,Y({"aria-hidden":!0},o,{ref:t}),r||"▼")}),NY=e=>f.createElement(Md,Y({asChild:!0},e)),ic="SelectContent",DY=f.forwardRef((e,t)=>{const n=Oa(ic,e.__scopeSelect),[r,o]=f.useState();if(Pn(()=>{o(new DocumentFragment)},[]),!n.open){const i=r;return i?Os.createPortal(f.createElement(s5,{scope:e.__scopeSelect},f.createElement(eg.Slot,{scope:e.__scopeSelect},f.createElement("div",null,e.children))),i):null}return f.createElement(IY,Y({},e,{ref:t}))}),ai=10,[s5,Ma]=Ec(ic),IY=f.forwardRef((e,t)=>{const{__scopeSelect:n,position:r="item-aligned",onCloseAutoFocus:o,onEscapeKeyDown:i,onPointerDownOutside:s,side:l,sideOffset:u,align:d,alignOffset:h,arrowPadding:m,collisionBoundary:g,collisionPadding:y,sticky:x,hideWhenDetached:_,avoidCollisions:C,...S}=e,b=Oa(ic,n),[E,k]=f.useState(null),[P,M]=f.useState(null),A=Be(t,fe=>k(fe)),[O,F]=f.useState(null),[V,J]=f.useState(null),G=tg(n),[ae,U]=f.useState(!1),te=f.useRef(!1);f.useEffect(()=>{if(E)return Xm(E)},[E]),Km();const L=f.useCallback(fe=>{const[xe,...$e]=G().map(je=>je.ref.current),[Ae]=$e.slice(-1),Oe=document.activeElement;for(const je of fe)if(je===Oe||(je==null||je.scrollIntoView({block:"nearest"}),je===xe&&P&&(P.scrollTop=0),je===Ae&&P&&(P.scrollTop=P.scrollHeight),je==null||je.focus(),document.activeElement!==Oe))return},[G,P]),ie=f.useCallback(()=>L([O,E]),[L,O,E]);f.useEffect(()=>{ae&&ie()},[ae,ie]);const{onOpenChange:K,triggerPointerDownPosRef:Q}=b;f.useEffect(()=>{if(E){let fe={x:0,y:0};const xe=Ae=>{var Oe,je,Ot,ct;fe={x:Math.abs(Math.round(Ae.pageX)-((Oe=(je=Q.current)===null||je===void 0?void 0:je.x)!==null&&Oe!==void 0?Oe:0)),y:Math.abs(Math.round(Ae.pageY)-((Ot=(ct=Q.current)===null||ct===void 0?void 0:ct.y)!==null&&Ot!==void 0?Ot:0))}},$e=Ae=>{fe.x<=10&&fe.y<=10?Ae.preventDefault():E.contains(Ae.target)||K(!1),document.removeEventListener("pointermove",xe),Q.current=null};return Q.current!==null&&(document.addEventListener("pointermove",xe),document.addEventListener("pointerup",$e,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",xe),document.removeEventListener("pointerup",$e,{capture:!0})}}},[E,K,Q]),f.useEffect(()=>{const fe=()=>K(!1);return window.addEventListener("blur",fe),window.addEventListener("resize",fe),()=>{window.removeEventListener("blur",fe),window.removeEventListener("resize",fe)}},[K]);const[W,le]=d5(fe=>{const xe=G().filter(Oe=>!Oe.disabled),$e=xe.find(Oe=>Oe.ref.current===document.activeElement),Ae=f5(xe,fe,$e);Ae&&setTimeout(()=>Ae.ref.current.focus())}),ge=f.useCallback((fe,xe,$e)=>{const Ae=!te.current&&!$e;(b.value!==void 0&&b.value===xe||Ae)&&(F(fe),Ae&&(te.current=!0))},[b.value]),Ve=f.useCallback(()=>E==null?void 0:E.focus(),[E]),Ue=f.useCallback((fe,xe,$e)=>{const Ae=!te.current&&!$e;(b.value!==void 0&&b.value===xe||Ae)&&J(fe)},[b.value]),We=r==="popper"?f2:LY,Me=We===f2?{side:l,sideOffset:u,align:d,alignOffset:h,arrowPadding:m,collisionBoundary:g,collisionPadding:y,sticky:x,hideWhenDetached:_,avoidCollisions:C}:{};return f.createElement(s5,{scope:n,content:E,viewport:P,onViewportChange:M,itemRefCallback:ge,selectedItem:O,onItemLeave:Ve,itemTextRefCallback:Ue,focusSelectedItem:ie,selectedItemText:V,position:r,isPositioned:ae,searchRef:W},f.createElement(Gm,{as:Wo,allowPinchZoom:!0},f.createElement(Hm,{asChild:!0,trapped:b.open,onMountAutoFocus:fe=>{fe.preventDefault()},onUnmountAutoFocus:ue(o,fe=>{var xe;(xe=b.trigger)===null||xe===void 0||xe.focus({preventScroll:!0}),fe.preventDefault()})},f.createElement(yc,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:i,onPointerDownOutside:s,onFocusOutside:fe=>fe.preventDefault(),onDismiss:()=>b.onOpenChange(!1)},f.createElement(We,Y({role:"listbox",id:b.contentId,"data-state":b.open?"open":"closed",dir:b.dir,onContextMenu:fe=>fe.preventDefault()},S,Me,{onPlaced:()=>U(!0),ref:A,style:{display:"flex",flexDirection:"column",outline:"none",...S.style},onKeyDown:ue(S.onKeyDown,fe=>{const xe=fe.ctrlKey||fe.altKey||fe.metaKey;if(fe.key==="Tab"&&fe.preventDefault(),!xe&&fe.key.length===1&&le(fe.key),["ArrowUp","ArrowDown","Home","End"].includes(fe.key)){let Ae=G().filter(Oe=>!Oe.disabled).map(Oe=>Oe.ref.current);if(["ArrowUp","End"].includes(fe.key)&&(Ae=Ae.slice().reverse()),["ArrowUp","ArrowDown"].includes(fe.key)){const Oe=fe.target,je=Ae.indexOf(Oe);Ae=Ae.slice(je+1)}setTimeout(()=>L(Ae)),fe.preventDefault()}})}))))))}),LY=f.forwardRef((e,t)=>{const{__scopeSelect:n,onPlaced:r,...o}=e,i=Oa(ic,n),s=Ma(ic,n),[l,u]=f.useState(null),[d,h]=f.useState(null),m=Be(t,A=>h(A)),g=tg(n),y=f.useRef(!1),x=f.useRef(!0),{viewport:_,selectedItem:C,selectedItemText:S,focusSelectedItem:b}=s,E=f.useCallback(()=>{if(i.trigger&&i.valueNode&&l&&d&&_&&C&&S){const A=i.trigger.getBoundingClientRect(),O=d.getBoundingClientRect(),F=i.valueNode.getBoundingClientRect(),V=S.getBoundingClientRect();if(i.dir!=="rtl"){const Oe=V.left-O.left,je=F.left-Oe,Ot=A.left-je,ct=A.width+Ot,Yt=Math.max(ct,O.width),Er=window.innerWidth-ai,gt=id(je,[ai,Er-Yt]);l.style.minWidth=ct+"px",l.style.left=gt+"px"}else{const Oe=O.right-V.right,je=window.innerWidth-F.right-Oe,Ot=window.innerWidth-A.right-je,ct=A.width+Ot,Yt=Math.max(ct,O.width),Er=window.innerWidth-ai,gt=id(je,[ai,Er-Yt]);l.style.minWidth=ct+"px",l.style.right=gt+"px"}const J=g(),G=window.innerHeight-ai*2,ae=_.scrollHeight,U=window.getComputedStyle(d),te=parseInt(U.borderTopWidth,10),L=parseInt(U.paddingTop,10),ie=parseInt(U.borderBottomWidth,10),K=parseInt(U.paddingBottom,10),Q=te+L+ae+K+ie,W=Math.min(C.offsetHeight*5,Q),le=window.getComputedStyle(_),ge=parseInt(le.paddingTop,10),Ve=parseInt(le.paddingBottom,10),Ue=A.top+A.height/2-ai,We=G-Ue,Me=C.offsetHeight/2,fe=C.offsetTop+Me,xe=te+L+fe,$e=Q-xe;if(xe<=Ue){const Oe=C===J[J.length-1].ref.current;l.style.bottom="0px";const je=d.clientHeight-_.offsetTop-_.offsetHeight,Ot=Math.max(We,Me+(Oe?Ve:0)+je+ie),ct=xe+Ot;l.style.height=ct+"px"}else{const Oe=C===J[0].ref.current;l.style.top="0px";const Ot=Math.max(Ue,te+_.offsetTop+(Oe?ge:0)+Me)+$e;l.style.height=Ot+"px",_.scrollTop=xe-Ue+_.offsetTop}l.style.margin=`${ai}px 0`,l.style.minHeight=W+"px",l.style.maxHeight=G+"px",r==null||r(),requestAnimationFrame(()=>y.current=!0)}},[g,i.trigger,i.valueNode,l,d,_,C,S,i.dir,r]);Pn(()=>E(),[E]);const[k,P]=f.useState();Pn(()=>{d&&P(window.getComputedStyle(d).zIndex)},[d]);const M=f.useCallback(A=>{A&&x.current===!0&&(E(),b==null||b(),x.current=!1)},[E,b]);return f.createElement(FY,{scope:n,contentWrapper:l,shouldExpandOnScrollRef:y,onScrollButtonChange:M},f.createElement("div",{ref:u,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:k}},f.createElement(Pe.div,Y({},o,{ref:m,style:{boxSizing:"border-box",maxHeight:"100%",...o.style}}))))}),f2=f.forwardRef((e,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:o=ai,...i}=e,s=jx(n);return f.createElement(Bm,Y({},s,i,{ref:t,align:r,collisionPadding:o,style:{boxSizing:"border-box",...i.style,"--radix-select-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-select-content-available-width":"var(--radix-popper-available-width)","--radix-select-content-available-height":"var(--radix-popper-available-height)","--radix-select-trigger-width":"var(--radix-popper-anchor-width)","--radix-select-trigger-height":"var(--radix-popper-anchor-height)"}}))}),[FY,zx]=Ec(ic,{}),p2="SelectViewport",jY=f.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=Ma(p2,n),i=zx(p2,n),s=Be(t,o.onViewportChange),l=f.useRef(0);return f.createElement(f.Fragment,null,f.createElement("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"}}),f.createElement(eg.Slot,{scope:n},f.createElement(Pe.div,Y({"data-radix-select-viewport":"",role:"presentation"},r,{ref:s,style:{position:"relative",flex:1,overflow:"auto",...r.style},onScroll:ue(r.onScroll,u=>{const d=u.currentTarget,{contentWrapper:h,shouldExpandOnScrollRef:m}=i;if(m!=null&&m.current&&h){const g=Math.abs(l.current-d.scrollTop);if(g>0){const y=window.innerHeight-ai*2,x=parseFloat(h.style.minHeight),_=parseFloat(h.style.height),C=Math.max(x,_);if(C0?E:0,h.style.justifyContent="flex-end")}}}l.current=d.scrollTop})}))))}),zY="SelectGroup",[BY,UY]=Ec(zY),VY=f.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=nr();return f.createElement(BY,{scope:n,id:o},f.createElement(Pe.div,Y({role:"group","aria-labelledby":o},r,{ref:t})))}),WY="SelectLabel",HY=f.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=UY(WY,n);return f.createElement(Pe.div,Y({id:o.id},r,{ref:t}))}),b1="SelectItem",[KY,a5]=Ec(b1),YY=f.forwardRef((e,t)=>{const{__scopeSelect:n,value:r,disabled:o=!1,textValue:i,...s}=e,l=Oa(b1,n),u=Ma(b1,n),d=l.value===r,[h,m]=f.useState(i??""),[g,y]=f.useState(!1),x=Be(t,S=>{var b;return(b=u.itemRefCallback)===null||b===void 0?void 0:b.call(u,S,r,o)}),_=nr(),C=()=>{o||(l.onValueChange(r),l.onOpenChange(!1))};if(r==="")throw new Error("A must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.");return f.createElement(KY,{scope:n,value:r,disabled:o,textId:_,isSelected:d,onItemTextChange:f.useCallback(S=>{m(b=>{var E;return b||((E=S==null?void 0:S.textContent)!==null&&E!==void 0?E:"").trim()})},[])},f.createElement(eg.ItemSlot,{scope:n,value:r,disabled:o,textValue:h},f.createElement(Pe.div,Y({role:"option","aria-labelledby":_,"data-highlighted":g?"":void 0,"aria-selected":d&&g,"data-state":d?"checked":"unchecked","aria-disabled":o||void 0,"data-disabled":o?"":void 0,tabIndex:o?void 0:-1},s,{ref:x,onFocus:ue(s.onFocus,()=>y(!0)),onBlur:ue(s.onBlur,()=>y(!1)),onPointerUp:ue(s.onPointerUp,C),onPointerMove:ue(s.onPointerMove,S=>{if(o){var b;(b=u.onItemLeave)===null||b===void 0||b.call(u)}else S.currentTarget.focus({preventScroll:!0})}),onPointerLeave:ue(s.onPointerLeave,S=>{if(S.currentTarget===document.activeElement){var b;(b=u.onItemLeave)===null||b===void 0||b.call(u)}}),onKeyDown:ue(s.onKeyDown,S=>{var b;((b=u.searchRef)===null||b===void 0?void 0:b.current)!==""&&S.key===" "||(SY.includes(S.key)&&C(),S.key===" "&&S.preventDefault())})}))))}),hp="SelectItemText",GY=f.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,...i}=e,s=Oa(hp,n),l=Ma(hp,n),u=a5(hp,n),d=kY(hp,n),[h,m]=f.useState(null),g=Be(t,S=>m(S),u.onItemTextChange,S=>{var b;return(b=l.itemTextRefCallback)===null||b===void 0?void 0:b.call(l,S,u.value,u.disabled)}),y=h==null?void 0:h.textContent,x=f.useMemo(()=>f.createElement("option",{key:u.value,value:u.value,disabled:u.disabled},y),[u.disabled,u.value,y]),{onNativeOptionAdd:_,onNativeOptionRemove:C}=d;return Pn(()=>(_(x),()=>C(x)),[_,C,x]),f.createElement(f.Fragment,null,f.createElement(Pe.span,Y({id:u.textId},i,{ref:g})),u.isSelected&&s.valueNode&&!s.valueNodeHasChildren?Os.createPortal(i.children,s.valueNode):null)}),XY="SelectItemIndicator",ZY=f.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return a5(XY,n).isSelected?f.createElement(Pe.span,Y({"aria-hidden":!0},r,{ref:t})):null}),h2="SelectScrollUpButton",qY=f.forwardRef((e,t)=>{const n=Ma(h2,e.__scopeSelect),r=zx(h2,e.__scopeSelect),[o,i]=f.useState(!1),s=Be(t,r.onScrollButtonChange);return Pn(()=>{if(n.viewport&&n.isPositioned){let d=function(){const h=u.scrollTop>0;i(h)};var l=d;const u=n.viewport;return d(),u.addEventListener("scroll",d),()=>u.removeEventListener("scroll",d)}},[n.viewport,n.isPositioned]),o?f.createElement(l5,Y({},e,{ref:s,onAutoScroll:()=>{const{viewport:l,selectedItem:u}=n;l&&u&&(l.scrollTop=l.scrollTop-u.offsetHeight)}})):null}),m2="SelectScrollDownButton",QY=f.forwardRef((e,t)=>{const n=Ma(m2,e.__scopeSelect),r=zx(m2,e.__scopeSelect),[o,i]=f.useState(!1),s=Be(t,r.onScrollButtonChange);return Pn(()=>{if(n.viewport&&n.isPositioned){let d=function(){const h=u.scrollHeight-u.clientHeight,m=Math.ceil(u.scrollTop)u.removeEventListener("scroll",d)}},[n.viewport,n.isPositioned]),o?f.createElement(l5,Y({},e,{ref:s,onAutoScroll:()=>{const{viewport:l,selectedItem:u}=n;l&&u&&(l.scrollTop=l.scrollTop+u.offsetHeight)}})):null}),l5=f.forwardRef((e,t)=>{const{__scopeSelect:n,onAutoScroll:r,...o}=e,i=Ma("SelectScrollButton",n),s=f.useRef(null),l=tg(n),u=f.useCallback(()=>{s.current!==null&&(window.clearInterval(s.current),s.current=null)},[]);return f.useEffect(()=>()=>u(),[u]),Pn(()=>{var d;const h=l().find(m=>m.ref.current===document.activeElement);h==null||(d=h.ref.current)===null||d===void 0||d.scrollIntoView({block:"nearest"})},[l]),f.createElement(Pe.div,Y({"aria-hidden":!0},o,{ref:t,style:{flexShrink:0,...o.style},onPointerDown:ue(o.onPointerDown,()=>{s.current===null&&(s.current=window.setInterval(r,50))}),onPointerMove:ue(o.onPointerMove,()=>{var d;(d=i.onItemLeave)===null||d===void 0||d.call(i),s.current===null&&(s.current=window.setInterval(r,50))}),onPointerLeave:ue(o.onPointerLeave,()=>{u()})}))}),JY=f.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return f.createElement(Pe.div,Y({"aria-hidden":!0},r,{ref:t}))});function c5(e){return e===""||e===void 0}const u5=f.forwardRef((e,t)=>{const{value:n,...r}=e,o=f.useRef(null),i=Be(t,o),s=Fx(n);return f.useEffect(()=>{const l=o.current,u=window.HTMLSelectElement.prototype,h=Object.getOwnPropertyDescriptor(u,"value").set;if(s!==n&&h){const m=new Event("change",{bubbles:!0});h.call(l,n),l.dispatchEvent(m)}},[s,n]),f.createElement(Um,{asChild:!0},f.createElement("select",Y({},r,{ref:i,defaultValue:n})))});u5.displayName="BubbleSelect";function d5(e){const t=Ft(e),n=f.useRef(""),r=f.useRef(0),o=f.useCallback(s=>{const l=n.current+s;t(l),function u(d){n.current=d,window.clearTimeout(r.current),d!==""&&(r.current=window.setTimeout(()=>u(""),1e3))}(l)},[t]),i=f.useCallback(()=>{n.current="",window.clearTimeout(r.current)},[]);return f.useEffect(()=>()=>window.clearTimeout(r.current),[]),[n,o,i]}function f5(e,t,n){const o=t.length>1&&Array.from(t).every(d=>d===t[0])?t[0]:t,i=n?e.indexOf(n):-1;let s=eG(e,Math.max(i,0));o.length===1&&(s=s.filter(d=>d!==n));const u=s.find(d=>d.textValue.toLowerCase().startsWith(o.toLowerCase()));return u!==n?u:void 0}function eG(e,t){return e.map((n,r)=>e[(t+r)%e.length])}const tG=RY,p5=PY,nG=OY,rG=MY,oG=NY,h5=DY,iG=jY,sG=VY,m5=HY,g5=YY,aG=GY,lG=ZY,v5=qY,y5=QY,w5=JY,aa=tG,wl=sG,la=nG,ls=f.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(p5,{ref:r,className:Ce("flex h-9 w-full items-center justify-between whitespace-nowrap rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",e),tabIndex:-1,...n,children:[t,v.jsx(rG,{asChild:!0,children:v.jsx(Gj,{className:"h-4 w-4 opacity-50"})})]}));ls.displayName=p5.displayName;const x5=f.forwardRef(({className:e,...t},n)=>v.jsx(v5,{ref:n,className:Ce("flex cursor-default items-center justify-center py-1",e),...t,children:v.jsx(tz,{})}));x5.displayName=v5.displayName;const b5=f.forwardRef(({className:e,...t},n)=>v.jsx(y5,{ref:n,className:Ce("flex cursor-default items-center justify-center py-1",e),...t,children:v.jsx(qj,{})}));b5.displayName=y5.displayName;const cs=f.forwardRef(({className:e,children:t,position:n="popper",...r},o)=>v.jsx(oG,{children:v.jsxs(h5,{ref:o,className:Ce("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",n==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:n,onCloseAutoFocus:i=>i.preventDefault(),...r,children:[v.jsx(x5,{}),v.jsx(iG,{className:Ce("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),v.jsx(b5,{})]})}));cs.displayName=h5.displayName;const cG=f.forwardRef(({className:e,...t},n)=>v.jsx(m5,{ref:n,className:Ce("px-2 py-1.5 text-sm font-semibold",e),...t}));cG.displayName=m5.displayName;const us=f.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(g5,{ref:r,className:Ce("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-2 pr-8 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[v.jsx("span",{className:"absolute right-2 flex h-3.5 w-3.5 items-center justify-center",children:v.jsx(lG,{children:v.jsx(vT,{className:"h-4 w-4"})})}),v.jsx(aG,{children:t})]}));us.displayName=g5.displayName;const uG=f.forwardRef(({className:e,...t},n)=>v.jsx(w5,{ref:n,className:Ce("-mx-1 my-1 h-px bg-muted",e),...t}));uG.displayName=w5.displayName;function dG(e,t){return f.useReducer((n,r)=>{const o=t[n][r];return o??n},e)}const _5="ScrollArea",[S5,_te]=An(_5),[fG,qr]=S5(_5),pG=f.forwardRef((e,t)=>{const{__scopeScrollArea:n,type:r="hover",dir:o,scrollHideDelay:i=600,...s}=e,[l,u]=f.useState(null),[d,h]=f.useState(null),[m,g]=f.useState(null),[y,x]=f.useState(null),[_,C]=f.useState(null),[S,b]=f.useState(0),[E,k]=f.useState(0),[P,M]=f.useState(!1),[A,O]=f.useState(!1),F=Be(t,J=>u(J)),V=Sc(o);return f.createElement(fG,{scope:n,type:r,dir:V,scrollHideDelay:i,scrollArea:l,viewport:d,onViewportChange:h,content:m,onContentChange:g,scrollbarX:y,onScrollbarXChange:x,scrollbarXEnabled:P,onScrollbarXEnabledChange:M,scrollbarY:_,onScrollbarYChange:C,scrollbarYEnabled:A,onScrollbarYEnabledChange:O,onCornerWidthChange:b,onCornerHeightChange:k},f.createElement(Pe.div,Y({dir:V},s,{ref:F,style:{position:"relative","--radix-scroll-area-corner-width":S+"px","--radix-scroll-area-corner-height":E+"px",...e.style}})))}),hG="ScrollAreaViewport",mG=f.forwardRef((e,t)=>{const{__scopeScrollArea:n,children:r,...o}=e,i=qr(hG,n),s=f.useRef(null),l=Be(t,s,i.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(Pe.div,Y({"data-radix-scroll-area-viewport":""},o,{ref:l,style:{overflowX:i.scrollbarXEnabled?"scroll":"hidden",overflowY:i.scrollbarYEnabled?"scroll":"hidden",...e.style}}),f.createElement("div",{ref:i.onContentChange,style:{minWidth:"100%",display:"table"}},r)))}),$i="ScrollAreaScrollbar",E5=f.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=qr($i,e.__scopeScrollArea),{onScrollbarXEnabledChange:i,onScrollbarYEnabledChange:s}=o,l=e.orientation==="horizontal";return f.useEffect(()=>(l?i(!0):s(!0),()=>{l?i(!1):s(!1)}),[l,i,s]),o.type==="hover"?f.createElement(gG,Y({},r,{ref:t,forceMount:n})):o.type==="scroll"?f.createElement(vG,Y({},r,{ref:t,forceMount:n})):o.type==="auto"?f.createElement(C5,Y({},r,{ref:t,forceMount:n})):o.type==="always"?f.createElement(Bx,Y({},r,{ref:t})):null}),gG=f.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=qr($i,e.__scopeScrollArea),[i,s]=f.useState(!1);return f.useEffect(()=>{const l=o.scrollArea;let u=0;if(l){const d=()=>{window.clearTimeout(u),s(!0)},h=()=>{u=window.setTimeout(()=>s(!1),o.scrollHideDelay)};return l.addEventListener("pointerenter",d),l.addEventListener("pointerleave",h),()=>{window.clearTimeout(u),l.removeEventListener("pointerenter",d),l.removeEventListener("pointerleave",h)}}},[o.scrollArea,o.scrollHideDelay]),f.createElement(xn,{present:n||i},f.createElement(C5,Y({"data-state":i?"visible":"hidden"},r,{ref:t})))}),vG=f.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=qr($i,e.__scopeScrollArea),i=e.orientation==="horizontal",s=rg(()=>u("SCROLL_END"),100),[l,u]=dG("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(l==="idle"){const d=window.setTimeout(()=>u("HIDE"),o.scrollHideDelay);return()=>window.clearTimeout(d)}},[l,o.scrollHideDelay,u]),f.useEffect(()=>{const d=o.viewport,h=i?"scrollLeft":"scrollTop";if(d){let m=d[h];const g=()=>{const y=d[h];m!==y&&(u("SCROLL"),s()),m=y};return d.addEventListener("scroll",g),()=>d.removeEventListener("scroll",g)}},[o.viewport,i,u,s]),f.createElement(xn,{present:n||l!=="hidden"},f.createElement(Bx,Y({"data-state":l==="hidden"?"hidden":"visible"},r,{ref:t,onPointerEnter:ue(e.onPointerEnter,()=>u("POINTER_ENTER")),onPointerLeave:ue(e.onPointerLeave,()=>u("POINTER_LEAVE"))})))}),C5=f.forwardRef((e,t)=>{const n=qr($i,e.__scopeScrollArea),{forceMount:r,...o}=e,[i,s]=f.useState(!1),l=e.orientation==="horizontal",u=rg(()=>{if(n.viewport){const d=n.viewport.offsetWidth{const{orientation:n="vertical",...r}=e,o=qr($i,e.__scopeScrollArea),i=f.useRef(null),s=f.useRef(0),[l,u]=f.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),d=T5(l.viewport,l.content),h={...r,sizes:l,onSizesChange:u,hasThumb:d>0&&d<1,onThumbChange:g=>i.current=g,onThumbPointerUp:()=>s.current=0,onThumbPointerDown:g=>s.current=g};function m(g,y){return CG(g,s.current,l,y)}return n==="horizontal"?f.createElement(yG,Y({},h,{ref:t,onThumbPositionChange:()=>{if(o.viewport&&i.current){const g=o.viewport.scrollLeft,y=g2(g,l,o.dir);i.current.style.transform=`translate3d(${y}px, 0, 0)`}},onWheelScroll:g=>{o.viewport&&(o.viewport.scrollLeft=g)},onDragScroll:g=>{o.viewport&&(o.viewport.scrollLeft=m(g,o.dir))}})):n==="vertical"?f.createElement(wG,Y({},h,{ref:t,onThumbPositionChange:()=>{if(o.viewport&&i.current){const g=o.viewport.scrollTop,y=g2(g,l);i.current.style.transform=`translate3d(0, ${y}px, 0)`}},onWheelScroll:g=>{o.viewport&&(o.viewport.scrollTop=g)},onDragScroll:g=>{o.viewport&&(o.viewport.scrollTop=m(g))}})):null}),yG=f.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,i=qr($i,e.__scopeScrollArea),[s,l]=f.useState(),u=f.useRef(null),d=Be(t,u,i.onScrollbarXChange);return f.useEffect(()=>{u.current&&l(getComputedStyle(u.current))},[u]),f.createElement(k5,Y({"data-orientation":"horizontal"},o,{ref:d,sizes:n,style:{bottom:0,left:i.dir==="rtl"?"var(--radix-scroll-area-corner-width)":0,right:i.dir==="ltr"?"var(--radix-scroll-area-corner-width)":0,"--radix-scroll-area-thumb-width":ng(n)+"px",...e.style},onThumbPointerDown:h=>e.onThumbPointerDown(h.x),onDragScroll:h=>e.onDragScroll(h.x),onWheelScroll:(h,m)=>{if(i.viewport){const g=i.viewport.scrollLeft+h.deltaX;e.onWheelScroll(g),A5(g,m)&&h.preventDefault()}},onResize:()=>{u.current&&i.viewport&&s&&r({content:i.viewport.scrollWidth,viewport:i.viewport.offsetWidth,scrollbar:{size:u.current.clientWidth,paddingStart:zh(s.paddingLeft),paddingEnd:zh(s.paddingRight)}})}}))}),wG=f.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,i=qr($i,e.__scopeScrollArea),[s,l]=f.useState(),u=f.useRef(null),d=Be(t,u,i.onScrollbarYChange);return f.useEffect(()=>{u.current&&l(getComputedStyle(u.current))},[u]),f.createElement(k5,Y({"data-orientation":"vertical"},o,{ref:d,sizes:n,style:{top:0,right:i.dir==="ltr"?0:void 0,left:i.dir==="rtl"?0:void 0,bottom:"var(--radix-scroll-area-corner-height)","--radix-scroll-area-thumb-height":ng(n)+"px",...e.style},onThumbPointerDown:h=>e.onThumbPointerDown(h.y),onDragScroll:h=>e.onDragScroll(h.y),onWheelScroll:(h,m)=>{if(i.viewport){const g=i.viewport.scrollTop+h.deltaY;e.onWheelScroll(g),A5(g,m)&&h.preventDefault()}},onResize:()=>{u.current&&i.viewport&&s&&r({content:i.viewport.scrollHeight,viewport:i.viewport.offsetHeight,scrollbar:{size:u.current.clientHeight,paddingStart:zh(s.paddingTop),paddingEnd:zh(s.paddingBottom)}})}}))}),[xG,$5]=S5($i),k5=f.forwardRef((e,t)=>{const{__scopeScrollArea:n,sizes:r,hasThumb:o,onThumbChange:i,onThumbPointerUp:s,onThumbPointerDown:l,onThumbPositionChange:u,onDragScroll:d,onWheelScroll:h,onResize:m,...g}=e,y=qr($i,n),[x,_]=f.useState(null),C=Be(t,F=>_(F)),S=f.useRef(null),b=f.useRef(""),E=y.viewport,k=r.content-r.viewport,P=Ft(h),M=Ft(u),A=rg(m,10);function O(F){if(S.current){const V=F.clientX-S.current.left,J=F.clientY-S.current.top;d({x:V,y:J})}}return f.useEffect(()=>{const F=V=>{const J=V.target;(x==null?void 0:x.contains(J))&&P(V,k)};return document.addEventListener("wheel",F,{passive:!1}),()=>document.removeEventListener("wheel",F,{passive:!1})},[E,x,k,P]),f.useEffect(M,[r,M]),sc(x,A),sc(y.content,A),f.createElement(xG,{scope:n,scrollbar:x,hasThumb:o,onThumbChange:Ft(i),onThumbPointerUp:Ft(s),onThumbPositionChange:M,onThumbPointerDown:Ft(l)},f.createElement(Pe.div,Y({},g,{ref:C,style:{position:"absolute",...g.style},onPointerDown:ue(e.onPointerDown,F=>{F.button===0&&(F.target.setPointerCapture(F.pointerId),S.current=x.getBoundingClientRect(),b.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",y.viewport&&(y.viewport.style.scrollBehavior="auto"),O(F))}),onPointerMove:ue(e.onPointerMove,O),onPointerUp:ue(e.onPointerUp,F=>{const V=F.target;V.hasPointerCapture(F.pointerId)&&V.releasePointerCapture(F.pointerId),document.body.style.webkitUserSelect=b.current,y.viewport&&(y.viewport.style.scrollBehavior=""),S.current=null})})))}),_1="ScrollAreaThumb",bG=f.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=$5(_1,e.__scopeScrollArea);return f.createElement(xn,{present:n||o.hasThumb},f.createElement(_G,Y({ref:t},r)))}),_G=f.forwardRef((e,t)=>{const{__scopeScrollArea:n,style:r,...o}=e,i=qr(_1,n),s=$5(_1,n),{onThumbPositionChange:l}=s,u=Be(t,m=>s.onThumbChange(m)),d=f.useRef(),h=rg(()=>{d.current&&(d.current(),d.current=void 0)},100);return f.useEffect(()=>{const m=i.viewport;if(m){const g=()=>{if(h(),!d.current){const y=$G(m,l);d.current=y,l()}};return l(),m.addEventListener("scroll",g),()=>m.removeEventListener("scroll",g)}},[i.viewport,h,l]),f.createElement(Pe.div,Y({"data-state":s.hasThumb?"visible":"hidden"},o,{ref:u,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...r},onPointerDownCapture:ue(e.onPointerDownCapture,m=>{const y=m.target.getBoundingClientRect(),x=m.clientX-y.left,_=m.clientY-y.top;s.onThumbPointerDown({x,y:_})}),onPointerUp:ue(e.onPointerUp,s.onThumbPointerUp)}))}),R5="ScrollAreaCorner",SG=f.forwardRef((e,t)=>{const n=qr(R5,e.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?f.createElement(EG,Y({},e,{ref:t})):null}),EG=f.forwardRef((e,t)=>{const{__scopeScrollArea:n,...r}=e,o=qr(R5,n),[i,s]=f.useState(0),[l,u]=f.useState(0),d=!!(i&&l);return sc(o.scrollbarX,()=>{var h;const m=((h=o.scrollbarX)===null||h===void 0?void 0:h.offsetHeight)||0;o.onCornerHeightChange(m),u(m)}),sc(o.scrollbarY,()=>{var h;const m=((h=o.scrollbarY)===null||h===void 0?void 0:h.offsetWidth)||0;o.onCornerWidthChange(m),s(m)}),d?f.createElement(Pe.div,Y({},r,{ref:t,style:{width:i,height:l,position:"absolute",right:o.dir==="ltr"?0:void 0,left:o.dir==="rtl"?0:void 0,bottom:0,...e.style}})):null});function zh(e){return e?parseInt(e,10):0}function T5(e,t){const n=e/t;return isNaN(n)?0:n}function ng(e){const t=T5(e.viewport,e.content),n=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,r=(e.scrollbar.size-n)*t;return Math.max(r,18)}function CG(e,t,n,r="ltr"){const o=ng(n),i=o/2,s=t||i,l=o-s,u=n.scrollbar.paddingStart+s,d=n.scrollbar.size-n.scrollbar.paddingEnd-l,h=n.content-n.viewport,m=r==="ltr"?[0,h]:[h*-1,0];return P5([u,d],m)(e)}function g2(e,t,n="ltr"){const r=ng(t),o=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,i=t.scrollbar.size-o,s=t.content-t.viewport,l=i-r,u=n==="ltr"?[0,s]:[s*-1,0],d=id(e,u);return P5([0,s],[0,l])(d)}function P5(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 A5(e,t){return e>0&&e{})=>{let n={left:e.scrollLeft,top:e.scrollTop},r=0;return function o(){const i={left:e.scrollLeft,top:e.scrollTop},s=n.left!==i.left,l=n.top!==i.top;(s||l)&&t(),n=i,r=window.requestAnimationFrame(o)}(),()=>window.cancelAnimationFrame(r)};function rg(e,t){const n=Ft(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 sc(e,t){const n=Ft(t);Pn(()=>{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 O5=pG,kG=mG,RG=SG,og=f.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(O5,{ref:r,className:Ce("relative overflow-hidden",e),scrollHideDelay:400,...n,children:[v.jsx(kG,{className:"h-full w-full rounded-[inherit]",children:t}),v.jsx(M5,{}),v.jsx(RG,{})]}));og.displayName=O5.displayName;const M5=f.forwardRef(({className:e,orientation:t="vertical",...n},r)=>v.jsx(E5,{ref:r,orientation:t,className:Ce("flex touch-none select-none transition-colors",t==="vertical"&&"h-full w-2.5 border-l border-l-transparent p-[1px]",t==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",e),...n,children:v.jsx(bG,{className:"relative flex-1 rounded-full bg-border"})}));M5.displayName=E5.displayName;const N5="Name",D5="Created time",I5="Modified time",v2="input",TG="output",y2={[xs.NAME]:N5,[xs.CTIME]:D5,[xs.MTIME]:I5};function PG(e){const{onPhotoClick:t,photoWidth:n}=e,[r,o]=AP(!1),[i,s]=bt(V=>[V.fileManagerState,V.updateFileManagerState]),{toast:l}=Td(),[u,d]=f.useState(0),[h,m]=f.useState(0),g=f.useRef(null),y=lV(i.searchText,300),[x,_]=f.useState(v2),[C,S]=f.useState([]),[b,E]=f.useState([]),[k,P]=f.useState(0);Zn("f",()=>{o()}),Zn("left",()=>{let V=k;k>0&&(V=k-1),P(V),t(x,b[V].name)},[k,b]),Zn("right",()=>{let V=k;k{r||m(u)},[r,u]);const M=f.useCallback(V=>{V!==null&&r&&setTimeout(()=>{V.scrollTo({top:h,left:0})},100)},[r,h]);f.useEffect(()=>{(async()=>{try{const J=await Uj(x);S(J)}catch(J){l({variant:"destructive",title:"Uh oh! Something went wrong.",description:J.message?J.message:J.toString()})}})()},[x]),f.useEffect(()=>{if(!r)return;(async()=>{try{let J=C;y&&(J=new _c(J,{keys:["name"]}).search(y).map(te=>J[te.refIndex])),J=xH.orderBy(J,i.sortBy,i.sortOrder);const G=J.map(ae=>{const U=n,te=ae.height*(U/ae.width);return{src:`${Ms}/media_thumbnail_file?tab=${x}&filename=${encodeURIComponent(ae.name)}&width=${Math.ceil(U)}&height=${Math.ceil(te)}`,height:te,width:U,name:ae.name}});E(G)}catch(J){l({variant:"destructive",title:"Uh oh! Something went wrong.",description:J.message?J.message:J.toString()})}})()},[C,y,i,n,r]);const A=V=>{d(V.currentTarget.scrollTop)},O=({index:V})=>{o(),P(V),t(x,b[V].name)},F=()=>v.jsxs("div",{className:"flex justify-start items-center gap-[12px]",children:[v.jsx("div",{children:`Images (${b.length})`}),v.jsxs("div",{className:"flex",children:[v.jsx(vn,{tooltip:"Rows layout",onClick:()=>{s({layout:"rows"})},children:v.jsx(fz,{className:i.layout!=="rows"?"opacity-50":""})}),v.jsx(vn,{tooltip:"Grid layout",onClick:()=>{s({layout:"masonry"})},children:v.jsx(uz,{className:i.layout!=="masonry"?"opacity-50":""})})]})]});return v.jsxs(Zm,{open:r,onOpenChange:o,children:[v.jsx(uP,{asChild:!0,children:v.jsx(vn,{tooltip:"File Manager",children:v.jsx(QU,{})})}),v.jsxs(Fd,{className:"h-4/5 max-w-6xl",children:[v.jsx(jd,{children:F()}),v.jsxs("div",{className:"flex justify-between gap-8 items-center",children:[v.jsxs("div",{className:"flex relative justify-start items-center",children:[v.jsx(sz,{className:"absolute left-[8px]"}),v.jsx(Pd,{ref:g,value:i.searchText,className:"w-[250px] pl-[30px]",tabIndex:-1,onInput:V=>{V.preventDefault(),V.stopPropagation();const J=V.target;s({searchText:J.value})},placeholder:"Search by file name"})]}),v.jsx(i5,{defaultValue:x,onValueChange:V=>_(V),children:v.jsxs(Lx,{"aria-label":"Manage your account",children:[v.jsx(sa,{value:v2,children:"Image Directory"}),v.jsx(sa,{value:TG,children:"Output Directory"})]})}),v.jsx("div",{className:"flex gap-2",children:v.jsxs("div",{className:"flex gap-1",children:[v.jsxs(aa,{value:y2[i.sortBy],onValueChange:V=>{switch(V){case N5:s({sortBy:xs.NAME});break;case D5:s({sortBy:xs.CTIME});break;case I5:s({sortBy:xs.MTIME});break}},children:[v.jsx(ls,{className:"w-[140px]",children:v.jsx(la,{})}),v.jsx(cs,{children:Object.values(y2).map(V=>v.jsx(us,{value:V,children:V},V))})]}),i.sortOrder===$u.DESCENDING?v.jsx(vn,{tooltip:"Descending Order",onClick:()=>{s({sortOrder:$u.ASCENDING})},children:v.jsx(iK,{})}):v.jsx(vn,{tooltip:"Ascending Order",onClick:()=>{s({sortOrder:$u.DESCENDING})},children:v.jsx(lK,{})})]})})]}),v.jsx(og,{className:"w-full h-full rounded-md",onScroll:A,ref:M,children:v.jsx(nK,{layout:i.layout,photos:b,spacing:12,padding:0,onClick:O})})]})]})}var Bd=e=>e.type==="checkbox",xl=e=>e instanceof Date,Ln=e=>e==null;const L5=e=>typeof e=="object";var sn=e=>!Ln(e)&&!Array.isArray(e)&&L5(e)&&!xl(e),F5=e=>sn(e)&&e.target?Bd(e.target)?e.target.checked:e.target.value:e,AG=e=>e.substring(0,e.search(/\.\d+(\.|$)/))||e,j5=(e,t)=>e.has(AG(t)),OG=e=>{const t=e.constructor&&e.constructor.prototype;return sn(t)&&t.hasOwnProperty("isPrototypeOf")},Ux=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function so(e){let t;const n=Array.isArray(e);if(e instanceof Date)t=new Date(e);else if(e instanceof Set)t=new Set(e);else if(!(Ux&&(e instanceof Blob||e instanceof FileList))&&(n||sn(e)))if(t=n?[]:{},!n&&!OG(e))t=e;else for(const r in e)e.hasOwnProperty(r)&&(t[r]=so(e[r]));else return e;return t}var Ud=e=>Array.isArray(e)?e.filter(Boolean):[],Ht=e=>e===void 0,ve=(e,t,n)=>{if(!t||!sn(e))return n;const r=Ud(t.split(/[,[\].]+?/)).reduce((o,i)=>Ln(o)?o:o[i],e);return Ht(r)||r===e?Ht(e[t])?n:e[t]:r},No=e=>typeof e=="boolean";const Bh={BLUR:"blur",FOCUS_OUT:"focusout",CHANGE:"change"},mo={onBlur:"onBlur",onChange:"onChange",onSubmit:"onSubmit",onTouched:"onTouched",all:"all"},oi={max:"max",min:"min",maxLength:"maxLength",minLength:"minLength",pattern:"pattern",required:"required",validate:"validate"},z5=Fe.createContext(null),ig=()=>Fe.useContext(z5),MG=e=>{const{children:t,...n}=e;return Fe.createElement(z5.Provider,{value:n},t)};var B5=(e,t,n,r=!0)=>{const o={defaultValues:t._defaultValues};for(const i in e)Object.defineProperty(o,i,{get:()=>{const s=i;return t._proxyFormState[s]!==mo.all&&(t._proxyFormState[s]=!r||mo.all),n&&(n[s]=!0),e[s]}});return o},Fr=e=>sn(e)&&!Object.keys(e).length,U5=(e,t,n,r)=>{n(e);const{name:o,...i}=e;return Fr(i)||Object.keys(i).length>=Object.keys(t).length||Object.keys(i).find(s=>t[s]===(!r||mo.all))},Yp=e=>Array.isArray(e)?e:[e],V5=(e,t,n)=>!e||!t||e===t||Yp(e).some(r=>r&&(n?r===t:r.startsWith(t)||t.startsWith(r)));function Vx(e){const t=Fe.useRef(e);t.current=e,Fe.useEffect(()=>{const n=!e.disabled&&t.current.subject&&t.current.subject.subscribe({next:t.current.next});return()=>{n&&n.unsubscribe()}},[e.disabled])}function NG(e){const t=ig(),{control:n=t.control,disabled:r,name:o,exact:i}=e||{},[s,l]=Fe.useState(n._formState),u=Fe.useRef(!0),d=Fe.useRef({isDirty:!1,isLoading:!1,dirtyFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1}),h=Fe.useRef(o);return h.current=o,Vx({disabled:r,next:m=>u.current&&V5(h.current,m.name,i)&&U5(m,d.current,n._updateFormState)&&l({...n._formState,...m}),subject:n._subjects.state}),Fe.useEffect(()=>(u.current=!0,d.current.isValid&&n._updateValid(!0),()=>{u.current=!1}),[n]),B5(s,n,d.current,!1)}var Fo=e=>typeof e=="string",W5=(e,t,n,r,o)=>Fo(e)?(r&&t.watch.add(e),ve(n,e,o)):Array.isArray(e)?e.map(i=>(r&&t.watch.add(i),ve(n,i))):(r&&(t.watchAll=!0),n);function DG(e){const t=ig(),{control:n=t.control,name:r,defaultValue:o,disabled:i,exact:s}=e||{},l=Fe.useRef(r);l.current=r,Vx({disabled:i,subject:n._subjects.values,next:h=>{V5(l.current,h.name,s)&&d(so(W5(l.current,n._names,h.values||n._formValues,!1,o)))}});const[u,d]=Fe.useState(n._getWatch(r,o));return Fe.useEffect(()=>n._removeUnmounted()),u}var Wx=e=>/^\w*$/.test(e),H5=e=>Ud(e.replace(/["|']|\]/g,"").split(/\.|\[/));function wt(e,t,n){let r=-1;const o=Wx(t)?[t]:H5(t),i=o.length,s=i-1;for(;++r{const h=o._options.shouldUnregister||i,m=(g,y)=>{const x=ve(o._fields,g);x&&(x._f.mount=y)};if(m(n,!0),h){const g=so(ve(o._options.defaultValues,n));wt(o._defaultValues,n,g),Ht(ve(o._formValues,n))&&wt(o._formValues,n,g)}return()=>{(s?h&&!o._state.action:h)?o.unregister(n):m(n,!1)}},[n,o,s,i]),Fe.useEffect(()=>{ve(o._fields,n)&&o._updateDisabledField({disabled:r,fields:o._fields,name:n,value:ve(o._fields,n)._f.value})},[r,n,o]),{field:{name:n,value:l,...No(r)||No(u.disabled)?{disabled:u.disabled||r}:{},onChange:Fe.useCallback(h=>d.current.onChange({target:{value:F5(h),name:n},type:Bh.CHANGE}),[n]),onBlur:Fe.useCallback(()=>d.current.onBlur({target:{value:ve(o._formValues,n),name:n},type:Bh.BLUR}),[n,o]),ref:h=>{const m=ve(o._fields,n);m&&h&&(m._f.ref={focus:()=>h.focus(),select:()=>h.select(),setCustomValidity:g=>h.setCustomValidity(g),reportValidity:()=>h.reportValidity()})}},formState:u,fieldState:Object.defineProperties({},{invalid:{enumerable:!0,get:()=>!!ve(u.errors,n)},isDirty:{enumerable:!0,get:()=>!!ve(u.dirtyFields,n)},isTouched:{enumerable:!0,get:()=>!!ve(u.touchedFields,n)},error:{enumerable:!0,get:()=>ve(u.errors,n)}})}}const LG=e=>e.render(IG(e));var K5=(e,t,n,r,o)=>t?{...n[e],types:{...n[e]&&n[e].types?n[e].types:{},[r]:o||!0}}:{},w2=e=>({isOnSubmit:!e||e===mo.onSubmit,isOnBlur:e===mo.onBlur,isOnChange:e===mo.onChange,isOnAll:e===mo.all,isOnTouch:e===mo.onTouched}),x2=(e,t,n)=>!n&&(t.watchAll||t.watch.has(e)||[...t.watch].some(r=>e.startsWith(r)&&/^\.\w+/.test(e.slice(r.length))));const Gp=(e,t,n,r)=>{for(const o of n||Object.keys(e)){const i=ve(e,o);if(i){const{_f:s,...l}=i;if(s){if(s.refs&&s.refs[0]&&t(s.refs[0],o)&&!r)break;if(s.ref&&t(s.ref,s.name)&&!r)break}else sn(l)&&Gp(l,t)}}};var FG=(e,t,n)=>{const r=Ud(ve(e,n));return wt(r,"root",t[n]),wt(e,n,r),e},Hx=e=>e.type==="file",ds=e=>typeof e=="function",Uh=e=>{if(!Ux)return!1;const t=e?e.ownerDocument:0;return e instanceof(t&&t.defaultView?t.defaultView.HTMLElement:HTMLElement)},Xp=e=>Fo(e),Kx=e=>e.type==="radio",Vh=e=>e instanceof RegExp;const b2={value:!1,isValid:!1},_2={value:!0,isValid:!0};var Y5=e=>{if(Array.isArray(e)){if(e.length>1){const t=e.filter(n=>n&&n.checked&&!n.disabled).map(n=>n.value);return{value:t,isValid:!!t.length}}return e[0].checked&&!e[0].disabled?e[0].attributes&&!Ht(e[0].attributes.value)?Ht(e[0].value)||e[0].value===""?_2:{value:e[0].value,isValid:!0}:_2:b2}return b2};const S2={isValid:!1,value:null};var G5=e=>Array.isArray(e)?e.reduce((t,n)=>n&&n.checked&&!n.disabled?{isValid:!0,value:n.value}:t,S2):S2;function E2(e,t,n="validate"){if(Xp(e)||Array.isArray(e)&&e.every(Xp)||No(e)&&!e)return{type:n,message:Xp(e)?e:"",ref:t}}var el=e=>sn(e)&&!Vh(e)?e:{value:e,message:""},C2=async(e,t,n,r,o)=>{const{ref:i,refs:s,required:l,maxLength:u,minLength:d,min:h,max:m,pattern:g,validate:y,name:x,valueAsNumber:_,mount:C,disabled:S}=e._f,b=ve(t,x);if(!C||S)return{};const E=s?s[0]:i,k=G=>{r&&E.reportValidity&&(E.setCustomValidity(No(G)?"":G||""),E.reportValidity())},P={},M=Kx(i),A=Bd(i),O=M||A,F=(_||Hx(i))&&Ht(i.value)&&Ht(b)||Uh(i)&&i.value===""||b===""||Array.isArray(b)&&!b.length,V=K5.bind(null,x,n,P),J=(G,ae,U,te=oi.maxLength,L=oi.minLength)=>{const ie=G?ae:U;P[x]={type:G?te:L,message:ie,ref:i,...V(G?te:L,ie)}};if(o?!Array.isArray(b)||!b.length:l&&(!O&&(F||Ln(b))||No(b)&&!b||A&&!Y5(s).isValid||M&&!G5(s).isValid)){const{value:G,message:ae}=Xp(l)?{value:!!l,message:l}:el(l);if(G&&(P[x]={type:oi.required,message:ae,ref:E,...V(oi.required,ae)},!n))return k(ae),P}if(!F&&(!Ln(h)||!Ln(m))){let G,ae;const U=el(m),te=el(h);if(!Ln(b)&&!isNaN(b)){const L=i.valueAsNumber||b&&+b;Ln(U.value)||(G=L>U.value),Ln(te.value)||(ae=Lnew Date(new Date().toDateString()+" "+W),K=i.type=="time",Q=i.type=="week";Fo(U.value)&&b&&(G=K?ie(b)>ie(U.value):Q?b>U.value:L>new Date(U.value)),Fo(te.value)&&b&&(ae=K?ie(b)+G.value,te=!Ln(ae.value)&&b.length<+ae.value;if((U||te)&&(J(U,G.message,ae.message),!n))return k(P[x].message),P}if(g&&!F&&Fo(b)){const{value:G,message:ae}=el(g);if(Vh(G)&&!b.match(G)&&(P[x]={type:oi.pattern,message:ae,ref:i,...V(oi.pattern,ae)},!n))return k(ae),P}if(y){if(ds(y)){const G=await y(b,t),ae=E2(G,E);if(ae&&(P[x]={...ae,...V(oi.validate,ae.message)},!n))return k(ae.message),P}else if(sn(y)){let G={};for(const ae in y){if(!Fr(G)&&!n)break;const U=E2(await y[ae](b,t),E,ae);U&&(G={...U,...V(ae,U.message)},k(U.message),n&&(P[x]=G))}if(!Fr(G)&&(P[x]={ref:E,...G},!n))return P}}return k(!0),P};function jG(e,t){const n=t.slice(0,-1).length;let r=0;for(;r{for(const i of e)i.next&&i.next(o)},subscribe:o=>(e.push(o),{unsubscribe:()=>{e=e.filter(i=>i!==o)}}),unsubscribe:()=>{e=[]}}}var Wh=e=>Ln(e)||!L5(e);function ca(e,t){if(Wh(e)||Wh(t))return e===t;if(xl(e)&&xl(t))return e.getTime()===t.getTime();const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(const o of n){const i=e[o];if(!r.includes(o))return!1;if(o!=="ref"){const s=t[o];if(xl(i)&&xl(s)||sn(i)&&sn(s)||Array.isArray(i)&&Array.isArray(s)?!ca(i,s):i!==s)return!1}}return!0}var X5=e=>e.type==="select-multiple",BG=e=>Kx(e)||Bd(e),P0=e=>Uh(e)&&e.isConnected,Z5=e=>{for(const t in e)if(ds(e[t]))return!0;return!1};function Hh(e,t={}){const n=Array.isArray(e);if(sn(e)||n)for(const r in e)Array.isArray(e[r])||sn(e[r])&&!Z5(e[r])?(t[r]=Array.isArray(e[r])?[]:{},Hh(e[r],t[r])):Ln(e[r])||(t[r]=!0);return t}function q5(e,t,n){const r=Array.isArray(e);if(sn(e)||r)for(const o in e)Array.isArray(e[o])||sn(e[o])&&!Z5(e[o])?Ht(t)||Wh(n[o])?n[o]=Array.isArray(e[o])?Hh(e[o],[]):{...Hh(e[o])}:q5(e[o],Ln(t)?{}:t[o],n[o]):n[o]=!ca(e[o],t[o]);return n}var A0=(e,t)=>q5(e,t,Hh(t)),Q5=(e,{valueAsNumber:t,valueAsDate:n,setValueAs:r})=>Ht(e)?e:t?e===""?NaN:e&&+e:n&&Fo(e)?new Date(e):r?r(e):e;function O0(e){const t=e.ref;if(!(e.refs?e.refs.every(n=>n.disabled):t.disabled))return Hx(t)?t.files:Kx(t)?G5(e.refs).value:X5(t)?[...t.selectedOptions].map(({value:n})=>n):Bd(t)?Y5(e.refs).value:Q5(Ht(t.value)?e.ref.value:t.value,e)}var UG=(e,t,n,r)=>{const o={};for(const i of e){const s=ve(t,i);s&&wt(o,i,s._f)}return{criteriaMode:n,names:[...e],fields:o,shouldUseNativeValidation:r}},iu=e=>Ht(e)?e:Vh(e)?e.source:sn(e)?Vh(e.value)?e.value.source:e.value:e,VG=e=>e.mount&&(e.required||e.min||e.max||e.maxLength||e.minLength||e.pattern||e.validate);function $2(e,t,n){const r=ve(e,n);if(r||Wx(n))return{error:r,name:n};const o=n.split(".");for(;o.length;){const i=o.join("."),s=ve(t,i),l=ve(e,i);if(s&&!Array.isArray(s)&&n!==i)return{name:n};if(l&&l.type)return{name:i,error:l};o.pop()}return{name:n}}var WG=(e,t,n,r,o)=>o.isOnAll?!1:!n&&o.isOnTouch?!(t||e):(n?r.isOnBlur:o.isOnBlur)?!e:(n?r.isOnChange:o.isOnChange)?e:!0,HG=(e,t)=>!Ud(ve(e,t)).length&&hn(e,t);const KG={mode:mo.onSubmit,reValidateMode:mo.onChange,shouldFocusError:!0};function YG(e={},t){let n={...KG,...e},r={submitCount:0,isDirty:!1,isLoading:ds(n.defaultValues),isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},errors:{},disabled:!1},o={},i=sn(n.defaultValues)||sn(n.values)?so(n.defaultValues||n.values)||{}:{},s=n.shouldUnregister?{}:so(i),l={action:!1,mount:!1,watch:!1},u={mount:new Set,unMount:new Set,array:new Set,watch:new Set},d,h=0;const m={isDirty:!1,dirtyFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1},g={values:T0(),array:T0(),state:T0()},y=e.resetOptions&&e.resetOptions.keepDirtyValues,x=w2(n.mode),_=w2(n.reValidateMode),C=n.criteriaMode===mo.all,S=I=>X=>{clearTimeout(h),h=setTimeout(I,X)},b=async I=>{if(m.isValid||I){const X=n.resolver?Fr((await F()).errors):await J(o,!0);X!==r.isValid&&g.state.next({isValid:X})}},E=I=>m.isValidating&&g.state.next({isValidating:I}),k=(I,X=[],Z,we,he=!0,de=!0)=>{if(we&&Z){if(l.action=!0,de&&Array.isArray(ve(o,I))){const ke=Z(ve(o,I),we.argA,we.argB);he&&wt(o,I,ke)}if(de&&Array.isArray(ve(r.errors,I))){const ke=Z(ve(r.errors,I),we.argA,we.argB);he&&wt(r.errors,I,ke),HG(r.errors,I)}if(m.touchedFields&&de&&Array.isArray(ve(r.touchedFields,I))){const ke=Z(ve(r.touchedFields,I),we.argA,we.argB);he&&wt(r.touchedFields,I,ke)}m.dirtyFields&&(r.dirtyFields=A0(i,s)),g.state.next({name:I,isDirty:ae(I,X),dirtyFields:r.dirtyFields,errors:r.errors,isValid:r.isValid})}else wt(s,I,X)},P=(I,X)=>{wt(r.errors,I,X),g.state.next({errors:r.errors})},M=(I,X,Z,we)=>{const he=ve(o,I);if(he){const de=ve(s,I,Ht(Z)?ve(i,I):Z);Ht(de)||we&&we.defaultChecked||X?wt(s,I,X?de:O0(he._f)):L(I,de),l.mount&&b()}},A=(I,X,Z,we,he)=>{let de=!1,ke=!1;const ft={name:I};if(!Z||we){m.isDirty&&(ke=r.isDirty,r.isDirty=ft.isDirty=ae(),de=ke!==ft.isDirty);const pt=ca(ve(i,I),X);ke=ve(r.dirtyFields,I),pt?hn(r.dirtyFields,I):wt(r.dirtyFields,I,!0),ft.dirtyFields=r.dirtyFields,de=de||m.dirtyFields&&ke!==!pt}if(Z){const pt=ve(r.touchedFields,I);pt||(wt(r.touchedFields,I,Z),ft.touchedFields=r.touchedFields,de=de||m.touchedFields&&pt!==Z)}return de&&he&&g.state.next(ft),de?ft:{}},O=(I,X,Z,we)=>{const he=ve(r.errors,I),de=m.isValid&&No(X)&&r.isValid!==X;if(e.delayError&&Z?(d=S(()=>P(I,Z)),d(e.delayError)):(clearTimeout(h),d=null,Z?wt(r.errors,I,Z):hn(r.errors,I)),(Z?!ca(he,Z):he)||!Fr(we)||de){const ke={...we,...de&&No(X)?{isValid:X}:{},errors:r.errors,name:I};r={...r,...ke},g.state.next(ke)}E(!1)},F=async I=>n.resolver(s,n.context,UG(I||u.mount,o,n.criteriaMode,n.shouldUseNativeValidation)),V=async I=>{const{errors:X}=await F(I);if(I)for(const Z of I){const we=ve(X,Z);we?wt(r.errors,Z,we):hn(r.errors,Z)}else r.errors=X;return X},J=async(I,X,Z={valid:!0})=>{for(const we in I){const he=I[we];if(he){const{_f:de,...ke}=he;if(de){const ft=u.array.has(de.name),pt=await C2(he,s,C,n.shouldUseNativeValidation&&!X,ft);if(pt[de.name]&&(Z.valid=!1,X))break;!X&&(ve(pt,de.name)?ft?FG(r.errors,pt,de.name):wt(r.errors,de.name,pt[de.name]):hn(r.errors,de.name))}ke&&await J(ke,X,Z)}}return Z.valid},G=()=>{for(const I of u.unMount){const X=ve(o,I);X&&(X._f.refs?X._f.refs.every(Z=>!P0(Z)):!P0(X._f.ref))&&fe(I)}u.unMount=new Set},ae=(I,X)=>(I&&X&&wt(s,I,X),!ca(ge(),i)),U=(I,X,Z)=>W5(I,u,{...l.mount?s:Ht(X)?i:Fo(I)?{[I]:X}:X},Z,X),te=I=>Ud(ve(l.mount?s:i,I,e.shouldUnregister?ve(i,I,[]):[])),L=(I,X,Z={})=>{const we=ve(o,I);let he=X;if(we){const de=we._f;de&&(!de.disabled&&wt(s,I,Q5(X,de)),he=Uh(de.ref)&&Ln(X)?"":X,X5(de.ref)?[...de.ref.options].forEach(ke=>ke.selected=he.includes(ke.value)):de.refs?Bd(de.ref)?de.refs.length>1?de.refs.forEach(ke=>(!ke.defaultChecked||!ke.disabled)&&(ke.checked=Array.isArray(he)?!!he.find(ft=>ft===ke.value):he===ke.value)):de.refs[0]&&(de.refs[0].checked=!!he):de.refs.forEach(ke=>ke.checked=ke.value===he):Hx(de.ref)?de.ref.value="":(de.ref.value=he,de.ref.type||g.values.next({name:I,values:{...s}})))}(Z.shouldDirty||Z.shouldTouch)&&A(I,he,Z.shouldTouch,Z.shouldDirty,!0),Z.shouldValidate&&le(I)},ie=(I,X,Z)=>{for(const we in X){const he=X[we],de=`${I}.${we}`,ke=ve(o,de);(u.array.has(I)||!Wh(he)||ke&&!ke._f)&&!xl(he)?ie(de,he,Z):L(de,he,Z)}},K=(I,X,Z={})=>{const we=ve(o,I),he=u.array.has(I),de=so(X);wt(s,I,de),he?(g.array.next({name:I,values:{...s}}),(m.isDirty||m.dirtyFields)&&Z.shouldDirty&&g.state.next({name:I,dirtyFields:A0(i,s),isDirty:ae(I,de)})):we&&!we._f&&!Ln(de)?ie(I,de,Z):L(I,de,Z),x2(I,u)&&g.state.next({...r}),g.values.next({name:I,values:{...s}}),!l.mount&&t()},Q=async I=>{const X=I.target;let Z=X.name,we=!0;const he=ve(o,Z),de=()=>X.type?O0(he._f):F5(I),ke=ft=>{we=Number.isNaN(ft)||ft===ve(s,Z,ft)};if(he){let ft,pt;const bn=de(),Cr=I.type===Bh.BLUR||I.type===Bh.FOCUS_OUT,ki=!VG(he._f)&&!n.resolver&&!ve(r.errors,Z)&&!he._f.deps||WG(Cr,ve(r.touchedFields,Z),r.isSubmitted,_,x),_o=x2(Z,u,Cr);wt(s,Z,bn),Cr?(he._f.onBlur&&he._f.onBlur(I),d&&d(0)):he._f.onChange&&he._f.onChange(I);const Vn=A(Z,bn,Cr,!1),Da=!Fr(Vn)||_o;if(!Cr&&g.values.next({name:Z,type:I.type,values:{...s}}),ki)return m.isValid&&b(),Da&&g.state.next({name:Z,..._o?{}:Vn});if(!Cr&&_o&&g.state.next({...r}),E(!0),n.resolver){const{errors:Ri}=await F([Z]);if(ke(bn),we){const zs=$2(r.errors,o,Z),Ti=$2(Ri,o,zs.name||Z);ft=Ti.error,Z=Ti.name,pt=Fr(Ri)}}else ft=(await C2(he,s,C,n.shouldUseNativeValidation))[Z],ke(bn),we&&(ft?pt=!1:m.isValid&&(pt=await J(o,!0)));we&&(he._f.deps&&le(he._f.deps),O(Z,pt,ft,Vn))}},W=(I,X)=>{if(ve(r.errors,X)&&I.focus)return I.focus(),1},le=async(I,X={})=>{let Z,we;const he=Yp(I);if(E(!0),n.resolver){const de=await V(Ht(I)?I:he);Z=Fr(de),we=I?!he.some(ke=>ve(de,ke)):Z}else I?(we=(await Promise.all(he.map(async de=>{const ke=ve(o,de);return await J(ke&&ke._f?{[de]:ke}:ke)}))).every(Boolean),!(!we&&!r.isValid)&&b()):we=Z=await J(o);return g.state.next({...!Fo(I)||m.isValid&&Z!==r.isValid?{}:{name:I},...n.resolver||!I?{isValid:Z}:{},errors:r.errors,isValidating:!1}),X.shouldFocus&&!we&&Gp(o,W,I?he:u.mount),we},ge=I=>{const X={...i,...l.mount?s:{}};return Ht(I)?X:Fo(I)?ve(X,I):I.map(Z=>ve(X,Z))},Ve=(I,X)=>({invalid:!!ve((X||r).errors,I),isDirty:!!ve((X||r).dirtyFields,I),isTouched:!!ve((X||r).touchedFields,I),error:ve((X||r).errors,I)}),Ue=I=>{I&&Yp(I).forEach(X=>hn(r.errors,X)),g.state.next({errors:I?r.errors:{}})},We=(I,X,Z)=>{const we=(ve(o,I,{_f:{}})._f||{}).ref;wt(r.errors,I,{...X,ref:we}),g.state.next({name:I,errors:r.errors,isValid:!1}),Z&&Z.shouldFocus&&we&&we.focus&&we.focus()},Me=(I,X)=>ds(I)?g.values.subscribe({next:Z=>I(U(void 0,X),Z)}):U(I,X,!0),fe=(I,X={})=>{for(const Z of I?Yp(I):u.mount)u.mount.delete(Z),u.array.delete(Z),X.keepValue||(hn(o,Z),hn(s,Z)),!X.keepError&&hn(r.errors,Z),!X.keepDirty&&hn(r.dirtyFields,Z),!X.keepTouched&&hn(r.touchedFields,Z),!n.shouldUnregister&&!X.keepDefaultValue&&hn(i,Z);g.values.next({values:{...s}}),g.state.next({...r,...X.keepDirty?{isDirty:ae()}:{}}),!X.keepIsValid&&b()},xe=({disabled:I,name:X,field:Z,fields:we,value:he})=>{if(No(I)){const de=I?void 0:Ht(he)?O0(Z?Z._f:ve(we,X)._f):he;wt(s,X,de),A(X,de,!1,!1,!0)}},$e=(I,X={})=>{let Z=ve(o,I);const we=No(X.disabled);return wt(o,I,{...Z||{},_f:{...Z&&Z._f?Z._f:{ref:{name:I}},name:I,mount:!0,...X}}),u.mount.add(I),Z?xe({field:Z,disabled:X.disabled,name:I}):M(I,!0,X.value),{...we?{disabled:X.disabled}:{},...n.progressive?{required:!!X.required,min:iu(X.min),max:iu(X.max),minLength:iu(X.minLength),maxLength:iu(X.maxLength),pattern:iu(X.pattern)}:{},name:I,onChange:Q,onBlur:Q,ref:he=>{if(he){$e(I,X),Z=ve(o,I);const de=Ht(he.value)&&he.querySelectorAll&&he.querySelectorAll("input,select,textarea")[0]||he,ke=BG(de),ft=Z._f.refs||[];if(ke?ft.find(pt=>pt===de):de===Z._f.ref)return;wt(o,I,{_f:{...Z._f,...ke?{refs:[...ft.filter(P0),de,...Array.isArray(ve(i,I))?[{}]:[]],ref:{type:de.type,name:I}}:{ref:de}}}),M(I,!1,void 0,de)}else Z=ve(o,I,{}),Z._f&&(Z._f.mount=!1),(n.shouldUnregister||X.shouldUnregister)&&!(j5(u.array,I)&&l.action)&&u.unMount.add(I)}}},Ae=()=>n.shouldFocusError&&Gp(o,W,u.mount),Oe=I=>{No(I)&&(g.state.next({disabled:I}),Gp(o,X=>{X.disabled=I},0,!1))},je=(I,X)=>async Z=>{Z&&(Z.preventDefault&&Z.preventDefault(),Z.persist&&Z.persist());let we=so(s);if(g.state.next({isSubmitting:!0}),n.resolver){const{errors:he,values:de}=await F();r.errors=he,we=de}else await J(o);hn(r.errors,"root"),Fr(r.errors)?(g.state.next({errors:{}}),await I(we,Z)):(X&&await X({...r.errors},Z),Ae(),setTimeout(Ae)),g.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:Fr(r.errors),submitCount:r.submitCount+1,errors:r.errors})},Ot=(I,X={})=>{ve(o,I)&&(Ht(X.defaultValue)?K(I,ve(i,I)):(K(I,X.defaultValue),wt(i,I,X.defaultValue)),X.keepTouched||hn(r.touchedFields,I),X.keepDirty||(hn(r.dirtyFields,I),r.isDirty=X.defaultValue?ae(I,ve(i,I)):ae()),X.keepError||(hn(r.errors,I),m.isValid&&b()),g.state.next({...r}))},ct=(I,X={})=>{const Z=I?so(I):i,we=so(Z),he=I&&!Fr(I)?we:i;if(X.keepDefaultValues||(i=Z),!X.keepValues){if(X.keepDirtyValues||y)for(const de of u.mount)ve(r.dirtyFields,de)?wt(he,de,ve(s,de)):K(de,ve(he,de));else{if(Ux&&Ht(I))for(const de of u.mount){const ke=ve(o,de);if(ke&&ke._f){const ft=Array.isArray(ke._f.refs)?ke._f.refs[0]:ke._f.ref;if(Uh(ft)){const pt=ft.closest("form");if(pt){pt.reset();break}}}}o={}}s=e.shouldUnregister?X.keepDefaultValues?so(i):{}:so(he),g.array.next({values:{...he}}),g.values.next({values:{...he}})}u={mount:new Set,unMount:new Set,array:new Set,watch:new Set,watchAll:!1,focus:""},!l.mount&&t(),l.mount=!m.isValid||!!X.keepIsValid,l.watch=!!e.shouldUnregister,g.state.next({submitCount:X.keepSubmitCount?r.submitCount:0,isDirty:X.keepDirty?r.isDirty:!!(X.keepDefaultValues&&!ca(I,i)),isSubmitted:X.keepIsSubmitted?r.isSubmitted:!1,dirtyFields:X.keepDirtyValues?r.dirtyFields:X.keepDefaultValues&&I?A0(i,I):{},touchedFields:X.keepTouched?r.touchedFields:{},errors:X.keepErrors?r.errors:{},isSubmitSuccessful:X.keepIsSubmitSuccessful?r.isSubmitSuccessful:!1,isSubmitting:!1})},Yt=(I,X)=>ct(ds(I)?I(s):I,X);return{control:{register:$e,unregister:fe,getFieldState:Ve,handleSubmit:je,setError:We,_executeSchema:F,_getWatch:U,_getDirty:ae,_updateValid:b,_removeUnmounted:G,_updateFieldArray:k,_updateDisabledField:xe,_getFieldArray:te,_reset:ct,_resetDefaultValues:()=>ds(n.defaultValues)&&n.defaultValues().then(I=>{Yt(I,n.resetOptions),g.state.next({isLoading:!1})}),_updateFormState:I=>{r={...r,...I}},_disableForm:Oe,_subjects:g,_proxyFormState:m,get _fields(){return o},get _formValues(){return s},get _state(){return l},set _state(I){l=I},get _defaultValues(){return i},get _names(){return u},set _names(I){u=I},get _formState(){return r},set _formState(I){r=I},get _options(){return n},set _options(I){n={...n,...I}}},trigger:le,register:$e,handleSubmit:je,watch:Me,setValue:K,getValues:ge,reset:Yt,resetField:Ot,clearErrors:Ue,unregister:fe,setError:We,setFocus:(I,X={})=>{const Z=ve(o,I),we=Z&&Z._f;if(we){const he=we.refs?we.refs[0]:we.ref;he.focus&&(he.focus(),X.shouldSelect&&he.select())}},getFieldState:Ve}}function GG(e={}){const t=Fe.useRef(),n=Fe.useRef(),[r,o]=Fe.useState({isDirty:!1,isValidating:!1,isLoading:ds(e.defaultValues),isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,submitCount:0,dirtyFields:{},touchedFields:{},errors:{},disabled:!1,defaultValues:ds(e.defaultValues)?void 0:e.defaultValues});t.current||(t.current={...YG(e,()=>o(s=>({...s}))),formState:r});const i=t.current.control;return i._options=e,Vx({subject:i._subjects.state,next:s=>{U5(s,i._proxyFormState,i._updateFormState,!0)&&o({...i._formState})}}),Fe.useEffect(()=>i._disableForm(e.disabled),[i,e.disabled]),Fe.useEffect(()=>{if(i._proxyFormState.isDirty){const s=i._getDirty();s!==r.isDirty&&i._subjects.state.next({isDirty:s})}},[i,r.isDirty]),Fe.useEffect(()=>{e.values&&!ca(e.values,n.current)?(i._reset(e.values,i._options.resetOptions),n.current=e.values):i._resetDefaultValues()},[e.values,i]),Fe.useEffect(()=>{i._state.mount||(i._updateValid(),i._state.mount=!0),i._state.watch&&(i._state.watch=!1,i._subjects.state.next({...i._formState})),i._removeUnmounted()}),t.current.formState=B5(r,i),t.current}var k2=function(e,t,n){if(e&&"reportValidity"in e){var r=ve(n,t);e.setCustomValidity(r&&r.message||""),e.reportValidity()}},J5=function(e,t){var n=function(o){var i=t.fields[o];i&&i.ref&&"reportValidity"in i.ref?k2(i.ref,o,e):i.refs&&i.refs.forEach(function(s){return k2(s,o,e)})};for(var r in t.fields)n(r)},XG=function(e,t){t.shouldUseNativeValidation&&J5(e,t);var n={};for(var r in e){var o=ve(t.fields,r),i=Object.assign(e[r]||{},{ref:o&&o.ref});if(qG(t.names||Object.keys(e),r)){var s=Object.assign({},ZG(ve(n,r)));wt(s,"root",i),wt(n,r,s)}else wt(n,r,i)}return n},ZG=function(e){return Array.isArray(e)?e.filter(Boolean):[]},qG=function(e,t){return e.some(function(n){return n.startsWith(t+".")})},QG=function(e,t){for(var n={};e.length;){var r=e[0],o=r.code,i=r.message,s=r.path.join(".");if(!n[s])if("unionErrors"in r){var l=r.unionErrors[0].errors[0];n[s]={message:l.message,type:l.code}}else n[s]={message:i,type:o};if("unionErrors"in r&&r.unionErrors.forEach(function(h){return h.errors.forEach(function(m){return e.push(m)})}),t){var u=n[s].types,d=u&&u[r.code];n[s]=K5(s,t,n,o,d?[].concat(d,r.message):r.message)}e.shift()}return n},JG=function(e,t,n){return n===void 0&&(n={}),function(r,o,i){try{return Promise.resolve(function(s,l){try{var u=Promise.resolve(e[n.mode==="sync"?"parse":"parseAsync"](r,t)).then(function(d){return i.shouldUseNativeValidation&&J5({},i),{errors:{},values:n.raw?r:d}})}catch(d){return l(d)}return u&&u.then?u.then(void 0,l):u}(0,function(s){if(function(l){return l.errors!=null}(s))return{values:{},errors:XG(QG(s.errors,!i.shouldUseNativeValidation&&i.criteriaMode==="all"),i)};throw s}))}catch(s){return Promise.reject(s)}}},mt;(function(e){e.assertEqual=o=>o;function t(o){}e.assertIs=t;function n(o){throw new Error}e.assertNever=n,e.arrayToEnum=o=>{const i={};for(const s of o)i[s]=s;return i},e.getValidEnumValues=o=>{const i=e.objectKeys(o).filter(l=>typeof o[o[l]]!="number"),s={};for(const l of i)s[l]=o[l];return e.objectValues(s)},e.objectValues=o=>e.objectKeys(o).map(function(i){return o[i]}),e.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{const i=[];for(const s in o)Object.prototype.hasOwnProperty.call(o,s)&&i.push(s);return i},e.find=(o,i)=>{for(const s of o)if(i(s))return s},e.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&isFinite(o)&&Math.floor(o)===o;function r(o,i=" | "){return o.map(s=>typeof s=="string"?`'${s}'`:s).join(i)}e.joinValues=r,e.jsonStringifyReplacer=(o,i)=>typeof i=="bigint"?i.toString():i})(mt||(mt={}));var R2;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(R2||(R2={}));const be=mt.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ta=e=>{switch(typeof e){case"undefined":return be.undefined;case"string":return be.string;case"number":return isNaN(e)?be.nan:be.number;case"boolean":return be.boolean;case"function":return be.function;case"bigint":return be.bigint;case"symbol":return be.symbol;case"object":return Array.isArray(e)?be.array:e===null?be.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?be.promise:typeof Map<"u"&&e instanceof Map?be.map:typeof Set<"u"&&e instanceof Set?be.set:typeof Date<"u"&&e instanceof Date?be.date:be.object;default:return be.unknown}},pe=mt.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"]);class Bo 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(i){return i.message},r={_errors:[]},o=i=>{for(const s of i.issues)if(s.code==="invalid_union")s.unionErrors.map(o);else if(s.code==="invalid_return_type")o(s.returnTypeError);else if(s.code==="invalid_arguments")o(s.argumentsError);else if(s.path.length===0)r._errors.push(n(s));else{let l=r,u=0;for(;un.message){const n={},r=[];for(const o of this.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(t(o))):r.push(t(o));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}}Bo.create=e=>new Bo(e);const Kh=(e,t)=>{let n;switch(e.code){case pe.invalid_type:e.received===be.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case pe.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,mt.jsonStringifyReplacer)}`;break;case pe.unrecognized_keys:n=`Unrecognized key(s) in object: ${mt.joinValues(e.keys,", ")}`;break;case pe.invalid_union:n="Invalid input";break;case pe.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${mt.joinValues(e.options)}`;break;case pe.invalid_enum_value:n=`Invalid enum value. Expected ${mt.joinValues(e.options)}, received '${e.received}'`;break;case pe.invalid_arguments:n="Invalid function arguments";break;case pe.invalid_return_type:n="Invalid function return type";break;case pe.invalid_date:n="Invalid date";break;case pe.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}"`:mt.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case pe.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 pe.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 pe.custom:n="Invalid input";break;case pe.invalid_intersection_types:n="Intersection results could not be merged";break;case pe.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case pe.not_finite:n="Number must be finite";break;default:n=t.defaultError,mt.assertNever(e)}return{message:n}};let eX=Kh;function S1(){return eX}const E1=e=>{const{data:t,path:n,errorMaps:r,issueData:o}=e,i=[...n,...o.path||[]],s={...o,path:i};let l="";const u=r.filter(d=>!!d).slice().reverse();for(const d of u)l=d(s,{data:t,defaultError:l}).message;return{...o,path:i,message:o.message||l}};function Ee(e,t){const n=E1({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,S1(),Kh].filter(r=>!!r)});e.common.issues.push(n)}class zn{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 o of n){if(o.status==="aborted")return Ze;o.status==="dirty"&&t.dirty(),r.push(o.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){const r=[];for(const o of n)r.push({key:await o.key,value:await o.value});return zn.mergeObjectSync(t,r)}static mergeObjectSync(t,n){const r={};for(const o of n){const{key:i,value:s}=o;if(i.status==="aborted"||s.status==="aborted")return Ze;i.status==="dirty"&&t.dirty(),s.status==="dirty"&&t.dirty(),i.value!=="__proto__"&&(typeof s.value<"u"||o.alwaysSet)&&(r[i.value]=s.value)}return{status:t.value,value:r}}}const Ze=Object.freeze({status:"aborted"}),tX=e=>({status:"dirty",value:e}),rr=e=>({status:"valid",value:e}),T2=e=>e.status==="aborted",P2=e=>e.status==="dirty",Yh=e=>e.status==="valid",C1=e=>typeof Promise<"u"&&e instanceof Promise;var Ne;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t==null?void 0:t.message})(Ne||(Ne={}));class Ko{constructor(t,n,r,o){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=o}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 A2=(e,t)=>{if(Yh(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 Bo(e.common.issues);return this._error=n,this._error}}};function Xe(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:r,description:o}=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:o}:{errorMap:(s,l)=>s.code!=="invalid_type"?{message:l.defaultError}:typeof l.data>"u"?{message:r??l.defaultError}:{message:n??l.defaultError},description:o}}class rt{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.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this)}get description(){return this._def.description}_getType(t){return ta(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:ta(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new zn,ctx:{common:t.parent.common,data:t.data,parsedType:ta(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const n=this._parse(t);if(C1(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 o={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:ta(t)},i=this._parseSync({data:t,path:o.path,parent:o});return A2(o,i)}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:ta(t)},o=this._parse({data:t,path:r.path,parent:r}),i=await(C1(o)?o:Promise.resolve(o));return A2(r,i)}refine(t,n){const r=o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n;return this._refinement((o,i)=>{const s=t(o),l=()=>i.addIssue({code:pe.custom,...r(o)});return typeof Promise<"u"&&s instanceof Promise?s.then(u=>u?!0:(l(),!1)):s?!0:(l(),!1)})}refinement(t,n){return this._refinement((r,o)=>t(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(t){return new Si({schema:this,typeName:ze.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}optional(){return bs.create(this,this._def)}nullable(){return uc.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Uo.create(this,this._def)}promise(){return ad.create(this,this._def)}or(t){return Zh.create([this,t],this._def)}and(t){return qh.create(this,t,this._def)}transform(t){return new Si({...Xe(this._def),schema:this,typeName:ze.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const n=typeof t=="function"?t:()=>t;return new nm({...Xe(this._def),innerType:this,defaultValue:n,typeName:ze.ZodDefault})}brand(){return new pX({typeName:ze.ZodBranded,type:this,...Xe(this._def)})}catch(t){const n=typeof t=="function"?t:()=>t;return new O1({...Xe(this._def),innerType:this,catchValue:n,typeName:ze.ZodCatch})}describe(t){const n=this.constructor;return new n({...this._def,description:t})}pipe(t){return sg.create(this,t)}readonly(){return N1.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const nX=/^c[^\s-]{8,}$/i,rX=/^[a-z][a-z0-9]*$/,oX=/^[0-9A-HJKMNP-TV-Z]{26}$/,iX=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,sX=/^(?!\.)(?!.*\.\.)([A-Z0-9_+-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,aX="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let M0;const lX=/^(((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}))$/,cX=/^(([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})))$/,uX=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 dX(e,t){return!!((t==="v4"||!t)&&lX.test(e)||(t==="v6"||!t)&&cX.test(e))}class di extends rt{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==be.string){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_type,expected:be.string,received:i.parsedType}),Ze}const r=new zn;let o;for(const i of this._def.checks)if(i.kind==="min")t.data.lengthi.value&&(o=this._getOrReturnCtx(t,o),Ee(o,{code:pe.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){const s=t.data.length>i.value,l=t.data.lengtht.test(o),{validation:n,code:pe.invalid_string,...Ne.errToObj(r)})}_addCheck(t){return new di({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...Ne.errToObj(t)})}url(t){return this._addCheck({kind:"url",...Ne.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...Ne.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...Ne.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...Ne.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...Ne.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...Ne.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...Ne.errToObj(t)})}datetime(t){var n;return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof(t==null?void 0:t.precision)>"u"?null:t==null?void 0:t.precision,offset:(n=t==null?void 0:t.offset)!==null&&n!==void 0?n:!1,...Ne.errToObj(t==null?void 0:t.message)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...Ne.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n==null?void 0:n.position,...Ne.errToObj(n==null?void 0:n.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...Ne.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...Ne.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...Ne.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...Ne.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...Ne.errToObj(n)})}nonempty(t){return this.min(1,Ne.errToObj(t))}trim(){return new di({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new di({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new di({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}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 di({checks:[],typeName:ze.ZodString,coerce:(t=e==null?void 0:e.coerce)!==null&&t!==void 0?t:!1,...Xe(e)})};function fX(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,o=n>r?n:r,i=parseInt(e.toFixed(o).replace(".","")),s=parseInt(t.toFixed(o).replace(".",""));return i%s/Math.pow(10,o)}class ac extends rt{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)!==be.number){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_type,expected:be.number,received:i.parsedType}),Ze}let r;const o=new zn;for(const i of this._def.checks)i.kind==="int"?mt.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.invalid_type,expected:"integer",received:"float",message:i.message}),o.dirty()):i.kind==="min"?(i.inclusive?t.datai.value:t.data>=i.value)&&(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),o.dirty()):i.kind==="multipleOf"?fX(t.data,i.value)!==0&&(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):i.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.not_finite,message:i.message}),o.dirty()):mt.assertNever(i);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,Ne.toString(n))}gt(t,n){return this.setLimit("min",t,!1,Ne.toString(n))}lte(t,n){return this.setLimit("max",t,!0,Ne.toString(n))}lt(t,n){return this.setLimit("max",t,!1,Ne.toString(n))}setLimit(t,n,r,o){return new ac({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:Ne.toString(o)}]})}_addCheck(t){return new ac({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:Ne.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Ne.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Ne.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Ne.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Ne.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:Ne.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:Ne.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Ne.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Ne.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"&&mt.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 ac({checks:[],typeName:ze.ZodNumber,coerce:(e==null?void 0:e.coerce)||!1,...Xe(e)});class lc extends rt{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)!==be.bigint){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_type,expected:be.bigint,received:i.parsedType}),Ze}let r;const o=new zn;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?t.datai.value:t.data>=i.value)&&(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),o.dirty()):i.kind==="multipleOf"?t.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):mt.assertNever(i);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,Ne.toString(n))}gt(t,n){return this.setLimit("min",t,!1,Ne.toString(n))}lte(t,n){return this.setLimit("max",t,!0,Ne.toString(n))}lt(t,n){return this.setLimit("max",t,!1,Ne.toString(n))}setLimit(t,n,r,o){return new lc({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:Ne.toString(o)}]})}_addCheck(t){return new lc({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Ne.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Ne.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Ne.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Ne.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:Ne.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 lc({checks:[],typeName:ze.ZodBigInt,coerce:(t=e==null?void 0:e.coerce)!==null&&t!==void 0?t:!1,...Xe(e)})};class $1 extends rt{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==be.boolean){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.boolean,received:r.parsedType}),Ze}return rr(t.data)}}$1.create=e=>new $1({typeName:ze.ZodBoolean,coerce:(e==null?void 0:e.coerce)||!1,...Xe(e)});class sd extends rt{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==be.date){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_type,expected:be.date,received:i.parsedType}),Ze}if(isNaN(t.data.getTime())){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_date}),Ze}const r=new zn;let o;for(const i of this._def.checks)i.kind==="min"?t.data.getTime()i.value&&(o=this._getOrReturnCtx(t,o),Ee(o,{code:pe.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):mt.assertNever(i);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new sd({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:Ne.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:Ne.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 sd({checks:[],coerce:(e==null?void 0:e.coerce)||!1,typeName:ze.ZodDate,...Xe(e)});class k1 extends rt{_parse(t){if(this._getType(t)!==be.symbol){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.symbol,received:r.parsedType}),Ze}return rr(t.data)}}k1.create=e=>new k1({typeName:ze.ZodSymbol,...Xe(e)});class Gh extends rt{_parse(t){if(this._getType(t)!==be.undefined){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.undefined,received:r.parsedType}),Ze}return rr(t.data)}}Gh.create=e=>new Gh({typeName:ze.ZodUndefined,...Xe(e)});class Xh extends rt{_parse(t){if(this._getType(t)!==be.null){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.null,received:r.parsedType}),Ze}return rr(t.data)}}Xh.create=e=>new Xh({typeName:ze.ZodNull,...Xe(e)});class R1 extends rt{constructor(){super(...arguments),this._any=!0}_parse(t){return rr(t.data)}}R1.create=e=>new R1({typeName:ze.ZodAny,...Xe(e)});class Tl extends rt{constructor(){super(...arguments),this._unknown=!0}_parse(t){return rr(t.data)}}Tl.create=e=>new Tl({typeName:ze.ZodUnknown,...Xe(e)});class Rs extends rt{_parse(t){const n=this._getOrReturnCtx(t);return Ee(n,{code:pe.invalid_type,expected:be.never,received:n.parsedType}),Ze}}Rs.create=e=>new Rs({typeName:ze.ZodNever,...Xe(e)});class T1 extends rt{_parse(t){if(this._getType(t)!==be.undefined){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.void,received:r.parsedType}),Ze}return rr(t.data)}}T1.create=e=>new T1({typeName:ze.ZodVoid,...Xe(e)});class Uo extends rt{_parse(t){const{ctx:n,status:r}=this._processInputParams(t),o=this._def;if(n.parsedType!==be.array)return Ee(n,{code:pe.invalid_type,expected:be.array,received:n.parsedType}),Ze;if(o.exactLength!==null){const s=n.data.length>o.exactLength.value,l=n.data.lengtho.maxLength.value&&(Ee(n,{code:pe.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((s,l)=>o.type._parseAsync(new Ko(n,s,n.path,l)))).then(s=>zn.mergeArray(r,s));const i=[...n.data].map((s,l)=>o.type._parseSync(new Ko(n,s,n.path,l)));return zn.mergeArray(r,i)}get element(){return this._def.type}min(t,n){return new Uo({...this._def,minLength:{value:t,message:Ne.toString(n)}})}max(t,n){return new Uo({...this._def,maxLength:{value:t,message:Ne.toString(n)}})}length(t,n){return new Uo({...this._def,exactLength:{value:t,message:Ne.toString(n)}})}nonempty(t){return this.min(1,t)}}Uo.create=(e,t)=>new Uo({type:e,minLength:null,maxLength:null,exactLength:null,typeName:ze.ZodArray,...Xe(t)});function ol(e){if(e instanceof Vt){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=bs.create(ol(r))}return new Vt({...e._def,shape:()=>t})}else return e instanceof Uo?new Uo({...e._def,type:ol(e.element)}):e instanceof bs?bs.create(ol(e.unwrap())):e instanceof uc?uc.create(ol(e.unwrap())):e instanceof _i?_i.create(e.items.map(t=>ol(t))):e}class Vt extends rt{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=mt.objectKeys(t);return this._cached={shape:t,keys:n}}_parse(t){if(this._getType(t)!==be.object){const d=this._getOrReturnCtx(t);return Ee(d,{code:pe.invalid_type,expected:be.object,received:d.parsedType}),Ze}const{status:r,ctx:o}=this._processInputParams(t),{shape:i,keys:s}=this._getCached(),l=[];if(!(this._def.catchall instanceof Rs&&this._def.unknownKeys==="strip"))for(const d in o.data)s.includes(d)||l.push(d);const u=[];for(const d of s){const h=i[d],m=o.data[d];u.push({key:{status:"valid",value:d},value:h._parse(new Ko(o,m,o.path,d)),alwaysSet:d in o.data})}if(this._def.catchall instanceof Rs){const d=this._def.unknownKeys;if(d==="passthrough")for(const h of l)u.push({key:{status:"valid",value:h},value:{status:"valid",value:o.data[h]}});else if(d==="strict")l.length>0&&(Ee(o,{code:pe.unrecognized_keys,keys:l}),r.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const d=this._def.catchall;for(const h of l){const m=o.data[h];u.push({key:{status:"valid",value:h},value:d._parse(new Ko(o,m,o.path,h)),alwaysSet:h in o.data})}}return o.common.async?Promise.resolve().then(async()=>{const d=[];for(const h of u){const m=await h.key;d.push({key:m,value:await h.value,alwaysSet:h.alwaysSet})}return d}).then(d=>zn.mergeObjectSync(r,d)):zn.mergeObjectSync(r,u)}get shape(){return this._def.shape()}strict(t){return Ne.errToObj,new Vt({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{var o,i,s,l;const u=(s=(i=(o=this._def).errorMap)===null||i===void 0?void 0:i.call(o,n,r).message)!==null&&s!==void 0?s:r.defaultError;return n.code==="unrecognized_keys"?{message:(l=Ne.errToObj(t).message)!==null&&l!==void 0?l:u}:{message:u}}}:{}})}strip(){return new Vt({...this._def,unknownKeys:"strip"})}passthrough(){return new Vt({...this._def,unknownKeys:"passthrough"})}extend(t){return new Vt({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new Vt({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:ze.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new Vt({...this._def,catchall:t})}pick(t){const n={};return mt.objectKeys(t).forEach(r=>{t[r]&&this.shape[r]&&(n[r]=this.shape[r])}),new Vt({...this._def,shape:()=>n})}omit(t){const n={};return mt.objectKeys(this.shape).forEach(r=>{t[r]||(n[r]=this.shape[r])}),new Vt({...this._def,shape:()=>n})}deepPartial(){return ol(this)}partial(t){const n={};return mt.objectKeys(this.shape).forEach(r=>{const o=this.shape[r];t&&!t[r]?n[r]=o:n[r]=o.optional()}),new Vt({...this._def,shape:()=>n})}required(t){const n={};return mt.objectKeys(this.shape).forEach(r=>{if(t&&!t[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof bs;)i=i._def.innerType;n[r]=i}}),new Vt({...this._def,shape:()=>n})}keyof(){return e3(mt.objectKeys(this.shape))}}Vt.create=(e,t)=>new Vt({shape:()=>e,unknownKeys:"strip",catchall:Rs.create(),typeName:ze.ZodObject,...Xe(t)});Vt.strictCreate=(e,t)=>new Vt({shape:()=>e,unknownKeys:"strict",catchall:Rs.create(),typeName:ze.ZodObject,...Xe(t)});Vt.lazycreate=(e,t)=>new Vt({shape:e,unknownKeys:"strip",catchall:Rs.create(),typeName:ze.ZodObject,...Xe(t)});class Zh extends rt{_parse(t){const{ctx:n}=this._processInputParams(t),r=this._def.options;function o(i){for(const l of i)if(l.result.status==="valid")return l.result;for(const l of i)if(l.result.status==="dirty")return n.common.issues.push(...l.ctx.common.issues),l.result;const s=i.map(l=>new Bo(l.ctx.common.issues));return Ee(n,{code:pe.invalid_union,unionErrors:s}),Ze}if(n.common.async)return Promise.all(r.map(async i=>{const s={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:s}),ctx:s}})).then(o);{let i;const s=[];for(const u of r){const d={...n,common:{...n.common,issues:[]},parent:null},h=u._parseSync({data:n.data,path:n.path,parent:d});if(h.status==="valid")return h;h.status==="dirty"&&!i&&(i={result:h,ctx:d}),d.common.issues.length&&s.push(d.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;const l=s.map(u=>new Bo(u));return Ee(n,{code:pe.invalid_union,unionErrors:l}),Ze}}get options(){return this._def.options}}Zh.create=(e,t)=>new Zh({options:e,typeName:ze.ZodUnion,...Xe(t)});const Zp=e=>e instanceof Jh?Zp(e.schema):e instanceof Si?Zp(e.innerType()):e instanceof em?[e.value]:e instanceof Ta?e.options:e instanceof tm?Object.keys(e.enum):e instanceof nm?Zp(e._def.innerType):e instanceof Gh?[void 0]:e instanceof Xh?[null]:null;class Yx extends rt{_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.object)return Ee(n,{code:pe.invalid_type,expected:be.object,received:n.parsedType}),Ze;const r=this.discriminator,o=n.data[r],i=this.optionsMap.get(o);return i?n.common.async?i._parseAsync({data:n.data,path:n.path,parent:n}):i._parseSync({data:n.data,path:n.path,parent:n}):(Ee(n,{code:pe.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),Ze)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){const o=new Map;for(const i of n){const s=Zp(i.shape[t]);if(!s)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const l of s){if(o.has(l))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(l)}`);o.set(l,i)}}return new Yx({typeName:ze.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:o,...Xe(r)})}}function P1(e,t){const n=ta(e),r=ta(t);if(e===t)return{valid:!0,data:e};if(n===be.object&&r===be.object){const o=mt.objectKeys(t),i=mt.objectKeys(e).filter(l=>o.indexOf(l)!==-1),s={...e,...t};for(const l of i){const u=P1(e[l],t[l]);if(!u.valid)return{valid:!1};s[l]=u.data}return{valid:!0,data:s}}else if(n===be.array&&r===be.array){if(e.length!==t.length)return{valid:!1};const o=[];for(let i=0;i{if(T2(i)||T2(s))return Ze;const l=P1(i.value,s.value);return l.valid?((P2(i)||P2(s))&&n.dirty(),{status:n.value,value:l.data}):(Ee(r,{code:pe.invalid_intersection_types}),Ze)};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(([i,s])=>o(i,s)):o(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}qh.create=(e,t,n)=>new qh({left:e,right:t,typeName:ze.ZodIntersection,...Xe(n)});class _i extends rt{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.array)return Ee(r,{code:pe.invalid_type,expected:be.array,received:r.parsedType}),Ze;if(r.data.lengththis._def.items.length&&(Ee(r,{code:pe.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const i=[...r.data].map((s,l)=>{const u=this._def.items[l]||this._def.rest;return u?u._parse(new Ko(r,s,r.path,l)):null}).filter(s=>!!s);return r.common.async?Promise.all(i).then(s=>zn.mergeArray(n,s)):zn.mergeArray(n,i)}get items(){return this._def.items}rest(t){return new _i({...this._def,rest:t})}}_i.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new _i({items:e,typeName:ze.ZodTuple,rest:null,...Xe(t)})};class Qh extends rt{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!==be.object)return Ee(r,{code:pe.invalid_type,expected:be.object,received:r.parsedType}),Ze;const o=[],i=this._def.keyType,s=this._def.valueType;for(const l in r.data)o.push({key:i._parse(new Ko(r,l,r.path,l)),value:s._parse(new Ko(r,r.data[l],r.path,l))});return r.common.async?zn.mergeObjectAsync(n,o):zn.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof rt?new Qh({keyType:t,valueType:n,typeName:ze.ZodRecord,...Xe(r)}):new Qh({keyType:di.create(),valueType:t,typeName:ze.ZodRecord,...Xe(n)})}}class A1 extends rt{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!==be.map)return Ee(r,{code:pe.invalid_type,expected:be.map,received:r.parsedType}),Ze;const o=this._def.keyType,i=this._def.valueType,s=[...r.data.entries()].map(([l,u],d)=>({key:o._parse(new Ko(r,l,r.path,[d,"key"])),value:i._parse(new Ko(r,u,r.path,[d,"value"]))}));if(r.common.async){const l=new Map;return Promise.resolve().then(async()=>{for(const u of s){const d=await u.key,h=await u.value;if(d.status==="aborted"||h.status==="aborted")return Ze;(d.status==="dirty"||h.status==="dirty")&&n.dirty(),l.set(d.value,h.value)}return{status:n.value,value:l}})}else{const l=new Map;for(const u of s){const d=u.key,h=u.value;if(d.status==="aborted"||h.status==="aborted")return Ze;(d.status==="dirty"||h.status==="dirty")&&n.dirty(),l.set(d.value,h.value)}return{status:n.value,value:l}}}}A1.create=(e,t,n)=>new A1({valueType:t,keyType:e,typeName:ze.ZodMap,...Xe(n)});class cc extends rt{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.set)return Ee(r,{code:pe.invalid_type,expected:be.set,received:r.parsedType}),Ze;const o=this._def;o.minSize!==null&&r.data.sizeo.maxSize.value&&(Ee(r,{code:pe.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());const i=this._def.valueType;function s(u){const d=new Set;for(const h of u){if(h.status==="aborted")return Ze;h.status==="dirty"&&n.dirty(),d.add(h.value)}return{status:n.value,value:d}}const l=[...r.data.values()].map((u,d)=>i._parse(new Ko(r,u,r.path,d)));return r.common.async?Promise.all(l).then(u=>s(u)):s(l)}min(t,n){return new cc({...this._def,minSize:{value:t,message:Ne.toString(n)}})}max(t,n){return new cc({...this._def,maxSize:{value:t,message:Ne.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}}cc.create=(e,t)=>new cc({valueType:e,minSize:null,maxSize:null,typeName:ze.ZodSet,...Xe(t)});class Pu extends rt{constructor(){super(...arguments),this.validate=this.implement}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.function)return Ee(n,{code:pe.invalid_type,expected:be.function,received:n.parsedType}),Ze;function r(l,u){return E1({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,S1(),Kh].filter(d=>!!d),issueData:{code:pe.invalid_arguments,argumentsError:u}})}function o(l,u){return E1({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,S1(),Kh].filter(d=>!!d),issueData:{code:pe.invalid_return_type,returnTypeError:u}})}const i={errorMap:n.common.contextualErrorMap},s=n.data;if(this._def.returns instanceof ad){const l=this;return rr(async function(...u){const d=new Bo([]),h=await l._def.args.parseAsync(u,i).catch(y=>{throw d.addIssue(r(u,y)),d}),m=await Reflect.apply(s,this,h);return await l._def.returns._def.type.parseAsync(m,i).catch(y=>{throw d.addIssue(o(m,y)),d})})}else{const l=this;return rr(function(...u){const d=l._def.args.safeParse(u,i);if(!d.success)throw new Bo([r(u,d.error)]);const h=Reflect.apply(s,this,d.data),m=l._def.returns.safeParse(h,i);if(!m.success)throw new Bo([o(h,m.error)]);return m.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new Pu({...this._def,args:_i.create(t).rest(Tl.create())})}returns(t){return new Pu({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new Pu({args:t||_i.create([]).rest(Tl.create()),returns:n||Tl.create(),typeName:ze.ZodFunction,...Xe(r)})}}class Jh extends rt{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})}}Jh.create=(e,t)=>new Jh({getter:e,typeName:ze.ZodLazy,...Xe(t)});class em extends rt{_parse(t){if(t.data!==this._def.value){const n=this._getOrReturnCtx(t);return Ee(n,{received:n.data,code:pe.invalid_literal,expected:this._def.value}),Ze}return{status:"valid",value:t.data}}get value(){return this._def.value}}em.create=(e,t)=>new em({value:e,typeName:ze.ZodLiteral,...Xe(t)});function e3(e,t){return new Ta({values:e,typeName:ze.ZodEnum,...Xe(t)})}class Ta extends rt{_parse(t){if(typeof t.data!="string"){const n=this._getOrReturnCtx(t),r=this._def.values;return Ee(n,{expected:mt.joinValues(r),received:n.parsedType,code:pe.invalid_type}),Ze}if(this._def.values.indexOf(t.data)===-1){const n=this._getOrReturnCtx(t),r=this._def.values;return Ee(n,{received:n.data,code:pe.invalid_enum_value,options:r}),Ze}return rr(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 Ta.create(t)}exclude(t){return Ta.create(this.options.filter(n=>!t.includes(n)))}}Ta.create=e3;class tm extends rt{_parse(t){const n=mt.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==be.string&&r.parsedType!==be.number){const o=mt.objectValues(n);return Ee(r,{expected:mt.joinValues(o),received:r.parsedType,code:pe.invalid_type}),Ze}if(n.indexOf(t.data)===-1){const o=mt.objectValues(n);return Ee(r,{received:r.data,code:pe.invalid_enum_value,options:o}),Ze}return rr(t.data)}get enum(){return this._def.values}}tm.create=(e,t)=>new tm({values:e,typeName:ze.ZodNativeEnum,...Xe(t)});class ad extends rt{unwrap(){return this._def.type}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.promise&&n.common.async===!1)return Ee(n,{code:pe.invalid_type,expected:be.promise,received:n.parsedType}),Ze;const r=n.parsedType===be.promise?n.data:Promise.resolve(n.data);return rr(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}}ad.create=(e,t)=>new ad({type:e,typeName:ze.ZodPromise,...Xe(t)});class Si extends rt{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ze.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:n,ctx:r}=this._processInputParams(t),o=this._def.effect||null,i={addIssue:s=>{Ee(r,s),s.fatal?n.abort():n.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),o.type==="preprocess"){const s=o.transform(r.data,i);return r.common.issues.length?{status:"dirty",value:r.data}:r.common.async?Promise.resolve(s).then(l=>this._def.schema._parseAsync({data:l,path:r.path,parent:r})):this._def.schema._parseSync({data:s,path:r.path,parent:r})}if(o.type==="refinement"){const s=l=>{const u=o.refinement(l,i);if(r.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return l};if(r.common.async===!1){const l=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return l.status==="aborted"?Ze:(l.status==="dirty"&&n.dirty(),s(l.value),{status:n.value,value:l.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(l=>l.status==="aborted"?Ze:(l.status==="dirty"&&n.dirty(),s(l.value).then(()=>({status:n.value,value:l.value}))))}if(o.type==="transform")if(r.common.async===!1){const s=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Yh(s))return s;const l=o.transform(s.value,i);if(l instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:l}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(s=>Yh(s)?Promise.resolve(o.transform(s.value,i)).then(l=>({status:n.value,value:l})):s);mt.assertNever(o)}}Si.create=(e,t,n)=>new Si({schema:e,typeName:ze.ZodEffects,effect:t,...Xe(n)});Si.createWithPreprocess=(e,t,n)=>new Si({schema:t,effect:{type:"preprocess",transform:e},typeName:ze.ZodEffects,...Xe(n)});class bs extends rt{_parse(t){return this._getType(t)===be.undefined?rr(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}bs.create=(e,t)=>new bs({innerType:e,typeName:ze.ZodOptional,...Xe(t)});class uc extends rt{_parse(t){return this._getType(t)===be.null?rr(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}uc.create=(e,t)=>new uc({innerType:e,typeName:ze.ZodNullable,...Xe(t)});class nm extends rt{_parse(t){const{ctx:n}=this._processInputParams(t);let r=n.data;return n.parsedType===be.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}nm.create=(e,t)=>new nm({innerType:e,typeName:ze.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Xe(t)});class O1 extends rt{_parse(t){const{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return C1(o)?o.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Bo(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Bo(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}O1.create=(e,t)=>new O1({innerType:e,typeName:ze.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Xe(t)});class M1 extends rt{_parse(t){if(this._getType(t)!==be.nan){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.nan,received:r.parsedType}),Ze}return{status:"valid",value:t.data}}}M1.create=e=>new M1({typeName:ze.ZodNaN,...Xe(e)});class pX extends rt{_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 sg extends rt{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?Ze:i.status==="dirty"?(n.dirty(),tX(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{const o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?Ze:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(t,n){return new sg({in:t,out:n,typeName:ze.ZodPipeline})}}class N1 extends rt{_parse(t){const n=this._def.innerType._parse(t);return Yh(n)&&(n.value=Object.freeze(n.value)),n}}N1.create=(e,t)=>new N1({innerType:e,typeName:ze.ZodReadonly,...Xe(t)});Vt.lazycreate;var ze;(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",e.ZodReadonly="ZodReadonly"})(ze||(ze={}));const O2=di.create;ac.create;M1.create;lc.create;const su=$1.create;sd.create;k1.create;Gh.create;Xh.create;R1.create;Tl.create;Rs.create;T1.create;Uo.create;const hX=Vt.create;Vt.strictCreate;Zh.create;Yx.create;qh.create;_i.create;Qh.create;A1.create;cc.create;Pu.create;Jh.create;em.create;Ta.create;tm.create;ad.create;Si.create;bs.create;uc.create;Si.createWithPreprocess;sg.create;const D1="horizontal",mX=["horizontal","vertical"],t3=f.forwardRef((e,t)=>{const{decorative:n,orientation:r=D1,...o}=e,i=n3(r)?r:D1,l=n?{role:"none"}:{"aria-orientation":i==="vertical"?i:void 0,role:"separator"};return f.createElement(Pe.div,Y({"data-orientation":i},l,o,{ref:t}))});t3.propTypes={orientation(e,t,n){const r=e[t],o=String(r);return r&&!n3(r)?new Error(gX(o,n)):null}};function gX(e,t){return`Invalid prop \`orientation\` of value \`${e}\` supplied to \`${t}\`, expected one of: + - horizontal + - vertical + +Defaulting to \`${D1}\`.`}function n3(e){return mX.includes(e)}const r3=t3,Fn=f.forwardRef(({className:e,orientation:t="horizontal",decorative:n=!0,...r},o)=>v.jsx(r3,{ref:o,decorative:n,orientation:t,className:Ce("shrink-0 bg-border",t==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",e),...r}));Fn.displayName=r3.displayName;const vX=f.forwardRef((e,t)=>f.createElement(Pe.label,Y({},e,{ref:t,onMouseDown:n=>{var r;(r=e.onMouseDown)===null||r===void 0||r.call(e,n),!n.defaultPrevented&&n.detail>1&&n.preventDefault()}}))),o3=vX,yX=Om("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),Gx=f.forwardRef(({className:e,disabled:t,...n},r)=>v.jsx(o3,{ref:r,className:Ce(yX(),e,t?"opacity-50":"","select-none"),...n}));Gx.displayName=o3.displayName;const wX=MG,i3=f.createContext({}),N0=({...e})=>v.jsx(i3.Provider,{value:{name:e.name},children:v.jsx(LG,{...e})}),ag=()=>{const e=f.useContext(i3),t=f.useContext(s3),{getFieldState:n,formState:r}=ig(),o=n(e.name,r);if(!e)throw new Error("useFormField should be used within ");const{id:i}=t;return{id:i,name:e.name,formItemId:`${i}-form-item`,formDescriptionId:`${i}-form-item-description`,formMessageId:`${i}-form-item-message`,...o}},s3=f.createContext({}),qp=f.forwardRef(({className:e,...t},n)=>{const r=f.useId();return v.jsx(s3.Provider,{value:{id:r},children:v.jsx("div",{ref:n,className:Ce("space-y-2",e),...t})})});qp.displayName="FormItem";const Qp=f.forwardRef(({className:e,...t},n)=>{const{error:r,formItemId:o}=ag();return v.jsx(Gx,{ref:n,className:Ce(r&&"text-destructive","text-sm",e),htmlFor:o,...t})});Qp.displayName="FormLabel";const Jp=f.forwardRef(({...e},t)=>{const{error:n,formItemId:r,formDescriptionId:o,formMessageId:i}=ag();return v.jsx(Wo,{ref:t,id:r,"aria-describedby":n?`${o} ${i}`:`${o}`,"aria-invalid":!!n,...e})});Jp.displayName="FormControl";const eh=f.forwardRef(({className:e,...t},n)=>{const{formDescriptionId:r}=ag();return v.jsx("p",{ref:n,id:r,className:Ce("text-[0.8rem] text-muted-foreground",e),...t})});eh.displayName="FormDescription";const xX=f.forwardRef(({className:e,children:t,...n},r)=>{const{error:o,formMessageId:i}=ag(),s=o?String(o==null?void 0:o.message):t;return s?v.jsx("p",{ref:r,id:i,className:Ce("text-[0.8rem] font-medium text-destructive",e),...n,children:s}):null});xX.displayName="FormMessage";const a3="Switch",[bX,Ste]=An(a3),[_X,SX]=bX(a3),EX=f.forwardRef((e,t)=>{const{__scopeSwitch:n,name:r,checked:o,defaultChecked:i,required:s,disabled:l,value:u="on",onCheckedChange:d,...h}=e,[m,g]=f.useState(null),y=Be(t,b=>g(b)),x=f.useRef(!1),_=m?!!m.closest("form"):!0,[C=!1,S]=Zr({prop:o,defaultProp:i,onChange:d});return f.createElement(_X,{scope:n,checked:C,disabled:l},f.createElement(Pe.button,Y({type:"button",role:"switch","aria-checked":C,"aria-required":s,"data-state":l3(C),"data-disabled":l?"":void 0,disabled:l,value:u},h,{ref:y,onClick:ue(e.onClick,b=>{S(E=>!E),_&&(x.current=b.isPropagationStopped(),x.current||b.stopPropagation())})})),_&&f.createElement(kX,{control:m,bubbles:!x.current,name:r,value:u,checked:C,required:s,disabled:l,style:{transform:"translateX(-100%)"}}))}),CX="SwitchThumb",$X=f.forwardRef((e,t)=>{const{__scopeSwitch:n,...r}=e,o=SX(CX,n);return f.createElement(Pe.span,Y({"data-state":l3(o.checked),"data-disabled":o.disabled?"":void 0},r,{ref:t}))}),kX=e=>{const{control:t,checked:n,bubbles:r=!0,...o}=e,i=f.useRef(null),s=Fx(n),l=gx(t);return f.useEffect(()=>{const u=i.current,d=window.HTMLInputElement.prototype,m=Object.getOwnPropertyDescriptor(d,"checked").set;if(s!==n&&m){const g=new Event("click",{bubbles:r});m.call(u,n),u.dispatchEvent(g)}},[s,n,r]),f.createElement("input",Y({type:"checkbox","aria-hidden":!0,defaultChecked:n},o,{tabIndex:-1,ref:i,style:{...e.style,...l,position:"absolute",pointerEvents:"none",opacity:0,margin:0}}))};function l3(e){return e?"checked":"unchecked"}const c3=EX,RX=$X,co=f.forwardRef(({className:e,...t},n)=>v.jsx(c3,{className:Ce("peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",e),tabIndex:-1,...t,ref:n,children:v.jsx(RX,{className:Ce("pointer-events-none block h-4 w-4 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0")})}));co.displayName=c3.displayName;const TX="AlertDialog",[PX,Ete]=An(TX,[cP]),Is=cP(),AX=e=>{const{__scopeAlertDialog:t,...n}=e,r=Is(t);return f.createElement(Sx,Y({},r,n,{modal:!0}))},OX=e=>{const{__scopeAlertDialog:t,...n}=e,r=Is(t);return f.createElement(Ex,Y({},r,n))},MX=f.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=Is(n);return f.createElement(Nd,Y({},o,r,{ref:t}))}),u3="AlertDialogContent",[NX,DX]=PX(u3),IX=f.forwardRef((e,t)=>{const{__scopeAlertDialog:n,children:r,...o}=e,i=Is(n),s=f.useRef(null),l=Be(t,s),u=f.useRef(null);return f.createElement(pW,{contentName:u3,titleName:LX,docsSlug:"alert-dialog"},f.createElement(NX,{scope:n,cancelRef:u},f.createElement(Dd,Y({role:"alertdialog"},i,o,{ref:l,onOpenAutoFocus:ue(o.onOpenAutoFocus,d=>{var h;d.preventDefault(),(h=u.current)===null||h===void 0||h.focus({preventScroll:!0})}),onPointerDownOutside:d=>d.preventDefault(),onInteractOutside:d=>d.preventDefault()}),f.createElement(sx,null,r),!1)))}),LX="AlertDialogTitle",FX=f.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=Is(n);return f.createElement(Id,Y({},o,r,{ref:t}))}),jX=f.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=Is(n);return f.createElement(Ld,Y({},o,r,{ref:t}))}),zX=f.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=Is(n);return f.createElement(Cx,Y({},o,r,{ref:t}))}),BX="AlertDialogCancel",UX=f.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,{cancelRef:o}=DX(BX,n),i=Is(n),s=Be(t,o);return f.createElement(Cx,Y({},i,r,{ref:s}))}),VX=AX,WX=OX,d3=MX,f3=IX,p3=zX,h3=UX,m3=FX,g3=jX,HX=VX,KX=WX,v3=f.forwardRef(({className:e,...t},n)=>v.jsx(d3,{className:Ce("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t,ref:n}));v3.displayName=d3.displayName;const y3=f.forwardRef(({className:e,...t},n)=>v.jsxs(KX,{children:[v.jsx(v3,{}),v.jsx(f3,{ref:n,className:Ce("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",e),...t})]}));y3.displayName=f3.displayName;const w3=({className:e,...t})=>v.jsx("div",{className:Ce("flex flex-col space-y-2 text-center sm:text-left",e),...t});w3.displayName="AlertDialogHeader";const YX=f.forwardRef(({className:e,...t},n)=>v.jsx(m3,{ref:n,className:Ce("text-lg font-semibold",e),...t}));YX.displayName=m3.displayName;const GX=f.forwardRef(({className:e,...t},n)=>v.jsx(g3,{ref:n,className:Ce("text-sm text-muted-foreground",e),...t}));GX.displayName=g3.displayName;const XX=f.forwardRef(({className:e,...t},n)=>v.jsx(p3,{ref:n,className:Ce(bx(),e),...t}));XX.displayName=p3.displayName;const ZX=f.forwardRef(({className:e,...t},n)=>v.jsx(h3,{ref:n,className:Ce(bx({variant:"outline"}),"mt-2 sm:mt-0",e),...t}));ZX.displayName=h3.displayName;const qX=hX({enableFileManager:su(),inputDirectory:O2(),outputDirectory:O2(),enableDownloadMask:su(),enableManualInpainting:su(),enableUploadMask:su(),enableAutoExtractPrompt:su()}),x3="General",I1="Model",QX=[I1,x3];function JX(){const[e,t]=u1(!1),[n,r]=u1(!1),[o,i]=f.useState(I1),[s,l,u,d,h,m]=bt(O=>[O.updateAppState,O.settings,O.updateSettings,O.fileManagerState,O.updateFileManagerState,O.setModel]),{toast:g}=Td(),[y,x]=f.useState(l.model);f.useEffect(()=>{x(l.model)},[l.model]);const{data:_,status:C}=TL({queryKey:["modelInfos"],queryFn:zj}),S=GG({resolver:JG(qX),defaultValues:{enableDownloadMask:l.enableDownloadMask,enableManualInpainting:l.enableManualInpainting,enableUploadMask:l.enableUploadMask,enableAutoExtractPrompt:l.enableAutoExtractPrompt,inputDirectory:d.inputDirectory,outputDirectory:d.outputDirectory}});async function b(O){if(u({enableDownloadMask:O.enableDownloadMask,enableManualInpainting:O.enableManualInpainting,enableUploadMask:O.enableUploadMask,enableAutoExtractPrompt:O.enableAutoExtractPrompt}),h({inputDirectory:O.inputDirectory,outputDirectory:O.outputDirectory}),y.name!==l.model.name){r(),s({disableShortCuts:!0});try{const F=await Fj(y.name);g({title:`Switch to ${F.name} success`}),m(y)}catch(F){g({variant:"destructive",title:`Switch to ${y.name} failed: ${F}`}),x(l.model)}finally{r(),s({disableShortCuts:!1})}}}Zn("s",()=>{t(),e&&b(S.getValues())},[e,S,y]);function E(O){t(),O||b(S.getValues())}function k(O){x(O)}function P(O){return _?_.filter(F=>O.includes(F.model_type)).map(F=>v.jsxs("div",{onClick:()=>k(F),className:"px-2",children:[v.jsx("div",{className:Ce([F.name===y.name?"bg-muted":"hover:bg-muted","rounded-md px-2 py-2","cursor-default"]),children:v.jsx("div",{className:"text-base",children:F.name})}),v.jsx(Fn,{className:"my-1"})]},F.name)):v.jsx("div",{children:"Please download model first"})}function M(){if(C!=="success")return v.jsx(v.Fragment,{});let O=is;for(let F of _)if(y.name===F.name){O=F.model_type,O===nC&&(O=rp),O===rC&&(O=op);break}return v.jsxs("div",{className:"flex flex-col gap-4 w-[510px]",children:[v.jsxs("div",{className:"flex flex-col gap-4 rounded-md",children:[v.jsx("div",{className:"font-medium",children:"Current Model"}),v.jsx("div",{children:y.name})]}),v.jsx(Fn,{}),v.jsxs("div",{className:"space-y-4 rounded-md",children:[v.jsx("div",{className:"flex gap-1 items-center justify-start",children:v.jsx("div",{className:"font-medium",children:"Available models"})}),v.jsxs(i5,{defaultValue:O,children:[v.jsxs(Lx,{children:[v.jsx(sa,{value:is,children:"Inpaint"}),v.jsx(sa,{value:rp,children:"Stable Diffusion"}),v.jsx(sa,{value:op,children:"Stable Diffusion Inpaint"}),v.jsx(sa,{value:l0,children:"Other Diffusion"})]}),v.jsxs(og,{className:"h-[240px] w-full mt-2 outline-none border rounded-lg",children:[v.jsx(mu,{value:is,children:P([is])}),v.jsx(mu,{value:rp,children:P([rp,nC])}),v.jsx(mu,{value:op,children:P([op,rC])}),v.jsx(mu,{value:l0,children:P([l0])})]})]})]})]})}function A(){return v.jsxs("div",{className:"space-y-4 w-[510px]",children:[v.jsx(N0,{control:S.control,name:"enableManualInpainting",render:({field:O})=>v.jsxs(qp,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(Qp,{children:"Enable manual inpainting"}),v.jsx(eh,{children:"For erase model, click a button to trigger inpainting after draw mask."})]}),v.jsx(Jp,{children:v.jsx(co,{checked:O.value,onCheckedChange:O.onChange})})]})}),v.jsx(Fn,{}),v.jsx(N0,{control:S.control,name:"enableDownloadMask",render:({field:O})=>v.jsxs(qp,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(Qp,{children:"Enable download mask"}),v.jsx(eh,{children:"Also download the mask after save the inpainting result."})]}),v.jsx(Jp,{children:v.jsx(co,{checked:O.value,onCheckedChange:O.onChange})})]})}),v.jsx(Fn,{}),v.jsx(N0,{control:S.control,name:"enableAutoExtractPrompt",render:({field:O})=>v.jsxs(qp,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(Qp,{children:"Enable auto extract prompt"}),v.jsx(eh,{children:"Automatically extract prompt/negativate prompt from the image meta."})]}),v.jsx(Jp,{children:v.jsx(co,{checked:O.value,onCheckedChange:O.onChange})})]})})]})}return v.jsxs(v.Fragment,{children:[v.jsx(HX,{open:n,children:v.jsx(y3,{children:v.jsx(w3,{children:v.jsxs("div",{className:"flex flex-col justify-center items-center gap-4",children:[v.jsxs("div",{role:"status",children:[v.jsxs("svg",{"aria-hidden":"true",className:"w-8 h-8 text-gray-200 animate-spin dark:text-gray-600 fill-primary",viewBox:"0 0 100 101",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[v.jsx("path",{d:"M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z",fill:"currentColor"}),v.jsx("path",{d:"M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z",fill:"currentFill"})]}),v.jsx("span",{className:"sr-only",children:"Loading..."})]}),v.jsxs("div",{children:["Switching to ",y.name]})]})})})}),v.jsxs(Zm,{open:e,onOpenChange:E,children:[v.jsx($x,{asChild:!0,children:v.jsx(vn,{tooltip:"Settings",children:v.jsx(sV,{})})}),v.jsxs(Fd,{className:"max-w-3xl h-[600px]",onOpenAutoFocus:O=>O.preventDefault(),children:[v.jsx(jd,{children:"Settings"}),v.jsx(Fn,{}),v.jsxs("div",{className:"flex flex-row space-x-8 h-full",children:[v.jsx("div",{className:"flex flex-col space-y-1",children:QX.map(O=>v.jsx(Rn,{variant:"ghost",onClick:()=>i(O),className:Ce(o===O?"bg-muted ":"hover:bg-muted","justify-start"),children:O},O))}),v.jsx(Fn,{orientation:"vertical"}),v.jsx(wX,{...S,children:v.jsx("div",{className:"flex w-full justify-center",children:v.jsxs("form",{onSubmit:S.handleSubmit(b),children:[o===I1?M():v.jsx(v.Fragment,{}),o===x3?A():v.jsx(v.Fragment,{}),v.jsx("div",{className:"absolute right-10 bottom-6",children:v.jsx(Rn,{onClick:()=>E(!1),children:"Ok"})})]})})})]})]})]})]})}const eZ="/assets/kofi_button_black-XI_Dr2zg.png";function tZ(){return v.jsxs(Zm,{children:[v.jsx($x,{asChild:!0,children:v.jsx(vn,{tooltip:"Buy me a coffee",children:v.jsx(YU,{})})}),v.jsxs(Fd,{children:[v.jsx(jd,{children:"Buy me a coffee"}),v.jsx(mP,{className:"mb-8",children:"Hi, if you found my project is useful, please conside buy me a coffee to support my work. Thanks!"}),v.jsx("div",{className:"w-full flex items-center justify-center",children:v.jsx("a",{href:"https://ko-fi.com/Z8Z1CZJGY",target:"_blank",rel:"noreferrer",children:v.jsx("img",{src:eZ,className:"h-[32px]"})})})]})]})}const nZ=()=>{const[e,t,n,r,o,i,s,l,u,d,h,m,g,y]=bt(M=>[M.file,M.customMask,M.isInpainting,M.serverConfig,M.runMannually(),M.settings.enableUploadMask,M.settings.model,M.setFile,M.setCustomFile,M.runInpainting,M.showPrevMask,M.hidePrevMask,M.imageHeight,M.imageWidth]),{toast:x}=Td(),[_,C]=Rx(t),[S,b]=f.useState(!1),E=()=>{d()},k=()=>{h()},P=()=>{m()};return v.jsxs("header",{className:"h-[60px] px-6 py-4 absolute top-[0] flex justify-between items-center w-full z-20 border-b backdrop-filter backdrop-blur-md bg-background/70",children:[v.jsxs("div",{className:"flex items-center gap-1",children:[r.enableFileManager?v.jsx(PG,{photoWidth:512,onPhotoClick:async(M,A)=>{try{const O=await Bj(M,A);l(O)}catch(O){x({variant:"destructive",description:O.message?O.message:O.toString()});return}}}):v.jsx(v.Fragment,{}),v.jsx(c1,{disabled:n,tooltip:"Upload image",onFileUpload:M=>{l(M)},children:v.jsx(JU,{})}),v.jsxs("div",{className:Ce(["flex items-center gap-1",e&&i?"visible":"hidden"]),children:[v.jsx(c1,{disabled:n,tooltip:"Upload custom mask",onFileUpload:async M=>{let A=null;try{A=await fF(M)}catch(O){x({variant:"destructive",description:O.message?O.message:O.toString()});return}if(A.naturalHeight!==g||A.naturalWidth!==y){x({variant:"destructive",description:`The size of the mask must same as image: ${y}x${g}`});return}u(M),o||d()},children:v.jsx(ZT,{})}),t?v.jsxs(KW,{open:S,children:[v.jsx(YW,{className:"btn-primary side-panel-trigger",onMouseEnter:()=>b(!0),onMouseLeave:()=>b(!1),style:{visibility:t?"visible":"hidden",outline:"none"},onClick:()=>{},children:v.jsx(vn,{tooltip:"Run custom mask",children:v.jsx(lz,{})})}),v.jsx(PP,{children:C?v.jsx("img",{src:_.src,alt:"Custom mask"}):v.jsx(v.Fragment,{})})]}):v.jsx(v.Fragment,{})]}),e&&!s.need_prompt?v.jsx(vn,{disabled:n,tooltip:"Rerun previous mask",onClick:E,onMouseEnter:k,onMouseLeave:P,children:v.jsx(iV,{})}):v.jsx(v.Fragment,{})]}),s.need_prompt?v.jsx(yH,{}):v.jsx(v.Fragment,{}),v.jsxs("div",{className:"flex gap-1",children:[v.jsx(tZ,{}),v.jsx(OW,{}),r.disableModelSwitch?v.jsx(v.Fragment,{}):v.jsx(JX,{})]})]})};var Wr=function(e,t){return Number(e.toFixed(t))},rZ=function(e,t){return typeof e=="number"?e:t},Nt=function(e,t,n){n&&typeof n=="function"&&n(e,t)},oZ=function(e){return-Math.cos(e*Math.PI)/2+.5},iZ=function(e){return e},sZ=function(e){return e*e},aZ=function(e){return e*(2-e)},lZ=function(e){return e<.5?2*e*e:-1+(4-2*e)*e},cZ=function(e){return e*e*e},uZ=function(e){return--e*e*e+1},dZ=function(e){return e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1},fZ=function(e){return e*e*e*e},pZ=function(e){return 1- --e*e*e*e},hZ=function(e){return e<.5?8*e*e*e*e:1-8*--e*e*e*e},mZ=function(e){return e*e*e*e*e},gZ=function(e){return 1+--e*e*e*e*e},vZ=function(e){return e<.5?16*e*e*e*e*e:1+16*--e*e*e*e*e},b3={easeOut:oZ,linear:iZ,easeInQuad:sZ,easeOutQuad:aZ,easeInOutQuad:lZ,easeInCubic:cZ,easeOutCubic:uZ,easeInOutCubic:dZ,easeInQuart:fZ,easeOutQuart:pZ,easeInOutQuart:hZ,easeInQuint:mZ,easeOutQuint:gZ,easeInOutQuint:vZ},_3=function(e){typeof e=="number"&&cancelAnimationFrame(e)},Do=function(e){e.mounted&&(_3(e.animation),e.animate=!1,e.animation=null,e.velocity=null)};function S3(e,t,n,r){if(e.mounted){var o=new Date().getTime(),i=1;Do(e),e.animation=function(){if(!e.mounted)return _3(e.animation);var s=new Date().getTime()-o,l=s/n,u=b3[t],d=u(l);s>=n?(r(i),e.animation=null):e.animation&&(r(d),requestAnimationFrame(e.animation))},requestAnimationFrame(e.animation)}}function yZ(e){var t=e.scale,n=e.positionX,r=e.positionY;return!(Number.isNaN(t)||Number.isNaN(n)||Number.isNaN(r))}function Ls(e,t,n,r){var o=yZ(t);if(!(!e.mounted||!o)){var i=e.setTransformState,s=e.transformState,l=s.scale,u=s.positionX,d=s.positionY,h=t.scale-l,m=t.positionX-u,g=t.positionY-d;n===0?i(t.scale,t.positionX,t.positionY):S3(e,r,n,function(y){var x=l+h*y,_=u+m*y,C=d+g*y;i(x,_,C)})}}function wZ(e,t,n){var r=e.offsetWidth,o=e.offsetHeight,i=t.offsetWidth,s=t.offsetHeight,l=i*n,u=s*n,d=r-l,h=o-u;return{wrapperWidth:r,wrapperHeight:o,newContentWidth:l,newDiffWidth:d,newContentHeight:u,newDiffHeight:h}}var xZ=function(e,t,n,r,o,i,s){var l=e>t?n*(s?1:.5):0,u=r>o?i*(s?1:.5):0,d=e-t-l,h=l,m=r-o-u,g=u;return{minPositionX:d,maxPositionX:h,minPositionY:m,maxPositionY:g}},Xx=function(e,t){var n=e.wrapperComponent,r=e.contentComponent,o=e.setup.centerZoomedOut;if(!n||!r)throw new Error("Components are not mounted");var i=wZ(n,r,t),s=i.wrapperWidth,l=i.wrapperHeight,u=i.newContentWidth,d=i.newDiffWidth,h=i.newContentHeight,m=i.newDiffHeight,g=xZ(s,u,d,l,h,m,!!o);return g},L1=function(e,t,n,r){return r?en?Wr(n,2):Wr(e,2):Wr(e,2)},dc=function(e,t){var n=Xx(e,t);return e.bounds=n,n};function lg(e,t,n,r,o,i,s){var l=n.minPositionX,u=n.minPositionY,d=n.maxPositionX,h=n.maxPositionY,m=0,g=0;s&&(m=o,g=i);var y=L1(e,l-m,d+m,r),x=L1(t,u-g,h+g,r);return{x:y,y:x}}function cg(e,t,n,r,o,i){var s=e.transformState,l=s.scale,u=s.positionX,d=s.positionY,h=r-l;if(typeof t!="number"||typeof n!="number")return console.error("Mouse X and Y position were not provided!"),{x:u,y:d};var m=u-t*h,g=d-n*h,y=lg(m,g,o,i,0,0,null);return y}function Vd(e,t,n,r,o){var i=o?r:0,s=t-i;return!Number.isNaN(n)&&e>=n?n:!Number.isNaN(t)&&e<=s?s:e}var M2=function(e,t){var n=e.setup.panning.excluded,r=e.isInitialized,o=e.wrapperComponent,i=t.target,s=o==null?void 0:o.contains(i),l=r&&i&&s;if(!l)return!1;var u=ug(i,n);return!u},N2=function(e){var t=e.isInitialized,n=e.isPanning,r=e.setup,o=r.panning.disabled,i=t&&n&&!o;return!!i},bZ=function(e,t){var n=e.transformState,r=n.positionX,o=n.positionY;e.isPanning=!0;var i=t.clientX,s=t.clientY;e.startCoords={x:i-r,y:s-o}},_Z=function(e,t){var n=t.touches,r=e.transformState,o=r.positionX,i=r.positionY;e.isPanning=!0;var s=n.length===1;if(s){var l=n[0].clientX,u=n[0].clientY;e.startCoords={x:l-o,y:u-i}}};function SZ(e){var t=e.transformState,n=t.positionX,r=t.positionY,o=t.scale,i=e.setup,s=i.disabled,l=i.limitToBounds,u=i.centerZoomedOut,d=e.wrapperComponent;if(!(s||!d||!e.bounds)){var h=e.bounds,m=h.maxPositionX,g=h.minPositionX,y=h.maxPositionY,x=h.minPositionY,_=n>m||ny||rm?d.offsetWidth:e.setup.minPositionX||0,b=r>y?d.offsetHeight:e.setup.minPositionY||0,E=cg(e,S,b,o,e.bounds,l||u),k=E.x,P=E.y;return{scale:o,positionX:_?k:n,positionY:C?P:r}}}function EZ(e,t,n,r,o){var i=e.setup.limitToBounds,s=e.wrapperComponent,l=e.bounds,u=e.transformState,d=u.scale,h=u.positionX,m=u.positionY;if(!(s===null||l===null||t===h&&n===m)){var g=lg(t,n,l,i,r,o,s),y=g.x,x=g.y;e.setTransformState(d,y,x)}}var CZ=function(e,t,n){var r=e.startCoords,o=e.transformState,i=e.setup.panning,s=i.lockAxisX,l=i.lockAxisY,u=o.positionX,d=o.positionY;if(!r)return{x:u,y:d};var h=t-r.x,m=n-r.y,g=s?u:h,y=l?d:m;return{x:g,y}},rm=function(e,t){var n=e.setup,r=e.transformState,o=r.scale,i=n.minScale,s=n.disablePadding;return t>0&&o>=i&&!s?t:0},$Z=function(e){var t=e.mounted,n=e.setup,r=n.disabled,o=n.velocityAnimation,i=e.transformState.scale,s=o.disabled,l=!s||i>1||!r||t;return!!l},kZ=function(e){var t=e.mounted,n=e.velocity,r=e.bounds,o=e.setup,i=o.disabled,s=o.velocityAnimation,l=e.transformState.scale,u=s.disabled,d=!u||l>1||!i||t;return!(!d||!n||!r)};function RZ(e,t){var n=e.setup.velocityAnimation,r=n.equalToMove,o=n.animationTime,i=n.sensitivity;return r?o*t*i:o}function D2(e,t,n,r,o,i,s,l,u,d){if(o){if(t>s&&n>s){var h=s+(e-s)*d;return h>u?u:hi?i:h}}return r?t:L1(e,i,s,o)}function TZ(e,t){var n=1;return t?Math.min(n,e.offsetWidth/window.innerWidth):n}function PZ(e,t){var n=$Z(e);if(n){var r=e.lastMousePosition,o=e.velocityTime,i=e.setup,s=e.wrapperComponent,l=i.velocityAnimation.equalToMove,u=Date.now();if(r&&o&&s){var d=TZ(s,l),h=t.x-r.x,m=t.y-r.y,g=h/d,y=m/d,x=u-o,_=h*h+m*m,C=Math.sqrt(_)/x;e.velocity={velocityX:g,velocityY:y,total:C}}e.lastMousePosition=t,e.velocityTime=u}}function AZ(e){var t=e.velocity,n=e.bounds,r=e.setup,o=e.wrapperComponent,i=kZ(e);if(!(!i||!t||!n||!o)){var s=t.velocityX,l=t.velocityY,u=t.total,d=n.maxPositionX,h=n.minPositionX,m=n.maxPositionY,g=n.minPositionY,y=r.limitToBounds,x=r.alignmentAnimation,_=r.zoomAnimation,C=r.panning,S=C.lockAxisY,b=C.lockAxisX,E=_.animationType,k=x.sizeX,P=x.sizeY,M=x.velocityAlignmentTime,A=M,O=RZ(e,u),F=Math.max(O,A),V=rm(e,k),J=rm(e,P),G=V*o.offsetWidth/100,ae=J*o.offsetHeight/100,U=d+G,te=h-G,L=m+ae,ie=g-ae,K=e.transformState,Q=new Date().getTime();S3(e,E,F,function(W){var le=e.transformState,ge=le.scale,Ve=le.positionX,Ue=le.positionY,We=new Date().getTime()-Q,Me=We/A,fe=b3[x.animationType],xe=1-fe(Math.min(1,Me)),$e=1-W,Ae=Ve+s*$e,Oe=Ue+l*$e,je=D2(Ae,K.positionX,Ve,b,y,h,d,te,U,xe),Ot=D2(Oe,K.positionY,Ue,S,y,g,m,ie,L,xe);(Ve!==Ae||Ue!==Oe)&&e.setTransformState(ge,je,Ot)})}}function I2(e,t){var n=e.transformState.scale;Do(e),dc(e,n),window.TouchEvent!==void 0&&t instanceof TouchEvent?_Z(e,t):bZ(e,t)}function E3(e){var t=e.transformState.scale,n=e.setup,r=n.minScale,o=n.alignmentAnimation,i=o.disabled,s=o.sizeX,l=o.sizeY,u=o.animationTime,d=o.animationType,h=i||t.1&&m;g?AZ(e):E3(e)}}function Zx(e,t,n,r){var o=e.setup,i=o.minScale,s=o.maxScale,l=o.limitToBounds,u=Vd(Wr(t,2),i,s,0,!1),d=dc(e,u),h=cg(e,n,r,u,d,l),m=h.x,g=h.y;return{scale:u,positionX:m,positionY:g}}function C3(e,t,n){var r=e.transformState.scale,o=e.wrapperComponent,i=e.setup,s=i.minScale,l=i.limitToBounds,u=i.zoomAnimation,d=u.disabled,h=u.animationTime,m=u.animationType,g=d||r>=s;if((r>=1||l)&&E3(e),!(g||!o||!e.mounted)){var y=t||o.offsetWidth/2,x=n||o.offsetHeight/2,_=Zx(e,s,y,x);_&&Ls(e,_,h,m)}}var _s=function(){return _s=Object.assign||function(t){for(var n,r=1,o=arguments.length;rs||Math.sign(n.deltaY)!==Math.sign(t.deltaY)||n.deltaY>0&&n.deltaYt.deltaY||Math.sign(n.deltaY)!==Math.sign(t.deltaY):!1},XZ=function(e,t){var n=e.setup.pinch,r=n.disabled,o=n.excluded,i=e.isInitialized,s=t.target,l=i&&!r&&s;if(!l)return!1;var u=ug(s,o);return!u},ZZ=function(e){var t=e.setup.pinch.disabled,n=e.isInitialized,r=e.pinchStartDistance,o=n&&!t&&r;return!!o},qZ=function(e,t,n){var r=n.getBoundingClientRect(),o=e.touches,i=Wr(o[0].clientX-r.left,5),s=Wr(o[0].clientY-r.top,5),l=Wr(o[1].clientX-r.left,5),u=Wr(o[1].clientY-r.top,5);return{x:(i+l)/2/t,y:(s+u)/2/t}},O3=function(e){return Math.sqrt(Math.pow(e.touches[0].pageX-e.touches[1].pageX,2)+Math.pow(e.touches[0].pageY-e.touches[1].pageY,2))},QZ=function(e,t){var n=e.pinchStartScale,r=e.pinchStartDistance,o=e.setup,i=o.maxScale,s=o.minScale,l=o.zoomAnimation,u=o.disablePadding,d=l.size,h=l.disabled;if(!n||r===null||!t)throw new Error("Pinch touches distance was not provided");if(t<0)return e.transformState.scale;var m=t/r,g=m*n;return Vd(Wr(g,2),s,i,d,!h&&!u)},JZ=160,eq=100,tq=function(e,t){var n=e.props,r=n.onWheelStart,o=n.onZoomStart;e.wheelStopEventTimer||(Do(e),Nt(St(e),t,r),Nt(St(e),t,o))},nq=function(e,t){var n=e.props,r=n.onWheel,o=n.onZoom,i=e.contentComponent,s=e.setup,l=e.transformState,u=l.scale,d=s.limitToBounds,h=s.centerZoomedOut,m=s.zoomAnimation,g=s.wheel,y=s.disablePadding,x=s.smooth,_=m.size,C=m.disabled,S=g.step,b=g.smoothStep;if(!i)throw new Error("Component not mounted");t.preventDefault(),t.stopPropagation();var E=KZ(t,null),k=x?b*Math.abs(t.deltaY):S,P=YZ(e,E,k,!t.ctrlKey);if(u!==P){var M=dc(e,P),A=A3(t,i,u),O=C||_===0||h||y,F=d&&O,V=cg(e,A.x,A.y,P,M,F),J=V.x,G=V.y;e.previousWheelEvent=t,e.setTransformState(P,J,G),Nt(St(e),t,r),Nt(St(e),t,o)}},rq=function(e,t){var n=e.props,r=n.onWheelStop,o=n.onZoomStop;j1(e.wheelAnimationTimer),e.wheelAnimationTimer=setTimeout(function(){e.mounted&&(C3(e,t.x,t.y),e.wheelAnimationTimer=null)},eq);var i=GZ(e,t);i&&(j1(e.wheelStopEventTimer),e.wheelStopEventTimer=setTimeout(function(){e.mounted&&(e.wheelStopEventTimer=null,Nt(St(e),t,r),Nt(St(e),t,o))},JZ))},oq=function(e,t){var n=O3(t);e.pinchStartDistance=n,e.lastDistance=n,e.pinchStartScale=e.transformState.scale,e.isPanning=!1,Do(e)},iq=function(e,t){var n=e.contentComponent,r=e.pinchStartDistance,o=e.transformState.scale,i=e.setup,s=i.limitToBounds,l=i.centerZoomedOut,u=i.zoomAnimation,d=u.disabled,h=u.size;if(!(r===null||!n)){var m=qZ(t,o,n);if(!(!Number.isFinite(m.x)||!Number.isFinite(m.y))){var g=O3(t),y=QZ(e,g);if(y!==o){var x=dc(e,y),_=d||h===0||l,C=s&&_,S=cg(e,m.x,m.y,y,x,C),b=S.x,E=S.y;e.pinchMidpoint=m,e.lastDistance=g,e.setTransformState(y,b,E)}}}},sq=function(e){var t=e.pinchMidpoint;e.velocity=null,e.lastDistance=null,e.pinchMidpoint=null,e.pinchStartScale=null,e.pinchStartDistance=null,C3(e,t==null?void 0:t.x,t==null?void 0:t.y)},M3=function(e,t){var n=e.props.onZoomStop,r=e.setup.doubleClick.animationTime;j1(e.doubleClickStopEventTimer),e.doubleClickStopEventTimer=setTimeout(function(){e.doubleClickStopEventTimer=null,Nt(St(e),t,n)},r)},aq=function(e,t){var n=e.props,r=n.onZoomStart,o=n.onZoom,i=e.setup.doubleClick,s=i.animationTime,l=i.animationType;Nt(St(e),t,r),T3(e,s,l,function(){return Nt(St(e),t,o)}),M3(e,t)};function lq(e,t){var n=e.setup,r=e.doubleClickStopEventTimer,o=e.transformState,i=e.contentComponent,s=o.scale,l=e.props,u=l.onZoomStart,d=l.onZoom,h=n.doubleClick,m=h.disabled,g=h.mode,y=h.step,x=h.animationTime,_=h.animationType;if(!m&&!r){if(g==="reset")return aq(e,t);if(!i)return console.error("No ContentComponent found");var C=g==="zoomOut"?-1:1,S=k3(e,C,y);if(s!==S){Nt(St(e),t,u);var b=A3(t,i,s),E=Zx(e,S,b.x,b.y);if(!E)return console.error("Error during zoom event. New transformation state was not calculated.");Nt(St(e),t,d),Ls(e,E,x,_),M3(e,t)}}}var cq=function(e,t){var n=e.isInitialized,r=e.setup,o=e.wrapperComponent,i=r.doubleClick,s=i.disabled,l=i.excluded,u=t.target,d=o==null?void 0:o.contains(u),h=n&&u&&d&&!s;if(!h)return!1;var m=ug(u,l);return!m},uq=function(){function e(t){var n=this;this.mounted=!0,this.onChangeCallbacks=new Set,this.onInitCallbacks=new Set,this.wrapperComponent=null,this.contentComponent=null,this.isInitialized=!1,this.bounds=null,this.previousWheelEvent=null,this.wheelStopEventTimer=null,this.wheelAnimationTimer=null,this.isPanning=!1,this.startCoords=null,this.lastTouch=null,this.distance=null,this.lastDistance=null,this.pinchStartDistance=null,this.pinchStartScale=null,this.pinchMidpoint=null,this.doubleClickStopEventTimer=null,this.velocity=null,this.velocityTime=null,this.lastMousePosition=null,this.animate=!1,this.animation=null,this.maxBounds=null,this.pressedKeys={},this.mount=function(){n.initializeWindowEvents()},this.unmount=function(){n.cleanupWindowEvents()},this.update=function(r){dc(n,n.transformState.scale),n.setup=j2(r)},this.initializeWindowEvents=function(){var r,o=I0(),i=(r=n.wrapperComponent)===null||r===void 0?void 0:r.ownerDocument,s=i==null?void 0:i.defaultView;s==null||s.addEventListener("mousedown",n.onPanningStart,o),s==null||s.addEventListener("mousemove",n.onPanning,o),s==null||s.addEventListener("mouseup",n.onPanningStop,o),i==null||i.addEventListener("mouseleave",n.clearPanning,o),s==null||s.addEventListener("keyup",n.setKeyUnPressed,o),s==null||s.addEventListener("keydown",n.setKeyPressed,o)},this.cleanupWindowEvents=function(){var r,o,i=I0(),s=(r=n.wrapperComponent)===null||r===void 0?void 0:r.ownerDocument,l=s==null?void 0:s.defaultView;l==null||l.removeEventListener("mousedown",n.onPanningStart,i),l==null||l.removeEventListener("mousemove",n.onPanning,i),l==null||l.removeEventListener("mouseup",n.onPanningStop,i),s==null||s.removeEventListener("mouseleave",n.clearPanning,i),l==null||l.removeEventListener("keyup",n.setKeyUnPressed,i),l==null||l.removeEventListener("keydown",n.setKeyPressed,i),document.removeEventListener("mouseleave",n.clearPanning,i),Do(n),(o=n.observer)===null||o===void 0||o.disconnect()},this.handleInitializeWrapperEvents=function(r){var o=I0();r.addEventListener("wheel",n.onWheelZoom,o),r.addEventListener("dblclick",n.onDoubleClick,o),r.addEventListener("touchstart",n.onTouchPanningStart,o),r.addEventListener("touchmove",n.onTouchPanning,o),r.addEventListener("touchend",n.onTouchPanningStop,o)},this.handleInitialize=function(r){var o=n.setup.centerOnInit;n.applyTransformation(),n.onInitCallbacks.forEach(function(i){return i(St(n))}),o&&(n.setCenter(),n.observer=new ResizeObserver(function(){var i;n.onInitCallbacks.forEach(function(s){return s(St(n))}),n.setCenter(),(i=n.observer)===null||i===void 0||i.disconnect()}),n.observer.observe(r))},this.onWheelZoom=function(r){var o=n.setup.disabled;if(!o){var i=WZ(n,r);if(i){var s=n.isPressingKeys(n.setup.wheel.activationKeys);s&&(tq(n,r),nq(n,r),rq(n,r))}}},this.onPanningStart=function(r){var o=n.setup.disabled,i=n.props.onPanningStart;if(!o){var s=M2(n,r);if(s){var l=n.isPressingKeys(n.setup.panning.activationKeys);l&&(r.button===0&&!n.setup.panning.allowLeftClickPan||r.button===1&&!n.setup.panning.allowMiddleClickPan||r.button===2&&!n.setup.panning.allowRightClickPan||(r.preventDefault(),r.stopPropagation(),Do(n),I2(n,r),Nt(St(n),r,i)))}}},this.onPanning=function(r){var o=n.setup.disabled,i=n.props.onPanning;if(!o){var s=N2(n);if(s){var l=n.isPressingKeys(n.setup.panning.activationKeys);l&&(r.preventDefault(),r.stopPropagation(),L2(n,r.clientX,r.clientY),Nt(St(n),r,i))}}},this.onPanningStop=function(r){var o=n.props.onPanningStop;n.isPanning&&(OZ(n),Nt(St(n),r,o))},this.onPinchStart=function(r){var o=n.setup.disabled,i=n.props,s=i.onPinchingStart,l=i.onZoomStart;if(!o){var u=XZ(n,r);u&&(oq(n,r),Do(n),Nt(St(n),r,s),Nt(St(n),r,l))}},this.onPinch=function(r){var o=n.setup.disabled,i=n.props,s=i.onPinching,l=i.onZoom;if(!o){var u=ZZ(n);u&&(r.preventDefault(),r.stopPropagation(),iq(n,r),Nt(St(n),r,s),Nt(St(n),r,l))}},this.onPinchStop=function(r){var o=n.props,i=o.onPinchingStop,s=o.onZoomStop;n.pinchStartScale&&(sq(n),Nt(St(n),r,i),Nt(St(n),r,s))},this.onTouchPanningStart=function(r){var o=n.setup.disabled,i=n.props.onPanningStart;if(!o){var s=M2(n,r);if(s){var l=n.lastTouch&&+new Date-n.lastTouch<200;if(l&&r.touches.length===1)n.onDoubleClick(r);else{n.lastTouch=+new Date,Do(n);var u=r.touches,d=u.length===1,h=u.length===2;d&&(Do(n),I2(n,r),Nt(St(n),r,i)),h&&n.onPinchStart(r)}}}},this.onTouchPanning=function(r){var o=n.setup.disabled,i=n.props.onPanning;if(n.isPanning&&r.touches.length===1){if(o)return;var s=N2(n);if(!s)return;r.preventDefault(),r.stopPropagation();var l=r.touches[0];L2(n,l.clientX,l.clientY),Nt(St(n),r,i)}else r.touches.length>1&&n.onPinch(r)},this.onTouchPanningStop=function(r){n.onPanningStop(r),n.onPinchStop(r)},this.onDoubleClick=function(r){var o=n.setup.disabled;if(!o){var i=cq(n,r);i&&lq(n,r)}},this.clearPanning=function(r){n.isPanning&&n.onPanningStop(r)},this.setKeyPressed=function(r){n.pressedKeys[r.key]=!0},this.setKeyUnPressed=function(r){n.pressedKeys[r.key]=!1},this.isPressingKeys=function(r){return r.length?!!r.find(function(o){return n.pressedKeys[o]}):!0},this.setTransformState=function(r,o,i){var s=n.props.onTransformed;if(!Number.isNaN(r)&&!Number.isNaN(o)&&!Number.isNaN(i)){r!==n.transformState.scale&&(n.transformState.previousScale=n.transformState.scale,n.transformState.scale=r),n.transformState.positionX=o,n.transformState.positionY=i,n.applyTransformation();var l=St(n);n.onChangeCallbacks.forEach(function(u){return u(l)}),Nt(l,{scale:r,positionX:o,positionY:i},s)}else console.error("Detected NaN set state values")},this.setCenter=function(){if(n.wrapperComponent&&n.contentComponent){var r=P3(n.transformState.scale,n.wrapperComponent,n.contentComponent);n.setTransformState(r.scale,r.positionX,r.positionY)}},this.handleTransformStyles=function(r,o,i){return n.props.customTransform?n.props.customTransform(r,o,i):UZ(r,o,i)},this.applyTransformation=function(){if(!(!n.mounted||!n.contentComponent)){var r=n.transformState,o=r.scale,i=r.positionX,s=r.positionY,l=n.handleTransformStyles(i,s,o);n.contentComponent.style.transform=l}},this.getContext=function(){return St(n)},this.onChange=function(r){return n.onChangeCallbacks.has(r)||n.onChangeCallbacks.add(r),function(){n.onChangeCallbacks.delete(r)}},this.onInit=function(r){return n.onInitCallbacks.has(r)||n.onInitCallbacks.add(r),function(){n.onInitCallbacks.delete(r)}},this.init=function(r,o){n.cleanupWindowEvents(),n.wrapperComponent=r,n.contentComponent=o,dc(n,n.transformState.scale),n.handleInitializeWrapperEvents(r),n.handleInitialize(o),n.initializeWindowEvents(),n.isInitialized=!0;var i=St(n);Nt(i,void 0,n.props.onInit)},this.props=t,this.setup=j2(this.props),this.transformState=$3(this.props)}return e}(),qx=Fe.createContext(null),dq=function(e,t){return typeof e=="function"?e(t):e},fq=Fe.forwardRef(function(e,t){var n=f.useRef(new uq(e)).current,r=dq(e.children,F1(n));return f.useImperativeHandle(t,function(){return F1(n)},[n]),f.useEffect(function(){n.update(e)},[n,e]),Fe.createElement(qx.Provider,{value:n},r)});Fe.forwardRef(function(e,t){var n=f.useRef(null),r=f.useContext(qx);return f.useEffect(function(){return r.onChange(function(o){if(n.current){var i=0,s=0;n.current.style.transform=r.handleTransformStyles(i,s,1/o.instance.transformState.scale)}})},[r]),Fe.createElement("div",_s({},e,{ref:VZ([n,t])}))});function pq(e,t){t===void 0&&(t={});var n=t.insertAt;if(!(!e||typeof document>"u")){var r=document.head||document.getElementsByTagName("head")[0],o=document.createElement("style");o.type="text/css",n==="top"&&r.firstChild?r.insertBefore(o,r.firstChild):r.appendChild(o),o.styleSheet?o.styleSheet.cssText=e:o.appendChild(document.createTextNode(e))}}var hq=`.transform-component-module_wrapper__SPB86 { + position: relative; + width: -moz-fit-content; + width: fit-content; + height: -moz-fit-content; + height: fit-content; + overflow: hidden; + -webkit-touch-callout: none; /* iOS Safari */ + -webkit-user-select: none; /* Safari */ + -khtml-user-select: none; /* Konqueror HTML */ + -moz-user-select: none; /* Firefox */ + -ms-user-select: none; /* Internet Explorer/Edge */ + user-select: none; + margin: 0; + padding: 0; +} +.transform-component-module_content__FBWxo { + display: flex; + flex-wrap: wrap; + width: -moz-fit-content; + width: fit-content; + height: -moz-fit-content; + height: fit-content; + margin: 0; + padding: 0; + transform-origin: 0% 0%; +} +.transform-component-module_content__FBWxo img { + pointer-events: none; +} +`,z2={wrapper:"transform-component-module_wrapper__SPB86",content:"transform-component-module_content__FBWxo"};pq(hq);var mq=function(e){var t=e.children,n=e.wrapperClass,r=n===void 0?"":n,o=e.contentClass,i=o===void 0?"":o,s=e.wrapperStyle,l=e.contentStyle,u=e.wrapperProps,d=u===void 0?{}:u,h=e.contentProps,m=h===void 0?{}:h,g=f.useContext(qx),y=g.init,x=g.cleanupWindowEvents,_=f.useRef(null),C=f.useRef(null);return f.useEffect(function(){var S=_.current,b=C.current;return S!==null&&b!==null&&y&&(y==null||y(S,b)),function(){x==null||x()}},[]),Fe.createElement("div",_s({},d,{ref:_,className:"react-transform-wrapper ".concat(z2.wrapper," ").concat(r),style:s}),Fe.createElement("div",_s({},m,{ref:C,className:"react-transform-component ".concat(z2.content," ").concat(i),style:l}),t))};const N3=["PageUp","PageDown"],D3=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],I3={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},Wd="Slider",[z1,gq,vq]=zd(Wd),[L3,Cte]=An(Wd,[vq]),[yq,dg]=L3(Wd),wq=f.forwardRef((e,t)=>{const{name:n,min:r=0,max:o=100,step:i=1,orientation:s="horizontal",disabled:l=!1,minStepsBetweenThumbs:u=0,defaultValue:d=[r],value:h,onValueChange:m=()=>{},onValueCommit:g=()=>{},inverted:y=!1,...x}=e,[_,C]=f.useState(null),S=Be(t,U=>C(U)),b=f.useRef(new Set),E=f.useRef(0),k=s==="horizontal",P=_?!!_.closest("form"):!0,M=k?xq:bq,[A=[],O]=Zr({prop:h,defaultProp:d,onChange:U=>{var te;(te=[...b.current][E.current])===null||te===void 0||te.focus(),m(U)}}),F=f.useRef(A);function V(U){const te=Pq(A,U);ae(U,te)}function J(U){ae(U,E.current)}function G(){const U=F.current[E.current];A[E.current]!==U&&g(A)}function ae(U,te,{commit:L}={commit:!1}){const ie=Nq(i),K=Dq(Math.round((U-r)/i)*i+r,ie),Q=id(K,[r,o]);O((W=[])=>{const le=Rq(W,Q,te);if(Mq(le,u*i)){E.current=le.indexOf(Q);const ge=String(le)!==String(W);return ge&&L&&g(le),ge?le:W}else return W})}return f.createElement(yq,{scope:e.__scopeSlider,disabled:l,min:r,max:o,valueIndexToChangeRef:E,thumbs:b.current,values:A,orientation:s},f.createElement(z1.Provider,{scope:e.__scopeSlider},f.createElement(z1.Slot,{scope:e.__scopeSlider},f.createElement(M,Y({"aria-disabled":l,"data-disabled":l?"":void 0},x,{ref:S,onPointerDown:ue(x.onPointerDown,()=>{l||(F.current=A)}),min:r,max:o,inverted:y,onSlideStart:l?void 0:V,onSlideMove:l?void 0:J,onSlideEnd:l?void 0:G,onHomeKeyDown:()=>!l&&ae(r,0,{commit:!0}),onEndKeyDown:()=>!l&&ae(o,A.length-1,{commit:!0}),onStepKeyDown:({event:U,direction:te})=>{if(!l){const K=N3.includes(U.key)||U.shiftKey&&D3.includes(U.key)?10:1,Q=E.current,W=A[Q],le=i*K*te;ae(W+le,Q,{commit:!0})}}})))),P&&A.map((U,te)=>f.createElement(kq,{key:te,name:n?n+(A.length>1?"[]":""):void 0,value:U})))}),[F3,j3]=L3(Wd,{startEdge:"left",endEdge:"right",size:"width",direction:1}),xq=f.forwardRef((e,t)=>{const{min:n,max:r,dir:o,inverted:i,onSlideStart:s,onSlideMove:l,onSlideEnd:u,onStepKeyDown:d,...h}=e,[m,g]=f.useState(null),y=Be(t,E=>g(E)),x=f.useRef(),_=Sc(o),C=_==="ltr",S=C&&!i||!C&&i;function b(E){const k=x.current||m.getBoundingClientRect(),P=[0,k.width],A=Qx(P,S?[n,r]:[r,n]);return x.current=k,A(E-k.left)}return f.createElement(F3,{scope:e.__scopeSlider,startEdge:S?"left":"right",endEdge:S?"right":"left",direction:S?1:-1,size:"width"},f.createElement(z3,Y({dir:_,"data-orientation":"horizontal"},h,{ref:y,style:{...h.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:E=>{const k=b(E.clientX);s==null||s(k)},onSlideMove:E=>{const k=b(E.clientX);l==null||l(k)},onSlideEnd:()=>{x.current=void 0,u==null||u()},onStepKeyDown:E=>{const P=I3[S?"from-left":"from-right"].includes(E.key);d==null||d({event:E,direction:P?-1:1})}})))}),bq=f.forwardRef((e,t)=>{const{min:n,max:r,inverted:o,onSlideStart:i,onSlideMove:s,onSlideEnd:l,onStepKeyDown:u,...d}=e,h=f.useRef(null),m=Be(t,h),g=f.useRef(),y=!o;function x(_){const C=g.current||h.current.getBoundingClientRect(),S=[0,C.height],E=Qx(S,y?[r,n]:[n,r]);return g.current=C,E(_-C.top)}return f.createElement(F3,{scope:e.__scopeSlider,startEdge:y?"bottom":"top",endEdge:y?"top":"bottom",size:"height",direction:y?1:-1},f.createElement(z3,Y({"data-orientation":"vertical"},d,{ref:m,style:{...d.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:_=>{const C=x(_.clientY);i==null||i(C)},onSlideMove:_=>{const C=x(_.clientY);s==null||s(C)},onSlideEnd:()=>{g.current=void 0,l==null||l()},onStepKeyDown:_=>{const S=I3[y?"from-bottom":"from-top"].includes(_.key);u==null||u({event:_,direction:S?-1:1})}})))}),z3=f.forwardRef((e,t)=>{const{__scopeSlider:n,onSlideStart:r,onSlideMove:o,onSlideEnd:i,onHomeKeyDown:s,onEndKeyDown:l,onStepKeyDown:u,...d}=e,h=dg(Wd,n);return f.createElement(Pe.span,Y({},d,{ref:t,onKeyDown:ue(e.onKeyDown,m=>{m.key==="Home"?(s(m),m.preventDefault()):m.key==="End"?(l(m),m.preventDefault()):N3.concat(D3).includes(m.key)&&(u(m),m.preventDefault())}),onPointerDown:ue(e.onPointerDown,m=>{const g=m.target;g.setPointerCapture(m.pointerId),m.preventDefault(),h.thumbs.has(g)?g.focus():r(m)}),onPointerMove:ue(e.onPointerMove,m=>{m.target.hasPointerCapture(m.pointerId)&&o(m)}),onPointerUp:ue(e.onPointerUp,m=>{const g=m.target;g.hasPointerCapture(m.pointerId)&&(g.releasePointerCapture(m.pointerId),i(m))})}))}),_q="SliderTrack",Sq=f.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,o=dg(_q,n);return f.createElement(Pe.span,Y({"data-disabled":o.disabled?"":void 0,"data-orientation":o.orientation},r,{ref:t}))}),B2="SliderRange",Eq=f.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,o=dg(B2,n),i=j3(B2,n),s=f.useRef(null),l=Be(t,s),u=o.values.length,d=o.values.map(g=>B3(g,o.min,o.max)),h=u>1?Math.min(...d):0,m=100-Math.max(...d);return f.createElement(Pe.span,Y({"data-orientation":o.orientation,"data-disabled":o.disabled?"":void 0},r,{ref:l,style:{...e.style,[i.startEdge]:h+"%",[i.endEdge]:m+"%"}}))}),U2="SliderThumb",Cq=f.forwardRef((e,t)=>{const n=gq(e.__scopeSlider),[r,o]=f.useState(null),i=Be(t,l=>o(l)),s=f.useMemo(()=>r?n().findIndex(l=>l.ref.current===r):-1,[n,r]);return f.createElement($q,Y({},e,{ref:i,index:s}))}),$q=f.forwardRef((e,t)=>{const{__scopeSlider:n,index:r,...o}=e,i=dg(U2,n),s=j3(U2,n),[l,u]=f.useState(null),d=Be(t,C=>u(C)),h=gx(l),m=i.values[r],g=m===void 0?0:B3(m,i.min,i.max),y=Tq(r,i.values.length),x=h==null?void 0:h[s.size],_=x?Aq(x,g,s.direction):0;return f.useEffect(()=>{if(l)return i.thumbs.add(l),()=>{i.thumbs.delete(l)}},[l,i.thumbs]),f.createElement("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[s.startEdge]:`calc(${g}% + ${_}px)`}},f.createElement(z1.ItemSlot,{scope:e.__scopeSlider},f.createElement(Pe.span,Y({role:"slider","aria-label":e["aria-label"]||y,"aria-valuemin":i.min,"aria-valuenow":m,"aria-valuemax":i.max,"aria-orientation":i.orientation,"data-orientation":i.orientation,"data-disabled":i.disabled?"":void 0,tabIndex:i.disabled?void 0:0},o,{ref:d,style:m===void 0?{display:"none"}:e.style,onFocus:ue(e.onFocus,()=>{i.valueIndexToChangeRef.current=r})}))))}),kq=e=>{const{value:t,...n}=e,r=f.useRef(null),o=Fx(t);return f.useEffect(()=>{const i=r.current,s=window.HTMLInputElement.prototype,u=Object.getOwnPropertyDescriptor(s,"value").set;if(o!==t&&u){const d=new Event("input",{bubbles:!0});u.call(i,t),i.dispatchEvent(d)}},[o,t]),f.createElement("input",Y({style:{display:"none"}},n,{ref:r,defaultValue:t}))};function Rq(e=[],t,n){const r=[...e];return r[n]=t,r.sort((o,i)=>o-i)}function B3(e,t,n){const i=100/(n-t)*(e-t);return id(i,[0,100])}function Tq(e,t){return t>2?`Value ${e+1} of ${t}`:t===2?["Minimum","Maximum"][e]:void 0}function Pq(e,t){if(e.length===1)return 0;const n=e.map(o=>Math.abs(o-t)),r=Math.min(...n);return n.indexOf(r)}function Aq(e,t,n){const r=e/2,i=Qx([0,50],[0,r]);return(r-i(t)*n)*n}function Oq(e){return e.slice(0,-1).map((t,n)=>e[n+1]-t)}function Mq(e,t){if(t>0){const n=Oq(e);return Math.min(...n)>=t}return!0}function Qx(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 Nq(e){return(String(e).split(".")[1]||"").length}function Dq(e,t){const n=Math.pow(10,t);return Math.round(e*n)/n}const U3=wq,Iq=Sq,Lq=Eq,Fq=Cq,uo=f.forwardRef(({className:e,...t},n)=>v.jsxs(U3,{ref:n,className:Ce("relative flex w-full touch-none select-none items-center",e),tabIndex:-1,...t,children:[v.jsx(Iq,{className:"relative h-1.5 w-full grow overflow-hidden rounded-full bg-primary/20 data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50",children:v.jsx(Lq,{className:"absolute h-full bg-primary data-[disabled]:cursor-not-allowed "})}),v.jsx(Fq,{tabIndex:-1,className:"block h-4 w-4 rounded-full border border-primary/60 bg-background shadow transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring data-[disabled]:cursor-not-allowed"})]}));uo.displayName=U3.displayName;const tl={capture:!0,passive:!1},jq=2,V2=(e,t,n,r,o,i)=>{if(e!==n&&t===r){if(e<0)return[0,r];if(e+t>i)return[i-r,r]}else{if(ti)return[e,i-e]}return[e,t]},zq=e=>{const{minHeight:t,minWidth:n,maxHeight:r,maxWidth:o,scale:i,show:s}=e,[l,u,d,h,{x:m,y:g,width:y,height:x},_,C,S,b,E,k]=bt(W=>[W.imageWidth,W.imageHeight,W.isInpainting,W.isSD(),W.cropperState,W.setCropperX,W.setCropperY,W.setCropperWidth,W.setCropperHeight,W.isCropperExtenderResizing,W.setIsCropperExtenderResizing]),[P,M]=f.useState(!1);f.useEffect(()=>{_(Math.round((o-512)/2)),C(Math.round((r-512)/2))},[r,o,l,u]);const[A,O]=f.useState({initX:0,initY:0,initHeight:0,initWidth:0,startResizeX:0,startResizeY:0,ord:"top"}),F=()=>{},V=(W,le)=>V2(W,le,m,y,n,o),J=(W,le)=>V2(W,le,g,x,t,r),G=W=>{if(d)return;const le=W.clientX,ge=W.clientY,Ve=Math.round((ge-A.startResizeY)/i),Ue=Math.round((le-A.startResizeX)/i),We=()=>{const $e=A.initHeight-Ve,Ae=A.initY+Ve,[Oe,je]=J(Ae,$e);b(je),C(Oe)},Me=()=>{const $e=A.initHeight+Ve,[Ae,Oe]=J(A.initY,$e);b(Oe),C(Ae)},fe=()=>{const $e=A.initWidth-Ue,Ae=A.initX+Ue,[Oe,je]=V(Ae,$e);S(je),_(Oe)},xe=()=>{const $e=A.initWidth+Ue,[Ae,Oe]=V(A.initX,$e);S(Oe),_(Ae)};if(E)switch(A.ord){case"topleft":{We(),fe();break}case"topright":{We(),xe();break}case"bottomleft":{Me(),fe();break}case"bottomright":{Me(),xe();break}case"top":{We();break}case"right":{xe();break}case"bottom":{Me();break}case"left":{fe();break}}if(P){const $e=A.initX+Ue,Ae=A.initY+Ve,[Oe,je]=V($e,A.initWidth),[Ot,ct]=J(Ae,A.initHeight);S(je),b(ct),_(Oe),C(Ot)}},ae=()=>{E&&k(!1),P&&M(!1)};f.useEffect(()=>{if(E||P)return document.addEventListener("pointermove",G,tl),document.addEventListener("pointerup",ae,tl),document.addEventListener("pointercancel",ae,tl),()=>{document.removeEventListener("pointermove",G,tl),document.removeEventListener("pointerup",ae,tl),document.removeEventListener("pointercancel",ae,tl)}},[E,P,y,x,A]);const U=W=>{const{ord:le}=W.target.dataset;le&&(k(!0),O({initX:m,initY:g,initHeight:x,initWidth:y,startResizeX:W.clientX,startResizeY:W.clientY,ord:le}))},te=(W,le,ge)=>{const We="w-[12px] h-[12px] z-[4] absolute content-[''] block border-2 border-primary borde pointer-events-auto hover:bg-primary";let Me="0",fe="0",xe=ge,$e="-6px";return ge===""&&($e="50%",le==="left"||le==="right"?(xe="top",fe="-50%"):(xe="left",Me="-50%")),v.jsx("div",{className:Ce(We,W),style:{[le]:-6,[xe]:$e,transform:`translate(${Me}, ${fe}) scale(${1/i})`},"data-ord":le+ge,"aria-label":le+ge,tabIndex:-1,role:"button"})},L=()=>v.jsxs("div",{onFocus:F,onPointerDown:U,className:"absolute top-0 h-full w-full",children:[v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 w-full cursor-ns-resize h-[12px] mt-[-6px]","data-ord":"top"}),v.jsx("div",{className:"absolute pointer-events-auto top-0 right-0 h-full cursor-ew-resize w-[12px] mr-[-6px]","data-ord":"right"}),v.jsx("div",{className:"absolute pointer-events-auto bottom-0 left-0 w-full cursor-ns-resize h-[12px] mb-[-6px]","data-ord":"bottom"}),v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 h-full cursor-ew-resize w-[12px] ml-[-6px]","data-ord":"left"}),te("cursor-nw-resize","top","left"),te("cursor-ne-resize","top","right"),te("cursor-sw-resize","bottom","left"),te("cursor-se-resize","bottom","right"),te("cursor-ns-resize","top",""),te("cursor-ns-resize","bottom",""),te("cursor-ew-resize","left",""),te("cursor-ew-resize","right","")]}),ie=W=>{M(!0),O({initX:m,initY:g,initHeight:x,initWidth:y,startResizeX:W.clientX,startResizeY:W.clientY,ord:""})},K=()=>v.jsxs("div",{className:Jw("border absolute pointer-events-auto px-2 py-1 rounded-full hover:cursor-move bg-background","origin-top-left top-0 left-0"),style:{transform:`scale(${1/i*.8})`},onPointerDown:ie,children:[y," x ",x]}),Q=()=>v.jsx("div",{className:"outline-dashed outline-primary",style:{height:x,width:y,outlineWidth:`${jq/i*1.3}px`}});return s===!1||!h?null:v.jsx("div",{className:"absolute h-full w-full overflow-hidden pointer-events-none z-[2]",children:v.jsxs("div",{className:"relative pointer-events-none z-[2] [box-shadow:0_0_0_9999px_rgba(0,_0,_0,_0.5)]",style:{height:x,width:y,left:m,top:g},children:[Q(),K(),L()]})})},Bq=()=>{const[e,t,n]=bt(r=>[r.interactiveSegState,r.resetInteractiveSegState,r.handleInteractiveSegAccept]);return e.isInteractiveSeg?v.jsxs("div",{className:"z-10 absolute top-[68px] rounded-xl border-solid border p-[8px] left-1/2 translate-x-[-50%] flex justify-center items-center gap-[8px] bg-background",children:[v.jsx(Rn,{onClick:()=>{t()},size:"sm",variant:"secondary",children:"Cancel"}),v.jsx(Rn,{size:"sm",onClick:()=>{n()},children:"Accept"})]}):null},Uq=e=>{const{x:t,y:n,positive:r}=e,o=r?"bg-[rgba(21,_215,_121,_0.936)] outline-[rgba(98,255,179,0.31)]":"bg-[rgba(237,_49,_55,_0.942)] outline-[rgba(255,89,95,0.31)]";return v.jsx("div",{className:`absolute h-[10px] w-[10px] rounded-[50%] ${o} outline-8 outline`,style:{left:t,top:n,transform:"translate(-50%, -50%)"}})},Vq=()=>{const e=bt(t=>t.interactiveSegState.clicks);return v.jsx("div",{className:"absolute h-full w-full overflow-hidden pointer-events-none",children:e.map(t=>v.jsx(Uq,{x:t[0],y:t[1],positive:t[2]===1},t[3]))})},Wq=()=>v.jsx("div",{children:v.jsx(Bq,{})}),nl={capture:!0,passive:!1},Hq=2,W2=(e,t,n,r)=>t{const{minHeight:t,minWidth:n,scale:r,show:o}=e,[i,s,l,u,{x:d,y:h,width:m,height:g},y,x,_,C,S,b,E]=bt(ie=>[ie.isInpainting,ie.imageHeight,ie.imageWidth,ie.isSD(),ie.extenderState,ie.setExtenderX,ie.setExtenderY,ie.setExtenderWidth,ie.setExtenderHeight,ie.settings.extenderDirection,ie.isCropperExtenderResizing,ie.setIsCropperExtenderResizing]),[k,P]=f.useState({initX:0,initY:0,initHeight:0,initWidth:0,startResizeX:0,startResizeY:0,ord:"top"}),M=()=>{},A=(ie,K)=>W2(ie,K,d,n),O=(ie,K)=>W2(ie,K,h,t),F=ie=>{if(i)return;const K=ie.clientX,Q=ie.clientY,W=Math.round((Q-k.startResizeY)/r),le=Math.round((K-k.startResizeX)/r),ge=()=>{const Me=k.initHeight-W,fe=k.initY+W;let xe=fe,$e=Me;if(S===In.xy)xe>0&&(xe=0,$e=k.initHeight-Math.abs(k.initY));else{const Ae=O(fe,Me);xe=Ae[0],$e=Ae[1]}C($e),x(xe)},Ve=()=>{const Me=k.initHeight+W;let[fe,xe]=O(k.initY,Me);S===In.xy&&xe{const Me=k.initWidth-le,fe=k.initX+le;let xe=fe,$e=Me;if(S===In.xy)xe>0&&(xe=0,$e=k.initWidth-Math.abs(k.initX));else{const Ae=A(fe,Me);xe=Ae[0],$e=Ae[1]}_($e),y(xe)},We=()=>{const Me=k.initWidth+le;let[fe,xe]=A(k.initX,Me);S===In.xy&&xe{b&&E(!1)};f.useEffect(()=>{if(b)return document.addEventListener("pointermove",F,nl),document.addEventListener("pointerup",V,nl),document.addEventListener("pointercancel",V,nl),()=>{document.removeEventListener("pointermove",F,nl),document.removeEventListener("pointerup",V,nl),document.removeEventListener("pointercancel",V,nl)}},[b,m,g,k]);const J=ie=>{const{ord:K}=ie.target.dataset;K&&(E(!0),P({initX:d,initY:h,initHeight:g,initWidth:m,startResizeX:ie.clientX,startResizeY:ie.clientY,ord:K}))},G=(ie,K,Q)=>{const ge="w-[12px] h-[12px] z-[4] absolute content-[''] block border-2 border-primary borde pointer-events-auto hover:bg-primary";let Ve="0",Ue="0",We=Q,Me="-6px";return Q===""&&(Me="50%",K==="left"||K==="right"?(We="top",Ue="-50%"):(We="left",Ve="-50%")),v.jsx("div",{className:Ce(ge,ie),style:{[K]:-6,[We]:Me,transform:`translate(${Ve}, ${Ue}) scale(${1/r})`},"data-ord":K+Q,"aria-label":K+Q,tabIndex:-1,role:"button"})},ae=()=>v.jsxs("div",{onFocus:M,onPointerDown:J,className:"absolute top-0 h-full w-full",children:[[In.y,In.xy].includes(S)?v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 w-full cursor-ns-resize h-[12px] mt-[-6px]","data-ord":"top"}),v.jsx("div",{className:"absolute pointer-events-auto bottom-0 left-0 w-full cursor-ns-resize h-[12px] mb-[-6px]","data-ord":"bottom"}),G("cursor-ns-resize","top",""),G("cursor-ns-resize","bottom","")]}):v.jsx(v.Fragment,{}),[In.x,In.xy].includes(S)?v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"absolute pointer-events-auto top-0 right-0 h-full cursor-ew-resize w-[12px] mr-[-6px]","data-ord":"right"}),v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 h-full cursor-ew-resize w-[12px] ml-[-6px]","data-ord":"left"}),G("cursor-ew-resize","left",""),G("cursor-ew-resize","right","")]}):v.jsx(v.Fragment,{}),S===In.xy?v.jsxs(v.Fragment,{children:[G("cursor-nw-resize","top","left"),G("cursor-ne-resize","top","right"),G("cursor-sw-resize","bottom","left"),G("cursor-se-resize","bottom","right")]}):v.jsx(v.Fragment,{})]}),U=ie=>{P({initX:d,initY:h,initHeight:g,initWidth:m,startResizeX:ie.clientX,startResizeY:ie.clientY,ord:""})},te=()=>v.jsxs("div",{className:Jw("border absolute pointer-events-auto px-2 py-1 rounded-full bg-background","origin-top-left top-0 left-0"),style:{transform:`scale(${1/r*.8})`},onPointerDown:U,children:[m," x ",g]}),L=()=>v.jsx("div",{className:Ce("outline-dashed outline-primary"),style:{height:g,width:m,outlineWidth:`${Hq/r*1.3}px`}});return o===!1||!u?null:v.jsx("div",{className:"absolute h-full w-full pointer-events-none z-[2]",children:v.jsxs("div",{className:"relative pointer-events-none z-[2] [box-shadow:0_0_0_9999px_rgba(0,_0,_0,_0.5)]",style:{height:g,width:m,left:d,top:h},children:[L(),te(),ae()]})})},Yq=200,Gq=10,Xq=200,lu=300;function Zq(e){const{file:t}=e,{toast:n}=Td(),[r,o,i,s,l,u,d,h,m,g,y,x,_,C,S,b,E,k,P,M,A,O]=bt(H=>[H.disableShortCuts,H.windowSize,H.isInpainting,H.imageWidth,H.imageHeight,H.settings,H.serverConfig.enableAutoSaving,H.setImageSize,H.setBaseBrushSize,H.interactiveSegState,H.updateInteractiveSegState,H.handleCanvasMouseDown,H.handleCanvasMouseMove,H.undo,H.redo,H.undoDisabled(),H.redoDisabled(),H.getIsProcessing(),H.updateAppState,H.runMannually(),H.runInpainting,H.isCropperExtenderResizing]),F=bt(H=>H.editorState.baseBrushSize),V=bt(H=>H.getBrushSize()),J=bt(H=>H.editorState.renders),G=bt(H=>H.editorState.extraMasks),ae=bt(H=>H.editorState.temporaryMasks),U=bt(H=>H.editorState.lineGroups),te=bt(H=>H.editorState.curLineGroup),[L,ie]=f.useState(!1),[K,Q]=Rx(t),[W,le]=f.useState(),[ge,Ve]=f.useState(),[{x:Ue,y:We},Me]=f.useState({x:-1,y:-1}),[fe,xe]=f.useState(!1),[$e,Ae]=f.useState(!1),[Oe,je]=f.useState(!1),[Ot,ct]=f.useState(1),[Yt,Er]=f.useState(!1),[gt,js]=f.useState(1),I=o.width/2,X=o.height/2,Z=f.useRef(null),[we,he]=f.useState(!1),[de,ke]=f.useState(!1),[ft,pt]=f.useState(0),bn=f.useCallback(()=>te.length!==0,[te]);f.useEffect(()=>{if(!ge||!Q||s===0||l===0)return;const H=J.length===0?K:J[J.length-1];ge.canvas.width=s,ge.canvas.height=l,ge.clearRect(0,0,ge.canvas.width,ge.canvas.height),ge.drawImage(H,0,0,s,l)},[J,K,Q,ge,l,s]),f.useEffect(()=>{!W||!Q||s===0||l===0||(W.canvas.width=s,W.canvas.height=l,W.clearRect(0,0,W.canvas.width,W.canvas.height),ae.forEach(H=>{W.drawImage(H,0,0,s,l)}),G.forEach(H=>{W.drawImage(H,0,0,s,l)}),g.isInteractiveSeg&&g.tmpInteractiveSegMask&&W.drawImage(g.tmpInteractiveSegMask,0,0,s,l),GR(W,te))},[ae,G,Q,g,W,te,l,s]);const Cr=f.useCallback(async()=>{let H=t;if(J.length>0){const Ge=J[J.length-1];H=await ku(Ge.currentSrc,t.name,t.type)}return H},[t,J]),ki=()=>J.length!==0,_o=f.useCallback(()=>{let H=512,Ge=512;return Q?(J.length===0?(H=K.naturalWidth,Ge=K.naturalHeight):J.length!==0&&(H=J[J.length-1].width,Ge=J[J.length-1].height),[H,Ge]):[H,Ge]},[K,Q,J]);f.useEffect(()=>{var Gd;if(!Q)return;const[H,Ge]=_o();(H!==s||Ge!==l)&&h(H,Ge);const st=o.width/H,Qr=(o.height-Yq)/Ge;let an=1;(st<1||Qr<1)&&(an=Math.min(st,Qr)),js(an),ct(an),console.log(`[on file load] image size: ${H}x${Ge}, scale: ${an}, initialCentered: ${we}`),W!=null&&W.canvas&&(console.log("[on file load] set canvas size"),H!=W.canvas.width&&(W.canvas.width=H),Ge!=W.canvas.height&&(W.canvas.height=Ge)),we||((Gd=Z.current)==null||Gd.centerView(an,1),console.log("[on file load] centerView"),he(!0))},[Z,l,s,K,Q,o,we,_o]),f.useEffect(()=>{var H;console.log("[useEffect] centerView"),(H=Z==null?void 0:Z.current)==null||H.centerView(gt,1)},[l,s,Z,gt]);const Vn=f.useCallback(()=>{if(!gt||!o)return;const H=Z.current;if(!H)return;const Ge=(o.width-s*gt)/2,st=(o.height-l*gt)/2;H.setTransform(Ge,st,gt,200,"easeOutQuad"),H.instance.transformState.scale&&(H.instance.transformState.scale=gt),ct(gt),Er(!1)},[Z,o,l,s,o.height,gt]);f.useEffect(()=>(window.addEventListener("resize",()=>{Vn()}),()=>{window.removeEventListener("resize",()=>{Vn()})}),[o,Vn]),Zn("Escape",()=>{k||(de?ke(!1):Vn())},[de,i,Vn]);const Ri=H=>{const Ge=H.nativeEvent;Me({x:Ge.pageX,y:Ge.pageY})},zs=H=>{k||g.isInteractiveSeg||Oe||de&&te.length!==0&&_(c0(H))},Ti=async H=>{P({isPluginRunning:!0});const Ge=await Cr();try{const st=await gT(!0,jR.InteractiveSeg,Ge,void 0,H),{blob:Qr}=st,an=new Image;an.onload=()=>{y({tmpInteractiveSegMask:an})},an.src=Qr}catch(st){n({variant:"destructive",description:st.message?st.message:st.toString()})}P({isPluginRunning:!1})},$c=H=>{if(!bn())return;if(cC(H)){je(!1);return}g.isInteractiveSeg||Oe||!K.src||!(W!=null&&W.canvas)||i||de&&(M?ke(!1):A())},yg=H=>{if(g.isInteractiveSeg){const Ge=c0(H),st=[...g.clicks];lC(H)?st.push([Ge.x,Ge.y,0,st.length]):st.push([Ge.x,Ge.y,1,st.length]),Ti(st),y({clicks:st})}},wg=H=>{if(!(k||g.isInteractiveSeg||Oe||!Q||!(W!=null&&W.canvas))&&!lC(H)){if(cC(H)){je(!0);return}ke(!0),x(c0(H))}},Kd=H=>{H.preventDefault(),C()};Zn("meta+z,ctrl+z",Kd);const kc=H=>{H.preventDefault(),S()};Zn("shift+ctrl+z,shift+meta+z",kc),o2("Tab",H=>{H==null||H.preventDefault(),H==null||H.stopPropagation(),ki()&&ie(()=>(window.setTimeout(()=>{pt(100)},10),!0))},H=>{H==null||H.preventDefault(),H==null||H.stopPropagation(),ki()&&(window.setTimeout(()=>{pt(0)},10),window.setTimeout(()=>{ie(!1)},lu))});const Rc=f.useCallback(async()=>{if(t===void 0)return;if(d&&J.length>0){try{await Vj(J[J.length-1],t.name,t.type),n({description:"Save image success"})}catch(st){n({variant:"destructive",title:"Uh oh! Something went wrong.",description:st.message?st.message:st.toString()})}return}const H=t.name.replace(/(\.[\w\d_-]+)$/i,"_cleanup$1"),Ge=J[J.length-1];if(vF(Ge.currentSrc,H),u.enableDownloadMask){let st=t.name.replace(/(\.[\w\d_-]+)$/i,"_mask$1");st=st.replace(/\.[^/.]+$/,".jpg");const Qr=Lp(s,l,U),an=document.createElement("a");an.download=st,an.href=Qr.toDataURL("image/jpeg"),an.click()}},[t,d,J,u,l,s,U]);Zn("meta+s,ctrl+s",Rc);const Tc=H=>{H!==fe&&!Oe&&!O&&xe(H)},xg=f.useCallback(()=>{if(k)return"default";if(Oe)return"grab";if(fe)return"none"},[fe,Oe,k]);Zn("[",()=>{let H=F;F>10&&(H=F-10),F<=10&&F>0&&(H=F-5),m(H)},[F]),Zn("]",()=>{m(F+10)},[F]),Zn("shift+r",()=>{M&&bn()&&A()},[M,A,bn]),Zn("ctrl+c,meta+c",async()=>{await pF()&&J.length>0&&W!=null&&W.canvas&&(await gF(W==null?void 0:W.canvas),n({title:"Copy inpainting result to clipboard"}))},[J,W]),o2(" ",H=>{r||(H==null||H.preventDefault(),H==null||H.stopPropagation(),xe(!1),je(!0))},H=>{r||(H==null||H.preventDefault(),H==null||H.stopPropagation(),xe(!0),je(!1))});const Pc=()=>{var Ge,st,Qr,an;let H=gt;return((st=(Ge=Z.current)==null?void 0:Ge.instance)==null?void 0:st.transformState.scale)!==void 0&&(H=(an=(Qr=Z.current)==null?void 0:Qr.instance)==null?void 0:an.transformState.scale),H},Yd=(H,Ge)=>{const st=Pc();return{width:`${V*st}px`,height:`${V*st}px`,left:`${H}px`,top:`${Ge}px`,transform:"translate(-50%, -50%)"}},Ac=H=>v.jsx("div",{className:"absolute rounded-[50%] border-[1px] border-[solid] border-[#ffcc00] pointer-events-none bg-[#ffcc00bb]",style:H}),bg=H=>{m(H),$e||(Ae(!0),window.setTimeout(()=>{Ae(!1)},1e4))},_g=()=>v.jsx("div",{className:"absolute h-[20px] w-[20px] pointer-events-none rounded-[50%] bg-[rgba(21,_215,_121,_0.936)] [box-shadow:0_0_0_0_rgba(21,_215,_121,_0.936)] animate-pulse",style:{left:`${Ue}px`,top:`${We}px`,transform:"translate(-50%, -50%)"},children:v.jsx(dK,{})}),Sg=()=>v.jsx(fq,{ref:H=>{H&&(Z.current=H)},panning:{disabled:!Oe,velocityDisabled:!0},wheel:{step:.05},centerZoomedOut:!0,alignmentAnimation:{disabled:!0},centerOnInit:!0,limitToBounds:!1,doubleClick:{disabled:!0},initialScale:gt,minScale:gt*.3,onPanning:()=>{Yt||Er(!0)},onZoom:H=>{ct(H.state.scale)},children:v.jsxs(mq,{contentStyle:{visibility:we?"visible":"hidden"},children:[v.jsxs("div",{className:"grid [grid-template-areas:'editor-content'] gap-y-4",children:[v.jsx("canvas",{className:"[grid-area:editor-content]",style:{clipPath:`inset(0 ${ft}% 0 0)`,transition:`clip-path ${lu}ms`},ref:H=>{if(H&&!ge){const Ge=H.getContext("2d");Ge&&Ve(Ge)}}}),v.jsx("canvas",{className:Ce("[grid-area:editor-content]",k?"pointer-events-none animate-pulse duration-600":""),style:{cursor:xg(),clipPath:`inset(0 ${ft}% 0 0)`,transition:`clip-path ${lu}ms`},onContextMenu:H=>{H.preventDefault()},onMouseOver:()=>{Tc(!0),Ae(!1)},onFocus:()=>Tc(!0),onMouseLeave:()=>Tc(!1),onMouseDown:wg,onMouseUp:yg,onMouseMove:zs,ref:H=>{if(H&&!W){const Ge=H.getContext("2d");Ge&&le(Ge)}}}),v.jsx("div",{className:"[grid-area:editor-content] pointer-events-none grid [grid-template-areas:'original-image-content']",style:{width:`${s}px`,height:`${l}px`},children:L&&v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"[grid-area:original-image-content] z-10 bg-primary h-full w-[6px] justify-self-end",style:{marginRight:`${ft}%`,transition:`margin-right ${lu}ms`}}),v.jsx("img",{className:"[grid-area:original-image-content]",src:K.src,alt:"original",style:{width:`${s}px`,height:`${l}px`}})]})})]}),v.jsx(zq,{maxHeight:l,maxWidth:s,minHeight:Math.min(512,l),minWidth:Math.min(512,s),scale:Pc(),show:u.showCropper}),v.jsx(Kq,{minHeight:Math.min(512,l),minWidth:Math.min(512,s),scale:Pc(),show:u.showExtender}),g.isInteractiveSeg?v.jsx(Vq,{}):v.jsx(v.Fragment,{})]})});return v.jsxs("div",{className:"flex w-screen h-screen justify-center items-center","aria-hidden":"true",onMouseMove:Ri,onMouseUp:$c,children:[Sg(),fe&&!i&&!Oe&&(g.isInteractiveSeg?_g():Ac(Yd(Ue,We))),$e&&Ac(Yd(I,X)),v.jsxs("div",{className:" overflow-hidden fixed flex bottom-5 border px-4 py-2 rounded-[3rem] gap-8 items-center justify-center backdrop-filter backdrop-blur-md bg-background/70",children:[v.jsx(uo,{className:"w-48",defaultValue:[50],min:Gq,max:Xq,step:1,tabIndex:-1,value:[F],onValueChange:H=>bg(H[0]),onClick:()=>Ae(!1)}),v.jsxs("div",{className:"flex gap-2",children:[v.jsx(vn,{tooltip:"Reset zoom & pan",disabled:Ot===gt&&Yt===!1,onClick:Vn,children:v.jsx(ZU,{})}),v.jsx(vn,{tooltip:"Undo",onClick:Kd,disabled:b,children:v.jsx(aV,{})}),v.jsx(vn,{tooltip:"Redo",onClick:kc,disabled:E,children:v.jsx(oV,{})}),v.jsx(vn,{tooltip:"Show original image",onPointerDown:H=>{H.preventDefault(),ie(()=>(window.setTimeout(()=>{pt(100)},10),!0))},onPointerUp:()=>{window.setTimeout(()=>{pt(0)},10),window.setTimeout(()=>{ie(!1)},lu)},disabled:J.length===0,children:v.jsx(qU,{})}),v.jsx(vn,{tooltip:"Save Image",disabled:!J.length,onClick:Rc,children:v.jsx(GU,{})}),u.enableManualInpainting&&u.model.model_type==="inpaint"?v.jsx(vn,{tooltip:"Run Inpainting",disabled:k||!bn()&&G.length===0,onClick:()=>{A()},children:v.jsx(XU,{})}):v.jsx(v.Fragment,{})]})]})]})}const qq=()=>{const[e,t]=bt(n=>[n.imageWidth,n.imageHeight]);return!e||!t?null:v.jsxs("div",{className:"border rounded-lg px-2 py-[6px] z-10 bg-background",children:[e,"x",t]})},B1=["Enter"," "],Qq=["ArrowDown","PageUp","Home"],V3=["ArrowUp","PageDown","End"],Jq=[...Qq,...V3],eQ={ltr:[...B1,"ArrowRight"],rtl:[...B1,"ArrowLeft"]},tQ={ltr:["ArrowLeft"],rtl:["ArrowRight"]},fg="Menu",[ld,nQ,rQ]=zd(fg),[Na,W3]=An(fg,[rQ,Ns,Qm]),pg=Ns(),H3=Qm(),[K3,Fs]=Na(fg),[oQ,Hd]=Na(fg),iQ=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:o,onOpenChange:i,modal:s=!0}=e,l=pg(t),[u,d]=f.useState(null),h=f.useRef(!1),m=Ft(i),g=Sc(o);return f.useEffect(()=>{const y=()=>{h.current=!0,document.addEventListener("pointerdown",x,{capture:!0,once:!0}),document.addEventListener("pointermove",x,{capture:!0,once:!0})},x=()=>h.current=!1;return document.addEventListener("keydown",y,{capture:!0}),()=>{document.removeEventListener("keydown",y,{capture:!0}),document.removeEventListener("pointerdown",x,{capture:!0}),document.removeEventListener("pointermove",x,{capture:!0})}},[]),f.createElement(Od,l,f.createElement(K3,{scope:t,open:n,onOpenChange:m,content:u,onContentChange:d},f.createElement(oQ,{scope:t,onClose:f.useCallback(()=>m(!1),[m]),isUsingKeyboardRef:h,dir:g,modal:s},r)))},Y3=f.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,o=pg(n);return f.createElement(zm,Y({},o,r,{ref:t}))}),G3="MenuPortal",[sQ,X3]=Na(G3,{forceMount:void 0}),aQ=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:o}=e,i=Fs(G3,t);return f.createElement(sQ,{scope:t,forceMount:n},f.createElement(xn,{present:n||i.open},f.createElement(Md,{asChild:!0,container:o},r)))},yo="MenuContent",[lQ,Jx]=Na(yo),cQ=f.forwardRef((e,t)=>{const n=X3(yo,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,i=Fs(yo,e.__scopeMenu),s=Hd(yo,e.__scopeMenu);return f.createElement(ld.Provider,{scope:e.__scopeMenu},f.createElement(xn,{present:r||i.open},f.createElement(ld.Slot,{scope:e.__scopeMenu},s.modal?f.createElement(uQ,Y({},o,{ref:t})):f.createElement(dQ,Y({},o,{ref:t})))))}),uQ=f.forwardRef((e,t)=>{const n=Fs(yo,e.__scopeMenu),r=f.useRef(null),o=Be(t,r);return f.useEffect(()=>{const i=r.current;if(i)return Xm(i)},[]),f.createElement(eb,Y({},e,{ref:o,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:ue(e.onFocusOutside,i=>i.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)}))}),dQ=f.forwardRef((e,t)=>{const n=Fs(yo,e.__scopeMenu);return f.createElement(eb,Y({},e,{ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)}))}),eb=f.forwardRef((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:o,onOpenAutoFocus:i,onCloseAutoFocus:s,disableOutsidePointerEvents:l,onEntryFocus:u,onEscapeKeyDown:d,onPointerDownOutside:h,onFocusOutside:m,onInteractOutside:g,onDismiss:y,disableOutsideScroll:x,..._}=e,C=Fs(yo,n),S=Hd(yo,n),b=pg(n),E=H3(n),k=nQ(n),[P,M]=f.useState(null),A=f.useRef(null),O=Be(t,A,C.onContentChange),F=f.useRef(0),V=f.useRef(""),J=f.useRef(0),G=f.useRef(null),ae=f.useRef("right"),U=f.useRef(0),te=x?Gm:f.Fragment,L=x?{as:Wo,allowPinchZoom:!0}:void 0,ie=Q=>{var W,le;const ge=V.current+Q,Ve=k().filter($e=>!$e.disabled),Ue=document.activeElement,We=(W=Ve.find($e=>$e.ref.current===Ue))===null||W===void 0?void 0:W.textValue,Me=Ve.map($e=>$e.textValue),fe=RQ(Me,ge,We),xe=(le=Ve.find($e=>$e.textValue===fe))===null||le===void 0?void 0:le.ref.current;(function $e(Ae){V.current=Ae,window.clearTimeout(F.current),Ae!==""&&(F.current=window.setTimeout(()=>$e(""),1e3))})(ge),xe&&setTimeout(()=>xe.focus())};f.useEffect(()=>()=>window.clearTimeout(F.current),[]),Km();const K=f.useCallback(Q=>{var W,le;return ae.current===((W=G.current)===null||W===void 0?void 0:W.side)&&PQ(Q,(le=G.current)===null||le===void 0?void 0:le.area)},[]);return f.createElement(lQ,{scope:n,searchRef:V,onItemEnter:f.useCallback(Q=>{K(Q)&&Q.preventDefault()},[K]),onItemLeave:f.useCallback(Q=>{var W;K(Q)||((W=A.current)===null||W===void 0||W.focus(),M(null))},[K]),onTriggerLeave:f.useCallback(Q=>{K(Q)&&Q.preventDefault()},[K]),pointerGraceTimerRef:J,onPointerGraceIntentChange:f.useCallback(Q=>{G.current=Q},[])},f.createElement(te,L,f.createElement(Hm,{asChild:!0,trapped:o,onMountAutoFocus:ue(i,Q=>{var W;Q.preventDefault(),(W=A.current)===null||W===void 0||W.focus()}),onUnmountAutoFocus:s},f.createElement(yc,{asChild:!0,disableOutsidePointerEvents:l,onEscapeKeyDown:d,onPointerDownOutside:h,onFocusOutside:m,onInteractOutside:g,onDismiss:y},f.createElement(ZP,Y({asChild:!0},E,{dir:S.dir,orientation:"vertical",loop:r,currentTabStopId:P,onCurrentTabStopIdChange:M,onEntryFocus:ue(u,Q=>{S.isUsingKeyboardRef.current||Q.preventDefault()})}),f.createElement(Bm,Y({role:"menu","aria-orientation":"vertical","data-state":tA(C.open),"data-radix-menu-content":"",dir:S.dir},b,_,{ref:O,style:{outline:"none",..._.style},onKeyDown:ue(_.onKeyDown,Q=>{const le=Q.target.closest("[data-radix-menu-content]")===Q.currentTarget,ge=Q.ctrlKey||Q.altKey||Q.metaKey,Ve=Q.key.length===1;le&&(Q.key==="Tab"&&Q.preventDefault(),!ge&&Ve&&ie(Q.key));const Ue=A.current;if(Q.target!==Ue||!Jq.includes(Q.key))return;Q.preventDefault();const Me=k().filter(fe=>!fe.disabled).map(fe=>fe.ref.current);V3.includes(Q.key)&&Me.reverse(),$Q(Me)}),onBlur:ue(e.onBlur,Q=>{Q.currentTarget.contains(Q.target)||(window.clearTimeout(F.current),V.current="")}),onPointerMove:ue(e.onPointerMove,cd(Q=>{const W=Q.target,le=U.current!==Q.clientX;if(Q.currentTarget.contains(W)&&le){const ge=Q.clientX>U.current?"right":"left";ae.current=ge,U.current=Q.clientX}}))})))))))}),fQ=f.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return f.createElement(Pe.div,Y({},r,{ref:t}))}),U1="MenuItem",H2="menu.itemSelect",tb=f.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...o}=e,i=f.useRef(null),s=Hd(U1,e.__scopeMenu),l=Jx(U1,e.__scopeMenu),u=Be(t,i),d=f.useRef(!1),h=()=>{const m=i.current;if(!n&&m){const g=new CustomEvent(H2,{bubbles:!0,cancelable:!0});m.addEventListener(H2,y=>r==null?void 0:r(y),{once:!0}),cx(m,g),g.defaultPrevented?d.current=!1:s.onClose()}};return f.createElement(Z3,Y({},o,{ref:u,disabled:n,onClick:ue(e.onClick,h),onPointerDown:m=>{var g;(g=e.onPointerDown)===null||g===void 0||g.call(e,m),d.current=!0},onPointerUp:ue(e.onPointerUp,m=>{var g;d.current||(g=m.currentTarget)===null||g===void 0||g.click()}),onKeyDown:ue(e.onKeyDown,m=>{const g=l.searchRef.current!=="";n||g&&m.key===" "||B1.includes(m.key)&&(m.currentTarget.click(),m.preventDefault())})}))}),Z3=f.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:o,...i}=e,s=Jx(U1,n),l=H3(n),u=f.useRef(null),d=Be(t,u),[h,m]=f.useState(!1),[g,y]=f.useState("");return f.useEffect(()=>{const x=u.current;if(x){var _;y(((_=x.textContent)!==null&&_!==void 0?_:"").trim())}},[i.children]),f.createElement(ld.ItemSlot,{scope:n,disabled:r,textValue:o??g},f.createElement(qP,Y({asChild:!0},l,{focusable:!r}),f.createElement(Pe.div,Y({role:"menuitem","data-highlighted":h?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0},i,{ref:d,onPointerMove:ue(e.onPointerMove,cd(x=>{r?s.onItemLeave(x):(s.onItemEnter(x),x.defaultPrevented||x.currentTarget.focus())})),onPointerLeave:ue(e.onPointerLeave,cd(x=>s.onItemLeave(x))),onFocus:ue(e.onFocus,()=>m(!0)),onBlur:ue(e.onBlur,()=>m(!1))}))))}),pQ=f.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...o}=e;return f.createElement(Q3,{scope:e.__scopeMenu,checked:n},f.createElement(tb,Y({role:"menuitemcheckbox","aria-checked":om(n)?"mixed":n},o,{ref:t,"data-state":nb(n),onSelect:ue(o.onSelect,()=>r==null?void 0:r(om(n)?!0:!n),{checkForDefaultPrevented:!1})})))}),hQ="MenuRadioGroup",[$te,mQ]=Na(hQ,{value:void 0,onValueChange:()=>{}}),gQ="MenuRadioItem",vQ=f.forwardRef((e,t)=>{const{value:n,...r}=e,o=mQ(gQ,e.__scopeMenu),i=n===o.value;return f.createElement(Q3,{scope:e.__scopeMenu,checked:i},f.createElement(tb,Y({role:"menuitemradio","aria-checked":i},r,{ref:t,"data-state":nb(i),onSelect:ue(r.onSelect,()=>{var s;return(s=o.onValueChange)===null||s===void 0?void 0:s.call(o,n)},{checkForDefaultPrevented:!1})})))}),q3="MenuItemIndicator",[Q3,yQ]=Na(q3,{checked:!1}),wQ=f.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...o}=e,i=yQ(q3,n);return f.createElement(xn,{present:r||om(i.checked)||i.checked===!0},f.createElement(Pe.span,Y({},o,{ref:t,"data-state":nb(i.checked)})))}),xQ=f.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return f.createElement(Pe.div,Y({role:"separator","aria-orientation":"horizontal"},r,{ref:t}))}),J3="MenuSub",[bQ,eA]=Na(J3),_Q=e=>{const{__scopeMenu:t,children:n,open:r=!1,onOpenChange:o}=e,i=Fs(J3,t),s=pg(t),[l,u]=f.useState(null),[d,h]=f.useState(null),m=Ft(o);return f.useEffect(()=>(i.open===!1&&m(!1),()=>m(!1)),[i.open,m]),f.createElement(Od,s,f.createElement(K3,{scope:t,open:r,onOpenChange:m,content:d,onContentChange:h},f.createElement(bQ,{scope:t,contentId:nr(),triggerId:nr(),trigger:l,onTriggerChange:u},n)))},gp="MenuSubTrigger",SQ=f.forwardRef((e,t)=>{const n=Fs(gp,e.__scopeMenu),r=Hd(gp,e.__scopeMenu),o=eA(gp,e.__scopeMenu),i=Jx(gp,e.__scopeMenu),s=f.useRef(null),{pointerGraceTimerRef:l,onPointerGraceIntentChange:u}=i,d={__scopeMenu:e.__scopeMenu},h=f.useCallback(()=>{s.current&&window.clearTimeout(s.current),s.current=null},[]);return f.useEffect(()=>h,[h]),f.useEffect(()=>{const m=l.current;return()=>{window.clearTimeout(m),u(null)}},[l,u]),f.createElement(Y3,Y({asChild:!0},d),f.createElement(Z3,Y({id:o.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":o.contentId,"data-state":tA(n.open)},e,{ref:Am(t,o.onTriggerChange),onClick:m=>{var g;(g=e.onClick)===null||g===void 0||g.call(e,m),!(e.disabled||m.defaultPrevented)&&(m.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:ue(e.onPointerMove,cd(m=>{i.onItemEnter(m),!m.defaultPrevented&&!e.disabled&&!n.open&&!s.current&&(i.onPointerGraceIntentChange(null),s.current=window.setTimeout(()=>{n.onOpenChange(!0),h()},100))})),onPointerLeave:ue(e.onPointerLeave,cd(m=>{var g;h();const y=(g=n.content)===null||g===void 0?void 0:g.getBoundingClientRect();if(y){var x;const _=(x=n.content)===null||x===void 0?void 0:x.dataset.side,C=_==="right",S=C?-5:5,b=y[C?"left":"right"],E=y[C?"right":"left"];i.onPointerGraceIntentChange({area:[{x:m.clientX+S,y:m.clientY},{x:b,y:y.top},{x:E,y:y.top},{x:E,y:y.bottom},{x:b,y:y.bottom}],side:_}),window.clearTimeout(l.current),l.current=window.setTimeout(()=>i.onPointerGraceIntentChange(null),300)}else{if(i.onTriggerLeave(m),m.defaultPrevented)return;i.onPointerGraceIntentChange(null)}})),onKeyDown:ue(e.onKeyDown,m=>{const g=i.searchRef.current!=="";if(!(e.disabled||g&&m.key===" ")&&eQ[r.dir].includes(m.key)){var y;n.onOpenChange(!0),(y=n.content)===null||y===void 0||y.focus(),m.preventDefault()}})})))}),EQ="MenuSubContent",CQ=f.forwardRef((e,t)=>{const n=X3(yo,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,i=Fs(yo,e.__scopeMenu),s=Hd(yo,e.__scopeMenu),l=eA(EQ,e.__scopeMenu),u=f.useRef(null),d=Be(t,u);return f.createElement(ld.Provider,{scope:e.__scopeMenu},f.createElement(xn,{present:r||i.open},f.createElement(ld.Slot,{scope:e.__scopeMenu},f.createElement(eb,Y({id:l.contentId,"aria-labelledby":l.triggerId},o,{ref:d,align:"start",side:s.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:h=>{var m;s.isUsingKeyboardRef.current&&((m=u.current)===null||m===void 0||m.focus()),h.preventDefault()},onCloseAutoFocus:h=>h.preventDefault(),onFocusOutside:ue(e.onFocusOutside,h=>{h.target!==l.trigger&&i.onOpenChange(!1)}),onEscapeKeyDown:ue(e.onEscapeKeyDown,h=>{s.onClose(),h.preventDefault()}),onKeyDown:ue(e.onKeyDown,h=>{const m=h.currentTarget.contains(h.target),g=tQ[s.dir].includes(h.key);if(m&&g){var y;i.onOpenChange(!1),(y=l.trigger)===null||y===void 0||y.focus(),h.preventDefault()}})})))))});function tA(e){return e?"open":"closed"}function om(e){return e==="indeterminate"}function nb(e){return om(e)?"indeterminate":e?"checked":"unchecked"}function $Q(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function kQ(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function RQ(e,t,n){const o=t.length>1&&Array.from(t).every(d=>d===t[0])?t[0]:t,i=n?e.indexOf(n):-1;let s=kQ(e,Math.max(i,0));o.length===1&&(s=s.filter(d=>d!==n));const u=s.find(d=>d.toLowerCase().startsWith(o.toLowerCase()));return u!==n?u:void 0}function TQ(e,t){const{x:n,y:r}=e;let o=!1;for(let i=0,s=t.length-1;ir!=h>r&&n<(d-l)*(r-u)/(h-u)+l&&(o=!o)}return o}function PQ(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return TQ(n,t)}function cd(e){return t=>t.pointerType==="mouse"?e(t):void 0}const AQ=iQ,OQ=Y3,MQ=aQ,NQ=cQ,DQ=fQ,IQ=tb,LQ=pQ,FQ=vQ,jQ=wQ,zQ=xQ,BQ=_Q,UQ=SQ,VQ=CQ,nA="DropdownMenu",[WQ,kte]=An(nA,[W3]),Sr=W3(),[HQ,rA]=WQ(nA),KQ=e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:o,defaultOpen:i,onOpenChange:s,modal:l=!0}=e,u=Sr(t),d=f.useRef(null),[h=!1,m]=Zr({prop:o,defaultProp:i,onChange:s});return f.createElement(HQ,{scope:t,triggerId:nr(),triggerRef:d,contentId:nr(),open:h,onOpenChange:m,onOpenToggle:f.useCallback(()=>m(g=>!g),[m]),modal:l},f.createElement(AQ,Y({},u,{open:h,onOpenChange:m,dir:r,modal:l}),n))},YQ="DropdownMenuTrigger",GQ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...o}=e,i=rA(YQ,n),s=Sr(n);return f.createElement(OQ,Y({asChild:!0},s),f.createElement(Pe.button,Y({type:"button",id:i.triggerId,"aria-haspopup":"menu","aria-expanded":i.open,"aria-controls":i.open?i.contentId:void 0,"data-state":i.open?"open":"closed","data-disabled":r?"":void 0,disabled:r},o,{ref:Am(t,i.triggerRef),onPointerDown:ue(e.onPointerDown,l=>{!r&&l.button===0&&l.ctrlKey===!1&&(i.onOpenToggle(),i.open||l.preventDefault())}),onKeyDown:ue(e.onKeyDown,l=>{r||(["Enter"," "].includes(l.key)&&i.onOpenToggle(),l.key==="ArrowDown"&&i.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(l.key)&&l.preventDefault())})})))}),XQ=e=>{const{__scopeDropdownMenu:t,...n}=e,r=Sr(t);return f.createElement(MQ,Y({},r,n))},ZQ="DropdownMenuContent",qQ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=rA(ZQ,n),i=Sr(n),s=f.useRef(!1);return f.createElement(NQ,Y({id:o.contentId,"aria-labelledby":o.triggerId},i,r,{ref:t,onCloseAutoFocus:ue(e.onCloseAutoFocus,l=>{var u;s.current||(u=o.triggerRef.current)===null||u===void 0||u.focus(),s.current=!1,l.preventDefault()}),onInteractOutside:ue(e.onInteractOutside,l=>{const u=l.detail.originalEvent,d=u.button===0&&u.ctrlKey===!0,h=u.button===2||d;(!o.modal||h)&&(s.current=!0)}),style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}}))}),QQ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(DQ,Y({},o,r,{ref:t}))}),JQ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(IQ,Y({},o,r,{ref:t}))}),eJ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(LQ,Y({},o,r,{ref:t}))}),tJ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(FQ,Y({},o,r,{ref:t}))}),nJ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(jQ,Y({},o,r,{ref:t}))}),rJ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(zQ,Y({},o,r,{ref:t}))}),oJ=e=>{const{__scopeDropdownMenu:t,children:n,open:r,onOpenChange:o,defaultOpen:i}=e,s=Sr(t),[l=!1,u]=Zr({prop:r,defaultProp:i,onChange:o});return f.createElement(BQ,Y({},s,{open:l,onOpenChange:u}),n)},iJ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(UQ,Y({},o,r,{ref:t}))}),sJ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(VQ,Y({},o,r,{ref:t,style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}}))}),aJ=KQ,lJ=GQ,cJ=XQ,oA=qQ,iA=QQ,sA=JQ,aA=eJ,lA=tJ,cA=nJ,uA=rJ,uJ=oJ,dA=iJ,fA=sJ,dJ=aJ,fJ=lJ,K2=uJ,V1=f.forwardRef(({className:e,inset:t,children:n,...r},o)=>v.jsxs(dA,{ref:o,className:Ce("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",e),...r,children:[n,v.jsx(Jj,{className:"ml-auto h-4 w-4"})]}));V1.displayName=dA.displayName;const W1=f.forwardRef(({className:e,...t},n)=>v.jsx(fA,{ref:n,className:Ce("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...t}));W1.displayName=fA.displayName;const pA=f.forwardRef(({className:e,sideOffset:t=4,...n},r)=>v.jsx(cJ,{children:v.jsx(oA,{ref:r,sideOffset:t,className:Ce("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md","data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),onCloseAutoFocus:o=>o.preventDefault(),...n})}));pA.displayName=oA.displayName;const il=f.forwardRef(({className:e,inset:t,...n},r)=>v.jsx(sA,{ref:r,className:Ce("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",e),...n}));il.displayName=sA.displayName;const pJ=f.forwardRef(({className:e,children:t,checked:n,...r},o)=>v.jsxs(aA,{ref:o,className:Ce("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),checked:n,...r,children:[v.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:v.jsx(cA,{children:v.jsx(vT,{className:"h-4 w-4"})})}),t]}));pJ.displayName=aA.displayName;const hJ=f.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(lA,{ref:r,className:Ce("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[v.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:v.jsx(cA,{children:v.jsx(oz,{className:"h-4 w-4 fill-current"})})}),t]}));hJ.displayName=lA.displayName;const mJ=f.forwardRef(({className:e,inset:t,...n},r)=>v.jsx(iA,{ref:r,className:Ce("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",e),...n}));mJ.displayName=iA.displayName;const gJ=f.forwardRef(({className:e,...t},n)=>v.jsx(uA,{ref:n,className:Ce("-mx-1 my-1 h-px bg-muted",e),...t}));gJ.displayName=uA.displayName;const Y2={RemoveBG:{IconClass:VC,showName:"RemoveBG"},AnimeSeg:{IconClass:VC,showName:"Anime Segmentation"},RealESRGAN:{IconClass:XT,showName:"RealESRGAN"},GFPGAN:{IconClass:WC,showName:"GFPGAN"},RestoreFormer:{IconClass:WC,showName:"RestoreFormer"},InteractiveSeg:{IconClass:nV,showName:"Interactive Segmentation"}},vJ=()=>{const[e,t,n,r]=bt(d=>[d.file,d.serverConfig.plugins,d.updateInteractiveSegState,d.runRenderablePlugin]),o=!e;if(t.length===0)return null;const i=(d,h)=>{h==="InteractiveSeg"?n({isInteractiveSeg:!0}):r(d,h)},s=()=>v.jsxs(K2,{children:[v.jsx(V1,{disabled:o,children:v.jsxs("div",{className:"flex gap-2 items-center",children:[v.jsx(XT,{}),"RealESRGAN"]})}),v.jsxs(W1,{children:[v.jsx(il,{onClick:()=>r(!1,"RealESRGAN",{upscale:2}),children:"upscale 2x"}),v.jsx(il,{onClick:()=>r(!1,"RealESRGAN",{upscale:4}),children:"upscale 4x"})]})]},"RealESRGAN"),l=d=>{const{IconClass:h,showName:m}=Y2[d.name];return v.jsxs(K2,{children:[v.jsx(V1,{disabled:o,children:v.jsxs("div",{className:"flex gap-2 items-center",children:[v.jsx(h,{className:"p-1"}),m]})}),v.jsxs(W1,{children:[v.jsx(il,{onClick:()=>i(!1,d.name),children:"Remove Background"}),v.jsx(il,{onClick:()=>i(!0,d.name),children:"Generate Mask"})]})]},d.name)},u=()=>t.map(d=>{const{IconClass:h,showName:m}=Y2[d.name];return d.name==="RealESRGAN"?s():d.name==="RemoveBG"||d.name==="AnimeSeg"?l(d):v.jsx(il,{onClick:()=>i(!1,d.name),disabled:o,children:v.jsxs("div",{className:"flex gap-2 items-center",children:[v.jsx(h,{className:"p-1"}),m]})},d.name)});return v.jsxs(dJ,{modal:!1,children:[v.jsx(fJ,{className:"border rounded-lg z-10 bg-background outline-none",tabIndex:-1,children:v.jsx(Rn,{variant:"ghost",size:"icon",asChild:!0,className:"p-1.5",children:v.jsx(WU,{strokeWidth:1})})}),v.jsx(pA,{side:"bottom",align:"start",children:u()})]})},yJ=Sx,wJ=gP,xJ=Ex,hA=f.forwardRef(({className:e,...t},n)=>v.jsx(Nd,{className:Ce("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t,ref:n}));hA.displayName=Nd.displayName;const bJ=Om("fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=closed]:duration-200 data-[state=open]:duration-300",{variants:{side:{top:"inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",bottom:"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",left:"inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",right:"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm"}},defaultVariants:{side:"right"}}),mA=f.forwardRef(({side:e="right",className:t,children:n,...r},o)=>v.jsxs(xJ,{children:[v.jsx(hA,{}),v.jsx(Dd,{ref:o,className:Ce(bJ({side:e}),t),...r,children:n})]}));mA.displayName=Dd.displayName;const gA=({className:e,...t})=>v.jsx("div",{className:Ce("flex flex-col space-y-2 text-center sm:text-left",e),...t});gA.displayName="SheetHeader";const _J=f.forwardRef(({className:e,...t},n)=>v.jsx(Id,{ref:n,className:Ce("text-lg font-semibold text-foreground",e),...t}));_J.displayName=Id.displayName;const SJ=f.forwardRef(({className:e,...t},n)=>v.jsx(Ld,{ref:n,className:Ce("text-sm text-muted-foreground",e),...t}));SJ.displayName=Ld.displayName;const Ut=({children:e})=>v.jsx("div",{className:"flex justify-between items-center pr-2",children:e}),Pt=({text:e,toolTip:t="",url:n,htmlFor:r,disabled:o=!1})=>v.jsxs(YT,{children:[v.jsx(GT,{asChild:!0,children:v.jsx(Gx,{htmlFor:r||e.toLowerCase().replace(" ","-"),className:"font-medium",disabled:o,children:e})}),t||n?v.jsxs(xx,{className:"flex flex-col max-w-xs text-sm",side:"left",children:[v.jsx("p",{children:t}),n?v.jsx(Rn,{variant:"link",className:"justify-end",children:v.jsx("a",{href:n,target:"_blank",children:"More info"})}):v.jsx(v.Fragment,{})]}):v.jsx(v.Fragment,{})]}),EJ=()=>{const[e,t]=bt(n=>[n.settings,n.updateSettings]);return v.jsxs("div",{className:"flex flex-col gap-4 mt-4",children:[v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{htmlFor:"steps",text:"Steps",toolTip:"The number of denoising steps. More denoising steps usually lead to a higher quality image at the expense of slower inference."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[30],min:1,max:100,step:1,value:[Math.floor(e.ldmSteps)],onValueChange:n=>t({ldmSteps:n[0]})}),v.jsx(Gn,{id:"steps",className:"w-[60px] rounded-full",numberValue:e.ldmSteps,allowFloat:!1,onNumberValueChange:n=>{t({ldmSteps:n})}})]})]}),v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Sampler"}),v.jsxs(aa,{value:e.ldmSampler,onValueChange:n=>{t({ldmSampler:n})},children:[v.jsx(ls,{className:"w-[100px]",children:v.jsx(la,{placeholder:"Select sampler"})}),v.jsx(cs,{align:"end",children:v.jsx(wl,{children:Object.values(Zw).map(n=>v.jsx(us,{value:n,children:n},n))})})]})]})]})},vA=f.forwardRef(({className:e,...t},n)=>v.jsx("textarea",{className:Ce("flex min-h-[60px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",e,"overflow-auto"),tabIndex:-1,ref:n,...t}));vA.displayName="Textarea";const vp=({text:e,onClick:t})=>{const[n]=bt(r=>[r.settings.showExtender]);return v.jsx(Rn,{variant:"outline",className:"p-1 h-8",disabled:!n,onClick:t,children:v.jsx("div",{className:"flex items-center gap-1",children:e})})},CJ=()=>{const[e,t,n,r,o,i,s,l,u,d,h]=bt(L=>[L.serverConfig.samplers,L.settings,L.paintByExampleFile,L.getIsProcessing(),L.updateSettings,L.runInpainting,L.updateAppState,L.updateExtenderByBuiltIn,L.updateExtenderDirection,L.adjustMask,L.clearMask]),[m,g]=Rx(n),y=f.useRef(null);OP(y,()=>{y!=null&&y.current&&y.current.blur()});const x=L=>{L.key==="Enter"&&L.ctrlKey&&t.prompt.length!==0&&i()},_=()=>v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Cropper",toolTip:"Inpainting on part of image, improve inference speed and reduce memory usage."}),v.jsx(co,{id:"cropper",checked:t.showCropper,onCheckedChange:L=>{o({showCropper:L}),L&&o({showExtender:!1})}})]}),C=()=>t.model.support_controlnet?v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex justify-between items-center pr-2",children:[v.jsx(Pt,{text:"ControlNet",toolTip:"Using an additional conditioning image to control how an image is generated",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#controlnet"}),v.jsx(co,{id:"controlnet",checked:t.enableControlnet,onCheckedChange:L=>{o({enableControlnet:L})}})]}),v.jsx("div",{className:"flex flex-col gap-1",children:v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[100],min:1,max:100,step:1,disabled:!t.enableControlnet,value:[Math.floor(t.controlnetConditioningScale*100)],onValueChange:L=>o({controlnetConditioningScale:L[0]/100})}),v.jsx(Gn,{id:"controlnet-weight",className:"w-[60px] rounded-full",disabled:!t.enableControlnet,numberValue:t.controlnetConditioningScale,allowFloat:!1,onNumberValueChange:L=>{o({controlnetConditioningScale:L})}})]})}),v.jsx("div",{className:"pr-2",children:v.jsxs(aa,{defaultValue:t.controlnetMethod,value:t.controlnetMethod,onValueChange:L=>{o({controlnetMethod:L})},disabled:!t.enableControlnet,children:[v.jsx(ls,{children:v.jsx(la,{placeholder:"Select control method"})}),v.jsx(cs,{align:"end",children:v.jsx(wl,{children:Object.values(t.model.controlnets).map(L=>v.jsx(us,{value:L,children:L.split("/")[1]},L))})})]})})]}),v.jsx(Fn,{})]}):null,S=()=>t.model.support_lcm_lora?v.jsxs(v.Fragment,{children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"LCM Lora",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inference_with_lcm_lora",toolTip:"Enable quality image generation in typically 2-4 steps. Suggest disabling guidance_scale by setting it to 0. You can also try values between 1.0 and 2.0. When LCM Lora is enabled, LCMSampler will be used automatically."}),v.jsx(co,{id:"lcm-lora",checked:t.enableLCMLora,onCheckedChange:L=>{o({enableLCMLora:L})}})]}),v.jsx(Fn,{})]}):null,b=()=>t.model.support_freeu?v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex justify-between items-center pr-2",children:[v.jsx(Pt,{text:"FreeU",toolTip:"FreeU is a technique for improving image quality. Different models may require different FreeU-specific hyperparameters, which can be viewed in the more info section.",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/freeu"}),v.jsx(co,{id:"freeu",checked:t.enableFreeu,onCheckedChange:L=>{o({enableFreeu:L})}})]}),v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex justify-center gap-6",children:[v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-s1",text:"s1",disabled:!t.enableFreeu}),v.jsx(Gn,{id:"freeu-s1",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.s1,allowFloat:!0,onNumberValueChange:L=>{o({freeuConfig:{...t.freeuConfig,s1:L}})}})]}),v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-s2",text:"s2",disabled:!t.enableFreeu}),v.jsx(Gn,{id:"freeu-s2",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.s2,allowFloat:!0,onNumberValueChange:L=>{o({freeuConfig:{...t.freeuConfig,s2:L}})}})]})]}),v.jsxs("div",{className:"flex justify-center gap-6",children:[v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-b1",text:"b1",disabled:!t.enableFreeu}),v.jsx(Gn,{id:"freeu-b1",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.b1,allowFloat:!0,onNumberValueChange:L=>{o({freeuConfig:{...t.freeuConfig,b1:L}})}})]}),v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-b2",text:"b2",disabled:!t.enableFreeu}),v.jsx(Gn,{id:"freeu-b2",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.b2,allowFloat:!0,onNumberValueChange:L=>{o({freeuConfig:{...t.freeuConfig,b2:L}})}})]})]})]}),v.jsx(Fn,{})]}):null,E=()=>t.model.need_prompt?v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsx(Pt,{text:"Negative prompt",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#negative-prompt",toolTip:"Negative prompt guides the model away from generating certain things in an image"}),v.jsx("div",{className:"pl-2 pr-4",children:v.jsx(vA,{ref:y,rows:4,onKeyUp:x,className:"max-h-[8rem] overflow-y-auto mb-2",placeholder:"",id:"negative-prompt",value:t.negativePrompt,onInput:L=>{L.preventDefault(),L.stopPropagation();const ie=L.target;o({negativePrompt:ie.value})}})})]}):null,k=()=>t.model.name!==YR?null:v.jsxs("div",{children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Example Image",toolTip:"An example image to guide image generation."}),v.jsx(c1,{tooltip:"Upload example image",onFileUpload:L=>{s({paintByExampleFile:L})},children:v.jsx(ZT,{})})]}),g?v.jsx("div",{className:"flex justify-center items-center",children:v.jsx("img",{src:m.src,alt:"example",className:"max-w-[200px] max-h-[200px] m-3"})}):v.jsx(v.Fragment,{}),v.jsx(Rn,{variant:"default",className:"w-full",disabled:r||!g,onClick:()=>{i()},children:"Paint"})]}),P=()=>t.model.name!==aF?null:v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Image guidance scale",toolTip:"Push the generated image towards the inital image. Higher image guidance scale encourages generated images that are closely linked to the source image, usually at the expense of lower image quality.",url:"https://huggingface.co/docs/diffusers/main/en/api/pipelines/pix2pix"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[150],min:100,max:1e3,step:1,value:[Math.floor(t.p2pImageGuidanceScale*100)],onValueChange:L=>o({p2pImageGuidanceScale:L[0]/100})}),v.jsx(Gn,{id:"image-guidance-scale",className:"w-[60px] rounded-full",numberValue:t.p2pImageGuidanceScale,allowFloat:!0,onNumberValueChange:L=>{o({p2pImageGuidanceScale:L})}})]})]}),M=()=>t.model.support_strength?v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Strength",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#strength",toolTip:"Strength is a measure of how much noise is added to the base image, which influences how similar the output is to the base image. Higher value means more noise and more different from the base image"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[100],min:10,max:100,step:1,value:[Math.floor(t.sdStrength*100)],onValueChange:L=>o({sdStrength:L[0]/100})}),v.jsx(Gn,{id:"strength",className:"w-[60px] rounded-full",numberValue:t.sdStrength,allowFloat:!0,onNumberValueChange:L=>{o({sdStrength:L})}})]})]}):null,A=()=>t.model.support_outpainting?v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Extender",toolTip:"Perform outpainting on images to expand it's content."}),v.jsx(co,{id:"extender",checked:t.showExtender,onCheckedChange:L=>{o({showExtender:L}),L&&o({showCropper:!1})}})]}),v.jsxs(Ut,{children:[v.jsxs(aa,{defaultValue:t.extenderDirection,value:t.extenderDirection,onValueChange:L=>{u(L)},children:[v.jsx(ls,{className:"w-[65px] h-7",disabled:!t.showExtender,children:v.jsx(la,{placeholder:"Select axis"})}),v.jsx(cs,{align:"end",children:v.jsx(wl,{children:Object.values(In).map(L=>v.jsx(us,{value:L,children:L},L))})})]}),v.jsxs("div",{className:"flex gap-1 justify-center mt-0",children:[v.jsx(vp,{text:"1.25x",onClick:()=>l(t.extenderDirection,1.25)}),v.jsx(vp,{text:"1.5x",onClick:()=>l(t.extenderDirection,1.5)}),v.jsx(vp,{text:"1.75x",onClick:()=>l(t.extenderDirection,1.75)}),v.jsx(vp,{text:"2.0x",onClick:()=>l(t.extenderDirection,2)})]})]})]}),v.jsx(Fn,{})]}):null,O=()=>t.model.name!==lF?null:v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Task",toolTip:"PowerPaint task. When using extender, image-outpainting task will be auto used. For object-removal and image-outpainting, it is recommended to set the guidance_scale at 10 or above."}),v.jsxs(aa,{defaultValue:t.powerpaintTask,value:t.powerpaintTask,onValueChange:L=>{o({powerpaintTask:L})},disabled:t.showExtender,children:[v.jsx(ls,{className:"w-[140px]",children:v.jsx(la,{placeholder:"Select task"})}),v.jsx(cs,{align:"end",children:v.jsx(wl,{children:[kl.text_guided,kl.object_remove,kl.shape_guided].map(L=>v.jsx(us,{value:L,children:L},L))})})]})]}),F=()=>v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{htmlFor:"steps",text:"Steps",toolTip:"The number of denoising steps. More denoising steps usually lead to a higher quality image at the expense of slower inference."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[30],min:1,max:100,step:1,value:[Math.floor(t.sdSteps)],onValueChange:L=>o({sdSteps:L[0]})}),v.jsx(Gn,{id:"steps",className:"w-[60px] rounded-full",numberValue:t.sdSteps,allowFloat:!1,onNumberValueChange:L=>{o({sdSteps:L})}})]})]}),V=()=>v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Guidance scale",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#guidance-scale",toolTip:"Guidance scale affects how aligned the text prompt and generated image are. Higher value means the prompt and generated image are closely aligned, so the output is a stricter interpretation of the prompt"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[750],min:0,max:1500,step:1,value:[Math.floor(t.sdGuidanceScale*100)],onValueChange:L=>o({sdGuidanceScale:L[0]/100})}),v.jsx(Gn,{id:"guidance-scale",className:"w-[60px] rounded-full",numberValue:t.sdGuidanceScale,allowFloat:!0,onNumberValueChange:L=>{o({sdGuidanceScale:L})}})]})]}),J=()=>v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Sampler"}),v.jsxs(aa,{defaultValue:t.sdSampler,value:t.sdSampler,onValueChange:L=>{o({sdSampler:L})},children:[v.jsx(ls,{className:"w-[175px] text-xs",children:v.jsx(la,{placeholder:"Select sampler"})}),v.jsx(cs,{align:"end",children:v.jsx(wl,{children:e.map(L=>v.jsx(us,{value:L,className:"text-xs",children:L},L))})})]})]}),G=()=>v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Seed",toolTip:"Using same parameters and a fixed seed can generate same result image."}),v.jsxs("div",{className:"flex gap-2 justify-center items-center",children:[v.jsx(co,{id:"seed",checked:t.seedFixed,onCheckedChange:L=>{o({seedFixed:L})}}),v.jsx(Gn,{id:"seed",className:"w-[100px]",disabled:!t.seedFixed,numberValue:t.seed,allowFloat:!1,onNumberValueChange:L=>{o({seed:L})}})]})]}),ae=()=>v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Mask blur",toolTip:"How much to blur the mask before processing, in pixels."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[t.sdMaskBlur],min:0,max:96,step:1,value:[Math.floor(t.sdMaskBlur)],onValueChange:L=>o({sdMaskBlur:L[0]})}),v.jsx(Gn,{id:"mask-blur",className:"w-[60px] rounded-full",numberValue:t.sdMaskBlur,allowFloat:!1,onNumberValueChange:L=>{o({sdMaskBlur:L})}})]})]}),U=()=>v.jsxs(v.Fragment,{children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Match histograms",toolTip:"Match the inpainting result histogram to the source image histogram",url:"https://github.com/Sanster/lama-cleaner/pull/143#issuecomment-1325859307"}),v.jsx(co,{id:"match-histograms",checked:t.sdMatchHistograms,onCheckedChange:L=>{o({sdMatchHistograms:L})}})]}),v.jsx(Fn,{})]}),te=()=>v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{htmlFor:"adjustMaskKernelSize",text:"Adjust Mask",toolTip:"Expand or shrink mask. Using the slider to adjust the kernel size for dilation or erosion."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[12],min:1,max:100,step:1,value:[Math.floor(t.adjustMaskKernelSize)],onValueChange:L=>o({adjustMaskKernelSize:L[0]})}),v.jsx(Gn,{id:"adjustMaskKernelSize",className:"w-[60px] rounded-full",numberValue:t.adjustMaskKernelSize,allowFloat:!1,onNumberValueChange:L=>{o({adjustMaskKernelSize:L})}})]}),v.jsxs(Ut,{children:[v.jsxs("div",{className:"flex gap-1 justify-start",children:[v.jsx(Rn,{variant:"outline",className:"p-1 h-8",onClick:()=>d("expand"),disabled:r,children:v.jsxs("div",{className:"flex items-center gap-1 select-none",children:[v.jsx(rV,{size:16}),"expand"]})}),v.jsx(Rn,{variant:"outline",className:"p-1 h-8",onClick:()=>d("shrink"),disabled:r,children:v.jsxs("div",{className:"flex items-center gap-1 select-none",children:[v.jsx(tV,{size:16}),"Shrink"]})})]}),v.jsx(Rn,{variant:"outline",className:"p-1 h-8 justify-self-end",onClick:h,disabled:r,children:v.jsx("div",{className:"flex items-center gap-1 select-none",children:"Clear"})})]})]}),v.jsx(Fn,{})]});return v.jsxs("div",{className:"flex flex-col gap-4 mt-4",children:[_(),A(),te(),O(),F(),V(),P(),M(),J(),G(),E(),v.jsx(Fn,{}),C(),S(),ae(),U(),b(),k()]})},$J=()=>{const[e,t]=bt(n=>[n.settings,n.updateSettings]);return v.jsxs("div",{className:"flex flex-col gap-4 mt-4",children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"CV2 Flag",url:"https://docs.opencv.org/4.8.0/d7/d8b/group__photo__inpaint.html#gga8002a65f5a3328fbf15df81b842d3c3ca892824c38e258feb5e72f308a358d52e"}),v.jsxs(aa,{value:e.cv2Flag,onValueChange:n=>{t({cv2Flag:n})},children:[v.jsx(ls,{className:"w-[160px]",children:v.jsx(la,{placeholder:"Select flag"})}),v.jsx(cs,{align:"end",children:v.jsx(wl,{children:Object.values(qw).map(n=>v.jsx(us,{value:n,children:n},n))})})]})]}),v.jsx(Pt,{text:"CV2 Radius",url:"https://docs.opencv.org/4.8.0/d7/d8b/group__photo__inpaint.html#gga8002a65f5a3328fbf15df81b842d3c3ca892824c38e258feb5e72f308a358d52e"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[5],min:1,max:100,step:1,value:[Math.floor(e.cv2Radius)],onValueChange:n=>t({cv2Radius:n[0]})}),v.jsx(Gn,{id:"cv2-radius",className:"w-[60px] rounded-full",numberValue:e.cv2Radius,allowFloat:!1,onNumberValueChange:n=>{t({cv2Radius:n})}})]})]})},kJ=()=>{const[e,t]=bt(i=>[i.settings,i.windowSize]),[n,r]=AP(!0);if(Zn("c",()=>{r()}),e.model.name!==oC&&e.model.name!==iC&&e.model.model_type===is)return null;const o=()=>e.model.name===oC?v.jsx(EJ,{}):e.model.name===iC?v.jsx($J,{}):v.jsx(CJ,{});return v.jsxs(yJ,{open:n,modal:!1,children:[v.jsx(wJ,{tabIndex:-1,className:"z-10 outline-none absolute top-[68px] right-6 rounded-lg border bg-background",children:v.jsx(Rn,{variant:"ghost",size:"icon",asChild:!0,className:"p-1.5",onClick:r,children:v.jsx(HU,{strokeWidth:1})})}),v.jsxs(mA,{side:"right",className:"w-[300px] mt-[60px] outline-none pl-4 pr-1",onOpenAutoFocus:i=>i.preventDefault(),onPointerDownOutside:i=>i.preventDefault(),children:[v.jsxs(gA,{children:[v.jsxs(Ut,{children:[v.jsx("div",{className:"overflow-hidden mr-8",children:e.model.name.split("/")[e.model.name.split("/").length-1]}),v.jsx(Rn,{variant:"ghost",size:"icon",className:"border h-6 w-6",onClick:r,children:v.jsx(KU,{strokeWidth:1})})]}),v.jsx(Fn,{})]}),v.jsx(og,{style:{height:t.height-160},className:"pr-3",children:o()})]})]})},Yo=Object.create(null);Yo.open="0";Yo.close="1";Yo.ping="2";Yo.pong="3";Yo.message="4";Yo.upgrade="5";Yo.noop="6";const th=Object.create(null);Object.keys(Yo).forEach(e=>{th[Yo[e]]=e});const H1={type:"error",data:"parser error"},yA=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",wA=typeof ArrayBuffer=="function",xA=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,rb=({type:e,data:t},n,r)=>yA&&t instanceof Blob?n?r(t):G2(t,r):wA&&(t instanceof ArrayBuffer||xA(t))?n?r(t):G2(new Blob([t]),r):r(Yo[e]+(t||"")),G2=(e,t)=>{const n=new FileReader;return n.onload=function(){const r=n.result.split(",")[1];t("b"+(r||""))},n.readAsDataURL(e)};function X2(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let L0;function RJ(e,t){if(yA&&e.data instanceof Blob)return e.data.arrayBuffer().then(X2).then(t);if(wA&&(e.data instanceof ArrayBuffer||xA(e.data)))return t(X2(e.data));rb(e,!1,n=>{L0||(L0=new TextEncoder),t(L0.encode(n))})}const Z2="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",gu=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let e=0;e{let t=e.length*.75,n=e.length,r,o=0,i,s,l,u;e[e.length-1]==="="&&(t--,e[e.length-2]==="="&&t--);const d=new ArrayBuffer(t),h=new Uint8Array(d);for(r=0;r>4,h[o++]=(s&15)<<4|l>>2,h[o++]=(l&3)<<6|u&63;return d},PJ=typeof ArrayBuffer=="function",ob=(e,t)=>{if(typeof e!="string")return{type:"message",data:bA(e,t)};const n=e.charAt(0);return n==="b"?{type:"message",data:AJ(e.substring(1),t)}:th[n]?e.length>1?{type:th[n],data:e.substring(1)}:{type:th[n]}:H1},AJ=(e,t)=>{if(PJ){const n=TJ(e);return bA(n,t)}else return{base64:!0,data:e}},bA=(e,t)=>{switch(t){case"blob":return e instanceof Blob?e:new Blob([e]);case"arraybuffer":default:return e instanceof ArrayBuffer?e:e.buffer}},_A="",OJ=(e,t)=>{const n=e.length,r=new Array(n);let o=0;e.forEach((i,s)=>{rb(i,!1,l=>{r[s]=l,++o===n&&t(r.join(_A))})})},MJ=(e,t)=>{const n=e.split(_A),r=[];for(let o=0;o{const r=n.length;let o;if(r<126)o=new Uint8Array(1),new DataView(o.buffer).setUint8(0,r);else if(r<65536){o=new Uint8Array(3);const i=new DataView(o.buffer);i.setUint8(0,126),i.setUint16(1,r)}else{o=new Uint8Array(9);const i=new DataView(o.buffer);i.setUint8(0,127),i.setBigUint64(1,BigInt(r))}e.data&&typeof e.data!="string"&&(o[0]|=128),t.enqueue(o),t.enqueue(n)})}})}let F0;function yp(e){return e.reduce((t,n)=>t+n.length,0)}function wp(e,t){if(e[0].length===t)return e.shift();const n=new Uint8Array(t);let r=0;for(let o=0;oMath.pow(2,21)-1){l.enqueue(H1);break}o=h*Math.pow(2,32)+d.getUint32(4),r=3}else{if(yp(n)e){l.enqueue(H1);break}}}})}const SA=4;function Qt(e){if(e)return IJ(e)}function IJ(e){for(var t in Qt.prototype)e[t]=Qt.prototype[t];return e}Qt.prototype.on=Qt.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this};Qt.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this};Qt.prototype.off=Qt.prototype.removeListener=Qt.prototype.removeAllListeners=Qt.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,o=0;o(e.hasOwnProperty(r)&&(n[r]=e[r]),n),{})}const LJ=Br.setTimeout,FJ=Br.clearTimeout;function hg(e,t){t.useNativeTimers?(e.setTimeoutFn=LJ.bind(Br),e.clearTimeoutFn=FJ.bind(Br)):(e.setTimeoutFn=Br.setTimeout.bind(Br),e.clearTimeoutFn=Br.clearTimeout.bind(Br))}const jJ=1.33;function zJ(e){return typeof e=="string"?BJ(e):Math.ceil((e.byteLength||e.size)*jJ)}function BJ(e){let t=0,n=0;for(let r=0,o=e.length;r=57344?n+=3:(r++,n+=4);return n}function UJ(e){let t="";for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+="&"),t+=encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t}function VJ(e){let t={},n=e.split("&");for(let r=0,o=n.length;r0);return t}function $A(){const e=J2(+new Date);return e!==Q2?(q2=0,Q2=e):e+"."+J2(q2++)}for(;xp{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)};MJ(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,OJ(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]=$A()),!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 Vo(this.uri(),t)}doWrite(t,n){const r=this.request({method:"POST",data:t});r.on("success",n),r.on("error",(o,i)=>{this.onError("xhr post error",o,i)})}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}}class Vo extends Qt{constructor(t,n){super(),hg(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=EA(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");n.xdomain=!!this.opts.xd;const r=this.xhr=new RA(n);try{r.open(this.method,this.uri,!0);try{if(this.opts.extraHeaders){r.setDisableHeaderCheck&&r.setDisableHeaderCheck(!0);for(let o in this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(o)&&r.setRequestHeader(o,this.opts.extraHeaders[o])}}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 o;r.readyState===3&&((o=this.opts.cookieJar)===null||o===void 0||o.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(o){this.setTimeoutFn(()=>{this.onError(o)},0);return}typeof document<"u"&&(this.index=Vo.requestsCount++,Vo.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=YJ,t)try{this.xhr.abort()}catch{}typeof document<"u"&&delete Vo.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()}}Vo.requestsCount=0;Vo.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",e$);else if(typeof addEventListener=="function"){const e="onpagehide"in Br?"pagehide":"unload";addEventListener(e,e$,!1)}}function e$(){for(let e in Vo.requests)Vo.requests.hasOwnProperty(e)&&Vo.requests[e].abort()}const sb=typeof Promise=="function"&&typeof Promise.resolve=="function"?t=>Promise.resolve().then(t):(t,n)=>n(t,0),bp=Br.WebSocket||Br.MozWebSocket,t$=!0,ZJ="arraybuffer",n$=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class qJ extends ib{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=n$?{}:EA(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=t$&&!n$?n?new bp(t,n):new bp(t):new bp(t,n,r)}catch(o){return this.emitReserved("error",o)}this.ws.binaryType=this.socket.binaryType,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{t$&&this.ws.send(i)}catch{}o&&sb(()=>{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]=$A()),this.supportsBinary||(n.b64=1),this.createUri(t,n)}check(){return!!bp}}class QJ extends ib{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=DJ(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=t.readable.pipeThrough(n).getReader(),o=NJ();o.readable.pipeTo(t.writable),this.writer=o.writable.getWriter();const i=()=>{r.read().then(({done:l,value:u})=>{l||(this.onPacket(u),i())}).catch(l=>{})};i();const s={type:"open"};this.query.sid&&(s.data=`{"sid":"${this.query.sid}"}`),this.writer.write(s).then(()=>this.onOpen())})}))}write(t){this.writable=!1;for(let n=0;n{o&&sb(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;(t=this.transport)===null||t===void 0||t.close()}}const JJ={websocket:qJ,webtransport:QJ,polling:XJ},eee=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,tee=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Y1(e){if(e.length>2e3)throw"URI too long";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 o=eee.exec(e||""),i={},s=14;for(;s--;)i[tee[s]]=o[s]||"";return n!=-1&&r!=-1&&(i.source=t,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=nee(i,i.path),i.queryKey=ree(i,i.query),i}function nee(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 ree(e,t){const n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(r,o,i){o&&(n[o]=i)}),n}let TA=class sl extends Qt{constructor(t,n={}){super(),this.binaryType=ZJ,this.writeBuffer=[],t&&typeof t=="object"&&(n=t,t=null),t?(t=Y1(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=Y1(n.host).host),hg(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=VJ(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=SA,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 JJ[t](r)}open(){let t;if(this.opts.rememberUpgrade&&sl.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;sl.priorWebsocketSuccess=!1;const o=()=>{r||(n.send([{type:"ping",data:"probe"}]),n.once("packet",m=>{if(!r)if(m.type==="pong"&&m.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",n),!n)return;sl.priorWebsocketSuccess=n.name==="websocket",this.transport.pause(()=>{r||this.readyState!=="closed"&&(h(),this.setTransport(n),n.send([{type:"upgrade"}]),this.emitReserved("upgrade",n),n=null,this.upgrading=!1,this.flush())})}else{const g=new Error("probe error");g.transport=n.name,this.emitReserved("upgradeError",g)}}))};function i(){r||(r=!0,h(),n.close(),n=null)}const s=m=>{const g=new Error("probe error: "+m);g.transport=n.name,i(),this.emitReserved("upgradeError",g)};function l(){s("transport closed")}function u(){s("socket closed")}function d(m){n&&m.name!==n.name&&i()}const h=()=>{n.removeListener("open",o),n.removeListener("error",s),n.removeListener("close",l),this.off("close",u),this.off("upgrading",d)};n.once("open",o),n.once("error",s),n.once("close",l),this.once("close",u),this.once("upgrading",d),this.upgrades.indexOf("webtransport")!==-1&&t!=="webtransport"?this.setTimeoutFn(()=>{r||n.open()},200):n.open()}onOpen(){if(this.readyState="open",sl.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,o){if(typeof n=="function"&&(o=n,n=void 0),typeof r=="function"&&(o=r,r=null),this.readyState==="closing"||this.readyState==="closed")return;r=r||{},r.compress=r.compress!==!1;const i={type:t,data:n,options:r};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),o&&this.once("flush",o),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){sl.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 o=t.length;for(;rtypeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,PA=Object.prototype.toString,aee=typeof Blob=="function"||typeof Blob<"u"&&PA.call(Blob)==="[object BlobConstructor]",lee=typeof File=="function"||typeof File<"u"&&PA.call(File)==="[object FileConstructor]";function ab(e){return iee&&(e instanceof ArrayBuffer||see(e))||aee&&e instanceof Blob||lee&&e instanceof File}function nh(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(i),n.apply(this,[null,...s])}}emitWithAck(t,...n){const r=this.flags.timeout!==void 0||this._opts.ackTimeout!==void 0;return new Promise((o,i)=>{n.push((s,l)=>r?s?i(s):o(l):o(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((o,...i)=>r!==this._queue[0]?void 0:(o!==null?r.tryCount>this._opts.retries&&(this._queue.shift(),n&&n(o)):(this._queue.shift(),n&&n(null,...i)),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:lt.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 lt.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 lt.EVENT:case lt.BINARY_EVENT:this.onevent(t);break;case lt.ACK:case lt.BINARY_ACK:this.onack(t);break;case lt.DISCONNECT:this.ondisconnect();break;case lt.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(...o){r||(r=!0,n.packet({type:lt.ACK,id:t,data:o}))}}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:lt.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}Cc.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};Cc.prototype.reset=function(){this.attempts=0};Cc.prototype.setMin=function(e){this.ms=e};Cc.prototype.setMax=function(e){this.max=e};Cc.prototype.setJitter=function(e){this.jitter=e};class Z1 extends Qt{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,hg(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 Cc({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(n.timeout==null?2e4:n.timeout),this._readyState="closed",this.uri=t;const o=n.parser||mee;this.encoder=new o.Encoder,this.decoder=new o.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 TA(this.uri,this.opts);const n=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;const o=fo(n,"open",function(){r.onopen(),t&&t()}),i=l=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",l),t?t(l):this.maybeReconnectOnOpen()},s=fo(n,"error",i);if(this._timeout!==!1){const l=this._timeout,u=this.setTimeoutFn(()=>{o(),i(new Error("timeout")),n.close()},l);this.opts.autoUnref&&u.unref(),this.subs.push(()=>{this.clearTimeoutFn(u)})}return this.subs.push(o),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(fo(t,"ping",this.onping.bind(this)),fo(t,"data",this.ondata.bind(this)),fo(t,"error",this.onerror.bind(this)),fo(t,"close",this.onclose.bind(this)),fo(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){sb(()=>{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 AA(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(o=>{o?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",o)):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 cu={};function rh(e,t){typeof e=="object"&&(t=e,e=void 0),t=t||{};const n=oee(e,t.path||"/socket.io"),r=n.source,o=n.id,i=n.path,s=cu[o]&&i in cu[o].nsps,l=t.forceNew||t["force new connection"]||t.multiplex===!1||s;let u;return l?u=new Z1(r,t):(cu[o]||(cu[o]=new Z1(r,t)),u=cu[o]),n.query&&!t.query&&(t.query=n.queryKey),u.socket(n.path,t)}Object.assign(rh,{Manager:Z1,Socket:AA,io:rh,connect:rh});const OA="Progress",mg=100,[vee,Rte]=An(OA),[yee,wee]=vee(OA),MA=f.forwardRef((e,t)=>{const{__scopeProgress:n,value:r,max:o,getValueLabel:i=_ee,...s}=e,l=q1(o)?o:mg,u=DA(r,l)?r:null,d=im(u)?i(u,l):void 0;return f.createElement(yee,{scope:n,value:u,max:l},f.createElement(Pe.div,Y({"aria-valuemax":l,"aria-valuemin":0,"aria-valuenow":im(u)?u:void 0,"aria-valuetext":d,role:"progressbar","data-state":NA(u,l),"data-value":u??void 0,"data-max":l},s,{ref:t})))});MA.propTypes={max(e,t,n){const r=e[t],o=String(r);return r&&!q1(r)?new Error(See(o,n)):null},value(e,t,n){const r=e[t],o=String(r),i=q1(e.max)?e.max:mg;return r!=null&&!DA(r,i)?new Error(Eee(o,n)):null}};const xee="ProgressIndicator",bee=f.forwardRef((e,t)=>{var n;const{__scopeProgress:r,...o}=e,i=wee(xee,r);return f.createElement(Pe.div,Y({"data-state":NA(i.value,i.max),"data-value":(n=i.value)!==null&&n!==void 0?n:void 0,"data-max":i.max},o,{ref:t}))});function _ee(e,t){return`${Math.round(e/t*100)}%`}function NA(e,t){return e==null?"indeterminate":e===t?"complete":"loading"}function im(e){return typeof e=="number"}function q1(e){return im(e)&&!isNaN(e)&&e>0}function DA(e,t){return im(e)&&!isNaN(e)&&e<=t&&e>=0}function See(e,t){return`Invalid prop \`max\` of value \`${e}\` supplied to \`${t}\`. Only numbers greater than 0 are valid max values. Defaulting to \`${mg}\`.`}function Eee(e,t){return`Invalid prop \`value\` of value \`${e}\` supplied to \`${t}\`. The \`value\` prop must be: + - a positive number + - less than the value passed to \`max\` (or ${mg} if no \`max\` prop is set) + - \`null\` if the progress is indeterminate. + +Defaulting to \`null\`.`}const IA=MA,Cee=bee,LA=f.forwardRef(({className:e,value:t,...n},r)=>v.jsx(IA,{ref:r,className:Ce("relative h-2 w-full overflow-hidden rounded-full bg-primary/20",e),...n,children:v.jsx(Cee,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(t||0)}%)`}})}));LA.displayName=IA.displayName;const $ee="http://127.0.0.1:8080",Vi=rh($ee),kee=()=>{const[e,t,n]=bt(u=>[u.settings,u.isInpainting,u.isSD()]),[r,o]=f.useState(!1),[i,s]=f.useState(0),l=Math.min(Math.round(i/e.sdSteps*100),100);return f.useEffect(()=>{if(n)return Vi.on("connect",()=>{o(!0)}),Vi.on("disconnect",()=>{o(!1)}),Vi.on("diffusion_progress",u=>{u&&s(u.step+1)}),Vi.on("diffusion_finish",()=>{s(0)}),()=>{Vi.off("connect"),Vi.off("disconnect"),Vi.off("diffusion_progress"),Vi.off("diffusion_finish")}},[n]),v.jsxs("div",{className:"z-10 fixed bg-background w-[220px] left-1/2 -translate-x-1/2 top-[68px] h-[32px] flex justify-center items-center gap-[18px] border-[1px] border-[solid] rounded-[14px] pl-[8px] pr-[8px]",style:{visibility:r&&t&&n?"visible":"hidden"},children:[v.jsx(LA,{value:l}),v.jsxs("div",{className:"w-[45px] flex justify-center font-nums",children:[l,"%"]})]})},Ree=()=>{const[e,t]=bt(n=>[n.file,n.updateSettings]);return f.useEffect(()=>{(async()=>{const r=await jj();t({model:r})})()},[]),v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"flex gap-3 absolute top-[68px] left-[24px] items-center",children:[v.jsx(vJ,{}),v.jsx(qq,{})]}),v.jsx(Wq,{}),v.jsx(kee,{}),v.jsx(kJ,{}),e?v.jsx(Zq,{file:e}):v.jsx(v.Fragment,{})]})},Tee=()=>{const[e,t]=f.useState(window.innerWidth),n=f.useCallback(()=>{t(window.innerWidth)},[]);if(f.useEffect(()=>(window.addEventListener("resize",n),()=>{window.removeEventListener("resize",n)})),e<768)return"mobile";if(e>=768&&e<1224)return"tablet";if(e>=1224)return"desktop"};function Pee(e){const{onSelection:t}=e,[n]=f.useState(`file-upload-${Math.random().toString()}`),r=Tee();function o(i){if(!(!i||!i.type.match("image.*")))try{if(i.size>20*1024*1024)throw new Error("file too large");t(i)}catch(l){alert(`error: ${l.message}`)}}return v.jsx("div",{className:"absolute flex w-screen h-screen justify-center items-center pointer-events-none",children:v.jsx("label",{htmlFor:n,className:"grid bg-background border-[2px] border-[dashed] rounded-lg min-w-[600px] hover:bg-primary hover:text-primary-foreground pointer-events-auto",children:v.jsxs("div",{className:"grid p-16 w-full h-full",onDragOver:i=>{i.stopPropagation(),i.preventDefault()},children:[v.jsx("input",{className:"hidden",id:n,name:n,type:"file",onChange:i=>{var l;const s=(l=i.currentTarget.files)==null?void 0:l[0];s&&o(s)},accept:"image/png, image/jpeg"}),v.jsx("p",{className:"text-center",children:r==="desktop"?"Click here or drag an image file":"Tap here to load your picture"})]})})})}const FA="ToastProvider",[cb,Aee,Oee]=zd("Toast"),[jA,Tte]=An("Toast",[Oee]),[Mee,gg]=jA(FA),zA=e=>{const{__scopeToast:t,label:n="Notification",duration:r=5e3,swipeDirection:o="right",swipeThreshold:i=50,children:s}=e,[l,u]=f.useState(null),[d,h]=f.useState(0),m=f.useRef(!1),g=f.useRef(!1);return f.createElement(cb.Provider,{scope:t},f.createElement(Mee,{scope:t,label:n,duration:r,swipeDirection:o,swipeThreshold:i,toastCount:d,viewport:l,onViewportChange:u,onToastAdd:f.useCallback(()=>h(y=>y+1),[]),onToastRemove:f.useCallback(()=>h(y=>y-1),[]),isFocusedToastEscapeKeyDownRef:m,isClosePausedRef:g},s))};zA.propTypes={label(e){if(e.label&&typeof e.label=="string"&&!e.label.trim()){const t=`Invalid prop \`label\` supplied to \`${FA}\`. Expected non-empty \`string\`.`;return new Error(t)}return null}};const Nee="ToastViewport",Dee=["F8"],Q1="toast.viewportPause",J1="toast.viewportResume",Iee=f.forwardRef((e,t)=>{const{__scopeToast:n,hotkey:r=Dee,label:o="Notifications ({hotkey})",...i}=e,s=gg(Nee,n),l=Aee(n),u=f.useRef(null),d=f.useRef(null),h=f.useRef(null),m=f.useRef(null),g=Be(t,m,s.onViewportChange),y=r.join("+").replace(/Key/g,"").replace(/Digit/g,""),x=s.toastCount>0;f.useEffect(()=>{const C=S=>{var b;r.every(k=>S[k]||S.code===k)&&((b=m.current)===null||b===void 0||b.focus())};return document.addEventListener("keydown",C),()=>document.removeEventListener("keydown",C)},[r]),f.useEffect(()=>{const C=u.current,S=m.current;if(x&&C&&S){const b=()=>{if(!s.isClosePausedRef.current){const M=new CustomEvent(Q1);S.dispatchEvent(M),s.isClosePausedRef.current=!0}},E=()=>{if(s.isClosePausedRef.current){const M=new CustomEvent(J1);S.dispatchEvent(M),s.isClosePausedRef.current=!1}},k=M=>{!C.contains(M.relatedTarget)&&E()},P=()=>{C.contains(document.activeElement)||E()};return C.addEventListener("focusin",b),C.addEventListener("focusout",k),C.addEventListener("pointermove",b),C.addEventListener("pointerleave",P),window.addEventListener("blur",b),window.addEventListener("focus",E),()=>{C.removeEventListener("focusin",b),C.removeEventListener("focusout",k),C.removeEventListener("pointermove",b),C.removeEventListener("pointerleave",P),window.removeEventListener("blur",b),window.removeEventListener("focus",E)}}},[x,s.isClosePausedRef]);const _=f.useCallback(({tabbingDirection:C})=>{const b=l().map(E=>{const k=E.ref.current,P=[k,...Qee(k)];return C==="forwards"?P:P.reverse()});return(C==="forwards"?b.reverse():b).flat()},[l]);return f.useEffect(()=>{const C=m.current;if(C){const S=b=>{const E=b.altKey||b.ctrlKey||b.metaKey;if(b.key==="Tab"&&!E){const O=document.activeElement,F=b.shiftKey;if(b.target===C&&F){var P;(P=d.current)===null||P===void 0||P.focus();return}const G=_({tabbingDirection:F?"backwards":"forwards"}),ae=G.findIndex(U=>U===O);if(j0(G.slice(ae+1)))b.preventDefault();else{var M,A;F?(M=d.current)===null||M===void 0||M.focus():(A=h.current)===null||A===void 0||A.focus()}}};return C.addEventListener("keydown",S),()=>C.removeEventListener("keydown",S)}},[l,_]),f.createElement(_B,{ref:u,role:"region","aria-label":o.replace("{hotkey}",y),tabIndex:-1,style:{pointerEvents:x?void 0:"none"}},x&&f.createElement(o$,{ref:d,onFocusFromOutsideViewport:()=>{const C=_({tabbingDirection:"forwards"});j0(C)}}),f.createElement(cb.Slot,{scope:n},f.createElement(Pe.ol,Y({tabIndex:-1},i,{ref:g}))),x&&f.createElement(o$,{ref:h,onFocusFromOutsideViewport:()=>{const C=_({tabbingDirection:"backwards"});j0(C)}}))}),Lee="ToastFocusProxy",o$=f.forwardRef((e,t)=>{const{__scopeToast:n,onFocusFromOutsideViewport:r,...o}=e,i=gg(Lee,n);return f.createElement(Um,Y({"aria-hidden":!0,tabIndex:0},o,{ref:t,style:{position:"fixed"},onFocus:s=>{var l;const u=s.relatedTarget;!((l=i.viewport)!==null&&l!==void 0&&l.contains(u))&&r()}}))}),vg="Toast",Fee="toast.swipeStart",jee="toast.swipeMove",zee="toast.swipeCancel",Bee="toast.swipeEnd",Uee=f.forwardRef((e,t)=>{const{forceMount:n,open:r,defaultOpen:o,onOpenChange:i,...s}=e,[l=!0,u]=Zr({prop:r,defaultProp:o,onChange:i});return f.createElement(xn,{present:n||l},f.createElement(BA,Y({open:l},s,{ref:t,onClose:()=>u(!1),onPause:Ft(e.onPause),onResume:Ft(e.onResume),onSwipeStart:ue(e.onSwipeStart,d=>{d.currentTarget.setAttribute("data-swipe","start")}),onSwipeMove:ue(e.onSwipeMove,d=>{const{x:h,y:m}=d.detail.delta;d.currentTarget.setAttribute("data-swipe","move"),d.currentTarget.style.setProperty("--radix-toast-swipe-move-x",`${h}px`),d.currentTarget.style.setProperty("--radix-toast-swipe-move-y",`${m}px`)}),onSwipeCancel:ue(e.onSwipeCancel,d=>{d.currentTarget.setAttribute("data-swipe","cancel"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),d.currentTarget.style.removeProperty("--radix-toast-swipe-end-x"),d.currentTarget.style.removeProperty("--radix-toast-swipe-end-y")}),onSwipeEnd:ue(e.onSwipeEnd,d=>{const{x:h,y:m}=d.detail.delta;d.currentTarget.setAttribute("data-swipe","end"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),d.currentTarget.style.setProperty("--radix-toast-swipe-end-x",`${h}px`),d.currentTarget.style.setProperty("--radix-toast-swipe-end-y",`${m}px`),u(!1)})})))}),[Vee,Wee]=jA(vg,{onClose(){}}),BA=f.forwardRef((e,t)=>{const{__scopeToast:n,type:r="foreground",duration:o,open:i,onClose:s,onEscapeKeyDown:l,onPause:u,onResume:d,onSwipeStart:h,onSwipeMove:m,onSwipeCancel:g,onSwipeEnd:y,...x}=e,_=gg(vg,n),[C,S]=f.useState(null),b=Be(t,U=>S(U)),E=f.useRef(null),k=f.useRef(null),P=o||_.duration,M=f.useRef(0),A=f.useRef(P),O=f.useRef(0),{onToastAdd:F,onToastRemove:V}=_,J=Ft(()=>{var U;(C==null?void 0:C.contains(document.activeElement))&&((U=_.viewport)===null||U===void 0||U.focus()),s()}),G=f.useCallback(U=>{!U||U===1/0||(window.clearTimeout(O.current),M.current=new Date().getTime(),O.current=window.setTimeout(J,U))},[J]);f.useEffect(()=>{const U=_.viewport;if(U){const te=()=>{G(A.current),d==null||d()},L=()=>{const ie=new Date().getTime()-M.current;A.current=A.current-ie,window.clearTimeout(O.current),u==null||u()};return U.addEventListener(Q1,L),U.addEventListener(J1,te),()=>{U.removeEventListener(Q1,L),U.removeEventListener(J1,te)}}},[_.viewport,P,u,d,G]),f.useEffect(()=>{i&&!_.isClosePausedRef.current&&G(P)},[i,P,_.isClosePausedRef,G]),f.useEffect(()=>(F(),()=>V()),[F,V]);const ae=f.useMemo(()=>C?HA(C):null,[C]);return _.viewport?f.createElement(f.Fragment,null,ae&&f.createElement(Hee,{__scopeToast:n,role:"status","aria-live":r==="foreground"?"assertive":"polite","aria-atomic":!0},ae),f.createElement(Vee,{scope:n,onClose:J},Os.createPortal(f.createElement(cb.ItemSlot,{scope:n},f.createElement(bB,{asChild:!0,onEscapeKeyDown:ue(l,()=>{_.isFocusedToastEscapeKeyDownRef.current||J(),_.isFocusedToastEscapeKeyDownRef.current=!1})},f.createElement(Pe.li,Y({role:"status","aria-live":"off","aria-atomic":!0,tabIndex:0,"data-state":i?"open":"closed","data-swipe-direction":_.swipeDirection},x,{ref:b,style:{userSelect:"none",touchAction:"none",...e.style},onKeyDown:ue(e.onKeyDown,U=>{U.key==="Escape"&&(l==null||l(U.nativeEvent),U.nativeEvent.defaultPrevented||(_.isFocusedToastEscapeKeyDownRef.current=!0,J()))}),onPointerDown:ue(e.onPointerDown,U=>{U.button===0&&(E.current={x:U.clientX,y:U.clientY})}),onPointerMove:ue(e.onPointerMove,U=>{if(!E.current)return;const te=U.clientX-E.current.x,L=U.clientY-E.current.y,ie=!!k.current,K=["left","right"].includes(_.swipeDirection),Q=["left","up"].includes(_.swipeDirection)?Math.min:Math.max,W=K?Q(0,te):0,le=K?0:Q(0,L),ge=U.pointerType==="touch"?10:2,Ve={x:W,y:le},Ue={originalEvent:U,delta:Ve};ie?(k.current=Ve,_p(jee,m,Ue,{discrete:!1})):i$(Ve,_.swipeDirection,ge)?(k.current=Ve,_p(Fee,h,Ue,{discrete:!1}),U.target.setPointerCapture(U.pointerId)):(Math.abs(te)>ge||Math.abs(L)>ge)&&(E.current=null)}),onPointerUp:ue(e.onPointerUp,U=>{const te=k.current,L=U.target;if(L.hasPointerCapture(U.pointerId)&&L.releasePointerCapture(U.pointerId),k.current=null,E.current=null,te){const ie=U.currentTarget,K={originalEvent:U,delta:te};i$(te,_.swipeDirection,_.swipeThreshold)?_p(Bee,y,K,{discrete:!0}):_p(zee,g,K,{discrete:!0}),ie.addEventListener("click",Q=>Q.preventDefault(),{once:!0})}})})))),_.viewport))):null});BA.propTypes={type(e){if(e.type&&!["foreground","background"].includes(e.type)){const t=`Invalid prop \`type\` supplied to \`${vg}\`. Expected \`foreground | background\`.`;return new Error(t)}return null}};const Hee=e=>{const{__scopeToast:t,children:n,...r}=e,o=gg(vg,t),[i,s]=f.useState(!1),[l,u]=f.useState(!1);return Zee(()=>s(!0)),f.useEffect(()=>{const d=window.setTimeout(()=>u(!0),1e3);return()=>window.clearTimeout(d)},[]),l?null:f.createElement(Md,{asChild:!0},f.createElement(Um,r,i&&f.createElement(f.Fragment,null,o.label," ",n)))},Kee=f.forwardRef((e,t)=>{const{__scopeToast:n,...r}=e;return f.createElement(Pe.div,Y({},r,{ref:t}))}),Yee=f.forwardRef((e,t)=>{const{__scopeToast:n,...r}=e;return f.createElement(Pe.div,Y({},r,{ref:t}))}),Gee="ToastAction",UA=f.forwardRef((e,t)=>{const{altText:n,...r}=e;return n?f.createElement(WA,{altText:n,asChild:!0},f.createElement(VA,Y({},r,{ref:t}))):null});UA.propTypes={altText(e){return e.altText?null:new Error(`Missing prop \`altText\` expected on \`${Gee}\``)}};const Xee="ToastClose",VA=f.forwardRef((e,t)=>{const{__scopeToast:n,...r}=e,o=Wee(Xee,n);return f.createElement(WA,{asChild:!0},f.createElement(Pe.button,Y({type:"button"},r,{ref:t,onClick:ue(e.onClick,o.onClose)})))}),WA=f.forwardRef((e,t)=>{const{__scopeToast:n,altText:r,...o}=e;return f.createElement(Pe.div,Y({"data-radix-toast-announce-exclude":"","data-radix-toast-announce-alt":r||void 0},o,{ref:t}))});function HA(e){const t=[];return Array.from(e.childNodes).forEach(r=>{if(r.nodeType===r.TEXT_NODE&&r.textContent&&t.push(r.textContent),qee(r)){const o=r.ariaHidden||r.hidden||r.style.display==="none",i=r.dataset.radixToastAnnounceExclude==="";if(!o)if(i){const s=r.dataset.radixToastAnnounceAlt;s&&t.push(s)}else t.push(...HA(r))}}),t}function _p(e,t,n,{discrete:r}){const o=n.originalEvent.currentTarget,i=new CustomEvent(e,{bubbles:!0,cancelable:!0,detail:n});t&&o.addEventListener(e,t,{once:!0}),r?cx(o,i):o.dispatchEvent(i)}const i$=(e,t,n=0)=>{const r=Math.abs(e.x),o=Math.abs(e.y),i=r>o;return t==="left"||t==="right"?i&&r>n:!i&&o>n};function Zee(e=()=>{}){const t=Ft(e);Pn(()=>{let n=0,r=0;return n=window.requestAnimationFrame(()=>r=window.requestAnimationFrame(t)),()=>{window.cancelAnimationFrame(n),window.cancelAnimationFrame(r)}},[t])}function qee(e){return e.nodeType===e.ELEMENT_NODE}function Qee(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const o=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||o?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function j0(e){const t=document.activeElement;return e.some(n=>n===t?!0:(n.focus(),document.activeElement!==t))}const Jee=zA,KA=Iee,YA=Uee,GA=Kee,XA=Yee,ZA=UA,qA=VA,ete=Jee,QA=f.forwardRef(({className:e,...t},n)=>v.jsx(KA,{ref:n,className:Ce("fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]",e),tabIndex:-1,...t}));QA.displayName=KA.displayName;const tte=Om("group pointer-events-auto relative flex w-full items-center justify-between space-x-2 overflow-hidden rounded-md border p-4 pr-6 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full",{variants:{variant:{default:"border bg-background text-foreground",destructive:"destructive group border-destructive bg-destructive text-destructive-foreground"}},defaultVariants:{variant:"default"}}),JA=f.forwardRef(({className:e,variant:t,...n},r)=>v.jsx(YA,{ref:r,className:Ce(tte({variant:t}),e),tabIndex:-1,...n}));JA.displayName=YA.displayName;const nte=f.forwardRef(({className:e,...t},n)=>v.jsx(ZA,{ref:n,className:Ce("inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium transition-colors hover:bg-secondary focus:outline-none focus:ring-1 focus:ring-ring disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive",e),tabIndex:-1,...t}));nte.displayName=ZA.displayName;const eO=f.forwardRef(({className:e,...t},n)=>v.jsx(qA,{ref:n,className:Ce("absolute right-1 top-1 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-1 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600",e),"toast-close":"",tabIndex:-1,...t,children:v.jsx(yT,{className:"h-4 w-4"})}));eO.displayName=qA.displayName;const tO=f.forwardRef(({className:e,...t},n)=>v.jsx(GA,{ref:n,className:Ce("text-sm font-semibold [&+div]:text-xs",e),tabIndex:-1,...t}));tO.displayName=GA.displayName;const nO=f.forwardRef(({className:e,...t},n)=>v.jsx(XA,{ref:n,className:Ce("text-sm opacity-90",e),...t,tabIndex:-1}));nO.displayName=XA.displayName;function rte(){const{toasts:e}=Td();return v.jsxs(ete,{children:[e.map(function({id:t,title:n,description:r,action:o,...i}){return v.jsxs(JA,{...i,children:[v.jsxs("div",{className:"grid gap-1",children:[n&&v.jsx(tO,{children:n}),r&&v.jsx(nO,{children:r})]}),o,v.jsx(eO,{})]},t)}),v.jsx(QA,{})]})}const ote=["image/jpeg","image/png","image/webp","image/bmp","image/tiff"];function ite(){const[e,t,n,r]=bt(g=>[g.file,g.updateAppState,g.setServerConfig,g.setFile]),o=Kj(),i=vH();f.useEffect(()=>{o&&r(o)},[o,r]),f.useEffect(()=>{t({windowSize:i})},[i]),f.useEffect(()=>{(async()=>{const y=await Lj();n(y),y.isDesktop&&uF()})()},[]);const s=f.useRef(0),l=f.useCallback(g=>{g.preventDefault(),g.stopPropagation()},[]),u=f.useCallback(g=>{g.preventDefault(),g.stopPropagation(),s.current+=1},[]),d=f.useCallback(g=>{g.preventDefault(),g.stopPropagation(),s.current-=1,s.current>0},[]),h=f.useCallback(g=>{if(g.preventDefault(),g.stopPropagation(),g.dataTransfer.files&&g.dataTransfer.files.length>0){if(!(g.dataTransfer.files.length>1)){const y=g.dataTransfer.files[0],x=y.type;ote.includes(x)&&r(y)}g.dataTransfer.clearData()}},[]),m=f.useCallback(g=>{if(!g.clipboardData)return;const y=g.clipboardData.items,x=[].slice.call(y).filter(S=>S.type.indexOf("image")!==-1);if(x.length===0)return;g.preventDefault(),g.stopPropagation();const C=x[0].getAsFile();C&&r(C)},[]);return f.useEffect(()=>(window.addEventListener("dragenter",u),window.addEventListener("dragleave",d),window.addEventListener("dragover",l),window.addEventListener("drop",h),window.addEventListener("paste",m),function(){window.removeEventListener("dragenter",u),window.removeEventListener("dragleave",d),window.removeEventListener("dragover",l),window.removeEventListener("drop",h),window.removeEventListener("paste",m)})),v.jsxs("main",{className:"flex min-h-screen flex-col items-center justify-between w-full bg-[radial-gradient(circle_at_1px_1px,_#8e8e8e8e_1px,_transparent_0)] [background-size:20px_20px] bg-repeat",children:[v.jsx(rte,{}),v.jsx(nZ,{}),v.jsx(Ree,{}),e?v.jsx(v.Fragment,{}):v.jsx(Pee,{onSelection:async g=>{r(g)}})]})}const sm=["light","dark"],ub="(prefers-color-scheme: dark)",ste=typeof window>"u",rO=f.createContext(void 0),ate=e=>f.useContext(rO)?Fe.createElement(f.Fragment,null,e.children):Fe.createElement(cte,e),lte=["light","dark"],cte=({forcedTheme:e,disableTransitionOnChange:t=!1,enableSystem:n=!0,enableColorScheme:r=!0,storageKey:o="theme",themes:i=lte,defaultTheme:s=n?"system":"light",attribute:l="data-theme",value:u,children:d,nonce:h})=>{const[m,g]=f.useState(()=>s$(o,s)),[y,x]=f.useState(()=>s$(o)),_=u?Object.values(u):i,C=f.useCallback(k=>{let P=k;if(!P)return;k==="system"&&n&&(P=a$());const M=u?u[P]:P,A=t?dte():null,O=document.documentElement;if(l==="class"?(O.classList.remove(..._),M&&O.classList.add(M)):M?O.setAttribute(l,M):O.removeAttribute(l),r){const F=sm.includes(s)?s:null,V=sm.includes(P)?P:F;O.style.colorScheme=V}A==null||A()},[]),S=f.useCallback(k=>{g(k);try{localStorage.setItem(o,k)}catch{}},[e]),b=f.useCallback(k=>{const P=a$(k);x(P),m==="system"&&n&&!e&&C("system")},[m,e]);f.useEffect(()=>{const k=window.matchMedia(ub);return k.addListener(b),b(k),()=>k.removeListener(b)},[b]),f.useEffect(()=>{const k=P=>{P.key===o&&S(P.newValue||s)};return window.addEventListener("storage",k),()=>window.removeEventListener("storage",k)},[S]),f.useEffect(()=>{C(e??m)},[e,m]);const E=f.useMemo(()=>({theme:m,setTheme:S,forcedTheme:e,resolvedTheme:m==="system"?y:m,themes:n?[...i,"system"]:i,systemTheme:n?y:void 0}),[m,S,e,y,n,i]);return Fe.createElement(rO.Provider,{value:E},Fe.createElement(ute,{forcedTheme:e,disableTransitionOnChange:t,enableSystem:n,enableColorScheme:r,storageKey:o,themes:i,defaultTheme:s,attribute:l,value:u,children:d,attrs:_,nonce:h}),d)},ute=f.memo(({forcedTheme:e,storageKey:t,attribute:n,enableSystem:r,enableColorScheme:o,defaultTheme:i,value:s,attrs:l,nonce:u})=>{const d=i==="system",h=n==="class"?`var d=document.documentElement,c=d.classList;c.remove(${l.map(x=>`'${x}'`).join(",")});`:`var d=document.documentElement,n='${n}',s='setAttribute';`,m=o?sm.includes(i)&&i?`if(e==='light'||e==='dark'||!e)d.style.colorScheme=e||'${i}'`:"if(e==='light'||e==='dark')d.style.colorScheme=e":"",g=(x,_=!1,C=!0)=>{const S=s?s[x]:x,b=_?x+"|| ''":`'${S}'`;let E="";return o&&C&&!_&&sm.includes(x)&&(E+=`d.style.colorScheme = '${x}';`),n==="class"?E+=_||S?`c.add(${b})`:"null":S&&(E+=`d[s](n,${b})`),E},y=e?`!function(){${h}${g(e)}}()`:r?`!function(){try{${h}var e=localStorage.getItem('${t}');if('system'===e||(!e&&${d})){var t='${ub}',m=window.matchMedia(t);if(m.media!==t||m.matches){${g("dark")}}else{${g("light")}}}else if(e){${s?`var x=${JSON.stringify(s)};`:""}${g(s?"x[e]":"e",!0)}}${d?"":"else{"+g(i,!1,!1)+"}"}${m}}catch(e){}}()`:`!function(){try{${h}var e=localStorage.getItem('${t}');if(e){${s?`var x=${JSON.stringify(s)};`:""}${g(s?"x[e]":"e",!0)}}else{${g(i,!1,!1)};}${m}}catch(t){}}();`;return Fe.createElement("script",{nonce:u,dangerouslySetInnerHTML:{__html:y}})},()=>!0),s$=(e,t)=>{if(ste)return;let n;try{n=localStorage.getItem(e)||void 0}catch{}return n||t},dte=()=>{const e=document.createElement("style");return e.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(e),()=>{window.getComputedStyle(document.body),setTimeout(()=>{document.head.removeChild(e)},1)}},a$=e=>(e||(e=window.matchMedia(ub)),e.matches?"dark":"light"),fte=new dL;z0.createRoot(document.getElementById("root")).render(v.jsx(Fe.StrictMode,{children:v.jsx(gL,{client:fte,children:v.jsx(ate,{defaultTheme:"dark",disableTransitionOnChange:!0,children:v.jsx(BU,{children:v.jsx(ite,{})})})})})); diff --git a/py/iopaint/web_app/assets/index-iK_rIxV0.css b/py/iopaint/web_app/assets/index-iK_rIxV0.css new file mode 100644 index 0000000..a4f1f98 --- /dev/null +++ b/py/iopaint/web_app/assets/index-iK_rIxV0.css @@ -0,0 +1 @@ +@font-face{font-family:Inter;font-style:normal;font-weight:100;font-display:swap;src:url(/assets/Inter-Thin-eKObIkJC.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:italic;font-weight:100;font-display:swap;src:url(/assets/Inter-ThinItalic-L6uBn3RP.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:normal;font-weight:200;font-display:swap;src:url(/assets/Inter-ExtraLight-w5HAp5iF.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:italic;font-weight:200;font-display:swap;src:url(/assets/Inter-ExtraLightItalic-ZptecSuc.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:normal;font-weight:300;font-display:swap;src:url(/assets/Inter-Light-DFhX0qo-.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:italic;font-weight:300;font-display:swap;src:url(/assets/Inter-LightItalic-fu56_DRc.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:normal;font-weight:400;font-display:swap;src:url(/assets/Inter-Regular-dEFHw1tF.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:italic;font-weight:400;font-display:swap;src:url(/assets/Inter-Italic-f6M78thn.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:normal;font-weight:500;font-display:swap;src:url(/assets/Inter-Medium-dDRaJ8tM.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:italic;font-weight:500;font-display:swap;src:url(/assets/Inter-MediumItalic-zr3roggP.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:normal;font-weight:600;font-display:swap;src:url(/assets/Inter-SemiBold-PyS8DO2L.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:italic;font-weight:600;font-display:swap;src:url(/assets/Inter-SemiBoldItalic-uIDb7hsH.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:normal;font-weight:700;font-display:swap;src:url(/assets/Inter-Bold-srYz_-1B.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:italic;font-weight:700;font-display:swap;src:url(/assets/Inter-BoldItalic-dE_gZyur.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:normal;font-weight:800;font-display:swap;src:url(/assets/Inter-ExtraBold-TduDdwUu.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:italic;font-weight:800;font-display:swap;src:url(/assets/Inter-ExtraBoldItalic-BJafRE5I.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:normal;font-weight:900;font-display:swap;src:url(/assets/Inter-Black-jiII8dog.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:italic;font-weight:900;font-display:swap;src:url(/assets/Inter-BlackItalic-1413vuen.woff2?v=4.0) format("woff2")}*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:before,:after{--tw-content: ""}html{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,"Apple Color Emoji","Segoe UI Emoji",Segoe UI Symbol,"Noto Color Emoji";font-feature-settings:normal;font-variation-settings:normal}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,[type=button],[type=reset],[type=submit]{-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]{display:none}:root{--background: 0 0% 100%;--foreground: 224 71.4% 4.1%;--card: 0 0% 100%;--card-foreground: 224 71.4% 4.1%;--popover: 0 0% 100%;--popover-foreground: 224 71.4% 4.1%;--primary: 48 100% 50%;--primary-foreground: 210 20% 98%;--secondary: 220 14.3% 95.9%;--secondary-foreground: 220.9 39.3% 11%;--muted: 220 14.3% 95.9%;--muted-foreground: 220 8.9% 46.1%;--accent: 220 14.3% 95.9%;--accent-foreground: 220.9 39.3% 11%;--destructive: 0 84.2% 60.2%;--destructive-foreground: 210 20% 98%;--border: 220 13% 91%;--input: 220 13% 91%;--ring: 224 71.4% 4.1%;--radius: .5rem}[data-theme=dark]{--background: 240 10% 3.9%;--foreground: 0 0% 98%;--card: 224 71.4% 4.1%;--card-foreground: 210 20% 98%;--popover: 240 10% 3.9%;--popover-foreground: 0 0% 98%;--primary: 48 100% 50%;--primary-foreground: 220.9 39.3% 11%;--secondary: 240 3.7% 15.9%;--secondary-foreground: 0 0% 98%;--muted: 240 3.7% 15.9%;--muted-foreground: 240 5% 64.9%;--accent: 240 3.7% 15.9%;--accent-foreground: 0 0% 98%;--destructive: 0 62.8% 30.6%;--destructive-foreground: 0 85.7% 97.3%;--border: 240 3.7% 15.9%;--input: 240 3.7% 15.9%;--ring: 240 4.9% 83.9%}*{border-color:hsl(var(--border))}body{background-color:hsl(var(--background));color:hsl(var(--foreground))}*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: }.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border-width:0}.pointer-events-none{pointer-events:none}.pointer-events-auto{pointer-events:auto}.visible{visibility:visible}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.inset-0{top:0;right:0;bottom:0;left:0}.inset-x-0{left:0;right:0}.inset-y-0{top:0;bottom:0}.bottom-0{bottom:0}.bottom-5{bottom:1.25rem}.bottom-6{bottom:1.5rem}.left-0{left:0}.left-1\/2{left:50%}.left-2{left:.5rem}.left-\[24px\]{left:24px}.left-\[50\%\]{left:50%}.left-\[8px\]{left:8px}.right-0{right:0}.right-1{right:.25rem}.right-10{right:2.5rem}.right-2{right:.5rem}.right-4{right:1rem}.right-6{right:1.5rem}.top-0{top:0}.top-1{top:.25rem}.top-4{top:1rem}.top-\[0\]{top:0}.top-\[50\%\]{top:50%}.top-\[68px\]{top:68px}.z-10{z-index:10}.z-20{z-index:20}.z-50{z-index:50}.z-\[100\]{z-index:100}.z-\[2\]{z-index:2}.z-\[4\]{z-index:4}.m-3{margin:.75rem}.-mx-1{margin-left:-.25rem;margin-right:-.25rem}.my-1{margin-top:.25rem;margin-bottom:.25rem}.mb-2{margin-bottom:.5rem}.mb-8{margin-bottom:2rem}.mb-\[-6px\]{margin-bottom:-6px}.ml-\[-6px\]{margin-left:-6px}.ml-auto{margin-left:auto}.mr-8{margin-right:2rem}.mr-\[-6px\]{margin-right:-6px}.mt-0{margin-top:0}.mt-2{margin-top:.5rem}.mt-4{margin-top:1rem}.mt-\[-6px\]{margin-top:-6px}.mt-\[60px\]{margin-top:60px}.block{display:block}.flex{display:flex}.inline-flex{display:inline-flex}.grid{display:grid}.hidden{display:none}.aspect-square{aspect-ratio:1 / 1}.h-1{height:.25rem}.h-1\.5{height:.375rem}.h-10{height:2.5rem}.h-2{height:.5rem}.h-2\.5{height:.625rem}.h-3{height:.75rem}.h-3\.5{height:.875rem}.h-4{height:1rem}.h-4\/5{height:80%}.h-5{height:1.25rem}.h-6{height:1.5rem}.h-7{height:1.75rem}.h-8{height:2rem}.h-9{height:2.25rem}.h-\[10px\]{height:10px}.h-\[12px\]{height:12px}.h-\[1px\]{height:1px}.h-\[20px\]{height:20px}.h-\[240px\]{height:240px}.h-\[32px\]{height:32px}.h-\[600px\]{height:600px}.h-\[60px\]{height:60px}.h-\[var\(--radix-select-trigger-height\)\]{height:var(--radix-select-trigger-height)}.h-full{height:100%}.h-px{height:1px}.h-screen{height:100vh}.max-h-96{max-height:24rem}.max-h-\[200px\]{max-height:200px}.max-h-\[8rem\]{max-height:8rem}.max-h-screen{max-height:100vh}.min-h-\[60px\]{min-height:60px}.min-h-screen{min-height:100vh}.w-14{width:3.5rem}.w-2{width:.5rem}.w-2\.5{width:.625rem}.w-3{width:.75rem}.w-3\.5{width:.875rem}.w-3\/4{width:75%}.w-4{width:1rem}.w-48{width:12rem}.w-6{width:1.5rem}.w-72{width:18rem}.w-8{width:2rem}.w-9{width:2.25rem}.w-\[100px\]{width:100px}.w-\[10px\]{width:10px}.w-\[12px\]{width:12px}.w-\[140px\]{width:140px}.w-\[160px\]{width:160px}.w-\[175px\]{width:175px}.w-\[180px\]{width:180px}.w-\[1px\]{width:1px}.w-\[20px\]{width:20px}.w-\[220px\]{width:220px}.w-\[250px\]{width:250px}.w-\[300px\]{width:300px}.w-\[400px\]{width:400px}.w-\[45px\]{width:45px}.w-\[510px\]{width:510px}.w-\[60px\]{width:60px}.w-\[65px\]{width:65px}.w-\[6px\]{width:6px}.w-full{width:100%}.w-screen{width:100vw}.min-w-\[500px\]{min-width:500px}.min-w-\[600px\]{min-width:600px}.min-w-\[8rem\]{min-width:8rem}.min-w-\[var\(--radix-select-trigger-width\)\]{min-width:var(--radix-select-trigger-width)}.max-w-3xl{max-width:48rem}.max-w-6xl{max-width:72rem}.max-w-\[200px\]{max-width:200px}.max-w-lg{max-width:32rem}.max-w-sm{max-width:24rem}.max-w-xs{max-width:20rem}.flex-1{flex:1 1 0%}.shrink{flex-shrink:1}.shrink-0{flex-shrink:0}.grow{flex-grow:1}.origin-top-left{transform-origin:top left}.-translate-x-1\/2,.translate-x-\[-50\%\]{--tw-translate-x: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-y-\[-50\%\]{--tw-translate-y: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.transform{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}@keyframes pulse{50%{opacity:.5}}.animate-pulse{animation:pulse 2s cubic-bezier(.4,0,.6,1) infinite}@keyframes spin{to{transform:rotate(360deg)}}.animate-spin{animation:spin 1s linear infinite}.cursor-default{cursor:default}.cursor-ew-resize{cursor:ew-resize}.cursor-ne-resize{cursor:ne-resize}.cursor-ns-resize{cursor:ns-resize}.cursor-nw-resize{cursor:nw-resize}.cursor-pointer{cursor:pointer}.cursor-se-resize{cursor:se-resize}.cursor-sw-resize{cursor:sw-resize}.touch-none{touch-action:none}.select-none{-webkit-user-select:none;-moz-user-select:none;user-select:none}.resize{resize:both}.flex-row{flex-direction:row}.flex-col{flex-direction:column}.flex-col-reverse{flex-direction:column-reverse}.items-center{align-items:center}.justify-start{justify-content:flex-start}.justify-end{justify-content:flex-end}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.gap-1{gap:.25rem}.gap-2{gap:.5rem}.gap-3{gap:.75rem}.gap-4{gap:1rem}.gap-6{gap:1.5rem}.gap-8{gap:2rem}.gap-\[12px\]{gap:12px}.gap-\[18px\]{gap:18px}.gap-\[8px\]{gap:8px}.gap-y-4{row-gap:1rem}.space-x-2>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.5rem * var(--tw-space-x-reverse));margin-left:calc(.5rem * calc(1 - var(--tw-space-x-reverse)))}.space-x-8>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(2rem * var(--tw-space-x-reverse));margin-left:calc(2rem * calc(1 - var(--tw-space-x-reverse)))}.space-y-0>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(0px * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(0px * var(--tw-space-y-reverse))}.space-y-0\.5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.125rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.125rem * var(--tw-space-y-reverse))}.space-y-1>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.25rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.25rem * var(--tw-space-y-reverse))}.space-y-1\.5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.375rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.375rem * var(--tw-space-y-reverse))}.space-y-2>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.5rem * var(--tw-space-y-reverse))}.space-y-4>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1rem * var(--tw-space-y-reverse))}.justify-self-end{justify-self:end}.overflow-auto{overflow:auto}.overflow-hidden{overflow:hidden}.overflow-y-auto{overflow-y:auto}.whitespace-nowrap{white-space:nowrap}.rounded-\[14px\]{border-radius:14px}.rounded-\[3rem\]{border-radius:3rem}.rounded-\[50\%\]{border-radius:50%}.rounded-\[inherit\]{border-radius:inherit}.rounded-full{border-radius:9999px}.rounded-lg{border-radius:var(--radius)}.rounded-md{border-radius:calc(var(--radius) - 2px)}.rounded-sm{border-radius:calc(var(--radius) - 4px)}.rounded-xl{border-radius:.75rem}.border{border-width:1px}.border-2{border-width:2px}.border-\[1px\]{border-width:1px}.border-\[2px\]{border-width:2px}.border-b{border-bottom-width:1px}.border-l{border-left-width:1px}.border-r{border-right-width:1px}.border-t{border-top-width:1px}.border-solid{border-style:solid}.border-\[\#ffcc00\]{--tw-border-opacity: 1;border-color:rgb(255 204 0 / var(--tw-border-opacity))}.border-\[dashed\]{border-color:dashed}.border-\[solid\]{border-color:solid}.border-destructive{border-color:hsl(var(--destructive))}.border-input{border-color:hsl(var(--input))}.border-primary{border-color:hsl(var(--primary))}.border-primary\/60{border-color:hsl(var(--primary) / .6)}.border-transparent{border-color:transparent}.border-l-transparent{border-left-color:transparent}.border-t-transparent{border-top-color:transparent}.bg-\[\#ffcc00bb\]{background-color:#fc0b}.bg-\[rgba\(21\,_215\,_121\,_0\.936\)\]{background-color:#15d779ef}.bg-\[rgba\(237\,_49\,_55\,_0\.942\)\]{background-color:#ed3137f0}.bg-background{background-color:hsl(var(--background))}.bg-background\/70{background-color:hsl(var(--background) / .7)}.bg-background\/80{background-color:hsl(var(--background) / .8)}.bg-border{background-color:hsl(var(--border))}.bg-destructive{background-color:hsl(var(--destructive))}.bg-muted{background-color:hsl(var(--muted))}.bg-popover{background-color:hsl(var(--popover))}.bg-primary{background-color:hsl(var(--primary))}.bg-primary\/20{background-color:hsl(var(--primary) / .2)}.bg-secondary{background-color:hsl(var(--secondary))}.bg-transparent{background-color:transparent}.bg-\[radial-gradient\(circle_at_1px_1px\,_\#8e8e8e8e_1px\,_transparent_0\)\]{background-image:radial-gradient(circle at 1px 1px,#8e8e8e8e 1px,transparent 0)}.bg-repeat{background-repeat:repeat}.fill-current{fill:currentColor}.fill-primary{fill:hsl(var(--primary))}.p-1{padding:.25rem}.p-1\.5{padding:.375rem}.p-16{padding:4rem}.p-4{padding:1rem}.p-6{padding:1.5rem}.p-\[1px\]{padding:1px}.p-\[8px\]{padding:8px}.px-2{padding-left:.5rem;padding-right:.5rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-4{padding-left:1rem;padding-right:1rem}.px-6{padding-left:1.5rem;padding-right:1.5rem}.px-8{padding-left:2rem;padding-right:2rem}.py-1{padding-top:.25rem;padding-bottom:.25rem}.py-1\.5{padding-top:.375rem;padding-bottom:.375rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.py-3{padding-top:.75rem;padding-bottom:.75rem}.py-4{padding-top:1rem;padding-bottom:1rem}.py-\[6px\]{padding-top:6px;padding-bottom:6px}.pb-4{padding-bottom:1rem}.pl-2{padding-left:.5rem}.pl-4{padding-left:1rem}.pl-8{padding-left:2rem}.pl-\[30px\]{padding-left:30px}.pl-\[8px\]{padding-left:8px}.pr-1{padding-right:.25rem}.pr-2{padding-right:.5rem}.pr-3{padding-right:.75rem}.pr-4{padding-right:1rem}.pr-6{padding-right:1.5rem}.pr-8{padding-right:2rem}.pr-\[8px\]{padding-right:8px}.pt-0{padding-top:0}.pt-4{padding-top:1rem}.text-center{text-align:center}.text-2xl{font-size:1.5rem;line-height:2rem}.text-\[0\.8rem\]{font-size:.8rem}.text-base{font-size:1rem;line-height:1.5rem}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xs{font-size:.75rem;line-height:1rem}.font-medium{font-weight:500}.font-semibold{font-weight:600}.leading-none{line-height:1}.tracking-tight{letter-spacing:-.025em}.tracking-widest{letter-spacing:.1em}.text-destructive{color:hsl(var(--destructive))}.text-destructive-foreground{color:hsl(var(--destructive-foreground))}.text-foreground{color:hsl(var(--foreground))}.text-foreground\/50{color:hsl(var(--foreground) / .5)}.text-gray-200{--tw-text-opacity: 1;color:rgb(229 231 235 / var(--tw-text-opacity))}.text-muted-foreground{color:hsl(var(--muted-foreground))}.text-popover-foreground{color:hsl(var(--popover-foreground))}.text-primary{color:hsl(var(--primary))}.text-primary-foreground{color:hsl(var(--primary-foreground))}.text-secondary-foreground{color:hsl(var(--secondary-foreground))}.underline-offset-4{text-underline-offset:4px}.opacity-0{opacity:0}.opacity-50{opacity:.5}.opacity-60{opacity:.6}.opacity-70{opacity:.7}.opacity-90{opacity:.9}.shadow{--tw-shadow: 0 1px 3px 0 rgb(0 0 0 / .1), 0 1px 2px -1px rgb(0 0 0 / .1);--tw-shadow-colored: 0 1px 3px 0 var(--tw-shadow-color), 0 1px 2px -1px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-lg{--tw-shadow: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1);--tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-md{--tw-shadow: 0 4px 6px -1px rgb(0 0 0 / .1), 0 2px 4px -2px rgb(0 0 0 / .1);--tw-shadow-colored: 0 4px 6px -1px var(--tw-shadow-color), 0 2px 4px -2px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-sm{--tw-shadow: 0 1px 2px 0 rgb(0 0 0 / .05);--tw-shadow-colored: 0 1px 2px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.outline-none{outline:2px solid transparent;outline-offset:2px}.outline{outline-style:solid}.outline-dashed{outline-style:dashed}.outline-8{outline-width:8px}.outline-\[rgba\(255\,89\,95\,0\.31\)\]{outline-color:#ff595f4f}.outline-\[rgba\(98\,255\,179\,0\.31\)\]{outline-color:#62ffb34f}.outline-primary{outline-color:hsl(var(--primary))}.ring-0{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(0px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.ring-offset-background{--tw-ring-offset-color: hsl(var(--background))}.blur{--tw-blur: blur(8px);filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.backdrop-blur-md{--tw-backdrop-blur: blur(12px);-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.backdrop-blur-sm{--tw-backdrop-blur: blur(4px);-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.backdrop-filter{-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.transition{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,-webkit-backdrop-filter;transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter;transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter,-webkit-backdrop-filter;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-all{transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-colors{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-opacity{transition-property:opacity;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-transform{transition-property:transform;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.duration-200{transition-duration:.2s}.ease-in-out{transition-timing-function:cubic-bezier(.4,0,.2,1)}.content-\[\'\'\]{--tw-content: "";content:var(--tw-content)}@keyframes enter{0%{opacity:var(--tw-enter-opacity, 1);transform:translate3d(var(--tw-enter-translate-x, 0),var(--tw-enter-translate-y, 0),0) scale3d(var(--tw-enter-scale, 1),var(--tw-enter-scale, 1),var(--tw-enter-scale, 1)) rotate(var(--tw-enter-rotate, 0))}}@keyframes exit{to{opacity:var(--tw-exit-opacity, 1);transform:translate3d(var(--tw-exit-translate-x, 0),var(--tw-exit-translate-y, 0),0) scale3d(var(--tw-exit-scale, 1),var(--tw-exit-scale, 1),var(--tw-exit-scale, 1)) rotate(var(--tw-exit-rotate, 0))}}.animate-in{animation-name:enter;animation-duration:.15s;--tw-enter-opacity: initial;--tw-enter-scale: initial;--tw-enter-rotate: initial;--tw-enter-translate-x: initial;--tw-enter-translate-y: initial}.fade-in-0{--tw-enter-opacity: 0}.zoom-in-95{--tw-enter-scale: .95}.duration-200{animation-duration:.2s}.ease-in-out{animation-timing-function:cubic-bezier(.4,0,.2,1)}.\[background-size\:20px_20px\]{background-size:20px 20px}.\[box-shadow\:0_0_0_0_rgba\(21\,_215\,_121\,_0\.936\)\]{box-shadow:0 0 #15d779ef}.\[box-shadow\:0_0_0_9999px_rgba\(0\,_0\,_0\,_0\.5\)\]{box-shadow:0 0 0 9999px #00000080}.\[grid-area\:editor-content\]{grid-area:editor-content}.\[grid-area\:original-image-content\]{grid-area:original-image-content}.\[grid-template-areas\:\'editor-content\'\]{grid-template-areas:"editor-content"}.\[grid-template-areas\:\'original-image-content\'\]{grid-template-areas:"original-image-content"}html{font-family:Inter,"system-ui";overflow:hidden}@supports (font-variation-settings: normal){html{font-family:Inter var,"system-ui"}}.react-transform-wrapper{display:grid!important;width:100%!important;height:100%!important}.react-photo-album{padding:8px}.react-photo-album--photo{-moz-user-select:none;-webkit-user-select:none;user-select:none;border-radius:8px;transition:transform .25s,visibility .25s ease-in}.react-photo-album--photo:hover{border:1px solid var(--border);transform:scale(1.03)}.icon-button-icon-wrapper svg{stroke-width:1px}.file\:border-0::file-selector-button{border-width:0px}.file\:bg-transparent::file-selector-button{background-color:transparent}.file\:text-sm::file-selector-button{font-size:.875rem;line-height:1.25rem}.file\:font-medium::file-selector-button{font-weight:500}.placeholder\:text-muted-foreground::-moz-placeholder{color:hsl(var(--muted-foreground))}.placeholder\:text-muted-foreground::placeholder{color:hsl(var(--muted-foreground))}.hover\:cursor-move:hover{cursor:move}.hover\:bg-accent:hover{background-color:hsl(var(--accent))}.hover\:bg-destructive\/90:hover{background-color:hsl(var(--destructive) / .9)}.hover\:bg-muted:hover{background-color:hsl(var(--muted))}.hover\:bg-primary:hover{background-color:hsl(var(--primary))}.hover\:bg-primary\/90:hover{background-color:hsl(var(--primary) / .9)}.hover\:bg-secondary:hover{background-color:hsl(var(--secondary))}.hover\:bg-secondary\/80:hover{background-color:hsl(var(--secondary) / .8)}.hover\:text-accent-foreground:hover{color:hsl(var(--accent-foreground))}.hover\:text-foreground:hover{color:hsl(var(--foreground))}.hover\:text-muted-foreground:hover{color:hsl(var(--muted-foreground))}.hover\:text-primary-foreground:hover{color:hsl(var(--primary-foreground))}.hover\:underline:hover{text-decoration-line:underline}.hover\:opacity-100:hover{opacity:1}.focus\:bg-accent:focus{background-color:hsl(var(--accent))}.focus\:text-accent-foreground:focus{color:hsl(var(--accent-foreground))}.focus\:opacity-100:focus{opacity:1}.focus\:outline-none:focus{outline:2px solid transparent;outline-offset:2px}.focus\:ring-1:focus{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus\:ring-2:focus{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus\:ring-ring:focus{--tw-ring-color: hsl(var(--ring))}.focus\:ring-offset-2:focus{--tw-ring-offset-width: 2px}.focus-visible\:outline-none:focus-visible{outline:2px solid transparent;outline-offset:2px}.focus-visible\:ring-1:focus-visible{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus-visible\:ring-2:focus-visible{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus-visible\:ring-ring:focus-visible{--tw-ring-color: hsl(var(--ring))}.focus-visible\:ring-offset-2:focus-visible{--tw-ring-offset-width: 2px}.focus-visible\:ring-offset-background:focus-visible{--tw-ring-offset-color: hsl(var(--background))}.disabled\:pointer-events-none:disabled{pointer-events:none}.disabled\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\:opacity-50:disabled{opacity:.5}.group:hover .group-hover\:opacity-100{opacity:1}.group.destructive .group-\[\.destructive\]\:border-muted\/40{border-color:hsl(var(--muted) / .4)}.group.destructive .group-\[\.destructive\]\:text-red-300{--tw-text-opacity: 1;color:rgb(252 165 165 / var(--tw-text-opacity))}.group.destructive .group-\[\.destructive\]\:hover\:border-destructive\/30:hover{border-color:hsl(var(--destructive) / .3)}.group.destructive .group-\[\.destructive\]\:hover\:bg-destructive:hover{background-color:hsl(var(--destructive))}.group.destructive .group-\[\.destructive\]\:hover\:text-destructive-foreground:hover{color:hsl(var(--destructive-foreground))}.group.destructive .group-\[\.destructive\]\:hover\:text-red-50:hover{--tw-text-opacity: 1;color:rgb(254 242 242 / var(--tw-text-opacity))}.group.destructive .group-\[\.destructive\]\:focus\:ring-destructive:focus{--tw-ring-color: hsl(var(--destructive))}.group.destructive .group-\[\.destructive\]\:focus\:ring-red-400:focus{--tw-ring-opacity: 1;--tw-ring-color: rgb(248 113 113 / var(--tw-ring-opacity))}.group.destructive .group-\[\.destructive\]\:focus\:ring-offset-red-600:focus{--tw-ring-offset-color: #dc2626}.peer:disabled~.peer-disabled\:cursor-not-allowed{cursor:not-allowed}.peer:disabled~.peer-disabled\:opacity-70{opacity:.7}.data-\[disabled\]\:pointer-events-none[data-disabled]{pointer-events:none}.data-\[side\=bottom\]\:translate-y-1[data-side=bottom]{--tw-translate-y: .25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[side\=left\]\:-translate-x-1[data-side=left]{--tw-translate-x: -.25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[side\=right\]\:translate-x-1[data-side=right]{--tw-translate-x: .25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[side\=top\]\:-translate-y-1[data-side=top]{--tw-translate-y: -.25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[state\=checked\]\:translate-x-4[data-state=checked]{--tw-translate-x: 1rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[state\=unchecked\]\:translate-x-0[data-state=unchecked],.data-\[swipe\=cancel\]\:translate-x-0[data-swipe=cancel]{--tw-translate-x: 0px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[swipe\=end\]\:translate-x-\[var\(--radix-toast-swipe-end-x\)\][data-swipe=end]{--tw-translate-x: var(--radix-toast-swipe-end-x);transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[swipe\=move\]\:translate-x-\[var\(--radix-toast-swipe-move-x\)\][data-swipe=move]{--tw-translate-x: var(--radix-toast-swipe-move-x);transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}@keyframes accordion-up{0%{height:var(--radix-accordion-content-height)}to{height:0}}.data-\[state\=closed\]\:animate-accordion-up[data-state=closed]{animation:accordion-up .2s ease-out}@keyframes accordion-down{0%{height:0}to{height:var(--radix-accordion-content-height)}}.data-\[state\=open\]\:animate-accordion-down[data-state=open]{animation:accordion-down .2s ease-out}.data-\[disabled\]\:cursor-not-allowed[data-disabled]{cursor:not-allowed}.data-\[state\=active\]\:bg-background[data-state=active]{background-color:hsl(var(--background))}.data-\[state\=checked\]\:bg-primary[data-state=checked]{background-color:hsl(var(--primary))}.data-\[state\=on\]\:bg-accent[data-state=on],.data-\[state\=open\]\:bg-accent[data-state=open]{background-color:hsl(var(--accent))}.data-\[state\=unchecked\]\:bg-input[data-state=unchecked]{background-color:hsl(var(--input))}.data-\[state\=active\]\:text-foreground[data-state=active]{color:hsl(var(--foreground))}.data-\[state\=on\]\:text-accent-foreground[data-state=on],.data-\[state\=open\]\:text-accent-foreground[data-state=open]{color:hsl(var(--accent-foreground))}.data-\[state\=open\]\:text-muted-foreground[data-state=open]{color:hsl(var(--muted-foreground))}.data-\[disabled\]\:opacity-50[data-disabled]{opacity:.5}.data-\[state\=active\]\:shadow[data-state=active]{--tw-shadow: 0 1px 3px 0 rgb(0 0 0 / .1), 0 1px 2px -1px rgb(0 0 0 / .1);--tw-shadow-colored: 0 1px 3px 0 var(--tw-shadow-color), 0 1px 2px -1px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.data-\[swipe\=move\]\:transition-none[data-swipe=move]{transition-property:none}.data-\[state\=closed\]\:duration-200[data-state=closed]{transition-duration:.2s}.data-\[state\=open\]\:duration-300[data-state=open]{transition-duration:.3s}.data-\[state\=open\]\:animate-in[data-state=open]{animation-name:enter;animation-duration:.15s;--tw-enter-opacity: initial;--tw-enter-scale: initial;--tw-enter-rotate: initial;--tw-enter-translate-x: initial;--tw-enter-translate-y: initial}.data-\[state\=closed\]\:animate-out[data-state=closed],.data-\[swipe\=end\]\:animate-out[data-swipe=end]{animation-name:exit;animation-duration:.15s;--tw-exit-opacity: initial;--tw-exit-scale: initial;--tw-exit-rotate: initial;--tw-exit-translate-x: initial;--tw-exit-translate-y: initial}.data-\[state\=closed\]\:fade-out-0[data-state=closed]{--tw-exit-opacity: 0}.data-\[state\=closed\]\:fade-out-80[data-state=closed]{--tw-exit-opacity: .8}.data-\[state\=open\]\:fade-in-0[data-state=open]{--tw-enter-opacity: 0}.data-\[state\=closed\]\:zoom-out-95[data-state=closed]{--tw-exit-scale: .95}.data-\[state\=open\]\:zoom-in-95[data-state=open]{--tw-enter-scale: .95}.data-\[side\=bottom\]\:slide-in-from-top-2[data-side=bottom]{--tw-enter-translate-y: -.5rem}.data-\[side\=left\]\:slide-in-from-right-2[data-side=left]{--tw-enter-translate-x: .5rem}.data-\[side\=right\]\:slide-in-from-left-2[data-side=right]{--tw-enter-translate-x: -.5rem}.data-\[side\=top\]\:slide-in-from-bottom-2[data-side=top]{--tw-enter-translate-y: .5rem}.data-\[state\=closed\]\:slide-out-to-bottom[data-state=closed]{--tw-exit-translate-y: 100%}.data-\[state\=closed\]\:slide-out-to-left[data-state=closed]{--tw-exit-translate-x: -100%}.data-\[state\=closed\]\:slide-out-to-left-1\/2[data-state=closed]{--tw-exit-translate-x: -50%}.data-\[state\=closed\]\:slide-out-to-right[data-state=closed],.data-\[state\=closed\]\:slide-out-to-right-full[data-state=closed]{--tw-exit-translate-x: 100%}.data-\[state\=closed\]\:slide-out-to-top[data-state=closed]{--tw-exit-translate-y: -100%}.data-\[state\=closed\]\:slide-out-to-top-\[48\%\][data-state=closed]{--tw-exit-translate-y: -48%}.data-\[state\=open\]\:slide-in-from-bottom[data-state=open]{--tw-enter-translate-y: 100%}.data-\[state\=open\]\:slide-in-from-left[data-state=open]{--tw-enter-translate-x: -100%}.data-\[state\=open\]\:slide-in-from-left-1\/2[data-state=open]{--tw-enter-translate-x: -50%}.data-\[state\=open\]\:slide-in-from-right[data-state=open]{--tw-enter-translate-x: 100%}.data-\[state\=open\]\:slide-in-from-top[data-state=open]{--tw-enter-translate-y: -100%}.data-\[state\=open\]\:slide-in-from-top-\[48\%\][data-state=open]{--tw-enter-translate-y: -48%}.data-\[state\=open\]\:slide-in-from-top-full[data-state=open]{--tw-enter-translate-y: -100%}.data-\[state\=closed\]\:duration-200[data-state=closed]{animation-duration:.2s}.data-\[state\=open\]\:duration-300[data-state=open]{animation-duration:.3s}:is(.dark .dark\:text-gray-600){--tw-text-opacity: 1;color:rgb(75 85 99 / var(--tw-text-opacity))}@media (min-width: 640px){.sm\:bottom-0{bottom:0}.sm\:right-0{right:0}.sm\:top-auto{top:auto}.sm\:mt-0{margin-top:0}.sm\:max-w-sm{max-width:24rem}.sm\:flex-row{flex-direction:row}.sm\:flex-col{flex-direction:column}.sm\:justify-end{justify-content:flex-end}.sm\:space-x-2>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.5rem * var(--tw-space-x-reverse));margin-left:calc(.5rem * calc(1 - var(--tw-space-x-reverse)))}.sm\:rounded-lg{border-radius:var(--radius)}.sm\:text-left{text-align:left}.data-\[state\=open\]\:sm\:slide-in-from-bottom-full[data-state=open]{--tw-enter-translate-y: 100%}}@media (min-width: 768px){.md\:max-w-\[420px\]{max-width:420px}}.\[\&\+div\]\:text-xs+div{font-size:.75rem;line-height:1rem}.\[\&\>span\]\:line-clamp-1>span{overflow:hidden;display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:1}.\[\&\[data-state\=open\]\>svg\]\:rotate-180[data-state=open]>svg{--tw-rotate: 180deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))} diff --git a/py/iopaint/web_app/assets/index-kS3ik1bw.js b/py/iopaint/web_app/assets/index-kS3ik1bw.js new file mode 100644 index 0000000..6350972 --- /dev/null +++ b/py/iopaint/web_app/assets/index-kS3ik1bw.js @@ -0,0 +1,165 @@ +var Lv=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)};var z=(e,t,n)=>(Lv(e,t,"read from private field"),n?n.call(e):t.get(e)),Te=(e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)},ye=(e,t,n,r)=>(Lv(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n);var Hf=(e,t,n,r)=>({set _(o){ye(e,t,o,n)},get _(){return z(e,t,r)}}),tt=(e,t,n)=>(Lv(e,t,"access private method"),n);function $D(e,t){for(var n=0;nr[o]})}}}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 o of document.querySelectorAll('link[rel="modulepreload"]'))r(o);new MutationObserver(o=>{for(const i of o)if(i.type==="childList")for(const s of i.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&r(s)}).observe(document,{childList:!0,subtree:!0});function n(o){const i={};return o.integrity&&(i.integrity=o.integrity),o.referrerPolicy&&(i.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?i.credentials="include":o.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(o){if(o.ep)return;o.ep=!0;const i=n(o);fetch(o.href,i)}})();var Jc=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function dm(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var y$={exports:{}},fm={},w$={exports:{}},it={};/** + * @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 kd=Symbol.for("react.element"),RD=Symbol.for("react.portal"),kD=Symbol.for("react.fragment"),TD=Symbol.for("react.strict_mode"),PD=Symbol.for("react.profiler"),AD=Symbol.for("react.provider"),MD=Symbol.for("react.context"),OD=Symbol.for("react.forward_ref"),ND=Symbol.for("react.suspense"),DD=Symbol.for("react.memo"),ID=Symbol.for("react.lazy"),j_=Symbol.iterator;function LD(e){return e===null||typeof e!="object"?null:(e=j_&&e[j_]||e["@@iterator"],typeof e=="function"?e:null)}var x$={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},b$=Object.assign,S$={};function yc(e,t,n){this.props=e,this.context=t,this.refs=S$,this.updater=n||x$}yc.prototype.isReactComponent={};yc.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")};yc.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function _$(){}_$.prototype=yc.prototype;function nw(e,t,n){this.props=e,this.context=t,this.refs=S$,this.updater=n||x$}var rw=nw.prototype=new _$;rw.constructor=nw;b$(rw,yc.prototype);rw.isPureReactComponent=!0;var z_=Array.isArray,E$=Object.prototype.hasOwnProperty,ow={current:null},C$={key:!0,ref:!0,__self:!0,__source:!0};function $$(e,t,n){var r,o={},i=null,s=null;if(t!=null)for(r in t.ref!==void 0&&(s=t.ref),t.key!==void 0&&(i=""+t.key),t)E$.call(t,r)&&!C$.hasOwnProperty(r)&&(o[r]=t[r]);var l=arguments.length-2;if(l===1)o.children=n;else if(1>>1,ce=K[se];if(0>>1;seo(We,H))Oeo(he,We)?(K[se]=he,K[Oe]=H,se=Oe):(K[se]=We,K[Ue]=H,se=Ue);else if(Oeo(he,H))K[se]=he,K[Oe]=H,se=Oe;else break e}}return Z}function o(K,Z){var H=K.sortIndex-Z.sortIndex;return H!==0?H:K.id-Z.id}if(typeof performance=="object"&&typeof performance.now=="function"){var i=performance;e.unstable_now=function(){return i.now()}}else{var s=Date,l=s.now();e.unstable_now=function(){return s.now()-l}}var u=[],f=[],m=1,p=null,g=3,y=!1,b=!1,S=!1,E=typeof setTimeout=="function"?setTimeout:null,_=typeof clearTimeout=="function"?clearTimeout:null,x=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function C(K){for(var Z=n(f);Z!==null;){if(Z.callback===null)r(f);else if(Z.startTime<=K)r(f),Z.sortIndex=Z.expirationTime,t(u,Z);else break;Z=n(f)}}function R(K){if(S=!1,C(K),!b)if(n(u)!==null)b=!0,N(P);else{var Z=n(f);Z!==null&&ie(R,Z.startTime-K)}}function P(K,Z){b=!1,S&&(S=!1,_(D),D=-1),y=!0;var H=g;try{for(C(Z),p=n(u);p!==null&&(!(p.expirationTime>Z)||K&&!q());){var se=p.callback;if(typeof se=="function"){p.callback=null,g=p.priorityLevel;var ce=se(p.expirationTime<=Z);Z=e.unstable_now(),typeof ce=="function"?p.callback=ce:p===n(u)&&r(u),C(Z)}else r(u);p=n(u)}if(p!==null)var Ve=!0;else{var Ue=n(f);Ue!==null&&ie(R,Ue.startTime-Z),Ve=!1}return Ve}finally{p=null,g=H,y=!1}}var M=!1,A=null,D=-1,U=5,W=-1;function q(){return!(e.unstable_now()-WK||125se?(K.sortIndex=H,t(f,K),n(u)===null&&K===n(f)&&(S?(_(D),D=-1):S=!0,ie(R,H-se))):(K.sortIndex=ce,t(u,K),b||y||(b=!0,N(P))),K},e.unstable_shouldYield=q,e.unstable_wrapCallback=function(K){var Z=g;return function(){var H=g;g=Z;try{return K.apply(this,arguments)}finally{g=H}}}})(P$);T$.exports=P$;var XD=T$.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 A$=d,yr=XD;function ue(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"),W0=Object.prototype.hasOwnProperty,ZD=/^[: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]*$/,U_={},V_={};function qD(e){return W0.call(V_,e)?!0:W0.call(U_,e)?!1:ZD.test(e)?V_[e]=!0:(U_[e]=!0,!1)}function QD(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 JD(e,t,n,r){if(t===null||typeof t>"u"||QD(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 Un(e,t,n,r,o,i,s){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=o,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=i,this.removeEmptyString=s}var bn={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){bn[e]=new Un(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];bn[t]=new Un(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){bn[e]=new Un(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){bn[e]=new Un(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){bn[e]=new Un(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){bn[e]=new Un(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){bn[e]=new Un(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){bn[e]=new Un(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){bn[e]=new Un(e,5,!1,e.toLowerCase(),null,!1,!1)});var sw=/[\-:]([a-z])/g;function aw(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(sw,aw);bn[t]=new Un(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(sw,aw);bn[t]=new Un(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(sw,aw);bn[t]=new Un(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){bn[e]=new Un(e,1,!1,e.toLowerCase(),null,!1,!1)});bn.xlinkHref=new Un("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){bn[e]=new Un(e,1,!1,e.toLowerCase(),null,!0,!0)});function lw(e,t,n,r){var o=bn.hasOwnProperty(t)?bn[t]:null;(o!==null?o.type!==0:r||!(2l||o[s]!==i[l]){var u=` +`+o[s].replace(" at new "," at ");return e.displayName&&u.includes("")&&(u=u.replace("",e.displayName)),u}while(1<=s&&0<=l);break}}}finally{zv=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?vu(e):""}function e9(e){switch(e.tag){case 5:return vu(e.type);case 16:return vu("Lazy");case 13:return vu("Suspense");case 19:return vu("SuspenseList");case 0:case 2:case 15:return e=Bv(e.type,!1),e;case 11:return e=Bv(e.type.render,!1),e;case 1:return e=Bv(e.type,!0),e;default:return""}}function Y0(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 ml:return"Fragment";case pl:return"Portal";case H0:return"Profiler";case cw:return"StrictMode";case K0:return"Suspense";case G0:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case N$:return(e.displayName||"Context")+".Consumer";case O$:return(e._context.displayName||"Context")+".Provider";case uw:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case dw:return t=e.displayName||null,t!==null?t:Y0(e.type)||"Memo";case Ji:t=e._payload,e=e._init;try{return Y0(e(t))}catch{}}return null}function t9(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 Y0(t);case 8:return t===cw?"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 Rs(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function I$(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function n9(e){var t=I$(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 o=n.get,i=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return o.call(this)},set:function(s){r=""+s,i.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 Yf(e){e._valueTracker||(e._valueTracker=n9(e))}function L$(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=I$(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function ap(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 X0(e,t){var n=t.checked;return zt({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function H_(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=Rs(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 F$(e,t){t=t.checked,t!=null&&lw(e,"checked",t,!1)}function Z0(e,t){F$(e,t);var n=Rs(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")?q0(e,t.type,n):t.hasOwnProperty("defaultValue")&&q0(e,t.type,Rs(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function K_(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 q0(e,t,n){(t!=="number"||ap(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var yu=Array.isArray;function Rl(e,t,n,r){if(e=e.options,t){t={};for(var o=0;o"+t.valueOf().toString()+"",t=Xf.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function ju(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var Eu={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},r9=["Webkit","ms","Moz","O"];Object.keys(Eu).forEach(function(e){r9.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),Eu[t]=Eu[e]})});function U$(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||Eu.hasOwnProperty(e)&&Eu[e]?(""+t).trim():t+"px"}function V$(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,o=U$(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,o):e[n]=o}}var o9=zt({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 ey(e,t){if(t){if(o9[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(ue(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(ue(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(ue(61))}if(t.style!=null&&typeof t.style!="object")throw Error(ue(62))}}function ty(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 ny=null;function fw(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var ry=null,kl=null,Tl=null;function X_(e){if(e=Ad(e)){if(typeof ry!="function")throw Error(ue(280));var t=e.stateNode;t&&(t=vm(t),ry(e.stateNode,e.type,t))}}function W$(e){kl?Tl?Tl.push(e):Tl=[e]:kl=e}function H$(){if(kl){var e=kl,t=Tl;if(Tl=kl=null,X_(e),t)for(e=0;e>>=0,e===0?32:31-(m9(e)/g9|0)|0}var Zf=64,qf=4194304;function wu(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 dp(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,o=e.suspendedLanes,i=e.pingedLanes,s=n&268435455;if(s!==0){var l=s&~o;l!==0?r=wu(l):(i&=s,i!==0&&(r=wu(i)))}else s=n&~o,s!==0?r=wu(s):i!==0&&(r=wu(i));if(r===0)return 0;if(t!==0&&t!==r&&!(t&o)&&(o=r&-r,i=t&-t,o>=i||o===16&&(i&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 Td(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-wo(t),e[t]=n}function x9(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=$u),oE=" ",iE=!1;function dR(e,t){switch(e){case"keyup":return Y9.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function fR(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var gl=!1;function Z9(e,t){switch(e){case"compositionend":return fR(t);case"keypress":return t.which!==32?null:(iE=!0,oE);case"textInput":return e=t.data,e===oE&&iE?null:e;default:return null}}function q9(e,t){if(gl)return e==="compositionend"||!xw&&dR(e,t)?(e=cR(),Oh=vw=us=null,gl=!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=cE(n)}}function gR(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?gR(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function vR(){for(var e=window,t=ap();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=ap(e.document)}return t}function bw(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 sI(e){var t=vR(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&gR(n.ownerDocument.documentElement,n)){if(r!==null&&bw(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 o=n.textContent.length,i=Math.min(r.start,o);r=r.end===void 0?i:Math.min(r.end,o),!e.extend&&i>r&&(o=r,r=i,i=o),o=uE(n,i);var s=uE(n,r);o&&s&&(e.rangeCount!==1||e.anchorNode!==o.node||e.anchorOffset!==o.offset||e.focusNode!==s.node||e.focusOffset!==s.offset)&&(t=t.createRange(),t.setStart(o.node,o.offset),e.removeAllRanges(),i>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,vl=null,cy=null,ku=null,uy=!1;function dE(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;uy||vl==null||vl!==ap(r)||(r=vl,"selectionStart"in r&&bw(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}),ku&&Hu(ku,r)||(ku=r,r=pp(cy,"onSelect"),0xl||(e.current=gy[xl],gy[xl]=null,xl--)}function $t(e,t){xl++,gy[xl]=e.current,e.current=t}var ks={},Pn=Ns(ks),Jn=Ns(!1),Ra=ks;function Ql(e,t){var n=e.type.contextTypes;if(!n)return ks;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var o={},i;for(i in n)o[i]=t[i];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=o),o}function er(e){return e=e.childContextTypes,e!=null}function gp(){At(Jn),At(Pn)}function yE(e,t,n){if(Pn.current!==ks)throw Error(ue(168));$t(Pn,t),$t(Jn,n)}function $R(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var o in r)if(!(o in t))throw Error(ue(108,t9(e)||"Unknown",o));return zt({},n,r)}function vp(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||ks,Ra=Pn.current,$t(Pn,e),$t(Jn,Jn.current),!0}function wE(e,t,n){var r=e.stateNode;if(!r)throw Error(ue(169));n?(e=$R(e,t,Ra),r.__reactInternalMemoizedMergedChildContext=e,At(Jn),At(Pn),$t(Pn,e)):At(Jn),$t(Jn,n)}var pi=null,ym=!1,t0=!1;function RR(e){pi===null?pi=[e]:pi.push(e)}function yI(e){ym=!0,RR(e)}function Ds(){if(!t0&&pi!==null){t0=!0;var e=0,t=xt;try{var n=pi;for(xt=1;e>=s,o-=s,mi=1<<32-wo(t)+o|n<D?(U=A,A=null):U=A.sibling;var W=g(_,A,C[D],R);if(W===null){A===null&&(A=U);break}e&&A&&W.alternate===null&&t(_,A),x=i(W,x,D),M===null?P=W:M.sibling=W,M=W,A=U}if(D===C.length)return n(_,A),Dt&&ta(_,D),P;if(A===null){for(;DD?(U=A,A=null):U=A.sibling;var q=g(_,A,W.value,R);if(q===null){A===null&&(A=U);break}e&&A&&q.alternate===null&&t(_,A),x=i(q,x,D),M===null?P=q:M.sibling=q,M=q,A=U}if(W.done)return n(_,A),Dt&&ta(_,D),P;if(A===null){for(;!W.done;D++,W=C.next())W=p(_,W.value,R),W!==null&&(x=i(W,x,D),M===null?P=W:M.sibling=W,M=W);return Dt&&ta(_,D),P}for(A=r(_,A);!W.done;D++,W=C.next())W=y(A,_,D,W.value,R),W!==null&&(e&&W.alternate!==null&&A.delete(W.key===null?D:W.key),x=i(W,x,D),M===null?P=W:M.sibling=W,M=W);return e&&A.forEach(function(X){return t(_,X)}),Dt&&ta(_,D),P}function E(_,x,C,R){if(typeof C=="object"&&C!==null&&C.type===ml&&C.key===null&&(C=C.props.children),typeof C=="object"&&C!==null){switch(C.$$typeof){case Gf:e:{for(var P=C.key,M=x;M!==null;){if(M.key===P){if(P=C.type,P===ml){if(M.tag===7){n(_,M.sibling),x=o(M,C.props.children),x.return=_,_=x;break e}}else if(M.elementType===P||typeof P=="object"&&P!==null&&P.$$typeof===Ji&&$E(P)===M.type){n(_,M.sibling),x=o(M,C.props),x.ref=iu(_,M,C),x.return=_,_=x;break e}n(_,M);break}else t(_,M);M=M.sibling}C.type===ml?(x=$a(C.props.children,_.mode,R,C.key),x.return=_,_=x):(R=Bh(C.type,C.key,C.props,null,_.mode,R),R.ref=iu(_,x,C),R.return=_,_=R)}return s(_);case pl:e:{for(M=C.key;x!==null;){if(x.key===M)if(x.tag===4&&x.stateNode.containerInfo===C.containerInfo&&x.stateNode.implementation===C.implementation){n(_,x.sibling),x=o(x,C.children||[]),x.return=_,_=x;break e}else{n(_,x);break}else t(_,x);x=x.sibling}x=c0(C,_.mode,R),x.return=_,_=x}return s(_);case Ji:return M=C._init,E(_,x,M(C._payload),R)}if(yu(C))return b(_,x,C,R);if(eu(C))return S(_,x,C,R);oh(_,C)}return typeof C=="string"&&C!==""||typeof C=="number"?(C=""+C,x!==null&&x.tag===6?(n(_,x.sibling),x=o(x,C),x.return=_,_=x):(n(_,x),x=l0(C,_.mode,R),x.return=_,_=x),s(_)):n(_,x)}return E}var ec=DR(!0),IR=DR(!1),Md={},Ko=Ns(Md),Xu=Ns(Md),Zu=Ns(Md);function fa(e){if(e===Md)throw Error(ue(174));return e}function Pw(e,t){switch($t(Zu,t),$t(Xu,e),$t(Ko,Md),e=t.nodeType,e){case 9:case 11:t=(t=t.documentElement)?t.namespaceURI:J0(null,"");break;default:e=e===8?t.parentNode:t,t=e.namespaceURI||null,e=e.tagName,t=J0(t,e)}At(Ko),$t(Ko,t)}function tc(){At(Ko),At(Xu),At(Zu)}function LR(e){fa(Zu.current);var t=fa(Ko.current),n=J0(t,e.type);t!==n&&($t(Xu,e),$t(Ko,n))}function Aw(e){Xu.current===e&&(At(Ko),At(Xu))}var Lt=Ns(0);function _p(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 n0=[];function Mw(){for(var e=0;en?n:4,e(!0);var r=r0.transition;r0.transition={};try{e(!1),t()}finally{xt=n,r0.transition=r}}function JR(){return Yr().memoizedState}function SI(e,t,n){var r=Ss(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},ek(e))tk(t,n);else if(n=AR(e,t,n,r),n!==null){var o=jn();xo(n,e,r,o),nk(n,t,r)}}function _I(e,t,n){var r=Ss(e),o={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(ek(e))tk(t,o);else{var i=e.alternate;if(e.lanes===0&&(i===null||i.lanes===0)&&(i=t.lastRenderedReducer,i!==null))try{var s=t.lastRenderedState,l=i(s,n);if(o.hasEagerState=!0,o.eagerState=l,So(l,s)){var u=t.interleaved;u===null?(o.next=o,kw(t)):(o.next=u.next,u.next=o),t.interleaved=o;return}}catch{}finally{}n=AR(e,t,o,r),n!==null&&(o=jn(),xo(n,e,r,o),nk(n,t,r))}}function ek(e){var t=e.alternate;return e===jt||t!==null&&t===jt}function tk(e,t){Tu=Ep=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function nk(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,pw(e,n)}}var Cp={readContext:Gr,useCallback:$n,useContext:$n,useEffect:$n,useImperativeHandle:$n,useInsertionEffect:$n,useLayoutEffect:$n,useMemo:$n,useReducer:$n,useRef:$n,useState:$n,useDebugValue:$n,useDeferredValue:$n,useTransition:$n,useMutableSource:$n,useSyncExternalStore:$n,useId:$n,unstable_isNewReconciler:!1},EI={readContext:Gr,useCallback:function(e,t){return Po().memoizedState=[e,t===void 0?null:t],e},useContext:Gr,useEffect:kE,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,Lh(4194308,4,YR.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Lh(4194308,4,e,t)},useInsertionEffect:function(e,t){return Lh(4,2,e,t)},useMemo:function(e,t){var n=Po();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=Po();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=SI.bind(null,jt,e),[r.memoizedState,e]},useRef:function(e){var t=Po();return e={current:e},t.memoizedState=e},useState:RE,useDebugValue:Lw,useDeferredValue:function(e){return Po().memoizedState=e},useTransition:function(){var e=RE(!1),t=e[0];return e=bI.bind(null,e[1]),Po().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=jt,o=Po();if(Dt){if(n===void 0)throw Error(ue(407));n=n()}else{if(n=t(),dn===null)throw Error(ue(349));Ta&30||zR(r,t,n)}o.memoizedState=n;var i={value:n,getSnapshot:t};return o.queue=i,kE(UR.bind(null,r,i,e),[e]),r.flags|=2048,Ju(9,BR.bind(null,r,i,n,t),void 0,null),n},useId:function(){var e=Po(),t=dn.identifierPrefix;if(Dt){var n=gi,r=mi;n=(r&~(1<<32-wo(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=qu++,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[Io]=t,e[Yu]=r,dk(e,t,!1,!1),t.stateNode=e;e:{switch(s=ty(n,r),n){case"dialog":Tt("cancel",e),Tt("close",e),o=r;break;case"iframe":case"object":case"embed":Tt("load",e),o=r;break;case"video":case"audio":for(o=0;orc&&(t.flags|=128,r=!0,su(i,!1),t.lanes=4194304)}else{if(!r)if(e=_p(s),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),su(i,!0),i.tail===null&&i.tailMode==="hidden"&&!s.alternate&&!Dt)return Rn(t),null}else 2*Xt()-i.renderingStartTime>rc&&n!==1073741824&&(t.flags|=128,r=!0,su(i,!1),t.lanes=4194304);i.isBackwards?(s.sibling=t.child,t.child=s):(n=i.last,n!==null?n.sibling=s:t.child=s,i.last=s)}return i.tail!==null?(t=i.tail,i.rendering=t,i.tail=t.sibling,i.renderingStartTime=Xt(),t.sibling=null,n=Lt.current,$t(Lt,r?n&1|2:n&1),t):(Rn(t),null);case 22:case 23:return Vw(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?fr&1073741824&&(Rn(t),t.subtreeFlags&6&&(t.flags|=8192)):Rn(t),null;case 24:return null;case 25:return null}throw Error(ue(156,t.tag))}function MI(e,t){switch(_w(t),t.tag){case 1:return er(t.type)&&gp(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return tc(),At(Jn),At(Pn),Mw(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return Aw(t),null;case 13:if(At(Lt),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(ue(340));Jl()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return At(Lt),null;case 4:return tc(),null;case 10:return Rw(t.type._context),null;case 22:case 23:return Vw(),null;case 24:return null;default:return null}}var sh=!1,Tn=!1,OI=typeof WeakSet=="function"?WeakSet:Set,_e=null;function El(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){Wt(e,t,r)}else n.current=null}function ky(e,t,n){try{n()}catch(r){Wt(e,t,r)}}var LE=!1;function NI(e,t){if(dy=fp,e=vR(),bw(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 o=r.anchorOffset,i=r.focusNode;r=r.focusOffset;try{n.nodeType,i.nodeType}catch{n=null;break e}var s=0,l=-1,u=-1,f=0,m=0,p=e,g=null;t:for(;;){for(var y;p!==n||o!==0&&p.nodeType!==3||(l=s+o),p!==i||r!==0&&p.nodeType!==3||(u=s+r),p.nodeType===3&&(s+=p.nodeValue.length),(y=p.firstChild)!==null;)g=p,p=y;for(;;){if(p===e)break t;if(g===n&&++f===o&&(l=s),g===i&&++m===r&&(u=s),(y=p.nextSibling)!==null)break;p=g,g=p.parentNode}p=y}n=l===-1||u===-1?null:{start:l,end:u}}else n=null}n=n||{start:0,end:0}}else n=null;for(fy={focusedElem:e,selectionRange:n},fp=!1,_e=t;_e!==null;)if(t=_e,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,_e=e;else for(;_e!==null;){t=_e;try{var b=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(b!==null){var S=b.memoizedProps,E=b.memoizedState,_=t.stateNode,x=_.getSnapshotBeforeUpdate(t.elementType===t.type?S:io(t.type,S),E);_.__reactInternalSnapshotBeforeUpdate=x}break;case 3:var C=t.stateNode.containerInfo;C.nodeType===1?C.textContent="":C.nodeType===9&&C.documentElement&&C.removeChild(C.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(ue(163))}}catch(R){Wt(t,t.return,R)}if(e=t.sibling,e!==null){e.return=t.return,_e=e;break}_e=t.return}return b=LE,LE=!1,b}function Pu(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var o=r=r.next;do{if((o.tag&e)===e){var i=o.destroy;o.destroy=void 0,i!==void 0&&ky(t,n,i)}o=o.next}while(o!==r)}}function bm(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 Ty(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 pk(e){var t=e.alternate;t!==null&&(e.alternate=null,pk(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Io],delete t[Yu],delete t[my],delete t[gI],delete t[vI])),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 mk(e){return e.tag===5||e.tag===3||e.tag===4}function FE(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||mk(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 Py(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=mp));else if(r!==4&&(e=e.child,e!==null))for(Py(e,t,n),e=e.sibling;e!==null;)Py(e,t,n),e=e.sibling}function Ay(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(Ay(e,t,n),e=e.sibling;e!==null;)Ay(e,t,n),e=e.sibling}var mn=null,lo=!1;function Ki(e,t,n){for(n=n.child;n!==null;)gk(e,t,n),n=n.sibling}function gk(e,t,n){if(Ho&&typeof Ho.onCommitFiberUnmount=="function")try{Ho.onCommitFiberUnmount(hm,n)}catch{}switch(n.tag){case 5:Tn||El(n,t);case 6:var r=mn,o=lo;mn=null,Ki(e,t,n),mn=r,lo=o,mn!==null&&(lo?(e=mn,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):mn.removeChild(n.stateNode));break;case 18:mn!==null&&(lo?(e=mn,n=n.stateNode,e.nodeType===8?e0(e.parentNode,n):e.nodeType===1&&e0(e,n),Vu(e)):e0(mn,n.stateNode));break;case 4:r=mn,o=lo,mn=n.stateNode.containerInfo,lo=!0,Ki(e,t,n),mn=r,lo=o;break;case 0:case 11:case 14:case 15:if(!Tn&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){o=r=r.next;do{var i=o,s=i.destroy;i=i.tag,s!==void 0&&(i&2||i&4)&&ky(n,t,s),o=o.next}while(o!==r)}Ki(e,t,n);break;case 1:if(!Tn&&(El(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(l){Wt(n,t,l)}Ki(e,t,n);break;case 21:Ki(e,t,n);break;case 22:n.mode&1?(Tn=(r=Tn)||n.memoizedState!==null,Ki(e,t,n),Tn=r):Ki(e,t,n);break;default:Ki(e,t,n)}}function jE(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new OI),t.forEach(function(r){var o=VI.bind(null,e,r);n.has(r)||(n.add(r),r.then(o,o))})}}function ro(e,t){var n=t.deletions;if(n!==null)for(var r=0;ro&&(o=s),r&=~i}if(r=o,r=Xt()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*II(r/1960))-r,10e?16:e,ds===null)var r=!1;else{if(e=ds,ds=null,kp=0,dt&6)throw Error(ue(331));var o=dt;for(dt|=4,_e=e.current;_e!==null;){var i=_e,s=i.child;if(_e.flags&16){var l=i.deletions;if(l!==null){for(var u=0;uXt()-Bw?Ca(e,0):zw|=n),tr(e,t)}function Ek(e,t){t===0&&(e.mode&1?(t=qf,qf<<=1,!(qf&130023424)&&(qf=4194304)):t=1);var n=jn();e=_i(e,t),e!==null&&(Td(e,t,n),tr(e,n))}function UI(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),Ek(e,n)}function VI(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,o=e.memoizedState;o!==null&&(n=o.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(ue(314))}r!==null&&r.delete(t),Ek(e,n)}var Ck;Ck=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||Jn.current)Qn=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return Qn=!1,PI(e,t,n);Qn=!!(e.flags&131072)}else Qn=!1,Dt&&t.flags&1048576&&kR(t,wp,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;Fh(e,t),e=t.pendingProps;var o=Ql(t,Pn.current);Al(t,n),o=Nw(null,t,r,e,o,n);var i=Dw();return t.flags|=1,typeof o=="object"&&o!==null&&typeof o.render=="function"&&o.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,er(r)?(i=!0,vp(t)):i=!1,t.memoizedState=o.state!==null&&o.state!==void 0?o.state:null,Tw(t),o.updater=wm,t.stateNode=o,o._reactInternals=t,by(t,r,e,n),t=Ey(null,t,r,!0,i,n)):(t.tag=0,Dt&&i&&Sw(t),In(null,t,o,n),t=t.child),t;case 16:r=t.elementType;e:{switch(Fh(e,t),e=t.pendingProps,o=r._init,r=o(r._payload),t.type=r,o=t.tag=HI(r),e=io(r,e),o){case 0:t=_y(null,t,r,e,n);break e;case 1:t=NE(null,t,r,e,n);break e;case 11:t=ME(null,t,r,e,n);break e;case 14:t=OE(null,t,r,io(r.type,e),n);break e}throw Error(ue(306,r,""))}return t;case 0:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),_y(e,t,r,o,n);case 1:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),NE(e,t,r,o,n);case 3:e:{if(lk(t),e===null)throw Error(ue(387));r=t.pendingProps,i=t.memoizedState,o=i.element,MR(e,t),Sp(t,r,null,n);var s=t.memoizedState;if(r=s.element,i.isDehydrated)if(i={element:r,isDehydrated:!1,cache:s.cache,pendingSuspenseBoundaries:s.pendingSuspenseBoundaries,transitions:s.transitions},t.updateQueue.baseState=i,t.memoizedState=i,t.flags&256){o=nc(Error(ue(423)),t),t=DE(e,t,r,n,o);break e}else if(r!==o){o=nc(Error(ue(424)),t),t=DE(e,t,r,n,o);break e}else for(mr=ws(t.stateNode.containerInfo.firstChild),gr=t,Dt=!0,ho=null,n=IR(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(Jl(),r===o){t=Ei(e,t,n);break e}In(e,t,r,n)}t=t.child}return t;case 5:return LR(t),e===null&&yy(t),r=t.type,o=t.pendingProps,i=e!==null?e.memoizedProps:null,s=o.children,hy(r,o)?s=null:i!==null&&hy(r,i)&&(t.flags|=32),ak(e,t),In(e,t,s,n),t.child;case 6:return e===null&&yy(t),null;case 13:return ck(e,t,n);case 4:return Pw(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=ec(t,null,r,n):In(e,t,r,n),t.child;case 11:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),ME(e,t,r,o,n);case 7:return In(e,t,t.pendingProps,n),t.child;case 8:return In(e,t,t.pendingProps.children,n),t.child;case 12:return In(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,o=t.pendingProps,i=t.memoizedProps,s=o.value,$t(xp,r._currentValue),r._currentValue=s,i!==null)if(So(i.value,s)){if(i.children===o.children&&!Jn.current){t=Ei(e,t,n);break e}}else for(i=t.child,i!==null&&(i.return=t);i!==null;){var l=i.dependencies;if(l!==null){s=i.child;for(var u=l.firstContext;u!==null;){if(u.context===r){if(i.tag===1){u=wi(-1,n&-n),u.tag=2;var f=i.updateQueue;if(f!==null){f=f.shared;var m=f.pending;m===null?u.next=u:(u.next=m.next,m.next=u),f.pending=u}}i.lanes|=n,u=i.alternate,u!==null&&(u.lanes|=n),wy(i.return,n,t),l.lanes|=n;break}u=u.next}}else if(i.tag===10)s=i.type===t.type?null:i.child;else if(i.tag===18){if(s=i.return,s===null)throw Error(ue(341));s.lanes|=n,l=s.alternate,l!==null&&(l.lanes|=n),wy(s,n,t),s=i.sibling}else s=i.child;if(s!==null)s.return=i;else for(s=i;s!==null;){if(s===t){s=null;break}if(i=s.sibling,i!==null){i.return=s.return,s=i;break}s=s.return}i=s}In(e,t,o.children,n),t=t.child}return t;case 9:return o=t.type,r=t.pendingProps.children,Al(t,n),o=Gr(o),r=r(o),t.flags|=1,In(e,t,r,n),t.child;case 14:return r=t.type,o=io(r,t.pendingProps),o=io(r.type,o),OE(e,t,r,o,n);case 15:return ik(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),Fh(e,t),t.tag=1,er(r)?(e=!0,vp(t)):e=!1,Al(t,n),NR(t,r,o),by(t,r,o,n),Ey(null,t,r,!0,e,n);case 19:return uk(e,t,n);case 22:return sk(e,t,n)}throw Error(ue(156,t.tag))};function $k(e,t){return Q$(e,t)}function WI(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 Ur(e,t,n,r){return new WI(e,t,n,r)}function Hw(e){return e=e.prototype,!(!e||!e.isReactComponent)}function HI(e){if(typeof e=="function")return Hw(e)?1:0;if(e!=null){if(e=e.$$typeof,e===uw)return 11;if(e===dw)return 14}return 2}function _s(e,t){var n=e.alternate;return n===null?(n=Ur(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 Bh(e,t,n,r,o,i){var s=2;if(r=e,typeof e=="function")Hw(e)&&(s=1);else if(typeof e=="string")s=5;else e:switch(e){case ml:return $a(n.children,o,i,t);case cw:s=8,o|=8;break;case H0:return e=Ur(12,n,t,o|2),e.elementType=H0,e.lanes=i,e;case K0:return e=Ur(13,n,t,o),e.elementType=K0,e.lanes=i,e;case G0:return e=Ur(19,n,t,o),e.elementType=G0,e.lanes=i,e;case D$:return _m(n,o,i,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case O$:s=10;break e;case N$:s=9;break e;case uw:s=11;break e;case dw:s=14;break e;case Ji:s=16,r=null;break e}throw Error(ue(130,e==null?e:typeof e,""))}return t=Ur(s,n,t,o),t.elementType=e,t.type=r,t.lanes=i,t}function $a(e,t,n,r){return e=Ur(7,e,r,t),e.lanes=n,e}function _m(e,t,n,r){return e=Ur(22,e,r,t),e.elementType=D$,e.lanes=n,e.stateNode={isHidden:!1},e}function l0(e,t,n){return e=Ur(6,e,null,t),e.lanes=n,e}function c0(e,t,n){return t=Ur(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function KI(e,t,n,r,o){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=Vv(0),this.expirationTimes=Vv(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Vv(0),this.identifierPrefix=r,this.onRecoverableError=o,this.mutableSourceEagerHydrationData=null}function Kw(e,t,n,r,o,i,s,l,u){return e=new KI(e,t,n,l,u),t===1?(t=1,i===!0&&(t|=8)):t=0,i=Ur(3,null,null,t),e.current=i,i.stateNode=e,i.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},Tw(i),e}function GI(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(Pk)}catch(e){console.error(e)}}Pk(),k$.exports=br;var Is=k$.exports;const QI=dm(Is);var GE=Is;V0.createRoot=GE.createRoot,V0.hydrateRoot=GE.hydrateRoot;var Od=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},oc=typeof window>"u"||"Deno"in window;function Lr(){}function JI(e,t){return typeof e=="function"?e(t):e}function Iy(e){return typeof e=="number"&&e>=0&&e!==1/0}function Ak(e,t){return Math.max(e+(t||0)-Date.now(),0)}function YE(e,t){const{type:n="all",exact:r,fetchStatus:o,predicate:i,queryKey:s,stale:l}=e;if(s){if(r){if(t.queryHash!==Zw(s,t.options))return!1}else if(!nd(t.queryKey,s))return!1}if(n!=="all"){const u=t.isActive();if(n==="active"&&!u||n==="inactive"&&u)return!1}return!(typeof l=="boolean"&&t.isStale()!==l||typeof o<"u"&&o!==t.state.fetchStatus||i&&!i(t))}function XE(e,t){const{exact:n,status:r,predicate:o,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(td(t.options.mutationKey)!==td(i))return!1}else if(!nd(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||o&&!o(t))}function Zw(e,t){return((t==null?void 0:t.queryKeyHashFn)||td)(e)}function td(e){return JSON.stringify(e,(t,n)=>Fy(n)?Object.keys(n).sort().reduce((r,o)=>(r[o]=n[o],r),{}):n)}function nd(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?!Object.keys(t).some(n=>!nd(e[n],t[n])):!1}function Mk(e,t){if(e===t)return e;const n=ZE(e)&&ZE(t);if(n||Fy(e)&&Fy(t)){const r=n?e.length:Object.keys(e).length,o=n?t:Object.keys(t),i=o.length,s=n?[]:{};let l=0;for(let u=0;u"u")return!0;const n=t.prototype;return!(!qE(n)||!n.hasOwnProperty("isPrototypeOf"))}function qE(e){return Object.prototype.toString.call(e)==="[object Object]"}function Ok(e){return new Promise(t=>{setTimeout(t,e)})}function QE(e){Ok(0).then(e)}function jy(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?Mk(e,t):t}function eL(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function tL(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var ga,rs,Il,c$,nL=(c$=class extends Od{constructor(){super();Te(this,ga,void 0);Te(this,rs,void 0);Te(this,Il,void 0);ye(this,Il,t=>{if(!oc&&window.addEventListener){const n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){z(this,rs)||this.setEventListener(z(this,Il))}onUnsubscribe(){var t;this.hasListeners()||((t=z(this,rs))==null||t.call(this),ye(this,rs,void 0))}setEventListener(t){var n;ye(this,Il,t),(n=z(this,rs))==null||n.call(this),ye(this,rs,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){z(this,ga)!==t&&(ye(this,ga,t),this.onFocus())}onFocus(){this.listeners.forEach(t=>{t()})}isFocused(){var t;return typeof z(this,ga)=="boolean"?z(this,ga):((t=globalThis.document)==null?void 0:t.visibilityState)!=="hidden"}},ga=new WeakMap,rs=new WeakMap,Il=new WeakMap,c$),Ap=new nL,Ll,os,Fl,u$,rL=(u$=class extends Od{constructor(){super();Te(this,Ll,!0);Te(this,os,void 0);Te(this,Fl,void 0);ye(this,Fl,t=>{if(!oc&&window.addEventListener){const n=()=>t(!0),r=()=>t(!1);return window.addEventListener("online",n,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",r)}}})}onSubscribe(){z(this,os)||this.setEventListener(z(this,Fl))}onUnsubscribe(){var t;this.hasListeners()||((t=z(this,os))==null||t.call(this),ye(this,os,void 0))}setEventListener(t){var n;ye(this,Fl,t),(n=z(this,os))==null||n.call(this),ye(this,os,t(this.setOnline.bind(this)))}setOnline(t){z(this,Ll)!==t&&(ye(this,Ll,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return z(this,Ll)}},Ll=new WeakMap,os=new WeakMap,Fl=new WeakMap,u$),Mp=new rL;function oL(e){return Math.min(1e3*2**e,3e4)}function km(e){return(e??"online")==="online"?Mp.isOnline():!0}var Nk=class{constructor(e){this.revert=e==null?void 0:e.revert,this.silent=e==null?void 0:e.silent}};function u0(e){return e instanceof Nk}function Dk(e){let t=!1,n=0,r=!1,o,i,s;const l=new Promise((E,_)=>{i=E,s=_}),u=E=>{var _;r||(y(new Nk(E)),(_=e.abort)==null||_.call(e))},f=()=>{t=!0},m=()=>{t=!1},p=()=>!Ap.isFocused()||e.networkMode!=="always"&&!Mp.isOnline(),g=E=>{var _;r||(r=!0,(_=e.onSuccess)==null||_.call(e,E),o==null||o(),i(E))},y=E=>{var _;r||(r=!0,(_=e.onError)==null||_.call(e,E),o==null||o(),s(E))},b=()=>new Promise(E=>{var _;o=x=>{const C=r||!p();return C&&E(x),C},(_=e.onPause)==null||_.call(e)}).then(()=>{var E;o=void 0,r||(E=e.onContinue)==null||E.call(e)}),S=()=>{if(r)return;let E;try{E=e.fn()}catch(_){E=Promise.reject(_)}Promise.resolve(E).then(g).catch(_=>{var M;if(r)return;const x=e.retry??(oc?0:3),C=e.retryDelay??oL,R=typeof C=="function"?C(n,_):C,P=x===!0||typeof x=="number"&&n{if(p())return b()}).then(()=>{t?y(_):S()})})};return km(e.networkMode)?S():b().then(S),{promise:l,cancel:u,continue:()=>(o==null?void 0:o())?l:Promise.resolve(),cancelRetry:f,continueRetry:m}}function iL(){let e=[],t=0,n=m=>{m()},r=m=>{m()};const o=m=>{let p;t++;try{p=m()}finally{t--,t||l()}return p},i=m=>{t?e.push(m):QE(()=>{n(m)})},s=m=>(...p)=>{i(()=>{m(...p)})},l=()=>{const m=e;e=[],m.length&&QE(()=>{r(()=>{m.forEach(p=>{n(p)})})})};return{batch:o,batchCalls:s,schedule:i,setNotifyFunction:m=>{n=m},setBatchNotifyFunction:m=>{r=m}}}var vn=iL(),va,d$,Ik=(d$=class{constructor(){Te(this,va,void 0)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Iy(this.gcTime)&&ye(this,va,setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(oc?1/0:5*60*1e3))}clearGcTimeout(){z(this,va)&&(clearTimeout(z(this,va)),ye(this,va,void 0))}},va=new WeakMap,d$),jl,zl,Nr,is,Dr,cn,vd,ya,Bl,Uh,ao,di,f$,sL=(f$=class extends Ik{constructor(t){super();Te(this,Bl);Te(this,ao);Te(this,jl,void 0);Te(this,zl,void 0);Te(this,Nr,void 0);Te(this,is,void 0);Te(this,Dr,void 0);Te(this,cn,void 0);Te(this,vd,void 0);Te(this,ya,void 0);ye(this,ya,!1),ye(this,vd,t.defaultOptions),tt(this,Bl,Uh).call(this,t.options),ye(this,cn,[]),ye(this,Nr,t.cache),this.queryKey=t.queryKey,this.queryHash=t.queryHash,ye(this,jl,t.state||aL(this.options)),this.state=z(this,jl),this.scheduleGc()}get meta(){return this.options.meta}optionalRemove(){!z(this,cn).length&&this.state.fetchStatus==="idle"&&z(this,Nr).remove(this)}setData(t,n){const r=jy(this.state.data,t,this.options);return tt(this,ao,di).call(this,{data:r,type:"success",dataUpdatedAt:n==null?void 0:n.updatedAt,manual:n==null?void 0:n.manual}),r}setState(t,n){tt(this,ao,di).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){var r;const n=z(this,is);return(r=z(this,Dr))==null||r.cancel(t),n?n.then(Lr).catch(Lr):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(z(this,jl))}isActive(){return z(this,cn).some(t=>t.options.enabled!==!1)}isDisabled(){return this.getObserversCount()>0&&!this.isActive()}isStale(){return this.state.isInvalidated||!this.state.dataUpdatedAt||z(this,cn).some(t=>t.getCurrentResult().isStale)}isStaleByTime(t=0){return this.state.isInvalidated||!this.state.dataUpdatedAt||!Ak(this.state.dataUpdatedAt,t)}onFocus(){var n;const t=z(this,cn).find(r=>r.shouldFetchOnWindowFocus());t==null||t.refetch({cancelRefetch:!1}),(n=z(this,Dr))==null||n.continue()}onOnline(){var n;const t=z(this,cn).find(r=>r.shouldFetchOnReconnect());t==null||t.refetch({cancelRefetch:!1}),(n=z(this,Dr))==null||n.continue()}addObserver(t){z(this,cn).includes(t)||(z(this,cn).push(t),this.clearGcTimeout(),z(this,Nr).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){z(this,cn).includes(t)&&(ye(this,cn,z(this,cn).filter(n=>n!==t)),z(this,cn).length||(z(this,Dr)&&(z(this,ya)?z(this,Dr).cancel({revert:!0}):z(this,Dr).cancelRetry()),this.scheduleGc()),z(this,Nr).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return z(this,cn).length}invalidate(){this.state.isInvalidated||tt(this,ao,di).call(this,{type:"invalidate"})}fetch(t,n){var f,m,p,g;if(this.state.fetchStatus!=="idle"){if(this.state.dataUpdatedAt&&(n!=null&&n.cancelRefetch))this.cancel({silent:!0});else if(z(this,is))return(f=z(this,Dr))==null||f.continueRetry(),z(this,is)}if(t&&tt(this,Bl,Uh).call(this,t),!this.options.queryFn){const y=z(this,cn).find(b=>b.options.queryFn);y&&tt(this,Bl,Uh).call(this,y.options)}const r=new AbortController,o={queryKey:this.queryKey,meta:this.meta},i=y=>{Object.defineProperty(y,"signal",{enumerable:!0,get:()=>(ye(this,ya,!0),r.signal)})};i(o);const s=()=>this.options.queryFn?(ye(this,ya,!1),this.options.persister?this.options.persister(this.options.queryFn,o,this):this.options.queryFn(o)):Promise.reject(new Error(`Missing queryFn: '${this.options.queryHash}'`)),l={fetchOptions:n,options:this.options,queryKey:this.queryKey,state:this.state,fetchFn:s};i(l),(m=this.options.behavior)==null||m.onFetch(l,this),ye(this,zl,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((p=l.fetchOptions)==null?void 0:p.meta))&&tt(this,ao,di).call(this,{type:"fetch",meta:(g=l.fetchOptions)==null?void 0:g.meta});const u=y=>{var b,S,E,_;u0(y)&&y.silent||tt(this,ao,di).call(this,{type:"error",error:y}),u0(y)||((S=(b=z(this,Nr).config).onError)==null||S.call(b,y,this),(_=(E=z(this,Nr).config).onSettled)==null||_.call(E,this.state.data,y,this)),this.isFetchingOptimistic||this.scheduleGc(),this.isFetchingOptimistic=!1};return ye(this,Dr,Dk({fn:l.fetchFn,abort:r.abort.bind(r),onSuccess:y=>{var b,S,E,_;if(typeof y>"u"){u(new Error(`${this.queryHash} data is undefined`));return}this.setData(y),(S=(b=z(this,Nr).config).onSuccess)==null||S.call(b,y,this),(_=(E=z(this,Nr).config).onSettled)==null||_.call(E,y,this.state.error,this),this.isFetchingOptimistic||this.scheduleGc(),this.isFetchingOptimistic=!1},onError:u,onFail:(y,b)=>{tt(this,ao,di).call(this,{type:"failed",failureCount:y,error:b})},onPause:()=>{tt(this,ao,di).call(this,{type:"pause"})},onContinue:()=>{tt(this,ao,di).call(this,{type:"continue"})},retry:l.options.retry,retryDelay:l.options.retryDelay,networkMode:l.options.networkMode})),ye(this,is,z(this,Dr).promise),z(this,is)}},jl=new WeakMap,zl=new WeakMap,Nr=new WeakMap,is=new WeakMap,Dr=new WeakMap,cn=new WeakMap,vd=new WeakMap,ya=new WeakMap,Bl=new WeakSet,Uh=function(t){this.options={...z(this,vd),...t},this.updateGcTime(this.options.gcTime)},ao=new WeakSet,di=function(t){const n=r=>{switch(t.type){case"failed":return{...r,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...r,fetchStatus:"paused"};case"continue":return{...r,fetchStatus:"fetching"};case"fetch":return{...r,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:t.meta??null,fetchStatus:km(this.options.networkMode)?"fetching":"paused",...!r.dataUpdatedAt&&{error:null,status:"pending"}};case"success":return{...r,data:t.data,dataUpdateCount:r.dataUpdateCount+1,dataUpdatedAt:t.dataUpdatedAt??Date.now(),error:null,isInvalidated:!1,status:"success",...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};case"error":const o=t.error;return u0(o)&&o.revert&&z(this,zl)?{...z(this,zl),fetchStatus:"idle"}:{...r,error:o,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:o,fetchStatus:"idle",status:"error"};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...t.state}}};this.state=n(this.state),vn.batch(()=>{z(this,cn).forEach(r=>{r.onQueryUpdate()}),z(this,Nr).notify({query:this,type:"updated",action:t})})},f$);function aL(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=typeof t<"u",r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var Mo,h$,lL=(h$=class extends Od{constructor(t={}){super();Te(this,Mo,void 0);this.config=t,ye(this,Mo,new Map)}build(t,n,r){const o=n.queryKey,i=n.queryHash??Zw(o,n);let s=this.get(i);return s||(s=new sL({cache:this,queryKey:o,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(o)}),this.add(s)),s}add(t){z(this,Mo).has(t.queryHash)||(z(this,Mo).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){const n=z(this,Mo).get(t.queryHash);n&&(t.destroy(),n===t&&z(this,Mo).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){vn.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return z(this,Mo).get(t)}getAll(){return[...z(this,Mo).values()]}find(t){const n={exact:!0,...t};return this.getAll().find(r=>YE(n,r))}findAll(t={}){const n=this.getAll();return Object.keys(t).length>0?n.filter(r=>YE(t,r)):n}notify(t){vn.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){vn.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){vn.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},Mo=new WeakMap,h$),Oo,yd,dr,Ul,No,qi,p$,cL=(p$=class extends Ik{constructor(t){super();Te(this,No);Te(this,Oo,void 0);Te(this,yd,void 0);Te(this,dr,void 0);Te(this,Ul,void 0);this.mutationId=t.mutationId,ye(this,yd,t.defaultOptions),ye(this,dr,t.mutationCache),ye(this,Oo,[]),this.state=t.state||uL(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options={...z(this,yd),...t},this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){z(this,Oo).includes(t)||(z(this,Oo).push(t),this.clearGcTimeout(),z(this,dr).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){ye(this,Oo,z(this,Oo).filter(n=>n!==t)),this.scheduleGc(),z(this,dr).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){z(this,Oo).length||(this.state.status==="pending"?this.scheduleGc():z(this,dr).remove(this))}continue(){var t;return((t=z(this,Ul))==null?void 0:t.continue())??this.execute(this.state.variables)}async execute(t){var o,i,s,l,u,f,m,p,g,y,b,S,E,_,x,C,R,P,M,A;const n=()=>(ye(this,Ul,Dk({fn:()=>this.options.mutationFn?this.options.mutationFn(t):Promise.reject(new Error("No mutationFn found")),onFail:(D,U)=>{tt(this,No,qi).call(this,{type:"failed",failureCount:D,error:U})},onPause:()=>{tt(this,No,qi).call(this,{type:"pause"})},onContinue:()=>{tt(this,No,qi).call(this,{type:"continue"})},retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode})),z(this,Ul).promise),r=this.state.status==="pending";try{if(!r){tt(this,No,qi).call(this,{type:"pending",variables:t}),await((i=(o=z(this,dr).config).onMutate)==null?void 0:i.call(o,t,this));const U=await((l=(s=this.options).onMutate)==null?void 0:l.call(s,t));U!==this.state.context&&tt(this,No,qi).call(this,{type:"pending",context:U,variables:t})}const D=await n();return await((f=(u=z(this,dr).config).onSuccess)==null?void 0:f.call(u,D,t,this.state.context,this)),await((p=(m=this.options).onSuccess)==null?void 0:p.call(m,D,t,this.state.context)),await((y=(g=z(this,dr).config).onSettled)==null?void 0:y.call(g,D,null,this.state.variables,this.state.context,this)),await((S=(b=this.options).onSettled)==null?void 0:S.call(b,D,null,t,this.state.context)),tt(this,No,qi).call(this,{type:"success",data:D}),D}catch(D){try{throw await((_=(E=z(this,dr).config).onError)==null?void 0:_.call(E,D,t,this.state.context,this)),await((C=(x=this.options).onError)==null?void 0:C.call(x,D,t,this.state.context)),await((P=(R=z(this,dr).config).onSettled)==null?void 0:P.call(R,void 0,D,this.state.variables,this.state.context,this)),await((A=(M=this.options).onSettled)==null?void 0:A.call(M,void 0,D,t,this.state.context)),D}finally{tt(this,No,qi).call(this,{type:"error",error:D})}}}},Oo=new WeakMap,yd=new WeakMap,dr=new WeakMap,Ul=new WeakMap,No=new WeakSet,qi=function(t){const n=r=>{switch(t.type){case"failed":return{...r,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};case"pending":return{...r,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:!km(this.options.networkMode),status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...r,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:t.error,failureCount:r.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}};this.state=n(this.state),vn.batch(()=>{z(this,Oo).forEach(r=>{r.onMutationUpdate(t)}),z(this,dr).notify({mutation:this,type:"updated",action:t})})},p$);function uL(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Ir,wd,wa,m$,dL=(m$=class extends Od{constructor(t={}){super();Te(this,Ir,void 0);Te(this,wd,void 0);Te(this,wa,void 0);this.config=t,ye(this,Ir,[]),ye(this,wd,0)}build(t,n,r){const o=new cL({mutationCache:this,mutationId:++Hf(this,wd)._,options:t.defaultMutationOptions(n),state:r});return this.add(o),o}add(t){z(this,Ir).push(t),this.notify({type:"added",mutation:t})}remove(t){ye(this,Ir,z(this,Ir).filter(n=>n!==t)),this.notify({type:"removed",mutation:t})}clear(){vn.batch(()=>{z(this,Ir).forEach(t=>{this.remove(t)})})}getAll(){return z(this,Ir)}find(t){const n={exact:!0,...t};return z(this,Ir).find(r=>XE(n,r))}findAll(t={}){return z(this,Ir).filter(n=>XE(t,n))}notify(t){vn.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){return ye(this,wa,(z(this,wa)??Promise.resolve()).then(()=>{const t=z(this,Ir).filter(n=>n.state.isPaused);return vn.batch(()=>t.reduce((n,r)=>n.then(()=>r.continue().catch(Lr)),Promise.resolve()))}).then(()=>{ye(this,wa,void 0)})),z(this,wa)}},Ir=new WeakMap,wd=new WeakMap,wa=new WeakMap,m$);function fL(e){return{onFetch:(t,n)=>{const r=async()=>{var b,S,E,_,x;const o=t.options,i=(E=(S=(b=t.fetchOptions)==null?void 0:b.meta)==null?void 0:S.fetchMore)==null?void 0:E.direction,s=((_=t.state.data)==null?void 0:_.pages)||[],l=((x=t.state.data)==null?void 0:x.pageParams)||[],u={pages:[],pageParams:[]};let f=!1;const m=C=>{Object.defineProperty(C,"signal",{enumerable:!0,get:()=>(t.signal.aborted?f=!0:t.signal.addEventListener("abort",()=>{f=!0}),t.signal)})},p=t.options.queryFn||(()=>Promise.reject(new Error(`Missing queryFn: '${t.options.queryHash}'`))),g=async(C,R,P)=>{if(f)return Promise.reject();if(R==null&&C.pages.length)return Promise.resolve(C);const M={queryKey:t.queryKey,pageParam:R,direction:P?"backward":"forward",meta:t.options.meta};m(M);const A=await p(M),{maxPages:D}=t.options,U=P?tL:eL;return{pages:U(C.pages,A,D),pageParams:U(C.pageParams,R,D)}};let y;if(i&&s.length){const C=i==="backward",R=C?hL:JE,P={pages:s,pageParams:l},M=R(o,P);y=await g(P,M,C)}else{y=await g(u,l[0]??o.initialPageParam);const C=e??s.length;for(let R=1;R{var o,i;return(i=(o=t.options).persister)==null?void 0:i.call(o,r,{queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n)}:t.fetchFn=r}}}function JE(e,{pages:t,pageParams:n}){const r=t.length-1;return e.getNextPageParam(t[r],t,n[r],n)}function hL(e,{pages:t,pageParams:n}){var r;return(r=e.getPreviousPageParam)==null?void 0:r.call(e,t[0],t,n[0],n)}var nn,ss,as,Vl,Wl,ls,Hl,Kl,g$,pL=(g$=class{constructor(e={}){Te(this,nn,void 0);Te(this,ss,void 0);Te(this,as,void 0);Te(this,Vl,void 0);Te(this,Wl,void 0);Te(this,ls,void 0);Te(this,Hl,void 0);Te(this,Kl,void 0);ye(this,nn,e.queryCache||new lL),ye(this,ss,e.mutationCache||new dL),ye(this,as,e.defaultOptions||{}),ye(this,Vl,new Map),ye(this,Wl,new Map),ye(this,ls,0)}mount(){Hf(this,ls)._++,z(this,ls)===1&&(ye(this,Hl,Ap.subscribe(()=>{Ap.isFocused()&&(this.resumePausedMutations(),z(this,nn).onFocus())})),ye(this,Kl,Mp.subscribe(()=>{Mp.isOnline()&&(this.resumePausedMutations(),z(this,nn).onOnline())})))}unmount(){var e,t;Hf(this,ls)._--,z(this,ls)===0&&((e=z(this,Hl))==null||e.call(this),ye(this,Hl,void 0),(t=z(this,Kl))==null||t.call(this),ye(this,Kl,void 0))}isFetching(e){return z(this,nn).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return z(this,ss).findAll({...e,status:"pending"}).length}getQueryData(e){var t;return(t=z(this,nn).find({queryKey:e}))==null?void 0:t.state.data}ensureQueryData(e){const t=this.getQueryData(e.queryKey);return t!==void 0?Promise.resolve(t):this.fetchQuery(e)}getQueriesData(e){return this.getQueryCache().findAll(e).map(({queryKey:t,state:n})=>{const r=n.data;return[t,r]})}setQueryData(e,t,n){const r=z(this,nn).find({queryKey:e}),o=r==null?void 0:r.state.data,i=JI(t,o);if(typeof i>"u")return;const s=this.defaultQueryOptions({queryKey:e});return z(this,nn).build(this,s).setData(i,{...n,manual:!0})}setQueriesData(e,t,n){return vn.batch(()=>this.getQueryCache().findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){var t;return(t=z(this,nn).find({queryKey:e}))==null?void 0:t.state}removeQueries(e){const t=z(this,nn);vn.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=z(this,nn),r={type:"active",...e};return vn.batch(()=>(n.findAll(e).forEach(o=>{o.reset()}),this.refetchQueries(r,t)))}cancelQueries(e={},t={}){const n={revert:!0,...t},r=vn.batch(()=>z(this,nn).findAll(e).map(o=>o.cancel(n)));return Promise.all(r).then(Lr).catch(Lr)}invalidateQueries(e={},t={}){return vn.batch(()=>{if(z(this,nn).findAll(e).forEach(r=>{r.invalidate()}),e.refetchType==="none")return Promise.resolve();const n={...e,type:e.refetchType??e.type??"active"};return this.refetchQueries(n,t)})}refetchQueries(e={},t){const n={...t,cancelRefetch:(t==null?void 0:t.cancelRefetch)??!0},r=vn.batch(()=>z(this,nn).findAll(e).filter(o=>!o.isDisabled()).map(o=>{let i=o.fetch(void 0,n);return n.throwOnError||(i=i.catch(Lr)),o.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(Lr)}fetchQuery(e){const t=this.defaultQueryOptions(e);typeof t.retry>"u"&&(t.retry=!1);const n=z(this,nn).build(this,t);return n.isStaleByTime(t.staleTime)?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Lr).catch(Lr)}fetchInfiniteQuery(e){return e.behavior=fL(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Lr).catch(Lr)}resumePausedMutations(){return z(this,ss).resumePausedMutations()}getQueryCache(){return z(this,nn)}getMutationCache(){return z(this,ss)}getDefaultOptions(){return z(this,as)}setDefaultOptions(e){ye(this,as,e)}setQueryDefaults(e,t){z(this,Vl).set(td(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...z(this,Vl).values()];let n={};return t.forEach(r=>{nd(e,r.queryKey)&&(n={...n,...r.defaultOptions})}),n}setMutationDefaults(e,t){z(this,Wl).set(td(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...z(this,Wl).values()];let n={};return t.forEach(r=>{nd(e,r.mutationKey)&&(n={...n,...r.defaultOptions})}),n}defaultQueryOptions(e){if(e!=null&&e._defaulted)return e;const t={...z(this,as).queries,...(e==null?void 0:e.queryKey)&&this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Zw(t.queryKey,t)),typeof t.refetchOnReconnect>"u"&&(t.refetchOnReconnect=t.networkMode!=="always"),typeof t.throwOnError>"u"&&(t.throwOnError=!!t.suspense),typeof t.networkMode>"u"&&t.persister&&(t.networkMode="offlineFirst"),t}defaultMutationOptions(e){return e!=null&&e._defaulted?e:{...z(this,as).mutations,...(e==null?void 0:e.mutationKey)&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){z(this,nn).clear(),z(this,ss).clear()}},nn=new WeakMap,ss=new WeakMap,as=new WeakMap,Vl=new WeakMap,Wl=new WeakMap,ls=new WeakMap,Hl=new WeakMap,Kl=new WeakMap,g$),Xn,Ct,Gl,kn,xa,Yl,Do,xd,Xl,Zl,ba,Sa,cs,_a,Ea,bu,bd,zy,Sd,By,_d,Uy,Ed,Vy,Cd,Wy,$d,Hy,Rd,Ky,um,Lk,v$,mL=(v$=class extends Od{constructor(t,n){super();Te(this,Ea);Te(this,bd);Te(this,Sd);Te(this,_d);Te(this,Ed);Te(this,Cd);Te(this,$d);Te(this,Rd);Te(this,um);Te(this,Xn,void 0);Te(this,Ct,void 0);Te(this,Gl,void 0);Te(this,kn,void 0);Te(this,xa,void 0);Te(this,Yl,void 0);Te(this,Do,void 0);Te(this,xd,void 0);Te(this,Xl,void 0);Te(this,Zl,void 0);Te(this,ba,void 0);Te(this,Sa,void 0);Te(this,cs,void 0);Te(this,_a,void 0);ye(this,Ct,void 0),ye(this,Gl,void 0),ye(this,kn,void 0),ye(this,_a,new Set),ye(this,Xn,t),this.options=n,ye(this,Do,null),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(z(this,Ct).addObserver(this),eC(z(this,Ct),this.options)?tt(this,Ea,bu).call(this):this.updateResult(),tt(this,Ed,Vy).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Gy(z(this,Ct),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Gy(z(this,Ct),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,tt(this,Cd,Wy).call(this),tt(this,$d,Hy).call(this),z(this,Ct).removeObserver(this)}setOptions(t,n){const r=this.options,o=z(this,Ct);if(this.options=z(this,Xn).defaultQueryOptions(t),Ly(r,this.options)||z(this,Xn).getQueryCache().notify({type:"observerOptionsUpdated",query:z(this,Ct),observer:this}),typeof this.options.enabled<"u"&&typeof this.options.enabled!="boolean")throw new Error("Expected enabled to be a boolean");this.options.queryKey||(this.options.queryKey=r.queryKey),tt(this,Rd,Ky).call(this);const i=this.hasListeners();i&&tC(z(this,Ct),o,this.options,r)&&tt(this,Ea,bu).call(this),this.updateResult(n),i&&(z(this,Ct)!==o||this.options.enabled!==r.enabled||this.options.staleTime!==r.staleTime)&&tt(this,bd,zy).call(this);const s=tt(this,Sd,By).call(this);i&&(z(this,Ct)!==o||this.options.enabled!==r.enabled||s!==z(this,cs))&&tt(this,_d,Uy).call(this,s)}getOptimisticResult(t){const n=z(this,Xn).getQueryCache().build(z(this,Xn),t),r=this.createResult(n,t);return vL(this,r)&&(ye(this,kn,r),ye(this,Yl,this.options),ye(this,xa,z(this,Ct).state)),r}getCurrentResult(){return z(this,kn)}trackResult(t){const n={};return Object.keys(t).forEach(r=>{Object.defineProperty(n,r,{configurable:!1,enumerable:!0,get:()=>(z(this,_a).add(r),t[r])})}),n}getCurrentQuery(){return z(this,Ct)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){const n=z(this,Xn).defaultQueryOptions(t),r=z(this,Xn).getQueryCache().build(z(this,Xn),n);return r.isFetchingOptimistic=!0,r.fetch().then(()=>this.createResult(r,n))}fetch(t){return tt(this,Ea,bu).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),z(this,kn)))}createResult(t,n){var M;const r=z(this,Ct),o=this.options,i=z(this,kn),s=z(this,xa),l=z(this,Yl),f=t!==r?t.state:z(this,Gl),{state:m}=t;let{error:p,errorUpdatedAt:g,fetchStatus:y,status:b}=m,S=!1,E;if(n._optimisticResults){const A=this.hasListeners(),D=!A&&eC(t,n),U=A&&tC(t,r,n,o);(D||U)&&(y=km(t.options.networkMode)?"fetching":"paused",m.dataUpdatedAt||(b="pending")),n._optimisticResults==="isRestoring"&&(y="idle")}if(n.select&&typeof m.data<"u")if(i&&m.data===(s==null?void 0:s.data)&&n.select===z(this,xd))E=z(this,Xl);else try{ye(this,xd,n.select),E=n.select(m.data),E=jy(i==null?void 0:i.data,E,n),ye(this,Xl,E),ye(this,Do,null)}catch(A){ye(this,Do,A)}else E=m.data;if(typeof n.placeholderData<"u"&&typeof E>"u"&&b==="pending"){let A;if(i!=null&&i.isPlaceholderData&&n.placeholderData===(l==null?void 0:l.placeholderData))A=i.data;else if(A=typeof n.placeholderData=="function"?n.placeholderData((M=z(this,Zl))==null?void 0:M.state.data,z(this,Zl)):n.placeholderData,n.select&&typeof A<"u")try{A=n.select(A),ye(this,Do,null)}catch(D){ye(this,Do,D)}typeof A<"u"&&(b="success",E=jy(i==null?void 0:i.data,A,n),S=!0)}z(this,Do)&&(p=z(this,Do),E=z(this,Xl),g=Date.now(),b="error");const _=y==="fetching",x=b==="pending",C=b==="error",R=x&&_;return{status:b,fetchStatus:y,isPending:x,isSuccess:b==="success",isError:C,isInitialLoading:R,isLoading:R,data:E,dataUpdatedAt:m.dataUpdatedAt,error:p,errorUpdatedAt:g,failureCount:m.fetchFailureCount,failureReason:m.fetchFailureReason,errorUpdateCount:m.errorUpdateCount,isFetched:m.dataUpdateCount>0||m.errorUpdateCount>0,isFetchedAfterMount:m.dataUpdateCount>f.dataUpdateCount||m.errorUpdateCount>f.errorUpdateCount,isFetching:_,isRefetching:_&&!x,isLoadingError:C&&m.dataUpdatedAt===0,isPaused:y==="paused",isPlaceholderData:S,isRefetchError:C&&m.dataUpdatedAt!==0,isStale:qw(t,n),refetch:this.refetch}}updateResult(t){const n=z(this,kn),r=this.createResult(z(this,Ct),this.options);if(ye(this,xa,z(this,Ct).state),ye(this,Yl,this.options),z(this,xa).data!==void 0&&ye(this,Zl,z(this,Ct)),Ly(r,n))return;ye(this,kn,r);const o={},i=()=>{if(!n)return!0;const{notifyOnChangeProps:s}=this.options,l=typeof s=="function"?s():s;if(l==="all"||!l&&!z(this,_a).size)return!0;const u=new Set(l??z(this,_a));return this.options.throwOnError&&u.add("error"),Object.keys(z(this,kn)).some(f=>{const m=f;return z(this,kn)[m]!==n[m]&&u.has(m)})};(t==null?void 0:t.listeners)!==!1&&i()&&(o.listeners=!0),tt(this,um,Lk).call(this,{...o,...t})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&tt(this,Ed,Vy).call(this)}},Xn=new WeakMap,Ct=new WeakMap,Gl=new WeakMap,kn=new WeakMap,xa=new WeakMap,Yl=new WeakMap,Do=new WeakMap,xd=new WeakMap,Xl=new WeakMap,Zl=new WeakMap,ba=new WeakMap,Sa=new WeakMap,cs=new WeakMap,_a=new WeakMap,Ea=new WeakSet,bu=function(t){tt(this,Rd,Ky).call(this);let n=z(this,Ct).fetch(this.options,t);return t!=null&&t.throwOnError||(n=n.catch(Lr)),n},bd=new WeakSet,zy=function(){if(tt(this,Cd,Wy).call(this),oc||z(this,kn).isStale||!Iy(this.options.staleTime))return;const n=Ak(z(this,kn).dataUpdatedAt,this.options.staleTime)+1;ye(this,ba,setTimeout(()=>{z(this,kn).isStale||this.updateResult()},n))},Sd=new WeakSet,By=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(z(this,Ct)):this.options.refetchInterval)??!1},_d=new WeakSet,Uy=function(t){tt(this,$d,Hy).call(this),ye(this,cs,t),!(oc||this.options.enabled===!1||!Iy(z(this,cs))||z(this,cs)===0)&&ye(this,Sa,setInterval(()=>{(this.options.refetchIntervalInBackground||Ap.isFocused())&&tt(this,Ea,bu).call(this)},z(this,cs)))},Ed=new WeakSet,Vy=function(){tt(this,bd,zy).call(this),tt(this,_d,Uy).call(this,tt(this,Sd,By).call(this))},Cd=new WeakSet,Wy=function(){z(this,ba)&&(clearTimeout(z(this,ba)),ye(this,ba,void 0))},$d=new WeakSet,Hy=function(){z(this,Sa)&&(clearInterval(z(this,Sa)),ye(this,Sa,void 0))},Rd=new WeakSet,Ky=function(){const t=z(this,Xn).getQueryCache().build(z(this,Xn),this.options);if(t===z(this,Ct))return;const n=z(this,Ct);ye(this,Ct,t),ye(this,Gl,t.state),this.hasListeners()&&(n==null||n.removeObserver(this),t.addObserver(this))},um=new WeakSet,Lk=function(t){vn.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(z(this,kn))}),z(this,Xn).getQueryCache().notify({query:z(this,Ct),type:"observerResultsUpdated"})})},v$);function gL(e,t){return t.enabled!==!1&&!e.state.dataUpdatedAt&&!(e.state.status==="error"&&t.retryOnMount===!1)}function eC(e,t){return gL(e,t)||e.state.dataUpdatedAt>0&&Gy(e,t,t.refetchOnMount)}function Gy(e,t,n){if(t.enabled!==!1){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&qw(e,t)}return!1}function tC(e,t,n,r){return n.enabled!==!1&&(e!==t||r.enabled===!1)&&(!n.suspense||e.state.status!=="error")&&qw(e,n)}function qw(e,t){return e.isStaleByTime(t.staleTime)}function vL(e,t){return!Ly(e.getCurrentResult(),t)}var Fk=d.createContext(void 0),yL=e=>{const t=d.useContext(Fk);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},wL=({client:e,children:t})=>(d.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),d.createElement(Fk.Provider,{value:e},t)),jk=d.createContext(!1),xL=()=>d.useContext(jk);jk.Provider;function bL(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var SL=d.createContext(bL()),_L=()=>d.useContext(SL);function EL(e,t){return typeof e=="function"?e(...t):!!e}var CL=(e,t)=>{(e.suspense||e.throwOnError)&&(t.isReset()||(e.retryOnMount=!1))},$L=e=>{d.useEffect(()=>{e.clearReset()},[e])},RL=({result:e,errorResetBoundary:t,throwOnError:n,query:r})=>e.isError&&!t.isReset()&&!e.isFetching&&EL(n,[e.error,r]),kL=e=>{e.suspense&&typeof e.staleTime!="number"&&(e.staleTime=1e3)},TL=(e,t)=>(e==null?void 0:e.suspense)&&t.isPending,PL=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function AL(e,t,n){const r=yL(n),o=xL(),i=_L(),s=r.defaultQueryOptions(e);s._optimisticResults=o?"isRestoring":"optimistic",kL(s),CL(s,i),$L(i);const[l]=d.useState(()=>new t(r,s)),u=l.getOptimisticResult(s);if(d.useSyncExternalStore(d.useCallback(f=>{const m=o?()=>{}:l.subscribe(vn.batchCalls(f));return l.updateResult(),m},[l,o]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),d.useEffect(()=>{l.setOptions(s,{listeners:!1})},[s,l]),TL(s,u))throw l.setOptions(s,{listeners:!1}),PL(s,l,i);if(RL({result:u,errorResetBoundary:i,throwOnError:s.throwOnError,query:l.getCurrentQuery()}))throw u.error;return s.notifyOnChangeProps?u:l.trackResult(u)}function ML(e,t){return AL(e,mL,t)}var Ao=(e=>(e.RemoveBG="RemoveBG",e.AnimeSeg="AnimeSeg",e.RealESRGAN="RealESRGAN",e.GFPGAN="GFPGAN",e.RestoreFormer="RestoreFormer",e.InteractiveSeg="InteractiveSeg",e))(Ao||{}),Es=(e=>(e.NAME="name",e.CTIME="ctime",e.MTIME="mtime",e))(Es||{}),Ou=(e=>(e.DESCENDING="desc",e.ASCENDING="asc",e))(Ou||{}),Qw=(e=>(e.ddim="ddim",e.plms="plms",e))(Qw||{}),Jw=(e=>(e.INPAINT_NS="INPAINT_NS",e.INPAINT_TELEA="INPAINT_TELEA",e))(Jw||{}),Ln=(e=>(e.x="x",e.y="y",e.xy="xy",e))(Ln||{}),Ol=(e=>(e.text_guided="text-guided",e.shape_guided="shape-guided",e.object_remove="object-remove",e.outpainting="outpainting",e))(Ol||{});function zk(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;tl(i)))==null?void 0:s.classGroupId}const nC=/^\[(.+)\]$/;function NL(e){if(nC.test(e)){const t=nC.exec(e)[1],n=t==null?void 0:t.substring(0,t.indexOf(":"));if(n)return"arbitrary.."+n}}function DL(e){const{theme:t,prefix:n}=e,r={nextPart:new Map,validators:[]};return LL(Object.entries(e.classGroups),n).forEach(([i,s])=>{Yy(s,r,i,t)}),r}function Yy(e,t,n,r){e.forEach(o=>{if(typeof o=="string"){const i=o===""?t:rC(t,o);i.classGroupId=n;return}if(typeof o=="function"){if(IL(o)){Yy(o(r),t,n,r);return}t.validators.push({validator:o,classGroupId:n});return}Object.entries(o).forEach(([i,s])=>{Yy(s,rC(t,i),n,r)})})}function rC(e,t){let n=e;return t.split(ex).forEach(r=>{n.nextPart.has(r)||n.nextPart.set(r,{nextPart:new Map,validators:[]}),n=n.nextPart.get(r)}),n}function IL(e){return e.isThemeGetter}function LL(e,t){return t?e.map(([n,r])=>{const o=r.map(i=>typeof i=="string"?t+i:typeof i=="object"?Object.fromEntries(Object.entries(i).map(([s,l])=>[t+s,l])):i);return[n,o]}):e}function FL(e){if(e<1)return{get:()=>{},set:()=>{}};let t=0,n=new Map,r=new Map;function o(i,s){n.set(i,s),t++,t>e&&(t=0,r=n,n=new Map)}return{get(i){let s=n.get(i);if(s!==void 0)return s;if((s=r.get(i))!==void 0)return o(i,s),s},set(i,s){n.has(i)?n.set(i,s):o(i,s)}}}const Vk="!";function jL(e){const t=e.separator,n=t.length===1,r=t[0],o=t.length;return function(s){const l=[];let u=0,f=0,m;for(let S=0;Sf?m-f:void 0;return{modifiers:l,hasImportantModifier:g,baseClassName:y,maybePostfixModifierPosition:b}}}function zL(e){if(e.length<=1)return e;const t=[];let n=[];return e.forEach(r=>{r[0]==="["?(t.push(...n.sort(),r),n=[]):n.push(r)}),t.push(...n.sort()),t}function BL(e){return{cache:FL(e.cacheSize),splitModifiers:jL(e),...OL(e)}}const UL=/\s+/;function VL(e,t){const{splitModifiers:n,getClassGroupId:r,getConflictingClassGroupIds:o}=t,i=new Set;return e.trim().split(UL).map(s=>{const{modifiers:l,hasImportantModifier:u,baseClassName:f,maybePostfixModifierPosition:m}=n(s);let p=r(m?f.substring(0,m):f),g=!!m;if(!p){if(!m)return{isTailwindClass:!1,originalClassName:s};if(p=r(f),!p)return{isTailwindClass:!1,originalClassName:s};g=!1}const y=zL(l).join(":");return{isTailwindClass:!0,modifierId:u?y+Vk:y,classGroupId:p,originalClassName:s,hasPostfixModifier:g}}).reverse().filter(s=>{if(!s.isTailwindClass)return!0;const{modifierId:l,classGroupId:u,hasPostfixModifier:f}=s,m=l+u;return i.has(m)?!1:(i.add(m),o(u,f).forEach(p=>i.add(l+p)),!0)}).reverse().map(s=>s.originalClassName).join(" ")}function WL(){let e=0,t,n,r="";for(;ep(m),e());return n=BL(f),r=n.cache.get,o=n.cache.set,i=l,l(u)}function l(u){const f=r(u);if(f)return f;const m=VL(u,n);return o(u,m),m}return function(){return i(WL.apply(null,arguments))}}function kt(e){const t=n=>n[e]||[];return t.isThemeGetter=!0,t}const Hk=/^\[(?:([a-z-]+):)?(.+)\]$/i,KL=/^\d+\/\d+$/,GL=new Set(["px","full","screen"]),YL=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,XL=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,ZL=/^-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,qL=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/;function oo(e){return ha(e)||GL.has(e)||KL.test(e)}function Gi(e){return bc(e,"length",iF)}function ha(e){return!!e&&!Number.isNaN(Number(e))}function ch(e){return bc(e,"number",ha)}function lu(e){return!!e&&Number.isInteger(Number(e))}function QL(e){return e.endsWith("%")&&ha(e.slice(0,-1))}function Je(e){return Hk.test(e)}function Yi(e){return YL.test(e)}const JL=new Set(["length","size","percentage"]);function eF(e){return bc(e,JL,Kk)}function tF(e){return bc(e,"position",Kk)}const nF=new Set(["image","url"]);function rF(e){return bc(e,nF,aF)}function oF(e){return bc(e,"",sF)}function cu(){return!0}function bc(e,t,n){const r=Hk.exec(e);return r?r[1]?typeof t=="string"?r[1]===t:t.has(r[1]):n(r[2]):!1}function iF(e){return XL.test(e)}function Kk(){return!1}function sF(e){return ZL.test(e)}function aF(e){return qL.test(e)}function lF(){const e=kt("colors"),t=kt("spacing"),n=kt("blur"),r=kt("brightness"),o=kt("borderColor"),i=kt("borderRadius"),s=kt("borderSpacing"),l=kt("borderWidth"),u=kt("contrast"),f=kt("grayscale"),m=kt("hueRotate"),p=kt("invert"),g=kt("gap"),y=kt("gradientColorStops"),b=kt("gradientColorStopPositions"),S=kt("inset"),E=kt("margin"),_=kt("opacity"),x=kt("padding"),C=kt("saturate"),R=kt("scale"),P=kt("sepia"),M=kt("skew"),A=kt("space"),D=kt("translate"),U=()=>["auto","contain","none"],W=()=>["auto","hidden","clip","visible","scroll"],q=()=>["auto",Je,t],X=()=>[Je,t],ae=()=>["",oo,Gi],V=()=>["auto",ha,Je],F=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],N=()=>["solid","dashed","dotted","double","none"],ie=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity","plus-lighter"],K=()=>["start","end","center","between","around","evenly","stretch"],Z=()=>["","0",Je],H=()=>["auto","avoid","all","avoid-page","page","left","right","column"],se=()=>[ha,ch],ce=()=>[ha,Je];return{cacheSize:500,separator:":",theme:{colors:[cu],spacing:[oo,Gi],blur:["none","",Yi,Je],brightness:se(),borderColor:[e],borderRadius:["none","","full",Yi,Je],borderSpacing:X(),borderWidth:ae(),contrast:se(),grayscale:Z(),hueRotate:ce(),invert:Z(),gap:X(),gradientColorStops:[e],gradientColorStopPositions:[QL,Gi],inset:q(),margin:q(),opacity:se(),padding:X(),saturate:se(),scale:se(),sepia:Z(),skew:ce(),space:X(),translate:X()},classGroups:{aspect:[{aspect:["auto","square","video",Je]}],container:["container"],columns:[{columns:[Yi]}],"break-after":[{"break-after":H()}],"break-before":[{"break-before":H()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],float:[{float:["right","left","none"]}],clear:[{clear:["left","right","both","none"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:[...F(),Je]}],overflow:[{overflow:W()}],"overflow-x":[{"overflow-x":W()}],"overflow-y":[{"overflow-y":W()}],overscroll:[{overscroll:U()}],"overscroll-x":[{"overscroll-x":U()}],"overscroll-y":[{"overscroll-y":U()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[S]}],"inset-x":[{"inset-x":[S]}],"inset-y":[{"inset-y":[S]}],start:[{start:[S]}],end:[{end:[S]}],top:[{top:[S]}],right:[{right:[S]}],bottom:[{bottom:[S]}],left:[{left:[S]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",lu,Je]}],basis:[{basis:q()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",Je]}],grow:[{grow:Z()}],shrink:[{shrink:Z()}],order:[{order:["first","last","none",lu,Je]}],"grid-cols":[{"grid-cols":[cu]}],"col-start-end":[{col:["auto",{span:["full",lu,Je]},Je]}],"col-start":[{"col-start":V()}],"col-end":[{"col-end":V()}],"grid-rows":[{"grid-rows":[cu]}],"row-start-end":[{row:["auto",{span:[lu,Je]},Je]}],"row-start":[{"row-start":V()}],"row-end":[{"row-end":V()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",Je]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",Je]}],gap:[{gap:[g]}],"gap-x":[{"gap-x":[g]}],"gap-y":[{"gap-y":[g]}],"justify-content":[{justify:["normal",...K()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...K(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...K(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[x]}],px:[{px:[x]}],py:[{py:[x]}],ps:[{ps:[x]}],pe:[{pe:[x]}],pt:[{pt:[x]}],pr:[{pr:[x]}],pb:[{pb:[x]}],pl:[{pl:[x]}],m:[{m:[E]}],mx:[{mx:[E]}],my:[{my:[E]}],ms:[{ms:[E]}],me:[{me:[E]}],mt:[{mt:[E]}],mr:[{mr:[E]}],mb:[{mb:[E]}],ml:[{ml:[E]}],"space-x":[{"space-x":[A]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[A]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit",Je,t]}],"min-w":[{"min-w":["min","max","fit",Je,oo]}],"max-w":[{"max-w":["0","none","full","min","max","fit","prose",{screen:[Yi]},Yi,Je]}],h:[{h:[Je,t,"auto","min","max","fit"]}],"min-h":[{"min-h":["min","max","fit",oo,Je]}],"max-h":[{"max-h":[Je,t,"min","max","fit"]}],"font-size":[{text:["base",Yi,Gi]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",ch]}],"font-family":[{font:[cu]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractons"],tracking:[{tracking:["tighter","tight","normal","wide","wider","widest",Je]}],"line-clamp":[{"line-clamp":["none",ha,ch]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",oo,Je]}],"list-image":[{"list-image":["none",Je]}],"list-style-type":[{list:["none","disc","decimal",Je]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[e]}],"placeholder-opacity":[{"placeholder-opacity":[_]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[e]}],"text-opacity":[{"text-opacity":[_]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...N(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",oo,Gi]}],"underline-offset":[{"underline-offset":["auto",oo,Je]}],"text-decoration-color":[{decoration:[e]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],indent:[{indent:X()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Je]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",Je]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[_]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...F(),tF]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",eF]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},rF]}],"bg-color":[{bg:[e]}],"gradient-from-pos":[{from:[b]}],"gradient-via-pos":[{via:[b]}],"gradient-to-pos":[{to:[b]}],"gradient-from":[{from:[y]}],"gradient-via":[{via:[y]}],"gradient-to":[{to:[y]}],rounded:[{rounded:[i]}],"rounded-s":[{"rounded-s":[i]}],"rounded-e":[{"rounded-e":[i]}],"rounded-t":[{"rounded-t":[i]}],"rounded-r":[{"rounded-r":[i]}],"rounded-b":[{"rounded-b":[i]}],"rounded-l":[{"rounded-l":[i]}],"rounded-ss":[{"rounded-ss":[i]}],"rounded-se":[{"rounded-se":[i]}],"rounded-ee":[{"rounded-ee":[i]}],"rounded-es":[{"rounded-es":[i]}],"rounded-tl":[{"rounded-tl":[i]}],"rounded-tr":[{"rounded-tr":[i]}],"rounded-br":[{"rounded-br":[i]}],"rounded-bl":[{"rounded-bl":[i]}],"border-w":[{border:[l]}],"border-w-x":[{"border-x":[l]}],"border-w-y":[{"border-y":[l]}],"border-w-s":[{"border-s":[l]}],"border-w-e":[{"border-e":[l]}],"border-w-t":[{"border-t":[l]}],"border-w-r":[{"border-r":[l]}],"border-w-b":[{"border-b":[l]}],"border-w-l":[{"border-l":[l]}],"border-opacity":[{"border-opacity":[_]}],"border-style":[{border:[...N(),"hidden"]}],"divide-x":[{"divide-x":[l]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[l]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[_]}],"divide-style":[{divide:N()}],"border-color":[{border:[o]}],"border-color-x":[{"border-x":[o]}],"border-color-y":[{"border-y":[o]}],"border-color-t":[{"border-t":[o]}],"border-color-r":[{"border-r":[o]}],"border-color-b":[{"border-b":[o]}],"border-color-l":[{"border-l":[o]}],"divide-color":[{divide:[o]}],"outline-style":[{outline:["",...N()]}],"outline-offset":[{"outline-offset":[oo,Je]}],"outline-w":[{outline:[oo,Gi]}],"outline-color":[{outline:[e]}],"ring-w":[{ring:ae()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[e]}],"ring-opacity":[{"ring-opacity":[_]}],"ring-offset-w":[{"ring-offset":[oo,Gi]}],"ring-offset-color":[{"ring-offset":[e]}],shadow:[{shadow:["","inner","none",Yi,oF]}],"shadow-color":[{shadow:[cu]}],opacity:[{opacity:[_]}],"mix-blend":[{"mix-blend":ie()}],"bg-blend":[{"bg-blend":ie()}],filter:[{filter:["","none"]}],blur:[{blur:[n]}],brightness:[{brightness:[r]}],contrast:[{contrast:[u]}],"drop-shadow":[{"drop-shadow":["","none",Yi,Je]}],grayscale:[{grayscale:[f]}],"hue-rotate":[{"hue-rotate":[m]}],invert:[{invert:[p]}],saturate:[{saturate:[C]}],sepia:[{sepia:[P]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[n]}],"backdrop-brightness":[{"backdrop-brightness":[r]}],"backdrop-contrast":[{"backdrop-contrast":[u]}],"backdrop-grayscale":[{"backdrop-grayscale":[f]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[m]}],"backdrop-invert":[{"backdrop-invert":[p]}],"backdrop-opacity":[{"backdrop-opacity":[_]}],"backdrop-saturate":[{"backdrop-saturate":[C]}],"backdrop-sepia":[{"backdrop-sepia":[P]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":[s]}],"border-spacing-x":[{"border-spacing-x":[s]}],"border-spacing-y":[{"border-spacing-y":[s]}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["none","all","","colors","opacity","shadow","transform",Je]}],duration:[{duration:ce()}],ease:[{ease:["linear","in","out","in-out",Je]}],delay:[{delay:ce()}],animate:[{animate:["none","spin","ping","pulse","bounce",Je]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[R]}],"scale-x":[{"scale-x":[R]}],"scale-y":[{"scale-y":[R]}],rotate:[{rotate:[lu,Je]}],"translate-x":[{"translate-x":[D]}],"translate-y":[{"translate-y":[D]}],"skew-x":[{"skew-x":[M]}],"skew-y":[{"skew-y":[M]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",Je]}],accent:[{accent:["auto",e]}],appearance:["appearance-none"],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",Je]}],"caret-color":[{caret:[e]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":X()}],"scroll-mx":[{"scroll-mx":X()}],"scroll-my":[{"scroll-my":X()}],"scroll-ms":[{"scroll-ms":X()}],"scroll-me":[{"scroll-me":X()}],"scroll-mt":[{"scroll-mt":X()}],"scroll-mr":[{"scroll-mr":X()}],"scroll-mb":[{"scroll-mb":X()}],"scroll-ml":[{"scroll-ml":X()}],"scroll-p":[{"scroll-p":X()}],"scroll-px":[{"scroll-px":X()}],"scroll-py":[{"scroll-py":X()}],"scroll-ps":[{"scroll-ps":X()}],"scroll-pe":[{"scroll-pe":X()}],"scroll-pt":[{"scroll-pt":X()}],"scroll-pr":[{"scroll-pr":X()}],"scroll-pb":[{"scroll-pb":X()}],"scroll-pl":[{"scroll-pl":X()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",Je]}],fill:[{fill:[e,"none"]}],"stroke-w":[{stroke:[oo,Gi,ch]}],stroke:[{stroke:[e,"none"]}],sr:["sr-only","not-sr-only"]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]}}}const tx=HL(lF),cF=40,fs="inpaint",uh="diffusers_sd",oC="diffusers_sdxl",dh="diffusers_sd_inpaint",iC="diffusers_sdxl_inpaint",d0="diffusers_other",Xy="#ffcc00bb",sC="ldm",aC="cv2",Gk="Fantasy-Studio/Paint-by-Example",uF="timbrooks/instruct-pix2pix",dF="Sanster/PowerPaint-V1-stable-diffusion-inpainting",fF="Sanster/AnyText",hF="out of frame, lowres, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, disfigured, gross proportions, malformed limbs, watermark, signature";function Ce(...e){return tx(Bk(e))}function pF(){async function e(r=""){return(await fetch(r,{method:"GET",cache:"no-cache"})).json()}const t=()=>{const r=document.location;e(r+"/flaskwebgui-keep-server-alive").then(i=>i)},n=3*1e3;t(),setInterval(t,n)}function lC(e){const t=e.split(",")[0].split(":")[1].split(";")[0],n=atob(e.split(",")[1]),r=[];for(let o=0;o{const o=e.src,i=e;i.onload=n,i.onerror=s=>{i.src=o,r(s)},i.src=t})}async function mF(e){const t=URL.createObjectURL(e),n=new Image;return await Vh(n,t),n}function cC(e){return new Promise((t,n)=>{const r=new Image;r.addEventListener("load",()=>{t(r)}),r.addEventListener("error",o=>{n(o)}),r.src=e.toDataURL()})}function gF(e){return new Promise((t,n)=>{const r=new FileReader;r.onload=()=>{const o=new Image;o.onload=()=>{t(o)},o.onerror=()=>{n("无法加载图像。")},o.src=r.result},r.onerror=()=>{n("无法读取文件。")},r.readAsDataURL(e)})}function Nu(e,t,n){return fetch(e).then(function(r){return r.arrayBuffer()}).then(function(r){return new File([r],t,{type:n})})}async function vF(){try{const{state:e}=await navigator.permissions.query({name:"clipboard-write"});return e==="granted"}catch{return!1}}function yF(e,t){return new Promise((n,r)=>e.toBlob(async o=>{o?n(o):r(new Error("Expected toBlob() to be defined"))},t))}const wF=async e=>{const t=[new ClipboardItem({[e.type]:e})];await navigator.clipboard.write(t)};function uC(e){return e.nativeEvent.button===2}function dC(e){return e.nativeEvent.button===1}async function xF(e){const t=await yF(e,"image/png");try{await wF(t)}catch{console.log("Copy image failed!")}}function bF(e,t){const n=document.createElement("a");n.href=e,n.download=t,n.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0,view:window})),setTimeout(()=>{n.remove()},100)}function f0(e){const t=e.nativeEvent;return{x:t.offsetX,y:t.offsetY}}function Yk(e,t,n=Xy){e.strokeStyle=n,e.lineCap="round",e.lineJoin="round",t.forEach(r=>{!(r!=null&&r.pts.length)||!r.size||(e.lineWidth=r.size,e.beginPath(),e.moveTo(r.pts[0].x,r.pts[0].y),r.pts.forEach(o=>e.lineTo(o.x,o.y)),e.stroke())})}const Wh=(e,t,n,r=[],o="white")=>{const i=document.createElement("canvas");i.width=e,i.height=t;const s=i.getContext("2d");if(!s)throw new Error("could not retrieve mask canvas");return r.forEach(l=>{s.drawImage(l,0,0,e,t)}),n.forEach(l=>{Yk(s,l,o)}),i},Du=e=>new Promise((t,n)=>{const r=new FileReader;r.onload=o=>{var s;const i=(s=o.target)==null?void 0:s.result;t(i)},r.onerror=o=>{n(o)},r.readAsDataURL(e)});function Xk(e,t){return function(){return e.apply(t,arguments)}}const{toString:SF}=Object.prototype,{getPrototypeOf:nx}=Object,Tm=(e=>t=>{const n=SF.call(t);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),ei=e=>(e=e.toLowerCase(),t=>Tm(t)===e),Pm=e=>t=>typeof t===e,{isArray:Sc}=Array,rd=Pm("undefined");function _F(e){return e!==null&&!rd(e)&&e.constructor!==null&&!rd(e.constructor)&&Kr(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const Zk=ei("ArrayBuffer");function EF(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&Zk(e.buffer),t}const CF=Pm("string"),Kr=Pm("function"),qk=Pm("number"),Am=e=>e!==null&&typeof e=="object",$F=e=>e===!0||e===!1,Hh=e=>{if(Tm(e)!=="object")return!1;const t=nx(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},RF=ei("Date"),kF=ei("File"),TF=ei("Blob"),PF=ei("FileList"),AF=e=>Am(e)&&Kr(e.pipe),MF=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||Kr(e.append)&&((t=Tm(e))==="formdata"||t==="object"&&Kr(e.toString)&&e.toString()==="[object FormData]"))},OF=ei("URLSearchParams"),NF=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function Nd(e,t,{allOwnKeys:n=!1}={}){if(e===null||typeof e>"u")return;let r,o;if(typeof e!="object"&&(e=[e]),Sc(e))for(r=0,o=e.length;r0;)if(o=n[r],t===o.toLowerCase())return o;return null}const Jk=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,eT=e=>!rd(e)&&e!==Jk;function Zy(){const{caseless:e}=eT(this)&&this||{},t={},n=(r,o)=>{const i=e&&Qk(t,o)||o;Hh(t[i])&&Hh(r)?t[i]=Zy(t[i],r):Hh(r)?t[i]=Zy({},r):Sc(r)?t[i]=r.slice():t[i]=r};for(let r=0,o=arguments.length;r(Nd(t,(o,i)=>{n&&Kr(o)?e[i]=Xk(o,n):e[i]=o},{allOwnKeys:r}),e),IF=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),LF=(e,t,n,r)=>{e.prototype=Object.create(t.prototype,r),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),n&&Object.assign(e.prototype,n)},FF=(e,t,n,r)=>{let o,i,s;const l={};if(t=t||{},e==null)return t;do{for(o=Object.getOwnPropertyNames(e),i=o.length;i-- >0;)s=o[i],(!r||r(s,e,t))&&!l[s]&&(t[s]=e[s],l[s]=!0);e=n!==!1&&nx(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},jF=(e,t,n)=>{e=String(e),(n===void 0||n>e.length)&&(n=e.length),n-=t.length;const r=e.indexOf(t,n);return r!==-1&&r===n},zF=e=>{if(!e)return null;if(Sc(e))return e;let t=e.length;if(!qk(t))return null;const n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},BF=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&nx(Uint8Array)),UF=(e,t)=>{const r=(e&&e[Symbol.iterator]).call(e);let o;for(;(o=r.next())&&!o.done;){const i=o.value;t.call(e,i[0],i[1])}},VF=(e,t)=>{let n;const r=[];for(;(n=e.exec(t))!==null;)r.push(n);return r},WF=ei("HTMLFormElement"),HF=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,r,o){return r.toUpperCase()+o}),fC=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),KF=ei("RegExp"),tT=(e,t)=>{const n=Object.getOwnPropertyDescriptors(e),r={};Nd(n,(o,i)=>{let s;(s=t(o,i,e))!==!1&&(r[i]=s||o)}),Object.defineProperties(e,r)},GF=e=>{tT(e,(t,n)=>{if(Kr(e)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;const r=e[n];if(Kr(r)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},YF=(e,t)=>{const n={},r=o=>{o.forEach(i=>{n[i]=!0})};return Sc(e)?r(e):r(String(e).split(t)),n},XF=()=>{},ZF=(e,t)=>(e=+e,Number.isFinite(e)?e:t),h0="abcdefghijklmnopqrstuvwxyz",hC="0123456789",nT={DIGIT:hC,ALPHA:h0,ALPHA_DIGIT:h0+h0.toUpperCase()+hC},qF=(e=16,t=nT.ALPHA_DIGIT)=>{let n="";const{length:r}=t;for(;e--;)n+=t[Math.random()*r|0];return n};function QF(e){return!!(e&&Kr(e.append)&&e[Symbol.toStringTag]==="FormData"&&e[Symbol.iterator])}const JF=e=>{const t=new Array(10),n=(r,o)=>{if(Am(r)){if(t.indexOf(r)>=0)return;if(!("toJSON"in r)){t[o]=r;const i=Sc(r)?[]:{};return Nd(r,(s,l)=>{const u=n(s,o+1);!rd(u)&&(i[l]=u)}),t[o]=void 0,i}}return r};return n(e,0)},ej=ei("AsyncFunction"),tj=e=>e&&(Am(e)||Kr(e))&&Kr(e.then)&&Kr(e.catch),oe={isArray:Sc,isArrayBuffer:Zk,isBuffer:_F,isFormData:MF,isArrayBufferView:EF,isString:CF,isNumber:qk,isBoolean:$F,isObject:Am,isPlainObject:Hh,isUndefined:rd,isDate:RF,isFile:kF,isBlob:TF,isRegExp:KF,isFunction:Kr,isStream:AF,isURLSearchParams:OF,isTypedArray:BF,isFileList:PF,forEach:Nd,merge:Zy,extend:DF,trim:NF,stripBOM:IF,inherits:LF,toFlatObject:FF,kindOf:Tm,kindOfTest:ei,endsWith:jF,toArray:zF,forEachEntry:UF,matchAll:VF,isHTMLForm:WF,hasOwnProperty:fC,hasOwnProp:fC,reduceDescriptors:tT,freezeMethods:GF,toObjectSet:YF,toCamelCase:HF,noop:XF,toFiniteNumber:ZF,findKey:Qk,global:Jk,isContextDefined:eT,ALPHABET:nT,generateString:qF,isSpecCompliantForm:QF,toJSONObject:JF,isAsyncFn:ej,isThenable:tj};function ut(e,t,n,r,o){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),n&&(this.config=n),r&&(this.request=r),o&&(this.response=o)}oe.inherits(ut,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:oe.toJSONObject(this.config),code:this.code,status:this.response&&this.response.status?this.response.status:null}}});const rT=ut.prototype,oT={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{oT[e]={value:e}});Object.defineProperties(ut,oT);Object.defineProperty(rT,"isAxiosError",{value:!0});ut.from=(e,t,n,r,o,i)=>{const s=Object.create(rT);return oe.toFlatObject(e,s,function(u){return u!==Error.prototype},l=>l!=="isAxiosError"),ut.call(s,e.message,t,n,r,o),s.cause=e,s.name=e.name,i&&Object.assign(s,i),s};const nj=null;function qy(e){return oe.isPlainObject(e)||oe.isArray(e)}function iT(e){return oe.endsWith(e,"[]")?e.slice(0,-2):e}function pC(e,t,n){return e?e.concat(t).map(function(o,i){return o=iT(o),!n&&i?"["+o+"]":o}).join(n?".":""):t}function rj(e){return oe.isArray(e)&&!e.some(qy)}const oj=oe.toFlatObject(oe,{},null,function(t){return/^is[A-Z]/.test(t)});function Mm(e,t,n){if(!oe.isObject(e))throw new TypeError("target must be an object");t=t||new FormData,n=oe.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(S,E){return!oe.isUndefined(E[S])});const r=n.metaTokens,o=n.visitor||m,i=n.dots,s=n.indexes,u=(n.Blob||typeof Blob<"u"&&Blob)&&oe.isSpecCompliantForm(t);if(!oe.isFunction(o))throw new TypeError("visitor must be a function");function f(b){if(b===null)return"";if(oe.isDate(b))return b.toISOString();if(!u&&oe.isBlob(b))throw new ut("Blob is not supported. Use a Buffer instead.");return oe.isArrayBuffer(b)||oe.isTypedArray(b)?u&&typeof Blob=="function"?new Blob([b]):Buffer.from(b):b}function m(b,S,E){let _=b;if(b&&!E&&typeof b=="object"){if(oe.endsWith(S,"{}"))S=r?S:S.slice(0,-2),b=JSON.stringify(b);else if(oe.isArray(b)&&rj(b)||(oe.isFileList(b)||oe.endsWith(S,"[]"))&&(_=oe.toArray(b)))return S=iT(S),_.forEach(function(C,R){!(oe.isUndefined(C)||C===null)&&t.append(s===!0?pC([S],R,i):s===null?S:S+"[]",f(C))}),!1}return qy(b)?!0:(t.append(pC(E,S,i),f(b)),!1)}const p=[],g=Object.assign(oj,{defaultVisitor:m,convertValue:f,isVisitable:qy});function y(b,S){if(!oe.isUndefined(b)){if(p.indexOf(b)!==-1)throw Error("Circular reference detected in "+S.join("."));p.push(b),oe.forEach(b,function(_,x){(!(oe.isUndefined(_)||_===null)&&o.call(t,_,oe.isString(x)?x.trim():x,S,g))===!0&&y(_,S?S.concat(x):[x])}),p.pop()}}if(!oe.isObject(e))throw new TypeError("data must be an object");return y(e),t}function mC(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(r){return t[r]})}function rx(e,t){this._pairs=[],e&&Mm(e,this,t)}const sT=rx.prototype;sT.append=function(t,n){this._pairs.push([t,n])};sT.toString=function(t){const n=t?function(r){return t.call(this,r,mC)}:mC;return this._pairs.map(function(o){return n(o[0])+"="+n(o[1])},"").join("&")};function ij(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function aT(e,t,n){if(!t)return e;const r=n&&n.encode||ij,o=n&&n.serialize;let i;if(o?i=o(t,n):i=oe.isURLSearchParams(t)?t.toString():new rx(t,n).toString(r),i){const s=e.indexOf("#");s!==-1&&(e=e.slice(0,s)),e+=(e.indexOf("?")===-1?"?":"&")+i}return e}class sj{constructor(){this.handlers=[]}use(t,n,r){return this.handlers.push({fulfilled:t,rejected:n,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){oe.forEach(this.handlers,function(r){r!==null&&t(r)})}}const gC=sj,lT={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},aj=typeof URLSearchParams<"u"?URLSearchParams:rx,lj=typeof FormData<"u"?FormData:null,cj=typeof Blob<"u"?Blob:null,uj={isBrowser:!0,classes:{URLSearchParams:aj,FormData:lj,Blob:cj},protocols:["http","https","file","blob","url","data"]},cT=typeof window<"u"&&typeof document<"u",dj=(e=>cT&&["ReactNative","NativeScript","NS"].indexOf(e)<0)(typeof navigator<"u"&&navigator.product),fj=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",hj=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:cT,hasStandardBrowserEnv:dj,hasStandardBrowserWebWorkerEnv:fj},Symbol.toStringTag,{value:"Module"})),zo={...hj,...uj};function pj(e,t){return Mm(e,new zo.classes.URLSearchParams,Object.assign({visitor:function(n,r,o,i){return zo.isNode&&oe.isBuffer(n)?(this.append(r,n.toString("base64")),!1):i.defaultVisitor.apply(this,arguments)}},t))}function mj(e){return oe.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function gj(e){const t={},n=Object.keys(e);let r;const o=n.length;let i;for(r=0;r=n.length;return s=!s&&oe.isArray(o)?o.length:s,u?(oe.hasOwnProp(o,s)?o[s]=[o[s],r]:o[s]=r,!l):((!o[s]||!oe.isObject(o[s]))&&(o[s]=[]),t(n,r,o[s],i)&&oe.isArray(o[s])&&(o[s]=gj(o[s])),!l)}if(oe.isFormData(e)&&oe.isFunction(e.entries)){const n={};return oe.forEachEntry(e,(r,o)=>{t(mj(r),o,n,0)}),n}return null}function vj(e,t,n){if(oe.isString(e))try{return(t||JSON.parse)(e),oe.trim(e)}catch(r){if(r.name!=="SyntaxError")throw r}return(n||JSON.stringify)(e)}const ox={transitional:lT,adapter:["xhr","http"],transformRequest:[function(t,n){const r=n.getContentType()||"",o=r.indexOf("application/json")>-1,i=oe.isObject(t);if(i&&oe.isHTMLForm(t)&&(t=new FormData(t)),oe.isFormData(t))return o&&o?JSON.stringify(uT(t)):t;if(oe.isArrayBuffer(t)||oe.isBuffer(t)||oe.isStream(t)||oe.isFile(t)||oe.isBlob(t))return t;if(oe.isArrayBufferView(t))return t.buffer;if(oe.isURLSearchParams(t))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let l;if(i){if(r.indexOf("application/x-www-form-urlencoded")>-1)return pj(t,this.formSerializer).toString();if((l=oe.isFileList(t))||r.indexOf("multipart/form-data")>-1){const u=this.env&&this.env.FormData;return Mm(l?{"files[]":t}:t,u&&new u,this.formSerializer)}}return i||o?(n.setContentType("application/json",!1),vj(t)):t}],transformResponse:[function(t){const n=this.transitional||ox.transitional,r=n&&n.forcedJSONParsing,o=this.responseType==="json";if(t&&oe.isString(t)&&(r&&!this.responseType||o)){const s=!(n&&n.silentJSONParsing)&&o;try{return JSON.parse(t)}catch(l){if(s)throw l.name==="SyntaxError"?ut.from(l,ut.ERR_BAD_RESPONSE,this,null,this.response):l}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:zo.classes.FormData,Blob:zo.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};oe.forEach(["delete","get","head","post","put","patch"],e=>{ox.headers[e]={}});const ix=ox,yj=oe.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),wj=e=>{const t={};let n,r,o;return e&&e.split(` +`).forEach(function(s){o=s.indexOf(":"),n=s.substring(0,o).trim().toLowerCase(),r=s.substring(o+1).trim(),!(!n||t[n]&&yj[n])&&(n==="set-cookie"?t[n]?t[n].push(r):t[n]=[r]:t[n]=t[n]?t[n]+", "+r:r)}),t},vC=Symbol("internals");function uu(e){return e&&String(e).trim().toLowerCase()}function Kh(e){return e===!1||e==null?e:oe.isArray(e)?e.map(Kh):String(e)}function xj(e){const t=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=n.exec(e);)t[r[1]]=r[2];return t}const bj=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function p0(e,t,n,r,o){if(oe.isFunction(r))return r.call(this,t,n);if(o&&(t=n),!!oe.isString(t)){if(oe.isString(r))return t.indexOf(r)!==-1;if(oe.isRegExp(r))return r.test(t)}}function Sj(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,n,r)=>n.toUpperCase()+r)}function _j(e,t){const n=oe.toCamelCase(" "+t);["get","set","has"].forEach(r=>{Object.defineProperty(e,r+n,{value:function(o,i,s){return this[r].call(this,t,o,i,s)},configurable:!0})})}class Om{constructor(t){t&&this.set(t)}set(t,n,r){const o=this;function i(l,u,f){const m=uu(u);if(!m)throw new Error("header name must be a non-empty string");const p=oe.findKey(o,m);(!p||o[p]===void 0||f===!0||f===void 0&&o[p]!==!1)&&(o[p||u]=Kh(l))}const s=(l,u)=>oe.forEach(l,(f,m)=>i(f,m,u));return oe.isPlainObject(t)||t instanceof this.constructor?s(t,n):oe.isString(t)&&(t=t.trim())&&!bj(t)?s(wj(t),n):t!=null&&i(n,t,r),this}get(t,n){if(t=uu(t),t){const r=oe.findKey(this,t);if(r){const o=this[r];if(!n)return o;if(n===!0)return xj(o);if(oe.isFunction(n))return n.call(this,o,r);if(oe.isRegExp(n))return n.exec(o);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,n){if(t=uu(t),t){const r=oe.findKey(this,t);return!!(r&&this[r]!==void 0&&(!n||p0(this,this[r],r,n)))}return!1}delete(t,n){const r=this;let o=!1;function i(s){if(s=uu(s),s){const l=oe.findKey(r,s);l&&(!n||p0(r,r[l],l,n))&&(delete r[l],o=!0)}}return oe.isArray(t)?t.forEach(i):i(t),o}clear(t){const n=Object.keys(this);let r=n.length,o=!1;for(;r--;){const i=n[r];(!t||p0(this,this[i],i,t,!0))&&(delete this[i],o=!0)}return o}normalize(t){const n=this,r={};return oe.forEach(this,(o,i)=>{const s=oe.findKey(r,i);if(s){n[s]=Kh(o),delete n[i];return}const l=t?Sj(i):String(i).trim();l!==i&&delete n[i],n[l]=Kh(o),r[l]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){const n=Object.create(null);return oe.forEach(this,(r,o)=>{r!=null&&r!==!1&&(n[o]=t&&oe.isArray(r)?r.join(", "):r)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,n])=>t+": "+n).join(` +`)}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...n){const r=new this(t);return n.forEach(o=>r.set(o)),r}static accessor(t){const r=(this[vC]=this[vC]={accessors:{}}).accessors,o=this.prototype;function i(s){const l=uu(s);r[l]||(_j(o,s),r[l]=!0)}return oe.isArray(t)?t.forEach(i):i(t),this}}Om.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);oe.reduceDescriptors(Om.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(r){this[n]=r}}});oe.freezeMethods(Om);const xi=Om;function m0(e,t){const n=this||ix,r=t||n,o=xi.from(r.headers);let i=r.data;return oe.forEach(e,function(l){i=l.call(n,i,o.normalize(),t?t.status:void 0)}),o.normalize(),i}function dT(e){return!!(e&&e.__CANCEL__)}function Dd(e,t,n){ut.call(this,e??"canceled",ut.ERR_CANCELED,t,n),this.name="CanceledError"}oe.inherits(Dd,ut,{__CANCEL__:!0});function Ej(e,t,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?e(n):t(new ut("Request failed with status code "+n.status,[ut.ERR_BAD_REQUEST,ut.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}const Cj=zo.hasStandardBrowserEnv?{write(e,t,n,r,o,i){const s=[e+"="+encodeURIComponent(t)];oe.isNumber(n)&&s.push("expires="+new Date(n).toGMTString()),oe.isString(r)&&s.push("path="+r),oe.isString(o)&&s.push("domain="+o),i===!0&&s.push("secure"),document.cookie=s.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function $j(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function Rj(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e}function fT(e,t){return e&&!$j(t)?Rj(e,t):t}const kj=zo.hasStandardBrowserEnv?function(){const t=/(msie|trident)/i.test(navigator.userAgent),n=document.createElement("a");let r;function o(i){let s=i;return t&&(n.setAttribute("href",s),s=n.href),n.setAttribute("href",s),{href:n.href,protocol:n.protocol?n.protocol.replace(/:$/,""):"",host:n.host,search:n.search?n.search.replace(/^\?/,""):"",hash:n.hash?n.hash.replace(/^#/,""):"",hostname:n.hostname,port:n.port,pathname:n.pathname.charAt(0)==="/"?n.pathname:"/"+n.pathname}}return r=o(window.location.href),function(s){const l=oe.isString(s)?o(s):s;return l.protocol===r.protocol&&l.host===r.host}}():function(){return function(){return!0}}();function Tj(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function Pj(e,t){e=e||10;const n=new Array(e),r=new Array(e);let o=0,i=0,s;return t=t!==void 0?t:1e3,function(u){const f=Date.now(),m=r[i];s||(s=f),n[o]=u,r[o]=f;let p=i,g=0;for(;p!==o;)g+=n[p++],p=p%e;if(o=(o+1)%e,o===i&&(i=(i+1)%e),f-s{const i=o.loaded,s=o.lengthComputable?o.total:void 0,l=i-n,u=r(l),f=i<=s;n=i;const m={loaded:i,total:s,progress:s?i/s:void 0,bytes:l,rate:u||void 0,estimated:u&&s&&f?(s-i)/u:void 0,event:o};m[t?"download":"upload"]=!0,e(m)}}const Aj=typeof XMLHttpRequest<"u",Mj=Aj&&function(e){return new Promise(function(n,r){let o=e.data;const i=xi.from(e.headers).normalize();let{responseType:s,withXSRFToken:l}=e,u;function f(){e.cancelToken&&e.cancelToken.unsubscribe(u),e.signal&&e.signal.removeEventListener("abort",u)}let m;if(oe.isFormData(o)){if(zo.hasStandardBrowserEnv||zo.hasStandardBrowserWebWorkerEnv)i.setContentType(!1);else if((m=i.getContentType())!==!1){const[S,...E]=m?m.split(";").map(_=>_.trim()).filter(Boolean):[];i.setContentType([S||"multipart/form-data",...E].join("; "))}}let p=new XMLHttpRequest;if(e.auth){const S=e.auth.username||"",E=e.auth.password?unescape(encodeURIComponent(e.auth.password)):"";i.set("Authorization","Basic "+btoa(S+":"+E))}const g=fT(e.baseURL,e.url);p.open(e.method.toUpperCase(),aT(g,e.params,e.paramsSerializer),!0),p.timeout=e.timeout;function y(){if(!p)return;const S=xi.from("getAllResponseHeaders"in p&&p.getAllResponseHeaders()),_={data:!s||s==="text"||s==="json"?p.responseText:p.response,status:p.status,statusText:p.statusText,headers:S,config:e,request:p};Ej(function(C){n(C),f()},function(C){r(C),f()},_),p=null}if("onloadend"in p?p.onloadend=y:p.onreadystatechange=function(){!p||p.readyState!==4||p.status===0&&!(p.responseURL&&p.responseURL.indexOf("file:")===0)||setTimeout(y)},p.onabort=function(){p&&(r(new ut("Request aborted",ut.ECONNABORTED,e,p)),p=null)},p.onerror=function(){r(new ut("Network Error",ut.ERR_NETWORK,e,p)),p=null},p.ontimeout=function(){let E=e.timeout?"timeout of "+e.timeout+"ms exceeded":"timeout exceeded";const _=e.transitional||lT;e.timeoutErrorMessage&&(E=e.timeoutErrorMessage),r(new ut(E,_.clarifyTimeoutError?ut.ETIMEDOUT:ut.ECONNABORTED,e,p)),p=null},zo.hasStandardBrowserEnv&&(l&&oe.isFunction(l)&&(l=l(e)),l||l!==!1&&kj(g))){const S=e.xsrfHeaderName&&e.xsrfCookieName&&Cj.read(e.xsrfCookieName);S&&i.set(e.xsrfHeaderName,S)}o===void 0&&i.setContentType(null),"setRequestHeader"in p&&oe.forEach(i.toJSON(),function(E,_){p.setRequestHeader(_,E)}),oe.isUndefined(e.withCredentials)||(p.withCredentials=!!e.withCredentials),s&&s!=="json"&&(p.responseType=e.responseType),typeof e.onDownloadProgress=="function"&&p.addEventListener("progress",yC(e.onDownloadProgress,!0)),typeof e.onUploadProgress=="function"&&p.upload&&p.upload.addEventListener("progress",yC(e.onUploadProgress)),(e.cancelToken||e.signal)&&(u=S=>{p&&(r(!S||S.type?new Dd(null,e,p):S),p.abort(),p=null)},e.cancelToken&&e.cancelToken.subscribe(u),e.signal&&(e.signal.aborted?u():e.signal.addEventListener("abort",u)));const b=Tj(g);if(b&&zo.protocols.indexOf(b)===-1){r(new ut("Unsupported protocol "+b+":",ut.ERR_BAD_REQUEST,e));return}p.send(o||null)})},Qy={http:nj,xhr:Mj};oe.forEach(Qy,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});const wC=e=>`- ${e}`,Oj=e=>oe.isFunction(e)||e===null||e===!1,hT={getAdapter:e=>{e=oe.isArray(e)?e:[e];const{length:t}=e;let n,r;const o={};for(let i=0;i`adapter ${l} `+(u===!1?"is not supported by the environment":"is not available in the build"));let s=t?i.length>1?`since : +`+i.map(wC).join(` +`):" "+wC(i[0]):"as no adapter specified";throw new ut("There is no suitable adapter to dispatch the request "+s,"ERR_NOT_SUPPORT")}return r},adapters:Qy};function g0(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Dd(null,e)}function xC(e){return g0(e),e.headers=xi.from(e.headers),e.data=m0.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),hT.getAdapter(e.adapter||ix.adapter)(e).then(function(r){return g0(e),r.data=m0.call(e,e.transformResponse,r),r.headers=xi.from(r.headers),r},function(r){return dT(r)||(g0(e),r&&r.response&&(r.response.data=m0.call(e,e.transformResponse,r.response),r.response.headers=xi.from(r.response.headers))),Promise.reject(r)})}const bC=e=>e instanceof xi?e.toJSON():e;function ic(e,t){t=t||{};const n={};function r(f,m,p){return oe.isPlainObject(f)&&oe.isPlainObject(m)?oe.merge.call({caseless:p},f,m):oe.isPlainObject(m)?oe.merge({},m):oe.isArray(m)?m.slice():m}function o(f,m,p){if(oe.isUndefined(m)){if(!oe.isUndefined(f))return r(void 0,f,p)}else return r(f,m,p)}function i(f,m){if(!oe.isUndefined(m))return r(void 0,m)}function s(f,m){if(oe.isUndefined(m)){if(!oe.isUndefined(f))return r(void 0,f)}else return r(void 0,m)}function l(f,m,p){if(p in t)return r(f,m);if(p in e)return r(void 0,f)}const u={url:i,method:i,data:i,baseURL:s,transformRequest:s,transformResponse:s,paramsSerializer:s,timeout:s,timeoutMessage:s,withCredentials:s,withXSRFToken:s,adapter:s,responseType:s,xsrfCookieName:s,xsrfHeaderName:s,onUploadProgress:s,onDownloadProgress:s,decompress:s,maxContentLength:s,maxBodyLength:s,beforeRedirect:s,transport:s,httpAgent:s,httpsAgent:s,cancelToken:s,socketPath:s,responseEncoding:s,validateStatus:l,headers:(f,m)=>o(bC(f),bC(m),!0)};return oe.forEach(Object.keys(Object.assign({},e,t)),function(m){const p=u[m]||o,g=p(e[m],t[m],m);oe.isUndefined(g)&&p!==l||(n[m]=g)}),n}const pT="1.6.2",sx={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{sx[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const SC={};sx.transitional=function(t,n,r){function o(i,s){return"[Axios v"+pT+"] Transitional option '"+i+"'"+s+(r?". "+r:"")}return(i,s,l)=>{if(t===!1)throw new ut(o(s," has been removed"+(n?" in "+n:"")),ut.ERR_DEPRECATED);return n&&!SC[s]&&(SC[s]=!0,console.warn(o(s," has been deprecated since v"+n+" and will be removed in the near future"))),t?t(i,s,l):!0}};function Nj(e,t,n){if(typeof e!="object")throw new ut("options must be an object",ut.ERR_BAD_OPTION_VALUE);const r=Object.keys(e);let o=r.length;for(;o-- >0;){const i=r[o],s=t[i];if(s){const l=e[i],u=l===void 0||s(l,i,e);if(u!==!0)throw new ut("option "+i+" must be "+u,ut.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new ut("Unknown option "+i,ut.ERR_BAD_OPTION)}}const Jy={assertOptions:Nj,validators:sx},Xi=Jy.validators;class Op{constructor(t){this.defaults=t,this.interceptors={request:new gC,response:new gC}}request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=ic(this.defaults,n);const{transitional:r,paramsSerializer:o,headers:i}=n;r!==void 0&&Jy.assertOptions(r,{silentJSONParsing:Xi.transitional(Xi.boolean),forcedJSONParsing:Xi.transitional(Xi.boolean),clarifyTimeoutError:Xi.transitional(Xi.boolean)},!1),o!=null&&(oe.isFunction(o)?n.paramsSerializer={serialize:o}:Jy.assertOptions(o,{encode:Xi.function,serialize:Xi.function},!0)),n.method=(n.method||this.defaults.method||"get").toLowerCase();let s=i&&oe.merge(i.common,i[n.method]);i&&oe.forEach(["delete","get","head","post","put","patch","common"],b=>{delete i[b]}),n.headers=xi.concat(s,i);const l=[];let u=!0;this.interceptors.request.forEach(function(S){typeof S.runWhen=="function"&&S.runWhen(n)===!1||(u=u&&S.synchronous,l.unshift(S.fulfilled,S.rejected))});const f=[];this.interceptors.response.forEach(function(S){f.push(S.fulfilled,S.rejected)});let m,p=0,g;if(!u){const b=[xC.bind(this),void 0];for(b.unshift.apply(b,l),b.push.apply(b,f),g=b.length,m=Promise.resolve(n);p{if(!r._listeners)return;let i=r._listeners.length;for(;i-- >0;)r._listeners[i](o);r._listeners=null}),this.promise.then=o=>{let i;const s=new Promise(l=>{r.subscribe(l),i=l}).then(o);return s.cancel=function(){r.unsubscribe(i)},s},t(function(i,s,l){r.reason||(r.reason=new Dd(i,s,l),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}static source(){let t;return{token:new ax(function(o){t=o}),cancel:t}}}const Dj=ax;function Ij(e){return function(n){return e.apply(null,n)}}function Lj(e){return oe.isObject(e)&&e.isAxiosError===!0}const e1={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(e1).forEach(([e,t])=>{e1[t]=e});const Fj=e1;function mT(e){const t=new Gh(e),n=Xk(Gh.prototype.request,t);return oe.extend(n,Gh.prototype,t,{allOwnKeys:!0}),oe.extend(n,t,null,{allOwnKeys:!0}),n.create=function(o){return mT(ic(e,o))},n}const Qt=mT(ix);Qt.Axios=Gh;Qt.CanceledError=Dd;Qt.CancelToken=Dj;Qt.isCancel=dT;Qt.VERSION=pT;Qt.toFormData=Mm;Qt.AxiosError=ut;Qt.Cancel=Qt.CanceledError;Qt.all=function(t){return Promise.all(t)};Qt.spread=Ij;Qt.isAxiosError=Lj;Qt.mergeConfig=ic;Qt.AxiosHeaders=xi;Qt.formToJSON=e=>uT(oe.isHTMLForm(e)?new FormData(e):e);Qt.getAdapter=hT.getAdapter;Qt.HttpStatusCode=Fj;Qt.default=Qt;const jj=Qt,Ls="/api/v1",_c=jj.create({baseURL:Ls});async function zj(e,t,n,r,o,i=null){const s=await Du(e),l=await Du(o),u=i?await Du(i):null,f=await fetch(`${Ls}/inpaint`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({image:s,mask:l,ldm_steps:t.ldmSteps,ldm_sampler:t.ldmSampler,zits_wireframe:t.zitsWireframe,cv2_flag:t.cv2Flag,cv2_radius:t.cv2Radius,hd_strategy:"Crop",hd_strategy_crop_triger_size:640,hd_strategy_crop_margin:128,hd_trategy_resize_imit:2048,prompt:t.prompt,negative_prompt:t.negativePrompt,use_croper:t.showCropper,croper_x:n.x,croper_y:n.y,croper_height:n.height,croper_width:n.width,use_extender:t.showExtender,extender_x:r.x,extender_y:r.y,extender_height:r.height,extender_width:r.width,sd_mask_blur:t.sdMaskBlur,sd_strength:t.sdStrength,sd_steps:t.sdSteps,sd_guidance_scale:t.sdGuidanceScale,sd_sampler:t.sdSampler,sd_seed:t.seedFixed?t.seed:-1,sd_match_histograms:t.sdMatchHistograms,sd_freeu:t.enableFreeu,sd_freeu_config:t.freeuConfig,sd_lcm_lora:t.enableLCMLora,paint_by_example_example_image:u,p2p_image_guidance_scale:t.p2pImageGuidanceScale,enable_controlnet:t.enableControlnet,controlnet_conditioning_scale:t.controlnetConditioningScale,controlnet_method:t.controlnetMethod?t.controlnetMethod:"",powerpaint_task:t.showExtender?Ol.outpainting:t.powerpaintTask})});if(f.ok){const p=await f.blob();return{blob:URL.createObjectURL(p),seed:f.headers.get("X-Seed")}}const m=await f.json();throw new Error(`Something went wrong: ${m.errors}`)}async function gT(){return(await _c.get("/server-config")).data}async function Bj(e){return(await _c.post("/model",{name:e})).data}async function v0(e,t){return _c.post("/switch_plugin_model",{plugin_name:e,model_name:t})}async function Uj(){return(await _c.get("/model")).data}async function vT(e,t,n,r,o){const i=await Du(n),l=await fetch(`${Ls}/${e?"run_plugin_gen_mask":"run_plugin_gen_image"}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t,image:i,upscale:r,clicks:o})});if(l.ok){const f=await l.blob();return{blob:URL.createObjectURL(f)}}const u=await l.json();throw new Error(u)}async function Vj(e,t){const n=await fetch(`${Ls}/media_file?tab=${e}&filename=${encodeURIComponent(t)}`,{method:"GET"});if(n.ok){const o=await n.blob();return new File([o],t,{type:n.headers.get("Content-Type")??"image/png"})}const r=await n.json();throw new Error(r.errors)}async function Wj(e){return(await _c.get("medias",{params:{tab:e}})).data}async function Hj(e,t,n){const r=await Nu(e.src,t,n),o=new FormData;o.append("file",r);try{const i=await fetch(`${Ls}/save_image`,{method:"POST",body:o});if(!i.ok){const s=await i.text();throw new Error(s)}}catch(i){throw new Error(`Something went wrong: ${i}`)}}async function Kj(e){const t=new FormData;return t.append("file",e),(await _c.post("/gen-info",t)).data}async function Gj(e,t,n){const r=await Du(e),o=await fetch(`${Ls}/adjust_mask`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mask:r,operate:t,kernel_size:n})});if(o.ok)return await o.blob();const i=await o.json();throw new Error(i)}function Yj(){const[e,t]=d.useState(null),n=d.useCallback(()=>{const r=new Headers;r.append("pragma","no-cache"),r.append("cache-control","no-cache"),fetch(`${Ls}/inputimage`,{headers:r}).then(async o=>{var l;if(!o.ok)return;const i=(l=o.headers.get("content-disposition"))==null?void 0:l.split("filename=")[1].split(";")[0],s=await o.blob();if(s&&s.type.startsWith("image")){const u=new File([s],i!==void 0?i:"inputImage");t(u)}}).catch(o=>{console.log(o)})},[t]);return d.useEffect(()=>{n()},[n]),e}function _o(e,t){if(e==null)return{};var n={},r=Object.keys(e),o,i;for(i=0;i=0)&&(n[o]=e[o]);return n}var Xj=["color"],Zj=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,Xj);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.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:r,fillRule:"evenodd",clipRule:"evenodd"}))}),qj=["color"],yT=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,qj);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M11.4669 3.72684C11.7558 3.91574 11.8369 4.30308 11.648 4.59198L7.39799 11.092C7.29783 11.2452 7.13556 11.3467 6.95402 11.3699C6.77247 11.3931 6.58989 11.3355 6.45446 11.2124L3.70446 8.71241C3.44905 8.48022 3.43023 8.08494 3.66242 7.82953C3.89461 7.57412 4.28989 7.55529 4.5453 7.78749L6.75292 9.79441L10.6018 3.90792C10.7907 3.61902 11.178 3.53795 11.4669 3.72684Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),Qj=["color"],Jj=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,Qj);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M3.13523 6.15803C3.3241 5.95657 3.64052 5.94637 3.84197 6.13523L7.5 9.56464L11.158 6.13523C11.3595 5.94637 11.6759 5.95657 11.8648 6.15803C12.0536 6.35949 12.0434 6.67591 11.842 6.86477L7.84197 10.6148C7.64964 10.7951 7.35036 10.7951 7.15803 10.6148L3.15803 6.86477C2.95657 6.67591 2.94637 6.35949 3.13523 6.15803Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),ez=["color"],tz=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,ez);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M6.1584 3.13508C6.35985 2.94621 6.67627 2.95642 6.86514 3.15788L10.6151 7.15788C10.7954 7.3502 10.7954 7.64949 10.6151 7.84182L6.86514 11.8418C6.67627 12.0433 6.35985 12.0535 6.1584 11.8646C5.95694 11.6757 5.94673 11.3593 6.1356 11.1579L9.565 7.49985L6.1356 3.84182C5.94673 3.64036 5.95694 3.32394 6.1584 3.13508Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),nz=["color"],rz=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,nz);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M3.13523 8.84197C3.3241 9.04343 3.64052 9.05363 3.84197 8.86477L7.5 5.43536L11.158 8.86477C11.3595 9.05363 11.6759 9.04343 11.8648 8.84197C12.0536 8.64051 12.0434 8.32409 11.842 8.13523L7.84197 4.38523C7.64964 4.20492 7.35036 4.20492 7.15803 4.38523L3.15803 8.13523C2.95657 8.32409 2.94637 8.64051 3.13523 8.84197Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),oz=["color"],wT=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,oz);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.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:r,fillRule:"evenodd",clipRule:"evenodd"}))}),iz=["color"],sz=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,iz);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M9.875 7.5C9.875 8.81168 8.81168 9.875 7.5 9.875C6.18832 9.875 5.125 8.81168 5.125 7.5C5.125 6.18832 6.18832 5.125 7.5 5.125C8.81168 5.125 9.875 6.18832 9.875 7.5Z",fill:r}))}),az=["color"],lz=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,az);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M10 6.5C10 8.433 8.433 10 6.5 10C4.567 10 3 8.433 3 6.5C3 4.567 4.567 3 6.5 3C8.433 3 10 4.567 10 6.5ZM9.30884 10.0159C8.53901 10.6318 7.56251 11 6.5 11C4.01472 11 2 8.98528 2 6.5C2 4.01472 4.01472 2 6.5 2C8.98528 2 11 4.01472 11 6.5C11 7.56251 10.6318 8.53901 10.0159 9.30884L12.8536 12.1464C13.0488 12.3417 13.0488 12.6583 12.8536 12.8536C12.6583 13.0488 12.3417 13.0488 12.1464 12.8536L9.30884 10.0159Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),cz=["color"],uz=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,cz);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M3.24182 2.32181C3.3919 2.23132 3.5784 2.22601 3.73338 2.30781L12.7334 7.05781C12.8974 7.14436 13 7.31457 13 7.5C13 7.68543 12.8974 7.85564 12.7334 7.94219L3.73338 12.6922C3.5784 12.774 3.3919 12.7687 3.24182 12.6782C3.09175 12.5877 3 12.4252 3 12.25V2.75C3 2.57476 3.09175 2.4123 3.24182 2.32181ZM4 3.57925V11.4207L11.4288 7.5L4 3.57925Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),dz=["color"],fz=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,dz);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M7 2H1.5C1.22386 2 1 2.22386 1 2.5V7H7V2ZM8 2V7H14V2.5C14 2.22386 13.7761 2 13.5 2H8ZM7 8H1V12.5C1 12.7761 1.22386 13 1.5 13H7V8ZM8 13V8H14V12.5C14 12.7761 13.7761 13 13.5 13H8ZM1.5 1C0.671573 1 0 1.67157 0 2.5V12.5C0 13.3284 0.671573 14 1.5 14H13.5C14.3284 14 15 13.3284 15 12.5V2.5C15 1.67157 14.3284 1 13.5 1H1.5Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),hz=["color"],pz=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,hz);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M1.5 2H13.5C13.7761 2 14 2.22386 14 2.5V7H1V2.5C1 2.22386 1.22386 2 1.5 2ZM1 8V12.5C1 12.7761 1.22386 13 1.5 13H13.5C13.7761 13 14 12.7761 14 12.5V8H1ZM0 2.5C0 1.67157 0.671573 1 1.5 1H13.5C14.3284 1 15 1.67157 15 2.5V12.5C15 13.3284 14.3284 14 13.5 14H1.5C0.671573 14 0 13.3284 0 12.5V2.5Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))});function Y(){return Y=Object.assign?Object.assign.bind():function(e){for(var t=1;te.forEach(n=>mz(n,t))}function Be(...e){return d.useCallback(Nm(...e),e)}const Zo=d.forwardRef((e,t)=>{const{children:n,...r}=e,o=d.Children.toArray(n),i=o.find(gz);if(i){const s=i.props.children,l=o.map(u=>u===i?d.Children.count(s)>1?d.Children.only(null):d.isValidElement(s)?s.props.children:null:u);return d.createElement(t1,Y({},r,{ref:t}),d.isValidElement(s)?d.cloneElement(s,void 0,l):null)}return d.createElement(t1,Y({},r,{ref:t}),n)});Zo.displayName="Slot";const t1=d.forwardRef((e,t)=>{const{children:n,...r}=e;return d.isValidElement(n)?d.cloneElement(n,{...vz(r,n.props),ref:t?Nm(t,n.ref):n.ref}):d.Children.count(n)>1?d.Children.only(null):null});t1.displayName="SlotClone";const lx=({children:e})=>d.createElement(d.Fragment,null,e);function gz(e){return d.isValidElement(e)&&e.type===lx}function vz(e,t){const n={...t};for(const r in t){const o=e[r],i=t[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...l)=>{i(...l),o(...l)}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...e,...n}}const _C=e=>typeof e=="boolean"?"".concat(e):e===0?"0":e,EC=Bk,Dm=(e,t)=>n=>{var r;if((t==null?void 0:t.variants)==null)return EC(e,n==null?void 0:n.class,n==null?void 0:n.className);const{variants:o,defaultVariants:i}=t,s=Object.keys(o).map(f=>{const m=n==null?void 0:n[f],p=i==null?void 0:i[f];if(m===null)return null;const g=_C(m)||_C(p);return o[f][g]}),l=n&&Object.entries(n).reduce((f,m)=>{let[p,g]=m;return g===void 0||(f[p]=g),f},{}),u=t==null||(r=t.compoundVariants)===null||r===void 0?void 0:r.reduce((f,m)=>{let{class:p,className:g,...y}=m;return Object.entries(y).every(b=>{let[S,E]=b;return Array.isArray(E)?E.includes({...i,...l}[S]):{...i,...l}[S]===E})?[...f,p,g]:f},[]);return EC(e,s,u,n==null?void 0:n.class,n==null?void 0:n.className)};var yz={VITE_BACKEND:"http://127.0.0.1:8080",BASE_URL:"/",MODE:"production",DEV:!1,PROD:!0,SSR:!1};function wz(e,t){let n;try{n=e()}catch{return}return{getItem:o=>{var i;const s=u=>u===null?null:JSON.parse(u,t==null?void 0:t.reviver),l=(i=n.getItem(o))!=null?i:null;return l instanceof Promise?l.then(s):s(l)},setItem:(o,i)=>n.setItem(o,JSON.stringify(i,t==null?void 0:t.replacer)),removeItem:o=>n.removeItem(o)}}const od=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then(r){return od(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return od(r)(n)}}}},xz=(e,t)=>(n,r,o)=>{let i={getStorage:()=>localStorage,serialize:JSON.stringify,deserialize:JSON.parse,partialize:E=>E,version:0,merge:(E,_)=>({..._,...E}),...t},s=!1;const l=new Set,u=new Set;let f;try{f=i.getStorage()}catch{}if(!f)return e((...E)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),n(...E)},r,o);const m=od(i.serialize),p=()=>{const E=i.partialize({...r()});let _;const x=m({state:E,version:i.version}).then(C=>f.setItem(i.name,C)).catch(C=>{_=C});if(_)throw _;return x},g=o.setState;o.setState=(E,_)=>{g(E,_),p()};const y=e((...E)=>{n(...E),p()},r,o);let b;const S=()=>{var E;if(!f)return;s=!1,l.forEach(x=>x(r()));const _=((E=i.onRehydrateStorage)==null?void 0:E.call(i,r()))||void 0;return od(f.getItem.bind(f))(i.name).then(x=>{if(x)return i.deserialize(x)}).then(x=>{if(x)if(typeof x.version=="number"&&x.version!==i.version){if(i.migrate)return i.migrate(x.state,x.version);console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return x.state}).then(x=>{var C;return b=i.merge(x,(C=r())!=null?C:y),n(b,!0),p()}).then(()=>{_==null||_(b,void 0),s=!0,u.forEach(x=>x(b))}).catch(x=>{_==null||_(void 0,x)})};return o.persist={setOptions:E=>{i={...i,...E},E.getStorage&&(f=E.getStorage())},clearStorage:()=>{f==null||f.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>S(),hasHydrated:()=>s,onHydrate:E=>(l.add(E),()=>{l.delete(E)}),onFinishHydration:E=>(u.add(E),()=>{u.delete(E)})},S(),b||y},bz=(e,t)=>(n,r,o)=>{let i={storage:wz(()=>localStorage),partialize:S=>S,version:0,merge:(S,E)=>({...E,...S}),...t},s=!1;const l=new Set,u=new Set;let f=i.storage;if(!f)return e((...S)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),n(...S)},r,o);const m=()=>{const S=i.partialize({...r()});return f.setItem(i.name,{state:S,version:i.version})},p=o.setState;o.setState=(S,E)=>{p(S,E),m()};const g=e((...S)=>{n(...S),m()},r,o);let y;const b=()=>{var S,E;if(!f)return;s=!1,l.forEach(x=>{var C;return x((C=r())!=null?C:g)});const _=((E=i.onRehydrateStorage)==null?void 0:E.call(i,(S=r())!=null?S:g))||void 0;return od(f.getItem.bind(f))(i.name).then(x=>{if(x)if(typeof x.version=="number"&&x.version!==i.version){if(i.migrate)return i.migrate(x.state,x.version);console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return x.state}).then(x=>{var C;return y=i.merge(x,(C=r())!=null?C:g),n(y,!0),m()}).then(()=>{_==null||_(y,void 0),y=r(),s=!0,u.forEach(x=>x(y))}).catch(x=>{_==null||_(void 0,x)})};return o.persist={setOptions:S=>{i={...i,...S},S.storage&&(f=S.storage)},clearStorage:()=>{f==null||f.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>b(),hasHydrated:()=>s,onHydrate:S=>(l.add(S),()=>{l.delete(S)}),onFinishHydration:S=>(u.add(S),()=>{u.delete(S)})},i.skipHydration||b(),y||g},Sz=(e,t)=>"getStorage"in t||"serialize"in t||"deserialize"in t?((yz?"production":void 0)!=="production"&&console.warn("[DEPRECATED] `getStorage`, `serialize` and `deserialize` options are deprecated. Use `storage` option instead."),xz(e,t)):bz(e,t),_z=Sz;function Ez(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,o]of e)if(!Object.is(o,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{t(n,r,e)}):e.forEach((n,r)=>t(r,n,e))}function Im(e){const t=e[wr];return t?t.type_:Array.isArray(e)?1:Lm(e)?2:Fm(e)?3:0}function n1(e,t){return Im(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function ST(e,t,n){const r=Im(e);r===2?e.set(t,n):r===3?e.add(n):e[t]=n}function $z(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function Lm(e){return e instanceof Map}function Fm(e){return e instanceof Set}function ra(e){return e.copy_||e.base_}function r1(e,t){if(Lm(e))return new Map(e);if(Fm(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);if(!t&&bT(e))return sc(e)?{...e}:Object.assign(Object.create(null),e);const n=Object.getOwnPropertyDescriptors(e);delete n[wr];let r=Reflect.ownKeys(n);for(let o=0;o1&&(e.set=e.add=e.clear=e.delete=Rz),Object.freeze(e),t&&id(e,(n,r)=>cx(r,!0))),e}function Rz(){po(2)}function jm(e){return Object.isFrozen(e)}var kz={};function Oa(e){const t=kz[e];return t||po(0,e),t}var sd;function _T(){return sd}function Tz(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function $C(e,t){t&&(Oa("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function o1(e){i1(e),e.drafts_.forEach(Pz),e.drafts_=null}function i1(e){e===sd&&(sd=e.parent_)}function RC(e){return sd=Tz(sd,e)}function Pz(e){const t=e[wr];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function kC(e,t){t.unfinalizedDrafts_=t.drafts_.length;const n=t.drafts_[0];return e!==void 0&&e!==n?(n[wr].modified_&&(o1(t),po(4)),Ma(e)&&(e=Np(t,e),t.parent_||Dp(t,e)),t.patches_&&Oa("Patches").generateReplacementPatches_(n[wr].base_,e,t.patches_,t.inversePatches_)):e=Np(t,n,[]),o1(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==xT?e:void 0}function Np(e,t,n){if(jm(t))return t;const r=t[wr];if(!r)return id(t,(o,i)=>TC(e,r,t,o,i,n)),t;if(r.scope_!==e)return t;if(!r.modified_)return Dp(e,r.base_,!0),r.base_;if(!r.finalized_){r.finalized_=!0,r.scope_.unfinalizedDrafts_--;const o=r.copy_;let i=o,s=!1;r.type_===3&&(i=new Set(o),o.clear(),s=!0),id(i,(l,u)=>TC(e,r,o,l,u,n,s)),Dp(e,o,!1),n&&e.patches_&&Oa("Patches").generatePatches_(r,n,e.patches_,e.inversePatches_)}return r.copy_}function TC(e,t,n,r,o,i,s){if(ac(o)){const l=i&&t&&t.type_!==3&&!n1(t.assigned_,r)?i.concat(r):void 0,u=Np(e,o,l);if(ST(n,r,u),ac(u))e.canAutoFreeze_=!1;else return}else s&&n.add(o);if(Ma(o)&&!jm(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;Np(e,o),(!t||!t.scope_.parent_)&&Dp(e,o)}}function Dp(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&cx(t,n)}function Az(e,t){const n=Array.isArray(e),r={type_:n?1:0,scope_:t?t.scope_:_T(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1};let o=r,i=ux;n&&(o=[r],i=ad);const{revoke:s,proxy:l}=Proxy.revocable(o,i);return r.draft_=l,r.revoke_=s,l}var ux={get(e,t){if(t===wr)return e;const n=ra(e);if(!n1(n,t))return Mz(e,n,t);const r=n[t];return e.finalized_||!Ma(r)?r:r===y0(e.base_,t)?(w0(e),e.copy_[t]=a1(r,e)):r},has(e,t){return t in ra(e)},ownKeys(e){return Reflect.ownKeys(ra(e))},set(e,t,n){const r=ET(ra(e),t);if(r!=null&&r.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){const o=y0(ra(e),t),i=o==null?void 0:o[wr];if(i&&i.base_===n)return e.copy_[t]=n,e.assigned_[t]=!1,!0;if($z(n,o)&&(n!==void 0||n1(e.base_,t)))return!0;w0(e),s1(e)}return e.copy_[t]===n&&(n!==void 0||t in e.copy_)||Number.isNaN(n)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=n,e.assigned_[t]=!0),!0},deleteProperty(e,t){return y0(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,w0(e),s1(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){const n=ra(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:r.enumerable,value:n[t]}},defineProperty(){po(11)},getPrototypeOf(e){return sc(e.base_)},setPrototypeOf(){po(12)}},ad={};id(ux,(e,t)=>{ad[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});ad.deleteProperty=function(e,t){return ad.set.call(this,e,t,void 0)};ad.set=function(e,t,n){return ux.set.call(this,e[0],t,n,e[0])};function y0(e,t){const n=e[wr];return(n?ra(n):e)[t]}function Mz(e,t,n){var o;const r=ET(t,n);return r?"value"in r?r.value:(o=r.get)==null?void 0:o.call(e.draft_):void 0}function ET(e,t){if(!(t in e))return;let n=sc(e);for(;n;){const r=Object.getOwnPropertyDescriptor(n,t);if(r)return r;n=sc(n)}}function s1(e){e.modified_||(e.modified_=!0,e.parent_&&s1(e.parent_))}function w0(e){e.copy_||(e.copy_=r1(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var Oz=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(t,n,r)=>{if(typeof t=="function"&&typeof n!="function"){const i=n;n=t;const s=this;return function(u=i,...f){return s.produce(u,m=>n.call(this,m,...f))}}typeof n!="function"&&po(6),r!==void 0&&typeof r!="function"&&po(7);let o;if(Ma(t)){const i=RC(this),s=a1(t,void 0);let l=!0;try{o=n(s),l=!1}finally{l?o1(i):i1(i)}return $C(i,r),kC(o,i)}else if(!t||typeof t!="object"){if(o=n(t),o===void 0&&(o=t),o===xT&&(o=void 0),this.autoFreeze_&&cx(o,!0),r){const i=[],s=[];Oa("Patches").generateReplacementPatches_(t,o,i,s),r(i,s)}return o}else po(1,t)},this.produceWithPatches=(t,n)=>{if(typeof t=="function")return(s,...l)=>this.produceWithPatches(s,u=>t(u,...l));let r,o;return[this.produce(t,n,(s,l)=>{r=s,o=l}),r,o]},typeof(e==null?void 0:e.autoFreeze)=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof(e==null?void 0:e.useStrictShallowCopy)=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){Ma(e)||po(8),ac(e)&&(e=Nz(e));const t=RC(this),n=a1(e,void 0);return n[wr].isManual_=!0,i1(t),n}finishDraft(e,t){const n=e&&e[wr];(!n||!n.isManual_)&&po(9);const{scope_:r}=n;return $C(r,t),kC(void 0,r)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let n;for(n=t.length-1;n>=0;n--){const o=t[n];if(o.path.length===0&&o.op==="replace"){e=o.value;break}}n>-1&&(t=t.slice(n+1));const r=Oa("Patches").applyPatches_;return ac(e)?r(e,t):this.produce(e,o=>r(o,t))}};function a1(e,t){const n=Lm(e)?Oa("MapSet").proxyMap_(e,t):Fm(e)?Oa("MapSet").proxySet_(e,t):Az(e,t);return(t?t.scope_:_T()).drafts_.push(n),n}function Nz(e){return ac(e)||po(10,e),CT(e)}function CT(e){if(!Ma(e)||jm(e))return e;const t=e[wr];let n;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=r1(e,t.scope_.immer_.useStrictShallowCopy_)}else n=r1(e,!0);return id(n,(r,o)=>{ST(n,r,CT(o))}),t&&(t.finalized_=!1),n}var xr=new Oz,Dz=xr.produce;xr.produceWithPatches.bind(xr);xr.setAutoFreeze.bind(xr);xr.setUseStrictShallowCopy.bind(xr);xr.applyPatches.bind(xr);xr.createDraft.bind(xr);xr.finishDraft.bind(xr);const Iz=e=>(t,n,r)=>(r.setState=(o,i,...s)=>{const l=typeof o=="function"?Dz(o):o;return t(l,i,...s)},e(r.setState,n,r)),Lz=Iz;var $T={exports:{}},RT={},kT={exports:{}},TT={};/** + * @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 lc=d;function Fz(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var jz=typeof Object.is=="function"?Object.is:Fz,zz=lc.useState,Bz=lc.useEffect,Uz=lc.useLayoutEffect,Vz=lc.useDebugValue;function Wz(e,t){var n=t(),r=zz({inst:{value:n,getSnapshot:t}}),o=r[0].inst,i=r[1];return Uz(function(){o.value=n,o.getSnapshot=t,x0(o)&&i({inst:o})},[e,n,t]),Bz(function(){return x0(o)&&i({inst:o}),e(function(){x0(o)&&i({inst:o})})},[e]),Vz(n),n}function x0(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!jz(e,n)}catch{return!0}}function Hz(e,t){return t()}var Kz=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?Hz:Wz;TT.useSyncExternalStore=lc.useSyncExternalStore!==void 0?lc.useSyncExternalStore:Kz;kT.exports=TT;var Gz=kT.exports;/** + * @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 zm=d,Yz=Gz;function Xz(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var Zz=typeof Object.is=="function"?Object.is:Xz,qz=Yz.useSyncExternalStore,Qz=zm.useRef,Jz=zm.useEffect,eB=zm.useMemo,tB=zm.useDebugValue;RT.useSyncExternalStoreWithSelector=function(e,t,n,r,o){var i=Qz(null);if(i.current===null){var s={hasValue:!1,value:null};i.current=s}else s=i.current;i=eB(function(){function u(y){if(!f){if(f=!0,m=y,y=r(y),o!==void 0&&s.hasValue){var b=s.value;if(o(b,y))return p=b}return p=y}if(b=p,Zz(m,y))return b;var S=r(y);return o!==void 0&&o(b,S)?b:(m=y,p=S)}var f=!1,m,p,g=n===void 0?null:n;return[function(){return u(t())},g===null?void 0:function(){return u(g())}]},[t,n,r,o]);var l=qz(e,i[0],i[1]);return Jz(function(){s.hasValue=!0,s.value=l},[l]),tB(l),l};$T.exports=RT;var nB=$T.exports;const rB=dm(nB);var oB={VITE_BACKEND:"http://127.0.0.1:8080",BASE_URL:"/",MODE:"production",DEV:!1,PROD:!0,SSR:!1};const PC=e=>{let t;const n=new Set,r=(u,f)=>{const m=typeof u=="function"?u(t):u;if(!Object.is(m,t)){const p=t;t=f??typeof m!="object"?m:Object.assign({},t,m),n.forEach(g=>g(t,p))}},o=()=>t,l={setState:r,getState:o,subscribe:u=>(n.add(u),()=>n.delete(u)),destroy:()=>{(oB?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),n.clear()}};return t=e(r,o,l),l},iB=e=>e?PC(e):PC,{useDebugValue:sB}=Fe,{useSyncExternalStoreWithSelector:aB}=rB;function lB(e,t=e.getState,n){const r=aB(e.subscribe,e.getState,e.getServerState||e.getState,t,n);return sB(r),r}const AC=(e,t)=>{const n=iB(e),r=(o,i=t)=>lB(n,o,i);return Object.assign(r,n),r},cB=(e,t)=>e?AC(e,t):AC,uB=1,dB=1e6;let b0=0;function fB(){return b0=(b0+1)%Number.MAX_VALUE,b0.toString()}const S0=new Map,MC=e=>{if(S0.has(e))return;const t=setTimeout(()=>{S0.delete(e),Iu({type:"REMOVE_TOAST",toastId:e})},dB);S0.set(e,t)},hB=(e,t)=>{switch(t.type){case"ADD_TOAST":return{...e,toasts:[t.toast,...e.toasts].slice(0,uB)};case"UPDATE_TOAST":return{...e,toasts:e.toasts.map(n=>n.id===t.toast.id?{...n,...t.toast}:n)};case"DISMISS_TOAST":{const{toastId:n}=t;return n?MC(n):e.toasts.forEach(r=>{MC(r.id)}),{...e,toasts:e.toasts.map(r=>r.id===n||n===void 0?{...r,open:!1}:r)}}case"REMOVE_TOAST":return t.toastId===void 0?{...e,toasts:[]}:{...e,toasts:e.toasts.filter(n=>n.id!==t.toastId)}}},Yh=[];let Xh={toasts:[]};function Iu(e){Xh=hB(Xh,e),Yh.forEach(t=>{t(Xh)})}function ul({...e}){const t=fB(),n=o=>Iu({type:"UPDATE_TOAST",toast:{...o,id:t}}),r=()=>Iu({type:"DISMISS_TOAST",toastId:t});return Iu({type:"ADD_TOAST",toast:{...e,id:t,open:!0,onOpenChange:o=>{o||r()}}}),{id:t,dismiss:r,update:n}}function Id(){const[e,t]=d.useState(Xh);return d.useEffect(()=>(Yh.push(t),()=>{const n=Yh.indexOf(t);n>-1&&Yh.splice(n,1)}),[e]),{...e,toast:ul,dismiss:n=>Iu({type:"DISMISS_TOAST",toastId:n})}}const ea={file:null,paintByExampleFile:null,customMask:null,imageHeight:0,imageWidth:0,isInpainting:!1,isPluginRunning:!1,isAdjustingMask:!1,disableShortCuts:!1,windowSize:{height:600,width:800},editorState:{baseBrushSize:cF,brushSizeScale:1,renders:[],extraMasks:[],prevExtraMasks:[],temporaryMasks:[],lineGroups:[],lastLineGroup:[],curLineGroup:[],redoRenders:[],redoCurLines:[],redoLineGroups:[]},interactiveSegState:{isInteractiveSeg:!1,tmpInteractiveSegMask:null,clicks:[]},cropperState:{x:0,y:0,width:512,height:512},extenderState:{x:0,y:0,width:512,height:512},isCropperExtenderResizing:!1,fileManagerState:{sortBy:Es.CTIME,sortOrder:Ou.DESCENDING,layout:"masonry",searchText:"",inputDirectory:"",outputDirectory:""},serverConfig:{plugins:[],modelInfos:[],removeBGModel:"briaai/RMBG-1.4",removeBGModels:[],realesrganModel:"realesr-general-x4v3",realesrganModels:[],interactiveSegModel:"vit_b",interactiveSegModels:[],enableFileManager:!1,enableAutoSaving:!1,enableControlnet:!1,controlnetMethod:"lllyasviel/control_v11p_sd15_canny",disableModelSwitch:!1,isDesktop:!1,samplers:["DPM++ 2M"]},settings:{model:{name:"lama",path:"lama",model_type:"inpaint",support_controlnet:!1,support_strength:!1,support_outpainting:!1,controlnets:[],support_freeu:!1,support_lcm_lora:!1,is_single_file_diffusers:!1,need_prompt:!1},enableControlnet:!1,showCropper:!1,showExtender:!1,extenderDirection:Ln.xy,enableDownloadMask:!1,enableManualInpainting:!1,enableUploadMask:!1,enableAutoExtractPrompt:!0,ldmSteps:30,ldmSampler:Qw.ddim,zitsWireframe:!0,cv2Radius:5,cv2Flag:Jw.INPAINT_NS,prompt:"",negativePrompt:hF,seed:42,seedFixed:!1,sdMaskBlur:12,sdStrength:1,sdSteps:50,sdGuidanceScale:7.5,sdSampler:"DPM++ 2M",sdMatchHistograms:!1,sdScale:1,p2pImageGuidanceScale:1.5,controlnetConditioningScale:.4,controlnetMethod:"lllyasviel/control_v11p_sd15_canny",enableLCMLora:!1,enableFreeu:!1,freeuConfig:{s1:.9,s2:.2,b1:1.2,b2:1.4},powerpaintTask:Ol.text_guided,adjustMaskKernelSize:12}},bt=cB()(_z(Lz((e,t)=>({...ea,showPrevMask:async()=>{if(t().settings.showExtender)return;const{lastLineGroup:n,curLineGroup:r,prevExtraMasks:o,extraMasks:i}=t().editorState;if(r.length!==0||i.length!==0)return;const{imageWidth:s,imageHeight:l}=t(),u=Wh(s,l,[n],o,Xy);try{const f=await cC(u);e(m=>{m.editorState.temporaryMasks.push(f)})}catch(f){console.error(f);return}},hidePrevMask:()=>{e(n=>{n.editorState.temporaryMasks=[]})},getCurrentTargetFile:async()=>{const n=t().file,r=t().editorState.renders;let o=n;if(r.length>0){const i=r[r.length-1];o=await Nu(i.currentSrc,n.name,n.type)}return o},runInpainting:async()=>{const{isInpainting:n,file:r,paintByExampleFile:o,imageWidth:i,imageHeight:s,settings:l,cropperState:u,extenderState:f}=t();if(n||r===null||t().settings.model.support_outpainting&&l.showExtender&&f.height===s&&f.width===i)return;const{lastLineGroup:m,curLineGroup:p,lineGroups:g,renders:y,prevExtraMasks:b,extraMasks:S}=t().editorState,E=p.length===0&&S.length===0&&!l.showExtender;let _=[],x=[];if(E===!0?(x=m,_=b):(x=p,_=S),x.length===0&&_===null&&!l.showExtender){ul({variant:"destructive",description:"Please draw mask on picture"});return}const C=[...g,x];e(M=>{M.isInpainting=!0});let R=r;if(E===!0){if(y.length>1){const M=y[y.length-2];R=await Nu(M.currentSrc,r.name,r.type)}}else if(y.length>0){const M=y[y.length-1];R=await Nu(M.currentSrc,r.name,r.type)}const P=Wh(i,s,[x],_);if(E){const M=await cC(P);e(A=>{A.editorState.temporaryMasks=[M]})}try{const M=await zj(R,l,u,f,lC(P.toDataURL()),o),{blob:A,seed:D}=M;D&&t().setSeed(parseInt(D,10));const U=new Image;await Vh(U,A);const W=[...y,U];t().setImageSize(U.width,U.height),t().updateEditorState({renders:W,lineGroups:C,lastLineGroup:x,curLineGroup:[],extraMasks:[],prevExtraMasks:_})}catch(M){ul({variant:"destructive",description:M.message?M.message:M.toString()})}t().resetRedoState(),e(M=>{M.isInpainting=!1,M.editorState.temporaryMasks=[]})},runRenderablePlugin:async(n,r,o={upscale:1})=>{const{renders:i,lineGroups:s}=t().editorState;e(l=>{l.isPluginRunning=!0});try{const l=new Date,u=await t().getCurrentTargetFile(),f=await vT(n,r,u,o.upscale),{blob:m}=f;if(n){const y=new Image;await Vh(y,m),e(b=>{b.editorState.extraMasks.push(y)})}else{const y=new Image;await Vh(y,m),t().setImageSize(y.width,y.height);const b=[...i,y],S=[...s,[]];t().updateEditorState({renders:b,lineGroups:S})}const g=new Date().getTime()-l.getTime();ul({description:`Run ${r} successfully in ${g/1e3}s`})}catch(l){ul({variant:"destructive",description:l.message?l.message:l.toString()})}e(l=>{l.isPluginRunning=!1})},updateEditorState:n=>{e(r=>{r.editorState={...r.editorState,...n}})},cleanCurLineGroup:()=>{t().updateEditorState({curLineGroup:[]})},handleCanvasMouseDown:n=>{let r=[];const o=t();o.runMannually()&&(r=[...o.editorState.curLineGroup]),r.push({size:o.getBrushSize(),pts:[n]}),e(i=>{i.editorState.curLineGroup=r})},handleCanvasMouseMove:n=>{e(r=>{const o=r.editorState.curLineGroup;o.length&&o[o.length-1].pts.push(n)})},runMannually:()=>{const n=t();return n.settings.enableManualInpainting||n.settings.model.model_type!==fs},getIsProcessing:()=>t().isInpainting||t().isPluginRunning||t().isAdjustingMask,isSD:()=>t().settings.model.model_type!==fs,undoDisabled:()=>{const n=t().editorState;if(n.renders.length>0)return!1;if(t().runMannually()){if(n.curLineGroup.length===0)return!0}else if(n.renders.length===0)return!0;return!1},undo:()=>{t().runMannually()&&t().editorState.curLineGroup.length!==0?e(n=>{const r=n.editorState;if(r.curLineGroup.length===0)return;r.lastLineGroup=[];const o=r.curLineGroup.pop();r.redoCurLines.push(o)}):e(n=>{const r=n.editorState;if(r.renders.length===0||r.lineGroups.length===0)return;const o=r.lineGroups.pop();r.redoLineGroups.push(o),r.redoCurLines=[],r.curLineGroup=[];const i=r.renders.pop();r.redoRenders.push(i)})},redoDisabled:()=>{const n=t().editorState;if(n.redoRenders.length>0)return!1;if(t().runMannually()){if(n.redoCurLines.length===0)return!0}else if(n.redoRenders.length===0)return!0;return!1},redo:()=>{t().runMannually()&&t().editorState.redoCurLines.length!==0?e(n=>{const r=n.editorState;if(r.redoCurLines.length===0)return;const o=r.redoCurLines.pop();r.curLineGroup.push(o)}):e(n=>{const r=n.editorState;if(r.redoRenders.length===0||r.redoLineGroups.length===0)return;const o=r.redoLineGroups.pop();r.lineGroups.push(o),r.curLineGroup=[];const i=r.redoRenders.pop();r.renders.push(i)})},resetRedoState:()=>{e(n=>{n.editorState.redoCurLines=[],n.editorState.redoLineGroups=[],n.editorState.redoRenders=[]})},updateAppState:n=>{e(()=>n)},getBrushSize:()=>t().editorState.baseBrushSize*t().editorState.brushSizeScale,showPromptInput:()=>{const n=t().settings.model;return n.model_type!==fs&&n.name!==Gk},setServerConfig:n=>{e(r=>{r.serverConfig=n,r.settings.enableControlnet=n.enableControlnet,r.settings.controlnetMethod=n.controlnetMethod})},updateSettings:n=>{e(r=>{r.settings={...r.settings,...n}})},setModel:n=>{e(r=>{r.settings.model=n,n.support_controlnet&&!n.controlnets.includes(r.settings.controlnetMethod)&&(r.settings.controlnetMethod=n.controlnets[0])})},updateFileManagerState:n=>{e(r=>{r.fileManagerState={...r.fileManagerState,...n}})},updateInteractiveSegState:n=>{e(r=>({...r,interactiveSegState:{...r.interactiveSegState,...n}}))},resetInteractiveSegState:()=>{t().updateInteractiveSegState(ea.interactiveSegState)},handleInteractiveSegAccept:()=>{e(n=>{n.interactiveSegState.tmpInteractiveSegMask&&n.editorState.extraMasks.push(n.interactiveSegState.tmpInteractiveSegMask),n.interactiveSegState={...ea.interactiveSegState}})},setIsInpainting:n=>e(r=>{r.isInpainting=n}),setFile:async n=>{if(t().settings.enableAutoExtractPrompt)try{const r=await Kj(n);r.prompt&&e(o=>{o.settings.prompt=r.prompt}),r.negative_prompt&&e(o=>{o.settings.negativePrompt=r.negative_prompt})}catch(r){ul({variant:"destructive",description:r.message?r.message:r.toString()})}e(r=>{r.file=n,r.interactiveSegState=ea.interactiveSegState,r.editorState=ea.editorState,r.cropperState=ea.cropperState})},setCustomFile:n=>e(r=>{r.customMask=n}),setBaseBrushSize:n=>e(r=>{r.editorState.baseBrushSize=n}),setImageSize:(n,r)=>{e(o=>{o.imageWidth=n,o.imageHeight=r,o.editorState.brushSizeScale=Math.max(Math.min(n,r),512)/512}),t().resetExtender(n,r)},setCropperX:n=>e(r=>{r.cropperState.x=n}),setCropperY:n=>e(r=>{r.cropperState.y=n}),setCropperWidth:n=>e(r=>{r.cropperState.width=n}),setCropperHeight:n=>e(r=>{r.cropperState.height=n}),setExtenderX:n=>e(r=>{r.extenderState.x=n}),setExtenderY:n=>e(r=>{r.extenderState.y=n}),setExtenderWidth:n=>e(r=>{r.extenderState.width=n}),setExtenderHeight:n=>e(r=>{r.extenderState.height=n}),setIsCropperExtenderResizing:n=>e(r=>{r.isCropperExtenderResizing=n}),updateExtenderDirection:n=>{console.log(`updateExtenderDirection: ${JSON.stringify(t().extenderState)}`),e(r=>{r.settings.extenderDirection=n,r.extenderState.x=0,r.extenderState.y=0,r.extenderState.width=r.imageWidth,r.extenderState.height=r.imageHeight}),t().updateExtenderByBuiltIn(n,1.5)},updateExtenderByBuiltIn:(n,r)=>{const o={...ea.extenderState};let{x:i,y:s,width:l,height:u}=o;const{imageWidth:f,imageHeight:m}=t();switch(l=f,u=m,n){case Ln.x:i=-Math.ceil(f*(r-1)/2),l=Math.ceil(f*r);break;case Ln.y:s=-Math.ceil(m*(r-1)/2),u=Math.ceil(m*r);break;case Ln.xy:i=-Math.ceil(f*(r-1)/2),s=-Math.ceil(m*(r-1)/2),l=Math.ceil(f*r),u=Math.ceil(m*r);break}e(p=>{p.extenderState.x=i,p.extenderState.y=s,p.extenderState.width=l,p.extenderState.height=u})},resetExtender:(n,r)=>{e(o=>{o.extenderState.x=0,o.extenderState.y=0,o.extenderState.width=n,o.extenderState.height=r})},setSeed:n=>e(r=>{r.settings.seed=n}),adjustMask:async n=>{const{imageWidth:r,imageHeight:o}=t(),{curLineGroup:i,extraMasks:s}=t().editorState,{adjustMaskKernelSize:l}=t().settings;if(i.length===0&&s.length===0)return;e(g=>{g.isAdjustingMask=!0});const u=Wh(r,o,[i],s,Xy),f=lC(u.toDataURL()),m=await Gj(f,n,l),p=await mF(m);e(g=>{g.editorState.extraMasks=[p],g.editorState.curLineGroup=[]}),e(g=>{g.isAdjustingMask=!1})},clearMask:()=>{e(n=>{n.editorState.extraMasks=[],n.editorState.curLineGroup=[]})}})),{name:"ZUSTAND_STATE",version:1,partialize:e=>Object.fromEntries(Object.entries(e).filter(([t])=>["fileManagerState","settings"].includes(t)))}),Ez),Ld=d.forwardRef(({className:e,type:t,...n},r)=>{const o=bt(l=>l.updateAppState),i=()=>{o({disableShortCuts:!0})},s=()=>{o({disableShortCuts:!1})};return v.jsx("input",{type:t,className:Ce("flex h-8 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",e),ref:r,autoComplete:"off",tabIndex:-1,onFocus:i,onBlur:s,...n})});Ld.displayName="Input";const Yn=d.forwardRef(({numberValue:e,allowFloat:t,onNumberValueChange:n,...r},o)=>{const[i,s]=d.useState(e.toString());d.useEffect(()=>{i!==e.toString()+"."&&s(e.toString())},[e]);const l=u=>{let m=u.target.value;if(t){if(m=m.replace(/[^0-9.]/g,"").replace(/(\..*?)\..*/g,"$1"),m.length===0){n(0);return}n(parseFloat(m))}else{if(m=m.replace(/\D/g,""),m.length===0){n(0);return}n(parseInt(m,10))}s(m)};return v.jsx(Ld,{ref:o,value:i,onInput:l,...r})});function de(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 pB(e,t){const n=d.createContext(t);function r(i){const{children:s,...l}=i,u=d.useMemo(()=>l,Object.values(l));return d.createElement(n.Provider,{value:u},s)}function o(i){const s=d.useContext(n);if(s)return s;if(t!==void 0)return t;throw new Error(`\`${i}\` must be used within \`${e}\``)}return r.displayName=e+"Provider",[r,o]}function Mn(e,t=[]){let n=[];function r(i,s){const l=d.createContext(s),u=n.length;n=[...n,s];function f(p){const{scope:g,children:y,...b}=p,S=(g==null?void 0:g[e][u])||l,E=d.useMemo(()=>b,Object.values(b));return d.createElement(S.Provider,{value:E},y)}function m(p,g){const y=(g==null?void 0:g[e][u])||l,b=d.useContext(y);if(b)return b;if(s!==void 0)return s;throw new Error(`\`${p}\` must be used within \`${i}\``)}return f.displayName=i+"Provider",[f,m]}const o=()=>{const i=n.map(s=>d.createContext(s));return function(l){const u=(l==null?void 0:l[e])||i;return d.useMemo(()=>({[`__scope${e}`]:{...l,[e]:u}}),[l,u])}};return o.scopeName=e,[r,mB(o,...t)]}function mB(...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(i){const s=r.reduce((l,{useScope:u,scopeName:f})=>{const p=u(i)[`__scope${f}`];return{...l,...p}},{});return d.useMemo(()=>({[`__scope${t.scopeName}`]:s}),[s])}};return n.scopeName=t.scopeName,n}const gB=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","span","svg","ul"],Pe=gB.reduce((e,t)=>{const n=d.forwardRef((r,o)=>{const{asChild:i,...s}=r,l=i?Zo:t;return d.useEffect(()=>{window[Symbol.for("radix-ui")]=!0},[]),d.createElement(l,Y({},s,{ref:o}))});return n.displayName=`Primitive.${t}`,{...e,[t]:n}},{});function dx(e,t){e&&Is.flushSync(()=>e.dispatchEvent(t))}function Ft(e){const t=d.useRef(e);return d.useEffect(()=>{t.current=e}),d.useMemo(()=>(...n)=>{var r;return(r=t.current)===null||r===void 0?void 0:r.call(t,...n)},[])}function vB(e,t=globalThis==null?void 0:globalThis.document){const n=Ft(e);d.useEffect(()=>{const r=o=>{o.key==="Escape"&&n(o)};return t.addEventListener("keydown",r),()=>t.removeEventListener("keydown",r)},[n,t])}const l1="dismissableLayer.update",yB="dismissableLayer.pointerDownOutside",wB="dismissableLayer.focusOutside";let OC;const PT=d.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),Ec=d.forwardRef((e,t)=>{var n;const{disableOutsidePointerEvents:r=!1,onEscapeKeyDown:o,onPointerDownOutside:i,onFocusOutside:s,onInteractOutside:l,onDismiss:u,...f}=e,m=d.useContext(PT),[p,g]=d.useState(null),y=(n=p==null?void 0:p.ownerDocument)!==null&&n!==void 0?n:globalThis==null?void 0:globalThis.document,[,b]=d.useState({}),S=Be(t,D=>g(D)),E=Array.from(m.layers),[_]=[...m.layersWithOutsidePointerEventsDisabled].slice(-1),x=E.indexOf(_),C=p?E.indexOf(p):-1,R=m.layersWithOutsidePointerEventsDisabled.size>0,P=C>=x,M=bB(D=>{const U=D.target,W=[...m.branches].some(q=>q.contains(U));!P||W||(i==null||i(D),l==null||l(D),D.defaultPrevented||u==null||u())},y),A=SB(D=>{const U=D.target;[...m.branches].some(q=>q.contains(U))||(s==null||s(D),l==null||l(D),D.defaultPrevented||u==null||u())},y);return vB(D=>{C===m.layers.size-1&&(o==null||o(D),!D.defaultPrevented&&u&&(D.preventDefault(),u()))},y),d.useEffect(()=>{if(p)return r&&(m.layersWithOutsidePointerEventsDisabled.size===0&&(OC=y.body.style.pointerEvents,y.body.style.pointerEvents="none"),m.layersWithOutsidePointerEventsDisabled.add(p)),m.layers.add(p),NC(),()=>{r&&m.layersWithOutsidePointerEventsDisabled.size===1&&(y.body.style.pointerEvents=OC)}},[p,y,r,m]),d.useEffect(()=>()=>{p&&(m.layers.delete(p),m.layersWithOutsidePointerEventsDisabled.delete(p),NC())},[p,m]),d.useEffect(()=>{const D=()=>b({});return document.addEventListener(l1,D),()=>document.removeEventListener(l1,D)},[]),d.createElement(Pe.div,Y({},f,{ref:S,style:{pointerEvents:R?P?"auto":"none":void 0,...e.style},onFocusCapture:de(e.onFocusCapture,A.onFocusCapture),onBlurCapture:de(e.onBlurCapture,A.onBlurCapture),onPointerDownCapture:de(e.onPointerDownCapture,M.onPointerDownCapture)}))}),xB=d.forwardRef((e,t)=>{const n=d.useContext(PT),r=d.useRef(null),o=Be(t,r);return d.useEffect(()=>{const i=r.current;if(i)return n.branches.add(i),()=>{n.branches.delete(i)}},[n.branches]),d.createElement(Pe.div,Y({},e,{ref:o}))});function bB(e,t=globalThis==null?void 0:globalThis.document){const n=Ft(e),r=d.useRef(!1),o=d.useRef(()=>{});return d.useEffect(()=>{const i=l=>{if(l.target&&!r.current){let m=function(){AT(yB,n,f,{discrete:!0})};var u=m;const f={originalEvent:l};l.pointerType==="touch"?(t.removeEventListener("click",o.current),o.current=m,t.addEventListener("click",o.current,{once:!0})):m()}else t.removeEventListener("click",o.current);r.current=!1},s=window.setTimeout(()=>{t.addEventListener("pointerdown",i)},0);return()=>{window.clearTimeout(s),t.removeEventListener("pointerdown",i),t.removeEventListener("click",o.current)}},[t,n]),{onPointerDownCapture:()=>r.current=!0}}function SB(e,t=globalThis==null?void 0:globalThis.document){const n=Ft(e),r=d.useRef(!1);return d.useEffect(()=>{const o=i=>{i.target&&!r.current&&AT(wB,n,{originalEvent:i},{discrete:!1})};return t.addEventListener("focusin",o),()=>t.removeEventListener("focusin",o)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function NC(){const e=new CustomEvent(l1);document.dispatchEvent(e)}function AT(e,t,n,{discrete:r}){const o=n.originalEvent.target,i=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&o.addEventListener(e,t,{once:!0}),r?dx(o,i):o.dispatchEvent(i)}const _B=Ec,EB=xB,An=globalThis!=null&&globalThis.document?d.useLayoutEffect:()=>{},CB=UD.useId||(()=>{});let $B=0;function nr(e){const[t,n]=d.useState(CB());return An(()=>{e||n(r=>r??String($B++))},[e]),e||(t?`radix-${t}`:"")}const RB=["top","right","bottom","left"],Ts=Math.min,hr=Math.max,Ip=Math.round,fh=Math.floor,Ps=e=>({x:e,y:e}),kB={left:"right",right:"left",bottom:"top",top:"bottom"},TB={start:"end",end:"start"};function c1(e,t,n){return hr(e,Ts(t,n))}function Ci(e,t){return typeof e=="function"?e(t):e}function $i(e){return e.split("-")[0]}function Cc(e){return e.split("-")[1]}function fx(e){return e==="x"?"y":"x"}function hx(e){return e==="y"?"height":"width"}function $c(e){return["top","bottom"].includes($i(e))?"y":"x"}function px(e){return fx($c(e))}function PB(e,t,n){n===void 0&&(n=!1);const r=Cc(e),o=px(e),i=hx(o);let s=o==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[i]>t.floating[i]&&(s=Lp(s)),[s,Lp(s)]}function AB(e){const t=Lp(e);return[u1(e),t,u1(t)]}function u1(e){return e.replace(/start|end/g,t=>TB[t])}function MB(e,t,n){const r=["left","right"],o=["right","left"],i=["top","bottom"],s=["bottom","top"];switch(e){case"top":case"bottom":return n?t?o:r:t?r:o;case"left":case"right":return t?i:s;default:return[]}}function OB(e,t,n,r){const o=Cc(e);let i=MB($i(e),n==="start",r);return o&&(i=i.map(s=>s+"-"+o),t&&(i=i.concat(i.map(u1)))),i}function Lp(e){return e.replace(/left|right|bottom|top/g,t=>kB[t])}function NB(e){return{top:0,right:0,bottom:0,left:0,...e}}function MT(e){return typeof e!="number"?NB(e):{top:e,right:e,bottom:e,left:e}}function Fp(e){return{...e,top:e.y,left:e.x,right:e.x+e.width,bottom:e.y+e.height}}function DC(e,t,n){let{reference:r,floating:o}=e;const i=$c(t),s=px(t),l=hx(s),u=$i(t),f=i==="y",m=r.x+r.width/2-o.width/2,p=r.y+r.height/2-o.height/2,g=r[l]/2-o[l]/2;let y;switch(u){case"top":y={x:m,y:r.y-o.height};break;case"bottom":y={x:m,y:r.y+r.height};break;case"right":y={x:r.x+r.width,y:p};break;case"left":y={x:r.x-o.width,y:p};break;default:y={x:r.x,y:r.y}}switch(Cc(t)){case"start":y[s]-=g*(n&&f?-1:1);break;case"end":y[s]+=g*(n&&f?-1:1);break}return y}const DB=async(e,t,n)=>{const{placement:r="bottom",strategy:o="absolute",middleware:i=[],platform:s}=n,l=i.filter(Boolean),u=await(s.isRTL==null?void 0:s.isRTL(t));let f=await s.getElementRects({reference:e,floating:t,strategy:o}),{x:m,y:p}=DC(f,r,u),g=r,y={},b=0;for(let S=0;S({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:o,rects:i,platform:s,elements:l,middlewareData:u}=t,{element:f,padding:m=0}=Ci(e,t)||{};if(f==null)return{};const p=MT(m),g={x:n,y:r},y=px(o),b=hx(y),S=await s.getDimensions(f),E=y==="y",_=E?"top":"left",x=E?"bottom":"right",C=E?"clientHeight":"clientWidth",R=i.reference[b]+i.reference[y]-g[y]-i.floating[b],P=g[y]-i.reference[y],M=await(s.getOffsetParent==null?void 0:s.getOffsetParent(f));let A=M?M[C]:0;(!A||!await(s.isElement==null?void 0:s.isElement(M)))&&(A=l.floating[C]||i.floating[b]);const D=R/2-P/2,U=A/2-S[b]/2-1,W=Ts(p[_],U),q=Ts(p[x],U),X=W,ae=A-S[b]-q,V=A/2-S[b]/2+D,F=c1(X,V,ae),N=!u.arrow&&Cc(o)!=null&&V!=F&&i.reference[b]/2-(VX<=0)){var U,W;const X=(((U=i.flip)==null?void 0:U.index)||0)+1,ae=P[X];if(ae)return{data:{index:X,overflows:D},reset:{placement:ae}};let V=(W=D.filter(F=>F.overflows[0]<=0).sort((F,N)=>F.overflows[1]-N.overflows[1])[0])==null?void 0:W.placement;if(!V)switch(y){case"bestFit":{var q;const F=(q=D.map(N=>[N.placement,N.overflows.filter(ie=>ie>0).reduce((ie,K)=>ie+K,0)]).sort((N,ie)=>N[1]-ie[1])[0])==null?void 0:q[0];F&&(V=F);break}case"initialPlacement":V=l;break}if(o!==V)return{reset:{placement:V}}}return{}}}};function LC(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function FC(e){return RB.some(t=>e[t]>=0)}const LB=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n}=t,{strategy:r="referenceHidden",...o}=Ci(e,t);switch(r){case"referenceHidden":{const i=await ld(t,{...o,elementContext:"reference"}),s=LC(i,n.reference);return{data:{referenceHiddenOffsets:s,referenceHidden:FC(s)}}}case"escaped":{const i=await ld(t,{...o,altBoundary:!0}),s=LC(i,n.floating);return{data:{escapedOffsets:s,escaped:FC(s)}}}default:return{}}}}};async function FB(e,t){const{placement:n,platform:r,elements:o}=e,i=await(r.isRTL==null?void 0:r.isRTL(o.floating)),s=$i(n),l=Cc(n),u=$c(n)==="y",f=["left","top"].includes(s)?-1:1,m=i&&u?-1:1,p=Ci(t,e);let{mainAxis:g,crossAxis:y,alignmentAxis:b}=typeof p=="number"?{mainAxis:p,crossAxis:0,alignmentAxis:null}:{mainAxis:0,crossAxis:0,alignmentAxis:null,...p};return l&&typeof b=="number"&&(y=l==="end"?b*-1:b),u?{x:y*m,y:g*f}:{x:g*f,y:y*m}}const jB=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){const{x:n,y:r}=t,o=await FB(t,e);return{x:n+o.x,y:r+o.y,data:o}}}},zB=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:o}=t,{mainAxis:i=!0,crossAxis:s=!1,limiter:l={fn:E=>{let{x:_,y:x}=E;return{x:_,y:x}}},...u}=Ci(e,t),f={x:n,y:r},m=await ld(t,u),p=$c($i(o)),g=fx(p);let y=f[g],b=f[p];if(i){const E=g==="y"?"top":"left",_=g==="y"?"bottom":"right",x=y+m[E],C=y-m[_];y=c1(x,y,C)}if(s){const E=p==="y"?"top":"left",_=p==="y"?"bottom":"right",x=b+m[E],C=b-m[_];b=c1(x,b,C)}const S=l.fn({...t,[g]:y,[p]:b});return{...S,data:{x:S.x-n,y:S.y-r}}}}},BB=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:r,placement:o,rects:i,middlewareData:s}=t,{offset:l=0,mainAxis:u=!0,crossAxis:f=!0}=Ci(e,t),m={x:n,y:r},p=$c(o),g=fx(p);let y=m[g],b=m[p];const S=Ci(l,t),E=typeof S=="number"?{mainAxis:S,crossAxis:0}:{mainAxis:0,crossAxis:0,...S};if(u){const C=g==="y"?"height":"width",R=i.reference[g]-i.floating[C]+E.mainAxis,P=i.reference[g]+i.reference[C]-E.mainAxis;yP&&(y=P)}if(f){var _,x;const C=g==="y"?"width":"height",R=["top","left"].includes($i(o)),P=i.reference[p]-i.floating[C]+(R&&((_=s.offset)==null?void 0:_[p])||0)+(R?0:E.crossAxis),M=i.reference[p]+i.reference[C]+(R?0:((x=s.offset)==null?void 0:x[p])||0)-(R?E.crossAxis:0);bM&&(b=M)}return{[g]:y,[p]:b}}}},UB=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){const{placement:n,rects:r,platform:o,elements:i}=t,{apply:s=()=>{},...l}=Ci(e,t),u=await ld(t,l),f=$i(n),m=Cc(n),p=$c(n)==="y",{width:g,height:y}=r.floating;let b,S;f==="top"||f==="bottom"?(b=f,S=m===(await(o.isRTL==null?void 0:o.isRTL(i.floating))?"start":"end")?"left":"right"):(S=f,b=m==="end"?"top":"bottom");const E=y-u[b],_=g-u[S],x=!t.middlewareData.shift;let C=E,R=_;if(p){const M=g-u.left-u.right;R=m||x?Ts(_,M):M}else{const M=y-u.top-u.bottom;C=m||x?Ts(E,M):M}if(x&&!m){const M=hr(u.left,0),A=hr(u.right,0),D=hr(u.top,0),U=hr(u.bottom,0);p?R=g-2*(M!==0||A!==0?M+A:hr(u.left,u.right)):C=y-2*(D!==0||U!==0?D+U:hr(u.top,u.bottom))}await s({...t,availableWidth:R,availableHeight:C});const P=await o.getDimensions(i.floating);return g!==P.width||y!==P.height?{reset:{rects:!0}}:{}}}};function As(e){return OT(e)?(e.nodeName||"").toLowerCase():"#document"}function vr(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Mi(e){var t;return(t=(OT(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function OT(e){return e instanceof Node||e instanceof vr(e).Node}function Ri(e){return e instanceof Element||e instanceof vr(e).Element}function qo(e){return e instanceof HTMLElement||e instanceof vr(e).HTMLElement}function jC(e){return typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof vr(e).ShadowRoot}function Fd(e){const{overflow:t,overflowX:n,overflowY:r,display:o}=Xr(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&!["inline","contents"].includes(o)}function VB(e){return["table","td","th"].includes(As(e))}function mx(e){const t=gx(),n=Xr(e);return n.transform!=="none"||n.perspective!=="none"||(n.containerType?n.containerType!=="normal":!1)||!t&&(n.backdropFilter?n.backdropFilter!=="none":!1)||!t&&(n.filter?n.filter!=="none":!1)||["transform","perspective","filter"].some(r=>(n.willChange||"").includes(r))||["paint","layout","strict","content"].some(r=>(n.contain||"").includes(r))}function WB(e){let t=cc(e);for(;qo(t)&&!Bm(t);){if(mx(t))return t;t=cc(t)}return null}function gx(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}function Bm(e){return["html","body","#document"].includes(As(e))}function Xr(e){return vr(e).getComputedStyle(e)}function Um(e){return Ri(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.pageXOffset,scrollTop:e.pageYOffset}}function cc(e){if(As(e)==="html")return e;const t=e.assignedSlot||e.parentNode||jC(e)&&e.host||Mi(e);return jC(t)?t.host:t}function NT(e){const t=cc(e);return Bm(t)?e.ownerDocument?e.ownerDocument.body:e.body:qo(t)&&Fd(t)?t:NT(t)}function cd(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const o=NT(e),i=o===((r=e.ownerDocument)==null?void 0:r.body),s=vr(o);return i?t.concat(s,s.visualViewport||[],Fd(o)?o:[],s.frameElement&&n?cd(s.frameElement):[]):t.concat(o,cd(o,[],n))}function DT(e){const t=Xr(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const o=qo(e),i=o?e.offsetWidth:n,s=o?e.offsetHeight:r,l=Ip(n)!==i||Ip(r)!==s;return l&&(n=i,r=s),{width:n,height:r,$:l}}function vx(e){return Ri(e)?e:e.contextElement}function Nl(e){const t=vx(e);if(!qo(t))return Ps(1);const n=t.getBoundingClientRect(),{width:r,height:o,$:i}=DT(t);let s=(i?Ip(n.width):n.width)/r,l=(i?Ip(n.height):n.height)/o;return(!s||!Number.isFinite(s))&&(s=1),(!l||!Number.isFinite(l))&&(l=1),{x:s,y:l}}const HB=Ps(0);function IT(e){const t=vr(e);return!gx()||!t.visualViewport?HB:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function KB(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==vr(e)?!1:t}function Na(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const o=e.getBoundingClientRect(),i=vx(e);let s=Ps(1);t&&(r?Ri(r)&&(s=Nl(r)):s=Nl(e));const l=KB(i,n,r)?IT(i):Ps(0);let u=(o.left+l.x)/s.x,f=(o.top+l.y)/s.y,m=o.width/s.x,p=o.height/s.y;if(i){const g=vr(i),y=r&&Ri(r)?vr(r):r;let b=g.frameElement;for(;b&&r&&y!==g;){const S=Nl(b),E=b.getBoundingClientRect(),_=Xr(b),x=E.left+(b.clientLeft+parseFloat(_.paddingLeft))*S.x,C=E.top+(b.clientTop+parseFloat(_.paddingTop))*S.y;u*=S.x,f*=S.y,m*=S.x,p*=S.y,u+=x,f+=C,b=vr(b).frameElement}}return Fp({width:m,height:p,x:u,y:f})}function GB(e){let{rect:t,offsetParent:n,strategy:r}=e;const o=qo(n),i=Mi(n);if(n===i)return t;let s={scrollLeft:0,scrollTop:0},l=Ps(1);const u=Ps(0);if((o||!o&&r!=="fixed")&&((As(n)!=="body"||Fd(i))&&(s=Um(n)),qo(n))){const f=Na(n);l=Nl(n),u.x=f.x+n.clientLeft,u.y=f.y+n.clientTop}return{width:t.width*l.x,height:t.height*l.y,x:t.x*l.x-s.scrollLeft*l.x+u.x,y:t.y*l.y-s.scrollTop*l.y+u.y}}function YB(e){return Array.from(e.getClientRects())}function LT(e){return Na(Mi(e)).left+Um(e).scrollLeft}function XB(e){const t=Mi(e),n=Um(e),r=e.ownerDocument.body,o=hr(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),i=hr(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let s=-n.scrollLeft+LT(e);const l=-n.scrollTop;return Xr(r).direction==="rtl"&&(s+=hr(t.clientWidth,r.clientWidth)-o),{width:o,height:i,x:s,y:l}}function ZB(e,t){const n=vr(e),r=Mi(e),o=n.visualViewport;let i=r.clientWidth,s=r.clientHeight,l=0,u=0;if(o){i=o.width,s=o.height;const f=gx();(!f||f&&t==="fixed")&&(l=o.offsetLeft,u=o.offsetTop)}return{width:i,height:s,x:l,y:u}}function qB(e,t){const n=Na(e,!0,t==="fixed"),r=n.top+e.clientTop,o=n.left+e.clientLeft,i=qo(e)?Nl(e):Ps(1),s=e.clientWidth*i.x,l=e.clientHeight*i.y,u=o*i.x,f=r*i.y;return{width:s,height:l,x:u,y:f}}function zC(e,t,n){let r;if(t==="viewport")r=ZB(e,n);else if(t==="document")r=XB(Mi(e));else if(Ri(t))r=qB(t,n);else{const o=IT(e);r={...t,x:t.x-o.x,y:t.y-o.y}}return Fp(r)}function FT(e,t){const n=cc(e);return n===t||!Ri(n)||Bm(n)?!1:Xr(n).position==="fixed"||FT(n,t)}function QB(e,t){const n=t.get(e);if(n)return n;let r=cd(e,[],!1).filter(l=>Ri(l)&&As(l)!=="body"),o=null;const i=Xr(e).position==="fixed";let s=i?cc(e):e;for(;Ri(s)&&!Bm(s);){const l=Xr(s),u=mx(s);!u&&l.position==="fixed"&&(o=null),(i?!u&&!o:!u&&l.position==="static"&&!!o&&["absolute","fixed"].includes(o.position)||Fd(s)&&!u&&FT(e,s))?r=r.filter(m=>m!==s):o=l,s=cc(s)}return t.set(e,r),r}function JB(e){let{element:t,boundary:n,rootBoundary:r,strategy:o}=e;const s=[...n==="clippingAncestors"?QB(t,this._c):[].concat(n),r],l=s[0],u=s.reduce((f,m)=>{const p=zC(t,m,o);return f.top=hr(p.top,f.top),f.right=Ts(p.right,f.right),f.bottom=Ts(p.bottom,f.bottom),f.left=hr(p.left,f.left),f},zC(t,l,o));return{width:u.right-u.left,height:u.bottom-u.top,x:u.left,y:u.top}}function eU(e){return DT(e)}function tU(e,t,n){const r=qo(t),o=Mi(t),i=n==="fixed",s=Na(e,!0,i,t);let l={scrollLeft:0,scrollTop:0};const u=Ps(0);if(r||!r&&!i)if((As(t)!=="body"||Fd(o))&&(l=Um(t)),r){const f=Na(t,!0,i,t);u.x=f.x+t.clientLeft,u.y=f.y+t.clientTop}else o&&(u.x=LT(o));return{x:s.left+l.scrollLeft-u.x,y:s.top+l.scrollTop-u.y,width:s.width,height:s.height}}function BC(e,t){return!qo(e)||Xr(e).position==="fixed"?null:t?t(e):e.offsetParent}function jT(e,t){const n=vr(e);if(!qo(e))return n;let r=BC(e,t);for(;r&&VB(r)&&Xr(r).position==="static";)r=BC(r,t);return r&&(As(r)==="html"||As(r)==="body"&&Xr(r).position==="static"&&!mx(r))?n:r||WB(e)||n}const nU=async function(e){let{reference:t,floating:n,strategy:r}=e;const o=this.getOffsetParent||jT,i=this.getDimensions;return{reference:tU(t,await o(n),r),floating:{x:0,y:0,...await i(n)}}};function rU(e){return Xr(e).direction==="rtl"}const oU={convertOffsetParentRelativeRectToViewportRelativeRect:GB,getDocumentElement:Mi,getClippingRect:JB,getOffsetParent:jT,getElementRects:nU,getClientRects:YB,getDimensions:eU,getScale:Nl,isElement:Ri,isRTL:rU};function iU(e,t){let n=null,r;const o=Mi(e);function i(){clearTimeout(r),n&&n.disconnect(),n=null}function s(l,u){l===void 0&&(l=!1),u===void 0&&(u=1),i();const{left:f,top:m,width:p,height:g}=e.getBoundingClientRect();if(l||t(),!p||!g)return;const y=fh(m),b=fh(o.clientWidth-(f+p)),S=fh(o.clientHeight-(m+g)),E=fh(f),x={rootMargin:-y+"px "+-b+"px "+-S+"px "+-E+"px",threshold:hr(0,Ts(1,u))||1};let C=!0;function R(P){const M=P[0].intersectionRatio;if(M!==u){if(!C)return s();M?s(!1,M):r=setTimeout(()=>{s(!1,1e-7)},100)}C=!1}try{n=new IntersectionObserver(R,{...x,root:o.ownerDocument})}catch{n=new IntersectionObserver(R,x)}n.observe(e)}return s(!0),i}function sU(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:o=!0,ancestorResize:i=!0,elementResize:s=typeof ResizeObserver=="function",layoutShift:l=typeof IntersectionObserver=="function",animationFrame:u=!1}=r,f=vx(e),m=o||i?[...f?cd(f):[],...cd(t)]:[];m.forEach(_=>{o&&_.addEventListener("scroll",n,{passive:!0}),i&&_.addEventListener("resize",n)});const p=f&&l?iU(f,n):null;let g=-1,y=null;s&&(y=new ResizeObserver(_=>{let[x]=_;x&&x.target===f&&y&&(y.unobserve(t),cancelAnimationFrame(g),g=requestAnimationFrame(()=>{y&&y.observe(t)})),n()}),f&&!u&&y.observe(f),y.observe(t));let b,S=u?Na(e):null;u&&E();function E(){const _=Na(e);S&&(_.x!==S.x||_.y!==S.y||_.width!==S.width||_.height!==S.height)&&n(),S=_,b=requestAnimationFrame(E)}return n(),()=>{m.forEach(_=>{o&&_.removeEventListener("scroll",n),i&&_.removeEventListener("resize",n)}),p&&p(),y&&y.disconnect(),y=null,u&&cancelAnimationFrame(b)}}const aU=(e,t,n)=>{const r=new Map,o={platform:oU,...n},i={...o.platform,_c:r};return DB(e,t,{...o,platform:i})},lU=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:o}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?IC({element:r.current,padding:o}).fn(n):{}:r?IC({element:r,padding:o}).fn(n):{}}}};var Zh=typeof document<"u"?d.useLayoutEffect:d.useEffect;function jp(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(!jp(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(!{}.hasOwnProperty.call(t,o[r]))return!1;for(r=n;r--!==0;){const i=o[r];if(!(i==="_owner"&&e.$$typeof)&&!jp(e[i],t[i]))return!1}return!0}return e!==e&&t!==t}function zT(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function UC(e,t){const n=zT(e);return Math.round(t*n)/n}function VC(e){const t=d.useRef(e);return Zh(()=>{t.current=e}),t}function cU(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:o,elements:{reference:i,floating:s}={},transform:l=!0,whileElementsMounted:u,open:f}=e,[m,p]=d.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[g,y]=d.useState(r);jp(g,r)||y(r);const[b,S]=d.useState(null),[E,_]=d.useState(null),x=d.useCallback(N=>{N!=M.current&&(M.current=N,S(N))},[S]),C=d.useCallback(N=>{N!==A.current&&(A.current=N,_(N))},[_]),R=i||b,P=s||E,M=d.useRef(null),A=d.useRef(null),D=d.useRef(m),U=VC(u),W=VC(o),q=d.useCallback(()=>{if(!M.current||!A.current)return;const N={placement:t,strategy:n,middleware:g};W.current&&(N.platform=W.current),aU(M.current,A.current,N).then(ie=>{const K={...ie,isPositioned:!0};X.current&&!jp(D.current,K)&&(D.current=K,Is.flushSync(()=>{p(K)}))})},[g,t,n,W]);Zh(()=>{f===!1&&D.current.isPositioned&&(D.current.isPositioned=!1,p(N=>({...N,isPositioned:!1})))},[f]);const X=d.useRef(!1);Zh(()=>(X.current=!0,()=>{X.current=!1}),[]),Zh(()=>{if(R&&(M.current=R),P&&(A.current=P),R&&P){if(U.current)return U.current(R,P,q);q()}},[R,P,q,U]);const ae=d.useMemo(()=>({reference:M,floating:A,setReference:x,setFloating:C}),[x,C]),V=d.useMemo(()=>({reference:R,floating:P}),[R,P]),F=d.useMemo(()=>{const N={position:n,left:0,top:0};if(!V.floating)return N;const ie=UC(V.floating,m.x),K=UC(V.floating,m.y);return l?{...N,transform:"translate("+ie+"px, "+K+"px)",...zT(V.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:ie,top:K}},[n,l,V.floating,m.x,m.y]);return d.useMemo(()=>({...m,update:q,refs:ae,elements:V,floatingStyles:F}),[m,q,ae,V,F])}function yx(e){const[t,n]=d.useState(void 0);return An(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(o=>{if(!Array.isArray(o)||!o.length)return;const i=o[0];let s,l;if("borderBoxSize"in i){const u=i.borderBoxSize,f=Array.isArray(u)?u[0]:u;s=f.inlineSize,l=f.blockSize}else s=e.offsetWidth,l=e.offsetHeight;n({width:s,height:l})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}const BT="Popper",[UT,Fs]=Mn(BT),[uU,VT]=UT(BT),dU=e=>{const{__scopePopper:t,children:n}=e,[r,o]=d.useState(null);return d.createElement(uU,{scope:t,anchor:r,onAnchorChange:o},n)},fU="PopperAnchor",hU=d.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...o}=e,i=VT(fU,n),s=d.useRef(null),l=Be(t,s);return d.useEffect(()=>{i.onAnchorChange((r==null?void 0:r.current)||s.current)}),r?null:d.createElement(Pe.div,Y({},o,{ref:l}))}),WT="PopperContent",[pU,pte]=UT(WT),mU=d.forwardRef((e,t)=>{var n,r,o,i,s,l,u,f;const{__scopePopper:m,side:p="bottom",sideOffset:g=0,align:y="center",alignOffset:b=0,arrowPadding:S=0,avoidCollisions:E=!0,collisionBoundary:_=[],collisionPadding:x=0,sticky:C="partial",hideWhenDetached:R=!1,updatePositionStrategy:P="optimized",onPlaced:M,...A}=e,D=VT(WT,m),[U,W]=d.useState(null),q=Be(t,Kt=>W(Kt)),[X,ae]=d.useState(null),V=yx(X),F=(n=V==null?void 0:V.width)!==null&&n!==void 0?n:0,N=(r=V==null?void 0:V.height)!==null&&r!==void 0?r:0,ie=p+(y!=="center"?"-"+y:""),K=typeof x=="number"?x:{top:0,right:0,bottom:0,left:0,...x},Z=Array.isArray(_)?_:[_],H=Z.length>0,se={padding:K,boundary:Z.filter(gU),altBoundary:H},{refs:ce,floatingStyles:Ve,placement:Ue,isPositioned:We,middlewareData:Oe}=cU({strategy:"fixed",placement:ie,whileElementsMounted:(...Kt)=>sU(...Kt,{animationFrame:P==="always"}),elements:{reference:D.anchor},middleware:[jB({mainAxis:g+N,alignmentAxis:b}),E&&zB({mainAxis:!0,crossAxis:!1,limiter:C==="partial"?BB():void 0,...se}),E&&IB({...se}),UB({...se,apply:({elements:Kt,rects:Er,availableWidth:gt,availableHeight:Vs})=>{const{width:L,height:Q}=Er.reference,J=Kt.floating.style;J.setProperty("--radix-popper-available-width",`${gt}px`),J.setProperty("--radix-popper-available-height",`${Vs}px`),J.setProperty("--radix-popper-anchor-width",`${L}px`),J.setProperty("--radix-popper-anchor-height",`${Q}px`)}}),X&&lU({element:X,padding:S}),vU({arrowWidth:F,arrowHeight:N}),R&&LB({strategy:"referenceHidden",...se})]}),[he,xe]=HT(Ue),$e=Ft(M);An(()=>{We&&($e==null||$e())},[We,$e]);const Ae=(o=Oe.arrow)===null||o===void 0?void 0:o.x,Me=(i=Oe.arrow)===null||i===void 0?void 0:i.y,je=((s=Oe.arrow)===null||s===void 0?void 0:s.centerOffset)!==0,[Mt,ct]=d.useState();return An(()=>{U&&ct(window.getComputedStyle(U).zIndex)},[U]),d.createElement("div",{ref:ce.setFloating,"data-radix-popper-content-wrapper":"",style:{...Ve,transform:We?Ve.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:Mt,"--radix-popper-transform-origin":[(l=Oe.transformOrigin)===null||l===void 0?void 0:l.x,(u=Oe.transformOrigin)===null||u===void 0?void 0:u.y].join(" ")},dir:e.dir},d.createElement(pU,{scope:m,placedSide:he,onArrowChange:ae,arrowX:Ae,arrowY:Me,shouldHideArrow:je},d.createElement(Pe.div,Y({"data-side":he,"data-align":xe},A,{ref:q,style:{...A.style,animation:We?void 0:"none",opacity:(f=Oe.hide)!==null&&f!==void 0&&f.referenceHidden?0:void 0}}))))});function gU(e){return e!==null}const vU=e=>({name:"transformOrigin",options:e,fn(t){var n,r,o,i,s;const{placement:l,rects:u,middlewareData:f}=t,p=((n=f.arrow)===null||n===void 0?void 0:n.centerOffset)!==0,g=p?0:e.arrowWidth,y=p?0:e.arrowHeight,[b,S]=HT(l),E={start:"0%",center:"50%",end:"100%"}[S],_=((r=(o=f.arrow)===null||o===void 0?void 0:o.x)!==null&&r!==void 0?r:0)+g/2,x=((i=(s=f.arrow)===null||s===void 0?void 0:s.y)!==null&&i!==void 0?i:0)+y/2;let C="",R="";return b==="bottom"?(C=p?E:`${_}px`,R=`${-y}px`):b==="top"?(C=p?E:`${_}px`,R=`${u.floating.height+y}px`):b==="right"?(C=`${-y}px`,R=p?E:`${x}px`):b==="left"&&(C=`${u.floating.width+y}px`,R=p?E:`${x}px`),{data:{x:C,y:R}}}});function HT(e){const[t,n="center"]=e.split("-");return[t,n]}const jd=dU,Vm=hU,Wm=mU,zd=d.forwardRef((e,t)=>{var n;const{container:r=globalThis==null||(n=globalThis.document)===null||n===void 0?void 0:n.body,...o}=e;return r?QI.createPortal(d.createElement(Pe.div,Y({},o,{ref:t})),r):null});function yU(e,t){return d.useReducer((n,r)=>{const o=t[n][r];return o??n},e)}const Sn=e=>{const{present:t,children:n}=e,r=wU(t),o=typeof n=="function"?n({present:r.isPresent}):d.Children.only(n),i=Be(r.ref,o.ref);return typeof n=="function"||r.isPresent?d.cloneElement(o,{ref:i}):null};Sn.displayName="Presence";function wU(e){const[t,n]=d.useState(),r=d.useRef({}),o=d.useRef(e),i=d.useRef("none"),s=e?"mounted":"unmounted",[l,u]=yU(s,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return d.useEffect(()=>{const f=hh(r.current);i.current=l==="mounted"?f:"none"},[l]),An(()=>{const f=r.current,m=o.current;if(m!==e){const g=i.current,y=hh(f);e?u("MOUNT"):y==="none"||(f==null?void 0:f.display)==="none"?u("UNMOUNT"):u(m&&g!==y?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,u]),An(()=>{if(t){const f=p=>{const y=hh(r.current).includes(p.animationName);p.target===t&&y&&Is.flushSync(()=>u("ANIMATION_END"))},m=p=>{p.target===t&&(i.current=hh(r.current))};return t.addEventListener("animationstart",m),t.addEventListener("animationcancel",f),t.addEventListener("animationend",f),()=>{t.removeEventListener("animationstart",m),t.removeEventListener("animationcancel",f),t.removeEventListener("animationend",f)}}else u("ANIMATION_END")},[t,u]),{isPresent:["mounted","unmountSuspended"].includes(l),ref:d.useCallback(f=>{f&&(r.current=getComputedStyle(f)),n(f)},[])}}function hh(e){return(e==null?void 0:e.animationName)||"none"}function Zr({prop:e,defaultProp:t,onChange:n=()=>{}}){const[r,o]=xU({defaultProp:t,onChange:n}),i=e!==void 0,s=i?e:r,l=Ft(n),u=d.useCallback(f=>{if(i){const p=typeof f=="function"?f(e):f;p!==e&&l(p)}else o(f)},[i,e,o,l]);return[s,u]}function xU({defaultProp:e,onChange:t}){const n=d.useState(e),[r]=n,o=d.useRef(r),i=Ft(t);return d.useEffect(()=>{o.current!==r&&(i(r),o.current=r)},[r,o,i]),n}const Hm=d.forwardRef((e,t)=>d.createElement(Pe.span,Y({},e,{ref:t,style:{position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal",...e.style}}))),bU=Hm,[Km,mte]=Mn("Tooltip",[Fs]),wx=Fs(),SU="TooltipProvider",_U=700,d1="tooltip.open",[EU,xx]=Km(SU),CU=e=>{const{__scopeTooltip:t,delayDuration:n=_U,skipDelayDuration:r=300,disableHoverableContent:o=!1,children:i}=e,[s,l]=d.useState(!0),u=d.useRef(!1),f=d.useRef(0);return d.useEffect(()=>{const m=f.current;return()=>window.clearTimeout(m)},[]),d.createElement(EU,{scope:t,isOpenDelayed:s,delayDuration:n,onOpen:d.useCallback(()=>{window.clearTimeout(f.current),l(!1)},[]),onClose:d.useCallback(()=>{window.clearTimeout(f.current),f.current=window.setTimeout(()=>l(!0),r)},[r]),isPointerInTransitRef:u,onPointerInTransitChange:d.useCallback(m=>{u.current=m},[]),disableHoverableContent:o},i)},bx="Tooltip",[$U,Gm]=Km(bx),RU=e=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:o=!1,onOpenChange:i,disableHoverableContent:s,delayDuration:l}=e,u=xx(bx,e.__scopeTooltip),f=wx(t),[m,p]=d.useState(null),g=nr(),y=d.useRef(0),b=s??u.disableHoverableContent,S=l??u.delayDuration,E=d.useRef(!1),[_=!1,x]=Zr({prop:r,defaultProp:o,onChange:A=>{A?(u.onOpen(),document.dispatchEvent(new CustomEvent(d1))):u.onClose(),i==null||i(A)}}),C=d.useMemo(()=>_?E.current?"delayed-open":"instant-open":"closed",[_]),R=d.useCallback(()=>{window.clearTimeout(y.current),E.current=!1,x(!0)},[x]),P=d.useCallback(()=>{window.clearTimeout(y.current),x(!1)},[x]),M=d.useCallback(()=>{window.clearTimeout(y.current),y.current=window.setTimeout(()=>{E.current=!0,x(!0)},S)},[S,x]);return d.useEffect(()=>()=>window.clearTimeout(y.current),[]),d.createElement(jd,f,d.createElement($U,{scope:t,contentId:g,open:_,stateAttribute:C,trigger:m,onTriggerChange:p,onTriggerEnter:d.useCallback(()=>{u.isOpenDelayed?M():R()},[u.isOpenDelayed,M,R]),onTriggerLeave:d.useCallback(()=>{b?P():window.clearTimeout(y.current)},[P,b]),onOpen:R,onClose:P,disableHoverableContent:b},n))},WC="TooltipTrigger",kU=d.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,o=Gm(WC,n),i=xx(WC,n),s=wx(n),l=d.useRef(null),u=Be(t,l,o.onTriggerChange),f=d.useRef(!1),m=d.useRef(!1),p=d.useCallback(()=>f.current=!1,[]);return d.useEffect(()=>()=>document.removeEventListener("pointerup",p),[p]),d.createElement(Vm,Y({asChild:!0},s),d.createElement(Pe.button,Y({"aria-describedby":o.open?o.contentId:void 0,"data-state":o.stateAttribute},r,{ref:u,onPointerMove:de(e.onPointerMove,g=>{g.pointerType!=="touch"&&!m.current&&!i.isPointerInTransitRef.current&&(o.onTriggerEnter(),m.current=!0)}),onPointerLeave:de(e.onPointerLeave,()=>{o.onTriggerLeave(),m.current=!1}),onPointerDown:de(e.onPointerDown,()=>{f.current=!0,document.addEventListener("pointerup",p,{once:!0})}),onFocus:de(e.onFocus,()=>{f.current||o.onOpen()}),onBlur:de(e.onBlur,o.onClose),onClick:de(e.onClick,o.onClose)})))}),TU="TooltipPortal",[gte,PU]=Km(TU,{forceMount:void 0}),ud="TooltipContent",AU=d.forwardRef((e,t)=>{const n=PU(ud,e.__scopeTooltip),{forceMount:r=n.forceMount,side:o="top",...i}=e,s=Gm(ud,e.__scopeTooltip);return d.createElement(Sn,{present:r||s.open},s.disableHoverableContent?d.createElement(KT,Y({side:o},i,{ref:t})):d.createElement(MU,Y({side:o},i,{ref:t})))}),MU=d.forwardRef((e,t)=>{const n=Gm(ud,e.__scopeTooltip),r=xx(ud,e.__scopeTooltip),o=d.useRef(null),i=Be(t,o),[s,l]=d.useState(null),{trigger:u,onClose:f}=n,m=o.current,{onPointerInTransitChange:p}=r,g=d.useCallback(()=>{l(null),p(!1)},[p]),y=d.useCallback((b,S)=>{const E=b.currentTarget,_={x:b.clientX,y:b.clientY},x=NU(_,E.getBoundingClientRect()),C=DU(_,x),R=IU(S.getBoundingClientRect()),P=FU([...C,...R]);l(P),p(!0)},[p]);return d.useEffect(()=>()=>g(),[g]),d.useEffect(()=>{if(u&&m){const b=E=>y(E,m),S=E=>y(E,u);return u.addEventListener("pointerleave",b),m.addEventListener("pointerleave",S),()=>{u.removeEventListener("pointerleave",b),m.removeEventListener("pointerleave",S)}}},[u,m,y,g]),d.useEffect(()=>{if(s){const b=S=>{const E=S.target,_={x:S.clientX,y:S.clientY},x=(u==null?void 0:u.contains(E))||(m==null?void 0:m.contains(E)),C=!LU(_,s);x?g():C&&(g(),f())};return document.addEventListener("pointermove",b),()=>document.removeEventListener("pointermove",b)}},[u,m,s,f,g]),d.createElement(KT,Y({},e,{ref:i}))}),[OU,vte]=Km(bx,{isInside:!1}),KT=d.forwardRef((e,t)=>{const{__scopeTooltip:n,children:r,"aria-label":o,onEscapeKeyDown:i,onPointerDownOutside:s,...l}=e,u=Gm(ud,n),f=wx(n),{onClose:m}=u;return d.useEffect(()=>(document.addEventListener(d1,m),()=>document.removeEventListener(d1,m)),[m]),d.useEffect(()=>{if(u.trigger){const p=g=>{const y=g.target;y!=null&&y.contains(u.trigger)&&m()};return window.addEventListener("scroll",p,{capture:!0}),()=>window.removeEventListener("scroll",p,{capture:!0})}},[u.trigger,m]),d.createElement(Ec,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:i,onPointerDownOutside:s,onFocusOutside:p=>p.preventDefault(),onDismiss:m},d.createElement(Wm,Y({"data-state":u.stateAttribute},f,l,{ref:t,style:{...l.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"}}),d.createElement(lx,null,r),d.createElement(OU,{scope:n,isInside:!0},d.createElement(bU,{id:u.contentId,role:"tooltip"},o||r))))});function NU(e,t){const n=Math.abs(t.top-e.y),r=Math.abs(t.bottom-e.y),o=Math.abs(t.right-e.x),i=Math.abs(t.left-e.x);switch(Math.min(n,r,o,i)){case i:return"left";case o:return"right";case n:return"top";case r:return"bottom";default:throw new Error("unreachable")}}function DU(e,t,n=5){const r=[];switch(t){case"top":r.push({x:e.x-n,y:e.y+n},{x:e.x+n,y:e.y+n});break;case"bottom":r.push({x:e.x-n,y:e.y-n},{x:e.x+n,y:e.y-n});break;case"left":r.push({x:e.x+n,y:e.y-n},{x:e.x+n,y:e.y+n});break;case"right":r.push({x:e.x-n,y:e.y-n},{x:e.x-n,y:e.y+n});break}return r}function IU(e){const{top:t,right:n,bottom:r,left:o}=e;return[{x:o,y:t},{x:n,y:t},{x:n,y:r},{x:o,y:r}]}function LU(e,t){const{x:n,y:r}=e;let o=!1;for(let i=0,s=t.length-1;ir!=m>r&&n<(f-l)*(r-u)/(m-u)+l&&(o=!o)}return o}function FU(e){const t=e.slice();return t.sort((n,r)=>n.xr.x?1:n.yr.y?1:0),jU(t)}function jU(e){if(e.length<=1)return e.slice();const t=[];for(let r=0;r=2;){const i=t[t.length-1],s=t[t.length-2];if((i.x-s.x)*(o.y-s.y)>=(i.y-s.y)*(o.x-s.x))t.pop();else break}t.push(o)}t.pop();const n=[];for(let r=e.length-1;r>=0;r--){const o=e[r];for(;n.length>=2;){const i=n[n.length-1],s=n[n.length-2];if((i.x-s.x)*(o.y-s.y)>=(i.y-s.y)*(o.x-s.x))n.pop();else break}n.push(o)}return n.pop(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}const zU=CU,BU=RU,UU=kU,GT=AU,VU=zU,YT=BU,XT=UU,Sx=d.forwardRef(({className:e,sideOffset:t=4,...n},r)=>v.jsx(GT,{ref:r,sideOffset:t,className:Ce("z-50 border overflow-hidden rounded-md bg-background text-foreground px-3 py-1.5 text-xs animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...n}));Sx.displayName=GT.displayName;const _x=Dm("inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50",{variants:{variant:{default:"bg-primary text-primary-foreground shadow hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",outline:"border border-input bg-transparent shadow-sm hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2",sm:"h-8 rounded-md px-3 text-xs",lg:"h-10 rounded-md px-8",icon:"h-9 w-9"}},defaultVariants:{variant:"default",size:"default"}}),wn=d.forwardRef(({className:e,variant:t,size:n,asChild:r=!1,...o},i)=>{const s=r?Zo:"button";return v.jsx(s,{className:Ce(_x({variant:t,size:n,className:e}),"outline-none cursor-default"),ref:i,tabIndex:-1,...o})});wn.displayName="Button";const yn=d.forwardRef(({tooltip:e,children:t,...n},r)=>v.jsxs(YT,{children:[v.jsx(XT,{asChild:!0,children:v.jsx(wn,{variant:"ghost",size:"icon",...n,ref:r,tabIndex:-1,className:"cursor-default bg-background",children:v.jsx("div",{className:"icon-button-icon-wrapper",children:t})})}),v.jsx(Sx,{children:v.jsx("p",{children:e})})]})),f1=e=>{const{onFileUpload:t,children:n,...r}=e,[o]=d.useState(`file-upload-${Math.random().toString()}`),i=s=>{var u;const l=(u=s.currentTarget.files)==null?void 0:u[0];l&&t(l)};return v.jsxs(v.Fragment,{children:[v.jsx("label",{htmlFor:o,children:v.jsx(yn,{...r,asChild:!0,children:n})}),v.jsx(Ld,{style:{display:"none"},id:o,name:o,type:"file",onChange:i,accept:"image/png, image/jpeg"})]})};var WU={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const HU=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Jt=(e,t)=>{const n=d.forwardRef(({color:r="currentColor",size:o=24,strokeWidth:i=2,absoluteStrokeWidth:s,children:l,...u},f)=>d.createElement("svg",{ref:f,...WU,width:o,height:o,stroke:r,strokeWidth:s?Number(i)*24/Number(o):i,className:`lucide lucide-${HU(e)}`,...u},[...t.map(([m,p])=>d.createElement(m,p)),...(Array.isArray(l)?l:[l])||[]]));return n.displayName=`${e}`,n},KU=Jt("Blocks",[["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["path",{d:"M10 21V8a1 1 0 0 0-1-1H4a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-5a1 1 0 0 0-1-1H3",key:"1fpvtg"}]]),GU=Jt("ChevronLeft",[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]]),YU=Jt("ChevronRight",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]),XU=Jt("Coffee",[["path",{d:"M17 8h1a4 4 0 1 1 0 8h-1",key:"jx4kbh"}],["path",{d:"M3 8h14v9a4 4 0 0 1-4 4H7a4 4 0 0 1-4-4Z",key:"1bxrl0"}],["line",{x1:"6",x2:"6",y1:"2",y2:"4",key:"1cr9l3"}],["line",{x1:"10",x2:"10",y1:"2",y2:"4",key:"170wym"}],["line",{x1:"14",x2:"14",y1:"2",y2:"4",key:"1c5f70"}]]),ZU=Jt("Download",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"7 10 12 15 17 10",key:"2ggqvy"}],["line",{x1:"12",x2:"12",y1:"15",y2:"3",key:"1vk2je"}]]),qU=Jt("Eraser",[["path",{d:"m7 21-4.3-4.3c-1-1-1-2.5 0-3.4l9.6-9.6c1-1 2.5-1 3.4 0l5.6 5.6c1 1 1 2.5 0 3.4L13 21",key:"182aya"}],["path",{d:"M22 21H7",key:"t4ddhn"}],["path",{d:"m5 11 9 9",key:"1mo9qw"}]]),QU=Jt("Expand",[["path",{d:"m21 21-6-6m6 6v-4.8m0 4.8h-4.8",key:"1c15vz"}],["path",{d:"M3 16.2V21m0 0h4.8M3 21l6-6",key:"1fsnz2"}],["path",{d:"M21 7.8V3m0 0h-4.8M21 3l-6 6",key:"hawz9i"}],["path",{d:"M3 7.8V3m0 0h4.8M3 3l6 6",key:"u9ee12"}]]),JU=Jt("Eye",[["path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z",key:"rwhkz3"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]),eV=Jt("FolderClosed",[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}],["path",{d:"M2 10h20",key:"1ir3d8"}]]),ZT=Jt("Fullscreen",[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}],["rect",{width:"10",height:"8",x:"7",y:"8",rx:"1",key:"vys8me"}]]),tV=Jt("Image",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]]),nV=Jt("Keyboard",[["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",ry:"2",key:"15u882"}],["path",{d:"M6 8h.001",key:"1ej0i3"}],["path",{d:"M10 8h.001",key:"1x2st2"}],["path",{d:"M14 8h.001",key:"1vkmyp"}],["path",{d:"M18 8h.001",key:"kfsenl"}],["path",{d:"M8 12h.001",key:"1sjpby"}],["path",{d:"M12 12h.001",key:"al75ts"}],["path",{d:"M16 12h.001",key:"931bgk"}],["path",{d:"M7 16h10",key:"wp8him"}]]),rV=Jt("MousePointerClick",[["path",{d:"m9 9 5 12 1.8-5.2L21 14Z",key:"1b76lo"}],["path",{d:"M7.2 2.2 8 5.1",key:"1cfko1"}],["path",{d:"m5.1 8-2.9-.8",key:"1go3kf"}],["path",{d:"M14 4.1 12 6",key:"ita8i4"}],["path",{d:"m6 12-1.9 2",key:"mnht97"}]]),oV=Jt("Redo",[["path",{d:"M21 7v6h-6",key:"3ptur4"}],["path",{d:"M3 17a9 9 0 0 1 9-9 9 9 0 0 1 6 2.3l3 2.7",key:"1kgawr"}]]),iV=Jt("RotateCw",[["path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8",key:"1p45f6"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}]]),sV=Jt("Settings",[["path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z",key:"1qme2f"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]),HC=Jt("Slice",[["path",{d:"m8 14-6 6h9v-3",key:"zo3j9a"}],["path",{d:"M18.37 3.63 8 14l3 3L21.37 6.63a2.12 2.12 0 1 0-3-3Z",key:"1dzx0j"}]]),KC=Jt("Smile",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 14s1.5 2 4 2 4-2 4-2",key:"1y1vjs"}],["line",{x1:"9",x2:"9.01",y1:"9",y2:"9",key:"yxxnd0"}],["line",{x1:"15",x2:"15.01",y1:"9",y2:"9",key:"1p4y9e"}]]),aV=Jt("Undo",[["path",{d:"M3 7v6h6",key:"1v2h90"}],["path",{d:"M21 17a9 9 0 0 0-9-9 9 9 0 0 0-6 2.3L3 13",key:"1r6uu6"}]]),qT=Jt("Upload",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"17 8 12 3 7 8",key:"t8dd8p"}],["line",{x1:"12",x2:"12",y1:"3",y2:"15",key:"widbto"}]]);function lV(e,t){const[n,r]=d.useState(e);return d.useEffect(()=>{const o=setTimeout(()=>{r(e)},t);return()=>{clearTimeout(o)}},[e,t]),n}function QT(e){const[t,n]=d.useState(()=>typeof e=="boolean"?e:!!e),r=d.useCallback(o=>n(typeof o=="boolean"?o:i=>!i),[]);return[t,r]}const _0="focusScope.autoFocusOnMount",E0="focusScope.autoFocusOnUnmount",GC={bubbles:!1,cancelable:!0},Ym=d.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:o,onUnmountAutoFocus:i,...s}=e,[l,u]=d.useState(null),f=Ft(o),m=Ft(i),p=d.useRef(null),g=Be(t,S=>u(S)),y=d.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;d.useEffect(()=>{if(r){let x=function(M){if(y.paused||!l)return;const A=M.target;l.contains(A)?p.current=A:Qi(p.current,{select:!0})},C=function(M){if(y.paused||!l)return;const A=M.relatedTarget;A!==null&&(l.contains(A)||Qi(p.current,{select:!0}))},R=function(M){if(document.activeElement===document.body)for(const D of M)D.removedNodes.length>0&&Qi(l)};var S=x,E=C,_=R;document.addEventListener("focusin",x),document.addEventListener("focusout",C);const P=new MutationObserver(R);return l&&P.observe(l,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",x),document.removeEventListener("focusout",C),P.disconnect()}}},[r,l,y.paused]),d.useEffect(()=>{if(l){XC.add(y);const S=document.activeElement;if(!l.contains(S)){const _=new CustomEvent(_0,GC);l.addEventListener(_0,f),l.dispatchEvent(_),_.defaultPrevented||(cV(pV(JT(l)),{select:!0}),document.activeElement===S&&Qi(l))}return()=>{l.removeEventListener(_0,f),setTimeout(()=>{const _=new CustomEvent(E0,GC);l.addEventListener(E0,m),l.dispatchEvent(_),_.defaultPrevented||Qi(S??document.body,{select:!0}),l.removeEventListener(E0,m),XC.remove(y)},0)}}},[l,f,m,y]);const b=d.useCallback(S=>{if(!n&&!r||y.paused)return;const E=S.key==="Tab"&&!S.altKey&&!S.ctrlKey&&!S.metaKey,_=document.activeElement;if(E&&_){const x=S.currentTarget,[C,R]=uV(x);C&&R?!S.shiftKey&&_===R?(S.preventDefault(),n&&Qi(C,{select:!0})):S.shiftKey&&_===C&&(S.preventDefault(),n&&Qi(R,{select:!0})):_===x&&S.preventDefault()}},[n,r,y.paused]);return d.createElement(Pe.div,Y({tabIndex:-1},s,{ref:g,onKeyDown:b}))});function cV(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(Qi(r,{select:t}),document.activeElement!==n)return}function uV(e){const t=JT(e),n=YC(t,e),r=YC(t.reverse(),e);return[n,r]}function JT(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const o=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||o?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function YC(e,t){for(const n of e)if(!dV(n,{upTo:t}))return n}function dV(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function fV(e){return e instanceof HTMLInputElement&&"select"in e}function Qi(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&fV(e)&&t&&e.select()}}const XC=hV();function hV(){let e=[];return{add(t){const n=e[0];t!==n&&(n==null||n.pause()),e=ZC(e,t),e.unshift(t)},remove(t){var n;e=ZC(e,t),(n=e[0])===null||n===void 0||n.resume()}}}function ZC(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function pV(e){return e.filter(t=>t.tagName!=="A")}let C0=0;function Xm(){d.useEffect(()=>{var e,t;const n=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",(e=n[0])!==null&&e!==void 0?e:qC()),document.body.insertAdjacentElement("beforeend",(t=n[1])!==null&&t!==void 0?t:qC()),C0++,()=>{C0===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(r=>r.remove()),C0--}},[])}function qC(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.cssText="outline: none; opacity: 0; position: fixed; pointer-events: none",e}var Lo=function(){return Lo=Object.assign||function(t){for(var n,r=1,o=arguments.length;r"u")return AV;var t=MV(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])}},NV=rP(),DV=function(e,t,n,r){var o=e.left,i=e.top,s=e.right,l=e.gap;return n===void 0&&(n="margin"),` + .`.concat(gV,` { + overflow: hidden `).concat(r,`; + padding-right: `).concat(l,"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(i,`px; + padding-right: `).concat(s,`px; + margin-left:0; + margin-top:0; + margin-right: `).concat(l,"px ").concat(r,`; + `),n==="padding"&&"padding-right: ".concat(l,"px ").concat(r,";")].filter(Boolean).join(""),` + } + + .`).concat(qh,` { + right: `).concat(l,"px ").concat(r,`; + } + + .`).concat(Qh,` { + margin-right: `).concat(l,"px ").concat(r,`; + } + + .`).concat(qh," .").concat(qh,` { + right: 0 `).concat(r,`; + } + + .`).concat(Qh," .").concat(Qh,` { + margin-right: 0 `).concat(r,`; + } + + body { + `).concat(vV,": ").concat(l,`px; + } +`)},IV=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,o=r===void 0?"margin":r,i=d.useMemo(function(){return OV(o)},[o]);return d.createElement(NV,{styles:DV(i,!t,o,n?"":"!important")})},h1=!1;if(typeof window<"u")try{var ph=Object.defineProperty({},"passive",{get:function(){return h1=!0,!0}});window.addEventListener("test",ph,ph),window.removeEventListener("test",ph,ph)}catch{h1=!1}var rl=h1?{passive:!1}:!1,LV=function(e){return e.tagName==="TEXTAREA"},oP=function(e,t){var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!LV(e)&&n[t]==="visible")},FV=function(e){return oP(e,"overflowY")},jV=function(e){return oP(e,"overflowX")},JC=function(e,t){var n=t;do{typeof ShadowRoot<"u"&&n instanceof ShadowRoot&&(n=n.host);var r=iP(e,n);if(r){var o=sP(e,n),i=o[1],s=o[2];if(i>s)return!0}n=n.parentNode}while(n&&n!==document.body);return!1},zV=function(e){var t=e.scrollTop,n=e.scrollHeight,r=e.clientHeight;return[t,n,r]},BV=function(e){var t=e.scrollLeft,n=e.scrollWidth,r=e.clientWidth;return[t,n,r]},iP=function(e,t){return e==="v"?FV(t):jV(t)},sP=function(e,t){return e==="v"?zV(t):BV(t)},UV=function(e,t){return e==="h"&&t==="rtl"?-1:1},VV=function(e,t,n,r,o){var i=UV(e,window.getComputedStyle(t).direction),s=i*r,l=n.target,u=t.contains(l),f=!1,m=s>0,p=0,g=0;do{var y=sP(e,l),b=y[0],S=y[1],E=y[2],_=S-E-i*b;(b||_)&&iP(e,l)&&(p+=_,g+=b),l=l.parentNode}while(!u&&l!==document.body||u&&(t.contains(l)||t===l));return(m&&(o&&p===0||!o&&s>p)||!m&&(o&&g===0||!o&&-s>g))&&(f=!0),f},mh=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},e2=function(e){return[e.deltaX,e.deltaY]},t2=function(e){return e&&"current"in e?e.current:e},WV=function(e,t){return e[0]===t[0]&&e[1]===t[1]},HV=function(e){return` + .block-interactivity-`.concat(e,` {pointer-events: none;} + .allow-interactivity-`).concat(e,` {pointer-events: all;} +`)},KV=0,ol=[];function GV(e){var t=d.useRef([]),n=d.useRef([0,0]),r=d.useRef(),o=d.useState(KV++)[0],i=d.useState(function(){return rP()})[0],s=d.useRef(e);d.useEffect(function(){s.current=e},[e]),d.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(o));var S=mV([e.lockRef.current],(e.shards||[]).map(t2),!0).filter(Boolean);return S.forEach(function(E){return E.classList.add("allow-interactivity-".concat(o))}),function(){document.body.classList.remove("block-interactivity-".concat(o)),S.forEach(function(E){return E.classList.remove("allow-interactivity-".concat(o))})}}},[e.inert,e.lockRef.current,e.shards]);var l=d.useCallback(function(S,E){if("touches"in S&&S.touches.length===2)return!s.current.allowPinchZoom;var _=mh(S),x=n.current,C="deltaX"in S?S.deltaX:x[0]-_[0],R="deltaY"in S?S.deltaY:x[1]-_[1],P,M=S.target,A=Math.abs(C)>Math.abs(R)?"h":"v";if("touches"in S&&A==="h"&&M.type==="range")return!1;var D=JC(A,M);if(!D)return!0;if(D?P=A:(P=A==="v"?"h":"v",D=JC(A,M)),!D)return!1;if(!r.current&&"changedTouches"in S&&(C||R)&&(r.current=P),!P)return!0;var U=r.current||P;return VV(U,E,S,U==="h"?C:R,!0)},[]),u=d.useCallback(function(S){var E=S;if(!(!ol.length||ol[ol.length-1]!==i)){var _="deltaY"in E?e2(E):mh(E),x=t.current.filter(function(P){return P.name===E.type&&P.target===E.target&&WV(P.delta,_)})[0];if(x&&x.should){E.cancelable&&E.preventDefault();return}if(!x){var C=(s.current.shards||[]).map(t2).filter(Boolean).filter(function(P){return P.contains(E.target)}),R=C.length>0?l(E,C[0]):!s.current.noIsolation;R&&E.cancelable&&E.preventDefault()}}},[]),f=d.useCallback(function(S,E,_,x){var C={name:S,delta:E,target:_,should:x};t.current.push(C),setTimeout(function(){t.current=t.current.filter(function(R){return R!==C})},1)},[]),m=d.useCallback(function(S){n.current=mh(S),r.current=void 0},[]),p=d.useCallback(function(S){f(S.type,e2(S),S.target,l(S,e.lockRef.current))},[]),g=d.useCallback(function(S){f(S.type,mh(S),S.target,l(S,e.lockRef.current))},[]);d.useEffect(function(){return ol.push(i),e.setCallbacks({onScrollCapture:p,onWheelCapture:p,onTouchMoveCapture:g}),document.addEventListener("wheel",u,rl),document.addEventListener("touchmove",u,rl),document.addEventListener("touchstart",m,rl),function(){ol=ol.filter(function(S){return S!==i}),document.removeEventListener("wheel",u,rl),document.removeEventListener("touchmove",u,rl),document.removeEventListener("touchstart",m,rl)}},[]);var y=e.removeScrollBar,b=e.inert;return d.createElement(d.Fragment,null,b?d.createElement(i,{styles:HV(o)}):null,y?d.createElement(IV,{gapMode:"margin"}):null)}const YV=EV(nP,GV);var aP=d.forwardRef(function(e,t){return d.createElement(Zm,Lo({},e,{ref:t,sideCar:YV}))});aP.classNames=Zm.classNames;const qm=aP;var XV=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},il=new WeakMap,gh=new WeakMap,vh={},k0=0,lP=function(e){return e&&(e.host||lP(e.parentNode))},ZV=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=lP(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})},qV=function(e,t,n,r){var o=ZV(t,Array.isArray(e)?e:[e]);vh[n]||(vh[n]=new WeakMap);var i=vh[n],s=[],l=new Set,u=new Set(o),f=function(p){!p||l.has(p)||(l.add(p),f(p.parentNode))};o.forEach(f);var m=function(p){!p||u.has(p)||Array.prototype.forEach.call(p.children,function(g){if(l.has(g))m(g);else{var y=g.getAttribute(r),b=y!==null&&y!=="false",S=(il.get(g)||0)+1,E=(i.get(g)||0)+1;il.set(g,S),i.set(g,E),s.push(g),S===1&&b&&gh.set(g,!0),E===1&&g.setAttribute(n,"true"),b||g.setAttribute(r,"true")}})};return m(t),l.clear(),k0++,function(){s.forEach(function(p){var g=il.get(p)-1,y=i.get(p)-1;il.set(p,g),i.set(p,y),g||(gh.has(p)||p.removeAttribute(r),gh.delete(p)),y||p.removeAttribute(n)}),k0--,k0||(il=new WeakMap,il=new WeakMap,gh=new WeakMap,vh={})}},Qm=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),o=t||XV(e);return o?(r.push.apply(r,Array.from(o.querySelectorAll("[aria-live]"))),qV(r,o,n,"aria-hidden")):function(){return null}};const cP="Dialog",[uP,dP]=Mn(cP),[QV,Eo]=uP(cP),JV=e=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:o,onOpenChange:i,modal:s=!0}=e,l=d.useRef(null),u=d.useRef(null),[f=!1,m]=Zr({prop:r,defaultProp:o,onChange:i});return d.createElement(QV,{scope:t,triggerRef:l,contentRef:u,contentId:nr(),titleId:nr(),descriptionId:nr(),open:f,onOpenChange:m,onOpenToggle:d.useCallback(()=>m(p=>!p),[m]),modal:s},n)},eW="DialogTrigger",fP=d.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=Eo(eW,n),i=Be(t,o.triggerRef);return d.createElement(Pe.button,Y({type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":Ex(o.open)},r,{ref:i,onClick:de(e.onClick,o.onOpenToggle)}))}),hP="DialogPortal",[tW,pP]=uP(hP,{forceMount:void 0}),nW=e=>{const{__scopeDialog:t,forceMount:n,children:r,container:o}=e,i=Eo(hP,t);return d.createElement(tW,{scope:t,forceMount:n},d.Children.map(r,s=>d.createElement(Sn,{present:n||i.open},d.createElement(zd,{asChild:!0,container:o},s))))},p1="DialogOverlay",rW=d.forwardRef((e,t)=>{const n=pP(p1,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,i=Eo(p1,e.__scopeDialog);return i.modal?d.createElement(Sn,{present:r||i.open},d.createElement(oW,Y({},o,{ref:t}))):null}),oW=d.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=Eo(p1,n);return d.createElement(qm,{as:Zo,allowPinchZoom:!0,shards:[o.contentRef]},d.createElement(Pe.div,Y({"data-state":Ex(o.open)},r,{ref:t,style:{pointerEvents:"auto",...r.style}})))}),uc="DialogContent",iW=d.forwardRef((e,t)=>{const n=pP(uc,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,i=Eo(uc,e.__scopeDialog);return d.createElement(Sn,{present:r||i.open},i.modal?d.createElement(sW,Y({},o,{ref:t})):d.createElement(aW,Y({},o,{ref:t})))}),sW=d.forwardRef((e,t)=>{const n=Eo(uc,e.__scopeDialog),r=d.useRef(null),o=Be(t,n.contentRef,r);return d.useEffect(()=>{const i=r.current;if(i)return Qm(i)},[]),d.createElement(mP,Y({},e,{ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:de(e.onCloseAutoFocus,i=>{var s;i.preventDefault(),(s=n.triggerRef.current)===null||s===void 0||s.focus()}),onPointerDownOutside:de(e.onPointerDownOutside,i=>{const s=i.detail.originalEvent,l=s.button===0&&s.ctrlKey===!0;(s.button===2||l)&&i.preventDefault()}),onFocusOutside:de(e.onFocusOutside,i=>i.preventDefault())}))}),aW=d.forwardRef((e,t)=>{const n=Eo(uc,e.__scopeDialog),r=d.useRef(!1),o=d.useRef(!1);return d.createElement(mP,Y({},e,{ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var s;if((s=e.onCloseAutoFocus)===null||s===void 0||s.call(e,i),!i.defaultPrevented){var l;r.current||(l=n.triggerRef.current)===null||l===void 0||l.focus(),i.preventDefault()}r.current=!1,o.current=!1},onInteractOutside:i=>{var s,l;(s=e.onInteractOutside)===null||s===void 0||s.call(e,i),i.defaultPrevented||(r.current=!0,i.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const u=i.target;((l=n.triggerRef.current)===null||l===void 0?void 0:l.contains(u))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&o.current&&i.preventDefault()}}))}),mP=d.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:i,...s}=e,l=Eo(uc,n),u=d.useRef(null),f=Be(t,u);return Xm(),d.createElement(d.Fragment,null,d.createElement(Ym,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:i},d.createElement(Ec,Y({role:"dialog",id:l.contentId,"aria-describedby":l.descriptionId,"aria-labelledby":l.titleId,"data-state":Ex(l.open)},s,{ref:f,onDismiss:()=>l.onOpenChange(!1)}))),!1)}),gP="DialogTitle",lW=d.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=Eo(gP,n);return d.createElement(Pe.h2,Y({id:o.titleId},r,{ref:t}))}),cW="DialogDescription",vP=d.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=Eo(cW,n);return d.createElement(Pe.p,Y({id:o.descriptionId},r,{ref:t}))}),uW="DialogClose",dW=d.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=Eo(uW,n);return d.createElement(Pe.button,Y({type:"button"},r,{ref:t,onClick:de(e.onClick,()=>o.onOpenChange(!1))}))});function Ex(e){return e?"open":"closed"}const fW="DialogTitleWarning",[hW,yte]=pB(fW,{contentName:uc,titleName:gP,docsSlug:"dialog"}),Cx=JV,yP=fP,$x=nW,Bd=rW,Ud=iW,Vd=lW,Wd=vP,Rx=dW,Jm=Cx,kx=yP,pW=$x,wP=d.forwardRef(({className:e,...t},n)=>v.jsx(Bd,{ref:n,className:Ce("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t}));wP.displayName=Bd.displayName;const Hd=d.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(pW,{children:[v.jsx(wP,{}),v.jsxs(Ud,{ref:r,className:Ce("fixed left-[50%] top-[50%] z-50 flex flex-col w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",e,"outline-none"),onCloseAutoFocus:o=>o.preventDefault(),...n,children:[t,v.jsxs(Rx,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[v.jsx(wT,{className:"h-4 w-4"}),v.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Hd.displayName=Ud.displayName;const xP=({className:e,...t})=>v.jsx("div",{className:Ce("flex flex-col space-y-1.5 text-center sm:text-left",e),...t});xP.displayName="DialogHeader";const Kd=d.forwardRef(({className:e,...t},n)=>v.jsx(Vd,{ref:n,className:Ce("text-2xl font-semibold leading-none tracking-tight",e),...t}));Kd.displayName=Vd.displayName;const mW=d.forwardRef(({className:e,...t},n)=>v.jsx(Wd,{ref:n,className:Ce("text-sm text-muted-foreground",e),...t}));mW.displayName=Wd.displayName;function m1(){return m1=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 _W=function(t,n,r){r===void 0&&(r=!1);var o=n.alt,i=n.meta,s=n.mod,l=n.shift,u=n.ctrl,f=n.keys,m=t.key,p=t.code,g=t.ctrlKey,y=t.metaKey,b=t.shiftKey,S=t.altKey,E=hs(p),_=m.toLowerCase();if(!r){if(o===!S&&_!=="alt"||l===!b&&_!=="shift")return!1;if(s){if(!y&&!g)return!1}else if(i===!y&&_!=="meta"&&_!=="os"||u===!g&&_!=="ctrl"&&_!=="control")return!1}return f&&f.length===1&&(f.includes(_)||f.includes(E))?!0:f?yW(f):!f},EW=d.createContext(void 0),CW=function(){return d.useContext(EW)};function CP(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&&CP(e[r],t[r])},!0):e===t}var $W=d.createContext({hotkeys:[],enabledScopes:[],toggleScope:function(){},enableScope:function(){},disableScope:function(){}}),RW=function(){return d.useContext($W)};function kW(e){var t=d.useRef(void 0);return CP(t.current,e)||(t.current=e),t.current}var n2=function(t){t.stopPropagation(),t.preventDefault(),t.stopImmediatePropagation()},TW=typeof window<"u"?d.useLayoutEffect:d.useEffect;function PW(e,t,n,r){var o=d.useRef(null),i=d.useRef(!1),s=n instanceof Array?r instanceof Array?void 0:r:n,l=Tx(e)?e.join(s==null?void 0:s.splitKey):e,u=n instanceof Array?n:r instanceof Array?r:void 0,f=d.useCallback(t,u??[]),m=d.useRef(f);u?m.current=f:m.current=t;var p=kW(s),g=RW(),y=g.enabledScopes,b=CW();return TW(function(){if(!((p==null?void 0:p.enabled)===!1||!SW(y,p==null?void 0:p.scopes))){var S=function(R,P){var M;if(P===void 0&&(P=!1),!(bW(R)&&!EP(R,p==null?void 0:p.enableOnFormTags))&&!(p!=null&&p.ignoreEventWhen!=null&&p.ignoreEventWhen(R))){if(o.current!==null&&document.activeElement!==o.current&&!o.current.contains(document.activeElement)){n2(R);return}(M=R.target)!=null&&M.isContentEditable&&!(p!=null&&p.enableOnContentEditable)||T0(l,p==null?void 0:p.splitKey).forEach(function(A){var D,U=P0(A,p==null?void 0:p.combinationKey);if(_W(R,U,p==null?void 0:p.ignoreModifiers)||(D=U.keys)!=null&&D.includes("*")){if(P&&i.current)return;if(wW(R,U,p==null?void 0:p.preventDefault),!xW(R,U,p==null?void 0:p.enabled)){n2(R);return}m.current(R,U),P||(i.current=!0)}})}},E=function(R){R.key!==void 0&&(SP(hs(R.code)),((p==null?void 0:p.keydown)===void 0&&(p==null?void 0:p.keyup)!==!0||p!=null&&p.keydown)&&S(R))},_=function(R){R.key!==void 0&&(_P(hs(R.code)),i.current=!1,p!=null&&p.keyup&&S(R,!0))},x=o.current||(s==null?void 0:s.document)||document;return x.addEventListener("keyup",_),x.addEventListener("keydown",E),b&&T0(l,p==null?void 0:p.splitKey).forEach(function(C){return b.addHotkey(P0(C,p==null?void 0:p.combinationKey,p==null?void 0:p.description))}),function(){x.removeEventListener("keyup",_),x.removeEventListener("keydown",E),b&&T0(l,p==null?void 0:p.splitKey).forEach(function(C){return b.removeHotkey(P0(C,p==null?void 0:p.combinationKey,p==null?void 0:p.description))})}}},[l,p,y]),o}const Zn=(e,t,n)=>{const r=bt(i=>i.disableShortCuts);return PW(e,t,{enabled:!r},n)};function ur(e){const{content:t,keys:n}=e;return v.jsxs("div",{className:"flex justify-between",children:[v.jsx("div",{children:t}),v.jsx("div",{className:"flex gap-[8px]",children:n.map(r=>v.jsx("div",{className:"border px-2 py-1 rounded-lg",children:r},r))})]})}const AW=function(){return/macintosh|mac os x/i.test(navigator.userAgent)},yh=()=>AW()?"Cmd":"Ctrl";function MW(){const[e,t]=QT(!1);return Zn("h",()=>{t()}),v.jsxs(Jm,{open:e,onOpenChange:t,children:[v.jsx(kx,{asChild:!0,children:v.jsx(yn,{tooltip:"Hotkeys",children:v.jsx(nV,{})})}),v.jsx(Hd,{children:v.jsxs(xP,{children:[v.jsx(Kd,{children:"Hotkeys"}),v.jsxs("div",{className:"flex gap-2 flex-col pt-4",children:[v.jsx(ur,{content:"Pan",keys:["Space + Drag"]}),v.jsx(ur,{content:"Reset Zoom/Pan",keys:["Esc"]}),v.jsx(ur,{content:"Decrease Brush Size",keys:["["]}),v.jsx(ur,{content:"Increase Brush Size",keys:["]"]}),v.jsx(ur,{content:"View Original Image",keys:["Hold Tab"]}),v.jsx(ur,{content:"Undo",keys:[yh(),"Z"]}),v.jsx(ur,{content:"Redo",keys:[yh(),"Shift","Z"]}),v.jsx(ur,{content:"Copy Result",keys:[yh(),"C"]}),v.jsx(ur,{content:"Paste Image",keys:[yh(),"V"]}),v.jsx(ur,{content:"Trigger Manually Inpainting",keys:["Shift","R"]}),v.jsx(ur,{content:"Toggle Hotkeys Dialog",keys:["H"]}),v.jsx(ur,{content:"Toggle Settings Dialog",keys:["S"]}),v.jsx(ur,{content:"Toggle File Manager",keys:["F"]})]})]})})]})}function Px(e){const[t]=d.useState(new Image),[n,r]=d.useState(!1);return d.useEffect(()=>{if(e)return t.onload=()=>{r(!0)},r(!1),t.src=URL.createObjectURL(e),()=>{t.onload=null}},[e,t]),[t,n]}const $P="Popover",[RP,wte]=Mn($P,[Fs]),Ax=Fs(),[OW,Rc]=RP($P),NW=e=>{const{__scopePopover:t,children:n,open:r,defaultOpen:o,onOpenChange:i,modal:s=!1}=e,l=Ax(t),u=d.useRef(null),[f,m]=d.useState(!1),[p=!1,g]=Zr({prop:r,defaultProp:o,onChange:i});return d.createElement(jd,l,d.createElement(OW,{scope:t,contentId:nr(),triggerRef:u,open:p,onOpenChange:g,onOpenToggle:d.useCallback(()=>g(y=>!y),[g]),hasCustomAnchor:f,onCustomAnchorAdd:d.useCallback(()=>m(!0),[]),onCustomAnchorRemove:d.useCallback(()=>m(!1),[]),modal:s},n))},DW="PopoverTrigger",IW=d.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,o=Rc(DW,n),i=Ax(n),s=Be(t,o.triggerRef),l=d.createElement(Pe.button,Y({type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":PP(o.open)},r,{ref:s,onClick:de(e.onClick,o.onOpenToggle)}));return o.hasCustomAnchor?l:d.createElement(Vm,Y({asChild:!0},i),l)}),kP="PopoverPortal",[LW,FW]=RP(kP,{forceMount:void 0}),jW=e=>{const{__scopePopover:t,forceMount:n,children:r,container:o}=e,i=Rc(kP,t);return d.createElement(LW,{scope:t,forceMount:n},d.createElement(Sn,{present:n||i.open},d.createElement(zd,{asChild:!0,container:o},r)))},dd="PopoverContent",zW=d.forwardRef((e,t)=>{const n=FW(dd,e.__scopePopover),{forceMount:r=n.forceMount,...o}=e,i=Rc(dd,e.__scopePopover);return d.createElement(Sn,{present:r||i.open},i.modal?d.createElement(BW,Y({},o,{ref:t})):d.createElement(UW,Y({},o,{ref:t})))}),BW=d.forwardRef((e,t)=>{const n=Rc(dd,e.__scopePopover),r=d.useRef(null),o=Be(t,r),i=d.useRef(!1);return d.useEffect(()=>{const s=r.current;if(s)return Qm(s)},[]),d.createElement(qm,{as:Zo,allowPinchZoom:!0},d.createElement(TP,Y({},e,{ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:de(e.onCloseAutoFocus,s=>{var l;s.preventDefault(),i.current||(l=n.triggerRef.current)===null||l===void 0||l.focus()}),onPointerDownOutside:de(e.onPointerDownOutside,s=>{const l=s.detail.originalEvent,u=l.button===0&&l.ctrlKey===!0,f=l.button===2||u;i.current=f},{checkForDefaultPrevented:!1}),onFocusOutside:de(e.onFocusOutside,s=>s.preventDefault(),{checkForDefaultPrevented:!1})})))}),UW=d.forwardRef((e,t)=>{const n=Rc(dd,e.__scopePopover),r=d.useRef(!1),o=d.useRef(!1);return d.createElement(TP,Y({},e,{ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var s;if((s=e.onCloseAutoFocus)===null||s===void 0||s.call(e,i),!i.defaultPrevented){var l;r.current||(l=n.triggerRef.current)===null||l===void 0||l.focus(),i.preventDefault()}r.current=!1,o.current=!1},onInteractOutside:i=>{var s,l;(s=e.onInteractOutside)===null||s===void 0||s.call(e,i),i.defaultPrevented||(r.current=!0,i.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const u=i.target;((l=n.triggerRef.current)===null||l===void 0?void 0:l.contains(u))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&o.current&&i.preventDefault()}}))}),TP=d.forwardRef((e,t)=>{const{__scopePopover:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:i,disableOutsidePointerEvents:s,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:f,onInteractOutside:m,...p}=e,g=Rc(dd,n),y=Ax(n);return Xm(),d.createElement(Ym,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:i},d.createElement(Ec,{asChild:!0,disableOutsidePointerEvents:s,onInteractOutside:m,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:f,onDismiss:()=>g.onOpenChange(!1)},d.createElement(Wm,Y({"data-state":PP(g.open),role:"dialog",id:g.contentId},y,p,{ref:t,style:{...p.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}}))))});function PP(e){return e?"open":"closed"}const VW=NW,WW=IW,HW=jW,AP=zW,KW=VW,GW=WW,MP=d.forwardRef(({className:e,align:t="center",sideOffset:n=4,...r},o)=>v.jsx(HW,{children:v.jsx(AP,{ref:o,align:t,tabIndex:-1,sideOffset:n,className:Ce("z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...r})}));MP.displayName=AP.displayName;function YW(){var e=d.useRef(!0);return e.current?(e.current=!1,!0):e.current}var XW=function(e,t){var n=YW();d.useEffect(function(){if(!n)return e()},t)};const ZW=XW;var qW=function(){};function Mx(e){for(var t=[],n=1;n{const[e,t,n,r,o,i]=bt(g=>[g.getIsProcessing(),g.settings.prompt,g.updateSettings,g.runInpainting,g.showPrevMask,g.hidePrevMask]),s=d.useRef(null);NP(s,()=>{s!=null&&s.current&&s.current.blur()});const l=g=>{g.preventDefault(),g.stopPropagation();const y=g.target;n({prompt:y.value})},u=()=>{e||r()},f=g=>{g.key==="Enter"&&!e&&u()},m=()=>{o()},p=()=>{i()};return v.jsxs("div",{className:"flex gap-4 items-center",children:[v.jsx(Ld,{ref:s,className:"min-w-[500px]",value:t,onInput:l,onKeyUp:f,placeholder:"I want to repaint of..."}),v.jsx(wn,{size:"sm",onClick:u,disabled:e,onMouseEnter:m,onMouseLeave:p,children:"Paint"})]})};var zp={exports:{}};/** + * @license + * Lodash + * Copyright OpenJS Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */zp.exports;(function(e,t){(function(){var n,r="4.17.21",o=200,i="Unsupported core-js use. Try https://npms.io/search?q=ponyfill.",s="Expected a function",l="Invalid `variable` option passed into `_.template`",u="__lodash_hash_undefined__",f=500,m="__lodash_placeholder__",p=1,g=2,y=4,b=1,S=2,E=1,_=2,x=4,C=8,R=16,P=32,M=64,A=128,D=256,U=512,W=30,q="...",X=800,ae=16,V=1,F=2,N=3,ie=1/0,K=9007199254740991,Z=17976931348623157e292,H=NaN,se=4294967295,ce=se-1,Ve=se>>>1,Ue=[["ary",A],["bind",E],["bindKey",_],["curry",C],["curryRight",R],["flip",U],["partial",P],["partialRight",M],["rearg",D]],We="[object Arguments]",Oe="[object Array]",he="[object AsyncFunction]",xe="[object Boolean]",$e="[object Date]",Ae="[object DOMException]",Me="[object Error]",je="[object Function]",Mt="[object GeneratorFunction]",ct="[object Map]",Kt="[object Number]",Er="[object Null]",gt="[object Object]",Vs="[object Promise]",L="[object Proxy]",Q="[object RegExp]",J="[object Set]",we="[object String]",me="[object Symbol]",fe="[object Undefined]",Re="[object WeakMap]",ft="[object WeakSet]",ht="[object ArrayBuffer]",_n="[object DataView]",Cr="[object Float32Array]",Ni="[object Float64Array]",Co="[object Int8Array]",Vn="[object Int16Array]",Ba="[object Int32Array]",Di="[object Uint8Array]",Ws="[object Uint8ClampedArray]",Ii="[object Uint16Array]",Mc="[object Uint32Array]",bg=/\b__p \+= '';/g,Sg=/\b(__p \+=) '' \+/g,Jd=/(__e\(.*?\)|\b__t\)) \+\n'';/g,Oc=/&(?:amp|lt|gt|quot|#39);/g,Nc=/[&<>"']/g,Dc=RegExp(Oc.source),_g=RegExp(Nc.source),Ic=/<%-([\s\S]+?)%>/g,ef=/<%([\s\S]+?)%>/g,Lc=/<%=([\s\S]+?)%>/g,Eg=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Cg=/^\w*$/,$g=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,G=/[\\^$.*+?()[\]{}|]/g,Ye=RegExp(G.source),st=/^\s+/,Qr=/\s/,an=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,tf=/\{\n\/\* \[wrapped with (.+)\] \*/,aM=/,? & /,lM=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,cM=/[()=,{}\[\]\/\s]/,uM=/\\(\\)?/g,dM=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,hb=/\w*$/,fM=/^[-+]0x[0-9a-f]+$/i,hM=/^0b[01]+$/i,pM=/^\[object .+?Constructor\]$/,mM=/^0o[0-7]+$/i,gM=/^(?:0|[1-9]\d*)$/,vM=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,nf=/($^)/,yM=/['\n\r\u2028\u2029\\]/g,rf="\\ud800-\\udfff",wM="\\u0300-\\u036f",xM="\\ufe20-\\ufe2f",bM="\\u20d0-\\u20ff",pb=wM+xM+bM,mb="\\u2700-\\u27bf",gb="a-z\\xdf-\\xf6\\xf8-\\xff",SM="\\xac\\xb1\\xd7\\xf7",_M="\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf",EM="\\u2000-\\u206f",CM=" \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",vb="A-Z\\xc0-\\xd6\\xd8-\\xde",yb="\\ufe0e\\ufe0f",wb=SM+_M+EM+CM,Rg="['’]",$M="["+rf+"]",xb="["+wb+"]",of="["+pb+"]",bb="\\d+",RM="["+mb+"]",Sb="["+gb+"]",_b="[^"+rf+wb+bb+mb+gb+vb+"]",kg="\\ud83c[\\udffb-\\udfff]",kM="(?:"+of+"|"+kg+")",Eb="[^"+rf+"]",Tg="(?:\\ud83c[\\udde6-\\uddff]){2}",Pg="[\\ud800-\\udbff][\\udc00-\\udfff]",Ua="["+vb+"]",Cb="\\u200d",$b="(?:"+Sb+"|"+_b+")",TM="(?:"+Ua+"|"+_b+")",Rb="(?:"+Rg+"(?:d|ll|m|re|s|t|ve))?",kb="(?:"+Rg+"(?:D|LL|M|RE|S|T|VE))?",Tb=kM+"?",Pb="["+yb+"]?",PM="(?:"+Cb+"(?:"+[Eb,Tg,Pg].join("|")+")"+Pb+Tb+")*",AM="\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",MM="\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])",Ab=Pb+Tb+PM,OM="(?:"+[RM,Tg,Pg].join("|")+")"+Ab,NM="(?:"+[Eb+of+"?",of,Tg,Pg,$M].join("|")+")",DM=RegExp(Rg,"g"),IM=RegExp(of,"g"),Ag=RegExp(kg+"(?="+kg+")|"+NM+Ab,"g"),LM=RegExp([Ua+"?"+Sb+"+"+Rb+"(?="+[xb,Ua,"$"].join("|")+")",TM+"+"+kb+"(?="+[xb,Ua+$b,"$"].join("|")+")",Ua+"?"+$b+"+"+Rb,Ua+"+"+kb,MM,AM,bb,OM].join("|"),"g"),FM=RegExp("["+Cb+rf+pb+yb+"]"),jM=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,zM=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],BM=-1,Rt={};Rt[Cr]=Rt[Ni]=Rt[Co]=Rt[Vn]=Rt[Ba]=Rt[Di]=Rt[Ws]=Rt[Ii]=Rt[Mc]=!0,Rt[We]=Rt[Oe]=Rt[ht]=Rt[xe]=Rt[_n]=Rt[$e]=Rt[Me]=Rt[je]=Rt[ct]=Rt[Kt]=Rt[gt]=Rt[Q]=Rt[J]=Rt[we]=Rt[Re]=!1;var Et={};Et[We]=Et[Oe]=Et[ht]=Et[_n]=Et[xe]=Et[$e]=Et[Cr]=Et[Ni]=Et[Co]=Et[Vn]=Et[Ba]=Et[ct]=Et[Kt]=Et[gt]=Et[Q]=Et[J]=Et[we]=Et[me]=Et[Di]=Et[Ws]=Et[Ii]=Et[Mc]=!0,Et[Me]=Et[je]=Et[Re]=!1;var UM={À:"A",Á:"A",Â:"A",Ã:"A",Ä:"A",Å:"A",à:"a",á:"a",â:"a",ã:"a",ä:"a",å:"a",Ç:"C",ç:"c",Ð:"D",ð:"d",È:"E",É:"E",Ê:"E",Ë:"E",è:"e",é:"e",ê:"e",ë:"e",Ì:"I",Í:"I",Î:"I",Ï:"I",ì:"i",í:"i",î:"i",ï:"i",Ñ:"N",ñ:"n",Ò:"O",Ó:"O",Ô:"O",Õ:"O",Ö:"O",Ø:"O",ò:"o",ó:"o",ô:"o",õ:"o",ö:"o",ø:"o",Ù:"U",Ú:"U",Û:"U",Ü:"U",ù:"u",ú:"u",û:"u",ü:"u",Ý:"Y",ý:"y",ÿ:"y",Æ:"Ae",æ:"ae",Þ:"Th",þ:"th",ß:"ss",Ā:"A",Ă:"A",Ą:"A",ā:"a",ă:"a",ą:"a",Ć:"C",Ĉ:"C",Ċ:"C",Č:"C",ć:"c",ĉ:"c",ċ:"c",č:"c",Ď:"D",Đ:"D",ď:"d",đ:"d",Ē:"E",Ĕ:"E",Ė:"E",Ę:"E",Ě:"E",ē:"e",ĕ:"e",ė:"e",ę:"e",ě:"e",Ĝ:"G",Ğ:"G",Ġ:"G",Ģ:"G",ĝ:"g",ğ:"g",ġ:"g",ģ:"g",Ĥ:"H",Ħ:"H",ĥ:"h",ħ:"h",Ĩ:"I",Ī:"I",Ĭ:"I",Į:"I",İ:"I",ĩ:"i",ī:"i",ĭ:"i",į:"i",ı:"i",Ĵ:"J",ĵ:"j",Ķ:"K",ķ:"k",ĸ:"k",Ĺ:"L",Ļ:"L",Ľ:"L",Ŀ:"L",Ł:"L",ĺ:"l",ļ:"l",ľ:"l",ŀ:"l",ł:"l",Ń:"N",Ņ:"N",Ň:"N",Ŋ:"N",ń:"n",ņ:"n",ň:"n",ŋ:"n",Ō:"O",Ŏ:"O",Ő:"O",ō:"o",ŏ:"o",ő:"o",Ŕ:"R",Ŗ:"R",Ř:"R",ŕ:"r",ŗ:"r",ř:"r",Ś:"S",Ŝ:"S",Ş:"S",Š:"S",ś:"s",ŝ:"s",ş:"s",š:"s",Ţ:"T",Ť:"T",Ŧ:"T",ţ:"t",ť:"t",ŧ:"t",Ũ:"U",Ū:"U",Ŭ:"U",Ů:"U",Ű:"U",Ų:"U",ũ:"u",ū:"u",ŭ:"u",ů:"u",ű:"u",ų:"u",Ŵ:"W",ŵ:"w",Ŷ:"Y",ŷ:"y",Ÿ:"Y",Ź:"Z",Ż:"Z",Ž:"Z",ź:"z",ż:"z",ž:"z",IJ:"IJ",ij:"ij",Œ:"Oe",œ:"oe",ʼn:"'n",ſ:"s"},VM={"&":"&","<":"<",">":">",'"':""","'":"'"},WM={"&":"&","<":"<",">":">",""":'"',"'":"'"},HM={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},KM=parseFloat,GM=parseInt,Mb=typeof Jc=="object"&&Jc&&Jc.Object===Object&&Jc,YM=typeof self=="object"&&self&&self.Object===Object&&self,fn=Mb||YM||Function("return this")(),Mg=t&&!t.nodeType&&t,Hs=Mg&&!0&&e&&!e.nodeType&&e,Ob=Hs&&Hs.exports===Mg,Og=Ob&&Mb.process,$r=function(){try{var j=Hs&&Hs.require&&Hs.require("util").types;return j||Og&&Og.binding&&Og.binding("util")}catch{}}(),Nb=$r&&$r.isArrayBuffer,Db=$r&&$r.isDate,Ib=$r&&$r.isMap,Lb=$r&&$r.isRegExp,Fb=$r&&$r.isSet,jb=$r&&$r.isTypedArray;function or(j,te,ee){switch(ee.length){case 0:return j.call(te);case 1:return j.call(te,ee[0]);case 2:return j.call(te,ee[0],ee[1]);case 3:return j.call(te,ee[0],ee[1],ee[2])}return j.apply(te,ee)}function XM(j,te,ee,Se){for(var Ke=-1,pt=j==null?0:j.length;++Ke-1}function Ng(j,te,ee){for(var Se=-1,Ke=j==null?0:j.length;++Se-1;);return ee}function Gb(j,te){for(var ee=j.length;ee--&&Va(te,j[ee],0)>-1;);return ee}function oO(j,te){for(var ee=j.length,Se=0;ee--;)j[ee]===te&&++Se;return Se}var iO=Fg(UM),sO=Fg(VM);function aO(j){return"\\"+HM[j]}function lO(j,te){return j==null?n:j[te]}function Wa(j){return FM.test(j)}function cO(j){return jM.test(j)}function uO(j){for(var te,ee=[];!(te=j.next()).done;)ee.push(te.value);return ee}function Ug(j){var te=-1,ee=Array(j.size);return j.forEach(function(Se,Ke){ee[++te]=[Ke,Se]}),ee}function Yb(j,te){return function(ee){return j(te(ee))}}function ji(j,te){for(var ee=-1,Se=j.length,Ke=0,pt=[];++ee-1}function qO(a,c){var h=this.__data__,w=_f(h,a);return w<0?(++this.size,h.push([a,c])):h[w][1]=c,this}ti.prototype.clear=GO,ti.prototype.delete=YO,ti.prototype.get=XO,ti.prototype.has=ZO,ti.prototype.set=qO;function ni(a){var c=-1,h=a==null?0:a.length;for(this.clear();++c=c?a:c)),a}function Pr(a,c,h,w,$,T){var O,I=c&p,B=c&g,ne=c&y;if(h&&(O=$?h(a,w,$,T):h(a)),O!==n)return O;if(!It(a))return a;var re=Ge(a);if(re){if(O=tN(a),!I)return Wn(a,O)}else{var le=Cn(a),ge=le==je||le==Mt;if(Hi(a))return PS(a,I);if(le==gt||le==We||ge&&!$){if(O=B||ge?{}:XS(a),!I)return B?W6(a,h6(O,a)):V6(a,sS(O,a))}else{if(!Et[le])return $?a:{};O=nN(a,le,I)}}T||(T=new eo);var ke=T.get(a);if(ke)return ke;T.set(a,O),E_(a)?a.forEach(function(Le){O.add(Pr(Le,c,h,Le,a,T))}):S_(a)&&a.forEach(function(Le,nt){O.set(nt,Pr(Le,c,h,nt,a,T))});var Ie=ne?B?pv:hv:B?Kn:ln,Qe=re?n:Ie(a);return Rr(Qe||a,function(Le,nt){Qe&&(nt=Le,Le=a[nt]),Wc(O,nt,Pr(Le,c,h,nt,a,T))}),O}function p6(a){var c=ln(a);return function(h){return aS(h,a,c)}}function aS(a,c,h){var w=h.length;if(a==null)return!w;for(a=St(a);w--;){var $=h[w],T=c[$],O=a[$];if(O===n&&!($ in a)||!T(O))return!1}return!0}function lS(a,c,h){if(typeof a!="function")throw new kr(s);return qc(function(){a.apply(n,h)},c)}function Hc(a,c,h,w){var $=-1,T=sf,O=!0,I=a.length,B=[],ne=c.length;if(!I)return B;h&&(c=Ot(c,ir(h))),w?(T=Ng,O=!1):c.length>=o&&(T=Fc,O=!1,c=new Ys(c));e:for(;++$$?0:$+h),w=w===n||w>$?$:qe(w),w<0&&(w+=$),w=h>w?0:$_(w);h0&&h(I)?c>1?hn(I,c-1,h,w,$):Fi($,I):w||($[$.length]=I)}return $}var Xg=IS(),dS=IS(!0);function $o(a,c){return a&&Xg(a,c,ln)}function Zg(a,c){return a&&dS(a,c,ln)}function Cf(a,c){return Li(c,function(h){return ai(a[h])})}function Zs(a,c){c=Vi(c,a);for(var h=0,w=c.length;a!=null&&hc}function v6(a,c){return a!=null&&yt.call(a,c)}function y6(a,c){return a!=null&&c in St(a)}function w6(a,c,h){return a>=En(c,h)&&a=120&&re.length>=120)?new Ys(O&&re):n}re=a[0];var le=-1,ge=I[0];e:for(;++le<$&&ne.length-1;)I!==a&&gf.call(I,B,1),gf.call(a,B,1);return a}function SS(a,c){for(var h=a?c.length:0,w=h-1;h--;){var $=c[h];if(h==w||$!==T){var T=$;si($)?gf.call(a,$,1):sv(a,$)}}return a}function rv(a,c){return a+wf(nS()*(c-a+1))}function M6(a,c,h,w){for(var $=-1,T=tn(yf((c-a)/(h||1)),0),O=ee(T);T--;)O[w?T:++$]=a,a+=h;return O}function ov(a,c){var h="";if(!a||c<1||c>K)return h;do c%2&&(h+=a),c=wf(c/2),c&&(a+=a);while(c);return h}function et(a,c){return bv(QS(a,c,Gn),a+"")}function O6(a){return iS(tl(a))}function N6(a,c){var h=tl(a);return If(h,Xs(c,0,h.length))}function Yc(a,c,h,w){if(!It(a))return a;c=Vi(c,a);for(var $=-1,T=c.length,O=T-1,I=a;I!=null&&++$$?0:$+c),h=h>$?$:h,h<0&&(h+=$),$=c>h?0:h-c>>>0,c>>>=0;for(var T=ee($);++w<$;)T[w]=a[w+c];return T}function L6(a,c){var h;return Bi(a,function(w,$,T){return h=c(w,$,T),!h}),!!h}function Rf(a,c,h){var w=0,$=a==null?w:a.length;if(typeof c=="number"&&c===c&&$<=Ve){for(;w<$;){var T=w+$>>>1,O=a[T];O!==null&&!ar(O)&&(h?O<=c:O=o){var ne=c?null:Y6(a);if(ne)return lf(ne);O=!1,$=Fc,B=new Ys}else B=c?[]:I;e:for(;++w=w?a:Ar(a,c,h)}var TS=CO||function(a){return fn.clearTimeout(a)};function PS(a,c){if(c)return a.slice();var h=a.length,w=qb?qb(h):new a.constructor(h);return a.copy(w),w}function uv(a){var c=new a.constructor(a.byteLength);return new pf(c).set(new pf(a)),c}function j6(a,c){var h=c?uv(a.buffer):a.buffer;return new a.constructor(h,a.byteOffset,a.byteLength)}function z6(a){var c=new a.constructor(a.source,hb.exec(a));return c.lastIndex=a.lastIndex,c}function B6(a){return Vc?St(Vc.call(a)):{}}function AS(a,c){var h=c?uv(a.buffer):a.buffer;return new a.constructor(h,a.byteOffset,a.length)}function MS(a,c){if(a!==c){var h=a!==n,w=a===null,$=a===a,T=ar(a),O=c!==n,I=c===null,B=c===c,ne=ar(c);if(!I&&!ne&&!T&&a>c||T&&O&&B&&!I&&!ne||w&&O&&B||!h&&B||!$)return 1;if(!w&&!T&&!ne&&a=I)return B;var ne=h[w];return B*(ne=="desc"?-1:1)}}return a.index-c.index}function OS(a,c,h,w){for(var $=-1,T=a.length,O=h.length,I=-1,B=c.length,ne=tn(T-O,0),re=ee(B+ne),le=!w;++I1?h[$-1]:n,O=$>2?h[2]:n;for(T=a.length>3&&typeof T=="function"?($--,T):n,O&&Nn(h[0],h[1],O)&&(T=$<3?n:T,$=1),c=St(c);++w<$;){var I=h[w];I&&a(c,I,w,T)}return c})}function DS(a,c){return function(h,w){if(h==null)return h;if(!Hn(h))return a(h,w);for(var $=h.length,T=c?$:-1,O=St(h);(c?T--:++T<$)&&w(O[T],T,O)!==!1;);return h}}function IS(a){return function(c,h,w){for(var $=-1,T=St(c),O=w(c),I=O.length;I--;){var B=O[a?I:++$];if(h(T[B],B,T)===!1)break}return c}}function H6(a,c,h){var w=c&E,$=Xc(a);function T(){var O=this&&this!==fn&&this instanceof T?$:a;return O.apply(w?h:this,arguments)}return T}function LS(a){return function(c){c=vt(c);var h=Wa(c)?Jr(c):n,w=h?h[0]:c.charAt(0),$=h?Wi(h,1).join(""):c.slice(1);return w[a]()+$}}function Qa(a){return function(c){return Dg(D_(N_(c).replace(DM,"")),a,"")}}function Xc(a){return function(){var c=arguments;switch(c.length){case 0:return new a;case 1:return new a(c[0]);case 2:return new a(c[0],c[1]);case 3:return new a(c[0],c[1],c[2]);case 4:return new a(c[0],c[1],c[2],c[3]);case 5:return new a(c[0],c[1],c[2],c[3],c[4]);case 6:return new a(c[0],c[1],c[2],c[3],c[4],c[5]);case 7:return new a(c[0],c[1],c[2],c[3],c[4],c[5],c[6])}var h=Za(a.prototype),w=a.apply(h,c);return It(w)?w:h}}function K6(a,c,h){var w=Xc(a);function $(){for(var T=arguments.length,O=ee(T),I=T,B=Ja($);I--;)O[I]=arguments[I];var ne=T<3&&O[0]!==B&&O[T-1]!==B?[]:ji(O,B);if(T-=ne.length,T-1?$[T?c[O]:O]:n}}function jS(a){return ii(function(c){var h=c.length,w=h,$=Tr.prototype.thru;for(a&&c.reverse();w--;){var T=c[w];if(typeof T!="function")throw new kr(s);if($&&!O&&Nf(T)=="wrapper")var O=new Tr([],!0)}for(w=O?w:h;++w1&&at.reverse(),re&&BI))return!1;var ne=T.get(a),re=T.get(c);if(ne&&re)return ne==c&&re==a;var le=-1,ge=!0,ke=h&S?new Ys:n;for(T.set(a,c),T.set(c,a);++le1?"& ":"")+c[w],c=c.join(h>2?", ":" "),a.replace(an,`{ +/* [wrapped with `+c+`] */ +`)}function oN(a){return Ge(a)||Js(a)||!!(eS&&a&&a[eS])}function si(a,c){var h=typeof a;return c=c??K,!!c&&(h=="number"||h!="symbol"&&gM.test(a))&&a>-1&&a%1==0&&a0){if(++c>=X)return arguments[0]}else c=0;return a.apply(n,arguments)}}function If(a,c){var h=-1,w=a.length,$=w-1;for(c=c===n?w:c;++h1?a[c-1]:n;return h=typeof h=="function"?(a.pop(),h):n,u_(a,h)});function d_(a){var c=k(a);return c.__chain__=!0,c}function m7(a,c){return c(a),a}function Lf(a,c){return c(a)}var g7=ii(function(a){var c=a.length,h=c?a[0]:0,w=this.__wrapped__,$=function(T){return Yg(T,a)};return c>1||this.__actions__.length||!(w instanceof ot)||!si(h)?this.thru($):(w=w.slice(h,+h+(c?1:0)),w.__actions__.push({func:Lf,args:[$],thisArg:n}),new Tr(w,this.__chain__).thru(function(T){return c&&!T.length&&T.push(n),T}))});function v7(){return d_(this)}function y7(){return new Tr(this.value(),this.__chain__)}function w7(){this.__values__===n&&(this.__values__=C_(this.value()));var a=this.__index__>=this.__values__.length,c=a?n:this.__values__[this.__index__++];return{done:a,value:c}}function x7(){return this}function b7(a){for(var c,h=this;h instanceof Sf;){var w=o_(h);w.__index__=0,w.__values__=n,c?$.__wrapped__=w:c=w;var $=w;h=h.__wrapped__}return $.__wrapped__=a,c}function S7(){var a=this.__wrapped__;if(a instanceof ot){var c=a;return this.__actions__.length&&(c=new ot(this)),c=c.reverse(),c.__actions__.push({func:Lf,args:[Sv],thisArg:n}),new Tr(c,this.__chain__)}return this.thru(Sv)}function _7(){return RS(this.__wrapped__,this.__actions__)}var E7=Tf(function(a,c,h){yt.call(a,h)?++a[h]:ri(a,h,1)});function C7(a,c,h){var w=Ge(a)?zb:m6;return h&&Nn(a,c,h)&&(c=n),w(a,De(c,3))}function $7(a,c){var h=Ge(a)?Li:uS;return h(a,De(c,3))}var R7=FS(i_),k7=FS(s_);function T7(a,c){return hn(Ff(a,c),1)}function P7(a,c){return hn(Ff(a,c),ie)}function A7(a,c,h){return h=h===n?1:qe(h),hn(Ff(a,c),h)}function f_(a,c){var h=Ge(a)?Rr:Bi;return h(a,De(c,3))}function h_(a,c){var h=Ge(a)?ZM:cS;return h(a,De(c,3))}var M7=Tf(function(a,c,h){yt.call(a,h)?a[h].push(c):ri(a,h,[c])});function O7(a,c,h,w){a=Hn(a)?a:tl(a),h=h&&!w?qe(h):0;var $=a.length;return h<0&&(h=tn($+h,0)),Vf(a)?h<=$&&a.indexOf(c,h)>-1:!!$&&Va(a,c,h)>-1}var N7=et(function(a,c,h){var w=-1,$=typeof c=="function",T=Hn(a)?ee(a.length):[];return Bi(a,function(O){T[++w]=$?or(c,O,h):Kc(O,c,h)}),T}),D7=Tf(function(a,c,h){ri(a,h,c)});function Ff(a,c){var h=Ge(a)?Ot:gS;return h(a,De(c,3))}function I7(a,c,h,w){return a==null?[]:(Ge(c)||(c=c==null?[]:[c]),h=w?n:h,Ge(h)||(h=h==null?[]:[h]),xS(a,c,h))}var L7=Tf(function(a,c,h){a[h?0:1].push(c)},function(){return[[],[]]});function F7(a,c,h){var w=Ge(a)?Dg:Wb,$=arguments.length<3;return w(a,De(c,4),h,$,Bi)}function j7(a,c,h){var w=Ge(a)?qM:Wb,$=arguments.length<3;return w(a,De(c,4),h,$,cS)}function z7(a,c){var h=Ge(a)?Li:uS;return h(a,Bf(De(c,3)))}function B7(a){var c=Ge(a)?iS:O6;return c(a)}function U7(a,c,h){(h?Nn(a,c,h):c===n)?c=1:c=qe(c);var w=Ge(a)?u6:N6;return w(a,c)}function V7(a){var c=Ge(a)?d6:I6;return c(a)}function W7(a){if(a==null)return 0;if(Hn(a))return Vf(a)?Ha(a):a.length;var c=Cn(a);return c==ct||c==J?a.size:ev(a).length}function H7(a,c,h){var w=Ge(a)?Ig:L6;return h&&Nn(a,c,h)&&(c=n),w(a,De(c,3))}var K7=et(function(a,c){if(a==null)return[];var h=c.length;return h>1&&Nn(a,c[0],c[1])?c=[]:h>2&&Nn(c[0],c[1],c[2])&&(c=[c[0]]),xS(a,hn(c,1),[])}),jf=$O||function(){return fn.Date.now()};function G7(a,c){if(typeof c!="function")throw new kr(s);return a=qe(a),function(){if(--a<1)return c.apply(this,arguments)}}function p_(a,c,h){return c=h?n:c,c=a&&c==null?a.length:c,oi(a,A,n,n,n,n,c)}function m_(a,c){var h;if(typeof c!="function")throw new kr(s);return a=qe(a),function(){return--a>0&&(h=c.apply(this,arguments)),a<=1&&(c=n),h}}var Ev=et(function(a,c,h){var w=E;if(h.length){var $=ji(h,Ja(Ev));w|=P}return oi(a,w,c,h,$)}),g_=et(function(a,c,h){var w=E|_;if(h.length){var $=ji(h,Ja(g_));w|=P}return oi(c,w,a,h,$)});function v_(a,c,h){c=h?n:c;var w=oi(a,C,n,n,n,n,n,c);return w.placeholder=v_.placeholder,w}function y_(a,c,h){c=h?n:c;var w=oi(a,R,n,n,n,n,n,c);return w.placeholder=y_.placeholder,w}function w_(a,c,h){var w,$,T,O,I,B,ne=0,re=!1,le=!1,ge=!0;if(typeof a!="function")throw new kr(s);c=Or(c)||0,It(h)&&(re=!!h.leading,le="maxWait"in h,T=le?tn(Or(h.maxWait)||0,c):T,ge="trailing"in h?!!h.trailing:ge);function ke(Yt){var no=w,ci=$;return w=$=n,ne=Yt,O=a.apply(ci,no),O}function Ie(Yt){return ne=Yt,I=qc(nt,c),re?ke(Yt):O}function Qe(Yt){var no=Yt-B,ci=Yt-ne,F_=c-no;return le?En(F_,T-ci):F_}function Le(Yt){var no=Yt-B,ci=Yt-ne;return B===n||no>=c||no<0||le&&ci>=T}function nt(){var Yt=jf();if(Le(Yt))return at(Yt);I=qc(nt,Qe(Yt))}function at(Yt){return I=n,ge&&w?ke(Yt):(w=$=n,O)}function lr(){I!==n&&TS(I),ne=0,w=B=$=I=n}function Dn(){return I===n?O:at(jf())}function cr(){var Yt=jf(),no=Le(Yt);if(w=arguments,$=this,B=Yt,no){if(I===n)return Ie(B);if(le)return TS(I),I=qc(nt,c),ke(B)}return I===n&&(I=qc(nt,c)),O}return cr.cancel=lr,cr.flush=Dn,cr}var Y7=et(function(a,c){return lS(a,1,c)}),X7=et(function(a,c,h){return lS(a,Or(c)||0,h)});function Z7(a){return oi(a,U)}function zf(a,c){if(typeof a!="function"||c!=null&&typeof c!="function")throw new kr(s);var h=function(){var w=arguments,$=c?c.apply(this,w):w[0],T=h.cache;if(T.has($))return T.get($);var O=a.apply(this,w);return h.cache=T.set($,O)||T,O};return h.cache=new(zf.Cache||ni),h}zf.Cache=ni;function Bf(a){if(typeof a!="function")throw new kr(s);return function(){var c=arguments;switch(c.length){case 0:return!a.call(this);case 1:return!a.call(this,c[0]);case 2:return!a.call(this,c[0],c[1]);case 3:return!a.call(this,c[0],c[1],c[2])}return!a.apply(this,c)}}function q7(a){return m_(2,a)}var Q7=F6(function(a,c){c=c.length==1&&Ge(c[0])?Ot(c[0],ir(De())):Ot(hn(c,1),ir(De()));var h=c.length;return et(function(w){for(var $=-1,T=En(w.length,h);++$=c}),Js=hS(function(){return arguments}())?hS:function(a){return Bt(a)&&yt.call(a,"callee")&&!Jb.call(a,"callee")},Ge=ee.isArray,h4=Nb?ir(Nb):b6;function Hn(a){return a!=null&&Uf(a.length)&&!ai(a)}function Gt(a){return Bt(a)&&Hn(a)}function p4(a){return a===!0||a===!1||Bt(a)&&On(a)==xe}var Hi=kO||Iv,m4=Db?ir(Db):S6;function g4(a){return Bt(a)&&a.nodeType===1&&!Qc(a)}function v4(a){if(a==null)return!0;if(Hn(a)&&(Ge(a)||typeof a=="string"||typeof a.splice=="function"||Hi(a)||el(a)||Js(a)))return!a.length;var c=Cn(a);if(c==ct||c==J)return!a.size;if(Zc(a))return!ev(a).length;for(var h in a)if(yt.call(a,h))return!1;return!0}function y4(a,c){return Gc(a,c)}function w4(a,c,h){h=typeof h=="function"?h:n;var w=h?h(a,c):n;return w===n?Gc(a,c,n,h):!!w}function $v(a){if(!Bt(a))return!1;var c=On(a);return c==Me||c==Ae||typeof a.message=="string"&&typeof a.name=="string"&&!Qc(a)}function x4(a){return typeof a=="number"&&tS(a)}function ai(a){if(!It(a))return!1;var c=On(a);return c==je||c==Mt||c==he||c==L}function b_(a){return typeof a=="number"&&a==qe(a)}function Uf(a){return typeof a=="number"&&a>-1&&a%1==0&&a<=K}function It(a){var c=typeof a;return a!=null&&(c=="object"||c=="function")}function Bt(a){return a!=null&&typeof a=="object"}var S_=Ib?ir(Ib):E6;function b4(a,c){return a===c||Jg(a,c,gv(c))}function S4(a,c,h){return h=typeof h=="function"?h:n,Jg(a,c,gv(c),h)}function _4(a){return __(a)&&a!=+a}function E4(a){if(aN(a))throw new Ke(i);return pS(a)}function C4(a){return a===null}function $4(a){return a==null}function __(a){return typeof a=="number"||Bt(a)&&On(a)==Kt}function Qc(a){if(!Bt(a)||On(a)!=gt)return!1;var c=mf(a);if(c===null)return!0;var h=yt.call(c,"constructor")&&c.constructor;return typeof h=="function"&&h instanceof h&&df.call(h)==SO}var Rv=Lb?ir(Lb):C6;function R4(a){return b_(a)&&a>=-K&&a<=K}var E_=Fb?ir(Fb):$6;function Vf(a){return typeof a=="string"||!Ge(a)&&Bt(a)&&On(a)==we}function ar(a){return typeof a=="symbol"||Bt(a)&&On(a)==me}var el=jb?ir(jb):R6;function k4(a){return a===n}function T4(a){return Bt(a)&&Cn(a)==Re}function P4(a){return Bt(a)&&On(a)==ft}var A4=Of(tv),M4=Of(function(a,c){return a<=c});function C_(a){if(!a)return[];if(Hn(a))return Vf(a)?Jr(a):Wn(a);if(jc&&a[jc])return uO(a[jc]());var c=Cn(a),h=c==ct?Ug:c==J?lf:tl;return h(a)}function li(a){if(!a)return a===0?a:0;if(a=Or(a),a===ie||a===-ie){var c=a<0?-1:1;return c*Z}return a===a?a:0}function qe(a){var c=li(a),h=c%1;return c===c?h?c-h:c:0}function $_(a){return a?Xs(qe(a),0,se):0}function Or(a){if(typeof a=="number")return a;if(ar(a))return H;if(It(a)){var c=typeof a.valueOf=="function"?a.valueOf():a;a=It(c)?c+"":c}if(typeof a!="string")return a===0?a:+a;a=Hb(a);var h=hM.test(a);return h||mM.test(a)?GM(a.slice(2),h?2:8):fM.test(a)?H:+a}function R_(a){return Ro(a,Kn(a))}function O4(a){return a?Xs(qe(a),-K,K):a===0?a:0}function vt(a){return a==null?"":sr(a)}var N4=qa(function(a,c){if(Zc(c)||Hn(c)){Ro(c,ln(c),a);return}for(var h in c)yt.call(c,h)&&Wc(a,h,c[h])}),k_=qa(function(a,c){Ro(c,Kn(c),a)}),Wf=qa(function(a,c,h,w){Ro(c,Kn(c),a,w)}),D4=qa(function(a,c,h,w){Ro(c,ln(c),a,w)}),I4=ii(Yg);function L4(a,c){var h=Za(a);return c==null?h:sS(h,c)}var F4=et(function(a,c){a=St(a);var h=-1,w=c.length,$=w>2?c[2]:n;for($&&Nn(c[0],c[1],$)&&(w=1);++h1),T}),Ro(a,pv(a),h),w&&(h=Pr(h,p|g|y,X6));for(var $=c.length;$--;)sv(h,c[$]);return h});function n8(a,c){return P_(a,Bf(De(c)))}var r8=ii(function(a,c){return a==null?{}:P6(a,c)});function P_(a,c){if(a==null)return{};var h=Ot(pv(a),function(w){return[w]});return c=De(c),bS(a,h,function(w,$){return c(w,$[0])})}function o8(a,c,h){c=Vi(c,a);var w=-1,$=c.length;for($||($=1,a=n);++w<$;){var T=a==null?n:a[ko(c[w])];T===n&&(w=$,T=h),a=ai(T)?T.call(a):T}return a}function i8(a,c,h){return a==null?a:Yc(a,c,h)}function s8(a,c,h,w){return w=typeof w=="function"?w:n,a==null?a:Yc(a,c,h,w)}var A_=VS(ln),M_=VS(Kn);function a8(a,c,h){var w=Ge(a),$=w||Hi(a)||el(a);if(c=De(c,4),h==null){var T=a&&a.constructor;$?h=w?new T:[]:It(a)?h=ai(T)?Za(mf(a)):{}:h={}}return($?Rr:$o)(a,function(O,I,B){return c(h,O,I,B)}),h}function l8(a,c){return a==null?!0:sv(a,c)}function c8(a,c,h){return a==null?a:$S(a,c,cv(h))}function u8(a,c,h,w){return w=typeof w=="function"?w:n,a==null?a:$S(a,c,cv(h),w)}function tl(a){return a==null?[]:Bg(a,ln(a))}function d8(a){return a==null?[]:Bg(a,Kn(a))}function f8(a,c,h){return h===n&&(h=c,c=n),h!==n&&(h=Or(h),h=h===h?h:0),c!==n&&(c=Or(c),c=c===c?c:0),Xs(Or(a),c,h)}function h8(a,c,h){return c=li(c),h===n?(h=c,c=0):h=li(h),a=Or(a),w6(a,c,h)}function p8(a,c,h){if(h&&typeof h!="boolean"&&Nn(a,c,h)&&(c=h=n),h===n&&(typeof c=="boolean"?(h=c,c=n):typeof a=="boolean"&&(h=a,a=n)),a===n&&c===n?(a=0,c=1):(a=li(a),c===n?(c=a,a=0):c=li(c)),a>c){var w=a;a=c,c=w}if(h||a%1||c%1){var $=nS();return En(a+$*(c-a+KM("1e-"+(($+"").length-1))),c)}return rv(a,c)}var m8=Qa(function(a,c,h){return c=c.toLowerCase(),a+(h?O_(c):c)});function O_(a){return Pv(vt(a).toLowerCase())}function N_(a){return a=vt(a),a&&a.replace(vM,iO).replace(IM,"")}function g8(a,c,h){a=vt(a),c=sr(c);var w=a.length;h=h===n?w:Xs(qe(h),0,w);var $=h;return h-=c.length,h>=0&&a.slice(h,$)==c}function v8(a){return a=vt(a),a&&_g.test(a)?a.replace(Nc,sO):a}function y8(a){return a=vt(a),a&&Ye.test(a)?a.replace(G,"\\$&"):a}var w8=Qa(function(a,c,h){return a+(h?"-":"")+c.toLowerCase()}),x8=Qa(function(a,c,h){return a+(h?" ":"")+c.toLowerCase()}),b8=LS("toLowerCase");function S8(a,c,h){a=vt(a),c=qe(c);var w=c?Ha(a):0;if(!c||w>=c)return a;var $=(c-w)/2;return Mf(wf($),h)+a+Mf(yf($),h)}function _8(a,c,h){a=vt(a),c=qe(c);var w=c?Ha(a):0;return c&&w>>0,h?(a=vt(a),a&&(typeof c=="string"||c!=null&&!Rv(c))&&(c=sr(c),!c&&Wa(a))?Wi(Jr(a),0,h):a.split(c,h)):[]}var P8=Qa(function(a,c,h){return a+(h?" ":"")+Pv(c)});function A8(a,c,h){return a=vt(a),h=h==null?0:Xs(qe(h),0,a.length),c=sr(c),a.slice(h,h+c.length)==c}function M8(a,c,h){var w=k.templateSettings;h&&Nn(a,c,h)&&(c=n),a=vt(a),c=Wf({},c,w,WS);var $=Wf({},c.imports,w.imports,WS),T=ln($),O=Bg($,T),I,B,ne=0,re=c.interpolate||nf,le="__p += '",ge=Vg((c.escape||nf).source+"|"+re.source+"|"+(re===Lc?dM:nf).source+"|"+(c.evaluate||nf).source+"|$","g"),ke="//# sourceURL="+(yt.call(c,"sourceURL")?(c.sourceURL+"").replace(/\s/g," "):"lodash.templateSources["+ ++BM+"]")+` +`;a.replace(ge,function(Le,nt,at,lr,Dn,cr){return at||(at=lr),le+=a.slice(ne,cr).replace(yM,aO),nt&&(I=!0,le+=`' + +__e(`+nt+`) + +'`),Dn&&(B=!0,le+=`'; +`+Dn+`; +__p += '`),at&&(le+=`' + +((__t = (`+at+`)) == null ? '' : __t) + +'`),ne=cr+Le.length,Le}),le+=`'; +`;var Ie=yt.call(c,"variable")&&c.variable;if(!Ie)le=`with (obj) { +`+le+` +} +`;else if(cM.test(Ie))throw new Ke(l);le=(B?le.replace(bg,""):le).replace(Sg,"$1").replace(Jd,"$1;"),le="function("+(Ie||"obj")+`) { +`+(Ie?"":`obj || (obj = {}); +`)+"var __t, __p = ''"+(I?", __e = _.escape":"")+(B?`, __j = Array.prototype.join; +function print() { __p += __j.call(arguments, '') } +`:`; +`)+le+`return __p +}`;var Qe=I_(function(){return pt(T,ke+"return "+le).apply(n,O)});if(Qe.source=le,$v(Qe))throw Qe;return Qe}function O8(a){return vt(a).toLowerCase()}function N8(a){return vt(a).toUpperCase()}function D8(a,c,h){if(a=vt(a),a&&(h||c===n))return Hb(a);if(!a||!(c=sr(c)))return a;var w=Jr(a),$=Jr(c),T=Kb(w,$),O=Gb(w,$)+1;return Wi(w,T,O).join("")}function I8(a,c,h){if(a=vt(a),a&&(h||c===n))return a.slice(0,Xb(a)+1);if(!a||!(c=sr(c)))return a;var w=Jr(a),$=Gb(w,Jr(c))+1;return Wi(w,0,$).join("")}function L8(a,c,h){if(a=vt(a),a&&(h||c===n))return a.replace(st,"");if(!a||!(c=sr(c)))return a;var w=Jr(a),$=Kb(w,Jr(c));return Wi(w,$).join("")}function F8(a,c){var h=W,w=q;if(It(c)){var $="separator"in c?c.separator:$;h="length"in c?qe(c.length):h,w="omission"in c?sr(c.omission):w}a=vt(a);var T=a.length;if(Wa(a)){var O=Jr(a);T=O.length}if(h>=T)return a;var I=h-Ha(w);if(I<1)return w;var B=O?Wi(O,0,I).join(""):a.slice(0,I);if($===n)return B+w;if(O&&(I+=B.length-I),Rv($)){if(a.slice(I).search($)){var ne,re=B;for($.global||($=Vg($.source,vt(hb.exec($))+"g")),$.lastIndex=0;ne=$.exec(re);)var le=ne.index;B=B.slice(0,le===n?I:le)}}else if(a.indexOf(sr($),I)!=I){var ge=B.lastIndexOf($);ge>-1&&(B=B.slice(0,ge))}return B+w}function j8(a){return a=vt(a),a&&Dc.test(a)?a.replace(Oc,pO):a}var z8=Qa(function(a,c,h){return a+(h?" ":"")+c.toUpperCase()}),Pv=LS("toUpperCase");function D_(a,c,h){return a=vt(a),c=h?n:c,c===n?cO(a)?vO(a):eO(a):a.match(c)||[]}var I_=et(function(a,c){try{return or(a,n,c)}catch(h){return $v(h)?h:new Ke(h)}}),B8=ii(function(a,c){return Rr(c,function(h){h=ko(h),ri(a,h,Ev(a[h],a))}),a});function U8(a){var c=a==null?0:a.length,h=De();return a=c?Ot(a,function(w){if(typeof w[1]!="function")throw new kr(s);return[h(w[0]),w[1]]}):[],et(function(w){for(var $=-1;++$K)return[];var h=se,w=En(a,se);c=De(c),a-=se;for(var $=zg(w,c);++h0||c<0)?new ot(h):(a<0?h=h.takeRight(-a):a&&(h=h.drop(a)),c!==n&&(c=qe(c),h=c<0?h.dropRight(-c):h.take(c-a)),h)},ot.prototype.takeRightWhile=function(a){return this.reverse().takeWhile(a).reverse()},ot.prototype.toArray=function(){return this.take(se)},$o(ot.prototype,function(a,c){var h=/^(?:filter|find|map|reject)|While$/.test(c),w=/^(?:head|last)$/.test(c),$=k[w?"take"+(c=="last"?"Right":""):c],T=w||/^find/.test(c);$&&(k.prototype[c]=function(){var O=this.__wrapped__,I=w?[1]:arguments,B=O instanceof ot,ne=I[0],re=B||Ge(O),le=function(nt){var at=$.apply(k,Fi([nt],I));return w&&ge?at[0]:at};re&&h&&typeof ne=="function"&&ne.length!=1&&(B=re=!1);var ge=this.__chain__,ke=!!this.__actions__.length,Ie=T&&!ge,Qe=B&&!ke;if(!T&&re){O=Qe?O:new ot(this);var Le=a.apply(O,I);return Le.__actions__.push({func:Lf,args:[le],thisArg:n}),new Tr(Le,ge)}return Ie&&Qe?a.apply(this,I):(Le=this.thru(le),Ie?w?Le.value()[0]:Le.value():Le)})}),Rr(["pop","push","shift","sort","splice","unshift"],function(a){var c=cf[a],h=/^(?:push|sort|unshift)$/.test(a)?"tap":"thru",w=/^(?:pop|shift)$/.test(a);k.prototype[a]=function(){var $=arguments;if(w&&!this.__chain__){var T=this.value();return c.apply(Ge(T)?T:[],$)}return this[h](function(O){return c.apply(Ge(O)?O:[],$)})}}),$o(ot.prototype,function(a,c){var h=k[c];if(h){var w=h.name+"";yt.call(Xa,w)||(Xa[w]=[]),Xa[w].push({name:c,func:h})}}),Xa[Pf(n,_).name]=[{name:"wrapper",func:n}],ot.prototype.clone=jO,ot.prototype.reverse=zO,ot.prototype.value=BO,k.prototype.at=g7,k.prototype.chain=v7,k.prototype.commit=y7,k.prototype.next=w7,k.prototype.plant=b7,k.prototype.reverse=S7,k.prototype.toJSON=k.prototype.valueOf=k.prototype.value=_7,k.prototype.first=k.prototype.head,jc&&(k.prototype[jc]=x7),k},Ka=yO();Hs?((Hs.exports=Ka)._=Ka,Mg._=Ka):fn._=Ka}).call(Jc)})(zp,zp.exports);var wH=zp.exports;const xH=dm(wH);function Vr({width:e,height:t}){return e/t}function Bp(e,t=0){const n=10**t;return Math.round((e+Number.EPSILON)*n)/n}function bH(e){return(t,n)=>e(n)-e(t)}class SH{constructor(t){this.comparator=t,this.heap=[],this.n=0}greater(t,n){return this.comparator(this.heap[t],this.heap[n])<0}swap(t,n){const r=this.heap[t];this.heap[t]=this.heap[n],this.heap[n]=r}swim(t){let n=t,r=Math.floor(n/2);for(;n>1&&this.greater(r,n);)this.swap(r,n),n=r,r=Math.floor(n/2)}sink(t){let n=t,r=n*2;for(;r<=this.n&&(rl.weight));for(s.push({id:t,weight:0});s.size()>0;){const{id:l,weight:u}=s.pop();if(!o.has(l)){const f=e(l);o.add(l),f.forEach((m,p)=>{const g=u+m,y=r.get(p),b=i.get(p);(b===void 0||b>g&&(b/g>1.005||y!==void 0&&yMath.min(Vr(i),o),Number.MAX_VALUE);return Bp(n/t/r)+2}function DP(e,t,n,r){const o=t-(e.length-1)*n-2*r*e.length,i=e.reduce((s,l)=>s+Vr(l),0);return o/i}function RH(e,t,n,r,o,i,s){const l=e.slice(t,n),u=DP(l,r,i,s);return u>0?(u-o)**2*l.length:void 0}function kH({photos:e,layoutOptions:t,targetRowHeight:n,limitNodeSearch:r,rowConstraints:o}){return i=>{var s,l;const{containerWidth:u,spacing:f,padding:m}=t,p=new Map;p.set(i,0);const g=(s=o==null?void 0:o.minPhotos)!=null?s:1,y=Math.min(r,(l=o==null?void 0:o.maxPhotos)!=null?l:1/0);for(let b=i+g;by);b+=1){const S=RH(e,i,b,u,n,f,m);if(S===void 0)break;p.set(b,S)}return p}}function TH({photos:e,layoutOptions:t}){const{spacing:n,padding:r,containerWidth:o,targetRowHeight:i,rowConstraints:s}=t,l=$H({photos:e,containerWidth:o,targetRowHeight:i}),u=kH({photos:e,layoutOptions:t,targetRowHeight:i,limitNodeSearch:l,rowConstraints:s}),f=CH(u,0,e.length);if(f===void 0)return;const m=[];for(let p=1;p({photo:b,index:S})).slice(f[p-1],f[p]),y=DP(g.map(({photo:b})=>b),o,n,r);m.push(g.map(({photo:b,index:S},E)=>({photo:b,layout:{height:y,width:y*Vr(b),index:S,photoIndex:E,photosCount:g.length}})))}return m}function eg(...e){return[...e].filter(t=>!!t).join(" ")}function IP(e,{width:t,photosCount:n},{spacing:r,padding:o,containerWidth:i}){const s=r*(n-1)+2*o*n;return`calc((${e} - ${s}px) / ${Bp((i-s)/t,5)})`}function PH(e,t){return t.layout!=="rows"?`calc(100% - ${2*t.padding}px)`:IP("100%",e,t)}function a2(e,t,n){var r,o;return IP((o=(r=e.match(/calc\((.*)\)/))==null?void 0:r[1])!=null?o:e,t,n)}function AH(e,t,n){let r,o;const i=e.srcSet||e.images;return i&&i.length>0&&(r=i.concat(i.find(({width:s})=>s===e.width)?[]:[{src:e.src,width:e.width,height:e.height}]).sort((s,l)=>s.width-l.width).map(s=>`${s.src} ${s.width}w`).join(", ")),n.sizes?o=(n.sizes.sizes||[]).map(({viewport:s,size:l})=>`${s} ${a2(l,t,n)}`).concat(a2(n.sizes.size,t,n)).join(", "):r&&(o=`${Math.ceil(t.width/n.containerWidth*100)}vw`),{srcSet:r,sizes:o}}function Nx(e){var t,n;const{photo:r,layout:o,layoutOptions:i,imageProps:{style:s,className:l,...u}={},renderPhoto:f}=e,{onClick:m}=i,p={display:"block",boxSizing:"content-box",width:PH(o,i),height:"auto",aspectRatio:`${r.width} / ${r.height}`,...i.padding?{padding:`${i.padding}px`}:null,...(i.layout==="columns"||i.layout==="masonry")&&o.photoIndex{m({event:E,photo:r,index:o.index})}:void 0,y={src:r.src,alt:(t=r.alt)!=null?t:"",title:r.title,onClick:g,style:p,className:eg("react-photo-album--photo",l),loading:"lazy",decoding:"async",...AH(r,o,i),...u},b=E=>{const{src:_,alt:x,srcSet:C,sizes:R,style:P,...M}=y;return d.createElement("img",{alt:x,...C?{srcSet:C,sizes:R}:null,src:_,style:E!=null&&E.wrapped?{display:"block",width:"100%",height:"100%"}:P,...M})},S=(({display:E,boxSizing:_,width:x,aspectRatio:C,padding:R,marginBottom:P,cursor:M})=>({display:E,boxSizing:_,width:x,aspectRatio:C,padding:R,marginBottom:P,cursor:M}))(p);return d.createElement(d.Fragment,null,(n=f==null?void 0:f({photo:r,layout:o,layoutOptions:i,imageProps:y,renderDefaultPhoto:b,wrapperStyle:S}))!=null?n:b())}function MH({rowContainerProps:e,children:t}){return d.createElement("div",{...e},t)}function OH(e){const{layoutOptions:t,rowIndex:n,rowsCount:r,renderRowContainer:o,rowContainerProps:{style:i,className:s,...l}={},children:u}=e,f={className:eg("react-photo-album--row",s),style:{display:"flex",flexDirection:"row",flexWrap:"nowrap",alignItems:"flex-start",justifyContent:"space-between",...nd.createElement(OH,{key:`row-${f}`,layoutOptions:n,rowIndex:f,rowsCount:l.length,renderRowContainer:o,rowContainerProps:s},u.map(({photo:m,layout:p})=>d.createElement(Nx,{key:m.key||m.src,photo:m,layout:p,layoutOptions:n,renderPhoto:r,imageProps:i}))))):null}function DH(e,t,n,r){const o=new Map,i=new Set;i.add(n);for(let s=0;s{const f=s>0?o.get(u)[s].weight:0;e(u).forEach(({neighbor:m,weight:p})=>{let g=o.get(m);g||(g=[],o.set(m,g));const y=f+p,b=g[s+1];(!b||b.weight>y&&(b.weight/y>1.0001||u0;i-=1)o=e.get(o)[i].node,r.push(o);return r.reverse()}function LH(e,t,n,r){return IH(DH(e,t,n,r),t,r)}function FH({photos:e,spacing:t,padding:n,targetColumnWidth:r,targetColumnHeight:o}){return i=>{const s=[],l=o*1.5;let u=r/Vr(e[i])+2*n;for(let f=i+1;fl||f===e.length));f+=1)u+=r/Vr(e[f])+t+2*n;return s}}function l2({path:e,photos:t,containerWidth:n,columnsGaps:r,columnsRatios:o,spacing:i,padding:s}){const l=[],u=o.reduce((f,m)=>f+m,0);for(let f=0;f({photo:y,index:b})).slice(e[f],e[f+1]),p=o.reduce((y,b,S)=>y+(r[f]-r[S])*b,0),g=(n-(e.length-2)*i-2*(e.length-1)*s-p)*o[f]/u;l.push(m.map(({photo:y,index:b},S)=>({photo:y,layout:{width:g,height:g/Vr(y),index:b,photoIndex:S,photosCount:m.length}})))}return l}function jH({photos:e,layoutOptions:t,targetColumnWidth:n}){const{columns:r,spacing:o,padding:i,containerWidth:s}=t,l=[],u=[];if(e.length<=r){const y=e.length>0?e.reduce((S,E)=>S+Vr(E),0)/e.length:1;for(let S=0;SMath.min(E,e.length)),photos:e,columnsRatios:u,columnsGaps:l,containerWidth:s,spacing:o,padding:i});return{columnsGaps:l,columnsRatios:u,columnsModel:b}}const f=(e.reduce((y,b)=>y+n/Vr(b),0)+o*(e.length-r)+2*i*e.length)/r,m=FH({photos:e,targetColumnWidth:n,targetColumnHeight:f,spacing:o,padding:i}),p=LH(m,r,0,e.length);for(let y=0;yS+1/Vr(E),0)}const g=l2({path:p,photos:e,columnsRatios:u,columnsGaps:l,containerWidth:s,spacing:o,padding:i});return{columnsGaps:l,columnsRatios:u,columnsModel:g}}function LP(e){const{photos:t,layoutOptions:n}=e,{columns:r,spacing:o,padding:i,containerWidth:s}=n,l=(s-o*(r-1)-2*i*r)/r,{columnsGaps:u,columnsRatios:f,columnsModel:m}=jH({photos:t,layoutOptions:n,targetColumnWidth:l});return m.findIndex(p=>p.findIndex(({layout:{width:g,height:y}})=>g<0||y<0)>=0)>=0?r>1?LP({photos:t,layoutOptions:{...n,columns:r-1}}):void 0:{columnsModel:m,columnsGaps:u,columnsRatios:f}}function zH({photos:e,layoutOptions:t}){return LP({photos:e,layoutOptions:t})}function BH({columnContainerProps:e,children:t}){return d.createElement("div",{...e},t)}function UH(e){const{layoutOptions:t,columnIndex:n,columnsCount:r,columnsGaps:o,columnsRatios:i}=e,{layout:s,spacing:l,padding:u}=t;if(s==="masonry"||!o||!i)return`calc((100% - ${l*(r-1)}px) / ${r})`;const f=i.reduce((p,g)=>p+g,0),m=i.reduce((p,g,y)=>p+(o[n]-o[y])*g,0);return`calc((100% - ${Bp((r-1)*l+2*r*u+m,3)}px) * ${Bp(i[n]/f,5)} + ${2*u}px)`}function FP(e){const{layoutOptions:t,renderColumnContainer:n,children:r,columnContainerProps:{style:o,className:i,...s}={},...l}=e,u={className:eg("react-photo-album--column",i),style:{display:"flex",flexDirection:"column",flexWrap:"nowrap",alignItems:"flex-start",width:UH(e),justifyContent:t.layout==="columns"?"space-between":"flex-start",...o},...s};return d.createElement(d.Fragment,null,(n??BH)({layoutOptions:t,columnContainerProps:u,children:r,...l}))}function VH(e){const{photos:t,layoutOptions:n,renderPhoto:r,renderColumnContainer:o,componentsProps:{imageProps:i,columnContainerProps:s}}=e,l=zH({photos:t,layoutOptions:n});if(!l)return null;const{columnsModel:u,columnsRatios:f,columnsGaps:m}=l;return d.createElement(d.Fragment,null,u.map((p,g)=>d.createElement(FP,{key:`column-${g}`,layoutOptions:n,columnIndex:g,columnsCount:u.length,columnsGaps:m,columnsRatios:f,renderColumnContainer:o,columnContainerProps:s},p.map(({photo:y,layout:b})=>d.createElement(Nx,{key:y.key||y.src,photo:y,layout:b,layoutOptions:n,renderPhoto:r,imageProps:i})))))}function jP(e){const{photos:t,layoutOptions:n}=e,{columns:r,spacing:o,padding:i,containerWidth:s}=n,l=(s-o*(r-1)-2*i*r)/r;if(l<=0)return r>1?jP({...e,layoutOptions:{...n,columns:r-1}}):void 0;const u=[];for(let m=0;m{const y=u.reduce((b,S,E)=>S[])).map(m=>m.map(({photo:p,index:g},y)=>({photo:p,layout:{width:l,height:l/Vr(p),index:g,photoIndex:y,photosCount:m.length}})))}function WH(e){const{photos:t,layoutOptions:n,renderPhoto:r,renderColumnContainer:o,componentsProps:{imageProps:i,columnContainerProps:s}}=e,l=jP({photos:t,layoutOptions:n});return l?d.createElement(d.Fragment,null,l.map((u,f)=>d.createElement(FP,{key:`masonry-column-${f}`,layoutOptions:n,columnsCount:l.length,columnIndex:f,renderColumnContainer:o,columnContainerProps:s},u.map(({photo:m,layout:p})=>d.createElement(Nx,{key:m.key||m.src,photo:m,layout:p,layoutOptions:n,renderPhoto:r,imageProps:i}))))):null}function HH({containerProps:e,children:t,containerRef:n}){return d.createElement("div",{ref:n,...e},t)}function KH(e){const{layout:t,renderContainer:n,children:r,containerRef:o,containerProps:{style:i,className:s,...l}={}}=e,u={className:eg("react-photo-album",`react-photo-album--${t}`,s),style:{display:"flex",flexWrap:"nowrap",justifyContent:"space-between",flexDirection:t==="rows"?"column":"row",...i},...l};return d.createElement(d.Fragment,null,(n??HH)({containerProps:u,containerRef:o,layout:t,children:r}))}function GH(e){const t=d.useRef(e);return(!e||!t.current||e.join()!==t.current.join())&&(t.current=e),t.current}function YH(e,{newContainerWidth:t,newScrollbarWidth:n}){const{containerWidth:r,scrollbarWidth:o}=e;return r!==void 0&&o!==void 0&&t!==void 0&&n!==void 0&&t>r&&t-r<=20&&n0){const r=[...t.filter(i=>i>0)].sort((i,s)=>s-i);r.push(Math.floor(r[r.length-1]/2));const o=n;n=r.find((i,s)=>i<=o||s===r.length-1)}return n}function ZH(e,t){const[{containerWidth:n},r]=d.useReducer(YH,{containerWidth:t}),o=d.useRef(null),i=d.useRef();return{containerRef:d.useCallback(l=>{var u;(u=i.current)==null||u.disconnect(),i.current=void 0,o.current=l;const f=()=>r({newContainerWidth:XH(o.current,e),newScrollbarWidth:window.innerWidth-document.documentElement.clientWidth});f(),l&&typeof ResizeObserver<"u"&&(i.current=new ResizeObserver(f),i.current.observe(l))},[e]),containerWidth:n}}const qH=Object.freeze([1200,600,300,0]);function Dx(e,t){return typeof e=="function"?e(t):e}function zP(e,t){return typeof e<"u"?Dx(e,t):void 0}function QH(e,t){const n=qH.findIndex(r=>r<=t);return Dx(e[n>=0?n:0],t)}function wh(e,t,n,r=0){const o=zP(e,t);return Math.round(Math.max(o===void 0?QH(n,t):o,r))}function JH({layout:e,onClick:t,containerWidth:n,targetRowHeight:r,rowConstraints:o,columns:i,spacing:s,padding:l,sizes:u}){return{layout:e,onClick:t,containerWidth:n,columns:wh(i,n,[5,4,3,2],1),spacing:wh(s,n,[20,15,10,5]),padding:wh(l,n,[0,0,0,0,0]),targetRowHeight:wh(r,n,[f=>f/5,f=>f/4,f=>f/3,f=>f/2]),rowConstraints:zP(o,n),sizes:u}}function eK(e,t,n){const{photos:r,componentsProps:o}=e,i=Dx(o,t)||{};if(n){const{layout:s,spacing:l,padding:u,rowConstraints:f}=n;if(s==="rows"){const{singleRowMaxHeight:m}=f||{};if(m){const p=Math.floor(r.reduce((g,{width:y,height:b})=>g+y/b*m-2*u,u*r.length*2+l*(r.length-1)));p>0&&(i.containerProps=i.containerProps||{},i.containerProps.style={maxWidth:p,...i.containerProps.style})}}}return i}function tK(e,t,n){const{photos:r,layout:o,renderPhoto:i,renderRowContainer:s,renderColumnContainer:l}=e,u={photos:r,renderPhoto:i,componentsProps:t};return o==="rows"?d.createElement(NH,{layoutOptions:n,renderRowContainer:s,...u}):o==="columns"?d.createElement(VH,{layoutOptions:n,renderColumnContainer:l,...u}):d.createElement(WH,{layoutOptions:n,renderColumnContainer:l,...u})}function nK(e){const{photos:t,layout:n,renderContainer:r,defaultContainerWidth:o,breakpoints:i}=e,{containerRef:s,containerWidth:l}=ZH(GH(i),o);if(!n||!["rows","columns","masonry"].includes(n)||!Array.isArray(t))return null;const u=l?JH({containerWidth:l,...e}):void 0,f=eK(e,l,u);return d.createElement(KH,{layout:n,containerRef:s,renderContainer:r,containerProps:f.containerProps},u&&tK(e,f,u))}function rK({title:e,titleId:t,...n},r){return d.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true",ref:r,"aria-labelledby":t},n),e?d.createElement("title",{id:t},e):null,d.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3 4.5h14.25M3 9h9.75M3 13.5h9.75m4.5-4.5v12m0 0l-3.75-3.75M17.25 21L21 17.25"}))}const oK=d.forwardRef(rK),iK=oK;function sK({title:e,titleId:t,...n},r){return d.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true",ref:r,"aria-labelledby":t},n),e?d.createElement("title",{id:t},e):null,d.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3 4.5h14.25M3 9h9.75M3 13.5h5.25m5.25-.75L17.25 9m0 0L21 12.75M17.25 9v12"}))}const aK=d.forwardRef(sK),lK=aK;function cK({title:e,titleId:t,...n},r){return d.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true",ref:r,"aria-labelledby":t},n),e?d.createElement("title",{id:t},e):null,d.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15.042 21.672L13.684 16.6m0 0l-2.51 2.225.569-9.47 5.227 7.917-3.286-.672zM12 2.25V4.5m5.834.166l-1.591 1.591M20.25 10.5H18M7.757 14.743l-1.59 1.59M6 10.5H3.75m4.007-4.243l-1.59-1.59"}))}const uK=d.forwardRef(cK),dK=uK;function ki(e){return Array.isArray?Array.isArray(e):VP(e)==="[object Array]"}const fK=1/0;function hK(e){if(typeof e=="string")return e;let t=e+"";return t=="0"&&1/e==-fK?"-0":t}function pK(e){return e==null?"":hK(e)}function Bo(e){return typeof e=="string"}function BP(e){return typeof e=="number"}function mK(e){return e===!0||e===!1||gK(e)&&VP(e)=="[object Boolean]"}function UP(e){return typeof e=="object"}function gK(e){return UP(e)&&e!==null}function pr(e){return e!=null}function A0(e){return!e.trim().length}function VP(e){return e==null?e===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}const vK="Incorrect 'index' type",yK=e=>`Invalid value for key ${e}`,wK=e=>`Pattern length exceeds max of ${e}.`,xK=e=>`Missing ${e} property in key`,bK=e=>`Property 'weight' in key '${e}' must be a positive integer`,c2=Object.prototype.hasOwnProperty;class SK{constructor(t){this._keys=[],this._keyMap={};let n=0;t.forEach(r=>{let o=WP(r);this._keys.push(o),this._keyMap[o.id]=o,n+=o.weight}),this._keys.forEach(r=>{r.weight/=n})}get(t){return this._keyMap[t]}keys(){return this._keys}toJSON(){return JSON.stringify(this._keys)}}function WP(e){let t=null,n=null,r=null,o=1,i=null;if(Bo(e)||ki(e))r=e,t=u2(e),n=g1(e);else{if(!c2.call(e,"name"))throw new Error(xK("name"));const s=e.name;if(r=s,c2.call(e,"weight")&&(o=e.weight,o<=0))throw new Error(bK(s));t=u2(s),n=g1(s),i=e.getFn}return{path:t,id:n,weight:o,src:r,getFn:i}}function u2(e){return ki(e)?e:e.split(".")}function g1(e){return ki(e)?e.join("."):e}function _K(e,t){let n=[],r=!1;const o=(i,s,l)=>{if(pr(i))if(!s[l])n.push(i);else{let u=s[l];const f=i[u];if(!pr(f))return;if(l===s.length-1&&(Bo(f)||BP(f)||mK(f)))n.push(pK(f));else if(ki(f)){r=!0;for(let m=0,p=f.length;me.score===t.score?e.idx{this._keysMap[n.id]=r})}create(){this.isCreated||!this.docs.length||(this.isCreated=!0,Bo(this.docs[0])?this.docs.forEach((t,n)=>{this._addString(t,n)}):this.docs.forEach((t,n)=>{this._addObject(t,n)}),this.norm.clear())}add(t){const n=this.size();Bo(t)?this._addString(t,n):this._addObject(t,n)}removeAt(t){this.records.splice(t,1);for(let n=t,r=this.size();n{let s=o.getFn?o.getFn(t):this.getFn(t,o.path);if(pr(s)){if(ki(s)){let l=[];const u=[{nestedArrIndex:-1,value:s}];for(;u.length;){const{nestedArrIndex:f,value:m}=u.pop();if(pr(m))if(Bo(m)&&!A0(m)){let p={v:m,i:f,n:this.norm.get(m)};l.push(p)}else ki(m)&&m.forEach((p,g)=>{u.push({nestedArrIndex:g,value:p})})}r.$[i]=l}else if(Bo(s)&&!A0(s)){let l={v:s,n:this.norm.get(s)};r.$[i]=l}}}),this.records.push(r)}toJSON(){return{keys:this.keys,records:this.records}}}function HP(e,t,{getFn:n=He.getFn,fieldNormWeight:r=He.fieldNormWeight}={}){const o=new Ix({getFn:n,fieldNormWeight:r});return o.setKeys(e.map(WP)),o.setSources(t),o.create(),o}function PK(e,{getFn:t=He.getFn,fieldNormWeight:n=He.fieldNormWeight}={}){const{keys:r,records:o}=e,i=new Ix({getFn:t,fieldNormWeight:n});return i.setKeys(r),i.setIndexRecords(o),i}function xh(e,{errors:t=0,currentLocation:n=0,expectedLocation:r=0,distance:o=He.distance,ignoreLocation:i=He.ignoreLocation}={}){const s=t/e.length;if(i)return s;const l=Math.abs(r-n);return o?s+l/o:l?1:s}function AK(e=[],t=He.minMatchCharLength){let n=[],r=-1,o=-1,i=0;for(let s=e.length;i=t&&n.push([r,o]),r=-1)}return e[i-1]&&i-r>=t&&n.push([r,i-1]),n}const la=32;function MK(e,t,n,{location:r=He.location,distance:o=He.distance,threshold:i=He.threshold,findAllMatches:s=He.findAllMatches,minMatchCharLength:l=He.minMatchCharLength,includeMatches:u=He.includeMatches,ignoreLocation:f=He.ignoreLocation}={}){if(t.length>la)throw new Error(wK(la));const m=t.length,p=e.length,g=Math.max(0,Math.min(r,p));let y=i,b=g;const S=l>1||u,E=S?Array(p):[];let _;for(;(_=e.indexOf(t,b))>-1;){let A=xh(t,{currentLocation:_,expectedLocation:g,distance:o,ignoreLocation:f});if(y=Math.min(A,y),b=_+m,S){let D=0;for(;D=W;V-=1){let F=V-1,N=n[e.charAt(F)];if(S&&(E[F]=+!!N),X[V]=(X[V+1]<<1|1)&N,A&&(X[V]|=(x[V+1]|x[V])<<1|1|x[V+1]),X[V]&P&&(C=xh(t,{errors:A,currentLocation:F,expectedLocation:g,distance:o,ignoreLocation:f}),C<=y)){if(y=C,b=F,b<=g)break;W=Math.max(1,2*g-b)}}if(xh(t,{errors:A+1,currentLocation:g,expectedLocation:g,distance:o,ignoreLocation:f})>y)break;x=X}const M={isMatch:b>=0,score:Math.max(.001,C)};if(S){const A=AK(E,l);A.length?u&&(M.indices=A):M.isMatch=!1}return M}function OK(e){let t={};for(let n=0,r=e.length;n{this.chunks.push({pattern:g,alphabet:OK(g),startIndex:y})},p=this.pattern.length;if(p>la){let g=0;const y=p%la,b=p-y;for(;g{const{isMatch:_,score:x,indices:C}=MK(t,b,S,{location:o+E,distance:i,threshold:s,findAllMatches:l,minMatchCharLength:u,includeMatches:r,ignoreLocation:f});_&&(g=!0),p+=x,_&&C&&(m=[...m,...C])});let y={isMatch:g,score:g?p/this.chunks.length:1};return g&&r&&(y.indices=m),y}}class js{constructor(t){this.pattern=t}static isMultiMatch(t){return d2(t,this.multiRegex)}static isSingleMatch(t){return d2(t,this.singleRegex)}search(){}}function d2(e,t){const n=e.match(t);return n?n[1]:null}class NK extends js{constructor(t){super(t)}static get type(){return"exact"}static get multiRegex(){return/^="(.*)"$/}static get singleRegex(){return/^=(.*)$/}search(t){const n=t===this.pattern;return{isMatch:n,score:n?0:1,indices:[0,this.pattern.length-1]}}}class DK extends js{constructor(t){super(t)}static get type(){return"inverse-exact"}static get multiRegex(){return/^!"(.*)"$/}static get singleRegex(){return/^!(.*)$/}search(t){const r=t.indexOf(this.pattern)===-1;return{isMatch:r,score:r?0:1,indices:[0,t.length-1]}}}class IK extends js{constructor(t){super(t)}static get type(){return"prefix-exact"}static get multiRegex(){return/^\^"(.*)"$/}static get singleRegex(){return/^\^(.*)$/}search(t){const n=t.startsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[0,this.pattern.length-1]}}}class LK extends js{constructor(t){super(t)}static get type(){return"inverse-prefix-exact"}static get multiRegex(){return/^!\^"(.*)"$/}static get singleRegex(){return/^!\^(.*)$/}search(t){const n=!t.startsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[0,t.length-1]}}}class FK extends js{constructor(t){super(t)}static get type(){return"suffix-exact"}static get multiRegex(){return/^"(.*)"\$$/}static get singleRegex(){return/^(.*)\$$/}search(t){const n=t.endsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[t.length-this.pattern.length,t.length-1]}}}class jK extends js{constructor(t){super(t)}static get type(){return"inverse-suffix-exact"}static get multiRegex(){return/^!"(.*)"\$$/}static get singleRegex(){return/^!(.*)\$$/}search(t){const n=!t.endsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[0,t.length-1]}}}class GP extends js{constructor(t,{location:n=He.location,threshold:r=He.threshold,distance:o=He.distance,includeMatches:i=He.includeMatches,findAllMatches:s=He.findAllMatches,minMatchCharLength:l=He.minMatchCharLength,isCaseSensitive:u=He.isCaseSensitive,ignoreLocation:f=He.ignoreLocation}={}){super(t),this._bitapSearch=new KP(t,{location:n,threshold:r,distance:o,includeMatches:i,findAllMatches:s,minMatchCharLength:l,isCaseSensitive:u,ignoreLocation:f})}static get type(){return"fuzzy"}static get multiRegex(){return/^"(.*)"$/}static get singleRegex(){return/^(.*)$/}search(t){return this._bitapSearch.searchIn(t)}}class YP extends js{constructor(t){super(t)}static get type(){return"include"}static get multiRegex(){return/^'"(.*)"$/}static get singleRegex(){return/^'(.*)$/}search(t){let n=0,r;const o=[],i=this.pattern.length;for(;(r=t.indexOf(this.pattern,n))>-1;)n=r+i,o.push([r,n-1]);const s=!!o.length;return{isMatch:s,score:s?0:1,indices:o}}}const v1=[NK,YP,IK,LK,jK,FK,DK,GP],f2=v1.length,zK=/ +(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/,BK="|";function UK(e,t={}){return e.split(BK).map(n=>{let r=n.trim().split(zK).filter(i=>i&&!!i.trim()),o=[];for(let i=0,s=r.length;i!!(e[Up.AND]||e[Up.OR]),KK=e=>!!e[x1.PATH],GK=e=>!ki(e)&&UP(e)&&!b1(e),h2=e=>({[Up.AND]:Object.keys(e).map(t=>({[t]:e[t]}))});function XP(e,t,{auto:n=!0}={}){const r=o=>{let i=Object.keys(o);const s=KK(o);if(!s&&i.length>1&&!b1(o))return r(h2(o));if(GK(o)){const u=s?o[x1.PATH]:i[0],f=s?o[x1.PATTERN]:o[u];if(!Bo(f))throw new Error(yK(u));const m={keyId:g1(u),pattern:f};return n&&(m.searcher=w1(f,t)),m}let l={children:[],operator:i[0]};return i.forEach(u=>{const f=o[u];ki(f)&&f.forEach(m=>{l.children.push(r(m))})}),l};return b1(e)||(e=h2(e)),r(e)}function YK(e,{ignoreFieldNorm:t=He.ignoreFieldNorm}){e.forEach(n=>{let r=1;n.matches.forEach(({key:o,norm:i,score:s})=>{const l=o?o.weight:null;r*=Math.pow(s===0&&l?Number.EPSILON:s,(l||1)*(t?1:i))}),n.score=r})}function XK(e,t){const n=e.matches;t.matches=[],pr(n)&&n.forEach(r=>{if(!pr(r.indices)||!r.indices.length)return;const{indices:o,value:i}=r;let s={indices:o,value:i};r.key&&(s.key=r.key.src),r.idx>-1&&(s.refIndex=r.idx),t.matches.push(s)})}function ZK(e,t){t.score=e.score}function qK(e,t,{includeMatches:n=He.includeMatches,includeScore:r=He.includeScore}={}){const o=[];return n&&o.push(XK),r&&o.push(ZK),e.map(i=>{const{idx:s}=i,l={item:t[s],refIndex:s};return o.length&&o.forEach(u=>{u(i,l)}),l})}class kc{constructor(t,n={},r){this.options={...He,...n},this.options.useExtendedSearch,this._keyStore=new SK(this.options.keys),this.setCollection(t,r)}setCollection(t,n){if(this._docs=t,n&&!(n instanceof Ix))throw new Error(vK);this._myIndex=n||HP(this.options.keys,this._docs,{getFn:this.options.getFn,fieldNormWeight:this.options.fieldNormWeight})}add(t){pr(t)&&(this._docs.push(t),this._myIndex.add(t))}remove(t=()=>!1){const n=[];for(let r=0,o=this._docs.length;r-1&&(u=u.slice(0,n)),qK(u,this._docs,{includeMatches:r,includeScore:o})}_searchStringList(t){const n=w1(t,this.options),{records:r}=this._myIndex,o=[];return r.forEach(({v:i,i:s,n:l})=>{if(!pr(i))return;const{isMatch:u,score:f,indices:m}=n.searchIn(i);u&&o.push({item:i,idx:s,matches:[{score:f,value:i,norm:l,indices:m}]})}),o}_searchLogical(t){const n=XP(t,this.options),r=(l,u,f)=>{if(!l.children){const{keyId:p,searcher:g}=l,y=this._findMatches({key:this._keyStore.get(p),value:this._myIndex.getValueForItemAtKeyId(u,p),searcher:g});return y&&y.length?[{idx:f,item:u,matches:y}]:[]}const m=[];for(let p=0,g=l.children.length;p{if(pr(l)){let f=r(n,l,u);f.length&&(i[u]||(i[u]={idx:u,item:l,matches:[]},s.push(i[u])),f.forEach(({matches:m})=>{i[u].matches.push(...m)}))}}),s}_searchObjectList(t){const n=w1(t,this.options),{keys:r,records:o}=this._myIndex,i=[];return o.forEach(({$:s,i:l})=>{if(!pr(s))return;let u=[];r.forEach((f,m)=>{u.push(...this._findMatches({key:f,value:s[m],searcher:n}))}),u.length&&i.push({idx:l,item:s,matches:u})}),i}_findMatches({key:t,value:n,searcher:r}){if(!pr(n))return[];let o=[];if(ki(n))n.forEach(({v:i,i:s,n:l})=>{if(!pr(i))return;const{isMatch:u,score:f,indices:m}=r.searchIn(i);u&&o.push({score:f,key:t,value:i,idx:s,norm:l,indices:m})});else{const{v:i,n:s}=n,{isMatch:l,score:u,indices:f}=r.searchIn(i);l&&o.push({score:u,key:t,value:i,norm:s,indices:f})}return o}}kc.version="7.0.0";kc.createIndex=HP;kc.parseIndex=PK;kc.config=He;kc.parseQuery=XP;HK(WK);function Gd(e){const t=e+"CollectionProvider",[n,r]=Mn(t),[o,i]=n(t,{collectionRef:{current:null},itemMap:new Map}),s=y=>{const{scope:b,children:S}=y,E=Fe.useRef(null),_=Fe.useRef(new Map).current;return Fe.createElement(o,{scope:b,itemMap:_,collectionRef:E},S)},l=e+"CollectionSlot",u=Fe.forwardRef((y,b)=>{const{scope:S,children:E}=y,_=i(l,S),x=Be(b,_.collectionRef);return Fe.createElement(Zo,{ref:x},E)}),f=e+"CollectionItemSlot",m="data-radix-collection-item",p=Fe.forwardRef((y,b)=>{const{scope:S,children:E,..._}=y,x=Fe.useRef(null),C=Be(b,x),R=i(f,S);return Fe.useEffect(()=>(R.itemMap.set(x,{ref:x,..._}),()=>void R.itemMap.delete(x))),Fe.createElement(Zo,{[m]:"",ref:C},E)});function g(y){const b=i(e+"CollectionConsumer",y);return Fe.useCallback(()=>{const E=b.collectionRef.current;if(!E)return[];const _=Array.from(E.querySelectorAll(`[${m}]`));return Array.from(b.itemMap.values()).sort((R,P)=>_.indexOf(R.ref.current)-_.indexOf(P.ref.current))},[b.collectionRef,b.itemMap])}return[{Provider:s,Slot:u,ItemSlot:p},g,r]}const QK=d.createContext(void 0);function Tc(e){const t=d.useContext(QK);return e||t||"ltr"}const M0="rovingFocusGroup.onEntryFocus",JK={bubbles:!1,cancelable:!0},Lx="RovingFocusGroup",[S1,ZP,eG]=Gd(Lx),[tG,tg]=Mn(Lx,[eG]),[nG,rG]=tG(Lx),oG=d.forwardRef((e,t)=>d.createElement(S1.Provider,{scope:e.__scopeRovingFocusGroup},d.createElement(S1.Slot,{scope:e.__scopeRovingFocusGroup},d.createElement(iG,Y({},e,{ref:t}))))),iG=d.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:o=!1,dir:i,currentTabStopId:s,defaultCurrentTabStopId:l,onCurrentTabStopIdChange:u,onEntryFocus:f,...m}=e,p=d.useRef(null),g=Be(t,p),y=Tc(i),[b=null,S]=Zr({prop:s,defaultProp:l,onChange:u}),[E,_]=d.useState(!1),x=Ft(f),C=ZP(n),R=d.useRef(!1),[P,M]=d.useState(0);return d.useEffect(()=>{const A=p.current;if(A)return A.addEventListener(M0,x),()=>A.removeEventListener(M0,x)},[x]),d.createElement(nG,{scope:n,orientation:r,dir:y,loop:o,currentTabStopId:b,onItemFocus:d.useCallback(A=>S(A),[S]),onItemShiftTab:d.useCallback(()=>_(!0),[]),onFocusableItemAdd:d.useCallback(()=>M(A=>A+1),[]),onFocusableItemRemove:d.useCallback(()=>M(A=>A-1),[])},d.createElement(Pe.div,Y({tabIndex:E||P===0?-1:0,"data-orientation":r},m,{ref:g,style:{outline:"none",...e.style},onMouseDown:de(e.onMouseDown,()=>{R.current=!0}),onFocus:de(e.onFocus,A=>{const D=!R.current;if(A.target===A.currentTarget&&D&&!E){const U=new CustomEvent(M0,JK);if(A.currentTarget.dispatchEvent(U),!U.defaultPrevented){const W=C().filter(F=>F.focusable),q=W.find(F=>F.active),X=W.find(F=>F.id===b),V=[q,X,...W].filter(Boolean).map(F=>F.ref.current);qP(V)}}R.current=!1}),onBlur:de(e.onBlur,()=>_(!1))})))}),sG="RovingFocusGroupItem",aG=d.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:o=!1,tabStopId:i,...s}=e,l=nr(),u=i||l,f=rG(sG,n),m=f.currentTabStopId===u,p=ZP(n),{onFocusableItemAdd:g,onFocusableItemRemove:y}=f;return d.useEffect(()=>{if(r)return g(),()=>y()},[r,g,y]),d.createElement(S1.ItemSlot,{scope:n,id:u,focusable:r,active:o},d.createElement(Pe.span,Y({tabIndex:m?0:-1,"data-orientation":f.orientation},s,{ref:t,onMouseDown:de(e.onMouseDown,b=>{r?f.onItemFocus(u):b.preventDefault()}),onFocus:de(e.onFocus,()=>f.onItemFocus(u)),onKeyDown:de(e.onKeyDown,b=>{if(b.key==="Tab"&&b.shiftKey){f.onItemShiftTab();return}if(b.target!==b.currentTarget)return;const S=uG(b,f.orientation,f.dir);if(S!==void 0){b.preventDefault();let _=p().filter(x=>x.focusable).map(x=>x.ref.current);if(S==="last")_.reverse();else if(S==="prev"||S==="next"){S==="prev"&&_.reverse();const x=_.indexOf(b.currentTarget);_=f.loop?dG(_,x+1):_.slice(x+1)}setTimeout(()=>qP(_))}})})))}),lG={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function cG(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function uG(e,t,n){const r=cG(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return lG[r]}function qP(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function dG(e,t){return e.map((n,r)=>e[(t+r)%e.length])}const QP=oG,JP=aG,e5="Tabs",[fG,xte]=Mn(e5,[tg]),t5=tg(),[hG,Fx]=fG(e5),pG=d.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,onValueChange:o,defaultValue:i,orientation:s="horizontal",dir:l,activationMode:u="automatic",...f}=e,m=Tc(l),[p,g]=Zr({prop:r,onChange:o,defaultProp:i});return d.createElement(hG,{scope:n,baseId:nr(),value:p,onValueChange:g,orientation:s,dir:m,activationMode:u},d.createElement(Pe.div,Y({dir:m,"data-orientation":s},f,{ref:t})))}),mG="TabsList",gG=d.forwardRef((e,t)=>{const{__scopeTabs:n,loop:r=!0,...o}=e,i=Fx(mG,n),s=t5(n);return d.createElement(QP,Y({asChild:!0},s,{orientation:i.orientation,dir:i.dir,loop:r}),d.createElement(Pe.div,Y({role:"tablist","aria-orientation":i.orientation},o,{ref:t})))}),vG="TabsTrigger",yG=d.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,disabled:o=!1,...i}=e,s=Fx(vG,n),l=t5(n),u=n5(s.baseId,r),f=r5(s.baseId,r),m=r===s.value;return d.createElement(JP,Y({asChild:!0},l,{focusable:!o,active:m}),d.createElement(Pe.button,Y({type:"button",role:"tab","aria-selected":m,"aria-controls":f,"data-state":m?"active":"inactive","data-disabled":o?"":void 0,disabled:o,id:u},i,{ref:t,onMouseDown:de(e.onMouseDown,p=>{!o&&p.button===0&&p.ctrlKey===!1?s.onValueChange(r):p.preventDefault()}),onKeyDown:de(e.onKeyDown,p=>{[" ","Enter"].includes(p.key)&&s.onValueChange(r)}),onFocus:de(e.onFocus,()=>{const p=s.activationMode!=="manual";!m&&!o&&p&&s.onValueChange(r)})})))}),wG="TabsContent",xG=d.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,forceMount:o,children:i,...s}=e,l=Fx(wG,n),u=n5(l.baseId,r),f=r5(l.baseId,r),m=r===l.value,p=d.useRef(m);return d.useEffect(()=>{const g=requestAnimationFrame(()=>p.current=!1);return()=>cancelAnimationFrame(g)},[]),d.createElement(Sn,{present:o||m},({present:g})=>d.createElement(Pe.div,Y({"data-state":m?"active":"inactive","data-orientation":l.orientation,role:"tabpanel","aria-labelledby":u,hidden:!g,id:f,tabIndex:0},s,{ref:t,style:{...e.style,animationDuration:p.current?"0s":void 0}}),g&&i))});function n5(e,t){return`${e}-trigger-${t}`}function r5(e,t){return`${e}-content-${t}`}const bG=pG,o5=gG,i5=yG,s5=xG,a5=bG,jx=d.forwardRef(({className:e,...t},n)=>v.jsx(o5,{ref:n,className:Ce("inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground",e),tabIndex:-1,...t}));jx.displayName=o5.displayName;const pa=d.forwardRef(({className:e,...t},n)=>v.jsx(i5,{ref:n,className:Ce("inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow",e),tabIndex:-1,...t}));pa.displayName=i5.displayName;const Su=d.forwardRef(({className:e,...t},n)=>v.jsx(s5,{ref:n,className:Ce("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",e),tabIndex:-1,...t}));Su.displayName=s5.displayName;function fd(e,[t,n]){return Math.min(n,Math.max(t,e))}function zx(e){const t=d.useRef({value:e,previous:e});return d.useMemo(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}const SG=[" ","Enter","ArrowUp","ArrowDown"],_G=[" ","Enter"],ng="Select",[rg,og,EG]=Gd(ng),[Pc,bte]=Mn(ng,[EG,Fs]),Bx=Fs(),[CG,Fa]=Pc(ng),[$G,RG]=Pc(ng),kG=e=>{const{__scopeSelect:t,children:n,open:r,defaultOpen:o,onOpenChange:i,value:s,defaultValue:l,onValueChange:u,dir:f,name:m,autoComplete:p,disabled:g,required:y}=e,b=Bx(t),[S,E]=d.useState(null),[_,x]=d.useState(null),[C,R]=d.useState(!1),P=Tc(f),[M=!1,A]=Zr({prop:r,defaultProp:o,onChange:i}),[D,U]=Zr({prop:s,defaultProp:l,onChange:u}),W=d.useRef(null),q=S?!!S.closest("form"):!0,[X,ae]=d.useState(new Set),V=Array.from(X).map(F=>F.props.value).join(";");return d.createElement(jd,b,d.createElement(CG,{required:y,scope:t,trigger:S,onTriggerChange:E,valueNode:_,onValueNodeChange:x,valueNodeHasChildren:C,onValueNodeHasChildrenChange:R,contentId:nr(),value:D,onValueChange:U,open:M,onOpenChange:A,dir:P,triggerPointerDownPosRef:W,disabled:g},d.createElement(rg.Provider,{scope:t},d.createElement($G,{scope:e.__scopeSelect,onNativeOptionAdd:d.useCallback(F=>{ae(N=>new Set(N).add(F))},[]),onNativeOptionRemove:d.useCallback(F=>{ae(N=>{const ie=new Set(N);return ie.delete(F),ie})},[])},n)),q?d.createElement(f5,{key:V,"aria-hidden":!0,required:y,tabIndex:-1,name:m,autoComplete:p,value:D,onChange:F=>U(F.target.value),disabled:g},D===void 0?d.createElement("option",{value:""}):null,Array.from(X)):null))},TG="SelectTrigger",PG=d.forwardRef((e,t)=>{const{__scopeSelect:n,disabled:r=!1,...o}=e,i=Bx(n),s=Fa(TG,n),l=s.disabled||r,u=Be(t,s.onTriggerChange),f=og(n),[m,p,g]=h5(b=>{const S=f().filter(x=>!x.disabled),E=S.find(x=>x.value===s.value),_=p5(S,b,E);_!==void 0&&s.onValueChange(_.value)}),y=()=>{l||(s.onOpenChange(!0),g())};return d.createElement(Vm,Y({asChild:!0},i),d.createElement(Pe.button,Y({type:"button",role:"combobox","aria-controls":s.contentId,"aria-expanded":s.open,"aria-required":s.required,"aria-autocomplete":"none",dir:s.dir,"data-state":s.open?"open":"closed",disabled:l,"data-disabled":l?"":void 0,"data-placeholder":d5(s.value)?"":void 0},o,{ref:u,onClick:de(o.onClick,b=>{b.currentTarget.focus()}),onPointerDown:de(o.onPointerDown,b=>{const S=b.target;S.hasPointerCapture(b.pointerId)&&S.releasePointerCapture(b.pointerId),b.button===0&&b.ctrlKey===!1&&(y(),s.triggerPointerDownPosRef.current={x:Math.round(b.pageX),y:Math.round(b.pageY)},b.preventDefault())}),onKeyDown:de(o.onKeyDown,b=>{const S=m.current!=="";!(b.ctrlKey||b.altKey||b.metaKey)&&b.key.length===1&&p(b.key),!(S&&b.key===" ")&&SG.includes(b.key)&&(y(),b.preventDefault())})})))}),AG="SelectValue",MG=d.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,children:i,placeholder:s="",...l}=e,u=Fa(AG,n),{onValueNodeHasChildrenChange:f}=u,m=i!==void 0,p=Be(t,u.onValueNodeChange);return An(()=>{f(m)},[f,m]),d.createElement(Pe.span,Y({},l,{ref:p,style:{pointerEvents:"none"}}),d5(u.value)?d.createElement(d.Fragment,null,s):i)}),OG=d.forwardRef((e,t)=>{const{__scopeSelect:n,children:r,...o}=e;return d.createElement(Pe.span,Y({"aria-hidden":!0},o,{ref:t}),r||"▼")}),NG=e=>d.createElement(zd,Y({asChild:!0},e)),dc="SelectContent",DG=d.forwardRef((e,t)=>{const n=Fa(dc,e.__scopeSelect),[r,o]=d.useState();if(An(()=>{o(new DocumentFragment)},[]),!n.open){const i=r;return i?Is.createPortal(d.createElement(l5,{scope:e.__scopeSelect},d.createElement(rg.Slot,{scope:e.__scopeSelect},d.createElement("div",null,e.children))),i):null}return d.createElement(IG,Y({},e,{ref:t}))}),hi=10,[l5,ja]=Pc(dc),IG=d.forwardRef((e,t)=>{const{__scopeSelect:n,position:r="item-aligned",onCloseAutoFocus:o,onEscapeKeyDown:i,onPointerDownOutside:s,side:l,sideOffset:u,align:f,alignOffset:m,arrowPadding:p,collisionBoundary:g,collisionPadding:y,sticky:b,hideWhenDetached:S,avoidCollisions:E,..._}=e,x=Fa(dc,n),[C,R]=d.useState(null),[P,M]=d.useState(null),A=Be(t,he=>R(he)),[D,U]=d.useState(null),[W,q]=d.useState(null),X=og(n),[ae,V]=d.useState(!1),F=d.useRef(!1);d.useEffect(()=>{if(C)return Qm(C)},[C]),Xm();const N=d.useCallback(he=>{const[xe,...$e]=X().map(je=>je.ref.current),[Ae]=$e.slice(-1),Me=document.activeElement;for(const je of he)if(je===Me||(je==null||je.scrollIntoView({block:"nearest"}),je===xe&&P&&(P.scrollTop=0),je===Ae&&P&&(P.scrollTop=P.scrollHeight),je==null||je.focus(),document.activeElement!==Me))return},[X,P]),ie=d.useCallback(()=>N([D,C]),[N,D,C]);d.useEffect(()=>{ae&&ie()},[ae,ie]);const{onOpenChange:K,triggerPointerDownPosRef:Z}=x;d.useEffect(()=>{if(C){let he={x:0,y:0};const xe=Ae=>{var Me,je,Mt,ct;he={x:Math.abs(Math.round(Ae.pageX)-((Me=(je=Z.current)===null||je===void 0?void 0:je.x)!==null&&Me!==void 0?Me:0)),y:Math.abs(Math.round(Ae.pageY)-((Mt=(ct=Z.current)===null||ct===void 0?void 0:ct.y)!==null&&Mt!==void 0?Mt:0))}},$e=Ae=>{he.x<=10&&he.y<=10?Ae.preventDefault():C.contains(Ae.target)||K(!1),document.removeEventListener("pointermove",xe),Z.current=null};return Z.current!==null&&(document.addEventListener("pointermove",xe),document.addEventListener("pointerup",$e,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",xe),document.removeEventListener("pointerup",$e,{capture:!0})}}},[C,K,Z]),d.useEffect(()=>{const he=()=>K(!1);return window.addEventListener("blur",he),window.addEventListener("resize",he),()=>{window.removeEventListener("blur",he),window.removeEventListener("resize",he)}},[K]);const[H,se]=h5(he=>{const xe=X().filter(Me=>!Me.disabled),$e=xe.find(Me=>Me.ref.current===document.activeElement),Ae=p5(xe,he,$e);Ae&&setTimeout(()=>Ae.ref.current.focus())}),ce=d.useCallback((he,xe,$e)=>{const Ae=!F.current&&!$e;(x.value!==void 0&&x.value===xe||Ae)&&(U(he),Ae&&(F.current=!0))},[x.value]),Ve=d.useCallback(()=>C==null?void 0:C.focus(),[C]),Ue=d.useCallback((he,xe,$e)=>{const Ae=!F.current&&!$e;(x.value!==void 0&&x.value===xe||Ae)&&q(he)},[x.value]),We=r==="popper"?p2:LG,Oe=We===p2?{side:l,sideOffset:u,align:f,alignOffset:m,arrowPadding:p,collisionBoundary:g,collisionPadding:y,sticky:b,hideWhenDetached:S,avoidCollisions:E}:{};return d.createElement(l5,{scope:n,content:C,viewport:P,onViewportChange:M,itemRefCallback:ce,selectedItem:D,onItemLeave:Ve,itemTextRefCallback:Ue,focusSelectedItem:ie,selectedItemText:W,position:r,isPositioned:ae,searchRef:H},d.createElement(qm,{as:Zo,allowPinchZoom:!0},d.createElement(Ym,{asChild:!0,trapped:x.open,onMountAutoFocus:he=>{he.preventDefault()},onUnmountAutoFocus:de(o,he=>{var xe;(xe=x.trigger)===null||xe===void 0||xe.focus({preventScroll:!0}),he.preventDefault()})},d.createElement(Ec,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:i,onPointerDownOutside:s,onFocusOutside:he=>he.preventDefault(),onDismiss:()=>x.onOpenChange(!1)},d.createElement(We,Y({role:"listbox",id:x.contentId,"data-state":x.open?"open":"closed",dir:x.dir,onContextMenu:he=>he.preventDefault()},_,Oe,{onPlaced:()=>V(!0),ref:A,style:{display:"flex",flexDirection:"column",outline:"none",..._.style},onKeyDown:de(_.onKeyDown,he=>{const xe=he.ctrlKey||he.altKey||he.metaKey;if(he.key==="Tab"&&he.preventDefault(),!xe&&he.key.length===1&&se(he.key),["ArrowUp","ArrowDown","Home","End"].includes(he.key)){let Ae=X().filter(Me=>!Me.disabled).map(Me=>Me.ref.current);if(["ArrowUp","End"].includes(he.key)&&(Ae=Ae.slice().reverse()),["ArrowUp","ArrowDown"].includes(he.key)){const Me=he.target,je=Ae.indexOf(Me);Ae=Ae.slice(je+1)}setTimeout(()=>N(Ae)),he.preventDefault()}})}))))))}),LG=d.forwardRef((e,t)=>{const{__scopeSelect:n,onPlaced:r,...o}=e,i=Fa(dc,n),s=ja(dc,n),[l,u]=d.useState(null),[f,m]=d.useState(null),p=Be(t,A=>m(A)),g=og(n),y=d.useRef(!1),b=d.useRef(!0),{viewport:S,selectedItem:E,selectedItemText:_,focusSelectedItem:x}=s,C=d.useCallback(()=>{if(i.trigger&&i.valueNode&&l&&f&&S&&E&&_){const A=i.trigger.getBoundingClientRect(),D=f.getBoundingClientRect(),U=i.valueNode.getBoundingClientRect(),W=_.getBoundingClientRect();if(i.dir!=="rtl"){const Me=W.left-D.left,je=U.left-Me,Mt=A.left-je,ct=A.width+Mt,Kt=Math.max(ct,D.width),Er=window.innerWidth-hi,gt=fd(je,[hi,Er-Kt]);l.style.minWidth=ct+"px",l.style.left=gt+"px"}else{const Me=D.right-W.right,je=window.innerWidth-U.right-Me,Mt=window.innerWidth-A.right-je,ct=A.width+Mt,Kt=Math.max(ct,D.width),Er=window.innerWidth-hi,gt=fd(je,[hi,Er-Kt]);l.style.minWidth=ct+"px",l.style.right=gt+"px"}const q=g(),X=window.innerHeight-hi*2,ae=S.scrollHeight,V=window.getComputedStyle(f),F=parseInt(V.borderTopWidth,10),N=parseInt(V.paddingTop,10),ie=parseInt(V.borderBottomWidth,10),K=parseInt(V.paddingBottom,10),Z=F+N+ae+K+ie,H=Math.min(E.offsetHeight*5,Z),se=window.getComputedStyle(S),ce=parseInt(se.paddingTop,10),Ve=parseInt(se.paddingBottom,10),Ue=A.top+A.height/2-hi,We=X-Ue,Oe=E.offsetHeight/2,he=E.offsetTop+Oe,xe=F+N+he,$e=Z-xe;if(xe<=Ue){const Me=E===q[q.length-1].ref.current;l.style.bottom="0px";const je=f.clientHeight-S.offsetTop-S.offsetHeight,Mt=Math.max(We,Oe+(Me?Ve:0)+je+ie),ct=xe+Mt;l.style.height=ct+"px"}else{const Me=E===q[0].ref.current;l.style.top="0px";const Mt=Math.max(Ue,F+S.offsetTop+(Me?ce:0)+Oe)+$e;l.style.height=Mt+"px",S.scrollTop=xe-Ue+S.offsetTop}l.style.margin=`${hi}px 0`,l.style.minHeight=H+"px",l.style.maxHeight=X+"px",r==null||r(),requestAnimationFrame(()=>y.current=!0)}},[g,i.trigger,i.valueNode,l,f,S,E,_,i.dir,r]);An(()=>C(),[C]);const[R,P]=d.useState();An(()=>{f&&P(window.getComputedStyle(f).zIndex)},[f]);const M=d.useCallback(A=>{A&&b.current===!0&&(C(),x==null||x(),b.current=!1)},[C,x]);return d.createElement(FG,{scope:n,contentWrapper:l,shouldExpandOnScrollRef:y,onScrollButtonChange:M},d.createElement("div",{ref:u,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:R}},d.createElement(Pe.div,Y({},o,{ref:p,style:{boxSizing:"border-box",maxHeight:"100%",...o.style}}))))}),p2=d.forwardRef((e,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:o=hi,...i}=e,s=Bx(n);return d.createElement(Wm,Y({},s,i,{ref:t,align:r,collisionPadding:o,style:{boxSizing:"border-box",...i.style,"--radix-select-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-select-content-available-width":"var(--radix-popper-available-width)","--radix-select-content-available-height":"var(--radix-popper-available-height)","--radix-select-trigger-width":"var(--radix-popper-anchor-width)","--radix-select-trigger-height":"var(--radix-popper-anchor-height)"}}))}),[FG,Ux]=Pc(dc,{}),m2="SelectViewport",jG=d.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=ja(m2,n),i=Ux(m2,n),s=Be(t,o.onViewportChange),l=d.useRef(0);return d.createElement(d.Fragment,null,d.createElement("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"}}),d.createElement(rg.Slot,{scope:n},d.createElement(Pe.div,Y({"data-radix-select-viewport":"",role:"presentation"},r,{ref:s,style:{position:"relative",flex:1,overflow:"auto",...r.style},onScroll:de(r.onScroll,u=>{const f=u.currentTarget,{contentWrapper:m,shouldExpandOnScrollRef:p}=i;if(p!=null&&p.current&&m){const g=Math.abs(l.current-f.scrollTop);if(g>0){const y=window.innerHeight-hi*2,b=parseFloat(m.style.minHeight),S=parseFloat(m.style.height),E=Math.max(b,S);if(E0?C:0,m.style.justifyContent="flex-end")}}}l.current=f.scrollTop})}))))}),zG="SelectGroup",[BG,UG]=Pc(zG),VG=d.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=nr();return d.createElement(BG,{scope:n,id:o},d.createElement(Pe.div,Y({role:"group","aria-labelledby":o},r,{ref:t})))}),WG="SelectLabel",HG=d.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=UG(WG,n);return d.createElement(Pe.div,Y({id:o.id},r,{ref:t}))}),_1="SelectItem",[KG,c5]=Pc(_1),GG=d.forwardRef((e,t)=>{const{__scopeSelect:n,value:r,disabled:o=!1,textValue:i,...s}=e,l=Fa(_1,n),u=ja(_1,n),f=l.value===r,[m,p]=d.useState(i??""),[g,y]=d.useState(!1),b=Be(t,_=>{var x;return(x=u.itemRefCallback)===null||x===void 0?void 0:x.call(u,_,r,o)}),S=nr(),E=()=>{o||(l.onValueChange(r),l.onOpenChange(!1))};if(r==="")throw new Error("A must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.");return d.createElement(KG,{scope:n,value:r,disabled:o,textId:S,isSelected:f,onItemTextChange:d.useCallback(_=>{p(x=>{var C;return x||((C=_==null?void 0:_.textContent)!==null&&C!==void 0?C:"").trim()})},[])},d.createElement(rg.ItemSlot,{scope:n,value:r,disabled:o,textValue:m},d.createElement(Pe.div,Y({role:"option","aria-labelledby":S,"data-highlighted":g?"":void 0,"aria-selected":f&&g,"data-state":f?"checked":"unchecked","aria-disabled":o||void 0,"data-disabled":o?"":void 0,tabIndex:o?void 0:-1},s,{ref:b,onFocus:de(s.onFocus,()=>y(!0)),onBlur:de(s.onBlur,()=>y(!1)),onPointerUp:de(s.onPointerUp,E),onPointerMove:de(s.onPointerMove,_=>{if(o){var x;(x=u.onItemLeave)===null||x===void 0||x.call(u)}else _.currentTarget.focus({preventScroll:!0})}),onPointerLeave:de(s.onPointerLeave,_=>{if(_.currentTarget===document.activeElement){var x;(x=u.onItemLeave)===null||x===void 0||x.call(u)}}),onKeyDown:de(s.onKeyDown,_=>{var x;((x=u.searchRef)===null||x===void 0?void 0:x.current)!==""&&_.key===" "||(_G.includes(_.key)&&E(),_.key===" "&&_.preventDefault())})}))))}),bh="SelectItemText",YG=d.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,...i}=e,s=Fa(bh,n),l=ja(bh,n),u=c5(bh,n),f=RG(bh,n),[m,p]=d.useState(null),g=Be(t,_=>p(_),u.onItemTextChange,_=>{var x;return(x=l.itemTextRefCallback)===null||x===void 0?void 0:x.call(l,_,u.value,u.disabled)}),y=m==null?void 0:m.textContent,b=d.useMemo(()=>d.createElement("option",{key:u.value,value:u.value,disabled:u.disabled},y),[u.disabled,u.value,y]),{onNativeOptionAdd:S,onNativeOptionRemove:E}=f;return An(()=>(S(b),()=>E(b)),[S,E,b]),d.createElement(d.Fragment,null,d.createElement(Pe.span,Y({id:u.textId},i,{ref:g})),u.isSelected&&s.valueNode&&!s.valueNodeHasChildren?Is.createPortal(i.children,s.valueNode):null)}),XG="SelectItemIndicator",ZG=d.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return c5(XG,n).isSelected?d.createElement(Pe.span,Y({"aria-hidden":!0},r,{ref:t})):null}),g2="SelectScrollUpButton",qG=d.forwardRef((e,t)=>{const n=ja(g2,e.__scopeSelect),r=Ux(g2,e.__scopeSelect),[o,i]=d.useState(!1),s=Be(t,r.onScrollButtonChange);return An(()=>{if(n.viewport&&n.isPositioned){let f=function(){const m=u.scrollTop>0;i(m)};var l=f;const u=n.viewport;return f(),u.addEventListener("scroll",f),()=>u.removeEventListener("scroll",f)}},[n.viewport,n.isPositioned]),o?d.createElement(u5,Y({},e,{ref:s,onAutoScroll:()=>{const{viewport:l,selectedItem:u}=n;l&&u&&(l.scrollTop=l.scrollTop-u.offsetHeight)}})):null}),v2="SelectScrollDownButton",QG=d.forwardRef((e,t)=>{const n=ja(v2,e.__scopeSelect),r=Ux(v2,e.__scopeSelect),[o,i]=d.useState(!1),s=Be(t,r.onScrollButtonChange);return An(()=>{if(n.viewport&&n.isPositioned){let f=function(){const m=u.scrollHeight-u.clientHeight,p=Math.ceil(u.scrollTop)u.removeEventListener("scroll",f)}},[n.viewport,n.isPositioned]),o?d.createElement(u5,Y({},e,{ref:s,onAutoScroll:()=>{const{viewport:l,selectedItem:u}=n;l&&u&&(l.scrollTop=l.scrollTop+u.offsetHeight)}})):null}),u5=d.forwardRef((e,t)=>{const{__scopeSelect:n,onAutoScroll:r,...o}=e,i=ja("SelectScrollButton",n),s=d.useRef(null),l=og(n),u=d.useCallback(()=>{s.current!==null&&(window.clearInterval(s.current),s.current=null)},[]);return d.useEffect(()=>()=>u(),[u]),An(()=>{var f;const m=l().find(p=>p.ref.current===document.activeElement);m==null||(f=m.ref.current)===null||f===void 0||f.scrollIntoView({block:"nearest"})},[l]),d.createElement(Pe.div,Y({"aria-hidden":!0},o,{ref:t,style:{flexShrink:0,...o.style},onPointerDown:de(o.onPointerDown,()=>{s.current===null&&(s.current=window.setInterval(r,50))}),onPointerMove:de(o.onPointerMove,()=>{var f;(f=i.onItemLeave)===null||f===void 0||f.call(i),s.current===null&&(s.current=window.setInterval(r,50))}),onPointerLeave:de(o.onPointerLeave,()=>{u()})}))}),JG=d.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return d.createElement(Pe.div,Y({"aria-hidden":!0},r,{ref:t}))});function d5(e){return e===""||e===void 0}const f5=d.forwardRef((e,t)=>{const{value:n,...r}=e,o=d.useRef(null),i=Be(t,o),s=zx(n);return d.useEffect(()=>{const l=o.current,u=window.HTMLSelectElement.prototype,m=Object.getOwnPropertyDescriptor(u,"value").set;if(s!==n&&m){const p=new Event("change",{bubbles:!0});m.call(l,n),l.dispatchEvent(p)}},[s,n]),d.createElement(Hm,{asChild:!0},d.createElement("select",Y({},r,{ref:i,defaultValue:n})))});f5.displayName="BubbleSelect";function h5(e){const t=Ft(e),n=d.useRef(""),r=d.useRef(0),o=d.useCallback(s=>{const l=n.current+s;t(l),function u(f){n.current=f,window.clearTimeout(r.current),f!==""&&(r.current=window.setTimeout(()=>u(""),1e3))}(l)},[t]),i=d.useCallback(()=>{n.current="",window.clearTimeout(r.current)},[]);return d.useEffect(()=>()=>window.clearTimeout(r.current),[]),[n,o,i]}function p5(e,t,n){const o=t.length>1&&Array.from(t).every(f=>f===t[0])?t[0]:t,i=n?e.indexOf(n):-1;let s=eY(e,Math.max(i,0));o.length===1&&(s=s.filter(f=>f!==n));const u=s.find(f=>f.textValue.toLowerCase().startsWith(o.toLowerCase()));return u!==n?u:void 0}function eY(e,t){return e.map((n,r)=>e[(t+r)%e.length])}const tY=kG,m5=PG,nY=MG,rY=OG,oY=NG,g5=DG,iY=jG,sY=VG,v5=HG,y5=GG,aY=YG,lY=ZG,w5=qG,x5=QG,b5=JG,Uo=tY,vi=sY,Vo=nY,go=d.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(m5,{ref:r,className:Ce("flex h-9 w-full items-center justify-between whitespace-nowrap rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",e),tabIndex:-1,...n,children:[t,v.jsx(rY,{asChild:!0,children:v.jsx(Zj,{className:"h-4 w-4 opacity-50"})})]}));go.displayName=m5.displayName;const S5=d.forwardRef(({className:e,...t},n)=>v.jsx(w5,{ref:n,className:Ce("flex cursor-default items-center justify-center py-1",e),...t,children:v.jsx(rz,{})}));S5.displayName=w5.displayName;const _5=d.forwardRef(({className:e,...t},n)=>v.jsx(x5,{ref:n,className:Ce("flex cursor-default items-center justify-center py-1",e),...t,children:v.jsx(Jj,{})}));_5.displayName=x5.displayName;const vo=d.forwardRef(({className:e,children:t,position:n="popper",...r},o)=>v.jsx(oY,{children:v.jsxs(g5,{ref:o,className:Ce("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",n==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:n,onCloseAutoFocus:i=>i.preventDefault(),...r,children:[v.jsx(S5,{}),v.jsx(iY,{className:Ce("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),v.jsx(_5,{})]})}));vo.displayName=g5.displayName;const cY=d.forwardRef(({className:e,...t},n)=>v.jsx(v5,{ref:n,className:Ce("px-2 py-1.5 text-sm font-semibold",e),...t}));cY.displayName=v5.displayName;const yo=d.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(y5,{ref:r,className:Ce("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-2 pr-8 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[v.jsx("span",{className:"absolute right-2 flex h-3.5 w-3.5 items-center justify-center",children:v.jsx(lY,{children:v.jsx(yT,{className:"h-4 w-4"})})}),v.jsx(aY,{children:t})]}));yo.displayName=y5.displayName;const uY=d.forwardRef(({className:e,...t},n)=>v.jsx(b5,{ref:n,className:Ce("-mx-1 my-1 h-px bg-muted",e),...t}));uY.displayName=b5.displayName;function dY(e,t){return d.useReducer((n,r)=>{const o=t[n][r];return o??n},e)}const E5="ScrollArea",[C5,Ste]=Mn(E5),[fY,qr]=C5(E5),hY=d.forwardRef((e,t)=>{const{__scopeScrollArea:n,type:r="hover",dir:o,scrollHideDelay:i=600,...s}=e,[l,u]=d.useState(null),[f,m]=d.useState(null),[p,g]=d.useState(null),[y,b]=d.useState(null),[S,E]=d.useState(null),[_,x]=d.useState(0),[C,R]=d.useState(0),[P,M]=d.useState(!1),[A,D]=d.useState(!1),U=Be(t,q=>u(q)),W=Tc(o);return d.createElement(fY,{scope:n,type:r,dir:W,scrollHideDelay:i,scrollArea:l,viewport:f,onViewportChange:m,content:p,onContentChange:g,scrollbarX:y,onScrollbarXChange:b,scrollbarXEnabled:P,onScrollbarXEnabledChange:M,scrollbarY:S,onScrollbarYChange:E,scrollbarYEnabled:A,onScrollbarYEnabledChange:D,onCornerWidthChange:x,onCornerHeightChange:R},d.createElement(Pe.div,Y({dir:W},s,{ref:U,style:{position:"relative","--radix-scroll-area-corner-width":_+"px","--radix-scroll-area-corner-height":C+"px",...e.style}})))}),pY="ScrollAreaViewport",mY=d.forwardRef((e,t)=>{const{__scopeScrollArea:n,children:r,...o}=e,i=qr(pY,n),s=d.useRef(null),l=Be(t,s,i.onViewportChange);return d.createElement(d.Fragment,null,d.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}"}}),d.createElement(Pe.div,Y({"data-radix-scroll-area-viewport":""},o,{ref:l,style:{overflowX:i.scrollbarXEnabled?"scroll":"hidden",overflowY:i.scrollbarYEnabled?"scroll":"hidden",...e.style}}),d.createElement("div",{ref:i.onContentChange,style:{minWidth:"100%",display:"table"}},r)))}),Oi="ScrollAreaScrollbar",$5=d.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=qr(Oi,e.__scopeScrollArea),{onScrollbarXEnabledChange:i,onScrollbarYEnabledChange:s}=o,l=e.orientation==="horizontal";return d.useEffect(()=>(l?i(!0):s(!0),()=>{l?i(!1):s(!1)}),[l,i,s]),o.type==="hover"?d.createElement(gY,Y({},r,{ref:t,forceMount:n})):o.type==="scroll"?d.createElement(vY,Y({},r,{ref:t,forceMount:n})):o.type==="auto"?d.createElement(R5,Y({},r,{ref:t,forceMount:n})):o.type==="always"?d.createElement(Vx,Y({},r,{ref:t})):null}),gY=d.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=qr(Oi,e.__scopeScrollArea),[i,s]=d.useState(!1);return d.useEffect(()=>{const l=o.scrollArea;let u=0;if(l){const f=()=>{window.clearTimeout(u),s(!0)},m=()=>{u=window.setTimeout(()=>s(!1),o.scrollHideDelay)};return l.addEventListener("pointerenter",f),l.addEventListener("pointerleave",m),()=>{window.clearTimeout(u),l.removeEventListener("pointerenter",f),l.removeEventListener("pointerleave",m)}}},[o.scrollArea,o.scrollHideDelay]),d.createElement(Sn,{present:n||i},d.createElement(R5,Y({"data-state":i?"visible":"hidden"},r,{ref:t})))}),vY=d.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=qr(Oi,e.__scopeScrollArea),i=e.orientation==="horizontal",s=sg(()=>u("SCROLL_END"),100),[l,u]=dY("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 d.useEffect(()=>{if(l==="idle"){const f=window.setTimeout(()=>u("HIDE"),o.scrollHideDelay);return()=>window.clearTimeout(f)}},[l,o.scrollHideDelay,u]),d.useEffect(()=>{const f=o.viewport,m=i?"scrollLeft":"scrollTop";if(f){let p=f[m];const g=()=>{const y=f[m];p!==y&&(u("SCROLL"),s()),p=y};return f.addEventListener("scroll",g),()=>f.removeEventListener("scroll",g)}},[o.viewport,i,u,s]),d.createElement(Sn,{present:n||l!=="hidden"},d.createElement(Vx,Y({"data-state":l==="hidden"?"hidden":"visible"},r,{ref:t,onPointerEnter:de(e.onPointerEnter,()=>u("POINTER_ENTER")),onPointerLeave:de(e.onPointerLeave,()=>u("POINTER_LEAVE"))})))}),R5=d.forwardRef((e,t)=>{const n=qr(Oi,e.__scopeScrollArea),{forceMount:r,...o}=e,[i,s]=d.useState(!1),l=e.orientation==="horizontal",u=sg(()=>{if(n.viewport){const f=n.viewport.offsetWidth{const{orientation:n="vertical",...r}=e,o=qr(Oi,e.__scopeScrollArea),i=d.useRef(null),s=d.useRef(0),[l,u]=d.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),f=A5(l.viewport,l.content),m={...r,sizes:l,onSizesChange:u,hasThumb:f>0&&f<1,onThumbChange:g=>i.current=g,onThumbPointerUp:()=>s.current=0,onThumbPointerDown:g=>s.current=g};function p(g,y){return CY(g,s.current,l,y)}return n==="horizontal"?d.createElement(yY,Y({},m,{ref:t,onThumbPositionChange:()=>{if(o.viewport&&i.current){const g=o.viewport.scrollLeft,y=y2(g,l,o.dir);i.current.style.transform=`translate3d(${y}px, 0, 0)`}},onWheelScroll:g=>{o.viewport&&(o.viewport.scrollLeft=g)},onDragScroll:g=>{o.viewport&&(o.viewport.scrollLeft=p(g,o.dir))}})):n==="vertical"?d.createElement(wY,Y({},m,{ref:t,onThumbPositionChange:()=>{if(o.viewport&&i.current){const g=o.viewport.scrollTop,y=y2(g,l);i.current.style.transform=`translate3d(0, ${y}px, 0)`}},onWheelScroll:g=>{o.viewport&&(o.viewport.scrollTop=g)},onDragScroll:g=>{o.viewport&&(o.viewport.scrollTop=p(g))}})):null}),yY=d.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,i=qr(Oi,e.__scopeScrollArea),[s,l]=d.useState(),u=d.useRef(null),f=Be(t,u,i.onScrollbarXChange);return d.useEffect(()=>{u.current&&l(getComputedStyle(u.current))},[u]),d.createElement(T5,Y({"data-orientation":"horizontal"},o,{ref:f,sizes:n,style:{bottom:0,left:i.dir==="rtl"?"var(--radix-scroll-area-corner-width)":0,right:i.dir==="ltr"?"var(--radix-scroll-area-corner-width)":0,"--radix-scroll-area-thumb-width":ig(n)+"px",...e.style},onThumbPointerDown:m=>e.onThumbPointerDown(m.x),onDragScroll:m=>e.onDragScroll(m.x),onWheelScroll:(m,p)=>{if(i.viewport){const g=i.viewport.scrollLeft+m.deltaX;e.onWheelScroll(g),O5(g,p)&&m.preventDefault()}},onResize:()=>{u.current&&i.viewport&&s&&r({content:i.viewport.scrollWidth,viewport:i.viewport.offsetWidth,scrollbar:{size:u.current.clientWidth,paddingStart:Vp(s.paddingLeft),paddingEnd:Vp(s.paddingRight)}})}}))}),wY=d.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,i=qr(Oi,e.__scopeScrollArea),[s,l]=d.useState(),u=d.useRef(null),f=Be(t,u,i.onScrollbarYChange);return d.useEffect(()=>{u.current&&l(getComputedStyle(u.current))},[u]),d.createElement(T5,Y({"data-orientation":"vertical"},o,{ref:f,sizes:n,style:{top:0,right:i.dir==="ltr"?0:void 0,left:i.dir==="rtl"?0:void 0,bottom:"var(--radix-scroll-area-corner-height)","--radix-scroll-area-thumb-height":ig(n)+"px",...e.style},onThumbPointerDown:m=>e.onThumbPointerDown(m.y),onDragScroll:m=>e.onDragScroll(m.y),onWheelScroll:(m,p)=>{if(i.viewport){const g=i.viewport.scrollTop+m.deltaY;e.onWheelScroll(g),O5(g,p)&&m.preventDefault()}},onResize:()=>{u.current&&i.viewport&&s&&r({content:i.viewport.scrollHeight,viewport:i.viewport.offsetHeight,scrollbar:{size:u.current.clientHeight,paddingStart:Vp(s.paddingTop),paddingEnd:Vp(s.paddingBottom)}})}}))}),[xY,k5]=C5(Oi),T5=d.forwardRef((e,t)=>{const{__scopeScrollArea:n,sizes:r,hasThumb:o,onThumbChange:i,onThumbPointerUp:s,onThumbPointerDown:l,onThumbPositionChange:u,onDragScroll:f,onWheelScroll:m,onResize:p,...g}=e,y=qr(Oi,n),[b,S]=d.useState(null),E=Be(t,U=>S(U)),_=d.useRef(null),x=d.useRef(""),C=y.viewport,R=r.content-r.viewport,P=Ft(m),M=Ft(u),A=sg(p,10);function D(U){if(_.current){const W=U.clientX-_.current.left,q=U.clientY-_.current.top;f({x:W,y:q})}}return d.useEffect(()=>{const U=W=>{const q=W.target;(b==null?void 0:b.contains(q))&&P(W,R)};return document.addEventListener("wheel",U,{passive:!1}),()=>document.removeEventListener("wheel",U,{passive:!1})},[C,b,R,P]),d.useEffect(M,[r,M]),fc(b,A),fc(y.content,A),d.createElement(xY,{scope:n,scrollbar:b,hasThumb:o,onThumbChange:Ft(i),onThumbPointerUp:Ft(s),onThumbPositionChange:M,onThumbPointerDown:Ft(l)},d.createElement(Pe.div,Y({},g,{ref:E,style:{position:"absolute",...g.style},onPointerDown:de(e.onPointerDown,U=>{U.button===0&&(U.target.setPointerCapture(U.pointerId),_.current=b.getBoundingClientRect(),x.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",y.viewport&&(y.viewport.style.scrollBehavior="auto"),D(U))}),onPointerMove:de(e.onPointerMove,D),onPointerUp:de(e.onPointerUp,U=>{const W=U.target;W.hasPointerCapture(U.pointerId)&&W.releasePointerCapture(U.pointerId),document.body.style.webkitUserSelect=x.current,y.viewport&&(y.viewport.style.scrollBehavior=""),_.current=null})})))}),E1="ScrollAreaThumb",bY=d.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=k5(E1,e.__scopeScrollArea);return d.createElement(Sn,{present:n||o.hasThumb},d.createElement(SY,Y({ref:t},r)))}),SY=d.forwardRef((e,t)=>{const{__scopeScrollArea:n,style:r,...o}=e,i=qr(E1,n),s=k5(E1,n),{onThumbPositionChange:l}=s,u=Be(t,p=>s.onThumbChange(p)),f=d.useRef(),m=sg(()=>{f.current&&(f.current(),f.current=void 0)},100);return d.useEffect(()=>{const p=i.viewport;if(p){const g=()=>{if(m(),!f.current){const y=$Y(p,l);f.current=y,l()}};return l(),p.addEventListener("scroll",g),()=>p.removeEventListener("scroll",g)}},[i.viewport,m,l]),d.createElement(Pe.div,Y({"data-state":s.hasThumb?"visible":"hidden"},o,{ref:u,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...r},onPointerDownCapture:de(e.onPointerDownCapture,p=>{const y=p.target.getBoundingClientRect(),b=p.clientX-y.left,S=p.clientY-y.top;s.onThumbPointerDown({x:b,y:S})}),onPointerUp:de(e.onPointerUp,s.onThumbPointerUp)}))}),P5="ScrollAreaCorner",_Y=d.forwardRef((e,t)=>{const n=qr(P5,e.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?d.createElement(EY,Y({},e,{ref:t})):null}),EY=d.forwardRef((e,t)=>{const{__scopeScrollArea:n,...r}=e,o=qr(P5,n),[i,s]=d.useState(0),[l,u]=d.useState(0),f=!!(i&&l);return fc(o.scrollbarX,()=>{var m;const p=((m=o.scrollbarX)===null||m===void 0?void 0:m.offsetHeight)||0;o.onCornerHeightChange(p),u(p)}),fc(o.scrollbarY,()=>{var m;const p=((m=o.scrollbarY)===null||m===void 0?void 0:m.offsetWidth)||0;o.onCornerWidthChange(p),s(p)}),f?d.createElement(Pe.div,Y({},r,{ref:t,style:{width:i,height:l,position:"absolute",right:o.dir==="ltr"?0:void 0,left:o.dir==="rtl"?0:void 0,bottom:0,...e.style}})):null});function Vp(e){return e?parseInt(e,10):0}function A5(e,t){const n=e/t;return isNaN(n)?0:n}function ig(e){const t=A5(e.viewport,e.content),n=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,r=(e.scrollbar.size-n)*t;return Math.max(r,18)}function CY(e,t,n,r="ltr"){const o=ig(n),i=o/2,s=t||i,l=o-s,u=n.scrollbar.paddingStart+s,f=n.scrollbar.size-n.scrollbar.paddingEnd-l,m=n.content-n.viewport,p=r==="ltr"?[0,m]:[m*-1,0];return M5([u,f],p)(e)}function y2(e,t,n="ltr"){const r=ig(t),o=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,i=t.scrollbar.size-o,s=t.content-t.viewport,l=i-r,u=n==="ltr"?[0,s]:[s*-1,0],f=fd(e,u);return M5([0,s],[0,l])(f)}function M5(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 O5(e,t){return e>0&&e{})=>{let n={left:e.scrollLeft,top:e.scrollTop},r=0;return function o(){const i={left:e.scrollLeft,top:e.scrollTop},s=n.left!==i.left,l=n.top!==i.top;(s||l)&&t(),n=i,r=window.requestAnimationFrame(o)}(),()=>window.cancelAnimationFrame(r)};function sg(e,t){const n=Ft(e),r=d.useRef(0);return d.useEffect(()=>()=>window.clearTimeout(r.current),[]),d.useCallback(()=>{window.clearTimeout(r.current),r.current=window.setTimeout(n,t)},[n,t])}function fc(e,t){const n=Ft(t);An(()=>{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 N5=hY,RY=mY,kY=_Y,ag=d.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(N5,{ref:r,className:Ce("relative overflow-hidden",e),scrollHideDelay:400,...n,children:[v.jsx(RY,{className:"h-full w-full rounded-[inherit]",children:t}),v.jsx(D5,{}),v.jsx(kY,{})]}));ag.displayName=N5.displayName;const D5=d.forwardRef(({className:e,orientation:t="vertical",...n},r)=>v.jsx($5,{ref:r,orientation:t,className:Ce("flex touch-none select-none transition-colors",t==="vertical"&&"h-full w-2.5 border-l border-l-transparent p-[1px]",t==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",e),...n,children:v.jsx(bY,{className:"relative flex-1 rounded-full bg-border"})}));D5.displayName=$5.displayName;const I5="Name",L5="Created time",F5="Modified time",w2="input",TY="output",x2={[Es.NAME]:I5,[Es.CTIME]:L5,[Es.MTIME]:F5};function PY(e){const{onPhotoClick:t,photoWidth:n}=e,[r,o]=OP(!1),[i,s]=bt(W=>[W.fileManagerState,W.updateFileManagerState]),{toast:l}=Id(),[u,f]=d.useState(0),[m,p]=d.useState(0),g=d.useRef(null),y=lV(i.searchText,300),[b,S]=d.useState(w2),[E,_]=d.useState([]),[x,C]=d.useState([]),[R,P]=d.useState(0);Zn("f",()=>{o()}),Zn("left",()=>{let W=R;R>0&&(W=R-1),P(W),t(b,x[W].name)},[R,x]),Zn("right",()=>{let W=R;R{r||p(u)},[r,u]);const M=d.useCallback(W=>{W!==null&&r&&setTimeout(()=>{W.scrollTo({top:m,left:0})},100)},[r,m]);d.useEffect(()=>{(async()=>{try{const q=await Wj(b);_(q)}catch(q){l({variant:"destructive",title:"Uh oh! Something went wrong.",description:q.message?q.message:q.toString()})}})()},[b]),d.useEffect(()=>{if(!r)return;(async()=>{try{let q=E;y&&(q=new kc(q,{keys:["name"]}).search(y).map(F=>q[F.refIndex])),q=xH.orderBy(q,i.sortBy,i.sortOrder);const X=q.map(ae=>{const V=n,F=ae.height*(V/ae.width);return{src:`${Ls}/media_thumbnail_file?tab=${b}&filename=${encodeURIComponent(ae.name)}&width=${Math.ceil(V)}&height=${Math.ceil(F)}`,height:F,width:V,name:ae.name}});C(X)}catch(q){l({variant:"destructive",title:"Uh oh! Something went wrong.",description:q.message?q.message:q.toString()})}})()},[E,y,i,n,r]);const A=W=>{f(W.currentTarget.scrollTop)},D=({index:W})=>{o(),P(W),t(b,x[W].name)},U=()=>v.jsxs("div",{className:"flex justify-start items-center gap-[12px]",children:[v.jsx("div",{children:`Images (${x.length})`}),v.jsxs("div",{className:"flex",children:[v.jsx(yn,{tooltip:"Rows layout",onClick:()=>{s({layout:"rows"})},children:v.jsx(pz,{className:i.layout!=="rows"?"opacity-50":""})}),v.jsx(yn,{tooltip:"Grid layout",onClick:()=>{s({layout:"masonry"})},children:v.jsx(fz,{className:i.layout!=="masonry"?"opacity-50":""})})]})]});return v.jsxs(Jm,{open:r,onOpenChange:o,children:[v.jsx(fP,{asChild:!0,children:v.jsx(yn,{tooltip:"File Manager",children:v.jsx(eV,{})})}),v.jsxs(Hd,{className:"h-4/5 max-w-6xl",children:[v.jsx(Kd,{children:U()}),v.jsxs("div",{className:"flex justify-between gap-8 items-center",children:[v.jsxs("div",{className:"flex relative justify-start items-center",children:[v.jsx(lz,{className:"absolute left-[8px]"}),v.jsx(Ld,{ref:g,value:i.searchText,className:"w-[250px] pl-[30px]",tabIndex:-1,onInput:W=>{W.preventDefault(),W.stopPropagation();const q=W.target;s({searchText:q.value})},placeholder:"Search by file name"})]}),v.jsx(a5,{defaultValue:b,onValueChange:W=>S(W),children:v.jsxs(jx,{"aria-label":"Manage your account",children:[v.jsx(pa,{value:w2,children:"Image Directory"}),v.jsx(pa,{value:TY,children:"Output Directory"})]})}),v.jsx("div",{className:"flex gap-2",children:v.jsxs("div",{className:"flex gap-1",children:[v.jsxs(Uo,{value:x2[i.sortBy],onValueChange:W=>{switch(W){case I5:s({sortBy:Es.NAME});break;case L5:s({sortBy:Es.CTIME});break;case F5:s({sortBy:Es.MTIME});break}},children:[v.jsx(go,{className:"w-[140px]",children:v.jsx(Vo,{})}),v.jsx(vo,{children:Object.values(x2).map(W=>v.jsx(yo,{value:W,children:W},W))})]}),i.sortOrder===Ou.DESCENDING?v.jsx(yn,{tooltip:"Descending Order",onClick:()=>{s({sortOrder:Ou.ASCENDING})},children:v.jsx(iK,{})}):v.jsx(yn,{tooltip:"Ascending Order",onClick:()=>{s({sortOrder:Ou.DESCENDING})},children:v.jsx(lK,{})})]})})]}),v.jsx(ag,{className:"w-full h-full rounded-md",onScroll:A,ref:M,children:v.jsx(nK,{layout:i.layout,photos:x,spacing:12,padding:0,onClick:D})})]})]})}var Yd=e=>e.type==="checkbox",$l=e=>e instanceof Date,Fn=e=>e==null;const j5=e=>typeof e=="object";var sn=e=>!Fn(e)&&!Array.isArray(e)&&j5(e)&&!$l(e),z5=e=>sn(e)&&e.target?Yd(e.target)?e.target.checked:e.target.value:e,AY=e=>e.substring(0,e.search(/\.\d+(\.|$)/))||e,B5=(e,t)=>e.has(AY(t)),MY=e=>{const t=e.constructor&&e.constructor.prototype;return sn(t)&&t.hasOwnProperty("isPrototypeOf")},Wx=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function so(e){let t;const n=Array.isArray(e);if(e instanceof Date)t=new Date(e);else if(e instanceof Set)t=new Set(e);else if(!(Wx&&(e instanceof Blob||e instanceof FileList))&&(n||sn(e)))if(t=n?[]:{},!n&&!MY(e))t=e;else for(const r in e)e.hasOwnProperty(r)&&(t[r]=so(e[r]));else return e;return t}var Xd=e=>Array.isArray(e)?e.filter(Boolean):[],Ht=e=>e===void 0,ve=(e,t,n)=>{if(!t||!sn(e))return n;const r=Xd(t.split(/[,[\].]+?/)).reduce((o,i)=>Fn(o)?o:o[i],e);return Ht(r)||r===e?Ht(e[t])?n:e[t]:r},Fo=e=>typeof e=="boolean";const Wp={BLUR:"blur",FOCUS_OUT:"focusout",CHANGE:"change"},mo={onBlur:"onBlur",onChange:"onChange",onSubmit:"onSubmit",onTouched:"onTouched",all:"all"},ui={max:"max",min:"min",maxLength:"maxLength",minLength:"minLength",pattern:"pattern",required:"required",validate:"validate"},U5=Fe.createContext(null),lg=()=>Fe.useContext(U5),OY=e=>{const{children:t,...n}=e;return Fe.createElement(U5.Provider,{value:n},t)};var V5=(e,t,n,r=!0)=>{const o={defaultValues:t._defaultValues};for(const i in e)Object.defineProperty(o,i,{get:()=>{const s=i;return t._proxyFormState[s]!==mo.all&&(t._proxyFormState[s]=!r||mo.all),n&&(n[s]=!0),e[s]}});return o},Fr=e=>sn(e)&&!Object.keys(e).length,W5=(e,t,n,r)=>{n(e);const{name:o,...i}=e;return Fr(i)||Object.keys(i).length>=Object.keys(t).length||Object.keys(i).find(s=>t[s]===(!r||mo.all))},ep=e=>Array.isArray(e)?e:[e],H5=(e,t,n)=>!e||!t||e===t||ep(e).some(r=>r&&(n?r===t:r.startsWith(t)||t.startsWith(r)));function Hx(e){const t=Fe.useRef(e);t.current=e,Fe.useEffect(()=>{const n=!e.disabled&&t.current.subject&&t.current.subject.subscribe({next:t.current.next});return()=>{n&&n.unsubscribe()}},[e.disabled])}function NY(e){const t=lg(),{control:n=t.control,disabled:r,name:o,exact:i}=e||{},[s,l]=Fe.useState(n._formState),u=Fe.useRef(!0),f=Fe.useRef({isDirty:!1,isLoading:!1,dirtyFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1}),m=Fe.useRef(o);return m.current=o,Hx({disabled:r,next:p=>u.current&&H5(m.current,p.name,i)&&W5(p,f.current,n._updateFormState)&&l({...n._formState,...p}),subject:n._subjects.state}),Fe.useEffect(()=>(u.current=!0,f.current.isValid&&n._updateValid(!0),()=>{u.current=!1}),[n]),V5(s,n,f.current,!1)}var Wo=e=>typeof e=="string",K5=(e,t,n,r,o)=>Wo(e)?(r&&t.watch.add(e),ve(n,e,o)):Array.isArray(e)?e.map(i=>(r&&t.watch.add(i),ve(n,i))):(r&&(t.watchAll=!0),n);function DY(e){const t=lg(),{control:n=t.control,name:r,defaultValue:o,disabled:i,exact:s}=e||{},l=Fe.useRef(r);l.current=r,Hx({disabled:i,subject:n._subjects.values,next:m=>{H5(l.current,m.name,s)&&f(so(K5(l.current,n._names,m.values||n._formValues,!1,o)))}});const[u,f]=Fe.useState(n._getWatch(r,o));return Fe.useEffect(()=>n._removeUnmounted()),u}var Kx=e=>/^\w*$/.test(e),G5=e=>Xd(e.replace(/["|']|\]/g,"").split(/\.|\[/));function wt(e,t,n){let r=-1;const o=Kx(t)?[t]:G5(t),i=o.length,s=i-1;for(;++r{const m=o._options.shouldUnregister||i,p=(g,y)=>{const b=ve(o._fields,g);b&&(b._f.mount=y)};if(p(n,!0),m){const g=so(ve(o._options.defaultValues,n));wt(o._defaultValues,n,g),Ht(ve(o._formValues,n))&&wt(o._formValues,n,g)}return()=>{(s?m&&!o._state.action:m)?o.unregister(n):p(n,!1)}},[n,o,s,i]),Fe.useEffect(()=>{ve(o._fields,n)&&o._updateDisabledField({disabled:r,fields:o._fields,name:n,value:ve(o._fields,n)._f.value})},[r,n,o]),{field:{name:n,value:l,...Fo(r)||Fo(u.disabled)?{disabled:u.disabled||r}:{},onChange:Fe.useCallback(m=>f.current.onChange({target:{value:z5(m),name:n},type:Wp.CHANGE}),[n]),onBlur:Fe.useCallback(()=>f.current.onBlur({target:{value:ve(o._formValues,n),name:n},type:Wp.BLUR}),[n,o]),ref:m=>{const p=ve(o._fields,n);p&&m&&(p._f.ref={focus:()=>m.focus(),select:()=>m.select(),setCustomValidity:g=>m.setCustomValidity(g),reportValidity:()=>m.reportValidity()})}},formState:u,fieldState:Object.defineProperties({},{invalid:{enumerable:!0,get:()=>!!ve(u.errors,n)},isDirty:{enumerable:!0,get:()=>!!ve(u.dirtyFields,n)},isTouched:{enumerable:!0,get:()=>!!ve(u.touchedFields,n)},error:{enumerable:!0,get:()=>ve(u.errors,n)}})}}const LY=e=>e.render(IY(e));var Y5=(e,t,n,r,o)=>t?{...n[e],types:{...n[e]&&n[e].types?n[e].types:{},[r]:o||!0}}:{},b2=e=>({isOnSubmit:!e||e===mo.onSubmit,isOnBlur:e===mo.onBlur,isOnChange:e===mo.onChange,isOnAll:e===mo.all,isOnTouch:e===mo.onTouched}),S2=(e,t,n)=>!n&&(t.watchAll||t.watch.has(e)||[...t.watch].some(r=>e.startsWith(r)&&/^\.\w+/.test(e.slice(r.length))));const tp=(e,t,n,r)=>{for(const o of n||Object.keys(e)){const i=ve(e,o);if(i){const{_f:s,...l}=i;if(s){if(s.refs&&s.refs[0]&&t(s.refs[0],o)&&!r)break;if(s.ref&&t(s.ref,s.name)&&!r)break}else sn(l)&&tp(l,t)}}};var FY=(e,t,n)=>{const r=Xd(ve(e,n));return wt(r,"root",t[n]),wt(e,n,r),e},Gx=e=>e.type==="file",ms=e=>typeof e=="function",Hp=e=>{if(!Wx)return!1;const t=e?e.ownerDocument:0;return e instanceof(t&&t.defaultView?t.defaultView.HTMLElement:HTMLElement)},np=e=>Wo(e),Yx=e=>e.type==="radio",Kp=e=>e instanceof RegExp;const _2={value:!1,isValid:!1},E2={value:!0,isValid:!0};var X5=e=>{if(Array.isArray(e)){if(e.length>1){const t=e.filter(n=>n&&n.checked&&!n.disabled).map(n=>n.value);return{value:t,isValid:!!t.length}}return e[0].checked&&!e[0].disabled?e[0].attributes&&!Ht(e[0].attributes.value)?Ht(e[0].value)||e[0].value===""?E2:{value:e[0].value,isValid:!0}:E2:_2}return _2};const C2={isValid:!1,value:null};var Z5=e=>Array.isArray(e)?e.reduce((t,n)=>n&&n.checked&&!n.disabled?{isValid:!0,value:n.value}:t,C2):C2;function $2(e,t,n="validate"){if(np(e)||Array.isArray(e)&&e.every(np)||Fo(e)&&!e)return{type:n,message:np(e)?e:"",ref:t}}var sl=e=>sn(e)&&!Kp(e)?e:{value:e,message:""},R2=async(e,t,n,r,o)=>{const{ref:i,refs:s,required:l,maxLength:u,minLength:f,min:m,max:p,pattern:g,validate:y,name:b,valueAsNumber:S,mount:E,disabled:_}=e._f,x=ve(t,b);if(!E||_)return{};const C=s?s[0]:i,R=X=>{r&&C.reportValidity&&(C.setCustomValidity(Fo(X)?"":X||""),C.reportValidity())},P={},M=Yx(i),A=Yd(i),D=M||A,U=(S||Gx(i))&&Ht(i.value)&&Ht(x)||Hp(i)&&i.value===""||x===""||Array.isArray(x)&&!x.length,W=Y5.bind(null,b,n,P),q=(X,ae,V,F=ui.maxLength,N=ui.minLength)=>{const ie=X?ae:V;P[b]={type:X?F:N,message:ie,ref:i,...W(X?F:N,ie)}};if(o?!Array.isArray(x)||!x.length:l&&(!D&&(U||Fn(x))||Fo(x)&&!x||A&&!X5(s).isValid||M&&!Z5(s).isValid)){const{value:X,message:ae}=np(l)?{value:!!l,message:l}:sl(l);if(X&&(P[b]={type:ui.required,message:ae,ref:C,...W(ui.required,ae)},!n))return R(ae),P}if(!U&&(!Fn(m)||!Fn(p))){let X,ae;const V=sl(p),F=sl(m);if(!Fn(x)&&!isNaN(x)){const N=i.valueAsNumber||x&&+x;Fn(V.value)||(X=N>V.value),Fn(F.value)||(ae=Nnew Date(new Date().toDateString()+" "+H),K=i.type=="time",Z=i.type=="week";Wo(V.value)&&x&&(X=K?ie(x)>ie(V.value):Z?x>V.value:N>new Date(V.value)),Wo(F.value)&&x&&(ae=K?ie(x)+X.value,F=!Fn(ae.value)&&x.length<+ae.value;if((V||F)&&(q(V,X.message,ae.message),!n))return R(P[b].message),P}if(g&&!U&&Wo(x)){const{value:X,message:ae}=sl(g);if(Kp(X)&&!x.match(X)&&(P[b]={type:ui.pattern,message:ae,ref:i,...W(ui.pattern,ae)},!n))return R(ae),P}if(y){if(ms(y)){const X=await y(x,t),ae=$2(X,C);if(ae&&(P[b]={...ae,...W(ui.validate,ae.message)},!n))return R(ae.message),P}else if(sn(y)){let X={};for(const ae in y){if(!Fr(X)&&!n)break;const V=$2(await y[ae](x,t),C,ae);V&&(X={...V,...W(ae,V.message)},R(V.message),n&&(P[b]=X))}if(!Fr(X)&&(P[b]={ref:C,...X},!n))return P}}return R(!0),P};function jY(e,t){const n=t.slice(0,-1).length;let r=0;for(;r{for(const i of e)i.next&&i.next(o)},subscribe:o=>(e.push(o),{unsubscribe:()=>{e=e.filter(i=>i!==o)}}),unsubscribe:()=>{e=[]}}}var Gp=e=>Fn(e)||!j5(e);function ma(e,t){if(Gp(e)||Gp(t))return e===t;if($l(e)&&$l(t))return e.getTime()===t.getTime();const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(const o of n){const i=e[o];if(!r.includes(o))return!1;if(o!=="ref"){const s=t[o];if($l(i)&&$l(s)||sn(i)&&sn(s)||Array.isArray(i)&&Array.isArray(s)?!ma(i,s):i!==s)return!1}}return!0}var q5=e=>e.type==="select-multiple",BY=e=>Yx(e)||Yd(e),N0=e=>Hp(e)&&e.isConnected,Q5=e=>{for(const t in e)if(ms(e[t]))return!0;return!1};function Yp(e,t={}){const n=Array.isArray(e);if(sn(e)||n)for(const r in e)Array.isArray(e[r])||sn(e[r])&&!Q5(e[r])?(t[r]=Array.isArray(e[r])?[]:{},Yp(e[r],t[r])):Fn(e[r])||(t[r]=!0);return t}function J5(e,t,n){const r=Array.isArray(e);if(sn(e)||r)for(const o in e)Array.isArray(e[o])||sn(e[o])&&!Q5(e[o])?Ht(t)||Gp(n[o])?n[o]=Array.isArray(e[o])?Yp(e[o],[]):{...Yp(e[o])}:J5(e[o],Fn(t)?{}:t[o],n[o]):n[o]=!ma(e[o],t[o]);return n}var D0=(e,t)=>J5(e,t,Yp(t)),e3=(e,{valueAsNumber:t,valueAsDate:n,setValueAs:r})=>Ht(e)?e:t?e===""?NaN:e&&+e:n&&Wo(e)?new Date(e):r?r(e):e;function I0(e){const t=e.ref;if(!(e.refs?e.refs.every(n=>n.disabled):t.disabled))return Gx(t)?t.files:Yx(t)?Z5(e.refs).value:q5(t)?[...t.selectedOptions].map(({value:n})=>n):Yd(t)?X5(e.refs).value:e3(Ht(t.value)?e.ref.value:t.value,e)}var UY=(e,t,n,r)=>{const o={};for(const i of e){const s=ve(t,i);s&&wt(o,i,s._f)}return{criteriaMode:n,names:[...e],fields:o,shouldUseNativeValidation:r}},du=e=>Ht(e)?e:Kp(e)?e.source:sn(e)?Kp(e.value)?e.value.source:e.value:e,VY=e=>e.mount&&(e.required||e.min||e.max||e.maxLength||e.minLength||e.pattern||e.validate);function k2(e,t,n){const r=ve(e,n);if(r||Kx(n))return{error:r,name:n};const o=n.split(".");for(;o.length;){const i=o.join("."),s=ve(t,i),l=ve(e,i);if(s&&!Array.isArray(s)&&n!==i)return{name:n};if(l&&l.type)return{name:i,error:l};o.pop()}return{name:n}}var WY=(e,t,n,r,o)=>o.isOnAll?!1:!n&&o.isOnTouch?!(t||e):(n?r.isOnBlur:o.isOnBlur)?!e:(n?r.isOnChange:o.isOnChange)?e:!0,HY=(e,t)=>!Xd(ve(e,t)).length&&pn(e,t);const KY={mode:mo.onSubmit,reValidateMode:mo.onChange,shouldFocusError:!0};function GY(e={},t){let n={...KY,...e},r={submitCount:0,isDirty:!1,isLoading:ms(n.defaultValues),isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},errors:{},disabled:!1},o={},i=sn(n.defaultValues)||sn(n.values)?so(n.defaultValues||n.values)||{}:{},s=n.shouldUnregister?{}:so(i),l={action:!1,mount:!1,watch:!1},u={mount:new Set,unMount:new Set,array:new Set,watch:new Set},f,m=0;const p={isDirty:!1,dirtyFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1},g={values:O0(),array:O0(),state:O0()},y=e.resetOptions&&e.resetOptions.keepDirtyValues,b=b2(n.mode),S=b2(n.reValidateMode),E=n.criteriaMode===mo.all,_=L=>Q=>{clearTimeout(m),m=setTimeout(L,Q)},x=async L=>{if(p.isValid||L){const Q=n.resolver?Fr((await U()).errors):await q(o,!0);Q!==r.isValid&&g.state.next({isValid:Q})}},C=L=>p.isValidating&&g.state.next({isValidating:L}),R=(L,Q=[],J,we,me=!0,fe=!0)=>{if(we&&J){if(l.action=!0,fe&&Array.isArray(ve(o,L))){const Re=J(ve(o,L),we.argA,we.argB);me&&wt(o,L,Re)}if(fe&&Array.isArray(ve(r.errors,L))){const Re=J(ve(r.errors,L),we.argA,we.argB);me&&wt(r.errors,L,Re),HY(r.errors,L)}if(p.touchedFields&&fe&&Array.isArray(ve(r.touchedFields,L))){const Re=J(ve(r.touchedFields,L),we.argA,we.argB);me&&wt(r.touchedFields,L,Re)}p.dirtyFields&&(r.dirtyFields=D0(i,s)),g.state.next({name:L,isDirty:ae(L,Q),dirtyFields:r.dirtyFields,errors:r.errors,isValid:r.isValid})}else wt(s,L,Q)},P=(L,Q)=>{wt(r.errors,L,Q),g.state.next({errors:r.errors})},M=(L,Q,J,we)=>{const me=ve(o,L);if(me){const fe=ve(s,L,Ht(J)?ve(i,L):J);Ht(fe)||we&&we.defaultChecked||Q?wt(s,L,Q?fe:I0(me._f)):N(L,fe),l.mount&&x()}},A=(L,Q,J,we,me)=>{let fe=!1,Re=!1;const ft={name:L};if(!J||we){p.isDirty&&(Re=r.isDirty,r.isDirty=ft.isDirty=ae(),fe=Re!==ft.isDirty);const ht=ma(ve(i,L),Q);Re=ve(r.dirtyFields,L),ht?pn(r.dirtyFields,L):wt(r.dirtyFields,L,!0),ft.dirtyFields=r.dirtyFields,fe=fe||p.dirtyFields&&Re!==!ht}if(J){const ht=ve(r.touchedFields,L);ht||(wt(r.touchedFields,L,J),ft.touchedFields=r.touchedFields,fe=fe||p.touchedFields&&ht!==J)}return fe&&me&&g.state.next(ft),fe?ft:{}},D=(L,Q,J,we)=>{const me=ve(r.errors,L),fe=p.isValid&&Fo(Q)&&r.isValid!==Q;if(e.delayError&&J?(f=_(()=>P(L,J)),f(e.delayError)):(clearTimeout(m),f=null,J?wt(r.errors,L,J):pn(r.errors,L)),(J?!ma(me,J):me)||!Fr(we)||fe){const Re={...we,...fe&&Fo(Q)?{isValid:Q}:{},errors:r.errors,name:L};r={...r,...Re},g.state.next(Re)}C(!1)},U=async L=>n.resolver(s,n.context,UY(L||u.mount,o,n.criteriaMode,n.shouldUseNativeValidation)),W=async L=>{const{errors:Q}=await U(L);if(L)for(const J of L){const we=ve(Q,J);we?wt(r.errors,J,we):pn(r.errors,J)}else r.errors=Q;return Q},q=async(L,Q,J={valid:!0})=>{for(const we in L){const me=L[we];if(me){const{_f:fe,...Re}=me;if(fe){const ft=u.array.has(fe.name),ht=await R2(me,s,E,n.shouldUseNativeValidation&&!Q,ft);if(ht[fe.name]&&(J.valid=!1,Q))break;!Q&&(ve(ht,fe.name)?ft?FY(r.errors,ht,fe.name):wt(r.errors,fe.name,ht[fe.name]):pn(r.errors,fe.name))}Re&&await q(Re,Q,J)}}return J.valid},X=()=>{for(const L of u.unMount){const Q=ve(o,L);Q&&(Q._f.refs?Q._f.refs.every(J=>!N0(J)):!N0(Q._f.ref))&&he(L)}u.unMount=new Set},ae=(L,Q)=>(L&&Q&&wt(s,L,Q),!ma(ce(),i)),V=(L,Q,J)=>K5(L,u,{...l.mount?s:Ht(Q)?i:Wo(L)?{[L]:Q}:Q},J,Q),F=L=>Xd(ve(l.mount?s:i,L,e.shouldUnregister?ve(i,L,[]):[])),N=(L,Q,J={})=>{const we=ve(o,L);let me=Q;if(we){const fe=we._f;fe&&(!fe.disabled&&wt(s,L,e3(Q,fe)),me=Hp(fe.ref)&&Fn(Q)?"":Q,q5(fe.ref)?[...fe.ref.options].forEach(Re=>Re.selected=me.includes(Re.value)):fe.refs?Yd(fe.ref)?fe.refs.length>1?fe.refs.forEach(Re=>(!Re.defaultChecked||!Re.disabled)&&(Re.checked=Array.isArray(me)?!!me.find(ft=>ft===Re.value):me===Re.value)):fe.refs[0]&&(fe.refs[0].checked=!!me):fe.refs.forEach(Re=>Re.checked=Re.value===me):Gx(fe.ref)?fe.ref.value="":(fe.ref.value=me,fe.ref.type||g.values.next({name:L,values:{...s}})))}(J.shouldDirty||J.shouldTouch)&&A(L,me,J.shouldTouch,J.shouldDirty,!0),J.shouldValidate&&se(L)},ie=(L,Q,J)=>{for(const we in Q){const me=Q[we],fe=`${L}.${we}`,Re=ve(o,fe);(u.array.has(L)||!Gp(me)||Re&&!Re._f)&&!$l(me)?ie(fe,me,J):N(fe,me,J)}},K=(L,Q,J={})=>{const we=ve(o,L),me=u.array.has(L),fe=so(Q);wt(s,L,fe),me?(g.array.next({name:L,values:{...s}}),(p.isDirty||p.dirtyFields)&&J.shouldDirty&&g.state.next({name:L,dirtyFields:D0(i,s),isDirty:ae(L,fe)})):we&&!we._f&&!Fn(fe)?ie(L,fe,J):N(L,fe,J),S2(L,u)&&g.state.next({...r}),g.values.next({name:L,values:{...s}}),!l.mount&&t()},Z=async L=>{const Q=L.target;let J=Q.name,we=!0;const me=ve(o,J),fe=()=>Q.type?I0(me._f):z5(L),Re=ft=>{we=Number.isNaN(ft)||ft===ve(s,J,ft)};if(me){let ft,ht;const _n=fe(),Cr=L.type===Wp.BLUR||L.type===Wp.FOCUS_OUT,Ni=!VY(me._f)&&!n.resolver&&!ve(r.errors,J)&&!me._f.deps||WY(Cr,ve(r.touchedFields,J),r.isSubmitted,S,b),Co=S2(J,u,Cr);wt(s,J,_n),Cr?(me._f.onBlur&&me._f.onBlur(L),f&&f(0)):me._f.onChange&&me._f.onChange(L);const Vn=A(J,_n,Cr,!1),Ba=!Fr(Vn)||Co;if(!Cr&&g.values.next({name:J,type:L.type,values:{...s}}),Ni)return p.isValid&&x(),Ba&&g.state.next({name:J,...Co?{}:Vn});if(!Cr&&Co&&g.state.next({...r}),C(!0),n.resolver){const{errors:Di}=await U([J]);if(Re(_n),we){const Ws=k2(r.errors,o,J),Ii=k2(Di,o,Ws.name||J);ft=Ii.error,J=Ii.name,ht=Fr(Di)}}else ft=(await R2(me,s,E,n.shouldUseNativeValidation))[J],Re(_n),we&&(ft?ht=!1:p.isValid&&(ht=await q(o,!0)));we&&(me._f.deps&&se(me._f.deps),D(J,ht,ft,Vn))}},H=(L,Q)=>{if(ve(r.errors,Q)&&L.focus)return L.focus(),1},se=async(L,Q={})=>{let J,we;const me=ep(L);if(C(!0),n.resolver){const fe=await W(Ht(L)?L:me);J=Fr(fe),we=L?!me.some(Re=>ve(fe,Re)):J}else L?(we=(await Promise.all(me.map(async fe=>{const Re=ve(o,fe);return await q(Re&&Re._f?{[fe]:Re}:Re)}))).every(Boolean),!(!we&&!r.isValid)&&x()):we=J=await q(o);return g.state.next({...!Wo(L)||p.isValid&&J!==r.isValid?{}:{name:L},...n.resolver||!L?{isValid:J}:{},errors:r.errors,isValidating:!1}),Q.shouldFocus&&!we&&tp(o,H,L?me:u.mount),we},ce=L=>{const Q={...i,...l.mount?s:{}};return Ht(L)?Q:Wo(L)?ve(Q,L):L.map(J=>ve(Q,J))},Ve=(L,Q)=>({invalid:!!ve((Q||r).errors,L),isDirty:!!ve((Q||r).dirtyFields,L),isTouched:!!ve((Q||r).touchedFields,L),error:ve((Q||r).errors,L)}),Ue=L=>{L&&ep(L).forEach(Q=>pn(r.errors,Q)),g.state.next({errors:L?r.errors:{}})},We=(L,Q,J)=>{const we=(ve(o,L,{_f:{}})._f||{}).ref;wt(r.errors,L,{...Q,ref:we}),g.state.next({name:L,errors:r.errors,isValid:!1}),J&&J.shouldFocus&&we&&we.focus&&we.focus()},Oe=(L,Q)=>ms(L)?g.values.subscribe({next:J=>L(V(void 0,Q),J)}):V(L,Q,!0),he=(L,Q={})=>{for(const J of L?ep(L):u.mount)u.mount.delete(J),u.array.delete(J),Q.keepValue||(pn(o,J),pn(s,J)),!Q.keepError&&pn(r.errors,J),!Q.keepDirty&&pn(r.dirtyFields,J),!Q.keepTouched&&pn(r.touchedFields,J),!n.shouldUnregister&&!Q.keepDefaultValue&&pn(i,J);g.values.next({values:{...s}}),g.state.next({...r,...Q.keepDirty?{isDirty:ae()}:{}}),!Q.keepIsValid&&x()},xe=({disabled:L,name:Q,field:J,fields:we,value:me})=>{if(Fo(L)){const fe=L?void 0:Ht(me)?I0(J?J._f:ve(we,Q)._f):me;wt(s,Q,fe),A(Q,fe,!1,!1,!0)}},$e=(L,Q={})=>{let J=ve(o,L);const we=Fo(Q.disabled);return wt(o,L,{...J||{},_f:{...J&&J._f?J._f:{ref:{name:L}},name:L,mount:!0,...Q}}),u.mount.add(L),J?xe({field:J,disabled:Q.disabled,name:L}):M(L,!0,Q.value),{...we?{disabled:Q.disabled}:{},...n.progressive?{required:!!Q.required,min:du(Q.min),max:du(Q.max),minLength:du(Q.minLength),maxLength:du(Q.maxLength),pattern:du(Q.pattern)}:{},name:L,onChange:Z,onBlur:Z,ref:me=>{if(me){$e(L,Q),J=ve(o,L);const fe=Ht(me.value)&&me.querySelectorAll&&me.querySelectorAll("input,select,textarea")[0]||me,Re=BY(fe),ft=J._f.refs||[];if(Re?ft.find(ht=>ht===fe):fe===J._f.ref)return;wt(o,L,{_f:{...J._f,...Re?{refs:[...ft.filter(N0),fe,...Array.isArray(ve(i,L))?[{}]:[]],ref:{type:fe.type,name:L}}:{ref:fe}}}),M(L,!1,void 0,fe)}else J=ve(o,L,{}),J._f&&(J._f.mount=!1),(n.shouldUnregister||Q.shouldUnregister)&&!(B5(u.array,L)&&l.action)&&u.unMount.add(L)}}},Ae=()=>n.shouldFocusError&&tp(o,H,u.mount),Me=L=>{Fo(L)&&(g.state.next({disabled:L}),tp(o,Q=>{Q.disabled=L},0,!1))},je=(L,Q)=>async J=>{J&&(J.preventDefault&&J.preventDefault(),J.persist&&J.persist());let we=so(s);if(g.state.next({isSubmitting:!0}),n.resolver){const{errors:me,values:fe}=await U();r.errors=me,we=fe}else await q(o);pn(r.errors,"root"),Fr(r.errors)?(g.state.next({errors:{}}),await L(we,J)):(Q&&await Q({...r.errors},J),Ae(),setTimeout(Ae)),g.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:Fr(r.errors),submitCount:r.submitCount+1,errors:r.errors})},Mt=(L,Q={})=>{ve(o,L)&&(Ht(Q.defaultValue)?K(L,ve(i,L)):(K(L,Q.defaultValue),wt(i,L,Q.defaultValue)),Q.keepTouched||pn(r.touchedFields,L),Q.keepDirty||(pn(r.dirtyFields,L),r.isDirty=Q.defaultValue?ae(L,ve(i,L)):ae()),Q.keepError||(pn(r.errors,L),p.isValid&&x()),g.state.next({...r}))},ct=(L,Q={})=>{const J=L?so(L):i,we=so(J),me=L&&!Fr(L)?we:i;if(Q.keepDefaultValues||(i=J),!Q.keepValues){if(Q.keepDirtyValues||y)for(const fe of u.mount)ve(r.dirtyFields,fe)?wt(me,fe,ve(s,fe)):K(fe,ve(me,fe));else{if(Wx&&Ht(L))for(const fe of u.mount){const Re=ve(o,fe);if(Re&&Re._f){const ft=Array.isArray(Re._f.refs)?Re._f.refs[0]:Re._f.ref;if(Hp(ft)){const ht=ft.closest("form");if(ht){ht.reset();break}}}}o={}}s=e.shouldUnregister?Q.keepDefaultValues?so(i):{}:so(me),g.array.next({values:{...me}}),g.values.next({values:{...me}})}u={mount:new Set,unMount:new Set,array:new Set,watch:new Set,watchAll:!1,focus:""},!l.mount&&t(),l.mount=!p.isValid||!!Q.keepIsValid,l.watch=!!e.shouldUnregister,g.state.next({submitCount:Q.keepSubmitCount?r.submitCount:0,isDirty:Q.keepDirty?r.isDirty:!!(Q.keepDefaultValues&&!ma(L,i)),isSubmitted:Q.keepIsSubmitted?r.isSubmitted:!1,dirtyFields:Q.keepDirtyValues?r.dirtyFields:Q.keepDefaultValues&&L?D0(i,L):{},touchedFields:Q.keepTouched?r.touchedFields:{},errors:Q.keepErrors?r.errors:{},isSubmitSuccessful:Q.keepIsSubmitSuccessful?r.isSubmitSuccessful:!1,isSubmitting:!1})},Kt=(L,Q)=>ct(ms(L)?L(s):L,Q);return{control:{register:$e,unregister:he,getFieldState:Ve,handleSubmit:je,setError:We,_executeSchema:U,_getWatch:V,_getDirty:ae,_updateValid:x,_removeUnmounted:X,_updateFieldArray:R,_updateDisabledField:xe,_getFieldArray:F,_reset:ct,_resetDefaultValues:()=>ms(n.defaultValues)&&n.defaultValues().then(L=>{Kt(L,n.resetOptions),g.state.next({isLoading:!1})}),_updateFormState:L=>{r={...r,...L}},_disableForm:Me,_subjects:g,_proxyFormState:p,get _fields(){return o},get _formValues(){return s},get _state(){return l},set _state(L){l=L},get _defaultValues(){return i},get _names(){return u},set _names(L){u=L},get _formState(){return r},set _formState(L){r=L},get _options(){return n},set _options(L){n={...n,...L}}},trigger:se,register:$e,handleSubmit:je,watch:Oe,setValue:K,getValues:ce,reset:Kt,resetField:Mt,clearErrors:Ue,unregister:he,setError:We,setFocus:(L,Q={})=>{const J=ve(o,L),we=J&&J._f;if(we){const me=we.refs?we.refs[0]:we.ref;me.focus&&(me.focus(),Q.shouldSelect&&me.select())}},getFieldState:Ve}}function YY(e={}){const t=Fe.useRef(),n=Fe.useRef(),[r,o]=Fe.useState({isDirty:!1,isValidating:!1,isLoading:ms(e.defaultValues),isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,submitCount:0,dirtyFields:{},touchedFields:{},errors:{},disabled:!1,defaultValues:ms(e.defaultValues)?void 0:e.defaultValues});t.current||(t.current={...GY(e,()=>o(s=>({...s}))),formState:r});const i=t.current.control;return i._options=e,Hx({subject:i._subjects.state,next:s=>{W5(s,i._proxyFormState,i._updateFormState,!0)&&o({...i._formState})}}),Fe.useEffect(()=>i._disableForm(e.disabled),[i,e.disabled]),Fe.useEffect(()=>{if(i._proxyFormState.isDirty){const s=i._getDirty();s!==r.isDirty&&i._subjects.state.next({isDirty:s})}},[i,r.isDirty]),Fe.useEffect(()=>{e.values&&!ma(e.values,n.current)?(i._reset(e.values,i._options.resetOptions),n.current=e.values):i._resetDefaultValues()},[e.values,i]),Fe.useEffect(()=>{i._state.mount||(i._updateValid(),i._state.mount=!0),i._state.watch&&(i._state.watch=!1,i._subjects.state.next({...i._formState})),i._removeUnmounted()}),t.current.formState=V5(r,i),t.current}var T2=function(e,t,n){if(e&&"reportValidity"in e){var r=ve(n,t);e.setCustomValidity(r&&r.message||""),e.reportValidity()}},t3=function(e,t){var n=function(o){var i=t.fields[o];i&&i.ref&&"reportValidity"in i.ref?T2(i.ref,o,e):i.refs&&i.refs.forEach(function(s){return T2(s,o,e)})};for(var r in t.fields)n(r)},XY=function(e,t){t.shouldUseNativeValidation&&t3(e,t);var n={};for(var r in e){var o=ve(t.fields,r),i=Object.assign(e[r]||{},{ref:o&&o.ref});if(qY(t.names||Object.keys(e),r)){var s=Object.assign({},ZY(ve(n,r)));wt(s,"root",i),wt(n,r,s)}else wt(n,r,i)}return n},ZY=function(e){return Array.isArray(e)?e.filter(Boolean):[]},qY=function(e,t){return e.some(function(n){return n.startsWith(t+".")})},QY=function(e,t){for(var n={};e.length;){var r=e[0],o=r.code,i=r.message,s=r.path.join(".");if(!n[s])if("unionErrors"in r){var l=r.unionErrors[0].errors[0];n[s]={message:l.message,type:l.code}}else n[s]={message:i,type:o};if("unionErrors"in r&&r.unionErrors.forEach(function(m){return m.errors.forEach(function(p){return e.push(p)})}),t){var u=n[s].types,f=u&&u[r.code];n[s]=Y5(s,t,n,o,f?[].concat(f,r.message):r.message)}e.shift()}return n},JY=function(e,t,n){return n===void 0&&(n={}),function(r,o,i){try{return Promise.resolve(function(s,l){try{var u=Promise.resolve(e[n.mode==="sync"?"parse":"parseAsync"](r,t)).then(function(f){return i.shouldUseNativeValidation&&t3({},i),{errors:{},values:n.raw?r:f}})}catch(f){return l(f)}return u&&u.then?u.then(void 0,l):u}(0,function(s){if(function(l){return l.errors!=null}(s))return{values:{},errors:XY(QY(s.errors,!i.shouldUseNativeValidation&&i.criteriaMode==="all"),i)};throw s}))}catch(s){return Promise.reject(s)}}},mt;(function(e){e.assertEqual=o=>o;function t(o){}e.assertIs=t;function n(o){throw new Error}e.assertNever=n,e.arrayToEnum=o=>{const i={};for(const s of o)i[s]=s;return i},e.getValidEnumValues=o=>{const i=e.objectKeys(o).filter(l=>typeof o[o[l]]!="number"),s={};for(const l of i)s[l]=o[l];return e.objectValues(s)},e.objectValues=o=>e.objectKeys(o).map(function(i){return o[i]}),e.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{const i=[];for(const s in o)Object.prototype.hasOwnProperty.call(o,s)&&i.push(s);return i},e.find=(o,i)=>{for(const s of o)if(i(s))return s},e.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&isFinite(o)&&Math.floor(o)===o;function r(o,i=" | "){return o.map(s=>typeof s=="string"?`'${s}'`:s).join(i)}e.joinValues=r,e.jsonStringifyReplacer=(o,i)=>typeof i=="bigint"?i.toString():i})(mt||(mt={}));var P2;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(P2||(P2={}));const be=mt.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ca=e=>{switch(typeof e){case"undefined":return be.undefined;case"string":return be.string;case"number":return isNaN(e)?be.nan:be.number;case"boolean":return be.boolean;case"function":return be.function;case"bigint":return be.bigint;case"symbol":return be.symbol;case"object":return Array.isArray(e)?be.array:e===null?be.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?be.promise:typeof Map<"u"&&e instanceof Map?be.map:typeof Set<"u"&&e instanceof Set?be.set:typeof Date<"u"&&e instanceof Date?be.date:be.object;default:return be.unknown}},pe=mt.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"]);class Go 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(i){return i.message},r={_errors:[]},o=i=>{for(const s of i.issues)if(s.code==="invalid_union")s.unionErrors.map(o);else if(s.code==="invalid_return_type")o(s.returnTypeError);else if(s.code==="invalid_arguments")o(s.argumentsError);else if(s.path.length===0)r._errors.push(n(s));else{let l=r,u=0;for(;un.message){const n={},r=[];for(const o of this.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(t(o))):r.push(t(o));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}}Go.create=e=>new Go(e);const Xp=(e,t)=>{let n;switch(e.code){case pe.invalid_type:e.received===be.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case pe.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,mt.jsonStringifyReplacer)}`;break;case pe.unrecognized_keys:n=`Unrecognized key(s) in object: ${mt.joinValues(e.keys,", ")}`;break;case pe.invalid_union:n="Invalid input";break;case pe.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${mt.joinValues(e.options)}`;break;case pe.invalid_enum_value:n=`Invalid enum value. Expected ${mt.joinValues(e.options)}, received '${e.received}'`;break;case pe.invalid_arguments:n="Invalid function arguments";break;case pe.invalid_return_type:n="Invalid function return type";break;case pe.invalid_date:n="Invalid date";break;case pe.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}"`:mt.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case pe.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 pe.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 pe.custom:n="Invalid input";break;case pe.invalid_intersection_types:n="Intersection results could not be merged";break;case pe.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case pe.not_finite:n="Number must be finite";break;default:n=t.defaultError,mt.assertNever(e)}return{message:n}};let eX=Xp;function C1(){return eX}const $1=e=>{const{data:t,path:n,errorMaps:r,issueData:o}=e,i=[...n,...o.path||[]],s={...o,path:i};let l="";const u=r.filter(f=>!!f).slice().reverse();for(const f of u)l=f(s,{data:t,defaultError:l}).message;return{...o,path:i,message:o.message||l}};function Ee(e,t){const n=$1({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,C1(),Xp].filter(r=>!!r)});e.common.issues.push(n)}class zn{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 o of n){if(o.status==="aborted")return Ze;o.status==="dirty"&&t.dirty(),r.push(o.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){const r=[];for(const o of n)r.push({key:await o.key,value:await o.value});return zn.mergeObjectSync(t,r)}static mergeObjectSync(t,n){const r={};for(const o of n){const{key:i,value:s}=o;if(i.status==="aborted"||s.status==="aborted")return Ze;i.status==="dirty"&&t.dirty(),s.status==="dirty"&&t.dirty(),i.value!=="__proto__"&&(typeof s.value<"u"||o.alwaysSet)&&(r[i.value]=s.value)}return{status:t.value,value:r}}}const Ze=Object.freeze({status:"aborted"}),tX=e=>({status:"dirty",value:e}),rr=e=>({status:"valid",value:e}),A2=e=>e.status==="aborted",M2=e=>e.status==="dirty",Zp=e=>e.status==="valid",R1=e=>typeof Promise<"u"&&e instanceof Promise;var Ne;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t==null?void 0:t.message})(Ne||(Ne={}));class Qo{constructor(t,n,r,o){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=o}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 O2=(e,t)=>{if(Zp(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 Go(e.common.issues);return this._error=n,this._error}}};function Xe(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:r,description:o}=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:o}:{errorMap:(s,l)=>s.code!=="invalid_type"?{message:l.defaultError}:typeof l.data>"u"?{message:r??l.defaultError}:{message:n??l.defaultError},description:o}}class rt{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.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this)}get description(){return this._def.description}_getType(t){return ca(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:ca(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new zn,ctx:{common:t.parent.common,data:t.data,parsedType:ca(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const n=this._parse(t);if(R1(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 o={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:ca(t)},i=this._parseSync({data:t,path:o.path,parent:o});return O2(o,i)}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:ca(t)},o=this._parse({data:t,path:r.path,parent:r}),i=await(R1(o)?o:Promise.resolve(o));return O2(r,i)}refine(t,n){const r=o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n;return this._refinement((o,i)=>{const s=t(o),l=()=>i.addIssue({code:pe.custom,...r(o)});return typeof Promise<"u"&&s instanceof Promise?s.then(u=>u?!0:(l(),!1)):s?!0:(l(),!1)})}refinement(t,n){return this._refinement((r,o)=>t(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(t){return new Pi({schema:this,typeName:ze.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}optional(){return Cs.create(this,this._def)}nullable(){return gc.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Yo.create(this,this._def)}promise(){return pd.create(this,this._def)}or(t){return Jp.create([this,t],this._def)}and(t){return em.create(this,t,this._def)}transform(t){return new Pi({...Xe(this._def),schema:this,typeName:ze.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const n=typeof t=="function"?t:()=>t;return new im({...Xe(this._def),innerType:this,defaultValue:n,typeName:ze.ZodDefault})}brand(){return new hX({typeName:ze.ZodBranded,type:this,...Xe(this._def)})}catch(t){const n=typeof t=="function"?t:()=>t;return new N1({...Xe(this._def),innerType:this,catchValue:n,typeName:ze.ZodCatch})}describe(t){const n=this.constructor;return new n({...this._def,description:t})}pipe(t){return cg.create(this,t)}readonly(){return I1.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const nX=/^c[^\s-]{8,}$/i,rX=/^[a-z][a-z0-9]*$/,oX=/^[0-9A-HJKMNP-TV-Z]{26}$/,iX=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,sX=/^(?!\.)(?!.*\.\.)([A-Z0-9_+-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,aX="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let L0;const lX=/^(((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}))$/,cX=/^(([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})))$/,uX=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 dX(e,t){return!!((t==="v4"||!t)&&lX.test(e)||(t==="v6"||!t)&&cX.test(e))}class yi extends rt{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==be.string){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_type,expected:be.string,received:i.parsedType}),Ze}const r=new zn;let o;for(const i of this._def.checks)if(i.kind==="min")t.data.lengthi.value&&(o=this._getOrReturnCtx(t,o),Ee(o,{code:pe.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){const s=t.data.length>i.value,l=t.data.lengtht.test(o),{validation:n,code:pe.invalid_string,...Ne.errToObj(r)})}_addCheck(t){return new yi({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...Ne.errToObj(t)})}url(t){return this._addCheck({kind:"url",...Ne.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...Ne.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...Ne.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...Ne.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...Ne.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...Ne.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...Ne.errToObj(t)})}datetime(t){var n;return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof(t==null?void 0:t.precision)>"u"?null:t==null?void 0:t.precision,offset:(n=t==null?void 0:t.offset)!==null&&n!==void 0?n:!1,...Ne.errToObj(t==null?void 0:t.message)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...Ne.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n==null?void 0:n.position,...Ne.errToObj(n==null?void 0:n.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...Ne.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...Ne.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...Ne.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...Ne.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...Ne.errToObj(n)})}nonempty(t){return this.min(1,Ne.errToObj(t))}trim(){return new yi({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new yi({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new yi({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}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 yi({checks:[],typeName:ze.ZodString,coerce:(t=e==null?void 0:e.coerce)!==null&&t!==void 0?t:!1,...Xe(e)})};function fX(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,o=n>r?n:r,i=parseInt(e.toFixed(o).replace(".","")),s=parseInt(t.toFixed(o).replace(".",""));return i%s/Math.pow(10,o)}class hc extends rt{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)!==be.number){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_type,expected:be.number,received:i.parsedType}),Ze}let r;const o=new zn;for(const i of this._def.checks)i.kind==="int"?mt.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.invalid_type,expected:"integer",received:"float",message:i.message}),o.dirty()):i.kind==="min"?(i.inclusive?t.datai.value:t.data>=i.value)&&(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),o.dirty()):i.kind==="multipleOf"?fX(t.data,i.value)!==0&&(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):i.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.not_finite,message:i.message}),o.dirty()):mt.assertNever(i);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,Ne.toString(n))}gt(t,n){return this.setLimit("min",t,!1,Ne.toString(n))}lte(t,n){return this.setLimit("max",t,!0,Ne.toString(n))}lt(t,n){return this.setLimit("max",t,!1,Ne.toString(n))}setLimit(t,n,r,o){return new hc({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:Ne.toString(o)}]})}_addCheck(t){return new hc({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:Ne.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Ne.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Ne.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Ne.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Ne.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:Ne.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:Ne.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Ne.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Ne.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"&&mt.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 hc({checks:[],typeName:ze.ZodNumber,coerce:(e==null?void 0:e.coerce)||!1,...Xe(e)});class pc extends rt{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)!==be.bigint){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_type,expected:be.bigint,received:i.parsedType}),Ze}let r;const o=new zn;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?t.datai.value:t.data>=i.value)&&(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),o.dirty()):i.kind==="multipleOf"?t.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):mt.assertNever(i);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,Ne.toString(n))}gt(t,n){return this.setLimit("min",t,!1,Ne.toString(n))}lte(t,n){return this.setLimit("max",t,!0,Ne.toString(n))}lt(t,n){return this.setLimit("max",t,!1,Ne.toString(n))}setLimit(t,n,r,o){return new pc({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:Ne.toString(o)}]})}_addCheck(t){return new pc({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Ne.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Ne.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Ne.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Ne.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:Ne.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 pc({checks:[],typeName:ze.ZodBigInt,coerce:(t=e==null?void 0:e.coerce)!==null&&t!==void 0?t:!1,...Xe(e)})};class k1 extends rt{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==be.boolean){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.boolean,received:r.parsedType}),Ze}return rr(t.data)}}k1.create=e=>new k1({typeName:ze.ZodBoolean,coerce:(e==null?void 0:e.coerce)||!1,...Xe(e)});class hd extends rt{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==be.date){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_type,expected:be.date,received:i.parsedType}),Ze}if(isNaN(t.data.getTime())){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_date}),Ze}const r=new zn;let o;for(const i of this._def.checks)i.kind==="min"?t.data.getTime()i.value&&(o=this._getOrReturnCtx(t,o),Ee(o,{code:pe.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):mt.assertNever(i);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new hd({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:Ne.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:Ne.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 hd({checks:[],coerce:(e==null?void 0:e.coerce)||!1,typeName:ze.ZodDate,...Xe(e)});class T1 extends rt{_parse(t){if(this._getType(t)!==be.symbol){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.symbol,received:r.parsedType}),Ze}return rr(t.data)}}T1.create=e=>new T1({typeName:ze.ZodSymbol,...Xe(e)});class qp extends rt{_parse(t){if(this._getType(t)!==be.undefined){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.undefined,received:r.parsedType}),Ze}return rr(t.data)}}qp.create=e=>new qp({typeName:ze.ZodUndefined,...Xe(e)});class Qp extends rt{_parse(t){if(this._getType(t)!==be.null){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.null,received:r.parsedType}),Ze}return rr(t.data)}}Qp.create=e=>new Qp({typeName:ze.ZodNull,...Xe(e)});class P1 extends rt{constructor(){super(...arguments),this._any=!0}_parse(t){return rr(t.data)}}P1.create=e=>new P1({typeName:ze.ZodAny,...Xe(e)});class Dl extends rt{constructor(){super(...arguments),this._unknown=!0}_parse(t){return rr(t.data)}}Dl.create=e=>new Dl({typeName:ze.ZodUnknown,...Xe(e)});class Ms extends rt{_parse(t){const n=this._getOrReturnCtx(t);return Ee(n,{code:pe.invalid_type,expected:be.never,received:n.parsedType}),Ze}}Ms.create=e=>new Ms({typeName:ze.ZodNever,...Xe(e)});class A1 extends rt{_parse(t){if(this._getType(t)!==be.undefined){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.void,received:r.parsedType}),Ze}return rr(t.data)}}A1.create=e=>new A1({typeName:ze.ZodVoid,...Xe(e)});class Yo extends rt{_parse(t){const{ctx:n,status:r}=this._processInputParams(t),o=this._def;if(n.parsedType!==be.array)return Ee(n,{code:pe.invalid_type,expected:be.array,received:n.parsedType}),Ze;if(o.exactLength!==null){const s=n.data.length>o.exactLength.value,l=n.data.lengtho.maxLength.value&&(Ee(n,{code:pe.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((s,l)=>o.type._parseAsync(new Qo(n,s,n.path,l)))).then(s=>zn.mergeArray(r,s));const i=[...n.data].map((s,l)=>o.type._parseSync(new Qo(n,s,n.path,l)));return zn.mergeArray(r,i)}get element(){return this._def.type}min(t,n){return new Yo({...this._def,minLength:{value:t,message:Ne.toString(n)}})}max(t,n){return new Yo({...this._def,maxLength:{value:t,message:Ne.toString(n)}})}length(t,n){return new Yo({...this._def,exactLength:{value:t,message:Ne.toString(n)}})}nonempty(t){return this.min(1,t)}}Yo.create=(e,t)=>new Yo({type:e,minLength:null,maxLength:null,exactLength:null,typeName:ze.ZodArray,...Xe(t)});function dl(e){if(e instanceof Vt){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=Cs.create(dl(r))}return new Vt({...e._def,shape:()=>t})}else return e instanceof Yo?new Yo({...e._def,type:dl(e.element)}):e instanceof Cs?Cs.create(dl(e.unwrap())):e instanceof gc?gc.create(dl(e.unwrap())):e instanceof Ti?Ti.create(e.items.map(t=>dl(t))):e}class Vt extends rt{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=mt.objectKeys(t);return this._cached={shape:t,keys:n}}_parse(t){if(this._getType(t)!==be.object){const f=this._getOrReturnCtx(t);return Ee(f,{code:pe.invalid_type,expected:be.object,received:f.parsedType}),Ze}const{status:r,ctx:o}=this._processInputParams(t),{shape:i,keys:s}=this._getCached(),l=[];if(!(this._def.catchall instanceof Ms&&this._def.unknownKeys==="strip"))for(const f in o.data)s.includes(f)||l.push(f);const u=[];for(const f of s){const m=i[f],p=o.data[f];u.push({key:{status:"valid",value:f},value:m._parse(new Qo(o,p,o.path,f)),alwaysSet:f in o.data})}if(this._def.catchall instanceof Ms){const f=this._def.unknownKeys;if(f==="passthrough")for(const m of l)u.push({key:{status:"valid",value:m},value:{status:"valid",value:o.data[m]}});else if(f==="strict")l.length>0&&(Ee(o,{code:pe.unrecognized_keys,keys:l}),r.dirty());else if(f!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const f=this._def.catchall;for(const m of l){const p=o.data[m];u.push({key:{status:"valid",value:m},value:f._parse(new Qo(o,p,o.path,m)),alwaysSet:m in o.data})}}return o.common.async?Promise.resolve().then(async()=>{const f=[];for(const m of u){const p=await m.key;f.push({key:p,value:await m.value,alwaysSet:m.alwaysSet})}return f}).then(f=>zn.mergeObjectSync(r,f)):zn.mergeObjectSync(r,u)}get shape(){return this._def.shape()}strict(t){return Ne.errToObj,new Vt({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{var o,i,s,l;const u=(s=(i=(o=this._def).errorMap)===null||i===void 0?void 0:i.call(o,n,r).message)!==null&&s!==void 0?s:r.defaultError;return n.code==="unrecognized_keys"?{message:(l=Ne.errToObj(t).message)!==null&&l!==void 0?l:u}:{message:u}}}:{}})}strip(){return new Vt({...this._def,unknownKeys:"strip"})}passthrough(){return new Vt({...this._def,unknownKeys:"passthrough"})}extend(t){return new Vt({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new Vt({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:ze.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new Vt({...this._def,catchall:t})}pick(t){const n={};return mt.objectKeys(t).forEach(r=>{t[r]&&this.shape[r]&&(n[r]=this.shape[r])}),new Vt({...this._def,shape:()=>n})}omit(t){const n={};return mt.objectKeys(this.shape).forEach(r=>{t[r]||(n[r]=this.shape[r])}),new Vt({...this._def,shape:()=>n})}deepPartial(){return dl(this)}partial(t){const n={};return mt.objectKeys(this.shape).forEach(r=>{const o=this.shape[r];t&&!t[r]?n[r]=o:n[r]=o.optional()}),new Vt({...this._def,shape:()=>n})}required(t){const n={};return mt.objectKeys(this.shape).forEach(r=>{if(t&&!t[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof Cs;)i=i._def.innerType;n[r]=i}}),new Vt({...this._def,shape:()=>n})}keyof(){return n3(mt.objectKeys(this.shape))}}Vt.create=(e,t)=>new Vt({shape:()=>e,unknownKeys:"strip",catchall:Ms.create(),typeName:ze.ZodObject,...Xe(t)});Vt.strictCreate=(e,t)=>new Vt({shape:()=>e,unknownKeys:"strict",catchall:Ms.create(),typeName:ze.ZodObject,...Xe(t)});Vt.lazycreate=(e,t)=>new Vt({shape:e,unknownKeys:"strip",catchall:Ms.create(),typeName:ze.ZodObject,...Xe(t)});class Jp extends rt{_parse(t){const{ctx:n}=this._processInputParams(t),r=this._def.options;function o(i){for(const l of i)if(l.result.status==="valid")return l.result;for(const l of i)if(l.result.status==="dirty")return n.common.issues.push(...l.ctx.common.issues),l.result;const s=i.map(l=>new Go(l.ctx.common.issues));return Ee(n,{code:pe.invalid_union,unionErrors:s}),Ze}if(n.common.async)return Promise.all(r.map(async i=>{const s={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:s}),ctx:s}})).then(o);{let i;const s=[];for(const u of r){const f={...n,common:{...n.common,issues:[]},parent:null},m=u._parseSync({data:n.data,path:n.path,parent:f});if(m.status==="valid")return m;m.status==="dirty"&&!i&&(i={result:m,ctx:f}),f.common.issues.length&&s.push(f.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;const l=s.map(u=>new Go(u));return Ee(n,{code:pe.invalid_union,unionErrors:l}),Ze}}get options(){return this._def.options}}Jp.create=(e,t)=>new Jp({options:e,typeName:ze.ZodUnion,...Xe(t)});const rp=e=>e instanceof nm?rp(e.schema):e instanceof Pi?rp(e.innerType()):e instanceof rm?[e.value]:e instanceof Da?e.options:e instanceof om?Object.keys(e.enum):e instanceof im?rp(e._def.innerType):e instanceof qp?[void 0]:e instanceof Qp?[null]:null;class Xx extends rt{_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.object)return Ee(n,{code:pe.invalid_type,expected:be.object,received:n.parsedType}),Ze;const r=this.discriminator,o=n.data[r],i=this.optionsMap.get(o);return i?n.common.async?i._parseAsync({data:n.data,path:n.path,parent:n}):i._parseSync({data:n.data,path:n.path,parent:n}):(Ee(n,{code:pe.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),Ze)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){const o=new Map;for(const i of n){const s=rp(i.shape[t]);if(!s)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const l of s){if(o.has(l))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(l)}`);o.set(l,i)}}return new Xx({typeName:ze.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:o,...Xe(r)})}}function M1(e,t){const n=ca(e),r=ca(t);if(e===t)return{valid:!0,data:e};if(n===be.object&&r===be.object){const o=mt.objectKeys(t),i=mt.objectKeys(e).filter(l=>o.indexOf(l)!==-1),s={...e,...t};for(const l of i){const u=M1(e[l],t[l]);if(!u.valid)return{valid:!1};s[l]=u.data}return{valid:!0,data:s}}else if(n===be.array&&r===be.array){if(e.length!==t.length)return{valid:!1};const o=[];for(let i=0;i{if(A2(i)||A2(s))return Ze;const l=M1(i.value,s.value);return l.valid?((M2(i)||M2(s))&&n.dirty(),{status:n.value,value:l.data}):(Ee(r,{code:pe.invalid_intersection_types}),Ze)};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(([i,s])=>o(i,s)):o(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}em.create=(e,t,n)=>new em({left:e,right:t,typeName:ze.ZodIntersection,...Xe(n)});class Ti extends rt{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.array)return Ee(r,{code:pe.invalid_type,expected:be.array,received:r.parsedType}),Ze;if(r.data.lengththis._def.items.length&&(Ee(r,{code:pe.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const i=[...r.data].map((s,l)=>{const u=this._def.items[l]||this._def.rest;return u?u._parse(new Qo(r,s,r.path,l)):null}).filter(s=>!!s);return r.common.async?Promise.all(i).then(s=>zn.mergeArray(n,s)):zn.mergeArray(n,i)}get items(){return this._def.items}rest(t){return new Ti({...this._def,rest:t})}}Ti.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ti({items:e,typeName:ze.ZodTuple,rest:null,...Xe(t)})};class tm extends rt{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!==be.object)return Ee(r,{code:pe.invalid_type,expected:be.object,received:r.parsedType}),Ze;const o=[],i=this._def.keyType,s=this._def.valueType;for(const l in r.data)o.push({key:i._parse(new Qo(r,l,r.path,l)),value:s._parse(new Qo(r,r.data[l],r.path,l))});return r.common.async?zn.mergeObjectAsync(n,o):zn.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof rt?new tm({keyType:t,valueType:n,typeName:ze.ZodRecord,...Xe(r)}):new tm({keyType:yi.create(),valueType:t,typeName:ze.ZodRecord,...Xe(n)})}}class O1 extends rt{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!==be.map)return Ee(r,{code:pe.invalid_type,expected:be.map,received:r.parsedType}),Ze;const o=this._def.keyType,i=this._def.valueType,s=[...r.data.entries()].map(([l,u],f)=>({key:o._parse(new Qo(r,l,r.path,[f,"key"])),value:i._parse(new Qo(r,u,r.path,[f,"value"]))}));if(r.common.async){const l=new Map;return Promise.resolve().then(async()=>{for(const u of s){const f=await u.key,m=await u.value;if(f.status==="aborted"||m.status==="aborted")return Ze;(f.status==="dirty"||m.status==="dirty")&&n.dirty(),l.set(f.value,m.value)}return{status:n.value,value:l}})}else{const l=new Map;for(const u of s){const f=u.key,m=u.value;if(f.status==="aborted"||m.status==="aborted")return Ze;(f.status==="dirty"||m.status==="dirty")&&n.dirty(),l.set(f.value,m.value)}return{status:n.value,value:l}}}}O1.create=(e,t,n)=>new O1({valueType:t,keyType:e,typeName:ze.ZodMap,...Xe(n)});class mc extends rt{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.set)return Ee(r,{code:pe.invalid_type,expected:be.set,received:r.parsedType}),Ze;const o=this._def;o.minSize!==null&&r.data.sizeo.maxSize.value&&(Ee(r,{code:pe.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());const i=this._def.valueType;function s(u){const f=new Set;for(const m of u){if(m.status==="aborted")return Ze;m.status==="dirty"&&n.dirty(),f.add(m.value)}return{status:n.value,value:f}}const l=[...r.data.values()].map((u,f)=>i._parse(new Qo(r,u,r.path,f)));return r.common.async?Promise.all(l).then(u=>s(u)):s(l)}min(t,n){return new mc({...this._def,minSize:{value:t,message:Ne.toString(n)}})}max(t,n){return new mc({...this._def,maxSize:{value:t,message:Ne.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}}mc.create=(e,t)=>new mc({valueType:e,minSize:null,maxSize:null,typeName:ze.ZodSet,...Xe(t)});class Lu extends rt{constructor(){super(...arguments),this.validate=this.implement}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.function)return Ee(n,{code:pe.invalid_type,expected:be.function,received:n.parsedType}),Ze;function r(l,u){return $1({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,C1(),Xp].filter(f=>!!f),issueData:{code:pe.invalid_arguments,argumentsError:u}})}function o(l,u){return $1({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,C1(),Xp].filter(f=>!!f),issueData:{code:pe.invalid_return_type,returnTypeError:u}})}const i={errorMap:n.common.contextualErrorMap},s=n.data;if(this._def.returns instanceof pd){const l=this;return rr(async function(...u){const f=new Go([]),m=await l._def.args.parseAsync(u,i).catch(y=>{throw f.addIssue(r(u,y)),f}),p=await Reflect.apply(s,this,m);return await l._def.returns._def.type.parseAsync(p,i).catch(y=>{throw f.addIssue(o(p,y)),f})})}else{const l=this;return rr(function(...u){const f=l._def.args.safeParse(u,i);if(!f.success)throw new Go([r(u,f.error)]);const m=Reflect.apply(s,this,f.data),p=l._def.returns.safeParse(m,i);if(!p.success)throw new Go([o(m,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new Lu({...this._def,args:Ti.create(t).rest(Dl.create())})}returns(t){return new Lu({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new Lu({args:t||Ti.create([]).rest(Dl.create()),returns:n||Dl.create(),typeName:ze.ZodFunction,...Xe(r)})}}class nm extends rt{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})}}nm.create=(e,t)=>new nm({getter:e,typeName:ze.ZodLazy,...Xe(t)});class rm extends rt{_parse(t){if(t.data!==this._def.value){const n=this._getOrReturnCtx(t);return Ee(n,{received:n.data,code:pe.invalid_literal,expected:this._def.value}),Ze}return{status:"valid",value:t.data}}get value(){return this._def.value}}rm.create=(e,t)=>new rm({value:e,typeName:ze.ZodLiteral,...Xe(t)});function n3(e,t){return new Da({values:e,typeName:ze.ZodEnum,...Xe(t)})}class Da extends rt{_parse(t){if(typeof t.data!="string"){const n=this._getOrReturnCtx(t),r=this._def.values;return Ee(n,{expected:mt.joinValues(r),received:n.parsedType,code:pe.invalid_type}),Ze}if(this._def.values.indexOf(t.data)===-1){const n=this._getOrReturnCtx(t),r=this._def.values;return Ee(n,{received:n.data,code:pe.invalid_enum_value,options:r}),Ze}return rr(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 Da.create(t)}exclude(t){return Da.create(this.options.filter(n=>!t.includes(n)))}}Da.create=n3;class om extends rt{_parse(t){const n=mt.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==be.string&&r.parsedType!==be.number){const o=mt.objectValues(n);return Ee(r,{expected:mt.joinValues(o),received:r.parsedType,code:pe.invalid_type}),Ze}if(n.indexOf(t.data)===-1){const o=mt.objectValues(n);return Ee(r,{received:r.data,code:pe.invalid_enum_value,options:o}),Ze}return rr(t.data)}get enum(){return this._def.values}}om.create=(e,t)=>new om({values:e,typeName:ze.ZodNativeEnum,...Xe(t)});class pd extends rt{unwrap(){return this._def.type}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.promise&&n.common.async===!1)return Ee(n,{code:pe.invalid_type,expected:be.promise,received:n.parsedType}),Ze;const r=n.parsedType===be.promise?n.data:Promise.resolve(n.data);return rr(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}}pd.create=(e,t)=>new pd({type:e,typeName:ze.ZodPromise,...Xe(t)});class Pi extends rt{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ze.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:n,ctx:r}=this._processInputParams(t),o=this._def.effect||null,i={addIssue:s=>{Ee(r,s),s.fatal?n.abort():n.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),o.type==="preprocess"){const s=o.transform(r.data,i);return r.common.issues.length?{status:"dirty",value:r.data}:r.common.async?Promise.resolve(s).then(l=>this._def.schema._parseAsync({data:l,path:r.path,parent:r})):this._def.schema._parseSync({data:s,path:r.path,parent:r})}if(o.type==="refinement"){const s=l=>{const u=o.refinement(l,i);if(r.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return l};if(r.common.async===!1){const l=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return l.status==="aborted"?Ze:(l.status==="dirty"&&n.dirty(),s(l.value),{status:n.value,value:l.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(l=>l.status==="aborted"?Ze:(l.status==="dirty"&&n.dirty(),s(l.value).then(()=>({status:n.value,value:l.value}))))}if(o.type==="transform")if(r.common.async===!1){const s=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Zp(s))return s;const l=o.transform(s.value,i);if(l instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:l}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(s=>Zp(s)?Promise.resolve(o.transform(s.value,i)).then(l=>({status:n.value,value:l})):s);mt.assertNever(o)}}Pi.create=(e,t,n)=>new Pi({schema:e,typeName:ze.ZodEffects,effect:t,...Xe(n)});Pi.createWithPreprocess=(e,t,n)=>new Pi({schema:t,effect:{type:"preprocess",transform:e},typeName:ze.ZodEffects,...Xe(n)});class Cs extends rt{_parse(t){return this._getType(t)===be.undefined?rr(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Cs.create=(e,t)=>new Cs({innerType:e,typeName:ze.ZodOptional,...Xe(t)});class gc extends rt{_parse(t){return this._getType(t)===be.null?rr(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}gc.create=(e,t)=>new gc({innerType:e,typeName:ze.ZodNullable,...Xe(t)});class im extends rt{_parse(t){const{ctx:n}=this._processInputParams(t);let r=n.data;return n.parsedType===be.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}im.create=(e,t)=>new im({innerType:e,typeName:ze.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Xe(t)});class N1 extends rt{_parse(t){const{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return R1(o)?o.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Go(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Go(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}N1.create=(e,t)=>new N1({innerType:e,typeName:ze.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Xe(t)});class D1 extends rt{_parse(t){if(this._getType(t)!==be.nan){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.nan,received:r.parsedType}),Ze}return{status:"valid",value:t.data}}}D1.create=e=>new D1({typeName:ze.ZodNaN,...Xe(e)});class hX extends rt{_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 cg extends rt{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?Ze:i.status==="dirty"?(n.dirty(),tX(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{const o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?Ze:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(t,n){return new cg({in:t,out:n,typeName:ze.ZodPipeline})}}class I1 extends rt{_parse(t){const n=this._def.innerType._parse(t);return Zp(n)&&(n.value=Object.freeze(n.value)),n}}I1.create=(e,t)=>new I1({innerType:e,typeName:ze.ZodReadonly,...Xe(t)});Vt.lazycreate;var ze;(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",e.ZodReadonly="ZodReadonly"})(ze||(ze={}));const fu=yi.create;hc.create;D1.create;pc.create;const hu=k1.create;hd.create;T1.create;qp.create;Qp.create;P1.create;Dl.create;Ms.create;A1.create;Yo.create;const pX=Vt.create;Vt.strictCreate;Jp.create;Xx.create;em.create;Ti.create;tm.create;O1.create;mc.create;Lu.create;nm.create;rm.create;Da.create;om.create;pd.create;Pi.create;Cs.create;gc.create;Pi.createWithPreprocess;cg.create;const L1="horizontal",mX=["horizontal","vertical"],r3=d.forwardRef((e,t)=>{const{decorative:n,orientation:r=L1,...o}=e,i=o3(r)?r:L1,l=n?{role:"none"}:{"aria-orientation":i==="vertical"?i:void 0,role:"separator"};return d.createElement(Pe.div,Y({"data-orientation":i},l,o,{ref:t}))});r3.propTypes={orientation(e,t,n){const r=e[t],o=String(r);return r&&!o3(r)?new Error(gX(o,n)):null}};function gX(e,t){return`Invalid prop \`orientation\` of value \`${e}\` supplied to \`${t}\`, expected one of: + - horizontal + - vertical + +Defaulting to \`${L1}\`.`}function o3(e){return mX.includes(e)}const i3=r3,gn=d.forwardRef(({className:e,orientation:t="horizontal",decorative:n=!0,...r},o)=>v.jsx(i3,{ref:o,decorative:n,orientation:t,className:Ce("shrink-0 bg-border",t==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",e),...r}));gn.displayName=i3.displayName;const vX=d.forwardRef((e,t)=>d.createElement(Pe.label,Y({},e,{ref:t,onMouseDown:n=>{var r;(r=e.onMouseDown)===null||r===void 0||r.call(e,n),!n.defaultPrevented&&n.detail>1&&n.preventDefault()}}))),s3=vX,yX=Dm("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),Zx=d.forwardRef(({className:e,disabled:t,...n},r)=>v.jsx(s3,{ref:r,className:Ce(yX(),e,t?"opacity-50":"","select-none"),...n}));Zx.displayName=s3.displayName;const wX=OY,a3=d.createContext({}),al=({...e})=>v.jsx(a3.Provider,{value:{name:e.name},children:v.jsx(LY,{...e})}),ug=()=>{const e=d.useContext(a3),t=d.useContext(l3),{getFieldState:n,formState:r}=lg(),o=n(e.name,r);if(!e)throw new Error("useFormField should be used within ");const{id:i}=t;return{id:i,name:e.name,formItemId:`${i}-form-item`,formDescriptionId:`${i}-form-item-description`,formMessageId:`${i}-form-item-message`,...o}},l3=d.createContext({}),oa=d.forwardRef(({className:e,...t},n)=>{const r=d.useId();return v.jsx(l3.Provider,{value:{id:r},children:v.jsx("div",{ref:n,className:Ce("space-y-2",e),...t})})});oa.displayName="FormItem";const ia=d.forwardRef(({className:e,...t},n)=>{const{error:r,formItemId:o}=ug();return v.jsx(Zx,{ref:n,className:Ce(r&&"text-destructive","text-sm",e),htmlFor:o,...t})});ia.displayName="FormLabel";const sa=d.forwardRef(({...e},t)=>{const{error:n,formItemId:r,formDescriptionId:o,formMessageId:i}=ug();return v.jsx(Zo,{ref:t,id:r,"aria-describedby":n?`${o} ${i}`:`${o}`,"aria-invalid":!!n,...e})});sa.displayName="FormControl";const aa=d.forwardRef(({className:e,...t},n)=>{const{formDescriptionId:r}=ug();return v.jsx("p",{ref:n,id:r,className:Ce("text-[0.8rem] text-muted-foreground",e),...t})});aa.displayName="FormDescription";const xX=d.forwardRef(({className:e,children:t,...n},r)=>{const{error:o,formMessageId:i}=ug(),s=o?String(o==null?void 0:o.message):t;return s?v.jsx("p",{ref:r,id:i,className:Ce("text-[0.8rem] font-medium text-destructive",e),...n,children:s}):null});xX.displayName="FormMessage";const c3="Switch",[bX,_te]=Mn(c3),[SX,_X]=bX(c3),EX=d.forwardRef((e,t)=>{const{__scopeSwitch:n,name:r,checked:o,defaultChecked:i,required:s,disabled:l,value:u="on",onCheckedChange:f,...m}=e,[p,g]=d.useState(null),y=Be(t,x=>g(x)),b=d.useRef(!1),S=p?!!p.closest("form"):!0,[E=!1,_]=Zr({prop:o,defaultProp:i,onChange:f});return d.createElement(SX,{scope:n,checked:E,disabled:l},d.createElement(Pe.button,Y({type:"button",role:"switch","aria-checked":E,"aria-required":s,"data-state":u3(E),"data-disabled":l?"":void 0,disabled:l,value:u},m,{ref:y,onClick:de(e.onClick,x=>{_(C=>!C),S&&(b.current=x.isPropagationStopped(),b.current||x.stopPropagation())})})),S&&d.createElement(RX,{control:p,bubbles:!b.current,name:r,value:u,checked:E,required:s,disabled:l,style:{transform:"translateX(-100%)"}}))}),CX="SwitchThumb",$X=d.forwardRef((e,t)=>{const{__scopeSwitch:n,...r}=e,o=_X(CX,n);return d.createElement(Pe.span,Y({"data-state":u3(o.checked),"data-disabled":o.disabled?"":void 0},r,{ref:t}))}),RX=e=>{const{control:t,checked:n,bubbles:r=!0,...o}=e,i=d.useRef(null),s=zx(n),l=yx(t);return d.useEffect(()=>{const u=i.current,f=window.HTMLInputElement.prototype,p=Object.getOwnPropertyDescriptor(f,"checked").set;if(s!==n&&p){const g=new Event("click",{bubbles:r});p.call(u,n),u.dispatchEvent(g)}},[s,n,r]),d.createElement("input",Y({type:"checkbox","aria-hidden":!0,defaultChecked:n},o,{tabIndex:-1,ref:i,style:{...e.style,...l,position:"absolute",pointerEvents:"none",opacity:0,margin:0}}))};function u3(e){return e?"checked":"unchecked"}const d3=EX,kX=$X,co=d.forwardRef(({className:e,...t},n)=>v.jsx(d3,{className:Ce("peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",e),tabIndex:-1,...t,ref:n,children:v.jsx(kX,{className:Ce("pointer-events-none block h-4 w-4 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0")})}));co.displayName=d3.displayName;const TX="AlertDialog",[PX,Ete]=Mn(TX,[dP]),zs=dP(),AX=e=>{const{__scopeAlertDialog:t,...n}=e,r=zs(t);return d.createElement(Cx,Y({},r,n,{modal:!0}))},MX=e=>{const{__scopeAlertDialog:t,...n}=e,r=zs(t);return d.createElement($x,Y({},r,n))},OX=d.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=zs(n);return d.createElement(Bd,Y({},o,r,{ref:t}))}),f3="AlertDialogContent",[NX,DX]=PX(f3),IX=d.forwardRef((e,t)=>{const{__scopeAlertDialog:n,children:r,...o}=e,i=zs(n),s=d.useRef(null),l=Be(t,s),u=d.useRef(null);return d.createElement(hW,{contentName:f3,titleName:LX,docsSlug:"alert-dialog"},d.createElement(NX,{scope:n,cancelRef:u},d.createElement(Ud,Y({role:"alertdialog"},i,o,{ref:l,onOpenAutoFocus:de(o.onOpenAutoFocus,f=>{var m;f.preventDefault(),(m=u.current)===null||m===void 0||m.focus({preventScroll:!0})}),onPointerDownOutside:f=>f.preventDefault(),onInteractOutside:f=>f.preventDefault()}),d.createElement(lx,null,r),!1)))}),LX="AlertDialogTitle",FX=d.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=zs(n);return d.createElement(Vd,Y({},o,r,{ref:t}))}),jX=d.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=zs(n);return d.createElement(Wd,Y({},o,r,{ref:t}))}),zX=d.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=zs(n);return d.createElement(Rx,Y({},o,r,{ref:t}))}),BX="AlertDialogCancel",UX=d.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,{cancelRef:o}=DX(BX,n),i=zs(n),s=Be(t,o);return d.createElement(Rx,Y({},i,r,{ref:s}))}),VX=AX,WX=MX,h3=OX,p3=IX,m3=zX,g3=UX,v3=FX,y3=jX,HX=VX,KX=WX,w3=d.forwardRef(({className:e,...t},n)=>v.jsx(h3,{className:Ce("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t,ref:n}));w3.displayName=h3.displayName;const x3=d.forwardRef(({className:e,...t},n)=>v.jsxs(KX,{children:[v.jsx(w3,{}),v.jsx(p3,{ref:n,className:Ce("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",e),...t})]}));x3.displayName=p3.displayName;const b3=({className:e,...t})=>v.jsx("div",{className:Ce("flex flex-col space-y-2 text-center sm:text-left",e),...t});b3.displayName="AlertDialogHeader";const GX=d.forwardRef(({className:e,...t},n)=>v.jsx(v3,{ref:n,className:Ce("text-lg font-semibold",e),...t}));GX.displayName=v3.displayName;const YX=d.forwardRef(({className:e,...t},n)=>v.jsx(y3,{ref:n,className:Ce("text-sm text-muted-foreground",e),...t}));YX.displayName=y3.displayName;const XX=d.forwardRef(({className:e,...t},n)=>v.jsx(m3,{ref:n,className:Ce(_x(),e),...t}));XX.displayName=m3.displayName;const ZX=d.forwardRef(({className:e,...t},n)=>v.jsx(g3,{ref:n,className:Ce(_x({variant:"outline"}),"mt-2 sm:mt-0",e),...t}));ZX.displayName=g3.displayName;const qX=pX({enableFileManager:hu(),inputDirectory:fu(),outputDirectory:fu(),enableDownloadMask:hu(),enableManualInpainting:hu(),enableUploadMask:hu(),enableAutoExtractPrompt:hu(),removeBGModel:fu(),realesrganModel:fu(),interactiveSegModel:fu()}),S3="General",F1="Model",_3="Plugins",QX=[F1,S3,_3];function JX(){const[e,t]=QT(!1),[n,r]=d.useState(F1),[o,i,s,l,u,f]=bt(F=>[F.updateAppState,F.settings,F.updateSettings,F.fileManagerState,F.setModel,F.setServerConfig]),{toast:m}=Id(),[p,g]=d.useState(i.model),[y,b]=d.useState([]),S=y.length>0;d.useEffect(()=>{g(i.model)},[i.model]);const{data:E,status:_}=ML({queryKey:["serverConfig"],queryFn:gT}),x=YY({resolver:JY(qX),defaultValues:{enableDownloadMask:i.enableDownloadMask,enableManualInpainting:i.enableManualInpainting,enableUploadMask:i.enableUploadMask,enableAutoExtractPrompt:i.enableAutoExtractPrompt,inputDirectory:l.inputDirectory,outputDirectory:l.outputDirectory,removeBGModel:E==null?void 0:E.removeBGModel,realesrganModel:E==null?void 0:E.realesrganModel,interactiveSegModel:E==null?void 0:E.interactiveSegModel}});d.useEffect(()=>{E&&(f(E),x.setValue("removeBGModel",E.removeBGModel),x.setValue("realesrganModel",E.realesrganModel),x.setValue("interactiveSegModel",E.interactiveSegModel))},[x,E]);async function C(F){s({enableDownloadMask:F.enableDownloadMask,enableManualInpainting:F.enableManualInpainting,enableUploadMask:F.enableUploadMask,enableAutoExtractPrompt:F.enableAutoExtractPrompt});const N=p.name!==i.model.name,ie=(E==null?void 0:E.removeBGModel)!==F.removeBGModel&&M,K=(E==null?void 0:E.realesrganModel)!==F.realesrganModel&&A,Z=(E==null?void 0:E.interactiveSegModel)!==F.interactiveSegModel&&D;if(N||ie||K||Z){const se=[];if(N&&se.push(`Switching model from ${i.model.name} to ${p.name}`),ie&&se.push(`Switching RemoveBG model from ${E==null?void 0:E.removeBGModel} to ${F.removeBGModel}`),K&&se.push(`Switching RealESRGAN model from ${E==null?void 0:E.realesrganModel} to ${F.realesrganModel}`),Z&&se.push(`Switching ${Ao.InteractiveSeg} model from ${E==null?void 0:E.interactiveSegModel} to ${F.interactiveSegModel}`),b(se),o({disableShortCuts:!0}),N)try{const ce=await Bj(p.name);m({title:`Switch to ${ce.name} success`}),u(p)}catch(ce){m({variant:"destructive",title:`Switch to ${p.name} failed: ${ce}`}),g(i.model)}if(ie)try{const ce=await v0(Ao.RemoveBG,F.removeBGModel);if(ce.status!==200)throw new Error(ce.statusText)}catch(ce){m({variant:"destructive",title:`Switch RemoveBG model to ${F.removeBGModel} failed: ${ce}`})}if(K)try{const ce=await v0(Ao.RealESRGAN,F.realesrganModel);if(ce.status!==200)throw new Error(ce.statusText)}catch(ce){m({variant:"destructive",title:`Switch RealESRGAN model to ${F.realesrganModel} failed: ${ce}`})}if(Z)try{const ce=await v0(Ao.InteractiveSeg,F.interactiveSegModel);if(ce.status!==200)throw new Error(ce.statusText)}catch(ce){m({variant:"destructive",title:`Switch ${Ao.InteractiveSeg} model to ${F.interactiveSegModel} failed: ${ce}`})}b([]),o({disableShortCuts:!1})}}if(Zn("s",()=>{t(),e&&C(x.getValues())},[e,x,p,E]),_!=="success")return v.jsx(v.Fragment,{});const R=E.modelInfos,P=E.plugins,M=P.some(F=>F.name===Ao.RemoveBG),A=P.some(F=>F.name===Ao.RealESRGAN),D=P.some(F=>F.name===Ao.InteractiveSeg);function U(F){t(),F||C(x.getValues())}function W(F){g(F)}function q(F){return R?R.filter(N=>F.includes(N.model_type)).map(N=>v.jsxs("div",{onClick:()=>W(N),className:"px-2",children:[v.jsx("div",{className:Ce([N.name===p.name?"bg-muted":"hover:bg-muted","rounded-md px-2 py-2","cursor-default"]),children:v.jsx("div",{className:"text-base",children:N.name})}),v.jsx(gn,{className:"my-1"})]},N.name)):v.jsx("div",{children:"Please download model first"})}function X(){let F=fs;for(let N of R)if(p.name===N.name){F=N.model_type,F===oC&&(F=uh),F===iC&&(F=dh);break}return v.jsxs("div",{className:"flex flex-col gap-4 w-[510px]",children:[v.jsxs("div",{className:"flex flex-col gap-4 rounded-md",children:[v.jsx("div",{className:"font-medium",children:"Current Model"}),v.jsx("div",{children:p.name})]}),v.jsx(gn,{}),v.jsxs("div",{className:"space-y-4 rounded-md",children:[v.jsx("div",{className:"flex gap-1 items-center justify-start",children:v.jsx("div",{className:"font-medium",children:"Available models"})}),v.jsxs(a5,{defaultValue:F,children:[v.jsxs(jx,{children:[v.jsx(pa,{value:fs,children:"Inpaint"}),v.jsx(pa,{value:uh,children:"Stable Diffusion"}),v.jsx(pa,{value:dh,children:"Stable Diffusion Inpaint"}),v.jsx(pa,{value:d0,children:"Other Diffusion"})]}),v.jsxs(ag,{className:"h-[240px] w-full mt-2 outline-none border rounded-lg",children:[v.jsx(Su,{value:fs,children:q([fs])}),v.jsx(Su,{value:uh,children:q([uh,oC])}),v.jsx(Su,{value:dh,children:q([dh,iC])}),v.jsx(Su,{value:d0,children:q([d0])})]})]})]})]})}function ae(){return v.jsxs("div",{className:"space-y-4 w-[510px]",children:[v.jsx(al,{control:x.control,name:"enableManualInpainting",render:({field:F})=>v.jsxs(oa,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(ia,{children:"Enable manual inpainting"}),v.jsx(aa,{children:"For erase model, click a button to trigger inpainting after draw mask."})]}),v.jsx(sa,{children:v.jsx(co,{checked:F.value,onCheckedChange:F.onChange})})]})}),v.jsx(gn,{}),v.jsx(al,{control:x.control,name:"enableDownloadMask",render:({field:F})=>v.jsxs(oa,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(ia,{children:"Enable download mask"}),v.jsx(aa,{children:"Also download the mask after save the inpainting result."})]}),v.jsx(sa,{children:v.jsx(co,{checked:F.value,onCheckedChange:F.onChange})})]})}),v.jsx(gn,{}),v.jsx(al,{control:x.control,name:"enableAutoExtractPrompt",render:({field:F})=>v.jsxs(oa,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(ia,{children:"Enable auto extract prompt"}),v.jsx(aa,{children:"Automatically extract prompt/negativate prompt from the image meta."})]}),v.jsx(sa,{children:v.jsx(co,{checked:F.value,onCheckedChange:F.onChange})})]})})]})}function V(){return v.jsxs("div",{className:"space-y-4 w-[510px]",children:[v.jsx(al,{control:x.control,name:"removeBGModel",render:({field:F})=>v.jsxs(oa,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(ia,{children:"Remove Background"}),v.jsx(aa,{children:"Remove background model"})]}),v.jsxs(Uo,{onValueChange:F.onChange,defaultValue:F.value,disabled:!M,children:[v.jsx(sa,{children:v.jsx(go,{className:"w-auto",children:v.jsx(Vo,{placeholder:"Select removebg model"})})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:E==null?void 0:E.removeBGModels.map(N=>v.jsx(yo,{value:N,children:N},N))})})]})]})}),v.jsx(gn,{}),v.jsx(al,{control:x.control,name:"realesrganModel",render:({field:F})=>v.jsxs(oa,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(ia,{children:"RealESRGAN"}),v.jsx(aa,{children:"RealESRGAN Model"})]}),v.jsxs(Uo,{onValueChange:F.onChange,defaultValue:F.value,disabled:!A,children:[v.jsx(sa,{children:v.jsx(go,{className:"w-auto",children:v.jsx(Vo,{placeholder:"Select RealESRGAN model"})})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:E==null?void 0:E.realesrganModels.map(N=>v.jsx(yo,{value:N,children:N},N))})})]})]})}),v.jsx(gn,{}),v.jsx(al,{control:x.control,name:"interactiveSegModel",render:({field:F})=>v.jsxs(oa,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(ia,{children:"Interactive Segmentation"}),v.jsx(aa,{children:"Interactive Segmentation Model"})]}),v.jsxs(Uo,{onValueChange:F.onChange,defaultValue:F.value,disabled:!D,children:[v.jsx(sa,{children:v.jsx(go,{className:"w-auto",children:v.jsx(Vo,{placeholder:"Select interactive segmentation model"})})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:E==null?void 0:E.interactiveSegModels.map(N=>v.jsx(yo,{value:N,children:N},N))})})]})]})})]})}return v.jsxs(v.Fragment,{children:[v.jsx(HX,{open:S,children:v.jsx(x3,{children:v.jsx(b3,{children:v.jsxs("div",{className:"flex flex-col justify-center items-center gap-4",children:[v.jsxs("div",{role:"status",children:[v.jsxs("svg",{"aria-hidden":"true",className:"w-8 h-8 text-gray-200 animate-spin dark:text-gray-600 fill-primary",viewBox:"0 0 100 101",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[v.jsx("path",{d:"M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z",fill:"currentColor"}),v.jsx("path",{d:"M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z",fill:"currentFill"})]}),v.jsx("span",{className:"sr-only",children:"Loading..."})]}),y?v.jsx("div",{className:"flex flex-col",children:y.map((F,N)=>v.jsx("div",{children:F},N))}):v.jsx(v.Fragment,{})]})})})}),v.jsxs(Jm,{open:e,onOpenChange:U,children:[v.jsx(kx,{asChild:!0,children:v.jsx(yn,{tooltip:"Settings",children:v.jsx(sV,{})})}),v.jsxs(Hd,{className:"max-w-3xl h-[600px]",onOpenAutoFocus:F=>F.preventDefault(),children:[v.jsx(Kd,{children:"Settings"}),v.jsx(gn,{}),v.jsxs("div",{className:"flex flex-row space-x-8 h-full",children:[v.jsx("div",{className:"flex flex-col space-y-1",children:QX.map(F=>v.jsx(wn,{variant:"ghost",onClick:()=>r(F),className:Ce(n===F?"bg-muted ":"hover:bg-muted","justify-start"),children:F},F))}),v.jsx(gn,{orientation:"vertical"}),v.jsx(wX,{...x,children:v.jsx("div",{className:"flex w-full justify-center",children:v.jsxs("form",{onSubmit:x.handleSubmit(C),children:[n===F1?X():v.jsx(v.Fragment,{}),n===S3?ae():v.jsx(v.Fragment,{}),n===_3?V():v.jsx(v.Fragment,{}),v.jsx("div",{className:"absolute right-10 bottom-6",children:v.jsx(wn,{onClick:()=>U(!1),children:"Ok"})})]})})})]})]})]})]})}const eZ="/assets/kofi_button_black-XI_Dr2zg.png";function tZ(){return v.jsxs(Jm,{children:[v.jsx(kx,{asChild:!0,children:v.jsx(yn,{tooltip:"Buy me a coffee",children:v.jsx(XU,{})})}),v.jsxs(Hd,{children:[v.jsx(Kd,{children:"Buy me a coffee"}),v.jsx(vP,{className:"mb-8",children:"Hi, if you found my project is useful, please conside buy me a coffee to support my work. Thanks!"}),v.jsx("div",{className:"w-full flex items-center justify-center",children:v.jsx("a",{href:"https://ko-fi.com/Z8Z1CZJGY",target:"_blank",rel:"noreferrer",children:v.jsx("img",{src:eZ,className:"h-[32px]"})})})]})]})}const nZ=()=>{const[e,t,n,r,o,i,s,l,u,f,m,p,g,y]=bt(M=>[M.file,M.customMask,M.isInpainting,M.serverConfig,M.runMannually(),M.settings.enableUploadMask,M.settings.model,M.setFile,M.setCustomFile,M.runInpainting,M.showPrevMask,M.hidePrevMask,M.imageHeight,M.imageWidth]),{toast:b}=Id(),[S,E]=Px(t),[_,x]=d.useState(!1),C=()=>{f()},R=()=>{m()},P=()=>{p()};return v.jsxs("header",{className:"h-[60px] px-6 py-4 absolute top-[0] flex justify-between items-center w-full z-20 border-b backdrop-filter backdrop-blur-md bg-background/70",children:[v.jsxs("div",{className:"flex items-center gap-1",children:[r.enableFileManager?v.jsx(PY,{photoWidth:512,onPhotoClick:async(M,A)=>{try{const D=await Vj(M,A);l(D)}catch(D){b({variant:"destructive",description:D.message?D.message:D.toString()});return}}}):v.jsx(v.Fragment,{}),v.jsx(f1,{disabled:n,tooltip:"Upload image",onFileUpload:M=>{l(M)},children:v.jsx(tV,{})}),v.jsxs("div",{className:Ce(["flex items-center gap-1",e&&i?"visible":"hidden"]),children:[v.jsx(f1,{disabled:n,tooltip:"Upload custom mask",onFileUpload:async M=>{let A=null;try{A=await gF(M)}catch(D){b({variant:"destructive",description:D.message?D.message:D.toString()});return}if(A.naturalHeight!==g||A.naturalWidth!==y){b({variant:"destructive",description:`The size of the mask must same as image: ${y}x${g}`});return}u(M),o||f()},children:v.jsx(qT,{})}),t?v.jsxs(KW,{open:_,children:[v.jsx(GW,{className:"btn-primary side-panel-trigger",onMouseEnter:()=>x(!0),onMouseLeave:()=>x(!1),style:{visibility:t?"visible":"hidden",outline:"none"},onClick:()=>{},children:v.jsx(yn,{tooltip:"Run custom mask",children:v.jsx(uz,{})})}),v.jsx(MP,{children:E?v.jsx("img",{src:S.src,alt:"Custom mask"}):v.jsx(v.Fragment,{})})]}):v.jsx(v.Fragment,{})]}),e&&!s.need_prompt?v.jsx(yn,{disabled:n,tooltip:"Rerun previous mask",onClick:C,onMouseEnter:R,onMouseLeave:P,children:v.jsx(iV,{})}):v.jsx(v.Fragment,{})]}),s.need_prompt?v.jsx(yH,{}):v.jsx(v.Fragment,{}),v.jsxs("div",{className:"flex gap-1",children:[v.jsx(tZ,{}),v.jsx(MW,{}),r.disableModelSwitch?v.jsx(v.Fragment,{}):v.jsx(JX,{})]})]})};var Wr=function(e,t){return Number(e.toFixed(t))},rZ=function(e,t){return typeof e=="number"?e:t},Nt=function(e,t,n){n&&typeof n=="function"&&n(e,t)},oZ=function(e){return-Math.cos(e*Math.PI)/2+.5},iZ=function(e){return e},sZ=function(e){return e*e},aZ=function(e){return e*(2-e)},lZ=function(e){return e<.5?2*e*e:-1+(4-2*e)*e},cZ=function(e){return e*e*e},uZ=function(e){return--e*e*e+1},dZ=function(e){return e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1},fZ=function(e){return e*e*e*e},hZ=function(e){return 1- --e*e*e*e},pZ=function(e){return e<.5?8*e*e*e*e:1-8*--e*e*e*e},mZ=function(e){return e*e*e*e*e},gZ=function(e){return 1+--e*e*e*e*e},vZ=function(e){return e<.5?16*e*e*e*e*e:1+16*--e*e*e*e*e},E3={easeOut:oZ,linear:iZ,easeInQuad:sZ,easeOutQuad:aZ,easeInOutQuad:lZ,easeInCubic:cZ,easeOutCubic:uZ,easeInOutCubic:dZ,easeInQuart:fZ,easeOutQuart:hZ,easeInOutQuart:pZ,easeInQuint:mZ,easeOutQuint:gZ,easeInOutQuint:vZ},C3=function(e){typeof e=="number"&&cancelAnimationFrame(e)},jo=function(e){e.mounted&&(C3(e.animation),e.animate=!1,e.animation=null,e.velocity=null)};function $3(e,t,n,r){if(e.mounted){var o=new Date().getTime(),i=1;jo(e),e.animation=function(){if(!e.mounted)return C3(e.animation);var s=new Date().getTime()-o,l=s/n,u=E3[t],f=u(l);s>=n?(r(i),e.animation=null):e.animation&&(r(f),requestAnimationFrame(e.animation))},requestAnimationFrame(e.animation)}}function yZ(e){var t=e.scale,n=e.positionX,r=e.positionY;return!(Number.isNaN(t)||Number.isNaN(n)||Number.isNaN(r))}function Bs(e,t,n,r){var o=yZ(t);if(!(!e.mounted||!o)){var i=e.setTransformState,s=e.transformState,l=s.scale,u=s.positionX,f=s.positionY,m=t.scale-l,p=t.positionX-u,g=t.positionY-f;n===0?i(t.scale,t.positionX,t.positionY):$3(e,r,n,function(y){var b=l+m*y,S=u+p*y,E=f+g*y;i(b,S,E)})}}function wZ(e,t,n){var r=e.offsetWidth,o=e.offsetHeight,i=t.offsetWidth,s=t.offsetHeight,l=i*n,u=s*n,f=r-l,m=o-u;return{wrapperWidth:r,wrapperHeight:o,newContentWidth:l,newDiffWidth:f,newContentHeight:u,newDiffHeight:m}}var xZ=function(e,t,n,r,o,i,s){var l=e>t?n*(s?1:.5):0,u=r>o?i*(s?1:.5):0,f=e-t-l,m=l,p=r-o-u,g=u;return{minPositionX:f,maxPositionX:m,minPositionY:p,maxPositionY:g}},qx=function(e,t){var n=e.wrapperComponent,r=e.contentComponent,o=e.setup.centerZoomedOut;if(!n||!r)throw new Error("Components are not mounted");var i=wZ(n,r,t),s=i.wrapperWidth,l=i.wrapperHeight,u=i.newContentWidth,f=i.newDiffWidth,m=i.newContentHeight,p=i.newDiffHeight,g=xZ(s,u,f,l,m,p,!!o);return g},j1=function(e,t,n,r){return r?en?Wr(n,2):Wr(e,2):Wr(e,2)},vc=function(e,t){var n=qx(e,t);return e.bounds=n,n};function dg(e,t,n,r,o,i,s){var l=n.minPositionX,u=n.minPositionY,f=n.maxPositionX,m=n.maxPositionY,p=0,g=0;s&&(p=o,g=i);var y=j1(e,l-p,f+p,r),b=j1(t,u-g,m+g,r);return{x:y,y:b}}function fg(e,t,n,r,o,i){var s=e.transformState,l=s.scale,u=s.positionX,f=s.positionY,m=r-l;if(typeof t!="number"||typeof n!="number")return console.error("Mouse X and Y position were not provided!"),{x:u,y:f};var p=u-t*m,g=f-n*m,y=dg(p,g,o,i,0,0,null);return y}function Zd(e,t,n,r,o){var i=o?r:0,s=t-i;return!Number.isNaN(n)&&e>=n?n:!Number.isNaN(t)&&e<=s?s:e}var N2=function(e,t){var n=e.setup.panning.excluded,r=e.isInitialized,o=e.wrapperComponent,i=t.target,s=o==null?void 0:o.contains(i),l=r&&i&&s;if(!l)return!1;var u=hg(i,n);return!u},D2=function(e){var t=e.isInitialized,n=e.isPanning,r=e.setup,o=r.panning.disabled,i=t&&n&&!o;return!!i},bZ=function(e,t){var n=e.transformState,r=n.positionX,o=n.positionY;e.isPanning=!0;var i=t.clientX,s=t.clientY;e.startCoords={x:i-r,y:s-o}},SZ=function(e,t){var n=t.touches,r=e.transformState,o=r.positionX,i=r.positionY;e.isPanning=!0;var s=n.length===1;if(s){var l=n[0].clientX,u=n[0].clientY;e.startCoords={x:l-o,y:u-i}}};function _Z(e){var t=e.transformState,n=t.positionX,r=t.positionY,o=t.scale,i=e.setup,s=i.disabled,l=i.limitToBounds,u=i.centerZoomedOut,f=e.wrapperComponent;if(!(s||!f||!e.bounds)){var m=e.bounds,p=m.maxPositionX,g=m.minPositionX,y=m.maxPositionY,b=m.minPositionY,S=n>p||ny||rp?f.offsetWidth:e.setup.minPositionX||0,x=r>y?f.offsetHeight:e.setup.minPositionY||0,C=fg(e,_,x,o,e.bounds,l||u),R=C.x,P=C.y;return{scale:o,positionX:S?R:n,positionY:E?P:r}}}function EZ(e,t,n,r,o){var i=e.setup.limitToBounds,s=e.wrapperComponent,l=e.bounds,u=e.transformState,f=u.scale,m=u.positionX,p=u.positionY;if(!(s===null||l===null||t===m&&n===p)){var g=dg(t,n,l,i,r,o,s),y=g.x,b=g.y;e.setTransformState(f,y,b)}}var CZ=function(e,t,n){var r=e.startCoords,o=e.transformState,i=e.setup.panning,s=i.lockAxisX,l=i.lockAxisY,u=o.positionX,f=o.positionY;if(!r)return{x:u,y:f};var m=t-r.x,p=n-r.y,g=s?u:m,y=l?f:p;return{x:g,y}},sm=function(e,t){var n=e.setup,r=e.transformState,o=r.scale,i=n.minScale,s=n.disablePadding;return t>0&&o>=i&&!s?t:0},$Z=function(e){var t=e.mounted,n=e.setup,r=n.disabled,o=n.velocityAnimation,i=e.transformState.scale,s=o.disabled,l=!s||i>1||!r||t;return!!l},RZ=function(e){var t=e.mounted,n=e.velocity,r=e.bounds,o=e.setup,i=o.disabled,s=o.velocityAnimation,l=e.transformState.scale,u=s.disabled,f=!u||l>1||!i||t;return!(!f||!n||!r)};function kZ(e,t){var n=e.setup.velocityAnimation,r=n.equalToMove,o=n.animationTime,i=n.sensitivity;return r?o*t*i:o}function I2(e,t,n,r,o,i,s,l,u,f){if(o){if(t>s&&n>s){var m=s+(e-s)*f;return m>u?u:mi?i:m}}return r?t:j1(e,i,s,o)}function TZ(e,t){var n=1;return t?Math.min(n,e.offsetWidth/window.innerWidth):n}function PZ(e,t){var n=$Z(e);if(n){var r=e.lastMousePosition,o=e.velocityTime,i=e.setup,s=e.wrapperComponent,l=i.velocityAnimation.equalToMove,u=Date.now();if(r&&o&&s){var f=TZ(s,l),m=t.x-r.x,p=t.y-r.y,g=m/f,y=p/f,b=u-o,S=m*m+p*p,E=Math.sqrt(S)/b;e.velocity={velocityX:g,velocityY:y,total:E}}e.lastMousePosition=t,e.velocityTime=u}}function AZ(e){var t=e.velocity,n=e.bounds,r=e.setup,o=e.wrapperComponent,i=RZ(e);if(!(!i||!t||!n||!o)){var s=t.velocityX,l=t.velocityY,u=t.total,f=n.maxPositionX,m=n.minPositionX,p=n.maxPositionY,g=n.minPositionY,y=r.limitToBounds,b=r.alignmentAnimation,S=r.zoomAnimation,E=r.panning,_=E.lockAxisY,x=E.lockAxisX,C=S.animationType,R=b.sizeX,P=b.sizeY,M=b.velocityAlignmentTime,A=M,D=kZ(e,u),U=Math.max(D,A),W=sm(e,R),q=sm(e,P),X=W*o.offsetWidth/100,ae=q*o.offsetHeight/100,V=f+X,F=m-X,N=p+ae,ie=g-ae,K=e.transformState,Z=new Date().getTime();$3(e,C,U,function(H){var se=e.transformState,ce=se.scale,Ve=se.positionX,Ue=se.positionY,We=new Date().getTime()-Z,Oe=We/A,he=E3[b.animationType],xe=1-he(Math.min(1,Oe)),$e=1-H,Ae=Ve+s*$e,Me=Ue+l*$e,je=I2(Ae,K.positionX,Ve,x,y,m,f,F,V,xe),Mt=I2(Me,K.positionY,Ue,_,y,g,p,ie,N,xe);(Ve!==Ae||Ue!==Me)&&e.setTransformState(ce,je,Mt)})}}function L2(e,t){var n=e.transformState.scale;jo(e),vc(e,n),window.TouchEvent!==void 0&&t instanceof TouchEvent?SZ(e,t):bZ(e,t)}function R3(e){var t=e.transformState.scale,n=e.setup,r=n.minScale,o=n.alignmentAnimation,i=o.disabled,s=o.sizeX,l=o.sizeY,u=o.animationTime,f=o.animationType,m=i||t.1&&p;g?AZ(e):R3(e)}}function Qx(e,t,n,r){var o=e.setup,i=o.minScale,s=o.maxScale,l=o.limitToBounds,u=Zd(Wr(t,2),i,s,0,!1),f=vc(e,u),m=fg(e,n,r,u,f,l),p=m.x,g=m.y;return{scale:u,positionX:p,positionY:g}}function k3(e,t,n){var r=e.transformState.scale,o=e.wrapperComponent,i=e.setup,s=i.minScale,l=i.limitToBounds,u=i.zoomAnimation,f=u.disabled,m=u.animationTime,p=u.animationType,g=f||r>=s;if((r>=1||l)&&R3(e),!(g||!o||!e.mounted)){var y=t||o.offsetWidth/2,b=n||o.offsetHeight/2,S=Qx(e,s,y,b);S&&Bs(e,S,m,p)}}var $s=function(){return $s=Object.assign||function(t){for(var n,r=1,o=arguments.length;rs||Math.sign(n.deltaY)!==Math.sign(t.deltaY)||n.deltaY>0&&n.deltaYt.deltaY||Math.sign(n.deltaY)!==Math.sign(t.deltaY):!1},XZ=function(e,t){var n=e.setup.pinch,r=n.disabled,o=n.excluded,i=e.isInitialized,s=t.target,l=i&&!r&&s;if(!l)return!1;var u=hg(s,o);return!u},ZZ=function(e){var t=e.setup.pinch.disabled,n=e.isInitialized,r=e.pinchStartDistance,o=n&&!t&&r;return!!o},qZ=function(e,t,n){var r=n.getBoundingClientRect(),o=e.touches,i=Wr(o[0].clientX-r.left,5),s=Wr(o[0].clientY-r.top,5),l=Wr(o[1].clientX-r.left,5),u=Wr(o[1].clientY-r.top,5);return{x:(i+l)/2/t,y:(s+u)/2/t}},D3=function(e){return Math.sqrt(Math.pow(e.touches[0].pageX-e.touches[1].pageX,2)+Math.pow(e.touches[0].pageY-e.touches[1].pageY,2))},QZ=function(e,t){var n=e.pinchStartScale,r=e.pinchStartDistance,o=e.setup,i=o.maxScale,s=o.minScale,l=o.zoomAnimation,u=o.disablePadding,f=l.size,m=l.disabled;if(!n||r===null||!t)throw new Error("Pinch touches distance was not provided");if(t<0)return e.transformState.scale;var p=t/r,g=p*n;return Zd(Wr(g,2),s,i,f,!m&&!u)},JZ=160,eq=100,tq=function(e,t){var n=e.props,r=n.onWheelStart,o=n.onZoomStart;e.wheelStopEventTimer||(jo(e),Nt(_t(e),t,r),Nt(_t(e),t,o))},nq=function(e,t){var n=e.props,r=n.onWheel,o=n.onZoom,i=e.contentComponent,s=e.setup,l=e.transformState,u=l.scale,f=s.limitToBounds,m=s.centerZoomedOut,p=s.zoomAnimation,g=s.wheel,y=s.disablePadding,b=s.smooth,S=p.size,E=p.disabled,_=g.step,x=g.smoothStep;if(!i)throw new Error("Component not mounted");t.preventDefault(),t.stopPropagation();var C=KZ(t,null),R=b?x*Math.abs(t.deltaY):_,P=GZ(e,C,R,!t.ctrlKey);if(u!==P){var M=vc(e,P),A=N3(t,i,u),D=E||S===0||m||y,U=f&&D,W=fg(e,A.x,A.y,P,M,U),q=W.x,X=W.y;e.previousWheelEvent=t,e.setTransformState(P,q,X),Nt(_t(e),t,r),Nt(_t(e),t,o)}},rq=function(e,t){var n=e.props,r=n.onWheelStop,o=n.onZoomStop;B1(e.wheelAnimationTimer),e.wheelAnimationTimer=setTimeout(function(){e.mounted&&(k3(e,t.x,t.y),e.wheelAnimationTimer=null)},eq);var i=YZ(e,t);i&&(B1(e.wheelStopEventTimer),e.wheelStopEventTimer=setTimeout(function(){e.mounted&&(e.wheelStopEventTimer=null,Nt(_t(e),t,r),Nt(_t(e),t,o))},JZ))},oq=function(e,t){var n=D3(t);e.pinchStartDistance=n,e.lastDistance=n,e.pinchStartScale=e.transformState.scale,e.isPanning=!1,jo(e)},iq=function(e,t){var n=e.contentComponent,r=e.pinchStartDistance,o=e.transformState.scale,i=e.setup,s=i.limitToBounds,l=i.centerZoomedOut,u=i.zoomAnimation,f=u.disabled,m=u.size;if(!(r===null||!n)){var p=qZ(t,o,n);if(!(!Number.isFinite(p.x)||!Number.isFinite(p.y))){var g=D3(t),y=QZ(e,g);if(y!==o){var b=vc(e,y),S=f||m===0||l,E=s&&S,_=fg(e,p.x,p.y,y,b,E),x=_.x,C=_.y;e.pinchMidpoint=p,e.lastDistance=g,e.setTransformState(y,x,C)}}}},sq=function(e){var t=e.pinchMidpoint;e.velocity=null,e.lastDistance=null,e.pinchMidpoint=null,e.pinchStartScale=null,e.pinchStartDistance=null,k3(e,t==null?void 0:t.x,t==null?void 0:t.y)},I3=function(e,t){var n=e.props.onZoomStop,r=e.setup.doubleClick.animationTime;B1(e.doubleClickStopEventTimer),e.doubleClickStopEventTimer=setTimeout(function(){e.doubleClickStopEventTimer=null,Nt(_t(e),t,n)},r)},aq=function(e,t){var n=e.props,r=n.onZoomStart,o=n.onZoom,i=e.setup.doubleClick,s=i.animationTime,l=i.animationType;Nt(_t(e),t,r),M3(e,s,l,function(){return Nt(_t(e),t,o)}),I3(e,t)};function lq(e,t){var n=e.setup,r=e.doubleClickStopEventTimer,o=e.transformState,i=e.contentComponent,s=o.scale,l=e.props,u=l.onZoomStart,f=l.onZoom,m=n.doubleClick,p=m.disabled,g=m.mode,y=m.step,b=m.animationTime,S=m.animationType;if(!p&&!r){if(g==="reset")return aq(e,t);if(!i)return console.error("No ContentComponent found");var E=g==="zoomOut"?-1:1,_=P3(e,E,y);if(s!==_){Nt(_t(e),t,u);var x=N3(t,i,s),C=Qx(e,_,x.x,x.y);if(!C)return console.error("Error during zoom event. New transformation state was not calculated.");Nt(_t(e),t,f),Bs(e,C,b,S),I3(e,t)}}}var cq=function(e,t){var n=e.isInitialized,r=e.setup,o=e.wrapperComponent,i=r.doubleClick,s=i.disabled,l=i.excluded,u=t.target,f=o==null?void 0:o.contains(u),m=n&&u&&f&&!s;if(!m)return!1;var p=hg(u,l);return!p},uq=function(){function e(t){var n=this;this.mounted=!0,this.onChangeCallbacks=new Set,this.onInitCallbacks=new Set,this.wrapperComponent=null,this.contentComponent=null,this.isInitialized=!1,this.bounds=null,this.previousWheelEvent=null,this.wheelStopEventTimer=null,this.wheelAnimationTimer=null,this.isPanning=!1,this.startCoords=null,this.lastTouch=null,this.distance=null,this.lastDistance=null,this.pinchStartDistance=null,this.pinchStartScale=null,this.pinchMidpoint=null,this.doubleClickStopEventTimer=null,this.velocity=null,this.velocityTime=null,this.lastMousePosition=null,this.animate=!1,this.animation=null,this.maxBounds=null,this.pressedKeys={},this.mount=function(){n.initializeWindowEvents()},this.unmount=function(){n.cleanupWindowEvents()},this.update=function(r){vc(n,n.transformState.scale),n.setup=z2(r)},this.initializeWindowEvents=function(){var r,o=j0(),i=(r=n.wrapperComponent)===null||r===void 0?void 0:r.ownerDocument,s=i==null?void 0:i.defaultView;s==null||s.addEventListener("mousedown",n.onPanningStart,o),s==null||s.addEventListener("mousemove",n.onPanning,o),s==null||s.addEventListener("mouseup",n.onPanningStop,o),i==null||i.addEventListener("mouseleave",n.clearPanning,o),s==null||s.addEventListener("keyup",n.setKeyUnPressed,o),s==null||s.addEventListener("keydown",n.setKeyPressed,o)},this.cleanupWindowEvents=function(){var r,o,i=j0(),s=(r=n.wrapperComponent)===null||r===void 0?void 0:r.ownerDocument,l=s==null?void 0:s.defaultView;l==null||l.removeEventListener("mousedown",n.onPanningStart,i),l==null||l.removeEventListener("mousemove",n.onPanning,i),l==null||l.removeEventListener("mouseup",n.onPanningStop,i),s==null||s.removeEventListener("mouseleave",n.clearPanning,i),l==null||l.removeEventListener("keyup",n.setKeyUnPressed,i),l==null||l.removeEventListener("keydown",n.setKeyPressed,i),document.removeEventListener("mouseleave",n.clearPanning,i),jo(n),(o=n.observer)===null||o===void 0||o.disconnect()},this.handleInitializeWrapperEvents=function(r){var o=j0();r.addEventListener("wheel",n.onWheelZoom,o),r.addEventListener("dblclick",n.onDoubleClick,o),r.addEventListener("touchstart",n.onTouchPanningStart,o),r.addEventListener("touchmove",n.onTouchPanning,o),r.addEventListener("touchend",n.onTouchPanningStop,o)},this.handleInitialize=function(r){var o=n.setup.centerOnInit;n.applyTransformation(),n.onInitCallbacks.forEach(function(i){return i(_t(n))}),o&&(n.setCenter(),n.observer=new ResizeObserver(function(){var i;n.onInitCallbacks.forEach(function(s){return s(_t(n))}),n.setCenter(),(i=n.observer)===null||i===void 0||i.disconnect()}),n.observer.observe(r))},this.onWheelZoom=function(r){var o=n.setup.disabled;if(!o){var i=WZ(n,r);if(i){var s=n.isPressingKeys(n.setup.wheel.activationKeys);s&&(tq(n,r),nq(n,r),rq(n,r))}}},this.onPanningStart=function(r){var o=n.setup.disabled,i=n.props.onPanningStart;if(!o){var s=N2(n,r);if(s){var l=n.isPressingKeys(n.setup.panning.activationKeys);l&&(r.button===0&&!n.setup.panning.allowLeftClickPan||r.button===1&&!n.setup.panning.allowMiddleClickPan||r.button===2&&!n.setup.panning.allowRightClickPan||(r.preventDefault(),r.stopPropagation(),jo(n),L2(n,r),Nt(_t(n),r,i)))}}},this.onPanning=function(r){var o=n.setup.disabled,i=n.props.onPanning;if(!o){var s=D2(n);if(s){var l=n.isPressingKeys(n.setup.panning.activationKeys);l&&(r.preventDefault(),r.stopPropagation(),F2(n,r.clientX,r.clientY),Nt(_t(n),r,i))}}},this.onPanningStop=function(r){var o=n.props.onPanningStop;n.isPanning&&(MZ(n),Nt(_t(n),r,o))},this.onPinchStart=function(r){var o=n.setup.disabled,i=n.props,s=i.onPinchingStart,l=i.onZoomStart;if(!o){var u=XZ(n,r);u&&(oq(n,r),jo(n),Nt(_t(n),r,s),Nt(_t(n),r,l))}},this.onPinch=function(r){var o=n.setup.disabled,i=n.props,s=i.onPinching,l=i.onZoom;if(!o){var u=ZZ(n);u&&(r.preventDefault(),r.stopPropagation(),iq(n,r),Nt(_t(n),r,s),Nt(_t(n),r,l))}},this.onPinchStop=function(r){var o=n.props,i=o.onPinchingStop,s=o.onZoomStop;n.pinchStartScale&&(sq(n),Nt(_t(n),r,i),Nt(_t(n),r,s))},this.onTouchPanningStart=function(r){var o=n.setup.disabled,i=n.props.onPanningStart;if(!o){var s=N2(n,r);if(s){var l=n.lastTouch&&+new Date-n.lastTouch<200;if(l&&r.touches.length===1)n.onDoubleClick(r);else{n.lastTouch=+new Date,jo(n);var u=r.touches,f=u.length===1,m=u.length===2;f&&(jo(n),L2(n,r),Nt(_t(n),r,i)),m&&n.onPinchStart(r)}}}},this.onTouchPanning=function(r){var o=n.setup.disabled,i=n.props.onPanning;if(n.isPanning&&r.touches.length===1){if(o)return;var s=D2(n);if(!s)return;r.preventDefault(),r.stopPropagation();var l=r.touches[0];F2(n,l.clientX,l.clientY),Nt(_t(n),r,i)}else r.touches.length>1&&n.onPinch(r)},this.onTouchPanningStop=function(r){n.onPanningStop(r),n.onPinchStop(r)},this.onDoubleClick=function(r){var o=n.setup.disabled;if(!o){var i=cq(n,r);i&&lq(n,r)}},this.clearPanning=function(r){n.isPanning&&n.onPanningStop(r)},this.setKeyPressed=function(r){n.pressedKeys[r.key]=!0},this.setKeyUnPressed=function(r){n.pressedKeys[r.key]=!1},this.isPressingKeys=function(r){return r.length?!!r.find(function(o){return n.pressedKeys[o]}):!0},this.setTransformState=function(r,o,i){var s=n.props.onTransformed;if(!Number.isNaN(r)&&!Number.isNaN(o)&&!Number.isNaN(i)){r!==n.transformState.scale&&(n.transformState.previousScale=n.transformState.scale,n.transformState.scale=r),n.transformState.positionX=o,n.transformState.positionY=i,n.applyTransformation();var l=_t(n);n.onChangeCallbacks.forEach(function(u){return u(l)}),Nt(l,{scale:r,positionX:o,positionY:i},s)}else console.error("Detected NaN set state values")},this.setCenter=function(){if(n.wrapperComponent&&n.contentComponent){var r=O3(n.transformState.scale,n.wrapperComponent,n.contentComponent);n.setTransformState(r.scale,r.positionX,r.positionY)}},this.handleTransformStyles=function(r,o,i){return n.props.customTransform?n.props.customTransform(r,o,i):UZ(r,o,i)},this.applyTransformation=function(){if(!(!n.mounted||!n.contentComponent)){var r=n.transformState,o=r.scale,i=r.positionX,s=r.positionY,l=n.handleTransformStyles(i,s,o);n.contentComponent.style.transform=l}},this.getContext=function(){return _t(n)},this.onChange=function(r){return n.onChangeCallbacks.has(r)||n.onChangeCallbacks.add(r),function(){n.onChangeCallbacks.delete(r)}},this.onInit=function(r){return n.onInitCallbacks.has(r)||n.onInitCallbacks.add(r),function(){n.onInitCallbacks.delete(r)}},this.init=function(r,o){n.cleanupWindowEvents(),n.wrapperComponent=r,n.contentComponent=o,vc(n,n.transformState.scale),n.handleInitializeWrapperEvents(r),n.handleInitialize(o),n.initializeWindowEvents(),n.isInitialized=!0;var i=_t(n);Nt(i,void 0,n.props.onInit)},this.props=t,this.setup=z2(this.props),this.transformState=T3(this.props)}return e}(),Jx=Fe.createContext(null),dq=function(e,t){return typeof e=="function"?e(t):e},fq=Fe.forwardRef(function(e,t){var n=d.useRef(new uq(e)).current,r=dq(e.children,z1(n));return d.useImperativeHandle(t,function(){return z1(n)},[n]),d.useEffect(function(){n.update(e)},[n,e]),Fe.createElement(Jx.Provider,{value:n},r)});Fe.forwardRef(function(e,t){var n=d.useRef(null),r=d.useContext(Jx);return d.useEffect(function(){return r.onChange(function(o){if(n.current){var i=0,s=0;n.current.style.transform=r.handleTransformStyles(i,s,1/o.instance.transformState.scale)}})},[r]),Fe.createElement("div",$s({},e,{ref:VZ([n,t])}))});function hq(e,t){t===void 0&&(t={});var n=t.insertAt;if(!(!e||typeof document>"u")){var r=document.head||document.getElementsByTagName("head")[0],o=document.createElement("style");o.type="text/css",n==="top"&&r.firstChild?r.insertBefore(o,r.firstChild):r.appendChild(o),o.styleSheet?o.styleSheet.cssText=e:o.appendChild(document.createTextNode(e))}}var pq=`.transform-component-module_wrapper__SPB86 { + position: relative; + width: -moz-fit-content; + width: fit-content; + height: -moz-fit-content; + height: fit-content; + overflow: hidden; + -webkit-touch-callout: none; /* iOS Safari */ + -webkit-user-select: none; /* Safari */ + -khtml-user-select: none; /* Konqueror HTML */ + -moz-user-select: none; /* Firefox */ + -ms-user-select: none; /* Internet Explorer/Edge */ + user-select: none; + margin: 0; + padding: 0; +} +.transform-component-module_content__FBWxo { + display: flex; + flex-wrap: wrap; + width: -moz-fit-content; + width: fit-content; + height: -moz-fit-content; + height: fit-content; + margin: 0; + padding: 0; + transform-origin: 0% 0%; +} +.transform-component-module_content__FBWxo img { + pointer-events: none; +} +`,B2={wrapper:"transform-component-module_wrapper__SPB86",content:"transform-component-module_content__FBWxo"};hq(pq);var mq=function(e){var t=e.children,n=e.wrapperClass,r=n===void 0?"":n,o=e.contentClass,i=o===void 0?"":o,s=e.wrapperStyle,l=e.contentStyle,u=e.wrapperProps,f=u===void 0?{}:u,m=e.contentProps,p=m===void 0?{}:m,g=d.useContext(Jx),y=g.init,b=g.cleanupWindowEvents,S=d.useRef(null),E=d.useRef(null);return d.useEffect(function(){var _=S.current,x=E.current;return _!==null&&x!==null&&y&&(y==null||y(_,x)),function(){b==null||b()}},[]),Fe.createElement("div",$s({},f,{ref:S,className:"react-transform-wrapper ".concat(B2.wrapper," ").concat(r),style:s}),Fe.createElement("div",$s({},p,{ref:E,className:"react-transform-component ".concat(B2.content," ").concat(i),style:l}),t))};const L3=["PageUp","PageDown"],F3=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],j3={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},qd="Slider",[U1,gq,vq]=Gd(qd),[z3,Cte]=Mn(qd,[vq]),[yq,pg]=z3(qd),wq=d.forwardRef((e,t)=>{const{name:n,min:r=0,max:o=100,step:i=1,orientation:s="horizontal",disabled:l=!1,minStepsBetweenThumbs:u=0,defaultValue:f=[r],value:m,onValueChange:p=()=>{},onValueCommit:g=()=>{},inverted:y=!1,...b}=e,[S,E]=d.useState(null),_=Be(t,V=>E(V)),x=d.useRef(new Set),C=d.useRef(0),R=s==="horizontal",P=S?!!S.closest("form"):!0,M=R?xq:bq,[A=[],D]=Zr({prop:m,defaultProp:f,onChange:V=>{var F;(F=[...x.current][C.current])===null||F===void 0||F.focus(),p(V)}}),U=d.useRef(A);function W(V){const F=Pq(A,V);ae(V,F)}function q(V){ae(V,C.current)}function X(){const V=U.current[C.current];A[C.current]!==V&&g(A)}function ae(V,F,{commit:N}={commit:!1}){const ie=Nq(i),K=Dq(Math.round((V-r)/i)*i+r,ie),Z=fd(K,[r,o]);D((H=[])=>{const se=kq(H,Z,F);if(Oq(se,u*i)){C.current=se.indexOf(Z);const ce=String(se)!==String(H);return ce&&N&&g(se),ce?se:H}else return H})}return d.createElement(yq,{scope:e.__scopeSlider,disabled:l,min:r,max:o,valueIndexToChangeRef:C,thumbs:x.current,values:A,orientation:s},d.createElement(U1.Provider,{scope:e.__scopeSlider},d.createElement(U1.Slot,{scope:e.__scopeSlider},d.createElement(M,Y({"aria-disabled":l,"data-disabled":l?"":void 0},b,{ref:_,onPointerDown:de(b.onPointerDown,()=>{l||(U.current=A)}),min:r,max:o,inverted:y,onSlideStart:l?void 0:W,onSlideMove:l?void 0:q,onSlideEnd:l?void 0:X,onHomeKeyDown:()=>!l&&ae(r,0,{commit:!0}),onEndKeyDown:()=>!l&&ae(o,A.length-1,{commit:!0}),onStepKeyDown:({event:V,direction:F})=>{if(!l){const K=L3.includes(V.key)||V.shiftKey&&F3.includes(V.key)?10:1,Z=C.current,H=A[Z],se=i*K*F;ae(H+se,Z,{commit:!0})}}})))),P&&A.map((V,F)=>d.createElement(Rq,{key:F,name:n?n+(A.length>1?"[]":""):void 0,value:V})))}),[B3,U3]=z3(qd,{startEdge:"left",endEdge:"right",size:"width",direction:1}),xq=d.forwardRef((e,t)=>{const{min:n,max:r,dir:o,inverted:i,onSlideStart:s,onSlideMove:l,onSlideEnd:u,onStepKeyDown:f,...m}=e,[p,g]=d.useState(null),y=Be(t,C=>g(C)),b=d.useRef(),S=Tc(o),E=S==="ltr",_=E&&!i||!E&&i;function x(C){const R=b.current||p.getBoundingClientRect(),P=[0,R.width],A=eb(P,_?[n,r]:[r,n]);return b.current=R,A(C-R.left)}return d.createElement(B3,{scope:e.__scopeSlider,startEdge:_?"left":"right",endEdge:_?"right":"left",direction:_?1:-1,size:"width"},d.createElement(V3,Y({dir:S,"data-orientation":"horizontal"},m,{ref:y,style:{...m.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:C=>{const R=x(C.clientX);s==null||s(R)},onSlideMove:C=>{const R=x(C.clientX);l==null||l(R)},onSlideEnd:()=>{b.current=void 0,u==null||u()},onStepKeyDown:C=>{const P=j3[_?"from-left":"from-right"].includes(C.key);f==null||f({event:C,direction:P?-1:1})}})))}),bq=d.forwardRef((e,t)=>{const{min:n,max:r,inverted:o,onSlideStart:i,onSlideMove:s,onSlideEnd:l,onStepKeyDown:u,...f}=e,m=d.useRef(null),p=Be(t,m),g=d.useRef(),y=!o;function b(S){const E=g.current||m.current.getBoundingClientRect(),_=[0,E.height],C=eb(_,y?[r,n]:[n,r]);return g.current=E,C(S-E.top)}return d.createElement(B3,{scope:e.__scopeSlider,startEdge:y?"bottom":"top",endEdge:y?"top":"bottom",size:"height",direction:y?1:-1},d.createElement(V3,Y({"data-orientation":"vertical"},f,{ref:p,style:{...f.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:S=>{const E=b(S.clientY);i==null||i(E)},onSlideMove:S=>{const E=b(S.clientY);s==null||s(E)},onSlideEnd:()=>{g.current=void 0,l==null||l()},onStepKeyDown:S=>{const _=j3[y?"from-bottom":"from-top"].includes(S.key);u==null||u({event:S,direction:_?-1:1})}})))}),V3=d.forwardRef((e,t)=>{const{__scopeSlider:n,onSlideStart:r,onSlideMove:o,onSlideEnd:i,onHomeKeyDown:s,onEndKeyDown:l,onStepKeyDown:u,...f}=e,m=pg(qd,n);return d.createElement(Pe.span,Y({},f,{ref:t,onKeyDown:de(e.onKeyDown,p=>{p.key==="Home"?(s(p),p.preventDefault()):p.key==="End"?(l(p),p.preventDefault()):L3.concat(F3).includes(p.key)&&(u(p),p.preventDefault())}),onPointerDown:de(e.onPointerDown,p=>{const g=p.target;g.setPointerCapture(p.pointerId),p.preventDefault(),m.thumbs.has(g)?g.focus():r(p)}),onPointerMove:de(e.onPointerMove,p=>{p.target.hasPointerCapture(p.pointerId)&&o(p)}),onPointerUp:de(e.onPointerUp,p=>{const g=p.target;g.hasPointerCapture(p.pointerId)&&(g.releasePointerCapture(p.pointerId),i(p))})}))}),Sq="SliderTrack",_q=d.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,o=pg(Sq,n);return d.createElement(Pe.span,Y({"data-disabled":o.disabled?"":void 0,"data-orientation":o.orientation},r,{ref:t}))}),U2="SliderRange",Eq=d.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,o=pg(U2,n),i=U3(U2,n),s=d.useRef(null),l=Be(t,s),u=o.values.length,f=o.values.map(g=>W3(g,o.min,o.max)),m=u>1?Math.min(...f):0,p=100-Math.max(...f);return d.createElement(Pe.span,Y({"data-orientation":o.orientation,"data-disabled":o.disabled?"":void 0},r,{ref:l,style:{...e.style,[i.startEdge]:m+"%",[i.endEdge]:p+"%"}}))}),V2="SliderThumb",Cq=d.forwardRef((e,t)=>{const n=gq(e.__scopeSlider),[r,o]=d.useState(null),i=Be(t,l=>o(l)),s=d.useMemo(()=>r?n().findIndex(l=>l.ref.current===r):-1,[n,r]);return d.createElement($q,Y({},e,{ref:i,index:s}))}),$q=d.forwardRef((e,t)=>{const{__scopeSlider:n,index:r,...o}=e,i=pg(V2,n),s=U3(V2,n),[l,u]=d.useState(null),f=Be(t,E=>u(E)),m=yx(l),p=i.values[r],g=p===void 0?0:W3(p,i.min,i.max),y=Tq(r,i.values.length),b=m==null?void 0:m[s.size],S=b?Aq(b,g,s.direction):0;return d.useEffect(()=>{if(l)return i.thumbs.add(l),()=>{i.thumbs.delete(l)}},[l,i.thumbs]),d.createElement("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[s.startEdge]:`calc(${g}% + ${S}px)`}},d.createElement(U1.ItemSlot,{scope:e.__scopeSlider},d.createElement(Pe.span,Y({role:"slider","aria-label":e["aria-label"]||y,"aria-valuemin":i.min,"aria-valuenow":p,"aria-valuemax":i.max,"aria-orientation":i.orientation,"data-orientation":i.orientation,"data-disabled":i.disabled?"":void 0,tabIndex:i.disabled?void 0:0},o,{ref:f,style:p===void 0?{display:"none"}:e.style,onFocus:de(e.onFocus,()=>{i.valueIndexToChangeRef.current=r})}))))}),Rq=e=>{const{value:t,...n}=e,r=d.useRef(null),o=zx(t);return d.useEffect(()=>{const i=r.current,s=window.HTMLInputElement.prototype,u=Object.getOwnPropertyDescriptor(s,"value").set;if(o!==t&&u){const f=new Event("input",{bubbles:!0});u.call(i,t),i.dispatchEvent(f)}},[o,t]),d.createElement("input",Y({style:{display:"none"}},n,{ref:r,defaultValue:t}))};function kq(e=[],t,n){const r=[...e];return r[n]=t,r.sort((o,i)=>o-i)}function W3(e,t,n){const i=100/(n-t)*(e-t);return fd(i,[0,100])}function Tq(e,t){return t>2?`Value ${e+1} of ${t}`:t===2?["Minimum","Maximum"][e]:void 0}function Pq(e,t){if(e.length===1)return 0;const n=e.map(o=>Math.abs(o-t)),r=Math.min(...n);return n.indexOf(r)}function Aq(e,t,n){const r=e/2,i=eb([0,50],[0,r]);return(r-i(t)*n)*n}function Mq(e){return e.slice(0,-1).map((t,n)=>e[n+1]-t)}function Oq(e,t){if(t>0){const n=Mq(e);return Math.min(...n)>=t}return!0}function eb(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 Nq(e){return(String(e).split(".")[1]||"").length}function Dq(e,t){const n=Math.pow(10,t);return Math.round(e*n)/n}const H3=wq,Iq=_q,Lq=Eq,Fq=Cq,uo=d.forwardRef(({className:e,...t},n)=>v.jsxs(H3,{ref:n,className:Ce("relative flex w-full touch-none select-none items-center",e),tabIndex:-1,...t,children:[v.jsx(Iq,{className:"relative h-1.5 w-full grow overflow-hidden rounded-full bg-primary/20 data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50",children:v.jsx(Lq,{className:"absolute h-full bg-primary data-[disabled]:cursor-not-allowed "})}),v.jsx(Fq,{tabIndex:-1,className:"block h-4 w-4 rounded-full border border-primary/60 bg-background shadow transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring data-[disabled]:cursor-not-allowed"})]}));uo.displayName=H3.displayName;const ll={capture:!0,passive:!1},jq=2,W2=(e,t,n,r,o,i)=>{if(e!==n&&t===r){if(e<0)return[0,r];if(e+t>i)return[i-r,r]}else{if(ti)return[e,i-e]}return[e,t]},zq=e=>{const{minHeight:t,minWidth:n,maxHeight:r,maxWidth:o,scale:i,show:s}=e,[l,u,f,m,{x:p,y:g,width:y,height:b},S,E,_,x,C,R]=bt(H=>[H.imageWidth,H.imageHeight,H.isInpainting,H.isSD(),H.cropperState,H.setCropperX,H.setCropperY,H.setCropperWidth,H.setCropperHeight,H.isCropperExtenderResizing,H.setIsCropperExtenderResizing]),[P,M]=d.useState(!1);d.useEffect(()=>{S(Math.round((o-512)/2)),E(Math.round((r-512)/2))},[r,o,l,u]);const[A,D]=d.useState({initX:0,initY:0,initHeight:0,initWidth:0,startResizeX:0,startResizeY:0,ord:"top"}),U=()=>{},W=(H,se)=>W2(H,se,p,y,n,o),q=(H,se)=>W2(H,se,g,b,t,r),X=H=>{if(f)return;const se=H.clientX,ce=H.clientY,Ve=Math.round((ce-A.startResizeY)/i),Ue=Math.round((se-A.startResizeX)/i),We=()=>{const $e=A.initHeight-Ve,Ae=A.initY+Ve,[Me,je]=q(Ae,$e);x(je),E(Me)},Oe=()=>{const $e=A.initHeight+Ve,[Ae,Me]=q(A.initY,$e);x(Me),E(Ae)},he=()=>{const $e=A.initWidth-Ue,Ae=A.initX+Ue,[Me,je]=W(Ae,$e);_(je),S(Me)},xe=()=>{const $e=A.initWidth+Ue,[Ae,Me]=W(A.initX,$e);_(Me),S(Ae)};if(C)switch(A.ord){case"topleft":{We(),he();break}case"topright":{We(),xe();break}case"bottomleft":{Oe(),he();break}case"bottomright":{Oe(),xe();break}case"top":{We();break}case"right":{xe();break}case"bottom":{Oe();break}case"left":{he();break}}if(P){const $e=A.initX+Ue,Ae=A.initY+Ve,[Me,je]=W($e,A.initWidth),[Mt,ct]=q(Ae,A.initHeight);_(je),x(ct),S(Me),E(Mt)}},ae=()=>{C&&R(!1),P&&M(!1)};d.useEffect(()=>{if(C||P)return document.addEventListener("pointermove",X,ll),document.addEventListener("pointerup",ae,ll),document.addEventListener("pointercancel",ae,ll),()=>{document.removeEventListener("pointermove",X,ll),document.removeEventListener("pointerup",ae,ll),document.removeEventListener("pointercancel",ae,ll)}},[C,P,y,b,A]);const V=H=>{const{ord:se}=H.target.dataset;se&&(R(!0),D({initX:p,initY:g,initHeight:b,initWidth:y,startResizeX:H.clientX,startResizeY:H.clientY,ord:se}))},F=(H,se,ce)=>{const We="w-[12px] h-[12px] z-[4] absolute content-[''] block border-2 border-primary borde pointer-events-auto hover:bg-primary";let Oe="0",he="0",xe=ce,$e="-6px";return ce===""&&($e="50%",se==="left"||se==="right"?(xe="top",he="-50%"):(xe="left",Oe="-50%")),v.jsx("div",{className:Ce(We,H),style:{[se]:-6,[xe]:$e,transform:`translate(${Oe}, ${he}) scale(${1/i})`},"data-ord":se+ce,"aria-label":se+ce,tabIndex:-1,role:"button"})},N=()=>v.jsxs("div",{onFocus:U,onPointerDown:V,className:"absolute top-0 h-full w-full",children:[v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 w-full cursor-ns-resize h-[12px] mt-[-6px]","data-ord":"top"}),v.jsx("div",{className:"absolute pointer-events-auto top-0 right-0 h-full cursor-ew-resize w-[12px] mr-[-6px]","data-ord":"right"}),v.jsx("div",{className:"absolute pointer-events-auto bottom-0 left-0 w-full cursor-ns-resize h-[12px] mb-[-6px]","data-ord":"bottom"}),v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 h-full cursor-ew-resize w-[12px] ml-[-6px]","data-ord":"left"}),F("cursor-nw-resize","top","left"),F("cursor-ne-resize","top","right"),F("cursor-sw-resize","bottom","left"),F("cursor-se-resize","bottom","right"),F("cursor-ns-resize","top",""),F("cursor-ns-resize","bottom",""),F("cursor-ew-resize","left",""),F("cursor-ew-resize","right","")]}),ie=H=>{M(!0),D({initX:p,initY:g,initHeight:b,initWidth:y,startResizeX:H.clientX,startResizeY:H.clientY,ord:""})},K=()=>v.jsxs("div",{className:tx("border absolute pointer-events-auto px-2 py-1 rounded-full hover:cursor-move bg-background","origin-top-left top-0 left-0"),style:{transform:`scale(${1/i*.8})`},onPointerDown:ie,children:[y," x ",b]}),Z=()=>v.jsx("div",{className:"outline-dashed outline-primary",style:{height:b,width:y,outlineWidth:`${jq/i*1.3}px`}});return s===!1||!m?null:v.jsx("div",{className:"absolute h-full w-full overflow-hidden pointer-events-none z-[2]",children:v.jsxs("div",{className:"relative pointer-events-none z-[2] [box-shadow:0_0_0_9999px_rgba(0,_0,_0,_0.5)]",style:{height:b,width:y,left:p,top:g},children:[Z(),K(),N()]})})},Bq=()=>{const[e,t,n]=bt(r=>[r.interactiveSegState,r.resetInteractiveSegState,r.handleInteractiveSegAccept]);return e.isInteractiveSeg?v.jsxs("div",{className:"z-10 absolute top-[68px] rounded-xl border-solid border p-[8px] left-1/2 translate-x-[-50%] flex justify-center items-center gap-[8px] bg-background",children:[v.jsx(wn,{onClick:()=>{t()},size:"sm",variant:"secondary",children:"Cancel"}),v.jsx(wn,{size:"sm",onClick:()=>{n()},children:"Accept"})]}):null},Uq=e=>{const{x:t,y:n,positive:r}=e,o=r?"bg-[rgba(21,_215,_121,_0.936)] outline-[rgba(98,255,179,0.31)]":"bg-[rgba(237,_49,_55,_0.942)] outline-[rgba(255,89,95,0.31)]";return v.jsx("div",{className:`absolute h-[10px] w-[10px] rounded-[50%] ${o} outline-8 outline`,style:{left:t,top:n,transform:"translate(-50%, -50%)"}})},Vq=()=>{const e=bt(t=>t.interactiveSegState.clicks);return v.jsx("div",{className:"absolute h-full w-full overflow-hidden pointer-events-none",children:e.map(t=>v.jsx(Uq,{x:t[0],y:t[1],positive:t[2]===1},t[3]))})},Wq=()=>v.jsx("div",{children:v.jsx(Bq,{})}),cl={capture:!0,passive:!1},Hq=2,H2=(e,t,n,r)=>t{const{minHeight:t,minWidth:n,scale:r,show:o}=e,[i,s,l,u,{x:f,y:m,width:p,height:g},y,b,S,E,_,x,C]=bt(ie=>[ie.isInpainting,ie.imageHeight,ie.imageWidth,ie.isSD(),ie.extenderState,ie.setExtenderX,ie.setExtenderY,ie.setExtenderWidth,ie.setExtenderHeight,ie.settings.extenderDirection,ie.isCropperExtenderResizing,ie.setIsCropperExtenderResizing]),[R,P]=d.useState({initX:0,initY:0,initHeight:0,initWidth:0,startResizeX:0,startResizeY:0,ord:"top"}),M=()=>{},A=(ie,K)=>H2(ie,K,f,n),D=(ie,K)=>H2(ie,K,m,t),U=ie=>{if(i)return;const K=ie.clientX,Z=ie.clientY,H=Math.round((Z-R.startResizeY)/r),se=Math.round((K-R.startResizeX)/r),ce=()=>{const Oe=R.initHeight-H,he=R.initY+H;let xe=he,$e=Oe;if(_===Ln.xy)xe>0&&(xe=0,$e=R.initHeight-Math.abs(R.initY));else{const Ae=D(he,Oe);xe=Ae[0],$e=Ae[1]}E($e),b(xe)},Ve=()=>{const Oe=R.initHeight+H;let[he,xe]=D(R.initY,Oe);_===Ln.xy&&xe{const Oe=R.initWidth-se,he=R.initX+se;let xe=he,$e=Oe;if(_===Ln.xy)xe>0&&(xe=0,$e=R.initWidth-Math.abs(R.initX));else{const Ae=A(he,Oe);xe=Ae[0],$e=Ae[1]}S($e),y(xe)},We=()=>{const Oe=R.initWidth+se;let[he,xe]=A(R.initX,Oe);_===Ln.xy&&xe{x&&C(!1)};d.useEffect(()=>{if(x)return document.addEventListener("pointermove",U,cl),document.addEventListener("pointerup",W,cl),document.addEventListener("pointercancel",W,cl),()=>{document.removeEventListener("pointermove",U,cl),document.removeEventListener("pointerup",W,cl),document.removeEventListener("pointercancel",W,cl)}},[x,p,g,R]);const q=ie=>{const{ord:K}=ie.target.dataset;K&&(C(!0),P({initX:f,initY:m,initHeight:g,initWidth:p,startResizeX:ie.clientX,startResizeY:ie.clientY,ord:K}))},X=(ie,K,Z)=>{const ce="w-[12px] h-[12px] z-[4] absolute content-[''] block border-2 border-primary borde pointer-events-auto hover:bg-primary";let Ve="0",Ue="0",We=Z,Oe="-6px";return Z===""&&(Oe="50%",K==="left"||K==="right"?(We="top",Ue="-50%"):(We="left",Ve="-50%")),v.jsx("div",{className:Ce(ce,ie),style:{[K]:-6,[We]:Oe,transform:`translate(${Ve}, ${Ue}) scale(${1/r})`},"data-ord":K+Z,"aria-label":K+Z,tabIndex:-1,role:"button"})},ae=()=>v.jsxs("div",{onFocus:M,onPointerDown:q,className:"absolute top-0 h-full w-full",children:[[Ln.y,Ln.xy].includes(_)?v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 w-full cursor-ns-resize h-[12px] mt-[-6px]","data-ord":"top"}),v.jsx("div",{className:"absolute pointer-events-auto bottom-0 left-0 w-full cursor-ns-resize h-[12px] mb-[-6px]","data-ord":"bottom"}),X("cursor-ns-resize","top",""),X("cursor-ns-resize","bottom","")]}):v.jsx(v.Fragment,{}),[Ln.x,Ln.xy].includes(_)?v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"absolute pointer-events-auto top-0 right-0 h-full cursor-ew-resize w-[12px] mr-[-6px]","data-ord":"right"}),v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 h-full cursor-ew-resize w-[12px] ml-[-6px]","data-ord":"left"}),X("cursor-ew-resize","left",""),X("cursor-ew-resize","right","")]}):v.jsx(v.Fragment,{}),_===Ln.xy?v.jsxs(v.Fragment,{children:[X("cursor-nw-resize","top","left"),X("cursor-ne-resize","top","right"),X("cursor-sw-resize","bottom","left"),X("cursor-se-resize","bottom","right")]}):v.jsx(v.Fragment,{})]}),V=ie=>{P({initX:f,initY:m,initHeight:g,initWidth:p,startResizeX:ie.clientX,startResizeY:ie.clientY,ord:""})},F=()=>v.jsxs("div",{className:tx("border absolute pointer-events-auto px-2 py-1 rounded-full bg-background","origin-top-left top-0 left-0"),style:{transform:`scale(${1/r*.8})`},onPointerDown:V,children:[p," x ",g]}),N=()=>v.jsx("div",{className:Ce("outline-dashed outline-primary"),style:{height:g,width:p,outlineWidth:`${Hq/r*1.3}px`}});return o===!1||!u?null:v.jsx("div",{className:"absolute h-full w-full pointer-events-none z-[2]",children:v.jsxs("div",{className:"relative pointer-events-none z-[2] [box-shadow:0_0_0_9999px_rgba(0,_0,_0,_0.5)]",style:{height:g,width:p,left:f,top:m},children:[N(),F(),ae()]})})},Gq=200,Yq=10,Xq=200,mu=300;function Zq(e){const{file:t}=e,{toast:n}=Id(),[r,o,i,s,l,u,f,m,p,g,y,b,S,E,_,x,C,R,P,M,A,D]=bt(G=>[G.disableShortCuts,G.windowSize,G.isInpainting,G.imageWidth,G.imageHeight,G.settings,G.serverConfig.enableAutoSaving,G.setImageSize,G.setBaseBrushSize,G.interactiveSegState,G.updateInteractiveSegState,G.handleCanvasMouseDown,G.handleCanvasMouseMove,G.undo,G.redo,G.undoDisabled(),G.redoDisabled(),G.getIsProcessing(),G.updateAppState,G.runMannually(),G.runInpainting,G.isCropperExtenderResizing]),U=bt(G=>G.editorState.baseBrushSize),W=bt(G=>G.getBrushSize()),q=bt(G=>G.editorState.renders),X=bt(G=>G.editorState.extraMasks),ae=bt(G=>G.editorState.temporaryMasks),V=bt(G=>G.editorState.lineGroups),F=bt(G=>G.editorState.curLineGroup),[N,ie]=d.useState(!1),[K,Z]=Px(t),[H,se]=d.useState(),[ce,Ve]=d.useState(),[{x:Ue,y:We},Oe]=d.useState({x:-1,y:-1}),[he,xe]=d.useState(!1),[$e,Ae]=d.useState(!1),[Me,je]=d.useState(!1),[Mt,ct]=d.useState(1),[Kt,Er]=d.useState(!1),[gt,Vs]=d.useState(1),L=o.width/2,Q=o.height/2,J=d.useRef(null),[we,me]=d.useState(!1),[fe,Re]=d.useState(!1),[ft,ht]=d.useState(0),_n=d.useCallback(()=>F.length!==0,[F]);d.useEffect(()=>{if(!ce||!Z||s===0||l===0)return;const G=q.length===0?K:q[q.length-1];ce.canvas.width=s,ce.canvas.height=l,ce.clearRect(0,0,ce.canvas.width,ce.canvas.height),ce.drawImage(G,0,0,s,l)},[q,K,Z,ce,l,s]),d.useEffect(()=>{!H||!Z||s===0||l===0||(H.canvas.width=s,H.canvas.height=l,H.clearRect(0,0,H.canvas.width,H.canvas.height),ae.forEach(G=>{H.drawImage(G,0,0,s,l)}),X.forEach(G=>{H.drawImage(G,0,0,s,l)}),g.isInteractiveSeg&&g.tmpInteractiveSegMask&&H.drawImage(g.tmpInteractiveSegMask,0,0,s,l),Yk(H,F))},[ae,X,Z,g,H,F,l,s]);const Cr=d.useCallback(async()=>{let G=t;if(q.length>0){const Ye=q[q.length-1];G=await Nu(Ye.currentSrc,t.name,t.type)}return G},[t,q]),Ni=()=>q.length!==0,Co=d.useCallback(()=>{let G=512,Ye=512;return Z?(q.length===0?(G=K.naturalWidth,Ye=K.naturalHeight):q.length!==0&&(G=q[q.length-1].width,Ye=q[q.length-1].height),[G,Ye]):[G,Ye]},[K,Z,q]);d.useEffect(()=>{var tf;if(!Z)return;const[G,Ye]=Co();(G!==s||Ye!==l)&&m(G,Ye);const st=o.width/G,Qr=(o.height-Gq)/Ye;let an=1;(st<1||Qr<1)&&(an=Math.min(st,Qr)),Vs(an),ct(an),console.log(`[on file load] image size: ${G}x${Ye}, scale: ${an}, initialCentered: ${we}`),H!=null&&H.canvas&&(console.log("[on file load] set canvas size"),G!=H.canvas.width&&(H.canvas.width=G),Ye!=H.canvas.height&&(H.canvas.height=Ye)),we||((tf=J.current)==null||tf.centerView(an,1),console.log("[on file load] centerView"),me(!0))},[J,l,s,K,Z,o,we,Co]),d.useEffect(()=>{var G;console.log("[useEffect] centerView"),(G=J==null?void 0:J.current)==null||G.centerView(gt,1)},[l,s,J,gt]);const Vn=d.useCallback(()=>{if(!gt||!o)return;const G=J.current;if(!G)return;const Ye=(o.width-s*gt)/2,st=(o.height-l*gt)/2;G.setTransform(Ye,st,gt,200,"easeOutQuad"),G.instance.transformState.scale&&(G.instance.transformState.scale=gt),ct(gt),Er(!1)},[J,o,l,s,o.height,gt]);d.useEffect(()=>(window.addEventListener("resize",()=>{Vn()}),()=>{window.removeEventListener("resize",()=>{Vn()})}),[o,Vn]),Zn("Escape",()=>{R||(fe?Re(!1):Vn())},[fe,i,Vn]);const Di=G=>{const Ye=G.nativeEvent;Oe({x:Ye.pageX,y:Ye.pageY})},Ws=G=>{R||g.isInteractiveSeg||Me||fe&&F.length!==0&&S(f0(G))},Ii=async G=>{P({isPluginRunning:!0});const Ye=await Cr();try{const st=await vT(!0,Ao.InteractiveSeg,Ye,void 0,G),{blob:Qr}=st,an=new Image;an.onload=()=>{y({tmpInteractiveSegMask:an})},an.src=Qr}catch(st){n({variant:"destructive",description:st.message?st.message:st.toString()})}P({isPluginRunning:!1})},Mc=G=>{if(dC(G)){je(!1);return}!_n()||g.isInteractiveSeg||Me||!K.src||!(H!=null&&H.canvas)||i||fe&&(M?Re(!1):A())},bg=G=>{if(g.isInteractiveSeg){const Ye=f0(G),st=[...g.clicks];uC(G)?st.push([Ye.x,Ye.y,0,st.length]):st.push([Ye.x,Ye.y,1,st.length]),Ii(st),y({clicks:st})}},Sg=G=>{if(!(R||g.isInteractiveSeg||Me||!Z||!(H!=null&&H.canvas))&&!uC(G)){if(dC(G)){je(!0);return}Re(!0),b(f0(G))}},Jd=G=>{G.preventDefault(),E()};Zn("meta+z,ctrl+z",Jd);const Oc=G=>{G.preventDefault(),_()};Zn("shift+ctrl+z,shift+meta+z",Oc),s2("Tab",G=>{G==null||G.preventDefault(),G==null||G.stopPropagation(),Ni()&&ie(()=>(window.setTimeout(()=>{ht(100)},10),!0))},G=>{G==null||G.preventDefault(),G==null||G.stopPropagation(),Ni()&&(window.setTimeout(()=>{ht(0)},10),window.setTimeout(()=>{ie(!1)},mu))});const Nc=d.useCallback(async()=>{if(t===void 0)return;if(f&&q.length>0){try{await Hj(q[q.length-1],t.name,t.type),n({description:"Save image success"})}catch(st){n({variant:"destructive",title:"Uh oh! Something went wrong.",description:st.message?st.message:st.toString()})}return}const G=t.name.replace(/(\.[\w\d_-]+)$/i,"_cleanup$1"),Ye=q[q.length-1];if(bF(Ye.currentSrc,G),u.enableDownloadMask){let st=t.name.replace(/(\.[\w\d_-]+)$/i,"_mask$1");st=st.replace(/\.[^/.]+$/,".jpg");const Qr=Wh(s,l,V),an=document.createElement("a");an.download=st,an.href=Qr.toDataURL("image/jpeg"),an.click()}},[t,f,q,u,l,s,V]);Zn("meta+s,ctrl+s",Nc);const Dc=G=>{G!==he&&!Me&&!D&&xe(G)},_g=d.useCallback(()=>{if(R)return"default";if(Me)return"grab";if(he)return"none"},[he,Me,R]);Zn("[",()=>{let G=U;U>10&&(G=U-10),U<=10&&U>0&&(G=U-5),p(G)},[U]),Zn("]",()=>{p(U+10)},[U]),Zn("shift+r",()=>{M&&_n()&&A()},[M,A,_n]),Zn("ctrl+c,meta+c",async()=>{await vF()&&q.length>0&&H!=null&&H.canvas&&(await xF(H==null?void 0:H.canvas),n({title:"Copy inpainting result to clipboard"}))},[q,H]),s2(" ",G=>{r||(G==null||G.preventDefault(),G==null||G.stopPropagation(),xe(!1),je(!0))},G=>{r||(G==null||G.preventDefault(),G==null||G.stopPropagation(),xe(!0),je(!1))});const Ic=()=>{var Ye,st,Qr,an;let G=gt;return((st=(Ye=J.current)==null?void 0:Ye.instance)==null?void 0:st.transformState.scale)!==void 0&&(G=(an=(Qr=J.current)==null?void 0:Qr.instance)==null?void 0:an.transformState.scale),G},ef=(G,Ye)=>{const st=Ic();return{width:`${W*st}px`,height:`${W*st}px`,left:`${G}px`,top:`${Ye}px`,transform:"translate(-50%, -50%)"}},Lc=G=>v.jsx("div",{className:"absolute rounded-[50%] border-[1px] border-[solid] border-[#ffcc00] pointer-events-none bg-[#ffcc00bb]",style:G}),Eg=G=>{p(G),$e||(Ae(!0),window.setTimeout(()=>{Ae(!1)},1e4))},Cg=()=>v.jsx("div",{className:"absolute h-[20px] w-[20px] pointer-events-none rounded-[50%] bg-[rgba(21,_215,_121,_0.936)] [box-shadow:0_0_0_0_rgba(21,_215,_121,_0.936)] animate-pulse",style:{left:`${Ue}px`,top:`${We}px`,transform:"translate(-50%, -50%)"},children:v.jsx(dK,{})}),$g=()=>v.jsx(fq,{ref:G=>{G&&(J.current=G)},panning:{disabled:!Me,velocityDisabled:!0},wheel:{step:.05},centerZoomedOut:!0,alignmentAnimation:{disabled:!0},centerOnInit:!0,limitToBounds:!1,doubleClick:{disabled:!0},initialScale:gt,minScale:gt*.3,onPanning:()=>{Kt||Er(!0)},onZoom:G=>{ct(G.state.scale)},children:v.jsxs(mq,{contentStyle:{visibility:we?"visible":"hidden"},children:[v.jsxs("div",{className:"grid [grid-template-areas:'editor-content'] gap-y-4",children:[v.jsx("canvas",{className:"[grid-area:editor-content]",style:{clipPath:`inset(0 ${ft}% 0 0)`,transition:`clip-path ${mu}ms`},ref:G=>{if(G&&!ce){const Ye=G.getContext("2d");Ye&&Ve(Ye)}}}),v.jsx("canvas",{className:Ce("[grid-area:editor-content]",R?"pointer-events-none animate-pulse duration-600":""),style:{cursor:_g(),clipPath:`inset(0 ${ft}% 0 0)`,transition:`clip-path ${mu}ms`},onContextMenu:G=>{G.preventDefault()},onMouseOver:()=>{Dc(!0),Ae(!1)},onFocus:()=>Dc(!0),onMouseLeave:()=>Dc(!1),onMouseDown:Sg,onMouseUp:bg,onMouseMove:Ws,ref:G=>{if(G&&!H){const Ye=G.getContext("2d");Ye&&se(Ye)}}}),v.jsx("div",{className:"[grid-area:editor-content] pointer-events-none grid [grid-template-areas:'original-image-content']",style:{width:`${s}px`,height:`${l}px`},children:N&&v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"[grid-area:original-image-content] z-10 bg-primary h-full w-[6px] justify-self-end",style:{marginRight:`${ft}%`,transition:`margin-right ${mu}ms`}}),v.jsx("img",{className:"[grid-area:original-image-content]",src:K.src,alt:"original",style:{width:`${s}px`,height:`${l}px`}})]})})]}),v.jsx(zq,{maxHeight:l,maxWidth:s,minHeight:Math.min(512,l),minWidth:Math.min(512,s),scale:Ic(),show:u.showCropper}),v.jsx(Kq,{minHeight:Math.min(512,l),minWidth:Math.min(512,s),scale:Ic(),show:u.showExtender}),g.isInteractiveSeg?v.jsx(Vq,{}):v.jsx(v.Fragment,{})]})});return v.jsxs("div",{className:"flex w-screen h-screen justify-center items-center","aria-hidden":"true",onMouseMove:Di,onMouseUp:Mc,children:[$g(),he&&!i&&!Me&&(g.isInteractiveSeg?Cg():Lc(ef(Ue,We))),$e&&Lc(ef(L,Q)),v.jsxs("div",{className:" overflow-hidden fixed flex bottom-5 border px-4 py-2 rounded-[3rem] gap-8 items-center justify-center backdrop-filter backdrop-blur-md bg-background/70",children:[v.jsx(uo,{className:"w-48",defaultValue:[50],min:Yq,max:Xq,step:1,tabIndex:-1,value:[U],onValueChange:G=>Eg(G[0]),onClick:()=>Ae(!1)}),v.jsxs("div",{className:"flex gap-2",children:[v.jsx(yn,{tooltip:"Reset zoom & pan",disabled:Mt===gt&&Kt===!1,onClick:Vn,children:v.jsx(QU,{})}),v.jsx(yn,{tooltip:"Undo",onClick:Jd,disabled:x,children:v.jsx(aV,{})}),v.jsx(yn,{tooltip:"Redo",onClick:Oc,disabled:C,children:v.jsx(oV,{})}),v.jsx(yn,{tooltip:"Show original image",onPointerDown:G=>{G.preventDefault(),ie(()=>(window.setTimeout(()=>{ht(100)},10),!0))},onPointerUp:()=>{window.setTimeout(()=>{ht(0)},10),window.setTimeout(()=>{ie(!1)},mu)},disabled:q.length===0,children:v.jsx(JU,{})}),v.jsx(yn,{tooltip:"Save Image",disabled:!q.length,onClick:Nc,children:v.jsx(ZU,{})}),u.enableManualInpainting&&u.model.model_type==="inpaint"?v.jsx(yn,{tooltip:"Run Inpainting",disabled:R||!_n()&&X.length===0,onClick:()=>{A()},children:v.jsx(qU,{})}):v.jsx(v.Fragment,{})]})]})]})}const qq=()=>{const[e,t]=bt(n=>[n.imageWidth,n.imageHeight]);return!e||!t?null:v.jsxs("div",{className:"border rounded-lg px-2 py-[6px] z-10 bg-background",children:[e,"x",t]})},V1=["Enter"," "],Qq=["ArrowDown","PageUp","Home"],K3=["ArrowUp","PageDown","End"],Jq=[...Qq,...K3],eQ={ltr:[...V1,"ArrowRight"],rtl:[...V1,"ArrowLeft"]},tQ={ltr:["ArrowLeft"],rtl:["ArrowRight"]},mg="Menu",[md,nQ,rQ]=Gd(mg),[za,G3]=Mn(mg,[rQ,Fs,tg]),gg=Fs(),Y3=tg(),[X3,Us]=za(mg),[oQ,Qd]=za(mg),iQ=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:o,onOpenChange:i,modal:s=!0}=e,l=gg(t),[u,f]=d.useState(null),m=d.useRef(!1),p=Ft(i),g=Tc(o);return d.useEffect(()=>{const y=()=>{m.current=!0,document.addEventListener("pointerdown",b,{capture:!0,once:!0}),document.addEventListener("pointermove",b,{capture:!0,once:!0})},b=()=>m.current=!1;return document.addEventListener("keydown",y,{capture:!0}),()=>{document.removeEventListener("keydown",y,{capture:!0}),document.removeEventListener("pointerdown",b,{capture:!0}),document.removeEventListener("pointermove",b,{capture:!0})}},[]),d.createElement(jd,l,d.createElement(X3,{scope:t,open:n,onOpenChange:p,content:u,onContentChange:f},d.createElement(oQ,{scope:t,onClose:d.useCallback(()=>p(!1),[p]),isUsingKeyboardRef:m,dir:g,modal:s},r)))},Z3=d.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,o=gg(n);return d.createElement(Vm,Y({},o,r,{ref:t}))}),q3="MenuPortal",[sQ,Q3]=za(q3,{forceMount:void 0}),aQ=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:o}=e,i=Us(q3,t);return d.createElement(sQ,{scope:t,forceMount:n},d.createElement(Sn,{present:n||i.open},d.createElement(zd,{asChild:!0,container:o},r)))},bo="MenuContent",[lQ,tb]=za(bo),cQ=d.forwardRef((e,t)=>{const n=Q3(bo,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,i=Us(bo,e.__scopeMenu),s=Qd(bo,e.__scopeMenu);return d.createElement(md.Provider,{scope:e.__scopeMenu},d.createElement(Sn,{present:r||i.open},d.createElement(md.Slot,{scope:e.__scopeMenu},s.modal?d.createElement(uQ,Y({},o,{ref:t})):d.createElement(dQ,Y({},o,{ref:t})))))}),uQ=d.forwardRef((e,t)=>{const n=Us(bo,e.__scopeMenu),r=d.useRef(null),o=Be(t,r);return d.useEffect(()=>{const i=r.current;if(i)return Qm(i)},[]),d.createElement(nb,Y({},e,{ref:o,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:de(e.onFocusOutside,i=>i.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)}))}),dQ=d.forwardRef((e,t)=>{const n=Us(bo,e.__scopeMenu);return d.createElement(nb,Y({},e,{ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)}))}),nb=d.forwardRef((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:o,onOpenAutoFocus:i,onCloseAutoFocus:s,disableOutsidePointerEvents:l,onEntryFocus:u,onEscapeKeyDown:f,onPointerDownOutside:m,onFocusOutside:p,onInteractOutside:g,onDismiss:y,disableOutsideScroll:b,...S}=e,E=Us(bo,n),_=Qd(bo,n),x=gg(n),C=Y3(n),R=nQ(n),[P,M]=d.useState(null),A=d.useRef(null),D=Be(t,A,E.onContentChange),U=d.useRef(0),W=d.useRef(""),q=d.useRef(0),X=d.useRef(null),ae=d.useRef("right"),V=d.useRef(0),F=b?qm:d.Fragment,N=b?{as:Zo,allowPinchZoom:!0}:void 0,ie=Z=>{var H,se;const ce=W.current+Z,Ve=R().filter($e=>!$e.disabled),Ue=document.activeElement,We=(H=Ve.find($e=>$e.ref.current===Ue))===null||H===void 0?void 0:H.textValue,Oe=Ve.map($e=>$e.textValue),he=kQ(Oe,ce,We),xe=(se=Ve.find($e=>$e.textValue===he))===null||se===void 0?void 0:se.ref.current;(function $e(Ae){W.current=Ae,window.clearTimeout(U.current),Ae!==""&&(U.current=window.setTimeout(()=>$e(""),1e3))})(ce),xe&&setTimeout(()=>xe.focus())};d.useEffect(()=>()=>window.clearTimeout(U.current),[]),Xm();const K=d.useCallback(Z=>{var H,se;return ae.current===((H=X.current)===null||H===void 0?void 0:H.side)&&PQ(Z,(se=X.current)===null||se===void 0?void 0:se.area)},[]);return d.createElement(lQ,{scope:n,searchRef:W,onItemEnter:d.useCallback(Z=>{K(Z)&&Z.preventDefault()},[K]),onItemLeave:d.useCallback(Z=>{var H;K(Z)||((H=A.current)===null||H===void 0||H.focus(),M(null))},[K]),onTriggerLeave:d.useCallback(Z=>{K(Z)&&Z.preventDefault()},[K]),pointerGraceTimerRef:q,onPointerGraceIntentChange:d.useCallback(Z=>{X.current=Z},[])},d.createElement(F,N,d.createElement(Ym,{asChild:!0,trapped:o,onMountAutoFocus:de(i,Z=>{var H;Z.preventDefault(),(H=A.current)===null||H===void 0||H.focus()}),onUnmountAutoFocus:s},d.createElement(Ec,{asChild:!0,disableOutsidePointerEvents:l,onEscapeKeyDown:f,onPointerDownOutside:m,onFocusOutside:p,onInteractOutside:g,onDismiss:y},d.createElement(QP,Y({asChild:!0},C,{dir:_.dir,orientation:"vertical",loop:r,currentTabStopId:P,onCurrentTabStopIdChange:M,onEntryFocus:de(u,Z=>{_.isUsingKeyboardRef.current||Z.preventDefault()})}),d.createElement(Wm,Y({role:"menu","aria-orientation":"vertical","data-state":oA(E.open),"data-radix-menu-content":"",dir:_.dir},x,S,{ref:D,style:{outline:"none",...S.style},onKeyDown:de(S.onKeyDown,Z=>{const se=Z.target.closest("[data-radix-menu-content]")===Z.currentTarget,ce=Z.ctrlKey||Z.altKey||Z.metaKey,Ve=Z.key.length===1;se&&(Z.key==="Tab"&&Z.preventDefault(),!ce&&Ve&&ie(Z.key));const Ue=A.current;if(Z.target!==Ue||!Jq.includes(Z.key))return;Z.preventDefault();const Oe=R().filter(he=>!he.disabled).map(he=>he.ref.current);K3.includes(Z.key)&&Oe.reverse(),$Q(Oe)}),onBlur:de(e.onBlur,Z=>{Z.currentTarget.contains(Z.target)||(window.clearTimeout(U.current),W.current="")}),onPointerMove:de(e.onPointerMove,gd(Z=>{const H=Z.target,se=V.current!==Z.clientX;if(Z.currentTarget.contains(H)&&se){const ce=Z.clientX>V.current?"right":"left";ae.current=ce,V.current=Z.clientX}}))})))))))}),fQ=d.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return d.createElement(Pe.div,Y({},r,{ref:t}))}),W1="MenuItem",K2="menu.itemSelect",rb=d.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...o}=e,i=d.useRef(null),s=Qd(W1,e.__scopeMenu),l=tb(W1,e.__scopeMenu),u=Be(t,i),f=d.useRef(!1),m=()=>{const p=i.current;if(!n&&p){const g=new CustomEvent(K2,{bubbles:!0,cancelable:!0});p.addEventListener(K2,y=>r==null?void 0:r(y),{once:!0}),dx(p,g),g.defaultPrevented?f.current=!1:s.onClose()}};return d.createElement(J3,Y({},o,{ref:u,disabled:n,onClick:de(e.onClick,m),onPointerDown:p=>{var g;(g=e.onPointerDown)===null||g===void 0||g.call(e,p),f.current=!0},onPointerUp:de(e.onPointerUp,p=>{var g;f.current||(g=p.currentTarget)===null||g===void 0||g.click()}),onKeyDown:de(e.onKeyDown,p=>{const g=l.searchRef.current!=="";n||g&&p.key===" "||V1.includes(p.key)&&(p.currentTarget.click(),p.preventDefault())})}))}),J3=d.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:o,...i}=e,s=tb(W1,n),l=Y3(n),u=d.useRef(null),f=Be(t,u),[m,p]=d.useState(!1),[g,y]=d.useState("");return d.useEffect(()=>{const b=u.current;if(b){var S;y(((S=b.textContent)!==null&&S!==void 0?S:"").trim())}},[i.children]),d.createElement(md.ItemSlot,{scope:n,disabled:r,textValue:o??g},d.createElement(JP,Y({asChild:!0},l,{focusable:!r}),d.createElement(Pe.div,Y({role:"menuitem","data-highlighted":m?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0},i,{ref:f,onPointerMove:de(e.onPointerMove,gd(b=>{r?s.onItemLeave(b):(s.onItemEnter(b),b.defaultPrevented||b.currentTarget.focus())})),onPointerLeave:de(e.onPointerLeave,gd(b=>s.onItemLeave(b))),onFocus:de(e.onFocus,()=>p(!0)),onBlur:de(e.onBlur,()=>p(!1))}))))}),hQ=d.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...o}=e;return d.createElement(tA,{scope:e.__scopeMenu,checked:n},d.createElement(rb,Y({role:"menuitemcheckbox","aria-checked":am(n)?"mixed":n},o,{ref:t,"data-state":ob(n),onSelect:de(o.onSelect,()=>r==null?void 0:r(am(n)?!0:!n),{checkForDefaultPrevented:!1})})))}),pQ="MenuRadioGroup",[$te,mQ]=za(pQ,{value:void 0,onValueChange:()=>{}}),gQ="MenuRadioItem",vQ=d.forwardRef((e,t)=>{const{value:n,...r}=e,o=mQ(gQ,e.__scopeMenu),i=n===o.value;return d.createElement(tA,{scope:e.__scopeMenu,checked:i},d.createElement(rb,Y({role:"menuitemradio","aria-checked":i},r,{ref:t,"data-state":ob(i),onSelect:de(r.onSelect,()=>{var s;return(s=o.onValueChange)===null||s===void 0?void 0:s.call(o,n)},{checkForDefaultPrevented:!1})})))}),eA="MenuItemIndicator",[tA,yQ]=za(eA,{checked:!1}),wQ=d.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...o}=e,i=yQ(eA,n);return d.createElement(Sn,{present:r||am(i.checked)||i.checked===!0},d.createElement(Pe.span,Y({},o,{ref:t,"data-state":ob(i.checked)})))}),xQ=d.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return d.createElement(Pe.div,Y({role:"separator","aria-orientation":"horizontal"},r,{ref:t}))}),nA="MenuSub",[bQ,rA]=za(nA),SQ=e=>{const{__scopeMenu:t,children:n,open:r=!1,onOpenChange:o}=e,i=Us(nA,t),s=gg(t),[l,u]=d.useState(null),[f,m]=d.useState(null),p=Ft(o);return d.useEffect(()=>(i.open===!1&&p(!1),()=>p(!1)),[i.open,p]),d.createElement(jd,s,d.createElement(X3,{scope:t,open:r,onOpenChange:p,content:f,onContentChange:m},d.createElement(bQ,{scope:t,contentId:nr(),triggerId:nr(),trigger:l,onTriggerChange:u},n)))},_h="MenuSubTrigger",_Q=d.forwardRef((e,t)=>{const n=Us(_h,e.__scopeMenu),r=Qd(_h,e.__scopeMenu),o=rA(_h,e.__scopeMenu),i=tb(_h,e.__scopeMenu),s=d.useRef(null),{pointerGraceTimerRef:l,onPointerGraceIntentChange:u}=i,f={__scopeMenu:e.__scopeMenu},m=d.useCallback(()=>{s.current&&window.clearTimeout(s.current),s.current=null},[]);return d.useEffect(()=>m,[m]),d.useEffect(()=>{const p=l.current;return()=>{window.clearTimeout(p),u(null)}},[l,u]),d.createElement(Z3,Y({asChild:!0},f),d.createElement(J3,Y({id:o.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":o.contentId,"data-state":oA(n.open)},e,{ref:Nm(t,o.onTriggerChange),onClick:p=>{var g;(g=e.onClick)===null||g===void 0||g.call(e,p),!(e.disabled||p.defaultPrevented)&&(p.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:de(e.onPointerMove,gd(p=>{i.onItemEnter(p),!p.defaultPrevented&&!e.disabled&&!n.open&&!s.current&&(i.onPointerGraceIntentChange(null),s.current=window.setTimeout(()=>{n.onOpenChange(!0),m()},100))})),onPointerLeave:de(e.onPointerLeave,gd(p=>{var g;m();const y=(g=n.content)===null||g===void 0?void 0:g.getBoundingClientRect();if(y){var b;const S=(b=n.content)===null||b===void 0?void 0:b.dataset.side,E=S==="right",_=E?-5:5,x=y[E?"left":"right"],C=y[E?"right":"left"];i.onPointerGraceIntentChange({area:[{x:p.clientX+_,y:p.clientY},{x,y:y.top},{x:C,y:y.top},{x:C,y:y.bottom},{x,y:y.bottom}],side:S}),window.clearTimeout(l.current),l.current=window.setTimeout(()=>i.onPointerGraceIntentChange(null),300)}else{if(i.onTriggerLeave(p),p.defaultPrevented)return;i.onPointerGraceIntentChange(null)}})),onKeyDown:de(e.onKeyDown,p=>{const g=i.searchRef.current!=="";if(!(e.disabled||g&&p.key===" ")&&eQ[r.dir].includes(p.key)){var y;n.onOpenChange(!0),(y=n.content)===null||y===void 0||y.focus(),p.preventDefault()}})})))}),EQ="MenuSubContent",CQ=d.forwardRef((e,t)=>{const n=Q3(bo,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,i=Us(bo,e.__scopeMenu),s=Qd(bo,e.__scopeMenu),l=rA(EQ,e.__scopeMenu),u=d.useRef(null),f=Be(t,u);return d.createElement(md.Provider,{scope:e.__scopeMenu},d.createElement(Sn,{present:r||i.open},d.createElement(md.Slot,{scope:e.__scopeMenu},d.createElement(nb,Y({id:l.contentId,"aria-labelledby":l.triggerId},o,{ref:f,align:"start",side:s.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:m=>{var p;s.isUsingKeyboardRef.current&&((p=u.current)===null||p===void 0||p.focus()),m.preventDefault()},onCloseAutoFocus:m=>m.preventDefault(),onFocusOutside:de(e.onFocusOutside,m=>{m.target!==l.trigger&&i.onOpenChange(!1)}),onEscapeKeyDown:de(e.onEscapeKeyDown,m=>{s.onClose(),m.preventDefault()}),onKeyDown:de(e.onKeyDown,m=>{const p=m.currentTarget.contains(m.target),g=tQ[s.dir].includes(m.key);if(p&&g){var y;i.onOpenChange(!1),(y=l.trigger)===null||y===void 0||y.focus(),m.preventDefault()}})})))))});function oA(e){return e?"open":"closed"}function am(e){return e==="indeterminate"}function ob(e){return am(e)?"indeterminate":e?"checked":"unchecked"}function $Q(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function RQ(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function kQ(e,t,n){const o=t.length>1&&Array.from(t).every(f=>f===t[0])?t[0]:t,i=n?e.indexOf(n):-1;let s=RQ(e,Math.max(i,0));o.length===1&&(s=s.filter(f=>f!==n));const u=s.find(f=>f.toLowerCase().startsWith(o.toLowerCase()));return u!==n?u:void 0}function TQ(e,t){const{x:n,y:r}=e;let o=!1;for(let i=0,s=t.length-1;ir!=m>r&&n<(f-l)*(r-u)/(m-u)+l&&(o=!o)}return o}function PQ(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return TQ(n,t)}function gd(e){return t=>t.pointerType==="mouse"?e(t):void 0}const AQ=iQ,MQ=Z3,OQ=aQ,NQ=cQ,DQ=fQ,IQ=rb,LQ=hQ,FQ=vQ,jQ=wQ,zQ=xQ,BQ=SQ,UQ=_Q,VQ=CQ,iA="DropdownMenu",[WQ,Rte]=Mn(iA,[G3]),_r=G3(),[HQ,sA]=WQ(iA),KQ=e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:o,defaultOpen:i,onOpenChange:s,modal:l=!0}=e,u=_r(t),f=d.useRef(null),[m=!1,p]=Zr({prop:o,defaultProp:i,onChange:s});return d.createElement(HQ,{scope:t,triggerId:nr(),triggerRef:f,contentId:nr(),open:m,onOpenChange:p,onOpenToggle:d.useCallback(()=>p(g=>!g),[p]),modal:l},d.createElement(AQ,Y({},u,{open:m,onOpenChange:p,dir:r,modal:l}),n))},GQ="DropdownMenuTrigger",YQ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...o}=e,i=sA(GQ,n),s=_r(n);return d.createElement(MQ,Y({asChild:!0},s),d.createElement(Pe.button,Y({type:"button",id:i.triggerId,"aria-haspopup":"menu","aria-expanded":i.open,"aria-controls":i.open?i.contentId:void 0,"data-state":i.open?"open":"closed","data-disabled":r?"":void 0,disabled:r},o,{ref:Nm(t,i.triggerRef),onPointerDown:de(e.onPointerDown,l=>{!r&&l.button===0&&l.ctrlKey===!1&&(i.onOpenToggle(),i.open||l.preventDefault())}),onKeyDown:de(e.onKeyDown,l=>{r||(["Enter"," "].includes(l.key)&&i.onOpenToggle(),l.key==="ArrowDown"&&i.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(l.key)&&l.preventDefault())})})))}),XQ=e=>{const{__scopeDropdownMenu:t,...n}=e,r=_r(t);return d.createElement(OQ,Y({},r,n))},ZQ="DropdownMenuContent",qQ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=sA(ZQ,n),i=_r(n),s=d.useRef(!1);return d.createElement(NQ,Y({id:o.contentId,"aria-labelledby":o.triggerId},i,r,{ref:t,onCloseAutoFocus:de(e.onCloseAutoFocus,l=>{var u;s.current||(u=o.triggerRef.current)===null||u===void 0||u.focus(),s.current=!1,l.preventDefault()}),onInteractOutside:de(e.onInteractOutside,l=>{const u=l.detail.originalEvent,f=u.button===0&&u.ctrlKey===!0,m=u.button===2||f;(!o.modal||m)&&(s.current=!0)}),style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}}))}),QQ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(DQ,Y({},o,r,{ref:t}))}),JQ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(IQ,Y({},o,r,{ref:t}))}),eJ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(LQ,Y({},o,r,{ref:t}))}),tJ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(FQ,Y({},o,r,{ref:t}))}),nJ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(jQ,Y({},o,r,{ref:t}))}),rJ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(zQ,Y({},o,r,{ref:t}))}),oJ=e=>{const{__scopeDropdownMenu:t,children:n,open:r,onOpenChange:o,defaultOpen:i}=e,s=_r(t),[l=!1,u]=Zr({prop:r,defaultProp:i,onChange:o});return d.createElement(BQ,Y({},s,{open:l,onOpenChange:u}),n)},iJ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(UQ,Y({},o,r,{ref:t}))}),sJ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(VQ,Y({},o,r,{ref:t,style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}}))}),aJ=KQ,lJ=YQ,cJ=XQ,aA=qQ,lA=QQ,cA=JQ,uA=eJ,dA=tJ,fA=nJ,hA=rJ,uJ=oJ,pA=iJ,mA=sJ,dJ=aJ,fJ=lJ,G2=uJ,H1=d.forwardRef(({className:e,inset:t,children:n,...r},o)=>v.jsxs(pA,{ref:o,className:Ce("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",e),...r,children:[n,v.jsx(tz,{className:"ml-auto h-4 w-4"})]}));H1.displayName=pA.displayName;const K1=d.forwardRef(({className:e,...t},n)=>v.jsx(mA,{ref:n,className:Ce("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...t}));K1.displayName=mA.displayName;const gA=d.forwardRef(({className:e,sideOffset:t=4,...n},r)=>v.jsx(cJ,{children:v.jsx(aA,{ref:r,sideOffset:t,className:Ce("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md","data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),onCloseAutoFocus:o=>o.preventDefault(),...n})}));gA.displayName=aA.displayName;const fl=d.forwardRef(({className:e,inset:t,...n},r)=>v.jsx(cA,{ref:r,className:Ce("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",e),...n}));fl.displayName=cA.displayName;const hJ=d.forwardRef(({className:e,children:t,checked:n,...r},o)=>v.jsxs(uA,{ref:o,className:Ce("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),checked:n,...r,children:[v.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:v.jsx(fA,{children:v.jsx(yT,{className:"h-4 w-4"})})}),t]}));hJ.displayName=uA.displayName;const pJ=d.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(dA,{ref:r,className:Ce("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[v.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:v.jsx(fA,{children:v.jsx(sz,{className:"h-4 w-4 fill-current"})})}),t]}));pJ.displayName=dA.displayName;const mJ=d.forwardRef(({className:e,inset:t,...n},r)=>v.jsx(lA,{ref:r,className:Ce("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",e),...n}));mJ.displayName=lA.displayName;const gJ=d.forwardRef(({className:e,...t},n)=>v.jsx(hA,{ref:n,className:Ce("-mx-1 my-1 h-px bg-muted",e),...t}));gJ.displayName=hA.displayName;const Y2={RemoveBG:{IconClass:HC,showName:"RemoveBG"},AnimeSeg:{IconClass:HC,showName:"Anime Segmentation"},RealESRGAN:{IconClass:ZT,showName:"RealESRGAN"},GFPGAN:{IconClass:KC,showName:"GFPGAN"},RestoreFormer:{IconClass:KC,showName:"RestoreFormer"},InteractiveSeg:{IconClass:rV,showName:"Interactive Segmentation"}},vJ=()=>{const[e,t,n,r]=bt(f=>[f.file,f.serverConfig.plugins,f.updateInteractiveSegState,f.runRenderablePlugin]),o=!e;if(t.length===0)return null;const i=(f,m)=>{m==="InteractiveSeg"?n({isInteractiveSeg:!0}):r(f,m)},s=()=>v.jsxs(G2,{children:[v.jsx(H1,{disabled:o,children:v.jsxs("div",{className:"flex gap-2 items-center",children:[v.jsx(ZT,{}),"RealESRGAN"]})}),v.jsxs(K1,{children:[v.jsx(fl,{onClick:()=>r(!1,"RealESRGAN",{upscale:2}),children:"upscale 2x"}),v.jsx(fl,{onClick:()=>r(!1,"RealESRGAN",{upscale:4}),children:"upscale 4x"})]})]},"RealESRGAN"),l=f=>{const{IconClass:m,showName:p}=Y2[f.name];return v.jsxs(G2,{children:[v.jsx(H1,{disabled:o,children:v.jsxs("div",{className:"flex gap-2 items-center",children:[v.jsx(m,{className:"p-1"}),p]})}),v.jsxs(K1,{children:[v.jsx(fl,{onClick:()=>i(!1,f.name),children:"Remove Background"}),v.jsx(fl,{onClick:()=>i(!0,f.name),children:"Generate Mask"})]})]},f.name)},u=()=>t.map(f=>{const{IconClass:m,showName:p}=Y2[f.name];return f.name==="RealESRGAN"?s():f.name==="RemoveBG"||f.name==="AnimeSeg"?l(f):v.jsx(fl,{onClick:()=>i(!1,f.name),disabled:o,children:v.jsxs("div",{className:"flex gap-2 items-center",children:[v.jsx(m,{className:"p-1"}),p]})},f.name)});return v.jsxs(dJ,{modal:!1,children:[v.jsx(fJ,{className:"border rounded-lg z-10 bg-background outline-none",tabIndex:-1,children:v.jsx(wn,{variant:"ghost",size:"icon",asChild:!0,className:"p-1.5",children:v.jsx(KU,{strokeWidth:1})})}),v.jsx(gA,{side:"bottom",align:"start",children:u()})]})},yJ=Cx,wJ=yP,xJ=$x,vA=d.forwardRef(({className:e,...t},n)=>v.jsx(Bd,{className:Ce("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t,ref:n}));vA.displayName=Bd.displayName;const bJ=Dm("fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=closed]:duration-200 data-[state=open]:duration-300",{variants:{side:{top:"inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",bottom:"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",left:"inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",right:"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm"}},defaultVariants:{side:"right"}}),yA=d.forwardRef(({side:e="right",className:t,children:n,...r},o)=>v.jsxs(xJ,{children:[v.jsx(vA,{}),v.jsx(Ud,{ref:o,className:Ce(bJ({side:e}),t),...r,children:n})]}));yA.displayName=Ud.displayName;const wA=({className:e,...t})=>v.jsx("div",{className:Ce("flex flex-col space-y-2 text-center sm:text-left",e),...t});wA.displayName="SheetHeader";const SJ=d.forwardRef(({className:e,...t},n)=>v.jsx(Vd,{ref:n,className:Ce("text-lg font-semibold text-foreground",e),...t}));SJ.displayName=Vd.displayName;const _J=d.forwardRef(({className:e,...t},n)=>v.jsx(Wd,{ref:n,className:Ce("text-sm text-muted-foreground",e),...t}));_J.displayName=Wd.displayName;const Ut=({children:e})=>v.jsx("div",{className:"flex justify-between items-center pr-2",children:e}),Pt=({text:e,toolTip:t="",url:n,htmlFor:r,disabled:o=!1})=>v.jsxs(YT,{children:[v.jsx(XT,{asChild:!0,children:v.jsx(Zx,{htmlFor:r||e.toLowerCase().replace(" ","-"),className:"font-medium",disabled:o,children:e})}),t||n?v.jsxs(Sx,{className:"flex flex-col max-w-xs text-sm",side:"left",children:[v.jsx("p",{children:t}),n?v.jsx(wn,{variant:"link",className:"justify-end",children:v.jsx("a",{href:n,target:"_blank",children:"More info"})}):v.jsx(v.Fragment,{})]}):v.jsx(v.Fragment,{})]}),EJ=()=>{const[e,t]=bt(n=>[n.settings,n.updateSettings]);return v.jsxs("div",{className:"flex flex-col gap-4 mt-4",children:[v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{htmlFor:"steps",text:"Steps",toolTip:"The number of denoising steps. More denoising steps usually lead to a higher quality image at the expense of slower inference."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[30],min:1,max:100,step:1,value:[Math.floor(e.ldmSteps)],onValueChange:n=>t({ldmSteps:n[0]})}),v.jsx(Yn,{id:"steps",className:"w-[60px] rounded-full",numberValue:e.ldmSteps,allowFloat:!1,onNumberValueChange:n=>{t({ldmSteps:n})}})]})]}),v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Sampler"}),v.jsxs(Uo,{value:e.ldmSampler,onValueChange:n=>{t({ldmSampler:n})},children:[v.jsx(go,{className:"w-[100px]",children:v.jsx(Vo,{placeholder:"Select sampler"})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:Object.values(Qw).map(n=>v.jsx(yo,{value:n,children:n},n))})})]})]})]})},xA=d.forwardRef(({className:e,...t},n)=>v.jsx("textarea",{className:Ce("flex min-h-[60px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",e,"overflow-auto"),tabIndex:-1,ref:n,...t}));xA.displayName="Textarea";const Eh=({text:e,onClick:t})=>{const[n]=bt(r=>[r.settings.showExtender]);return v.jsx(wn,{variant:"outline",className:"p-1 h-8",disabled:!n,onClick:t,children:v.jsx("div",{className:"flex items-center gap-1",children:e})})},CJ=()=>{const[e,t,n,r,o,i,s,l,u,f,m]=bt(N=>[N.serverConfig.samplers,N.settings,N.paintByExampleFile,N.getIsProcessing(),N.updateSettings,N.runInpainting,N.updateAppState,N.updateExtenderByBuiltIn,N.updateExtenderDirection,N.adjustMask,N.clearMask]),[p,g]=Px(n),y=d.useRef(null);NP(y,()=>{y!=null&&y.current&&y.current.blur()});const b=N=>{N.key==="Enter"&&N.ctrlKey&&t.prompt.length!==0&&i()},S=()=>v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Cropper",toolTip:"Inpainting on part of image, improve inference speed and reduce memory usage."}),v.jsx(co,{id:"cropper",checked:t.showCropper,onCheckedChange:N=>{o({showCropper:N}),N&&o({showExtender:!1})}})]}),E=()=>t.model.support_controlnet?v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex justify-between items-center pr-2",children:[v.jsx(Pt,{text:"ControlNet",toolTip:"Using an additional conditioning image to control how an image is generated",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#controlnet"}),v.jsx(co,{id:"controlnet",checked:t.enableControlnet,onCheckedChange:N=>{o({enableControlnet:N})}})]}),v.jsx("div",{className:"flex flex-col gap-1",children:v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[100],min:1,max:100,step:1,disabled:!t.enableControlnet,value:[Math.floor(t.controlnetConditioningScale*100)],onValueChange:N=>o({controlnetConditioningScale:N[0]/100})}),v.jsx(Yn,{id:"controlnet-weight",className:"w-[60px] rounded-full",disabled:!t.enableControlnet,numberValue:t.controlnetConditioningScale,allowFloat:!1,onNumberValueChange:N=>{o({controlnetConditioningScale:N})}})]})}),v.jsx("div",{className:"pr-2",children:v.jsxs(Uo,{defaultValue:t.controlnetMethod,value:t.controlnetMethod,onValueChange:N=>{o({controlnetMethod:N})},disabled:!t.enableControlnet,children:[v.jsx(go,{children:v.jsx(Vo,{placeholder:"Select control method"})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:Object.values(t.model.controlnets).map(N=>v.jsx(yo,{value:N,children:N.split("/")[1]},N))})})]})})]}),v.jsx(gn,{})]}):null,_=()=>t.model.support_lcm_lora?v.jsxs(v.Fragment,{children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"LCM LoRA",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inference_with_lcm_lora",toolTip:"Enable quality image generation in typically 2-4 steps. Suggest disabling guidance_scale by setting it to 0. You can also try values between 1.0 and 2.0. When LCM Lora is enabled, LCMSampler will be used automatically."}),v.jsx(co,{id:"lcm-lora",checked:t.enableLCMLora,onCheckedChange:N=>{o({enableLCMLora:N})}})]}),v.jsx(gn,{})]}):null,x=()=>t.model.support_freeu?v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex justify-between items-center pr-2",children:[v.jsx(Pt,{text:"FreeU",toolTip:"FreeU is a technique for improving image quality. Different models may require different FreeU-specific hyperparameters, which can be viewed in the more info section.",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/freeu"}),v.jsx(co,{id:"freeu",checked:t.enableFreeu,onCheckedChange:N=>{o({enableFreeu:N})}})]}),v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex justify-center gap-6",children:[v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-s1",text:"s1",disabled:!t.enableFreeu}),v.jsx(Yn,{id:"freeu-s1",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.s1,allowFloat:!0,onNumberValueChange:N=>{o({freeuConfig:{...t.freeuConfig,s1:N}})}})]}),v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-s2",text:"s2",disabled:!t.enableFreeu}),v.jsx(Yn,{id:"freeu-s2",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.s2,allowFloat:!0,onNumberValueChange:N=>{o({freeuConfig:{...t.freeuConfig,s2:N}})}})]})]}),v.jsxs("div",{className:"flex justify-center gap-6",children:[v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-b1",text:"b1",disabled:!t.enableFreeu}),v.jsx(Yn,{id:"freeu-b1",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.b1,allowFloat:!0,onNumberValueChange:N=>{o({freeuConfig:{...t.freeuConfig,b1:N}})}})]}),v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-b2",text:"b2",disabled:!t.enableFreeu}),v.jsx(Yn,{id:"freeu-b2",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.b2,allowFloat:!0,onNumberValueChange:N=>{o({freeuConfig:{...t.freeuConfig,b2:N}})}})]})]})]}),v.jsx(gn,{})]}):null,C=()=>t.model.need_prompt?v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsx(Pt,{text:"Negative prompt",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#negative-prompt",toolTip:"Negative prompt guides the model away from generating certain things in an image"}),v.jsx("div",{className:"pl-2 pr-4",children:v.jsx(xA,{ref:y,rows:4,onKeyUp:b,className:"max-h-[8rem] overflow-y-auto mb-2",placeholder:"",id:"negative-prompt",value:t.negativePrompt,onInput:N=>{N.preventDefault(),N.stopPropagation();const ie=N.target;o({negativePrompt:ie.value})}})})]}):null,R=()=>t.model.name!==Gk?null:v.jsxs("div",{children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Example Image",toolTip:"An example image to guide image generation."}),v.jsx(f1,{tooltip:"Upload example image",onFileUpload:N=>{s({paintByExampleFile:N})},children:v.jsx(qT,{})})]}),g?v.jsx("div",{className:"flex justify-center items-center",children:v.jsx("img",{src:p.src,alt:"example",className:"max-w-[200px] max-h-[200px] m-3"})}):v.jsx(v.Fragment,{}),v.jsx(wn,{variant:"default",className:"w-full",disabled:r||!g,onClick:()=>{i()},children:"Paint"})]}),P=()=>t.model.name!==uF?null:v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Image guidance scale",toolTip:"Push the generated image towards the inital image. Higher image guidance scale encourages generated images that are closely linked to the source image, usually at the expense of lower image quality.",url:"https://huggingface.co/docs/diffusers/main/en/api/pipelines/pix2pix"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[150],min:100,max:1e3,step:1,value:[Math.floor(t.p2pImageGuidanceScale*100)],onValueChange:N=>o({p2pImageGuidanceScale:N[0]/100})}),v.jsx(Yn,{id:"image-guidance-scale",className:"w-[60px] rounded-full",numberValue:t.p2pImageGuidanceScale,allowFloat:!0,onNumberValueChange:N=>{o({p2pImageGuidanceScale:N})}})]})]}),M=()=>t.model.support_strength?v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Strength",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#strength",toolTip:"Strength is a measure of how much noise is added to the base image, which influences how similar the output is to the base image. Higher value means more noise and more different from the base image"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[100],min:10,max:100,step:1,value:[Math.floor(t.sdStrength*100)],onValueChange:N=>o({sdStrength:N[0]/100})}),v.jsx(Yn,{id:"strength",className:"w-[60px] rounded-full",numberValue:t.sdStrength,allowFloat:!0,onNumberValueChange:N=>{o({sdStrength:N})}})]})]}):null,A=()=>t.model.support_outpainting?v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Extender",toolTip:"Perform outpainting on images to expand it's content."}),v.jsx(co,{id:"extender",checked:t.showExtender,onCheckedChange:N=>{o({showExtender:N}),N&&o({showCropper:!1})}})]}),v.jsxs(Ut,{children:[v.jsxs(Uo,{defaultValue:t.extenderDirection,value:t.extenderDirection,onValueChange:N=>{u(N)},children:[v.jsx(go,{className:"w-[65px] h-7",disabled:!t.showExtender,children:v.jsx(Vo,{placeholder:"Select axis"})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:Object.values(Ln).map(N=>v.jsx(yo,{value:N,children:N},N))})})]}),v.jsxs("div",{className:"flex gap-1 justify-center mt-0",children:[v.jsx(Eh,{text:"1.25x",onClick:()=>l(t.extenderDirection,1.25)}),v.jsx(Eh,{text:"1.5x",onClick:()=>l(t.extenderDirection,1.5)}),v.jsx(Eh,{text:"1.75x",onClick:()=>l(t.extenderDirection,1.75)}),v.jsx(Eh,{text:"2.0x",onClick:()=>l(t.extenderDirection,2)})]})]})]}),v.jsx(gn,{})]}):null,D=()=>t.model.name!==dF?null:v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Task",toolTip:"PowerPaint task. When using extender, image-outpainting task will be auto used. For object-removal and image-outpainting, it is recommended to set the guidance_scale at 10 or above."}),v.jsxs(Uo,{defaultValue:t.powerpaintTask,value:t.powerpaintTask,onValueChange:N=>{o({powerpaintTask:N})},disabled:t.showExtender,children:[v.jsx(go,{className:"w-[140px]",children:v.jsx(Vo,{placeholder:"Select task"})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:[Ol.text_guided,Ol.object_remove,Ol.shape_guided].map(N=>v.jsx(yo,{value:N,children:N},N))})})]})]}),U=()=>v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{htmlFor:"steps",text:"Steps",toolTip:"The number of denoising steps. More denoising steps usually lead to a higher quality image at the expense of slower inference."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[30],min:1,max:100,step:1,value:[Math.floor(t.sdSteps)],onValueChange:N=>o({sdSteps:N[0]})}),v.jsx(Yn,{id:"steps",className:"w-[60px] rounded-full",numberValue:t.sdSteps,allowFloat:!1,onNumberValueChange:N=>{o({sdSteps:N})}})]})]}),W=()=>v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Guidance scale",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#guidance-scale",toolTip:"Guidance scale affects how aligned the text prompt and generated image are. Higher value means the prompt and generated image are closely aligned, so the output is a stricter interpretation of the prompt"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[750],min:0,max:1500,step:1,value:[Math.floor(t.sdGuidanceScale*100)],onValueChange:N=>o({sdGuidanceScale:N[0]/100})}),v.jsx(Yn,{id:"guidance-scale",className:"w-[60px] rounded-full",numberValue:t.sdGuidanceScale,allowFloat:!0,onNumberValueChange:N=>{o({sdGuidanceScale:N})}})]})]}),q=()=>t.model.name===fF?null:v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Sampler"}),v.jsxs(Uo,{defaultValue:t.sdSampler,value:t.sdSampler,onValueChange:N=>{o({sdSampler:N})},children:[v.jsx(go,{className:"w-[175px] text-xs",children:v.jsx(Vo,{placeholder:"Select sampler"})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:e.map(N=>v.jsx(yo,{value:N,className:"text-xs",children:N},N))})})]})]}),X=()=>v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Seed",toolTip:"Using same parameters and a fixed seed can generate same result image."}),v.jsxs("div",{className:"flex gap-2 justify-center items-center",children:[v.jsx(co,{id:"seed",checked:t.seedFixed,onCheckedChange:N=>{o({seedFixed:N})}}),v.jsx(Yn,{id:"seed",className:"w-[100px]",disabled:!t.seedFixed,numberValue:t.seed,allowFloat:!1,onNumberValueChange:N=>{o({seed:N})}})]})]}),ae=()=>v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Mask blur",toolTip:"How much to blur the mask before processing, in pixels. Make the generated inpainting boundaries appear more natural."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[t.sdMaskBlur],min:0,max:96,step:1,value:[Math.floor(t.sdMaskBlur)],onValueChange:N=>o({sdMaskBlur:N[0]})}),v.jsx(Yn,{id:"mask-blur",className:"w-[60px] rounded-full",numberValue:t.sdMaskBlur,allowFloat:!1,onNumberValueChange:N=>{o({sdMaskBlur:N})}})]})]}),V=()=>v.jsxs(v.Fragment,{children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Match histograms",toolTip:"Match the inpainting result histogram to the source image histogram",url:"https://github.com/Sanster/lama-cleaner/pull/143#issuecomment-1325859307"}),v.jsx(co,{id:"match-histograms",checked:t.sdMatchHistograms,onCheckedChange:N=>{o({sdMatchHistograms:N})}})]}),v.jsx(gn,{})]}),F=()=>v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{htmlFor:"adjustMaskKernelSize",text:"Adjust Mask",toolTip:"Expand or shrink mask. Using the slider to adjust the kernel size for dilation or erosion."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[12],min:1,max:100,step:1,value:[Math.floor(t.adjustMaskKernelSize)],onValueChange:N=>o({adjustMaskKernelSize:N[0]})}),v.jsx(Yn,{id:"adjustMaskKernelSize",className:"w-[60px] rounded-full",numberValue:t.adjustMaskKernelSize,allowFloat:!1,onNumberValueChange:N=>{o({adjustMaskKernelSize:N})}})]}),v.jsxs(Ut,{children:[v.jsxs("div",{className:"flex gap-1 justify-start",children:[v.jsx(wn,{variant:"outline",className:"p-1 h-8",onClick:()=>f("expand"),disabled:r,children:v.jsx("div",{className:"flex items-center gap-1 select-none",children:"expand"})}),v.jsx(wn,{variant:"outline",className:"p-1 h-8",onClick:()=>f("shrink"),disabled:r,children:v.jsx("div",{className:"flex items-center gap-1 select-none",children:"Shrink"})}),v.jsx(wn,{variant:"outline",className:"p-1 h-8",onClick:()=>f("reverse"),disabled:r,children:v.jsx("div",{className:"flex items-center gap-1 select-none",children:"Reverse"})})]}),v.jsx(wn,{variant:"outline",className:"p-1 h-8 justify-self-end",onClick:m,disabled:r,children:v.jsx("div",{className:"flex items-center gap-1 select-none",children:"Clear"})})]})]}),v.jsx(gn,{})]});return v.jsxs("div",{className:"flex flex-col gap-4 mt-4",children:[S(),A(),F(),D(),U(),W(),P(),M(),q(),X(),C(),v.jsx(gn,{}),E(),_(),ae(),V(),x(),R()]})},$J=()=>{const[e,t]=bt(n=>[n.settings,n.updateSettings]);return v.jsxs("div",{className:"flex flex-col gap-4 mt-4",children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"CV2 Flag",url:"https://docs.opencv.org/4.8.0/d7/d8b/group__photo__inpaint.html#gga8002a65f5a3328fbf15df81b842d3c3ca892824c38e258feb5e72f308a358d52e"}),v.jsxs(Uo,{value:e.cv2Flag,onValueChange:n=>{t({cv2Flag:n})},children:[v.jsx(go,{className:"w-[160px]",children:v.jsx(Vo,{placeholder:"Select flag"})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:Object.values(Jw).map(n=>v.jsx(yo,{value:n,children:n},n))})})]})]}),v.jsx(Pt,{text:"CV2 Radius",url:"https://docs.opencv.org/4.8.0/d7/d8b/group__photo__inpaint.html#gga8002a65f5a3328fbf15df81b842d3c3ca892824c38e258feb5e72f308a358d52e"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[5],min:1,max:100,step:1,value:[Math.floor(e.cv2Radius)],onValueChange:n=>t({cv2Radius:n[0]})}),v.jsx(Yn,{id:"cv2-radius",className:"w-[60px] rounded-full",numberValue:e.cv2Radius,allowFloat:!1,onNumberValueChange:n=>{t({cv2Radius:n})}})]})]})},RJ=()=>{const[e,t]=bt(i=>[i.settings,i.windowSize]),[n,r]=OP(!0);if(Zn("c",()=>{r()}),e.model.name!==sC&&e.model.name!==aC&&e.model.model_type===fs)return null;const o=()=>e.model.name===sC?v.jsx(EJ,{}):e.model.name===aC?v.jsx($J,{}):v.jsx(CJ,{});return v.jsxs(yJ,{open:n,modal:!1,children:[v.jsx(wJ,{tabIndex:-1,className:"z-10 outline-none absolute top-[68px] right-6 rounded-lg border bg-background",children:v.jsx(wn,{variant:"ghost",size:"icon",asChild:!0,className:"p-1.5",onClick:r,children:v.jsx(GU,{strokeWidth:1})})}),v.jsxs(yA,{side:"right",className:"w-[300px] mt-[60px] outline-none pl-4 pr-1",onOpenAutoFocus:i=>i.preventDefault(),onPointerDownOutside:i=>i.preventDefault(),children:[v.jsxs(wA,{children:[v.jsxs(Ut,{children:[v.jsx("div",{className:"overflow-hidden mr-8",children:e.model.name.split("/")[e.model.name.split("/").length-1]}),v.jsx(wn,{variant:"ghost",size:"icon",className:"border h-6 w-6",onClick:r,children:v.jsx(YU,{strokeWidth:1})})]}),v.jsx(gn,{})]}),v.jsx(ag,{style:{height:t.height-160},className:"pr-3",children:o()})]})]})},Jo=Object.create(null);Jo.open="0";Jo.close="1";Jo.ping="2";Jo.pong="3";Jo.message="4";Jo.upgrade="5";Jo.noop="6";const op=Object.create(null);Object.keys(Jo).forEach(e=>{op[Jo[e]]=e});const G1={type:"error",data:"parser error"},bA=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",SA=typeof ArrayBuffer=="function",_A=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,ib=({type:e,data:t},n,r)=>bA&&t instanceof Blob?n?r(t):X2(t,r):SA&&(t instanceof ArrayBuffer||_A(t))?n?r(t):X2(new Blob([t]),r):r(Jo[e]+(t||"")),X2=(e,t)=>{const n=new FileReader;return n.onload=function(){const r=n.result.split(",")[1];t("b"+(r||""))},n.readAsDataURL(e)};function Z2(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let z0;function kJ(e,t){if(bA&&e.data instanceof Blob)return e.data.arrayBuffer().then(Z2).then(t);if(SA&&(e.data instanceof ArrayBuffer||_A(e.data)))return t(Z2(e.data));ib(e,!1,n=>{z0||(z0=new TextEncoder),t(z0.encode(n))})}const q2="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",_u=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let e=0;e{let t=e.length*.75,n=e.length,r,o=0,i,s,l,u;e[e.length-1]==="="&&(t--,e[e.length-2]==="="&&t--);const f=new ArrayBuffer(t),m=new Uint8Array(f);for(r=0;r>4,m[o++]=(s&15)<<4|l>>2,m[o++]=(l&3)<<6|u&63;return f},PJ=typeof ArrayBuffer=="function",sb=(e,t)=>{if(typeof e!="string")return{type:"message",data:EA(e,t)};const n=e.charAt(0);return n==="b"?{type:"message",data:AJ(e.substring(1),t)}:op[n]?e.length>1?{type:op[n],data:e.substring(1)}:{type:op[n]}:G1},AJ=(e,t)=>{if(PJ){const n=TJ(e);return EA(n,t)}else return{base64:!0,data:e}},EA=(e,t)=>{switch(t){case"blob":return e instanceof Blob?e:new Blob([e]);case"arraybuffer":default:return e instanceof ArrayBuffer?e:e.buffer}},CA="",MJ=(e,t)=>{const n=e.length,r=new Array(n);let o=0;e.forEach((i,s)=>{ib(i,!1,l=>{r[s]=l,++o===n&&t(r.join(CA))})})},OJ=(e,t)=>{const n=e.split(CA),r=[];for(let o=0;o{const r=n.length;let o;if(r<126)o=new Uint8Array(1),new DataView(o.buffer).setUint8(0,r);else if(r<65536){o=new Uint8Array(3);const i=new DataView(o.buffer);i.setUint8(0,126),i.setUint16(1,r)}else{o=new Uint8Array(9);const i=new DataView(o.buffer);i.setUint8(0,127),i.setBigUint64(1,BigInt(r))}e.data&&typeof e.data!="string"&&(o[0]|=128),t.enqueue(o),t.enqueue(n)})}})}let B0;function Ch(e){return e.reduce((t,n)=>t+n.length,0)}function $h(e,t){if(e[0].length===t)return e.shift();const n=new Uint8Array(t);let r=0;for(let o=0;oMath.pow(2,21)-1){l.enqueue(G1);break}o=m*Math.pow(2,32)+f.getUint32(4),r=3}else{if(Ch(n)e){l.enqueue(G1);break}}}})}const $A=4;function qt(e){if(e)return IJ(e)}function IJ(e){for(var t in qt.prototype)e[t]=qt.prototype[t];return e}qt.prototype.on=qt.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this};qt.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this};qt.prototype.off=qt.prototype.removeListener=qt.prototype.removeAllListeners=qt.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,o=0;o(e.hasOwnProperty(r)&&(n[r]=e[r]),n),{})}const LJ=Br.setTimeout,FJ=Br.clearTimeout;function vg(e,t){t.useNativeTimers?(e.setTimeoutFn=LJ.bind(Br),e.clearTimeoutFn=FJ.bind(Br)):(e.setTimeoutFn=Br.setTimeout.bind(Br),e.clearTimeoutFn=Br.clearTimeout.bind(Br))}const jJ=1.33;function zJ(e){return typeof e=="string"?BJ(e):Math.ceil((e.byteLength||e.size)*jJ)}function BJ(e){let t=0,n=0;for(let r=0,o=e.length;r=57344?n+=3:(r++,n+=4);return n}function UJ(e){let t="";for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+="&"),t+=encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t}function VJ(e){let t={},n=e.split("&");for(let r=0,o=n.length;r0);return t}function TA(){const e=e$(+new Date);return e!==J2?(Q2=0,J2=e):e+"."+e$(Q2++)}for(;Rh{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)};OJ(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,MJ(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]=TA()),!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 Xo(this.uri(),t)}doWrite(t,n){const r=this.request({method:"POST",data:t});r.on("success",n),r.on("error",(o,i)=>{this.onError("xhr post error",o,i)})}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}}class Xo extends qt{constructor(t,n){super(),vg(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=RA(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");n.xdomain=!!this.opts.xd;const r=this.xhr=new AA(n);try{r.open(this.method,this.uri,!0);try{if(this.opts.extraHeaders){r.setDisableHeaderCheck&&r.setDisableHeaderCheck(!0);for(let o in this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(o)&&r.setRequestHeader(o,this.opts.extraHeaders[o])}}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 o;r.readyState===3&&((o=this.opts.cookieJar)===null||o===void 0||o.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(o){this.setTimeoutFn(()=>{this.onError(o)},0);return}typeof document<"u"&&(this.index=Xo.requestsCount++,Xo.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=GJ,t)try{this.xhr.abort()}catch{}typeof document<"u"&&delete Xo.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()}}Xo.requestsCount=0;Xo.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",t$);else if(typeof addEventListener=="function"){const e="onpagehide"in Br?"pagehide":"unload";addEventListener(e,t$,!1)}}function t$(){for(let e in Xo.requests)Xo.requests.hasOwnProperty(e)&&Xo.requests[e].abort()}const lb=typeof Promise=="function"&&typeof Promise.resolve=="function"?t=>Promise.resolve().then(t):(t,n)=>n(t,0),kh=Br.WebSocket||Br.MozWebSocket,n$=!0,ZJ="arraybuffer",r$=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class qJ extends ab{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=r$?{}:RA(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=n$&&!r$?n?new kh(t,n):new kh(t):new kh(t,n,r)}catch(o){return this.emitReserved("error",o)}this.ws.binaryType=this.socket.binaryType,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{n$&&this.ws.send(i)}catch{}o&&lb(()=>{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]=TA()),this.supportsBinary||(n.b64=1),this.createUri(t,n)}check(){return!!kh}}class QJ extends ab{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=DJ(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=t.readable.pipeThrough(n).getReader(),o=NJ();o.readable.pipeTo(t.writable),this.writer=o.writable.getWriter();const i=()=>{r.read().then(({done:l,value:u})=>{l||(this.onPacket(u),i())}).catch(l=>{})};i();const s={type:"open"};this.query.sid&&(s.data=`{"sid":"${this.query.sid}"}`),this.writer.write(s).then(()=>this.onOpen())})}))}write(t){this.writable=!1;for(let n=0;n{o&&lb(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;(t=this.transport)===null||t===void 0||t.close()}}const JJ={websocket:qJ,webtransport:QJ,polling:XJ},eee=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,tee=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function X1(e){if(e.length>2e3)throw"URI too long";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 o=eee.exec(e||""),i={},s=14;for(;s--;)i[tee[s]]=o[s]||"";return n!=-1&&r!=-1&&(i.source=t,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=nee(i,i.path),i.queryKey=ree(i,i.query),i}function nee(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 ree(e,t){const n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(r,o,i){o&&(n[o]=i)}),n}let MA=class hl extends qt{constructor(t,n={}){super(),this.binaryType=ZJ,this.writeBuffer=[],t&&typeof t=="object"&&(n=t,t=null),t?(t=X1(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=X1(n.host).host),vg(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=VJ(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=$A,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 JJ[t](r)}open(){let t;if(this.opts.rememberUpgrade&&hl.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;hl.priorWebsocketSuccess=!1;const o=()=>{r||(n.send([{type:"ping",data:"probe"}]),n.once("packet",p=>{if(!r)if(p.type==="pong"&&p.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",n),!n)return;hl.priorWebsocketSuccess=n.name==="websocket",this.transport.pause(()=>{r||this.readyState!=="closed"&&(m(),this.setTransport(n),n.send([{type:"upgrade"}]),this.emitReserved("upgrade",n),n=null,this.upgrading=!1,this.flush())})}else{const g=new Error("probe error");g.transport=n.name,this.emitReserved("upgradeError",g)}}))};function i(){r||(r=!0,m(),n.close(),n=null)}const s=p=>{const g=new Error("probe error: "+p);g.transport=n.name,i(),this.emitReserved("upgradeError",g)};function l(){s("transport closed")}function u(){s("socket closed")}function f(p){n&&p.name!==n.name&&i()}const m=()=>{n.removeListener("open",o),n.removeListener("error",s),n.removeListener("close",l),this.off("close",u),this.off("upgrading",f)};n.once("open",o),n.once("error",s),n.once("close",l),this.once("close",u),this.once("upgrading",f),this.upgrades.indexOf("webtransport")!==-1&&t!=="webtransport"?this.setTimeoutFn(()=>{r||n.open()},200):n.open()}onOpen(){if(this.readyState="open",hl.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,o){if(typeof n=="function"&&(o=n,n=void 0),typeof r=="function"&&(o=r,r=null),this.readyState==="closing"||this.readyState==="closed")return;r=r||{},r.compress=r.compress!==!1;const i={type:t,data:n,options:r};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),o&&this.once("flush",o),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){hl.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 o=t.length;for(;rtypeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,OA=Object.prototype.toString,aee=typeof Blob=="function"||typeof Blob<"u"&&OA.call(Blob)==="[object BlobConstructor]",lee=typeof File=="function"||typeof File<"u"&&OA.call(File)==="[object FileConstructor]";function cb(e){return iee&&(e instanceof ArrayBuffer||see(e))||aee&&e instanceof Blob||lee&&e instanceof File}function ip(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(i),n.apply(this,[null,...s])}}emitWithAck(t,...n){const r=this.flags.timeout!==void 0||this._opts.ackTimeout!==void 0;return new Promise((o,i)=>{n.push((s,l)=>r?s?i(s):o(l):o(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((o,...i)=>r!==this._queue[0]?void 0:(o!==null?r.tryCount>this._opts.retries&&(this._queue.shift(),n&&n(o)):(this._queue.shift(),n&&n(null,...i)),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:lt.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 lt.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 lt.EVENT:case lt.BINARY_EVENT:this.onevent(t);break;case lt.ACK:case lt.BINARY_ACK:this.onack(t);break;case lt.DISCONNECT:this.ondisconnect();break;case lt.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(...o){r||(r=!0,n.packet({type:lt.ACK,id:t,data:o}))}}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:lt.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}Ac.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};Ac.prototype.reset=function(){this.attempts=0};Ac.prototype.setMin=function(e){this.ms=e};Ac.prototype.setMax=function(e){this.max=e};Ac.prototype.setJitter=function(e){this.jitter=e};class Q1 extends qt{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,vg(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 Ac({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(n.timeout==null?2e4:n.timeout),this._readyState="closed",this.uri=t;const o=n.parser||mee;this.encoder=new o.Encoder,this.decoder=new o.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 MA(this.uri,this.opts);const n=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;const o=fo(n,"open",function(){r.onopen(),t&&t()}),i=l=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",l),t?t(l):this.maybeReconnectOnOpen()},s=fo(n,"error",i);if(this._timeout!==!1){const l=this._timeout,u=this.setTimeoutFn(()=>{o(),i(new Error("timeout")),n.close()},l);this.opts.autoUnref&&u.unref(),this.subs.push(()=>{this.clearTimeoutFn(u)})}return this.subs.push(o),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(fo(t,"ping",this.onping.bind(this)),fo(t,"data",this.ondata.bind(this)),fo(t,"error",this.onerror.bind(this)),fo(t,"close",this.onclose.bind(this)),fo(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){lb(()=>{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 NA(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(o=>{o?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",o)):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 gu={};function sp(e,t){typeof e=="object"&&(t=e,e=void 0),t=t||{};const n=oee(e,t.path||"/socket.io"),r=n.source,o=n.id,i=n.path,s=gu[o]&&i in gu[o].nsps,l=t.forceNew||t["force new connection"]||t.multiplex===!1||s;let u;return l?u=new Q1(r,t):(gu[o]||(gu[o]=new Q1(r,t)),u=gu[o]),n.query&&!t.query&&(t.query=n.queryKey),u.socket(n.path,t)}Object.assign(sp,{Manager:Q1,Socket:NA,io:sp,connect:sp});const DA="Progress",yg=100,[vee,kte]=Mn(DA),[yee,wee]=vee(DA),IA=d.forwardRef((e,t)=>{const{__scopeProgress:n,value:r,max:o,getValueLabel:i=See,...s}=e,l=J1(o)?o:yg,u=FA(r,l)?r:null,f=lm(u)?i(u,l):void 0;return d.createElement(yee,{scope:n,value:u,max:l},d.createElement(Pe.div,Y({"aria-valuemax":l,"aria-valuemin":0,"aria-valuenow":lm(u)?u:void 0,"aria-valuetext":f,role:"progressbar","data-state":LA(u,l),"data-value":u??void 0,"data-max":l},s,{ref:t})))});IA.propTypes={max(e,t,n){const r=e[t],o=String(r);return r&&!J1(r)?new Error(_ee(o,n)):null},value(e,t,n){const r=e[t],o=String(r),i=J1(e.max)?e.max:yg;return r!=null&&!FA(r,i)?new Error(Eee(o,n)):null}};const xee="ProgressIndicator",bee=d.forwardRef((e,t)=>{var n;const{__scopeProgress:r,...o}=e,i=wee(xee,r);return d.createElement(Pe.div,Y({"data-state":LA(i.value,i.max),"data-value":(n=i.value)!==null&&n!==void 0?n:void 0,"data-max":i.max},o,{ref:t}))});function See(e,t){return`${Math.round(e/t*100)}%`}function LA(e,t){return e==null?"indeterminate":e===t?"complete":"loading"}function lm(e){return typeof e=="number"}function J1(e){return lm(e)&&!isNaN(e)&&e>0}function FA(e,t){return lm(e)&&!isNaN(e)&&e<=t&&e>=0}function _ee(e,t){return`Invalid prop \`max\` of value \`${e}\` supplied to \`${t}\`. Only numbers greater than 0 are valid max values. Defaulting to \`${yg}\`.`}function Eee(e,t){return`Invalid prop \`value\` of value \`${e}\` supplied to \`${t}\`. The \`value\` prop must be: + - a positive number + - less than the value passed to \`max\` (or ${yg} if no \`max\` prop is set) + - \`null\` if the progress is indeterminate. + +Defaulting to \`null\`.`}const jA=IA,Cee=bee,zA=d.forwardRef(({className:e,value:t,...n},r)=>v.jsx(jA,{ref:r,className:Ce("relative h-2 w-full overflow-hidden rounded-full bg-primary/20",e),...n,children:v.jsx(Cee,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(t||0)}%)`}})}));zA.displayName=jA.displayName;const $ee="",Zi=sp($ee),Ree=()=>{const[e,t,n]=bt(u=>[u.settings,u.isInpainting,u.isSD()]),[r,o]=d.useState(!1),[i,s]=d.useState(0),l=Math.min(Math.round(i/e.sdSteps*100),100);return d.useEffect(()=>(Zi.on("connect",()=>{o(!0)}),Zi.on("disconnect",()=>{o(!1)}),Zi.on("diffusion_progress",u=>{u&&s(u.step+1)}),Zi.on("diffusion_finish",()=>{s(0)}),()=>{Zi.off("connect"),Zi.off("disconnect"),Zi.off("diffusion_progress"),Zi.off("diffusion_finish")}),[]),v.jsxs("div",{className:"z-10 fixed bg-background w-[220px] left-1/2 -translate-x-1/2 top-[68px] h-[32px] flex justify-center items-center gap-[18px] border-[1px] border-[solid] rounded-[14px] pl-[8px] pr-[8px]",style:{visibility:r&&t&&n?"visible":"hidden"},children:[v.jsx(zA,{value:l}),v.jsxs("div",{className:"w-[45px] flex justify-center font-nums",children:[l,"%"]})]})},kee=()=>{const[e,t]=bt(n=>[n.file,n.updateSettings]);return d.useEffect(()=>{(async()=>{const r=await Uj();t({model:r})})()},[]),v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"flex gap-3 absolute top-[68px] left-[24px] items-center",children:[v.jsx(vJ,{}),v.jsx(qq,{})]}),v.jsx(Wq,{}),v.jsx(Ree,{}),v.jsx(RJ,{}),e?v.jsx(Zq,{file:e}):v.jsx(v.Fragment,{})]})},Tee=()=>{const[e,t]=d.useState(window.innerWidth),n=d.useCallback(()=>{t(window.innerWidth)},[]);if(d.useEffect(()=>(window.addEventListener("resize",n),()=>{window.removeEventListener("resize",n)})),e<768)return"mobile";if(e>=768&&e<1224)return"tablet";if(e>=1224)return"desktop"};function Pee(e){const{onSelection:t}=e,[n]=d.useState(`file-upload-${Math.random().toString()}`),r=Tee();function o(i){if(!(!i||!i.type.match("image.*")))try{if(i.size>20*1024*1024)throw new Error("file too large");t(i)}catch(l){alert(`error: ${l.message}`)}}return v.jsx("div",{className:"absolute flex w-screen h-screen justify-center items-center pointer-events-none",children:v.jsx("label",{htmlFor:n,className:"grid bg-background border-[2px] border-[dashed] rounded-lg min-w-[600px] hover:bg-primary hover:text-primary-foreground pointer-events-auto",children:v.jsxs("div",{className:"grid p-16 w-full h-full",onDragOver:i=>{i.stopPropagation(),i.preventDefault()},children:[v.jsx("input",{className:"hidden",id:n,name:n,type:"file",onChange:i=>{var l;const s=(l=i.currentTarget.files)==null?void 0:l[0];s&&o(s)},accept:"image/png, image/jpeg"}),v.jsx("p",{className:"text-center",children:r==="desktop"?"Click here or drag an image file":"Tap here to load your picture"})]})})})}const BA="ToastProvider",[db,Aee,Mee]=Gd("Toast"),[UA,Tte]=Mn("Toast",[Mee]),[Oee,wg]=UA(BA),VA=e=>{const{__scopeToast:t,label:n="Notification",duration:r=5e3,swipeDirection:o="right",swipeThreshold:i=50,children:s}=e,[l,u]=d.useState(null),[f,m]=d.useState(0),p=d.useRef(!1),g=d.useRef(!1);return d.createElement(db.Provider,{scope:t},d.createElement(Oee,{scope:t,label:n,duration:r,swipeDirection:o,swipeThreshold:i,toastCount:f,viewport:l,onViewportChange:u,onToastAdd:d.useCallback(()=>m(y=>y+1),[]),onToastRemove:d.useCallback(()=>m(y=>y-1),[]),isFocusedToastEscapeKeyDownRef:p,isClosePausedRef:g},s))};VA.propTypes={label(e){if(e.label&&typeof e.label=="string"&&!e.label.trim()){const t=`Invalid prop \`label\` supplied to \`${BA}\`. Expected non-empty \`string\`.`;return new Error(t)}return null}};const Nee="ToastViewport",Dee=["F8"],ew="toast.viewportPause",tw="toast.viewportResume",Iee=d.forwardRef((e,t)=>{const{__scopeToast:n,hotkey:r=Dee,label:o="Notifications ({hotkey})",...i}=e,s=wg(Nee,n),l=Aee(n),u=d.useRef(null),f=d.useRef(null),m=d.useRef(null),p=d.useRef(null),g=Be(t,p,s.onViewportChange),y=r.join("+").replace(/Key/g,"").replace(/Digit/g,""),b=s.toastCount>0;d.useEffect(()=>{const E=_=>{var x;r.every(R=>_[R]||_.code===R)&&((x=p.current)===null||x===void 0||x.focus())};return document.addEventListener("keydown",E),()=>document.removeEventListener("keydown",E)},[r]),d.useEffect(()=>{const E=u.current,_=p.current;if(b&&E&&_){const x=()=>{if(!s.isClosePausedRef.current){const M=new CustomEvent(ew);_.dispatchEvent(M),s.isClosePausedRef.current=!0}},C=()=>{if(s.isClosePausedRef.current){const M=new CustomEvent(tw);_.dispatchEvent(M),s.isClosePausedRef.current=!1}},R=M=>{!E.contains(M.relatedTarget)&&C()},P=()=>{E.contains(document.activeElement)||C()};return E.addEventListener("focusin",x),E.addEventListener("focusout",R),E.addEventListener("pointermove",x),E.addEventListener("pointerleave",P),window.addEventListener("blur",x),window.addEventListener("focus",C),()=>{E.removeEventListener("focusin",x),E.removeEventListener("focusout",R),E.removeEventListener("pointermove",x),E.removeEventListener("pointerleave",P),window.removeEventListener("blur",x),window.removeEventListener("focus",C)}}},[b,s.isClosePausedRef]);const S=d.useCallback(({tabbingDirection:E})=>{const x=l().map(C=>{const R=C.ref.current,P=[R,...Qee(R)];return E==="forwards"?P:P.reverse()});return(E==="forwards"?x.reverse():x).flat()},[l]);return d.useEffect(()=>{const E=p.current;if(E){const _=x=>{const C=x.altKey||x.ctrlKey||x.metaKey;if(x.key==="Tab"&&!C){const D=document.activeElement,U=x.shiftKey;if(x.target===E&&U){var P;(P=f.current)===null||P===void 0||P.focus();return}const X=S({tabbingDirection:U?"backwards":"forwards"}),ae=X.findIndex(V=>V===D);if(U0(X.slice(ae+1)))x.preventDefault();else{var M,A;U?(M=f.current)===null||M===void 0||M.focus():(A=m.current)===null||A===void 0||A.focus()}}};return E.addEventListener("keydown",_),()=>E.removeEventListener("keydown",_)}},[l,S]),d.createElement(EB,{ref:u,role:"region","aria-label":o.replace("{hotkey}",y),tabIndex:-1,style:{pointerEvents:b?void 0:"none"}},b&&d.createElement(i$,{ref:f,onFocusFromOutsideViewport:()=>{const E=S({tabbingDirection:"forwards"});U0(E)}}),d.createElement(db.Slot,{scope:n},d.createElement(Pe.ol,Y({tabIndex:-1},i,{ref:g}))),b&&d.createElement(i$,{ref:m,onFocusFromOutsideViewport:()=>{const E=S({tabbingDirection:"backwards"});U0(E)}}))}),Lee="ToastFocusProxy",i$=d.forwardRef((e,t)=>{const{__scopeToast:n,onFocusFromOutsideViewport:r,...o}=e,i=wg(Lee,n);return d.createElement(Hm,Y({"aria-hidden":!0,tabIndex:0},o,{ref:t,style:{position:"fixed"},onFocus:s=>{var l;const u=s.relatedTarget;!((l=i.viewport)!==null&&l!==void 0&&l.contains(u))&&r()}}))}),xg="Toast",Fee="toast.swipeStart",jee="toast.swipeMove",zee="toast.swipeCancel",Bee="toast.swipeEnd",Uee=d.forwardRef((e,t)=>{const{forceMount:n,open:r,defaultOpen:o,onOpenChange:i,...s}=e,[l=!0,u]=Zr({prop:r,defaultProp:o,onChange:i});return d.createElement(Sn,{present:n||l},d.createElement(WA,Y({open:l},s,{ref:t,onClose:()=>u(!1),onPause:Ft(e.onPause),onResume:Ft(e.onResume),onSwipeStart:de(e.onSwipeStart,f=>{f.currentTarget.setAttribute("data-swipe","start")}),onSwipeMove:de(e.onSwipeMove,f=>{const{x:m,y:p}=f.detail.delta;f.currentTarget.setAttribute("data-swipe","move"),f.currentTarget.style.setProperty("--radix-toast-swipe-move-x",`${m}px`),f.currentTarget.style.setProperty("--radix-toast-swipe-move-y",`${p}px`)}),onSwipeCancel:de(e.onSwipeCancel,f=>{f.currentTarget.setAttribute("data-swipe","cancel"),f.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),f.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),f.currentTarget.style.removeProperty("--radix-toast-swipe-end-x"),f.currentTarget.style.removeProperty("--radix-toast-swipe-end-y")}),onSwipeEnd:de(e.onSwipeEnd,f=>{const{x:m,y:p}=f.detail.delta;f.currentTarget.setAttribute("data-swipe","end"),f.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),f.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),f.currentTarget.style.setProperty("--radix-toast-swipe-end-x",`${m}px`),f.currentTarget.style.setProperty("--radix-toast-swipe-end-y",`${p}px`),u(!1)})})))}),[Vee,Wee]=UA(xg,{onClose(){}}),WA=d.forwardRef((e,t)=>{const{__scopeToast:n,type:r="foreground",duration:o,open:i,onClose:s,onEscapeKeyDown:l,onPause:u,onResume:f,onSwipeStart:m,onSwipeMove:p,onSwipeCancel:g,onSwipeEnd:y,...b}=e,S=wg(xg,n),[E,_]=d.useState(null),x=Be(t,V=>_(V)),C=d.useRef(null),R=d.useRef(null),P=o||S.duration,M=d.useRef(0),A=d.useRef(P),D=d.useRef(0),{onToastAdd:U,onToastRemove:W}=S,q=Ft(()=>{var V;(E==null?void 0:E.contains(document.activeElement))&&((V=S.viewport)===null||V===void 0||V.focus()),s()}),X=d.useCallback(V=>{!V||V===1/0||(window.clearTimeout(D.current),M.current=new Date().getTime(),D.current=window.setTimeout(q,V))},[q]);d.useEffect(()=>{const V=S.viewport;if(V){const F=()=>{X(A.current),f==null||f()},N=()=>{const ie=new Date().getTime()-M.current;A.current=A.current-ie,window.clearTimeout(D.current),u==null||u()};return V.addEventListener(ew,N),V.addEventListener(tw,F),()=>{V.removeEventListener(ew,N),V.removeEventListener(tw,F)}}},[S.viewport,P,u,f,X]),d.useEffect(()=>{i&&!S.isClosePausedRef.current&&X(P)},[i,P,S.isClosePausedRef,X]),d.useEffect(()=>(U(),()=>W()),[U,W]);const ae=d.useMemo(()=>E?YA(E):null,[E]);return S.viewport?d.createElement(d.Fragment,null,ae&&d.createElement(Hee,{__scopeToast:n,role:"status","aria-live":r==="foreground"?"assertive":"polite","aria-atomic":!0},ae),d.createElement(Vee,{scope:n,onClose:q},Is.createPortal(d.createElement(db.ItemSlot,{scope:n},d.createElement(_B,{asChild:!0,onEscapeKeyDown:de(l,()=>{S.isFocusedToastEscapeKeyDownRef.current||q(),S.isFocusedToastEscapeKeyDownRef.current=!1})},d.createElement(Pe.li,Y({role:"status","aria-live":"off","aria-atomic":!0,tabIndex:0,"data-state":i?"open":"closed","data-swipe-direction":S.swipeDirection},b,{ref:x,style:{userSelect:"none",touchAction:"none",...e.style},onKeyDown:de(e.onKeyDown,V=>{V.key==="Escape"&&(l==null||l(V.nativeEvent),V.nativeEvent.defaultPrevented||(S.isFocusedToastEscapeKeyDownRef.current=!0,q()))}),onPointerDown:de(e.onPointerDown,V=>{V.button===0&&(C.current={x:V.clientX,y:V.clientY})}),onPointerMove:de(e.onPointerMove,V=>{if(!C.current)return;const F=V.clientX-C.current.x,N=V.clientY-C.current.y,ie=!!R.current,K=["left","right"].includes(S.swipeDirection),Z=["left","up"].includes(S.swipeDirection)?Math.min:Math.max,H=K?Z(0,F):0,se=K?0:Z(0,N),ce=V.pointerType==="touch"?10:2,Ve={x:H,y:se},Ue={originalEvent:V,delta:Ve};ie?(R.current=Ve,Th(jee,p,Ue,{discrete:!1})):s$(Ve,S.swipeDirection,ce)?(R.current=Ve,Th(Fee,m,Ue,{discrete:!1}),V.target.setPointerCapture(V.pointerId)):(Math.abs(F)>ce||Math.abs(N)>ce)&&(C.current=null)}),onPointerUp:de(e.onPointerUp,V=>{const F=R.current,N=V.target;if(N.hasPointerCapture(V.pointerId)&&N.releasePointerCapture(V.pointerId),R.current=null,C.current=null,F){const ie=V.currentTarget,K={originalEvent:V,delta:F};s$(F,S.swipeDirection,S.swipeThreshold)?Th(Bee,y,K,{discrete:!0}):Th(zee,g,K,{discrete:!0}),ie.addEventListener("click",Z=>Z.preventDefault(),{once:!0})}})})))),S.viewport))):null});WA.propTypes={type(e){if(e.type&&!["foreground","background"].includes(e.type)){const t=`Invalid prop \`type\` supplied to \`${xg}\`. Expected \`foreground | background\`.`;return new Error(t)}return null}};const Hee=e=>{const{__scopeToast:t,children:n,...r}=e,o=wg(xg,t),[i,s]=d.useState(!1),[l,u]=d.useState(!1);return Zee(()=>s(!0)),d.useEffect(()=>{const f=window.setTimeout(()=>u(!0),1e3);return()=>window.clearTimeout(f)},[]),l?null:d.createElement(zd,{asChild:!0},d.createElement(Hm,r,i&&d.createElement(d.Fragment,null,o.label," ",n)))},Kee=d.forwardRef((e,t)=>{const{__scopeToast:n,...r}=e;return d.createElement(Pe.div,Y({},r,{ref:t}))}),Gee=d.forwardRef((e,t)=>{const{__scopeToast:n,...r}=e;return d.createElement(Pe.div,Y({},r,{ref:t}))}),Yee="ToastAction",HA=d.forwardRef((e,t)=>{const{altText:n,...r}=e;return n?d.createElement(GA,{altText:n,asChild:!0},d.createElement(KA,Y({},r,{ref:t}))):null});HA.propTypes={altText(e){return e.altText?null:new Error(`Missing prop \`altText\` expected on \`${Yee}\``)}};const Xee="ToastClose",KA=d.forwardRef((e,t)=>{const{__scopeToast:n,...r}=e,o=Wee(Xee,n);return d.createElement(GA,{asChild:!0},d.createElement(Pe.button,Y({type:"button"},r,{ref:t,onClick:de(e.onClick,o.onClose)})))}),GA=d.forwardRef((e,t)=>{const{__scopeToast:n,altText:r,...o}=e;return d.createElement(Pe.div,Y({"data-radix-toast-announce-exclude":"","data-radix-toast-announce-alt":r||void 0},o,{ref:t}))});function YA(e){const t=[];return Array.from(e.childNodes).forEach(r=>{if(r.nodeType===r.TEXT_NODE&&r.textContent&&t.push(r.textContent),qee(r)){const o=r.ariaHidden||r.hidden||r.style.display==="none",i=r.dataset.radixToastAnnounceExclude==="";if(!o)if(i){const s=r.dataset.radixToastAnnounceAlt;s&&t.push(s)}else t.push(...YA(r))}}),t}function Th(e,t,n,{discrete:r}){const o=n.originalEvent.currentTarget,i=new CustomEvent(e,{bubbles:!0,cancelable:!0,detail:n});t&&o.addEventListener(e,t,{once:!0}),r?dx(o,i):o.dispatchEvent(i)}const s$=(e,t,n=0)=>{const r=Math.abs(e.x),o=Math.abs(e.y),i=r>o;return t==="left"||t==="right"?i&&r>n:!i&&o>n};function Zee(e=()=>{}){const t=Ft(e);An(()=>{let n=0,r=0;return n=window.requestAnimationFrame(()=>r=window.requestAnimationFrame(t)),()=>{window.cancelAnimationFrame(n),window.cancelAnimationFrame(r)}},[t])}function qee(e){return e.nodeType===e.ELEMENT_NODE}function Qee(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const o=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||o?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function U0(e){const t=document.activeElement;return e.some(n=>n===t?!0:(n.focus(),document.activeElement!==t))}const Jee=VA,XA=Iee,ZA=Uee,qA=Kee,QA=Gee,JA=HA,eM=KA,ete=Jee,tM=d.forwardRef(({className:e,...t},n)=>v.jsx(XA,{ref:n,className:Ce("fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]",e),tabIndex:-1,...t}));tM.displayName=XA.displayName;const tte=Dm("group pointer-events-auto relative flex w-full items-center justify-between space-x-2 overflow-hidden rounded-md border p-4 pr-6 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full",{variants:{variant:{default:"border bg-background text-foreground",destructive:"destructive group border-destructive bg-destructive text-destructive-foreground"}},defaultVariants:{variant:"default"}}),nM=d.forwardRef(({className:e,variant:t,...n},r)=>v.jsx(ZA,{ref:r,className:Ce(tte({variant:t}),e),tabIndex:-1,...n}));nM.displayName=ZA.displayName;const nte=d.forwardRef(({className:e,...t},n)=>v.jsx(JA,{ref:n,className:Ce("inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium transition-colors hover:bg-secondary focus:outline-none focus:ring-1 focus:ring-ring disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive",e),tabIndex:-1,...t}));nte.displayName=JA.displayName;const rM=d.forwardRef(({className:e,...t},n)=>v.jsx(eM,{ref:n,className:Ce("absolute right-1 top-1 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-1 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600",e),"toast-close":"",tabIndex:-1,...t,children:v.jsx(wT,{className:"h-4 w-4"})}));rM.displayName=eM.displayName;const oM=d.forwardRef(({className:e,...t},n)=>v.jsx(qA,{ref:n,className:Ce("text-sm font-semibold [&+div]:text-xs",e),tabIndex:-1,...t}));oM.displayName=qA.displayName;const iM=d.forwardRef(({className:e,...t},n)=>v.jsx(QA,{ref:n,className:Ce("text-sm opacity-90",e),...t,tabIndex:-1}));iM.displayName=QA.displayName;function rte(){const{toasts:e}=Id();return v.jsxs(ete,{children:[e.map(function({id:t,title:n,description:r,action:o,...i}){return v.jsxs(nM,{...i,children:[v.jsxs("div",{className:"grid gap-1",children:[n&&v.jsx(oM,{children:n}),r&&v.jsx(iM,{children:r})]}),o,v.jsx(rM,{})]},t)}),v.jsx(tM,{})]})}const ote=["image/jpeg","image/png","image/webp","image/bmp","image/tiff"];function ite(){const[e,t,n,r]=bt(g=>[g.file,g.updateAppState,g.setServerConfig,g.setFile]),o=Yj(),i=vH();d.useEffect(()=>{o&&r(o)},[o,r]),d.useEffect(()=>{t({windowSize:i})},[i]),d.useEffect(()=>{(async()=>{const y=await gT();n(y),y.isDesktop&&pF()})()},[]);const s=d.useRef(0),l=d.useCallback(g=>{g.preventDefault(),g.stopPropagation()},[]),u=d.useCallback(g=>{g.preventDefault(),g.stopPropagation(),s.current+=1},[]),f=d.useCallback(g=>{g.preventDefault(),g.stopPropagation(),s.current-=1,s.current>0},[]),m=d.useCallback(g=>{if(g.preventDefault(),g.stopPropagation(),g.dataTransfer.files&&g.dataTransfer.files.length>0){if(!(g.dataTransfer.files.length>1)){const y=g.dataTransfer.files[0],b=y.type;ote.includes(b)&&r(y)}g.dataTransfer.clearData()}},[]),p=d.useCallback(g=>{if(!g.clipboardData)return;const y=g.clipboardData.items,b=[].slice.call(y).filter(_=>_.type.indexOf("image")!==-1);if(b.length===0)return;g.preventDefault(),g.stopPropagation();const E=b[0].getAsFile();E&&r(E)},[]);return d.useEffect(()=>(window.addEventListener("dragenter",u),window.addEventListener("dragleave",f),window.addEventListener("dragover",l),window.addEventListener("drop",m),window.addEventListener("paste",p),function(){window.removeEventListener("dragenter",u),window.removeEventListener("dragleave",f),window.removeEventListener("dragover",l),window.removeEventListener("drop",m),window.removeEventListener("paste",p)})),v.jsxs("main",{className:"flex min-h-screen flex-col items-center justify-between w-full bg-[radial-gradient(circle_at_1px_1px,_#8e8e8e8e_1px,_transparent_0)] [background-size:20px_20px] bg-repeat",children:[v.jsx(rte,{}),v.jsx(nZ,{}),v.jsx(kee,{}),e?v.jsx(v.Fragment,{}):v.jsx(Pee,{onSelection:async g=>{r(g)}})]})}const cm=["light","dark"],fb="(prefers-color-scheme: dark)",ste=typeof window>"u",sM=d.createContext(void 0),ate=e=>d.useContext(sM)?Fe.createElement(d.Fragment,null,e.children):Fe.createElement(cte,e),lte=["light","dark"],cte=({forcedTheme:e,disableTransitionOnChange:t=!1,enableSystem:n=!0,enableColorScheme:r=!0,storageKey:o="theme",themes:i=lte,defaultTheme:s=n?"system":"light",attribute:l="data-theme",value:u,children:f,nonce:m})=>{const[p,g]=d.useState(()=>a$(o,s)),[y,b]=d.useState(()=>a$(o)),S=u?Object.values(u):i,E=d.useCallback(R=>{let P=R;if(!P)return;R==="system"&&n&&(P=l$());const M=u?u[P]:P,A=t?dte():null,D=document.documentElement;if(l==="class"?(D.classList.remove(...S),M&&D.classList.add(M)):M?D.setAttribute(l,M):D.removeAttribute(l),r){const U=cm.includes(s)?s:null,W=cm.includes(P)?P:U;D.style.colorScheme=W}A==null||A()},[]),_=d.useCallback(R=>{g(R);try{localStorage.setItem(o,R)}catch{}},[e]),x=d.useCallback(R=>{const P=l$(R);b(P),p==="system"&&n&&!e&&E("system")},[p,e]);d.useEffect(()=>{const R=window.matchMedia(fb);return R.addListener(x),x(R),()=>R.removeListener(x)},[x]),d.useEffect(()=>{const R=P=>{P.key===o&&_(P.newValue||s)};return window.addEventListener("storage",R),()=>window.removeEventListener("storage",R)},[_]),d.useEffect(()=>{E(e??p)},[e,p]);const C=d.useMemo(()=>({theme:p,setTheme:_,forcedTheme:e,resolvedTheme:p==="system"?y:p,themes:n?[...i,"system"]:i,systemTheme:n?y:void 0}),[p,_,e,y,n,i]);return Fe.createElement(sM.Provider,{value:C},Fe.createElement(ute,{forcedTheme:e,disableTransitionOnChange:t,enableSystem:n,enableColorScheme:r,storageKey:o,themes:i,defaultTheme:s,attribute:l,value:u,children:f,attrs:S,nonce:m}),f)},ute=d.memo(({forcedTheme:e,storageKey:t,attribute:n,enableSystem:r,enableColorScheme:o,defaultTheme:i,value:s,attrs:l,nonce:u})=>{const f=i==="system",m=n==="class"?`var d=document.documentElement,c=d.classList;c.remove(${l.map(b=>`'${b}'`).join(",")});`:`var d=document.documentElement,n='${n}',s='setAttribute';`,p=o?cm.includes(i)&&i?`if(e==='light'||e==='dark'||!e)d.style.colorScheme=e||'${i}'`:"if(e==='light'||e==='dark')d.style.colorScheme=e":"",g=(b,S=!1,E=!0)=>{const _=s?s[b]:b,x=S?b+"|| ''":`'${_}'`;let C="";return o&&E&&!S&&cm.includes(b)&&(C+=`d.style.colorScheme = '${b}';`),n==="class"?C+=S||_?`c.add(${x})`:"null":_&&(C+=`d[s](n,${x})`),C},y=e?`!function(){${m}${g(e)}}()`:r?`!function(){try{${m}var e=localStorage.getItem('${t}');if('system'===e||(!e&&${f})){var t='${fb}',m=window.matchMedia(t);if(m.media!==t||m.matches){${g("dark")}}else{${g("light")}}}else if(e){${s?`var x=${JSON.stringify(s)};`:""}${g(s?"x[e]":"e",!0)}}${f?"":"else{"+g(i,!1,!1)+"}"}${p}}catch(e){}}()`:`!function(){try{${m}var e=localStorage.getItem('${t}');if(e){${s?`var x=${JSON.stringify(s)};`:""}${g(s?"x[e]":"e",!0)}}else{${g(i,!1,!1)};}${p}}catch(t){}}();`;return Fe.createElement("script",{nonce:u,dangerouslySetInnerHTML:{__html:y}})},()=>!0),a$=(e,t)=>{if(ste)return;let n;try{n=localStorage.getItem(e)||void 0}catch{}return n||t},dte=()=>{const e=document.createElement("style");return e.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(e),()=>{window.getComputedStyle(document.body),setTimeout(()=>{document.head.removeChild(e)},1)}},l$=e=>(e||(e=window.matchMedia(fb)),e.matches?"dark":"light"),fte=new pL;V0.createRoot(document.getElementById("root")).render(v.jsx(Fe.StrictMode,{children:v.jsx(wL,{client:fte,children:v.jsx(ate,{defaultTheme:"dark",disableTransitionOnChange:!0,children:v.jsx(VU,{children:v.jsx(ite,{})})})})})); diff --git a/py/iopaint/web_app/assets/index-p0ivNJpo.css b/py/iopaint/web_app/assets/index-p0ivNJpo.css new file mode 100644 index 0000000..61296f4 --- /dev/null +++ b/py/iopaint/web_app/assets/index-p0ivNJpo.css @@ -0,0 +1 @@ +@font-face{font-family:Inter;font-style:normal;font-weight:100;font-display:swap;src:url(/assets/Inter-Thin-eKObIkJC.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:italic;font-weight:100;font-display:swap;src:url(/assets/Inter-ThinItalic-L6uBn3RP.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:normal;font-weight:200;font-display:swap;src:url(/assets/Inter-ExtraLight-w5HAp5iF.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:italic;font-weight:200;font-display:swap;src:url(/assets/Inter-ExtraLightItalic-ZptecSuc.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:normal;font-weight:300;font-display:swap;src:url(/assets/Inter-Light-DFhX0qo-.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:italic;font-weight:300;font-display:swap;src:url(/assets/Inter-LightItalic-fu56_DRc.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:normal;font-weight:400;font-display:swap;src:url(/assets/Inter-Regular-dEFHw1tF.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:italic;font-weight:400;font-display:swap;src:url(/assets/Inter-Italic-f6M78thn.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:normal;font-weight:500;font-display:swap;src:url(/assets/Inter-Medium-dDRaJ8tM.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:italic;font-weight:500;font-display:swap;src:url(/assets/Inter-MediumItalic-zr3roggP.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:normal;font-weight:600;font-display:swap;src:url(/assets/Inter-SemiBold-PyS8DO2L.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:italic;font-weight:600;font-display:swap;src:url(/assets/Inter-SemiBoldItalic-uIDb7hsH.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:normal;font-weight:700;font-display:swap;src:url(/assets/Inter-Bold-srYz_-1B.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:italic;font-weight:700;font-display:swap;src:url(/assets/Inter-BoldItalic-dE_gZyur.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:normal;font-weight:800;font-display:swap;src:url(/assets/Inter-ExtraBold-TduDdwUu.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:italic;font-weight:800;font-display:swap;src:url(/assets/Inter-ExtraBoldItalic-BJafRE5I.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:normal;font-weight:900;font-display:swap;src:url(/assets/Inter-Black-jiII8dog.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:italic;font-weight:900;font-display:swap;src:url(/assets/Inter-BlackItalic-1413vuen.woff2?v=4.0) format("woff2")}*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:before,:after{--tw-content: ""}html{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,"Apple Color Emoji","Segoe UI Emoji",Segoe UI Symbol,"Noto Color Emoji";font-feature-settings:normal;font-variation-settings:normal}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,[type=button],[type=reset],[type=submit]{-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]{display:none}:root{--background: 0 0% 100%;--foreground: 224 71.4% 4.1%;--card: 0 0% 100%;--card-foreground: 224 71.4% 4.1%;--popover: 0 0% 100%;--popover-foreground: 224 71.4% 4.1%;--primary: 48 100% 50%;--primary-foreground: 210 20% 98%;--secondary: 220 14.3% 95.9%;--secondary-foreground: 220.9 39.3% 11%;--muted: 220 14.3% 95.9%;--muted-foreground: 220 8.9% 46.1%;--accent: 220 14.3% 95.9%;--accent-foreground: 220.9 39.3% 11%;--destructive: 0 84.2% 60.2%;--destructive-foreground: 210 20% 98%;--border: 220 13% 91%;--input: 220 13% 91%;--ring: 224 71.4% 4.1%;--radius: .5rem}[data-theme=dark]{--background: 240 10% 3.9%;--foreground: 0 0% 98%;--card: 224 71.4% 4.1%;--card-foreground: 210 20% 98%;--popover: 240 10% 3.9%;--popover-foreground: 0 0% 98%;--primary: 48 100% 50%;--primary-foreground: 220.9 39.3% 11%;--secondary: 240 3.7% 15.9%;--secondary-foreground: 0 0% 98%;--muted: 240 3.7% 15.9%;--muted-foreground: 240 5% 64.9%;--accent: 240 3.7% 15.9%;--accent-foreground: 0 0% 98%;--destructive: 0 62.8% 30.6%;--destructive-foreground: 0 85.7% 97.3%;--border: 240 3.7% 15.9%;--input: 240 3.7% 15.9%;--ring: 240 4.9% 83.9%}*{border-color:hsl(var(--border))}body{background-color:hsl(var(--background));color:hsl(var(--foreground))}*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: }.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border-width:0}.pointer-events-none{pointer-events:none}.pointer-events-auto{pointer-events:auto}.visible{visibility:visible}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.inset-0{top:0;right:0;bottom:0;left:0}.inset-x-0{left:0;right:0}.inset-y-0{top:0;bottom:0}.bottom-0{bottom:0}.bottom-5{bottom:1.25rem}.bottom-6{bottom:1.5rem}.left-0{left:0}.left-1\/2{left:50%}.left-2{left:.5rem}.left-\[24px\]{left:24px}.left-\[50\%\]{left:50%}.left-\[8px\]{left:8px}.right-0{right:0}.right-1{right:.25rem}.right-10{right:2.5rem}.right-2{right:.5rem}.right-4{right:1rem}.right-6{right:1.5rem}.top-0{top:0}.top-1{top:.25rem}.top-4{top:1rem}.top-\[0\]{top:0}.top-\[50\%\]{top:50%}.top-\[68px\]{top:68px}.z-10{z-index:10}.z-20{z-index:20}.z-50{z-index:50}.z-\[100\]{z-index:100}.z-\[2\]{z-index:2}.z-\[4\]{z-index:4}.m-3{margin:.75rem}.-mx-1{margin-left:-.25rem;margin-right:-.25rem}.my-1{margin-top:.25rem;margin-bottom:.25rem}.mb-2{margin-bottom:.5rem}.mb-8{margin-bottom:2rem}.mb-\[-6px\]{margin-bottom:-6px}.ml-\[-6px\]{margin-left:-6px}.ml-auto{margin-left:auto}.mr-8{margin-right:2rem}.mr-\[-6px\]{margin-right:-6px}.mt-0{margin-top:0}.mt-2{margin-top:.5rem}.mt-4{margin-top:1rem}.mt-\[-6px\]{margin-top:-6px}.mt-\[60px\]{margin-top:60px}.block{display:block}.flex{display:flex}.inline-flex{display:inline-flex}.grid{display:grid}.hidden{display:none}.aspect-square{aspect-ratio:1 / 1}.h-1{height:.25rem}.h-1\.5{height:.375rem}.h-10{height:2.5rem}.h-2{height:.5rem}.h-2\.5{height:.625rem}.h-3{height:.75rem}.h-3\.5{height:.875rem}.h-4{height:1rem}.h-4\/5{height:80%}.h-5{height:1.25rem}.h-6{height:1.5rem}.h-7{height:1.75rem}.h-8{height:2rem}.h-9{height:2.25rem}.h-\[10px\]{height:10px}.h-\[12px\]{height:12px}.h-\[1px\]{height:1px}.h-\[20px\]{height:20px}.h-\[240px\]{height:240px}.h-\[32px\]{height:32px}.h-\[600px\]{height:600px}.h-\[60px\]{height:60px}.h-\[var\(--radix-select-trigger-height\)\]{height:var(--radix-select-trigger-height)}.h-full{height:100%}.h-px{height:1px}.h-screen{height:100vh}.max-h-96{max-height:24rem}.max-h-\[200px\]{max-height:200px}.max-h-\[8rem\]{max-height:8rem}.max-h-screen{max-height:100vh}.min-h-\[32px\]{min-height:32px}.min-h-\[60px\]{min-height:60px}.min-h-screen{min-height:100vh}.w-14{width:3.5rem}.w-2{width:.5rem}.w-2\.5{width:.625rem}.w-3{width:.75rem}.w-3\.5{width:.875rem}.w-3\/4{width:75%}.w-4{width:1rem}.w-48{width:12rem}.w-5{width:1.25rem}.w-6{width:1.5rem}.w-72{width:18rem}.w-8{width:2rem}.w-9{width:2.25rem}.w-\[100px\]{width:100px}.w-\[10px\]{width:10px}.w-\[12px\]{width:12px}.w-\[140px\]{width:140px}.w-\[160px\]{width:160px}.w-\[175px\]{width:175px}.w-\[180px\]{width:180px}.w-\[1px\]{width:1px}.w-\[20px\]{width:20px}.w-\[220px\]{width:220px}.w-\[250px\]{width:250px}.w-\[300px\]{width:300px}.w-\[400px\]{width:400px}.w-\[45px\]{width:45px}.w-\[500px\]{width:500px}.w-\[510px\]{width:510px}.w-\[60px\]{width:60px}.w-\[65px\]{width:65px}.w-\[6px\]{width:6px}.w-auto{width:auto}.w-full{width:100%}.w-screen{width:100vw}.min-w-\[600px\]{min-width:600px}.min-w-\[8rem\]{min-width:8rem}.min-w-\[var\(--radix-select-trigger-width\)\]{min-width:var(--radix-select-trigger-width)}.max-w-3xl{max-width:48rem}.max-w-6xl{max-width:72rem}.max-w-\[200px\]{max-width:200px}.max-w-lg{max-width:32rem}.max-w-sm{max-width:24rem}.max-w-xs{max-width:20rem}.flex-1{flex:1 1 0%}.shrink{flex-shrink:1}.shrink-0{flex-shrink:0}.grow{flex-grow:1}.origin-top-left{transform-origin:top left}.-translate-x-1\/2,.translate-x-\[-50\%\]{--tw-translate-x: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-y-\[-50\%\]{--tw-translate-y: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.transform{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}@keyframes pulse{50%{opacity:.5}}.animate-pulse{animation:pulse 2s cubic-bezier(.4,0,.6,1) infinite}@keyframes spin{to{transform:rotate(360deg)}}.animate-spin{animation:spin 1s linear infinite}.cursor-default{cursor:default}.cursor-ew-resize{cursor:ew-resize}.cursor-ne-resize{cursor:ne-resize}.cursor-ns-resize{cursor:ns-resize}.cursor-nw-resize{cursor:nw-resize}.cursor-pointer{cursor:pointer}.cursor-se-resize{cursor:se-resize}.cursor-sw-resize{cursor:sw-resize}.touch-none{touch-action:none}.select-none{-webkit-user-select:none;-moz-user-select:none;user-select:none}.resize-none{resize:none}.resize{resize:both}.flex-row{flex-direction:row}.flex-col{flex-direction:column}.flex-col-reverse{flex-direction:column-reverse}.items-center{align-items:center}.justify-start{justify-content:flex-start}.justify-end{justify-content:flex-end}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.gap-1{gap:.25rem}.gap-2{gap:.5rem}.gap-3{gap:.75rem}.gap-4{gap:1rem}.gap-6{gap:1.5rem}.gap-8{gap:2rem}.gap-\[12px\]{gap:12px}.gap-\[18px\]{gap:18px}.gap-\[8px\]{gap:8px}.gap-y-4{row-gap:1rem}.space-x-2>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.5rem * var(--tw-space-x-reverse));margin-left:calc(.5rem * calc(1 - var(--tw-space-x-reverse)))}.space-x-8>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(2rem * var(--tw-space-x-reverse));margin-left:calc(2rem * calc(1 - var(--tw-space-x-reverse)))}.space-y-0>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(0px * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(0px * var(--tw-space-y-reverse))}.space-y-0\.5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.125rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.125rem * var(--tw-space-y-reverse))}.space-y-1>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.25rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.25rem * var(--tw-space-y-reverse))}.space-y-1\.5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.375rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.375rem * var(--tw-space-y-reverse))}.space-y-2>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.5rem * var(--tw-space-y-reverse))}.space-y-4>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1rem * var(--tw-space-y-reverse))}.justify-self-end{justify-self:end}.overflow-auto{overflow:auto}.overflow-hidden{overflow:hidden}.overflow-y-auto{overflow-y:auto}.overflow-x-hidden{overflow-x:hidden}.overflow-y-hidden{overflow-y:hidden}.whitespace-nowrap{white-space:nowrap}.rounded-\[14px\]{border-radius:14px}.rounded-\[3rem\]{border-radius:3rem}.rounded-\[50\%\]{border-radius:50%}.rounded-\[inherit\]{border-radius:inherit}.rounded-full{border-radius:9999px}.rounded-lg{border-radius:var(--radius)}.rounded-md{border-radius:calc(var(--radius) - 2px)}.rounded-sm{border-radius:calc(var(--radius) - 4px)}.rounded-xl{border-radius:.75rem}.border{border-width:1px}.border-2{border-width:2px}.border-\[1px\]{border-width:1px}.border-\[2px\]{border-width:2px}.border-b{border-bottom-width:1px}.border-l{border-left-width:1px}.border-r{border-right-width:1px}.border-t{border-top-width:1px}.border-solid{border-style:solid}.border-\[\#ffcc00\]{--tw-border-opacity: 1;border-color:rgb(255 204 0 / var(--tw-border-opacity))}.border-\[dashed\]{border-color:dashed}.border-\[solid\]{border-color:solid}.border-destructive{border-color:hsl(var(--destructive))}.border-input{border-color:hsl(var(--input))}.border-primary{border-color:hsl(var(--primary))}.border-primary\/60{border-color:hsl(var(--primary) / .6)}.border-transparent{border-color:transparent}.border-l-transparent{border-left-color:transparent}.border-t-transparent{border-top-color:transparent}.bg-\[\#ffcc00bb\]{background-color:#fc0b}.bg-\[rgba\(21\,_215\,_121\,_0\.936\)\]{background-color:#15d779ef}.bg-\[rgba\(237\,_49\,_55\,_0\.942\)\]{background-color:#ed3137f0}.bg-background{background-color:hsl(var(--background))}.bg-background\/70{background-color:hsl(var(--background) / .7)}.bg-background\/80{background-color:hsl(var(--background) / .8)}.bg-border{background-color:hsl(var(--border))}.bg-destructive{background-color:hsl(var(--destructive))}.bg-muted{background-color:hsl(var(--muted))}.bg-popover{background-color:hsl(var(--popover))}.bg-primary{background-color:hsl(var(--primary))}.bg-primary\/20{background-color:hsl(var(--primary) / .2)}.bg-secondary{background-color:hsl(var(--secondary))}.bg-transparent{background-color:transparent}.bg-\[radial-gradient\(circle_at_1px_1px\,_\#8e8e8e8e_1px\,_transparent_0\)\]{background-image:radial-gradient(circle at 1px 1px,#8e8e8e8e 1px,transparent 0)}.bg-repeat{background-repeat:repeat}.fill-current{fill:currentColor}.fill-primary{fill:hsl(var(--primary))}.p-1{padding:.25rem}.p-1\.5{padding:.375rem}.p-16{padding:4rem}.p-4{padding:1rem}.p-6{padding:1.5rem}.p-\[1px\]{padding:1px}.p-\[8px\]{padding:8px}.px-2{padding-left:.5rem;padding-right:.5rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-4{padding-left:1rem;padding-right:1rem}.px-6{padding-left:1.5rem;padding-right:1.5rem}.px-8{padding-left:2rem;padding-right:2rem}.py-1{padding-top:.25rem;padding-bottom:.25rem}.py-1\.5{padding-top:.375rem;padding-bottom:.375rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.py-3{padding-top:.75rem;padding-bottom:.75rem}.py-4{padding-top:1rem;padding-bottom:1rem}.py-\[6px\]{padding-top:6px;padding-bottom:6px}.pb-4{padding-bottom:1rem}.pl-2{padding-left:.5rem}.pl-4{padding-left:1rem}.pl-8{padding-left:2rem}.pl-\[30px\]{padding-left:30px}.pl-\[8px\]{padding-left:8px}.pr-1{padding-right:.25rem}.pr-2{padding-right:.5rem}.pr-3{padding-right:.75rem}.pr-4{padding-right:1rem}.pr-6{padding-right:1.5rem}.pr-8{padding-right:2rem}.pr-\[8px\]{padding-right:8px}.pt-0{padding-top:0}.pt-4{padding-top:1rem}.text-center{text-align:center}.text-2xl{font-size:1.5rem;line-height:2rem}.text-\[0\.8rem\]{font-size:.8rem}.text-base{font-size:1rem;line-height:1.5rem}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xs{font-size:.75rem;line-height:1rem}.font-medium{font-weight:500}.font-semibold{font-weight:600}.leading-none{line-height:1}.tracking-tight{letter-spacing:-.025em}.tracking-widest{letter-spacing:.1em}.text-destructive{color:hsl(var(--destructive))}.text-destructive-foreground{color:hsl(var(--destructive-foreground))}.text-foreground{color:hsl(var(--foreground))}.text-foreground\/50{color:hsl(var(--foreground) / .5)}.text-gray-200{--tw-text-opacity: 1;color:rgb(229 231 235 / var(--tw-text-opacity))}.text-muted-foreground{color:hsl(var(--muted-foreground))}.text-popover-foreground{color:hsl(var(--popover-foreground))}.text-primary{color:hsl(var(--primary))}.text-primary-foreground{color:hsl(var(--primary-foreground))}.text-secondary-foreground{color:hsl(var(--secondary-foreground))}.underline-offset-4{text-underline-offset:4px}.opacity-0{opacity:0}.opacity-50{opacity:.5}.opacity-60{opacity:.6}.opacity-70{opacity:.7}.opacity-90{opacity:.9}.shadow{--tw-shadow: 0 1px 3px 0 rgb(0 0 0 / .1), 0 1px 2px -1px rgb(0 0 0 / .1);--tw-shadow-colored: 0 1px 3px 0 var(--tw-shadow-color), 0 1px 2px -1px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-lg{--tw-shadow: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1);--tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-md{--tw-shadow: 0 4px 6px -1px rgb(0 0 0 / .1), 0 2px 4px -2px rgb(0 0 0 / .1);--tw-shadow-colored: 0 4px 6px -1px var(--tw-shadow-color), 0 2px 4px -2px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-sm{--tw-shadow: 0 1px 2px 0 rgb(0 0 0 / .05);--tw-shadow-colored: 0 1px 2px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.outline-none{outline:2px solid transparent;outline-offset:2px}.outline{outline-style:solid}.outline-dashed{outline-style:dashed}.outline-8{outline-width:8px}.outline-\[rgba\(255\,89\,95\,0\.31\)\]{outline-color:#ff595f4f}.outline-\[rgba\(98\,255\,179\,0\.31\)\]{outline-color:#62ffb34f}.outline-primary{outline-color:hsl(var(--primary))}.ring-0{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(0px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.ring-offset-background{--tw-ring-offset-color: hsl(var(--background))}.blur{--tw-blur: blur(8px);filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.backdrop-blur-md{--tw-backdrop-blur: blur(12px);-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.backdrop-blur-sm{--tw-backdrop-blur: blur(4px);-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.backdrop-filter{-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.transition{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,-webkit-backdrop-filter;transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter;transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter,-webkit-backdrop-filter;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-\[height\]{transition-property:height;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-all{transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-colors{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-opacity{transition-property:opacity;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-transform{transition-property:transform;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.duration-200{transition-duration:.2s}.ease-in-out{transition-timing-function:cubic-bezier(.4,0,.2,1)}.content-\[\'\'\]{--tw-content: "";content:var(--tw-content)}@keyframes enter{0%{opacity:var(--tw-enter-opacity, 1);transform:translate3d(var(--tw-enter-translate-x, 0),var(--tw-enter-translate-y, 0),0) scale3d(var(--tw-enter-scale, 1),var(--tw-enter-scale, 1),var(--tw-enter-scale, 1)) rotate(var(--tw-enter-rotate, 0))}}@keyframes exit{to{opacity:var(--tw-exit-opacity, 1);transform:translate3d(var(--tw-exit-translate-x, 0),var(--tw-exit-translate-y, 0),0) scale3d(var(--tw-exit-scale, 1),var(--tw-exit-scale, 1),var(--tw-exit-scale, 1)) rotate(var(--tw-exit-rotate, 0))}}.animate-in{animation-name:enter;animation-duration:.15s;--tw-enter-opacity: initial;--tw-enter-scale: initial;--tw-enter-rotate: initial;--tw-enter-translate-x: initial;--tw-enter-translate-y: initial}.fade-in-0{--tw-enter-opacity: 0}.zoom-in-95{--tw-enter-scale: .95}.duration-200{animation-duration:.2s}.ease-in-out{animation-timing-function:cubic-bezier(.4,0,.2,1)}.\[background-size\:20px_20px\]{background-size:20px 20px}.\[box-shadow\:0_0_0_0_rgba\(21\,_215\,_121\,_0\.936\)\]{box-shadow:0 0 #15d779ef}.\[box-shadow\:0_0_0_9999px_rgba\(0\,_0\,_0\,_0\.5\)\]{box-shadow:0 0 0 9999px #00000080}.\[grid-area\:editor-content\]{grid-area:editor-content}.\[grid-area\:original-image-content\]{grid-area:original-image-content}.\[grid-template-areas\:\'editor-content\'\]{grid-template-areas:"editor-content"}.\[grid-template-areas\:\'original-image-content\'\]{grid-template-areas:"original-image-content"}html{font-family:Inter,"system-ui";overflow:hidden}@supports (font-variation-settings: normal){html{font-family:Inter var,"system-ui"}}.react-transform-wrapper{display:grid!important;width:100%!important;height:100%!important}.react-photo-album{padding:8px}.react-photo-album--photo{-moz-user-select:none;-webkit-user-select:none;user-select:none;border-radius:8px;transition:transform .25s,visibility .25s ease-in}.react-photo-album--photo:hover{border:1px solid var(--border);transform:scale(1.03)}.icon-button-icon-wrapper svg{stroke-width:1px}.file\:border-0::file-selector-button{border-width:0px}.file\:bg-transparent::file-selector-button{background-color:transparent}.file\:text-sm::file-selector-button{font-size:.875rem;line-height:1.25rem}.file\:font-medium::file-selector-button{font-weight:500}.placeholder\:text-muted-foreground::-moz-placeholder{color:hsl(var(--muted-foreground))}.placeholder\:text-muted-foreground::placeholder{color:hsl(var(--muted-foreground))}.hover\:cursor-move:hover{cursor:move}.hover\:bg-accent:hover{background-color:hsl(var(--accent))}.hover\:bg-destructive\/90:hover{background-color:hsl(var(--destructive) / .9)}.hover\:bg-muted:hover{background-color:hsl(var(--muted))}.hover\:bg-primary:hover{background-color:hsl(var(--primary))}.hover\:bg-primary\/90:hover{background-color:hsl(var(--primary) / .9)}.hover\:bg-secondary:hover{background-color:hsl(var(--secondary))}.hover\:bg-secondary\/80:hover{background-color:hsl(var(--secondary) / .8)}.hover\:text-accent-foreground:hover{color:hsl(var(--accent-foreground))}.hover\:text-foreground:hover{color:hsl(var(--foreground))}.hover\:text-muted-foreground:hover{color:hsl(var(--muted-foreground))}.hover\:text-primary-foreground:hover{color:hsl(var(--primary-foreground))}.hover\:underline:hover{text-decoration-line:underline}.hover\:opacity-100:hover{opacity:1}.focus\:h-\[120px\]:focus{height:120px}.focus\:overflow-y-auto:focus{overflow-y:auto}.focus\:bg-accent:focus{background-color:hsl(var(--accent))}.focus\:text-accent-foreground:focus{color:hsl(var(--accent-foreground))}.focus\:opacity-100:focus{opacity:1}.focus\:outline-none:focus{outline:2px solid transparent;outline-offset:2px}.focus\:ring-1:focus{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus\:ring-2:focus{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus\:ring-ring:focus{--tw-ring-color: hsl(var(--ring))}.focus\:ring-offset-2:focus{--tw-ring-offset-width: 2px}.focus-visible\:outline-none:focus-visible{outline:2px solid transparent;outline-offset:2px}.focus-visible\:ring-1:focus-visible{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus-visible\:ring-2:focus-visible{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus-visible\:ring-ring:focus-visible{--tw-ring-color: hsl(var(--ring))}.focus-visible\:ring-offset-2:focus-visible{--tw-ring-offset-width: 2px}.focus-visible\:ring-offset-background:focus-visible{--tw-ring-offset-color: hsl(var(--background))}.disabled\:pointer-events-none:disabled{pointer-events:none}.disabled\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\:opacity-50:disabled{opacity:.5}.group:hover .group-hover\:opacity-100{opacity:1}.group.destructive .group-\[\.destructive\]\:border-muted\/40{border-color:hsl(var(--muted) / .4)}.group.destructive .group-\[\.destructive\]\:text-red-300{--tw-text-opacity: 1;color:rgb(252 165 165 / var(--tw-text-opacity))}.group.destructive .group-\[\.destructive\]\:hover\:border-destructive\/30:hover{border-color:hsl(var(--destructive) / .3)}.group.destructive .group-\[\.destructive\]\:hover\:bg-destructive:hover{background-color:hsl(var(--destructive))}.group.destructive .group-\[\.destructive\]\:hover\:text-destructive-foreground:hover{color:hsl(var(--destructive-foreground))}.group.destructive .group-\[\.destructive\]\:hover\:text-red-50:hover{--tw-text-opacity: 1;color:rgb(254 242 242 / var(--tw-text-opacity))}.group.destructive .group-\[\.destructive\]\:focus\:ring-destructive:focus{--tw-ring-color: hsl(var(--destructive))}.group.destructive .group-\[\.destructive\]\:focus\:ring-red-400:focus{--tw-ring-opacity: 1;--tw-ring-color: rgb(248 113 113 / var(--tw-ring-opacity))}.group.destructive .group-\[\.destructive\]\:focus\:ring-offset-red-600:focus{--tw-ring-offset-color: #dc2626}.peer:disabled~.peer-disabled\:cursor-not-allowed{cursor:not-allowed}.peer:disabled~.peer-disabled\:opacity-70{opacity:.7}.data-\[disabled\]\:pointer-events-none[data-disabled]{pointer-events:none}.data-\[side\=bottom\]\:translate-y-1[data-side=bottom]{--tw-translate-y: .25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[side\=left\]\:-translate-x-1[data-side=left]{--tw-translate-x: -.25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[side\=right\]\:translate-x-1[data-side=right]{--tw-translate-x: .25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[side\=top\]\:-translate-y-1[data-side=top]{--tw-translate-y: -.25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[state\=checked\]\:translate-x-4[data-state=checked]{--tw-translate-x: 1rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[state\=unchecked\]\:translate-x-0[data-state=unchecked],.data-\[swipe\=cancel\]\:translate-x-0[data-swipe=cancel]{--tw-translate-x: 0px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[swipe\=end\]\:translate-x-\[var\(--radix-toast-swipe-end-x\)\][data-swipe=end]{--tw-translate-x: var(--radix-toast-swipe-end-x);transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[swipe\=move\]\:translate-x-\[var\(--radix-toast-swipe-move-x\)\][data-swipe=move]{--tw-translate-x: var(--radix-toast-swipe-move-x);transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}@keyframes accordion-up{0%{height:var(--radix-accordion-content-height)}to{height:0}}.data-\[state\=closed\]\:animate-accordion-up[data-state=closed]{animation:accordion-up .2s ease-out}@keyframes accordion-down{0%{height:0}to{height:var(--radix-accordion-content-height)}}.data-\[state\=open\]\:animate-accordion-down[data-state=open]{animation:accordion-down .2s ease-out}.data-\[disabled\]\:cursor-not-allowed[data-disabled]{cursor:not-allowed}.data-\[state\=active\]\:bg-background[data-state=active]{background-color:hsl(var(--background))}.data-\[state\=checked\]\:bg-primary[data-state=checked]{background-color:hsl(var(--primary))}.data-\[state\=on\]\:bg-accent[data-state=on],.data-\[state\=open\]\:bg-accent[data-state=open]{background-color:hsl(var(--accent))}.data-\[state\=unchecked\]\:bg-input[data-state=unchecked]{background-color:hsl(var(--input))}.data-\[state\=active\]\:text-foreground[data-state=active]{color:hsl(var(--foreground))}.data-\[state\=on\]\:text-accent-foreground[data-state=on],.data-\[state\=open\]\:text-accent-foreground[data-state=open]{color:hsl(var(--accent-foreground))}.data-\[state\=open\]\:text-muted-foreground[data-state=open]{color:hsl(var(--muted-foreground))}.data-\[disabled\]\:opacity-50[data-disabled]{opacity:.5}.data-\[state\=active\]\:shadow[data-state=active]{--tw-shadow: 0 1px 3px 0 rgb(0 0 0 / .1), 0 1px 2px -1px rgb(0 0 0 / .1);--tw-shadow-colored: 0 1px 3px 0 var(--tw-shadow-color), 0 1px 2px -1px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.data-\[swipe\=move\]\:transition-none[data-swipe=move]{transition-property:none}.data-\[state\=closed\]\:duration-200[data-state=closed]{transition-duration:.2s}.data-\[state\=open\]\:duration-300[data-state=open]{transition-duration:.3s}.data-\[state\=open\]\:animate-in[data-state=open]{animation-name:enter;animation-duration:.15s;--tw-enter-opacity: initial;--tw-enter-scale: initial;--tw-enter-rotate: initial;--tw-enter-translate-x: initial;--tw-enter-translate-y: initial}.data-\[state\=closed\]\:animate-out[data-state=closed],.data-\[swipe\=end\]\:animate-out[data-swipe=end]{animation-name:exit;animation-duration:.15s;--tw-exit-opacity: initial;--tw-exit-scale: initial;--tw-exit-rotate: initial;--tw-exit-translate-x: initial;--tw-exit-translate-y: initial}.data-\[state\=closed\]\:fade-out-0[data-state=closed]{--tw-exit-opacity: 0}.data-\[state\=closed\]\:fade-out-80[data-state=closed]{--tw-exit-opacity: .8}.data-\[state\=open\]\:fade-in-0[data-state=open]{--tw-enter-opacity: 0}.data-\[state\=closed\]\:zoom-out-95[data-state=closed]{--tw-exit-scale: .95}.data-\[state\=open\]\:zoom-in-95[data-state=open]{--tw-enter-scale: .95}.data-\[side\=bottom\]\:slide-in-from-top-2[data-side=bottom]{--tw-enter-translate-y: -.5rem}.data-\[side\=left\]\:slide-in-from-right-2[data-side=left]{--tw-enter-translate-x: .5rem}.data-\[side\=right\]\:slide-in-from-left-2[data-side=right]{--tw-enter-translate-x: -.5rem}.data-\[side\=top\]\:slide-in-from-bottom-2[data-side=top]{--tw-enter-translate-y: .5rem}.data-\[state\=closed\]\:slide-out-to-bottom[data-state=closed]{--tw-exit-translate-y: 100%}.data-\[state\=closed\]\:slide-out-to-left[data-state=closed]{--tw-exit-translate-x: -100%}.data-\[state\=closed\]\:slide-out-to-left-1\/2[data-state=closed]{--tw-exit-translate-x: -50%}.data-\[state\=closed\]\:slide-out-to-right[data-state=closed],.data-\[state\=closed\]\:slide-out-to-right-full[data-state=closed]{--tw-exit-translate-x: 100%}.data-\[state\=closed\]\:slide-out-to-top[data-state=closed]{--tw-exit-translate-y: -100%}.data-\[state\=closed\]\:slide-out-to-top-\[48\%\][data-state=closed]{--tw-exit-translate-y: -48%}.data-\[state\=open\]\:slide-in-from-bottom[data-state=open]{--tw-enter-translate-y: 100%}.data-\[state\=open\]\:slide-in-from-left[data-state=open]{--tw-enter-translate-x: -100%}.data-\[state\=open\]\:slide-in-from-left-1\/2[data-state=open]{--tw-enter-translate-x: -50%}.data-\[state\=open\]\:slide-in-from-right[data-state=open]{--tw-enter-translate-x: 100%}.data-\[state\=open\]\:slide-in-from-top[data-state=open]{--tw-enter-translate-y: -100%}.data-\[state\=open\]\:slide-in-from-top-\[48\%\][data-state=open]{--tw-enter-translate-y: -48%}.data-\[state\=open\]\:slide-in-from-top-full[data-state=open]{--tw-enter-translate-y: -100%}.data-\[state\=closed\]\:duration-200[data-state=closed]{animation-duration:.2s}.data-\[state\=open\]\:duration-300[data-state=open]{animation-duration:.3s}:is(.dark .dark\:text-gray-600){--tw-text-opacity: 1;color:rgb(75 85 99 / var(--tw-text-opacity))}@media (min-width: 640px){.sm\:bottom-0{bottom:0}.sm\:right-0{right:0}.sm\:top-auto{top:auto}.sm\:mt-0{margin-top:0}.sm\:max-w-sm{max-width:24rem}.sm\:flex-row{flex-direction:row}.sm\:flex-col{flex-direction:column}.sm\:justify-end{justify-content:flex-end}.sm\:space-x-2>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.5rem * var(--tw-space-x-reverse));margin-left:calc(.5rem * calc(1 - var(--tw-space-x-reverse)))}.sm\:rounded-lg{border-radius:var(--radius)}.sm\:text-left{text-align:left}.data-\[state\=open\]\:sm\:slide-in-from-bottom-full[data-state=open]{--tw-enter-translate-y: 100%}}@media (min-width: 768px){.md\:max-w-\[420px\]{max-width:420px}}.\[\&\+div\]\:text-xs+div{font-size:.75rem;line-height:1rem}.\[\&\>span\]\:line-clamp-1>span{overflow:hidden;display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:1}.\[\&\[data-state\=open\]\>svg\]\:rotate-180[data-state=open]>svg{--tw-rotate: 180deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))} diff --git a/py/iopaint/web_app/assets/index-qFliSBYV.js b/py/iopaint/web_app/assets/index-qFliSBYV.js new file mode 100644 index 0000000..71fc7b1 --- /dev/null +++ b/py/iopaint/web_app/assets/index-qFliSBYV.js @@ -0,0 +1,165 @@ +var Nv=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)};var z=(e,t,n)=>(Nv(e,t,"read from private field"),n?n.call(e):t.get(e)),Te=(e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)},ye=(e,t,n,r)=>(Nv(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n);var Ff=(e,t,n,r)=>({set _(o){ye(e,t,o,n)},get _(){return z(e,t,r)}}),tt=(e,t,n)=>(Nv(e,t,"access private method"),n);function SD(e,t){for(var n=0;nr[o]})}}}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 o of document.querySelectorAll('link[rel="modulepreload"]'))r(o);new MutationObserver(o=>{for(const i of o)if(i.type==="childList")for(const s of i.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&r(s)}).observe(document,{childList:!0,subtree:!0});function n(o){const i={};return o.integrity&&(i.integrity=o.integrity),o.referrerPolicy&&(i.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?i.credentials="include":o.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(o){if(o.ep)return;o.ep=!0;const i=n(o);fetch(o.href,i)}})();var Yc=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function lm(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var v$={exports:{}},cm={},y$={exports:{}},it={};/** + * @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 bd=Symbol.for("react.element"),ED=Symbol.for("react.portal"),CD=Symbol.for("react.fragment"),$D=Symbol.for("react.strict_mode"),kD=Symbol.for("react.profiler"),RD=Symbol.for("react.provider"),TD=Symbol.for("react.context"),PD=Symbol.for("react.forward_ref"),AD=Symbol.for("react.suspense"),OD=Symbol.for("react.memo"),MD=Symbol.for("react.lazy"),LS=Symbol.iterator;function ND(e){return e===null||typeof e!="object"?null:(e=LS&&e[LS]||e["@@iterator"],typeof e=="function"?e:null)}var w$={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},x$=Object.assign,b$={};function fc(e,t,n){this.props=e,this.context=t,this.refs=b$,this.updater=n||w$}fc.prototype.isReactComponent={};fc.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")};fc.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function _$(){}_$.prototype=fc.prototype;function ew(e,t,n){this.props=e,this.context=t,this.refs=b$,this.updater=n||w$}var tw=ew.prototype=new _$;tw.constructor=ew;x$(tw,fc.prototype);tw.isPureReactComponent=!0;var FS=Array.isArray,S$=Object.prototype.hasOwnProperty,nw={current:null},E$={key:!0,ref:!0,__self:!0,__source:!0};function C$(e,t,n){var r,o={},i=null,s=null;if(t!=null)for(r in t.ref!==void 0&&(s=t.ref),t.key!==void 0&&(i=""+t.key),t)S$.call(t,r)&&!E$.hasOwnProperty(r)&&(o[r]=t[r]);var l=arguments.length-2;if(l===1)o.children=n;else if(1>>1,ge=K[le];if(0>>1;leo(We,W))Meo(fe,We)?(K[le]=fe,K[Me]=W,le=Me):(K[le]=We,K[Ue]=W,le=Ue);else if(Meo(fe,W))K[le]=fe,K[Me]=W,le=Me;else break e}}return Q}function o(K,Q){var W=K.sortIndex-Q.sortIndex;return W!==0?W:K.id-Q.id}if(typeof performance=="object"&&typeof performance.now=="function"){var i=performance;e.unstable_now=function(){return i.now()}}else{var s=Date,l=s.now();e.unstable_now=function(){return s.now()-l}}var u=[],d=[],h=1,m=null,g=3,y=!1,x=!1,_=!1,C=typeof setTimeout=="function"?setTimeout:null,S=typeof clearTimeout=="function"?clearTimeout:null,b=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function E(K){for(var Q=n(d);Q!==null;){if(Q.callback===null)r(d);else if(Q.startTime<=K)r(d),Q.sortIndex=Q.expirationTime,t(u,Q);else break;Q=n(d)}}function k(K){if(_=!1,E(K),!x)if(n(u)!==null)x=!0,L(P);else{var Q=n(d);Q!==null&&ie(k,Q.startTime-K)}}function P(K,Q){x=!1,_&&(_=!1,S(O),O=-1),y=!0;var W=g;try{for(E(Q),m=n(u);m!==null&&(!(m.expirationTime>Q)||K&&!J());){var le=m.callback;if(typeof le=="function"){m.callback=null,g=m.priorityLevel;var ge=le(m.expirationTime<=Q);Q=e.unstable_now(),typeof ge=="function"?m.callback=ge:m===n(u)&&r(u),E(Q)}else r(u);m=n(u)}if(m!==null)var Ve=!0;else{var Ue=n(d);Ue!==null&&ie(k,Ue.startTime-Q),Ve=!1}return Ve}finally{m=null,g=W,y=!1}}var M=!1,A=null,O=-1,F=5,V=-1;function J(){return!(e.unstable_now()-VK||125le?(K.sortIndex=W,t(d,K),n(u)===null&&K===n(d)&&(_?(S(O),O=-1):_=!0,ie(k,W-le))):(K.sortIndex=ge,t(u,K),x||y||(x=!0,L(P))),K},e.unstable_shouldYield=J,e.unstable_wrapCallback=function(K){var Q=g;return function(){var W=g;g=Q;try{return K.apply(this,arguments)}finally{g=W}}}})(T$);R$.exports=T$;var KD=R$.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 P$=f,yr=KD;function ce(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"),B0=Object.prototype.hasOwnProperty,YD=/^[: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]*$/,zS={},BS={};function GD(e){return B0.call(BS,e)?!0:B0.call(zS,e)?!1:YD.test(e)?BS[e]=!0:(zS[e]=!0,!1)}function XD(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 ZD(e,t,n,r){if(t===null||typeof t>"u"||XD(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 Un(e,t,n,r,o,i,s){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=o,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=i,this.removeEmptyString=s}var xn={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){xn[e]=new Un(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];xn[t]=new Un(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){xn[e]=new Un(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){xn[e]=new Un(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){xn[e]=new Un(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){xn[e]=new Un(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){xn[e]=new Un(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){xn[e]=new Un(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){xn[e]=new Un(e,5,!1,e.toLowerCase(),null,!1,!1)});var ow=/[\-:]([a-z])/g;function iw(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(ow,iw);xn[t]=new Un(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(ow,iw);xn[t]=new Un(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(ow,iw);xn[t]=new Un(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){xn[e]=new Un(e,1,!1,e.toLowerCase(),null,!1,!1)});xn.xlinkHref=new Un("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){xn[e]=new Un(e,1,!1,e.toLowerCase(),null,!0,!0)});function sw(e,t,n,r){var o=xn.hasOwnProperty(t)?xn[t]:null;(o!==null?o.type!==0:r||!(2l||o[s]!==i[l]){var u=` +`+o[s].replace(" at new "," at ");return e.displayName&&u.includes("")&&(u=u.replace("",e.displayName)),u}while(1<=s&&0<=l);break}}}finally{Lv=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?uu(e):""}function qD(e){switch(e.tag){case 5:return uu(e.type);case 16:return uu("Lazy");case 13:return uu("Suspense");case 19:return uu("SuspenseList");case 0:case 2:case 15:return e=Fv(e.type,!1),e;case 11:return e=Fv(e.type.render,!1),e;case 1:return e=Fv(e.type,!0),e;default:return""}}function H0(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 ll:return"Fragment";case al:return"Portal";case U0:return"Profiler";case aw:return"StrictMode";case V0:return"Suspense";case W0:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case M$:return(e.displayName||"Context")+".Consumer";case O$:return(e._context.displayName||"Context")+".Provider";case lw:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case cw:return t=e.displayName||null,t!==null?t:H0(e.type)||"Memo";case Ki:t=e._payload,e=e._init;try{return H0(e(t))}catch{}}return null}function QD(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 H0(t);case 8:return t===aw?"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 Ss(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function D$(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function JD(e){var t=D$(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 o=n.get,i=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return o.call(this)},set:function(s){r=""+s,i.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 Bf(e){e._valueTracker||(e._valueTracker=JD(e))}function I$(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=D$(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function oh(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 K0(e,t){var n=t.checked;return zt({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function VS(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=Ss(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 L$(e,t){t=t.checked,t!=null&&sw(e,"checked",t,!1)}function Y0(e,t){L$(e,t);var n=Ss(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")?G0(e,t.type,n):t.hasOwnProperty("defaultValue")&&G0(e,t.type,Ss(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function WS(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 G0(e,t,n){(t!=="number"||oh(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var du=Array.isArray;function bl(e,t,n,r){if(e=e.options,t){t={};for(var o=0;o"+t.valueOf().toString()+"",t=Uf.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function Ou(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var vu={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},e9=["Webkit","ms","Moz","O"];Object.keys(vu).forEach(function(e){e9.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),vu[t]=vu[e]})});function B$(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||vu.hasOwnProperty(e)&&vu[e]?(""+t).trim():t+"px"}function U$(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,o=B$(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,o):e[n]=o}}var t9=zt({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 q0(e,t){if(t){if(t9[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(ce(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(ce(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(ce(61))}if(t.style!=null&&typeof t.style!="object")throw Error(ce(62))}}function Q0(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 J0=null;function uw(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var ey=null,_l=null,Sl=null;function YS(e){if(e=Ed(e)){if(typeof ey!="function")throw Error(ce(280));var t=e.stateNode;t&&(t=hm(t),ey(e.stateNode,e.type,t))}}function V$(e){_l?Sl?Sl.push(e):Sl=[e]:_l=e}function W$(){if(_l){var e=_l,t=Sl;if(Sl=_l=null,YS(e),t)for(e=0;e>>=0,e===0?32:31-(f9(e)/p9|0)|0}var Vf=64,Wf=4194304;function fu(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 lh(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,o=e.suspendedLanes,i=e.pingedLanes,s=n&268435455;if(s!==0){var l=s&~o;l!==0?r=fu(l):(i&=s,i!==0&&(r=fu(i)))}else s=n&~o,s!==0?r=fu(s):i!==0&&(r=fu(i));if(r===0)return 0;if(t!==0&&t!==r&&!(t&o)&&(o=r&-r,i=t&-t,o>=i||o===16&&(i&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 _d(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-go(t),e[t]=n}function v9(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=wu),nE=" ",rE=!1;function uk(e,t){switch(e){case"keyup":return H9.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function dk(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var cl=!1;function Y9(e,t){switch(e){case"compositionend":return dk(t);case"keypress":return t.which!==32?null:(rE=!0,nE);case"textInput":return e=t.data,e===nE&&rE?null:e;default:return null}}function G9(e,t){if(cl)return e==="compositionend"||!yw&&uk(e,t)?(e=lk(),$p=mw=rs=null,cl=!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=aE(n)}}function mk(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?mk(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function gk(){for(var e=window,t=oh();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=oh(e.document)}return t}function ww(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 rI(e){var t=gk(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&mk(n.ownerDocument.documentElement,n)){if(r!==null&&ww(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 o=n.textContent.length,i=Math.min(r.start,o);r=r.end===void 0?i:Math.min(r.end,o),!e.extend&&i>r&&(o=r,r=i,i=o),o=lE(n,i);var s=lE(n,r);o&&s&&(e.rangeCount!==1||e.anchorNode!==o.node||e.anchorOffset!==o.offset||e.focusNode!==s.node||e.focusOffset!==s.offset)&&(t=t.createRange(),t.setStart(o.node,o.offset),e.removeAllRanges(),i>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,ul=null,sy=null,bu=null,ay=!1;function cE(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;ay||ul==null||ul!==oh(r)||(r=ul,"selectionStart"in r&&ww(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}),bu&&Fu(bu,r)||(bu=r,r=dh(sy,"onSelect"),0pl||(e.current=py[pl],py[pl]=null,pl--)}function $t(e,t){pl++,py[pl]=e.current,e.current=t}var Es={},Tn=Ps(Es),Jn=Ps(!1),ba=Es;function Kl(e,t){var n=e.type.contextTypes;if(!n)return Es;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var o={},i;for(i in n)o[i]=t[i];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=o),o}function er(e){return e=e.childContextTypes,e!=null}function ph(){At(Jn),At(Tn)}function gE(e,t,n){if(Tn.current!==Es)throw Error(ce(168));$t(Tn,t),$t(Jn,n)}function Ck(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var o in r)if(!(o in t))throw Error(ce(108,QD(e)||"Unknown",o));return zt({},n,r)}function hh(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||Es,ba=Tn.current,$t(Tn,e),$t(Jn,Jn.current),!0}function vE(e,t,n){var r=e.stateNode;if(!r)throw Error(ce(169));n?(e=Ck(e,t,ba),r.__reactInternalMemoizedMergedChildContext=e,At(Jn),At(Tn),$t(Tn,e)):At(Jn),$t(Jn,n)}var li=null,mm=!1,Qv=!1;function $k(e){li===null?li=[e]:li.push(e)}function mI(e){mm=!0,$k(e)}function As(){if(!Qv&&li!==null){Qv=!0;var e=0,t=xt;try{var n=li;for(xt=1;e>=s,o-=s,ci=1<<32-go(t)+o|n<O?(F=A,A=null):F=A.sibling;var V=g(S,A,E[O],k);if(V===null){A===null&&(A=F);break}e&&A&&V.alternate===null&&t(S,A),b=i(V,b,O),M===null?P=V:M.sibling=V,M=V,A=F}if(O===E.length)return n(S,A),Dt&&qs(S,O),P;if(A===null){for(;OO?(F=A,A=null):F=A.sibling;var J=g(S,A,V.value,k);if(J===null){A===null&&(A=F);break}e&&A&&J.alternate===null&&t(S,A),b=i(J,b,O),M===null?P=J:M.sibling=J,M=J,A=F}if(V.done)return n(S,A),Dt&&qs(S,O),P;if(A===null){for(;!V.done;O++,V=E.next())V=m(S,V.value,k),V!==null&&(b=i(V,b,O),M===null?P=V:M.sibling=V,M=V);return Dt&&qs(S,O),P}for(A=r(S,A);!V.done;O++,V=E.next())V=y(A,S,O,V.value,k),V!==null&&(e&&V.alternate!==null&&A.delete(V.key===null?O:V.key),b=i(V,b,O),M===null?P=V:M.sibling=V,M=V);return e&&A.forEach(function(G){return t(S,G)}),Dt&&qs(S,O),P}function C(S,b,E,k){if(typeof E=="object"&&E!==null&&E.type===ll&&E.key===null&&(E=E.props.children),typeof E=="object"&&E!==null){switch(E.$$typeof){case zf:e:{for(var P=E.key,M=b;M!==null;){if(M.key===P){if(P=E.type,P===ll){if(M.tag===7){n(S,M.sibling),b=o(M,E.props.children),b.return=S,S=b;break e}}else if(M.elementType===P||typeof P=="object"&&P!==null&&P.$$typeof===Ki&&EE(P)===M.type){n(S,M.sibling),b=o(M,E.props),b.ref=Jc(S,M,E),b.return=S,S=b;break e}n(S,M);break}else t(S,M);M=M.sibling}E.type===ll?(b=xa(E.props.children,S.mode,k,E.key),b.return=S,S=b):(k=Np(E.type,E.key,E.props,null,S.mode,k),k.ref=Jc(S,b,E),k.return=S,S=k)}return s(S);case al:e:{for(M=E.key;b!==null;){if(b.key===M)if(b.tag===4&&b.stateNode.containerInfo===E.containerInfo&&b.stateNode.implementation===E.implementation){n(S,b.sibling),b=o(b,E.children||[]),b.return=S,S=b;break e}else{n(S,b);break}else t(S,b);b=b.sibling}b=s0(E,S.mode,k),b.return=S,S=b}return s(S);case Ki:return M=E._init,C(S,b,M(E._payload),k)}if(du(E))return x(S,b,E,k);if(Gc(E))return _(S,b,E,k);qf(S,E)}return typeof E=="string"&&E!==""||typeof E=="number"?(E=""+E,b!==null&&b.tag===6?(n(S,b.sibling),b=o(b,E),b.return=S,S=b):(n(S,b),b=i0(E,S.mode,k),b.return=S,S=b),s(S)):n(S,b)}return C}var Gl=Nk(!0),Dk=Nk(!1),Cd={},zo=Ps(Cd),Uu=Ps(Cd),Vu=Ps(Cd);function oa(e){if(e===Cd)throw Error(ce(174));return e}function Rw(e,t){switch($t(Vu,t),$t(Uu,e),$t(zo,Cd),e=t.nodeType,e){case 9:case 11:t=(t=t.documentElement)?t.namespaceURI:Z0(null,"");break;default:e=e===8?t.parentNode:t,t=e.namespaceURI||null,e=e.tagName,t=Z0(t,e)}At(zo),$t(zo,t)}function Xl(){At(zo),At(Uu),At(Vu)}function Ik(e){oa(Vu.current);var t=oa(zo.current),n=Z0(t,e.type);t!==n&&($t(Uu,e),$t(zo,n))}function Tw(e){Uu.current===e&&(At(zo),At(Uu))}var Lt=Ps(0);function xh(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 Jv=[];function Pw(){for(var e=0;en?n:4,e(!0);var r=e0.transition;e0.transition={};try{e(!1),t()}finally{xt=n,e0.transition=r}}function Qk(){return Gr().memoizedState}function wI(e,t,n){var r=ys(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},Jk(e))eR(t,n);else if(n=Pk(e,t,n,r),n!==null){var o=jn();vo(n,e,r,o),tR(n,t,r)}}function xI(e,t,n){var r=ys(e),o={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(Jk(e))eR(t,o);else{var i=e.alternate;if(e.lanes===0&&(i===null||i.lanes===0)&&(i=t.lastRenderedReducer,i!==null))try{var s=t.lastRenderedState,l=i(s,n);if(o.hasEagerState=!0,o.eagerState=l,wo(l,s)){var u=t.interleaved;u===null?(o.next=o,$w(t)):(o.next=u.next,u.next=o),t.interleaved=o;return}}catch{}finally{}n=Pk(e,t,o,r),n!==null&&(o=jn(),vo(n,e,r,o),tR(n,t,r))}}function Jk(e){var t=e.alternate;return e===jt||t!==null&&t===jt}function eR(e,t){_u=bh=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function tR(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,fw(e,n)}}var _h={readContext:Yr,useCallback:Cn,useContext:Cn,useEffect:Cn,useImperativeHandle:Cn,useInsertionEffect:Cn,useLayoutEffect:Cn,useMemo:Cn,useReducer:Cn,useRef:Cn,useState:Cn,useDebugValue:Cn,useDeferredValue:Cn,useTransition:Cn,useMutableSource:Cn,useSyncExternalStore:Cn,useId:Cn,unstable_isNewReconciler:!1},bI={readContext:Yr,useCallback:function(e,t){return ko().memoizedState=[e,t===void 0?null:t],e},useContext:Yr,useEffect:$E,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,Pp(4194308,4,Yk.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Pp(4194308,4,e,t)},useInsertionEffect:function(e,t){return Pp(4,2,e,t)},useMemo:function(e,t){var n=ko();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=ko();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=wI.bind(null,jt,e),[r.memoizedState,e]},useRef:function(e){var t=ko();return e={current:e},t.memoizedState=e},useState:CE,useDebugValue:Dw,useDeferredValue:function(e){return ko().memoizedState=e},useTransition:function(){var e=CE(!1),t=e[0];return e=yI.bind(null,e[1]),ko().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=jt,o=ko();if(Dt){if(n===void 0)throw Error(ce(407));n=n()}else{if(n=t(),dn===null)throw Error(ce(349));Sa&30||jk(r,t,n)}o.memoizedState=n;var i={value:n,getSnapshot:t};return o.queue=i,$E(Bk.bind(null,r,i,e),[e]),r.flags|=2048,Ku(9,zk.bind(null,r,i,n,t),void 0,null),n},useId:function(){var e=ko(),t=dn.identifierPrefix;if(Dt){var n=ui,r=ci;n=(r&~(1<<32-go(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=Wu++,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[Oo]=t,e[Bu]=r,uR(e,t,!1,!1),t.stateNode=e;e:{switch(s=Q0(n,r),n){case"dialog":Tt("cancel",e),Tt("close",e),o=r;break;case"iframe":case"object":case"embed":Tt("load",e),o=r;break;case"video":case"audio":for(o=0;oql&&(t.flags|=128,r=!0,eu(i,!1),t.lanes=4194304)}else{if(!r)if(e=xh(s),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),eu(i,!0),i.tail===null&&i.tailMode==="hidden"&&!s.alternate&&!Dt)return $n(t),null}else 2*Xt()-i.renderingStartTime>ql&&n!==1073741824&&(t.flags|=128,r=!0,eu(i,!1),t.lanes=4194304);i.isBackwards?(s.sibling=t.child,t.child=s):(n=i.last,n!==null?n.sibling=s:t.child=s,i.last=s)}return i.tail!==null?(t=i.tail,i.rendering=t,i.tail=t.sibling,i.renderingStartTime=Xt(),t.sibling=null,n=Lt.current,$t(Lt,r?n&1|2:n&1),t):($n(t),null);case 22:case 23:return Bw(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?fr&1073741824&&($n(t),t.subtreeFlags&6&&(t.flags|=8192)):$n(t),null;case 24:return null;case 25:return null}throw Error(ce(156,t.tag))}function TI(e,t){switch(bw(t),t.tag){case 1:return er(t.type)&&ph(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Xl(),At(Jn),At(Tn),Pw(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return Tw(t),null;case 13:if(At(Lt),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(ce(340));Yl()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return At(Lt),null;case 4:return Xl(),null;case 10:return Cw(t.type._context),null;case 22:case 23:return Bw(),null;case 24:return null;default:return null}}var Jf=!1,Rn=!1,PI=typeof WeakSet=="function"?WeakSet:Set,Se=null;function vl(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){Wt(e,t,r)}else n.current=null}function Cy(e,t,n){try{n()}catch(r){Wt(e,t,r)}}var DE=!1;function AI(e,t){if(ly=ch,e=gk(),ww(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 o=r.anchorOffset,i=r.focusNode;r=r.focusOffset;try{n.nodeType,i.nodeType}catch{n=null;break e}var s=0,l=-1,u=-1,d=0,h=0,m=e,g=null;t:for(;;){for(var y;m!==n||o!==0&&m.nodeType!==3||(l=s+o),m!==i||r!==0&&m.nodeType!==3||(u=s+r),m.nodeType===3&&(s+=m.nodeValue.length),(y=m.firstChild)!==null;)g=m,m=y;for(;;){if(m===e)break t;if(g===n&&++d===o&&(l=s),g===i&&++h===r&&(u=s),(y=m.nextSibling)!==null)break;m=g,g=m.parentNode}m=y}n=l===-1||u===-1?null:{start:l,end:u}}else n=null}n=n||{start:0,end:0}}else n=null;for(cy={focusedElem:e,selectionRange:n},ch=!1,Se=t;Se!==null;)if(t=Se,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,Se=e;else for(;Se!==null;){t=Se;try{var x=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(x!==null){var _=x.memoizedProps,C=x.memoizedState,S=t.stateNode,b=S.getSnapshotBeforeUpdate(t.elementType===t.type?_:io(t.type,_),C);S.__reactInternalSnapshotBeforeUpdate=b}break;case 3:var E=t.stateNode.containerInfo;E.nodeType===1?E.textContent="":E.nodeType===9&&E.documentElement&&E.removeChild(E.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(ce(163))}}catch(k){Wt(t,t.return,k)}if(e=t.sibling,e!==null){e.return=t.return,Se=e;break}Se=t.return}return x=DE,DE=!1,x}function Su(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var o=r=r.next;do{if((o.tag&e)===e){var i=o.destroy;o.destroy=void 0,i!==void 0&&Cy(t,n,i)}o=o.next}while(o!==r)}}function ym(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 $y(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 pR(e){var t=e.alternate;t!==null&&(e.alternate=null,pR(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Oo],delete t[Bu],delete t[fy],delete t[pI],delete t[hI])),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 hR(e){return e.tag===5||e.tag===3||e.tag===4}function IE(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||hR(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 ky(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=fh));else if(r!==4&&(e=e.child,e!==null))for(ky(e,t,n),e=e.sibling;e!==null;)ky(e,t,n),e=e.sibling}function Ry(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(Ry(e,t,n),e=e.sibling;e!==null;)Ry(e,t,n),e=e.sibling}var mn=null,lo=!1;function ji(e,t,n){for(n=n.child;n!==null;)mR(e,t,n),n=n.sibling}function mR(e,t,n){if(jo&&typeof jo.onCommitFiberUnmount=="function")try{jo.onCommitFiberUnmount(um,n)}catch{}switch(n.tag){case 5:Rn||vl(n,t);case 6:var r=mn,o=lo;mn=null,ji(e,t,n),mn=r,lo=o,mn!==null&&(lo?(e=mn,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):mn.removeChild(n.stateNode));break;case 18:mn!==null&&(lo?(e=mn,n=n.stateNode,e.nodeType===8?qv(e.parentNode,n):e.nodeType===1&&qv(e,n),Iu(e)):qv(mn,n.stateNode));break;case 4:r=mn,o=lo,mn=n.stateNode.containerInfo,lo=!0,ji(e,t,n),mn=r,lo=o;break;case 0:case 11:case 14:case 15:if(!Rn&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){o=r=r.next;do{var i=o,s=i.destroy;i=i.tag,s!==void 0&&(i&2||i&4)&&Cy(n,t,s),o=o.next}while(o!==r)}ji(e,t,n);break;case 1:if(!Rn&&(vl(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(l){Wt(n,t,l)}ji(e,t,n);break;case 21:ji(e,t,n);break;case 22:n.mode&1?(Rn=(r=Rn)||n.memoizedState!==null,ji(e,t,n),Rn=r):ji(e,t,n);break;default:ji(e,t,n)}}function LE(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new PI),t.forEach(function(r){var o=zI.bind(null,e,r);n.has(r)||(n.add(r),r.then(o,o))})}}function ro(e,t){var n=t.deletions;if(n!==null)for(var r=0;ro&&(o=s),r&=~i}if(r=o,r=Xt()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*MI(r/1960))-r,10e?16:e,os===null)var r=!1;else{if(e=os,os=null,Ch=0,dt&6)throw Error(ce(331));var o=dt;for(dt|=4,Se=e.current;Se!==null;){var i=Se,s=i.child;if(Se.flags&16){var l=i.deletions;if(l!==null){for(var u=0;uXt()-jw?wa(e,0):Fw|=n),tr(e,t)}function SR(e,t){t===0&&(e.mode&1?(t=Wf,Wf<<=1,!(Wf&130023424)&&(Wf=4194304)):t=1);var n=jn();e=gi(e,t),e!==null&&(_d(e,t,n),tr(e,n))}function jI(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),SR(e,n)}function zI(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,o=e.memoizedState;o!==null&&(n=o.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(ce(314))}r!==null&&r.delete(t),SR(e,n)}var ER;ER=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||Jn.current)Qn=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return Qn=!1,kI(e,t,n);Qn=!!(e.flags&131072)}else Qn=!1,Dt&&t.flags&1048576&&kk(t,gh,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;Ap(e,t),e=t.pendingProps;var o=Kl(t,Tn.current);Cl(t,n),o=Ow(null,t,r,e,o,n);var i=Mw();return t.flags|=1,typeof o=="object"&&o!==null&&typeof o.render=="function"&&o.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,er(r)?(i=!0,hh(t)):i=!1,t.memoizedState=o.state!==null&&o.state!==void 0?o.state:null,kw(t),o.updater=gm,t.stateNode=o,o._reactInternals=t,yy(t,r,e,n),t=by(null,t,r,!0,i,n)):(t.tag=0,Dt&&i&&xw(t),Dn(null,t,o,n),t=t.child),t;case 16:r=t.elementType;e:{switch(Ap(e,t),e=t.pendingProps,o=r._init,r=o(r._payload),t.type=r,o=t.tag=UI(r),e=io(r,e),o){case 0:t=xy(null,t,r,e,n);break e;case 1:t=OE(null,t,r,e,n);break e;case 11:t=PE(null,t,r,e,n);break e;case 14:t=AE(null,t,r,io(r.type,e),n);break e}throw Error(ce(306,r,""))}return t;case 0:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),xy(e,t,r,o,n);case 1:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),OE(e,t,r,o,n);case 3:e:{if(aR(t),e===null)throw Error(ce(387));r=t.pendingProps,i=t.memoizedState,o=i.element,Ak(e,t),wh(t,r,null,n);var s=t.memoizedState;if(r=s.element,i.isDehydrated)if(i={element:r,isDehydrated:!1,cache:s.cache,pendingSuspenseBoundaries:s.pendingSuspenseBoundaries,transitions:s.transitions},t.updateQueue.baseState=i,t.memoizedState=i,t.flags&256){o=Zl(Error(ce(423)),t),t=ME(e,t,r,n,o);break e}else if(r!==o){o=Zl(Error(ce(424)),t),t=ME(e,t,r,n,o);break e}else for(mr=ms(t.stateNode.containerInfo.firstChild),gr=t,Dt=!0,po=null,n=Dk(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(Yl(),r===o){t=vi(e,t,n);break e}Dn(e,t,r,n)}t=t.child}return t;case 5:return Ik(t),e===null&&my(t),r=t.type,o=t.pendingProps,i=e!==null?e.memoizedProps:null,s=o.children,uy(r,o)?s=null:i!==null&&uy(r,i)&&(t.flags|=32),sR(e,t),Dn(e,t,s,n),t.child;case 6:return e===null&&my(t),null;case 13:return lR(e,t,n);case 4:return Rw(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=Gl(t,null,r,n):Dn(e,t,r,n),t.child;case 11:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),PE(e,t,r,o,n);case 7:return Dn(e,t,t.pendingProps,n),t.child;case 8:return Dn(e,t,t.pendingProps.children,n),t.child;case 12:return Dn(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,o=t.pendingProps,i=t.memoizedProps,s=o.value,$t(vh,r._currentValue),r._currentValue=s,i!==null)if(wo(i.value,s)){if(i.children===o.children&&!Jn.current){t=vi(e,t,n);break e}}else for(i=t.child,i!==null&&(i.return=t);i!==null;){var l=i.dependencies;if(l!==null){s=i.child;for(var u=l.firstContext;u!==null;){if(u.context===r){if(i.tag===1){u=fi(-1,n&-n),u.tag=2;var d=i.updateQueue;if(d!==null){d=d.shared;var h=d.pending;h===null?u.next=u:(u.next=h.next,h.next=u),d.pending=u}}i.lanes|=n,u=i.alternate,u!==null&&(u.lanes|=n),gy(i.return,n,t),l.lanes|=n;break}u=u.next}}else if(i.tag===10)s=i.type===t.type?null:i.child;else if(i.tag===18){if(s=i.return,s===null)throw Error(ce(341));s.lanes|=n,l=s.alternate,l!==null&&(l.lanes|=n),gy(s,n,t),s=i.sibling}else s=i.child;if(s!==null)s.return=i;else for(s=i;s!==null;){if(s===t){s=null;break}if(i=s.sibling,i!==null){i.return=s.return,s=i;break}s=s.return}i=s}Dn(e,t,o.children,n),t=t.child}return t;case 9:return o=t.type,r=t.pendingProps.children,Cl(t,n),o=Yr(o),r=r(o),t.flags|=1,Dn(e,t,r,n),t.child;case 14:return r=t.type,o=io(r,t.pendingProps),o=io(r.type,o),AE(e,t,r,o,n);case 15:return oR(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),Ap(e,t),t.tag=1,er(r)?(e=!0,hh(t)):e=!1,Cl(t,n),Mk(t,r,o),yy(t,r,o,n),by(null,t,r,!0,e,n);case 19:return cR(e,t,n);case 22:return iR(e,t,n)}throw Error(ce(156,t.tag))};function CR(e,t){return q$(e,t)}function BI(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 Ur(e,t,n,r){return new BI(e,t,n,r)}function Vw(e){return e=e.prototype,!(!e||!e.isReactComponent)}function UI(e){if(typeof e=="function")return Vw(e)?1:0;if(e!=null){if(e=e.$$typeof,e===lw)return 11;if(e===cw)return 14}return 2}function ws(e,t){var n=e.alternate;return n===null?(n=Ur(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 Np(e,t,n,r,o,i){var s=2;if(r=e,typeof e=="function")Vw(e)&&(s=1);else if(typeof e=="string")s=5;else e:switch(e){case ll:return xa(n.children,o,i,t);case aw:s=8,o|=8;break;case U0:return e=Ur(12,n,t,o|2),e.elementType=U0,e.lanes=i,e;case V0:return e=Ur(13,n,t,o),e.elementType=V0,e.lanes=i,e;case W0:return e=Ur(19,n,t,o),e.elementType=W0,e.lanes=i,e;case N$:return xm(n,o,i,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case O$:s=10;break e;case M$:s=9;break e;case lw:s=11;break e;case cw:s=14;break e;case Ki:s=16,r=null;break e}throw Error(ce(130,e==null?e:typeof e,""))}return t=Ur(s,n,t,o),t.elementType=e,t.type=r,t.lanes=i,t}function xa(e,t,n,r){return e=Ur(7,e,r,t),e.lanes=n,e}function xm(e,t,n,r){return e=Ur(22,e,r,t),e.elementType=N$,e.lanes=n,e.stateNode={isHidden:!1},e}function i0(e,t,n){return e=Ur(6,e,null,t),e.lanes=n,e}function s0(e,t,n){return t=Ur(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function VI(e,t,n,r,o){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=zv(0),this.expirationTimes=zv(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=zv(0),this.identifierPrefix=r,this.onRecoverableError=o,this.mutableSourceEagerHydrationData=null}function Ww(e,t,n,r,o,i,s,l,u){return e=new VI(e,t,n,l,u),t===1?(t=1,i===!0&&(t|=8)):t=0,i=Ur(3,null,null,t),e.current=i,i.stateNode=e,i.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},kw(i),e}function WI(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(TR)}catch(e){console.error(e)}}TR(),k$.exports=br;var Os=k$.exports;const XI=lm(Os);var HE=Os;z0.createRoot=HE.createRoot,z0.hydrateRoot=HE.hydrateRoot;var $d=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},Ql=typeof window>"u"||"Deno"in window;function Lr(){}function ZI(e,t){return typeof e=="function"?e(t):e}function My(e){return typeof e=="number"&&e>=0&&e!==1/0}function PR(e,t){return Math.max(e+(t||0)-Date.now(),0)}function KE(e,t){const{type:n="all",exact:r,fetchStatus:o,predicate:i,queryKey:s,stale:l}=e;if(s){if(r){if(t.queryHash!==Gw(s,t.options))return!1}else if(!Xu(t.queryKey,s))return!1}if(n!=="all"){const u=t.isActive();if(n==="active"&&!u||n==="inactive"&&u)return!1}return!(typeof l=="boolean"&&t.isStale()!==l||typeof o<"u"&&o!==t.state.fetchStatus||i&&!i(t))}function YE(e,t){const{exact:n,status:r,predicate:o,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(Gu(t.options.mutationKey)!==Gu(i))return!1}else if(!Xu(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||o&&!o(t))}function Gw(e,t){return((t==null?void 0:t.queryKeyHashFn)||Gu)(e)}function Gu(e){return JSON.stringify(e,(t,n)=>Dy(n)?Object.keys(n).sort().reduce((r,o)=>(r[o]=n[o],r),{}):n)}function Xu(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?!Object.keys(t).some(n=>!Xu(e[n],t[n])):!1}function AR(e,t){if(e===t)return e;const n=GE(e)&&GE(t);if(n||Dy(e)&&Dy(t)){const r=n?e.length:Object.keys(e).length,o=n?t:Object.keys(t),i=o.length,s=n?[]:{};let l=0;for(let u=0;u"u")return!0;const n=t.prototype;return!(!XE(n)||!n.hasOwnProperty("isPrototypeOf"))}function XE(e){return Object.prototype.toString.call(e)==="[object Object]"}function OR(e){return new Promise(t=>{setTimeout(t,e)})}function ZE(e){OR(0).then(e)}function Iy(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?AR(e,t):t}function qI(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function QI(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var ua,Zi,Pl,l$,JI=(l$=class extends $d{constructor(){super();Te(this,ua,void 0);Te(this,Zi,void 0);Te(this,Pl,void 0);ye(this,Pl,t=>{if(!Ql&&window.addEventListener){const n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){z(this,Zi)||this.setEventListener(z(this,Pl))}onUnsubscribe(){var t;this.hasListeners()||((t=z(this,Zi))==null||t.call(this),ye(this,Zi,void 0))}setEventListener(t){var n;ye(this,Pl,t),(n=z(this,Zi))==null||n.call(this),ye(this,Zi,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){z(this,ua)!==t&&(ye(this,ua,t),this.onFocus())}onFocus(){this.listeners.forEach(t=>{t()})}isFocused(){var t;return typeof z(this,ua)=="boolean"?z(this,ua):((t=globalThis.document)==null?void 0:t.visibilityState)!=="hidden"}},ua=new WeakMap,Zi=new WeakMap,Pl=new WeakMap,l$),Rh=new JI,Al,qi,Ol,c$,eL=(c$=class extends $d{constructor(){super();Te(this,Al,!0);Te(this,qi,void 0);Te(this,Ol,void 0);ye(this,Ol,t=>{if(!Ql&&window.addEventListener){const n=()=>t(!0),r=()=>t(!1);return window.addEventListener("online",n,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",r)}}})}onSubscribe(){z(this,qi)||this.setEventListener(z(this,Ol))}onUnsubscribe(){var t;this.hasListeners()||((t=z(this,qi))==null||t.call(this),ye(this,qi,void 0))}setEventListener(t){var n;ye(this,Ol,t),(n=z(this,qi))==null||n.call(this),ye(this,qi,t(this.setOnline.bind(this)))}setOnline(t){z(this,Al)!==t&&(ye(this,Al,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return z(this,Al)}},Al=new WeakMap,qi=new WeakMap,Ol=new WeakMap,c$),Th=new eL;function tL(e){return Math.min(1e3*2**e,3e4)}function Cm(e){return(e??"online")==="online"?Th.isOnline():!0}var MR=class{constructor(e){this.revert=e==null?void 0:e.revert,this.silent=e==null?void 0:e.silent}};function a0(e){return e instanceof MR}function NR(e){let t=!1,n=0,r=!1,o,i,s;const l=new Promise((C,S)=>{i=C,s=S}),u=C=>{var S;r||(y(new MR(C)),(S=e.abort)==null||S.call(e))},d=()=>{t=!0},h=()=>{t=!1},m=()=>!Rh.isFocused()||e.networkMode!=="always"&&!Th.isOnline(),g=C=>{var S;r||(r=!0,(S=e.onSuccess)==null||S.call(e,C),o==null||o(),i(C))},y=C=>{var S;r||(r=!0,(S=e.onError)==null||S.call(e,C),o==null||o(),s(C))},x=()=>new Promise(C=>{var S;o=b=>{const E=r||!m();return E&&C(b),E},(S=e.onPause)==null||S.call(e)}).then(()=>{var C;o=void 0,r||(C=e.onContinue)==null||C.call(e)}),_=()=>{if(r)return;let C;try{C=e.fn()}catch(S){C=Promise.reject(S)}Promise.resolve(C).then(g).catch(S=>{var M;if(r)return;const b=e.retry??(Ql?0:3),E=e.retryDelay??tL,k=typeof E=="function"?E(n,S):E,P=b===!0||typeof b=="number"&&n{if(m())return x()}).then(()=>{t?y(S):_()})})};return Cm(e.networkMode)?_():x().then(_),{promise:l,cancel:u,continue:()=>(o==null?void 0:o())?l:Promise.resolve(),cancelRetry:d,continueRetry:h}}function nL(){let e=[],t=0,n=h=>{h()},r=h=>{h()};const o=h=>{let m;t++;try{m=h()}finally{t--,t||l()}return m},i=h=>{t?e.push(h):ZE(()=>{n(h)})},s=h=>(...m)=>{i(()=>{h(...m)})},l=()=>{const h=e;e=[],h.length&&ZE(()=>{r(()=>{h.forEach(m=>{n(m)})})})};return{batch:o,batchCalls:s,schedule:i,setNotifyFunction:h=>{n=h},setBatchNotifyFunction:h=>{r=h}}}var gn=nL(),da,u$,DR=(u$=class{constructor(){Te(this,da,void 0)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),My(this.gcTime)&&ye(this,da,setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Ql?1/0:5*60*1e3))}clearGcTimeout(){z(this,da)&&(clearTimeout(z(this,da)),ye(this,da,void 0))}},da=new WeakMap,u$),Ml,Nl,Nr,Qi,Dr,cn,ud,fa,Dl,Dp,ao,ii,d$,rL=(d$=class extends DR{constructor(t){super();Te(this,Dl);Te(this,ao);Te(this,Ml,void 0);Te(this,Nl,void 0);Te(this,Nr,void 0);Te(this,Qi,void 0);Te(this,Dr,void 0);Te(this,cn,void 0);Te(this,ud,void 0);Te(this,fa,void 0);ye(this,fa,!1),ye(this,ud,t.defaultOptions),tt(this,Dl,Dp).call(this,t.options),ye(this,cn,[]),ye(this,Nr,t.cache),this.queryKey=t.queryKey,this.queryHash=t.queryHash,ye(this,Ml,t.state||oL(this.options)),this.state=z(this,Ml),this.scheduleGc()}get meta(){return this.options.meta}optionalRemove(){!z(this,cn).length&&this.state.fetchStatus==="idle"&&z(this,Nr).remove(this)}setData(t,n){const r=Iy(this.state.data,t,this.options);return tt(this,ao,ii).call(this,{data:r,type:"success",dataUpdatedAt:n==null?void 0:n.updatedAt,manual:n==null?void 0:n.manual}),r}setState(t,n){tt(this,ao,ii).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){var r;const n=z(this,Qi);return(r=z(this,Dr))==null||r.cancel(t),n?n.then(Lr).catch(Lr):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(z(this,Ml))}isActive(){return z(this,cn).some(t=>t.options.enabled!==!1)}isDisabled(){return this.getObserversCount()>0&&!this.isActive()}isStale(){return this.state.isInvalidated||!this.state.dataUpdatedAt||z(this,cn).some(t=>t.getCurrentResult().isStale)}isStaleByTime(t=0){return this.state.isInvalidated||!this.state.dataUpdatedAt||!PR(this.state.dataUpdatedAt,t)}onFocus(){var n;const t=z(this,cn).find(r=>r.shouldFetchOnWindowFocus());t==null||t.refetch({cancelRefetch:!1}),(n=z(this,Dr))==null||n.continue()}onOnline(){var n;const t=z(this,cn).find(r=>r.shouldFetchOnReconnect());t==null||t.refetch({cancelRefetch:!1}),(n=z(this,Dr))==null||n.continue()}addObserver(t){z(this,cn).includes(t)||(z(this,cn).push(t),this.clearGcTimeout(),z(this,Nr).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){z(this,cn).includes(t)&&(ye(this,cn,z(this,cn).filter(n=>n!==t)),z(this,cn).length||(z(this,Dr)&&(z(this,fa)?z(this,Dr).cancel({revert:!0}):z(this,Dr).cancelRetry()),this.scheduleGc()),z(this,Nr).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return z(this,cn).length}invalidate(){this.state.isInvalidated||tt(this,ao,ii).call(this,{type:"invalidate"})}fetch(t,n){var d,h,m,g;if(this.state.fetchStatus!=="idle"){if(this.state.dataUpdatedAt&&(n!=null&&n.cancelRefetch))this.cancel({silent:!0});else if(z(this,Qi))return(d=z(this,Dr))==null||d.continueRetry(),z(this,Qi)}if(t&&tt(this,Dl,Dp).call(this,t),!this.options.queryFn){const y=z(this,cn).find(x=>x.options.queryFn);y&&tt(this,Dl,Dp).call(this,y.options)}const r=new AbortController,o={queryKey:this.queryKey,meta:this.meta},i=y=>{Object.defineProperty(y,"signal",{enumerable:!0,get:()=>(ye(this,fa,!0),r.signal)})};i(o);const s=()=>this.options.queryFn?(ye(this,fa,!1),this.options.persister?this.options.persister(this.options.queryFn,o,this):this.options.queryFn(o)):Promise.reject(new Error(`Missing queryFn: '${this.options.queryHash}'`)),l={fetchOptions:n,options:this.options,queryKey:this.queryKey,state:this.state,fetchFn:s};i(l),(h=this.options.behavior)==null||h.onFetch(l,this),ye(this,Nl,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((m=l.fetchOptions)==null?void 0:m.meta))&&tt(this,ao,ii).call(this,{type:"fetch",meta:(g=l.fetchOptions)==null?void 0:g.meta});const u=y=>{var x,_,C,S;a0(y)&&y.silent||tt(this,ao,ii).call(this,{type:"error",error:y}),a0(y)||((_=(x=z(this,Nr).config).onError)==null||_.call(x,y,this),(S=(C=z(this,Nr).config).onSettled)==null||S.call(C,this.state.data,y,this)),this.isFetchingOptimistic||this.scheduleGc(),this.isFetchingOptimistic=!1};return ye(this,Dr,NR({fn:l.fetchFn,abort:r.abort.bind(r),onSuccess:y=>{var x,_,C,S;if(typeof y>"u"){u(new Error(`${this.queryHash} data is undefined`));return}this.setData(y),(_=(x=z(this,Nr).config).onSuccess)==null||_.call(x,y,this),(S=(C=z(this,Nr).config).onSettled)==null||S.call(C,y,this.state.error,this),this.isFetchingOptimistic||this.scheduleGc(),this.isFetchingOptimistic=!1},onError:u,onFail:(y,x)=>{tt(this,ao,ii).call(this,{type:"failed",failureCount:y,error:x})},onPause:()=>{tt(this,ao,ii).call(this,{type:"pause"})},onContinue:()=>{tt(this,ao,ii).call(this,{type:"continue"})},retry:l.options.retry,retryDelay:l.options.retryDelay,networkMode:l.options.networkMode})),ye(this,Qi,z(this,Dr).promise),z(this,Qi)}},Ml=new WeakMap,Nl=new WeakMap,Nr=new WeakMap,Qi=new WeakMap,Dr=new WeakMap,cn=new WeakMap,ud=new WeakMap,fa=new WeakMap,Dl=new WeakSet,Dp=function(t){this.options={...z(this,ud),...t},this.updateGcTime(this.options.gcTime)},ao=new WeakSet,ii=function(t){const n=r=>{switch(t.type){case"failed":return{...r,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...r,fetchStatus:"paused"};case"continue":return{...r,fetchStatus:"fetching"};case"fetch":return{...r,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:t.meta??null,fetchStatus:Cm(this.options.networkMode)?"fetching":"paused",...!r.dataUpdatedAt&&{error:null,status:"pending"}};case"success":return{...r,data:t.data,dataUpdateCount:r.dataUpdateCount+1,dataUpdatedAt:t.dataUpdatedAt??Date.now(),error:null,isInvalidated:!1,status:"success",...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};case"error":const o=t.error;return a0(o)&&o.revert&&z(this,Nl)?{...z(this,Nl),fetchStatus:"idle"}:{...r,error:o,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:o,fetchStatus:"idle",status:"error"};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...t.state}}};this.state=n(this.state),gn.batch(()=>{z(this,cn).forEach(r=>{r.onQueryUpdate()}),z(this,Nr).notify({query:this,type:"updated",action:t})})},d$);function oL(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=typeof t<"u",r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var Ro,f$,iL=(f$=class extends $d{constructor(t={}){super();Te(this,Ro,void 0);this.config=t,ye(this,Ro,new Map)}build(t,n,r){const o=n.queryKey,i=n.queryHash??Gw(o,n);let s=this.get(i);return s||(s=new rL({cache:this,queryKey:o,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(o)}),this.add(s)),s}add(t){z(this,Ro).has(t.queryHash)||(z(this,Ro).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){const n=z(this,Ro).get(t.queryHash);n&&(t.destroy(),n===t&&z(this,Ro).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){gn.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return z(this,Ro).get(t)}getAll(){return[...z(this,Ro).values()]}find(t){const n={exact:!0,...t};return this.getAll().find(r=>KE(n,r))}findAll(t={}){const n=this.getAll();return Object.keys(t).length>0?n.filter(r=>KE(t,r)):n}notify(t){gn.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){gn.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){gn.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},Ro=new WeakMap,f$),To,dd,dr,Il,Po,Wi,p$,sL=(p$=class extends DR{constructor(t){super();Te(this,Po);Te(this,To,void 0);Te(this,dd,void 0);Te(this,dr,void 0);Te(this,Il,void 0);this.mutationId=t.mutationId,ye(this,dd,t.defaultOptions),ye(this,dr,t.mutationCache),ye(this,To,[]),this.state=t.state||aL(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options={...z(this,dd),...t},this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){z(this,To).includes(t)||(z(this,To).push(t),this.clearGcTimeout(),z(this,dr).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){ye(this,To,z(this,To).filter(n=>n!==t)),this.scheduleGc(),z(this,dr).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){z(this,To).length||(this.state.status==="pending"?this.scheduleGc():z(this,dr).remove(this))}continue(){var t;return((t=z(this,Il))==null?void 0:t.continue())??this.execute(this.state.variables)}async execute(t){var o,i,s,l,u,d,h,m,g,y,x,_,C,S,b,E,k,P,M,A;const n=()=>(ye(this,Il,NR({fn:()=>this.options.mutationFn?this.options.mutationFn(t):Promise.reject(new Error("No mutationFn found")),onFail:(O,F)=>{tt(this,Po,Wi).call(this,{type:"failed",failureCount:O,error:F})},onPause:()=>{tt(this,Po,Wi).call(this,{type:"pause"})},onContinue:()=>{tt(this,Po,Wi).call(this,{type:"continue"})},retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode})),z(this,Il).promise),r=this.state.status==="pending";try{if(!r){tt(this,Po,Wi).call(this,{type:"pending",variables:t}),await((i=(o=z(this,dr).config).onMutate)==null?void 0:i.call(o,t,this));const F=await((l=(s=this.options).onMutate)==null?void 0:l.call(s,t));F!==this.state.context&&tt(this,Po,Wi).call(this,{type:"pending",context:F,variables:t})}const O=await n();return await((d=(u=z(this,dr).config).onSuccess)==null?void 0:d.call(u,O,t,this.state.context,this)),await((m=(h=this.options).onSuccess)==null?void 0:m.call(h,O,t,this.state.context)),await((y=(g=z(this,dr).config).onSettled)==null?void 0:y.call(g,O,null,this.state.variables,this.state.context,this)),await((_=(x=this.options).onSettled)==null?void 0:_.call(x,O,null,t,this.state.context)),tt(this,Po,Wi).call(this,{type:"success",data:O}),O}catch(O){try{throw await((S=(C=z(this,dr).config).onError)==null?void 0:S.call(C,O,t,this.state.context,this)),await((E=(b=this.options).onError)==null?void 0:E.call(b,O,t,this.state.context)),await((P=(k=z(this,dr).config).onSettled)==null?void 0:P.call(k,void 0,O,this.state.variables,this.state.context,this)),await((A=(M=this.options).onSettled)==null?void 0:A.call(M,void 0,O,t,this.state.context)),O}finally{tt(this,Po,Wi).call(this,{type:"error",error:O})}}}},To=new WeakMap,dd=new WeakMap,dr=new WeakMap,Il=new WeakMap,Po=new WeakSet,Wi=function(t){const n=r=>{switch(t.type){case"failed":return{...r,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};case"pending":return{...r,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:!Cm(this.options.networkMode),status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...r,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:t.error,failureCount:r.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}};this.state=n(this.state),gn.batch(()=>{z(this,To).forEach(r=>{r.onMutationUpdate(t)}),z(this,dr).notify({mutation:this,type:"updated",action:t})})},p$);function aL(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Ir,fd,pa,h$,lL=(h$=class extends $d{constructor(t={}){super();Te(this,Ir,void 0);Te(this,fd,void 0);Te(this,pa,void 0);this.config=t,ye(this,Ir,[]),ye(this,fd,0)}build(t,n,r){const o=new sL({mutationCache:this,mutationId:++Ff(this,fd)._,options:t.defaultMutationOptions(n),state:r});return this.add(o),o}add(t){z(this,Ir).push(t),this.notify({type:"added",mutation:t})}remove(t){ye(this,Ir,z(this,Ir).filter(n=>n!==t)),this.notify({type:"removed",mutation:t})}clear(){gn.batch(()=>{z(this,Ir).forEach(t=>{this.remove(t)})})}getAll(){return z(this,Ir)}find(t){const n={exact:!0,...t};return z(this,Ir).find(r=>YE(n,r))}findAll(t={}){return z(this,Ir).filter(n=>YE(t,n))}notify(t){gn.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){return ye(this,pa,(z(this,pa)??Promise.resolve()).then(()=>{const t=z(this,Ir).filter(n=>n.state.isPaused);return gn.batch(()=>t.reduce((n,r)=>n.then(()=>r.continue().catch(Lr)),Promise.resolve()))}).then(()=>{ye(this,pa,void 0)})),z(this,pa)}},Ir=new WeakMap,fd=new WeakMap,pa=new WeakMap,h$);function cL(e){return{onFetch:(t,n)=>{const r=async()=>{var x,_,C,S,b;const o=t.options,i=(C=(_=(x=t.fetchOptions)==null?void 0:x.meta)==null?void 0:_.fetchMore)==null?void 0:C.direction,s=((S=t.state.data)==null?void 0:S.pages)||[],l=((b=t.state.data)==null?void 0:b.pageParams)||[],u={pages:[],pageParams:[]};let d=!1;const h=E=>{Object.defineProperty(E,"signal",{enumerable:!0,get:()=>(t.signal.aborted?d=!0:t.signal.addEventListener("abort",()=>{d=!0}),t.signal)})},m=t.options.queryFn||(()=>Promise.reject(new Error(`Missing queryFn: '${t.options.queryHash}'`))),g=async(E,k,P)=>{if(d)return Promise.reject();if(k==null&&E.pages.length)return Promise.resolve(E);const M={queryKey:t.queryKey,pageParam:k,direction:P?"backward":"forward",meta:t.options.meta};h(M);const A=await m(M),{maxPages:O}=t.options,F=P?QI:qI;return{pages:F(E.pages,A,O),pageParams:F(E.pageParams,k,O)}};let y;if(i&&s.length){const E=i==="backward",k=E?uL:qE,P={pages:s,pageParams:l},M=k(o,P);y=await g(P,M,E)}else{y=await g(u,l[0]??o.initialPageParam);const E=e??s.length;for(let k=1;k{var o,i;return(i=(o=t.options).persister)==null?void 0:i.call(o,r,{queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n)}:t.fetchFn=r}}}function qE(e,{pages:t,pageParams:n}){const r=t.length-1;return e.getNextPageParam(t[r],t,n[r],n)}function uL(e,{pages:t,pageParams:n}){var r;return(r=e.getPreviousPageParam)==null?void 0:r.call(e,t[0],t,n[0],n)}var nn,Ji,es,Ll,Fl,ts,jl,zl,m$,dL=(m$=class{constructor(e={}){Te(this,nn,void 0);Te(this,Ji,void 0);Te(this,es,void 0);Te(this,Ll,void 0);Te(this,Fl,void 0);Te(this,ts,void 0);Te(this,jl,void 0);Te(this,zl,void 0);ye(this,nn,e.queryCache||new iL),ye(this,Ji,e.mutationCache||new lL),ye(this,es,e.defaultOptions||{}),ye(this,Ll,new Map),ye(this,Fl,new Map),ye(this,ts,0)}mount(){Ff(this,ts)._++,z(this,ts)===1&&(ye(this,jl,Rh.subscribe(()=>{Rh.isFocused()&&(this.resumePausedMutations(),z(this,nn).onFocus())})),ye(this,zl,Th.subscribe(()=>{Th.isOnline()&&(this.resumePausedMutations(),z(this,nn).onOnline())})))}unmount(){var e,t;Ff(this,ts)._--,z(this,ts)===0&&((e=z(this,jl))==null||e.call(this),ye(this,jl,void 0),(t=z(this,zl))==null||t.call(this),ye(this,zl,void 0))}isFetching(e){return z(this,nn).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return z(this,Ji).findAll({...e,status:"pending"}).length}getQueryData(e){var t;return(t=z(this,nn).find({queryKey:e}))==null?void 0:t.state.data}ensureQueryData(e){const t=this.getQueryData(e.queryKey);return t!==void 0?Promise.resolve(t):this.fetchQuery(e)}getQueriesData(e){return this.getQueryCache().findAll(e).map(({queryKey:t,state:n})=>{const r=n.data;return[t,r]})}setQueryData(e,t,n){const r=z(this,nn).find({queryKey:e}),o=r==null?void 0:r.state.data,i=ZI(t,o);if(typeof i>"u")return;const s=this.defaultQueryOptions({queryKey:e});return z(this,nn).build(this,s).setData(i,{...n,manual:!0})}setQueriesData(e,t,n){return gn.batch(()=>this.getQueryCache().findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){var t;return(t=z(this,nn).find({queryKey:e}))==null?void 0:t.state}removeQueries(e){const t=z(this,nn);gn.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=z(this,nn),r={type:"active",...e};return gn.batch(()=>(n.findAll(e).forEach(o=>{o.reset()}),this.refetchQueries(r,t)))}cancelQueries(e={},t={}){const n={revert:!0,...t},r=gn.batch(()=>z(this,nn).findAll(e).map(o=>o.cancel(n)));return Promise.all(r).then(Lr).catch(Lr)}invalidateQueries(e={},t={}){return gn.batch(()=>{if(z(this,nn).findAll(e).forEach(r=>{r.invalidate()}),e.refetchType==="none")return Promise.resolve();const n={...e,type:e.refetchType??e.type??"active"};return this.refetchQueries(n,t)})}refetchQueries(e={},t){const n={...t,cancelRefetch:(t==null?void 0:t.cancelRefetch)??!0},r=gn.batch(()=>z(this,nn).findAll(e).filter(o=>!o.isDisabled()).map(o=>{let i=o.fetch(void 0,n);return n.throwOnError||(i=i.catch(Lr)),o.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(Lr)}fetchQuery(e){const t=this.defaultQueryOptions(e);typeof t.retry>"u"&&(t.retry=!1);const n=z(this,nn).build(this,t);return n.isStaleByTime(t.staleTime)?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Lr).catch(Lr)}fetchInfiniteQuery(e){return e.behavior=cL(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Lr).catch(Lr)}resumePausedMutations(){return z(this,Ji).resumePausedMutations()}getQueryCache(){return z(this,nn)}getMutationCache(){return z(this,Ji)}getDefaultOptions(){return z(this,es)}setDefaultOptions(e){ye(this,es,e)}setQueryDefaults(e,t){z(this,Ll).set(Gu(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...z(this,Ll).values()];let n={};return t.forEach(r=>{Xu(e,r.queryKey)&&(n={...n,...r.defaultOptions})}),n}setMutationDefaults(e,t){z(this,Fl).set(Gu(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...z(this,Fl).values()];let n={};return t.forEach(r=>{Xu(e,r.mutationKey)&&(n={...n,...r.defaultOptions})}),n}defaultQueryOptions(e){if(e!=null&&e._defaulted)return e;const t={...z(this,es).queries,...(e==null?void 0:e.queryKey)&&this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Gw(t.queryKey,t)),typeof t.refetchOnReconnect>"u"&&(t.refetchOnReconnect=t.networkMode!=="always"),typeof t.throwOnError>"u"&&(t.throwOnError=!!t.suspense),typeof t.networkMode>"u"&&t.persister&&(t.networkMode="offlineFirst"),t}defaultMutationOptions(e){return e!=null&&e._defaulted?e:{...z(this,es).mutations,...(e==null?void 0:e.mutationKey)&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){z(this,nn).clear(),z(this,Ji).clear()}},nn=new WeakMap,Ji=new WeakMap,es=new WeakMap,Ll=new WeakMap,Fl=new WeakMap,ts=new WeakMap,jl=new WeakMap,zl=new WeakMap,m$),Xn,Ct,Bl,kn,ha,Ul,Ao,pd,Vl,Wl,ma,ga,ns,va,ya,hu,hd,Ly,md,Fy,gd,jy,vd,zy,yd,By,wd,Uy,xd,Vy,am,IR,g$,fL=(g$=class extends $d{constructor(t,n){super();Te(this,ya);Te(this,hd);Te(this,md);Te(this,gd);Te(this,vd);Te(this,yd);Te(this,wd);Te(this,xd);Te(this,am);Te(this,Xn,void 0);Te(this,Ct,void 0);Te(this,Bl,void 0);Te(this,kn,void 0);Te(this,ha,void 0);Te(this,Ul,void 0);Te(this,Ao,void 0);Te(this,pd,void 0);Te(this,Vl,void 0);Te(this,Wl,void 0);Te(this,ma,void 0);Te(this,ga,void 0);Te(this,ns,void 0);Te(this,va,void 0);ye(this,Ct,void 0),ye(this,Bl,void 0),ye(this,kn,void 0),ye(this,va,new Set),ye(this,Xn,t),this.options=n,ye(this,Ao,null),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(z(this,Ct).addObserver(this),QE(z(this,Ct),this.options)?tt(this,ya,hu).call(this):this.updateResult(),tt(this,vd,zy).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Wy(z(this,Ct),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Wy(z(this,Ct),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,tt(this,yd,By).call(this),tt(this,wd,Uy).call(this),z(this,Ct).removeObserver(this)}setOptions(t,n){const r=this.options,o=z(this,Ct);if(this.options=z(this,Xn).defaultQueryOptions(t),Ny(r,this.options)||z(this,Xn).getQueryCache().notify({type:"observerOptionsUpdated",query:z(this,Ct),observer:this}),typeof this.options.enabled<"u"&&typeof this.options.enabled!="boolean")throw new Error("Expected enabled to be a boolean");this.options.queryKey||(this.options.queryKey=r.queryKey),tt(this,xd,Vy).call(this);const i=this.hasListeners();i&&JE(z(this,Ct),o,this.options,r)&&tt(this,ya,hu).call(this),this.updateResult(n),i&&(z(this,Ct)!==o||this.options.enabled!==r.enabled||this.options.staleTime!==r.staleTime)&&tt(this,hd,Ly).call(this);const s=tt(this,md,Fy).call(this);i&&(z(this,Ct)!==o||this.options.enabled!==r.enabled||s!==z(this,ns))&&tt(this,gd,jy).call(this,s)}getOptimisticResult(t){const n=z(this,Xn).getQueryCache().build(z(this,Xn),t),r=this.createResult(n,t);return hL(this,r)&&(ye(this,kn,r),ye(this,Ul,this.options),ye(this,ha,z(this,Ct).state)),r}getCurrentResult(){return z(this,kn)}trackResult(t){const n={};return Object.keys(t).forEach(r=>{Object.defineProperty(n,r,{configurable:!1,enumerable:!0,get:()=>(z(this,va).add(r),t[r])})}),n}getCurrentQuery(){return z(this,Ct)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){const n=z(this,Xn).defaultQueryOptions(t),r=z(this,Xn).getQueryCache().build(z(this,Xn),n);return r.isFetchingOptimistic=!0,r.fetch().then(()=>this.createResult(r,n))}fetch(t){return tt(this,ya,hu).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),z(this,kn)))}createResult(t,n){var M;const r=z(this,Ct),o=this.options,i=z(this,kn),s=z(this,ha),l=z(this,Ul),d=t!==r?t.state:z(this,Bl),{state:h}=t;let{error:m,errorUpdatedAt:g,fetchStatus:y,status:x}=h,_=!1,C;if(n._optimisticResults){const A=this.hasListeners(),O=!A&&QE(t,n),F=A&&JE(t,r,n,o);(O||F)&&(y=Cm(t.options.networkMode)?"fetching":"paused",h.dataUpdatedAt||(x="pending")),n._optimisticResults==="isRestoring"&&(y="idle")}if(n.select&&typeof h.data<"u")if(i&&h.data===(s==null?void 0:s.data)&&n.select===z(this,pd))C=z(this,Vl);else try{ye(this,pd,n.select),C=n.select(h.data),C=Iy(i==null?void 0:i.data,C,n),ye(this,Vl,C),ye(this,Ao,null)}catch(A){ye(this,Ao,A)}else C=h.data;if(typeof n.placeholderData<"u"&&typeof C>"u"&&x==="pending"){let A;if(i!=null&&i.isPlaceholderData&&n.placeholderData===(l==null?void 0:l.placeholderData))A=i.data;else if(A=typeof n.placeholderData=="function"?n.placeholderData((M=z(this,Wl))==null?void 0:M.state.data,z(this,Wl)):n.placeholderData,n.select&&typeof A<"u")try{A=n.select(A),ye(this,Ao,null)}catch(O){ye(this,Ao,O)}typeof A<"u"&&(x="success",C=Iy(i==null?void 0:i.data,A,n),_=!0)}z(this,Ao)&&(m=z(this,Ao),C=z(this,Vl),g=Date.now(),x="error");const S=y==="fetching",b=x==="pending",E=x==="error",k=b&&S;return{status:x,fetchStatus:y,isPending:b,isSuccess:x==="success",isError:E,isInitialLoading:k,isLoading:k,data:C,dataUpdatedAt:h.dataUpdatedAt,error:m,errorUpdatedAt:g,failureCount:h.fetchFailureCount,failureReason:h.fetchFailureReason,errorUpdateCount:h.errorUpdateCount,isFetched:h.dataUpdateCount>0||h.errorUpdateCount>0,isFetchedAfterMount:h.dataUpdateCount>d.dataUpdateCount||h.errorUpdateCount>d.errorUpdateCount,isFetching:S,isRefetching:S&&!b,isLoadingError:E&&h.dataUpdatedAt===0,isPaused:y==="paused",isPlaceholderData:_,isRefetchError:E&&h.dataUpdatedAt!==0,isStale:Xw(t,n),refetch:this.refetch}}updateResult(t){const n=z(this,kn),r=this.createResult(z(this,Ct),this.options);if(ye(this,ha,z(this,Ct).state),ye(this,Ul,this.options),z(this,ha).data!==void 0&&ye(this,Wl,z(this,Ct)),Ny(r,n))return;ye(this,kn,r);const o={},i=()=>{if(!n)return!0;const{notifyOnChangeProps:s}=this.options,l=typeof s=="function"?s():s;if(l==="all"||!l&&!z(this,va).size)return!0;const u=new Set(l??z(this,va));return this.options.throwOnError&&u.add("error"),Object.keys(z(this,kn)).some(d=>{const h=d;return z(this,kn)[h]!==n[h]&&u.has(h)})};(t==null?void 0:t.listeners)!==!1&&i()&&(o.listeners=!0),tt(this,am,IR).call(this,{...o,...t})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&tt(this,vd,zy).call(this)}},Xn=new WeakMap,Ct=new WeakMap,Bl=new WeakMap,kn=new WeakMap,ha=new WeakMap,Ul=new WeakMap,Ao=new WeakMap,pd=new WeakMap,Vl=new WeakMap,Wl=new WeakMap,ma=new WeakMap,ga=new WeakMap,ns=new WeakMap,va=new WeakMap,ya=new WeakSet,hu=function(t){tt(this,xd,Vy).call(this);let n=z(this,Ct).fetch(this.options,t);return t!=null&&t.throwOnError||(n=n.catch(Lr)),n},hd=new WeakSet,Ly=function(){if(tt(this,yd,By).call(this),Ql||z(this,kn).isStale||!My(this.options.staleTime))return;const n=PR(z(this,kn).dataUpdatedAt,this.options.staleTime)+1;ye(this,ma,setTimeout(()=>{z(this,kn).isStale||this.updateResult()},n))},md=new WeakSet,Fy=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(z(this,Ct)):this.options.refetchInterval)??!1},gd=new WeakSet,jy=function(t){tt(this,wd,Uy).call(this),ye(this,ns,t),!(Ql||this.options.enabled===!1||!My(z(this,ns))||z(this,ns)===0)&&ye(this,ga,setInterval(()=>{(this.options.refetchIntervalInBackground||Rh.isFocused())&&tt(this,ya,hu).call(this)},z(this,ns)))},vd=new WeakSet,zy=function(){tt(this,hd,Ly).call(this),tt(this,gd,jy).call(this,tt(this,md,Fy).call(this))},yd=new WeakSet,By=function(){z(this,ma)&&(clearTimeout(z(this,ma)),ye(this,ma,void 0))},wd=new WeakSet,Uy=function(){z(this,ga)&&(clearInterval(z(this,ga)),ye(this,ga,void 0))},xd=new WeakSet,Vy=function(){const t=z(this,Xn).getQueryCache().build(z(this,Xn),this.options);if(t===z(this,Ct))return;const n=z(this,Ct);ye(this,Ct,t),ye(this,Bl,t.state),this.hasListeners()&&(n==null||n.removeObserver(this),t.addObserver(this))},am=new WeakSet,IR=function(t){gn.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(z(this,kn))}),z(this,Xn).getQueryCache().notify({query:z(this,Ct),type:"observerResultsUpdated"})})},g$);function pL(e,t){return t.enabled!==!1&&!e.state.dataUpdatedAt&&!(e.state.status==="error"&&t.retryOnMount===!1)}function QE(e,t){return pL(e,t)||e.state.dataUpdatedAt>0&&Wy(e,t,t.refetchOnMount)}function Wy(e,t,n){if(t.enabled!==!1){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&Xw(e,t)}return!1}function JE(e,t,n,r){return n.enabled!==!1&&(e!==t||r.enabled===!1)&&(!n.suspense||e.state.status!=="error")&&Xw(e,n)}function Xw(e,t){return e.isStaleByTime(t.staleTime)}function hL(e,t){return!Ny(e.getCurrentResult(),t)}var LR=f.createContext(void 0),mL=e=>{const t=f.useContext(LR);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},gL=({client:e,children:t})=>(f.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),f.createElement(LR.Provider,{value:e},t)),FR=f.createContext(!1),vL=()=>f.useContext(FR);FR.Provider;function yL(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var wL=f.createContext(yL()),xL=()=>f.useContext(wL);function bL(e,t){return typeof e=="function"?e(...t):!!e}var _L=(e,t)=>{(e.suspense||e.throwOnError)&&(t.isReset()||(e.retryOnMount=!1))},SL=e=>{f.useEffect(()=>{e.clearReset()},[e])},EL=({result:e,errorResetBoundary:t,throwOnError:n,query:r})=>e.isError&&!t.isReset()&&!e.isFetching&&bL(n,[e.error,r]),CL=e=>{e.suspense&&typeof e.staleTime!="number"&&(e.staleTime=1e3)},$L=(e,t)=>(e==null?void 0:e.suspense)&&t.isPending,kL=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function RL(e,t,n){const r=mL(n),o=vL(),i=xL(),s=r.defaultQueryOptions(e);s._optimisticResults=o?"isRestoring":"optimistic",CL(s),_L(s,i),SL(i);const[l]=f.useState(()=>new t(r,s)),u=l.getOptimisticResult(s);if(f.useSyncExternalStore(f.useCallback(d=>{const h=o?()=>{}:l.subscribe(gn.batchCalls(d));return l.updateResult(),h},[l,o]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),f.useEffect(()=>{l.setOptions(s,{listeners:!1})},[s,l]),$L(s,u))throw l.setOptions(s,{listeners:!1}),kL(s,l,i);if(EL({result:u,errorResetBoundary:i,throwOnError:s.throwOnError,query:l.getCurrentQuery()}))throw u.error;return s.notifyOnChangeProps?u:l.trackResult(u)}function TL(e,t){return RL(e,fL,t)}var jR=(e=>(e.RemoveBG="RemoveBG",e.AnimeSeg="AnimeSeg",e.RealESRGAN="RealESRGAN",e.GFPGAN="GFPGAN",e.RestoreFormer="RestoreFormer",e.InteractiveSeg="InteractiveSeg",e))(jR||{}),xs=(e=>(e.NAME="name",e.CTIME="ctime",e.MTIME="mtime",e))(xs||{}),$u=(e=>(e.DESCENDING="desc",e.ASCENDING="asc",e))($u||{}),Zw=(e=>(e.ddim="ddim",e.plms="plms",e))(Zw||{}),qw=(e=>(e.INPAINT_NS="INPAINT_NS",e.INPAINT_TELEA="INPAINT_TELEA",e))(qw||{}),In=(e=>(e.x="x",e.y="y",e.xy="xy",e))(In||{}),kl=(e=>(e.text_guided="text-guided",e.shape_guided="shape-guided",e.object_remove="object-remove",e.outpainting="outpainting",e))(kl||{});function zR(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;tl(i)))==null?void 0:s.classGroupId}const eC=/^\[(.+)\]$/;function AL(e){if(eC.test(e)){const t=eC.exec(e)[1],n=t==null?void 0:t.substring(0,t.indexOf(":"));if(n)return"arbitrary.."+n}}function OL(e){const{theme:t,prefix:n}=e,r={nextPart:new Map,validators:[]};return NL(Object.entries(e.classGroups),n).forEach(([i,s])=>{Hy(s,r,i,t)}),r}function Hy(e,t,n,r){e.forEach(o=>{if(typeof o=="string"){const i=o===""?t:tC(t,o);i.classGroupId=n;return}if(typeof o=="function"){if(ML(o)){Hy(o(r),t,n,r);return}t.validators.push({validator:o,classGroupId:n});return}Object.entries(o).forEach(([i,s])=>{Hy(s,tC(t,i),n,r)})})}function tC(e,t){let n=e;return t.split(Qw).forEach(r=>{n.nextPart.has(r)||n.nextPart.set(r,{nextPart:new Map,validators:[]}),n=n.nextPart.get(r)}),n}function ML(e){return e.isThemeGetter}function NL(e,t){return t?e.map(([n,r])=>{const o=r.map(i=>typeof i=="string"?t+i:typeof i=="object"?Object.fromEntries(Object.entries(i).map(([s,l])=>[t+s,l])):i);return[n,o]}):e}function DL(e){if(e<1)return{get:()=>{},set:()=>{}};let t=0,n=new Map,r=new Map;function o(i,s){n.set(i,s),t++,t>e&&(t=0,r=n,n=new Map)}return{get(i){let s=n.get(i);if(s!==void 0)return s;if((s=r.get(i))!==void 0)return o(i,s),s},set(i,s){n.has(i)?n.set(i,s):o(i,s)}}}const VR="!";function IL(e){const t=e.separator,n=t.length===1,r=t[0],o=t.length;return function(s){const l=[];let u=0,d=0,h;for(let _=0;_d?h-d:void 0;return{modifiers:l,hasImportantModifier:g,baseClassName:y,maybePostfixModifierPosition:x}}}function LL(e){if(e.length<=1)return e;const t=[];let n=[];return e.forEach(r=>{r[0]==="["?(t.push(...n.sort(),r),n=[]):n.push(r)}),t.push(...n.sort()),t}function FL(e){return{cache:DL(e.cacheSize),splitModifiers:IL(e),...PL(e)}}const jL=/\s+/;function zL(e,t){const{splitModifiers:n,getClassGroupId:r,getConflictingClassGroupIds:o}=t,i=new Set;return e.trim().split(jL).map(s=>{const{modifiers:l,hasImportantModifier:u,baseClassName:d,maybePostfixModifierPosition:h}=n(s);let m=r(h?d.substring(0,h):d),g=!!h;if(!m){if(!h)return{isTailwindClass:!1,originalClassName:s};if(m=r(d),!m)return{isTailwindClass:!1,originalClassName:s};g=!1}const y=LL(l).join(":");return{isTailwindClass:!0,modifierId:u?y+VR:y,classGroupId:m,originalClassName:s,hasPostfixModifier:g}}).reverse().filter(s=>{if(!s.isTailwindClass)return!0;const{modifierId:l,classGroupId:u,hasPostfixModifier:d}=s,h=l+u;return i.has(h)?!1:(i.add(h),o(u,d).forEach(m=>i.add(l+m)),!0)}).reverse().map(s=>s.originalClassName).join(" ")}function BL(){let e=0,t,n,r="";for(;em(h),e());return n=FL(d),r=n.cache.get,o=n.cache.set,i=l,l(u)}function l(u){const d=r(u);if(d)return d;const h=zL(u,n);return o(u,h),h}return function(){return i(BL.apply(null,arguments))}}function Rt(e){const t=n=>n[e]||[];return t.isThemeGetter=!0,t}const HR=/^\[(?:([a-z-]+):)?(.+)\]$/i,VL=/^\d+\/\d+$/,WL=new Set(["px","full","screen"]),HL=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,KL=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,YL=/^-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,GL=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/;function oo(e){return ia(e)||WL.has(e)||VL.test(e)}function zi(e){return mc(e,"length",nF)}function ia(e){return!!e&&!Number.isNaN(Number(e))}function np(e){return mc(e,"number",ia)}function nu(e){return!!e&&Number.isInteger(Number(e))}function XL(e){return e.endsWith("%")&&ia(e.slice(0,-1))}function Je(e){return HR.test(e)}function Bi(e){return HL.test(e)}const ZL=new Set(["length","size","percentage"]);function qL(e){return mc(e,ZL,KR)}function QL(e){return mc(e,"position",KR)}const JL=new Set(["image","url"]);function eF(e){return mc(e,JL,oF)}function tF(e){return mc(e,"",rF)}function ru(){return!0}function mc(e,t,n){const r=HR.exec(e);return r?r[1]?typeof t=="string"?r[1]===t:t.has(r[1]):n(r[2]):!1}function nF(e){return KL.test(e)}function KR(){return!1}function rF(e){return YL.test(e)}function oF(e){return GL.test(e)}function iF(){const e=Rt("colors"),t=Rt("spacing"),n=Rt("blur"),r=Rt("brightness"),o=Rt("borderColor"),i=Rt("borderRadius"),s=Rt("borderSpacing"),l=Rt("borderWidth"),u=Rt("contrast"),d=Rt("grayscale"),h=Rt("hueRotate"),m=Rt("invert"),g=Rt("gap"),y=Rt("gradientColorStops"),x=Rt("gradientColorStopPositions"),_=Rt("inset"),C=Rt("margin"),S=Rt("opacity"),b=Rt("padding"),E=Rt("saturate"),k=Rt("scale"),P=Rt("sepia"),M=Rt("skew"),A=Rt("space"),O=Rt("translate"),F=()=>["auto","contain","none"],V=()=>["auto","hidden","clip","visible","scroll"],J=()=>["auto",Je,t],G=()=>[Je,t],ae=()=>["",oo,zi],U=()=>["auto",ia,Je],te=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],L=()=>["solid","dashed","dotted","double","none"],ie=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity","plus-lighter"],K=()=>["start","end","center","between","around","evenly","stretch"],Q=()=>["","0",Je],W=()=>["auto","avoid","all","avoid-page","page","left","right","column"],le=()=>[ia,np],ge=()=>[ia,Je];return{cacheSize:500,separator:":",theme:{colors:[ru],spacing:[oo,zi],blur:["none","",Bi,Je],brightness:le(),borderColor:[e],borderRadius:["none","","full",Bi,Je],borderSpacing:G(),borderWidth:ae(),contrast:le(),grayscale:Q(),hueRotate:ge(),invert:Q(),gap:G(),gradientColorStops:[e],gradientColorStopPositions:[XL,zi],inset:J(),margin:J(),opacity:le(),padding:G(),saturate:le(),scale:le(),sepia:Q(),skew:ge(),space:G(),translate:G()},classGroups:{aspect:[{aspect:["auto","square","video",Je]}],container:["container"],columns:[{columns:[Bi]}],"break-after":[{"break-after":W()}],"break-before":[{"break-before":W()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],float:[{float:["right","left","none"]}],clear:[{clear:["left","right","both","none"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:[...te(),Je]}],overflow:[{overflow:V()}],"overflow-x":[{"overflow-x":V()}],"overflow-y":[{"overflow-y":V()}],overscroll:[{overscroll:F()}],"overscroll-x":[{"overscroll-x":F()}],"overscroll-y":[{"overscroll-y":F()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[_]}],"inset-x":[{"inset-x":[_]}],"inset-y":[{"inset-y":[_]}],start:[{start:[_]}],end:[{end:[_]}],top:[{top:[_]}],right:[{right:[_]}],bottom:[{bottom:[_]}],left:[{left:[_]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",nu,Je]}],basis:[{basis:J()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",Je]}],grow:[{grow:Q()}],shrink:[{shrink:Q()}],order:[{order:["first","last","none",nu,Je]}],"grid-cols":[{"grid-cols":[ru]}],"col-start-end":[{col:["auto",{span:["full",nu,Je]},Je]}],"col-start":[{"col-start":U()}],"col-end":[{"col-end":U()}],"grid-rows":[{"grid-rows":[ru]}],"row-start-end":[{row:["auto",{span:[nu,Je]},Je]}],"row-start":[{"row-start":U()}],"row-end":[{"row-end":U()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",Je]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",Je]}],gap:[{gap:[g]}],"gap-x":[{"gap-x":[g]}],"gap-y":[{"gap-y":[g]}],"justify-content":[{justify:["normal",...K()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...K(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...K(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[b]}],px:[{px:[b]}],py:[{py:[b]}],ps:[{ps:[b]}],pe:[{pe:[b]}],pt:[{pt:[b]}],pr:[{pr:[b]}],pb:[{pb:[b]}],pl:[{pl:[b]}],m:[{m:[C]}],mx:[{mx:[C]}],my:[{my:[C]}],ms:[{ms:[C]}],me:[{me:[C]}],mt:[{mt:[C]}],mr:[{mr:[C]}],mb:[{mb:[C]}],ml:[{ml:[C]}],"space-x":[{"space-x":[A]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[A]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit",Je,t]}],"min-w":[{"min-w":["min","max","fit",Je,oo]}],"max-w":[{"max-w":["0","none","full","min","max","fit","prose",{screen:[Bi]},Bi,Je]}],h:[{h:[Je,t,"auto","min","max","fit"]}],"min-h":[{"min-h":["min","max","fit",oo,Je]}],"max-h":[{"max-h":[Je,t,"min","max","fit"]}],"font-size":[{text:["base",Bi,zi]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",np]}],"font-family":[{font:[ru]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractons"],tracking:[{tracking:["tighter","tight","normal","wide","wider","widest",Je]}],"line-clamp":[{"line-clamp":["none",ia,np]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",oo,Je]}],"list-image":[{"list-image":["none",Je]}],"list-style-type":[{list:["none","disc","decimal",Je]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[e]}],"placeholder-opacity":[{"placeholder-opacity":[S]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[e]}],"text-opacity":[{"text-opacity":[S]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...L(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",oo,zi]}],"underline-offset":[{"underline-offset":["auto",oo,Je]}],"text-decoration-color":[{decoration:[e]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],indent:[{indent:G()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Je]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",Je]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[S]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...te(),QL]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",qL]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},eF]}],"bg-color":[{bg:[e]}],"gradient-from-pos":[{from:[x]}],"gradient-via-pos":[{via:[x]}],"gradient-to-pos":[{to:[x]}],"gradient-from":[{from:[y]}],"gradient-via":[{via:[y]}],"gradient-to":[{to:[y]}],rounded:[{rounded:[i]}],"rounded-s":[{"rounded-s":[i]}],"rounded-e":[{"rounded-e":[i]}],"rounded-t":[{"rounded-t":[i]}],"rounded-r":[{"rounded-r":[i]}],"rounded-b":[{"rounded-b":[i]}],"rounded-l":[{"rounded-l":[i]}],"rounded-ss":[{"rounded-ss":[i]}],"rounded-se":[{"rounded-se":[i]}],"rounded-ee":[{"rounded-ee":[i]}],"rounded-es":[{"rounded-es":[i]}],"rounded-tl":[{"rounded-tl":[i]}],"rounded-tr":[{"rounded-tr":[i]}],"rounded-br":[{"rounded-br":[i]}],"rounded-bl":[{"rounded-bl":[i]}],"border-w":[{border:[l]}],"border-w-x":[{"border-x":[l]}],"border-w-y":[{"border-y":[l]}],"border-w-s":[{"border-s":[l]}],"border-w-e":[{"border-e":[l]}],"border-w-t":[{"border-t":[l]}],"border-w-r":[{"border-r":[l]}],"border-w-b":[{"border-b":[l]}],"border-w-l":[{"border-l":[l]}],"border-opacity":[{"border-opacity":[S]}],"border-style":[{border:[...L(),"hidden"]}],"divide-x":[{"divide-x":[l]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[l]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[S]}],"divide-style":[{divide:L()}],"border-color":[{border:[o]}],"border-color-x":[{"border-x":[o]}],"border-color-y":[{"border-y":[o]}],"border-color-t":[{"border-t":[o]}],"border-color-r":[{"border-r":[o]}],"border-color-b":[{"border-b":[o]}],"border-color-l":[{"border-l":[o]}],"divide-color":[{divide:[o]}],"outline-style":[{outline:["",...L()]}],"outline-offset":[{"outline-offset":[oo,Je]}],"outline-w":[{outline:[oo,zi]}],"outline-color":[{outline:[e]}],"ring-w":[{ring:ae()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[e]}],"ring-opacity":[{"ring-opacity":[S]}],"ring-offset-w":[{"ring-offset":[oo,zi]}],"ring-offset-color":[{"ring-offset":[e]}],shadow:[{shadow:["","inner","none",Bi,tF]}],"shadow-color":[{shadow:[ru]}],opacity:[{opacity:[S]}],"mix-blend":[{"mix-blend":ie()}],"bg-blend":[{"bg-blend":ie()}],filter:[{filter:["","none"]}],blur:[{blur:[n]}],brightness:[{brightness:[r]}],contrast:[{contrast:[u]}],"drop-shadow":[{"drop-shadow":["","none",Bi,Je]}],grayscale:[{grayscale:[d]}],"hue-rotate":[{"hue-rotate":[h]}],invert:[{invert:[m]}],saturate:[{saturate:[E]}],sepia:[{sepia:[P]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[n]}],"backdrop-brightness":[{"backdrop-brightness":[r]}],"backdrop-contrast":[{"backdrop-contrast":[u]}],"backdrop-grayscale":[{"backdrop-grayscale":[d]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[h]}],"backdrop-invert":[{"backdrop-invert":[m]}],"backdrop-opacity":[{"backdrop-opacity":[S]}],"backdrop-saturate":[{"backdrop-saturate":[E]}],"backdrop-sepia":[{"backdrop-sepia":[P]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":[s]}],"border-spacing-x":[{"border-spacing-x":[s]}],"border-spacing-y":[{"border-spacing-y":[s]}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["none","all","","colors","opacity","shadow","transform",Je]}],duration:[{duration:ge()}],ease:[{ease:["linear","in","out","in-out",Je]}],delay:[{delay:ge()}],animate:[{animate:["none","spin","ping","pulse","bounce",Je]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[k]}],"scale-x":[{"scale-x":[k]}],"scale-y":[{"scale-y":[k]}],rotate:[{rotate:[nu,Je]}],"translate-x":[{"translate-x":[O]}],"translate-y":[{"translate-y":[O]}],"skew-x":[{"skew-x":[M]}],"skew-y":[{"skew-y":[M]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",Je]}],accent:[{accent:["auto",e]}],appearance:["appearance-none"],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",Je]}],"caret-color":[{caret:[e]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":G()}],"scroll-mx":[{"scroll-mx":G()}],"scroll-my":[{"scroll-my":G()}],"scroll-ms":[{"scroll-ms":G()}],"scroll-me":[{"scroll-me":G()}],"scroll-mt":[{"scroll-mt":G()}],"scroll-mr":[{"scroll-mr":G()}],"scroll-mb":[{"scroll-mb":G()}],"scroll-ml":[{"scroll-ml":G()}],"scroll-p":[{"scroll-p":G()}],"scroll-px":[{"scroll-px":G()}],"scroll-py":[{"scroll-py":G()}],"scroll-ps":[{"scroll-ps":G()}],"scroll-pe":[{"scroll-pe":G()}],"scroll-pt":[{"scroll-pt":G()}],"scroll-pr":[{"scroll-pr":G()}],"scroll-pb":[{"scroll-pb":G()}],"scroll-pl":[{"scroll-pl":G()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",Je]}],fill:[{fill:[e,"none"]}],"stroke-w":[{stroke:[oo,zi,np]}],stroke:[{stroke:[e,"none"]}],sr:["sr-only","not-sr-only"]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]}}}const Jw=UL(iF),sF=40,is="inpaint",rp="diffusers_sd",nC="diffusers_sdxl",op="diffusers_sd_inpaint",rC="diffusers_sdxl_inpaint",l0="diffusers_other",Ky="#ffcc00bb",oC="ldm",iC="cv2",YR="Fantasy-Studio/Paint-by-Example",aF="timbrooks/instruct-pix2pix",lF="Sanster/PowerPaint-V1-stable-diffusion-inpainting",cF="Sanster/AnyText",uF="out of frame, lowres, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, disfigured, gross proportions, malformed limbs, watermark, signature";function Ce(...e){return Jw(BR(e))}function dF(){async function e(r=""){return(await fetch(r,{method:"GET",cache:"no-cache"})).json()}const t=()=>{const r=document.location;e(r+"/flaskwebgui-keep-server-alive").then(i=>i)},n=3*1e3;t(),setInterval(t,n)}function sC(e){const t=e.split(",")[0].split(":")[1].split(";")[0],n=atob(e.split(",")[1]),r=[];for(let o=0;o{const o=e.src,i=e;i.onload=n,i.onerror=s=>{i.src=o,r(s)},i.src=t})}async function fF(e){const t=URL.createObjectURL(e),n=new Image;return await Ip(n,t),n}function aC(e){return new Promise((t,n)=>{const r=new Image;r.addEventListener("load",()=>{t(r)}),r.addEventListener("error",o=>{n(o)}),r.src=e.toDataURL()})}function pF(e){return new Promise((t,n)=>{const r=new FileReader;r.onload=()=>{const o=new Image;o.onload=()=>{t(o)},o.onerror=()=>{n("无法加载图像。")},o.src=r.result},r.onerror=()=>{n("无法读取文件。")},r.readAsDataURL(e)})}function ku(e,t,n){return fetch(e).then(function(r){return r.arrayBuffer()}).then(function(r){return new File([r],t,{type:n})})}async function hF(){try{const{state:e}=await navigator.permissions.query({name:"clipboard-write"});return e==="granted"}catch{return!1}}function mF(e,t){return new Promise((n,r)=>e.toBlob(async o=>{o?n(o):r(new Error("Expected toBlob() to be defined"))},t))}const gF=async e=>{const t=[new ClipboardItem({[e.type]:e})];await navigator.clipboard.write(t)};function lC(e){return e.nativeEvent.button===2}function cC(e){return e.nativeEvent.button===1}async function vF(e){const t=await mF(e,"image/png");try{await gF(t)}catch{console.log("Copy image failed!")}}function yF(e,t){const n=document.createElement("a");n.href=e,n.download=t,n.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0,view:window})),setTimeout(()=>{n.remove()},100)}function c0(e){const t=e.nativeEvent;return{x:t.offsetX,y:t.offsetY}}function GR(e,t,n=Ky){e.strokeStyle=n,e.lineCap="round",e.lineJoin="round",t.forEach(r=>{!(r!=null&&r.pts.length)||!r.size||(e.lineWidth=r.size,e.beginPath(),e.moveTo(r.pts[0].x,r.pts[0].y),r.pts.forEach(o=>e.lineTo(o.x,o.y)),e.stroke())})}const Lp=(e,t,n,r=[],o="white")=>{const i=document.createElement("canvas");i.width=e,i.height=t;const s=i.getContext("2d");if(!s)throw new Error("could not retrieve mask canvas");return r.forEach(l=>{s.drawImage(l,0,0,e,t)}),n.forEach(l=>{GR(s,l,o)}),i},Ru=e=>new Promise((t,n)=>{const r=new FileReader;r.onload=o=>{var s;const i=(s=o.target)==null?void 0:s.result;t(i)},r.onerror=o=>{n(o)},r.readAsDataURL(e)});function XR(e,t){return function(){return e.apply(t,arguments)}}const{toString:wF}=Object.prototype,{getPrototypeOf:ex}=Object,$m=(e=>t=>{const n=wF.call(t);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),Go=e=>(e=e.toLowerCase(),t=>$m(t)===e),km=e=>t=>typeof t===e,{isArray:gc}=Array,Zu=km("undefined");function xF(e){return e!==null&&!Zu(e)&&e.constructor!==null&&!Zu(e.constructor)&&Kr(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const ZR=Go("ArrayBuffer");function bF(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&ZR(e.buffer),t}const _F=km("string"),Kr=km("function"),qR=km("number"),Rm=e=>e!==null&&typeof e=="object",SF=e=>e===!0||e===!1,Fp=e=>{if($m(e)!=="object")return!1;const t=ex(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},EF=Go("Date"),CF=Go("File"),$F=Go("Blob"),kF=Go("FileList"),RF=e=>Rm(e)&&Kr(e.pipe),TF=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||Kr(e.append)&&((t=$m(e))==="formdata"||t==="object"&&Kr(e.toString)&&e.toString()==="[object FormData]"))},PF=Go("URLSearchParams"),AF=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function kd(e,t,{allOwnKeys:n=!1}={}){if(e===null||typeof e>"u")return;let r,o;if(typeof e!="object"&&(e=[e]),gc(e))for(r=0,o=e.length;r0;)if(o=n[r],t===o.toLowerCase())return o;return null}const JR=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,eT=e=>!Zu(e)&&e!==JR;function Yy(){const{caseless:e}=eT(this)&&this||{},t={},n=(r,o)=>{const i=e&&QR(t,o)||o;Fp(t[i])&&Fp(r)?t[i]=Yy(t[i],r):Fp(r)?t[i]=Yy({},r):gc(r)?t[i]=r.slice():t[i]=r};for(let r=0,o=arguments.length;r(kd(t,(o,i)=>{n&&Kr(o)?e[i]=XR(o,n):e[i]=o},{allOwnKeys:r}),e),MF=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),NF=(e,t,n,r)=>{e.prototype=Object.create(t.prototype,r),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),n&&Object.assign(e.prototype,n)},DF=(e,t,n,r)=>{let o,i,s;const l={};if(t=t||{},e==null)return t;do{for(o=Object.getOwnPropertyNames(e),i=o.length;i-- >0;)s=o[i],(!r||r(s,e,t))&&!l[s]&&(t[s]=e[s],l[s]=!0);e=n!==!1&&ex(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},IF=(e,t,n)=>{e=String(e),(n===void 0||n>e.length)&&(n=e.length),n-=t.length;const r=e.indexOf(t,n);return r!==-1&&r===n},LF=e=>{if(!e)return null;if(gc(e))return e;let t=e.length;if(!qR(t))return null;const n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},FF=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&ex(Uint8Array)),jF=(e,t)=>{const r=(e&&e[Symbol.iterator]).call(e);let o;for(;(o=r.next())&&!o.done;){const i=o.value;t.call(e,i[0],i[1])}},zF=(e,t)=>{let n;const r=[];for(;(n=e.exec(t))!==null;)r.push(n);return r},BF=Go("HTMLFormElement"),UF=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,r,o){return r.toUpperCase()+o}),uC=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),VF=Go("RegExp"),tT=(e,t)=>{const n=Object.getOwnPropertyDescriptors(e),r={};kd(n,(o,i)=>{let s;(s=t(o,i,e))!==!1&&(r[i]=s||o)}),Object.defineProperties(e,r)},WF=e=>{tT(e,(t,n)=>{if(Kr(e)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;const r=e[n];if(Kr(r)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},HF=(e,t)=>{const n={},r=o=>{o.forEach(i=>{n[i]=!0})};return gc(e)?r(e):r(String(e).split(t)),n},KF=()=>{},YF=(e,t)=>(e=+e,Number.isFinite(e)?e:t),u0="abcdefghijklmnopqrstuvwxyz",dC="0123456789",nT={DIGIT:dC,ALPHA:u0,ALPHA_DIGIT:u0+u0.toUpperCase()+dC},GF=(e=16,t=nT.ALPHA_DIGIT)=>{let n="";const{length:r}=t;for(;e--;)n+=t[Math.random()*r|0];return n};function XF(e){return!!(e&&Kr(e.append)&&e[Symbol.toStringTag]==="FormData"&&e[Symbol.iterator])}const ZF=e=>{const t=new Array(10),n=(r,o)=>{if(Rm(r)){if(t.indexOf(r)>=0)return;if(!("toJSON"in r)){t[o]=r;const i=gc(r)?[]:{};return kd(r,(s,l)=>{const u=n(s,o+1);!Zu(u)&&(i[l]=u)}),t[o]=void 0,i}}return r};return n(e,0)},qF=Go("AsyncFunction"),QF=e=>e&&(Rm(e)||Kr(e))&&Kr(e.then)&&Kr(e.catch),oe={isArray:gc,isArrayBuffer:ZR,isBuffer:xF,isFormData:TF,isArrayBufferView:bF,isString:_F,isNumber:qR,isBoolean:SF,isObject:Rm,isPlainObject:Fp,isUndefined:Zu,isDate:EF,isFile:CF,isBlob:$F,isRegExp:VF,isFunction:Kr,isStream:RF,isURLSearchParams:PF,isTypedArray:FF,isFileList:kF,forEach:kd,merge:Yy,extend:OF,trim:AF,stripBOM:MF,inherits:NF,toFlatObject:DF,kindOf:$m,kindOfTest:Go,endsWith:IF,toArray:LF,forEachEntry:jF,matchAll:zF,isHTMLForm:BF,hasOwnProperty:uC,hasOwnProp:uC,reduceDescriptors:tT,freezeMethods:WF,toObjectSet:HF,toCamelCase:UF,noop:KF,toFiniteNumber:YF,findKey:QR,global:JR,isContextDefined:eT,ALPHABET:nT,generateString:GF,isSpecCompliantForm:XF,toJSONObject:ZF,isAsyncFn:qF,isThenable:QF};function ut(e,t,n,r,o){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),n&&(this.config=n),r&&(this.request=r),o&&(this.response=o)}oe.inherits(ut,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:oe.toJSONObject(this.config),code:this.code,status:this.response&&this.response.status?this.response.status:null}}});const rT=ut.prototype,oT={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{oT[e]={value:e}});Object.defineProperties(ut,oT);Object.defineProperty(rT,"isAxiosError",{value:!0});ut.from=(e,t,n,r,o,i)=>{const s=Object.create(rT);return oe.toFlatObject(e,s,function(u){return u!==Error.prototype},l=>l!=="isAxiosError"),ut.call(s,e.message,t,n,r,o),s.cause=e,s.name=e.name,i&&Object.assign(s,i),s};const JF=null;function Gy(e){return oe.isPlainObject(e)||oe.isArray(e)}function iT(e){return oe.endsWith(e,"[]")?e.slice(0,-2):e}function fC(e,t,n){return e?e.concat(t).map(function(o,i){return o=iT(o),!n&&i?"["+o+"]":o}).join(n?".":""):t}function ej(e){return oe.isArray(e)&&!e.some(Gy)}const tj=oe.toFlatObject(oe,{},null,function(t){return/^is[A-Z]/.test(t)});function Tm(e,t,n){if(!oe.isObject(e))throw new TypeError("target must be an object");t=t||new FormData,n=oe.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(_,C){return!oe.isUndefined(C[_])});const r=n.metaTokens,o=n.visitor||h,i=n.dots,s=n.indexes,u=(n.Blob||typeof Blob<"u"&&Blob)&&oe.isSpecCompliantForm(t);if(!oe.isFunction(o))throw new TypeError("visitor must be a function");function d(x){if(x===null)return"";if(oe.isDate(x))return x.toISOString();if(!u&&oe.isBlob(x))throw new ut("Blob is not supported. Use a Buffer instead.");return oe.isArrayBuffer(x)||oe.isTypedArray(x)?u&&typeof Blob=="function"?new Blob([x]):Buffer.from(x):x}function h(x,_,C){let S=x;if(x&&!C&&typeof x=="object"){if(oe.endsWith(_,"{}"))_=r?_:_.slice(0,-2),x=JSON.stringify(x);else if(oe.isArray(x)&&ej(x)||(oe.isFileList(x)||oe.endsWith(_,"[]"))&&(S=oe.toArray(x)))return _=iT(_),S.forEach(function(E,k){!(oe.isUndefined(E)||E===null)&&t.append(s===!0?fC([_],k,i):s===null?_:_+"[]",d(E))}),!1}return Gy(x)?!0:(t.append(fC(C,_,i),d(x)),!1)}const m=[],g=Object.assign(tj,{defaultVisitor:h,convertValue:d,isVisitable:Gy});function y(x,_){if(!oe.isUndefined(x)){if(m.indexOf(x)!==-1)throw Error("Circular reference detected in "+_.join("."));m.push(x),oe.forEach(x,function(S,b){(!(oe.isUndefined(S)||S===null)&&o.call(t,S,oe.isString(b)?b.trim():b,_,g))===!0&&y(S,_?_.concat(b):[b])}),m.pop()}}if(!oe.isObject(e))throw new TypeError("data must be an object");return y(e),t}function pC(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(r){return t[r]})}function tx(e,t){this._pairs=[],e&&Tm(e,this,t)}const sT=tx.prototype;sT.append=function(t,n){this._pairs.push([t,n])};sT.toString=function(t){const n=t?function(r){return t.call(this,r,pC)}:pC;return this._pairs.map(function(o){return n(o[0])+"="+n(o[1])},"").join("&")};function nj(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function aT(e,t,n){if(!t)return e;const r=n&&n.encode||nj,o=n&&n.serialize;let i;if(o?i=o(t,n):i=oe.isURLSearchParams(t)?t.toString():new tx(t,n).toString(r),i){const s=e.indexOf("#");s!==-1&&(e=e.slice(0,s)),e+=(e.indexOf("?")===-1?"?":"&")+i}return e}class rj{constructor(){this.handlers=[]}use(t,n,r){return this.handlers.push({fulfilled:t,rejected:n,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){oe.forEach(this.handlers,function(r){r!==null&&t(r)})}}const hC=rj,lT={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},oj=typeof URLSearchParams<"u"?URLSearchParams:tx,ij=typeof FormData<"u"?FormData:null,sj=typeof Blob<"u"?Blob:null,aj={isBrowser:!0,classes:{URLSearchParams:oj,FormData:ij,Blob:sj},protocols:["http","https","file","blob","url","data"]},cT=typeof window<"u"&&typeof document<"u",lj=(e=>cT&&["ReactNative","NativeScript","NS"].indexOf(e)<0)(typeof navigator<"u"&&navigator.product),cj=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",uj=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:cT,hasStandardBrowserEnv:lj,hasStandardBrowserWebWorkerEnv:cj},Symbol.toStringTag,{value:"Module"})),Io={...uj,...aj};function dj(e,t){return Tm(e,new Io.classes.URLSearchParams,Object.assign({visitor:function(n,r,o,i){return Io.isNode&&oe.isBuffer(n)?(this.append(r,n.toString("base64")),!1):i.defaultVisitor.apply(this,arguments)}},t))}function fj(e){return oe.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function pj(e){const t={},n=Object.keys(e);let r;const o=n.length;let i;for(r=0;r=n.length;return s=!s&&oe.isArray(o)?o.length:s,u?(oe.hasOwnProp(o,s)?o[s]=[o[s],r]:o[s]=r,!l):((!o[s]||!oe.isObject(o[s]))&&(o[s]=[]),t(n,r,o[s],i)&&oe.isArray(o[s])&&(o[s]=pj(o[s])),!l)}if(oe.isFormData(e)&&oe.isFunction(e.entries)){const n={};return oe.forEachEntry(e,(r,o)=>{t(fj(r),o,n,0)}),n}return null}function hj(e,t,n){if(oe.isString(e))try{return(t||JSON.parse)(e),oe.trim(e)}catch(r){if(r.name!=="SyntaxError")throw r}return(n||JSON.stringify)(e)}const nx={transitional:lT,adapter:["xhr","http"],transformRequest:[function(t,n){const r=n.getContentType()||"",o=r.indexOf("application/json")>-1,i=oe.isObject(t);if(i&&oe.isHTMLForm(t)&&(t=new FormData(t)),oe.isFormData(t))return o&&o?JSON.stringify(uT(t)):t;if(oe.isArrayBuffer(t)||oe.isBuffer(t)||oe.isStream(t)||oe.isFile(t)||oe.isBlob(t))return t;if(oe.isArrayBufferView(t))return t.buffer;if(oe.isURLSearchParams(t))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let l;if(i){if(r.indexOf("application/x-www-form-urlencoded")>-1)return dj(t,this.formSerializer).toString();if((l=oe.isFileList(t))||r.indexOf("multipart/form-data")>-1){const u=this.env&&this.env.FormData;return Tm(l?{"files[]":t}:t,u&&new u,this.formSerializer)}}return i||o?(n.setContentType("application/json",!1),hj(t)):t}],transformResponse:[function(t){const n=this.transitional||nx.transitional,r=n&&n.forcedJSONParsing,o=this.responseType==="json";if(t&&oe.isString(t)&&(r&&!this.responseType||o)){const s=!(n&&n.silentJSONParsing)&&o;try{return JSON.parse(t)}catch(l){if(s)throw l.name==="SyntaxError"?ut.from(l,ut.ERR_BAD_RESPONSE,this,null,this.response):l}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:Io.classes.FormData,Blob:Io.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};oe.forEach(["delete","get","head","post","put","patch"],e=>{nx.headers[e]={}});const rx=nx,mj=oe.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),gj=e=>{const t={};let n,r,o;return e&&e.split(` +`).forEach(function(s){o=s.indexOf(":"),n=s.substring(0,o).trim().toLowerCase(),r=s.substring(o+1).trim(),!(!n||t[n]&&mj[n])&&(n==="set-cookie"?t[n]?t[n].push(r):t[n]=[r]:t[n]=t[n]?t[n]+", "+r:r)}),t},mC=Symbol("internals");function ou(e){return e&&String(e).trim().toLowerCase()}function jp(e){return e===!1||e==null?e:oe.isArray(e)?e.map(jp):String(e)}function vj(e){const t=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=n.exec(e);)t[r[1]]=r[2];return t}const yj=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function d0(e,t,n,r,o){if(oe.isFunction(r))return r.call(this,t,n);if(o&&(t=n),!!oe.isString(t)){if(oe.isString(r))return t.indexOf(r)!==-1;if(oe.isRegExp(r))return r.test(t)}}function wj(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,n,r)=>n.toUpperCase()+r)}function xj(e,t){const n=oe.toCamelCase(" "+t);["get","set","has"].forEach(r=>{Object.defineProperty(e,r+n,{value:function(o,i,s){return this[r].call(this,t,o,i,s)},configurable:!0})})}class Pm{constructor(t){t&&this.set(t)}set(t,n,r){const o=this;function i(l,u,d){const h=ou(u);if(!h)throw new Error("header name must be a non-empty string");const m=oe.findKey(o,h);(!m||o[m]===void 0||d===!0||d===void 0&&o[m]!==!1)&&(o[m||u]=jp(l))}const s=(l,u)=>oe.forEach(l,(d,h)=>i(d,h,u));return oe.isPlainObject(t)||t instanceof this.constructor?s(t,n):oe.isString(t)&&(t=t.trim())&&!yj(t)?s(gj(t),n):t!=null&&i(n,t,r),this}get(t,n){if(t=ou(t),t){const r=oe.findKey(this,t);if(r){const o=this[r];if(!n)return o;if(n===!0)return vj(o);if(oe.isFunction(n))return n.call(this,o,r);if(oe.isRegExp(n))return n.exec(o);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,n){if(t=ou(t),t){const r=oe.findKey(this,t);return!!(r&&this[r]!==void 0&&(!n||d0(this,this[r],r,n)))}return!1}delete(t,n){const r=this;let o=!1;function i(s){if(s=ou(s),s){const l=oe.findKey(r,s);l&&(!n||d0(r,r[l],l,n))&&(delete r[l],o=!0)}}return oe.isArray(t)?t.forEach(i):i(t),o}clear(t){const n=Object.keys(this);let r=n.length,o=!1;for(;r--;){const i=n[r];(!t||d0(this,this[i],i,t,!0))&&(delete this[i],o=!0)}return o}normalize(t){const n=this,r={};return oe.forEach(this,(o,i)=>{const s=oe.findKey(r,i);if(s){n[s]=jp(o),delete n[i];return}const l=t?wj(i):String(i).trim();l!==i&&delete n[i],n[l]=jp(o),r[l]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){const n=Object.create(null);return oe.forEach(this,(r,o)=>{r!=null&&r!==!1&&(n[o]=t&&oe.isArray(r)?r.join(", "):r)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,n])=>t+": "+n).join(` +`)}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...n){const r=new this(t);return n.forEach(o=>r.set(o)),r}static accessor(t){const r=(this[mC]=this[mC]={accessors:{}}).accessors,o=this.prototype;function i(s){const l=ou(s);r[l]||(xj(o,s),r[l]=!0)}return oe.isArray(t)?t.forEach(i):i(t),this}}Pm.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);oe.reduceDescriptors(Pm.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(r){this[n]=r}}});oe.freezeMethods(Pm);const pi=Pm;function f0(e,t){const n=this||rx,r=t||n,o=pi.from(r.headers);let i=r.data;return oe.forEach(e,function(l){i=l.call(n,i,o.normalize(),t?t.status:void 0)}),o.normalize(),i}function dT(e){return!!(e&&e.__CANCEL__)}function Rd(e,t,n){ut.call(this,e??"canceled",ut.ERR_CANCELED,t,n),this.name="CanceledError"}oe.inherits(Rd,ut,{__CANCEL__:!0});function bj(e,t,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?e(n):t(new ut("Request failed with status code "+n.status,[ut.ERR_BAD_REQUEST,ut.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}const _j=Io.hasStandardBrowserEnv?{write(e,t,n,r,o,i){const s=[e+"="+encodeURIComponent(t)];oe.isNumber(n)&&s.push("expires="+new Date(n).toGMTString()),oe.isString(r)&&s.push("path="+r),oe.isString(o)&&s.push("domain="+o),i===!0&&s.push("secure"),document.cookie=s.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function Sj(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function Ej(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e}function fT(e,t){return e&&!Sj(t)?Ej(e,t):t}const Cj=Io.hasStandardBrowserEnv?function(){const t=/(msie|trident)/i.test(navigator.userAgent),n=document.createElement("a");let r;function o(i){let s=i;return t&&(n.setAttribute("href",s),s=n.href),n.setAttribute("href",s),{href:n.href,protocol:n.protocol?n.protocol.replace(/:$/,""):"",host:n.host,search:n.search?n.search.replace(/^\?/,""):"",hash:n.hash?n.hash.replace(/^#/,""):"",hostname:n.hostname,port:n.port,pathname:n.pathname.charAt(0)==="/"?n.pathname:"/"+n.pathname}}return r=o(window.location.href),function(s){const l=oe.isString(s)?o(s):s;return l.protocol===r.protocol&&l.host===r.host}}():function(){return function(){return!0}}();function $j(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function kj(e,t){e=e||10;const n=new Array(e),r=new Array(e);let o=0,i=0,s;return t=t!==void 0?t:1e3,function(u){const d=Date.now(),h=r[i];s||(s=d),n[o]=u,r[o]=d;let m=i,g=0;for(;m!==o;)g+=n[m++],m=m%e;if(o=(o+1)%e,o===i&&(i=(i+1)%e),d-s{const i=o.loaded,s=o.lengthComputable?o.total:void 0,l=i-n,u=r(l),d=i<=s;n=i;const h={loaded:i,total:s,progress:s?i/s:void 0,bytes:l,rate:u||void 0,estimated:u&&s&&d?(s-i)/u:void 0,event:o};h[t?"download":"upload"]=!0,e(h)}}const Rj=typeof XMLHttpRequest<"u",Tj=Rj&&function(e){return new Promise(function(n,r){let o=e.data;const i=pi.from(e.headers).normalize();let{responseType:s,withXSRFToken:l}=e,u;function d(){e.cancelToken&&e.cancelToken.unsubscribe(u),e.signal&&e.signal.removeEventListener("abort",u)}let h;if(oe.isFormData(o)){if(Io.hasStandardBrowserEnv||Io.hasStandardBrowserWebWorkerEnv)i.setContentType(!1);else if((h=i.getContentType())!==!1){const[_,...C]=h?h.split(";").map(S=>S.trim()).filter(Boolean):[];i.setContentType([_||"multipart/form-data",...C].join("; "))}}let m=new XMLHttpRequest;if(e.auth){const _=e.auth.username||"",C=e.auth.password?unescape(encodeURIComponent(e.auth.password)):"";i.set("Authorization","Basic "+btoa(_+":"+C))}const g=fT(e.baseURL,e.url);m.open(e.method.toUpperCase(),aT(g,e.params,e.paramsSerializer),!0),m.timeout=e.timeout;function y(){if(!m)return;const _=pi.from("getAllResponseHeaders"in m&&m.getAllResponseHeaders()),S={data:!s||s==="text"||s==="json"?m.responseText:m.response,status:m.status,statusText:m.statusText,headers:_,config:e,request:m};bj(function(E){n(E),d()},function(E){r(E),d()},S),m=null}if("onloadend"in m?m.onloadend=y:m.onreadystatechange=function(){!m||m.readyState!==4||m.status===0&&!(m.responseURL&&m.responseURL.indexOf("file:")===0)||setTimeout(y)},m.onabort=function(){m&&(r(new ut("Request aborted",ut.ECONNABORTED,e,m)),m=null)},m.onerror=function(){r(new ut("Network Error",ut.ERR_NETWORK,e,m)),m=null},m.ontimeout=function(){let C=e.timeout?"timeout of "+e.timeout+"ms exceeded":"timeout exceeded";const S=e.transitional||lT;e.timeoutErrorMessage&&(C=e.timeoutErrorMessage),r(new ut(C,S.clarifyTimeoutError?ut.ETIMEDOUT:ut.ECONNABORTED,e,m)),m=null},Io.hasStandardBrowserEnv&&(l&&oe.isFunction(l)&&(l=l(e)),l||l!==!1&&Cj(g))){const _=e.xsrfHeaderName&&e.xsrfCookieName&&_j.read(e.xsrfCookieName);_&&i.set(e.xsrfHeaderName,_)}o===void 0&&i.setContentType(null),"setRequestHeader"in m&&oe.forEach(i.toJSON(),function(C,S){m.setRequestHeader(S,C)}),oe.isUndefined(e.withCredentials)||(m.withCredentials=!!e.withCredentials),s&&s!=="json"&&(m.responseType=e.responseType),typeof e.onDownloadProgress=="function"&&m.addEventListener("progress",gC(e.onDownloadProgress,!0)),typeof e.onUploadProgress=="function"&&m.upload&&m.upload.addEventListener("progress",gC(e.onUploadProgress)),(e.cancelToken||e.signal)&&(u=_=>{m&&(r(!_||_.type?new Rd(null,e,m):_),m.abort(),m=null)},e.cancelToken&&e.cancelToken.subscribe(u),e.signal&&(e.signal.aborted?u():e.signal.addEventListener("abort",u)));const x=$j(g);if(x&&Io.protocols.indexOf(x)===-1){r(new ut("Unsupported protocol "+x+":",ut.ERR_BAD_REQUEST,e));return}m.send(o||null)})},Xy={http:JF,xhr:Tj};oe.forEach(Xy,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});const vC=e=>`- ${e}`,Pj=e=>oe.isFunction(e)||e===null||e===!1,pT={getAdapter:e=>{e=oe.isArray(e)?e:[e];const{length:t}=e;let n,r;const o={};for(let i=0;i`adapter ${l} `+(u===!1?"is not supported by the environment":"is not available in the build"));let s=t?i.length>1?`since : +`+i.map(vC).join(` +`):" "+vC(i[0]):"as no adapter specified";throw new ut("There is no suitable adapter to dispatch the request "+s,"ERR_NOT_SUPPORT")}return r},adapters:Xy};function p0(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Rd(null,e)}function yC(e){return p0(e),e.headers=pi.from(e.headers),e.data=f0.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),pT.getAdapter(e.adapter||rx.adapter)(e).then(function(r){return p0(e),r.data=f0.call(e,e.transformResponse,r),r.headers=pi.from(r.headers),r},function(r){return dT(r)||(p0(e),r&&r.response&&(r.response.data=f0.call(e,e.transformResponse,r.response),r.response.headers=pi.from(r.response.headers))),Promise.reject(r)})}const wC=e=>e instanceof pi?e.toJSON():e;function Jl(e,t){t=t||{};const n={};function r(d,h,m){return oe.isPlainObject(d)&&oe.isPlainObject(h)?oe.merge.call({caseless:m},d,h):oe.isPlainObject(h)?oe.merge({},h):oe.isArray(h)?h.slice():h}function o(d,h,m){if(oe.isUndefined(h)){if(!oe.isUndefined(d))return r(void 0,d,m)}else return r(d,h,m)}function i(d,h){if(!oe.isUndefined(h))return r(void 0,h)}function s(d,h){if(oe.isUndefined(h)){if(!oe.isUndefined(d))return r(void 0,d)}else return r(void 0,h)}function l(d,h,m){if(m in t)return r(d,h);if(m in e)return r(void 0,d)}const u={url:i,method:i,data:i,baseURL:s,transformRequest:s,transformResponse:s,paramsSerializer:s,timeout:s,timeoutMessage:s,withCredentials:s,withXSRFToken:s,adapter:s,responseType:s,xsrfCookieName:s,xsrfHeaderName:s,onUploadProgress:s,onDownloadProgress:s,decompress:s,maxContentLength:s,maxBodyLength:s,beforeRedirect:s,transport:s,httpAgent:s,httpsAgent:s,cancelToken:s,socketPath:s,responseEncoding:s,validateStatus:l,headers:(d,h)=>o(wC(d),wC(h),!0)};return oe.forEach(Object.keys(Object.assign({},e,t)),function(h){const m=u[h]||o,g=m(e[h],t[h],h);oe.isUndefined(g)&&m!==l||(n[h]=g)}),n}const hT="1.6.2",ox={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{ox[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const xC={};ox.transitional=function(t,n,r){function o(i,s){return"[Axios v"+hT+"] Transitional option '"+i+"'"+s+(r?". "+r:"")}return(i,s,l)=>{if(t===!1)throw new ut(o(s," has been removed"+(n?" in "+n:"")),ut.ERR_DEPRECATED);return n&&!xC[s]&&(xC[s]=!0,console.warn(o(s," has been deprecated since v"+n+" and will be removed in the near future"))),t?t(i,s,l):!0}};function Aj(e,t,n){if(typeof e!="object")throw new ut("options must be an object",ut.ERR_BAD_OPTION_VALUE);const r=Object.keys(e);let o=r.length;for(;o-- >0;){const i=r[o],s=t[i];if(s){const l=e[i],u=l===void 0||s(l,i,e);if(u!==!0)throw new ut("option "+i+" must be "+u,ut.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new ut("Unknown option "+i,ut.ERR_BAD_OPTION)}}const Zy={assertOptions:Aj,validators:ox},Ui=Zy.validators;class Ph{constructor(t){this.defaults=t,this.interceptors={request:new hC,response:new hC}}request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=Jl(this.defaults,n);const{transitional:r,paramsSerializer:o,headers:i}=n;r!==void 0&&Zy.assertOptions(r,{silentJSONParsing:Ui.transitional(Ui.boolean),forcedJSONParsing:Ui.transitional(Ui.boolean),clarifyTimeoutError:Ui.transitional(Ui.boolean)},!1),o!=null&&(oe.isFunction(o)?n.paramsSerializer={serialize:o}:Zy.assertOptions(o,{encode:Ui.function,serialize:Ui.function},!0)),n.method=(n.method||this.defaults.method||"get").toLowerCase();let s=i&&oe.merge(i.common,i[n.method]);i&&oe.forEach(["delete","get","head","post","put","patch","common"],x=>{delete i[x]}),n.headers=pi.concat(s,i);const l=[];let u=!0;this.interceptors.request.forEach(function(_){typeof _.runWhen=="function"&&_.runWhen(n)===!1||(u=u&&_.synchronous,l.unshift(_.fulfilled,_.rejected))});const d=[];this.interceptors.response.forEach(function(_){d.push(_.fulfilled,_.rejected)});let h,m=0,g;if(!u){const x=[yC.bind(this),void 0];for(x.unshift.apply(x,l),x.push.apply(x,d),g=x.length,h=Promise.resolve(n);m{if(!r._listeners)return;let i=r._listeners.length;for(;i-- >0;)r._listeners[i](o);r._listeners=null}),this.promise.then=o=>{let i;const s=new Promise(l=>{r.subscribe(l),i=l}).then(o);return s.cancel=function(){r.unsubscribe(i)},s},t(function(i,s,l){r.reason||(r.reason=new Rd(i,s,l),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}static source(){let t;return{token:new ix(function(o){t=o}),cancel:t}}}const Oj=ix;function Mj(e){return function(n){return e.apply(null,n)}}function Nj(e){return oe.isObject(e)&&e.isAxiosError===!0}const qy={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(qy).forEach(([e,t])=>{qy[t]=e});const Dj=qy;function mT(e){const t=new zp(e),n=XR(zp.prototype.request,t);return oe.extend(n,zp.prototype,t,{allOwnKeys:!0}),oe.extend(n,t,null,{allOwnKeys:!0}),n.create=function(o){return mT(Jl(e,o))},n}const Qt=mT(rx);Qt.Axios=zp;Qt.CanceledError=Rd;Qt.CancelToken=Oj;Qt.isCancel=dT;Qt.VERSION=hT;Qt.toFormData=Tm;Qt.AxiosError=ut;Qt.Cancel=Qt.CanceledError;Qt.all=function(t){return Promise.all(t)};Qt.spread=Mj;Qt.isAxiosError=Nj;Qt.mergeConfig=Jl;Qt.AxiosHeaders=pi;Qt.formToJSON=e=>uT(oe.isHTMLForm(e)?new FormData(e):e);Qt.getAdapter=pT.getAdapter;Qt.HttpStatusCode=Dj;Qt.default=Qt;const Ij=Qt,Ms="/api/v1",vc=Ij.create({baseURL:Ms});async function Lj(e,t,n,r,o,i=null){const s=await Ru(e),l=await Ru(o),u=i?await Ru(i):null,d=await fetch(`${Ms}/inpaint`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({image:s,mask:l,ldm_steps:t.ldmSteps,ldm_sampler:t.ldmSampler,zits_wireframe:t.zitsWireframe,cv2_flag:t.cv2Flag,cv2_radius:t.cv2Radius,hd_strategy:"Crop",hd_strategy_crop_triger_size:640,hd_strategy_crop_margin:128,hd_trategy_resize_imit:2048,prompt:t.prompt,negative_prompt:t.negativePrompt,use_croper:t.showCropper,croper_x:n.x,croper_y:n.y,croper_height:n.height,croper_width:n.width,use_extender:t.showExtender,extender_x:r.x,extender_y:r.y,extender_height:r.height,extender_width:r.width,sd_mask_blur:t.sdMaskBlur,sd_strength:t.sdStrength,sd_steps:t.sdSteps,sd_guidance_scale:t.sdGuidanceScale,sd_sampler:t.sdSampler,sd_seed:t.seedFixed?t.seed:-1,sd_match_histograms:t.sdMatchHistograms,sd_freeu:t.enableFreeu,sd_freeu_config:t.freeuConfig,sd_lcm_lora:t.enableLCMLora,paint_by_example_example_image:u,p2p_image_guidance_scale:t.p2pImageGuidanceScale,enable_controlnet:t.enableControlnet,controlnet_conditioning_scale:t.controlnetConditioningScale,controlnet_method:t.controlnetMethod?t.controlnetMethod:"",powerpaint_task:t.showExtender?kl.outpainting:t.powerpaintTask})});if(d.ok){const m=await d.blob();return{blob:URL.createObjectURL(m),seed:d.headers.get("X-Seed")}}const h=await d.json();throw new Error(`Something went wrong: ${h.errors}`)}async function Fj(){return(await vc.get("/server-config")).data}async function jj(e){return(await vc.post("/model",{name:e})).data}async function zj(){return(await vc.get("/model")).data}function Bj(){return vc.get("/models").then(e=>e.data)}async function gT(e,t,n,r,o){const i=await Ru(n),l=await fetch(`${Ms}/${e?"run_plugin_gen_mask":"run_plugin_gen_image"}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t,image:i,upscale:r,clicks:o})});if(l.ok){const d=await l.blob();return{blob:URL.createObjectURL(d)}}const u=await l.json();throw new Error(u)}async function Uj(e,t){const n=await fetch(`${Ms}/media_file?tab=${e}&filename=${encodeURIComponent(t)}`,{method:"GET"});if(n.ok){const o=await n.blob();return new File([o],t,{type:n.headers.get("Content-Type")??"image/png"})}const r=await n.json();throw new Error(r.errors)}async function Vj(e){return(await vc.get("medias",{params:{tab:e}})).data}async function Wj(e,t,n){const r=await ku(e.src,t,n),o=new FormData;o.append("file",r);try{const i=await fetch(`${Ms}/save_image`,{method:"POST",body:o});if(!i.ok){const s=await i.text();throw new Error(s)}}catch(i){throw new Error(`Something went wrong: ${i}`)}}async function Hj(e){const t=new FormData;return t.append("file",e),(await vc.post("/gen-info",t)).data}async function Kj(e,t,n){const r=await Ru(e),o=await fetch(`${Ms}/adjust_mask`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mask:r,operate:t,kernel_size:n})});if(o.ok)return await o.blob();const i=await o.json();throw new Error(i)}function Yj(){const[e,t]=f.useState(null),n=f.useCallback(()=>{const r=new Headers;r.append("pragma","no-cache"),r.append("cache-control","no-cache"),fetch(`${Ms}/inputimage`,{headers:r}).then(async o=>{var l;if(!o.ok)throw new Error("No input image found");const i=(l=o.headers.get("content-disposition"))==null?void 0:l.split("filename=")[1].split(";")[0],s=await o.blob();if(s&&s.type.startsWith("image")){const u=new File([s],i!==void 0?i:"inputImage");t(u)}}).catch(o=>{console.log(o)})},[t]);return f.useEffect(()=>{n()},[n]),e}function xo(e,t){if(e==null)return{};var n={},r=Object.keys(e),o,i;for(i=0;i=0)&&(n[o]=e[o]);return n}var Gj=["color"],Xj=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,Gj);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),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:r,fillRule:"evenodd",clipRule:"evenodd"}))}),Zj=["color"],vT=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,Zj);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M11.4669 3.72684C11.7558 3.91574 11.8369 4.30308 11.648 4.59198L7.39799 11.092C7.29783 11.2452 7.13556 11.3467 6.95402 11.3699C6.77247 11.3931 6.58989 11.3355 6.45446 11.2124L3.70446 8.71241C3.44905 8.48022 3.43023 8.08494 3.66242 7.82953C3.89461 7.57412 4.28989 7.55529 4.5453 7.78749L6.75292 9.79441L10.6018 3.90792C10.7907 3.61902 11.178 3.53795 11.4669 3.72684Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),qj=["color"],Qj=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,qj);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M3.13523 6.15803C3.3241 5.95657 3.64052 5.94637 3.84197 6.13523L7.5 9.56464L11.158 6.13523C11.3595 5.94637 11.6759 5.95657 11.8648 6.15803C12.0536 6.35949 12.0434 6.67591 11.842 6.86477L7.84197 10.6148C7.64964 10.7951 7.35036 10.7951 7.15803 10.6148L3.15803 6.86477C2.95657 6.67591 2.94637 6.35949 3.13523 6.15803Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),Jj=["color"],ez=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,Jj);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M6.1584 3.13508C6.35985 2.94621 6.67627 2.95642 6.86514 3.15788L10.6151 7.15788C10.7954 7.3502 10.7954 7.64949 10.6151 7.84182L6.86514 11.8418C6.67627 12.0433 6.35985 12.0535 6.1584 11.8646C5.95694 11.6757 5.94673 11.3593 6.1356 11.1579L9.565 7.49985L6.1356 3.84182C5.94673 3.64036 5.95694 3.32394 6.1584 3.13508Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),tz=["color"],nz=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,tz);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M3.13523 8.84197C3.3241 9.04343 3.64052 9.05363 3.84197 8.86477L7.5 5.43536L11.158 8.86477C11.3595 9.05363 11.6759 9.04343 11.8648 8.84197C12.0536 8.64051 12.0434 8.32409 11.842 8.13523L7.84197 4.38523C7.64964 4.20492 7.35036 4.20492 7.15803 4.38523L3.15803 8.13523C2.95657 8.32409 2.94637 8.64051 3.13523 8.84197Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),rz=["color"],yT=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,rz);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),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:r,fillRule:"evenodd",clipRule:"evenodd"}))}),oz=["color"],iz=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,oz);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M9.875 7.5C9.875 8.81168 8.81168 9.875 7.5 9.875C6.18832 9.875 5.125 8.81168 5.125 7.5C5.125 6.18832 6.18832 5.125 7.5 5.125C8.81168 5.125 9.875 6.18832 9.875 7.5Z",fill:r}))}),sz=["color"],az=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,sz);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M10 6.5C10 8.433 8.433 10 6.5 10C4.567 10 3 8.433 3 6.5C3 4.567 4.567 3 6.5 3C8.433 3 10 4.567 10 6.5ZM9.30884 10.0159C8.53901 10.6318 7.56251 11 6.5 11C4.01472 11 2 8.98528 2 6.5C2 4.01472 4.01472 2 6.5 2C8.98528 2 11 4.01472 11 6.5C11 7.56251 10.6318 8.53901 10.0159 9.30884L12.8536 12.1464C13.0488 12.3417 13.0488 12.6583 12.8536 12.8536C12.6583 13.0488 12.3417 13.0488 12.1464 12.8536L9.30884 10.0159Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),lz=["color"],cz=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,lz);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M3.24182 2.32181C3.3919 2.23132 3.5784 2.22601 3.73338 2.30781L12.7334 7.05781C12.8974 7.14436 13 7.31457 13 7.5C13 7.68543 12.8974 7.85564 12.7334 7.94219L3.73338 12.6922C3.5784 12.774 3.3919 12.7687 3.24182 12.6782C3.09175 12.5877 3 12.4252 3 12.25V2.75C3 2.57476 3.09175 2.4123 3.24182 2.32181ZM4 3.57925V11.4207L11.4288 7.5L4 3.57925Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),uz=["color"],dz=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,uz);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M7 2H1.5C1.22386 2 1 2.22386 1 2.5V7H7V2ZM8 2V7H14V2.5C14 2.22386 13.7761 2 13.5 2H8ZM7 8H1V12.5C1 12.7761 1.22386 13 1.5 13H7V8ZM8 13V8H14V12.5C14 12.7761 13.7761 13 13.5 13H8ZM1.5 1C0.671573 1 0 1.67157 0 2.5V12.5C0 13.3284 0.671573 14 1.5 14H13.5C14.3284 14 15 13.3284 15 12.5V2.5C15 1.67157 14.3284 1 13.5 1H1.5Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),fz=["color"],pz=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,fz);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M1.5 2H13.5C13.7761 2 14 2.22386 14 2.5V7H1V2.5C1 2.22386 1.22386 2 1.5 2ZM1 8V12.5C1 12.7761 1.22386 13 1.5 13H13.5C13.7761 13 14 12.7761 14 12.5V8H1ZM0 2.5C0 1.67157 0.671573 1 1.5 1H13.5C14.3284 1 15 1.67157 15 2.5V12.5C15 13.3284 14.3284 14 13.5 14H1.5C0.671573 14 0 13.3284 0 12.5V2.5Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))});function Y(){return Y=Object.assign?Object.assign.bind():function(e){for(var t=1;te.forEach(n=>hz(n,t))}function Be(...e){return f.useCallback(Am(...e),e)}const Wo=f.forwardRef((e,t)=>{const{children:n,...r}=e,o=f.Children.toArray(n),i=o.find(mz);if(i){const s=i.props.children,l=o.map(u=>u===i?f.Children.count(s)>1?f.Children.only(null):f.isValidElement(s)?s.props.children:null:u);return f.createElement(Qy,Y({},r,{ref:t}),f.isValidElement(s)?f.cloneElement(s,void 0,l):null)}return f.createElement(Qy,Y({},r,{ref:t}),n)});Wo.displayName="Slot";const Qy=f.forwardRef((e,t)=>{const{children:n,...r}=e;return f.isValidElement(n)?f.cloneElement(n,{...gz(r,n.props),ref:t?Am(t,n.ref):n.ref}):f.Children.count(n)>1?f.Children.only(null):null});Qy.displayName="SlotClone";const sx=({children:e})=>f.createElement(f.Fragment,null,e);function mz(e){return f.isValidElement(e)&&e.type===sx}function gz(e,t){const n={...t};for(const r in t){const o=e[r],i=t[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...l)=>{i(...l),o(...l)}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...e,...n}}const bC=e=>typeof e=="boolean"?"".concat(e):e===0?"0":e,_C=BR,Om=(e,t)=>n=>{var r;if((t==null?void 0:t.variants)==null)return _C(e,n==null?void 0:n.class,n==null?void 0:n.className);const{variants:o,defaultVariants:i}=t,s=Object.keys(o).map(d=>{const h=n==null?void 0:n[d],m=i==null?void 0:i[d];if(h===null)return null;const g=bC(h)||bC(m);return o[d][g]}),l=n&&Object.entries(n).reduce((d,h)=>{let[m,g]=h;return g===void 0||(d[m]=g),d},{}),u=t==null||(r=t.compoundVariants)===null||r===void 0?void 0:r.reduce((d,h)=>{let{class:m,className:g,...y}=h;return Object.entries(y).every(x=>{let[_,C]=x;return Array.isArray(C)?C.includes({...i,...l}[_]):{...i,...l}[_]===C})?[...d,m,g]:d},[]);return _C(e,s,u,n==null?void 0:n.class,n==null?void 0:n.className)};var vz={VITE_BACKEND:"http://127.0.0.1:8080",BASE_URL:"/",MODE:"production",DEV:!1,PROD:!0,SSR:!1};function yz(e,t){let n;try{n=e()}catch{return}return{getItem:o=>{var i;const s=u=>u===null?null:JSON.parse(u,t==null?void 0:t.reviver),l=(i=n.getItem(o))!=null?i:null;return l instanceof Promise?l.then(s):s(l)},setItem:(o,i)=>n.setItem(o,JSON.stringify(i,t==null?void 0:t.replacer)),removeItem:o=>n.removeItem(o)}}const qu=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then(r){return qu(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return qu(r)(n)}}}},wz=(e,t)=>(n,r,o)=>{let i={getStorage:()=>localStorage,serialize:JSON.stringify,deserialize:JSON.parse,partialize:C=>C,version:0,merge:(C,S)=>({...S,...C}),...t},s=!1;const l=new Set,u=new Set;let d;try{d=i.getStorage()}catch{}if(!d)return e((...C)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),n(...C)},r,o);const h=qu(i.serialize),m=()=>{const C=i.partialize({...r()});let S;const b=h({state:C,version:i.version}).then(E=>d.setItem(i.name,E)).catch(E=>{S=E});if(S)throw S;return b},g=o.setState;o.setState=(C,S)=>{g(C,S),m()};const y=e((...C)=>{n(...C),m()},r,o);let x;const _=()=>{var C;if(!d)return;s=!1,l.forEach(b=>b(r()));const S=((C=i.onRehydrateStorage)==null?void 0:C.call(i,r()))||void 0;return qu(d.getItem.bind(d))(i.name).then(b=>{if(b)return i.deserialize(b)}).then(b=>{if(b)if(typeof b.version=="number"&&b.version!==i.version){if(i.migrate)return i.migrate(b.state,b.version);console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return b.state}).then(b=>{var E;return x=i.merge(b,(E=r())!=null?E:y),n(x,!0),m()}).then(()=>{S==null||S(x,void 0),s=!0,u.forEach(b=>b(x))}).catch(b=>{S==null||S(void 0,b)})};return o.persist={setOptions:C=>{i={...i,...C},C.getStorage&&(d=C.getStorage())},clearStorage:()=>{d==null||d.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>_(),hasHydrated:()=>s,onHydrate:C=>(l.add(C),()=>{l.delete(C)}),onFinishHydration:C=>(u.add(C),()=>{u.delete(C)})},_(),x||y},xz=(e,t)=>(n,r,o)=>{let i={storage:yz(()=>localStorage),partialize:_=>_,version:0,merge:(_,C)=>({...C,..._}),...t},s=!1;const l=new Set,u=new Set;let d=i.storage;if(!d)return e((..._)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),n(..._)},r,o);const h=()=>{const _=i.partialize({...r()});return d.setItem(i.name,{state:_,version:i.version})},m=o.setState;o.setState=(_,C)=>{m(_,C),h()};const g=e((..._)=>{n(..._),h()},r,o);let y;const x=()=>{var _,C;if(!d)return;s=!1,l.forEach(b=>{var E;return b((E=r())!=null?E:g)});const S=((C=i.onRehydrateStorage)==null?void 0:C.call(i,(_=r())!=null?_:g))||void 0;return qu(d.getItem.bind(d))(i.name).then(b=>{if(b)if(typeof b.version=="number"&&b.version!==i.version){if(i.migrate)return i.migrate(b.state,b.version);console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return b.state}).then(b=>{var E;return y=i.merge(b,(E=r())!=null?E:g),n(y,!0),h()}).then(()=>{S==null||S(y,void 0),y=r(),s=!0,u.forEach(b=>b(y))}).catch(b=>{S==null||S(void 0,b)})};return o.persist={setOptions:_=>{i={...i,..._},_.storage&&(d=_.storage)},clearStorage:()=>{d==null||d.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>x(),hasHydrated:()=>s,onHydrate:_=>(l.add(_),()=>{l.delete(_)}),onFinishHydration:_=>(u.add(_),()=>{u.delete(_)})},i.skipHydration||x(),y||g},bz=(e,t)=>"getStorage"in t||"serialize"in t||"deserialize"in t?((vz?"production":void 0)!=="production"&&console.warn("[DEPRECATED] `getStorage`, `serialize` and `deserialize` options are deprecated. Use `storage` option instead."),wz(e,t)):xz(e,t),_z=bz;function Sz(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,o]of e)if(!Object.is(o,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{t(n,r,e)}):e.forEach((n,r)=>t(r,n,e))}function Mm(e){const t=e[wr];return t?t.type_:Array.isArray(e)?1:Nm(e)?2:Dm(e)?3:0}function Jy(e,t){return Mm(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function bT(e,t,n){const r=Mm(e);r===2?e.set(t,n):r===3?e.add(n):e[t]=n}function Cz(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function Nm(e){return e instanceof Map}function Dm(e){return e instanceof Set}function Js(e){return e.copy_||e.base_}function e1(e,t){if(Nm(e))return new Map(e);if(Dm(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);if(!t&&xT(e))return ec(e)?{...e}:Object.assign(Object.create(null),e);const n=Object.getOwnPropertyDescriptors(e);delete n[wr];let r=Reflect.ownKeys(n);for(let o=0;o1&&(e.set=e.add=e.clear=e.delete=$z),Object.freeze(e),t&&Qu(e,(n,r)=>ax(r,!0))),e}function $z(){ho(2)}function Im(e){return Object.isFrozen(e)}var kz={};function ka(e){const t=kz[e];return t||ho(0,e),t}var Ju;function _T(){return Ju}function Rz(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function EC(e,t){t&&(ka("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function t1(e){n1(e),e.drafts_.forEach(Tz),e.drafts_=null}function n1(e){e===Ju&&(Ju=e.parent_)}function CC(e){return Ju=Rz(Ju,e)}function Tz(e){const t=e[wr];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function $C(e,t){t.unfinalizedDrafts_=t.drafts_.length;const n=t.drafts_[0];return e!==void 0&&e!==n?(n[wr].modified_&&(t1(t),ho(4)),$a(e)&&(e=Ah(t,e),t.parent_||Oh(t,e)),t.patches_&&ka("Patches").generateReplacementPatches_(n[wr].base_,e,t.patches_,t.inversePatches_)):e=Ah(t,n,[]),t1(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==wT?e:void 0}function Ah(e,t,n){if(Im(t))return t;const r=t[wr];if(!r)return Qu(t,(o,i)=>kC(e,r,t,o,i,n)),t;if(r.scope_!==e)return t;if(!r.modified_)return Oh(e,r.base_,!0),r.base_;if(!r.finalized_){r.finalized_=!0,r.scope_.unfinalizedDrafts_--;const o=r.copy_;let i=o,s=!1;r.type_===3&&(i=new Set(o),o.clear(),s=!0),Qu(i,(l,u)=>kC(e,r,o,l,u,n,s)),Oh(e,o,!1),n&&e.patches_&&ka("Patches").generatePatches_(r,n,e.patches_,e.inversePatches_)}return r.copy_}function kC(e,t,n,r,o,i,s){if(tc(o)){const l=i&&t&&t.type_!==3&&!Jy(t.assigned_,r)?i.concat(r):void 0,u=Ah(e,o,l);if(bT(n,r,u),tc(u))e.canAutoFreeze_=!1;else return}else s&&n.add(o);if($a(o)&&!Im(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;Ah(e,o),(!t||!t.scope_.parent_)&&Oh(e,o)}}function Oh(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&ax(t,n)}function Pz(e,t){const n=Array.isArray(e),r={type_:n?1:0,scope_:t?t.scope_:_T(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1};let o=r,i=lx;n&&(o=[r],i=ed);const{revoke:s,proxy:l}=Proxy.revocable(o,i);return r.draft_=l,r.revoke_=s,l}var lx={get(e,t){if(t===wr)return e;const n=Js(e);if(!Jy(n,t))return Az(e,n,t);const r=n[t];return e.finalized_||!$a(r)?r:r===h0(e.base_,t)?(m0(e),e.copy_[t]=o1(r,e)):r},has(e,t){return t in Js(e)},ownKeys(e){return Reflect.ownKeys(Js(e))},set(e,t,n){const r=ST(Js(e),t);if(r!=null&&r.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){const o=h0(Js(e),t),i=o==null?void 0:o[wr];if(i&&i.base_===n)return e.copy_[t]=n,e.assigned_[t]=!1,!0;if(Cz(n,o)&&(n!==void 0||Jy(e.base_,t)))return!0;m0(e),r1(e)}return e.copy_[t]===n&&(n!==void 0||t in e.copy_)||Number.isNaN(n)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=n,e.assigned_[t]=!0),!0},deleteProperty(e,t){return h0(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,m0(e),r1(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){const n=Js(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:r.enumerable,value:n[t]}},defineProperty(){ho(11)},getPrototypeOf(e){return ec(e.base_)},setPrototypeOf(){ho(12)}},ed={};Qu(lx,(e,t)=>{ed[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});ed.deleteProperty=function(e,t){return ed.set.call(this,e,t,void 0)};ed.set=function(e,t,n){return lx.set.call(this,e[0],t,n,e[0])};function h0(e,t){const n=e[wr];return(n?Js(n):e)[t]}function Az(e,t,n){var o;const r=ST(t,n);return r?"value"in r?r.value:(o=r.get)==null?void 0:o.call(e.draft_):void 0}function ST(e,t){if(!(t in e))return;let n=ec(e);for(;n;){const r=Object.getOwnPropertyDescriptor(n,t);if(r)return r;n=ec(n)}}function r1(e){e.modified_||(e.modified_=!0,e.parent_&&r1(e.parent_))}function m0(e){e.copy_||(e.copy_=e1(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var Oz=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(t,n,r)=>{if(typeof t=="function"&&typeof n!="function"){const i=n;n=t;const s=this;return function(u=i,...d){return s.produce(u,h=>n.call(this,h,...d))}}typeof n!="function"&&ho(6),r!==void 0&&typeof r!="function"&&ho(7);let o;if($a(t)){const i=CC(this),s=o1(t,void 0);let l=!0;try{o=n(s),l=!1}finally{l?t1(i):n1(i)}return EC(i,r),$C(o,i)}else if(!t||typeof t!="object"){if(o=n(t),o===void 0&&(o=t),o===wT&&(o=void 0),this.autoFreeze_&&ax(o,!0),r){const i=[],s=[];ka("Patches").generateReplacementPatches_(t,o,i,s),r(i,s)}return o}else ho(1,t)},this.produceWithPatches=(t,n)=>{if(typeof t=="function")return(s,...l)=>this.produceWithPatches(s,u=>t(u,...l));let r,o;return[this.produce(t,n,(s,l)=>{r=s,o=l}),r,o]},typeof(e==null?void 0:e.autoFreeze)=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof(e==null?void 0:e.useStrictShallowCopy)=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){$a(e)||ho(8),tc(e)&&(e=Mz(e));const t=CC(this),n=o1(e,void 0);return n[wr].isManual_=!0,n1(t),n}finishDraft(e,t){const n=e&&e[wr];(!n||!n.isManual_)&&ho(9);const{scope_:r}=n;return EC(r,t),$C(void 0,r)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let n;for(n=t.length-1;n>=0;n--){const o=t[n];if(o.path.length===0&&o.op==="replace"){e=o.value;break}}n>-1&&(t=t.slice(n+1));const r=ka("Patches").applyPatches_;return tc(e)?r(e,t):this.produce(e,o=>r(o,t))}};function o1(e,t){const n=Nm(e)?ka("MapSet").proxyMap_(e,t):Dm(e)?ka("MapSet").proxySet_(e,t):Pz(e,t);return(t?t.scope_:_T()).drafts_.push(n),n}function Mz(e){return tc(e)||ho(10,e),ET(e)}function ET(e){if(!$a(e)||Im(e))return e;const t=e[wr];let n;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=e1(e,t.scope_.immer_.useStrictShallowCopy_)}else n=e1(e,!0);return Qu(n,(r,o)=>{bT(n,r,ET(o))}),t&&(t.finalized_=!1),n}var xr=new Oz,Nz=xr.produce;xr.produceWithPatches.bind(xr);xr.setAutoFreeze.bind(xr);xr.setUseStrictShallowCopy.bind(xr);xr.applyPatches.bind(xr);xr.createDraft.bind(xr);xr.finishDraft.bind(xr);const Dz=e=>(t,n,r)=>(r.setState=(o,i,...s)=>{const l=typeof o=="function"?Nz(o):o;return t(l,i,...s)},e(r.setState,n,r)),Iz=Dz;var CT={exports:{}},$T={},kT={exports:{}},RT={};/** + * @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 nc=f;function Lz(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var Fz=typeof Object.is=="function"?Object.is:Lz,jz=nc.useState,zz=nc.useEffect,Bz=nc.useLayoutEffect,Uz=nc.useDebugValue;function Vz(e,t){var n=t(),r=jz({inst:{value:n,getSnapshot:t}}),o=r[0].inst,i=r[1];return Bz(function(){o.value=n,o.getSnapshot=t,g0(o)&&i({inst:o})},[e,n,t]),zz(function(){return g0(o)&&i({inst:o}),e(function(){g0(o)&&i({inst:o})})},[e]),Uz(n),n}function g0(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!Fz(e,n)}catch{return!0}}function Wz(e,t){return t()}var Hz=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?Wz:Vz;RT.useSyncExternalStore=nc.useSyncExternalStore!==void 0?nc.useSyncExternalStore:Hz;kT.exports=RT;var Kz=kT.exports;/** + * @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 Lm=f,Yz=Kz;function Gz(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var Xz=typeof Object.is=="function"?Object.is:Gz,Zz=Yz.useSyncExternalStore,qz=Lm.useRef,Qz=Lm.useEffect,Jz=Lm.useMemo,eB=Lm.useDebugValue;$T.useSyncExternalStoreWithSelector=function(e,t,n,r,o){var i=qz(null);if(i.current===null){var s={hasValue:!1,value:null};i.current=s}else s=i.current;i=Jz(function(){function u(y){if(!d){if(d=!0,h=y,y=r(y),o!==void 0&&s.hasValue){var x=s.value;if(o(x,y))return m=x}return m=y}if(x=m,Xz(h,y))return x;var _=r(y);return o!==void 0&&o(x,_)?x:(h=y,m=_)}var d=!1,h,m,g=n===void 0?null:n;return[function(){return u(t())},g===null?void 0:function(){return u(g())}]},[t,n,r,o]);var l=Zz(e,i[0],i[1]);return Qz(function(){s.hasValue=!0,s.value=l},[l]),eB(l),l};CT.exports=$T;var tB=CT.exports;const nB=lm(tB);var rB={VITE_BACKEND:"http://127.0.0.1:8080",BASE_URL:"/",MODE:"production",DEV:!1,PROD:!0,SSR:!1};const RC=e=>{let t;const n=new Set,r=(u,d)=>{const h=typeof u=="function"?u(t):u;if(!Object.is(h,t)){const m=t;t=d??typeof h!="object"?h:Object.assign({},t,h),n.forEach(g=>g(t,m))}},o=()=>t,l={setState:r,getState:o,subscribe:u=>(n.add(u),()=>n.delete(u)),destroy:()=>{(rB?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),n.clear()}};return t=e(r,o,l),l},oB=e=>e?RC(e):RC,{useDebugValue:iB}=Fe,{useSyncExternalStoreWithSelector:sB}=nB;function aB(e,t=e.getState,n){const r=sB(e.subscribe,e.getState,e.getServerState||e.getState,t,n);return iB(r),r}const TC=(e,t)=>{const n=oB(e),r=(o,i=t)=>aB(n,o,i);return Object.assign(r,n),r},lB=(e,t)=>e?TC(e,t):TC,cB=1,uB=1e6;let v0=0;function dB(){return v0=(v0+1)%Number.MAX_VALUE,v0.toString()}const y0=new Map,PC=e=>{if(y0.has(e))return;const t=setTimeout(()=>{y0.delete(e),Tu({type:"REMOVE_TOAST",toastId:e})},uB);y0.set(e,t)},fB=(e,t)=>{switch(t.type){case"ADD_TOAST":return{...e,toasts:[t.toast,...e.toasts].slice(0,cB)};case"UPDATE_TOAST":return{...e,toasts:e.toasts.map(n=>n.id===t.toast.id?{...n,...t.toast}:n)};case"DISMISS_TOAST":{const{toastId:n}=t;return n?PC(n):e.toasts.forEach(r=>{PC(r.id)}),{...e,toasts:e.toasts.map(r=>r.id===n||n===void 0?{...r,open:!1}:r)}}case"REMOVE_TOAST":return t.toastId===void 0?{...e,toasts:[]}:{...e,toasts:e.toasts.filter(n=>n.id!==t.toastId)}}},Bp=[];let Up={toasts:[]};function Tu(e){Up=fB(Up,e),Bp.forEach(t=>{t(Up)})}function rl({...e}){const t=dB(),n=o=>Tu({type:"UPDATE_TOAST",toast:{...o,id:t}}),r=()=>Tu({type:"DISMISS_TOAST",toastId:t});return Tu({type:"ADD_TOAST",toast:{...e,id:t,open:!0,onOpenChange:o=>{o||r()}}}),{id:t,dismiss:r,update:n}}function Td(){const[e,t]=f.useState(Up);return f.useEffect(()=>(Bp.push(t),()=>{const n=Bp.indexOf(t);n>-1&&Bp.splice(n,1)}),[e]),{...e,toast:rl,dismiss:n=>Tu({type:"DISMISS_TOAST",toastId:n})}}const Zs={file:null,paintByExampleFile:null,customMask:null,imageHeight:0,imageWidth:0,isInpainting:!1,isPluginRunning:!1,isAdjustingMask:!1,disableShortCuts:!1,windowSize:{height:600,width:800},editorState:{baseBrushSize:sF,brushSizeScale:1,renders:[],extraMasks:[],prevExtraMasks:[],temporaryMasks:[],lineGroups:[],lastLineGroup:[],curLineGroup:[],redoRenders:[],redoCurLines:[],redoLineGroups:[]},interactiveSegState:{isInteractiveSeg:!1,tmpInteractiveSegMask:null,clicks:[]},cropperState:{x:0,y:0,width:512,height:512},extenderState:{x:0,y:0,width:512,height:512},isCropperExtenderResizing:!1,fileManagerState:{sortBy:xs.CTIME,sortOrder:$u.DESCENDING,layout:"masonry",searchText:"",inputDirectory:"",outputDirectory:""},serverConfig:{plugins:[],enableFileManager:!1,enableAutoSaving:!1,enableControlnet:!1,controlnetMethod:"lllyasviel/control_v11p_sd15_canny",disableModelSwitch:!1,isDesktop:!1,samplers:["DPM++ 2M"]},settings:{model:{name:"lama",path:"lama",model_type:"inpaint",support_controlnet:!1,support_strength:!1,support_outpainting:!1,controlnets:[],support_freeu:!1,support_lcm_lora:!1,is_single_file_diffusers:!1,need_prompt:!1},enableControlnet:!1,showCropper:!1,showExtender:!1,extenderDirection:In.xy,enableDownloadMask:!1,enableManualInpainting:!1,enableUploadMask:!1,enableAutoExtractPrompt:!0,ldmSteps:30,ldmSampler:Zw.ddim,zitsWireframe:!0,cv2Radius:5,cv2Flag:qw.INPAINT_NS,prompt:"",negativePrompt:uF,seed:42,seedFixed:!1,sdMaskBlur:35,sdStrength:1,sdSteps:50,sdGuidanceScale:7.5,sdSampler:"DPM++ 2M",sdMatchHistograms:!1,sdScale:1,p2pImageGuidanceScale:1.5,controlnetConditioningScale:.4,controlnetMethod:"lllyasviel/control_v11p_sd15_canny",enableLCMLora:!1,enableFreeu:!1,freeuConfig:{s1:.9,s2:.2,b1:1.2,b2:1.4},powerpaintTask:kl.text_guided,adjustMaskKernelSize:12}},bt=lB()(_z(Iz((e,t)=>({...Zs,showPrevMask:async()=>{if(t().settings.showExtender)return;const{lastLineGroup:n,curLineGroup:r,prevExtraMasks:o,extraMasks:i}=t().editorState;if(r.length!==0||i.length!==0)return;const{imageWidth:s,imageHeight:l}=t(),u=Lp(s,l,[n],o,Ky);try{const d=await aC(u);e(h=>{h.editorState.temporaryMasks.push(d)})}catch(d){console.error(d);return}},hidePrevMask:()=>{e(n=>{n.editorState.temporaryMasks=[]})},getCurrentTargetFile:async()=>{const n=t().file,r=t().editorState.renders;let o=n;if(r.length>0){const i=r[r.length-1];o=await ku(i.currentSrc,n.name,n.type)}return o},runInpainting:async()=>{const{isInpainting:n,file:r,paintByExampleFile:o,imageWidth:i,imageHeight:s,settings:l,cropperState:u,extenderState:d}=t();if(n||r===null||t().settings.model.support_outpainting&&l.showExtender&&d.height===s&&d.width===i)return;const{lastLineGroup:h,curLineGroup:m,lineGroups:g,renders:y,prevExtraMasks:x,extraMasks:_}=t().editorState,C=m.length===0&&_.length===0&&!l.showExtender;let S=[],b=[];if(C===!0?(b=h,S=x):(b=m,S=_),b.length===0&&S===null&&!l.showExtender){rl({variant:"destructive",description:"Please draw mask on picture"});return}const E=[...g,b];e(M=>{M.isInpainting=!0});let k=r;if(C===!0){if(y.length>1){const M=y[y.length-2];k=await ku(M.currentSrc,r.name,r.type)}}else if(y.length>0){const M=y[y.length-1];k=await ku(M.currentSrc,r.name,r.type)}const P=Lp(i,s,[b],S);if(C){const M=await aC(P);e(A=>{A.editorState.temporaryMasks=[M]})}try{const M=await Lj(k,l,u,d,sC(P.toDataURL()),o),{blob:A,seed:O}=M;O&&t().setSeed(parseInt(O,10));const F=new Image;await Ip(F,A);const V=[...y,F];t().setImageSize(F.width,F.height),t().updateEditorState({renders:V,lineGroups:E,lastLineGroup:b,curLineGroup:[],extraMasks:[],prevExtraMasks:S})}catch(M){rl({variant:"destructive",description:M.message?M.message:M.toString()})}t().resetRedoState(),e(M=>{M.isInpainting=!1,M.editorState.temporaryMasks=[]})},runRenderablePlugin:async(n,r,o={upscale:1})=>{const{renders:i,lineGroups:s}=t().editorState;e(l=>{l.isPluginRunning=!0});try{const l=new Date,u=await t().getCurrentTargetFile(),d=await gT(n,r,u,o.upscale),{blob:h}=d;if(n){const y=new Image;await Ip(y,h),e(x=>{x.editorState.extraMasks.push(y)})}else{const y=new Image;await Ip(y,h),t().setImageSize(y.width,y.height);const x=[...i,y],_=[...s,[]];t().updateEditorState({renders:x,lineGroups:_})}const g=new Date().getTime()-l.getTime();rl({description:`Run ${r} successfully in ${g/1e3}s`})}catch(l){rl({variant:"destructive",description:l.message?l.message:l.toString()})}e(l=>{l.isPluginRunning=!1})},updateEditorState:n=>{e(r=>{r.editorState={...r.editorState,...n}})},cleanCurLineGroup:()=>{t().updateEditorState({curLineGroup:[]})},handleCanvasMouseDown:n=>{let r=[];const o=t();o.runMannually()&&(r=[...o.editorState.curLineGroup]),r.push({size:o.getBrushSize(),pts:[n]}),e(i=>{i.editorState.curLineGroup=r})},handleCanvasMouseMove:n=>{e(r=>{const o=r.editorState.curLineGroup;o.length&&o[o.length-1].pts.push(n)})},runMannually:()=>{const n=t();return n.settings.enableManualInpainting||n.settings.model.model_type!==is},getIsProcessing:()=>t().isInpainting||t().isPluginRunning||t().isAdjustingMask,isSD:()=>t().settings.model.model_type!==is,undoDisabled:()=>{const n=t().editorState;if(n.renders.length>0)return!1;if(t().runMannually()){if(n.curLineGroup.length===0)return!0}else if(n.renders.length===0)return!0;return!1},undo:()=>{t().runMannually()&&t().editorState.curLineGroup.length!==0?e(n=>{const r=n.editorState;if(r.curLineGroup.length===0)return;r.lastLineGroup=[];const o=r.curLineGroup.pop();r.redoCurLines.push(o)}):e(n=>{const r=n.editorState;if(r.renders.length===0||r.lineGroups.length===0)return;const o=r.lineGroups.pop();r.redoLineGroups.push(o),r.redoCurLines=[],r.curLineGroup=[];const i=r.renders.pop();r.redoRenders.push(i)})},redoDisabled:()=>{const n=t().editorState;if(n.redoRenders.length>0)return!1;if(t().runMannually()){if(n.redoCurLines.length===0)return!0}else if(n.redoRenders.length===0)return!0;return!1},redo:()=>{t().runMannually()&&t().editorState.redoCurLines.length!==0?e(n=>{const r=n.editorState;if(r.redoCurLines.length===0)return;const o=r.redoCurLines.pop();r.curLineGroup.push(o)}):e(n=>{const r=n.editorState;if(r.redoRenders.length===0||r.redoLineGroups.length===0)return;const o=r.redoLineGroups.pop();r.lineGroups.push(o),r.curLineGroup=[];const i=r.redoRenders.pop();r.renders.push(i)})},resetRedoState:()=>{e(n=>{n.editorState.redoCurLines=[],n.editorState.redoLineGroups=[],n.editorState.redoRenders=[]})},updateAppState:n=>{e(()=>n)},getBrushSize:()=>t().editorState.baseBrushSize*t().editorState.brushSizeScale,showPromptInput:()=>{const n=t().settings.model;return n.model_type!==is&&n.name!==YR},setServerConfig:n=>{e(r=>{r.serverConfig=n,r.settings.enableControlnet=n.enableControlnet,r.settings.controlnetMethod=n.controlnetMethod})},updateSettings:n=>{e(r=>{r.settings={...r.settings,...n}})},setModel:n=>{e(r=>{r.settings.model=n,n.support_controlnet&&!n.controlnets.includes(r.settings.controlnetMethod)&&(r.settings.controlnetMethod=n.controlnets[0])})},updateFileManagerState:n=>{e(r=>{r.fileManagerState={...r.fileManagerState,...n}})},updateInteractiveSegState:n=>{e(r=>({...r,interactiveSegState:{...r.interactiveSegState,...n}}))},resetInteractiveSegState:()=>{t().updateInteractiveSegState(Zs.interactiveSegState)},handleInteractiveSegAccept:()=>{e(n=>{n.interactiveSegState.tmpInteractiveSegMask&&n.editorState.extraMasks.push(n.interactiveSegState.tmpInteractiveSegMask),n.interactiveSegState={...Zs.interactiveSegState}})},setIsInpainting:n=>e(r=>{r.isInpainting=n}),setFile:async n=>{if(t().settings.enableAutoExtractPrompt)try{const r=await Hj(n);r.prompt&&e(o=>{o.settings.prompt=r.prompt}),r.negative_prompt&&e(o=>{o.settings.negativePrompt=r.negative_prompt})}catch(r){rl({variant:"destructive",description:r.message?r.message:r.toString()})}e(r=>{r.file=n,r.interactiveSegState=Zs.interactiveSegState,r.editorState=Zs.editorState,r.cropperState=Zs.cropperState})},setCustomFile:n=>e(r=>{r.customMask=n}),setBaseBrushSize:n=>e(r=>{r.editorState.baseBrushSize=n}),setImageSize:(n,r)=>{e(o=>{o.imageWidth=n,o.imageHeight=r,o.editorState.brushSizeScale=Math.max(Math.min(n,r),512)/512}),t().resetExtender(n,r)},setCropperX:n=>e(r=>{r.cropperState.x=n}),setCropperY:n=>e(r=>{r.cropperState.y=n}),setCropperWidth:n=>e(r=>{r.cropperState.width=n}),setCropperHeight:n=>e(r=>{r.cropperState.height=n}),setExtenderX:n=>e(r=>{r.extenderState.x=n}),setExtenderY:n=>e(r=>{r.extenderState.y=n}),setExtenderWidth:n=>e(r=>{r.extenderState.width=n}),setExtenderHeight:n=>e(r=>{r.extenderState.height=n}),setIsCropperExtenderResizing:n=>e(r=>{r.isCropperExtenderResizing=n}),updateExtenderDirection:n=>{console.log(`updateExtenderDirection: ${JSON.stringify(t().extenderState)}`),e(r=>{r.settings.extenderDirection=n,r.extenderState.x=0,r.extenderState.y=0,r.extenderState.width=r.imageWidth,r.extenderState.height=r.imageHeight}),t().updateExtenderByBuiltIn(n,1.5)},updateExtenderByBuiltIn:(n,r)=>{const o={...Zs.extenderState};let{x:i,y:s,width:l,height:u}=o;const{imageWidth:d,imageHeight:h}=t();switch(l=d,u=h,n){case In.x:i=-Math.ceil(d*(r-1)/2),l=Math.ceil(d*r);break;case In.y:s=-Math.ceil(h*(r-1)/2),u=Math.ceil(h*r);break;case In.xy:i=-Math.ceil(d*(r-1)/2),s=-Math.ceil(h*(r-1)/2),l=Math.ceil(d*r),u=Math.ceil(h*r);break}e(m=>{m.extenderState.x=i,m.extenderState.y=s,m.extenderState.width=l,m.extenderState.height=u})},resetExtender:(n,r)=>{e(o=>{o.extenderState.x=0,o.extenderState.y=0,o.extenderState.width=n,o.extenderState.height=r})},setSeed:n=>e(r=>{r.settings.seed=n}),adjustMask:async n=>{const{imageWidth:r,imageHeight:o}=t(),{curLineGroup:i,extraMasks:s}=t().editorState,{adjustMaskKernelSize:l}=t().settings;if(i.length===0&&s.length===0)return;e(g=>{g.isAdjustingMask=!0});const u=Lp(r,o,[i],s,Ky),d=sC(u.toDataURL()),h=await Kj(d,n,l),m=await fF(h);e(g=>{g.editorState.extraMasks=[m],g.editorState.curLineGroup=[]}),e(g=>{g.isAdjustingMask=!1})},clearMask:()=>{e(n=>{n.editorState.extraMasks=[],n.editorState.curLineGroup=[]})}})),{name:"ZUSTAND_STATE",version:1,partialize:e=>Object.fromEntries(Object.entries(e).filter(([t])=>["fileManagerState","settings"].includes(t)))}),Sz),Pd=f.forwardRef(({className:e,type:t,...n},r)=>{const o=bt(l=>l.updateAppState),i=()=>{o({disableShortCuts:!0})},s=()=>{o({disableShortCuts:!1})};return v.jsx("input",{type:t,className:Ce("flex h-8 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",e),ref:r,autoComplete:"off",tabIndex:-1,onFocus:i,onBlur:s,...n})});Pd.displayName="Input";const Gn=f.forwardRef(({numberValue:e,allowFloat:t,onNumberValueChange:n,...r},o)=>{const[i,s]=f.useState(e.toString());f.useEffect(()=>{i!==e.toString()+"."&&s(e.toString())},[e]);const l=u=>{let h=u.target.value;if(t){if(h=h.replace(/[^0-9.]/g,"").replace(/(\..*?)\..*/g,"$1"),h.length===0){n(0);return}n(parseFloat(h))}else{if(h=h.replace(/\D/g,""),h.length===0){n(0);return}n(parseInt(h,10))}s(h)};return v.jsx(Pd,{ref:o,value:i,onInput:l,...r})});function ue(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 pB(e,t){const n=f.createContext(t);function r(i){const{children:s,...l}=i,u=f.useMemo(()=>l,Object.values(l));return f.createElement(n.Provider,{value:u},s)}function o(i){const s=f.useContext(n);if(s)return s;if(t!==void 0)return t;throw new Error(`\`${i}\` must be used within \`${e}\``)}return r.displayName=e+"Provider",[r,o]}function An(e,t=[]){let n=[];function r(i,s){const l=f.createContext(s),u=n.length;n=[...n,s];function d(m){const{scope:g,children:y,...x}=m,_=(g==null?void 0:g[e][u])||l,C=f.useMemo(()=>x,Object.values(x));return f.createElement(_.Provider,{value:C},y)}function h(m,g){const y=(g==null?void 0:g[e][u])||l,x=f.useContext(y);if(x)return x;if(s!==void 0)return s;throw new Error(`\`${m}\` must be used within \`${i}\``)}return d.displayName=i+"Provider",[d,h]}const o=()=>{const i=n.map(s=>f.createContext(s));return function(l){const u=(l==null?void 0:l[e])||i;return f.useMemo(()=>({[`__scope${e}`]:{...l,[e]:u}}),[l,u])}};return o.scopeName=e,[r,hB(o,...t)]}function hB(...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(i){const s=r.reduce((l,{useScope:u,scopeName:d})=>{const m=u(i)[`__scope${d}`];return{...l,...m}},{});return f.useMemo(()=>({[`__scope${t.scopeName}`]:s}),[s])}};return n.scopeName=t.scopeName,n}const mB=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","span","svg","ul"],Pe=mB.reduce((e,t)=>{const n=f.forwardRef((r,o)=>{const{asChild:i,...s}=r,l=i?Wo:t;return f.useEffect(()=>{window[Symbol.for("radix-ui")]=!0},[]),f.createElement(l,Y({},s,{ref:o}))});return n.displayName=`Primitive.${t}`,{...e,[t]:n}},{});function cx(e,t){e&&Os.flushSync(()=>e.dispatchEvent(t))}function Ft(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)},[])}function gB(e,t=globalThis==null?void 0:globalThis.document){const n=Ft(e);f.useEffect(()=>{const r=o=>{o.key==="Escape"&&n(o)};return t.addEventListener("keydown",r),()=>t.removeEventListener("keydown",r)},[n,t])}const i1="dismissableLayer.update",vB="dismissableLayer.pointerDownOutside",yB="dismissableLayer.focusOutside";let AC;const TT=f.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),yc=f.forwardRef((e,t)=>{var n;const{disableOutsidePointerEvents:r=!1,onEscapeKeyDown:o,onPointerDownOutside:i,onFocusOutside:s,onInteractOutside:l,onDismiss:u,...d}=e,h=f.useContext(TT),[m,g]=f.useState(null),y=(n=m==null?void 0:m.ownerDocument)!==null&&n!==void 0?n:globalThis==null?void 0:globalThis.document,[,x]=f.useState({}),_=Be(t,O=>g(O)),C=Array.from(h.layers),[S]=[...h.layersWithOutsidePointerEventsDisabled].slice(-1),b=C.indexOf(S),E=m?C.indexOf(m):-1,k=h.layersWithOutsidePointerEventsDisabled.size>0,P=E>=b,M=xB(O=>{const F=O.target,V=[...h.branches].some(J=>J.contains(F));!P||V||(i==null||i(O),l==null||l(O),O.defaultPrevented||u==null||u())},y),A=bB(O=>{const F=O.target;[...h.branches].some(J=>J.contains(F))||(s==null||s(O),l==null||l(O),O.defaultPrevented||u==null||u())},y);return gB(O=>{E===h.layers.size-1&&(o==null||o(O),!O.defaultPrevented&&u&&(O.preventDefault(),u()))},y),f.useEffect(()=>{if(m)return r&&(h.layersWithOutsidePointerEventsDisabled.size===0&&(AC=y.body.style.pointerEvents,y.body.style.pointerEvents="none"),h.layersWithOutsidePointerEventsDisabled.add(m)),h.layers.add(m),OC(),()=>{r&&h.layersWithOutsidePointerEventsDisabled.size===1&&(y.body.style.pointerEvents=AC)}},[m,y,r,h]),f.useEffect(()=>()=>{m&&(h.layers.delete(m),h.layersWithOutsidePointerEventsDisabled.delete(m),OC())},[m,h]),f.useEffect(()=>{const O=()=>x({});return document.addEventListener(i1,O),()=>document.removeEventListener(i1,O)},[]),f.createElement(Pe.div,Y({},d,{ref:_,style:{pointerEvents:k?P?"auto":"none":void 0,...e.style},onFocusCapture:ue(e.onFocusCapture,A.onFocusCapture),onBlurCapture:ue(e.onBlurCapture,A.onBlurCapture),onPointerDownCapture:ue(e.onPointerDownCapture,M.onPointerDownCapture)}))}),wB=f.forwardRef((e,t)=>{const n=f.useContext(TT),r=f.useRef(null),o=Be(t,r);return f.useEffect(()=>{const i=r.current;if(i)return n.branches.add(i),()=>{n.branches.delete(i)}},[n.branches]),f.createElement(Pe.div,Y({},e,{ref:o}))});function xB(e,t=globalThis==null?void 0:globalThis.document){const n=Ft(e),r=f.useRef(!1),o=f.useRef(()=>{});return f.useEffect(()=>{const i=l=>{if(l.target&&!r.current){let h=function(){PT(vB,n,d,{discrete:!0})};var u=h;const d={originalEvent:l};l.pointerType==="touch"?(t.removeEventListener("click",o.current),o.current=h,t.addEventListener("click",o.current,{once:!0})):h()}else t.removeEventListener("click",o.current);r.current=!1},s=window.setTimeout(()=>{t.addEventListener("pointerdown",i)},0);return()=>{window.clearTimeout(s),t.removeEventListener("pointerdown",i),t.removeEventListener("click",o.current)}},[t,n]),{onPointerDownCapture:()=>r.current=!0}}function bB(e,t=globalThis==null?void 0:globalThis.document){const n=Ft(e),r=f.useRef(!1);return f.useEffect(()=>{const o=i=>{i.target&&!r.current&&PT(yB,n,{originalEvent:i},{discrete:!1})};return t.addEventListener("focusin",o),()=>t.removeEventListener("focusin",o)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function OC(){const e=new CustomEvent(i1);document.dispatchEvent(e)}function PT(e,t,n,{discrete:r}){const o=n.originalEvent.target,i=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&o.addEventListener(e,t,{once:!0}),r?cx(o,i):o.dispatchEvent(i)}const _B=yc,SB=wB,Pn=globalThis!=null&&globalThis.document?f.useLayoutEffect:()=>{},EB=jD.useId||(()=>{});let CB=0;function nr(e){const[t,n]=f.useState(EB());return Pn(()=>{e||n(r=>r??String(CB++))},[e]),e||(t?`radix-${t}`:"")}const $B=["top","right","bottom","left"],Cs=Math.min,pr=Math.max,Mh=Math.round,ip=Math.floor,$s=e=>({x:e,y:e}),kB={left:"right",right:"left",bottom:"top",top:"bottom"},RB={start:"end",end:"start"};function s1(e,t,n){return pr(e,Cs(t,n))}function yi(e,t){return typeof e=="function"?e(t):e}function wi(e){return e.split("-")[0]}function wc(e){return e.split("-")[1]}function ux(e){return e==="x"?"y":"x"}function dx(e){return e==="y"?"height":"width"}function xc(e){return["top","bottom"].includes(wi(e))?"y":"x"}function fx(e){return ux(xc(e))}function TB(e,t,n){n===void 0&&(n=!1);const r=wc(e),o=fx(e),i=dx(o);let s=o==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[i]>t.floating[i]&&(s=Nh(s)),[s,Nh(s)]}function PB(e){const t=Nh(e);return[a1(e),t,a1(t)]}function a1(e){return e.replace(/start|end/g,t=>RB[t])}function AB(e,t,n){const r=["left","right"],o=["right","left"],i=["top","bottom"],s=["bottom","top"];switch(e){case"top":case"bottom":return n?t?o:r:t?r:o;case"left":case"right":return t?i:s;default:return[]}}function OB(e,t,n,r){const o=wc(e);let i=AB(wi(e),n==="start",r);return o&&(i=i.map(s=>s+"-"+o),t&&(i=i.concat(i.map(a1)))),i}function Nh(e){return e.replace(/left|right|bottom|top/g,t=>kB[t])}function MB(e){return{top:0,right:0,bottom:0,left:0,...e}}function AT(e){return typeof e!="number"?MB(e):{top:e,right:e,bottom:e,left:e}}function Dh(e){return{...e,top:e.y,left:e.x,right:e.x+e.width,bottom:e.y+e.height}}function MC(e,t,n){let{reference:r,floating:o}=e;const i=xc(t),s=fx(t),l=dx(s),u=wi(t),d=i==="y",h=r.x+r.width/2-o.width/2,m=r.y+r.height/2-o.height/2,g=r[l]/2-o[l]/2;let y;switch(u){case"top":y={x:h,y:r.y-o.height};break;case"bottom":y={x:h,y:r.y+r.height};break;case"right":y={x:r.x+r.width,y:m};break;case"left":y={x:r.x-o.width,y:m};break;default:y={x:r.x,y:r.y}}switch(wc(t)){case"start":y[s]-=g*(n&&d?-1:1);break;case"end":y[s]+=g*(n&&d?-1:1);break}return y}const NB=async(e,t,n)=>{const{placement:r="bottom",strategy:o="absolute",middleware:i=[],platform:s}=n,l=i.filter(Boolean),u=await(s.isRTL==null?void 0:s.isRTL(t));let d=await s.getElementRects({reference:e,floating:t,strategy:o}),{x:h,y:m}=MC(d,r,u),g=r,y={},x=0;for(let _=0;_({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:o,rects:i,platform:s,elements:l,middlewareData:u}=t,{element:d,padding:h=0}=yi(e,t)||{};if(d==null)return{};const m=AT(h),g={x:n,y:r},y=fx(o),x=dx(y),_=await s.getDimensions(d),C=y==="y",S=C?"top":"left",b=C?"bottom":"right",E=C?"clientHeight":"clientWidth",k=i.reference[x]+i.reference[y]-g[y]-i.floating[x],P=g[y]-i.reference[y],M=await(s.getOffsetParent==null?void 0:s.getOffsetParent(d));let A=M?M[E]:0;(!A||!await(s.isElement==null?void 0:s.isElement(M)))&&(A=l.floating[E]||i.floating[x]);const O=k/2-P/2,F=A/2-_[x]/2-1,V=Cs(m[S],F),J=Cs(m[b],F),G=V,ae=A-_[x]-J,U=A/2-_[x]/2+O,te=s1(G,U,ae),L=!u.arrow&&wc(o)!=null&&U!=te&&i.reference[x]/2-(UG<=0)){var F,V;const G=(((F=i.flip)==null?void 0:F.index)||0)+1,ae=P[G];if(ae)return{data:{index:G,overflows:O},reset:{placement:ae}};let U=(V=O.filter(te=>te.overflows[0]<=0).sort((te,L)=>te.overflows[1]-L.overflows[1])[0])==null?void 0:V.placement;if(!U)switch(y){case"bestFit":{var J;const te=(J=O.map(L=>[L.placement,L.overflows.filter(ie=>ie>0).reduce((ie,K)=>ie+K,0)]).sort((L,ie)=>L[1]-ie[1])[0])==null?void 0:J[0];te&&(U=te);break}case"initialPlacement":U=l;break}if(o!==U)return{reset:{placement:U}}}return{}}}};function DC(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function IC(e){return $B.some(t=>e[t]>=0)}const IB=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n}=t,{strategy:r="referenceHidden",...o}=yi(e,t);switch(r){case"referenceHidden":{const i=await td(t,{...o,elementContext:"reference"}),s=DC(i,n.reference);return{data:{referenceHiddenOffsets:s,referenceHidden:IC(s)}}}case"escaped":{const i=await td(t,{...o,altBoundary:!0}),s=DC(i,n.floating);return{data:{escapedOffsets:s,escaped:IC(s)}}}default:return{}}}}};async function LB(e,t){const{placement:n,platform:r,elements:o}=e,i=await(r.isRTL==null?void 0:r.isRTL(o.floating)),s=wi(n),l=wc(n),u=xc(n)==="y",d=["left","top"].includes(s)?-1:1,h=i&&u?-1:1,m=yi(t,e);let{mainAxis:g,crossAxis:y,alignmentAxis:x}=typeof m=="number"?{mainAxis:m,crossAxis:0,alignmentAxis:null}:{mainAxis:0,crossAxis:0,alignmentAxis:null,...m};return l&&typeof x=="number"&&(y=l==="end"?x*-1:x),u?{x:y*h,y:g*d}:{x:g*d,y:y*h}}const FB=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){const{x:n,y:r}=t,o=await LB(t,e);return{x:n+o.x,y:r+o.y,data:o}}}},jB=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:o}=t,{mainAxis:i=!0,crossAxis:s=!1,limiter:l={fn:C=>{let{x:S,y:b}=C;return{x:S,y:b}}},...u}=yi(e,t),d={x:n,y:r},h=await td(t,u),m=xc(wi(o)),g=ux(m);let y=d[g],x=d[m];if(i){const C=g==="y"?"top":"left",S=g==="y"?"bottom":"right",b=y+h[C],E=y-h[S];y=s1(b,y,E)}if(s){const C=m==="y"?"top":"left",S=m==="y"?"bottom":"right",b=x+h[C],E=x-h[S];x=s1(b,x,E)}const _=l.fn({...t,[g]:y,[m]:x});return{..._,data:{x:_.x-n,y:_.y-r}}}}},zB=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:r,placement:o,rects:i,middlewareData:s}=t,{offset:l=0,mainAxis:u=!0,crossAxis:d=!0}=yi(e,t),h={x:n,y:r},m=xc(o),g=ux(m);let y=h[g],x=h[m];const _=yi(l,t),C=typeof _=="number"?{mainAxis:_,crossAxis:0}:{mainAxis:0,crossAxis:0,..._};if(u){const E=g==="y"?"height":"width",k=i.reference[g]-i.floating[E]+C.mainAxis,P=i.reference[g]+i.reference[E]-C.mainAxis;yP&&(y=P)}if(d){var S,b;const E=g==="y"?"width":"height",k=["top","left"].includes(wi(o)),P=i.reference[m]-i.floating[E]+(k&&((S=s.offset)==null?void 0:S[m])||0)+(k?0:C.crossAxis),M=i.reference[m]+i.reference[E]+(k?0:((b=s.offset)==null?void 0:b[m])||0)-(k?C.crossAxis:0);xM&&(x=M)}return{[g]:y,[m]:x}}}},BB=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){const{placement:n,rects:r,platform:o,elements:i}=t,{apply:s=()=>{},...l}=yi(e,t),u=await td(t,l),d=wi(n),h=wc(n),m=xc(n)==="y",{width:g,height:y}=r.floating;let x,_;d==="top"||d==="bottom"?(x=d,_=h===(await(o.isRTL==null?void 0:o.isRTL(i.floating))?"start":"end")?"left":"right"):(_=d,x=h==="end"?"top":"bottom");const C=y-u[x],S=g-u[_],b=!t.middlewareData.shift;let E=C,k=S;if(m){const M=g-u.left-u.right;k=h||b?Cs(S,M):M}else{const M=y-u.top-u.bottom;E=h||b?Cs(C,M):M}if(b&&!h){const M=pr(u.left,0),A=pr(u.right,0),O=pr(u.top,0),F=pr(u.bottom,0);m?k=g-2*(M!==0||A!==0?M+A:pr(u.left,u.right)):E=y-2*(O!==0||F!==0?O+F:pr(u.top,u.bottom))}await s({...t,availableWidth:k,availableHeight:E});const P=await o.getDimensions(i.floating);return g!==P.width||y!==P.height?{reset:{rects:!0}}:{}}}};function ks(e){return OT(e)?(e.nodeName||"").toLowerCase():"#document"}function vr(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Ci(e){var t;return(t=(OT(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function OT(e){return e instanceof Node||e instanceof vr(e).Node}function xi(e){return e instanceof Element||e instanceof vr(e).Element}function Ho(e){return e instanceof HTMLElement||e instanceof vr(e).HTMLElement}function LC(e){return typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof vr(e).ShadowRoot}function Ad(e){const{overflow:t,overflowX:n,overflowY:r,display:o}=Xr(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&!["inline","contents"].includes(o)}function UB(e){return["table","td","th"].includes(ks(e))}function px(e){const t=hx(),n=Xr(e);return n.transform!=="none"||n.perspective!=="none"||(n.containerType?n.containerType!=="normal":!1)||!t&&(n.backdropFilter?n.backdropFilter!=="none":!1)||!t&&(n.filter?n.filter!=="none":!1)||["transform","perspective","filter"].some(r=>(n.willChange||"").includes(r))||["paint","layout","strict","content"].some(r=>(n.contain||"").includes(r))}function VB(e){let t=rc(e);for(;Ho(t)&&!Fm(t);){if(px(t))return t;t=rc(t)}return null}function hx(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}function Fm(e){return["html","body","#document"].includes(ks(e))}function Xr(e){return vr(e).getComputedStyle(e)}function jm(e){return xi(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.pageXOffset,scrollTop:e.pageYOffset}}function rc(e){if(ks(e)==="html")return e;const t=e.assignedSlot||e.parentNode||LC(e)&&e.host||Ci(e);return LC(t)?t.host:t}function MT(e){const t=rc(e);return Fm(t)?e.ownerDocument?e.ownerDocument.body:e.body:Ho(t)&&Ad(t)?t:MT(t)}function nd(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const o=MT(e),i=o===((r=e.ownerDocument)==null?void 0:r.body),s=vr(o);return i?t.concat(s,s.visualViewport||[],Ad(o)?o:[],s.frameElement&&n?nd(s.frameElement):[]):t.concat(o,nd(o,[],n))}function NT(e){const t=Xr(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const o=Ho(e),i=o?e.offsetWidth:n,s=o?e.offsetHeight:r,l=Mh(n)!==i||Mh(r)!==s;return l&&(n=i,r=s),{width:n,height:r,$:l}}function mx(e){return xi(e)?e:e.contextElement}function Rl(e){const t=mx(e);if(!Ho(t))return $s(1);const n=t.getBoundingClientRect(),{width:r,height:o,$:i}=NT(t);let s=(i?Mh(n.width):n.width)/r,l=(i?Mh(n.height):n.height)/o;return(!s||!Number.isFinite(s))&&(s=1),(!l||!Number.isFinite(l))&&(l=1),{x:s,y:l}}const WB=$s(0);function DT(e){const t=vr(e);return!hx()||!t.visualViewport?WB:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function HB(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==vr(e)?!1:t}function Ra(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const o=e.getBoundingClientRect(),i=mx(e);let s=$s(1);t&&(r?xi(r)&&(s=Rl(r)):s=Rl(e));const l=HB(i,n,r)?DT(i):$s(0);let u=(o.left+l.x)/s.x,d=(o.top+l.y)/s.y,h=o.width/s.x,m=o.height/s.y;if(i){const g=vr(i),y=r&&xi(r)?vr(r):r;let x=g.frameElement;for(;x&&r&&y!==g;){const _=Rl(x),C=x.getBoundingClientRect(),S=Xr(x),b=C.left+(x.clientLeft+parseFloat(S.paddingLeft))*_.x,E=C.top+(x.clientTop+parseFloat(S.paddingTop))*_.y;u*=_.x,d*=_.y,h*=_.x,m*=_.y,u+=b,d+=E,x=vr(x).frameElement}}return Dh({width:h,height:m,x:u,y:d})}function KB(e){let{rect:t,offsetParent:n,strategy:r}=e;const o=Ho(n),i=Ci(n);if(n===i)return t;let s={scrollLeft:0,scrollTop:0},l=$s(1);const u=$s(0);if((o||!o&&r!=="fixed")&&((ks(n)!=="body"||Ad(i))&&(s=jm(n)),Ho(n))){const d=Ra(n);l=Rl(n),u.x=d.x+n.clientLeft,u.y=d.y+n.clientTop}return{width:t.width*l.x,height:t.height*l.y,x:t.x*l.x-s.scrollLeft*l.x+u.x,y:t.y*l.y-s.scrollTop*l.y+u.y}}function YB(e){return Array.from(e.getClientRects())}function IT(e){return Ra(Ci(e)).left+jm(e).scrollLeft}function GB(e){const t=Ci(e),n=jm(e),r=e.ownerDocument.body,o=pr(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),i=pr(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let s=-n.scrollLeft+IT(e);const l=-n.scrollTop;return Xr(r).direction==="rtl"&&(s+=pr(t.clientWidth,r.clientWidth)-o),{width:o,height:i,x:s,y:l}}function XB(e,t){const n=vr(e),r=Ci(e),o=n.visualViewport;let i=r.clientWidth,s=r.clientHeight,l=0,u=0;if(o){i=o.width,s=o.height;const d=hx();(!d||d&&t==="fixed")&&(l=o.offsetLeft,u=o.offsetTop)}return{width:i,height:s,x:l,y:u}}function ZB(e,t){const n=Ra(e,!0,t==="fixed"),r=n.top+e.clientTop,o=n.left+e.clientLeft,i=Ho(e)?Rl(e):$s(1),s=e.clientWidth*i.x,l=e.clientHeight*i.y,u=o*i.x,d=r*i.y;return{width:s,height:l,x:u,y:d}}function FC(e,t,n){let r;if(t==="viewport")r=XB(e,n);else if(t==="document")r=GB(Ci(e));else if(xi(t))r=ZB(t,n);else{const o=DT(e);r={...t,x:t.x-o.x,y:t.y-o.y}}return Dh(r)}function LT(e,t){const n=rc(e);return n===t||!xi(n)||Fm(n)?!1:Xr(n).position==="fixed"||LT(n,t)}function qB(e,t){const n=t.get(e);if(n)return n;let r=nd(e,[],!1).filter(l=>xi(l)&&ks(l)!=="body"),o=null;const i=Xr(e).position==="fixed";let s=i?rc(e):e;for(;xi(s)&&!Fm(s);){const l=Xr(s),u=px(s);!u&&l.position==="fixed"&&(o=null),(i?!u&&!o:!u&&l.position==="static"&&!!o&&["absolute","fixed"].includes(o.position)||Ad(s)&&!u&<(e,s))?r=r.filter(h=>h!==s):o=l,s=rc(s)}return t.set(e,r),r}function QB(e){let{element:t,boundary:n,rootBoundary:r,strategy:o}=e;const s=[...n==="clippingAncestors"?qB(t,this._c):[].concat(n),r],l=s[0],u=s.reduce((d,h)=>{const m=FC(t,h,o);return d.top=pr(m.top,d.top),d.right=Cs(m.right,d.right),d.bottom=Cs(m.bottom,d.bottom),d.left=pr(m.left,d.left),d},FC(t,l,o));return{width:u.right-u.left,height:u.bottom-u.top,x:u.left,y:u.top}}function JB(e){return NT(e)}function eU(e,t,n){const r=Ho(t),o=Ci(t),i=n==="fixed",s=Ra(e,!0,i,t);let l={scrollLeft:0,scrollTop:0};const u=$s(0);if(r||!r&&!i)if((ks(t)!=="body"||Ad(o))&&(l=jm(t)),r){const d=Ra(t,!0,i,t);u.x=d.x+t.clientLeft,u.y=d.y+t.clientTop}else o&&(u.x=IT(o));return{x:s.left+l.scrollLeft-u.x,y:s.top+l.scrollTop-u.y,width:s.width,height:s.height}}function jC(e,t){return!Ho(e)||Xr(e).position==="fixed"?null:t?t(e):e.offsetParent}function FT(e,t){const n=vr(e);if(!Ho(e))return n;let r=jC(e,t);for(;r&&UB(r)&&Xr(r).position==="static";)r=jC(r,t);return r&&(ks(r)==="html"||ks(r)==="body"&&Xr(r).position==="static"&&!px(r))?n:r||VB(e)||n}const tU=async function(e){let{reference:t,floating:n,strategy:r}=e;const o=this.getOffsetParent||FT,i=this.getDimensions;return{reference:eU(t,await o(n),r),floating:{x:0,y:0,...await i(n)}}};function nU(e){return Xr(e).direction==="rtl"}const rU={convertOffsetParentRelativeRectToViewportRelativeRect:KB,getDocumentElement:Ci,getClippingRect:QB,getOffsetParent:FT,getElementRects:tU,getClientRects:YB,getDimensions:JB,getScale:Rl,isElement:xi,isRTL:nU};function oU(e,t){let n=null,r;const o=Ci(e);function i(){clearTimeout(r),n&&n.disconnect(),n=null}function s(l,u){l===void 0&&(l=!1),u===void 0&&(u=1),i();const{left:d,top:h,width:m,height:g}=e.getBoundingClientRect();if(l||t(),!m||!g)return;const y=ip(h),x=ip(o.clientWidth-(d+m)),_=ip(o.clientHeight-(h+g)),C=ip(d),b={rootMargin:-y+"px "+-x+"px "+-_+"px "+-C+"px",threshold:pr(0,Cs(1,u))||1};let E=!0;function k(P){const M=P[0].intersectionRatio;if(M!==u){if(!E)return s();M?s(!1,M):r=setTimeout(()=>{s(!1,1e-7)},100)}E=!1}try{n=new IntersectionObserver(k,{...b,root:o.ownerDocument})}catch{n=new IntersectionObserver(k,b)}n.observe(e)}return s(!0),i}function iU(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:o=!0,ancestorResize:i=!0,elementResize:s=typeof ResizeObserver=="function",layoutShift:l=typeof IntersectionObserver=="function",animationFrame:u=!1}=r,d=mx(e),h=o||i?[...d?nd(d):[],...nd(t)]:[];h.forEach(S=>{o&&S.addEventListener("scroll",n,{passive:!0}),i&&S.addEventListener("resize",n)});const m=d&&l?oU(d,n):null;let g=-1,y=null;s&&(y=new ResizeObserver(S=>{let[b]=S;b&&b.target===d&&y&&(y.unobserve(t),cancelAnimationFrame(g),g=requestAnimationFrame(()=>{y&&y.observe(t)})),n()}),d&&!u&&y.observe(d),y.observe(t));let x,_=u?Ra(e):null;u&&C();function C(){const S=Ra(e);_&&(S.x!==_.x||S.y!==_.y||S.width!==_.width||S.height!==_.height)&&n(),_=S,x=requestAnimationFrame(C)}return n(),()=>{h.forEach(S=>{o&&S.removeEventListener("scroll",n),i&&S.removeEventListener("resize",n)}),m&&m(),y&&y.disconnect(),y=null,u&&cancelAnimationFrame(x)}}const sU=(e,t,n)=>{const r=new Map,o={platform:rU,...n},i={...o.platform,_c:r};return NB(e,t,{...o,platform:i})},aU=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:o}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?NC({element:r.current,padding:o}).fn(n):{}:r?NC({element:r,padding:o}).fn(n):{}}}};var Vp=typeof document<"u"?f.useLayoutEffect:f.useEffect;function Ih(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(!Ih(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(!{}.hasOwnProperty.call(t,o[r]))return!1;for(r=n;r--!==0;){const i=o[r];if(!(i==="_owner"&&e.$$typeof)&&!Ih(e[i],t[i]))return!1}return!0}return e!==e&&t!==t}function jT(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function zC(e,t){const n=jT(e);return Math.round(t*n)/n}function BC(e){const t=f.useRef(e);return Vp(()=>{t.current=e}),t}function lU(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:o,elements:{reference:i,floating:s}={},transform:l=!0,whileElementsMounted:u,open:d}=e,[h,m]=f.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[g,y]=f.useState(r);Ih(g,r)||y(r);const[x,_]=f.useState(null),[C,S]=f.useState(null),b=f.useCallback(L=>{L!=M.current&&(M.current=L,_(L))},[_]),E=f.useCallback(L=>{L!==A.current&&(A.current=L,S(L))},[S]),k=i||x,P=s||C,M=f.useRef(null),A=f.useRef(null),O=f.useRef(h),F=BC(u),V=BC(o),J=f.useCallback(()=>{if(!M.current||!A.current)return;const L={placement:t,strategy:n,middleware:g};V.current&&(L.platform=V.current),sU(M.current,A.current,L).then(ie=>{const K={...ie,isPositioned:!0};G.current&&!Ih(O.current,K)&&(O.current=K,Os.flushSync(()=>{m(K)}))})},[g,t,n,V]);Vp(()=>{d===!1&&O.current.isPositioned&&(O.current.isPositioned=!1,m(L=>({...L,isPositioned:!1})))},[d]);const G=f.useRef(!1);Vp(()=>(G.current=!0,()=>{G.current=!1}),[]),Vp(()=>{if(k&&(M.current=k),P&&(A.current=P),k&&P){if(F.current)return F.current(k,P,J);J()}},[k,P,J,F]);const ae=f.useMemo(()=>({reference:M,floating:A,setReference:b,setFloating:E}),[b,E]),U=f.useMemo(()=>({reference:k,floating:P}),[k,P]),te=f.useMemo(()=>{const L={position:n,left:0,top:0};if(!U.floating)return L;const ie=zC(U.floating,h.x),K=zC(U.floating,h.y);return l?{...L,transform:"translate("+ie+"px, "+K+"px)",...jT(U.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:ie,top:K}},[n,l,U.floating,h.x,h.y]);return f.useMemo(()=>({...h,update:J,refs:ae,elements:U,floatingStyles:te}),[h,J,ae,U,te])}function gx(e){const[t,n]=f.useState(void 0);return Pn(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(o=>{if(!Array.isArray(o)||!o.length)return;const i=o[0];let s,l;if("borderBoxSize"in i){const u=i.borderBoxSize,d=Array.isArray(u)?u[0]:u;s=d.inlineSize,l=d.blockSize}else s=e.offsetWidth,l=e.offsetHeight;n({width:s,height:l})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}const zT="Popper",[BT,Ns]=An(zT),[cU,UT]=BT(zT),uU=e=>{const{__scopePopper:t,children:n}=e,[r,o]=f.useState(null);return f.createElement(cU,{scope:t,anchor:r,onAnchorChange:o},n)},dU="PopperAnchor",fU=f.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...o}=e,i=UT(dU,n),s=f.useRef(null),l=Be(t,s);return f.useEffect(()=>{i.onAnchorChange((r==null?void 0:r.current)||s.current)}),r?null:f.createElement(Pe.div,Y({},o,{ref:l}))}),VT="PopperContent",[pU,pte]=BT(VT),hU=f.forwardRef((e,t)=>{var n,r,o,i,s,l,u,d;const{__scopePopper:h,side:m="bottom",sideOffset:g=0,align:y="center",alignOffset:x=0,arrowPadding:_=0,avoidCollisions:C=!0,collisionBoundary:S=[],collisionPadding:b=0,sticky:E="partial",hideWhenDetached:k=!1,updatePositionStrategy:P="optimized",onPlaced:M,...A}=e,O=UT(VT,h),[F,V]=f.useState(null),J=Be(t,Kt=>V(Kt)),[G,ae]=f.useState(null),U=gx(G),te=(n=U==null?void 0:U.width)!==null&&n!==void 0?n:0,L=(r=U==null?void 0:U.height)!==null&&r!==void 0?r:0,ie=m+(y!=="center"?"-"+y:""),K=typeof b=="number"?b:{top:0,right:0,bottom:0,left:0,...b},Q=Array.isArray(S)?S:[S],W=Q.length>0,le={padding:K,boundary:Q.filter(mU),altBoundary:W},{refs:ge,floatingStyles:Ve,placement:Ue,isPositioned:We,middlewareData:Me}=lU({strategy:"fixed",placement:ie,whileElementsMounted:(...Kt)=>iU(...Kt,{animationFrame:P==="always"}),elements:{reference:O.anchor},middleware:[FB({mainAxis:g+L,alignmentAxis:x}),C&&jB({mainAxis:!0,crossAxis:!1,limiter:E==="partial"?zB():void 0,...le}),C&&DB({...le}),BB({...le,apply:({elements:Kt,rects:Er,availableWidth:gt,availableHeight:js})=>{const{width:I,height:X}=Er.reference,Z=Kt.floating.style;Z.setProperty("--radix-popper-available-width",`${gt}px`),Z.setProperty("--radix-popper-available-height",`${js}px`),Z.setProperty("--radix-popper-anchor-width",`${I}px`),Z.setProperty("--radix-popper-anchor-height",`${X}px`)}}),G&&aU({element:G,padding:_}),gU({arrowWidth:te,arrowHeight:L}),k&&IB({strategy:"referenceHidden",...le})]}),[fe,xe]=WT(Ue),$e=Ft(M);Pn(()=>{We&&($e==null||$e())},[We,$e]);const Ae=(o=Me.arrow)===null||o===void 0?void 0:o.x,Oe=(i=Me.arrow)===null||i===void 0?void 0:i.y,je=((s=Me.arrow)===null||s===void 0?void 0:s.centerOffset)!==0,[Ot,ct]=f.useState();return Pn(()=>{F&&ct(window.getComputedStyle(F).zIndex)},[F]),f.createElement("div",{ref:ge.setFloating,"data-radix-popper-content-wrapper":"",style:{...Ve,transform:We?Ve.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:Ot,"--radix-popper-transform-origin":[(l=Me.transformOrigin)===null||l===void 0?void 0:l.x,(u=Me.transformOrigin)===null||u===void 0?void 0:u.y].join(" ")},dir:e.dir},f.createElement(pU,{scope:h,placedSide:fe,onArrowChange:ae,arrowX:Ae,arrowY:Oe,shouldHideArrow:je},f.createElement(Pe.div,Y({"data-side":fe,"data-align":xe},A,{ref:J,style:{...A.style,animation:We?void 0:"none",opacity:(d=Me.hide)!==null&&d!==void 0&&d.referenceHidden?0:void 0}}))))});function mU(e){return e!==null}const gU=e=>({name:"transformOrigin",options:e,fn(t){var n,r,o,i,s;const{placement:l,rects:u,middlewareData:d}=t,m=((n=d.arrow)===null||n===void 0?void 0:n.centerOffset)!==0,g=m?0:e.arrowWidth,y=m?0:e.arrowHeight,[x,_]=WT(l),C={start:"0%",center:"50%",end:"100%"}[_],S=((r=(o=d.arrow)===null||o===void 0?void 0:o.x)!==null&&r!==void 0?r:0)+g/2,b=((i=(s=d.arrow)===null||s===void 0?void 0:s.y)!==null&&i!==void 0?i:0)+y/2;let E="",k="";return x==="bottom"?(E=m?C:`${S}px`,k=`${-y}px`):x==="top"?(E=m?C:`${S}px`,k=`${u.floating.height+y}px`):x==="right"?(E=`${-y}px`,k=m?C:`${b}px`):x==="left"&&(E=`${u.floating.width+y}px`,k=m?C:`${b}px`),{data:{x:E,y:k}}}});function WT(e){const[t,n="center"]=e.split("-");return[t,n]}const Od=uU,zm=fU,Bm=hU,Md=f.forwardRef((e,t)=>{var n;const{container:r=globalThis==null||(n=globalThis.document)===null||n===void 0?void 0:n.body,...o}=e;return r?XI.createPortal(f.createElement(Pe.div,Y({},o,{ref:t})),r):null});function vU(e,t){return f.useReducer((n,r)=>{const o=t[n][r];return o??n},e)}const bn=e=>{const{present:t,children:n}=e,r=yU(t),o=typeof n=="function"?n({present:r.isPresent}):f.Children.only(n),i=Be(r.ref,o.ref);return typeof n=="function"||r.isPresent?f.cloneElement(o,{ref:i}):null};bn.displayName="Presence";function yU(e){const[t,n]=f.useState(),r=f.useRef({}),o=f.useRef(e),i=f.useRef("none"),s=e?"mounted":"unmounted",[l,u]=vU(s,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return f.useEffect(()=>{const d=sp(r.current);i.current=l==="mounted"?d:"none"},[l]),Pn(()=>{const d=r.current,h=o.current;if(h!==e){const g=i.current,y=sp(d);e?u("MOUNT"):y==="none"||(d==null?void 0:d.display)==="none"?u("UNMOUNT"):u(h&&g!==y?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,u]),Pn(()=>{if(t){const d=m=>{const y=sp(r.current).includes(m.animationName);m.target===t&&y&&Os.flushSync(()=>u("ANIMATION_END"))},h=m=>{m.target===t&&(i.current=sp(r.current))};return t.addEventListener("animationstart",h),t.addEventListener("animationcancel",d),t.addEventListener("animationend",d),()=>{t.removeEventListener("animationstart",h),t.removeEventListener("animationcancel",d),t.removeEventListener("animationend",d)}}else u("ANIMATION_END")},[t,u]),{isPresent:["mounted","unmountSuspended"].includes(l),ref:f.useCallback(d=>{d&&(r.current=getComputedStyle(d)),n(d)},[])}}function sp(e){return(e==null?void 0:e.animationName)||"none"}function Zr({prop:e,defaultProp:t,onChange:n=()=>{}}){const[r,o]=wU({defaultProp:t,onChange:n}),i=e!==void 0,s=i?e:r,l=Ft(n),u=f.useCallback(d=>{if(i){const m=typeof d=="function"?d(e):d;m!==e&&l(m)}else o(d)},[i,e,o,l]);return[s,u]}function wU({defaultProp:e,onChange:t}){const n=f.useState(e),[r]=n,o=f.useRef(r),i=Ft(t);return f.useEffect(()=>{o.current!==r&&(i(r),o.current=r)},[r,o,i]),n}const Um=f.forwardRef((e,t)=>f.createElement(Pe.span,Y({},e,{ref:t,style:{position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal",...e.style}}))),xU=Um,[Vm,hte]=An("Tooltip",[Ns]),vx=Ns(),bU="TooltipProvider",_U=700,l1="tooltip.open",[SU,yx]=Vm(bU),EU=e=>{const{__scopeTooltip:t,delayDuration:n=_U,skipDelayDuration:r=300,disableHoverableContent:o=!1,children:i}=e,[s,l]=f.useState(!0),u=f.useRef(!1),d=f.useRef(0);return f.useEffect(()=>{const h=d.current;return()=>window.clearTimeout(h)},[]),f.createElement(SU,{scope:t,isOpenDelayed:s,delayDuration:n,onOpen:f.useCallback(()=>{window.clearTimeout(d.current),l(!1)},[]),onClose:f.useCallback(()=>{window.clearTimeout(d.current),d.current=window.setTimeout(()=>l(!0),r)},[r]),isPointerInTransitRef:u,onPointerInTransitChange:f.useCallback(h=>{u.current=h},[]),disableHoverableContent:o},i)},wx="Tooltip",[CU,Wm]=Vm(wx),$U=e=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:o=!1,onOpenChange:i,disableHoverableContent:s,delayDuration:l}=e,u=yx(wx,e.__scopeTooltip),d=vx(t),[h,m]=f.useState(null),g=nr(),y=f.useRef(0),x=s??u.disableHoverableContent,_=l??u.delayDuration,C=f.useRef(!1),[S=!1,b]=Zr({prop:r,defaultProp:o,onChange:A=>{A?(u.onOpen(),document.dispatchEvent(new CustomEvent(l1))):u.onClose(),i==null||i(A)}}),E=f.useMemo(()=>S?C.current?"delayed-open":"instant-open":"closed",[S]),k=f.useCallback(()=>{window.clearTimeout(y.current),C.current=!1,b(!0)},[b]),P=f.useCallback(()=>{window.clearTimeout(y.current),b(!1)},[b]),M=f.useCallback(()=>{window.clearTimeout(y.current),y.current=window.setTimeout(()=>{C.current=!0,b(!0)},_)},[_,b]);return f.useEffect(()=>()=>window.clearTimeout(y.current),[]),f.createElement(Od,d,f.createElement(CU,{scope:t,contentId:g,open:S,stateAttribute:E,trigger:h,onTriggerChange:m,onTriggerEnter:f.useCallback(()=>{u.isOpenDelayed?M():k()},[u.isOpenDelayed,M,k]),onTriggerLeave:f.useCallback(()=>{x?P():window.clearTimeout(y.current)},[P,x]),onOpen:k,onClose:P,disableHoverableContent:x},n))},UC="TooltipTrigger",kU=f.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,o=Wm(UC,n),i=yx(UC,n),s=vx(n),l=f.useRef(null),u=Be(t,l,o.onTriggerChange),d=f.useRef(!1),h=f.useRef(!1),m=f.useCallback(()=>d.current=!1,[]);return f.useEffect(()=>()=>document.removeEventListener("pointerup",m),[m]),f.createElement(zm,Y({asChild:!0},s),f.createElement(Pe.button,Y({"aria-describedby":o.open?o.contentId:void 0,"data-state":o.stateAttribute},r,{ref:u,onPointerMove:ue(e.onPointerMove,g=>{g.pointerType!=="touch"&&!h.current&&!i.isPointerInTransitRef.current&&(o.onTriggerEnter(),h.current=!0)}),onPointerLeave:ue(e.onPointerLeave,()=>{o.onTriggerLeave(),h.current=!1}),onPointerDown:ue(e.onPointerDown,()=>{d.current=!0,document.addEventListener("pointerup",m,{once:!0})}),onFocus:ue(e.onFocus,()=>{d.current||o.onOpen()}),onBlur:ue(e.onBlur,o.onClose),onClick:ue(e.onClick,o.onClose)})))}),RU="TooltipPortal",[mte,TU]=Vm(RU,{forceMount:void 0}),rd="TooltipContent",PU=f.forwardRef((e,t)=>{const n=TU(rd,e.__scopeTooltip),{forceMount:r=n.forceMount,side:o="top",...i}=e,s=Wm(rd,e.__scopeTooltip);return f.createElement(bn,{present:r||s.open},s.disableHoverableContent?f.createElement(HT,Y({side:o},i,{ref:t})):f.createElement(AU,Y({side:o},i,{ref:t})))}),AU=f.forwardRef((e,t)=>{const n=Wm(rd,e.__scopeTooltip),r=yx(rd,e.__scopeTooltip),o=f.useRef(null),i=Be(t,o),[s,l]=f.useState(null),{trigger:u,onClose:d}=n,h=o.current,{onPointerInTransitChange:m}=r,g=f.useCallback(()=>{l(null),m(!1)},[m]),y=f.useCallback((x,_)=>{const C=x.currentTarget,S={x:x.clientX,y:x.clientY},b=MU(S,C.getBoundingClientRect()),E=NU(S,b),k=DU(_.getBoundingClientRect()),P=LU([...E,...k]);l(P),m(!0)},[m]);return f.useEffect(()=>()=>g(),[g]),f.useEffect(()=>{if(u&&h){const x=C=>y(C,h),_=C=>y(C,u);return u.addEventListener("pointerleave",x),h.addEventListener("pointerleave",_),()=>{u.removeEventListener("pointerleave",x),h.removeEventListener("pointerleave",_)}}},[u,h,y,g]),f.useEffect(()=>{if(s){const x=_=>{const C=_.target,S={x:_.clientX,y:_.clientY},b=(u==null?void 0:u.contains(C))||(h==null?void 0:h.contains(C)),E=!IU(S,s);b?g():E&&(g(),d())};return document.addEventListener("pointermove",x),()=>document.removeEventListener("pointermove",x)}},[u,h,s,d,g]),f.createElement(HT,Y({},e,{ref:i}))}),[OU,gte]=Vm(wx,{isInside:!1}),HT=f.forwardRef((e,t)=>{const{__scopeTooltip:n,children:r,"aria-label":o,onEscapeKeyDown:i,onPointerDownOutside:s,...l}=e,u=Wm(rd,n),d=vx(n),{onClose:h}=u;return f.useEffect(()=>(document.addEventListener(l1,h),()=>document.removeEventListener(l1,h)),[h]),f.useEffect(()=>{if(u.trigger){const m=g=>{const y=g.target;y!=null&&y.contains(u.trigger)&&h()};return window.addEventListener("scroll",m,{capture:!0}),()=>window.removeEventListener("scroll",m,{capture:!0})}},[u.trigger,h]),f.createElement(yc,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:i,onPointerDownOutside:s,onFocusOutside:m=>m.preventDefault(),onDismiss:h},f.createElement(Bm,Y({"data-state":u.stateAttribute},d,l,{ref:t,style:{...l.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"}}),f.createElement(sx,null,r),f.createElement(OU,{scope:n,isInside:!0},f.createElement(xU,{id:u.contentId,role:"tooltip"},o||r))))});function MU(e,t){const n=Math.abs(t.top-e.y),r=Math.abs(t.bottom-e.y),o=Math.abs(t.right-e.x),i=Math.abs(t.left-e.x);switch(Math.min(n,r,o,i)){case i:return"left";case o:return"right";case n:return"top";case r:return"bottom";default:throw new Error("unreachable")}}function NU(e,t,n=5){const r=[];switch(t){case"top":r.push({x:e.x-n,y:e.y+n},{x:e.x+n,y:e.y+n});break;case"bottom":r.push({x:e.x-n,y:e.y-n},{x:e.x+n,y:e.y-n});break;case"left":r.push({x:e.x+n,y:e.y-n},{x:e.x+n,y:e.y+n});break;case"right":r.push({x:e.x-n,y:e.y-n},{x:e.x-n,y:e.y+n});break}return r}function DU(e){const{top:t,right:n,bottom:r,left:o}=e;return[{x:o,y:t},{x:n,y:t},{x:n,y:r},{x:o,y:r}]}function IU(e,t){const{x:n,y:r}=e;let o=!1;for(let i=0,s=t.length-1;ir!=h>r&&n<(d-l)*(r-u)/(h-u)+l&&(o=!o)}return o}function LU(e){const t=e.slice();return t.sort((n,r)=>n.xr.x?1:n.yr.y?1:0),FU(t)}function FU(e){if(e.length<=1)return e.slice();const t=[];for(let r=0;r=2;){const i=t[t.length-1],s=t[t.length-2];if((i.x-s.x)*(o.y-s.y)>=(i.y-s.y)*(o.x-s.x))t.pop();else break}t.push(o)}t.pop();const n=[];for(let r=e.length-1;r>=0;r--){const o=e[r];for(;n.length>=2;){const i=n[n.length-1],s=n[n.length-2];if((i.x-s.x)*(o.y-s.y)>=(i.y-s.y)*(o.x-s.x))n.pop();else break}n.push(o)}return n.pop(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}const jU=EU,zU=$U,BU=kU,KT=PU,UU=jU,YT=zU,GT=BU,xx=f.forwardRef(({className:e,sideOffset:t=4,...n},r)=>v.jsx(KT,{ref:r,sideOffset:t,className:Ce("z-50 border overflow-hidden rounded-md bg-background text-foreground px-3 py-1.5 text-xs animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...n}));xx.displayName=KT.displayName;const bx=Om("inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50",{variants:{variant:{default:"bg-primary text-primary-foreground shadow hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",outline:"border border-input bg-transparent shadow-sm hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2",sm:"h-8 rounded-md px-3 text-xs",lg:"h-10 rounded-md px-8",icon:"h-9 w-9"}},defaultVariants:{variant:"default",size:"default"}}),yn=f.forwardRef(({className:e,variant:t,size:n,asChild:r=!1,...o},i)=>{const s=r?Wo:"button";return v.jsx(s,{className:Ce(bx({variant:t,size:n,className:e}),"outline-none cursor-default"),ref:i,tabIndex:-1,...o})});yn.displayName="Button";const vn=f.forwardRef(({tooltip:e,children:t,...n},r)=>v.jsxs(YT,{children:[v.jsx(GT,{asChild:!0,children:v.jsx(yn,{variant:"ghost",size:"icon",...n,ref:r,tabIndex:-1,className:"cursor-default bg-background",children:v.jsx("div",{className:"icon-button-icon-wrapper",children:t})})}),v.jsx(xx,{children:v.jsx("p",{children:e})})]})),c1=e=>{const{onFileUpload:t,children:n,...r}=e,[o]=f.useState(`file-upload-${Math.random().toString()}`),i=s=>{var u;const l=(u=s.currentTarget.files)==null?void 0:u[0];l&&t(l)};return v.jsxs(v.Fragment,{children:[v.jsx("label",{htmlFor:o,children:v.jsx(vn,{...r,asChild:!0,children:n})}),v.jsx(Pd,{style:{display:"none"},id:o,name:o,type:"file",onChange:i,accept:"image/png, image/jpeg"})]})};var VU={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const WU=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Jt=(e,t)=>{const n=f.forwardRef(({color:r="currentColor",size:o=24,strokeWidth:i=2,absoluteStrokeWidth:s,children:l,...u},d)=>f.createElement("svg",{ref:d,...VU,width:o,height:o,stroke:r,strokeWidth:s?Number(i)*24/Number(o):i,className:`lucide lucide-${WU(e)}`,...u},[...t.map(([h,m])=>f.createElement(h,m)),...(Array.isArray(l)?l:[l])||[]]));return n.displayName=`${e}`,n},HU=Jt("Blocks",[["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["path",{d:"M10 21V8a1 1 0 0 0-1-1H4a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-5a1 1 0 0 0-1-1H3",key:"1fpvtg"}]]),KU=Jt("ChevronLeft",[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]]),YU=Jt("ChevronRight",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]),GU=Jt("Coffee",[["path",{d:"M17 8h1a4 4 0 1 1 0 8h-1",key:"jx4kbh"}],["path",{d:"M3 8h14v9a4 4 0 0 1-4 4H7a4 4 0 0 1-4-4Z",key:"1bxrl0"}],["line",{x1:"6",x2:"6",y1:"2",y2:"4",key:"1cr9l3"}],["line",{x1:"10",x2:"10",y1:"2",y2:"4",key:"170wym"}],["line",{x1:"14",x2:"14",y1:"2",y2:"4",key:"1c5f70"}]]),XU=Jt("Download",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"7 10 12 15 17 10",key:"2ggqvy"}],["line",{x1:"12",x2:"12",y1:"15",y2:"3",key:"1vk2je"}]]),ZU=Jt("Eraser",[["path",{d:"m7 21-4.3-4.3c-1-1-1-2.5 0-3.4l9.6-9.6c1-1 2.5-1 3.4 0l5.6 5.6c1 1 1 2.5 0 3.4L13 21",key:"182aya"}],["path",{d:"M22 21H7",key:"t4ddhn"}],["path",{d:"m5 11 9 9",key:"1mo9qw"}]]),qU=Jt("Expand",[["path",{d:"m21 21-6-6m6 6v-4.8m0 4.8h-4.8",key:"1c15vz"}],["path",{d:"M3 16.2V21m0 0h4.8M3 21l6-6",key:"1fsnz2"}],["path",{d:"M21 7.8V3m0 0h-4.8M21 3l-6 6",key:"hawz9i"}],["path",{d:"M3 7.8V3m0 0h4.8M3 3l6 6",key:"u9ee12"}]]),QU=Jt("Eye",[["path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z",key:"rwhkz3"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]),JU=Jt("FolderClosed",[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}],["path",{d:"M2 10h20",key:"1ir3d8"}]]),XT=Jt("Fullscreen",[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}],["rect",{width:"10",height:"8",x:"7",y:"8",rx:"1",key:"vys8me"}]]),eV=Jt("Image",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]]),tV=Jt("Keyboard",[["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",ry:"2",key:"15u882"}],["path",{d:"M6 8h.001",key:"1ej0i3"}],["path",{d:"M10 8h.001",key:"1x2st2"}],["path",{d:"M14 8h.001",key:"1vkmyp"}],["path",{d:"M18 8h.001",key:"kfsenl"}],["path",{d:"M8 12h.001",key:"1sjpby"}],["path",{d:"M12 12h.001",key:"al75ts"}],["path",{d:"M16 12h.001",key:"931bgk"}],["path",{d:"M7 16h10",key:"wp8him"}]]),nV=Jt("MousePointerClick",[["path",{d:"m9 9 5 12 1.8-5.2L21 14Z",key:"1b76lo"}],["path",{d:"M7.2 2.2 8 5.1",key:"1cfko1"}],["path",{d:"m5.1 8-2.9-.8",key:"1go3kf"}],["path",{d:"M14 4.1 12 6",key:"ita8i4"}],["path",{d:"m6 12-1.9 2",key:"mnht97"}]]),rV=Jt("Redo",[["path",{d:"M21 7v6h-6",key:"3ptur4"}],["path",{d:"M3 17a9 9 0 0 1 9-9 9 9 0 0 1 6 2.3l3 2.7",key:"1kgawr"}]]),oV=Jt("RotateCw",[["path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8",key:"1p45f6"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}]]),iV=Jt("Settings",[["path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z",key:"1qme2f"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]),VC=Jt("Slice",[["path",{d:"m8 14-6 6h9v-3",key:"zo3j9a"}],["path",{d:"M18.37 3.63 8 14l3 3L21.37 6.63a2.12 2.12 0 1 0-3-3Z",key:"1dzx0j"}]]),WC=Jt("Smile",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 14s1.5 2 4 2 4-2 4-2",key:"1y1vjs"}],["line",{x1:"9",x2:"9.01",y1:"9",y2:"9",key:"yxxnd0"}],["line",{x1:"15",x2:"15.01",y1:"9",y2:"9",key:"1p4y9e"}]]),sV=Jt("Undo",[["path",{d:"M3 7v6h6",key:"1v2h90"}],["path",{d:"M21 17a9 9 0 0 0-9-9 9 9 0 0 0-6 2.3L3 13",key:"1r6uu6"}]]),ZT=Jt("Upload",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"17 8 12 3 7 8",key:"t8dd8p"}],["line",{x1:"12",x2:"12",y1:"3",y2:"15",key:"widbto"}]]);function aV(e,t){const[n,r]=f.useState(e);return f.useEffect(()=>{const o=setTimeout(()=>{r(e)},t);return()=>{clearTimeout(o)}},[e,t]),n}function u1(e){const[t,n]=f.useState(()=>typeof e=="boolean"?e:!!e),r=f.useCallback(o=>n(typeof o=="boolean"?o:i=>!i),[]);return[t,r]}const w0="focusScope.autoFocusOnMount",x0="focusScope.autoFocusOnUnmount",HC={bubbles:!1,cancelable:!0},Hm=f.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:o,onUnmountAutoFocus:i,...s}=e,[l,u]=f.useState(null),d=Ft(o),h=Ft(i),m=f.useRef(null),g=Be(t,_=>u(_)),y=f.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;f.useEffect(()=>{if(r){let b=function(M){if(y.paused||!l)return;const A=M.target;l.contains(A)?m.current=A:Hi(m.current,{select:!0})},E=function(M){if(y.paused||!l)return;const A=M.relatedTarget;A!==null&&(l.contains(A)||Hi(m.current,{select:!0}))},k=function(M){if(document.activeElement===document.body)for(const O of M)O.removedNodes.length>0&&Hi(l)};var _=b,C=E,S=k;document.addEventListener("focusin",b),document.addEventListener("focusout",E);const P=new MutationObserver(k);return l&&P.observe(l,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",b),document.removeEventListener("focusout",E),P.disconnect()}}},[r,l,y.paused]),f.useEffect(()=>{if(l){YC.add(y);const _=document.activeElement;if(!l.contains(_)){const S=new CustomEvent(w0,HC);l.addEventListener(w0,d),l.dispatchEvent(S),S.defaultPrevented||(lV(pV(qT(l)),{select:!0}),document.activeElement===_&&Hi(l))}return()=>{l.removeEventListener(w0,d),setTimeout(()=>{const S=new CustomEvent(x0,HC);l.addEventListener(x0,h),l.dispatchEvent(S),S.defaultPrevented||Hi(_??document.body,{select:!0}),l.removeEventListener(x0,h),YC.remove(y)},0)}}},[l,d,h,y]);const x=f.useCallback(_=>{if(!n&&!r||y.paused)return;const C=_.key==="Tab"&&!_.altKey&&!_.ctrlKey&&!_.metaKey,S=document.activeElement;if(C&&S){const b=_.currentTarget,[E,k]=cV(b);E&&k?!_.shiftKey&&S===k?(_.preventDefault(),n&&Hi(E,{select:!0})):_.shiftKey&&S===E&&(_.preventDefault(),n&&Hi(k,{select:!0})):S===b&&_.preventDefault()}},[n,r,y.paused]);return f.createElement(Pe.div,Y({tabIndex:-1},s,{ref:g,onKeyDown:x}))});function lV(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(Hi(r,{select:t}),document.activeElement!==n)return}function cV(e){const t=qT(e),n=KC(t,e),r=KC(t.reverse(),e);return[n,r]}function qT(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const o=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||o?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function KC(e,t){for(const n of e)if(!uV(n,{upTo:t}))return n}function uV(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function dV(e){return e instanceof HTMLInputElement&&"select"in e}function Hi(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&dV(e)&&t&&e.select()}}const YC=fV();function fV(){let e=[];return{add(t){const n=e[0];t!==n&&(n==null||n.pause()),e=GC(e,t),e.unshift(t)},remove(t){var n;e=GC(e,t),(n=e[0])===null||n===void 0||n.resume()}}}function GC(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function pV(e){return e.filter(t=>t.tagName!=="A")}let b0=0;function Km(){f.useEffect(()=>{var e,t;const n=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",(e=n[0])!==null&&e!==void 0?e:XC()),document.body.insertAdjacentElement("beforeend",(t=n[1])!==null&&t!==void 0?t:XC()),b0++,()=>{b0===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(r=>r.remove()),b0--}},[])}function XC(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.cssText="outline: none; opacity: 0; position: fixed; pointer-events: none",e}var Mo=function(){return Mo=Object.assign||function(t){for(var n,r=1,o=arguments.length;r"u")return PV;var t=AV(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])}},MV=tP(),NV=function(e,t,n,r){var o=e.left,i=e.top,s=e.right,l=e.gap;return n===void 0&&(n="margin"),` + .`.concat(mV,` { + overflow: hidden `).concat(r,`; + padding-right: `).concat(l,"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(i,`px; + padding-right: `).concat(s,`px; + margin-left:0; + margin-top:0; + margin-right: `).concat(l,"px ").concat(r,`; + `),n==="padding"&&"padding-right: ".concat(l,"px ").concat(r,";")].filter(Boolean).join(""),` + } + + .`).concat(Wp,` { + right: `).concat(l,"px ").concat(r,`; + } + + .`).concat(Hp,` { + margin-right: `).concat(l,"px ").concat(r,`; + } + + .`).concat(Wp," .").concat(Wp,` { + right: 0 `).concat(r,`; + } + + .`).concat(Hp," .").concat(Hp,` { + margin-right: 0 `).concat(r,`; + } + + body { + `).concat(gV,": ").concat(l,`px; + } +`)},DV=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,o=r===void 0?"margin":r,i=f.useMemo(function(){return OV(o)},[o]);return f.createElement(MV,{styles:NV(i,!t,o,n?"":"!important")})},d1=!1;if(typeof window<"u")try{var ap=Object.defineProperty({},"passive",{get:function(){return d1=!0,!0}});window.addEventListener("test",ap,ap),window.removeEventListener("test",ap,ap)}catch{d1=!1}var qa=d1?{passive:!1}:!1,IV=function(e){return e.tagName==="TEXTAREA"},nP=function(e,t){var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!IV(e)&&n[t]==="visible")},LV=function(e){return nP(e,"overflowY")},FV=function(e){return nP(e,"overflowX")},qC=function(e,t){var n=t;do{typeof ShadowRoot<"u"&&n instanceof ShadowRoot&&(n=n.host);var r=rP(e,n);if(r){var o=oP(e,n),i=o[1],s=o[2];if(i>s)return!0}n=n.parentNode}while(n&&n!==document.body);return!1},jV=function(e){var t=e.scrollTop,n=e.scrollHeight,r=e.clientHeight;return[t,n,r]},zV=function(e){var t=e.scrollLeft,n=e.scrollWidth,r=e.clientWidth;return[t,n,r]},rP=function(e,t){return e==="v"?LV(t):FV(t)},oP=function(e,t){return e==="v"?jV(t):zV(t)},BV=function(e,t){return e==="h"&&t==="rtl"?-1:1},UV=function(e,t,n,r,o){var i=BV(e,window.getComputedStyle(t).direction),s=i*r,l=n.target,u=t.contains(l),d=!1,h=s>0,m=0,g=0;do{var y=oP(e,l),x=y[0],_=y[1],C=y[2],S=_-C-i*x;(x||S)&&rP(e,l)&&(m+=S,g+=x),l=l.parentNode}while(!u&&l!==document.body||u&&(t.contains(l)||t===l));return(h&&(o&&m===0||!o&&s>m)||!h&&(o&&g===0||!o&&-s>g))&&(d=!0),d},lp=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},QC=function(e){return[e.deltaX,e.deltaY]},JC=function(e){return e&&"current"in e?e.current:e},VV=function(e,t){return e[0]===t[0]&&e[1]===t[1]},WV=function(e){return` + .block-interactivity-`.concat(e,` {pointer-events: none;} + .allow-interactivity-`).concat(e,` {pointer-events: all;} +`)},HV=0,Qa=[];function KV(e){var t=f.useRef([]),n=f.useRef([0,0]),r=f.useRef(),o=f.useState(HV++)[0],i=f.useState(function(){return tP()})[0],s=f.useRef(e);f.useEffect(function(){s.current=e},[e]),f.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(o));var _=hV([e.lockRef.current],(e.shards||[]).map(JC),!0).filter(Boolean);return _.forEach(function(C){return C.classList.add("allow-interactivity-".concat(o))}),function(){document.body.classList.remove("block-interactivity-".concat(o)),_.forEach(function(C){return C.classList.remove("allow-interactivity-".concat(o))})}}},[e.inert,e.lockRef.current,e.shards]);var l=f.useCallback(function(_,C){if("touches"in _&&_.touches.length===2)return!s.current.allowPinchZoom;var S=lp(_),b=n.current,E="deltaX"in _?_.deltaX:b[0]-S[0],k="deltaY"in _?_.deltaY:b[1]-S[1],P,M=_.target,A=Math.abs(E)>Math.abs(k)?"h":"v";if("touches"in _&&A==="h"&&M.type==="range")return!1;var O=qC(A,M);if(!O)return!0;if(O?P=A:(P=A==="v"?"h":"v",O=qC(A,M)),!O)return!1;if(!r.current&&"changedTouches"in _&&(E||k)&&(r.current=P),!P)return!0;var F=r.current||P;return UV(F,C,_,F==="h"?E:k,!0)},[]),u=f.useCallback(function(_){var C=_;if(!(!Qa.length||Qa[Qa.length-1]!==i)){var S="deltaY"in C?QC(C):lp(C),b=t.current.filter(function(P){return P.name===C.type&&P.target===C.target&&VV(P.delta,S)})[0];if(b&&b.should){C.cancelable&&C.preventDefault();return}if(!b){var E=(s.current.shards||[]).map(JC).filter(Boolean).filter(function(P){return P.contains(C.target)}),k=E.length>0?l(C,E[0]):!s.current.noIsolation;k&&C.cancelable&&C.preventDefault()}}},[]),d=f.useCallback(function(_,C,S,b){var E={name:_,delta:C,target:S,should:b};t.current.push(E),setTimeout(function(){t.current=t.current.filter(function(k){return k!==E})},1)},[]),h=f.useCallback(function(_){n.current=lp(_),r.current=void 0},[]),m=f.useCallback(function(_){d(_.type,QC(_),_.target,l(_,e.lockRef.current))},[]),g=f.useCallback(function(_){d(_.type,lp(_),_.target,l(_,e.lockRef.current))},[]);f.useEffect(function(){return Qa.push(i),e.setCallbacks({onScrollCapture:m,onWheelCapture:m,onTouchMoveCapture:g}),document.addEventListener("wheel",u,qa),document.addEventListener("touchmove",u,qa),document.addEventListener("touchstart",h,qa),function(){Qa=Qa.filter(function(_){return _!==i}),document.removeEventListener("wheel",u,qa),document.removeEventListener("touchmove",u,qa),document.removeEventListener("touchstart",h,qa)}},[]);var y=e.removeScrollBar,x=e.inert;return f.createElement(f.Fragment,null,x?f.createElement(i,{styles:WV(o)}):null,y?f.createElement(DV,{gapMode:"margin"}):null)}const YV=SV(eP,KV);var iP=f.forwardRef(function(e,t){return f.createElement(Ym,Mo({},e,{ref:t,sideCar:YV}))});iP.classNames=Ym.classNames;const Gm=iP;var GV=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},Ja=new WeakMap,cp=new WeakMap,up={},E0=0,sP=function(e){return e&&(e.host||sP(e.parentNode))},XV=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=sP(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})},ZV=function(e,t,n,r){var o=XV(t,Array.isArray(e)?e:[e]);up[n]||(up[n]=new WeakMap);var i=up[n],s=[],l=new Set,u=new Set(o),d=function(m){!m||l.has(m)||(l.add(m),d(m.parentNode))};o.forEach(d);var h=function(m){!m||u.has(m)||Array.prototype.forEach.call(m.children,function(g){if(l.has(g))h(g);else{var y=g.getAttribute(r),x=y!==null&&y!=="false",_=(Ja.get(g)||0)+1,C=(i.get(g)||0)+1;Ja.set(g,_),i.set(g,C),s.push(g),_===1&&x&&cp.set(g,!0),C===1&&g.setAttribute(n,"true"),x||g.setAttribute(r,"true")}})};return h(t),l.clear(),E0++,function(){s.forEach(function(m){var g=Ja.get(m)-1,y=i.get(m)-1;Ja.set(m,g),i.set(m,y),g||(cp.has(m)||m.removeAttribute(r),cp.delete(m)),y||m.removeAttribute(n)}),E0--,E0||(Ja=new WeakMap,Ja=new WeakMap,cp=new WeakMap,up={})}},Xm=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),o=t||GV(e);return o?(r.push.apply(r,Array.from(o.querySelectorAll("[aria-live]"))),ZV(r,o,n,"aria-hidden")):function(){return null}};const aP="Dialog",[lP,cP]=An(aP),[qV,bo]=lP(aP),QV=e=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:o,onOpenChange:i,modal:s=!0}=e,l=f.useRef(null),u=f.useRef(null),[d=!1,h]=Zr({prop:r,defaultProp:o,onChange:i});return f.createElement(qV,{scope:t,triggerRef:l,contentRef:u,contentId:nr(),titleId:nr(),descriptionId:nr(),open:d,onOpenChange:h,onOpenToggle:f.useCallback(()=>h(m=>!m),[h]),modal:s},n)},JV="DialogTrigger",uP=f.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=bo(JV,n),i=Be(t,o.triggerRef);return f.createElement(Pe.button,Y({type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":_x(o.open)},r,{ref:i,onClick:ue(e.onClick,o.onOpenToggle)}))}),dP="DialogPortal",[eW,fP]=lP(dP,{forceMount:void 0}),tW=e=>{const{__scopeDialog:t,forceMount:n,children:r,container:o}=e,i=bo(dP,t);return f.createElement(eW,{scope:t,forceMount:n},f.Children.map(r,s=>f.createElement(bn,{present:n||i.open},f.createElement(Md,{asChild:!0,container:o},s))))},f1="DialogOverlay",nW=f.forwardRef((e,t)=>{const n=fP(f1,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,i=bo(f1,e.__scopeDialog);return i.modal?f.createElement(bn,{present:r||i.open},f.createElement(rW,Y({},o,{ref:t}))):null}),rW=f.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=bo(f1,n);return f.createElement(Gm,{as:Wo,allowPinchZoom:!0,shards:[o.contentRef]},f.createElement(Pe.div,Y({"data-state":_x(o.open)},r,{ref:t,style:{pointerEvents:"auto",...r.style}})))}),oc="DialogContent",oW=f.forwardRef((e,t)=>{const n=fP(oc,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,i=bo(oc,e.__scopeDialog);return f.createElement(bn,{present:r||i.open},i.modal?f.createElement(iW,Y({},o,{ref:t})):f.createElement(sW,Y({},o,{ref:t})))}),iW=f.forwardRef((e,t)=>{const n=bo(oc,e.__scopeDialog),r=f.useRef(null),o=Be(t,n.contentRef,r);return f.useEffect(()=>{const i=r.current;if(i)return Xm(i)},[]),f.createElement(pP,Y({},e,{ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:ue(e.onCloseAutoFocus,i=>{var s;i.preventDefault(),(s=n.triggerRef.current)===null||s===void 0||s.focus()}),onPointerDownOutside:ue(e.onPointerDownOutside,i=>{const s=i.detail.originalEvent,l=s.button===0&&s.ctrlKey===!0;(s.button===2||l)&&i.preventDefault()}),onFocusOutside:ue(e.onFocusOutside,i=>i.preventDefault())}))}),sW=f.forwardRef((e,t)=>{const n=bo(oc,e.__scopeDialog),r=f.useRef(!1),o=f.useRef(!1);return f.createElement(pP,Y({},e,{ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var s;if((s=e.onCloseAutoFocus)===null||s===void 0||s.call(e,i),!i.defaultPrevented){var l;r.current||(l=n.triggerRef.current)===null||l===void 0||l.focus(),i.preventDefault()}r.current=!1,o.current=!1},onInteractOutside:i=>{var s,l;(s=e.onInteractOutside)===null||s===void 0||s.call(e,i),i.defaultPrevented||(r.current=!0,i.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const u=i.target;((l=n.triggerRef.current)===null||l===void 0?void 0:l.contains(u))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&o.current&&i.preventDefault()}}))}),pP=f.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:i,...s}=e,l=bo(oc,n),u=f.useRef(null),d=Be(t,u);return Km(),f.createElement(f.Fragment,null,f.createElement(Hm,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:i},f.createElement(yc,Y({role:"dialog",id:l.contentId,"aria-describedby":l.descriptionId,"aria-labelledby":l.titleId,"data-state":_x(l.open)},s,{ref:d,onDismiss:()=>l.onOpenChange(!1)}))),!1)}),hP="DialogTitle",aW=f.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=bo(hP,n);return f.createElement(Pe.h2,Y({id:o.titleId},r,{ref:t}))}),lW="DialogDescription",mP=f.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=bo(lW,n);return f.createElement(Pe.p,Y({id:o.descriptionId},r,{ref:t}))}),cW="DialogClose",uW=f.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=bo(cW,n);return f.createElement(Pe.button,Y({type:"button"},r,{ref:t,onClick:ue(e.onClick,()=>o.onOpenChange(!1))}))});function _x(e){return e?"open":"closed"}const dW="DialogTitleWarning",[fW,vte]=pB(dW,{contentName:oc,titleName:hP,docsSlug:"dialog"}),Sx=QV,gP=uP,Ex=tW,Nd=nW,Dd=oW,Id=aW,Ld=mP,Cx=uW,Zm=Sx,$x=gP,pW=Ex,vP=f.forwardRef(({className:e,...t},n)=>v.jsx(Nd,{ref:n,className:Ce("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t}));vP.displayName=Nd.displayName;const Fd=f.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(pW,{children:[v.jsx(vP,{}),v.jsxs(Dd,{ref:r,className:Ce("fixed left-[50%] top-[50%] z-50 flex flex-col w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",e,"outline-none"),onCloseAutoFocus:o=>o.preventDefault(),...n,children:[t,v.jsxs(Cx,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[v.jsx(yT,{className:"h-4 w-4"}),v.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Fd.displayName=Dd.displayName;const yP=({className:e,...t})=>v.jsx("div",{className:Ce("flex flex-col space-y-1.5 text-center sm:text-left",e),...t});yP.displayName="DialogHeader";const jd=f.forwardRef(({className:e,...t},n)=>v.jsx(Id,{ref:n,className:Ce("text-2xl font-semibold leading-none tracking-tight",e),...t}));jd.displayName=Id.displayName;const hW=f.forwardRef(({className:e,...t},n)=>v.jsx(Ld,{ref:n,className:Ce("text-sm text-muted-foreground",e),...t}));hW.displayName=Ld.displayName;function p1(){return p1=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 _W=function(t,n,r){r===void 0&&(r=!1);var o=n.alt,i=n.meta,s=n.mod,l=n.shift,u=n.ctrl,d=n.keys,h=t.key,m=t.code,g=t.ctrlKey,y=t.metaKey,x=t.shiftKey,_=t.altKey,C=ss(m),S=h.toLowerCase();if(!r){if(o===!_&&S!=="alt"||l===!x&&S!=="shift")return!1;if(s){if(!y&&!g)return!1}else if(i===!y&&S!=="meta"&&S!=="os"||u===!g&&S!=="ctrl"&&S!=="control")return!1}return d&&d.length===1&&(d.includes(S)||d.includes(C))?!0:d?vW(d):!d},SW=f.createContext(void 0),EW=function(){return f.useContext(SW)};function SP(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&&SP(e[r],t[r])},!0):e===t}var CW=f.createContext({hotkeys:[],enabledScopes:[],toggleScope:function(){},enableScope:function(){},disableScope:function(){}}),$W=function(){return f.useContext(CW)};function kW(e){var t=f.useRef(void 0);return SP(t.current,e)||(t.current=e),t.current}var e2=function(t){t.stopPropagation(),t.preventDefault(),t.stopImmediatePropagation()},RW=typeof window<"u"?f.useLayoutEffect:f.useEffect;function TW(e,t,n,r){var o=f.useRef(null),i=f.useRef(!1),s=n instanceof Array?r instanceof Array?void 0:r:n,l=kx(e)?e.join(s==null?void 0:s.splitKey):e,u=n instanceof Array?n:r instanceof Array?r:void 0,d=f.useCallback(t,u??[]),h=f.useRef(d);u?h.current=d:h.current=t;var m=kW(s),g=$W(),y=g.enabledScopes,x=EW();return RW(function(){if(!((m==null?void 0:m.enabled)===!1||!bW(y,m==null?void 0:m.scopes))){var _=function(k,P){var M;if(P===void 0&&(P=!1),!(xW(k)&&!_P(k,m==null?void 0:m.enableOnFormTags))&&!(m!=null&&m.ignoreEventWhen!=null&&m.ignoreEventWhen(k))){if(o.current!==null&&document.activeElement!==o.current&&!o.current.contains(document.activeElement)){e2(k);return}(M=k.target)!=null&&M.isContentEditable&&!(m!=null&&m.enableOnContentEditable)||C0(l,m==null?void 0:m.splitKey).forEach(function(A){var O,F=$0(A,m==null?void 0:m.combinationKey);if(_W(k,F,m==null?void 0:m.ignoreModifiers)||(O=F.keys)!=null&&O.includes("*")){if(P&&i.current)return;if(yW(k,F,m==null?void 0:m.preventDefault),!wW(k,F,m==null?void 0:m.enabled)){e2(k);return}h.current(k,F),P||(i.current=!0)}})}},C=function(k){k.key!==void 0&&(xP(ss(k.code)),((m==null?void 0:m.keydown)===void 0&&(m==null?void 0:m.keyup)!==!0||m!=null&&m.keydown)&&_(k))},S=function(k){k.key!==void 0&&(bP(ss(k.code)),i.current=!1,m!=null&&m.keyup&&_(k,!0))},b=o.current||(s==null?void 0:s.document)||document;return b.addEventListener("keyup",S),b.addEventListener("keydown",C),x&&C0(l,m==null?void 0:m.splitKey).forEach(function(E){return x.addHotkey($0(E,m==null?void 0:m.combinationKey,m==null?void 0:m.description))}),function(){b.removeEventListener("keyup",S),b.removeEventListener("keydown",C),x&&C0(l,m==null?void 0:m.splitKey).forEach(function(E){return x.removeHotkey($0(E,m==null?void 0:m.combinationKey,m==null?void 0:m.description))})}}},[l,m,y]),o}const Zn=(e,t,n)=>{const r=bt(i=>i.disableShortCuts);return TW(e,t,{enabled:!r},n)};function ur(e){const{content:t,keys:n}=e;return v.jsxs("div",{className:"flex justify-between",children:[v.jsx("div",{children:t}),v.jsx("div",{className:"flex gap-[8px]",children:n.map(r=>v.jsx("div",{className:"border px-2 py-1 rounded-lg",children:r},r))})]})}const PW=function(){return/macintosh|mac os x/i.test(navigator.userAgent)},dp=()=>PW()?"Cmd":"Ctrl";function AW(){const[e,t]=u1(!1);return Zn("h",()=>{t()}),v.jsxs(Zm,{open:e,onOpenChange:t,children:[v.jsx($x,{asChild:!0,children:v.jsx(vn,{tooltip:"Hotkeys",children:v.jsx(tV,{})})}),v.jsx(Fd,{children:v.jsxs(yP,{children:[v.jsx(jd,{children:"Hotkeys"}),v.jsxs("div",{className:"flex gap-2 flex-col pt-4",children:[v.jsx(ur,{content:"Pan",keys:["Space + Drag"]}),v.jsx(ur,{content:"Reset Zoom/Pan",keys:["Esc"]}),v.jsx(ur,{content:"Decrease Brush Size",keys:["["]}),v.jsx(ur,{content:"Increase Brush Size",keys:["]"]}),v.jsx(ur,{content:"View Original Image",keys:["Hold Tab"]}),v.jsx(ur,{content:"Undo",keys:[dp(),"Z"]}),v.jsx(ur,{content:"Redo",keys:[dp(),"Shift","Z"]}),v.jsx(ur,{content:"Copy Result",keys:[dp(),"C"]}),v.jsx(ur,{content:"Paste Image",keys:[dp(),"V"]}),v.jsx(ur,{content:"Trigger Manually Inpainting",keys:["Shift","R"]}),v.jsx(ur,{content:"Toggle Hotkeys Dialog",keys:["H"]}),v.jsx(ur,{content:"Toggle Settings Dialog",keys:["S"]}),v.jsx(ur,{content:"Toggle File Manager",keys:["F"]})]})]})})]})}function Rx(e){const[t]=f.useState(new Image),[n,r]=f.useState(!1);return f.useEffect(()=>{if(e)return t.onload=()=>{r(!0)},r(!1),t.src=URL.createObjectURL(e),()=>{t.onload=null}},[e,t]),[t,n]}const EP="Popover",[CP,yte]=An(EP,[Ns]),Tx=Ns(),[OW,bc]=CP(EP),MW=e=>{const{__scopePopover:t,children:n,open:r,defaultOpen:o,onOpenChange:i,modal:s=!1}=e,l=Tx(t),u=f.useRef(null),[d,h]=f.useState(!1),[m=!1,g]=Zr({prop:r,defaultProp:o,onChange:i});return f.createElement(Od,l,f.createElement(OW,{scope:t,contentId:nr(),triggerRef:u,open:m,onOpenChange:g,onOpenToggle:f.useCallback(()=>g(y=>!y),[g]),hasCustomAnchor:d,onCustomAnchorAdd:f.useCallback(()=>h(!0),[]),onCustomAnchorRemove:f.useCallback(()=>h(!1),[]),modal:s},n))},NW="PopoverTrigger",DW=f.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,o=bc(NW,n),i=Tx(n),s=Be(t,o.triggerRef),l=f.createElement(Pe.button,Y({type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":RP(o.open)},r,{ref:s,onClick:ue(e.onClick,o.onOpenToggle)}));return o.hasCustomAnchor?l:f.createElement(zm,Y({asChild:!0},i),l)}),$P="PopoverPortal",[IW,LW]=CP($P,{forceMount:void 0}),FW=e=>{const{__scopePopover:t,forceMount:n,children:r,container:o}=e,i=bc($P,t);return f.createElement(IW,{scope:t,forceMount:n},f.createElement(bn,{present:n||i.open},f.createElement(Md,{asChild:!0,container:o},r)))},od="PopoverContent",jW=f.forwardRef((e,t)=>{const n=LW(od,e.__scopePopover),{forceMount:r=n.forceMount,...o}=e,i=bc(od,e.__scopePopover);return f.createElement(bn,{present:r||i.open},i.modal?f.createElement(zW,Y({},o,{ref:t})):f.createElement(BW,Y({},o,{ref:t})))}),zW=f.forwardRef((e,t)=>{const n=bc(od,e.__scopePopover),r=f.useRef(null),o=Be(t,r),i=f.useRef(!1);return f.useEffect(()=>{const s=r.current;if(s)return Xm(s)},[]),f.createElement(Gm,{as:Wo,allowPinchZoom:!0},f.createElement(kP,Y({},e,{ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:ue(e.onCloseAutoFocus,s=>{var l;s.preventDefault(),i.current||(l=n.triggerRef.current)===null||l===void 0||l.focus()}),onPointerDownOutside:ue(e.onPointerDownOutside,s=>{const l=s.detail.originalEvent,u=l.button===0&&l.ctrlKey===!0,d=l.button===2||u;i.current=d},{checkForDefaultPrevented:!1}),onFocusOutside:ue(e.onFocusOutside,s=>s.preventDefault(),{checkForDefaultPrevented:!1})})))}),BW=f.forwardRef((e,t)=>{const n=bc(od,e.__scopePopover),r=f.useRef(!1),o=f.useRef(!1);return f.createElement(kP,Y({},e,{ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var s;if((s=e.onCloseAutoFocus)===null||s===void 0||s.call(e,i),!i.defaultPrevented){var l;r.current||(l=n.triggerRef.current)===null||l===void 0||l.focus(),i.preventDefault()}r.current=!1,o.current=!1},onInteractOutside:i=>{var s,l;(s=e.onInteractOutside)===null||s===void 0||s.call(e,i),i.defaultPrevented||(r.current=!0,i.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const u=i.target;((l=n.triggerRef.current)===null||l===void 0?void 0:l.contains(u))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&o.current&&i.preventDefault()}}))}),kP=f.forwardRef((e,t)=>{const{__scopePopover:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:i,disableOutsidePointerEvents:s,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:d,onInteractOutside:h,...m}=e,g=bc(od,n),y=Tx(n);return Km(),f.createElement(Hm,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:i},f.createElement(yc,{asChild:!0,disableOutsidePointerEvents:s,onInteractOutside:h,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:d,onDismiss:()=>g.onOpenChange(!1)},f.createElement(Bm,Y({"data-state":RP(g.open),role:"dialog",id:g.contentId},y,m,{ref:t,style:{...m.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}}))))});function RP(e){return e?"open":"closed"}const UW=MW,VW=DW,WW=FW,TP=jW,HW=UW,KW=VW,PP=f.forwardRef(({className:e,align:t="center",sideOffset:n=4,...r},o)=>v.jsx(WW,{children:v.jsx(TP,{ref:o,align:t,tabIndex:-1,sideOffset:n,className:Ce("z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...r})}));PP.displayName=TP.displayName;function YW(){var e=f.useRef(!0);return e.current?(e.current=!1,!0):e.current}var GW=function(e,t){var n=YW();f.useEffect(function(){if(!n)return e()},t)};const XW=GW;var ZW=function(){};function Px(e){for(var t=[],n=1;n{const[e,t,n,r,o,i]=bt(g=>[g.getIsProcessing(),g.settings.prompt,g.updateSettings,g.runInpainting,g.showPrevMask,g.hidePrevMask]),s=f.useRef(null);OP(s,()=>{s!=null&&s.current&&s.current.blur()});const l=g=>{g.preventDefault(),g.stopPropagation();const y=g.target;n({prompt:y.value})},u=()=>{e||r()},d=g=>{g.key==="Enter"&&!e&&u()},h=()=>{o()},m=()=>{i()};return v.jsxs("div",{className:"flex gap-4 items-center",children:[v.jsx(Pd,{ref:s,className:"min-w-[500px]",value:t,onInput:l,onKeyUp:d,placeholder:"I want to repaint of..."}),v.jsx(yn,{size:"sm",onClick:u,disabled:e,onMouseEnter:h,onMouseLeave:m,children:"Paint"})]})};var Lh={exports:{}};/** + * @license + * Lodash + * Copyright OpenJS Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */Lh.exports;(function(e,t){(function(){var n,r="4.17.21",o=200,i="Unsupported core-js use. Try https://npms.io/search?q=ponyfill.",s="Expected a function",l="Invalid `variable` option passed into `_.template`",u="__lodash_hash_undefined__",d=500,h="__lodash_placeholder__",m=1,g=2,y=4,x=1,_=2,C=1,S=2,b=4,E=8,k=16,P=32,M=64,A=128,O=256,F=512,V=30,J="...",G=800,ae=16,U=1,te=2,L=3,ie=1/0,K=9007199254740991,Q=17976931348623157e292,W=NaN,le=4294967295,ge=le-1,Ve=le>>>1,Ue=[["ary",A],["bind",C],["bindKey",S],["curry",E],["curryRight",k],["flip",F],["partial",P],["partialRight",M],["rearg",O]],We="[object Arguments]",Me="[object Array]",fe="[object AsyncFunction]",xe="[object Boolean]",$e="[object Date]",Ae="[object DOMException]",Oe="[object Error]",je="[object Function]",Ot="[object GeneratorFunction]",ct="[object Map]",Kt="[object Number]",Er="[object Null]",gt="[object Object]",js="[object Promise]",I="[object Proxy]",X="[object RegExp]",Z="[object Set]",we="[object String]",he="[object Symbol]",de="[object Undefined]",ke="[object WeakMap]",ft="[object WeakSet]",pt="[object ArrayBuffer]",_n="[object DataView]",Cr="[object Float32Array]",ki="[object Float64Array]",_o="[object Int8Array]",Vn="[object Int16Array]",Da="[object Int32Array]",Ri="[object Uint8Array]",zs="[object Uint8ClampedArray]",Ti="[object Uint16Array]",$c="[object Uint32Array]",yg=/\b__p \+= '';/g,wg=/\b(__p \+=) '' \+/g,Kd=/(__e\(.*?\)|\b__t\)) \+\n'';/g,kc=/&(?:amp|lt|gt|quot|#39);/g,Rc=/[&<>"']/g,Tc=RegExp(kc.source),xg=RegExp(Rc.source),Pc=/<%-([\s\S]+?)%>/g,Yd=/<%([\s\S]+?)%>/g,Ac=/<%=([\s\S]+?)%>/g,bg=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,_g=/^\w*$/,Sg=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,H=/[\\^$.*+?()[\]{}|]/g,Ge=RegExp(H.source),st=/^\s+/,Qr=/\s/,an=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,Gd=/\{\n\/\* \[wrapped with (.+)\] \*/,oO=/,? & /,iO=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,sO=/[()=,{}\[\]\/\s]/,aO=/\\(\\)?/g,lO=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,db=/\w*$/,cO=/^[-+]0x[0-9a-f]+$/i,uO=/^0b[01]+$/i,dO=/^\[object .+?Constructor\]$/,fO=/^0o[0-7]+$/i,pO=/^(?:0|[1-9]\d*)$/,hO=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,Xd=/($^)/,mO=/['\n\r\u2028\u2029\\]/g,Zd="\\ud800-\\udfff",gO="\\u0300-\\u036f",vO="\\ufe20-\\ufe2f",yO="\\u20d0-\\u20ff",fb=gO+vO+yO,pb="\\u2700-\\u27bf",hb="a-z\\xdf-\\xf6\\xf8-\\xff",wO="\\xac\\xb1\\xd7\\xf7",xO="\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf",bO="\\u2000-\\u206f",_O=" \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",mb="A-Z\\xc0-\\xd6\\xd8-\\xde",gb="\\ufe0e\\ufe0f",vb=wO+xO+bO+_O,Eg="['’]",SO="["+Zd+"]",yb="["+vb+"]",qd="["+fb+"]",wb="\\d+",EO="["+pb+"]",xb="["+hb+"]",bb="[^"+Zd+vb+wb+pb+hb+mb+"]",Cg="\\ud83c[\\udffb-\\udfff]",CO="(?:"+qd+"|"+Cg+")",_b="[^"+Zd+"]",$g="(?:\\ud83c[\\udde6-\\uddff]){2}",kg="[\\ud800-\\udbff][\\udc00-\\udfff]",Ia="["+mb+"]",Sb="\\u200d",Eb="(?:"+xb+"|"+bb+")",$O="(?:"+Ia+"|"+bb+")",Cb="(?:"+Eg+"(?:d|ll|m|re|s|t|ve))?",$b="(?:"+Eg+"(?:D|LL|M|RE|S|T|VE))?",kb=CO+"?",Rb="["+gb+"]?",kO="(?:"+Sb+"(?:"+[_b,$g,kg].join("|")+")"+Rb+kb+")*",RO="\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",TO="\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])",Tb=Rb+kb+kO,PO="(?:"+[EO,$g,kg].join("|")+")"+Tb,AO="(?:"+[_b+qd+"?",qd,$g,kg,SO].join("|")+")",OO=RegExp(Eg,"g"),MO=RegExp(qd,"g"),Rg=RegExp(Cg+"(?="+Cg+")|"+AO+Tb,"g"),NO=RegExp([Ia+"?"+xb+"+"+Cb+"(?="+[yb,Ia,"$"].join("|")+")",$O+"+"+$b+"(?="+[yb,Ia+Eb,"$"].join("|")+")",Ia+"?"+Eb+"+"+Cb,Ia+"+"+$b,TO,RO,wb,PO].join("|"),"g"),DO=RegExp("["+Sb+Zd+fb+gb+"]"),IO=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,LO=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],FO=-1,kt={};kt[Cr]=kt[ki]=kt[_o]=kt[Vn]=kt[Da]=kt[Ri]=kt[zs]=kt[Ti]=kt[$c]=!0,kt[We]=kt[Me]=kt[pt]=kt[xe]=kt[_n]=kt[$e]=kt[Oe]=kt[je]=kt[ct]=kt[Kt]=kt[gt]=kt[X]=kt[Z]=kt[we]=kt[ke]=!1;var Et={};Et[We]=Et[Me]=Et[pt]=Et[_n]=Et[xe]=Et[$e]=Et[Cr]=Et[ki]=Et[_o]=Et[Vn]=Et[Da]=Et[ct]=Et[Kt]=Et[gt]=Et[X]=Et[Z]=Et[we]=Et[he]=Et[Ri]=Et[zs]=Et[Ti]=Et[$c]=!0,Et[Oe]=Et[je]=Et[ke]=!1;var jO={À:"A",Á:"A",Â:"A",Ã:"A",Ä:"A",Å:"A",à:"a",á:"a",â:"a",ã:"a",ä:"a",å:"a",Ç:"C",ç:"c",Ð:"D",ð:"d",È:"E",É:"E",Ê:"E",Ë:"E",è:"e",é:"e",ê:"e",ë:"e",Ì:"I",Í:"I",Î:"I",Ï:"I",ì:"i",í:"i",î:"i",ï:"i",Ñ:"N",ñ:"n",Ò:"O",Ó:"O",Ô:"O",Õ:"O",Ö:"O",Ø:"O",ò:"o",ó:"o",ô:"o",õ:"o",ö:"o",ø:"o",Ù:"U",Ú:"U",Û:"U",Ü:"U",ù:"u",ú:"u",û:"u",ü:"u",Ý:"Y",ý:"y",ÿ:"y",Æ:"Ae",æ:"ae",Þ:"Th",þ:"th",ß:"ss",Ā:"A",Ă:"A",Ą:"A",ā:"a",ă:"a",ą:"a",Ć:"C",Ĉ:"C",Ċ:"C",Č:"C",ć:"c",ĉ:"c",ċ:"c",č:"c",Ď:"D",Đ:"D",ď:"d",đ:"d",Ē:"E",Ĕ:"E",Ė:"E",Ę:"E",Ě:"E",ē:"e",ĕ:"e",ė:"e",ę:"e",ě:"e",Ĝ:"G",Ğ:"G",Ġ:"G",Ģ:"G",ĝ:"g",ğ:"g",ġ:"g",ģ:"g",Ĥ:"H",Ħ:"H",ĥ:"h",ħ:"h",Ĩ:"I",Ī:"I",Ĭ:"I",Į:"I",İ:"I",ĩ:"i",ī:"i",ĭ:"i",į:"i",ı:"i",Ĵ:"J",ĵ:"j",Ķ:"K",ķ:"k",ĸ:"k",Ĺ:"L",Ļ:"L",Ľ:"L",Ŀ:"L",Ł:"L",ĺ:"l",ļ:"l",ľ:"l",ŀ:"l",ł:"l",Ń:"N",Ņ:"N",Ň:"N",Ŋ:"N",ń:"n",ņ:"n",ň:"n",ŋ:"n",Ō:"O",Ŏ:"O",Ő:"O",ō:"o",ŏ:"o",ő:"o",Ŕ:"R",Ŗ:"R",Ř:"R",ŕ:"r",ŗ:"r",ř:"r",Ś:"S",Ŝ:"S",Ş:"S",Š:"S",ś:"s",ŝ:"s",ş:"s",š:"s",Ţ:"T",Ť:"T",Ŧ:"T",ţ:"t",ť:"t",ŧ:"t",Ũ:"U",Ū:"U",Ŭ:"U",Ů:"U",Ű:"U",Ų:"U",ũ:"u",ū:"u",ŭ:"u",ů:"u",ű:"u",ų:"u",Ŵ:"W",ŵ:"w",Ŷ:"Y",ŷ:"y",Ÿ:"Y",Ź:"Z",Ż:"Z",Ž:"Z",ź:"z",ż:"z",ž:"z",IJ:"IJ",ij:"ij",Œ:"Oe",œ:"oe",ʼn:"'n",ſ:"s"},zO={"&":"&","<":"<",">":">",'"':""","'":"'"},BO={"&":"&","<":"<",">":">",""":'"',"'":"'"},UO={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},VO=parseFloat,WO=parseInt,Pb=typeof Yc=="object"&&Yc&&Yc.Object===Object&&Yc,HO=typeof self=="object"&&self&&self.Object===Object&&self,fn=Pb||HO||Function("return this")(),Tg=t&&!t.nodeType&&t,Bs=Tg&&!0&&e&&!e.nodeType&&e,Ab=Bs&&Bs.exports===Tg,Pg=Ab&&Pb.process,$r=function(){try{var j=Bs&&Bs.require&&Bs.require("util").types;return j||Pg&&Pg.binding&&Pg.binding("util")}catch{}}(),Ob=$r&&$r.isArrayBuffer,Mb=$r&&$r.isDate,Nb=$r&&$r.isMap,Db=$r&&$r.isRegExp,Ib=$r&&$r.isSet,Lb=$r&&$r.isTypedArray;function or(j,ee,q){switch(q.length){case 0:return j.call(ee);case 1:return j.call(ee,q[0]);case 2:return j.call(ee,q[0],q[1]);case 3:return j.call(ee,q[0],q[1],q[2])}return j.apply(ee,q)}function KO(j,ee,q,_e){for(var Ke=-1,ht=j==null?0:j.length;++Ke-1}function Ag(j,ee,q){for(var _e=-1,Ke=j==null?0:j.length;++_e-1;);return q}function Hb(j,ee){for(var q=j.length;q--&&La(ee,j[q],0)>-1;);return q}function t6(j,ee){for(var q=j.length,_e=0;q--;)j[q]===ee&&++_e;return _e}var n6=Dg(jO),r6=Dg(zO);function o6(j){return"\\"+UO[j]}function i6(j,ee){return j==null?n:j[ee]}function Fa(j){return DO.test(j)}function s6(j){return IO.test(j)}function a6(j){for(var ee,q=[];!(ee=j.next()).done;)q.push(ee.value);return q}function jg(j){var ee=-1,q=Array(j.size);return j.forEach(function(_e,Ke){q[++ee]=[Ke,_e]}),q}function Kb(j,ee){return function(q){return j(ee(q))}}function Oi(j,ee){for(var q=-1,_e=j.length,Ke=0,ht=[];++q<_e;){var en=j[q];(en===ee||en===h)&&(j[q]=h,ht[Ke++]=q)}return ht}function ef(j){var ee=-1,q=Array(j.size);return j.forEach(function(_e){q[++ee]=_e}),q}function l6(j){var ee=-1,q=Array(j.size);return j.forEach(function(_e){q[++ee]=[_e,_e]}),q}function c6(j,ee,q){for(var _e=q-1,Ke=j.length;++_e-1}function G6(a,c){var p=this.__data__,w=gf(p,a);return w<0?(++this.size,p.push([a,c])):p[w][1]=c,this}Xo.prototype.clear=W6,Xo.prototype.delete=H6,Xo.prototype.get=K6,Xo.prototype.has=Y6,Xo.prototype.set=G6;function Zo(a){var c=-1,p=a==null?0:a.length;for(this.clear();++c=c?a:c)),a}function Pr(a,c,p,w,$,T){var N,D=c&m,B=c&g,ne=c&y;if(p&&(N=$?p(a,w,$,T):p(a)),N!==n)return N;if(!It(a))return a;var re=Ye(a);if(re){if(N=QM(a),!D)return Wn(a,N)}else{var se=En(a),me=se==je||se==Ot;if(Fi(a))return R_(a,D);if(se==gt||se==We||me&&!$){if(N=B||me?{}:Y_(a),!D)return B?BM(a,uM(N,a)):zM(a,o_(N,a))}else{if(!Et[se])return $?a:{};N=JM(a,se,D)}}T||(T=new eo);var Re=T.get(a);if(Re)return Re;T.set(a,N),_S(a)?a.forEach(function(Le){N.add(Pr(Le,c,p,Le,a,T))}):xS(a)&&a.forEach(function(Le,nt){N.set(nt,Pr(Le,c,p,nt,a,T))});var Ie=ne?B?dv:uv:B?Kn:ln,Qe=re?n:Ie(a);return kr(Qe||a,function(Le,nt){Qe&&(nt=Le,Le=a[nt]),Fc(N,nt,Pr(Le,c,p,nt,a,T))}),N}function dM(a){var c=ln(a);return function(p){return i_(p,a,c)}}function i_(a,c,p){var w=p.length;if(a==null)return!w;for(a=_t(a);w--;){var $=p[w],T=c[$],N=a[$];if(N===n&&!($ in a)||!T(N))return!1}return!0}function s_(a,c,p){if(typeof a!="function")throw new Rr(s);return Hc(function(){a.apply(n,p)},c)}function jc(a,c,p,w){var $=-1,T=Qd,N=!0,D=a.length,B=[],ne=c.length;if(!D)return B;p&&(c=Mt(c,ir(p))),w?(T=Ag,N=!1):c.length>=o&&(T=Oc,N=!1,c=new Ws(c));e:for(;++$$?0:$+p),w=w===n||w>$?$:qe(w),w<0&&(w+=$),w=p>w?0:ES(w);p0&&p(D)?c>1?pn(D,c-1,p,w,$):Ai($,D):w||($[$.length]=D)}return $}var Kg=N_(),c_=N_(!0);function So(a,c){return a&&Kg(a,c,ln)}function Yg(a,c){return a&&c_(a,c,ln)}function yf(a,c){return Pi(c,function(p){return ti(a[p])})}function Ks(a,c){c=Ii(c,a);for(var p=0,w=c.length;a!=null&&pc}function hM(a,c){return a!=null&&yt.call(a,c)}function mM(a,c){return a!=null&&c in _t(a)}function gM(a,c,p){return a>=Sn(c,p)&&a=120&&re.length>=120)?new Ws(N&&re):n}re=a[0];var se=-1,me=D[0];e:for(;++se<$&&ne.length-1;)D!==a&&cf.call(D,B,1),cf.call(a,B,1);return a}function x_(a,c){for(var p=a?c.length:0,w=p-1;p--;){var $=c[p];if(p==w||$!==T){var T=$;ei($)?cf.call(a,$,1):rv(a,$)}}return a}function ev(a,c){return a+ff(e_()*(c-a+1))}function TM(a,c,p,w){for(var $=-1,T=tn(df((c-a)/(p||1)),0),N=q(T);T--;)N[w?T:++$]=a,a+=p;return N}function tv(a,c){var p="";if(!a||c<1||c>K)return p;do c%2&&(p+=a),c=ff(c/2),c&&(a+=a);while(c);return p}function et(a,c){return yv(Z_(a,c,Yn),a+"")}function PM(a){return r_(Xa(a))}function AM(a,c){var p=Xa(a);return Tf(p,Hs(c,0,p.length))}function Uc(a,c,p,w){if(!It(a))return a;c=Ii(c,a);for(var $=-1,T=c.length,N=T-1,D=a;D!=null&&++$$?0:$+c),p=p>$?$:p,p<0&&(p+=$),$=c>p?0:p-c>>>0,c>>>=0;for(var T=q($);++w<$;)T[w]=a[w+c];return T}function NM(a,c){var p;return Ni(a,function(w,$,T){return p=c(w,$,T),!p}),!!p}function xf(a,c,p){var w=0,$=a==null?w:a.length;if(typeof c=="number"&&c===c&&$<=Ve){for(;w<$;){var T=w+$>>>1,N=a[T];N!==null&&!ar(N)&&(p?N<=c:N=o){var ne=c?null:HM(a);if(ne)return ef(ne);N=!1,$=Oc,B=new Ws}else B=c?[]:D;e:for(;++w=w?a:Ar(a,c,p)}var k_=_6||function(a){return fn.clearTimeout(a)};function R_(a,c){if(c)return a.slice();var p=a.length,w=Xb?Xb(p):new a.constructor(p);return a.copy(w),w}function av(a){var c=new a.constructor(a.byteLength);return new af(c).set(new af(a)),c}function IM(a,c){var p=c?av(a.buffer):a.buffer;return new a.constructor(p,a.byteOffset,a.byteLength)}function LM(a){var c=new a.constructor(a.source,db.exec(a));return c.lastIndex=a.lastIndex,c}function FM(a){return Lc?_t(Lc.call(a)):{}}function T_(a,c){var p=c?av(a.buffer):a.buffer;return new a.constructor(p,a.byteOffset,a.length)}function P_(a,c){if(a!==c){var p=a!==n,w=a===null,$=a===a,T=ar(a),N=c!==n,D=c===null,B=c===c,ne=ar(c);if(!D&&!ne&&!T&&a>c||T&&N&&B&&!D&&!ne||w&&N&&B||!p&&B||!$)return 1;if(!w&&!T&&!ne&&a=D)return B;var ne=p[w];return B*(ne=="desc"?-1:1)}}return a.index-c.index}function A_(a,c,p,w){for(var $=-1,T=a.length,N=p.length,D=-1,B=c.length,ne=tn(T-N,0),re=q(B+ne),se=!w;++D1?p[$-1]:n,N=$>2?p[2]:n;for(T=a.length>3&&typeof T=="function"?($--,T):n,N&&Mn(p[0],p[1],N)&&(T=$<3?n:T,$=1),c=_t(c);++w<$;){var D=p[w];D&&a(c,D,w,T)}return c})}function M_(a,c){return function(p,w){if(p==null)return p;if(!Hn(p))return a(p,w);for(var $=p.length,T=c?$:-1,N=_t(p);(c?T--:++T<$)&&w(N[T],T,N)!==!1;);return p}}function N_(a){return function(c,p,w){for(var $=-1,T=_t(c),N=w(c),D=N.length;D--;){var B=N[a?D:++$];if(p(T[B],B,T)===!1)break}return c}}function UM(a,c,p){var w=c&C,$=Vc(a);function T(){var N=this&&this!==fn&&this instanceof T?$:a;return N.apply(w?p:this,arguments)}return T}function D_(a){return function(c){c=vt(c);var p=Fa(c)?Jr(c):n,w=p?p[0]:c.charAt(0),$=p?Li(p,1).join(""):c.slice(1);return w[a]()+$}}function Ka(a){return function(c){return Og(MS(OS(c).replace(OO,"")),a,"")}}function Vc(a){return function(){var c=arguments;switch(c.length){case 0:return new a;case 1:return new a(c[0]);case 2:return new a(c[0],c[1]);case 3:return new a(c[0],c[1],c[2]);case 4:return new a(c[0],c[1],c[2],c[3]);case 5:return new a(c[0],c[1],c[2],c[3],c[4]);case 6:return new a(c[0],c[1],c[2],c[3],c[4],c[5]);case 7:return new a(c[0],c[1],c[2],c[3],c[4],c[5],c[6])}var p=Wa(a.prototype),w=a.apply(p,c);return It(w)?w:p}}function VM(a,c,p){var w=Vc(a);function $(){for(var T=arguments.length,N=q(T),D=T,B=Ya($);D--;)N[D]=arguments[D];var ne=T<3&&N[0]!==B&&N[T-1]!==B?[]:Oi(N,B);if(T-=ne.length,T-1?$[T?c[N]:N]:n}}function L_(a){return Jo(function(c){var p=c.length,w=p,$=Tr.prototype.thru;for(a&&c.reverse();w--;){var T=c[w];if(typeof T!="function")throw new Rr(s);if($&&!N&&kf(T)=="wrapper")var N=new Tr([],!0)}for(w=N?w:p;++w1&&at.reverse(),re&&BD))return!1;var ne=T.get(a),re=T.get(c);if(ne&&re)return ne==c&&re==a;var se=-1,me=!0,Re=p&_?new Ws:n;for(T.set(a,c),T.set(c,a);++se1?"& ":"")+c[w],c=c.join(p>2?", ":" "),a.replace(an,`{ +/* [wrapped with `+c+`] */ +`)}function tN(a){return Ye(a)||Xs(a)||!!(Qb&&a&&a[Qb])}function ei(a,c){var p=typeof a;return c=c??K,!!c&&(p=="number"||p!="symbol"&&pO.test(a))&&a>-1&&a%1==0&&a0){if(++c>=G)return arguments[0]}else c=0;return a.apply(n,arguments)}}function Tf(a,c){var p=-1,w=a.length,$=w-1;for(c=c===n?w:c;++p1?a[c-1]:n;return p=typeof p=="function"?(a.pop(),p):n,lS(a,p)});function cS(a){var c=R(a);return c.__chain__=!0,c}function f7(a,c){return c(a),a}function Pf(a,c){return c(a)}var p7=Jo(function(a){var c=a.length,p=c?a[0]:0,w=this.__wrapped__,$=function(T){return Hg(T,a)};return c>1||this.__actions__.length||!(w instanceof ot)||!ei(p)?this.thru($):(w=w.slice(p,+p+(c?1:0)),w.__actions__.push({func:Pf,args:[$],thisArg:n}),new Tr(w,this.__chain__).thru(function(T){return c&&!T.length&&T.push(n),T}))});function h7(){return cS(this)}function m7(){return new Tr(this.value(),this.__chain__)}function g7(){this.__values__===n&&(this.__values__=SS(this.value()));var a=this.__index__>=this.__values__.length,c=a?n:this.__values__[this.__index__++];return{done:a,value:c}}function v7(){return this}function y7(a){for(var c,p=this;p instanceof mf;){var w=nS(p);w.__index__=0,w.__values__=n,c?$.__wrapped__=w:c=w;var $=w;p=p.__wrapped__}return $.__wrapped__=a,c}function w7(){var a=this.__wrapped__;if(a instanceof ot){var c=a;return this.__actions__.length&&(c=new ot(this)),c=c.reverse(),c.__actions__.push({func:Pf,args:[wv],thisArg:n}),new Tr(c,this.__chain__)}return this.thru(wv)}function x7(){return C_(this.__wrapped__,this.__actions__)}var b7=_f(function(a,c,p){yt.call(a,p)?++a[p]:qo(a,p,1)});function _7(a,c,p){var w=Ye(a)?Fb:fM;return p&&Mn(a,c,p)&&(c=n),w(a,De(c,3))}function S7(a,c){var p=Ye(a)?Pi:l_;return p(a,De(c,3))}var E7=I_(rS),C7=I_(oS);function $7(a,c){return pn(Af(a,c),1)}function k7(a,c){return pn(Af(a,c),ie)}function R7(a,c,p){return p=p===n?1:qe(p),pn(Af(a,c),p)}function uS(a,c){var p=Ye(a)?kr:Ni;return p(a,De(c,3))}function dS(a,c){var p=Ye(a)?YO:a_;return p(a,De(c,3))}var T7=_f(function(a,c,p){yt.call(a,p)?a[p].push(c):qo(a,p,[c])});function P7(a,c,p,w){a=Hn(a)?a:Xa(a),p=p&&!w?qe(p):0;var $=a.length;return p<0&&(p=tn($+p,0)),If(a)?p<=$&&a.indexOf(c,p)>-1:!!$&&La(a,c,p)>-1}var A7=et(function(a,c,p){var w=-1,$=typeof c=="function",T=Hn(a)?q(a.length):[];return Ni(a,function(N){T[++w]=$?or(c,N,p):zc(N,c,p)}),T}),O7=_f(function(a,c,p){qo(a,p,c)});function Af(a,c){var p=Ye(a)?Mt:h_;return p(a,De(c,3))}function M7(a,c,p,w){return a==null?[]:(Ye(c)||(c=c==null?[]:[c]),p=w?n:p,Ye(p)||(p=p==null?[]:[p]),y_(a,c,p))}var N7=_f(function(a,c,p){a[p?0:1].push(c)},function(){return[[],[]]});function D7(a,c,p){var w=Ye(a)?Og:Ub,$=arguments.length<3;return w(a,De(c,4),p,$,Ni)}function I7(a,c,p){var w=Ye(a)?GO:Ub,$=arguments.length<3;return w(a,De(c,4),p,$,a_)}function L7(a,c){var p=Ye(a)?Pi:l_;return p(a,Nf(De(c,3)))}function F7(a){var c=Ye(a)?r_:PM;return c(a)}function j7(a,c,p){(p?Mn(a,c,p):c===n)?c=1:c=qe(c);var w=Ye(a)?aM:AM;return w(a,c)}function z7(a){var c=Ye(a)?lM:MM;return c(a)}function B7(a){if(a==null)return 0;if(Hn(a))return If(a)?ja(a):a.length;var c=En(a);return c==ct||c==Z?a.size:qg(a).length}function U7(a,c,p){var w=Ye(a)?Mg:NM;return p&&Mn(a,c,p)&&(c=n),w(a,De(c,3))}var V7=et(function(a,c){if(a==null)return[];var p=c.length;return p>1&&Mn(a,c[0],c[1])?c=[]:p>2&&Mn(c[0],c[1],c[2])&&(c=[c[0]]),y_(a,pn(c,1),[])}),Of=S6||function(){return fn.Date.now()};function W7(a,c){if(typeof c!="function")throw new Rr(s);return a=qe(a),function(){if(--a<1)return c.apply(this,arguments)}}function fS(a,c,p){return c=p?n:c,c=a&&c==null?a.length:c,Qo(a,A,n,n,n,n,c)}function pS(a,c){var p;if(typeof c!="function")throw new Rr(s);return a=qe(a),function(){return--a>0&&(p=c.apply(this,arguments)),a<=1&&(c=n),p}}var bv=et(function(a,c,p){var w=C;if(p.length){var $=Oi(p,Ya(bv));w|=P}return Qo(a,w,c,p,$)}),hS=et(function(a,c,p){var w=C|S;if(p.length){var $=Oi(p,Ya(hS));w|=P}return Qo(c,w,a,p,$)});function mS(a,c,p){c=p?n:c;var w=Qo(a,E,n,n,n,n,n,c);return w.placeholder=mS.placeholder,w}function gS(a,c,p){c=p?n:c;var w=Qo(a,k,n,n,n,n,n,c);return w.placeholder=gS.placeholder,w}function vS(a,c,p){var w,$,T,N,D,B,ne=0,re=!1,se=!1,me=!0;if(typeof a!="function")throw new Rr(s);c=Mr(c)||0,It(p)&&(re=!!p.leading,se="maxWait"in p,T=se?tn(Mr(p.maxWait)||0,c):T,me="trailing"in p?!!p.trailing:me);function Re(Gt){var no=w,ri=$;return w=$=n,ne=Gt,N=a.apply(ri,no),N}function Ie(Gt){return ne=Gt,D=Hc(nt,c),re?Re(Gt):N}function Qe(Gt){var no=Gt-B,ri=Gt-ne,IS=c-no;return se?Sn(IS,T-ri):IS}function Le(Gt){var no=Gt-B,ri=Gt-ne;return B===n||no>=c||no<0||se&&ri>=T}function nt(){var Gt=Of();if(Le(Gt))return at(Gt);D=Hc(nt,Qe(Gt))}function at(Gt){return D=n,me&&w?Re(Gt):(w=$=n,N)}function lr(){D!==n&&k_(D),ne=0,w=B=$=D=n}function Nn(){return D===n?N:at(Of())}function cr(){var Gt=Of(),no=Le(Gt);if(w=arguments,$=this,B=Gt,no){if(D===n)return Ie(B);if(se)return k_(D),D=Hc(nt,c),Re(B)}return D===n&&(D=Hc(nt,c)),N}return cr.cancel=lr,cr.flush=Nn,cr}var H7=et(function(a,c){return s_(a,1,c)}),K7=et(function(a,c,p){return s_(a,Mr(c)||0,p)});function Y7(a){return Qo(a,F)}function Mf(a,c){if(typeof a!="function"||c!=null&&typeof c!="function")throw new Rr(s);var p=function(){var w=arguments,$=c?c.apply(this,w):w[0],T=p.cache;if(T.has($))return T.get($);var N=a.apply(this,w);return p.cache=T.set($,N)||T,N};return p.cache=new(Mf.Cache||Zo),p}Mf.Cache=Zo;function Nf(a){if(typeof a!="function")throw new Rr(s);return function(){var c=arguments;switch(c.length){case 0:return!a.call(this);case 1:return!a.call(this,c[0]);case 2:return!a.call(this,c[0],c[1]);case 3:return!a.call(this,c[0],c[1],c[2])}return!a.apply(this,c)}}function G7(a){return pS(2,a)}var X7=DM(function(a,c){c=c.length==1&&Ye(c[0])?Mt(c[0],ir(De())):Mt(pn(c,1),ir(De()));var p=c.length;return et(function(w){for(var $=-1,T=Sn(w.length,p);++$=c}),Xs=d_(function(){return arguments}())?d_:function(a){return Bt(a)&&yt.call(a,"callee")&&!qb.call(a,"callee")},Ye=q.isArray,u4=Ob?ir(Ob):yM;function Hn(a){return a!=null&&Df(a.length)&&!ti(a)}function Yt(a){return Bt(a)&&Hn(a)}function d4(a){return a===!0||a===!1||Bt(a)&&On(a)==xe}var Fi=C6||Mv,f4=Mb?ir(Mb):wM;function p4(a){return Bt(a)&&a.nodeType===1&&!Kc(a)}function h4(a){if(a==null)return!0;if(Hn(a)&&(Ye(a)||typeof a=="string"||typeof a.splice=="function"||Fi(a)||Ga(a)||Xs(a)))return!a.length;var c=En(a);if(c==ct||c==Z)return!a.size;if(Wc(a))return!qg(a).length;for(var p in a)if(yt.call(a,p))return!1;return!0}function m4(a,c){return Bc(a,c)}function g4(a,c,p){p=typeof p=="function"?p:n;var w=p?p(a,c):n;return w===n?Bc(a,c,n,p):!!w}function Sv(a){if(!Bt(a))return!1;var c=On(a);return c==Oe||c==Ae||typeof a.message=="string"&&typeof a.name=="string"&&!Kc(a)}function v4(a){return typeof a=="number"&&Jb(a)}function ti(a){if(!It(a))return!1;var c=On(a);return c==je||c==Ot||c==fe||c==I}function wS(a){return typeof a=="number"&&a==qe(a)}function Df(a){return typeof a=="number"&&a>-1&&a%1==0&&a<=K}function It(a){var c=typeof a;return a!=null&&(c=="object"||c=="function")}function Bt(a){return a!=null&&typeof a=="object"}var xS=Nb?ir(Nb):bM;function y4(a,c){return a===c||Zg(a,c,pv(c))}function w4(a,c,p){return p=typeof p=="function"?p:n,Zg(a,c,pv(c),p)}function x4(a){return bS(a)&&a!=+a}function b4(a){if(oN(a))throw new Ke(i);return f_(a)}function _4(a){return a===null}function S4(a){return a==null}function bS(a){return typeof a=="number"||Bt(a)&&On(a)==Kt}function Kc(a){if(!Bt(a)||On(a)!=gt)return!1;var c=lf(a);if(c===null)return!0;var p=yt.call(c,"constructor")&&c.constructor;return typeof p=="function"&&p instanceof p&&rf.call(p)==w6}var Ev=Db?ir(Db):_M;function E4(a){return wS(a)&&a>=-K&&a<=K}var _S=Ib?ir(Ib):SM;function If(a){return typeof a=="string"||!Ye(a)&&Bt(a)&&On(a)==we}function ar(a){return typeof a=="symbol"||Bt(a)&&On(a)==he}var Ga=Lb?ir(Lb):EM;function C4(a){return a===n}function $4(a){return Bt(a)&&En(a)==ke}function k4(a){return Bt(a)&&On(a)==ft}var R4=$f(Qg),T4=$f(function(a,c){return a<=c});function SS(a){if(!a)return[];if(Hn(a))return If(a)?Jr(a):Wn(a);if(Mc&&a[Mc])return a6(a[Mc]());var c=En(a),p=c==ct?jg:c==Z?ef:Xa;return p(a)}function ni(a){if(!a)return a===0?a:0;if(a=Mr(a),a===ie||a===-ie){var c=a<0?-1:1;return c*Q}return a===a?a:0}function qe(a){var c=ni(a),p=c%1;return c===c?p?c-p:c:0}function ES(a){return a?Hs(qe(a),0,le):0}function Mr(a){if(typeof a=="number")return a;if(ar(a))return W;if(It(a)){var c=typeof a.valueOf=="function"?a.valueOf():a;a=It(c)?c+"":c}if(typeof a!="string")return a===0?a:+a;a=Vb(a);var p=uO.test(a);return p||fO.test(a)?WO(a.slice(2),p?2:8):cO.test(a)?W:+a}function CS(a){return Eo(a,Kn(a))}function P4(a){return a?Hs(qe(a),-K,K):a===0?a:0}function vt(a){return a==null?"":sr(a)}var A4=Ha(function(a,c){if(Wc(c)||Hn(c)){Eo(c,ln(c),a);return}for(var p in c)yt.call(c,p)&&Fc(a,p,c[p])}),$S=Ha(function(a,c){Eo(c,Kn(c),a)}),Lf=Ha(function(a,c,p,w){Eo(c,Kn(c),a,w)}),O4=Ha(function(a,c,p,w){Eo(c,ln(c),a,w)}),M4=Jo(Hg);function N4(a,c){var p=Wa(a);return c==null?p:o_(p,c)}var D4=et(function(a,c){a=_t(a);var p=-1,w=c.length,$=w>2?c[2]:n;for($&&Mn(c[0],c[1],$)&&(w=1);++p1),T}),Eo(a,dv(a),p),w&&(p=Pr(p,m|g|y,KM));for(var $=c.length;$--;)rv(p,c[$]);return p});function J4(a,c){return RS(a,Nf(De(c)))}var e8=Jo(function(a,c){return a==null?{}:kM(a,c)});function RS(a,c){if(a==null)return{};var p=Mt(dv(a),function(w){return[w]});return c=De(c),w_(a,p,function(w,$){return c(w,$[0])})}function t8(a,c,p){c=Ii(c,a);var w=-1,$=c.length;for($||($=1,a=n);++w<$;){var T=a==null?n:a[Co(c[w])];T===n&&(w=$,T=p),a=ti(T)?T.call(a):T}return a}function n8(a,c,p){return a==null?a:Uc(a,c,p)}function r8(a,c,p,w){return w=typeof w=="function"?w:n,a==null?a:Uc(a,c,p,w)}var TS=B_(ln),PS=B_(Kn);function o8(a,c,p){var w=Ye(a),$=w||Fi(a)||Ga(a);if(c=De(c,4),p==null){var T=a&&a.constructor;$?p=w?new T:[]:It(a)?p=ti(T)?Wa(lf(a)):{}:p={}}return($?kr:So)(a,function(N,D,B){return c(p,N,D,B)}),p}function i8(a,c){return a==null?!0:rv(a,c)}function s8(a,c,p){return a==null?a:E_(a,c,sv(p))}function a8(a,c,p,w){return w=typeof w=="function"?w:n,a==null?a:E_(a,c,sv(p),w)}function Xa(a){return a==null?[]:Fg(a,ln(a))}function l8(a){return a==null?[]:Fg(a,Kn(a))}function c8(a,c,p){return p===n&&(p=c,c=n),p!==n&&(p=Mr(p),p=p===p?p:0),c!==n&&(c=Mr(c),c=c===c?c:0),Hs(Mr(a),c,p)}function u8(a,c,p){return c=ni(c),p===n?(p=c,c=0):p=ni(p),a=Mr(a),gM(a,c,p)}function d8(a,c,p){if(p&&typeof p!="boolean"&&Mn(a,c,p)&&(c=p=n),p===n&&(typeof c=="boolean"?(p=c,c=n):typeof a=="boolean"&&(p=a,a=n)),a===n&&c===n?(a=0,c=1):(a=ni(a),c===n?(c=a,a=0):c=ni(c)),a>c){var w=a;a=c,c=w}if(p||a%1||c%1){var $=e_();return Sn(a+$*(c-a+VO("1e-"+(($+"").length-1))),c)}return ev(a,c)}var f8=Ka(function(a,c,p){return c=c.toLowerCase(),a+(p?AS(c):c)});function AS(a){return kv(vt(a).toLowerCase())}function OS(a){return a=vt(a),a&&a.replace(hO,n6).replace(MO,"")}function p8(a,c,p){a=vt(a),c=sr(c);var w=a.length;p=p===n?w:Hs(qe(p),0,w);var $=p;return p-=c.length,p>=0&&a.slice(p,$)==c}function h8(a){return a=vt(a),a&&xg.test(a)?a.replace(Rc,r6):a}function m8(a){return a=vt(a),a&&Ge.test(a)?a.replace(H,"\\$&"):a}var g8=Ka(function(a,c,p){return a+(p?"-":"")+c.toLowerCase()}),v8=Ka(function(a,c,p){return a+(p?" ":"")+c.toLowerCase()}),y8=D_("toLowerCase");function w8(a,c,p){a=vt(a),c=qe(c);var w=c?ja(a):0;if(!c||w>=c)return a;var $=(c-w)/2;return Cf(ff($),p)+a+Cf(df($),p)}function x8(a,c,p){a=vt(a),c=qe(c);var w=c?ja(a):0;return c&&w>>0,p?(a=vt(a),a&&(typeof c=="string"||c!=null&&!Ev(c))&&(c=sr(c),!c&&Fa(a))?Li(Jr(a),0,p):a.split(c,p)):[]}var k8=Ka(function(a,c,p){return a+(p?" ":"")+kv(c)});function R8(a,c,p){return a=vt(a),p=p==null?0:Hs(qe(p),0,a.length),c=sr(c),a.slice(p,p+c.length)==c}function T8(a,c,p){var w=R.templateSettings;p&&Mn(a,c,p)&&(c=n),a=vt(a),c=Lf({},c,w,U_);var $=Lf({},c.imports,w.imports,U_),T=ln($),N=Fg($,T),D,B,ne=0,re=c.interpolate||Xd,se="__p += '",me=zg((c.escape||Xd).source+"|"+re.source+"|"+(re===Ac?lO:Xd).source+"|"+(c.evaluate||Xd).source+"|$","g"),Re="//# sourceURL="+(yt.call(c,"sourceURL")?(c.sourceURL+"").replace(/\s/g," "):"lodash.templateSources["+ ++FO+"]")+` +`;a.replace(me,function(Le,nt,at,lr,Nn,cr){return at||(at=lr),se+=a.slice(ne,cr).replace(mO,o6),nt&&(D=!0,se+=`' + +__e(`+nt+`) + +'`),Nn&&(B=!0,se+=`'; +`+Nn+`; +__p += '`),at&&(se+=`' + +((__t = (`+at+`)) == null ? '' : __t) + +'`),ne=cr+Le.length,Le}),se+=`'; +`;var Ie=yt.call(c,"variable")&&c.variable;if(!Ie)se=`with (obj) { +`+se+` +} +`;else if(sO.test(Ie))throw new Ke(l);se=(B?se.replace(yg,""):se).replace(wg,"$1").replace(Kd,"$1;"),se="function("+(Ie||"obj")+`) { +`+(Ie?"":`obj || (obj = {}); +`)+"var __t, __p = ''"+(D?", __e = _.escape":"")+(B?`, __j = Array.prototype.join; +function print() { __p += __j.call(arguments, '') } +`:`; +`)+se+`return __p +}`;var Qe=NS(function(){return ht(T,Re+"return "+se).apply(n,N)});if(Qe.source=se,Sv(Qe))throw Qe;return Qe}function P8(a){return vt(a).toLowerCase()}function A8(a){return vt(a).toUpperCase()}function O8(a,c,p){if(a=vt(a),a&&(p||c===n))return Vb(a);if(!a||!(c=sr(c)))return a;var w=Jr(a),$=Jr(c),T=Wb(w,$),N=Hb(w,$)+1;return Li(w,T,N).join("")}function M8(a,c,p){if(a=vt(a),a&&(p||c===n))return a.slice(0,Yb(a)+1);if(!a||!(c=sr(c)))return a;var w=Jr(a),$=Hb(w,Jr(c))+1;return Li(w,0,$).join("")}function N8(a,c,p){if(a=vt(a),a&&(p||c===n))return a.replace(st,"");if(!a||!(c=sr(c)))return a;var w=Jr(a),$=Wb(w,Jr(c));return Li(w,$).join("")}function D8(a,c){var p=V,w=J;if(It(c)){var $="separator"in c?c.separator:$;p="length"in c?qe(c.length):p,w="omission"in c?sr(c.omission):w}a=vt(a);var T=a.length;if(Fa(a)){var N=Jr(a);T=N.length}if(p>=T)return a;var D=p-ja(w);if(D<1)return w;var B=N?Li(N,0,D).join(""):a.slice(0,D);if($===n)return B+w;if(N&&(D+=B.length-D),Ev($)){if(a.slice(D).search($)){var ne,re=B;for($.global||($=zg($.source,vt(db.exec($))+"g")),$.lastIndex=0;ne=$.exec(re);)var se=ne.index;B=B.slice(0,se===n?D:se)}}else if(a.indexOf(sr($),D)!=D){var me=B.lastIndexOf($);me>-1&&(B=B.slice(0,me))}return B+w}function I8(a){return a=vt(a),a&&Tc.test(a)?a.replace(kc,d6):a}var L8=Ka(function(a,c,p){return a+(p?" ":"")+c.toUpperCase()}),kv=D_("toUpperCase");function MS(a,c,p){return a=vt(a),c=p?n:c,c===n?s6(a)?h6(a):qO(a):a.match(c)||[]}var NS=et(function(a,c){try{return or(a,n,c)}catch(p){return Sv(p)?p:new Ke(p)}}),F8=Jo(function(a,c){return kr(c,function(p){p=Co(p),qo(a,p,bv(a[p],a))}),a});function j8(a){var c=a==null?0:a.length,p=De();return a=c?Mt(a,function(w){if(typeof w[1]!="function")throw new Rr(s);return[p(w[0]),w[1]]}):[],et(function(w){for(var $=-1;++$K)return[];var p=le,w=Sn(a,le);c=De(c),a-=le;for(var $=Lg(w,c);++p0||c<0)?new ot(p):(a<0?p=p.takeRight(-a):a&&(p=p.drop(a)),c!==n&&(c=qe(c),p=c<0?p.dropRight(-c):p.take(c-a)),p)},ot.prototype.takeRightWhile=function(a){return this.reverse().takeWhile(a).reverse()},ot.prototype.toArray=function(){return this.take(le)},So(ot.prototype,function(a,c){var p=/^(?:filter|find|map|reject)|While$/.test(c),w=/^(?:head|last)$/.test(c),$=R[w?"take"+(c=="last"?"Right":""):c],T=w||/^find/.test(c);$&&(R.prototype[c]=function(){var N=this.__wrapped__,D=w?[1]:arguments,B=N instanceof ot,ne=D[0],re=B||Ye(N),se=function(nt){var at=$.apply(R,Ai([nt],D));return w&&me?at[0]:at};re&&p&&typeof ne=="function"&&ne.length!=1&&(B=re=!1);var me=this.__chain__,Re=!!this.__actions__.length,Ie=T&&!me,Qe=B&&!Re;if(!T&&re){N=Qe?N:new ot(this);var Le=a.apply(N,D);return Le.__actions__.push({func:Pf,args:[se],thisArg:n}),new Tr(Le,me)}return Ie&&Qe?a.apply(this,D):(Le=this.thru(se),Ie?w?Le.value()[0]:Le.value():Le)})}),kr(["pop","push","shift","sort","splice","unshift"],function(a){var c=tf[a],p=/^(?:push|sort|unshift)$/.test(a)?"tap":"thru",w=/^(?:pop|shift)$/.test(a);R.prototype[a]=function(){var $=arguments;if(w&&!this.__chain__){var T=this.value();return c.apply(Ye(T)?T:[],$)}return this[p](function(N){return c.apply(Ye(N)?N:[],$)})}}),So(ot.prototype,function(a,c){var p=R[c];if(p){var w=p.name+"";yt.call(Va,w)||(Va[w]=[]),Va[w].push({name:c,func:p})}}),Va[Sf(n,S).name]=[{name:"wrapper",func:n}],ot.prototype.clone=I6,ot.prototype.reverse=L6,ot.prototype.value=F6,R.prototype.at=p7,R.prototype.chain=h7,R.prototype.commit=m7,R.prototype.next=g7,R.prototype.plant=y7,R.prototype.reverse=w7,R.prototype.toJSON=R.prototype.valueOf=R.prototype.value=x7,R.prototype.first=R.prototype.head,Mc&&(R.prototype[Mc]=v7),R},za=m6();Bs?((Bs.exports=za)._=za,Tg._=za):fn._=za}).call(Yc)})(Lh,Lh.exports);var yH=Lh.exports;const wH=lm(yH);function Vr({width:e,height:t}){return e/t}function Fh(e,t=0){const n=10**t;return Math.round((e+Number.EPSILON)*n)/n}function xH(e){return(t,n)=>e(n)-e(t)}class bH{constructor(t){this.comparator=t,this.heap=[],this.n=0}greater(t,n){return this.comparator(this.heap[t],this.heap[n])<0}swap(t,n){const r=this.heap[t];this.heap[t]=this.heap[n],this.heap[n]=r}swim(t){let n=t,r=Math.floor(n/2);for(;n>1&&this.greater(r,n);)this.swap(r,n),n=r,r=Math.floor(n/2)}sink(t){let n=t,r=n*2;for(;r<=this.n&&(rl.weight));for(s.push({id:t,weight:0});s.size()>0;){const{id:l,weight:u}=s.pop();if(!o.has(l)){const d=e(l);o.add(l),d.forEach((h,m)=>{const g=u+h,y=r.get(m),x=i.get(m);(x===void 0||x>g&&(x/g>1.005||y!==void 0&&yMath.min(Vr(i),o),Number.MAX_VALUE);return Fh(n/t/r)+2}function MP(e,t,n,r){const o=t-(e.length-1)*n-2*r*e.length,i=e.reduce((s,l)=>s+Vr(l),0);return o/i}function $H(e,t,n,r,o,i,s){const l=e.slice(t,n),u=MP(l,r,i,s);return u>0?(u-o)**2*l.length:void 0}function kH({photos:e,layoutOptions:t,targetRowHeight:n,limitNodeSearch:r,rowConstraints:o}){return i=>{var s,l;const{containerWidth:u,spacing:d,padding:h}=t,m=new Map;m.set(i,0);const g=(s=o==null?void 0:o.minPhotos)!=null?s:1,y=Math.min(r,(l=o==null?void 0:o.maxPhotos)!=null?l:1/0);for(let x=i+g;xy);x+=1){const _=$H(e,i,x,u,n,d,h);if(_===void 0)break;m.set(x,_)}return m}}function RH({photos:e,layoutOptions:t}){const{spacing:n,padding:r,containerWidth:o,targetRowHeight:i,rowConstraints:s}=t,l=CH({photos:e,containerWidth:o,targetRowHeight:i}),u=kH({photos:e,layoutOptions:t,targetRowHeight:i,limitNodeSearch:l,rowConstraints:s}),d=EH(u,0,e.length);if(d===void 0)return;const h=[];for(let m=1;m({photo:x,index:_})).slice(d[m-1],d[m]),y=MP(g.map(({photo:x})=>x),o,n,r);h.push(g.map(({photo:x,index:_},C)=>({photo:x,layout:{height:y,width:y*Vr(x),index:_,photoIndex:C,photosCount:g.length}})))}return h}function qm(...e){return[...e].filter(t=>!!t).join(" ")}function NP(e,{width:t,photosCount:n},{spacing:r,padding:o,containerWidth:i}){const s=r*(n-1)+2*o*n;return`calc((${e} - ${s}px) / ${Fh((i-s)/t,5)})`}function TH(e,t){return t.layout!=="rows"?`calc(100% - ${2*t.padding}px)`:NP("100%",e,t)}function i2(e,t,n){var r,o;return NP((o=(r=e.match(/calc\((.*)\)/))==null?void 0:r[1])!=null?o:e,t,n)}function PH(e,t,n){let r,o;const i=e.srcSet||e.images;return i&&i.length>0&&(r=i.concat(i.find(({width:s})=>s===e.width)?[]:[{src:e.src,width:e.width,height:e.height}]).sort((s,l)=>s.width-l.width).map(s=>`${s.src} ${s.width}w`).join(", ")),n.sizes?o=(n.sizes.sizes||[]).map(({viewport:s,size:l})=>`${s} ${i2(l,t,n)}`).concat(i2(n.sizes.size,t,n)).join(", "):r&&(o=`${Math.ceil(t.width/n.containerWidth*100)}vw`),{srcSet:r,sizes:o}}function Ox(e){var t,n;const{photo:r,layout:o,layoutOptions:i,imageProps:{style:s,className:l,...u}={},renderPhoto:d}=e,{onClick:h}=i,m={display:"block",boxSizing:"content-box",width:TH(o,i),height:"auto",aspectRatio:`${r.width} / ${r.height}`,...i.padding?{padding:`${i.padding}px`}:null,...(i.layout==="columns"||i.layout==="masonry")&&o.photoIndex{h({event:C,photo:r,index:o.index})}:void 0,y={src:r.src,alt:(t=r.alt)!=null?t:"",title:r.title,onClick:g,style:m,className:qm("react-photo-album--photo",l),loading:"lazy",decoding:"async",...PH(r,o,i),...u},x=C=>{const{src:S,alt:b,srcSet:E,sizes:k,style:P,...M}=y;return f.createElement("img",{alt:b,...E?{srcSet:E,sizes:k}:null,src:S,style:C!=null&&C.wrapped?{display:"block",width:"100%",height:"100%"}:P,...M})},_=(({display:C,boxSizing:S,width:b,aspectRatio:E,padding:k,marginBottom:P,cursor:M})=>({display:C,boxSizing:S,width:b,aspectRatio:E,padding:k,marginBottom:P,cursor:M}))(m);return f.createElement(f.Fragment,null,(n=d==null?void 0:d({photo:r,layout:o,layoutOptions:i,imageProps:y,renderDefaultPhoto:x,wrapperStyle:_}))!=null?n:x())}function AH({rowContainerProps:e,children:t}){return f.createElement("div",{...e},t)}function OH(e){const{layoutOptions:t,rowIndex:n,rowsCount:r,renderRowContainer:o,rowContainerProps:{style:i,className:s,...l}={},children:u}=e,d={className:qm("react-photo-album--row",s),style:{display:"flex",flexDirection:"row",flexWrap:"nowrap",alignItems:"flex-start",justifyContent:"space-between",...nf.createElement(OH,{key:`row-${d}`,layoutOptions:n,rowIndex:d,rowsCount:l.length,renderRowContainer:o,rowContainerProps:s},u.map(({photo:h,layout:m})=>f.createElement(Ox,{key:h.key||h.src,photo:h,layout:m,layoutOptions:n,renderPhoto:r,imageProps:i}))))):null}function NH(e,t,n,r){const o=new Map,i=new Set;i.add(n);for(let s=0;s{const d=s>0?o.get(u)[s].weight:0;e(u).forEach(({neighbor:h,weight:m})=>{let g=o.get(h);g||(g=[],o.set(h,g));const y=d+m,x=g[s+1];(!x||x.weight>y&&(x.weight/y>1.0001||u0;i-=1)o=e.get(o)[i].node,r.push(o);return r.reverse()}function IH(e,t,n,r){return DH(NH(e,t,n,r),t,r)}function LH({photos:e,spacing:t,padding:n,targetColumnWidth:r,targetColumnHeight:o}){return i=>{const s=[],l=o*1.5;let u=r/Vr(e[i])+2*n;for(let d=i+1;dl||d===e.length));d+=1)u+=r/Vr(e[d])+t+2*n;return s}}function s2({path:e,photos:t,containerWidth:n,columnsGaps:r,columnsRatios:o,spacing:i,padding:s}){const l=[],u=o.reduce((d,h)=>d+h,0);for(let d=0;d({photo:y,index:x})).slice(e[d],e[d+1]),m=o.reduce((y,x,_)=>y+(r[d]-r[_])*x,0),g=(n-(e.length-2)*i-2*(e.length-1)*s-m)*o[d]/u;l.push(h.map(({photo:y,index:x},_)=>({photo:y,layout:{width:g,height:g/Vr(y),index:x,photoIndex:_,photosCount:h.length}})))}return l}function FH({photos:e,layoutOptions:t,targetColumnWidth:n}){const{columns:r,spacing:o,padding:i,containerWidth:s}=t,l=[],u=[];if(e.length<=r){const y=e.length>0?e.reduce((_,C)=>_+Vr(C),0)/e.length:1;for(let _=0;_Math.min(C,e.length)),photos:e,columnsRatios:u,columnsGaps:l,containerWidth:s,spacing:o,padding:i});return{columnsGaps:l,columnsRatios:u,columnsModel:x}}const d=(e.reduce((y,x)=>y+n/Vr(x),0)+o*(e.length-r)+2*i*e.length)/r,h=LH({photos:e,targetColumnWidth:n,targetColumnHeight:d,spacing:o,padding:i}),m=IH(h,r,0,e.length);for(let y=0;y_+1/Vr(C),0)}const g=s2({path:m,photos:e,columnsRatios:u,columnsGaps:l,containerWidth:s,spacing:o,padding:i});return{columnsGaps:l,columnsRatios:u,columnsModel:g}}function DP(e){const{photos:t,layoutOptions:n}=e,{columns:r,spacing:o,padding:i,containerWidth:s}=n,l=(s-o*(r-1)-2*i*r)/r,{columnsGaps:u,columnsRatios:d,columnsModel:h}=FH({photos:t,layoutOptions:n,targetColumnWidth:l});return h.findIndex(m=>m.findIndex(({layout:{width:g,height:y}})=>g<0||y<0)>=0)>=0?r>1?DP({photos:t,layoutOptions:{...n,columns:r-1}}):void 0:{columnsModel:h,columnsGaps:u,columnsRatios:d}}function jH({photos:e,layoutOptions:t}){return DP({photos:e,layoutOptions:t})}function zH({columnContainerProps:e,children:t}){return f.createElement("div",{...e},t)}function BH(e){const{layoutOptions:t,columnIndex:n,columnsCount:r,columnsGaps:o,columnsRatios:i}=e,{layout:s,spacing:l,padding:u}=t;if(s==="masonry"||!o||!i)return`calc((100% - ${l*(r-1)}px) / ${r})`;const d=i.reduce((m,g)=>m+g,0),h=i.reduce((m,g,y)=>m+(o[n]-o[y])*g,0);return`calc((100% - ${Fh((r-1)*l+2*r*u+h,3)}px) * ${Fh(i[n]/d,5)} + ${2*u}px)`}function IP(e){const{layoutOptions:t,renderColumnContainer:n,children:r,columnContainerProps:{style:o,className:i,...s}={},...l}=e,u={className:qm("react-photo-album--column",i),style:{display:"flex",flexDirection:"column",flexWrap:"nowrap",alignItems:"flex-start",width:BH(e),justifyContent:t.layout==="columns"?"space-between":"flex-start",...o},...s};return f.createElement(f.Fragment,null,(n??zH)({layoutOptions:t,columnContainerProps:u,children:r,...l}))}function UH(e){const{photos:t,layoutOptions:n,renderPhoto:r,renderColumnContainer:o,componentsProps:{imageProps:i,columnContainerProps:s}}=e,l=jH({photos:t,layoutOptions:n});if(!l)return null;const{columnsModel:u,columnsRatios:d,columnsGaps:h}=l;return f.createElement(f.Fragment,null,u.map((m,g)=>f.createElement(IP,{key:`column-${g}`,layoutOptions:n,columnIndex:g,columnsCount:u.length,columnsGaps:h,columnsRatios:d,renderColumnContainer:o,columnContainerProps:s},m.map(({photo:y,layout:x})=>f.createElement(Ox,{key:y.key||y.src,photo:y,layout:x,layoutOptions:n,renderPhoto:r,imageProps:i})))))}function LP(e){const{photos:t,layoutOptions:n}=e,{columns:r,spacing:o,padding:i,containerWidth:s}=n,l=(s-o*(r-1)-2*i*r)/r;if(l<=0)return r>1?LP({...e,layoutOptions:{...n,columns:r-1}}):void 0;const u=[];for(let h=0;h{const y=u.reduce((x,_,C)=>_[])).map(h=>h.map(({photo:m,index:g},y)=>({photo:m,layout:{width:l,height:l/Vr(m),index:g,photoIndex:y,photosCount:h.length}})))}function VH(e){const{photos:t,layoutOptions:n,renderPhoto:r,renderColumnContainer:o,componentsProps:{imageProps:i,columnContainerProps:s}}=e,l=LP({photos:t,layoutOptions:n});return l?f.createElement(f.Fragment,null,l.map((u,d)=>f.createElement(IP,{key:`masonry-column-${d}`,layoutOptions:n,columnsCount:l.length,columnIndex:d,renderColumnContainer:o,columnContainerProps:s},u.map(({photo:h,layout:m})=>f.createElement(Ox,{key:h.key||h.src,photo:h,layout:m,layoutOptions:n,renderPhoto:r,imageProps:i}))))):null}function WH({containerProps:e,children:t,containerRef:n}){return f.createElement("div",{ref:n,...e},t)}function HH(e){const{layout:t,renderContainer:n,children:r,containerRef:o,containerProps:{style:i,className:s,...l}={}}=e,u={className:qm("react-photo-album",`react-photo-album--${t}`,s),style:{display:"flex",flexWrap:"nowrap",justifyContent:"space-between",flexDirection:t==="rows"?"column":"row",...i},...l};return f.createElement(f.Fragment,null,(n??WH)({containerProps:u,containerRef:o,layout:t,children:r}))}function KH(e){const t=f.useRef(e);return(!e||!t.current||e.join()!==t.current.join())&&(t.current=e),t.current}function YH(e,{newContainerWidth:t,newScrollbarWidth:n}){const{containerWidth:r,scrollbarWidth:o}=e;return r!==void 0&&o!==void 0&&t!==void 0&&n!==void 0&&t>r&&t-r<=20&&n0){const r=[...t.filter(i=>i>0)].sort((i,s)=>s-i);r.push(Math.floor(r[r.length-1]/2));const o=n;n=r.find((i,s)=>i<=o||s===r.length-1)}return n}function XH(e,t){const[{containerWidth:n},r]=f.useReducer(YH,{containerWidth:t}),o=f.useRef(null),i=f.useRef();return{containerRef:f.useCallback(l=>{var u;(u=i.current)==null||u.disconnect(),i.current=void 0,o.current=l;const d=()=>r({newContainerWidth:GH(o.current,e),newScrollbarWidth:window.innerWidth-document.documentElement.clientWidth});d(),l&&typeof ResizeObserver<"u"&&(i.current=new ResizeObserver(d),i.current.observe(l))},[e]),containerWidth:n}}const ZH=Object.freeze([1200,600,300,0]);function Mx(e,t){return typeof e=="function"?e(t):e}function FP(e,t){return typeof e<"u"?Mx(e,t):void 0}function qH(e,t){const n=ZH.findIndex(r=>r<=t);return Mx(e[n>=0?n:0],t)}function fp(e,t,n,r=0){const o=FP(e,t);return Math.round(Math.max(o===void 0?qH(n,t):o,r))}function QH({layout:e,onClick:t,containerWidth:n,targetRowHeight:r,rowConstraints:o,columns:i,spacing:s,padding:l,sizes:u}){return{layout:e,onClick:t,containerWidth:n,columns:fp(i,n,[5,4,3,2],1),spacing:fp(s,n,[20,15,10,5]),padding:fp(l,n,[0,0,0,0,0]),targetRowHeight:fp(r,n,[d=>d/5,d=>d/4,d=>d/3,d=>d/2]),rowConstraints:FP(o,n),sizes:u}}function JH(e,t,n){const{photos:r,componentsProps:o}=e,i=Mx(o,t)||{};if(n){const{layout:s,spacing:l,padding:u,rowConstraints:d}=n;if(s==="rows"){const{singleRowMaxHeight:h}=d||{};if(h){const m=Math.floor(r.reduce((g,{width:y,height:x})=>g+y/x*h-2*u,u*r.length*2+l*(r.length-1)));m>0&&(i.containerProps=i.containerProps||{},i.containerProps.style={maxWidth:m,...i.containerProps.style})}}}return i}function eK(e,t,n){const{photos:r,layout:o,renderPhoto:i,renderRowContainer:s,renderColumnContainer:l}=e,u={photos:r,renderPhoto:i,componentsProps:t};return o==="rows"?f.createElement(MH,{layoutOptions:n,renderRowContainer:s,...u}):o==="columns"?f.createElement(UH,{layoutOptions:n,renderColumnContainer:l,...u}):f.createElement(VH,{layoutOptions:n,renderColumnContainer:l,...u})}function tK(e){const{photos:t,layout:n,renderContainer:r,defaultContainerWidth:o,breakpoints:i}=e,{containerRef:s,containerWidth:l}=XH(KH(i),o);if(!n||!["rows","columns","masonry"].includes(n)||!Array.isArray(t))return null;const u=l?QH({containerWidth:l,...e}):void 0,d=JH(e,l,u);return f.createElement(HH,{layout:n,containerRef:s,renderContainer:r,containerProps:d.containerProps},u&&eK(e,d,u))}function nK({title:e,titleId:t,...n},r){return f.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true",ref:r,"aria-labelledby":t},n),e?f.createElement("title",{id:t},e):null,f.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3 4.5h14.25M3 9h9.75M3 13.5h9.75m4.5-4.5v12m0 0l-3.75-3.75M17.25 21L21 17.25"}))}const rK=f.forwardRef(nK),oK=rK;function iK({title:e,titleId:t,...n},r){return f.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true",ref:r,"aria-labelledby":t},n),e?f.createElement("title",{id:t},e):null,f.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3 4.5h14.25M3 9h9.75M3 13.5h5.25m5.25-.75L17.25 9m0 0L21 12.75M17.25 9v12"}))}const sK=f.forwardRef(iK),aK=sK;function lK({title:e,titleId:t,...n},r){return f.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true",ref:r,"aria-labelledby":t},n),e?f.createElement("title",{id:t},e):null,f.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15.042 21.672L13.684 16.6m0 0l-2.51 2.225.569-9.47 5.227 7.917-3.286-.672zM12 2.25V4.5m5.834.166l-1.591 1.591M20.25 10.5H18M7.757 14.743l-1.59 1.59M6 10.5H3.75m4.007-4.243l-1.59-1.59"}))}const cK=f.forwardRef(lK),uK=cK;function bi(e){return Array.isArray?Array.isArray(e):BP(e)==="[object Array]"}const dK=1/0;function fK(e){if(typeof e=="string")return e;let t=e+"";return t=="0"&&1/e==-dK?"-0":t}function pK(e){return e==null?"":fK(e)}function Lo(e){return typeof e=="string"}function jP(e){return typeof e=="number"}function hK(e){return e===!0||e===!1||mK(e)&&BP(e)=="[object Boolean]"}function zP(e){return typeof e=="object"}function mK(e){return zP(e)&&e!==null}function hr(e){return e!=null}function k0(e){return!e.trim().length}function BP(e){return e==null?e===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}const gK="Incorrect 'index' type",vK=e=>`Invalid value for key ${e}`,yK=e=>`Pattern length exceeds max of ${e}.`,wK=e=>`Missing ${e} property in key`,xK=e=>`Property 'weight' in key '${e}' must be a positive integer`,a2=Object.prototype.hasOwnProperty;class bK{constructor(t){this._keys=[],this._keyMap={};let n=0;t.forEach(r=>{let o=UP(r);this._keys.push(o),this._keyMap[o.id]=o,n+=o.weight}),this._keys.forEach(r=>{r.weight/=n})}get(t){return this._keyMap[t]}keys(){return this._keys}toJSON(){return JSON.stringify(this._keys)}}function UP(e){let t=null,n=null,r=null,o=1,i=null;if(Lo(e)||bi(e))r=e,t=l2(e),n=h1(e);else{if(!a2.call(e,"name"))throw new Error(wK("name"));const s=e.name;if(r=s,a2.call(e,"weight")&&(o=e.weight,o<=0))throw new Error(xK(s));t=l2(s),n=h1(s),i=e.getFn}return{path:t,id:n,weight:o,src:r,getFn:i}}function l2(e){return bi(e)?e:e.split(".")}function h1(e){return bi(e)?e.join("."):e}function _K(e,t){let n=[],r=!1;const o=(i,s,l)=>{if(hr(i))if(!s[l])n.push(i);else{let u=s[l];const d=i[u];if(!hr(d))return;if(l===s.length-1&&(Lo(d)||jP(d)||hK(d)))n.push(pK(d));else if(bi(d)){r=!0;for(let h=0,m=d.length;he.score===t.score?e.idx{this._keysMap[n.id]=r})}create(){this.isCreated||!this.docs.length||(this.isCreated=!0,Lo(this.docs[0])?this.docs.forEach((t,n)=>{this._addString(t,n)}):this.docs.forEach((t,n)=>{this._addObject(t,n)}),this.norm.clear())}add(t){const n=this.size();Lo(t)?this._addString(t,n):this._addObject(t,n)}removeAt(t){this.records.splice(t,1);for(let n=t,r=this.size();n{let s=o.getFn?o.getFn(t):this.getFn(t,o.path);if(hr(s)){if(bi(s)){let l=[];const u=[{nestedArrIndex:-1,value:s}];for(;u.length;){const{nestedArrIndex:d,value:h}=u.pop();if(hr(h))if(Lo(h)&&!k0(h)){let m={v:h,i:d,n:this.norm.get(h)};l.push(m)}else bi(h)&&h.forEach((m,g)=>{u.push({nestedArrIndex:g,value:m})})}r.$[i]=l}else if(Lo(s)&&!k0(s)){let l={v:s,n:this.norm.get(s)};r.$[i]=l}}}),this.records.push(r)}toJSON(){return{keys:this.keys,records:this.records}}}function VP(e,t,{getFn:n=He.getFn,fieldNormWeight:r=He.fieldNormWeight}={}){const o=new Nx({getFn:n,fieldNormWeight:r});return o.setKeys(e.map(UP)),o.setSources(t),o.create(),o}function TK(e,{getFn:t=He.getFn,fieldNormWeight:n=He.fieldNormWeight}={}){const{keys:r,records:o}=e,i=new Nx({getFn:t,fieldNormWeight:n});return i.setKeys(r),i.setIndexRecords(o),i}function pp(e,{errors:t=0,currentLocation:n=0,expectedLocation:r=0,distance:o=He.distance,ignoreLocation:i=He.ignoreLocation}={}){const s=t/e.length;if(i)return s;const l=Math.abs(r-n);return o?s+l/o:l?1:s}function PK(e=[],t=He.minMatchCharLength){let n=[],r=-1,o=-1,i=0;for(let s=e.length;i=t&&n.push([r,o]),r=-1)}return e[i-1]&&i-r>=t&&n.push([r,i-1]),n}const ea=32;function AK(e,t,n,{location:r=He.location,distance:o=He.distance,threshold:i=He.threshold,findAllMatches:s=He.findAllMatches,minMatchCharLength:l=He.minMatchCharLength,includeMatches:u=He.includeMatches,ignoreLocation:d=He.ignoreLocation}={}){if(t.length>ea)throw new Error(yK(ea));const h=t.length,m=e.length,g=Math.max(0,Math.min(r,m));let y=i,x=g;const _=l>1||u,C=_?Array(m):[];let S;for(;(S=e.indexOf(t,x))>-1;){let A=pp(t,{currentLocation:S,expectedLocation:g,distance:o,ignoreLocation:d});if(y=Math.min(A,y),x=S+h,_){let O=0;for(;O=V;U-=1){let te=U-1,L=n[e.charAt(te)];if(_&&(C[te]=+!!L),G[U]=(G[U+1]<<1|1)&L,A&&(G[U]|=(b[U+1]|b[U])<<1|1|b[U+1]),G[U]&P&&(E=pp(t,{errors:A,currentLocation:te,expectedLocation:g,distance:o,ignoreLocation:d}),E<=y)){if(y=E,x=te,x<=g)break;V=Math.max(1,2*g-x)}}if(pp(t,{errors:A+1,currentLocation:g,expectedLocation:g,distance:o,ignoreLocation:d})>y)break;b=G}const M={isMatch:x>=0,score:Math.max(.001,E)};if(_){const A=PK(C,l);A.length?u&&(M.indices=A):M.isMatch=!1}return M}function OK(e){let t={};for(let n=0,r=e.length;n{this.chunks.push({pattern:g,alphabet:OK(g),startIndex:y})},m=this.pattern.length;if(m>ea){let g=0;const y=m%ea,x=m-y;for(;g{const{isMatch:S,score:b,indices:E}=AK(t,x,_,{location:o+C,distance:i,threshold:s,findAllMatches:l,minMatchCharLength:u,includeMatches:r,ignoreLocation:d});S&&(g=!0),m+=b,S&&E&&(h=[...h,...E])});let y={isMatch:g,score:g?m/this.chunks.length:1};return g&&r&&(y.indices=h),y}}class Ds{constructor(t){this.pattern=t}static isMultiMatch(t){return c2(t,this.multiRegex)}static isSingleMatch(t){return c2(t,this.singleRegex)}search(){}}function c2(e,t){const n=e.match(t);return n?n[1]:null}class MK extends Ds{constructor(t){super(t)}static get type(){return"exact"}static get multiRegex(){return/^="(.*)"$/}static get singleRegex(){return/^=(.*)$/}search(t){const n=t===this.pattern;return{isMatch:n,score:n?0:1,indices:[0,this.pattern.length-1]}}}class NK extends Ds{constructor(t){super(t)}static get type(){return"inverse-exact"}static get multiRegex(){return/^!"(.*)"$/}static get singleRegex(){return/^!(.*)$/}search(t){const r=t.indexOf(this.pattern)===-1;return{isMatch:r,score:r?0:1,indices:[0,t.length-1]}}}class DK extends Ds{constructor(t){super(t)}static get type(){return"prefix-exact"}static get multiRegex(){return/^\^"(.*)"$/}static get singleRegex(){return/^\^(.*)$/}search(t){const n=t.startsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[0,this.pattern.length-1]}}}class IK extends Ds{constructor(t){super(t)}static get type(){return"inverse-prefix-exact"}static get multiRegex(){return/^!\^"(.*)"$/}static get singleRegex(){return/^!\^(.*)$/}search(t){const n=!t.startsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[0,t.length-1]}}}class LK extends Ds{constructor(t){super(t)}static get type(){return"suffix-exact"}static get multiRegex(){return/^"(.*)"\$$/}static get singleRegex(){return/^(.*)\$$/}search(t){const n=t.endsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[t.length-this.pattern.length,t.length-1]}}}class FK extends Ds{constructor(t){super(t)}static get type(){return"inverse-suffix-exact"}static get multiRegex(){return/^!"(.*)"\$$/}static get singleRegex(){return/^!(.*)\$$/}search(t){const n=!t.endsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[0,t.length-1]}}}class HP extends Ds{constructor(t,{location:n=He.location,threshold:r=He.threshold,distance:o=He.distance,includeMatches:i=He.includeMatches,findAllMatches:s=He.findAllMatches,minMatchCharLength:l=He.minMatchCharLength,isCaseSensitive:u=He.isCaseSensitive,ignoreLocation:d=He.ignoreLocation}={}){super(t),this._bitapSearch=new WP(t,{location:n,threshold:r,distance:o,includeMatches:i,findAllMatches:s,minMatchCharLength:l,isCaseSensitive:u,ignoreLocation:d})}static get type(){return"fuzzy"}static get multiRegex(){return/^"(.*)"$/}static get singleRegex(){return/^(.*)$/}search(t){return this._bitapSearch.searchIn(t)}}class KP extends Ds{constructor(t){super(t)}static get type(){return"include"}static get multiRegex(){return/^'"(.*)"$/}static get singleRegex(){return/^'(.*)$/}search(t){let n=0,r;const o=[],i=this.pattern.length;for(;(r=t.indexOf(this.pattern,n))>-1;)n=r+i,o.push([r,n-1]);const s=!!o.length;return{isMatch:s,score:s?0:1,indices:o}}}const m1=[MK,KP,DK,IK,FK,LK,NK,HP],u2=m1.length,jK=/ +(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/,zK="|";function BK(e,t={}){return e.split(zK).map(n=>{let r=n.trim().split(jK).filter(i=>i&&!!i.trim()),o=[];for(let i=0,s=r.length;i!!(e[jh.AND]||e[jh.OR]),HK=e=>!!e[y1.PATH],KK=e=>!bi(e)&&zP(e)&&!w1(e),d2=e=>({[jh.AND]:Object.keys(e).map(t=>({[t]:e[t]}))});function YP(e,t,{auto:n=!0}={}){const r=o=>{let i=Object.keys(o);const s=HK(o);if(!s&&i.length>1&&!w1(o))return r(d2(o));if(KK(o)){const u=s?o[y1.PATH]:i[0],d=s?o[y1.PATTERN]:o[u];if(!Lo(d))throw new Error(vK(u));const h={keyId:h1(u),pattern:d};return n&&(h.searcher=v1(d,t)),h}let l={children:[],operator:i[0]};return i.forEach(u=>{const d=o[u];bi(d)&&d.forEach(h=>{l.children.push(r(h))})}),l};return w1(e)||(e=d2(e)),r(e)}function YK(e,{ignoreFieldNorm:t=He.ignoreFieldNorm}){e.forEach(n=>{let r=1;n.matches.forEach(({key:o,norm:i,score:s})=>{const l=o?o.weight:null;r*=Math.pow(s===0&&l?Number.EPSILON:s,(l||1)*(t?1:i))}),n.score=r})}function GK(e,t){const n=e.matches;t.matches=[],hr(n)&&n.forEach(r=>{if(!hr(r.indices)||!r.indices.length)return;const{indices:o,value:i}=r;let s={indices:o,value:i};r.key&&(s.key=r.key.src),r.idx>-1&&(s.refIndex=r.idx),t.matches.push(s)})}function XK(e,t){t.score=e.score}function ZK(e,t,{includeMatches:n=He.includeMatches,includeScore:r=He.includeScore}={}){const o=[];return n&&o.push(GK),r&&o.push(XK),e.map(i=>{const{idx:s}=i,l={item:t[s],refIndex:s};return o.length&&o.forEach(u=>{u(i,l)}),l})}class _c{constructor(t,n={},r){this.options={...He,...n},this.options.useExtendedSearch,this._keyStore=new bK(this.options.keys),this.setCollection(t,r)}setCollection(t,n){if(this._docs=t,n&&!(n instanceof Nx))throw new Error(gK);this._myIndex=n||VP(this.options.keys,this._docs,{getFn:this.options.getFn,fieldNormWeight:this.options.fieldNormWeight})}add(t){hr(t)&&(this._docs.push(t),this._myIndex.add(t))}remove(t=()=>!1){const n=[];for(let r=0,o=this._docs.length;r-1&&(u=u.slice(0,n)),ZK(u,this._docs,{includeMatches:r,includeScore:o})}_searchStringList(t){const n=v1(t,this.options),{records:r}=this._myIndex,o=[];return r.forEach(({v:i,i:s,n:l})=>{if(!hr(i))return;const{isMatch:u,score:d,indices:h}=n.searchIn(i);u&&o.push({item:i,idx:s,matches:[{score:d,value:i,norm:l,indices:h}]})}),o}_searchLogical(t){const n=YP(t,this.options),r=(l,u,d)=>{if(!l.children){const{keyId:m,searcher:g}=l,y=this._findMatches({key:this._keyStore.get(m),value:this._myIndex.getValueForItemAtKeyId(u,m),searcher:g});return y&&y.length?[{idx:d,item:u,matches:y}]:[]}const h=[];for(let m=0,g=l.children.length;m{if(hr(l)){let d=r(n,l,u);d.length&&(i[u]||(i[u]={idx:u,item:l,matches:[]},s.push(i[u])),d.forEach(({matches:h})=>{i[u].matches.push(...h)}))}}),s}_searchObjectList(t){const n=v1(t,this.options),{keys:r,records:o}=this._myIndex,i=[];return o.forEach(({$:s,i:l})=>{if(!hr(s))return;let u=[];r.forEach((d,h)=>{u.push(...this._findMatches({key:d,value:s[h],searcher:n}))}),u.length&&i.push({idx:l,item:s,matches:u})}),i}_findMatches({key:t,value:n,searcher:r}){if(!hr(n))return[];let o=[];if(bi(n))n.forEach(({v:i,i:s,n:l})=>{if(!hr(i))return;const{isMatch:u,score:d,indices:h}=r.searchIn(i);u&&o.push({score:d,key:t,value:i,idx:s,norm:l,indices:h})});else{const{v:i,n:s}=n,{isMatch:l,score:u,indices:d}=r.searchIn(i);l&&o.push({score:u,key:t,value:i,norm:s,indices:d})}return o}}_c.version="7.0.0";_c.createIndex=VP;_c.parseIndex=TK;_c.config=He;_c.parseQuery=YP;WK(VK);function zd(e){const t=e+"CollectionProvider",[n,r]=An(t),[o,i]=n(t,{collectionRef:{current:null},itemMap:new Map}),s=y=>{const{scope:x,children:_}=y,C=Fe.useRef(null),S=Fe.useRef(new Map).current;return Fe.createElement(o,{scope:x,itemMap:S,collectionRef:C},_)},l=e+"CollectionSlot",u=Fe.forwardRef((y,x)=>{const{scope:_,children:C}=y,S=i(l,_),b=Be(x,S.collectionRef);return Fe.createElement(Wo,{ref:b},C)}),d=e+"CollectionItemSlot",h="data-radix-collection-item",m=Fe.forwardRef((y,x)=>{const{scope:_,children:C,...S}=y,b=Fe.useRef(null),E=Be(x,b),k=i(d,_);return Fe.useEffect(()=>(k.itemMap.set(b,{ref:b,...S}),()=>void k.itemMap.delete(b))),Fe.createElement(Wo,{[h]:"",ref:E},C)});function g(y){const x=i(e+"CollectionConsumer",y);return Fe.useCallback(()=>{const C=x.collectionRef.current;if(!C)return[];const S=Array.from(C.querySelectorAll(`[${h}]`));return Array.from(x.itemMap.values()).sort((k,P)=>S.indexOf(k.ref.current)-S.indexOf(P.ref.current))},[x.collectionRef,x.itemMap])}return[{Provider:s,Slot:u,ItemSlot:m},g,r]}const qK=f.createContext(void 0);function Sc(e){const t=f.useContext(qK);return e||t||"ltr"}const R0="rovingFocusGroup.onEntryFocus",QK={bubbles:!1,cancelable:!0},Dx="RovingFocusGroup",[x1,GP,JK]=zd(Dx),[eY,Qm]=An(Dx,[JK]),[tY,nY]=eY(Dx),rY=f.forwardRef((e,t)=>f.createElement(x1.Provider,{scope:e.__scopeRovingFocusGroup},f.createElement(x1.Slot,{scope:e.__scopeRovingFocusGroup},f.createElement(oY,Y({},e,{ref:t}))))),oY=f.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:o=!1,dir:i,currentTabStopId:s,defaultCurrentTabStopId:l,onCurrentTabStopIdChange:u,onEntryFocus:d,...h}=e,m=f.useRef(null),g=Be(t,m),y=Sc(i),[x=null,_]=Zr({prop:s,defaultProp:l,onChange:u}),[C,S]=f.useState(!1),b=Ft(d),E=GP(n),k=f.useRef(!1),[P,M]=f.useState(0);return f.useEffect(()=>{const A=m.current;if(A)return A.addEventListener(R0,b),()=>A.removeEventListener(R0,b)},[b]),f.createElement(tY,{scope:n,orientation:r,dir:y,loop:o,currentTabStopId:x,onItemFocus:f.useCallback(A=>_(A),[_]),onItemShiftTab:f.useCallback(()=>S(!0),[]),onFocusableItemAdd:f.useCallback(()=>M(A=>A+1),[]),onFocusableItemRemove:f.useCallback(()=>M(A=>A-1),[])},f.createElement(Pe.div,Y({tabIndex:C||P===0?-1:0,"data-orientation":r},h,{ref:g,style:{outline:"none",...e.style},onMouseDown:ue(e.onMouseDown,()=>{k.current=!0}),onFocus:ue(e.onFocus,A=>{const O=!k.current;if(A.target===A.currentTarget&&O&&!C){const F=new CustomEvent(R0,QK);if(A.currentTarget.dispatchEvent(F),!F.defaultPrevented){const V=E().filter(te=>te.focusable),J=V.find(te=>te.active),G=V.find(te=>te.id===x),U=[J,G,...V].filter(Boolean).map(te=>te.ref.current);XP(U)}}k.current=!1}),onBlur:ue(e.onBlur,()=>S(!1))})))}),iY="RovingFocusGroupItem",sY=f.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:o=!1,tabStopId:i,...s}=e,l=nr(),u=i||l,d=nY(iY,n),h=d.currentTabStopId===u,m=GP(n),{onFocusableItemAdd:g,onFocusableItemRemove:y}=d;return f.useEffect(()=>{if(r)return g(),()=>y()},[r,g,y]),f.createElement(x1.ItemSlot,{scope:n,id:u,focusable:r,active:o},f.createElement(Pe.span,Y({tabIndex:h?0:-1,"data-orientation":d.orientation},s,{ref:t,onMouseDown:ue(e.onMouseDown,x=>{r?d.onItemFocus(u):x.preventDefault()}),onFocus:ue(e.onFocus,()=>d.onItemFocus(u)),onKeyDown:ue(e.onKeyDown,x=>{if(x.key==="Tab"&&x.shiftKey){d.onItemShiftTab();return}if(x.target!==x.currentTarget)return;const _=cY(x,d.orientation,d.dir);if(_!==void 0){x.preventDefault();let S=m().filter(b=>b.focusable).map(b=>b.ref.current);if(_==="last")S.reverse();else if(_==="prev"||_==="next"){_==="prev"&&S.reverse();const b=S.indexOf(x.currentTarget);S=d.loop?uY(S,b+1):S.slice(b+1)}setTimeout(()=>XP(S))}})})))}),aY={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function lY(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function cY(e,t,n){const r=lY(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return aY[r]}function XP(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function uY(e,t){return e.map((n,r)=>e[(t+r)%e.length])}const ZP=rY,qP=sY,QP="Tabs",[dY,wte]=An(QP,[Qm]),JP=Qm(),[fY,Ix]=dY(QP),pY=f.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,onValueChange:o,defaultValue:i,orientation:s="horizontal",dir:l,activationMode:u="automatic",...d}=e,h=Sc(l),[m,g]=Zr({prop:r,onChange:o,defaultProp:i});return f.createElement(fY,{scope:n,baseId:nr(),value:m,onValueChange:g,orientation:s,dir:h,activationMode:u},f.createElement(Pe.div,Y({dir:h,"data-orientation":s},d,{ref:t})))}),hY="TabsList",mY=f.forwardRef((e,t)=>{const{__scopeTabs:n,loop:r=!0,...o}=e,i=Ix(hY,n),s=JP(n);return f.createElement(ZP,Y({asChild:!0},s,{orientation:i.orientation,dir:i.dir,loop:r}),f.createElement(Pe.div,Y({role:"tablist","aria-orientation":i.orientation},o,{ref:t})))}),gY="TabsTrigger",vY=f.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,disabled:o=!1,...i}=e,s=Ix(gY,n),l=JP(n),u=e5(s.baseId,r),d=t5(s.baseId,r),h=r===s.value;return f.createElement(qP,Y({asChild:!0},l,{focusable:!o,active:h}),f.createElement(Pe.button,Y({type:"button",role:"tab","aria-selected":h,"aria-controls":d,"data-state":h?"active":"inactive","data-disabled":o?"":void 0,disabled:o,id:u},i,{ref:t,onMouseDown:ue(e.onMouseDown,m=>{!o&&m.button===0&&m.ctrlKey===!1?s.onValueChange(r):m.preventDefault()}),onKeyDown:ue(e.onKeyDown,m=>{[" ","Enter"].includes(m.key)&&s.onValueChange(r)}),onFocus:ue(e.onFocus,()=>{const m=s.activationMode!=="manual";!h&&!o&&m&&s.onValueChange(r)})})))}),yY="TabsContent",wY=f.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,forceMount:o,children:i,...s}=e,l=Ix(yY,n),u=e5(l.baseId,r),d=t5(l.baseId,r),h=r===l.value,m=f.useRef(h);return f.useEffect(()=>{const g=requestAnimationFrame(()=>m.current=!1);return()=>cancelAnimationFrame(g)},[]),f.createElement(bn,{present:o||h},({present:g})=>f.createElement(Pe.div,Y({"data-state":h?"active":"inactive","data-orientation":l.orientation,role:"tabpanel","aria-labelledby":u,hidden:!g,id:d,tabIndex:0},s,{ref:t,style:{...e.style,animationDuration:m.current?"0s":void 0}}),g&&i))});function e5(e,t){return`${e}-trigger-${t}`}function t5(e,t){return`${e}-content-${t}`}const xY=pY,n5=mY,r5=vY,o5=wY,i5=xY,Lx=f.forwardRef(({className:e,...t},n)=>v.jsx(n5,{ref:n,className:Ce("inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground",e),tabIndex:-1,...t}));Lx.displayName=n5.displayName;const sa=f.forwardRef(({className:e,...t},n)=>v.jsx(r5,{ref:n,className:Ce("inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow",e),tabIndex:-1,...t}));sa.displayName=r5.displayName;const mu=f.forwardRef(({className:e,...t},n)=>v.jsx(o5,{ref:n,className:Ce("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",e),tabIndex:-1,...t}));mu.displayName=o5.displayName;function id(e,[t,n]){return Math.min(n,Math.max(t,e))}function Fx(e){const t=f.useRef({value:e,previous:e});return f.useMemo(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}const bY=[" ","Enter","ArrowUp","ArrowDown"],_Y=[" ","Enter"],Jm="Select",[eg,tg,SY]=zd(Jm),[Ec,xte]=An(Jm,[SY,Ns]),jx=Ns(),[EY,Oa]=Ec(Jm),[CY,$Y]=Ec(Jm),kY=e=>{const{__scopeSelect:t,children:n,open:r,defaultOpen:o,onOpenChange:i,value:s,defaultValue:l,onValueChange:u,dir:d,name:h,autoComplete:m,disabled:g,required:y}=e,x=jx(t),[_,C]=f.useState(null),[S,b]=f.useState(null),[E,k]=f.useState(!1),P=Sc(d),[M=!1,A]=Zr({prop:r,defaultProp:o,onChange:i}),[O,F]=Zr({prop:s,defaultProp:l,onChange:u}),V=f.useRef(null),J=_?!!_.closest("form"):!0,[G,ae]=f.useState(new Set),U=Array.from(G).map(te=>te.props.value).join(";");return f.createElement(Od,x,f.createElement(EY,{required:y,scope:t,trigger:_,onTriggerChange:C,valueNode:S,onValueNodeChange:b,valueNodeHasChildren:E,onValueNodeHasChildrenChange:k,contentId:nr(),value:O,onValueChange:F,open:M,onOpenChange:A,dir:P,triggerPointerDownPosRef:V,disabled:g},f.createElement(eg.Provider,{scope:t},f.createElement(CY,{scope:e.__scopeSelect,onNativeOptionAdd:f.useCallback(te=>{ae(L=>new Set(L).add(te))},[]),onNativeOptionRemove:f.useCallback(te=>{ae(L=>{const ie=new Set(L);return ie.delete(te),ie})},[])},n)),J?f.createElement(u5,{key:U,"aria-hidden":!0,required:y,tabIndex:-1,name:h,autoComplete:m,value:O,onChange:te=>F(te.target.value),disabled:g},O===void 0?f.createElement("option",{value:""}):null,Array.from(G)):null))},RY="SelectTrigger",TY=f.forwardRef((e,t)=>{const{__scopeSelect:n,disabled:r=!1,...o}=e,i=jx(n),s=Oa(RY,n),l=s.disabled||r,u=Be(t,s.onTriggerChange),d=tg(n),[h,m,g]=d5(x=>{const _=d().filter(b=>!b.disabled),C=_.find(b=>b.value===s.value),S=f5(_,x,C);S!==void 0&&s.onValueChange(S.value)}),y=()=>{l||(s.onOpenChange(!0),g())};return f.createElement(zm,Y({asChild:!0},i),f.createElement(Pe.button,Y({type:"button",role:"combobox","aria-controls":s.contentId,"aria-expanded":s.open,"aria-required":s.required,"aria-autocomplete":"none",dir:s.dir,"data-state":s.open?"open":"closed",disabled:l,"data-disabled":l?"":void 0,"data-placeholder":c5(s.value)?"":void 0},o,{ref:u,onClick:ue(o.onClick,x=>{x.currentTarget.focus()}),onPointerDown:ue(o.onPointerDown,x=>{const _=x.target;_.hasPointerCapture(x.pointerId)&&_.releasePointerCapture(x.pointerId),x.button===0&&x.ctrlKey===!1&&(y(),s.triggerPointerDownPosRef.current={x:Math.round(x.pageX),y:Math.round(x.pageY)},x.preventDefault())}),onKeyDown:ue(o.onKeyDown,x=>{const _=h.current!=="";!(x.ctrlKey||x.altKey||x.metaKey)&&x.key.length===1&&m(x.key),!(_&&x.key===" ")&&bY.includes(x.key)&&(y(),x.preventDefault())})})))}),PY="SelectValue",AY=f.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,children:i,placeholder:s="",...l}=e,u=Oa(PY,n),{onValueNodeHasChildrenChange:d}=u,h=i!==void 0,m=Be(t,u.onValueNodeChange);return Pn(()=>{d(h)},[d,h]),f.createElement(Pe.span,Y({},l,{ref:m,style:{pointerEvents:"none"}}),c5(u.value)?f.createElement(f.Fragment,null,s):i)}),OY=f.forwardRef((e,t)=>{const{__scopeSelect:n,children:r,...o}=e;return f.createElement(Pe.span,Y({"aria-hidden":!0},o,{ref:t}),r||"▼")}),MY=e=>f.createElement(Md,Y({asChild:!0},e)),ic="SelectContent",NY=f.forwardRef((e,t)=>{const n=Oa(ic,e.__scopeSelect),[r,o]=f.useState();if(Pn(()=>{o(new DocumentFragment)},[]),!n.open){const i=r;return i?Os.createPortal(f.createElement(s5,{scope:e.__scopeSelect},f.createElement(eg.Slot,{scope:e.__scopeSelect},f.createElement("div",null,e.children))),i):null}return f.createElement(DY,Y({},e,{ref:t}))}),ai=10,[s5,Ma]=Ec(ic),DY=f.forwardRef((e,t)=>{const{__scopeSelect:n,position:r="item-aligned",onCloseAutoFocus:o,onEscapeKeyDown:i,onPointerDownOutside:s,side:l,sideOffset:u,align:d,alignOffset:h,arrowPadding:m,collisionBoundary:g,collisionPadding:y,sticky:x,hideWhenDetached:_,avoidCollisions:C,...S}=e,b=Oa(ic,n),[E,k]=f.useState(null),[P,M]=f.useState(null),A=Be(t,fe=>k(fe)),[O,F]=f.useState(null),[V,J]=f.useState(null),G=tg(n),[ae,U]=f.useState(!1),te=f.useRef(!1);f.useEffect(()=>{if(E)return Xm(E)},[E]),Km();const L=f.useCallback(fe=>{const[xe,...$e]=G().map(je=>je.ref.current),[Ae]=$e.slice(-1),Oe=document.activeElement;for(const je of fe)if(je===Oe||(je==null||je.scrollIntoView({block:"nearest"}),je===xe&&P&&(P.scrollTop=0),je===Ae&&P&&(P.scrollTop=P.scrollHeight),je==null||je.focus(),document.activeElement!==Oe))return},[G,P]),ie=f.useCallback(()=>L([O,E]),[L,O,E]);f.useEffect(()=>{ae&&ie()},[ae,ie]);const{onOpenChange:K,triggerPointerDownPosRef:Q}=b;f.useEffect(()=>{if(E){let fe={x:0,y:0};const xe=Ae=>{var Oe,je,Ot,ct;fe={x:Math.abs(Math.round(Ae.pageX)-((Oe=(je=Q.current)===null||je===void 0?void 0:je.x)!==null&&Oe!==void 0?Oe:0)),y:Math.abs(Math.round(Ae.pageY)-((Ot=(ct=Q.current)===null||ct===void 0?void 0:ct.y)!==null&&Ot!==void 0?Ot:0))}},$e=Ae=>{fe.x<=10&&fe.y<=10?Ae.preventDefault():E.contains(Ae.target)||K(!1),document.removeEventListener("pointermove",xe),Q.current=null};return Q.current!==null&&(document.addEventListener("pointermove",xe),document.addEventListener("pointerup",$e,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",xe),document.removeEventListener("pointerup",$e,{capture:!0})}}},[E,K,Q]),f.useEffect(()=>{const fe=()=>K(!1);return window.addEventListener("blur",fe),window.addEventListener("resize",fe),()=>{window.removeEventListener("blur",fe),window.removeEventListener("resize",fe)}},[K]);const[W,le]=d5(fe=>{const xe=G().filter(Oe=>!Oe.disabled),$e=xe.find(Oe=>Oe.ref.current===document.activeElement),Ae=f5(xe,fe,$e);Ae&&setTimeout(()=>Ae.ref.current.focus())}),ge=f.useCallback((fe,xe,$e)=>{const Ae=!te.current&&!$e;(b.value!==void 0&&b.value===xe||Ae)&&(F(fe),Ae&&(te.current=!0))},[b.value]),Ve=f.useCallback(()=>E==null?void 0:E.focus(),[E]),Ue=f.useCallback((fe,xe,$e)=>{const Ae=!te.current&&!$e;(b.value!==void 0&&b.value===xe||Ae)&&J(fe)},[b.value]),We=r==="popper"?f2:IY,Me=We===f2?{side:l,sideOffset:u,align:d,alignOffset:h,arrowPadding:m,collisionBoundary:g,collisionPadding:y,sticky:x,hideWhenDetached:_,avoidCollisions:C}:{};return f.createElement(s5,{scope:n,content:E,viewport:P,onViewportChange:M,itemRefCallback:ge,selectedItem:O,onItemLeave:Ve,itemTextRefCallback:Ue,focusSelectedItem:ie,selectedItemText:V,position:r,isPositioned:ae,searchRef:W},f.createElement(Gm,{as:Wo,allowPinchZoom:!0},f.createElement(Hm,{asChild:!0,trapped:b.open,onMountAutoFocus:fe=>{fe.preventDefault()},onUnmountAutoFocus:ue(o,fe=>{var xe;(xe=b.trigger)===null||xe===void 0||xe.focus({preventScroll:!0}),fe.preventDefault()})},f.createElement(yc,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:i,onPointerDownOutside:s,onFocusOutside:fe=>fe.preventDefault(),onDismiss:()=>b.onOpenChange(!1)},f.createElement(We,Y({role:"listbox",id:b.contentId,"data-state":b.open?"open":"closed",dir:b.dir,onContextMenu:fe=>fe.preventDefault()},S,Me,{onPlaced:()=>U(!0),ref:A,style:{display:"flex",flexDirection:"column",outline:"none",...S.style},onKeyDown:ue(S.onKeyDown,fe=>{const xe=fe.ctrlKey||fe.altKey||fe.metaKey;if(fe.key==="Tab"&&fe.preventDefault(),!xe&&fe.key.length===1&&le(fe.key),["ArrowUp","ArrowDown","Home","End"].includes(fe.key)){let Ae=G().filter(Oe=>!Oe.disabled).map(Oe=>Oe.ref.current);if(["ArrowUp","End"].includes(fe.key)&&(Ae=Ae.slice().reverse()),["ArrowUp","ArrowDown"].includes(fe.key)){const Oe=fe.target,je=Ae.indexOf(Oe);Ae=Ae.slice(je+1)}setTimeout(()=>L(Ae)),fe.preventDefault()}})}))))))}),IY=f.forwardRef((e,t)=>{const{__scopeSelect:n,onPlaced:r,...o}=e,i=Oa(ic,n),s=Ma(ic,n),[l,u]=f.useState(null),[d,h]=f.useState(null),m=Be(t,A=>h(A)),g=tg(n),y=f.useRef(!1),x=f.useRef(!0),{viewport:_,selectedItem:C,selectedItemText:S,focusSelectedItem:b}=s,E=f.useCallback(()=>{if(i.trigger&&i.valueNode&&l&&d&&_&&C&&S){const A=i.trigger.getBoundingClientRect(),O=d.getBoundingClientRect(),F=i.valueNode.getBoundingClientRect(),V=S.getBoundingClientRect();if(i.dir!=="rtl"){const Oe=V.left-O.left,je=F.left-Oe,Ot=A.left-je,ct=A.width+Ot,Kt=Math.max(ct,O.width),Er=window.innerWidth-ai,gt=id(je,[ai,Er-Kt]);l.style.minWidth=ct+"px",l.style.left=gt+"px"}else{const Oe=O.right-V.right,je=window.innerWidth-F.right-Oe,Ot=window.innerWidth-A.right-je,ct=A.width+Ot,Kt=Math.max(ct,O.width),Er=window.innerWidth-ai,gt=id(je,[ai,Er-Kt]);l.style.minWidth=ct+"px",l.style.right=gt+"px"}const J=g(),G=window.innerHeight-ai*2,ae=_.scrollHeight,U=window.getComputedStyle(d),te=parseInt(U.borderTopWidth,10),L=parseInt(U.paddingTop,10),ie=parseInt(U.borderBottomWidth,10),K=parseInt(U.paddingBottom,10),Q=te+L+ae+K+ie,W=Math.min(C.offsetHeight*5,Q),le=window.getComputedStyle(_),ge=parseInt(le.paddingTop,10),Ve=parseInt(le.paddingBottom,10),Ue=A.top+A.height/2-ai,We=G-Ue,Me=C.offsetHeight/2,fe=C.offsetTop+Me,xe=te+L+fe,$e=Q-xe;if(xe<=Ue){const Oe=C===J[J.length-1].ref.current;l.style.bottom="0px";const je=d.clientHeight-_.offsetTop-_.offsetHeight,Ot=Math.max(We,Me+(Oe?Ve:0)+je+ie),ct=xe+Ot;l.style.height=ct+"px"}else{const Oe=C===J[0].ref.current;l.style.top="0px";const Ot=Math.max(Ue,te+_.offsetTop+(Oe?ge:0)+Me)+$e;l.style.height=Ot+"px",_.scrollTop=xe-Ue+_.offsetTop}l.style.margin=`${ai}px 0`,l.style.minHeight=W+"px",l.style.maxHeight=G+"px",r==null||r(),requestAnimationFrame(()=>y.current=!0)}},[g,i.trigger,i.valueNode,l,d,_,C,S,i.dir,r]);Pn(()=>E(),[E]);const[k,P]=f.useState();Pn(()=>{d&&P(window.getComputedStyle(d).zIndex)},[d]);const M=f.useCallback(A=>{A&&x.current===!0&&(E(),b==null||b(),x.current=!1)},[E,b]);return f.createElement(LY,{scope:n,contentWrapper:l,shouldExpandOnScrollRef:y,onScrollButtonChange:M},f.createElement("div",{ref:u,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:k}},f.createElement(Pe.div,Y({},o,{ref:m,style:{boxSizing:"border-box",maxHeight:"100%",...o.style}}))))}),f2=f.forwardRef((e,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:o=ai,...i}=e,s=jx(n);return f.createElement(Bm,Y({},s,i,{ref:t,align:r,collisionPadding:o,style:{boxSizing:"border-box",...i.style,"--radix-select-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-select-content-available-width":"var(--radix-popper-available-width)","--radix-select-content-available-height":"var(--radix-popper-available-height)","--radix-select-trigger-width":"var(--radix-popper-anchor-width)","--radix-select-trigger-height":"var(--radix-popper-anchor-height)"}}))}),[LY,zx]=Ec(ic,{}),p2="SelectViewport",FY=f.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=Ma(p2,n),i=zx(p2,n),s=Be(t,o.onViewportChange),l=f.useRef(0);return f.createElement(f.Fragment,null,f.createElement("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"}}),f.createElement(eg.Slot,{scope:n},f.createElement(Pe.div,Y({"data-radix-select-viewport":"",role:"presentation"},r,{ref:s,style:{position:"relative",flex:1,overflow:"auto",...r.style},onScroll:ue(r.onScroll,u=>{const d=u.currentTarget,{contentWrapper:h,shouldExpandOnScrollRef:m}=i;if(m!=null&&m.current&&h){const g=Math.abs(l.current-d.scrollTop);if(g>0){const y=window.innerHeight-ai*2,x=parseFloat(h.style.minHeight),_=parseFloat(h.style.height),C=Math.max(x,_);if(C0?E:0,h.style.justifyContent="flex-end")}}}l.current=d.scrollTop})}))))}),jY="SelectGroup",[zY,BY]=Ec(jY),UY=f.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=nr();return f.createElement(zY,{scope:n,id:o},f.createElement(Pe.div,Y({role:"group","aria-labelledby":o},r,{ref:t})))}),VY="SelectLabel",WY=f.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=BY(VY,n);return f.createElement(Pe.div,Y({id:o.id},r,{ref:t}))}),b1="SelectItem",[HY,a5]=Ec(b1),KY=f.forwardRef((e,t)=>{const{__scopeSelect:n,value:r,disabled:o=!1,textValue:i,...s}=e,l=Oa(b1,n),u=Ma(b1,n),d=l.value===r,[h,m]=f.useState(i??""),[g,y]=f.useState(!1),x=Be(t,S=>{var b;return(b=u.itemRefCallback)===null||b===void 0?void 0:b.call(u,S,r,o)}),_=nr(),C=()=>{o||(l.onValueChange(r),l.onOpenChange(!1))};if(r==="")throw new Error("A must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.");return f.createElement(HY,{scope:n,value:r,disabled:o,textId:_,isSelected:d,onItemTextChange:f.useCallback(S=>{m(b=>{var E;return b||((E=S==null?void 0:S.textContent)!==null&&E!==void 0?E:"").trim()})},[])},f.createElement(eg.ItemSlot,{scope:n,value:r,disabled:o,textValue:h},f.createElement(Pe.div,Y({role:"option","aria-labelledby":_,"data-highlighted":g?"":void 0,"aria-selected":d&&g,"data-state":d?"checked":"unchecked","aria-disabled":o||void 0,"data-disabled":o?"":void 0,tabIndex:o?void 0:-1},s,{ref:x,onFocus:ue(s.onFocus,()=>y(!0)),onBlur:ue(s.onBlur,()=>y(!1)),onPointerUp:ue(s.onPointerUp,C),onPointerMove:ue(s.onPointerMove,S=>{if(o){var b;(b=u.onItemLeave)===null||b===void 0||b.call(u)}else S.currentTarget.focus({preventScroll:!0})}),onPointerLeave:ue(s.onPointerLeave,S=>{if(S.currentTarget===document.activeElement){var b;(b=u.onItemLeave)===null||b===void 0||b.call(u)}}),onKeyDown:ue(s.onKeyDown,S=>{var b;((b=u.searchRef)===null||b===void 0?void 0:b.current)!==""&&S.key===" "||(_Y.includes(S.key)&&C(),S.key===" "&&S.preventDefault())})}))))}),hp="SelectItemText",YY=f.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,...i}=e,s=Oa(hp,n),l=Ma(hp,n),u=a5(hp,n),d=$Y(hp,n),[h,m]=f.useState(null),g=Be(t,S=>m(S),u.onItemTextChange,S=>{var b;return(b=l.itemTextRefCallback)===null||b===void 0?void 0:b.call(l,S,u.value,u.disabled)}),y=h==null?void 0:h.textContent,x=f.useMemo(()=>f.createElement("option",{key:u.value,value:u.value,disabled:u.disabled},y),[u.disabled,u.value,y]),{onNativeOptionAdd:_,onNativeOptionRemove:C}=d;return Pn(()=>(_(x),()=>C(x)),[_,C,x]),f.createElement(f.Fragment,null,f.createElement(Pe.span,Y({id:u.textId},i,{ref:g})),u.isSelected&&s.valueNode&&!s.valueNodeHasChildren?Os.createPortal(i.children,s.valueNode):null)}),GY="SelectItemIndicator",XY=f.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return a5(GY,n).isSelected?f.createElement(Pe.span,Y({"aria-hidden":!0},r,{ref:t})):null}),h2="SelectScrollUpButton",ZY=f.forwardRef((e,t)=>{const n=Ma(h2,e.__scopeSelect),r=zx(h2,e.__scopeSelect),[o,i]=f.useState(!1),s=Be(t,r.onScrollButtonChange);return Pn(()=>{if(n.viewport&&n.isPositioned){let d=function(){const h=u.scrollTop>0;i(h)};var l=d;const u=n.viewport;return d(),u.addEventListener("scroll",d),()=>u.removeEventListener("scroll",d)}},[n.viewport,n.isPositioned]),o?f.createElement(l5,Y({},e,{ref:s,onAutoScroll:()=>{const{viewport:l,selectedItem:u}=n;l&&u&&(l.scrollTop=l.scrollTop-u.offsetHeight)}})):null}),m2="SelectScrollDownButton",qY=f.forwardRef((e,t)=>{const n=Ma(m2,e.__scopeSelect),r=zx(m2,e.__scopeSelect),[o,i]=f.useState(!1),s=Be(t,r.onScrollButtonChange);return Pn(()=>{if(n.viewport&&n.isPositioned){let d=function(){const h=u.scrollHeight-u.clientHeight,m=Math.ceil(u.scrollTop)u.removeEventListener("scroll",d)}},[n.viewport,n.isPositioned]),o?f.createElement(l5,Y({},e,{ref:s,onAutoScroll:()=>{const{viewport:l,selectedItem:u}=n;l&&u&&(l.scrollTop=l.scrollTop+u.offsetHeight)}})):null}),l5=f.forwardRef((e,t)=>{const{__scopeSelect:n,onAutoScroll:r,...o}=e,i=Ma("SelectScrollButton",n),s=f.useRef(null),l=tg(n),u=f.useCallback(()=>{s.current!==null&&(window.clearInterval(s.current),s.current=null)},[]);return f.useEffect(()=>()=>u(),[u]),Pn(()=>{var d;const h=l().find(m=>m.ref.current===document.activeElement);h==null||(d=h.ref.current)===null||d===void 0||d.scrollIntoView({block:"nearest"})},[l]),f.createElement(Pe.div,Y({"aria-hidden":!0},o,{ref:t,style:{flexShrink:0,...o.style},onPointerDown:ue(o.onPointerDown,()=>{s.current===null&&(s.current=window.setInterval(r,50))}),onPointerMove:ue(o.onPointerMove,()=>{var d;(d=i.onItemLeave)===null||d===void 0||d.call(i),s.current===null&&(s.current=window.setInterval(r,50))}),onPointerLeave:ue(o.onPointerLeave,()=>{u()})}))}),QY=f.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return f.createElement(Pe.div,Y({"aria-hidden":!0},r,{ref:t}))});function c5(e){return e===""||e===void 0}const u5=f.forwardRef((e,t)=>{const{value:n,...r}=e,o=f.useRef(null),i=Be(t,o),s=Fx(n);return f.useEffect(()=>{const l=o.current,u=window.HTMLSelectElement.prototype,h=Object.getOwnPropertyDescriptor(u,"value").set;if(s!==n&&h){const m=new Event("change",{bubbles:!0});h.call(l,n),l.dispatchEvent(m)}},[s,n]),f.createElement(Um,{asChild:!0},f.createElement("select",Y({},r,{ref:i,defaultValue:n})))});u5.displayName="BubbleSelect";function d5(e){const t=Ft(e),n=f.useRef(""),r=f.useRef(0),o=f.useCallback(s=>{const l=n.current+s;t(l),function u(d){n.current=d,window.clearTimeout(r.current),d!==""&&(r.current=window.setTimeout(()=>u(""),1e3))}(l)},[t]),i=f.useCallback(()=>{n.current="",window.clearTimeout(r.current)},[]);return f.useEffect(()=>()=>window.clearTimeout(r.current),[]),[n,o,i]}function f5(e,t,n){const o=t.length>1&&Array.from(t).every(d=>d===t[0])?t[0]:t,i=n?e.indexOf(n):-1;let s=JY(e,Math.max(i,0));o.length===1&&(s=s.filter(d=>d!==n));const u=s.find(d=>d.textValue.toLowerCase().startsWith(o.toLowerCase()));return u!==n?u:void 0}function JY(e,t){return e.map((n,r)=>e[(t+r)%e.length])}const eG=kY,p5=TY,tG=AY,nG=OY,rG=MY,h5=NY,oG=FY,iG=UY,m5=WY,g5=KY,sG=YY,aG=XY,v5=ZY,y5=qY,w5=QY,aa=eG,wl=iG,la=tG,ls=f.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(p5,{ref:r,className:Ce("flex h-9 w-full items-center justify-between whitespace-nowrap rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",e),tabIndex:-1,...n,children:[t,v.jsx(nG,{asChild:!0,children:v.jsx(Xj,{className:"h-4 w-4 opacity-50"})})]}));ls.displayName=p5.displayName;const x5=f.forwardRef(({className:e,...t},n)=>v.jsx(v5,{ref:n,className:Ce("flex cursor-default items-center justify-center py-1",e),...t,children:v.jsx(nz,{})}));x5.displayName=v5.displayName;const b5=f.forwardRef(({className:e,...t},n)=>v.jsx(y5,{ref:n,className:Ce("flex cursor-default items-center justify-center py-1",e),...t,children:v.jsx(Qj,{})}));b5.displayName=y5.displayName;const cs=f.forwardRef(({className:e,children:t,position:n="popper",...r},o)=>v.jsx(rG,{children:v.jsxs(h5,{ref:o,className:Ce("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",n==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:n,onCloseAutoFocus:i=>i.preventDefault(),...r,children:[v.jsx(x5,{}),v.jsx(oG,{className:Ce("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),v.jsx(b5,{})]})}));cs.displayName=h5.displayName;const lG=f.forwardRef(({className:e,...t},n)=>v.jsx(m5,{ref:n,className:Ce("px-2 py-1.5 text-sm font-semibold",e),...t}));lG.displayName=m5.displayName;const us=f.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(g5,{ref:r,className:Ce("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-2 pr-8 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[v.jsx("span",{className:"absolute right-2 flex h-3.5 w-3.5 items-center justify-center",children:v.jsx(aG,{children:v.jsx(vT,{className:"h-4 w-4"})})}),v.jsx(sG,{children:t})]}));us.displayName=g5.displayName;const cG=f.forwardRef(({className:e,...t},n)=>v.jsx(w5,{ref:n,className:Ce("-mx-1 my-1 h-px bg-muted",e),...t}));cG.displayName=w5.displayName;function uG(e,t){return f.useReducer((n,r)=>{const o=t[n][r];return o??n},e)}const _5="ScrollArea",[S5,bte]=An(_5),[dG,qr]=S5(_5),fG=f.forwardRef((e,t)=>{const{__scopeScrollArea:n,type:r="hover",dir:o,scrollHideDelay:i=600,...s}=e,[l,u]=f.useState(null),[d,h]=f.useState(null),[m,g]=f.useState(null),[y,x]=f.useState(null),[_,C]=f.useState(null),[S,b]=f.useState(0),[E,k]=f.useState(0),[P,M]=f.useState(!1),[A,O]=f.useState(!1),F=Be(t,J=>u(J)),V=Sc(o);return f.createElement(dG,{scope:n,type:r,dir:V,scrollHideDelay:i,scrollArea:l,viewport:d,onViewportChange:h,content:m,onContentChange:g,scrollbarX:y,onScrollbarXChange:x,scrollbarXEnabled:P,onScrollbarXEnabledChange:M,scrollbarY:_,onScrollbarYChange:C,scrollbarYEnabled:A,onScrollbarYEnabledChange:O,onCornerWidthChange:b,onCornerHeightChange:k},f.createElement(Pe.div,Y({dir:V},s,{ref:F,style:{position:"relative","--radix-scroll-area-corner-width":S+"px","--radix-scroll-area-corner-height":E+"px",...e.style}})))}),pG="ScrollAreaViewport",hG=f.forwardRef((e,t)=>{const{__scopeScrollArea:n,children:r,...o}=e,i=qr(pG,n),s=f.useRef(null),l=Be(t,s,i.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(Pe.div,Y({"data-radix-scroll-area-viewport":""},o,{ref:l,style:{overflowX:i.scrollbarXEnabled?"scroll":"hidden",overflowY:i.scrollbarYEnabled?"scroll":"hidden",...e.style}}),f.createElement("div",{ref:i.onContentChange,style:{minWidth:"100%",display:"table"}},r)))}),$i="ScrollAreaScrollbar",E5=f.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=qr($i,e.__scopeScrollArea),{onScrollbarXEnabledChange:i,onScrollbarYEnabledChange:s}=o,l=e.orientation==="horizontal";return f.useEffect(()=>(l?i(!0):s(!0),()=>{l?i(!1):s(!1)}),[l,i,s]),o.type==="hover"?f.createElement(mG,Y({},r,{ref:t,forceMount:n})):o.type==="scroll"?f.createElement(gG,Y({},r,{ref:t,forceMount:n})):o.type==="auto"?f.createElement(C5,Y({},r,{ref:t,forceMount:n})):o.type==="always"?f.createElement(Bx,Y({},r,{ref:t})):null}),mG=f.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=qr($i,e.__scopeScrollArea),[i,s]=f.useState(!1);return f.useEffect(()=>{const l=o.scrollArea;let u=0;if(l){const d=()=>{window.clearTimeout(u),s(!0)},h=()=>{u=window.setTimeout(()=>s(!1),o.scrollHideDelay)};return l.addEventListener("pointerenter",d),l.addEventListener("pointerleave",h),()=>{window.clearTimeout(u),l.removeEventListener("pointerenter",d),l.removeEventListener("pointerleave",h)}}},[o.scrollArea,o.scrollHideDelay]),f.createElement(bn,{present:n||i},f.createElement(C5,Y({"data-state":i?"visible":"hidden"},r,{ref:t})))}),gG=f.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=qr($i,e.__scopeScrollArea),i=e.orientation==="horizontal",s=rg(()=>u("SCROLL_END"),100),[l,u]=uG("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(l==="idle"){const d=window.setTimeout(()=>u("HIDE"),o.scrollHideDelay);return()=>window.clearTimeout(d)}},[l,o.scrollHideDelay,u]),f.useEffect(()=>{const d=o.viewport,h=i?"scrollLeft":"scrollTop";if(d){let m=d[h];const g=()=>{const y=d[h];m!==y&&(u("SCROLL"),s()),m=y};return d.addEventListener("scroll",g),()=>d.removeEventListener("scroll",g)}},[o.viewport,i,u,s]),f.createElement(bn,{present:n||l!=="hidden"},f.createElement(Bx,Y({"data-state":l==="hidden"?"hidden":"visible"},r,{ref:t,onPointerEnter:ue(e.onPointerEnter,()=>u("POINTER_ENTER")),onPointerLeave:ue(e.onPointerLeave,()=>u("POINTER_LEAVE"))})))}),C5=f.forwardRef((e,t)=>{const n=qr($i,e.__scopeScrollArea),{forceMount:r,...o}=e,[i,s]=f.useState(!1),l=e.orientation==="horizontal",u=rg(()=>{if(n.viewport){const d=n.viewport.offsetWidth{const{orientation:n="vertical",...r}=e,o=qr($i,e.__scopeScrollArea),i=f.useRef(null),s=f.useRef(0),[l,u]=f.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),d=T5(l.viewport,l.content),h={...r,sizes:l,onSizesChange:u,hasThumb:d>0&&d<1,onThumbChange:g=>i.current=g,onThumbPointerUp:()=>s.current=0,onThumbPointerDown:g=>s.current=g};function m(g,y){return EG(g,s.current,l,y)}return n==="horizontal"?f.createElement(vG,Y({},h,{ref:t,onThumbPositionChange:()=>{if(o.viewport&&i.current){const g=o.viewport.scrollLeft,y=g2(g,l,o.dir);i.current.style.transform=`translate3d(${y}px, 0, 0)`}},onWheelScroll:g=>{o.viewport&&(o.viewport.scrollLeft=g)},onDragScroll:g=>{o.viewport&&(o.viewport.scrollLeft=m(g,o.dir))}})):n==="vertical"?f.createElement(yG,Y({},h,{ref:t,onThumbPositionChange:()=>{if(o.viewport&&i.current){const g=o.viewport.scrollTop,y=g2(g,l);i.current.style.transform=`translate3d(0, ${y}px, 0)`}},onWheelScroll:g=>{o.viewport&&(o.viewport.scrollTop=g)},onDragScroll:g=>{o.viewport&&(o.viewport.scrollTop=m(g))}})):null}),vG=f.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,i=qr($i,e.__scopeScrollArea),[s,l]=f.useState(),u=f.useRef(null),d=Be(t,u,i.onScrollbarXChange);return f.useEffect(()=>{u.current&&l(getComputedStyle(u.current))},[u]),f.createElement(k5,Y({"data-orientation":"horizontal"},o,{ref:d,sizes:n,style:{bottom:0,left:i.dir==="rtl"?"var(--radix-scroll-area-corner-width)":0,right:i.dir==="ltr"?"var(--radix-scroll-area-corner-width)":0,"--radix-scroll-area-thumb-width":ng(n)+"px",...e.style},onThumbPointerDown:h=>e.onThumbPointerDown(h.x),onDragScroll:h=>e.onDragScroll(h.x),onWheelScroll:(h,m)=>{if(i.viewport){const g=i.viewport.scrollLeft+h.deltaX;e.onWheelScroll(g),A5(g,m)&&h.preventDefault()}},onResize:()=>{u.current&&i.viewport&&s&&r({content:i.viewport.scrollWidth,viewport:i.viewport.offsetWidth,scrollbar:{size:u.current.clientWidth,paddingStart:zh(s.paddingLeft),paddingEnd:zh(s.paddingRight)}})}}))}),yG=f.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,i=qr($i,e.__scopeScrollArea),[s,l]=f.useState(),u=f.useRef(null),d=Be(t,u,i.onScrollbarYChange);return f.useEffect(()=>{u.current&&l(getComputedStyle(u.current))},[u]),f.createElement(k5,Y({"data-orientation":"vertical"},o,{ref:d,sizes:n,style:{top:0,right:i.dir==="ltr"?0:void 0,left:i.dir==="rtl"?0:void 0,bottom:"var(--radix-scroll-area-corner-height)","--radix-scroll-area-thumb-height":ng(n)+"px",...e.style},onThumbPointerDown:h=>e.onThumbPointerDown(h.y),onDragScroll:h=>e.onDragScroll(h.y),onWheelScroll:(h,m)=>{if(i.viewport){const g=i.viewport.scrollTop+h.deltaY;e.onWheelScroll(g),A5(g,m)&&h.preventDefault()}},onResize:()=>{u.current&&i.viewport&&s&&r({content:i.viewport.scrollHeight,viewport:i.viewport.offsetHeight,scrollbar:{size:u.current.clientHeight,paddingStart:zh(s.paddingTop),paddingEnd:zh(s.paddingBottom)}})}}))}),[wG,$5]=S5($i),k5=f.forwardRef((e,t)=>{const{__scopeScrollArea:n,sizes:r,hasThumb:o,onThumbChange:i,onThumbPointerUp:s,onThumbPointerDown:l,onThumbPositionChange:u,onDragScroll:d,onWheelScroll:h,onResize:m,...g}=e,y=qr($i,n),[x,_]=f.useState(null),C=Be(t,F=>_(F)),S=f.useRef(null),b=f.useRef(""),E=y.viewport,k=r.content-r.viewport,P=Ft(h),M=Ft(u),A=rg(m,10);function O(F){if(S.current){const V=F.clientX-S.current.left,J=F.clientY-S.current.top;d({x:V,y:J})}}return f.useEffect(()=>{const F=V=>{const J=V.target;(x==null?void 0:x.contains(J))&&P(V,k)};return document.addEventListener("wheel",F,{passive:!1}),()=>document.removeEventListener("wheel",F,{passive:!1})},[E,x,k,P]),f.useEffect(M,[r,M]),sc(x,A),sc(y.content,A),f.createElement(wG,{scope:n,scrollbar:x,hasThumb:o,onThumbChange:Ft(i),onThumbPointerUp:Ft(s),onThumbPositionChange:M,onThumbPointerDown:Ft(l)},f.createElement(Pe.div,Y({},g,{ref:C,style:{position:"absolute",...g.style},onPointerDown:ue(e.onPointerDown,F=>{F.button===0&&(F.target.setPointerCapture(F.pointerId),S.current=x.getBoundingClientRect(),b.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",y.viewport&&(y.viewport.style.scrollBehavior="auto"),O(F))}),onPointerMove:ue(e.onPointerMove,O),onPointerUp:ue(e.onPointerUp,F=>{const V=F.target;V.hasPointerCapture(F.pointerId)&&V.releasePointerCapture(F.pointerId),document.body.style.webkitUserSelect=b.current,y.viewport&&(y.viewport.style.scrollBehavior=""),S.current=null})})))}),_1="ScrollAreaThumb",xG=f.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=$5(_1,e.__scopeScrollArea);return f.createElement(bn,{present:n||o.hasThumb},f.createElement(bG,Y({ref:t},r)))}),bG=f.forwardRef((e,t)=>{const{__scopeScrollArea:n,style:r,...o}=e,i=qr(_1,n),s=$5(_1,n),{onThumbPositionChange:l}=s,u=Be(t,m=>s.onThumbChange(m)),d=f.useRef(),h=rg(()=>{d.current&&(d.current(),d.current=void 0)},100);return f.useEffect(()=>{const m=i.viewport;if(m){const g=()=>{if(h(),!d.current){const y=CG(m,l);d.current=y,l()}};return l(),m.addEventListener("scroll",g),()=>m.removeEventListener("scroll",g)}},[i.viewport,h,l]),f.createElement(Pe.div,Y({"data-state":s.hasThumb?"visible":"hidden"},o,{ref:u,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...r},onPointerDownCapture:ue(e.onPointerDownCapture,m=>{const y=m.target.getBoundingClientRect(),x=m.clientX-y.left,_=m.clientY-y.top;s.onThumbPointerDown({x,y:_})}),onPointerUp:ue(e.onPointerUp,s.onThumbPointerUp)}))}),R5="ScrollAreaCorner",_G=f.forwardRef((e,t)=>{const n=qr(R5,e.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?f.createElement(SG,Y({},e,{ref:t})):null}),SG=f.forwardRef((e,t)=>{const{__scopeScrollArea:n,...r}=e,o=qr(R5,n),[i,s]=f.useState(0),[l,u]=f.useState(0),d=!!(i&&l);return sc(o.scrollbarX,()=>{var h;const m=((h=o.scrollbarX)===null||h===void 0?void 0:h.offsetHeight)||0;o.onCornerHeightChange(m),u(m)}),sc(o.scrollbarY,()=>{var h;const m=((h=o.scrollbarY)===null||h===void 0?void 0:h.offsetWidth)||0;o.onCornerWidthChange(m),s(m)}),d?f.createElement(Pe.div,Y({},r,{ref:t,style:{width:i,height:l,position:"absolute",right:o.dir==="ltr"?0:void 0,left:o.dir==="rtl"?0:void 0,bottom:0,...e.style}})):null});function zh(e){return e?parseInt(e,10):0}function T5(e,t){const n=e/t;return isNaN(n)?0:n}function ng(e){const t=T5(e.viewport,e.content),n=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,r=(e.scrollbar.size-n)*t;return Math.max(r,18)}function EG(e,t,n,r="ltr"){const o=ng(n),i=o/2,s=t||i,l=o-s,u=n.scrollbar.paddingStart+s,d=n.scrollbar.size-n.scrollbar.paddingEnd-l,h=n.content-n.viewport,m=r==="ltr"?[0,h]:[h*-1,0];return P5([u,d],m)(e)}function g2(e,t,n="ltr"){const r=ng(t),o=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,i=t.scrollbar.size-o,s=t.content-t.viewport,l=i-r,u=n==="ltr"?[0,s]:[s*-1,0],d=id(e,u);return P5([0,s],[0,l])(d)}function P5(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 A5(e,t){return e>0&&e{})=>{let n={left:e.scrollLeft,top:e.scrollTop},r=0;return function o(){const i={left:e.scrollLeft,top:e.scrollTop},s=n.left!==i.left,l=n.top!==i.top;(s||l)&&t(),n=i,r=window.requestAnimationFrame(o)}(),()=>window.cancelAnimationFrame(r)};function rg(e,t){const n=Ft(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 sc(e,t){const n=Ft(t);Pn(()=>{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 O5=fG,$G=hG,kG=_G,og=f.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(O5,{ref:r,className:Ce("relative overflow-hidden",e),scrollHideDelay:400,...n,children:[v.jsx($G,{className:"h-full w-full rounded-[inherit]",children:t}),v.jsx(M5,{}),v.jsx(kG,{})]}));og.displayName=O5.displayName;const M5=f.forwardRef(({className:e,orientation:t="vertical",...n},r)=>v.jsx(E5,{ref:r,orientation:t,className:Ce("flex touch-none select-none transition-colors",t==="vertical"&&"h-full w-2.5 border-l border-l-transparent p-[1px]",t==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",e),...n,children:v.jsx(xG,{className:"relative flex-1 rounded-full bg-border"})}));M5.displayName=E5.displayName;const N5="Name",D5="Created time",I5="Modified time",v2="input",RG="output",y2={[xs.NAME]:N5,[xs.CTIME]:D5,[xs.MTIME]:I5};function TG(e){const{onPhotoClick:t,photoWidth:n}=e,[r,o]=AP(!1),[i,s]=bt(V=>[V.fileManagerState,V.updateFileManagerState]),{toast:l}=Td(),[u,d]=f.useState(0),[h,m]=f.useState(0),g=f.useRef(null),y=aV(i.searchText,300),[x,_]=f.useState(v2),[C,S]=f.useState([]),[b,E]=f.useState([]),[k,P]=f.useState(0);Zn("f",()=>{o()}),Zn("left",()=>{let V=k;k>0&&(V=k-1),P(V),t(x,b[V].name)},[k,b]),Zn("right",()=>{let V=k;k{r||m(u)},[r,u]);const M=f.useCallback(V=>{V!==null&&r&&setTimeout(()=>{V.scrollTo({top:h,left:0})},100)},[r,h]);f.useEffect(()=>{(async()=>{try{const J=await Vj(x);S(J)}catch(J){l({variant:"destructive",title:"Uh oh! Something went wrong.",description:J.message?J.message:J.toString()})}})()},[x]),f.useEffect(()=>{if(!r)return;(async()=>{try{let J=C;y&&(J=new _c(J,{keys:["name"]}).search(y).map(te=>J[te.refIndex])),J=wH.orderBy(J,i.sortBy,i.sortOrder);const G=J.map(ae=>{const U=n,te=ae.height*(U/ae.width);return{src:`${Ms}/media_thumbnail_file?tab=${x}&filename=${encodeURIComponent(ae.name)}&width=${Math.ceil(U)}&height=${Math.ceil(te)}`,height:te,width:U,name:ae.name}});E(G)}catch(J){l({variant:"destructive",title:"Uh oh! Something went wrong.",description:J.message?J.message:J.toString()})}})()},[C,y,i,n,r]);const A=V=>{d(V.currentTarget.scrollTop)},O=({index:V})=>{o(),P(V),t(x,b[V].name)},F=()=>v.jsxs("div",{className:"flex justify-start items-center gap-[12px]",children:[v.jsx("div",{children:`Images (${b.length})`}),v.jsxs("div",{className:"flex",children:[v.jsx(vn,{tooltip:"Rows layout",onClick:()=>{s({layout:"rows"})},children:v.jsx(pz,{className:i.layout!=="rows"?"opacity-50":""})}),v.jsx(vn,{tooltip:"Grid layout",onClick:()=>{s({layout:"masonry"})},children:v.jsx(dz,{className:i.layout!=="masonry"?"opacity-50":""})})]})]});return v.jsxs(Zm,{open:r,onOpenChange:o,children:[v.jsx(uP,{asChild:!0,children:v.jsx(vn,{tooltip:"File Manager",children:v.jsx(JU,{})})}),v.jsxs(Fd,{className:"h-4/5 max-w-6xl",children:[v.jsx(jd,{children:F()}),v.jsxs("div",{className:"flex justify-between gap-8 items-center",children:[v.jsxs("div",{className:"flex relative justify-start items-center",children:[v.jsx(az,{className:"absolute left-[8px]"}),v.jsx(Pd,{ref:g,value:i.searchText,className:"w-[250px] pl-[30px]",tabIndex:-1,onInput:V=>{V.preventDefault(),V.stopPropagation();const J=V.target;s({searchText:J.value})},placeholder:"Search by file name"})]}),v.jsx(i5,{defaultValue:x,onValueChange:V=>_(V),children:v.jsxs(Lx,{"aria-label":"Manage your account",children:[v.jsx(sa,{value:v2,children:"Image Directory"}),v.jsx(sa,{value:RG,children:"Output Directory"})]})}),v.jsx("div",{className:"flex gap-2",children:v.jsxs("div",{className:"flex gap-1",children:[v.jsxs(aa,{value:y2[i.sortBy],onValueChange:V=>{switch(V){case N5:s({sortBy:xs.NAME});break;case D5:s({sortBy:xs.CTIME});break;case I5:s({sortBy:xs.MTIME});break}},children:[v.jsx(ls,{className:"w-[140px]",children:v.jsx(la,{})}),v.jsx(cs,{children:Object.values(y2).map(V=>v.jsx(us,{value:V,children:V},V))})]}),i.sortOrder===$u.DESCENDING?v.jsx(vn,{tooltip:"Descending Order",onClick:()=>{s({sortOrder:$u.ASCENDING})},children:v.jsx(oK,{})}):v.jsx(vn,{tooltip:"Ascending Order",onClick:()=>{s({sortOrder:$u.DESCENDING})},children:v.jsx(aK,{})})]})})]}),v.jsx(og,{className:"w-full h-full rounded-md",onScroll:A,ref:M,children:v.jsx(tK,{layout:i.layout,photos:b,spacing:12,padding:0,onClick:O})})]})]})}var Bd=e=>e.type==="checkbox",xl=e=>e instanceof Date,Ln=e=>e==null;const L5=e=>typeof e=="object";var sn=e=>!Ln(e)&&!Array.isArray(e)&&L5(e)&&!xl(e),F5=e=>sn(e)&&e.target?Bd(e.target)?e.target.checked:e.target.value:e,PG=e=>e.substring(0,e.search(/\.\d+(\.|$)/))||e,j5=(e,t)=>e.has(PG(t)),AG=e=>{const t=e.constructor&&e.constructor.prototype;return sn(t)&&t.hasOwnProperty("isPrototypeOf")},Ux=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function so(e){let t;const n=Array.isArray(e);if(e instanceof Date)t=new Date(e);else if(e instanceof Set)t=new Set(e);else if(!(Ux&&(e instanceof Blob||e instanceof FileList))&&(n||sn(e)))if(t=n?[]:{},!n&&!AG(e))t=e;else for(const r in e)e.hasOwnProperty(r)&&(t[r]=so(e[r]));else return e;return t}var Ud=e=>Array.isArray(e)?e.filter(Boolean):[],Ht=e=>e===void 0,ve=(e,t,n)=>{if(!t||!sn(e))return n;const r=Ud(t.split(/[,[\].]+?/)).reduce((o,i)=>Ln(o)?o:o[i],e);return Ht(r)||r===e?Ht(e[t])?n:e[t]:r},No=e=>typeof e=="boolean";const Bh={BLUR:"blur",FOCUS_OUT:"focusout",CHANGE:"change"},mo={onBlur:"onBlur",onChange:"onChange",onSubmit:"onSubmit",onTouched:"onTouched",all:"all"},oi={max:"max",min:"min",maxLength:"maxLength",minLength:"minLength",pattern:"pattern",required:"required",validate:"validate"},z5=Fe.createContext(null),ig=()=>Fe.useContext(z5),OG=e=>{const{children:t,...n}=e;return Fe.createElement(z5.Provider,{value:n},t)};var B5=(e,t,n,r=!0)=>{const o={defaultValues:t._defaultValues};for(const i in e)Object.defineProperty(o,i,{get:()=>{const s=i;return t._proxyFormState[s]!==mo.all&&(t._proxyFormState[s]=!r||mo.all),n&&(n[s]=!0),e[s]}});return o},Fr=e=>sn(e)&&!Object.keys(e).length,U5=(e,t,n,r)=>{n(e);const{name:o,...i}=e;return Fr(i)||Object.keys(i).length>=Object.keys(t).length||Object.keys(i).find(s=>t[s]===(!r||mo.all))},Yp=e=>Array.isArray(e)?e:[e],V5=(e,t,n)=>!e||!t||e===t||Yp(e).some(r=>r&&(n?r===t:r.startsWith(t)||t.startsWith(r)));function Vx(e){const t=Fe.useRef(e);t.current=e,Fe.useEffect(()=>{const n=!e.disabled&&t.current.subject&&t.current.subject.subscribe({next:t.current.next});return()=>{n&&n.unsubscribe()}},[e.disabled])}function MG(e){const t=ig(),{control:n=t.control,disabled:r,name:o,exact:i}=e||{},[s,l]=Fe.useState(n._formState),u=Fe.useRef(!0),d=Fe.useRef({isDirty:!1,isLoading:!1,dirtyFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1}),h=Fe.useRef(o);return h.current=o,Vx({disabled:r,next:m=>u.current&&V5(h.current,m.name,i)&&U5(m,d.current,n._updateFormState)&&l({...n._formState,...m}),subject:n._subjects.state}),Fe.useEffect(()=>(u.current=!0,d.current.isValid&&n._updateValid(!0),()=>{u.current=!1}),[n]),B5(s,n,d.current,!1)}var Fo=e=>typeof e=="string",W5=(e,t,n,r,o)=>Fo(e)?(r&&t.watch.add(e),ve(n,e,o)):Array.isArray(e)?e.map(i=>(r&&t.watch.add(i),ve(n,i))):(r&&(t.watchAll=!0),n);function NG(e){const t=ig(),{control:n=t.control,name:r,defaultValue:o,disabled:i,exact:s}=e||{},l=Fe.useRef(r);l.current=r,Vx({disabled:i,subject:n._subjects.values,next:h=>{V5(l.current,h.name,s)&&d(so(W5(l.current,n._names,h.values||n._formValues,!1,o)))}});const[u,d]=Fe.useState(n._getWatch(r,o));return Fe.useEffect(()=>n._removeUnmounted()),u}var Wx=e=>/^\w*$/.test(e),H5=e=>Ud(e.replace(/["|']|\]/g,"").split(/\.|\[/));function wt(e,t,n){let r=-1;const o=Wx(t)?[t]:H5(t),i=o.length,s=i-1;for(;++r{const h=o._options.shouldUnregister||i,m=(g,y)=>{const x=ve(o._fields,g);x&&(x._f.mount=y)};if(m(n,!0),h){const g=so(ve(o._options.defaultValues,n));wt(o._defaultValues,n,g),Ht(ve(o._formValues,n))&&wt(o._formValues,n,g)}return()=>{(s?h&&!o._state.action:h)?o.unregister(n):m(n,!1)}},[n,o,s,i]),Fe.useEffect(()=>{ve(o._fields,n)&&o._updateDisabledField({disabled:r,fields:o._fields,name:n,value:ve(o._fields,n)._f.value})},[r,n,o]),{field:{name:n,value:l,...No(r)||No(u.disabled)?{disabled:u.disabled||r}:{},onChange:Fe.useCallback(h=>d.current.onChange({target:{value:F5(h),name:n},type:Bh.CHANGE}),[n]),onBlur:Fe.useCallback(()=>d.current.onBlur({target:{value:ve(o._formValues,n),name:n},type:Bh.BLUR}),[n,o]),ref:h=>{const m=ve(o._fields,n);m&&h&&(m._f.ref={focus:()=>h.focus(),select:()=>h.select(),setCustomValidity:g=>h.setCustomValidity(g),reportValidity:()=>h.reportValidity()})}},formState:u,fieldState:Object.defineProperties({},{invalid:{enumerable:!0,get:()=>!!ve(u.errors,n)},isDirty:{enumerable:!0,get:()=>!!ve(u.dirtyFields,n)},isTouched:{enumerable:!0,get:()=>!!ve(u.touchedFields,n)},error:{enumerable:!0,get:()=>ve(u.errors,n)}})}}const IG=e=>e.render(DG(e));var K5=(e,t,n,r,o)=>t?{...n[e],types:{...n[e]&&n[e].types?n[e].types:{},[r]:o||!0}}:{},w2=e=>({isOnSubmit:!e||e===mo.onSubmit,isOnBlur:e===mo.onBlur,isOnChange:e===mo.onChange,isOnAll:e===mo.all,isOnTouch:e===mo.onTouched}),x2=(e,t,n)=>!n&&(t.watchAll||t.watch.has(e)||[...t.watch].some(r=>e.startsWith(r)&&/^\.\w+/.test(e.slice(r.length))));const Gp=(e,t,n,r)=>{for(const o of n||Object.keys(e)){const i=ve(e,o);if(i){const{_f:s,...l}=i;if(s){if(s.refs&&s.refs[0]&&t(s.refs[0],o)&&!r)break;if(s.ref&&t(s.ref,s.name)&&!r)break}else sn(l)&&Gp(l,t)}}};var LG=(e,t,n)=>{const r=Ud(ve(e,n));return wt(r,"root",t[n]),wt(e,n,r),e},Hx=e=>e.type==="file",ds=e=>typeof e=="function",Uh=e=>{if(!Ux)return!1;const t=e?e.ownerDocument:0;return e instanceof(t&&t.defaultView?t.defaultView.HTMLElement:HTMLElement)},Xp=e=>Fo(e),Kx=e=>e.type==="radio",Vh=e=>e instanceof RegExp;const b2={value:!1,isValid:!1},_2={value:!0,isValid:!0};var Y5=e=>{if(Array.isArray(e)){if(e.length>1){const t=e.filter(n=>n&&n.checked&&!n.disabled).map(n=>n.value);return{value:t,isValid:!!t.length}}return e[0].checked&&!e[0].disabled?e[0].attributes&&!Ht(e[0].attributes.value)?Ht(e[0].value)||e[0].value===""?_2:{value:e[0].value,isValid:!0}:_2:b2}return b2};const S2={isValid:!1,value:null};var G5=e=>Array.isArray(e)?e.reduce((t,n)=>n&&n.checked&&!n.disabled?{isValid:!0,value:n.value}:t,S2):S2;function E2(e,t,n="validate"){if(Xp(e)||Array.isArray(e)&&e.every(Xp)||No(e)&&!e)return{type:n,message:Xp(e)?e:"",ref:t}}var el=e=>sn(e)&&!Vh(e)?e:{value:e,message:""},C2=async(e,t,n,r,o)=>{const{ref:i,refs:s,required:l,maxLength:u,minLength:d,min:h,max:m,pattern:g,validate:y,name:x,valueAsNumber:_,mount:C,disabled:S}=e._f,b=ve(t,x);if(!C||S)return{};const E=s?s[0]:i,k=G=>{r&&E.reportValidity&&(E.setCustomValidity(No(G)?"":G||""),E.reportValidity())},P={},M=Kx(i),A=Bd(i),O=M||A,F=(_||Hx(i))&&Ht(i.value)&&Ht(b)||Uh(i)&&i.value===""||b===""||Array.isArray(b)&&!b.length,V=K5.bind(null,x,n,P),J=(G,ae,U,te=oi.maxLength,L=oi.minLength)=>{const ie=G?ae:U;P[x]={type:G?te:L,message:ie,ref:i,...V(G?te:L,ie)}};if(o?!Array.isArray(b)||!b.length:l&&(!O&&(F||Ln(b))||No(b)&&!b||A&&!Y5(s).isValid||M&&!G5(s).isValid)){const{value:G,message:ae}=Xp(l)?{value:!!l,message:l}:el(l);if(G&&(P[x]={type:oi.required,message:ae,ref:E,...V(oi.required,ae)},!n))return k(ae),P}if(!F&&(!Ln(h)||!Ln(m))){let G,ae;const U=el(m),te=el(h);if(!Ln(b)&&!isNaN(b)){const L=i.valueAsNumber||b&&+b;Ln(U.value)||(G=L>U.value),Ln(te.value)||(ae=Lnew Date(new Date().toDateString()+" "+W),K=i.type=="time",Q=i.type=="week";Fo(U.value)&&b&&(G=K?ie(b)>ie(U.value):Q?b>U.value:L>new Date(U.value)),Fo(te.value)&&b&&(ae=K?ie(b)+G.value,te=!Ln(ae.value)&&b.length<+ae.value;if((U||te)&&(J(U,G.message,ae.message),!n))return k(P[x].message),P}if(g&&!F&&Fo(b)){const{value:G,message:ae}=el(g);if(Vh(G)&&!b.match(G)&&(P[x]={type:oi.pattern,message:ae,ref:i,...V(oi.pattern,ae)},!n))return k(ae),P}if(y){if(ds(y)){const G=await y(b,t),ae=E2(G,E);if(ae&&(P[x]={...ae,...V(oi.validate,ae.message)},!n))return k(ae.message),P}else if(sn(y)){let G={};for(const ae in y){if(!Fr(G)&&!n)break;const U=E2(await y[ae](b,t),E,ae);U&&(G={...U,...V(ae,U.message)},k(U.message),n&&(P[x]=G))}if(!Fr(G)&&(P[x]={ref:E,...G},!n))return P}}return k(!0),P};function FG(e,t){const n=t.slice(0,-1).length;let r=0;for(;r{for(const i of e)i.next&&i.next(o)},subscribe:o=>(e.push(o),{unsubscribe:()=>{e=e.filter(i=>i!==o)}}),unsubscribe:()=>{e=[]}}}var Wh=e=>Ln(e)||!L5(e);function ca(e,t){if(Wh(e)||Wh(t))return e===t;if(xl(e)&&xl(t))return e.getTime()===t.getTime();const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(const o of n){const i=e[o];if(!r.includes(o))return!1;if(o!=="ref"){const s=t[o];if(xl(i)&&xl(s)||sn(i)&&sn(s)||Array.isArray(i)&&Array.isArray(s)?!ca(i,s):i!==s)return!1}}return!0}var X5=e=>e.type==="select-multiple",zG=e=>Kx(e)||Bd(e),P0=e=>Uh(e)&&e.isConnected,Z5=e=>{for(const t in e)if(ds(e[t]))return!0;return!1};function Hh(e,t={}){const n=Array.isArray(e);if(sn(e)||n)for(const r in e)Array.isArray(e[r])||sn(e[r])&&!Z5(e[r])?(t[r]=Array.isArray(e[r])?[]:{},Hh(e[r],t[r])):Ln(e[r])||(t[r]=!0);return t}function q5(e,t,n){const r=Array.isArray(e);if(sn(e)||r)for(const o in e)Array.isArray(e[o])||sn(e[o])&&!Z5(e[o])?Ht(t)||Wh(n[o])?n[o]=Array.isArray(e[o])?Hh(e[o],[]):{...Hh(e[o])}:q5(e[o],Ln(t)?{}:t[o],n[o]):n[o]=!ca(e[o],t[o]);return n}var A0=(e,t)=>q5(e,t,Hh(t)),Q5=(e,{valueAsNumber:t,valueAsDate:n,setValueAs:r})=>Ht(e)?e:t?e===""?NaN:e&&+e:n&&Fo(e)?new Date(e):r?r(e):e;function O0(e){const t=e.ref;if(!(e.refs?e.refs.every(n=>n.disabled):t.disabled))return Hx(t)?t.files:Kx(t)?G5(e.refs).value:X5(t)?[...t.selectedOptions].map(({value:n})=>n):Bd(t)?Y5(e.refs).value:Q5(Ht(t.value)?e.ref.value:t.value,e)}var BG=(e,t,n,r)=>{const o={};for(const i of e){const s=ve(t,i);s&&wt(o,i,s._f)}return{criteriaMode:n,names:[...e],fields:o,shouldUseNativeValidation:r}},iu=e=>Ht(e)?e:Vh(e)?e.source:sn(e)?Vh(e.value)?e.value.source:e.value:e,UG=e=>e.mount&&(e.required||e.min||e.max||e.maxLength||e.minLength||e.pattern||e.validate);function $2(e,t,n){const r=ve(e,n);if(r||Wx(n))return{error:r,name:n};const o=n.split(".");for(;o.length;){const i=o.join("."),s=ve(t,i),l=ve(e,i);if(s&&!Array.isArray(s)&&n!==i)return{name:n};if(l&&l.type)return{name:i,error:l};o.pop()}return{name:n}}var VG=(e,t,n,r,o)=>o.isOnAll?!1:!n&&o.isOnTouch?!(t||e):(n?r.isOnBlur:o.isOnBlur)?!e:(n?r.isOnChange:o.isOnChange)?e:!0,WG=(e,t)=>!Ud(ve(e,t)).length&&hn(e,t);const HG={mode:mo.onSubmit,reValidateMode:mo.onChange,shouldFocusError:!0};function KG(e={},t){let n={...HG,...e},r={submitCount:0,isDirty:!1,isLoading:ds(n.defaultValues),isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},errors:{},disabled:!1},o={},i=sn(n.defaultValues)||sn(n.values)?so(n.defaultValues||n.values)||{}:{},s=n.shouldUnregister?{}:so(i),l={action:!1,mount:!1,watch:!1},u={mount:new Set,unMount:new Set,array:new Set,watch:new Set},d,h=0;const m={isDirty:!1,dirtyFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1},g={values:T0(),array:T0(),state:T0()},y=e.resetOptions&&e.resetOptions.keepDirtyValues,x=w2(n.mode),_=w2(n.reValidateMode),C=n.criteriaMode===mo.all,S=I=>X=>{clearTimeout(h),h=setTimeout(I,X)},b=async I=>{if(m.isValid||I){const X=n.resolver?Fr((await F()).errors):await J(o,!0);X!==r.isValid&&g.state.next({isValid:X})}},E=I=>m.isValidating&&g.state.next({isValidating:I}),k=(I,X=[],Z,we,he=!0,de=!0)=>{if(we&&Z){if(l.action=!0,de&&Array.isArray(ve(o,I))){const ke=Z(ve(o,I),we.argA,we.argB);he&&wt(o,I,ke)}if(de&&Array.isArray(ve(r.errors,I))){const ke=Z(ve(r.errors,I),we.argA,we.argB);he&&wt(r.errors,I,ke),WG(r.errors,I)}if(m.touchedFields&&de&&Array.isArray(ve(r.touchedFields,I))){const ke=Z(ve(r.touchedFields,I),we.argA,we.argB);he&&wt(r.touchedFields,I,ke)}m.dirtyFields&&(r.dirtyFields=A0(i,s)),g.state.next({name:I,isDirty:ae(I,X),dirtyFields:r.dirtyFields,errors:r.errors,isValid:r.isValid})}else wt(s,I,X)},P=(I,X)=>{wt(r.errors,I,X),g.state.next({errors:r.errors})},M=(I,X,Z,we)=>{const he=ve(o,I);if(he){const de=ve(s,I,Ht(Z)?ve(i,I):Z);Ht(de)||we&&we.defaultChecked||X?wt(s,I,X?de:O0(he._f)):L(I,de),l.mount&&b()}},A=(I,X,Z,we,he)=>{let de=!1,ke=!1;const ft={name:I};if(!Z||we){m.isDirty&&(ke=r.isDirty,r.isDirty=ft.isDirty=ae(),de=ke!==ft.isDirty);const pt=ca(ve(i,I),X);ke=ve(r.dirtyFields,I),pt?hn(r.dirtyFields,I):wt(r.dirtyFields,I,!0),ft.dirtyFields=r.dirtyFields,de=de||m.dirtyFields&&ke!==!pt}if(Z){const pt=ve(r.touchedFields,I);pt||(wt(r.touchedFields,I,Z),ft.touchedFields=r.touchedFields,de=de||m.touchedFields&&pt!==Z)}return de&&he&&g.state.next(ft),de?ft:{}},O=(I,X,Z,we)=>{const he=ve(r.errors,I),de=m.isValid&&No(X)&&r.isValid!==X;if(e.delayError&&Z?(d=S(()=>P(I,Z)),d(e.delayError)):(clearTimeout(h),d=null,Z?wt(r.errors,I,Z):hn(r.errors,I)),(Z?!ca(he,Z):he)||!Fr(we)||de){const ke={...we,...de&&No(X)?{isValid:X}:{},errors:r.errors,name:I};r={...r,...ke},g.state.next(ke)}E(!1)},F=async I=>n.resolver(s,n.context,BG(I||u.mount,o,n.criteriaMode,n.shouldUseNativeValidation)),V=async I=>{const{errors:X}=await F(I);if(I)for(const Z of I){const we=ve(X,Z);we?wt(r.errors,Z,we):hn(r.errors,Z)}else r.errors=X;return X},J=async(I,X,Z={valid:!0})=>{for(const we in I){const he=I[we];if(he){const{_f:de,...ke}=he;if(de){const ft=u.array.has(de.name),pt=await C2(he,s,C,n.shouldUseNativeValidation&&!X,ft);if(pt[de.name]&&(Z.valid=!1,X))break;!X&&(ve(pt,de.name)?ft?LG(r.errors,pt,de.name):wt(r.errors,de.name,pt[de.name]):hn(r.errors,de.name))}ke&&await J(ke,X,Z)}}return Z.valid},G=()=>{for(const I of u.unMount){const X=ve(o,I);X&&(X._f.refs?X._f.refs.every(Z=>!P0(Z)):!P0(X._f.ref))&&fe(I)}u.unMount=new Set},ae=(I,X)=>(I&&X&&wt(s,I,X),!ca(ge(),i)),U=(I,X,Z)=>W5(I,u,{...l.mount?s:Ht(X)?i:Fo(I)?{[I]:X}:X},Z,X),te=I=>Ud(ve(l.mount?s:i,I,e.shouldUnregister?ve(i,I,[]):[])),L=(I,X,Z={})=>{const we=ve(o,I);let he=X;if(we){const de=we._f;de&&(!de.disabled&&wt(s,I,Q5(X,de)),he=Uh(de.ref)&&Ln(X)?"":X,X5(de.ref)?[...de.ref.options].forEach(ke=>ke.selected=he.includes(ke.value)):de.refs?Bd(de.ref)?de.refs.length>1?de.refs.forEach(ke=>(!ke.defaultChecked||!ke.disabled)&&(ke.checked=Array.isArray(he)?!!he.find(ft=>ft===ke.value):he===ke.value)):de.refs[0]&&(de.refs[0].checked=!!he):de.refs.forEach(ke=>ke.checked=ke.value===he):Hx(de.ref)?de.ref.value="":(de.ref.value=he,de.ref.type||g.values.next({name:I,values:{...s}})))}(Z.shouldDirty||Z.shouldTouch)&&A(I,he,Z.shouldTouch,Z.shouldDirty,!0),Z.shouldValidate&&le(I)},ie=(I,X,Z)=>{for(const we in X){const he=X[we],de=`${I}.${we}`,ke=ve(o,de);(u.array.has(I)||!Wh(he)||ke&&!ke._f)&&!xl(he)?ie(de,he,Z):L(de,he,Z)}},K=(I,X,Z={})=>{const we=ve(o,I),he=u.array.has(I),de=so(X);wt(s,I,de),he?(g.array.next({name:I,values:{...s}}),(m.isDirty||m.dirtyFields)&&Z.shouldDirty&&g.state.next({name:I,dirtyFields:A0(i,s),isDirty:ae(I,de)})):we&&!we._f&&!Ln(de)?ie(I,de,Z):L(I,de,Z),x2(I,u)&&g.state.next({...r}),g.values.next({name:I,values:{...s}}),!l.mount&&t()},Q=async I=>{const X=I.target;let Z=X.name,we=!0;const he=ve(o,Z),de=()=>X.type?O0(he._f):F5(I),ke=ft=>{we=Number.isNaN(ft)||ft===ve(s,Z,ft)};if(he){let ft,pt;const _n=de(),Cr=I.type===Bh.BLUR||I.type===Bh.FOCUS_OUT,ki=!UG(he._f)&&!n.resolver&&!ve(r.errors,Z)&&!he._f.deps||VG(Cr,ve(r.touchedFields,Z),r.isSubmitted,_,x),_o=x2(Z,u,Cr);wt(s,Z,_n),Cr?(he._f.onBlur&&he._f.onBlur(I),d&&d(0)):he._f.onChange&&he._f.onChange(I);const Vn=A(Z,_n,Cr,!1),Da=!Fr(Vn)||_o;if(!Cr&&g.values.next({name:Z,type:I.type,values:{...s}}),ki)return m.isValid&&b(),Da&&g.state.next({name:Z,..._o?{}:Vn});if(!Cr&&_o&&g.state.next({...r}),E(!0),n.resolver){const{errors:Ri}=await F([Z]);if(ke(_n),we){const zs=$2(r.errors,o,Z),Ti=$2(Ri,o,zs.name||Z);ft=Ti.error,Z=Ti.name,pt=Fr(Ri)}}else ft=(await C2(he,s,C,n.shouldUseNativeValidation))[Z],ke(_n),we&&(ft?pt=!1:m.isValid&&(pt=await J(o,!0)));we&&(he._f.deps&&le(he._f.deps),O(Z,pt,ft,Vn))}},W=(I,X)=>{if(ve(r.errors,X)&&I.focus)return I.focus(),1},le=async(I,X={})=>{let Z,we;const he=Yp(I);if(E(!0),n.resolver){const de=await V(Ht(I)?I:he);Z=Fr(de),we=I?!he.some(ke=>ve(de,ke)):Z}else I?(we=(await Promise.all(he.map(async de=>{const ke=ve(o,de);return await J(ke&&ke._f?{[de]:ke}:ke)}))).every(Boolean),!(!we&&!r.isValid)&&b()):we=Z=await J(o);return g.state.next({...!Fo(I)||m.isValid&&Z!==r.isValid?{}:{name:I},...n.resolver||!I?{isValid:Z}:{},errors:r.errors,isValidating:!1}),X.shouldFocus&&!we&&Gp(o,W,I?he:u.mount),we},ge=I=>{const X={...i,...l.mount?s:{}};return Ht(I)?X:Fo(I)?ve(X,I):I.map(Z=>ve(X,Z))},Ve=(I,X)=>({invalid:!!ve((X||r).errors,I),isDirty:!!ve((X||r).dirtyFields,I),isTouched:!!ve((X||r).touchedFields,I),error:ve((X||r).errors,I)}),Ue=I=>{I&&Yp(I).forEach(X=>hn(r.errors,X)),g.state.next({errors:I?r.errors:{}})},We=(I,X,Z)=>{const we=(ve(o,I,{_f:{}})._f||{}).ref;wt(r.errors,I,{...X,ref:we}),g.state.next({name:I,errors:r.errors,isValid:!1}),Z&&Z.shouldFocus&&we&&we.focus&&we.focus()},Me=(I,X)=>ds(I)?g.values.subscribe({next:Z=>I(U(void 0,X),Z)}):U(I,X,!0),fe=(I,X={})=>{for(const Z of I?Yp(I):u.mount)u.mount.delete(Z),u.array.delete(Z),X.keepValue||(hn(o,Z),hn(s,Z)),!X.keepError&&hn(r.errors,Z),!X.keepDirty&&hn(r.dirtyFields,Z),!X.keepTouched&&hn(r.touchedFields,Z),!n.shouldUnregister&&!X.keepDefaultValue&&hn(i,Z);g.values.next({values:{...s}}),g.state.next({...r,...X.keepDirty?{isDirty:ae()}:{}}),!X.keepIsValid&&b()},xe=({disabled:I,name:X,field:Z,fields:we,value:he})=>{if(No(I)){const de=I?void 0:Ht(he)?O0(Z?Z._f:ve(we,X)._f):he;wt(s,X,de),A(X,de,!1,!1,!0)}},$e=(I,X={})=>{let Z=ve(o,I);const we=No(X.disabled);return wt(o,I,{...Z||{},_f:{...Z&&Z._f?Z._f:{ref:{name:I}},name:I,mount:!0,...X}}),u.mount.add(I),Z?xe({field:Z,disabled:X.disabled,name:I}):M(I,!0,X.value),{...we?{disabled:X.disabled}:{},...n.progressive?{required:!!X.required,min:iu(X.min),max:iu(X.max),minLength:iu(X.minLength),maxLength:iu(X.maxLength),pattern:iu(X.pattern)}:{},name:I,onChange:Q,onBlur:Q,ref:he=>{if(he){$e(I,X),Z=ve(o,I);const de=Ht(he.value)&&he.querySelectorAll&&he.querySelectorAll("input,select,textarea")[0]||he,ke=zG(de),ft=Z._f.refs||[];if(ke?ft.find(pt=>pt===de):de===Z._f.ref)return;wt(o,I,{_f:{...Z._f,...ke?{refs:[...ft.filter(P0),de,...Array.isArray(ve(i,I))?[{}]:[]],ref:{type:de.type,name:I}}:{ref:de}}}),M(I,!1,void 0,de)}else Z=ve(o,I,{}),Z._f&&(Z._f.mount=!1),(n.shouldUnregister||X.shouldUnregister)&&!(j5(u.array,I)&&l.action)&&u.unMount.add(I)}}},Ae=()=>n.shouldFocusError&&Gp(o,W,u.mount),Oe=I=>{No(I)&&(g.state.next({disabled:I}),Gp(o,X=>{X.disabled=I},0,!1))},je=(I,X)=>async Z=>{Z&&(Z.preventDefault&&Z.preventDefault(),Z.persist&&Z.persist());let we=so(s);if(g.state.next({isSubmitting:!0}),n.resolver){const{errors:he,values:de}=await F();r.errors=he,we=de}else await J(o);hn(r.errors,"root"),Fr(r.errors)?(g.state.next({errors:{}}),await I(we,Z)):(X&&await X({...r.errors},Z),Ae(),setTimeout(Ae)),g.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:Fr(r.errors),submitCount:r.submitCount+1,errors:r.errors})},Ot=(I,X={})=>{ve(o,I)&&(Ht(X.defaultValue)?K(I,ve(i,I)):(K(I,X.defaultValue),wt(i,I,X.defaultValue)),X.keepTouched||hn(r.touchedFields,I),X.keepDirty||(hn(r.dirtyFields,I),r.isDirty=X.defaultValue?ae(I,ve(i,I)):ae()),X.keepError||(hn(r.errors,I),m.isValid&&b()),g.state.next({...r}))},ct=(I,X={})=>{const Z=I?so(I):i,we=so(Z),he=I&&!Fr(I)?we:i;if(X.keepDefaultValues||(i=Z),!X.keepValues){if(X.keepDirtyValues||y)for(const de of u.mount)ve(r.dirtyFields,de)?wt(he,de,ve(s,de)):K(de,ve(he,de));else{if(Ux&&Ht(I))for(const de of u.mount){const ke=ve(o,de);if(ke&&ke._f){const ft=Array.isArray(ke._f.refs)?ke._f.refs[0]:ke._f.ref;if(Uh(ft)){const pt=ft.closest("form");if(pt){pt.reset();break}}}}o={}}s=e.shouldUnregister?X.keepDefaultValues?so(i):{}:so(he),g.array.next({values:{...he}}),g.values.next({values:{...he}})}u={mount:new Set,unMount:new Set,array:new Set,watch:new Set,watchAll:!1,focus:""},!l.mount&&t(),l.mount=!m.isValid||!!X.keepIsValid,l.watch=!!e.shouldUnregister,g.state.next({submitCount:X.keepSubmitCount?r.submitCount:0,isDirty:X.keepDirty?r.isDirty:!!(X.keepDefaultValues&&!ca(I,i)),isSubmitted:X.keepIsSubmitted?r.isSubmitted:!1,dirtyFields:X.keepDirtyValues?r.dirtyFields:X.keepDefaultValues&&I?A0(i,I):{},touchedFields:X.keepTouched?r.touchedFields:{},errors:X.keepErrors?r.errors:{},isSubmitSuccessful:X.keepIsSubmitSuccessful?r.isSubmitSuccessful:!1,isSubmitting:!1})},Kt=(I,X)=>ct(ds(I)?I(s):I,X);return{control:{register:$e,unregister:fe,getFieldState:Ve,handleSubmit:je,setError:We,_executeSchema:F,_getWatch:U,_getDirty:ae,_updateValid:b,_removeUnmounted:G,_updateFieldArray:k,_updateDisabledField:xe,_getFieldArray:te,_reset:ct,_resetDefaultValues:()=>ds(n.defaultValues)&&n.defaultValues().then(I=>{Kt(I,n.resetOptions),g.state.next({isLoading:!1})}),_updateFormState:I=>{r={...r,...I}},_disableForm:Oe,_subjects:g,_proxyFormState:m,get _fields(){return o},get _formValues(){return s},get _state(){return l},set _state(I){l=I},get _defaultValues(){return i},get _names(){return u},set _names(I){u=I},get _formState(){return r},set _formState(I){r=I},get _options(){return n},set _options(I){n={...n,...I}}},trigger:le,register:$e,handleSubmit:je,watch:Me,setValue:K,getValues:ge,reset:Kt,resetField:Ot,clearErrors:Ue,unregister:fe,setError:We,setFocus:(I,X={})=>{const Z=ve(o,I),we=Z&&Z._f;if(we){const he=we.refs?we.refs[0]:we.ref;he.focus&&(he.focus(),X.shouldSelect&&he.select())}},getFieldState:Ve}}function YG(e={}){const t=Fe.useRef(),n=Fe.useRef(),[r,o]=Fe.useState({isDirty:!1,isValidating:!1,isLoading:ds(e.defaultValues),isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,submitCount:0,dirtyFields:{},touchedFields:{},errors:{},disabled:!1,defaultValues:ds(e.defaultValues)?void 0:e.defaultValues});t.current||(t.current={...KG(e,()=>o(s=>({...s}))),formState:r});const i=t.current.control;return i._options=e,Vx({subject:i._subjects.state,next:s=>{U5(s,i._proxyFormState,i._updateFormState,!0)&&o({...i._formState})}}),Fe.useEffect(()=>i._disableForm(e.disabled),[i,e.disabled]),Fe.useEffect(()=>{if(i._proxyFormState.isDirty){const s=i._getDirty();s!==r.isDirty&&i._subjects.state.next({isDirty:s})}},[i,r.isDirty]),Fe.useEffect(()=>{e.values&&!ca(e.values,n.current)?(i._reset(e.values,i._options.resetOptions),n.current=e.values):i._resetDefaultValues()},[e.values,i]),Fe.useEffect(()=>{i._state.mount||(i._updateValid(),i._state.mount=!0),i._state.watch&&(i._state.watch=!1,i._subjects.state.next({...i._formState})),i._removeUnmounted()}),t.current.formState=B5(r,i),t.current}var k2=function(e,t,n){if(e&&"reportValidity"in e){var r=ve(n,t);e.setCustomValidity(r&&r.message||""),e.reportValidity()}},J5=function(e,t){var n=function(o){var i=t.fields[o];i&&i.ref&&"reportValidity"in i.ref?k2(i.ref,o,e):i.refs&&i.refs.forEach(function(s){return k2(s,o,e)})};for(var r in t.fields)n(r)},GG=function(e,t){t.shouldUseNativeValidation&&J5(e,t);var n={};for(var r in e){var o=ve(t.fields,r),i=Object.assign(e[r]||{},{ref:o&&o.ref});if(ZG(t.names||Object.keys(e),r)){var s=Object.assign({},XG(ve(n,r)));wt(s,"root",i),wt(n,r,s)}else wt(n,r,i)}return n},XG=function(e){return Array.isArray(e)?e.filter(Boolean):[]},ZG=function(e,t){return e.some(function(n){return n.startsWith(t+".")})},qG=function(e,t){for(var n={};e.length;){var r=e[0],o=r.code,i=r.message,s=r.path.join(".");if(!n[s])if("unionErrors"in r){var l=r.unionErrors[0].errors[0];n[s]={message:l.message,type:l.code}}else n[s]={message:i,type:o};if("unionErrors"in r&&r.unionErrors.forEach(function(h){return h.errors.forEach(function(m){return e.push(m)})}),t){var u=n[s].types,d=u&&u[r.code];n[s]=K5(s,t,n,o,d?[].concat(d,r.message):r.message)}e.shift()}return n},QG=function(e,t,n){return n===void 0&&(n={}),function(r,o,i){try{return Promise.resolve(function(s,l){try{var u=Promise.resolve(e[n.mode==="sync"?"parse":"parseAsync"](r,t)).then(function(d){return i.shouldUseNativeValidation&&J5({},i),{errors:{},values:n.raw?r:d}})}catch(d){return l(d)}return u&&u.then?u.then(void 0,l):u}(0,function(s){if(function(l){return l.errors!=null}(s))return{values:{},errors:GG(qG(s.errors,!i.shouldUseNativeValidation&&i.criteriaMode==="all"),i)};throw s}))}catch(s){return Promise.reject(s)}}},mt;(function(e){e.assertEqual=o=>o;function t(o){}e.assertIs=t;function n(o){throw new Error}e.assertNever=n,e.arrayToEnum=o=>{const i={};for(const s of o)i[s]=s;return i},e.getValidEnumValues=o=>{const i=e.objectKeys(o).filter(l=>typeof o[o[l]]!="number"),s={};for(const l of i)s[l]=o[l];return e.objectValues(s)},e.objectValues=o=>e.objectKeys(o).map(function(i){return o[i]}),e.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{const i=[];for(const s in o)Object.prototype.hasOwnProperty.call(o,s)&&i.push(s);return i},e.find=(o,i)=>{for(const s of o)if(i(s))return s},e.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&isFinite(o)&&Math.floor(o)===o;function r(o,i=" | "){return o.map(s=>typeof s=="string"?`'${s}'`:s).join(i)}e.joinValues=r,e.jsonStringifyReplacer=(o,i)=>typeof i=="bigint"?i.toString():i})(mt||(mt={}));var R2;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(R2||(R2={}));const be=mt.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ta=e=>{switch(typeof e){case"undefined":return be.undefined;case"string":return be.string;case"number":return isNaN(e)?be.nan:be.number;case"boolean":return be.boolean;case"function":return be.function;case"bigint":return be.bigint;case"symbol":return be.symbol;case"object":return Array.isArray(e)?be.array:e===null?be.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?be.promise:typeof Map<"u"&&e instanceof Map?be.map:typeof Set<"u"&&e instanceof Set?be.set:typeof Date<"u"&&e instanceof Date?be.date:be.object;default:return be.unknown}},pe=mt.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"]);class Bo 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(i){return i.message},r={_errors:[]},o=i=>{for(const s of i.issues)if(s.code==="invalid_union")s.unionErrors.map(o);else if(s.code==="invalid_return_type")o(s.returnTypeError);else if(s.code==="invalid_arguments")o(s.argumentsError);else if(s.path.length===0)r._errors.push(n(s));else{let l=r,u=0;for(;un.message){const n={},r=[];for(const o of this.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(t(o))):r.push(t(o));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}}Bo.create=e=>new Bo(e);const Kh=(e,t)=>{let n;switch(e.code){case pe.invalid_type:e.received===be.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case pe.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,mt.jsonStringifyReplacer)}`;break;case pe.unrecognized_keys:n=`Unrecognized key(s) in object: ${mt.joinValues(e.keys,", ")}`;break;case pe.invalid_union:n="Invalid input";break;case pe.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${mt.joinValues(e.options)}`;break;case pe.invalid_enum_value:n=`Invalid enum value. Expected ${mt.joinValues(e.options)}, received '${e.received}'`;break;case pe.invalid_arguments:n="Invalid function arguments";break;case pe.invalid_return_type:n="Invalid function return type";break;case pe.invalid_date:n="Invalid date";break;case pe.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}"`:mt.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case pe.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 pe.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 pe.custom:n="Invalid input";break;case pe.invalid_intersection_types:n="Intersection results could not be merged";break;case pe.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case pe.not_finite:n="Number must be finite";break;default:n=t.defaultError,mt.assertNever(e)}return{message:n}};let JG=Kh;function S1(){return JG}const E1=e=>{const{data:t,path:n,errorMaps:r,issueData:o}=e,i=[...n,...o.path||[]],s={...o,path:i};let l="";const u=r.filter(d=>!!d).slice().reverse();for(const d of u)l=d(s,{data:t,defaultError:l}).message;return{...o,path:i,message:o.message||l}};function Ee(e,t){const n=E1({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,S1(),Kh].filter(r=>!!r)});e.common.issues.push(n)}class zn{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 o of n){if(o.status==="aborted")return Ze;o.status==="dirty"&&t.dirty(),r.push(o.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){const r=[];for(const o of n)r.push({key:await o.key,value:await o.value});return zn.mergeObjectSync(t,r)}static mergeObjectSync(t,n){const r={};for(const o of n){const{key:i,value:s}=o;if(i.status==="aborted"||s.status==="aborted")return Ze;i.status==="dirty"&&t.dirty(),s.status==="dirty"&&t.dirty(),i.value!=="__proto__"&&(typeof s.value<"u"||o.alwaysSet)&&(r[i.value]=s.value)}return{status:t.value,value:r}}}const Ze=Object.freeze({status:"aborted"}),eX=e=>({status:"dirty",value:e}),rr=e=>({status:"valid",value:e}),T2=e=>e.status==="aborted",P2=e=>e.status==="dirty",Yh=e=>e.status==="valid",C1=e=>typeof Promise<"u"&&e instanceof Promise;var Ne;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t==null?void 0:t.message})(Ne||(Ne={}));class Ko{constructor(t,n,r,o){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=o}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 A2=(e,t)=>{if(Yh(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 Bo(e.common.issues);return this._error=n,this._error}}};function Xe(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:r,description:o}=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:o}:{errorMap:(s,l)=>s.code!=="invalid_type"?{message:l.defaultError}:typeof l.data>"u"?{message:r??l.defaultError}:{message:n??l.defaultError},description:o}}class rt{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.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this)}get description(){return this._def.description}_getType(t){return ta(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:ta(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new zn,ctx:{common:t.parent.common,data:t.data,parsedType:ta(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const n=this._parse(t);if(C1(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 o={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:ta(t)},i=this._parseSync({data:t,path:o.path,parent:o});return A2(o,i)}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:ta(t)},o=this._parse({data:t,path:r.path,parent:r}),i=await(C1(o)?o:Promise.resolve(o));return A2(r,i)}refine(t,n){const r=o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n;return this._refinement((o,i)=>{const s=t(o),l=()=>i.addIssue({code:pe.custom,...r(o)});return typeof Promise<"u"&&s instanceof Promise?s.then(u=>u?!0:(l(),!1)):s?!0:(l(),!1)})}refinement(t,n){return this._refinement((r,o)=>t(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(t){return new Si({schema:this,typeName:ze.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}optional(){return bs.create(this,this._def)}nullable(){return uc.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Uo.create(this,this._def)}promise(){return ad.create(this,this._def)}or(t){return Zh.create([this,t],this._def)}and(t){return qh.create(this,t,this._def)}transform(t){return new Si({...Xe(this._def),schema:this,typeName:ze.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const n=typeof t=="function"?t:()=>t;return new nm({...Xe(this._def),innerType:this,defaultValue:n,typeName:ze.ZodDefault})}brand(){return new fX({typeName:ze.ZodBranded,type:this,...Xe(this._def)})}catch(t){const n=typeof t=="function"?t:()=>t;return new O1({...Xe(this._def),innerType:this,catchValue:n,typeName:ze.ZodCatch})}describe(t){const n=this.constructor;return new n({...this._def,description:t})}pipe(t){return sg.create(this,t)}readonly(){return N1.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const tX=/^c[^\s-]{8,}$/i,nX=/^[a-z][a-z0-9]*$/,rX=/^[0-9A-HJKMNP-TV-Z]{26}$/,oX=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,iX=/^(?!\.)(?!.*\.\.)([A-Z0-9_+-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,sX="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let M0;const aX=/^(((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}))$/,lX=/^(([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})))$/,cX=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 uX(e,t){return!!((t==="v4"||!t)&&aX.test(e)||(t==="v6"||!t)&&lX.test(e))}class di extends rt{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==be.string){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_type,expected:be.string,received:i.parsedType}),Ze}const r=new zn;let o;for(const i of this._def.checks)if(i.kind==="min")t.data.lengthi.value&&(o=this._getOrReturnCtx(t,o),Ee(o,{code:pe.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){const s=t.data.length>i.value,l=t.data.lengtht.test(o),{validation:n,code:pe.invalid_string,...Ne.errToObj(r)})}_addCheck(t){return new di({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...Ne.errToObj(t)})}url(t){return this._addCheck({kind:"url",...Ne.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...Ne.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...Ne.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...Ne.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...Ne.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...Ne.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...Ne.errToObj(t)})}datetime(t){var n;return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof(t==null?void 0:t.precision)>"u"?null:t==null?void 0:t.precision,offset:(n=t==null?void 0:t.offset)!==null&&n!==void 0?n:!1,...Ne.errToObj(t==null?void 0:t.message)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...Ne.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n==null?void 0:n.position,...Ne.errToObj(n==null?void 0:n.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...Ne.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...Ne.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...Ne.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...Ne.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...Ne.errToObj(n)})}nonempty(t){return this.min(1,Ne.errToObj(t))}trim(){return new di({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new di({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new di({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}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 di({checks:[],typeName:ze.ZodString,coerce:(t=e==null?void 0:e.coerce)!==null&&t!==void 0?t:!1,...Xe(e)})};function dX(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,o=n>r?n:r,i=parseInt(e.toFixed(o).replace(".","")),s=parseInt(t.toFixed(o).replace(".",""));return i%s/Math.pow(10,o)}class ac extends rt{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)!==be.number){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_type,expected:be.number,received:i.parsedType}),Ze}let r;const o=new zn;for(const i of this._def.checks)i.kind==="int"?mt.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.invalid_type,expected:"integer",received:"float",message:i.message}),o.dirty()):i.kind==="min"?(i.inclusive?t.datai.value:t.data>=i.value)&&(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),o.dirty()):i.kind==="multipleOf"?dX(t.data,i.value)!==0&&(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):i.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.not_finite,message:i.message}),o.dirty()):mt.assertNever(i);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,Ne.toString(n))}gt(t,n){return this.setLimit("min",t,!1,Ne.toString(n))}lte(t,n){return this.setLimit("max",t,!0,Ne.toString(n))}lt(t,n){return this.setLimit("max",t,!1,Ne.toString(n))}setLimit(t,n,r,o){return new ac({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:Ne.toString(o)}]})}_addCheck(t){return new ac({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:Ne.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Ne.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Ne.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Ne.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Ne.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:Ne.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:Ne.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Ne.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Ne.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"&&mt.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 ac({checks:[],typeName:ze.ZodNumber,coerce:(e==null?void 0:e.coerce)||!1,...Xe(e)});class lc extends rt{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)!==be.bigint){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_type,expected:be.bigint,received:i.parsedType}),Ze}let r;const o=new zn;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?t.datai.value:t.data>=i.value)&&(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),o.dirty()):i.kind==="multipleOf"?t.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):mt.assertNever(i);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,Ne.toString(n))}gt(t,n){return this.setLimit("min",t,!1,Ne.toString(n))}lte(t,n){return this.setLimit("max",t,!0,Ne.toString(n))}lt(t,n){return this.setLimit("max",t,!1,Ne.toString(n))}setLimit(t,n,r,o){return new lc({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:Ne.toString(o)}]})}_addCheck(t){return new lc({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Ne.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Ne.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Ne.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Ne.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:Ne.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 lc({checks:[],typeName:ze.ZodBigInt,coerce:(t=e==null?void 0:e.coerce)!==null&&t!==void 0?t:!1,...Xe(e)})};class $1 extends rt{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==be.boolean){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.boolean,received:r.parsedType}),Ze}return rr(t.data)}}$1.create=e=>new $1({typeName:ze.ZodBoolean,coerce:(e==null?void 0:e.coerce)||!1,...Xe(e)});class sd extends rt{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==be.date){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_type,expected:be.date,received:i.parsedType}),Ze}if(isNaN(t.data.getTime())){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_date}),Ze}const r=new zn;let o;for(const i of this._def.checks)i.kind==="min"?t.data.getTime()i.value&&(o=this._getOrReturnCtx(t,o),Ee(o,{code:pe.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):mt.assertNever(i);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new sd({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:Ne.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:Ne.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 sd({checks:[],coerce:(e==null?void 0:e.coerce)||!1,typeName:ze.ZodDate,...Xe(e)});class k1 extends rt{_parse(t){if(this._getType(t)!==be.symbol){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.symbol,received:r.parsedType}),Ze}return rr(t.data)}}k1.create=e=>new k1({typeName:ze.ZodSymbol,...Xe(e)});class Gh extends rt{_parse(t){if(this._getType(t)!==be.undefined){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.undefined,received:r.parsedType}),Ze}return rr(t.data)}}Gh.create=e=>new Gh({typeName:ze.ZodUndefined,...Xe(e)});class Xh extends rt{_parse(t){if(this._getType(t)!==be.null){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.null,received:r.parsedType}),Ze}return rr(t.data)}}Xh.create=e=>new Xh({typeName:ze.ZodNull,...Xe(e)});class R1 extends rt{constructor(){super(...arguments),this._any=!0}_parse(t){return rr(t.data)}}R1.create=e=>new R1({typeName:ze.ZodAny,...Xe(e)});class Tl extends rt{constructor(){super(...arguments),this._unknown=!0}_parse(t){return rr(t.data)}}Tl.create=e=>new Tl({typeName:ze.ZodUnknown,...Xe(e)});class Rs extends rt{_parse(t){const n=this._getOrReturnCtx(t);return Ee(n,{code:pe.invalid_type,expected:be.never,received:n.parsedType}),Ze}}Rs.create=e=>new Rs({typeName:ze.ZodNever,...Xe(e)});class T1 extends rt{_parse(t){if(this._getType(t)!==be.undefined){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.void,received:r.parsedType}),Ze}return rr(t.data)}}T1.create=e=>new T1({typeName:ze.ZodVoid,...Xe(e)});class Uo extends rt{_parse(t){const{ctx:n,status:r}=this._processInputParams(t),o=this._def;if(n.parsedType!==be.array)return Ee(n,{code:pe.invalid_type,expected:be.array,received:n.parsedType}),Ze;if(o.exactLength!==null){const s=n.data.length>o.exactLength.value,l=n.data.lengtho.maxLength.value&&(Ee(n,{code:pe.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((s,l)=>o.type._parseAsync(new Ko(n,s,n.path,l)))).then(s=>zn.mergeArray(r,s));const i=[...n.data].map((s,l)=>o.type._parseSync(new Ko(n,s,n.path,l)));return zn.mergeArray(r,i)}get element(){return this._def.type}min(t,n){return new Uo({...this._def,minLength:{value:t,message:Ne.toString(n)}})}max(t,n){return new Uo({...this._def,maxLength:{value:t,message:Ne.toString(n)}})}length(t,n){return new Uo({...this._def,exactLength:{value:t,message:Ne.toString(n)}})}nonempty(t){return this.min(1,t)}}Uo.create=(e,t)=>new Uo({type:e,minLength:null,maxLength:null,exactLength:null,typeName:ze.ZodArray,...Xe(t)});function ol(e){if(e instanceof Vt){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=bs.create(ol(r))}return new Vt({...e._def,shape:()=>t})}else return e instanceof Uo?new Uo({...e._def,type:ol(e.element)}):e instanceof bs?bs.create(ol(e.unwrap())):e instanceof uc?uc.create(ol(e.unwrap())):e instanceof _i?_i.create(e.items.map(t=>ol(t))):e}class Vt extends rt{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=mt.objectKeys(t);return this._cached={shape:t,keys:n}}_parse(t){if(this._getType(t)!==be.object){const d=this._getOrReturnCtx(t);return Ee(d,{code:pe.invalid_type,expected:be.object,received:d.parsedType}),Ze}const{status:r,ctx:o}=this._processInputParams(t),{shape:i,keys:s}=this._getCached(),l=[];if(!(this._def.catchall instanceof Rs&&this._def.unknownKeys==="strip"))for(const d in o.data)s.includes(d)||l.push(d);const u=[];for(const d of s){const h=i[d],m=o.data[d];u.push({key:{status:"valid",value:d},value:h._parse(new Ko(o,m,o.path,d)),alwaysSet:d in o.data})}if(this._def.catchall instanceof Rs){const d=this._def.unknownKeys;if(d==="passthrough")for(const h of l)u.push({key:{status:"valid",value:h},value:{status:"valid",value:o.data[h]}});else if(d==="strict")l.length>0&&(Ee(o,{code:pe.unrecognized_keys,keys:l}),r.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const d=this._def.catchall;for(const h of l){const m=o.data[h];u.push({key:{status:"valid",value:h},value:d._parse(new Ko(o,m,o.path,h)),alwaysSet:h in o.data})}}return o.common.async?Promise.resolve().then(async()=>{const d=[];for(const h of u){const m=await h.key;d.push({key:m,value:await h.value,alwaysSet:h.alwaysSet})}return d}).then(d=>zn.mergeObjectSync(r,d)):zn.mergeObjectSync(r,u)}get shape(){return this._def.shape()}strict(t){return Ne.errToObj,new Vt({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{var o,i,s,l;const u=(s=(i=(o=this._def).errorMap)===null||i===void 0?void 0:i.call(o,n,r).message)!==null&&s!==void 0?s:r.defaultError;return n.code==="unrecognized_keys"?{message:(l=Ne.errToObj(t).message)!==null&&l!==void 0?l:u}:{message:u}}}:{}})}strip(){return new Vt({...this._def,unknownKeys:"strip"})}passthrough(){return new Vt({...this._def,unknownKeys:"passthrough"})}extend(t){return new Vt({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new Vt({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:ze.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new Vt({...this._def,catchall:t})}pick(t){const n={};return mt.objectKeys(t).forEach(r=>{t[r]&&this.shape[r]&&(n[r]=this.shape[r])}),new Vt({...this._def,shape:()=>n})}omit(t){const n={};return mt.objectKeys(this.shape).forEach(r=>{t[r]||(n[r]=this.shape[r])}),new Vt({...this._def,shape:()=>n})}deepPartial(){return ol(this)}partial(t){const n={};return mt.objectKeys(this.shape).forEach(r=>{const o=this.shape[r];t&&!t[r]?n[r]=o:n[r]=o.optional()}),new Vt({...this._def,shape:()=>n})}required(t){const n={};return mt.objectKeys(this.shape).forEach(r=>{if(t&&!t[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof bs;)i=i._def.innerType;n[r]=i}}),new Vt({...this._def,shape:()=>n})}keyof(){return e3(mt.objectKeys(this.shape))}}Vt.create=(e,t)=>new Vt({shape:()=>e,unknownKeys:"strip",catchall:Rs.create(),typeName:ze.ZodObject,...Xe(t)});Vt.strictCreate=(e,t)=>new Vt({shape:()=>e,unknownKeys:"strict",catchall:Rs.create(),typeName:ze.ZodObject,...Xe(t)});Vt.lazycreate=(e,t)=>new Vt({shape:e,unknownKeys:"strip",catchall:Rs.create(),typeName:ze.ZodObject,...Xe(t)});class Zh extends rt{_parse(t){const{ctx:n}=this._processInputParams(t),r=this._def.options;function o(i){for(const l of i)if(l.result.status==="valid")return l.result;for(const l of i)if(l.result.status==="dirty")return n.common.issues.push(...l.ctx.common.issues),l.result;const s=i.map(l=>new Bo(l.ctx.common.issues));return Ee(n,{code:pe.invalid_union,unionErrors:s}),Ze}if(n.common.async)return Promise.all(r.map(async i=>{const s={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:s}),ctx:s}})).then(o);{let i;const s=[];for(const u of r){const d={...n,common:{...n.common,issues:[]},parent:null},h=u._parseSync({data:n.data,path:n.path,parent:d});if(h.status==="valid")return h;h.status==="dirty"&&!i&&(i={result:h,ctx:d}),d.common.issues.length&&s.push(d.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;const l=s.map(u=>new Bo(u));return Ee(n,{code:pe.invalid_union,unionErrors:l}),Ze}}get options(){return this._def.options}}Zh.create=(e,t)=>new Zh({options:e,typeName:ze.ZodUnion,...Xe(t)});const Zp=e=>e instanceof Jh?Zp(e.schema):e instanceof Si?Zp(e.innerType()):e instanceof em?[e.value]:e instanceof Ta?e.options:e instanceof tm?Object.keys(e.enum):e instanceof nm?Zp(e._def.innerType):e instanceof Gh?[void 0]:e instanceof Xh?[null]:null;class Yx extends rt{_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.object)return Ee(n,{code:pe.invalid_type,expected:be.object,received:n.parsedType}),Ze;const r=this.discriminator,o=n.data[r],i=this.optionsMap.get(o);return i?n.common.async?i._parseAsync({data:n.data,path:n.path,parent:n}):i._parseSync({data:n.data,path:n.path,parent:n}):(Ee(n,{code:pe.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),Ze)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){const o=new Map;for(const i of n){const s=Zp(i.shape[t]);if(!s)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const l of s){if(o.has(l))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(l)}`);o.set(l,i)}}return new Yx({typeName:ze.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:o,...Xe(r)})}}function P1(e,t){const n=ta(e),r=ta(t);if(e===t)return{valid:!0,data:e};if(n===be.object&&r===be.object){const o=mt.objectKeys(t),i=mt.objectKeys(e).filter(l=>o.indexOf(l)!==-1),s={...e,...t};for(const l of i){const u=P1(e[l],t[l]);if(!u.valid)return{valid:!1};s[l]=u.data}return{valid:!0,data:s}}else if(n===be.array&&r===be.array){if(e.length!==t.length)return{valid:!1};const o=[];for(let i=0;i{if(T2(i)||T2(s))return Ze;const l=P1(i.value,s.value);return l.valid?((P2(i)||P2(s))&&n.dirty(),{status:n.value,value:l.data}):(Ee(r,{code:pe.invalid_intersection_types}),Ze)};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(([i,s])=>o(i,s)):o(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}qh.create=(e,t,n)=>new qh({left:e,right:t,typeName:ze.ZodIntersection,...Xe(n)});class _i extends rt{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.array)return Ee(r,{code:pe.invalid_type,expected:be.array,received:r.parsedType}),Ze;if(r.data.lengththis._def.items.length&&(Ee(r,{code:pe.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const i=[...r.data].map((s,l)=>{const u=this._def.items[l]||this._def.rest;return u?u._parse(new Ko(r,s,r.path,l)):null}).filter(s=>!!s);return r.common.async?Promise.all(i).then(s=>zn.mergeArray(n,s)):zn.mergeArray(n,i)}get items(){return this._def.items}rest(t){return new _i({...this._def,rest:t})}}_i.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new _i({items:e,typeName:ze.ZodTuple,rest:null,...Xe(t)})};class Qh extends rt{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!==be.object)return Ee(r,{code:pe.invalid_type,expected:be.object,received:r.parsedType}),Ze;const o=[],i=this._def.keyType,s=this._def.valueType;for(const l in r.data)o.push({key:i._parse(new Ko(r,l,r.path,l)),value:s._parse(new Ko(r,r.data[l],r.path,l))});return r.common.async?zn.mergeObjectAsync(n,o):zn.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof rt?new Qh({keyType:t,valueType:n,typeName:ze.ZodRecord,...Xe(r)}):new Qh({keyType:di.create(),valueType:t,typeName:ze.ZodRecord,...Xe(n)})}}class A1 extends rt{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!==be.map)return Ee(r,{code:pe.invalid_type,expected:be.map,received:r.parsedType}),Ze;const o=this._def.keyType,i=this._def.valueType,s=[...r.data.entries()].map(([l,u],d)=>({key:o._parse(new Ko(r,l,r.path,[d,"key"])),value:i._parse(new Ko(r,u,r.path,[d,"value"]))}));if(r.common.async){const l=new Map;return Promise.resolve().then(async()=>{for(const u of s){const d=await u.key,h=await u.value;if(d.status==="aborted"||h.status==="aborted")return Ze;(d.status==="dirty"||h.status==="dirty")&&n.dirty(),l.set(d.value,h.value)}return{status:n.value,value:l}})}else{const l=new Map;for(const u of s){const d=u.key,h=u.value;if(d.status==="aborted"||h.status==="aborted")return Ze;(d.status==="dirty"||h.status==="dirty")&&n.dirty(),l.set(d.value,h.value)}return{status:n.value,value:l}}}}A1.create=(e,t,n)=>new A1({valueType:t,keyType:e,typeName:ze.ZodMap,...Xe(n)});class cc extends rt{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.set)return Ee(r,{code:pe.invalid_type,expected:be.set,received:r.parsedType}),Ze;const o=this._def;o.minSize!==null&&r.data.sizeo.maxSize.value&&(Ee(r,{code:pe.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());const i=this._def.valueType;function s(u){const d=new Set;for(const h of u){if(h.status==="aborted")return Ze;h.status==="dirty"&&n.dirty(),d.add(h.value)}return{status:n.value,value:d}}const l=[...r.data.values()].map((u,d)=>i._parse(new Ko(r,u,r.path,d)));return r.common.async?Promise.all(l).then(u=>s(u)):s(l)}min(t,n){return new cc({...this._def,minSize:{value:t,message:Ne.toString(n)}})}max(t,n){return new cc({...this._def,maxSize:{value:t,message:Ne.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}}cc.create=(e,t)=>new cc({valueType:e,minSize:null,maxSize:null,typeName:ze.ZodSet,...Xe(t)});class Pu extends rt{constructor(){super(...arguments),this.validate=this.implement}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.function)return Ee(n,{code:pe.invalid_type,expected:be.function,received:n.parsedType}),Ze;function r(l,u){return E1({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,S1(),Kh].filter(d=>!!d),issueData:{code:pe.invalid_arguments,argumentsError:u}})}function o(l,u){return E1({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,S1(),Kh].filter(d=>!!d),issueData:{code:pe.invalid_return_type,returnTypeError:u}})}const i={errorMap:n.common.contextualErrorMap},s=n.data;if(this._def.returns instanceof ad){const l=this;return rr(async function(...u){const d=new Bo([]),h=await l._def.args.parseAsync(u,i).catch(y=>{throw d.addIssue(r(u,y)),d}),m=await Reflect.apply(s,this,h);return await l._def.returns._def.type.parseAsync(m,i).catch(y=>{throw d.addIssue(o(m,y)),d})})}else{const l=this;return rr(function(...u){const d=l._def.args.safeParse(u,i);if(!d.success)throw new Bo([r(u,d.error)]);const h=Reflect.apply(s,this,d.data),m=l._def.returns.safeParse(h,i);if(!m.success)throw new Bo([o(h,m.error)]);return m.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new Pu({...this._def,args:_i.create(t).rest(Tl.create())})}returns(t){return new Pu({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new Pu({args:t||_i.create([]).rest(Tl.create()),returns:n||Tl.create(),typeName:ze.ZodFunction,...Xe(r)})}}class Jh extends rt{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})}}Jh.create=(e,t)=>new Jh({getter:e,typeName:ze.ZodLazy,...Xe(t)});class em extends rt{_parse(t){if(t.data!==this._def.value){const n=this._getOrReturnCtx(t);return Ee(n,{received:n.data,code:pe.invalid_literal,expected:this._def.value}),Ze}return{status:"valid",value:t.data}}get value(){return this._def.value}}em.create=(e,t)=>new em({value:e,typeName:ze.ZodLiteral,...Xe(t)});function e3(e,t){return new Ta({values:e,typeName:ze.ZodEnum,...Xe(t)})}class Ta extends rt{_parse(t){if(typeof t.data!="string"){const n=this._getOrReturnCtx(t),r=this._def.values;return Ee(n,{expected:mt.joinValues(r),received:n.parsedType,code:pe.invalid_type}),Ze}if(this._def.values.indexOf(t.data)===-1){const n=this._getOrReturnCtx(t),r=this._def.values;return Ee(n,{received:n.data,code:pe.invalid_enum_value,options:r}),Ze}return rr(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 Ta.create(t)}exclude(t){return Ta.create(this.options.filter(n=>!t.includes(n)))}}Ta.create=e3;class tm extends rt{_parse(t){const n=mt.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==be.string&&r.parsedType!==be.number){const o=mt.objectValues(n);return Ee(r,{expected:mt.joinValues(o),received:r.parsedType,code:pe.invalid_type}),Ze}if(n.indexOf(t.data)===-1){const o=mt.objectValues(n);return Ee(r,{received:r.data,code:pe.invalid_enum_value,options:o}),Ze}return rr(t.data)}get enum(){return this._def.values}}tm.create=(e,t)=>new tm({values:e,typeName:ze.ZodNativeEnum,...Xe(t)});class ad extends rt{unwrap(){return this._def.type}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.promise&&n.common.async===!1)return Ee(n,{code:pe.invalid_type,expected:be.promise,received:n.parsedType}),Ze;const r=n.parsedType===be.promise?n.data:Promise.resolve(n.data);return rr(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}}ad.create=(e,t)=>new ad({type:e,typeName:ze.ZodPromise,...Xe(t)});class Si extends rt{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ze.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:n,ctx:r}=this._processInputParams(t),o=this._def.effect||null,i={addIssue:s=>{Ee(r,s),s.fatal?n.abort():n.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),o.type==="preprocess"){const s=o.transform(r.data,i);return r.common.issues.length?{status:"dirty",value:r.data}:r.common.async?Promise.resolve(s).then(l=>this._def.schema._parseAsync({data:l,path:r.path,parent:r})):this._def.schema._parseSync({data:s,path:r.path,parent:r})}if(o.type==="refinement"){const s=l=>{const u=o.refinement(l,i);if(r.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return l};if(r.common.async===!1){const l=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return l.status==="aborted"?Ze:(l.status==="dirty"&&n.dirty(),s(l.value),{status:n.value,value:l.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(l=>l.status==="aborted"?Ze:(l.status==="dirty"&&n.dirty(),s(l.value).then(()=>({status:n.value,value:l.value}))))}if(o.type==="transform")if(r.common.async===!1){const s=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Yh(s))return s;const l=o.transform(s.value,i);if(l instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:l}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(s=>Yh(s)?Promise.resolve(o.transform(s.value,i)).then(l=>({status:n.value,value:l})):s);mt.assertNever(o)}}Si.create=(e,t,n)=>new Si({schema:e,typeName:ze.ZodEffects,effect:t,...Xe(n)});Si.createWithPreprocess=(e,t,n)=>new Si({schema:t,effect:{type:"preprocess",transform:e},typeName:ze.ZodEffects,...Xe(n)});class bs extends rt{_parse(t){return this._getType(t)===be.undefined?rr(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}bs.create=(e,t)=>new bs({innerType:e,typeName:ze.ZodOptional,...Xe(t)});class uc extends rt{_parse(t){return this._getType(t)===be.null?rr(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}uc.create=(e,t)=>new uc({innerType:e,typeName:ze.ZodNullable,...Xe(t)});class nm extends rt{_parse(t){const{ctx:n}=this._processInputParams(t);let r=n.data;return n.parsedType===be.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}nm.create=(e,t)=>new nm({innerType:e,typeName:ze.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Xe(t)});class O1 extends rt{_parse(t){const{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return C1(o)?o.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Bo(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Bo(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}O1.create=(e,t)=>new O1({innerType:e,typeName:ze.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Xe(t)});class M1 extends rt{_parse(t){if(this._getType(t)!==be.nan){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.nan,received:r.parsedType}),Ze}return{status:"valid",value:t.data}}}M1.create=e=>new M1({typeName:ze.ZodNaN,...Xe(e)});class fX extends rt{_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 sg extends rt{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?Ze:i.status==="dirty"?(n.dirty(),eX(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{const o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?Ze:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(t,n){return new sg({in:t,out:n,typeName:ze.ZodPipeline})}}class N1 extends rt{_parse(t){const n=this._def.innerType._parse(t);return Yh(n)&&(n.value=Object.freeze(n.value)),n}}N1.create=(e,t)=>new N1({innerType:e,typeName:ze.ZodReadonly,...Xe(t)});Vt.lazycreate;var ze;(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",e.ZodReadonly="ZodReadonly"})(ze||(ze={}));const O2=di.create;ac.create;M1.create;lc.create;const su=$1.create;sd.create;k1.create;Gh.create;Xh.create;R1.create;Tl.create;Rs.create;T1.create;Uo.create;const pX=Vt.create;Vt.strictCreate;Zh.create;Yx.create;qh.create;_i.create;Qh.create;A1.create;cc.create;Pu.create;Jh.create;em.create;Ta.create;tm.create;ad.create;Si.create;bs.create;uc.create;Si.createWithPreprocess;sg.create;const D1="horizontal",hX=["horizontal","vertical"],t3=f.forwardRef((e,t)=>{const{decorative:n,orientation:r=D1,...o}=e,i=n3(r)?r:D1,l=n?{role:"none"}:{"aria-orientation":i==="vertical"?i:void 0,role:"separator"};return f.createElement(Pe.div,Y({"data-orientation":i},l,o,{ref:t}))});t3.propTypes={orientation(e,t,n){const r=e[t],o=String(r);return r&&!n3(r)?new Error(mX(o,n)):null}};function mX(e,t){return`Invalid prop \`orientation\` of value \`${e}\` supplied to \`${t}\`, expected one of: + - horizontal + - vertical + +Defaulting to \`${D1}\`.`}function n3(e){return hX.includes(e)}const r3=t3,Fn=f.forwardRef(({className:e,orientation:t="horizontal",decorative:n=!0,...r},o)=>v.jsx(r3,{ref:o,decorative:n,orientation:t,className:Ce("shrink-0 bg-border",t==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",e),...r}));Fn.displayName=r3.displayName;const gX=f.forwardRef((e,t)=>f.createElement(Pe.label,Y({},e,{ref:t,onMouseDown:n=>{var r;(r=e.onMouseDown)===null||r===void 0||r.call(e,n),!n.defaultPrevented&&n.detail>1&&n.preventDefault()}}))),o3=gX,vX=Om("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),Gx=f.forwardRef(({className:e,disabled:t,...n},r)=>v.jsx(o3,{ref:r,className:Ce(vX(),e,t?"opacity-50":"","select-none"),...n}));Gx.displayName=o3.displayName;const yX=OG,i3=f.createContext({}),N0=({...e})=>v.jsx(i3.Provider,{value:{name:e.name},children:v.jsx(IG,{...e})}),ag=()=>{const e=f.useContext(i3),t=f.useContext(s3),{getFieldState:n,formState:r}=ig(),o=n(e.name,r);if(!e)throw new Error("useFormField should be used within ");const{id:i}=t;return{id:i,name:e.name,formItemId:`${i}-form-item`,formDescriptionId:`${i}-form-item-description`,formMessageId:`${i}-form-item-message`,...o}},s3=f.createContext({}),qp=f.forwardRef(({className:e,...t},n)=>{const r=f.useId();return v.jsx(s3.Provider,{value:{id:r},children:v.jsx("div",{ref:n,className:Ce("space-y-2",e),...t})})});qp.displayName="FormItem";const Qp=f.forwardRef(({className:e,...t},n)=>{const{error:r,formItemId:o}=ag();return v.jsx(Gx,{ref:n,className:Ce(r&&"text-destructive","text-sm",e),htmlFor:o,...t})});Qp.displayName="FormLabel";const Jp=f.forwardRef(({...e},t)=>{const{error:n,formItemId:r,formDescriptionId:o,formMessageId:i}=ag();return v.jsx(Wo,{ref:t,id:r,"aria-describedby":n?`${o} ${i}`:`${o}`,"aria-invalid":!!n,...e})});Jp.displayName="FormControl";const eh=f.forwardRef(({className:e,...t},n)=>{const{formDescriptionId:r}=ag();return v.jsx("p",{ref:n,id:r,className:Ce("text-[0.8rem] text-muted-foreground",e),...t})});eh.displayName="FormDescription";const wX=f.forwardRef(({className:e,children:t,...n},r)=>{const{error:o,formMessageId:i}=ag(),s=o?String(o==null?void 0:o.message):t;return s?v.jsx("p",{ref:r,id:i,className:Ce("text-[0.8rem] font-medium text-destructive",e),...n,children:s}):null});wX.displayName="FormMessage";const a3="Switch",[xX,_te]=An(a3),[bX,_X]=xX(a3),SX=f.forwardRef((e,t)=>{const{__scopeSwitch:n,name:r,checked:o,defaultChecked:i,required:s,disabled:l,value:u="on",onCheckedChange:d,...h}=e,[m,g]=f.useState(null),y=Be(t,b=>g(b)),x=f.useRef(!1),_=m?!!m.closest("form"):!0,[C=!1,S]=Zr({prop:o,defaultProp:i,onChange:d});return f.createElement(bX,{scope:n,checked:C,disabled:l},f.createElement(Pe.button,Y({type:"button",role:"switch","aria-checked":C,"aria-required":s,"data-state":l3(C),"data-disabled":l?"":void 0,disabled:l,value:u},h,{ref:y,onClick:ue(e.onClick,b=>{S(E=>!E),_&&(x.current=b.isPropagationStopped(),x.current||b.stopPropagation())})})),_&&f.createElement($X,{control:m,bubbles:!x.current,name:r,value:u,checked:C,required:s,disabled:l,style:{transform:"translateX(-100%)"}}))}),EX="SwitchThumb",CX=f.forwardRef((e,t)=>{const{__scopeSwitch:n,...r}=e,o=_X(EX,n);return f.createElement(Pe.span,Y({"data-state":l3(o.checked),"data-disabled":o.disabled?"":void 0},r,{ref:t}))}),$X=e=>{const{control:t,checked:n,bubbles:r=!0,...o}=e,i=f.useRef(null),s=Fx(n),l=gx(t);return f.useEffect(()=>{const u=i.current,d=window.HTMLInputElement.prototype,m=Object.getOwnPropertyDescriptor(d,"checked").set;if(s!==n&&m){const g=new Event("click",{bubbles:r});m.call(u,n),u.dispatchEvent(g)}},[s,n,r]),f.createElement("input",Y({type:"checkbox","aria-hidden":!0,defaultChecked:n},o,{tabIndex:-1,ref:i,style:{...e.style,...l,position:"absolute",pointerEvents:"none",opacity:0,margin:0}}))};function l3(e){return e?"checked":"unchecked"}const c3=SX,kX=CX,co=f.forwardRef(({className:e,...t},n)=>v.jsx(c3,{className:Ce("peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",e),tabIndex:-1,...t,ref:n,children:v.jsx(kX,{className:Ce("pointer-events-none block h-4 w-4 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0")})}));co.displayName=c3.displayName;const RX="AlertDialog",[TX,Ste]=An(RX,[cP]),Is=cP(),PX=e=>{const{__scopeAlertDialog:t,...n}=e,r=Is(t);return f.createElement(Sx,Y({},r,n,{modal:!0}))},AX=e=>{const{__scopeAlertDialog:t,...n}=e,r=Is(t);return f.createElement(Ex,Y({},r,n))},OX=f.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=Is(n);return f.createElement(Nd,Y({},o,r,{ref:t}))}),u3="AlertDialogContent",[MX,NX]=TX(u3),DX=f.forwardRef((e,t)=>{const{__scopeAlertDialog:n,children:r,...o}=e,i=Is(n),s=f.useRef(null),l=Be(t,s),u=f.useRef(null);return f.createElement(fW,{contentName:u3,titleName:IX,docsSlug:"alert-dialog"},f.createElement(MX,{scope:n,cancelRef:u},f.createElement(Dd,Y({role:"alertdialog"},i,o,{ref:l,onOpenAutoFocus:ue(o.onOpenAutoFocus,d=>{var h;d.preventDefault(),(h=u.current)===null||h===void 0||h.focus({preventScroll:!0})}),onPointerDownOutside:d=>d.preventDefault(),onInteractOutside:d=>d.preventDefault()}),f.createElement(sx,null,r),!1)))}),IX="AlertDialogTitle",LX=f.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=Is(n);return f.createElement(Id,Y({},o,r,{ref:t}))}),FX=f.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=Is(n);return f.createElement(Ld,Y({},o,r,{ref:t}))}),jX=f.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=Is(n);return f.createElement(Cx,Y({},o,r,{ref:t}))}),zX="AlertDialogCancel",BX=f.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,{cancelRef:o}=NX(zX,n),i=Is(n),s=Be(t,o);return f.createElement(Cx,Y({},i,r,{ref:s}))}),UX=PX,VX=AX,d3=OX,f3=DX,p3=jX,h3=BX,m3=LX,g3=FX,WX=UX,HX=VX,v3=f.forwardRef(({className:e,...t},n)=>v.jsx(d3,{className:Ce("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t,ref:n}));v3.displayName=d3.displayName;const y3=f.forwardRef(({className:e,...t},n)=>v.jsxs(HX,{children:[v.jsx(v3,{}),v.jsx(f3,{ref:n,className:Ce("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",e),...t})]}));y3.displayName=f3.displayName;const w3=({className:e,...t})=>v.jsx("div",{className:Ce("flex flex-col space-y-2 text-center sm:text-left",e),...t});w3.displayName="AlertDialogHeader";const KX=f.forwardRef(({className:e,...t},n)=>v.jsx(m3,{ref:n,className:Ce("text-lg font-semibold",e),...t}));KX.displayName=m3.displayName;const YX=f.forwardRef(({className:e,...t},n)=>v.jsx(g3,{ref:n,className:Ce("text-sm text-muted-foreground",e),...t}));YX.displayName=g3.displayName;const GX=f.forwardRef(({className:e,...t},n)=>v.jsx(p3,{ref:n,className:Ce(bx(),e),...t}));GX.displayName=p3.displayName;const XX=f.forwardRef(({className:e,...t},n)=>v.jsx(h3,{ref:n,className:Ce(bx({variant:"outline"}),"mt-2 sm:mt-0",e),...t}));XX.displayName=h3.displayName;const ZX=pX({enableFileManager:su(),inputDirectory:O2(),outputDirectory:O2(),enableDownloadMask:su(),enableManualInpainting:su(),enableUploadMask:su(),enableAutoExtractPrompt:su()}),x3="General",I1="Model",qX=[I1,x3];function QX(){const[e,t]=u1(!1),[n,r]=u1(!1),[o,i]=f.useState(I1),[s,l,u,d,h,m]=bt(O=>[O.updateAppState,O.settings,O.updateSettings,O.fileManagerState,O.updateFileManagerState,O.setModel]),{toast:g}=Td(),[y,x]=f.useState(l.model);f.useEffect(()=>{x(l.model)},[l.model]);const{data:_,status:C}=TL({queryKey:["modelInfos"],queryFn:Bj}),S=YG({resolver:QG(ZX),defaultValues:{enableDownloadMask:l.enableDownloadMask,enableManualInpainting:l.enableManualInpainting,enableUploadMask:l.enableUploadMask,enableAutoExtractPrompt:l.enableAutoExtractPrompt,inputDirectory:d.inputDirectory,outputDirectory:d.outputDirectory}});async function b(O){if(u({enableDownloadMask:O.enableDownloadMask,enableManualInpainting:O.enableManualInpainting,enableUploadMask:O.enableUploadMask,enableAutoExtractPrompt:O.enableAutoExtractPrompt}),h({inputDirectory:O.inputDirectory,outputDirectory:O.outputDirectory}),y.name!==l.model.name){r(),s({disableShortCuts:!0});try{const F=await jj(y.name);g({title:`Switch to ${F.name} success`}),m(y)}catch(F){g({variant:"destructive",title:`Switch to ${y.name} failed: ${F}`}),x(l.model)}finally{r(),s({disableShortCuts:!1})}}}Zn("s",()=>{t(),e&&b(S.getValues())},[e,S,y]);function E(O){t(),O||b(S.getValues())}function k(O){x(O)}function P(O){return _?_.filter(F=>O.includes(F.model_type)).map(F=>v.jsxs("div",{onClick:()=>k(F),className:"px-2",children:[v.jsx("div",{className:Ce([F.name===y.name?"bg-muted":"hover:bg-muted","rounded-md px-2 py-2","cursor-default"]),children:v.jsx("div",{className:"text-base",children:F.name})}),v.jsx(Fn,{className:"my-1"})]},F.name)):v.jsx("div",{children:"Please download model first"})}function M(){if(C!=="success")return v.jsx(v.Fragment,{});let O=is;for(let F of _)if(y.name===F.name){O=F.model_type,O===nC&&(O=rp),O===rC&&(O=op);break}return v.jsxs("div",{className:"flex flex-col gap-4 w-[510px]",children:[v.jsxs("div",{className:"flex flex-col gap-4 rounded-md",children:[v.jsx("div",{className:"font-medium",children:"Current Model"}),v.jsx("div",{children:y.name})]}),v.jsx(Fn,{}),v.jsxs("div",{className:"space-y-4 rounded-md",children:[v.jsx("div",{className:"flex gap-1 items-center justify-start",children:v.jsx("div",{className:"font-medium",children:"Available models"})}),v.jsxs(i5,{defaultValue:O,children:[v.jsxs(Lx,{children:[v.jsx(sa,{value:is,children:"Inpaint"}),v.jsx(sa,{value:rp,children:"Stable Diffusion"}),v.jsx(sa,{value:op,children:"Stable Diffusion Inpaint"}),v.jsx(sa,{value:l0,children:"Other Diffusion"})]}),v.jsxs(og,{className:"h-[240px] w-full mt-2 outline-none border rounded-lg",children:[v.jsx(mu,{value:is,children:P([is])}),v.jsx(mu,{value:rp,children:P([rp,nC])}),v.jsx(mu,{value:op,children:P([op,rC])}),v.jsx(mu,{value:l0,children:P([l0])})]})]})]})]})}function A(){return v.jsxs("div",{className:"space-y-4 w-[510px]",children:[v.jsx(N0,{control:S.control,name:"enableManualInpainting",render:({field:O})=>v.jsxs(qp,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(Qp,{children:"Enable manual inpainting"}),v.jsx(eh,{children:"For erase model, click a button to trigger inpainting after draw mask."})]}),v.jsx(Jp,{children:v.jsx(co,{checked:O.value,onCheckedChange:O.onChange})})]})}),v.jsx(Fn,{}),v.jsx(N0,{control:S.control,name:"enableDownloadMask",render:({field:O})=>v.jsxs(qp,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(Qp,{children:"Enable download mask"}),v.jsx(eh,{children:"Also download the mask after save the inpainting result."})]}),v.jsx(Jp,{children:v.jsx(co,{checked:O.value,onCheckedChange:O.onChange})})]})}),v.jsx(Fn,{}),v.jsx(N0,{control:S.control,name:"enableAutoExtractPrompt",render:({field:O})=>v.jsxs(qp,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(Qp,{children:"Enable auto extract prompt"}),v.jsx(eh,{children:"Automatically extract prompt/negativate prompt from the image meta."})]}),v.jsx(Jp,{children:v.jsx(co,{checked:O.value,onCheckedChange:O.onChange})})]})})]})}return v.jsxs(v.Fragment,{children:[v.jsx(WX,{open:n,children:v.jsx(y3,{children:v.jsx(w3,{children:v.jsxs("div",{className:"flex flex-col justify-center items-center gap-4",children:[v.jsxs("div",{role:"status",children:[v.jsxs("svg",{"aria-hidden":"true",className:"w-8 h-8 text-gray-200 animate-spin dark:text-gray-600 fill-primary",viewBox:"0 0 100 101",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[v.jsx("path",{d:"M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z",fill:"currentColor"}),v.jsx("path",{d:"M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z",fill:"currentFill"})]}),v.jsx("span",{className:"sr-only",children:"Loading..."})]}),v.jsxs("div",{children:["Switching to ",y.name]})]})})})}),v.jsxs(Zm,{open:e,onOpenChange:E,children:[v.jsx($x,{asChild:!0,children:v.jsx(vn,{tooltip:"Settings",children:v.jsx(iV,{})})}),v.jsxs(Fd,{className:"max-w-3xl h-[600px]",onOpenAutoFocus:O=>O.preventDefault(),children:[v.jsx(jd,{children:"Settings"}),v.jsx(Fn,{}),v.jsxs("div",{className:"flex flex-row space-x-8 h-full",children:[v.jsx("div",{className:"flex flex-col space-y-1",children:qX.map(O=>v.jsx(yn,{variant:"ghost",onClick:()=>i(O),className:Ce(o===O?"bg-muted ":"hover:bg-muted","justify-start"),children:O},O))}),v.jsx(Fn,{orientation:"vertical"}),v.jsx(yX,{...S,children:v.jsx("div",{className:"flex w-full justify-center",children:v.jsxs("form",{onSubmit:S.handleSubmit(b),children:[o===I1?M():v.jsx(v.Fragment,{}),o===x3?A():v.jsx(v.Fragment,{}),v.jsx("div",{className:"absolute right-10 bottom-6",children:v.jsx(yn,{onClick:()=>E(!1),children:"Ok"})})]})})})]})]})]})]})}const JX="/assets/kofi_button_black-XI_Dr2zg.png";function eZ(){return v.jsxs(Zm,{children:[v.jsx($x,{asChild:!0,children:v.jsx(vn,{tooltip:"Buy me a coffee",children:v.jsx(GU,{})})}),v.jsxs(Fd,{children:[v.jsx(jd,{children:"Buy me a coffee"}),v.jsx(mP,{className:"mb-8",children:"Hi, if you found my project is useful, please conside buy me a coffee to support my work. Thanks!"}),v.jsx("div",{className:"w-full flex items-center justify-center",children:v.jsx("a",{href:"https://ko-fi.com/Z8Z1CZJGY",target:"_blank",rel:"noreferrer",children:v.jsx("img",{src:JX,className:"h-[32px]"})})})]})]})}const tZ=()=>{const[e,t,n,r,o,i,s,l,u,d,h,m,g,y]=bt(M=>[M.file,M.customMask,M.isInpainting,M.serverConfig,M.runMannually(),M.settings.enableUploadMask,M.settings.model,M.setFile,M.setCustomFile,M.runInpainting,M.showPrevMask,M.hidePrevMask,M.imageHeight,M.imageWidth]),{toast:x}=Td(),[_,C]=Rx(t),[S,b]=f.useState(!1),E=()=>{d()},k=()=>{h()},P=()=>{m()};return v.jsxs("header",{className:"h-[60px] px-6 py-4 absolute top-[0] flex justify-between items-center w-full z-20 border-b backdrop-filter backdrop-blur-md bg-background/70",children:[v.jsxs("div",{className:"flex items-center gap-1",children:[r.enableFileManager?v.jsx(TG,{photoWidth:512,onPhotoClick:async(M,A)=>{try{const O=await Uj(M,A);l(O)}catch(O){x({variant:"destructive",description:O.message?O.message:O.toString()});return}}}):v.jsx(v.Fragment,{}),v.jsx(c1,{disabled:n,tooltip:"Upload image",onFileUpload:M=>{l(M)},children:v.jsx(eV,{})}),v.jsxs("div",{className:Ce(["flex items-center gap-1",e&&i?"visible":"hidden"]),children:[v.jsx(c1,{disabled:n,tooltip:"Upload custom mask",onFileUpload:async M=>{let A=null;try{A=await pF(M)}catch(O){x({variant:"destructive",description:O.message?O.message:O.toString()});return}if(A.naturalHeight!==g||A.naturalWidth!==y){x({variant:"destructive",description:`The size of the mask must same as image: ${y}x${g}`});return}u(M),o||d()},children:v.jsx(ZT,{})}),t?v.jsxs(HW,{open:S,children:[v.jsx(KW,{className:"btn-primary side-panel-trigger",onMouseEnter:()=>b(!0),onMouseLeave:()=>b(!1),style:{visibility:t?"visible":"hidden",outline:"none"},onClick:()=>{},children:v.jsx(vn,{tooltip:"Run custom mask",children:v.jsx(cz,{})})}),v.jsx(PP,{children:C?v.jsx("img",{src:_.src,alt:"Custom mask"}):v.jsx(v.Fragment,{})})]}):v.jsx(v.Fragment,{})]}),e&&!s.need_prompt?v.jsx(vn,{disabled:n,tooltip:"Rerun previous mask",onClick:E,onMouseEnter:k,onMouseLeave:P,children:v.jsx(oV,{})}):v.jsx(v.Fragment,{})]}),s.need_prompt?v.jsx(vH,{}):v.jsx(v.Fragment,{}),v.jsxs("div",{className:"flex gap-1",children:[v.jsx(eZ,{}),v.jsx(AW,{}),r.disableModelSwitch?v.jsx(v.Fragment,{}):v.jsx(QX,{})]})]})};var Wr=function(e,t){return Number(e.toFixed(t))},nZ=function(e,t){return typeof e=="number"?e:t},Nt=function(e,t,n){n&&typeof n=="function"&&n(e,t)},rZ=function(e){return-Math.cos(e*Math.PI)/2+.5},oZ=function(e){return e},iZ=function(e){return e*e},sZ=function(e){return e*(2-e)},aZ=function(e){return e<.5?2*e*e:-1+(4-2*e)*e},lZ=function(e){return e*e*e},cZ=function(e){return--e*e*e+1},uZ=function(e){return e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1},dZ=function(e){return e*e*e*e},fZ=function(e){return 1- --e*e*e*e},pZ=function(e){return e<.5?8*e*e*e*e:1-8*--e*e*e*e},hZ=function(e){return e*e*e*e*e},mZ=function(e){return 1+--e*e*e*e*e},gZ=function(e){return e<.5?16*e*e*e*e*e:1+16*--e*e*e*e*e},b3={easeOut:rZ,linear:oZ,easeInQuad:iZ,easeOutQuad:sZ,easeInOutQuad:aZ,easeInCubic:lZ,easeOutCubic:cZ,easeInOutCubic:uZ,easeInQuart:dZ,easeOutQuart:fZ,easeInOutQuart:pZ,easeInQuint:hZ,easeOutQuint:mZ,easeInOutQuint:gZ},_3=function(e){typeof e=="number"&&cancelAnimationFrame(e)},Do=function(e){e.mounted&&(_3(e.animation),e.animate=!1,e.animation=null,e.velocity=null)};function S3(e,t,n,r){if(e.mounted){var o=new Date().getTime(),i=1;Do(e),e.animation=function(){if(!e.mounted)return _3(e.animation);var s=new Date().getTime()-o,l=s/n,u=b3[t],d=u(l);s>=n?(r(i),e.animation=null):e.animation&&(r(d),requestAnimationFrame(e.animation))},requestAnimationFrame(e.animation)}}function vZ(e){var t=e.scale,n=e.positionX,r=e.positionY;return!(Number.isNaN(t)||Number.isNaN(n)||Number.isNaN(r))}function Ls(e,t,n,r){var o=vZ(t);if(!(!e.mounted||!o)){var i=e.setTransformState,s=e.transformState,l=s.scale,u=s.positionX,d=s.positionY,h=t.scale-l,m=t.positionX-u,g=t.positionY-d;n===0?i(t.scale,t.positionX,t.positionY):S3(e,r,n,function(y){var x=l+h*y,_=u+m*y,C=d+g*y;i(x,_,C)})}}function yZ(e,t,n){var r=e.offsetWidth,o=e.offsetHeight,i=t.offsetWidth,s=t.offsetHeight,l=i*n,u=s*n,d=r-l,h=o-u;return{wrapperWidth:r,wrapperHeight:o,newContentWidth:l,newDiffWidth:d,newContentHeight:u,newDiffHeight:h}}var wZ=function(e,t,n,r,o,i,s){var l=e>t?n*(s?1:.5):0,u=r>o?i*(s?1:.5):0,d=e-t-l,h=l,m=r-o-u,g=u;return{minPositionX:d,maxPositionX:h,minPositionY:m,maxPositionY:g}},Xx=function(e,t){var n=e.wrapperComponent,r=e.contentComponent,o=e.setup.centerZoomedOut;if(!n||!r)throw new Error("Components are not mounted");var i=yZ(n,r,t),s=i.wrapperWidth,l=i.wrapperHeight,u=i.newContentWidth,d=i.newDiffWidth,h=i.newContentHeight,m=i.newDiffHeight,g=wZ(s,u,d,l,h,m,!!o);return g},L1=function(e,t,n,r){return r?en?Wr(n,2):Wr(e,2):Wr(e,2)},dc=function(e,t){var n=Xx(e,t);return e.bounds=n,n};function lg(e,t,n,r,o,i,s){var l=n.minPositionX,u=n.minPositionY,d=n.maxPositionX,h=n.maxPositionY,m=0,g=0;s&&(m=o,g=i);var y=L1(e,l-m,d+m,r),x=L1(t,u-g,h+g,r);return{x:y,y:x}}function cg(e,t,n,r,o,i){var s=e.transformState,l=s.scale,u=s.positionX,d=s.positionY,h=r-l;if(typeof t!="number"||typeof n!="number")return console.error("Mouse X and Y position were not provided!"),{x:u,y:d};var m=u-t*h,g=d-n*h,y=lg(m,g,o,i,0,0,null);return y}function Vd(e,t,n,r,o){var i=o?r:0,s=t-i;return!Number.isNaN(n)&&e>=n?n:!Number.isNaN(t)&&e<=s?s:e}var M2=function(e,t){var n=e.setup.panning.excluded,r=e.isInitialized,o=e.wrapperComponent,i=t.target,s=o==null?void 0:o.contains(i),l=r&&i&&s;if(!l)return!1;var u=ug(i,n);return!u},N2=function(e){var t=e.isInitialized,n=e.isPanning,r=e.setup,o=r.panning.disabled,i=t&&n&&!o;return!!i},xZ=function(e,t){var n=e.transformState,r=n.positionX,o=n.positionY;e.isPanning=!0;var i=t.clientX,s=t.clientY;e.startCoords={x:i-r,y:s-o}},bZ=function(e,t){var n=t.touches,r=e.transformState,o=r.positionX,i=r.positionY;e.isPanning=!0;var s=n.length===1;if(s){var l=n[0].clientX,u=n[0].clientY;e.startCoords={x:l-o,y:u-i}}};function _Z(e){var t=e.transformState,n=t.positionX,r=t.positionY,o=t.scale,i=e.setup,s=i.disabled,l=i.limitToBounds,u=i.centerZoomedOut,d=e.wrapperComponent;if(!(s||!d||!e.bounds)){var h=e.bounds,m=h.maxPositionX,g=h.minPositionX,y=h.maxPositionY,x=h.minPositionY,_=n>m||ny||rm?d.offsetWidth:e.setup.minPositionX||0,b=r>y?d.offsetHeight:e.setup.minPositionY||0,E=cg(e,S,b,o,e.bounds,l||u),k=E.x,P=E.y;return{scale:o,positionX:_?k:n,positionY:C?P:r}}}function SZ(e,t,n,r,o){var i=e.setup.limitToBounds,s=e.wrapperComponent,l=e.bounds,u=e.transformState,d=u.scale,h=u.positionX,m=u.positionY;if(!(s===null||l===null||t===h&&n===m)){var g=lg(t,n,l,i,r,o,s),y=g.x,x=g.y;e.setTransformState(d,y,x)}}var EZ=function(e,t,n){var r=e.startCoords,o=e.transformState,i=e.setup.panning,s=i.lockAxisX,l=i.lockAxisY,u=o.positionX,d=o.positionY;if(!r)return{x:u,y:d};var h=t-r.x,m=n-r.y,g=s?u:h,y=l?d:m;return{x:g,y}},rm=function(e,t){var n=e.setup,r=e.transformState,o=r.scale,i=n.minScale,s=n.disablePadding;return t>0&&o>=i&&!s?t:0},CZ=function(e){var t=e.mounted,n=e.setup,r=n.disabled,o=n.velocityAnimation,i=e.transformState.scale,s=o.disabled,l=!s||i>1||!r||t;return!!l},$Z=function(e){var t=e.mounted,n=e.velocity,r=e.bounds,o=e.setup,i=o.disabled,s=o.velocityAnimation,l=e.transformState.scale,u=s.disabled,d=!u||l>1||!i||t;return!(!d||!n||!r)};function kZ(e,t){var n=e.setup.velocityAnimation,r=n.equalToMove,o=n.animationTime,i=n.sensitivity;return r?o*t*i:o}function D2(e,t,n,r,o,i,s,l,u,d){if(o){if(t>s&&n>s){var h=s+(e-s)*d;return h>u?u:hi?i:h}}return r?t:L1(e,i,s,o)}function RZ(e,t){var n=1;return t?Math.min(n,e.offsetWidth/window.innerWidth):n}function TZ(e,t){var n=CZ(e);if(n){var r=e.lastMousePosition,o=e.velocityTime,i=e.setup,s=e.wrapperComponent,l=i.velocityAnimation.equalToMove,u=Date.now();if(r&&o&&s){var d=RZ(s,l),h=t.x-r.x,m=t.y-r.y,g=h/d,y=m/d,x=u-o,_=h*h+m*m,C=Math.sqrt(_)/x;e.velocity={velocityX:g,velocityY:y,total:C}}e.lastMousePosition=t,e.velocityTime=u}}function PZ(e){var t=e.velocity,n=e.bounds,r=e.setup,o=e.wrapperComponent,i=$Z(e);if(!(!i||!t||!n||!o)){var s=t.velocityX,l=t.velocityY,u=t.total,d=n.maxPositionX,h=n.minPositionX,m=n.maxPositionY,g=n.minPositionY,y=r.limitToBounds,x=r.alignmentAnimation,_=r.zoomAnimation,C=r.panning,S=C.lockAxisY,b=C.lockAxisX,E=_.animationType,k=x.sizeX,P=x.sizeY,M=x.velocityAlignmentTime,A=M,O=kZ(e,u),F=Math.max(O,A),V=rm(e,k),J=rm(e,P),G=V*o.offsetWidth/100,ae=J*o.offsetHeight/100,U=d+G,te=h-G,L=m+ae,ie=g-ae,K=e.transformState,Q=new Date().getTime();S3(e,E,F,function(W){var le=e.transformState,ge=le.scale,Ve=le.positionX,Ue=le.positionY,We=new Date().getTime()-Q,Me=We/A,fe=b3[x.animationType],xe=1-fe(Math.min(1,Me)),$e=1-W,Ae=Ve+s*$e,Oe=Ue+l*$e,je=D2(Ae,K.positionX,Ve,b,y,h,d,te,U,xe),Ot=D2(Oe,K.positionY,Ue,S,y,g,m,ie,L,xe);(Ve!==Ae||Ue!==Oe)&&e.setTransformState(ge,je,Ot)})}}function I2(e,t){var n=e.transformState.scale;Do(e),dc(e,n),window.TouchEvent!==void 0&&t instanceof TouchEvent?bZ(e,t):xZ(e,t)}function E3(e){var t=e.transformState.scale,n=e.setup,r=n.minScale,o=n.alignmentAnimation,i=o.disabled,s=o.sizeX,l=o.sizeY,u=o.animationTime,d=o.animationType,h=i||t.1&&m;g?PZ(e):E3(e)}}function Zx(e,t,n,r){var o=e.setup,i=o.minScale,s=o.maxScale,l=o.limitToBounds,u=Vd(Wr(t,2),i,s,0,!1),d=dc(e,u),h=cg(e,n,r,u,d,l),m=h.x,g=h.y;return{scale:u,positionX:m,positionY:g}}function C3(e,t,n){var r=e.transformState.scale,o=e.wrapperComponent,i=e.setup,s=i.minScale,l=i.limitToBounds,u=i.zoomAnimation,d=u.disabled,h=u.animationTime,m=u.animationType,g=d||r>=s;if((r>=1||l)&&E3(e),!(g||!o||!e.mounted)){var y=t||o.offsetWidth/2,x=n||o.offsetHeight/2,_=Zx(e,s,y,x);_&&Ls(e,_,h,m)}}var _s=function(){return _s=Object.assign||function(t){for(var n,r=1,o=arguments.length;rs||Math.sign(n.deltaY)!==Math.sign(t.deltaY)||n.deltaY>0&&n.deltaYt.deltaY||Math.sign(n.deltaY)!==Math.sign(t.deltaY):!1},GZ=function(e,t){var n=e.setup.pinch,r=n.disabled,o=n.excluded,i=e.isInitialized,s=t.target,l=i&&!r&&s;if(!l)return!1;var u=ug(s,o);return!u},XZ=function(e){var t=e.setup.pinch.disabled,n=e.isInitialized,r=e.pinchStartDistance,o=n&&!t&&r;return!!o},ZZ=function(e,t,n){var r=n.getBoundingClientRect(),o=e.touches,i=Wr(o[0].clientX-r.left,5),s=Wr(o[0].clientY-r.top,5),l=Wr(o[1].clientX-r.left,5),u=Wr(o[1].clientY-r.top,5);return{x:(i+l)/2/t,y:(s+u)/2/t}},O3=function(e){return Math.sqrt(Math.pow(e.touches[0].pageX-e.touches[1].pageX,2)+Math.pow(e.touches[0].pageY-e.touches[1].pageY,2))},qZ=function(e,t){var n=e.pinchStartScale,r=e.pinchStartDistance,o=e.setup,i=o.maxScale,s=o.minScale,l=o.zoomAnimation,u=o.disablePadding,d=l.size,h=l.disabled;if(!n||r===null||!t)throw new Error("Pinch touches distance was not provided");if(t<0)return e.transformState.scale;var m=t/r,g=m*n;return Vd(Wr(g,2),s,i,d,!h&&!u)},QZ=160,JZ=100,eq=function(e,t){var n=e.props,r=n.onWheelStart,o=n.onZoomStart;e.wheelStopEventTimer||(Do(e),Nt(St(e),t,r),Nt(St(e),t,o))},tq=function(e,t){var n=e.props,r=n.onWheel,o=n.onZoom,i=e.contentComponent,s=e.setup,l=e.transformState,u=l.scale,d=s.limitToBounds,h=s.centerZoomedOut,m=s.zoomAnimation,g=s.wheel,y=s.disablePadding,x=s.smooth,_=m.size,C=m.disabled,S=g.step,b=g.smoothStep;if(!i)throw new Error("Component not mounted");t.preventDefault(),t.stopPropagation();var E=HZ(t,null),k=x?b*Math.abs(t.deltaY):S,P=KZ(e,E,k,!t.ctrlKey);if(u!==P){var M=dc(e,P),A=A3(t,i,u),O=C||_===0||h||y,F=d&&O,V=cg(e,A.x,A.y,P,M,F),J=V.x,G=V.y;e.previousWheelEvent=t,e.setTransformState(P,J,G),Nt(St(e),t,r),Nt(St(e),t,o)}},nq=function(e,t){var n=e.props,r=n.onWheelStop,o=n.onZoomStop;j1(e.wheelAnimationTimer),e.wheelAnimationTimer=setTimeout(function(){e.mounted&&(C3(e,t.x,t.y),e.wheelAnimationTimer=null)},JZ);var i=YZ(e,t);i&&(j1(e.wheelStopEventTimer),e.wheelStopEventTimer=setTimeout(function(){e.mounted&&(e.wheelStopEventTimer=null,Nt(St(e),t,r),Nt(St(e),t,o))},QZ))},rq=function(e,t){var n=O3(t);e.pinchStartDistance=n,e.lastDistance=n,e.pinchStartScale=e.transformState.scale,e.isPanning=!1,Do(e)},oq=function(e,t){var n=e.contentComponent,r=e.pinchStartDistance,o=e.transformState.scale,i=e.setup,s=i.limitToBounds,l=i.centerZoomedOut,u=i.zoomAnimation,d=u.disabled,h=u.size;if(!(r===null||!n)){var m=ZZ(t,o,n);if(!(!Number.isFinite(m.x)||!Number.isFinite(m.y))){var g=O3(t),y=qZ(e,g);if(y!==o){var x=dc(e,y),_=d||h===0||l,C=s&&_,S=cg(e,m.x,m.y,y,x,C),b=S.x,E=S.y;e.pinchMidpoint=m,e.lastDistance=g,e.setTransformState(y,b,E)}}}},iq=function(e){var t=e.pinchMidpoint;e.velocity=null,e.lastDistance=null,e.pinchMidpoint=null,e.pinchStartScale=null,e.pinchStartDistance=null,C3(e,t==null?void 0:t.x,t==null?void 0:t.y)},M3=function(e,t){var n=e.props.onZoomStop,r=e.setup.doubleClick.animationTime;j1(e.doubleClickStopEventTimer),e.doubleClickStopEventTimer=setTimeout(function(){e.doubleClickStopEventTimer=null,Nt(St(e),t,n)},r)},sq=function(e,t){var n=e.props,r=n.onZoomStart,o=n.onZoom,i=e.setup.doubleClick,s=i.animationTime,l=i.animationType;Nt(St(e),t,r),T3(e,s,l,function(){return Nt(St(e),t,o)}),M3(e,t)};function aq(e,t){var n=e.setup,r=e.doubleClickStopEventTimer,o=e.transformState,i=e.contentComponent,s=o.scale,l=e.props,u=l.onZoomStart,d=l.onZoom,h=n.doubleClick,m=h.disabled,g=h.mode,y=h.step,x=h.animationTime,_=h.animationType;if(!m&&!r){if(g==="reset")return sq(e,t);if(!i)return console.error("No ContentComponent found");var C=g==="zoomOut"?-1:1,S=k3(e,C,y);if(s!==S){Nt(St(e),t,u);var b=A3(t,i,s),E=Zx(e,S,b.x,b.y);if(!E)return console.error("Error during zoom event. New transformation state was not calculated.");Nt(St(e),t,d),Ls(e,E,x,_),M3(e,t)}}}var lq=function(e,t){var n=e.isInitialized,r=e.setup,o=e.wrapperComponent,i=r.doubleClick,s=i.disabled,l=i.excluded,u=t.target,d=o==null?void 0:o.contains(u),h=n&&u&&d&&!s;if(!h)return!1;var m=ug(u,l);return!m},cq=function(){function e(t){var n=this;this.mounted=!0,this.onChangeCallbacks=new Set,this.onInitCallbacks=new Set,this.wrapperComponent=null,this.contentComponent=null,this.isInitialized=!1,this.bounds=null,this.previousWheelEvent=null,this.wheelStopEventTimer=null,this.wheelAnimationTimer=null,this.isPanning=!1,this.startCoords=null,this.lastTouch=null,this.distance=null,this.lastDistance=null,this.pinchStartDistance=null,this.pinchStartScale=null,this.pinchMidpoint=null,this.doubleClickStopEventTimer=null,this.velocity=null,this.velocityTime=null,this.lastMousePosition=null,this.animate=!1,this.animation=null,this.maxBounds=null,this.pressedKeys={},this.mount=function(){n.initializeWindowEvents()},this.unmount=function(){n.cleanupWindowEvents()},this.update=function(r){dc(n,n.transformState.scale),n.setup=j2(r)},this.initializeWindowEvents=function(){var r,o=I0(),i=(r=n.wrapperComponent)===null||r===void 0?void 0:r.ownerDocument,s=i==null?void 0:i.defaultView;s==null||s.addEventListener("mousedown",n.onPanningStart,o),s==null||s.addEventListener("mousemove",n.onPanning,o),s==null||s.addEventListener("mouseup",n.onPanningStop,o),i==null||i.addEventListener("mouseleave",n.clearPanning,o),s==null||s.addEventListener("keyup",n.setKeyUnPressed,o),s==null||s.addEventListener("keydown",n.setKeyPressed,o)},this.cleanupWindowEvents=function(){var r,o,i=I0(),s=(r=n.wrapperComponent)===null||r===void 0?void 0:r.ownerDocument,l=s==null?void 0:s.defaultView;l==null||l.removeEventListener("mousedown",n.onPanningStart,i),l==null||l.removeEventListener("mousemove",n.onPanning,i),l==null||l.removeEventListener("mouseup",n.onPanningStop,i),s==null||s.removeEventListener("mouseleave",n.clearPanning,i),l==null||l.removeEventListener("keyup",n.setKeyUnPressed,i),l==null||l.removeEventListener("keydown",n.setKeyPressed,i),document.removeEventListener("mouseleave",n.clearPanning,i),Do(n),(o=n.observer)===null||o===void 0||o.disconnect()},this.handleInitializeWrapperEvents=function(r){var o=I0();r.addEventListener("wheel",n.onWheelZoom,o),r.addEventListener("dblclick",n.onDoubleClick,o),r.addEventListener("touchstart",n.onTouchPanningStart,o),r.addEventListener("touchmove",n.onTouchPanning,o),r.addEventListener("touchend",n.onTouchPanningStop,o)},this.handleInitialize=function(r){var o=n.setup.centerOnInit;n.applyTransformation(),n.onInitCallbacks.forEach(function(i){return i(St(n))}),o&&(n.setCenter(),n.observer=new ResizeObserver(function(){var i;n.onInitCallbacks.forEach(function(s){return s(St(n))}),n.setCenter(),(i=n.observer)===null||i===void 0||i.disconnect()}),n.observer.observe(r))},this.onWheelZoom=function(r){var o=n.setup.disabled;if(!o){var i=VZ(n,r);if(i){var s=n.isPressingKeys(n.setup.wheel.activationKeys);s&&(eq(n,r),tq(n,r),nq(n,r))}}},this.onPanningStart=function(r){var o=n.setup.disabled,i=n.props.onPanningStart;if(!o){var s=M2(n,r);if(s){var l=n.isPressingKeys(n.setup.panning.activationKeys);l&&(r.button===0&&!n.setup.panning.allowLeftClickPan||r.button===1&&!n.setup.panning.allowMiddleClickPan||r.button===2&&!n.setup.panning.allowRightClickPan||(r.preventDefault(),r.stopPropagation(),Do(n),I2(n,r),Nt(St(n),r,i)))}}},this.onPanning=function(r){var o=n.setup.disabled,i=n.props.onPanning;if(!o){var s=N2(n);if(s){var l=n.isPressingKeys(n.setup.panning.activationKeys);l&&(r.preventDefault(),r.stopPropagation(),L2(n,r.clientX,r.clientY),Nt(St(n),r,i))}}},this.onPanningStop=function(r){var o=n.props.onPanningStop;n.isPanning&&(AZ(n),Nt(St(n),r,o))},this.onPinchStart=function(r){var o=n.setup.disabled,i=n.props,s=i.onPinchingStart,l=i.onZoomStart;if(!o){var u=GZ(n,r);u&&(rq(n,r),Do(n),Nt(St(n),r,s),Nt(St(n),r,l))}},this.onPinch=function(r){var o=n.setup.disabled,i=n.props,s=i.onPinching,l=i.onZoom;if(!o){var u=XZ(n);u&&(r.preventDefault(),r.stopPropagation(),oq(n,r),Nt(St(n),r,s),Nt(St(n),r,l))}},this.onPinchStop=function(r){var o=n.props,i=o.onPinchingStop,s=o.onZoomStop;n.pinchStartScale&&(iq(n),Nt(St(n),r,i),Nt(St(n),r,s))},this.onTouchPanningStart=function(r){var o=n.setup.disabled,i=n.props.onPanningStart;if(!o){var s=M2(n,r);if(s){var l=n.lastTouch&&+new Date-n.lastTouch<200;if(l&&r.touches.length===1)n.onDoubleClick(r);else{n.lastTouch=+new Date,Do(n);var u=r.touches,d=u.length===1,h=u.length===2;d&&(Do(n),I2(n,r),Nt(St(n),r,i)),h&&n.onPinchStart(r)}}}},this.onTouchPanning=function(r){var o=n.setup.disabled,i=n.props.onPanning;if(n.isPanning&&r.touches.length===1){if(o)return;var s=N2(n);if(!s)return;r.preventDefault(),r.stopPropagation();var l=r.touches[0];L2(n,l.clientX,l.clientY),Nt(St(n),r,i)}else r.touches.length>1&&n.onPinch(r)},this.onTouchPanningStop=function(r){n.onPanningStop(r),n.onPinchStop(r)},this.onDoubleClick=function(r){var o=n.setup.disabled;if(!o){var i=lq(n,r);i&&aq(n,r)}},this.clearPanning=function(r){n.isPanning&&n.onPanningStop(r)},this.setKeyPressed=function(r){n.pressedKeys[r.key]=!0},this.setKeyUnPressed=function(r){n.pressedKeys[r.key]=!1},this.isPressingKeys=function(r){return r.length?!!r.find(function(o){return n.pressedKeys[o]}):!0},this.setTransformState=function(r,o,i){var s=n.props.onTransformed;if(!Number.isNaN(r)&&!Number.isNaN(o)&&!Number.isNaN(i)){r!==n.transformState.scale&&(n.transformState.previousScale=n.transformState.scale,n.transformState.scale=r),n.transformState.positionX=o,n.transformState.positionY=i,n.applyTransformation();var l=St(n);n.onChangeCallbacks.forEach(function(u){return u(l)}),Nt(l,{scale:r,positionX:o,positionY:i},s)}else console.error("Detected NaN set state values")},this.setCenter=function(){if(n.wrapperComponent&&n.contentComponent){var r=P3(n.transformState.scale,n.wrapperComponent,n.contentComponent);n.setTransformState(r.scale,r.positionX,r.positionY)}},this.handleTransformStyles=function(r,o,i){return n.props.customTransform?n.props.customTransform(r,o,i):BZ(r,o,i)},this.applyTransformation=function(){if(!(!n.mounted||!n.contentComponent)){var r=n.transformState,o=r.scale,i=r.positionX,s=r.positionY,l=n.handleTransformStyles(i,s,o);n.contentComponent.style.transform=l}},this.getContext=function(){return St(n)},this.onChange=function(r){return n.onChangeCallbacks.has(r)||n.onChangeCallbacks.add(r),function(){n.onChangeCallbacks.delete(r)}},this.onInit=function(r){return n.onInitCallbacks.has(r)||n.onInitCallbacks.add(r),function(){n.onInitCallbacks.delete(r)}},this.init=function(r,o){n.cleanupWindowEvents(),n.wrapperComponent=r,n.contentComponent=o,dc(n,n.transformState.scale),n.handleInitializeWrapperEvents(r),n.handleInitialize(o),n.initializeWindowEvents(),n.isInitialized=!0;var i=St(n);Nt(i,void 0,n.props.onInit)},this.props=t,this.setup=j2(this.props),this.transformState=$3(this.props)}return e}(),qx=Fe.createContext(null),uq=function(e,t){return typeof e=="function"?e(t):e},dq=Fe.forwardRef(function(e,t){var n=f.useRef(new cq(e)).current,r=uq(e.children,F1(n));return f.useImperativeHandle(t,function(){return F1(n)},[n]),f.useEffect(function(){n.update(e)},[n,e]),Fe.createElement(qx.Provider,{value:n},r)});Fe.forwardRef(function(e,t){var n=f.useRef(null),r=f.useContext(qx);return f.useEffect(function(){return r.onChange(function(o){if(n.current){var i=0,s=0;n.current.style.transform=r.handleTransformStyles(i,s,1/o.instance.transformState.scale)}})},[r]),Fe.createElement("div",_s({},e,{ref:UZ([n,t])}))});function fq(e,t){t===void 0&&(t={});var n=t.insertAt;if(!(!e||typeof document>"u")){var r=document.head||document.getElementsByTagName("head")[0],o=document.createElement("style");o.type="text/css",n==="top"&&r.firstChild?r.insertBefore(o,r.firstChild):r.appendChild(o),o.styleSheet?o.styleSheet.cssText=e:o.appendChild(document.createTextNode(e))}}var pq=`.transform-component-module_wrapper__SPB86 { + position: relative; + width: -moz-fit-content; + width: fit-content; + height: -moz-fit-content; + height: fit-content; + overflow: hidden; + -webkit-touch-callout: none; /* iOS Safari */ + -webkit-user-select: none; /* Safari */ + -khtml-user-select: none; /* Konqueror HTML */ + -moz-user-select: none; /* Firefox */ + -ms-user-select: none; /* Internet Explorer/Edge */ + user-select: none; + margin: 0; + padding: 0; +} +.transform-component-module_content__FBWxo { + display: flex; + flex-wrap: wrap; + width: -moz-fit-content; + width: fit-content; + height: -moz-fit-content; + height: fit-content; + margin: 0; + padding: 0; + transform-origin: 0% 0%; +} +.transform-component-module_content__FBWxo img { + pointer-events: none; +} +`,z2={wrapper:"transform-component-module_wrapper__SPB86",content:"transform-component-module_content__FBWxo"};fq(pq);var hq=function(e){var t=e.children,n=e.wrapperClass,r=n===void 0?"":n,o=e.contentClass,i=o===void 0?"":o,s=e.wrapperStyle,l=e.contentStyle,u=e.wrapperProps,d=u===void 0?{}:u,h=e.contentProps,m=h===void 0?{}:h,g=f.useContext(qx),y=g.init,x=g.cleanupWindowEvents,_=f.useRef(null),C=f.useRef(null);return f.useEffect(function(){var S=_.current,b=C.current;return S!==null&&b!==null&&y&&(y==null||y(S,b)),function(){x==null||x()}},[]),Fe.createElement("div",_s({},d,{ref:_,className:"react-transform-wrapper ".concat(z2.wrapper," ").concat(r),style:s}),Fe.createElement("div",_s({},m,{ref:C,className:"react-transform-component ".concat(z2.content," ").concat(i),style:l}),t))};const N3=["PageUp","PageDown"],D3=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],I3={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},Wd="Slider",[z1,mq,gq]=zd(Wd),[L3,Ete]=An(Wd,[gq]),[vq,dg]=L3(Wd),yq=f.forwardRef((e,t)=>{const{name:n,min:r=0,max:o=100,step:i=1,orientation:s="horizontal",disabled:l=!1,minStepsBetweenThumbs:u=0,defaultValue:d=[r],value:h,onValueChange:m=()=>{},onValueCommit:g=()=>{},inverted:y=!1,...x}=e,[_,C]=f.useState(null),S=Be(t,U=>C(U)),b=f.useRef(new Set),E=f.useRef(0),k=s==="horizontal",P=_?!!_.closest("form"):!0,M=k?wq:xq,[A=[],O]=Zr({prop:h,defaultProp:d,onChange:U=>{var te;(te=[...b.current][E.current])===null||te===void 0||te.focus(),m(U)}}),F=f.useRef(A);function V(U){const te=Tq(A,U);ae(U,te)}function J(U){ae(U,E.current)}function G(){const U=F.current[E.current];A[E.current]!==U&&g(A)}function ae(U,te,{commit:L}={commit:!1}){const ie=Mq(i),K=Nq(Math.round((U-r)/i)*i+r,ie),Q=id(K,[r,o]);O((W=[])=>{const le=kq(W,Q,te);if(Oq(le,u*i)){E.current=le.indexOf(Q);const ge=String(le)!==String(W);return ge&&L&&g(le),ge?le:W}else return W})}return f.createElement(vq,{scope:e.__scopeSlider,disabled:l,min:r,max:o,valueIndexToChangeRef:E,thumbs:b.current,values:A,orientation:s},f.createElement(z1.Provider,{scope:e.__scopeSlider},f.createElement(z1.Slot,{scope:e.__scopeSlider},f.createElement(M,Y({"aria-disabled":l,"data-disabled":l?"":void 0},x,{ref:S,onPointerDown:ue(x.onPointerDown,()=>{l||(F.current=A)}),min:r,max:o,inverted:y,onSlideStart:l?void 0:V,onSlideMove:l?void 0:J,onSlideEnd:l?void 0:G,onHomeKeyDown:()=>!l&&ae(r,0,{commit:!0}),onEndKeyDown:()=>!l&&ae(o,A.length-1,{commit:!0}),onStepKeyDown:({event:U,direction:te})=>{if(!l){const K=N3.includes(U.key)||U.shiftKey&&D3.includes(U.key)?10:1,Q=E.current,W=A[Q],le=i*K*te;ae(W+le,Q,{commit:!0})}}})))),P&&A.map((U,te)=>f.createElement($q,{key:te,name:n?n+(A.length>1?"[]":""):void 0,value:U})))}),[F3,j3]=L3(Wd,{startEdge:"left",endEdge:"right",size:"width",direction:1}),wq=f.forwardRef((e,t)=>{const{min:n,max:r,dir:o,inverted:i,onSlideStart:s,onSlideMove:l,onSlideEnd:u,onStepKeyDown:d,...h}=e,[m,g]=f.useState(null),y=Be(t,E=>g(E)),x=f.useRef(),_=Sc(o),C=_==="ltr",S=C&&!i||!C&&i;function b(E){const k=x.current||m.getBoundingClientRect(),P=[0,k.width],A=Qx(P,S?[n,r]:[r,n]);return x.current=k,A(E-k.left)}return f.createElement(F3,{scope:e.__scopeSlider,startEdge:S?"left":"right",endEdge:S?"right":"left",direction:S?1:-1,size:"width"},f.createElement(z3,Y({dir:_,"data-orientation":"horizontal"},h,{ref:y,style:{...h.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:E=>{const k=b(E.clientX);s==null||s(k)},onSlideMove:E=>{const k=b(E.clientX);l==null||l(k)},onSlideEnd:()=>{x.current=void 0,u==null||u()},onStepKeyDown:E=>{const P=I3[S?"from-left":"from-right"].includes(E.key);d==null||d({event:E,direction:P?-1:1})}})))}),xq=f.forwardRef((e,t)=>{const{min:n,max:r,inverted:o,onSlideStart:i,onSlideMove:s,onSlideEnd:l,onStepKeyDown:u,...d}=e,h=f.useRef(null),m=Be(t,h),g=f.useRef(),y=!o;function x(_){const C=g.current||h.current.getBoundingClientRect(),S=[0,C.height],E=Qx(S,y?[r,n]:[n,r]);return g.current=C,E(_-C.top)}return f.createElement(F3,{scope:e.__scopeSlider,startEdge:y?"bottom":"top",endEdge:y?"top":"bottom",size:"height",direction:y?1:-1},f.createElement(z3,Y({"data-orientation":"vertical"},d,{ref:m,style:{...d.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:_=>{const C=x(_.clientY);i==null||i(C)},onSlideMove:_=>{const C=x(_.clientY);s==null||s(C)},onSlideEnd:()=>{g.current=void 0,l==null||l()},onStepKeyDown:_=>{const S=I3[y?"from-bottom":"from-top"].includes(_.key);u==null||u({event:_,direction:S?-1:1})}})))}),z3=f.forwardRef((e,t)=>{const{__scopeSlider:n,onSlideStart:r,onSlideMove:o,onSlideEnd:i,onHomeKeyDown:s,onEndKeyDown:l,onStepKeyDown:u,...d}=e,h=dg(Wd,n);return f.createElement(Pe.span,Y({},d,{ref:t,onKeyDown:ue(e.onKeyDown,m=>{m.key==="Home"?(s(m),m.preventDefault()):m.key==="End"?(l(m),m.preventDefault()):N3.concat(D3).includes(m.key)&&(u(m),m.preventDefault())}),onPointerDown:ue(e.onPointerDown,m=>{const g=m.target;g.setPointerCapture(m.pointerId),m.preventDefault(),h.thumbs.has(g)?g.focus():r(m)}),onPointerMove:ue(e.onPointerMove,m=>{m.target.hasPointerCapture(m.pointerId)&&o(m)}),onPointerUp:ue(e.onPointerUp,m=>{const g=m.target;g.hasPointerCapture(m.pointerId)&&(g.releasePointerCapture(m.pointerId),i(m))})}))}),bq="SliderTrack",_q=f.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,o=dg(bq,n);return f.createElement(Pe.span,Y({"data-disabled":o.disabled?"":void 0,"data-orientation":o.orientation},r,{ref:t}))}),B2="SliderRange",Sq=f.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,o=dg(B2,n),i=j3(B2,n),s=f.useRef(null),l=Be(t,s),u=o.values.length,d=o.values.map(g=>B3(g,o.min,o.max)),h=u>1?Math.min(...d):0,m=100-Math.max(...d);return f.createElement(Pe.span,Y({"data-orientation":o.orientation,"data-disabled":o.disabled?"":void 0},r,{ref:l,style:{...e.style,[i.startEdge]:h+"%",[i.endEdge]:m+"%"}}))}),U2="SliderThumb",Eq=f.forwardRef((e,t)=>{const n=mq(e.__scopeSlider),[r,o]=f.useState(null),i=Be(t,l=>o(l)),s=f.useMemo(()=>r?n().findIndex(l=>l.ref.current===r):-1,[n,r]);return f.createElement(Cq,Y({},e,{ref:i,index:s}))}),Cq=f.forwardRef((e,t)=>{const{__scopeSlider:n,index:r,...o}=e,i=dg(U2,n),s=j3(U2,n),[l,u]=f.useState(null),d=Be(t,C=>u(C)),h=gx(l),m=i.values[r],g=m===void 0?0:B3(m,i.min,i.max),y=Rq(r,i.values.length),x=h==null?void 0:h[s.size],_=x?Pq(x,g,s.direction):0;return f.useEffect(()=>{if(l)return i.thumbs.add(l),()=>{i.thumbs.delete(l)}},[l,i.thumbs]),f.createElement("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[s.startEdge]:`calc(${g}% + ${_}px)`}},f.createElement(z1.ItemSlot,{scope:e.__scopeSlider},f.createElement(Pe.span,Y({role:"slider","aria-label":e["aria-label"]||y,"aria-valuemin":i.min,"aria-valuenow":m,"aria-valuemax":i.max,"aria-orientation":i.orientation,"data-orientation":i.orientation,"data-disabled":i.disabled?"":void 0,tabIndex:i.disabled?void 0:0},o,{ref:d,style:m===void 0?{display:"none"}:e.style,onFocus:ue(e.onFocus,()=>{i.valueIndexToChangeRef.current=r})}))))}),$q=e=>{const{value:t,...n}=e,r=f.useRef(null),o=Fx(t);return f.useEffect(()=>{const i=r.current,s=window.HTMLInputElement.prototype,u=Object.getOwnPropertyDescriptor(s,"value").set;if(o!==t&&u){const d=new Event("input",{bubbles:!0});u.call(i,t),i.dispatchEvent(d)}},[o,t]),f.createElement("input",Y({style:{display:"none"}},n,{ref:r,defaultValue:t}))};function kq(e=[],t,n){const r=[...e];return r[n]=t,r.sort((o,i)=>o-i)}function B3(e,t,n){const i=100/(n-t)*(e-t);return id(i,[0,100])}function Rq(e,t){return t>2?`Value ${e+1} of ${t}`:t===2?["Minimum","Maximum"][e]:void 0}function Tq(e,t){if(e.length===1)return 0;const n=e.map(o=>Math.abs(o-t)),r=Math.min(...n);return n.indexOf(r)}function Pq(e,t,n){const r=e/2,i=Qx([0,50],[0,r]);return(r-i(t)*n)*n}function Aq(e){return e.slice(0,-1).map((t,n)=>e[n+1]-t)}function Oq(e,t){if(t>0){const n=Aq(e);return Math.min(...n)>=t}return!0}function Qx(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 Mq(e){return(String(e).split(".")[1]||"").length}function Nq(e,t){const n=Math.pow(10,t);return Math.round(e*n)/n}const U3=yq,Dq=_q,Iq=Sq,Lq=Eq,uo=f.forwardRef(({className:e,...t},n)=>v.jsxs(U3,{ref:n,className:Ce("relative flex w-full touch-none select-none items-center",e),tabIndex:-1,...t,children:[v.jsx(Dq,{className:"relative h-1.5 w-full grow overflow-hidden rounded-full bg-primary/20 data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50",children:v.jsx(Iq,{className:"absolute h-full bg-primary data-[disabled]:cursor-not-allowed "})}),v.jsx(Lq,{tabIndex:-1,className:"block h-4 w-4 rounded-full border border-primary/60 bg-background shadow transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring data-[disabled]:cursor-not-allowed"})]}));uo.displayName=U3.displayName;const tl={capture:!0,passive:!1},Fq=2,V2=(e,t,n,r,o,i)=>{if(e!==n&&t===r){if(e<0)return[0,r];if(e+t>i)return[i-r,r]}else{if(ti)return[e,i-e]}return[e,t]},jq=e=>{const{minHeight:t,minWidth:n,maxHeight:r,maxWidth:o,scale:i,show:s}=e,[l,u,d,h,{x:m,y:g,width:y,height:x},_,C,S,b,E,k]=bt(W=>[W.imageWidth,W.imageHeight,W.isInpainting,W.isSD(),W.cropperState,W.setCropperX,W.setCropperY,W.setCropperWidth,W.setCropperHeight,W.isCropperExtenderResizing,W.setIsCropperExtenderResizing]),[P,M]=f.useState(!1);f.useEffect(()=>{_(Math.round((o-512)/2)),C(Math.round((r-512)/2))},[r,o,l,u]);const[A,O]=f.useState({initX:0,initY:0,initHeight:0,initWidth:0,startResizeX:0,startResizeY:0,ord:"top"}),F=()=>{},V=(W,le)=>V2(W,le,m,y,n,o),J=(W,le)=>V2(W,le,g,x,t,r),G=W=>{if(d)return;const le=W.clientX,ge=W.clientY,Ve=Math.round((ge-A.startResizeY)/i),Ue=Math.round((le-A.startResizeX)/i),We=()=>{const $e=A.initHeight-Ve,Ae=A.initY+Ve,[Oe,je]=J(Ae,$e);b(je),C(Oe)},Me=()=>{const $e=A.initHeight+Ve,[Ae,Oe]=J(A.initY,$e);b(Oe),C(Ae)},fe=()=>{const $e=A.initWidth-Ue,Ae=A.initX+Ue,[Oe,je]=V(Ae,$e);S(je),_(Oe)},xe=()=>{const $e=A.initWidth+Ue,[Ae,Oe]=V(A.initX,$e);S(Oe),_(Ae)};if(E)switch(A.ord){case"topleft":{We(),fe();break}case"topright":{We(),xe();break}case"bottomleft":{Me(),fe();break}case"bottomright":{Me(),xe();break}case"top":{We();break}case"right":{xe();break}case"bottom":{Me();break}case"left":{fe();break}}if(P){const $e=A.initX+Ue,Ae=A.initY+Ve,[Oe,je]=V($e,A.initWidth),[Ot,ct]=J(Ae,A.initHeight);S(je),b(ct),_(Oe),C(Ot)}},ae=()=>{E&&k(!1),P&&M(!1)};f.useEffect(()=>{if(E||P)return document.addEventListener("pointermove",G,tl),document.addEventListener("pointerup",ae,tl),document.addEventListener("pointercancel",ae,tl),()=>{document.removeEventListener("pointermove",G,tl),document.removeEventListener("pointerup",ae,tl),document.removeEventListener("pointercancel",ae,tl)}},[E,P,y,x,A]);const U=W=>{const{ord:le}=W.target.dataset;le&&(k(!0),O({initX:m,initY:g,initHeight:x,initWidth:y,startResizeX:W.clientX,startResizeY:W.clientY,ord:le}))},te=(W,le,ge)=>{const We="w-[12px] h-[12px] z-[4] absolute content-[''] block border-2 border-primary borde pointer-events-auto hover:bg-primary";let Me="0",fe="0",xe=ge,$e="-6px";return ge===""&&($e="50%",le==="left"||le==="right"?(xe="top",fe="-50%"):(xe="left",Me="-50%")),v.jsx("div",{className:Ce(We,W),style:{[le]:-6,[xe]:$e,transform:`translate(${Me}, ${fe}) scale(${1/i})`},"data-ord":le+ge,"aria-label":le+ge,tabIndex:-1,role:"button"})},L=()=>v.jsxs("div",{onFocus:F,onPointerDown:U,className:"absolute top-0 h-full w-full",children:[v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 w-full cursor-ns-resize h-[12px] mt-[-6px]","data-ord":"top"}),v.jsx("div",{className:"absolute pointer-events-auto top-0 right-0 h-full cursor-ew-resize w-[12px] mr-[-6px]","data-ord":"right"}),v.jsx("div",{className:"absolute pointer-events-auto bottom-0 left-0 w-full cursor-ns-resize h-[12px] mb-[-6px]","data-ord":"bottom"}),v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 h-full cursor-ew-resize w-[12px] ml-[-6px]","data-ord":"left"}),te("cursor-nw-resize","top","left"),te("cursor-ne-resize","top","right"),te("cursor-sw-resize","bottom","left"),te("cursor-se-resize","bottom","right"),te("cursor-ns-resize","top",""),te("cursor-ns-resize","bottom",""),te("cursor-ew-resize","left",""),te("cursor-ew-resize","right","")]}),ie=W=>{M(!0),O({initX:m,initY:g,initHeight:x,initWidth:y,startResizeX:W.clientX,startResizeY:W.clientY,ord:""})},K=()=>v.jsxs("div",{className:Jw("border absolute pointer-events-auto px-2 py-1 rounded-full hover:cursor-move bg-background","origin-top-left top-0 left-0"),style:{transform:`scale(${1/i*.8})`},onPointerDown:ie,children:[y," x ",x]}),Q=()=>v.jsx("div",{className:"outline-dashed outline-primary",style:{height:x,width:y,outlineWidth:`${Fq/i*1.3}px`}});return s===!1||!h?null:v.jsx("div",{className:"absolute h-full w-full overflow-hidden pointer-events-none z-[2]",children:v.jsxs("div",{className:"relative pointer-events-none z-[2] [box-shadow:0_0_0_9999px_rgba(0,_0,_0,_0.5)]",style:{height:x,width:y,left:m,top:g},children:[Q(),K(),L()]})})},zq=()=>{const[e,t,n]=bt(r=>[r.interactiveSegState,r.resetInteractiveSegState,r.handleInteractiveSegAccept]);return e.isInteractiveSeg?v.jsxs("div",{className:"z-10 absolute top-[68px] rounded-xl border-solid border p-[8px] left-1/2 translate-x-[-50%] flex justify-center items-center gap-[8px] bg-background",children:[v.jsx(yn,{onClick:()=>{t()},size:"sm",variant:"secondary",children:"Cancel"}),v.jsx(yn,{size:"sm",onClick:()=>{n()},children:"Accept"})]}):null},Bq=e=>{const{x:t,y:n,positive:r}=e,o=r?"bg-[rgba(21,_215,_121,_0.936)] outline-[rgba(98,255,179,0.31)]":"bg-[rgba(237,_49,_55,_0.942)] outline-[rgba(255,89,95,0.31)]";return v.jsx("div",{className:`absolute h-[10px] w-[10px] rounded-[50%] ${o} outline-8 outline`,style:{left:t,top:n,transform:"translate(-50%, -50%)"}})},Uq=()=>{const e=bt(t=>t.interactiveSegState.clicks);return v.jsx("div",{className:"absolute h-full w-full overflow-hidden pointer-events-none",children:e.map(t=>v.jsx(Bq,{x:t[0],y:t[1],positive:t[2]===1},t[3]))})},Vq=()=>v.jsx("div",{children:v.jsx(zq,{})}),nl={capture:!0,passive:!1},Wq=2,W2=(e,t,n,r)=>t{const{minHeight:t,minWidth:n,scale:r,show:o}=e,[i,s,l,u,{x:d,y:h,width:m,height:g},y,x,_,C,S,b,E]=bt(ie=>[ie.isInpainting,ie.imageHeight,ie.imageWidth,ie.isSD(),ie.extenderState,ie.setExtenderX,ie.setExtenderY,ie.setExtenderWidth,ie.setExtenderHeight,ie.settings.extenderDirection,ie.isCropperExtenderResizing,ie.setIsCropperExtenderResizing]),[k,P]=f.useState({initX:0,initY:0,initHeight:0,initWidth:0,startResizeX:0,startResizeY:0,ord:"top"}),M=()=>{},A=(ie,K)=>W2(ie,K,d,n),O=(ie,K)=>W2(ie,K,h,t),F=ie=>{if(i)return;const K=ie.clientX,Q=ie.clientY,W=Math.round((Q-k.startResizeY)/r),le=Math.round((K-k.startResizeX)/r),ge=()=>{const Me=k.initHeight-W,fe=k.initY+W;let xe=fe,$e=Me;if(S===In.xy)xe>0&&(xe=0,$e=k.initHeight-Math.abs(k.initY));else{const Ae=O(fe,Me);xe=Ae[0],$e=Ae[1]}C($e),x(xe)},Ve=()=>{const Me=k.initHeight+W;let[fe,xe]=O(k.initY,Me);S===In.xy&&xe{const Me=k.initWidth-le,fe=k.initX+le;let xe=fe,$e=Me;if(S===In.xy)xe>0&&(xe=0,$e=k.initWidth-Math.abs(k.initX));else{const Ae=A(fe,Me);xe=Ae[0],$e=Ae[1]}_($e),y(xe)},We=()=>{const Me=k.initWidth+le;let[fe,xe]=A(k.initX,Me);S===In.xy&&xe{b&&E(!1)};f.useEffect(()=>{if(b)return document.addEventListener("pointermove",F,nl),document.addEventListener("pointerup",V,nl),document.addEventListener("pointercancel",V,nl),()=>{document.removeEventListener("pointermove",F,nl),document.removeEventListener("pointerup",V,nl),document.removeEventListener("pointercancel",V,nl)}},[b,m,g,k]);const J=ie=>{const{ord:K}=ie.target.dataset;K&&(E(!0),P({initX:d,initY:h,initHeight:g,initWidth:m,startResizeX:ie.clientX,startResizeY:ie.clientY,ord:K}))},G=(ie,K,Q)=>{const ge="w-[12px] h-[12px] z-[4] absolute content-[''] block border-2 border-primary borde pointer-events-auto hover:bg-primary";let Ve="0",Ue="0",We=Q,Me="-6px";return Q===""&&(Me="50%",K==="left"||K==="right"?(We="top",Ue="-50%"):(We="left",Ve="-50%")),v.jsx("div",{className:Ce(ge,ie),style:{[K]:-6,[We]:Me,transform:`translate(${Ve}, ${Ue}) scale(${1/r})`},"data-ord":K+Q,"aria-label":K+Q,tabIndex:-1,role:"button"})},ae=()=>v.jsxs("div",{onFocus:M,onPointerDown:J,className:"absolute top-0 h-full w-full",children:[[In.y,In.xy].includes(S)?v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 w-full cursor-ns-resize h-[12px] mt-[-6px]","data-ord":"top"}),v.jsx("div",{className:"absolute pointer-events-auto bottom-0 left-0 w-full cursor-ns-resize h-[12px] mb-[-6px]","data-ord":"bottom"}),G("cursor-ns-resize","top",""),G("cursor-ns-resize","bottom","")]}):v.jsx(v.Fragment,{}),[In.x,In.xy].includes(S)?v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"absolute pointer-events-auto top-0 right-0 h-full cursor-ew-resize w-[12px] mr-[-6px]","data-ord":"right"}),v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 h-full cursor-ew-resize w-[12px] ml-[-6px]","data-ord":"left"}),G("cursor-ew-resize","left",""),G("cursor-ew-resize","right","")]}):v.jsx(v.Fragment,{}),S===In.xy?v.jsxs(v.Fragment,{children:[G("cursor-nw-resize","top","left"),G("cursor-ne-resize","top","right"),G("cursor-sw-resize","bottom","left"),G("cursor-se-resize","bottom","right")]}):v.jsx(v.Fragment,{})]}),U=ie=>{P({initX:d,initY:h,initHeight:g,initWidth:m,startResizeX:ie.clientX,startResizeY:ie.clientY,ord:""})},te=()=>v.jsxs("div",{className:Jw("border absolute pointer-events-auto px-2 py-1 rounded-full bg-background","origin-top-left top-0 left-0"),style:{transform:`scale(${1/r*.8})`},onPointerDown:U,children:[m," x ",g]}),L=()=>v.jsx("div",{className:Ce("outline-dashed outline-primary"),style:{height:g,width:m,outlineWidth:`${Wq/r*1.3}px`}});return o===!1||!u?null:v.jsx("div",{className:"absolute h-full w-full pointer-events-none z-[2]",children:v.jsxs("div",{className:"relative pointer-events-none z-[2] [box-shadow:0_0_0_9999px_rgba(0,_0,_0,_0.5)]",style:{height:g,width:m,left:d,top:h},children:[L(),te(),ae()]})})},Kq=200,Yq=10,Gq=200,lu=300;function Xq(e){const{file:t}=e,{toast:n}=Td(),[r,o,i,s,l,u,d,h,m,g,y,x,_,C,S,b,E,k,P,M,A,O]=bt(H=>[H.disableShortCuts,H.windowSize,H.isInpainting,H.imageWidth,H.imageHeight,H.settings,H.serverConfig.enableAutoSaving,H.setImageSize,H.setBaseBrushSize,H.interactiveSegState,H.updateInteractiveSegState,H.handleCanvasMouseDown,H.handleCanvasMouseMove,H.undo,H.redo,H.undoDisabled(),H.redoDisabled(),H.getIsProcessing(),H.updateAppState,H.runMannually(),H.runInpainting,H.isCropperExtenderResizing]),F=bt(H=>H.editorState.baseBrushSize),V=bt(H=>H.getBrushSize()),J=bt(H=>H.editorState.renders),G=bt(H=>H.editorState.extraMasks),ae=bt(H=>H.editorState.temporaryMasks),U=bt(H=>H.editorState.lineGroups),te=bt(H=>H.editorState.curLineGroup),[L,ie]=f.useState(!1),[K,Q]=Rx(t),[W,le]=f.useState(),[ge,Ve]=f.useState(),[{x:Ue,y:We},Me]=f.useState({x:-1,y:-1}),[fe,xe]=f.useState(!1),[$e,Ae]=f.useState(!1),[Oe,je]=f.useState(!1),[Ot,ct]=f.useState(1),[Kt,Er]=f.useState(!1),[gt,js]=f.useState(1),I=o.width/2,X=o.height/2,Z=f.useRef(null),[we,he]=f.useState(!1),[de,ke]=f.useState(!1),[ft,pt]=f.useState(0),_n=f.useCallback(()=>te.length!==0,[te]);f.useEffect(()=>{if(!ge||!Q||s===0||l===0)return;const H=J.length===0?K:J[J.length-1];ge.canvas.width=s,ge.canvas.height=l,ge.clearRect(0,0,ge.canvas.width,ge.canvas.height),ge.drawImage(H,0,0,s,l)},[J,K,Q,ge,l,s]),f.useEffect(()=>{!W||!Q||s===0||l===0||(W.canvas.width=s,W.canvas.height=l,W.clearRect(0,0,W.canvas.width,W.canvas.height),ae.forEach(H=>{W.drawImage(H,0,0,s,l)}),G.forEach(H=>{W.drawImage(H,0,0,s,l)}),g.isInteractiveSeg&&g.tmpInteractiveSegMask&&W.drawImage(g.tmpInteractiveSegMask,0,0,s,l),GR(W,te))},[ae,G,Q,g,W,te,l,s]);const Cr=f.useCallback(async()=>{let H=t;if(J.length>0){const Ge=J[J.length-1];H=await ku(Ge.currentSrc,t.name,t.type)}return H},[t,J]),ki=()=>J.length!==0,_o=f.useCallback(()=>{let H=512,Ge=512;return Q?(J.length===0?(H=K.naturalWidth,Ge=K.naturalHeight):J.length!==0&&(H=J[J.length-1].width,Ge=J[J.length-1].height),[H,Ge]):[H,Ge]},[K,Q,J]);f.useEffect(()=>{var Gd;if(!Q)return;const[H,Ge]=_o();(H!==s||Ge!==l)&&h(H,Ge);const st=o.width/H,Qr=(o.height-Kq)/Ge;let an=1;(st<1||Qr<1)&&(an=Math.min(st,Qr)),js(an),ct(an),console.log(`[on file load] image size: ${H}x${Ge}, scale: ${an}, initialCentered: ${we}`),W!=null&&W.canvas&&(console.log("[on file load] set canvas size"),H!=W.canvas.width&&(W.canvas.width=H),Ge!=W.canvas.height&&(W.canvas.height=Ge)),we||((Gd=Z.current)==null||Gd.centerView(an,1),console.log("[on file load] centerView"),he(!0))},[Z,l,s,K,Q,o,we,_o]),f.useEffect(()=>{var H;console.log("[useEffect] centerView"),(H=Z==null?void 0:Z.current)==null||H.centerView(gt,1)},[l,s,Z,gt]);const Vn=f.useCallback(()=>{if(!gt||!o)return;const H=Z.current;if(!H)return;const Ge=(o.width-s*gt)/2,st=(o.height-l*gt)/2;H.setTransform(Ge,st,gt,200,"easeOutQuad"),H.instance.transformState.scale&&(H.instance.transformState.scale=gt),ct(gt),Er(!1)},[Z,o,l,s,o.height,gt]);f.useEffect(()=>(window.addEventListener("resize",()=>{Vn()}),()=>{window.removeEventListener("resize",()=>{Vn()})}),[o,Vn]),Zn("Escape",()=>{k||(de?ke(!1):Vn())},[de,i,Vn]);const Ri=H=>{const Ge=H.nativeEvent;Me({x:Ge.pageX,y:Ge.pageY})},zs=H=>{k||g.isInteractiveSeg||Oe||de&&te.length!==0&&_(c0(H))},Ti=async H=>{P({isPluginRunning:!0});const Ge=await Cr();try{const st=await gT(!0,jR.InteractiveSeg,Ge,void 0,H),{blob:Qr}=st,an=new Image;an.onload=()=>{y({tmpInteractiveSegMask:an})},an.src=Qr}catch(st){n({variant:"destructive",description:st.message?st.message:st.toString()})}P({isPluginRunning:!1})},$c=H=>{if(!_n())return;if(cC(H)){je(!1);return}g.isInteractiveSeg||Oe||!K.src||!(W!=null&&W.canvas)||i||de&&(M?ke(!1):A())},yg=H=>{if(g.isInteractiveSeg){const Ge=c0(H),st=[...g.clicks];lC(H)?st.push([Ge.x,Ge.y,0,st.length]):st.push([Ge.x,Ge.y,1,st.length]),Ti(st),y({clicks:st})}},wg=H=>{if(!(k||g.isInteractiveSeg||Oe||!Q||!(W!=null&&W.canvas))&&!lC(H)){if(cC(H)){je(!0);return}ke(!0),x(c0(H))}},Kd=H=>{H.preventDefault(),C()};Zn("meta+z,ctrl+z",Kd);const kc=H=>{H.preventDefault(),S()};Zn("shift+ctrl+z,shift+meta+z",kc),o2("Tab",H=>{H==null||H.preventDefault(),H==null||H.stopPropagation(),ki()&&ie(()=>(window.setTimeout(()=>{pt(100)},10),!0))},H=>{H==null||H.preventDefault(),H==null||H.stopPropagation(),ki()&&(window.setTimeout(()=>{pt(0)},10),window.setTimeout(()=>{ie(!1)},lu))});const Rc=f.useCallback(async()=>{if(t===void 0)return;if(d&&J.length>0){try{await Wj(J[J.length-1],t.name,t.type),n({description:"Save image success"})}catch(st){n({variant:"destructive",title:"Uh oh! Something went wrong.",description:st.message?st.message:st.toString()})}return}const H=t.name.replace(/(\.[\w\d_-]+)$/i,"_cleanup$1"),Ge=J[J.length-1];if(yF(Ge.currentSrc,H),u.enableDownloadMask){let st=t.name.replace(/(\.[\w\d_-]+)$/i,"_mask$1");st=st.replace(/\.[^/.]+$/,".jpg");const Qr=Lp(s,l,U),an=document.createElement("a");an.download=st,an.href=Qr.toDataURL("image/jpeg"),an.click()}},[t,d,J,u,l,s,U]);Zn("meta+s,ctrl+s",Rc);const Tc=H=>{H!==fe&&!Oe&&!O&&xe(H)},xg=f.useCallback(()=>{if(k)return"default";if(Oe)return"grab";if(fe)return"none"},[fe,Oe,k]);Zn("[",()=>{let H=F;F>10&&(H=F-10),F<=10&&F>0&&(H=F-5),m(H)},[F]),Zn("]",()=>{m(F+10)},[F]),Zn("shift+r",()=>{M&&_n()&&A()},[M,A,_n]),Zn("ctrl+c,meta+c",async()=>{await hF()&&J.length>0&&W!=null&&W.canvas&&(await vF(W==null?void 0:W.canvas),n({title:"Copy inpainting result to clipboard"}))},[J,W]),o2(" ",H=>{r||(H==null||H.preventDefault(),H==null||H.stopPropagation(),xe(!1),je(!0))},H=>{r||(H==null||H.preventDefault(),H==null||H.stopPropagation(),xe(!0),je(!1))});const Pc=()=>{var Ge,st,Qr,an;let H=gt;return((st=(Ge=Z.current)==null?void 0:Ge.instance)==null?void 0:st.transformState.scale)!==void 0&&(H=(an=(Qr=Z.current)==null?void 0:Qr.instance)==null?void 0:an.transformState.scale),H},Yd=(H,Ge)=>{const st=Pc();return{width:`${V*st}px`,height:`${V*st}px`,left:`${H}px`,top:`${Ge}px`,transform:"translate(-50%, -50%)"}},Ac=H=>v.jsx("div",{className:"absolute rounded-[50%] border-[1px] border-[solid] border-[#ffcc00] pointer-events-none bg-[#ffcc00bb]",style:H}),bg=H=>{m(H),$e||(Ae(!0),window.setTimeout(()=>{Ae(!1)},1e4))},_g=()=>v.jsx("div",{className:"absolute h-[20px] w-[20px] pointer-events-none rounded-[50%] bg-[rgba(21,_215,_121,_0.936)] [box-shadow:0_0_0_0_rgba(21,_215,_121,_0.936)] animate-pulse",style:{left:`${Ue}px`,top:`${We}px`,transform:"translate(-50%, -50%)"},children:v.jsx(uK,{})}),Sg=()=>v.jsx(dq,{ref:H=>{H&&(Z.current=H)},panning:{disabled:!Oe,velocityDisabled:!0},wheel:{step:.05},centerZoomedOut:!0,alignmentAnimation:{disabled:!0},centerOnInit:!0,limitToBounds:!1,doubleClick:{disabled:!0},initialScale:gt,minScale:gt*.3,onPanning:()=>{Kt||Er(!0)},onZoom:H=>{ct(H.state.scale)},children:v.jsxs(hq,{contentStyle:{visibility:we?"visible":"hidden"},children:[v.jsxs("div",{className:"grid [grid-template-areas:'editor-content'] gap-y-4",children:[v.jsx("canvas",{className:"[grid-area:editor-content]",style:{clipPath:`inset(0 ${ft}% 0 0)`,transition:`clip-path ${lu}ms`},ref:H=>{if(H&&!ge){const Ge=H.getContext("2d");Ge&&Ve(Ge)}}}),v.jsx("canvas",{className:Ce("[grid-area:editor-content]",k?"pointer-events-none animate-pulse duration-600":""),style:{cursor:xg(),clipPath:`inset(0 ${ft}% 0 0)`,transition:`clip-path ${lu}ms`},onContextMenu:H=>{H.preventDefault()},onMouseOver:()=>{Tc(!0),Ae(!1)},onFocus:()=>Tc(!0),onMouseLeave:()=>Tc(!1),onMouseDown:wg,onMouseUp:yg,onMouseMove:zs,ref:H=>{if(H&&!W){const Ge=H.getContext("2d");Ge&&le(Ge)}}}),v.jsx("div",{className:"[grid-area:editor-content] pointer-events-none grid [grid-template-areas:'original-image-content']",style:{width:`${s}px`,height:`${l}px`},children:L&&v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"[grid-area:original-image-content] z-10 bg-primary h-full w-[6px] justify-self-end",style:{marginRight:`${ft}%`,transition:`margin-right ${lu}ms`}}),v.jsx("img",{className:"[grid-area:original-image-content]",src:K.src,alt:"original",style:{width:`${s}px`,height:`${l}px`}})]})})]}),v.jsx(jq,{maxHeight:l,maxWidth:s,minHeight:Math.min(512,l),minWidth:Math.min(512,s),scale:Pc(),show:u.showCropper}),v.jsx(Hq,{minHeight:Math.min(512,l),minWidth:Math.min(512,s),scale:Pc(),show:u.showExtender}),g.isInteractiveSeg?v.jsx(Uq,{}):v.jsx(v.Fragment,{})]})});return v.jsxs("div",{className:"flex w-screen h-screen justify-center items-center","aria-hidden":"true",onMouseMove:Ri,onMouseUp:$c,children:[Sg(),fe&&!i&&!Oe&&(g.isInteractiveSeg?_g():Ac(Yd(Ue,We))),$e&&Ac(Yd(I,X)),v.jsxs("div",{className:" overflow-hidden fixed flex bottom-5 border px-4 py-2 rounded-[3rem] gap-8 items-center justify-center backdrop-filter backdrop-blur-md bg-background/70",children:[v.jsx(uo,{className:"w-48",defaultValue:[50],min:Yq,max:Gq,step:1,tabIndex:-1,value:[F],onValueChange:H=>bg(H[0]),onClick:()=>Ae(!1)}),v.jsxs("div",{className:"flex gap-2",children:[v.jsx(vn,{tooltip:"Reset zoom & pan",disabled:Ot===gt&&Kt===!1,onClick:Vn,children:v.jsx(qU,{})}),v.jsx(vn,{tooltip:"Undo",onClick:Kd,disabled:b,children:v.jsx(sV,{})}),v.jsx(vn,{tooltip:"Redo",onClick:kc,disabled:E,children:v.jsx(rV,{})}),v.jsx(vn,{tooltip:"Show original image",onPointerDown:H=>{H.preventDefault(),ie(()=>(window.setTimeout(()=>{pt(100)},10),!0))},onPointerUp:()=>{window.setTimeout(()=>{pt(0)},10),window.setTimeout(()=>{ie(!1)},lu)},disabled:J.length===0,children:v.jsx(QU,{})}),v.jsx(vn,{tooltip:"Save Image",disabled:!J.length,onClick:Rc,children:v.jsx(XU,{})}),u.enableManualInpainting&&u.model.model_type==="inpaint"?v.jsx(vn,{tooltip:"Run Inpainting",disabled:k||!_n()&&G.length===0,onClick:()=>{A()},children:v.jsx(ZU,{})}):v.jsx(v.Fragment,{})]})]})]})}const Zq=()=>{const[e,t]=bt(n=>[n.imageWidth,n.imageHeight]);return!e||!t?null:v.jsxs("div",{className:"border rounded-lg px-2 py-[6px] z-10 bg-background",children:[e,"x",t]})},B1=["Enter"," "],qq=["ArrowDown","PageUp","Home"],V3=["ArrowUp","PageDown","End"],Qq=[...qq,...V3],Jq={ltr:[...B1,"ArrowRight"],rtl:[...B1,"ArrowLeft"]},eQ={ltr:["ArrowLeft"],rtl:["ArrowRight"]},fg="Menu",[ld,tQ,nQ]=zd(fg),[Na,W3]=An(fg,[nQ,Ns,Qm]),pg=Ns(),H3=Qm(),[K3,Fs]=Na(fg),[rQ,Hd]=Na(fg),oQ=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:o,onOpenChange:i,modal:s=!0}=e,l=pg(t),[u,d]=f.useState(null),h=f.useRef(!1),m=Ft(i),g=Sc(o);return f.useEffect(()=>{const y=()=>{h.current=!0,document.addEventListener("pointerdown",x,{capture:!0,once:!0}),document.addEventListener("pointermove",x,{capture:!0,once:!0})},x=()=>h.current=!1;return document.addEventListener("keydown",y,{capture:!0}),()=>{document.removeEventListener("keydown",y,{capture:!0}),document.removeEventListener("pointerdown",x,{capture:!0}),document.removeEventListener("pointermove",x,{capture:!0})}},[]),f.createElement(Od,l,f.createElement(K3,{scope:t,open:n,onOpenChange:m,content:u,onContentChange:d},f.createElement(rQ,{scope:t,onClose:f.useCallback(()=>m(!1),[m]),isUsingKeyboardRef:h,dir:g,modal:s},r)))},Y3=f.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,o=pg(n);return f.createElement(zm,Y({},o,r,{ref:t}))}),G3="MenuPortal",[iQ,X3]=Na(G3,{forceMount:void 0}),sQ=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:o}=e,i=Fs(G3,t);return f.createElement(iQ,{scope:t,forceMount:n},f.createElement(bn,{present:n||i.open},f.createElement(Md,{asChild:!0,container:o},r)))},yo="MenuContent",[aQ,Jx]=Na(yo),lQ=f.forwardRef((e,t)=>{const n=X3(yo,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,i=Fs(yo,e.__scopeMenu),s=Hd(yo,e.__scopeMenu);return f.createElement(ld.Provider,{scope:e.__scopeMenu},f.createElement(bn,{present:r||i.open},f.createElement(ld.Slot,{scope:e.__scopeMenu},s.modal?f.createElement(cQ,Y({},o,{ref:t})):f.createElement(uQ,Y({},o,{ref:t})))))}),cQ=f.forwardRef((e,t)=>{const n=Fs(yo,e.__scopeMenu),r=f.useRef(null),o=Be(t,r);return f.useEffect(()=>{const i=r.current;if(i)return Xm(i)},[]),f.createElement(eb,Y({},e,{ref:o,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:ue(e.onFocusOutside,i=>i.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)}))}),uQ=f.forwardRef((e,t)=>{const n=Fs(yo,e.__scopeMenu);return f.createElement(eb,Y({},e,{ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)}))}),eb=f.forwardRef((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:o,onOpenAutoFocus:i,onCloseAutoFocus:s,disableOutsidePointerEvents:l,onEntryFocus:u,onEscapeKeyDown:d,onPointerDownOutside:h,onFocusOutside:m,onInteractOutside:g,onDismiss:y,disableOutsideScroll:x,..._}=e,C=Fs(yo,n),S=Hd(yo,n),b=pg(n),E=H3(n),k=tQ(n),[P,M]=f.useState(null),A=f.useRef(null),O=Be(t,A,C.onContentChange),F=f.useRef(0),V=f.useRef(""),J=f.useRef(0),G=f.useRef(null),ae=f.useRef("right"),U=f.useRef(0),te=x?Gm:f.Fragment,L=x?{as:Wo,allowPinchZoom:!0}:void 0,ie=Q=>{var W,le;const ge=V.current+Q,Ve=k().filter($e=>!$e.disabled),Ue=document.activeElement,We=(W=Ve.find($e=>$e.ref.current===Ue))===null||W===void 0?void 0:W.textValue,Me=Ve.map($e=>$e.textValue),fe=kQ(Me,ge,We),xe=(le=Ve.find($e=>$e.textValue===fe))===null||le===void 0?void 0:le.ref.current;(function $e(Ae){V.current=Ae,window.clearTimeout(F.current),Ae!==""&&(F.current=window.setTimeout(()=>$e(""),1e3))})(ge),xe&&setTimeout(()=>xe.focus())};f.useEffect(()=>()=>window.clearTimeout(F.current),[]),Km();const K=f.useCallback(Q=>{var W,le;return ae.current===((W=G.current)===null||W===void 0?void 0:W.side)&&TQ(Q,(le=G.current)===null||le===void 0?void 0:le.area)},[]);return f.createElement(aQ,{scope:n,searchRef:V,onItemEnter:f.useCallback(Q=>{K(Q)&&Q.preventDefault()},[K]),onItemLeave:f.useCallback(Q=>{var W;K(Q)||((W=A.current)===null||W===void 0||W.focus(),M(null))},[K]),onTriggerLeave:f.useCallback(Q=>{K(Q)&&Q.preventDefault()},[K]),pointerGraceTimerRef:J,onPointerGraceIntentChange:f.useCallback(Q=>{G.current=Q},[])},f.createElement(te,L,f.createElement(Hm,{asChild:!0,trapped:o,onMountAutoFocus:ue(i,Q=>{var W;Q.preventDefault(),(W=A.current)===null||W===void 0||W.focus()}),onUnmountAutoFocus:s},f.createElement(yc,{asChild:!0,disableOutsidePointerEvents:l,onEscapeKeyDown:d,onPointerDownOutside:h,onFocusOutside:m,onInteractOutside:g,onDismiss:y},f.createElement(ZP,Y({asChild:!0},E,{dir:S.dir,orientation:"vertical",loop:r,currentTabStopId:P,onCurrentTabStopIdChange:M,onEntryFocus:ue(u,Q=>{S.isUsingKeyboardRef.current||Q.preventDefault()})}),f.createElement(Bm,Y({role:"menu","aria-orientation":"vertical","data-state":tA(C.open),"data-radix-menu-content":"",dir:S.dir},b,_,{ref:O,style:{outline:"none",..._.style},onKeyDown:ue(_.onKeyDown,Q=>{const le=Q.target.closest("[data-radix-menu-content]")===Q.currentTarget,ge=Q.ctrlKey||Q.altKey||Q.metaKey,Ve=Q.key.length===1;le&&(Q.key==="Tab"&&Q.preventDefault(),!ge&&Ve&&ie(Q.key));const Ue=A.current;if(Q.target!==Ue||!Qq.includes(Q.key))return;Q.preventDefault();const Me=k().filter(fe=>!fe.disabled).map(fe=>fe.ref.current);V3.includes(Q.key)&&Me.reverse(),CQ(Me)}),onBlur:ue(e.onBlur,Q=>{Q.currentTarget.contains(Q.target)||(window.clearTimeout(F.current),V.current="")}),onPointerMove:ue(e.onPointerMove,cd(Q=>{const W=Q.target,le=U.current!==Q.clientX;if(Q.currentTarget.contains(W)&&le){const ge=Q.clientX>U.current?"right":"left";ae.current=ge,U.current=Q.clientX}}))})))))))}),dQ=f.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return f.createElement(Pe.div,Y({},r,{ref:t}))}),U1="MenuItem",H2="menu.itemSelect",tb=f.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...o}=e,i=f.useRef(null),s=Hd(U1,e.__scopeMenu),l=Jx(U1,e.__scopeMenu),u=Be(t,i),d=f.useRef(!1),h=()=>{const m=i.current;if(!n&&m){const g=new CustomEvent(H2,{bubbles:!0,cancelable:!0});m.addEventListener(H2,y=>r==null?void 0:r(y),{once:!0}),cx(m,g),g.defaultPrevented?d.current=!1:s.onClose()}};return f.createElement(Z3,Y({},o,{ref:u,disabled:n,onClick:ue(e.onClick,h),onPointerDown:m=>{var g;(g=e.onPointerDown)===null||g===void 0||g.call(e,m),d.current=!0},onPointerUp:ue(e.onPointerUp,m=>{var g;d.current||(g=m.currentTarget)===null||g===void 0||g.click()}),onKeyDown:ue(e.onKeyDown,m=>{const g=l.searchRef.current!=="";n||g&&m.key===" "||B1.includes(m.key)&&(m.currentTarget.click(),m.preventDefault())})}))}),Z3=f.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:o,...i}=e,s=Jx(U1,n),l=H3(n),u=f.useRef(null),d=Be(t,u),[h,m]=f.useState(!1),[g,y]=f.useState("");return f.useEffect(()=>{const x=u.current;if(x){var _;y(((_=x.textContent)!==null&&_!==void 0?_:"").trim())}},[i.children]),f.createElement(ld.ItemSlot,{scope:n,disabled:r,textValue:o??g},f.createElement(qP,Y({asChild:!0},l,{focusable:!r}),f.createElement(Pe.div,Y({role:"menuitem","data-highlighted":h?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0},i,{ref:d,onPointerMove:ue(e.onPointerMove,cd(x=>{r?s.onItemLeave(x):(s.onItemEnter(x),x.defaultPrevented||x.currentTarget.focus())})),onPointerLeave:ue(e.onPointerLeave,cd(x=>s.onItemLeave(x))),onFocus:ue(e.onFocus,()=>m(!0)),onBlur:ue(e.onBlur,()=>m(!1))}))))}),fQ=f.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...o}=e;return f.createElement(Q3,{scope:e.__scopeMenu,checked:n},f.createElement(tb,Y({role:"menuitemcheckbox","aria-checked":om(n)?"mixed":n},o,{ref:t,"data-state":nb(n),onSelect:ue(o.onSelect,()=>r==null?void 0:r(om(n)?!0:!n),{checkForDefaultPrevented:!1})})))}),pQ="MenuRadioGroup",[Cte,hQ]=Na(pQ,{value:void 0,onValueChange:()=>{}}),mQ="MenuRadioItem",gQ=f.forwardRef((e,t)=>{const{value:n,...r}=e,o=hQ(mQ,e.__scopeMenu),i=n===o.value;return f.createElement(Q3,{scope:e.__scopeMenu,checked:i},f.createElement(tb,Y({role:"menuitemradio","aria-checked":i},r,{ref:t,"data-state":nb(i),onSelect:ue(r.onSelect,()=>{var s;return(s=o.onValueChange)===null||s===void 0?void 0:s.call(o,n)},{checkForDefaultPrevented:!1})})))}),q3="MenuItemIndicator",[Q3,vQ]=Na(q3,{checked:!1}),yQ=f.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...o}=e,i=vQ(q3,n);return f.createElement(bn,{present:r||om(i.checked)||i.checked===!0},f.createElement(Pe.span,Y({},o,{ref:t,"data-state":nb(i.checked)})))}),wQ=f.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return f.createElement(Pe.div,Y({role:"separator","aria-orientation":"horizontal"},r,{ref:t}))}),J3="MenuSub",[xQ,eA]=Na(J3),bQ=e=>{const{__scopeMenu:t,children:n,open:r=!1,onOpenChange:o}=e,i=Fs(J3,t),s=pg(t),[l,u]=f.useState(null),[d,h]=f.useState(null),m=Ft(o);return f.useEffect(()=>(i.open===!1&&m(!1),()=>m(!1)),[i.open,m]),f.createElement(Od,s,f.createElement(K3,{scope:t,open:r,onOpenChange:m,content:d,onContentChange:h},f.createElement(xQ,{scope:t,contentId:nr(),triggerId:nr(),trigger:l,onTriggerChange:u},n)))},gp="MenuSubTrigger",_Q=f.forwardRef((e,t)=>{const n=Fs(gp,e.__scopeMenu),r=Hd(gp,e.__scopeMenu),o=eA(gp,e.__scopeMenu),i=Jx(gp,e.__scopeMenu),s=f.useRef(null),{pointerGraceTimerRef:l,onPointerGraceIntentChange:u}=i,d={__scopeMenu:e.__scopeMenu},h=f.useCallback(()=>{s.current&&window.clearTimeout(s.current),s.current=null},[]);return f.useEffect(()=>h,[h]),f.useEffect(()=>{const m=l.current;return()=>{window.clearTimeout(m),u(null)}},[l,u]),f.createElement(Y3,Y({asChild:!0},d),f.createElement(Z3,Y({id:o.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":o.contentId,"data-state":tA(n.open)},e,{ref:Am(t,o.onTriggerChange),onClick:m=>{var g;(g=e.onClick)===null||g===void 0||g.call(e,m),!(e.disabled||m.defaultPrevented)&&(m.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:ue(e.onPointerMove,cd(m=>{i.onItemEnter(m),!m.defaultPrevented&&!e.disabled&&!n.open&&!s.current&&(i.onPointerGraceIntentChange(null),s.current=window.setTimeout(()=>{n.onOpenChange(!0),h()},100))})),onPointerLeave:ue(e.onPointerLeave,cd(m=>{var g;h();const y=(g=n.content)===null||g===void 0?void 0:g.getBoundingClientRect();if(y){var x;const _=(x=n.content)===null||x===void 0?void 0:x.dataset.side,C=_==="right",S=C?-5:5,b=y[C?"left":"right"],E=y[C?"right":"left"];i.onPointerGraceIntentChange({area:[{x:m.clientX+S,y:m.clientY},{x:b,y:y.top},{x:E,y:y.top},{x:E,y:y.bottom},{x:b,y:y.bottom}],side:_}),window.clearTimeout(l.current),l.current=window.setTimeout(()=>i.onPointerGraceIntentChange(null),300)}else{if(i.onTriggerLeave(m),m.defaultPrevented)return;i.onPointerGraceIntentChange(null)}})),onKeyDown:ue(e.onKeyDown,m=>{const g=i.searchRef.current!=="";if(!(e.disabled||g&&m.key===" ")&&Jq[r.dir].includes(m.key)){var y;n.onOpenChange(!0),(y=n.content)===null||y===void 0||y.focus(),m.preventDefault()}})})))}),SQ="MenuSubContent",EQ=f.forwardRef((e,t)=>{const n=X3(yo,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,i=Fs(yo,e.__scopeMenu),s=Hd(yo,e.__scopeMenu),l=eA(SQ,e.__scopeMenu),u=f.useRef(null),d=Be(t,u);return f.createElement(ld.Provider,{scope:e.__scopeMenu},f.createElement(bn,{present:r||i.open},f.createElement(ld.Slot,{scope:e.__scopeMenu},f.createElement(eb,Y({id:l.contentId,"aria-labelledby":l.triggerId},o,{ref:d,align:"start",side:s.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:h=>{var m;s.isUsingKeyboardRef.current&&((m=u.current)===null||m===void 0||m.focus()),h.preventDefault()},onCloseAutoFocus:h=>h.preventDefault(),onFocusOutside:ue(e.onFocusOutside,h=>{h.target!==l.trigger&&i.onOpenChange(!1)}),onEscapeKeyDown:ue(e.onEscapeKeyDown,h=>{s.onClose(),h.preventDefault()}),onKeyDown:ue(e.onKeyDown,h=>{const m=h.currentTarget.contains(h.target),g=eQ[s.dir].includes(h.key);if(m&&g){var y;i.onOpenChange(!1),(y=l.trigger)===null||y===void 0||y.focus(),h.preventDefault()}})})))))});function tA(e){return e?"open":"closed"}function om(e){return e==="indeterminate"}function nb(e){return om(e)?"indeterminate":e?"checked":"unchecked"}function CQ(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function $Q(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function kQ(e,t,n){const o=t.length>1&&Array.from(t).every(d=>d===t[0])?t[0]:t,i=n?e.indexOf(n):-1;let s=$Q(e,Math.max(i,0));o.length===1&&(s=s.filter(d=>d!==n));const u=s.find(d=>d.toLowerCase().startsWith(o.toLowerCase()));return u!==n?u:void 0}function RQ(e,t){const{x:n,y:r}=e;let o=!1;for(let i=0,s=t.length-1;ir!=h>r&&n<(d-l)*(r-u)/(h-u)+l&&(o=!o)}return o}function TQ(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return RQ(n,t)}function cd(e){return t=>t.pointerType==="mouse"?e(t):void 0}const PQ=oQ,AQ=Y3,OQ=sQ,MQ=lQ,NQ=dQ,DQ=tb,IQ=fQ,LQ=gQ,FQ=yQ,jQ=wQ,zQ=bQ,BQ=_Q,UQ=EQ,nA="DropdownMenu",[VQ,$te]=An(nA,[W3]),Sr=W3(),[WQ,rA]=VQ(nA),HQ=e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:o,defaultOpen:i,onOpenChange:s,modal:l=!0}=e,u=Sr(t),d=f.useRef(null),[h=!1,m]=Zr({prop:o,defaultProp:i,onChange:s});return f.createElement(WQ,{scope:t,triggerId:nr(),triggerRef:d,contentId:nr(),open:h,onOpenChange:m,onOpenToggle:f.useCallback(()=>m(g=>!g),[m]),modal:l},f.createElement(PQ,Y({},u,{open:h,onOpenChange:m,dir:r,modal:l}),n))},KQ="DropdownMenuTrigger",YQ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...o}=e,i=rA(KQ,n),s=Sr(n);return f.createElement(AQ,Y({asChild:!0},s),f.createElement(Pe.button,Y({type:"button",id:i.triggerId,"aria-haspopup":"menu","aria-expanded":i.open,"aria-controls":i.open?i.contentId:void 0,"data-state":i.open?"open":"closed","data-disabled":r?"":void 0,disabled:r},o,{ref:Am(t,i.triggerRef),onPointerDown:ue(e.onPointerDown,l=>{!r&&l.button===0&&l.ctrlKey===!1&&(i.onOpenToggle(),i.open||l.preventDefault())}),onKeyDown:ue(e.onKeyDown,l=>{r||(["Enter"," "].includes(l.key)&&i.onOpenToggle(),l.key==="ArrowDown"&&i.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(l.key)&&l.preventDefault())})})))}),GQ=e=>{const{__scopeDropdownMenu:t,...n}=e,r=Sr(t);return f.createElement(OQ,Y({},r,n))},XQ="DropdownMenuContent",ZQ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=rA(XQ,n),i=Sr(n),s=f.useRef(!1);return f.createElement(MQ,Y({id:o.contentId,"aria-labelledby":o.triggerId},i,r,{ref:t,onCloseAutoFocus:ue(e.onCloseAutoFocus,l=>{var u;s.current||(u=o.triggerRef.current)===null||u===void 0||u.focus(),s.current=!1,l.preventDefault()}),onInteractOutside:ue(e.onInteractOutside,l=>{const u=l.detail.originalEvent,d=u.button===0&&u.ctrlKey===!0,h=u.button===2||d;(!o.modal||h)&&(s.current=!0)}),style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}}))}),qQ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(NQ,Y({},o,r,{ref:t}))}),QQ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(DQ,Y({},o,r,{ref:t}))}),JQ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(IQ,Y({},o,r,{ref:t}))}),eJ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(LQ,Y({},o,r,{ref:t}))}),tJ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(FQ,Y({},o,r,{ref:t}))}),nJ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(jQ,Y({},o,r,{ref:t}))}),rJ=e=>{const{__scopeDropdownMenu:t,children:n,open:r,onOpenChange:o,defaultOpen:i}=e,s=Sr(t),[l=!1,u]=Zr({prop:r,defaultProp:i,onChange:o});return f.createElement(zQ,Y({},s,{open:l,onOpenChange:u}),n)},oJ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(BQ,Y({},o,r,{ref:t}))}),iJ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(UQ,Y({},o,r,{ref:t,style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}}))}),sJ=HQ,aJ=YQ,lJ=GQ,oA=ZQ,iA=qQ,sA=QQ,aA=JQ,lA=eJ,cA=tJ,uA=nJ,cJ=rJ,dA=oJ,fA=iJ,uJ=sJ,dJ=aJ,K2=cJ,V1=f.forwardRef(({className:e,inset:t,children:n,...r},o)=>v.jsxs(dA,{ref:o,className:Ce("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",e),...r,children:[n,v.jsx(ez,{className:"ml-auto h-4 w-4"})]}));V1.displayName=dA.displayName;const W1=f.forwardRef(({className:e,...t},n)=>v.jsx(fA,{ref:n,className:Ce("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...t}));W1.displayName=fA.displayName;const pA=f.forwardRef(({className:e,sideOffset:t=4,...n},r)=>v.jsx(lJ,{children:v.jsx(oA,{ref:r,sideOffset:t,className:Ce("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md","data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),onCloseAutoFocus:o=>o.preventDefault(),...n})}));pA.displayName=oA.displayName;const il=f.forwardRef(({className:e,inset:t,...n},r)=>v.jsx(sA,{ref:r,className:Ce("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",e),...n}));il.displayName=sA.displayName;const fJ=f.forwardRef(({className:e,children:t,checked:n,...r},o)=>v.jsxs(aA,{ref:o,className:Ce("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),checked:n,...r,children:[v.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:v.jsx(cA,{children:v.jsx(vT,{className:"h-4 w-4"})})}),t]}));fJ.displayName=aA.displayName;const pJ=f.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(lA,{ref:r,className:Ce("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[v.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:v.jsx(cA,{children:v.jsx(iz,{className:"h-4 w-4 fill-current"})})}),t]}));pJ.displayName=lA.displayName;const hJ=f.forwardRef(({className:e,inset:t,...n},r)=>v.jsx(iA,{ref:r,className:Ce("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",e),...n}));hJ.displayName=iA.displayName;const mJ=f.forwardRef(({className:e,...t},n)=>v.jsx(uA,{ref:n,className:Ce("-mx-1 my-1 h-px bg-muted",e),...t}));mJ.displayName=uA.displayName;const Y2={RemoveBG:{IconClass:VC,showName:"RemoveBG"},AnimeSeg:{IconClass:VC,showName:"Anime Segmentation"},RealESRGAN:{IconClass:XT,showName:"RealESRGAN"},GFPGAN:{IconClass:WC,showName:"GFPGAN"},RestoreFormer:{IconClass:WC,showName:"RestoreFormer"},InteractiveSeg:{IconClass:nV,showName:"Interactive Segmentation"}},gJ=()=>{const[e,t,n,r]=bt(d=>[d.file,d.serverConfig.plugins,d.updateInteractiveSegState,d.runRenderablePlugin]),o=!e;if(t.length===0)return null;const i=(d,h)=>{h==="InteractiveSeg"?n({isInteractiveSeg:!0}):r(d,h)},s=()=>v.jsxs(K2,{children:[v.jsx(V1,{disabled:o,children:v.jsxs("div",{className:"flex gap-2 items-center",children:[v.jsx(XT,{}),"RealESRGAN"]})}),v.jsxs(W1,{children:[v.jsx(il,{onClick:()=>r(!1,"RealESRGAN",{upscale:2}),children:"upscale 2x"}),v.jsx(il,{onClick:()=>r(!1,"RealESRGAN",{upscale:4}),children:"upscale 4x"})]})]},"RealESRGAN"),l=d=>{const{IconClass:h,showName:m}=Y2[d.name];return v.jsxs(K2,{children:[v.jsx(V1,{disabled:o,children:v.jsxs("div",{className:"flex gap-2 items-center",children:[v.jsx(h,{className:"p-1"}),m]})}),v.jsxs(W1,{children:[v.jsx(il,{onClick:()=>i(!1,d.name),children:"Remove Background"}),v.jsx(il,{onClick:()=>i(!0,d.name),children:"Generate Mask"})]})]},d.name)},u=()=>t.map(d=>{const{IconClass:h,showName:m}=Y2[d.name];return d.name==="RealESRGAN"?s():d.name==="RemoveBG"||d.name==="AnimeSeg"?l(d):v.jsx(il,{onClick:()=>i(!1,d.name),disabled:o,children:v.jsxs("div",{className:"flex gap-2 items-center",children:[v.jsx(h,{className:"p-1"}),m]})},d.name)});return v.jsxs(uJ,{modal:!1,children:[v.jsx(dJ,{className:"border rounded-lg z-10 bg-background outline-none",tabIndex:-1,children:v.jsx(yn,{variant:"ghost",size:"icon",asChild:!0,className:"p-1.5",children:v.jsx(HU,{strokeWidth:1})})}),v.jsx(pA,{side:"bottom",align:"start",children:u()})]})},vJ=Sx,yJ=gP,wJ=Ex,hA=f.forwardRef(({className:e,...t},n)=>v.jsx(Nd,{className:Ce("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t,ref:n}));hA.displayName=Nd.displayName;const xJ=Om("fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=closed]:duration-200 data-[state=open]:duration-300",{variants:{side:{top:"inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",bottom:"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",left:"inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",right:"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm"}},defaultVariants:{side:"right"}}),mA=f.forwardRef(({side:e="right",className:t,children:n,...r},o)=>v.jsxs(wJ,{children:[v.jsx(hA,{}),v.jsx(Dd,{ref:o,className:Ce(xJ({side:e}),t),...r,children:n})]}));mA.displayName=Dd.displayName;const gA=({className:e,...t})=>v.jsx("div",{className:Ce("flex flex-col space-y-2 text-center sm:text-left",e),...t});gA.displayName="SheetHeader";const bJ=f.forwardRef(({className:e,...t},n)=>v.jsx(Id,{ref:n,className:Ce("text-lg font-semibold text-foreground",e),...t}));bJ.displayName=Id.displayName;const _J=f.forwardRef(({className:e,...t},n)=>v.jsx(Ld,{ref:n,className:Ce("text-sm text-muted-foreground",e),...t}));_J.displayName=Ld.displayName;const Ut=({children:e})=>v.jsx("div",{className:"flex justify-between items-center pr-2",children:e}),Pt=({text:e,toolTip:t="",url:n,htmlFor:r,disabled:o=!1})=>v.jsxs(YT,{children:[v.jsx(GT,{asChild:!0,children:v.jsx(Gx,{htmlFor:r||e.toLowerCase().replace(" ","-"),className:"font-medium",disabled:o,children:e})}),t||n?v.jsxs(xx,{className:"flex flex-col max-w-xs text-sm",side:"left",children:[v.jsx("p",{children:t}),n?v.jsx(yn,{variant:"link",className:"justify-end",children:v.jsx("a",{href:n,target:"_blank",children:"More info"})}):v.jsx(v.Fragment,{})]}):v.jsx(v.Fragment,{})]}),SJ=()=>{const[e,t]=bt(n=>[n.settings,n.updateSettings]);return v.jsxs("div",{className:"flex flex-col gap-4 mt-4",children:[v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{htmlFor:"steps",text:"Steps",toolTip:"The number of denoising steps. More denoising steps usually lead to a higher quality image at the expense of slower inference."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[30],min:1,max:100,step:1,value:[Math.floor(e.ldmSteps)],onValueChange:n=>t({ldmSteps:n[0]})}),v.jsx(Gn,{id:"steps",className:"w-[60px] rounded-full",numberValue:e.ldmSteps,allowFloat:!1,onNumberValueChange:n=>{t({ldmSteps:n})}})]})]}),v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Sampler"}),v.jsxs(aa,{value:e.ldmSampler,onValueChange:n=>{t({ldmSampler:n})},children:[v.jsx(ls,{className:"w-[100px]",children:v.jsx(la,{placeholder:"Select sampler"})}),v.jsx(cs,{align:"end",children:v.jsx(wl,{children:Object.values(Zw).map(n=>v.jsx(us,{value:n,children:n},n))})})]})]})]})},vA=f.forwardRef(({className:e,...t},n)=>v.jsx("textarea",{className:Ce("flex min-h-[60px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",e,"overflow-auto"),tabIndex:-1,ref:n,...t}));vA.displayName="Textarea";const vp=({text:e,onClick:t})=>{const[n]=bt(r=>[r.settings.showExtender]);return v.jsx(yn,{variant:"outline",className:"p-1 h-8",disabled:!n,onClick:t,children:v.jsx("div",{className:"flex items-center gap-1",children:e})})},EJ=()=>{const[e,t,n,r,o,i,s,l,u,d,h]=bt(L=>[L.serverConfig.samplers,L.settings,L.paintByExampleFile,L.getIsProcessing(),L.updateSettings,L.runInpainting,L.updateAppState,L.updateExtenderByBuiltIn,L.updateExtenderDirection,L.adjustMask,L.clearMask]),[m,g]=Rx(n),y=f.useRef(null);OP(y,()=>{y!=null&&y.current&&y.current.blur()});const x=L=>{L.key==="Enter"&&L.ctrlKey&&t.prompt.length!==0&&i()},_=()=>v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Cropper",toolTip:"Inpainting on part of image, improve inference speed and reduce memory usage."}),v.jsx(co,{id:"cropper",checked:t.showCropper,onCheckedChange:L=>{o({showCropper:L}),L&&o({showExtender:!1})}})]}),C=()=>t.model.support_controlnet?v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex justify-between items-center pr-2",children:[v.jsx(Pt,{text:"ControlNet",toolTip:"Using an additional conditioning image to control how an image is generated",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#controlnet"}),v.jsx(co,{id:"controlnet",checked:t.enableControlnet,onCheckedChange:L=>{o({enableControlnet:L})}})]}),v.jsx("div",{className:"flex flex-col gap-1",children:v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[100],min:1,max:100,step:1,disabled:!t.enableControlnet,value:[Math.floor(t.controlnetConditioningScale*100)],onValueChange:L=>o({controlnetConditioningScale:L[0]/100})}),v.jsx(Gn,{id:"controlnet-weight",className:"w-[60px] rounded-full",disabled:!t.enableControlnet,numberValue:t.controlnetConditioningScale,allowFloat:!1,onNumberValueChange:L=>{o({controlnetConditioningScale:L})}})]})}),v.jsx("div",{className:"pr-2",children:v.jsxs(aa,{defaultValue:t.controlnetMethod,value:t.controlnetMethod,onValueChange:L=>{o({controlnetMethod:L})},disabled:!t.enableControlnet,children:[v.jsx(ls,{children:v.jsx(la,{placeholder:"Select control method"})}),v.jsx(cs,{align:"end",children:v.jsx(wl,{children:Object.values(t.model.controlnets).map(L=>v.jsx(us,{value:L,children:L.split("/")[1]},L))})})]})})]}),v.jsx(Fn,{})]}):null,S=()=>t.model.support_lcm_lora?v.jsxs(v.Fragment,{children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"LCM LoRA",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inference_with_lcm_lora",toolTip:"Enable quality image generation in typically 2-4 steps. Suggest disabling guidance_scale by setting it to 0. You can also try values between 1.0 and 2.0. When LCM Lora is enabled, LCMSampler will be used automatically."}),v.jsx(co,{id:"lcm-lora",checked:t.enableLCMLora,onCheckedChange:L=>{o({enableLCMLora:L})}})]}),v.jsx(Fn,{})]}):null,b=()=>t.model.support_freeu?v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex justify-between items-center pr-2",children:[v.jsx(Pt,{text:"FreeU",toolTip:"FreeU is a technique for improving image quality. Different models may require different FreeU-specific hyperparameters, which can be viewed in the more info section.",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/freeu"}),v.jsx(co,{id:"freeu",checked:t.enableFreeu,onCheckedChange:L=>{o({enableFreeu:L})}})]}),v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex justify-center gap-6",children:[v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-s1",text:"s1",disabled:!t.enableFreeu}),v.jsx(Gn,{id:"freeu-s1",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.s1,allowFloat:!0,onNumberValueChange:L=>{o({freeuConfig:{...t.freeuConfig,s1:L}})}})]}),v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-s2",text:"s2",disabled:!t.enableFreeu}),v.jsx(Gn,{id:"freeu-s2",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.s2,allowFloat:!0,onNumberValueChange:L=>{o({freeuConfig:{...t.freeuConfig,s2:L}})}})]})]}),v.jsxs("div",{className:"flex justify-center gap-6",children:[v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-b1",text:"b1",disabled:!t.enableFreeu}),v.jsx(Gn,{id:"freeu-b1",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.b1,allowFloat:!0,onNumberValueChange:L=>{o({freeuConfig:{...t.freeuConfig,b1:L}})}})]}),v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-b2",text:"b2",disabled:!t.enableFreeu}),v.jsx(Gn,{id:"freeu-b2",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.b2,allowFloat:!0,onNumberValueChange:L=>{o({freeuConfig:{...t.freeuConfig,b2:L}})}})]})]})]}),v.jsx(Fn,{})]}):null,E=()=>t.model.need_prompt?v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsx(Pt,{text:"Negative prompt",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#negative-prompt",toolTip:"Negative prompt guides the model away from generating certain things in an image"}),v.jsx("div",{className:"pl-2 pr-4",children:v.jsx(vA,{ref:y,rows:4,onKeyUp:x,className:"max-h-[8rem] overflow-y-auto mb-2",placeholder:"",id:"negative-prompt",value:t.negativePrompt,onInput:L=>{L.preventDefault(),L.stopPropagation();const ie=L.target;o({negativePrompt:ie.value})}})})]}):null,k=()=>t.model.name!==YR?null:v.jsxs("div",{children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Example Image",toolTip:"An example image to guide image generation."}),v.jsx(c1,{tooltip:"Upload example image",onFileUpload:L=>{s({paintByExampleFile:L})},children:v.jsx(ZT,{})})]}),g?v.jsx("div",{className:"flex justify-center items-center",children:v.jsx("img",{src:m.src,alt:"example",className:"max-w-[200px] max-h-[200px] m-3"})}):v.jsx(v.Fragment,{}),v.jsx(yn,{variant:"default",className:"w-full",disabled:r||!g,onClick:()=>{i()},children:"Paint"})]}),P=()=>t.model.name!==aF?null:v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Image guidance scale",toolTip:"Push the generated image towards the inital image. Higher image guidance scale encourages generated images that are closely linked to the source image, usually at the expense of lower image quality.",url:"https://huggingface.co/docs/diffusers/main/en/api/pipelines/pix2pix"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[150],min:100,max:1e3,step:1,value:[Math.floor(t.p2pImageGuidanceScale*100)],onValueChange:L=>o({p2pImageGuidanceScale:L[0]/100})}),v.jsx(Gn,{id:"image-guidance-scale",className:"w-[60px] rounded-full",numberValue:t.p2pImageGuidanceScale,allowFloat:!0,onNumberValueChange:L=>{o({p2pImageGuidanceScale:L})}})]})]}),M=()=>t.model.support_strength?v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Strength",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#strength",toolTip:"Strength is a measure of how much noise is added to the base image, which influences how similar the output is to the base image. Higher value means more noise and more different from the base image"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[100],min:10,max:100,step:1,value:[Math.floor(t.sdStrength*100)],onValueChange:L=>o({sdStrength:L[0]/100})}),v.jsx(Gn,{id:"strength",className:"w-[60px] rounded-full",numberValue:t.sdStrength,allowFloat:!0,onNumberValueChange:L=>{o({sdStrength:L})}})]})]}):null,A=()=>t.model.support_outpainting?v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Extender",toolTip:"Perform outpainting on images to expand it's content."}),v.jsx(co,{id:"extender",checked:t.showExtender,onCheckedChange:L=>{o({showExtender:L}),L&&o({showCropper:!1})}})]}),v.jsxs(Ut,{children:[v.jsxs(aa,{defaultValue:t.extenderDirection,value:t.extenderDirection,onValueChange:L=>{u(L)},children:[v.jsx(ls,{className:"w-[65px] h-7",disabled:!t.showExtender,children:v.jsx(la,{placeholder:"Select axis"})}),v.jsx(cs,{align:"end",children:v.jsx(wl,{children:Object.values(In).map(L=>v.jsx(us,{value:L,children:L},L))})})]}),v.jsxs("div",{className:"flex gap-1 justify-center mt-0",children:[v.jsx(vp,{text:"1.25x",onClick:()=>l(t.extenderDirection,1.25)}),v.jsx(vp,{text:"1.5x",onClick:()=>l(t.extenderDirection,1.5)}),v.jsx(vp,{text:"1.75x",onClick:()=>l(t.extenderDirection,1.75)}),v.jsx(vp,{text:"2.0x",onClick:()=>l(t.extenderDirection,2)})]})]})]}),v.jsx(Fn,{})]}):null,O=()=>t.model.name!==lF?null:v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Task",toolTip:"PowerPaint task. When using extender, image-outpainting task will be auto used. For object-removal and image-outpainting, it is recommended to set the guidance_scale at 10 or above."}),v.jsxs(aa,{defaultValue:t.powerpaintTask,value:t.powerpaintTask,onValueChange:L=>{o({powerpaintTask:L})},disabled:t.showExtender,children:[v.jsx(ls,{className:"w-[140px]",children:v.jsx(la,{placeholder:"Select task"})}),v.jsx(cs,{align:"end",children:v.jsx(wl,{children:[kl.text_guided,kl.object_remove,kl.shape_guided].map(L=>v.jsx(us,{value:L,children:L},L))})})]})]}),F=()=>v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{htmlFor:"steps",text:"Steps",toolTip:"The number of denoising steps. More denoising steps usually lead to a higher quality image at the expense of slower inference."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[30],min:1,max:100,step:1,value:[Math.floor(t.sdSteps)],onValueChange:L=>o({sdSteps:L[0]})}),v.jsx(Gn,{id:"steps",className:"w-[60px] rounded-full",numberValue:t.sdSteps,allowFloat:!1,onNumberValueChange:L=>{o({sdSteps:L})}})]})]}),V=()=>v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Guidance scale",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#guidance-scale",toolTip:"Guidance scale affects how aligned the text prompt and generated image are. Higher value means the prompt and generated image are closely aligned, so the output is a stricter interpretation of the prompt"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[750],min:0,max:1500,step:1,value:[Math.floor(t.sdGuidanceScale*100)],onValueChange:L=>o({sdGuidanceScale:L[0]/100})}),v.jsx(Gn,{id:"guidance-scale",className:"w-[60px] rounded-full",numberValue:t.sdGuidanceScale,allowFloat:!0,onNumberValueChange:L=>{o({sdGuidanceScale:L})}})]})]}),J=()=>t.model.name===cF?null:v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Sampler"}),v.jsxs(aa,{defaultValue:t.sdSampler,value:t.sdSampler,onValueChange:L=>{o({sdSampler:L})},children:[v.jsx(ls,{className:"w-[175px] text-xs",children:v.jsx(la,{placeholder:"Select sampler"})}),v.jsx(cs,{align:"end",children:v.jsx(wl,{children:e.map(L=>v.jsx(us,{value:L,className:"text-xs",children:L},L))})})]})]}),G=()=>v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Seed",toolTip:"Using same parameters and a fixed seed can generate same result image."}),v.jsxs("div",{className:"flex gap-2 justify-center items-center",children:[v.jsx(co,{id:"seed",checked:t.seedFixed,onCheckedChange:L=>{o({seedFixed:L})}}),v.jsx(Gn,{id:"seed",className:"w-[100px]",disabled:!t.seedFixed,numberValue:t.seed,allowFloat:!1,onNumberValueChange:L=>{o({seed:L})}})]})]}),ae=()=>v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Mask blur",toolTip:"How much to blur the mask before processing, in pixels. Make the generated inpainting boundaries appear more natural."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[t.sdMaskBlur],min:0,max:96,step:1,value:[Math.floor(t.sdMaskBlur)],onValueChange:L=>o({sdMaskBlur:L[0]})}),v.jsx(Gn,{id:"mask-blur",className:"w-[60px] rounded-full",numberValue:t.sdMaskBlur,allowFloat:!1,onNumberValueChange:L=>{o({sdMaskBlur:L})}})]})]}),U=()=>v.jsxs(v.Fragment,{children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Match histograms",toolTip:"Match the inpainting result histogram to the source image histogram",url:"https://github.com/Sanster/lama-cleaner/pull/143#issuecomment-1325859307"}),v.jsx(co,{id:"match-histograms",checked:t.sdMatchHistograms,onCheckedChange:L=>{o({sdMatchHistograms:L})}})]}),v.jsx(Fn,{})]}),te=()=>v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{htmlFor:"adjustMaskKernelSize",text:"Adjust Mask",toolTip:"Expand or shrink mask. Using the slider to adjust the kernel size for dilation or erosion."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[12],min:1,max:100,step:1,value:[Math.floor(t.adjustMaskKernelSize)],onValueChange:L=>o({adjustMaskKernelSize:L[0]})}),v.jsx(Gn,{id:"adjustMaskKernelSize",className:"w-[60px] rounded-full",numberValue:t.adjustMaskKernelSize,allowFloat:!1,onNumberValueChange:L=>{o({adjustMaskKernelSize:L})}})]}),v.jsxs(Ut,{children:[v.jsxs("div",{className:"flex gap-1 justify-start",children:[v.jsx(yn,{variant:"outline",className:"p-1 h-8",onClick:()=>d("expand"),disabled:r,children:v.jsx("div",{className:"flex items-center gap-1 select-none",children:"expand"})}),v.jsx(yn,{variant:"outline",className:"p-1 h-8",onClick:()=>d("shrink"),disabled:r,children:v.jsx("div",{className:"flex items-center gap-1 select-none",children:"Shrink"})}),v.jsx(yn,{variant:"outline",className:"p-1 h-8",onClick:()=>d("reverse"),disabled:r,children:v.jsx("div",{className:"flex items-center gap-1 select-none",children:"Reverse"})})]}),v.jsx(yn,{variant:"outline",className:"p-1 h-8 justify-self-end",onClick:h,disabled:r,children:v.jsx("div",{className:"flex items-center gap-1 select-none",children:"Clear"})})]})]}),v.jsx(Fn,{})]});return v.jsxs("div",{className:"flex flex-col gap-4 mt-4",children:[_(),A(),te(),O(),F(),V(),P(),M(),J(),G(),E(),v.jsx(Fn,{}),C(),S(),ae(),U(),b(),k()]})},CJ=()=>{const[e,t]=bt(n=>[n.settings,n.updateSettings]);return v.jsxs("div",{className:"flex flex-col gap-4 mt-4",children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"CV2 Flag",url:"https://docs.opencv.org/4.8.0/d7/d8b/group__photo__inpaint.html#gga8002a65f5a3328fbf15df81b842d3c3ca892824c38e258feb5e72f308a358d52e"}),v.jsxs(aa,{value:e.cv2Flag,onValueChange:n=>{t({cv2Flag:n})},children:[v.jsx(ls,{className:"w-[160px]",children:v.jsx(la,{placeholder:"Select flag"})}),v.jsx(cs,{align:"end",children:v.jsx(wl,{children:Object.values(qw).map(n=>v.jsx(us,{value:n,children:n},n))})})]})]}),v.jsx(Pt,{text:"CV2 Radius",url:"https://docs.opencv.org/4.8.0/d7/d8b/group__photo__inpaint.html#gga8002a65f5a3328fbf15df81b842d3c3ca892824c38e258feb5e72f308a358d52e"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[5],min:1,max:100,step:1,value:[Math.floor(e.cv2Radius)],onValueChange:n=>t({cv2Radius:n[0]})}),v.jsx(Gn,{id:"cv2-radius",className:"w-[60px] rounded-full",numberValue:e.cv2Radius,allowFloat:!1,onNumberValueChange:n=>{t({cv2Radius:n})}})]})]})},$J=()=>{const[e,t]=bt(i=>[i.settings,i.windowSize]),[n,r]=AP(!0);if(Zn("c",()=>{r()}),e.model.name!==oC&&e.model.name!==iC&&e.model.model_type===is)return null;const o=()=>e.model.name===oC?v.jsx(SJ,{}):e.model.name===iC?v.jsx(CJ,{}):v.jsx(EJ,{});return v.jsxs(vJ,{open:n,modal:!1,children:[v.jsx(yJ,{tabIndex:-1,className:"z-10 outline-none absolute top-[68px] right-6 rounded-lg border bg-background",children:v.jsx(yn,{variant:"ghost",size:"icon",asChild:!0,className:"p-1.5",onClick:r,children:v.jsx(KU,{strokeWidth:1})})}),v.jsxs(mA,{side:"right",className:"w-[300px] mt-[60px] outline-none pl-4 pr-1",onOpenAutoFocus:i=>i.preventDefault(),onPointerDownOutside:i=>i.preventDefault(),children:[v.jsxs(gA,{children:[v.jsxs(Ut,{children:[v.jsx("div",{className:"overflow-hidden mr-8",children:e.model.name.split("/")[e.model.name.split("/").length-1]}),v.jsx(yn,{variant:"ghost",size:"icon",className:"border h-6 w-6",onClick:r,children:v.jsx(YU,{strokeWidth:1})})]}),v.jsx(Fn,{})]}),v.jsx(og,{style:{height:t.height-160},className:"pr-3",children:o()})]})]})},Yo=Object.create(null);Yo.open="0";Yo.close="1";Yo.ping="2";Yo.pong="3";Yo.message="4";Yo.upgrade="5";Yo.noop="6";const th=Object.create(null);Object.keys(Yo).forEach(e=>{th[Yo[e]]=e});const H1={type:"error",data:"parser error"},yA=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",wA=typeof ArrayBuffer=="function",xA=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,rb=({type:e,data:t},n,r)=>yA&&t instanceof Blob?n?r(t):G2(t,r):wA&&(t instanceof ArrayBuffer||xA(t))?n?r(t):G2(new Blob([t]),r):r(Yo[e]+(t||"")),G2=(e,t)=>{const n=new FileReader;return n.onload=function(){const r=n.result.split(",")[1];t("b"+(r||""))},n.readAsDataURL(e)};function X2(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let L0;function kJ(e,t){if(yA&&e.data instanceof Blob)return e.data.arrayBuffer().then(X2).then(t);if(wA&&(e.data instanceof ArrayBuffer||xA(e.data)))return t(X2(e.data));rb(e,!1,n=>{L0||(L0=new TextEncoder),t(L0.encode(n))})}const Z2="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",gu=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let e=0;e{let t=e.length*.75,n=e.length,r,o=0,i,s,l,u;e[e.length-1]==="="&&(t--,e[e.length-2]==="="&&t--);const d=new ArrayBuffer(t),h=new Uint8Array(d);for(r=0;r>4,h[o++]=(s&15)<<4|l>>2,h[o++]=(l&3)<<6|u&63;return d},TJ=typeof ArrayBuffer=="function",ob=(e,t)=>{if(typeof e!="string")return{type:"message",data:bA(e,t)};const n=e.charAt(0);return n==="b"?{type:"message",data:PJ(e.substring(1),t)}:th[n]?e.length>1?{type:th[n],data:e.substring(1)}:{type:th[n]}:H1},PJ=(e,t)=>{if(TJ){const n=RJ(e);return bA(n,t)}else return{base64:!0,data:e}},bA=(e,t)=>{switch(t){case"blob":return e instanceof Blob?e:new Blob([e]);case"arraybuffer":default:return e instanceof ArrayBuffer?e:e.buffer}},_A="",AJ=(e,t)=>{const n=e.length,r=new Array(n);let o=0;e.forEach((i,s)=>{rb(i,!1,l=>{r[s]=l,++o===n&&t(r.join(_A))})})},OJ=(e,t)=>{const n=e.split(_A),r=[];for(let o=0;o{const r=n.length;let o;if(r<126)o=new Uint8Array(1),new DataView(o.buffer).setUint8(0,r);else if(r<65536){o=new Uint8Array(3);const i=new DataView(o.buffer);i.setUint8(0,126),i.setUint16(1,r)}else{o=new Uint8Array(9);const i=new DataView(o.buffer);i.setUint8(0,127),i.setBigUint64(1,BigInt(r))}e.data&&typeof e.data!="string"&&(o[0]|=128),t.enqueue(o),t.enqueue(n)})}})}let F0;function yp(e){return e.reduce((t,n)=>t+n.length,0)}function wp(e,t){if(e[0].length===t)return e.shift();const n=new Uint8Array(t);let r=0;for(let o=0;oMath.pow(2,21)-1){l.enqueue(H1);break}o=h*Math.pow(2,32)+d.getUint32(4),r=3}else{if(yp(n)e){l.enqueue(H1);break}}}})}const SA=4;function qt(e){if(e)return DJ(e)}function DJ(e){for(var t in qt.prototype)e[t]=qt.prototype[t];return e}qt.prototype.on=qt.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this};qt.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this};qt.prototype.off=qt.prototype.removeListener=qt.prototype.removeAllListeners=qt.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,o=0;o(e.hasOwnProperty(r)&&(n[r]=e[r]),n),{})}const IJ=Br.setTimeout,LJ=Br.clearTimeout;function hg(e,t){t.useNativeTimers?(e.setTimeoutFn=IJ.bind(Br),e.clearTimeoutFn=LJ.bind(Br)):(e.setTimeoutFn=Br.setTimeout.bind(Br),e.clearTimeoutFn=Br.clearTimeout.bind(Br))}const FJ=1.33;function jJ(e){return typeof e=="string"?zJ(e):Math.ceil((e.byteLength||e.size)*FJ)}function zJ(e){let t=0,n=0;for(let r=0,o=e.length;r=57344?n+=3:(r++,n+=4);return n}function BJ(e){let t="";for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+="&"),t+=encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t}function UJ(e){let t={},n=e.split("&");for(let r=0,o=n.length;r0);return t}function $A(){const e=J2(+new Date);return e!==Q2?(q2=0,Q2=e):e+"."+J2(q2++)}for(;xp{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)};OJ(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,AJ(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]=$A()),!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 Vo(this.uri(),t)}doWrite(t,n){const r=this.request({method:"POST",data:t});r.on("success",n),r.on("error",(o,i)=>{this.onError("xhr post error",o,i)})}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}}class Vo extends qt{constructor(t,n){super(),hg(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=EA(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");n.xdomain=!!this.opts.xd;const r=this.xhr=new RA(n);try{r.open(this.method,this.uri,!0);try{if(this.opts.extraHeaders){r.setDisableHeaderCheck&&r.setDisableHeaderCheck(!0);for(let o in this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(o)&&r.setRequestHeader(o,this.opts.extraHeaders[o])}}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 o;r.readyState===3&&((o=this.opts.cookieJar)===null||o===void 0||o.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(o){this.setTimeoutFn(()=>{this.onError(o)},0);return}typeof document<"u"&&(this.index=Vo.requestsCount++,Vo.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=KJ,t)try{this.xhr.abort()}catch{}typeof document<"u"&&delete Vo.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()}}Vo.requestsCount=0;Vo.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",e$);else if(typeof addEventListener=="function"){const e="onpagehide"in Br?"pagehide":"unload";addEventListener(e,e$,!1)}}function e$(){for(let e in Vo.requests)Vo.requests.hasOwnProperty(e)&&Vo.requests[e].abort()}const sb=typeof Promise=="function"&&typeof Promise.resolve=="function"?t=>Promise.resolve().then(t):(t,n)=>n(t,0),bp=Br.WebSocket||Br.MozWebSocket,t$=!0,XJ="arraybuffer",n$=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class ZJ extends ib{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=n$?{}:EA(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=t$&&!n$?n?new bp(t,n):new bp(t):new bp(t,n,r)}catch(o){return this.emitReserved("error",o)}this.ws.binaryType=this.socket.binaryType,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{t$&&this.ws.send(i)}catch{}o&&sb(()=>{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]=$A()),this.supportsBinary||(n.b64=1),this.createUri(t,n)}check(){return!!bp}}class qJ extends ib{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=NJ(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=t.readable.pipeThrough(n).getReader(),o=MJ();o.readable.pipeTo(t.writable),this.writer=o.writable.getWriter();const i=()=>{r.read().then(({done:l,value:u})=>{l||(this.onPacket(u),i())}).catch(l=>{})};i();const s={type:"open"};this.query.sid&&(s.data=`{"sid":"${this.query.sid}"}`),this.writer.write(s).then(()=>this.onOpen())})}))}write(t){this.writable=!1;for(let n=0;n{o&&sb(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;(t=this.transport)===null||t===void 0||t.close()}}const QJ={websocket:ZJ,webtransport:qJ,polling:GJ},JJ=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,eee=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Y1(e){if(e.length>2e3)throw"URI too long";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 o=JJ.exec(e||""),i={},s=14;for(;s--;)i[eee[s]]=o[s]||"";return n!=-1&&r!=-1&&(i.source=t,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=tee(i,i.path),i.queryKey=nee(i,i.query),i}function tee(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 nee(e,t){const n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(r,o,i){o&&(n[o]=i)}),n}let TA=class sl extends qt{constructor(t,n={}){super(),this.binaryType=XJ,this.writeBuffer=[],t&&typeof t=="object"&&(n=t,t=null),t?(t=Y1(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=Y1(n.host).host),hg(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=UJ(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=SA,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 QJ[t](r)}open(){let t;if(this.opts.rememberUpgrade&&sl.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;sl.priorWebsocketSuccess=!1;const o=()=>{r||(n.send([{type:"ping",data:"probe"}]),n.once("packet",m=>{if(!r)if(m.type==="pong"&&m.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",n),!n)return;sl.priorWebsocketSuccess=n.name==="websocket",this.transport.pause(()=>{r||this.readyState!=="closed"&&(h(),this.setTransport(n),n.send([{type:"upgrade"}]),this.emitReserved("upgrade",n),n=null,this.upgrading=!1,this.flush())})}else{const g=new Error("probe error");g.transport=n.name,this.emitReserved("upgradeError",g)}}))};function i(){r||(r=!0,h(),n.close(),n=null)}const s=m=>{const g=new Error("probe error: "+m);g.transport=n.name,i(),this.emitReserved("upgradeError",g)};function l(){s("transport closed")}function u(){s("socket closed")}function d(m){n&&m.name!==n.name&&i()}const h=()=>{n.removeListener("open",o),n.removeListener("error",s),n.removeListener("close",l),this.off("close",u),this.off("upgrading",d)};n.once("open",o),n.once("error",s),n.once("close",l),this.once("close",u),this.once("upgrading",d),this.upgrades.indexOf("webtransport")!==-1&&t!=="webtransport"?this.setTimeoutFn(()=>{r||n.open()},200):n.open()}onOpen(){if(this.readyState="open",sl.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,o){if(typeof n=="function"&&(o=n,n=void 0),typeof r=="function"&&(o=r,r=null),this.readyState==="closing"||this.readyState==="closed")return;r=r||{},r.compress=r.compress!==!1;const i={type:t,data:n,options:r};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),o&&this.once("flush",o),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){sl.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 o=t.length;for(;rtypeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,PA=Object.prototype.toString,see=typeof Blob=="function"||typeof Blob<"u"&&PA.call(Blob)==="[object BlobConstructor]",aee=typeof File=="function"||typeof File<"u"&&PA.call(File)==="[object FileConstructor]";function ab(e){return oee&&(e instanceof ArrayBuffer||iee(e))||see&&e instanceof Blob||aee&&e instanceof File}function nh(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(i),n.apply(this,[null,...s])}}emitWithAck(t,...n){const r=this.flags.timeout!==void 0||this._opts.ackTimeout!==void 0;return new Promise((o,i)=>{n.push((s,l)=>r?s?i(s):o(l):o(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((o,...i)=>r!==this._queue[0]?void 0:(o!==null?r.tryCount>this._opts.retries&&(this._queue.shift(),n&&n(o)):(this._queue.shift(),n&&n(null,...i)),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:lt.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 lt.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 lt.EVENT:case lt.BINARY_EVENT:this.onevent(t);break;case lt.ACK:case lt.BINARY_ACK:this.onack(t);break;case lt.DISCONNECT:this.ondisconnect();break;case lt.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(...o){r||(r=!0,n.packet({type:lt.ACK,id:t,data:o}))}}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:lt.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}Cc.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};Cc.prototype.reset=function(){this.attempts=0};Cc.prototype.setMin=function(e){this.ms=e};Cc.prototype.setMax=function(e){this.max=e};Cc.prototype.setJitter=function(e){this.jitter=e};class Z1 extends qt{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,hg(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 Cc({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(n.timeout==null?2e4:n.timeout),this._readyState="closed",this.uri=t;const o=n.parser||hee;this.encoder=new o.Encoder,this.decoder=new o.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 TA(this.uri,this.opts);const n=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;const o=fo(n,"open",function(){r.onopen(),t&&t()}),i=l=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",l),t?t(l):this.maybeReconnectOnOpen()},s=fo(n,"error",i);if(this._timeout!==!1){const l=this._timeout,u=this.setTimeoutFn(()=>{o(),i(new Error("timeout")),n.close()},l);this.opts.autoUnref&&u.unref(),this.subs.push(()=>{this.clearTimeoutFn(u)})}return this.subs.push(o),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(fo(t,"ping",this.onping.bind(this)),fo(t,"data",this.ondata.bind(this)),fo(t,"error",this.onerror.bind(this)),fo(t,"close",this.onclose.bind(this)),fo(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){sb(()=>{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 AA(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(o=>{o?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",o)):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 cu={};function rh(e,t){typeof e=="object"&&(t=e,e=void 0),t=t||{};const n=ree(e,t.path||"/socket.io"),r=n.source,o=n.id,i=n.path,s=cu[o]&&i in cu[o].nsps,l=t.forceNew||t["force new connection"]||t.multiplex===!1||s;let u;return l?u=new Z1(r,t):(cu[o]||(cu[o]=new Z1(r,t)),u=cu[o]),n.query&&!t.query&&(t.query=n.queryKey),u.socket(n.path,t)}Object.assign(rh,{Manager:Z1,Socket:AA,io:rh,connect:rh});const OA="Progress",mg=100,[gee,kte]=An(OA),[vee,yee]=gee(OA),MA=f.forwardRef((e,t)=>{const{__scopeProgress:n,value:r,max:o,getValueLabel:i=bee,...s}=e,l=q1(o)?o:mg,u=DA(r,l)?r:null,d=im(u)?i(u,l):void 0;return f.createElement(vee,{scope:n,value:u,max:l},f.createElement(Pe.div,Y({"aria-valuemax":l,"aria-valuemin":0,"aria-valuenow":im(u)?u:void 0,"aria-valuetext":d,role:"progressbar","data-state":NA(u,l),"data-value":u??void 0,"data-max":l},s,{ref:t})))});MA.propTypes={max(e,t,n){const r=e[t],o=String(r);return r&&!q1(r)?new Error(_ee(o,n)):null},value(e,t,n){const r=e[t],o=String(r),i=q1(e.max)?e.max:mg;return r!=null&&!DA(r,i)?new Error(See(o,n)):null}};const wee="ProgressIndicator",xee=f.forwardRef((e,t)=>{var n;const{__scopeProgress:r,...o}=e,i=yee(wee,r);return f.createElement(Pe.div,Y({"data-state":NA(i.value,i.max),"data-value":(n=i.value)!==null&&n!==void 0?n:void 0,"data-max":i.max},o,{ref:t}))});function bee(e,t){return`${Math.round(e/t*100)}%`}function NA(e,t){return e==null?"indeterminate":e===t?"complete":"loading"}function im(e){return typeof e=="number"}function q1(e){return im(e)&&!isNaN(e)&&e>0}function DA(e,t){return im(e)&&!isNaN(e)&&e<=t&&e>=0}function _ee(e,t){return`Invalid prop \`max\` of value \`${e}\` supplied to \`${t}\`. Only numbers greater than 0 are valid max values. Defaulting to \`${mg}\`.`}function See(e,t){return`Invalid prop \`value\` of value \`${e}\` supplied to \`${t}\`. The \`value\` prop must be: + - a positive number + - less than the value passed to \`max\` (or ${mg} if no \`max\` prop is set) + - \`null\` if the progress is indeterminate. + +Defaulting to \`null\`.`}const IA=MA,Eee=xee,LA=f.forwardRef(({className:e,value:t,...n},r)=>v.jsx(IA,{ref:r,className:Ce("relative h-2 w-full overflow-hidden rounded-full bg-primary/20",e),...n,children:v.jsx(Eee,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(t||0)}%)`}})}));LA.displayName=IA.displayName;const Cee="",Vi=rh(Cee),$ee=()=>{const[e,t,n]=bt(u=>[u.settings,u.isInpainting,u.isSD()]),[r,o]=f.useState(!1),[i,s]=f.useState(0),l=Math.min(Math.round(i/e.sdSteps*100),100);return f.useEffect(()=>(Vi.on("connect",()=>{o(!0)}),Vi.on("disconnect",()=>{o(!1)}),Vi.on("diffusion_progress",u=>{u&&s(u.step+1)}),Vi.on("diffusion_finish",()=>{s(0)}),()=>{Vi.off("connect"),Vi.off("disconnect"),Vi.off("diffusion_progress"),Vi.off("diffusion_finish")}),[]),v.jsxs("div",{className:"z-10 fixed bg-background w-[220px] left-1/2 -translate-x-1/2 top-[68px] h-[32px] flex justify-center items-center gap-[18px] border-[1px] border-[solid] rounded-[14px] pl-[8px] pr-[8px]",style:{visibility:r&&t&&n?"visible":"hidden"},children:[v.jsx(LA,{value:l}),v.jsxs("div",{className:"w-[45px] flex justify-center font-nums",children:[l,"%"]})]})},kee=()=>{const[e,t]=bt(n=>[n.file,n.updateSettings]);return f.useEffect(()=>{(async()=>{const r=await zj();t({model:r})})()},[]),v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"flex gap-3 absolute top-[68px] left-[24px] items-center",children:[v.jsx(gJ,{}),v.jsx(Zq,{})]}),v.jsx(Vq,{}),v.jsx($ee,{}),v.jsx($J,{}),e?v.jsx(Xq,{file:e}):v.jsx(v.Fragment,{})]})},Ree=()=>{const[e,t]=f.useState(window.innerWidth),n=f.useCallback(()=>{t(window.innerWidth)},[]);if(f.useEffect(()=>(window.addEventListener("resize",n),()=>{window.removeEventListener("resize",n)})),e<768)return"mobile";if(e>=768&&e<1224)return"tablet";if(e>=1224)return"desktop"};function Tee(e){const{onSelection:t}=e,[n]=f.useState(`file-upload-${Math.random().toString()}`),r=Ree();function o(i){if(!(!i||!i.type.match("image.*")))try{if(i.size>20*1024*1024)throw new Error("file too large");t(i)}catch(l){alert(`error: ${l.message}`)}}return v.jsx("div",{className:"absolute flex w-screen h-screen justify-center items-center pointer-events-none",children:v.jsx("label",{htmlFor:n,className:"grid bg-background border-[2px] border-[dashed] rounded-lg min-w-[600px] hover:bg-primary hover:text-primary-foreground pointer-events-auto",children:v.jsxs("div",{className:"grid p-16 w-full h-full",onDragOver:i=>{i.stopPropagation(),i.preventDefault()},children:[v.jsx("input",{className:"hidden",id:n,name:n,type:"file",onChange:i=>{var l;const s=(l=i.currentTarget.files)==null?void 0:l[0];s&&o(s)},accept:"image/png, image/jpeg"}),v.jsx("p",{className:"text-center",children:r==="desktop"?"Click here or drag an image file":"Tap here to load your picture"})]})})})}const FA="ToastProvider",[cb,Pee,Aee]=zd("Toast"),[jA,Rte]=An("Toast",[Aee]),[Oee,gg]=jA(FA),zA=e=>{const{__scopeToast:t,label:n="Notification",duration:r=5e3,swipeDirection:o="right",swipeThreshold:i=50,children:s}=e,[l,u]=f.useState(null),[d,h]=f.useState(0),m=f.useRef(!1),g=f.useRef(!1);return f.createElement(cb.Provider,{scope:t},f.createElement(Oee,{scope:t,label:n,duration:r,swipeDirection:o,swipeThreshold:i,toastCount:d,viewport:l,onViewportChange:u,onToastAdd:f.useCallback(()=>h(y=>y+1),[]),onToastRemove:f.useCallback(()=>h(y=>y-1),[]),isFocusedToastEscapeKeyDownRef:m,isClosePausedRef:g},s))};zA.propTypes={label(e){if(e.label&&typeof e.label=="string"&&!e.label.trim()){const t=`Invalid prop \`label\` supplied to \`${FA}\`. Expected non-empty \`string\`.`;return new Error(t)}return null}};const Mee="ToastViewport",Nee=["F8"],Q1="toast.viewportPause",J1="toast.viewportResume",Dee=f.forwardRef((e,t)=>{const{__scopeToast:n,hotkey:r=Nee,label:o="Notifications ({hotkey})",...i}=e,s=gg(Mee,n),l=Pee(n),u=f.useRef(null),d=f.useRef(null),h=f.useRef(null),m=f.useRef(null),g=Be(t,m,s.onViewportChange),y=r.join("+").replace(/Key/g,"").replace(/Digit/g,""),x=s.toastCount>0;f.useEffect(()=>{const C=S=>{var b;r.every(k=>S[k]||S.code===k)&&((b=m.current)===null||b===void 0||b.focus())};return document.addEventListener("keydown",C),()=>document.removeEventListener("keydown",C)},[r]),f.useEffect(()=>{const C=u.current,S=m.current;if(x&&C&&S){const b=()=>{if(!s.isClosePausedRef.current){const M=new CustomEvent(Q1);S.dispatchEvent(M),s.isClosePausedRef.current=!0}},E=()=>{if(s.isClosePausedRef.current){const M=new CustomEvent(J1);S.dispatchEvent(M),s.isClosePausedRef.current=!1}},k=M=>{!C.contains(M.relatedTarget)&&E()},P=()=>{C.contains(document.activeElement)||E()};return C.addEventListener("focusin",b),C.addEventListener("focusout",k),C.addEventListener("pointermove",b),C.addEventListener("pointerleave",P),window.addEventListener("blur",b),window.addEventListener("focus",E),()=>{C.removeEventListener("focusin",b),C.removeEventListener("focusout",k),C.removeEventListener("pointermove",b),C.removeEventListener("pointerleave",P),window.removeEventListener("blur",b),window.removeEventListener("focus",E)}}},[x,s.isClosePausedRef]);const _=f.useCallback(({tabbingDirection:C})=>{const b=l().map(E=>{const k=E.ref.current,P=[k,...qee(k)];return C==="forwards"?P:P.reverse()});return(C==="forwards"?b.reverse():b).flat()},[l]);return f.useEffect(()=>{const C=m.current;if(C){const S=b=>{const E=b.altKey||b.ctrlKey||b.metaKey;if(b.key==="Tab"&&!E){const O=document.activeElement,F=b.shiftKey;if(b.target===C&&F){var P;(P=d.current)===null||P===void 0||P.focus();return}const G=_({tabbingDirection:F?"backwards":"forwards"}),ae=G.findIndex(U=>U===O);if(j0(G.slice(ae+1)))b.preventDefault();else{var M,A;F?(M=d.current)===null||M===void 0||M.focus():(A=h.current)===null||A===void 0||A.focus()}}};return C.addEventListener("keydown",S),()=>C.removeEventListener("keydown",S)}},[l,_]),f.createElement(SB,{ref:u,role:"region","aria-label":o.replace("{hotkey}",y),tabIndex:-1,style:{pointerEvents:x?void 0:"none"}},x&&f.createElement(o$,{ref:d,onFocusFromOutsideViewport:()=>{const C=_({tabbingDirection:"forwards"});j0(C)}}),f.createElement(cb.Slot,{scope:n},f.createElement(Pe.ol,Y({tabIndex:-1},i,{ref:g}))),x&&f.createElement(o$,{ref:h,onFocusFromOutsideViewport:()=>{const C=_({tabbingDirection:"backwards"});j0(C)}}))}),Iee="ToastFocusProxy",o$=f.forwardRef((e,t)=>{const{__scopeToast:n,onFocusFromOutsideViewport:r,...o}=e,i=gg(Iee,n);return f.createElement(Um,Y({"aria-hidden":!0,tabIndex:0},o,{ref:t,style:{position:"fixed"},onFocus:s=>{var l;const u=s.relatedTarget;!((l=i.viewport)!==null&&l!==void 0&&l.contains(u))&&r()}}))}),vg="Toast",Lee="toast.swipeStart",Fee="toast.swipeMove",jee="toast.swipeCancel",zee="toast.swipeEnd",Bee=f.forwardRef((e,t)=>{const{forceMount:n,open:r,defaultOpen:o,onOpenChange:i,...s}=e,[l=!0,u]=Zr({prop:r,defaultProp:o,onChange:i});return f.createElement(bn,{present:n||l},f.createElement(BA,Y({open:l},s,{ref:t,onClose:()=>u(!1),onPause:Ft(e.onPause),onResume:Ft(e.onResume),onSwipeStart:ue(e.onSwipeStart,d=>{d.currentTarget.setAttribute("data-swipe","start")}),onSwipeMove:ue(e.onSwipeMove,d=>{const{x:h,y:m}=d.detail.delta;d.currentTarget.setAttribute("data-swipe","move"),d.currentTarget.style.setProperty("--radix-toast-swipe-move-x",`${h}px`),d.currentTarget.style.setProperty("--radix-toast-swipe-move-y",`${m}px`)}),onSwipeCancel:ue(e.onSwipeCancel,d=>{d.currentTarget.setAttribute("data-swipe","cancel"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),d.currentTarget.style.removeProperty("--radix-toast-swipe-end-x"),d.currentTarget.style.removeProperty("--radix-toast-swipe-end-y")}),onSwipeEnd:ue(e.onSwipeEnd,d=>{const{x:h,y:m}=d.detail.delta;d.currentTarget.setAttribute("data-swipe","end"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),d.currentTarget.style.setProperty("--radix-toast-swipe-end-x",`${h}px`),d.currentTarget.style.setProperty("--radix-toast-swipe-end-y",`${m}px`),u(!1)})})))}),[Uee,Vee]=jA(vg,{onClose(){}}),BA=f.forwardRef((e,t)=>{const{__scopeToast:n,type:r="foreground",duration:o,open:i,onClose:s,onEscapeKeyDown:l,onPause:u,onResume:d,onSwipeStart:h,onSwipeMove:m,onSwipeCancel:g,onSwipeEnd:y,...x}=e,_=gg(vg,n),[C,S]=f.useState(null),b=Be(t,U=>S(U)),E=f.useRef(null),k=f.useRef(null),P=o||_.duration,M=f.useRef(0),A=f.useRef(P),O=f.useRef(0),{onToastAdd:F,onToastRemove:V}=_,J=Ft(()=>{var U;(C==null?void 0:C.contains(document.activeElement))&&((U=_.viewport)===null||U===void 0||U.focus()),s()}),G=f.useCallback(U=>{!U||U===1/0||(window.clearTimeout(O.current),M.current=new Date().getTime(),O.current=window.setTimeout(J,U))},[J]);f.useEffect(()=>{const U=_.viewport;if(U){const te=()=>{G(A.current),d==null||d()},L=()=>{const ie=new Date().getTime()-M.current;A.current=A.current-ie,window.clearTimeout(O.current),u==null||u()};return U.addEventListener(Q1,L),U.addEventListener(J1,te),()=>{U.removeEventListener(Q1,L),U.removeEventListener(J1,te)}}},[_.viewport,P,u,d,G]),f.useEffect(()=>{i&&!_.isClosePausedRef.current&&G(P)},[i,P,_.isClosePausedRef,G]),f.useEffect(()=>(F(),()=>V()),[F,V]);const ae=f.useMemo(()=>C?HA(C):null,[C]);return _.viewport?f.createElement(f.Fragment,null,ae&&f.createElement(Wee,{__scopeToast:n,role:"status","aria-live":r==="foreground"?"assertive":"polite","aria-atomic":!0},ae),f.createElement(Uee,{scope:n,onClose:J},Os.createPortal(f.createElement(cb.ItemSlot,{scope:n},f.createElement(_B,{asChild:!0,onEscapeKeyDown:ue(l,()=>{_.isFocusedToastEscapeKeyDownRef.current||J(),_.isFocusedToastEscapeKeyDownRef.current=!1})},f.createElement(Pe.li,Y({role:"status","aria-live":"off","aria-atomic":!0,tabIndex:0,"data-state":i?"open":"closed","data-swipe-direction":_.swipeDirection},x,{ref:b,style:{userSelect:"none",touchAction:"none",...e.style},onKeyDown:ue(e.onKeyDown,U=>{U.key==="Escape"&&(l==null||l(U.nativeEvent),U.nativeEvent.defaultPrevented||(_.isFocusedToastEscapeKeyDownRef.current=!0,J()))}),onPointerDown:ue(e.onPointerDown,U=>{U.button===0&&(E.current={x:U.clientX,y:U.clientY})}),onPointerMove:ue(e.onPointerMove,U=>{if(!E.current)return;const te=U.clientX-E.current.x,L=U.clientY-E.current.y,ie=!!k.current,K=["left","right"].includes(_.swipeDirection),Q=["left","up"].includes(_.swipeDirection)?Math.min:Math.max,W=K?Q(0,te):0,le=K?0:Q(0,L),ge=U.pointerType==="touch"?10:2,Ve={x:W,y:le},Ue={originalEvent:U,delta:Ve};ie?(k.current=Ve,_p(Fee,m,Ue,{discrete:!1})):i$(Ve,_.swipeDirection,ge)?(k.current=Ve,_p(Lee,h,Ue,{discrete:!1}),U.target.setPointerCapture(U.pointerId)):(Math.abs(te)>ge||Math.abs(L)>ge)&&(E.current=null)}),onPointerUp:ue(e.onPointerUp,U=>{const te=k.current,L=U.target;if(L.hasPointerCapture(U.pointerId)&&L.releasePointerCapture(U.pointerId),k.current=null,E.current=null,te){const ie=U.currentTarget,K={originalEvent:U,delta:te};i$(te,_.swipeDirection,_.swipeThreshold)?_p(zee,y,K,{discrete:!0}):_p(jee,g,K,{discrete:!0}),ie.addEventListener("click",Q=>Q.preventDefault(),{once:!0})}})})))),_.viewport))):null});BA.propTypes={type(e){if(e.type&&!["foreground","background"].includes(e.type)){const t=`Invalid prop \`type\` supplied to \`${vg}\`. Expected \`foreground | background\`.`;return new Error(t)}return null}};const Wee=e=>{const{__scopeToast:t,children:n,...r}=e,o=gg(vg,t),[i,s]=f.useState(!1),[l,u]=f.useState(!1);return Xee(()=>s(!0)),f.useEffect(()=>{const d=window.setTimeout(()=>u(!0),1e3);return()=>window.clearTimeout(d)},[]),l?null:f.createElement(Md,{asChild:!0},f.createElement(Um,r,i&&f.createElement(f.Fragment,null,o.label," ",n)))},Hee=f.forwardRef((e,t)=>{const{__scopeToast:n,...r}=e;return f.createElement(Pe.div,Y({},r,{ref:t}))}),Kee=f.forwardRef((e,t)=>{const{__scopeToast:n,...r}=e;return f.createElement(Pe.div,Y({},r,{ref:t}))}),Yee="ToastAction",UA=f.forwardRef((e,t)=>{const{altText:n,...r}=e;return n?f.createElement(WA,{altText:n,asChild:!0},f.createElement(VA,Y({},r,{ref:t}))):null});UA.propTypes={altText(e){return e.altText?null:new Error(`Missing prop \`altText\` expected on \`${Yee}\``)}};const Gee="ToastClose",VA=f.forwardRef((e,t)=>{const{__scopeToast:n,...r}=e,o=Vee(Gee,n);return f.createElement(WA,{asChild:!0},f.createElement(Pe.button,Y({type:"button"},r,{ref:t,onClick:ue(e.onClick,o.onClose)})))}),WA=f.forwardRef((e,t)=>{const{__scopeToast:n,altText:r,...o}=e;return f.createElement(Pe.div,Y({"data-radix-toast-announce-exclude":"","data-radix-toast-announce-alt":r||void 0},o,{ref:t}))});function HA(e){const t=[];return Array.from(e.childNodes).forEach(r=>{if(r.nodeType===r.TEXT_NODE&&r.textContent&&t.push(r.textContent),Zee(r)){const o=r.ariaHidden||r.hidden||r.style.display==="none",i=r.dataset.radixToastAnnounceExclude==="";if(!o)if(i){const s=r.dataset.radixToastAnnounceAlt;s&&t.push(s)}else t.push(...HA(r))}}),t}function _p(e,t,n,{discrete:r}){const o=n.originalEvent.currentTarget,i=new CustomEvent(e,{bubbles:!0,cancelable:!0,detail:n});t&&o.addEventListener(e,t,{once:!0}),r?cx(o,i):o.dispatchEvent(i)}const i$=(e,t,n=0)=>{const r=Math.abs(e.x),o=Math.abs(e.y),i=r>o;return t==="left"||t==="right"?i&&r>n:!i&&o>n};function Xee(e=()=>{}){const t=Ft(e);Pn(()=>{let n=0,r=0;return n=window.requestAnimationFrame(()=>r=window.requestAnimationFrame(t)),()=>{window.cancelAnimationFrame(n),window.cancelAnimationFrame(r)}},[t])}function Zee(e){return e.nodeType===e.ELEMENT_NODE}function qee(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const o=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||o?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function j0(e){const t=document.activeElement;return e.some(n=>n===t?!0:(n.focus(),document.activeElement!==t))}const Qee=zA,KA=Dee,YA=Bee,GA=Hee,XA=Kee,ZA=UA,qA=VA,Jee=Qee,QA=f.forwardRef(({className:e,...t},n)=>v.jsx(KA,{ref:n,className:Ce("fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]",e),tabIndex:-1,...t}));QA.displayName=KA.displayName;const ete=Om("group pointer-events-auto relative flex w-full items-center justify-between space-x-2 overflow-hidden rounded-md border p-4 pr-6 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full",{variants:{variant:{default:"border bg-background text-foreground",destructive:"destructive group border-destructive bg-destructive text-destructive-foreground"}},defaultVariants:{variant:"default"}}),JA=f.forwardRef(({className:e,variant:t,...n},r)=>v.jsx(YA,{ref:r,className:Ce(ete({variant:t}),e),tabIndex:-1,...n}));JA.displayName=YA.displayName;const tte=f.forwardRef(({className:e,...t},n)=>v.jsx(ZA,{ref:n,className:Ce("inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium transition-colors hover:bg-secondary focus:outline-none focus:ring-1 focus:ring-ring disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive",e),tabIndex:-1,...t}));tte.displayName=ZA.displayName;const eO=f.forwardRef(({className:e,...t},n)=>v.jsx(qA,{ref:n,className:Ce("absolute right-1 top-1 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-1 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600",e),"toast-close":"",tabIndex:-1,...t,children:v.jsx(yT,{className:"h-4 w-4"})}));eO.displayName=qA.displayName;const tO=f.forwardRef(({className:e,...t},n)=>v.jsx(GA,{ref:n,className:Ce("text-sm font-semibold [&+div]:text-xs",e),tabIndex:-1,...t}));tO.displayName=GA.displayName;const nO=f.forwardRef(({className:e,...t},n)=>v.jsx(XA,{ref:n,className:Ce("text-sm opacity-90",e),...t,tabIndex:-1}));nO.displayName=XA.displayName;function nte(){const{toasts:e}=Td();return v.jsxs(Jee,{children:[e.map(function({id:t,title:n,description:r,action:o,...i}){return v.jsxs(JA,{...i,children:[v.jsxs("div",{className:"grid gap-1",children:[n&&v.jsx(tO,{children:n}),r&&v.jsx(nO,{children:r})]}),o,v.jsx(eO,{})]},t)}),v.jsx(QA,{})]})}const rte=["image/jpeg","image/png","image/webp","image/bmp","image/tiff"];function ote(){const[e,t,n,r]=bt(g=>[g.file,g.updateAppState,g.setServerConfig,g.setFile]),o=Yj(),i=gH();f.useEffect(()=>{o&&r(o)},[o,r]),f.useEffect(()=>{t({windowSize:i})},[i]),f.useEffect(()=>{(async()=>{const y=await Fj();n(y),y.isDesktop&&dF()})()},[]);const s=f.useRef(0),l=f.useCallback(g=>{g.preventDefault(),g.stopPropagation()},[]),u=f.useCallback(g=>{g.preventDefault(),g.stopPropagation(),s.current+=1},[]),d=f.useCallback(g=>{g.preventDefault(),g.stopPropagation(),s.current-=1,s.current>0},[]),h=f.useCallback(g=>{if(g.preventDefault(),g.stopPropagation(),g.dataTransfer.files&&g.dataTransfer.files.length>0){if(!(g.dataTransfer.files.length>1)){const y=g.dataTransfer.files[0],x=y.type;rte.includes(x)&&r(y)}g.dataTransfer.clearData()}},[]),m=f.useCallback(g=>{if(!g.clipboardData)return;const y=g.clipboardData.items,x=[].slice.call(y).filter(S=>S.type.indexOf("image")!==-1);if(x.length===0)return;g.preventDefault(),g.stopPropagation();const C=x[0].getAsFile();C&&r(C)},[]);return f.useEffect(()=>(window.addEventListener("dragenter",u),window.addEventListener("dragleave",d),window.addEventListener("dragover",l),window.addEventListener("drop",h),window.addEventListener("paste",m),function(){window.removeEventListener("dragenter",u),window.removeEventListener("dragleave",d),window.removeEventListener("dragover",l),window.removeEventListener("drop",h),window.removeEventListener("paste",m)})),v.jsxs("main",{className:"flex min-h-screen flex-col items-center justify-between w-full bg-[radial-gradient(circle_at_1px_1px,_#8e8e8e8e_1px,_transparent_0)] [background-size:20px_20px] bg-repeat",children:[v.jsx(nte,{}),v.jsx(tZ,{}),v.jsx(kee,{}),e?v.jsx(v.Fragment,{}):v.jsx(Tee,{onSelection:async g=>{r(g)}})]})}const sm=["light","dark"],ub="(prefers-color-scheme: dark)",ite=typeof window>"u",rO=f.createContext(void 0),ste=e=>f.useContext(rO)?Fe.createElement(f.Fragment,null,e.children):Fe.createElement(lte,e),ate=["light","dark"],lte=({forcedTheme:e,disableTransitionOnChange:t=!1,enableSystem:n=!0,enableColorScheme:r=!0,storageKey:o="theme",themes:i=ate,defaultTheme:s=n?"system":"light",attribute:l="data-theme",value:u,children:d,nonce:h})=>{const[m,g]=f.useState(()=>s$(o,s)),[y,x]=f.useState(()=>s$(o)),_=u?Object.values(u):i,C=f.useCallback(k=>{let P=k;if(!P)return;k==="system"&&n&&(P=a$());const M=u?u[P]:P,A=t?ute():null,O=document.documentElement;if(l==="class"?(O.classList.remove(..._),M&&O.classList.add(M)):M?O.setAttribute(l,M):O.removeAttribute(l),r){const F=sm.includes(s)?s:null,V=sm.includes(P)?P:F;O.style.colorScheme=V}A==null||A()},[]),S=f.useCallback(k=>{g(k);try{localStorage.setItem(o,k)}catch{}},[e]),b=f.useCallback(k=>{const P=a$(k);x(P),m==="system"&&n&&!e&&C("system")},[m,e]);f.useEffect(()=>{const k=window.matchMedia(ub);return k.addListener(b),b(k),()=>k.removeListener(b)},[b]),f.useEffect(()=>{const k=P=>{P.key===o&&S(P.newValue||s)};return window.addEventListener("storage",k),()=>window.removeEventListener("storage",k)},[S]),f.useEffect(()=>{C(e??m)},[e,m]);const E=f.useMemo(()=>({theme:m,setTheme:S,forcedTheme:e,resolvedTheme:m==="system"?y:m,themes:n?[...i,"system"]:i,systemTheme:n?y:void 0}),[m,S,e,y,n,i]);return Fe.createElement(rO.Provider,{value:E},Fe.createElement(cte,{forcedTheme:e,disableTransitionOnChange:t,enableSystem:n,enableColorScheme:r,storageKey:o,themes:i,defaultTheme:s,attribute:l,value:u,children:d,attrs:_,nonce:h}),d)},cte=f.memo(({forcedTheme:e,storageKey:t,attribute:n,enableSystem:r,enableColorScheme:o,defaultTheme:i,value:s,attrs:l,nonce:u})=>{const d=i==="system",h=n==="class"?`var d=document.documentElement,c=d.classList;c.remove(${l.map(x=>`'${x}'`).join(",")});`:`var d=document.documentElement,n='${n}',s='setAttribute';`,m=o?sm.includes(i)&&i?`if(e==='light'||e==='dark'||!e)d.style.colorScheme=e||'${i}'`:"if(e==='light'||e==='dark')d.style.colorScheme=e":"",g=(x,_=!1,C=!0)=>{const S=s?s[x]:x,b=_?x+"|| ''":`'${S}'`;let E="";return o&&C&&!_&&sm.includes(x)&&(E+=`d.style.colorScheme = '${x}';`),n==="class"?E+=_||S?`c.add(${b})`:"null":S&&(E+=`d[s](n,${b})`),E},y=e?`!function(){${h}${g(e)}}()`:r?`!function(){try{${h}var e=localStorage.getItem('${t}');if('system'===e||(!e&&${d})){var t='${ub}',m=window.matchMedia(t);if(m.media!==t||m.matches){${g("dark")}}else{${g("light")}}}else if(e){${s?`var x=${JSON.stringify(s)};`:""}${g(s?"x[e]":"e",!0)}}${d?"":"else{"+g(i,!1,!1)+"}"}${m}}catch(e){}}()`:`!function(){try{${h}var e=localStorage.getItem('${t}');if(e){${s?`var x=${JSON.stringify(s)};`:""}${g(s?"x[e]":"e",!0)}}else{${g(i,!1,!1)};}${m}}catch(t){}}();`;return Fe.createElement("script",{nonce:u,dangerouslySetInnerHTML:{__html:y}})},()=>!0),s$=(e,t)=>{if(ite)return;let n;try{n=localStorage.getItem(e)||void 0}catch{}return n||t},ute=()=>{const e=document.createElement("style");return e.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(e),()=>{window.getComputedStyle(document.body),setTimeout(()=>{document.head.removeChild(e)},1)}},a$=e=>(e||(e=window.matchMedia(ub)),e.matches?"dark":"light"),dte=new dL;z0.createRoot(document.getElementById("root")).render(v.jsx(Fe.StrictMode,{children:v.jsx(gL,{client:dte,children:v.jsx(ste,{defaultTheme:"dark",disableTransitionOnChange:!0,children:v.jsx(UU,{children:v.jsx(ote,{})})})})})); diff --git a/py/iopaint/web_app/assets/kofi_button_black-XI_Dr2zg.png b/py/iopaint/web_app/assets/kofi_button_black-XI_Dr2zg.png new file mode 100644 index 0000000..0baa366 Binary files /dev/null and b/py/iopaint/web_app/assets/kofi_button_black-XI_Dr2zg.png differ diff --git a/py/iopaint/web_app/index.html b/py/iopaint/web_app/index.html new file mode 100644 index 0000000..954c49b --- /dev/null +++ b/py/iopaint/web_app/index.html @@ -0,0 +1,13 @@ + + + + + + IOPaint + + + + +
+ + diff --git a/py/iopaint/web_config.py b/py/iopaint/web_config.py new file mode 100644 index 0000000..534a0ca --- /dev/null +++ b/py/iopaint/web_config.py @@ -0,0 +1,307 @@ +import json +import os +from pathlib import Path + +from .schema import ( + Device, + InteractiveSegModel, + RemoveBGModel, + RealESRGANModel, + ApiConfig, +) + +os.environ["GRADIO_ANALYTICS_ENABLED"] = "False" + +from datetime import datetime +from json import JSONDecodeError + +import gradio as gr +from .download import scan_models +from loguru import logger + +from .const import * + + +_config_file: Path = None + + +default_configs = dict( + host="127.0.0.1", + port=8080, + inbrowser=True, + model=DEFAULT_MODEL, + model_dir=DEFAULT_MODEL_DIR, + no_half=False, + low_mem=False, + cpu_offload=False, + disable_nsfw_checker=False, + local_files_only=False, + cpu_textencoder=False, + device=Device.cuda, + input=None, + output_dir=None, + quality=95, + enable_interactive_seg=False, + interactive_seg_model=InteractiveSegModel.vit_b, + interactive_seg_device=Device.cpu, + enable_remove_bg=False, + remove_bg_model=RemoveBGModel.briaai_rmbg_1_4, + enable_anime_seg=False, + enable_realesrgan=False, + realesrgan_device=Device.cpu, + realesrgan_model=RealESRGANModel.realesr_general_x4v3, + enable_gfpgan=False, + gfpgan_device=Device.cpu, + enable_restoreformer=False, + restoreformer_device=Device.cpu, +) + + +class WebConfig(ApiConfig): + model_dir: str = DEFAULT_MODEL_DIR + + +def load_config(p: Path) -> WebConfig: + if p.exists(): + with open(p, "r", encoding="utf-8") as f: + try: + return WebConfig(**{**default_configs, **json.load(f)}) + except JSONDecodeError: + print(f"Load config file failed, using default configs") + return WebConfig(**default_configs) + else: + return WebConfig(**default_configs) + + +def save_config( + host, + port, + model, + model_dir, + no_half, + low_mem, + cpu_offload, + disable_nsfw_checker, + local_files_only, + cpu_textencoder, + device, + input, + output_dir, + quality, + enable_interactive_seg, + interactive_seg_model, + interactive_seg_device, + enable_remove_bg, + remove_bg_model, + enable_anime_seg, + enable_realesrgan, + realesrgan_device, + realesrgan_model, + enable_gfpgan, + gfpgan_device, + enable_restoreformer, + restoreformer_device, + inbrowser, +): + config = WebConfig(**locals()) + if str(config.input) == ".": + config.input = None + if str(config.output_dir) == ".": + config.output_dir = None + config.model = config.model.strip() + print(config.model_dump_json(indent=4)) + if config.input and not os.path.exists(config.input): + return "[Error] Input file or directory does not exist" + + current_time = datetime.now().strftime("%H:%M:%S") + msg = f"[{current_time}] Successful save config to: {str(_config_file.absolute())}" + logger.info(msg) + try: + with open(_config_file, "w", encoding="utf-8") as f: + f.write(config.model_dump_json(indent=4)) + except Exception as e: + return f"Save configure file failed: {str(e)}" + return msg + + +def change_current_model(new_model): + return new_model + + +def main(config_file: Path): + global _config_file + _config_file = config_file + + init_config = load_config(config_file) + downloaded_models = [it.name for it in scan_models()] + + with gr.Blocks() as demo: + with gr.Row(): + with gr.Column(): + gr.Textbox(config_file, label="Config file", interactive=False) + with gr.Column(): + save_btn = gr.Button(value="Save configurations") + message = gr.HTML() + + with gr.Tabs(): + with gr.Tab("Common"): + with gr.Row(): + host = gr.Textbox(init_config.host, label="Host") + port = gr.Number(init_config.port, label="Port", precision=0) + inbrowser = gr.Checkbox(init_config.inbrowser, label=INBROWSER_HELP) + + with gr.Column(): + model = gr.Textbox( + init_config.model, + label="Current Model. This is the model that will be used when the service starts. " + "If the model has not been downloaded before, it will be automatically downloaded. " + "You can select a model from the dropdown box below or manually enter the SD/SDXL model ID from HuggingFace, for example, runwayml/stable-diffusion-inpainting.", + ) + with gr.Row(): + recommend_model = gr.Dropdown( + ["lama", "mat", "migan"] + DIFFUSION_MODELS, + label="Recommended Models", + ) + downloaded_model = gr.Dropdown( + downloaded_models, label="Downloaded Models" + ) + + device = gr.Radio( + Device.values(), label="Device", value=init_config.device + ) + quality = gr.Slider( + value=95, + label=f"Image Quality ({QUALITY_HELP})", + minimum=75, + maximum=100, + step=1, + ) + + no_half = gr.Checkbox(init_config.no_half, label=f"{NO_HALF_HELP}") + cpu_offload = gr.Checkbox( + init_config.cpu_offload, label=f"{CPU_OFFLOAD_HELP}" + ) + low_mem = gr.Checkbox(init_config.low_mem, label=f"{LOW_MEM_HELP}") + cpu_textencoder = gr.Checkbox( + init_config.cpu_textencoder, label=f"{CPU_TEXTENCODER_HELP}" + ) + disable_nsfw_checker = gr.Checkbox( + init_config.disable_nsfw_checker, label=f"{DISABLE_NSFW_HELP}" + ) + local_files_only = gr.Checkbox( + init_config.local_files_only, label=f"{LOCAL_FILES_ONLY_HELP}" + ) + + with gr.Column(): + model_dir = gr.Textbox( + init_config.model_dir, label=f"{MODEL_DIR_HELP}" + ) + input = gr.Textbox( + init_config.input, + label=f"Input file or directory. {INPUT_HELP}", + ) + output_dir = gr.Textbox( + init_config.output_dir, + label=f"Output directory. {OUTPUT_DIR_HELP}", + ) + + with gr.Tab("Plugins"): + with gr.Row(): + enable_interactive_seg = gr.Checkbox( + init_config.enable_interactive_seg, label=INTERACTIVE_SEG_HELP + ) + interactive_seg_model = gr.Radio( + InteractiveSegModel.values(), + label=f"Segment Anything models. {INTERACTIVE_SEG_MODEL_HELP}", + value=init_config.interactive_seg_model, + ) + interactive_seg_device = gr.Radio( + Device.values(), + label="Segment Anything Device", + value=init_config.interactive_seg_device, + ) + with gr.Row(): + enable_remove_bg = gr.Checkbox( + init_config.enable_remove_bg, label=REMOVE_BG_HELP + ) + remove_bg_model = gr.Radio( + RemoveBGModel.values(), + label="Remove bg model", + value=init_config.remove_bg_model, + ) + with gr.Row(): + enable_anime_seg = gr.Checkbox( + init_config.enable_anime_seg, label=ANIMESEG_HELP + ) + + with gr.Row(): + enable_realesrgan = gr.Checkbox( + init_config.enable_realesrgan, label=REALESRGAN_HELP + ) + realesrgan_device = gr.Radio( + Device.values(), + label="RealESRGAN Device", + value=init_config.realesrgan_device, + ) + realesrgan_model = gr.Radio( + RealESRGANModel.values(), + label="RealESRGAN model", + value=init_config.realesrgan_model, + ) + with gr.Row(): + enable_gfpgan = gr.Checkbox( + init_config.enable_gfpgan, label=GFPGAN_HELP + ) + gfpgan_device = gr.Radio( + Device.values(), + label="GFPGAN Device", + value=init_config.gfpgan_device, + ) + with gr.Row(): + enable_restoreformer = gr.Checkbox( + init_config.enable_restoreformer, label=RESTOREFORMER_HELP + ) + restoreformer_device = gr.Radio( + Device.values(), + label="RestoreFormer Device", + value=init_config.restoreformer_device, + ) + + downloaded_model.change(change_current_model, [downloaded_model], model) + recommend_model.change(change_current_model, [recommend_model], model) + + save_btn.click( + save_config, + [ + host, + port, + model, + model_dir, + no_half, + low_mem, + cpu_offload, + disable_nsfw_checker, + local_files_only, + cpu_textencoder, + device, + input, + output_dir, + quality, + enable_interactive_seg, + interactive_seg_model, + interactive_seg_device, + enable_remove_bg, + remove_bg_model, + enable_anime_seg, + enable_realesrgan, + realesrgan_device, + realesrgan_model, + enable_gfpgan, + gfpgan_device, + enable_restoreformer, + restoreformer_device, + inbrowser, + ], + message, + ) + demo.launch(inbrowser=True, show_api=False) diff --git a/py/joycaption_alpha_2.py b/py/joycaption_alpha_2.py new file mode 100644 index 0000000..3155c99 --- /dev/null +++ b/py/joycaption_alpha_2.py @@ -0,0 +1,640 @@ +# layerstyle advance + +# Based on https://huggingface.co/John6666/joy-caption-alpha-two-cli-mod + +import os +import sys +import torch +import torch.amp.autocast_mode +from torch import nn +from typing import List, Union +from PIL import Image + +import folder_paths +from .imagefunc import download_hg_model, log, tensor2pil, clear_memory + +class Joy2_Model(): + def __init__(self, clip_processor, clip_model, tokenizer, text_model, image_adapter): + self.clip_processor = clip_processor + self.clip_model = clip_model + self.tokenizer = tokenizer + self.text_model = text_model + self.image_adapter = image_adapter + +class ImageAdapter(nn.Module): + def __init__(self, input_features: int, output_features: int, ln1: bool, pos_emb: bool, num_image_tokens: int, + deep_extract: bool): + super().__init__() + self.deep_extract = deep_extract + + if self.deep_extract: + input_features = input_features * 5 + + self.linear1 = nn.Linear(input_features, output_features) + self.activation = nn.GELU() + self.linear2 = nn.Linear(output_features, output_features) + self.ln1 = nn.Identity() if not ln1 else nn.LayerNorm(input_features) + self.pos_emb = None if not pos_emb else nn.Parameter(torch.zeros(num_image_tokens, input_features)) + + # Other tokens (<|image_start|>, <|image_end|>, <|eot_id|>) + self.other_tokens = nn.Embedding(3, output_features) + self.other_tokens.weight.data.normal_(mean=0.0, std=0.02) # Matches HF's implementation of llama3 + + def forward(self, vision_outputs: torch.Tensor): + if self.deep_extract: + x = torch.concat(( + vision_outputs[-2], + vision_outputs[3], + vision_outputs[7], + vision_outputs[13], + vision_outputs[20], + ), dim=-1) + assert len(x.shape) == 3, f"Expected 3, got {len(x.shape)}" # batch, tokens, features + assert x.shape[-1] == vision_outputs[-2].shape[ + -1] * 5, f"Expected {vision_outputs[-2].shape[-1] * 5}, got {x.shape[-1]}" + else: + x = vision_outputs[-2] + + x = self.ln1(x) + + if self.pos_emb is not None: + assert x.shape[-2:] == self.pos_emb.shape, f"Expected {self.pos_emb.shape}, got {x.shape[-2:]}" + x = x + self.pos_emb + + x = self.linear1(x) + x = self.activation(x) + x = self.linear2(x) + + other_tokens = self.other_tokens( + torch.tensor([0, 1], device=self.other_tokens.weight.device).expand(x.shape[0], -1)) + assert other_tokens.shape == ( + x.shape[0], 2, x.shape[2]), f"Expected {(x.shape[0], 2, x.shape[2])}, got {other_tokens.shape}" + x = torch.cat((other_tokens[:, 0:1], x, other_tokens[:, 1:2]), dim=1) + + return x + + def get_eot_embedding(self): + return self.other_tokens(torch.tensor([2], device=self.other_tokens.weight.device)).squeeze(0) + +def load_models(model_path, dtype, vlm_lora, device): + from transformers import AutoModel, AutoProcessor, AutoTokenizer, PreTrainedTokenizer, PreTrainedTokenizerFast, \ + AutoModelForCausalLM + from peft import PeftModel + + use_lora = True if vlm_lora != "none" else False + CLIP_PATH = download_hg_model("google/siglip-so400m-patch14-384", "clip") + CHECKPOINT_PATH = os.path.join(folder_paths.models_dir, "Joy_caption", "cgrkzexw-599808") + LORA_PATH = os.path.join(CHECKPOINT_PATH, "text_model") + + try: + if dtype=="nf4": + from transformers import BitsAndBytesConfig + nf4_config = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4", + bnb_4bit_use_double_quant=True, bnb_4bit_compute_dtype=torch.bfloat16) + print("Loading in NF4") + print("Loading CLIP 📎") + clip_processor = AutoProcessor.from_pretrained(CLIP_PATH) + clip_model = AutoModel.from_pretrained(CLIP_PATH).vision_model + + print("Loading VLM's custom vision model 📎") + checkpoint = torch.load(os.path.join(CHECKPOINT_PATH, "clip_model.pt"), map_location='cpu', weights_only=False) + checkpoint = {k.replace("_orig_mod.module.", ""): v for k, v in checkpoint.items()} + clip_model.load_state_dict(checkpoint) + del checkpoint + clip_model.eval().requires_grad_(False).to(device) + + print("Loading tokenizer 🪙") + tokenizer = AutoTokenizer.from_pretrained(os.path.join(CHECKPOINT_PATH, "text_model"), use_fast=True) + assert isinstance(tokenizer, + (PreTrainedTokenizer, PreTrainedTokenizerFast)), f"Tokenizer is of type {type(tokenizer)}" + + print(f"Loading LLM: {model_path} 🤖") + text_model = AutoModelForCausalLM.from_pretrained(model_path, quantization_config=nf4_config, + device_map=device, torch_dtype=torch.bfloat16).eval() + + if False and use_lora and os.path.exists(LORA_PATH): # omitted + print("Loading VLM's custom text model 🤖") + text_model = PeftModel.from_pretrained(model=text_model, model_id=LORA_PATH, device_map=device, + quantization_config=nf4_config) + text_model = text_model.merge_and_unload( + safe_merge=True) # to avoid PEFT bug https://github.com/huggingface/transformers/issues/28515 + else: + print("VLM's custom text model isn't loaded 🤖") + + print("Loading image adapter 🖼️") + image_adapter = ImageAdapter(clip_model.config.hidden_size, text_model.config.hidden_size, False, False, 38, + False).eval().to("cpu") + image_adapter.load_state_dict( + torch.load(os.path.join(CHECKPOINT_PATH, "image_adapter.pt"), map_location=device, weights_only=False)) + image_adapter.eval().to(device) + else: # bf16 + print("Loading in bfloat16") + print("Loading CLIP 📎") + clip_processor = AutoProcessor.from_pretrained(CLIP_PATH) + clip_model = AutoModel.from_pretrained(CLIP_PATH).vision_model + if os.path.exists(os.path.join(CHECKPOINT_PATH, "clip_model.pt")): + print("Loading VLM's custom vision model 📎") + checkpoint = torch.load(os.path.join(CHECKPOINT_PATH, "clip_model.pt"), map_location=device, weights_only=False) + checkpoint = {k.replace("_orig_mod.module.", ""): v for k, v in checkpoint.items()} + clip_model.load_state_dict(checkpoint) + del checkpoint + clip_model.eval().requires_grad_(False).to(device) + + print("Loading tokenizer 🪙") + tokenizer = AutoTokenizer.from_pretrained(os.path.join(CHECKPOINT_PATH, "text_model"), use_fast=True) + assert isinstance(tokenizer, + (PreTrainedTokenizer, PreTrainedTokenizerFast)), f"Tokenizer is of type {type(tokenizer)}" + + print(f"Loading LLM: {model_path} 🤖") + text_model = AutoModelForCausalLM.from_pretrained(model_path, device_map="auto", + torch_dtype=torch.bfloat16).eval() # device_map="auto" may cause LoRA issue + + if use_lora and os.path.exists(LORA_PATH): + print("Loading VLM's custom text model 🤖") + text_model = PeftModel.from_pretrained(model=text_model, model_id=LORA_PATH, device_map=device) + text_model = text_model.merge_and_unload( + safe_merge=True) # to avoid PEFT bug https://github.com/huggingface/transformers/issues/28515 + else: + print("VLM's custom text model isn't loaded 🤖") + + print("Loading image adapter 🖼️") + image_adapter = ImageAdapter(clip_model.config.hidden_size, text_model.config.hidden_size, False, False, 38, + False).eval().to(device) + image_adapter.load_state_dict( + torch.load(os.path.join(CHECKPOINT_PATH, "image_adapter.pt"), map_location=device, weights_only=False)) + except Exception as e: + print(f"Error loading models: {e}") + finally: + clear_memory() + + return Joy2_Model(clip_processor, clip_model, tokenizer, text_model, image_adapter) + +@torch.inference_mode() +def stream_chat(input_images: List[Image.Image], caption_type: str, caption_length: Union[str, int], + extra_options: list[str], name_input: str, custom_prompt: str, + max_new_tokens: int, top_p: float, temperature: float, batch_size: int, model:Joy2_Model, device=str): + + CAPTION_TYPE_MAP = { + "Descriptive": [ + "Write a descriptive caption for this image in a formal tone.", + "Write a descriptive caption for this image in a formal tone within {word_count} words.", + "Write a {length} descriptive caption for this image in a formal tone.", + ], + "Descriptive (Informal)": [ + "Write a descriptive caption for this image in a casual tone.", + "Write a descriptive caption for this image in a casual tone within {word_count} words.", + "Write a {length} descriptive caption for this image in a casual tone.", + ], + "Training Prompt": [ + "Write a stable diffusion prompt for this image.", + "Write a stable diffusion prompt for this image within {word_count} words.", + "Write a {length} stable diffusion prompt for this image.", + ], + "MidJourney": [ + "Write a MidJourney prompt for this image.", + "Write a MidJourney prompt for this image within {word_count} words.", + "Write a {length} MidJourney prompt for this image.", + ], + "Booru tag list": [ + "Write a list of Booru tags for this image.", + "Write a list of Booru tags for this image within {word_count} words.", + "Write a {length} list of Booru tags for this image.", + ], + "Booru-like tag list": [ + "Write a list of Booru-like tags for this image.", + "Write a list of Booru-like tags for this image within {word_count} words.", + "Write a {length} list of Booru-like tags for this image.", + ], + "Art Critic": [ + "Analyze this image like an art critic would with information about its composition, style, symbolism, the use of color, light, any artistic movement it might belong to, etc.", + "Analyze this image like an art critic would with information about its composition, style, symbolism, the use of color, light, any artistic movement it might belong to, etc. Keep it within {word_count} words.", + "Analyze this image like an art critic would with information about its composition, style, symbolism, the use of color, light, any artistic movement it might belong to, etc. Keep it {length}.", + ], + "Product Listing": [ + "Write a caption for this image as though it were a product listing.", + "Write a caption for this image as though it were a product listing. Keep it under {word_count} words.", + "Write a {length} caption for this image as though it were a product listing.", + ], + "Social Media Post": [ + "Write a caption for this image as if it were being used for a social media post.", + "Write a caption for this image as if it were being used for a social media post. Limit the caption to {word_count} words.", + "Write a {length} caption for this image as if it were being used for a social media post.", + ], + } + + clear_memory() + all_captions = [] + + # 'any' means no length specified + length = None if caption_length == "any" else caption_length + + if isinstance(length, str): + try: + length = int(length) + except ValueError: + pass + + # Build prompt + if length is None: + map_idx = 0 + elif isinstance(length, int): + map_idx = 1 + elif isinstance(length, str): + map_idx = 2 + else: + raise ValueError(f"Invalid caption length: {length}") + + prompt_str = CAPTION_TYPE_MAP[caption_type][map_idx] + + # Add extra options + if len(extra_options) > 0: + prompt_str += " " + " ".join(extra_options) + + # Add name, length, word_count + prompt_str = prompt_str.format(name=name_input, length=caption_length, word_count=caption_length) + + if custom_prompt.strip() != "": + prompt_str = custom_prompt.strip() + + # For debugging + print(f"Prompt: {prompt_str}") + import torchvision.transforms.functional as TVF + + for i in range(0, len(input_images), batch_size): + batch = input_images[i:i + batch_size] + + for input_image in input_images: + try: + # Preprocess image + image = input_image.resize((384, 384), Image.LANCZOS) + pixel_values = TVF.pil_to_tensor(image).unsqueeze(0) / 255.0 + pixel_values = TVF.normalize(pixel_values, [0.5], [0.5]) + pixel_values = pixel_values.to(device) + except ValueError as e: + print(f"Error processing image: {e}") + print("Skipping this image and continuing...") + continue + + # Embed image + # This results in Batch x Image Tokens x Features + with torch.amp.autocast_mode.autocast(device, enabled=True): + vision_outputs = model.clip_model(pixel_values=pixel_values, output_hidden_states=True) + image_features = vision_outputs.hidden_states + embedded_images = model.image_adapter(image_features).to(device) + + # Build the conversation + convo = [ + { + "role": "system", + "content": "You are a helpful image captioner.", + }, + { + "role": "user", + "content": prompt_str, + }, + ] + + # Format the conversation + convo_string = model.tokenizer.apply_chat_template(convo, tokenize=False, add_generation_prompt=True) + assert isinstance(convo_string, str) + + # Tokenize the conversation + # prompt_str is tokenized separately so we can do the calculations below + convo_tokens = model.tokenizer.encode(convo_string, return_tensors="pt", add_special_tokens=False, + truncation=False) + prompt_tokens = model.tokenizer.encode(prompt_str, return_tensors="pt", add_special_tokens=False, + truncation=False) + assert isinstance(convo_tokens, torch.Tensor) and isinstance(prompt_tokens, torch.Tensor) + convo_tokens = convo_tokens.squeeze(0) # Squeeze just to make the following easier + prompt_tokens = prompt_tokens.squeeze(0) + + # Calculate where to inject the image + eot_id_indices = (convo_tokens == model.tokenizer.convert_tokens_to_ids("<|eot_id|>")).nonzero(as_tuple=True)[ + 0].tolist() + assert len(eot_id_indices) == 2, f"Expected 2 <|eot_id|> tokens, got {len(eot_id_indices)}" + + preamble_len = eot_id_indices[1] - prompt_tokens.shape[0] # Number of tokens before the prompt + + # Embed the tokens + convo_embeds = model.text_model.model.embed_tokens(convo_tokens.unsqueeze(0).to(device)) + + # Construct the input + input_embeds = torch.cat([ + convo_embeds[:, :preamble_len], # Part before the prompt + embedded_images.to(dtype=convo_embeds.dtype), # Image + convo_embeds[:, preamble_len:], # The prompt and anything after it + ], dim=1).to(device) + + input_ids = torch.cat([ + convo_tokens[:preamble_len].unsqueeze(0), + torch.zeros((1, embedded_images.shape[1]), dtype=torch.long), + convo_tokens[preamble_len:].unsqueeze(0), + ], dim=1).to(device) + attention_mask = torch.ones_like(input_ids) + + generate_ids = model.text_model.generate(input_ids=input_ids, inputs_embeds=input_embeds, + attention_mask=attention_mask, do_sample=True, + suppress_tokens=None, max_new_tokens=max_new_tokens, top_p=top_p, + temperature=temperature) + + # Trim off the prompt + generate_ids = generate_ids[:, input_ids.shape[1]:] + if generate_ids[0][-1] == model.tokenizer.eos_token_id or generate_ids[0][-1] == model.tokenizer.convert_tokens_to_ids( + "<|eot_id|>"): + generate_ids = generate_ids[:, :-1] + + caption = model.tokenizer.batch_decode(generate_ids, skip_special_tokens=False, clean_up_tokenization_spaces=False)[0] + all_captions.append(caption.strip()) + + return all_captions + + +class LS_JoyCaptionExtraOptions: + + CATEGORY = '😺dzNodes/LayerUtility' + FUNCTION = "extra_choice" + RETURN_TYPES = ("JoyCaption2ExtraOption",) + RETURN_NAMES = ("extra_option",) + + @classmethod + def INPUT_TYPES(self): + return { + "required": { + "refer_character_name": ("BOOLEAN", {"default": False}), + "exclude_people_info": ("BOOLEAN", {"default": False}), + "include_lighting": ("BOOLEAN", {"default": False}), + "include_camera_angle": ("BOOLEAN", {"default": False}), + "include_watermark": ("BOOLEAN", {"default": False}), + "include_JPEG_artifacts": ("BOOLEAN", {"default": False}), + "include_exif": ("BOOLEAN", {"default": False}), + "exclude_sexual": ("BOOLEAN", {"default": False}), + "exclude_image_resolution": ("BOOLEAN", {"default": False}), + "include_aesthetic_quality": ("BOOLEAN", {"default": False}), + "include_composition_style": ("BOOLEAN", {"default": False}), + "exclude_text": ("BOOLEAN", {"default": False}), + "specify_depth_field": ("BOOLEAN", {"default": False}), + "specify_lighting_sources": ("BOOLEAN", {"default": False}), + "do_not_use_ambiguous_language": ("BOOLEAN", {"default": False}), + "include_nsfw": ("BOOLEAN", {"default": False}), + "only_describe_most_important_elements": ("BOOLEAN", {"default": False}), + "character_name": ("STRING", {"default": "Huluwa", "multiline": False}), + }, + "optional": { + } + } + + def extra_choice(self, refer_character_name, exclude_people_info, include_lighting, include_camera_angle, + include_watermark, include_JPEG_artifacts, include_exif, exclude_sexual, + exclude_image_resolution, include_aesthetic_quality, include_composition_style, + exclude_text, specify_depth_field, specify_lighting_sources, + do_not_use_ambiguous_language, include_nsfw, only_describe_most_important_elements, + character_name): + + extra_list = { + "refer_character_name":"If there is a person/character in the image you must refer to them as {name}.", + "exclude_people_info":"Do NOT include information about people/characters that cannot be changed (like ethnicity, gender, etc), but do still include changeable attributes (like hair style).", + "include_lighting":"Include information about lighting.", + "include_camera_angle":"Include information about camera angle.", + "include_watermark":"Include information about whether there is a watermark or not.", + "include_JPEG_artifacts":"Include information about whether there are JPEG artifacts or not.", + "include_exif":"If it is a photo you MUST include information about what camera was likely used and details such as aperture, shutter speed, ISO, etc.", + "exclude_sexual":"Do NOT include anything sexual; keep it PG.", + "exclude_image_resolution":"Do NOT mention the image's resolution.", + "include_aesthetic_quality":"You MUST include information about the subjective aesthetic quality of the image from low to very high.", + "include_composition_style":"Include information on the image's composition style, such as leading lines, rule of thirds, or symmetry.", + "exclude_text":"Do NOT mention any text that is in the image.", + "specify_depth_field":"Specify the depth of field and whether the background is in focus or blurred.", + "specify_lighting_sources":"If applicable, mention the likely use of artificial or natural lighting sources.", + "do_not_use_ambiguous_language":"Do NOT use any ambiguous language.", + "include_nsfw":"Include whether the image is sfw, suggestive, or nsfw.", + "only_describe_most_important_elements":"ONLY describe the most important elements of the image." + } + ret_list = [] + if refer_character_name: + ret_list.append(extra_list["refer_character_name"]) + if exclude_people_info: + ret_list.append(extra_list["exclude_people_info"]) + if include_lighting: + ret_list.append(extra_list["include_lighting"]) + if include_camera_angle: + ret_list.append(extra_list["include_camera_angle"]) + if include_watermark: + ret_list.append(extra_list["include_watermark"]) + if include_JPEG_artifacts: + ret_list.append(extra_list["include_JPEG_artifacts"]) + if include_exif: + ret_list.append(extra_list["include_exif"]) + if exclude_sexual: + ret_list.append(extra_list["exclude_sexual"]) + if exclude_image_resolution: + ret_list.append(extra_list["exclude_image_resolution"]) + if include_aesthetic_quality: + ret_list.append(extra_list["include_aesthetic_quality"]) + if include_composition_style: + ret_list.append(extra_list["include_composition_style"]) + if exclude_text: + ret_list.append(extra_list["exclude_text"]) + if specify_depth_field: + ret_list.append(extra_list["specify_depth_field"]) + if specify_lighting_sources: + ret_list.append(extra_list["specify_lighting_sources"]) + if do_not_use_ambiguous_language: + ret_list.append(extra_list["do_not_use_ambiguous_language"]) + if include_nsfw: + ret_list.append(extra_list["include_nsfw"]) + if only_describe_most_important_elements: + ret_list.append(extra_list["only_describe_most_important_elements"]) + + return ([ret_list, character_name],) + + +class LS_JoyCaption2: + + CATEGORY = '😺dzNodes/LayerUtility' + FUNCTION = "joycaption2" + RETURN_TYPES = ("STRING",) + RETURN_NAMES = ("text",) + OUTPUT_IS_LIST = (True,) + + def __init__(self): + self.NODE_NAME = 'JoyCaption2' + self.previous_model = None + + @classmethod + def INPUT_TYPES(self): + llm_model_list = ["Orenguteng/Llama-3.1-8B-Lexi-Uncensored-V2", "unsloth/Meta-Llama-3.1-8B-Instruct"] + device_list = ['cuda'] + dtype_list = ['nf4','bf16'] + vlm_lora_list = ['text_model', 'none'] + caption_type_list = ["Descriptive", "Descriptive (Informal)", "Training Prompt", "MidJourney", + "Booru tag list", "Booru-like tag list", "Art Critic", "Product Listing", + "Social Media Post"] + caption_length_list = ["any", "very short", "short", "medium-length", "long", "very long"] + [str(i) for i in range(20, 261, 10)] + + return { + "required": { + "image": ("IMAGE",), + "llm_model": (llm_model_list,), + "device": (device_list,), + "dtype": (dtype_list,), + "vlm_lora": (vlm_lora_list,), + "caption_type": (caption_type_list,), + "caption_length": (caption_length_list,), + "user_prompt": ("STRING", {"default": "","multiline": False}), + "max_new_tokens": ("INT", {"default": 300, "min": 8, "max": 4096, "step": 1}), + "top_p": ("FLOAT", {"default": 0.9, "min": 0, "max":1, "step": 0.01}), + "temperature": ("FLOAT", {"default": 0.6, "min": 0, "max":1, "step": 0.01}), + "cache_model": ("BOOLEAN", {"default": False}), + }, + "optional": { + "extra_options": ("JoyCaption2ExtraOption",), + } + } + + def joycaption2(self, image, llm_model, device, dtype, vlm_lora, caption_type, caption_length, + user_prompt, max_new_tokens, top_p, temperature, cache_model, + extra_options=None): + + ret_text = [] + llm_model_path = download_hg_model(llm_model, "LLM") + if self.previous_model is None: + model = load_models(llm_model_path, dtype, vlm_lora, device) + else: + model = self.previous_model + + extra = [] + character_name = "" + if extra_options is not None: + extra, character_name = extra_options + + for img in image: + img = tensor2pil(img.unsqueeze(0)).convert('RGB') + # log(f"{self.NODE_NAME}: caption_type={caption_type}, caption_length={caption_length}, extra={extra}, character_name={character_name}, user_prompt={user_prompt}") + caption = stream_chat([img], caption_type, caption_length, + extra, character_name, user_prompt, + max_new_tokens, top_p, temperature, 1, + model, device) + log(f"{self.NODE_NAME}: caption={caption[0]}") + ret_text.append(caption[0]) + + if cache_model: + self.previous_model = model + else: + self.previous_model = None + del model + clear_memory() + + return (ret_text,) + +class LS_LoadJoyCaption2Model: + + CATEGORY = '😺dzNodes/LayerUtility' + FUNCTION = "load_joycaption2_model" + RETURN_TYPES = ("JoyCaption2_Model",) + RETURN_NAMES = ("joy2_model",) + OUTPUT_IS_LIST = (True,) + + def __init__(self): + self.NODE_NAME = 'LoadJoyCaption2Model' + + @classmethod + def INPUT_TYPES(self): + llm_model_list = ["Orenguteng/Llama-3.1-8B-Lexi-Uncensored-V2", "unsloth/Meta-Llama-3.1-8B-Instruct"] + device_list = ['cuda'] + dtype_list = ['nf4','bf16'] + vlm_lora_list = ['text_model', 'none'] + + return { + "required": { + "llm_model": (llm_model_list,), + "device": (device_list,), + "dtype": (dtype_list,), + "vlm_lora": (vlm_lora_list,), + }, + "optional": { + } + } + + def load_joycaption2_model(self, llm_model, device, dtype, vlm_lora): + llm_model_path = download_hg_model(llm_model, "LLM") + model = load_models(llm_model_path, dtype, vlm_lora, device) + + return ([[model,device]],) + +class LS_JoyCaption2Split: + + CATEGORY = '😺dzNodes/LayerUtility' + FUNCTION = "joycaption2split" + RETURN_TYPES = ("STRING",) + RETURN_NAMES = ("text",) + OUTPUT_IS_LIST = (True,) + + def __init__(self): + self.NODE_NAME = 'JoyCaption2split' + self.previous_model = None + + @classmethod + def INPUT_TYPES(self): + caption_type_list = ["Descriptive", "Descriptive (Informal)", "Training Prompt", "MidJourney", + "Booru tag list", "Booru-like tag list", "Art Critic", "Product Listing", + "Social Media Post"] + caption_length_list = ["any", "very short", "short", "medium-length", "long", "very long"] + [str(i) for i in range(20, 261, 10)] + + return { + "required": { + "image": ("IMAGE",), + "joy2_model": ("JoyCaption2_Model",), + "caption_type": (caption_type_list,), + "caption_length": (caption_length_list,), + "user_prompt": ("STRING", {"default": "","multiline": False}), + "max_new_tokens": ("INT", {"default": 300, "min": 8, "max": 4096, "step": 1}), + "top_p": ("FLOAT", {"default": 0.9, "min": 0, "max": 1, "step": 0.01}), + "temperature": ("FLOAT", {"default": 0.6, "min": 0, "max": 1, "step": 0.01}), + }, + "optional": { + "extra_options": ("JoyCaption2ExtraOption",), + } + } + + def joycaption2split(self, image, joy2_model, caption_type, caption_length, + user_prompt, max_new_tokens, top_p, temperature, + extra_options=None): + + model, device = joy2_model + # device = "cuda" + ret_text = [] + extra = [] + character_name = "" + if extra_options is not None: + extra, character_name = extra_options + + for img in image: + img = tensor2pil(img.unsqueeze(0)).convert('RGB') + # log(f"{self.NODE_NAME}: caption_type={caption_type}, caption_length={caption_length}, extra={extra}, character_name={character_name}, user_prompt={user_prompt}") + caption = stream_chat([img], caption_type, caption_length, + extra, character_name, user_prompt, + max_new_tokens, top_p, temperature, 1, + model, device) + log(f"{self.NODE_NAME}: caption={caption[0]}") + ret_text.append(caption[0]) + + del joy2_model + del model, device + clear_memory() + + return (ret_text,) + + +NODE_CLASS_MAPPINGS = { + "LayerUtility: LoadJoyCaption2Model": LS_LoadJoyCaption2Model, + "LayerUtility: JoyCaption2Split": LS_JoyCaption2Split, + "LayerUtility: JoyCaption2": LS_JoyCaption2, + "LayerUtility: JoyCaption2ExtraOptions": LS_JoyCaptionExtraOptions +} + +NODE_DISPLAY_NAME_MAPPINGS = { + "LayerUtility: LoadJoyCaption2Model": "LayerUtility: Load JoyCaption2 Model(Advance)", + "LayerUtility: JoyCaption2Split": "LayerUtility: JoyCaption2 Split(Advance)", + "LayerUtility: JoyCaption2": "LayerUtility: JoyCaption2(Advance)", + "LayerUtility: JoyCaption2ExtraOptions": "LayerUtility: JoyCaption2 Extra Options(Advance)" +} \ No newline at end of file diff --git a/py/lama.py b/py/lama.py new file mode 100644 index 0000000..5186a04 --- /dev/null +++ b/py/lama.py @@ -0,0 +1,127 @@ +# layerstyle advance + +import os.path +import shutil +from pathlib import Path +from .imagefunc import * + + +NODE_NAME = 'LaMa' + +class LaMa: + + def __init__(self): + pass + + @classmethod + def INPUT_TYPES(self): + model_list = ['lama', 'ldm', 'zits', 'mat', 'fcf', 'manga', 'spread'] + device_list = ['cuda', 'cpu'] + return { + "required": { + "image": ("IMAGE", ), # + "mask": ("MASK",), # + "lama_model": (model_list,), + "device": (device_list,), + "invert_mask": ("BOOLEAN", {"default": False}), # 反转mask + "mask_grow": ("INT", {"default": 25, "min": -255, "max": 255, "step": 1}), + "mask_blur": ("INT", {"default": 8, "min": -255, "max": 255, "step": 1}), + }, + "optional": { + } + } + + RETURN_TYPES = ("IMAGE",) + RETURN_NAMES = ("image",) + FUNCTION = 'lama' + CATEGORY = '😺dzNodes/LayerUtility' + + def lama(self, image, mask, lama_model, device, invert_mask, mask_grow, mask_blur): + log("lama copy") + l_images = [] + l_masks = [] + ret_images = [] + + for l in image: + l_images.append(torch.unsqueeze(l, 0)) + m = tensor2pil(l) + if m.mode == 'RGBA': + l_masks.append(m.split()[-1]) + if mask is not None: + if mask.dim() == 2: + mask = torch.unsqueeze(mask, 0) + l_masks = [] + for m in mask: + if invert_mask: + m = 1 - m + l_masks.append(tensor2pil(torch.unsqueeze(m, 0)).convert('L')) + if len(l_masks) == 0: + log(f"Error: {NODE_NAME} skipped, because the available mask is not found.", message_type='error') + return (image,) + + max_batch = max(len(l_images), len(l_masks)) + + if lama_model == 'spread': + for i in range(max_batch): + _image = l_images[i] if i < len(l_images) else l_images[-1] + _mask = l_masks[i] if i < len(l_masks) else l_masks[-1] + if mask_grow or mask_blur: + _mask = tensor2pil(expand_mask(image2mask(_mask), mask_grow, mask_blur)) + + ret_image = pixel_spread(tensor2pil(_image).convert('RGB'), ImageChops.invert(_mask.convert('RGB'))) + ret_images.append(pil2tensor(ret_image)) + else: + temp_dir = os.path.join(folder_paths.get_temp_directory(), generate_random_name('_lama_', '_temp', 16)) + if os.path.isdir(temp_dir): + shutil.rmtree(temp_dir) + image_dir = os.path.join(temp_dir, 'image') + mask_dir = os.path.join(temp_dir, 'mask') + result_dir = os.path.join(temp_dir, 'result') + config_dir = os.path.join(temp_dir, 'config.json') + + try: + os.makedirs(image_dir) + os.makedirs(mask_dir) + os.makedirs(result_dir) + # Write Config File + with open(config_dir, "w") as file: + json.dump({ + "hd_strategy_crop_trigger_size":1024 + },file) + log(f"config file written: {config_dir}") + except Exception as e: + print(e) + log(f"Error: {NODE_NAME} skipped, because unable to create temporary folder.", message_type='error') + return (image, ) + file_name_list = [] + for i in range(max_batch): + _image = l_images[i] if i < len(l_images) else l_images[-1] + _mask = l_masks[i] if i < len(l_masks) else l_masks[-1] + if mask_grow or mask_blur: + _mask = tensor2pil(expand_mask(image2mask(_mask), mask_grow, mask_blur)) + file_name = os.path.join(generate_random_name('lama_', '_temp', 16) + '.png') + try: + tensor2pil(_image).save(os.path.join(image_dir, file_name)) + _mask.save(os.path.join(mask_dir, file_name)) + except IOError as e: + print(e) + log(f"Error: {NODE_NAME} skipped, because unable to create temporary file.", message_type='error') + return (image, ) + file_name_list.append(file_name) + # process + from .iopaint import cli + cli.run(model=lama_model, device=device, image=Path(image_dir), mask=Path(mask_dir), output=Path(result_dir), config=Path(config_dir)) + ret_images = [pil2tensor(check_image_file(os.path.join(result_dir, file_name), 500)) for file_name in file_name_list] + shutil.rmtree(temp_dir) + + + log(f"{NODE_NAME} Processed {len(ret_images)} image(s).", message_type='finish') + return (torch.cat(ret_images, dim=0),) + +NODE_CLASS_MAPPINGS = { + "LayerUtility: LaMa": LaMa +} + +NODE_DISPLAY_NAME_MAPPINGS = { + "LayerUtility: LaMa": "LayerUtility: LaMa(Advance)" +} diff --git a/py/llama_vision.py b/py/llama_vision.py new file mode 100644 index 0000000..e170898 --- /dev/null +++ b/py/llama_vision.py @@ -0,0 +1,121 @@ +# layerstyle advance + +# Based on https://github.com/SeanScripts/ComfyUI-PixtralLlamaMolmoVision +import os +import comfy.model_management as mm +import folder_paths + +from .imagefunc import tensor2pil, log, clear_memory + +class LS_LlamaVision: + + def __init__(self): + self.NODE_NAME = 'Llama Vision' + self.previous_model = None + + @classmethod + def INPUT_TYPES(s): + model_list = ["Llama-3.2-11B-Vision-Instruct-nf4"] + return { + "required": { + "image": ("IMAGE",), + "model": (model_list,), + "system_prompt": ("STRING", {"default": "You are a helpful AI assistant.", "multiline": True}), + "user_prompt": ("STRING", {"default": "Describe this image in natural language.", "multiline": True}), + "max_new_tokens": ("INT", {"default": 256, "min": 1, "max": 4096}), + "do_sample": ("BOOLEAN", {"default": True}), + "temperature": ("FLOAT", {"default": 0.3, "min": 0.0, "step": 0.1}), + "top_p": ("FLOAT", {"default": 0.9, "min": 0.0, "max": 1.0, "step": 0.1}), + "top_k": ("INT", {"default": 40, "min": 1}), + "stop_strings": ("STRING", {"default": "<|eot_id|>"}), + "seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffff}), + "include_prompt_in_output": ("BOOLEAN", {"default": False}), + "cache_model": ("BOOLEAN", {"default": False}), + }, + "optional": { + }, + } + + CATEGORY = '😺dzNodes/LayerUtility' + FUNCTION = "llama_vision" + RETURN_TYPES = ("STRING",) + RETURN_NAMES = ("text",) + OUTPUT_IS_LIST = (True,) + + def llama_vision(self, image, model, system_prompt, user_prompt, max_new_tokens, do_sample, temperature, + top_p, top_k, stop_strings, seed, include_prompt_in_output, cache_model,): + + from transformers import MllamaForConditionalGeneration, AutoProcessor, GenerationConfig, StopStringCriteria, set_seed + + device = mm.get_torch_device() + if self.previous_model is not None: + llama_vision_model = self.previous_model + else: + model_path = os.path.join(folder_paths.models_dir, 'LLM', model) + # Don't load the full model until needed for generation + processor = AutoProcessor.from_pretrained(model_path) + llama_vision_model = { + 'path': model_path, + 'processor': processor, + } + + if llama_vision_model['path'] and 'model' not in llama_vision_model: + llama_vision_model['model'] = MllamaForConditionalGeneration.from_pretrained( + llama_vision_model['path'], + use_safetensors=True, + device_map=device, + ) + + ret_texts = [] + + for img in image: + img = tensor2pil(img.unsqueeze(0)) + # Process prompt + image_tags = "<|image|>" * len(image) + final_prompt = "<|begin_of_text|>" + if system_prompt != "": + final_prompt += f"<|start_header_id|>system<|end_header_id|>\n\n{system_prompt}<|eot_id|>\n\n" + final_prompt += f"<|start_header_id|>user<|end_header_id|>\n\n{image_tags}{user_prompt}<|eot_id|>\n\n" + final_prompt += "<|start_header_id|>assistant<|end_header_id|>\n\n" + + inputs = llama_vision_model['processor'](images=[img], text=final_prompt, return_tensors="pt").to(device) + prompt_tokens = len(inputs['input_ids'][0]) + stop_strings_list = stop_strings.split(",") + set_seed(seed) + generate_ids = llama_vision_model['model'].generate( + **inputs, + generation_config=GenerationConfig( + max_new_tokens=max_new_tokens, + do_sample=do_sample, + temperature=temperature, + top_p=top_p, + top_k=top_k, + ), + stopping_criteria=[StopStringCriteria(tokenizer=llama_vision_model['processor'].tokenizer, + stop_strings=stop_strings_list)], + ) + + generated_tokens = len(generate_ids[0]) - prompt_tokens + output_tokens = generate_ids[0] if include_prompt_in_output else generate_ids[0][prompt_tokens:] + output = llama_vision_model['processor'].decode(output_tokens, skip_special_tokens=True, + clean_up_tokenization_spaces=False) + log(f"{self.NODE_NAME} generated: {output}") + ret_texts.append(output) + + if cache_model: + self.previous_model = llama_vision_model + else: + self.previous_model = None + del llama_vision_model + clear_memory() + log(f"{self.NODE_NAME} generated {len(ret_texts)} texts.") + return (ret_texts,) + + +NODE_CLASS_MAPPINGS = { + "LayerUtility: LlamaVision": LS_LlamaVision +} + +NODE_DISPLAY_NAME_MAPPINGS = { + "LayerUtility: LlamaVision": "LayerUtility: Llama Vision(Advance)" +} \ No newline at end of file diff --git a/py/loadpsd.py b/py/loadpsd.py new file mode 100644 index 0000000..a75adc2 --- /dev/null +++ b/py/loadpsd.py @@ -0,0 +1,109 @@ +# layerstyle advance + +import os +import numpy as np +import torch +import folder_paths +# import node_helpers +from nodes import LoadImage +from PIL import Image,ImageOps,ImageSequence,ImageDraw,ImageFont +from .imagefunc import pil2tensor, log, generate_text_image, get_resource_dir + + +class LoadPSD(LoadImage): + @classmethod + def INPUT_TYPES(s): + input_dir = folder_paths.get_input_directory() + files = [f for f in os.listdir(input_dir) if os.path.isfile( + os.path.join(input_dir, f)) and f.endswith(".psd")] + fine_layer_method = ["layer_index", "layer_name"] + return {"required":{ + "image": (sorted(files), {"image_upload": True}), + "file_path": ("STRING", {"default": ""}), + "include_hidden_layer": ("BOOLEAN", {"default": False}), + "find_layer_by": (fine_layer_method,), + "layer_index": ("INT", {"default": 0, "min": -1, "max": 999, "step": 1}), + "layer_name": ("STRING", {"default": ""}), + }, + "optional": { + } + } + + + RETURN_TYPES = ("IMAGE", "IMAGE", "IMAGE",) + RETURN_NAMES = ("flat_image", "layer_image", "all_layers",) + FUNCTION = "load_psd" + CATEGORY = '😺dzNodes/LayerUtility/SystemIO' + + def load_psd(self, image, file_path, include_hidden_layer, layer_index, find_layer_by, layer_name,): + + from psd_tools import PSDImage + from psd_tools.api.layers import Layer + + (LUT_DICT, FONT_DICT) = get_resource_dir() + + NODE_NAME = 'LoadPSD' + number_of_layers = 1 + layer_image = [] + all_layers = [] + if file_path == "": + psd_file_path = folder_paths.get_annotated_filepath(image) + else: + psd_file_path = folder_paths.get_annotated_filepath(file_path) + flat_image = Image.open(psd_file_path).convert("RGB") + width, height = flat_image.size + + if image.endswith(".psd"): + from psd_tools import PSDImage + from psd_tools.api.layers import Layer + log(f"{NODE_NAME} -> Loading PSD file: {psd_file_path}") + psd_image = PSDImage.open(psd_file_path) + layers = [] + for layer in psd_image: + if include_hidden_layer: + if not layer.is_visible(): + layer.visible = True + layers.append(layer) + else: + if layer.is_visible(): + layers.append(layer) + + number_of_layers = len(layers) + for i in range(number_of_layers): + layer_canvas = Image.new("RGBA", (width, height), (0, 0, 0, 0)) + layer_canvas.paste(layers[i].composite(), layers[i].bbox) + all_layers.append(pil2tensor(layer_canvas)) + if find_layer_by == "layer_name": + if layers[i].name == layer_name: + layer_image.append(pil2tensor(layer_canvas)) + log(f"{NODE_NAME} -> Layer {i} : {layer.name} found.") + elif find_layer_by == "layer_index": + if i == layer_index: + layer_image.append(pil2tensor(layer_canvas)) + log(f"{NODE_NAME} -> Layer {i} : {layer.name} found.") + + text = "Layer Not Found!" + font_file = list(FONT_DICT.values())[0] + empty_layer_image = generate_text_image(flat_image.width, flat_image.height, text, font_file, font_color="#F01000") + if layer_image == []: + if layer_index == -1: + layer_image.append(all_layers[-1]) + elif find_layer_by == "layer_name": + log(f'{NODE_NAME} -> Layer "{layer_name}" not found, top layer will be output.', message_type="warning") + elif find_layer_by == "layer_index": + log(f'{NODE_NAME} -> Layer index {layer_index} not found, top layer will be output.', message_type="warning") + layer_image.append(pil2tensor(empty_layer_image)) + else: + layer_image.append(pil2tensor(flat_image)) + all_layers.append(pil2tensor(flat_image)) + + return (torch.cat([pil2tensor(flat_image),], dim=0), torch.cat(layer_image, dim=0), torch.cat(all_layers, dim=0),) + + +NODE_CLASS_MAPPINGS = { + "LayerUtility: LoadPSD": LoadPSD, +} + +NODE_DISPLAY_NAME_MAPPINGS = { + "LayerUtility: LoadPSD": "LayerUtility: Load PSD(Advance)", +} \ No newline at end of file diff --git a/py/local_groundingdino/datasets/__init__.py b/py/local_groundingdino/datasets/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/py/local_groundingdino/datasets/transforms.py b/py/local_groundingdino/datasets/transforms.py new file mode 100644 index 0000000..8f0cbf3 --- /dev/null +++ b/py/local_groundingdino/datasets/transforms.py @@ -0,0 +1,311 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved +""" +Transforms and data augmentation for both image + bbox. +""" +import os +import random + +import PIL +import torch +import torchvision.transforms as T +import torchvision.transforms.functional as F + +from local_groundingdino.util.box_ops import box_xyxy_to_cxcywh +from local_groundingdino.util.misc import interpolate + + +def crop(image, target, region): + cropped_image = F.crop(image, *region) + + target = target.copy() + i, j, h, w = region + + # should we do something wrt the original size? + target["size"] = torch.tensor([h, w]) + + fields = ["labels", "area", "iscrowd", "positive_map"] + + if "boxes" in target: + boxes = target["boxes"] + max_size = torch.as_tensor([w, h], dtype=torch.float32) + cropped_boxes = boxes - torch.as_tensor([j, i, j, i]) + cropped_boxes = torch.min(cropped_boxes.reshape(-1, 2, 2), max_size) + cropped_boxes = cropped_boxes.clamp(min=0) + area = (cropped_boxes[:, 1, :] - cropped_boxes[:, 0, :]).prod(dim=1) + target["boxes"] = cropped_boxes.reshape(-1, 4) + target["area"] = area + fields.append("boxes") + + if "masks" in target: + # FIXME should we update the area here if there are no boxes? + target["masks"] = target["masks"][:, i : i + h, j : j + w] + fields.append("masks") + + # remove elements for which the boxes or masks that have zero area + if "boxes" in target or "masks" in target: + # favor boxes selection when defining which elements to keep + # this is compatible with previous implementation + if "boxes" in target: + cropped_boxes = target["boxes"].reshape(-1, 2, 2) + keep = torch.all(cropped_boxes[:, 1, :] > cropped_boxes[:, 0, :], dim=1) + else: + keep = target["masks"].flatten(1).any(1) + + for field in fields: + if field in target: + target[field] = target[field][keep] + + if os.environ.get("IPDB_SHILONG_DEBUG", None) == "INFO": + # for debug and visualization only. + if "strings_positive" in target: + target["strings_positive"] = [ + _i for _i, _j in zip(target["strings_positive"], keep) if _j + ] + + return cropped_image, target + + +def hflip(image, target): + flipped_image = F.hflip(image) + + w, h = image.size + + target = target.copy() + if "boxes" in target: + boxes = target["boxes"] + boxes = boxes[:, [2, 1, 0, 3]] * torch.as_tensor([-1, 1, -1, 1]) + torch.as_tensor( + [w, 0, w, 0] + ) + target["boxes"] = boxes + + if "masks" in target: + target["masks"] = target["masks"].flip(-1) + + return flipped_image, target + + +def resize(image, target, size, max_size=None): + # size can be min_size (scalar) or (w, h) tuple + + def get_size_with_aspect_ratio(image_size, size, max_size=None): + w, h = image_size + if max_size is not None: + min_original_size = float(min((w, h))) + max_original_size = float(max((w, h))) + if max_original_size / min_original_size * size > max_size: + size = int(round(max_size * min_original_size / max_original_size)) + + if (w <= h and w == size) or (h <= w and h == size): + return (h, w) + + if w < h: + ow = size + oh = int(size * h / w) + else: + oh = size + ow = int(size * w / h) + + return (oh, ow) + + def get_size(image_size, size, max_size=None): + if isinstance(size, (list, tuple)): + return size[::-1] + else: + return get_size_with_aspect_ratio(image_size, size, max_size) + + size = get_size(image.size, size, max_size) + rescaled_image = F.resize(image, size) + + if target is None: + return rescaled_image, None + + ratios = tuple(float(s) / float(s_orig) for s, s_orig in zip(rescaled_image.size, image.size)) + ratio_width, ratio_height = ratios + + target = target.copy() + if "boxes" in target: + boxes = target["boxes"] + scaled_boxes = boxes * torch.as_tensor( + [ratio_width, ratio_height, ratio_width, ratio_height] + ) + target["boxes"] = scaled_boxes + + if "area" in target: + area = target["area"] + scaled_area = area * (ratio_width * ratio_height) + target["area"] = scaled_area + + h, w = size + target["size"] = torch.tensor([h, w]) + + if "masks" in target: + target["masks"] = ( + interpolate(target["masks"][:, None].float(), size, mode="nearest")[:, 0] > 0.5 + ) + + return rescaled_image, target + + +def pad(image, target, padding): + # assumes that we only pad on the bottom right corners + padded_image = F.pad(image, (0, 0, padding[0], padding[1])) + if target is None: + return padded_image, None + target = target.copy() + # should we do something wrt the original size? + target["size"] = torch.tensor(padded_image.size[::-1]) + if "masks" in target: + target["masks"] = torch.nn.functional.pad(target["masks"], (0, padding[0], 0, padding[1])) + return padded_image, target + + +class ResizeDebug(object): + def __init__(self, size): + self.size = size + + def __call__(self, img, target): + return resize(img, target, self.size) + + +class RandomCrop(object): + def __init__(self, size): + self.size = size + + def __call__(self, img, target): + region = T.RandomCrop.get_params(img, self.size) + return crop(img, target, region) + + +class RandomSizeCrop(object): + def __init__(self, min_size: int, max_size: int, respect_boxes: bool = False): + # respect_boxes: True to keep all boxes + # False to tolerence box filter + self.min_size = min_size + self.max_size = max_size + self.respect_boxes = respect_boxes + + def __call__(self, img: PIL.Image.Image, target: dict): + init_boxes = len(target["boxes"]) + max_patience = 10 + for i in range(max_patience): + w = random.randint(self.min_size, min(img.width, self.max_size)) + h = random.randint(self.min_size, min(img.height, self.max_size)) + region = T.RandomCrop.get_params(img, [h, w]) + result_img, result_target = crop(img, target, region) + if ( + not self.respect_boxes + or len(result_target["boxes"]) == init_boxes + or i == max_patience - 1 + ): + return result_img, result_target + return result_img, result_target + + +class CenterCrop(object): + def __init__(self, size): + self.size = size + + def __call__(self, img, target): + image_width, image_height = img.size + crop_height, crop_width = self.size + crop_top = int(round((image_height - crop_height) / 2.0)) + crop_left = int(round((image_width - crop_width) / 2.0)) + return crop(img, target, (crop_top, crop_left, crop_height, crop_width)) + + +class RandomHorizontalFlip(object): + def __init__(self, p=0.5): + self.p = p + + def __call__(self, img, target): + if random.random() < self.p: + return hflip(img, target) + return img, target + + +class RandomResize(object): + def __init__(self, sizes, max_size=None): + assert isinstance(sizes, (list, tuple)) + self.sizes = sizes + self.max_size = max_size + + def __call__(self, img, target=None): + size = random.choice(self.sizes) + return resize(img, target, size, self.max_size) + + +class RandomPad(object): + def __init__(self, max_pad): + self.max_pad = max_pad + + def __call__(self, img, target): + pad_x = random.randint(0, self.max_pad) + pad_y = random.randint(0, self.max_pad) + return pad(img, target, (pad_x, pad_y)) + + +class RandomSelect(object): + """ + Randomly selects between transforms1 and transforms2, + with probability p for transforms1 and (1 - p) for transforms2 + """ + + def __init__(self, transforms1, transforms2, p=0.5): + self.transforms1 = transforms1 + self.transforms2 = transforms2 + self.p = p + + def __call__(self, img, target): + if random.random() < self.p: + return self.transforms1(img, target) + return self.transforms2(img, target) + + +class ToTensor(object): + def __call__(self, img, target): + return F.to_tensor(img), target + + +class RandomErasing(object): + def __init__(self, *args, **kwargs): + self.eraser = T.RandomErasing(*args, **kwargs) + + def __call__(self, img, target): + return self.eraser(img), target + + +class Normalize(object): + def __init__(self, mean, std): + self.mean = mean + self.std = std + + def __call__(self, image, target=None): + image = F.normalize(image, mean=self.mean, std=self.std) + if target is None: + return image, None + target = target.copy() + h, w = image.shape[-2:] + if "boxes" in target: + boxes = target["boxes"] + boxes = box_xyxy_to_cxcywh(boxes) + boxes = boxes / torch.tensor([w, h, w, h], dtype=torch.float32) + target["boxes"] = boxes + return image, target + + +class Compose(object): + def __init__(self, transforms): + self.transforms = transforms + + def __call__(self, image, target): + for t in self.transforms: + image, target = t(image, target) + return image, target + + def __repr__(self): + format_string = self.__class__.__name__ + "(" + for t in self.transforms: + format_string += "\n" + format_string += " {0}".format(t) + format_string += "\n)" + return format_string diff --git a/py/local_groundingdino/models/GroundingDINO/__init__.py b/py/local_groundingdino/models/GroundingDINO/__init__.py new file mode 100644 index 0000000..2af819d --- /dev/null +++ b/py/local_groundingdino/models/GroundingDINO/__init__.py @@ -0,0 +1,15 @@ +# ------------------------------------------------------------------------ +# Grounding DINO +# url: https://github.com/IDEA-Research/GroundingDINO +# Copyright (c) 2023 IDEA. All Rights Reserved. +# Licensed under the Apache License, Version 2.0 [see LICENSE for details] +# ------------------------------------------------------------------------ +# Conditional DETR +# Copyright (c) 2021 Microsoft. All Rights Reserved. +# Licensed under the Apache License, Version 2.0 [see LICENSE for details] +# ------------------------------------------------------------------------ +# Copied from DETR (https://github.com/facebookresearch/detr) +# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. +# ------------------------------------------------------------------------ + +from .groundingdino import build_groundingdino diff --git a/py/local_groundingdino/models/GroundingDINO/backbone/__init__.py b/py/local_groundingdino/models/GroundingDINO/backbone/__init__.py new file mode 100644 index 0000000..76e4b27 --- /dev/null +++ b/py/local_groundingdino/models/GroundingDINO/backbone/__init__.py @@ -0,0 +1 @@ +from .backbone import build_backbone diff --git a/py/local_groundingdino/models/GroundingDINO/backbone/backbone.py b/py/local_groundingdino/models/GroundingDINO/backbone/backbone.py new file mode 100644 index 0000000..fb150d3 --- /dev/null +++ b/py/local_groundingdino/models/GroundingDINO/backbone/backbone.py @@ -0,0 +1,221 @@ +# ------------------------------------------------------------------------ +# Grounding DINO +# url: https://github.com/IDEA-Research/GroundingDINO +# Copyright (c) 2023 IDEA. All Rights Reserved. +# Licensed under the Apache License, Version 2.0 [see LICENSE for details] +# ------------------------------------------------------------------------ +# Conditional DETR +# Copyright (c) 2021 Microsoft. All Rights Reserved. +# Licensed under the Apache License, Version 2.0 [see LICENSE for details] +# ------------------------------------------------------------------------ +# Copied from DETR (https://github.com/facebookresearch/detr) +# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. +# ------------------------------------------------------------------------ + +""" +Backbone modules. +""" + +from typing import Dict, List + +import torch +import torch.nn.functional as F +import torchvision +from torch import nn +from torchvision.models._utils import IntermediateLayerGetter + +from local_groundingdino.util.misc import NestedTensor, is_main_process + +from .position_encoding import build_position_encoding +from .swin_transformer import build_swin_transformer + + +class FrozenBatchNorm2d(torch.nn.Module): + """ + BatchNorm2d where the batch statistics and the affine parameters are fixed. + + Copy-paste from torchvision.misc.ops with added eps before rqsrt, + without which any other models than torchvision.models.resnet[18,34,50,101] + produce nans. + """ + + def __init__(self, n): + super(FrozenBatchNorm2d, self).__init__() + self.register_buffer("weight", torch.ones(n)) + self.register_buffer("bias", torch.zeros(n)) + self.register_buffer("running_mean", torch.zeros(n)) + self.register_buffer("running_var", torch.ones(n)) + + def _load_from_state_dict( + self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs + ): + num_batches_tracked_key = prefix + "num_batches_tracked" + if num_batches_tracked_key in state_dict: + del state_dict[num_batches_tracked_key] + + super(FrozenBatchNorm2d, self)._load_from_state_dict( + state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs + ) + + def forward(self, x): + # move reshapes to the beginning + # to make it fuser-friendly + w = self.weight.reshape(1, -1, 1, 1) + b = self.bias.reshape(1, -1, 1, 1) + rv = self.running_var.reshape(1, -1, 1, 1) + rm = self.running_mean.reshape(1, -1, 1, 1) + eps = 1e-5 + scale = w * (rv + eps).rsqrt() + bias = b - rm * scale + return x * scale + bias + + +class BackboneBase(nn.Module): + def __init__( + self, + backbone: nn.Module, + train_backbone: bool, + num_channels: int, + return_interm_indices: list, + ): + super().__init__() + for name, parameter in backbone.named_parameters(): + if ( + not train_backbone + or "layer2" not in name + and "layer3" not in name + and "layer4" not in name + ): + parameter.requires_grad_(False) + + return_layers = {} + for idx, layer_index in enumerate(return_interm_indices): + return_layers.update( + {"layer{}".format(5 - len(return_interm_indices) + idx): "{}".format(layer_index)} + ) + + # if len: + # if use_stage1_feature: + # return_layers = {"layer1": "0", "layer2": "1", "layer3": "2", "layer4": "3"} + # else: + # return_layers = {"layer2": "0", "layer3": "1", "layer4": "2"} + # else: + # return_layers = {'layer4': "0"} + self.body = IntermediateLayerGetter(backbone, return_layers=return_layers) + self.num_channels = num_channels + + def forward(self, tensor_list: NestedTensor): + xs = self.body(tensor_list.tensors) + out: Dict[str, NestedTensor] = {} + for name, x in xs.items(): + m = tensor_list.mask + assert m is not None + mask = F.interpolate(m[None].float(), size=x.shape[-2:]).to(torch.bool)[0] + out[name] = NestedTensor(x, mask) + # import ipdb; ipdb.set_trace() + return out + + +class Backbone(BackboneBase): + """ResNet backbone with frozen BatchNorm.""" + + def __init__( + self, + name: str, + train_backbone: bool, + dilation: bool, + return_interm_indices: list, + batch_norm=FrozenBatchNorm2d, + ): + if name in ["resnet18", "resnet34", "resnet50", "resnet101"]: + backbone = getattr(torchvision.models, name)( + replace_stride_with_dilation=[False, False, dilation], + pretrained=is_main_process(), + norm_layer=batch_norm, + ) + else: + raise NotImplementedError("Why you can get here with name {}".format(name)) + # num_channels = 512 if name in ('resnet18', 'resnet34') else 2048 + assert name not in ("resnet18", "resnet34"), "Only resnet50 and resnet101 are available." + assert return_interm_indices in [[0, 1, 2, 3], [1, 2, 3], [3]] + num_channels_all = [256, 512, 1024, 2048] + num_channels = num_channels_all[4 - len(return_interm_indices) :] + super().__init__(backbone, train_backbone, num_channels, return_interm_indices) + + +class Joiner(nn.Sequential): + def __init__(self, backbone, position_embedding): + super().__init__(backbone, position_embedding) + + def forward(self, tensor_list: NestedTensor): + xs = self[0](tensor_list) + out: List[NestedTensor] = [] + pos = [] + for name, x in xs.items(): + out.append(x) + # position encoding + pos.append(self[1](x).to(x.tensors.dtype)) + + return out, pos + + +def build_backbone(args): + """ + Useful args: + - backbone: backbone name + - lr_backbone: + - dilation + - return_interm_indices: available: [0,1,2,3], [1,2,3], [3] + - backbone_freeze_keywords: + - use_checkpoint: for swin only for now + + """ + position_embedding = build_position_encoding(args) + train_backbone = True + if not train_backbone: + raise ValueError("Please set lr_backbone > 0") + return_interm_indices = args.return_interm_indices + assert return_interm_indices in [[0, 1, 2, 3], [1, 2, 3], [3]] + args.backbone_freeze_keywords + use_checkpoint = getattr(args, "use_checkpoint", False) + + if args.backbone in ["resnet50", "resnet101"]: + backbone = Backbone( + args.backbone, + train_backbone, + args.dilation, + return_interm_indices, + batch_norm=FrozenBatchNorm2d, + ) + bb_num_channels = backbone.num_channels + elif args.backbone in [ + "swin_T_224_1k", + "swin_B_224_22k", + "swin_B_384_22k", + "swin_L_224_22k", + "swin_L_384_22k", + ]: + pretrain_img_size = int(args.backbone.split("_")[-2]) + backbone = build_swin_transformer( + args.backbone, + pretrain_img_size=pretrain_img_size, + out_indices=tuple(return_interm_indices), + dilation=False, + use_checkpoint=use_checkpoint, + ) + + bb_num_channels = backbone.num_features[4 - len(return_interm_indices) :] + else: + raise NotImplementedError("Unknown backbone {}".format(args.backbone)) + + assert len(bb_num_channels) == len( + return_interm_indices + ), f"len(bb_num_channels) {len(bb_num_channels)} != len(return_interm_indices) {len(return_interm_indices)}" + + model = Joiner(backbone, position_embedding) + model.num_channels = bb_num_channels + assert isinstance( + bb_num_channels, List + ), "bb_num_channels is expected to be a List but {}".format(type(bb_num_channels)) + # import ipdb; ipdb.set_trace() + return model diff --git a/py/local_groundingdino/models/GroundingDINO/backbone/position_encoding.py b/py/local_groundingdino/models/GroundingDINO/backbone/position_encoding.py new file mode 100644 index 0000000..e200633 --- /dev/null +++ b/py/local_groundingdino/models/GroundingDINO/backbone/position_encoding.py @@ -0,0 +1,186 @@ +# ------------------------------------------------------------------------ +# Grounding DINO +# url: https://github.com/IDEA-Research/GroundingDINO +# Copyright (c) 2023 IDEA. All Rights Reserved. +# Licensed under the Apache License, Version 2.0 [see LICENSE for details] +# ------------------------------------------------------------------------ +# DINO +# Copyright (c) 2022 IDEA. All Rights Reserved. +# Licensed under the Apache License, Version 2.0 [see LICENSE for details] +# ------------------------------------------------------------------------ +# Conditional DETR +# Copyright (c) 2021 Microsoft. All Rights Reserved. +# Licensed under the Apache License, Version 2.0 [see LICENSE for details] +# ------------------------------------------------------------------------ +# Copied from DETR (https://github.com/facebookresearch/detr) +# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. +# ------------------------------------------------------------------------ + +""" +Various positional encodings for the transformer. +""" +import math + +import torch +from torch import nn + +from local_groundingdino.util.misc import NestedTensor + + +class PositionEmbeddingSine(nn.Module): + """ + This is a more standard version of the position embedding, very similar to the one + used by the Attention is all you need paper, generalized to work on images. + """ + + def __init__(self, num_pos_feats=64, temperature=10000, normalize=False, scale=None): + super().__init__() + self.num_pos_feats = num_pos_feats + self.temperature = temperature + self.normalize = normalize + if scale is not None and normalize is False: + raise ValueError("normalize should be True if scale is passed") + if scale is None: + scale = 2 * math.pi + self.scale = scale + + def forward(self, tensor_list: NestedTensor): + x = tensor_list.tensors + mask = tensor_list.mask + assert mask is not None + not_mask = ~mask + y_embed = not_mask.cumsum(1, dtype=torch.float32) + x_embed = not_mask.cumsum(2, dtype=torch.float32) + if self.normalize: + eps = 1e-6 + # if os.environ.get("SHILONG_AMP", None) == '1': + # eps = 1e-4 + # else: + # eps = 1e-6 + y_embed = y_embed / (y_embed[:, -1:, :] + eps) * self.scale + x_embed = x_embed / (x_embed[:, :, -1:] + eps) * self.scale + + dim_t = torch.arange(self.num_pos_feats, dtype=torch.float32, device=x.device) + dim_t = self.temperature ** (2 * (dim_t // 2) / self.num_pos_feats) + + pos_x = x_embed[:, :, :, None] / dim_t + pos_y = y_embed[:, :, :, None] / dim_t + pos_x = torch.stack( + (pos_x[:, :, :, 0::2].sin(), pos_x[:, :, :, 1::2].cos()), dim=4 + ).flatten(3) + pos_y = torch.stack( + (pos_y[:, :, :, 0::2].sin(), pos_y[:, :, :, 1::2].cos()), dim=4 + ).flatten(3) + pos = torch.cat((pos_y, pos_x), dim=3).permute(0, 3, 1, 2) + return pos + + +class PositionEmbeddingSineHW(nn.Module): + """ + This is a more standard version of the position embedding, very similar to the one + used by the Attention is all you need paper, generalized to work on images. + """ + + def __init__( + self, num_pos_feats=64, temperatureH=10000, temperatureW=10000, normalize=False, scale=None + ): + super().__init__() + self.num_pos_feats = num_pos_feats + self.temperatureH = temperatureH + self.temperatureW = temperatureW + self.normalize = normalize + if scale is not None and normalize is False: + raise ValueError("normalize should be True if scale is passed") + if scale is None: + scale = 2 * math.pi + self.scale = scale + + def forward(self, tensor_list: NestedTensor): + x = tensor_list.tensors + mask = tensor_list.mask + assert mask is not None + not_mask = ~mask + y_embed = not_mask.cumsum(1, dtype=torch.float32) + x_embed = not_mask.cumsum(2, dtype=torch.float32) + + # import ipdb; ipdb.set_trace() + + if self.normalize: + eps = 1e-6 + y_embed = y_embed / (y_embed[:, -1:, :] + eps) * self.scale + x_embed = x_embed / (x_embed[:, :, -1:] + eps) * self.scale + + dim_tx = torch.arange(self.num_pos_feats, dtype=torch.float32, device=x.device) + dim_tx = self.temperatureW ** (2 * (torch.div(dim_tx, 2, rounding_mode='floor')) / self.num_pos_feats) + pos_x = x_embed[:, :, :, None] / dim_tx + + dim_ty = torch.arange(self.num_pos_feats, dtype=torch.float32, device=x.device) + dim_ty = self.temperatureH ** (2 * (torch.div(dim_ty, 2, rounding_mode='floor')) / self.num_pos_feats) + pos_y = y_embed[:, :, :, None] / dim_ty + + pos_x = torch.stack( + (pos_x[:, :, :, 0::2].sin(), pos_x[:, :, :, 1::2].cos()), dim=4 + ).flatten(3) + pos_y = torch.stack( + (pos_y[:, :, :, 0::2].sin(), pos_y[:, :, :, 1::2].cos()), dim=4 + ).flatten(3) + pos = torch.cat((pos_y, pos_x), dim=3).permute(0, 3, 1, 2) + + # import ipdb; ipdb.set_trace() + + return pos + + +class PositionEmbeddingLearned(nn.Module): + """ + Absolute pos embedding, learned. + """ + + def __init__(self, num_pos_feats=256): + super().__init__() + self.row_embed = nn.Embedding(50, num_pos_feats) + self.col_embed = nn.Embedding(50, num_pos_feats) + self.reset_parameters() + + def reset_parameters(self): + nn.init.uniform_(self.row_embed.weight) + nn.init.uniform_(self.col_embed.weight) + + def forward(self, tensor_list: NestedTensor): + x = tensor_list.tensors + h, w = x.shape[-2:] + i = torch.arange(w, device=x.device) + j = torch.arange(h, device=x.device) + x_emb = self.col_embed(i) + y_emb = self.row_embed(j) + pos = ( + torch.cat( + [ + x_emb.unsqueeze(0).repeat(h, 1, 1), + y_emb.unsqueeze(1).repeat(1, w, 1), + ], + dim=-1, + ) + .permute(2, 0, 1) + .unsqueeze(0) + .repeat(x.shape[0], 1, 1, 1) + ) + return pos + + +def build_position_encoding(args): + N_steps = args.hidden_dim // 2 + if args.position_embedding in ("v2", "sine"): + # TODO find a better way of exposing other arguments + position_embedding = PositionEmbeddingSineHW( + N_steps, + temperatureH=args.pe_temperatureH, + temperatureW=args.pe_temperatureW, + normalize=True, + ) + elif args.position_embedding in ("v3", "learned"): + position_embedding = PositionEmbeddingLearned(N_steps) + else: + raise ValueError(f"not supported {args.position_embedding}") + + return position_embedding diff --git a/py/local_groundingdino/models/GroundingDINO/backbone/swin_transformer.py b/py/local_groundingdino/models/GroundingDINO/backbone/swin_transformer.py new file mode 100644 index 0000000..c35b5c2 --- /dev/null +++ b/py/local_groundingdino/models/GroundingDINO/backbone/swin_transformer.py @@ -0,0 +1,802 @@ +# ------------------------------------------------------------------------ +# Grounding DINO +# url: https://github.com/IDEA-Research/GroundingDINO +# Copyright (c) 2023 IDEA. All Rights Reserved. +# Licensed under the Apache License, Version 2.0 [see LICENSE for details] +# ------------------------------------------------------------------------ +# DINO +# Copyright (c) 2022 IDEA. All Rights Reserved. +# Licensed under the Apache License, Version 2.0 [see LICENSE for details] +# -------------------------------------------------------- +# modified from https://github.com/SwinTransformer/Swin-Transformer-Object-Detection/blob/master/mmdet/models/backbones/swin_transformer.py +# -------------------------------------------------------- + +import numpy as np +import torch +import torch.nn as nn +import torch.nn.functional as F +import torch.utils.checkpoint as checkpoint +from timm.models.layers import DropPath, to_2tuple, trunc_normal_ + +from local_groundingdino.util.misc import NestedTensor + + +class Mlp(nn.Module): + """Multilayer perceptron.""" + + def __init__( + self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.0 + ): + super().__init__() + out_features = out_features or in_features + hidden_features = hidden_features or in_features + self.fc1 = nn.Linear(in_features, hidden_features) + self.act = act_layer() + self.fc2 = nn.Linear(hidden_features, out_features) + self.drop = nn.Dropout(drop) + + def forward(self, x): + x = self.fc1(x) + x = self.act(x) + x = self.drop(x) + x = self.fc2(x) + x = self.drop(x) + return x + + +def window_partition(x, window_size): + """ + Args: + x: (B, H, W, C) + window_size (int): window size + Returns: + windows: (num_windows*B, window_size, window_size, C) + """ + B, H, W, C = x.shape + x = x.view(B, H // window_size, window_size, W // window_size, window_size, C) + windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C) + return windows + + +def window_reverse(windows, window_size, H, W): + """ + Args: + windows: (num_windows*B, window_size, window_size, C) + window_size (int): Window size + H (int): Height of image + W (int): Width of image + Returns: + x: (B, H, W, C) + """ + B = int(windows.shape[0] / (H * W / window_size / window_size)) + x = windows.view(B, H // window_size, W // window_size, window_size, window_size, -1) + x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1) + return x + + +class WindowAttention(nn.Module): + """Window based multi-head self attention (W-MSA) module with relative position bias. + It supports both of shifted and non-shifted window. + Args: + dim (int): Number of input channels. + window_size (tuple[int]): The height and width of the window. + num_heads (int): Number of attention heads. + qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True + qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set + attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0 + proj_drop (float, optional): Dropout ratio of output. Default: 0.0 + """ + + def __init__( + self, + dim, + window_size, + num_heads, + qkv_bias=True, + qk_scale=None, + attn_drop=0.0, + proj_drop=0.0, + ): + + super().__init__() + self.dim = dim + self.window_size = window_size # Wh, Ww + self.num_heads = num_heads + head_dim = dim // num_heads + self.scale = qk_scale or head_dim**-0.5 + + # define a parameter table of relative position bias + self.relative_position_bias_table = nn.Parameter( + torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1), num_heads) + ) # 2*Wh-1 * 2*Ww-1, nH + + # get pair-wise relative position index for each token inside the window + coords_h = torch.arange(self.window_size[0]) + coords_w = torch.arange(self.window_size[1]) + coords = torch.stack(torch.meshgrid([coords_h, coords_w])) # 2, Wh, Ww + coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww + relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww + relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2 + relative_coords[:, :, 0] += self.window_size[0] - 1 # shift to start from 0 + relative_coords[:, :, 1] += self.window_size[1] - 1 + relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1 + relative_position_index = relative_coords.sum(-1) # Wh*Ww, Wh*Ww + self.register_buffer("relative_position_index", relative_position_index) + + self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) + self.attn_drop = nn.Dropout(attn_drop) + self.proj = nn.Linear(dim, dim) + self.proj_drop = nn.Dropout(proj_drop) + + trunc_normal_(self.relative_position_bias_table, std=0.02) + self.softmax = nn.Softmax(dim=-1) + + def forward(self, x, mask=None): + """Forward function. + Args: + x: input features with shape of (num_windows*B, N, C) + mask: (0/-inf) mask with shape of (num_windows, Wh*Ww, Wh*Ww) or None + """ + B_, N, C = x.shape + qkv = ( + self.qkv(x) + .reshape(B_, N, 3, self.num_heads, C // self.num_heads) + .permute(2, 0, 3, 1, 4) + ) + q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple) + + q = q * self.scale + attn = q @ k.transpose(-2, -1) + + relative_position_bias = self.relative_position_bias_table[ + self.relative_position_index.view(-1) + ].view( + self.window_size[0] * self.window_size[1], self.window_size[0] * self.window_size[1], -1 + ) # Wh*Ww,Wh*Ww,nH + relative_position_bias = relative_position_bias.permute( + 2, 0, 1 + ).contiguous() # nH, Wh*Ww, Wh*Ww + attn = attn + relative_position_bias.unsqueeze(0) + + if mask is not None: + nW = mask.shape[0] + attn = attn.view(B_ // nW, nW, self.num_heads, N, N) + mask.unsqueeze(1).unsqueeze(0) + attn = attn.view(-1, self.num_heads, N, N) + attn = self.softmax(attn) + else: + attn = self.softmax(attn) + + attn = self.attn_drop(attn) + + x = (attn @ v).transpose(1, 2).reshape(B_, N, C) + x = self.proj(x) + x = self.proj_drop(x) + return x + + +class SwinTransformerBlock(nn.Module): + """Swin Transformer Block. + Args: + dim (int): Number of input channels. + num_heads (int): Number of attention heads. + window_size (int): Window size. + shift_size (int): Shift size for SW-MSA. + mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. + qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True + qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set. + drop (float, optional): Dropout rate. Default: 0.0 + attn_drop (float, optional): Attention dropout rate. Default: 0.0 + drop_path (float, optional): Stochastic depth rate. Default: 0.0 + act_layer (nn.Module, optional): Activation layer. Default: nn.GELU + norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm + """ + + def __init__( + self, + dim, + num_heads, + window_size=7, + shift_size=0, + mlp_ratio=4.0, + qkv_bias=True, + qk_scale=None, + drop=0.0, + attn_drop=0.0, + drop_path=0.0, + act_layer=nn.GELU, + norm_layer=nn.LayerNorm, + ): + super().__init__() + self.dim = dim + self.num_heads = num_heads + self.window_size = window_size + self.shift_size = shift_size + self.mlp_ratio = mlp_ratio + assert 0 <= self.shift_size < self.window_size, "shift_size must in 0-window_size" + + self.norm1 = norm_layer(dim) + self.attn = WindowAttention( + dim, + window_size=to_2tuple(self.window_size), + num_heads=num_heads, + qkv_bias=qkv_bias, + qk_scale=qk_scale, + attn_drop=attn_drop, + proj_drop=drop, + ) + + self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity() + self.norm2 = norm_layer(dim) + mlp_hidden_dim = int(dim * mlp_ratio) + self.mlp = Mlp( + in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop + ) + + self.H = None + self.W = None + + def forward(self, x, mask_matrix): + """Forward function. + Args: + x: Input feature, tensor size (B, H*W, C). + H, W: Spatial resolution of the input feature. + mask_matrix: Attention mask for cyclic shift. + """ + B, L, C = x.shape + H, W = self.H, self.W + assert L == H * W, "input feature has wrong size" + + shortcut = x + x = self.norm1(x) + x = x.view(B, H, W, C) + + # pad feature maps to multiples of window size + pad_l = pad_t = 0 + pad_r = (self.window_size - W % self.window_size) % self.window_size + pad_b = (self.window_size - H % self.window_size) % self.window_size + x = F.pad(x, (0, 0, pad_l, pad_r, pad_t, pad_b)) + _, Hp, Wp, _ = x.shape + + # cyclic shift + if self.shift_size > 0: + shifted_x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2)) + attn_mask = mask_matrix + else: + shifted_x = x + attn_mask = None + + # partition windows + x_windows = window_partition( + shifted_x, self.window_size + ) # nW*B, window_size, window_size, C + x_windows = x_windows.view( + -1, self.window_size * self.window_size, C + ) # nW*B, window_size*window_size, C + + # W-MSA/SW-MSA + attn_windows = self.attn(x_windows, mask=attn_mask) # nW*B, window_size*window_size, C + + # merge windows + attn_windows = attn_windows.view(-1, self.window_size, self.window_size, C) + shifted_x = window_reverse(attn_windows, self.window_size, Hp, Wp) # B H' W' C + + # reverse cyclic shift + if self.shift_size > 0: + x = torch.roll(shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2)) + else: + x = shifted_x + + if pad_r > 0 or pad_b > 0: + x = x[:, :H, :W, :].contiguous() + + x = x.view(B, H * W, C) + + # FFN + x = shortcut + self.drop_path(x) + x = x + self.drop_path(self.mlp(self.norm2(x))) + + return x + + +class PatchMerging(nn.Module): + """Patch Merging Layer + Args: + dim (int): Number of input channels. + norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm + """ + + def __init__(self, dim, norm_layer=nn.LayerNorm): + super().__init__() + self.dim = dim + self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False) + self.norm = norm_layer(4 * dim) + + def forward(self, x, H, W): + """Forward function. + Args: + x: Input feature, tensor size (B, H*W, C). + H, W: Spatial resolution of the input feature. + """ + B, L, C = x.shape + assert L == H * W, "input feature has wrong size" + + x = x.view(B, H, W, C) + + # padding + pad_input = (H % 2 == 1) or (W % 2 == 1) + if pad_input: + x = F.pad(x, (0, 0, 0, W % 2, 0, H % 2)) + + x0 = x[:, 0::2, 0::2, :] # B H/2 W/2 C + x1 = x[:, 1::2, 0::2, :] # B H/2 W/2 C + x2 = x[:, 0::2, 1::2, :] # B H/2 W/2 C + x3 = x[:, 1::2, 1::2, :] # B H/2 W/2 C + x = torch.cat([x0, x1, x2, x3], -1) # B H/2 W/2 4*C + x = x.view(B, -1, 4 * C) # B H/2*W/2 4*C + + x = self.norm(x) + x = self.reduction(x) + + return x + + +class BasicLayer(nn.Module): + """A basic Swin Transformer layer for one stage. + Args: + dim (int): Number of feature channels + depth (int): Depths of this stage. + num_heads (int): Number of attention head. + window_size (int): Local window size. Default: 7. + mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4. + qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True + qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set. + drop (float, optional): Dropout rate. Default: 0.0 + attn_drop (float, optional): Attention dropout rate. Default: 0.0 + drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0 + norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm + downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None + use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False. + """ + + def __init__( + self, + dim, + depth, + num_heads, + window_size=7, + mlp_ratio=4.0, + qkv_bias=True, + qk_scale=None, + drop=0.0, + attn_drop=0.0, + drop_path=0.0, + norm_layer=nn.LayerNorm, + downsample=None, + use_checkpoint=False, + ): + super().__init__() + self.window_size = window_size + self.shift_size = window_size // 2 + self.depth = depth + self.use_checkpoint = use_checkpoint + + # build blocks + self.blocks = nn.ModuleList( + [ + SwinTransformerBlock( + dim=dim, + num_heads=num_heads, + window_size=window_size, + shift_size=0 if (i % 2 == 0) else window_size // 2, + mlp_ratio=mlp_ratio, + qkv_bias=qkv_bias, + qk_scale=qk_scale, + drop=drop, + attn_drop=attn_drop, + drop_path=drop_path[i] if isinstance(drop_path, list) else drop_path, + norm_layer=norm_layer, + ) + for i in range(depth) + ] + ) + + # patch merging layer + if downsample is not None: + self.downsample = downsample(dim=dim, norm_layer=norm_layer) + else: + self.downsample = None + + def forward(self, x, H, W): + """Forward function. + Args: + x: Input feature, tensor size (B, H*W, C). + H, W: Spatial resolution of the input feature. + """ + + # calculate attention mask for SW-MSA + Hp = int(np.ceil(H / self.window_size)) * self.window_size + Wp = int(np.ceil(W / self.window_size)) * self.window_size + img_mask = torch.zeros((1, Hp, Wp, 1), device=x.device) # 1 Hp Wp 1 + h_slices = ( + slice(0, -self.window_size), + slice(-self.window_size, -self.shift_size), + slice(-self.shift_size, None), + ) + w_slices = ( + slice(0, -self.window_size), + slice(-self.window_size, -self.shift_size), + slice(-self.shift_size, None), + ) + cnt = 0 + for h in h_slices: + for w in w_slices: + img_mask[:, h, w, :] = cnt + cnt += 1 + + mask_windows = window_partition( + img_mask, self.window_size + ) # nW, window_size, window_size, 1 + mask_windows = mask_windows.view(-1, self.window_size * self.window_size) + attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2) + attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill( + attn_mask == 0, float(0.0) + ) + + for blk in self.blocks: + blk.H, blk.W = H, W + if self.use_checkpoint: + x = checkpoint.checkpoint(blk, x, attn_mask) + else: + x = blk(x, attn_mask) + if self.downsample is not None: + x_down = self.downsample(x, H, W) + Wh, Ww = (H + 1) // 2, (W + 1) // 2 + return x, H, W, x_down, Wh, Ww + else: + return x, H, W, x, H, W + + +class PatchEmbed(nn.Module): + """Image to Patch Embedding + Args: + patch_size (int): Patch token size. Default: 4. + in_chans (int): Number of input image channels. Default: 3. + embed_dim (int): Number of linear projection output channels. Default: 96. + norm_layer (nn.Module, optional): Normalization layer. Default: None + """ + + def __init__(self, patch_size=4, in_chans=3, embed_dim=96, norm_layer=None): + super().__init__() + patch_size = to_2tuple(patch_size) + self.patch_size = patch_size + + self.in_chans = in_chans + self.embed_dim = embed_dim + + self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size) + if norm_layer is not None: + self.norm = norm_layer(embed_dim) + else: + self.norm = None + + def forward(self, x): + """Forward function.""" + # padding + _, _, H, W = x.size() + if W % self.patch_size[1] != 0: + x = F.pad(x, (0, self.patch_size[1] - W % self.patch_size[1])) + if H % self.patch_size[0] != 0: + x = F.pad(x, (0, 0, 0, self.patch_size[0] - H % self.patch_size[0])) + + x = self.proj(x) # B C Wh Ww + if self.norm is not None: + Wh, Ww = x.size(2), x.size(3) + x = x.flatten(2).transpose(1, 2) + x = self.norm(x) + x = x.transpose(1, 2).view(-1, self.embed_dim, Wh, Ww) + + return x + + +class SwinTransformer(nn.Module): + """Swin Transformer backbone. + A PyTorch impl of : `Swin Transformer: Hierarchical Vision Transformer using Shifted Windows` - + https://arxiv.org/pdf/2103.14030 + Args: + pretrain_img_size (int): Input image size for training the pretrained model, + used in absolute postion embedding. Default 224. + patch_size (int | tuple(int)): Patch size. Default: 4. + in_chans (int): Number of input image channels. Default: 3. + embed_dim (int): Number of linear projection output channels. Default: 96. + depths (tuple[int]): Depths of each Swin Transformer stage. + num_heads (tuple[int]): Number of attention head of each stage. + window_size (int): Window size. Default: 7. + mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4. + qkv_bias (bool): If True, add a learnable bias to query, key, value. Default: True + qk_scale (float): Override default qk scale of head_dim ** -0.5 if set. + drop_rate (float): Dropout rate. + attn_drop_rate (float): Attention dropout rate. Default: 0. + drop_path_rate (float): Stochastic depth rate. Default: 0.2. + norm_layer (nn.Module): Normalization layer. Default: nn.LayerNorm. + ape (bool): If True, add absolute position embedding to the patch embedding. Default: False. + patch_norm (bool): If True, add normalization after patch embedding. Default: True. + out_indices (Sequence[int]): Output from which stages. + frozen_stages (int): Stages to be frozen (stop grad and set eval mode). + -1 means not freezing any parameters. + use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False. + dilation (bool): if True, the output size if 16x downsample, ow 32x downsample. + """ + + def __init__( + self, + pretrain_img_size=224, + patch_size=4, + in_chans=3, + embed_dim=96, + depths=[2, 2, 6, 2], + num_heads=[3, 6, 12, 24], + window_size=7, + mlp_ratio=4.0, + qkv_bias=True, + qk_scale=None, + drop_rate=0.0, + attn_drop_rate=0.0, + drop_path_rate=0.2, + norm_layer=nn.LayerNorm, + ape=False, + patch_norm=True, + out_indices=(0, 1, 2, 3), + frozen_stages=-1, + dilation=False, + use_checkpoint=False, + ): + super().__init__() + + self.pretrain_img_size = pretrain_img_size + self.num_layers = len(depths) + self.embed_dim = embed_dim + self.ape = ape + self.patch_norm = patch_norm + self.out_indices = out_indices + self.frozen_stages = frozen_stages + self.dilation = dilation + + # if use_checkpoint: + # print("use_checkpoint!!!!!!!!!!!!!!!!!!!!!!!!") + + # split image into non-overlapping patches + self.patch_embed = PatchEmbed( + patch_size=patch_size, + in_chans=in_chans, + embed_dim=embed_dim, + norm_layer=norm_layer if self.patch_norm else None, + ) + + # absolute position embedding + if self.ape: + pretrain_img_size = to_2tuple(pretrain_img_size) + patch_size = to_2tuple(patch_size) + patches_resolution = [ + pretrain_img_size[0] // patch_size[0], + pretrain_img_size[1] // patch_size[1], + ] + + self.absolute_pos_embed = nn.Parameter( + torch.zeros(1, embed_dim, patches_resolution[0], patches_resolution[1]) + ) + trunc_normal_(self.absolute_pos_embed, std=0.02) + + self.pos_drop = nn.Dropout(p=drop_rate) + + # stochastic depth + dpr = [ + x.item() for x in torch.linspace(0, drop_path_rate, sum(depths)) + ] # stochastic depth decay rule + + # build layers + self.layers = nn.ModuleList() + # prepare downsample list + downsamplelist = [PatchMerging for i in range(self.num_layers)] + downsamplelist[-1] = None + num_features = [int(embed_dim * 2**i) for i in range(self.num_layers)] + if self.dilation: + downsamplelist[-2] = None + num_features[-1] = int(embed_dim * 2 ** (self.num_layers - 1)) // 2 + for i_layer in range(self.num_layers): + layer = BasicLayer( + # dim=int(embed_dim * 2 ** i_layer), + dim=num_features[i_layer], + depth=depths[i_layer], + num_heads=num_heads[i_layer], + window_size=window_size, + mlp_ratio=mlp_ratio, + qkv_bias=qkv_bias, + qk_scale=qk_scale, + drop=drop_rate, + attn_drop=attn_drop_rate, + drop_path=dpr[sum(depths[:i_layer]) : sum(depths[: i_layer + 1])], + norm_layer=norm_layer, + # downsample=PatchMerging if (i_layer < self.num_layers - 1) else None, + downsample=downsamplelist[i_layer], + use_checkpoint=use_checkpoint, + ) + self.layers.append(layer) + + # num_features = [int(embed_dim * 2 ** i) for i in range(self.num_layers)] + self.num_features = num_features + + # add a norm layer for each output + for i_layer in out_indices: + layer = norm_layer(num_features[i_layer]) + layer_name = f"norm{i_layer}" + self.add_module(layer_name, layer) + + self._freeze_stages() + + def _freeze_stages(self): + if self.frozen_stages >= 0: + self.patch_embed.eval() + for param in self.patch_embed.parameters(): + param.requires_grad = False + + if self.frozen_stages >= 1 and self.ape: + self.absolute_pos_embed.requires_grad = False + + if self.frozen_stages >= 2: + self.pos_drop.eval() + for i in range(0, self.frozen_stages - 1): + m = self.layers[i] + m.eval() + for param in m.parameters(): + param.requires_grad = False + + # def init_weights(self, pretrained=None): + # """Initialize the weights in backbone. + # Args: + # pretrained (str, optional): Path to pre-trained weights. + # Defaults to None. + # """ + + # def _init_weights(m): + # if isinstance(m, nn.Linear): + # trunc_normal_(m.weight, std=.02) + # if isinstance(m, nn.Linear) and m.bias is not None: + # nn.init.constant_(m.bias, 0) + # elif isinstance(m, nn.LayerNorm): + # nn.init.constant_(m.bias, 0) + # nn.init.constant_(m.weight, 1.0) + + # if isinstance(pretrained, str): + # self.apply(_init_weights) + # logger = get_root_logger() + # load_checkpoint(self, pretrained, strict=False, logger=logger) + # elif pretrained is None: + # self.apply(_init_weights) + # else: + # raise TypeError('pretrained must be a str or None') + + def forward_raw(self, x): + """Forward function.""" + x = self.patch_embed(x) + + Wh, Ww = x.size(2), x.size(3) + if self.ape: + # interpolate the position embedding to the corresponding size + absolute_pos_embed = F.interpolate( + self.absolute_pos_embed, size=(Wh, Ww), mode="bicubic" + ) + x = (x + absolute_pos_embed).flatten(2).transpose(1, 2) # B Wh*Ww C + else: + x = x.flatten(2).transpose(1, 2) + x = self.pos_drop(x) + + outs = [] + for i in range(self.num_layers): + layer = self.layers[i] + x_out, H, W, x, Wh, Ww = layer(x, Wh, Ww) + # import ipdb; ipdb.set_trace() + + if i in self.out_indices: + norm_layer = getattr(self, f"norm{i}") + x_out = norm_layer(x_out) + + out = x_out.view(-1, H, W, self.num_features[i]).permute(0, 3, 1, 2).contiguous() + outs.append(out) + # in: + # torch.Size([2, 3, 1024, 1024]) + # outs: + # [torch.Size([2, 192, 256, 256]), torch.Size([2, 384, 128, 128]), \ + # torch.Size([2, 768, 64, 64]), torch.Size([2, 1536, 32, 32])] + return tuple(outs) + + def forward(self, tensor_list: NestedTensor): + x = tensor_list.tensors + + """Forward function.""" + x = self.patch_embed(x) + + Wh, Ww = x.size(2), x.size(3) + if self.ape: + # interpolate the position embedding to the corresponding size + absolute_pos_embed = F.interpolate( + self.absolute_pos_embed, size=(Wh, Ww), mode="bicubic" + ) + x = (x + absolute_pos_embed).flatten(2).transpose(1, 2) # B Wh*Ww C + else: + x = x.flatten(2).transpose(1, 2) + x = self.pos_drop(x) + + outs = [] + for i in range(self.num_layers): + layer = self.layers[i] + x_out, H, W, x, Wh, Ww = layer(x, Wh, Ww) + + if i in self.out_indices: + norm_layer = getattr(self, f"norm{i}") + x_out = norm_layer(x_out) + + out = x_out.view(-1, H, W, self.num_features[i]).permute(0, 3, 1, 2).contiguous() + outs.append(out) + # in: + # torch.Size([2, 3, 1024, 1024]) + # out: + # [torch.Size([2, 192, 256, 256]), torch.Size([2, 384, 128, 128]), \ + # torch.Size([2, 768, 64, 64]), torch.Size([2, 1536, 32, 32])] + + # collect for nesttensors + outs_dict = {} + for idx, out_i in enumerate(outs): + m = tensor_list.mask + assert m is not None + mask = F.interpolate(m[None].float(), size=out_i.shape[-2:]).to(torch.bool)[0] + outs_dict[idx] = NestedTensor(out_i, mask) + + return outs_dict + + def train(self, mode=True): + """Convert the model into training mode while keep layers freezed.""" + super(SwinTransformer, self).train(mode) + self._freeze_stages() + + +def build_swin_transformer(modelname, pretrain_img_size, **kw): + assert modelname in [ + "swin_T_224_1k", + "swin_B_224_22k", + "swin_B_384_22k", + "swin_L_224_22k", + "swin_L_384_22k", + ] + + model_para_dict = { + "swin_T_224_1k": dict( + embed_dim=96, depths=[2, 2, 6, 2], num_heads=[3, 6, 12, 24], window_size=7 + ), + "swin_B_224_22k": dict( + embed_dim=128, depths=[2, 2, 18, 2], num_heads=[4, 8, 16, 32], window_size=7 + ), + "swin_B_384_22k": dict( + embed_dim=128, depths=[2, 2, 18, 2], num_heads=[4, 8, 16, 32], window_size=12 + ), + "swin_L_224_22k": dict( + embed_dim=192, depths=[2, 2, 18, 2], num_heads=[6, 12, 24, 48], window_size=7 + ), + "swin_L_384_22k": dict( + embed_dim=192, depths=[2, 2, 18, 2], num_heads=[6, 12, 24, 48], window_size=12 + ), + } + kw_cgf = model_para_dict[modelname] + kw_cgf.update(kw) + model = SwinTransformer(pretrain_img_size=pretrain_img_size, **kw_cgf) + return model + + +if __name__ == "__main__": + model = build_swin_transformer("swin_L_384_22k", 384, dilation=True) + x = torch.rand(2, 3, 1024, 1024) + y = model.forward_raw(x) + import ipdb + + ipdb.set_trace() + x = torch.rand(2, 3, 384, 384) + y = model.forward_raw(x) diff --git a/py/local_groundingdino/models/GroundingDINO/bertwarper.py b/py/local_groundingdino/models/GroundingDINO/bertwarper.py new file mode 100644 index 0000000..e209a39 --- /dev/null +++ b/py/local_groundingdino/models/GroundingDINO/bertwarper.py @@ -0,0 +1,269 @@ +# ------------------------------------------------------------------------ +# Grounding DINO +# url: https://github.com/IDEA-Research/GroundingDINO +# Copyright (c) 2023 IDEA. All Rights Reserved. +# Licensed under the Apache License, Version 2.0 [see LICENSE for details] +# ------------------------------------------------------------------------ + +import torch +from torch import nn +from transformers.modeling_outputs import BaseModelOutputWithPoolingAndCrossAttentions + + +class BertModelWarper(nn.Module): + def __init__(self, bert_model): + super().__init__() + # self.bert = bert_modelc + + self.config = bert_model.config + self.embeddings = bert_model.embeddings + self.encoder = bert_model.encoder + self.pooler = bert_model.pooler + + self.get_extended_attention_mask = bert_model.get_extended_attention_mask + self.invert_attention_mask = bert_model.invert_attention_mask + self.get_head_mask = bert_model.get_head_mask + + def forward( + self, + input_ids=None, + attention_mask=None, + token_type_ids=None, + position_ids=None, + head_mask=None, + inputs_embeds=None, + encoder_hidden_states=None, + encoder_attention_mask=None, + past_key_values=None, + use_cache=None, + output_attentions=None, + output_hidden_states=None, + return_dict=None, + ): + r""" + encoder_hidden_states (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`): + Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if + the model is configured as a decoder. + encoder_attention_mask (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`): + Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in + the cross-attention if the model is configured as a decoder. Mask values selected in ``[0, 1]``: + + - 1 for tokens that are **not masked**, + - 0 for tokens that are **masked**. + past_key_values (:obj:`tuple(tuple(torch.FloatTensor))` of length :obj:`config.n_layers` with each tuple having 4 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`): + Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding. + + If :obj:`past_key_values` are used, the user can optionally input only the last :obj:`decoder_input_ids` + (those that don't have their past key value states given to this model) of shape :obj:`(batch_size, 1)` + instead of all :obj:`decoder_input_ids` of shape :obj:`(batch_size, sequence_length)`. + use_cache (:obj:`bool`, `optional`): + If set to :obj:`True`, :obj:`past_key_values` key value states are returned and can be used to speed up + decoding (see :obj:`past_key_values`). + """ + output_attentions = ( + output_attentions if output_attentions is not None else self.config.output_attentions + ) + output_hidden_states = ( + output_hidden_states + if output_hidden_states is not None + else self.config.output_hidden_states + ) + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + if self.config.is_decoder: + use_cache = use_cache if use_cache is not None else self.config.use_cache + else: + use_cache = False + + if input_ids is not None and inputs_embeds is not None: + raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time") + elif input_ids is not None: + input_shape = input_ids.size() + batch_size, seq_length = input_shape + elif inputs_embeds is not None: + input_shape = inputs_embeds.size()[:-1] + batch_size, seq_length = input_shape + else: + raise ValueError("You have to specify either input_ids or inputs_embeds") + + device = input_ids.device if input_ids is not None else inputs_embeds.device + + # past_key_values_length + past_key_values_length = ( + past_key_values[0][0].shape[2] if past_key_values is not None else 0 + ) + + if attention_mask is None: + attention_mask = torch.ones( + ((batch_size, seq_length + past_key_values_length)), device=device + ) + if token_type_ids is None: + token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device) + + # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length] + # ourselves in which case we just need to make it broadcastable to all heads. + extended_attention_mask: torch.Tensor = self.get_extended_attention_mask( + attention_mask, input_shape, device + ) + + # If a 2D or 3D attention mask is provided for the cross-attention + # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length] + if self.config.is_decoder and encoder_hidden_states is not None: + encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size() + encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length) + if encoder_attention_mask is None: + encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device) + encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask) + else: + encoder_extended_attention_mask = None + # if os.environ.get('IPDB_SHILONG_DEBUG', None) == 'INFO': + # import ipdb; ipdb.set_trace() + + # Prepare head mask if needed + # 1.0 in head_mask indicate we keep the head + # attention_probs has shape bsz x n_heads x N x N + # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads] + # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length] + head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers) + + embedding_output = self.embeddings( + input_ids=input_ids, + position_ids=position_ids, + token_type_ids=token_type_ids, + inputs_embeds=inputs_embeds, + past_key_values_length=past_key_values_length, + ) + + encoder_outputs = self.encoder( + embedding_output, + attention_mask=extended_attention_mask, + head_mask=head_mask, + encoder_hidden_states=encoder_hidden_states, + encoder_attention_mask=encoder_extended_attention_mask, + past_key_values=past_key_values, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + sequence_output = encoder_outputs[0] + pooled_output = self.pooler(sequence_output) if self.pooler is not None else None + + if not return_dict: + return (sequence_output, pooled_output) + encoder_outputs[1:] + + return BaseModelOutputWithPoolingAndCrossAttentions( + last_hidden_state=sequence_output, + pooler_output=pooled_output, + past_key_values=encoder_outputs.past_key_values, + hidden_states=encoder_outputs.hidden_states, + attentions=encoder_outputs.attentions, + cross_attentions=encoder_outputs.cross_attentions, + ) + + +class TextEncoderShell(nn.Module): + def __init__(self, text_encoder): + super().__init__() + self.text_encoder = text_encoder + self.config = self.text_encoder.config + + def forward(self, **kw): + # feed into text encoder + return self.text_encoder(**kw) + + +def generate_masks_with_special_tokens(tokenized, special_tokens_list, tokenizer): + """Generate attention mask between each pair of special tokens + Args: + input_ids (torch.Tensor): input ids. Shape: [bs, num_token] + special_tokens_mask (list): special tokens mask. + Returns: + torch.Tensor: attention mask between each special tokens. + """ + input_ids = tokenized["input_ids"] + bs, num_token = input_ids.shape + # special_tokens_mask: bs, num_token. 1 for special tokens. 0 for normal tokens + special_tokens_mask = torch.zeros((bs, num_token), device=input_ids.device).bool() + for special_token in special_tokens_list: + special_tokens_mask |= input_ids == special_token + + # idxs: each row is a list of indices of special tokens + idxs = torch.nonzero(special_tokens_mask) + + # generate attention mask and positional ids + attention_mask = ( + torch.eye(num_token, device=input_ids.device).bool().unsqueeze(0).repeat(bs, 1, 1) + ) + position_ids = torch.zeros((bs, num_token), device=input_ids.device) + previous_col = 0 + for i in range(idxs.shape[0]): + row, col = idxs[i] + if (col == 0) or (col == num_token - 1): + attention_mask[row, col, col] = True + position_ids[row, col] = 0 + else: + attention_mask[row, previous_col + 1 : col + 1, previous_col + 1 : col + 1] = True + position_ids[row, previous_col + 1 : col + 1] = torch.arange( + 0, col - previous_col, device=input_ids.device + ) + + previous_col = col + + # # padding mask + # padding_mask = tokenized['attention_mask'] + # attention_mask = attention_mask & padding_mask.unsqueeze(1).bool() & padding_mask.unsqueeze(2).bool() + + return attention_mask, position_ids.to(torch.long) + + +def generate_masks_with_special_tokens_and_transfer_map(tokenized, special_tokens_list, tokenizer): + """Generate attention mask between each pair of special tokens + Args: + input_ids (torch.Tensor): input ids. Shape: [bs, num_token] + special_tokens_mask (list): special tokens mask. + Returns: + torch.Tensor: attention mask between each special tokens. + """ + input_ids = tokenized["input_ids"] + bs, num_token = input_ids.shape + # special_tokens_mask: bs, num_token. 1 for special tokens. 0 for normal tokens + special_tokens_mask = torch.zeros((bs, num_token), device=input_ids.device).bool() + for special_token in special_tokens_list: + special_tokens_mask |= input_ids == special_token + + # idxs: each row is a list of indices of special tokens + idxs = torch.nonzero(special_tokens_mask) + + # generate attention mask and positional ids + attention_mask = ( + torch.eye(num_token, device=input_ids.device).bool().unsqueeze(0).repeat(bs, 1, 1) + ) + position_ids = torch.zeros((bs, num_token), device=input_ids.device) + cate_to_token_mask_list = [[] for _ in range(bs)] + previous_col = 0 + for i in range(idxs.shape[0]): + row, col = idxs[i] + if (col == 0) or (col == num_token - 1): + attention_mask[row, col, col] = True + position_ids[row, col] = 0 + else: + attention_mask[row, previous_col + 1 : col + 1, previous_col + 1 : col + 1] = True + position_ids[row, previous_col + 1 : col + 1] = torch.arange( + 0, col - previous_col, device=input_ids.device + ) + c2t_maski = torch.zeros((num_token), device=input_ids.device).bool() + c2t_maski[previous_col + 1 : col] = True + cate_to_token_mask_list[row].append(c2t_maski) + previous_col = col + + cate_to_token_mask_list = [ + torch.stack(cate_to_token_mask_listi, dim=0) + for cate_to_token_mask_listi in cate_to_token_mask_list + ] + + # # padding mask + # padding_mask = tokenized['attention_mask'] + # attention_mask = attention_mask & padding_mask.unsqueeze(1).bool() & padding_mask.unsqueeze(2).bool() + + return attention_mask, position_ids.to(torch.long), cate_to_token_mask_list diff --git a/py/local_groundingdino/models/GroundingDINO/fuse_modules.py b/py/local_groundingdino/models/GroundingDINO/fuse_modules.py new file mode 100644 index 0000000..2753b3d --- /dev/null +++ b/py/local_groundingdino/models/GroundingDINO/fuse_modules.py @@ -0,0 +1,297 @@ +# ------------------------------------------------------------------------ +# Grounding DINO +# url: https://github.com/IDEA-Research/GroundingDINO +# Copyright (c) 2023 IDEA. All Rights Reserved. +# Licensed under the Apache License, Version 2.0 [see LICENSE for details] +# ------------------------------------------------------------------------ + +import torch +import torch.nn as nn +import torch.nn.functional as F +from timm.models.layers import DropPath + + +class FeatureResizer(nn.Module): + """ + This class takes as input a set of embeddings of dimension C1 and outputs a set of + embedding of dimension C2, after a linear transformation, dropout and normalization (LN). + """ + + def __init__(self, input_feat_size, output_feat_size, dropout, do_ln=True): + super().__init__() + self.do_ln = do_ln + # Object feature encoding + self.fc = nn.Linear(input_feat_size, output_feat_size, bias=True) + self.layer_norm = nn.LayerNorm(output_feat_size, eps=1e-12) + self.dropout = nn.Dropout(dropout) + + def forward(self, encoder_features): + x = self.fc(encoder_features) + if self.do_ln: + x = self.layer_norm(x) + output = self.dropout(x) + return output + + +def l1norm(X, dim, eps=1e-8): + """L1-normalize columns of X""" + norm = torch.abs(X).sum(dim=dim, keepdim=True) + eps + X = torch.div(X, norm) + return X + + +def l2norm(X, dim, eps=1e-8): + """L2-normalize columns of X""" + norm = torch.pow(X, 2).sum(dim=dim, keepdim=True).sqrt() + eps + X = torch.div(X, norm) + return X + + +def func_attention(query, context, smooth=1, raw_feature_norm="softmax", eps=1e-8): + """ + query: (n_context, queryL, d) + context: (n_context, sourceL, d) + """ + batch_size_q, queryL = query.size(0), query.size(1) + batch_size, sourceL = context.size(0), context.size(1) + + # Get attention + # --> (batch, d, queryL) + queryT = torch.transpose(query, 1, 2) + + # (batch, sourceL, d)(batch, d, queryL) + # --> (batch, sourceL, queryL) + attn = torch.bmm(context, queryT) + if raw_feature_norm == "softmax": + # --> (batch*sourceL, queryL) + attn = attn.view(batch_size * sourceL, queryL) + attn = nn.Softmax()(attn) + # --> (batch, sourceL, queryL) + attn = attn.view(batch_size, sourceL, queryL) + elif raw_feature_norm == "l2norm": + attn = l2norm(attn, 2) + elif raw_feature_norm == "clipped_l2norm": + attn = nn.LeakyReLU(0.1)(attn) + attn = l2norm(attn, 2) + else: + raise ValueError("unknown first norm type:", raw_feature_norm) + # --> (batch, queryL, sourceL) + attn = torch.transpose(attn, 1, 2).contiguous() + # --> (batch*queryL, sourceL) + attn = attn.view(batch_size * queryL, sourceL) + attn = nn.Softmax()(attn * smooth) + # --> (batch, queryL, sourceL) + attn = attn.view(batch_size, queryL, sourceL) + # --> (batch, sourceL, queryL) + attnT = torch.transpose(attn, 1, 2).contiguous() + + # --> (batch, d, sourceL) + contextT = torch.transpose(context, 1, 2) + # (batch x d x sourceL)(batch x sourceL x queryL) + # --> (batch, d, queryL) + weightedContext = torch.bmm(contextT, attnT) + # --> (batch, queryL, d) + weightedContext = torch.transpose(weightedContext, 1, 2) + + return weightedContext, attnT + + +class BiMultiHeadAttention(nn.Module): + def __init__(self, v_dim, l_dim, embed_dim, num_heads, dropout=0.1, cfg=None): + super(BiMultiHeadAttention, self).__init__() + + self.embed_dim = embed_dim + self.num_heads = num_heads + self.head_dim = embed_dim // num_heads + self.v_dim = v_dim + self.l_dim = l_dim + + assert ( + self.head_dim * self.num_heads == self.embed_dim + ), f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`: {self.num_heads})." + self.scale = self.head_dim ** (-0.5) + self.dropout = dropout + + self.v_proj = nn.Linear(self.v_dim, self.embed_dim) + self.l_proj = nn.Linear(self.l_dim, self.embed_dim) + self.values_v_proj = nn.Linear(self.v_dim, self.embed_dim) + self.values_l_proj = nn.Linear(self.l_dim, self.embed_dim) + + self.out_v_proj = nn.Linear(self.embed_dim, self.v_dim) + self.out_l_proj = nn.Linear(self.embed_dim, self.l_dim) + + self.stable_softmax_2d = True + self.clamp_min_for_underflow = True + self.clamp_max_for_overflow = True + + self._reset_parameters() + + def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int): + return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous() + + def _reset_parameters(self): + nn.init.xavier_uniform_(self.v_proj.weight) + self.v_proj.bias.data.fill_(0) + nn.init.xavier_uniform_(self.l_proj.weight) + self.l_proj.bias.data.fill_(0) + nn.init.xavier_uniform_(self.values_v_proj.weight) + self.values_v_proj.bias.data.fill_(0) + nn.init.xavier_uniform_(self.values_l_proj.weight) + self.values_l_proj.bias.data.fill_(0) + nn.init.xavier_uniform_(self.out_v_proj.weight) + self.out_v_proj.bias.data.fill_(0) + nn.init.xavier_uniform_(self.out_l_proj.weight) + self.out_l_proj.bias.data.fill_(0) + + def forward(self, v, l, attention_mask_v=None, attention_mask_l=None): + """_summary_ + + Args: + v (_type_): bs, n_img, dim + l (_type_): bs, n_text, dim + attention_mask_v (_type_, optional): _description_. bs, n_img + attention_mask_l (_type_, optional): _description_. bs, n_text + + Returns: + _type_: _description_ + """ + # if os.environ.get('IPDB_SHILONG_DEBUG', None) == 'INFO': + # import ipdb; ipdb.set_trace() + bsz, tgt_len, _ = v.size() + + query_states = self.v_proj(v) * self.scale + key_states = self._shape(self.l_proj(l), -1, bsz) + value_v_states = self._shape(self.values_v_proj(v), -1, bsz) + value_l_states = self._shape(self.values_l_proj(l), -1, bsz) + + proj_shape = (bsz * self.num_heads, -1, self.head_dim) + query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape) + key_states = key_states.view(*proj_shape) + value_v_states = value_v_states.view(*proj_shape) + value_l_states = value_l_states.view(*proj_shape) + + src_len = key_states.size(1) + attn_weights = torch.bmm(query_states, key_states.transpose(1, 2)) # bs*nhead, nimg, ntxt + + if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len): + raise ValueError( + f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is {attn_weights.size()}" + ) + + if self.stable_softmax_2d: + attn_weights = attn_weights - attn_weights.max() + + if self.clamp_min_for_underflow: + attn_weights = torch.clamp( + attn_weights, min=-50000 + ) # Do not increase -50000, data type half has quite limited range + if self.clamp_max_for_overflow: + attn_weights = torch.clamp( + attn_weights, max=50000 + ) # Do not increase 50000, data type half has quite limited range + + attn_weights_T = attn_weights.transpose(1, 2) + attn_weights_l = attn_weights_T - torch.max(attn_weights_T, dim=-1, keepdim=True)[0] + if self.clamp_min_for_underflow: + attn_weights_l = torch.clamp( + attn_weights_l, min=-50000 + ) # Do not increase -50000, data type half has quite limited range + if self.clamp_max_for_overflow: + attn_weights_l = torch.clamp( + attn_weights_l, max=50000 + ) # Do not increase 50000, data type half has quite limited range + + # mask vison for language + if attention_mask_v is not None: + attention_mask_v = ( + attention_mask_v[:, None, None, :].repeat(1, self.num_heads, 1, 1).flatten(0, 1) + ) + attn_weights_l.masked_fill_(attention_mask_v, float("-inf")) + + attn_weights_l = attn_weights_l.softmax(dim=-1) + + # mask language for vision + if attention_mask_l is not None: + attention_mask_l = ( + attention_mask_l[:, None, None, :].repeat(1, self.num_heads, 1, 1).flatten(0, 1) + ) + attn_weights.masked_fill_(attention_mask_l, float("-inf")) + attn_weights_v = attn_weights.softmax(dim=-1) + + attn_probs_v = F.dropout(attn_weights_v, p=self.dropout, training=self.training) + attn_probs_l = F.dropout(attn_weights_l, p=self.dropout, training=self.training) + + attn_output_v = torch.bmm(attn_probs_v, value_l_states) + attn_output_l = torch.bmm(attn_probs_l, value_v_states) + + if attn_output_v.size() != (bsz * self.num_heads, tgt_len, self.head_dim): + raise ValueError( + f"`attn_output_v` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is {attn_output_v.size()}" + ) + + if attn_output_l.size() != (bsz * self.num_heads, src_len, self.head_dim): + raise ValueError( + f"`attn_output_l` should be of size {(bsz, self.num_heads, src_len, self.head_dim)}, but is {attn_output_l.size()}" + ) + + attn_output_v = attn_output_v.view(bsz, self.num_heads, tgt_len, self.head_dim) + attn_output_v = attn_output_v.transpose(1, 2) + attn_output_v = attn_output_v.reshape(bsz, tgt_len, self.embed_dim) + + attn_output_l = attn_output_l.view(bsz, self.num_heads, src_len, self.head_dim) + attn_output_l = attn_output_l.transpose(1, 2) + attn_output_l = attn_output_l.reshape(bsz, src_len, self.embed_dim) + + attn_output_v = self.out_v_proj(attn_output_v) + attn_output_l = self.out_l_proj(attn_output_l) + + return attn_output_v, attn_output_l + + +# Bi-Direction MHA (text->image, image->text) +class BiAttentionBlock(nn.Module): + def __init__( + self, + v_dim, + l_dim, + embed_dim, + num_heads, + dropout=0.1, + drop_path=0.0, + init_values=1e-4, + cfg=None, + ): + """ + Inputs: + embed_dim - Dimensionality of input and attention feature vectors + hidden_dim - Dimensionality of hidden layer in feed-forward network + (usually 2-4x larger than embed_dim) + num_heads - Number of heads to use in the Multi-Head Attention block + dropout - Amount of dropout to apply in the feed-forward network + """ + super(BiAttentionBlock, self).__init__() + + # pre layer norm + self.layer_norm_v = nn.LayerNorm(v_dim) + self.layer_norm_l = nn.LayerNorm(l_dim) + self.attn = BiMultiHeadAttention( + v_dim=v_dim, l_dim=l_dim, embed_dim=embed_dim, num_heads=num_heads, dropout=dropout + ) + + # add layer scale for training stability + self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity() + self.gamma_v = nn.Parameter(init_values * torch.ones((v_dim)), requires_grad=True) + self.gamma_l = nn.Parameter(init_values * torch.ones((l_dim)), requires_grad=True) + + def forward(self, v, l, attention_mask_v=None, attention_mask_l=None): + v = self.layer_norm_v(v) + l = self.layer_norm_l(l) + delta_v, delta_l = self.attn( + v, l, attention_mask_v=attention_mask_v, attention_mask_l=attention_mask_l + ) + # v, l = v + delta_v, l + delta_l + v = v + self.drop_path(self.gamma_v * delta_v) + l = l + self.drop_path(self.gamma_l * delta_l) + return v, l + + # def forward(self, v:List[torch.Tensor], l, attention_mask_v=None, attention_mask_l=None) diff --git a/py/local_groundingdino/models/GroundingDINO/groundingdino.py b/py/local_groundingdino/models/GroundingDINO/groundingdino.py new file mode 100644 index 0000000..0e2b20c --- /dev/null +++ b/py/local_groundingdino/models/GroundingDINO/groundingdino.py @@ -0,0 +1,385 @@ +# ------------------------------------------------------------------------ +# Grounding DINO +# url: https://github.com/IDEA-Research/GroundingDINO +# Copyright (c) 2023 IDEA. All Rights Reserved. +# Licensed under the Apache License, Version 2.0 [see LICENSE for details] +# ------------------------------------------------------------------------ +# Conditional DETR model and criterion classes. +# Copyright (c) 2021 Microsoft. All Rights Reserved. +# Licensed under the Apache License, Version 2.0 [see LICENSE for details] +# ------------------------------------------------------------------------ +# Modified from DETR (https://github.com/facebookresearch/detr) +# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. +# ------------------------------------------------------------------------ +# Modified from Deformable DETR (https://github.com/fundamentalvision/Deformable-DETR) +# Copyright (c) 2020 SenseTime. All Rights Reserved. +# ------------------------------------------------------------------------ +import copy +from typing import List + +import torch +import torch.nn.functional as F +from torch import nn + +from local_groundingdino.util import get_tokenlizer +from local_groundingdino.util.misc import ( + NestedTensor, + inverse_sigmoid, + nested_tensor_from_tensor_list, +) + +from ..registry import MODULE_BUILD_FUNCS +from .backbone import build_backbone +from .bertwarper import ( + BertModelWarper, + generate_masks_with_special_tokens_and_transfer_map, +) +from .transformer import build_transformer +from .utils import MLP, ContrastiveEmbed + + +class GroundingDINO(nn.Module): + """This is the Cross-Attention Detector module that performs object detection""" + + def __init__( + self, + backbone, + transformer, + num_queries, + aux_loss=False, + iter_update=False, + query_dim=2, + num_feature_levels=1, + nheads=8, + # two stage + two_stage_type="no", # ['no', 'standard'] + dec_pred_bbox_embed_share=True, + two_stage_class_embed_share=True, + two_stage_bbox_embed_share=True, + num_patterns=0, + dn_number=100, + dn_box_noise_scale=0.4, + dn_label_noise_ratio=0.5, + dn_labelbook_size=100, + text_encoder_type="bert-base-uncased", + sub_sentence_present=True, + max_text_len=256, + ): + """Initializes the model. + Parameters: + backbone: torch module of the backbone to be used. See backbone.py + transformer: torch module of the transformer architecture. See transformer.py + num_queries: number of object queries, ie detection slot. This is the maximal number of objects + Conditional DETR can detect in a single image. For COCO, we recommend 100 queries. + aux_loss: True if auxiliary decoding losses (loss at each decoder layer) are to be used. + """ + super().__init__() + self.num_queries = num_queries + self.transformer = transformer + self.hidden_dim = hidden_dim = transformer.d_model + self.num_feature_levels = num_feature_levels + self.nheads = nheads + self.max_text_len = 256 + self.sub_sentence_present = sub_sentence_present + + # setting query dim + self.query_dim = query_dim + assert query_dim == 4 + + # for dn training + self.num_patterns = num_patterns + self.dn_number = dn_number + self.dn_box_noise_scale = dn_box_noise_scale + self.dn_label_noise_ratio = dn_label_noise_ratio + self.dn_labelbook_size = dn_labelbook_size + + # bert + self.tokenizer = get_tokenlizer.get_tokenlizer(text_encoder_type) + self.bert = get_tokenlizer.get_pretrained_language_model(text_encoder_type) + self.bert.pooler.dense.weight.requires_grad_(False) + self.bert.pooler.dense.bias.requires_grad_(False) + self.bert = BertModelWarper(bert_model=self.bert) + + self.feat_map = nn.Linear(self.bert.config.hidden_size, self.hidden_dim, bias=True) + nn.init.constant_(self.feat_map.bias.data, 0) + nn.init.xavier_uniform_(self.feat_map.weight.data) + # freeze + + # special tokens + self.specical_tokens = self.tokenizer.convert_tokens_to_ids(["[CLS]", "[SEP]", ".", "?"]) + + # prepare input projection layers + if num_feature_levels > 1: + num_backbone_outs = len(backbone.num_channels) + input_proj_list = [] + for _ in range(num_backbone_outs): + in_channels = backbone.num_channels[_] + input_proj_list.append( + nn.Sequential( + nn.Conv2d(in_channels, hidden_dim, kernel_size=1), + nn.GroupNorm(32, hidden_dim), + ) + ) + for _ in range(num_feature_levels - num_backbone_outs): + input_proj_list.append( + nn.Sequential( + nn.Conv2d(in_channels, hidden_dim, kernel_size=3, stride=2, padding=1), + nn.GroupNorm(32, hidden_dim), + ) + ) + in_channels = hidden_dim + self.input_proj = nn.ModuleList(input_proj_list) + else: + assert two_stage_type == "no", "two_stage_type should be no if num_feature_levels=1 !!!" + self.input_proj = nn.ModuleList( + [ + nn.Sequential( + nn.Conv2d(backbone.num_channels[-1], hidden_dim, kernel_size=1), + nn.GroupNorm(32, hidden_dim), + ) + ] + ) + + self.backbone = backbone + self.aux_loss = aux_loss + self.box_pred_damping = box_pred_damping = None + + self.iter_update = iter_update + assert iter_update, "Why not iter_update?" + + # prepare pred layers + self.dec_pred_bbox_embed_share = dec_pred_bbox_embed_share + # prepare class & box embed + _class_embed = ContrastiveEmbed() + + _bbox_embed = MLP(hidden_dim, hidden_dim, 4, 3) + nn.init.constant_(_bbox_embed.layers[-1].weight.data, 0) + nn.init.constant_(_bbox_embed.layers[-1].bias.data, 0) + + if dec_pred_bbox_embed_share: + box_embed_layerlist = [_bbox_embed for i in range(transformer.num_decoder_layers)] + else: + box_embed_layerlist = [ + copy.deepcopy(_bbox_embed) for i in range(transformer.num_decoder_layers) + ] + class_embed_layerlist = [_class_embed for i in range(transformer.num_decoder_layers)] + self.bbox_embed = nn.ModuleList(box_embed_layerlist) + self.class_embed = nn.ModuleList(class_embed_layerlist) + self.transformer.decoder.bbox_embed = self.bbox_embed + self.transformer.decoder.class_embed = self.class_embed + + # two stage + self.two_stage_type = two_stage_type + assert two_stage_type in ["no", "standard"], "unknown param {} of two_stage_type".format( + two_stage_type + ) + if two_stage_type != "no": + if two_stage_bbox_embed_share: + assert dec_pred_bbox_embed_share + self.transformer.enc_out_bbox_embed = _bbox_embed + else: + self.transformer.enc_out_bbox_embed = copy.deepcopy(_bbox_embed) + + if two_stage_class_embed_share: + assert dec_pred_bbox_embed_share + self.transformer.enc_out_class_embed = _class_embed + else: + self.transformer.enc_out_class_embed = copy.deepcopy(_class_embed) + + self.refpoint_embed = None + + self._reset_parameters() + + def _reset_parameters(self): + # init input_proj + for proj in self.input_proj: + nn.init.xavier_uniform_(proj[0].weight, gain=1) + nn.init.constant_(proj[0].bias, 0) + + def init_ref_points(self, use_num_queries): + self.refpoint_embed = nn.Embedding(use_num_queries, self.query_dim) + + def forward(self, samples: NestedTensor, targets: List = None, **kw): + """The forward expects a NestedTensor, which consists of: + - samples.tensor: batched images, of shape [batch_size x 3 x H x W] + - samples.mask: a binary mask of shape [batch_size x H x W], containing 1 on padded pixels + + It returns a dict with the following elements: + - "pred_logits": the classification logits (including no-object) for all queries. + Shape= [batch_size x num_queries x num_classes] + - "pred_boxes": The normalized boxes coordinates for all queries, represented as + (center_x, center_y, width, height). These values are normalized in [0, 1], + relative to the size of each individual image (disregarding possible padding). + See PostProcess for information on how to retrieve the unnormalized bounding box. + - "aux_outputs": Optional, only returned when auxilary losses are activated. It is a list of + dictionnaries containing the two above keys for each decoder layer. + """ + if targets is None: + captions = kw["captions"] + else: + captions = [t["caption"] for t in targets] + len(captions) + + # encoder texts + tokenized = self.tokenizer(captions, padding="longest", return_tensors="pt").to( + samples.device + ) + ( + text_self_attention_masks, + position_ids, + cate_to_token_mask_list, + ) = generate_masks_with_special_tokens_and_transfer_map( + tokenized, self.specical_tokens, self.tokenizer + ) + + if text_self_attention_masks.shape[1] > self.max_text_len: + text_self_attention_masks = text_self_attention_masks[ + :, : self.max_text_len, : self.max_text_len + ] + position_ids = position_ids[:, : self.max_text_len] + tokenized["input_ids"] = tokenized["input_ids"][:, : self.max_text_len] + tokenized["attention_mask"] = tokenized["attention_mask"][:, : self.max_text_len] + tokenized["token_type_ids"] = tokenized["token_type_ids"][:, : self.max_text_len] + + # extract text embeddings + if self.sub_sentence_present: + tokenized_for_encoder = {k: v for k, v in tokenized.items() if k != "attention_mask"} + tokenized_for_encoder["attention_mask"] = text_self_attention_masks + tokenized_for_encoder["position_ids"] = position_ids + else: + # import ipdb; ipdb.set_trace() + tokenized_for_encoder = tokenized + + bert_output = self.bert(**tokenized_for_encoder) # bs, 195, 768 + + encoded_text = self.feat_map(bert_output["last_hidden_state"]) # bs, 195, d_model + text_token_mask = tokenized.attention_mask.bool() # bs, 195 + # text_token_mask: True for nomask, False for mask + # text_self_attention_masks: True for nomask, False for mask + + if encoded_text.shape[1] > self.max_text_len: + encoded_text = encoded_text[:, : self.max_text_len, :] + text_token_mask = text_token_mask[:, : self.max_text_len] + position_ids = position_ids[:, : self.max_text_len] + text_self_attention_masks = text_self_attention_masks[ + :, : self.max_text_len, : self.max_text_len + ] + + text_dict = { + "encoded_text": encoded_text, # bs, 195, d_model + "text_token_mask": text_token_mask, # bs, 195 + "position_ids": position_ids, # bs, 195 + "text_self_attention_masks": text_self_attention_masks, # bs, 195,195 + } + + # import ipdb; ipdb.set_trace() + + if isinstance(samples, (list, torch.Tensor)): + samples = nested_tensor_from_tensor_list(samples) + features, poss = self.backbone(samples) + + srcs = [] + masks = [] + for l, feat in enumerate(features): + src, mask = feat.decompose() + srcs.append(self.input_proj[l](src)) + masks.append(mask) + assert mask is not None + if self.num_feature_levels > len(srcs): + _len_srcs = len(srcs) + for l in range(_len_srcs, self.num_feature_levels): + if l == _len_srcs: + src = self.input_proj[l](features[-1].tensors) + else: + src = self.input_proj[l](srcs[-1]) + m = samples.mask + mask = F.interpolate(m[None].float(), size=src.shape[-2:]).to(torch.bool)[0] + pos_l = self.backbone[1](NestedTensor(src, mask)).to(src.dtype) + srcs.append(src) + masks.append(mask) + poss.append(pos_l) + + input_query_bbox = input_query_label = attn_mask = dn_meta = None + hs, reference, hs_enc, ref_enc, init_box_proposal = self.transformer( + srcs, masks, input_query_bbox, poss, input_query_label, attn_mask, text_dict + ) + + # deformable-detr-like anchor update + outputs_coord_list = [] + for dec_lid, (layer_ref_sig, layer_bbox_embed, layer_hs) in enumerate( + zip(reference[:-1], self.bbox_embed, hs) + ): + layer_delta_unsig = layer_bbox_embed(layer_hs) + layer_outputs_unsig = layer_delta_unsig + inverse_sigmoid(layer_ref_sig) + layer_outputs_unsig = layer_outputs_unsig.sigmoid() + outputs_coord_list.append(layer_outputs_unsig) + outputs_coord_list = torch.stack(outputs_coord_list) + + # output + outputs_class = torch.stack( + [ + layer_cls_embed(layer_hs, text_dict) + for layer_cls_embed, layer_hs in zip(self.class_embed, hs) + ] + ) + out = {"pred_logits": outputs_class[-1], "pred_boxes": outputs_coord_list[-1]} + + # # for intermediate outputs + # if self.aux_loss: + # out['aux_outputs'] = self._set_aux_loss(outputs_class, outputs_coord_list) + + # # for encoder output + # if hs_enc is not None: + # # prepare intermediate outputs + # interm_coord = ref_enc[-1] + # interm_class = self.transformer.enc_out_class_embed(hs_enc[-1], text_dict) + # out['interm_outputs'] = {'pred_logits': interm_class, 'pred_boxes': interm_coord} + # out['interm_outputs_for_matching_pre'] = {'pred_logits': interm_class, 'pred_boxes': init_box_proposal} + + return out + + @torch.jit.unused + def _set_aux_loss(self, outputs_class, outputs_coord): + # this is a workaround to make torchscript happy, as torchscript + # doesn't support dictionary with non-homogeneous values, such + # as a dict having both a Tensor and a list. + return [ + {"pred_logits": a, "pred_boxes": b} + for a, b in zip(outputs_class[:-1], outputs_coord[:-1]) + ] + + +@MODULE_BUILD_FUNCS.registe_with_name(module_name="groundingdino") +def build_groundingdino(args): + + backbone = build_backbone(args) + transformer = build_transformer(args) + + dn_labelbook_size = args.dn_labelbook_size + dec_pred_bbox_embed_share = args.dec_pred_bbox_embed_share + sub_sentence_present = args.sub_sentence_present + + model = GroundingDINO( + backbone, + transformer, + num_queries=args.num_queries, + aux_loss=True, + iter_update=True, + query_dim=4, + num_feature_levels=args.num_feature_levels, + nheads=args.nheads, + dec_pred_bbox_embed_share=dec_pred_bbox_embed_share, + two_stage_type=args.two_stage_type, + two_stage_bbox_embed_share=args.two_stage_bbox_embed_share, + two_stage_class_embed_share=args.two_stage_class_embed_share, + num_patterns=args.num_patterns, + dn_number=0, + dn_box_noise_scale=args.dn_box_noise_scale, + dn_label_noise_ratio=args.dn_label_noise_ratio, + dn_labelbook_size=dn_labelbook_size, + text_encoder_type=args.text_encoder_type, + sub_sentence_present=sub_sentence_present, + max_text_len=args.max_text_len, + ) + + return model diff --git a/py/local_groundingdino/models/GroundingDINO/ms_deform_attn.py b/py/local_groundingdino/models/GroundingDINO/ms_deform_attn.py new file mode 100644 index 0000000..9269d33 --- /dev/null +++ b/py/local_groundingdino/models/GroundingDINO/ms_deform_attn.py @@ -0,0 +1,334 @@ +# ------------------------------------------------------------------------ +# Grounding DINO +# url: https://github.com/IDEA-Research/GroundingDINO +# Copyright (c) 2023 IDEA. All Rights Reserved. +# Licensed under the Apache License, Version 2.0 [see LICENSE for details] +# ------------------------------------------------------------------------ +# Deformable DETR +# Copyright (c) 2020 SenseTime. All Rights Reserved. +# Licensed under the Apache License, Version 2.0 [see LICENSE for details] +# ------------------------------------------------------------------------------------------------ +# Modified from: +# https://github.com/fundamentalvision/Deformable-DETR/blob/main/models/ops/functions/ms_deform_attn_func.py +# https://github.com/fundamentalvision/Deformable-DETR/blob/main/models/ops/modules/ms_deform_attn.py +# https://github.com/open-mmlab/mmcv/blob/master/mmcv/ops/multi_scale_deform_attn.py +# ------------------------------------------------------------------------------------------------ + +import math +import warnings +from typing import Optional + +import torch +import torch.nn as nn +import torch.nn.functional as F +from torch.nn.init import constant_, xavier_uniform_ + + +# helpers +def _is_power_of_2(n): + if (not isinstance(n, int)) or (n < 0): + raise ValueError("invalid input for _is_power_of_2: {} (type: {})".format(n, type(n))) + return (n & (n - 1) == 0) and n != 0 + + +def multi_scale_deformable_attn_pytorch( + value: torch.Tensor, + value_spatial_shapes: torch.Tensor, + sampling_locations: torch.Tensor, + attention_weights: torch.Tensor, +) -> torch.Tensor: + + bs, _, num_heads, embed_dims = value.shape + _, num_queries, num_heads, num_levels, num_points, _ = sampling_locations.shape + value_list = value.split([H_ * W_ for H_, W_ in value_spatial_shapes], dim=1) + sampling_grids = 2 * sampling_locations - 1 + sampling_value_list = [] + for level, (H_, W_) in enumerate(value_spatial_shapes): + # bs, H_*W_, num_heads, embed_dims -> + # bs, H_*W_, num_heads*embed_dims -> + # bs, num_heads*embed_dims, H_*W_ -> + # bs*num_heads, embed_dims, H_, W_ + value_l_ = ( + value_list[level].flatten(2).transpose(1, 2).reshape(bs * num_heads, embed_dims, H_, W_) + ) + # bs, num_queries, num_heads, num_points, 2 -> + # bs, num_heads, num_queries, num_points, 2 -> + # bs*num_heads, num_queries, num_points, 2 + sampling_grid_l_ = sampling_grids[:, :, :, level].transpose(1, 2).flatten(0, 1) + # bs*num_heads, embed_dims, num_queries, num_points + sampling_value_l_ = F.grid_sample( + value_l_, sampling_grid_l_, mode="bilinear", padding_mode="zeros", align_corners=False + ) + sampling_value_list.append(sampling_value_l_) + # (bs, num_queries, num_heads, num_levels, num_points) -> + # (bs, num_heads, num_queries, num_levels, num_points) -> + # (bs, num_heads, 1, num_queries, num_levels*num_points) + attention_weights = attention_weights.transpose(1, 2).reshape( + bs * num_heads, 1, num_queries, num_levels * num_points + ) + output = ( + (torch.stack(sampling_value_list, dim=-2).flatten(-2) * attention_weights) + .sum(-1) + .view(bs, num_heads * embed_dims, num_queries) + ) + return output.transpose(1, 2).contiguous() + + +class MultiScaleDeformableAttention(nn.Module): + """Multi-Scale Deformable Attention Module used in Deformable-DETR + + `Deformable DETR: Deformable Transformers for End-to-End Object Detection. + `_. + + Args: + embed_dim (int): The embedding dimension of Attention. Default: 256. + num_heads (int): The number of attention heads. Default: 8. + num_levels (int): The number of feature map used in Attention. Default: 4. + num_points (int): The number of sampling points for each query + in each head. Default: 4. + img2col_steps (int): The step used in image_to_column. Defualt: 64. + dropout (float): Dropout layer used in output. Default: 0.1. + batch_first (bool): if ``True``, then the input and output tensor will be + provided as `(bs, n, embed_dim)`. Default: False. `(n, bs, embed_dim)` + """ + + def __init__( + self, + embed_dim: int = 256, + num_heads: int = 8, + num_levels: int = 4, + num_points: int = 4, + img2col_step: int = 64, + batch_first: bool = False, + ): + super().__init__() + if embed_dim % num_heads != 0: + raise ValueError( + "embed_dim must be divisible by num_heads, but got {} and {}".format( + embed_dim, num_heads + ) + ) + head_dim = embed_dim // num_heads + + self.batch_first = batch_first + + if not _is_power_of_2(head_dim): + warnings.warn( + """ + You'd better set d_model in MSDeformAttn to make sure that + each dim of the attention head a power of 2, which is more efficient. + """ + ) + + self.im2col_step = img2col_step + self.embed_dim = embed_dim + self.num_heads = num_heads + self.num_levels = num_levels + self.num_points = num_points + self.sampling_offsets = nn.Linear(embed_dim, num_heads * num_levels * num_points * 2) + self.attention_weights = nn.Linear(embed_dim, num_heads * num_levels * num_points) + self.value_proj = nn.Linear(embed_dim, embed_dim) + self.output_proj = nn.Linear(embed_dim, embed_dim) + + self.init_weights() + + def _reset_parameters(self): + return self.init_weights() + + def init_weights(self): + """ + Default initialization for Parameters of Module. + """ + constant_(self.sampling_offsets.weight.data, 0.0) + thetas = torch.arange(self.num_heads, dtype=torch.float32) * ( + 2.0 * math.pi / self.num_heads + ) + grid_init = torch.stack([thetas.cos(), thetas.sin()], -1) + grid_init = ( + (grid_init / grid_init.abs().max(-1, keepdim=True)[0]) + .view(self.num_heads, 1, 1, 2) + .repeat(1, self.num_levels, self.num_points, 1) + ) + for i in range(self.num_points): + grid_init[:, :, i, :] *= i + 1 + with torch.no_grad(): + self.sampling_offsets.bias = nn.Parameter(grid_init.view(-1)) + constant_(self.attention_weights.weight.data, 0.0) + constant_(self.attention_weights.bias.data, 0.0) + xavier_uniform_(self.value_proj.weight.data) + constant_(self.value_proj.bias.data, 0.0) + xavier_uniform_(self.output_proj.weight.data) + constant_(self.output_proj.bias.data, 0.0) + + def freeze_sampling_offsets(self): + print("Freeze sampling offsets") + self.sampling_offsets.weight.requires_grad = False + self.sampling_offsets.bias.requires_grad = False + + def freeze_attention_weights(self): + print("Freeze attention weights") + self.attention_weights.weight.requires_grad = False + self.attention_weights.bias.requires_grad = False + + def forward( + self, + query: torch.Tensor, + key: Optional[torch.Tensor] = None, + value: Optional[torch.Tensor] = None, + query_pos: Optional[torch.Tensor] = None, + key_padding_mask: Optional[torch.Tensor] = None, + reference_points: Optional[torch.Tensor] = None, + spatial_shapes: Optional[torch.Tensor] = None, + level_start_index: Optional[torch.Tensor] = None, + **kwargs + ) -> torch.Tensor: + + """Forward Function of MultiScaleDeformableAttention + + Args: + query (torch.Tensor): Query embeddings with shape + `(num_query, bs, embed_dim)` + key (torch.Tensor): Key embeddings with shape + `(num_key, bs, embed_dim)` + value (torch.Tensor): Value embeddings with shape + `(num_key, bs, embed_dim)` + query_pos (torch.Tensor): The position embedding for `query`. Default: None. + key_padding_mask (torch.Tensor): ByteTensor for `query`, with shape `(bs, num_key)`, + indicating which elements within `key` to be ignored in attention. + reference_points (torch.Tensor): The normalized reference points + with shape `(bs, num_query, num_levels, 2)`, + all elements is range in [0, 1], top-left (0, 0), + bottom-right (1, 1), including padding are. + or `(N, Length_{query}, num_levels, 4)`, add additional + two dimensions `(h, w)` to form reference boxes. + spatial_shapes (torch.Tensor): Spatial shape of features in different levels. + With shape `(num_levels, 2)`, last dimension represents `(h, w)`. + level_start_index (torch.Tensor): The start index of each level. A tensor with + shape `(num_levels, )` which can be represented as + `[0, h_0 * w_0, h_0 * w_0 + h_1 * w_1, ...]`. + + Returns: + torch.Tensor: forward results with shape `(num_query, bs, embed_dim)` + """ + + if value is None: + value = query + + if query_pos is not None: + query = query + query_pos + + if not self.batch_first: + # change to (bs, num_query ,embed_dims) + query = query.permute(1, 0, 2) + value = value.permute(1, 0, 2) + + bs, num_query, _ = query.shape + bs, num_value, _ = value.shape + + assert (spatial_shapes[:, 0] * spatial_shapes[:, 1]).sum() == num_value + + value = self.value_proj(value) + if key_padding_mask is not None: + value = value.masked_fill(key_padding_mask[..., None], float(0)) + value = value.view(bs, num_value, self.num_heads, -1) + sampling_offsets = self.sampling_offsets(query).view( + bs, num_query, self.num_heads, self.num_levels, self.num_points, 2 + ) + attention_weights = self.attention_weights(query).view( + bs, num_query, self.num_heads, self.num_levels * self.num_points + ) + attention_weights = attention_weights.softmax(-1) + attention_weights = attention_weights.view( + bs, + num_query, + self.num_heads, + self.num_levels, + self.num_points, + ) + + # bs, num_query, num_heads, num_levels, num_points, 2 + if reference_points.shape[-1] == 2: + offset_normalizer = torch.stack([spatial_shapes[..., 1], spatial_shapes[..., 0]], -1) + sampling_locations = ( + reference_points[:, :, None, :, None, :] + + sampling_offsets / offset_normalizer[None, None, None, :, None, :] + ) + elif reference_points.shape[-1] == 4: + sampling_locations = ( + reference_points[:, :, None, :, None, :2] + + sampling_offsets + / self.num_points + * reference_points[:, :, None, :, None, 2:] + * 0.5 + ) + else: + raise ValueError( + "Last dim of reference_points must be 2 or 4, but get {} instead.".format( + reference_points.shape[-1] + ) + ) + + output = multi_scale_deformable_attn_pytorch( + value, spatial_shapes, sampling_locations, attention_weights + ) + + output = self.output_proj(output) + + if not self.batch_first: + output = output.permute(1, 0, 2) + + return output + + +def create_dummy_class(klass, dependency, message=""): + """ + When a dependency of a class is not available, create a dummy class which throws ImportError + when used. + + Args: + klass (str): name of the class. + dependency (str): name of the dependency. + message: extra message to print + Returns: + class: a class object + """ + err = "Cannot import '{}', therefore '{}' is not available.".format(dependency, klass) + if message: + err = err + " " + message + + class _DummyMetaClass(type): + # throw error on class attribute access + def __getattr__(_, __): # noqa: B902 + raise ImportError(err) + + class _Dummy(object, metaclass=_DummyMetaClass): + # throw error on constructor + def __init__(self, *args, **kwargs): + raise ImportError(err) + + return _Dummy + + +def create_dummy_func(func, dependency, message=""): + """ + When a dependency of a function is not available, create a dummy function which throws + ImportError when used. + + Args: + func (str): name of the function. + dependency (str or list[str]): name(s) of the dependency. + message: extra message to print + Returns: + function: a function object + """ + err = "Cannot import '{}', therefore '{}' is not available.".format(dependency, func) + if message: + err = err + " " + message + + if isinstance(dependency, (list, tuple)): + dependency = ",".join(dependency) + + def _dummy(*args, **kwargs): + raise ImportError(err) + + return _dummy diff --git a/py/local_groundingdino/models/GroundingDINO/transformer.py b/py/local_groundingdino/models/GroundingDINO/transformer.py new file mode 100644 index 0000000..47e87f3 --- /dev/null +++ b/py/local_groundingdino/models/GroundingDINO/transformer.py @@ -0,0 +1,959 @@ +# ------------------------------------------------------------------------ +# Grounding DINO +# url: https://github.com/IDEA-Research/GroundingDINO +# Copyright (c) 2023 IDEA. All Rights Reserved. +# Licensed under the Apache License, Version 2.0 [see LICENSE for details] +# ------------------------------------------------------------------------ +# DINO +# Copyright (c) 2022 IDEA. All Rights Reserved. +# Licensed under the Apache License, Version 2.0 [see LICENSE for details] +# ------------------------------------------------------------------------ +# Conditional DETR Transformer class. +# Copyright (c) 2021 Microsoft. All Rights Reserved. +# Licensed under the Apache License, Version 2.0 [see LICENSE for details] +# ------------------------------------------------------------------------ +# Modified from DETR (https://github.com/facebookresearch/detr) +# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. +# ------------------------------------------------------------------------ + +from typing import Optional + +import torch +import torch.utils.checkpoint as checkpoint +from torch import Tensor, nn + +from local_groundingdino.util.misc import inverse_sigmoid + +from .fuse_modules import BiAttentionBlock +from .ms_deform_attn import MultiScaleDeformableAttention as MSDeformAttn +from .transformer_vanilla import TransformerEncoderLayer +from .utils import ( + MLP, + _get_activation_fn, + _get_clones, + gen_encoder_output_proposals, + gen_sineembed_for_position, + get_sine_pos_embed, +) + + +class Transformer(nn.Module): + def __init__( + self, + d_model=256, + nhead=8, + num_queries=300, + num_encoder_layers=6, + num_unicoder_layers=0, + num_decoder_layers=6, + dim_feedforward=2048, + dropout=0.0, + activation="relu", + normalize_before=False, + return_intermediate_dec=False, + query_dim=4, + num_patterns=0, + # for deformable encoder + num_feature_levels=1, + enc_n_points=4, + dec_n_points=4, + # init query + learnable_tgt_init=False, + # two stage + two_stage_type="no", # ['no', 'standard', 'early', 'combine', 'enceachlayer', 'enclayer1'] + embed_init_tgt=False, + # for text + use_text_enhancer=False, + use_fusion_layer=False, + use_checkpoint=False, + use_transformer_ckpt=False, + use_text_cross_attention=False, + text_dropout=0.1, + fusion_dropout=0.1, + fusion_droppath=0.0, + ): + super().__init__() + self.num_feature_levels = num_feature_levels + self.num_encoder_layers = num_encoder_layers + self.num_unicoder_layers = num_unicoder_layers + self.num_decoder_layers = num_decoder_layers + self.num_queries = num_queries + assert query_dim == 4 + + # choose encoder layer type + encoder_layer = DeformableTransformerEncoderLayer( + d_model, dim_feedforward, dropout, activation, num_feature_levels, nhead, enc_n_points + ) + + if use_text_enhancer: + text_enhance_layer = TransformerEncoderLayer( + d_model=d_model, + nhead=nhead // 2, + dim_feedforward=dim_feedforward // 2, + dropout=text_dropout, + ) + else: + text_enhance_layer = None + + if use_fusion_layer: + feature_fusion_layer = BiAttentionBlock( + v_dim=d_model, + l_dim=d_model, + embed_dim=dim_feedforward // 2, + num_heads=nhead // 2, + dropout=fusion_dropout, + drop_path=fusion_droppath, + ) + else: + feature_fusion_layer = None + + encoder_norm = nn.LayerNorm(d_model) if normalize_before else None + assert encoder_norm is None + self.encoder = TransformerEncoder( + encoder_layer, + num_encoder_layers, + d_model=d_model, + num_queries=num_queries, + text_enhance_layer=text_enhance_layer, + feature_fusion_layer=feature_fusion_layer, + use_checkpoint=use_checkpoint, + use_transformer_ckpt=use_transformer_ckpt, + ) + + # choose decoder layer type + decoder_layer = DeformableTransformerDecoderLayer( + d_model, + dim_feedforward, + dropout, + activation, + num_feature_levels, + nhead, + dec_n_points, + use_text_cross_attention=use_text_cross_attention, + ) + + decoder_norm = nn.LayerNorm(d_model) + self.decoder = TransformerDecoder( + decoder_layer, + num_decoder_layers, + decoder_norm, + return_intermediate=return_intermediate_dec, + d_model=d_model, + query_dim=query_dim, + num_feature_levels=num_feature_levels, + ) + + self.d_model = d_model + self.nhead = nhead + self.dec_layers = num_decoder_layers + self.num_queries = num_queries # useful for single stage model only + self.num_patterns = num_patterns + if not isinstance(num_patterns, int): + Warning("num_patterns should be int but {}".format(type(num_patterns))) + self.num_patterns = 0 + + if num_feature_levels > 1: + if self.num_encoder_layers > 0: + self.level_embed = nn.Parameter(torch.Tensor(num_feature_levels, d_model)) + else: + self.level_embed = None + + self.learnable_tgt_init = learnable_tgt_init + assert learnable_tgt_init, "why not learnable_tgt_init" + self.embed_init_tgt = embed_init_tgt + if (two_stage_type != "no" and embed_init_tgt) or (two_stage_type == "no"): + self.tgt_embed = nn.Embedding(self.num_queries, d_model) + nn.init.normal_(self.tgt_embed.weight.data) + else: + self.tgt_embed = None + + # for two stage + self.two_stage_type = two_stage_type + assert two_stage_type in ["no", "standard"], "unknown param {} of two_stage_type".format( + two_stage_type + ) + if two_stage_type == "standard": + # anchor selection at the output of encoder + self.enc_output = nn.Linear(d_model, d_model) + self.enc_output_norm = nn.LayerNorm(d_model) + self.two_stage_wh_embedding = None + + if two_stage_type == "no": + self.init_ref_points(num_queries) # init self.refpoint_embed + + self.enc_out_class_embed = None + self.enc_out_bbox_embed = None + + self._reset_parameters() + + def _reset_parameters(self): + for p in self.parameters(): + if p.dim() > 1: + nn.init.xavier_uniform_(p) + for m in self.modules(): + if isinstance(m, MSDeformAttn): + m._reset_parameters() + if self.num_feature_levels > 1 and self.level_embed is not None: + nn.init.normal_(self.level_embed) + + def get_valid_ratio(self, mask): + _, H, W = mask.shape + valid_H = torch.sum(~mask[:, :, 0], 1) + valid_W = torch.sum(~mask[:, 0, :], 1) + valid_ratio_h = valid_H.float() / H + valid_ratio_w = valid_W.float() / W + valid_ratio = torch.stack([valid_ratio_w, valid_ratio_h], -1) + return valid_ratio + + def init_ref_points(self, use_num_queries): + self.refpoint_embed = nn.Embedding(use_num_queries, 4) + + def forward(self, srcs, masks, refpoint_embed, pos_embeds, tgt, attn_mask=None, text_dict=None): + """ + Input: + - srcs: List of multi features [bs, ci, hi, wi] + - masks: List of multi masks [bs, hi, wi] + - refpoint_embed: [bs, num_dn, 4]. None in infer + - pos_embeds: List of multi pos embeds [bs, ci, hi, wi] + - tgt: [bs, num_dn, d_model]. None in infer + + """ + # prepare input for encoder + src_flatten = [] + mask_flatten = [] + lvl_pos_embed_flatten = [] + spatial_shapes = [] + for lvl, (src, mask, pos_embed) in enumerate(zip(srcs, masks, pos_embeds)): + bs, c, h, w = src.shape + spatial_shape = (h, w) + spatial_shapes.append(spatial_shape) + + src = src.flatten(2).transpose(1, 2) # bs, hw, c + mask = mask.flatten(1) # bs, hw + pos_embed = pos_embed.flatten(2).transpose(1, 2) # bs, hw, c + if self.num_feature_levels > 1 and self.level_embed is not None: + lvl_pos_embed = pos_embed + self.level_embed[lvl].view(1, 1, -1) + else: + lvl_pos_embed = pos_embed + lvl_pos_embed_flatten.append(lvl_pos_embed) + src_flatten.append(src) + mask_flatten.append(mask) + src_flatten = torch.cat(src_flatten, 1) # bs, \sum{hxw}, c + mask_flatten = torch.cat(mask_flatten, 1) # bs, \sum{hxw} + lvl_pos_embed_flatten = torch.cat(lvl_pos_embed_flatten, 1) # bs, \sum{hxw}, c + spatial_shapes = torch.as_tensor( + spatial_shapes, dtype=torch.long, device=src_flatten.device + ) + level_start_index = torch.cat( + (spatial_shapes.new_zeros((1,)), spatial_shapes.prod(1).cumsum(0)[:-1]) + ) + valid_ratios = torch.stack([self.get_valid_ratio(m) for m in masks], 1) + + # two stage + enc_topk_proposals = enc_refpoint_embed = None + + ######################################################### + # Begin Encoder + ######################################################### + memory, memory_text = self.encoder( + src_flatten, + pos=lvl_pos_embed_flatten, + level_start_index=level_start_index, + spatial_shapes=spatial_shapes, + valid_ratios=valid_ratios, + key_padding_mask=mask_flatten, + memory_text=text_dict["encoded_text"], + text_attention_mask=~text_dict["text_token_mask"], + # we ~ the mask . False means use the token; True means pad the token + position_ids=text_dict["position_ids"], + text_self_attention_masks=text_dict["text_self_attention_masks"], + ) + ######################################################### + # End Encoder + # - memory: bs, \sum{hw}, c + # - mask_flatten: bs, \sum{hw} + # - lvl_pos_embed_flatten: bs, \sum{hw}, c + # - enc_intermediate_output: None or (nenc+1, bs, nq, c) or (nenc, bs, nq, c) + # - enc_intermediate_refpoints: None or (nenc+1, bs, nq, c) or (nenc, bs, nq, c) + ######################################################### + text_dict["encoded_text"] = memory_text + # if os.environ.get("SHILONG_AMP_INFNAN_DEBUG") == '1': + # if memory.isnan().any() | memory.isinf().any(): + # import ipdb; ipdb.set_trace() + + if self.two_stage_type == "standard": + output_memory, output_proposals = gen_encoder_output_proposals( + memory, mask_flatten, spatial_shapes + ) + output_memory = self.enc_output_norm(self.enc_output(output_memory)) + + if text_dict is not None: + enc_outputs_class_unselected = self.enc_out_class_embed(output_memory, text_dict) + else: + enc_outputs_class_unselected = self.enc_out_class_embed(output_memory) + + topk_logits = enc_outputs_class_unselected.max(-1)[0] + enc_outputs_coord_unselected = ( + self.enc_out_bbox_embed(output_memory) + output_proposals + ) # (bs, \sum{hw}, 4) unsigmoid + topk = self.num_queries + + topk_proposals = torch.topk(topk_logits, topk, dim=1)[1] # bs, nq + + # gather boxes + refpoint_embed_undetach = torch.gather( + enc_outputs_coord_unselected, 1, topk_proposals.unsqueeze(-1).repeat(1, 1, 4) + ) # unsigmoid + refpoint_embed_ = refpoint_embed_undetach.detach() + init_box_proposal = torch.gather( + output_proposals, 1, topk_proposals.unsqueeze(-1).repeat(1, 1, 4) + ).sigmoid() # sigmoid + + # gather tgt + tgt_undetach = torch.gather( + output_memory, 1, topk_proposals.unsqueeze(-1).repeat(1, 1, self.d_model) + ) + if self.embed_init_tgt: + tgt_ = ( + self.tgt_embed.weight[:, None, :].repeat(1, bs, 1).transpose(0, 1) + ) # nq, bs, d_model + else: + tgt_ = tgt_undetach.detach() + + if refpoint_embed is not None: + refpoint_embed = torch.cat([refpoint_embed, refpoint_embed_], dim=1) + tgt = torch.cat([tgt, tgt_], dim=1) + else: + refpoint_embed, tgt = refpoint_embed_, tgt_ + + elif self.two_stage_type == "no": + tgt_ = ( + self.tgt_embed.weight[:, None, :].repeat(1, bs, 1).transpose(0, 1) + ) # nq, bs, d_model + refpoint_embed_ = ( + self.refpoint_embed.weight[:, None, :].repeat(1, bs, 1).transpose(0, 1) + ) # nq, bs, 4 + + if refpoint_embed is not None: + refpoint_embed = torch.cat([refpoint_embed, refpoint_embed_], dim=1) + tgt = torch.cat([tgt, tgt_], dim=1) + else: + refpoint_embed, tgt = refpoint_embed_, tgt_ + + if self.num_patterns > 0: + tgt_embed = tgt.repeat(1, self.num_patterns, 1) + refpoint_embed = refpoint_embed.repeat(1, self.num_patterns, 1) + tgt_pat = self.patterns.weight[None, :, :].repeat_interleave( + self.num_queries, 1 + ) # 1, n_q*n_pat, d_model + tgt = tgt_embed + tgt_pat + + init_box_proposal = refpoint_embed_.sigmoid() + + else: + raise NotImplementedError("unknown two_stage_type {}".format(self.two_stage_type)) + ######################################################### + # End preparing tgt + # - tgt: bs, NQ, d_model + # - refpoint_embed(unsigmoid): bs, NQ, d_model + ######################################################### + + ######################################################### + # Begin Decoder + ######################################################### + hs, references = self.decoder( + tgt=tgt.transpose(0, 1), + memory=memory.transpose(0, 1), + memory_key_padding_mask=mask_flatten, + pos=lvl_pos_embed_flatten.transpose(0, 1), + refpoints_unsigmoid=refpoint_embed.transpose(0, 1), + level_start_index=level_start_index, + spatial_shapes=spatial_shapes, + valid_ratios=valid_ratios, + tgt_mask=attn_mask, + memory_text=text_dict["encoded_text"], + text_attention_mask=~text_dict["text_token_mask"], + # we ~ the mask . False means use the token; True means pad the token + ) + ######################################################### + # End Decoder + # hs: n_dec, bs, nq, d_model + # references: n_dec+1, bs, nq, query_dim + ######################################################### + + ######################################################### + # Begin postprocess + ######################################################### + if self.two_stage_type == "standard": + hs_enc = tgt_undetach.unsqueeze(0) + ref_enc = refpoint_embed_undetach.sigmoid().unsqueeze(0) + else: + hs_enc = ref_enc = None + ######################################################### + # End postprocess + # hs_enc: (n_enc+1, bs, nq, d_model) or (1, bs, nq, d_model) or (n_enc, bs, nq, d_model) or None + # ref_enc: (n_enc+1, bs, nq, query_dim) or (1, bs, nq, query_dim) or (n_enc, bs, nq, d_model) or None + ######################################################### + + return hs, references, hs_enc, ref_enc, init_box_proposal + # hs: (n_dec, bs, nq, d_model) + # references: sigmoid coordinates. (n_dec+1, bs, bq, 4) + # hs_enc: (n_enc+1, bs, nq, d_model) or (1, bs, nq, d_model) or None + # ref_enc: sigmoid coordinates. \ + # (n_enc+1, bs, nq, query_dim) or (1, bs, nq, query_dim) or None + + +class TransformerEncoder(nn.Module): + def __init__( + self, + encoder_layer, + num_layers, + d_model=256, + num_queries=300, + enc_layer_share=False, + text_enhance_layer=None, + feature_fusion_layer=None, + use_checkpoint=False, + use_transformer_ckpt=False, + ): + """_summary_ + + Args: + encoder_layer (_type_): _description_ + num_layers (_type_): _description_ + norm (_type_, optional): _description_. Defaults to None. + d_model (int, optional): _description_. Defaults to 256. + num_queries (int, optional): _description_. Defaults to 300. + enc_layer_share (bool, optional): _description_. Defaults to False. + + """ + super().__init__() + # prepare layers + self.layers = [] + self.text_layers = [] + self.fusion_layers = [] + if num_layers > 0: + self.layers = _get_clones(encoder_layer, num_layers, layer_share=enc_layer_share) + + if text_enhance_layer is not None: + self.text_layers = _get_clones( + text_enhance_layer, num_layers, layer_share=enc_layer_share + ) + if feature_fusion_layer is not None: + self.fusion_layers = _get_clones( + feature_fusion_layer, num_layers, layer_share=enc_layer_share + ) + else: + self.layers = [] + del encoder_layer + + if text_enhance_layer is not None: + self.text_layers = [] + del text_enhance_layer + if feature_fusion_layer is not None: + self.fusion_layers = [] + del feature_fusion_layer + + self.query_scale = None + self.num_queries = num_queries + self.num_layers = num_layers + self.d_model = d_model + + self.use_checkpoint = use_checkpoint + self.use_transformer_ckpt = use_transformer_ckpt + + @staticmethod + def get_reference_points(spatial_shapes, valid_ratios, device): + reference_points_list = [] + for lvl, (H_, W_) in enumerate(spatial_shapes): + + ref_y, ref_x = torch.meshgrid( + torch.linspace(0.5, H_ - 0.5, H_, dtype=torch.float32, device=device), + torch.linspace(0.5, W_ - 0.5, W_, dtype=torch.float32, device=device), + ) + ref_y = ref_y.reshape(-1)[None] / (valid_ratios[:, None, lvl, 1] * H_) + ref_x = ref_x.reshape(-1)[None] / (valid_ratios[:, None, lvl, 0] * W_) + ref = torch.stack((ref_x, ref_y), -1) + reference_points_list.append(ref) + reference_points = torch.cat(reference_points_list, 1) + reference_points = reference_points[:, :, None] * valid_ratios[:, None] + return reference_points + + def forward( + self, + # for images + src: Tensor, + pos: Tensor, + spatial_shapes: Tensor, + level_start_index: Tensor, + valid_ratios: Tensor, + key_padding_mask: Tensor, + # for texts + memory_text: Tensor = None, + text_attention_mask: Tensor = None, + pos_text: Tensor = None, + text_self_attention_masks: Tensor = None, + position_ids: Tensor = None, + ): + """ + Input: + - src: [bs, sum(hi*wi), 256] + - pos: pos embed for src. [bs, sum(hi*wi), 256] + - spatial_shapes: h,w of each level [num_level, 2] + - level_start_index: [num_level] start point of level in sum(hi*wi). + - valid_ratios: [bs, num_level, 2] + - key_padding_mask: [bs, sum(hi*wi)] + + - memory_text: bs, n_text, 256 + - text_attention_mask: bs, n_text + False for no padding; True for padding + - pos_text: bs, n_text, 256 + + - position_ids: bs, n_text + Intermedia: + - reference_points: [bs, sum(hi*wi), num_level, 2] + Outpus: + - output: [bs, sum(hi*wi), 256] + """ + + output = src + + # preparation and reshape + if self.num_layers > 0: + reference_points = self.get_reference_points( + spatial_shapes, valid_ratios, device=src.device + ) + + if self.text_layers: + # generate pos_text + bs, n_text, text_dim = memory_text.shape + if pos_text is None and position_ids is None: + pos_text = ( + torch.arange(n_text, device=memory_text.device) + .float() + .unsqueeze(0) + .unsqueeze(-1) + .repeat(bs, 1, 1) + ) + pos_text = get_sine_pos_embed(pos_text, num_pos_feats=256, exchange_xy=False) + if position_ids is not None: + pos_text = get_sine_pos_embed( + position_ids[..., None], num_pos_feats=256, exchange_xy=False + ) + + # main process + for layer_id, layer in enumerate(self.layers): + # if output.isnan().any() or memory_text.isnan().any(): + # if os.environ.get('IPDB_SHILONG_DEBUG', None) == 'INFO': + # import ipdb; ipdb.set_trace() + if self.fusion_layers: + if self.use_checkpoint: + output, memory_text = checkpoint.checkpoint( + self.fusion_layers[layer_id], + output, + memory_text, + key_padding_mask, + text_attention_mask, + ) + else: + output, memory_text = self.fusion_layers[layer_id]( + v=output, + l=memory_text, + attention_mask_v=key_padding_mask, + attention_mask_l=text_attention_mask, + ) + + if self.text_layers: + memory_text = self.text_layers[layer_id]( + src=memory_text.transpose(0, 1), + src_mask=~text_self_attention_masks, # note we use ~ for mask here + src_key_padding_mask=text_attention_mask, + pos=(pos_text.transpose(0, 1) if pos_text is not None else None), + ).transpose(0, 1) + + # main process + if self.use_transformer_ckpt: + output = checkpoint.checkpoint( + layer, + output, + pos, + reference_points, + spatial_shapes, + level_start_index, + key_padding_mask, + ) + else: + output = layer( + src=output, + pos=pos, + reference_points=reference_points, + spatial_shapes=spatial_shapes, + level_start_index=level_start_index, + key_padding_mask=key_padding_mask, + ) + + return output, memory_text + + +class TransformerDecoder(nn.Module): + def __init__( + self, + decoder_layer, + num_layers, + norm=None, + return_intermediate=False, + d_model=256, + query_dim=4, + num_feature_levels=1, + ): + super().__init__() + if num_layers > 0: + self.layers = _get_clones(decoder_layer, num_layers) + else: + self.layers = [] + self.num_layers = num_layers + self.norm = norm + self.return_intermediate = return_intermediate + assert return_intermediate, "support return_intermediate only" + self.query_dim = query_dim + assert query_dim in [2, 4], "query_dim should be 2/4 but {}".format(query_dim) + self.num_feature_levels = num_feature_levels + + self.ref_point_head = MLP(query_dim // 2 * d_model, d_model, d_model, 2) + self.query_pos_sine_scale = None + + self.query_scale = None + self.bbox_embed = None + self.class_embed = None + + self.d_model = d_model + + self.ref_anchor_head = None + + def forward( + self, + tgt, + memory, + tgt_mask: Optional[Tensor] = None, + memory_mask: Optional[Tensor] = None, + tgt_key_padding_mask: Optional[Tensor] = None, + memory_key_padding_mask: Optional[Tensor] = None, + pos: Optional[Tensor] = None, + refpoints_unsigmoid: Optional[Tensor] = None, # num_queries, bs, 2 + # for memory + level_start_index: Optional[Tensor] = None, # num_levels + spatial_shapes: Optional[Tensor] = None, # bs, num_levels, 2 + valid_ratios: Optional[Tensor] = None, + # for text + memory_text: Optional[Tensor] = None, + text_attention_mask: Optional[Tensor] = None, + ): + """ + Input: + - tgt: nq, bs, d_model + - memory: hw, bs, d_model + - pos: hw, bs, d_model + - refpoints_unsigmoid: nq, bs, 2/4 + - valid_ratios/spatial_shapes: bs, nlevel, 2 + """ + output = tgt + + intermediate = [] + reference_points = refpoints_unsigmoid.sigmoid() + ref_points = [reference_points] + + for layer_id, layer in enumerate(self.layers): + + if reference_points.shape[-1] == 4: + reference_points_input = ( + reference_points[:, :, None] + * torch.cat([valid_ratios, valid_ratios], -1)[None, :] + ) # nq, bs, nlevel, 4 + else: + assert reference_points.shape[-1] == 2 + reference_points_input = reference_points[:, :, None] * valid_ratios[None, :] + query_sine_embed = gen_sineembed_for_position( + reference_points_input[:, :, 0, :] + ) # nq, bs, 256*2 + + # conditional query + raw_query_pos = self.ref_point_head(query_sine_embed) # nq, bs, 256 + pos_scale = self.query_scale(output) if self.query_scale is not None else 1 + query_pos = pos_scale * raw_query_pos + # if os.environ.get("SHILONG_AMP_INFNAN_DEBUG") == '1': + # if query_pos.isnan().any() | query_pos.isinf().any(): + # import ipdb; ipdb.set_trace() + + # main process + output = layer( + tgt=output, + tgt_query_pos=query_pos, + tgt_query_sine_embed=query_sine_embed, + tgt_key_padding_mask=tgt_key_padding_mask, + tgt_reference_points=reference_points_input, + memory_text=memory_text, + text_attention_mask=text_attention_mask, + memory=memory, + memory_key_padding_mask=memory_key_padding_mask, + memory_level_start_index=level_start_index, + memory_spatial_shapes=spatial_shapes, + memory_pos=pos, + self_attn_mask=tgt_mask, + cross_attn_mask=memory_mask, + ) + if output.isnan().any() | output.isinf().any(): + print(f"output layer_id {layer_id} is nan") + try: + num_nan = output.isnan().sum().item() + num_inf = output.isinf().sum().item() + print(f"num_nan {num_nan}, num_inf {num_inf}") + except Exception as e: + print(e) + # if os.environ.get("SHILONG_AMP_INFNAN_DEBUG") == '1': + # import ipdb; ipdb.set_trace() + + # iter update + if self.bbox_embed is not None: + # box_holder = self.bbox_embed(output) + # box_holder[..., :self.query_dim] += inverse_sigmoid(reference_points) + # new_reference_points = box_holder[..., :self.query_dim].sigmoid() + + reference_before_sigmoid = inverse_sigmoid(reference_points) + delta_unsig = self.bbox_embed[layer_id](output) + outputs_unsig = delta_unsig + reference_before_sigmoid + new_reference_points = outputs_unsig.sigmoid() + + reference_points = new_reference_points.detach() + # if layer_id != self.num_layers - 1: + ref_points.append(new_reference_points) + + intermediate.append(self.norm(output)) + + return [ + [itm_out.transpose(0, 1) for itm_out in intermediate], + [itm_refpoint.transpose(0, 1) for itm_refpoint in ref_points], + ] + + +class DeformableTransformerEncoderLayer(nn.Module): + def __init__( + self, + d_model=256, + d_ffn=1024, + dropout=0.1, + activation="relu", + n_levels=4, + n_heads=8, + n_points=4, + ): + super().__init__() + + # self attention + self.self_attn = MSDeformAttn( + embed_dim=d_model, + num_levels=n_levels, + num_heads=n_heads, + num_points=n_points, + batch_first=True, + ) + self.dropout1 = nn.Dropout(dropout) + self.norm1 = nn.LayerNorm(d_model) + + # ffn + self.linear1 = nn.Linear(d_model, d_ffn) + self.activation = _get_activation_fn(activation, d_model=d_ffn) + self.dropout2 = nn.Dropout(dropout) + self.linear2 = nn.Linear(d_ffn, d_model) + self.dropout3 = nn.Dropout(dropout) + self.norm2 = nn.LayerNorm(d_model) + + @staticmethod + def with_pos_embed(tensor, pos): + return tensor if pos is None else tensor + pos + + def forward_ffn(self, src): + src2 = self.linear2(self.dropout2(self.activation(self.linear1(src)))) + src = src + self.dropout3(src2) + src = self.norm2(src) + return src + + def forward( + self, src, pos, reference_points, spatial_shapes, level_start_index, key_padding_mask=None + ): + # self attention + # import ipdb; ipdb.set_trace() + src2 = self.self_attn( + query=self.with_pos_embed(src, pos), + reference_points=reference_points, + value=src, + spatial_shapes=spatial_shapes, + level_start_index=level_start_index, + key_padding_mask=key_padding_mask, + ) + src = src + self.dropout1(src2) + src = self.norm1(src) + + # ffn + src = self.forward_ffn(src) + + return src + + +class DeformableTransformerDecoderLayer(nn.Module): + def __init__( + self, + d_model=256, + d_ffn=1024, + dropout=0.1, + activation="relu", + n_levels=4, + n_heads=8, + n_points=4, + use_text_feat_guide=False, + use_text_cross_attention=False, + ): + super().__init__() + + # cross attention + self.cross_attn = MSDeformAttn( + embed_dim=d_model, + num_levels=n_levels, + num_heads=n_heads, + num_points=n_points, + batch_first=True, + ) + self.dropout1 = nn.Dropout(dropout) if dropout > 0 else nn.Identity() + self.norm1 = nn.LayerNorm(d_model) + + # cross attention text + if use_text_cross_attention: + self.ca_text = nn.MultiheadAttention(d_model, n_heads, dropout=dropout) + self.catext_dropout = nn.Dropout(dropout) if dropout > 0 else nn.Identity() + self.catext_norm = nn.LayerNorm(d_model) + + # self attention + self.self_attn = nn.MultiheadAttention(d_model, n_heads, dropout=dropout) + self.dropout2 = nn.Dropout(dropout) if dropout > 0 else nn.Identity() + self.norm2 = nn.LayerNorm(d_model) + + # ffn + self.linear1 = nn.Linear(d_model, d_ffn) + self.activation = _get_activation_fn(activation, d_model=d_ffn, batch_dim=1) + self.dropout3 = nn.Dropout(dropout) if dropout > 0 else nn.Identity() + self.linear2 = nn.Linear(d_ffn, d_model) + self.dropout4 = nn.Dropout(dropout) if dropout > 0 else nn.Identity() + self.norm3 = nn.LayerNorm(d_model) + + self.key_aware_proj = None + self.use_text_feat_guide = use_text_feat_guide + assert not use_text_feat_guide + self.use_text_cross_attention = use_text_cross_attention + + def rm_self_attn_modules(self): + self.self_attn = None + self.dropout2 = None + self.norm2 = None + + @staticmethod + def with_pos_embed(tensor, pos): + return tensor if pos is None else tensor + pos + + def forward_ffn(self, tgt): + with torch.cuda.amp.autocast(enabled=False): + tgt2 = self.linear2(self.dropout3(self.activation(self.linear1(tgt)))) + tgt = tgt + self.dropout4(tgt2) + tgt = self.norm3(tgt) + return tgt + + def forward( + self, + # for tgt + tgt: Optional[Tensor], # nq, bs, d_model + tgt_query_pos: Optional[Tensor] = None, # pos for query. MLP(Sine(pos)) + tgt_query_sine_embed: Optional[Tensor] = None, # pos for query. Sine(pos) + tgt_key_padding_mask: Optional[Tensor] = None, + tgt_reference_points: Optional[Tensor] = None, # nq, bs, 4 + memory_text: Optional[Tensor] = None, # bs, num_token, d_model + text_attention_mask: Optional[Tensor] = None, # bs, num_token + # for memory + memory: Optional[Tensor] = None, # hw, bs, d_model + memory_key_padding_mask: Optional[Tensor] = None, + memory_level_start_index: Optional[Tensor] = None, # num_levels + memory_spatial_shapes: Optional[Tensor] = None, # bs, num_levels, 2 + memory_pos: Optional[Tensor] = None, # pos for memory + # sa + self_attn_mask: Optional[Tensor] = None, # mask used for self-attention + cross_attn_mask: Optional[Tensor] = None, # mask used for cross-attention + ): + """ + Input: + - tgt/tgt_query_pos: nq, bs, d_model + - + """ + assert cross_attn_mask is None + + # self attention + if self.self_attn is not None: + # import ipdb; ipdb.set_trace() + q = k = self.with_pos_embed(tgt, tgt_query_pos) + tgt2 = self.self_attn(q, k, tgt, attn_mask=self_attn_mask)[0] + tgt = tgt + self.dropout2(tgt2) + tgt = self.norm2(tgt) + + if self.use_text_cross_attention: + tgt2 = self.ca_text( + self.with_pos_embed(tgt, tgt_query_pos), + memory_text.transpose(0, 1), + memory_text.transpose(0, 1), + key_padding_mask=text_attention_mask, + )[0] + tgt = tgt + self.catext_dropout(tgt2) + tgt = self.catext_norm(tgt) + + tgt2 = self.cross_attn( + query=self.with_pos_embed(tgt, tgt_query_pos).transpose(0, 1), + reference_points=tgt_reference_points.transpose(0, 1).contiguous(), + value=memory.transpose(0, 1), + spatial_shapes=memory_spatial_shapes, + level_start_index=memory_level_start_index, + key_padding_mask=memory_key_padding_mask, + ).transpose(0, 1) + tgt = tgt + self.dropout1(tgt2) + tgt = self.norm1(tgt) + + # ffn + tgt = self.forward_ffn(tgt) + + return tgt + + +def build_transformer(args): + return Transformer( + d_model=args.hidden_dim, + dropout=args.dropout, + nhead=args.nheads, + num_queries=args.num_queries, + dim_feedforward=args.dim_feedforward, + num_encoder_layers=args.enc_layers, + num_decoder_layers=args.dec_layers, + normalize_before=args.pre_norm, + return_intermediate_dec=True, + query_dim=args.query_dim, + activation=args.transformer_activation, + num_patterns=args.num_patterns, + num_feature_levels=args.num_feature_levels, + enc_n_points=args.enc_n_points, + dec_n_points=args.dec_n_points, + learnable_tgt_init=True, + # two stage + two_stage_type=args.two_stage_type, # ['no', 'standard', 'early'] + embed_init_tgt=args.embed_init_tgt, + use_text_enhancer=args.use_text_enhancer, + use_fusion_layer=args.use_fusion_layer, + use_checkpoint=args.use_checkpoint, + use_transformer_ckpt=args.use_transformer_ckpt, + use_text_cross_attention=args.use_text_cross_attention, + text_dropout=args.text_dropout, + fusion_dropout=args.fusion_dropout, + fusion_droppath=args.fusion_droppath, + ) diff --git a/py/local_groundingdino/models/GroundingDINO/transformer_vanilla.py b/py/local_groundingdino/models/GroundingDINO/transformer_vanilla.py new file mode 100644 index 0000000..85f6822 --- /dev/null +++ b/py/local_groundingdino/models/GroundingDINO/transformer_vanilla.py @@ -0,0 +1,118 @@ +# ------------------------------------------------------------------------ +# Grounding DINO +# url: https://github.com/IDEA-Research/GroundingDINO +# Copyright (c) 2023 IDEA. All Rights Reserved. +# Licensed under the Apache License, Version 2.0 [see LICENSE for details] +# ------------------------------------------------------------------------ +# Copyright (c) Aishwarya Kamath & Nicolas Carion. Licensed under the Apache License 2.0. All Rights Reserved +# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved +""" +DETR Transformer class. + +Copy-paste from torch.nn.Transformer with modifications: + * positional encodings are passed in MHattention + * extra LN at the end of encoder is removed + * decoder returns a stack of activations from all decoding layers +""" +from typing import Optional + +import torch +from torch import Tensor, nn + +from .utils import ( + _get_activation_fn, + _get_clones, +) + + +class TextTransformer(nn.Module): + def __init__(self, num_layers, d_model=256, nheads=8, dim_feedforward=2048, dropout=0.1): + super().__init__() + self.num_layers = num_layers + self.d_model = d_model + self.nheads = nheads + self.dim_feedforward = dim_feedforward + self.norm = None + + single_encoder_layer = TransformerEncoderLayer( + d_model=d_model, nhead=nheads, dim_feedforward=dim_feedforward, dropout=dropout + ) + self.layers = _get_clones(single_encoder_layer, num_layers) + + def forward(self, memory_text: torch.Tensor, text_attention_mask: torch.Tensor): + """ + + Args: + text_attention_mask: bs, num_token + memory_text: bs, num_token, d_model + + Raises: + RuntimeError: _description_ + + Returns: + output: bs, num_token, d_model + """ + + output = memory_text.transpose(0, 1) + + for layer in self.layers: + output = layer(output, src_key_padding_mask=text_attention_mask) + + if self.norm is not None: + output = self.norm(output) + + return output.transpose(0, 1) + + +class TransformerEncoderLayer(nn.Module): + def __init__( + self, + d_model, + nhead, + dim_feedforward=2048, + dropout=0.1, + activation="relu", + normalize_before=False, + ): + super().__init__() + self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout) + # Implementation of Feedforward model + self.linear1 = nn.Linear(d_model, dim_feedforward) + self.dropout = nn.Dropout(dropout) + self.linear2 = nn.Linear(dim_feedforward, d_model) + + self.norm1 = nn.LayerNorm(d_model) + self.norm2 = nn.LayerNorm(d_model) + self.dropout1 = nn.Dropout(dropout) + self.dropout2 = nn.Dropout(dropout) + + self.activation = _get_activation_fn(activation) + self.normalize_before = normalize_before + self.nhead = nhead + + def with_pos_embed(self, tensor, pos: Optional[Tensor]): + return tensor if pos is None else tensor + pos + + def forward( + self, + src, + src_mask: Optional[Tensor] = None, + src_key_padding_mask: Optional[Tensor] = None, + pos: Optional[Tensor] = None, + ): + # repeat attn mask + if src_mask.dim() == 3 and src_mask.shape[0] == src.shape[1]: + # bs, num_q, num_k + src_mask = src_mask.repeat(self.nhead, 1, 1) + + q = k = self.with_pos_embed(src, pos) + + src2 = self.self_attn(q, k, value=src, attn_mask=src_mask)[0] + + # src2 = self.self_attn(q, k, value=src, attn_mask=src_mask, key_padding_mask=src_key_padding_mask)[0] + src = src + self.dropout1(src2) + src = self.norm1(src) + src2 = self.linear2(self.dropout(self.activation(self.linear1(src)))) + src = src + self.dropout2(src2) + src = self.norm2(src) + return src diff --git a/py/local_groundingdino/models/GroundingDINO/utils.py b/py/local_groundingdino/models/GroundingDINO/utils.py new file mode 100644 index 0000000..5bd18f7 --- /dev/null +++ b/py/local_groundingdino/models/GroundingDINO/utils.py @@ -0,0 +1,268 @@ +# ------------------------------------------------------------------------ +# Grounding DINO +# url: https://github.com/IDEA-Research/GroundingDINO +# Copyright (c) 2023 IDEA. All Rights Reserved. +# Licensed under the Apache License, Version 2.0 [see LICENSE for details] +# ------------------------------------------------------------------------ + +import copy +import math + +import torch +import torch.nn.functional as F +from torch import Tensor, nn + + +def _get_clones(module, N, layer_share=False): + # import ipdb; ipdb.set_trace() + if layer_share: + return nn.ModuleList([module for i in range(N)]) + else: + return nn.ModuleList([copy.deepcopy(module) for i in range(N)]) + + +def get_sine_pos_embed( + pos_tensor: torch.Tensor, + num_pos_feats: int = 128, + temperature: int = 10000, + exchange_xy: bool = True, +): + """generate sine position embedding from a position tensor + Args: + pos_tensor (torch.Tensor): shape: [..., n]. + num_pos_feats (int): projected shape for each float in the tensor. + temperature (int): temperature in the sine/cosine function. + exchange_xy (bool, optional): exchange pos x and pos y. \ + For example, input tensor is [x,y], the results will be [pos(y), pos(x)]. Defaults to True. + Returns: + pos_embed (torch.Tensor): shape: [..., n*num_pos_feats]. + """ + scale = 2 * math.pi + dim_t = torch.arange(num_pos_feats, dtype=torch.float32, device=pos_tensor.device) + dim_t = temperature ** (2 * torch.div(dim_t, 2, rounding_mode="floor") / num_pos_feats) + + def sine_func(x: torch.Tensor): + sin_x = x * scale / dim_t + sin_x = torch.stack((sin_x[..., 0::2].sin(), sin_x[..., 1::2].cos()), dim=3).flatten(2) + return sin_x + + pos_res = [sine_func(x) for x in pos_tensor.split([1] * pos_tensor.shape[-1], dim=-1)] + if exchange_xy: + pos_res[0], pos_res[1] = pos_res[1], pos_res[0] + pos_res = torch.cat(pos_res, dim=-1) + return pos_res + + +def gen_encoder_output_proposals( + memory: Tensor, memory_padding_mask: Tensor, spatial_shapes: Tensor, learnedwh=None +): + """ + Input: + - memory: bs, \sum{hw}, d_model + - memory_padding_mask: bs, \sum{hw} + - spatial_shapes: nlevel, 2 + - learnedwh: 2 + Output: + - output_memory: bs, \sum{hw}, d_model + - output_proposals: bs, \sum{hw}, 4 + """ + N_, S_, C_ = memory.shape + proposals = [] + _cur = 0 + for lvl, (H_, W_) in enumerate(spatial_shapes): + mask_flatten_ = memory_padding_mask[:, _cur : (_cur + H_ * W_)].view(N_, H_, W_, 1) + valid_H = torch.sum(~mask_flatten_[:, :, 0, 0], 1) + valid_W = torch.sum(~mask_flatten_[:, 0, :, 0], 1) + + # import ipdb; ipdb.set_trace() + + grid_y, grid_x = torch.meshgrid( + torch.linspace(0, H_ - 1, H_, dtype=torch.float32, device=memory.device), + torch.linspace(0, W_ - 1, W_, dtype=torch.float32, device=memory.device), + ) + grid = torch.cat([grid_x.unsqueeze(-1), grid_y.unsqueeze(-1)], -1) # H_, W_, 2 + + scale = torch.cat([valid_W.unsqueeze(-1), valid_H.unsqueeze(-1)], 1).view(N_, 1, 1, 2) + grid = (grid.unsqueeze(0).expand(N_, -1, -1, -1) + 0.5) / scale + + if learnedwh is not None: + # import ipdb; ipdb.set_trace() + wh = torch.ones_like(grid) * learnedwh.sigmoid() * (2.0**lvl) + else: + wh = torch.ones_like(grid) * 0.05 * (2.0**lvl) + + # scale = torch.cat([W_[None].unsqueeze(-1), H_[None].unsqueeze(-1)], 1).view(1, 1, 1, 2).repeat(N_, 1, 1, 1) + # grid = (grid.unsqueeze(0).expand(N_, -1, -1, -1) + 0.5) / scale + # wh = torch.ones_like(grid) / scale + proposal = torch.cat((grid, wh), -1).view(N_, -1, 4) + proposals.append(proposal) + _cur += H_ * W_ + # import ipdb; ipdb.set_trace() + output_proposals = torch.cat(proposals, 1) + output_proposals_valid = ((output_proposals > 0.01) & (output_proposals < 0.99)).all( + -1, keepdim=True + ) + output_proposals = torch.log(output_proposals / (1 - output_proposals)) # unsigmoid + output_proposals = output_proposals.masked_fill(memory_padding_mask.unsqueeze(-1), float("inf")) + output_proposals = output_proposals.masked_fill(~output_proposals_valid, float("inf")) + + output_memory = memory + output_memory = output_memory.masked_fill(memory_padding_mask.unsqueeze(-1), float(0)) + output_memory = output_memory.masked_fill(~output_proposals_valid, float(0)) + + # output_memory = output_memory.masked_fill(memory_padding_mask.unsqueeze(-1), float('inf')) + # output_memory = output_memory.masked_fill(~output_proposals_valid, float('inf')) + + return output_memory, output_proposals + + +class RandomBoxPerturber: + def __init__( + self, x_noise_scale=0.2, y_noise_scale=0.2, w_noise_scale=0.2, h_noise_scale=0.2 + ) -> None: + self.noise_scale = torch.Tensor( + [x_noise_scale, y_noise_scale, w_noise_scale, h_noise_scale] + ) + + def __call__(self, refanchors: Tensor) -> Tensor: + nq, bs, query_dim = refanchors.shape + device = refanchors.device + + noise_raw = torch.rand_like(refanchors) + noise_scale = self.noise_scale.to(device)[:query_dim] + + new_refanchors = refanchors * (1 + (noise_raw - 0.5) * noise_scale) + return new_refanchors.clamp_(0, 1) + + +def sigmoid_focal_loss( + inputs, targets, num_boxes, alpha: float = 0.25, gamma: float = 2, no_reduction=False +): + """ + Loss used in RetinaNet for dense detection: https://arxiv.org/abs/1708.02002. + Args: + inputs: A float tensor of arbitrary shape. + The predictions for each example. + targets: A float tensor with the same shape as inputs. Stores the binary + classification label for each element in inputs + (0 for the negative class and 1 for the positive class). + alpha: (optional) Weighting factor in range (0,1) to balance + positive vs negative examples. Default = -1 (no weighting). + gamma: Exponent of the modulating factor (1 - p_t) to + balance easy vs hard examples. + Returns: + Loss tensor + """ + prob = inputs.sigmoid() + ce_loss = F.binary_cross_entropy_with_logits(inputs, targets, reduction="none") + p_t = prob * targets + (1 - prob) * (1 - targets) + loss = ce_loss * ((1 - p_t) ** gamma) + + if alpha >= 0: + alpha_t = alpha * targets + (1 - alpha) * (1 - targets) + loss = alpha_t * loss + + if no_reduction: + return loss + + return loss.mean(1).sum() / num_boxes + + +class MLP(nn.Module): + """Very simple multi-layer perceptron (also called FFN)""" + + def __init__(self, input_dim, hidden_dim, output_dim, num_layers): + super().__init__() + self.num_layers = num_layers + h = [hidden_dim] * (num_layers - 1) + self.layers = nn.ModuleList( + nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim]) + ) + + def forward(self, x): + for i, layer in enumerate(self.layers): + x = F.relu(layer(x)) if i < self.num_layers - 1 else layer(x) + return x + + +def _get_activation_fn(activation, d_model=256, batch_dim=0): + """Return an activation function given a string""" + if activation == "relu": + return F.relu + if activation == "gelu": + return F.gelu + if activation == "glu": + return F.glu + if activation == "prelu": + return nn.PReLU() + if activation == "selu": + return F.selu + + raise RuntimeError(f"activation should be relu/gelu, not {activation}.") + + +def gen_sineembed_for_position(pos_tensor): + # n_query, bs, _ = pos_tensor.size() + # sineembed_tensor = torch.zeros(n_query, bs, 256) + scale = 2 * math.pi + dim_t = torch.arange(128, dtype=torch.float32, device=pos_tensor.device) + dim_t = 10000 ** (2 * (torch.div(dim_t, 2, rounding_mode='floor')) / 128) + x_embed = pos_tensor[:, :, 0] * scale + y_embed = pos_tensor[:, :, 1] * scale + pos_x = x_embed[:, :, None] / dim_t + pos_y = y_embed[:, :, None] / dim_t + pos_x = torch.stack((pos_x[:, :, 0::2].sin(), pos_x[:, :, 1::2].cos()), dim=3).flatten(2) + pos_y = torch.stack((pos_y[:, :, 0::2].sin(), pos_y[:, :, 1::2].cos()), dim=3).flatten(2) + if pos_tensor.size(-1) == 2: + pos = torch.cat((pos_y, pos_x), dim=2) + elif pos_tensor.size(-1) == 4: + w_embed = pos_tensor[:, :, 2] * scale + pos_w = w_embed[:, :, None] / dim_t + pos_w = torch.stack((pos_w[:, :, 0::2].sin(), pos_w[:, :, 1::2].cos()), dim=3).flatten(2) + + h_embed = pos_tensor[:, :, 3] * scale + pos_h = h_embed[:, :, None] / dim_t + pos_h = torch.stack((pos_h[:, :, 0::2].sin(), pos_h[:, :, 1::2].cos()), dim=3).flatten(2) + + pos = torch.cat((pos_y, pos_x, pos_w, pos_h), dim=2) + else: + raise ValueError("Unknown pos_tensor shape(-1):{}".format(pos_tensor.size(-1))) + return pos + + +class ContrastiveEmbed(nn.Module): + def __init__(self, max_text_len=256): + """ + Args: + max_text_len: max length of text. + """ + super().__init__() + self.max_text_len = max_text_len + + def forward(self, x, text_dict): + """_summary_ + + Args: + x (_type_): _description_ + text_dict (_type_): _description_ + { + 'encoded_text': encoded_text, # bs, 195, d_model + 'text_token_mask': text_token_mask, # bs, 195 + # True for used tokens. False for padding tokens + } + Returns: + _type_: _description_ + """ + assert isinstance(text_dict, dict) + + y = text_dict["encoded_text"] + text_token_mask = text_dict["text_token_mask"] + + res = x @ y.transpose(-1, -2) + res.masked_fill_(~text_token_mask[:, None, :], float("-inf")) + + # padding to max_text_len + new_res = torch.full((*res.shape[:-1], self.max_text_len), float("-inf"), device=res.device) + new_res[..., : res.shape[-1]] = res + + return new_res diff --git a/py/local_groundingdino/models/__init__.py b/py/local_groundingdino/models/__init__.py new file mode 100644 index 0000000..e341396 --- /dev/null +++ b/py/local_groundingdino/models/__init__.py @@ -0,0 +1,18 @@ +# ------------------------------------------------------------------------ +# Grounding DINO +# url: https://github.com/IDEA-Research/GroundingDINO +# Copyright (c) 2023 IDEA. All Rights Reserved. +# Licensed under the Apache License, Version 2.0 [see LICENSE for details] +# ------------------------------------------------------------------------ +# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved +from .GroundingDINO import build_groundingdino + + +def build_model(args): + # we use register to maintain models from catdet6 on. + from .registry import MODULE_BUILD_FUNCS + + assert args.modelname in MODULE_BUILD_FUNCS._module_dict + build_func = MODULE_BUILD_FUNCS.get(args.modelname) + model = build_func(args) + return model diff --git a/py/local_groundingdino/models/registry.py b/py/local_groundingdino/models/registry.py new file mode 100644 index 0000000..2d22a59 --- /dev/null +++ b/py/local_groundingdino/models/registry.py @@ -0,0 +1,66 @@ +# ------------------------------------------------------------------------ +# Grounding DINO +# url: https://github.com/IDEA-Research/GroundingDINO +# Copyright (c) 2023 IDEA. All Rights Reserved. +# Licensed under the Apache License, Version 2.0 [see LICENSE for details] +# ------------------------------------------------------------------------ +# -*- coding: utf-8 -*- +# @Author: Yihao Chen +# @Date: 2021-08-16 16:03:17 +# @Last Modified by: Shilong Liu +# @Last Modified time: 2022-01-23 15:26 +# modified from mmcv + +import inspect +from functools import partial + + +class Registry(object): + def __init__(self, name): + self._name = name + self._module_dict = dict() + + def __repr__(self): + format_str = self.__class__.__name__ + "(name={}, items={})".format( + self._name, list(self._module_dict.keys()) + ) + return format_str + + def __len__(self): + return len(self._module_dict) + + @property + def name(self): + return self._name + + @property + def module_dict(self): + return self._module_dict + + def get(self, key): + return self._module_dict.get(key, None) + + def registe_with_name(self, module_name=None, force=False): + return partial(self.register, module_name=module_name, force=force) + + def register(self, module_build_function, module_name=None, force=False): + """Register a module build function. + Args: + module (:obj:`nn.Module`): Module to be registered. + """ + if not inspect.isfunction(module_build_function): + raise TypeError( + "module_build_function must be a function, but got {}".format( + type(module_build_function) + ) + ) + if module_name is None: + module_name = module_build_function.__name__ + if not force and module_name in self._module_dict: + raise KeyError("{} is already registered in {}".format(module_name, self.name)) + self._module_dict[module_name] = module_build_function + + return module_build_function + + +MODULE_BUILD_FUNCS = Registry("model build functions") diff --git a/py/local_groundingdino/util/__init__.py b/py/local_groundingdino/util/__init__.py new file mode 100644 index 0000000..168f997 --- /dev/null +++ b/py/local_groundingdino/util/__init__.py @@ -0,0 +1 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved diff --git a/py/local_groundingdino/util/box_ops.py b/py/local_groundingdino/util/box_ops.py new file mode 100644 index 0000000..781068d --- /dev/null +++ b/py/local_groundingdino/util/box_ops.py @@ -0,0 +1,140 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved +""" +Utilities for bounding box manipulation and GIoU. +""" +import torch +from torchvision.ops.boxes import box_area + + +def box_cxcywh_to_xyxy(x): + x_c, y_c, w, h = x.unbind(-1) + b = [(x_c - 0.5 * w), (y_c - 0.5 * h), (x_c + 0.5 * w), (y_c + 0.5 * h)] + return torch.stack(b, dim=-1) + + +def box_xyxy_to_cxcywh(x): + x0, y0, x1, y1 = x.unbind(-1) + b = [(x0 + x1) / 2, (y0 + y1) / 2, (x1 - x0), (y1 - y0)] + return torch.stack(b, dim=-1) + + +# modified from torchvision to also return the union +def box_iou(boxes1, boxes2): + area1 = box_area(boxes1) + area2 = box_area(boxes2) + + # import ipdb; ipdb.set_trace() + lt = torch.max(boxes1[:, None, :2], boxes2[:, :2]) # [N,M,2] + rb = torch.min(boxes1[:, None, 2:], boxes2[:, 2:]) # [N,M,2] + + wh = (rb - lt).clamp(min=0) # [N,M,2] + inter = wh[:, :, 0] * wh[:, :, 1] # [N,M] + + union = area1[:, None] + area2 - inter + + iou = inter / (union + 1e-6) + return iou, union + + +def generalized_box_iou(boxes1, boxes2): + """ + Generalized IoU from https://giou.stanford.edu/ + + The boxes should be in [x0, y0, x1, y1] format + + Returns a [N, M] pairwise matrix, where N = len(boxes1) + and M = len(boxes2) + """ + # degenerate boxes gives inf / nan results + # so do an early check + assert (boxes1[:, 2:] >= boxes1[:, :2]).all() + assert (boxes2[:, 2:] >= boxes2[:, :2]).all() + # except: + # import ipdb; ipdb.set_trace() + iou, union = box_iou(boxes1, boxes2) + + lt = torch.min(boxes1[:, None, :2], boxes2[:, :2]) + rb = torch.max(boxes1[:, None, 2:], boxes2[:, 2:]) + + wh = (rb - lt).clamp(min=0) # [N,M,2] + area = wh[:, :, 0] * wh[:, :, 1] + + return iou - (area - union) / (area + 1e-6) + + +# modified from torchvision to also return the union +def box_iou_pairwise(boxes1, boxes2): + area1 = box_area(boxes1) + area2 = box_area(boxes2) + + lt = torch.max(boxes1[:, :2], boxes2[:, :2]) # [N,2] + rb = torch.min(boxes1[:, 2:], boxes2[:, 2:]) # [N,2] + + wh = (rb - lt).clamp(min=0) # [N,2] + inter = wh[:, 0] * wh[:, 1] # [N] + + union = area1 + area2 - inter + + iou = inter / union + return iou, union + + +def generalized_box_iou_pairwise(boxes1, boxes2): + """ + Generalized IoU from https://giou.stanford.edu/ + + Input: + - boxes1, boxes2: N,4 + Output: + - giou: N, 4 + """ + # degenerate boxes gives inf / nan results + # so do an early check + assert (boxes1[:, 2:] >= boxes1[:, :2]).all() + assert (boxes2[:, 2:] >= boxes2[:, :2]).all() + assert boxes1.shape == boxes2.shape + iou, union = box_iou_pairwise(boxes1, boxes2) # N, 4 + + lt = torch.min(boxes1[:, :2], boxes2[:, :2]) + rb = torch.max(boxes1[:, 2:], boxes2[:, 2:]) + + wh = (rb - lt).clamp(min=0) # [N,2] + area = wh[:, 0] * wh[:, 1] + + return iou - (area - union) / area + + +def masks_to_boxes(masks): + """Compute the bounding boxes around the provided masks + + The masks should be in format [N, H, W] where N is the number of masks, (H, W) are the spatial dimensions. + + Returns a [N, 4] tensors, with the boxes in xyxy format + """ + if masks.numel() == 0: + return torch.zeros((0, 4), device=masks.device) + + h, w = masks.shape[-2:] + + y = torch.arange(0, h, dtype=torch.float) + x = torch.arange(0, w, dtype=torch.float) + y, x = torch.meshgrid(y, x) + + x_mask = masks * x.unsqueeze(0) + x_max = x_mask.flatten(1).max(-1)[0] + x_min = x_mask.masked_fill(~(masks.bool()), 1e8).flatten(1).min(-1)[0] + + y_mask = masks * y.unsqueeze(0) + y_max = y_mask.flatten(1).max(-1)[0] + y_min = y_mask.masked_fill(~(masks.bool()), 1e8).flatten(1).min(-1)[0] + + return torch.stack([x_min, y_min, x_max, y_max], 1) + + +if __name__ == "__main__": + x = torch.rand(5, 4) + y = torch.rand(3, 4) + iou, union = box_iou(x, y) + import ipdb + + ipdb.set_trace() diff --git a/py/local_groundingdino/util/get_tokenlizer.py b/py/local_groundingdino/util/get_tokenlizer.py new file mode 100644 index 0000000..dd2d972 --- /dev/null +++ b/py/local_groundingdino/util/get_tokenlizer.py @@ -0,0 +1,29 @@ +from transformers import AutoTokenizer, BertModel, BertTokenizer, RobertaModel, RobertaTokenizerFast +import os + +def get_tokenlizer(text_encoder_type): + if not isinstance(text_encoder_type, str): + # print("text_encoder_type is not a str") + if hasattr(text_encoder_type, "text_encoder_type"): + text_encoder_type = text_encoder_type.text_encoder_type + elif text_encoder_type.get("text_encoder_type", False): + text_encoder_type = text_encoder_type.get("text_encoder_type") + elif os.path.isdir(text_encoder_type) and os.path.exists(text_encoder_type): + pass + else: + raise ValueError( + "Unknown type of text_encoder_type: {}".format(type(text_encoder_type)) + ) + print("final text_encoder_type: {}".format(text_encoder_type)) + + tokenizer = AutoTokenizer.from_pretrained(text_encoder_type) + return tokenizer + + +def get_pretrained_language_model(text_encoder_type): + if text_encoder_type == "bert-base-uncased" or (os.path.isdir(text_encoder_type) and os.path.exists(text_encoder_type)): + return BertModel.from_pretrained(text_encoder_type) + if text_encoder_type == "roberta-base": + return RobertaModel.from_pretrained(text_encoder_type) + + raise ValueError("Unknown text_encoder_type {}".format(text_encoder_type)) diff --git a/py/local_groundingdino/util/inference.py b/py/local_groundingdino/util/inference.py new file mode 100644 index 0000000..5a36833 --- /dev/null +++ b/py/local_groundingdino/util/inference.py @@ -0,0 +1,244 @@ +from typing import Tuple, List + +import cv2 +import numpy as np +import supervision as sv +import torch +from PIL import Image +from torchvision.ops import box_convert + +import local_groundingdino.datasets.transforms as T +from local_groundingdino.models import build_model +from local_groundingdino.util.misc import clean_state_dict +from local_groundingdino.util.slconfig import SLConfig +from local_groundingdino.util.utils import get_phrases_from_posmap + +# ---------------------------------------------------------------------------------------------------------------------- +# OLD API +# ---------------------------------------------------------------------------------------------------------------------- + + +def preprocess_caption(caption: str) -> str: + result = caption.lower().strip() + if result.endswith("."): + return result + return result + "." + + +def load_model(model_config_path: str, model_checkpoint_path: str, device: str = "cuda"): + args = SLConfig.fromfile(model_config_path) + args.device = device + model = build_model(args) + checkpoint = torch.load(model_checkpoint_path, map_location="cpu") + model.load_state_dict(clean_state_dict(checkpoint["model"]), strict=False) + model.eval() + return model + + +def load_image(image_path: str) -> Tuple[np.array, torch.Tensor]: + transform = T.Compose( + [ + T.RandomResize([800], max_size=1333), + T.ToTensor(), + T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]), + ] + ) + image_source = Image.open(image_path).convert("RGB") + image = np.asarray(image_source) + image_transformed, _ = transform(image_source, None) + return image, image_transformed + + +def predict( + model, + image: torch.Tensor, + caption: str, + box_threshold: float, + text_threshold: float, + device: str = "cuda" +) -> Tuple[torch.Tensor, torch.Tensor, List[str]]: + caption = preprocess_caption(caption=caption) + + model = model.to(device) + image = image.to(device) + + with torch.no_grad(): + outputs = model(image[None], captions=[caption]) + + prediction_logits = outputs["pred_logits"].cpu().sigmoid()[0] # prediction_logits.shape = (nq, 256) + prediction_boxes = outputs["pred_boxes"].cpu()[0] # prediction_boxes.shape = (nq, 4) + + mask = prediction_logits.max(dim=1)[0] > box_threshold + logits = prediction_logits[mask] # logits.shape = (n, 256) + boxes = prediction_boxes[mask] # boxes.shape = (n, 4) + + tokenizer = model.tokenizer + tokenized = tokenizer(caption) + + phrases = [ + get_phrases_from_posmap(logit > text_threshold, tokenized, tokenizer).replace('.', '') + for logit + in logits + ] + + return boxes, logits.max(dim=1)[0], phrases + + +def annotate(image_source: np.ndarray, boxes: torch.Tensor, logits: torch.Tensor, phrases: List[str]) -> np.ndarray: + h, w, _ = image_source.shape + boxes = boxes * torch.Tensor([w, h, w, h]) + xyxy = box_convert(boxes=boxes, in_fmt="cxcywh", out_fmt="xyxy").numpy() + detections = sv.Detections(xyxy=xyxy) + + labels = [ + f"{phrase} {logit:.2f}" + for phrase, logit + in zip(phrases, logits) + ] + + box_annotator = sv.BoxAnnotator() + annotated_frame = cv2.cvtColor(image_source, cv2.COLOR_RGB2BGR) + annotated_frame = box_annotator.annotate(scene=annotated_frame, detections=detections, labels=labels) + return annotated_frame + + +# ---------------------------------------------------------------------------------------------------------------------- +# NEW API +# ---------------------------------------------------------------------------------------------------------------------- + + +class Model: + + def __init__( + self, + model_config_path: str, + model_checkpoint_path: str, + device: str = "cuda" + ): + self.model = load_model( + model_config_path=model_config_path, + model_checkpoint_path=model_checkpoint_path, + device=device + ).to(device) + self.device = device + + def predict_with_caption( + self, + image: np.ndarray, + caption: str, + box_threshold: float = 0.35, + text_threshold: float = 0.25 + ) -> Tuple[sv.Detections, List[str]]: + """ + import cv2 + + image = cv2.imread(IMAGE_PATH) + + model = Model(model_config_path=CONFIG_PATH, model_checkpoint_path=WEIGHTS_PATH) + detections, labels = model.predict_with_caption( + image=image, + caption=caption, + box_threshold=BOX_THRESHOLD, + text_threshold=TEXT_THRESHOLD + ) + + import supervision as sv + + box_annotator = sv.BoxAnnotator() + annotated_image = box_annotator.annotate(scene=image, detections=detections, labels=labels) + """ + processed_image = Model.preprocess_image(image_bgr=image).to(self.device) + boxes, logits, phrases = predict( + model=self.model, + image=processed_image, + caption=caption, + box_threshold=box_threshold, + text_threshold=text_threshold, + device=self.device) + source_h, source_w, _ = image.shape + detections = Model.post_process_result( + source_h=source_h, + source_w=source_w, + boxes=boxes, + logits=logits) + return detections, phrases + + def predict_with_classes( + self, + image: np.ndarray, + classes: List[str], + box_threshold: float, + text_threshold: float + ) -> sv.Detections: + """ + import cv2 + + image = cv2.imread(IMAGE_PATH) + + model = Model(model_config_path=CONFIG_PATH, model_checkpoint_path=WEIGHTS_PATH) + detections = model.predict_with_classes( + image=image, + classes=CLASSES, + box_threshold=BOX_THRESHOLD, + text_threshold=TEXT_THRESHOLD + ) + + + import supervision as sv + + box_annotator = sv.BoxAnnotator() + annotated_image = box_annotator.annotate(scene=image, detections=detections) + """ + caption = ". ".join(classes) + processed_image = Model.preprocess_image(image_bgr=image).to(self.device) + boxes, logits, phrases = predict( + model=self.model, + image=processed_image, + caption=caption, + box_threshold=box_threshold, + text_threshold=text_threshold, + device=self.device) + source_h, source_w, _ = image.shape + detections = Model.post_process_result( + source_h=source_h, + source_w=source_w, + boxes=boxes, + logits=logits) + class_id = Model.phrases2classes(phrases=phrases, classes=classes) + detections.class_id = class_id + return detections + + @staticmethod + def preprocess_image(image_bgr: np.ndarray) -> torch.Tensor: + transform = T.Compose( + [ + T.RandomResize([800], max_size=1333), + T.ToTensor(), + T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]), + ] + ) + image_pillow = Image.fromarray(cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)) + image_transformed, _ = transform(image_pillow, None) + return image_transformed + + @staticmethod + def post_process_result( + source_h: int, + source_w: int, + boxes: torch.Tensor, + logits: torch.Tensor + ) -> sv.Detections: + boxes = boxes * torch.Tensor([source_w, source_h, source_w, source_h]) + xyxy = box_convert(boxes=boxes, in_fmt="cxcywh", out_fmt="xyxy").numpy() + confidence = logits.numpy() + return sv.Detections(xyxy=xyxy, confidence=confidence) + + @staticmethod + def phrases2classes(phrases: List[str], classes: List[str]) -> np.ndarray: + class_ids = [] + for phrase in phrases: + try: + class_ids.append(classes.index(phrase)) + except ValueError: + class_ids.append(None) + return np.array(class_ids) diff --git a/py/local_groundingdino/util/misc.py b/py/local_groundingdino/util/misc.py new file mode 100644 index 0000000..d64b84e --- /dev/null +++ b/py/local_groundingdino/util/misc.py @@ -0,0 +1,717 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved +""" +Misc functions, including distributed helpers. + +Mostly copy-paste from torchvision references. +""" +import colorsys +import datetime +import functools +import io +import json +import os +import pickle +import subprocess +import time +from collections import OrderedDict, defaultdict, deque +from typing import List, Optional + +import numpy as np +import torch +import torch.distributed as dist + +# needed due to empty tensor bug in pytorch and torchvision 0.5 +import torchvision +from torch import Tensor + +__torchvision_need_compat_flag = float(torchvision.__version__.split(".")[1]) < 7 +if __torchvision_need_compat_flag: + from torchvision.ops import _new_empty_tensor + from torchvision.ops.misc import _output_size + + +class SmoothedValue(object): + """Track a series of values and provide access to smoothed values over a + window or the global series average. + """ + + def __init__(self, window_size=20, fmt=None): + if fmt is None: + fmt = "{median:.4f} ({global_avg:.4f})" + self.deque = deque(maxlen=window_size) + self.total = 0.0 + self.count = 0 + self.fmt = fmt + + def update(self, value, n=1): + self.deque.append(value) + self.count += n + self.total += value * n + + def synchronize_between_processes(self): + """ + Warning: does not synchronize the deque! + """ + if not is_dist_avail_and_initialized(): + return + t = torch.tensor([self.count, self.total], dtype=torch.float64, device="cuda") + dist.barrier() + dist.all_reduce(t) + t = t.tolist() + self.count = int(t[0]) + self.total = t[1] + + @property + def median(self): + d = torch.tensor(list(self.deque)) + if d.shape[0] == 0: + return 0 + return d.median().item() + + @property + def avg(self): + d = torch.tensor(list(self.deque), dtype=torch.float32) + return d.mean().item() + + @property + def global_avg(self): + if os.environ.get("SHILONG_AMP", None) == "1": + eps = 1e-4 + else: + eps = 1e-6 + return self.total / (self.count + eps) + + @property + def max(self): + return max(self.deque) + + @property + def value(self): + return self.deque[-1] + + def __str__(self): + return self.fmt.format( + median=self.median, + avg=self.avg, + global_avg=self.global_avg, + max=self.max, + value=self.value, + ) + + +@functools.lru_cache() +def _get_global_gloo_group(): + """ + Return a process group based on gloo backend, containing all the ranks + The result is cached. + """ + + if dist.get_backend() == "nccl": + return dist.new_group(backend="gloo") + + return dist.group.WORLD + + +def all_gather_cpu(data): + """ + Run all_gather on arbitrary picklable data (not necessarily tensors) + Args: + data: any picklable object + Returns: + list[data]: list of data gathered from each rank + """ + + world_size = get_world_size() + if world_size == 1: + return [data] + + cpu_group = _get_global_gloo_group() + + buffer = io.BytesIO() + torch.save(data, buffer) + data_view = buffer.getbuffer() + device = "cuda" if cpu_group is None else "cpu" + tensor = torch.ByteTensor(data_view).to(device) + + # obtain Tensor size of each rank + local_size = torch.tensor([tensor.numel()], device=device, dtype=torch.long) + size_list = [torch.tensor([0], device=device, dtype=torch.long) for _ in range(world_size)] + if cpu_group is None: + dist.all_gather(size_list, local_size) + else: + print("gathering on cpu") + dist.all_gather(size_list, local_size, group=cpu_group) + size_list = [int(size.item()) for size in size_list] + max_size = max(size_list) + assert isinstance(local_size.item(), int) + local_size = int(local_size.item()) + + # receiving Tensor from all ranks + # we pad the tensor because torch all_gather does not support + # gathering tensors of different shapes + tensor_list = [] + for _ in size_list: + tensor_list.append(torch.empty((max_size,), dtype=torch.uint8, device=device)) + if local_size != max_size: + padding = torch.empty(size=(max_size - local_size,), dtype=torch.uint8, device=device) + tensor = torch.cat((tensor, padding), dim=0) + if cpu_group is None: + dist.all_gather(tensor_list, tensor) + else: + dist.all_gather(tensor_list, tensor, group=cpu_group) + + data_list = [] + for size, tensor in zip(size_list, tensor_list): + tensor = torch.split(tensor, [size, max_size - size], dim=0)[0] + buffer = io.BytesIO(tensor.cpu().numpy()) + obj = torch.load(buffer) + data_list.append(obj) + + return data_list + + +def all_gather(data): + """ + Run all_gather on arbitrary picklable data (not necessarily tensors) + Args: + data: any picklable object + Returns: + list[data]: list of data gathered from each rank + """ + + if os.getenv("CPU_REDUCE") == "1": + return all_gather_cpu(data) + + world_size = get_world_size() + if world_size == 1: + return [data] + + # serialized to a Tensor + buffer = pickle.dumps(data) + storage = torch.ByteStorage.from_buffer(buffer) + tensor = torch.ByteTensor(storage).to("cuda") + + # obtain Tensor size of each rank + local_size = torch.tensor([tensor.numel()], device="cuda") + size_list = [torch.tensor([0], device="cuda") for _ in range(world_size)] + dist.all_gather(size_list, local_size) + size_list = [int(size.item()) for size in size_list] + max_size = max(size_list) + + # receiving Tensor from all ranks + # we pad the tensor because torch all_gather does not support + # gathering tensors of different shapes + tensor_list = [] + for _ in size_list: + tensor_list.append(torch.empty((max_size,), dtype=torch.uint8, device="cuda")) + if local_size != max_size: + padding = torch.empty(size=(max_size - local_size,), dtype=torch.uint8, device="cuda") + tensor = torch.cat((tensor, padding), dim=0) + dist.all_gather(tensor_list, tensor) + + data_list = [] + for size, tensor in zip(size_list, tensor_list): + buffer = tensor.cpu().numpy().tobytes()[:size] + data_list.append(pickle.loads(buffer)) + + return data_list + + +def reduce_dict(input_dict, average=True): + """ + Args: + input_dict (dict): all the values will be reduced + average (bool): whether to do average or sum + Reduce the values in the dictionary from all processes so that all processes + have the averaged results. Returns a dict with the same fields as + input_dict, after reduction. + """ + world_size = get_world_size() + if world_size < 2: + return input_dict + with torch.no_grad(): + names = [] + values = [] + # sort the keys so that they are consistent across processes + for k in sorted(input_dict.keys()): + names.append(k) + values.append(input_dict[k]) + values = torch.stack(values, dim=0) + dist.all_reduce(values) + if average: + values /= world_size + reduced_dict = {k: v for k, v in zip(names, values)} + return reduced_dict + + +class MetricLogger(object): + def __init__(self, delimiter="\t"): + self.meters = defaultdict(SmoothedValue) + self.delimiter = delimiter + + def update(self, **kwargs): + for k, v in kwargs.items(): + if isinstance(v, torch.Tensor): + v = v.item() + assert isinstance(v, (float, int)) + self.meters[k].update(v) + + def __getattr__(self, attr): + if attr in self.meters: + return self.meters[attr] + if attr in self.__dict__: + return self.__dict__[attr] + raise AttributeError("'{}' object has no attribute '{}'".format(type(self).__name__, attr)) + + def __str__(self): + loss_str = [] + for name, meter in self.meters.items(): + # print(name, str(meter)) + # import ipdb;ipdb.set_trace() + if meter.count > 0: + loss_str.append("{}: {}".format(name, str(meter))) + return self.delimiter.join(loss_str) + + def synchronize_between_processes(self): + for meter in self.meters.values(): + meter.synchronize_between_processes() + + def add_meter(self, name, meter): + self.meters[name] = meter + + def log_every(self, iterable, print_freq, header=None, logger=None): + if logger is None: + print_func = print + else: + print_func = logger.info + + i = 0 + if not header: + header = "" + start_time = time.time() + end = time.time() + iter_time = SmoothedValue(fmt="{avg:.4f}") + data_time = SmoothedValue(fmt="{avg:.4f}") + space_fmt = ":" + str(len(str(len(iterable)))) + "d" + if torch.cuda.is_available(): + log_msg = self.delimiter.join( + [ + header, + "[{0" + space_fmt + "}/{1}]", + "eta: {eta}", + "{meters}", + "time: {time}", + "data: {data}", + "max mem: {memory:.0f}", + ] + ) + else: + log_msg = self.delimiter.join( + [ + header, + "[{0" + space_fmt + "}/{1}]", + "eta: {eta}", + "{meters}", + "time: {time}", + "data: {data}", + ] + ) + MB = 1024.0 * 1024.0 + for obj in iterable: + data_time.update(time.time() - end) + yield obj + # import ipdb; ipdb.set_trace() + iter_time.update(time.time() - end) + if i % print_freq == 0 or i == len(iterable) - 1: + eta_seconds = iter_time.global_avg * (len(iterable) - i) + eta_string = str(datetime.timedelta(seconds=int(eta_seconds))) + if torch.cuda.is_available(): + print_func( + log_msg.format( + i, + len(iterable), + eta=eta_string, + meters=str(self), + time=str(iter_time), + data=str(data_time), + memory=torch.cuda.max_memory_allocated() / MB, + ) + ) + else: + print_func( + log_msg.format( + i, + len(iterable), + eta=eta_string, + meters=str(self), + time=str(iter_time), + data=str(data_time), + ) + ) + i += 1 + end = time.time() + total_time = time.time() - start_time + total_time_str = str(datetime.timedelta(seconds=int(total_time))) + print_func( + "{} Total time: {} ({:.4f} s / it)".format( + header, total_time_str, total_time / len(iterable) + ) + ) + + +def get_sha(): + cwd = os.path.dirname(os.path.abspath(__file__)) + + def _run(command): + return subprocess.check_output(command, cwd=cwd).decode("ascii").strip() + + sha = "N/A" + diff = "clean" + branch = "N/A" + try: + sha = _run(["git", "rev-parse", "HEAD"]) + subprocess.check_output(["git", "diff"], cwd=cwd) + diff = _run(["git", "diff-index", "HEAD"]) + diff = "has uncommited changes" if diff else "clean" + branch = _run(["git", "rev-parse", "--abbrev-ref", "HEAD"]) + except Exception: + pass + message = f"sha: {sha}, status: {diff}, branch: {branch}" + return message + + +def collate_fn(batch): + # import ipdb; ipdb.set_trace() + batch = list(zip(*batch)) + batch[0] = nested_tensor_from_tensor_list(batch[0]) + return tuple(batch) + + +def _max_by_axis(the_list): + # type: (List[List[int]]) -> List[int] + maxes = the_list[0] + for sublist in the_list[1:]: + for index, item in enumerate(sublist): + maxes[index] = max(maxes[index], item) + return maxes + + +class NestedTensor(object): + def __init__(self, tensors, mask: Optional[Tensor]): + self.tensors = tensors + self.mask = mask + if mask == "auto": + self.mask = torch.zeros_like(tensors).to(tensors.device) + if self.mask.dim() == 3: + self.mask = self.mask.sum(0).to(bool) + elif self.mask.dim() == 4: + self.mask = self.mask.sum(1).to(bool) + else: + raise ValueError( + "tensors dim must be 3 or 4 but {}({})".format( + self.tensors.dim(), self.tensors.shape + ) + ) + + def imgsize(self): + res = [] + for i in range(self.tensors.shape[0]): + mask = self.mask[i] + maxH = (~mask).sum(0).max() + maxW = (~mask).sum(1).max() + res.append(torch.Tensor([maxH, maxW])) + return res + + def to(self, device): + # type: (Device) -> NestedTensor # noqa + cast_tensor = self.tensors.to(device) + mask = self.mask + if mask is not None: + assert mask is not None + cast_mask = mask.to(device) + else: + cast_mask = None + return NestedTensor(cast_tensor, cast_mask) + + def to_img_list_single(self, tensor, mask): + assert tensor.dim() == 3, "dim of tensor should be 3 but {}".format(tensor.dim()) + maxH = (~mask).sum(0).max() + maxW = (~mask).sum(1).max() + img = tensor[:, :maxH, :maxW] + return img + + def to_img_list(self): + """remove the padding and convert to img list + + Returns: + [type]: [description] + """ + if self.tensors.dim() == 3: + return self.to_img_list_single(self.tensors, self.mask) + else: + res = [] + for i in range(self.tensors.shape[0]): + tensor_i = self.tensors[i] + mask_i = self.mask[i] + res.append(self.to_img_list_single(tensor_i, mask_i)) + return res + + @property + def device(self): + return self.tensors.device + + def decompose(self): + return self.tensors, self.mask + + def __repr__(self): + return str(self.tensors) + + @property + def shape(self): + return {"tensors.shape": self.tensors.shape, "mask.shape": self.mask.shape} + + +def nested_tensor_from_tensor_list(tensor_list: List[Tensor]): + # TODO make this more general + if tensor_list[0].ndim == 3: + if torchvision._is_tracing(): + # nested_tensor_from_tensor_list() does not export well to ONNX + # call _onnx_nested_tensor_from_tensor_list() instead + return _onnx_nested_tensor_from_tensor_list(tensor_list) + + # TODO make it support different-sized images + max_size = _max_by_axis([list(img.shape) for img in tensor_list]) + # min_size = tuple(min(s) for s in zip(*[img.shape for img in tensor_list])) + batch_shape = [len(tensor_list)] + max_size + b, c, h, w = batch_shape + dtype = tensor_list[0].dtype + device = tensor_list[0].device + tensor = torch.zeros(batch_shape, dtype=dtype, device=device) + mask = torch.ones((b, h, w), dtype=torch.bool, device=device) + for img, pad_img, m in zip(tensor_list, tensor, mask): + pad_img[: img.shape[0], : img.shape[1], : img.shape[2]].copy_(img) + m[: img.shape[1], : img.shape[2]] = False + else: + raise ValueError("not supported") + return NestedTensor(tensor, mask) + + +# _onnx_nested_tensor_from_tensor_list() is an implementation of +# nested_tensor_from_tensor_list() that is supported by ONNX tracing. +@torch.jit.unused +def _onnx_nested_tensor_from_tensor_list(tensor_list: List[Tensor]) -> NestedTensor: + max_size = [] + for i in range(tensor_list[0].dim()): + max_size_i = torch.max( + torch.stack([img.shape[i] for img in tensor_list]).to(torch.float32) + ).to(torch.int64) + max_size.append(max_size_i) + max_size = tuple(max_size) + + # work around for + # pad_img[: img.shape[0], : img.shape[1], : img.shape[2]].copy_(img) + # m[: img.shape[1], :img.shape[2]] = False + # which is not yet supported in onnx + padded_imgs = [] + padded_masks = [] + for img in tensor_list: + padding = [(s1 - s2) for s1, s2 in zip(max_size, tuple(img.shape))] + padded_img = torch.nn.functional.pad(img, (0, padding[2], 0, padding[1], 0, padding[0])) + padded_imgs.append(padded_img) + + m = torch.zeros_like(img[0], dtype=torch.int, device=img.device) + padded_mask = torch.nn.functional.pad(m, (0, padding[2], 0, padding[1]), "constant", 1) + padded_masks.append(padded_mask.to(torch.bool)) + + tensor = torch.stack(padded_imgs) + mask = torch.stack(padded_masks) + + return NestedTensor(tensor, mask=mask) + + +def setup_for_distributed(is_master): + """ + This function disables printing when not in master process + """ + import builtins as __builtin__ + + builtin_print = __builtin__.print + + def print(*args, **kwargs): + force = kwargs.pop("force", False) + if is_master or force: + builtin_print(*args, **kwargs) + + __builtin__.print = print + + +def is_dist_avail_and_initialized(): + if not dist.is_available(): + return False + if not dist.is_initialized(): + return False + return True + + +def get_world_size(): + if not is_dist_avail_and_initialized(): + return 1 + return dist.get_world_size() + + +def get_rank(): + if not is_dist_avail_and_initialized(): + return 0 + return dist.get_rank() + + +def is_main_process(): + return get_rank() == 0 + + +def save_on_master(*args, **kwargs): + if is_main_process(): + torch.save(*args, **kwargs) + + +def init_distributed_mode(args): + if "WORLD_SIZE" in os.environ and os.environ["WORLD_SIZE"] != "": # 'RANK' in os.environ and + args.rank = int(os.environ["RANK"]) + args.world_size = int(os.environ["WORLD_SIZE"]) + args.gpu = args.local_rank = int(os.environ["LOCAL_RANK"]) + + # launch by torch.distributed.launch + # Single node + # python -m torch.distributed.launch --nproc_per_node=8 main.py --world-size 1 --rank 0 ... + # Multi nodes + # python -m torch.distributed.launch --nproc_per_node=8 main.py --world-size 2 --rank 0 --dist-url 'tcp://IP_OF_NODE0:FREEPORT' ... + # python -m torch.distributed.launch --nproc_per_node=8 main.py --world-size 2 --rank 1 --dist-url 'tcp://IP_OF_NODE0:FREEPORT' ... + # args.rank = int(os.environ.get('OMPI_COMM_WORLD_RANK')) + # local_world_size = int(os.environ['GPU_PER_NODE_COUNT']) + # args.world_size = args.world_size * local_world_size + # args.gpu = args.local_rank = int(os.environ['LOCAL_RANK']) + # args.rank = args.rank * local_world_size + args.local_rank + print( + "world size: {}, rank: {}, local rank: {}".format( + args.world_size, args.rank, args.local_rank + ) + ) + print(json.dumps(dict(os.environ), indent=2)) + elif "SLURM_PROCID" in os.environ: + args.rank = int(os.environ["SLURM_PROCID"]) + args.gpu = args.local_rank = int(os.environ["SLURM_LOCALID"]) + args.world_size = int(os.environ["SLURM_NPROCS"]) + + print( + "world size: {}, world rank: {}, local rank: {}, device_count: {}".format( + args.world_size, args.rank, args.local_rank, torch.cuda.device_count() + ) + ) + else: + print("Not using distributed mode") + args.distributed = False + args.world_size = 1 + args.rank = 0 + args.local_rank = 0 + return + + print("world_size:{} rank:{} local_rank:{}".format(args.world_size, args.rank, args.local_rank)) + args.distributed = True + torch.cuda.set_device(args.local_rank) + args.dist_backend = "nccl" + print("| distributed init (rank {}): {}".format(args.rank, args.dist_url), flush=True) + + torch.distributed.init_process_group( + backend=args.dist_backend, + world_size=args.world_size, + rank=args.rank, + init_method=args.dist_url, + ) + + print("Before torch.distributed.barrier()") + torch.distributed.barrier() + print("End torch.distributed.barrier()") + setup_for_distributed(args.rank == 0) + + +@torch.no_grad() +def accuracy(output, target, topk=(1,)): + """Computes the precision@k for the specified values of k""" + if target.numel() == 0: + return [torch.zeros([], device=output.device)] + maxk = max(topk) + batch_size = target.size(0) + + _, pred = output.topk(maxk, 1, True, True) + pred = pred.t() + correct = pred.eq(target.view(1, -1).expand_as(pred)) + + res = [] + for k in topk: + correct_k = correct[:k].view(-1).float().sum(0) + res.append(correct_k.mul_(100.0 / batch_size)) + return res + + +@torch.no_grad() +def accuracy_onehot(pred, gt): + """_summary_ + + Args: + pred (_type_): n, c + gt (_type_): n, c + """ + tp = ((pred - gt).abs().sum(-1) < 1e-4).float().sum() + acc = tp / gt.shape[0] * 100 + return acc + + +def interpolate(input, size=None, scale_factor=None, mode="nearest", align_corners=None): + # type: (Tensor, Optional[List[int]], Optional[float], str, Optional[bool]) -> Tensor + """ + Equivalent to nn.functional.interpolate, but with support for empty batch sizes. + This will eventually be supported natively by PyTorch, and this + class can go away. + """ + if __torchvision_need_compat_flag < 0.7: + if input.numel() > 0: + return torch.nn.functional.interpolate(input, size, scale_factor, mode, align_corners) + + output_shape = _output_size(2, input, size, scale_factor) + output_shape = list(input.shape[:-2]) + list(output_shape) + return _new_empty_tensor(input, output_shape) + else: + return torchvision.ops.misc.interpolate(input, size, scale_factor, mode, align_corners) + + +class color_sys: + def __init__(self, num_colors) -> None: + self.num_colors = num_colors + colors = [] + for i in np.arange(0.0, 360.0, 360.0 / num_colors): + hue = i / 360.0 + lightness = (50 + np.random.rand() * 10) / 100.0 + saturation = (90 + np.random.rand() * 10) / 100.0 + colors.append( + tuple([int(j * 255) for j in colorsys.hls_to_rgb(hue, lightness, saturation)]) + ) + self.colors = colors + + def __call__(self, idx): + return self.colors[idx] + + +def inverse_sigmoid(x, eps=1e-3): + x = x.clamp(min=0, max=1) + x1 = x.clamp(min=eps) + x2 = (1 - x).clamp(min=eps) + return torch.log(x1 / x2) + + +def clean_state_dict(state_dict): + new_state_dict = OrderedDict() + for k, v in state_dict.items(): + if k[:7] == "module.": + k = k[7:] # remove `module.` + new_state_dict[k] = v + return new_state_dict diff --git a/py/local_groundingdino/util/slconfig.py b/py/local_groundingdino/util/slconfig.py new file mode 100644 index 0000000..672e72e --- /dev/null +++ b/py/local_groundingdino/util/slconfig.py @@ -0,0 +1,427 @@ +# ========================================================== +# Modified from mmcv +# ========================================================== +import ast +import os +import os.path as osp +import shutil +import sys +import tempfile +from argparse import Action +from importlib import import_module + +from addict import Dict +from yapf.yapflib.yapf_api import FormatCode + +BASE_KEY = "_base_" +DELETE_KEY = "_delete_" +RESERVED_KEYS = ["filename", "text", "pretty_text", "get", "dump", "merge_from_dict"] + + +def check_file_exist(filename, msg_tmpl='file "{}" does not exist'): + if not osp.isfile(filename): + raise FileNotFoundError(msg_tmpl.format(filename)) + + +class ConfigDict(Dict): + def __missing__(self, name): + raise KeyError(name) + + def __getattr__(self, name): + try: + value = super(ConfigDict, self).__getattr__(name) + except KeyError: + ex = AttributeError(f"'{self.__class__.__name__}' object has no " f"attribute '{name}'") + except Exception as e: + ex = e + else: + return value + raise ex + + +class SLConfig(object): + """ + config files. + only support .py file as config now. + + ref: mmcv.utils.config + + Example: + >>> cfg = Config(dict(a=1, b=dict(b1=[0, 1]))) + >>> cfg.a + 1 + >>> cfg.b + {'b1': [0, 1]} + >>> cfg.b.b1 + [0, 1] + >>> cfg = Config.fromfile('tests/data/config/a.py') + >>> cfg.filename + "/home/kchen/projects/mmcv/tests/data/config/a.py" + >>> cfg.item4 + 'test' + >>> cfg + "Config [path: /home/kchen/projects/mmcv/tests/data/config/a.py]: " + "{'item1': [1, 2], 'item2': {'a': 0}, 'item3': True, 'item4': 'test'}" + """ + + @staticmethod + def _validate_py_syntax(filename): + with open(filename) as f: + content = f.read() + try: + ast.parse(content) + except SyntaxError: + raise SyntaxError("There are syntax errors in config " f"file {filename}") + + @staticmethod + def _file2dict(filename): + filename = osp.abspath(osp.expanduser(filename)) + check_file_exist(filename) + if filename.lower().endswith(".py"): + with tempfile.TemporaryDirectory() as temp_config_dir: + temp_config_file = tempfile.NamedTemporaryFile(dir=temp_config_dir, suffix=".py") + temp_config_name = osp.basename(temp_config_file.name) + if os.name == 'nt': + temp_config_file.close() + shutil.copyfile(filename, osp.join(temp_config_dir, temp_config_name)) + temp_module_name = osp.splitext(temp_config_name)[0] + sys.path.insert(0, temp_config_dir) + SLConfig._validate_py_syntax(filename) + mod = import_module(temp_module_name) + sys.path.pop(0) + cfg_dict = { + name: value for name, value in mod.__dict__.items() if not name.startswith("__") + } + # delete imported module + del sys.modules[temp_module_name] + # close temp file + temp_config_file.close() + elif filename.lower().endswith((".yml", ".yaml", ".json")): + from .slio import slload + + cfg_dict = slload(filename) + else: + raise IOError("Only py/yml/yaml/json type are supported now!") + + cfg_text = filename + "\n" + with open(filename, "r") as f: + cfg_text += f.read() + + # parse the base file + if BASE_KEY in cfg_dict: + cfg_dir = osp.dirname(filename) + base_filename = cfg_dict.pop(BASE_KEY) + base_filename = base_filename if isinstance(base_filename, list) else [base_filename] + + cfg_dict_list = list() + cfg_text_list = list() + for f in base_filename: + _cfg_dict, _cfg_text = SLConfig._file2dict(osp.join(cfg_dir, f)) + cfg_dict_list.append(_cfg_dict) + cfg_text_list.append(_cfg_text) + + base_cfg_dict = dict() + for c in cfg_dict_list: + if len(base_cfg_dict.keys() & c.keys()) > 0: + raise KeyError("Duplicate key is not allowed among bases") + # TODO Allow the duplicate key while warnning user + base_cfg_dict.update(c) + + base_cfg_dict = SLConfig._merge_a_into_b(cfg_dict, base_cfg_dict) + cfg_dict = base_cfg_dict + + # merge cfg_text + cfg_text_list.append(cfg_text) + cfg_text = "\n".join(cfg_text_list) + + return cfg_dict, cfg_text + + @staticmethod + def _merge_a_into_b(a, b): + """merge dict `a` into dict `b` (non-inplace). + values in `a` will overwrite `b`. + copy first to avoid inplace modification + + Args: + a ([type]): [description] + b ([type]): [description] + + Returns: + [dict]: [description] + """ + # import ipdb; ipdb.set_trace() + if not isinstance(a, dict): + return a + + b = b.copy() + for k, v in a.items(): + if isinstance(v, dict) and k in b and not v.pop(DELETE_KEY, False): + + if not isinstance(b[k], dict) and not isinstance(b[k], list): + # if : + # import ipdb; ipdb.set_trace() + raise TypeError( + f"{k}={v} in child config cannot inherit from base " + f"because {k} is a dict in the child config but is of " + f"type {type(b[k])} in base config. You may set " + f"`{DELETE_KEY}=True` to ignore the base config" + ) + b[k] = SLConfig._merge_a_into_b(v, b[k]) + elif isinstance(b, list): + try: + _ = int(k) + except: + raise TypeError( + f"b is a list, " f"index {k} should be an int when input but {type(k)}" + ) + b[int(k)] = SLConfig._merge_a_into_b(v, b[int(k)]) + else: + b[k] = v + + return b + + @staticmethod + def fromfile(filename): + cfg_dict, cfg_text = SLConfig._file2dict(filename) + return SLConfig(cfg_dict, cfg_text=cfg_text, filename=filename) + + def __init__(self, cfg_dict=None, cfg_text=None, filename=None): + if cfg_dict is None: + cfg_dict = dict() + elif not isinstance(cfg_dict, dict): + raise TypeError("cfg_dict must be a dict, but " f"got {type(cfg_dict)}") + for key in cfg_dict: + if key in RESERVED_KEYS: + raise KeyError(f"{key} is reserved for config file") + + super(SLConfig, self).__setattr__("_cfg_dict", ConfigDict(cfg_dict)) + super(SLConfig, self).__setattr__("_filename", filename) + if cfg_text: + text = cfg_text + elif filename: + with open(filename, "r") as f: + text = f.read() + else: + text = "" + super(SLConfig, self).__setattr__("_text", text) + + @property + def filename(self): + return self._filename + + @property + def text(self): + return self._text + + @property + def pretty_text(self): + + indent = 4 + + def _indent(s_, num_spaces): + s = s_.split("\n") + if len(s) == 1: + return s_ + first = s.pop(0) + s = [(num_spaces * " ") + line for line in s] + s = "\n".join(s) + s = first + "\n" + s + return s + + def _format_basic_types(k, v, use_mapping=False): + if isinstance(v, str): + v_str = f"'{v}'" + else: + v_str = str(v) + + if use_mapping: + k_str = f"'{k}'" if isinstance(k, str) else str(k) + attr_str = f"{k_str}: {v_str}" + else: + attr_str = f"{str(k)}={v_str}" + attr_str = _indent(attr_str, indent) + + return attr_str + + def _format_list(k, v, use_mapping=False): + # check if all items in the list are dict + if all(isinstance(_, dict) for _ in v): + v_str = "[\n" + v_str += "\n".join( + f"dict({_indent(_format_dict(v_), indent)})," for v_ in v + ).rstrip(",") + if use_mapping: + k_str = f"'{k}'" if isinstance(k, str) else str(k) + attr_str = f"{k_str}: {v_str}" + else: + attr_str = f"{str(k)}={v_str}" + attr_str = _indent(attr_str, indent) + "]" + else: + attr_str = _format_basic_types(k, v, use_mapping) + return attr_str + + def _contain_invalid_identifier(dict_str): + contain_invalid_identifier = False + for key_name in dict_str: + contain_invalid_identifier |= not str(key_name).isidentifier() + return contain_invalid_identifier + + def _format_dict(input_dict, outest_level=False): + r = "" + s = [] + + use_mapping = _contain_invalid_identifier(input_dict) + if use_mapping: + r += "{" + for idx, (k, v) in enumerate(input_dict.items()): + is_last = idx >= len(input_dict) - 1 + end = "" if outest_level or is_last else "," + if isinstance(v, dict): + v_str = "\n" + _format_dict(v) + if use_mapping: + k_str = f"'{k}'" if isinstance(k, str) else str(k) + attr_str = f"{k_str}: dict({v_str}" + else: + attr_str = f"{str(k)}=dict({v_str}" + attr_str = _indent(attr_str, indent) + ")" + end + elif isinstance(v, list): + attr_str = _format_list(k, v, use_mapping) + end + else: + attr_str = _format_basic_types(k, v, use_mapping) + end + + s.append(attr_str) + r += "\n".join(s) + if use_mapping: + r += "}" + return r + + cfg_dict = self._cfg_dict.to_dict() + text = _format_dict(cfg_dict, outest_level=True) + # copied from setup.cfg + yapf_style = dict( + based_on_style="pep8", + blank_line_before_nested_class_or_def=True, + split_before_expression_after_opening_paren=True, + ) + text, _ = FormatCode(text, style_config=yapf_style, verify=True) + + return text + + def __repr__(self): + return f"Config (path: {self.filename}): {self._cfg_dict.__repr__()}" + + def __len__(self): + return len(self._cfg_dict) + + def __getattr__(self, name): + # # debug + # print('+'*15) + # print('name=%s' % name) + # print("addr:", id(self)) + # # print('type(self):', type(self)) + # print(self.__dict__) + # print('+'*15) + # if self.__dict__ == {}: + # raise ValueError + + return getattr(self._cfg_dict, name) + + def __getitem__(self, name): + return self._cfg_dict.__getitem__(name) + + def __setattr__(self, name, value): + if isinstance(value, dict): + value = ConfigDict(value) + self._cfg_dict.__setattr__(name, value) + + def __setitem__(self, name, value): + if isinstance(value, dict): + value = ConfigDict(value) + self._cfg_dict.__setitem__(name, value) + + def __iter__(self): + return iter(self._cfg_dict) + + def dump(self, file=None): + # import ipdb; ipdb.set_trace() + if file is None: + return self.pretty_text + else: + with open(file, "w") as f: + f.write(self.pretty_text) + + def merge_from_dict(self, options): + """Merge list into cfg_dict + + Merge the dict parsed by MultipleKVAction into this cfg. + + Examples: + >>> options = {'model.backbone.depth': 50, + ... 'model.backbone.with_cp':True} + >>> cfg = Config(dict(model=dict(backbone=dict(type='ResNet')))) + >>> cfg.merge_from_dict(options) + >>> cfg_dict = super(Config, self).__getattribute__('_cfg_dict') + >>> assert cfg_dict == dict( + ... model=dict(backbone=dict(depth=50, with_cp=True))) + + Args: + options (dict): dict of configs to merge from. + """ + option_cfg_dict = {} + for full_key, v in options.items(): + d = option_cfg_dict + key_list = full_key.split(".") + for subkey in key_list[:-1]: + d.setdefault(subkey, ConfigDict()) + d = d[subkey] + subkey = key_list[-1] + d[subkey] = v + + cfg_dict = super(SLConfig, self).__getattribute__("_cfg_dict") + super(SLConfig, self).__setattr__( + "_cfg_dict", SLConfig._merge_a_into_b(option_cfg_dict, cfg_dict) + ) + + # for multiprocess + def __setstate__(self, state): + self.__init__(state) + + def copy(self): + return SLConfig(self._cfg_dict.copy()) + + def deepcopy(self): + return SLConfig(self._cfg_dict.deepcopy()) + + +class DictAction(Action): + """ + argparse action to split an argument into KEY=VALUE form + on the first = and append to a dictionary. List options should + be passed as comma separated values, i.e KEY=V1,V2,V3 + """ + + @staticmethod + def _parse_int_float_bool(val): + try: + return int(val) + except ValueError: + pass + try: + return float(val) + except ValueError: + pass + if val.lower() in ["true", "false"]: + return True if val.lower() == "true" else False + if val.lower() in ["none", "null"]: + return None + return val + + def __call__(self, parser, namespace, values, option_string=None): + options = {} + for kv in values: + key, val = kv.split("=", maxsplit=1) + val = [self._parse_int_float_bool(v) for v in val.split(",")] + if len(val) == 1: + val = val[0] + options[key] = val + setattr(namespace, self.dest, options) diff --git a/py/local_groundingdino/util/slio.py b/py/local_groundingdino/util/slio.py new file mode 100644 index 0000000..72c1f0f --- /dev/null +++ b/py/local_groundingdino/util/slio.py @@ -0,0 +1,177 @@ +# ========================================================== +# Modified from mmcv +# ========================================================== + +import json +import pickle +from abc import ABCMeta, abstractmethod +from pathlib import Path + +import yaml + +try: + from yaml import CLoader as Loader, CDumper as Dumper +except ImportError: + from yaml import Loader, Dumper + + +# =========================== +# Rigister handler +# =========================== + + +class BaseFileHandler(metaclass=ABCMeta): + @abstractmethod + def load_from_fileobj(self, file, **kwargs): + pass + + @abstractmethod + def dump_to_fileobj(self, obj, file, **kwargs): + pass + + @abstractmethod + def dump_to_str(self, obj, **kwargs): + pass + + def load_from_path(self, filepath, mode="r", **kwargs): + with open(filepath, mode) as f: + return self.load_from_fileobj(f, **kwargs) + + def dump_to_path(self, obj, filepath, mode="w", **kwargs): + with open(filepath, mode) as f: + self.dump_to_fileobj(obj, f, **kwargs) + + +class JsonHandler(BaseFileHandler): + def load_from_fileobj(self, file): + return json.load(file) + + def dump_to_fileobj(self, obj, file, **kwargs): + json.dump(obj, file, **kwargs) + + def dump_to_str(self, obj, **kwargs): + return json.dumps(obj, **kwargs) + + +class PickleHandler(BaseFileHandler): + def load_from_fileobj(self, file, **kwargs): + return pickle.load(file, **kwargs) + + def load_from_path(self, filepath, **kwargs): + return super(PickleHandler, self).load_from_path(filepath, mode="rb", **kwargs) + + def dump_to_str(self, obj, **kwargs): + kwargs.setdefault("protocol", 2) + return pickle.dumps(obj, **kwargs) + + def dump_to_fileobj(self, obj, file, **kwargs): + kwargs.setdefault("protocol", 2) + pickle.dump(obj, file, **kwargs) + + def dump_to_path(self, obj, filepath, **kwargs): + super(PickleHandler, self).dump_to_path(obj, filepath, mode="wb", **kwargs) + + +class YamlHandler(BaseFileHandler): + def load_from_fileobj(self, file, **kwargs): + kwargs.setdefault("Loader", Loader) + return yaml.load(file, **kwargs) + + def dump_to_fileobj(self, obj, file, **kwargs): + kwargs.setdefault("Dumper", Dumper) + yaml.dump(obj, file, **kwargs) + + def dump_to_str(self, obj, **kwargs): + kwargs.setdefault("Dumper", Dumper) + return yaml.dump(obj, **kwargs) + + +file_handlers = { + "json": JsonHandler(), + "yaml": YamlHandler(), + "yml": YamlHandler(), + "pickle": PickleHandler(), + "pkl": PickleHandler(), +} + +# =========================== +# load and dump +# =========================== + + +def is_str(x): + """Whether the input is an string instance. + + Note: This method is deprecated since python 2 is no longer supported. + """ + return isinstance(x, str) + + +def slload(file, file_format=None, **kwargs): + """Load data from json/yaml/pickle files. + + This method provides a unified api for loading data from serialized files. + + Args: + file (str or :obj:`Path` or file-like object): Filename or a file-like + object. + file_format (str, optional): If not specified, the file format will be + inferred from the file extension, otherwise use the specified one. + Currently supported formats include "json", "yaml/yml" and + "pickle/pkl". + + Returns: + The content from the file. + """ + if isinstance(file, Path): + file = str(file) + if file_format is None and is_str(file): + file_format = file.split(".")[-1] + if file_format not in file_handlers: + raise TypeError(f"Unsupported format: {file_format}") + + handler = file_handlers[file_format] + if is_str(file): + obj = handler.load_from_path(file, **kwargs) + elif hasattr(file, "read"): + obj = handler.load_from_fileobj(file, **kwargs) + else: + raise TypeError('"file" must be a filepath str or a file-object') + return obj + + +def sldump(obj, file=None, file_format=None, **kwargs): + """Dump data to json/yaml/pickle strings or files. + + This method provides a unified api for dumping data as strings or to files, + and also supports custom arguments for each file format. + + Args: + obj (any): The python object to be dumped. + file (str or :obj:`Path` or file-like object, optional): If not + specified, then the object is dump to a str, otherwise to a file + specified by the filename or file-like object. + file_format (str, optional): Same as :func:`load`. + + Returns: + bool: True for success, False otherwise. + """ + if isinstance(file, Path): + file = str(file) + if file_format is None: + if is_str(file): + file_format = file.split(".")[-1] + elif file is None: + raise ValueError("file_format must be specified since file is None") + if file_format not in file_handlers: + raise TypeError(f"Unsupported format: {file_format}") + + handler = file_handlers[file_format] + if file is None: + return handler.dump_to_str(obj, **kwargs) + elif is_str(file): + handler.dump_to_path(obj, file, **kwargs) + elif hasattr(file, "write"): + handler.dump_to_fileobj(obj, file, **kwargs) + else: + raise TypeError('"file" must be a filename str or a file-object') diff --git a/py/local_groundingdino/util/utils.py b/py/local_groundingdino/util/utils.py new file mode 100644 index 0000000..9b37abe --- /dev/null +++ b/py/local_groundingdino/util/utils.py @@ -0,0 +1,608 @@ +import argparse +import json +import warnings +from collections import OrderedDict +from copy import deepcopy +from typing import Any, Dict, List + +import numpy as np +import torch +from transformers import AutoTokenizer + +from local_groundingdino.util.slconfig import SLConfig + + +def slprint(x, name="x"): + if isinstance(x, (torch.Tensor, np.ndarray)): + print(f"{name}.shape:", x.shape) + elif isinstance(x, (tuple, list)): + print("type x:", type(x)) + for i in range(min(10, len(x))): + slprint(x[i], f"{name}[{i}]") + elif isinstance(x, dict): + for k, v in x.items(): + slprint(v, f"{name}[{k}]") + else: + print(f"{name}.type:", type(x)) + + +def clean_state_dict(state_dict): + new_state_dict = OrderedDict() + for k, v in state_dict.items(): + if k[:7] == "module.": + k = k[7:] # remove `module.` + new_state_dict[k] = v + return new_state_dict + + +def renorm( + img: torch.FloatTensor, mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225] +) -> torch.FloatTensor: + # img: tensor(3,H,W) or tensor(B,3,H,W) + # return: same as img + assert img.dim() == 3 or img.dim() == 4, "img.dim() should be 3 or 4 but %d" % img.dim() + if img.dim() == 3: + assert img.size(0) == 3, 'img.size(0) shoule be 3 but "%d". (%s)' % ( + img.size(0), + str(img.size()), + ) + img_perm = img.permute(1, 2, 0) + mean = torch.Tensor(mean) + std = torch.Tensor(std) + img_res = img_perm * std + mean + return img_res.permute(2, 0, 1) + else: # img.dim() == 4 + assert img.size(1) == 3, 'img.size(1) shoule be 3 but "%d". (%s)' % ( + img.size(1), + str(img.size()), + ) + img_perm = img.permute(0, 2, 3, 1) + mean = torch.Tensor(mean) + std = torch.Tensor(std) + img_res = img_perm * std + mean + return img_res.permute(0, 3, 1, 2) + + +class CocoClassMapper: + def __init__(self) -> None: + self.category_map_str = { + "1": 1, + "2": 2, + "3": 3, + "4": 4, + "5": 5, + "6": 6, + "7": 7, + "8": 8, + "9": 9, + "10": 10, + "11": 11, + "13": 12, + "14": 13, + "15": 14, + "16": 15, + "17": 16, + "18": 17, + "19": 18, + "20": 19, + "21": 20, + "22": 21, + "23": 22, + "24": 23, + "25": 24, + "27": 25, + "28": 26, + "31": 27, + "32": 28, + "33": 29, + "34": 30, + "35": 31, + "36": 32, + "37": 33, + "38": 34, + "39": 35, + "40": 36, + "41": 37, + "42": 38, + "43": 39, + "44": 40, + "46": 41, + "47": 42, + "48": 43, + "49": 44, + "50": 45, + "51": 46, + "52": 47, + "53": 48, + "54": 49, + "55": 50, + "56": 51, + "57": 52, + "58": 53, + "59": 54, + "60": 55, + "61": 56, + "62": 57, + "63": 58, + "64": 59, + "65": 60, + "67": 61, + "70": 62, + "72": 63, + "73": 64, + "74": 65, + "75": 66, + "76": 67, + "77": 68, + "78": 69, + "79": 70, + "80": 71, + "81": 72, + "82": 73, + "84": 74, + "85": 75, + "86": 76, + "87": 77, + "88": 78, + "89": 79, + "90": 80, + } + self.origin2compact_mapper = {int(k): v - 1 for k, v in self.category_map_str.items()} + self.compact2origin_mapper = {int(v - 1): int(k) for k, v in self.category_map_str.items()} + + def origin2compact(self, idx): + return self.origin2compact_mapper[int(idx)] + + def compact2origin(self, idx): + return self.compact2origin_mapper[int(idx)] + + +def to_device(item, device): + if isinstance(item, torch.Tensor): + return item.to(device) + elif isinstance(item, list): + return [to_device(i, device) for i in item] + elif isinstance(item, dict): + return {k: to_device(v, device) for k, v in item.items()} + else: + raise NotImplementedError( + "Call Shilong if you use other containers! type: {}".format(type(item)) + ) + + +# +def get_gaussian_mean(x, axis, other_axis, softmax=True): + """ + + Args: + x (float): Input images(BxCxHxW) + axis (int): The index for weighted mean + other_axis (int): The other index + + Returns: weighted index for axis, BxC + + """ + mat2line = torch.sum(x, axis=other_axis) + # mat2line = mat2line / mat2line.mean() * 10 + if softmax: + u = torch.softmax(mat2line, axis=2) + else: + u = mat2line / (mat2line.sum(2, keepdim=True) + 1e-6) + size = x.shape[axis] + ind = torch.linspace(0, 1, size).to(x.device) + batch = x.shape[0] + channel = x.shape[1] + index = ind.repeat([batch, channel, 1]) + mean_position = torch.sum(index * u, dim=2) + return mean_position + + +def get_expected_points_from_map(hm, softmax=True): + """get_gaussian_map_from_points + B,C,H,W -> B,N,2 float(0, 1) float(0, 1) + softargmax function + + Args: + hm (float): Input images(BxCxHxW) + + Returns: + weighted index for axis, BxCx2. float between 0 and 1. + + """ + # hm = 10*hm + B, C, H, W = hm.shape + y_mean = get_gaussian_mean(hm, 2, 3, softmax=softmax) # B,C + x_mean = get_gaussian_mean(hm, 3, 2, softmax=softmax) # B,C + # return torch.cat((x_mean.unsqueeze(-1), y_mean.unsqueeze(-1)), 2) + return torch.stack([x_mean, y_mean], dim=2) + + +# Positional encoding (section 5.1) +# borrow from nerf +class Embedder: + def __init__(self, **kwargs): + self.kwargs = kwargs + self.create_embedding_fn() + + def create_embedding_fn(self): + embed_fns = [] + d = self.kwargs["input_dims"] + out_dim = 0 + if self.kwargs["include_input"]: + embed_fns.append(lambda x: x) + out_dim += d + + max_freq = self.kwargs["max_freq_log2"] + N_freqs = self.kwargs["num_freqs"] + + if self.kwargs["log_sampling"]: + freq_bands = 2.0 ** torch.linspace(0.0, max_freq, steps=N_freqs) + else: + freq_bands = torch.linspace(2.0**0.0, 2.0**max_freq, steps=N_freqs) + + for freq in freq_bands: + for p_fn in self.kwargs["periodic_fns"]: + embed_fns.append(lambda x, p_fn=p_fn, freq=freq: p_fn(x * freq)) + out_dim += d + + self.embed_fns = embed_fns + self.out_dim = out_dim + + def embed(self, inputs): + return torch.cat([fn(inputs) for fn in self.embed_fns], -1) + + +def get_embedder(multires, i=0): + import torch.nn as nn + + if i == -1: + return nn.Identity(), 3 + + embed_kwargs = { + "include_input": True, + "input_dims": 3, + "max_freq_log2": multires - 1, + "num_freqs": multires, + "log_sampling": True, + "periodic_fns": [torch.sin, torch.cos], + } + + embedder_obj = Embedder(**embed_kwargs) + embed = lambda x, eo=embedder_obj: eo.embed(x) + return embed, embedder_obj.out_dim + + +class APOPMeter: + def __init__(self) -> None: + self.tp = 0 + self.fp = 0 + self.tn = 0 + self.fn = 0 + + def update(self, pred, gt): + """ + Input: + pred, gt: Tensor() + """ + assert pred.shape == gt.shape + self.tp += torch.logical_and(pred == 1, gt == 1).sum().item() + self.fp += torch.logical_and(pred == 1, gt == 0).sum().item() + self.tn += torch.logical_and(pred == 0, gt == 0).sum().item() + self.tn += torch.logical_and(pred == 1, gt == 0).sum().item() + + def update_cm(self, tp, fp, tn, fn): + self.tp += tp + self.fp += fp + self.tn += tn + self.tn += fn + + +def inverse_sigmoid(x, eps=1e-5): + x = x.clamp(min=0, max=1) + x1 = x.clamp(min=eps) + x2 = (1 - x).clamp(min=eps) + return torch.log(x1 / x2) + + +def get_raw_dict(args): + """ + return the dicf contained in args. + + e.g: + >>> with open(path, 'w') as f: + json.dump(get_raw_dict(args), f, indent=2) + """ + if isinstance(args, argparse.Namespace): + return vars(args) + elif isinstance(args, dict): + return args + elif isinstance(args, SLConfig): + return args._cfg_dict + else: + raise NotImplementedError("Unknown type {}".format(type(args))) + + +def stat_tensors(tensor): + assert tensor.dim() == 1 + tensor_sm = tensor.softmax(0) + entropy = (tensor_sm * torch.log(tensor_sm + 1e-9)).sum() + + return { + "max": tensor.max(), + "min": tensor.min(), + "mean": tensor.mean(), + "var": tensor.var(), + "std": tensor.var() ** 0.5, + "entropy": entropy, + } + + +class NiceRepr: + """Inherit from this class and define ``__nice__`` to "nicely" print your + objects. + + Defines ``__str__`` and ``__repr__`` in terms of ``__nice__`` function + Classes that inherit from :class:`NiceRepr` should redefine ``__nice__``. + If the inheriting class has a ``__len__``, method then the default + ``__nice__`` method will return its length. + + Example: + >>> class Foo(NiceRepr): + ... def __nice__(self): + ... return 'info' + >>> foo = Foo() + >>> assert str(foo) == '' + >>> assert repr(foo).startswith('>> class Bar(NiceRepr): + ... pass + >>> bar = Bar() + >>> import pytest + >>> with pytest.warns(None) as record: + >>> assert 'object at' in str(bar) + >>> assert 'object at' in repr(bar) + + Example: + >>> class Baz(NiceRepr): + ... def __len__(self): + ... return 5 + >>> baz = Baz() + >>> assert str(baz) == '' + """ + + def __nice__(self): + """str: a "nice" summary string describing this module""" + if hasattr(self, "__len__"): + # It is a common pattern for objects to use __len__ in __nice__ + # As a convenience we define a default __nice__ for these objects + return str(len(self)) + else: + # In all other cases force the subclass to overload __nice__ + raise NotImplementedError(f"Define the __nice__ method for {self.__class__!r}") + + def __repr__(self): + """str: the string of the module""" + try: + nice = self.__nice__() + classname = self.__class__.__name__ + return f"<{classname}({nice}) at {hex(id(self))}>" + except NotImplementedError as ex: + warnings.warn(str(ex), category=RuntimeWarning) + return object.__repr__(self) + + def __str__(self): + """str: the string of the module""" + try: + classname = self.__class__.__name__ + nice = self.__nice__() + return f"<{classname}({nice})>" + except NotImplementedError as ex: + warnings.warn(str(ex), category=RuntimeWarning) + return object.__repr__(self) + + +def ensure_rng(rng=None): + """Coerces input into a random number generator. + + If the input is None, then a global random state is returned. + + If the input is a numeric value, then that is used as a seed to construct a + random state. Otherwise the input is returned as-is. + + Adapted from [1]_. + + Args: + rng (int | numpy.random.RandomState | None): + if None, then defaults to the global rng. Otherwise this can be an + integer or a RandomState class + Returns: + (numpy.random.RandomState) : rng - + a numpy random number generator + + References: + .. [1] https://gitlab.kitware.com/computer-vision/kwarray/blob/master/kwarray/util_random.py#L270 # noqa: E501 + """ + + if rng is None: + rng = np.random.mtrand._rand + elif isinstance(rng, int): + rng = np.random.RandomState(rng) + else: + rng = rng + return rng + + +def random_boxes(num=1, scale=1, rng=None): + """Simple version of ``kwimage.Boxes.random`` + + Returns: + Tensor: shape (n, 4) in x1, y1, x2, y2 format. + + References: + https://gitlab.kitware.com/computer-vision/kwimage/blob/master/kwimage/structs/boxes.py#L1390 + + Example: + >>> num = 3 + >>> scale = 512 + >>> rng = 0 + >>> boxes = random_boxes(num, scale, rng) + >>> print(boxes) + tensor([[280.9925, 278.9802, 308.6148, 366.1769], + [216.9113, 330.6978, 224.0446, 456.5878], + [405.3632, 196.3221, 493.3953, 270.7942]]) + """ + rng = ensure_rng(rng) + + tlbr = rng.rand(num, 4).astype(np.float32) + + tl_x = np.minimum(tlbr[:, 0], tlbr[:, 2]) + tl_y = np.minimum(tlbr[:, 1], tlbr[:, 3]) + br_x = np.maximum(tlbr[:, 0], tlbr[:, 2]) + br_y = np.maximum(tlbr[:, 1], tlbr[:, 3]) + + tlbr[:, 0] = tl_x * scale + tlbr[:, 1] = tl_y * scale + tlbr[:, 2] = br_x * scale + tlbr[:, 3] = br_y * scale + + boxes = torch.from_numpy(tlbr) + return boxes + + +class ModelEma(torch.nn.Module): + def __init__(self, model, decay=0.9997, device=None): + super(ModelEma, self).__init__() + # make a copy of the model for accumulating moving average of weights + self.module = deepcopy(model) + self.module.eval() + + # import ipdb; ipdb.set_trace() + + self.decay = decay + self.device = device # perform ema on different device from model if set + if self.device is not None: + self.module.to(device=device) + + def _update(self, model, update_fn): + with torch.no_grad(): + for ema_v, model_v in zip( + self.module.state_dict().values(), model.state_dict().values() + ): + if self.device is not None: + model_v = model_v.to(device=self.device) + ema_v.copy_(update_fn(ema_v, model_v)) + + def update(self, model): + self._update(model, update_fn=lambda e, m: self.decay * e + (1.0 - self.decay) * m) + + def set(self, model): + self._update(model, update_fn=lambda e, m: m) + + +class BestMetricSingle: + def __init__(self, init_res=0.0, better="large") -> None: + self.init_res = init_res + self.best_res = init_res + self.best_ep = -1 + + self.better = better + assert better in ["large", "small"] + + def isbetter(self, new_res, old_res): + if self.better == "large": + return new_res > old_res + if self.better == "small": + return new_res < old_res + + def update(self, new_res, ep): + if self.isbetter(new_res, self.best_res): + self.best_res = new_res + self.best_ep = ep + return True + return False + + def __str__(self) -> str: + return "best_res: {}\t best_ep: {}".format(self.best_res, self.best_ep) + + def __repr__(self) -> str: + return self.__str__() + + def summary(self) -> dict: + return { + "best_res": self.best_res, + "best_ep": self.best_ep, + } + + +class BestMetricHolder: + def __init__(self, init_res=0.0, better="large", use_ema=False) -> None: + self.best_all = BestMetricSingle(init_res, better) + self.use_ema = use_ema + if use_ema: + self.best_ema = BestMetricSingle(init_res, better) + self.best_regular = BestMetricSingle(init_res, better) + + def update(self, new_res, epoch, is_ema=False): + """ + return if the results is the best. + """ + if not self.use_ema: + return self.best_all.update(new_res, epoch) + else: + if is_ema: + self.best_ema.update(new_res, epoch) + return self.best_all.update(new_res, epoch) + else: + self.best_regular.update(new_res, epoch) + return self.best_all.update(new_res, epoch) + + def summary(self): + if not self.use_ema: + return self.best_all.summary() + + res = {} + res.update({f"all_{k}": v for k, v in self.best_all.summary().items()}) + res.update({f"regular_{k}": v for k, v in self.best_regular.summary().items()}) + res.update({f"ema_{k}": v for k, v in self.best_ema.summary().items()}) + return res + + def __repr__(self) -> str: + return json.dumps(self.summary(), indent=2) + + def __str__(self) -> str: + return self.__repr__() + + +def targets_to(targets: List[Dict[str, Any]], device): + """Moves the target dicts to the given device.""" + excluded_keys = [ + "questionId", + "tokens_positive", + "strings_positive", + "tokens", + "dataset_name", + "sentence_id", + "original_img_id", + "nb_eval", + "task_id", + "original_id", + "token_span", + "caption", + "dataset_type", + ] + return [ + {k: v.to(device) if k not in excluded_keys else v for k, v in t.items()} for t in targets + ] + + +def get_phrases_from_posmap( + posmap: torch.BoolTensor, tokenized: Dict, tokenizer: AutoTokenizer +): + assert isinstance(posmap, torch.Tensor), "posmap must be torch.Tensor" + if posmap.dim() == 1: + non_zero_idx = posmap.nonzero(as_tuple=True)[0].tolist() + token_ids = [tokenized["input_ids"][i] for i in non_zero_idx] + return tokenizer.decode(token_ids) + else: + raise NotImplementedError("posmap must be 1-dim") diff --git a/py/mask_by_different.py b/py/mask_by_different.py new file mode 100644 index 0000000..bf0ae7f --- /dev/null +++ b/py/mask_by_different.py @@ -0,0 +1,82 @@ +# layerstyle advance + +import torch +from PIL import Image +from .imagefunc import log, tensor2pil, pil2tensor, image2mask, mask2image, mask_fix, RMBG, chop_image + + + +class MaskByDifferent: + + def __init__(self): + self.NODE_NAME = 'MaskByDifferent' + + @classmethod + def INPUT_TYPES(self): + + return { + "required": { + "image_1": ("IMAGE", ), # + "image_2": ("IMAGE",), # + "gain": ("FLOAT", {"default": 1.5, "min": 0.1, "max": 100, "step": 0.1}), + "fix_gap": ("INT", {"default": 4, "min": 0, "max": 32, "step": 1}), + "fix_threshold": ("FLOAT", {"default": 0.75, "min": 0.01, "max": 0.99, "step": 0.01}), + "main_subject_detect": ("BOOLEAN", {"default": False}), + }, + "optional": { + } + } + + RETURN_TYPES = ( "MASK",) + RETURN_NAMES = ("mask",) + FUNCTION = 'mask_by_different' + CATEGORY = '😺dzNodes/LayerMask' + + def mask_by_different(self, image_1, image_2, gain, fix_gap, fix_threshold, main_subject_detect): + + image1s = [] + image2s = [] + ret_masks = [] + for i in image_1: + image1s.append(torch.unsqueeze(i, 0)) + for i in image_2: + image2s.append(torch.unsqueeze(i, 0)) + max_batch = max(len(image1s), len(image2s)) + blank_mask = image2mask(Image.new('L', size=tensor2pil(image1s[0]).size, color='black')) + if tensor2pil(image1s[0]).size != tensor2pil(image2s[0]).size: + log(f"Error: {self.NODE_NAME} skipped, because the image size is not match.", message_type='error') + return (torch.cat([blank_mask], dim=0)) + for i in range(max_batch): + t1 = image1s[i] if i < len(image1s) else image1s[-1] + t2 = image2s[i] if i < len(image2s) else image2s[-1] + t1 = pil2tensor(tensor2pil(t1).convert('RGB')) + t2 = pil2tensor(tensor2pil(t2).convert('RGB')) + t = torch.abs(t1 - t2) * gain + _mask = mask_fix(t, 1, fix_gap, fix_threshold, fix_threshold) + _mask = tensor2pil(_mask) + if main_subject_detect: + subject_mask1 = RMBG(tensor2pil(t1)) + subject_mask2 = RMBG(tensor2pil(t2)) + subject_mask = chop_image(subject_mask1, subject_mask2, blend_mode='add', opacity=100) + grow = (subject_mask.width + subject_mask.height) // 100 + subject_mask = mask2image(expand_mask(image2mask(subject_mask), grow * 2, grow)) + black = Image.new('L', size=_mask.size, color='black') + white = Image.new('L', size=_mask.size, color='white') + black.paste(_mask, mask=subject_mask.convert('L')) + black.paste(white, mask=subject_mask1.convert('L')) + black.paste(white, mask=subject_mask2.convert('L')) + _mask = black + + ret_masks.append(image2mask(_mask)) + + log(f"{self.NODE_NAME} Processed {len(ret_masks)} mask(s).", message_type='finish') + return (torch.cat(ret_masks, dim=0),) + + +NODE_CLASS_MAPPINGS = { + "LayerMask: MaskByDifferent": MaskByDifferent +} + +NODE_DISPLAY_NAME_MAPPINGS = { + "LayerMask: MaskByDifferent": "LayerMask: MaskByDifferent(Advance)" +} \ No newline at end of file diff --git a/py/mediapipe_facial_segment.py b/py/mediapipe_facial_segment.py new file mode 100644 index 0000000..f598b08 --- /dev/null +++ b/py/mediapipe_facial_segment.py @@ -0,0 +1,111 @@ +# layerstyle advance + +import numpy as np +from .imagefunc import * + +NODE_NAME = 'MediapipeFacialSegment' + + +# 获取特征点的坐标 +def get_points(indices, face_landmarks, width, height): + return [(int(face_landmarks.landmark[i].x * width), int(face_landmarks.landmark[i].y * height)) + for i in indices] + +# 绘制面部特征的多边形 +def draw_feature(indices, mask, face_landmarks, width, height): + points = get_points(indices, face_landmarks, width, height) + points = np.array(points, dtype=np.int32) + cv2.fillPoly(mask, [points], 255) + +class FacialFeatureSegment: + + def __init__(self): + pass + + @classmethod + def INPUT_TYPES(self): + + return { + "required": { + "image": ("IMAGE",), # + "left_eye": ("BOOLEAN", {"default": True}), + "left_eyebrow": ("BOOLEAN", {"default": True}), + "right_eye": ("BOOLEAN", {"default": True}), + "right_eyebrow": ("BOOLEAN", {"default": True}), + "lips": ("BOOLEAN", {"default": True}), + "tooth": ("BOOLEAN", {"default": True}), + }, + "optional": { + } + } + + RETURN_TYPES = ("IMAGE", "MASK",) + RETURN_NAMES = ("image", "mask",) + FUNCTION = 'facial_feature_segment' + CATEGORY = '😺dzNodes/LayerMask' + + def facial_feature_segment(self, image, + left_eye, left_eyebrow, right_eye, right_eyebrow, lips, tooth + ): + + import mediapipe as mp + # 定义面部特征索引 + left_eye_indices = [33, 7, 163, 144, 145, 153, 154, 155, 133, 173, 157, 158, 159, 160, 161, 246] + right_eye_indices = [263, 249, 390, 373, 374, 380, 381, 382, 362, 398, 384, 385, 386, 387, 388, 466] + left_eyebrow_indices = [70, 63, 105, 66, 107, 55, 65, 52, 53, 46] + right_eyebrow_indices = [336, 296, 334, 293, 300, 276, 283, 282, 295, 285] + # upper_lip_indices = [61, 146, 91, 181, 84, 17, 314, 405, 321, 375, 291, 308, 324, 318, 402, 317, 14, 87, 178, 88, 95, 78] + # lower_lip_indices = [61, 185, 40, 39, 37, 0, 267, 269, 270, 409, 291, 308, 415, 310, 311, 312, 13, 82, 81, 80, 191, 78] + tooth_indices = [78, 95, 88, 178, 87, 14, 317, 402, 318, 324, 308, 415, 310, 311, 312, 13, 82, 81, 80, 191, 78] + lips_indices = [61, 76, 62, 78, 191, 80, 81, 82, 13, 312, 311, 310, 415, 308, 324, 318, 402, 317, 14, 87, 178, + 88, 95, 185, 40, 39, 37, 0, 267, 269, 270, 409, 291, 375, 321, 405, 314, 17, 84, 181, 91, 146, + 61] + + ret_images = [] + ret_masks = [] + scale_factor = 4 + + for i in image: + face_image = tensor2pil(i.unsqueeze(0)).convert('RGB') + width, height = face_image.size + width *= scale_factor + height *= scale_factor + cv2_image = pil2cv2(face_image) + mp_face_mesh = mp.solutions.face_mesh + fase_mesh = mp_face_mesh.FaceMesh(static_image_mode=True, max_num_faces=1, min_detection_confidence=0.5) + results = fase_mesh.process(cv2_image) + mask = np.zeros((height, width), dtype=np.uint8) + + + if results.multi_face_landmarks: + for face_landmarks in results.multi_face_landmarks: + # 绘制各个面部特征 + if left_eye: + draw_feature(left_eye_indices, mask, face_landmarks, width, height) + if right_eye: + draw_feature(right_eye_indices, mask, face_landmarks, width, height) + if left_eyebrow: + draw_feature(left_eyebrow_indices, mask, face_landmarks, width, height) + if right_eyebrow: + draw_feature(right_eyebrow_indices, mask, face_landmarks, width, height) + if lips: + draw_feature(lips_indices, mask, face_landmarks, width, height) + if tooth: + draw_feature(tooth_indices, mask, face_landmarks, width, height) + + mask = cv22pil(mask).convert('L') + mask = gaussian_blur(mask, 2) + mask = mask.resize(face_image.size, Image.BILINEAR) + ret_images.append(pil2tensor(RGB2RGBA(face_image, mask))) + ret_masks.append(image2mask(mask)) + + log(f"{NODE_NAME} Processed {len(ret_images)} image(s).", message_type='finish') + return (torch.cat(ret_images, dim=0), torch.cat(ret_masks, dim=0),) + +NODE_CLASS_MAPPINGS = { + "LayerMask: MediapipeFacialSegment": FacialFeatureSegment +} + +NODE_DISPLAY_NAME_MAPPINGS = { + "LayerMask: MediapipeFacialSegment": "LayerMask: Mediapipe Facial Segment(Advance)" +} \ No newline at end of file diff --git a/py/object_detector.py b/py/object_detector.py new file mode 100644 index 0000000..40d98d1 --- /dev/null +++ b/py/object_detector.py @@ -0,0 +1,486 @@ +# layerstyle advance + +from .imagefunc import * + +select_list = ["all", "first", "by_index"] +sort_method_list = ["left_to_right", "top_to_bottom", "big_to_small", "confidence"] + + +# 规范bbox,保证x1 < x2, y1 < y2, 并返回int +def standardize_bbox(bboxes:list) -> list: + ret_bboxes = [] + for bbox in bboxes: + x1 = int(min(bbox[0], bbox[2])) + y1 = int(min(bbox[1], bbox[3])) + x2 = int(max(bbox[0], bbox[2])) + y2 = int(max(bbox[1], bbox[3])) + ret_bboxes.append([x1, y1, x2, y2]) + return ret_bboxes + +def sort_bboxes(bboxes:list, method:str) -> list: + sorted_bboxes = [] + if method == "left_to_right": + sorted_bboxes = sorted(bboxes, key=lambda bbox: bbox[0]) + elif method == "top_to_bottom": + sorted_bboxes = sorted(bboxes, key=lambda bbox: bbox[1]) + elif method == "big_to_small": + sorted_bboxes = sorted(bboxes, key=lambda bbox: (bbox[2] - bbox[0]) * (bbox[3] - bbox[1]), reverse=True) + else: + sorted_bboxes = bboxes + return sorted_bboxes + +def select_bboxes(bboxes:list, bbox_select:str, select_index:str) -> list: + indexs = extract_numbers(select_index) + if bbox_select == "all": + return bboxes + elif bbox_select == "first": + return [bboxes[0]] + elif bbox_select == "by_index": + new_bboxes = [] + for i in indexs: + try: + new_bboxes.append(bboxes[i]) + except IndexError: + log(f"Object detector output by_index: invalid bbox index {i}", message_type='warning') + return new_bboxes + + +class LS_BBOXES_JOIN: + + def __init__(self): + self.NODE_NAME = 'BBoxes Join' + + @classmethod + def INPUT_TYPES(cls): + + return { + "required": { + "bboxes_1": ("BBOXES",), + }, + "optional": { + "bboxes_2": ("BBOXES",), + "bboxes_3": ("BBOXES",), + "bboxes_4": ("BBOXES",), + } + } + + RETURN_TYPES = ("BBOXES",) + RETURN_NAMES = ("bboxes",) + FUNCTION = 'bboxes_join' + CATEGORY = '😺dzNodes/LayerMask' + + def bboxes_join(self, bboxes_1, bboxes_2=None, bboxes_3=None, bboxes_4=None): + if bboxes_2 is not None: + bboxes_1.extend(bboxes_2) + if bboxes_3 is not None: + bboxes_1.extend(bboxes_3) + if bboxes_4 is not None: + bboxes_1.extend(bboxes_4) + return (bboxes_1,) + +class LS_OBJECT_DETECTOR_FL2: + + def __init__(self): + self.NODE_NAME = 'Object Detector Florence2' + + @classmethod + def INPUT_TYPES(cls): + + return { + "required": { + "image": ("IMAGE", ), # + "prompt": ("STRING", {"default": "subject"}), + "florence2_model": ("FLORENCE2",), + "sort_method": (sort_method_list,), + "bbox_select": (select_list,), + "select_index": ("STRING", {"default": "0,"},), + }, + "optional": { + } + } + + RETURN_TYPES = ("BBOXES", "IMAGE",) + RETURN_NAMES = ("bboxes", "preview",) + FUNCTION = 'object_detector_fl2' + CATEGORY = '😺dzNodes/LayerMask' + + def object_detector_fl2(self, image, prompt, florence2_model, sort_method, bbox_select, select_index): + + ret_bboxes = [] + ret_previews = [] + max_new_tokens = 512 + num_beams = 3 + do_sample = False + fill_mask = False + + model = florence2_model['model'] + processor = florence2_model['processor'] + + for img in image: + bboxes = [] + img = tensor2pil(img.unsqueeze(0)).convert("RGB") + task = 'caption to phrase grounding' + from .florence2_ultra import process_image + results, _ = process_image(model, processor, img, task, + max_new_tokens, num_beams, do_sample, + fill_mask, prompt) + + if isinstance(results, dict): + results["width"] = img.width + results["height"] = img.height + + bboxes = self.fbboxes_to_list(results) + bboxes = sort_bboxes(bboxes, sort_method) + bboxes = select_bboxes(bboxes, bbox_select, select_index) + preview = draw_bounding_boxes(img, bboxes, color="random", line_width=-1) + ret_previews.append(pil2tensor(preview)) + ret_bboxes.append(standardize_bbox(bboxes)) + if len(bboxes) == 0: + log(f"{self.NODE_NAME} no object found", message_type='warning') + else: + log(f"{self.NODE_NAME} found {len(bboxes)} object(s)", message_type='info') + + return (ret_bboxes, torch.cat(ret_previews, dim=0)) + + def fbboxes_to_list(self, F_BBOXES) -> list: + if isinstance(F_BBOXES, str): + return None + ret_bboxes = [] + width = F_BBOXES["width"] + height = F_BBOXES["height"] + x1_c = width + y1_c = height + x2_c = y2_c = 0 + label = "" + if "bboxes" in F_BBOXES: + for idx in range(len(F_BBOXES["bboxes"])): + bbox = F_BBOXES["bboxes"][idx] + new_label = F_BBOXES["labels"][idx].removeprefix("") + if new_label not in label: + if idx > 0: + label = label + ", " + label = label + new_label + if len(bbox) == 4: + x1, y1, x2, y2 = int(bbox[0]), int(bbox[1]), int(bbox[2]), int(bbox[3]) + elif len(bbox) == 8: + x1 = int(min(bbox[0::2])) + x2 = int(max(bbox[0::2])) + y1 = int(min(bbox[1::2])) + y2 = int(max(bbox[1::2])) + else: + continue + x1_c = min(x1_c, x1) + y1_c = min(y1_c, y1) + x2_c = max(x2_c, x2) + y2_c = max(y2_c, y2) + ret_bboxes.append([x1, y1, x2, y2]) + else: + x1_c = width + y1_c = height + x2_c = y2_c = 0 + for polygon in F_BBOXES["polygons"][0]: + if len(_polygon) < 3: + print('Invalid polygon:', _polygon) + continue + x1_c = min(x1_c, int(min(polygon[0::2]))) + x2_c = max(x2_c, int(max(polygon[0::2]))) + y1_c = min(y1_c, int(min(polygon[1::2]))) + y2_c = max(y2_c, int(max(polygon[1::2]))) + ret_bboxes.append(x1_c, y1_c, x2_c, y2_c) + return ret_bboxes + +class LS_OBJECT_DETECTOR_MASK: + + def __init__(self): + self.NODE_NAME = 'Object Detector MASK' + + @classmethod + def INPUT_TYPES(cls): + + return { + "required": { + "object_mask": ("MASK",), + "sort_method": (sort_method_list,), + "bbox_select": (select_list,), + "select_index": ("STRING", {"default": "0,"},), + }, + "optional": { + } + } + + RETURN_TYPES = ("BBOXES", "IMAGE",) + RETURN_NAMES = ("bboxes", "preview",) + FUNCTION = 'object_detector_mask' + CATEGORY = '😺dzNodes/LayerMask' + + def object_detector_mask(self, object_mask, sort_method, bbox_select, select_index): + + ret_bboxes = [] + ret_previews = [] + + if object_mask.dim() == 2: + object_mask = torch.unsqueeze(object_mask, 0) + + for msk in object_mask: + bboxes = [] + cv_mask = tensor2cv2(msk) + cv_mask = cv2.cvtColor(cv_mask, cv2.COLOR_BGR2GRAY) + _, binary = cv2.threshold(cv_mask, 127, 255, cv2.THRESH_BINARY) + # invert mask + # binary = cv2.bitwise_not(binary) + contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) + for contour in contours: + x, y, w, h = cv2.boundingRect(contour) + bboxes.append([x, y, x + w, y + h]) + bboxes = sort_bboxes(bboxes, sort_method) + bboxes = select_bboxes(bboxes, bbox_select, select_index) + preview = draw_bounding_boxes(tensor2pil(msk).convert("RGB"), bboxes, color="random", line_width=-1) + ret_previews.append(pil2tensor(preview)) + + if len(bboxes) == 0: + log(f"{self.NODE_NAME} no object found", message_type='warning') + else: + log(f"{self.NODE_NAME} found {len(bboxes)} object(s)", message_type='info') + ret_bboxes.append(standardize_bbox(bboxes)) + + return (ret_bboxes, torch.cat(ret_previews, dim=0)) + + +class LS_OBJECT_DETECTOR_YOLO8: + + def __init__(self): + self.NODE_NAME = 'Object Detector YOLO8' + + @classmethod + def INPUT_TYPES(cls): + model_ext = [".pt"] + model_path = os.path.join(folder_paths.models_dir, 'yolo') + FILES_DICT = get_files(model_path, model_ext) + FILE_LIST = list(FILES_DICT.keys()) + return { + "required": { + "image": ("IMAGE", ), + "yolo_model": (FILE_LIST,), + "sort_method": (sort_method_list,), + "bbox_select": (select_list,), + "select_index": ("STRING", {"default": "0,"},), + }, + "optional": { + } + } + + RETURN_TYPES = ("BBOXES", "IMAGE",) + RETURN_NAMES = ("bboxes", "preview",) + FUNCTION = 'object_detector_yolo8' + CATEGORY = '😺dzNodes/LayerMask' + + def object_detector_yolo8(self, image, yolo_model, sort_method, bbox_select, select_index): + + from ultralytics import YOLO + model_path = os.path.join(folder_paths.models_dir, 'yolo') + yolo_model = YOLO(os.path.join(model_path, yolo_model)) + + ret_bboxes = [] + ret_previews = [] + + for img in image: + bboxes = [] + img = torch.unsqueeze(img.unsqueeze(0), 0) + _image = tensor2pil(img) + results = yolo_model(_image, retina_masks=True) + for result in results: + yolo_plot_image = cv2.cvtColor(result.plot(), cv2.COLOR_BGR2RGB) + + # no mask, if have box, draw box + if result.boxes is not None and len(result.boxes.xyxy) > 0: + for box in result.boxes: + x1, y1, x2, y2 = box.xyxy[0].cpu().numpy() + bboxes.append([x1, y1, x2, y2]) + bboxes = sort_bboxes(bboxes, sort_method) + bboxes = select_bboxes(bboxes, bbox_select, select_index) + preview = draw_bounding_boxes(_image.convert("RGB"), bboxes, color="random", line_width=-1) + ret_previews.append(pil2tensor(preview)) + + if len(bboxes) == 0: + log(f"{self.NODE_NAME} no object found", message_type='warning') + else: + log(f"{self.NODE_NAME} found {len(bboxes)} object(s)", message_type='info') + ret_bboxes.append(standardize_bbox(bboxes)) + + return (ret_bboxes, torch.cat(ret_previews, dim=0),) + +class LS_OBJECT_DETECTOR_YOLOWORLD: + + def __init__(self): + self.NODE_NAME = 'Object Detector YOLO-WORLD' + self.model_path = os.path.join(folder_paths.models_dir, 'yolo-world') + os.environ['MODEL_CACHE_DIR'] = self.model_path + + @classmethod + def INPUT_TYPES(cls): + model_list =['yolo_world/v2-x', 'yolo_world/v2-l', 'yolo_world/v2-m', + 'yolo_world/v2-s', 'yolo_world/l', 'yolo_world/m', + 'yolo_world/s'] + return { + "required": { + "image": ("IMAGE", ), + "yolo_world_model": (model_list,), + "confidence_threshold": ("FLOAT", {"default": 0.05, "min": 0, "max": 1, "step": 0.01}), + "nms_iou_threshold": ("FLOAT", {"default": 0.3, "min": 0, "max": 1, "step": 0.01}), + "prompt": ("STRING", {"default": "subject"}), + "sort_method": (sort_method_list,), + "bbox_select": (select_list,), + "select_index": ("STRING", {"default": "0,"},), + }, + "optional": { + } + } + + RETURN_TYPES = ("BBOXES", "IMAGE",) + RETURN_NAMES = ("bboxes", "preview",) + FUNCTION = 'object_detector_yoloworld' + CATEGORY = '😺dzNodes/LayerMask' + + def object_detector_yoloworld(self, image, yolo_world_model, + confidence_threshold, nms_iou_threshold, prompt, + sort_method, bbox_select, select_index): + ret_previews = [] + ret_bboxes = [] + + import supervision as sv + + model=self.load_yolo_world_model(yolo_world_model, prompt) + + for i in image: + infer_outputs = [] + # img = (255 * img.unsqueeze(0).cpu().numpy()).astype(np.uint8) + img = tensor2np(i) + results = model.infer( + img, confidence=confidence_threshold) + detections = sv.Detections.from_inference(results) + detections = detections.with_nms( + class_agnostic=False, + threshold=nms_iou_threshold + ) + infer_outputs.append(detections) + + # if len(infer_outputs[0].xyxy) > 0: + # bboxes = infer_outputs[0].xyxy.tolist() + # bboxes = [[int(value) for value in sublist] for sublist in bboxes] + # bboxes = sort_bboxes(bboxes, sort_method) + # bboxes = select_bboxes(bboxes, bbox_select, select_index) + # else: + # bboxes = [] + + bboxes = infer_outputs[0].xyxy.tolist() + bboxes = [[int(value) for value in sublist] for sublist in bboxes] + bboxes = sort_bboxes(bboxes, sort_method) + bboxes = select_bboxes(bboxes, bbox_select, select_index) + + + preview = draw_bounding_boxes(tensor2pil(i.unsqueeze(0)).convert('RGB'), bboxes, color="random", line_width=-1) + ret_previews.append(pil2tensor(preview)) + + if len(bboxes) == 0: + log(f"{self.NODE_NAME} no object found", message_type='warning') + else: + log(f"{self.NODE_NAME} found {len(bboxes)} object(s)", message_type='info') + ret_bboxes.append(standardize_bbox(bboxes)) + + return (ret_bboxes, torch.cat(ret_previews, dim=0)) + + def process_categories(self, categories: str) -> List[str]: + return [category.strip().lower() for category in categories.split(',')] + + def load_yolo_world_model(self,model_id: str, categories: str) -> List[torch.nn.Module]: + from inference.models import YOLOWorld as YOLOWorldImpl + model = YOLOWorldImpl(model_id=model_id) + categories = self.process_categories(categories) + model.set_classes(categories) + return model + + + +class LS_DrawBBoxMask: + + def __init__(self): + self.NODE_NAME = 'Draw BBOX Mask' + pass + + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "image": ("IMAGE",), + "bboxes": ("BBOXES",), + "grow_top": ("FLOAT", {"default": 0, "min": -10, "max": 10, "step": 0.01}), # bbox向上扩展,按高度比例 + "grow_bottom": ("FLOAT", {"default": 0, "min": -10, "max": 10, "step": 0.01}), + "grow_left": ("FLOAT", {"default": 0, "min": -10, "max": 10, "step": 0.01}), + "grow_right": ("FLOAT", {"default": 0, "min": -10, "max": 10, "step": 0.01}), + }, + "optional": { + } + } + + RETURN_TYPES = ("MASK",) + RETURN_NAMES = ("mask",) + FUNCTION = 'draw_bbox_mask' + CATEGORY = '😺dzNodes/LayerMask' + + def draw_bbox_mask(self, image, bboxes, grow_top, grow_bottom, grow_left, grow_right + ): + + ret_masks = [] + for index in range(len(image)): + img = tensor2pil(image[index].unsqueeze(0)) + mask = Image.new("L", img.size, color='black') + bboxes_i = bboxes[index] + for bbox in bboxes_i: + try: + if len(bbox) == 0: + continue + else: + x1, y1, x2, y2 = bbox + except ValueError: + if len(bbox) == 0: + continue + else: + x1, y1, x2, y2 = bbox[index] + w = x2 - x1 + h = y2 - y1 + if grow_top: + y1 = int(y1 - h * grow_top) + if grow_bottom: + y2 = int(y2 + h * grow_bottom) + if grow_left: + x1 = int(x1 - w * grow_left) + if grow_right: + x2 = int(x2 + w * grow_right) + if y1 > y2 or x1 > x2: + log(f"{self.NODE_NAME} Invalid bbox after extend: ({x1},{y1},{x2},{y2})", message_type='warning') + continue + draw = ImageDraw.Draw(mask) + draw.rectangle([x1, y1, x2, y2], fill='white', outline='white', width=0) + ret_masks.append(pil2tensor(mask)) + + log(f"{self.NODE_NAME} Processed {len(ret_masks)} mask(s).", message_type='finish') + return (torch.cat(ret_masks, dim=0),) + + +NODE_CLASS_MAPPINGS = { + "LayerMask: BBoxJoin": LS_BBOXES_JOIN, + "LayerMask: DrawBBoxMask": LS_DrawBBoxMask, + "LayerMask: ObjectDetectorFL2": LS_OBJECT_DETECTOR_FL2, + "LayerMask: ObjectDetectorMask": LS_OBJECT_DETECTOR_MASK, + "LayerMask: ObjectDetectorYOLO8": LS_OBJECT_DETECTOR_YOLO8, + "LayerMask: ObjectDetectorYOLOWorld": LS_OBJECT_DETECTOR_YOLOWORLD +} + +NODE_DISPLAY_NAME_MAPPINGS = { + "LayerMask: BBoxJoin": "LayerMask: BBox Join(Advance)", + "LayerMask: DrawBBoxMask": "LayerMask: Draw BBox Mask(Advance)", + "LayerMask: ObjectDetectorFL2": "LayerMask: Object Detector Florence2(Advance)", + "LayerMask: ObjectDetectorMask": "LayerMask: Object Detector Mask(Advance)", + "LayerMask: ObjectDetectorYOLO8": "LayerMask: Object Detector YOLO8(Advance)", + "LayerMask: ObjectDetectorYOLOWorld": "LayerMask: Object Detector YOLO World(Obsolete)" +} \ No newline at end of file diff --git a/py/person_mask_Ultra.py b/py/person_mask_Ultra.py new file mode 100644 index 0000000..4f803ad --- /dev/null +++ b/py/person_mask_Ultra.py @@ -0,0 +1,146 @@ +# layerstyle advance + +from .imagefunc import * +from functools import reduce +import wget +import folder_paths +from .segment_anything_func import * + +NODE_NAME = 'PersonMaskUltra' + + +class PersonMaskUltra: + + def __init__(self): + # download the model if we need it + get_a_person_mask_generator_model_path() + + @classmethod + def INPUT_TYPES(self): + return { + "required": + { + "images": ("IMAGE",), + "face": ("BOOLEAN", {"default": True, "label_on": "enabled", "label_off": "disabled"}), + "hair": ("BOOLEAN", {"default": False, "label_on": "enabled", "label_off": "disabled"}), + "body": ("BOOLEAN", {"default": False, "label_on": "enabled", "label_off": "disabled"}), + "clothes": ("BOOLEAN", {"default": False, "label_on": "enabled", "label_off": "disabled"}), + "accessories": ("BOOLEAN", {"default": False, "label_on": "enabled", "label_off": "disabled"}), + "background": ("BOOLEAN", {"default": False, "label_on": "enabled", "label_off": "disabled"}), + "confidence": ("FLOAT", {"default": 0.4, "min": 0.05, "max": 0.95, "step": 0.01},), + "detail_range": ("INT", {"default": 16, "min": 1, "max": 256, "step": 1}), + "black_point": ("FLOAT", {"default": 0.01, "min": 0.01, "max": 0.98, "step": 0.01}), + "white_point": ("FLOAT", {"default": 0.99, "min": 0.02, "max": 0.99, "step": 0.01}), + "process_detail": ("BOOLEAN", {"default": True}), + }, + "optional": + { + } + } + + RETURN_TYPES = ("IMAGE", "MASK", ) + RETURN_NAMES = ("image", "mask", ) + FUNCTION = 'person_mask_ultra' + CATEGORY = '😺dzNodes/LayerMask' + + def get_mediapipe_image(self, image: Image): + import mediapipe as mp + # Convert image to NumPy array + numpy_image = np.asarray(image) + image_format = mp.ImageFormat.SRGB + # Convert BGR to RGB (if necessary) + if numpy_image.shape[-1] == 4: + image_format = mp.ImageFormat.SRGBA + elif numpy_image.shape[-1] == 3: + image_format = mp.ImageFormat.SRGB + numpy_image = cv2.cvtColor(numpy_image, cv2.COLOR_BGR2RGB) + return mp.Image(image_format=image_format, data=numpy_image) + + def person_mask_ultra(self, images, face, hair, body, clothes, + accessories, background, confidence, + detail_range, black_point, white_point, process_detail): + import mediapipe as mp + a_person_mask_generator_model_path = get_a_person_mask_generator_model_path() + a_person_mask_generator_model_buffer = None + with open(a_person_mask_generator_model_path, "rb") as f: + a_person_mask_generator_model_buffer = f.read() + image_segmenter_base_options = mp.tasks.BaseOptions(model_asset_buffer=a_person_mask_generator_model_buffer) + options = mp.tasks.vision.ImageSegmenterOptions( + base_options=image_segmenter_base_options, + running_mode=mp.tasks.vision.RunningMode.IMAGE, + output_category_mask=True) + # Create the image segmenter + ret_images = [] + ret_masks = [] + with mp.tasks.vision.ImageSegmenter.create_from_options(options) as segmenter: + for image in images: + # image = torch.unsqueeze(image, 0) + orig_image = tensor2pil(image.unsqueeze(0)).convert('RGB') + # Convert the Tensor to a PIL image + # i = 255. * image.cpu().numpy() + # image_pil = Image.fromarray(np.clip(i, 0, 255).astype(np.uint8)) + image_pil = tensor2pil(image.unsqueeze(0)).convert('RGB') + # create our foreground and background arrays for storing the mask results + mask_background_array = np.zeros((image_pil.size[0], image_pil.size[1], 4), dtype=np.uint8) + mask_background_array[:] = (0, 0, 0, 255) + mask_foreground_array = np.zeros((image_pil.size[0], image_pil.size[1], 4), dtype=np.uint8) + mask_foreground_array[:] = (255, 255, 255, 255) + # Retrieve the masks for the segmented image + media_pipe_image = self.get_mediapipe_image(image=image_pil) + segmented_masks = segmenter.segment(media_pipe_image) + masks = [] + if background: + masks.append(segmented_masks.confidence_masks[0]) + if hair: + masks.append(segmented_masks.confidence_masks[1]) + if body: + masks.append(segmented_masks.confidence_masks[2]) + if face: + masks.append(segmented_masks.confidence_masks[3]) + if clothes: + masks.append(segmented_masks.confidence_masks[4]) + if accessories: + masks.append(segmented_masks.confidence_masks[5]) + image_data = media_pipe_image.numpy_view() + image_shape = image_data.shape + # convert the image shape from "rgb" to "rgba" aka add the alpha channel + if image_shape[-1] == 3: + image_shape = (image_shape[0], image_shape[1], 4) + mask_background_array = np.zeros(image_shape, dtype=np.uint8) + mask_background_array[:] = (0, 0, 0, 255) + mask_foreground_array = np.zeros(image_shape, dtype=np.uint8) + mask_foreground_array[:] = (255, 255, 255, 255) + mask_arrays = [] + if len(masks) == 0: + mask_arrays.append(mask_background_array) + else: + for i, mask in enumerate(masks): + condition = np.stack((mask.numpy_view(),) * image_shape[-1], axis=-1) > confidence + mask_array = np.where(condition, mask_foreground_array, mask_background_array) + mask_arrays.append(mask_array) + # Merge our masks taking the maximum from each + merged_mask_arrays = reduce(np.maximum, mask_arrays) + # Create the image + mask_image = Image.fromarray(merged_mask_arrays) + # convert PIL image to tensor image + tensor_mask = mask_image.convert("RGB") + tensor_mask = np.array(tensor_mask).astype(np.float32) / 255.0 + tensor_mask = torch.from_numpy(tensor_mask)[None,] + tensor_mask = tensor_mask.squeeze(3)[..., 0] + _mask = tensor2pil(tensor_mask).convert('L') + if process_detail: + _mask = tensor2pil(mask_edge_detail(pil2tensor(orig_image), pil2tensor(_mask), detail_range, black_point, white_point)) + ret_image = RGB2RGBA(orig_image, _mask) + ret_images.append(pil2tensor(ret_image)) + ret_masks.append(image2mask(_mask)) + + log(f"{NODE_NAME} Processed {len(ret_images)} image(s).", message_type='finish') + return (torch.cat(ret_images, dim=0), torch.cat(ret_masks, dim=0),) + +NODE_CLASS_MAPPINGS = { + "LayerMask: PersonMaskUltra": PersonMaskUltra +} + +NODE_DISPLAY_NAME_MAPPINGS = { + "LayerMask: PersonMaskUltra": "LayerMask: PersonMaskUltra(Advance)" +} \ No newline at end of file diff --git a/py/person_mask_ultra_v2.py b/py/person_mask_ultra_v2.py new file mode 100644 index 0000000..8cdbd64 --- /dev/null +++ b/py/person_mask_ultra_v2.py @@ -0,0 +1,176 @@ +# layerstyle advance + +import cv2 + +from .imagefunc import * +from functools import reduce +import wget +import folder_paths +from .segment_anything_func import * + +NODE_NAME = 'PersonMaskUltra V2' + +class PersonMaskUltraV2: + + def __init__(self): + # download the model if we need it + get_a_person_mask_generator_model_path() + + @classmethod + def INPUT_TYPES(self): + + method_list = ['VITMatte', 'VITMatte(local)', 'PyMatting', 'GuidedFilter', ] + device_list = ['cuda','cpu'] + return { + "required": + { + "images": ("IMAGE",), + "face": ("BOOLEAN", {"default": True, "label_on": "enabled", "label_off": "disabled"}), + "hair": ("BOOLEAN", {"default": False, "label_on": "enabled", "label_off": "disabled"}), + "body": ("BOOLEAN", {"default": False, "label_on": "enabled", "label_off": "disabled"}), + "clothes": ("BOOLEAN", {"default": False, "label_on": "enabled", "label_off": "disabled"}), + "accessories": ("BOOLEAN", {"default": False, "label_on": "enabled", "label_off": "disabled"}), + "background": ("BOOLEAN", {"default": False, "label_on": "enabled", "label_off": "disabled"}), + "confidence": ("FLOAT", {"default": 0.4, "min": 0.05, "max": 0.95, "step": 0.01},), + "detail_method": (method_list,), + "detail_erode": ("INT", {"default": 6, "min": 1, "max": 255, "step": 1}), + "detail_dilate": ("INT", {"default": 6, "min": 1, "max": 255, "step": 1}), + "black_point": ("FLOAT", {"default": 0.01, "min": 0.01, "max": 0.98, "step": 0.01, "display": "slider"}), + "white_point": ("FLOAT", {"default": 0.99, "min": 0.02, "max": 0.99, "step": 0.01, "display": "slider"}), + "process_detail": ("BOOLEAN", {"default": True}), + "device": (device_list,), + "max_megapixels": ("FLOAT", {"default": 2.0, "min": 1, "max": 999, "step": 0.1}), + }, + "optional": + { + } + } + + RETURN_TYPES = ("IMAGE", "MASK", ) + RETURN_NAMES = ("image", "mask", ) + FUNCTION = 'person_mask_ultra_v2' + CATEGORY = '😺dzNodes/LayerMask' + + def get_mediapipe_image(self, image: Image): + import mediapipe as mp + # Convert image to NumPy array + numpy_image = np.asarray(image) + image_format = mp.ImageFormat.SRGB + # Convert BGR to RGB (if necessary) + if numpy_image.shape[-1] == 4: + image_format = mp.ImageFormat.SRGBA + elif numpy_image.shape[-1] == 3: + image_format = mp.ImageFormat.SRGB + + numpy_image = cv2.cvtColor(numpy_image, cv2.COLOR_BGR2RGB) + return mp.Image(image_format=image_format, data=numpy_image) + + def person_mask_ultra_v2(self, images, face, hair, body, clothes, + accessories, background, confidence, + detail_method, detail_erode, detail_dilate, + black_point, white_point, process_detail, device, max_megapixels,): + + import mediapipe as mp + a_person_mask_generator_model_path = get_a_person_mask_generator_model_path() + a_person_mask_generator_model_buffer = None + with open(a_person_mask_generator_model_path, "rb") as f: + a_person_mask_generator_model_buffer = f.read() + image_segmenter_base_options = mp.tasks.BaseOptions(model_asset_buffer=a_person_mask_generator_model_buffer) + options = mp.tasks.vision.ImageSegmenterOptions( + base_options=image_segmenter_base_options, + running_mode=mp.tasks.vision.RunningMode.IMAGE, + output_category_mask=True) + # Create the image segmenter + ret_images = [] + ret_masks = [] + + if detail_method == 'VITMatte(local)': + local_files_only = True + else: + local_files_only = False + + with mp.tasks.vision.ImageSegmenter.create_from_options(options) as segmenter: + for image in images: + _image = torch.unsqueeze(image, 0) + orig_image = tensor2pil(_image).convert('RGB') + # Convert the Tensor to a PIL image + i = 255. * image.cpu().numpy() + image_pil = Image.fromarray(np.clip(i, 0, 255).astype(np.uint8)) + # create our foreground and background arrays for storing the mask results + mask_background_array = np.zeros((image_pil.size[0], image_pil.size[1], 4), dtype=np.uint8) + mask_background_array[:] = (0, 0, 0, 255) + mask_foreground_array = np.zeros((image_pil.size[0], image_pil.size[1], 4), dtype=np.uint8) + mask_foreground_array[:] = (255, 255, 255, 255) + # Retrieve the masks for the segmented image + media_pipe_image = self.get_mediapipe_image(image=image_pil) + segmented_masks = segmenter.segment(media_pipe_image) + masks = [] + if background: + masks.append(segmented_masks.confidence_masks[0]) + if hair: + masks.append(segmented_masks.confidence_masks[1]) + if body: + masks.append(segmented_masks.confidence_masks[2]) + if face: + masks.append(segmented_masks.confidence_masks[3]) + if clothes: + masks.append(segmented_masks.confidence_masks[4]) + if accessories: + masks.append(segmented_masks.confidence_masks[5]) + image_data = media_pipe_image.numpy_view() + image_shape = image_data.shape + # convert the image shape from "rgb" to "rgba" aka add the alpha channel + if image_shape[-1] == 3: + image_shape = (image_shape[0], image_shape[1], 4) + mask_background_array = np.zeros(image_shape, dtype=np.uint8) + mask_background_array[:] = (0, 0, 0, 255) + mask_foreground_array = np.zeros(image_shape, dtype=np.uint8) + mask_foreground_array[:] = (255, 255, 255, 255) + mask_arrays = [] + if len(masks) == 0: + mask_arrays.append(mask_background_array) + else: + for i, mask in enumerate(masks): + condition = np.stack((mask.numpy_view(),) * image_shape[-1], axis=-1) > confidence + mask_array = np.where(condition, mask_foreground_array, mask_background_array) + mask_arrays.append(mask_array) + # Merge our masks taking the maximum from each + merged_mask_arrays = reduce(np.maximum, mask_arrays) + # Create the image + mask_image = Image.fromarray(merged_mask_arrays) + # convert PIL image to tensor image + tensor_mask = mask_image.convert("RGB") + tensor_mask = np.array(tensor_mask).astype(np.float32) / 255.0 + tensor_mask = torch.from_numpy(tensor_mask)[None,] + _mask = tensor_mask.squeeze(3)[..., 0] + + detail_range = detail_erode + detail_dilate + if process_detail: + if detail_method == 'GuidedFilter': + _mask = guided_filter_alpha(pil2tensor(orig_image), _mask, detail_range // 6 + 1) + _mask = tensor2pil(histogram_remap(_mask, black_point, white_point)) + elif detail_method == 'PyMatting': + _mask = tensor2pil( + mask_edge_detail(pil2tensor(orig_image), _mask, + detail_range // 8 + 1, black_point, white_point)) + else: + _trimap = generate_VITMatte_trimap(_mask, detail_erode, detail_dilate) + _mask = generate_VITMatte(orig_image, _trimap, local_files_only=local_files_only, device=device, max_megapixels=max_megapixels) + _mask = tensor2pil(histogram_remap(pil2tensor(_mask), black_point, white_point)) + else: + _mask = mask2image(_mask) + + ret_image = RGB2RGBA(orig_image, _mask) + ret_images.append(pil2tensor(ret_image)) + ret_masks.append(image2mask(_mask)) + + log(f"{NODE_NAME} Processed {len(ret_images)} image(s).", message_type='finish') + return (torch.cat(ret_images, dim=0), torch.cat(ret_masks, dim=0),) + +NODE_CLASS_MAPPINGS = { + "LayerMask: PersonMaskUltra V2": PersonMaskUltraV2 +} + +NODE_DISPLAY_NAME_MAPPINGS = { + "LayerMask: PersonMaskUltra V2": "LayerMask: PersonMaskUltra V2(Advance)" +} \ No newline at end of file diff --git a/py/phi_nodes.py b/py/phi_nodes.py new file mode 100644 index 0000000..396507f --- /dev/null +++ b/py/phi_nodes.py @@ -0,0 +1,209 @@ +# layerstyle advance + +import numpy as np +import os +import torch +from PIL import Image +from transformers import AutoModelForCausalLM, AutoProcessor, AutoTokenizer, pipeline +import folder_paths +from .imagefunc import log, clear_memory + +model_path = os.path.join(folder_paths.models_dir, 'LLM') + +class LS_PhiModel: + def __init__(self, name, device, dtype): + self.name = name + self.device = device + self.dtype = dtype + self.model = None + self.tokenizer= None + self.processor = None + +class LS_Phi_Prompt: + + CATEGORY = '😺dzNodes/LayerUtility' + FUNCTION = "phi_prompt" + RETURN_TYPES = ("STRING",) + RETURN_NAMES = ("text",) + + def __init__(self): + self.NODE_NAME = 'Phi Prompt' + self.previous_model = LS_PhiModel("", "", "") + + @classmethod + def INPUT_TYPES(self): + phi_model_list = ["auto", "Phi-3.5-mini-instruct", "Phi-3.5-vision-instruct"] + device_list = ['cuda', 'cpu'] + dtype_list = ['fp16', 'bf16', 'fp32'] + return { + "required": { + "model": (phi_model_list,), + "device": (device_list,), + "dtype": (dtype_list,), + "cache_model": ("BOOLEAN", {"default": False}), + "system_prompt": ("STRING", {"default": "You are a helpful AI assistant.","multiline": False}), + "user_prompt": ("STRING", {"default": "Describe this image","multiline": True}), + "do_sample": ("BOOLEAN", {"default": True}), + "temperature": ("FLOAT", {"default": 0.5, "min": 0.01, "max":1, "step": 0.01}), + "max_new_tokens": ("INT", {"default": 512,"min": 8, "max":4096, "step": 1}), + }, + "optional": { + "image": ("IMAGE",), + } + } + + def phi_prompt(self, model, device, dtype, cache_model, + system_prompt, user_prompt, do_sample, + temperature, max_new_tokens, image=None): + + if model == "Phi-3.5-mini-instruct" or (model=="auto" and image is None): + + if (self.previous_model.name != "Phi-3.5-mini-instruct" + or self.previous_model.device != device + or self.previous_model.dtype != dtype): + phi_model = self.load_phi_model("Phi-3.5-mini-instruct", device, dtype) + else: + phi_model = self.previous_model + + # Prepare messages + messages = [ + {"role": "system", "content": system_prompt}, + {"role": "user", "content": user_prompt} + ] + + # Build pipeline + pipe = pipeline("text-generation", model=phi_model.model, tokenizer=phi_model.tokenizer) + generation_args = { + "return_full_text": False, + "do_sample": do_sample, + "temperature": temperature, + "max_new_tokens": max_new_tokens + } + + # Generate + output = pipe(messages, **generation_args) + response = output[0]["generated_text"] + + elif model == "Phi-3.5-vision-instruct" or (model=="auto" and image is not None): + + if image is None: + log(f"{self.NODE_NAME} input is vision model but image is None.", message_type="error") + return ("",) + else: + if (self.previous_model.name != "Phi-3.5-vision-instruct" + or self.previous_model.device != device + or self.previous_model.dtype != dtype): + phi_model = self.load_phi_model("Phi-3.5-vision-instruct", device, dtype) + else: + phi_model = self.previous_model + images = self.tensor2batch_pil(image) # Convert tensor to PIL image batch + + # Prepare images placeholders in the prompt + placeholder = '' + for index, value in enumerate(images, start=1): + placeholder += f"<|image_{index}|>\n" + + # Prepare prompt + messages = [{"role": "user", "content": placeholder + user_prompt}] + prompt = phi_model.processor.tokenizer.apply_chat_template( + messages, + tokenize=False, + add_generation_prompt=True + ) + + # Prepare generation arguments + inputs = phi_model.processor(prompt, images, return_tensors="pt").to(device) + generate_args = {} + if do_sample: + generate_args["do_sample"] = do_sample + generate_args["temperature"] = temperature + else: + generate_args["do_sample"] = do_sample + + # Generate + generate_ids = phi_model.model.generate( + **inputs, + eos_token_id=phi_model.processor.tokenizer.eos_token_id, + max_new_tokens=max_new_tokens, + **generate_args + ) + + # Remove input tokens + generate_ids = generate_ids[:, inputs['input_ids'].shape[1]:] + response = phi_model.processor.batch_decode( + generate_ids, + skip_special_tokens=True, + clean_up_tokenization_spaces=False + )[0] + + log(f"{self.NODE_NAME} processed successfully.", message_type="finish") + + if cache_model: + self.previous_model = phi_model + else: + self.previous_model = LS_PhiModel("", "", "") + del phi_model + clear_memory() + response = response.strip() + return (response,) + + def load_phi_model(self, model, device, dtype): + phi_model =LS_PhiModel(model, device, dtype) + model_dir = os.path.join(model_path, model) + if dtype == 'fp16': + torch_dtype = torch.float16 + elif dtype == 'bf16': + torch_dtype = torch.bfloat16 + else: + torch_dtype = torch.float32 + clear_memory() + if model == "Phi-3.5-mini-instruct": + try: + phi_model.model = AutoModelForCausalLM.from_pretrained( + pretrained_model_name_or_path=model_dir, + device_map=device, + torch_dtype=torch_dtype, + trust_remote_code=True + ) + phi_model.tokenizer = AutoTokenizer.from_pretrained( + model_dir, + ) + except Exception as e: + log(f"{self.NODE_NAME} failed to load {model}. Error: {e}", message_type="error") + + elif model == "Phi-3.5-vision-instruct": + try: + phi_model.model = AutoModelForCausalLM.from_pretrained( + model_dir, + device_map=device, + trust_remote_code=True, + torch_dtype=torch_dtype, + # _attn_implementation="flash_attention_2", + _attn_implementation="eager" + ) + # For best performance, use num_crops=4 for multi-frame, num_crops=16 for single-frame. + phi_model.processor = AutoProcessor.from_pretrained( + model_dir, + trust_remote_code=True, + num_crops=16 + ) + except Exception as e: + log(f"{self.NODE_NAME} failed to load {model}. Error: {e}", message_type="error") + + return phi_model + def tensor2batch_pil(self, image): + batch_count = image.size(0) if len(image.shape) > 3 else 1 + if batch_count > 1: + out = [] + for i in range(batch_count): + out.extend(self.tensor2pil(image[i])) + return out + return [Image.fromarray(np.clip(255.0 * image.cpu().numpy().squeeze(), 0, 255).astype(np.uint8))] + +NODE_CLASS_MAPPINGS = { + "LayerUtility: PhiPrompt": LS_Phi_Prompt +} + +NODE_DISPLAY_NAME_MAPPINGS = { + "LayerUtility: PhiPrompt": "LayerUtility: Phi Prompt(Advance)" +} diff --git a/py/prompt_embellish.py b/py/prompt_embellish.py new file mode 100644 index 0000000..9eb4fdf --- /dev/null +++ b/py/prompt_embellish.py @@ -0,0 +1,104 @@ +# layerstyle advance + +from .imagefunc import * + +NODE_NAME = 'PromptEmbellish' + +class PromptEmbellish: + + def __init__(self): + pass + + @classmethod + def INPUT_TYPES(self): + api_list = ['gemini-1.5-flash', 'gemini-pro-vision'] + return { + "required": { + "api": (api_list,), + "token_limit": ("INT", {"default": 40, "min": 2, "max": 1024, "step": 1}), + "describe": ("STRING", {"default": "", "multiline": True}), + }, + "optional": { + "image": ("IMAGE",), + } + } + + RETURN_TYPES = ("STRING",) + RETURN_NAMES = ("text",) + FUNCTION = 'prompt_embellish' + CATEGORY = '😺dzNodes/LayerUtility/Prompt' + + def prompt_embellish(self, api, token_limit, describe, image=None): + if describe == "" and image is None: + return ("",) + import google.generativeai as genai + ret_text = "" + first_step_prompt = (f"You are creating a prompt for Stable Diffusion to generate an image. " + f"First step:Using '{describe}' as the basic content, " + f"polish and embellish it to describe into text, keep it on {token_limit} tokens." + f"Second step: Generate a Stable Diffusion text prompt for based on first step in at least {token_limit} words." + f"Only respond with the prompt itself, but embellish it." + ) + + genai.configure(api_key=get_api_key('google_api_key'), transport='rest') + if describe != "": + model = genai.GenerativeModel('gemini-pro', + generation_config=gemini_generate_config, + safety_settings=gemini_safety_settings) + log(f"{NODE_NAME}: Request to gemini-pro...") + response = model.generate_content(first_step_prompt) + print(response) + ret_text = response.text + ret_text = ret_text[ret_text.rfind(':') + 1:] + ret_text = ret_text[ret_text.rfind('\n') + 1:] + # log(f"{NODE_NAME}: Text2Image Prompt is:\n\033[1;36m{ret_text}\033[m") + if is_contain_chinese(describe): + translate_prompt = (f"Please translate the text in parentheses into English:({describe})" + ) + response = model.generate_content(translate_prompt) + print(response) + ret_discribe = response.text + else: + ret_discribe = describe + + if image is not None: + if describe != "": + second_step_prompt = (f"You are creating a prompt for Stable Diffusion to generate an image. " + f"First step:Modify and polish the content in parentheses to match this photo," + f"but must keep '{describe}': ({ret_text}) " + f"Second step: Find objects that is similar in parentheses from the content of the first step" + f" and replace it with the content in parentheses: ({describe})" + f"Third step: Generate a Stable Diffusion text prompt for based on second step in at least {token_limit} words." + f"Only respond with the prompt itself, but embellish it." + ) + else: + second_step_prompt = (f"You are creating a prompt for Stable Diffusion to generate an image. " + f"First step: describe this image, " + f"polish and embellish it into text, discrete it in {token_limit} tokens." + f"Second step: Generate a Stable Diffusion text prompt for based on first step in at least {token_limit} words." + f"Only respond with the prompt itself, but embellish it." + ) + _image = tensor2pil(image).convert('RGB') + model = genai.GenerativeModel(api, + generation_config=gemini_generate_config, + safety_settings=gemini_safety_settings) + log(f"{NODE_NAME}: Request to {api}...") + response = model.generate_content([second_step_prompt, _image]) + print(response) + ret_text = response.text + ret_text = ret_text[ret_text.rfind(':') + 1:] + ret_text = ret_text.replace('(','').replace(')','') + if describe != "": + ret_text = f"((({ret_discribe}))), {ret_text}" + # log(f"{NODE_NAME}: Text2Image by ImageRefrence Prompt is:\n\033[1;36m{ret_text}\033[m") + log(f"{NODE_NAME}: Prompt is:\n\033[1;36m{ret_text}\033[m") + log(f"{NODE_NAME} Processed.", message_type='finish') + return (ret_text,) + +NODE_CLASS_MAPPINGS = { + "LayerUtility: PromptEmbellish": PromptEmbellish +} + +NODE_DISPLAY_NAME_MAPPINGS = { + "LayerUtility: PromptEmbellish": "LayerUtility: PromptEmbellish(Advance)" +} \ No newline at end of file diff --git a/py/prompt_tagger.py b/py/prompt_tagger.py new file mode 100644 index 0000000..69098bd --- /dev/null +++ b/py/prompt_tagger.py @@ -0,0 +1,79 @@ +# layerstyle advance + +from .imagefunc import * + +NODE_NAME = 'PromptTagger' + +class PromptTagger: + + def __init__(self): + pass + + @classmethod + def INPUT_TYPES(self): + api_list = ['gemini-1.5-flash', 'gemini-pro-vision'] + + return { + "required": { + "image": ("IMAGE", ), + "api": (api_list,), + "token_limit": ("INT", {"default": 80, "min": 2, "max": 1024, "step": 1}), + "exclude_word": ("STRING", {"default": ""}), + "replace_with_word": ("STRING", {"default": ""}), + }, + "optional": { + } + } + + RETURN_TYPES = ("STRING",) + RETURN_NAMES = ("text",) + FUNCTION = 'prompt_tagger' + CATEGORY = '😺dzNodes/LayerUtility/Prompt' + + def prompt_tagger(self, image, api, token_limit, exclude_word, replace_with_word): + import google.generativeai as genai + replace_with_word = replace_with_word.strip() + exclude_word = exclude_word.strip() + _image = tensor2pil(image).convert('RGB') + ret_text = "" + prompt = ("You are creating a prompt for Stable Diffusion to generate an image. " + "First step: describe this image, then put description into text. " + "Second step: generate a text prompt for based on first step. " + "Only respond with the prompt itself. ") + prompt = f"{prompt}As needed keep it under {token_limit} tokens." + + model = genai.GenerativeModel(api, + generation_config=gemini_generate_config, + safety_settings=gemini_safety_settings) + genai.configure(api_key=get_api_key('google_api_key'), transport='rest') + log(f"{NODE_NAME}: Request to {api}...") + response = model.generate_content([prompt, _image]) + ret_text = response.text + ret_text = ret_text[ret_text.rfind(':') + 1:] + log(f"{NODE_NAME}: Gemini response is:\n\033[1;36m{ret_text}\033[m") + if len(exclude_word) > 0: + if len(replace_with_word) > 0: + ret_text = replace_case(exclude_word, replace_with_word, ret_text) + refine_model = genai.GenerativeModel('gemini-pro', + generation_config=gemini_generate_config, + safety_settings=gemini_safety_settings + ) + response = refine_model.generate_content( + f'You are creating a prompt for Stable Diffusion to generate an image. ' + f'First step: Replace "{exclude_word}" and its synonyms with "{replace_with_word}" in the following text:{ret_text}' + f'Second step: Correct the grammar errors for based on first step.') + ret_text = response.text + if len(replace_with_word) > 0: + ret_text = ret_text.replace(replace_with_word, f"({replace_with_word})") + log(f"{NODE_NAME}: Tagger prompt is:\n\033[1;36m{ret_text}\033[m") + + log(f"{NODE_NAME} Processed.", message_type='finish') + return (ret_text,) + +NODE_CLASS_MAPPINGS = { + "LayerUtility: PromptTagger": PromptTagger +} + +NODE_DISPLAY_NAME_MAPPINGS = { + "LayerUtility: PromptTagger": "LayerUtility: PromptTagger(Advance)" +} \ No newline at end of file diff --git a/py/qrcode.py b/py/qrcode.py new file mode 100644 index 0000000..e500b5a --- /dev/null +++ b/py/qrcode.py @@ -0,0 +1,89 @@ +# layerstyle advance + +from .imagefunc import * + +class CreateQRCode: + + def __init__(self): + pass + + @classmethod + def INPUT_TYPES(self): + + return { + "required": { + "size": ("INT", {"default": 512, "min": 4, "max": 99999, "step": 1}), + "border": ("INT", {"default": 1, "min": 1, "max": 10, "step": 1}), + "text": ("STRING", {"default": "", "multiline": True}), + }, + "optional": { + } + } + + RETURN_TYPES = ("IMAGE", ) + RETURN_NAMES = ("image", ) + FUNCTION = 'create_qrcode' + CATEGORY = '😺dzNodes/LayerUtility/SystemIO' + + def create_qrcode(self, size, border, text): + import qrcode + qr = qrcode.QRCode( + version=1, + error_correction=qrcode.constants.ERROR_CORRECT_H, + box_size=20, + border=border, + ) + qr.add_data(text.encode('utf-8')) + qr.make(fit=True) + ret_image = qr.make_image(fill_color="black", back_color="white") + ret_image = ret_image.resize((size, size), Image.BICUBIC) + + return (pil2tensor(ret_image.convert("RGB")), ) + +class DecodeQRCode: + + def __init__(self): + pass + + @classmethod + def INPUT_TYPES(self): + + return { + "required": { + "image": ("IMAGE",), + "pre_blur": ("INT", {"default": 2, "min": 0, "max": 16, "step": 1}), + }, + "optional": { + } + } + + RETURN_TYPES = ("STRING", ) + RETURN_NAMES = ("string", ) + FUNCTION = 'decode_qrcode' + CATEGORY = '😺dzNodes/LayerUtility/SystemIO' + + def decode_qrcode(self, image, pre_blur): + ret_texts = [] + from pyzbar.pyzbar import decode + for i in image: + _image = torch.unsqueeze(i, 0) + _image = tensor2pil(_image) + if pre_blur: + _image = gaussian_blur(_image, pre_blur) + qrmessage = decode(_image) + if len(qrmessage) > 0: + ret_texts.append(qrmessage[0][0].decode('utf-8')) + else: + ret_texts.append("Cannot recognize QR") + + return (ret_texts, ) + +NODE_CLASS_MAPPINGS = { + "LayerUtility: CreateQRCode": CreateQRCode, + "LayerUtility: DecodeQRCode": DecodeQRCode +} + +NODE_DISPLAY_NAME_MAPPINGS = { + "LayerUtility: CreateQRCode": "LayerUtility: Create QRCode(Advance)", + "LayerUtility: DecodeQRCode": "LayerUtility: Decode QRCode(Advance)" +} \ No newline at end of file diff --git a/py/sam2/__init__.py b/py/sam2/__init__.py new file mode 100644 index 0000000..5277f46 --- /dev/null +++ b/py/sam2/__init__.py @@ -0,0 +1,5 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. diff --git a/py/sam2/automatic_mask_generator.py b/py/sam2/automatic_mask_generator.py new file mode 100644 index 0000000..e589132 --- /dev/null +++ b/py/sam2/automatic_mask_generator.py @@ -0,0 +1,434 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +# Adapted from https://github.com/facebookresearch/segment-anything/blob/main/segment_anything/automatic_mask_generator.py +from typing import Any, Dict, List, Optional, Tuple + +import numpy as np +import torch +from torchvision.ops.boxes import batched_nms, box_area # type: ignore + +from ..sam2.modeling.sam2_base import SAM2Base +from ..sam2.sam2_image_predictor import SAM2ImagePredictor +from ..sam2.utils.amg import ( + area_from_rle, + batch_iterator, + batched_mask_to_box, + box_xyxy_to_xywh, + build_all_layer_point_grids, + calculate_stability_score, + coco_encode_rle, + generate_crop_boxes, + is_box_near_crop_edge, + mask_to_rle_pytorch, + MaskData, + remove_small_regions, + rle_to_mask, + uncrop_boxes_xyxy, + uncrop_masks, + uncrop_points, +) + + +class SAM2AutomaticMaskGenerator: + def __init__( + self, + model: SAM2Base, + points_per_side: Optional[int] = 32, + points_per_batch: int = 64, + pred_iou_thresh: float = 0.8, + stability_score_thresh: float = 0.95, + stability_score_offset: float = 1.0, + mask_threshold: float = 0.0, + box_nms_thresh: float = 0.7, + crop_n_layers: int = 0, + crop_nms_thresh: float = 0.7, + crop_overlap_ratio: float = 512 / 1500, + crop_n_points_downscale_factor: int = 1, + point_grids: Optional[List[np.ndarray]] = None, + min_mask_region_area: int = 0, + output_mode: str = "binary_mask", + use_m2m: bool = False, + multimask_output: bool = True, + ) -> None: + """ + Using a SAM 2 model, generates masks for the entire image. + Generates a grid of point prompts over the image, then filters + low quality and duplicate masks. The default settings are chosen + for SAM 2 with a HieraL backbone. + + Arguments: + model (Sam): The SAM 2 model to use for mask prediction. + points_per_side (int or None): The number of points to be sampled + along one side of the image. The total number of points is + points_per_side**2. If None, 'point_grids' must provide explicit + point sampling. + points_per_batch (int): Sets the number of points run simultaneously + by the model. Higher numbers may be faster but use more GPU memory. + pred_iou_thresh (float): A filtering threshold in [0,1], using the + model's predicted mask quality. + stability_score_thresh (float): A filtering threshold in [0,1], using + the stability of the mask under changes to the cutoff used to binarize + the model's mask predictions. + stability_score_offset (float): The amount to shift the cutoff when + calculated the stability score. + mask_threshold (float): Threshold for binarizing the mask logits + box_nms_thresh (float): The box IoU cutoff used by non-maximal + suppression to filter duplicate masks. + crop_n_layers (int): If >0, mask prediction will be run again on + crops of the image. Sets the number of layers to run, where each + layer has 2**i_layer number of image crops. + crop_nms_thresh (float): The box IoU cutoff used by non-maximal + suppression to filter duplicate masks between different crops. + crop_overlap_ratio (float): Sets the degree to which crops overlap. + In the first crop layer, crops will overlap by this fraction of + the image length. Later layers with more crops scale down this overlap. + crop_n_points_downscale_factor (int): The number of points-per-side + sampled in layer n is scaled down by crop_n_points_downscale_factor**n. + point_grids (list(np.ndarray) or None): A list over explicit grids + of points used for sampling, normalized to [0,1]. The nth grid in the + list is used in the nth crop layer. Exclusive with points_per_side. + min_mask_region_area (int): If >0, postprocessing will be applied + to remove disconnected regions and holes in masks with area smaller + than min_mask_region_area. Requires opencv. + output_mode (str): The form masks are returned in. Can be 'binary_mask', + 'uncompressed_rle', or 'coco_rle'. 'coco_rle' requires pycocotools. + For large resolutions, 'binary_mask' may consume large amounts of + memory. + use_m2m (bool): Whether to add a one step refinement using previous mask predictions. + multimask_output (bool): Whether to output multimask at each point of the grid. + """ + + assert (points_per_side is None) != ( + point_grids is None + ), "Exactly one of points_per_side or point_grid must be provided." + if points_per_side is not None: + self.point_grids = build_all_layer_point_grids( + points_per_side, + crop_n_layers, + crop_n_points_downscale_factor, + ) + elif point_grids is not None: + self.point_grids = point_grids + else: + raise ValueError("Can't have both points_per_side and point_grid be None.") + + assert output_mode in [ + "binary_mask", + "uncompressed_rle", + "coco_rle", + ], f"Unknown output_mode {output_mode}." + if output_mode == "coco_rle": + try: + from pycocotools import mask as mask_utils # type: ignore # noqa: F401 + except ImportError as e: + print("Please install pycocotools") + raise e + + self.predictor = SAM2ImagePredictor( + model, + max_hole_area=min_mask_region_area, + max_sprinkle_area=min_mask_region_area, + ) + self.points_per_batch = points_per_batch + self.pred_iou_thresh = pred_iou_thresh + self.stability_score_thresh = stability_score_thresh + self.stability_score_offset = stability_score_offset + self.mask_threshold = mask_threshold + self.box_nms_thresh = box_nms_thresh + self.crop_n_layers = crop_n_layers + self.crop_nms_thresh = crop_nms_thresh + self.crop_overlap_ratio = crop_overlap_ratio + self.crop_n_points_downscale_factor = crop_n_points_downscale_factor + self.min_mask_region_area = min_mask_region_area + self.output_mode = output_mode + self.use_m2m = use_m2m + self.multimask_output = multimask_output + + @torch.no_grad() + def generate(self, image: np.ndarray) -> List[Dict[str, Any]]: + """ + Generates masks for the given image. + + Arguments: + image (np.ndarray): The image to generate masks for, in HWC uint8 format. + + Returns: + list(dict(str, any)): A list over records for masks. Each record is + a dict containing the following keys: + segmentation (dict(str, any) or np.ndarray): The mask. If + output_mode='binary_mask', is an array of shape HW. Otherwise, + is a dictionary containing the RLE. + bbox (list(float)): The box around the mask, in XYWH format. + area (int): The area in pixels of the mask. + predicted_iou (float): The model's own prediction of the mask's + quality. This is filtered by the pred_iou_thresh parameter. + point_coords (list(list(float))): The point coordinates input + to the model to generate this mask. + stability_score (float): A measure of the mask's quality. This + is filtered on using the stability_score_thresh parameter. + crop_box (list(float)): The crop of the image used to generate + the mask, given in XYWH format. + """ + + # Generate masks + mask_data = self._generate_masks(image) + + # Encode masks + if self.output_mode == "coco_rle": + mask_data["segmentations"] = [ + coco_encode_rle(rle) for rle in mask_data["rles"] + ] + elif self.output_mode == "binary_mask": + mask_data["segmentations"] = [rle_to_mask(rle) for rle in mask_data["rles"]] + else: + mask_data["segmentations"] = mask_data["rles"] + + # Write mask records + curr_anns = [] + for idx in range(len(mask_data["segmentations"])): + ann = { + "segmentation": mask_data["segmentations"][idx], + "area": area_from_rle(mask_data["rles"][idx]), + "bbox": box_xyxy_to_xywh(mask_data["boxes"][idx]).tolist(), + "predicted_iou": mask_data["iou_preds"][idx].item(), + "point_coords": [mask_data["points"][idx].tolist()], + "stability_score": mask_data["stability_score"][idx].item(), + "crop_box": box_xyxy_to_xywh(mask_data["crop_boxes"][idx]).tolist(), + } + curr_anns.append(ann) + + return curr_anns + + def _generate_masks(self, image: np.ndarray) -> MaskData: + orig_size = image.shape[:2] + crop_boxes, layer_idxs = generate_crop_boxes( + orig_size, self.crop_n_layers, self.crop_overlap_ratio + ) + + # Iterate over image crops + data = MaskData() + for crop_box, layer_idx in zip(crop_boxes, layer_idxs): + crop_data = self._process_crop(image, crop_box, layer_idx, orig_size) + data.cat(crop_data) + + # Remove duplicate masks between crops + if len(crop_boxes) > 1: + # Prefer masks from smaller crops + scores = 1 / box_area(data["crop_boxes"]) + scores = scores.to(data["boxes"].device) + keep_by_nms = batched_nms( + data["boxes"].float(), + scores, + torch.zeros_like(data["boxes"][:, 0]), # categories + iou_threshold=self.crop_nms_thresh, + ) + data.filter(keep_by_nms) + data.to_numpy() + return data + + def _process_crop( + self, + image: np.ndarray, + crop_box: List[int], + crop_layer_idx: int, + orig_size: Tuple[int, ...], + ) -> MaskData: + # Crop the image and calculate embeddings + x0, y0, x1, y1 = crop_box + cropped_im = image[y0:y1, x0:x1, :] + cropped_im_size = cropped_im.shape[:2] + self.predictor.set_image(cropped_im) + + # Get points for this crop + points_scale = np.array(cropped_im_size)[None, ::-1] + points_for_image = self.point_grids[crop_layer_idx] * points_scale + + # Generate masks for this crop in batches + data = MaskData() + for (points,) in batch_iterator(self.points_per_batch, points_for_image): + batch_data = self._process_batch( + points, cropped_im_size, crop_box, orig_size, normalize=True + ) + data.cat(batch_data) + del batch_data + self.predictor.reset_predictor() + + # Remove duplicates within this crop. + keep_by_nms = batched_nms( + data["boxes"].float(), + data["iou_preds"], + torch.zeros_like(data["boxes"][:, 0]), # categories + iou_threshold=self.box_nms_thresh, + ) + data.filter(keep_by_nms) + + # Return to the original image frame + data["boxes"] = uncrop_boxes_xyxy(data["boxes"], crop_box) + data["points"] = uncrop_points(data["points"], crop_box) + data["crop_boxes"] = torch.tensor([crop_box for _ in range(len(data["rles"]))]) + + return data + + def _process_batch( + self, + points: np.ndarray, + im_size: Tuple[int, ...], + crop_box: List[int], + orig_size: Tuple[int, ...], + normalize=False, + ) -> MaskData: + orig_h, orig_w = orig_size + + # Run model on this batch + points = torch.as_tensor(points, device=self.predictor.device) + in_points = self.predictor._transforms.transform_coords( + points, normalize=normalize, orig_hw=im_size + ) + in_labels = torch.ones( + in_points.shape[0], dtype=torch.int, device=in_points.device + ) + masks, iou_preds, low_res_masks = self.predictor._predict( + in_points[:, None, :], + in_labels[:, None], + multimask_output=self.multimask_output, + return_logits=True, + ) + + # Serialize predictions and store in MaskData + data = MaskData( + masks=masks.flatten(0, 1), + iou_preds=iou_preds.flatten(0, 1), + points=points.repeat_interleave(masks.shape[1], dim=0), + low_res_masks=low_res_masks.flatten(0, 1), + ) + del masks + + if not self.use_m2m: + # Filter by predicted IoU + if self.pred_iou_thresh > 0.0: + keep_mask = data["iou_preds"] > self.pred_iou_thresh + data.filter(keep_mask) + + # Calculate and filter by stability score + data["stability_score"] = calculate_stability_score( + data["masks"], self.mask_threshold, self.stability_score_offset + ) + if self.stability_score_thresh > 0.0: + keep_mask = data["stability_score"] >= self.stability_score_thresh + data.filter(keep_mask) + else: + # One step refinement using previous mask predictions + in_points = self.predictor._transforms.transform_coords( + data["points"], normalize=normalize, orig_hw=im_size + ) + labels = torch.ones( + in_points.shape[0], dtype=torch.int, device=in_points.device + ) + masks, ious = self.refine_with_m2m( + in_points, labels, data["low_res_masks"], self.points_per_batch + ) + data["masks"] = masks.squeeze(1) + data["iou_preds"] = ious.squeeze(1) + + if self.pred_iou_thresh > 0.0: + keep_mask = data["iou_preds"] > self.pred_iou_thresh + data.filter(keep_mask) + + data["stability_score"] = calculate_stability_score( + data["masks"], self.mask_threshold, self.stability_score_offset + ) + if self.stability_score_thresh > 0.0: + keep_mask = data["stability_score"] >= self.stability_score_thresh + data.filter(keep_mask) + + # Threshold masks and calculate boxes + data["masks"] = data["masks"] > self.mask_threshold + data["boxes"] = batched_mask_to_box(data["masks"]) + + # Filter boxes that touch crop boundaries + keep_mask = ~is_box_near_crop_edge( + data["boxes"], crop_box, [0, 0, orig_w, orig_h] + ) + if not torch.all(keep_mask): + data.filter(keep_mask) + + # Compress to RLE + data["masks"] = uncrop_masks(data["masks"], crop_box, orig_h, orig_w) + data["rles"] = mask_to_rle_pytorch(data["masks"]) + del data["masks"] + + return data + + @staticmethod + def postprocess_small_regions( + mask_data: MaskData, min_area: int, nms_thresh: float + ) -> MaskData: + """ + Removes small disconnected regions and holes in masks, then reruns + box NMS to remove any new duplicates. + + Edits mask_data in place. + + Requires open-cv as a dependency. + """ + if len(mask_data["rles"]) == 0: + return mask_data + + # Filter small disconnected regions and holes + new_masks = [] + scores = [] + for rle in mask_data["rles"]: + mask = rle_to_mask(rle) + + mask, changed = remove_small_regions(mask, min_area, mode="holes") + unchanged = not changed + mask, changed = remove_small_regions(mask, min_area, mode="islands") + unchanged = unchanged and not changed + + new_masks.append(torch.as_tensor(mask).unsqueeze(0)) + # Give score=0 to changed masks and score=1 to unchanged masks + # so NMS will prefer ones that didn't need postprocessing + scores.append(float(unchanged)) + + # Recalculate boxes and remove any new duplicates + masks = torch.cat(new_masks, dim=0) + boxes = batched_mask_to_box(masks) + keep_by_nms = batched_nms( + boxes.float(), + torch.as_tensor(scores), + torch.zeros_like(boxes[:, 0]), # categories + iou_threshold=nms_thresh, + ) + + # Only recalculate RLEs for masks that have changed + for i_mask in keep_by_nms: + if scores[i_mask] == 0.0: + mask_torch = masks[i_mask].unsqueeze(0) + mask_data["rles"][i_mask] = mask_to_rle_pytorch(mask_torch)[0] + mask_data["boxes"][i_mask] = boxes[i_mask] # update res directly + mask_data.filter(keep_by_nms) + + return mask_data + + def refine_with_m2m(self, points, point_labels, low_res_masks, points_per_batch): + new_masks = [] + new_iou_preds = [] + + for cur_points, cur_point_labels, low_res_mask in batch_iterator( + points_per_batch, points, point_labels, low_res_masks + ): + best_masks, best_iou_preds, _ = self.predictor._predict( + cur_points[:, None, :], + cur_point_labels[:, None], + mask_input=low_res_mask[:, None, :], + multimask_output=False, + return_logits=True, + ) + new_masks.append(best_masks) + new_iou_preds.append(best_iou_preds) + masks = torch.cat(new_masks, dim=0) + return masks, torch.cat(new_iou_preds, dim=0) diff --git a/py/sam2/modeling/__init__.py b/py/sam2/modeling/__init__.py new file mode 100644 index 0000000..5277f46 --- /dev/null +++ b/py/sam2/modeling/__init__.py @@ -0,0 +1,5 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. diff --git a/py/sam2/modeling/backbones/__init__.py b/py/sam2/modeling/backbones/__init__.py new file mode 100644 index 0000000..5277f46 --- /dev/null +++ b/py/sam2/modeling/backbones/__init__.py @@ -0,0 +1,5 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. diff --git a/py/sam2/modeling/backbones/hieradet.py b/py/sam2/modeling/backbones/hieradet.py new file mode 100644 index 0000000..217a054 --- /dev/null +++ b/py/sam2/modeling/backbones/hieradet.py @@ -0,0 +1,316 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +from functools import partial +from typing import List, Tuple, Union + +import torch +import torch.nn as nn +import torch.nn.functional as F +from iopath.common.file_io import g_pathmgr + +from ....sam2.modeling.backbones.utils import ( + PatchEmbed, + window_partition, + window_unpartition, +) + +from ....sam2.modeling.sam2_utils import DropPath, MLP + + +def do_pool(x: torch.Tensor, pool: nn.Module, norm: nn.Module = None) -> torch.Tensor: + if pool is None: + return x + # (B, H, W, C) -> (B, C, H, W) + x = x.permute(0, 3, 1, 2) + x = pool(x) + # (B, C, H', W') -> (B, H', W', C) + x = x.permute(0, 2, 3, 1) + if norm: + x = norm(x) + + return x + + +class MultiScaleAttention(nn.Module): + def __init__( + self, + dim: int, + dim_out: int, + num_heads: int, + q_pool: nn.Module = None, + ): + super().__init__() + + self.dim = dim + self.dim_out = dim_out + self.num_heads = num_heads + self.q_pool = q_pool + self.qkv = nn.Linear(dim, dim_out * 3) + self.proj = nn.Linear(dim_out, dim_out) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + B, H, W, _ = x.shape + # qkv with shape (B, H * W, 3, nHead, C) + qkv = self.qkv(x).reshape(B, H * W, 3, self.num_heads, -1) + # q, k, v with shape (B, H * W, nheads, C) + q, k, v = torch.unbind(qkv, 2) + + # Q pooling (for downsample at stage changes) + if self.q_pool: + q = do_pool(q.reshape(B, H, W, -1), self.q_pool) + H, W = q.shape[1:3] # downsampled shape + q = q.reshape(B, H * W, self.num_heads, -1) + + # Torch's SDPA expects [B, nheads, H*W, C] so we transpose + x = F.scaled_dot_product_attention( + q.transpose(1, 2), + k.transpose(1, 2), + v.transpose(1, 2), + ) + # Transpose back + x = x.transpose(1, 2) + x = x.reshape(B, H, W, -1) + + x = self.proj(x) + + return x + + +class MultiScaleBlock(nn.Module): + def __init__( + self, + dim: int, + dim_out: int, + num_heads: int, + mlp_ratio: float = 4.0, + drop_path: float = 0.0, + norm_layer: Union[nn.Module, str] = "LayerNorm", + q_stride: Tuple[int, int] = None, + act_layer: nn.Module = nn.GELU, + window_size: int = 0, + ): + super().__init__() + + if isinstance(norm_layer, str): + norm_layer = partial(getattr(nn, norm_layer), eps=1e-6) + + self.dim = dim + self.dim_out = dim_out + self.norm1 = norm_layer(dim) + + self.window_size = window_size + + self.pool, self.q_stride = None, q_stride + if self.q_stride: + self.pool = nn.MaxPool2d( + kernel_size=q_stride, stride=q_stride, ceil_mode=False + ) + + self.attn = MultiScaleAttention( + dim, + dim_out, + num_heads=num_heads, + q_pool=self.pool, + ) + self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity() + + self.norm2 = norm_layer(dim_out) + self.mlp = MLP( + dim_out, + int(dim_out * mlp_ratio), + dim_out, + num_layers=2, + activation=act_layer, + ) + + if dim != dim_out: + self.proj = nn.Linear(dim, dim_out) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + shortcut = x # B, H, W, C + x = self.norm1(x) + + # Skip connection + if self.dim != self.dim_out: + shortcut = do_pool(self.proj(x), self.pool) + + # Window partition + window_size = self.window_size + if window_size > 0: + H, W = x.shape[1], x.shape[2] + x, pad_hw = window_partition(x, window_size) + + # Window Attention + Q Pooling (if stage change) + x = self.attn(x) + if self.q_stride: + # Shapes have changed due to Q pooling + window_size = self.window_size // self.q_stride[0] + H, W = shortcut.shape[1:3] + + pad_h = (window_size - H % window_size) % window_size + pad_w = (window_size - W % window_size) % window_size + pad_hw = (H + pad_h, W + pad_w) + + # Reverse window partition + if self.window_size > 0: + x = window_unpartition(x, window_size, pad_hw, (H, W)) + + x = shortcut + self.drop_path(x) + # MLP + x = x + self.drop_path(self.mlp(self.norm2(x))) + return x + + +class Hiera(nn.Module): + """ + Reference: https://arxiv.org/abs/2306.00989 + """ + + def __init__( + self, + embed_dim: int = 96, # initial embed dim + num_heads: int = 1, # initial number of heads + drop_path_rate: float = 0.0, # stochastic depth + q_pool: int = 3, # number of q_pool stages + q_stride: Tuple[int, int] = (2, 2), # downsample stride bet. stages + stages: Tuple[int, ...] = (2, 3, 16, 3), # blocks per stage + dim_mul: float = 2.0, # dim_mul factor at stage shift + head_mul: float = 2.0, # head_mul factor at stage shift + window_pos_embed_bkg_spatial_size: Tuple[int, int] = (14, 14), + # window size per stage, when not using global att. + window_spec: Tuple[int, ...] = ( + 8, + 4, + 14, + 7, + ), + # global attn in these blocks + global_att_blocks: Tuple[int, ...] = ( + 12, + 16, + 20, + ), + weights_path=None, + return_interm_layers=True, # return feats from every stage + ): + super().__init__() + + assert len(stages) == len(window_spec) + self.window_spec = window_spec + + depth = sum(stages) + self.q_stride = q_stride + self.stage_ends = [sum(stages[:i]) - 1 for i in range(1, len(stages) + 1)] + assert 0 <= q_pool <= len(self.stage_ends[:-1]) + self.q_pool_blocks = [x + 1 for x in self.stage_ends[:-1]][:q_pool] + self.return_interm_layers = return_interm_layers + + self.patch_embed = PatchEmbed( + embed_dim=embed_dim, + ) + # Which blocks have global att? + self.global_att_blocks = global_att_blocks + + # Windowed positional embedding (https://arxiv.org/abs/2311.05613) + self.window_pos_embed_bkg_spatial_size = window_pos_embed_bkg_spatial_size + self.pos_embed = nn.Parameter( + torch.zeros(1, embed_dim, *self.window_pos_embed_bkg_spatial_size) + ) + self.pos_embed_window = nn.Parameter( + torch.zeros(1, embed_dim, self.window_spec[0], self.window_spec[0]) + ) + + dpr = [ + x.item() for x in torch.linspace(0, drop_path_rate, depth) + ] # stochastic depth decay rule + + cur_stage = 1 + self.blocks = nn.ModuleList() + + for i in range(depth): + dim_out = embed_dim + # lags by a block, so first block of + # next stage uses an initial window size + # of previous stage and final window size of current stage + window_size = self.window_spec[cur_stage - 1] + + if self.global_att_blocks is not None: + window_size = 0 if i in self.global_att_blocks else window_size + + if i - 1 in self.stage_ends: + dim_out = int(embed_dim * dim_mul) + num_heads = int(num_heads * head_mul) + cur_stage += 1 + + block = MultiScaleBlock( + dim=embed_dim, + dim_out=dim_out, + num_heads=num_heads, + drop_path=dpr[i], + q_stride=self.q_stride if i in self.q_pool_blocks else None, + window_size=window_size, + ) + + embed_dim = dim_out + self.blocks.append(block) + + self.channel_list = ( + [self.blocks[i].dim_out for i in self.stage_ends[::-1]] + if return_interm_layers + else [self.blocks[-1].dim_out] + ) + + if weights_path is not None: + with g_pathmgr.open(weights_path, "rb") as f: + chkpt = torch.load(f, map_location="cpu") + logging.info("loading Hiera", self.load_state_dict(chkpt, strict=False)) + + def _get_pos_embed(self, hw: Tuple[int, int]) -> torch.Tensor: + h, w = hw + window_embed = self.pos_embed_window + pos_embed = F.interpolate(self.pos_embed, size=(h, w), mode="bicubic") + pos_embed = pos_embed + window_embed.tile( + [x // y for x, y in zip(pos_embed.shape, window_embed.shape)] + ) + pos_embed = pos_embed.permute(0, 2, 3, 1) + return pos_embed + + def forward(self, x: torch.Tensor) -> List[torch.Tensor]: + x = self.patch_embed(x) + # x: (B, H, W, C) + + # Add pos embed + x = x + self._get_pos_embed(x.shape[1:3]) + + outputs = [] + for i, blk in enumerate(self.blocks): + x = blk(x) + if (i == self.stage_ends[-1]) or ( + i in self.stage_ends and self.return_interm_layers + ): + feats = x.permute(0, 3, 1, 2) + outputs.append(feats) + + return outputs + + def get_layer_id(self, layer_name): + # https://github.com/microsoft/unilm/blob/master/beit/optim_factory.py#L33 + num_layers = self.get_num_layers() + + if layer_name.find("rel_pos") != -1: + return num_layers + 1 + elif layer_name.find("pos_embed") != -1: + return 0 + elif layer_name.find("patch_embed") != -1: + return 0 + elif layer_name.find("blocks") != -1: + return int(layer_name.split("blocks")[1].split(".")[1]) + 1 + else: + return num_layers + 1 + + def get_num_layers(self) -> int: + return len(self.blocks) diff --git a/py/sam2/modeling/backbones/image_encoder.py b/py/sam2/modeling/backbones/image_encoder.py new file mode 100644 index 0000000..37e9266 --- /dev/null +++ b/py/sam2/modeling/backbones/image_encoder.py @@ -0,0 +1,134 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +from typing import List, Optional + +import torch +import torch.nn as nn +import torch.nn.functional as F + + +class ImageEncoder(nn.Module): + def __init__( + self, + trunk: nn.Module, + neck: nn.Module, + scalp: int = 0, + ): + super().__init__() + self.trunk = trunk + self.neck = neck + self.scalp = scalp + assert ( + self.trunk.channel_list == self.neck.backbone_channel_list + ), f"Channel dims of trunk and neck do not match. Trunk: {self.trunk.channel_list}, neck: {self.neck.backbone_channel_list}" + + def forward(self, sample: torch.Tensor): + # Forward through backbone + features, pos = self.neck(self.trunk(sample)) + if self.scalp > 0: + # Discard the lowest resolution features + features, pos = features[: -self.scalp], pos[: -self.scalp] + + src = features[-1] + output = { + "vision_features": src, + "vision_pos_enc": pos, + "backbone_fpn": features, + } + return output + + +class FpnNeck(nn.Module): + """ + A modified variant of Feature Pyramid Network (FPN) neck + (we remove output conv and also do bicubic interpolation similar to ViT + pos embed interpolation) + """ + + def __init__( + self, + position_encoding: nn.Module, + d_model: int, + backbone_channel_list: List[int], + kernel_size: int = 1, + stride: int = 1, + padding: int = 0, + fpn_interp_model: str = "bilinear", + fuse_type: str = "sum", + fpn_top_down_levels: Optional[List[int]] = None, + ): + """Initialize the neck + :param trunk: the backbone + :param position_encoding: the positional encoding to use + :param d_model: the dimension of the model + :param neck_norm: the normalization to use + """ + super().__init__() + self.position_encoding = position_encoding + self.convs = nn.ModuleList() + self.backbone_channel_list = backbone_channel_list + self.d_model = d_model + for dim in backbone_channel_list: + current = nn.Sequential() + current.add_module( + "conv", + nn.Conv2d( + in_channels=dim, + out_channels=d_model, + kernel_size=kernel_size, + stride=stride, + padding=padding, + ), + ) + + self.convs.append(current) + self.fpn_interp_model = fpn_interp_model + assert fuse_type in ["sum", "avg"] + self.fuse_type = fuse_type + + # levels to have top-down features in its outputs + # e.g. if fpn_top_down_levels is [2, 3], then only outputs of level 2 and 3 + # have top-down propagation, while outputs of level 0 and level 1 have only + # lateral features from the same backbone level. + if fpn_top_down_levels is None: + # default is to have top-down features on all levels + fpn_top_down_levels = range(len(self.convs)) + self.fpn_top_down_levels = list(fpn_top_down_levels) + + def forward(self, xs: List[torch.Tensor]): + + out = [None] * len(self.convs) + pos = [None] * len(self.convs) + assert len(xs) == len(self.convs) + # fpn forward pass + # see https://github.com/facebookresearch/detectron2/blob/main/detectron2/modeling/backbone/fpn.py + prev_features = None + # forward in top-down order (from low to high resolution) + n = len(self.convs) - 1 + for i in range(n, -1, -1): + x = xs[i] + lateral_features = self.convs[n - i](x) + if i in self.fpn_top_down_levels and prev_features is not None: + top_down_features = F.interpolate( + prev_features.to(dtype=torch.float32), + scale_factor=2.0, + mode=self.fpn_interp_model, + align_corners=( + None if self.fpn_interp_model == "nearest" else False + ), + antialias=False, + ) + prev_features = lateral_features + top_down_features + if self.fuse_type == "avg": + prev_features /= 2 + else: + prev_features = lateral_features + x_out = prev_features + out[i] = x_out + pos[i] = self.position_encoding(x_out).to(x_out.dtype) + + return out, pos diff --git a/py/sam2/modeling/backbones/utils.py b/py/sam2/modeling/backbones/utils.py new file mode 100644 index 0000000..32d55c7 --- /dev/null +++ b/py/sam2/modeling/backbones/utils.py @@ -0,0 +1,95 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +"""Some utilities for backbones, in particular for windowing""" + +from typing import Tuple + +import torch +import torch.nn as nn +import torch.nn.functional as F + + +def window_partition(x, window_size): + """ + Partition into non-overlapping windows with padding if needed. + Args: + x (tensor): input tokens with [B, H, W, C]. + window_size (int): window size. + Returns: + windows: windows after partition with [B * num_windows, window_size, window_size, C]. + (Hp, Wp): padded height and width before partition + """ + B, H, W, C = x.shape + + pad_h = (window_size - H % window_size) % window_size + pad_w = (window_size - W % window_size) % window_size + if pad_h > 0 or pad_w > 0: + x = F.pad(x, (0, 0, 0, pad_w, 0, pad_h)) + Hp, Wp = H + pad_h, W + pad_w + + x = x.view(B, Hp // window_size, window_size, Wp // window_size, window_size, C) + windows = ( + x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C) + ) + return windows, (Hp, Wp) + + +def window_unpartition(windows, window_size, pad_hw, hw): + """ + Window unpartition into original sequences and removing padding. + Args: + x (tensor): input tokens with [B * num_windows, window_size, window_size, C]. + window_size (int): window size. + pad_hw (Tuple): padded height and width (Hp, Wp). + hw (Tuple): original height and width (H, W) before padding. + Returns: + x: unpartitioned sequences with [B, H, W, C]. + """ + Hp, Wp = pad_hw + H, W = hw + B = windows.shape[0] // (Hp * Wp // window_size // window_size) + x = windows.view( + B, Hp // window_size, Wp // window_size, window_size, window_size, -1 + ) + x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, Hp, Wp, -1) + + if Hp > H or Wp > W: + x = x[:, :H, :W, :].contiguous() + return x + + +class PatchEmbed(nn.Module): + """ + Image to Patch Embedding. + """ + + def __init__( + self, + kernel_size: Tuple[int, ...] = (7, 7), + stride: Tuple[int, ...] = (4, 4), + padding: Tuple[int, ...] = (3, 3), + in_chans: int = 3, + embed_dim: int = 768, + ): + """ + Args: + kernel_size (Tuple): kernel size of the projection layer. + stride (Tuple): stride of the projection layer. + padding (Tuple): padding size of the projection layer. + in_chans (int): Number of input image channels. + embed_dim (int): embed_dim (int): Patch embedding dimension. + """ + super().__init__() + self.proj = nn.Conv2d( + in_chans, embed_dim, kernel_size=kernel_size, stride=stride, padding=padding + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x = self.proj(x) + # B C H W -> B H W C + x = x.permute(0, 2, 3, 1) + return x diff --git a/py/sam2/modeling/memory_attention.py b/py/sam2/modeling/memory_attention.py new file mode 100644 index 0000000..07788e5 --- /dev/null +++ b/py/sam2/modeling/memory_attention.py @@ -0,0 +1,169 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +from typing import Optional + +import torch +from torch import nn, Tensor + +from ...sam2.modeling.sam.transformer import RoPEAttention + +from ...sam2.modeling.sam2_utils import get_activation_fn, get_clones + + +class MemoryAttentionLayer(nn.Module): + + def __init__( + self, + activation: str, + cross_attention: nn.Module, + d_model: int, + dim_feedforward: int, + dropout: float, + pos_enc_at_attn: bool, + pos_enc_at_cross_attn_keys: bool, + pos_enc_at_cross_attn_queries: bool, + self_attention: nn.Module, + ): + super().__init__() + self.d_model = d_model + self.dim_feedforward = dim_feedforward + self.dropout_value = dropout + self.self_attn = self_attention + self.cross_attn_image = cross_attention + + # Implementation of Feedforward model + self.linear1 = nn.Linear(d_model, dim_feedforward) + self.dropout = nn.Dropout(dropout) + self.linear2 = nn.Linear(dim_feedforward, d_model) + + self.norm1 = nn.LayerNorm(d_model) + self.norm2 = nn.LayerNorm(d_model) + self.norm3 = nn.LayerNorm(d_model) + self.dropout1 = nn.Dropout(dropout) + self.dropout2 = nn.Dropout(dropout) + self.dropout3 = nn.Dropout(dropout) + + self.activation_str = activation + self.activation = get_activation_fn(activation) + + # Where to add pos enc + self.pos_enc_at_attn = pos_enc_at_attn + self.pos_enc_at_cross_attn_queries = pos_enc_at_cross_attn_queries + self.pos_enc_at_cross_attn_keys = pos_enc_at_cross_attn_keys + + def _forward_sa(self, tgt, query_pos): + # Self-Attention + tgt2 = self.norm1(tgt) + q = k = tgt2 + query_pos if self.pos_enc_at_attn else tgt2 + tgt2 = self.self_attn(q, k, v=tgt2) + tgt = tgt + self.dropout1(tgt2) + return tgt + + def _forward_ca(self, tgt, memory, query_pos, pos, num_k_exclude_rope=0): + kwds = {} + if num_k_exclude_rope > 0: + assert isinstance(self.cross_attn_image, RoPEAttention) + kwds = {"num_k_exclude_rope": num_k_exclude_rope} + + # Cross-Attention + tgt2 = self.norm2(tgt) + tgt2 = self.cross_attn_image( + q=tgt2 + query_pos if self.pos_enc_at_cross_attn_queries else tgt2, + k=memory + pos if self.pos_enc_at_cross_attn_keys else memory, + v=memory, + **kwds, + ) + tgt = tgt + self.dropout2(tgt2) + return tgt + + def forward( + self, + tgt, + memory, + pos: Optional[Tensor] = None, + query_pos: Optional[Tensor] = None, + num_k_exclude_rope: int = 0, + ) -> torch.Tensor: + + # Self-Attn, Cross-Attn + tgt = self._forward_sa(tgt, query_pos) + tgt = self._forward_ca(tgt, memory, query_pos, pos, num_k_exclude_rope) + # MLP + tgt2 = self.norm3(tgt) + tgt2 = self.linear2(self.dropout(self.activation(self.linear1(tgt2)))) + tgt = tgt + self.dropout3(tgt2) + return tgt + + +class MemoryAttention(nn.Module): + def __init__( + self, + d_model: int, + pos_enc_at_input: bool, + layer: nn.Module, + num_layers: int, + batch_first: bool = True, # Do layers expect batch first input? + ): + super().__init__() + self.d_model = d_model + self.layers = get_clones(layer, num_layers) + self.num_layers = num_layers + self.norm = nn.LayerNorm(d_model) + self.pos_enc_at_input = pos_enc_at_input + self.batch_first = batch_first + + def forward( + self, + curr: torch.Tensor, # self-attention inputs + memory: torch.Tensor, # cross-attention inputs + curr_pos: Optional[Tensor] = None, # pos_enc for self-attention inputs + memory_pos: Optional[Tensor] = None, # pos_enc for cross-attention inputs + num_obj_ptr_tokens: int = 0, # number of object pointer *tokens* + ): + if isinstance(curr, list): + assert isinstance(curr_pos, list) + assert len(curr) == len(curr_pos) == 1 + curr, curr_pos = ( + curr[0], + curr_pos[0], + ) + + assert ( + curr.shape[1] == memory.shape[1] + ), "Batch size must be the same for curr and memory" + + output = curr + if self.pos_enc_at_input and curr_pos is not None: + output = output + 0.1 * curr_pos + + if self.batch_first: + # Convert to batch first + output = output.transpose(0, 1) + curr_pos = curr_pos.transpose(0, 1) + memory = memory.transpose(0, 1) + memory_pos = memory_pos.transpose(0, 1) + + for layer in self.layers: + kwds = {} + if isinstance(layer.cross_attn_image, RoPEAttention): + kwds = {"num_k_exclude_rope": num_obj_ptr_tokens} + + output = layer( + tgt=output, + memory=memory, + pos=memory_pos, + query_pos=curr_pos, + **kwds, + ) + normed_output = self.norm(output) + + if self.batch_first: + # Convert back to seq first + normed_output = normed_output.transpose(0, 1) + curr_pos = curr_pos.transpose(0, 1) + + return normed_output diff --git a/py/sam2/modeling/memory_encoder.py b/py/sam2/modeling/memory_encoder.py new file mode 100644 index 0000000..1fbf1c8 --- /dev/null +++ b/py/sam2/modeling/memory_encoder.py @@ -0,0 +1,181 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import math +from typing import Tuple + +import torch +import torch.nn as nn +import torch.nn.functional as F + +from ...sam2.modeling.sam2_utils import DropPath, get_clones, LayerNorm2d + + +class MaskDownSampler(nn.Module): + """ + Progressively downsample a mask by total_stride, each time by stride. + Note that LayerNorm is applied per *token*, like in ViT. + + With each downsample (by a factor stride**2), channel capacity increases by the same factor. + In the end, we linearly project to embed_dim channels. + """ + + def __init__( + self, + embed_dim=256, + kernel_size=4, + stride=4, + padding=0, + total_stride=16, + activation=nn.GELU, + ): + super().__init__() + num_layers = int(math.log2(total_stride) // math.log2(stride)) + assert stride**num_layers == total_stride + self.encoder = nn.Sequential() + mask_in_chans, mask_out_chans = 1, 1 + for _ in range(num_layers): + mask_out_chans = mask_in_chans * (stride**2) + self.encoder.append( + nn.Conv2d( + mask_in_chans, + mask_out_chans, + kernel_size=kernel_size, + stride=stride, + padding=padding, + ) + ) + self.encoder.append(LayerNorm2d(mask_out_chans)) + self.encoder.append(activation()) + mask_in_chans = mask_out_chans + + self.encoder.append(nn.Conv2d(mask_out_chans, embed_dim, kernel_size=1)) + + def forward(self, x): + return self.encoder(x) + + +# Lightly adapted from ConvNext (https://github.com/facebookresearch/ConvNeXt) +class CXBlock(nn.Module): + r"""ConvNeXt Block. There are two equivalent implementations: + (1) DwConv -> LayerNorm (channels_first) -> 1x1 Conv -> GELU -> 1x1 Conv; all in (N, C, H, W) + (2) DwConv -> Permute to (N, H, W, C); LayerNorm (channels_last) -> Linear -> GELU -> Linear; Permute back + We use (2) as we find it slightly faster in PyTorch + + Args: + dim (int): Number of input channels. + drop_path (float): Stochastic depth rate. Default: 0.0 + layer_scale_init_value (float): Init value for Layer Scale. Default: 1e-6. + """ + + def __init__( + self, + dim, + kernel_size=7, + padding=3, + drop_path=0.0, + layer_scale_init_value=1e-6, + use_dwconv=True, + ): + super().__init__() + self.dwconv = nn.Conv2d( + dim, + dim, + kernel_size=kernel_size, + padding=padding, + groups=dim if use_dwconv else 1, + ) # depthwise conv + self.norm = LayerNorm2d(dim, eps=1e-6) + self.pwconv1 = nn.Linear( + dim, 4 * dim + ) # pointwise/1x1 convs, implemented with linear layers + self.act = nn.GELU() + self.pwconv2 = nn.Linear(4 * dim, dim) + self.gamma = ( + nn.Parameter(layer_scale_init_value * torch.ones((dim)), requires_grad=True) + if layer_scale_init_value > 0 + else None + ) + self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity() + + def forward(self, x): + input = x + x = self.dwconv(x) + x = self.norm(x) + x = x.permute(0, 2, 3, 1) # (N, C, H, W) -> (N, H, W, C) + x = self.pwconv1(x) + x = self.act(x) + x = self.pwconv2(x) + if self.gamma is not None: + x = self.gamma * x + x = x.permute(0, 3, 1, 2) # (N, H, W, C) -> (N, C, H, W) + + x = input + self.drop_path(x) + return x + + +class Fuser(nn.Module): + def __init__(self, layer, num_layers, dim=None, input_projection=False): + super().__init__() + self.proj = nn.Identity() + self.layers = get_clones(layer, num_layers) + + if input_projection: + assert dim is not None + self.proj = nn.Conv2d(dim, dim, kernel_size=1) + + def forward(self, x): + # normally x: (N, C, H, W) + x = self.proj(x) + for layer in self.layers: + x = layer(x) + return x + + +class MemoryEncoder(nn.Module): + def __init__( + self, + out_dim, + mask_downsampler, + fuser, + position_encoding, + in_dim=256, # in_dim of pix_feats + ): + super().__init__() + + self.mask_downsampler = mask_downsampler + + self.pix_feat_proj = nn.Conv2d(in_dim, in_dim, kernel_size=1) + self.fuser = fuser + self.position_encoding = position_encoding + self.out_proj = nn.Identity() + if out_dim != in_dim: + self.out_proj = nn.Conv2d(in_dim, out_dim, kernel_size=1) + + def forward( + self, + pix_feat: torch.Tensor, + masks: torch.Tensor, + skip_mask_sigmoid: bool = False, + ) -> Tuple[torch.Tensor, torch.Tensor]: + ## Process masks + # sigmoid, so that less domain shift from gt masks which are bool + if not skip_mask_sigmoid: + masks = F.sigmoid(masks) + masks = self.mask_downsampler(masks) + + ## Fuse pix_feats and downsampled masks + # in case the visual features are on CPU, cast them to CUDA + pix_feat = pix_feat.to(masks.device) + + x = self.pix_feat_proj(pix_feat) + x = x + masks + x = self.fuser(x) + x = self.out_proj(x) + + pos = self.position_encoding(x).to(x.dtype) + + return {"vision_features": x, "vision_pos_enc": [pos]} diff --git a/py/sam2/modeling/position_encoding.py b/py/sam2/modeling/position_encoding.py new file mode 100644 index 0000000..f4b57ae --- /dev/null +++ b/py/sam2/modeling/position_encoding.py @@ -0,0 +1,216 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import math +from typing import Any, Optional, Tuple + +import numpy as np + +import torch +from torch import nn + + +class PositionEmbeddingSine(nn.Module): + """ + This is a more standard version of the position embedding, very similar to the one + used by the Attention is all you need paper, generalized to work on images. + """ + + def __init__( + self, + num_pos_feats, + temperature: int = 10000, + normalize: bool = True, + scale: Optional[float] = None, + ): + super().__init__() + assert num_pos_feats % 2 == 0, "Expecting even model width" + self.num_pos_feats = num_pos_feats // 2 + self.temperature = temperature + self.normalize = normalize + if scale is not None and normalize is False: + raise ValueError("normalize should be True if scale is passed") + if scale is None: + scale = 2 * math.pi + self.scale = scale + + self.cache = {} + + def _encode_xy(self, x, y): + # The positions are expected to be normalized + assert len(x) == len(y) and x.ndim == y.ndim == 1 + x_embed = x * self.scale + y_embed = y * self.scale + + dim_t = torch.arange(self.num_pos_feats, dtype=torch.float32, device=x.device) + dim_t = self.temperature ** (2 * (dim_t // 2) / self.num_pos_feats) + + pos_x = x_embed[:, None] / dim_t + pos_y = y_embed[:, None] / dim_t + pos_x = torch.stack( + (pos_x[:, 0::2].sin(), pos_x[:, 1::2].cos()), dim=2 + ).flatten(1) + pos_y = torch.stack( + (pos_y[:, 0::2].sin(), pos_y[:, 1::2].cos()), dim=2 + ).flatten(1) + return pos_x, pos_y + + @torch.no_grad() + def encode_boxes(self, x, y, w, h): + pos_x, pos_y = self._encode_xy(x, y) + pos = torch.cat((pos_y, pos_x, h[:, None], w[:, None]), dim=1) + return pos + + encode = encode_boxes # Backwards compatibility + + @torch.no_grad() + def encode_points(self, x, y, labels): + (bx, nx), (by, ny), (bl, nl) = x.shape, y.shape, labels.shape + assert bx == by and nx == ny and bx == bl and nx == nl + pos_x, pos_y = self._encode_xy(x.flatten(), y.flatten()) + pos_x, pos_y = pos_x.reshape(bx, nx, -1), pos_y.reshape(by, ny, -1) + pos = torch.cat((pos_y, pos_x, labels[:, :, None]), dim=2) + return pos + + @torch.no_grad() + def forward(self, x: torch.Tensor): + cache_key = (x.shape[-2], x.shape[-1]) + if cache_key in self.cache: + return self.cache[cache_key][None].repeat(x.shape[0], 1, 1, 1) + y_embed = ( + torch.arange(1, x.shape[-2] + 1, dtype=torch.float32, device=x.device) + .view(1, -1, 1) + .repeat(x.shape[0], 1, x.shape[-1]) + ) + x_embed = ( + torch.arange(1, x.shape[-1] + 1, dtype=torch.float32, device=x.device) + .view(1, 1, -1) + .repeat(x.shape[0], x.shape[-2], 1) + ) + + if self.normalize: + eps = 1e-6 + y_embed = y_embed / (y_embed[:, -1:, :] + eps) * self.scale + x_embed = x_embed / (x_embed[:, :, -1:] + eps) * self.scale + + dim_t = torch.arange(self.num_pos_feats, dtype=torch.float32, device=x.device) + dim_t = self.temperature ** (2 * (dim_t // 2) / self.num_pos_feats) + + pos_x = x_embed[:, :, :, None] / dim_t + pos_y = y_embed[:, :, :, None] / dim_t + pos_x = torch.stack( + (pos_x[:, :, :, 0::2].sin(), pos_x[:, :, :, 1::2].cos()), dim=4 + ).flatten(3) + pos_y = torch.stack( + (pos_y[:, :, :, 0::2].sin(), pos_y[:, :, :, 1::2].cos()), dim=4 + ).flatten(3) + pos = torch.cat((pos_y, pos_x), dim=3).permute(0, 3, 1, 2) + self.cache[cache_key] = pos[0] + return pos + + +class PositionEmbeddingRandom(nn.Module): + """ + Positional encoding using random spatial frequencies. + """ + + def __init__(self, num_pos_feats: int = 64, scale: Optional[float] = None) -> None: + super().__init__() + if scale is None or scale <= 0.0: + scale = 1.0 + self.register_buffer( + "positional_encoding_gaussian_matrix", + scale * torch.randn((2, num_pos_feats)), + ) + + def _pe_encoding(self, coords: torch.Tensor) -> torch.Tensor: + """Positionally encode points that are normalized to [0,1].""" + # assuming coords are in [0, 1]^2 square and have d_1 x ... x d_n x 2 shape + coords = 2 * coords - 1 + coords = coords @ self.positional_encoding_gaussian_matrix + coords = 2 * np.pi * coords + # outputs d_1 x ... x d_n x C shape + return torch.cat([torch.sin(coords), torch.cos(coords)], dim=-1) + + def forward(self, size: Tuple[int, int]) -> torch.Tensor: + """Generate positional encoding for a grid of the specified size.""" + h, w = size + device: Any = self.positional_encoding_gaussian_matrix.device + grid = torch.ones((h, w), device=device, dtype=torch.float32) + y_embed = grid.cumsum(dim=0) - 0.5 + x_embed = grid.cumsum(dim=1) - 0.5 + y_embed = y_embed / h + x_embed = x_embed / w + + pe = self._pe_encoding(torch.stack([x_embed, y_embed], dim=-1)) + return pe.permute(2, 0, 1) # C x H x W + + def forward_with_coords( + self, coords_input: torch.Tensor, image_size: Tuple[int, int] + ) -> torch.Tensor: + """Positionally encode points that are not normalized to [0,1].""" + coords = coords_input.clone() + coords[:, :, 0] = coords[:, :, 0] / image_size[1] + coords[:, :, 1] = coords[:, :, 1] / image_size[0] + return self._pe_encoding(coords.to(torch.float)) # B x N x C + + +# Rotary Positional Encoding, adapted from: +# 1. https://github.com/meta-llama/codellama/blob/main/llama/model.py +# 2. https://github.com/naver-ai/rope-vit +# 3. https://github.com/lucidrains/rotary-embedding-torch + + +def init_t_xy(end_x: int, end_y: int): + t = torch.arange(end_x * end_y, dtype=torch.float32) + t_x = (t % end_x).float() + t_y = torch.div(t, end_x, rounding_mode="floor").float() + return t_x, t_y + + +def compute_axial_cis(dim: int, end_x: int, end_y: int, theta: float = 10000.0): + freqs_x = 1.0 / (theta ** (torch.arange(0, dim, 4)[: (dim // 4)].float() / dim)) + freqs_y = 1.0 / (theta ** (torch.arange(0, dim, 4)[: (dim // 4)].float() / dim)) + + t_x, t_y = init_t_xy(end_x, end_y) + freqs_x = torch.outer(t_x, freqs_x) + freqs_y = torch.outer(t_y, freqs_y) + freqs_cis_x = torch.polar(torch.ones_like(freqs_x), freqs_x) + freqs_cis_y = torch.polar(torch.ones_like(freqs_y), freqs_y) + return torch.cat([freqs_cis_x, freqs_cis_y], dim=-1) + + +def reshape_for_broadcast(freqs_cis: torch.Tensor, x: torch.Tensor): + ndim = x.ndim + assert 0 <= 1 < ndim + assert freqs_cis.shape == (x.shape[-2], x.shape[-1]) + shape = [d if i >= ndim - 2 else 1 for i, d in enumerate(x.shape)] + return freqs_cis.view(*shape) + + +def apply_rotary_enc( + xq: torch.Tensor, + xk: torch.Tensor, + freqs_cis: torch.Tensor, + repeat_freqs_k: bool = False, +): + xq_ = torch.view_as_complex(xq.float().reshape(*xq.shape[:-1], -1, 2)) + xk_ = ( + torch.view_as_complex(xk.float().reshape(*xk.shape[:-1], -1, 2)) + if xk.shape[-2] != 0 + else None + ) + freqs_cis = reshape_for_broadcast(freqs_cis, xq_) + xq_out = torch.view_as_real(xq_ * freqs_cis).flatten(3) + if xk_ is None: + # no keys to rotate, due to dropout + return xq_out.type_as(xq).to(xq.device), xk + # repeat freqs along seq_len dim to match k seq_len + if repeat_freqs_k: + r = xk_.shape[-2] // xq_.shape[-2] + freqs_cis = freqs_cis.repeat(*([1] * (freqs_cis.ndim - 2)), r, 1) + xk_out = torch.view_as_real(xk_ * freqs_cis).flatten(3) + return xq_out.type_as(xq).to(xq.device), xk_out.type_as(xk).to(xk.device) diff --git a/py/sam2/modeling/sam/__init__.py b/py/sam2/modeling/sam/__init__.py new file mode 100644 index 0000000..5277f46 --- /dev/null +++ b/py/sam2/modeling/sam/__init__.py @@ -0,0 +1,5 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. diff --git a/py/sam2/modeling/sam/mask_decoder.py b/py/sam2/modeling/sam/mask_decoder.py new file mode 100644 index 0000000..007d141 --- /dev/null +++ b/py/sam2/modeling/sam/mask_decoder.py @@ -0,0 +1,295 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +from typing import List, Optional, Tuple, Type + +import torch +from torch import nn + +from ....sam2.modeling.sam2_utils import LayerNorm2d, MLP + + +class MaskDecoder(nn.Module): + def __init__( + self, + *, + transformer_dim: int, + transformer: nn.Module, + num_multimask_outputs: int = 3, + activation: Type[nn.Module] = nn.GELU, + iou_head_depth: int = 3, + iou_head_hidden_dim: int = 256, + use_high_res_features: bool = False, + iou_prediction_use_sigmoid=False, + dynamic_multimask_via_stability=False, + dynamic_multimask_stability_delta=0.05, + dynamic_multimask_stability_thresh=0.98, + pred_obj_scores: bool = False, + pred_obj_scores_mlp: bool = False, + use_multimask_token_for_obj_ptr: bool = False, + ) -> None: + """ + Predicts masks given an image and prompt embeddings, using a + transformer architecture. + + Arguments: + transformer_dim (int): the channel dimension of the transformer + transformer (nn.Module): the transformer used to predict masks + num_multimask_outputs (int): the number of masks to predict + when disambiguating masks + activation (nn.Module): the type of activation to use when + upscaling masks + iou_head_depth (int): the depth of the MLP used to predict + mask quality + iou_head_hidden_dim (int): the hidden dimension of the MLP + used to predict mask quality + """ + super().__init__() + self.transformer_dim = transformer_dim + self.transformer = transformer + + self.num_multimask_outputs = num_multimask_outputs + + self.iou_token = nn.Embedding(1, transformer_dim) + self.num_mask_tokens = num_multimask_outputs + 1 + self.mask_tokens = nn.Embedding(self.num_mask_tokens, transformer_dim) + + self.pred_obj_scores = pred_obj_scores + if self.pred_obj_scores: + self.obj_score_token = nn.Embedding(1, transformer_dim) + self.use_multimask_token_for_obj_ptr = use_multimask_token_for_obj_ptr + + self.output_upscaling = nn.Sequential( + nn.ConvTranspose2d( + transformer_dim, transformer_dim // 4, kernel_size=2, stride=2 + ), + LayerNorm2d(transformer_dim // 4), + activation(), + nn.ConvTranspose2d( + transformer_dim // 4, transformer_dim // 8, kernel_size=2, stride=2 + ), + activation(), + ) + self.use_high_res_features = use_high_res_features + if use_high_res_features: + self.conv_s0 = nn.Conv2d( + transformer_dim, transformer_dim // 8, kernel_size=1, stride=1 + ) + self.conv_s1 = nn.Conv2d( + transformer_dim, transformer_dim // 4, kernel_size=1, stride=1 + ) + + self.output_hypernetworks_mlps = nn.ModuleList( + [ + MLP(transformer_dim, transformer_dim, transformer_dim // 8, 3) + for i in range(self.num_mask_tokens) + ] + ) + + self.iou_prediction_head = MLP( + transformer_dim, + iou_head_hidden_dim, + self.num_mask_tokens, + iou_head_depth, + sigmoid_output=iou_prediction_use_sigmoid, + ) + if self.pred_obj_scores: + self.pred_obj_score_head = nn.Linear(transformer_dim, 1) + if pred_obj_scores_mlp: + self.pred_obj_score_head = MLP(transformer_dim, transformer_dim, 1, 3) + + # When outputting a single mask, optionally we can dynamically fall back to the best + # multimask output token if the single mask output token gives low stability scores. + self.dynamic_multimask_via_stability = dynamic_multimask_via_stability + self.dynamic_multimask_stability_delta = dynamic_multimask_stability_delta + self.dynamic_multimask_stability_thresh = dynamic_multimask_stability_thresh + + def forward( + self, + image_embeddings: torch.Tensor, + image_pe: torch.Tensor, + sparse_prompt_embeddings: torch.Tensor, + dense_prompt_embeddings: torch.Tensor, + multimask_output: bool, + repeat_image: bool, + high_res_features: Optional[List[torch.Tensor]] = None, + ) -> Tuple[torch.Tensor, torch.Tensor]: + """ + Predict masks given image and prompt embeddings. + + Arguments: + image_embeddings (torch.Tensor): the embeddings from the image encoder + image_pe (torch.Tensor): positional encoding with the shape of image_embeddings + sparse_prompt_embeddings (torch.Tensor): the embeddings of the points and boxes + dense_prompt_embeddings (torch.Tensor): the embeddings of the mask inputs + multimask_output (bool): Whether to return multiple masks or a single + mask. + + Returns: + torch.Tensor: batched predicted masks + torch.Tensor: batched predictions of mask quality + torch.Tensor: batched SAM token for mask output + """ + masks, iou_pred, mask_tokens_out, object_score_logits = self.predict_masks( + image_embeddings=image_embeddings, + image_pe=image_pe, + sparse_prompt_embeddings=sparse_prompt_embeddings, + dense_prompt_embeddings=dense_prompt_embeddings, + repeat_image=repeat_image, + high_res_features=high_res_features, + ) + + # Select the correct mask or masks for output + if multimask_output: + masks = masks[:, 1:, :, :] + iou_pred = iou_pred[:, 1:] + elif self.dynamic_multimask_via_stability and not self.training: + masks, iou_pred = self._dynamic_multimask_via_stability(masks, iou_pred) + else: + masks = masks[:, 0:1, :, :] + iou_pred = iou_pred[:, 0:1] + + if multimask_output and self.use_multimask_token_for_obj_ptr: + sam_tokens_out = mask_tokens_out[:, 1:] # [b, 3, c] shape + else: + # Take the mask output token. Here we *always* use the token for single mask output. + # At test time, even if we track after 1-click (and using multimask_output=True), + # we still take the single mask token here. The rationale is that we always track + # after multiple clicks during training, so the past tokens seen during training + # are always the single mask token (and we'll let it be the object-memory token). + sam_tokens_out = mask_tokens_out[:, 0:1] # [b, 1, c] shape + + # Prepare output + return masks, iou_pred, sam_tokens_out, object_score_logits + + def predict_masks( + self, + image_embeddings: torch.Tensor, + image_pe: torch.Tensor, + sparse_prompt_embeddings: torch.Tensor, + dense_prompt_embeddings: torch.Tensor, + repeat_image: bool, + high_res_features: Optional[List[torch.Tensor]] = None, + ) -> Tuple[torch.Tensor, torch.Tensor]: + """Predicts masks. See 'forward' for more details.""" + # Concatenate output tokens + s = 0 + if self.pred_obj_scores: + output_tokens = torch.cat( + [ + self.obj_score_token.weight, + self.iou_token.weight, + self.mask_tokens.weight, + ], + dim=0, + ) + s = 1 + else: + output_tokens = torch.cat( + [self.iou_token.weight, self.mask_tokens.weight], dim=0 + ) + output_tokens = output_tokens.unsqueeze(0).expand( + sparse_prompt_embeddings.size(0), -1, -1 + ) + tokens = torch.cat((output_tokens, sparse_prompt_embeddings), dim=1) + + # Expand per-image data in batch direction to be per-mask + if repeat_image: + src = torch.repeat_interleave(image_embeddings, tokens.shape[0], dim=0) + else: + assert image_embeddings.shape[0] == tokens.shape[0] + src = image_embeddings + src = src + dense_prompt_embeddings + assert ( + image_pe.size(0) == 1 + ), "image_pe should have size 1 in batch dim (from `get_dense_pe()`)" + pos_src = torch.repeat_interleave(image_pe, tokens.shape[0], dim=0) + b, c, h, w = src.shape + + # Run the transformer + hs, src = self.transformer(src, pos_src, tokens) + iou_token_out = hs[:, s, :] + mask_tokens_out = hs[:, s + 1 : (s + 1 + self.num_mask_tokens), :] + + # Upscale mask embeddings and predict masks using the mask tokens + src = src.transpose(1, 2).view(b, c, h, w) + if not self.use_high_res_features: + upscaled_embedding = self.output_upscaling(src) + else: + dc1, ln1, act1, dc2, act2 = self.output_upscaling + feat_s0, feat_s1 = high_res_features + upscaled_embedding = act1(ln1(dc1(src) + feat_s1)) + upscaled_embedding = act2(dc2(upscaled_embedding) + feat_s0) + + hyper_in_list: List[torch.Tensor] = [] + for i in range(self.num_mask_tokens): + hyper_in_list.append( + self.output_hypernetworks_mlps[i](mask_tokens_out[:, i, :]) + ) + hyper_in = torch.stack(hyper_in_list, dim=1) + b, c, h, w = upscaled_embedding.shape + masks = (hyper_in @ upscaled_embedding.view(b, c, h * w)).view(b, -1, h, w) + + # Generate mask quality predictions + iou_pred = self.iou_prediction_head(iou_token_out) + if self.pred_obj_scores: + assert s == 1 + object_score_logits = self.pred_obj_score_head(hs[:, 0, :]) + else: + # Obj scores logits - default to 10.0, i.e. assuming the object is present, sigmoid(10)=1 + object_score_logits = 10.0 * iou_pred.new_ones(iou_pred.shape[0], 1) + + return masks, iou_pred, mask_tokens_out, object_score_logits + + def _get_stability_scores(self, mask_logits): + """ + Compute stability scores of the mask logits based on the IoU between upper and + lower thresholds. + """ + mask_logits = mask_logits.flatten(-2) + stability_delta = self.dynamic_multimask_stability_delta + area_i = torch.sum(mask_logits > stability_delta, dim=-1).float() + area_u = torch.sum(mask_logits > -stability_delta, dim=-1).float() + stability_scores = torch.where(area_u > 0, area_i / area_u, 1.0) + return stability_scores + + def _dynamic_multimask_via_stability(self, all_mask_logits, all_iou_scores): + """ + When outputting a single mask, if the stability score from the current single-mask + output (based on output token 0) falls below a threshold, we instead select from + multi-mask outputs (based on output token 1~3) the mask with the highest predicted + IoU score. This is intended to ensure a valid mask for both clicking and tracking. + """ + # The best mask from multimask output tokens (1~3) + multimask_logits = all_mask_logits[:, 1:, :, :] + multimask_iou_scores = all_iou_scores[:, 1:] + best_scores_inds = torch.argmax(multimask_iou_scores, dim=-1) + batch_inds = torch.arange( + multimask_iou_scores.size(0), device=all_iou_scores.device + ) + best_multimask_logits = multimask_logits[batch_inds, best_scores_inds] + best_multimask_logits = best_multimask_logits.unsqueeze(1) + best_multimask_iou_scores = multimask_iou_scores[batch_inds, best_scores_inds] + best_multimask_iou_scores = best_multimask_iou_scores.unsqueeze(1) + + # The mask from singlemask output token 0 and its stability score + singlemask_logits = all_mask_logits[:, 0:1, :, :] + singlemask_iou_scores = all_iou_scores[:, 0:1] + stability_scores = self._get_stability_scores(singlemask_logits) + is_stable = stability_scores >= self.dynamic_multimask_stability_thresh + + # Dynamically fall back to best multimask output upon low stability scores. + mask_logits_out = torch.where( + is_stable[..., None, None].expand_as(singlemask_logits), + singlemask_logits, + best_multimask_logits, + ) + iou_scores_out = torch.where( + is_stable.expand_as(singlemask_iou_scores), + singlemask_iou_scores, + best_multimask_iou_scores, + ) + return mask_logits_out, iou_scores_out diff --git a/py/sam2/modeling/sam/prompt_encoder.py b/py/sam2/modeling/sam/prompt_encoder.py new file mode 100644 index 0000000..fe125c7 --- /dev/null +++ b/py/sam2/modeling/sam/prompt_encoder.py @@ -0,0 +1,182 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +from typing import Optional, Tuple, Type + +import torch +from torch import nn + +from ....sam2.modeling.position_encoding import PositionEmbeddingRandom + +from ....sam2.modeling.sam2_utils import LayerNorm2d + + +class PromptEncoder(nn.Module): + def __init__( + self, + embed_dim: int, + image_embedding_size: Tuple[int, int], + input_image_size: Tuple[int, int], + mask_in_chans: int, + activation: Type[nn.Module] = nn.GELU, + ) -> None: + """ + Encodes prompts for input to SAM's mask decoder. + + Arguments: + embed_dim (int): The prompts' embedding dimension + image_embedding_size (tuple(int, int)): The spatial size of the + image embedding, as (H, W). + input_image_size (int): The padded size of the image as input + to the image encoder, as (H, W). + mask_in_chans (int): The number of hidden channels used for + encoding input masks. + activation (nn.Module): The activation to use when encoding + input masks. + """ + super().__init__() + self.embed_dim = embed_dim + self.input_image_size = input_image_size + self.image_embedding_size = image_embedding_size + self.pe_layer = PositionEmbeddingRandom(embed_dim // 2) + + self.num_point_embeddings: int = 4 # pos/neg point + 2 box corners + point_embeddings = [ + nn.Embedding(1, embed_dim) for i in range(self.num_point_embeddings) + ] + self.point_embeddings = nn.ModuleList(point_embeddings) + self.not_a_point_embed = nn.Embedding(1, embed_dim) + + self.mask_input_size = ( + 4 * image_embedding_size[0], + 4 * image_embedding_size[1], + ) + self.mask_downscaling = nn.Sequential( + nn.Conv2d(1, mask_in_chans // 4, kernel_size=2, stride=2), + LayerNorm2d(mask_in_chans // 4), + activation(), + nn.Conv2d(mask_in_chans // 4, mask_in_chans, kernel_size=2, stride=2), + LayerNorm2d(mask_in_chans), + activation(), + nn.Conv2d(mask_in_chans, embed_dim, kernel_size=1), + ) + self.no_mask_embed = nn.Embedding(1, embed_dim) + + def get_dense_pe(self) -> torch.Tensor: + """ + Returns the positional encoding used to encode point prompts, + applied to a dense set of points the shape of the image encoding. + + Returns: + torch.Tensor: Positional encoding with shape + 1x(embed_dim)x(embedding_h)x(embedding_w) + """ + return self.pe_layer(self.image_embedding_size).unsqueeze(0) + + def _embed_points( + self, + points: torch.Tensor, + labels: torch.Tensor, + pad: bool, + ) -> torch.Tensor: + """Embeds point prompts.""" + points = points + 0.5 # Shift to center of pixel + if pad: + padding_point = torch.zeros((points.shape[0], 1, 2), device=points.device) + padding_label = -torch.ones((labels.shape[0], 1), device=labels.device) + points = torch.cat([points, padding_point], dim=1) + labels = torch.cat([labels, padding_label], dim=1) + point_embedding = self.pe_layer.forward_with_coords( + points, self.input_image_size + ) + point_embedding[labels == -1] = 0.0 + point_embedding[labels == -1] += self.not_a_point_embed.weight + point_embedding[labels == 0] += self.point_embeddings[0].weight + point_embedding[labels == 1] += self.point_embeddings[1].weight + point_embedding[labels == 2] += self.point_embeddings[2].weight + point_embedding[labels == 3] += self.point_embeddings[3].weight + return point_embedding + + def _embed_boxes(self, boxes: torch.Tensor) -> torch.Tensor: + """Embeds box prompts.""" + boxes = boxes + 0.5 # Shift to center of pixel + coords = boxes.reshape(-1, 2, 2) + corner_embedding = self.pe_layer.forward_with_coords( + coords, self.input_image_size + ) + corner_embedding[:, 0, :] += self.point_embeddings[2].weight + corner_embedding[:, 1, :] += self.point_embeddings[3].weight + return corner_embedding + + def _embed_masks(self, masks: torch.Tensor) -> torch.Tensor: + """Embeds mask inputs.""" + mask_embedding = self.mask_downscaling(masks) + return mask_embedding + + def _get_batch_size( + self, + points: Optional[Tuple[torch.Tensor, torch.Tensor]], + boxes: Optional[torch.Tensor], + masks: Optional[torch.Tensor], + ) -> int: + """ + Gets the batch size of the output given the batch size of the input prompts. + """ + if points is not None: + return points[0].shape[0] + elif boxes is not None: + return boxes.shape[0] + elif masks is not None: + return masks.shape[0] + else: + return 1 + + def _get_device(self) -> torch.device: + return self.point_embeddings[0].weight.device + + def forward( + self, + points: Optional[Tuple[torch.Tensor, torch.Tensor]], + boxes: Optional[torch.Tensor], + masks: Optional[torch.Tensor], + ) -> Tuple[torch.Tensor, torch.Tensor]: + """ + Embeds different types of prompts, returning both sparse and dense + embeddings. + + Arguments: + points (tuple(torch.Tensor, torch.Tensor) or none): point coordinates + and labels to embed. + boxes (torch.Tensor or none): boxes to embed + masks (torch.Tensor or none): masks to embed + + Returns: + torch.Tensor: sparse embeddings for the points and boxes, with shape + BxNx(embed_dim), where N is determined by the number of input points + and boxes. + torch.Tensor: dense embeddings for the masks, in the shape + Bx(embed_dim)x(embed_H)x(embed_W) + """ + bs = self._get_batch_size(points, boxes, masks) + sparse_embeddings = torch.empty( + (bs, 0, self.embed_dim), device=self._get_device() + ) + if points is not None: + coords, labels = points + point_embeddings = self._embed_points(coords, labels, pad=(boxes is None)) + sparse_embeddings = torch.cat([sparse_embeddings, point_embeddings], dim=1) + if boxes is not None: + box_embeddings = self._embed_boxes(boxes) + sparse_embeddings = torch.cat([sparse_embeddings, box_embeddings], dim=1) + + if masks is not None: + dense_embeddings = self._embed_masks(masks) + else: + dense_embeddings = self.no_mask_embed.weight.reshape(1, -1, 1, 1).expand( + bs, -1, self.image_embedding_size[0], self.image_embedding_size[1] + ) + + return sparse_embeddings, dense_embeddings diff --git a/py/sam2/modeling/sam/transformer.py b/py/sam2/modeling/sam/transformer.py new file mode 100644 index 0000000..fb71606 --- /dev/null +++ b/py/sam2/modeling/sam/transformer.py @@ -0,0 +1,347 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import math +import warnings +from functools import partial +from typing import Tuple, Type + +import torch +import torch.nn.functional as F +from torch import nn, Tensor + +from ....sam2.modeling.position_encoding import apply_rotary_enc, compute_axial_cis +from ....sam2.modeling.sam2_utils import MLP + +from ....sam2.utils.misc import get_sdpa_settings +OLD_GPU, USE_FLASH_ATTN, MATH_KERNEL_ON = get_sdpa_settings() + +try: + from torch.nn.attention import SDPBackend, sdpa_kernel + backends = [] + if USE_FLASH_ATTN: + backends.append(SDPBackend.FLASH_ATTENTION) + if MATH_KERNEL_ON: + backends.append(SDPBackend.MATH) + if OLD_GPU: + backends.append(SDPBackend.EFFICIENT_ATTENTION) + OLD_TORCH = False +except: + OLD_TORCH = True + +warnings.simplefilter(action="ignore", category=FutureWarning) + +class TwoWayTransformer(nn.Module): + def __init__( + self, + depth: int, + embedding_dim: int, + num_heads: int, + mlp_dim: int, + activation: Type[nn.Module] = nn.ReLU, + attention_downsample_rate: int = 2, + ) -> None: + """ + A transformer decoder that attends to an input image using + queries whose positional embedding is supplied. + + Args: + depth (int): number of layers in the transformer + embedding_dim (int): the channel dimension for the input embeddings + num_heads (int): the number of heads for multihead attention. Must + divide embedding_dim + mlp_dim (int): the channel dimension internal to the MLP block + activation (nn.Module): the activation to use in the MLP block + """ + super().__init__() + self.depth = depth + self.embedding_dim = embedding_dim + self.num_heads = num_heads + self.mlp_dim = mlp_dim + self.layers = nn.ModuleList() + + for i in range(depth): + self.layers.append( + TwoWayAttentionBlock( + embedding_dim=embedding_dim, + num_heads=num_heads, + mlp_dim=mlp_dim, + activation=activation, + attention_downsample_rate=attention_downsample_rate, + skip_first_layer_pe=(i == 0), + ) + ) + + self.final_attn_token_to_image = Attention( + embedding_dim, num_heads, downsample_rate=attention_downsample_rate + ) + self.norm_final_attn = nn.LayerNorm(embedding_dim) + + def forward( + self, + image_embedding: Tensor, + image_pe: Tensor, + point_embedding: Tensor, + ) -> Tuple[Tensor, Tensor]: + """ + Args: + image_embedding (torch.Tensor): image to attend to. Should be shape + B x embedding_dim x h x w for any h and w. + image_pe (torch.Tensor): the positional encoding to add to the image. Must + have the same shape as image_embedding. + point_embedding (torch.Tensor): the embedding to add to the query points. + Must have shape B x N_points x embedding_dim for any N_points. + + Returns: + torch.Tensor: the processed point_embedding + torch.Tensor: the processed image_embedding + """ + # BxCxHxW -> BxHWxC == B x N_image_tokens x C + bs, c, h, w = image_embedding.shape + image_embedding = image_embedding.flatten(2).permute(0, 2, 1) + image_pe = image_pe.flatten(2).permute(0, 2, 1) + + # Prepare queries + queries = point_embedding + keys = image_embedding + + # Apply transformer blocks and final layernorm + for layer in self.layers: + queries, keys = layer( + queries=queries, + keys=keys, + query_pe=point_embedding, + key_pe=image_pe, + ) + + # Apply the final attention layer from the points to the image + q = queries + point_embedding + k = keys + image_pe + attn_out = self.final_attn_token_to_image(q=q, k=k, v=keys) + queries = queries + attn_out + queries = self.norm_final_attn(queries) + + return queries, keys + + +class TwoWayAttentionBlock(nn.Module): + def __init__( + self, + embedding_dim: int, + num_heads: int, + mlp_dim: int = 2048, + activation: Type[nn.Module] = nn.ReLU, + attention_downsample_rate: int = 2, + skip_first_layer_pe: bool = False, + ) -> None: + """ + A transformer block with four layers: (1) self-attention of sparse + inputs, (2) cross attention of sparse inputs to dense inputs, (3) mlp + block on sparse inputs, and (4) cross attention of dense inputs to sparse + inputs. + + Arguments: + embedding_dim (int): the channel dimension of the embeddings + num_heads (int): the number of heads in the attention layers + mlp_dim (int): the hidden dimension of the mlp block + activation (nn.Module): the activation of the mlp block + skip_first_layer_pe (bool): skip the PE on the first layer + """ + super().__init__() + self.self_attn = Attention(embedding_dim, num_heads) + self.norm1 = nn.LayerNorm(embedding_dim) + + self.cross_attn_token_to_image = Attention( + embedding_dim, num_heads, downsample_rate=attention_downsample_rate + ) + self.norm2 = nn.LayerNorm(embedding_dim) + + self.mlp = MLP( + embedding_dim, mlp_dim, embedding_dim, num_layers=2, activation=activation + ) + self.norm3 = nn.LayerNorm(embedding_dim) + + self.norm4 = nn.LayerNorm(embedding_dim) + self.cross_attn_image_to_token = Attention( + embedding_dim, num_heads, downsample_rate=attention_downsample_rate + ) + + self.skip_first_layer_pe = skip_first_layer_pe + + def forward( + self, queries: Tensor, keys: Tensor, query_pe: Tensor, key_pe: Tensor + ) -> Tuple[Tensor, Tensor]: + # Self attention block + if self.skip_first_layer_pe: + queries = self.self_attn(q=queries, k=queries, v=queries) + else: + q = queries + query_pe + attn_out = self.self_attn(q=q, k=q, v=queries) + queries = queries + attn_out + queries = self.norm1(queries) + + # Cross attention block, tokens attending to image embedding + q = queries + query_pe + k = keys + key_pe + attn_out = self.cross_attn_token_to_image(q=q, k=k, v=keys) + queries = queries + attn_out + queries = self.norm2(queries) + + # MLP block + mlp_out = self.mlp(queries) + queries = queries + mlp_out + queries = self.norm3(queries) + + # Cross attention block, image embedding attending to tokens + q = queries + query_pe + k = keys + key_pe + attn_out = self.cross_attn_image_to_token(q=k, k=q, v=queries) + keys = keys + attn_out + keys = self.norm4(keys) + + return queries, keys + + +class Attention(nn.Module): + """ + An attention layer that allows for downscaling the size of the embedding + after projection to queries, keys, and values. + """ + + def __init__( + self, + embedding_dim: int, + num_heads: int, + downsample_rate: int = 1, + dropout: float = 0.0, + kv_in_dim: int = None, + ) -> None: + super().__init__() + self.embedding_dim = embedding_dim + self.kv_in_dim = kv_in_dim if kv_in_dim is not None else embedding_dim + self.internal_dim = embedding_dim // downsample_rate + self.num_heads = num_heads + assert ( + self.internal_dim % num_heads == 0 + ), "num_heads must divide embedding_dim." + + self.q_proj = nn.Linear(embedding_dim, self.internal_dim) + self.k_proj = nn.Linear(self.kv_in_dim, self.internal_dim) + self.v_proj = nn.Linear(self.kv_in_dim, self.internal_dim) + self.out_proj = nn.Linear(self.internal_dim, embedding_dim) + + self.dropout_p = dropout + + def _separate_heads(self, x: Tensor, num_heads: int) -> Tensor: + b, n, c = x.shape + x = x.reshape(b, n, num_heads, c // num_heads) + return x.transpose(1, 2) # B x N_heads x N_tokens x C_per_head + + def _recombine_heads(self, x: Tensor) -> Tensor: + b, n_heads, n_tokens, c_per_head = x.shape + x = x.transpose(1, 2) + return x.reshape(b, n_tokens, n_heads * c_per_head) # B x N_tokens x C + + def forward(self, q: Tensor, k: Tensor, v: Tensor) -> Tensor: + # Input projections + q = self.q_proj(q) + k = self.k_proj(k) + v = self.v_proj(v) + + # Separate into heads + q = self._separate_heads(q, self.num_heads) + k = self._separate_heads(k, self.num_heads) + v = self._separate_heads(v, self.num_heads) + + dropout_p = self.dropout_p if self.training else 0.0 + # Attention + if not OLD_TORCH: + if not MATH_KERNEL_ON and OLD_GPU and dropout_p > 0.0: + backends.append(SDPBackend.MATH) + with sdpa_kernel(backends): + out = F.scaled_dot_product_attention(q, k, v, dropout_p=dropout_p) + else: + with torch.backends.cuda.sdp_kernel( + enable_flash=USE_FLASH_ATTN, + enable_math=(OLD_GPU and dropout_p > 0.0) or MATH_KERNEL_ON, + enable_mem_efficient=OLD_GPU, + ): + out = F.scaled_dot_product_attention(q, k, v, dropout_p=dropout_p) + out = self._recombine_heads(out) + out = self.out_proj(out) + + return out + + +class RoPEAttention(Attention): + """Attention with rotary position encoding.""" + + def __init__( + self, + *args, + rope_theta=10000.0, + # whether to repeat q rope to match k length + # this is needed for cross-attention to memories + rope_k_repeat=False, + feat_sizes=(32, 32), # [w, h] for stride 16 feats at 512 resolution + **kwargs, + ): + super().__init__(*args, **kwargs) + + self.compute_cis = partial( + compute_axial_cis, dim=self.internal_dim // self.num_heads, theta=rope_theta + ) + freqs_cis = self.compute_cis(end_x=feat_sizes[0], end_y=feat_sizes[1]) + self.freqs_cis = freqs_cis + self.rope_k_repeat = rope_k_repeat + + def forward( + self, q: Tensor, k: Tensor, v: Tensor, num_k_exclude_rope: int = 0 + ) -> Tensor: + # Input projections + q = self.q_proj(q) + k = self.k_proj(k) + v = self.v_proj(v) + + # Separate into heads + q = self._separate_heads(q, self.num_heads) + k = self._separate_heads(k, self.num_heads) + v = self._separate_heads(v, self.num_heads) + + # Apply rotary position encoding + w = h = math.sqrt(q.shape[-2]) + self.freqs_cis = self.freqs_cis.to(q.device) + if self.freqs_cis.shape[0] != q.shape[-2]: + self.freqs_cis = self.compute_cis(end_x=w, end_y=h).to(q.device) + if q.shape[-2] != k.shape[-2]: + assert self.rope_k_repeat + + num_k_rope = k.size(-2) - num_k_exclude_rope + q, k[:, :, :num_k_rope] = apply_rotary_enc( + q, + k[:, :, :num_k_rope], + freqs_cis=self.freqs_cis, + repeat_freqs_k=self.rope_k_repeat, + ) + + dropout_p = self.dropout_p if self.training else 0.0 + # Attention + if not OLD_TORCH: + if not MATH_KERNEL_ON and OLD_GPU and dropout_p > 0.0: + backends.append(SDPBackend.MATH) + with sdpa_kernel(backends): + out = F.scaled_dot_product_attention(q, k, v, dropout_p=dropout_p) + else: + with torch.backends.cuda.sdp_kernel( + enable_flash=USE_FLASH_ATTN, + enable_math=(OLD_GPU and dropout_p > 0.0) or MATH_KERNEL_ON, + enable_mem_efficient=OLD_GPU, + ): + out = F.scaled_dot_product_attention(q, k, v, dropout_p=dropout_p) + out = self._recombine_heads(out) + out = self.out_proj(out) + + return out diff --git a/py/sam2/modeling/sam2_base.py b/py/sam2/modeling/sam2_base.py new file mode 100644 index 0000000..078d63b --- /dev/null +++ b/py/sam2/modeling/sam2_base.py @@ -0,0 +1,907 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import torch +import torch.distributed +import torch.nn.functional as F + +from torch.nn.init import trunc_normal_ + +from ...sam2.modeling.sam.mask_decoder import MaskDecoder +from ...sam2.modeling.sam.prompt_encoder import PromptEncoder +from ...sam2.modeling.sam.transformer import TwoWayTransformer +from ...sam2.modeling.sam2_utils import get_1d_sine_pe, MLP, select_closest_cond_frames + +# a large negative value as a placeholder score for missing objects +NO_OBJ_SCORE = -1024.0 + + +class SAM2Base(torch.nn.Module): + def __init__( + self, + image_encoder, + memory_attention, + memory_encoder, + num_maskmem=7, # default 1 input frame + 6 previous frames + image_size=512, + backbone_stride=16, # stride of the image backbone output + sigmoid_scale_for_mem_enc=1.0, # scale factor for mask sigmoid prob + sigmoid_bias_for_mem_enc=0.0, # bias factor for mask sigmoid prob + # During evaluation, whether to binarize the sigmoid mask logits on interacted frames with clicks + binarize_mask_from_pts_for_mem_enc=False, + use_mask_input_as_output_without_sam=False, # on frames with mask input, whether to directly output the input mask without using a SAM prompt encoder + mask decoder + # The maximum number of conditioning frames to participate in the memory attention (-1 means no limit; if there are more conditioning frames than this limit, + # we only cross-attend to the temporally closest `max_cond_frames_in_attn` conditioning frames in the encoder when tracking each frame). This gives the model + # a temporal locality when handling a large number of annotated frames (since closer frames should be more important) and also avoids GPU OOM. + max_cond_frames_in_attn=-1, + # on the first frame, whether to directly add the no-memory embedding to the image feature + # (instead of using the transformer encoder) + directly_add_no_mem_embed=False, + # whether to use high-resolution feature maps in the SAM mask decoder + use_high_res_features_in_sam=False, + # whether to output multiple (3) masks for the first click on initial conditioning frames + multimask_output_in_sam=False, + # the minimum and maximum number of clicks to use multimask_output_in_sam (only relevant when `multimask_output_in_sam=True`; + # default is 1 for both, meaning that only the first click gives multimask output; also note that a box counts as two points) + multimask_min_pt_num=1, + multimask_max_pt_num=1, + # whether to also use multimask output for tracking (not just for the first click on initial conditioning frames; only relevant when `multimask_output_in_sam=True`) + multimask_output_for_tracking=False, + # Whether to use multimask tokens for obj ptr; Only relevant when both + # use_obj_ptrs_in_encoder=True and multimask_output_for_tracking=True + use_multimask_token_for_obj_ptr: bool = False, + # whether to use sigmoid to restrict ious prediction to [0-1] + iou_prediction_use_sigmoid=False, + # The memory bank's temporal stride during evaluation (i.e. the `r` parameter in XMem and Cutie; XMem and Cutie use r=5). + # For r>1, the (self.num_maskmem - 1) non-conditioning memory frames consist of + # (self.num_maskmem - 2) nearest frames from every r-th frames, plus the last frame. + memory_temporal_stride_for_eval=1, + # whether to apply non-overlapping constraints on the object masks in the memory encoder during evaluation (to avoid/alleviate superposing masks) + non_overlap_masks_for_mem_enc=False, + # whether to cross-attend to object pointers from other frames (based on SAM output tokens) in the encoder + use_obj_ptrs_in_encoder=False, + # the maximum number of object pointers from other frames in encoder cross attention (only relevant when `use_obj_ptrs_in_encoder=True`) + max_obj_ptrs_in_encoder=16, + # whether to add temporal positional encoding to the object pointers in the encoder (only relevant when `use_obj_ptrs_in_encoder=True`) + add_tpos_enc_to_obj_ptrs=True, + # whether to add an extra linear projection layer for the temporal positional encoding in the object pointers to avoid potential interference + # with spatial positional encoding (only relevant when both `use_obj_ptrs_in_encoder=True` and `add_tpos_enc_to_obj_ptrs=True`) + proj_tpos_enc_in_obj_ptrs=False, + # whether to use signed distance (instead of unsigned absolute distance) in the temporal positional encoding in the object pointers + # (only relevant when both `use_obj_ptrs_in_encoder=True` and `add_tpos_enc_to_obj_ptrs=True`) + use_signed_tpos_enc_to_obj_ptrs=False, + # whether to only attend to object pointers in the past (before the current frame) in the encoder during evaluation + # (only relevant when `use_obj_ptrs_in_encoder=True`; this might avoid pointer information too far in the future to distract the initial tracking) + only_obj_ptrs_in_the_past_for_eval=False, + # Whether to predict if there is an object in the frame + pred_obj_scores: bool = False, + # Whether to use an MLP to predict object scores + pred_obj_scores_mlp: bool = False, + # Only relevant if pred_obj_scores=True and use_obj_ptrs_in_encoder=True; + # Whether to have a fixed no obj pointer when there is no object present + # or to use it as an additive embedding with obj_ptr produced by decoder + fixed_no_obj_ptr: bool = False, + # Soft no object, i.e. mix in no_obj_ptr softly, + # hope to make recovery easier if there is a mistake and mitigate accumulation of errors + soft_no_obj_ptr: bool = False, + use_mlp_for_obj_ptr_proj: bool = False, + # add no obj embedding to spatial frames + no_obj_embed_spatial: bool = False, + # extra arguments used to construct the SAM mask decoder; if not None, it should be a dict of kwargs to be passed into `MaskDecoder` class. + sam_mask_decoder_extra_args=None, + compile_image_encoder: bool = False, + ): + super().__init__() + + # Part 1: the image backbone + self.image_encoder = image_encoder + # Use level 0, 1, 2 for high-res setting, or just level 2 for the default setting + self.use_high_res_features_in_sam = use_high_res_features_in_sam + self.num_feature_levels = 3 if use_high_res_features_in_sam else 1 + self.use_obj_ptrs_in_encoder = use_obj_ptrs_in_encoder + self.max_obj_ptrs_in_encoder = max_obj_ptrs_in_encoder + if use_obj_ptrs_in_encoder: + # A conv layer to downsample the mask prompt to stride 4 (the same stride as + # low-res SAM mask logits) and to change its scales from 0~1 to SAM logit scale, + # so that it can be fed into the SAM mask decoder to generate a pointer. + self.mask_downsample = torch.nn.Conv2d(1, 1, kernel_size=4, stride=4) + self.add_tpos_enc_to_obj_ptrs = add_tpos_enc_to_obj_ptrs + if proj_tpos_enc_in_obj_ptrs: + assert add_tpos_enc_to_obj_ptrs # these options need to be used together + self.proj_tpos_enc_in_obj_ptrs = proj_tpos_enc_in_obj_ptrs + self.use_signed_tpos_enc_to_obj_ptrs = use_signed_tpos_enc_to_obj_ptrs + self.only_obj_ptrs_in_the_past_for_eval = only_obj_ptrs_in_the_past_for_eval + + # Part 2: memory attention to condition current frame's visual features + # with memories (and obj ptrs) from past frames + self.memory_attention = memory_attention + self.hidden_dim = image_encoder.neck.d_model + + # Part 3: memory encoder for the previous frame's outputs + self.memory_encoder = memory_encoder + self.mem_dim = self.hidden_dim + if hasattr(self.memory_encoder, "out_proj") and hasattr( + self.memory_encoder.out_proj, "weight" + ): + # if there is compression of memories along channel dim + self.mem_dim = self.memory_encoder.out_proj.weight.shape[0] + self.num_maskmem = num_maskmem # Number of memories accessible + # Temporal encoding of the memories + self.maskmem_tpos_enc = torch.nn.Parameter( + torch.zeros(num_maskmem, 1, 1, self.mem_dim) + ) + trunc_normal_(self.maskmem_tpos_enc, std=0.02) + # a single token to indicate no memory embedding from previous frames + self.no_mem_embed = torch.nn.Parameter(torch.zeros(1, 1, self.hidden_dim)) + self.no_mem_pos_enc = torch.nn.Parameter(torch.zeros(1, 1, self.hidden_dim)) + trunc_normal_(self.no_mem_embed, std=0.02) + trunc_normal_(self.no_mem_pos_enc, std=0.02) + self.directly_add_no_mem_embed = directly_add_no_mem_embed + # Apply sigmoid to the output raw mask logits (to turn them from + # range (-inf, +inf) to range (0, 1)) before feeding them into the memory encoder + self.sigmoid_scale_for_mem_enc = sigmoid_scale_for_mem_enc + self.sigmoid_bias_for_mem_enc = sigmoid_bias_for_mem_enc + self.binarize_mask_from_pts_for_mem_enc = binarize_mask_from_pts_for_mem_enc + self.non_overlap_masks_for_mem_enc = non_overlap_masks_for_mem_enc + self.memory_temporal_stride_for_eval = memory_temporal_stride_for_eval + # On frames with mask input, whether to directly output the input mask without + # using a SAM prompt encoder + mask decoder + self.use_mask_input_as_output_without_sam = use_mask_input_as_output_without_sam + self.multimask_output_in_sam = multimask_output_in_sam + self.multimask_min_pt_num = multimask_min_pt_num + self.multimask_max_pt_num = multimask_max_pt_num + self.multimask_output_for_tracking = multimask_output_for_tracking + self.use_multimask_token_for_obj_ptr = use_multimask_token_for_obj_ptr + self.iou_prediction_use_sigmoid = iou_prediction_use_sigmoid + + # Part 4: SAM-style prompt encoder (for both mask and point inputs) + # and SAM-style mask decoder for the final mask output + self.image_size = image_size + self.backbone_stride = backbone_stride + self.sam_mask_decoder_extra_args = sam_mask_decoder_extra_args + self.pred_obj_scores = pred_obj_scores + self.pred_obj_scores_mlp = pred_obj_scores_mlp + self.fixed_no_obj_ptr = fixed_no_obj_ptr + self.soft_no_obj_ptr = soft_no_obj_ptr + if self.fixed_no_obj_ptr: + assert self.pred_obj_scores + assert self.use_obj_ptrs_in_encoder + if self.pred_obj_scores and self.use_obj_ptrs_in_encoder: + self.no_obj_ptr = torch.nn.Parameter(torch.zeros(1, self.hidden_dim)) + trunc_normal_(self.no_obj_ptr, std=0.02) + self.use_mlp_for_obj_ptr_proj = use_mlp_for_obj_ptr_proj + self.no_obj_embed_spatial = None + if no_obj_embed_spatial: + self.no_obj_embed_spatial = torch.nn.Parameter(torch.zeros(1, self.mem_dim)) + trunc_normal_(self.no_obj_embed_spatial, std=0.02) + + self._build_sam_heads() + self.max_cond_frames_in_attn = max_cond_frames_in_attn + + # Model compilation + if compile_image_encoder: + # Compile the forward function (not the full module) to allow loading checkpoints. + print( + "Image encoder compilation is enabled. First forward pass will be slow." + ) + self.image_encoder.forward = torch.compile( + self.image_encoder.forward, + mode="max-autotune", + fullgraph=True, + dynamic=False, + ) + + @property + def device(self): + return next(self.parameters()).device + + def forward(self, *args, **kwargs): + raise NotImplementedError( + "Please use the corresponding methods in SAM2VideoPredictor for inference or SAM2Train for training/fine-tuning" + "See notebooks/video_predictor_example.ipynb for an inference example." + ) + + def _build_sam_heads(self): + """Build SAM-style prompt encoder and mask decoder.""" + self.sam_prompt_embed_dim = self.hidden_dim + self.sam_image_embedding_size = self.image_size // self.backbone_stride + + # build PromptEncoder and MaskDecoder from SAM + # (their hyperparameters like `mask_in_chans=16` are from SAM code) + self.sam_prompt_encoder = PromptEncoder( + embed_dim=self.sam_prompt_embed_dim, + image_embedding_size=( + self.sam_image_embedding_size, + self.sam_image_embedding_size, + ), + input_image_size=(self.image_size, self.image_size), + mask_in_chans=16, + ) + self.sam_mask_decoder = MaskDecoder( + num_multimask_outputs=3, + transformer=TwoWayTransformer( + depth=2, + embedding_dim=self.sam_prompt_embed_dim, + mlp_dim=2048, + num_heads=8, + ), + transformer_dim=self.sam_prompt_embed_dim, + iou_head_depth=3, + iou_head_hidden_dim=256, + use_high_res_features=self.use_high_res_features_in_sam, + iou_prediction_use_sigmoid=self.iou_prediction_use_sigmoid, + pred_obj_scores=self.pred_obj_scores, + pred_obj_scores_mlp=self.pred_obj_scores_mlp, + use_multimask_token_for_obj_ptr=self.use_multimask_token_for_obj_ptr, + **(self.sam_mask_decoder_extra_args or {}), + ) + if self.use_obj_ptrs_in_encoder: + # a linear projection on SAM output tokens to turn them into object pointers + self.obj_ptr_proj = torch.nn.Linear(self.hidden_dim, self.hidden_dim) + if self.use_mlp_for_obj_ptr_proj: + self.obj_ptr_proj = MLP( + self.hidden_dim, self.hidden_dim, self.hidden_dim, 3 + ) + else: + self.obj_ptr_proj = torch.nn.Identity() + if self.proj_tpos_enc_in_obj_ptrs: + # a linear projection on temporal positional encoding in object pointers to + # avoid potential interference with spatial positional encoding + self.obj_ptr_tpos_proj = torch.nn.Linear(self.hidden_dim, self.mem_dim) + else: + self.obj_ptr_tpos_proj = torch.nn.Identity() + + def _forward_sam_heads( + self, + backbone_features, + point_inputs=None, + mask_inputs=None, + high_res_features=None, + multimask_output=False, + ): + """ + Forward SAM prompt encoders and mask heads. + + Inputs: + - backbone_features: image features of [B, C, H, W] shape + - point_inputs: a dictionary with "point_coords" and "point_labels", where + 1) "point_coords" has [B, P, 2] shape and float32 dtype and contains the + absolute pixel-unit coordinate in (x, y) format of the P input points + 2) "point_labels" has shape [B, P] and int32 dtype, where 1 means + positive clicks, 0 means negative clicks, and -1 means padding + - mask_inputs: a mask of [B, 1, H*16, W*16] shape, float or bool, with the + same spatial size as the image. + - high_res_features: either 1) None or 2) or a list of length 2 containing + two feature maps of [B, C, 4*H, 4*W] and [B, C, 2*H, 2*W] shapes respectively, + which will be used as high-resolution feature maps for SAM decoder. + - multimask_output: if it's True, we output 3 candidate masks and their 3 + corresponding IoU estimates, and if it's False, we output only 1 mask and + its corresponding IoU estimate. + + Outputs: + - low_res_multimasks: [B, M, H*4, W*4] shape (where M = 3 if + `multimask_output=True` and M = 1 if `multimask_output=False`), the SAM + output mask logits (before sigmoid) for the low-resolution masks, with 4x + the resolution (1/4 stride) of the input backbone_features. + - high_res_multimasks: [B, M, H*16, W*16] shape (where M = 3 + if `multimask_output=True` and M = 1 if `multimask_output=False`), + upsampled from the low-resolution masks, with shape size as the image + (stride is 1 pixel). + - ious, [B, M] shape, where (where M = 3 if `multimask_output=True` and M = 1 + if `multimask_output=False`), the estimated IoU of each output mask. + - low_res_masks: [B, 1, H*4, W*4] shape, the best mask in `low_res_multimasks`. + If `multimask_output=True`, it's the mask with the highest IoU estimate. + If `multimask_output=False`, it's the same as `low_res_multimasks`. + - high_res_masks: [B, 1, H*16, W*16] shape, the best mask in `high_res_multimasks`. + If `multimask_output=True`, it's the mask with the highest IoU estimate. + If `multimask_output=False`, it's the same as `high_res_multimasks`. + - obj_ptr: [B, C] shape, the object pointer vector for the output mask, extracted + based on the output token from the SAM mask decoder. + """ + B = backbone_features.size(0) + device = backbone_features.device + assert backbone_features.size(1) == self.sam_prompt_embed_dim + assert backbone_features.size(2) == self.sam_image_embedding_size + assert backbone_features.size(3) == self.sam_image_embedding_size + + # a) Handle point prompts + if point_inputs is not None: + sam_point_coords = point_inputs["point_coords"] + sam_point_labels = point_inputs["point_labels"] + assert sam_point_coords.size(0) == B and sam_point_labels.size(0) == B + else: + # If no points are provide, pad with an empty point (with label -1) + sam_point_coords = torch.zeros(B, 1, 2, device=device) + sam_point_labels = -torch.ones(B, 1, dtype=torch.int32, device=device) + + # b) Handle mask prompts + if mask_inputs is not None: + # If mask_inputs is provided, downsize it into low-res mask input if needed + # and feed it as a dense mask prompt into the SAM mask encoder + assert len(mask_inputs.shape) == 4 and mask_inputs.shape[:2] == (B, 1) + if mask_inputs.shape[-2:] != self.sam_prompt_encoder.mask_input_size: + sam_mask_prompt = F.interpolate( + mask_inputs.float(), + size=self.sam_prompt_encoder.mask_input_size, + align_corners=False, + mode="bilinear", + antialias=True, # use antialias for downsampling + ) + else: + sam_mask_prompt = mask_inputs + else: + # Otherwise, simply feed None (and SAM's prompt encoder will add + # a learned `no_mask_embed` to indicate no mask input in this case). + sam_mask_prompt = None + + sparse_embeddings, dense_embeddings = self.sam_prompt_encoder( + points=(sam_point_coords, sam_point_labels), + boxes=None, + masks=sam_mask_prompt, + ) + ( + low_res_multimasks, + ious, + sam_output_tokens, + object_score_logits, + ) = self.sam_mask_decoder( + image_embeddings=backbone_features, + image_pe=self.sam_prompt_encoder.get_dense_pe(), + sparse_prompt_embeddings=sparse_embeddings, + dense_prompt_embeddings=dense_embeddings, + multimask_output=multimask_output, + repeat_image=False, # the image is already batched + high_res_features=high_res_features, + ) + if self.pred_obj_scores: + is_obj_appearing = object_score_logits > 0 + + # Mask used for spatial memories is always a *hard* choice between obj and no obj, + # consistent with the actual mask prediction + low_res_multimasks = torch.where( + is_obj_appearing[:, None, None], + low_res_multimasks, + NO_OBJ_SCORE, + ) + + # convert masks from possibly bfloat16 (or float16) to float32 + # (older PyTorch versions before 2.1 don't support `interpolate` on bf16) + low_res_multimasks = low_res_multimasks.float() + high_res_multimasks = F.interpolate( + low_res_multimasks, + size=(self.image_size, self.image_size), + mode="bilinear", + align_corners=False, + ) + + sam_output_token = sam_output_tokens[:, 0] + if multimask_output: + # take the best mask prediction (with the highest IoU estimation) + best_iou_inds = torch.argmax(ious, dim=-1) + batch_inds = torch.arange(B, device=device) + low_res_masks = low_res_multimasks[batch_inds, best_iou_inds].unsqueeze(1) + high_res_masks = high_res_multimasks[batch_inds, best_iou_inds].unsqueeze(1) + if sam_output_tokens.size(1) > 1: + sam_output_token = sam_output_tokens[batch_inds, best_iou_inds] + else: + low_res_masks, high_res_masks = low_res_multimasks, high_res_multimasks + + # Extract object pointer from the SAM output token (with occlusion handling) + obj_ptr = self.obj_ptr_proj(sam_output_token) + if self.pred_obj_scores: + # Allow *soft* no obj ptr, unlike for masks + if self.soft_no_obj_ptr: + lambda_is_obj_appearing = object_score_logits.sigmoid() + else: + lambda_is_obj_appearing = is_obj_appearing.float() + + if self.fixed_no_obj_ptr: + obj_ptr = lambda_is_obj_appearing * obj_ptr + obj_ptr = obj_ptr + (1 - lambda_is_obj_appearing) * self.no_obj_ptr + + return ( + low_res_multimasks, + high_res_multimasks, + ious, + low_res_masks, + high_res_masks, + obj_ptr, + object_score_logits, + ) + + def _use_mask_as_output(self, backbone_features, high_res_features, mask_inputs): + """ + Directly turn binary `mask_inputs` into a output mask logits without using SAM. + (same input and output shapes as in _forward_sam_heads above). + """ + # Use -10/+10 as logits for neg/pos pixels (very close to 0/1 in prob after sigmoid). + out_scale, out_bias = 20.0, -10.0 # sigmoid(-10.0)=4.5398e-05 + mask_inputs_float = mask_inputs.float() + high_res_masks = mask_inputs_float * out_scale + out_bias + low_res_masks = F.interpolate( + high_res_masks, + size=(high_res_masks.size(-2) // 4, high_res_masks.size(-1) // 4), + align_corners=False, + mode="bilinear", + antialias=True, # use antialias for downsampling + ) + # a dummy IoU prediction of all 1's under mask input + ious = mask_inputs.new_ones(mask_inputs.size(0), 1).float() + if not self.use_obj_ptrs_in_encoder: + # all zeros as a dummy object pointer (of shape [B, C]) + obj_ptr = torch.zeros( + mask_inputs.size(0), self.hidden_dim, device=mask_inputs.device + ) + else: + # produce an object pointer using the SAM decoder from the mask input + _, _, _, _, _, obj_ptr, _ = self._forward_sam_heads( + backbone_features=backbone_features, + mask_inputs=self.mask_downsample(mask_inputs_float), + high_res_features=high_res_features, + ) + # In this method, we are treating mask_input as output, e.g. using it directly to create spatial mem; + # Below, we follow the same design axiom to use mask_input to decide if obj appears or not instead of relying + # on the object_scores from the SAM decoder. + is_obj_appearing = torch.any(mask_inputs.flatten(1).float() > 0.0, dim=1) + is_obj_appearing = is_obj_appearing[..., None] + lambda_is_obj_appearing = is_obj_appearing.float() + object_score_logits = out_scale * lambda_is_obj_appearing + out_bias + if self.pred_obj_scores: + if self.fixed_no_obj_ptr: + obj_ptr = lambda_is_obj_appearing * obj_ptr + obj_ptr = obj_ptr + (1 - lambda_is_obj_appearing) * self.no_obj_ptr + + return ( + low_res_masks, + high_res_masks, + ious, + low_res_masks, + high_res_masks, + obj_ptr, + object_score_logits, + ) + + def forward_image(self, img_batch: torch.Tensor): + """Get the image feature on the input batch.""" + backbone_out = self.image_encoder(img_batch) + if self.use_high_res_features_in_sam: + # precompute projected level 0 and level 1 features in SAM decoder + # to avoid running it again on every SAM click + backbone_out["backbone_fpn"][0] = self.sam_mask_decoder.conv_s0( + backbone_out["backbone_fpn"][0] + ) + backbone_out["backbone_fpn"][1] = self.sam_mask_decoder.conv_s1( + backbone_out["backbone_fpn"][1] + ) + return backbone_out + + def _prepare_backbone_features(self, backbone_out): + """Prepare and flatten visual features.""" + backbone_out = backbone_out.copy() + assert len(backbone_out["backbone_fpn"]) == len(backbone_out["vision_pos_enc"]) + assert len(backbone_out["backbone_fpn"]) >= self.num_feature_levels + + feature_maps = backbone_out["backbone_fpn"][-self.num_feature_levels :] + vision_pos_embeds = backbone_out["vision_pos_enc"][-self.num_feature_levels :] + + feat_sizes = [(x.shape[-2], x.shape[-1]) for x in vision_pos_embeds] + # flatten NxCxHxW to HWxNxC + vision_feats = [x.flatten(2).permute(2, 0, 1) for x in feature_maps] + vision_pos_embeds = [x.flatten(2).permute(2, 0, 1) for x in vision_pos_embeds] + + return backbone_out, vision_feats, vision_pos_embeds, feat_sizes + + def _prepare_memory_conditioned_features( + self, + frame_idx, + is_init_cond_frame, + current_vision_feats, + current_vision_pos_embeds, + feat_sizes, + output_dict, + num_frames, + track_in_reverse=False, # tracking in reverse time order (for demo usage) + ): + """Fuse the current frame's visual feature map with previous memory.""" + B = current_vision_feats[-1].size(1) # batch size on this frame + C = self.hidden_dim + H, W = feat_sizes[-1] # top-level (lowest-resolution) feature size + device = current_vision_feats[-1].device + # The case of `self.num_maskmem == 0` below is primarily used for reproducing SAM on images. + # In this case, we skip the fusion with any memory. + if self.num_maskmem == 0: # Disable memory and skip fusion + pix_feat = current_vision_feats[-1].permute(1, 2, 0).view(B, C, H, W) + return pix_feat + + num_obj_ptr_tokens = 0 + tpos_sign_mul = -1 if track_in_reverse else 1 + # Step 1: condition the visual features of the current frame on previous memories + if not is_init_cond_frame: + # Retrieve the memories encoded with the maskmem backbone + to_cat_memory, to_cat_memory_pos_embed = [], [] + # Add conditioning frames's output first (all cond frames have t_pos=0 for + # when getting temporal positional embedding below) + assert len(output_dict["cond_frame_outputs"]) > 0 + # Select a maximum number of temporally closest cond frames for cross attention + cond_outputs = output_dict["cond_frame_outputs"] + selected_cond_outputs, unselected_cond_outputs = select_closest_cond_frames( + frame_idx, cond_outputs, self.max_cond_frames_in_attn + ) + t_pos_and_prevs = [(0, out) for out in selected_cond_outputs.values()] + # Add last (self.num_maskmem - 1) frames before current frame for non-conditioning memory + # the earliest one has t_pos=1 and the latest one has t_pos=self.num_maskmem-1 + # We also allow taking the memory frame non-consecutively (with stride>1), in which case + # we take (self.num_maskmem - 2) frames among every stride-th frames plus the last frame. + stride = 1 if self.training else self.memory_temporal_stride_for_eval + for t_pos in range(1, self.num_maskmem): + t_rel = self.num_maskmem - t_pos # how many frames before current frame + if t_rel == 1: + # for t_rel == 1, we take the last frame (regardless of r) + if not track_in_reverse: + # the frame immediately before this frame (i.e. frame_idx - 1) + prev_frame_idx = frame_idx - t_rel + else: + # the frame immediately after this frame (i.e. frame_idx + 1) + prev_frame_idx = frame_idx + t_rel + else: + # for t_rel >= 2, we take the memory frame from every r-th frames + if not track_in_reverse: + # first find the nearest frame among every r-th frames before this frame + # for r=1, this would be (frame_idx - 2) + prev_frame_idx = ((frame_idx - 2) // stride) * stride + # then seek further among every r-th frames + prev_frame_idx = prev_frame_idx - (t_rel - 2) * stride + else: + # first find the nearest frame among every r-th frames after this frame + # for r=1, this would be (frame_idx + 2) + prev_frame_idx = -(-(frame_idx + 2) // stride) * stride + # then seek further among every r-th frames + prev_frame_idx = prev_frame_idx + (t_rel - 2) * stride + out = output_dict["non_cond_frame_outputs"].get(prev_frame_idx, None) + if out is None: + # If an unselected conditioning frame is among the last (self.num_maskmem - 1) + # frames, we still attend to it as if it's a non-conditioning frame. + out = unselected_cond_outputs.get(prev_frame_idx, None) + t_pos_and_prevs.append((t_pos, out)) + + for t_pos, prev in t_pos_and_prevs: + if prev is None: + continue # skip padding frames + # "maskmem_features" might have been offloaded to CPU in demo use cases, + # so we load it back to GPU (it's a no-op if it's already on GPU). + feats = prev["maskmem_features"].to(device, non_blocking=True) + to_cat_memory.append(feats.flatten(2).permute(2, 0, 1)) + # Spatial positional encoding (it might have been offloaded to CPU in eval) + maskmem_enc = prev["maskmem_pos_enc"][-1].to(device) + maskmem_enc = maskmem_enc.flatten(2).permute(2, 0, 1) + # Temporal positional encoding + maskmem_enc = ( + maskmem_enc + self.maskmem_tpos_enc[self.num_maskmem - t_pos - 1] + ) + to_cat_memory_pos_embed.append(maskmem_enc) + + # Construct the list of past object pointers + if self.use_obj_ptrs_in_encoder: + max_obj_ptrs_in_encoder = min(num_frames, self.max_obj_ptrs_in_encoder) + # First add those object pointers from selected conditioning frames + # (optionally, only include object pointers in the past during evaluation) + if not self.training and self.only_obj_ptrs_in_the_past_for_eval: + ptr_cond_outputs = { + t: out + for t, out in selected_cond_outputs.items() + if (t >= frame_idx if track_in_reverse else t <= frame_idx) + } + else: + ptr_cond_outputs = selected_cond_outputs + pos_and_ptrs = [ + # Temporal pos encoding contains how far away each pointer is from current frame + ( + ( + (frame_idx - t) * tpos_sign_mul + if self.use_signed_tpos_enc_to_obj_ptrs + else abs(frame_idx - t) + ), + out["obj_ptr"], + ) + for t, out in ptr_cond_outputs.items() + ] + # Add up to (max_obj_ptrs_in_encoder - 1) non-conditioning frames before current frame + for t_diff in range(1, max_obj_ptrs_in_encoder): + t = frame_idx + t_diff if track_in_reverse else frame_idx - t_diff + if t < 0 or (num_frames is not None and t >= num_frames): + break + out = output_dict["non_cond_frame_outputs"].get( + t, unselected_cond_outputs.get(t, None) + ) + if out is not None: + pos_and_ptrs.append((t_diff, out["obj_ptr"])) + # If we have at least one object pointer, add them to the across attention + if len(pos_and_ptrs) > 0: + pos_list, ptrs_list = zip(*pos_and_ptrs) + # stack object pointers along dim=0 into [ptr_seq_len, B, C] shape + obj_ptrs = torch.stack(ptrs_list, dim=0) + # a temporal positional embedding based on how far each object pointer is from + # the current frame (sine embedding normalized by the max pointer num). + if self.add_tpos_enc_to_obj_ptrs: + t_diff_max = max_obj_ptrs_in_encoder - 1 + tpos_dim = C if self.proj_tpos_enc_in_obj_ptrs else self.mem_dim + obj_pos = torch.tensor(pos_list, device=device) + obj_pos = get_1d_sine_pe(obj_pos / t_diff_max, dim=tpos_dim) + obj_pos = self.obj_ptr_tpos_proj(obj_pos) + obj_pos = obj_pos.unsqueeze(1).expand(-1, B, self.mem_dim) + else: + obj_pos = obj_ptrs.new_zeros(len(pos_list), B, self.mem_dim) + if self.mem_dim < C: + # split a pointer into (C // self.mem_dim) tokens for self.mem_dim < C + obj_ptrs = obj_ptrs.reshape( + -1, B, C // self.mem_dim, self.mem_dim + ) + obj_ptrs = obj_ptrs.permute(0, 2, 1, 3).flatten(0, 1) + obj_pos = obj_pos.repeat_interleave(C // self.mem_dim, dim=0) + to_cat_memory.append(obj_ptrs) + to_cat_memory_pos_embed.append(obj_pos) + num_obj_ptr_tokens = obj_ptrs.shape[0] + else: + num_obj_ptr_tokens = 0 + else: + # for initial conditioning frames, encode them without using any previous memory + if self.directly_add_no_mem_embed: + # directly add no-mem embedding (instead of using the transformer encoder) + pix_feat_with_mem = current_vision_feats[-1] + self.no_mem_embed + pix_feat_with_mem = pix_feat_with_mem.permute(1, 2, 0).view(B, C, H, W) + return pix_feat_with_mem + + # Use a dummy token on the first frame (to avoid empty memory input to tranformer encoder) + to_cat_memory = [self.no_mem_embed.expand(1, B, self.mem_dim)] + to_cat_memory_pos_embed = [self.no_mem_pos_enc.expand(1, B, self.mem_dim)] + + # Step 2: Concatenate the memories and forward through the transformer encoder + memory = torch.cat(to_cat_memory, dim=0) + memory_pos_embed = torch.cat(to_cat_memory_pos_embed, dim=0) + + pix_feat_with_mem = self.memory_attention( + curr=current_vision_feats, + curr_pos=current_vision_pos_embeds, + memory=memory, + memory_pos=memory_pos_embed, + num_obj_ptr_tokens=num_obj_ptr_tokens, + ) + # reshape the output (HW)BC => BCHW + pix_feat_with_mem = pix_feat_with_mem.permute(1, 2, 0).view(B, C, H, W) + return pix_feat_with_mem + + def _encode_new_memory( + self, + current_vision_feats, + feat_sizes, + pred_masks_high_res, + object_score_logits, + is_mask_from_pts, + ): + """Encode the current image and its prediction into a memory feature.""" + B = current_vision_feats[-1].size(1) # batch size on this frame + C = self.hidden_dim + H, W = feat_sizes[-1] # top-level (lowest-resolution) feature size + # top-level feature, (HW)BC => BCHW + pix_feat = current_vision_feats[-1].permute(1, 2, 0).view(B, C, H, W) + if self.non_overlap_masks_for_mem_enc and not self.training: + # optionally, apply non-overlapping constraints to the masks (it's applied + # in the batch dimension and should only be used during eval, where all + # the objects come from the same video under batch size 1). + pred_masks_high_res = self._apply_non_overlapping_constraints( + pred_masks_high_res + ) + # scale the raw mask logits with a temperature before applying sigmoid + binarize = self.binarize_mask_from_pts_for_mem_enc and is_mask_from_pts + if binarize and not self.training: + mask_for_mem = (pred_masks_high_res > 0).float() + else: + # apply sigmoid on the raw mask logits to turn them into range (0, 1) + mask_for_mem = torch.sigmoid(pred_masks_high_res) + # apply scale and bias terms to the sigmoid probabilities + if self.sigmoid_scale_for_mem_enc != 1.0: + mask_for_mem = mask_for_mem * self.sigmoid_scale_for_mem_enc + if self.sigmoid_bias_for_mem_enc != 0.0: + mask_for_mem = mask_for_mem + self.sigmoid_bias_for_mem_enc + maskmem_out = self.memory_encoder( + pix_feat, mask_for_mem, skip_mask_sigmoid=True # sigmoid already applied + ) + maskmem_features = maskmem_out["vision_features"] + maskmem_pos_enc = maskmem_out["vision_pos_enc"] + # add a no-object embedding to the spatial memory to indicate that the frame + # is predicted to be occluded (i.e. no object is appearing in the frame) + if self.no_obj_embed_spatial is not None: + is_obj_appearing = (object_score_logits > 0).float() + maskmem_features += ( + 1 - is_obj_appearing[..., None, None] + ) * self.no_obj_embed_spatial[..., None, None].expand( + *maskmem_features.shape + ) + + return maskmem_features, maskmem_pos_enc + + def _track_step( + self, + frame_idx, + is_init_cond_frame, + current_vision_feats, + current_vision_pos_embeds, + feat_sizes, + point_inputs, + mask_inputs, + output_dict, + num_frames, + track_in_reverse, + prev_sam_mask_logits, + ): + current_out = {"point_inputs": point_inputs, "mask_inputs": mask_inputs} + # High-resolution feature maps for the SAM head, reshape (HW)BC => BCHW + if len(current_vision_feats) > 1: + high_res_features = [ + x.permute(1, 2, 0).view(x.size(1), x.size(2), *s) + for x, s in zip(current_vision_feats[:-1], feat_sizes[:-1]) + ] + else: + high_res_features = None + if mask_inputs is not None and self.use_mask_input_as_output_without_sam: + # When use_mask_input_as_output_without_sam=True, we directly output the mask input + # (see it as a GT mask) without using a SAM prompt encoder + mask decoder. + pix_feat = current_vision_feats[-1].permute(1, 2, 0) + pix_feat = pix_feat.view(-1, self.hidden_dim, *feat_sizes[-1]) + sam_outputs = self._use_mask_as_output( + pix_feat, high_res_features, mask_inputs + ) + else: + # fused the visual feature with previous memory features in the memory bank + pix_feat = self._prepare_memory_conditioned_features( + frame_idx=frame_idx, + is_init_cond_frame=is_init_cond_frame, + current_vision_feats=current_vision_feats[-1:], + current_vision_pos_embeds=current_vision_pos_embeds[-1:], + feat_sizes=feat_sizes[-1:], + output_dict=output_dict, + num_frames=num_frames, + track_in_reverse=track_in_reverse, + ) + # apply SAM-style segmentation head + # here we might feed previously predicted low-res SAM mask logits into the SAM mask decoder, + # e.g. in demo where such logits come from earlier interaction instead of correction sampling + # (in this case, any `mask_inputs` shouldn't reach here as they are sent to _use_mask_as_output instead) + if prev_sam_mask_logits is not None: + assert point_inputs is not None and mask_inputs is None + mask_inputs = prev_sam_mask_logits + multimask_output = self._use_multimask(is_init_cond_frame, point_inputs) + sam_outputs = self._forward_sam_heads( + backbone_features=pix_feat, + point_inputs=point_inputs, + mask_inputs=mask_inputs, + high_res_features=high_res_features, + multimask_output=multimask_output, + ) + + return current_out, sam_outputs, high_res_features, pix_feat + + def _encode_memory_in_output( + self, + current_vision_feats, + feat_sizes, + point_inputs, + run_mem_encoder, + high_res_masks, + object_score_logits, + current_out, + ): + if run_mem_encoder and self.num_maskmem > 0: + high_res_masks_for_mem_enc = high_res_masks + maskmem_features, maskmem_pos_enc = self._encode_new_memory( + current_vision_feats=current_vision_feats, + feat_sizes=feat_sizes, + pred_masks_high_res=high_res_masks_for_mem_enc, + object_score_logits=object_score_logits, + is_mask_from_pts=(point_inputs is not None), + ) + current_out["maskmem_features"] = maskmem_features + current_out["maskmem_pos_enc"] = maskmem_pos_enc + else: + current_out["maskmem_features"] = None + current_out["maskmem_pos_enc"] = None + + def track_step( + self, + frame_idx, + is_init_cond_frame, + current_vision_feats, + current_vision_pos_embeds, + feat_sizes, + point_inputs, + mask_inputs, + output_dict, + num_frames, + track_in_reverse=False, # tracking in reverse time order (for demo usage) + # Whether to run the memory encoder on the predicted masks. Sometimes we might want + # to skip the memory encoder with `run_mem_encoder=False`. For example, + # in demo we might call `track_step` multiple times for each user click, + # and only encode the memory when the user finalizes their clicks. And in ablation + # settings like SAM training on static images, we don't need the memory encoder. + run_mem_encoder=True, + # The previously predicted SAM mask logits (which can be fed together with new clicks in demo). + prev_sam_mask_logits=None, + ): + current_out, sam_outputs, _, _ = self._track_step( + frame_idx, + is_init_cond_frame, + current_vision_feats, + current_vision_pos_embeds, + feat_sizes, + point_inputs, + mask_inputs, + output_dict, + num_frames, + track_in_reverse, + prev_sam_mask_logits, + ) + + ( + _, + _, + _, + low_res_masks, + high_res_masks, + obj_ptr, + object_score_logits, + ) = sam_outputs + + current_out["pred_masks"] = low_res_masks + current_out["pred_masks_high_res"] = high_res_masks + current_out["obj_ptr"] = obj_ptr + if not self.training: + # Only add this in inference (to avoid unused param in activation checkpointing; + # it's mainly used in the demo to encode spatial memories w/ consolidated masks) + current_out["object_score_logits"] = object_score_logits + + # Finally run the memory encoder on the predicted mask to encode + # it into a new memory feature (that can be used in future frames) + self._encode_memory_in_output( + current_vision_feats, + feat_sizes, + point_inputs, + run_mem_encoder, + high_res_masks, + object_score_logits, + current_out, + ) + + return current_out + + def _use_multimask(self, is_init_cond_frame, point_inputs): + """Whether to use multimask output in the SAM head.""" + num_pts = 0 if point_inputs is None else point_inputs["point_labels"].size(1) + multimask_output = ( + self.multimask_output_in_sam + and (is_init_cond_frame or self.multimask_output_for_tracking) + and (self.multimask_min_pt_num <= num_pts <= self.multimask_max_pt_num) + ) + return multimask_output + + def _apply_non_overlapping_constraints(self, pred_masks): + """ + Apply non-overlapping constraints to the object scores in pred_masks. Here we + keep only the highest scoring object at each spatial location in pred_masks. + """ + batch_size = pred_masks.size(0) + if batch_size == 1: + return pred_masks + + device = pred_masks.device + # "max_obj_inds": object index of the object with the highest score at each location + max_obj_inds = torch.argmax(pred_masks, dim=0, keepdim=True) + # "batch_obj_inds": object index of each object slice (along dim 0) in `pred_masks` + batch_obj_inds = torch.arange(batch_size, device=device)[:, None, None, None] + keep = max_obj_inds == batch_obj_inds + # suppress overlapping regions' scores below -10.0 so that the foreground regions + # don't overlap (here sigmoid(-10.0)=4.5398e-05) + pred_masks = torch.where(keep, pred_masks, torch.clamp(pred_masks, max=-10.0)) + return pred_masks diff --git a/py/sam2/modeling/sam2_utils.py b/py/sam2/modeling/sam2_utils.py new file mode 100644 index 0000000..ad00a76 --- /dev/null +++ b/py/sam2/modeling/sam2_utils.py @@ -0,0 +1,323 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + + +import copy +from typing import Tuple + +import numpy as np +import torch +import torch.nn as nn +import torch.nn.functional as F + +from ..utils.misc import mask_to_box + + +def select_closest_cond_frames(frame_idx, cond_frame_outputs, max_cond_frame_num): + """ + Select up to `max_cond_frame_num` conditioning frames from `cond_frame_outputs` + that are temporally closest to the current frame at `frame_idx`. Here, we take + - a) the closest conditioning frame before `frame_idx` (if any); + - b) the closest conditioning frame after `frame_idx` (if any); + - c) any other temporally closest conditioning frames until reaching a total + of `max_cond_frame_num` conditioning frames. + + Outputs: + - selected_outputs: selected items (keys & values) from `cond_frame_outputs`. + - unselected_outputs: items (keys & values) not selected in `cond_frame_outputs`. + """ + if max_cond_frame_num == -1 or len(cond_frame_outputs) <= max_cond_frame_num: + selected_outputs = cond_frame_outputs + unselected_outputs = {} + else: + assert max_cond_frame_num >= 2, "we should allow using 2+ conditioning frames" + selected_outputs = {} + + # the closest conditioning frame before `frame_idx` (if any) + idx_before = max((t for t in cond_frame_outputs if t < frame_idx), default=None) + if idx_before is not None: + selected_outputs[idx_before] = cond_frame_outputs[idx_before] + + # the closest conditioning frame after `frame_idx` (if any) + idx_after = min((t for t in cond_frame_outputs if t >= frame_idx), default=None) + if idx_after is not None: + selected_outputs[idx_after] = cond_frame_outputs[idx_after] + + # add other temporally closest conditioning frames until reaching a total + # of `max_cond_frame_num` conditioning frames. + num_remain = max_cond_frame_num - len(selected_outputs) + inds_remain = sorted( + (t for t in cond_frame_outputs if t not in selected_outputs), + key=lambda x: abs(x - frame_idx), + )[:num_remain] + selected_outputs.update((t, cond_frame_outputs[t]) for t in inds_remain) + unselected_outputs = { + t: v for t, v in cond_frame_outputs.items() if t not in selected_outputs + } + + return selected_outputs, unselected_outputs + + +def get_1d_sine_pe(pos_inds, dim, temperature=10000): + """ + Get 1D sine positional embedding as in the original Transformer paper. + """ + pe_dim = dim // 2 + dim_t = torch.arange(pe_dim, dtype=torch.float32, device=pos_inds.device) + dim_t = temperature ** (2 * (dim_t // 2) / pe_dim) + + pos_embed = pos_inds.unsqueeze(-1) / dim_t + pos_embed = torch.cat([pos_embed.sin(), pos_embed.cos()], dim=-1) + return pos_embed + + +def get_activation_fn(activation): + """Return an activation function given a string""" + if activation == "relu": + return F.relu + if activation == "gelu": + return F.gelu + if activation == "glu": + return F.glu + raise RuntimeError(f"activation should be relu/gelu, not {activation}.") + + +def get_clones(module, N): + return nn.ModuleList([copy.deepcopy(module) for i in range(N)]) + + +class DropPath(nn.Module): + # adapted from https://github.com/huggingface/pytorch-image-models/blob/main/timm/layers/drop.py + def __init__(self, drop_prob=0.0, scale_by_keep=True): + super(DropPath, self).__init__() + self.drop_prob = drop_prob + self.scale_by_keep = scale_by_keep + + def forward(self, x): + if self.drop_prob == 0.0 or not self.training: + return x + keep_prob = 1 - self.drop_prob + shape = (x.shape[0],) + (1,) * (x.ndim - 1) + random_tensor = x.new_empty(shape).bernoulli_(keep_prob) + if keep_prob > 0.0 and self.scale_by_keep: + random_tensor.div_(keep_prob) + return x * random_tensor + + +# Lightly adapted from +# https://github.com/facebookresearch/MaskFormer/blob/main/mask_former/modeling/transformer/transformer_predictor.py # noqa +class MLP(nn.Module): + def __init__( + self, + input_dim: int, + hidden_dim: int, + output_dim: int, + num_layers: int, + activation: nn.Module = nn.ReLU, + sigmoid_output: bool = False, + ) -> None: + super().__init__() + self.num_layers = num_layers + h = [hidden_dim] * (num_layers - 1) + self.layers = nn.ModuleList( + nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim]) + ) + self.sigmoid_output = sigmoid_output + self.act = activation() + + def forward(self, x): + for i, layer in enumerate(self.layers): + x = self.act(layer(x)) if i < self.num_layers - 1 else layer(x) + if self.sigmoid_output: + x = F.sigmoid(x) + return x + + +# From https://github.com/facebookresearch/detectron2/blob/main/detectron2/layers/batch_norm.py # noqa +# Itself from https://github.com/facebookresearch/ConvNeXt/blob/d1fa8f6fef0a165b27399986cc2bdacc92777e40/models/convnext.py#L119 # noqa +class LayerNorm2d(nn.Module): + def __init__(self, num_channels: int, eps: float = 1e-6) -> None: + super().__init__() + self.weight = nn.Parameter(torch.ones(num_channels)) + self.bias = nn.Parameter(torch.zeros(num_channels)) + self.eps = eps + + def forward(self, x: torch.Tensor) -> torch.Tensor: + u = x.mean(1, keepdim=True) + s = (x - u).pow(2).mean(1, keepdim=True) + x = (x - u) / torch.sqrt(s + self.eps) + x = self.weight[:, None, None] * x + self.bias[:, None, None] + return x + + +def sample_box_points( + masks: torch.Tensor, + noise: float = 0.1, # SAM default + noise_bound: int = 20, # SAM default + top_left_label: int = 2, + bottom_right_label: int = 3, +) -> Tuple[np.array, np.array]: + """ + Sample a noised version of the top left and bottom right corners of a given `bbox` + + Inputs: + - masks: [B, 1, H,W] boxes, dtype=torch.Tensor + - noise: noise as a fraction of box width and height, dtype=float + - noise_bound: maximum amount of noise (in pure pixesl), dtype=int + + Returns: + - box_coords: [B, num_pt, 2], contains (x, y) coordinates of top left and bottom right box corners, dtype=torch.float + - box_labels: [B, num_pt], label 2 is reserverd for top left and 3 for bottom right corners, dtype=torch.int32 + """ + device = masks.device + box_coords = mask_to_box(masks) + B, _, H, W = masks.shape + box_labels = torch.tensor( + [top_left_label, bottom_right_label], dtype=torch.int, device=device + ).repeat(B) + if noise > 0.0: + if not isinstance(noise_bound, torch.Tensor): + noise_bound = torch.tensor(noise_bound, device=device) + bbox_w = box_coords[..., 2] - box_coords[..., 0] + bbox_h = box_coords[..., 3] - box_coords[..., 1] + max_dx = torch.min(bbox_w * noise, noise_bound) + max_dy = torch.min(bbox_h * noise, noise_bound) + box_noise = 2 * torch.rand(B, 1, 4, device=device) - 1 + box_noise = box_noise * torch.stack((max_dx, max_dy, max_dx, max_dy), dim=-1) + + box_coords = box_coords + box_noise + img_bounds = ( + torch.tensor([W, H, W, H], device=device) - 1 + ) # uncentered pixel coords + box_coords.clamp_(torch.zeros_like(img_bounds), img_bounds) # In place clamping + + box_coords = box_coords.reshape(-1, 2, 2) # always 2 points + box_labels = box_labels.reshape(-1, 2) + return box_coords, box_labels + + +def sample_random_points_from_errors(gt_masks, pred_masks, num_pt=1): + """ + Sample `num_pt` random points (along with their labels) independently from the error regions. + + Inputs: + - gt_masks: [B, 1, H_im, W_im] masks, dtype=torch.bool + - pred_masks: [B, 1, H_im, W_im] masks, dtype=torch.bool or None + - num_pt: int, number of points to sample independently for each of the B error maps + + Outputs: + - points: [B, num_pt, 2], dtype=torch.float, contains (x, y) coordinates of each sampled point + - labels: [B, num_pt], dtype=torch.int32, where 1 means positive clicks and 0 means + negative clicks + """ + if pred_masks is None: # if pred_masks is not provided, treat it as empty + pred_masks = torch.zeros_like(gt_masks) + assert gt_masks.dtype == torch.bool and gt_masks.size(1) == 1 + assert pred_masks.dtype == torch.bool and pred_masks.shape == gt_masks.shape + assert num_pt >= 0 + + B, _, H_im, W_im = gt_masks.shape + device = gt_masks.device + + # false positive region, a new point sampled in this region should have + # negative label to correct the FP error + fp_masks = ~gt_masks & pred_masks + # false negative region, a new point sampled in this region should have + # positive label to correct the FN error + fn_masks = gt_masks & ~pred_masks + # whether the prediction completely match the ground-truth on each mask + all_correct = torch.all((gt_masks == pred_masks).flatten(2), dim=2) + all_correct = all_correct[..., None, None] + + # channel 0 is FP map, while channel 1 is FN map + pts_noise = torch.rand(B, num_pt, H_im, W_im, 2, device=device) + # sample a negative new click from FP region or a positive new click + # from FN region, depend on where the maximum falls, + # and in case the predictions are all correct (no FP or FN), we just + # sample a negative click from the background region + pts_noise[..., 0] *= fp_masks | (all_correct & ~gt_masks) + pts_noise[..., 1] *= fn_masks + pts_idx = pts_noise.flatten(2).argmax(dim=2) + labels = (pts_idx % 2).to(torch.int32) + pts_idx = pts_idx // 2 + pts_x = pts_idx % W_im + pts_y = pts_idx // W_im + points = torch.stack([pts_x, pts_y], dim=2).to(torch.float) + return points, labels + + +def sample_one_point_from_error_center(gt_masks, pred_masks, padding=True): + """ + Sample 1 random point (along with its label) from the center of each error region, + that is, the point with the largest distance to the boundary of each error region. + This is the RITM sampling method from https://github.com/saic-vul/ritm_interactive_segmentation/blob/master/isegm/inference/clicker.py + + Inputs: + - gt_masks: [B, 1, H_im, W_im] masks, dtype=torch.bool + - pred_masks: [B, 1, H_im, W_im] masks, dtype=torch.bool or None + - padding: if True, pad with boundary of 1 px for distance transform + + Outputs: + - points: [B, 1, 2], dtype=torch.float, contains (x, y) coordinates of each sampled point + - labels: [B, 1], dtype=torch.int32, where 1 means positive clicks and 0 means negative clicks + """ + import cv2 + + if pred_masks is None: + pred_masks = torch.zeros_like(gt_masks) + assert gt_masks.dtype == torch.bool and gt_masks.size(1) == 1 + assert pred_masks.dtype == torch.bool and pred_masks.shape == gt_masks.shape + + B, _, _, W_im = gt_masks.shape + device = gt_masks.device + + # false positive region, a new point sampled in this region should have + # negative label to correct the FP error + fp_masks = ~gt_masks & pred_masks + # false negative region, a new point sampled in this region should have + # positive label to correct the FN error + fn_masks = gt_masks & ~pred_masks + + fp_masks = fp_masks.cpu().numpy() + fn_masks = fn_masks.cpu().numpy() + points = torch.zeros(B, 1, 2, dtype=torch.float) + labels = torch.ones(B, 1, dtype=torch.int32) + for b in range(B): + fn_mask = fn_masks[b, 0] + fp_mask = fp_masks[b, 0] + if padding: + fn_mask = np.pad(fn_mask, ((1, 1), (1, 1)), "constant") + fp_mask = np.pad(fp_mask, ((1, 1), (1, 1)), "constant") + # compute the distance of each point in FN/FP region to its boundary + fn_mask_dt = cv2.distanceTransform(fn_mask.astype(np.uint8), cv2.DIST_L2, 0) + fp_mask_dt = cv2.distanceTransform(fp_mask.astype(np.uint8), cv2.DIST_L2, 0) + if padding: + fn_mask_dt = fn_mask_dt[1:-1, 1:-1] + fp_mask_dt = fp_mask_dt[1:-1, 1:-1] + + # take the point in FN/FP region with the largest distance to its boundary + fn_mask_dt_flat = fn_mask_dt.reshape(-1) + fp_mask_dt_flat = fp_mask_dt.reshape(-1) + fn_argmax = np.argmax(fn_mask_dt_flat) + fp_argmax = np.argmax(fp_mask_dt_flat) + is_positive = fn_mask_dt_flat[fn_argmax] > fp_mask_dt_flat[fp_argmax] + pt_idx = fn_argmax if is_positive else fp_argmax + points[b, 0, 0] = pt_idx % W_im # x + points[b, 0, 1] = pt_idx // W_im # y + labels[b, 0] = int(is_positive) + + points = points.to(device) + labels = labels.to(device) + return points, labels + + +def get_next_point(gt_masks, pred_masks, method): + if method == "uniform": + return sample_random_points_from_errors(gt_masks, pred_masks) + elif method == "center": + return sample_one_point_from_error_center(gt_masks, pred_masks) + else: + raise ValueError(f"unknown sampling method {method}") diff --git a/py/sam2/sam2_configs/__init__.py b/py/sam2/sam2_configs/__init__.py new file mode 100644 index 0000000..5277f46 --- /dev/null +++ b/py/sam2/sam2_configs/__init__.py @@ -0,0 +1,5 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. diff --git a/py/sam2/sam2_configs/sam2.1_hiera_b+.yaml b/py/sam2/sam2_configs/sam2.1_hiera_b+.yaml new file mode 100644 index 0000000..cbee3cf --- /dev/null +++ b/py/sam2/sam2_configs/sam2.1_hiera_b+.yaml @@ -0,0 +1,116 @@ +# @package _global_ + +# Model +model: + _target_: sam2.modeling.sam2_base.SAM2Base + image_encoder: + _target_: sam2.modeling.backbones.image_encoder.ImageEncoder + scalp: 1 + trunk: + _target_: sam2.modeling.backbones.hieradet.Hiera + embed_dim: 112 + num_heads: 2 + neck: + _target_: sam2.modeling.backbones.image_encoder.FpnNeck + position_encoding: + _target_: sam2.modeling.position_encoding.PositionEmbeddingSine + num_pos_feats: 256 + normalize: true + scale: null + temperature: 10000 + d_model: 256 + backbone_channel_list: [896, 448, 224, 112] + fpn_top_down_levels: [2, 3] # output level 0 and 1 directly use the backbone features + fpn_interp_model: nearest + + memory_attention: + _target_: sam2.modeling.memory_attention.MemoryAttention + d_model: 256 + pos_enc_at_input: true + layer: + _target_: sam2.modeling.memory_attention.MemoryAttentionLayer + activation: relu + dim_feedforward: 2048 + dropout: 0.1 + pos_enc_at_attn: false + self_attention: + _target_: sam2.modeling.sam.transformer.RoPEAttention + rope_theta: 10000.0 + feat_sizes: [32, 32] + embedding_dim: 256 + num_heads: 1 + downsample_rate: 1 + dropout: 0.1 + d_model: 256 + pos_enc_at_cross_attn_keys: true + pos_enc_at_cross_attn_queries: false + cross_attention: + _target_: sam2.modeling.sam.transformer.RoPEAttention + rope_theta: 10000.0 + feat_sizes: [32, 32] + rope_k_repeat: True + embedding_dim: 256 + num_heads: 1 + downsample_rate: 1 + dropout: 0.1 + kv_in_dim: 64 + num_layers: 4 + + memory_encoder: + _target_: sam2.modeling.memory_encoder.MemoryEncoder + out_dim: 64 + position_encoding: + _target_: sam2.modeling.position_encoding.PositionEmbeddingSine + num_pos_feats: 64 + normalize: true + scale: null + temperature: 10000 + mask_downsampler: + _target_: sam2.modeling.memory_encoder.MaskDownSampler + kernel_size: 3 + stride: 2 + padding: 1 + fuser: + _target_: sam2.modeling.memory_encoder.Fuser + layer: + _target_: sam2.modeling.memory_encoder.CXBlock + dim: 256 + kernel_size: 7 + padding: 3 + layer_scale_init_value: 1e-6 + use_dwconv: True # depth-wise convs + num_layers: 2 + + num_maskmem: 7 + image_size: 1024 + # apply scaled sigmoid on mask logits for memory encoder, and directly feed input mask as output mask + sigmoid_scale_for_mem_enc: 20.0 + sigmoid_bias_for_mem_enc: -10.0 + use_mask_input_as_output_without_sam: true + # Memory + directly_add_no_mem_embed: true + no_obj_embed_spatial: true + # use high-resolution feature map in the SAM mask decoder + use_high_res_features_in_sam: true + # output 3 masks on the first click on initial conditioning frames + multimask_output_in_sam: true + # SAM heads + iou_prediction_use_sigmoid: True + # cross-attend to object pointers from other frames (based on SAM output tokens) in the encoder + use_obj_ptrs_in_encoder: true + add_tpos_enc_to_obj_ptrs: true + proj_tpos_enc_in_obj_ptrs: true + use_signed_tpos_enc_to_obj_ptrs: true + only_obj_ptrs_in_the_past_for_eval: true + # object occlusion prediction + pred_obj_scores: true + pred_obj_scores_mlp: true + fixed_no_obj_ptr: true + # multimask tracking settings + multimask_output_for_tracking: true + use_multimask_token_for_obj_ptr: true + multimask_min_pt_num: 0 + multimask_max_pt_num: 1 + use_mlp_for_obj_ptr_proj: true + # Compilation flag + compile_image_encoder: False diff --git a/py/sam2/sam2_configs/sam2.1_hiera_l.yaml b/py/sam2/sam2_configs/sam2.1_hiera_l.yaml new file mode 100644 index 0000000..33c9097 --- /dev/null +++ b/py/sam2/sam2_configs/sam2.1_hiera_l.yaml @@ -0,0 +1,120 @@ +# @package _global_ + +# Model +model: + _target_: sam2.modeling.sam2_base.SAM2Base + image_encoder: + _target_: sam2.modeling.backbones.image_encoder.ImageEncoder + scalp: 1 + trunk: + _target_: sam2.modeling.backbones.hieradet.Hiera + embed_dim: 144 + num_heads: 2 + stages: [2, 6, 36, 4] + global_att_blocks: [23, 33, 43] + window_pos_embed_bkg_spatial_size: [7, 7] + window_spec: [8, 4, 16, 8] + neck: + _target_: sam2.modeling.backbones.image_encoder.FpnNeck + position_encoding: + _target_: sam2.modeling.position_encoding.PositionEmbeddingSine + num_pos_feats: 256 + normalize: true + scale: null + temperature: 10000 + d_model: 256 + backbone_channel_list: [1152, 576, 288, 144] + fpn_top_down_levels: [2, 3] # output level 0 and 1 directly use the backbone features + fpn_interp_model: nearest + + memory_attention: + _target_: sam2.modeling.memory_attention.MemoryAttention + d_model: 256 + pos_enc_at_input: true + layer: + _target_: sam2.modeling.memory_attention.MemoryAttentionLayer + activation: relu + dim_feedforward: 2048 + dropout: 0.1 + pos_enc_at_attn: false + self_attention: + _target_: sam2.modeling.sam.transformer.RoPEAttention + rope_theta: 10000.0 + feat_sizes: [32, 32] + embedding_dim: 256 + num_heads: 1 + downsample_rate: 1 + dropout: 0.1 + d_model: 256 + pos_enc_at_cross_attn_keys: true + pos_enc_at_cross_attn_queries: false + cross_attention: + _target_: sam2.modeling.sam.transformer.RoPEAttention + rope_theta: 10000.0 + feat_sizes: [32, 32] + rope_k_repeat: True + embedding_dim: 256 + num_heads: 1 + downsample_rate: 1 + dropout: 0.1 + kv_in_dim: 64 + num_layers: 4 + + memory_encoder: + _target_: sam2.modeling.memory_encoder.MemoryEncoder + out_dim: 64 + position_encoding: + _target_: sam2.modeling.position_encoding.PositionEmbeddingSine + num_pos_feats: 64 + normalize: true + scale: null + temperature: 10000 + mask_downsampler: + _target_: sam2.modeling.memory_encoder.MaskDownSampler + kernel_size: 3 + stride: 2 + padding: 1 + fuser: + _target_: sam2.modeling.memory_encoder.Fuser + layer: + _target_: sam2.modeling.memory_encoder.CXBlock + dim: 256 + kernel_size: 7 + padding: 3 + layer_scale_init_value: 1e-6 + use_dwconv: True # depth-wise convs + num_layers: 2 + + num_maskmem: 7 + image_size: 1024 + # apply scaled sigmoid on mask logits for memory encoder, and directly feed input mask as output mask + sigmoid_scale_for_mem_enc: 20.0 + sigmoid_bias_for_mem_enc: -10.0 + use_mask_input_as_output_without_sam: true + # Memory + directly_add_no_mem_embed: true + no_obj_embed_spatial: true + # use high-resolution feature map in the SAM mask decoder + use_high_res_features_in_sam: true + # output 3 masks on the first click on initial conditioning frames + multimask_output_in_sam: true + # SAM heads + iou_prediction_use_sigmoid: True + # cross-attend to object pointers from other frames (based on SAM output tokens) in the encoder + use_obj_ptrs_in_encoder: true + add_tpos_enc_to_obj_ptrs: true + proj_tpos_enc_in_obj_ptrs: true + use_signed_tpos_enc_to_obj_ptrs: true + only_obj_ptrs_in_the_past_for_eval: true + # object occlusion prediction + pred_obj_scores: true + pred_obj_scores_mlp: true + fixed_no_obj_ptr: true + # multimask tracking settings + multimask_output_for_tracking: true + use_multimask_token_for_obj_ptr: true + multimask_min_pt_num: 0 + multimask_max_pt_num: 1 + use_mlp_for_obj_ptr_proj: true + # Compilation flag + compile_image_encoder: False diff --git a/py/sam2/sam2_configs/sam2.1_hiera_s.yaml b/py/sam2/sam2_configs/sam2.1_hiera_s.yaml new file mode 100644 index 0000000..8e803df --- /dev/null +++ b/py/sam2/sam2_configs/sam2.1_hiera_s.yaml @@ -0,0 +1,119 @@ +# @package _global_ + +# Model +model: + _target_: sam2.modeling.sam2_base.SAM2Base + image_encoder: + _target_: sam2.modeling.backbones.image_encoder.ImageEncoder + scalp: 1 + trunk: + _target_: sam2.modeling.backbones.hieradet.Hiera + embed_dim: 96 + num_heads: 1 + stages: [1, 2, 11, 2] + global_att_blocks: [7, 10, 13] + window_pos_embed_bkg_spatial_size: [7, 7] + neck: + _target_: sam2.modeling.backbones.image_encoder.FpnNeck + position_encoding: + _target_: sam2.modeling.position_encoding.PositionEmbeddingSine + num_pos_feats: 256 + normalize: true + scale: null + temperature: 10000 + d_model: 256 + backbone_channel_list: [768, 384, 192, 96] + fpn_top_down_levels: [2, 3] # output level 0 and 1 directly use the backbone features + fpn_interp_model: nearest + + memory_attention: + _target_: sam2.modeling.memory_attention.MemoryAttention + d_model: 256 + pos_enc_at_input: true + layer: + _target_: sam2.modeling.memory_attention.MemoryAttentionLayer + activation: relu + dim_feedforward: 2048 + dropout: 0.1 + pos_enc_at_attn: false + self_attention: + _target_: sam2.modeling.sam.transformer.RoPEAttention + rope_theta: 10000.0 + feat_sizes: [32, 32] + embedding_dim: 256 + num_heads: 1 + downsample_rate: 1 + dropout: 0.1 + d_model: 256 + pos_enc_at_cross_attn_keys: true + pos_enc_at_cross_attn_queries: false + cross_attention: + _target_: sam2.modeling.sam.transformer.RoPEAttention + rope_theta: 10000.0 + feat_sizes: [32, 32] + rope_k_repeat: True + embedding_dim: 256 + num_heads: 1 + downsample_rate: 1 + dropout: 0.1 + kv_in_dim: 64 + num_layers: 4 + + memory_encoder: + _target_: sam2.modeling.memory_encoder.MemoryEncoder + out_dim: 64 + position_encoding: + _target_: sam2.modeling.position_encoding.PositionEmbeddingSine + num_pos_feats: 64 + normalize: true + scale: null + temperature: 10000 + mask_downsampler: + _target_: sam2.modeling.memory_encoder.MaskDownSampler + kernel_size: 3 + stride: 2 + padding: 1 + fuser: + _target_: sam2.modeling.memory_encoder.Fuser + layer: + _target_: sam2.modeling.memory_encoder.CXBlock + dim: 256 + kernel_size: 7 + padding: 3 + layer_scale_init_value: 1e-6 + use_dwconv: True # depth-wise convs + num_layers: 2 + + num_maskmem: 7 + image_size: 1024 + # apply scaled sigmoid on mask logits for memory encoder, and directly feed input mask as output mask + sigmoid_scale_for_mem_enc: 20.0 + sigmoid_bias_for_mem_enc: -10.0 + use_mask_input_as_output_without_sam: true + # Memory + directly_add_no_mem_embed: true + no_obj_embed_spatial: true + # use high-resolution feature map in the SAM mask decoder + use_high_res_features_in_sam: true + # output 3 masks on the first click on initial conditioning frames + multimask_output_in_sam: true + # SAM heads + iou_prediction_use_sigmoid: True + # cross-attend to object pointers from other frames (based on SAM output tokens) in the encoder + use_obj_ptrs_in_encoder: true + add_tpos_enc_to_obj_ptrs: true + proj_tpos_enc_in_obj_ptrs: true + use_signed_tpos_enc_to_obj_ptrs: true + only_obj_ptrs_in_the_past_for_eval: true + # object occlusion prediction + pred_obj_scores: true + pred_obj_scores_mlp: true + fixed_no_obj_ptr: true + # multimask tracking settings + multimask_output_for_tracking: true + use_multimask_token_for_obj_ptr: true + multimask_min_pt_num: 0 + multimask_max_pt_num: 1 + use_mlp_for_obj_ptr_proj: true + # Compilation flag + compile_image_encoder: False diff --git a/py/sam2/sam2_configs/sam2.1_hiera_t.yaml b/py/sam2/sam2_configs/sam2.1_hiera_t.yaml new file mode 100644 index 0000000..983c2ea --- /dev/null +++ b/py/sam2/sam2_configs/sam2.1_hiera_t.yaml @@ -0,0 +1,121 @@ +# @package _global_ + +# Model +model: + _target_: sam2.modeling.sam2_base.SAM2Base + image_encoder: + _target_: sam2.modeling.backbones.image_encoder.ImageEncoder + scalp: 1 + trunk: + _target_: sam2.modeling.backbones.hieradet.Hiera + embed_dim: 96 + num_heads: 1 + stages: [1, 2, 7, 2] + global_att_blocks: [5, 7, 9] + window_pos_embed_bkg_spatial_size: [7, 7] + neck: + _target_: sam2.modeling.backbones.image_encoder.FpnNeck + position_encoding: + _target_: sam2.modeling.position_encoding.PositionEmbeddingSine + num_pos_feats: 256 + normalize: true + scale: null + temperature: 10000 + d_model: 256 + backbone_channel_list: [768, 384, 192, 96] + fpn_top_down_levels: [2, 3] # output level 0 and 1 directly use the backbone features + fpn_interp_model: nearest + + memory_attention: + _target_: sam2.modeling.memory_attention.MemoryAttention + d_model: 256 + pos_enc_at_input: true + layer: + _target_: sam2.modeling.memory_attention.MemoryAttentionLayer + activation: relu + dim_feedforward: 2048 + dropout: 0.1 + pos_enc_at_attn: false + self_attention: + _target_: sam2.modeling.sam.transformer.RoPEAttention + rope_theta: 10000.0 + feat_sizes: [32, 32] + embedding_dim: 256 + num_heads: 1 + downsample_rate: 1 + dropout: 0.1 + d_model: 256 + pos_enc_at_cross_attn_keys: true + pos_enc_at_cross_attn_queries: false + cross_attention: + _target_: sam2.modeling.sam.transformer.RoPEAttention + rope_theta: 10000.0 + feat_sizes: [32, 32] + rope_k_repeat: True + embedding_dim: 256 + num_heads: 1 + downsample_rate: 1 + dropout: 0.1 + kv_in_dim: 64 + num_layers: 4 + + memory_encoder: + _target_: sam2.modeling.memory_encoder.MemoryEncoder + out_dim: 64 + position_encoding: + _target_: sam2.modeling.position_encoding.PositionEmbeddingSine + num_pos_feats: 64 + normalize: true + scale: null + temperature: 10000 + mask_downsampler: + _target_: sam2.modeling.memory_encoder.MaskDownSampler + kernel_size: 3 + stride: 2 + padding: 1 + fuser: + _target_: sam2.modeling.memory_encoder.Fuser + layer: + _target_: sam2.modeling.memory_encoder.CXBlock + dim: 256 + kernel_size: 7 + padding: 3 + layer_scale_init_value: 1e-6 + use_dwconv: True # depth-wise convs + num_layers: 2 + + num_maskmem: 7 + image_size: 1024 + # apply scaled sigmoid on mask logits for memory encoder, and directly feed input mask as output mask + # SAM decoder + sigmoid_scale_for_mem_enc: 20.0 + sigmoid_bias_for_mem_enc: -10.0 + use_mask_input_as_output_without_sam: true + # Memory + directly_add_no_mem_embed: true + no_obj_embed_spatial: true + # use high-resolution feature map in the SAM mask decoder + use_high_res_features_in_sam: true + # output 3 masks on the first click on initial conditioning frames + multimask_output_in_sam: true + # SAM heads + iou_prediction_use_sigmoid: True + # cross-attend to object pointers from other frames (based on SAM output tokens) in the encoder + use_obj_ptrs_in_encoder: true + add_tpos_enc_to_obj_ptrs: true + proj_tpos_enc_in_obj_ptrs: true + use_signed_tpos_enc_to_obj_ptrs: true + only_obj_ptrs_in_the_past_for_eval: true + # object occlusion prediction + pred_obj_scores: true + pred_obj_scores_mlp: true + fixed_no_obj_ptr: true + # multimask tracking settings + multimask_output_for_tracking: true + use_multimask_token_for_obj_ptr: true + multimask_min_pt_num: 0 + multimask_max_pt_num: 1 + use_mlp_for_obj_ptr_proj: true + # Compilation flag + # HieraT does not currently support compilation, should always be set to False + compile_image_encoder: False diff --git a/py/sam2/sam2_configs/sam2_hiera_b+.yaml b/py/sam2/sam2_configs/sam2_hiera_b+.yaml new file mode 100644 index 0000000..4e46167 --- /dev/null +++ b/py/sam2/sam2_configs/sam2_hiera_b+.yaml @@ -0,0 +1,119 @@ +# @package _global_ + +# Model +model: + _target_: sam2.modeling.sam2_base.SAM2Base + image_encoder: + _target_: sam2.modeling.backbones.image_encoder.ImageEncoder + scalp: 1 + trunk: + _target_: sam2.modeling.backbones.hieradet.Hiera + embed_dim: 112 + num_heads: 2 + stages: [2, 3, 16, 3] + global_att_blocks: [12, 16, 20] + window_pos_embed_bkg_spatial_size: [14, 14] + neck: + _target_: sam2.modeling.backbones.image_encoder.FpnNeck + position_encoding: + _target_: sam2.modeling.position_encoding.PositionEmbeddingSine + num_pos_feats: 256 + normalize: true + scale: null + temperature: 10000 + d_model: 256 + backbone_channel_list: [896, 448, 224, 112] + fpn_top_down_levels: [2, 3] # output level 0 and 1 directly use the backbone features + fpn_interp_model: nearest + + memory_attention: + _target_: sam2.modeling.memory_attention.MemoryAttention + d_model: 256 + pos_enc_at_input: true + layer: + _target_: sam2.modeling.memory_attention.MemoryAttentionLayer + activation: relu + dim_feedforward: 2048 + dropout: 0.1 + pos_enc_at_attn: false + self_attention: + _target_: sam2.modeling.sam.transformer.RoPEAttention + rope_theta: 10000.0 + feat_sizes: [32, 32] + embedding_dim: 256 + num_heads: 1 + downsample_rate: 1 + dropout: 0.1 + d_model: 256 + pos_enc_at_cross_attn_keys: true + pos_enc_at_cross_attn_queries: false + cross_attention: + _target_: sam2.modeling.sam.transformer.RoPEAttention + rope_theta: 10000.0 + feat_sizes: [32, 32] + rope_k_repeat: True + embedding_dim: 256 + num_heads: 1 + downsample_rate: 1 + dropout: 0.1 + kv_in_dim: 64 + num_layers: 4 + + memory_encoder: + _target_: sam2.modeling.memory_encoder.MemoryEncoder + out_dim: 64 + position_encoding: + _target_: sam2.modeling.position_encoding.PositionEmbeddingSine + num_pos_feats: 64 + normalize: true + scale: null + temperature: 10000 + mask_downsampler: + _target_: sam2.modeling.memory_encoder.MaskDownSampler + kernel_size: 3 + stride: 2 + padding: 1 + fuser: + _target_: sam2.modeling.memory_encoder.Fuser + layer: + _target_: sam2.modeling.memory_encoder.CXBlock + dim: 256 + kernel_size: 7 + padding: 3 + layer_scale_init_value: 1e-6 + use_dwconv: True # depth-wise convs + num_layers: 2 + + num_maskmem: 7 + image_size: 1024 + # apply scaled sigmoid on mask logits for memory encoder, and directly feed input mask as output mask + sigmoid_scale_for_mem_enc: 20.0 + sigmoid_bias_for_mem_enc: -10.0 + use_mask_input_as_output_without_sam: true + # Memory + directly_add_no_mem_embed: true + no_obj_embed_spatial: false + # use high-resolution feature map in the SAM mask decoder + use_high_res_features_in_sam: true + # output 3 masks on the first click on initial conditioning frames + multimask_output_in_sam: true + # SAM heads + iou_prediction_use_sigmoid: True + # cross-attend to object pointers from other frames (based on SAM output tokens) in the encoder + use_obj_ptrs_in_encoder: true + add_tpos_enc_to_obj_ptrs: false + proj_tpos_enc_in_obj_ptrs: false + use_signed_tpos_enc_to_obj_ptrs: false + only_obj_ptrs_in_the_past_for_eval: true + # object occlusion prediction + pred_obj_scores: true + pred_obj_scores_mlp: true + fixed_no_obj_ptr: true + # multimask tracking settings + multimask_output_for_tracking: true + use_multimask_token_for_obj_ptr: true + multimask_min_pt_num: 0 + multimask_max_pt_num: 1 + use_mlp_for_obj_ptr_proj: true + # Compilation flag + compile_image_encoder: False diff --git a/py/sam2/sam2_configs/sam2_hiera_l.yaml b/py/sam2/sam2_configs/sam2_hiera_l.yaml new file mode 100644 index 0000000..f24f1de --- /dev/null +++ b/py/sam2/sam2_configs/sam2_hiera_l.yaml @@ -0,0 +1,120 @@ +# @package _global_ + +# Model +model: + _target_: sam2.modeling.sam2_base.SAM2Base + image_encoder: + _target_: sam2.modeling.backbones.image_encoder.ImageEncoder + scalp: 1 + trunk: + _target_: sam2.modeling.backbones.hieradet.Hiera + embed_dim: 144 + num_heads: 2 + stages: [2, 6, 36, 4] + global_att_blocks: [23, 33, 43] + window_pos_embed_bkg_spatial_size: [7, 7] + window_spec: [8, 4, 16, 8] + neck: + _target_: sam2.modeling.backbones.image_encoder.FpnNeck + position_encoding: + _target_: sam2.modeling.position_encoding.PositionEmbeddingSine + num_pos_feats: 256 + normalize: true + scale: null + temperature: 10000 + d_model: 256 + backbone_channel_list: [1152, 576, 288, 144] + fpn_top_down_levels: [2, 3] # output level 0 and 1 directly use the backbone features + fpn_interp_model: nearest + + memory_attention: + _target_: sam2.modeling.memory_attention.MemoryAttention + d_model: 256 + pos_enc_at_input: true + layer: + _target_: sam2.modeling.memory_attention.MemoryAttentionLayer + activation: relu + dim_feedforward: 2048 + dropout: 0.1 + pos_enc_at_attn: false + self_attention: + _target_: sam2.modeling.sam.transformer.RoPEAttention + rope_theta: 10000.0 + feat_sizes: [32, 32] + embedding_dim: 256 + num_heads: 1 + downsample_rate: 1 + dropout: 0.1 + d_model: 256 + pos_enc_at_cross_attn_keys: true + pos_enc_at_cross_attn_queries: false + cross_attention: + _target_: sam2.modeling.sam.transformer.RoPEAttention + rope_theta: 10000.0 + feat_sizes: [32, 32] + rope_k_repeat: True + embedding_dim: 256 + num_heads: 1 + downsample_rate: 1 + dropout: 0.1 + kv_in_dim: 64 + num_layers: 4 + + memory_encoder: + _target_: sam2.modeling.memory_encoder.MemoryEncoder + out_dim: 64 + position_encoding: + _target_: sam2.modeling.position_encoding.PositionEmbeddingSine + num_pos_feats: 64 + normalize: true + scale: null + temperature: 10000 + mask_downsampler: + _target_: sam2.modeling.memory_encoder.MaskDownSampler + kernel_size: 3 + stride: 2 + padding: 1 + fuser: + _target_: sam2.modeling.memory_encoder.Fuser + layer: + _target_: sam2.modeling.memory_encoder.CXBlock + dim: 256 + kernel_size: 7 + padding: 3 + layer_scale_init_value: 1e-6 + use_dwconv: True # depth-wise convs + num_layers: 2 + + num_maskmem: 7 + image_size: 1024 + # apply scaled sigmoid on mask logits for memory encoder, and directly feed input mask as output mask + sigmoid_scale_for_mem_enc: 20.0 + sigmoid_bias_for_mem_enc: -10.0 + use_mask_input_as_output_without_sam: true + # Memory + directly_add_no_mem_embed: true + no_obj_embed_spatial: false + # use high-resolution feature map in the SAM mask decoder + use_high_res_features_in_sam: true + # output 3 masks on the first click on initial conditioning frames + multimask_output_in_sam: true + # SAM heads + iou_prediction_use_sigmoid: True + # cross-attend to object pointers from other frames (based on SAM output tokens) in the encoder + use_obj_ptrs_in_encoder: true + add_tpos_enc_to_obj_ptrs: false + proj_tpos_enc_in_obj_ptrs: false + use_signed_tpos_enc_to_obj_ptrs: false + only_obj_ptrs_in_the_past_for_eval: true + # object occlusion prediction + pred_obj_scores: true + pred_obj_scores_mlp: true + fixed_no_obj_ptr: true + # multimask tracking settings + multimask_output_for_tracking: true + use_multimask_token_for_obj_ptr: true + multimask_min_pt_num: 0 + multimask_max_pt_num: 1 + use_mlp_for_obj_ptr_proj: true + # Compilation flag + compile_image_encoder: False diff --git a/py/sam2/sam2_configs/sam2_hiera_s.yaml b/py/sam2/sam2_configs/sam2_hiera_s.yaml new file mode 100644 index 0000000..795858e --- /dev/null +++ b/py/sam2/sam2_configs/sam2_hiera_s.yaml @@ -0,0 +1,119 @@ +# @package _global_ + +# Model +model: + _target_: sam2.modeling.sam2_base.SAM2Base + image_encoder: + _target_: sam2.modeling.backbones.image_encoder.ImageEncoder + scalp: 1 + trunk: + _target_: sam2.modeling.backbones.hieradet.Hiera + embed_dim: 96 + num_heads: 1 + stages: [1, 2, 11, 2] + global_att_blocks: [7, 10, 13] + window_pos_embed_bkg_spatial_size: [7, 7] + neck: + _target_: sam2.modeling.backbones.image_encoder.FpnNeck + position_encoding: + _target_: sam2.modeling.position_encoding.PositionEmbeddingSine + num_pos_feats: 256 + normalize: true + scale: null + temperature: 10000 + d_model: 256 + backbone_channel_list: [768, 384, 192, 96] + fpn_top_down_levels: [2, 3] # output level 0 and 1 directly use the backbone features + fpn_interp_model: nearest + + memory_attention: + _target_: sam2.modeling.memory_attention.MemoryAttention + d_model: 256 + pos_enc_at_input: true + layer: + _target_: sam2.modeling.memory_attention.MemoryAttentionLayer + activation: relu + dim_feedforward: 2048 + dropout: 0.1 + pos_enc_at_attn: false + self_attention: + _target_: sam2.modeling.sam.transformer.RoPEAttention + rope_theta: 10000.0 + feat_sizes: [32, 32] + embedding_dim: 256 + num_heads: 1 + downsample_rate: 1 + dropout: 0.1 + d_model: 256 + pos_enc_at_cross_attn_keys: true + pos_enc_at_cross_attn_queries: false + cross_attention: + _target_: sam2.modeling.sam.transformer.RoPEAttention + rope_theta: 10000.0 + feat_sizes: [32, 32] + rope_k_repeat: True + embedding_dim: 256 + num_heads: 1 + downsample_rate: 1 + dropout: 0.1 + kv_in_dim: 64 + num_layers: 4 + + memory_encoder: + _target_: sam2.modeling.memory_encoder.MemoryEncoder + out_dim: 64 + position_encoding: + _target_: sam2.modeling.position_encoding.PositionEmbeddingSine + num_pos_feats: 64 + normalize: true + scale: null + temperature: 10000 + mask_downsampler: + _target_: sam2.modeling.memory_encoder.MaskDownSampler + kernel_size: 3 + stride: 2 + padding: 1 + fuser: + _target_: sam2.modeling.memory_encoder.Fuser + layer: + _target_: sam2.modeling.memory_encoder.CXBlock + dim: 256 + kernel_size: 7 + padding: 3 + layer_scale_init_value: 1e-6 + use_dwconv: True # depth-wise convs + num_layers: 2 + + num_maskmem: 7 + image_size: 1024 + # apply scaled sigmoid on mask logits for memory encoder, and directly feed input mask as output mask + sigmoid_scale_for_mem_enc: 20.0 + sigmoid_bias_for_mem_enc: -10.0 + use_mask_input_as_output_without_sam: true + # Memory + directly_add_no_mem_embed: true + no_obj_embed_spatial: false + # use high-resolution feature map in the SAM mask decoder + use_high_res_features_in_sam: true + # output 3 masks on the first click on initial conditioning frames + multimask_output_in_sam: true + # SAM heads + iou_prediction_use_sigmoid: True + # cross-attend to object pointers from other frames (based on SAM output tokens) in the encoder + use_obj_ptrs_in_encoder: true + add_tpos_enc_to_obj_ptrs: false + proj_tpos_enc_in_obj_ptrs: false + use_signed_tpos_enc_to_obj_ptrs: false + only_obj_ptrs_in_the_past_for_eval: true + # object occlusion prediction + pred_obj_scores: true + pred_obj_scores_mlp: true + fixed_no_obj_ptr: true + # multimask tracking settings + multimask_output_for_tracking: true + use_multimask_token_for_obj_ptr: true + multimask_min_pt_num: 0 + multimask_max_pt_num: 1 + use_mlp_for_obj_ptr_proj: true + # Compilation flag + compile_image_encoder: False diff --git a/py/sam2/sam2_configs/sam2_hiera_t.yaml b/py/sam2/sam2_configs/sam2_hiera_t.yaml new file mode 100644 index 0000000..5eb3f24 --- /dev/null +++ b/py/sam2/sam2_configs/sam2_hiera_t.yaml @@ -0,0 +1,121 @@ +# @package _global_ + +# Model +model: + _target_: sam2.modeling.sam2_base.SAM2Base + image_encoder: + _target_: sam2.modeling.backbones.image_encoder.ImageEncoder + scalp: 1 + trunk: + _target_: sam2.modeling.backbones.hieradet.Hiera + embed_dim: 96 + num_heads: 1 + stages: [1, 2, 7, 2] + global_att_blocks: [5, 7, 9] + window_pos_embed_bkg_spatial_size: [7, 7] + neck: + _target_: sam2.modeling.backbones.image_encoder.FpnNeck + position_encoding: + _target_: sam2.modeling.position_encoding.PositionEmbeddingSine + num_pos_feats: 256 + normalize: true + scale: null + temperature: 10000 + d_model: 256 + backbone_channel_list: [768, 384, 192, 96] + fpn_top_down_levels: [2, 3] # output level 0 and 1 directly use the backbone features + fpn_interp_model: nearest + + memory_attention: + _target_: sam2.modeling.memory_attention.MemoryAttention + d_model: 256 + pos_enc_at_input: true + layer: + _target_: sam2.modeling.memory_attention.MemoryAttentionLayer + activation: relu + dim_feedforward: 2048 + dropout: 0.1 + pos_enc_at_attn: false + self_attention: + _target_: sam2.modeling.sam.transformer.RoPEAttention + rope_theta: 10000.0 + feat_sizes: [32, 32] + embedding_dim: 256 + num_heads: 1 + downsample_rate: 1 + dropout: 0.1 + d_model: 256 + pos_enc_at_cross_attn_keys: true + pos_enc_at_cross_attn_queries: false + cross_attention: + _target_: sam2.modeling.sam.transformer.RoPEAttention + rope_theta: 10000.0 + feat_sizes: [32, 32] + rope_k_repeat: True + embedding_dim: 256 + num_heads: 1 + downsample_rate: 1 + dropout: 0.1 + kv_in_dim: 64 + num_layers: 4 + + memory_encoder: + _target_: sam2.modeling.memory_encoder.MemoryEncoder + out_dim: 64 + position_encoding: + _target_: sam2.modeling.position_encoding.PositionEmbeddingSine + num_pos_feats: 64 + normalize: true + scale: null + temperature: 10000 + mask_downsampler: + _target_: sam2.modeling.memory_encoder.MaskDownSampler + kernel_size: 3 + stride: 2 + padding: 1 + fuser: + _target_: sam2.modeling.memory_encoder.Fuser + layer: + _target_: sam2.modeling.memory_encoder.CXBlock + dim: 256 + kernel_size: 7 + padding: 3 + layer_scale_init_value: 1e-6 + use_dwconv: True # depth-wise convs + num_layers: 2 + + num_maskmem: 7 + image_size: 1024 + # apply scaled sigmoid on mask logits for memory encoder, and directly feed input mask as output mask + # SAM decoder + sigmoid_scale_for_mem_enc: 20.0 + sigmoid_bias_for_mem_enc: -10.0 + use_mask_input_as_output_without_sam: true + # Memory + directly_add_no_mem_embed: true + no_obj_embed_spatial: false + # use high-resolution feature map in the SAM mask decoder + use_high_res_features_in_sam: true + # output 3 masks on the first click on initial conditioning frames + multimask_output_in_sam: true + # SAM heads + iou_prediction_use_sigmoid: True + # cross-attend to object pointers from other frames (based on SAM output tokens) in the encoder + use_obj_ptrs_in_encoder: true + add_tpos_enc_to_obj_ptrs: false + proj_tpos_enc_in_obj_ptrs: false + use_signed_tpos_enc_to_obj_ptrs: false + only_obj_ptrs_in_the_past_for_eval: true + # object occlusion prediction + pred_obj_scores: true + pred_obj_scores_mlp: true + fixed_no_obj_ptr: true + # multimask tracking settings + multimask_output_for_tracking: true + use_multimask_token_for_obj_ptr: true + multimask_min_pt_num: 0 + multimask_max_pt_num: 1 + use_mlp_for_obj_ptr_proj: true + # Compilation flag + # HieraT does not currently support compilation, should always be set to False + compile_image_encoder: False diff --git a/py/sam2/sam2_image_predictor.py b/py/sam2/sam2_image_predictor.py new file mode 100644 index 0000000..271a0f0 --- /dev/null +++ b/py/sam2/sam2_image_predictor.py @@ -0,0 +1,446 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import logging + +from typing import List, Optional, Tuple, Union + +import numpy as np +import torch +from PIL.Image import Image + +from ..sam2.modeling.sam2_base import SAM2Base + +from ..sam2.utils.transforms import SAM2Transforms + + +class SAM2ImagePredictor: + def __init__( + self, + sam_model: SAM2Base, + mask_threshold=0.0, + max_hole_area=0.0, + max_sprinkle_area=0.0, + ) -> None: + """ + Uses SAM-2 to calculate the image embedding for an image, and then + allow repeated, efficient mask prediction given prompts. + + Arguments: + sam_model (Sam-2): The model to use for mask prediction. + mask_threshold (float): The threshold to use when converting mask logits + to binary masks. Masks are thresholded at 0 by default. + fill_hole_area (int): If fill_hole_area > 0, we fill small holes in up to + the maximum area of fill_hole_area in low_res_masks. + """ + super().__init__() + self.model = sam_model + self._transforms = SAM2Transforms( + resolution=self.model.image_size, + mask_threshold=mask_threshold, + max_hole_area=max_hole_area, + max_sprinkle_area=max_sprinkle_area, + ) + + # Predictor state + self._is_image_set = False + self._features = None + self._orig_hw = None + # Whether the predictor is set for single image or a batch of images + self._is_batch = False + + # Predictor config + self.mask_threshold = mask_threshold + + # Spatial dim for backbone feature maps + self._bb_feat_sizes = [ + (256, 256), + (128, 128), + (64, 64), + ] + + @torch.no_grad() + def set_image( + self, + image: Union[np.ndarray, Image], + ) -> None: + """ + Calculates the image embeddings for the provided image, allowing + masks to be predicted with the 'predict' method. + + Arguments: + image (np.ndarray or PIL Image): The input image to embed in RGB format. The image should be in HWC format if np.ndarray, or WHC format if PIL Image + with pixel values in [0, 255]. + image_format (str): The color format of the image, in ['RGB', 'BGR']. + """ + self.reset_predictor() + # Transform the image to the form expected by the model + if isinstance(image, np.ndarray): + #logging.info("For numpy array image, we assume (HxWxC) format") + self._orig_hw = [image.shape[:2]] + elif isinstance(image, Image): + w, h = image.size + self._orig_hw = [(h, w)] + else: + raise NotImplementedError("Image format not supported") + + input_image = self._transforms(image) + input_image = input_image[None, ...].to(self.device) + + assert ( + len(input_image.shape) == 4 and input_image.shape[1] == 3 + ), f"input_image must be of size 1x3xHxW, got {input_image.shape}" + #logging.info("Computing image embeddings for the provided image...") + backbone_out = self.model.forward_image(input_image) + _, vision_feats, _, _ = self.model._prepare_backbone_features(backbone_out) + # Add no_mem_embed, which is added to the lowest rest feat. map during training on videos + if self.model.directly_add_no_mem_embed: + vision_feats[-1] = vision_feats[-1] + self.model.no_mem_embed + + feats = [ + feat.permute(1, 2, 0).view(1, -1, *feat_size) + for feat, feat_size in zip(vision_feats[::-1], self._bb_feat_sizes[::-1]) + ][::-1] + self._features = {"image_embed": feats[-1], "high_res_feats": feats[:-1]} + self._is_image_set = True + #logging.info("Image embeddings computed.") + + @torch.no_grad() + def set_image_batch( + self, + image_list: List[Union[np.ndarray]], + ) -> None: + """ + Calculates the image embeddings for the provided image batch, allowing + masks to be predicted with the 'predict_batch' method. + + Arguments: + image_list (List[np.ndarray]): The input images to embed in RGB format. The image should be in HWC format if np.ndarray + with pixel values in [0, 255]. + """ + self.reset_predictor() + assert isinstance(image_list, list) + self._orig_hw = [] + for image in image_list: + assert isinstance( + image, np.ndarray + ), "Images are expected to be an np.ndarray in RGB format, and of shape HWC" + self._orig_hw.append(image.shape[:2]) + # Transform the image to the form expected by the model + img_batch = self._transforms.forward_batch(image_list) + img_batch = img_batch.to(self.device) + batch_size = img_batch.shape[0] + assert ( + len(img_batch.shape) == 4 and img_batch.shape[1] == 3 + ), f"img_batch must be of size Bx3xHxW, got {img_batch.shape}" + logging.info("Computing image embeddings for the provided images...") + backbone_out = self.model.forward_image(img_batch) + _, vision_feats, _, _ = self.model._prepare_backbone_features(backbone_out) + # Add no_mem_embed, which is added to the lowest rest feat. map during training on videos + if self.model.directly_add_no_mem_embed: + vision_feats[-1] = vision_feats[-1] + self.model.no_mem_embed + + feats = [ + feat.permute(1, 2, 0).view(batch_size, -1, *feat_size) + for feat, feat_size in zip(vision_feats[::-1], self._bb_feat_sizes[::-1]) + ][::-1] + self._features = {"image_embed": feats[-1], "high_res_feats": feats[:-1]} + self._is_image_set = True + self._is_batch = True + logging.info("Image embeddings computed.") + + def predict_batch( + self, + point_coords_batch: List[np.ndarray] = None, + point_labels_batch: List[np.ndarray] = None, + box_batch: List[np.ndarray] = None, + mask_input_batch: List[np.ndarray] = None, + multimask_output: bool = True, + return_logits: bool = False, + normalize_coords=True, + ) -> Tuple[List[np.ndarray], List[np.ndarray], List[np.ndarray]]: + """This function is very similar to predict(...), however it is used for batched mode, when the model is expected to generate predictions on multiple images. + It returns a tupele of lists of masks, ious, and low_res_masks_logits. + """ + assert self._is_batch, "This function should only be used when in batched mode" + if not self._is_image_set: + raise RuntimeError( + "An image must be set with .set_image_batch(...) before mask prediction." + ) + num_images = len(self._features["image_embed"]) + all_masks = [] + all_ious = [] + all_low_res_masks = [] + for img_idx in range(num_images): + # Transform input prompts + point_coords = ( + point_coords_batch[img_idx] if point_coords_batch is not None else None + ) + point_labels = ( + point_labels_batch[img_idx] if point_labels_batch is not None else None + ) + box = box_batch[img_idx] if box_batch is not None else None + mask_input = ( + mask_input_batch[img_idx] if mask_input_batch is not None else None + ) + mask_input, unnorm_coords, labels, unnorm_box = self._prep_prompts( + point_coords, + point_labels, + box, + mask_input, + normalize_coords, + img_idx=img_idx, + ) + masks, iou_predictions, low_res_masks = self._predict( + unnorm_coords, + labels, + unnorm_box, + mask_input, + multimask_output, + return_logits=return_logits, + img_idx=img_idx, + ) + masks_np = masks.squeeze(0).float().detach().cpu().numpy() + iou_predictions_np = ( + iou_predictions.squeeze(0).float().detach().cpu().numpy() + ) + low_res_masks_np = low_res_masks.squeeze(0).float().detach().cpu().numpy() + all_masks.append(masks_np) + all_ious.append(iou_predictions_np) + all_low_res_masks.append(low_res_masks_np) + + return all_masks, all_ious, all_low_res_masks + + def predict( + self, + point_coords: Optional[np.ndarray] = None, + point_labels: Optional[np.ndarray] = None, + box: Optional[np.ndarray] = None, + mask_input: Optional[np.ndarray] = None, + multimask_output: bool = True, + return_logits: bool = False, + normalize_coords=True, + ) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: + """ + Predict masks for the given input prompts, using the currently set image. + + Arguments: + point_coords (np.ndarray or None): A Nx2 array of point prompts to the + model. Each point is in (X,Y) in pixels. + point_labels (np.ndarray or None): A length N array of labels for the + point prompts. 1 indicates a foreground point and 0 indicates a + background point. + box (np.ndarray or None): A length 4 array given a box prompt to the + model, in XYXY format. + mask_input (np.ndarray): A low resolution mask input to the model, typically + coming from a previous prediction iteration. Has form 1xHxW, where + for SAM, H=W=256. + multimask_output (bool): If true, the model will return three masks. + For ambiguous input prompts (such as a single click), this will often + produce better masks than a single prediction. If only a single + mask is needed, the model's predicted quality score can be used + to select the best mask. For non-ambiguous prompts, such as multiple + input prompts, multimask_output=False can give better results. + return_logits (bool): If true, returns un-thresholded masks logits + instead of a binary mask. + normalize_coords (bool): If true, the point coordinates will be normalized to the range [0,1] and point_coords is expected to be wrt. image dimensions. + + Returns: + (np.ndarray): The output masks in CxHxW format, where C is the + number of masks, and (H, W) is the original image size. + (np.ndarray): An array of length C containing the model's + predictions for the quality of each mask. + (np.ndarray): An array of shape CxHxW, where C is the number + of masks and H=W=256. These low resolution logits can be passed to + a subsequent iteration as mask input. + """ + if not self._is_image_set: + raise RuntimeError( + "An image must be set with .set_image(...) before mask prediction." + ) + + # Transform input prompts + + mask_input, unnorm_coords, labels, unnorm_box = self._prep_prompts( + point_coords, point_labels, box, mask_input, normalize_coords + ) + + masks, iou_predictions, low_res_masks = self._predict( + unnorm_coords, + labels, + unnorm_box, + mask_input, + multimask_output, + return_logits=return_logits, + ) + + masks_np = masks.squeeze(0).float().detach().cpu().numpy() + iou_predictions_np = iou_predictions.squeeze(0).float().detach().cpu().numpy() + low_res_masks_np = low_res_masks.squeeze(0).float().detach().cpu().numpy() + return masks_np, iou_predictions_np, low_res_masks_np + + def _prep_prompts( + self, point_coords, point_labels, box, mask_logits, normalize_coords, img_idx=-1 + ): + + unnorm_coords, labels, unnorm_box, mask_input = None, None, None, None + if point_coords is not None: + assert ( + point_labels is not None + ), "point_labels must be supplied if point_coords is supplied." + point_coords = torch.as_tensor( + point_coords, dtype=torch.float, device=self.device + ) + unnorm_coords = self._transforms.transform_coords( + point_coords, normalize=normalize_coords, orig_hw=self._orig_hw[img_idx] + ) + labels = torch.as_tensor(point_labels, dtype=torch.int, device=self.device) + if len(unnorm_coords.shape) == 2: + unnorm_coords, labels = unnorm_coords[None, ...], labels[None, ...] + if box is not None: + box = torch.as_tensor(box, dtype=torch.float, device=self.device) + unnorm_box = self._transforms.transform_boxes( + box, normalize=normalize_coords, orig_hw=self._orig_hw[img_idx] + ) # Bx2x2 + if mask_logits is not None: + mask_input = torch.as_tensor( + mask_logits, dtype=torch.float, device=self.device + ) + if len(mask_input.shape) == 3: + mask_input = mask_input[None, :, :, :] + return mask_input, unnorm_coords, labels, unnorm_box + + @torch.no_grad() + def _predict( + self, + point_coords: Optional[torch.Tensor], + point_labels: Optional[torch.Tensor], + boxes: Optional[torch.Tensor] = None, + mask_input: Optional[torch.Tensor] = None, + multimask_output: bool = True, + return_logits: bool = False, + img_idx: int = -1, + ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """ + Predict masks for the given input prompts, using the currently set image. + Input prompts are batched torch tensors and are expected to already be + transformed to the input frame using SAM2Transforms. + + Arguments: + point_coords (torch.Tensor or None): A BxNx2 array of point prompts to the + model. Each point is in (X,Y) in pixels. + point_labels (torch.Tensor or None): A BxN array of labels for the + point prompts. 1 indicates a foreground point and 0 indicates a + background point. + boxes (np.ndarray or None): A Bx4 array given a box prompt to the + model, in XYXY format. + mask_input (np.ndarray): A low resolution mask input to the model, typically + coming from a previous prediction iteration. Has form Bx1xHxW, where + for SAM, H=W=256. Masks returned by a previous iteration of the + predict method do not need further transformation. + multimask_output (bool): If true, the model will return three masks. + For ambiguous input prompts (such as a single click), this will often + produce better masks than a single prediction. If only a single + mask is needed, the model's predicted quality score can be used + to select the best mask. For non-ambiguous prompts, such as multiple + input prompts, multimask_output=False can give better results. + return_logits (bool): If true, returns un-thresholded masks logits + instead of a binary mask. + + Returns: + (torch.Tensor): The output masks in BxCxHxW format, where C is the + number of masks, and (H, W) is the original image size. + (torch.Tensor): An array of shape BxC containing the model's + predictions for the quality of each mask. + (torch.Tensor): An array of shape BxCxHxW, where C is the number + of masks and H=W=256. These low res logits can be passed to + a subsequent iteration as mask input. + """ + if not self._is_image_set: + raise RuntimeError( + "An image must be set with .set_image(...) before mask prediction." + ) + + if point_coords is not None: + concat_points = (point_coords, point_labels) + else: + concat_points = None + + # Embed prompts + if boxes is not None: + box_coords = boxes.reshape(-1, 2, 2) + box_labels = torch.tensor([[2, 3]], dtype=torch.int, device=boxes.device) + box_labels = box_labels.repeat(boxes.size(0), 1) + # we merge "boxes" and "points" into a single "concat_points" input (where + # boxes are added at the beginning) to sam_prompt_encoder + if concat_points is not None: + concat_coords = torch.cat([box_coords, concat_points[0]], dim=1) + concat_labels = torch.cat([box_labels, concat_points[1]], dim=1) + concat_points = (concat_coords, concat_labels) + else: + concat_points = (box_coords, box_labels) + + sparse_embeddings, dense_embeddings = self.model.sam_prompt_encoder( + points=concat_points, + boxes=None, + masks=mask_input, + ) + + # Predict masks + batched_mode = ( + concat_points is not None and concat_points[0].shape[0] > 1 + ) # multi object prediction + high_res_features = [ + feat_level[img_idx].unsqueeze(0) + for feat_level in self._features["high_res_feats"] + ] + low_res_masks, iou_predictions, _, _ = self.model.sam_mask_decoder( + image_embeddings=self._features["image_embed"][img_idx].unsqueeze(0), + image_pe=self.model.sam_prompt_encoder.get_dense_pe(), + sparse_prompt_embeddings=sparse_embeddings, + dense_prompt_embeddings=dense_embeddings, + multimask_output=multimask_output, + repeat_image=batched_mode, + high_res_features=high_res_features, + ) + + # Upscale the masks to the original image resolution + masks = self._transforms.postprocess_masks( + low_res_masks, self._orig_hw[img_idx] + ) + low_res_masks = torch.clamp(low_res_masks, -32.0, 32.0) + if not return_logits: + masks = masks > self.mask_threshold + + return masks, iou_predictions, low_res_masks + + def get_image_embedding(self) -> torch.Tensor: + """ + Returns the image embeddings for the currently set image, with + shape 1xCxHxW, where C is the embedding dimension and (H,W) are + the embedding spatial dimension of SAM (typically C=256, H=W=64). + """ + if not self._is_image_set: + raise RuntimeError( + "An image must be set with .set_image(...) to generate an embedding." + ) + assert ( + self._features is not None + ), "Features must exist if an image has been set." + return self._features["image_embed"] + + @property + def device(self) -> torch.device: + return self.model.device + + def reset_predictor(self) -> None: + """ + Resets the image embeddings and other state variables. + """ + self._is_image_set = False + self._features = None + self._orig_hw = None + self._is_batch = False diff --git a/py/sam2/sam2_video_predictor.py b/py/sam2/sam2_video_predictor.py new file mode 100644 index 0000000..9285f13 --- /dev/null +++ b/py/sam2/sam2_video_predictor.py @@ -0,0 +1,1154 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import warnings +from collections import OrderedDict + +import torch + +from tqdm import tqdm + +from ..sam2.modeling.sam2_base import NO_OBJ_SCORE, SAM2Base +from ..sam2.utils.misc import concat_points, fill_holes_in_mask_scores, load_video_frames + + +class SAM2VideoPredictor(SAM2Base): + """The predictor class to handle user interactions and manage inference states.""" + + def __init__( + self, + fill_hole_area=0, + # whether to apply non-overlapping constraints on the output object masks + non_overlap_masks=False, + # whether to clear non-conditioning memory of the surrounding frames (which may contain outdated information) after adding correction clicks; + # note that this would only apply to *single-object tracking* unless `clear_non_cond_mem_for_multi_obj` is also set to True) + clear_non_cond_mem_around_input=False, + # whether to also clear non-conditioning memory of the surrounding frames (only effective when `clear_non_cond_mem_around_input` is True). + clear_non_cond_mem_for_multi_obj=False, + # if `add_all_frames_to_correct_as_cond` is True, we also append to the conditioning frame list any frame that receives a later correction click + # if `add_all_frames_to_correct_as_cond` is False, we conditioning frame list to only use those initial conditioning frames + add_all_frames_to_correct_as_cond=False, + **kwargs, + ): + super().__init__(**kwargs) + self.fill_hole_area = fill_hole_area + self.non_overlap_masks = non_overlap_masks + self.clear_non_cond_mem_around_input = clear_non_cond_mem_around_input + self.clear_non_cond_mem_for_multi_obj = clear_non_cond_mem_for_multi_obj + self.add_all_frames_to_correct_as_cond = add_all_frames_to_correct_as_cond + + @torch.inference_mode() + def init_state( + self, + images, + video_height, + video_width, + device='cuda', + offload_video_to_cpu=False, + offload_state_to_cpu=False, + async_loading_frames=False, + ): + """Initialize a inference state.""" + # images, video_height, video_width = load_video_frames( + # video_path=video_path, + # image_size=self.image_size, + # offload_video_to_cpu=offload_video_to_cpu, + # async_loading_frames=async_loading_frames, + # ) + inference_state = {} + inference_state["images"] = images + inference_state["num_frames"] = len(images) + # whether to offload the video frames to CPU memory + # turning on this option saves the GPU memory with only a very small overhead + inference_state["offload_video_to_cpu"] = offload_video_to_cpu + # whether to offload the inference state to CPU memory + # turning on this option saves the GPU memory at the cost of a lower tracking fps + # (e.g. in a test case of 768x768 model, fps dropped from 27 to 24 when tracking one object + # and from 24 to 21 when tracking two objects) + inference_state["offload_state_to_cpu"] = offload_state_to_cpu + # the original video height and width, used for resizing final output scores + inference_state["video_height"] = video_height + inference_state["video_width"] = video_width + inference_state["device"] = torch.device(device) + if offload_state_to_cpu: + inference_state["storage_device"] = torch.device("cpu") + else: + inference_state["storage_device"] = torch.device(device) + # inputs on each frame + inference_state["point_inputs_per_obj"] = {} + inference_state["mask_inputs_per_obj"] = {} + # visual features on a small number of recently visited frames for quick interactions + inference_state["cached_features"] = {} + # values that don't change across frames (so we only need to hold one copy of them) + inference_state["constants"] = {} + # mapping between client-side object id and model-side object index + inference_state["obj_id_to_idx"] = OrderedDict() + inference_state["obj_idx_to_id"] = OrderedDict() + inference_state["obj_ids"] = [] + # A storage to hold the model's tracking results and states on each frame + inference_state["output_dict"] = { + "cond_frame_outputs": {}, # dict containing {frame_idx: } + "non_cond_frame_outputs": {}, # dict containing {frame_idx: } + } + # Slice (view) of each object tracking results, sharing the same memory with "output_dict" + inference_state["output_dict_per_obj"] = {} + # A temporary storage to hold new outputs when user interact with a frame + # to add clicks or mask (it's merged into "output_dict" before propagation starts) + inference_state["temp_output_dict_per_obj"] = {} + # Frames that already holds consolidated outputs from click or mask inputs + # (we directly use their consolidated outputs during tracking) + inference_state["consolidated_frame_inds"] = { + "cond_frame_outputs": set(), # set containing frame indices + "non_cond_frame_outputs": set(), # set containing frame indices + } + # metadata for each tracking frame (e.g. which direction it's tracked) + inference_state["tracking_has_started"] = False + inference_state["frames_already_tracked"] = {} + # Warm up the visual backbone and cache the image feature on frame 0 + self._get_image_feature(inference_state, frame_idx=0, batch_size=1) + return inference_state + + def _obj_id_to_idx(self, inference_state, obj_id): + """Map client-side object id to model-side object index.""" + obj_idx = inference_state["obj_id_to_idx"].get(obj_id, None) + if obj_idx is not None: + return obj_idx + + # This is a new object id not sent to the server before. We only allow adding + # new objects *before* the tracking starts. + allow_new_object = not inference_state["tracking_has_started"] + if allow_new_object: + # get the next object slot + obj_idx = len(inference_state["obj_id_to_idx"]) + inference_state["obj_id_to_idx"][obj_id] = obj_idx + inference_state["obj_idx_to_id"][obj_idx] = obj_id + inference_state["obj_ids"] = list(inference_state["obj_id_to_idx"]) + # set up input and output structures for this object + inference_state["point_inputs_per_obj"][obj_idx] = {} + inference_state["mask_inputs_per_obj"][obj_idx] = {} + inference_state["output_dict_per_obj"][obj_idx] = { + "cond_frame_outputs": {}, # dict containing {frame_idx: } + "non_cond_frame_outputs": {}, # dict containing {frame_idx: } + } + inference_state["temp_output_dict_per_obj"][obj_idx] = { + "cond_frame_outputs": {}, # dict containing {frame_idx: } + "non_cond_frame_outputs": {}, # dict containing {frame_idx: } + } + return obj_idx + else: + raise RuntimeError( + f"Cannot add new object id {obj_id} after tracking starts. " + f"All existing object ids: {inference_state['obj_ids']}. " + f"Please call 'reset_state' to restart from scratch." + ) + + def _obj_idx_to_id(self, inference_state, obj_idx): + """Map model-side object index to client-side object id.""" + return inference_state["obj_idx_to_id"][obj_idx] + + def _get_obj_num(self, inference_state): + """Get the total number of unique object ids received so far in this session.""" + return len(inference_state["obj_idx_to_id"]) + + @torch.inference_mode() + def add_new_points_or_box( + self, + inference_state, + frame_idx, + obj_id, + points=None, + labels=None, + clear_old_points=True, + normalize_coords=True, + box=None, + ): + """Add new points to a frame.""" + obj_idx = self._obj_id_to_idx(inference_state, obj_id) + point_inputs_per_frame = inference_state["point_inputs_per_obj"][obj_idx] + mask_inputs_per_frame = inference_state["mask_inputs_per_obj"][obj_idx] + + if (points is not None) != (labels is not None): + raise ValueError("points and labels must be provided together") + if points is None and box is None: + raise ValueError("at least one of points or box must be provided as input") + + if points is None: + points = torch.zeros(0, 2, dtype=torch.float32) + elif not isinstance(points, torch.Tensor): + points = torch.tensor(points, dtype=torch.float32) + if labels is None: + labels = torch.zeros(0, dtype=torch.int32) + elif not isinstance(labels, torch.Tensor): + labels = torch.tensor(labels, dtype=torch.int32) + if points.dim() == 2: + points = points.unsqueeze(0) # add batch dimension + if labels.dim() == 1: + labels = labels.unsqueeze(0) # add batch dimension + + # If `box` is provided, we add it as the first two points with labels 2 and 3 + # along with the user-provided points (consistent with how SAM 2 is trained). + if box is not None: + if not clear_old_points: + raise ValueError( + "cannot add box without clearing old points, since " + "box prompt must be provided before any point prompt " + "(please use clear_old_points=True instead)" + ) + if inference_state["tracking_has_started"]: + warnings.warn( + "You are adding a box after tracking starts. SAM 2 may not always be " + "able to incorporate a box prompt for *refinement*. If you intend to " + "use box prompt as an *initial* input before tracking, please call " + "'reset_state' on the inference state to restart from scratch.", + category=UserWarning, + stacklevel=2, + ) + if not isinstance(box, torch.Tensor): + box = torch.tensor(box, dtype=torch.float32, device=points.device) + box_coords = box.reshape(1, 2, 2) + box_labels = torch.tensor([2, 3], dtype=torch.int32, device=labels.device) + box_labels = box_labels.reshape(1, 2) + points = torch.cat([box_coords, points], dim=1) + labels = torch.cat([box_labels, labels], dim=1) + + if normalize_coords: + video_H = inference_state["video_height"] + video_W = inference_state["video_width"] + points = points / torch.tensor([video_W, video_H]).to(points.device) + # scale the (normalized) coordinates by the model's internal image size + points = points * self.image_size + points = points.to(inference_state["device"]) + labels = labels.to(inference_state["device"]) + + if not clear_old_points: + point_inputs = point_inputs_per_frame.get(frame_idx, None) + else: + point_inputs = None + point_inputs = concat_points(point_inputs, points, labels) + + point_inputs_per_frame[frame_idx] = point_inputs + mask_inputs_per_frame.pop(frame_idx, None) + # If this frame hasn't been tracked before, we treat it as an initial conditioning + # frame, meaning that the inputs points are to generate segments on this frame without + # using any memory from other frames, like in SAM. Otherwise (if it has been tracked), + # the input points will be used to correct the already tracked masks. + is_init_cond_frame = frame_idx not in inference_state["frames_already_tracked"] + # whether to track in reverse time order + if is_init_cond_frame: + reverse = False + else: + reverse = inference_state["frames_already_tracked"][frame_idx]["reverse"] + obj_output_dict = inference_state["output_dict_per_obj"][obj_idx] + obj_temp_output_dict = inference_state["temp_output_dict_per_obj"][obj_idx] + # Add a frame to conditioning output if it's an initial conditioning frame or + # if the model sees all frames receiving clicks/mask as conditioning frames. + is_cond = is_init_cond_frame or self.add_all_frames_to_correct_as_cond + storage_key = "cond_frame_outputs" if is_cond else "non_cond_frame_outputs" + + # Get any previously predicted mask logits on this object and feed it along with + # the new clicks into the SAM mask decoder. + prev_sam_mask_logits = None + # lookup temporary output dict first, which contains the most recent output + # (if not found, then lookup conditioning and non-conditioning frame output) + prev_out = obj_temp_output_dict[storage_key].get(frame_idx) + if prev_out is None: + prev_out = obj_output_dict["cond_frame_outputs"].get(frame_idx) + if prev_out is None: + prev_out = obj_output_dict["non_cond_frame_outputs"].get(frame_idx) + + if prev_out is not None and prev_out["pred_masks"] is not None: + prev_sam_mask_logits = prev_out["pred_masks"].to(inference_state["device"],non_blocking=True) + # Clamp the scale of prev_sam_mask_logits to avoid rare numerical issues. + prev_sam_mask_logits = torch.clamp(prev_sam_mask_logits, -32.0, 32.0) + current_out, _ = self._run_single_frame_inference( + inference_state=inference_state, + output_dict=obj_output_dict, # run on the slice of a single object + frame_idx=frame_idx, + batch_size=1, # run on the slice of a single object + is_init_cond_frame=is_init_cond_frame, + point_inputs=point_inputs, + mask_inputs=None, + reverse=reverse, + # Skip the memory encoder when adding clicks or mask. We execute the memory encoder + # at the beginning of `propagate_in_video` (after user finalize their clicks). This + # allows us to enforce non-overlapping constraints on all objects before encoding + # them into memory. + run_mem_encoder=False, + prev_sam_mask_logits=prev_sam_mask_logits, + ) + # Add the output to the output dict (to be used as future memory) + obj_temp_output_dict[storage_key][frame_idx] = current_out + + # Resize the output mask to the original video resolution + obj_ids = inference_state["obj_ids"] + consolidated_out = self._consolidate_temp_output_across_obj( + inference_state, + frame_idx, + is_cond=is_cond, + run_mem_encoder=False, + consolidate_at_video_res=True, + ) + _, video_res_masks = self._get_orig_video_res_output( + inference_state, consolidated_out["pred_masks_video_res"] + ) + return frame_idx, obj_ids, video_res_masks + + def add_new_points(self, *args, **kwargs): + """Deprecated method. Please use `add_new_points_or_box` instead.""" + return self.add_new_points_or_box(*args, **kwargs) + + @torch.inference_mode() + def add_new_mask( + self, + inference_state, + frame_idx, + obj_id, + mask, + ): + """Add new mask to a frame.""" + obj_idx = self._obj_id_to_idx(inference_state, obj_id) + point_inputs_per_frame = inference_state["point_inputs_per_obj"][obj_idx] + mask_inputs_per_frame = inference_state["mask_inputs_per_obj"][obj_idx] + + if not isinstance(mask, torch.Tensor): + mask = torch.tensor(mask, dtype=torch.bool) + assert mask.dim() == 2 + mask_H, mask_W = mask.shape + mask_inputs_orig = mask[None, None] # add batch and channel dimension + mask_inputs_orig = mask_inputs_orig.float().to(inference_state["device"]) + + # resize the mask if it doesn't match the model's image size + if mask_H != self.image_size or mask_W != self.image_size: + mask_inputs = torch.nn.functional.interpolate( + mask_inputs_orig, + size=(self.image_size, self.image_size), + align_corners=False, + mode="bilinear", + antialias=True, # use antialias for downsampling + ) + mask_inputs = (mask_inputs >= 0.5).float() + else: + mask_inputs = mask_inputs_orig + + mask_inputs_per_frame[frame_idx] = mask_inputs + point_inputs_per_frame.pop(frame_idx, None) + # If this frame hasn't been tracked before, we treat it as an initial conditioning + # frame, meaning that the inputs points are to generate segments on this frame without + # using any memory from other frames, like in SAM. Otherwise (if it has been tracked), + # the input points will be used to correct the already tracked masks. + is_init_cond_frame = frame_idx not in inference_state["frames_already_tracked"] + # whether to track in reverse time order + if is_init_cond_frame: + reverse = False + else: + reverse = inference_state["frames_already_tracked"][frame_idx]["reverse"] + obj_output_dict = inference_state["output_dict_per_obj"][obj_idx] + obj_temp_output_dict = inference_state["temp_output_dict_per_obj"][obj_idx] + # Add a frame to conditioning output if it's an initial conditioning frame or + # if the model sees all frames receiving clicks/mask as conditioning frames. + is_cond = is_init_cond_frame or self.add_all_frames_to_correct_as_cond + storage_key = "cond_frame_outputs" if is_cond else "non_cond_frame_outputs" + + current_out, _ = self._run_single_frame_inference( + inference_state=inference_state, + output_dict=obj_output_dict, # run on the slice of a single object + frame_idx=frame_idx, + batch_size=1, # run on the slice of a single object + is_init_cond_frame=is_init_cond_frame, + point_inputs=None, + mask_inputs=mask_inputs, + reverse=reverse, + # Skip the memory encoder when adding clicks or mask. We execute the memory encoder + # at the beginning of `propagate_in_video` (after user finalize their clicks). This + # allows us to enforce non-overlapping constraints on all objects before encoding + # them into memory. + run_mem_encoder=False, + ) + # Add the output to the output dict (to be used as future memory) + obj_temp_output_dict[storage_key][frame_idx] = current_out + + # Resize the output mask to the original video resolution + obj_ids = inference_state["obj_ids"] + consolidated_out = self._consolidate_temp_output_across_obj( + inference_state, + frame_idx, + is_cond=is_cond, + run_mem_encoder=False, + consolidate_at_video_res=True, + ) + _, video_res_masks = self._get_orig_video_res_output( + inference_state, consolidated_out["pred_masks_video_res"] + ) + return frame_idx, obj_ids, video_res_masks + + def _get_orig_video_res_output(self, inference_state, any_res_masks): + """ + Resize the object scores to the original video resolution (video_res_masks) + and apply non-overlapping constraints for final output. + """ + device = inference_state["device"] + video_H = inference_state["video_height"] + video_W = inference_state["video_width"] + any_res_masks = any_res_masks.to(device, non_blocking=True) + if any_res_masks.shape[-2:] == (video_H, video_W): + video_res_masks = any_res_masks + else: + video_res_masks = torch.nn.functional.interpolate( + any_res_masks, + size=(video_H, video_W), + mode="bilinear", + align_corners=False, + ) + if self.non_overlap_masks: + video_res_masks = self._apply_non_overlapping_constraints(video_res_masks) + return any_res_masks, video_res_masks + + def _consolidate_temp_output_across_obj( + self, + inference_state, + frame_idx, + is_cond, + run_mem_encoder, + consolidate_at_video_res=False, + ): + """ + Consolidate the per-object temporary outputs in `temp_output_dict_per_obj` on + a frame into a single output for all objects, including + 1) fill any missing objects either from `output_dict_per_obj` (if they exist in + `output_dict_per_obj` for this frame) or leave them as placeholder values + (if they don't exist in `output_dict_per_obj` for this frame); + 2) if specified, rerun memory encoder after apply non-overlapping constraints + on the object scores. + """ + batch_size = self._get_obj_num(inference_state) + storage_key = "cond_frame_outputs" if is_cond else "non_cond_frame_outputs" + # Optionally, we allow consolidating the temporary outputs at the original + # video resolution (to provide a better editing experience for mask prompts). + if consolidate_at_video_res: + assert not run_mem_encoder, "memory encoder cannot run at video resolution" + consolidated_H = inference_state["video_height"] + consolidated_W = inference_state["video_width"] + consolidated_mask_key = "pred_masks_video_res" + else: + consolidated_H = consolidated_W = self.image_size // 4 + consolidated_mask_key = "pred_masks" + + # Initialize `consolidated_out`. Its "maskmem_features" and "maskmem_pos_enc" + # will be added when rerunning the memory encoder after applying non-overlapping + # constraints to object scores. Its "pred_masks" are prefilled with a large + # negative value (NO_OBJ_SCORE) to represent missing objects. + consolidated_out = { + "maskmem_features": None, + "maskmem_pos_enc": None, + consolidated_mask_key: torch.full( + size=(batch_size, 1, consolidated_H, consolidated_W), + fill_value=NO_OBJ_SCORE, + dtype=torch.float32, + device=inference_state["storage_device"], + ), + "obj_ptr": torch.full( + size=(batch_size, self.hidden_dim), + fill_value=NO_OBJ_SCORE, + dtype=torch.float32, + device=inference_state["device"], + ), + "object_score_logits": torch.full( + size=(batch_size, 1), + # default to 10.0 for object_score_logits, i.e. assuming the object is + # present as sigmoid(10)=1, same as in `predict_masks` of `MaskDecoder` + fill_value=10.0, + dtype=torch.float32, + device=inference_state["device"], + ), + } + empty_mask_ptr = None + for obj_idx in range(batch_size): + obj_temp_output_dict = inference_state["temp_output_dict_per_obj"][obj_idx] + obj_output_dict = inference_state["output_dict_per_obj"][obj_idx] + out = obj_temp_output_dict[storage_key].get(frame_idx, None) + # If the object doesn't appear in "temp_output_dict_per_obj" on this frame, + # we fall back and look up its previous output in "output_dict_per_obj". + # We look up both "cond_frame_outputs" and "non_cond_frame_outputs" in + # "output_dict_per_obj" to find a previous output for this object. + if out is None: + out = obj_output_dict["cond_frame_outputs"].get(frame_idx, None) + if out is None: + out = obj_output_dict["non_cond_frame_outputs"].get(frame_idx, None) + # If the object doesn't appear in "output_dict_per_obj" either, we skip it + # and leave its mask scores to the default scores (i.e. the NO_OBJ_SCORE + # placeholder above) and set its object pointer to be a dummy pointer. + if out is None: + # Fill in dummy object pointers for those objects without any inputs or + # tracking outcomes on this frame (only do it under `run_mem_encoder=True`, + # i.e. when we need to build the memory for tracking). + if run_mem_encoder: + if empty_mask_ptr is None: + empty_mask_ptr = self._get_empty_mask_ptr( + inference_state, frame_idx + ) + # fill object pointer with a dummy pointer (based on an empty mask) + consolidated_out["obj_ptr"][obj_idx : obj_idx + 1] = empty_mask_ptr + continue + # Add the temporary object output mask to consolidated output mask + obj_mask = out["pred_masks"] + consolidated_pred_masks = consolidated_out[consolidated_mask_key] + if obj_mask.shape[-2:] == consolidated_pred_masks.shape[-2:]: + consolidated_pred_masks[obj_idx : obj_idx + 1] = obj_mask + else: + # Resize first if temporary object mask has a different resolution + resized_obj_mask = torch.nn.functional.interpolate( + obj_mask, + size=consolidated_pred_masks.shape[-2:], + mode="bilinear", + align_corners=False, + ) + consolidated_pred_masks[obj_idx : obj_idx + 1] = resized_obj_mask + consolidated_out["obj_ptr"][obj_idx : obj_idx + 1] = out["obj_ptr"] + consolidated_out["object_score_logits"][obj_idx : obj_idx + 1] = out[ + "object_score_logits" + ] + + # Optionally, apply non-overlapping constraints on the consolidated scores + # and rerun the memory encoder + if run_mem_encoder: + device = inference_state["device"] + high_res_masks = torch.nn.functional.interpolate( + consolidated_out["pred_masks"].to(device, non_blocking=True), + size=(self.image_size, self.image_size), + mode="bilinear", + align_corners=False, + ) + if self.non_overlap_masks_for_mem_enc: + high_res_masks = self._apply_non_overlapping_constraints(high_res_masks) + maskmem_features, maskmem_pos_enc = self._run_memory_encoder( + inference_state=inference_state, + frame_idx=frame_idx, + batch_size=batch_size, + high_res_masks=high_res_masks, + object_score_logits=consolidated_out["object_score_logits"], + is_mask_from_pts=True, # these frames are what the user interacted with + ) + consolidated_out["maskmem_features"] = maskmem_features + consolidated_out["maskmem_pos_enc"] = maskmem_pos_enc + + return consolidated_out + + def _get_empty_mask_ptr(self, inference_state, frame_idx): + """Get a dummy object pointer based on an empty mask on the current frame.""" + # A dummy (empty) mask with a single object + batch_size = 1 + mask_inputs = torch.zeros( + (batch_size, 1, self.image_size, self.image_size), + dtype=torch.float32, + device=inference_state["device"], + ) + + # Retrieve correct image features + ( + _, + _, + current_vision_feats, + current_vision_pos_embeds, + feat_sizes, + ) = self._get_image_feature(inference_state, frame_idx, batch_size) + + # Feed the empty mask and image feature above to get a dummy object pointer + current_out = self.track_step( + frame_idx=frame_idx, + is_init_cond_frame=True, + current_vision_feats=current_vision_feats, + current_vision_pos_embeds=current_vision_pos_embeds, + feat_sizes=feat_sizes, + point_inputs=None, + mask_inputs=mask_inputs, + output_dict={}, + num_frames=inference_state["num_frames"], + track_in_reverse=False, + run_mem_encoder=False, + prev_sam_mask_logits=None, + ) + return current_out["obj_ptr"] + + @torch.inference_mode() + def propagate_in_video_preflight(self, inference_state): + """Prepare inference_state and consolidate temporary outputs before tracking.""" + # Tracking has started and we don't allow adding new objects until session is reset. + inference_state["tracking_has_started"] = True + batch_size = self._get_obj_num(inference_state) + + # Consolidate per-object temporary outputs in "temp_output_dict_per_obj" and + # add them into "output_dict". + temp_output_dict_per_obj = inference_state["temp_output_dict_per_obj"] + output_dict = inference_state["output_dict"] + # "consolidated_frame_inds" contains indices of those frames where consolidated + # temporary outputs have been added (either in this call or any previous calls + # to `propagate_in_video_preflight`). + consolidated_frame_inds = inference_state["consolidated_frame_inds"] + for is_cond in [False, True]: + # Separately consolidate conditioning and non-conditioning temp outputs + storage_key = "cond_frame_outputs" if is_cond else "non_cond_frame_outputs" + # Find all the frames that contain temporary outputs for any objects + # (these should be the frames that have just received clicks for mask inputs + # via `add_new_points_or_box` or `add_new_mask`) + temp_frame_inds = set() + for obj_temp_output_dict in temp_output_dict_per_obj.values(): + temp_frame_inds.update(obj_temp_output_dict[storage_key].keys()) + consolidated_frame_inds[storage_key].update(temp_frame_inds) + # consolidate the temporary output across all objects on this frame + for frame_idx in temp_frame_inds: + consolidated_out = self._consolidate_temp_output_across_obj( + inference_state, frame_idx, is_cond=is_cond, run_mem_encoder=True + ) + # merge them into "output_dict" and also create per-object slices + output_dict[storage_key][frame_idx] = consolidated_out + self._add_output_per_object( + inference_state, frame_idx, consolidated_out, storage_key + ) + clear_non_cond_mem = self.clear_non_cond_mem_around_input and ( + self.clear_non_cond_mem_for_multi_obj or batch_size <= 1 + ) + if clear_non_cond_mem: + # clear non-conditioning memory of the surrounding frames + self._clear_non_cond_mem_around_input(inference_state, frame_idx) + + # clear temporary outputs in `temp_output_dict_per_obj` + for obj_temp_output_dict in temp_output_dict_per_obj.values(): + obj_temp_output_dict[storage_key].clear() + + # edge case: if an output is added to "cond_frame_outputs", we remove any prior + # output on the same frame in "non_cond_frame_outputs" + for frame_idx in output_dict["cond_frame_outputs"]: + output_dict["non_cond_frame_outputs"].pop(frame_idx, None) + for obj_output_dict in inference_state["output_dict_per_obj"].values(): + for frame_idx in obj_output_dict["cond_frame_outputs"]: + obj_output_dict["non_cond_frame_outputs"].pop(frame_idx, None) + for frame_idx in consolidated_frame_inds["cond_frame_outputs"]: + assert frame_idx in output_dict["cond_frame_outputs"] + consolidated_frame_inds["non_cond_frame_outputs"].discard(frame_idx) + + # Make sure that the frame indices in "consolidated_frame_inds" are exactly those frames + # with either points or mask inputs (which should be true under a correct workflow). + all_consolidated_frame_inds = ( + consolidated_frame_inds["cond_frame_outputs"] + | consolidated_frame_inds["non_cond_frame_outputs"] + ) + input_frames_inds = set() + for point_inputs_per_frame in inference_state["point_inputs_per_obj"].values(): + input_frames_inds.update(point_inputs_per_frame.keys()) + for mask_inputs_per_frame in inference_state["mask_inputs_per_obj"].values(): + input_frames_inds.update(mask_inputs_per_frame.keys()) + assert all_consolidated_frame_inds == input_frames_inds + + @torch.inference_mode() + def propagate_in_video( + self, + inference_state, + start_frame_idx=None, + max_frame_num_to_track=None, + reverse=False, + ): + """Propagate the input points across frames to track in the entire video.""" + self.propagate_in_video_preflight(inference_state) + + output_dict = inference_state["output_dict"] + consolidated_frame_inds = inference_state["consolidated_frame_inds"] + obj_ids = inference_state["obj_ids"] + num_frames = inference_state["num_frames"] + batch_size = self._get_obj_num(inference_state) + if len(output_dict["cond_frame_outputs"]) == 0: + raise RuntimeError("No points are provided; please add points first") + clear_non_cond_mem = self.clear_non_cond_mem_around_input and ( + self.clear_non_cond_mem_for_multi_obj or batch_size <= 1 + ) + + # set start index, end index, and processing order + if start_frame_idx is None: + # default: start from the earliest frame with input points + start_frame_idx = min(output_dict["cond_frame_outputs"]) + if max_frame_num_to_track is None: + # default: track all the frames in the video + max_frame_num_to_track = num_frames + if reverse: + end_frame_idx = max(start_frame_idx - max_frame_num_to_track, 0) + if start_frame_idx > 0: + processing_order = range(start_frame_idx, end_frame_idx - 1, -1) + else: + processing_order = [] # skip reverse tracking if starting from frame 0 + else: + end_frame_idx = min( + start_frame_idx + max_frame_num_to_track, num_frames - 1 + ) + processing_order = range(start_frame_idx, end_frame_idx + 1) + + for frame_idx in tqdm(processing_order, desc="propagate in video"): + # We skip those frames already in consolidated outputs (these are frames + # that received input clicks or mask). Note that we cannot directly run + # batched forward on them via `_run_single_frame_inference` because the + # number of clicks on each object might be different. + if frame_idx in consolidated_frame_inds["cond_frame_outputs"]: + storage_key = "cond_frame_outputs" + current_out = output_dict[storage_key][frame_idx] + pred_masks = current_out["pred_masks"] + if clear_non_cond_mem: + # clear non-conditioning memory of the surrounding frames + self._clear_non_cond_mem_around_input(inference_state, frame_idx) + elif frame_idx in consolidated_frame_inds["non_cond_frame_outputs"]: + storage_key = "non_cond_frame_outputs" + current_out = output_dict[storage_key][frame_idx] + pred_masks = current_out["pred_masks"] + else: + storage_key = "non_cond_frame_outputs" + current_out, pred_masks = self._run_single_frame_inference( + inference_state=inference_state, + output_dict=output_dict, + frame_idx=frame_idx, + batch_size=batch_size, + is_init_cond_frame=False, + point_inputs=None, + mask_inputs=None, + reverse=reverse, + run_mem_encoder=True, + ) + output_dict[storage_key][frame_idx] = current_out + # Create slices of per-object outputs for subsequent interaction with each + # individual object after tracking. + self._add_output_per_object( + inference_state, frame_idx, current_out, storage_key + ) + inference_state["frames_already_tracked"][frame_idx] = {"reverse": reverse} + + # Resize the output mask to the original video resolution (we directly use + # the mask scores on GPU for output to avoid any CPU conversion in between) + _, video_res_masks = self._get_orig_video_res_output( + inference_state, pred_masks + ) + yield frame_idx, obj_ids, video_res_masks + + def _add_output_per_object( + self, inference_state, frame_idx, current_out, storage_key + ): + """ + Split a multi-object output into per-object output slices and add them into + `output_dict_per_obj`. The resulting slices share the same tensor storage. + """ + maskmem_features = current_out["maskmem_features"] + assert maskmem_features is None or isinstance(maskmem_features, torch.Tensor) + + maskmem_pos_enc = current_out["maskmem_pos_enc"] + assert maskmem_pos_enc is None or isinstance(maskmem_pos_enc, list) + + output_dict_per_obj = inference_state["output_dict_per_obj"] + for obj_idx, obj_output_dict in output_dict_per_obj.items(): + obj_slice = slice(obj_idx, obj_idx + 1) + obj_out = { + "maskmem_features": None, + "maskmem_pos_enc": None, + "pred_masks": current_out["pred_masks"][obj_slice], + "obj_ptr": current_out["obj_ptr"][obj_slice], + "object_score_logits": current_out["object_score_logits"][obj_slice], + } + if maskmem_features is not None: + obj_out["maskmem_features"] = maskmem_features[obj_slice] + if maskmem_pos_enc is not None: + obj_out["maskmem_pos_enc"] = [x[obj_slice] for x in maskmem_pos_enc] + obj_output_dict[storage_key][frame_idx] = obj_out + + @torch.inference_mode() + def clear_all_prompts_in_frame( + self, inference_state, frame_idx, obj_id, need_output=True + ): + """Remove all input points or mask in a specific frame for a given object.""" + obj_idx = self._obj_id_to_idx(inference_state, obj_id) + + # Clear the conditioning information on the given frame + inference_state["point_inputs_per_obj"][obj_idx].pop(frame_idx, None) + inference_state["mask_inputs_per_obj"][obj_idx].pop(frame_idx, None) + + temp_output_dict_per_obj = inference_state["temp_output_dict_per_obj"] + temp_output_dict_per_obj[obj_idx]["cond_frame_outputs"].pop(frame_idx, None) + temp_output_dict_per_obj[obj_idx]["non_cond_frame_outputs"].pop(frame_idx, None) + + # Check and see if there are still any inputs left on this frame + batch_size = self._get_obj_num(inference_state) + frame_has_input = False + for obj_idx2 in range(batch_size): + if frame_idx in inference_state["point_inputs_per_obj"][obj_idx2]: + frame_has_input = True + break + if frame_idx in inference_state["mask_inputs_per_obj"][obj_idx2]: + frame_has_input = True + break + + # If this frame has no remaining inputs for any objects, we further clear its + # conditioning frame status + if not frame_has_input: + output_dict = inference_state["output_dict"] + consolidated_frame_inds = inference_state["consolidated_frame_inds"] + consolidated_frame_inds["cond_frame_outputs"].discard(frame_idx) + consolidated_frame_inds["non_cond_frame_outputs"].discard(frame_idx) + # Remove the frame's conditioning output (possibly downgrading it to non-conditioning) + out = output_dict["cond_frame_outputs"].pop(frame_idx, None) + if out is not None: + # The frame is not a conditioning frame anymore since it's not receiving inputs, + # so we "downgrade" its output (if exists) to a non-conditioning frame output. + output_dict["non_cond_frame_outputs"][frame_idx] = out + inference_state["frames_already_tracked"].pop(frame_idx, None) + # Similarly, do it for the sliced output on each object. + for obj_idx2 in range(batch_size): + obj_output_dict = inference_state["output_dict_per_obj"][obj_idx2] + obj_out = obj_output_dict["cond_frame_outputs"].pop(frame_idx, None) + if obj_out is not None: + obj_output_dict["non_cond_frame_outputs"][frame_idx] = obj_out + + # If all the conditioning frames have been removed, we also clear the tracking outputs + if len(output_dict["cond_frame_outputs"]) == 0: + self._reset_tracking_results(inference_state) + + if not need_output: + return + # Finally, output updated masks per object (after removing the inputs above) + obj_ids = inference_state["obj_ids"] + is_cond = any( + frame_idx in obj_temp_output_dict["cond_frame_outputs"] + for obj_temp_output_dict in temp_output_dict_per_obj.values() + ) + consolidated_out = self._consolidate_temp_output_across_obj( + inference_state, + frame_idx, + is_cond=is_cond, + run_mem_encoder=False, + consolidate_at_video_res=True, + ) + _, video_res_masks = self._get_orig_video_res_output( + inference_state, consolidated_out["pred_masks_video_res"] + ) + return frame_idx, obj_ids, video_res_masks + + @torch.inference_mode() + def reset_state(self, inference_state): + """Remove all input points or mask in all frames throughout the video.""" + self._reset_tracking_results(inference_state) + # Remove all object ids + inference_state["obj_id_to_idx"].clear() + inference_state["obj_idx_to_id"].clear() + inference_state["obj_ids"].clear() + inference_state["point_inputs_per_obj"].clear() + inference_state["mask_inputs_per_obj"].clear() + inference_state["output_dict_per_obj"].clear() + inference_state["temp_output_dict_per_obj"].clear() + + def _reset_tracking_results(self, inference_state): + """Reset all tracking inputs and results across the videos.""" + for v in inference_state["point_inputs_per_obj"].values(): + v.clear() + for v in inference_state["mask_inputs_per_obj"].values(): + v.clear() + for v in inference_state["output_dict_per_obj"].values(): + v["cond_frame_outputs"].clear() + v["non_cond_frame_outputs"].clear() + for v in inference_state["temp_output_dict_per_obj"].values(): + v["cond_frame_outputs"].clear() + v["non_cond_frame_outputs"].clear() + inference_state["output_dict"]["cond_frame_outputs"].clear() + inference_state["output_dict"]["non_cond_frame_outputs"].clear() + inference_state["consolidated_frame_inds"]["cond_frame_outputs"].clear() + inference_state["consolidated_frame_inds"]["non_cond_frame_outputs"].clear() + inference_state["tracking_has_started"] = False + inference_state["frames_already_tracked"].clear() + + def _get_image_feature(self, inference_state, frame_idx, batch_size): + """Compute the image features on a given frame.""" + # Look up in the cache first + image, backbone_out = inference_state["cached_features"].get( + frame_idx, (None, None) + ) + if backbone_out is None: + # Cache miss -- we will run inference on a single image + image = inference_state["images"][frame_idx].to(inference_state["device"]).float().unsqueeze(0) + backbone_out = self.forward_image(image) + # Cache the most recent frame's feature (for repeated interactions with + # a frame; we can use an LRU cache for more frames in the future). + inference_state["cached_features"] = {frame_idx: (image, backbone_out)} + + # expand the features to have the same dimension as the number of objects + expanded_image = image.expand(batch_size, -1, -1, -1) + expanded_backbone_out = { + "backbone_fpn": backbone_out["backbone_fpn"].copy(), + "vision_pos_enc": backbone_out["vision_pos_enc"].copy(), + } + for i, feat in enumerate(expanded_backbone_out["backbone_fpn"]): + expanded_backbone_out["backbone_fpn"][i] = feat.expand( + batch_size, -1, -1, -1 + ) + for i, pos in enumerate(expanded_backbone_out["vision_pos_enc"]): + pos = pos.expand(batch_size, -1, -1, -1) + expanded_backbone_out["vision_pos_enc"][i] = pos + + features = self._prepare_backbone_features(expanded_backbone_out) + features = (expanded_image,) + features + return features + + def _run_single_frame_inference( + self, + inference_state, + output_dict, + frame_idx, + batch_size, + is_init_cond_frame, + point_inputs, + mask_inputs, + reverse, + run_mem_encoder, + prev_sam_mask_logits=None, + ): + """Run tracking on a single frame based on current inputs and previous memory.""" + # Retrieve correct image features + ( + _, + _, + current_vision_feats, + current_vision_pos_embeds, + feat_sizes, + ) = self._get_image_feature(inference_state, frame_idx, batch_size) + + # point and mask should not appear as input simultaneously on the same frame + assert point_inputs is None or mask_inputs is None + current_out = self.track_step( + frame_idx=frame_idx, + is_init_cond_frame=is_init_cond_frame, + current_vision_feats=current_vision_feats, + current_vision_pos_embeds=current_vision_pos_embeds, + feat_sizes=feat_sizes, + point_inputs=point_inputs, + mask_inputs=mask_inputs, + output_dict=output_dict, + num_frames=inference_state["num_frames"], + track_in_reverse=reverse, + run_mem_encoder=run_mem_encoder, + prev_sam_mask_logits=prev_sam_mask_logits, + ) + + # optionally offload the output to CPU memory to save GPU space + storage_device = inference_state["storage_device"] + maskmem_features = current_out["maskmem_features"] + if maskmem_features is not None: + maskmem_features = maskmem_features.to(torch.bfloat16) + maskmem_features = maskmem_features.to(storage_device, non_blocking=True) + pred_masks_gpu = current_out["pred_masks"] + # potentially fill holes in the predicted masks + if self.fill_hole_area > 0: + pred_masks_gpu = fill_holes_in_mask_scores( + pred_masks_gpu, self.fill_hole_area + ) + pred_masks = pred_masks_gpu.to(storage_device, non_blocking=True) + # "maskmem_pos_enc" is the same across frames, so we only need to store one copy of it + maskmem_pos_enc = self._get_maskmem_pos_enc(inference_state, current_out) + # object pointer is a small tensor, so we always keep it on GPU memory for fast access + obj_ptr = current_out["obj_ptr"] + object_score_logits = current_out["object_score_logits"] + # make a compact version of this frame's output to reduce the state size + compact_current_out = { + "maskmem_features": maskmem_features, + "maskmem_pos_enc": maskmem_pos_enc, + "pred_masks": pred_masks, + "obj_ptr": obj_ptr, + "object_score_logits": object_score_logits, + } + return compact_current_out, pred_masks_gpu + + def _run_memory_encoder( + self, + inference_state, + frame_idx, + batch_size, + high_res_masks, + object_score_logits, + is_mask_from_pts, + ): + """ + Run the memory encoder on `high_res_masks`. This is usually after applying + non-overlapping constraints to object scores. Since their scores changed, their + memory also need to be computed again with the memory encoder. + """ + # Retrieve correct image features + _, _, current_vision_feats, _, feat_sizes = self._get_image_feature( + inference_state, frame_idx, batch_size + ) + maskmem_features, maskmem_pos_enc = self._encode_new_memory( + current_vision_feats=current_vision_feats, + feat_sizes=feat_sizes, + pred_masks_high_res=high_res_masks, + object_score_logits=object_score_logits, + is_mask_from_pts=is_mask_from_pts, + ) + + # optionally offload the output to CPU memory to save GPU space + storage_device = inference_state["storage_device"] + maskmem_features = maskmem_features.to(torch.bfloat16) + maskmem_features = maskmem_features.to(storage_device, non_blocking=True) + # "maskmem_pos_enc" is the same across frames, so we only need to store one copy of it + maskmem_pos_enc = self._get_maskmem_pos_enc( + inference_state, {"maskmem_pos_enc": maskmem_pos_enc} + ) + return maskmem_features, maskmem_pos_enc + + def _get_maskmem_pos_enc(self, inference_state, current_out): + """ + `maskmem_pos_enc` is the same across frames and objects, so we cache it as + a constant in the inference session to reduce session storage size. + """ + model_constants = inference_state["constants"] + # "out_maskmem_pos_enc" should be either a list of tensors or None + out_maskmem_pos_enc = current_out["maskmem_pos_enc"] + if out_maskmem_pos_enc is not None: + if "maskmem_pos_enc" not in model_constants: + assert isinstance(out_maskmem_pos_enc, list) + # only take the slice for one object, since it's same across objects + maskmem_pos_enc = [x[0:1].clone() for x in out_maskmem_pos_enc] + model_constants["maskmem_pos_enc"] = maskmem_pos_enc + else: + maskmem_pos_enc = model_constants["maskmem_pos_enc"] + # expand the cached maskmem_pos_enc to the actual batch size + batch_size = out_maskmem_pos_enc[0].size(0) + expanded_maskmem_pos_enc = [ + x.expand(batch_size, -1, -1, -1) for x in maskmem_pos_enc + ] + else: + expanded_maskmem_pos_enc = None + return expanded_maskmem_pos_enc + + @torch.inference_mode() + def remove_object(self, inference_state, obj_id, strict=False, need_output=True): + """ + Remove an object id from the tracking state. If strict is True, we check whether + the object id actually exists and raise an error if it doesn't exist. + """ + old_obj_idx_to_rm = inference_state["obj_id_to_idx"].get(obj_id, None) + updated_frames = [] + # Check whether this object_id to remove actually exists and possibly raise an error. + if old_obj_idx_to_rm is None: + if not strict: + return inference_state["obj_ids"], updated_frames + raise RuntimeError( + f"Cannot remove object id {obj_id} as it doesn't exist. " + f"All existing object ids: {inference_state['obj_ids']}." + ) + + # If this is the only remaining object id, we simply reset the state. + if len(inference_state["obj_id_to_idx"]) == 1: + self.reset_state(inference_state) + return inference_state["obj_ids"], updated_frames + + # There are still remaining objects after removing this object id. In this case, + # we need to delete the object storage from inference state tensors. + # Step 0: clear the input on those frames where this object id has point or mask input + # (note that this step is required as it might downgrade conditioning frames to + # non-conditioning ones) + obj_input_frames_inds = set() + obj_input_frames_inds.update( + inference_state["point_inputs_per_obj"][old_obj_idx_to_rm] + ) + obj_input_frames_inds.update( + inference_state["mask_inputs_per_obj"][old_obj_idx_to_rm] + ) + for frame_idx in obj_input_frames_inds: + self.clear_all_prompts_in_frame( + inference_state, frame_idx, obj_id, need_output=False + ) + + # Step 1: Update the object id mapping (note that it must be done after Step 0, + # since Step 0 still requires the old object id mappings in inference_state) + old_obj_ids = inference_state["obj_ids"] + old_obj_inds = list(range(len(old_obj_ids))) + remain_old_obj_inds = old_obj_inds.copy() + remain_old_obj_inds.remove(old_obj_idx_to_rm) + new_obj_ids = [old_obj_ids[old_idx] for old_idx in remain_old_obj_inds] + new_obj_inds = list(range(len(new_obj_ids))) + # build new mappings + old_idx_to_new_idx = dict(zip(remain_old_obj_inds, new_obj_inds)) + inference_state["obj_id_to_idx"] = dict(zip(new_obj_ids, new_obj_inds)) + inference_state["obj_idx_to_id"] = dict(zip(new_obj_inds, new_obj_ids)) + inference_state["obj_ids"] = new_obj_ids + + # Step 2: For per-object tensor storage, we shift their obj_idx in the dict keys. + # (note that "consolidated_frame_inds" doesn't need to be updated in this step as + # it's already handled in Step 0) + def _map_keys(container): + new_kvs = [] + for k in old_obj_inds: + v = container.pop(k) + if k in old_idx_to_new_idx: + new_kvs.append((old_idx_to_new_idx[k], v)) + container.update(new_kvs) + + _map_keys(inference_state["point_inputs_per_obj"]) + _map_keys(inference_state["mask_inputs_per_obj"]) + _map_keys(inference_state["output_dict_per_obj"]) + _map_keys(inference_state["temp_output_dict_per_obj"]) + + # Step 3: For packed tensor storage, we index the remaining ids and rebuild the per-object slices. + def _slice_state(output_dict, storage_key): + for frame_idx, out in output_dict[storage_key].items(): + out["maskmem_features"] = out["maskmem_features"][remain_old_obj_inds] + out["maskmem_pos_enc"] = [ + x[remain_old_obj_inds] for x in out["maskmem_pos_enc"] + ] + # "maskmem_pos_enc" is the same across frames, so we only need to store one copy of it + out["maskmem_pos_enc"] = self._get_maskmem_pos_enc(inference_state, out) + out["pred_masks"] = out["pred_masks"][remain_old_obj_inds] + out["obj_ptr"] = out["obj_ptr"][remain_old_obj_inds] + out["object_score_logits"] = out["object_score_logits"][ + remain_old_obj_inds + ] + # also update the per-object slices + self._add_output_per_object( + inference_state, frame_idx, out, storage_key + ) + + _slice_state(inference_state["output_dict"], "cond_frame_outputs") + _slice_state(inference_state["output_dict"], "non_cond_frame_outputs") + + # Step 4: Further collect the outputs on those frames in `obj_input_frames_inds`, which + # could show an updated mask for objects previously occluded by the object being removed + if need_output: + temp_output_dict_per_obj = inference_state["temp_output_dict_per_obj"] + for frame_idx in obj_input_frames_inds: + is_cond = any( + frame_idx in obj_temp_output_dict["cond_frame_outputs"] + for obj_temp_output_dict in temp_output_dict_per_obj.values() + ) + consolidated_out = self._consolidate_temp_output_across_obj( + inference_state, + frame_idx, + is_cond=is_cond, + run_mem_encoder=False, + consolidate_at_video_res=True, + ) + _, video_res_masks = self._get_orig_video_res_output( + inference_state, consolidated_out["pred_masks_video_res"] + ) + updated_frames.append((frame_idx, video_res_masks)) + + return inference_state["obj_ids"], updated_frames + + def _clear_non_cond_mem_around_input(self, inference_state, frame_idx): + """ + Remove the non-conditioning memory around the input frame. When users provide + correction clicks, the surrounding frames' non-conditioning memories can still + contain outdated object appearance information and could confuse the model. + + This method clears those non-conditioning memories surrounding the interacted + frame to avoid giving the model both old and new information about the object. + """ + r = self.memory_temporal_stride_for_eval + frame_idx_begin = frame_idx - r * self.num_maskmem + frame_idx_end = frame_idx + r * self.num_maskmem + output_dict = inference_state["output_dict"] + non_cond_frame_outputs = output_dict["non_cond_frame_outputs"] + for t in range(frame_idx_begin, frame_idx_end + 1): + non_cond_frame_outputs.pop(t, None) + for obj_output_dict in inference_state["output_dict_per_obj"].values(): + obj_output_dict["non_cond_frame_outputs"].pop(t, None) diff --git a/py/sam2/utils/__init__.py b/py/sam2/utils/__init__.py new file mode 100644 index 0000000..5277f46 --- /dev/null +++ b/py/sam2/utils/__init__.py @@ -0,0 +1,5 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. diff --git a/py/sam2/utils/amg.py b/py/sam2/utils/amg.py new file mode 100644 index 0000000..9868429 --- /dev/null +++ b/py/sam2/utils/amg.py @@ -0,0 +1,348 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import math +from copy import deepcopy +from itertools import product +from typing import Any, Dict, Generator, ItemsView, List, Tuple + +import numpy as np +import torch + +# Very lightly adapted from https://github.com/facebookresearch/segment-anything/blob/main/segment_anything/utils/amg.py + + +class MaskData: + """ + A structure for storing masks and their related data in batched format. + Implements basic filtering and concatenation. + """ + + def __init__(self, **kwargs) -> None: + for v in kwargs.values(): + assert isinstance( + v, (list, np.ndarray, torch.Tensor) + ), "MaskData only supports list, numpy arrays, and torch tensors." + self._stats = dict(**kwargs) + + def __setitem__(self, key: str, item: Any) -> None: + assert isinstance( + item, (list, np.ndarray, torch.Tensor) + ), "MaskData only supports list, numpy arrays, and torch tensors." + self._stats[key] = item + + def __delitem__(self, key: str) -> None: + del self._stats[key] + + def __getitem__(self, key: str) -> Any: + return self._stats[key] + + def items(self) -> ItemsView[str, Any]: + return self._stats.items() + + def filter(self, keep: torch.Tensor) -> None: + for k, v in self._stats.items(): + if v is None: + self._stats[k] = None + elif isinstance(v, torch.Tensor): + self._stats[k] = v[torch.as_tensor(keep, device=v.device)] + elif isinstance(v, np.ndarray): + self._stats[k] = v[keep.detach().cpu().numpy()] + elif isinstance(v, list) and keep.dtype == torch.bool: + self._stats[k] = [a for i, a in enumerate(v) if keep[i]] + elif isinstance(v, list): + self._stats[k] = [v[i] for i in keep] + else: + raise TypeError(f"MaskData key {k} has an unsupported type {type(v)}.") + + def cat(self, new_stats: "MaskData") -> None: + for k, v in new_stats.items(): + if k not in self._stats or self._stats[k] is None: + self._stats[k] = deepcopy(v) + elif isinstance(v, torch.Tensor): + self._stats[k] = torch.cat([self._stats[k], v], dim=0) + elif isinstance(v, np.ndarray): + self._stats[k] = np.concatenate([self._stats[k], v], axis=0) + elif isinstance(v, list): + self._stats[k] = self._stats[k] + deepcopy(v) + else: + raise TypeError(f"MaskData key {k} has an unsupported type {type(v)}.") + + def to_numpy(self) -> None: + for k, v in self._stats.items(): + if isinstance(v, torch.Tensor): + self._stats[k] = v.float().detach().cpu().numpy() + + +def is_box_near_crop_edge( + boxes: torch.Tensor, crop_box: List[int], orig_box: List[int], atol: float = 20.0 +) -> torch.Tensor: + """Filter masks at the edge of a crop, but not at the edge of the original image.""" + crop_box_torch = torch.as_tensor(crop_box, dtype=torch.float, device=boxes.device) + orig_box_torch = torch.as_tensor(orig_box, dtype=torch.float, device=boxes.device) + boxes = uncrop_boxes_xyxy(boxes, crop_box).float() + near_crop_edge = torch.isclose(boxes, crop_box_torch[None, :], atol=atol, rtol=0) + near_image_edge = torch.isclose(boxes, orig_box_torch[None, :], atol=atol, rtol=0) + near_crop_edge = torch.logical_and(near_crop_edge, ~near_image_edge) + return torch.any(near_crop_edge, dim=1) + + +def box_xyxy_to_xywh(box_xyxy: torch.Tensor) -> torch.Tensor: + box_xywh = deepcopy(box_xyxy) + box_xywh[2] = box_xywh[2] - box_xywh[0] + box_xywh[3] = box_xywh[3] - box_xywh[1] + return box_xywh + + +def batch_iterator(batch_size: int, *args) -> Generator[List[Any], None, None]: + assert len(args) > 0 and all( + len(a) == len(args[0]) for a in args + ), "Batched iteration must have inputs of all the same size." + n_batches = len(args[0]) // batch_size + int(len(args[0]) % batch_size != 0) + for b in range(n_batches): + yield [arg[b * batch_size : (b + 1) * batch_size] for arg in args] + + +def mask_to_rle_pytorch(tensor: torch.Tensor) -> List[Dict[str, Any]]: + """ + Encodes masks to an uncompressed RLE, in the format expected by + pycoco tools. + """ + # Put in fortran order and flatten h,w + b, h, w = tensor.shape + tensor = tensor.permute(0, 2, 1).flatten(1) + + # Compute change indices + diff = tensor[:, 1:] ^ tensor[:, :-1] + change_indices = diff.nonzero() + + # Encode run length + out = [] + for i in range(b): + cur_idxs = change_indices[change_indices[:, 0] == i, 1] + cur_idxs = torch.cat( + [ + torch.tensor([0], dtype=cur_idxs.dtype, device=cur_idxs.device), + cur_idxs + 1, + torch.tensor([h * w], dtype=cur_idxs.dtype, device=cur_idxs.device), + ] + ) + btw_idxs = cur_idxs[1:] - cur_idxs[:-1] + counts = [] if tensor[i, 0] == 0 else [0] + counts.extend(btw_idxs.detach().cpu().tolist()) + out.append({"size": [h, w], "counts": counts}) + return out + + +def rle_to_mask(rle: Dict[str, Any]) -> np.ndarray: + """Compute a binary mask from an uncompressed RLE.""" + h, w = rle["size"] + mask = np.empty(h * w, dtype=bool) + idx = 0 + parity = False + for count in rle["counts"]: + mask[idx : idx + count] = parity + idx += count + parity ^= True + mask = mask.reshape(w, h) + return mask.transpose() # Put in C order + + +def area_from_rle(rle: Dict[str, Any]) -> int: + return sum(rle["counts"][1::2]) + + +def calculate_stability_score( + masks: torch.Tensor, mask_threshold: float, threshold_offset: float +) -> torch.Tensor: + """ + Computes the stability score for a batch of masks. The stability + score is the IoU between the binary masks obtained by thresholding + the predicted mask logits at high and low values. + """ + # One mask is always contained inside the other. + # Save memory by preventing unnecessary cast to torch.int64 + intersections = ( + (masks > (mask_threshold + threshold_offset)) + .sum(-1, dtype=torch.int16) + .sum(-1, dtype=torch.int32) + ) + unions = ( + (masks > (mask_threshold - threshold_offset)) + .sum(-1, dtype=torch.int16) + .sum(-1, dtype=torch.int32) + ) + return intersections / unions + + +def build_point_grid(n_per_side: int) -> np.ndarray: + """Generates a 2D grid of points evenly spaced in [0,1]x[0,1].""" + offset = 1 / (2 * n_per_side) + points_one_side = np.linspace(offset, 1 - offset, n_per_side) + points_x = np.tile(points_one_side[None, :], (n_per_side, 1)) + points_y = np.tile(points_one_side[:, None], (1, n_per_side)) + points = np.stack([points_x, points_y], axis=-1).reshape(-1, 2) + return points + + +def build_all_layer_point_grids( + n_per_side: int, n_layers: int, scale_per_layer: int +) -> List[np.ndarray]: + """Generates point grids for all crop layers.""" + points_by_layer = [] + for i in range(n_layers + 1): + n_points = int(n_per_side / (scale_per_layer**i)) + points_by_layer.append(build_point_grid(n_points)) + return points_by_layer + + +def generate_crop_boxes( + im_size: Tuple[int, ...], n_layers: int, overlap_ratio: float +) -> Tuple[List[List[int]], List[int]]: + """ + Generates a list of crop boxes of different sizes. Each layer + has (2**i)**2 boxes for the ith layer. + """ + crop_boxes, layer_idxs = [], [] + im_h, im_w = im_size + short_side = min(im_h, im_w) + + # Original image + crop_boxes.append([0, 0, im_w, im_h]) + layer_idxs.append(0) + + def crop_len(orig_len, n_crops, overlap): + return int(math.ceil((overlap * (n_crops - 1) + orig_len) / n_crops)) + + for i_layer in range(n_layers): + n_crops_per_side = 2 ** (i_layer + 1) + overlap = int(overlap_ratio * short_side * (2 / n_crops_per_side)) + + crop_w = crop_len(im_w, n_crops_per_side, overlap) + crop_h = crop_len(im_h, n_crops_per_side, overlap) + + crop_box_x0 = [int((crop_w - overlap) * i) for i in range(n_crops_per_side)] + crop_box_y0 = [int((crop_h - overlap) * i) for i in range(n_crops_per_side)] + + # Crops in XYWH format + for x0, y0 in product(crop_box_x0, crop_box_y0): + box = [x0, y0, min(x0 + crop_w, im_w), min(y0 + crop_h, im_h)] + crop_boxes.append(box) + layer_idxs.append(i_layer + 1) + + return crop_boxes, layer_idxs + + +def uncrop_boxes_xyxy(boxes: torch.Tensor, crop_box: List[int]) -> torch.Tensor: + x0, y0, _, _ = crop_box + offset = torch.tensor([[x0, y0, x0, y0]], device=boxes.device) + # Check if boxes has a channel dimension + if len(boxes.shape) == 3: + offset = offset.unsqueeze(1) + return boxes + offset + + +def uncrop_points(points: torch.Tensor, crop_box: List[int]) -> torch.Tensor: + x0, y0, _, _ = crop_box + offset = torch.tensor([[x0, y0]], device=points.device) + # Check if points has a channel dimension + if len(points.shape) == 3: + offset = offset.unsqueeze(1) + return points + offset + + +def uncrop_masks( + masks: torch.Tensor, crop_box: List[int], orig_h: int, orig_w: int +) -> torch.Tensor: + x0, y0, x1, y1 = crop_box + if x0 == 0 and y0 == 0 and x1 == orig_w and y1 == orig_h: + return masks + # Coordinate transform masks + pad_x, pad_y = orig_w - (x1 - x0), orig_h - (y1 - y0) + pad = (x0, pad_x - x0, y0, pad_y - y0) + return torch.nn.functional.pad(masks, pad, value=0) + + +def remove_small_regions( + mask: np.ndarray, area_thresh: float, mode: str +) -> Tuple[np.ndarray, bool]: + """ + Removes small disconnected regions and holes in a mask. Returns the + mask and an indicator of if the mask has been modified. + """ + import cv2 # type: ignore + + assert mode in ["holes", "islands"] + correct_holes = mode == "holes" + working_mask = (correct_holes ^ mask).astype(np.uint8) + n_labels, regions, stats, _ = cv2.connectedComponentsWithStats(working_mask, 8) + sizes = stats[:, -1][1:] # Row 0 is background label + small_regions = [i + 1 for i, s in enumerate(sizes) if s < area_thresh] + if len(small_regions) == 0: + return mask, False + fill_labels = [0] + small_regions + if not correct_holes: + fill_labels = [i for i in range(n_labels) if i not in fill_labels] + # If every region is below threshold, keep largest + if len(fill_labels) == 0: + fill_labels = [int(np.argmax(sizes)) + 1] + mask = np.isin(regions, fill_labels) + return mask, True + + +def coco_encode_rle(uncompressed_rle: Dict[str, Any]) -> Dict[str, Any]: + from pycocotools import mask as mask_utils # type: ignore + + h, w = uncompressed_rle["size"] + rle = mask_utils.frPyObjects(uncompressed_rle, h, w) + rle["counts"] = rle["counts"].decode("utf-8") # Necessary to serialize with json + return rle + + +def batched_mask_to_box(masks: torch.Tensor) -> torch.Tensor: + """ + Calculates boxes in XYXY format around masks. Return [0,0,0,0] for + an empty mask. For input shape C1xC2x...xHxW, the output shape is C1xC2x...x4. + """ + # torch.max below raises an error on empty inputs, just skip in this case + if torch.numel(masks) == 0: + return torch.zeros(*masks.shape[:-2], 4, device=masks.device) + + # Normalize shape to CxHxW + shape = masks.shape + h, w = shape[-2:] + if len(shape) > 2: + masks = masks.flatten(0, -3) + else: + masks = masks.unsqueeze(0) + + # Get top and bottom edges + in_height, _ = torch.max(masks, dim=-1) + in_height_coords = in_height * torch.arange(h, device=in_height.device)[None, :] + bottom_edges, _ = torch.max(in_height_coords, dim=-1) + in_height_coords = in_height_coords + h * (~in_height) + top_edges, _ = torch.min(in_height_coords, dim=-1) + + # Get left and right edges + in_width, _ = torch.max(masks, dim=-2) + in_width_coords = in_width * torch.arange(w, device=in_width.device)[None, :] + right_edges, _ = torch.max(in_width_coords, dim=-1) + in_width_coords = in_width_coords + w * (~in_width) + left_edges, _ = torch.min(in_width_coords, dim=-1) + + # If the mask is empty the right edge will be to the left of the left edge. + # Replace these boxes with [0, 0, 0, 0] + empty_filter = (right_edges < left_edges) | (bottom_edges < top_edges) + out = torch.stack([left_edges, top_edges, right_edges, bottom_edges], dim=-1) + out = out * (~empty_filter).unsqueeze(-1) + + # Return to original shape + if len(shape) > 2: + out = out.reshape(*shape[:-2], 4) + else: + out = out[0] + + return out diff --git a/py/sam2/utils/misc.py b/py/sam2/utils/misc.py new file mode 100644 index 0000000..abb888a --- /dev/null +++ b/py/sam2/utils/misc.py @@ -0,0 +1,349 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import os +import warnings +from threading import Thread + +import numpy as np +import torch +from PIL import Image +from tqdm import tqdm +import platform + +def get_sdpa_settings(): + if torch.cuda.is_available(): + old_gpu = torch.cuda.get_device_properties(0).major < 7 + # only use Flash Attention on Ampere (8.0) or newer GPUs + use_flash_attn = torch.cuda.get_device_properties(0).major >= 8 and platform.system() == 'Linux' + if not use_flash_attn: + warnings.warn( + "Flash Attention is disabled as it requires a GPU with Ampere (8.0) CUDA capability.", + category=UserWarning, + stacklevel=2, + ) + # keep math kernel for PyTorch versions before 2.2 (Flash Attention v2 is only + # available on PyTorch 2.2+, while Flash Attention v1 cannot handle all cases) + pytorch_version = tuple(int(v) for v in torch.__version__.split(".")[:2]) + if pytorch_version < (2, 2): + warnings.warn( + f"You are using PyTorch {torch.__version__} without Flash Attention v2 support. " + "Consider upgrading to PyTorch 2.2+ for Flash Attention v2 (which could be faster).", + category=UserWarning, + stacklevel=2, + ) + math_kernel_on = pytorch_version < (2, 2) or not use_flash_attn + else: + old_gpu = True + use_flash_attn = False + math_kernel_on = True + + return old_gpu, use_flash_attn, math_kernel_on + + +def get_connected_components(mask): + """ + Get the connected components (8-connectivity) of binary masks of shape (N, 1, H, W). + + Inputs: + - mask: A binary mask tensor of shape (N, 1, H, W), where 1 is foreground and 0 is + background. + + Outputs: + - labels: A tensor of shape (N, 1, H, W) containing the connected component labels + for foreground pixels and 0 for background pixels. + - counts: A tensor of shape (N, 1, H, W) containing the area of the connected + components for foreground pixels and 0 for background pixels. + """ + from ...sam2 import _C + + return _C.get_connected_componnets(mask.to(torch.uint8).contiguous()) + + +def mask_to_box(masks: torch.Tensor): + """ + compute bounding box given an input mask + + Inputs: + - masks: [B, 1, H, W] masks, dtype=torch.Tensor + + Returns: + - box_coords: [B, 1, 4], contains (x, y) coordinates of top left and bottom right box corners, dtype=torch.Tensor + """ + B, _, h, w = masks.shape + device = masks.device + xs = torch.arange(w, device=device, dtype=torch.int32) + ys = torch.arange(h, device=device, dtype=torch.int32) + grid_xs, grid_ys = torch.meshgrid(xs, ys, indexing="xy") + grid_xs = grid_xs[None, None, ...].expand(B, 1, h, w) + grid_ys = grid_ys[None, None, ...].expand(B, 1, h, w) + min_xs, _ = torch.min(torch.where(masks, grid_xs, w).flatten(-2), dim=-1) + max_xs, _ = torch.max(torch.where(masks, grid_xs, -1).flatten(-2), dim=-1) + min_ys, _ = torch.min(torch.where(masks, grid_ys, h).flatten(-2), dim=-1) + max_ys, _ = torch.max(torch.where(masks, grid_ys, -1).flatten(-2), dim=-1) + bbox_coords = torch.stack((min_xs, min_ys, max_xs, max_ys), dim=-1) + + return bbox_coords + + +def _load_img_as_tensor(img_path, image_size): + img_pil = Image.open(img_path) + img_np = np.array(img_pil.convert("RGB").resize((image_size, image_size))) + if img_np.dtype == np.uint8: # np.uint8 is expected for JPEG images + img_np = img_np / 255.0 + else: + raise RuntimeError(f"Unknown image dtype: {img_np.dtype} on {img_path}") + img = torch.from_numpy(img_np).permute(2, 0, 1) + video_width, video_height = img_pil.size # the original video size + return img, video_height, video_width + + +class AsyncVideoFrameLoader: + """ + A list of video frames to be load asynchronously without blocking session start. + """ + + def __init__( + self, + img_paths, + image_size, + offload_video_to_cpu, + img_mean, + img_std, + compute_device, + ): + self.img_paths = img_paths + self.image_size = image_size + self.offload_video_to_cpu = offload_video_to_cpu + self.img_mean = img_mean + self.img_std = img_std + # items in `self.images` will be loaded asynchronously + self.images = [None] * len(img_paths) + # catch and raise any exceptions in the async loading thread + self.exception = None + # video_height and video_width be filled when loading the first image + self.video_height = None + self.video_width = None + self.compute_device = compute_device + + # load the first frame to fill video_height and video_width and also + # to cache it (since it's most likely where the user will click) + self.__getitem__(0) + + # load the rest of frames asynchronously without blocking the session start + def _load_frames(): + try: + for n in tqdm(range(len(self.images)), desc="frame loading (JPEG)"): + self.__getitem__(n) + except Exception as e: + self.exception = e + + self.thread = Thread(target=_load_frames, daemon=True) + self.thread.start() + + def __getitem__(self, index): + if self.exception is not None: + raise RuntimeError("Failure in frame loading thread") from self.exception + + img = self.images[index] + if img is not None: + return img + + img, video_height, video_width = _load_img_as_tensor( + self.img_paths[index], self.image_size + ) + self.video_height = video_height + self.video_width = video_width + # normalize by mean and std + img -= self.img_mean + img /= self.img_std + if not self.offload_video_to_cpu: + img = img.to(self.compute_device, non_blocking=True) + self.images[index] = img + return img + + def __len__(self): + return len(self.images) + + +def load_video_frames( + video_path, + image_size, + offload_video_to_cpu, + img_mean=(0.485, 0.456, 0.406), + img_std=(0.229, 0.224, 0.225), + async_loading_frames=False, + compute_device=torch.device("cuda"), +): + """ + Load the video frames from video_path. The frames are resized to image_size as in + the model and are loaded to GPU if offload_video_to_cpu=False. This is used by the demo. + """ + is_bytes = isinstance(video_path, bytes) + is_str = isinstance(video_path, str) + is_mp4_path = is_str and os.path.splitext(video_path)[-1] in [".mp4", ".MP4"] + if is_bytes or is_mp4_path: + return load_video_frames_from_video_file( + video_path=video_path, + image_size=image_size, + offload_video_to_cpu=offload_video_to_cpu, + img_mean=img_mean, + img_std=img_std, + compute_device=compute_device, + ) + elif is_str and os.path.isdir(video_path): + return load_video_frames_from_jpg_images( + video_path=video_path, + image_size=image_size, + offload_video_to_cpu=offload_video_to_cpu, + img_mean=img_mean, + img_std=img_std, + async_loading_frames=async_loading_frames, + compute_device=compute_device, + ) + else: + raise NotImplementedError( + "Only MP4 video and JPEG folder are supported at this moment" + ) + + +def load_video_frames_from_jpg_images( + video_path, + image_size, + offload_video_to_cpu, + img_mean=(0.485, 0.456, 0.406), + img_std=(0.229, 0.224, 0.225), + async_loading_frames=False, + compute_device=torch.device("cuda"), +): + """ + Load the video frames from a directory of JPEG files (".jpg" format). + + The frames are resized to image_size x image_size and are loaded to GPU if + `offload_video_to_cpu` is `False` and to CPU if `offload_video_to_cpu` is `True`. + + You can load a frame asynchronously by setting `async_loading_frames` to `True`. + """ + if isinstance(video_path, str) and os.path.isdir(video_path): + jpg_folder = video_path + else: + raise NotImplementedError( + "Only JPEG frames are supported at this moment. For video files, you may use " + "ffmpeg (https://ffmpeg.org/) to extract frames into a folder of JPEG files, such as \n" + "```\n" + "ffmpeg -i .mp4 -q:v 2 -start_number 0 /'%05d.jpg'\n" + "```\n" + "where `-q:v` generates high-quality JPEG frames and `-start_number 0` asks " + "ffmpeg to start the JPEG file from 00000.jpg." + ) + + frame_names = [ + p + for p in os.listdir(jpg_folder) + if os.path.splitext(p)[-1] in [".jpg", ".jpeg", ".JPG", ".JPEG"] + ] + frame_names.sort(key=lambda p: int(os.path.splitext(p)[0])) + num_frames = len(frame_names) + if num_frames == 0: + raise RuntimeError(f"no images found in {jpg_folder}") + img_paths = [os.path.join(jpg_folder, frame_name) for frame_name in frame_names] + img_mean = torch.tensor(img_mean, dtype=torch.float32)[:, None, None] + img_std = torch.tensor(img_std, dtype=torch.float32)[:, None, None] + + if async_loading_frames: + lazy_images = AsyncVideoFrameLoader( + img_paths, + image_size, + offload_video_to_cpu, + img_mean, + img_std, + compute_device, + ) + return lazy_images, lazy_images.video_height, lazy_images.video_width + + images = torch.zeros(num_frames, 3, image_size, image_size, dtype=torch.float32) + for n, img_path in enumerate(tqdm(img_paths, desc="frame loading (JPEG)")): + images[n], video_height, video_width = _load_img_as_tensor(img_path, image_size) + if not offload_video_to_cpu: + images = images.to(compute_device) + img_mean = img_mean.to(compute_device) + img_std = img_std.to(compute_device) + # normalize by mean and std + images -= img_mean + images /= img_std + return images, video_height, video_width + + +def load_video_frames_from_video_file( + video_path, + image_size, + offload_video_to_cpu, + img_mean=(0.485, 0.456, 0.406), + img_std=(0.229, 0.224, 0.225), + compute_device=torch.device("cuda"), +): + """Load the video frames from a video file.""" + import decord + + img_mean = torch.tensor(img_mean, dtype=torch.float32)[:, None, None] + img_std = torch.tensor(img_std, dtype=torch.float32)[:, None, None] + # Get the original video height and width + decord.bridge.set_bridge("torch") + video_height, video_width, _ = decord.VideoReader(video_path).next().shape + # Iterate over all frames in the video + images = [] + for frame in decord.VideoReader(video_path, width=image_size, height=image_size): + images.append(frame.permute(2, 0, 1)) + + images = torch.stack(images, dim=0).float() / 255.0 + if not offload_video_to_cpu: + images = images.to(compute_device) + img_mean = img_mean.to(compute_device) + img_std = img_std.to(compute_device) + # normalize by mean and std + images -= img_mean + images /= img_std + return images, video_height, video_width + + +def fill_holes_in_mask_scores(mask, max_area): + """ + A post processor to fill small holes in mask scores with area under `max_area`. + """ + # Holes are those connected components in background with area <= self.max_area + # (background regions are those with mask scores <= 0) + assert max_area > 0, "max_area must be positive" + + input_mask = mask + try: + labels, areas = get_connected_components(mask <= 0) + is_hole = (labels > 0) & (areas <= max_area) + # We fill holes with a small positive mask score (0.1) to change them to foreground. + mask = torch.where(is_hole, 0.1, mask) + except Exception as e: + # Skip the post-processing step on removing small holes if the CUDA kernel fails + warnings.warn( + f"{e}\n\nSkipping the post-processing step due to the error above. You can " + "still use SAM 2 and it's OK to ignore the error above, although some post-processing " + "functionality may be limited (which doesn't affect the results in most cases; see " + "https://github.com/facebookresearch/sam2/blob/main/INSTALL.md).", + category=UserWarning, + stacklevel=2, + ) + mask = input_mask + + return mask + + +def concat_points(old_point_inputs, new_points, new_labels): + """Add new points and labels to previous point inputs (add at the end).""" + if old_point_inputs is None: + points, labels = new_points, new_labels + else: + points = torch.cat([old_point_inputs["point_coords"], new_points], dim=1) + labels = torch.cat([old_point_inputs["point_labels"], new_labels], dim=1) + + return {"point_coords": points, "point_labels": labels} diff --git a/py/sam2/utils/transforms.py b/py/sam2/utils/transforms.py new file mode 100644 index 0000000..428a569 --- /dev/null +++ b/py/sam2/utils/transforms.py @@ -0,0 +1,106 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import torch +import torch.nn as nn +import torch.nn.functional as F +from torchvision.transforms import Normalize, Resize, ToTensor + + +class SAM2Transforms(nn.Module): + def __init__( + self, resolution, mask_threshold, max_hole_area=0.0, max_sprinkle_area=0.0 + ): + """ + Transforms for SAM2. + """ + super().__init__() + self.resolution = resolution + self.mask_threshold = mask_threshold + self.max_hole_area = max_hole_area + self.max_sprinkle_area = max_sprinkle_area + self.mean = [0.485, 0.456, 0.406] + self.std = [0.229, 0.224, 0.225] + self.to_tensor = ToTensor() + try: + self.transforms = torch.jit.script( + nn.Sequential( + Resize((self.resolution, self.resolution)), + Normalize(self.mean, self.std), + ) + ) + except Exception as e: + print(f"Failed to torch jit script transforms: {e}, falling back to normal transforms") + self.transforms = nn.Sequential( + Resize((self.resolution, self.resolution)), + Normalize(self.mean, self.std), + ) + + def __call__(self, x): + x = self.to_tensor(x) + return self.transforms(x) + + def forward_batch(self, img_list): + img_batch = [self.transforms(self.to_tensor(img)) for img in img_list] + img_batch = torch.stack(img_batch, dim=0) + return img_batch + + def transform_coords( + self, coords: torch.Tensor, normalize=False, orig_hw=None + ) -> torch.Tensor: + """ + Expects a torch tensor with length 2 in the last dimension. The coordinates can be in absolute image or normalized coordinates, + If the coords are in absolute image coordinates, normalize should be set to True and original image size is required. + + Returns + Un-normalized coordinates in the range of [0, 1] which is expected by the SAM2 model. + """ + if normalize: + assert orig_hw is not None + h, w = orig_hw + coords = coords.clone() + coords[..., 0] = coords[..., 0] / w + coords[..., 1] = coords[..., 1] / h + + coords = coords * self.resolution # unnormalize coords + return coords + + def transform_boxes( + self, boxes: torch.Tensor, normalize=False, orig_hw=None + ) -> torch.Tensor: + """ + Expects a tensor of shape Bx4. The coordinates can be in absolute image or normalized coordinates, + if the coords are in absolute image coordinates, normalize should be set to True and original image size is required. + """ + boxes = self.transform_coords(boxes.reshape(-1, 2, 2), normalize, orig_hw) + return boxes + + def postprocess_masks(self, masks: torch.Tensor, orig_hw) -> torch.Tensor: + """ + Perform PostProcessing on output masks. + """ + #from ...sam2.utils.misc import get_connected_components + + masks = masks.float() + # if self.max_hole_area > 0: + # # Holes are those connected components in background with area <= self.fill_hole_area + # # (background regions are those with mask scores <= self.mask_threshold) + # mask_flat = masks.flatten(0, 1).unsqueeze(1) # flatten as 1-channel image + # labels, areas = get_connected_components(mask_flat <= self.mask_threshold) + # is_hole = (labels > 0) & (areas <= self.max_hole_area) + # is_hole = is_hole.reshape_as(masks) + # # We fill holes with a small positive mask score (10.0) to change them to foreground. + # masks = torch.where(is_hole, self.mask_threshold + 10.0, masks) + + # if self.max_sprinkle_area > 0: + # labels, areas = get_connected_components(mask_flat > self.mask_threshold) + # is_hole = (labels > 0) & (areas <= self.max_sprinkle_area) + # is_hole = is_hole.reshape_as(masks) + # # We fill holes with negative mask score (-10.0) to change them to background. + # masks = torch.where(is_hole, self.mask_threshold - 10.0, masks) + + masks = F.interpolate(masks, orig_hw, mode="bilinear", align_corners=False) + return masks diff --git a/py/sam_2_ultra.py b/py/sam_2_ultra.py new file mode 100644 index 0000000..64f6c58 --- /dev/null +++ b/py/sam_2_ultra.py @@ -0,0 +1,795 @@ +# layerstyle advance + +import cv2 +import torch +import yaml +import comfy.model_management as mm +from comfy.utils import ProgressBar +from comfy.utils import load_torch_file +from contextlib import nullcontext +from .imagefunc import * + +def bboxes2coordinates(bboxes:list) -> list: + coordinates = [] + for bbox in bboxes: + coordinates.append(((bbox[0]+bbox[2]) // 2, (bbox[1]+bbox[3]) // 2)) + return coordinates + +def load_model(model_path, model_cfg_path, segmentor, dtype, device): + # import yaml + from .sam2.modeling.sam2_base import SAM2Base + from .sam2.modeling.backbones.image_encoder import ImageEncoder + from .sam2.modeling.backbones.hieradet import Hiera + from .sam2.modeling.backbones.image_encoder import FpnNeck + from .sam2.modeling.position_encoding import PositionEmbeddingSine + from .sam2.modeling.memory_attention import MemoryAttention, MemoryAttentionLayer + from .sam2.modeling.sam.transformer import RoPEAttention + from .sam2.modeling.memory_encoder import MemoryEncoder, MaskDownSampler, Fuser, CXBlock + + from .sam2.sam2_image_predictor import SAM2ImagePredictor + from .sam2.sam2_video_predictor import SAM2VideoPredictor + from .sam2.automatic_mask_generator import SAM2AutomaticMaskGenerator + # from comfy.utils import load_torch_file + + # Load the YAML configuration + with open(model_cfg_path, 'r') as file: + config = yaml.safe_load(file) + + # Extract the model configuration + model_config = config['model'] + + # Instantiate the image encoder components + trunk_config = model_config['image_encoder']['trunk'] + neck_config = model_config['image_encoder']['neck'] + position_encoding_config = neck_config['position_encoding'] + + position_encoding = PositionEmbeddingSine( + num_pos_feats=position_encoding_config['num_pos_feats'], + normalize=position_encoding_config['normalize'], + scale=position_encoding_config['scale'], + temperature=position_encoding_config['temperature'] + ) + + neck = FpnNeck( + position_encoding=position_encoding, + d_model=neck_config['d_model'], + backbone_channel_list=neck_config['backbone_channel_list'], + fpn_top_down_levels=neck_config['fpn_top_down_levels'], + fpn_interp_model=neck_config['fpn_interp_model'] + ) + + keys_to_include = ['embed_dim', 'num_heads', 'global_att_blocks', 'window_pos_embed_bkg_spatial_size', 'stages'] + trunk_kwargs = {key: trunk_config[key] for key in keys_to_include if key in trunk_config} + trunk = Hiera(**trunk_kwargs) + + image_encoder = ImageEncoder( + scalp=model_config['image_encoder']['scalp'], + trunk=trunk, + neck=neck + ) + # Instantiate the memory attention components + memory_attention_layer_config = config['model']['memory_attention']['layer'] + self_attention_config = memory_attention_layer_config['self_attention'] + cross_attention_config = memory_attention_layer_config['cross_attention'] + + self_attention = RoPEAttention( + rope_theta=self_attention_config['rope_theta'], + feat_sizes=self_attention_config['feat_sizes'], + embedding_dim=self_attention_config['embedding_dim'], + num_heads=self_attention_config['num_heads'], + downsample_rate=self_attention_config['downsample_rate'], + dropout=self_attention_config['dropout'] + ) + + cross_attention = RoPEAttention( + rope_theta=cross_attention_config['rope_theta'], + feat_sizes=cross_attention_config['feat_sizes'], + rope_k_repeat=cross_attention_config['rope_k_repeat'], + embedding_dim=cross_attention_config['embedding_dim'], + num_heads=cross_attention_config['num_heads'], + downsample_rate=cross_attention_config['downsample_rate'], + dropout=cross_attention_config['dropout'], + kv_in_dim=cross_attention_config['kv_in_dim'] + ) + + memory_attention_layer = MemoryAttentionLayer( + activation=memory_attention_layer_config['activation'], + dim_feedforward=memory_attention_layer_config['dim_feedforward'], + dropout=memory_attention_layer_config['dropout'], + pos_enc_at_attn=memory_attention_layer_config['pos_enc_at_attn'], + self_attention=self_attention, + d_model=memory_attention_layer_config['d_model'], + pos_enc_at_cross_attn_keys=memory_attention_layer_config['pos_enc_at_cross_attn_keys'], + pos_enc_at_cross_attn_queries=memory_attention_layer_config['pos_enc_at_cross_attn_queries'], + cross_attention=cross_attention + ) + + memory_attention = MemoryAttention( + d_model=config['model']['memory_attention']['d_model'], + pos_enc_at_input=config['model']['memory_attention']['pos_enc_at_input'], + layer=memory_attention_layer, + num_layers=config['model']['memory_attention']['num_layers'] + ) + + # Instantiate the memory encoder components + memory_encoder_config = config['model']['memory_encoder'] + position_encoding_mem_enc_config = memory_encoder_config['position_encoding'] + mask_downsampler_config = memory_encoder_config['mask_downsampler'] + fuser_layer_config = memory_encoder_config['fuser']['layer'] + + position_encoding_mem_enc = PositionEmbeddingSine( + num_pos_feats=position_encoding_mem_enc_config['num_pos_feats'], + normalize=position_encoding_mem_enc_config['normalize'], + scale=position_encoding_mem_enc_config['scale'], + temperature=position_encoding_mem_enc_config['temperature'] + ) + + mask_downsampler = MaskDownSampler( + kernel_size=mask_downsampler_config['kernel_size'], + stride=mask_downsampler_config['stride'], + padding=mask_downsampler_config['padding'] + ) + + fuser_layer = CXBlock( + dim=fuser_layer_config['dim'], + kernel_size=fuser_layer_config['kernel_size'], + padding=fuser_layer_config['padding'], + layer_scale_init_value=float(fuser_layer_config['layer_scale_init_value']) + ) + fuser = Fuser( + num_layers=memory_encoder_config['fuser']['num_layers'], + layer=fuser_layer + ) + + memory_encoder = MemoryEncoder( + position_encoding=position_encoding_mem_enc, + mask_downsampler=mask_downsampler, + fuser=fuser, + out_dim=memory_encoder_config['out_dim'] + ) + + sam_mask_decoder_extra_args = { + "dynamic_multimask_via_stability": True, + "dynamic_multimask_stability_delta": 0.05, + "dynamic_multimask_stability_thresh": 0.98, + } + + def initialize_model(model_class, model_config, segmentor, image_encoder, memory_attention, memory_encoder, sam_mask_decoder_extra_args, dtype, device): + return model_class( + image_encoder=image_encoder, + memory_attention=memory_attention, + memory_encoder=memory_encoder, + sam_mask_decoder_extra_args=sam_mask_decoder_extra_args, + num_maskmem=model_config['num_maskmem'], + image_size=model_config['image_size'], + sigmoid_scale_for_mem_enc=model_config['sigmoid_scale_for_mem_enc'], + sigmoid_bias_for_mem_enc=model_config['sigmoid_bias_for_mem_enc'], + use_mask_input_as_output_without_sam=model_config['use_mask_input_as_output_without_sam'], + directly_add_no_mem_embed=model_config['directly_add_no_mem_embed'], + use_high_res_features_in_sam=model_config['use_high_res_features_in_sam'], + multimask_output_in_sam=model_config['multimask_output_in_sam'], + iou_prediction_use_sigmoid=model_config['iou_prediction_use_sigmoid'], + use_obj_ptrs_in_encoder=model_config['use_obj_ptrs_in_encoder'], + add_tpos_enc_to_obj_ptrs=model_config['add_tpos_enc_to_obj_ptrs'], + only_obj_ptrs_in_the_past_for_eval=model_config['only_obj_ptrs_in_the_past_for_eval'], + pred_obj_scores=model_config['pred_obj_scores'], + pred_obj_scores_mlp=model_config['pred_obj_scores_mlp'], + fixed_no_obj_ptr=model_config['fixed_no_obj_ptr'], + multimask_output_for_tracking=model_config['multimask_output_for_tracking'], + use_multimask_token_for_obj_ptr=model_config['use_multimask_token_for_obj_ptr'], + compile_image_encoder=model_config['compile_image_encoder'], + multimask_min_pt_num=model_config['multimask_min_pt_num'], + multimask_max_pt_num=model_config['multimask_max_pt_num'], + use_mlp_for_obj_ptr_proj=model_config['use_mlp_for_obj_ptr_proj'], + proj_tpos_enc_in_obj_ptrs=model_config['proj_tpos_enc_in_obj_ptrs'], + no_obj_embed_spatial=model_config['no_obj_embed_spatial'], + use_signed_tpos_enc_to_obj_ptrs=model_config['use_signed_tpos_enc_to_obj_ptrs'], + binarize_mask_from_pts_for_mem_enc=True if segmentor == 'video' else False, + ).to(dtype).to(device).eval() + + # Load the state dictionary + sd = load_torch_file(model_path) + + # Initialize model based on segmentor type + if segmentor == 'single_image': + model_class = SAM2Base + model = initialize_model(model_class, model_config, segmentor, image_encoder, memory_attention, memory_encoder, sam_mask_decoder_extra_args, dtype, device) + model.load_state_dict(sd, strict=False) + model = SAM2ImagePredictor(model) + elif segmentor == 'video': + model_class = SAM2VideoPredictor + model = initialize_model(model_class, model_config, segmentor, image_encoder, memory_attention, memory_encoder, sam_mask_decoder_extra_args, dtype, device) + model.load_state_dict(sd, strict=False) + elif segmentor == 'automaskgenerator': + model_class = SAM2Base + model = initialize_model(model_class, model_config, segmentor, image_encoder, memory_attention, memory_encoder, sam_mask_decoder_extra_args, dtype, device) + model.load_state_dict(sd, strict=False) + model = SAM2AutomaticMaskGenerator(model) + else: + raise ValueError(f"Segmentor {segmentor} not supported") + + return model + + +class LS_SAM2_ULTRA: + + def __init__(self): + self.NODE_NAME = 'SAM2 Ultra' + pass + + @classmethod + def INPUT_TYPES(cls): + sam2_model_list = ['sam2_hiera_base_plus.safetensors', + 'sam2_hiera_large.safetensors', + 'sam2_hiera_small.safetensors', + 'sam2_hiera_tiny.safetensors', + 'sam2.1_hiera_base_plus.safetensors', + 'sam2.1_hiera_large.safetensors', + 'sam2.1_hiera_small.safetensors', + 'sam2.1_hiera_tiny.safetensors', + ] + model_precision_list = [ 'fp16','bf16','fp32'] + select_list = ["all", "first", "by_index"] + method_list = ['VITMatte', 'VITMatte(local)', 'PyMatting', 'GuidedFilter', ] + device_list = ['cuda','cpu'] + return { + "required": { + "image": ("IMAGE",), + "bboxes": ("BBOXES",), + "sam2_model": (sam2_model_list,), + "precision": (model_precision_list,), + "bbox_select": (select_list,), + "select_index": ("STRING", {"default": "0,"},), + "cache_model": ("BOOLEAN", {"default": False}), + "detail_method": (method_list,), + "detail_erode": ("INT", {"default": 6, "min": 1, "max": 255, "step": 1}), + "detail_dilate": ("INT", {"default": 4, "min": 1, "max": 255, "step": 1}), + "black_point": ("FLOAT", {"default": 0.15, "min": 0.01, "max": 0.98, "step": 0.01, "display": "slider"}), + "white_point": ("FLOAT", {"default": 0.99, "min": 0.02, "max": 0.99, "step": 0.01, "display": "slider"}), + "process_detail": ("BOOLEAN", {"default": True}), + "device": (device_list,), + "max_megapixels": ("FLOAT", {"default": 2.0, "min": 1, "max": 999, "step": 0.1}), + }, + "optional": { + } + } + + RETURN_TYPES = ("IMAGE", "MASK",) + RETURN_NAMES = ("image", "mask",) + FUNCTION = 'sam2_ultra' + CATEGORY = '😺dzNodes/LayerMask' + + def sam2_ultra(self, image, bboxes, sam2_model, precision, + bbox_select, select_index, cache_model, + detail_method, detail_erode, detail_dilate, black_point, white_point, + process_detail, device, max_megapixels, + ): + + ret_images = [] + ret_masks = [] + + # load model + sam2_path = os.path.join(folder_paths.models_dir, "sam2") + if precision != 'fp32' and "2.1" in sam2_model: + base_name, extension = sam2_model.rsplit('.', 1) + sam2_model = f"{base_name}-fp16.{extension}" + model_path = os.path.join(sam2_path, sam2_model) + + if device == "cuda": + if torch.cuda.get_device_properties(0).major >= 8: + # turn on tfloat32 for Ampere GPUs (https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + dtype = {"bf16": torch.bfloat16, "fp16": torch.float16, "fp32": torch.float32}[precision] + # device = {"cuda": torch.device("cuda"), "cpu": torch.device("cpu")}[device] + segmentor = 'single_image' + if not os.path.exists(model_path): + log(f"{self.NODE_NAME}: Downloading SAM2 model to: {model_path}") + from huggingface_hub import snapshot_download + snapshot_download(repo_id="Kijai/sam2-safetensors", + allow_patterns=[f"*{sam2_model}*"], + local_dir=sam2_path, + local_dir_use_symlinks=False) + + model_mapping = { + "2.0": { + "base": "sam2_hiera_b+.yaml", + "large": "sam2_hiera_l.yaml", + "small": "sam2_hiera_s.yaml", + "tiny": "sam2_hiera_t.yaml" + }, + "2.1": { + "base": "sam2.1_hiera_b+.yaml", + "large": "sam2.1_hiera_l.yaml", + "small": "sam2.1_hiera_s.yaml", + "tiny": "sam2.1_hiera_t.yaml" + } + } + version = "2.1" if "2.1" in sam2_model else "2.0" + + model_cfg_path = next( + (os.path.join(os.path.dirname(os.path.abspath(__file__)), "sam2", "sam2_configs", cfg) + for key, cfg in model_mapping[version].items() if key in sam2_model), + None + ) + log(f"{self.NODE_NAME}: Using model config: {model_cfg_path}") + model = load_model(model_path, model_cfg_path, segmentor, dtype, device) + + offload_device = mm.unet_offload_device() + + indexs = extract_numbers(select_index) + + try: + model.to(device) + except: + model.model.to(device) + autocast_condition = not mm.is_device_mps(device) + + for index in range(len(image)): + img = image[index].unsqueeze(0) + orig_image = tensor2pil(img) + + # Handle possible bboxes + if len(bboxes[index]) == 0: + log(f"{self.NODE_NAME} bboxes index {index} is empty, output black mask.", message_type='warning') + _mask = Image.new("L", orig_image.size, color="black") + ret_image = RGB2RGBA(orig_image, _mask.convert('L')) + ret_images.append(pil2tensor(ret_image)) + ret_masks.append(image2mask(_mask)) + continue + else: + boxes_np_batch = [] + for bbox_list in bboxes[index]: + boxes_np = [] + for bbox in bbox_list: + boxes_np.append(bbox) + boxes_np = np.array(boxes_np) + boxes_np_batch.append(boxes_np) + if bbox_select == "all": + final_box = np.array(boxes_np_batch) + elif bbox_select == "by_index": + final_box = [] + try: + for i in indexs: + final_box.append(boxes_np_batch[i]) + except IndexError: + log(f"{self.NODE_NAME} invalid bbox index {i}", message_type='warning') + else: + final_box = np.array(boxes_np_batch[0]) + + mask_list = [] + + with torch.autocast(mm.get_autocast_device(device), dtype=dtype) if autocast_condition else nullcontext(): + + image_np = (img.contiguous() * 255).byte().numpy() + comfy_pbar = ProgressBar(len(image_np)) + tqdm_pbar = tqdm(total=len(image_np), desc="Processing Images") + for i in range(len(image_np)): + model.set_image(image_np[i]) + # if len(image_np) > 1: + # input_box = final_box[i] + input_box = final_box + + out_masks, scores, logits = model.predict( + point_coords=None, + point_labels=None, + box=input_box, + multimask_output=True, + mask_input=None, + ) + + if out_masks.ndim == 3: + sorted_ind = np.argsort(scores)[::-1] + out_masks = out_masks[sorted_ind][0] # choose only the best result for now + # scores = scores[sorted_ind] + # logits = logits[sorted_ind] + mask_list.append(np.expand_dims(out_masks, axis=0)) + else: + _, _, H, W = out_masks.shape + # Combine masks for all object IDs in the frame + combined_mask = np.zeros((H, W), dtype=bool) + for out_mask in out_masks: + combined_mask = np.logical_or(combined_mask, out_mask) + combined_mask = combined_mask.astype(np.uint8) + mask_list.append(combined_mask) + comfy_pbar.update(1) + tqdm_pbar.update(1) + + out_list = [] + for mask in mask_list: + mask_tensor = torch.from_numpy(mask) + mask_tensor = mask_tensor.permute(1, 2, 0) + mask_tensor = mask_tensor[:, :, 0] + out_list.append(mask_tensor) + mask_tensor = torch.stack(out_list, dim=0).cpu().float() + _mask = mask_tensor.squeeze() + + if detail_method == 'VITMatte(local)': + local_files_only = True + else: + local_files_only = False + + detail_range = detail_erode + detail_dilate + if process_detail: + if detail_method == 'GuidedFilter': + _mask = guided_filter_alpha(pil2tensor(orig_image), _mask, detail_range // 6 + 1) + _mask = tensor2pil(histogram_remap(_mask, black_point, white_point)) + elif detail_method == 'PyMatting': + _mask = tensor2pil(mask_edge_detail(pil2tensor(orig_image), _mask, detail_range // 8 + 1, black_point, white_point)) + else: + _trimap = generate_VITMatte_trimap(_mask, detail_erode, detail_dilate) + _mask = generate_VITMatte(orig_image, _trimap, local_files_only=local_files_only, device=device, + max_megapixels=max_megapixels) + _mask = tensor2pil(histogram_remap(pil2tensor(_mask), black_point, white_point)) + else: + _mask = tensor2pil(_mask) + + ret_image = RGB2RGBA(orig_image, _mask.convert('L')) + ret_images.append(pil2tensor(ret_image)) + ret_masks.append(image2mask(_mask)) + + if cache_model: + try: + model.to(offload_device) + except: + try: + model.model.to(offload_device) + except: + pass + else: + del model + clear_memory() + log(f"{self.NODE_NAME} Processed {len(ret_images)} image(s).", message_type='finish') + return (torch.cat(ret_images, dim=0), torch.cat(ret_masks, dim=0)) + +# 在mask范围内随机生成指定数量的点 +def poisson_disk_sampling(mask:Image, radius:float=32, num_points:int=16) -> list: + """ + 使用泊松盘采样在掩码的白色区域内生成点,确保每个点之间至少为radius像素。 + + 参数: + - mask: PIL.Image对象,将转换为numpy数组,二值化的掩码图像,白色区域为1,黑色区域为0 + - radius: float,点之间的最小距离 + - num_points: int,期望生成的点的数量 + + 返回: + - points: list of (x, y)元组,生成的点的坐标 + """ + + gray_mask = np.asarray(mask.convert('L')) + # gray_mask = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY) + _, binary_mask = cv2.threshold(gray_mask, 127, 1, cv2.THRESH_BINARY) + # binary_mask = binary_mask.astype(np.uint8) + # 计算距离变换 + distance = cv2.distanceTransform(binary_mask, distanceType=cv2.DIST_L2, maskSize=5) + + # 使用泊松盘采样算法 + from skimage.feature import peak_local_max + coordinates = peak_local_max(distance, min_distance=radius, num_peaks=num_points, exclude_border=True) + + # 将坐标转换为列表形式 + points = [tuple(pt[::-1]) for pt in coordinates] # (x, y) + + return points + + +class LS_SAM2_VIDEO_ULTRA: + + + def __init__(self): + self.NODE_NAME = 'SAM2 Video Ultra' + + @classmethod + def INPUT_TYPES(cls): + sam2_model_list = ['sam2_hiera_base_plus.safetensors', + 'sam2_hiera_large.safetensors', + 'sam2_hiera_small.safetensors', + 'sam2_hiera_tiny.safetensors', + 'sam2.1_hiera_base_plus.safetensors', + 'sam2.1_hiera_large.safetensors', + 'sam2.1_hiera_small.safetensors', + 'sam2.1_hiera_tiny.safetensors', + ] + model_precision_list = ['fp16','bf16'] + method_list = ['VITMatte'] + device_list = ['cuda'] + return { + "required": { + "image": ("IMAGE",), + "sam2_model": (sam2_model_list,), + "precision": (model_precision_list,), + "cache_model": ("BOOLEAN", {"default": False}), + "individual_objects": ("BOOLEAN", {"default": False}), + "mask_preview_color": ("STRING", {"default": "#FF0080"},), + "detail_method": (method_list,), + "detail_erode": ("INT", {"default": 6, "min": 1, "max": 255, "step": 1}), + "detail_dilate": ("INT", {"default": 4, "min": 1, "max": 255, "step": 1}), + "black_point": ("FLOAT", {"default": 0.15, "min": 0.01, "max": 0.98, "step": 0.01, "display": "slider"}), + "white_point": ("FLOAT", {"default": 0.99, "min": 0.02, "max": 0.99, "step": 0.01, "display": "slider"}), + "process_detail": ("BOOLEAN", {"default": True}), + "device": (device_list,), + "max_megapixels": ("FLOAT", {"default": 0.5, "min": 0.1, "max": 10, "step": 0.1}), + }, + "optional": { + "bboxes": ("BBOXES",), + "first_frame_mask": ("MASK",), + "pre_mask": ("MASK",), + } + } + + RETURN_TYPES = ("MASK","IMAGE") + RETURN_NAMES = ("mask","preview") + FUNCTION = 'sam2_video_ultra' + CATEGORY = '😺dzNodes/LayerMask' + + def sam2_video_ultra(self, image, sam2_model, precision, + cache_model, individual_objects, mask_preview_color, + detail_method, detail_erode, detail_dilate, black_point, white_point, + process_detail, device, max_megapixels, + bboxes = None, first_frame_mask=None, pre_mask=None + ): + + if first_frame_mask is None: + if bboxes is None: + log(f"{self.NODE_NAME} skipped, first_frame_mask or bboxes must have input.", message_type='error') + return (image, None) + elif len(bboxes) == 0: + log(f"{self.NODE_NAME} skipped, because first_frame_mask is none and bboxes is empty.", message_type='error') + return (image, None) + + # load model + sam2_path = os.path.join(folder_paths.models_dir, "sam2") + if precision != 'fp32' and "2.1" in sam2_model: + base_name, extension = sam2_model.rsplit('.', 1) + sam2_model = f"{base_name}-fp16.{extension}" + model_path = os.path.join(sam2_path, sam2_model) + + if device == "cuda": + if torch.cuda.get_device_properties(0).major >= 8: + # turn on tfloat32 for Ampere GPUs (https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + dtype = {"bf16": torch.bfloat16, "fp16": torch.float16, "fp32": torch.float32}[precision] + + if not os.path.exists(model_path): + log(f"{self.NODE_NAME}: Downloading SAM2 model to: {model_path}") + from huggingface_hub import snapshot_download + snapshot_download(repo_id="Kijai/sam2-safetensors", + allow_patterns=[f"*{sam2_model}*"], + local_dir=sam2_path, + local_dir_use_symlinks=False) + + model_mapping = { + "2.0": { + "base": "sam2_hiera_b+.yaml", + "large": "sam2_hiera_l.yaml", + "small": "sam2_hiera_s.yaml", + "tiny": "sam2_hiera_t.yaml" + }, + "2.1": { + "base": "sam2.1_hiera_b+.yaml", + "large": "sam2.1_hiera_l.yaml", + "small": "sam2.1_hiera_s.yaml", + "tiny": "sam2.1_hiera_t.yaml" + } + } + version = "2.1" if "2.1" in sam2_model else "2.0" + + model_cfg_path = next( + (os.path.join(os.path.dirname(os.path.abspath(__file__)), "sam2", "sam2_configs", cfg) + for key, cfg in model_mapping[version].items() if key in sam2_model), + None + ) + log(f"{self.NODE_NAME}: Using model config: {model_cfg_path}") + + offload_device = mm.unet_offload_device() + B, H, W, C = image.shape + + if pre_mask is not None: + input_mask = pre_mask.clone().unsqueeze(1) + input_mask = F.interpolate(input_mask, size=(256, 256), mode="bilinear") + input_mask = input_mask.squeeze(1) + + autocast_condition = not mm.is_device_mps(device) + + # init video model + v_model = load_model(model_path, model_cfg_path, 'video', dtype, device) + model_input_image_size = v_model.image_size + from comfy.utils import common_upscale + resized_image = common_upscale(image.movedim(-1,1), model_input_image_size, model_input_image_size, "bilinear", "disabled").movedim(1,-1) + try: + v_model.to(device) + except: + v_model.model.to(device) + s_model = None + if first_frame_mask is None: + # load single_image_model + s_model = load_model(model_path, model_cfg_path, 'single_image', dtype, device) + + # gen first frame mask + with torch.autocast(mm.get_autocast_device(device), dtype=dtype) if autocast_condition else nullcontext(): + f_mask = [] + boxes_np_batch = [] + for bbox_list in bboxes: + boxes_np = [] + for bbox in bbox_list: + boxes_np.append(bbox) + boxes_np = np.array(boxes_np) + boxes_np_batch.append(boxes_np) + final_box = np.array(boxes_np_batch) + final_labels = None + + image_np = (image.contiguous() * 255).byte().numpy() + i = 0 + s_model.set_image(image_np[i]) + input_box = final_box + + out_masks, scores, logits = s_model.predict( + point_coords=None, + point_labels=None, + box=input_box, + multimask_output=True, + # mask_input=None, + mask_input=input_mask[0].unsqueeze(0) if pre_mask is not None else None, + ) + + if out_masks.ndim == 3: + sorted_ind = np.argsort(scores)[::-1] + out_masks = out_masks[sorted_ind][0] # choose only the best result for now + # scores = scores[sorted_ind] + # logits = logits[sorted_ind] + f_mask.append(np.expand_dims(out_masks, axis=0)) + else: + _, _, H, W = out_masks.shape + # Combine masks for all object IDs in the frame + combined_mask = np.zeros((H, W), dtype=bool) + for out_mask in out_masks: + combined_mask = np.logical_or(combined_mask, out_mask) + combined_mask = combined_mask.astype(np.uint8) + f_mask.append(combined_mask) + + out_list = [] + for mask in f_mask: + mask_tensor = torch.from_numpy(mask) + mask_tensor = mask_tensor.permute(1, 2, 0) + mask_tensor = mask_tensor[:, :, 0] + out_list.append(mask_tensor) + mask_tensor = torch.stack(out_list, dim=0).cpu().float() + f_mask = tensor2pil(mask_tensor.squeeze()).convert("L") + else: + if first_frame_mask.dim() == 2: + first_frame_mask = torch.unsqueeze(first_frame_mask, 0) + f_mask = tensor2pil(first_frame_mask[0]) + coords = poisson_disk_sampling(f_mask, radius=32, num_points=16) + + # gen video mask + with torch.autocast(mm.get_autocast_device(device), dtype=dtype) if autocast_condition else nullcontext(): + if not individual_objects: + positive_point_coords = np.atleast_2d(np.array(coords)) + else: + positive_point_coords = np.array([np.atleast_2d(coord) for coord in coords]) + + if not individual_objects: + positive_point_labels = np.ones(len(positive_point_coords)) + else: + positive_labels = [] + for point in positive_point_coords: + positive_labels.append(np.array([1])) # 1) + positive_point_labels = np.stack(positive_labels, axis=0) + + final_coords = positive_point_coords + final_labels = positive_point_labels + + mask_list = [] + if hasattr(self, 'inference_state'): + v_model.reset_state(self.inference_state) + self.inference_state = v_model.init_state(resized_image.permute(0, 3, 1, 2).contiguous(), H, W, device=device) + + if individual_objects: + for i, (coord, label) in enumerate(zip(final_coords, final_labels)): + _, out_obj_ids, out_mask_logits = v_model.add_new_points( + inference_state=self.inference_state, + frame_idx=0, + obj_id=i, + points=final_coords[i], + labels=final_labels[i], + ) + else: + _, out_obj_ids, out_mask_logits = v_model.add_new_points( + inference_state=self.inference_state, + frame_idx=0, + obj_id=1, + points=final_coords, + labels=final_labels, + ) + + pbar = ProgressBar(B) + video_segments = {} + for out_frame_idx, out_obj_ids, out_mask_logits in v_model.propagate_in_video(self.inference_state): + video_segments[out_frame_idx] = { + out_obj_id: (out_mask_logits[i] > 0.0).cpu().numpy() + for i, out_obj_id in enumerate(out_obj_ids) + } + pbar.update(1) + if individual_objects: + _, _, H, W = out_mask_logits.shape + # Combine masks for all object IDs in the frame + combined_mask = np.zeros((H, W), dtype=np.uint8) + for i, out_obj_id in enumerate(out_obj_ids): + out_mask = (out_mask_logits[i] > 0.0).cpu().numpy() + combined_mask = np.logical_or(combined_mask, out_mask) + video_segments[out_frame_idx] = combined_mask + + if individual_objects: + for frame_idx, combined_mask in video_segments.items(): + mask_list.append(combined_mask) + else: + for frame_idx, obj_masks in video_segments.items(): + for out_obj_id, out_mask in obj_masks.items(): + mask_list.append(out_mask) + + if cache_model: + try: + v_model.to(offload_device) + s_model.to(offload_device) + except: + try: + v_model.model.to(offload_device) + s_model.model.to(offload_device) + except: + pass + else: + del v_model + del s_model + clear_memory() + + out_list = [] + for mask in mask_list: + mask_tensor = torch.from_numpy(mask) + mask_tensor = mask_tensor.permute(1, 2, 0) + mask_tensor = mask_tensor[:, :, 0] + out_list.append(mask_tensor) + out_list = torch.stack(out_list, dim=0).cpu().float() + + if detail_method == 'VITMatte(local)': + local_files_only = True + else: + local_files_only = False + + detail_range = detail_erode + detail_dilate + ret_previews = [] + ret_masks = [] + from tqdm import tqdm + comfy_pbar = ProgressBar(len(image)) + tqdm_pbar = tqdm(total=len(image), desc="processing masks") + for index, img in tqdm(enumerate(image)): + orig_image = tensor2pil(img) + _mask = out_list[index].unsqueeze(0) + _mask = tensor2pil(_mask).resize((orig_image.size), Image.BILINEAR) + if process_detail: + _trimap = generate_VITMatte_trimap(pil2tensor(_mask), detail_erode, detail_dilate) + _mask = generate_VITMatte(orig_image, _trimap, local_files_only=local_files_only, device=device, + max_megapixels=max_megapixels) + _mask = tensor2pil(histogram_remap(pil2tensor(_mask), black_point, white_point)) + + color_image = Image.new("RGB", orig_image.size,color=mask_preview_color) + color_image = chop_image_v2(orig_image, color_image, "normal", 50) + color_image.paste(orig_image, mask=_mask) + ret_previews.append(pil2tensor(color_image)) + ret_masks.append(image2mask(_mask)) + comfy_pbar.update(1) + tqdm_pbar.update(1) + + log(f"{self.NODE_NAME} Processed {len(ret_masks)} frame(s).", message_type='finish') + return (torch.cat(ret_masks, dim=0), torch.cat(ret_previews, dim=0)) + + +NODE_CLASS_MAPPINGS = { + "LayerMask: SAM2Ultra": LS_SAM2_ULTRA, + "LayerMask: SAM2VideoUltra": LS_SAM2_VIDEO_ULTRA +} + +NODE_DISPLAY_NAME_MAPPINGS = { + "LayerMask: SAM2Ultra": "LayerMask: SAM2 Ultra", + "LayerMask: SAM2VideoUltra": "LayerMask: SAM2 Video Ultra(Advance)" +} \ No newline at end of file diff --git a/py/sam_hq/automatic.py b/py/sam_hq/automatic.py new file mode 100644 index 0000000..b563d36 --- /dev/null +++ b/py/sam_hq/automatic.py @@ -0,0 +1,115 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import numpy as np + +from typing import List, Optional + +from segment_anything import SamAutomaticMaskGenerator +from segment_anything.utils.amg import build_all_layer_point_grids +from .predictor import SamPredictorHQ + + +class SamAutomaticMaskGeneratorHQ(SamAutomaticMaskGenerator): + def __init__( + self, + model: SamPredictorHQ, + points_per_side: Optional[int] = 32, + points_per_batch: int = 64, + pred_iou_thresh: float = 0.88, + stability_score_thresh: float = 0.95, + stability_score_offset: float = 1.0, + box_nms_thresh: float = 0.7, + crop_n_layers: int = 0, + crop_nms_thresh: float = 0.7, + crop_overlap_ratio: float = 512 / 1500, + crop_n_points_downscale_factor: int = 1, + point_grids: Optional[List[np.ndarray]] = None, + min_mask_region_area: int = 0, + output_mode: str = "binary_mask", + ) -> None: + """ + Using a SAM model, generates masks for the entire image. + Generates a grid of point prompts over the image, then filters + low quality and duplicate masks. The default settings are chosen + for SAM with a ViT-H backbone. + + Arguments: + model (Sam): The SAM model to use for mask prediction. + points_per_side (int or None): The number of points to be sampled + along one side of the image. The total number of points is + points_per_side**2. If None, 'point_grids' must provide explicit + point sampling. + points_per_batch (int): Sets the number of points run simultaneously + by the model. Higher numbers may be faster but use more GPU memory. + pred_iou_thresh (float): A filtering threshold in [0,1], using the + model's predicted mask quality. + stability_score_thresh (float): A filtering threshold in [0,1], using + the stability of the mask under changes to the cutoff used to binarize + the model's mask predictions. + stability_score_offset (float): The amount to shift the cutoff when + calculated the stability score. + box_nms_thresh (float): The box IoU cutoff used by non-maximal + suppression to filter duplicate masks. + crop_n_layers (int): If >0, mask prediction will be run again on + crops of the image. Sets the number of layers to run, where each + layer has 2**i_layer number of image crops. + crop_nms_thresh (float): The box IoU cutoff used by non-maximal + suppression to filter duplicate masks between different crops. + crop_overlap_ratio (float): Sets the degree to which crops overlap. + In the first crop layer, crops will overlap by this fraction of + the image length. Later layers with more crops scale down this overlap. + crop_n_points_downscale_factor (int): The number of points-per-side + sampled in layer n is scaled down by crop_n_points_downscale_factor**n. + point_grids (list(np.ndarray) or None): A list over explicit grids + of points used for sampling, normalized to [0,1]. The nth grid in the + list is used in the nth crop layer. Exclusive with points_per_side. + min_mask_region_area (int): If >0, postprocessing will be applied + to remove disconnected regions and holes in masks with area smaller + than min_mask_region_area. Requires opencv. + output_mode (str): The form masks are returned in. Can be 'binary_mask', + 'uncompressed_rle', or 'coco_rle'. 'coco_rle' requires pycocotools. + For large resolutions, 'binary_mask' may consume large amounts of + memory. + """ + + assert (points_per_side is None) != ( + point_grids is None + ), "Exactly one of points_per_side or point_grid must be provided." + if points_per_side is not None: + self.point_grids = build_all_layer_point_grids( + points_per_side, + crop_n_layers, + crop_n_points_downscale_factor, + ) + elif point_grids is not None: + self.point_grids = point_grids + else: + raise ValueError("Can't have both points_per_side and point_grid be None.") + + assert output_mode in [ + "binary_mask", + "uncompressed_rle", + "coco_rle", + ], f"Unknown output_mode {output_mode}." + if output_mode == "coco_rle": + from pycocotools import mask as mask_utils # type: ignore # noqa: F401 + + if min_mask_region_area > 0: + import cv2 # type: ignore # noqa: F401 + + self.predictor = model + self.points_per_batch = points_per_batch + self.pred_iou_thresh = pred_iou_thresh + self.stability_score_thresh = stability_score_thresh + self.stability_score_offset = stability_score_offset + self.box_nms_thresh = box_nms_thresh + self.crop_n_layers = crop_n_layers + self.crop_nms_thresh = crop_nms_thresh + self.crop_overlap_ratio = crop_overlap_ratio + self.crop_n_points_downscale_factor = crop_n_points_downscale_factor + self.min_mask_region_area = min_mask_region_area + self.output_mode = output_mode diff --git a/py/sam_hq/build_sam_hq.py b/py/sam_hq/build_sam_hq.py new file mode 100644 index 0000000..c8f41f2 --- /dev/null +++ b/py/sam_hq/build_sam_hq.py @@ -0,0 +1,166 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import torch + +from functools import partial + +from .modeling.mask_decoder_hq import MaskDecoderHQ +from .modeling.image_encoder import ImageEncoderViTHQ +from .modeling.tiny_vit import TinyViT +from segment_anything.modeling import PromptEncoder, Sam, TwoWayTransformer, MaskDecoder +from segment_anything import build_sam_vit_h, build_sam_vit_l, build_sam_vit_b + + +def build_sam_hq_vit_h(checkpoint=None): + return _build_sam_hq( + encoder_embed_dim=1280, + encoder_depth=32, + encoder_num_heads=16, + encoder_global_attn_indexes=[7, 15, 23, 31], + checkpoint=checkpoint, + ) + + +def build_sam_hq_vit_l(checkpoint=None): + return _build_sam_hq( + encoder_embed_dim=1024, + encoder_depth=24, + encoder_num_heads=16, + encoder_global_attn_indexes=[5, 11, 17, 23], + checkpoint=checkpoint, + ) + + +def build_sam_hq_vit_b(checkpoint=None): + return _build_sam_hq( + encoder_embed_dim=768, + encoder_depth=12, + encoder_num_heads=12, + encoder_global_attn_indexes=[2, 5, 8, 11], + checkpoint=checkpoint, + ) + + +def build_mobile_sam(checkpoint=None): + return _build_mobile_sam(checkpoint) + + +sam_model_registry = { + "sam_vit_h": build_sam_vit_h, + "sam_vit_l": build_sam_vit_l, + "sam_vit_b": build_sam_vit_b, + "sam_hq_vit_h": build_sam_hq_vit_h, + "sam_hq_vit_l": build_sam_hq_vit_l, + "sam_hq_vit_b": build_sam_hq_vit_b, + "mobile_sam": build_mobile_sam, +} + + +def _load_sam_checkpoint(sam: Sam, checkpoint=None): + sam.eval() + if checkpoint is not None: + with open(checkpoint, "rb") as f: + state_dict = torch.load(f) + info = sam.load_state_dict(state_dict, strict=False) + print(info) + for _, p in sam.named_parameters(): + p.requires_grad = False + return sam + +def _build_sam_hq( + encoder_embed_dim, + encoder_depth, + encoder_num_heads, + encoder_global_attn_indexes, + checkpoint=None, +): + prompt_embed_dim = 256 + image_size = 1024 + vit_patch_size = 16 + image_embedding_size = image_size // vit_patch_size + sam = Sam( + image_encoder=ImageEncoderViTHQ( + depth=encoder_depth, + embed_dim=encoder_embed_dim, + img_size=image_size, + mlp_ratio=4, + norm_layer=partial(torch.nn.LayerNorm, eps=1e-6), + num_heads=encoder_num_heads, + patch_size=vit_patch_size, + qkv_bias=True, + use_rel_pos=True, + global_attn_indexes=encoder_global_attn_indexes, + window_size=14, + out_chans=prompt_embed_dim, + ), + prompt_encoder=PromptEncoder( + embed_dim=prompt_embed_dim, + image_embedding_size=(image_embedding_size, image_embedding_size), + input_image_size=(image_size, image_size), + mask_in_chans=16, + ), + mask_decoder=MaskDecoderHQ( + num_multimask_outputs=3, + transformer=TwoWayTransformer( + depth=2, + embedding_dim=prompt_embed_dim, + mlp_dim=2048, + num_heads=8, + ), + transformer_dim=prompt_embed_dim, + iou_head_depth=3, + iou_head_hidden_dim=256, + vit_dim=encoder_embed_dim, + ), + pixel_mean=[123.675, 116.28, 103.53], + pixel_std=[58.395, 57.12, 57.375], + ) + return _load_sam_checkpoint(sam, checkpoint) + + +def _build_mobile_sam(checkpoint=None): + prompt_embed_dim = 256 + image_size = 1024 + vit_patch_size = 16 + image_embedding_size = image_size // vit_patch_size + mobile_sam = Sam( + image_encoder=TinyViT( + img_size=1024, in_chans=3, num_classes=1000, + embed_dims=[64, 128, 160, 320], + depths=[2, 2, 6, 2], + num_heads=[2, 4, 5, 10], + window_sizes=[7, 7, 14, 7], + mlp_ratio=4., + drop_rate=0., + drop_path_rate=0.0, + use_checkpoint=False, + mbconv_expand_ratio=4.0, + local_conv_size=3, + layer_lr_decay=0.8 + ), + prompt_encoder=PromptEncoder( + embed_dim=prompt_embed_dim, + image_embedding_size=(image_embedding_size, image_embedding_size), + input_image_size=(image_size, image_size), + mask_in_chans=16, + ), + mask_decoder=MaskDecoder( + num_multimask_outputs=3, + transformer=TwoWayTransformer( + depth=2, + embedding_dim=prompt_embed_dim, + mlp_dim=2048, + num_heads=8, + ), + transformer_dim=prompt_embed_dim, + iou_head_depth=3, + iou_head_hidden_dim=256, + ), + pixel_mean=[123.675, 116.28, 103.53], + pixel_std=[58.395, 57.12, 57.375], + ) + return _load_sam_checkpoint(mobile_sam, checkpoint) diff --git a/py/sam_hq/modeling/image_encoder.py b/py/sam_hq/modeling/image_encoder.py new file mode 100644 index 0000000..8933bc0 --- /dev/null +++ b/py/sam_hq/modeling/image_encoder.py @@ -0,0 +1,20 @@ +import torch +from segment_anything.modeling import ImageEncoderViT + +# This class and its supporting functions below lightly adapted from the ViTDet backbone available at: https://github.com/facebookresearch/detectron2/blob/main/detectron2/modeling/backbone/vit.py # noqa +class ImageEncoderViTHQ(ImageEncoderViT): + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x = self.patch_embed(x) + if self.pos_embed is not None: + x = x + self.pos_embed + + interm_embeddings=[] + for blk in self.blocks: + x = blk(x) + if blk.window_size == 0: + interm_embeddings.append(x) + + x = self.neck(x.permute(0, 3, 1, 2)) + + return x, interm_embeddings \ No newline at end of file diff --git a/py/sam_hq/modeling/mask_decoder_hq.py b/py/sam_hq/modeling/mask_decoder_hq.py new file mode 100644 index 0000000..244133c --- /dev/null +++ b/py/sam_hq/modeling/mask_decoder_hq.py @@ -0,0 +1,236 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# Modified by HQ-SAM team +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import torch +from torch import nn +from torch.nn import functional as F + +from typing import List, Tuple, Type + +from segment_anything.modeling.common import LayerNorm2d + + +class MaskDecoderHQ(nn.Module): + def __init__( + self, + *, + transformer_dim: int, + transformer: nn.Module, + num_multimask_outputs: int = 3, + activation: Type[nn.Module] = nn.GELU, + iou_head_depth: int = 3, + iou_head_hidden_dim: int = 256, + vit_dim: int = 1024, + ) -> None: + """ + Predicts masks given an image and prompt embeddings, using a + transformer architecture. + + Arguments: + transformer_dim (int): the channel dimension of the transformer + transformer (nn.Module): the transformer used to predict masks + num_multimask_outputs (int): the number of masks to predict + when disambiguating masks + activation (nn.Module): the type of activation to use when + upscaling masks + iou_head_depth (int): the depth of the MLP used to predict + mask quality + iou_head_hidden_dim (int): the hidden dimension of the MLP + used to predict mask quality + """ + super().__init__() + self.transformer_dim = transformer_dim + self.transformer = transformer + + self.num_multimask_outputs = num_multimask_outputs + + self.iou_token = nn.Embedding(1, transformer_dim) + self.num_mask_tokens = num_multimask_outputs + 1 + self.mask_tokens = nn.Embedding(self.num_mask_tokens, transformer_dim) + + self.output_upscaling = nn.Sequential( + nn.ConvTranspose2d(transformer_dim, transformer_dim // 4, kernel_size=2, stride=2), + LayerNorm2d(transformer_dim // 4), + activation(), + nn.ConvTranspose2d(transformer_dim // 4, transformer_dim // 8, kernel_size=2, stride=2), + activation(), + ) + self.output_hypernetworks_mlps = nn.ModuleList( + [ + MLP(transformer_dim, transformer_dim, transformer_dim // 8, 3) + for i in range(self.num_mask_tokens) + ] + ) + + self.iou_prediction_head = MLP( + transformer_dim, iou_head_hidden_dim, self.num_mask_tokens, iou_head_depth + ) + + # HQ-SAM parameters + self.hf_token = nn.Embedding(1, transformer_dim) # HQ-Ouptput-Token + self.hf_mlp = MLP(transformer_dim, transformer_dim, transformer_dim // 8, 3) # corresponding new MLP layer for HQ-Ouptput-Token + self.num_mask_tokens = self.num_mask_tokens + 1 + + # three conv fusion layers for obtaining HQ-Feature + self.compress_vit_feat = nn.Sequential( + nn.ConvTranspose2d(vit_dim, transformer_dim, kernel_size=2, stride=2), + LayerNorm2d(transformer_dim), + nn.GELU(), + nn.ConvTranspose2d(transformer_dim, transformer_dim // 8, kernel_size=2, stride=2)) + + self.embedding_encoder = nn.Sequential( + nn.ConvTranspose2d(transformer_dim, transformer_dim // 4, kernel_size=2, stride=2), + LayerNorm2d(transformer_dim // 4), + nn.GELU(), + nn.ConvTranspose2d(transformer_dim // 4, transformer_dim // 8, kernel_size=2, stride=2), + ) + self.embedding_maskfeature = nn.Sequential( + nn.Conv2d(transformer_dim // 8, transformer_dim // 4, 3, 1, 1), + LayerNorm2d(transformer_dim // 4), + nn.GELU(), + nn.Conv2d(transformer_dim // 4, transformer_dim // 8, 3, 1, 1)) + + + + def forward( + self, + image_embeddings: torch.Tensor, + image_pe: torch.Tensor, + sparse_prompt_embeddings: torch.Tensor, + dense_prompt_embeddings: torch.Tensor, + multimask_output: bool, + hq_token_only: bool = False, + interm_embeddings: torch.Tensor = None, + ) -> Tuple[torch.Tensor, torch.Tensor]: + """ + Predict masks given image and prompt embeddings. + + Arguments: + image_embeddings (torch.Tensor): the embeddings from the ViT image encoder + image_pe (torch.Tensor): positional encoding with the shape of image_embeddings + sparse_prompt_embeddings (torch.Tensor): the embeddings of the points and boxes + dense_prompt_embeddings (torch.Tensor): the embeddings of the mask inputs + multimask_output (bool): Whether to return multiple masks or a single + mask. + + Returns: + torch.Tensor: batched predicted masks + torch.Tensor: batched predictions of mask quality + """ + vit_features = interm_embeddings[0].permute(0, 3, 1, 2) # early-layer ViT feature, after 1st global attention block in ViT + hq_features = self.embedding_encoder(image_embeddings) + self.compress_vit_feat(vit_features) + + masks, iou_pred, masks_hq = self.predict_masks( + image_embeddings=image_embeddings, + image_pe=image_pe, + sparse_prompt_embeddings=sparse_prompt_embeddings, + dense_prompt_embeddings=dense_prompt_embeddings, + hq_features=hq_features, + ) + + # Select the correct mask or masks for output + # if multimask_output: + # # mask with highest score + # mask_slice = slice(1,self.num_mask_tokens-1) + # iou_pred = iou_pred[:, mask_slice] + # iou_pred, max_iou_idx = torch.max(iou_pred,dim=1) + # iou_pred = iou_pred.unsqueeze(1) + # masks_multi = masks[:, mask_slice, :, :] + # masks_sam = masks_multi[torch.arange(masks_multi.size(0)),max_iou_idx].unsqueeze(1) + # else: + # # single mask output, default + # mask_slice = slice(0, 1) + # iou_pred = iou_pred[:,mask_slice] + # masks_sam = masks[:,mask_slice] + if multimask_output: + mask_slice = slice(1, None) + else: + mask_slice = slice(0, 1) + masks_sam = masks[:, mask_slice, :, :] + iou_pred = iou_pred[:, mask_slice] + if hq_token_only: + masks = masks_hq + else: + masks = masks_sam + masks_hq + # Prepare output + return masks, iou_pred + + def predict_masks( + self, + image_embeddings: torch.Tensor, + image_pe: torch.Tensor, + sparse_prompt_embeddings: torch.Tensor, + dense_prompt_embeddings: torch.Tensor, + hq_features: torch.Tensor, + ) -> Tuple[torch.Tensor, torch.Tensor]: + """Predicts masks. See 'forward' for more details.""" + # Concatenate output tokens + output_tokens = torch.cat([self.iou_token.weight, self.mask_tokens.weight, self.hf_token.weight], dim=0) + output_tokens = output_tokens.unsqueeze(0).expand(sparse_prompt_embeddings.size(0), -1, -1) + tokens = torch.cat((output_tokens, sparse_prompt_embeddings), dim=1) + + # Expand per-image data in batch direction to be per-mask + src = torch.repeat_interleave(image_embeddings, tokens.shape[0], dim=0) + src = src + dense_prompt_embeddings + pos_src = torch.repeat_interleave(image_pe, tokens.shape[0], dim=0) + b, c, h, w = src.shape + + # Run the transformer + hs, src = self.transformer(src, pos_src, tokens) + iou_token_out = hs[:, 0, :] + mask_tokens_out = hs[:, 1 : (1 + self.num_mask_tokens), :] + + # Upscale mask embeddings and predict masks using the mask tokens + src = src.transpose(1, 2).view(b, c, h, w) + + upscaled_embedding_sam = self.output_upscaling(src) + upscaled_embedding_hq = self.embedding_maskfeature(upscaled_embedding_sam) + hq_features.repeat(b,1,1,1) + + hyper_in_list: List[torch.Tensor] = [] + for i in range(self.num_mask_tokens): + if i < self.num_mask_tokens - 1: + hyper_in_list.append(self.output_hypernetworks_mlps[i](mask_tokens_out[:, i, :])) + else: + hyper_in_list.append(self.hf_mlp(mask_tokens_out[:, i, :])) + + hyper_in = torch.stack(hyper_in_list, dim=1) + b, c, h, w = upscaled_embedding_sam.shape + + masks_sam = (hyper_in[:,:self.num_mask_tokens-1] @ upscaled_embedding_sam.view(b, c, h * w)).view(b, -1, h, w) + masks_sam_hq = (hyper_in[:,self.num_mask_tokens-1:] @ upscaled_embedding_hq.view(b, c, h * w)).view(b, -1, h, w) + # masks = torch.cat([masks_sam,masks_sam_hq],dim=1) + # Generate mask quality predictions + iou_pred = self.iou_prediction_head(iou_token_out) + + return masks_sam, iou_pred, masks_sam_hq + + +# Lightly adapted from +# https://github.com/facebookresearch/MaskFormer/blob/main/mask_former/modeling/transformer/transformer_predictor.py # noqa +class MLP(nn.Module): + def __init__( + self, + input_dim: int, + hidden_dim: int, + output_dim: int, + num_layers: int, + sigmoid_output: bool = False, + ) -> None: + super().__init__() + self.num_layers = num_layers + h = [hidden_dim] * (num_layers - 1) + self.layers = nn.ModuleList( + nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim]) + ) + self.sigmoid_output = sigmoid_output + + def forward(self, x): + for i, layer in enumerate(self.layers): + x = F.relu(layer(x)) if i < self.num_layers - 1 else layer(x) + if self.sigmoid_output: + x = F.sigmoid(x) + return x diff --git a/py/sam_hq/modeling/tiny_vit.py b/py/sam_hq/modeling/tiny_vit.py new file mode 100644 index 0000000..38b7bf9 --- /dev/null +++ b/py/sam_hq/modeling/tiny_vit.py @@ -0,0 +1,618 @@ +# -------------------------------------------------------- +# TinyViT Model Architecture +# Copyright (c) 2022 Microsoft +# Adapted from LeViT and Swin Transformer +# LeViT: (https://github.com/facebookresearch/levit) +# Swin: (https://github.com/microsoft/swin-transformer) +# Build the TinyViT Model +# -------------------------------------------------------- + +import itertools +import torch +import torch.nn as nn +import torch.nn.functional as F +import torch.utils.checkpoint as checkpoint +from timm.models.layers import DropPath as TimmDropPath,\ + to_2tuple, trunc_normal_ +from timm.models import register_model +from typing import Tuple + + +class Conv2d_BN(torch.nn.Sequential): + def __init__(self, a, b, ks=1, stride=1, pad=0, dilation=1, + groups=1, bn_weight_init=1): + super().__init__() + self.add_module('c', torch.nn.Conv2d( + a, b, ks, stride, pad, dilation, groups, bias=False)) + bn = torch.nn.BatchNorm2d(b) + torch.nn.init.constant_(bn.weight, bn_weight_init) + torch.nn.init.constant_(bn.bias, 0) + self.add_module('bn', bn) + + @torch.no_grad() + def fuse(self): + c, bn = self._modules.values() + w = bn.weight / (bn.running_var + bn.eps)**0.5 + w = c.weight * w[:, None, None, None] + b = bn.bias - bn.running_mean * bn.weight / \ + (bn.running_var + bn.eps)**0.5 + m = torch.nn.Conv2d(w.size(1) * self.c.groups, w.size( + 0), w.shape[2:], stride=self.c.stride, padding=self.c.padding, dilation=self.c.dilation, groups=self.c.groups) + m.weight.data.copy_(w) + m.bias.data.copy_(b) + return m + + +class DropPath(TimmDropPath): + def __init__(self, drop_prob=None): + super().__init__(drop_prob=drop_prob) + self.drop_prob = drop_prob + + def __repr__(self): + msg = super().__repr__() + msg += f'(drop_prob={self.drop_prob})' + return msg + + +class PatchEmbed(nn.Module): + def __init__(self, in_chans, embed_dim, resolution, activation): + super().__init__() + img_size: Tuple[int, int] = to_2tuple(resolution) + self.patches_resolution = (img_size[0] // 4, img_size[1] // 4) + self.num_patches = self.patches_resolution[0] * \ + self.patches_resolution[1] + self.in_chans = in_chans + self.embed_dim = embed_dim + n = embed_dim + self.seq = nn.Sequential( + Conv2d_BN(in_chans, n // 2, 3, 2, 1), + activation(), + Conv2d_BN(n // 2, n, 3, 2, 1), + ) + + def forward(self, x): + return self.seq(x) + + +class MBConv(nn.Module): + def __init__(self, in_chans, out_chans, expand_ratio, + activation, drop_path): + super().__init__() + self.in_chans = in_chans + self.hidden_chans = int(in_chans * expand_ratio) + self.out_chans = out_chans + + self.conv1 = Conv2d_BN(in_chans, self.hidden_chans, ks=1) + self.act1 = activation() + + self.conv2 = Conv2d_BN(self.hidden_chans, self.hidden_chans, + ks=3, stride=1, pad=1, groups=self.hidden_chans) + self.act2 = activation() + + self.conv3 = Conv2d_BN( + self.hidden_chans, out_chans, ks=1, bn_weight_init=0.0) + self.act3 = activation() + + self.drop_path = DropPath( + drop_path) if drop_path > 0. else nn.Identity() + + def forward(self, x): + shortcut = x + + x = self.conv1(x) + x = self.act1(x) + + x = self.conv2(x) + x = self.act2(x) + + x = self.conv3(x) + + x = self.drop_path(x) + + x += shortcut + x = self.act3(x) + + return x + + +class PatchMerging(nn.Module): + def __init__(self, input_resolution, dim, out_dim, activation): + super().__init__() + + self.input_resolution = input_resolution + self.dim = dim + self.out_dim = out_dim + self.act = activation() + self.conv1 = Conv2d_BN(dim, out_dim, 1, 1, 0) + stride_c=2 + if(out_dim==320 or out_dim==448 or out_dim==576): + stride_c=1 + self.conv2 = Conv2d_BN(out_dim, out_dim, 3, stride_c, 1, groups=out_dim) + self.conv3 = Conv2d_BN(out_dim, out_dim, 1, 1, 0) + + def forward(self, x): + if x.ndim == 3: + H, W = self.input_resolution + B = len(x) + # (B, C, H, W) + x = x.view(B, H, W, -1).permute(0, 3, 1, 2) + + x = self.conv1(x) + x = self.act(x) + + x = self.conv2(x) + x = self.act(x) + x = self.conv3(x) + x = x.flatten(2).transpose(1, 2) + return x + + +class ConvLayer(nn.Module): + def __init__(self, dim, input_resolution, depth, + activation, + drop_path=0., downsample=None, use_checkpoint=False, + out_dim=None, + conv_expand_ratio=4., + ): + + super().__init__() + self.dim = dim + self.input_resolution = input_resolution + self.depth = depth + self.use_checkpoint = use_checkpoint + + # build blocks + self.blocks = nn.ModuleList([ + MBConv(dim, dim, conv_expand_ratio, activation, + drop_path[i] if isinstance(drop_path, list) else drop_path, + ) + for i in range(depth)]) + + # patch merging layer + if downsample is not None: + self.downsample = downsample( + input_resolution, dim=dim, out_dim=out_dim, activation=activation) + else: + self.downsample = None + + def forward(self, x): + for blk in self.blocks: + if self.use_checkpoint: + x = checkpoint.checkpoint(blk, x) + else: + x = blk(x) + if self.downsample is not None: + x = self.downsample(x) + return x + + +class Mlp(nn.Module): + def __init__(self, in_features, hidden_features=None, + out_features=None, act_layer=nn.GELU, drop=0.): + super().__init__() + out_features = out_features or in_features + hidden_features = hidden_features or in_features + self.norm = nn.LayerNorm(in_features) + self.fc1 = nn.Linear(in_features, hidden_features) + self.fc2 = nn.Linear(hidden_features, out_features) + self.act = act_layer() + self.drop = nn.Dropout(drop) + + def forward(self, x): + x = self.norm(x) + + x = self.fc1(x) + x = self.act(x) + x = self.drop(x) + x = self.fc2(x) + x = self.drop(x) + return x + + +class Attention(torch.nn.Module): + def __init__(self, dim, key_dim, num_heads=8, + attn_ratio=4, + resolution=(14, 14), + ): + super().__init__() + # (h, w) + assert isinstance(resolution, tuple) and len(resolution) == 2 + self.num_heads = num_heads + self.scale = key_dim ** -0.5 + self.key_dim = key_dim + self.nh_kd = nh_kd = key_dim * num_heads + self.d = int(attn_ratio * key_dim) + self.dh = int(attn_ratio * key_dim) * num_heads + self.attn_ratio = attn_ratio + h = self.dh + nh_kd * 2 + + self.norm = nn.LayerNorm(dim) + self.qkv = nn.Linear(dim, h) + self.proj = nn.Linear(self.dh, dim) + + points = list(itertools.product( + range(resolution[0]), range(resolution[1]))) + N = len(points) + attention_offsets = {} + idxs = [] + for p1 in points: + for p2 in points: + offset = (abs(p1[0] - p2[0]), abs(p1[1] - p2[1])) + if offset not in attention_offsets: + attention_offsets[offset] = len(attention_offsets) + idxs.append(attention_offsets[offset]) + self.attention_biases = torch.nn.Parameter( + torch.zeros(num_heads, len(attention_offsets))) + self.register_buffer('attention_bias_idxs', + torch.LongTensor(idxs).view(N, N), + persistent=False) + + @torch.no_grad() + def train(self, mode=True): + super().train(mode) + if mode and hasattr(self, 'ab'): + del self.ab + else: + self.ab = self.attention_biases[:, self.attention_bias_idxs] + + def forward(self, x): # x (B,N,C) + B, N, _ = x.shape + + # Normalization + x = self.norm(x) + + qkv = self.qkv(x) + # (B, N, num_heads, d) + q, k, v = qkv.view(B, N, self.num_heads, - + 1).split([self.key_dim, self.key_dim, self.d], dim=3) + # (B, num_heads, N, d) + q = q.permute(0, 2, 1, 3) + k = k.permute(0, 2, 1, 3) + v = v.permute(0, 2, 1, 3) + + attn = ( + (q @ k.transpose(-2, -1)) * self.scale + + + (self.attention_biases[:, self.attention_bias_idxs] + if self.training else self.ab) + ) + attn = attn.softmax(dim=-1) + x = (attn @ v).transpose(1, 2).reshape(B, N, self.dh) + x = self.proj(x) + return x + + +class TinyViTBlock(nn.Module): + r""" TinyViT Block. + + Args: + dim (int): Number of input channels. + input_resolution (tuple[int, int]): Input resulotion. + num_heads (int): Number of attention heads. + window_size (int): Window size. + mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. + drop (float, optional): Dropout rate. Default: 0.0 + drop_path (float, optional): Stochastic depth rate. Default: 0.0 + local_conv_size (int): the kernel size of the convolution between + Attention and MLP. Default: 3 + activation: the activation function. Default: nn.GELU + """ + + def __init__(self, dim, input_resolution, num_heads, window_size=7, + mlp_ratio=4., drop=0., drop_path=0., + local_conv_size=3, + activation=nn.GELU, + ): + super().__init__() + self.dim = dim + self.input_resolution = input_resolution + self.num_heads = num_heads + assert window_size > 0, 'window_size must be greater than 0' + self.window_size = window_size + self.mlp_ratio = mlp_ratio + + self.drop_path = DropPath( + drop_path) if drop_path > 0. else nn.Identity() + + assert dim % num_heads == 0, 'dim must be divisible by num_heads' + head_dim = dim // num_heads + + window_resolution = (window_size, window_size) + self.attn = Attention(dim, head_dim, num_heads, + attn_ratio=1, resolution=window_resolution) + + mlp_hidden_dim = int(dim * mlp_ratio) + mlp_activation = activation + self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, + act_layer=mlp_activation, drop=drop) + + pad = local_conv_size // 2 + self.local_conv = Conv2d_BN( + dim, dim, ks=local_conv_size, stride=1, pad=pad, groups=dim) + + def forward(self, x): + H, W = self.input_resolution + B, L, C = x.shape + assert L == H * W, "input feature has wrong size" + res_x = x + if H == self.window_size and W == self.window_size: + x = self.attn(x) + else: + x = x.view(B, H, W, C) + pad_b = (self.window_size - H % + self.window_size) % self.window_size + pad_r = (self.window_size - W % + self.window_size) % self.window_size + padding = pad_b > 0 or pad_r > 0 + + if padding: + x = F.pad(x, (0, 0, 0, pad_r, 0, pad_b)) + + pH, pW = H + pad_b, W + pad_r + nH = pH // self.window_size + nW = pW // self.window_size + # window partition + x = x.view(B, nH, self.window_size, nW, self.window_size, C).transpose(2, 3).reshape( + B * nH * nW, self.window_size * self.window_size, C) + x = self.attn(x) + # window reverse + x = x.view(B, nH, nW, self.window_size, self.window_size, + C).transpose(2, 3).reshape(B, pH, pW, C) + + if padding: + x = x[:, :H, :W].contiguous() + + x = x.view(B, L, C) + + x = res_x + self.drop_path(x) + + x = x.transpose(1, 2).reshape(B, C, H, W) + x = self.local_conv(x) + x = x.view(B, C, L).transpose(1, 2) + + x = x + self.drop_path(self.mlp(x)) + return x + + def extra_repr(self) -> str: + return f"dim={self.dim}, input_resolution={self.input_resolution}, num_heads={self.num_heads}, " \ + f"window_size={self.window_size}, mlp_ratio={self.mlp_ratio}" + + +class BasicLayer(nn.Module): + """ A basic TinyViT layer for one stage. + + Args: + dim (int): Number of input channels. + input_resolution (tuple[int]): Input resolution. + depth (int): Number of blocks. + num_heads (int): Number of attention heads. + window_size (int): Local window size. + mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. + drop (float, optional): Dropout rate. Default: 0.0 + drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0 + downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None + use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False. + local_conv_size: the kernel size of the depthwise convolution between attention and MLP. Default: 3 + activation: the activation function. Default: nn.GELU + out_dim: the output dimension of the layer. Default: dim + """ + + def __init__(self, dim, input_resolution, depth, num_heads, window_size, + mlp_ratio=4., drop=0., + drop_path=0., downsample=None, use_checkpoint=False, + local_conv_size=3, + activation=nn.GELU, + out_dim=None, + ): + + super().__init__() + self.dim = dim + self.input_resolution = input_resolution + self.depth = depth + self.use_checkpoint = use_checkpoint + + # build blocks + self.blocks = nn.ModuleList([ + TinyViTBlock(dim=dim, input_resolution=input_resolution, + num_heads=num_heads, window_size=window_size, + mlp_ratio=mlp_ratio, + drop=drop, + drop_path=drop_path[i] if isinstance( + drop_path, list) else drop_path, + local_conv_size=local_conv_size, + activation=activation, + ) + for i in range(depth)]) + + # patch merging layer + if downsample is not None: + self.downsample = downsample( + input_resolution, dim=dim, out_dim=out_dim, activation=activation) + else: + self.downsample = None + + def forward(self, x): + for blk in self.blocks: + if self.use_checkpoint: + x = checkpoint.checkpoint(blk, x) + else: + x = blk(x) + if self.downsample is not None: + x = self.downsample(x) + return x + + def extra_repr(self) -> str: + return f"dim={self.dim}, input_resolution={self.input_resolution}, depth={self.depth}" + +class LayerNorm2d(nn.Module): + def __init__(self, num_channels: int, eps: float = 1e-6) -> None: + super().__init__() + self.weight = nn.Parameter(torch.ones(num_channels)) + self.bias = nn.Parameter(torch.zeros(num_channels)) + self.eps = eps + + def forward(self, x: torch.Tensor) -> torch.Tensor: + u = x.mean(1, keepdim=True) + s = (x - u).pow(2).mean(1, keepdim=True) + x = (x - u) / torch.sqrt(s + self.eps) + x = self.weight[:, None, None] * x + self.bias[:, None, None] + return x +class TinyViT(nn.Module): + def __init__(self, img_size=224, in_chans=3, num_classes=1000, + embed_dims=[96, 192, 384, 768], depths=[2, 2, 6, 2], + num_heads=[3, 6, 12, 24], + window_sizes=[7, 7, 14, 7], + mlp_ratio=4., + drop_rate=0., + drop_path_rate=0.1, + use_checkpoint=False, + mbconv_expand_ratio=4.0, + local_conv_size=3, + layer_lr_decay=1.0, + ): + super().__init__() + self.img_size=img_size + self.num_classes = num_classes + self.depths = depths + self.num_layers = len(depths) + self.mlp_ratio = mlp_ratio + + activation = nn.GELU + + self.patch_embed = PatchEmbed(in_chans=in_chans, + embed_dim=embed_dims[0], + resolution=img_size, + activation=activation) + + patches_resolution = self.patch_embed.patches_resolution + self.patches_resolution = patches_resolution + + # stochastic depth + dpr = [x.item() for x in torch.linspace(0, drop_path_rate, + sum(depths))] # stochastic depth decay rule + + # build layers + self.layers = nn.ModuleList() + for i_layer in range(self.num_layers): + kwargs = dict(dim=embed_dims[i_layer], + input_resolution=(patches_resolution[0] // (2 ** (i_layer-1 if i_layer == 3 else i_layer)), + patches_resolution[1] // (2 ** (i_layer-1 if i_layer == 3 else i_layer))), + # input_resolution=(patches_resolution[0] // (2 ** i_layer), + # patches_resolution[1] // (2 ** i_layer)), + depth=depths[i_layer], + drop_path=dpr[sum(depths[:i_layer]):sum(depths[:i_layer + 1])], + downsample=PatchMerging if ( + i_layer < self.num_layers - 1) else None, + use_checkpoint=use_checkpoint, + out_dim=embed_dims[min( + i_layer + 1, len(embed_dims) - 1)], + activation=activation, + ) + if i_layer == 0: + layer = ConvLayer( + conv_expand_ratio=mbconv_expand_ratio, + **kwargs, + ) + else: + layer = BasicLayer( + num_heads=num_heads[i_layer], + window_size=window_sizes[i_layer], + mlp_ratio=self.mlp_ratio, + drop=drop_rate, + local_conv_size=local_conv_size, + **kwargs) + self.layers.append(layer) + + # Classifier head + self.norm_head = nn.LayerNorm(embed_dims[-1]) + self.head = nn.Linear( + embed_dims[-1], num_classes) if num_classes > 0 else torch.nn.Identity() + + # init weights + self.apply(self._init_weights) + self.set_layer_lr_decay(layer_lr_decay) + self.neck = nn.Sequential( + nn.Conv2d( + embed_dims[-1], + 256, + kernel_size=1, + bias=False, + ), + LayerNorm2d(256), + nn.Conv2d( + 256, + 256, + kernel_size=3, + padding=1, + bias=False, + ), + LayerNorm2d(256), + ) + def set_layer_lr_decay(self, layer_lr_decay): + decay_rate = layer_lr_decay + + # layers -> blocks (depth) + depth = sum(self.depths) + lr_scales = [decay_rate ** (depth - i - 1) for i in range(depth)] + print("LR SCALES:", lr_scales) + + def _set_lr_scale(m, scale): + for p in m.parameters(): + p.lr_scale = scale + + self.patch_embed.apply(lambda x: _set_lr_scale(x, lr_scales[0])) + i = 0 + for layer in self.layers: + for block in layer.blocks: + block.apply(lambda x: _set_lr_scale(x, lr_scales[i])) + i += 1 + if layer.downsample is not None: + layer.downsample.apply( + lambda x: _set_lr_scale(x, lr_scales[i - 1])) + assert i == depth + for m in [self.norm_head, self.head]: + m.apply(lambda x: _set_lr_scale(x, lr_scales[-1])) + + for k, p in self.named_parameters(): + p.param_name = k + + def _check_lr_scale(m): + for p in m.parameters(): + assert hasattr(p, 'lr_scale'), p.param_name + + self.apply(_check_lr_scale) + + def _init_weights(self, m): + if isinstance(m, nn.Linear): + trunc_normal_(m.weight, std=.02) + if isinstance(m, nn.Linear) and m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.LayerNorm): + nn.init.constant_(m.bias, 0) + nn.init.constant_(m.weight, 1.0) + + @torch.jit.ignore + def no_weight_decay_keywords(self): + return {'attention_biases'} + + def forward_features(self, x): + # x: (N, C, H, W) + x = self.patch_embed(x) + + x = self.layers[0](x) + start_i = 1 + + for i in range(start_i, len(self.layers)): + layer = self.layers[i] + x = layer(x) + B,_,C=x.size() + x = x.view(B, 64, 64, C) + x=x.permute(0, 3, 1, 2) + x=self.neck(x) + return x + + def forward(self, x): + x = self.forward_features(x) + #x = self.norm_head(x) + #x = self.head(x) + return x diff --git a/py/sam_hq/predictor.py b/py/sam_hq/predictor.py new file mode 100644 index 0000000..40e3162 --- /dev/null +++ b/py/sam_hq/predictor.py @@ -0,0 +1,145 @@ +from typing import Optional, Tuple +import numpy as np +import torch +from segment_anything import SamPredictor +from segment_anything.modeling import Sam + + +class SamPredictorHQ(SamPredictor): + + def __init__( + self, + sam_model: Sam, + sam_is_hq: bool = False, + ) -> None: + """ + Uses SAM to calculate the image embedding for an image, and then + allow repeated, efficient mask prediction given prompts. + + Arguments: + sam_model (Sam): The model to use for mask prediction. + """ + super().__init__(sam_model=sam_model) + self.is_hq = sam_is_hq + + + @torch.no_grad() + def set_torch_image( + self, + transformed_image: torch.Tensor, + original_image_size: Tuple[int, ...], + ) -> None: + """ + Calculates the image embeddings for the provided image, allowing + masks to be predicted with the 'predict' method. Expects the input + image to be already transformed to the format expected by the model. + + Arguments: + transformed_image (torch.Tensor): The input image, with shape + 1x3xHxW, which has been transformed with ResizeLongestSide. + original_image_size (tuple(int, int)): The size of the image + before transformation, in (H, W) format. + """ + assert ( + len(transformed_image.shape) == 4 + and transformed_image.shape[1] == 3 + and max(*transformed_image.shape[2:]) == self.model.image_encoder.img_size + ), f"set_torch_image input must be BCHW with long side {self.model.image_encoder.img_size}." + self.reset_image() + + self.original_size = original_image_size + self.input_size = tuple(transformed_image.shape[-2:]) + input_image = self.model.preprocess(transformed_image) + if self.is_hq: + self.features, self.interm_features = self.model.image_encoder(input_image) + else: + self.features = self.model.image_encoder(input_image) + self.is_image_set = True + + + @torch.no_grad() + def predict_torch( + self, + point_coords: Optional[torch.Tensor], + point_labels: Optional[torch.Tensor], + boxes: Optional[torch.Tensor] = None, + mask_input: Optional[torch.Tensor] = None, + multimask_output: bool = True, + return_logits: bool = False, + ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """ + Predict masks for the given input prompts, using the currently set image. + Input prompts are batched torch tensors and are expected to already be + transformed to the input frame using ResizeLongestSide. + + Arguments: + point_coords (torch.Tensor or None): A BxNx2 array of point prompts to the + model. Each point is in (X,Y) in pixels. + point_labels (torch.Tensor or None): A BxN array of labels for the + point prompts. 1 indicates a foreground point and 0 indicates a + background point. + boxes (np.ndarray or None): A Bx4 array given a box prompt to the + model, in XYXY format. + mask_input (np.ndarray): A low resolution mask input to the model, typically + coming from a previous prediction iteration. Has form Bx1xHxW, where + for SAM, H=W=256. Masks returned by a previous iteration of the + predict method do not need further transformation. + multimask_output (bool): If true, the model will return three masks. + For ambiguous input prompts (such as a single click), this will often + produce better masks than a single prediction. If only a single + mask is needed, the model's predicted quality score can be used + to select the best mask. For non-ambiguous prompts, such as multiple + input prompts, multimask_output=False can give better results. + return_logits (bool): If true, returns un-thresholded masks logits + instead of a binary mask. + + Returns: + (torch.Tensor): The output masks in BxCxHxW format, where C is the + number of masks, and (H, W) is the original image size. + (torch.Tensor): An array of shape BxC containing the model's + predictions for the quality of each mask. + (torch.Tensor): An array of shape BxCxHxW, where C is the number + of masks and H=W=256. These low res logits can be passed to + a subsequent iteration as mask input. + """ + if not self.is_image_set: + raise RuntimeError("An image must be set with .set_image(...) before mask prediction.") + + if point_coords is not None: + points = (point_coords, point_labels) + else: + points = None + + # Embed prompts + sparse_embeddings, dense_embeddings = self.model.prompt_encoder( + points=points, + boxes=boxes, + masks=mask_input, + ) + + # Predict masks + if self.is_hq: + low_res_masks, iou_predictions = self.model.mask_decoder( + image_embeddings=self.features, + image_pe=self.model.prompt_encoder.get_dense_pe(), + sparse_prompt_embeddings=sparse_embeddings, + dense_prompt_embeddings=dense_embeddings, + multimask_output=multimask_output, + hq_token_only=False, + interm_embeddings=self.interm_features, + ) + else: + low_res_masks, iou_predictions = self.model.mask_decoder( + image_embeddings=self.features, + image_pe=self.model.prompt_encoder.get_dense_pe(), + sparse_prompt_embeddings=sparse_embeddings, + dense_prompt_embeddings=dense_embeddings, + multimask_output=multimask_output, + ) + # Upscale the masks to the original image resolution + masks = self.model.postprocess_masks(low_res_masks, self.input_size, self.original_size) + + if not return_logits: + masks = masks > self.model.mask_threshold + + return masks, iou_predictions, low_res_masks diff --git a/py/save_image_plus.py b/py/save_image_plus.py new file mode 100644 index 0000000..ceaf656 --- /dev/null +++ b/py/save_image_plus.py @@ -0,0 +1,183 @@ +# layerstyle advance + +import os.path +import shutil +from PIL.PngImagePlugin import PngInfo +import datetime +from .imagefunc import * + +NODE_NAME = 'SaveImagePlus' + +class SaveImagePlus: + def __init__(self): + self.output_dir = folder_paths.get_output_directory() + self.type = "output" + self.prefix_append = "" + self.compress_level = 4 + + @classmethod + def INPUT_TYPES(s): + return {"required": + {"images": ("IMAGE", ), + "custom_path": ("STRING", {"default": ""}), + "filename_prefix": ("STRING", {"default": "comfyui"}), + "timestamp": (["None", "second", "millisecond"],), + "format": (["png", "jpg"],), + "quality": ("INT", {"default": 80, "min": 10, "max": 100, "step": 1}), + "meta_data": ("BOOLEAN", {"default": False}), + "blind_watermark": ("STRING", {"default": ""}), + "save_workflow_as_json": ("BOOLEAN", {"default": False}), + "preview": ("BOOLEAN", {"default": True}), + }, + "hidden": {"prompt": "PROMPT", "extra_pnginfo": "EXTRA_PNGINFO"}, + } + + RETURN_TYPES = () + FUNCTION = "save_image_plus" + OUTPUT_NODE = True + CATEGORY = '😺dzNodes/LayerUtility/SystemIO' + + def save_image_plus(self, images, custom_path, filename_prefix, timestamp, format, quality, + meta_data, blind_watermark, preview, save_workflow_as_json, + prompt=None, extra_pnginfo=None): + + now = datetime.datetime.now() + custom_path = custom_path.replace("%date", now.strftime("%Y-%m-%d")) + custom_path = custom_path.replace("%time", now.strftime("%H-%M-%S")) + filename_prefix = filename_prefix.replace("%date", now.strftime("%Y-%m-%d")) + filename_prefix = filename_prefix.replace("%time", now.strftime("%H-%M-%S")) + filename_prefix += self.prefix_append + full_output_folder, filename, counter, subfolder, filename_prefix = folder_paths.get_save_image_path(filename_prefix, self.output_dir, images[0].shape[1], images[0].shape[0]) + results = list() + temp_sub_dir = generate_random_name('_savepreview_', '_temp', 16) + temp_dir = os.path.join(folder_paths.get_temp_directory(), temp_sub_dir) + for image in images: + i = 255. * image.cpu().numpy() + img = Image.fromarray(np.clip(i, 0, 255).astype(np.uint8)) + + if blind_watermark != "": + img_mode = img.mode + wm_size = watermark_image_size(img) + import qrcode + qr = qrcode.QRCode( + version=1, + error_correction=qrcode.constants.ERROR_CORRECT_H, + box_size=20, + border=1, + ) + qr.add_data(blind_watermark.encode('utf-8')) + qr.make(fit=True) + qr_image = qr.make_image(fill_color="black", back_color="white") + qr_image = qr_image.resize((wm_size, wm_size), Image.BICUBIC).convert("L") + + y, u, v, _ = image_channel_split(img, mode='YCbCr') + _u = add_invisibal_watermark(u, qr_image) + wm_img = image_channel_merge((y, _u, v), mode='YCbCr') + + if img.mode == "RGBA": + img = RGB2RGBA(wm_img, img.split()[-1]) + else: + img = wm_img.convert(img_mode) + + metadata = None + if meta_data: + metadata = PngInfo() + if prompt is not None: + metadata.add_text("prompt", json.dumps(prompt)) + if extra_pnginfo is not None: + for x in extra_pnginfo: + metadata.add_text(x, json.dumps(extra_pnginfo[x])) + + if timestamp == "millisecond": + file = f'{filename}_{now.strftime("%Y-%m-%d_%H-%M-%S-%f")[:-3]}' + elif timestamp == "second": + file = f'{filename}_{now.strftime("%Y-%m-%d_%H-%M-%S")}' + else: + file = f'{filename}_{counter:05}' + + + preview_filename = "" + if custom_path != "": + if not os.path.exists(custom_path): + try: + os.makedirs(custom_path) + except Exception as e: + log(f"Error: {NODE_NAME} skipped, because unable to create temporary folder.", + message_type='warning') + raise FileNotFoundError(f"cannot create custom_path {custom_path}, {e}") + + full_output_folder = os.path.normpath(custom_path) + # save preview image to temp_dir + if os.path.isdir(temp_dir): + shutil.rmtree(temp_dir) + try: + os.makedirs(temp_dir) + except Exception as e: + print(e) + log(f"Error: {NODE_NAME} skipped, because unable to create temporary folder.", + message_type='warning') + try: + preview_filename = os.path.join(generate_random_name('saveimage_preview_', '_temp', 16) + '.png') + img.save(os.path.join(temp_dir, preview_filename)) + except Exception as e: + print(e) + log(f"Error: {NODE_NAME} skipped, because unable to create temporary file.", message_type='warning') + + # check if file exists, change filename + while os.path.isfile(os.path.join(full_output_folder, f"{file}.{format}")): + counter += 1 + if timestamp == "millisecond": + file = f'{filename}_{now.strftime("%Y-%m-%d_%H-%M-%S-%f")[:-3]}_{counter:05}' + elif timestamp == "second": + file = f'{filename}_{now.strftime("%Y-%m-%d_%H-%M-%S")}_{counter:05}' + else: + file = f"{filename}_{counter:05}" + + image_file_name = os.path.join(full_output_folder, f"{file}.{format}") + json_file_name = os.path.join(full_output_folder, f"{file}.json") + + if format == "png": + img.save(image_file_name, pnginfo=metadata, compress_level= (100 - quality) // 10) + else: + if img.mode == "RGBA": + img = img.convert("RGB") + img.save(image_file_name, quality=quality) + log(f"{NODE_NAME} -> Saving image to {image_file_name}") + + if save_workflow_as_json: + try: + workflow = (extra_pnginfo or {}).get('workflow') + if workflow is None: + log('No workflow found, skipping saving of JSON') + with open(f'{json_file_name}', 'w') as workflow_file: + json.dump(workflow, workflow_file) + log(f'Saved workflow to {json_file_name}') + except Exception as e: + log( + f'Failed to save workflow as json due to: {e}, proceeding with the remainder of saving execution', message_type="warning") + + if preview: + if custom_path == "": + results.append({ + "filename": f"{file}.{format}", + "subfolder": subfolder, + "type": self.type + }) + else: + results.append({ + "filename": preview_filename, + "subfolder": temp_sub_dir, + "type": "temp" + }) + + counter += 1 + + return { "ui": { "images": results } } + +NODE_CLASS_MAPPINGS = { + "LayerUtility: SaveImagePlus": SaveImagePlus +} + +NODE_DISPLAY_NAME_MAPPINGS = { + "LayerUtility: SaveImagePlus": "LayerUtility: SaveImage Plus(Advance)" +} \ No newline at end of file diff --git a/py/sd3_negative_conditioning.py b/py/sd3_negative_conditioning.py new file mode 100644 index 0000000..8a994c9 --- /dev/null +++ b/py/sd3_negative_conditioning.py @@ -0,0 +1,49 @@ +# layerstyle advance + +import torch +import node_helpers + +NODE_NAME = 'SD3NegativeConditioning' + +class SD3NegativeConditioning: + + @classmethod + def INPUT_TYPES(self): + return {"required": {"conditioning": ("CONDITIONING", ), + "zero_out_start": ("FLOAT", {"default": 0.1, "min": 0.0, "max": 1.0, "step": 0.001}), + }} + + RETURN_TYPES = ("CONDITIONING",) + FUNCTION = 'sd3_negative_conditioning' + CATEGORY = '😺dzNodes/LayerUtility/SystemIO' + + def sd3_negative_conditioning(self, conditioning, zero_out_start): + def zero_out(conditioning): + c = [] + for t in conditioning: + d = t[1].copy() + if "pooled_output" in d: + d["pooled_output"] = torch.zeros_like(d["pooled_output"]) + n = [torch.zeros_like(t[0]), d] + c.append(n) + return c + + def set_range(conditioning, start, end): + c = node_helpers.conditioning_set_values(conditioning, {"start_percent": start, + "end_percent": end}) + return c + + zero_out_c = zero_out(conditioning) + c_1 = set_range(zero_out_c, zero_out_start, 1.0) + c_2 = set_range(conditioning, 0.0, zero_out_start) + return (c_1 + c_2,) + + + +NODE_CLASS_MAPPINGS = { + "LayerUtility: SD3NegativeConditioning": SD3NegativeConditioning +} + +NODE_DISPLAY_NAME_MAPPINGS = { + "LayerUtility: SD3NegativeConditioning": "LayerUtility: SD3 Negative Conditioning(Advance)" +} \ No newline at end of file diff --git a/py/segment_anything_func.py b/py/segment_anything_func.py new file mode 100644 index 0000000..2be0d35 --- /dev/null +++ b/py/segment_anything_func.py @@ -0,0 +1,233 @@ +# layerstyle advance + +import os +import sys +sys.path.append( + os.path.dirname(os.path.abspath(__file__)) +) + +import copy +import torch +import numpy as np +from PIL import Image +import logging +from torch.hub import download_url_to_file +from urllib.parse import urlparse +import folder_paths +import comfy.model_management +from sam_hq.predictor import SamPredictorHQ +from sam_hq.build_sam_hq import sam_model_registry + +import glob +import folder_paths + +logger = logging.getLogger('comfyui_segment_anything') + +sam_model_dir_name = "sams" +sam_model_list = { + "sam_vit_h (2.56GB)": { + "model_url": "https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth" + }, + "sam_vit_l (1.25GB)": { + "model_url": "https://dl.fbaipublicfiles.com/segment_anything/sam_vit_l_0b3195.pth" + }, + "sam_vit_b (375MB)": { + "model_url": "https://dl.fbaipublicfiles.com/segment_anything/sam_vit_b_01ec64.pth" + }, + "sam_hq_vit_h (2.57GB)": { + "model_url": "https://huggingface.co/lkeab/hq-sam/resolve/main/sam_hq_vit_h.pth" + }, + "sam_hq_vit_l (1.25GB)": { + "model_url": "https://huggingface.co/lkeab/hq-sam/resolve/main/sam_hq_vit_l.pth" + }, + "sam_hq_vit_b (379MB)": { + "model_url": "https://huggingface.co/lkeab/hq-sam/resolve/main/sam_hq_vit_b.pth" + }, + "mobile_sam(39MB)": { + "model_url": "https://github.com/ChaoningZhang/MobileSAM/blob/master/weights/mobile_sam.pt" + } +} + +groundingdino_model_dir_name = "grounding-dino" +groundingdino_model_list = { + "GroundingDINO_SwinT_OGC (694MB)": { + "config_url": "https://huggingface.co/ShilongLiu/GroundingDINO/resolve/main/GroundingDINO_SwinT_OGC.cfg.py", + "model_url": "https://huggingface.co/ShilongLiu/GroundingDINO/resolve/main/groundingdino_swint_ogc.pth", + }, + "GroundingDINO_SwinB (938MB)": { + "config_url": "https://huggingface.co/ShilongLiu/GroundingDINO/resolve/main/GroundingDINO_SwinB.cfg.py", + "model_url": "https://huggingface.co/ShilongLiu/GroundingDINO/resolve/main/groundingdino_swinb_cogcoor.pth" + }, +} + +def get_bert_base_uncased_model_path(): + comfy_bert_model_base = os.path.join(folder_paths.models_dir, 'bert-base-uncased') + if glob.glob(os.path.join(comfy_bert_model_base, '**/model.safetensors'), recursive=True): + print('grounding-dino is using models/bert-base-uncased') + return comfy_bert_model_base + return 'bert-base-uncased' + +def list_sam_model(): + return list(sam_model_list.keys()) + +def load_sam_model(model_name): + sam_checkpoint_path = get_local_filepath( + sam_model_list[model_name]["model_url"], sam_model_dir_name) + model_file_name = os.path.basename(sam_checkpoint_path) + model_type = model_file_name.split('.')[0] + if 'hq' not in model_type and 'mobile' not in model_type: + model_type = '_'.join(model_type.split('_')[:-1]) + sam = sam_model_registry[model_type](checkpoint=sam_checkpoint_path) + sam_device = comfy.model_management.get_torch_device() + sam.to(device=sam_device) + sam.eval() + sam.model_name = model_file_name + return sam + +def get_local_filepath(url, dirname, local_file_name=None): + if not local_file_name: + parsed_url = urlparse(url) + local_file_name = os.path.basename(parsed_url.path) + + destination = folder_paths.get_full_path(dirname, local_file_name) + if destination: + logger.warn(f'using extra model: {destination}') + return destination + + folder = os.path.join(folder_paths.models_dir, dirname) + if not os.path.exists(folder): + os.makedirs(folder) + + destination = os.path.join(folder, local_file_name) + if not os.path.exists(destination): + logger.warn(f'downloading {url} to {destination}') + download_url_to_file(url, destination) + return destination + +def load_groundingdino_model(model_name): + from local_groundingdino.util.utils import clean_state_dict as local_groundingdino_clean_state_dict + from local_groundingdino.util.slconfig import SLConfig as local_groundingdino_SLConfig + from local_groundingdino.models import build_model as local_groundingdino_build_model + dino_model_args = local_groundingdino_SLConfig.fromfile( + get_local_filepath( + groundingdino_model_list[model_name]["config_url"], + groundingdino_model_dir_name + ), + ) + + if dino_model_args.text_encoder_type == 'bert-base-uncased': + dino_model_args.text_encoder_type = get_bert_base_uncased_model_path() + + dino = local_groundingdino_build_model(dino_model_args) + checkpoint = torch.load( + get_local_filepath( + groundingdino_model_list[model_name]["model_url"], + groundingdino_model_dir_name, + ), + ) + dino.load_state_dict(local_groundingdino_clean_state_dict( + checkpoint['model']), strict=False) + device = comfy.model_management.get_torch_device() + dino.to(device=device) + dino.eval() + return dino + +def list_groundingdino_model(): + return list(groundingdino_model_list.keys()) + +def groundingdino_predict( + dino_model, + image, + prompt, + threshold +): + from local_groundingdino.datasets import transforms as T + def load_dino_image(image_pil): + transform = T.Compose( + [ + T.RandomResize([800], max_size=1333), + T.ToTensor(), + T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]), + ] + ) + image, _ = transform(image_pil, None) # 3, h, w + return image + + def get_grounding_output(model, image, caption, box_threshold): + caption = caption.lower() + caption = caption.strip() + if not caption.endswith("."): + caption = caption + "." + device = comfy.model_management.get_torch_device() + image = image.to(device) + with torch.no_grad(): + outputs = model(image[None], captions=[caption]) + logits = outputs["pred_logits"].sigmoid()[0] # (nq, 256) + boxes = outputs["pred_boxes"][0] # (nq, 4) + # filter output + logits_filt = logits.clone() + boxes_filt = boxes.clone() + filt_mask = logits_filt.max(dim=1)[0] > box_threshold + logits_filt = logits_filt[filt_mask] # num_filt, 256 + boxes_filt = boxes_filt[filt_mask] # num_filt, 4 + return boxes_filt.cpu() + + dino_image = load_dino_image(image.convert("RGB")) + boxes_filt = get_grounding_output( + dino_model, dino_image, prompt, threshold + ) + H, W = image.size[1], image.size[0] + for i in range(boxes_filt.size(0)): + boxes_filt[i] = boxes_filt[i] * torch.Tensor([W, H, W, H]) + boxes_filt[i][:2] -= boxes_filt[i][2:] / 2 + boxes_filt[i][2:] += boxes_filt[i][:2] + return boxes_filt + +def create_tensor_output(image_np, masks, boxes_filt): + output_masks, output_images = [], [] + boxes_filt = boxes_filt.numpy().astype(int) if boxes_filt is not None else None + for mask in masks: + image_np_copy = copy.deepcopy(image_np) + image_np_copy[~np.any(mask, axis=0)] = np.array([0, 0, 0, 0]) + output_image, output_mask = split_image_mask( + Image.fromarray(image_np_copy)) + output_masks.append(output_mask) + output_images.append(output_image) + return (output_images, output_masks) + +def split_image_mask(image): + image_rgb = image.convert("RGB") + image_rgb = np.array(image_rgb).astype(np.float32) / 255.0 + image_rgb = torch.from_numpy(image_rgb)[None,] + if 'A' in image.getbands(): + mask = np.array(image.getchannel('A')).astype(np.float32) / 255.0 + mask = torch.from_numpy(mask)[None,] + else: + mask = torch.zeros((64, 64), dtype=torch.float32, device="cpu") + return (image_rgb, mask) + +def sam_segment( + sam_model, + image, + boxes +): + if boxes.shape[0] == 0: + return None + sam_is_hq = False + # TODO: more elegant + if hasattr(sam_model, 'model_name') and 'hq' in sam_model.model_name: + sam_is_hq = True + predictor = SamPredictorHQ(sam_model, sam_is_hq) + image_np = np.array(image) + image_np_rgb = image_np[..., :3] + predictor.set_image(image_np_rgb) + transformed_boxes = predictor.transform.apply_boxes_torch( + boxes, image_np.shape[:2]) + sam_device = comfy.model_management.get_torch_device() + masks, _, _ = predictor.predict_torch( + point_coords=None, + point_labels=None, + boxes=transformed_boxes.to(sam_device), + multimask_output=False) + masks = masks.permute(1, 0, 2, 3).cpu().numpy() + return create_tensor_output(image_np, masks, boxes) diff --git a/py/segment_anything_ultra.py b/py/segment_anything_ultra.py new file mode 100644 index 0000000..3bf887b --- /dev/null +++ b/py/segment_anything_ultra.py @@ -0,0 +1,93 @@ +# layerstyle advance + +from .imagefunc import * +from .segment_anything_func import * + +NODE_NAME = 'SegmentAnythingUltra' + +class SegmentAnythingUltra: + def __init__(self): + self.SAM_MODEL = None + self.DINO_MODEL = None + self.previous_sam_model = "" + self.previous_dino_model = "" + + @classmethod + def INPUT_TYPES(cls): + + return { + "required": { + "image": ("IMAGE",), + "sam_model": (list_sam_model(), ), + "grounding_dino_model": (list_groundingdino_model(),), + "threshold": ("FLOAT", {"default": 0.3, "min": 0, "max": 1.0, "step": 0.01}), + "detail_range": ("INT", {"default": 16, "min": 1, "max": 256, "step": 1}), + "black_point": ("FLOAT", {"default": 0.15, "min": 0.01, "max": 0.98, "step": 0.01}), + "white_point": ("FLOAT", {"default": 0.99, "min": 0.02, "max": 0.99, "step": 0.01}), + "process_detail": ("BOOLEAN", {"default": True}), + "prompt": ("STRING", {"default": "subject"}), + "cache_model": ("BOOLEAN", {"default": False}), + }, + "optional": { + } + } + + RETURN_TYPES = ("IMAGE", "MASK", ) + RETURN_NAMES = ("image", "mask", ) + FUNCTION = "segment_anything_ultra" + CATEGORY = '😺dzNodes/LayerMask' + + def segment_anything_ultra(self, image, sam_model, grounding_dino_model, threshold, + detail_range, black_point, white_point, process_detail, + prompt, cache_model): + + if self.previous_sam_model != sam_model or self.SAM_MODEL is None: + self.SAM_MODEL = load_sam_model(sam_model) + self.previous_sam_model = sam_model + if self.previous_dino_model != grounding_dino_model or self.DINO_MODEL is None: + self.DINO_MODEL = load_groundingdino_model(grounding_dino_model) + self.previous_dino_model = grounding_dino_model + + + ret_images = [] + ret_masks = [] + + for i in image: + i = torch.unsqueeze(i, 0) + i = pil2tensor(tensor2pil(i).convert('RGB')) + item = tensor2pil(i).convert('RGBA') + boxes = groundingdino_predict(self.DINO_MODEL, item, prompt, threshold) + if boxes.shape[0] == 0: + break + (_, _mask) = sam_segment(self.SAM_MODEL, item, boxes) + _mask = _mask[0] + if process_detail: + _mask = tensor2pil(mask_edge_detail(i, _mask, detail_range, black_point, white_point)) + else: + _mask = mask2image(_mask) + _image = RGB2RGBA(tensor2pil(i).convert('RGB'), _mask.convert('L')) + + ret_images.append(pil2tensor(_image)) + ret_masks.append(image2mask(_mask)) + if len(ret_masks) == 0: + _, height, width, _ = image.size() + empty_mask = torch.zeros((1, height, width), dtype=torch.uint8, device="cpu") + return (empty_mask, empty_mask) + + if not cache_model: + self.SAM_MODEL = None + self.DINO_MODEL = None + self.previous_sam_model = "" + self.previous_dino_model = "" + clear_memory() + + log(f"{NODE_NAME} Processed {len(ret_masks)} image(s).", message_type='finish') + return (torch.cat(ret_images, dim=0), torch.cat(ret_masks, dim=0),) + +NODE_CLASS_MAPPINGS = { + "LayerMask: SegmentAnythingUltra": SegmentAnythingUltra, +} + +NODE_DISPLAY_NAME_MAPPINGS = { + "LayerMask: SegmentAnythingUltra": "LayerMask: SegmentAnythingUltra(Advance)", +} diff --git a/py/segment_anything_ultra_v2.py b/py/segment_anything_ultra_v2.py new file mode 100644 index 0000000..9494f72 --- /dev/null +++ b/py/segment_anything_ultra_v2.py @@ -0,0 +1,120 @@ +# layerstyle advance + +from .imagefunc import * +from .segment_anything_func import * + +NODE_NAME = 'SegmentAnythingUltra V2' + + + + +class SegmentAnythingUltraV2: + def __init__(self): + self.SAM_MODEL = None + self.DINO_MODEL = None + self.previous_sam_model = "" + self.previous_dino_model = "" + pass + + @classmethod + def INPUT_TYPES(cls): + + method_list = ['VITMatte', 'VITMatte(local)', 'PyMatting', 'GuidedFilter', ] + device_list = ['cuda','cpu'] + return { + "required": { + "image": ("IMAGE",), + "sam_model": (list_sam_model(), ), + "grounding_dino_model": (list_groundingdino_model(),), + "threshold": ("FLOAT", {"default": 0.3, "min": 0, "max": 1.0, "step": 0.01}), + "detail_method": (method_list,), + "detail_erode": ("INT", {"default": 6, "min": 1, "max": 255, "step": 1}), + "detail_dilate": ("INT", {"default": 6, "min": 1, "max": 255, "step": 1}), + "black_point": ("FLOAT", {"default": 0.15, "min": 0.01, "max": 0.98, "step": 0.01, "display": "slider"}), + "white_point": ("FLOAT", {"default": 0.99, "min": 0.02, "max": 0.99, "step": 0.01, "display": "slider"}), + "process_detail": ("BOOLEAN", {"default": True}), + "prompt": ("STRING", {"default": "subject"}), + "device": (device_list,), + "max_megapixels": ("FLOAT", {"default": 2.0, "min": 1, "max": 999, "step": 0.1}), + "cache_model": ("BOOLEAN", {"default": False}), + }, + "optional": { + } + } + + RETURN_TYPES = ("IMAGE", "MASK", ) + RETURN_NAMES = ("image", "mask", ) + FUNCTION = "segment_anything_ultra_v2" + CATEGORY = '😺dzNodes/LayerMask' + + def segment_anything_ultra_v2(self, image, sam_model, grounding_dino_model, threshold, + detail_method, detail_erode, detail_dilate, + black_point, white_point, process_detail, prompt, + device, max_megapixels, cache_model + ): + + if detail_method == 'VITMatte(local)': + local_files_only = True + else: + local_files_only = False + + if self.previous_sam_model != sam_model or self.SAM_MODEL is None: + self.SAM_MODEL = load_sam_model(sam_model) + self.previous_sam_model = sam_model + if self.previous_dino_model != grounding_dino_model or self.DINO_MODEL is None: + self.DINO_MODEL = load_groundingdino_model(grounding_dino_model) + self.previous_dino_model = grounding_dino_model + + # SAM_MODEL = load_sam_model(sam_model) + # DINO_MODEL = load_groundingdino_model(grounding_dino_model) + ret_images = [] + ret_masks = [] + + for i in image: + i = torch.unsqueeze(i, 0) + i = pil2tensor(tensor2pil(i).convert('RGB')) + _image = tensor2pil(i).convert('RGBA') + boxes = groundingdino_predict(self.DINO_MODEL, _image, prompt, threshold) + if boxes.shape[0] == 0: + break + (_, _mask) = sam_segment(self.SAM_MODEL, _image, boxes) + _mask = _mask[0] + detail_range = detail_erode + detail_dilate + if process_detail: + if detail_method == 'GuidedFilter': + _mask = guided_filter_alpha(i, _mask, detail_range // 6 + 1) + _mask = tensor2pil(histogram_remap(_mask, black_point, white_point)) + elif detail_method == 'PyMatting': + _mask = tensor2pil(mask_edge_detail(i, _mask, detail_range // 8 + 1, black_point, white_point)) + else: + _trimap = generate_VITMatte_trimap(_mask, detail_erode, detail_dilate) + _mask = generate_VITMatte(_image, _trimap, local_files_only=local_files_only, device=device, max_megapixels=max_megapixels) + _mask = tensor2pil(histogram_remap(pil2tensor(_mask), black_point, white_point)) + else: + _mask = mask2image(_mask) + _image = RGB2RGBA(tensor2pil(i).convert('RGB'), _mask.convert('L')) + + ret_images.append(pil2tensor(_image)) + ret_masks.append(image2mask(_mask)) + if len(ret_masks) == 0: + _, height, width, _ = image.size() + empty_mask = torch.zeros((1, height, width), dtype=torch.uint8, device="cpu") + return (empty_mask, empty_mask) + + if not cache_model: + self.SAM_MODEL = None + self.DINO_MODEL = None + self.previous_sam_model = "" + self.previous_dino_model = "" + clear_memory() + + log(f"{NODE_NAME} Processed {len(ret_masks)} image(s).", message_type='finish') + return (torch.cat(ret_images, dim=0), torch.cat(ret_masks, dim=0),) + +NODE_CLASS_MAPPINGS = { + "LayerMask: SegmentAnythingUltra V2": SegmentAnythingUltraV2, +} + +NODE_DISPLAY_NAME_MAPPINGS = { + "LayerMask: SegmentAnythingUltra V2": "LayerMask: SegmentAnythingUltra V2(Advance)", +} diff --git a/py/transparent_background_ultra.py b/py/transparent_background_ultra.py new file mode 100644 index 0000000..b850bd0 --- /dev/null +++ b/py/transparent_background_ultra.py @@ -0,0 +1,98 @@ +# layerstyle advance + +from .imagefunc import * + + + +mode_dict = {"ckpt_base.pth": "base", "ckpt_base_nightly.pth": "base-nightly", "ckpt_fast.pth": "fast"} +def scan_model(): + model_file_list = glob.glob(os.path.join(folder_paths.models_dir, "transparent-background") + '/*.pth') + model_dict = {} + for i in range(len(model_file_list)): + _, __filename = os.path.split(model_file_list[i]) + model_dict[__filename] = model_file_list[i] + return model_dict + +class TransparentBackgroundUltra: + def __init__(self): + self.NODE_NAME = 'TransparentBackgroundUltra' + + @classmethod + def INPUT_TYPES(cls): + method_list = ['VITMatte', 'VITMatte(local)', 'PyMatting', 'GuidedFilter', ] + device_list = ['cuda','cpu'] + + return { + "required": { + "image": ("IMAGE",), + "model": (list(scan_model().keys()),), + "detail_method": (method_list,), + "detail_erode": ("INT", {"default": 6, "min": 1, "max": 255, "step": 1}), + "detail_dilate": ("INT", {"default": 6, "min": 1, "max": 255, "step": 1}), + "black_point": ("FLOAT", {"default": 0.01, "min": 0.01, "max": 0.98, "step": 0.01, "display": "slider"}), + "white_point": ("FLOAT", {"default": 0.99, "min": 0.02, "max": 0.99, "step": 0.01, "display": "slider"}), + "process_detail": ("BOOLEAN", {"default": True}), + "device": (device_list,), + "max_megapixels": ("FLOAT", {"default": 2.0, "min": 1, "max": 999, "step": 0.1}), + }, + "optional": { + } + } + + RETURN_TYPES = ("IMAGE", "MASK", ) + RETURN_NAMES = ("image", "mask", ) + FUNCTION = "transparent_background_ultra" + CATEGORY = '😺dzNodes/LayerMask' + + def transparent_background_ultra(self, image, model, detail_method, detail_erode, detail_dilate, + black_point, white_point, process_detail, device, max_megapixels): + + from transparent_background import Remover + + ret_images = [] + ret_masks = [] + if detail_method == 'VITMatte(local)': + local_files_only = True + else: + local_files_only = False + model_dict = scan_model() + try : + mode = mode_dict[model] + except : + mode = "base" + remover = Remover(mode=mode, jit=False, device=device, ckpt=model_dict[model]) + for i in image: + i = torch.unsqueeze(i, 0) + orig_image = tensor2pil(i).convert('RGB') + ret_image = remover.process(orig_image, type='rgba') + _mask = ret_image.split()[3] + _mask = adjust_levels(_mask, 64, 192) + + if process_detail: + detail_range = detail_erode + detail_dilate + _mask = pil2tensor(_mask) + if detail_method == 'GuidedFilter': + _mask = guided_filter_alpha(i, _mask, detail_range // 6 + 1) + _mask = tensor2pil(histogram_remap(_mask, black_point, white_point)) + elif detail_method == 'PyMatting': + _mask = tensor2pil(mask_edge_detail(i, _mask, detail_range // 8 + 1, black_point, white_point)) + else: + _trimap = generate_VITMatte_trimap(_mask, detail_erode, detail_dilate) + _mask = generate_VITMatte(orig_image, _trimap, local_files_only=local_files_only, device=device, max_megapixels=max_megapixels) + _mask = tensor2pil(histogram_remap(pil2tensor(_mask), black_point, white_point)) + ret_image = RGB2RGBA(orig_image, _mask.convert('L')) + + ret_images.append(pil2tensor(ret_image)) + ret_masks.append(image2mask(_mask)) + + log(f"{self.NODE_NAME} Processed {len(ret_images)} image(s).", message_type='finish') + + return (torch.cat(ret_images, dim=0), torch.cat(ret_masks, dim=0),) + +NODE_CLASS_MAPPINGS = { + "LayerMask: TransparentBackgroundUltra": TransparentBackgroundUltra, +} + +NODE_DISPLAY_NAME_MAPPINGS = { + "LayerMask: TransparentBackgroundUltra": "LayerMask: Transparent Background Ultra(Advance)", +} diff --git a/py/user_prompt_generator.py b/py/user_prompt_generator.py new file mode 100644 index 0000000..fc0229b --- /dev/null +++ b/py/user_prompt_generator.py @@ -0,0 +1,123 @@ +# layerstyle advance + +from .imagefunc import log + +class LS_UserPromptGenerator_Txt2ImgPromptWithReference: + + def __init__(self): + self.NODE_NAME = 'UserPromptGenerator-Txt2ImgPromptWithReference' + + @classmethod + def INPUT_TYPES(self): + template_list = ['SD txt2img prompt',] + return { + "required": { + "template": (template_list,), + "reference_text": ("STRING", {"multiline": False,"forceInput":True}), + "describe": ("STRING", {"default": "1 girl","multiline": True}), + "limit_words": ("INT", {"default": 200, "min": 2, "max": 999, "step": 1}), + }, + "optional": { + } + } + + RETURN_TYPES = ("STRING", ) + RETURN_NAMES = ("user_prompt", ) + FUNCTION = 'user_prompt_generator_txt2img_prompt_with_reference' + CATEGORY = '😺dzNodes/LayerUtility/Prompt' + + def user_prompt_generator_txt2img_prompt_with_reference(self, template, reference_text, describe, limit_words): + + if template == 'SD txt2img prompt': + prompt = (f'The REFERENCE TEXT is "{reference_text}".\r\n' + f"You are creating a prompt for Stable Diffusion to generate an image.\r\n" + f"Using '{describe}' as the basic content and depicting it as main subject, refer to the visual style described in the REFERENCE TEXT, polish and embellish it to describe into text.\r\n" + f"The word limit for the answer is between {int(limit_words * 0.7)} - {int(limit_words * 1.1)} words. Not too little, nor too much.\r\n" + f"Only output the prompt itself, don't output any unnecessary content like word count info.") + + log(f'{self.NODE_NAME} Processed. result is \r\n"{prompt}".') + return (prompt,) + + +class LS_UserPromptGenerator_Txt2ImgPrompt: + + def __init__(self): + self.NODE_NAME = 'UserPromptGenerator-Txt2ImgPrompt' + + @classmethod + def INPUT_TYPES(self): + template_list = ['SD txt2img prompt',] + return { + "required": { + "template": (template_list,), + "describe": ("STRING", {"default": "1 girl","multiline": True}), + "limit_words": ("INT", {"default": 200, "min": 2, "max": 999, "step": 1}), + }, + "optional": { + } + } + + RETURN_TYPES = ("STRING", ) + RETURN_NAMES = ("user_prompt", ) + FUNCTION = 'user_prompt_generator_txt2img_prompt' + CATEGORY = '😺dzNodes/LayerUtility/Prompt' + + def user_prompt_generator_txt2img_prompt(self, template, describe, limit_words): + + if template == 'SD txt2img prompt': + prompt = (f"You are creating a prompt for Stable Diffusion to generate an image.\r\n" + f"Using '{describe}' as the basic content, polish and embellish it to describe into text.\r\n" + f"The word limit for the answer is between {int(limit_words * 0.7)} - {int(limit_words * 1.1)} words. Not too little, nor too much.\r\n" + f"Only output the prompt itself, don't output any unnecessary content like word count info.") + + log(f'{self.NODE_NAME} Processed. result is \r\n"{prompt}".') + return (prompt,) + + +class LS_UserPromptGenerator_ReplaceWord: + + def __init__(self): + self.NODE_NAME = 'UserPromptGenerator-ReplaceWord' + + @classmethod + def INPUT_TYPES(self): + template_list = ['prompt replace word', ] + return { + "required": { + "orig_prompt": ("STRING", {"forceInput":True}), + "template": (template_list,), + "exclude_word": ("STRING", {"default": ""}), + "replace_with_word": ("STRING", {"default": ""}), + }, + "optional": { + } + } + + RETURN_TYPES = ("STRING",) + RETURN_NAMES = ("user_prompt",) + FUNCTION = 'user_prompt_generator_replace_word' + CATEGORY = '😺dzNodes/LayerUtility/Prompt' + + def user_prompt_generator_replace_word(self, orig_prompt, template, exclude_word, replace_with_word): + if template == 'prompt replace word': + prompt = (f'You are creating a prompt for Stable Diffusion to generate an image. ' + f'First step: Replace "{exclude_word}" and its synonyms with "{replace_with_word}" in the following text:"{orig_prompt}".\r\n' + f'Second step: Correct the grammar errors for based on first step.\r\n' + f"Only output the second step result, don't output any unnecessary content like first step result." + ) + + log(f'{self.NODE_NAME} Processed. result is \r\n"{prompt}".') + return (prompt,) + + +NODE_CLASS_MAPPINGS = { + "LayerUtility: UserPromptGeneratorTxt2ImgPrompt": LS_UserPromptGenerator_Txt2ImgPrompt, + "LayerUtility: UserPromptGeneratorTxt2ImgPromptWithReference": LS_UserPromptGenerator_Txt2ImgPromptWithReference, + "LayerUtility: UserPromptGeneratorReplaceWord": LS_UserPromptGenerator_ReplaceWord +} + +NODE_DISPLAY_NAME_MAPPINGS = { + "LayerUtility: UserPromptGeneratorTxt2ImgPrompt": "LayerUtility: UserPrompt Generator Txt2Img(Advance)", + "LayerUtility: UserPromptGeneratorTxt2ImgPromptWithReference": "LayerUtility: UserPrompt Generator Txt2Img with Reference(Advance)", + "LayerUtility: UserPromptGeneratorReplaceWord": "LayerUtility: UserPrompt Generator Replace Word(Advance)" +} \ No newline at end of file diff --git a/py/watermark.py b/py/watermark.py new file mode 100644 index 0000000..7be3bf2 --- /dev/null +++ b/py/watermark.py @@ -0,0 +1,112 @@ +# layerstyle advance + +from .imagefunc import * + + +class EncodeBlindWaterMark: + + def __init__(self): + pass + + @classmethod + def INPUT_TYPES(self): + + return { + "required": { + "image": ("IMAGE", ), # + "watermark_image": ("IMAGE",), # + }, + "optional": { + } + } + + RETURN_TYPES = ("IMAGE",) + RETURN_NAMES = ("image",) + FUNCTION = 'watermark_encode' + CATEGORY = '😺dzNodes/LayerUtility/SystemIO' + + def watermark_encode(self, image, watermark_image): + + NODE_NAME = 'Add BlindWaterMark' + + l_images = [] + w_images = [] + ret_images = [] + + for l in image: + l_images.append(torch.unsqueeze(l, 0)) + for w in watermark_image: + w_images.append(torch.unsqueeze(w, 0)) + + for i in range(len(l_images)): + _image = tensor2pil(l_images[i]) + wm_size = watermark_image_size(_image) + _wm_image = w_images[i] if i < len(w_images) else w_images[-1] + _wm_image = tensor2pil(_wm_image) + _wm_image = _wm_image.resize((wm_size, wm_size), Image.LANCZOS) + _wm_image = _wm_image.convert("L") + + y, u, v, _ = image_channel_split(_image, mode='YCbCr') + _u = add_invisibal_watermark(u, _wm_image) + ret_image = image_channel_merge((y, _u, v), mode='YCbCr') + + if _image.mode == "RGBA": + ret_image = RGB2RGBA(ret_image, _image.split()[-1]) + ret_images.append(pil2tensor(ret_image)) + + log(f"{NODE_NAME} Processed {len(ret_images)} image(s).", message_type='finish') + return (torch.cat(ret_images, dim=0),) + + + +class DecodeBlindWaterMark: + + def __init__(self): + pass + + @classmethod + def INPUT_TYPES(self): + + return { + "required": { + "image": ("IMAGE",), # + }, + "optional": { + } + } + + RETURN_TYPES = ("IMAGE", ) + RETURN_NAMES = ("watermark_image",) + FUNCTION = 'watermark_decode' + CATEGORY = '😺dzNodes/LayerUtility/SystemIO' + + def watermark_decode(self, image): + + NODE_NAME = 'Decode BlindWaterMark' + + ret_images = [] + + for i in image: + _image = torch.unsqueeze(i,0) + _image = tensor2pil(_image) + wm_size = watermark_image_size(_image) + y, u, v, _ = image_channel_split(_image, mode='YCbCr') + ret_image = decode_watermark(u, wm_size) + ret_image = ret_image.resize((512, 512), Image.LANCZOS) + ret_image = normalize_gray(ret_image) + ret_images.append(pil2tensor(ret_image.convert('RGB'))) + + log(f"{NODE_NAME} Processed {len(ret_images)} image(s).", message_type='finish') + return (torch.cat(ret_images, dim=0), ) + + + +NODE_CLASS_MAPPINGS = { + "LayerUtility: AddBlindWaterMark": EncodeBlindWaterMark, + "LayerUtility: ShowBlindWaterMark": DecodeBlindWaterMark +} + +NODE_DISPLAY_NAME_MAPPINGS = { + "LayerUtility: AddBlindWaterMark": "LayerUtility: Add BlindWaterMark(Advance)", + "LayerUtility: ShowBlindWaterMark": "LayerUtility: Show BlindWaterMark(Advance)" +} \ No newline at end of file diff --git a/py/yolov8_detect.py b/py/yolov8_detect.py new file mode 100644 index 0000000..b49991e --- /dev/null +++ b/py/yolov8_detect.py @@ -0,0 +1,98 @@ +# layerstyle advance + +import copy +import os.path +from .imagefunc import * + +model_path = os.path.join(folder_paths.models_dir, 'yolo') + +class YoloV8Detect: + + def __init__(self): + self.NODE_NAME = 'YoloV8Detect' + + + @classmethod + def INPUT_TYPES(self): + model_ext = [".pt"] + FILES_DICT = get_files(model_path, model_ext) + FILE_LIST = list(FILES_DICT.keys()) + mask_merge = ["all", "1", "2", "3", "4", "5", "6", "7", "8", "9"] + return { + "required": { + "image": ("IMAGE", ), + "yolo_model": (FILE_LIST,), + "mask_merge": (mask_merge,), + }, + "optional": { + } + } + + RETURN_TYPES = ("MASK", "IMAGE", "MASK" ) + RETURN_NAMES = ("mask", "yolo_plot_image", "yolo_masks") + FUNCTION = 'yolo_detect' + CATEGORY = '😺dzNodes/LayerMask' + + def yolo_detect(self, image, + yolo_model, mask_merge + ): + + ret_masks = [] + ret_yolo_plot_images = [] + ret_yolo_masks = [] + + from ultralytics import YOLO + yolo_model = YOLO(os.path.join(model_path, yolo_model)) + + for i in image: + i = torch.unsqueeze(i, 0) + _image = tensor2pil(i) + results = yolo_model(_image, retina_masks=True) + for result in results: + yolo_plot_image = cv2.cvtColor(result.plot(), cv2.COLOR_BGR2RGB) + ret_yolo_plot_images.append(pil2tensor(Image.fromarray(yolo_plot_image))) + # have mask + if result.masks is not None and len(result.masks) > 0: + masks = [] + masks_data = result.masks.data + for index, mask in enumerate(masks_data): + _mask = mask.cpu().numpy() * 255 + _mask = np2pil(_mask).convert("L") + ret_yolo_masks.append(image2mask(_mask)) + # no mask, if have box, draw box + elif result.boxes is not None and len(result.boxes.xyxy) > 0: + white_image = Image.new('L', _image.size, "white") + for box in result.boxes: + x1, y1, x2, y2 = box.xyxy[0].cpu().numpy() + x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2) + _mask = Image.new('L', _image.size, "black") + _mask.paste(white_image.crop((x1, y1, x2, y2)), (x1, y1)) + ret_yolo_masks.append(image2mask(_mask)) + # no mask and box, add a black mask + else: + ret_yolo_masks.append(torch.zeros((1, _image.size[1], _image.size[0]), dtype=torch.float32)) + # ret_yolo_masks.append(image2mask(Image.new('L', _image.size, "black"))) + log(f"{self.NODE_NAME} mask or box not detected.") + + # merge mask + _mask = ret_yolo_masks[0] + if mask_merge == "all": + for i in range(len(ret_yolo_masks) - 1): + _mask = add_mask(_mask, ret_yolo_masks[i + 1]) + else: + for i in range(min(len(ret_yolo_masks), int(mask_merge)) - 1): + _mask = add_mask(_mask, ret_yolo_masks[i + 1]) + ret_masks.append(_mask) + + log(f"{self.NODE_NAME} Processed {len(ret_masks)} image(s).", message_type='finish') + return (torch.cat(ret_masks, dim=0), + torch.cat(ret_yolo_plot_images, dim=0), + torch.cat(ret_yolo_masks, dim=0),) + +NODE_CLASS_MAPPINGS = { + "LayerMask: YoloV8Detect": YoloV8Detect +} + +NODE_DISPLAY_NAME_MAPPINGS = { + "LayerMask: YoloV8Detect": "LayerMask: YoloV8 Detect(Advance)" +} \ No newline at end of file diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..89d9675 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,15 @@ +[project] +name = "comfyui_layerstyle_advance" +description = "The nodes detached from ComfyUI Layer Style are mainly those with complex requirements for dependency packages." +version = "2.0.0" +license = "MIT" +dependencies = ["numpy", "matplotlib", "scikit_image", "scikit_learn", "opencv-contrib-python", "pymatting", "timm", "blend_modes", "transformers", "diffusers", "loguru", "colour-science", "huggingface_hub", "segment_anything", "addict", "omegaconf", "yapf", "wget", "iopath", "mediapipe", "typer_config", "fastapi", "rich", "google-generativeai", "ultralytics", "transparent-background", "accelerate", "onnxruntime", "bitsandbytes", "peft", "protobuf", "hydra-core", "blind-watermark", "qrcode", "pyzbar", "psd-tools"] + +[project.urls] +Repository = "https://github.com/chflame163/ComfyUI_LayerStyle_Advance" +# Used by Comfy Registry https://comfyregistry.org + +[tool.comfy] +PublisherId = "chflame163" +DisplayName = "ComfyUI_LayerStyle_Advance" +Icon = "" diff --git a/repair_dependency.bat b/repair_dependency.bat new file mode 100644 index 0000000..b57581f --- /dev/null +++ b/repair_dependency.bat @@ -0,0 +1,16 @@ +@echo off + +set "requirements_txt=%~dp0\repair_dependency_list.txt" +set "python_exec=..\..\..\python_embeded\python.exe" + +echo Fixing Dependency Package... + +echo Installing with ComfyUI Portable +%python_exec% -s -m pip uninstall -y onnxruntime +%python_exec% -s -m pip uninstall -y opencv-python opencv-contrib-python opencv-python-headless opencv-contrib-python-headless + +for /f "delims=" %%i in (%requirements_txt%) do ( + %python_exec% -s -m pip install -i https://pypi.tuna.tsinghua.edu.cn/simple "%%i" + ) + +pause \ No newline at end of file diff --git a/repair_dependency_aki.bat b/repair_dependency_aki.bat new file mode 100644 index 0000000..3e6b352 --- /dev/null +++ b/repair_dependency_aki.bat @@ -0,0 +1,16 @@ +@echo off + +set "requirements_txt=%~dp0\repair_dependency_list.txt" +set "python_exec=..\..\python\python.exe" + +echo Fixing Dependency Package... + +echo Installing with ComfyUI Portable +%python_exec% -s -m pip uninstall -y onnxruntime +%python_exec% -s -m pip uninstall -y opencv-python opencv-contrib-python opencv-python-headless opencv-contrib-python-headless + +for /f "delims=" %%i in (%requirements_txt%) do ( + %python_exec% -s -m pip install -i https://pypi.tuna.tsinghua.edu.cn/simple "%%i" + ) + +pause \ No newline at end of file diff --git a/repair_dependency_list.txt b/repair_dependency_list.txt new file mode 100644 index 0000000..6a5510a --- /dev/null +++ b/repair_dependency_list.txt @@ -0,0 +1,8 @@ +image-reward +torchscale +numpy<2 +onnxruntime +huggingface_hub>=0.23.3 +transformers>=4.45.0 +protobuf>=4.25.3 +opencv-contrib-python>=4.9.0.80 \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..8bf977b --- /dev/null +++ b/requirements.txt @@ -0,0 +1,40 @@ +numpy<2.0 +matplotlib +scikit_image +scikit_learn +opencv-contrib-python +pymatting +timm +blend_modes +transformers>=4.45.0 +diffusers +loguru +colour-science +huggingface_hub>=0.23.4 +segment_anything +addict +omegaconf +yapf +wget +iopath +mediapipe +typer_config +fastapi +rich +google-generativeai +ultralytics>=8.2.0 +transparent-background +accelerate>=0.26.0 +onnxruntime +bitsandbytes>=0.41.1 +peft>=0.12.0 +protobuf>=3.20.3 +hydra-core +blind-watermark +qrcode +pyzbar +psd-tools + +#torchscale +# inference-cli>=0.13.0 +# inference-gpu[yolo-world]>=0.13.0 \ No newline at end of file diff --git a/resource_dir.ini.example b/resource_dir.ini.example new file mode 100644 index 0000000..ca39fad --- /dev/null +++ b/resource_dir.ini.example @@ -0,0 +1,2 @@ +FONT_dir=C:\font,D:\other_font +LUT_dir=C:\lut,D:\other_lut \ No newline at end of file diff --git a/whl/docopt-0.6.2-py2.py3-none-any.whl b/whl/docopt-0.6.2-py2.py3-none-any.whl new file mode 100644 index 0000000..1409c76 Binary files /dev/null and b/whl/docopt-0.6.2-py2.py3-none-any.whl differ diff --git a/whl/hydra_core-1.3.2-py3-none-any.whl b/whl/hydra_core-1.3.2-py3-none-any.whl new file mode 100644 index 0000000..224d386 Binary files /dev/null and b/whl/hydra_core-1.3.2-py3-none-any.whl differ